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