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/irq_work.h>
27 #include <linux/prefetch.h>
28 #include <linux/sched.h>
29 #include <linux/sched/clock.h>
30 #include <linux/sched/signal.h>
31 
32 #include "i915_active.h"
33 #include "i915_drv.h"
34 #include "i915_globals.h"
35 #include "intel_pm.h"
36 
37 struct execute_cb {
38 	struct list_head link;
39 	struct irq_work work;
40 	struct i915_sw_fence *fence;
41 	void (*hook)(struct i915_request *rq, struct dma_fence *signal);
42 	struct i915_request *signal;
43 };
44 
45 static struct i915_global_request {
46 	struct i915_global base;
47 	struct kmem_cache *slab_requests;
48 	struct kmem_cache *slab_dependencies;
49 	struct kmem_cache *slab_execute_cbs;
50 } global;
51 
52 static const char *i915_fence_get_driver_name(struct dma_fence *fence)
53 {
54 	return "i915";
55 }
56 
57 static const char *i915_fence_get_timeline_name(struct dma_fence *fence)
58 {
59 	/*
60 	 * The timeline struct (as part of the ppgtt underneath a context)
61 	 * may be freed when the request is no longer in use by the GPU.
62 	 * We could extend the life of a context to beyond that of all
63 	 * fences, possibly keeping the hw resource around indefinitely,
64 	 * or we just give them a false name. Since
65 	 * dma_fence_ops.get_timeline_name is a debug feature, the occasional
66 	 * lie seems justifiable.
67 	 */
68 	if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
69 		return "signaled";
70 
71 	return to_request(fence)->gem_context->name ?: "[i915]";
72 }
73 
74 static bool i915_fence_signaled(struct dma_fence *fence)
75 {
76 	return i915_request_completed(to_request(fence));
77 }
78 
79 static bool i915_fence_enable_signaling(struct dma_fence *fence)
80 {
81 	return i915_request_enable_breadcrumb(to_request(fence));
82 }
83 
84 static signed long i915_fence_wait(struct dma_fence *fence,
85 				   bool interruptible,
86 				   signed long timeout)
87 {
88 	return i915_request_wait(to_request(fence),
89 				 interruptible | I915_WAIT_PRIORITY,
90 				 timeout);
91 }
92 
93 static void i915_fence_release(struct dma_fence *fence)
94 {
95 	struct i915_request *rq = to_request(fence);
96 
97 	/*
98 	 * The request is put onto a RCU freelist (i.e. the address
99 	 * is immediately reused), mark the fences as being freed now.
100 	 * Otherwise the debugobjects for the fences are only marked as
101 	 * freed when the slab cache itself is freed, and so we would get
102 	 * caught trying to reuse dead objects.
103 	 */
104 	i915_sw_fence_fini(&rq->submit);
105 	i915_sw_fence_fini(&rq->semaphore);
106 
107 	kmem_cache_free(global.slab_requests, rq);
108 }
109 
110 const struct dma_fence_ops i915_fence_ops = {
111 	.get_driver_name = i915_fence_get_driver_name,
112 	.get_timeline_name = i915_fence_get_timeline_name,
113 	.enable_signaling = i915_fence_enable_signaling,
114 	.signaled = i915_fence_signaled,
115 	.wait = i915_fence_wait,
116 	.release = i915_fence_release,
117 };
118 
119 static inline void
120 i915_request_remove_from_client(struct i915_request *request)
121 {
122 	struct drm_i915_file_private *file_priv;
123 
124 	file_priv = request->file_priv;
125 	if (!file_priv)
126 		return;
127 
128 	spin_lock(&file_priv->mm.lock);
129 	if (request->file_priv) {
130 		list_del(&request->client_link);
131 		request->file_priv = NULL;
132 	}
133 	spin_unlock(&file_priv->mm.lock);
134 }
135 
136 static void advance_ring(struct i915_request *request)
137 {
138 	struct intel_ring *ring = request->ring;
139 	unsigned int tail;
140 
141 	/*
142 	 * We know the GPU must have read the request to have
143 	 * sent us the seqno + interrupt, so use the position
144 	 * of tail of the request to update the last known position
145 	 * of the GPU head.
146 	 *
147 	 * Note this requires that we are always called in request
148 	 * completion order.
149 	 */
150 	GEM_BUG_ON(!list_is_first(&request->ring_link, &ring->request_list));
151 	if (list_is_last(&request->ring_link, &ring->request_list)) {
152 		/*
153 		 * We may race here with execlists resubmitting this request
154 		 * as we retire it. The resubmission will move the ring->tail
155 		 * forwards (to request->wa_tail). We either read the
156 		 * current value that was written to hw, or the value that
157 		 * is just about to be. Either works, if we miss the last two
158 		 * noops - they are safe to be replayed on a reset.
159 		 */
160 		tail = READ_ONCE(request->tail);
161 		list_del(&ring->active_link);
162 	} else {
163 		tail = request->postfix;
164 	}
165 	list_del_init(&request->ring_link);
166 
167 	ring->head = tail;
168 }
169 
170 static void free_capture_list(struct i915_request *request)
171 {
172 	struct i915_capture_list *capture;
173 
174 	capture = request->capture_list;
175 	while (capture) {
176 		struct i915_capture_list *next = capture->next;
177 
178 		kfree(capture);
179 		capture = next;
180 	}
181 }
182 
183 static void __retire_engine_request(struct intel_engine_cs *engine,
184 				    struct i915_request *rq)
185 {
186 	GEM_TRACE("%s(%s) fence %llx:%lld, current %d\n",
187 		  __func__, engine->name,
188 		  rq->fence.context, rq->fence.seqno,
189 		  hwsp_seqno(rq));
190 
191 	GEM_BUG_ON(!i915_request_completed(rq));
192 
193 	local_irq_disable();
194 
195 	spin_lock(&engine->timeline.lock);
196 	GEM_BUG_ON(!list_is_first(&rq->link, &engine->timeline.requests));
197 	list_del_init(&rq->link);
198 	spin_unlock(&engine->timeline.lock);
199 
200 	spin_lock(&rq->lock);
201 	i915_request_mark_complete(rq);
202 	if (!i915_request_signaled(rq))
203 		dma_fence_signal_locked(&rq->fence);
204 	if (test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT, &rq->fence.flags))
205 		i915_request_cancel_breadcrumb(rq);
206 	if (rq->waitboost) {
207 		GEM_BUG_ON(!atomic_read(&rq->i915->gt_pm.rps.num_waiters));
208 		atomic_dec(&rq->i915->gt_pm.rps.num_waiters);
209 	}
210 	spin_unlock(&rq->lock);
211 
212 	local_irq_enable();
213 
214 	/*
215 	 * The backing object for the context is done after switching to the
216 	 * *next* context. Therefore we cannot retire the previous context until
217 	 * the next context has already started running. However, since we
218 	 * cannot take the required locks at i915_request_submit() we
219 	 * defer the unpinning of the active context to now, retirement of
220 	 * the subsequent request.
221 	 */
222 	if (engine->last_retired_context)
223 		intel_context_unpin(engine->last_retired_context);
224 	engine->last_retired_context = rq->hw_context;
225 }
226 
227 static void __retire_engine_upto(struct intel_engine_cs *engine,
228 				 struct i915_request *rq)
229 {
230 	struct i915_request *tmp;
231 
232 	if (list_empty(&rq->link))
233 		return;
234 
235 	do {
236 		tmp = list_first_entry(&engine->timeline.requests,
237 				       typeof(*tmp), link);
238 
239 		GEM_BUG_ON(tmp->engine != engine);
240 		__retire_engine_request(engine, tmp);
241 	} while (tmp != rq);
242 }
243 
244 static void i915_request_retire(struct i915_request *request)
245 {
246 	struct i915_active_request *active, *next;
247 
248 	GEM_TRACE("%s fence %llx:%lld, current %d\n",
249 		  request->engine->name,
250 		  request->fence.context, request->fence.seqno,
251 		  hwsp_seqno(request));
252 
253 	lockdep_assert_held(&request->i915->drm.struct_mutex);
254 	GEM_BUG_ON(!i915_sw_fence_signaled(&request->submit));
255 	GEM_BUG_ON(!i915_request_completed(request));
256 
257 	trace_i915_request_retire(request);
258 
259 	advance_ring(request);
260 	free_capture_list(request);
261 
262 	/*
263 	 * Walk through the active list, calling retire on each. This allows
264 	 * objects to track their GPU activity and mark themselves as idle
265 	 * when their *last* active request is completed (updating state
266 	 * tracking lists for eviction, active references for GEM, etc).
267 	 *
268 	 * As the ->retire() may free the node, we decouple it first and
269 	 * pass along the auxiliary information (to avoid dereferencing
270 	 * the node after the callback).
271 	 */
272 	list_for_each_entry_safe(active, next, &request->active_list, link) {
273 		/*
274 		 * In microbenchmarks or focusing upon time inside the kernel,
275 		 * we may spend an inordinate amount of time simply handling
276 		 * the retirement of requests and processing their callbacks.
277 		 * Of which, this loop itself is particularly hot due to the
278 		 * cache misses when jumping around the list of
279 		 * i915_active_request.  So we try to keep this loop as
280 		 * streamlined as possible and also prefetch the next
281 		 * i915_active_request to try and hide the likely cache miss.
282 		 */
283 		prefetchw(next);
284 
285 		INIT_LIST_HEAD(&active->link);
286 		RCU_INIT_POINTER(active->request, NULL);
287 
288 		active->retire(active, request);
289 	}
290 
291 	i915_request_remove_from_client(request);
292 
293 	__retire_engine_upto(request->engine, request);
294 
295 	intel_context_exit(request->hw_context);
296 	intel_context_unpin(request->hw_context);
297 
298 	i915_sched_node_fini(&request->sched);
299 	i915_request_put(request);
300 }
301 
302 void i915_request_retire_upto(struct i915_request *rq)
303 {
304 	struct intel_ring *ring = rq->ring;
305 	struct i915_request *tmp;
306 
307 	GEM_TRACE("%s fence %llx:%lld, current %d\n",
308 		  rq->engine->name,
309 		  rq->fence.context, rq->fence.seqno,
310 		  hwsp_seqno(rq));
311 
312 	lockdep_assert_held(&rq->i915->drm.struct_mutex);
313 	GEM_BUG_ON(!i915_request_completed(rq));
314 
315 	if (list_empty(&rq->ring_link))
316 		return;
317 
318 	do {
319 		tmp = list_first_entry(&ring->request_list,
320 				       typeof(*tmp), ring_link);
321 
322 		i915_request_retire(tmp);
323 	} while (tmp != rq);
324 }
325 
326 static void irq_execute_cb(struct irq_work *wrk)
327 {
328 	struct execute_cb *cb = container_of(wrk, typeof(*cb), work);
329 
330 	i915_sw_fence_complete(cb->fence);
331 	kmem_cache_free(global.slab_execute_cbs, cb);
332 }
333 
334 static void irq_execute_cb_hook(struct irq_work *wrk)
335 {
336 	struct execute_cb *cb = container_of(wrk, typeof(*cb), work);
337 
338 	cb->hook(container_of(cb->fence, struct i915_request, submit),
339 		 &cb->signal->fence);
340 	i915_request_put(cb->signal);
341 
342 	irq_execute_cb(wrk);
343 }
344 
345 static void __notify_execute_cb(struct i915_request *rq)
346 {
347 	struct execute_cb *cb;
348 
349 	lockdep_assert_held(&rq->lock);
350 
351 	if (list_empty(&rq->execute_cb))
352 		return;
353 
354 	list_for_each_entry(cb, &rq->execute_cb, link)
355 		irq_work_queue(&cb->work);
356 
357 	/*
358 	 * XXX Rollback on __i915_request_unsubmit()
359 	 *
360 	 * In the future, perhaps when we have an active time-slicing scheduler,
361 	 * it will be interesting to unsubmit parallel execution and remove
362 	 * busywaits from the GPU until their master is restarted. This is
363 	 * quite hairy, we have to carefully rollback the fence and do a
364 	 * preempt-to-idle cycle on the target engine, all the while the
365 	 * master execute_cb may refire.
366 	 */
367 	INIT_LIST_HEAD(&rq->execute_cb);
368 }
369 
370 static int
371 __i915_request_await_execution(struct i915_request *rq,
372 			       struct i915_request *signal,
373 			       void (*hook)(struct i915_request *rq,
374 					    struct dma_fence *signal),
375 			       gfp_t gfp)
376 {
377 	struct execute_cb *cb;
378 
379 	if (i915_request_is_active(signal)) {
380 		if (hook)
381 			hook(rq, &signal->fence);
382 		return 0;
383 	}
384 
385 	cb = kmem_cache_alloc(global.slab_execute_cbs, gfp);
386 	if (!cb)
387 		return -ENOMEM;
388 
389 	cb->fence = &rq->submit;
390 	i915_sw_fence_await(cb->fence);
391 	init_irq_work(&cb->work, irq_execute_cb);
392 
393 	if (hook) {
394 		cb->hook = hook;
395 		cb->signal = i915_request_get(signal);
396 		cb->work.func = irq_execute_cb_hook;
397 	}
398 
399 	spin_lock_irq(&signal->lock);
400 	if (i915_request_is_active(signal)) {
401 		if (hook) {
402 			hook(rq, &signal->fence);
403 			i915_request_put(signal);
404 		}
405 		i915_sw_fence_complete(cb->fence);
406 		kmem_cache_free(global.slab_execute_cbs, cb);
407 	} else {
408 		list_add_tail(&cb->link, &signal->execute_cb);
409 	}
410 	spin_unlock_irq(&signal->lock);
411 
412 	return 0;
413 }
414 
415 static void move_to_timeline(struct i915_request *request,
416 			     struct i915_timeline *timeline)
417 {
418 	GEM_BUG_ON(request->timeline == &request->engine->timeline);
419 	lockdep_assert_held(&request->engine->timeline.lock);
420 
421 	spin_lock(&request->timeline->lock);
422 	list_move_tail(&request->link, &timeline->requests);
423 	spin_unlock(&request->timeline->lock);
424 }
425 
426 void __i915_request_submit(struct i915_request *request)
427 {
428 	struct intel_engine_cs *engine = request->engine;
429 
430 	GEM_TRACE("%s fence %llx:%lld -> current %d\n",
431 		  engine->name,
432 		  request->fence.context, request->fence.seqno,
433 		  hwsp_seqno(request));
434 
435 	GEM_BUG_ON(!irqs_disabled());
436 	lockdep_assert_held(&engine->timeline.lock);
437 
438 	if (i915_gem_context_is_banned(request->gem_context))
439 		i915_request_skip(request, -EIO);
440 
441 	/*
442 	 * Are we using semaphores when the gpu is already saturated?
443 	 *
444 	 * Using semaphores incurs a cost in having the GPU poll a
445 	 * memory location, busywaiting for it to change. The continual
446 	 * memory reads can have a noticeable impact on the rest of the
447 	 * system with the extra bus traffic, stalling the cpu as it too
448 	 * tries to access memory across the bus (perf stat -e bus-cycles).
449 	 *
450 	 * If we installed a semaphore on this request and we only submit
451 	 * the request after the signaler completed, that indicates the
452 	 * system is overloaded and using semaphores at this time only
453 	 * increases the amount of work we are doing. If so, we disable
454 	 * further use of semaphores until we are idle again, whence we
455 	 * optimistically try again.
456 	 */
457 	if (request->sched.semaphores &&
458 	    i915_sw_fence_signaled(&request->semaphore))
459 		request->hw_context->saturated |= request->sched.semaphores;
460 
461 	/* We may be recursing from the signal callback of another i915 fence */
462 	spin_lock_nested(&request->lock, SINGLE_DEPTH_NESTING);
463 
464 	GEM_BUG_ON(test_bit(I915_FENCE_FLAG_ACTIVE, &request->fence.flags));
465 	set_bit(I915_FENCE_FLAG_ACTIVE, &request->fence.flags);
466 
467 	if (test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT, &request->fence.flags) &&
468 	    !test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &request->fence.flags) &&
469 	    !i915_request_enable_breadcrumb(request))
470 		intel_engine_queue_breadcrumbs(engine);
471 
472 	__notify_execute_cb(request);
473 
474 	spin_unlock(&request->lock);
475 
476 	engine->emit_fini_breadcrumb(request,
477 				     request->ring->vaddr + request->postfix);
478 
479 	/* Transfer from per-context onto the global per-engine timeline */
480 	move_to_timeline(request, &engine->timeline);
481 
482 	engine->serial++;
483 
484 	trace_i915_request_execute(request);
485 }
486 
487 void i915_request_submit(struct i915_request *request)
488 {
489 	struct intel_engine_cs *engine = request->engine;
490 	unsigned long flags;
491 
492 	/* Will be called from irq-context when using foreign fences. */
493 	spin_lock_irqsave(&engine->timeline.lock, flags);
494 
495 	__i915_request_submit(request);
496 
497 	spin_unlock_irqrestore(&engine->timeline.lock, flags);
498 }
499 
500 void __i915_request_unsubmit(struct i915_request *request)
501 {
502 	struct intel_engine_cs *engine = request->engine;
503 
504 	GEM_TRACE("%s fence %llx:%lld, current %d\n",
505 		  engine->name,
506 		  request->fence.context, request->fence.seqno,
507 		  hwsp_seqno(request));
508 
509 	GEM_BUG_ON(!irqs_disabled());
510 	lockdep_assert_held(&engine->timeline.lock);
511 
512 	/*
513 	 * Only unwind in reverse order, required so that the per-context list
514 	 * is kept in seqno/ring order.
515 	 */
516 
517 	/* We may be recursing from the signal callback of another i915 fence */
518 	spin_lock_nested(&request->lock, SINGLE_DEPTH_NESTING);
519 
520 	if (test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT, &request->fence.flags))
521 		i915_request_cancel_breadcrumb(request);
522 
523 	GEM_BUG_ON(!test_bit(I915_FENCE_FLAG_ACTIVE, &request->fence.flags));
524 	clear_bit(I915_FENCE_FLAG_ACTIVE, &request->fence.flags);
525 
526 	spin_unlock(&request->lock);
527 
528 	/* Transfer back from the global per-engine timeline to per-context */
529 	move_to_timeline(request, request->timeline);
530 
531 	/* We've already spun, don't charge on resubmitting. */
532 	if (request->sched.semaphores && i915_request_started(request)) {
533 		request->sched.attr.priority |= I915_PRIORITY_NOSEMAPHORE;
534 		request->sched.semaphores = 0;
535 	}
536 
537 	/*
538 	 * We don't need to wake_up any waiters on request->execute, they
539 	 * will get woken by any other event or us re-adding this request
540 	 * to the engine timeline (__i915_request_submit()). The waiters
541 	 * should be quite adapt at finding that the request now has a new
542 	 * global_seqno to the one they went to sleep on.
543 	 */
544 }
545 
546 void i915_request_unsubmit(struct i915_request *request)
547 {
548 	struct intel_engine_cs *engine = request->engine;
549 	unsigned long flags;
550 
551 	/* Will be called from irq-context when using foreign fences. */
552 	spin_lock_irqsave(&engine->timeline.lock, flags);
553 
554 	__i915_request_unsubmit(request);
555 
556 	spin_unlock_irqrestore(&engine->timeline.lock, flags);
557 }
558 
559 static int __i915_sw_fence_call
560 submit_notify(struct i915_sw_fence *fence, enum i915_sw_fence_notify state)
561 {
562 	struct i915_request *request =
563 		container_of(fence, typeof(*request), submit);
564 
565 	switch (state) {
566 	case FENCE_COMPLETE:
567 		trace_i915_request_submit(request);
568 		/*
569 		 * We need to serialize use of the submit_request() callback
570 		 * with its hotplugging performed during an emergency
571 		 * i915_gem_set_wedged().  We use the RCU mechanism to mark the
572 		 * critical section in order to force i915_gem_set_wedged() to
573 		 * wait until the submit_request() is completed before
574 		 * proceeding.
575 		 */
576 		rcu_read_lock();
577 		request->engine->submit_request(request);
578 		rcu_read_unlock();
579 		break;
580 
581 	case FENCE_FREE:
582 		i915_request_put(request);
583 		break;
584 	}
585 
586 	return NOTIFY_DONE;
587 }
588 
589 static int __i915_sw_fence_call
590 semaphore_notify(struct i915_sw_fence *fence, enum i915_sw_fence_notify state)
591 {
592 	struct i915_request *request =
593 		container_of(fence, typeof(*request), semaphore);
594 
595 	switch (state) {
596 	case FENCE_COMPLETE:
597 		i915_schedule_bump_priority(request, I915_PRIORITY_NOSEMAPHORE);
598 		break;
599 
600 	case FENCE_FREE:
601 		i915_request_put(request);
602 		break;
603 	}
604 
605 	return NOTIFY_DONE;
606 }
607 
608 static void ring_retire_requests(struct intel_ring *ring)
609 {
610 	struct i915_request *rq, *rn;
611 
612 	list_for_each_entry_safe(rq, rn, &ring->request_list, ring_link) {
613 		if (!i915_request_completed(rq))
614 			break;
615 
616 		i915_request_retire(rq);
617 	}
618 }
619 
620 static noinline struct i915_request *
621 request_alloc_slow(struct intel_context *ce, gfp_t gfp)
622 {
623 	struct intel_ring *ring = ce->ring;
624 	struct i915_request *rq;
625 
626 	if (list_empty(&ring->request_list))
627 		goto out;
628 
629 	if (!gfpflags_allow_blocking(gfp))
630 		goto out;
631 
632 	/* Ratelimit ourselves to prevent oom from malicious clients */
633 	rq = list_last_entry(&ring->request_list, typeof(*rq), ring_link);
634 	cond_synchronize_rcu(rq->rcustate);
635 
636 	/* Retire our old requests in the hope that we free some */
637 	ring_retire_requests(ring);
638 
639 out:
640 	return kmem_cache_alloc(global.slab_requests, gfp);
641 }
642 
643 struct i915_request *
644 __i915_request_create(struct intel_context *ce, gfp_t gfp)
645 {
646 	struct i915_timeline *tl = ce->ring->timeline;
647 	struct i915_request *rq;
648 	u32 seqno;
649 	int ret;
650 
651 	might_sleep_if(gfpflags_allow_blocking(gfp));
652 
653 	/* Check that the caller provided an already pinned context */
654 	__intel_context_pin(ce);
655 
656 	/*
657 	 * Beware: Dragons be flying overhead.
658 	 *
659 	 * We use RCU to look up requests in flight. The lookups may
660 	 * race with the request being allocated from the slab freelist.
661 	 * That is the request we are writing to here, may be in the process
662 	 * of being read by __i915_active_request_get_rcu(). As such,
663 	 * we have to be very careful when overwriting the contents. During
664 	 * the RCU lookup, we change chase the request->engine pointer,
665 	 * read the request->global_seqno and increment the reference count.
666 	 *
667 	 * The reference count is incremented atomically. If it is zero,
668 	 * the lookup knows the request is unallocated and complete. Otherwise,
669 	 * it is either still in use, or has been reallocated and reset
670 	 * with dma_fence_init(). This increment is safe for release as we
671 	 * check that the request we have a reference to and matches the active
672 	 * request.
673 	 *
674 	 * Before we increment the refcount, we chase the request->engine
675 	 * pointer. We must not call kmem_cache_zalloc() or else we set
676 	 * that pointer to NULL and cause a crash during the lookup. If
677 	 * we see the request is completed (based on the value of the
678 	 * old engine and seqno), the lookup is complete and reports NULL.
679 	 * If we decide the request is not completed (new engine or seqno),
680 	 * then we grab a reference and double check that it is still the
681 	 * active request - which it won't be and restart the lookup.
682 	 *
683 	 * Do not use kmem_cache_zalloc() here!
684 	 */
685 	rq = kmem_cache_alloc(global.slab_requests,
686 			      gfp | __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
687 	if (unlikely(!rq)) {
688 		rq = request_alloc_slow(ce, gfp);
689 		if (!rq) {
690 			ret = -ENOMEM;
691 			goto err_unreserve;
692 		}
693 	}
694 
695 	ret = i915_timeline_get_seqno(tl, rq, &seqno);
696 	if (ret)
697 		goto err_free;
698 
699 	rq->i915 = ce->engine->i915;
700 	rq->hw_context = ce;
701 	rq->gem_context = ce->gem_context;
702 	rq->engine = ce->engine;
703 	rq->ring = ce->ring;
704 	rq->timeline = tl;
705 	GEM_BUG_ON(rq->timeline == &ce->engine->timeline);
706 	rq->hwsp_seqno = tl->hwsp_seqno;
707 	rq->hwsp_cacheline = tl->hwsp_cacheline;
708 	rq->rcustate = get_state_synchronize_rcu(); /* acts as smp_mb() */
709 
710 	spin_lock_init(&rq->lock);
711 	dma_fence_init(&rq->fence, &i915_fence_ops, &rq->lock,
712 		       tl->fence_context, seqno);
713 
714 	/* We bump the ref for the fence chain */
715 	i915_sw_fence_init(&i915_request_get(rq)->submit, submit_notify);
716 	i915_sw_fence_init(&i915_request_get(rq)->semaphore, semaphore_notify);
717 
718 	i915_sched_node_init(&rq->sched);
719 
720 	/* No zalloc, must clear what we need by hand */
721 	rq->file_priv = NULL;
722 	rq->batch = NULL;
723 	rq->capture_list = NULL;
724 	rq->waitboost = false;
725 	rq->execution_mask = ALL_ENGINES;
726 
727 	INIT_LIST_HEAD(&rq->active_list);
728 	INIT_LIST_HEAD(&rq->execute_cb);
729 
730 	/*
731 	 * Reserve space in the ring buffer for all the commands required to
732 	 * eventually emit this request. This is to guarantee that the
733 	 * i915_request_add() call can't fail. Note that the reserve may need
734 	 * to be redone if the request is not actually submitted straight
735 	 * away, e.g. because a GPU scheduler has deferred it.
736 	 *
737 	 * Note that due to how we add reserved_space to intel_ring_begin()
738 	 * we need to double our request to ensure that if we need to wrap
739 	 * around inside i915_request_add() there is sufficient space at
740 	 * the beginning of the ring as well.
741 	 */
742 	rq->reserved_space =
743 		2 * rq->engine->emit_fini_breadcrumb_dw * sizeof(u32);
744 
745 	/*
746 	 * Record the position of the start of the request so that
747 	 * should we detect the updated seqno part-way through the
748 	 * GPU processing the request, we never over-estimate the
749 	 * position of the head.
750 	 */
751 	rq->head = rq->ring->emit;
752 
753 	ret = rq->engine->request_alloc(rq);
754 	if (ret)
755 		goto err_unwind;
756 
757 	rq->infix = rq->ring->emit; /* end of header; start of user payload */
758 
759 	/* Keep a second pin for the dual retirement along engine and ring */
760 	__intel_context_pin(ce);
761 
762 	intel_context_mark_active(ce);
763 	return rq;
764 
765 err_unwind:
766 	ce->ring->emit = rq->head;
767 
768 	/* Make sure we didn't add ourselves to external state before freeing */
769 	GEM_BUG_ON(!list_empty(&rq->active_list));
770 	GEM_BUG_ON(!list_empty(&rq->sched.signalers_list));
771 	GEM_BUG_ON(!list_empty(&rq->sched.waiters_list));
772 
773 err_free:
774 	kmem_cache_free(global.slab_requests, rq);
775 err_unreserve:
776 	intel_context_unpin(ce);
777 	return ERR_PTR(ret);
778 }
779 
780 struct i915_request *
781 i915_request_create(struct intel_context *ce)
782 {
783 	struct i915_request *rq;
784 
785 	intel_context_timeline_lock(ce);
786 
787 	/* Move our oldest request to the slab-cache (if not in use!) */
788 	rq = list_first_entry(&ce->ring->request_list, typeof(*rq), ring_link);
789 	if (!list_is_last(&rq->ring_link, &ce->ring->request_list) &&
790 	    i915_request_completed(rq))
791 		i915_request_retire(rq);
792 
793 	intel_context_enter(ce);
794 	rq = __i915_request_create(ce, GFP_KERNEL);
795 	intel_context_exit(ce); /* active reference transferred to request */
796 	if (IS_ERR(rq))
797 		goto err_unlock;
798 
799 	/* Check that we do not interrupt ourselves with a new request */
800 	rq->cookie = lockdep_pin_lock(&ce->ring->timeline->mutex);
801 
802 	return rq;
803 
804 err_unlock:
805 	intel_context_timeline_unlock(ce);
806 	return rq;
807 }
808 
809 static int
810 i915_request_await_start(struct i915_request *rq, struct i915_request *signal)
811 {
812 	if (list_is_first(&signal->ring_link, &signal->ring->request_list))
813 		return 0;
814 
815 	signal = list_prev_entry(signal, ring_link);
816 	if (i915_timeline_sync_is_later(rq->timeline, &signal->fence))
817 		return 0;
818 
819 	return i915_sw_fence_await_dma_fence(&rq->submit,
820 					     &signal->fence, 0,
821 					     I915_FENCE_GFP);
822 }
823 
824 static intel_engine_mask_t
825 already_busywaiting(struct i915_request *rq)
826 {
827 	/*
828 	 * Polling a semaphore causes bus traffic, delaying other users of
829 	 * both the GPU and CPU. We want to limit the impact on others,
830 	 * while taking advantage of early submission to reduce GPU
831 	 * latency. Therefore we restrict ourselves to not using more
832 	 * than one semaphore from each source, and not using a semaphore
833 	 * if we have detected the engine is saturated (i.e. would not be
834 	 * submitted early and cause bus traffic reading an already passed
835 	 * semaphore).
836 	 *
837 	 * See the are-we-too-late? check in __i915_request_submit().
838 	 */
839 	return rq->sched.semaphores | rq->hw_context->saturated;
840 }
841 
842 static int
843 emit_semaphore_wait(struct i915_request *to,
844 		    struct i915_request *from,
845 		    gfp_t gfp)
846 {
847 	u32 hwsp_offset;
848 	u32 *cs;
849 	int err;
850 
851 	GEM_BUG_ON(!from->timeline->has_initial_breadcrumb);
852 	GEM_BUG_ON(INTEL_GEN(to->i915) < 8);
853 
854 	/* Just emit the first semaphore we see as request space is limited. */
855 	if (already_busywaiting(to) & from->engine->mask)
856 		return i915_sw_fence_await_dma_fence(&to->submit,
857 						     &from->fence, 0,
858 						     I915_FENCE_GFP);
859 
860 	err = i915_request_await_start(to, from);
861 	if (err < 0)
862 		return err;
863 
864 	/* Only submit our spinner after the signaler is running! */
865 	err = __i915_request_await_execution(to, from, NULL, gfp);
866 	if (err)
867 		return err;
868 
869 	/* We need to pin the signaler's HWSP until we are finished reading. */
870 	err = i915_timeline_read_hwsp(from, to, &hwsp_offset);
871 	if (err)
872 		return err;
873 
874 	cs = intel_ring_begin(to, 4);
875 	if (IS_ERR(cs))
876 		return PTR_ERR(cs);
877 
878 	/*
879 	 * Using greater-than-or-equal here means we have to worry
880 	 * about seqno wraparound. To side step that issue, we swap
881 	 * the timeline HWSP upon wrapping, so that everyone listening
882 	 * for the old (pre-wrap) values do not see the much smaller
883 	 * (post-wrap) values than they were expecting (and so wait
884 	 * forever).
885 	 */
886 	*cs++ = MI_SEMAPHORE_WAIT |
887 		MI_SEMAPHORE_GLOBAL_GTT |
888 		MI_SEMAPHORE_POLL |
889 		MI_SEMAPHORE_SAD_GTE_SDD;
890 	*cs++ = from->fence.seqno;
891 	*cs++ = hwsp_offset;
892 	*cs++ = 0;
893 
894 	intel_ring_advance(to, cs);
895 	to->sched.semaphores |= from->engine->mask;
896 	to->sched.flags |= I915_SCHED_HAS_SEMAPHORE_CHAIN;
897 	return 0;
898 }
899 
900 static int
901 i915_request_await_request(struct i915_request *to, struct i915_request *from)
902 {
903 	int ret;
904 
905 	GEM_BUG_ON(to == from);
906 	GEM_BUG_ON(to->timeline == from->timeline);
907 
908 	if (i915_request_completed(from))
909 		return 0;
910 
911 	if (to->engine->schedule) {
912 		ret = i915_sched_node_add_dependency(&to->sched, &from->sched);
913 		if (ret < 0)
914 			return ret;
915 	}
916 
917 	if (to->engine == from->engine) {
918 		ret = i915_sw_fence_await_sw_fence_gfp(&to->submit,
919 						       &from->submit,
920 						       I915_FENCE_GFP);
921 	} else if (intel_engine_has_semaphores(to->engine) &&
922 		   to->gem_context->sched.priority >= I915_PRIORITY_NORMAL) {
923 		ret = emit_semaphore_wait(to, from, I915_FENCE_GFP);
924 	} else {
925 		ret = i915_sw_fence_await_dma_fence(&to->submit,
926 						    &from->fence, 0,
927 						    I915_FENCE_GFP);
928 	}
929 	if (ret < 0)
930 		return ret;
931 
932 	if (to->sched.flags & I915_SCHED_HAS_SEMAPHORE_CHAIN) {
933 		ret = i915_sw_fence_await_dma_fence(&to->semaphore,
934 						    &from->fence, 0,
935 						    I915_FENCE_GFP);
936 		if (ret < 0)
937 			return ret;
938 	}
939 
940 	return 0;
941 }
942 
943 int
944 i915_request_await_dma_fence(struct i915_request *rq, struct dma_fence *fence)
945 {
946 	struct dma_fence **child = &fence;
947 	unsigned int nchild = 1;
948 	int ret;
949 
950 	/*
951 	 * Note that if the fence-array was created in signal-on-any mode,
952 	 * we should *not* decompose it into its individual fences. However,
953 	 * we don't currently store which mode the fence-array is operating
954 	 * in. Fortunately, the only user of signal-on-any is private to
955 	 * amdgpu and we should not see any incoming fence-array from
956 	 * sync-file being in signal-on-any mode.
957 	 */
958 	if (dma_fence_is_array(fence)) {
959 		struct dma_fence_array *array = to_dma_fence_array(fence);
960 
961 		child = array->fences;
962 		nchild = array->num_fences;
963 		GEM_BUG_ON(!nchild);
964 	}
965 
966 	do {
967 		fence = *child++;
968 		if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
969 			continue;
970 
971 		/*
972 		 * Requests on the same timeline are explicitly ordered, along
973 		 * with their dependencies, by i915_request_add() which ensures
974 		 * that requests are submitted in-order through each ring.
975 		 */
976 		if (fence->context == rq->fence.context)
977 			continue;
978 
979 		/* Squash repeated waits to the same timelines */
980 		if (fence->context != rq->i915->mm.unordered_timeline &&
981 		    i915_timeline_sync_is_later(rq->timeline, fence))
982 			continue;
983 
984 		if (dma_fence_is_i915(fence))
985 			ret = i915_request_await_request(rq, to_request(fence));
986 		else
987 			ret = i915_sw_fence_await_dma_fence(&rq->submit, fence,
988 							    I915_FENCE_TIMEOUT,
989 							    I915_FENCE_GFP);
990 		if (ret < 0)
991 			return ret;
992 
993 		/* Record the latest fence used against each timeline */
994 		if (fence->context != rq->i915->mm.unordered_timeline)
995 			i915_timeline_sync_set(rq->timeline, fence);
996 	} while (--nchild);
997 
998 	return 0;
999 }
1000 
1001 int
1002 i915_request_await_execution(struct i915_request *rq,
1003 			     struct dma_fence *fence,
1004 			     void (*hook)(struct i915_request *rq,
1005 					  struct dma_fence *signal))
1006 {
1007 	struct dma_fence **child = &fence;
1008 	unsigned int nchild = 1;
1009 	int ret;
1010 
1011 	if (dma_fence_is_array(fence)) {
1012 		struct dma_fence_array *array = to_dma_fence_array(fence);
1013 
1014 		/* XXX Error for signal-on-any fence arrays */
1015 
1016 		child = array->fences;
1017 		nchild = array->num_fences;
1018 		GEM_BUG_ON(!nchild);
1019 	}
1020 
1021 	do {
1022 		fence = *child++;
1023 		if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
1024 			continue;
1025 
1026 		/*
1027 		 * We don't squash repeated fence dependencies here as we
1028 		 * want to run our callback in all cases.
1029 		 */
1030 
1031 		if (dma_fence_is_i915(fence))
1032 			ret = __i915_request_await_execution(rq,
1033 							     to_request(fence),
1034 							     hook,
1035 							     I915_FENCE_GFP);
1036 		else
1037 			ret = i915_sw_fence_await_dma_fence(&rq->submit, fence,
1038 							    I915_FENCE_TIMEOUT,
1039 							    GFP_KERNEL);
1040 		if (ret < 0)
1041 			return ret;
1042 	} while (--nchild);
1043 
1044 	return 0;
1045 }
1046 
1047 /**
1048  * i915_request_await_object - set this request to (async) wait upon a bo
1049  * @to: request we are wishing to use
1050  * @obj: object which may be in use on another ring.
1051  * @write: whether the wait is on behalf of a writer
1052  *
1053  * This code is meant to abstract object synchronization with the GPU.
1054  * Conceptually we serialise writes between engines inside the GPU.
1055  * We only allow one engine to write into a buffer at any time, but
1056  * multiple readers. To ensure each has a coherent view of memory, we must:
1057  *
1058  * - If there is an outstanding write request to the object, the new
1059  *   request must wait for it to complete (either CPU or in hw, requests
1060  *   on the same ring will be naturally ordered).
1061  *
1062  * - If we are a write request (pending_write_domain is set), the new
1063  *   request must wait for outstanding read requests to complete.
1064  *
1065  * Returns 0 if successful, else propagates up the lower layer error.
1066  */
1067 int
1068 i915_request_await_object(struct i915_request *to,
1069 			  struct drm_i915_gem_object *obj,
1070 			  bool write)
1071 {
1072 	struct dma_fence *excl;
1073 	int ret = 0;
1074 
1075 	if (write) {
1076 		struct dma_fence **shared;
1077 		unsigned int count, i;
1078 
1079 		ret = reservation_object_get_fences_rcu(obj->resv,
1080 							&excl, &count, &shared);
1081 		if (ret)
1082 			return ret;
1083 
1084 		for (i = 0; i < count; i++) {
1085 			ret = i915_request_await_dma_fence(to, shared[i]);
1086 			if (ret)
1087 				break;
1088 
1089 			dma_fence_put(shared[i]);
1090 		}
1091 
1092 		for (; i < count; i++)
1093 			dma_fence_put(shared[i]);
1094 		kfree(shared);
1095 	} else {
1096 		excl = reservation_object_get_excl_rcu(obj->resv);
1097 	}
1098 
1099 	if (excl) {
1100 		if (ret == 0)
1101 			ret = i915_request_await_dma_fence(to, excl);
1102 
1103 		dma_fence_put(excl);
1104 	}
1105 
1106 	return ret;
1107 }
1108 
1109 void i915_request_skip(struct i915_request *rq, int error)
1110 {
1111 	void *vaddr = rq->ring->vaddr;
1112 	u32 head;
1113 
1114 	GEM_BUG_ON(!IS_ERR_VALUE((long)error));
1115 	dma_fence_set_error(&rq->fence, error);
1116 
1117 	/*
1118 	 * As this request likely depends on state from the lost
1119 	 * context, clear out all the user operations leaving the
1120 	 * breadcrumb at the end (so we get the fence notifications).
1121 	 */
1122 	head = rq->infix;
1123 	if (rq->postfix < head) {
1124 		memset(vaddr + head, 0, rq->ring->size - head);
1125 		head = 0;
1126 	}
1127 	memset(vaddr + head, 0, rq->postfix - head);
1128 }
1129 
1130 static struct i915_request *
1131 __i915_request_add_to_timeline(struct i915_request *rq)
1132 {
1133 	struct i915_timeline *timeline = rq->timeline;
1134 	struct i915_request *prev;
1135 
1136 	/*
1137 	 * Dependency tracking and request ordering along the timeline
1138 	 * is special cased so that we can eliminate redundant ordering
1139 	 * operations while building the request (we know that the timeline
1140 	 * itself is ordered, and here we guarantee it).
1141 	 *
1142 	 * As we know we will need to emit tracking along the timeline,
1143 	 * we embed the hooks into our request struct -- at the cost of
1144 	 * having to have specialised no-allocation interfaces (which will
1145 	 * be beneficial elsewhere).
1146 	 *
1147 	 * A second benefit to open-coding i915_request_await_request is
1148 	 * that we can apply a slight variant of the rules specialised
1149 	 * for timelines that jump between engines (such as virtual engines).
1150 	 * If we consider the case of virtual engine, we must emit a dma-fence
1151 	 * to prevent scheduling of the second request until the first is
1152 	 * complete (to maximise our greedy late load balancing) and this
1153 	 * precludes optimising to use semaphores serialisation of a single
1154 	 * timeline across engines.
1155 	 */
1156 	prev = rcu_dereference_protected(timeline->last_request.request, 1);
1157 	if (prev && !i915_request_completed(prev)) {
1158 		if (is_power_of_2(prev->engine->mask | rq->engine->mask))
1159 			i915_sw_fence_await_sw_fence(&rq->submit,
1160 						     &prev->submit,
1161 						     &rq->submitq);
1162 		else
1163 			__i915_sw_fence_await_dma_fence(&rq->submit,
1164 							&prev->fence,
1165 							&rq->dmaq);
1166 		if (rq->engine->schedule)
1167 			__i915_sched_node_add_dependency(&rq->sched,
1168 							 &prev->sched,
1169 							 &rq->dep,
1170 							 0);
1171 	}
1172 
1173 	spin_lock_irq(&timeline->lock);
1174 	list_add_tail(&rq->link, &timeline->requests);
1175 	spin_unlock_irq(&timeline->lock);
1176 
1177 	/*
1178 	 * Make sure that no request gazumped us - if it was allocated after
1179 	 * our i915_request_alloc() and called __i915_request_add() before
1180 	 * us, the timeline will hold its seqno which is later than ours.
1181 	 */
1182 	GEM_BUG_ON(timeline->seqno != rq->fence.seqno);
1183 	__i915_active_request_set(&timeline->last_request, rq);
1184 
1185 	return prev;
1186 }
1187 
1188 /*
1189  * NB: This function is not allowed to fail. Doing so would mean the the
1190  * request is not being tracked for completion but the work itself is
1191  * going to happen on the hardware. This would be a Bad Thing(tm).
1192  */
1193 struct i915_request *__i915_request_commit(struct i915_request *rq)
1194 {
1195 	struct intel_engine_cs *engine = rq->engine;
1196 	struct intel_ring *ring = rq->ring;
1197 	struct i915_request *prev;
1198 	u32 *cs;
1199 
1200 	GEM_TRACE("%s fence %llx:%lld\n",
1201 		  engine->name, rq->fence.context, rq->fence.seqno);
1202 
1203 	/*
1204 	 * To ensure that this call will not fail, space for its emissions
1205 	 * should already have been reserved in the ring buffer. Let the ring
1206 	 * know that it is time to use that space up.
1207 	 */
1208 	GEM_BUG_ON(rq->reserved_space > ring->space);
1209 	rq->reserved_space = 0;
1210 
1211 	/*
1212 	 * Record the position of the start of the breadcrumb so that
1213 	 * should we detect the updated seqno part-way through the
1214 	 * GPU processing the request, we never over-estimate the
1215 	 * position of the ring's HEAD.
1216 	 */
1217 	cs = intel_ring_begin(rq, engine->emit_fini_breadcrumb_dw);
1218 	GEM_BUG_ON(IS_ERR(cs));
1219 	rq->postfix = intel_ring_offset(rq, cs);
1220 
1221 	prev = __i915_request_add_to_timeline(rq);
1222 
1223 	list_add_tail(&rq->ring_link, &ring->request_list);
1224 	if (list_is_first(&rq->ring_link, &ring->request_list))
1225 		list_add(&ring->active_link, &rq->i915->gt.active_rings);
1226 	rq->emitted_jiffies = jiffies;
1227 
1228 	/*
1229 	 * Let the backend know a new request has arrived that may need
1230 	 * to adjust the existing execution schedule due to a high priority
1231 	 * request - i.e. we may want to preempt the current request in order
1232 	 * to run a high priority dependency chain *before* we can execute this
1233 	 * request.
1234 	 *
1235 	 * This is called before the request is ready to run so that we can
1236 	 * decide whether to preempt the entire chain so that it is ready to
1237 	 * run at the earliest possible convenience.
1238 	 */
1239 	local_bh_disable();
1240 	i915_sw_fence_commit(&rq->semaphore);
1241 	rcu_read_lock(); /* RCU serialisation for set-wedged protection */
1242 	if (engine->schedule) {
1243 		struct i915_sched_attr attr = rq->gem_context->sched;
1244 
1245 		/*
1246 		 * Boost actual workloads past semaphores!
1247 		 *
1248 		 * With semaphores we spin on one engine waiting for another,
1249 		 * simply to reduce the latency of starting our work when
1250 		 * the signaler completes. However, if there is any other
1251 		 * work that we could be doing on this engine instead, that
1252 		 * is better utilisation and will reduce the overall duration
1253 		 * of the current work. To avoid PI boosting a semaphore
1254 		 * far in the distance past over useful work, we keep a history
1255 		 * of any semaphore use along our dependency chain.
1256 		 */
1257 		if (!(rq->sched.flags & I915_SCHED_HAS_SEMAPHORE_CHAIN))
1258 			attr.priority |= I915_PRIORITY_NOSEMAPHORE;
1259 
1260 		/*
1261 		 * Boost priorities to new clients (new request flows).
1262 		 *
1263 		 * Allow interactive/synchronous clients to jump ahead of
1264 		 * the bulk clients. (FQ_CODEL)
1265 		 */
1266 		if (list_empty(&rq->sched.signalers_list))
1267 			attr.priority |= I915_PRIORITY_WAIT;
1268 
1269 		engine->schedule(rq, &attr);
1270 	}
1271 	rcu_read_unlock();
1272 	i915_sw_fence_commit(&rq->submit);
1273 	local_bh_enable(); /* Kick the execlists tasklet if just scheduled */
1274 
1275 	return prev;
1276 }
1277 
1278 void i915_request_add(struct i915_request *rq)
1279 {
1280 	struct i915_request *prev;
1281 
1282 	lockdep_assert_held(&rq->timeline->mutex);
1283 	lockdep_unpin_lock(&rq->timeline->mutex, rq->cookie);
1284 
1285 	trace_i915_request_add(rq);
1286 
1287 	prev = __i915_request_commit(rq);
1288 
1289 	/*
1290 	 * In typical scenarios, we do not expect the previous request on
1291 	 * the timeline to be still tracked by timeline->last_request if it
1292 	 * has been completed. If the completed request is still here, that
1293 	 * implies that request retirement is a long way behind submission,
1294 	 * suggesting that we haven't been retiring frequently enough from
1295 	 * the combination of retire-before-alloc, waiters and the background
1296 	 * retirement worker. So if the last request on this timeline was
1297 	 * already completed, do a catch up pass, flushing the retirement queue
1298 	 * up to this client. Since we have now moved the heaviest operations
1299 	 * during retirement onto secondary workers, such as freeing objects
1300 	 * or contexts, retiring a bunch of requests is mostly list management
1301 	 * (and cache misses), and so we should not be overly penalizing this
1302 	 * client by performing excess work, though we may still performing
1303 	 * work on behalf of others -- but instead we should benefit from
1304 	 * improved resource management. (Well, that's the theory at least.)
1305 	 */
1306 	if (prev && i915_request_completed(prev))
1307 		i915_request_retire_upto(prev);
1308 
1309 	mutex_unlock(&rq->timeline->mutex);
1310 }
1311 
1312 static unsigned long local_clock_us(unsigned int *cpu)
1313 {
1314 	unsigned long t;
1315 
1316 	/*
1317 	 * Cheaply and approximately convert from nanoseconds to microseconds.
1318 	 * The result and subsequent calculations are also defined in the same
1319 	 * approximate microseconds units. The principal source of timing
1320 	 * error here is from the simple truncation.
1321 	 *
1322 	 * Note that local_clock() is only defined wrt to the current CPU;
1323 	 * the comparisons are no longer valid if we switch CPUs. Instead of
1324 	 * blocking preemption for the entire busywait, we can detect the CPU
1325 	 * switch and use that as indicator of system load and a reason to
1326 	 * stop busywaiting, see busywait_stop().
1327 	 */
1328 	*cpu = get_cpu();
1329 	t = local_clock() >> 10;
1330 	put_cpu();
1331 
1332 	return t;
1333 }
1334 
1335 static bool busywait_stop(unsigned long timeout, unsigned int cpu)
1336 {
1337 	unsigned int this_cpu;
1338 
1339 	if (time_after(local_clock_us(&this_cpu), timeout))
1340 		return true;
1341 
1342 	return this_cpu != cpu;
1343 }
1344 
1345 static bool __i915_spin_request(const struct i915_request * const rq,
1346 				int state, unsigned long timeout_us)
1347 {
1348 	unsigned int cpu;
1349 
1350 	/*
1351 	 * Only wait for the request if we know it is likely to complete.
1352 	 *
1353 	 * We don't track the timestamps around requests, nor the average
1354 	 * request length, so we do not have a good indicator that this
1355 	 * request will complete within the timeout. What we do know is the
1356 	 * order in which requests are executed by the context and so we can
1357 	 * tell if the request has been started. If the request is not even
1358 	 * running yet, it is a fair assumption that it will not complete
1359 	 * within our relatively short timeout.
1360 	 */
1361 	if (!i915_request_is_running(rq))
1362 		return false;
1363 
1364 	/*
1365 	 * When waiting for high frequency requests, e.g. during synchronous
1366 	 * rendering split between the CPU and GPU, the finite amount of time
1367 	 * required to set up the irq and wait upon it limits the response
1368 	 * rate. By busywaiting on the request completion for a short while we
1369 	 * can service the high frequency waits as quick as possible. However,
1370 	 * if it is a slow request, we want to sleep as quickly as possible.
1371 	 * The tradeoff between waiting and sleeping is roughly the time it
1372 	 * takes to sleep on a request, on the order of a microsecond.
1373 	 */
1374 
1375 	timeout_us += local_clock_us(&cpu);
1376 	do {
1377 		if (i915_request_completed(rq))
1378 			return true;
1379 
1380 		if (signal_pending_state(state, current))
1381 			break;
1382 
1383 		if (busywait_stop(timeout_us, cpu))
1384 			break;
1385 
1386 		cpu_relax();
1387 	} while (!need_resched());
1388 
1389 	return false;
1390 }
1391 
1392 struct request_wait {
1393 	struct dma_fence_cb cb;
1394 	struct task_struct *tsk;
1395 };
1396 
1397 static void request_wait_wake(struct dma_fence *fence, struct dma_fence_cb *cb)
1398 {
1399 	struct request_wait *wait = container_of(cb, typeof(*wait), cb);
1400 
1401 	wake_up_process(wait->tsk);
1402 }
1403 
1404 /**
1405  * i915_request_wait - wait until execution of request has finished
1406  * @rq: the request to wait upon
1407  * @flags: how to wait
1408  * @timeout: how long to wait in jiffies
1409  *
1410  * i915_request_wait() waits for the request to be completed, for a
1411  * maximum of @timeout jiffies (with MAX_SCHEDULE_TIMEOUT implying an
1412  * unbounded wait).
1413  *
1414  * If the caller holds the struct_mutex, the caller must pass I915_WAIT_LOCKED
1415  * in via the flags, and vice versa if the struct_mutex is not held, the caller
1416  * must not specify that the wait is locked.
1417  *
1418  * Returns the remaining time (in jiffies) if the request completed, which may
1419  * be zero or -ETIME if the request is unfinished after the timeout expires.
1420  * May return -EINTR is called with I915_WAIT_INTERRUPTIBLE and a signal is
1421  * pending before the request completes.
1422  */
1423 long i915_request_wait(struct i915_request *rq,
1424 		       unsigned int flags,
1425 		       long timeout)
1426 {
1427 	const int state = flags & I915_WAIT_INTERRUPTIBLE ?
1428 		TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE;
1429 	struct request_wait wait;
1430 
1431 	might_sleep();
1432 	GEM_BUG_ON(timeout < 0);
1433 
1434 	if (i915_request_completed(rq))
1435 		return timeout;
1436 
1437 	if (!timeout)
1438 		return -ETIME;
1439 
1440 	trace_i915_request_wait_begin(rq, flags);
1441 
1442 	/*
1443 	 * Optimistic spin before touching IRQs.
1444 	 *
1445 	 * We may use a rather large value here to offset the penalty of
1446 	 * switching away from the active task. Frequently, the client will
1447 	 * wait upon an old swapbuffer to throttle itself to remain within a
1448 	 * frame of the gpu. If the client is running in lockstep with the gpu,
1449 	 * then it should not be waiting long at all, and a sleep now will incur
1450 	 * extra scheduler latency in producing the next frame. To try to
1451 	 * avoid adding the cost of enabling/disabling the interrupt to the
1452 	 * short wait, we first spin to see if the request would have completed
1453 	 * in the time taken to setup the interrupt.
1454 	 *
1455 	 * We need upto 5us to enable the irq, and upto 20us to hide the
1456 	 * scheduler latency of a context switch, ignoring the secondary
1457 	 * impacts from a context switch such as cache eviction.
1458 	 *
1459 	 * The scheme used for low-latency IO is called "hybrid interrupt
1460 	 * polling". The suggestion there is to sleep until just before you
1461 	 * expect to be woken by the device interrupt and then poll for its
1462 	 * completion. That requires having a good predictor for the request
1463 	 * duration, which we currently lack.
1464 	 */
1465 	if (CONFIG_DRM_I915_SPIN_REQUEST &&
1466 	    __i915_spin_request(rq, state, CONFIG_DRM_I915_SPIN_REQUEST))
1467 		goto out;
1468 
1469 	/*
1470 	 * This client is about to stall waiting for the GPU. In many cases
1471 	 * this is undesirable and limits the throughput of the system, as
1472 	 * many clients cannot continue processing user input/output whilst
1473 	 * blocked. RPS autotuning may take tens of milliseconds to respond
1474 	 * to the GPU load and thus incurs additional latency for the client.
1475 	 * We can circumvent that by promoting the GPU frequency to maximum
1476 	 * before we sleep. This makes the GPU throttle up much more quickly
1477 	 * (good for benchmarks and user experience, e.g. window animations),
1478 	 * but at a cost of spending more power processing the workload
1479 	 * (bad for battery).
1480 	 */
1481 	if (flags & I915_WAIT_PRIORITY) {
1482 		if (!i915_request_started(rq) && INTEL_GEN(rq->i915) >= 6)
1483 			gen6_rps_boost(rq);
1484 		i915_schedule_bump_priority(rq, I915_PRIORITY_WAIT);
1485 	}
1486 
1487 	wait.tsk = current;
1488 	if (dma_fence_add_callback(&rq->fence, &wait.cb, request_wait_wake))
1489 		goto out;
1490 
1491 	for (;;) {
1492 		set_current_state(state);
1493 
1494 		if (i915_request_completed(rq))
1495 			break;
1496 
1497 		if (signal_pending_state(state, current)) {
1498 			timeout = -ERESTARTSYS;
1499 			break;
1500 		}
1501 
1502 		if (!timeout) {
1503 			timeout = -ETIME;
1504 			break;
1505 		}
1506 
1507 		timeout = io_schedule_timeout(timeout);
1508 	}
1509 	__set_current_state(TASK_RUNNING);
1510 
1511 	dma_fence_remove_callback(&rq->fence, &wait.cb);
1512 
1513 out:
1514 	trace_i915_request_wait_end(rq);
1515 	return timeout;
1516 }
1517 
1518 bool i915_retire_requests(struct drm_i915_private *i915)
1519 {
1520 	struct intel_ring *ring, *tmp;
1521 
1522 	lockdep_assert_held(&i915->drm.struct_mutex);
1523 
1524 	list_for_each_entry_safe(ring, tmp,
1525 				 &i915->gt.active_rings, active_link) {
1526 		intel_ring_get(ring); /* last rq holds reference! */
1527 		ring_retire_requests(ring);
1528 		intel_ring_put(ring);
1529 	}
1530 
1531 	return !list_empty(&i915->gt.active_rings);
1532 }
1533 
1534 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
1535 #include "selftests/mock_request.c"
1536 #include "selftests/i915_request.c"
1537 #endif
1538 
1539 static void i915_global_request_shrink(void)
1540 {
1541 	kmem_cache_shrink(global.slab_dependencies);
1542 	kmem_cache_shrink(global.slab_execute_cbs);
1543 	kmem_cache_shrink(global.slab_requests);
1544 }
1545 
1546 static void i915_global_request_exit(void)
1547 {
1548 	kmem_cache_destroy(global.slab_dependencies);
1549 	kmem_cache_destroy(global.slab_execute_cbs);
1550 	kmem_cache_destroy(global.slab_requests);
1551 }
1552 
1553 static struct i915_global_request global = { {
1554 	.shrink = i915_global_request_shrink,
1555 	.exit = i915_global_request_exit,
1556 } };
1557 
1558 int __init i915_global_request_init(void)
1559 {
1560 	global.slab_requests = KMEM_CACHE(i915_request,
1561 					  SLAB_HWCACHE_ALIGN |
1562 					  SLAB_RECLAIM_ACCOUNT |
1563 					  SLAB_TYPESAFE_BY_RCU);
1564 	if (!global.slab_requests)
1565 		return -ENOMEM;
1566 
1567 	global.slab_execute_cbs = KMEM_CACHE(execute_cb,
1568 					     SLAB_HWCACHE_ALIGN |
1569 					     SLAB_RECLAIM_ACCOUNT |
1570 					     SLAB_TYPESAFE_BY_RCU);
1571 	if (!global.slab_execute_cbs)
1572 		goto err_requests;
1573 
1574 	global.slab_dependencies = KMEM_CACHE(i915_dependency,
1575 					      SLAB_HWCACHE_ALIGN |
1576 					      SLAB_RECLAIM_ACCOUNT);
1577 	if (!global.slab_dependencies)
1578 		goto err_execute_cbs;
1579 
1580 	i915_global_register(&global.base);
1581 	return 0;
1582 
1583 err_execute_cbs:
1584 	kmem_cache_destroy(global.slab_execute_cbs);
1585 err_requests:
1586 	kmem_cache_destroy(global.slab_requests);
1587 	return -ENOMEM;
1588 }
1589