]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/gpu/drm/i915/i915_gem_request.c
drm/i915: Combine seqno + tracking into a global timeline struct
[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 *dev_priv,
242                                       u32 seqno)
243 {
244         struct i915_gem_timeline *timeline = &dev_priv->gt.global_timeline;
245         struct intel_engine_cs *engine;
246         enum intel_engine_id id;
247         int ret;
248
249         /* Carefully retire all requests without writing to the rings */
250         ret = i915_gem_wait_for_idle(dev_priv,
251                                      I915_WAIT_INTERRUPTIBLE |
252                                      I915_WAIT_LOCKED);
253         if (ret)
254                 return ret;
255
256         i915_gem_retire_requests(dev_priv);
257
258         /* If the seqno wraps around, we need to clear the breadcrumb rbtree */
259         if (!i915_seqno_passed(seqno, timeline->next_seqno)) {
260                 while (intel_kick_waiters(dev_priv) ||
261                        intel_kick_signalers(dev_priv))
262                         yield();
263                 yield();
264         }
265
266         /* Finally reset hw state */
267         for_each_engine(engine, dev_priv, id)
268                 intel_engine_init_global_seqno(engine, seqno);
269
270         return 0;
271 }
272
273 int i915_gem_set_global_seqno(struct drm_device *dev, u32 seqno)
274 {
275         struct drm_i915_private *dev_priv = to_i915(dev);
276         int ret;
277
278         lockdep_assert_held(&dev_priv->drm.struct_mutex);
279
280         if (seqno == 0)
281                 return -EINVAL;
282
283         /* HWS page needs to be set less than what we
284          * will inject to ring
285          */
286         ret = i915_gem_init_global_seqno(dev_priv, seqno - 1);
287         if (ret)
288                 return ret;
289
290         dev_priv->gt.global_timeline.next_seqno = seqno;
291         return 0;
292 }
293
294 static int i915_gem_get_global_seqno(struct drm_i915_private *dev_priv,
295                                      u32 *seqno)
296 {
297         struct i915_gem_timeline *tl = &dev_priv->gt.global_timeline;
298
299         /* reserve 0 for non-seqno */
300         if (unlikely(tl->next_seqno == 0)) {
301                 int ret;
302
303                 ret = i915_gem_init_global_seqno(dev_priv, 0);
304                 if (ret)
305                         return ret;
306
307                 tl->next_seqno = 1;
308         }
309
310         *seqno = tl->next_seqno++;
311         return 0;
312 }
313
314 static int __i915_sw_fence_call
315 submit_notify(struct i915_sw_fence *fence, enum i915_sw_fence_notify state)
316 {
317         struct drm_i915_gem_request *request =
318                 container_of(fence, typeof(*request), submit);
319         struct intel_engine_cs *engine = request->engine;
320
321         /* Will be called from irq-context when using foreign DMA fences */
322
323         switch (state) {
324         case FENCE_COMPLETE:
325                 engine->timeline->last_submitted_seqno = request->fence.seqno;
326                 engine->submit_request(request);
327                 break;
328
329         case FENCE_FREE:
330                 break;
331         }
332
333         return NOTIFY_DONE;
334 }
335
336 /**
337  * i915_gem_request_alloc - allocate a request structure
338  *
339  * @engine: engine that we wish to issue the request on.
340  * @ctx: context that the request will be associated with.
341  *       This can be NULL if the request is not directly related to
342  *       any specific user context, in which case this function will
343  *       choose an appropriate context to use.
344  *
345  * Returns a pointer to the allocated request if successful,
346  * or an error code if not.
347  */
348 struct drm_i915_gem_request *
349 i915_gem_request_alloc(struct intel_engine_cs *engine,
350                        struct i915_gem_context *ctx)
351 {
352         struct drm_i915_private *dev_priv = engine->i915;
353         struct drm_i915_gem_request *req;
354         u32 seqno;
355         int ret;
356
357         /* ABI: Before userspace accesses the GPU (e.g. execbuffer), report
358          * EIO if the GPU is already wedged, or EAGAIN to drop the struct_mutex
359          * and restart.
360          */
361         ret = i915_gem_check_wedge(dev_priv);
362         if (ret)
363                 return ERR_PTR(ret);
364
365         /* Move the oldest request to the slab-cache (if not in use!) */
366         req = list_first_entry_or_null(&engine->timeline->requests,
367                                        typeof(*req), link);
368         if (req && i915_gem_request_completed(req))
369                 i915_gem_request_retire(req);
370
371         /* Beware: Dragons be flying overhead.
372          *
373          * We use RCU to look up requests in flight. The lookups may
374          * race with the request being allocated from the slab freelist.
375          * That is the request we are writing to here, may be in the process
376          * of being read by __i915_gem_active_get_rcu(). As such,
377          * we have to be very careful when overwriting the contents. During
378          * the RCU lookup, we change chase the request->engine pointer,
379          * read the request->fence.seqno and increment the reference count.
380          *
381          * The reference count is incremented atomically. If it is zero,
382          * the lookup knows the request is unallocated and complete. Otherwise,
383          * it is either still in use, or has been reallocated and reset
384          * with dma_fence_init(). This increment is safe for release as we
385          * check that the request we have a reference to and matches the active
386          * request.
387          *
388          * Before we increment the refcount, we chase the request->engine
389          * pointer. We must not call kmem_cache_zalloc() or else we set
390          * that pointer to NULL and cause a crash during the lookup. If
391          * we see the request is completed (based on the value of the
392          * old engine and seqno), the lookup is complete and reports NULL.
393          * If we decide the request is not completed (new engine or seqno),
394          * then we grab a reference and double check that it is still the
395          * active request - which it won't be and restart the lookup.
396          *
397          * Do not use kmem_cache_zalloc() here!
398          */
399         req = kmem_cache_alloc(dev_priv->requests, GFP_KERNEL);
400         if (!req)
401                 return ERR_PTR(-ENOMEM);
402
403         ret = i915_gem_get_global_seqno(dev_priv, &seqno);
404         if (ret)
405                 goto err;
406
407         req->timeline = engine->timeline;
408
409         spin_lock_init(&req->lock);
410         dma_fence_init(&req->fence,
411                        &i915_fence_ops,
412                        &req->lock,
413                        req->timeline->fence_context,
414                        seqno);
415
416         i915_sw_fence_init(&req->submit, submit_notify);
417
418         INIT_LIST_HEAD(&req->active_list);
419         req->i915 = dev_priv;
420         req->engine = engine;
421         req->ctx = i915_gem_context_get(ctx);
422
423         /* No zalloc, must clear what we need by hand */
424         req->previous_context = NULL;
425         req->file_priv = NULL;
426         req->batch = NULL;
427
428         /*
429          * Reserve space in the ring buffer for all the commands required to
430          * eventually emit this request. This is to guarantee that the
431          * i915_add_request() call can't fail. Note that the reserve may need
432          * to be redone if the request is not actually submitted straight
433          * away, e.g. because a GPU scheduler has deferred it.
434          */
435         req->reserved_space = MIN_SPACE_FOR_ADD_REQUEST;
436
437         if (i915.enable_execlists)
438                 ret = intel_logical_ring_alloc_request_extras(req);
439         else
440                 ret = intel_ring_alloc_request_extras(req);
441         if (ret)
442                 goto err_ctx;
443
444         /* Record the position of the start of the request so that
445          * should we detect the updated seqno part-way through the
446          * GPU processing the request, we never over-estimate the
447          * position of the head.
448          */
449         req->head = req->ring->tail;
450
451         return req;
452
453 err_ctx:
454         i915_gem_context_put(ctx);
455 err:
456         kmem_cache_free(dev_priv->requests, req);
457         return ERR_PTR(ret);
458 }
459
460 static int
461 i915_gem_request_await_request(struct drm_i915_gem_request *to,
462                                struct drm_i915_gem_request *from)
463 {
464         int idx, ret;
465
466         GEM_BUG_ON(to == from);
467
468         if (to->timeline == from->timeline)
469                 return 0;
470
471         if (to->engine == from->engine) {
472                 ret = i915_sw_fence_await_sw_fence_gfp(&to->submit,
473                                                        &from->submit,
474                                                        GFP_KERNEL);
475                 return ret < 0 ? ret : 0;
476         }
477
478         idx = intel_engine_sync_index(from->engine, to->engine);
479         if (from->fence.seqno <= from->engine->semaphore.sync_seqno[idx])
480                 return 0;
481
482         trace_i915_gem_ring_sync_to(to, from);
483         if (!i915.semaphores) {
484                 if (!i915_spin_request(from, TASK_INTERRUPTIBLE, 2)) {
485                         ret = i915_sw_fence_await_dma_fence(&to->submit,
486                                                             &from->fence, 0,
487                                                             GFP_KERNEL);
488                         if (ret < 0)
489                                 return ret;
490                 }
491         } else {
492                 ret = to->engine->semaphore.sync_to(to, from);
493                 if (ret)
494                         return ret;
495         }
496
497         from->engine->semaphore.sync_seqno[idx] = from->fence.seqno;
498         return 0;
499 }
500
501 int
502 i915_gem_request_await_dma_fence(struct drm_i915_gem_request *req,
503                                  struct dma_fence *fence)
504 {
505         struct dma_fence_array *array;
506         int ret;
507         int i;
508
509         if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
510                 return 0;
511
512         if (dma_fence_is_i915(fence))
513                 return i915_gem_request_await_request(req, to_request(fence));
514
515         if (!dma_fence_is_array(fence)) {
516                 ret = i915_sw_fence_await_dma_fence(&req->submit,
517                                                     fence, I915_FENCE_TIMEOUT,
518                                                     GFP_KERNEL);
519                 return ret < 0 ? ret : 0;
520         }
521
522         /* Note that if the fence-array was created in signal-on-any mode,
523          * we should *not* decompose it into its individual fences. However,
524          * we don't currently store which mode the fence-array is operating
525          * in. Fortunately, the only user of signal-on-any is private to
526          * amdgpu and we should not see any incoming fence-array from
527          * sync-file being in signal-on-any mode.
528          */
529
530         array = to_dma_fence_array(fence);
531         for (i = 0; i < array->num_fences; i++) {
532                 struct dma_fence *child = array->fences[i];
533
534                 if (dma_fence_is_i915(child))
535                         ret = i915_gem_request_await_request(req,
536                                                              to_request(child));
537                 else
538                         ret = i915_sw_fence_await_dma_fence(&req->submit,
539                                                             child, I915_FENCE_TIMEOUT,
540                                                             GFP_KERNEL);
541                 if (ret < 0)
542                         return ret;
543         }
544
545         return 0;
546 }
547
548 /**
549  * i915_gem_request_await_object - set this request to (async) wait upon a bo
550  *
551  * @to: request we are wishing to use
552  * @obj: object which may be in use on another ring.
553  *
554  * This code is meant to abstract object synchronization with the GPU.
555  * Conceptually we serialise writes between engines inside the GPU.
556  * We only allow one engine to write into a buffer at any time, but
557  * multiple readers. To ensure each has a coherent view of memory, we must:
558  *
559  * - If there is an outstanding write request to the object, the new
560  *   request must wait for it to complete (either CPU or in hw, requests
561  *   on the same ring will be naturally ordered).
562  *
563  * - If we are a write request (pending_write_domain is set), the new
564  *   request must wait for outstanding read requests to complete.
565  *
566  * Returns 0 if successful, else propagates up the lower layer error.
567  */
568 int
569 i915_gem_request_await_object(struct drm_i915_gem_request *to,
570                               struct drm_i915_gem_object *obj,
571                               bool write)
572 {
573         struct dma_fence *excl;
574         int ret = 0;
575
576         if (write) {
577                 struct dma_fence **shared;
578                 unsigned int count, i;
579
580                 ret = reservation_object_get_fences_rcu(obj->resv,
581                                                         &excl, &count, &shared);
582                 if (ret)
583                         return ret;
584
585                 for (i = 0; i < count; i++) {
586                         ret = i915_gem_request_await_dma_fence(to, shared[i]);
587                         if (ret)
588                                 break;
589
590                         dma_fence_put(shared[i]);
591                 }
592
593                 for (; i < count; i++)
594                         dma_fence_put(shared[i]);
595                 kfree(shared);
596         } else {
597                 excl = reservation_object_get_excl_rcu(obj->resv);
598         }
599
600         if (excl) {
601                 if (ret == 0)
602                         ret = i915_gem_request_await_dma_fence(to, excl);
603
604                 dma_fence_put(excl);
605         }
606
607         return ret;
608 }
609
610 static void i915_gem_mark_busy(const struct intel_engine_cs *engine)
611 {
612         struct drm_i915_private *dev_priv = engine->i915;
613
614         dev_priv->gt.active_engines |= intel_engine_flag(engine);
615         if (dev_priv->gt.awake)
616                 return;
617
618         intel_runtime_pm_get_noresume(dev_priv);
619         dev_priv->gt.awake = true;
620
621         intel_enable_gt_powersave(dev_priv);
622         i915_update_gfx_val(dev_priv);
623         if (INTEL_GEN(dev_priv) >= 6)
624                 gen6_rps_busy(dev_priv);
625
626         queue_delayed_work(dev_priv->wq,
627                            &dev_priv->gt.retire_work,
628                            round_jiffies_up_relative(HZ));
629 }
630
631 /*
632  * NB: This function is not allowed to fail. Doing so would mean the the
633  * request is not being tracked for completion but the work itself is
634  * going to happen on the hardware. This would be a Bad Thing(tm).
635  */
636 void __i915_add_request(struct drm_i915_gem_request *request, bool flush_caches)
637 {
638         struct intel_engine_cs *engine = request->engine;
639         struct intel_ring *ring = request->ring;
640         struct intel_timeline *timeline = request->timeline;
641         struct drm_i915_gem_request *prev;
642         u32 request_start;
643         u32 reserved_tail;
644         int ret;
645
646         lockdep_assert_held(&request->i915->drm.struct_mutex);
647         trace_i915_gem_request_add(request);
648
649         /*
650          * To ensure that this call will not fail, space for its emissions
651          * should already have been reserved in the ring buffer. Let the ring
652          * know that it is time to use that space up.
653          */
654         request_start = ring->tail;
655         reserved_tail = request->reserved_space;
656         request->reserved_space = 0;
657
658         /*
659          * Emit any outstanding flushes - execbuf can fail to emit the flush
660          * after having emitted the batchbuffer command. Hence we need to fix
661          * things up similar to emitting the lazy request. The difference here
662          * is that the flush _must_ happen before the next request, no matter
663          * what.
664          */
665         if (flush_caches) {
666                 ret = engine->emit_flush(request, EMIT_FLUSH);
667
668                 /* Not allowed to fail! */
669                 WARN(ret, "engine->emit_flush() failed: %d!\n", ret);
670         }
671
672         /* Record the position of the start of the breadcrumb so that
673          * should we detect the updated seqno part-way through the
674          * GPU processing the request, we never over-estimate the
675          * position of the ring's HEAD.
676          */
677         request->postfix = ring->tail;
678
679         /* Not allowed to fail! */
680         ret = engine->emit_request(request);
681         WARN(ret, "(%s)->emit_request failed: %d!\n", engine->name, ret);
682
683         /* Sanity check that the reserved size was large enough. */
684         ret = ring->tail - request_start;
685         if (ret < 0)
686                 ret += ring->size;
687         WARN_ONCE(ret > reserved_tail,
688                   "Not enough space reserved (%d bytes) "
689                   "for adding the request (%d bytes)\n",
690                   reserved_tail, ret);
691
692         /* Seal the request and mark it as pending execution. Note that
693          * we may inspect this state, without holding any locks, during
694          * hangcheck. Hence we apply the barrier to ensure that we do not
695          * see a more recent value in the hws than we are tracking.
696          */
697
698         prev = i915_gem_active_raw(&timeline->last_request,
699                                    &request->i915->drm.struct_mutex);
700         if (prev)
701                 i915_sw_fence_await_sw_fence(&request->submit, &prev->submit,
702                                              &request->submitq);
703
704         request->emitted_jiffies = jiffies;
705         request->previous_seqno = timeline->last_pending_seqno;
706         timeline->last_pending_seqno = request->fence.seqno;
707         i915_gem_active_set(&timeline->last_request, request);
708         list_add_tail(&request->link, &timeline->requests);
709         list_add_tail(&request->ring_link, &ring->request_list);
710
711         i915_gem_mark_busy(engine);
712
713         local_bh_disable();
714         i915_sw_fence_commit(&request->submit);
715         local_bh_enable(); /* Kick the execlists tasklet if just scheduled */
716 }
717
718 static void reset_wait_queue(wait_queue_head_t *q, wait_queue_t *wait)
719 {
720         unsigned long flags;
721
722         spin_lock_irqsave(&q->lock, flags);
723         if (list_empty(&wait->task_list))
724                 __add_wait_queue(q, wait);
725         spin_unlock_irqrestore(&q->lock, flags);
726 }
727
728 static unsigned long local_clock_us(unsigned int *cpu)
729 {
730         unsigned long t;
731
732         /* Cheaply and approximately convert from nanoseconds to microseconds.
733          * The result and subsequent calculations are also defined in the same
734          * approximate microseconds units. The principal source of timing
735          * error here is from the simple truncation.
736          *
737          * Note that local_clock() is only defined wrt to the current CPU;
738          * the comparisons are no longer valid if we switch CPUs. Instead of
739          * blocking preemption for the entire busywait, we can detect the CPU
740          * switch and use that as indicator of system load and a reason to
741          * stop busywaiting, see busywait_stop().
742          */
743         *cpu = get_cpu();
744         t = local_clock() >> 10;
745         put_cpu();
746
747         return t;
748 }
749
750 static bool busywait_stop(unsigned long timeout, unsigned int cpu)
751 {
752         unsigned int this_cpu;
753
754         if (time_after(local_clock_us(&this_cpu), timeout))
755                 return true;
756
757         return this_cpu != cpu;
758 }
759
760 bool __i915_spin_request(const struct drm_i915_gem_request *req,
761                          int state, unsigned long timeout_us)
762 {
763         unsigned int cpu;
764
765         /* When waiting for high frequency requests, e.g. during synchronous
766          * rendering split between the CPU and GPU, the finite amount of time
767          * required to set up the irq and wait upon it limits the response
768          * rate. By busywaiting on the request completion for a short while we
769          * can service the high frequency waits as quick as possible. However,
770          * if it is a slow request, we want to sleep as quickly as possible.
771          * The tradeoff between waiting and sleeping is roughly the time it
772          * takes to sleep on a request, on the order of a microsecond.
773          */
774
775         timeout_us += local_clock_us(&cpu);
776         do {
777                 if (i915_gem_request_completed(req))
778                         return true;
779
780                 if (signal_pending_state(state, current))
781                         break;
782
783                 if (busywait_stop(timeout_us, cpu))
784                         break;
785
786                 cpu_relax_lowlatency();
787         } while (!need_resched());
788
789         return false;
790 }
791
792 /**
793  * i915_wait_request - wait until execution of request has finished
794  * @req: the request to wait upon
795  * @flags: how to wait
796  * @timeout: how long to wait in jiffies
797  *
798  * i915_wait_request() waits for the request to be completed, for a
799  * maximum of @timeout jiffies (with MAX_SCHEDULE_TIMEOUT implying an
800  * unbounded wait).
801  *
802  * If the caller holds the struct_mutex, the caller must pass I915_WAIT_LOCKED
803  * in via the flags, and vice versa if the struct_mutex is not held, the caller
804  * must not specify that the wait is locked.
805  *
806  * Returns the remaining time (in jiffies) if the request completed, which may
807  * be zero or -ETIME if the request is unfinished after the timeout expires.
808  * May return -EINTR is called with I915_WAIT_INTERRUPTIBLE and a signal is
809  * pending before the request completes.
810  */
811 long i915_wait_request(struct drm_i915_gem_request *req,
812                        unsigned int flags,
813                        long timeout)
814 {
815         const int state = flags & I915_WAIT_INTERRUPTIBLE ?
816                 TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE;
817         DEFINE_WAIT(reset);
818         struct intel_wait wait;
819
820         might_sleep();
821 #if IS_ENABLED(CONFIG_LOCKDEP)
822         GEM_BUG_ON(debug_locks &&
823                    !!lockdep_is_held(&req->i915->drm.struct_mutex) !=
824                    !!(flags & I915_WAIT_LOCKED));
825 #endif
826         GEM_BUG_ON(timeout < 0);
827
828         if (i915_gem_request_completed(req))
829                 return timeout;
830
831         if (!timeout)
832                 return -ETIME;
833
834         trace_i915_gem_request_wait_begin(req);
835
836         /* Optimistic short spin before touching IRQs */
837         if (i915_spin_request(req, state, 5))
838                 goto complete;
839
840         set_current_state(state);
841         if (flags & I915_WAIT_LOCKED)
842                 add_wait_queue(&req->i915->gpu_error.wait_queue, &reset);
843
844         intel_wait_init(&wait, req->fence.seqno);
845         if (intel_engine_add_wait(req->engine, &wait))
846                 /* In order to check that we haven't missed the interrupt
847                  * as we enabled it, we need to kick ourselves to do a
848                  * coherent check on the seqno before we sleep.
849                  */
850                 goto wakeup;
851
852         for (;;) {
853                 if (signal_pending_state(state, current)) {
854                         timeout = -ERESTARTSYS;
855                         break;
856                 }
857
858                 if (!timeout) {
859                         timeout = -ETIME;
860                         break;
861                 }
862
863                 timeout = io_schedule_timeout(timeout);
864
865                 if (intel_wait_complete(&wait))
866                         break;
867
868                 set_current_state(state);
869
870 wakeup:
871                 /* Carefully check if the request is complete, giving time
872                  * for the seqno to be visible following the interrupt.
873                  * We also have to check in case we are kicked by the GPU
874                  * reset in order to drop the struct_mutex.
875                  */
876                 if (__i915_request_irq_complete(req))
877                         break;
878
879                 /* If the GPU is hung, and we hold the lock, reset the GPU
880                  * and then check for completion. On a full reset, the engine's
881                  * HW seqno will be advanced passed us and we are complete.
882                  * If we do a partial reset, we have to wait for the GPU to
883                  * resume and update the breadcrumb.
884                  *
885                  * If we don't hold the mutex, we can just wait for the worker
886                  * to come along and update the breadcrumb (either directly
887                  * itself, or indirectly by recovering the GPU).
888                  */
889                 if (flags & I915_WAIT_LOCKED &&
890                     i915_reset_in_progress(&req->i915->gpu_error)) {
891                         __set_current_state(TASK_RUNNING);
892                         i915_reset(req->i915);
893                         reset_wait_queue(&req->i915->gpu_error.wait_queue,
894                                          &reset);
895                         continue;
896                 }
897
898                 /* Only spin if we know the GPU is processing this request */
899                 if (i915_spin_request(req, state, 2))
900                         break;
901         }
902
903         intel_engine_remove_wait(req->engine, &wait);
904         if (flags & I915_WAIT_LOCKED)
905                 remove_wait_queue(&req->i915->gpu_error.wait_queue, &reset);
906         __set_current_state(TASK_RUNNING);
907
908 complete:
909         trace_i915_gem_request_wait_end(req);
910
911         return timeout;
912 }
913
914 static bool engine_retire_requests(struct intel_engine_cs *engine)
915 {
916         struct drm_i915_gem_request *request, *next;
917
918         list_for_each_entry_safe(request, next,
919                                  &engine->timeline->requests, link) {
920                 if (!i915_gem_request_completed(request))
921                         return false;
922
923                 i915_gem_request_retire(request);
924         }
925
926         return true;
927 }
928
929 void i915_gem_retire_requests(struct drm_i915_private *dev_priv)
930 {
931         struct intel_engine_cs *engine;
932         unsigned int tmp;
933
934         lockdep_assert_held(&dev_priv->drm.struct_mutex);
935
936         if (dev_priv->gt.active_engines == 0)
937                 return;
938
939         GEM_BUG_ON(!dev_priv->gt.awake);
940
941         for_each_engine_masked(engine, dev_priv, dev_priv->gt.active_engines, tmp)
942                 if (engine_retire_requests(engine))
943                         dev_priv->gt.active_engines &= ~intel_engine_flag(engine);
944
945         if (dev_priv->gt.active_engines == 0)
946                 queue_delayed_work(dev_priv->wq,
947                                    &dev_priv->gt.idle_work,
948                                    msecs_to_jiffies(100));
949 }