]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/gpu/drm/i915/gem/i915_gem_context.c
drm/i915: Move aliasing_ppgtt underneath its i915_ggtt
[linux.git] / drivers / gpu / drm / i915 / gem / i915_gem_context.c
1 /*
2  * SPDX-License-Identifier: MIT
3  *
4  * Copyright © 2011-2012 Intel Corporation
5  */
6
7 /*
8  * This file implements HW context support. On gen5+ a HW context consists of an
9  * opaque GPU object which is referenced at times of context saves and restores.
10  * With RC6 enabled, the context is also referenced as the GPU enters and exists
11  * from RC6 (GPU has it's own internal power context, except on gen5). Though
12  * something like a context does exist for the media ring, the code only
13  * supports contexts for the render ring.
14  *
15  * In software, there is a distinction between contexts created by the user,
16  * and the default HW context. The default HW context is used by GPU clients
17  * that do not request setup of their own hardware context. The default
18  * context's state is never restored to help prevent programming errors. This
19  * would happen if a client ran and piggy-backed off another clients GPU state.
20  * The default context only exists to give the GPU some offset to load as the
21  * current to invoke a save of the context we actually care about. In fact, the
22  * code could likely be constructed, albeit in a more complicated fashion, to
23  * never use the default context, though that limits the driver's ability to
24  * swap out, and/or destroy other contexts.
25  *
26  * All other contexts are created as a request by the GPU client. These contexts
27  * store GPU state, and thus allow GPU clients to not re-emit state (and
28  * potentially query certain state) at any time. The kernel driver makes
29  * certain that the appropriate commands are inserted.
30  *
31  * The context life cycle is semi-complicated in that context BOs may live
32  * longer than the context itself because of the way the hardware, and object
33  * tracking works. Below is a very crude representation of the state machine
34  * describing the context life.
35  *                                         refcount     pincount     active
36  * S0: initial state                          0            0           0
37  * S1: context created                        1            0           0
38  * S2: context is currently running           2            1           X
39  * S3: GPU referenced, but not current        2            0           1
40  * S4: context is current, but destroyed      1            1           0
41  * S5: like S3, but destroyed                 1            0           1
42  *
43  * The most common (but not all) transitions:
44  * S0->S1: client creates a context
45  * S1->S2: client submits execbuf with context
46  * S2->S3: other clients submits execbuf with context
47  * S3->S1: context object was retired
48  * S3->S2: clients submits another execbuf
49  * S2->S4: context destroy called with current context
50  * S3->S5->S0: destroy path
51  * S4->S5->S0: destroy path on current context
52  *
53  * There are two confusing terms used above:
54  *  The "current context" means the context which is currently running on the
55  *  GPU. The GPU has loaded its state already and has stored away the gtt
56  *  offset of the BO. The GPU is not actively referencing the data at this
57  *  offset, but it will on the next context switch. The only way to avoid this
58  *  is to do a GPU reset.
59  *
60  *  An "active context' is one which was previously the "current context" and is
61  *  on the active list waiting for the next context switch to occur. Until this
62  *  happens, the object must remain at the same gtt offset. It is therefore
63  *  possible to destroy a context, but it is still active.
64  *
65  */
66
67 #include <linux/log2.h>
68 #include <linux/nospec.h>
69
70 #include <drm/i915_drm.h>
71
72 #include "gt/intel_lrc_reg.h"
73
74 #include "i915_gem_context.h"
75 #include "i915_globals.h"
76 #include "i915_trace.h"
77 #include "i915_user_extensions.h"
78
79 #define ALL_L3_SLICES(dev) (1 << NUM_L3_SLICES(dev)) - 1
80
81 static struct i915_global_gem_context {
82         struct i915_global base;
83         struct kmem_cache *slab_luts;
84 } global;
85
86 struct i915_lut_handle *i915_lut_handle_alloc(void)
87 {
88         return kmem_cache_alloc(global.slab_luts, GFP_KERNEL);
89 }
90
91 void i915_lut_handle_free(struct i915_lut_handle *lut)
92 {
93         return kmem_cache_free(global.slab_luts, lut);
94 }
95
96 static void lut_close(struct i915_gem_context *ctx)
97 {
98         struct radix_tree_iter iter;
99         void __rcu **slot;
100
101         lockdep_assert_held(&ctx->mutex);
102
103         rcu_read_lock();
104         radix_tree_for_each_slot(slot, &ctx->handles_vma, &iter, 0) {
105                 struct i915_vma *vma = rcu_dereference_raw(*slot);
106                 struct drm_i915_gem_object *obj = vma->obj;
107                 struct i915_lut_handle *lut;
108
109                 if (!kref_get_unless_zero(&obj->base.refcount))
110                         continue;
111
112                 rcu_read_unlock();
113                 i915_gem_object_lock(obj);
114                 list_for_each_entry(lut, &obj->lut_list, obj_link) {
115                         if (lut->ctx != ctx)
116                                 continue;
117
118                         if (lut->handle != iter.index)
119                                 continue;
120
121                         list_del(&lut->obj_link);
122                         break;
123                 }
124                 i915_gem_object_unlock(obj);
125                 rcu_read_lock();
126
127                 if (&lut->obj_link != &obj->lut_list) {
128                         i915_lut_handle_free(lut);
129                         radix_tree_iter_delete(&ctx->handles_vma, &iter, slot);
130                         if (atomic_dec_and_test(&vma->open_count) &&
131                             !i915_vma_is_ggtt(vma))
132                                 i915_vma_close(vma);
133                         i915_gem_object_put(obj);
134                 }
135
136                 i915_gem_object_put(obj);
137         }
138         rcu_read_unlock();
139 }
140
141 static struct intel_context *
142 lookup_user_engine(struct i915_gem_context *ctx,
143                    unsigned long flags,
144                    const struct i915_engine_class_instance *ci)
145 #define LOOKUP_USER_INDEX BIT(0)
146 {
147         int idx;
148
149         if (!!(flags & LOOKUP_USER_INDEX) != i915_gem_context_user_engines(ctx))
150                 return ERR_PTR(-EINVAL);
151
152         if (!i915_gem_context_user_engines(ctx)) {
153                 struct intel_engine_cs *engine;
154
155                 engine = intel_engine_lookup_user(ctx->i915,
156                                                   ci->engine_class,
157                                                   ci->engine_instance);
158                 if (!engine)
159                         return ERR_PTR(-EINVAL);
160
161                 idx = engine->id;
162         } else {
163                 idx = ci->engine_instance;
164         }
165
166         return i915_gem_context_get_engine(ctx, idx);
167 }
168
169 static inline int new_hw_id(struct drm_i915_private *i915, gfp_t gfp)
170 {
171         unsigned int max;
172
173         lockdep_assert_held(&i915->contexts.mutex);
174
175         if (INTEL_GEN(i915) >= 11)
176                 max = GEN11_MAX_CONTEXT_HW_ID;
177         else if (USES_GUC_SUBMISSION(i915))
178                 /*
179                  * When using GuC in proxy submission, GuC consumes the
180                  * highest bit in the context id to indicate proxy submission.
181                  */
182                 max = MAX_GUC_CONTEXT_HW_ID;
183         else
184                 max = MAX_CONTEXT_HW_ID;
185
186         return ida_simple_get(&i915->contexts.hw_ida, 0, max, gfp);
187 }
188
189 static int steal_hw_id(struct drm_i915_private *i915)
190 {
191         struct i915_gem_context *ctx, *cn;
192         LIST_HEAD(pinned);
193         int id = -ENOSPC;
194
195         lockdep_assert_held(&i915->contexts.mutex);
196
197         list_for_each_entry_safe(ctx, cn,
198                                  &i915->contexts.hw_id_list, hw_id_link) {
199                 if (atomic_read(&ctx->hw_id_pin_count)) {
200                         list_move_tail(&ctx->hw_id_link, &pinned);
201                         continue;
202                 }
203
204                 GEM_BUG_ON(!ctx->hw_id); /* perma-pinned kernel context */
205                 list_del_init(&ctx->hw_id_link);
206                 id = ctx->hw_id;
207                 break;
208         }
209
210         /*
211          * Remember how far we got up on the last repossesion scan, so the
212          * list is kept in a "least recently scanned" order.
213          */
214         list_splice_tail(&pinned, &i915->contexts.hw_id_list);
215         return id;
216 }
217
218 static int assign_hw_id(struct drm_i915_private *i915, unsigned int *out)
219 {
220         int ret;
221
222         lockdep_assert_held(&i915->contexts.mutex);
223
224         /*
225          * We prefer to steal/stall ourselves and our users over that of the
226          * entire system. That may be a little unfair to our users, and
227          * even hurt high priority clients. The choice is whether to oomkill
228          * something else, or steal a context id.
229          */
230         ret = new_hw_id(i915, GFP_KERNEL | __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
231         if (unlikely(ret < 0)) {
232                 ret = steal_hw_id(i915);
233                 if (ret < 0) /* once again for the correct errno code */
234                         ret = new_hw_id(i915, GFP_KERNEL);
235                 if (ret < 0)
236                         return ret;
237         }
238
239         *out = ret;
240         return 0;
241 }
242
243 static void release_hw_id(struct i915_gem_context *ctx)
244 {
245         struct drm_i915_private *i915 = ctx->i915;
246
247         if (list_empty(&ctx->hw_id_link))
248                 return;
249
250         mutex_lock(&i915->contexts.mutex);
251         if (!list_empty(&ctx->hw_id_link)) {
252                 ida_simple_remove(&i915->contexts.hw_ida, ctx->hw_id);
253                 list_del_init(&ctx->hw_id_link);
254         }
255         mutex_unlock(&i915->contexts.mutex);
256 }
257
258 static void __free_engines(struct i915_gem_engines *e, unsigned int count)
259 {
260         while (count--) {
261                 if (!e->engines[count])
262                         continue;
263
264                 intel_context_put(e->engines[count]);
265         }
266         kfree(e);
267 }
268
269 static void free_engines(struct i915_gem_engines *e)
270 {
271         __free_engines(e, e->num_engines);
272 }
273
274 static void free_engines_rcu(struct rcu_head *rcu)
275 {
276         free_engines(container_of(rcu, struct i915_gem_engines, rcu));
277 }
278
279 static struct i915_gem_engines *default_engines(struct i915_gem_context *ctx)
280 {
281         struct intel_engine_cs *engine;
282         struct i915_gem_engines *e;
283         enum intel_engine_id id;
284
285         e = kzalloc(struct_size(e, engines, I915_NUM_ENGINES), GFP_KERNEL);
286         if (!e)
287                 return ERR_PTR(-ENOMEM);
288
289         init_rcu_head(&e->rcu);
290         for_each_engine(engine, ctx->i915, id) {
291                 struct intel_context *ce;
292
293                 ce = intel_context_create(ctx, engine);
294                 if (IS_ERR(ce)) {
295                         __free_engines(e, id);
296                         return ERR_CAST(ce);
297                 }
298
299                 e->engines[id] = ce;
300         }
301         e->num_engines = id;
302
303         return e;
304 }
305
306 static void i915_gem_context_free(struct i915_gem_context *ctx)
307 {
308         lockdep_assert_held(&ctx->i915->drm.struct_mutex);
309         GEM_BUG_ON(!i915_gem_context_is_closed(ctx));
310
311         release_hw_id(ctx);
312         if (ctx->vm)
313                 i915_vm_put(ctx->vm);
314
315         free_engines(rcu_access_pointer(ctx->engines));
316         mutex_destroy(&ctx->engines_mutex);
317
318         if (ctx->timeline)
319                 intel_timeline_put(ctx->timeline);
320
321         kfree(ctx->name);
322         put_pid(ctx->pid);
323
324         list_del(&ctx->link);
325         mutex_destroy(&ctx->mutex);
326
327         kfree_rcu(ctx, rcu);
328 }
329
330 static void contexts_free(struct drm_i915_private *i915)
331 {
332         struct llist_node *freed = llist_del_all(&i915->contexts.free_list);
333         struct i915_gem_context *ctx, *cn;
334
335         lockdep_assert_held(&i915->drm.struct_mutex);
336
337         llist_for_each_entry_safe(ctx, cn, freed, free_link)
338                 i915_gem_context_free(ctx);
339 }
340
341 static void contexts_free_first(struct drm_i915_private *i915)
342 {
343         struct i915_gem_context *ctx;
344         struct llist_node *freed;
345
346         lockdep_assert_held(&i915->drm.struct_mutex);
347
348         freed = llist_del_first(&i915->contexts.free_list);
349         if (!freed)
350                 return;
351
352         ctx = container_of(freed, typeof(*ctx), free_link);
353         i915_gem_context_free(ctx);
354 }
355
356 static void contexts_free_worker(struct work_struct *work)
357 {
358         struct drm_i915_private *i915 =
359                 container_of(work, typeof(*i915), contexts.free_work);
360
361         mutex_lock(&i915->drm.struct_mutex);
362         contexts_free(i915);
363         mutex_unlock(&i915->drm.struct_mutex);
364 }
365
366 void i915_gem_context_release(struct kref *ref)
367 {
368         struct i915_gem_context *ctx = container_of(ref, typeof(*ctx), ref);
369         struct drm_i915_private *i915 = ctx->i915;
370
371         trace_i915_context_free(ctx);
372         if (llist_add(&ctx->free_link, &i915->contexts.free_list))
373                 queue_work(i915->wq, &i915->contexts.free_work);
374 }
375
376 static void context_close(struct i915_gem_context *ctx)
377 {
378         mutex_lock(&ctx->mutex);
379
380         i915_gem_context_set_closed(ctx);
381         ctx->file_priv = ERR_PTR(-EBADF);
382
383         /*
384          * This context will never again be assinged to HW, so we can
385          * reuse its ID for the next context.
386          */
387         release_hw_id(ctx);
388
389         /*
390          * The LUT uses the VMA as a backpointer to unref the object,
391          * so we need to clear the LUT before we close all the VMA (inside
392          * the ppgtt).
393          */
394         lut_close(ctx);
395
396         mutex_unlock(&ctx->mutex);
397         i915_gem_context_put(ctx);
398 }
399
400 static u32 default_desc_template(const struct drm_i915_private *i915,
401                                  const struct i915_address_space *vm)
402 {
403         u32 address_mode;
404         u32 desc;
405
406         desc = GEN8_CTX_VALID | GEN8_CTX_PRIVILEGE;
407
408         address_mode = INTEL_LEGACY_32B_CONTEXT;
409         if (vm && i915_vm_is_4lvl(vm))
410                 address_mode = INTEL_LEGACY_64B_CONTEXT;
411         desc |= address_mode << GEN8_CTX_ADDRESSING_MODE_SHIFT;
412
413         if (IS_GEN(i915, 8))
414                 desc |= GEN8_CTX_L3LLC_COHERENT;
415
416         /* TODO: WaDisableLiteRestore when we start using semaphore
417          * signalling between Command Streamers
418          * ring->ctx_desc_template |= GEN8_CTX_FORCE_RESTORE;
419          */
420
421         return desc;
422 }
423
424 static struct i915_gem_context *
425 __create_context(struct drm_i915_private *i915)
426 {
427         struct i915_gem_context *ctx;
428         struct i915_gem_engines *e;
429         int err;
430         int i;
431
432         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
433         if (!ctx)
434                 return ERR_PTR(-ENOMEM);
435
436         kref_init(&ctx->ref);
437         list_add_tail(&ctx->link, &i915->contexts.list);
438         ctx->i915 = i915;
439         ctx->sched.priority = I915_USER_PRIORITY(I915_PRIORITY_NORMAL);
440         mutex_init(&ctx->mutex);
441
442         mutex_init(&ctx->engines_mutex);
443         e = default_engines(ctx);
444         if (IS_ERR(e)) {
445                 err = PTR_ERR(e);
446                 goto err_free;
447         }
448         RCU_INIT_POINTER(ctx->engines, e);
449
450         INIT_RADIX_TREE(&ctx->handles_vma, GFP_KERNEL);
451         INIT_LIST_HEAD(&ctx->hw_id_link);
452
453         /* NB: Mark all slices as needing a remap so that when the context first
454          * loads it will restore whatever remap state already exists. If there
455          * is no remap info, it will be a NOP. */
456         ctx->remap_slice = ALL_L3_SLICES(i915);
457
458         i915_gem_context_set_bannable(ctx);
459         i915_gem_context_set_recoverable(ctx);
460
461         ctx->ring_size = 4 * PAGE_SIZE;
462         ctx->desc_template = default_desc_template(i915, NULL);
463
464         for (i = 0; i < ARRAY_SIZE(ctx->hang_timestamp); i++)
465                 ctx->hang_timestamp[i] = jiffies - CONTEXT_FAST_HANG_JIFFIES;
466
467         return ctx;
468
469 err_free:
470         kfree(ctx);
471         return ERR_PTR(err);
472 }
473
474 static struct i915_address_space *
475 __set_ppgtt(struct i915_gem_context *ctx, struct i915_address_space *vm)
476 {
477         struct i915_address_space *old = ctx->vm;
478
479         ctx->vm = i915_vm_get(vm);
480         ctx->desc_template = default_desc_template(ctx->i915, vm);
481
482         return old;
483 }
484
485 static void __assign_ppgtt(struct i915_gem_context *ctx,
486                            struct i915_address_space *vm)
487 {
488         if (vm == ctx->vm)
489                 return;
490
491         vm = __set_ppgtt(ctx, vm);
492         if (vm)
493                 i915_vm_put(vm);
494 }
495
496 static struct i915_gem_context *
497 i915_gem_create_context(struct drm_i915_private *dev_priv, unsigned int flags)
498 {
499         struct i915_gem_context *ctx;
500
501         lockdep_assert_held(&dev_priv->drm.struct_mutex);
502
503         if (flags & I915_CONTEXT_CREATE_FLAGS_SINGLE_TIMELINE &&
504             !HAS_EXECLISTS(dev_priv))
505                 return ERR_PTR(-EINVAL);
506
507         /* Reap the most stale context */
508         contexts_free_first(dev_priv);
509
510         ctx = __create_context(dev_priv);
511         if (IS_ERR(ctx))
512                 return ctx;
513
514         if (HAS_FULL_PPGTT(dev_priv)) {
515                 struct i915_ppgtt *ppgtt;
516
517                 ppgtt = i915_ppgtt_create(dev_priv);
518                 if (IS_ERR(ppgtt)) {
519                         DRM_DEBUG_DRIVER("PPGTT setup failed (%ld)\n",
520                                          PTR_ERR(ppgtt));
521                         context_close(ctx);
522                         return ERR_CAST(ppgtt);
523                 }
524
525                 __assign_ppgtt(ctx, &ppgtt->vm);
526                 i915_vm_put(&ppgtt->vm);
527         }
528
529         if (flags & I915_CONTEXT_CREATE_FLAGS_SINGLE_TIMELINE) {
530                 struct intel_timeline *timeline;
531
532                 timeline = intel_timeline_create(&dev_priv->gt, NULL);
533                 if (IS_ERR(timeline)) {
534                         context_close(ctx);
535                         return ERR_CAST(timeline);
536                 }
537
538                 ctx->timeline = timeline;
539         }
540
541         trace_i915_context_create(ctx);
542
543         return ctx;
544 }
545
546 /**
547  * i915_gem_context_create_gvt - create a GVT GEM context
548  * @dev: drm device *
549  *
550  * This function is used to create a GVT specific GEM context.
551  *
552  * Returns:
553  * pointer to i915_gem_context on success, error pointer if failed
554  *
555  */
556 struct i915_gem_context *
557 i915_gem_context_create_gvt(struct drm_device *dev)
558 {
559         struct i915_gem_context *ctx;
560         int ret;
561
562         if (!IS_ENABLED(CONFIG_DRM_I915_GVT))
563                 return ERR_PTR(-ENODEV);
564
565         ret = i915_mutex_lock_interruptible(dev);
566         if (ret)
567                 return ERR_PTR(ret);
568
569         ctx = i915_gem_create_context(to_i915(dev), 0);
570         if (IS_ERR(ctx))
571                 goto out;
572
573         ret = i915_gem_context_pin_hw_id(ctx);
574         if (ret) {
575                 context_close(ctx);
576                 ctx = ERR_PTR(ret);
577                 goto out;
578         }
579
580         ctx->file_priv = ERR_PTR(-EBADF);
581         i915_gem_context_set_closed(ctx); /* not user accessible */
582         i915_gem_context_clear_bannable(ctx);
583         i915_gem_context_set_force_single_submission(ctx);
584         if (!USES_GUC_SUBMISSION(to_i915(dev)))
585                 ctx->ring_size = 512 * PAGE_SIZE; /* Max ring buffer size */
586
587         GEM_BUG_ON(i915_gem_context_is_kernel(ctx));
588 out:
589         mutex_unlock(&dev->struct_mutex);
590         return ctx;
591 }
592
593 static void
594 destroy_kernel_context(struct i915_gem_context **ctxp)
595 {
596         struct i915_gem_context *ctx;
597
598         /* Keep the context ref so that we can free it immediately ourselves */
599         ctx = i915_gem_context_get(fetch_and_zero(ctxp));
600         GEM_BUG_ON(!i915_gem_context_is_kernel(ctx));
601
602         context_close(ctx);
603         i915_gem_context_free(ctx);
604 }
605
606 struct i915_gem_context *
607 i915_gem_context_create_kernel(struct drm_i915_private *i915, int prio)
608 {
609         struct i915_gem_context *ctx;
610         int err;
611
612         ctx = i915_gem_create_context(i915, 0);
613         if (IS_ERR(ctx))
614                 return ctx;
615
616         err = i915_gem_context_pin_hw_id(ctx);
617         if (err) {
618                 destroy_kernel_context(&ctx);
619                 return ERR_PTR(err);
620         }
621
622         i915_gem_context_clear_bannable(ctx);
623         ctx->sched.priority = I915_USER_PRIORITY(prio);
624         ctx->ring_size = PAGE_SIZE;
625
626         GEM_BUG_ON(!i915_gem_context_is_kernel(ctx));
627
628         return ctx;
629 }
630
631 static void init_contexts(struct drm_i915_private *i915)
632 {
633         mutex_init(&i915->contexts.mutex);
634         INIT_LIST_HEAD(&i915->contexts.list);
635
636         /* Using the simple ida interface, the max is limited by sizeof(int) */
637         BUILD_BUG_ON(MAX_CONTEXT_HW_ID > INT_MAX);
638         BUILD_BUG_ON(GEN11_MAX_CONTEXT_HW_ID > INT_MAX);
639         ida_init(&i915->contexts.hw_ida);
640         INIT_LIST_HEAD(&i915->contexts.hw_id_list);
641
642         INIT_WORK(&i915->contexts.free_work, contexts_free_worker);
643         init_llist_head(&i915->contexts.free_list);
644 }
645
646 int i915_gem_contexts_init(struct drm_i915_private *dev_priv)
647 {
648         struct i915_gem_context *ctx;
649
650         /* Reassure ourselves we are only called once */
651         GEM_BUG_ON(dev_priv->kernel_context);
652
653         init_contexts(dev_priv);
654
655         /* lowest priority; idle task */
656         ctx = i915_gem_context_create_kernel(dev_priv, I915_PRIORITY_MIN);
657         if (IS_ERR(ctx)) {
658                 DRM_ERROR("Failed to create default global context\n");
659                 return PTR_ERR(ctx);
660         }
661         /*
662          * For easy recognisablity, we want the kernel context to be 0 and then
663          * all user contexts will have non-zero hw_id. Kernel contexts are
664          * permanently pinned, so that we never suffer a stall and can
665          * use them from any allocation context (e.g. for evicting other
666          * contexts and from inside the shrinker).
667          */
668         GEM_BUG_ON(ctx->hw_id);
669         GEM_BUG_ON(!atomic_read(&ctx->hw_id_pin_count));
670         dev_priv->kernel_context = ctx;
671
672         DRM_DEBUG_DRIVER("%s context support initialized\n",
673                          DRIVER_CAPS(dev_priv)->has_logical_contexts ?
674                          "logical" : "fake");
675         return 0;
676 }
677
678 void i915_gem_contexts_fini(struct drm_i915_private *i915)
679 {
680         lockdep_assert_held(&i915->drm.struct_mutex);
681
682         destroy_kernel_context(&i915->kernel_context);
683
684         /* Must free all deferred contexts (via flush_workqueue) first */
685         GEM_BUG_ON(!list_empty(&i915->contexts.hw_id_list));
686         ida_destroy(&i915->contexts.hw_ida);
687 }
688
689 static int context_idr_cleanup(int id, void *p, void *data)
690 {
691         context_close(p);
692         return 0;
693 }
694
695 static int vm_idr_cleanup(int id, void *p, void *data)
696 {
697         i915_vm_put(p);
698         return 0;
699 }
700
701 static int gem_context_register(struct i915_gem_context *ctx,
702                                 struct drm_i915_file_private *fpriv)
703 {
704         int ret;
705
706         ctx->file_priv = fpriv;
707         if (ctx->vm)
708                 ctx->vm->file = fpriv;
709
710         ctx->pid = get_task_pid(current, PIDTYPE_PID);
711         ctx->name = kasprintf(GFP_KERNEL, "%s[%d]",
712                               current->comm, pid_nr(ctx->pid));
713         if (!ctx->name) {
714                 ret = -ENOMEM;
715                 goto err_pid;
716         }
717
718         /* And finally expose ourselves to userspace via the idr */
719         mutex_lock(&fpriv->context_idr_lock);
720         ret = idr_alloc(&fpriv->context_idr, ctx, 0, 0, GFP_KERNEL);
721         mutex_unlock(&fpriv->context_idr_lock);
722         if (ret >= 0)
723                 goto out;
724
725         kfree(fetch_and_zero(&ctx->name));
726 err_pid:
727         put_pid(fetch_and_zero(&ctx->pid));
728 out:
729         return ret;
730 }
731
732 int i915_gem_context_open(struct drm_i915_private *i915,
733                           struct drm_file *file)
734 {
735         struct drm_i915_file_private *file_priv = file->driver_priv;
736         struct i915_gem_context *ctx;
737         int err;
738
739         mutex_init(&file_priv->context_idr_lock);
740         mutex_init(&file_priv->vm_idr_lock);
741
742         idr_init(&file_priv->context_idr);
743         idr_init_base(&file_priv->vm_idr, 1);
744
745         mutex_lock(&i915->drm.struct_mutex);
746         ctx = i915_gem_create_context(i915, 0);
747         mutex_unlock(&i915->drm.struct_mutex);
748         if (IS_ERR(ctx)) {
749                 err = PTR_ERR(ctx);
750                 goto err;
751         }
752
753         err = gem_context_register(ctx, file_priv);
754         if (err < 0)
755                 goto err_ctx;
756
757         GEM_BUG_ON(i915_gem_context_is_kernel(ctx));
758         GEM_BUG_ON(err > 0);
759
760         return 0;
761
762 err_ctx:
763         context_close(ctx);
764 err:
765         idr_destroy(&file_priv->vm_idr);
766         idr_destroy(&file_priv->context_idr);
767         mutex_destroy(&file_priv->vm_idr_lock);
768         mutex_destroy(&file_priv->context_idr_lock);
769         return err;
770 }
771
772 void i915_gem_context_close(struct drm_file *file)
773 {
774         struct drm_i915_file_private *file_priv = file->driver_priv;
775
776         idr_for_each(&file_priv->context_idr, context_idr_cleanup, NULL);
777         idr_destroy(&file_priv->context_idr);
778         mutex_destroy(&file_priv->context_idr_lock);
779
780         idr_for_each(&file_priv->vm_idr, vm_idr_cleanup, NULL);
781         idr_destroy(&file_priv->vm_idr);
782         mutex_destroy(&file_priv->vm_idr_lock);
783 }
784
785 int i915_gem_vm_create_ioctl(struct drm_device *dev, void *data,
786                              struct drm_file *file)
787 {
788         struct drm_i915_private *i915 = to_i915(dev);
789         struct drm_i915_gem_vm_control *args = data;
790         struct drm_i915_file_private *file_priv = file->driver_priv;
791         struct i915_ppgtt *ppgtt;
792         int err;
793
794         if (!HAS_FULL_PPGTT(i915))
795                 return -ENODEV;
796
797         if (args->flags)
798                 return -EINVAL;
799
800         ppgtt = i915_ppgtt_create(i915);
801         if (IS_ERR(ppgtt))
802                 return PTR_ERR(ppgtt);
803
804         ppgtt->vm.file = file_priv;
805
806         if (args->extensions) {
807                 err = i915_user_extensions(u64_to_user_ptr(args->extensions),
808                                            NULL, 0,
809                                            ppgtt);
810                 if (err)
811                         goto err_put;
812         }
813
814         err = mutex_lock_interruptible(&file_priv->vm_idr_lock);
815         if (err)
816                 goto err_put;
817
818         err = idr_alloc(&file_priv->vm_idr, &ppgtt->vm, 0, 0, GFP_KERNEL);
819         if (err < 0)
820                 goto err_unlock;
821
822         GEM_BUG_ON(err == 0); /* reserved for invalid/unassigned ppgtt */
823
824         mutex_unlock(&file_priv->vm_idr_lock);
825
826         args->vm_id = err;
827         return 0;
828
829 err_unlock:
830         mutex_unlock(&file_priv->vm_idr_lock);
831 err_put:
832         i915_vm_put(&ppgtt->vm);
833         return err;
834 }
835
836 int i915_gem_vm_destroy_ioctl(struct drm_device *dev, void *data,
837                               struct drm_file *file)
838 {
839         struct drm_i915_file_private *file_priv = file->driver_priv;
840         struct drm_i915_gem_vm_control *args = data;
841         struct i915_address_space *vm;
842         int err;
843         u32 id;
844
845         if (args->flags)
846                 return -EINVAL;
847
848         if (args->extensions)
849                 return -EINVAL;
850
851         id = args->vm_id;
852         if (!id)
853                 return -ENOENT;
854
855         err = mutex_lock_interruptible(&file_priv->vm_idr_lock);
856         if (err)
857                 return err;
858
859         vm = idr_remove(&file_priv->vm_idr, id);
860
861         mutex_unlock(&file_priv->vm_idr_lock);
862         if (!vm)
863                 return -ENOENT;
864
865         i915_vm_put(vm);
866         return 0;
867 }
868
869 struct context_barrier_task {
870         struct i915_active base;
871         void (*task)(void *data);
872         void *data;
873 };
874
875 static void cb_retire(struct i915_active *base)
876 {
877         struct context_barrier_task *cb = container_of(base, typeof(*cb), base);
878
879         if (cb->task)
880                 cb->task(cb->data);
881
882         i915_active_fini(&cb->base);
883         kfree(cb);
884 }
885
886 I915_SELFTEST_DECLARE(static intel_engine_mask_t context_barrier_inject_fault);
887 static int context_barrier_task(struct i915_gem_context *ctx,
888                                 intel_engine_mask_t engines,
889                                 bool (*skip)(struct intel_context *ce, void *data),
890                                 int (*emit)(struct i915_request *rq, void *data),
891                                 void (*task)(void *data),
892                                 void *data)
893 {
894         struct drm_i915_private *i915 = ctx->i915;
895         struct context_barrier_task *cb;
896         struct i915_gem_engines_iter it;
897         struct intel_context *ce;
898         int err = 0;
899
900         lockdep_assert_held(&i915->drm.struct_mutex);
901         GEM_BUG_ON(!task);
902
903         cb = kmalloc(sizeof(*cb), GFP_KERNEL);
904         if (!cb)
905                 return -ENOMEM;
906
907         i915_active_init(i915, &cb->base, NULL, cb_retire);
908         err = i915_active_acquire(&cb->base);
909         if (err) {
910                 kfree(cb);
911                 return err;
912         }
913
914         for_each_gem_engine(ce, i915_gem_context_lock_engines(ctx), it) {
915                 struct i915_request *rq;
916
917                 if (I915_SELFTEST_ONLY(context_barrier_inject_fault &
918                                        ce->engine->mask)) {
919                         err = -ENXIO;
920                         break;
921                 }
922
923                 if (!(ce->engine->mask & engines))
924                         continue;
925
926                 if (skip && skip(ce, data))
927                         continue;
928
929                 rq = intel_context_create_request(ce);
930                 if (IS_ERR(rq)) {
931                         err = PTR_ERR(rq);
932                         break;
933                 }
934
935                 err = 0;
936                 if (emit)
937                         err = emit(rq, data);
938                 if (err == 0)
939                         err = i915_active_ref(&cb->base, rq->fence.context, rq);
940
941                 i915_request_add(rq);
942                 if (err)
943                         break;
944         }
945         i915_gem_context_unlock_engines(ctx);
946
947         cb->task = err ? NULL : task; /* caller needs to unwind instead */
948         cb->data = data;
949
950         i915_active_release(&cb->base);
951
952         return err;
953 }
954
955 static int get_ppgtt(struct drm_i915_file_private *file_priv,
956                      struct i915_gem_context *ctx,
957                      struct drm_i915_gem_context_param *args)
958 {
959         struct i915_address_space *vm;
960         int ret;
961
962         if (!ctx->vm)
963                 return -ENODEV;
964
965         /* XXX rcu acquire? */
966         ret = mutex_lock_interruptible(&ctx->i915->drm.struct_mutex);
967         if (ret)
968                 return ret;
969
970         vm = i915_vm_get(ctx->vm);
971         mutex_unlock(&ctx->i915->drm.struct_mutex);
972
973         ret = mutex_lock_interruptible(&file_priv->vm_idr_lock);
974         if (ret)
975                 goto err_put;
976
977         ret = idr_alloc(&file_priv->vm_idr, vm, 0, 0, GFP_KERNEL);
978         GEM_BUG_ON(!ret);
979         if (ret < 0)
980                 goto err_unlock;
981
982         i915_vm_get(vm);
983
984         args->size = 0;
985         args->value = ret;
986
987         ret = 0;
988 err_unlock:
989         mutex_unlock(&file_priv->vm_idr_lock);
990 err_put:
991         i915_vm_put(vm);
992         return ret;
993 }
994
995 static void set_ppgtt_barrier(void *data)
996 {
997         struct i915_address_space *old = data;
998
999         if (INTEL_GEN(old->i915) < 8)
1000                 gen6_ppgtt_unpin_all(i915_vm_to_ppgtt(old));
1001
1002         i915_vm_put(old);
1003 }
1004
1005 static int emit_ppgtt_update(struct i915_request *rq, void *data)
1006 {
1007         struct i915_address_space *vm = rq->gem_context->vm;
1008         struct intel_engine_cs *engine = rq->engine;
1009         u32 base = engine->mmio_base;
1010         u32 *cs;
1011         int i;
1012
1013         if (i915_vm_is_4lvl(vm)) {
1014                 struct i915_ppgtt *ppgtt = i915_vm_to_ppgtt(vm);
1015                 const dma_addr_t pd_daddr = px_dma(ppgtt->pd);
1016
1017                 cs = intel_ring_begin(rq, 6);
1018                 if (IS_ERR(cs))
1019                         return PTR_ERR(cs);
1020
1021                 *cs++ = MI_LOAD_REGISTER_IMM(2);
1022
1023                 *cs++ = i915_mmio_reg_offset(GEN8_RING_PDP_UDW(base, 0));
1024                 *cs++ = upper_32_bits(pd_daddr);
1025                 *cs++ = i915_mmio_reg_offset(GEN8_RING_PDP_LDW(base, 0));
1026                 *cs++ = lower_32_bits(pd_daddr);
1027
1028                 *cs++ = MI_NOOP;
1029                 intel_ring_advance(rq, cs);
1030         } else if (HAS_LOGICAL_RING_CONTEXTS(engine->i915)) {
1031                 struct i915_ppgtt *ppgtt = i915_vm_to_ppgtt(vm);
1032
1033                 cs = intel_ring_begin(rq, 4 * GEN8_3LVL_PDPES + 2);
1034                 if (IS_ERR(cs))
1035                         return PTR_ERR(cs);
1036
1037                 *cs++ = MI_LOAD_REGISTER_IMM(2 * GEN8_3LVL_PDPES);
1038                 for (i = GEN8_3LVL_PDPES; i--; ) {
1039                         const dma_addr_t pd_daddr = i915_page_dir_dma_addr(ppgtt, i);
1040
1041                         *cs++ = i915_mmio_reg_offset(GEN8_RING_PDP_UDW(base, i));
1042                         *cs++ = upper_32_bits(pd_daddr);
1043                         *cs++ = i915_mmio_reg_offset(GEN8_RING_PDP_LDW(base, i));
1044                         *cs++ = lower_32_bits(pd_daddr);
1045                 }
1046                 *cs++ = MI_NOOP;
1047                 intel_ring_advance(rq, cs);
1048         } else {
1049                 /* ppGTT is not part of the legacy context image */
1050                 gen6_ppgtt_pin(i915_vm_to_ppgtt(vm));
1051         }
1052
1053         return 0;
1054 }
1055
1056 static bool skip_ppgtt_update(struct intel_context *ce, void *data)
1057 {
1058         if (HAS_LOGICAL_RING_CONTEXTS(ce->engine->i915))
1059                 return !ce->state;
1060         else
1061                 return !atomic_read(&ce->pin_count);
1062 }
1063
1064 static int set_ppgtt(struct drm_i915_file_private *file_priv,
1065                      struct i915_gem_context *ctx,
1066                      struct drm_i915_gem_context_param *args)
1067 {
1068         struct i915_address_space *vm, *old;
1069         int err;
1070
1071         if (args->size)
1072                 return -EINVAL;
1073
1074         if (!ctx->vm)
1075                 return -ENODEV;
1076
1077         if (upper_32_bits(args->value))
1078                 return -ENOENT;
1079
1080         err = mutex_lock_interruptible(&file_priv->vm_idr_lock);
1081         if (err)
1082                 return err;
1083
1084         vm = idr_find(&file_priv->vm_idr, args->value);
1085         if (vm)
1086                 i915_vm_get(vm);
1087         mutex_unlock(&file_priv->vm_idr_lock);
1088         if (!vm)
1089                 return -ENOENT;
1090
1091         err = mutex_lock_interruptible(&ctx->i915->drm.struct_mutex);
1092         if (err)
1093                 goto out;
1094
1095         if (vm == ctx->vm)
1096                 goto unlock;
1097
1098         /* Teardown the existing obj:vma cache, it will have to be rebuilt. */
1099         mutex_lock(&ctx->mutex);
1100         lut_close(ctx);
1101         mutex_unlock(&ctx->mutex);
1102
1103         old = __set_ppgtt(ctx, vm);
1104
1105         /*
1106          * We need to flush any requests using the current ppgtt before
1107          * we release it as the requests do not hold a reference themselves,
1108          * only indirectly through the context.
1109          */
1110         err = context_barrier_task(ctx, ALL_ENGINES,
1111                                    skip_ppgtt_update,
1112                                    emit_ppgtt_update,
1113                                    set_ppgtt_barrier,
1114                                    old);
1115         if (err) {
1116                 ctx->vm = old;
1117                 ctx->desc_template = default_desc_template(ctx->i915, old);
1118                 i915_vm_put(vm);
1119         }
1120
1121 unlock:
1122         mutex_unlock(&ctx->i915->drm.struct_mutex);
1123
1124 out:
1125         i915_vm_put(vm);
1126         return err;
1127 }
1128
1129 static int gen8_emit_rpcs_config(struct i915_request *rq,
1130                                  struct intel_context *ce,
1131                                  struct intel_sseu sseu)
1132 {
1133         u64 offset;
1134         u32 *cs;
1135
1136         cs = intel_ring_begin(rq, 4);
1137         if (IS_ERR(cs))
1138                 return PTR_ERR(cs);
1139
1140         offset = i915_ggtt_offset(ce->state) +
1141                  LRC_STATE_PN * PAGE_SIZE +
1142                  (CTX_R_PWR_CLK_STATE + 1) * 4;
1143
1144         *cs++ = MI_STORE_DWORD_IMM_GEN4 | MI_USE_GGTT;
1145         *cs++ = lower_32_bits(offset);
1146         *cs++ = upper_32_bits(offset);
1147         *cs++ = intel_sseu_make_rpcs(rq->i915, &sseu);
1148
1149         intel_ring_advance(rq, cs);
1150
1151         return 0;
1152 }
1153
1154 static int
1155 gen8_modify_rpcs(struct intel_context *ce, struct intel_sseu sseu)
1156 {
1157         struct i915_request *rq;
1158         int ret;
1159
1160         lockdep_assert_held(&ce->pin_mutex);
1161
1162         /*
1163          * If the context is not idle, we have to submit an ordered request to
1164          * modify its context image via the kernel context (writing to our own
1165          * image, or into the registers directory, does not stick). Pristine
1166          * and idle contexts will be configured on pinning.
1167          */
1168         if (!intel_context_is_pinned(ce))
1169                 return 0;
1170
1171         rq = i915_request_create(ce->engine->kernel_context);
1172         if (IS_ERR(rq))
1173                 return PTR_ERR(rq);
1174
1175         /* Serialise with the remote context */
1176         ret = intel_context_prepare_remote_request(ce, rq);
1177         if (ret == 0)
1178                 ret = gen8_emit_rpcs_config(rq, ce, sseu);
1179
1180         i915_request_add(rq);
1181         return ret;
1182 }
1183
1184 static int
1185 __intel_context_reconfigure_sseu(struct intel_context *ce,
1186                                  struct intel_sseu sseu)
1187 {
1188         int ret;
1189
1190         GEM_BUG_ON(INTEL_GEN(ce->gem_context->i915) < 8);
1191
1192         ret = intel_context_lock_pinned(ce);
1193         if (ret)
1194                 return ret;
1195
1196         /* Nothing to do if unmodified. */
1197         if (!memcmp(&ce->sseu, &sseu, sizeof(sseu)))
1198                 goto unlock;
1199
1200         ret = gen8_modify_rpcs(ce, sseu);
1201         if (!ret)
1202                 ce->sseu = sseu;
1203
1204 unlock:
1205         intel_context_unlock_pinned(ce);
1206         return ret;
1207 }
1208
1209 static int
1210 intel_context_reconfigure_sseu(struct intel_context *ce, struct intel_sseu sseu)
1211 {
1212         struct drm_i915_private *i915 = ce->gem_context->i915;
1213         int ret;
1214
1215         ret = mutex_lock_interruptible(&i915->drm.struct_mutex);
1216         if (ret)
1217                 return ret;
1218
1219         ret = __intel_context_reconfigure_sseu(ce, sseu);
1220
1221         mutex_unlock(&i915->drm.struct_mutex);
1222
1223         return ret;
1224 }
1225
1226 static int
1227 user_to_context_sseu(struct drm_i915_private *i915,
1228                      const struct drm_i915_gem_context_param_sseu *user,
1229                      struct intel_sseu *context)
1230 {
1231         const struct sseu_dev_info *device = &RUNTIME_INFO(i915)->sseu;
1232
1233         /* No zeros in any field. */
1234         if (!user->slice_mask || !user->subslice_mask ||
1235             !user->min_eus_per_subslice || !user->max_eus_per_subslice)
1236                 return -EINVAL;
1237
1238         /* Max > min. */
1239         if (user->max_eus_per_subslice < user->min_eus_per_subslice)
1240                 return -EINVAL;
1241
1242         /*
1243          * Some future proofing on the types since the uAPI is wider than the
1244          * current internal implementation.
1245          */
1246         if (overflows_type(user->slice_mask, context->slice_mask) ||
1247             overflows_type(user->subslice_mask, context->subslice_mask) ||
1248             overflows_type(user->min_eus_per_subslice,
1249                            context->min_eus_per_subslice) ||
1250             overflows_type(user->max_eus_per_subslice,
1251                            context->max_eus_per_subslice))
1252                 return -EINVAL;
1253
1254         /* Check validity against hardware. */
1255         if (user->slice_mask & ~device->slice_mask)
1256                 return -EINVAL;
1257
1258         if (user->subslice_mask & ~device->subslice_mask[0])
1259                 return -EINVAL;
1260
1261         if (user->max_eus_per_subslice > device->max_eus_per_subslice)
1262                 return -EINVAL;
1263
1264         context->slice_mask = user->slice_mask;
1265         context->subslice_mask = user->subslice_mask;
1266         context->min_eus_per_subslice = user->min_eus_per_subslice;
1267         context->max_eus_per_subslice = user->max_eus_per_subslice;
1268
1269         /* Part specific restrictions. */
1270         if (IS_GEN(i915, 11)) {
1271                 unsigned int hw_s = hweight8(device->slice_mask);
1272                 unsigned int hw_ss_per_s = hweight8(device->subslice_mask[0]);
1273                 unsigned int req_s = hweight8(context->slice_mask);
1274                 unsigned int req_ss = hweight8(context->subslice_mask);
1275
1276                 /*
1277                  * Only full subslice enablement is possible if more than one
1278                  * slice is turned on.
1279                  */
1280                 if (req_s > 1 && req_ss != hw_ss_per_s)
1281                         return -EINVAL;
1282
1283                 /*
1284                  * If more than four (SScount bitfield limit) subslices are
1285                  * requested then the number has to be even.
1286                  */
1287                 if (req_ss > 4 && (req_ss & 1))
1288                         return -EINVAL;
1289
1290                 /*
1291                  * If only one slice is enabled and subslice count is below the
1292                  * device full enablement, it must be at most half of the all
1293                  * available subslices.
1294                  */
1295                 if (req_s == 1 && req_ss < hw_ss_per_s &&
1296                     req_ss > (hw_ss_per_s / 2))
1297                         return -EINVAL;
1298
1299                 /* ABI restriction - VME use case only. */
1300
1301                 /* All slices or one slice only. */
1302                 if (req_s != 1 && req_s != hw_s)
1303                         return -EINVAL;
1304
1305                 /*
1306                  * Half subslices or full enablement only when one slice is
1307                  * enabled.
1308                  */
1309                 if (req_s == 1 &&
1310                     (req_ss != hw_ss_per_s && req_ss != (hw_ss_per_s / 2)))
1311                         return -EINVAL;
1312
1313                 /* No EU configuration changes. */
1314                 if ((user->min_eus_per_subslice !=
1315                      device->max_eus_per_subslice) ||
1316                     (user->max_eus_per_subslice !=
1317                      device->max_eus_per_subslice))
1318                         return -EINVAL;
1319         }
1320
1321         return 0;
1322 }
1323
1324 static int set_sseu(struct i915_gem_context *ctx,
1325                     struct drm_i915_gem_context_param *args)
1326 {
1327         struct drm_i915_private *i915 = ctx->i915;
1328         struct drm_i915_gem_context_param_sseu user_sseu;
1329         struct intel_context *ce;
1330         struct intel_sseu sseu;
1331         unsigned long lookup;
1332         int ret;
1333
1334         if (args->size < sizeof(user_sseu))
1335                 return -EINVAL;
1336
1337         if (!IS_GEN(i915, 11))
1338                 return -ENODEV;
1339
1340         if (copy_from_user(&user_sseu, u64_to_user_ptr(args->value),
1341                            sizeof(user_sseu)))
1342                 return -EFAULT;
1343
1344         if (user_sseu.rsvd)
1345                 return -EINVAL;
1346
1347         if (user_sseu.flags & ~(I915_CONTEXT_SSEU_FLAG_ENGINE_INDEX))
1348                 return -EINVAL;
1349
1350         lookup = 0;
1351         if (user_sseu.flags & I915_CONTEXT_SSEU_FLAG_ENGINE_INDEX)
1352                 lookup |= LOOKUP_USER_INDEX;
1353
1354         ce = lookup_user_engine(ctx, lookup, &user_sseu.engine);
1355         if (IS_ERR(ce))
1356                 return PTR_ERR(ce);
1357
1358         /* Only render engine supports RPCS configuration. */
1359         if (ce->engine->class != RENDER_CLASS) {
1360                 ret = -ENODEV;
1361                 goto out_ce;
1362         }
1363
1364         ret = user_to_context_sseu(i915, &user_sseu, &sseu);
1365         if (ret)
1366                 goto out_ce;
1367
1368         ret = intel_context_reconfigure_sseu(ce, sseu);
1369         if (ret)
1370                 goto out_ce;
1371
1372         args->size = sizeof(user_sseu);
1373
1374 out_ce:
1375         intel_context_put(ce);
1376         return ret;
1377 }
1378
1379 struct set_engines {
1380         struct i915_gem_context *ctx;
1381         struct i915_gem_engines *engines;
1382 };
1383
1384 static int
1385 set_engines__load_balance(struct i915_user_extension __user *base, void *data)
1386 {
1387         struct i915_context_engines_load_balance __user *ext =
1388                 container_of_user(base, typeof(*ext), base);
1389         const struct set_engines *set = data;
1390         struct intel_engine_cs *stack[16];
1391         struct intel_engine_cs **siblings;
1392         struct intel_context *ce;
1393         u16 num_siblings, idx;
1394         unsigned int n;
1395         int err;
1396
1397         if (!HAS_EXECLISTS(set->ctx->i915))
1398                 return -ENODEV;
1399
1400         if (USES_GUC_SUBMISSION(set->ctx->i915))
1401                 return -ENODEV; /* not implement yet */
1402
1403         if (get_user(idx, &ext->engine_index))
1404                 return -EFAULT;
1405
1406         if (idx >= set->engines->num_engines) {
1407                 DRM_DEBUG("Invalid placement value, %d >= %d\n",
1408                           idx, set->engines->num_engines);
1409                 return -EINVAL;
1410         }
1411
1412         idx = array_index_nospec(idx, set->engines->num_engines);
1413         if (set->engines->engines[idx]) {
1414                 DRM_DEBUG("Invalid placement[%d], already occupied\n", idx);
1415                 return -EEXIST;
1416         }
1417
1418         if (get_user(num_siblings, &ext->num_siblings))
1419                 return -EFAULT;
1420
1421         err = check_user_mbz(&ext->flags);
1422         if (err)
1423                 return err;
1424
1425         err = check_user_mbz(&ext->mbz64);
1426         if (err)
1427                 return err;
1428
1429         siblings = stack;
1430         if (num_siblings > ARRAY_SIZE(stack)) {
1431                 siblings = kmalloc_array(num_siblings,
1432                                          sizeof(*siblings),
1433                                          GFP_KERNEL);
1434                 if (!siblings)
1435                         return -ENOMEM;
1436         }
1437
1438         for (n = 0; n < num_siblings; n++) {
1439                 struct i915_engine_class_instance ci;
1440
1441                 if (copy_from_user(&ci, &ext->engines[n], sizeof(ci))) {
1442                         err = -EFAULT;
1443                         goto out_siblings;
1444                 }
1445
1446                 siblings[n] = intel_engine_lookup_user(set->ctx->i915,
1447                                                        ci.engine_class,
1448                                                        ci.engine_instance);
1449                 if (!siblings[n]) {
1450                         DRM_DEBUG("Invalid sibling[%d]: { class:%d, inst:%d }\n",
1451                                   n, ci.engine_class, ci.engine_instance);
1452                         err = -EINVAL;
1453                         goto out_siblings;
1454                 }
1455         }
1456
1457         ce = intel_execlists_create_virtual(set->ctx, siblings, n);
1458         if (IS_ERR(ce)) {
1459                 err = PTR_ERR(ce);
1460                 goto out_siblings;
1461         }
1462
1463         if (cmpxchg(&set->engines->engines[idx], NULL, ce)) {
1464                 intel_context_put(ce);
1465                 err = -EEXIST;
1466                 goto out_siblings;
1467         }
1468
1469 out_siblings:
1470         if (siblings != stack)
1471                 kfree(siblings);
1472
1473         return err;
1474 }
1475
1476 static int
1477 set_engines__bond(struct i915_user_extension __user *base, void *data)
1478 {
1479         struct i915_context_engines_bond __user *ext =
1480                 container_of_user(base, typeof(*ext), base);
1481         const struct set_engines *set = data;
1482         struct i915_engine_class_instance ci;
1483         struct intel_engine_cs *virtual;
1484         struct intel_engine_cs *master;
1485         u16 idx, num_bonds;
1486         int err, n;
1487
1488         if (get_user(idx, &ext->virtual_index))
1489                 return -EFAULT;
1490
1491         if (idx >= set->engines->num_engines) {
1492                 DRM_DEBUG("Invalid index for virtual engine: %d >= %d\n",
1493                           idx, set->engines->num_engines);
1494                 return -EINVAL;
1495         }
1496
1497         idx = array_index_nospec(idx, set->engines->num_engines);
1498         if (!set->engines->engines[idx]) {
1499                 DRM_DEBUG("Invalid engine at %d\n", idx);
1500                 return -EINVAL;
1501         }
1502         virtual = set->engines->engines[idx]->engine;
1503
1504         err = check_user_mbz(&ext->flags);
1505         if (err)
1506                 return err;
1507
1508         for (n = 0; n < ARRAY_SIZE(ext->mbz64); n++) {
1509                 err = check_user_mbz(&ext->mbz64[n]);
1510                 if (err)
1511                         return err;
1512         }
1513
1514         if (copy_from_user(&ci, &ext->master, sizeof(ci)))
1515                 return -EFAULT;
1516
1517         master = intel_engine_lookup_user(set->ctx->i915,
1518                                           ci.engine_class, ci.engine_instance);
1519         if (!master) {
1520                 DRM_DEBUG("Unrecognised master engine: { class:%u, instance:%u }\n",
1521                           ci.engine_class, ci.engine_instance);
1522                 return -EINVAL;
1523         }
1524
1525         if (get_user(num_bonds, &ext->num_bonds))
1526                 return -EFAULT;
1527
1528         for (n = 0; n < num_bonds; n++) {
1529                 struct intel_engine_cs *bond;
1530
1531                 if (copy_from_user(&ci, &ext->engines[n], sizeof(ci)))
1532                         return -EFAULT;
1533
1534                 bond = intel_engine_lookup_user(set->ctx->i915,
1535                                                 ci.engine_class,
1536                                                 ci.engine_instance);
1537                 if (!bond) {
1538                         DRM_DEBUG("Unrecognised engine[%d] for bonding: { class:%d, instance: %d }\n",
1539                                   n, ci.engine_class, ci.engine_instance);
1540                         return -EINVAL;
1541                 }
1542
1543                 /*
1544                  * A non-virtual engine has no siblings to choose between; and
1545                  * a submit fence will always be directed to the one engine.
1546                  */
1547                 if (intel_engine_is_virtual(virtual)) {
1548                         err = intel_virtual_engine_attach_bond(virtual,
1549                                                                master,
1550                                                                bond);
1551                         if (err)
1552                                 return err;
1553                 }
1554         }
1555
1556         return 0;
1557 }
1558
1559 static const i915_user_extension_fn set_engines__extensions[] = {
1560         [I915_CONTEXT_ENGINES_EXT_LOAD_BALANCE] = set_engines__load_balance,
1561         [I915_CONTEXT_ENGINES_EXT_BOND] = set_engines__bond,
1562 };
1563
1564 static int
1565 set_engines(struct i915_gem_context *ctx,
1566             const struct drm_i915_gem_context_param *args)
1567 {
1568         struct i915_context_param_engines __user *user =
1569                 u64_to_user_ptr(args->value);
1570         struct set_engines set = { .ctx = ctx };
1571         unsigned int num_engines, n;
1572         u64 extensions;
1573         int err;
1574
1575         if (!args->size) { /* switch back to legacy user_ring_map */
1576                 if (!i915_gem_context_user_engines(ctx))
1577                         return 0;
1578
1579                 set.engines = default_engines(ctx);
1580                 if (IS_ERR(set.engines))
1581                         return PTR_ERR(set.engines);
1582
1583                 goto replace;
1584         }
1585
1586         BUILD_BUG_ON(!IS_ALIGNED(sizeof(*user), sizeof(*user->engines)));
1587         if (args->size < sizeof(*user) ||
1588             !IS_ALIGNED(args->size, sizeof(*user->engines))) {
1589                 DRM_DEBUG("Invalid size for engine array: %d\n",
1590                           args->size);
1591                 return -EINVAL;
1592         }
1593
1594         /*
1595          * Note that I915_EXEC_RING_MASK limits execbuf to only using the
1596          * first 64 engines defined here.
1597          */
1598         num_engines = (args->size - sizeof(*user)) / sizeof(*user->engines);
1599
1600         set.engines = kmalloc(struct_size(set.engines, engines, num_engines),
1601                               GFP_KERNEL);
1602         if (!set.engines)
1603                 return -ENOMEM;
1604
1605         init_rcu_head(&set.engines->rcu);
1606         for (n = 0; n < num_engines; n++) {
1607                 struct i915_engine_class_instance ci;
1608                 struct intel_engine_cs *engine;
1609
1610                 if (copy_from_user(&ci, &user->engines[n], sizeof(ci))) {
1611                         __free_engines(set.engines, n);
1612                         return -EFAULT;
1613                 }
1614
1615                 if (ci.engine_class == (u16)I915_ENGINE_CLASS_INVALID &&
1616                     ci.engine_instance == (u16)I915_ENGINE_CLASS_INVALID_NONE) {
1617                         set.engines->engines[n] = NULL;
1618                         continue;
1619                 }
1620
1621                 engine = intel_engine_lookup_user(ctx->i915,
1622                                                   ci.engine_class,
1623                                                   ci.engine_instance);
1624                 if (!engine) {
1625                         DRM_DEBUG("Invalid engine[%d]: { class:%d, instance:%d }\n",
1626                                   n, ci.engine_class, ci.engine_instance);
1627                         __free_engines(set.engines, n);
1628                         return -ENOENT;
1629                 }
1630
1631                 set.engines->engines[n] = intel_context_create(ctx, engine);
1632                 if (!set.engines->engines[n]) {
1633                         __free_engines(set.engines, n);
1634                         return -ENOMEM;
1635                 }
1636         }
1637         set.engines->num_engines = num_engines;
1638
1639         err = -EFAULT;
1640         if (!get_user(extensions, &user->extensions))
1641                 err = i915_user_extensions(u64_to_user_ptr(extensions),
1642                                            set_engines__extensions,
1643                                            ARRAY_SIZE(set_engines__extensions),
1644                                            &set);
1645         if (err) {
1646                 free_engines(set.engines);
1647                 return err;
1648         }
1649
1650 replace:
1651         mutex_lock(&ctx->engines_mutex);
1652         if (args->size)
1653                 i915_gem_context_set_user_engines(ctx);
1654         else
1655                 i915_gem_context_clear_user_engines(ctx);
1656         rcu_swap_protected(ctx->engines, set.engines, 1);
1657         mutex_unlock(&ctx->engines_mutex);
1658
1659         call_rcu(&set.engines->rcu, free_engines_rcu);
1660
1661         return 0;
1662 }
1663
1664 static struct i915_gem_engines *
1665 __copy_engines(struct i915_gem_engines *e)
1666 {
1667         struct i915_gem_engines *copy;
1668         unsigned int n;
1669
1670         copy = kmalloc(struct_size(e, engines, e->num_engines), GFP_KERNEL);
1671         if (!copy)
1672                 return ERR_PTR(-ENOMEM);
1673
1674         init_rcu_head(&copy->rcu);
1675         for (n = 0; n < e->num_engines; n++) {
1676                 if (e->engines[n])
1677                         copy->engines[n] = intel_context_get(e->engines[n]);
1678                 else
1679                         copy->engines[n] = NULL;
1680         }
1681         copy->num_engines = n;
1682
1683         return copy;
1684 }
1685
1686 static int
1687 get_engines(struct i915_gem_context *ctx,
1688             struct drm_i915_gem_context_param *args)
1689 {
1690         struct i915_context_param_engines __user *user;
1691         struct i915_gem_engines *e;
1692         size_t n, count, size;
1693         int err = 0;
1694
1695         err = mutex_lock_interruptible(&ctx->engines_mutex);
1696         if (err)
1697                 return err;
1698
1699         e = NULL;
1700         if (i915_gem_context_user_engines(ctx))
1701                 e = __copy_engines(i915_gem_context_engines(ctx));
1702         mutex_unlock(&ctx->engines_mutex);
1703         if (IS_ERR_OR_NULL(e)) {
1704                 args->size = 0;
1705                 return PTR_ERR_OR_ZERO(e);
1706         }
1707
1708         count = e->num_engines;
1709
1710         /* Be paranoid in case we have an impedance mismatch */
1711         if (!check_struct_size(user, engines, count, &size)) {
1712                 err = -EINVAL;
1713                 goto err_free;
1714         }
1715         if (overflows_type(size, args->size)) {
1716                 err = -EINVAL;
1717                 goto err_free;
1718         }
1719
1720         if (!args->size) {
1721                 args->size = size;
1722                 goto err_free;
1723         }
1724
1725         if (args->size < size) {
1726                 err = -EINVAL;
1727                 goto err_free;
1728         }
1729
1730         user = u64_to_user_ptr(args->value);
1731         if (!access_ok(user, size)) {
1732                 err = -EFAULT;
1733                 goto err_free;
1734         }
1735
1736         if (put_user(0, &user->extensions)) {
1737                 err = -EFAULT;
1738                 goto err_free;
1739         }
1740
1741         for (n = 0; n < count; n++) {
1742                 struct i915_engine_class_instance ci = {
1743                         .engine_class = I915_ENGINE_CLASS_INVALID,
1744                         .engine_instance = I915_ENGINE_CLASS_INVALID_NONE,
1745                 };
1746
1747                 if (e->engines[n]) {
1748                         ci.engine_class = e->engines[n]->engine->uabi_class;
1749                         ci.engine_instance = e->engines[n]->engine->instance;
1750                 }
1751
1752                 if (copy_to_user(&user->engines[n], &ci, sizeof(ci))) {
1753                         err = -EFAULT;
1754                         goto err_free;
1755                 }
1756         }
1757
1758         args->size = size;
1759
1760 err_free:
1761         free_engines(e);
1762         return err;
1763 }
1764
1765 static int ctx_setparam(struct drm_i915_file_private *fpriv,
1766                         struct i915_gem_context *ctx,
1767                         struct drm_i915_gem_context_param *args)
1768 {
1769         int ret = 0;
1770
1771         switch (args->param) {
1772         case I915_CONTEXT_PARAM_NO_ZEROMAP:
1773                 if (args->size)
1774                         ret = -EINVAL;
1775                 else if (args->value)
1776                         set_bit(UCONTEXT_NO_ZEROMAP, &ctx->user_flags);
1777                 else
1778                         clear_bit(UCONTEXT_NO_ZEROMAP, &ctx->user_flags);
1779                 break;
1780
1781         case I915_CONTEXT_PARAM_NO_ERROR_CAPTURE:
1782                 if (args->size)
1783                         ret = -EINVAL;
1784                 else if (args->value)
1785                         i915_gem_context_set_no_error_capture(ctx);
1786                 else
1787                         i915_gem_context_clear_no_error_capture(ctx);
1788                 break;
1789
1790         case I915_CONTEXT_PARAM_BANNABLE:
1791                 if (args->size)
1792                         ret = -EINVAL;
1793                 else if (!capable(CAP_SYS_ADMIN) && !args->value)
1794                         ret = -EPERM;
1795                 else if (args->value)
1796                         i915_gem_context_set_bannable(ctx);
1797                 else
1798                         i915_gem_context_clear_bannable(ctx);
1799                 break;
1800
1801         case I915_CONTEXT_PARAM_RECOVERABLE:
1802                 if (args->size)
1803                         ret = -EINVAL;
1804                 else if (args->value)
1805                         i915_gem_context_set_recoverable(ctx);
1806                 else
1807                         i915_gem_context_clear_recoverable(ctx);
1808                 break;
1809
1810         case I915_CONTEXT_PARAM_PRIORITY:
1811                 {
1812                         s64 priority = args->value;
1813
1814                         if (args->size)
1815                                 ret = -EINVAL;
1816                         else if (!(ctx->i915->caps.scheduler & I915_SCHEDULER_CAP_PRIORITY))
1817                                 ret = -ENODEV;
1818                         else if (priority > I915_CONTEXT_MAX_USER_PRIORITY ||
1819                                  priority < I915_CONTEXT_MIN_USER_PRIORITY)
1820                                 ret = -EINVAL;
1821                         else if (priority > I915_CONTEXT_DEFAULT_PRIORITY &&
1822                                  !capable(CAP_SYS_NICE))
1823                                 ret = -EPERM;
1824                         else
1825                                 ctx->sched.priority =
1826                                         I915_USER_PRIORITY(priority);
1827                 }
1828                 break;
1829
1830         case I915_CONTEXT_PARAM_SSEU:
1831                 ret = set_sseu(ctx, args);
1832                 break;
1833
1834         case I915_CONTEXT_PARAM_VM:
1835                 ret = set_ppgtt(fpriv, ctx, args);
1836                 break;
1837
1838         case I915_CONTEXT_PARAM_ENGINES:
1839                 ret = set_engines(ctx, args);
1840                 break;
1841
1842         case I915_CONTEXT_PARAM_BAN_PERIOD:
1843         default:
1844                 ret = -EINVAL;
1845                 break;
1846         }
1847
1848         return ret;
1849 }
1850
1851 struct create_ext {
1852         struct i915_gem_context *ctx;
1853         struct drm_i915_file_private *fpriv;
1854 };
1855
1856 static int create_setparam(struct i915_user_extension __user *ext, void *data)
1857 {
1858         struct drm_i915_gem_context_create_ext_setparam local;
1859         const struct create_ext *arg = data;
1860
1861         if (copy_from_user(&local, ext, sizeof(local)))
1862                 return -EFAULT;
1863
1864         if (local.param.ctx_id)
1865                 return -EINVAL;
1866
1867         return ctx_setparam(arg->fpriv, arg->ctx, &local.param);
1868 }
1869
1870 static int clone_engines(struct i915_gem_context *dst,
1871                          struct i915_gem_context *src)
1872 {
1873         struct i915_gem_engines *e = i915_gem_context_lock_engines(src);
1874         struct i915_gem_engines *clone;
1875         bool user_engines;
1876         unsigned long n;
1877
1878         clone = kmalloc(struct_size(e, engines, e->num_engines), GFP_KERNEL);
1879         if (!clone)
1880                 goto err_unlock;
1881
1882         init_rcu_head(&clone->rcu);
1883         for (n = 0; n < e->num_engines; n++) {
1884                 struct intel_engine_cs *engine;
1885
1886                 if (!e->engines[n]) {
1887                         clone->engines[n] = NULL;
1888                         continue;
1889                 }
1890                 engine = e->engines[n]->engine;
1891
1892                 /*
1893                  * Virtual engines are singletons; they can only exist
1894                  * inside a single context, because they embed their
1895                  * HW context... As each virtual context implies a single
1896                  * timeline (each engine can only dequeue a single request
1897                  * at any time), it would be surprising for two contexts
1898                  * to use the same engine. So let's create a copy of
1899                  * the virtual engine instead.
1900                  */
1901                 if (intel_engine_is_virtual(engine))
1902                         clone->engines[n] =
1903                                 intel_execlists_clone_virtual(dst, engine);
1904                 else
1905                         clone->engines[n] = intel_context_create(dst, engine);
1906                 if (IS_ERR_OR_NULL(clone->engines[n])) {
1907                         __free_engines(clone, n);
1908                         goto err_unlock;
1909                 }
1910         }
1911         clone->num_engines = n;
1912
1913         user_engines = i915_gem_context_user_engines(src);
1914         i915_gem_context_unlock_engines(src);
1915
1916         free_engines(dst->engines);
1917         RCU_INIT_POINTER(dst->engines, clone);
1918         if (user_engines)
1919                 i915_gem_context_set_user_engines(dst);
1920         else
1921                 i915_gem_context_clear_user_engines(dst);
1922         return 0;
1923
1924 err_unlock:
1925         i915_gem_context_unlock_engines(src);
1926         return -ENOMEM;
1927 }
1928
1929 static int clone_flags(struct i915_gem_context *dst,
1930                        struct i915_gem_context *src)
1931 {
1932         dst->user_flags = src->user_flags;
1933         return 0;
1934 }
1935
1936 static int clone_schedattr(struct i915_gem_context *dst,
1937                            struct i915_gem_context *src)
1938 {
1939         dst->sched = src->sched;
1940         return 0;
1941 }
1942
1943 static int clone_sseu(struct i915_gem_context *dst,
1944                       struct i915_gem_context *src)
1945 {
1946         struct i915_gem_engines *e = i915_gem_context_lock_engines(src);
1947         struct i915_gem_engines *clone;
1948         unsigned long n;
1949         int err;
1950
1951         clone = dst->engines; /* no locking required; sole access */
1952         if (e->num_engines != clone->num_engines) {
1953                 err = -EINVAL;
1954                 goto unlock;
1955         }
1956
1957         for (n = 0; n < e->num_engines; n++) {
1958                 struct intel_context *ce = e->engines[n];
1959
1960                 if (clone->engines[n]->engine->class != ce->engine->class) {
1961                         /* Must have compatible engine maps! */
1962                         err = -EINVAL;
1963                         goto unlock;
1964                 }
1965
1966                 /* serialises with set_sseu */
1967                 err = intel_context_lock_pinned(ce);
1968                 if (err)
1969                         goto unlock;
1970
1971                 clone->engines[n]->sseu = ce->sseu;
1972                 intel_context_unlock_pinned(ce);
1973         }
1974
1975         err = 0;
1976 unlock:
1977         i915_gem_context_unlock_engines(src);
1978         return err;
1979 }
1980
1981 static int clone_timeline(struct i915_gem_context *dst,
1982                           struct i915_gem_context *src)
1983 {
1984         if (src->timeline) {
1985                 GEM_BUG_ON(src->timeline == dst->timeline);
1986
1987                 if (dst->timeline)
1988                         intel_timeline_put(dst->timeline);
1989                 dst->timeline = intel_timeline_get(src->timeline);
1990         }
1991
1992         return 0;
1993 }
1994
1995 static int clone_vm(struct i915_gem_context *dst,
1996                     struct i915_gem_context *src)
1997 {
1998         struct i915_address_space *vm;
1999
2000         rcu_read_lock();
2001         do {
2002                 vm = READ_ONCE(src->vm);
2003                 if (!vm)
2004                         break;
2005
2006                 if (!kref_get_unless_zero(&vm->ref))
2007                         continue;
2008
2009                 /*
2010                  * This ppgtt may have be reallocated between
2011                  * the read and the kref, and reassigned to a third
2012                  * context. In order to avoid inadvertent sharing
2013                  * of this ppgtt with that third context (and not
2014                  * src), we have to confirm that we have the same
2015                  * ppgtt after passing through the strong memory
2016                  * barrier implied by a successful
2017                  * kref_get_unless_zero().
2018                  *
2019                  * Once we have acquired the current ppgtt of src,
2020                  * we no longer care if it is released from src, as
2021                  * it cannot be reallocated elsewhere.
2022                  */
2023
2024                 if (vm == READ_ONCE(src->vm))
2025                         break;
2026
2027                 i915_vm_put(vm);
2028         } while (1);
2029         rcu_read_unlock();
2030
2031         if (vm) {
2032                 __assign_ppgtt(dst, vm);
2033                 i915_vm_put(vm);
2034         }
2035
2036         return 0;
2037 }
2038
2039 static int create_clone(struct i915_user_extension __user *ext, void *data)
2040 {
2041         static int (* const fn[])(struct i915_gem_context *dst,
2042                                   struct i915_gem_context *src) = {
2043 #define MAP(x, y) [ilog2(I915_CONTEXT_CLONE_##x)] = y
2044                 MAP(ENGINES, clone_engines),
2045                 MAP(FLAGS, clone_flags),
2046                 MAP(SCHEDATTR, clone_schedattr),
2047                 MAP(SSEU, clone_sseu),
2048                 MAP(TIMELINE, clone_timeline),
2049                 MAP(VM, clone_vm),
2050 #undef MAP
2051         };
2052         struct drm_i915_gem_context_create_ext_clone local;
2053         const struct create_ext *arg = data;
2054         struct i915_gem_context *dst = arg->ctx;
2055         struct i915_gem_context *src;
2056         int err, bit;
2057
2058         if (copy_from_user(&local, ext, sizeof(local)))
2059                 return -EFAULT;
2060
2061         BUILD_BUG_ON(GENMASK(BITS_PER_TYPE(local.flags) - 1, ARRAY_SIZE(fn)) !=
2062                      I915_CONTEXT_CLONE_UNKNOWN);
2063
2064         if (local.flags & I915_CONTEXT_CLONE_UNKNOWN)
2065                 return -EINVAL;
2066
2067         if (local.rsvd)
2068                 return -EINVAL;
2069
2070         rcu_read_lock();
2071         src = __i915_gem_context_lookup_rcu(arg->fpriv, local.clone_id);
2072         rcu_read_unlock();
2073         if (!src)
2074                 return -ENOENT;
2075
2076         GEM_BUG_ON(src == dst);
2077
2078         for (bit = 0; bit < ARRAY_SIZE(fn); bit++) {
2079                 if (!(local.flags & BIT(bit)))
2080                         continue;
2081
2082                 err = fn[bit](dst, src);
2083                 if (err)
2084                         return err;
2085         }
2086
2087         return 0;
2088 }
2089
2090 static const i915_user_extension_fn create_extensions[] = {
2091         [I915_CONTEXT_CREATE_EXT_SETPARAM] = create_setparam,
2092         [I915_CONTEXT_CREATE_EXT_CLONE] = create_clone,
2093 };
2094
2095 static bool client_is_banned(struct drm_i915_file_private *file_priv)
2096 {
2097         return atomic_read(&file_priv->ban_score) >= I915_CLIENT_SCORE_BANNED;
2098 }
2099
2100 int i915_gem_context_create_ioctl(struct drm_device *dev, void *data,
2101                                   struct drm_file *file)
2102 {
2103         struct drm_i915_private *i915 = to_i915(dev);
2104         struct drm_i915_gem_context_create_ext *args = data;
2105         struct create_ext ext_data;
2106         int ret;
2107
2108         if (!DRIVER_CAPS(i915)->has_logical_contexts)
2109                 return -ENODEV;
2110
2111         if (args->flags & I915_CONTEXT_CREATE_FLAGS_UNKNOWN)
2112                 return -EINVAL;
2113
2114         ret = intel_gt_terminally_wedged(&i915->gt);
2115         if (ret)
2116                 return ret;
2117
2118         ext_data.fpriv = file->driver_priv;
2119         if (client_is_banned(ext_data.fpriv)) {
2120                 DRM_DEBUG("client %s[%d] banned from creating ctx\n",
2121                           current->comm,
2122                           pid_nr(get_task_pid(current, PIDTYPE_PID)));
2123                 return -EIO;
2124         }
2125
2126         ret = i915_mutex_lock_interruptible(dev);
2127         if (ret)
2128                 return ret;
2129
2130         ext_data.ctx = i915_gem_create_context(i915, args->flags);
2131         mutex_unlock(&dev->struct_mutex);
2132         if (IS_ERR(ext_data.ctx))
2133                 return PTR_ERR(ext_data.ctx);
2134
2135         if (args->flags & I915_CONTEXT_CREATE_FLAGS_USE_EXTENSIONS) {
2136                 ret = i915_user_extensions(u64_to_user_ptr(args->extensions),
2137                                            create_extensions,
2138                                            ARRAY_SIZE(create_extensions),
2139                                            &ext_data);
2140                 if (ret)
2141                         goto err_ctx;
2142         }
2143
2144         ret = gem_context_register(ext_data.ctx, ext_data.fpriv);
2145         if (ret < 0)
2146                 goto err_ctx;
2147
2148         args->ctx_id = ret;
2149         DRM_DEBUG("HW context %d created\n", args->ctx_id);
2150
2151         return 0;
2152
2153 err_ctx:
2154         context_close(ext_data.ctx);
2155         return ret;
2156 }
2157
2158 int i915_gem_context_destroy_ioctl(struct drm_device *dev, void *data,
2159                                    struct drm_file *file)
2160 {
2161         struct drm_i915_gem_context_destroy *args = data;
2162         struct drm_i915_file_private *file_priv = file->driver_priv;
2163         struct i915_gem_context *ctx;
2164
2165         if (args->pad != 0)
2166                 return -EINVAL;
2167
2168         if (!args->ctx_id)
2169                 return -ENOENT;
2170
2171         if (mutex_lock_interruptible(&file_priv->context_idr_lock))
2172                 return -EINTR;
2173
2174         ctx = idr_remove(&file_priv->context_idr, args->ctx_id);
2175         mutex_unlock(&file_priv->context_idr_lock);
2176         if (!ctx)
2177                 return -ENOENT;
2178
2179         context_close(ctx);
2180         return 0;
2181 }
2182
2183 static int get_sseu(struct i915_gem_context *ctx,
2184                     struct drm_i915_gem_context_param *args)
2185 {
2186         struct drm_i915_gem_context_param_sseu user_sseu;
2187         struct intel_context *ce;
2188         unsigned long lookup;
2189         int err;
2190
2191         if (args->size == 0)
2192                 goto out;
2193         else if (args->size < sizeof(user_sseu))
2194                 return -EINVAL;
2195
2196         if (copy_from_user(&user_sseu, u64_to_user_ptr(args->value),
2197                            sizeof(user_sseu)))
2198                 return -EFAULT;
2199
2200         if (user_sseu.rsvd)
2201                 return -EINVAL;
2202
2203         if (user_sseu.flags & ~(I915_CONTEXT_SSEU_FLAG_ENGINE_INDEX))
2204                 return -EINVAL;
2205
2206         lookup = 0;
2207         if (user_sseu.flags & I915_CONTEXT_SSEU_FLAG_ENGINE_INDEX)
2208                 lookup |= LOOKUP_USER_INDEX;
2209
2210         ce = lookup_user_engine(ctx, lookup, &user_sseu.engine);
2211         if (IS_ERR(ce))
2212                 return PTR_ERR(ce);
2213
2214         err = intel_context_lock_pinned(ce); /* serialises with set_sseu */
2215         if (err) {
2216                 intel_context_put(ce);
2217                 return err;
2218         }
2219
2220         user_sseu.slice_mask = ce->sseu.slice_mask;
2221         user_sseu.subslice_mask = ce->sseu.subslice_mask;
2222         user_sseu.min_eus_per_subslice = ce->sseu.min_eus_per_subslice;
2223         user_sseu.max_eus_per_subslice = ce->sseu.max_eus_per_subslice;
2224
2225         intel_context_unlock_pinned(ce);
2226         intel_context_put(ce);
2227
2228         if (copy_to_user(u64_to_user_ptr(args->value), &user_sseu,
2229                          sizeof(user_sseu)))
2230                 return -EFAULT;
2231
2232 out:
2233         args->size = sizeof(user_sseu);
2234
2235         return 0;
2236 }
2237
2238 int i915_gem_context_getparam_ioctl(struct drm_device *dev, void *data,
2239                                     struct drm_file *file)
2240 {
2241         struct drm_i915_file_private *file_priv = file->driver_priv;
2242         struct drm_i915_gem_context_param *args = data;
2243         struct i915_gem_context *ctx;
2244         int ret = 0;
2245
2246         ctx = i915_gem_context_lookup(file_priv, args->ctx_id);
2247         if (!ctx)
2248                 return -ENOENT;
2249
2250         switch (args->param) {
2251         case I915_CONTEXT_PARAM_NO_ZEROMAP:
2252                 args->size = 0;
2253                 args->value = test_bit(UCONTEXT_NO_ZEROMAP, &ctx->user_flags);
2254                 break;
2255
2256         case I915_CONTEXT_PARAM_GTT_SIZE:
2257                 args->size = 0;
2258                 if (ctx->vm)
2259                         args->value = ctx->vm->total;
2260                 else if (to_i915(dev)->ggtt.alias)
2261                         args->value = to_i915(dev)->ggtt.alias->vm.total;
2262                 else
2263                         args->value = to_i915(dev)->ggtt.vm.total;
2264                 break;
2265
2266         case I915_CONTEXT_PARAM_NO_ERROR_CAPTURE:
2267                 args->size = 0;
2268                 args->value = i915_gem_context_no_error_capture(ctx);
2269                 break;
2270
2271         case I915_CONTEXT_PARAM_BANNABLE:
2272                 args->size = 0;
2273                 args->value = i915_gem_context_is_bannable(ctx);
2274                 break;
2275
2276         case I915_CONTEXT_PARAM_RECOVERABLE:
2277                 args->size = 0;
2278                 args->value = i915_gem_context_is_recoverable(ctx);
2279                 break;
2280
2281         case I915_CONTEXT_PARAM_PRIORITY:
2282                 args->size = 0;
2283                 args->value = ctx->sched.priority >> I915_USER_PRIORITY_SHIFT;
2284                 break;
2285
2286         case I915_CONTEXT_PARAM_SSEU:
2287                 ret = get_sseu(ctx, args);
2288                 break;
2289
2290         case I915_CONTEXT_PARAM_VM:
2291                 ret = get_ppgtt(file_priv, ctx, args);
2292                 break;
2293
2294         case I915_CONTEXT_PARAM_ENGINES:
2295                 ret = get_engines(ctx, args);
2296                 break;
2297
2298         case I915_CONTEXT_PARAM_BAN_PERIOD:
2299         default:
2300                 ret = -EINVAL;
2301                 break;
2302         }
2303
2304         i915_gem_context_put(ctx);
2305         return ret;
2306 }
2307
2308 int i915_gem_context_setparam_ioctl(struct drm_device *dev, void *data,
2309                                     struct drm_file *file)
2310 {
2311         struct drm_i915_file_private *file_priv = file->driver_priv;
2312         struct drm_i915_gem_context_param *args = data;
2313         struct i915_gem_context *ctx;
2314         int ret;
2315
2316         ctx = i915_gem_context_lookup(file_priv, args->ctx_id);
2317         if (!ctx)
2318                 return -ENOENT;
2319
2320         ret = ctx_setparam(file_priv, ctx, args);
2321
2322         i915_gem_context_put(ctx);
2323         return ret;
2324 }
2325
2326 int i915_gem_context_reset_stats_ioctl(struct drm_device *dev,
2327                                        void *data, struct drm_file *file)
2328 {
2329         struct drm_i915_private *dev_priv = to_i915(dev);
2330         struct drm_i915_reset_stats *args = data;
2331         struct i915_gem_context *ctx;
2332         int ret;
2333
2334         if (args->flags || args->pad)
2335                 return -EINVAL;
2336
2337         ret = -ENOENT;
2338         rcu_read_lock();
2339         ctx = __i915_gem_context_lookup_rcu(file->driver_priv, args->ctx_id);
2340         if (!ctx)
2341                 goto out;
2342
2343         /*
2344          * We opt for unserialised reads here. This may result in tearing
2345          * in the extremely unlikely event of a GPU hang on this context
2346          * as we are querying them. If we need that extra layer of protection,
2347          * we should wrap the hangstats with a seqlock.
2348          */
2349
2350         if (capable(CAP_SYS_ADMIN))
2351                 args->reset_count = i915_reset_count(&dev_priv->gpu_error);
2352         else
2353                 args->reset_count = 0;
2354
2355         args->batch_active = atomic_read(&ctx->guilty_count);
2356         args->batch_pending = atomic_read(&ctx->active_count);
2357
2358         ret = 0;
2359 out:
2360         rcu_read_unlock();
2361         return ret;
2362 }
2363
2364 int __i915_gem_context_pin_hw_id(struct i915_gem_context *ctx)
2365 {
2366         struct drm_i915_private *i915 = ctx->i915;
2367         int err = 0;
2368
2369         mutex_lock(&i915->contexts.mutex);
2370
2371         GEM_BUG_ON(i915_gem_context_is_closed(ctx));
2372
2373         if (list_empty(&ctx->hw_id_link)) {
2374                 GEM_BUG_ON(atomic_read(&ctx->hw_id_pin_count));
2375
2376                 err = assign_hw_id(i915, &ctx->hw_id);
2377                 if (err)
2378                         goto out_unlock;
2379
2380                 list_add_tail(&ctx->hw_id_link, &i915->contexts.hw_id_list);
2381         }
2382
2383         GEM_BUG_ON(atomic_read(&ctx->hw_id_pin_count) == ~0u);
2384         atomic_inc(&ctx->hw_id_pin_count);
2385
2386 out_unlock:
2387         mutex_unlock(&i915->contexts.mutex);
2388         return err;
2389 }
2390
2391 /* GEM context-engines iterator: for_each_gem_engine() */
2392 struct intel_context *
2393 i915_gem_engines_iter_next(struct i915_gem_engines_iter *it)
2394 {
2395         const struct i915_gem_engines *e = it->engines;
2396         struct intel_context *ctx;
2397
2398         do {
2399                 if (it->idx >= e->num_engines)
2400                         return NULL;
2401
2402                 ctx = e->engines[it->idx++];
2403         } while (!ctx);
2404
2405         return ctx;
2406 }
2407
2408 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
2409 #include "selftests/mock_context.c"
2410 #include "selftests/i915_gem_context.c"
2411 #endif
2412
2413 static void i915_global_gem_context_shrink(void)
2414 {
2415         kmem_cache_shrink(global.slab_luts);
2416 }
2417
2418 static void i915_global_gem_context_exit(void)
2419 {
2420         kmem_cache_destroy(global.slab_luts);
2421 }
2422
2423 static struct i915_global_gem_context global = { {
2424         .shrink = i915_global_gem_context_shrink,
2425         .exit = i915_global_gem_context_exit,
2426 } };
2427
2428 int __init i915_global_gem_context_init(void)
2429 {
2430         global.slab_luts = KMEM_CACHE(i915_lut_handle, 0);
2431         if (!global.slab_luts)
2432                 return -ENOMEM;
2433
2434         i915_global_register(&global.base);
2435         return 0;
2436 }