drm/i915: Add control flags to i915_handle_error()
[linux-2.6-block.git] / drivers / gpu / drm / i915 / i915_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         /*
41          * The timeline struct (as part of the ppgtt underneath a context)
42          * may be freed when the request is no longer in use by the GPU.
43          * We could extend the life of a context to beyond that of all
44          * fences, possibly keeping the hw resource around indefinitely,
45          * or we just give them a false name. Since
46          * dma_fence_ops.get_timeline_name is a debug feature, the occasional
47          * lie seems justifiable.
48          */
49         if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
50                 return "signaled";
51
52         return to_request(fence)->timeline->common->name;
53 }
54
55 static bool i915_fence_signaled(struct dma_fence *fence)
56 {
57         return i915_request_completed(to_request(fence));
58 }
59
60 static bool i915_fence_enable_signaling(struct dma_fence *fence)
61 {
62         return intel_engine_enable_signaling(to_request(fence), true);
63 }
64
65 static signed long i915_fence_wait(struct dma_fence *fence,
66                                    bool interruptible,
67                                    signed long timeout)
68 {
69         return i915_request_wait(to_request(fence), interruptible, timeout);
70 }
71
72 static void i915_fence_release(struct dma_fence *fence)
73 {
74         struct i915_request *rq = to_request(fence);
75
76         /*
77          * The request is put onto a RCU freelist (i.e. the address
78          * is immediately reused), mark the fences as being freed now.
79          * Otherwise the debugobjects for the fences are only marked as
80          * freed when the slab cache itself is freed, and so we would get
81          * caught trying to reuse dead objects.
82          */
83         i915_sw_fence_fini(&rq->submit);
84
85         kmem_cache_free(rq->i915->requests, rq);
86 }
87
88 const struct dma_fence_ops i915_fence_ops = {
89         .get_driver_name = i915_fence_get_driver_name,
90         .get_timeline_name = i915_fence_get_timeline_name,
91         .enable_signaling = i915_fence_enable_signaling,
92         .signaled = i915_fence_signaled,
93         .wait = i915_fence_wait,
94         .release = i915_fence_release,
95 };
96
97 static inline void
98 i915_request_remove_from_client(struct i915_request *request)
99 {
100         struct drm_i915_file_private *file_priv;
101
102         file_priv = request->file_priv;
103         if (!file_priv)
104                 return;
105
106         spin_lock(&file_priv->mm.lock);
107         if (request->file_priv) {
108                 list_del(&request->client_link);
109                 request->file_priv = NULL;
110         }
111         spin_unlock(&file_priv->mm.lock);
112 }
113
114 static struct i915_dependency *
115 i915_dependency_alloc(struct drm_i915_private *i915)
116 {
117         return kmem_cache_alloc(i915->dependencies, GFP_KERNEL);
118 }
119
120 static void
121 i915_dependency_free(struct drm_i915_private *i915,
122                      struct i915_dependency *dep)
123 {
124         kmem_cache_free(i915->dependencies, dep);
125 }
126
127 static void
128 __i915_priotree_add_dependency(struct i915_priotree *pt,
129                                struct i915_priotree *signal,
130                                struct i915_dependency *dep,
131                                unsigned long flags)
132 {
133         INIT_LIST_HEAD(&dep->dfs_link);
134         list_add(&dep->wait_link, &signal->waiters_list);
135         list_add(&dep->signal_link, &pt->signalers_list);
136         dep->signaler = signal;
137         dep->flags = flags;
138 }
139
140 static int
141 i915_priotree_add_dependency(struct drm_i915_private *i915,
142                              struct i915_priotree *pt,
143                              struct i915_priotree *signal)
144 {
145         struct i915_dependency *dep;
146
147         dep = i915_dependency_alloc(i915);
148         if (!dep)
149                 return -ENOMEM;
150
151         __i915_priotree_add_dependency(pt, signal, dep, I915_DEPENDENCY_ALLOC);
152         return 0;
153 }
154
155 static void
156 i915_priotree_fini(struct drm_i915_private *i915, struct i915_priotree *pt)
157 {
158         struct i915_dependency *dep, *next;
159
160         GEM_BUG_ON(!list_empty(&pt->link));
161
162         /*
163          * Everyone we depended upon (the fences we wait to be signaled)
164          * should retire before us and remove themselves from our list.
165          * However, retirement is run independently on each timeline and
166          * so we may be called out-of-order.
167          */
168         list_for_each_entry_safe(dep, next, &pt->signalers_list, signal_link) {
169                 GEM_BUG_ON(!i915_priotree_signaled(dep->signaler));
170                 GEM_BUG_ON(!list_empty(&dep->dfs_link));
171
172                 list_del(&dep->wait_link);
173                 if (dep->flags & I915_DEPENDENCY_ALLOC)
174                         i915_dependency_free(i915, dep);
175         }
176
177         /* Remove ourselves from everyone who depends upon us */
178         list_for_each_entry_safe(dep, next, &pt->waiters_list, wait_link) {
179                 GEM_BUG_ON(dep->signaler != pt);
180                 GEM_BUG_ON(!list_empty(&dep->dfs_link));
181
182                 list_del(&dep->signal_link);
183                 if (dep->flags & I915_DEPENDENCY_ALLOC)
184                         i915_dependency_free(i915, dep);
185         }
186 }
187
188 static void
189 i915_priotree_init(struct i915_priotree *pt)
190 {
191         INIT_LIST_HEAD(&pt->signalers_list);
192         INIT_LIST_HEAD(&pt->waiters_list);
193         INIT_LIST_HEAD(&pt->link);
194         pt->priority = I915_PRIORITY_INVALID;
195 }
196
197 static int reset_all_global_seqno(struct drm_i915_private *i915, u32 seqno)
198 {
199         struct intel_engine_cs *engine;
200         enum intel_engine_id id;
201         int ret;
202
203         /* Carefully retire all requests without writing to the rings */
204         ret = i915_gem_wait_for_idle(i915,
205                                      I915_WAIT_INTERRUPTIBLE |
206                                      I915_WAIT_LOCKED);
207         if (ret)
208                 return ret;
209
210         GEM_BUG_ON(i915->gt.active_requests);
211
212         /* If the seqno wraps around, we need to clear the breadcrumb rbtree */
213         for_each_engine(engine, i915, id) {
214                 struct i915_gem_timeline *timeline;
215                 struct intel_timeline *tl = engine->timeline;
216
217                 GEM_TRACE("%s seqno %d -> %d\n",
218                           engine->name, tl->seqno, seqno);
219
220                 if (!i915_seqno_passed(seqno, tl->seqno)) {
221                         /* Flush any waiters before we reuse the seqno */
222                         intel_engine_disarm_breadcrumbs(engine);
223                         GEM_BUG_ON(!list_empty(&engine->breadcrumbs.signals));
224                 }
225
226                 /* Check we are idle before we fiddle with hw state! */
227                 GEM_BUG_ON(!intel_engine_is_idle(engine));
228                 GEM_BUG_ON(i915_gem_active_isset(&engine->timeline->last_request));
229
230                 /* Finally reset hw state */
231                 intel_engine_init_global_seqno(engine, seqno);
232                 tl->seqno = seqno;
233
234                 list_for_each_entry(timeline, &i915->gt.timelines, link)
235                         memset(timeline->engine[id].global_sync, 0,
236                                sizeof(timeline->engine[id].global_sync));
237         }
238
239         return 0;
240 }
241
242 int i915_gem_set_global_seqno(struct drm_device *dev, u32 seqno)
243 {
244         struct drm_i915_private *i915 = to_i915(dev);
245
246         lockdep_assert_held(&i915->drm.struct_mutex);
247
248         if (seqno == 0)
249                 return -EINVAL;
250
251         /* HWS page needs to be set less than what we will inject to ring */
252         return reset_all_global_seqno(i915, seqno - 1);
253 }
254
255 static void mark_busy(struct drm_i915_private *i915)
256 {
257         if (i915->gt.awake)
258                 return;
259
260         GEM_BUG_ON(!i915->gt.active_requests);
261
262         intel_runtime_pm_get_noresume(i915);
263
264         /*
265          * It seems that the DMC likes to transition between the DC states a lot
266          * when there are no connected displays (no active power domains) during
267          * command submission.
268          *
269          * This activity has negative impact on the performance of the chip with
270          * huge latencies observed in the interrupt handler and elsewhere.
271          *
272          * Work around it by grabbing a GT IRQ power domain whilst there is any
273          * GT activity, preventing any DC state transitions.
274          */
275         intel_display_power_get(i915, POWER_DOMAIN_GT_IRQ);
276
277         i915->gt.awake = true;
278         if (unlikely(++i915->gt.epoch == 0)) /* keep 0 as invalid */
279                 i915->gt.epoch = 1;
280
281         intel_enable_gt_powersave(i915);
282         i915_update_gfx_val(i915);
283         if (INTEL_GEN(i915) >= 6)
284                 gen6_rps_busy(i915);
285         i915_pmu_gt_unparked(i915);
286
287         intel_engines_unpark(i915);
288
289         i915_queue_hangcheck(i915);
290
291         queue_delayed_work(i915->wq,
292                            &i915->gt.retire_work,
293                            round_jiffies_up_relative(HZ));
294 }
295
296 static int reserve_engine(struct intel_engine_cs *engine)
297 {
298         struct drm_i915_private *i915 = engine->i915;
299         u32 active = ++engine->timeline->inflight_seqnos;
300         u32 seqno = engine->timeline->seqno;
301         int ret;
302
303         /* Reservation is fine until we need to wrap around */
304         if (unlikely(add_overflows(seqno, active))) {
305                 ret = reset_all_global_seqno(i915, 0);
306                 if (ret) {
307                         engine->timeline->inflight_seqnos--;
308                         return ret;
309                 }
310         }
311
312         if (!i915->gt.active_requests++)
313                 mark_busy(i915);
314
315         return 0;
316 }
317
318 static void unreserve_engine(struct intel_engine_cs *engine)
319 {
320         struct drm_i915_private *i915 = engine->i915;
321
322         if (!--i915->gt.active_requests) {
323                 /* Cancel the mark_busy() from our reserve_engine() */
324                 GEM_BUG_ON(!i915->gt.awake);
325                 mod_delayed_work(i915->wq,
326                                  &i915->gt.idle_work,
327                                  msecs_to_jiffies(100));
328         }
329
330         GEM_BUG_ON(!engine->timeline->inflight_seqnos);
331         engine->timeline->inflight_seqnos--;
332 }
333
334 void i915_gem_retire_noop(struct i915_gem_active *active,
335                           struct i915_request *request)
336 {
337         /* Space left intentionally blank */
338 }
339
340 static void advance_ring(struct i915_request *request)
341 {
342         unsigned int tail;
343
344         /*
345          * We know the GPU must have read the request to have
346          * sent us the seqno + interrupt, so use the position
347          * of tail of the request to update the last known position
348          * of the GPU head.
349          *
350          * Note this requires that we are always called in request
351          * completion order.
352          */
353         if (list_is_last(&request->ring_link, &request->ring->request_list)) {
354                 /*
355                  * We may race here with execlists resubmitting this request
356                  * as we retire it. The resubmission will move the ring->tail
357                  * forwards (to request->wa_tail). We either read the
358                  * current value that was written to hw, or the value that
359                  * is just about to be. Either works, if we miss the last two
360                  * noops - they are safe to be replayed on a reset.
361                  */
362                 tail = READ_ONCE(request->tail);
363         } else {
364                 tail = request->postfix;
365         }
366         list_del(&request->ring_link);
367
368         request->ring->head = tail;
369 }
370
371 static void free_capture_list(struct i915_request *request)
372 {
373         struct i915_capture_list *capture;
374
375         capture = request->capture_list;
376         while (capture) {
377                 struct i915_capture_list *next = capture->next;
378
379                 kfree(capture);
380                 capture = next;
381         }
382 }
383
384 static void i915_request_retire(struct i915_request *request)
385 {
386         struct intel_engine_cs *engine = request->engine;
387         struct i915_gem_active *active, *next;
388
389         GEM_TRACE("%s(%d) fence %llx:%d, global_seqno %d\n",
390                   engine->name, intel_engine_get_seqno(engine),
391                   request->fence.context, request->fence.seqno,
392                   request->global_seqno);
393
394         lockdep_assert_held(&request->i915->drm.struct_mutex);
395         GEM_BUG_ON(!i915_sw_fence_signaled(&request->submit));
396         GEM_BUG_ON(!i915_request_completed(request));
397         GEM_BUG_ON(!request->i915->gt.active_requests);
398
399         trace_i915_request_retire(request);
400
401         spin_lock_irq(&engine->timeline->lock);
402         list_del_init(&request->link);
403         spin_unlock_irq(&engine->timeline->lock);
404
405         unreserve_engine(request->engine);
406         advance_ring(request);
407
408         free_capture_list(request);
409
410         /*
411          * Walk through the active list, calling retire on each. This allows
412          * objects to track their GPU activity and mark themselves as idle
413          * when their *last* active request is completed (updating state
414          * tracking lists for eviction, active references for GEM, etc).
415          *
416          * As the ->retire() may free the node, we decouple it first and
417          * pass along the auxiliary information (to avoid dereferencing
418          * the node after the callback).
419          */
420         list_for_each_entry_safe(active, next, &request->active_list, link) {
421                 /*
422                  * In microbenchmarks or focusing upon time inside the kernel,
423                  * we may spend an inordinate amount of time simply handling
424                  * the retirement of requests and processing their callbacks.
425                  * Of which, this loop itself is particularly hot due to the
426                  * cache misses when jumping around the list of i915_gem_active.
427                  * So we try to keep this loop as streamlined as possible and
428                  * also prefetch the next i915_gem_active to try and hide
429                  * the likely cache miss.
430                  */
431                 prefetchw(next);
432
433                 INIT_LIST_HEAD(&active->link);
434                 RCU_INIT_POINTER(active->request, NULL);
435
436                 active->retire(active, request);
437         }
438
439         i915_request_remove_from_client(request);
440
441         /* Retirement decays the ban score as it is a sign of ctx progress */
442         atomic_dec_if_positive(&request->ctx->ban_score);
443
444         /*
445          * The backing object for the context is done after switching to the
446          * *next* context. Therefore we cannot retire the previous context until
447          * the next context has already started running. However, since we
448          * cannot take the required locks at i915_request_submit() we
449          * defer the unpinning of the active context to now, retirement of
450          * the subsequent request.
451          */
452         if (engine->last_retired_context)
453                 engine->context_unpin(engine, engine->last_retired_context);
454         engine->last_retired_context = request->ctx;
455
456         spin_lock_irq(&request->lock);
457         if (!test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &request->fence.flags))
458                 dma_fence_signal_locked(&request->fence);
459         if (test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT, &request->fence.flags))
460                 intel_engine_cancel_signaling(request);
461         if (request->waitboost) {
462                 GEM_BUG_ON(!atomic_read(&request->i915->gt_pm.rps.num_waiters));
463                 atomic_dec(&request->i915->gt_pm.rps.num_waiters);
464         }
465         spin_unlock_irq(&request->lock);
466
467         i915_priotree_fini(request->i915, &request->priotree);
468         i915_request_put(request);
469 }
470
471 void i915_request_retire_upto(struct i915_request *rq)
472 {
473         struct intel_engine_cs *engine = rq->engine;
474         struct i915_request *tmp;
475
476         lockdep_assert_held(&rq->i915->drm.struct_mutex);
477         GEM_BUG_ON(!i915_request_completed(rq));
478
479         if (list_empty(&rq->link))
480                 return;
481
482         do {
483                 tmp = list_first_entry(&engine->timeline->requests,
484                                        typeof(*tmp), link);
485
486                 i915_request_retire(tmp);
487         } while (tmp != rq);
488 }
489
490 static u32 timeline_get_seqno(struct intel_timeline *tl)
491 {
492         return ++tl->seqno;
493 }
494
495 void __i915_request_submit(struct i915_request *request)
496 {
497         struct intel_engine_cs *engine = request->engine;
498         struct intel_timeline *timeline;
499         u32 seqno;
500
501         GEM_TRACE("%s fence %llx:%d -> global_seqno %d\n",
502                   request->engine->name,
503                   request->fence.context, request->fence.seqno,
504                   engine->timeline->seqno);
505
506         GEM_BUG_ON(!irqs_disabled());
507         lockdep_assert_held(&engine->timeline->lock);
508
509         /* Transfer from per-context onto the global per-engine timeline */
510         timeline = engine->timeline;
511         GEM_BUG_ON(timeline == request->timeline);
512         GEM_BUG_ON(request->global_seqno);
513
514         seqno = timeline_get_seqno(timeline);
515         GEM_BUG_ON(!seqno);
516         GEM_BUG_ON(i915_seqno_passed(intel_engine_get_seqno(engine), seqno));
517
518         /* We may be recursing from the signal callback of another i915 fence */
519         spin_lock_nested(&request->lock, SINGLE_DEPTH_NESTING);
520         request->global_seqno = seqno;
521         if (test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT, &request->fence.flags))
522                 intel_engine_enable_signaling(request, false);
523         spin_unlock(&request->lock);
524
525         engine->emit_breadcrumb(request,
526                                 request->ring->vaddr + request->postfix);
527
528         spin_lock(&request->timeline->lock);
529         list_move_tail(&request->link, &timeline->requests);
530         spin_unlock(&request->timeline->lock);
531
532         trace_i915_request_execute(request);
533
534         wake_up_all(&request->execute);
535 }
536
537 void i915_request_submit(struct i915_request *request)
538 {
539         struct intel_engine_cs *engine = request->engine;
540         unsigned long flags;
541
542         /* Will be called from irq-context when using foreign fences. */
543         spin_lock_irqsave(&engine->timeline->lock, flags);
544
545         __i915_request_submit(request);
546
547         spin_unlock_irqrestore(&engine->timeline->lock, flags);
548 }
549
550 void __i915_request_unsubmit(struct i915_request *request)
551 {
552         struct intel_engine_cs *engine = request->engine;
553         struct intel_timeline *timeline;
554
555         GEM_TRACE("%s fence %llx:%d <- global_seqno %d\n",
556                   request->engine->name,
557                   request->fence.context, request->fence.seqno,
558                   request->global_seqno);
559
560         GEM_BUG_ON(!irqs_disabled());
561         lockdep_assert_held(&engine->timeline->lock);
562
563         /*
564          * Only unwind in reverse order, required so that the per-context list
565          * is kept in seqno/ring order.
566          */
567         GEM_BUG_ON(!request->global_seqno);
568         GEM_BUG_ON(request->global_seqno != engine->timeline->seqno);
569         GEM_BUG_ON(i915_seqno_passed(intel_engine_get_seqno(engine),
570                                      request->global_seqno));
571         engine->timeline->seqno--;
572
573         /* We may be recursing from the signal callback of another i915 fence */
574         spin_lock_nested(&request->lock, SINGLE_DEPTH_NESTING);
575         request->global_seqno = 0;
576         if (test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT, &request->fence.flags))
577                 intel_engine_cancel_signaling(request);
578         spin_unlock(&request->lock);
579
580         /* Transfer back from the global per-engine timeline to per-context */
581         timeline = request->timeline;
582         GEM_BUG_ON(timeline == engine->timeline);
583
584         spin_lock(&timeline->lock);
585         list_move(&request->link, &timeline->requests);
586         spin_unlock(&timeline->lock);
587
588         /*
589          * We don't need to wake_up any waiters on request->execute, they
590          * will get woken by any other event or us re-adding this request
591          * to the engine timeline (__i915_request_submit()). The waiters
592          * should be quite adapt at finding that the request now has a new
593          * global_seqno to the one they went to sleep on.
594          */
595 }
596
597 void i915_request_unsubmit(struct i915_request *request)
598 {
599         struct intel_engine_cs *engine = request->engine;
600         unsigned long flags;
601
602         /* Will be called from irq-context when using foreign fences. */
603         spin_lock_irqsave(&engine->timeline->lock, flags);
604
605         __i915_request_unsubmit(request);
606
607         spin_unlock_irqrestore(&engine->timeline->lock, flags);
608 }
609
610 static int __i915_sw_fence_call
611 submit_notify(struct i915_sw_fence *fence, enum i915_sw_fence_notify state)
612 {
613         struct i915_request *request =
614                 container_of(fence, typeof(*request), submit);
615
616         switch (state) {
617         case FENCE_COMPLETE:
618                 trace_i915_request_submit(request);
619                 /*
620                  * We need to serialize use of the submit_request() callback
621                  * with its hotplugging performed during an emergency
622                  * i915_gem_set_wedged().  We use the RCU mechanism to mark the
623                  * critical section in order to force i915_gem_set_wedged() to
624                  * wait until the submit_request() is completed before
625                  * proceeding.
626                  */
627                 rcu_read_lock();
628                 request->engine->submit_request(request);
629                 rcu_read_unlock();
630                 break;
631
632         case FENCE_FREE:
633                 i915_request_put(request);
634                 break;
635         }
636
637         return NOTIFY_DONE;
638 }
639
640 /**
641  * i915_request_alloc - allocate a request structure
642  *
643  * @engine: engine that we wish to issue the request on.
644  * @ctx: context that the request will be associated with.
645  *
646  * Returns a pointer to the allocated request if successful,
647  * or an error code if not.
648  */
649 struct i915_request *
650 i915_request_alloc(struct intel_engine_cs *engine, struct i915_gem_context *ctx)
651 {
652         struct drm_i915_private *i915 = engine->i915;
653         struct i915_request *rq;
654         struct intel_ring *ring;
655         int ret;
656
657         lockdep_assert_held(&i915->drm.struct_mutex);
658
659         /*
660          * Preempt contexts are reserved for exclusive use to inject a
661          * preemption context switch. They are never to be used for any trivial
662          * request!
663          */
664         GEM_BUG_ON(ctx == i915->preempt_context);
665
666         /*
667          * ABI: Before userspace accesses the GPU (e.g. execbuffer), report
668          * EIO if the GPU is already wedged.
669          */
670         if (i915_terminally_wedged(&i915->gpu_error))
671                 return ERR_PTR(-EIO);
672
673         /*
674          * Pinning the contexts may generate requests in order to acquire
675          * GGTT space, so do this first before we reserve a seqno for
676          * ourselves.
677          */
678         ring = engine->context_pin(engine, ctx);
679         if (IS_ERR(ring))
680                 return ERR_CAST(ring);
681         GEM_BUG_ON(!ring);
682
683         ret = reserve_engine(engine);
684         if (ret)
685                 goto err_unpin;
686
687         ret = intel_ring_wait_for_space(ring, MIN_SPACE_FOR_ADD_REQUEST);
688         if (ret)
689                 goto err_unreserve;
690
691         /* Move the oldest request to the slab-cache (if not in use!) */
692         rq = list_first_entry_or_null(&engine->timeline->requests,
693                                       typeof(*rq), link);
694         if (rq && i915_request_completed(rq))
695                 i915_request_retire(rq);
696
697         /*
698          * Beware: Dragons be flying overhead.
699          *
700          * We use RCU to look up requests in flight. The lookups may
701          * race with the request being allocated from the slab freelist.
702          * That is the request we are writing to here, may be in the process
703          * of being read by __i915_gem_active_get_rcu(). As such,
704          * we have to be very careful when overwriting the contents. During
705          * the RCU lookup, we change chase the request->engine pointer,
706          * read the request->global_seqno and increment the reference count.
707          *
708          * The reference count is incremented atomically. If it is zero,
709          * the lookup knows the request is unallocated and complete. Otherwise,
710          * it is either still in use, or has been reallocated and reset
711          * with dma_fence_init(). This increment is safe for release as we
712          * check that the request we have a reference to and matches the active
713          * request.
714          *
715          * Before we increment the refcount, we chase the request->engine
716          * pointer. We must not call kmem_cache_zalloc() or else we set
717          * that pointer to NULL and cause a crash during the lookup. If
718          * we see the request is completed (based on the value of the
719          * old engine and seqno), the lookup is complete and reports NULL.
720          * If we decide the request is not completed (new engine or seqno),
721          * then we grab a reference and double check that it is still the
722          * active request - which it won't be and restart the lookup.
723          *
724          * Do not use kmem_cache_zalloc() here!
725          */
726         rq = kmem_cache_alloc(i915->requests,
727                               GFP_KERNEL | __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
728         if (unlikely(!rq)) {
729                 /* Ratelimit ourselves to prevent oom from malicious clients */
730                 ret = i915_gem_wait_for_idle(i915,
731                                              I915_WAIT_LOCKED |
732                                              I915_WAIT_INTERRUPTIBLE);
733                 if (ret)
734                         goto err_unreserve;
735
736                 /*
737                  * We've forced the client to stall and catch up with whatever
738                  * backlog there might have been. As we are assuming that we
739                  * caused the mempressure, now is an opportune time to
740                  * recover as much memory from the request pool as is possible.
741                  * Having already penalized the client to stall, we spend
742                  * a little extra time to re-optimise page allocation.
743                  */
744                 kmem_cache_shrink(i915->requests);
745                 rcu_barrier(); /* Recover the TYPESAFE_BY_RCU pages */
746
747                 rq = kmem_cache_alloc(i915->requests, GFP_KERNEL);
748                 if (!rq) {
749                         ret = -ENOMEM;
750                         goto err_unreserve;
751                 }
752         }
753
754         rq->timeline = i915_gem_context_lookup_timeline(ctx, engine);
755         GEM_BUG_ON(rq->timeline == engine->timeline);
756
757         spin_lock_init(&rq->lock);
758         dma_fence_init(&rq->fence,
759                        &i915_fence_ops,
760                        &rq->lock,
761                        rq->timeline->fence_context,
762                        timeline_get_seqno(rq->timeline));
763
764         /* We bump the ref for the fence chain */
765         i915_sw_fence_init(&i915_request_get(rq)->submit, submit_notify);
766         init_waitqueue_head(&rq->execute);
767
768         i915_priotree_init(&rq->priotree);
769
770         INIT_LIST_HEAD(&rq->active_list);
771         rq->i915 = i915;
772         rq->engine = engine;
773         rq->ctx = ctx;
774         rq->ring = ring;
775
776         /* No zalloc, must clear what we need by hand */
777         rq->global_seqno = 0;
778         rq->signaling.wait.seqno = 0;
779         rq->file_priv = NULL;
780         rq->batch = NULL;
781         rq->capture_list = NULL;
782         rq->waitboost = false;
783
784         /*
785          * Reserve space in the ring buffer for all the commands required to
786          * eventually emit this request. This is to guarantee that the
787          * i915_request_add() call can't fail. Note that the reserve may need
788          * to be redone if the request is not actually submitted straight
789          * away, e.g. because a GPU scheduler has deferred it.
790          */
791         rq->reserved_space = MIN_SPACE_FOR_ADD_REQUEST;
792         GEM_BUG_ON(rq->reserved_space < engine->emit_breadcrumb_sz);
793
794         /*
795          * Record the position of the start of the request so that
796          * should we detect the updated seqno part-way through the
797          * GPU processing the request, we never over-estimate the
798          * position of the head.
799          */
800         rq->head = rq->ring->emit;
801
802         /* Unconditionally invalidate GPU caches and TLBs. */
803         ret = engine->emit_flush(rq, EMIT_INVALIDATE);
804         if (ret)
805                 goto err_unwind;
806
807         ret = engine->request_alloc(rq);
808         if (ret)
809                 goto err_unwind;
810
811         /* Check that we didn't interrupt ourselves with a new request */
812         GEM_BUG_ON(rq->timeline->seqno != rq->fence.seqno);
813         return rq;
814
815 err_unwind:
816         rq->ring->emit = rq->head;
817
818         /* Make sure we didn't add ourselves to external state before freeing */
819         GEM_BUG_ON(!list_empty(&rq->active_list));
820         GEM_BUG_ON(!list_empty(&rq->priotree.signalers_list));
821         GEM_BUG_ON(!list_empty(&rq->priotree.waiters_list));
822
823         kmem_cache_free(i915->requests, rq);
824 err_unreserve:
825         unreserve_engine(engine);
826 err_unpin:
827         engine->context_unpin(engine, ctx);
828         return ERR_PTR(ret);
829 }
830
831 static int
832 i915_request_await_request(struct i915_request *to, struct i915_request *from)
833 {
834         int ret;
835
836         GEM_BUG_ON(to == from);
837         GEM_BUG_ON(to->timeline == from->timeline);
838
839         if (i915_request_completed(from))
840                 return 0;
841
842         if (to->engine->schedule) {
843                 ret = i915_priotree_add_dependency(to->i915,
844                                                    &to->priotree,
845                                                    &from->priotree);
846                 if (ret < 0)
847                         return ret;
848         }
849
850         if (to->engine == from->engine) {
851                 ret = i915_sw_fence_await_sw_fence_gfp(&to->submit,
852                                                        &from->submit,
853                                                        I915_FENCE_GFP);
854                 return ret < 0 ? ret : 0;
855         }
856
857         if (to->engine->semaphore.sync_to) {
858                 u32 seqno;
859
860                 GEM_BUG_ON(!from->engine->semaphore.signal);
861
862                 seqno = i915_request_global_seqno(from);
863                 if (!seqno)
864                         goto await_dma_fence;
865
866                 if (seqno <= to->timeline->global_sync[from->engine->id])
867                         return 0;
868
869                 trace_i915_gem_ring_sync_to(to, from);
870                 ret = to->engine->semaphore.sync_to(to, from);
871                 if (ret)
872                         return ret;
873
874                 to->timeline->global_sync[from->engine->id] = seqno;
875                 return 0;
876         }
877
878 await_dma_fence:
879         ret = i915_sw_fence_await_dma_fence(&to->submit,
880                                             &from->fence, 0,
881                                             I915_FENCE_GFP);
882         return ret < 0 ? ret : 0;
883 }
884
885 int
886 i915_request_await_dma_fence(struct i915_request *rq, struct dma_fence *fence)
887 {
888         struct dma_fence **child = &fence;
889         unsigned int nchild = 1;
890         int ret;
891
892         /*
893          * Note that if the fence-array was created in signal-on-any mode,
894          * we should *not* decompose it into its individual fences. However,
895          * we don't currently store which mode the fence-array is operating
896          * in. Fortunately, the only user of signal-on-any is private to
897          * amdgpu and we should not see any incoming fence-array from
898          * sync-file being in signal-on-any mode.
899          */
900         if (dma_fence_is_array(fence)) {
901                 struct dma_fence_array *array = to_dma_fence_array(fence);
902
903                 child = array->fences;
904                 nchild = array->num_fences;
905                 GEM_BUG_ON(!nchild);
906         }
907
908         do {
909                 fence = *child++;
910                 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
911                         continue;
912
913                 /*
914                  * Requests on the same timeline are explicitly ordered, along
915                  * with their dependencies, by i915_request_add() which ensures
916                  * that requests are submitted in-order through each ring.
917                  */
918                 if (fence->context == rq->fence.context)
919                         continue;
920
921                 /* Squash repeated waits to the same timelines */
922                 if (fence->context != rq->i915->mm.unordered_timeline &&
923                     intel_timeline_sync_is_later(rq->timeline, fence))
924                         continue;
925
926                 if (dma_fence_is_i915(fence))
927                         ret = i915_request_await_request(rq, to_request(fence));
928                 else
929                         ret = i915_sw_fence_await_dma_fence(&rq->submit, fence,
930                                                             I915_FENCE_TIMEOUT,
931                                                             I915_FENCE_GFP);
932                 if (ret < 0)
933                         return ret;
934
935                 /* Record the latest fence used against each timeline */
936                 if (fence->context != rq->i915->mm.unordered_timeline)
937                         intel_timeline_sync_set(rq->timeline, fence);
938         } while (--nchild);
939
940         return 0;
941 }
942
943 /**
944  * i915_request_await_object - set this request to (async) wait upon a bo
945  * @to: request we are wishing to use
946  * @obj: object which may be in use on another ring.
947  * @write: whether the wait is on behalf of a writer
948  *
949  * This code is meant to abstract object synchronization with the GPU.
950  * Conceptually we serialise writes between engines inside the GPU.
951  * We only allow one engine to write into a buffer at any time, but
952  * multiple readers. To ensure each has a coherent view of memory, we must:
953  *
954  * - If there is an outstanding write request to the object, the new
955  *   request must wait for it to complete (either CPU or in hw, requests
956  *   on the same ring will be naturally ordered).
957  *
958  * - If we are a write request (pending_write_domain is set), the new
959  *   request must wait for outstanding read requests to complete.
960  *
961  * Returns 0 if successful, else propagates up the lower layer error.
962  */
963 int
964 i915_request_await_object(struct i915_request *to,
965                           struct drm_i915_gem_object *obj,
966                           bool write)
967 {
968         struct dma_fence *excl;
969         int ret = 0;
970
971         if (write) {
972                 struct dma_fence **shared;
973                 unsigned int count, i;
974
975                 ret = reservation_object_get_fences_rcu(obj->resv,
976                                                         &excl, &count, &shared);
977                 if (ret)
978                         return ret;
979
980                 for (i = 0; i < count; i++) {
981                         ret = i915_request_await_dma_fence(to, shared[i]);
982                         if (ret)
983                                 break;
984
985                         dma_fence_put(shared[i]);
986                 }
987
988                 for (; i < count; i++)
989                         dma_fence_put(shared[i]);
990                 kfree(shared);
991         } else {
992                 excl = reservation_object_get_excl_rcu(obj->resv);
993         }
994
995         if (excl) {
996                 if (ret == 0)
997                         ret = i915_request_await_dma_fence(to, excl);
998
999                 dma_fence_put(excl);
1000         }
1001
1002         return ret;
1003 }
1004
1005 /*
1006  * NB: This function is not allowed to fail. Doing so would mean the the
1007  * request is not being tracked for completion but the work itself is
1008  * going to happen on the hardware. This would be a Bad Thing(tm).
1009  */
1010 void __i915_request_add(struct i915_request *request, bool flush_caches)
1011 {
1012         struct intel_engine_cs *engine = request->engine;
1013         struct intel_ring *ring = request->ring;
1014         struct intel_timeline *timeline = request->timeline;
1015         struct i915_request *prev;
1016         u32 *cs;
1017         int err;
1018
1019         GEM_TRACE("%s fence %llx:%d\n",
1020                   engine->name, request->fence.context, request->fence.seqno);
1021
1022         lockdep_assert_held(&request->i915->drm.struct_mutex);
1023         trace_i915_request_add(request);
1024
1025         /*
1026          * Make sure that no request gazumped us - if it was allocated after
1027          * our i915_request_alloc() and called __i915_request_add() before
1028          * us, the timeline will hold its seqno which is later than ours.
1029          */
1030         GEM_BUG_ON(timeline->seqno != request->fence.seqno);
1031
1032         /*
1033          * To ensure that this call will not fail, space for its emissions
1034          * should already have been reserved in the ring buffer. Let the ring
1035          * know that it is time to use that space up.
1036          */
1037         request->reserved_space = 0;
1038
1039         /*
1040          * Emit any outstanding flushes - execbuf can fail to emit the flush
1041          * after having emitted the batchbuffer command. Hence we need to fix
1042          * things up similar to emitting the lazy request. The difference here
1043          * is that the flush _must_ happen before the next request, no matter
1044          * what.
1045          */
1046         if (flush_caches) {
1047                 err = engine->emit_flush(request, EMIT_FLUSH);
1048
1049                 /* Not allowed to fail! */
1050                 WARN(err, "engine->emit_flush() failed: %d!\n", err);
1051         }
1052
1053         /*
1054          * Record the position of the start of the breadcrumb so that
1055          * should we detect the updated seqno part-way through the
1056          * GPU processing the request, we never over-estimate the
1057          * position of the ring's HEAD.
1058          */
1059         cs = intel_ring_begin(request, engine->emit_breadcrumb_sz);
1060         GEM_BUG_ON(IS_ERR(cs));
1061         request->postfix = intel_ring_offset(request, cs);
1062
1063         /*
1064          * Seal the request and mark it as pending execution. Note that
1065          * we may inspect this state, without holding any locks, during
1066          * hangcheck. Hence we apply the barrier to ensure that we do not
1067          * see a more recent value in the hws than we are tracking.
1068          */
1069
1070         prev = i915_gem_active_raw(&timeline->last_request,
1071                                    &request->i915->drm.struct_mutex);
1072         if (prev && !i915_request_completed(prev)) {
1073                 i915_sw_fence_await_sw_fence(&request->submit, &prev->submit,
1074                                              &request->submitq);
1075                 if (engine->schedule)
1076                         __i915_priotree_add_dependency(&request->priotree,
1077                                                        &prev->priotree,
1078                                                        &request->dep,
1079                                                        0);
1080         }
1081
1082         spin_lock_irq(&timeline->lock);
1083         list_add_tail(&request->link, &timeline->requests);
1084         spin_unlock_irq(&timeline->lock);
1085
1086         GEM_BUG_ON(timeline->seqno != request->fence.seqno);
1087         i915_gem_active_set(&timeline->last_request, request);
1088
1089         list_add_tail(&request->ring_link, &ring->request_list);
1090         request->emitted_jiffies = jiffies;
1091
1092         /*
1093          * Let the backend know a new request has arrived that may need
1094          * to adjust the existing execution schedule due to a high priority
1095          * request - i.e. we may want to preempt the current request in order
1096          * to run a high priority dependency chain *before* we can execute this
1097          * request.
1098          *
1099          * This is called before the request is ready to run so that we can
1100          * decide whether to preempt the entire chain so that it is ready to
1101          * run at the earliest possible convenience.
1102          */
1103         rcu_read_lock();
1104         if (engine->schedule)
1105                 engine->schedule(request, request->ctx->priority);
1106         rcu_read_unlock();
1107
1108         local_bh_disable();
1109         i915_sw_fence_commit(&request->submit);
1110         local_bh_enable(); /* Kick the execlists tasklet if just scheduled */
1111
1112         /*
1113          * In typical scenarios, we do not expect the previous request on
1114          * the timeline to be still tracked by timeline->last_request if it
1115          * has been completed. If the completed request is still here, that
1116          * implies that request retirement is a long way behind submission,
1117          * suggesting that we haven't been retiring frequently enough from
1118          * the combination of retire-before-alloc, waiters and the background
1119          * retirement worker. So if the last request on this timeline was
1120          * already completed, do a catch up pass, flushing the retirement queue
1121          * up to this client. Since we have now moved the heaviest operations
1122          * during retirement onto secondary workers, such as freeing objects
1123          * or contexts, retiring a bunch of requests is mostly list management
1124          * (and cache misses), and so we should not be overly penalizing this
1125          * client by performing excess work, though we may still performing
1126          * work on behalf of others -- but instead we should benefit from
1127          * improved resource management. (Well, that's the theory at least.)
1128          */
1129         if (prev && i915_request_completed(prev))
1130                 i915_request_retire_upto(prev);
1131 }
1132
1133 static unsigned long local_clock_us(unsigned int *cpu)
1134 {
1135         unsigned long t;
1136
1137         /*
1138          * Cheaply and approximately convert from nanoseconds to microseconds.
1139          * The result and subsequent calculations are also defined in the same
1140          * approximate microseconds units. The principal source of timing
1141          * error here is from the simple truncation.
1142          *
1143          * Note that local_clock() is only defined wrt to the current CPU;
1144          * the comparisons are no longer valid if we switch CPUs. Instead of
1145          * blocking preemption for the entire busywait, we can detect the CPU
1146          * switch and use that as indicator of system load and a reason to
1147          * stop busywaiting, see busywait_stop().
1148          */
1149         *cpu = get_cpu();
1150         t = local_clock() >> 10;
1151         put_cpu();
1152
1153         return t;
1154 }
1155
1156 static bool busywait_stop(unsigned long timeout, unsigned int cpu)
1157 {
1158         unsigned int this_cpu;
1159
1160         if (time_after(local_clock_us(&this_cpu), timeout))
1161                 return true;
1162
1163         return this_cpu != cpu;
1164 }
1165
1166 static bool __i915_spin_request(const struct i915_request *rq,
1167                                 u32 seqno, int state, unsigned long timeout_us)
1168 {
1169         struct intel_engine_cs *engine = rq->engine;
1170         unsigned int irq, cpu;
1171
1172         GEM_BUG_ON(!seqno);
1173
1174         /*
1175          * Only wait for the request if we know it is likely to complete.
1176          *
1177          * We don't track the timestamps around requests, nor the average
1178          * request length, so we do not have a good indicator that this
1179          * request will complete within the timeout. What we do know is the
1180          * order in which requests are executed by the engine and so we can
1181          * tell if the request has started. If the request hasn't started yet,
1182          * it is a fair assumption that it will not complete within our
1183          * relatively short timeout.
1184          */
1185         if (!i915_seqno_passed(intel_engine_get_seqno(engine), seqno - 1))
1186                 return false;
1187
1188         /*
1189          * When waiting for high frequency requests, e.g. during synchronous
1190          * rendering split between the CPU and GPU, the finite amount of time
1191          * required to set up the irq and wait upon it limits the response
1192          * rate. By busywaiting on the request completion for a short while we
1193          * can service the high frequency waits as quick as possible. However,
1194          * if it is a slow request, we want to sleep as quickly as possible.
1195          * The tradeoff between waiting and sleeping is roughly the time it
1196          * takes to sleep on a request, on the order of a microsecond.
1197          */
1198
1199         irq = atomic_read(&engine->irq_count);
1200         timeout_us += local_clock_us(&cpu);
1201         do {
1202                 if (i915_seqno_passed(intel_engine_get_seqno(engine), seqno))
1203                         return seqno == i915_request_global_seqno(rq);
1204
1205                 /*
1206                  * Seqno are meant to be ordered *before* the interrupt. If
1207                  * we see an interrupt without a corresponding seqno advance,
1208                  * assume we won't see one in the near future but require
1209                  * the engine->seqno_barrier() to fixup coherency.
1210                  */
1211                 if (atomic_read(&engine->irq_count) != irq)
1212                         break;
1213
1214                 if (signal_pending_state(state, current))
1215                         break;
1216
1217                 if (busywait_stop(timeout_us, cpu))
1218                         break;
1219
1220                 cpu_relax();
1221         } while (!need_resched());
1222
1223         return false;
1224 }
1225
1226 static bool __i915_wait_request_check_and_reset(struct i915_request *request)
1227 {
1228         if (likely(!i915_reset_handoff(&request->i915->gpu_error)))
1229                 return false;
1230
1231         __set_current_state(TASK_RUNNING);
1232         i915_reset(request->i915);
1233         return true;
1234 }
1235
1236 /**
1237  * i915_request_wait - wait until execution of request has finished
1238  * @rq: the request to wait upon
1239  * @flags: how to wait
1240  * @timeout: how long to wait in jiffies
1241  *
1242  * i915_request_wait() waits for the request to be completed, for a
1243  * maximum of @timeout jiffies (with MAX_SCHEDULE_TIMEOUT implying an
1244  * unbounded wait).
1245  *
1246  * If the caller holds the struct_mutex, the caller must pass I915_WAIT_LOCKED
1247  * in via the flags, and vice versa if the struct_mutex is not held, the caller
1248  * must not specify that the wait is locked.
1249  *
1250  * Returns the remaining time (in jiffies) if the request completed, which may
1251  * be zero or -ETIME if the request is unfinished after the timeout expires.
1252  * May return -EINTR is called with I915_WAIT_INTERRUPTIBLE and a signal is
1253  * pending before the request completes.
1254  */
1255 long i915_request_wait(struct i915_request *rq,
1256                        unsigned int flags,
1257                        long timeout)
1258 {
1259         const int state = flags & I915_WAIT_INTERRUPTIBLE ?
1260                 TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE;
1261         wait_queue_head_t *errq = &rq->i915->gpu_error.wait_queue;
1262         DEFINE_WAIT_FUNC(reset, default_wake_function);
1263         DEFINE_WAIT_FUNC(exec, default_wake_function);
1264         struct intel_wait wait;
1265
1266         might_sleep();
1267 #if IS_ENABLED(CONFIG_LOCKDEP)
1268         GEM_BUG_ON(debug_locks &&
1269                    !!lockdep_is_held(&rq->i915->drm.struct_mutex) !=
1270                    !!(flags & I915_WAIT_LOCKED));
1271 #endif
1272         GEM_BUG_ON(timeout < 0);
1273
1274         if (i915_request_completed(rq))
1275                 return timeout;
1276
1277         if (!timeout)
1278                 return -ETIME;
1279
1280         trace_i915_request_wait_begin(rq, flags);
1281
1282         add_wait_queue(&rq->execute, &exec);
1283         if (flags & I915_WAIT_LOCKED)
1284                 add_wait_queue(errq, &reset);
1285
1286         intel_wait_init(&wait, rq);
1287
1288 restart:
1289         do {
1290                 set_current_state(state);
1291                 if (intel_wait_update_request(&wait, rq))
1292                         break;
1293
1294                 if (flags & I915_WAIT_LOCKED &&
1295                     __i915_wait_request_check_and_reset(rq))
1296                         continue;
1297
1298                 if (signal_pending_state(state, current)) {
1299                         timeout = -ERESTARTSYS;
1300                         goto complete;
1301                 }
1302
1303                 if (!timeout) {
1304                         timeout = -ETIME;
1305                         goto complete;
1306                 }
1307
1308                 timeout = io_schedule_timeout(timeout);
1309         } while (1);
1310
1311         GEM_BUG_ON(!intel_wait_has_seqno(&wait));
1312         GEM_BUG_ON(!i915_sw_fence_signaled(&rq->submit));
1313
1314         /* Optimistic short spin before touching IRQs */
1315         if (__i915_spin_request(rq, wait.seqno, state, 5))
1316                 goto complete;
1317
1318         set_current_state(state);
1319         if (intel_engine_add_wait(rq->engine, &wait))
1320                 /*
1321                  * In order to check that we haven't missed the interrupt
1322                  * as we enabled it, we need to kick ourselves to do a
1323                  * coherent check on the seqno before we sleep.
1324                  */
1325                 goto wakeup;
1326
1327         if (flags & I915_WAIT_LOCKED)
1328                 __i915_wait_request_check_and_reset(rq);
1329
1330         for (;;) {
1331                 if (signal_pending_state(state, current)) {
1332                         timeout = -ERESTARTSYS;
1333                         break;
1334                 }
1335
1336                 if (!timeout) {
1337                         timeout = -ETIME;
1338                         break;
1339                 }
1340
1341                 timeout = io_schedule_timeout(timeout);
1342
1343                 if (intel_wait_complete(&wait) &&
1344                     intel_wait_check_request(&wait, rq))
1345                         break;
1346
1347                 set_current_state(state);
1348
1349 wakeup:
1350                 /*
1351                  * Carefully check if the request is complete, giving time
1352                  * for the seqno to be visible following the interrupt.
1353                  * We also have to check in case we are kicked by the GPU
1354                  * reset in order to drop the struct_mutex.
1355                  */
1356                 if (__i915_request_irq_complete(rq))
1357                         break;
1358
1359                 /*
1360                  * If the GPU is hung, and we hold the lock, reset the GPU
1361                  * and then check for completion. On a full reset, the engine's
1362                  * HW seqno will be advanced passed us and we are complete.
1363                  * If we do a partial reset, we have to wait for the GPU to
1364                  * resume and update the breadcrumb.
1365                  *
1366                  * If we don't hold the mutex, we can just wait for the worker
1367                  * to come along and update the breadcrumb (either directly
1368                  * itself, or indirectly by recovering the GPU).
1369                  */
1370                 if (flags & I915_WAIT_LOCKED &&
1371                     __i915_wait_request_check_and_reset(rq))
1372                         continue;
1373
1374                 /* Only spin if we know the GPU is processing this request */
1375                 if (__i915_spin_request(rq, wait.seqno, state, 2))
1376                         break;
1377
1378                 if (!intel_wait_check_request(&wait, rq)) {
1379                         intel_engine_remove_wait(rq->engine, &wait);
1380                         goto restart;
1381                 }
1382         }
1383
1384         intel_engine_remove_wait(rq->engine, &wait);
1385 complete:
1386         __set_current_state(TASK_RUNNING);
1387         if (flags & I915_WAIT_LOCKED)
1388                 remove_wait_queue(errq, &reset);
1389         remove_wait_queue(&rq->execute, &exec);
1390         trace_i915_request_wait_end(rq);
1391
1392         return timeout;
1393 }
1394
1395 static void engine_retire_requests(struct intel_engine_cs *engine)
1396 {
1397         struct i915_request *request, *next;
1398         u32 seqno = intel_engine_get_seqno(engine);
1399         LIST_HEAD(retire);
1400
1401         spin_lock_irq(&engine->timeline->lock);
1402         list_for_each_entry_safe(request, next,
1403                                  &engine->timeline->requests, link) {
1404                 if (!i915_seqno_passed(seqno, request->global_seqno))
1405                         break;
1406
1407                 list_move_tail(&request->link, &retire);
1408         }
1409         spin_unlock_irq(&engine->timeline->lock);
1410
1411         list_for_each_entry_safe(request, next, &retire, link)
1412                 i915_request_retire(request);
1413 }
1414
1415 void i915_retire_requests(struct drm_i915_private *i915)
1416 {
1417         struct intel_engine_cs *engine;
1418         enum intel_engine_id id;
1419
1420         lockdep_assert_held(&i915->drm.struct_mutex);
1421
1422         if (!i915->gt.active_requests)
1423                 return;
1424
1425         for_each_engine(engine, i915, id)
1426                 engine_retire_requests(engine);
1427 }
1428
1429 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
1430 #include "selftests/mock_request.c"
1431 #include "selftests/i915_request.c"
1432 #endif