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