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_gpu_commands.h"
40 #include "gt/intel_reset.h"
41 #include "gt/intel_ring.h"
42 #include "gt/intel_rps.h"
44 #include "i915_active.h"
46 #include "i915_trace.h"
51 struct i915_sw_fence *fence;
52 struct i915_request *signal;
55 static struct kmem_cache *slab_requests;
56 static struct kmem_cache *slab_execute_cbs;
58 static const char *i915_fence_get_driver_name(struct dma_fence *fence)
60 return dev_name(to_request(fence)->engine->i915->drm.dev);
63 static const char *i915_fence_get_timeline_name(struct dma_fence *fence)
65 const struct i915_gem_context *ctx;
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.
76 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
79 ctx = i915_request_gem_context(to_request(fence));
81 return "[" DRIVER_NAME "]";
86 static bool i915_fence_signaled(struct dma_fence *fence)
88 return i915_request_completed(to_request(fence));
91 static bool i915_fence_enable_signaling(struct dma_fence *fence)
93 return i915_request_enable_breadcrumb(to_request(fence));
96 static signed long i915_fence_wait(struct dma_fence *fence,
100 return i915_request_wait_timeout(to_request(fence),
101 interruptible | I915_WAIT_PRIORITY,
105 struct kmem_cache *i915_request_slab_cache(void)
107 return slab_requests;
110 static void i915_fence_release(struct dma_fence *fence)
112 struct i915_request *rq = to_request(fence);
114 GEM_BUG_ON(rq->guc_prio != GUC_PRIO_INIT &&
115 rq->guc_prio != GUC_PRIO_FINI);
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);
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.
128 i915_sw_fence_fini(&rq->submit);
129 i915_sw_fence_fini(&rq->semaphore);
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
136 if (!intel_engine_is_virtual(rq->engine) &&
137 !cmpxchg(&rq->engine->request_pool, NULL, rq)) {
138 intel_context_put(rq->context);
142 intel_context_put(rq->context);
144 kmem_cache_free(slab_requests, rq);
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,
156 static void irq_execute_cb(struct irq_work *wrk)
158 struct execute_cb *cb = container_of(wrk, typeof(*cb), work);
160 i915_sw_fence_complete(cb->fence);
161 kmem_cache_free(slab_execute_cbs, cb);
164 static __always_inline void
165 __notify_execute_cb(struct i915_request *rq, bool (*fn)(struct irq_work *wrk))
167 struct execute_cb *cb, *cn;
169 if (llist_empty(&rq->execute_cb))
172 llist_for_each_entry_safe(cb, cn,
173 llist_del_all(&rq->execute_cb),
178 static void __notify_execute_cb_irq(struct i915_request *rq)
180 __notify_execute_cb(rq, irq_work_queue);
183 static bool irq_work_imm(struct irq_work *wrk)
189 void i915_request_notify_execute_cb_imm(struct i915_request *rq)
191 __notify_execute_cb(rq, irq_work_imm);
194 static void __i915_request_fill(struct i915_request *rq, u8 val)
196 void *vaddr = rq->ring->vaddr;
200 if (rq->postfix < head) {
201 memset(vaddr + head, val, rq->ring->size - head);
204 memset(vaddr + head, val, rq->postfix - head);
208 * i915_request_active_engine
209 * @rq: request to inspect
210 * @active: pointer in which to return the active engine
212 * Fills the currently active engine to the @active pointer if the request
213 * is active and still not completed.
215 * Returns true if request was active or false otherwise.
218 i915_request_active_engine(struct i915_request *rq,
219 struct intel_engine_cs **active)
221 struct intel_engine_cs *engine, *locked;
225 * Serialise with __i915_request_submit() so that it sees
226 * is-banned?, or we know the request is already inflight.
228 * Note that rq->engine is unstable, and so we double
229 * check that we have acquired the lock on the final engine.
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);
236 spin_lock(&locked->sched_engine->lock);
239 if (i915_request_is_active(rq)) {
240 if (!__i915_request_is_complete(rq))
245 spin_unlock_irq(&locked->sched_engine->lock);
250 static void __rq_init_watchdog(struct i915_request *rq)
252 rq->watchdog.timer.function = NULL;
255 static enum hrtimer_restart __rq_watchdog_expired(struct hrtimer *hrtimer)
257 struct i915_request *rq =
258 container_of(hrtimer, struct i915_request, watchdog.timer);
259 struct intel_gt *gt = rq->engine->gt;
261 if (!i915_request_completed(rq)) {
262 if (llist_add(&rq->watchdog.link, >->watchdog.list))
263 schedule_work(>->watchdog.work);
265 i915_request_put(rq);
268 return HRTIMER_NORESTART;
271 static void __rq_arm_watchdog(struct i915_request *rq)
273 struct i915_request_watchdog *wdg = &rq->watchdog;
274 struct intel_context *ce = rq->context;
276 if (!ce->watchdog.timeout_us)
279 i915_request_get(rq);
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 *
290 static void __rq_cancel_watchdog(struct i915_request *rq)
292 struct i915_request_watchdog *wdg = &rq->watchdog;
294 if (wdg->timer.function && hrtimer_try_to_cancel(&wdg->timer) > 0)
295 i915_request_put(rq);
298 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
301 * i915_request_free_capture_list - Free a capture list
302 * @capture: Pointer to the first list item or NULL
305 void i915_request_free_capture_list(struct i915_capture_list *capture)
308 struct i915_capture_list *next = capture->next;
310 i915_vma_snapshot_put(capture->vma_snapshot);
315 #define assert_capture_list_is_null(_rq) GEM_BUG_ON((_rq)->capture_list)
317 #define clear_capture_list(_rq) ((_rq)->capture_list = NULL)
321 #define i915_request_free_capture_list(_a) do {} while (0)
323 #define assert_capture_list_is_null(_a) do {} while (0)
325 #define clear_capture_list(_rq) do {} while (0)
329 bool i915_request_retire(struct i915_request *rq)
331 if (!__i915_request_is_complete(rq))
336 GEM_BUG_ON(!i915_sw_fence_signaled(&rq->submit));
337 trace_i915_request_retire(rq);
338 i915_request_mark_complete(rq);
340 __rq_cancel_watchdog(rq);
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
348 * Note this requires that we are always called in request
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;
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);
364 if (test_and_set_bit(I915_FENCE_FLAG_BOOST, &rq->fence.flags))
365 intel_rps_dec_waiters(&rq->engine->gt->rps);
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
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.
377 rq->engine->remove_active_request(rq);
378 GEM_BUG_ON(!llist_empty(&rq->execute_cb));
380 __list_del_entry(&rq->link); /* poison neither prev/next (RCU walks) */
382 intel_context_exit(rq->context);
383 intel_context_unpin(rq->context);
385 i915_sched_node_fini(&rq->sched);
386 i915_request_put(rq);
391 void i915_request_retire_upto(struct i915_request *rq)
393 struct intel_timeline * const tl = i915_request_timeline(rq);
394 struct i915_request *tmp;
397 GEM_BUG_ON(!__i915_request_is_complete(rq));
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);
405 static struct i915_request * const *
406 __engine_active(struct intel_engine_cs *engine)
408 return READ_ONCE(engine->execlists.active);
411 static bool __request_in_flight(const struct i915_request *signal)
413 struct i915_request * const *port, *rq;
414 bool inflight = false;
416 if (!i915_request_is_ready(signal))
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.
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.
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
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.
455 if (!intel_context_inflight(signal->context))
459 for (port = __engine_active(signal->engine);
460 (rq = READ_ONCE(*port)); /* may race with promotion of pending[] */
462 if (rq->context == signal->context) {
463 inflight = i915_seqno_passed(rq->fence.seqno,
464 signal->fence.seqno);
474 __await_execution(struct i915_request *rq,
475 struct i915_request *signal,
478 struct execute_cb *cb;
480 if (i915_request_is_active(signal))
483 cb = kmem_cache_alloc(slab_execute_cbs, gfp);
487 cb->fence = &rq->submit;
488 i915_sw_fence_await(cb->fence);
489 init_irq_work(&cb->work, irq_execute_cb);
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.
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.
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);
513 static bool fatal_error(int 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) */
525 void __i915_request_skip(struct i915_request *rq)
527 GEM_BUG_ON(!fatal_error(rq->fence.error));
529 if (rq->infix == rq->postfix)
532 RQ_TRACE(rq, "error: %d\n", rq->fence.error);
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).
539 __i915_request_fill(rq, 0);
540 rq->infix = rq->postfix;
543 bool i915_request_set_error_once(struct i915_request *rq, int error)
547 GEM_BUG_ON(!IS_ERR_VALUE((long)error));
549 if (i915_request_signaled(rq))
552 old = READ_ONCE(rq->fence.error);
554 if (fatal_error(old))
556 } while (!try_cmpxchg(&rq->fence.error, &old, error));
561 struct i915_request *i915_request_mark_eio(struct i915_request *rq)
563 if (__i915_request_is_complete(rq))
566 GEM_BUG_ON(i915_request_signaled(rq));
568 /* As soon as the request is completed, it may be retired */
569 rq = i915_request_get(rq);
571 i915_request_set_error_once(rq, -EIO);
572 i915_request_mark_complete(rq);
577 bool __i915_request_submit(struct i915_request *request)
579 struct intel_engine_cs *engine = request->engine;
582 RQ_TRACE(request, "\n");
584 GEM_BUG_ON(!irqs_disabled());
585 lockdep_assert_held(&engine->sched_engine->lock);
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
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.)
603 if (__i915_request_is_complete(request)) {
604 list_del_init(&request->sched.link);
608 if (unlikely(intel_context_is_banned(request->context)))
609 i915_request_set_error_once(request, -EIO);
611 if (unlikely(fatal_error(request->fence.error)))
612 __i915_request_skip(request);
615 * Are we using semaphores when the gpu is already saturated?
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).
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.
630 if (request->sched.semaphores &&
631 i915_sw_fence_signaled(&request->semaphore))
632 engine->saturated |= request->sched.semaphores;
634 engine->emit_fini_breadcrumb(request,
635 request->ring->vaddr + request->postfix);
637 trace_i915_request_execute(request);
638 if (engine->bump_serial)
639 engine->bump_serial(engine);
645 GEM_BUG_ON(test_bit(I915_FENCE_FLAG_ACTIVE, &request->fence.flags));
646 engine->add_active_request(request);
648 clear_bit(I915_FENCE_FLAG_PQUEUE, &request->fence.flags);
649 set_bit(I915_FENCE_FLAG_ACTIVE, &request->fence.flags);
652 * XXX Rollback bonded-execution on __i915_request_unsubmit()?
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.
661 __notify_execute_cb_irq(request);
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);
670 void i915_request_submit(struct i915_request *request)
672 struct intel_engine_cs *engine = request->engine;
675 /* Will be called from irq-context when using foreign fences. */
676 spin_lock_irqsave(&engine->sched_engine->lock, flags);
678 __i915_request_submit(request);
680 spin_unlock_irqrestore(&engine->sched_engine->lock, flags);
683 void __i915_request_unsubmit(struct i915_request *request)
685 struct intel_engine_cs *engine = request->engine;
688 * Only unwind in reverse order, required so that the per-context list
689 * is kept in seqno/ring order.
691 RQ_TRACE(request, "\n");
693 GEM_BUG_ON(!irqs_disabled());
694 lockdep_assert_held(&engine->sched_engine->lock);
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.
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);
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;
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.
721 void i915_request_unsubmit(struct i915_request *request)
723 struct intel_engine_cs *engine = request->engine;
726 /* Will be called from irq-context when using foreign fences. */
727 spin_lock_irqsave(&engine->sched_engine->lock, flags);
729 __i915_request_unsubmit(request);
731 spin_unlock_irqrestore(&engine->sched_engine->lock, flags);
734 void i915_request_cancel(struct i915_request *rq, int error)
736 if (!i915_request_set_error_once(rq, error))
739 set_bit(I915_FENCE_FLAG_SENTINEL, &rq->fence.flags);
741 intel_context_cancel_request(rq->context, rq);
745 submit_notify(struct i915_sw_fence *fence, enum i915_sw_fence_notify state)
747 struct i915_request *request =
748 container_of(fence, typeof(*request), submit);
752 trace_i915_request_submit(request);
754 if (unlikely(fence->error))
755 i915_request_set_error_once(request, fence->error);
757 __rq_arm_watchdog(request);
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
768 request->engine->submit_request(request);
773 i915_request_put(request);
781 semaphore_notify(struct i915_sw_fence *fence, enum i915_sw_fence_notify state)
783 struct i915_request *rq = container_of(fence, typeof(*rq), semaphore);
790 i915_request_put(rq);
797 static void retire_requests(struct intel_timeline *tl)
799 struct i915_request *rq, *rn;
801 list_for_each_entry_safe(rq, rn, &tl->requests, link)
802 if (!i915_request_retire(rq))
806 static noinline struct i915_request *
807 request_alloc_slow(struct intel_timeline *tl,
808 struct i915_request **rsvd,
811 struct i915_request *rq;
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 */
822 if (list_empty(&tl->requests))
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);
829 rq = kmem_cache_alloc(slab_requests,
830 gfp | __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
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);
838 /* Retire our old requests in the hope that we free some */
842 return kmem_cache_alloc(slab_requests, gfp);
845 static void __i915_request_ctor(void *arg)
847 struct i915_request *rq = arg;
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);
854 clear_capture_list(rq);
855 rq->batch_snapshot.present = false;
857 init_llist_head(&rq->execute_cb);
860 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
861 #define clear_batch_ptr(_rq) ((_rq)->batch = NULL)
863 #define clear_batch_ptr(_a) do {} while (0)
866 struct i915_request *
867 __i915_request_create(struct intel_context *ce, gfp_t gfp)
869 struct intel_timeline *tl = ce->timeline;
870 struct i915_request *rq;
876 /* Check that the caller provided an already pinned context */
877 __intel_context_pin(ce);
880 * Beware: Dragons be flying overhead.
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.
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
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.
906 * Do not use kmem_cache_zalloc() here!
908 rq = kmem_cache_alloc(slab_requests,
909 gfp | __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
911 rq = request_alloc_slow(tl, &ce->engine->request_pool, gfp);
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.
930 rq->context = intel_context_get(ce);
931 rq->engine = ce->engine;
933 rq->execution_mask = ce->engine->mask;
935 ret = intel_timeline_get_seqno(tl, rq, &seqno);
939 dma_fence_init(&rq->fence, &i915_fence_ops, &rq->lock,
940 tl->fence_context, seqno);
942 RCU_INIT_POINTER(rq->timeline, tl);
943 rq->hwsp_seqno = tl->hwsp_seqno;
944 GEM_BUG_ON(__i915_request_is_complete(rq));
946 rq->rcustate = get_state_synchronize_rcu(); /* acts as smp_mb() */
948 rq->guc_prio = GUC_PRIO_INIT;
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);
954 i915_sched_node_reinit(&rq->sched);
956 /* No zalloc, everything must be cleared after use */
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));
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.
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.
976 2 * rq->engine->emit_fini_breadcrumb_dw * sizeof(u32);
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.
984 rq->head = rq->ring->emit;
986 ret = rq->engine->request_alloc(rq);
990 rq->infix = rq->ring->emit; /* end of header; start of user payload */
992 intel_context_mark_active(ce);
993 list_add_tail_rcu(&rq->link, &tl->requests);
998 ce->ring->emit = rq->head;
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));
1005 intel_context_put(ce);
1006 kmem_cache_free(slab_requests, rq);
1008 intel_context_unpin(ce);
1009 return ERR_PTR(ret);
1012 struct i915_request *
1013 i915_request_create(struct intel_context *ce)
1015 struct i915_request *rq;
1016 struct intel_timeline *tl;
1018 tl = intel_context_timeline_lock(ce);
1020 return ERR_CAST(tl);
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);
1027 intel_context_enter(ce);
1028 rq = __i915_request_create(ce, GFP_KERNEL);
1029 intel_context_exit(ce); /* active reference transferred to request */
1033 /* Check that we do not interrupt ourselves with a new request */
1034 rq->cookie = lockdep_pin_lock(&tl->mutex);
1039 intel_context_timeline_unlock(tl);
1044 i915_request_await_start(struct i915_request *rq, struct i915_request *signal)
1046 struct dma_fence *fence;
1049 if (i915_request_timeline(rq) == rcu_access_pointer(signal->timeline))
1052 if (i915_request_started(signal))
1056 * The caller holds a reference on @signal, but we do not serialise
1057 * against it being retired and removed from the lists.
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.
1066 struct list_head *pos = READ_ONCE(signal->link.prev);
1067 struct i915_request *prev;
1069 /* Confirm signal has not been retired, the link is valid */
1070 if (unlikely(__i915_request_has_started(signal)))
1073 /* Is signal the earliest request on its timeline? */
1074 if (pos == &rcu_dereference(signal->timeline)->requests)
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.
1083 prev = list_entry(pos, typeof(*prev), link);
1084 if (!i915_request_get_rcu(prev))
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);
1093 fence = &prev->fence;
1100 if (!intel_timeline_sync_is_later(i915_request_timeline(rq), fence))
1101 err = i915_sw_fence_await_dma_fence(&rq->submit,
1104 dma_fence_put(fence);
1109 static intel_engine_mask_t
1110 already_busywaiting(struct i915_request *rq)
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
1122 * See the are-we-too-late? check in __i915_request_submit().
1124 return rq->sched.semaphores | READ_ONCE(rq->engine->saturated);
1128 __emit_semaphore_wait(struct i915_request *to,
1129 struct i915_request *from,
1132 const int has_token = GRAPHICS_VER(to->engine->i915) >= 12;
1137 GEM_BUG_ON(GRAPHICS_VER(to->engine->i915) < 8);
1138 GEM_BUG_ON(i915_request_has_initial_breadcrumb(to));
1140 /* We need to pin the signaler's HWSP until we are finished reading. */
1141 err = intel_timeline_read_hwsp(from, to, &hwsp_offset);
1149 cs = intel_ring_begin(to, len);
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
1161 *cs++ = (MI_SEMAPHORE_WAIT |
1162 MI_SEMAPHORE_GLOBAL_GTT |
1164 MI_SEMAPHORE_SAD_GTE_SDD) +
1167 *cs++ = hwsp_offset;
1174 intel_ring_advance(to, cs);
1179 can_use_semaphore_wait(struct i915_request *to, struct i915_request *from)
1181 return to->engine->gt->ggtt == from->engine->gt->ggtt;
1185 emit_semaphore_wait(struct i915_request *to,
1186 struct i915_request *from,
1189 const intel_engine_mask_t mask = READ_ONCE(from->engine)->mask;
1190 struct i915_sw_fence *wait = &to->submit;
1192 if (!can_use_semaphore_wait(to, from))
1195 if (!intel_context_use_semaphores(to->context))
1198 if (i915_request_has_initial_breadcrumb(to))
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.
1207 if (from->sched.flags & I915_SCHED_HAS_EXTERNAL_CHAIN)
1210 /* Just emit the first semaphore we see as request space is limited. */
1211 if (already_busywaiting(to) & mask)
1214 if (i915_request_await_start(to, from) < 0)
1217 /* Only submit our spinner after the signaler is running! */
1218 if (__await_execution(to, from, gfp))
1221 if (__emit_semaphore_wait(to, from, from->fence.seqno))
1224 to->sched.semaphores |= mask;
1225 wait = &to->semaphore;
1228 return i915_sw_fence_await_dma_fence(wait,
1233 static bool intel_timeline_sync_has_start(struct intel_timeline *tl,
1234 struct dma_fence *fence)
1236 return __intel_timeline_sync_is_later(tl,
1241 static int intel_timeline_sync_set_start(struct intel_timeline *tl,
1242 const struct dma_fence *fence)
1244 return __intel_timeline_sync_set(tl, fence->context, fence->seqno - 1);
1248 __i915_request_await_execution(struct i915_request *to,
1249 struct i915_request *from)
1253 GEM_BUG_ON(intel_context_is_barrier(from->context));
1255 /* Submit both requests at the same time */
1256 err = __await_execution(to, from, I915_FENCE_GFP);
1260 /* Squash repeated depenendices to the same timelines */
1261 if (intel_timeline_sync_has_start(i915_request_timeline(to),
1266 * Wait until the start of this request.
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.
1275 err = i915_request_await_start(to, from);
1280 * Ensure both start together [after all semaphores in signal]
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.
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
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);
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,
1310 I915_DEPENDENCY_WEAK);
1315 return intel_timeline_sync_set_start(i915_request_timeline(to),
1319 static void mark_external(struct i915_request *rq)
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.
1329 rq->sched.flags |= I915_SCHED_HAS_EXTERNAL_CHAIN;
1333 __i915_request_await_external(struct i915_request *rq, struct dma_fence *fence)
1336 return i915_sw_fence_await_dma_fence(&rq->submit, fence,
1337 i915_fence_context_timeout(rq->engine->i915,
1343 i915_request_await_external(struct i915_request *rq, struct dma_fence *fence)
1345 struct dma_fence *iter;
1348 if (!to_dma_fence_chain(fence))
1349 return __i915_request_await_external(rq, fence);
1351 dma_fence_chain_for_each(iter, fence) {
1352 struct dma_fence_chain *chain = to_dma_fence_chain(iter);
1354 if (!dma_fence_is_i915(chain->fence)) {
1355 err = __i915_request_await_external(rq, iter);
1359 err = i915_request_await_dma_fence(rq, chain->fence);
1364 dma_fence_put(iter);
1368 static inline bool is_parallel_rq(struct i915_request *rq)
1370 return intel_context_is_parallel(rq->context);
1373 static inline struct intel_context *request_to_parent(struct i915_request *rq)
1375 return intel_context_to_parent(rq->context);
1378 static bool is_same_parallel_context(struct i915_request *to,
1379 struct i915_request *from)
1381 if (is_parallel_rq(to))
1382 return request_to_parent(to) == request_to_parent(from);
1388 i915_request_await_execution(struct i915_request *rq,
1389 struct dma_fence *fence)
1391 struct dma_fence **child = &fence;
1392 unsigned int nchild = 1;
1395 if (dma_fence_is_array(fence)) {
1396 struct dma_fence_array *array = to_dma_fence_array(fence);
1398 /* XXX Error for signal-on-any fence arrays */
1400 child = array->fences;
1401 nchild = array->num_fences;
1402 GEM_BUG_ON(!nchild);
1407 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
1410 if (fence->context == rq->fence.context)
1414 * We don't squash repeated fence dependencies here as we
1415 * want to run our callback in all cases.
1418 if (dma_fence_is_i915(fence)) {
1419 if (is_same_parallel_context(rq, to_request(fence)))
1421 ret = __i915_request_await_execution(rq,
1424 ret = i915_request_await_external(rq, fence);
1434 await_request_submit(struct i915_request *to, struct i915_request *from)
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.
1444 if (to->engine == READ_ONCE(from->engine))
1445 return i915_sw_fence_await_sw_fence_gfp(&to->submit,
1449 return __i915_request_await_execution(to, from);
1453 i915_request_await_request(struct i915_request *to, struct i915_request *from)
1457 GEM_BUG_ON(to == from);
1458 GEM_BUG_ON(to->timeline == from->timeline);
1460 if (i915_request_completed(from)) {
1461 i915_sw_fence_set_error_once(&to->submit, from->fence.error);
1465 if (to->engine->sched_engine->schedule) {
1466 ret = i915_sched_node_add_dependency(&to->sched,
1468 I915_DEPENDENCY_EXTERNAL);
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);
1477 ret = emit_semaphore_wait(to, from, I915_FENCE_GFP);
1485 i915_request_await_dma_fence(struct i915_request *rq, struct dma_fence *fence)
1487 struct dma_fence **child = &fence;
1488 unsigned int nchild = 1;
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.
1499 if (dma_fence_is_array(fence)) {
1500 struct dma_fence_array *array = to_dma_fence_array(fence);
1502 child = array->fences;
1503 nchild = array->num_fences;
1504 GEM_BUG_ON(!nchild);
1509 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
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.
1517 if (fence->context == rq->fence.context)
1520 /* Squash repeated waits to the same timelines */
1521 if (fence->context &&
1522 intel_timeline_sync_is_later(i915_request_timeline(rq),
1526 if (dma_fence_is_i915(fence)) {
1527 if (is_same_parallel_context(rq, to_request(fence)))
1529 ret = i915_request_await_request(rq, to_request(fence));
1531 ret = i915_request_await_external(rq, fence);
1536 /* Record the latest fence used against each timeline */
1538 intel_timeline_sync_set(i915_request_timeline(rq),
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
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:
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).
1560 * - If we are a write request (pending_write_domain is set), the new
1561 * request must wait for outstanding read requests to complete.
1563 * Returns 0 if successful, else propagates up the lower layer error.
1566 i915_request_await_object(struct i915_request *to,
1567 struct drm_i915_gem_object *obj,
1570 struct dma_resv_iter cursor;
1571 struct dma_fence *fence;
1574 dma_resv_for_each_fence(&cursor, obj->base.resv, write, fence) {
1575 ret = i915_request_await_dma_fence(to, fence);
1583 static struct i915_request *
1584 __i915_request_ensure_parallel_ordering(struct i915_request *rq,
1585 struct intel_timeline *timeline)
1587 struct i915_request *prev;
1589 GEM_BUG_ON(!is_parallel_rq(rq));
1591 prev = request_to_parent(rq)->parallel.last_rq;
1593 if (!__i915_request_is_complete(prev)) {
1594 i915_sw_fence_await_sw_fence(&rq->submit,
1598 if (rq->engine->sched_engine->schedule)
1599 __i915_sched_node_add_dependency(&rq->sched,
1604 i915_request_put(prev);
1607 request_to_parent(rq)->parallel.last_rq = i915_request_get(rq);
1609 return to_request(__i915_active_fence_set(&timeline->last_request,
1613 static struct i915_request *
1614 __i915_request_ensure_ordering(struct i915_request *rq,
1615 struct intel_timeline *timeline)
1617 struct i915_request *prev;
1619 GEM_BUG_ON(is_parallel_rq(rq));
1621 prev = to_request(__i915_active_fence_set(&timeline->last_request,
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 |
1628 bool same_context = prev->context == rq->context;
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
1636 GEM_BUG_ON(same_context &&
1637 i915_seqno_passed(prev->fence.seqno,
1640 if ((same_context && uses_guc) || (!uses_guc && pow2))
1641 i915_sw_fence_await_sw_fence(&rq->submit,
1645 __i915_sw_fence_await_dma_fence(&rq->submit,
1648 if (rq->engine->sched_engine->schedule)
1649 __i915_sched_node_add_dependency(&rq->sched,
1658 static struct i915_request *
1659 __i915_request_add_to_timeline(struct i915_request *rq)
1661 struct intel_timeline *timeline = i915_request_timeline(rq);
1662 struct i915_request *prev;
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).
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).
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.
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.
1694 if (likely(!is_parallel_rq(rq)))
1695 prev = __i915_request_ensure_ordering(rq, timeline);
1697 prev = __i915_request_ensure_parallel_ordering(rq, timeline);
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.
1704 GEM_BUG_ON(timeline->seqno != rq->fence.seqno);
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).
1714 struct i915_request *__i915_request_commit(struct i915_request *rq)
1716 struct intel_engine_cs *engine = rq->engine;
1717 struct intel_ring *ring = rq->ring;
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.
1727 GEM_BUG_ON(rq->reserved_space > ring->space);
1728 rq->reserved_space = 0;
1729 rq->emitted_jiffies = jiffies;
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.
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);
1741 return __i915_request_add_to_timeline(rq);
1744 void __i915_request_queue_bh(struct i915_request *rq)
1746 i915_sw_fence_commit(&rq->semaphore);
1747 i915_sw_fence_commit(&rq->submit);
1750 void __i915_request_queue(struct i915_request *rq,
1751 const struct i915_sched_attr *attr)
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
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.
1764 if (attr && rq->engine->sched_engine->schedule)
1765 rq->engine->sched_engine->schedule(rq, attr);
1768 __i915_request_queue_bh(rq);
1769 local_bh_enable(); /* kick tasklets */
1772 void i915_request_add(struct i915_request *rq)
1774 struct intel_timeline * const tl = i915_request_timeline(rq);
1775 struct i915_sched_attr attr = {};
1776 struct i915_gem_context *ctx;
1778 lockdep_assert_held(&tl->mutex);
1779 lockdep_unpin_lock(&tl->mutex, rq->cookie);
1781 trace_i915_request_add(rq);
1782 __i915_request_commit(rq);
1784 /* XXX placeholder for selftests */
1786 ctx = rcu_dereference(rq->context->gem_context);
1791 __i915_request_queue(rq, &attr);
1793 mutex_unlock(&tl->mutex);
1796 static unsigned long local_clock_ns(unsigned int *cpu)
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.
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().
1819 static bool busywait_stop(unsigned long timeout, unsigned int cpu)
1821 unsigned int this_cpu;
1823 if (time_after(local_clock_ns(&this_cpu), timeout))
1826 return this_cpu != cpu;
1829 static bool __i915_spin_request(struct i915_request * const rq, int state)
1831 unsigned long timeout_ns;
1835 * Only wait for the request if we know it is likely to complete.
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.
1845 if (!i915_request_is_running(rq))
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.
1859 timeout_ns = READ_ONCE(rq->engine->props.max_busywait_duration_ns);
1860 timeout_ns += local_clock_ns(&cpu);
1862 if (dma_fence_is_signaled(&rq->fence))
1865 if (signal_pending_state(state, current))
1868 if (busywait_stop(timeout_ns, cpu))
1872 } while (!need_resched());
1877 struct request_wait {
1878 struct dma_fence_cb cb;
1879 struct task_struct *tsk;
1882 static void request_wait_wake(struct dma_fence *fence, struct dma_fence_cb *cb)
1884 struct request_wait *wait = container_of(cb, typeof(*wait), cb);
1886 wake_up_process(fetch_and_zero(&wait->tsk));
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
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
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.
1903 * May return -EINTR is called with I915_WAIT_INTERRUPTIBLE and a signal is
1904 * pending before the request completes.
1906 * NOTE: This function has the same wait semantics as dma-fence.
1908 long i915_request_wait_timeout(struct i915_request *rq,
1912 const int state = flags & I915_WAIT_INTERRUPTIBLE ?
1913 TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE;
1914 struct request_wait wait;
1917 GEM_BUG_ON(timeout < 0);
1919 if (dma_fence_is_signaled(&rq->fence))
1920 return timeout ?: 1;
1925 trace_i915_request_wait_begin(rq, flags);
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.
1933 mutex_acquire(&rq->engine->gt->reset.mutex.dep_map, 0, 0, _THIS_IP_);
1936 * Optimistic spin before touching IRQs.
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.
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.
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.
1958 if (CONFIG_DRM_I915_MAX_REQUEST_BUSYWAIT &&
1959 __i915_spin_request(rq, state))
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).
1974 if (flags & I915_WAIT_PRIORITY && !i915_request_started(rq))
1975 intel_rps_boost(rq);
1978 if (dma_fence_add_callback(&rq->fence, &wait.cb, request_wait_wake))
1982 * Flush the submission tasklet, but only if it may help this request.
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.
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
1996 if (i915_request_is_ready(rq))
1997 __intel_engine_flush_submission(rq->engine, false);
2000 set_current_state(state);
2002 if (dma_fence_is_signaled(&rq->fence))
2005 if (signal_pending_state(state, current)) {
2006 timeout = -ERESTARTSYS;
2015 timeout = io_schedule_timeout(timeout);
2017 __set_current_state(TASK_RUNNING);
2019 if (READ_ONCE(wait.tsk))
2020 dma_fence_remove_callback(&rq->fence, &wait.cb);
2021 GEM_BUG_ON(!list_empty(&wait.cb.node));
2024 mutex_release(&rq->engine->gt->reset.mutex.dep_map, _THIS_IP_);
2025 trace_i915_request_wait_end(rq);
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
2035 * i915_request_wait() waits for the request to be completed, for a
2036 * maximum of @timeout jiffies (with MAX_SCHEDULE_TIMEOUT implying an
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.
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.
2047 long i915_request_wait(struct i915_request *rq,
2051 long ret = i915_request_wait_timeout(rq, flags, timeout);
2056 if (ret > 0 && !timeout)
2062 static int print_sched_attr(const struct i915_sched_attr *attr,
2063 char *buf, int x, int len)
2065 if (attr->priority == I915_PRIORITY_INVALID)
2068 x += snprintf(buf + x, len - x,
2069 " prio=%d", attr->priority);
2074 static char queue_status(const struct i915_request *rq)
2076 if (i915_request_is_active(rq))
2079 if (i915_request_is_ready(rq))
2080 return intel_engine_is_virtual(rq->engine) ? 'V' : 'R';
2085 static const char *run_status(const struct i915_request *rq)
2087 if (__i915_request_is_complete(rq))
2090 if (__i915_request_has_started(rq))
2093 if (!i915_sw_fence_signaled(&rq->semaphore))
2099 static const char *fence_status(const struct i915_request *rq)
2101 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &rq->fence.flags))
2104 if (test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT, &rq->fence.flags))
2110 void i915_request_show(struct drm_printer *m,
2111 const struct i915_request *rq,
2115 const char *name = rq->fence.ops->get_timeline_name((struct dma_fence *)&rq->fence);
2120 * The prefix is used to show the queue status, for which we use
2121 * the following flags:
2124 * - initial status upon being submitted by the user
2126 * - the request is not ready for execution as it is waiting
2127 * for external fences
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
2134 * - a ready request may still need to wait on semaphores
2138 * - same as ready, but queued over multiple backends
2141 * - the request has been transferred from the backend queue and
2142 * submitted for execution on HW
2144 * - a completed request may still be regarded as executing, its
2145 * status may not be updated until it is retired and removed
2149 x = print_sched_attr(&rq->sched.attr, buf, x, sizeof(buf));
2151 drm_printf(m, "%s%.*s%c %llx:%lld%s%s %s @ %dms: %s\n",
2152 prefix, indent, " ",
2154 rq->fence.context, rq->fence.seqno,
2158 jiffies_to_msecs(jiffies - rq->emitted_jiffies),
2162 static bool engine_match_ring(struct intel_engine_cs *engine, struct i915_request *rq)
2164 u32 ring = ENGINE_READ(engine, RING_START);
2166 return ring == i915_ggtt_offset(rq->ring->vma);
2169 static bool match_ring(struct i915_request *rq)
2171 struct intel_engine_cs *engine;
2175 if (!intel_engine_is_virtual(rq->engine))
2176 return engine_match_ring(rq->engine, rq);
2180 while ((engine = intel_engine_get_sibling(rq->engine, i++))) {
2181 found = engine_match_ring(engine, rq);
2189 enum i915_request_state i915_test_request_state(struct i915_request *rq)
2191 if (i915_request_completed(rq))
2192 return I915_REQUEST_COMPLETE;
2194 if (!i915_request_started(rq))
2195 return I915_REQUEST_PENDING;
2198 return I915_REQUEST_ACTIVE;
2200 return I915_REQUEST_QUEUED;
2203 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
2204 #include "selftests/mock_request.c"
2205 #include "selftests/i915_request.c"
2208 void i915_request_module_exit(void)
2210 kmem_cache_destroy(slab_execute_cbs);
2211 kmem_cache_destroy(slab_requests);
2214 int __init i915_request_module_init(void)
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);
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)
2237 kmem_cache_destroy(slab_requests);