2 * Copyright © 2008-2015 Intel Corporation
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:
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
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
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>
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_engine_regs.h"
40 #include "gt/intel_gpu_commands.h"
41 #include "gt/intel_reset.h"
42 #include "gt/intel_ring.h"
43 #include "gt/intel_rps.h"
45 #include "i915_active.h"
46 #include "i915_deps.h"
48 #include "i915_trace.h"
53 struct i915_sw_fence *fence;
54 struct i915_request *signal;
57 static struct kmem_cache *slab_requests;
58 static struct kmem_cache *slab_execute_cbs;
60 static const char *i915_fence_get_driver_name(struct dma_fence *fence)
62 return dev_name(to_request(fence)->engine->i915->drm.dev);
65 static const char *i915_fence_get_timeline_name(struct dma_fence *fence)
67 const struct i915_gem_context *ctx;
70 * The timeline struct (as part of the ppgtt underneath a context)
71 * may be freed when the request is no longer in use by the GPU.
72 * We could extend the life of a context to beyond that of all
73 * fences, possibly keeping the hw resource around indefinitely,
74 * or we just give them a false name. Since
75 * dma_fence_ops.get_timeline_name is a debug feature, the occasional
76 * lie seems justifiable.
78 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
81 ctx = i915_request_gem_context(to_request(fence));
83 return "[" DRIVER_NAME "]";
88 static bool i915_fence_signaled(struct dma_fence *fence)
90 return i915_request_completed(to_request(fence));
93 static bool i915_fence_enable_signaling(struct dma_fence *fence)
95 return i915_request_enable_breadcrumb(to_request(fence));
98 static signed long i915_fence_wait(struct dma_fence *fence,
102 return i915_request_wait_timeout(to_request(fence),
103 interruptible | I915_WAIT_PRIORITY,
107 struct kmem_cache *i915_request_slab_cache(void)
109 return slab_requests;
112 static void i915_fence_release(struct dma_fence *fence)
114 struct i915_request *rq = to_request(fence);
116 GEM_BUG_ON(rq->guc_prio != GUC_PRIO_INIT &&
117 rq->guc_prio != GUC_PRIO_FINI);
119 i915_request_free_capture_list(fetch_and_zero(&rq->capture_list));
120 if (i915_vma_snapshot_present(&rq->batch_snapshot))
121 i915_vma_snapshot_put_onstack(&rq->batch_snapshot);
124 * The request is put onto a RCU freelist (i.e. the address
125 * is immediately reused), mark the fences as being freed now.
126 * Otherwise the debugobjects for the fences are only marked as
127 * freed when the slab cache itself is freed, and so we would get
128 * caught trying to reuse dead objects.
130 i915_sw_fence_fini(&rq->submit);
131 i915_sw_fence_fini(&rq->semaphore);
134 * Keep one request on each engine for reserved use under mempressure,
135 * do not use with virtual engines as this really is only needed for
138 if (!intel_engine_is_virtual(rq->engine) &&
139 !cmpxchg(&rq->engine->request_pool, NULL, rq)) {
140 intel_context_put(rq->context);
144 intel_context_put(rq->context);
146 kmem_cache_free(slab_requests, rq);
149 const struct dma_fence_ops i915_fence_ops = {
150 .get_driver_name = i915_fence_get_driver_name,
151 .get_timeline_name = i915_fence_get_timeline_name,
152 .enable_signaling = i915_fence_enable_signaling,
153 .signaled = i915_fence_signaled,
154 .wait = i915_fence_wait,
155 .release = i915_fence_release,
158 static void irq_execute_cb(struct irq_work *wrk)
160 struct execute_cb *cb = container_of(wrk, typeof(*cb), work);
162 i915_sw_fence_complete(cb->fence);
163 kmem_cache_free(slab_execute_cbs, cb);
166 static __always_inline void
167 __notify_execute_cb(struct i915_request *rq, bool (*fn)(struct irq_work *wrk))
169 struct execute_cb *cb, *cn;
171 if (llist_empty(&rq->execute_cb))
174 llist_for_each_entry_safe(cb, cn,
175 llist_del_all(&rq->execute_cb),
180 static void __notify_execute_cb_irq(struct i915_request *rq)
182 __notify_execute_cb(rq, irq_work_queue);
185 static bool irq_work_imm(struct irq_work *wrk)
191 void i915_request_notify_execute_cb_imm(struct i915_request *rq)
193 __notify_execute_cb(rq, irq_work_imm);
196 static void __i915_request_fill(struct i915_request *rq, u8 val)
198 void *vaddr = rq->ring->vaddr;
202 if (rq->postfix < head) {
203 memset(vaddr + head, val, rq->ring->size - head);
206 memset(vaddr + head, val, rq->postfix - head);
210 * i915_request_active_engine
211 * @rq: request to inspect
212 * @active: pointer in which to return the active engine
214 * Fills the currently active engine to the @active pointer if the request
215 * is active and still not completed.
217 * Returns true if request was active or false otherwise.
220 i915_request_active_engine(struct i915_request *rq,
221 struct intel_engine_cs **active)
223 struct intel_engine_cs *engine, *locked;
227 * Serialise with __i915_request_submit() so that it sees
228 * is-banned?, or we know the request is already inflight.
230 * Note that rq->engine is unstable, and so we double
231 * check that we have acquired the lock on the final engine.
233 locked = READ_ONCE(rq->engine);
234 spin_lock_irq(&locked->sched_engine->lock);
235 while (unlikely(locked != (engine = READ_ONCE(rq->engine)))) {
236 spin_unlock(&locked->sched_engine->lock);
238 spin_lock(&locked->sched_engine->lock);
241 if (i915_request_is_active(rq)) {
242 if (!__i915_request_is_complete(rq))
247 spin_unlock_irq(&locked->sched_engine->lock);
252 static void __rq_init_watchdog(struct i915_request *rq)
254 rq->watchdog.timer.function = NULL;
257 static enum hrtimer_restart __rq_watchdog_expired(struct hrtimer *hrtimer)
259 struct i915_request *rq =
260 container_of(hrtimer, struct i915_request, watchdog.timer);
261 struct intel_gt *gt = rq->engine->gt;
263 if (!i915_request_completed(rq)) {
264 if (llist_add(&rq->watchdog.link, >->watchdog.list))
265 schedule_work(>->watchdog.work);
267 i915_request_put(rq);
270 return HRTIMER_NORESTART;
273 static void __rq_arm_watchdog(struct i915_request *rq)
275 struct i915_request_watchdog *wdg = &rq->watchdog;
276 struct intel_context *ce = rq->context;
278 if (!ce->watchdog.timeout_us)
281 i915_request_get(rq);
283 hrtimer_init(&wdg->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
284 wdg->timer.function = __rq_watchdog_expired;
285 hrtimer_start_range_ns(&wdg->timer,
286 ns_to_ktime(ce->watchdog.timeout_us *
292 static void __rq_cancel_watchdog(struct i915_request *rq)
294 struct i915_request_watchdog *wdg = &rq->watchdog;
296 if (wdg->timer.function && hrtimer_try_to_cancel(&wdg->timer) > 0)
297 i915_request_put(rq);
300 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
303 * i915_request_free_capture_list - Free a capture list
304 * @capture: Pointer to the first list item or NULL
307 void i915_request_free_capture_list(struct i915_capture_list *capture)
310 struct i915_capture_list *next = capture->next;
312 i915_vma_snapshot_put(capture->vma_snapshot);
318 #define assert_capture_list_is_null(_rq) GEM_BUG_ON((_rq)->capture_list)
320 #define clear_capture_list(_rq) ((_rq)->capture_list = NULL)
324 #define i915_request_free_capture_list(_a) do {} while (0)
326 #define assert_capture_list_is_null(_a) do {} while (0)
328 #define clear_capture_list(_rq) do {} while (0)
332 bool i915_request_retire(struct i915_request *rq)
334 if (!__i915_request_is_complete(rq))
339 GEM_BUG_ON(!i915_sw_fence_signaled(&rq->submit));
340 trace_i915_request_retire(rq);
341 i915_request_mark_complete(rq);
343 __rq_cancel_watchdog(rq);
346 * We know the GPU must have read the request to have
347 * sent us the seqno + interrupt, so use the position
348 * of tail of the request to update the last known position
351 * Note this requires that we are always called in request
354 GEM_BUG_ON(!list_is_first(&rq->link,
355 &i915_request_timeline(rq)->requests));
356 if (IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM))
357 /* Poison before we release our space in the ring */
358 __i915_request_fill(rq, POISON_FREE);
359 rq->ring->head = rq->postfix;
361 if (!i915_request_signaled(rq)) {
362 spin_lock_irq(&rq->lock);
363 dma_fence_signal_locked(&rq->fence);
364 spin_unlock_irq(&rq->lock);
367 if (test_and_set_bit(I915_FENCE_FLAG_BOOST, &rq->fence.flags))
368 intel_rps_dec_waiters(&rq->engine->gt->rps);
371 * We only loosely track inflight requests across preemption,
372 * and so we may find ourselves attempting to retire a _completed_
373 * request that we have removed from the HW and put back on a run
376 * As we set I915_FENCE_FLAG_ACTIVE on the request, this should be
377 * after removing the breadcrumb and signaling it, so that we do not
378 * inadvertently attach the breadcrumb to a completed request.
380 rq->engine->remove_active_request(rq);
381 GEM_BUG_ON(!llist_empty(&rq->execute_cb));
383 __list_del_entry(&rq->link); /* poison neither prev/next (RCU walks) */
385 intel_context_exit(rq->context);
386 intel_context_unpin(rq->context);
388 i915_sched_node_fini(&rq->sched);
389 i915_request_put(rq);
394 void i915_request_retire_upto(struct i915_request *rq)
396 struct intel_timeline * const tl = i915_request_timeline(rq);
397 struct i915_request *tmp;
400 GEM_BUG_ON(!__i915_request_is_complete(rq));
403 tmp = list_first_entry(&tl->requests, typeof(*tmp), link);
404 GEM_BUG_ON(!i915_request_completed(tmp));
405 } while (i915_request_retire(tmp) && tmp != rq);
408 static struct i915_request * const *
409 __engine_active(struct intel_engine_cs *engine)
411 return READ_ONCE(engine->execlists.active);
414 static bool __request_in_flight(const struct i915_request *signal)
416 struct i915_request * const *port, *rq;
417 bool inflight = false;
419 if (!i915_request_is_ready(signal))
423 * Even if we have unwound the request, it may still be on
424 * the GPU (preempt-to-busy). If that request is inside an
425 * unpreemptible critical section, it will not be removed. Some
426 * GPU functions may even be stuck waiting for the paired request
427 * (__await_execution) to be submitted and cannot be preempted
428 * until the bond is executing.
430 * As we know that there are always preemption points between
431 * requests, we know that only the currently executing request
432 * may be still active even though we have cleared the flag.
433 * However, we can't rely on our tracking of ELSP[0] to know
434 * which request is currently active and so maybe stuck, as
435 * the tracking maybe an event behind. Instead assume that
436 * if the context is still inflight, then it is still active
437 * even if the active flag has been cleared.
439 * To further complicate matters, if there a pending promotion, the HW
440 * may either perform a context switch to the second inflight execlists,
441 * or it may switch to the pending set of execlists. In the case of the
442 * latter, it may send the ACK and we process the event copying the
443 * pending[] over top of inflight[], _overwriting_ our *active. Since
444 * this implies the HW is arbitrating and not struck in *active, we do
445 * not worry about complete accuracy, but we do require no read/write
446 * tearing of the pointer [the read of the pointer must be valid, even
447 * as the array is being overwritten, for which we require the writes
450 * Note that the read of *execlists->active may race with the promotion
451 * of execlists->pending[] to execlists->inflight[], overwritting
452 * the value at *execlists->active. This is fine. The promotion implies
453 * that we received an ACK from the HW, and so the context is not
454 * stuck -- if we do not see ourselves in *active, the inflight status
455 * is valid. If instead we see ourselves being copied into *active,
456 * we are inflight and may signal the callback.
458 if (!intel_context_inflight(signal->context))
462 for (port = __engine_active(signal->engine);
463 (rq = READ_ONCE(*port)); /* may race with promotion of pending[] */
465 if (rq->context == signal->context) {
466 inflight = i915_seqno_passed(rq->fence.seqno,
467 signal->fence.seqno);
477 __await_execution(struct i915_request *rq,
478 struct i915_request *signal,
481 struct execute_cb *cb;
483 if (i915_request_is_active(signal))
486 cb = kmem_cache_alloc(slab_execute_cbs, gfp);
490 cb->fence = &rq->submit;
491 i915_sw_fence_await(cb->fence);
492 init_irq_work(&cb->work, irq_execute_cb);
495 * Register the callback first, then see if the signaler is already
496 * active. This ensures that if we race with the
497 * __notify_execute_cb from i915_request_submit() and we are not
498 * included in that list, we get a second bite of the cherry and
499 * execute it ourselves. After this point, a future
500 * i915_request_submit() will notify us.
502 * In i915_request_retire() we set the ACTIVE bit on a completed
503 * request (then flush the execute_cb). So by registering the
504 * callback first, then checking the ACTIVE bit, we serialise with
505 * the completed/retired request.
507 if (llist_add(&cb->work.node.llist, &signal->execute_cb)) {
508 if (i915_request_is_active(signal) ||
509 __request_in_flight(signal))
510 i915_request_notify_execute_cb_imm(signal);
516 static bool fatal_error(int error)
519 case 0: /* not an error! */
520 case -EAGAIN: /* innocent victim of a GT reset (__i915_request_reset) */
521 case -ETIMEDOUT: /* waiting for Godot (timer_i915_sw_fence_wake) */
528 void __i915_request_skip(struct i915_request *rq)
530 GEM_BUG_ON(!fatal_error(rq->fence.error));
532 if (rq->infix == rq->postfix)
535 RQ_TRACE(rq, "error: %d\n", rq->fence.error);
538 * As this request likely depends on state from the lost
539 * context, clear out all the user operations leaving the
540 * breadcrumb at the end (so we get the fence notifications).
542 __i915_request_fill(rq, 0);
543 rq->infix = rq->postfix;
546 bool i915_request_set_error_once(struct i915_request *rq, int error)
550 GEM_BUG_ON(!IS_ERR_VALUE((long)error));
552 if (i915_request_signaled(rq))
555 old = READ_ONCE(rq->fence.error);
557 if (fatal_error(old))
559 } while (!try_cmpxchg(&rq->fence.error, &old, error));
564 struct i915_request *i915_request_mark_eio(struct i915_request *rq)
566 if (__i915_request_is_complete(rq))
569 GEM_BUG_ON(i915_request_signaled(rq));
571 /* As soon as the request is completed, it may be retired */
572 rq = i915_request_get(rq);
574 i915_request_set_error_once(rq, -EIO);
575 i915_request_mark_complete(rq);
580 bool __i915_request_submit(struct i915_request *request)
582 struct intel_engine_cs *engine = request->engine;
585 RQ_TRACE(request, "\n");
587 GEM_BUG_ON(!irqs_disabled());
588 lockdep_assert_held(&engine->sched_engine->lock);
591 * With the advent of preempt-to-busy, we frequently encounter
592 * requests that we have unsubmitted from HW, but left running
593 * until the next ack and so have completed in the meantime. On
594 * resubmission of that completed request, we can skip
595 * updating the payload, and execlists can even skip submitting
598 * We must remove the request from the caller's priority queue,
599 * and the caller must only call us when the request is in their
600 * priority queue, under the sched_engine->lock. This ensures that the
601 * request has *not* yet been retired and we can safely move
602 * the request into the engine->active.list where it will be
603 * dropped upon retiring. (Otherwise if resubmit a *retired*
604 * request, this would be a horrible use-after-free.)
606 if (__i915_request_is_complete(request)) {
607 list_del_init(&request->sched.link);
611 if (unlikely(intel_context_is_banned(request->context)))
612 i915_request_set_error_once(request, -EIO);
614 if (unlikely(fatal_error(request->fence.error)))
615 __i915_request_skip(request);
618 * Are we using semaphores when the gpu is already saturated?
620 * Using semaphores incurs a cost in having the GPU poll a
621 * memory location, busywaiting for it to change. The continual
622 * memory reads can have a noticeable impact on the rest of the
623 * system with the extra bus traffic, stalling the cpu as it too
624 * tries to access memory across the bus (perf stat -e bus-cycles).
626 * If we installed a semaphore on this request and we only submit
627 * the request after the signaler completed, that indicates the
628 * system is overloaded and using semaphores at this time only
629 * increases the amount of work we are doing. If so, we disable
630 * further use of semaphores until we are idle again, whence we
631 * optimistically try again.
633 if (request->sched.semaphores &&
634 i915_sw_fence_signaled(&request->semaphore))
635 engine->saturated |= request->sched.semaphores;
637 engine->emit_fini_breadcrumb(request,
638 request->ring->vaddr + request->postfix);
640 trace_i915_request_execute(request);
641 if (engine->bump_serial)
642 engine->bump_serial(engine);
648 GEM_BUG_ON(test_bit(I915_FENCE_FLAG_ACTIVE, &request->fence.flags));
649 engine->add_active_request(request);
651 clear_bit(I915_FENCE_FLAG_PQUEUE, &request->fence.flags);
652 set_bit(I915_FENCE_FLAG_ACTIVE, &request->fence.flags);
655 * XXX Rollback bonded-execution on __i915_request_unsubmit()?
657 * In the future, perhaps when we have an active time-slicing scheduler,
658 * it will be interesting to unsubmit parallel execution and remove
659 * busywaits from the GPU until their master is restarted. This is
660 * quite hairy, we have to carefully rollback the fence and do a
661 * preempt-to-idle cycle on the target engine, all the while the
662 * master execute_cb may refire.
664 __notify_execute_cb_irq(request);
666 /* We may be recursing from the signal callback of another i915 fence */
667 if (test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT, &request->fence.flags))
668 i915_request_enable_breadcrumb(request);
673 void i915_request_submit(struct i915_request *request)
675 struct intel_engine_cs *engine = request->engine;
678 /* Will be called from irq-context when using foreign fences. */
679 spin_lock_irqsave(&engine->sched_engine->lock, flags);
681 __i915_request_submit(request);
683 spin_unlock_irqrestore(&engine->sched_engine->lock, flags);
686 void __i915_request_unsubmit(struct i915_request *request)
688 struct intel_engine_cs *engine = request->engine;
691 * Only unwind in reverse order, required so that the per-context list
692 * is kept in seqno/ring order.
694 RQ_TRACE(request, "\n");
696 GEM_BUG_ON(!irqs_disabled());
697 lockdep_assert_held(&engine->sched_engine->lock);
700 * Before we remove this breadcrumb from the signal list, we have
701 * to ensure that a concurrent dma_fence_enable_signaling() does not
702 * attach itself. We first mark the request as no longer active and
703 * make sure that is visible to other cores, and then remove the
704 * breadcrumb if attached.
706 GEM_BUG_ON(!test_bit(I915_FENCE_FLAG_ACTIVE, &request->fence.flags));
707 clear_bit_unlock(I915_FENCE_FLAG_ACTIVE, &request->fence.flags);
708 if (test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT, &request->fence.flags))
709 i915_request_cancel_breadcrumb(request);
711 /* We've already spun, don't charge on resubmitting. */
712 if (request->sched.semaphores && __i915_request_has_started(request))
713 request->sched.semaphores = 0;
716 * We don't need to wake_up any waiters on request->execute, they
717 * will get woken by any other event or us re-adding this request
718 * to the engine timeline (__i915_request_submit()). The waiters
719 * should be quite adapt at finding that the request now has a new
720 * global_seqno to the one they went to sleep on.
724 void i915_request_unsubmit(struct i915_request *request)
726 struct intel_engine_cs *engine = request->engine;
729 /* Will be called from irq-context when using foreign fences. */
730 spin_lock_irqsave(&engine->sched_engine->lock, flags);
732 __i915_request_unsubmit(request);
734 spin_unlock_irqrestore(&engine->sched_engine->lock, flags);
737 void i915_request_cancel(struct i915_request *rq, int error)
739 if (!i915_request_set_error_once(rq, error))
742 set_bit(I915_FENCE_FLAG_SENTINEL, &rq->fence.flags);
744 intel_context_cancel_request(rq->context, rq);
748 submit_notify(struct i915_sw_fence *fence, enum i915_sw_fence_notify state)
750 struct i915_request *request =
751 container_of(fence, typeof(*request), submit);
755 trace_i915_request_submit(request);
757 if (unlikely(fence->error))
758 i915_request_set_error_once(request, fence->error);
760 __rq_arm_watchdog(request);
763 * We need to serialize use of the submit_request() callback
764 * with its hotplugging performed during an emergency
765 * i915_gem_set_wedged(). We use the RCU mechanism to mark the
766 * critical section in order to force i915_gem_set_wedged() to
767 * wait until the submit_request() is completed before
771 request->engine->submit_request(request);
776 i915_request_put(request);
784 semaphore_notify(struct i915_sw_fence *fence, enum i915_sw_fence_notify state)
786 struct i915_request *rq = container_of(fence, typeof(*rq), semaphore);
793 i915_request_put(rq);
800 static void retire_requests(struct intel_timeline *tl)
802 struct i915_request *rq, *rn;
804 list_for_each_entry_safe(rq, rn, &tl->requests, link)
805 if (!i915_request_retire(rq))
809 static noinline struct i915_request *
810 request_alloc_slow(struct intel_timeline *tl,
811 struct i915_request **rsvd,
814 struct i915_request *rq;
816 /* If we cannot wait, dip into our reserves */
817 if (!gfpflags_allow_blocking(gfp)) {
818 rq = xchg(rsvd, NULL);
819 if (!rq) /* Use the normal failure path for one final WARN */
825 if (list_empty(&tl->requests))
828 /* Move our oldest request to the slab-cache (if not in use!) */
829 rq = list_first_entry(&tl->requests, typeof(*rq), link);
830 i915_request_retire(rq);
832 rq = kmem_cache_alloc(slab_requests,
833 gfp | __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
837 /* Ratelimit ourselves to prevent oom from malicious clients */
838 rq = list_last_entry(&tl->requests, typeof(*rq), link);
839 cond_synchronize_rcu(rq->rcustate);
841 /* Retire our old requests in the hope that we free some */
845 return kmem_cache_alloc(slab_requests, gfp);
848 static void __i915_request_ctor(void *arg)
850 struct i915_request *rq = arg;
852 spin_lock_init(&rq->lock);
853 i915_sched_node_init(&rq->sched);
854 i915_sw_fence_init(&rq->submit, submit_notify);
855 i915_sw_fence_init(&rq->semaphore, semaphore_notify);
857 clear_capture_list(rq);
858 rq->batch_snapshot.present = false;
860 init_llist_head(&rq->execute_cb);
863 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
864 #define clear_batch_ptr(_rq) ((_rq)->batch = NULL)
866 #define clear_batch_ptr(_a) do {} while (0)
869 struct i915_request *
870 __i915_request_create(struct intel_context *ce, gfp_t gfp)
872 struct intel_timeline *tl = ce->timeline;
873 struct i915_request *rq;
879 /* Check that the caller provided an already pinned context */
880 __intel_context_pin(ce);
883 * Beware: Dragons be flying overhead.
885 * We use RCU to look up requests in flight. The lookups may
886 * race with the request being allocated from the slab freelist.
887 * That is the request we are writing to here, may be in the process
888 * of being read by __i915_active_request_get_rcu(). As such,
889 * we have to be very careful when overwriting the contents. During
890 * the RCU lookup, we change chase the request->engine pointer,
891 * read the request->global_seqno and increment the reference count.
893 * The reference count is incremented atomically. If it is zero,
894 * the lookup knows the request is unallocated and complete. Otherwise,
895 * it is either still in use, or has been reallocated and reset
896 * with dma_fence_init(). This increment is safe for release as we
897 * check that the request we have a reference to and matches the active
900 * Before we increment the refcount, we chase the request->engine
901 * pointer. We must not call kmem_cache_zalloc() or else we set
902 * that pointer to NULL and cause a crash during the lookup. If
903 * we see the request is completed (based on the value of the
904 * old engine and seqno), the lookup is complete and reports NULL.
905 * If we decide the request is not completed (new engine or seqno),
906 * then we grab a reference and double check that it is still the
907 * active request - which it won't be and restart the lookup.
909 * Do not use kmem_cache_zalloc() here!
911 rq = kmem_cache_alloc(slab_requests,
912 gfp | __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
914 rq = request_alloc_slow(tl, &ce->engine->request_pool, gfp);
922 * Hold a reference to the intel_context over life of an i915_request.
923 * Without this an i915_request can exist after the context has been
924 * destroyed (e.g. request retired, context closed, but user space holds
925 * a reference to the request from an out fence). In the case of GuC
926 * submission + virtual engine, the engine that the request references
927 * is also destroyed which can trigger bad pointer dref in fence ops
928 * (e.g. i915_fence_get_driver_name). We could likely change these
929 * functions to avoid touching the engine but let's just be safe and
930 * hold the intel_context reference. In execlist mode the request always
931 * eventually points to a physical engine so this isn't an issue.
933 rq->context = intel_context_get(ce);
934 rq->engine = ce->engine;
936 rq->execution_mask = ce->engine->mask;
938 ret = intel_timeline_get_seqno(tl, rq, &seqno);
942 dma_fence_init(&rq->fence, &i915_fence_ops, &rq->lock,
943 tl->fence_context, seqno);
945 RCU_INIT_POINTER(rq->timeline, tl);
946 rq->hwsp_seqno = tl->hwsp_seqno;
947 GEM_BUG_ON(__i915_request_is_complete(rq));
949 rq->rcustate = get_state_synchronize_rcu(); /* acts as smp_mb() */
951 rq->guc_prio = GUC_PRIO_INIT;
953 /* We bump the ref for the fence chain */
954 i915_sw_fence_reinit(&i915_request_get(rq)->submit);
955 i915_sw_fence_reinit(&i915_request_get(rq)->semaphore);
957 i915_sched_node_reinit(&rq->sched);
959 /* No zalloc, everything must be cleared after use */
961 __rq_init_watchdog(rq);
962 assert_capture_list_is_null(rq);
963 GEM_BUG_ON(!llist_empty(&rq->execute_cb));
964 GEM_BUG_ON(i915_vma_snapshot_present(&rq->batch_snapshot));
967 * Reserve space in the ring buffer for all the commands required to
968 * eventually emit this request. This is to guarantee that the
969 * i915_request_add() call can't fail. Note that the reserve may need
970 * to be redone if the request is not actually submitted straight
971 * away, e.g. because a GPU scheduler has deferred it.
973 * Note that due to how we add reserved_space to intel_ring_begin()
974 * we need to double our request to ensure that if we need to wrap
975 * around inside i915_request_add() there is sufficient space at
976 * the beginning of the ring as well.
979 2 * rq->engine->emit_fini_breadcrumb_dw * sizeof(u32);
982 * Record the position of the start of the request so that
983 * should we detect the updated seqno part-way through the
984 * GPU processing the request, we never over-estimate the
985 * position of the head.
987 rq->head = rq->ring->emit;
989 ret = rq->engine->request_alloc(rq);
993 rq->infix = rq->ring->emit; /* end of header; start of user payload */
995 intel_context_mark_active(ce);
996 list_add_tail_rcu(&rq->link, &tl->requests);
1001 ce->ring->emit = rq->head;
1003 /* Make sure we didn't add ourselves to external state before freeing */
1004 GEM_BUG_ON(!list_empty(&rq->sched.signalers_list));
1005 GEM_BUG_ON(!list_empty(&rq->sched.waiters_list));
1008 intel_context_put(ce);
1009 kmem_cache_free(slab_requests, rq);
1011 intel_context_unpin(ce);
1012 return ERR_PTR(ret);
1015 struct i915_request *
1016 i915_request_create(struct intel_context *ce)
1018 struct i915_request *rq;
1019 struct intel_timeline *tl;
1021 tl = intel_context_timeline_lock(ce);
1023 return ERR_CAST(tl);
1025 /* Move our oldest request to the slab-cache (if not in use!) */
1026 rq = list_first_entry(&tl->requests, typeof(*rq), link);
1027 if (!list_is_last(&rq->link, &tl->requests))
1028 i915_request_retire(rq);
1030 intel_context_enter(ce);
1031 rq = __i915_request_create(ce, GFP_KERNEL);
1032 intel_context_exit(ce); /* active reference transferred to request */
1036 /* Check that we do not interrupt ourselves with a new request */
1037 rq->cookie = lockdep_pin_lock(&tl->mutex);
1042 intel_context_timeline_unlock(tl);
1047 i915_request_await_start(struct i915_request *rq, struct i915_request *signal)
1049 struct dma_fence *fence;
1052 if (i915_request_timeline(rq) == rcu_access_pointer(signal->timeline))
1055 if (i915_request_started(signal))
1059 * The caller holds a reference on @signal, but we do not serialise
1060 * against it being retired and removed from the lists.
1062 * We do not hold a reference to the request before @signal, and
1063 * so must be very careful to ensure that it is not _recycled_ as
1064 * we follow the link backwards.
1069 struct list_head *pos = READ_ONCE(signal->link.prev);
1070 struct i915_request *prev;
1072 /* Confirm signal has not been retired, the link is valid */
1073 if (unlikely(__i915_request_has_started(signal)))
1076 /* Is signal the earliest request on its timeline? */
1077 if (pos == &rcu_dereference(signal->timeline)->requests)
1081 * Peek at the request before us in the timeline. That
1082 * request will only be valid before it is retired, so
1083 * after acquiring a reference to it, confirm that it is
1084 * still part of the signaler's timeline.
1086 prev = list_entry(pos, typeof(*prev), link);
1087 if (!i915_request_get_rcu(prev))
1090 /* After the strong barrier, confirm prev is still attached */
1091 if (unlikely(READ_ONCE(prev->link.next) != &signal->link)) {
1092 i915_request_put(prev);
1096 fence = &prev->fence;
1103 if (!intel_timeline_sync_is_later(i915_request_timeline(rq), fence))
1104 err = i915_sw_fence_await_dma_fence(&rq->submit,
1107 dma_fence_put(fence);
1112 static intel_engine_mask_t
1113 already_busywaiting(struct i915_request *rq)
1116 * Polling a semaphore causes bus traffic, delaying other users of
1117 * both the GPU and CPU. We want to limit the impact on others,
1118 * while taking advantage of early submission to reduce GPU
1119 * latency. Therefore we restrict ourselves to not using more
1120 * than one semaphore from each source, and not using a semaphore
1121 * if we have detected the engine is saturated (i.e. would not be
1122 * submitted early and cause bus traffic reading an already passed
1125 * See the are-we-too-late? check in __i915_request_submit().
1127 return rq->sched.semaphores | READ_ONCE(rq->engine->saturated);
1131 __emit_semaphore_wait(struct i915_request *to,
1132 struct i915_request *from,
1135 const int has_token = GRAPHICS_VER(to->engine->i915) >= 12;
1140 GEM_BUG_ON(GRAPHICS_VER(to->engine->i915) < 8);
1141 GEM_BUG_ON(i915_request_has_initial_breadcrumb(to));
1143 /* We need to pin the signaler's HWSP until we are finished reading. */
1144 err = intel_timeline_read_hwsp(from, to, &hwsp_offset);
1152 cs = intel_ring_begin(to, len);
1157 * Using greater-than-or-equal here means we have to worry
1158 * about seqno wraparound. To side step that issue, we swap
1159 * the timeline HWSP upon wrapping, so that everyone listening
1160 * for the old (pre-wrap) values do not see the much smaller
1161 * (post-wrap) values than they were expecting (and so wait
1164 *cs++ = (MI_SEMAPHORE_WAIT |
1165 MI_SEMAPHORE_GLOBAL_GTT |
1167 MI_SEMAPHORE_SAD_GTE_SDD) +
1170 *cs++ = hwsp_offset;
1177 intel_ring_advance(to, cs);
1182 can_use_semaphore_wait(struct i915_request *to, struct i915_request *from)
1184 return to->engine->gt->ggtt == from->engine->gt->ggtt;
1188 emit_semaphore_wait(struct i915_request *to,
1189 struct i915_request *from,
1192 const intel_engine_mask_t mask = READ_ONCE(from->engine)->mask;
1193 struct i915_sw_fence *wait = &to->submit;
1195 if (!can_use_semaphore_wait(to, from))
1198 if (!intel_context_use_semaphores(to->context))
1201 if (i915_request_has_initial_breadcrumb(to))
1205 * If this or its dependents are waiting on an external fence
1206 * that may fail catastrophically, then we want to avoid using
1207 * sempahores as they bypass the fence signaling metadata, and we
1208 * lose the fence->error propagation.
1210 if (from->sched.flags & I915_SCHED_HAS_EXTERNAL_CHAIN)
1213 /* Just emit the first semaphore we see as request space is limited. */
1214 if (already_busywaiting(to) & mask)
1217 if (i915_request_await_start(to, from) < 0)
1220 /* Only submit our spinner after the signaler is running! */
1221 if (__await_execution(to, from, gfp))
1224 if (__emit_semaphore_wait(to, from, from->fence.seqno))
1227 to->sched.semaphores |= mask;
1228 wait = &to->semaphore;
1231 return i915_sw_fence_await_dma_fence(wait,
1236 static bool intel_timeline_sync_has_start(struct intel_timeline *tl,
1237 struct dma_fence *fence)
1239 return __intel_timeline_sync_is_later(tl,
1244 static int intel_timeline_sync_set_start(struct intel_timeline *tl,
1245 const struct dma_fence *fence)
1247 return __intel_timeline_sync_set(tl, fence->context, fence->seqno - 1);
1251 __i915_request_await_execution(struct i915_request *to,
1252 struct i915_request *from)
1256 GEM_BUG_ON(intel_context_is_barrier(from->context));
1258 /* Submit both requests at the same time */
1259 err = __await_execution(to, from, I915_FENCE_GFP);
1263 /* Squash repeated depenendices to the same timelines */
1264 if (intel_timeline_sync_has_start(i915_request_timeline(to),
1269 * Wait until the start of this request.
1271 * The execution cb fires when we submit the request to HW. But in
1272 * many cases this may be long before the request itself is ready to
1273 * run (consider that we submit 2 requests for the same context, where
1274 * the request of interest is behind an indefinite spinner). So we hook
1275 * up to both to reduce our queues and keep the execution lag minimised
1276 * in the worst case, though we hope that the await_start is elided.
1278 err = i915_request_await_start(to, from);
1283 * Ensure both start together [after all semaphores in signal]
1285 * Now that we are queued to the HW at roughly the same time (thanks
1286 * to the execute cb) and are ready to run at roughly the same time
1287 * (thanks to the await start), our signaler may still be indefinitely
1288 * delayed by waiting on a semaphore from a remote engine. If our
1289 * signaler depends on a semaphore, so indirectly do we, and we do not
1290 * want to start our payload until our signaler also starts theirs.
1293 * However, there is also a second condition for which we need to wait
1294 * for the precise start of the signaler. Consider that the signaler
1295 * was submitted in a chain of requests following another context
1296 * (with just an ordinary intra-engine fence dependency between the
1297 * two). In this case the signaler is queued to HW, but not for
1298 * immediate execution, and so we must wait until it reaches the
1301 if (can_use_semaphore_wait(to, from) &&
1302 intel_engine_has_semaphores(to->engine) &&
1303 !i915_request_has_initial_breadcrumb(to)) {
1304 err = __emit_semaphore_wait(to, from, from->fence.seqno - 1);
1309 /* Couple the dependency tree for PI on this exposed to->fence */
1310 if (to->engine->sched_engine->schedule) {
1311 err = i915_sched_node_add_dependency(&to->sched,
1313 I915_DEPENDENCY_WEAK);
1318 return intel_timeline_sync_set_start(i915_request_timeline(to),
1322 static void mark_external(struct i915_request *rq)
1325 * The downside of using semaphores is that we lose metadata passing
1326 * along the signaling chain. This is particularly nasty when we
1327 * need to pass along a fatal error such as EFAULT or EDEADLK. For
1328 * fatal errors we want to scrub the request before it is executed,
1329 * which means that we cannot preload the request onto HW and have
1330 * it wait upon a semaphore.
1332 rq->sched.flags |= I915_SCHED_HAS_EXTERNAL_CHAIN;
1336 __i915_request_await_external(struct i915_request *rq, struct dma_fence *fence)
1339 return i915_sw_fence_await_dma_fence(&rq->submit, fence,
1340 i915_fence_context_timeout(rq->engine->i915,
1346 i915_request_await_external(struct i915_request *rq, struct dma_fence *fence)
1348 struct dma_fence *iter;
1351 if (!to_dma_fence_chain(fence))
1352 return __i915_request_await_external(rq, fence);
1354 dma_fence_chain_for_each(iter, fence) {
1355 struct dma_fence_chain *chain = to_dma_fence_chain(iter);
1357 if (!dma_fence_is_i915(chain->fence)) {
1358 err = __i915_request_await_external(rq, iter);
1362 err = i915_request_await_dma_fence(rq, chain->fence);
1367 dma_fence_put(iter);
1371 static inline bool is_parallel_rq(struct i915_request *rq)
1373 return intel_context_is_parallel(rq->context);
1376 static inline struct intel_context *request_to_parent(struct i915_request *rq)
1378 return intel_context_to_parent(rq->context);
1381 static bool is_same_parallel_context(struct i915_request *to,
1382 struct i915_request *from)
1384 if (is_parallel_rq(to))
1385 return request_to_parent(to) == request_to_parent(from);
1391 i915_request_await_execution(struct i915_request *rq,
1392 struct dma_fence *fence)
1394 struct dma_fence **child = &fence;
1395 unsigned int nchild = 1;
1398 if (dma_fence_is_array(fence)) {
1399 struct dma_fence_array *array = to_dma_fence_array(fence);
1401 /* XXX Error for signal-on-any fence arrays */
1403 child = array->fences;
1404 nchild = array->num_fences;
1405 GEM_BUG_ON(!nchild);
1410 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
1413 if (fence->context == rq->fence.context)
1417 * We don't squash repeated fence dependencies here as we
1418 * want to run our callback in all cases.
1421 if (dma_fence_is_i915(fence)) {
1422 if (is_same_parallel_context(rq, to_request(fence)))
1424 ret = __i915_request_await_execution(rq,
1427 ret = i915_request_await_external(rq, fence);
1437 await_request_submit(struct i915_request *to, struct i915_request *from)
1440 * If we are waiting on a virtual engine, then it may be
1441 * constrained to execute on a single engine *prior* to submission.
1442 * When it is submitted, it will be first submitted to the virtual
1443 * engine and then passed to the physical engine. We cannot allow
1444 * the waiter to be submitted immediately to the physical engine
1445 * as it may then bypass the virtual request.
1447 if (to->engine == READ_ONCE(from->engine))
1448 return i915_sw_fence_await_sw_fence_gfp(&to->submit,
1452 return __i915_request_await_execution(to, from);
1456 i915_request_await_request(struct i915_request *to, struct i915_request *from)
1460 GEM_BUG_ON(to == from);
1461 GEM_BUG_ON(to->timeline == from->timeline);
1463 if (i915_request_completed(from)) {
1464 i915_sw_fence_set_error_once(&to->submit, from->fence.error);
1468 if (to->engine->sched_engine->schedule) {
1469 ret = i915_sched_node_add_dependency(&to->sched,
1471 I915_DEPENDENCY_EXTERNAL);
1476 if (!intel_engine_uses_guc(to->engine) &&
1477 is_power_of_2(to->execution_mask | READ_ONCE(from->execution_mask)))
1478 ret = await_request_submit(to, from);
1480 ret = emit_semaphore_wait(to, from, I915_FENCE_GFP);
1488 i915_request_await_dma_fence(struct i915_request *rq, struct dma_fence *fence)
1490 struct dma_fence **child = &fence;
1491 unsigned int nchild = 1;
1495 * Note that if the fence-array was created in signal-on-any mode,
1496 * we should *not* decompose it into its individual fences. However,
1497 * we don't currently store which mode the fence-array is operating
1498 * in. Fortunately, the only user of signal-on-any is private to
1499 * amdgpu and we should not see any incoming fence-array from
1500 * sync-file being in signal-on-any mode.
1502 if (dma_fence_is_array(fence)) {
1503 struct dma_fence_array *array = to_dma_fence_array(fence);
1505 child = array->fences;
1506 nchild = array->num_fences;
1507 GEM_BUG_ON(!nchild);
1512 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
1516 * Requests on the same timeline are explicitly ordered, along
1517 * with their dependencies, by i915_request_add() which ensures
1518 * that requests are submitted in-order through each ring.
1520 if (fence->context == rq->fence.context)
1523 /* Squash repeated waits to the same timelines */
1524 if (fence->context &&
1525 intel_timeline_sync_is_later(i915_request_timeline(rq),
1529 if (dma_fence_is_i915(fence)) {
1530 if (is_same_parallel_context(rq, to_request(fence)))
1532 ret = i915_request_await_request(rq, to_request(fence));
1534 ret = i915_request_await_external(rq, fence);
1539 /* Record the latest fence used against each timeline */
1541 intel_timeline_sync_set(i915_request_timeline(rq),
1549 * i915_request_await_deps - set this request to (async) wait upon a struct
1550 * i915_deps dma_fence collection
1551 * @rq: request we are wishing to use
1552 * @deps: The struct i915_deps containing the dependencies.
1554 * Returns 0 if successful, negative error code on error.
1556 int i915_request_await_deps(struct i915_request *rq, const struct i915_deps *deps)
1560 for (i = 0; i < deps->num_deps; ++i) {
1561 err = i915_request_await_dma_fence(rq, deps->fences[i]);
1570 * i915_request_await_object - set this request to (async) wait upon a bo
1571 * @to: request we are wishing to use
1572 * @obj: object which may be in use on another ring.
1573 * @write: whether the wait is on behalf of a writer
1575 * This code is meant to abstract object synchronization with the GPU.
1576 * Conceptually we serialise writes between engines inside the GPU.
1577 * We only allow one engine to write into a buffer at any time, but
1578 * multiple readers. To ensure each has a coherent view of memory, we must:
1580 * - If there is an outstanding write request to the object, the new
1581 * request must wait for it to complete (either CPU or in hw, requests
1582 * on the same ring will be naturally ordered).
1584 * - If we are a write request (pending_write_domain is set), the new
1585 * request must wait for outstanding read requests to complete.
1587 * Returns 0 if successful, else propagates up the lower layer error.
1590 i915_request_await_object(struct i915_request *to,
1591 struct drm_i915_gem_object *obj,
1594 struct dma_resv_iter cursor;
1595 struct dma_fence *fence;
1598 dma_resv_for_each_fence(&cursor, obj->base.resv, write, fence) {
1599 ret = i915_request_await_dma_fence(to, fence);
1607 static struct i915_request *
1608 __i915_request_ensure_parallel_ordering(struct i915_request *rq,
1609 struct intel_timeline *timeline)
1611 struct i915_request *prev;
1613 GEM_BUG_ON(!is_parallel_rq(rq));
1615 prev = request_to_parent(rq)->parallel.last_rq;
1617 if (!__i915_request_is_complete(prev)) {
1618 i915_sw_fence_await_sw_fence(&rq->submit,
1622 if (rq->engine->sched_engine->schedule)
1623 __i915_sched_node_add_dependency(&rq->sched,
1628 i915_request_put(prev);
1631 request_to_parent(rq)->parallel.last_rq = i915_request_get(rq);
1633 return to_request(__i915_active_fence_set(&timeline->last_request,
1637 static struct i915_request *
1638 __i915_request_ensure_ordering(struct i915_request *rq,
1639 struct intel_timeline *timeline)
1641 struct i915_request *prev;
1643 GEM_BUG_ON(is_parallel_rq(rq));
1645 prev = to_request(__i915_active_fence_set(&timeline->last_request,
1648 if (prev && !__i915_request_is_complete(prev)) {
1649 bool uses_guc = intel_engine_uses_guc(rq->engine);
1650 bool pow2 = is_power_of_2(READ_ONCE(prev->engine)->mask |
1652 bool same_context = prev->context == rq->context;
1655 * The requests are supposed to be kept in order. However,
1656 * we need to be wary in case the timeline->last_request
1657 * is used as a barrier for external modification to this
1660 GEM_BUG_ON(same_context &&
1661 i915_seqno_passed(prev->fence.seqno,
1664 if ((same_context && uses_guc) || (!uses_guc && pow2))
1665 i915_sw_fence_await_sw_fence(&rq->submit,
1669 __i915_sw_fence_await_dma_fence(&rq->submit,
1672 if (rq->engine->sched_engine->schedule)
1673 __i915_sched_node_add_dependency(&rq->sched,
1682 static struct i915_request *
1683 __i915_request_add_to_timeline(struct i915_request *rq)
1685 struct intel_timeline *timeline = i915_request_timeline(rq);
1686 struct i915_request *prev;
1689 * Dependency tracking and request ordering along the timeline
1690 * is special cased so that we can eliminate redundant ordering
1691 * operations while building the request (we know that the timeline
1692 * itself is ordered, and here we guarantee it).
1694 * As we know we will need to emit tracking along the timeline,
1695 * we embed the hooks into our request struct -- at the cost of
1696 * having to have specialised no-allocation interfaces (which will
1697 * be beneficial elsewhere).
1699 * A second benefit to open-coding i915_request_await_request is
1700 * that we can apply a slight variant of the rules specialised
1701 * for timelines that jump between engines (such as virtual engines).
1702 * If we consider the case of virtual engine, we must emit a dma-fence
1703 * to prevent scheduling of the second request until the first is
1704 * complete (to maximise our greedy late load balancing) and this
1705 * precludes optimising to use semaphores serialisation of a single
1706 * timeline across engines.
1708 * We do not order parallel submission requests on the timeline as each
1709 * parallel submission context has its own timeline and the ordering
1710 * rules for parallel requests are that they must be submitted in the
1711 * order received from the execbuf IOCTL. So rather than using the
1712 * timeline we store a pointer to last request submitted in the
1713 * relationship in the gem context and insert a submission fence
1714 * between that request and request passed into this function or
1715 * alternatively we use completion fence if gem context has a single
1716 * timeline and this is the first submission of an execbuf IOCTL.
1718 if (likely(!is_parallel_rq(rq)))
1719 prev = __i915_request_ensure_ordering(rq, timeline);
1721 prev = __i915_request_ensure_parallel_ordering(rq, timeline);
1724 * Make sure that no request gazumped us - if it was allocated after
1725 * our i915_request_alloc() and called __i915_request_add() before
1726 * us, the timeline will hold its seqno which is later than ours.
1728 GEM_BUG_ON(timeline->seqno != rq->fence.seqno);
1734 * NB: This function is not allowed to fail. Doing so would mean the the
1735 * request is not being tracked for completion but the work itself is
1736 * going to happen on the hardware. This would be a Bad Thing(tm).
1738 struct i915_request *__i915_request_commit(struct i915_request *rq)
1740 struct intel_engine_cs *engine = rq->engine;
1741 struct intel_ring *ring = rq->ring;
1747 * To ensure that this call will not fail, space for its emissions
1748 * should already have been reserved in the ring buffer. Let the ring
1749 * know that it is time to use that space up.
1751 GEM_BUG_ON(rq->reserved_space > ring->space);
1752 rq->reserved_space = 0;
1753 rq->emitted_jiffies = jiffies;
1756 * Record the position of the start of the breadcrumb so that
1757 * should we detect the updated seqno part-way through the
1758 * GPU processing the request, we never over-estimate the
1759 * position of the ring's HEAD.
1761 cs = intel_ring_begin(rq, engine->emit_fini_breadcrumb_dw);
1762 GEM_BUG_ON(IS_ERR(cs));
1763 rq->postfix = intel_ring_offset(rq, cs);
1765 return __i915_request_add_to_timeline(rq);
1768 void __i915_request_queue_bh(struct i915_request *rq)
1770 i915_sw_fence_commit(&rq->semaphore);
1771 i915_sw_fence_commit(&rq->submit);
1774 void __i915_request_queue(struct i915_request *rq,
1775 const struct i915_sched_attr *attr)
1778 * Let the backend know a new request has arrived that may need
1779 * to adjust the existing execution schedule due to a high priority
1780 * request - i.e. we may want to preempt the current request in order
1781 * to run a high priority dependency chain *before* we can execute this
1784 * This is called before the request is ready to run so that we can
1785 * decide whether to preempt the entire chain so that it is ready to
1786 * run at the earliest possible convenience.
1788 if (attr && rq->engine->sched_engine->schedule)
1789 rq->engine->sched_engine->schedule(rq, attr);
1792 __i915_request_queue_bh(rq);
1793 local_bh_enable(); /* kick tasklets */
1796 void i915_request_add(struct i915_request *rq)
1798 struct intel_timeline * const tl = i915_request_timeline(rq);
1799 struct i915_sched_attr attr = {};
1800 struct i915_gem_context *ctx;
1802 lockdep_assert_held(&tl->mutex);
1803 lockdep_unpin_lock(&tl->mutex, rq->cookie);
1805 trace_i915_request_add(rq);
1806 __i915_request_commit(rq);
1808 /* XXX placeholder for selftests */
1810 ctx = rcu_dereference(rq->context->gem_context);
1815 __i915_request_queue(rq, &attr);
1817 mutex_unlock(&tl->mutex);
1820 static unsigned long local_clock_ns(unsigned int *cpu)
1825 * Cheaply and approximately convert from nanoseconds to microseconds.
1826 * The result and subsequent calculations are also defined in the same
1827 * approximate microseconds units. The principal source of timing
1828 * error here is from the simple truncation.
1830 * Note that local_clock() is only defined wrt to the current CPU;
1831 * the comparisons are no longer valid if we switch CPUs. Instead of
1832 * blocking preemption for the entire busywait, we can detect the CPU
1833 * switch and use that as indicator of system load and a reason to
1834 * stop busywaiting, see busywait_stop().
1843 static bool busywait_stop(unsigned long timeout, unsigned int cpu)
1845 unsigned int this_cpu;
1847 if (time_after(local_clock_ns(&this_cpu), timeout))
1850 return this_cpu != cpu;
1853 static bool __i915_spin_request(struct i915_request * const rq, int state)
1855 unsigned long timeout_ns;
1859 * Only wait for the request if we know it is likely to complete.
1861 * We don't track the timestamps around requests, nor the average
1862 * request length, so we do not have a good indicator that this
1863 * request will complete within the timeout. What we do know is the
1864 * order in which requests are executed by the context and so we can
1865 * tell if the request has been started. If the request is not even
1866 * running yet, it is a fair assumption that it will not complete
1867 * within our relatively short timeout.
1869 if (!i915_request_is_running(rq))
1873 * When waiting for high frequency requests, e.g. during synchronous
1874 * rendering split between the CPU and GPU, the finite amount of time
1875 * required to set up the irq and wait upon it limits the response
1876 * rate. By busywaiting on the request completion for a short while we
1877 * can service the high frequency waits as quick as possible. However,
1878 * if it is a slow request, we want to sleep as quickly as possible.
1879 * The tradeoff between waiting and sleeping is roughly the time it
1880 * takes to sleep on a request, on the order of a microsecond.
1883 timeout_ns = READ_ONCE(rq->engine->props.max_busywait_duration_ns);
1884 timeout_ns += local_clock_ns(&cpu);
1886 if (dma_fence_is_signaled(&rq->fence))
1889 if (signal_pending_state(state, current))
1892 if (busywait_stop(timeout_ns, cpu))
1896 } while (!need_resched());
1901 struct request_wait {
1902 struct dma_fence_cb cb;
1903 struct task_struct *tsk;
1906 static void request_wait_wake(struct dma_fence *fence, struct dma_fence_cb *cb)
1908 struct request_wait *wait = container_of(cb, typeof(*wait), cb);
1910 wake_up_process(fetch_and_zero(&wait->tsk));
1914 * i915_request_wait_timeout - wait until execution of request has finished
1915 * @rq: the request to wait upon
1916 * @flags: how to wait
1917 * @timeout: how long to wait in jiffies
1919 * i915_request_wait_timeout() waits for the request to be completed, for a
1920 * maximum of @timeout jiffies (with MAX_SCHEDULE_TIMEOUT implying an
1923 * Returns the remaining time (in jiffies) if the request completed, which may
1924 * be zero if the request is unfinished after the timeout expires.
1925 * If the timeout is 0, it will return 1 if the fence is signaled.
1927 * May return -EINTR is called with I915_WAIT_INTERRUPTIBLE and a signal is
1928 * pending before the request completes.
1930 * NOTE: This function has the same wait semantics as dma-fence.
1932 long i915_request_wait_timeout(struct i915_request *rq,
1936 const int state = flags & I915_WAIT_INTERRUPTIBLE ?
1937 TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE;
1938 struct request_wait wait;
1941 GEM_BUG_ON(timeout < 0);
1943 if (dma_fence_is_signaled(&rq->fence))
1944 return timeout ?: 1;
1949 trace_i915_request_wait_begin(rq, flags);
1952 * We must never wait on the GPU while holding a lock as we
1953 * may need to perform a GPU reset. So while we don't need to
1954 * serialise wait/reset with an explicit lock, we do want
1955 * lockdep to detect potential dependency cycles.
1957 mutex_acquire(&rq->engine->gt->reset.mutex.dep_map, 0, 0, _THIS_IP_);
1960 * Optimistic spin before touching IRQs.
1962 * We may use a rather large value here to offset the penalty of
1963 * switching away from the active task. Frequently, the client will
1964 * wait upon an old swapbuffer to throttle itself to remain within a
1965 * frame of the gpu. If the client is running in lockstep with the gpu,
1966 * then it should not be waiting long at all, and a sleep now will incur
1967 * extra scheduler latency in producing the next frame. To try to
1968 * avoid adding the cost of enabling/disabling the interrupt to the
1969 * short wait, we first spin to see if the request would have completed
1970 * in the time taken to setup the interrupt.
1972 * We need upto 5us to enable the irq, and upto 20us to hide the
1973 * scheduler latency of a context switch, ignoring the secondary
1974 * impacts from a context switch such as cache eviction.
1976 * The scheme used for low-latency IO is called "hybrid interrupt
1977 * polling". The suggestion there is to sleep until just before you
1978 * expect to be woken by the device interrupt and then poll for its
1979 * completion. That requires having a good predictor for the request
1980 * duration, which we currently lack.
1982 if (CONFIG_DRM_I915_MAX_REQUEST_BUSYWAIT &&
1983 __i915_spin_request(rq, state))
1987 * This client is about to stall waiting for the GPU. In many cases
1988 * this is undesirable and limits the throughput of the system, as
1989 * many clients cannot continue processing user input/output whilst
1990 * blocked. RPS autotuning may take tens of milliseconds to respond
1991 * to the GPU load and thus incurs additional latency for the client.
1992 * We can circumvent that by promoting the GPU frequency to maximum
1993 * before we sleep. This makes the GPU throttle up much more quickly
1994 * (good for benchmarks and user experience, e.g. window animations),
1995 * but at a cost of spending more power processing the workload
1996 * (bad for battery).
1998 if (flags & I915_WAIT_PRIORITY && !i915_request_started(rq))
1999 intel_rps_boost(rq);
2002 if (dma_fence_add_callback(&rq->fence, &wait.cb, request_wait_wake))
2006 * Flush the submission tasklet, but only if it may help this request.
2008 * We sometimes experience some latency between the HW interrupts and
2009 * tasklet execution (mostly due to ksoftirqd latency, but it can also
2010 * be due to lazy CS events), so lets run the tasklet manually if there
2011 * is a chance it may submit this request. If the request is not ready
2012 * to run, as it is waiting for other fences to be signaled, flushing
2013 * the tasklet is busy work without any advantage for this client.
2015 * If the HW is being lazy, this is the last chance before we go to
2016 * sleep to catch any pending events. We will check periodically in
2017 * the heartbeat to flush the submission tasklets as a last resort
2020 if (i915_request_is_ready(rq))
2021 __intel_engine_flush_submission(rq->engine, false);
2024 set_current_state(state);
2026 if (dma_fence_is_signaled(&rq->fence))
2029 if (signal_pending_state(state, current)) {
2030 timeout = -ERESTARTSYS;
2039 timeout = io_schedule_timeout(timeout);
2041 __set_current_state(TASK_RUNNING);
2043 if (READ_ONCE(wait.tsk))
2044 dma_fence_remove_callback(&rq->fence, &wait.cb);
2045 GEM_BUG_ON(!list_empty(&wait.cb.node));
2048 mutex_release(&rq->engine->gt->reset.mutex.dep_map, _THIS_IP_);
2049 trace_i915_request_wait_end(rq);
2054 * i915_request_wait - wait until execution of request has finished
2055 * @rq: the request to wait upon
2056 * @flags: how to wait
2057 * @timeout: how long to wait in jiffies
2059 * i915_request_wait() waits for the request to be completed, for a
2060 * maximum of @timeout jiffies (with MAX_SCHEDULE_TIMEOUT implying an
2063 * Returns the remaining time (in jiffies) if the request completed, which may
2064 * be zero or -ETIME if the request is unfinished after the timeout expires.
2065 * May return -EINTR is called with I915_WAIT_INTERRUPTIBLE and a signal is
2066 * pending before the request completes.
2068 * NOTE: This function behaves differently from dma-fence wait semantics for
2069 * timeout = 0. It returns 0 on success, and -ETIME if not signaled.
2071 long i915_request_wait(struct i915_request *rq,
2075 long ret = i915_request_wait_timeout(rq, flags, timeout);
2080 if (ret > 0 && !timeout)
2086 static int print_sched_attr(const struct i915_sched_attr *attr,
2087 char *buf, int x, int len)
2089 if (attr->priority == I915_PRIORITY_INVALID)
2092 x += snprintf(buf + x, len - x,
2093 " prio=%d", attr->priority);
2098 static char queue_status(const struct i915_request *rq)
2100 if (i915_request_is_active(rq))
2103 if (i915_request_is_ready(rq))
2104 return intel_engine_is_virtual(rq->engine) ? 'V' : 'R';
2109 static const char *run_status(const struct i915_request *rq)
2111 if (__i915_request_is_complete(rq))
2114 if (__i915_request_has_started(rq))
2117 if (!i915_sw_fence_signaled(&rq->semaphore))
2123 static const char *fence_status(const struct i915_request *rq)
2125 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &rq->fence.flags))
2128 if (test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT, &rq->fence.flags))
2134 void i915_request_show(struct drm_printer *m,
2135 const struct i915_request *rq,
2139 const char *name = rq->fence.ops->get_timeline_name((struct dma_fence *)&rq->fence);
2144 * The prefix is used to show the queue status, for which we use
2145 * the following flags:
2148 * - initial status upon being submitted by the user
2150 * - the request is not ready for execution as it is waiting
2151 * for external fences
2154 * - all fences the request was waiting on have been signaled,
2155 * and the request is now ready for execution and will be
2156 * in a backend queue
2158 * - a ready request may still need to wait on semaphores
2162 * - same as ready, but queued over multiple backends
2165 * - the request has been transferred from the backend queue and
2166 * submitted for execution on HW
2168 * - a completed request may still be regarded as executing, its
2169 * status may not be updated until it is retired and removed
2173 x = print_sched_attr(&rq->sched.attr, buf, x, sizeof(buf));
2175 drm_printf(m, "%s%.*s%c %llx:%lld%s%s %s @ %dms: %s\n",
2176 prefix, indent, " ",
2178 rq->fence.context, rq->fence.seqno,
2182 jiffies_to_msecs(jiffies - rq->emitted_jiffies),
2186 static bool engine_match_ring(struct intel_engine_cs *engine, struct i915_request *rq)
2188 u32 ring = ENGINE_READ(engine, RING_START);
2190 return ring == i915_ggtt_offset(rq->ring->vma);
2193 static bool match_ring(struct i915_request *rq)
2195 struct intel_engine_cs *engine;
2199 if (!intel_engine_is_virtual(rq->engine))
2200 return engine_match_ring(rq->engine, rq);
2204 while ((engine = intel_engine_get_sibling(rq->engine, i++))) {
2205 found = engine_match_ring(engine, rq);
2213 enum i915_request_state i915_test_request_state(struct i915_request *rq)
2215 if (i915_request_completed(rq))
2216 return I915_REQUEST_COMPLETE;
2218 if (!i915_request_started(rq))
2219 return I915_REQUEST_PENDING;
2222 return I915_REQUEST_ACTIVE;
2224 return I915_REQUEST_QUEUED;
2227 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
2228 #include "selftests/mock_request.c"
2229 #include "selftests/i915_request.c"
2232 void i915_request_module_exit(void)
2234 kmem_cache_destroy(slab_execute_cbs);
2235 kmem_cache_destroy(slab_requests);
2238 int __init i915_request_module_init(void)
2241 kmem_cache_create("i915_request",
2242 sizeof(struct i915_request),
2243 __alignof__(struct i915_request),
2244 SLAB_HWCACHE_ALIGN |
2245 SLAB_RECLAIM_ACCOUNT |
2246 SLAB_TYPESAFE_BY_RCU,
2247 __i915_request_ctor);
2251 slab_execute_cbs = KMEM_CACHE(execute_cb,
2252 SLAB_HWCACHE_ALIGN |
2253 SLAB_RECLAIM_ACCOUNT |
2254 SLAB_TYPESAFE_BY_RCU);
2255 if (!slab_execute_cbs)
2261 kmem_cache_destroy(slab_requests);