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/prefetch.h>
26 #include <linux/dma-fence-array.h>
27 #include <linux/sched.h>
28 #include <linux/sched/clock.h>
29 #include <linux/sched/signal.h>
32 #include "i915_reset.h"
34 static const char *i915_fence_get_driver_name(struct dma_fence *fence)
39 static const char *i915_fence_get_timeline_name(struct dma_fence *fence)
42 * The timeline struct (as part of the ppgtt underneath a context)
43 * may be freed when the request is no longer in use by the GPU.
44 * We could extend the life of a context to beyond that of all
45 * fences, possibly keeping the hw resource around indefinitely,
46 * or we just give them a false name. Since
47 * dma_fence_ops.get_timeline_name is a debug feature, the occasional
48 * lie seems justifiable.
50 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
53 return to_request(fence)->timeline->name;
56 static bool i915_fence_signaled(struct dma_fence *fence)
58 return i915_request_completed(to_request(fence));
61 static bool i915_fence_enable_signaling(struct dma_fence *fence)
63 return intel_engine_enable_signaling(to_request(fence), true);
66 static signed long i915_fence_wait(struct dma_fence *fence,
70 return i915_request_wait(to_request(fence), interruptible, timeout);
73 static void i915_fence_release(struct dma_fence *fence)
75 struct i915_request *rq = to_request(fence);
78 * The request is put onto a RCU freelist (i.e. the address
79 * is immediately reused), mark the fences as being freed now.
80 * Otherwise the debugobjects for the fences are only marked as
81 * freed when the slab cache itself is freed, and so we would get
82 * caught trying to reuse dead objects.
84 i915_sw_fence_fini(&rq->submit);
86 kmem_cache_free(rq->i915->requests, rq);
89 const struct dma_fence_ops i915_fence_ops = {
90 .get_driver_name = i915_fence_get_driver_name,
91 .get_timeline_name = i915_fence_get_timeline_name,
92 .enable_signaling = i915_fence_enable_signaling,
93 .signaled = i915_fence_signaled,
94 .wait = i915_fence_wait,
95 .release = i915_fence_release,
99 i915_request_remove_from_client(struct i915_request *request)
101 struct drm_i915_file_private *file_priv;
103 file_priv = request->file_priv;
107 spin_lock(&file_priv->mm.lock);
108 if (request->file_priv) {
109 list_del(&request->client_link);
110 request->file_priv = NULL;
112 spin_unlock(&file_priv->mm.lock);
115 static void reserve_gt(struct drm_i915_private *i915)
117 if (!i915->gt.active_requests++)
118 i915_gem_unpark(i915);
121 static void unreserve_gt(struct drm_i915_private *i915)
123 GEM_BUG_ON(!i915->gt.active_requests);
124 if (!--i915->gt.active_requests)
128 void i915_gem_retire_noop(struct i915_gem_active *active,
129 struct i915_request *request)
131 /* Space left intentionally blank */
134 static void advance_ring(struct i915_request *request)
136 struct intel_ring *ring = request->ring;
140 * We know the GPU must have read the request to have
141 * sent us the seqno + interrupt, so use the position
142 * of tail of the request to update the last known position
145 * Note this requires that we are always called in request
148 GEM_BUG_ON(!list_is_first(&request->ring_link, &ring->request_list));
149 if (list_is_last(&request->ring_link, &ring->request_list)) {
151 * We may race here with execlists resubmitting this request
152 * as we retire it. The resubmission will move the ring->tail
153 * forwards (to request->wa_tail). We either read the
154 * current value that was written to hw, or the value that
155 * is just about to be. Either works, if we miss the last two
156 * noops - they are safe to be replayed on a reset.
158 GEM_TRACE("marking %s as inactive\n", ring->timeline->name);
159 tail = READ_ONCE(request->tail);
160 list_del(&ring->active_link);
162 tail = request->postfix;
164 list_del_init(&request->ring_link);
169 static void free_capture_list(struct i915_request *request)
171 struct i915_capture_list *capture;
173 capture = request->capture_list;
175 struct i915_capture_list *next = capture->next;
182 static void __retire_engine_request(struct intel_engine_cs *engine,
183 struct i915_request *rq)
185 GEM_TRACE("%s(%s) fence %llx:%lld, global=%d, current %d:%d\n",
186 __func__, engine->name,
187 rq->fence.context, rq->fence.seqno,
190 intel_engine_get_seqno(engine));
192 GEM_BUG_ON(!i915_request_completed(rq));
196 spin_lock(&engine->timeline.lock);
197 GEM_BUG_ON(!list_is_first(&rq->link, &engine->timeline.requests));
198 list_del_init(&rq->link);
199 spin_unlock(&engine->timeline.lock);
201 spin_lock(&rq->lock);
202 if (!i915_request_signaled(rq))
203 dma_fence_signal_locked(&rq->fence);
204 if (test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT, &rq->fence.flags))
205 intel_engine_cancel_signaling(rq);
207 GEM_BUG_ON(!atomic_read(&rq->i915->gt_pm.rps.num_waiters));
208 atomic_dec(&rq->i915->gt_pm.rps.num_waiters);
210 spin_unlock(&rq->lock);
215 * The backing object for the context is done after switching to the
216 * *next* context. Therefore we cannot retire the previous context until
217 * the next context has already started running. However, since we
218 * cannot take the required locks at i915_request_submit() we
219 * defer the unpinning of the active context to now, retirement of
220 * the subsequent request.
222 if (engine->last_retired_context)
223 intel_context_unpin(engine->last_retired_context);
224 engine->last_retired_context = rq->hw_context;
227 static void __retire_engine_upto(struct intel_engine_cs *engine,
228 struct i915_request *rq)
230 struct i915_request *tmp;
232 if (list_empty(&rq->link))
236 tmp = list_first_entry(&engine->timeline.requests,
239 GEM_BUG_ON(tmp->engine != engine);
240 __retire_engine_request(engine, tmp);
244 static void i915_request_retire(struct i915_request *request)
246 struct i915_gem_active *active, *next;
248 GEM_TRACE("%s fence %llx:%lld, global=%d, current %d:%d\n",
249 request->engine->name,
250 request->fence.context, request->fence.seqno,
251 request->global_seqno,
253 intel_engine_get_seqno(request->engine));
255 lockdep_assert_held(&request->i915->drm.struct_mutex);
256 GEM_BUG_ON(!i915_sw_fence_signaled(&request->submit));
257 GEM_BUG_ON(!i915_request_completed(request));
259 trace_i915_request_retire(request);
261 advance_ring(request);
262 free_capture_list(request);
265 * Walk through the active list, calling retire on each. This allows
266 * objects to track their GPU activity and mark themselves as idle
267 * when their *last* active request is completed (updating state
268 * tracking lists for eviction, active references for GEM, etc).
270 * As the ->retire() may free the node, we decouple it first and
271 * pass along the auxiliary information (to avoid dereferencing
272 * the node after the callback).
274 list_for_each_entry_safe(active, next, &request->active_list, link) {
276 * In microbenchmarks or focusing upon time inside the kernel,
277 * we may spend an inordinate amount of time simply handling
278 * the retirement of requests and processing their callbacks.
279 * Of which, this loop itself is particularly hot due to the
280 * cache misses when jumping around the list of i915_gem_active.
281 * So we try to keep this loop as streamlined as possible and
282 * also prefetch the next i915_gem_active to try and hide
283 * the likely cache miss.
287 INIT_LIST_HEAD(&active->link);
288 RCU_INIT_POINTER(active->request, NULL);
290 active->retire(active, request);
293 i915_request_remove_from_client(request);
295 /* Retirement decays the ban score as it is a sign of ctx progress */
296 atomic_dec_if_positive(&request->gem_context->ban_score);
297 intel_context_unpin(request->hw_context);
299 __retire_engine_upto(request->engine, request);
301 unreserve_gt(request->i915);
303 i915_sched_node_fini(request->i915, &request->sched);
304 i915_request_put(request);
307 void i915_request_retire_upto(struct i915_request *rq)
309 struct intel_ring *ring = rq->ring;
310 struct i915_request *tmp;
312 GEM_TRACE("%s fence %llx:%lld, global=%d, current %d:%d\n",
314 rq->fence.context, rq->fence.seqno,
317 intel_engine_get_seqno(rq->engine));
319 lockdep_assert_held(&rq->i915->drm.struct_mutex);
320 GEM_BUG_ON(!i915_request_completed(rq));
322 if (list_empty(&rq->ring_link))
326 tmp = list_first_entry(&ring->request_list,
327 typeof(*tmp), ring_link);
329 i915_request_retire(tmp);
333 static u32 timeline_get_seqno(struct i915_timeline *tl)
338 static void move_to_timeline(struct i915_request *request,
339 struct i915_timeline *timeline)
341 GEM_BUG_ON(request->timeline == &request->engine->timeline);
342 lockdep_assert_held(&request->engine->timeline.lock);
344 spin_lock(&request->timeline->lock);
345 list_move_tail(&request->link, &timeline->requests);
346 spin_unlock(&request->timeline->lock);
349 static u32 next_global_seqno(struct i915_timeline *tl)
356 void __i915_request_submit(struct i915_request *request)
358 struct intel_engine_cs *engine = request->engine;
361 GEM_TRACE("%s fence %llx:%lld -> global=%d, current %d:%d\n",
363 request->fence.context, request->fence.seqno,
364 engine->timeline.seqno + 1,
366 intel_engine_get_seqno(engine));
368 GEM_BUG_ON(!irqs_disabled());
369 lockdep_assert_held(&engine->timeline.lock);
371 GEM_BUG_ON(request->global_seqno);
373 seqno = next_global_seqno(&engine->timeline);
375 GEM_BUG_ON(intel_engine_signaled(engine, seqno));
377 /* We may be recursing from the signal callback of another i915 fence */
378 spin_lock_nested(&request->lock, SINGLE_DEPTH_NESTING);
379 request->global_seqno = seqno;
380 if (test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT, &request->fence.flags))
381 intel_engine_enable_signaling(request, false);
382 spin_unlock(&request->lock);
384 engine->emit_breadcrumb(request,
385 request->ring->vaddr + request->postfix);
387 /* Transfer from per-context onto the global per-engine timeline */
388 move_to_timeline(request, &engine->timeline);
390 trace_i915_request_execute(request);
392 wake_up_all(&request->execute);
395 void i915_request_submit(struct i915_request *request)
397 struct intel_engine_cs *engine = request->engine;
400 /* Will be called from irq-context when using foreign fences. */
401 spin_lock_irqsave(&engine->timeline.lock, flags);
403 __i915_request_submit(request);
405 spin_unlock_irqrestore(&engine->timeline.lock, flags);
408 void __i915_request_unsubmit(struct i915_request *request)
410 struct intel_engine_cs *engine = request->engine;
412 GEM_TRACE("%s fence %llx:%lld <- global=%d, current %d:%d\n",
414 request->fence.context, request->fence.seqno,
415 request->global_seqno,
417 intel_engine_get_seqno(engine));
419 GEM_BUG_ON(!irqs_disabled());
420 lockdep_assert_held(&engine->timeline.lock);
423 * Only unwind in reverse order, required so that the per-context list
424 * is kept in seqno/ring order.
426 GEM_BUG_ON(!request->global_seqno);
427 GEM_BUG_ON(request->global_seqno != engine->timeline.seqno);
428 GEM_BUG_ON(intel_engine_has_completed(engine, request->global_seqno));
429 engine->timeline.seqno--;
431 /* We may be recursing from the signal callback of another i915 fence */
432 spin_lock_nested(&request->lock, SINGLE_DEPTH_NESTING);
433 request->global_seqno = 0;
434 if (test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT, &request->fence.flags))
435 intel_engine_cancel_signaling(request);
436 spin_unlock(&request->lock);
438 /* Transfer back from the global per-engine timeline to per-context */
439 move_to_timeline(request, request->timeline);
442 * We don't need to wake_up any waiters on request->execute, they
443 * will get woken by any other event or us re-adding this request
444 * to the engine timeline (__i915_request_submit()). The waiters
445 * should be quite adapt at finding that the request now has a new
446 * global_seqno to the one they went to sleep on.
450 void i915_request_unsubmit(struct i915_request *request)
452 struct intel_engine_cs *engine = request->engine;
455 /* Will be called from irq-context when using foreign fences. */
456 spin_lock_irqsave(&engine->timeline.lock, flags);
458 __i915_request_unsubmit(request);
460 spin_unlock_irqrestore(&engine->timeline.lock, flags);
463 static int __i915_sw_fence_call
464 submit_notify(struct i915_sw_fence *fence, enum i915_sw_fence_notify state)
466 struct i915_request *request =
467 container_of(fence, typeof(*request), submit);
471 trace_i915_request_submit(request);
473 * We need to serialize use of the submit_request() callback
474 * with its hotplugging performed during an emergency
475 * i915_gem_set_wedged(). We use the RCU mechanism to mark the
476 * critical section in order to force i915_gem_set_wedged() to
477 * wait until the submit_request() is completed before
481 request->engine->submit_request(request);
486 i915_request_put(request);
493 static void ring_retire_requests(struct intel_ring *ring)
495 struct i915_request *rq, *rn;
497 list_for_each_entry_safe(rq, rn, &ring->request_list, ring_link) {
498 if (!i915_request_completed(rq))
501 i915_request_retire(rq);
505 static noinline struct i915_request *
506 i915_request_alloc_slow(struct intel_context *ce)
508 struct intel_ring *ring = ce->ring;
509 struct i915_request *rq;
511 if (list_empty(&ring->request_list))
514 /* Ratelimit ourselves to prevent oom from malicious clients */
515 rq = list_last_entry(&ring->request_list, typeof(*rq), ring_link);
516 cond_synchronize_rcu(rq->rcustate);
518 /* Retire our old requests in the hope that we free some */
519 ring_retire_requests(ring);
522 return kmem_cache_alloc(ce->gem_context->i915->requests, GFP_KERNEL);
526 * i915_request_alloc - allocate a request structure
528 * @engine: engine that we wish to issue the request on.
529 * @ctx: context that the request will be associated with.
531 * Returns a pointer to the allocated request if successful,
532 * or an error code if not.
534 struct i915_request *
535 i915_request_alloc(struct intel_engine_cs *engine, struct i915_gem_context *ctx)
537 struct drm_i915_private *i915 = engine->i915;
538 struct i915_request *rq;
539 struct intel_context *ce;
542 lockdep_assert_held(&i915->drm.struct_mutex);
545 * Preempt contexts are reserved for exclusive use to inject a
546 * preemption context switch. They are never to be used for any trivial
549 GEM_BUG_ON(ctx == i915->preempt_context);
552 * ABI: Before userspace accesses the GPU (e.g. execbuffer), report
553 * EIO if the GPU is already wedged.
555 if (i915_terminally_wedged(&i915->gpu_error))
556 return ERR_PTR(-EIO);
559 * Pinning the contexts may generate requests in order to acquire
560 * GGTT space, so do this first before we reserve a seqno for
563 ce = intel_context_pin(ctx, engine);
569 /* Move our oldest request to the slab-cache (if not in use!) */
570 rq = list_first_entry(&ce->ring->request_list, typeof(*rq), ring_link);
571 if (!list_is_last(&rq->ring_link, &ce->ring->request_list) &&
572 i915_request_completed(rq))
573 i915_request_retire(rq);
576 * Beware: Dragons be flying overhead.
578 * We use RCU to look up requests in flight. The lookups may
579 * race with the request being allocated from the slab freelist.
580 * That is the request we are writing to here, may be in the process
581 * of being read by __i915_gem_active_get_rcu(). As such,
582 * we have to be very careful when overwriting the contents. During
583 * the RCU lookup, we change chase the request->engine pointer,
584 * read the request->global_seqno and increment the reference count.
586 * The reference count is incremented atomically. If it is zero,
587 * the lookup knows the request is unallocated and complete. Otherwise,
588 * it is either still in use, or has been reallocated and reset
589 * with dma_fence_init(). This increment is safe for release as we
590 * check that the request we have a reference to and matches the active
593 * Before we increment the refcount, we chase the request->engine
594 * pointer. We must not call kmem_cache_zalloc() or else we set
595 * that pointer to NULL and cause a crash during the lookup. If
596 * we see the request is completed (based on the value of the
597 * old engine and seqno), the lookup is complete and reports NULL.
598 * If we decide the request is not completed (new engine or seqno),
599 * then we grab a reference and double check that it is still the
600 * active request - which it won't be and restart the lookup.
602 * Do not use kmem_cache_zalloc() here!
604 rq = kmem_cache_alloc(i915->requests,
605 GFP_KERNEL | __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
607 rq = i915_request_alloc_slow(ce);
614 rq->rcustate = get_state_synchronize_rcu();
616 INIT_LIST_HEAD(&rq->active_list);
619 rq->gem_context = ctx;
622 rq->timeline = ce->ring->timeline;
623 GEM_BUG_ON(rq->timeline == &engine->timeline);
624 rq->hwsp_seqno = &engine->status_page.addr[I915_GEM_HWS_INDEX];
626 spin_lock_init(&rq->lock);
627 dma_fence_init(&rq->fence,
630 rq->timeline->fence_context,
631 timeline_get_seqno(rq->timeline));
633 /* We bump the ref for the fence chain */
634 i915_sw_fence_init(&i915_request_get(rq)->submit, submit_notify);
635 init_waitqueue_head(&rq->execute);
637 i915_sched_node_init(&rq->sched);
639 /* No zalloc, must clear what we need by hand */
640 rq->global_seqno = 0;
641 rq->signaling.wait.seqno = 0;
642 rq->file_priv = NULL;
644 rq->capture_list = NULL;
645 rq->waitboost = false;
648 * Reserve space in the ring buffer for all the commands required to
649 * eventually emit this request. This is to guarantee that the
650 * i915_request_add() call can't fail. Note that the reserve may need
651 * to be redone if the request is not actually submitted straight
652 * away, e.g. because a GPU scheduler has deferred it.
654 * Note that due to how we add reserved_space to intel_ring_begin()
655 * we need to double our request to ensure that if we need to wrap
656 * around inside i915_request_add() there is sufficient space at
657 * the beginning of the ring as well.
659 rq->reserved_space = 2 * engine->emit_breadcrumb_dw * sizeof(u32);
662 * Record the position of the start of the request so that
663 * should we detect the updated seqno part-way through the
664 * GPU processing the request, we never over-estimate the
665 * position of the head.
667 rq->head = rq->ring->emit;
669 ret = engine->request_alloc(rq);
673 /* Keep a second pin for the dual retirement along engine and ring */
674 __intel_context_pin(ce);
676 rq->infix = rq->ring->emit; /* end of header; start of user payload */
678 /* Check that we didn't interrupt ourselves with a new request */
679 GEM_BUG_ON(rq->timeline->seqno != rq->fence.seqno);
683 ce->ring->emit = rq->head;
685 /* Make sure we didn't add ourselves to external state before freeing */
686 GEM_BUG_ON(!list_empty(&rq->active_list));
687 GEM_BUG_ON(!list_empty(&rq->sched.signalers_list));
688 GEM_BUG_ON(!list_empty(&rq->sched.waiters_list));
690 kmem_cache_free(i915->requests, rq);
693 intel_context_unpin(ce);
698 i915_request_await_request(struct i915_request *to, struct i915_request *from)
702 GEM_BUG_ON(to == from);
703 GEM_BUG_ON(to->timeline == from->timeline);
705 if (i915_request_completed(from))
708 if (to->engine->schedule) {
709 ret = i915_sched_node_add_dependency(to->i915,
716 if (to->engine == from->engine) {
717 ret = i915_sw_fence_await_sw_fence_gfp(&to->submit,
721 ret = i915_sw_fence_await_dma_fence(&to->submit,
726 return ret < 0 ? ret : 0;
730 i915_request_await_dma_fence(struct i915_request *rq, struct dma_fence *fence)
732 struct dma_fence **child = &fence;
733 unsigned int nchild = 1;
737 * Note that if the fence-array was created in signal-on-any mode,
738 * we should *not* decompose it into its individual fences. However,
739 * we don't currently store which mode the fence-array is operating
740 * in. Fortunately, the only user of signal-on-any is private to
741 * amdgpu and we should not see any incoming fence-array from
742 * sync-file being in signal-on-any mode.
744 if (dma_fence_is_array(fence)) {
745 struct dma_fence_array *array = to_dma_fence_array(fence);
747 child = array->fences;
748 nchild = array->num_fences;
754 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
758 * Requests on the same timeline are explicitly ordered, along
759 * with their dependencies, by i915_request_add() which ensures
760 * that requests are submitted in-order through each ring.
762 if (fence->context == rq->fence.context)
765 /* Squash repeated waits to the same timelines */
766 if (fence->context != rq->i915->mm.unordered_timeline &&
767 i915_timeline_sync_is_later(rq->timeline, fence))
770 if (dma_fence_is_i915(fence))
771 ret = i915_request_await_request(rq, to_request(fence));
773 ret = i915_sw_fence_await_dma_fence(&rq->submit, fence,
779 /* Record the latest fence used against each timeline */
780 if (fence->context != rq->i915->mm.unordered_timeline)
781 i915_timeline_sync_set(rq->timeline, fence);
788 * i915_request_await_object - set this request to (async) wait upon a bo
789 * @to: request we are wishing to use
790 * @obj: object which may be in use on another ring.
791 * @write: whether the wait is on behalf of a writer
793 * This code is meant to abstract object synchronization with the GPU.
794 * Conceptually we serialise writes between engines inside the GPU.
795 * We only allow one engine to write into a buffer at any time, but
796 * multiple readers. To ensure each has a coherent view of memory, we must:
798 * - If there is an outstanding write request to the object, the new
799 * request must wait for it to complete (either CPU or in hw, requests
800 * on the same ring will be naturally ordered).
802 * - If we are a write request (pending_write_domain is set), the new
803 * request must wait for outstanding read requests to complete.
805 * Returns 0 if successful, else propagates up the lower layer error.
808 i915_request_await_object(struct i915_request *to,
809 struct drm_i915_gem_object *obj,
812 struct dma_fence *excl;
816 struct dma_fence **shared;
817 unsigned int count, i;
819 ret = reservation_object_get_fences_rcu(obj->resv,
820 &excl, &count, &shared);
824 for (i = 0; i < count; i++) {
825 ret = i915_request_await_dma_fence(to, shared[i]);
829 dma_fence_put(shared[i]);
832 for (; i < count; i++)
833 dma_fence_put(shared[i]);
836 excl = reservation_object_get_excl_rcu(obj->resv);
841 ret = i915_request_await_dma_fence(to, excl);
849 void i915_request_skip(struct i915_request *rq, int error)
851 void *vaddr = rq->ring->vaddr;
854 GEM_BUG_ON(!IS_ERR_VALUE((long)error));
855 dma_fence_set_error(&rq->fence, error);
858 * As this request likely depends on state from the lost
859 * context, clear out all the user operations leaving the
860 * breadcrumb at the end (so we get the fence notifications).
863 if (rq->postfix < head) {
864 memset(vaddr + head, 0, rq->ring->size - head);
867 memset(vaddr + head, 0, rq->postfix - head);
871 * NB: This function is not allowed to fail. Doing so would mean the the
872 * request is not being tracked for completion but the work itself is
873 * going to happen on the hardware. This would be a Bad Thing(tm).
875 void i915_request_add(struct i915_request *request)
877 struct intel_engine_cs *engine = request->engine;
878 struct i915_timeline *timeline = request->timeline;
879 struct intel_ring *ring = request->ring;
880 struct i915_request *prev;
883 GEM_TRACE("%s fence %llx:%lld\n",
884 engine->name, request->fence.context, request->fence.seqno);
886 lockdep_assert_held(&request->i915->drm.struct_mutex);
887 trace_i915_request_add(request);
890 * Make sure that no request gazumped us - if it was allocated after
891 * our i915_request_alloc() and called __i915_request_add() before
892 * us, the timeline will hold its seqno which is later than ours.
894 GEM_BUG_ON(timeline->seqno != request->fence.seqno);
897 * To ensure that this call will not fail, space for its emissions
898 * should already have been reserved in the ring buffer. Let the ring
899 * know that it is time to use that space up.
901 GEM_BUG_ON(request->reserved_space > request->ring->space);
902 request->reserved_space = 0;
905 * Record the position of the start of the breadcrumb so that
906 * should we detect the updated seqno part-way through the
907 * GPU processing the request, we never over-estimate the
908 * position of the ring's HEAD.
910 cs = intel_ring_begin(request, engine->emit_breadcrumb_dw);
911 GEM_BUG_ON(IS_ERR(cs));
912 request->postfix = intel_ring_offset(request, cs);
915 * Seal the request and mark it as pending execution. Note that
916 * we may inspect this state, without holding any locks, during
917 * hangcheck. Hence we apply the barrier to ensure that we do not
918 * see a more recent value in the hws than we are tracking.
921 prev = i915_gem_active_raw(&timeline->last_request,
922 &request->i915->drm.struct_mutex);
923 if (prev && !i915_request_completed(prev)) {
924 i915_sw_fence_await_sw_fence(&request->submit, &prev->submit,
926 if (engine->schedule)
927 __i915_sched_node_add_dependency(&request->sched,
933 spin_lock_irq(&timeline->lock);
934 list_add_tail(&request->link, &timeline->requests);
935 spin_unlock_irq(&timeline->lock);
937 GEM_BUG_ON(timeline->seqno != request->fence.seqno);
938 i915_gem_active_set(&timeline->last_request, request);
940 list_add_tail(&request->ring_link, &ring->request_list);
941 if (list_is_first(&request->ring_link, &ring->request_list)) {
942 GEM_TRACE("marking %s as active\n", ring->timeline->name);
943 list_add(&ring->active_link, &request->i915->gt.active_rings);
945 request->emitted_jiffies = jiffies;
948 * Let the backend know a new request has arrived that may need
949 * to adjust the existing execution schedule due to a high priority
950 * request - i.e. we may want to preempt the current request in order
951 * to run a high priority dependency chain *before* we can execute this
954 * This is called before the request is ready to run so that we can
955 * decide whether to preempt the entire chain so that it is ready to
956 * run at the earliest possible convenience.
959 rcu_read_lock(); /* RCU serialisation for set-wedged protection */
960 if (engine->schedule) {
961 struct i915_sched_attr attr = request->gem_context->sched;
964 * Boost priorities to new clients (new request flows).
966 * Allow interactive/synchronous clients to jump ahead of
967 * the bulk clients. (FQ_CODEL)
969 if (!prev || i915_request_completed(prev))
970 attr.priority |= I915_PRIORITY_NEWCLIENT;
972 engine->schedule(request, &attr);
975 i915_sw_fence_commit(&request->submit);
976 local_bh_enable(); /* Kick the execlists tasklet if just scheduled */
979 * In typical scenarios, we do not expect the previous request on
980 * the timeline to be still tracked by timeline->last_request if it
981 * has been completed. If the completed request is still here, that
982 * implies that request retirement is a long way behind submission,
983 * suggesting that we haven't been retiring frequently enough from
984 * the combination of retire-before-alloc, waiters and the background
985 * retirement worker. So if the last request on this timeline was
986 * already completed, do a catch up pass, flushing the retirement queue
987 * up to this client. Since we have now moved the heaviest operations
988 * during retirement onto secondary workers, such as freeing objects
989 * or contexts, retiring a bunch of requests is mostly list management
990 * (and cache misses), and so we should not be overly penalizing this
991 * client by performing excess work, though we may still performing
992 * work on behalf of others -- but instead we should benefit from
993 * improved resource management. (Well, that's the theory at least.)
995 if (prev && i915_request_completed(prev))
996 i915_request_retire_upto(prev);
999 static unsigned long local_clock_us(unsigned int *cpu)
1004 * Cheaply and approximately convert from nanoseconds to microseconds.
1005 * The result and subsequent calculations are also defined in the same
1006 * approximate microseconds units. The principal source of timing
1007 * error here is from the simple truncation.
1009 * Note that local_clock() is only defined wrt to the current CPU;
1010 * the comparisons are no longer valid if we switch CPUs. Instead of
1011 * blocking preemption for the entire busywait, we can detect the CPU
1012 * switch and use that as indicator of system load and a reason to
1013 * stop busywaiting, see busywait_stop().
1016 t = local_clock() >> 10;
1022 static bool busywait_stop(unsigned long timeout, unsigned int cpu)
1024 unsigned int this_cpu;
1026 if (time_after(local_clock_us(&this_cpu), timeout))
1029 return this_cpu != cpu;
1032 static bool __i915_spin_request(const struct i915_request *rq,
1033 u32 seqno, int state, unsigned long timeout_us)
1035 struct intel_engine_cs *engine = rq->engine;
1036 unsigned int irq, cpu;
1041 * Only wait for the request if we know it is likely to complete.
1043 * We don't track the timestamps around requests, nor the average
1044 * request length, so we do not have a good indicator that this
1045 * request will complete within the timeout. What we do know is the
1046 * order in which requests are executed by the engine and so we can
1047 * tell if the request has started. If the request hasn't started yet,
1048 * it is a fair assumption that it will not complete within our
1049 * relatively short timeout.
1051 if (!intel_engine_has_started(engine, seqno))
1055 * When waiting for high frequency requests, e.g. during synchronous
1056 * rendering split between the CPU and GPU, the finite amount of time
1057 * required to set up the irq and wait upon it limits the response
1058 * rate. By busywaiting on the request completion for a short while we
1059 * can service the high frequency waits as quick as possible. However,
1060 * if it is a slow request, we want to sleep as quickly as possible.
1061 * The tradeoff between waiting and sleeping is roughly the time it
1062 * takes to sleep on a request, on the order of a microsecond.
1065 irq = READ_ONCE(engine->breadcrumbs.irq_count);
1066 timeout_us += local_clock_us(&cpu);
1068 if (intel_engine_has_completed(engine, seqno))
1069 return seqno == i915_request_global_seqno(rq);
1072 * Seqno are meant to be ordered *before* the interrupt. If
1073 * we see an interrupt without a corresponding seqno advance,
1074 * assume we won't see one in the near future but require
1075 * the engine->seqno_barrier() to fixup coherency.
1077 if (READ_ONCE(engine->breadcrumbs.irq_count) != irq)
1080 if (signal_pending_state(state, current))
1083 if (busywait_stop(timeout_us, cpu))
1087 } while (!need_resched());
1093 * i915_request_wait - wait until execution of request has finished
1094 * @rq: the request to wait upon
1095 * @flags: how to wait
1096 * @timeout: how long to wait in jiffies
1098 * i915_request_wait() waits for the request to be completed, for a
1099 * maximum of @timeout jiffies (with MAX_SCHEDULE_TIMEOUT implying an
1102 * If the caller holds the struct_mutex, the caller must pass I915_WAIT_LOCKED
1103 * in via the flags, and vice versa if the struct_mutex is not held, the caller
1104 * must not specify that the wait is locked.
1106 * Returns the remaining time (in jiffies) if the request completed, which may
1107 * be zero or -ETIME if the request is unfinished after the timeout expires.
1108 * May return -EINTR is called with I915_WAIT_INTERRUPTIBLE and a signal is
1109 * pending before the request completes.
1111 long i915_request_wait(struct i915_request *rq,
1115 const int state = flags & I915_WAIT_INTERRUPTIBLE ?
1116 TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE;
1117 DEFINE_WAIT_FUNC(exec, default_wake_function);
1118 struct intel_wait wait;
1121 GEM_BUG_ON(timeout < 0);
1123 if (i915_request_completed(rq))
1129 trace_i915_request_wait_begin(rq, flags);
1130 add_wait_queue(&rq->execute, &exec);
1131 intel_wait_init(&wait);
1132 if (flags & I915_WAIT_PRIORITY)
1133 i915_schedule_bump_priority(rq, I915_PRIORITY_WAIT);
1137 set_current_state(state);
1138 if (intel_wait_update_request(&wait, rq))
1141 if (signal_pending_state(state, current)) {
1142 timeout = -ERESTARTSYS;
1151 timeout = io_schedule_timeout(timeout);
1154 GEM_BUG_ON(!intel_wait_has_seqno(&wait));
1155 GEM_BUG_ON(!i915_sw_fence_signaled(&rq->submit));
1157 /* Optimistic short spin before touching IRQs */
1158 if (__i915_spin_request(rq, wait.seqno, state, 5))
1161 set_current_state(state);
1162 if (intel_engine_add_wait(rq->engine, &wait))
1164 * In order to check that we haven't missed the interrupt
1165 * as we enabled it, we need to kick ourselves to do a
1166 * coherent check on the seqno before we sleep.
1171 if (signal_pending_state(state, current)) {
1172 timeout = -ERESTARTSYS;
1181 timeout = io_schedule_timeout(timeout);
1183 if (intel_wait_complete(&wait) &&
1184 intel_wait_check_request(&wait, rq))
1187 set_current_state(state);
1190 if (i915_request_completed(rq))
1193 /* Only spin if we know the GPU is processing this request */
1194 if (__i915_spin_request(rq, wait.seqno, state, 2))
1197 if (!intel_wait_check_request(&wait, rq)) {
1198 intel_engine_remove_wait(rq->engine, &wait);
1203 intel_engine_remove_wait(rq->engine, &wait);
1205 __set_current_state(TASK_RUNNING);
1206 remove_wait_queue(&rq->execute, &exec);
1207 trace_i915_request_wait_end(rq);
1212 void i915_retire_requests(struct drm_i915_private *i915)
1214 struct intel_ring *ring, *tmp;
1216 lockdep_assert_held(&i915->drm.struct_mutex);
1218 if (!i915->gt.active_requests)
1221 list_for_each_entry_safe(ring, tmp, &i915->gt.active_rings, active_link)
1222 ring_retire_requests(ring);
1225 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
1226 #include "selftests/mock_request.c"
1227 #include "selftests/i915_request.c"