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