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