]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/gpu/drm/i915/i915_gem_request.c
drm/i915: Move the global sync optimisation to the timeline
[karo-tx-linux.git] / drivers / gpu / drm / i915 / i915_gem_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
28 #include "i915_drv.h"
29
30 static const char *i915_fence_get_driver_name(struct dma_fence *fence)
31 {
32         return "i915";
33 }
34
35 static const char *i915_fence_get_timeline_name(struct dma_fence *fence)
36 {
37         /* Timelines are bound by eviction to a VM. However, since
38          * we only have a global seqno at the moment, we only have
39          * a single timeline. Note that each timeline will have
40          * multiple execution contexts (fence contexts) as we allow
41          * engines within a single timeline to execute in parallel.
42          */
43         return to_request(fence)->timeline->common->name;
44 }
45
46 static bool i915_fence_signaled(struct dma_fence *fence)
47 {
48         return i915_gem_request_completed(to_request(fence));
49 }
50
51 static bool i915_fence_enable_signaling(struct dma_fence *fence)
52 {
53         if (i915_fence_signaled(fence))
54                 return false;
55
56         intel_engine_enable_signaling(to_request(fence));
57         return true;
58 }
59
60 static signed long i915_fence_wait(struct dma_fence *fence,
61                                    bool interruptible,
62                                    signed long timeout)
63 {
64         return i915_wait_request(to_request(fence), interruptible, timeout);
65 }
66
67 static void i915_fence_value_str(struct dma_fence *fence, char *str, int size)
68 {
69         snprintf(str, size, "%u", fence->seqno);
70 }
71
72 static void i915_fence_timeline_value_str(struct dma_fence *fence, char *str,
73                                           int size)
74 {
75         snprintf(str, size, "%u",
76                  intel_engine_get_seqno(to_request(fence)->engine));
77 }
78
79 static void i915_fence_release(struct dma_fence *fence)
80 {
81         struct drm_i915_gem_request *req = to_request(fence);
82
83         kmem_cache_free(req->i915->requests, req);
84 }
85
86 const struct dma_fence_ops i915_fence_ops = {
87         .get_driver_name = i915_fence_get_driver_name,
88         .get_timeline_name = i915_fence_get_timeline_name,
89         .enable_signaling = i915_fence_enable_signaling,
90         .signaled = i915_fence_signaled,
91         .wait = i915_fence_wait,
92         .release = i915_fence_release,
93         .fence_value_str = i915_fence_value_str,
94         .timeline_value_str = i915_fence_timeline_value_str,
95 };
96
97 int i915_gem_request_add_to_client(struct drm_i915_gem_request *req,
98                                    struct drm_file *file)
99 {
100         struct drm_i915_private *dev_private;
101         struct drm_i915_file_private *file_priv;
102
103         WARN_ON(!req || !file || req->file_priv);
104
105         if (!req || !file)
106                 return -EINVAL;
107
108         if (req->file_priv)
109                 return -EINVAL;
110
111         dev_private = req->i915;
112         file_priv = file->driver_priv;
113
114         spin_lock(&file_priv->mm.lock);
115         req->file_priv = file_priv;
116         list_add_tail(&req->client_list, &file_priv->mm.request_list);
117         spin_unlock(&file_priv->mm.lock);
118
119         return 0;
120 }
121
122 static inline void
123 i915_gem_request_remove_from_client(struct drm_i915_gem_request *request)
124 {
125         struct drm_i915_file_private *file_priv = request->file_priv;
126
127         if (!file_priv)
128                 return;
129
130         spin_lock(&file_priv->mm.lock);
131         list_del(&request->client_list);
132         request->file_priv = NULL;
133         spin_unlock(&file_priv->mm.lock);
134 }
135
136 void i915_gem_retire_noop(struct i915_gem_active *active,
137                           struct drm_i915_gem_request *request)
138 {
139         /* Space left intentionally blank */
140 }
141
142 static void i915_gem_request_retire(struct drm_i915_gem_request *request)
143 {
144         struct i915_gem_active *active, *next;
145
146         lockdep_assert_held(&request->i915->drm.struct_mutex);
147         GEM_BUG_ON(!i915_gem_request_completed(request));
148
149         trace_i915_gem_request_retire(request);
150         list_del_init(&request->link);
151
152         /* We know the GPU must have read the request to have
153          * sent us the seqno + interrupt, so use the position
154          * of tail of the request to update the last known position
155          * of the GPU head.
156          *
157          * Note this requires that we are always called in request
158          * completion order.
159          */
160         list_del(&request->ring_link);
161         request->ring->last_retired_head = request->postfix;
162
163         /* Walk through the active list, calling retire on each. This allows
164          * objects to track their GPU activity and mark themselves as idle
165          * when their *last* active request is completed (updating state
166          * tracking lists for eviction, active references for GEM, etc).
167          *
168          * As the ->retire() may free the node, we decouple it first and
169          * pass along the auxiliary information (to avoid dereferencing
170          * the node after the callback).
171          */
172         list_for_each_entry_safe(active, next, &request->active_list, link) {
173                 /* In microbenchmarks or focusing upon time inside the kernel,
174                  * we may spend an inordinate amount of time simply handling
175                  * the retirement of requests and processing their callbacks.
176                  * Of which, this loop itself is particularly hot due to the
177                  * cache misses when jumping around the list of i915_gem_active.
178                  * So we try to keep this loop as streamlined as possible and
179                  * also prefetch the next i915_gem_active to try and hide
180                  * the likely cache miss.
181                  */
182                 prefetchw(next);
183
184                 INIT_LIST_HEAD(&active->link);
185                 RCU_INIT_POINTER(active->request, NULL);
186
187                 active->retire(active, request);
188         }
189
190         i915_gem_request_remove_from_client(request);
191
192         if (request->previous_context) {
193                 if (i915.enable_execlists)
194                         intel_lr_context_unpin(request->previous_context,
195                                                request->engine);
196         }
197
198         i915_gem_context_put(request->ctx);
199
200         dma_fence_signal(&request->fence);
201         i915_gem_request_put(request);
202 }
203
204 void i915_gem_request_retire_upto(struct drm_i915_gem_request *req)
205 {
206         struct intel_engine_cs *engine = req->engine;
207         struct drm_i915_gem_request *tmp;
208
209         lockdep_assert_held(&req->i915->drm.struct_mutex);
210         if (list_empty(&req->link))
211                 return;
212
213         do {
214                 tmp = list_first_entry(&engine->timeline->requests,
215                                        typeof(*tmp), link);
216
217                 i915_gem_request_retire(tmp);
218         } while (tmp != req);
219 }
220
221 static int i915_gem_check_wedge(struct drm_i915_private *dev_priv)
222 {
223         struct i915_gpu_error *error = &dev_priv->gpu_error;
224
225         if (i915_terminally_wedged(error))
226                 return -EIO;
227
228         if (i915_reset_in_progress(error)) {
229                 /* Non-interruptible callers can't handle -EAGAIN, hence return
230                  * -EIO unconditionally for these.
231                  */
232                 if (!dev_priv->mm.interruptible)
233                         return -EIO;
234
235                 return -EAGAIN;
236         }
237
238         return 0;
239 }
240
241 static int i915_gem_init_global_seqno(struct drm_i915_private *i915, u32 seqno)
242 {
243         struct i915_gem_timeline *timeline = &i915->gt.global_timeline;
244         struct intel_engine_cs *engine;
245         enum intel_engine_id id;
246         int ret;
247
248         /* Carefully retire all requests without writing to the rings */
249         ret = i915_gem_wait_for_idle(i915,
250                                      I915_WAIT_INTERRUPTIBLE |
251                                      I915_WAIT_LOCKED);
252         if (ret)
253                 return ret;
254
255         i915_gem_retire_requests(i915);
256
257         /* If the seqno wraps around, we need to clear the breadcrumb rbtree */
258         if (!i915_seqno_passed(seqno, timeline->next_seqno)) {
259                 while (intel_kick_waiters(i915) || intel_kick_signalers(i915))
260                         yield();
261                 yield();
262         }
263
264         /* Finally reset hw state */
265         for_each_engine(engine, i915, id)
266                 intel_engine_init_global_seqno(engine, seqno);
267
268         list_for_each_entry(timeline, &i915->gt.timelines, link) {
269                 for_each_engine(engine, i915, id) {
270                         struct intel_timeline *tl = &timeline->engine[id];
271
272                         memset(tl->sync_seqno, 0, sizeof(tl->sync_seqno));
273                 }
274         }
275
276         return 0;
277 }
278
279 int i915_gem_set_global_seqno(struct drm_device *dev, u32 seqno)
280 {
281         struct drm_i915_private *dev_priv = to_i915(dev);
282         int ret;
283
284         lockdep_assert_held(&dev_priv->drm.struct_mutex);
285
286         if (seqno == 0)
287                 return -EINVAL;
288
289         /* HWS page needs to be set less than what we
290          * will inject to ring
291          */
292         ret = i915_gem_init_global_seqno(dev_priv, seqno - 1);
293         if (ret)
294                 return ret;
295
296         dev_priv->gt.global_timeline.next_seqno = seqno;
297         return 0;
298 }
299
300 static int i915_gem_get_global_seqno(struct drm_i915_private *dev_priv,
301                                      u32 *seqno)
302 {
303         struct i915_gem_timeline *tl = &dev_priv->gt.global_timeline;
304
305         /* reserve 0 for non-seqno */
306         if (unlikely(tl->next_seqno == 0)) {
307                 int ret;
308
309                 ret = i915_gem_init_global_seqno(dev_priv, 0);
310                 if (ret)
311                         return ret;
312
313                 tl->next_seqno = 1;
314         }
315
316         *seqno = tl->next_seqno++;
317         return 0;
318 }
319
320 static int __i915_sw_fence_call
321 submit_notify(struct i915_sw_fence *fence, enum i915_sw_fence_notify state)
322 {
323         struct drm_i915_gem_request *request =
324                 container_of(fence, typeof(*request), submit);
325         struct intel_engine_cs *engine = request->engine;
326
327         if (state != FENCE_COMPLETE)
328                 return NOTIFY_DONE;
329
330         /* Will be called from irq-context when using foreign DMA fences */
331
332         engine->timeline->last_submitted_seqno = request->fence.seqno;
333
334         engine->emit_breadcrumb(request,
335                                 request->ring->vaddr + request->postfix);
336         engine->submit_request(request);
337
338         return NOTIFY_DONE;
339 }
340
341 /**
342  * i915_gem_request_alloc - allocate a request structure
343  *
344  * @engine: engine that we wish to issue the request on.
345  * @ctx: context that the request will be associated with.
346  *       This can be NULL if the request is not directly related to
347  *       any specific user context, in which case this function will
348  *       choose an appropriate context to use.
349  *
350  * Returns a pointer to the allocated request if successful,
351  * or an error code if not.
352  */
353 struct drm_i915_gem_request *
354 i915_gem_request_alloc(struct intel_engine_cs *engine,
355                        struct i915_gem_context *ctx)
356 {
357         struct drm_i915_private *dev_priv = engine->i915;
358         struct drm_i915_gem_request *req;
359         u32 seqno;
360         int ret;
361
362         /* ABI: Before userspace accesses the GPU (e.g. execbuffer), report
363          * EIO if the GPU is already wedged, or EAGAIN to drop the struct_mutex
364          * and restart.
365          */
366         ret = i915_gem_check_wedge(dev_priv);
367         if (ret)
368                 return ERR_PTR(ret);
369
370         /* Move the oldest request to the slab-cache (if not in use!) */
371         req = list_first_entry_or_null(&engine->timeline->requests,
372                                        typeof(*req), link);
373         if (req && i915_gem_request_completed(req))
374                 i915_gem_request_retire(req);
375
376         /* Beware: Dragons be flying overhead.
377          *
378          * We use RCU to look up requests in flight. The lookups may
379          * race with the request being allocated from the slab freelist.
380          * That is the request we are writing to here, may be in the process
381          * of being read by __i915_gem_active_get_rcu(). As such,
382          * we have to be very careful when overwriting the contents. During
383          * the RCU lookup, we change chase the request->engine pointer,
384          * read the request->global_seqno and increment the reference count.
385          *
386          * The reference count is incremented atomically. If it is zero,
387          * the lookup knows the request is unallocated and complete. Otherwise,
388          * it is either still in use, or has been reallocated and reset
389          * with dma_fence_init(). This increment is safe for release as we
390          * check that the request we have a reference to and matches the active
391          * request.
392          *
393          * Before we increment the refcount, we chase the request->engine
394          * pointer. We must not call kmem_cache_zalloc() or else we set
395          * that pointer to NULL and cause a crash during the lookup. If
396          * we see the request is completed (based on the value of the
397          * old engine and seqno), the lookup is complete and reports NULL.
398          * If we decide the request is not completed (new engine or seqno),
399          * then we grab a reference and double check that it is still the
400          * active request - which it won't be and restart the lookup.
401          *
402          * Do not use kmem_cache_zalloc() here!
403          */
404         req = kmem_cache_alloc(dev_priv->requests, GFP_KERNEL);
405         if (!req)
406                 return ERR_PTR(-ENOMEM);
407
408         ret = i915_gem_get_global_seqno(dev_priv, &seqno);
409         if (ret)
410                 goto err;
411
412         req->timeline = engine->timeline;
413
414         spin_lock_init(&req->lock);
415         dma_fence_init(&req->fence,
416                        &i915_fence_ops,
417                        &req->lock,
418                        req->timeline->fence_context,
419                        seqno);
420
421         i915_sw_fence_init(&req->submit, submit_notify);
422
423         INIT_LIST_HEAD(&req->active_list);
424         req->i915 = dev_priv;
425         req->engine = engine;
426         req->global_seqno = seqno;
427         req->ctx = i915_gem_context_get(ctx);
428
429         /* No zalloc, must clear what we need by hand */
430         req->previous_context = NULL;
431         req->file_priv = NULL;
432         req->batch = NULL;
433
434         /*
435          * Reserve space in the ring buffer for all the commands required to
436          * eventually emit this request. This is to guarantee that the
437          * i915_add_request() call can't fail. Note that the reserve may need
438          * to be redone if the request is not actually submitted straight
439          * away, e.g. because a GPU scheduler has deferred it.
440          */
441         req->reserved_space = MIN_SPACE_FOR_ADD_REQUEST;
442         GEM_BUG_ON(req->reserved_space < engine->emit_breadcrumb_sz);
443
444         if (i915.enable_execlists)
445                 ret = intel_logical_ring_alloc_request_extras(req);
446         else
447                 ret = intel_ring_alloc_request_extras(req);
448         if (ret)
449                 goto err_ctx;
450
451         /* Record the position of the start of the request so that
452          * should we detect the updated seqno part-way through the
453          * GPU processing the request, we never over-estimate the
454          * position of the head.
455          */
456         req->head = req->ring->tail;
457
458         return req;
459
460 err_ctx:
461         i915_gem_context_put(ctx);
462 err:
463         kmem_cache_free(dev_priv->requests, req);
464         return ERR_PTR(ret);
465 }
466
467 static int
468 i915_gem_request_await_request(struct drm_i915_gem_request *to,
469                                struct drm_i915_gem_request *from)
470 {
471         int ret;
472
473         GEM_BUG_ON(to == from);
474
475         if (to->timeline == from->timeline)
476                 return 0;
477
478         if (to->engine == from->engine) {
479                 ret = i915_sw_fence_await_sw_fence_gfp(&to->submit,
480                                                        &from->submit,
481                                                        GFP_KERNEL);
482                 return ret < 0 ? ret : 0;
483         }
484
485         if (!from->global_seqno) {
486                 ret = i915_sw_fence_await_dma_fence(&to->submit,
487                                                     &from->fence, 0,
488                                                     GFP_KERNEL);
489                 return ret < 0 ? ret : 0;
490         }
491
492         if (from->global_seqno <= to->timeline->sync_seqno[from->engine->id])
493                 return 0;
494
495         trace_i915_gem_ring_sync_to(to, from);
496         if (!i915.semaphores) {
497                 if (!i915_spin_request(from, TASK_INTERRUPTIBLE, 2)) {
498                         ret = i915_sw_fence_await_dma_fence(&to->submit,
499                                                             &from->fence, 0,
500                                                             GFP_KERNEL);
501                         if (ret < 0)
502                                 return ret;
503                 }
504         } else {
505                 ret = to->engine->semaphore.sync_to(to, from);
506                 if (ret)
507                         return ret;
508         }
509
510         to->timeline->sync_seqno[from->engine->id] = from->global_seqno;
511         return 0;
512 }
513
514 int
515 i915_gem_request_await_dma_fence(struct drm_i915_gem_request *req,
516                                  struct dma_fence *fence)
517 {
518         struct dma_fence_array *array;
519         int ret;
520         int i;
521
522         if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
523                 return 0;
524
525         if (dma_fence_is_i915(fence))
526                 return i915_gem_request_await_request(req, to_request(fence));
527
528         if (!dma_fence_is_array(fence)) {
529                 ret = i915_sw_fence_await_dma_fence(&req->submit,
530                                                     fence, I915_FENCE_TIMEOUT,
531                                                     GFP_KERNEL);
532                 return ret < 0 ? ret : 0;
533         }
534
535         /* Note that if the fence-array was created in signal-on-any mode,
536          * we should *not* decompose it into its individual fences. However,
537          * we don't currently store which mode the fence-array is operating
538          * in. Fortunately, the only user of signal-on-any is private to
539          * amdgpu and we should not see any incoming fence-array from
540          * sync-file being in signal-on-any mode.
541          */
542
543         array = to_dma_fence_array(fence);
544         for (i = 0; i < array->num_fences; i++) {
545                 struct dma_fence *child = array->fences[i];
546
547                 if (dma_fence_is_i915(child))
548                         ret = i915_gem_request_await_request(req,
549                                                              to_request(child));
550                 else
551                         ret = i915_sw_fence_await_dma_fence(&req->submit,
552                                                             child, I915_FENCE_TIMEOUT,
553                                                             GFP_KERNEL);
554                 if (ret < 0)
555                         return ret;
556         }
557
558         return 0;
559 }
560
561 /**
562  * i915_gem_request_await_object - set this request to (async) wait upon a bo
563  *
564  * @to: request we are wishing to use
565  * @obj: object which may be in use on another ring.
566  *
567  * This code is meant to abstract object synchronization with the GPU.
568  * Conceptually we serialise writes between engines inside the GPU.
569  * We only allow one engine to write into a buffer at any time, but
570  * multiple readers. To ensure each has a coherent view of memory, we must:
571  *
572  * - If there is an outstanding write request to the object, the new
573  *   request must wait for it to complete (either CPU or in hw, requests
574  *   on the same ring will be naturally ordered).
575  *
576  * - If we are a write request (pending_write_domain is set), the new
577  *   request must wait for outstanding read requests to complete.
578  *
579  * Returns 0 if successful, else propagates up the lower layer error.
580  */
581 int
582 i915_gem_request_await_object(struct drm_i915_gem_request *to,
583                               struct drm_i915_gem_object *obj,
584                               bool write)
585 {
586         struct dma_fence *excl;
587         int ret = 0;
588
589         if (write) {
590                 struct dma_fence **shared;
591                 unsigned int count, i;
592
593                 ret = reservation_object_get_fences_rcu(obj->resv,
594                                                         &excl, &count, &shared);
595                 if (ret)
596                         return ret;
597
598                 for (i = 0; i < count; i++) {
599                         ret = i915_gem_request_await_dma_fence(to, shared[i]);
600                         if (ret)
601                                 break;
602
603                         dma_fence_put(shared[i]);
604                 }
605
606                 for (; i < count; i++)
607                         dma_fence_put(shared[i]);
608                 kfree(shared);
609         } else {
610                 excl = reservation_object_get_excl_rcu(obj->resv);
611         }
612
613         if (excl) {
614                 if (ret == 0)
615                         ret = i915_gem_request_await_dma_fence(to, excl);
616
617                 dma_fence_put(excl);
618         }
619
620         return ret;
621 }
622
623 static void i915_gem_mark_busy(const struct intel_engine_cs *engine)
624 {
625         struct drm_i915_private *dev_priv = engine->i915;
626
627         dev_priv->gt.active_engines |= intel_engine_flag(engine);
628         if (dev_priv->gt.awake)
629                 return;
630
631         intel_runtime_pm_get_noresume(dev_priv);
632         dev_priv->gt.awake = true;
633
634         intel_enable_gt_powersave(dev_priv);
635         i915_update_gfx_val(dev_priv);
636         if (INTEL_GEN(dev_priv) >= 6)
637                 gen6_rps_busy(dev_priv);
638
639         queue_delayed_work(dev_priv->wq,
640                            &dev_priv->gt.retire_work,
641                            round_jiffies_up_relative(HZ));
642 }
643
644 /*
645  * NB: This function is not allowed to fail. Doing so would mean the the
646  * request is not being tracked for completion but the work itself is
647  * going to happen on the hardware. This would be a Bad Thing(tm).
648  */
649 void __i915_add_request(struct drm_i915_gem_request *request, bool flush_caches)
650 {
651         struct intel_engine_cs *engine = request->engine;
652         struct intel_ring *ring = request->ring;
653         struct intel_timeline *timeline = request->timeline;
654         struct drm_i915_gem_request *prev;
655         int err;
656
657         lockdep_assert_held(&request->i915->drm.struct_mutex);
658         trace_i915_gem_request_add(request);
659
660         /*
661          * To ensure that this call will not fail, space for its emissions
662          * should already have been reserved in the ring buffer. Let the ring
663          * know that it is time to use that space up.
664          */
665         request->reserved_space = 0;
666
667         /*
668          * Emit any outstanding flushes - execbuf can fail to emit the flush
669          * after having emitted the batchbuffer command. Hence we need to fix
670          * things up similar to emitting the lazy request. The difference here
671          * is that the flush _must_ happen before the next request, no matter
672          * what.
673          */
674         if (flush_caches) {
675                 err = engine->emit_flush(request, EMIT_FLUSH);
676
677                 /* Not allowed to fail! */
678                 WARN(err, "engine->emit_flush() failed: %d!\n", err);
679         }
680
681         /* Record the position of the start of the breadcrumb so that
682          * should we detect the updated seqno part-way through the
683          * GPU processing the request, we never over-estimate the
684          * position of the ring's HEAD.
685          */
686         err = intel_ring_begin(request, engine->emit_breadcrumb_sz);
687         GEM_BUG_ON(err);
688         request->postfix = ring->tail;
689         ring->tail += engine->emit_breadcrumb_sz * sizeof(u32);
690
691         /* Seal the request and mark it as pending execution. Note that
692          * we may inspect this state, without holding any locks, during
693          * hangcheck. Hence we apply the barrier to ensure that we do not
694          * see a more recent value in the hws than we are tracking.
695          */
696
697         prev = i915_gem_active_raw(&timeline->last_request,
698                                    &request->i915->drm.struct_mutex);
699         if (prev)
700                 i915_sw_fence_await_sw_fence(&request->submit, &prev->submit,
701                                              &request->submitq);
702
703         request->emitted_jiffies = jiffies;
704         request->previous_seqno = timeline->last_pending_seqno;
705         timeline->last_pending_seqno = request->fence.seqno;
706         i915_gem_active_set(&timeline->last_request, request);
707         list_add_tail(&request->link, &timeline->requests);
708         list_add_tail(&request->ring_link, &ring->request_list);
709
710         i915_gem_mark_busy(engine);
711
712         local_bh_disable();
713         i915_sw_fence_commit(&request->submit);
714         local_bh_enable(); /* Kick the execlists tasklet if just scheduled */
715 }
716
717 static void reset_wait_queue(wait_queue_head_t *q, wait_queue_t *wait)
718 {
719         unsigned long flags;
720
721         spin_lock_irqsave(&q->lock, flags);
722         if (list_empty(&wait->task_list))
723                 __add_wait_queue(q, wait);
724         spin_unlock_irqrestore(&q->lock, flags);
725 }
726
727 static unsigned long local_clock_us(unsigned int *cpu)
728 {
729         unsigned long t;
730
731         /* Cheaply and approximately convert from nanoseconds to microseconds.
732          * The result and subsequent calculations are also defined in the same
733          * approximate microseconds units. The principal source of timing
734          * error here is from the simple truncation.
735          *
736          * Note that local_clock() is only defined wrt to the current CPU;
737          * the comparisons are no longer valid if we switch CPUs. Instead of
738          * blocking preemption for the entire busywait, we can detect the CPU
739          * switch and use that as indicator of system load and a reason to
740          * stop busywaiting, see busywait_stop().
741          */
742         *cpu = get_cpu();
743         t = local_clock() >> 10;
744         put_cpu();
745
746         return t;
747 }
748
749 static bool busywait_stop(unsigned long timeout, unsigned int cpu)
750 {
751         unsigned int this_cpu;
752
753         if (time_after(local_clock_us(&this_cpu), timeout))
754                 return true;
755
756         return this_cpu != cpu;
757 }
758
759 bool __i915_spin_request(const struct drm_i915_gem_request *req,
760                          int state, unsigned long timeout_us)
761 {
762         unsigned int cpu;
763
764         /* When waiting for high frequency requests, e.g. during synchronous
765          * rendering split between the CPU and GPU, the finite amount of time
766          * required to set up the irq and wait upon it limits the response
767          * rate. By busywaiting on the request completion for a short while we
768          * can service the high frequency waits as quick as possible. However,
769          * if it is a slow request, we want to sleep as quickly as possible.
770          * The tradeoff between waiting and sleeping is roughly the time it
771          * takes to sleep on a request, on the order of a microsecond.
772          */
773
774         timeout_us += local_clock_us(&cpu);
775         do {
776                 if (__i915_gem_request_completed(req))
777                         return true;
778
779                 if (signal_pending_state(state, current))
780                         break;
781
782                 if (busywait_stop(timeout_us, cpu))
783                         break;
784
785                 cpu_relax_lowlatency();
786         } while (!need_resched());
787
788         return false;
789 }
790
791 static long
792 __i915_request_wait_for_submit(struct drm_i915_gem_request *request,
793                                unsigned int flags,
794                                long timeout)
795 {
796         const int state = flags & I915_WAIT_INTERRUPTIBLE ?
797                 TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE;
798         wait_queue_head_t *q = &request->i915->gpu_error.wait_queue;
799         DEFINE_WAIT(reset);
800         DEFINE_WAIT(wait);
801
802         if (flags & I915_WAIT_LOCKED)
803                 add_wait_queue(q, &reset);
804
805         do {
806                 prepare_to_wait(&request->submit.wait, &wait, state);
807
808                 if (i915_sw_fence_done(&request->submit))
809                         break;
810
811                 if (flags & I915_WAIT_LOCKED &&
812                     i915_reset_in_progress(&request->i915->gpu_error)) {
813                         __set_current_state(TASK_RUNNING);
814                         i915_reset(request->i915);
815                         reset_wait_queue(q, &reset);
816                         continue;
817                 }
818
819                 if (signal_pending_state(state, current)) {
820                         timeout = -ERESTARTSYS;
821                         break;
822                 }
823
824                 timeout = io_schedule_timeout(timeout);
825         } while (timeout);
826         finish_wait(&request->submit.wait, &wait);
827
828         if (flags & I915_WAIT_LOCKED)
829                 remove_wait_queue(q, &reset);
830
831         return timeout;
832 }
833
834 /**
835  * i915_wait_request - wait until execution of request has finished
836  * @req: the request to wait upon
837  * @flags: how to wait
838  * @timeout: how long to wait in jiffies
839  *
840  * i915_wait_request() waits for the request to be completed, for a
841  * maximum of @timeout jiffies (with MAX_SCHEDULE_TIMEOUT implying an
842  * unbounded wait).
843  *
844  * If the caller holds the struct_mutex, the caller must pass I915_WAIT_LOCKED
845  * in via the flags, and vice versa if the struct_mutex is not held, the caller
846  * must not specify that the wait is locked.
847  *
848  * Returns the remaining time (in jiffies) if the request completed, which may
849  * be zero or -ETIME if the request is unfinished after the timeout expires.
850  * May return -EINTR is called with I915_WAIT_INTERRUPTIBLE and a signal is
851  * pending before the request completes.
852  */
853 long i915_wait_request(struct drm_i915_gem_request *req,
854                        unsigned int flags,
855                        long timeout)
856 {
857         const int state = flags & I915_WAIT_INTERRUPTIBLE ?
858                 TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE;
859         DEFINE_WAIT(reset);
860         struct intel_wait wait;
861
862         might_sleep();
863 #if IS_ENABLED(CONFIG_LOCKDEP)
864         GEM_BUG_ON(debug_locks &&
865                    !!lockdep_is_held(&req->i915->drm.struct_mutex) !=
866                    !!(flags & I915_WAIT_LOCKED));
867 #endif
868         GEM_BUG_ON(timeout < 0);
869
870         if (i915_gem_request_completed(req))
871                 return timeout;
872
873         if (!timeout)
874                 return -ETIME;
875
876         trace_i915_gem_request_wait_begin(req);
877
878         if (!i915_sw_fence_done(&req->submit)) {
879                 timeout = __i915_request_wait_for_submit(req, flags, timeout);
880                 if (timeout < 0)
881                         goto complete;
882
883                 GEM_BUG_ON(!i915_sw_fence_done(&req->submit));
884         }
885         GEM_BUG_ON(!req->global_seqno);
886
887         /* Optimistic short spin before touching IRQs */
888         if (i915_spin_request(req, state, 5))
889                 goto complete;
890
891         set_current_state(state);
892         if (flags & I915_WAIT_LOCKED)
893                 add_wait_queue(&req->i915->gpu_error.wait_queue, &reset);
894
895         intel_wait_init(&wait, req->global_seqno);
896         if (intel_engine_add_wait(req->engine, &wait))
897                 /* In order to check that we haven't missed the interrupt
898                  * as we enabled it, we need to kick ourselves to do a
899                  * coherent check on the seqno before we sleep.
900                  */
901                 goto wakeup;
902
903         for (;;) {
904                 if (signal_pending_state(state, current)) {
905                         timeout = -ERESTARTSYS;
906                         break;
907                 }
908
909                 if (!timeout) {
910                         timeout = -ETIME;
911                         break;
912                 }
913
914                 timeout = io_schedule_timeout(timeout);
915
916                 if (intel_wait_complete(&wait))
917                         break;
918
919                 set_current_state(state);
920
921 wakeup:
922                 /* Carefully check if the request is complete, giving time
923                  * for the seqno to be visible following the interrupt.
924                  * We also have to check in case we are kicked by the GPU
925                  * reset in order to drop the struct_mutex.
926                  */
927                 if (__i915_request_irq_complete(req))
928                         break;
929
930                 /* If the GPU is hung, and we hold the lock, reset the GPU
931                  * and then check for completion. On a full reset, the engine's
932                  * HW seqno will be advanced passed us and we are complete.
933                  * If we do a partial reset, we have to wait for the GPU to
934                  * resume and update the breadcrumb.
935                  *
936                  * If we don't hold the mutex, we can just wait for the worker
937                  * to come along and update the breadcrumb (either directly
938                  * itself, or indirectly by recovering the GPU).
939                  */
940                 if (flags & I915_WAIT_LOCKED &&
941                     i915_reset_in_progress(&req->i915->gpu_error)) {
942                         __set_current_state(TASK_RUNNING);
943                         i915_reset(req->i915);
944                         reset_wait_queue(&req->i915->gpu_error.wait_queue,
945                                          &reset);
946                         continue;
947                 }
948
949                 /* Only spin if we know the GPU is processing this request */
950                 if (i915_spin_request(req, state, 2))
951                         break;
952         }
953
954         intel_engine_remove_wait(req->engine, &wait);
955         if (flags & I915_WAIT_LOCKED)
956                 remove_wait_queue(&req->i915->gpu_error.wait_queue, &reset);
957         __set_current_state(TASK_RUNNING);
958
959 complete:
960         trace_i915_gem_request_wait_end(req);
961
962         return timeout;
963 }
964
965 static bool engine_retire_requests(struct intel_engine_cs *engine)
966 {
967         struct drm_i915_gem_request *request, *next;
968
969         list_for_each_entry_safe(request, next,
970                                  &engine->timeline->requests, link) {
971                 if (!i915_gem_request_completed(request))
972                         return false;
973
974                 i915_gem_request_retire(request);
975         }
976
977         return true;
978 }
979
980 void i915_gem_retire_requests(struct drm_i915_private *dev_priv)
981 {
982         struct intel_engine_cs *engine;
983         unsigned int tmp;
984
985         lockdep_assert_held(&dev_priv->drm.struct_mutex);
986
987         if (dev_priv->gt.active_engines == 0)
988                 return;
989
990         GEM_BUG_ON(!dev_priv->gt.awake);
991
992         for_each_engine_masked(engine, dev_priv, dev_priv->gt.active_engines, tmp)
993                 if (engine_retire_requests(engine))
994                         dev_priv->gt.active_engines &= ~intel_engine_flag(engine);
995
996         if (dev_priv->gt.active_engines == 0)
997                 queue_delayed_work(dev_priv->wq,
998                                    &dev_priv->gt.idle_work,
999                                    msecs_to_jiffies(100));
1000 }