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