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