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