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