]> Git Repo - linux.git/blob - drivers/gpu/drm/i915/i915_gem_request.c
Merge remote-tracking branches 'asoc/topic/rockchip', 'asoc/topic/rt5514', 'asoc...
[linux.git] / drivers / gpu / drm / i915 / i915_gem_request.c
1 /*
2  * Copyright © 2008-2015 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  *
23  */
24
25 #include <linux/prefetch.h>
26 #include <linux/dma-fence-array.h>
27 #include <linux/sched.h>
28 #include <linux/sched/clock.h>
29 #include <linux/sched/signal.h>
30
31 #include "i915_drv.h"
32
33 static const char *i915_fence_get_driver_name(struct dma_fence *fence)
34 {
35         return "i915";
36 }
37
38 static const char *i915_fence_get_timeline_name(struct dma_fence *fence)
39 {
40         /* The timeline struct (as part of the ppgtt underneath a context)
41          * may be freed when the request is no longer in use by the GPU.
42          * We could extend the life of a context to beyond that of all
43          * fences, possibly keeping the hw resource around indefinitely,
44          * or we just give them a false name. Since
45          * dma_fence_ops.get_timeline_name is a debug feature, the occasional
46          * lie seems justifiable.
47          */
48         if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
49                 return "signaled";
50
51         return to_request(fence)->timeline->common->name;
52 }
53
54 static bool i915_fence_signaled(struct dma_fence *fence)
55 {
56         return i915_gem_request_completed(to_request(fence));
57 }
58
59 static bool i915_fence_enable_signaling(struct dma_fence *fence)
60 {
61         if (i915_fence_signaled(fence))
62                 return false;
63
64         intel_engine_enable_signaling(to_request(fence));
65         return true;
66 }
67
68 static signed long i915_fence_wait(struct dma_fence *fence,
69                                    bool interruptible,
70                                    signed long timeout)
71 {
72         return i915_wait_request(to_request(fence), interruptible, timeout);
73 }
74
75 static void i915_fence_release(struct dma_fence *fence)
76 {
77         struct drm_i915_gem_request *req = to_request(fence);
78
79         /* The request is put onto a RCU freelist (i.e. the address
80          * is immediately reused), mark the fences as being freed now.
81          * Otherwise the debugobjects for the fences are only marked as
82          * freed when the slab cache itself is freed, and so we would get
83          * caught trying to reuse dead objects.
84          */
85         i915_sw_fence_fini(&req->submit);
86         i915_sw_fence_fini(&req->execute);
87
88         kmem_cache_free(req->i915->requests, req);
89 }
90
91 const struct dma_fence_ops i915_fence_ops = {
92         .get_driver_name = i915_fence_get_driver_name,
93         .get_timeline_name = i915_fence_get_timeline_name,
94         .enable_signaling = i915_fence_enable_signaling,
95         .signaled = i915_fence_signaled,
96         .wait = i915_fence_wait,
97         .release = i915_fence_release,
98 };
99
100 int i915_gem_request_add_to_client(struct drm_i915_gem_request *req,
101                                    struct drm_file *file)
102 {
103         struct drm_i915_private *dev_private;
104         struct drm_i915_file_private *file_priv;
105
106         WARN_ON(!req || !file || req->file_priv);
107
108         if (!req || !file)
109                 return -EINVAL;
110
111         if (req->file_priv)
112                 return -EINVAL;
113
114         dev_private = req->i915;
115         file_priv = file->driver_priv;
116
117         spin_lock(&file_priv->mm.lock);
118         req->file_priv = file_priv;
119         list_add_tail(&req->client_list, &file_priv->mm.request_list);
120         spin_unlock(&file_priv->mm.lock);
121
122         return 0;
123 }
124
125 static inline void
126 i915_gem_request_remove_from_client(struct drm_i915_gem_request *request)
127 {
128         struct drm_i915_file_private *file_priv = request->file_priv;
129
130         if (!file_priv)
131                 return;
132
133         spin_lock(&file_priv->mm.lock);
134         list_del(&request->client_list);
135         request->file_priv = NULL;
136         spin_unlock(&file_priv->mm.lock);
137 }
138
139 static struct i915_dependency *
140 i915_dependency_alloc(struct drm_i915_private *i915)
141 {
142         return kmem_cache_alloc(i915->dependencies, GFP_KERNEL);
143 }
144
145 static void
146 i915_dependency_free(struct drm_i915_private *i915,
147                      struct i915_dependency *dep)
148 {
149         kmem_cache_free(i915->dependencies, dep);
150 }
151
152 static void
153 __i915_priotree_add_dependency(struct i915_priotree *pt,
154                                struct i915_priotree *signal,
155                                struct i915_dependency *dep,
156                                unsigned long flags)
157 {
158         INIT_LIST_HEAD(&dep->dfs_link);
159         list_add(&dep->wait_link, &signal->waiters_list);
160         list_add(&dep->signal_link, &pt->signalers_list);
161         dep->signaler = signal;
162         dep->flags = flags;
163 }
164
165 static int
166 i915_priotree_add_dependency(struct drm_i915_private *i915,
167                              struct i915_priotree *pt,
168                              struct i915_priotree *signal)
169 {
170         struct i915_dependency *dep;
171
172         dep = i915_dependency_alloc(i915);
173         if (!dep)
174                 return -ENOMEM;
175
176         __i915_priotree_add_dependency(pt, signal, dep, I915_DEPENDENCY_ALLOC);
177         return 0;
178 }
179
180 static void
181 i915_priotree_fini(struct drm_i915_private *i915, struct i915_priotree *pt)
182 {
183         struct i915_dependency *dep, *next;
184
185         GEM_BUG_ON(!RB_EMPTY_NODE(&pt->node));
186
187         /* Everyone we depended upon (the fences we wait to be signaled)
188          * should retire before us and remove themselves from our list.
189          * However, retirement is run independently on each timeline and
190          * so we may be called out-of-order.
191          */
192         list_for_each_entry_safe(dep, next, &pt->signalers_list, signal_link) {
193                 list_del(&dep->wait_link);
194                 if (dep->flags & I915_DEPENDENCY_ALLOC)
195                         i915_dependency_free(i915, dep);
196         }
197
198         /* Remove ourselves from everyone who depends upon us */
199         list_for_each_entry_safe(dep, next, &pt->waiters_list, wait_link) {
200                 list_del(&dep->signal_link);
201                 if (dep->flags & I915_DEPENDENCY_ALLOC)
202                         i915_dependency_free(i915, dep);
203         }
204 }
205
206 static void
207 i915_priotree_init(struct i915_priotree *pt)
208 {
209         INIT_LIST_HEAD(&pt->signalers_list);
210         INIT_LIST_HEAD(&pt->waiters_list);
211         RB_CLEAR_NODE(&pt->node);
212         pt->priority = INT_MIN;
213 }
214
215 void i915_gem_retire_noop(struct i915_gem_active *active,
216                           struct drm_i915_gem_request *request)
217 {
218         /* Space left intentionally blank */
219 }
220
221 static void i915_gem_request_retire(struct drm_i915_gem_request *request)
222 {
223         struct intel_engine_cs *engine = request->engine;
224         struct i915_gem_active *active, *next;
225
226         lockdep_assert_held(&request->i915->drm.struct_mutex);
227         GEM_BUG_ON(!i915_sw_fence_signaled(&request->submit));
228         GEM_BUG_ON(!i915_sw_fence_signaled(&request->execute));
229         GEM_BUG_ON(!i915_gem_request_completed(request));
230         GEM_BUG_ON(!request->i915->gt.active_requests);
231
232         trace_i915_gem_request_retire(request);
233
234         spin_lock_irq(&engine->timeline->lock);
235         list_del_init(&request->link);
236         spin_unlock_irq(&engine->timeline->lock);
237
238         /* We know the GPU must have read the request to have
239          * sent us the seqno + interrupt, so use the position
240          * of tail of the request to update the last known position
241          * of the GPU head.
242          *
243          * Note this requires that we are always called in request
244          * completion order.
245          */
246         list_del(&request->ring_link);
247         request->ring->last_retired_head = request->postfix;
248         if (!--request->i915->gt.active_requests) {
249                 GEM_BUG_ON(!request->i915->gt.awake);
250                 mod_delayed_work(request->i915->wq,
251                                  &request->i915->gt.idle_work,
252                                  msecs_to_jiffies(100));
253         }
254
255         /* Walk through the active list, calling retire on each. This allows
256          * objects to track their GPU activity and mark themselves as idle
257          * when their *last* active request is completed (updating state
258          * tracking lists for eviction, active references for GEM, etc).
259          *
260          * As the ->retire() may free the node, we decouple it first and
261          * pass along the auxiliary information (to avoid dereferencing
262          * the node after the callback).
263          */
264         list_for_each_entry_safe(active, next, &request->active_list, link) {
265                 /* In microbenchmarks or focusing upon time inside the kernel,
266                  * we may spend an inordinate amount of time simply handling
267                  * the retirement of requests and processing their callbacks.
268                  * Of which, this loop itself is particularly hot due to the
269                  * cache misses when jumping around the list of i915_gem_active.
270                  * So we try to keep this loop as streamlined as possible and
271                  * also prefetch the next i915_gem_active to try and hide
272                  * the likely cache miss.
273                  */
274                 prefetchw(next);
275
276                 INIT_LIST_HEAD(&active->link);
277                 RCU_INIT_POINTER(active->request, NULL);
278
279                 active->retire(active, request);
280         }
281
282         i915_gem_request_remove_from_client(request);
283
284         /* Retirement decays the ban score as it is a sign of ctx progress */
285         if (request->ctx->ban_score > 0)
286                 request->ctx->ban_score--;
287
288         /* The backing object for the context is done after switching to the
289          * *next* context. Therefore we cannot retire the previous context until
290          * the next context has already started running. However, since we
291          * cannot take the required locks at i915_gem_request_submit() we
292          * defer the unpinning of the active context to now, retirement of
293          * the subsequent request.
294          */
295         if (engine->last_retired_context)
296                 engine->context_unpin(engine, engine->last_retired_context);
297         engine->last_retired_context = request->ctx;
298
299         dma_fence_signal(&request->fence);
300
301         i915_priotree_fini(request->i915, &request->priotree);
302         i915_gem_request_put(request);
303 }
304
305 void i915_gem_request_retire_upto(struct drm_i915_gem_request *req)
306 {
307         struct intel_engine_cs *engine = req->engine;
308         struct drm_i915_gem_request *tmp;
309
310         lockdep_assert_held(&req->i915->drm.struct_mutex);
311         GEM_BUG_ON(!i915_gem_request_completed(req));
312
313         if (list_empty(&req->link))
314                 return;
315
316         do {
317                 tmp = list_first_entry(&engine->timeline->requests,
318                                        typeof(*tmp), link);
319
320                 i915_gem_request_retire(tmp);
321         } while (tmp != req);
322 }
323
324 static int i915_gem_init_global_seqno(struct drm_i915_private *i915, u32 seqno)
325 {
326         struct i915_gem_timeline *timeline = &i915->gt.global_timeline;
327         struct intel_engine_cs *engine;
328         enum intel_engine_id id;
329         int ret;
330
331         /* Carefully retire all requests without writing to the rings */
332         ret = i915_gem_wait_for_idle(i915,
333                                      I915_WAIT_INTERRUPTIBLE |
334                                      I915_WAIT_LOCKED);
335         if (ret)
336                 return ret;
337
338         i915_gem_retire_requests(i915);
339         GEM_BUG_ON(i915->gt.active_requests > 1);
340
341         /* If the seqno wraps around, we need to clear the breadcrumb rbtree */
342         if (!i915_seqno_passed(seqno, atomic_read(&timeline->seqno))) {
343                 while (intel_breadcrumbs_busy(i915))
344                         cond_resched(); /* spin until threads are complete */
345         }
346         atomic_set(&timeline->seqno, seqno);
347
348         /* Finally reset hw state */
349         for_each_engine(engine, i915, id)
350                 intel_engine_init_global_seqno(engine, seqno);
351
352         list_for_each_entry(timeline, &i915->gt.timelines, link) {
353                 for_each_engine(engine, i915, id) {
354                         struct intel_timeline *tl = &timeline->engine[id];
355
356                         memset(tl->sync_seqno, 0, sizeof(tl->sync_seqno));
357                 }
358         }
359
360         return 0;
361 }
362
363 int i915_gem_set_global_seqno(struct drm_device *dev, u32 seqno)
364 {
365         struct drm_i915_private *dev_priv = to_i915(dev);
366
367         lockdep_assert_held(&dev_priv->drm.struct_mutex);
368
369         if (seqno == 0)
370                 return -EINVAL;
371
372         /* HWS page needs to be set less than what we
373          * will inject to ring
374          */
375         return i915_gem_init_global_seqno(dev_priv, seqno - 1);
376 }
377
378 static int reserve_global_seqno(struct drm_i915_private *i915)
379 {
380         u32 active_requests = ++i915->gt.active_requests;
381         u32 seqno = atomic_read(&i915->gt.global_timeline.seqno);
382         int ret;
383
384         /* Reservation is fine until we need to wrap around */
385         if (likely(seqno + active_requests > seqno))
386                 return 0;
387
388         ret = i915_gem_init_global_seqno(i915, 0);
389         if (ret) {
390                 i915->gt.active_requests--;
391                 return ret;
392         }
393
394         return 0;
395 }
396
397 static u32 __timeline_get_seqno(struct i915_gem_timeline *tl)
398 {
399         /* seqno only incremented under a mutex */
400         return ++tl->seqno.counter;
401 }
402
403 static u32 timeline_get_seqno(struct i915_gem_timeline *tl)
404 {
405         return atomic_inc_return(&tl->seqno);
406 }
407
408 void __i915_gem_request_submit(struct drm_i915_gem_request *request)
409 {
410         struct intel_engine_cs *engine = request->engine;
411         struct intel_timeline *timeline;
412         u32 seqno;
413
414         /* Transfer from per-context onto the global per-engine timeline */
415         timeline = engine->timeline;
416         GEM_BUG_ON(timeline == request->timeline);
417         assert_spin_locked(&timeline->lock);
418
419         seqno = timeline_get_seqno(timeline->common);
420         GEM_BUG_ON(!seqno);
421         GEM_BUG_ON(i915_seqno_passed(intel_engine_get_seqno(engine), seqno));
422
423         GEM_BUG_ON(i915_seqno_passed(timeline->last_submitted_seqno, seqno));
424         request->previous_seqno = timeline->last_submitted_seqno;
425         timeline->last_submitted_seqno = seqno;
426
427         /* We may be recursing from the signal callback of another i915 fence */
428         spin_lock_nested(&request->lock, SINGLE_DEPTH_NESTING);
429         request->global_seqno = seqno;
430         if (test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT, &request->fence.flags))
431                 intel_engine_enable_signaling(request);
432         spin_unlock(&request->lock);
433
434         GEM_BUG_ON(!request->global_seqno);
435         engine->emit_breadcrumb(request,
436                                 request->ring->vaddr + request->postfix);
437
438         spin_lock(&request->timeline->lock);
439         list_move_tail(&request->link, &timeline->requests);
440         spin_unlock(&request->timeline->lock);
441
442         i915_sw_fence_commit(&request->execute);
443 }
444
445 void i915_gem_request_submit(struct drm_i915_gem_request *request)
446 {
447         struct intel_engine_cs *engine = request->engine;
448         unsigned long flags;
449
450         /* Will be called from irq-context when using foreign fences. */
451         spin_lock_irqsave(&engine->timeline->lock, flags);
452
453         __i915_gem_request_submit(request);
454
455         spin_unlock_irqrestore(&engine->timeline->lock, flags);
456 }
457
458 static int __i915_sw_fence_call
459 submit_notify(struct i915_sw_fence *fence, enum i915_sw_fence_notify state)
460 {
461         struct drm_i915_gem_request *request =
462                 container_of(fence, typeof(*request), submit);
463
464         switch (state) {
465         case FENCE_COMPLETE:
466                 request->engine->submit_request(request);
467                 break;
468
469         case FENCE_FREE:
470                 i915_gem_request_put(request);
471                 break;
472         }
473
474         return NOTIFY_DONE;
475 }
476
477 static int __i915_sw_fence_call
478 execute_notify(struct i915_sw_fence *fence, enum i915_sw_fence_notify state)
479 {
480         struct drm_i915_gem_request *request =
481                 container_of(fence, typeof(*request), execute);
482
483         switch (state) {
484         case FENCE_COMPLETE:
485                 break;
486
487         case FENCE_FREE:
488                 i915_gem_request_put(request);
489                 break;
490         }
491
492         return NOTIFY_DONE;
493 }
494
495 /**
496  * i915_gem_request_alloc - allocate a request structure
497  *
498  * @engine: engine that we wish to issue the request on.
499  * @ctx: context that the request will be associated with.
500  *       This can be NULL if the request is not directly related to
501  *       any specific user context, in which case this function will
502  *       choose an appropriate context to use.
503  *
504  * Returns a pointer to the allocated request if successful,
505  * or an error code if not.
506  */
507 struct drm_i915_gem_request *
508 i915_gem_request_alloc(struct intel_engine_cs *engine,
509                        struct i915_gem_context *ctx)
510 {
511         struct drm_i915_private *dev_priv = engine->i915;
512         struct drm_i915_gem_request *req;
513         int ret;
514
515         lockdep_assert_held(&dev_priv->drm.struct_mutex);
516
517         /* ABI: Before userspace accesses the GPU (e.g. execbuffer), report
518          * EIO if the GPU is already wedged.
519          */
520         if (i915_terminally_wedged(&dev_priv->gpu_error))
521                 return ERR_PTR(-EIO);
522
523         /* Pinning the contexts may generate requests in order to acquire
524          * GGTT space, so do this first before we reserve a seqno for
525          * ourselves.
526          */
527         ret = engine->context_pin(engine, ctx);
528         if (ret)
529                 return ERR_PTR(ret);
530
531         ret = reserve_global_seqno(dev_priv);
532         if (ret)
533                 goto err_unpin;
534
535         /* Move the oldest request to the slab-cache (if not in use!) */
536         req = list_first_entry_or_null(&engine->timeline->requests,
537                                        typeof(*req), link);
538         if (req && __i915_gem_request_completed(req))
539                 i915_gem_request_retire(req);
540
541         /* Beware: Dragons be flying overhead.
542          *
543          * We use RCU to look up requests in flight. The lookups may
544          * race with the request being allocated from the slab freelist.
545          * That is the request we are writing to here, may be in the process
546          * of being read by __i915_gem_active_get_rcu(). As such,
547          * we have to be very careful when overwriting the contents. During
548          * the RCU lookup, we change chase the request->engine pointer,
549          * read the request->global_seqno and increment the reference count.
550          *
551          * The reference count is incremented atomically. If it is zero,
552          * the lookup knows the request is unallocated and complete. Otherwise,
553          * it is either still in use, or has been reallocated and reset
554          * with dma_fence_init(). This increment is safe for release as we
555          * check that the request we have a reference to and matches the active
556          * request.
557          *
558          * Before we increment the refcount, we chase the request->engine
559          * pointer. We must not call kmem_cache_zalloc() or else we set
560          * that pointer to NULL and cause a crash during the lookup. If
561          * we see the request is completed (based on the value of the
562          * old engine and seqno), the lookup is complete and reports NULL.
563          * If we decide the request is not completed (new engine or seqno),
564          * then we grab a reference and double check that it is still the
565          * active request - which it won't be and restart the lookup.
566          *
567          * Do not use kmem_cache_zalloc() here!
568          */
569         req = kmem_cache_alloc(dev_priv->requests, GFP_KERNEL);
570         if (!req) {
571                 ret = -ENOMEM;
572                 goto err_unreserve;
573         }
574
575         req->timeline = i915_gem_context_lookup_timeline(ctx, engine);
576         GEM_BUG_ON(req->timeline == engine->timeline);
577
578         spin_lock_init(&req->lock);
579         dma_fence_init(&req->fence,
580                        &i915_fence_ops,
581                        &req->lock,
582                        req->timeline->fence_context,
583                        __timeline_get_seqno(req->timeline->common));
584
585         /* We bump the ref for the fence chain */
586         i915_sw_fence_init(&i915_gem_request_get(req)->submit, submit_notify);
587         i915_sw_fence_init(&i915_gem_request_get(req)->execute, execute_notify);
588
589         /* Ensure that the execute fence completes after the submit fence -
590          * as we complete the execute fence from within the submit fence
591          * callback, its completion would otherwise be visible first.
592          */
593         i915_sw_fence_await_sw_fence(&req->execute, &req->submit, &req->execq);
594
595         i915_priotree_init(&req->priotree);
596
597         INIT_LIST_HEAD(&req->active_list);
598         req->i915 = dev_priv;
599         req->engine = engine;
600         req->ctx = ctx;
601
602         /* No zalloc, must clear what we need by hand */
603         req->global_seqno = 0;
604         req->file_priv = NULL;
605         req->batch = NULL;
606
607         /*
608          * Reserve space in the ring buffer for all the commands required to
609          * eventually emit this request. This is to guarantee that the
610          * i915_add_request() call can't fail. Note that the reserve may need
611          * to be redone if the request is not actually submitted straight
612          * away, e.g. because a GPU scheduler has deferred it.
613          */
614         req->reserved_space = MIN_SPACE_FOR_ADD_REQUEST;
615         GEM_BUG_ON(req->reserved_space < engine->emit_breadcrumb_sz);
616
617         ret = engine->request_alloc(req);
618         if (ret)
619                 goto err_ctx;
620
621         /* Record the position of the start of the request so that
622          * should we detect the updated seqno part-way through the
623          * GPU processing the request, we never over-estimate the
624          * position of the head.
625          */
626         req->head = req->ring->tail;
627
628         return req;
629
630 err_ctx:
631         /* Make sure we didn't add ourselves to external state before freeing */
632         GEM_BUG_ON(!list_empty(&req->active_list));
633         GEM_BUG_ON(!list_empty(&req->priotree.signalers_list));
634         GEM_BUG_ON(!list_empty(&req->priotree.waiters_list));
635
636         kmem_cache_free(dev_priv->requests, req);
637 err_unreserve:
638         dev_priv->gt.active_requests--;
639 err_unpin:
640         engine->context_unpin(engine, ctx);
641         return ERR_PTR(ret);
642 }
643
644 static int
645 i915_gem_request_await_request(struct drm_i915_gem_request *to,
646                                struct drm_i915_gem_request *from)
647 {
648         int ret;
649
650         GEM_BUG_ON(to == from);
651
652         if (to->engine->schedule) {
653                 ret = i915_priotree_add_dependency(to->i915,
654                                                    &to->priotree,
655                                                    &from->priotree);
656                 if (ret < 0)
657                         return ret;
658         }
659
660         if (to->timeline == from->timeline)
661                 return 0;
662
663         if (to->engine == from->engine) {
664                 ret = i915_sw_fence_await_sw_fence_gfp(&to->submit,
665                                                        &from->submit,
666                                                        GFP_KERNEL);
667                 return ret < 0 ? ret : 0;
668         }
669
670         if (!from->global_seqno) {
671                 ret = i915_sw_fence_await_dma_fence(&to->submit,
672                                                     &from->fence, 0,
673                                                     GFP_KERNEL);
674                 return ret < 0 ? ret : 0;
675         }
676
677         if (from->global_seqno <= to->timeline->sync_seqno[from->engine->id])
678                 return 0;
679
680         trace_i915_gem_ring_sync_to(to, from);
681         if (!i915.semaphores) {
682                 if (!i915_spin_request(from, TASK_INTERRUPTIBLE, 2)) {
683                         ret = i915_sw_fence_await_dma_fence(&to->submit,
684                                                             &from->fence, 0,
685                                                             GFP_KERNEL);
686                         if (ret < 0)
687                                 return ret;
688                 }
689         } else {
690                 ret = to->engine->semaphore.sync_to(to, from);
691                 if (ret)
692                         return ret;
693         }
694
695         to->timeline->sync_seqno[from->engine->id] = from->global_seqno;
696         return 0;
697 }
698
699 int
700 i915_gem_request_await_dma_fence(struct drm_i915_gem_request *req,
701                                  struct dma_fence *fence)
702 {
703         struct dma_fence_array *array;
704         int ret;
705         int i;
706
707         if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
708                 return 0;
709
710         if (dma_fence_is_i915(fence))
711                 return i915_gem_request_await_request(req, to_request(fence));
712
713         if (!dma_fence_is_array(fence)) {
714                 ret = i915_sw_fence_await_dma_fence(&req->submit,
715                                                     fence, I915_FENCE_TIMEOUT,
716                                                     GFP_KERNEL);
717                 return ret < 0 ? ret : 0;
718         }
719
720         /* Note that if the fence-array was created in signal-on-any mode,
721          * we should *not* decompose it into its individual fences. However,
722          * we don't currently store which mode the fence-array is operating
723          * in. Fortunately, the only user of signal-on-any is private to
724          * amdgpu and we should not see any incoming fence-array from
725          * sync-file being in signal-on-any mode.
726          */
727
728         array = to_dma_fence_array(fence);
729         for (i = 0; i < array->num_fences; i++) {
730                 struct dma_fence *child = array->fences[i];
731
732                 if (dma_fence_is_i915(child))
733                         ret = i915_gem_request_await_request(req,
734                                                              to_request(child));
735                 else
736                         ret = i915_sw_fence_await_dma_fence(&req->submit,
737                                                             child, I915_FENCE_TIMEOUT,
738                                                             GFP_KERNEL);
739                 if (ret < 0)
740                         return ret;
741         }
742
743         return 0;
744 }
745
746 /**
747  * i915_gem_request_await_object - set this request to (async) wait upon a bo
748  *
749  * @to: request we are wishing to use
750  * @obj: object which may be in use on another ring.
751  *
752  * This code is meant to abstract object synchronization with the GPU.
753  * Conceptually we serialise writes between engines inside the GPU.
754  * We only allow one engine to write into a buffer at any time, but
755  * multiple readers. To ensure each has a coherent view of memory, we must:
756  *
757  * - If there is an outstanding write request to the object, the new
758  *   request must wait for it to complete (either CPU or in hw, requests
759  *   on the same ring will be naturally ordered).
760  *
761  * - If we are a write request (pending_write_domain is set), the new
762  *   request must wait for outstanding read requests to complete.
763  *
764  * Returns 0 if successful, else propagates up the lower layer error.
765  */
766 int
767 i915_gem_request_await_object(struct drm_i915_gem_request *to,
768                               struct drm_i915_gem_object *obj,
769                               bool write)
770 {
771         struct dma_fence *excl;
772         int ret = 0;
773
774         if (write) {
775                 struct dma_fence **shared;
776                 unsigned int count, i;
777
778                 ret = reservation_object_get_fences_rcu(obj->resv,
779                                                         &excl, &count, &shared);
780                 if (ret)
781                         return ret;
782
783                 for (i = 0; i < count; i++) {
784                         ret = i915_gem_request_await_dma_fence(to, shared[i]);
785                         if (ret)
786                                 break;
787
788                         dma_fence_put(shared[i]);
789                 }
790
791                 for (; i < count; i++)
792                         dma_fence_put(shared[i]);
793                 kfree(shared);
794         } else {
795                 excl = reservation_object_get_excl_rcu(obj->resv);
796         }
797
798         if (excl) {
799                 if (ret == 0)
800                         ret = i915_gem_request_await_dma_fence(to, excl);
801
802                 dma_fence_put(excl);
803         }
804
805         return ret;
806 }
807
808 static void i915_gem_mark_busy(const struct intel_engine_cs *engine)
809 {
810         struct drm_i915_private *dev_priv = engine->i915;
811
812         if (dev_priv->gt.awake)
813                 return;
814
815         GEM_BUG_ON(!dev_priv->gt.active_requests);
816
817         intel_runtime_pm_get_noresume(dev_priv);
818         dev_priv->gt.awake = true;
819
820         intel_enable_gt_powersave(dev_priv);
821         i915_update_gfx_val(dev_priv);
822         if (INTEL_GEN(dev_priv) >= 6)
823                 gen6_rps_busy(dev_priv);
824
825         queue_delayed_work(dev_priv->wq,
826                            &dev_priv->gt.retire_work,
827                            round_jiffies_up_relative(HZ));
828 }
829
830 /*
831  * NB: This function is not allowed to fail. Doing so would mean the the
832  * request is not being tracked for completion but the work itself is
833  * going to happen on the hardware. This would be a Bad Thing(tm).
834  */
835 void __i915_add_request(struct drm_i915_gem_request *request, bool flush_caches)
836 {
837         struct intel_engine_cs *engine = request->engine;
838         struct intel_ring *ring = request->ring;
839         struct intel_timeline *timeline = request->timeline;
840         struct drm_i915_gem_request *prev;
841         int err;
842
843         lockdep_assert_held(&request->i915->drm.struct_mutex);
844         trace_i915_gem_request_add(request);
845
846         /* Make sure that no request gazumped us - if it was allocated after
847          * our i915_gem_request_alloc() and called __i915_add_request() before
848          * us, the timeline will hold its seqno which is later than ours.
849          */
850         GEM_BUG_ON(i915_seqno_passed(timeline->last_submitted_seqno,
851                                      request->fence.seqno));
852
853         /*
854          * To ensure that this call will not fail, space for its emissions
855          * should already have been reserved in the ring buffer. Let the ring
856          * know that it is time to use that space up.
857          */
858         request->reserved_space = 0;
859
860         /*
861          * Emit any outstanding flushes - execbuf can fail to emit the flush
862          * after having emitted the batchbuffer command. Hence we need to fix
863          * things up similar to emitting the lazy request. The difference here
864          * is that the flush _must_ happen before the next request, no matter
865          * what.
866          */
867         if (flush_caches) {
868                 err = engine->emit_flush(request, EMIT_FLUSH);
869
870                 /* Not allowed to fail! */
871                 WARN(err, "engine->emit_flush() failed: %d!\n", err);
872         }
873
874         /* Record the position of the start of the breadcrumb so that
875          * should we detect the updated seqno part-way through the
876          * GPU processing the request, we never over-estimate the
877          * position of the ring's HEAD.
878          */
879         err = intel_ring_begin(request, engine->emit_breadcrumb_sz);
880         GEM_BUG_ON(err);
881         request->postfix = ring->tail;
882         ring->tail += engine->emit_breadcrumb_sz * sizeof(u32);
883
884         /* Seal the request and mark it as pending execution. Note that
885          * we may inspect this state, without holding any locks, during
886          * hangcheck. Hence we apply the barrier to ensure that we do not
887          * see a more recent value in the hws than we are tracking.
888          */
889
890         prev = i915_gem_active_raw(&timeline->last_request,
891                                    &request->i915->drm.struct_mutex);
892         if (prev) {
893                 i915_sw_fence_await_sw_fence(&request->submit, &prev->submit,
894                                              &request->submitq);
895                 if (engine->schedule)
896                         __i915_priotree_add_dependency(&request->priotree,
897                                                        &prev->priotree,
898                                                        &request->dep,
899                                                        0);
900         }
901
902         spin_lock_irq(&timeline->lock);
903         list_add_tail(&request->link, &timeline->requests);
904         spin_unlock_irq(&timeline->lock);
905
906         GEM_BUG_ON(i915_seqno_passed(timeline->last_submitted_seqno,
907                                      request->fence.seqno));
908
909         timeline->last_submitted_seqno = request->fence.seqno;
910         i915_gem_active_set(&timeline->last_request, request);
911
912         list_add_tail(&request->ring_link, &ring->request_list);
913         request->emitted_jiffies = jiffies;
914
915         i915_gem_mark_busy(engine);
916
917         /* Let the backend know a new request has arrived that may need
918          * to adjust the existing execution schedule due to a high priority
919          * request - i.e. we may want to preempt the current request in order
920          * to run a high priority dependency chain *before* we can execute this
921          * request.
922          *
923          * This is called before the request is ready to run so that we can
924          * decide whether to preempt the entire chain so that it is ready to
925          * run at the earliest possible convenience.
926          */
927         if (engine->schedule)
928                 engine->schedule(request, request->ctx->priority);
929
930         local_bh_disable();
931         i915_sw_fence_commit(&request->submit);
932         local_bh_enable(); /* Kick the execlists tasklet if just scheduled */
933 }
934
935 static void reset_wait_queue(wait_queue_head_t *q, wait_queue_t *wait)
936 {
937         unsigned long flags;
938
939         spin_lock_irqsave(&q->lock, flags);
940         if (list_empty(&wait->task_list))
941                 __add_wait_queue(q, wait);
942         spin_unlock_irqrestore(&q->lock, flags);
943 }
944
945 static unsigned long local_clock_us(unsigned int *cpu)
946 {
947         unsigned long t;
948
949         /* Cheaply and approximately convert from nanoseconds to microseconds.
950          * The result and subsequent calculations are also defined in the same
951          * approximate microseconds units. The principal source of timing
952          * error here is from the simple truncation.
953          *
954          * Note that local_clock() is only defined wrt to the current CPU;
955          * the comparisons are no longer valid if we switch CPUs. Instead of
956          * blocking preemption for the entire busywait, we can detect the CPU
957          * switch and use that as indicator of system load and a reason to
958          * stop busywaiting, see busywait_stop().
959          */
960         *cpu = get_cpu();
961         t = local_clock() >> 10;
962         put_cpu();
963
964         return t;
965 }
966
967 static bool busywait_stop(unsigned long timeout, unsigned int cpu)
968 {
969         unsigned int this_cpu;
970
971         if (time_after(local_clock_us(&this_cpu), timeout))
972                 return true;
973
974         return this_cpu != cpu;
975 }
976
977 bool __i915_spin_request(const struct drm_i915_gem_request *req,
978                          int state, unsigned long timeout_us)
979 {
980         unsigned int cpu;
981
982         /* When waiting for high frequency requests, e.g. during synchronous
983          * rendering split between the CPU and GPU, the finite amount of time
984          * required to set up the irq and wait upon it limits the response
985          * rate. By busywaiting on the request completion for a short while we
986          * can service the high frequency waits as quick as possible. However,
987          * if it is a slow request, we want to sleep as quickly as possible.
988          * The tradeoff between waiting and sleeping is roughly the time it
989          * takes to sleep on a request, on the order of a microsecond.
990          */
991
992         timeout_us += local_clock_us(&cpu);
993         do {
994                 if (__i915_gem_request_completed(req))
995                         return true;
996
997                 if (signal_pending_state(state, current))
998                         break;
999
1000                 if (busywait_stop(timeout_us, cpu))
1001                         break;
1002
1003                 cpu_relax();
1004         } while (!need_resched());
1005
1006         return false;
1007 }
1008
1009 static long
1010 __i915_request_wait_for_execute(struct drm_i915_gem_request *request,
1011                                 unsigned int flags,
1012                                 long timeout)
1013 {
1014         const int state = flags & I915_WAIT_INTERRUPTIBLE ?
1015                 TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE;
1016         wait_queue_head_t *q = &request->i915->gpu_error.wait_queue;
1017         DEFINE_WAIT(reset);
1018         DEFINE_WAIT(wait);
1019
1020         if (flags & I915_WAIT_LOCKED)
1021                 add_wait_queue(q, &reset);
1022
1023         do {
1024                 prepare_to_wait(&request->execute.wait, &wait, state);
1025
1026                 if (i915_sw_fence_done(&request->execute))
1027                         break;
1028
1029                 if (flags & I915_WAIT_LOCKED &&
1030                     i915_reset_in_progress(&request->i915->gpu_error)) {
1031                         __set_current_state(TASK_RUNNING);
1032                         i915_reset(request->i915);
1033                         reset_wait_queue(q, &reset);
1034                         continue;
1035                 }
1036
1037                 if (signal_pending_state(state, current)) {
1038                         timeout = -ERESTARTSYS;
1039                         break;
1040                 }
1041
1042                 if (!timeout) {
1043                         timeout = -ETIME;
1044                         break;
1045                 }
1046
1047                 timeout = io_schedule_timeout(timeout);
1048         } while (1);
1049         finish_wait(&request->execute.wait, &wait);
1050
1051         if (flags & I915_WAIT_LOCKED)
1052                 remove_wait_queue(q, &reset);
1053
1054         return timeout;
1055 }
1056
1057 /**
1058  * i915_wait_request - wait until execution of request has finished
1059  * @req: the request to wait upon
1060  * @flags: how to wait
1061  * @timeout: how long to wait in jiffies
1062  *
1063  * i915_wait_request() waits for the request to be completed, for a
1064  * maximum of @timeout jiffies (with MAX_SCHEDULE_TIMEOUT implying an
1065  * unbounded wait).
1066  *
1067  * If the caller holds the struct_mutex, the caller must pass I915_WAIT_LOCKED
1068  * in via the flags, and vice versa if the struct_mutex is not held, the caller
1069  * must not specify that the wait is locked.
1070  *
1071  * Returns the remaining time (in jiffies) if the request completed, which may
1072  * be zero or -ETIME if the request is unfinished after the timeout expires.
1073  * May return -EINTR is called with I915_WAIT_INTERRUPTIBLE and a signal is
1074  * pending before the request completes.
1075  */
1076 long i915_wait_request(struct drm_i915_gem_request *req,
1077                        unsigned int flags,
1078                        long timeout)
1079 {
1080         const int state = flags & I915_WAIT_INTERRUPTIBLE ?
1081                 TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE;
1082         DEFINE_WAIT(reset);
1083         struct intel_wait wait;
1084
1085         might_sleep();
1086 #if IS_ENABLED(CONFIG_LOCKDEP)
1087         GEM_BUG_ON(debug_locks &&
1088                    !!lockdep_is_held(&req->i915->drm.struct_mutex) !=
1089                    !!(flags & I915_WAIT_LOCKED));
1090 #endif
1091         GEM_BUG_ON(timeout < 0);
1092
1093         if (i915_gem_request_completed(req))
1094                 return timeout;
1095
1096         if (!timeout)
1097                 return -ETIME;
1098
1099         trace_i915_gem_request_wait_begin(req);
1100
1101         if (!i915_sw_fence_done(&req->execute)) {
1102                 timeout = __i915_request_wait_for_execute(req, flags, timeout);
1103                 if (timeout < 0)
1104                         goto complete;
1105
1106                 GEM_BUG_ON(!i915_sw_fence_done(&req->execute));
1107         }
1108         GEM_BUG_ON(!i915_sw_fence_done(&req->submit));
1109         GEM_BUG_ON(!req->global_seqno);
1110
1111         /* Optimistic short spin before touching IRQs */
1112         if (i915_spin_request(req, state, 5))
1113                 goto complete;
1114
1115         set_current_state(state);
1116         if (flags & I915_WAIT_LOCKED)
1117                 add_wait_queue(&req->i915->gpu_error.wait_queue, &reset);
1118
1119         intel_wait_init(&wait, req->global_seqno);
1120         if (intel_engine_add_wait(req->engine, &wait))
1121                 /* In order to check that we haven't missed the interrupt
1122                  * as we enabled it, we need to kick ourselves to do a
1123                  * coherent check on the seqno before we sleep.
1124                  */
1125                 goto wakeup;
1126
1127         for (;;) {
1128                 if (signal_pending_state(state, current)) {
1129                         timeout = -ERESTARTSYS;
1130                         break;
1131                 }
1132
1133                 if (!timeout) {
1134                         timeout = -ETIME;
1135                         break;
1136                 }
1137
1138                 timeout = io_schedule_timeout(timeout);
1139
1140                 if (intel_wait_complete(&wait))
1141                         break;
1142
1143                 set_current_state(state);
1144
1145 wakeup:
1146                 /* Carefully check if the request is complete, giving time
1147                  * for the seqno to be visible following the interrupt.
1148                  * We also have to check in case we are kicked by the GPU
1149                  * reset in order to drop the struct_mutex.
1150                  */
1151                 if (__i915_request_irq_complete(req))
1152                         break;
1153
1154                 /* If the GPU is hung, and we hold the lock, reset the GPU
1155                  * and then check for completion. On a full reset, the engine's
1156                  * HW seqno will be advanced passed us and we are complete.
1157                  * If we do a partial reset, we have to wait for the GPU to
1158                  * resume and update the breadcrumb.
1159                  *
1160                  * If we don't hold the mutex, we can just wait for the worker
1161                  * to come along and update the breadcrumb (either directly
1162                  * itself, or indirectly by recovering the GPU).
1163                  */
1164                 if (flags & I915_WAIT_LOCKED &&
1165                     i915_reset_in_progress(&req->i915->gpu_error)) {
1166                         __set_current_state(TASK_RUNNING);
1167                         i915_reset(req->i915);
1168                         reset_wait_queue(&req->i915->gpu_error.wait_queue,
1169                                          &reset);
1170                         continue;
1171                 }
1172
1173                 /* Only spin if we know the GPU is processing this request */
1174                 if (i915_spin_request(req, state, 2))
1175                         break;
1176         }
1177
1178         intel_engine_remove_wait(req->engine, &wait);
1179         if (flags & I915_WAIT_LOCKED)
1180                 remove_wait_queue(&req->i915->gpu_error.wait_queue, &reset);
1181         __set_current_state(TASK_RUNNING);
1182
1183 complete:
1184         trace_i915_gem_request_wait_end(req);
1185
1186         return timeout;
1187 }
1188
1189 static void engine_retire_requests(struct intel_engine_cs *engine)
1190 {
1191         struct drm_i915_gem_request *request, *next;
1192
1193         list_for_each_entry_safe(request, next,
1194                                  &engine->timeline->requests, link) {
1195                 if (!__i915_gem_request_completed(request))
1196                         return;
1197
1198                 i915_gem_request_retire(request);
1199         }
1200 }
1201
1202 void i915_gem_retire_requests(struct drm_i915_private *dev_priv)
1203 {
1204         struct intel_engine_cs *engine;
1205         enum intel_engine_id id;
1206
1207         lockdep_assert_held(&dev_priv->drm.struct_mutex);
1208
1209         if (!dev_priv->gt.active_requests)
1210                 return;
1211
1212         for_each_engine(engine, dev_priv, id)
1213                 engine_retire_requests(engine);
1214 }
This page took 0.117404 seconds and 4 git commands to generate.