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