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