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