Merge tag 'drm-misc-next-2019-01-07-1' of git://anongit.freedesktop.org/drm/drm-misc...
[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_USER_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 (HAS_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 = i915_gem_create_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 = I915_USER_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
539         /* Reassure ourselves we are only called once */
540         GEM_BUG_ON(dev_priv->kernel_context);
541         GEM_BUG_ON(dev_priv->preempt_context);
542
543         intel_engine_init_ctx_wa(dev_priv->engine[RCS]);
544         init_contexts(dev_priv);
545
546         /* lowest priority; idle task */
547         ctx = i915_gem_context_create_kernel(dev_priv, I915_PRIORITY_MIN);
548         if (IS_ERR(ctx)) {
549                 DRM_ERROR("Failed to create default global context\n");
550                 return PTR_ERR(ctx);
551         }
552         /*
553          * For easy recognisablity, we want the kernel context to be 0 and then
554          * all user contexts will have non-zero hw_id. Kernel contexts are
555          * permanently pinned, so that we never suffer a stall and can
556          * use them from any allocation context (e.g. for evicting other
557          * contexts and from inside the shrinker).
558          */
559         GEM_BUG_ON(ctx->hw_id);
560         GEM_BUG_ON(!atomic_read(&ctx->hw_id_pin_count));
561         dev_priv->kernel_context = ctx;
562
563         /* highest priority; preempting task */
564         if (needs_preempt_context(dev_priv)) {
565                 ctx = i915_gem_context_create_kernel(dev_priv, INT_MAX);
566                 if (!IS_ERR(ctx))
567                         dev_priv->preempt_context = ctx;
568                 else
569                         DRM_ERROR("Failed to create preempt context; disabling preemption\n");
570         }
571
572         DRM_DEBUG_DRIVER("%s context support initialized\n",
573                          DRIVER_CAPS(dev_priv)->has_logical_contexts ?
574                          "logical" : "fake");
575         return 0;
576 }
577
578 void i915_gem_contexts_lost(struct drm_i915_private *dev_priv)
579 {
580         struct intel_engine_cs *engine;
581         enum intel_engine_id id;
582
583         lockdep_assert_held(&dev_priv->drm.struct_mutex);
584
585         for_each_engine(engine, dev_priv, id)
586                 intel_engine_lost_context(engine);
587 }
588
589 void i915_gem_contexts_fini(struct drm_i915_private *i915)
590 {
591         lockdep_assert_held(&i915->drm.struct_mutex);
592
593         if (i915->preempt_context)
594                 destroy_kernel_context(&i915->preempt_context);
595         destroy_kernel_context(&i915->kernel_context);
596
597         /* Must free all deferred contexts (via flush_workqueue) first */
598         GEM_BUG_ON(!list_empty(&i915->contexts.hw_id_list));
599         ida_destroy(&i915->contexts.hw_ida);
600 }
601
602 static int context_idr_cleanup(int id, void *p, void *data)
603 {
604         struct i915_gem_context *ctx = p;
605
606         context_close(ctx);
607         return 0;
608 }
609
610 int i915_gem_context_open(struct drm_i915_private *i915,
611                           struct drm_file *file)
612 {
613         struct drm_i915_file_private *file_priv = file->driver_priv;
614         struct i915_gem_context *ctx;
615
616         idr_init(&file_priv->context_idr);
617
618         mutex_lock(&i915->drm.struct_mutex);
619         ctx = i915_gem_create_context(i915, file_priv);
620         mutex_unlock(&i915->drm.struct_mutex);
621         if (IS_ERR(ctx)) {
622                 idr_destroy(&file_priv->context_idr);
623                 return PTR_ERR(ctx);
624         }
625
626         GEM_BUG_ON(i915_gem_context_is_kernel(ctx));
627
628         return 0;
629 }
630
631 void i915_gem_context_close(struct drm_file *file)
632 {
633         struct drm_i915_file_private *file_priv = file->driver_priv;
634
635         lockdep_assert_held(&file_priv->dev_priv->drm.struct_mutex);
636
637         idr_for_each(&file_priv->context_idr, context_idr_cleanup, NULL);
638         idr_destroy(&file_priv->context_idr);
639 }
640
641 static struct i915_request *
642 last_request_on_engine(struct i915_timeline *timeline,
643                        struct intel_engine_cs *engine)
644 {
645         struct i915_request *rq;
646
647         GEM_BUG_ON(timeline == &engine->timeline);
648
649         rq = i915_gem_active_raw(&timeline->last_request,
650                                  &engine->i915->drm.struct_mutex);
651         if (rq && rq->engine == engine) {
652                 GEM_TRACE("last request for %s on engine %s: %llx:%llu\n",
653                           timeline->name, engine->name,
654                           rq->fence.context, rq->fence.seqno);
655                 GEM_BUG_ON(rq->timeline != timeline);
656                 return rq;
657         }
658
659         return NULL;
660 }
661
662 static bool engine_has_kernel_context_barrier(struct intel_engine_cs *engine)
663 {
664         struct drm_i915_private *i915 = engine->i915;
665         const struct intel_context * const ce =
666                 to_intel_context(i915->kernel_context, engine);
667         struct i915_timeline *barrier = ce->ring->timeline;
668         struct intel_ring *ring;
669         bool any_active = false;
670
671         lockdep_assert_held(&i915->drm.struct_mutex);
672         list_for_each_entry(ring, &i915->gt.active_rings, active_link) {
673                 struct i915_request *rq;
674
675                 rq = last_request_on_engine(ring->timeline, engine);
676                 if (!rq)
677                         continue;
678
679                 any_active = true;
680
681                 if (rq->hw_context == ce)
682                         continue;
683
684                 /*
685                  * Was this request submitted after the previous
686                  * switch-to-kernel-context?
687                  */
688                 if (!i915_timeline_sync_is_later(barrier, &rq->fence)) {
689                         GEM_TRACE("%s needs barrier for %llx:%lld\n",
690                                   ring->timeline->name,
691                                   rq->fence.context,
692                                   rq->fence.seqno);
693                         return false;
694                 }
695
696                 GEM_TRACE("%s has barrier after %llx:%lld\n",
697                           ring->timeline->name,
698                           rq->fence.context,
699                           rq->fence.seqno);
700         }
701
702         /*
703          * If any other timeline was still active and behind the last barrier,
704          * then our last switch-to-kernel-context must still be queued and
705          * will run last (leaving the engine in the kernel context when it
706          * eventually idles).
707          */
708         if (any_active)
709                 return true;
710
711         /* The engine is idle; check that it is idling in the kernel context. */
712         return engine->last_retired_context == ce;
713 }
714
715 int i915_gem_switch_to_kernel_context(struct drm_i915_private *i915)
716 {
717         struct intel_engine_cs *engine;
718         enum intel_engine_id id;
719
720         GEM_TRACE("awake?=%s\n", yesno(i915->gt.awake));
721
722         lockdep_assert_held(&i915->drm.struct_mutex);
723         GEM_BUG_ON(!i915->kernel_context);
724
725         i915_retire_requests(i915);
726
727         for_each_engine(engine, i915, id) {
728                 struct intel_ring *ring;
729                 struct i915_request *rq;
730
731                 GEM_BUG_ON(!to_intel_context(i915->kernel_context, engine));
732                 if (engine_has_kernel_context_barrier(engine))
733                         continue;
734
735                 GEM_TRACE("emit barrier on %s\n", engine->name);
736
737                 rq = i915_request_alloc(engine, i915->kernel_context);
738                 if (IS_ERR(rq))
739                         return PTR_ERR(rq);
740
741                 /* Queue this switch after all other activity */
742                 list_for_each_entry(ring, &i915->gt.active_rings, active_link) {
743                         struct i915_request *prev;
744
745                         prev = last_request_on_engine(ring->timeline, engine);
746                         if (!prev)
747                                 continue;
748
749                         if (prev->gem_context == i915->kernel_context)
750                                 continue;
751
752                         GEM_TRACE("add barrier on %s for %llx:%lld\n",
753                                   engine->name,
754                                   prev->fence.context,
755                                   prev->fence.seqno);
756                         i915_sw_fence_await_sw_fence_gfp(&rq->submit,
757                                                          &prev->submit,
758                                                          I915_FENCE_GFP);
759                         i915_timeline_sync_set(rq->timeline, &prev->fence);
760                 }
761
762                 i915_request_add(rq);
763         }
764
765         return 0;
766 }
767
768 static bool client_is_banned(struct drm_i915_file_private *file_priv)
769 {
770         return atomic_read(&file_priv->ban_score) >= I915_CLIENT_SCORE_BANNED;
771 }
772
773 int i915_gem_context_create_ioctl(struct drm_device *dev, void *data,
774                                   struct drm_file *file)
775 {
776         struct drm_i915_private *dev_priv = to_i915(dev);
777         struct drm_i915_gem_context_create *args = data;
778         struct drm_i915_file_private *file_priv = file->driver_priv;
779         struct i915_gem_context *ctx;
780         int ret;
781
782         if (!DRIVER_CAPS(dev_priv)->has_logical_contexts)
783                 return -ENODEV;
784
785         if (args->pad != 0)
786                 return -EINVAL;
787
788         if (client_is_banned(file_priv)) {
789                 DRM_DEBUG("client %s[%d] banned from creating ctx\n",
790                           current->comm,
791                           pid_nr(get_task_pid(current, PIDTYPE_PID)));
792
793                 return -EIO;
794         }
795
796         ret = i915_mutex_lock_interruptible(dev);
797         if (ret)
798                 return ret;
799
800         ctx = i915_gem_create_context(dev_priv, file_priv);
801         mutex_unlock(&dev->struct_mutex);
802         if (IS_ERR(ctx))
803                 return PTR_ERR(ctx);
804
805         GEM_BUG_ON(i915_gem_context_is_kernel(ctx));
806
807         args->ctx_id = ctx->user_handle;
808         DRM_DEBUG("HW context %d created\n", args->ctx_id);
809
810         return 0;
811 }
812
813 int i915_gem_context_destroy_ioctl(struct drm_device *dev, void *data,
814                                    struct drm_file *file)
815 {
816         struct drm_i915_gem_context_destroy *args = data;
817         struct drm_i915_file_private *file_priv = file->driver_priv;
818         struct i915_gem_context *ctx;
819         int ret;
820
821         if (args->pad != 0)
822                 return -EINVAL;
823
824         if (args->ctx_id == DEFAULT_CONTEXT_HANDLE)
825                 return -ENOENT;
826
827         ctx = i915_gem_context_lookup(file_priv, args->ctx_id);
828         if (!ctx)
829                 return -ENOENT;
830
831         ret = mutex_lock_interruptible(&dev->struct_mutex);
832         if (ret)
833                 goto out;
834
835         __destroy_hw_context(ctx, file_priv);
836         mutex_unlock(&dev->struct_mutex);
837
838 out:
839         i915_gem_context_put(ctx);
840         return 0;
841 }
842
843 int i915_gem_context_getparam_ioctl(struct drm_device *dev, void *data,
844                                     struct drm_file *file)
845 {
846         struct drm_i915_file_private *file_priv = file->driver_priv;
847         struct drm_i915_gem_context_param *args = data;
848         struct i915_gem_context *ctx;
849         int ret = 0;
850
851         ctx = i915_gem_context_lookup(file_priv, args->ctx_id);
852         if (!ctx)
853                 return -ENOENT;
854
855         args->size = 0;
856         switch (args->param) {
857         case I915_CONTEXT_PARAM_BAN_PERIOD:
858                 ret = -EINVAL;
859                 break;
860         case I915_CONTEXT_PARAM_NO_ZEROMAP:
861                 args->value = test_bit(UCONTEXT_NO_ZEROMAP, &ctx->user_flags);
862                 break;
863         case I915_CONTEXT_PARAM_GTT_SIZE:
864                 if (ctx->ppgtt)
865                         args->value = ctx->ppgtt->vm.total;
866                 else if (to_i915(dev)->mm.aliasing_ppgtt)
867                         args->value = to_i915(dev)->mm.aliasing_ppgtt->vm.total;
868                 else
869                         args->value = to_i915(dev)->ggtt.vm.total;
870                 break;
871         case I915_CONTEXT_PARAM_NO_ERROR_CAPTURE:
872                 args->value = i915_gem_context_no_error_capture(ctx);
873                 break;
874         case I915_CONTEXT_PARAM_BANNABLE:
875                 args->value = i915_gem_context_is_bannable(ctx);
876                 break;
877         case I915_CONTEXT_PARAM_PRIORITY:
878                 args->value = ctx->sched.priority >> I915_USER_PRIORITY_SHIFT;
879                 break;
880         default:
881                 ret = -EINVAL;
882                 break;
883         }
884
885         i915_gem_context_put(ctx);
886         return ret;
887 }
888
889 int i915_gem_context_setparam_ioctl(struct drm_device *dev, void *data,
890                                     struct drm_file *file)
891 {
892         struct drm_i915_file_private *file_priv = file->driver_priv;
893         struct drm_i915_gem_context_param *args = data;
894         struct i915_gem_context *ctx;
895         int ret = 0;
896
897         ctx = i915_gem_context_lookup(file_priv, args->ctx_id);
898         if (!ctx)
899                 return -ENOENT;
900
901         switch (args->param) {
902         case I915_CONTEXT_PARAM_BAN_PERIOD:
903                 ret = -EINVAL;
904                 break;
905         case I915_CONTEXT_PARAM_NO_ZEROMAP:
906                 if (args->size)
907                         ret = -EINVAL;
908                 else if (args->value)
909                         set_bit(UCONTEXT_NO_ZEROMAP, &ctx->user_flags);
910                 else
911                         clear_bit(UCONTEXT_NO_ZEROMAP, &ctx->user_flags);
912                 break;
913         case I915_CONTEXT_PARAM_NO_ERROR_CAPTURE:
914                 if (args->size)
915                         ret = -EINVAL;
916                 else if (args->value)
917                         i915_gem_context_set_no_error_capture(ctx);
918                 else
919                         i915_gem_context_clear_no_error_capture(ctx);
920                 break;
921         case I915_CONTEXT_PARAM_BANNABLE:
922                 if (args->size)
923                         ret = -EINVAL;
924                 else if (!capable(CAP_SYS_ADMIN) && !args->value)
925                         ret = -EPERM;
926                 else if (args->value)
927                         i915_gem_context_set_bannable(ctx);
928                 else
929                         i915_gem_context_clear_bannable(ctx);
930                 break;
931
932         case I915_CONTEXT_PARAM_PRIORITY:
933                 {
934                         s64 priority = args->value;
935
936                         if (args->size)
937                                 ret = -EINVAL;
938                         else if (!(to_i915(dev)->caps.scheduler & I915_SCHEDULER_CAP_PRIORITY))
939                                 ret = -ENODEV;
940                         else if (priority > I915_CONTEXT_MAX_USER_PRIORITY ||
941                                  priority < I915_CONTEXT_MIN_USER_PRIORITY)
942                                 ret = -EINVAL;
943                         else if (priority > I915_CONTEXT_DEFAULT_PRIORITY &&
944                                  !capable(CAP_SYS_NICE))
945                                 ret = -EPERM;
946                         else
947                                 ctx->sched.priority =
948                                         I915_USER_PRIORITY(priority);
949                 }
950                 break;
951
952         default:
953                 ret = -EINVAL;
954                 break;
955         }
956
957         i915_gem_context_put(ctx);
958         return ret;
959 }
960
961 int i915_gem_context_reset_stats_ioctl(struct drm_device *dev,
962                                        void *data, struct drm_file *file)
963 {
964         struct drm_i915_private *dev_priv = to_i915(dev);
965         struct drm_i915_reset_stats *args = data;
966         struct i915_gem_context *ctx;
967         int ret;
968
969         if (args->flags || args->pad)
970                 return -EINVAL;
971
972         ret = -ENOENT;
973         rcu_read_lock();
974         ctx = __i915_gem_context_lookup_rcu(file->driver_priv, args->ctx_id);
975         if (!ctx)
976                 goto out;
977
978         /*
979          * We opt for unserialised reads here. This may result in tearing
980          * in the extremely unlikely event of a GPU hang on this context
981          * as we are querying them. If we need that extra layer of protection,
982          * we should wrap the hangstats with a seqlock.
983          */
984
985         if (capable(CAP_SYS_ADMIN))
986                 args->reset_count = i915_reset_count(&dev_priv->gpu_error);
987         else
988                 args->reset_count = 0;
989
990         args->batch_active = atomic_read(&ctx->guilty_count);
991         args->batch_pending = atomic_read(&ctx->active_count);
992
993         ret = 0;
994 out:
995         rcu_read_unlock();
996         return ret;
997 }
998
999 int __i915_gem_context_pin_hw_id(struct i915_gem_context *ctx)
1000 {
1001         struct drm_i915_private *i915 = ctx->i915;
1002         int err = 0;
1003
1004         mutex_lock(&i915->contexts.mutex);
1005
1006         GEM_BUG_ON(i915_gem_context_is_closed(ctx));
1007
1008         if (list_empty(&ctx->hw_id_link)) {
1009                 GEM_BUG_ON(atomic_read(&ctx->hw_id_pin_count));
1010
1011                 err = assign_hw_id(i915, &ctx->hw_id);
1012                 if (err)
1013                         goto out_unlock;
1014
1015                 list_add_tail(&ctx->hw_id_link, &i915->contexts.hw_id_list);
1016         }
1017
1018         GEM_BUG_ON(atomic_read(&ctx->hw_id_pin_count) == ~0u);
1019         atomic_inc(&ctx->hw_id_pin_count);
1020
1021 out_unlock:
1022         mutex_unlock(&i915->contexts.mutex);
1023         return err;
1024 }
1025
1026 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
1027 #include "selftests/mock_context.c"
1028 #include "selftests/i915_gem_context.c"
1029 #endif