]> Git Repo - J-linux.git/blob - drivers/gpu/drm/i915/i915_request.c
Merge v5.16-rc5 into drm-next
[J-linux.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/dma-fence-array.h>
26 #include <linux/dma-fence-chain.h>
27 #include <linux/irq_work.h>
28 #include <linux/prefetch.h>
29 #include <linux/sched.h>
30 #include <linux/sched/clock.h>
31 #include <linux/sched/signal.h>
32 #include <linux/sched/mm.h>
33
34 #include "gem/i915_gem_context.h"
35 #include "gt/intel_breadcrumbs.h"
36 #include "gt/intel_context.h"
37 #include "gt/intel_engine.h"
38 #include "gt/intel_engine_heartbeat.h"
39 #include "gt/intel_gpu_commands.h"
40 #include "gt/intel_reset.h"
41 #include "gt/intel_ring.h"
42 #include "gt/intel_rps.h"
43
44 #include "i915_active.h"
45 #include "i915_drv.h"
46 #include "i915_trace.h"
47 #include "intel_pm.h"
48
49 struct execute_cb {
50         struct irq_work work;
51         struct i915_sw_fence *fence;
52         struct i915_request *signal;
53 };
54
55 static struct kmem_cache *slab_requests;
56 static struct kmem_cache *slab_execute_cbs;
57
58 static const char *i915_fence_get_driver_name(struct dma_fence *fence)
59 {
60         return dev_name(to_request(fence)->engine->i915->drm.dev);
61 }
62
63 static const char *i915_fence_get_timeline_name(struct dma_fence *fence)
64 {
65         const struct i915_gem_context *ctx;
66
67         /*
68          * The timeline struct (as part of the ppgtt underneath a context)
69          * may be freed when the request is no longer in use by the GPU.
70          * We could extend the life of a context to beyond that of all
71          * fences, possibly keeping the hw resource around indefinitely,
72          * or we just give them a false name. Since
73          * dma_fence_ops.get_timeline_name is a debug feature, the occasional
74          * lie seems justifiable.
75          */
76         if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
77                 return "signaled";
78
79         ctx = i915_request_gem_context(to_request(fence));
80         if (!ctx)
81                 return "[" DRIVER_NAME "]";
82
83         return ctx->name;
84 }
85
86 static bool i915_fence_signaled(struct dma_fence *fence)
87 {
88         return i915_request_completed(to_request(fence));
89 }
90
91 static bool i915_fence_enable_signaling(struct dma_fence *fence)
92 {
93         return i915_request_enable_breadcrumb(to_request(fence));
94 }
95
96 static signed long i915_fence_wait(struct dma_fence *fence,
97                                    bool interruptible,
98                                    signed long timeout)
99 {
100         return i915_request_wait_timeout(to_request(fence),
101                                          interruptible | I915_WAIT_PRIORITY,
102                                          timeout);
103 }
104
105 struct kmem_cache *i915_request_slab_cache(void)
106 {
107         return slab_requests;
108 }
109
110 static void i915_fence_release(struct dma_fence *fence)
111 {
112         struct i915_request *rq = to_request(fence);
113
114         GEM_BUG_ON(rq->guc_prio != GUC_PRIO_INIT &&
115                    rq->guc_prio != GUC_PRIO_FINI);
116
117         i915_request_free_capture_list(fetch_and_zero(&rq->capture_list));
118         if (i915_vma_snapshot_present(&rq->batch_snapshot))
119                 i915_vma_snapshot_put_onstack(&rq->batch_snapshot);
120
121         /*
122          * The request is put onto a RCU freelist (i.e. the address
123          * is immediately reused), mark the fences as being freed now.
124          * Otherwise the debugobjects for the fences are only marked as
125          * freed when the slab cache itself is freed, and so we would get
126          * caught trying to reuse dead objects.
127          */
128         i915_sw_fence_fini(&rq->submit);
129         i915_sw_fence_fini(&rq->semaphore);
130
131         /*
132          * Keep one request on each engine for reserved use under mempressure,
133          * do not use with virtual engines as this really is only needed for
134          * kernel contexts.
135          */
136         if (!intel_engine_is_virtual(rq->engine) &&
137             !cmpxchg(&rq->engine->request_pool, NULL, rq)) {
138                 intel_context_put(rq->context);
139                 return;
140         }
141
142         intel_context_put(rq->context);
143
144         kmem_cache_free(slab_requests, rq);
145 }
146
147 const struct dma_fence_ops i915_fence_ops = {
148         .get_driver_name = i915_fence_get_driver_name,
149         .get_timeline_name = i915_fence_get_timeline_name,
150         .enable_signaling = i915_fence_enable_signaling,
151         .signaled = i915_fence_signaled,
152         .wait = i915_fence_wait,
153         .release = i915_fence_release,
154 };
155
156 static void irq_execute_cb(struct irq_work *wrk)
157 {
158         struct execute_cb *cb = container_of(wrk, typeof(*cb), work);
159
160         i915_sw_fence_complete(cb->fence);
161         kmem_cache_free(slab_execute_cbs, cb);
162 }
163
164 static __always_inline void
165 __notify_execute_cb(struct i915_request *rq, bool (*fn)(struct irq_work *wrk))
166 {
167         struct execute_cb *cb, *cn;
168
169         if (llist_empty(&rq->execute_cb))
170                 return;
171
172         llist_for_each_entry_safe(cb, cn,
173                                   llist_del_all(&rq->execute_cb),
174                                   work.node.llist)
175                 fn(&cb->work);
176 }
177
178 static void __notify_execute_cb_irq(struct i915_request *rq)
179 {
180         __notify_execute_cb(rq, irq_work_queue);
181 }
182
183 static bool irq_work_imm(struct irq_work *wrk)
184 {
185         wrk->func(wrk);
186         return false;
187 }
188
189 void i915_request_notify_execute_cb_imm(struct i915_request *rq)
190 {
191         __notify_execute_cb(rq, irq_work_imm);
192 }
193
194 static void __i915_request_fill(struct i915_request *rq, u8 val)
195 {
196         void *vaddr = rq->ring->vaddr;
197         u32 head;
198
199         head = rq->infix;
200         if (rq->postfix < head) {
201                 memset(vaddr + head, val, rq->ring->size - head);
202                 head = 0;
203         }
204         memset(vaddr + head, val, rq->postfix - head);
205 }
206
207 /**
208  * i915_request_active_engine
209  * @rq: request to inspect
210  * @active: pointer in which to return the active engine
211  *
212  * Fills the currently active engine to the @active pointer if the request
213  * is active and still not completed.
214  *
215  * Returns true if request was active or false otherwise.
216  */
217 bool
218 i915_request_active_engine(struct i915_request *rq,
219                            struct intel_engine_cs **active)
220 {
221         struct intel_engine_cs *engine, *locked;
222         bool ret = false;
223
224         /*
225          * Serialise with __i915_request_submit() so that it sees
226          * is-banned?, or we know the request is already inflight.
227          *
228          * Note that rq->engine is unstable, and so we double
229          * check that we have acquired the lock on the final engine.
230          */
231         locked = READ_ONCE(rq->engine);
232         spin_lock_irq(&locked->sched_engine->lock);
233         while (unlikely(locked != (engine = READ_ONCE(rq->engine)))) {
234                 spin_unlock(&locked->sched_engine->lock);
235                 locked = engine;
236                 spin_lock(&locked->sched_engine->lock);
237         }
238
239         if (i915_request_is_active(rq)) {
240                 if (!__i915_request_is_complete(rq))
241                         *active = locked;
242                 ret = true;
243         }
244
245         spin_unlock_irq(&locked->sched_engine->lock);
246
247         return ret;
248 }
249
250 static void __rq_init_watchdog(struct i915_request *rq)
251 {
252         rq->watchdog.timer.function = NULL;
253 }
254
255 static enum hrtimer_restart __rq_watchdog_expired(struct hrtimer *hrtimer)
256 {
257         struct i915_request *rq =
258                 container_of(hrtimer, struct i915_request, watchdog.timer);
259         struct intel_gt *gt = rq->engine->gt;
260
261         if (!i915_request_completed(rq)) {
262                 if (llist_add(&rq->watchdog.link, &gt->watchdog.list))
263                         schedule_work(&gt->watchdog.work);
264         } else {
265                 i915_request_put(rq);
266         }
267
268         return HRTIMER_NORESTART;
269 }
270
271 static void __rq_arm_watchdog(struct i915_request *rq)
272 {
273         struct i915_request_watchdog *wdg = &rq->watchdog;
274         struct intel_context *ce = rq->context;
275
276         if (!ce->watchdog.timeout_us)
277                 return;
278
279         i915_request_get(rq);
280
281         hrtimer_init(&wdg->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
282         wdg->timer.function = __rq_watchdog_expired;
283         hrtimer_start_range_ns(&wdg->timer,
284                                ns_to_ktime(ce->watchdog.timeout_us *
285                                            NSEC_PER_USEC),
286                                NSEC_PER_MSEC,
287                                HRTIMER_MODE_REL);
288 }
289
290 static void __rq_cancel_watchdog(struct i915_request *rq)
291 {
292         struct i915_request_watchdog *wdg = &rq->watchdog;
293
294         if (wdg->timer.function && hrtimer_try_to_cancel(&wdg->timer) > 0)
295                 i915_request_put(rq);
296 }
297
298 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
299
300 /**
301  * i915_request_free_capture_list - Free a capture list
302  * @capture: Pointer to the first list item or NULL
303  *
304  */
305 void i915_request_free_capture_list(struct i915_capture_list *capture)
306 {
307         while (capture) {
308                 struct i915_capture_list *next = capture->next;
309
310                 i915_vma_snapshot_put(capture->vma_snapshot);
311                 capture = next;
312         }
313 }
314
315 #define assert_capture_list_is_null(_rq) GEM_BUG_ON((_rq)->capture_list)
316
317 #define clear_capture_list(_rq) ((_rq)->capture_list = NULL)
318
319 #else
320
321 #define i915_request_free_capture_list(_a) do {} while (0)
322
323 #define assert_capture_list_is_null(_a) do {} while (0)
324
325 #define clear_capture_list(_rq) do {} while (0)
326
327 #endif
328
329 bool i915_request_retire(struct i915_request *rq)
330 {
331         if (!__i915_request_is_complete(rq))
332                 return false;
333
334         RQ_TRACE(rq, "\n");
335
336         GEM_BUG_ON(!i915_sw_fence_signaled(&rq->submit));
337         trace_i915_request_retire(rq);
338         i915_request_mark_complete(rq);
339
340         __rq_cancel_watchdog(rq);
341
342         /*
343          * We know the GPU must have read the request to have
344          * sent us the seqno + interrupt, so use the position
345          * of tail of the request to update the last known position
346          * of the GPU head.
347          *
348          * Note this requires that we are always called in request
349          * completion order.
350          */
351         GEM_BUG_ON(!list_is_first(&rq->link,
352                                   &i915_request_timeline(rq)->requests));
353         if (IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM))
354                 /* Poison before we release our space in the ring */
355                 __i915_request_fill(rq, POISON_FREE);
356         rq->ring->head = rq->postfix;
357
358         if (!i915_request_signaled(rq)) {
359                 spin_lock_irq(&rq->lock);
360                 dma_fence_signal_locked(&rq->fence);
361                 spin_unlock_irq(&rq->lock);
362         }
363
364         if (test_and_set_bit(I915_FENCE_FLAG_BOOST, &rq->fence.flags))
365                 intel_rps_dec_waiters(&rq->engine->gt->rps);
366
367         /*
368          * We only loosely track inflight requests across preemption,
369          * and so we may find ourselves attempting to retire a _completed_
370          * request that we have removed from the HW and put back on a run
371          * queue.
372          *
373          * As we set I915_FENCE_FLAG_ACTIVE on the request, this should be
374          * after removing the breadcrumb and signaling it, so that we do not
375          * inadvertently attach the breadcrumb to a completed request.
376          */
377         rq->engine->remove_active_request(rq);
378         GEM_BUG_ON(!llist_empty(&rq->execute_cb));
379
380         __list_del_entry(&rq->link); /* poison neither prev/next (RCU walks) */
381
382         intel_context_exit(rq->context);
383         intel_context_unpin(rq->context);
384
385         i915_sched_node_fini(&rq->sched);
386         i915_request_put(rq);
387
388         return true;
389 }
390
391 void i915_request_retire_upto(struct i915_request *rq)
392 {
393         struct intel_timeline * const tl = i915_request_timeline(rq);
394         struct i915_request *tmp;
395
396         RQ_TRACE(rq, "\n");
397         GEM_BUG_ON(!__i915_request_is_complete(rq));
398
399         do {
400                 tmp = list_first_entry(&tl->requests, typeof(*tmp), link);
401                 GEM_BUG_ON(!i915_request_completed(tmp));
402         } while (i915_request_retire(tmp) && tmp != rq);
403 }
404
405 static struct i915_request * const *
406 __engine_active(struct intel_engine_cs *engine)
407 {
408         return READ_ONCE(engine->execlists.active);
409 }
410
411 static bool __request_in_flight(const struct i915_request *signal)
412 {
413         struct i915_request * const *port, *rq;
414         bool inflight = false;
415
416         if (!i915_request_is_ready(signal))
417                 return false;
418
419         /*
420          * Even if we have unwound the request, it may still be on
421          * the GPU (preempt-to-busy). If that request is inside an
422          * unpreemptible critical section, it will not be removed. Some
423          * GPU functions may even be stuck waiting for the paired request
424          * (__await_execution) to be submitted and cannot be preempted
425          * until the bond is executing.
426          *
427          * As we know that there are always preemption points between
428          * requests, we know that only the currently executing request
429          * may be still active even though we have cleared the flag.
430          * However, we can't rely on our tracking of ELSP[0] to know
431          * which request is currently active and so maybe stuck, as
432          * the tracking maybe an event behind. Instead assume that
433          * if the context is still inflight, then it is still active
434          * even if the active flag has been cleared.
435          *
436          * To further complicate matters, if there a pending promotion, the HW
437          * may either perform a context switch to the second inflight execlists,
438          * or it may switch to the pending set of execlists. In the case of the
439          * latter, it may send the ACK and we process the event copying the
440          * pending[] over top of inflight[], _overwriting_ our *active. Since
441          * this implies the HW is arbitrating and not struck in *active, we do
442          * not worry about complete accuracy, but we do require no read/write
443          * tearing of the pointer [the read of the pointer must be valid, even
444          * as the array is being overwritten, for which we require the writes
445          * to avoid tearing.]
446          *
447          * Note that the read of *execlists->active may race with the promotion
448          * of execlists->pending[] to execlists->inflight[], overwritting
449          * the value at *execlists->active. This is fine. The promotion implies
450          * that we received an ACK from the HW, and so the context is not
451          * stuck -- if we do not see ourselves in *active, the inflight status
452          * is valid. If instead we see ourselves being copied into *active,
453          * we are inflight and may signal the callback.
454          */
455         if (!intel_context_inflight(signal->context))
456                 return false;
457
458         rcu_read_lock();
459         for (port = __engine_active(signal->engine);
460              (rq = READ_ONCE(*port)); /* may race with promotion of pending[] */
461              port++) {
462                 if (rq->context == signal->context) {
463                         inflight = i915_seqno_passed(rq->fence.seqno,
464                                                      signal->fence.seqno);
465                         break;
466                 }
467         }
468         rcu_read_unlock();
469
470         return inflight;
471 }
472
473 static int
474 __await_execution(struct i915_request *rq,
475                   struct i915_request *signal,
476                   gfp_t gfp)
477 {
478         struct execute_cb *cb;
479
480         if (i915_request_is_active(signal))
481                 return 0;
482
483         cb = kmem_cache_alloc(slab_execute_cbs, gfp);
484         if (!cb)
485                 return -ENOMEM;
486
487         cb->fence = &rq->submit;
488         i915_sw_fence_await(cb->fence);
489         init_irq_work(&cb->work, irq_execute_cb);
490
491         /*
492          * Register the callback first, then see if the signaler is already
493          * active. This ensures that if we race with the
494          * __notify_execute_cb from i915_request_submit() and we are not
495          * included in that list, we get a second bite of the cherry and
496          * execute it ourselves. After this point, a future
497          * i915_request_submit() will notify us.
498          *
499          * In i915_request_retire() we set the ACTIVE bit on a completed
500          * request (then flush the execute_cb). So by registering the
501          * callback first, then checking the ACTIVE bit, we serialise with
502          * the completed/retired request.
503          */
504         if (llist_add(&cb->work.node.llist, &signal->execute_cb)) {
505                 if (i915_request_is_active(signal) ||
506                     __request_in_flight(signal))
507                         i915_request_notify_execute_cb_imm(signal);
508         }
509
510         return 0;
511 }
512
513 static bool fatal_error(int error)
514 {
515         switch (error) {
516         case 0: /* not an error! */
517         case -EAGAIN: /* innocent victim of a GT reset (__i915_request_reset) */
518         case -ETIMEDOUT: /* waiting for Godot (timer_i915_sw_fence_wake) */
519                 return false;
520         default:
521                 return true;
522         }
523 }
524
525 void __i915_request_skip(struct i915_request *rq)
526 {
527         GEM_BUG_ON(!fatal_error(rq->fence.error));
528
529         if (rq->infix == rq->postfix)
530                 return;
531
532         RQ_TRACE(rq, "error: %d\n", rq->fence.error);
533
534         /*
535          * As this request likely depends on state from the lost
536          * context, clear out all the user operations leaving the
537          * breadcrumb at the end (so we get the fence notifications).
538          */
539         __i915_request_fill(rq, 0);
540         rq->infix = rq->postfix;
541 }
542
543 bool i915_request_set_error_once(struct i915_request *rq, int error)
544 {
545         int old;
546
547         GEM_BUG_ON(!IS_ERR_VALUE((long)error));
548
549         if (i915_request_signaled(rq))
550                 return false;
551
552         old = READ_ONCE(rq->fence.error);
553         do {
554                 if (fatal_error(old))
555                         return false;
556         } while (!try_cmpxchg(&rq->fence.error, &old, error));
557
558         return true;
559 }
560
561 struct i915_request *i915_request_mark_eio(struct i915_request *rq)
562 {
563         if (__i915_request_is_complete(rq))
564                 return NULL;
565
566         GEM_BUG_ON(i915_request_signaled(rq));
567
568         /* As soon as the request is completed, it may be retired */
569         rq = i915_request_get(rq);
570
571         i915_request_set_error_once(rq, -EIO);
572         i915_request_mark_complete(rq);
573
574         return rq;
575 }
576
577 bool __i915_request_submit(struct i915_request *request)
578 {
579         struct intel_engine_cs *engine = request->engine;
580         bool result = false;
581
582         RQ_TRACE(request, "\n");
583
584         GEM_BUG_ON(!irqs_disabled());
585         lockdep_assert_held(&engine->sched_engine->lock);
586
587         /*
588          * With the advent of preempt-to-busy, we frequently encounter
589          * requests that we have unsubmitted from HW, but left running
590          * until the next ack and so have completed in the meantime. On
591          * resubmission of that completed request, we can skip
592          * updating the payload, and execlists can even skip submitting
593          * the request.
594          *
595          * We must remove the request from the caller's priority queue,
596          * and the caller must only call us when the request is in their
597          * priority queue, under the sched_engine->lock. This ensures that the
598          * request has *not* yet been retired and we can safely move
599          * the request into the engine->active.list where it will be
600          * dropped upon retiring. (Otherwise if resubmit a *retired*
601          * request, this would be a horrible use-after-free.)
602          */
603         if (__i915_request_is_complete(request)) {
604                 list_del_init(&request->sched.link);
605                 goto active;
606         }
607
608         if (unlikely(intel_context_is_banned(request->context)))
609                 i915_request_set_error_once(request, -EIO);
610
611         if (unlikely(fatal_error(request->fence.error)))
612                 __i915_request_skip(request);
613
614         /*
615          * Are we using semaphores when the gpu is already saturated?
616          *
617          * Using semaphores incurs a cost in having the GPU poll a
618          * memory location, busywaiting for it to change. The continual
619          * memory reads can have a noticeable impact on the rest of the
620          * system with the extra bus traffic, stalling the cpu as it too
621          * tries to access memory across the bus (perf stat -e bus-cycles).
622          *
623          * If we installed a semaphore on this request and we only submit
624          * the request after the signaler completed, that indicates the
625          * system is overloaded and using semaphores at this time only
626          * increases the amount of work we are doing. If so, we disable
627          * further use of semaphores until we are idle again, whence we
628          * optimistically try again.
629          */
630         if (request->sched.semaphores &&
631             i915_sw_fence_signaled(&request->semaphore))
632                 engine->saturated |= request->sched.semaphores;
633
634         engine->emit_fini_breadcrumb(request,
635                                      request->ring->vaddr + request->postfix);
636
637         trace_i915_request_execute(request);
638         if (engine->bump_serial)
639                 engine->bump_serial(engine);
640         else
641                 engine->serial++;
642
643         result = true;
644
645         GEM_BUG_ON(test_bit(I915_FENCE_FLAG_ACTIVE, &request->fence.flags));
646         engine->add_active_request(request);
647 active:
648         clear_bit(I915_FENCE_FLAG_PQUEUE, &request->fence.flags);
649         set_bit(I915_FENCE_FLAG_ACTIVE, &request->fence.flags);
650
651         /*
652          * XXX Rollback bonded-execution on __i915_request_unsubmit()?
653          *
654          * In the future, perhaps when we have an active time-slicing scheduler,
655          * it will be interesting to unsubmit parallel execution and remove
656          * busywaits from the GPU until their master is restarted. This is
657          * quite hairy, we have to carefully rollback the fence and do a
658          * preempt-to-idle cycle on the target engine, all the while the
659          * master execute_cb may refire.
660          */
661         __notify_execute_cb_irq(request);
662
663         /* We may be recursing from the signal callback of another i915 fence */
664         if (test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT, &request->fence.flags))
665                 i915_request_enable_breadcrumb(request);
666
667         return result;
668 }
669
670 void i915_request_submit(struct i915_request *request)
671 {
672         struct intel_engine_cs *engine = request->engine;
673         unsigned long flags;
674
675         /* Will be called from irq-context when using foreign fences. */
676         spin_lock_irqsave(&engine->sched_engine->lock, flags);
677
678         __i915_request_submit(request);
679
680         spin_unlock_irqrestore(&engine->sched_engine->lock, flags);
681 }
682
683 void __i915_request_unsubmit(struct i915_request *request)
684 {
685         struct intel_engine_cs *engine = request->engine;
686
687         /*
688          * Only unwind in reverse order, required so that the per-context list
689          * is kept in seqno/ring order.
690          */
691         RQ_TRACE(request, "\n");
692
693         GEM_BUG_ON(!irqs_disabled());
694         lockdep_assert_held(&engine->sched_engine->lock);
695
696         /*
697          * Before we remove this breadcrumb from the signal list, we have
698          * to ensure that a concurrent dma_fence_enable_signaling() does not
699          * attach itself. We first mark the request as no longer active and
700          * make sure that is visible to other cores, and then remove the
701          * breadcrumb if attached.
702          */
703         GEM_BUG_ON(!test_bit(I915_FENCE_FLAG_ACTIVE, &request->fence.flags));
704         clear_bit_unlock(I915_FENCE_FLAG_ACTIVE, &request->fence.flags);
705         if (test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT, &request->fence.flags))
706                 i915_request_cancel_breadcrumb(request);
707
708         /* We've already spun, don't charge on resubmitting. */
709         if (request->sched.semaphores && __i915_request_has_started(request))
710                 request->sched.semaphores = 0;
711
712         /*
713          * We don't need to wake_up any waiters on request->execute, they
714          * will get woken by any other event or us re-adding this request
715          * to the engine timeline (__i915_request_submit()). The waiters
716          * should be quite adapt at finding that the request now has a new
717          * global_seqno to the one they went to sleep on.
718          */
719 }
720
721 void i915_request_unsubmit(struct i915_request *request)
722 {
723         struct intel_engine_cs *engine = request->engine;
724         unsigned long flags;
725
726         /* Will be called from irq-context when using foreign fences. */
727         spin_lock_irqsave(&engine->sched_engine->lock, flags);
728
729         __i915_request_unsubmit(request);
730
731         spin_unlock_irqrestore(&engine->sched_engine->lock, flags);
732 }
733
734 void i915_request_cancel(struct i915_request *rq, int error)
735 {
736         if (!i915_request_set_error_once(rq, error))
737                 return;
738
739         set_bit(I915_FENCE_FLAG_SENTINEL, &rq->fence.flags);
740
741         intel_context_cancel_request(rq->context, rq);
742 }
743
744 static int
745 submit_notify(struct i915_sw_fence *fence, enum i915_sw_fence_notify state)
746 {
747         struct i915_request *request =
748                 container_of(fence, typeof(*request), submit);
749
750         switch (state) {
751         case FENCE_COMPLETE:
752                 trace_i915_request_submit(request);
753
754                 if (unlikely(fence->error))
755                         i915_request_set_error_once(request, fence->error);
756                 else
757                         __rq_arm_watchdog(request);
758
759                 /*
760                  * We need to serialize use of the submit_request() callback
761                  * with its hotplugging performed during an emergency
762                  * i915_gem_set_wedged().  We use the RCU mechanism to mark the
763                  * critical section in order to force i915_gem_set_wedged() to
764                  * wait until the submit_request() is completed before
765                  * proceeding.
766                  */
767                 rcu_read_lock();
768                 request->engine->submit_request(request);
769                 rcu_read_unlock();
770                 break;
771
772         case FENCE_FREE:
773                 i915_request_put(request);
774                 break;
775         }
776
777         return NOTIFY_DONE;
778 }
779
780 static int
781 semaphore_notify(struct i915_sw_fence *fence, enum i915_sw_fence_notify state)
782 {
783         struct i915_request *rq = container_of(fence, typeof(*rq), semaphore);
784
785         switch (state) {
786         case FENCE_COMPLETE:
787                 break;
788
789         case FENCE_FREE:
790                 i915_request_put(rq);
791                 break;
792         }
793
794         return NOTIFY_DONE;
795 }
796
797 static void retire_requests(struct intel_timeline *tl)
798 {
799         struct i915_request *rq, *rn;
800
801         list_for_each_entry_safe(rq, rn, &tl->requests, link)
802                 if (!i915_request_retire(rq))
803                         break;
804 }
805
806 static noinline struct i915_request *
807 request_alloc_slow(struct intel_timeline *tl,
808                    struct i915_request **rsvd,
809                    gfp_t gfp)
810 {
811         struct i915_request *rq;
812
813         /* If we cannot wait, dip into our reserves */
814         if (!gfpflags_allow_blocking(gfp)) {
815                 rq = xchg(rsvd, NULL);
816                 if (!rq) /* Use the normal failure path for one final WARN */
817                         goto out;
818
819                 return rq;
820         }
821
822         if (list_empty(&tl->requests))
823                 goto out;
824
825         /* Move our oldest request to the slab-cache (if not in use!) */
826         rq = list_first_entry(&tl->requests, typeof(*rq), link);
827         i915_request_retire(rq);
828
829         rq = kmem_cache_alloc(slab_requests,
830                               gfp | __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
831         if (rq)
832                 return rq;
833
834         /* Ratelimit ourselves to prevent oom from malicious clients */
835         rq = list_last_entry(&tl->requests, typeof(*rq), link);
836         cond_synchronize_rcu(rq->rcustate);
837
838         /* Retire our old requests in the hope that we free some */
839         retire_requests(tl);
840
841 out:
842         return kmem_cache_alloc(slab_requests, gfp);
843 }
844
845 static void __i915_request_ctor(void *arg)
846 {
847         struct i915_request *rq = arg;
848
849         spin_lock_init(&rq->lock);
850         i915_sched_node_init(&rq->sched);
851         i915_sw_fence_init(&rq->submit, submit_notify);
852         i915_sw_fence_init(&rq->semaphore, semaphore_notify);
853
854         clear_capture_list(rq);
855         rq->batch_snapshot.present = false;
856
857         init_llist_head(&rq->execute_cb);
858 }
859
860 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
861 #define clear_batch_ptr(_rq) ((_rq)->batch = NULL)
862 #else
863 #define clear_batch_ptr(_a) do {} while (0)
864 #endif
865
866 struct i915_request *
867 __i915_request_create(struct intel_context *ce, gfp_t gfp)
868 {
869         struct intel_timeline *tl = ce->timeline;
870         struct i915_request *rq;
871         u32 seqno;
872         int ret;
873
874         might_alloc(gfp);
875
876         /* Check that the caller provided an already pinned context */
877         __intel_context_pin(ce);
878
879         /*
880          * Beware: Dragons be flying overhead.
881          *
882          * We use RCU to look up requests in flight. The lookups may
883          * race with the request being allocated from the slab freelist.
884          * That is the request we are writing to here, may be in the process
885          * of being read by __i915_active_request_get_rcu(). As such,
886          * we have to be very careful when overwriting the contents. During
887          * the RCU lookup, we change chase the request->engine pointer,
888          * read the request->global_seqno and increment the reference count.
889          *
890          * The reference count is incremented atomically. If it is zero,
891          * the lookup knows the request is unallocated and complete. Otherwise,
892          * it is either still in use, or has been reallocated and reset
893          * with dma_fence_init(). This increment is safe for release as we
894          * check that the request we have a reference to and matches the active
895          * request.
896          *
897          * Before we increment the refcount, we chase the request->engine
898          * pointer. We must not call kmem_cache_zalloc() or else we set
899          * that pointer to NULL and cause a crash during the lookup. If
900          * we see the request is completed (based on the value of the
901          * old engine and seqno), the lookup is complete and reports NULL.
902          * If we decide the request is not completed (new engine or seqno),
903          * then we grab a reference and double check that it is still the
904          * active request - which it won't be and restart the lookup.
905          *
906          * Do not use kmem_cache_zalloc() here!
907          */
908         rq = kmem_cache_alloc(slab_requests,
909                               gfp | __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
910         if (unlikely(!rq)) {
911                 rq = request_alloc_slow(tl, &ce->engine->request_pool, gfp);
912                 if (!rq) {
913                         ret = -ENOMEM;
914                         goto err_unreserve;
915                 }
916         }
917
918         /*
919          * Hold a reference to the intel_context over life of an i915_request.
920          * Without this an i915_request can exist after the context has been
921          * destroyed (e.g. request retired, context closed, but user space holds
922          * a reference to the request from an out fence). In the case of GuC
923          * submission + virtual engine, the engine that the request references
924          * is also destroyed which can trigger bad pointer dref in fence ops
925          * (e.g. i915_fence_get_driver_name). We could likely change these
926          * functions to avoid touching the engine but let's just be safe and
927          * hold the intel_context reference. In execlist mode the request always
928          * eventually points to a physical engine so this isn't an issue.
929          */
930         rq->context = intel_context_get(ce);
931         rq->engine = ce->engine;
932         rq->ring = ce->ring;
933         rq->execution_mask = ce->engine->mask;
934
935         ret = intel_timeline_get_seqno(tl, rq, &seqno);
936         if (ret)
937                 goto err_free;
938
939         dma_fence_init(&rq->fence, &i915_fence_ops, &rq->lock,
940                        tl->fence_context, seqno);
941
942         RCU_INIT_POINTER(rq->timeline, tl);
943         rq->hwsp_seqno = tl->hwsp_seqno;
944         GEM_BUG_ON(__i915_request_is_complete(rq));
945
946         rq->rcustate = get_state_synchronize_rcu(); /* acts as smp_mb() */
947
948         rq->guc_prio = GUC_PRIO_INIT;
949
950         /* We bump the ref for the fence chain */
951         i915_sw_fence_reinit(&i915_request_get(rq)->submit);
952         i915_sw_fence_reinit(&i915_request_get(rq)->semaphore);
953
954         i915_sched_node_reinit(&rq->sched);
955
956         /* No zalloc, everything must be cleared after use */
957         clear_batch_ptr(rq);
958         __rq_init_watchdog(rq);
959         assert_capture_list_is_null(rq);
960         GEM_BUG_ON(!llist_empty(&rq->execute_cb));
961         GEM_BUG_ON(i915_vma_snapshot_present(&rq->batch_snapshot));
962
963         /*
964          * Reserve space in the ring buffer for all the commands required to
965          * eventually emit this request. This is to guarantee that the
966          * i915_request_add() call can't fail. Note that the reserve may need
967          * to be redone if the request is not actually submitted straight
968          * away, e.g. because a GPU scheduler has deferred it.
969          *
970          * Note that due to how we add reserved_space to intel_ring_begin()
971          * we need to double our request to ensure that if we need to wrap
972          * around inside i915_request_add() there is sufficient space at
973          * the beginning of the ring as well.
974          */
975         rq->reserved_space =
976                 2 * rq->engine->emit_fini_breadcrumb_dw * sizeof(u32);
977
978         /*
979          * Record the position of the start of the request so that
980          * should we detect the updated seqno part-way through the
981          * GPU processing the request, we never over-estimate the
982          * position of the head.
983          */
984         rq->head = rq->ring->emit;
985
986         ret = rq->engine->request_alloc(rq);
987         if (ret)
988                 goto err_unwind;
989
990         rq->infix = rq->ring->emit; /* end of header; start of user payload */
991
992         intel_context_mark_active(ce);
993         list_add_tail_rcu(&rq->link, &tl->requests);
994
995         return rq;
996
997 err_unwind:
998         ce->ring->emit = rq->head;
999
1000         /* Make sure we didn't add ourselves to external state before freeing */
1001         GEM_BUG_ON(!list_empty(&rq->sched.signalers_list));
1002         GEM_BUG_ON(!list_empty(&rq->sched.waiters_list));
1003
1004 err_free:
1005         intel_context_put(ce);
1006         kmem_cache_free(slab_requests, rq);
1007 err_unreserve:
1008         intel_context_unpin(ce);
1009         return ERR_PTR(ret);
1010 }
1011
1012 struct i915_request *
1013 i915_request_create(struct intel_context *ce)
1014 {
1015         struct i915_request *rq;
1016         struct intel_timeline *tl;
1017
1018         tl = intel_context_timeline_lock(ce);
1019         if (IS_ERR(tl))
1020                 return ERR_CAST(tl);
1021
1022         /* Move our oldest request to the slab-cache (if not in use!) */
1023         rq = list_first_entry(&tl->requests, typeof(*rq), link);
1024         if (!list_is_last(&rq->link, &tl->requests))
1025                 i915_request_retire(rq);
1026
1027         intel_context_enter(ce);
1028         rq = __i915_request_create(ce, GFP_KERNEL);
1029         intel_context_exit(ce); /* active reference transferred to request */
1030         if (IS_ERR(rq))
1031                 goto err_unlock;
1032
1033         /* Check that we do not interrupt ourselves with a new request */
1034         rq->cookie = lockdep_pin_lock(&tl->mutex);
1035
1036         return rq;
1037
1038 err_unlock:
1039         intel_context_timeline_unlock(tl);
1040         return rq;
1041 }
1042
1043 static int
1044 i915_request_await_start(struct i915_request *rq, struct i915_request *signal)
1045 {
1046         struct dma_fence *fence;
1047         int err;
1048
1049         if (i915_request_timeline(rq) == rcu_access_pointer(signal->timeline))
1050                 return 0;
1051
1052         if (i915_request_started(signal))
1053                 return 0;
1054
1055         /*
1056          * The caller holds a reference on @signal, but we do not serialise
1057          * against it being retired and removed from the lists.
1058          *
1059          * We do not hold a reference to the request before @signal, and
1060          * so must be very careful to ensure that it is not _recycled_ as
1061          * we follow the link backwards.
1062          */
1063         fence = NULL;
1064         rcu_read_lock();
1065         do {
1066                 struct list_head *pos = READ_ONCE(signal->link.prev);
1067                 struct i915_request *prev;
1068
1069                 /* Confirm signal has not been retired, the link is valid */
1070                 if (unlikely(__i915_request_has_started(signal)))
1071                         break;
1072
1073                 /* Is signal the earliest request on its timeline? */
1074                 if (pos == &rcu_dereference(signal->timeline)->requests)
1075                         break;
1076
1077                 /*
1078                  * Peek at the request before us in the timeline. That
1079                  * request will only be valid before it is retired, so
1080                  * after acquiring a reference to it, confirm that it is
1081                  * still part of the signaler's timeline.
1082                  */
1083                 prev = list_entry(pos, typeof(*prev), link);
1084                 if (!i915_request_get_rcu(prev))
1085                         break;
1086
1087                 /* After the strong barrier, confirm prev is still attached */
1088                 if (unlikely(READ_ONCE(prev->link.next) != &signal->link)) {
1089                         i915_request_put(prev);
1090                         break;
1091                 }
1092
1093                 fence = &prev->fence;
1094         } while (0);
1095         rcu_read_unlock();
1096         if (!fence)
1097                 return 0;
1098
1099         err = 0;
1100         if (!intel_timeline_sync_is_later(i915_request_timeline(rq), fence))
1101                 err = i915_sw_fence_await_dma_fence(&rq->submit,
1102                                                     fence, 0,
1103                                                     I915_FENCE_GFP);
1104         dma_fence_put(fence);
1105
1106         return err;
1107 }
1108
1109 static intel_engine_mask_t
1110 already_busywaiting(struct i915_request *rq)
1111 {
1112         /*
1113          * Polling a semaphore causes bus traffic, delaying other users of
1114          * both the GPU and CPU. We want to limit the impact on others,
1115          * while taking advantage of early submission to reduce GPU
1116          * latency. Therefore we restrict ourselves to not using more
1117          * than one semaphore from each source, and not using a semaphore
1118          * if we have detected the engine is saturated (i.e. would not be
1119          * submitted early and cause bus traffic reading an already passed
1120          * semaphore).
1121          *
1122          * See the are-we-too-late? check in __i915_request_submit().
1123          */
1124         return rq->sched.semaphores | READ_ONCE(rq->engine->saturated);
1125 }
1126
1127 static int
1128 __emit_semaphore_wait(struct i915_request *to,
1129                       struct i915_request *from,
1130                       u32 seqno)
1131 {
1132         const int has_token = GRAPHICS_VER(to->engine->i915) >= 12;
1133         u32 hwsp_offset;
1134         int len, err;
1135         u32 *cs;
1136
1137         GEM_BUG_ON(GRAPHICS_VER(to->engine->i915) < 8);
1138         GEM_BUG_ON(i915_request_has_initial_breadcrumb(to));
1139
1140         /* We need to pin the signaler's HWSP until we are finished reading. */
1141         err = intel_timeline_read_hwsp(from, to, &hwsp_offset);
1142         if (err)
1143                 return err;
1144
1145         len = 4;
1146         if (has_token)
1147                 len += 2;
1148
1149         cs = intel_ring_begin(to, len);
1150         if (IS_ERR(cs))
1151                 return PTR_ERR(cs);
1152
1153         /*
1154          * Using greater-than-or-equal here means we have to worry
1155          * about seqno wraparound. To side step that issue, we swap
1156          * the timeline HWSP upon wrapping, so that everyone listening
1157          * for the old (pre-wrap) values do not see the much smaller
1158          * (post-wrap) values than they were expecting (and so wait
1159          * forever).
1160          */
1161         *cs++ = (MI_SEMAPHORE_WAIT |
1162                  MI_SEMAPHORE_GLOBAL_GTT |
1163                  MI_SEMAPHORE_POLL |
1164                  MI_SEMAPHORE_SAD_GTE_SDD) +
1165                 has_token;
1166         *cs++ = seqno;
1167         *cs++ = hwsp_offset;
1168         *cs++ = 0;
1169         if (has_token) {
1170                 *cs++ = 0;
1171                 *cs++ = MI_NOOP;
1172         }
1173
1174         intel_ring_advance(to, cs);
1175         return 0;
1176 }
1177
1178 static bool
1179 can_use_semaphore_wait(struct i915_request *to, struct i915_request *from)
1180 {
1181         return to->engine->gt->ggtt == from->engine->gt->ggtt;
1182 }
1183
1184 static int
1185 emit_semaphore_wait(struct i915_request *to,
1186                     struct i915_request *from,
1187                     gfp_t gfp)
1188 {
1189         const intel_engine_mask_t mask = READ_ONCE(from->engine)->mask;
1190         struct i915_sw_fence *wait = &to->submit;
1191
1192         if (!can_use_semaphore_wait(to, from))
1193                 goto await_fence;
1194
1195         if (!intel_context_use_semaphores(to->context))
1196                 goto await_fence;
1197
1198         if (i915_request_has_initial_breadcrumb(to))
1199                 goto await_fence;
1200
1201         /*
1202          * If this or its dependents are waiting on an external fence
1203          * that may fail catastrophically, then we want to avoid using
1204          * sempahores as they bypass the fence signaling metadata, and we
1205          * lose the fence->error propagation.
1206          */
1207         if (from->sched.flags & I915_SCHED_HAS_EXTERNAL_CHAIN)
1208                 goto await_fence;
1209
1210         /* Just emit the first semaphore we see as request space is limited. */
1211         if (already_busywaiting(to) & mask)
1212                 goto await_fence;
1213
1214         if (i915_request_await_start(to, from) < 0)
1215                 goto await_fence;
1216
1217         /* Only submit our spinner after the signaler is running! */
1218         if (__await_execution(to, from, gfp))
1219                 goto await_fence;
1220
1221         if (__emit_semaphore_wait(to, from, from->fence.seqno))
1222                 goto await_fence;
1223
1224         to->sched.semaphores |= mask;
1225         wait = &to->semaphore;
1226
1227 await_fence:
1228         return i915_sw_fence_await_dma_fence(wait,
1229                                              &from->fence, 0,
1230                                              I915_FENCE_GFP);
1231 }
1232
1233 static bool intel_timeline_sync_has_start(struct intel_timeline *tl,
1234                                           struct dma_fence *fence)
1235 {
1236         return __intel_timeline_sync_is_later(tl,
1237                                               fence->context,
1238                                               fence->seqno - 1);
1239 }
1240
1241 static int intel_timeline_sync_set_start(struct intel_timeline *tl,
1242                                          const struct dma_fence *fence)
1243 {
1244         return __intel_timeline_sync_set(tl, fence->context, fence->seqno - 1);
1245 }
1246
1247 static int
1248 __i915_request_await_execution(struct i915_request *to,
1249                                struct i915_request *from)
1250 {
1251         int err;
1252
1253         GEM_BUG_ON(intel_context_is_barrier(from->context));
1254
1255         /* Submit both requests at the same time */
1256         err = __await_execution(to, from, I915_FENCE_GFP);
1257         if (err)
1258                 return err;
1259
1260         /* Squash repeated depenendices to the same timelines */
1261         if (intel_timeline_sync_has_start(i915_request_timeline(to),
1262                                           &from->fence))
1263                 return 0;
1264
1265         /*
1266          * Wait until the start of this request.
1267          *
1268          * The execution cb fires when we submit the request to HW. But in
1269          * many cases this may be long before the request itself is ready to
1270          * run (consider that we submit 2 requests for the same context, where
1271          * the request of interest is behind an indefinite spinner). So we hook
1272          * up to both to reduce our queues and keep the execution lag minimised
1273          * in the worst case, though we hope that the await_start is elided.
1274          */
1275         err = i915_request_await_start(to, from);
1276         if (err < 0)
1277                 return err;
1278
1279         /*
1280          * Ensure both start together [after all semaphores in signal]
1281          *
1282          * Now that we are queued to the HW at roughly the same time (thanks
1283          * to the execute cb) and are ready to run at roughly the same time
1284          * (thanks to the await start), our signaler may still be indefinitely
1285          * delayed by waiting on a semaphore from a remote engine. If our
1286          * signaler depends on a semaphore, so indirectly do we, and we do not
1287          * want to start our payload until our signaler also starts theirs.
1288          * So we wait.
1289          *
1290          * However, there is also a second condition for which we need to wait
1291          * for the precise start of the signaler. Consider that the signaler
1292          * was submitted in a chain of requests following another context
1293          * (with just an ordinary intra-engine fence dependency between the
1294          * two). In this case the signaler is queued to HW, but not for
1295          * immediate execution, and so we must wait until it reaches the
1296          * active slot.
1297          */
1298         if (can_use_semaphore_wait(to, from) &&
1299             intel_engine_has_semaphores(to->engine) &&
1300             !i915_request_has_initial_breadcrumb(to)) {
1301                 err = __emit_semaphore_wait(to, from, from->fence.seqno - 1);
1302                 if (err < 0)
1303                         return err;
1304         }
1305
1306         /* Couple the dependency tree for PI on this exposed to->fence */
1307         if (to->engine->sched_engine->schedule) {
1308                 err = i915_sched_node_add_dependency(&to->sched,
1309                                                      &from->sched,
1310                                                      I915_DEPENDENCY_WEAK);
1311                 if (err < 0)
1312                         return err;
1313         }
1314
1315         return intel_timeline_sync_set_start(i915_request_timeline(to),
1316                                              &from->fence);
1317 }
1318
1319 static void mark_external(struct i915_request *rq)
1320 {
1321         /*
1322          * The downside of using semaphores is that we lose metadata passing
1323          * along the signaling chain. This is particularly nasty when we
1324          * need to pass along a fatal error such as EFAULT or EDEADLK. For
1325          * fatal errors we want to scrub the request before it is executed,
1326          * which means that we cannot preload the request onto HW and have
1327          * it wait upon a semaphore.
1328          */
1329         rq->sched.flags |= I915_SCHED_HAS_EXTERNAL_CHAIN;
1330 }
1331
1332 static int
1333 __i915_request_await_external(struct i915_request *rq, struct dma_fence *fence)
1334 {
1335         mark_external(rq);
1336         return i915_sw_fence_await_dma_fence(&rq->submit, fence,
1337                                              i915_fence_context_timeout(rq->engine->i915,
1338                                                                         fence->context),
1339                                              I915_FENCE_GFP);
1340 }
1341
1342 static int
1343 i915_request_await_external(struct i915_request *rq, struct dma_fence *fence)
1344 {
1345         struct dma_fence *iter;
1346         int err = 0;
1347
1348         if (!to_dma_fence_chain(fence))
1349                 return __i915_request_await_external(rq, fence);
1350
1351         dma_fence_chain_for_each(iter, fence) {
1352                 struct dma_fence_chain *chain = to_dma_fence_chain(iter);
1353
1354                 if (!dma_fence_is_i915(chain->fence)) {
1355                         err = __i915_request_await_external(rq, iter);
1356                         break;
1357                 }
1358
1359                 err = i915_request_await_dma_fence(rq, chain->fence);
1360                 if (err < 0)
1361                         break;
1362         }
1363
1364         dma_fence_put(iter);
1365         return err;
1366 }
1367
1368 static inline bool is_parallel_rq(struct i915_request *rq)
1369 {
1370         return intel_context_is_parallel(rq->context);
1371 }
1372
1373 static inline struct intel_context *request_to_parent(struct i915_request *rq)
1374 {
1375         return intel_context_to_parent(rq->context);
1376 }
1377
1378 static bool is_same_parallel_context(struct i915_request *to,
1379                                      struct i915_request *from)
1380 {
1381         if (is_parallel_rq(to))
1382                 return request_to_parent(to) == request_to_parent(from);
1383
1384         return false;
1385 }
1386
1387 int
1388 i915_request_await_execution(struct i915_request *rq,
1389                              struct dma_fence *fence)
1390 {
1391         struct dma_fence **child = &fence;
1392         unsigned int nchild = 1;
1393         int ret;
1394
1395         if (dma_fence_is_array(fence)) {
1396                 struct dma_fence_array *array = to_dma_fence_array(fence);
1397
1398                 /* XXX Error for signal-on-any fence arrays */
1399
1400                 child = array->fences;
1401                 nchild = array->num_fences;
1402                 GEM_BUG_ON(!nchild);
1403         }
1404
1405         do {
1406                 fence = *child++;
1407                 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
1408                         continue;
1409
1410                 if (fence->context == rq->fence.context)
1411                         continue;
1412
1413                 /*
1414                  * We don't squash repeated fence dependencies here as we
1415                  * want to run our callback in all cases.
1416                  */
1417
1418                 if (dma_fence_is_i915(fence)) {
1419                         if (is_same_parallel_context(rq, to_request(fence)))
1420                                 continue;
1421                         ret = __i915_request_await_execution(rq,
1422                                                              to_request(fence));
1423                 } else {
1424                         ret = i915_request_await_external(rq, fence);
1425                 }
1426                 if (ret < 0)
1427                         return ret;
1428         } while (--nchild);
1429
1430         return 0;
1431 }
1432
1433 static int
1434 await_request_submit(struct i915_request *to, struct i915_request *from)
1435 {
1436         /*
1437          * If we are waiting on a virtual engine, then it may be
1438          * constrained to execute on a single engine *prior* to submission.
1439          * When it is submitted, it will be first submitted to the virtual
1440          * engine and then passed to the physical engine. We cannot allow
1441          * the waiter to be submitted immediately to the physical engine
1442          * as it may then bypass the virtual request.
1443          */
1444         if (to->engine == READ_ONCE(from->engine))
1445                 return i915_sw_fence_await_sw_fence_gfp(&to->submit,
1446                                                         &from->submit,
1447                                                         I915_FENCE_GFP);
1448         else
1449                 return __i915_request_await_execution(to, from);
1450 }
1451
1452 static int
1453 i915_request_await_request(struct i915_request *to, struct i915_request *from)
1454 {
1455         int ret;
1456
1457         GEM_BUG_ON(to == from);
1458         GEM_BUG_ON(to->timeline == from->timeline);
1459
1460         if (i915_request_completed(from)) {
1461                 i915_sw_fence_set_error_once(&to->submit, from->fence.error);
1462                 return 0;
1463         }
1464
1465         if (to->engine->sched_engine->schedule) {
1466                 ret = i915_sched_node_add_dependency(&to->sched,
1467                                                      &from->sched,
1468                                                      I915_DEPENDENCY_EXTERNAL);
1469                 if (ret < 0)
1470                         return ret;
1471         }
1472
1473         if (!intel_engine_uses_guc(to->engine) &&
1474             is_power_of_2(to->execution_mask | READ_ONCE(from->execution_mask)))
1475                 ret = await_request_submit(to, from);
1476         else
1477                 ret = emit_semaphore_wait(to, from, I915_FENCE_GFP);
1478         if (ret < 0)
1479                 return ret;
1480
1481         return 0;
1482 }
1483
1484 int
1485 i915_request_await_dma_fence(struct i915_request *rq, struct dma_fence *fence)
1486 {
1487         struct dma_fence **child = &fence;
1488         unsigned int nchild = 1;
1489         int ret;
1490
1491         /*
1492          * Note that if the fence-array was created in signal-on-any mode,
1493          * we should *not* decompose it into its individual fences. However,
1494          * we don't currently store which mode the fence-array is operating
1495          * in. Fortunately, the only user of signal-on-any is private to
1496          * amdgpu and we should not see any incoming fence-array from
1497          * sync-file being in signal-on-any mode.
1498          */
1499         if (dma_fence_is_array(fence)) {
1500                 struct dma_fence_array *array = to_dma_fence_array(fence);
1501
1502                 child = array->fences;
1503                 nchild = array->num_fences;
1504                 GEM_BUG_ON(!nchild);
1505         }
1506
1507         do {
1508                 fence = *child++;
1509                 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
1510                         continue;
1511
1512                 /*
1513                  * Requests on the same timeline are explicitly ordered, along
1514                  * with their dependencies, by i915_request_add() which ensures
1515                  * that requests are submitted in-order through each ring.
1516                  */
1517                 if (fence->context == rq->fence.context)
1518                         continue;
1519
1520                 /* Squash repeated waits to the same timelines */
1521                 if (fence->context &&
1522                     intel_timeline_sync_is_later(i915_request_timeline(rq),
1523                                                  fence))
1524                         continue;
1525
1526                 if (dma_fence_is_i915(fence)) {
1527                         if (is_same_parallel_context(rq, to_request(fence)))
1528                                 continue;
1529                         ret = i915_request_await_request(rq, to_request(fence));
1530                 } else {
1531                         ret = i915_request_await_external(rq, fence);
1532                 }
1533                 if (ret < 0)
1534                         return ret;
1535
1536                 /* Record the latest fence used against each timeline */
1537                 if (fence->context)
1538                         intel_timeline_sync_set(i915_request_timeline(rq),
1539                                                 fence);
1540         } while (--nchild);
1541
1542         return 0;
1543 }
1544
1545 /**
1546  * i915_request_await_object - set this request to (async) wait upon a bo
1547  * @to: request we are wishing to use
1548  * @obj: object which may be in use on another ring.
1549  * @write: whether the wait is on behalf of a writer
1550  *
1551  * This code is meant to abstract object synchronization with the GPU.
1552  * Conceptually we serialise writes between engines inside the GPU.
1553  * We only allow one engine to write into a buffer at any time, but
1554  * multiple readers. To ensure each has a coherent view of memory, we must:
1555  *
1556  * - If there is an outstanding write request to the object, the new
1557  *   request must wait for it to complete (either CPU or in hw, requests
1558  *   on the same ring will be naturally ordered).
1559  *
1560  * - If we are a write request (pending_write_domain is set), the new
1561  *   request must wait for outstanding read requests to complete.
1562  *
1563  * Returns 0 if successful, else propagates up the lower layer error.
1564  */
1565 int
1566 i915_request_await_object(struct i915_request *to,
1567                           struct drm_i915_gem_object *obj,
1568                           bool write)
1569 {
1570         struct dma_resv_iter cursor;
1571         struct dma_fence *fence;
1572         int ret = 0;
1573
1574         dma_resv_for_each_fence(&cursor, obj->base.resv, write, fence) {
1575                 ret = i915_request_await_dma_fence(to, fence);
1576                 if (ret)
1577                         break;
1578         }
1579
1580         return ret;
1581 }
1582
1583 static struct i915_request *
1584 __i915_request_ensure_parallel_ordering(struct i915_request *rq,
1585                                         struct intel_timeline *timeline)
1586 {
1587         struct i915_request *prev;
1588
1589         GEM_BUG_ON(!is_parallel_rq(rq));
1590
1591         prev = request_to_parent(rq)->parallel.last_rq;
1592         if (prev) {
1593                 if (!__i915_request_is_complete(prev)) {
1594                         i915_sw_fence_await_sw_fence(&rq->submit,
1595                                                      &prev->submit,
1596                                                      &rq->submitq);
1597
1598                         if (rq->engine->sched_engine->schedule)
1599                                 __i915_sched_node_add_dependency(&rq->sched,
1600                                                                  &prev->sched,
1601                                                                  &rq->dep,
1602                                                                  0);
1603                 }
1604                 i915_request_put(prev);
1605         }
1606
1607         request_to_parent(rq)->parallel.last_rq = i915_request_get(rq);
1608
1609         return to_request(__i915_active_fence_set(&timeline->last_request,
1610                                                   &rq->fence));
1611 }
1612
1613 static struct i915_request *
1614 __i915_request_ensure_ordering(struct i915_request *rq,
1615                                struct intel_timeline *timeline)
1616 {
1617         struct i915_request *prev;
1618
1619         GEM_BUG_ON(is_parallel_rq(rq));
1620
1621         prev = to_request(__i915_active_fence_set(&timeline->last_request,
1622                                                   &rq->fence));
1623
1624         if (prev && !__i915_request_is_complete(prev)) {
1625                 bool uses_guc = intel_engine_uses_guc(rq->engine);
1626                 bool pow2 = is_power_of_2(READ_ONCE(prev->engine)->mask |
1627                                           rq->engine->mask);
1628                 bool same_context = prev->context == rq->context;
1629
1630                 /*
1631                  * The requests are supposed to be kept in order. However,
1632                  * we need to be wary in case the timeline->last_request
1633                  * is used as a barrier for external modification to this
1634                  * context.
1635                  */
1636                 GEM_BUG_ON(same_context &&
1637                            i915_seqno_passed(prev->fence.seqno,
1638                                              rq->fence.seqno));
1639
1640                 if ((same_context && uses_guc) || (!uses_guc && pow2))
1641                         i915_sw_fence_await_sw_fence(&rq->submit,
1642                                                      &prev->submit,
1643                                                      &rq->submitq);
1644                 else
1645                         __i915_sw_fence_await_dma_fence(&rq->submit,
1646                                                         &prev->fence,
1647                                                         &rq->dmaq);
1648                 if (rq->engine->sched_engine->schedule)
1649                         __i915_sched_node_add_dependency(&rq->sched,
1650                                                          &prev->sched,
1651                                                          &rq->dep,
1652                                                          0);
1653         }
1654
1655         return prev;
1656 }
1657
1658 static struct i915_request *
1659 __i915_request_add_to_timeline(struct i915_request *rq)
1660 {
1661         struct intel_timeline *timeline = i915_request_timeline(rq);
1662         struct i915_request *prev;
1663
1664         /*
1665          * Dependency tracking and request ordering along the timeline
1666          * is special cased so that we can eliminate redundant ordering
1667          * operations while building the request (we know that the timeline
1668          * itself is ordered, and here we guarantee it).
1669          *
1670          * As we know we will need to emit tracking along the timeline,
1671          * we embed the hooks into our request struct -- at the cost of
1672          * having to have specialised no-allocation interfaces (which will
1673          * be beneficial elsewhere).
1674          *
1675          * A second benefit to open-coding i915_request_await_request is
1676          * that we can apply a slight variant of the rules specialised
1677          * for timelines that jump between engines (such as virtual engines).
1678          * If we consider the case of virtual engine, we must emit a dma-fence
1679          * to prevent scheduling of the second request until the first is
1680          * complete (to maximise our greedy late load balancing) and this
1681          * precludes optimising to use semaphores serialisation of a single
1682          * timeline across engines.
1683          *
1684          * We do not order parallel submission requests on the timeline as each
1685          * parallel submission context has its own timeline and the ordering
1686          * rules for parallel requests are that they must be submitted in the
1687          * order received from the execbuf IOCTL. So rather than using the
1688          * timeline we store a pointer to last request submitted in the
1689          * relationship in the gem context and insert a submission fence
1690          * between that request and request passed into this function or
1691          * alternatively we use completion fence if gem context has a single
1692          * timeline and this is the first submission of an execbuf IOCTL.
1693          */
1694         if (likely(!is_parallel_rq(rq)))
1695                 prev = __i915_request_ensure_ordering(rq, timeline);
1696         else
1697                 prev = __i915_request_ensure_parallel_ordering(rq, timeline);
1698
1699         /*
1700          * Make sure that no request gazumped us - if it was allocated after
1701          * our i915_request_alloc() and called __i915_request_add() before
1702          * us, the timeline will hold its seqno which is later than ours.
1703          */
1704         GEM_BUG_ON(timeline->seqno != rq->fence.seqno);
1705
1706         return prev;
1707 }
1708
1709 /*
1710  * NB: This function is not allowed to fail. Doing so would mean the the
1711  * request is not being tracked for completion but the work itself is
1712  * going to happen on the hardware. This would be a Bad Thing(tm).
1713  */
1714 struct i915_request *__i915_request_commit(struct i915_request *rq)
1715 {
1716         struct intel_engine_cs *engine = rq->engine;
1717         struct intel_ring *ring = rq->ring;
1718         u32 *cs;
1719
1720         RQ_TRACE(rq, "\n");
1721
1722         /*
1723          * To ensure that this call will not fail, space for its emissions
1724          * should already have been reserved in the ring buffer. Let the ring
1725          * know that it is time to use that space up.
1726          */
1727         GEM_BUG_ON(rq->reserved_space > ring->space);
1728         rq->reserved_space = 0;
1729         rq->emitted_jiffies = jiffies;
1730
1731         /*
1732          * Record the position of the start of the breadcrumb so that
1733          * should we detect the updated seqno part-way through the
1734          * GPU processing the request, we never over-estimate the
1735          * position of the ring's HEAD.
1736          */
1737         cs = intel_ring_begin(rq, engine->emit_fini_breadcrumb_dw);
1738         GEM_BUG_ON(IS_ERR(cs));
1739         rq->postfix = intel_ring_offset(rq, cs);
1740
1741         return __i915_request_add_to_timeline(rq);
1742 }
1743
1744 void __i915_request_queue_bh(struct i915_request *rq)
1745 {
1746         i915_sw_fence_commit(&rq->semaphore);
1747         i915_sw_fence_commit(&rq->submit);
1748 }
1749
1750 void __i915_request_queue(struct i915_request *rq,
1751                           const struct i915_sched_attr *attr)
1752 {
1753         /*
1754          * Let the backend know a new request has arrived that may need
1755          * to adjust the existing execution schedule due to a high priority
1756          * request - i.e. we may want to preempt the current request in order
1757          * to run a high priority dependency chain *before* we can execute this
1758          * request.
1759          *
1760          * This is called before the request is ready to run so that we can
1761          * decide whether to preempt the entire chain so that it is ready to
1762          * run at the earliest possible convenience.
1763          */
1764         if (attr && rq->engine->sched_engine->schedule)
1765                 rq->engine->sched_engine->schedule(rq, attr);
1766
1767         local_bh_disable();
1768         __i915_request_queue_bh(rq);
1769         local_bh_enable(); /* kick tasklets */
1770 }
1771
1772 void i915_request_add(struct i915_request *rq)
1773 {
1774         struct intel_timeline * const tl = i915_request_timeline(rq);
1775         struct i915_sched_attr attr = {};
1776         struct i915_gem_context *ctx;
1777
1778         lockdep_assert_held(&tl->mutex);
1779         lockdep_unpin_lock(&tl->mutex, rq->cookie);
1780
1781         trace_i915_request_add(rq);
1782         __i915_request_commit(rq);
1783
1784         /* XXX placeholder for selftests */
1785         rcu_read_lock();
1786         ctx = rcu_dereference(rq->context->gem_context);
1787         if (ctx)
1788                 attr = ctx->sched;
1789         rcu_read_unlock();
1790
1791         __i915_request_queue(rq, &attr);
1792
1793         mutex_unlock(&tl->mutex);
1794 }
1795
1796 static unsigned long local_clock_ns(unsigned int *cpu)
1797 {
1798         unsigned long t;
1799
1800         /*
1801          * Cheaply and approximately convert from nanoseconds to microseconds.
1802          * The result and subsequent calculations are also defined in the same
1803          * approximate microseconds units. The principal source of timing
1804          * error here is from the simple truncation.
1805          *
1806          * Note that local_clock() is only defined wrt to the current CPU;
1807          * the comparisons are no longer valid if we switch CPUs. Instead of
1808          * blocking preemption for the entire busywait, we can detect the CPU
1809          * switch and use that as indicator of system load and a reason to
1810          * stop busywaiting, see busywait_stop().
1811          */
1812         *cpu = get_cpu();
1813         t = local_clock();
1814         put_cpu();
1815
1816         return t;
1817 }
1818
1819 static bool busywait_stop(unsigned long timeout, unsigned int cpu)
1820 {
1821         unsigned int this_cpu;
1822
1823         if (time_after(local_clock_ns(&this_cpu), timeout))
1824                 return true;
1825
1826         return this_cpu != cpu;
1827 }
1828
1829 static bool __i915_spin_request(struct i915_request * const rq, int state)
1830 {
1831         unsigned long timeout_ns;
1832         unsigned int cpu;
1833
1834         /*
1835          * Only wait for the request if we know it is likely to complete.
1836          *
1837          * We don't track the timestamps around requests, nor the average
1838          * request length, so we do not have a good indicator that this
1839          * request will complete within the timeout. What we do know is the
1840          * order in which requests are executed by the context and so we can
1841          * tell if the request has been started. If the request is not even
1842          * running yet, it is a fair assumption that it will not complete
1843          * within our relatively short timeout.
1844          */
1845         if (!i915_request_is_running(rq))
1846                 return false;
1847
1848         /*
1849          * When waiting for high frequency requests, e.g. during synchronous
1850          * rendering split between the CPU and GPU, the finite amount of time
1851          * required to set up the irq and wait upon it limits the response
1852          * rate. By busywaiting on the request completion for a short while we
1853          * can service the high frequency waits as quick as possible. However,
1854          * if it is a slow request, we want to sleep as quickly as possible.
1855          * The tradeoff between waiting and sleeping is roughly the time it
1856          * takes to sleep on a request, on the order of a microsecond.
1857          */
1858
1859         timeout_ns = READ_ONCE(rq->engine->props.max_busywait_duration_ns);
1860         timeout_ns += local_clock_ns(&cpu);
1861         do {
1862                 if (dma_fence_is_signaled(&rq->fence))
1863                         return true;
1864
1865                 if (signal_pending_state(state, current))
1866                         break;
1867
1868                 if (busywait_stop(timeout_ns, cpu))
1869                         break;
1870
1871                 cpu_relax();
1872         } while (!need_resched());
1873
1874         return false;
1875 }
1876
1877 struct request_wait {
1878         struct dma_fence_cb cb;
1879         struct task_struct *tsk;
1880 };
1881
1882 static void request_wait_wake(struct dma_fence *fence, struct dma_fence_cb *cb)
1883 {
1884         struct request_wait *wait = container_of(cb, typeof(*wait), cb);
1885
1886         wake_up_process(fetch_and_zero(&wait->tsk));
1887 }
1888
1889 /**
1890  * i915_request_wait_timeout - wait until execution of request has finished
1891  * @rq: the request to wait upon
1892  * @flags: how to wait
1893  * @timeout: how long to wait in jiffies
1894  *
1895  * i915_request_wait_timeout() waits for the request to be completed, for a
1896  * maximum of @timeout jiffies (with MAX_SCHEDULE_TIMEOUT implying an
1897  * unbounded wait).
1898  *
1899  * Returns the remaining time (in jiffies) if the request completed, which may
1900  * be zero if the request is unfinished after the timeout expires.
1901  * If the timeout is 0, it will return 1 if the fence is signaled.
1902  *
1903  * May return -EINTR is called with I915_WAIT_INTERRUPTIBLE and a signal is
1904  * pending before the request completes.
1905  *
1906  * NOTE: This function has the same wait semantics as dma-fence.
1907  */
1908 long i915_request_wait_timeout(struct i915_request *rq,
1909                                unsigned int flags,
1910                                long timeout)
1911 {
1912         const int state = flags & I915_WAIT_INTERRUPTIBLE ?
1913                 TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE;
1914         struct request_wait wait;
1915
1916         might_sleep();
1917         GEM_BUG_ON(timeout < 0);
1918
1919         if (dma_fence_is_signaled(&rq->fence))
1920                 return timeout ?: 1;
1921
1922         if (!timeout)
1923                 return -ETIME;
1924
1925         trace_i915_request_wait_begin(rq, flags);
1926
1927         /*
1928          * We must never wait on the GPU while holding a lock as we
1929          * may need to perform a GPU reset. So while we don't need to
1930          * serialise wait/reset with an explicit lock, we do want
1931          * lockdep to detect potential dependency cycles.
1932          */
1933         mutex_acquire(&rq->engine->gt->reset.mutex.dep_map, 0, 0, _THIS_IP_);
1934
1935         /*
1936          * Optimistic spin before touching IRQs.
1937          *
1938          * We may use a rather large value here to offset the penalty of
1939          * switching away from the active task. Frequently, the client will
1940          * wait upon an old swapbuffer to throttle itself to remain within a
1941          * frame of the gpu. If the client is running in lockstep with the gpu,
1942          * then it should not be waiting long at all, and a sleep now will incur
1943          * extra scheduler latency in producing the next frame. To try to
1944          * avoid adding the cost of enabling/disabling the interrupt to the
1945          * short wait, we first spin to see if the request would have completed
1946          * in the time taken to setup the interrupt.
1947          *
1948          * We need upto 5us to enable the irq, and upto 20us to hide the
1949          * scheduler latency of a context switch, ignoring the secondary
1950          * impacts from a context switch such as cache eviction.
1951          *
1952          * The scheme used for low-latency IO is called "hybrid interrupt
1953          * polling". The suggestion there is to sleep until just before you
1954          * expect to be woken by the device interrupt and then poll for its
1955          * completion. That requires having a good predictor for the request
1956          * duration, which we currently lack.
1957          */
1958         if (CONFIG_DRM_I915_MAX_REQUEST_BUSYWAIT &&
1959             __i915_spin_request(rq, state))
1960                 goto out;
1961
1962         /*
1963          * This client is about to stall waiting for the GPU. In many cases
1964          * this is undesirable and limits the throughput of the system, as
1965          * many clients cannot continue processing user input/output whilst
1966          * blocked. RPS autotuning may take tens of milliseconds to respond
1967          * to the GPU load and thus incurs additional latency for the client.
1968          * We can circumvent that by promoting the GPU frequency to maximum
1969          * before we sleep. This makes the GPU throttle up much more quickly
1970          * (good for benchmarks and user experience, e.g. window animations),
1971          * but at a cost of spending more power processing the workload
1972          * (bad for battery).
1973          */
1974         if (flags & I915_WAIT_PRIORITY && !i915_request_started(rq))
1975                 intel_rps_boost(rq);
1976
1977         wait.tsk = current;
1978         if (dma_fence_add_callback(&rq->fence, &wait.cb, request_wait_wake))
1979                 goto out;
1980
1981         /*
1982          * Flush the submission tasklet, but only if it may help this request.
1983          *
1984          * We sometimes experience some latency between the HW interrupts and
1985          * tasklet execution (mostly due to ksoftirqd latency, but it can also
1986          * be due to lazy CS events), so lets run the tasklet manually if there
1987          * is a chance it may submit this request. If the request is not ready
1988          * to run, as it is waiting for other fences to be signaled, flushing
1989          * the tasklet is busy work without any advantage for this client.
1990          *
1991          * If the HW is being lazy, this is the last chance before we go to
1992          * sleep to catch any pending events. We will check periodically in
1993          * the heartbeat to flush the submission tasklets as a last resort
1994          * for unhappy HW.
1995          */
1996         if (i915_request_is_ready(rq))
1997                 __intel_engine_flush_submission(rq->engine, false);
1998
1999         for (;;) {
2000                 set_current_state(state);
2001
2002                 if (dma_fence_is_signaled(&rq->fence))
2003                         break;
2004
2005                 if (signal_pending_state(state, current)) {
2006                         timeout = -ERESTARTSYS;
2007                         break;
2008                 }
2009
2010                 if (!timeout) {
2011                         timeout = -ETIME;
2012                         break;
2013                 }
2014
2015                 timeout = io_schedule_timeout(timeout);
2016         }
2017         __set_current_state(TASK_RUNNING);
2018
2019         if (READ_ONCE(wait.tsk))
2020                 dma_fence_remove_callback(&rq->fence, &wait.cb);
2021         GEM_BUG_ON(!list_empty(&wait.cb.node));
2022
2023 out:
2024         mutex_release(&rq->engine->gt->reset.mutex.dep_map, _THIS_IP_);
2025         trace_i915_request_wait_end(rq);
2026         return timeout;
2027 }
2028
2029 /**
2030  * i915_request_wait - wait until execution of request has finished
2031  * @rq: the request to wait upon
2032  * @flags: how to wait
2033  * @timeout: how long to wait in jiffies
2034  *
2035  * i915_request_wait() waits for the request to be completed, for a
2036  * maximum of @timeout jiffies (with MAX_SCHEDULE_TIMEOUT implying an
2037  * unbounded wait).
2038  *
2039  * Returns the remaining time (in jiffies) if the request completed, which may
2040  * be zero or -ETIME if the request is unfinished after the timeout expires.
2041  * May return -EINTR is called with I915_WAIT_INTERRUPTIBLE and a signal is
2042  * pending before the request completes.
2043  *
2044  * NOTE: This function behaves differently from dma-fence wait semantics for
2045  * timeout = 0. It returns 0 on success, and -ETIME if not signaled.
2046  */
2047 long i915_request_wait(struct i915_request *rq,
2048                        unsigned int flags,
2049                        long timeout)
2050 {
2051         long ret = i915_request_wait_timeout(rq, flags, timeout);
2052
2053         if (!ret)
2054                 return -ETIME;
2055
2056         if (ret > 0 && !timeout)
2057                 return 0;
2058
2059         return ret;
2060 }
2061
2062 static int print_sched_attr(const struct i915_sched_attr *attr,
2063                             char *buf, int x, int len)
2064 {
2065         if (attr->priority == I915_PRIORITY_INVALID)
2066                 return x;
2067
2068         x += snprintf(buf + x, len - x,
2069                       " prio=%d", attr->priority);
2070
2071         return x;
2072 }
2073
2074 static char queue_status(const struct i915_request *rq)
2075 {
2076         if (i915_request_is_active(rq))
2077                 return 'E';
2078
2079         if (i915_request_is_ready(rq))
2080                 return intel_engine_is_virtual(rq->engine) ? 'V' : 'R';
2081
2082         return 'U';
2083 }
2084
2085 static const char *run_status(const struct i915_request *rq)
2086 {
2087         if (__i915_request_is_complete(rq))
2088                 return "!";
2089
2090         if (__i915_request_has_started(rq))
2091                 return "*";
2092
2093         if (!i915_sw_fence_signaled(&rq->semaphore))
2094                 return "&";
2095
2096         return "";
2097 }
2098
2099 static const char *fence_status(const struct i915_request *rq)
2100 {
2101         if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &rq->fence.flags))
2102                 return "+";
2103
2104         if (test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT, &rq->fence.flags))
2105                 return "-";
2106
2107         return "";
2108 }
2109
2110 void i915_request_show(struct drm_printer *m,
2111                        const struct i915_request *rq,
2112                        const char *prefix,
2113                        int indent)
2114 {
2115         const char *name = rq->fence.ops->get_timeline_name((struct dma_fence *)&rq->fence);
2116         char buf[80] = "";
2117         int x = 0;
2118
2119         /*
2120          * The prefix is used to show the queue status, for which we use
2121          * the following flags:
2122          *
2123          *  U [Unready]
2124          *    - initial status upon being submitted by the user
2125          *
2126          *    - the request is not ready for execution as it is waiting
2127          *      for external fences
2128          *
2129          *  R [Ready]
2130          *    - all fences the request was waiting on have been signaled,
2131          *      and the request is now ready for execution and will be
2132          *      in a backend queue
2133          *
2134          *    - a ready request may still need to wait on semaphores
2135          *      [internal fences]
2136          *
2137          *  V [Ready/virtual]
2138          *    - same as ready, but queued over multiple backends
2139          *
2140          *  E [Executing]
2141          *    - the request has been transferred from the backend queue and
2142          *      submitted for execution on HW
2143          *
2144          *    - a completed request may still be regarded as executing, its
2145          *      status may not be updated until it is retired and removed
2146          *      from the lists
2147          */
2148
2149         x = print_sched_attr(&rq->sched.attr, buf, x, sizeof(buf));
2150
2151         drm_printf(m, "%s%.*s%c %llx:%lld%s%s %s @ %dms: %s\n",
2152                    prefix, indent, "                ",
2153                    queue_status(rq),
2154                    rq->fence.context, rq->fence.seqno,
2155                    run_status(rq),
2156                    fence_status(rq),
2157                    buf,
2158                    jiffies_to_msecs(jiffies - rq->emitted_jiffies),
2159                    name);
2160 }
2161
2162 static bool engine_match_ring(struct intel_engine_cs *engine, struct i915_request *rq)
2163 {
2164         u32 ring = ENGINE_READ(engine, RING_START);
2165
2166         return ring == i915_ggtt_offset(rq->ring->vma);
2167 }
2168
2169 static bool match_ring(struct i915_request *rq)
2170 {
2171         struct intel_engine_cs *engine;
2172         bool found;
2173         int i;
2174
2175         if (!intel_engine_is_virtual(rq->engine))
2176                 return engine_match_ring(rq->engine, rq);
2177
2178         found = false;
2179         i = 0;
2180         while ((engine = intel_engine_get_sibling(rq->engine, i++))) {
2181                 found = engine_match_ring(engine, rq);
2182                 if (found)
2183                         break;
2184         }
2185
2186         return found;
2187 }
2188
2189 enum i915_request_state i915_test_request_state(struct i915_request *rq)
2190 {
2191         if (i915_request_completed(rq))
2192                 return I915_REQUEST_COMPLETE;
2193
2194         if (!i915_request_started(rq))
2195                 return I915_REQUEST_PENDING;
2196
2197         if (match_ring(rq))
2198                 return I915_REQUEST_ACTIVE;
2199
2200         return I915_REQUEST_QUEUED;
2201 }
2202
2203 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
2204 #include "selftests/mock_request.c"
2205 #include "selftests/i915_request.c"
2206 #endif
2207
2208 void i915_request_module_exit(void)
2209 {
2210         kmem_cache_destroy(slab_execute_cbs);
2211         kmem_cache_destroy(slab_requests);
2212 }
2213
2214 int __init i915_request_module_init(void)
2215 {
2216         slab_requests =
2217                 kmem_cache_create("i915_request",
2218                                   sizeof(struct i915_request),
2219                                   __alignof__(struct i915_request),
2220                                   SLAB_HWCACHE_ALIGN |
2221                                   SLAB_RECLAIM_ACCOUNT |
2222                                   SLAB_TYPESAFE_BY_RCU,
2223                                   __i915_request_ctor);
2224         if (!slab_requests)
2225                 return -ENOMEM;
2226
2227         slab_execute_cbs = KMEM_CACHE(execute_cb,
2228                                              SLAB_HWCACHE_ALIGN |
2229                                              SLAB_RECLAIM_ACCOUNT |
2230                                              SLAB_TYPESAFE_BY_RCU);
2231         if (!slab_execute_cbs)
2232                 goto err_requests;
2233
2234         return 0;
2235
2236 err_requests:
2237         kmem_cache_destroy(slab_requests);
2238         return -ENOMEM;
2239 }
This page took 0.181682 seconds and 4 git commands to generate.