i915_request.c revision 1.12 1 /* $NetBSD: i915_request.c,v 1.12 2021/12/19 12:34:34 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.12 2021/12/19 12:34:34 riastradh Exp $");
29
30 #include <linux/dma-fence-array.h>
31 #include <linux/irq_work.h>
32 #include <linux/prefetch.h>
33 #include <linux/sched.h>
34 #include <linux/sched/clock.h>
35 #include <linux/sched/signal.h>
36
37 #include "gem/i915_gem_context.h"
38 #include "gt/intel_context.h"
39 #include "gt/intel_ring.h"
40 #include "gt/intel_rps.h"
41
42 #include "i915_active.h"
43 #include "i915_drv.h"
44 #include "i915_globals.h"
45 #include "i915_trace.h"
46 #include "intel_pm.h"
47
48 struct execute_cb {
49 struct list_head link;
50 struct irq_work work;
51 struct i915_sw_fence *fence;
52 void (*hook)(struct i915_request *rq, struct dma_fence *signal);
53 struct i915_request *signal;
54 };
55
56 static struct i915_global_request {
57 struct i915_global base;
58 struct kmem_cache *slab_requests;
59 struct kmem_cache *slab_dependencies;
60 struct kmem_cache *slab_execute_cbs;
61 } global;
62
63 static const char *i915_fence_get_driver_name(struct dma_fence *fence)
64 {
65 return dev_name(to_request(fence)->i915->drm.dev);
66 }
67
68 static const char *i915_fence_get_timeline_name(struct dma_fence *fence)
69 {
70 const struct i915_gem_context *ctx;
71
72 /*
73 * The timeline struct (as part of the ppgtt underneath a context)
74 * may be freed when the request is no longer in use by the GPU.
75 * We could extend the life of a context to beyond that of all
76 * fences, possibly keeping the hw resource around indefinitely,
77 * or we just give them a false name. Since
78 * dma_fence_ops.get_timeline_name is a debug feature, the occasional
79 * lie seems justifiable.
80 */
81 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
82 return "signaled";
83
84 ctx = i915_request_gem_context(to_request(fence));
85 if (!ctx)
86 return "[" DRIVER_NAME "]";
87
88 return ctx->name;
89 }
90
91 static bool i915_fence_signaled(struct dma_fence *fence)
92 {
93 return i915_request_completed(to_request(fence));
94 }
95
96 static bool i915_fence_enable_signaling(struct dma_fence *fence)
97 {
98 return i915_request_enable_breadcrumb(to_request(fence));
99 }
100
101 static signed long i915_fence_wait(struct dma_fence *fence,
102 bool interruptible,
103 signed long timeout)
104 {
105 return i915_request_wait(to_request(fence),
106 interruptible | I915_WAIT_PRIORITY,
107 timeout);
108 }
109
110 static void i915_fence_release(struct dma_fence *fence)
111 {
112 struct i915_request *rq = to_request(fence);
113
114 /*
115 * The request is put onto a RCU freelist (i.e. the address
116 * is immediately reused), mark the fences as being freed now.
117 * Otherwise the debugobjects for the fences are only marked as
118 * freed when the slab cache itself is freed, and so we would get
119 * caught trying to reuse dead objects.
120 */
121 #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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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 *
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
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
613 static void __i915_request_dtor(void *arg)
614 {
615 struct i915_request *rq = arg;
616
617 #ifdef __NetBSD__
618 /* XXX pool cache does not guarantee this for us. */
619 synchronize_rcu();
620 #endif
621
622 dma_fence_destroy(&rq->fence);
623 #ifdef __NetBSD__
624 i915_sw_fence_fini(&rq->submit);
625 i915_sw_fence_fini(&rq->semaphore);
626 #endif
627 spin_lock_destroy(&rq->lock);
628 }
629
630 struct i915_request *
631 __i915_request_create(struct intel_context *ce, gfp_t gfp)
632 {
633 struct intel_timeline *tl = ce->timeline;
634 struct i915_request *rq;
635 u32 seqno;
636 int ret;
637
638 might_sleep_if(gfpflags_allow_blocking(gfp));
639
640 /* Check that the caller provided an already pinned context */
641 __intel_context_pin(ce);
642
643 /*
644 * Beware: Dragons be flying overhead.
645 *
646 * We use RCU to look up requests in flight. The lookups may
647 * race with the request being allocated from the slab freelist.
648 * That is the request we are writing to here, may be in the process
649 * of being read by __i915_active_request_get_rcu(). As such,
650 * we have to be very careful when overwriting the contents. During
651 * the RCU lookup, we change chase the request->engine pointer,
652 * read the request->global_seqno and increment the reference count.
653 *
654 * The reference count is incremented atomically. If it is zero,
655 * the lookup knows the request is unallocated and complete. Otherwise,
656 * it is either still in use, or has been reallocated and reset
657 * with dma_fence_init(). This increment is safe for release as we
658 * check that the request we have a reference to and matches the active
659 * request.
660 *
661 * Before we increment the refcount, we chase the request->engine
662 * pointer. We must not call kmem_cache_zalloc() or else we set
663 * that pointer to NULL and cause a crash during the lookup. If
664 * we see the request is completed (based on the value of the
665 * old engine and seqno), the lookup is complete and reports NULL.
666 * If we decide the request is not completed (new engine or seqno),
667 * then we grab a reference and double check that it is still the
668 * active request - which it won't be and restart the lookup.
669 *
670 * Do not use kmem_cache_zalloc() here!
671 */
672 rq = kmem_cache_alloc(global.slab_requests,
673 gfp | __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
674 if (unlikely(!rq)) {
675 rq = request_alloc_slow(tl, gfp);
676 if (!rq) {
677 ret = -ENOMEM;
678 goto err_unreserve;
679 }
680 }
681
682 rq->i915 = ce->engine->i915;
683 rq->context = ce;
684 rq->engine = ce->engine;
685 rq->ring = ce->ring;
686 rq->execution_mask = ce->engine->mask;
687
688 #ifdef __NetBSD__
689 dma_fence_reset(&rq->fence, &i915_fence_ops, &rq->lock, 0, 0);
690 #else
691 kref_init(&rq->fence.refcount);
692 rq->fence.flags = 0;
693 rq->fence.error = 0;
694 INIT_LIST_HEAD(&rq->fence.cb_list);
695 #endif
696
697 ret = intel_timeline_get_seqno(tl, rq, &seqno);
698 if (ret)
699 goto err_free;
700
701 rq->fence.context = tl->fence_context;
702 rq->fence.seqno = seqno;
703
704 RCU_INIT_POINTER(rq->timeline, tl);
705 RCU_INIT_POINTER(rq->hwsp_cacheline, tl->hwsp_cacheline);
706 rq->hwsp_seqno = tl->hwsp_seqno;
707
708 rq->rcustate = get_state_synchronize_rcu(); /* acts as smp_mb() */
709
710 /* We bump the ref for the fence chain */
711 i915_sw_fence_reinit(&i915_request_get(rq)->submit);
712 i915_sw_fence_reinit(&i915_request_get(rq)->semaphore);
713
714 i915_sched_node_reinit(&rq->sched);
715
716 /* No zalloc, everything must be cleared after use */
717 rq->batch = NULL;
718 GEM_BUG_ON(rq->file_priv);
719 GEM_BUG_ON(rq->capture_list);
720 GEM_BUG_ON(!list_empty(&rq->execute_cb));
721
722 /*
723 * Reserve space in the ring buffer for all the commands required to
724 * eventually emit this request. This is to guarantee that the
725 * i915_request_add() call can't fail. Note that the reserve may need
726 * to be redone if the request is not actually submitted straight
727 * away, e.g. because a GPU scheduler has deferred it.
728 *
729 * Note that due to how we add reserved_space to intel_ring_begin()
730 * we need to double our request to ensure that if we need to wrap
731 * around inside i915_request_add() there is sufficient space at
732 * the beginning of the ring as well.
733 */
734 rq->reserved_space =
735 2 * rq->engine->emit_fini_breadcrumb_dw * sizeof(u32);
736
737 /*
738 * Record the position of the start of the request so that
739 * should we detect the updated seqno part-way through the
740 * GPU processing the request, we never over-estimate the
741 * position of the head.
742 */
743 rq->head = rq->ring->emit;
744
745 ret = rq->engine->request_alloc(rq);
746 if (ret)
747 goto err_unwind;
748
749 rq->infix = rq->ring->emit; /* end of header; start of user payload */
750
751 intel_context_mark_active(ce);
752 return rq;
753
754 err_unwind:
755 ce->ring->emit = rq->head;
756
757 /* Make sure we didn't add ourselves to external state before freeing */
758 GEM_BUG_ON(!list_empty(&rq->sched.signalers_list));
759 GEM_BUG_ON(!list_empty(&rq->sched.waiters_list));
760
761 err_free:
762 kmem_cache_free(global.slab_requests, rq);
763 err_unreserve:
764 intel_context_unpin(ce);
765 return ERR_PTR(ret);
766 }
767
768 struct i915_request *
769 i915_request_create(struct intel_context *ce)
770 {
771 struct i915_request *rq;
772 struct intel_timeline *tl;
773
774 tl = intel_context_timeline_lock(ce);
775 if (IS_ERR(tl))
776 return ERR_CAST(tl);
777
778 /* Move our oldest request to the slab-cache (if not in use!) */
779 rq = list_first_entry(&tl->requests, typeof(*rq), link);
780 if (!list_is_last(&rq->link, &tl->requests))
781 i915_request_retire(rq);
782
783 intel_context_enter(ce);
784 rq = __i915_request_create(ce, GFP_KERNEL);
785 intel_context_exit(ce); /* active reference transferred to request */
786 if (IS_ERR(rq))
787 goto err_unlock;
788
789 /* Check that we do not interrupt ourselves with a new request */
790 rq->cookie = lockdep_pin_lock(&tl->mutex);
791
792 return rq;
793
794 err_unlock:
795 intel_context_timeline_unlock(tl);
796 return rq;
797 }
798
799 static int
800 i915_request_await_start(struct i915_request *rq, struct i915_request *signal)
801 {
802 struct dma_fence *fence;
803 int err;
804
805 GEM_BUG_ON(i915_request_timeline(rq) ==
806 rcu_access_pointer(signal->timeline));
807
808 fence = NULL;
809 rcu_read_lock();
810 spin_lock_irq(&signal->lock);
811 if (!i915_request_started(signal) &&
812 !list_is_first(&signal->link,
813 &rcu_dereference(signal->timeline)->requests)) {
814 struct i915_request *prev = list_prev_entry(signal, link);
815
816 /*
817 * Peek at the request before us in the timeline. That
818 * request will only be valid before it is retired, so
819 * after acquiring a reference to it, confirm that it is
820 * still part of the signaler's timeline.
821 */
822 if (i915_request_get_rcu(prev)) {
823 if (list_next_entry(prev, link) == signal)
824 fence = &prev->fence;
825 else
826 i915_request_put(prev);
827 }
828 }
829 spin_unlock_irq(&signal->lock);
830 rcu_read_unlock();
831 if (!fence)
832 return 0;
833
834 err = 0;
835 if (intel_timeline_sync_is_later(i915_request_timeline(rq), fence))
836 err = i915_sw_fence_await_dma_fence(&rq->submit,
837 fence, 0,
838 I915_FENCE_GFP);
839 dma_fence_put(fence);
840
841 return err;
842 }
843
844 static intel_engine_mask_t
845 already_busywaiting(struct i915_request *rq)
846 {
847 /*
848 * Polling a semaphore causes bus traffic, delaying other users of
849 * both the GPU and CPU. We want to limit the impact on others,
850 * while taking advantage of early submission to reduce GPU
851 * latency. Therefore we restrict ourselves to not using more
852 * than one semaphore from each source, and not using a semaphore
853 * if we have detected the engine is saturated (i.e. would not be
854 * submitted early and cause bus traffic reading an already passed
855 * semaphore).
856 *
857 * See the are-we-too-late? check in __i915_request_submit().
858 */
859 return rq->sched.semaphores | rq->engine->saturated;
860 }
861
862 static int
863 __emit_semaphore_wait(struct i915_request *to,
864 struct i915_request *from,
865 u32 seqno)
866 {
867 const int has_token = INTEL_GEN(to->i915) >= 12;
868 u32 hwsp_offset;
869 int len, err;
870 u32 *cs;
871
872 GEM_BUG_ON(INTEL_GEN(to->i915) < 8);
873
874 /* We need to pin the signaler's HWSP until we are finished reading. */
875 err = intel_timeline_read_hwsp(from, to, &hwsp_offset);
876 if (err)
877 return err;
878
879 len = 4;
880 if (has_token)
881 len += 2;
882
883 cs = intel_ring_begin(to, len);
884 if (IS_ERR(cs))
885 return PTR_ERR(cs);
886
887 /*
888 * Using greater-than-or-equal here means we have to worry
889 * about seqno wraparound. To side step that issue, we swap
890 * the timeline HWSP upon wrapping, so that everyone listening
891 * for the old (pre-wrap) values do not see the much smaller
892 * (post-wrap) values than they were expecting (and so wait
893 * forever).
894 */
895 *cs++ = (MI_SEMAPHORE_WAIT |
896 MI_SEMAPHORE_GLOBAL_GTT |
897 MI_SEMAPHORE_POLL |
898 MI_SEMAPHORE_SAD_GTE_SDD) +
899 has_token;
900 *cs++ = seqno;
901 *cs++ = hwsp_offset;
902 *cs++ = 0;
903 if (has_token) {
904 *cs++ = 0;
905 *cs++ = MI_NOOP;
906 }
907
908 intel_ring_advance(to, cs);
909 return 0;
910 }
911
912 static int
913 emit_semaphore_wait(struct i915_request *to,
914 struct i915_request *from,
915 gfp_t gfp)
916 {
917 /* Just emit the first semaphore we see as request space is limited. */
918 if (already_busywaiting(to) & from->engine->mask)
919 goto await_fence;
920
921 if (i915_request_await_start(to, from) < 0)
922 goto await_fence;
923
924 /* Only submit our spinner after the signaler is running! */
925 if (__await_execution(to, from, NULL, gfp))
926 goto await_fence;
927
928 if (__emit_semaphore_wait(to, from, from->fence.seqno))
929 goto await_fence;
930
931 to->sched.semaphores |= from->engine->mask;
932 to->sched.flags |= I915_SCHED_HAS_SEMAPHORE_CHAIN;
933 return 0;
934
935 await_fence:
936 return i915_sw_fence_await_dma_fence(&to->submit,
937 &from->fence, 0,
938 I915_FENCE_GFP);
939 }
940
941 static int
942 i915_request_await_request(struct i915_request *to, struct i915_request *from)
943 {
944 int ret;
945
946 GEM_BUG_ON(to == from);
947 GEM_BUG_ON(to->timeline == from->timeline);
948
949 if (i915_request_completed(from))
950 return 0;
951
952 if (to->engine->schedule) {
953 ret = i915_sched_node_add_dependency(&to->sched, &from->sched);
954 if (ret < 0)
955 return ret;
956 }
957
958 if (to->engine == from->engine)
959 ret = i915_sw_fence_await_sw_fence_gfp(&to->submit,
960 &from->submit,
961 I915_FENCE_GFP);
962 else if (intel_context_use_semaphores(to->context))
963 ret = emit_semaphore_wait(to, from, I915_FENCE_GFP);
964 else
965 ret = i915_sw_fence_await_dma_fence(&to->submit,
966 &from->fence, 0,
967 I915_FENCE_GFP);
968 if (ret < 0)
969 return ret;
970
971 if (to->sched.flags & I915_SCHED_HAS_SEMAPHORE_CHAIN) {
972 ret = i915_sw_fence_await_dma_fence(&to->semaphore,
973 &from->fence, 0,
974 I915_FENCE_GFP);
975 if (ret < 0)
976 return ret;
977 }
978
979 return 0;
980 }
981
982 int
983 i915_request_await_dma_fence(struct i915_request *rq, struct dma_fence *fence)
984 {
985 struct dma_fence **child = &fence;
986 unsigned int nchild = 1;
987 int ret;
988
989 /*
990 * Note that if the fence-array was created in signal-on-any mode,
991 * we should *not* decompose it into its individual fences. However,
992 * we don't currently store which mode the fence-array is operating
993 * in. Fortunately, the only user of signal-on-any is private to
994 * amdgpu and we should not see any incoming fence-array from
995 * sync-file being in signal-on-any mode.
996 */
997 if (dma_fence_is_array(fence)) {
998 struct dma_fence_array *array = to_dma_fence_array(fence);
999
1000 child = array->fences;
1001 nchild = array->num_fences;
1002 GEM_BUG_ON(!nchild);
1003 }
1004
1005 do {
1006 fence = *child++;
1007 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
1008 i915_sw_fence_set_error_once(&rq->submit, fence->error);
1009 continue;
1010 }
1011
1012 /*
1013 * Requests on the same timeline are explicitly ordered, along
1014 * with their dependencies, by i915_request_add() which ensures
1015 * that requests are submitted in-order through each ring.
1016 */
1017 if (fence->context == rq->fence.context)
1018 continue;
1019
1020 /* Squash repeated waits to the same timelines */
1021 if (fence->context &&
1022 intel_timeline_sync_is_later(i915_request_timeline(rq),
1023 fence))
1024 continue;
1025
1026 if (dma_fence_is_i915(fence))
1027 ret = i915_request_await_request(rq, to_request(fence));
1028 else
1029 ret = i915_sw_fence_await_dma_fence(&rq->submit, fence,
1030 fence->context ? I915_FENCE_TIMEOUT : 0,
1031 I915_FENCE_GFP);
1032 if (ret < 0)
1033 return ret;
1034
1035 /* Record the latest fence used against each timeline */
1036 if (fence->context)
1037 intel_timeline_sync_set(i915_request_timeline(rq),
1038 fence);
1039 } while (--nchild);
1040
1041 return 0;
1042 }
1043
1044 static bool intel_timeline_sync_has_start(struct intel_timeline *tl,
1045 struct dma_fence *fence)
1046 {
1047 return __intel_timeline_sync_is_later(tl,
1048 fence->context,
1049 fence->seqno - 1);
1050 }
1051
1052 static int intel_timeline_sync_set_start(struct intel_timeline *tl,
1053 const struct dma_fence *fence)
1054 {
1055 return __intel_timeline_sync_set(tl, fence->context, fence->seqno - 1);
1056 }
1057
1058 static int
1059 __i915_request_await_execution(struct i915_request *to,
1060 struct i915_request *from,
1061 void (*hook)(struct i915_request *rq,
1062 struct dma_fence *signal))
1063 {
1064 int err;
1065
1066 /* Submit both requests at the same time */
1067 err = __await_execution(to, from, hook, I915_FENCE_GFP);
1068 if (err)
1069 return err;
1070
1071 /* Squash repeated depenendices to the same timelines */
1072 if (intel_timeline_sync_has_start(i915_request_timeline(to),
1073 &from->fence))
1074 return 0;
1075
1076 /* Ensure both start together [after all semaphores in signal] */
1077 if (intel_engine_has_semaphores(to->engine))
1078 err = __emit_semaphore_wait(to, from, from->fence.seqno - 1);
1079 else
1080 err = i915_request_await_start(to, from);
1081 if (err < 0)
1082 return err;
1083
1084 /* Couple the dependency tree for PI on this exposed to->fence */
1085 if (to->engine->schedule) {
1086 err = i915_sched_node_add_dependency(&to->sched, &from->sched);
1087 if (err < 0)
1088 return err;
1089 }
1090
1091 return intel_timeline_sync_set_start(i915_request_timeline(to),
1092 &from->fence);
1093 }
1094
1095 int
1096 i915_request_await_execution(struct i915_request *rq,
1097 struct dma_fence *fence,
1098 void (*hook)(struct i915_request *rq,
1099 struct dma_fence *signal))
1100 {
1101 struct dma_fence **child = &fence;
1102 unsigned int nchild = 1;
1103 int ret;
1104
1105 if (dma_fence_is_array(fence)) {
1106 struct dma_fence_array *array = to_dma_fence_array(fence);
1107
1108 /* XXX Error for signal-on-any fence arrays */
1109
1110 child = array->fences;
1111 nchild = array->num_fences;
1112 GEM_BUG_ON(!nchild);
1113 }
1114
1115 do {
1116 fence = *child++;
1117 if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
1118 i915_sw_fence_set_error_once(&rq->submit, fence->error);
1119 continue;
1120 }
1121
1122 /*
1123 * We don't squash repeated fence dependencies here as we
1124 * want to run our callback in all cases.
1125 */
1126
1127 if (dma_fence_is_i915(fence))
1128 ret = __i915_request_await_execution(rq,
1129 to_request(fence),
1130 hook);
1131 else
1132 ret = i915_sw_fence_await_dma_fence(&rq->submit, fence,
1133 I915_FENCE_TIMEOUT,
1134 GFP_KERNEL);
1135 if (ret < 0)
1136 return ret;
1137 } while (--nchild);
1138
1139 return 0;
1140 }
1141
1142 /**
1143 * i915_request_await_object - set this request to (async) wait upon a bo
1144 * @to: request we are wishing to use
1145 * @obj: object which may be in use on another ring.
1146 * @write: whether the wait is on behalf of a writer
1147 *
1148 * This code is meant to abstract object synchronization with the GPU.
1149 * Conceptually we serialise writes between engines inside the GPU.
1150 * We only allow one engine to write into a buffer at any time, but
1151 * multiple readers. To ensure each has a coherent view of memory, we must:
1152 *
1153 * - If there is an outstanding write request to the object, the new
1154 * request must wait for it to complete (either CPU or in hw, requests
1155 * on the same ring will be naturally ordered).
1156 *
1157 * - If we are a write request (pending_write_domain is set), the new
1158 * request must wait for outstanding read requests to complete.
1159 *
1160 * Returns 0 if successful, else propagates up the lower layer error.
1161 */
1162 int
1163 i915_request_await_object(struct i915_request *to,
1164 struct drm_i915_gem_object *obj,
1165 bool write)
1166 {
1167 struct dma_fence *excl;
1168 int ret = 0;
1169
1170 if (write) {
1171 struct dma_fence **shared;
1172 unsigned int count, i;
1173
1174 ret = dma_resv_get_fences_rcu(obj->base.resv,
1175 &excl, &count, &shared);
1176 if (ret)
1177 return ret;
1178
1179 for (i = 0; i < count; i++) {
1180 ret = i915_request_await_dma_fence(to, shared[i]);
1181 if (ret)
1182 break;
1183
1184 dma_fence_put(shared[i]);
1185 }
1186
1187 for (; i < count; i++)
1188 dma_fence_put(shared[i]);
1189 kfree(shared);
1190 } else {
1191 excl = dma_resv_get_excl_rcu(obj->base.resv);
1192 }
1193
1194 if (excl) {
1195 if (ret == 0)
1196 ret = i915_request_await_dma_fence(to, excl);
1197
1198 dma_fence_put(excl);
1199 }
1200
1201 return ret;
1202 }
1203
1204 void i915_request_skip(struct i915_request *rq, int error)
1205 {
1206 void *vaddr = rq->ring->vaddr;
1207 u32 head;
1208
1209 GEM_BUG_ON(!IS_ERR_VALUE((long)error));
1210 dma_fence_set_error(&rq->fence, error);
1211
1212 if (rq->infix == rq->postfix)
1213 return;
1214
1215 /*
1216 * As this request likely depends on state from the lost
1217 * context, clear out all the user operations leaving the
1218 * breadcrumb at the end (so we get the fence notifications).
1219 */
1220 head = rq->infix;
1221 if (rq->postfix < head) {
1222 memset(vaddr + head, 0, rq->ring->size - head);
1223 head = 0;
1224 }
1225 memset(vaddr + head, 0, rq->postfix - head);
1226 rq->infix = rq->postfix;
1227 }
1228
1229 static struct i915_request *
1230 __i915_request_add_to_timeline(struct i915_request *rq)
1231 {
1232 struct intel_timeline *timeline = i915_request_timeline(rq);
1233 struct i915_request *prev;
1234
1235 /*
1236 * Dependency tracking and request ordering along the timeline
1237 * is special cased so that we can eliminate redundant ordering
1238 * operations while building the request (we know that the timeline
1239 * itself is ordered, and here we guarantee it).
1240 *
1241 * As we know we will need to emit tracking along the timeline,
1242 * we embed the hooks into our request struct -- at the cost of
1243 * having to have specialised no-allocation interfaces (which will
1244 * be beneficial elsewhere).
1245 *
1246 * A second benefit to open-coding i915_request_await_request is
1247 * that we can apply a slight variant of the rules specialised
1248 * for timelines that jump between engines (such as virtual engines).
1249 * If we consider the case of virtual engine, we must emit a dma-fence
1250 * to prevent scheduling of the second request until the first is
1251 * complete (to maximise our greedy late load balancing) and this
1252 * precludes optimising to use semaphores serialisation of a single
1253 * timeline across engines.
1254 */
1255 prev = to_request(__i915_active_fence_set(&timeline->last_request,
1256 &rq->fence));
1257 if (prev && !i915_request_completed(prev)) {
1258 if (is_power_of_2(prev->engine->mask | rq->engine->mask))
1259 i915_sw_fence_await_sw_fence(&rq->submit,
1260 &prev->submit,
1261 &rq->submitq);
1262 else
1263 __i915_sw_fence_await_dma_fence(&rq->submit,
1264 &prev->fence,
1265 &rq->dmaq);
1266 if (rq->engine->schedule)
1267 __i915_sched_node_add_dependency(&rq->sched,
1268 &prev->sched,
1269 &rq->dep,
1270 0);
1271 }
1272
1273 list_add_tail(&rq->link, &timeline->requests);
1274
1275 /*
1276 * Make sure that no request gazumped us - if it was allocated after
1277 * our i915_request_alloc() and called __i915_request_add() before
1278 * us, the timeline will hold its seqno which is later than ours.
1279 */
1280 GEM_BUG_ON(timeline->seqno != rq->fence.seqno);
1281
1282 return prev;
1283 }
1284
1285 /*
1286 * NB: This function is not allowed to fail. Doing so would mean the the
1287 * request is not being tracked for completion but the work itself is
1288 * going to happen on the hardware. This would be a Bad Thing(tm).
1289 */
1290 struct i915_request *__i915_request_commit(struct i915_request *rq)
1291 {
1292 struct intel_engine_cs *engine = rq->engine;
1293 struct intel_ring *ring = rq->ring;
1294 u32 *cs;
1295
1296 RQ_TRACE(rq, "\n");
1297
1298 /*
1299 * To ensure that this call will not fail, space for its emissions
1300 * should already have been reserved in the ring buffer. Let the ring
1301 * know that it is time to use that space up.
1302 */
1303 GEM_BUG_ON(rq->reserved_space > ring->space);
1304 rq->reserved_space = 0;
1305 rq->emitted_jiffies = jiffies;
1306
1307 /*
1308 * Record the position of the start of the breadcrumb so that
1309 * should we detect the updated seqno part-way through the
1310 * GPU processing the request, we never over-estimate the
1311 * position of the ring's HEAD.
1312 */
1313 cs = intel_ring_begin(rq, engine->emit_fini_breadcrumb_dw);
1314 GEM_BUG_ON(IS_ERR(cs));
1315 rq->postfix = intel_ring_offset(rq, cs);
1316
1317 return __i915_request_add_to_timeline(rq);
1318 }
1319
1320 void __i915_request_queue(struct i915_request *rq,
1321 const struct i915_sched_attr *attr)
1322 {
1323 /*
1324 * Let the backend know a new request has arrived that may need
1325 * to adjust the existing execution schedule due to a high priority
1326 * request - i.e. we may want to preempt the current request in order
1327 * to run a high priority dependency chain *before* we can execute this
1328 * request.
1329 *
1330 * This is called before the request is ready to run so that we can
1331 * decide whether to preempt the entire chain so that it is ready to
1332 * run at the earliest possible convenience.
1333 */
1334 i915_sw_fence_commit(&rq->semaphore);
1335 if (attr && rq->engine->schedule)
1336 rq->engine->schedule(rq, attr);
1337 i915_sw_fence_commit(&rq->submit);
1338 }
1339
1340 void i915_request_add(struct i915_request *rq)
1341 {
1342 struct intel_timeline * const tl = i915_request_timeline(rq);
1343 struct i915_sched_attr attr = {};
1344 struct i915_request *prev;
1345
1346 lockdep_assert_held(&tl->mutex);
1347 lockdep_unpin_lock(&tl->mutex, rq->cookie);
1348
1349 trace_i915_request_add(rq);
1350
1351 prev = __i915_request_commit(rq);
1352
1353 if (rcu_access_pointer(rq->context->gem_context))
1354 attr = i915_request_gem_context(rq)->sched;
1355
1356 /*
1357 * Boost actual workloads past semaphores!
1358 *
1359 * With semaphores we spin on one engine waiting for another,
1360 * simply to reduce the latency of starting our work when
1361 * the signaler completes. However, if there is any other
1362 * work that we could be doing on this engine instead, that
1363 * is better utilisation and will reduce the overall duration
1364 * of the current work. To avoid PI boosting a semaphore
1365 * far in the distance past over useful work, we keep a history
1366 * of any semaphore use along our dependency chain.
1367 */
1368 if (!(rq->sched.flags & I915_SCHED_HAS_SEMAPHORE_CHAIN))
1369 attr.priority |= I915_PRIORITY_NOSEMAPHORE;
1370
1371 /*
1372 * Boost priorities to new clients (new request flows).
1373 *
1374 * Allow interactive/synchronous clients to jump ahead of
1375 * the bulk clients. (FQ_CODEL)
1376 */
1377 if (list_empty(&rq->sched.signalers_list))
1378 attr.priority |= I915_PRIORITY_WAIT;
1379
1380 #ifdef __NetBSD__
1381 int s = splsoftserial();
1382 #else
1383 local_bh_disable();
1384 #endif
1385 __i915_request_queue(rq, &attr);
1386 #ifdef __NetBSD__
1387 splx(s);
1388 #else
1389 local_bh_enable(); /* Kick the execlists tasklet if just scheduled */
1390 #endif
1391
1392 /*
1393 * In typical scenarios, we do not expect the previous request on
1394 * the timeline to be still tracked by timeline->last_request if it
1395 * has been completed. If the completed request is still here, that
1396 * implies that request retirement is a long way behind submission,
1397 * suggesting that we haven't been retiring frequently enough from
1398 * the combination of retire-before-alloc, waiters and the background
1399 * retirement worker. So if the last request on this timeline was
1400 * already completed, do a catch up pass, flushing the retirement queue
1401 * up to this client. Since we have now moved the heaviest operations
1402 * during retirement onto secondary workers, such as freeing objects
1403 * or contexts, retiring a bunch of requests is mostly list management
1404 * (and cache misses), and so we should not be overly penalizing this
1405 * client by performing excess work, though we may still performing
1406 * work on behalf of others -- but instead we should benefit from
1407 * improved resource management. (Well, that's the theory at least.)
1408 */
1409 if (prev &&
1410 i915_request_completed(prev) &&
1411 rcu_access_pointer(prev->timeline) == tl)
1412 i915_request_retire_upto(prev);
1413
1414 mutex_unlock(&tl->mutex);
1415 }
1416
1417 static unsigned long local_clock_us(unsigned int *cpu)
1418 {
1419 unsigned long t;
1420
1421 /*
1422 * Cheaply and approximately convert from nanoseconds to microseconds.
1423 * The result and subsequent calculations are also defined in the same
1424 * approximate microseconds units. The principal source of timing
1425 * error here is from the simple truncation.
1426 *
1427 * Note that local_clock() is only defined wrt to the current CPU;
1428 * the comparisons are no longer valid if we switch CPUs. Instead of
1429 * blocking preemption for the entire busywait, we can detect the CPU
1430 * switch and use that as indicator of system load and a reason to
1431 * stop busywaiting, see busywait_stop().
1432 */
1433 *cpu = get_cpu();
1434 t = local_clock() >> 10;
1435 put_cpu();
1436
1437 return t;
1438 }
1439
1440 static bool busywait_stop(unsigned long timeout, unsigned int cpu)
1441 {
1442 unsigned int this_cpu;
1443
1444 if (time_after(local_clock_us(&this_cpu), timeout))
1445 return true;
1446
1447 return this_cpu != cpu;
1448 }
1449
1450 static bool __i915_spin_request(const struct i915_request * const rq,
1451 int state, unsigned long timeout_us)
1452 {
1453 unsigned int cpu;
1454
1455 /*
1456 * Only wait for the request if we know it is likely to complete.
1457 *
1458 * We don't track the timestamps around requests, nor the average
1459 * request length, so we do not have a good indicator that this
1460 * request will complete within the timeout. What we do know is the
1461 * order in which requests are executed by the context and so we can
1462 * tell if the request has been started. If the request is not even
1463 * running yet, it is a fair assumption that it will not complete
1464 * within our relatively short timeout.
1465 */
1466 if (!i915_request_is_running(rq))
1467 return false;
1468
1469 /*
1470 * When waiting for high frequency requests, e.g. during synchronous
1471 * rendering split between the CPU and GPU, the finite amount of time
1472 * required to set up the irq and wait upon it limits the response
1473 * rate. By busywaiting on the request completion for a short while we
1474 * can service the high frequency waits as quick as possible. However,
1475 * if it is a slow request, we want to sleep as quickly as possible.
1476 * The tradeoff between waiting and sleeping is roughly the time it
1477 * takes to sleep on a request, on the order of a microsecond.
1478 */
1479
1480 timeout_us += local_clock_us(&cpu);
1481 do {
1482 if (i915_request_completed(rq))
1483 return true;
1484
1485 if (signal_pending_state(state, current))
1486 break;
1487
1488 if (busywait_stop(timeout_us, cpu))
1489 break;
1490
1491 cpu_relax();
1492 } while (!need_resched());
1493
1494 return false;
1495 }
1496
1497 struct request_wait {
1498 struct dma_fence_cb cb;
1499 #ifdef __NetBSD__
1500 drm_waitqueue_t wq;
1501 #else
1502 struct task_struct *tsk;
1503 #endif
1504 };
1505
1506 static void request_wait_wake(struct dma_fence *fence, struct dma_fence_cb *cb)
1507 {
1508 struct request_wait *wait = container_of(cb, typeof(*wait), cb);
1509
1510 #ifdef __NetBSD__
1511 DRM_SPIN_WAKEUP_ALL(&wait->wq, fence->lock);
1512 #else
1513 wake_up_process(wait->tsk);
1514 #endif
1515 }
1516
1517 /**
1518 * i915_request_wait - wait until execution of request has finished
1519 * @rq: the request to wait upon
1520 * @flags: how to wait
1521 * @timeout: how long to wait in jiffies
1522 *
1523 * i915_request_wait() waits for the request to be completed, for a
1524 * maximum of @timeout jiffies (with MAX_SCHEDULE_TIMEOUT implying an
1525 * unbounded wait).
1526 *
1527 * Returns the remaining time (in jiffies) if the request completed, which may
1528 * be zero or -ETIME if the request is unfinished after the timeout expires.
1529 * May return -EINTR is called with I915_WAIT_INTERRUPTIBLE and a signal is
1530 * pending before the request completes.
1531 */
1532 long i915_request_wait(struct i915_request *rq,
1533 unsigned int flags,
1534 long timeout)
1535 {
1536 #ifdef __NetBSD__
1537 const int state = 0;
1538 #else
1539 const int state = flags & I915_WAIT_INTERRUPTIBLE ?
1540 TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE;
1541 #endif
1542 struct request_wait wait;
1543
1544 might_sleep();
1545 GEM_BUG_ON(timeout < 0);
1546
1547 if (dma_fence_is_signaled(&rq->fence))
1548 return timeout;
1549
1550 if (!timeout)
1551 return -ETIME;
1552
1553 trace_i915_request_wait_begin(rq, flags);
1554
1555 /*
1556 * We must never wait on the GPU while holding a lock as we
1557 * may need to perform a GPU reset. So while we don't need to
1558 * serialise wait/reset with an explicit lock, we do want
1559 * lockdep to detect potential dependency cycles.
1560 */
1561 mutex_acquire(&rq->engine->gt->reset.mutex.dep_map, 0, 0, _THIS_IP_);
1562
1563 /*
1564 * Optimistic spin before touching IRQs.
1565 *
1566 * We may use a rather large value here to offset the penalty of
1567 * switching away from the active task. Frequently, the client will
1568 * wait upon an old swapbuffer to throttle itself to remain within a
1569 * frame of the gpu. If the client is running in lockstep with the gpu,
1570 * then it should not be waiting long at all, and a sleep now will incur
1571 * extra scheduler latency in producing the next frame. To try to
1572 * avoid adding the cost of enabling/disabling the interrupt to the
1573 * short wait, we first spin to see if the request would have completed
1574 * in the time taken to setup the interrupt.
1575 *
1576 * We need upto 5us to enable the irq, and upto 20us to hide the
1577 * scheduler latency of a context switch, ignoring the secondary
1578 * impacts from a context switch such as cache eviction.
1579 *
1580 * The scheme used for low-latency IO is called "hybrid interrupt
1581 * polling". The suggestion there is to sleep until just before you
1582 * expect to be woken by the device interrupt and then poll for its
1583 * completion. That requires having a good predictor for the request
1584 * duration, which we currently lack.
1585 */
1586 if (IS_ACTIVE(CONFIG_DRM_I915_SPIN_REQUEST) &&
1587 __i915_spin_request(rq, state, CONFIG_DRM_I915_SPIN_REQUEST)) {
1588 dma_fence_signal(&rq->fence);
1589 goto out;
1590 }
1591
1592 /*
1593 * This client is about to stall waiting for the GPU. In many cases
1594 * this is undesirable and limits the throughput of the system, as
1595 * many clients cannot continue processing user input/output whilst
1596 * blocked. RPS autotuning may take tens of milliseconds to respond
1597 * to the GPU load and thus incurs additional latency for the client.
1598 * We can circumvent that by promoting the GPU frequency to maximum
1599 * before we sleep. This makes the GPU throttle up much more quickly
1600 * (good for benchmarks and user experience, e.g. window animations),
1601 * but at a cost of spending more power processing the workload
1602 * (bad for battery).
1603 */
1604 if (flags & I915_WAIT_PRIORITY) {
1605 if (!i915_request_started(rq) && INTEL_GEN(rq->i915) >= 6)
1606 intel_rps_boost(rq);
1607 i915_schedule_bump_priority(rq, I915_PRIORITY_WAIT);
1608 }
1609
1610 #ifdef __NetBSD__
1611 DRM_INIT_WAITQUEUE(&wait.wq, "i915req");
1612 if (dma_fence_add_callback(&rq->fence, &wait.cb, request_wait_wake))
1613 goto out;
1614 spin_lock(rq->fence.lock);
1615 #define C (i915_request_completed(rq) ? 1 : \
1616 (spin_unlock(rq->fence.lock), \
1617 intel_engine_flush_submission(rq->engine), \
1618 spin_lock(rq->fence.lock), \
1619 i915_request_completed(rq)))
1620 if (flags & I915_WAIT_INTERRUPTIBLE) {
1621 DRM_SPIN_TIMED_WAIT_UNTIL(timeout, &wait.wq,
1622 rq->fence.lock, timeout,
1623 C);
1624 } else {
1625 DRM_SPIN_TIMED_WAIT_NOINTR_UNTIL(timeout, &wait.wq,
1626 rq->fence.lock, timeout,
1627 C);
1628 }
1629 #undef C
1630 if (timeout > 0) /* succeeded before timeout */
1631 dma_fence_signal_locked(&rq->fence);
1632 spin_unlock(rq->fence.lock);
1633 DRM_DESTROY_WAITQUEUE(&wait.wq);
1634 #else
1635 wait.tsk = current;
1636 if (dma_fence_add_callback(&rq->fence, &wait.cb, request_wait_wake))
1637 goto out;
1638
1639 for (;;) {
1640 set_current_state(state);
1641
1642 if (i915_request_completed(rq)) {
1643 dma_fence_signal(&rq->fence);
1644 break;
1645 }
1646
1647 if (signal_pending_state(state, current)) {
1648 timeout = -ERESTARTSYS;
1649 break;
1650 }
1651
1652 if (!timeout) {
1653 timeout = -ETIME;
1654 break;
1655 }
1656
1657 intel_engine_flush_submission(rq->engine);
1658 timeout = io_schedule_timeout(timeout);
1659 }
1660 __set_current_state(TASK_RUNNING);
1661 #endif
1662
1663 dma_fence_remove_callback(&rq->fence, &wait.cb);
1664
1665 out:
1666 mutex_release(&rq->engine->gt->reset.mutex.dep_map, _THIS_IP_);
1667 trace_i915_request_wait_end(rq);
1668 return timeout;
1669 }
1670
1671 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
1672 #include "selftests/mock_request.c"
1673 #include "selftests/i915_request.c"
1674 #endif
1675
1676 static void i915_global_request_shrink(void)
1677 {
1678 kmem_cache_shrink(global.slab_dependencies);
1679 kmem_cache_shrink(global.slab_execute_cbs);
1680 kmem_cache_shrink(global.slab_requests);
1681 }
1682
1683 static void i915_global_request_exit(void)
1684 {
1685 kmem_cache_destroy(global.slab_dependencies);
1686 kmem_cache_destroy(global.slab_execute_cbs);
1687 kmem_cache_destroy(global.slab_requests);
1688 }
1689
1690 static struct i915_global_request global = { {
1691 .shrink = i915_global_request_shrink,
1692 .exit = i915_global_request_exit,
1693 } };
1694
1695 int __init i915_global_request_init(void)
1696 {
1697 global.slab_requests =
1698 kmem_cache_create_dtor("i915_request",
1699 sizeof(struct i915_request),
1700 __alignof__(struct i915_request),
1701 SLAB_HWCACHE_ALIGN |
1702 SLAB_RECLAIM_ACCOUNT |
1703 SLAB_TYPESAFE_BY_RCU,
1704 __i915_request_ctor,
1705 __i915_request_dtor);
1706 if (!global.slab_requests)
1707 return -ENOMEM;
1708
1709 global.slab_execute_cbs = KMEM_CACHE(execute_cb,
1710 SLAB_HWCACHE_ALIGN |
1711 SLAB_RECLAIM_ACCOUNT |
1712 SLAB_TYPESAFE_BY_RCU);
1713 if (!global.slab_execute_cbs)
1714 goto err_requests;
1715
1716 global.slab_dependencies = KMEM_CACHE(i915_dependency,
1717 SLAB_HWCACHE_ALIGN |
1718 SLAB_RECLAIM_ACCOUNT);
1719 if (!global.slab_dependencies)
1720 goto err_execute_cbs;
1721
1722 i915_global_register(&global.base);
1723 return 0;
1724
1725 err_execute_cbs:
1726 kmem_cache_destroy(global.slab_execute_cbs);
1727 err_requests:
1728 kmem_cache_destroy(global.slab_requests);
1729 return -ENOMEM;
1730 }
1731