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