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