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