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