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