Merge tag 'm68k-for-v4.20-tag1' of git://git.kernel.org/pub/scm/linux/kernel/git...
[linux-2.6-block.git] / drivers / gpu / drm / i915 / i915_gem_context.c
1 /*
2  * Copyright © 2011-2012 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  * Authors:
24  *    Ben Widawsky <ben@bwidawsk.net>
25  *
26  */
27
28 /*
29  * This file implements HW context support. On gen5+ a HW context consists of an
30  * opaque GPU object which is referenced at times of context saves and restores.
31  * With RC6 enabled, the context is also referenced as the GPU enters and exists
32  * from RC6 (GPU has it's own internal power context, except on gen5). Though
33  * something like a context does exist for the media ring, the code only
34  * supports contexts for the render ring.
35  *
36  * In software, there is a distinction between contexts created by the user,
37  * and the default HW context. The default HW context is used by GPU clients
38  * that do not request setup of their own hardware context. The default
39  * context's state is never restored to help prevent programming errors. This
40  * would happen if a client ran and piggy-backed off another clients GPU state.
41  * The default context only exists to give the GPU some offset to load as the
42  * current to invoke a save of the context we actually care about. In fact, the
43  * code could likely be constructed, albeit in a more complicated fashion, to
44  * never use the default context, though that limits the driver's ability to
45  * swap out, and/or destroy other contexts.
46  *
47  * All other contexts are created as a request by the GPU client. These contexts
48  * store GPU state, and thus allow GPU clients to not re-emit state (and
49  * potentially query certain state) at any time. The kernel driver makes
50  * certain that the appropriate commands are inserted.
51  *
52  * The context life cycle is semi-complicated in that context BOs may live
53  * longer than the context itself because of the way the hardware, and object
54  * tracking works. Below is a very crude representation of the state machine
55  * describing the context life.
56  *                                         refcount     pincount     active
57  * S0: initial state                          0            0           0
58  * S1: context created                        1            0           0
59  * S2: context is currently running           2            1           X
60  * S3: GPU referenced, but not current        2            0           1
61  * S4: context is current, but destroyed      1            1           0
62  * S5: like S3, but destroyed                 1            0           1
63  *
64  * The most common (but not all) transitions:
65  * S0->S1: client creates a context
66  * S1->S2: client submits execbuf with context
67  * S2->S3: other clients submits execbuf with context
68  * S3->S1: context object was retired
69  * S3->S2: clients submits another execbuf
70  * S2->S4: context destroy called with current context
71  * S3->S5->S0: destroy path
72  * S4->S5->S0: destroy path on current context
73  *
74  * There are two confusing terms used above:
75  *  The "current context" means the context which is currently running on the
76  *  GPU. The GPU has loaded its state already and has stored away the gtt
77  *  offset of the BO. The GPU is not actively referencing the data at this
78  *  offset, but it will on the next context switch. The only way to avoid this
79  *  is to do a GPU reset.
80  *
81  *  An "active context' is one which was previously the "current context" and is
82  *  on the active list waiting for the next context switch to occur. Until this
83  *  happens, the object must remain at the same gtt offset. It is therefore
84  *  possible to destroy a context, but it is still active.
85  *
86  */
87
88 #include <linux/log2.h>
89 #include <drm/drmP.h>
90 #include <drm/i915_drm.h>
91 #include "i915_drv.h"
92 #include "i915_trace.h"
93 #include "intel_workarounds.h"
94
95 #define ALL_L3_SLICES(dev) (1 << NUM_L3_SLICES(dev)) - 1
96
97 static void lut_close(struct i915_gem_context *ctx)
98 {
99         struct i915_lut_handle *lut, *ln;
100         struct radix_tree_iter iter;
101         void __rcu **slot;
102
103         list_for_each_entry_safe(lut, ln, &ctx->handles_list, ctx_link) {
104                 list_del(&lut->obj_link);
105                 kmem_cache_free(ctx->i915->luts, lut);
106         }
107
108         rcu_read_lock();
109         radix_tree_for_each_slot(slot, &ctx->handles_vma, &iter, 0) {
110                 struct i915_vma *vma = rcu_dereference_raw(*slot);
111
112                 radix_tree_iter_delete(&ctx->handles_vma, &iter, slot);
113                 __i915_gem_object_release_unless_active(vma->obj);
114         }
115         rcu_read_unlock();
116 }
117
118 static inline int new_hw_id(struct drm_i915_private *i915, gfp_t gfp)
119 {
120         unsigned int max;
121
122         lockdep_assert_held(&i915->contexts.mutex);
123
124         if (INTEL_GEN(i915) >= 11)
125                 max = GEN11_MAX_CONTEXT_HW_ID;
126         else if (USES_GUC_SUBMISSION(i915))
127                 /*
128                  * When using GuC in proxy submission, GuC consumes the
129                  * highest bit in the context id to indicate proxy submission.
130                  */
131                 max = MAX_GUC_CONTEXT_HW_ID;
132         else
133                 max = MAX_CONTEXT_HW_ID;
134
135         return ida_simple_get(&i915->contexts.hw_ida, 0, max, gfp);
136 }
137
138 static int steal_hw_id(struct drm_i915_private *i915)
139 {
140         struct i915_gem_context *ctx, *cn;
141         LIST_HEAD(pinned);
142         int id = -ENOSPC;
143
144         lockdep_assert_held(&i915->contexts.mutex);
145
146         list_for_each_entry_safe(ctx, cn,
147                                  &i915->contexts.hw_id_list, hw_id_link) {
148                 if (atomic_read(&ctx->hw_id_pin_count)) {
149                         list_move_tail(&ctx->hw_id_link, &pinned);
150                         continue;
151                 }
152
153                 GEM_BUG_ON(!ctx->hw_id); /* perma-pinned kernel context */
154                 list_del_init(&ctx->hw_id_link);
155                 id = ctx->hw_id;
156                 break;
157         }
158
159         /*
160          * Remember how far we got up on the last repossesion scan, so the
161          * list is kept in a "least recently scanned" order.
162          */
163         list_splice_tail(&pinned, &i915->contexts.hw_id_list);
164         return id;
165 }
166
167 static int assign_hw_id(struct drm_i915_private *i915, unsigned int *out)
168 {
169         int ret;
170
171         lockdep_assert_held(&i915->contexts.mutex);
172
173         /*
174          * We prefer to steal/stall ourselves and our users over that of the
175          * entire system. That may be a little unfair to our users, and
176          * even hurt high priority clients. The choice is whether to oomkill
177          * something else, or steal a context id.
178          */
179         ret = new_hw_id(i915, GFP_KERNEL | __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
180         if (unlikely(ret < 0)) {
181                 ret = steal_hw_id(i915);
182                 if (ret < 0) /* once again for the correct errno code */
183                         ret = new_hw_id(i915, GFP_KERNEL);
184                 if (ret < 0)
185                         return ret;
186         }
187
188         *out = ret;
189         return 0;
190 }
191
192 static void release_hw_id(struct i915_gem_context *ctx)
193 {
194         struct drm_i915_private *i915 = ctx->i915;
195
196         if (list_empty(&ctx->hw_id_link))
197                 return;
198
199         mutex_lock(&i915->contexts.mutex);
200         if (!list_empty(&ctx->hw_id_link)) {
201                 ida_simple_remove(&i915->contexts.hw_ida, ctx->hw_id);
202                 list_del_init(&ctx->hw_id_link);
203         }
204         mutex_unlock(&i915->contexts.mutex);
205 }
206
207 static void i915_gem_context_free(struct i915_gem_context *ctx)
208 {
209         unsigned int n;
210
211         lockdep_assert_held(&ctx->i915->drm.struct_mutex);
212         GEM_BUG_ON(!i915_gem_context_is_closed(ctx));
213
214         release_hw_id(ctx);
215         i915_ppgtt_put(ctx->ppgtt);
216
217         for (n = 0; n < ARRAY_SIZE(ctx->__engine); n++) {
218                 struct intel_context *ce = &ctx->__engine[n];
219
220                 if (ce->ops)
221                         ce->ops->destroy(ce);
222         }
223
224         kfree(ctx->name);
225         put_pid(ctx->pid);
226
227         list_del(&ctx->link);
228
229         kfree_rcu(ctx, rcu);
230 }
231
232 static void contexts_free(struct drm_i915_private *i915)
233 {
234         struct llist_node *freed = llist_del_all(&i915->contexts.free_list);
235         struct i915_gem_context *ctx, *cn;
236
237         lockdep_assert_held(&i915->drm.struct_mutex);
238
239         llist_for_each_entry_safe(ctx, cn, freed, free_link)
240                 i915_gem_context_free(ctx);
241 }
242
243 static void contexts_free_first(struct drm_i915_private *i915)
244 {
245         struct i915_gem_context *ctx;
246         struct llist_node *freed;
247
248         lockdep_assert_held(&i915->drm.struct_mutex);
249
250         freed = llist_del_first(&i915->contexts.free_list);
251         if (!freed)
252                 return;
253
254         ctx = container_of(freed, typeof(*ctx), free_link);
255         i915_gem_context_free(ctx);
256 }
257
258 static void contexts_free_worker(struct work_struct *work)
259 {
260         struct drm_i915_private *i915 =
261                 container_of(work, typeof(*i915), contexts.free_work);
262
263         mutex_lock(&i915->drm.struct_mutex);
264         contexts_free(i915);
265         mutex_unlock(&i915->drm.struct_mutex);
266 }
267
268 void i915_gem_context_release(struct kref *ref)
269 {
270         struct i915_gem_context *ctx = container_of(ref, typeof(*ctx), ref);
271         struct drm_i915_private *i915 = ctx->i915;
272
273         trace_i915_context_free(ctx);
274         if (llist_add(&ctx->free_link, &i915->contexts.free_list))
275                 queue_work(i915->wq, &i915->contexts.free_work);
276 }
277
278 static void context_close(struct i915_gem_context *ctx)
279 {
280         i915_gem_context_set_closed(ctx);
281
282         /*
283          * This context will never again be assinged to HW, so we can
284          * reuse its ID for the next context.
285          */
286         release_hw_id(ctx);
287
288         /*
289          * The LUT uses the VMA as a backpointer to unref the object,
290          * so we need to clear the LUT before we close all the VMA (inside
291          * the ppgtt).
292          */
293         lut_close(ctx);
294         if (ctx->ppgtt)
295                 i915_ppgtt_close(&ctx->ppgtt->vm);
296
297         ctx->file_priv = ERR_PTR(-EBADF);
298         i915_gem_context_put(ctx);
299 }
300
301 static u32 default_desc_template(const struct drm_i915_private *i915,
302                                  const struct i915_hw_ppgtt *ppgtt)
303 {
304         u32 address_mode;
305         u32 desc;
306
307         desc = GEN8_CTX_VALID | GEN8_CTX_PRIVILEGE;
308
309         address_mode = INTEL_LEGACY_32B_CONTEXT;
310         if (ppgtt && i915_vm_is_48bit(&ppgtt->vm))
311                 address_mode = INTEL_LEGACY_64B_CONTEXT;
312         desc |= address_mode << GEN8_CTX_ADDRESSING_MODE_SHIFT;
313
314         if (IS_GEN8(i915))
315                 desc |= GEN8_CTX_L3LLC_COHERENT;
316
317         /* TODO: WaDisableLiteRestore when we start using semaphore
318          * signalling between Command Streamers
319          * ring->ctx_desc_template |= GEN8_CTX_FORCE_RESTORE;
320          */
321
322         return desc;
323 }
324
325 static struct i915_gem_context *
326 __create_hw_context(struct drm_i915_private *dev_priv,
327                     struct drm_i915_file_private *file_priv)
328 {
329         struct i915_gem_context *ctx;
330         unsigned int n;
331         int ret;
332
333         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
334         if (ctx == NULL)
335                 return ERR_PTR(-ENOMEM);
336
337         kref_init(&ctx->ref);
338         list_add_tail(&ctx->link, &dev_priv->contexts.list);
339         ctx->i915 = dev_priv;
340         ctx->sched.priority = I915_PRIORITY_NORMAL;
341
342         for (n = 0; n < ARRAY_SIZE(ctx->__engine); n++) {
343                 struct intel_context *ce = &ctx->__engine[n];
344
345                 ce->gem_context = ctx;
346         }
347
348         INIT_RADIX_TREE(&ctx->handles_vma, GFP_KERNEL);
349         INIT_LIST_HEAD(&ctx->handles_list);
350         INIT_LIST_HEAD(&ctx->hw_id_link);
351
352         /* Default context will never have a file_priv */
353         ret = DEFAULT_CONTEXT_HANDLE;
354         if (file_priv) {
355                 ret = idr_alloc(&file_priv->context_idr, ctx,
356                                 DEFAULT_CONTEXT_HANDLE, 0, GFP_KERNEL);
357                 if (ret < 0)
358                         goto err_lut;
359         }
360         ctx->user_handle = ret;
361
362         ctx->file_priv = file_priv;
363         if (file_priv) {
364                 ctx->pid = get_task_pid(current, PIDTYPE_PID);
365                 ctx->name = kasprintf(GFP_KERNEL, "%s[%d]/%x",
366                                       current->comm,
367                                       pid_nr(ctx->pid),
368                                       ctx->user_handle);
369                 if (!ctx->name) {
370                         ret = -ENOMEM;
371                         goto err_pid;
372                 }
373         }
374
375         /* NB: Mark all slices as needing a remap so that when the context first
376          * loads it will restore whatever remap state already exists. If there
377          * is no remap info, it will be a NOP. */
378         ctx->remap_slice = ALL_L3_SLICES(dev_priv);
379
380         i915_gem_context_set_bannable(ctx);
381         ctx->ring_size = 4 * PAGE_SIZE;
382         ctx->desc_template =
383                 default_desc_template(dev_priv, dev_priv->mm.aliasing_ppgtt);
384
385         return ctx;
386
387 err_pid:
388         put_pid(ctx->pid);
389         idr_remove(&file_priv->context_idr, ctx->user_handle);
390 err_lut:
391         context_close(ctx);
392         return ERR_PTR(ret);
393 }
394
395 static void __destroy_hw_context(struct i915_gem_context *ctx,
396                                  struct drm_i915_file_private *file_priv)
397 {
398         idr_remove(&file_priv->context_idr, ctx->user_handle);
399         context_close(ctx);
400 }
401
402 static struct i915_gem_context *
403 i915_gem_create_context(struct drm_i915_private *dev_priv,
404                         struct drm_i915_file_private *file_priv)
405 {
406         struct i915_gem_context *ctx;
407
408         lockdep_assert_held(&dev_priv->drm.struct_mutex);
409
410         /* Reap the most stale context */
411         contexts_free_first(dev_priv);
412
413         ctx = __create_hw_context(dev_priv, file_priv);
414         if (IS_ERR(ctx))
415                 return ctx;
416
417         if (USES_FULL_PPGTT(dev_priv)) {
418                 struct i915_hw_ppgtt *ppgtt;
419
420                 ppgtt = i915_ppgtt_create(dev_priv, file_priv);
421                 if (IS_ERR(ppgtt)) {
422                         DRM_DEBUG_DRIVER("PPGTT setup failed (%ld)\n",
423                                          PTR_ERR(ppgtt));
424                         __destroy_hw_context(ctx, file_priv);
425                         return ERR_CAST(ppgtt);
426                 }
427
428                 ctx->ppgtt = ppgtt;
429                 ctx->desc_template = default_desc_template(dev_priv, ppgtt);
430         }
431
432         trace_i915_context_create(ctx);
433
434         return ctx;
435 }
436
437 /**
438  * i915_gem_context_create_gvt - create a GVT GEM context
439  * @dev: drm device *
440  *
441  * This function is used to create a GVT specific GEM context.
442  *
443  * Returns:
444  * pointer to i915_gem_context on success, error pointer if failed
445  *
446  */
447 struct i915_gem_context *
448 i915_gem_context_create_gvt(struct drm_device *dev)
449 {
450         struct i915_gem_context *ctx;
451         int ret;
452
453         if (!IS_ENABLED(CONFIG_DRM_I915_GVT))
454                 return ERR_PTR(-ENODEV);
455
456         ret = i915_mutex_lock_interruptible(dev);
457         if (ret)
458                 return ERR_PTR(ret);
459
460         ctx = __create_hw_context(to_i915(dev), NULL);
461         if (IS_ERR(ctx))
462                 goto out;
463
464         ctx->file_priv = ERR_PTR(-EBADF);
465         i915_gem_context_set_closed(ctx); /* not user accessible */
466         i915_gem_context_clear_bannable(ctx);
467         i915_gem_context_set_force_single_submission(ctx);
468         if (!USES_GUC_SUBMISSION(to_i915(dev)))
469                 ctx->ring_size = 512 * PAGE_SIZE; /* Max ring buffer size */
470
471         GEM_BUG_ON(i915_gem_context_is_kernel(ctx));
472 out:
473         mutex_unlock(&dev->struct_mutex);
474         return ctx;
475 }
476
477 static void
478 destroy_kernel_context(struct i915_gem_context **ctxp)
479 {
480         struct i915_gem_context *ctx;
481
482         /* Keep the context ref so that we can free it immediately ourselves */
483         ctx = i915_gem_context_get(fetch_and_zero(ctxp));
484         GEM_BUG_ON(!i915_gem_context_is_kernel(ctx));
485
486         context_close(ctx);
487         i915_gem_context_free(ctx);
488 }
489
490 struct i915_gem_context *
491 i915_gem_context_create_kernel(struct drm_i915_private *i915, int prio)
492 {
493         struct i915_gem_context *ctx;
494         int err;
495
496         ctx = i915_gem_create_context(i915, NULL);
497         if (IS_ERR(ctx))
498                 return ctx;
499
500         err = i915_gem_context_pin_hw_id(ctx);
501         if (err) {
502                 destroy_kernel_context(&ctx);
503                 return ERR_PTR(err);
504         }
505
506         i915_gem_context_clear_bannable(ctx);
507         ctx->sched.priority = prio;
508         ctx->ring_size = PAGE_SIZE;
509
510         GEM_BUG_ON(!i915_gem_context_is_kernel(ctx));
511
512         return ctx;
513 }
514
515 static void init_contexts(struct drm_i915_private *i915)
516 {
517         mutex_init(&i915->contexts.mutex);
518         INIT_LIST_HEAD(&i915->contexts.list);
519
520         /* Using the simple ida interface, the max is limited by sizeof(int) */
521         BUILD_BUG_ON(MAX_CONTEXT_HW_ID > INT_MAX);
522         BUILD_BUG_ON(GEN11_MAX_CONTEXT_HW_ID > INT_MAX);
523         ida_init(&i915->contexts.hw_ida);
524         INIT_LIST_HEAD(&i915->contexts.hw_id_list);
525
526         INIT_WORK(&i915->contexts.free_work, contexts_free_worker);
527         init_llist_head(&i915->contexts.free_list);
528 }
529
530 static bool needs_preempt_context(struct drm_i915_private *i915)
531 {
532         return HAS_LOGICAL_RING_PREEMPTION(i915);
533 }
534
535 int i915_gem_contexts_init(struct drm_i915_private *dev_priv)
536 {
537         struct i915_gem_context *ctx;
538         int ret;
539
540         /* Reassure ourselves we are only called once */
541         GEM_BUG_ON(dev_priv->kernel_context);
542         GEM_BUG_ON(dev_priv->preempt_context);
543
544         ret = intel_ctx_workarounds_init(dev_priv);
545         if (ret)
546                 return ret;
547
548         init_contexts(dev_priv);
549
550         /* lowest priority; idle task */
551         ctx = i915_gem_context_create_kernel(dev_priv, I915_PRIORITY_MIN);
552         if (IS_ERR(ctx)) {
553                 DRM_ERROR("Failed to create default global context\n");
554                 return PTR_ERR(ctx);
555         }
556         /*
557          * For easy recognisablity, we want the kernel context to be 0 and then
558          * all user contexts will have non-zero hw_id. Kernel contexts are
559          * permanently pinned, so that we never suffer a stall and can
560          * use them from any allocation context (e.g. for evicting other
561          * contexts and from inside the shrinker).
562          */
563         GEM_BUG_ON(ctx->hw_id);
564         GEM_BUG_ON(!atomic_read(&ctx->hw_id_pin_count));
565         dev_priv->kernel_context = ctx;
566
567         /* highest priority; preempting task */
568         if (needs_preempt_context(dev_priv)) {
569                 ctx = i915_gem_context_create_kernel(dev_priv, INT_MAX);
570                 if (!IS_ERR(ctx))
571                         dev_priv->preempt_context = ctx;
572                 else
573                         DRM_ERROR("Failed to create preempt context; disabling preemption\n");
574         }
575
576         DRM_DEBUG_DRIVER("%s context support initialized\n",
577                          DRIVER_CAPS(dev_priv)->has_logical_contexts ?
578                          "logical" : "fake");
579         return 0;
580 }
581
582 void i915_gem_contexts_lost(struct drm_i915_private *dev_priv)
583 {
584         struct intel_engine_cs *engine;
585         enum intel_engine_id id;
586
587         lockdep_assert_held(&dev_priv->drm.struct_mutex);
588
589         for_each_engine(engine, dev_priv, id)
590                 intel_engine_lost_context(engine);
591 }
592
593 void i915_gem_contexts_fini(struct drm_i915_private *i915)
594 {
595         lockdep_assert_held(&i915->drm.struct_mutex);
596
597         if (i915->preempt_context)
598                 destroy_kernel_context(&i915->preempt_context);
599         destroy_kernel_context(&i915->kernel_context);
600
601         /* Must free all deferred contexts (via flush_workqueue) first */
602         GEM_BUG_ON(!list_empty(&i915->contexts.hw_id_list));
603         ida_destroy(&i915->contexts.hw_ida);
604 }
605
606 static int context_idr_cleanup(int id, void *p, void *data)
607 {
608         struct i915_gem_context *ctx = p;
609
610         context_close(ctx);
611         return 0;
612 }
613
614 int i915_gem_context_open(struct drm_i915_private *i915,
615                           struct drm_file *file)
616 {
617         struct drm_i915_file_private *file_priv = file->driver_priv;
618         struct i915_gem_context *ctx;
619
620         idr_init(&file_priv->context_idr);
621
622         mutex_lock(&i915->drm.struct_mutex);
623         ctx = i915_gem_create_context(i915, file_priv);
624         mutex_unlock(&i915->drm.struct_mutex);
625         if (IS_ERR(ctx)) {
626                 idr_destroy(&file_priv->context_idr);
627                 return PTR_ERR(ctx);
628         }
629
630         GEM_BUG_ON(i915_gem_context_is_kernel(ctx));
631
632         return 0;
633 }
634
635 void i915_gem_context_close(struct drm_file *file)
636 {
637         struct drm_i915_file_private *file_priv = file->driver_priv;
638
639         lockdep_assert_held(&file_priv->dev_priv->drm.struct_mutex);
640
641         idr_for_each(&file_priv->context_idr, context_idr_cleanup, NULL);
642         idr_destroy(&file_priv->context_idr);
643 }
644
645 static struct i915_request *
646 last_request_on_engine(struct i915_timeline *timeline,
647                        struct intel_engine_cs *engine)
648 {
649         struct i915_request *rq;
650
651         GEM_BUG_ON(timeline == &engine->timeline);
652
653         rq = i915_gem_active_raw(&timeline->last_request,
654                                  &engine->i915->drm.struct_mutex);
655         if (rq && rq->engine == engine) {
656                 GEM_TRACE("last request for %s on engine %s: %llx:%d\n",
657                           timeline->name, engine->name,
658                           rq->fence.context, rq->fence.seqno);
659                 GEM_BUG_ON(rq->timeline != timeline);
660                 return rq;
661         }
662
663         return NULL;
664 }
665
666 static bool engine_has_kernel_context_barrier(struct intel_engine_cs *engine)
667 {
668         struct drm_i915_private *i915 = engine->i915;
669         const struct intel_context * const ce =
670                 to_intel_context(i915->kernel_context, engine);
671         struct i915_timeline *barrier = ce->ring->timeline;
672         struct intel_ring *ring;
673         bool any_active = false;
674
675         lockdep_assert_held(&i915->drm.struct_mutex);
676         list_for_each_entry(ring, &i915->gt.active_rings, active_link) {
677                 struct i915_request *rq;
678
679                 rq = last_request_on_engine(ring->timeline, engine);
680                 if (!rq)
681                         continue;
682
683                 any_active = true;
684
685                 if (rq->hw_context == ce)
686                         continue;
687
688                 /*
689                  * Was this request submitted after the previous
690                  * switch-to-kernel-context?
691                  */
692                 if (!i915_timeline_sync_is_later(barrier, &rq->fence)) {
693                         GEM_TRACE("%s needs barrier for %llx:%d\n",
694                                   ring->timeline->name,
695                                   rq->fence.context,
696                                   rq->fence.seqno);
697                         return false;
698                 }
699
700                 GEM_TRACE("%s has barrier after %llx:%d\n",
701                           ring->timeline->name,
702                           rq->fence.context,
703                           rq->fence.seqno);
704         }
705
706         /*
707          * If any other timeline was still active and behind the last barrier,
708          * then our last switch-to-kernel-context must still be queued and
709          * will run last (leaving the engine in the kernel context when it
710          * eventually idles).
711          */
712         if (any_active)
713                 return true;
714
715         /* The engine is idle; check that it is idling in the kernel context. */
716         return engine->last_retired_context == ce;
717 }
718
719 int i915_gem_switch_to_kernel_context(struct drm_i915_private *i915)
720 {
721         struct intel_engine_cs *engine;
722         enum intel_engine_id id;
723
724         GEM_TRACE("awake?=%s\n", yesno(i915->gt.awake));
725
726         lockdep_assert_held(&i915->drm.struct_mutex);
727         GEM_BUG_ON(!i915->kernel_context);
728
729         i915_retire_requests(i915);
730
731         for_each_engine(engine, i915, id) {
732                 struct intel_ring *ring;
733                 struct i915_request *rq;
734
735                 GEM_BUG_ON(!to_intel_context(i915->kernel_context, engine));
736                 if (engine_has_kernel_context_barrier(engine))
737                         continue;
738
739                 GEM_TRACE("emit barrier on %s\n", engine->name);
740
741                 rq = i915_request_alloc(engine, i915->kernel_context);
742                 if (IS_ERR(rq))
743                         return PTR_ERR(rq);
744
745                 /* Queue this switch after all other activity */
746                 list_for_each_entry(ring, &i915->gt.active_rings, active_link) {
747                         struct i915_request *prev;
748
749                         prev = last_request_on_engine(ring->timeline, engine);
750                         if (!prev)
751                                 continue;
752
753                         if (prev->gem_context == i915->kernel_context)
754                                 continue;
755
756                         GEM_TRACE("add barrier on %s for %llx:%d\n",
757                                   engine->name,
758                                   prev->fence.context,
759                                   prev->fence.seqno);
760                         i915_sw_fence_await_sw_fence_gfp(&rq->submit,
761                                                          &prev->submit,
762                                                          I915_FENCE_GFP);
763                         i915_timeline_sync_set(rq->timeline, &prev->fence);
764                 }
765
766                 i915_request_add(rq);
767         }
768
769         return 0;
770 }
771
772 static bool client_is_banned(struct drm_i915_file_private *file_priv)
773 {
774         return atomic_read(&file_priv->ban_score) >= I915_CLIENT_SCORE_BANNED;
775 }
776
777 int i915_gem_context_create_ioctl(struct drm_device *dev, void *data,
778                                   struct drm_file *file)
779 {
780         struct drm_i915_private *dev_priv = to_i915(dev);
781         struct drm_i915_gem_context_create *args = data;
782         struct drm_i915_file_private *file_priv = file->driver_priv;
783         struct i915_gem_context *ctx;
784         int ret;
785
786         if (!DRIVER_CAPS(dev_priv)->has_logical_contexts)
787                 return -ENODEV;
788
789         if (args->pad != 0)
790                 return -EINVAL;
791
792         if (client_is_banned(file_priv)) {
793                 DRM_DEBUG("client %s[%d] banned from creating ctx\n",
794                           current->comm,
795                           pid_nr(get_task_pid(current, PIDTYPE_PID)));
796
797                 return -EIO;
798         }
799
800         ret = i915_mutex_lock_interruptible(dev);
801         if (ret)
802                 return ret;
803
804         ctx = i915_gem_create_context(dev_priv, file_priv);
805         mutex_unlock(&dev->struct_mutex);
806         if (IS_ERR(ctx))
807                 return PTR_ERR(ctx);
808
809         GEM_BUG_ON(i915_gem_context_is_kernel(ctx));
810
811         args->ctx_id = ctx->user_handle;
812         DRM_DEBUG("HW context %d created\n", args->ctx_id);
813
814         return 0;
815 }
816
817 int i915_gem_context_destroy_ioctl(struct drm_device *dev, void *data,
818                                    struct drm_file *file)
819 {
820         struct drm_i915_gem_context_destroy *args = data;
821         struct drm_i915_file_private *file_priv = file->driver_priv;
822         struct i915_gem_context *ctx;
823         int ret;
824
825         if (args->pad != 0)
826                 return -EINVAL;
827
828         if (args->ctx_id == DEFAULT_CONTEXT_HANDLE)
829                 return -ENOENT;
830
831         ctx = i915_gem_context_lookup(file_priv, args->ctx_id);
832         if (!ctx)
833                 return -ENOENT;
834
835         ret = mutex_lock_interruptible(&dev->struct_mutex);
836         if (ret)
837                 goto out;
838
839         __destroy_hw_context(ctx, file_priv);
840         mutex_unlock(&dev->struct_mutex);
841
842 out:
843         i915_gem_context_put(ctx);
844         return 0;
845 }
846
847 int i915_gem_context_getparam_ioctl(struct drm_device *dev, void *data,
848                                     struct drm_file *file)
849 {
850         struct drm_i915_file_private *file_priv = file->driver_priv;
851         struct drm_i915_gem_context_param *args = data;
852         struct i915_gem_context *ctx;
853         int ret = 0;
854
855         ctx = i915_gem_context_lookup(file_priv, args->ctx_id);
856         if (!ctx)
857                 return -ENOENT;
858
859         args->size = 0;
860         switch (args->param) {
861         case I915_CONTEXT_PARAM_BAN_PERIOD:
862                 ret = -EINVAL;
863                 break;
864         case I915_CONTEXT_PARAM_NO_ZEROMAP:
865                 args->value = test_bit(UCONTEXT_NO_ZEROMAP, &ctx->user_flags);
866                 break;
867         case I915_CONTEXT_PARAM_GTT_SIZE:
868                 if (ctx->ppgtt)
869                         args->value = ctx->ppgtt->vm.total;
870                 else if (to_i915(dev)->mm.aliasing_ppgtt)
871                         args->value = to_i915(dev)->mm.aliasing_ppgtt->vm.total;
872                 else
873                         args->value = to_i915(dev)->ggtt.vm.total;
874                 break;
875         case I915_CONTEXT_PARAM_NO_ERROR_CAPTURE:
876                 args->value = i915_gem_context_no_error_capture(ctx);
877                 break;
878         case I915_CONTEXT_PARAM_BANNABLE:
879                 args->value = i915_gem_context_is_bannable(ctx);
880                 break;
881         case I915_CONTEXT_PARAM_PRIORITY:
882                 args->value = ctx->sched.priority;
883                 break;
884         default:
885                 ret = -EINVAL;
886                 break;
887         }
888
889         i915_gem_context_put(ctx);
890         return ret;
891 }
892
893 int i915_gem_context_setparam_ioctl(struct drm_device *dev, void *data,
894                                     struct drm_file *file)
895 {
896         struct drm_i915_file_private *file_priv = file->driver_priv;
897         struct drm_i915_gem_context_param *args = data;
898         struct i915_gem_context *ctx;
899         int ret = 0;
900
901         ctx = i915_gem_context_lookup(file_priv, args->ctx_id);
902         if (!ctx)
903                 return -ENOENT;
904
905         switch (args->param) {
906         case I915_CONTEXT_PARAM_BAN_PERIOD:
907                 ret = -EINVAL;
908                 break;
909         case I915_CONTEXT_PARAM_NO_ZEROMAP:
910                 if (args->size)
911                         ret = -EINVAL;
912                 else if (args->value)
913                         set_bit(UCONTEXT_NO_ZEROMAP, &ctx->user_flags);
914                 else
915                         clear_bit(UCONTEXT_NO_ZEROMAP, &ctx->user_flags);
916                 break;
917         case I915_CONTEXT_PARAM_NO_ERROR_CAPTURE:
918                 if (args->size)
919                         ret = -EINVAL;
920                 else if (args->value)
921                         i915_gem_context_set_no_error_capture(ctx);
922                 else
923                         i915_gem_context_clear_no_error_capture(ctx);
924                 break;
925         case I915_CONTEXT_PARAM_BANNABLE:
926                 if (args->size)
927                         ret = -EINVAL;
928                 else if (!capable(CAP_SYS_ADMIN) && !args->value)
929                         ret = -EPERM;
930                 else if (args->value)
931                         i915_gem_context_set_bannable(ctx);
932                 else
933                         i915_gem_context_clear_bannable(ctx);
934                 break;
935
936         case I915_CONTEXT_PARAM_PRIORITY:
937                 {
938                         s64 priority = args->value;
939
940                         if (args->size)
941                                 ret = -EINVAL;
942                         else if (!(to_i915(dev)->caps.scheduler & I915_SCHEDULER_CAP_PRIORITY))
943                                 ret = -ENODEV;
944                         else if (priority > I915_CONTEXT_MAX_USER_PRIORITY ||
945                                  priority < I915_CONTEXT_MIN_USER_PRIORITY)
946                                 ret = -EINVAL;
947                         else if (priority > I915_CONTEXT_DEFAULT_PRIORITY &&
948                                  !capable(CAP_SYS_NICE))
949                                 ret = -EPERM;
950                         else
951                                 ctx->sched.priority = priority;
952                 }
953                 break;
954
955         default:
956                 ret = -EINVAL;
957                 break;
958         }
959
960         i915_gem_context_put(ctx);
961         return ret;
962 }
963
964 int i915_gem_context_reset_stats_ioctl(struct drm_device *dev,
965                                        void *data, struct drm_file *file)
966 {
967         struct drm_i915_private *dev_priv = to_i915(dev);
968         struct drm_i915_reset_stats *args = data;
969         struct i915_gem_context *ctx;
970         int ret;
971
972         if (args->flags || args->pad)
973                 return -EINVAL;
974
975         ret = -ENOENT;
976         rcu_read_lock();
977         ctx = __i915_gem_context_lookup_rcu(file->driver_priv, args->ctx_id);
978         if (!ctx)
979                 goto out;
980
981         /*
982          * We opt for unserialised reads here. This may result in tearing
983          * in the extremely unlikely event of a GPU hang on this context
984          * as we are querying them. If we need that extra layer of protection,
985          * we should wrap the hangstats with a seqlock.
986          */
987
988         if (capable(CAP_SYS_ADMIN))
989                 args->reset_count = i915_reset_count(&dev_priv->gpu_error);
990         else
991                 args->reset_count = 0;
992
993         args->batch_active = atomic_read(&ctx->guilty_count);
994         args->batch_pending = atomic_read(&ctx->active_count);
995
996         ret = 0;
997 out:
998         rcu_read_unlock();
999         return ret;
1000 }
1001
1002 int __i915_gem_context_pin_hw_id(struct i915_gem_context *ctx)
1003 {
1004         struct drm_i915_private *i915 = ctx->i915;
1005         int err = 0;
1006
1007         mutex_lock(&i915->contexts.mutex);
1008
1009         GEM_BUG_ON(i915_gem_context_is_closed(ctx));
1010
1011         if (list_empty(&ctx->hw_id_link)) {
1012                 GEM_BUG_ON(atomic_read(&ctx->hw_id_pin_count));
1013
1014                 err = assign_hw_id(i915, &ctx->hw_id);
1015                 if (err)
1016                         goto out_unlock;
1017
1018                 list_add_tail(&ctx->hw_id_link, &i915->contexts.hw_id_list);
1019         }
1020
1021         GEM_BUG_ON(atomic_read(&ctx->hw_id_pin_count) == ~0u);
1022         atomic_inc(&ctx->hw_id_pin_count);
1023
1024 out_unlock:
1025         mutex_unlock(&i915->contexts.mutex);
1026         return err;
1027 }
1028
1029 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
1030 #include "selftests/mock_context.c"
1031 #include "selftests/i915_gem_context.c"
1032 #endif