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