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/irq_work.h>
27 #include <linux/prefetch.h>
28 #include <linux/sched.h>
29 #include <linux/sched/clock.h>
30 #include <linux/sched/signal.h>
32 #include "i915_active.h"
34 #include "i915_globals.h"
35 #include "i915_reset.h"
39 struct list_head link;
41 struct i915_sw_fence *fence;
44 static struct i915_global_request {
45 struct i915_global base;
46 struct kmem_cache *slab_requests;
47 struct kmem_cache *slab_dependencies;
48 struct kmem_cache *slab_execute_cbs;
51 static const char *i915_fence_get_driver_name(struct dma_fence *fence)
56 static const char *i915_fence_get_timeline_name(struct dma_fence *fence)
59 * The timeline struct (as part of the ppgtt underneath a context)
60 * may be freed when the request is no longer in use by the GPU.
61 * We could extend the life of a context to beyond that of all
62 * fences, possibly keeping the hw resource around indefinitely,
63 * or we just give them a false name. Since
64 * dma_fence_ops.get_timeline_name is a debug feature, the occasional
65 * lie seems justifiable.
67 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
70 return to_request(fence)->gem_context->name ?: "[i915]";
73 static bool i915_fence_signaled(struct dma_fence *fence)
75 return i915_request_completed(to_request(fence));
78 static bool i915_fence_enable_signaling(struct dma_fence *fence)
80 return i915_request_enable_breadcrumb(to_request(fence));
83 static signed long i915_fence_wait(struct dma_fence *fence,
87 return i915_request_wait(to_request(fence),
88 interruptible | I915_WAIT_PRIORITY,
92 static void i915_fence_release(struct dma_fence *fence)
94 struct i915_request *rq = to_request(fence);
97 * The request is put onto a RCU freelist (i.e. the address
98 * is immediately reused), mark the fences as being freed now.
99 * Otherwise the debugobjects for the fences are only marked as
100 * freed when the slab cache itself is freed, and so we would get
101 * caught trying to reuse dead objects.
103 i915_sw_fence_fini(&rq->submit);
104 i915_sw_fence_fini(&rq->semaphore);
106 kmem_cache_free(global.slab_requests, rq);
109 const struct dma_fence_ops i915_fence_ops = {
110 .get_driver_name = i915_fence_get_driver_name,
111 .get_timeline_name = i915_fence_get_timeline_name,
112 .enable_signaling = i915_fence_enable_signaling,
113 .signaled = i915_fence_signaled,
114 .wait = i915_fence_wait,
115 .release = i915_fence_release,
119 i915_request_remove_from_client(struct i915_request *request)
121 struct drm_i915_file_private *file_priv;
123 file_priv = request->file_priv;
127 spin_lock(&file_priv->mm.lock);
128 if (request->file_priv) {
129 list_del(&request->client_link);
130 request->file_priv = NULL;
132 spin_unlock(&file_priv->mm.lock);
135 static void reserve_gt(struct drm_i915_private *i915)
137 if (!i915->gt.active_requests++)
138 i915_gem_unpark(i915);
141 static void unreserve_gt(struct drm_i915_private *i915)
143 GEM_BUG_ON(!i915->gt.active_requests);
144 if (!--i915->gt.active_requests)
148 static void advance_ring(struct i915_request *request)
150 struct intel_ring *ring = request->ring;
154 * We know the GPU must have read the request to have
155 * sent us the seqno + interrupt, so use the position
156 * of tail of the request to update the last known position
159 * Note this requires that we are always called in request
162 GEM_BUG_ON(!list_is_first(&request->ring_link, &ring->request_list));
163 if (list_is_last(&request->ring_link, &ring->request_list)) {
165 * We may race here with execlists resubmitting this request
166 * as we retire it. The resubmission will move the ring->tail
167 * forwards (to request->wa_tail). We either read the
168 * current value that was written to hw, or the value that
169 * is just about to be. Either works, if we miss the last two
170 * noops - they are safe to be replayed on a reset.
172 tail = READ_ONCE(request->tail);
173 list_del(&ring->active_link);
175 tail = request->postfix;
177 list_del_init(&request->ring_link);
182 static void free_capture_list(struct i915_request *request)
184 struct i915_capture_list *capture;
186 capture = request->capture_list;
188 struct i915_capture_list *next = capture->next;
195 static void __retire_engine_request(struct intel_engine_cs *engine,
196 struct i915_request *rq)
198 GEM_TRACE("%s(%s) fence %llx:%lld, current %d\n",
199 __func__, engine->name,
200 rq->fence.context, rq->fence.seqno,
203 GEM_BUG_ON(!i915_request_completed(rq));
207 spin_lock(&engine->timeline.lock);
208 GEM_BUG_ON(!list_is_first(&rq->link, &engine->timeline.requests));
209 list_del_init(&rq->link);
210 spin_unlock(&engine->timeline.lock);
212 spin_lock(&rq->lock);
213 i915_request_mark_complete(rq);
214 if (!i915_request_signaled(rq))
215 dma_fence_signal_locked(&rq->fence);
216 if (test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT, &rq->fence.flags))
217 i915_request_cancel_breadcrumb(rq);
219 GEM_BUG_ON(!atomic_read(&rq->i915->gt_pm.rps.num_waiters));
220 atomic_dec(&rq->i915->gt_pm.rps.num_waiters);
222 spin_unlock(&rq->lock);
227 * The backing object for the context is done after switching to the
228 * *next* context. Therefore we cannot retire the previous context until
229 * the next context has already started running. However, since we
230 * cannot take the required locks at i915_request_submit() we
231 * defer the unpinning of the active context to now, retirement of
232 * the subsequent request.
234 if (engine->last_retired_context)
235 intel_context_unpin(engine->last_retired_context);
236 engine->last_retired_context = rq->hw_context;
239 static void __retire_engine_upto(struct intel_engine_cs *engine,
240 struct i915_request *rq)
242 struct i915_request *tmp;
244 if (list_empty(&rq->link))
248 tmp = list_first_entry(&engine->timeline.requests,
251 GEM_BUG_ON(tmp->engine != engine);
252 __retire_engine_request(engine, tmp);
256 static void i915_request_retire(struct i915_request *request)
258 struct i915_active_request *active, *next;
260 GEM_TRACE("%s fence %llx:%lld, current %d\n",
261 request->engine->name,
262 request->fence.context, request->fence.seqno,
263 hwsp_seqno(request));
265 lockdep_assert_held(&request->i915->drm.struct_mutex);
266 GEM_BUG_ON(!i915_sw_fence_signaled(&request->submit));
267 GEM_BUG_ON(!i915_request_completed(request));
269 trace_i915_request_retire(request);
271 advance_ring(request);
272 free_capture_list(request);
275 * Walk through the active list, calling retire on each. This allows
276 * objects to track their GPU activity and mark themselves as idle
277 * when their *last* active request is completed (updating state
278 * tracking lists for eviction, active references for GEM, etc).
280 * As the ->retire() may free the node, we decouple it first and
281 * pass along the auxiliary information (to avoid dereferencing
282 * the node after the callback).
284 list_for_each_entry_safe(active, next, &request->active_list, link) {
286 * In microbenchmarks or focusing upon time inside the kernel,
287 * we may spend an inordinate amount of time simply handling
288 * the retirement of requests and processing their callbacks.
289 * Of which, this loop itself is particularly hot due to the
290 * cache misses when jumping around the list of
291 * i915_active_request. So we try to keep this loop as
292 * streamlined as possible and also prefetch the next
293 * i915_active_request to try and hide the likely cache miss.
297 INIT_LIST_HEAD(&active->link);
298 RCU_INIT_POINTER(active->request, NULL);
300 active->retire(active, request);
303 i915_request_remove_from_client(request);
305 intel_context_unpin(request->hw_context);
307 __retire_engine_upto(request->engine, request);
309 unreserve_gt(request->i915);
311 i915_sched_node_fini(&request->sched);
312 i915_request_put(request);
315 void i915_request_retire_upto(struct i915_request *rq)
317 struct intel_ring *ring = rq->ring;
318 struct i915_request *tmp;
320 GEM_TRACE("%s fence %llx:%lld, current %d\n",
322 rq->fence.context, rq->fence.seqno,
325 lockdep_assert_held(&rq->i915->drm.struct_mutex);
326 GEM_BUG_ON(!i915_request_completed(rq));
328 if (list_empty(&rq->ring_link))
332 tmp = list_first_entry(&ring->request_list,
333 typeof(*tmp), ring_link);
335 i915_request_retire(tmp);
339 static void irq_execute_cb(struct irq_work *wrk)
341 struct execute_cb *cb = container_of(wrk, typeof(*cb), work);
343 i915_sw_fence_complete(cb->fence);
344 kmem_cache_free(global.slab_execute_cbs, cb);
347 static void __notify_execute_cb(struct i915_request *rq)
349 struct execute_cb *cb;
351 lockdep_assert_held(&rq->lock);
353 if (list_empty(&rq->execute_cb))
356 list_for_each_entry(cb, &rq->execute_cb, link)
357 irq_work_queue(&cb->work);
360 * XXX Rollback on __i915_request_unsubmit()
362 * In the future, perhaps when we have an active time-slicing scheduler,
363 * it will be interesting to unsubmit parallel execution and remove
364 * busywaits from the GPU until their master is restarted. This is
365 * quite hairy, we have to carefully rollback the fence and do a
366 * preempt-to-idle cycle on the target engine, all the while the
367 * master execute_cb may refire.
369 INIT_LIST_HEAD(&rq->execute_cb);
373 i915_request_await_execution(struct i915_request *rq,
374 struct i915_request *signal,
377 struct execute_cb *cb;
379 if (i915_request_is_active(signal))
382 cb = kmem_cache_alloc(global.slab_execute_cbs, gfp);
386 cb->fence = &rq->submit;
387 i915_sw_fence_await(cb->fence);
388 init_irq_work(&cb->work, irq_execute_cb);
390 spin_lock_irq(&signal->lock);
391 if (i915_request_is_active(signal)) {
392 i915_sw_fence_complete(cb->fence);
393 kmem_cache_free(global.slab_execute_cbs, cb);
395 list_add_tail(&cb->link, &signal->execute_cb);
397 spin_unlock_irq(&signal->lock);
402 static void move_to_timeline(struct i915_request *request,
403 struct i915_timeline *timeline)
405 GEM_BUG_ON(request->timeline == &request->engine->timeline);
406 lockdep_assert_held(&request->engine->timeline.lock);
408 spin_lock(&request->timeline->lock);
409 list_move_tail(&request->link, &timeline->requests);
410 spin_unlock(&request->timeline->lock);
413 void __i915_request_submit(struct i915_request *request)
415 struct intel_engine_cs *engine = request->engine;
417 GEM_TRACE("%s fence %llx:%lld -> current %d\n",
419 request->fence.context, request->fence.seqno,
420 hwsp_seqno(request));
422 GEM_BUG_ON(!irqs_disabled());
423 lockdep_assert_held(&engine->timeline.lock);
425 if (i915_gem_context_is_banned(request->gem_context))
426 i915_request_skip(request, -EIO);
429 * Are we using semaphores when the gpu is already saturated?
431 * Using semaphores incurs a cost in having the GPU poll a
432 * memory location, busywaiting for it to change. The continual
433 * memory reads can have a noticeable impact on the rest of the
434 * system with the extra bus traffic, stalling the cpu as it too
435 * tries to access memory across the bus (perf stat -e bus-cycles).
437 * If we installed a semaphore on this request and we only submit
438 * the request after the signaler completed, that indicates the
439 * system is overloaded and using semaphores at this time only
440 * increases the amount of work we are doing. If so, we disable
441 * further use of semaphores until we are idle again, whence we
442 * optimistically try again.
444 if (request->sched.semaphores &&
445 i915_sw_fence_signaled(&request->semaphore))
446 request->hw_context->saturated |= request->sched.semaphores;
448 /* We may be recursing from the signal callback of another i915 fence */
449 spin_lock_nested(&request->lock, SINGLE_DEPTH_NESTING);
451 GEM_BUG_ON(test_bit(I915_FENCE_FLAG_ACTIVE, &request->fence.flags));
452 set_bit(I915_FENCE_FLAG_ACTIVE, &request->fence.flags);
454 if (test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT, &request->fence.flags) &&
455 !i915_request_enable_breadcrumb(request))
456 intel_engine_queue_breadcrumbs(engine);
458 __notify_execute_cb(request);
460 spin_unlock(&request->lock);
462 engine->emit_fini_breadcrumb(request,
463 request->ring->vaddr + request->postfix);
465 /* Transfer from per-context onto the global per-engine timeline */
466 move_to_timeline(request, &engine->timeline);
468 trace_i915_request_execute(request);
471 void i915_request_submit(struct i915_request *request)
473 struct intel_engine_cs *engine = request->engine;
476 /* Will be called from irq-context when using foreign fences. */
477 spin_lock_irqsave(&engine->timeline.lock, flags);
479 __i915_request_submit(request);
481 spin_unlock_irqrestore(&engine->timeline.lock, flags);
484 void __i915_request_unsubmit(struct i915_request *request)
486 struct intel_engine_cs *engine = request->engine;
488 GEM_TRACE("%s fence %llx:%lld, current %d\n",
490 request->fence.context, request->fence.seqno,
491 hwsp_seqno(request));
493 GEM_BUG_ON(!irqs_disabled());
494 lockdep_assert_held(&engine->timeline.lock);
497 * Only unwind in reverse order, required so that the per-context list
498 * is kept in seqno/ring order.
501 /* We may be recursing from the signal callback of another i915 fence */
502 spin_lock_nested(&request->lock, SINGLE_DEPTH_NESTING);
505 * As we do not allow WAIT to preempt inflight requests,
506 * once we have executed a request, along with triggering
507 * any execution callbacks, we must preserve its ordering
508 * within the non-preemptible FIFO.
510 BUILD_BUG_ON(__NO_PREEMPTION & ~I915_PRIORITY_MASK); /* only internal */
511 request->sched.attr.priority |= __NO_PREEMPTION;
513 if (test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT, &request->fence.flags))
514 i915_request_cancel_breadcrumb(request);
516 GEM_BUG_ON(!test_bit(I915_FENCE_FLAG_ACTIVE, &request->fence.flags));
517 clear_bit(I915_FENCE_FLAG_ACTIVE, &request->fence.flags);
519 spin_unlock(&request->lock);
521 /* Transfer back from the global per-engine timeline to per-context */
522 move_to_timeline(request, request->timeline);
525 * We don't need to wake_up any waiters on request->execute, they
526 * will get woken by any other event or us re-adding this request
527 * to the engine timeline (__i915_request_submit()). The waiters
528 * should be quite adapt at finding that the request now has a new
529 * global_seqno to the one they went to sleep on.
533 void i915_request_unsubmit(struct i915_request *request)
535 struct intel_engine_cs *engine = request->engine;
538 /* Will be called from irq-context when using foreign fences. */
539 spin_lock_irqsave(&engine->timeline.lock, flags);
541 __i915_request_unsubmit(request);
543 spin_unlock_irqrestore(&engine->timeline.lock, flags);
546 static int __i915_sw_fence_call
547 submit_notify(struct i915_sw_fence *fence, enum i915_sw_fence_notify state)
549 struct i915_request *request =
550 container_of(fence, typeof(*request), submit);
554 trace_i915_request_submit(request);
556 * We need to serialize use of the submit_request() callback
557 * with its hotplugging performed during an emergency
558 * i915_gem_set_wedged(). We use the RCU mechanism to mark the
559 * critical section in order to force i915_gem_set_wedged() to
560 * wait until the submit_request() is completed before
564 request->engine->submit_request(request);
569 i915_request_put(request);
576 static int __i915_sw_fence_call
577 semaphore_notify(struct i915_sw_fence *fence, enum i915_sw_fence_notify state)
579 struct i915_request *request =
580 container_of(fence, typeof(*request), semaphore);
585 * We only check a small portion of our dependencies
586 * and so cannot guarantee that there remains no
587 * semaphore chain across all. Instead of opting
588 * for the full NOSEMAPHORE boost, we go for the
589 * smaller (but still preempting) boost of
590 * NEWCLIENT. This will be enough to boost over
591 * a busywaiting request (as that cannot be
592 * NEWCLIENT) without accidentally boosting
593 * a busywait over real work elsewhere.
595 i915_schedule_bump_priority(request, I915_PRIORITY_NEWCLIENT);
599 i915_request_put(request);
606 static void ring_retire_requests(struct intel_ring *ring)
608 struct i915_request *rq, *rn;
610 list_for_each_entry_safe(rq, rn, &ring->request_list, ring_link) {
611 if (!i915_request_completed(rq))
614 i915_request_retire(rq);
618 static noinline struct i915_request *
619 i915_request_alloc_slow(struct intel_context *ce)
621 struct intel_ring *ring = ce->ring;
622 struct i915_request *rq;
624 if (list_empty(&ring->request_list))
627 /* Ratelimit ourselves to prevent oom from malicious clients */
628 rq = list_last_entry(&ring->request_list, typeof(*rq), ring_link);
629 cond_synchronize_rcu(rq->rcustate);
631 /* Retire our old requests in the hope that we free some */
632 ring_retire_requests(ring);
635 return kmem_cache_alloc(global.slab_requests, GFP_KERNEL);
639 * i915_request_alloc - allocate a request structure
641 * @engine: engine that we wish to issue the request on.
642 * @ctx: context that the request will be associated with.
644 * Returns a pointer to the allocated request if successful,
645 * or an error code if not.
647 struct i915_request *
648 i915_request_alloc(struct intel_engine_cs *engine, struct i915_gem_context *ctx)
650 struct drm_i915_private *i915 = engine->i915;
651 struct intel_context *ce;
652 struct i915_timeline *tl;
653 struct i915_request *rq;
657 lockdep_assert_held(&i915->drm.struct_mutex);
660 * Preempt contexts are reserved for exclusive use to inject a
661 * preemption context switch. They are never to be used for any trivial
664 GEM_BUG_ON(ctx == i915->preempt_context);
667 * ABI: Before userspace accesses the GPU (e.g. execbuffer), report
668 * EIO if the GPU is already wedged.
670 ret = i915_terminally_wedged(i915);
675 * Pinning the contexts may generate requests in order to acquire
676 * GGTT space, so do this first before we reserve a seqno for
679 ce = intel_context_pin(ctx, engine);
684 mutex_lock(&ce->ring->timeline->mutex);
686 /* Move our oldest request to the slab-cache (if not in use!) */
687 rq = list_first_entry(&ce->ring->request_list, typeof(*rq), ring_link);
688 if (!list_is_last(&rq->ring_link, &ce->ring->request_list) &&
689 i915_request_completed(rq))
690 i915_request_retire(rq);
693 * Beware: Dragons be flying overhead.
695 * We use RCU to look up requests in flight. The lookups may
696 * race with the request being allocated from the slab freelist.
697 * That is the request we are writing to here, may be in the process
698 * of being read by __i915_active_request_get_rcu(). As such,
699 * we have to be very careful when overwriting the contents. During
700 * the RCU lookup, we change chase the request->engine pointer,
701 * read the request->global_seqno and increment the reference count.
703 * The reference count is incremented atomically. If it is zero,
704 * the lookup knows the request is unallocated and complete. Otherwise,
705 * it is either still in use, or has been reallocated and reset
706 * with dma_fence_init(). This increment is safe for release as we
707 * check that the request we have a reference to and matches the active
710 * Before we increment the refcount, we chase the request->engine
711 * pointer. We must not call kmem_cache_zalloc() or else we set
712 * that pointer to NULL and cause a crash during the lookup. If
713 * we see the request is completed (based on the value of the
714 * old engine and seqno), the lookup is complete and reports NULL.
715 * If we decide the request is not completed (new engine or seqno),
716 * then we grab a reference and double check that it is still the
717 * active request - which it won't be and restart the lookup.
719 * Do not use kmem_cache_zalloc() here!
721 rq = kmem_cache_alloc(global.slab_requests,
722 GFP_KERNEL | __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
724 rq = i915_request_alloc_slow(ce);
731 INIT_LIST_HEAD(&rq->active_list);
732 INIT_LIST_HEAD(&rq->execute_cb);
734 tl = ce->ring->timeline;
735 ret = i915_timeline_get_seqno(tl, rq, &seqno);
741 rq->gem_context = ctx;
745 GEM_BUG_ON(rq->timeline == &engine->timeline);
746 rq->hwsp_seqno = tl->hwsp_seqno;
747 rq->hwsp_cacheline = tl->hwsp_cacheline;
748 rq->rcustate = get_state_synchronize_rcu(); /* acts as smp_mb() */
750 spin_lock_init(&rq->lock);
751 dma_fence_init(&rq->fence, &i915_fence_ops, &rq->lock,
752 tl->fence_context, seqno);
754 /* We bump the ref for the fence chain */
755 i915_sw_fence_init(&i915_request_get(rq)->submit, submit_notify);
756 i915_sw_fence_init(&i915_request_get(rq)->semaphore, semaphore_notify);
758 i915_sched_node_init(&rq->sched);
760 /* No zalloc, must clear what we need by hand */
761 rq->file_priv = NULL;
763 rq->capture_list = NULL;
764 rq->waitboost = false;
767 * Reserve space in the ring buffer for all the commands required to
768 * eventually emit this request. This is to guarantee that the
769 * i915_request_add() call can't fail. Note that the reserve may need
770 * to be redone if the request is not actually submitted straight
771 * away, e.g. because a GPU scheduler has deferred it.
773 * Note that due to how we add reserved_space to intel_ring_begin()
774 * we need to double our request to ensure that if we need to wrap
775 * around inside i915_request_add() there is sufficient space at
776 * the beginning of the ring as well.
778 rq->reserved_space = 2 * engine->emit_fini_breadcrumb_dw * sizeof(u32);
781 * Record the position of the start of the request so that
782 * should we detect the updated seqno part-way through the
783 * GPU processing the request, we never over-estimate the
784 * position of the head.
786 rq->head = rq->ring->emit;
788 ret = engine->request_alloc(rq);
792 /* Keep a second pin for the dual retirement along engine and ring */
793 __intel_context_pin(ce);
795 rq->infix = rq->ring->emit; /* end of header; start of user payload */
797 /* Check that we didn't interrupt ourselves with a new request */
798 lockdep_assert_held(&rq->timeline->mutex);
799 GEM_BUG_ON(rq->timeline->seqno != rq->fence.seqno);
800 rq->cookie = lockdep_pin_lock(&rq->timeline->mutex);
805 ce->ring->emit = rq->head;
807 /* Make sure we didn't add ourselves to external state before freeing */
808 GEM_BUG_ON(!list_empty(&rq->active_list));
809 GEM_BUG_ON(!list_empty(&rq->sched.signalers_list));
810 GEM_BUG_ON(!list_empty(&rq->sched.waiters_list));
813 kmem_cache_free(global.slab_requests, rq);
815 mutex_unlock(&ce->ring->timeline->mutex);
817 intel_context_unpin(ce);
822 i915_request_await_start(struct i915_request *rq, struct i915_request *signal)
824 if (list_is_first(&signal->ring_link, &signal->ring->request_list))
827 signal = list_prev_entry(signal, ring_link);
828 if (i915_timeline_sync_is_later(rq->timeline, &signal->fence))
831 return i915_sw_fence_await_dma_fence(&rq->submit,
836 static intel_engine_mask_t
837 already_busywaiting(struct i915_request *rq)
840 * Polling a semaphore causes bus traffic, delaying other users of
841 * both the GPU and CPU. We want to limit the impact on others,
842 * while taking advantage of early submission to reduce GPU
843 * latency. Therefore we restrict ourselves to not using more
844 * than one semaphore from each source, and not using a semaphore
845 * if we have detected the engine is saturated (i.e. would not be
846 * submitted early and cause bus traffic reading an already passed
849 * See the are-we-too-late? check in __i915_request_submit().
851 return rq->sched.semaphores | rq->hw_context->saturated;
855 emit_semaphore_wait(struct i915_request *to,
856 struct i915_request *from,
863 GEM_BUG_ON(!from->timeline->has_initial_breadcrumb);
864 GEM_BUG_ON(INTEL_GEN(to->i915) < 8);
866 /* Just emit the first semaphore we see as request space is limited. */
867 if (already_busywaiting(to) & from->engine->mask)
868 return i915_sw_fence_await_dma_fence(&to->submit,
872 err = i915_request_await_start(to, from);
876 err = i915_sw_fence_await_dma_fence(&to->semaphore,
882 /* We need to pin the signaler's HWSP until we are finished reading. */
883 err = i915_timeline_read_hwsp(from, to, &hwsp_offset);
887 /* Only submit our spinner after the signaler is running! */
888 err = i915_request_await_execution(to, from, gfp);
892 cs = intel_ring_begin(to, 4);
897 * Using greater-than-or-equal here means we have to worry
898 * about seqno wraparound. To side step that issue, we swap
899 * the timeline HWSP upon wrapping, so that everyone listening
900 * for the old (pre-wrap) values do not see the much smaller
901 * (post-wrap) values than they were expecting (and so wait
904 *cs++ = MI_SEMAPHORE_WAIT |
905 MI_SEMAPHORE_GLOBAL_GTT |
907 MI_SEMAPHORE_SAD_GTE_SDD;
908 *cs++ = from->fence.seqno;
912 intel_ring_advance(to, cs);
913 to->sched.semaphores |= from->engine->mask;
914 to->sched.flags |= I915_SCHED_HAS_SEMAPHORE_CHAIN;
919 i915_request_await_request(struct i915_request *to, struct i915_request *from)
923 GEM_BUG_ON(to == from);
924 GEM_BUG_ON(to->timeline == from->timeline);
926 if (i915_request_completed(from))
929 if (to->engine->schedule) {
930 ret = i915_sched_node_add_dependency(&to->sched, &from->sched);
935 if (to->engine == from->engine) {
936 ret = i915_sw_fence_await_sw_fence_gfp(&to->submit,
939 } else if (intel_engine_has_semaphores(to->engine) &&
940 to->gem_context->sched.priority >= I915_PRIORITY_NORMAL) {
941 ret = emit_semaphore_wait(to, from, I915_FENCE_GFP);
943 ret = i915_sw_fence_await_dma_fence(&to->submit,
948 return ret < 0 ? ret : 0;
952 i915_request_await_dma_fence(struct i915_request *rq, struct dma_fence *fence)
954 struct dma_fence **child = &fence;
955 unsigned int nchild = 1;
959 * Note that if the fence-array was created in signal-on-any mode,
960 * we should *not* decompose it into its individual fences. However,
961 * we don't currently store which mode the fence-array is operating
962 * in. Fortunately, the only user of signal-on-any is private to
963 * amdgpu and we should not see any incoming fence-array from
964 * sync-file being in signal-on-any mode.
966 if (dma_fence_is_array(fence)) {
967 struct dma_fence_array *array = to_dma_fence_array(fence);
969 child = array->fences;
970 nchild = array->num_fences;
976 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
980 * Requests on the same timeline are explicitly ordered, along
981 * with their dependencies, by i915_request_add() which ensures
982 * that requests are submitted in-order through each ring.
984 if (fence->context == rq->fence.context)
987 /* Squash repeated waits to the same timelines */
988 if (fence->context != rq->i915->mm.unordered_timeline &&
989 i915_timeline_sync_is_later(rq->timeline, fence))
992 if (dma_fence_is_i915(fence))
993 ret = i915_request_await_request(rq, to_request(fence));
995 ret = i915_sw_fence_await_dma_fence(&rq->submit, fence,
1001 /* Record the latest fence used against each timeline */
1002 if (fence->context != rq->i915->mm.unordered_timeline)
1003 i915_timeline_sync_set(rq->timeline, fence);
1010 * i915_request_await_object - set this request to (async) wait upon a bo
1011 * @to: request we are wishing to use
1012 * @obj: object which may be in use on another ring.
1013 * @write: whether the wait is on behalf of a writer
1015 * This code is meant to abstract object synchronization with the GPU.
1016 * Conceptually we serialise writes between engines inside the GPU.
1017 * We only allow one engine to write into a buffer at any time, but
1018 * multiple readers. To ensure each has a coherent view of memory, we must:
1020 * - If there is an outstanding write request to the object, the new
1021 * request must wait for it to complete (either CPU or in hw, requests
1022 * on the same ring will be naturally ordered).
1024 * - If we are a write request (pending_write_domain is set), the new
1025 * request must wait for outstanding read requests to complete.
1027 * Returns 0 if successful, else propagates up the lower layer error.
1030 i915_request_await_object(struct i915_request *to,
1031 struct drm_i915_gem_object *obj,
1034 struct dma_fence *excl;
1038 struct dma_fence **shared;
1039 unsigned int count, i;
1041 ret = reservation_object_get_fences_rcu(obj->resv,
1042 &excl, &count, &shared);
1046 for (i = 0; i < count; i++) {
1047 ret = i915_request_await_dma_fence(to, shared[i]);
1051 dma_fence_put(shared[i]);
1054 for (; i < count; i++)
1055 dma_fence_put(shared[i]);
1058 excl = reservation_object_get_excl_rcu(obj->resv);
1063 ret = i915_request_await_dma_fence(to, excl);
1065 dma_fence_put(excl);
1071 void i915_request_skip(struct i915_request *rq, int error)
1073 void *vaddr = rq->ring->vaddr;
1076 GEM_BUG_ON(!IS_ERR_VALUE((long)error));
1077 dma_fence_set_error(&rq->fence, error);
1080 * As this request likely depends on state from the lost
1081 * context, clear out all the user operations leaving the
1082 * breadcrumb at the end (so we get the fence notifications).
1085 if (rq->postfix < head) {
1086 memset(vaddr + head, 0, rq->ring->size - head);
1089 memset(vaddr + head, 0, rq->postfix - head);
1092 static struct i915_request *
1093 __i915_request_add_to_timeline(struct i915_request *rq)
1095 struct i915_timeline *timeline = rq->timeline;
1096 struct i915_request *prev;
1099 * Dependency tracking and request ordering along the timeline
1100 * is special cased so that we can eliminate redundant ordering
1101 * operations while building the request (we know that the timeline
1102 * itself is ordered, and here we guarantee it).
1104 * As we know we will need to emit tracking along the timeline,
1105 * we embed the hooks into our request struct -- at the cost of
1106 * having to have specialised no-allocation interfaces (which will
1107 * be beneficial elsewhere).
1109 * A second benefit to open-coding i915_request_await_request is
1110 * that we can apply a slight variant of the rules specialised
1111 * for timelines that jump between engines (such as virtual engines).
1112 * If we consider the case of virtual engine, we must emit a dma-fence
1113 * to prevent scheduling of the second request until the first is
1114 * complete (to maximise our greedy late load balancing) and this
1115 * precludes optimising to use semaphores serialisation of a single
1116 * timeline across engines.
1118 prev = i915_active_request_raw(&timeline->last_request,
1119 &rq->i915->drm.struct_mutex);
1120 if (prev && !i915_request_completed(prev)) {
1121 if (is_power_of_2(prev->engine->mask | rq->engine->mask))
1122 i915_sw_fence_await_sw_fence(&rq->submit,
1126 __i915_sw_fence_await_dma_fence(&rq->submit,
1129 if (rq->engine->schedule)
1130 __i915_sched_node_add_dependency(&rq->sched,
1136 spin_lock_irq(&timeline->lock);
1137 list_add_tail(&rq->link, &timeline->requests);
1138 spin_unlock_irq(&timeline->lock);
1140 GEM_BUG_ON(timeline->seqno != rq->fence.seqno);
1141 __i915_active_request_set(&timeline->last_request, rq);
1147 * NB: This function is not allowed to fail. Doing so would mean the the
1148 * request is not being tracked for completion but the work itself is
1149 * going to happen on the hardware. This would be a Bad Thing(tm).
1151 void i915_request_add(struct i915_request *request)
1153 struct intel_engine_cs *engine = request->engine;
1154 struct i915_timeline *timeline = request->timeline;
1155 struct intel_ring *ring = request->ring;
1156 struct i915_request *prev;
1159 GEM_TRACE("%s fence %llx:%lld\n",
1160 engine->name, request->fence.context, request->fence.seqno);
1162 lockdep_assert_held(&request->timeline->mutex);
1163 lockdep_unpin_lock(&request->timeline->mutex, request->cookie);
1165 trace_i915_request_add(request);
1168 * Make sure that no request gazumped us - if it was allocated after
1169 * our i915_request_alloc() and called __i915_request_add() before
1170 * us, the timeline will hold its seqno which is later than ours.
1172 GEM_BUG_ON(timeline->seqno != request->fence.seqno);
1175 * To ensure that this call will not fail, space for its emissions
1176 * should already have been reserved in the ring buffer. Let the ring
1177 * know that it is time to use that space up.
1179 GEM_BUG_ON(request->reserved_space > request->ring->space);
1180 request->reserved_space = 0;
1183 * Record the position of the start of the breadcrumb so that
1184 * should we detect the updated seqno part-way through the
1185 * GPU processing the request, we never over-estimate the
1186 * position of the ring's HEAD.
1188 cs = intel_ring_begin(request, engine->emit_fini_breadcrumb_dw);
1189 GEM_BUG_ON(IS_ERR(cs));
1190 request->postfix = intel_ring_offset(request, cs);
1192 prev = __i915_request_add_to_timeline(request);
1194 list_add_tail(&request->ring_link, &ring->request_list);
1195 if (list_is_first(&request->ring_link, &ring->request_list))
1196 list_add(&ring->active_link, &request->i915->gt.active_rings);
1197 request->i915->gt.active_engines |= request->engine->mask;
1198 request->emitted_jiffies = jiffies;
1201 * Let the backend know a new request has arrived that may need
1202 * to adjust the existing execution schedule due to a high priority
1203 * request - i.e. we may want to preempt the current request in order
1204 * to run a high priority dependency chain *before* we can execute this
1207 * This is called before the request is ready to run so that we can
1208 * decide whether to preempt the entire chain so that it is ready to
1209 * run at the earliest possible convenience.
1212 i915_sw_fence_commit(&request->semaphore);
1213 rcu_read_lock(); /* RCU serialisation for set-wedged protection */
1214 if (engine->schedule) {
1215 struct i915_sched_attr attr = request->gem_context->sched;
1218 * Boost actual workloads past semaphores!
1220 * With semaphores we spin on one engine waiting for another,
1221 * simply to reduce the latency of starting our work when
1222 * the signaler completes. However, if there is any other
1223 * work that we could be doing on this engine instead, that
1224 * is better utilisation and will reduce the overall duration
1225 * of the current work. To avoid PI boosting a semaphore
1226 * far in the distance past over useful work, we keep a history
1227 * of any semaphore use along our dependency chain.
1229 if (!(request->sched.flags & I915_SCHED_HAS_SEMAPHORE_CHAIN))
1230 attr.priority |= I915_PRIORITY_NOSEMAPHORE;
1233 * Boost priorities to new clients (new request flows).
1235 * Allow interactive/synchronous clients to jump ahead of
1236 * the bulk clients. (FQ_CODEL)
1238 if (list_empty(&request->sched.signalers_list))
1239 attr.priority |= I915_PRIORITY_NEWCLIENT;
1241 engine->schedule(request, &attr);
1244 i915_sw_fence_commit(&request->submit);
1245 local_bh_enable(); /* Kick the execlists tasklet if just scheduled */
1248 * In typical scenarios, we do not expect the previous request on
1249 * the timeline to be still tracked by timeline->last_request if it
1250 * has been completed. If the completed request is still here, that
1251 * implies that request retirement is a long way behind submission,
1252 * suggesting that we haven't been retiring frequently enough from
1253 * the combination of retire-before-alloc, waiters and the background
1254 * retirement worker. So if the last request on this timeline was
1255 * already completed, do a catch up pass, flushing the retirement queue
1256 * up to this client. Since we have now moved the heaviest operations
1257 * during retirement onto secondary workers, such as freeing objects
1258 * or contexts, retiring a bunch of requests is mostly list management
1259 * (and cache misses), and so we should not be overly penalizing this
1260 * client by performing excess work, though we may still performing
1261 * work on behalf of others -- but instead we should benefit from
1262 * improved resource management. (Well, that's the theory at least.)
1264 if (prev && i915_request_completed(prev))
1265 i915_request_retire_upto(prev);
1267 mutex_unlock(&request->timeline->mutex);
1270 static unsigned long local_clock_us(unsigned int *cpu)
1275 * Cheaply and approximately convert from nanoseconds to microseconds.
1276 * The result and subsequent calculations are also defined in the same
1277 * approximate microseconds units. The principal source of timing
1278 * error here is from the simple truncation.
1280 * Note that local_clock() is only defined wrt to the current CPU;
1281 * the comparisons are no longer valid if we switch CPUs. Instead of
1282 * blocking preemption for the entire busywait, we can detect the CPU
1283 * switch and use that as indicator of system load and a reason to
1284 * stop busywaiting, see busywait_stop().
1287 t = local_clock() >> 10;
1293 static bool busywait_stop(unsigned long timeout, unsigned int cpu)
1295 unsigned int this_cpu;
1297 if (time_after(local_clock_us(&this_cpu), timeout))
1300 return this_cpu != cpu;
1303 static bool __i915_spin_request(const struct i915_request * const rq,
1304 int state, unsigned long timeout_us)
1309 * Only wait for the request if we know it is likely to complete.
1311 * We don't track the timestamps around requests, nor the average
1312 * request length, so we do not have a good indicator that this
1313 * request will complete within the timeout. What we do know is the
1314 * order in which requests are executed by the context and so we can
1315 * tell if the request has been started. If the request is not even
1316 * running yet, it is a fair assumption that it will not complete
1317 * within our relatively short timeout.
1319 if (!i915_request_is_running(rq))
1323 * When waiting for high frequency requests, e.g. during synchronous
1324 * rendering split between the CPU and GPU, the finite amount of time
1325 * required to set up the irq and wait upon it limits the response
1326 * rate. By busywaiting on the request completion for a short while we
1327 * can service the high frequency waits as quick as possible. However,
1328 * if it is a slow request, we want to sleep as quickly as possible.
1329 * The tradeoff between waiting and sleeping is roughly the time it
1330 * takes to sleep on a request, on the order of a microsecond.
1333 timeout_us += local_clock_us(&cpu);
1335 if (i915_request_completed(rq))
1338 if (signal_pending_state(state, current))
1341 if (busywait_stop(timeout_us, cpu))
1345 } while (!need_resched());
1350 struct request_wait {
1351 struct dma_fence_cb cb;
1352 struct task_struct *tsk;
1355 static void request_wait_wake(struct dma_fence *fence, struct dma_fence_cb *cb)
1357 struct request_wait *wait = container_of(cb, typeof(*wait), cb);
1359 wake_up_process(wait->tsk);
1363 * i915_request_wait - wait until execution of request has finished
1364 * @rq: the request to wait upon
1365 * @flags: how to wait
1366 * @timeout: how long to wait in jiffies
1368 * i915_request_wait() waits for the request to be completed, for a
1369 * maximum of @timeout jiffies (with MAX_SCHEDULE_TIMEOUT implying an
1372 * If the caller holds the struct_mutex, the caller must pass I915_WAIT_LOCKED
1373 * in via the flags, and vice versa if the struct_mutex is not held, the caller
1374 * must not specify that the wait is locked.
1376 * Returns the remaining time (in jiffies) if the request completed, which may
1377 * be zero or -ETIME if the request is unfinished after the timeout expires.
1378 * May return -EINTR is called with I915_WAIT_INTERRUPTIBLE and a signal is
1379 * pending before the request completes.
1381 long i915_request_wait(struct i915_request *rq,
1385 const int state = flags & I915_WAIT_INTERRUPTIBLE ?
1386 TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE;
1387 struct request_wait wait;
1390 GEM_BUG_ON(timeout < 0);
1392 if (i915_request_completed(rq))
1398 trace_i915_request_wait_begin(rq, flags);
1400 /* Optimistic short spin before touching IRQs */
1401 if (__i915_spin_request(rq, state, 5))
1405 * This client is about to stall waiting for the GPU. In many cases
1406 * this is undesirable and limits the throughput of the system, as
1407 * many clients cannot continue processing user input/output whilst
1408 * blocked. RPS autotuning may take tens of milliseconds to respond
1409 * to the GPU load and thus incurs additional latency for the client.
1410 * We can circumvent that by promoting the GPU frequency to maximum
1411 * before we sleep. This makes the GPU throttle up much more quickly
1412 * (good for benchmarks and user experience, e.g. window animations),
1413 * but at a cost of spending more power processing the workload
1414 * (bad for battery).
1416 if (flags & I915_WAIT_PRIORITY) {
1417 if (!i915_request_started(rq) && INTEL_GEN(rq->i915) >= 6)
1419 local_bh_disable(); /* suspend tasklets for reprioritisation */
1420 i915_schedule_bump_priority(rq, I915_PRIORITY_WAIT);
1421 local_bh_enable(); /* kick tasklets en masse */
1425 if (dma_fence_add_callback(&rq->fence, &wait.cb, request_wait_wake))
1429 set_current_state(state);
1431 if (i915_request_completed(rq))
1434 if (signal_pending_state(state, current)) {
1435 timeout = -ERESTARTSYS;
1444 timeout = io_schedule_timeout(timeout);
1446 __set_current_state(TASK_RUNNING);
1448 dma_fence_remove_callback(&rq->fence, &wait.cb);
1451 trace_i915_request_wait_end(rq);
1455 void i915_retire_requests(struct drm_i915_private *i915)
1457 struct intel_ring *ring, *tmp;
1459 lockdep_assert_held(&i915->drm.struct_mutex);
1461 if (!i915->gt.active_requests)
1464 list_for_each_entry_safe(ring, tmp,
1465 &i915->gt.active_rings, active_link) {
1466 intel_ring_get(ring); /* last rq holds reference! */
1467 ring_retire_requests(ring);
1468 intel_ring_put(ring);
1472 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
1473 #include "selftests/mock_request.c"
1474 #include "selftests/i915_request.c"
1477 static void i915_global_request_shrink(void)
1479 kmem_cache_shrink(global.slab_dependencies);
1480 kmem_cache_shrink(global.slab_execute_cbs);
1481 kmem_cache_shrink(global.slab_requests);
1484 static void i915_global_request_exit(void)
1486 kmem_cache_destroy(global.slab_dependencies);
1487 kmem_cache_destroy(global.slab_execute_cbs);
1488 kmem_cache_destroy(global.slab_requests);
1491 static struct i915_global_request global = { {
1492 .shrink = i915_global_request_shrink,
1493 .exit = i915_global_request_exit,
1496 int __init i915_global_request_init(void)
1498 global.slab_requests = KMEM_CACHE(i915_request,
1499 SLAB_HWCACHE_ALIGN |
1500 SLAB_RECLAIM_ACCOUNT |
1501 SLAB_TYPESAFE_BY_RCU);
1502 if (!global.slab_requests)
1505 global.slab_execute_cbs = KMEM_CACHE(execute_cb,
1506 SLAB_HWCACHE_ALIGN |
1507 SLAB_RECLAIM_ACCOUNT |
1508 SLAB_TYPESAFE_BY_RCU);
1509 if (!global.slab_execute_cbs)
1512 global.slab_dependencies = KMEM_CACHE(i915_dependency,
1513 SLAB_HWCACHE_ALIGN |
1514 SLAB_RECLAIM_ACCOUNT);
1515 if (!global.slab_dependencies)
1516 goto err_execute_cbs;
1518 i915_global_register(&global.base);
1522 kmem_cache_destroy(global.slab_execute_cbs);
1524 kmem_cache_destroy(global.slab_requests);