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