]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/gpu/drm/i915/gem/i915_gem_context.c
Merge drm/drm-next into drm-intel-next-queued
[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 =
463                 default_desc_template(i915, &i915->mm.aliasing_ppgtt->vm);
464
465         for (i = 0; i < ARRAY_SIZE(ctx->hang_timestamp); i++)
466                 ctx->hang_timestamp[i] = jiffies - CONTEXT_FAST_HANG_JIFFIES;
467
468         return ctx;
469
470 err_free:
471         kfree(ctx);
472         return ERR_PTR(err);
473 }
474
475 static struct i915_address_space *
476 __set_ppgtt(struct i915_gem_context *ctx, struct i915_address_space *vm)
477 {
478         struct i915_address_space *old = ctx->vm;
479
480         ctx->vm = i915_vm_get(vm);
481         ctx->desc_template = default_desc_template(ctx->i915, vm);
482
483         return old;
484 }
485
486 static void __assign_ppgtt(struct i915_gem_context *ctx,
487                            struct i915_address_space *vm)
488 {
489         if (vm == ctx->vm)
490                 return;
491
492         vm = __set_ppgtt(ctx, vm);
493         if (vm)
494                 i915_vm_put(vm);
495 }
496
497 static struct i915_gem_context *
498 i915_gem_create_context(struct drm_i915_private *dev_priv, unsigned int flags)
499 {
500         struct i915_gem_context *ctx;
501
502         lockdep_assert_held(&dev_priv->drm.struct_mutex);
503
504         if (flags & I915_CONTEXT_CREATE_FLAGS_SINGLE_TIMELINE &&
505             !HAS_EXECLISTS(dev_priv))
506                 return ERR_PTR(-EINVAL);
507
508         /* Reap the most stale context */
509         contexts_free_first(dev_priv);
510
511         ctx = __create_context(dev_priv);
512         if (IS_ERR(ctx))
513                 return ctx;
514
515         if (HAS_FULL_PPGTT(dev_priv)) {
516                 struct i915_ppgtt *ppgtt;
517
518                 ppgtt = i915_ppgtt_create(dev_priv);
519                 if (IS_ERR(ppgtt)) {
520                         DRM_DEBUG_DRIVER("PPGTT setup failed (%ld)\n",
521                                          PTR_ERR(ppgtt));
522                         context_close(ctx);
523                         return ERR_CAST(ppgtt);
524                 }
525
526                 __assign_ppgtt(ctx, &ppgtt->vm);
527                 i915_vm_put(&ppgtt->vm);
528         }
529
530         if (flags & I915_CONTEXT_CREATE_FLAGS_SINGLE_TIMELINE) {
531                 struct intel_timeline *timeline;
532
533                 timeline = intel_timeline_create(&dev_priv->gt, NULL);
534                 if (IS_ERR(timeline)) {
535                         context_close(ctx);
536                         return ERR_CAST(timeline);
537                 }
538
539                 ctx->timeline = timeline;
540         }
541
542         trace_i915_context_create(ctx);
543
544         return ctx;
545 }
546
547 /**
548  * i915_gem_context_create_gvt - create a GVT GEM context
549  * @dev: drm device *
550  *
551  * This function is used to create a GVT specific GEM context.
552  *
553  * Returns:
554  * pointer to i915_gem_context on success, error pointer if failed
555  *
556  */
557 struct i915_gem_context *
558 i915_gem_context_create_gvt(struct drm_device *dev)
559 {
560         struct i915_gem_context *ctx;
561         int ret;
562
563         if (!IS_ENABLED(CONFIG_DRM_I915_GVT))
564                 return ERR_PTR(-ENODEV);
565
566         ret = i915_mutex_lock_interruptible(dev);
567         if (ret)
568                 return ERR_PTR(ret);
569
570         ctx = i915_gem_create_context(to_i915(dev), 0);
571         if (IS_ERR(ctx))
572                 goto out;
573
574         ret = i915_gem_context_pin_hw_id(ctx);
575         if (ret) {
576                 context_close(ctx);
577                 ctx = ERR_PTR(ret);
578                 goto out;
579         }
580
581         ctx->file_priv = ERR_PTR(-EBADF);
582         i915_gem_context_set_closed(ctx); /* not user accessible */
583         i915_gem_context_clear_bannable(ctx);
584         i915_gem_context_set_force_single_submission(ctx);
585         if (!USES_GUC_SUBMISSION(to_i915(dev)))
586                 ctx->ring_size = 512 * PAGE_SIZE; /* Max ring buffer size */
587
588         GEM_BUG_ON(i915_gem_context_is_kernel(ctx));
589 out:
590         mutex_unlock(&dev->struct_mutex);
591         return ctx;
592 }
593
594 static void
595 destroy_kernel_context(struct i915_gem_context **ctxp)
596 {
597         struct i915_gem_context *ctx;
598
599         /* Keep the context ref so that we can free it immediately ourselves */
600         ctx = i915_gem_context_get(fetch_and_zero(ctxp));
601         GEM_BUG_ON(!i915_gem_context_is_kernel(ctx));
602
603         context_close(ctx);
604         i915_gem_context_free(ctx);
605 }
606
607 struct i915_gem_context *
608 i915_gem_context_create_kernel(struct drm_i915_private *i915, int prio)
609 {
610         struct i915_gem_context *ctx;
611         int err;
612
613         ctx = i915_gem_create_context(i915, 0);
614         if (IS_ERR(ctx))
615                 return ctx;
616
617         err = i915_gem_context_pin_hw_id(ctx);
618         if (err) {
619                 destroy_kernel_context(&ctx);
620                 return ERR_PTR(err);
621         }
622
623         i915_gem_context_clear_bannable(ctx);
624         ctx->sched.priority = I915_USER_PRIORITY(prio);
625         ctx->ring_size = PAGE_SIZE;
626
627         GEM_BUG_ON(!i915_gem_context_is_kernel(ctx));
628
629         return ctx;
630 }
631
632 static void init_contexts(struct drm_i915_private *i915)
633 {
634         mutex_init(&i915->contexts.mutex);
635         INIT_LIST_HEAD(&i915->contexts.list);
636
637         /* Using the simple ida interface, the max is limited by sizeof(int) */
638         BUILD_BUG_ON(MAX_CONTEXT_HW_ID > INT_MAX);
639         BUILD_BUG_ON(GEN11_MAX_CONTEXT_HW_ID > INT_MAX);
640         ida_init(&i915->contexts.hw_ida);
641         INIT_LIST_HEAD(&i915->contexts.hw_id_list);
642
643         INIT_WORK(&i915->contexts.free_work, contexts_free_worker);
644         init_llist_head(&i915->contexts.free_list);
645 }
646
647 static bool needs_preempt_context(struct drm_i915_private *i915)
648 {
649         return USES_GUC_SUBMISSION(i915);
650 }
651
652 int i915_gem_contexts_init(struct drm_i915_private *dev_priv)
653 {
654         struct i915_gem_context *ctx;
655
656         /* Reassure ourselves we are only called once */
657         GEM_BUG_ON(dev_priv->kernel_context);
658         GEM_BUG_ON(dev_priv->preempt_context);
659
660         init_contexts(dev_priv);
661
662         /* lowest priority; idle task */
663         ctx = i915_gem_context_create_kernel(dev_priv, I915_PRIORITY_MIN);
664         if (IS_ERR(ctx)) {
665                 DRM_ERROR("Failed to create default global context\n");
666                 return PTR_ERR(ctx);
667         }
668         /*
669          * For easy recognisablity, we want the kernel context to be 0 and then
670          * all user contexts will have non-zero hw_id. Kernel contexts are
671          * permanently pinned, so that we never suffer a stall and can
672          * use them from any allocation context (e.g. for evicting other
673          * contexts and from inside the shrinker).
674          */
675         GEM_BUG_ON(ctx->hw_id);
676         GEM_BUG_ON(!atomic_read(&ctx->hw_id_pin_count));
677         dev_priv->kernel_context = ctx;
678
679         /* highest priority; preempting task */
680         if (needs_preempt_context(dev_priv)) {
681                 ctx = i915_gem_context_create_kernel(dev_priv, INT_MAX);
682                 if (!IS_ERR(ctx))
683                         dev_priv->preempt_context = ctx;
684                 else
685                         DRM_ERROR("Failed to create preempt context; disabling preemption\n");
686         }
687
688         DRM_DEBUG_DRIVER("%s context support initialized\n",
689                          DRIVER_CAPS(dev_priv)->has_logical_contexts ?
690                          "logical" : "fake");
691         return 0;
692 }
693
694 void i915_gem_contexts_fini(struct drm_i915_private *i915)
695 {
696         lockdep_assert_held(&i915->drm.struct_mutex);
697
698         if (i915->preempt_context)
699                 destroy_kernel_context(&i915->preempt_context);
700         destroy_kernel_context(&i915->kernel_context);
701
702         /* Must free all deferred contexts (via flush_workqueue) first */
703         GEM_BUG_ON(!list_empty(&i915->contexts.hw_id_list));
704         ida_destroy(&i915->contexts.hw_ida);
705 }
706
707 static int context_idr_cleanup(int id, void *p, void *data)
708 {
709         context_close(p);
710         return 0;
711 }
712
713 static int vm_idr_cleanup(int id, void *p, void *data)
714 {
715         i915_vm_put(p);
716         return 0;
717 }
718
719 static int gem_context_register(struct i915_gem_context *ctx,
720                                 struct drm_i915_file_private *fpriv)
721 {
722         int ret;
723
724         ctx->file_priv = fpriv;
725         if (ctx->vm)
726                 ctx->vm->file = fpriv;
727
728         ctx->pid = get_task_pid(current, PIDTYPE_PID);
729         ctx->name = kasprintf(GFP_KERNEL, "%s[%d]",
730                               current->comm, pid_nr(ctx->pid));
731         if (!ctx->name) {
732                 ret = -ENOMEM;
733                 goto err_pid;
734         }
735
736         /* And finally expose ourselves to userspace via the idr */
737         mutex_lock(&fpriv->context_idr_lock);
738         ret = idr_alloc(&fpriv->context_idr, ctx, 0, 0, GFP_KERNEL);
739         mutex_unlock(&fpriv->context_idr_lock);
740         if (ret >= 0)
741                 goto out;
742
743         kfree(fetch_and_zero(&ctx->name));
744 err_pid:
745         put_pid(fetch_and_zero(&ctx->pid));
746 out:
747         return ret;
748 }
749
750 int i915_gem_context_open(struct drm_i915_private *i915,
751                           struct drm_file *file)
752 {
753         struct drm_i915_file_private *file_priv = file->driver_priv;
754         struct i915_gem_context *ctx;
755         int err;
756
757         mutex_init(&file_priv->context_idr_lock);
758         mutex_init(&file_priv->vm_idr_lock);
759
760         idr_init(&file_priv->context_idr);
761         idr_init_base(&file_priv->vm_idr, 1);
762
763         mutex_lock(&i915->drm.struct_mutex);
764         ctx = i915_gem_create_context(i915, 0);
765         mutex_unlock(&i915->drm.struct_mutex);
766         if (IS_ERR(ctx)) {
767                 err = PTR_ERR(ctx);
768                 goto err;
769         }
770
771         err = gem_context_register(ctx, file_priv);
772         if (err < 0)
773                 goto err_ctx;
774
775         GEM_BUG_ON(i915_gem_context_is_kernel(ctx));
776         GEM_BUG_ON(err > 0);
777
778         return 0;
779
780 err_ctx:
781         context_close(ctx);
782 err:
783         idr_destroy(&file_priv->vm_idr);
784         idr_destroy(&file_priv->context_idr);
785         mutex_destroy(&file_priv->vm_idr_lock);
786         mutex_destroy(&file_priv->context_idr_lock);
787         return err;
788 }
789
790 void i915_gem_context_close(struct drm_file *file)
791 {
792         struct drm_i915_file_private *file_priv = file->driver_priv;
793
794         idr_for_each(&file_priv->context_idr, context_idr_cleanup, NULL);
795         idr_destroy(&file_priv->context_idr);
796         mutex_destroy(&file_priv->context_idr_lock);
797
798         idr_for_each(&file_priv->vm_idr, vm_idr_cleanup, NULL);
799         idr_destroy(&file_priv->vm_idr);
800         mutex_destroy(&file_priv->vm_idr_lock);
801 }
802
803 int i915_gem_vm_create_ioctl(struct drm_device *dev, void *data,
804                              struct drm_file *file)
805 {
806         struct drm_i915_private *i915 = to_i915(dev);
807         struct drm_i915_gem_vm_control *args = data;
808         struct drm_i915_file_private *file_priv = file->driver_priv;
809         struct i915_ppgtt *ppgtt;
810         int err;
811
812         if (!HAS_FULL_PPGTT(i915))
813                 return -ENODEV;
814
815         if (args->flags)
816                 return -EINVAL;
817
818         ppgtt = i915_ppgtt_create(i915);
819         if (IS_ERR(ppgtt))
820                 return PTR_ERR(ppgtt);
821
822         ppgtt->vm.file = file_priv;
823
824         if (args->extensions) {
825                 err = i915_user_extensions(u64_to_user_ptr(args->extensions),
826                                            NULL, 0,
827                                            ppgtt);
828                 if (err)
829                         goto err_put;
830         }
831
832         err = mutex_lock_interruptible(&file_priv->vm_idr_lock);
833         if (err)
834                 goto err_put;
835
836         err = idr_alloc(&file_priv->vm_idr, &ppgtt->vm, 0, 0, GFP_KERNEL);
837         if (err < 0)
838                 goto err_unlock;
839
840         GEM_BUG_ON(err == 0); /* reserved for invalid/unassigned ppgtt */
841
842         mutex_unlock(&file_priv->vm_idr_lock);
843
844         args->vm_id = err;
845         return 0;
846
847 err_unlock:
848         mutex_unlock(&file_priv->vm_idr_lock);
849 err_put:
850         i915_vm_put(&ppgtt->vm);
851         return err;
852 }
853
854 int i915_gem_vm_destroy_ioctl(struct drm_device *dev, void *data,
855                               struct drm_file *file)
856 {
857         struct drm_i915_file_private *file_priv = file->driver_priv;
858         struct drm_i915_gem_vm_control *args = data;
859         struct i915_address_space *vm;
860         int err;
861         u32 id;
862
863         if (args->flags)
864                 return -EINVAL;
865
866         if (args->extensions)
867                 return -EINVAL;
868
869         id = args->vm_id;
870         if (!id)
871                 return -ENOENT;
872
873         err = mutex_lock_interruptible(&file_priv->vm_idr_lock);
874         if (err)
875                 return err;
876
877         vm = idr_remove(&file_priv->vm_idr, id);
878
879         mutex_unlock(&file_priv->vm_idr_lock);
880         if (!vm)
881                 return -ENOENT;
882
883         i915_vm_put(vm);
884         return 0;
885 }
886
887 struct context_barrier_task {
888         struct i915_active base;
889         void (*task)(void *data);
890         void *data;
891 };
892
893 static void cb_retire(struct i915_active *base)
894 {
895         struct context_barrier_task *cb = container_of(base, typeof(*cb), base);
896
897         if (cb->task)
898                 cb->task(cb->data);
899
900         i915_active_fini(&cb->base);
901         kfree(cb);
902 }
903
904 I915_SELFTEST_DECLARE(static intel_engine_mask_t context_barrier_inject_fault);
905 static int context_barrier_task(struct i915_gem_context *ctx,
906                                 intel_engine_mask_t engines,
907                                 bool (*skip)(struct intel_context *ce, void *data),
908                                 int (*emit)(struct i915_request *rq, void *data),
909                                 void (*task)(void *data),
910                                 void *data)
911 {
912         struct drm_i915_private *i915 = ctx->i915;
913         struct context_barrier_task *cb;
914         struct i915_gem_engines_iter it;
915         struct intel_context *ce;
916         int err = 0;
917
918         lockdep_assert_held(&i915->drm.struct_mutex);
919         GEM_BUG_ON(!task);
920
921         cb = kmalloc(sizeof(*cb), GFP_KERNEL);
922         if (!cb)
923                 return -ENOMEM;
924
925         i915_active_init(i915, &cb->base, NULL, cb_retire);
926         err = i915_active_acquire(&cb->base);
927         if (err) {
928                 kfree(cb);
929                 return err;
930         }
931
932         for_each_gem_engine(ce, i915_gem_context_lock_engines(ctx), it) {
933                 struct i915_request *rq;
934
935                 if (I915_SELFTEST_ONLY(context_barrier_inject_fault &
936                                        ce->engine->mask)) {
937                         err = -ENXIO;
938                         break;
939                 }
940
941                 if (!(ce->engine->mask & engines))
942                         continue;
943
944                 if (skip && skip(ce, data))
945                         continue;
946
947                 rq = intel_context_create_request(ce);
948                 if (IS_ERR(rq)) {
949                         err = PTR_ERR(rq);
950                         break;
951                 }
952
953                 err = 0;
954                 if (emit)
955                         err = emit(rq, data);
956                 if (err == 0)
957                         err = i915_active_ref(&cb->base, rq->fence.context, rq);
958
959                 i915_request_add(rq);
960                 if (err)
961                         break;
962         }
963         i915_gem_context_unlock_engines(ctx);
964
965         cb->task = err ? NULL : task; /* caller needs to unwind instead */
966         cb->data = data;
967
968         i915_active_release(&cb->base);
969
970         return err;
971 }
972
973 static int get_ppgtt(struct drm_i915_file_private *file_priv,
974                      struct i915_gem_context *ctx,
975                      struct drm_i915_gem_context_param *args)
976 {
977         struct i915_address_space *vm;
978         int ret;
979
980         if (!ctx->vm)
981                 return -ENODEV;
982
983         /* XXX rcu acquire? */
984         ret = mutex_lock_interruptible(&ctx->i915->drm.struct_mutex);
985         if (ret)
986                 return ret;
987
988         vm = i915_vm_get(ctx->vm);
989         mutex_unlock(&ctx->i915->drm.struct_mutex);
990
991         ret = mutex_lock_interruptible(&file_priv->vm_idr_lock);
992         if (ret)
993                 goto err_put;
994
995         ret = idr_alloc(&file_priv->vm_idr, vm, 0, 0, GFP_KERNEL);
996         GEM_BUG_ON(!ret);
997         if (ret < 0)
998                 goto err_unlock;
999
1000         i915_vm_get(vm);
1001
1002         args->size = 0;
1003         args->value = ret;
1004
1005         ret = 0;
1006 err_unlock:
1007         mutex_unlock(&file_priv->vm_idr_lock);
1008 err_put:
1009         i915_vm_put(vm);
1010         return ret;
1011 }
1012
1013 static void set_ppgtt_barrier(void *data)
1014 {
1015         struct i915_address_space *old = data;
1016
1017         if (INTEL_GEN(old->i915) < 8)
1018                 gen6_ppgtt_unpin_all(i915_vm_to_ppgtt(old));
1019
1020         i915_vm_put(old);
1021 }
1022
1023 static int emit_ppgtt_update(struct i915_request *rq, void *data)
1024 {
1025         struct i915_address_space *vm = rq->gem_context->vm;
1026         struct intel_engine_cs *engine = rq->engine;
1027         u32 base = engine->mmio_base;
1028         u32 *cs;
1029         int i;
1030
1031         if (i915_vm_is_4lvl(vm)) {
1032                 struct i915_ppgtt *ppgtt = i915_vm_to_ppgtt(vm);
1033                 const dma_addr_t pd_daddr = px_dma(ppgtt->pd);
1034
1035                 cs = intel_ring_begin(rq, 6);
1036                 if (IS_ERR(cs))
1037                         return PTR_ERR(cs);
1038
1039                 *cs++ = MI_LOAD_REGISTER_IMM(2);
1040
1041                 *cs++ = i915_mmio_reg_offset(GEN8_RING_PDP_UDW(base, 0));
1042                 *cs++ = upper_32_bits(pd_daddr);
1043                 *cs++ = i915_mmio_reg_offset(GEN8_RING_PDP_LDW(base, 0));
1044                 *cs++ = lower_32_bits(pd_daddr);
1045
1046                 *cs++ = MI_NOOP;
1047                 intel_ring_advance(rq, cs);
1048         } else if (HAS_LOGICAL_RING_CONTEXTS(engine->i915)) {
1049                 struct i915_ppgtt *ppgtt = i915_vm_to_ppgtt(vm);
1050
1051                 cs = intel_ring_begin(rq, 4 * GEN8_3LVL_PDPES + 2);
1052                 if (IS_ERR(cs))
1053                         return PTR_ERR(cs);
1054
1055                 *cs++ = MI_LOAD_REGISTER_IMM(2 * GEN8_3LVL_PDPES);
1056                 for (i = GEN8_3LVL_PDPES; i--; ) {
1057                         const dma_addr_t pd_daddr = i915_page_dir_dma_addr(ppgtt, i);
1058
1059                         *cs++ = i915_mmio_reg_offset(GEN8_RING_PDP_UDW(base, i));
1060                         *cs++ = upper_32_bits(pd_daddr);
1061                         *cs++ = i915_mmio_reg_offset(GEN8_RING_PDP_LDW(base, i));
1062                         *cs++ = lower_32_bits(pd_daddr);
1063                 }
1064                 *cs++ = MI_NOOP;
1065                 intel_ring_advance(rq, cs);
1066         } else {
1067                 /* ppGTT is not part of the legacy context image */
1068                 gen6_ppgtt_pin(i915_vm_to_ppgtt(vm));
1069         }
1070
1071         return 0;
1072 }
1073
1074 static bool skip_ppgtt_update(struct intel_context *ce, void *data)
1075 {
1076         if (HAS_LOGICAL_RING_CONTEXTS(ce->engine->i915))
1077                 return !ce->state;
1078         else
1079                 return !atomic_read(&ce->pin_count);
1080 }
1081
1082 static int set_ppgtt(struct drm_i915_file_private *file_priv,
1083                      struct i915_gem_context *ctx,
1084                      struct drm_i915_gem_context_param *args)
1085 {
1086         struct i915_address_space *vm, *old;
1087         int err;
1088
1089         if (args->size)
1090                 return -EINVAL;
1091
1092         if (!ctx->vm)
1093                 return -ENODEV;
1094
1095         if (upper_32_bits(args->value))
1096                 return -ENOENT;
1097
1098         err = mutex_lock_interruptible(&file_priv->vm_idr_lock);
1099         if (err)
1100                 return err;
1101
1102         vm = idr_find(&file_priv->vm_idr, args->value);
1103         if (vm)
1104                 i915_vm_get(vm);
1105         mutex_unlock(&file_priv->vm_idr_lock);
1106         if (!vm)
1107                 return -ENOENT;
1108
1109         err = mutex_lock_interruptible(&ctx->i915->drm.struct_mutex);
1110         if (err)
1111                 goto out;
1112
1113         if (vm == ctx->vm)
1114                 goto unlock;
1115
1116         /* Teardown the existing obj:vma cache, it will have to be rebuilt. */
1117         mutex_lock(&ctx->mutex);
1118         lut_close(ctx);
1119         mutex_unlock(&ctx->mutex);
1120
1121         old = __set_ppgtt(ctx, vm);
1122
1123         /*
1124          * We need to flush any requests using the current ppgtt before
1125          * we release it as the requests do not hold a reference themselves,
1126          * only indirectly through the context.
1127          */
1128         err = context_barrier_task(ctx, ALL_ENGINES,
1129                                    skip_ppgtt_update,
1130                                    emit_ppgtt_update,
1131                                    set_ppgtt_barrier,
1132                                    old);
1133         if (err) {
1134                 ctx->vm = old;
1135                 ctx->desc_template = default_desc_template(ctx->i915, old);
1136                 i915_vm_put(vm);
1137         }
1138
1139 unlock:
1140         mutex_unlock(&ctx->i915->drm.struct_mutex);
1141
1142 out:
1143         i915_vm_put(vm);
1144         return err;
1145 }
1146
1147 static int gen8_emit_rpcs_config(struct i915_request *rq,
1148                                  struct intel_context *ce,
1149                                  struct intel_sseu sseu)
1150 {
1151         u64 offset;
1152         u32 *cs;
1153
1154         cs = intel_ring_begin(rq, 4);
1155         if (IS_ERR(cs))
1156                 return PTR_ERR(cs);
1157
1158         offset = i915_ggtt_offset(ce->state) +
1159                  LRC_STATE_PN * PAGE_SIZE +
1160                  (CTX_R_PWR_CLK_STATE + 1) * 4;
1161
1162         *cs++ = MI_STORE_DWORD_IMM_GEN4 | MI_USE_GGTT;
1163         *cs++ = lower_32_bits(offset);
1164         *cs++ = upper_32_bits(offset);
1165         *cs++ = intel_sseu_make_rpcs(rq->i915, &sseu);
1166
1167         intel_ring_advance(rq, cs);
1168
1169         return 0;
1170 }
1171
1172 static int
1173 gen8_modify_rpcs(struct intel_context *ce, struct intel_sseu sseu)
1174 {
1175         struct i915_request *rq;
1176         int ret;
1177
1178         lockdep_assert_held(&ce->pin_mutex);
1179
1180         /*
1181          * If the context is not idle, we have to submit an ordered request to
1182          * modify its context image via the kernel context (writing to our own
1183          * image, or into the registers directory, does not stick). Pristine
1184          * and idle contexts will be configured on pinning.
1185          */
1186         if (!intel_context_is_pinned(ce))
1187                 return 0;
1188
1189         rq = i915_request_create(ce->engine->kernel_context);
1190         if (IS_ERR(rq))
1191                 return PTR_ERR(rq);
1192
1193         /* Queue this switch after all other activity by this context. */
1194         ret = i915_active_request_set(&ce->ring->timeline->last_request, rq);
1195         if (ret)
1196                 goto out_add;
1197
1198         /*
1199          * Guarantee context image and the timeline remains pinned until the
1200          * modifying request is retired by setting the ce activity tracker.
1201          *
1202          * But we only need to take one pin on the account of it. Or in other
1203          * words transfer the pinned ce object to tracked active request.
1204          */
1205         GEM_BUG_ON(i915_active_is_idle(&ce->active));
1206         ret = i915_active_ref(&ce->active, rq->fence.context, rq);
1207         if (ret)
1208                 goto out_add;
1209
1210         ret = gen8_emit_rpcs_config(rq, ce, sseu);
1211
1212 out_add:
1213         i915_request_add(rq);
1214         return ret;
1215 }
1216
1217 static int
1218 __intel_context_reconfigure_sseu(struct intel_context *ce,
1219                                  struct intel_sseu sseu)
1220 {
1221         int ret;
1222
1223         GEM_BUG_ON(INTEL_GEN(ce->gem_context->i915) < 8);
1224
1225         ret = intel_context_lock_pinned(ce);
1226         if (ret)
1227                 return ret;
1228
1229         /* Nothing to do if unmodified. */
1230         if (!memcmp(&ce->sseu, &sseu, sizeof(sseu)))
1231                 goto unlock;
1232
1233         ret = gen8_modify_rpcs(ce, sseu);
1234         if (!ret)
1235                 ce->sseu = sseu;
1236
1237 unlock:
1238         intel_context_unlock_pinned(ce);
1239         return ret;
1240 }
1241
1242 static int
1243 intel_context_reconfigure_sseu(struct intel_context *ce, struct intel_sseu sseu)
1244 {
1245         struct drm_i915_private *i915 = ce->gem_context->i915;
1246         int ret;
1247
1248         ret = mutex_lock_interruptible(&i915->drm.struct_mutex);
1249         if (ret)
1250                 return ret;
1251
1252         ret = __intel_context_reconfigure_sseu(ce, sseu);
1253
1254         mutex_unlock(&i915->drm.struct_mutex);
1255
1256         return ret;
1257 }
1258
1259 static int
1260 user_to_context_sseu(struct drm_i915_private *i915,
1261                      const struct drm_i915_gem_context_param_sseu *user,
1262                      struct intel_sseu *context)
1263 {
1264         const struct sseu_dev_info *device = &RUNTIME_INFO(i915)->sseu;
1265
1266         /* No zeros in any field. */
1267         if (!user->slice_mask || !user->subslice_mask ||
1268             !user->min_eus_per_subslice || !user->max_eus_per_subslice)
1269                 return -EINVAL;
1270
1271         /* Max > min. */
1272         if (user->max_eus_per_subslice < user->min_eus_per_subslice)
1273                 return -EINVAL;
1274
1275         /*
1276          * Some future proofing on the types since the uAPI is wider than the
1277          * current internal implementation.
1278          */
1279         if (overflows_type(user->slice_mask, context->slice_mask) ||
1280             overflows_type(user->subslice_mask, context->subslice_mask) ||
1281             overflows_type(user->min_eus_per_subslice,
1282                            context->min_eus_per_subslice) ||
1283             overflows_type(user->max_eus_per_subslice,
1284                            context->max_eus_per_subslice))
1285                 return -EINVAL;
1286
1287         /* Check validity against hardware. */
1288         if (user->slice_mask & ~device->slice_mask)
1289                 return -EINVAL;
1290
1291         if (user->subslice_mask & ~device->subslice_mask[0])
1292                 return -EINVAL;
1293
1294         if (user->max_eus_per_subslice > device->max_eus_per_subslice)
1295                 return -EINVAL;
1296
1297         context->slice_mask = user->slice_mask;
1298         context->subslice_mask = user->subslice_mask;
1299         context->min_eus_per_subslice = user->min_eus_per_subslice;
1300         context->max_eus_per_subslice = user->max_eus_per_subslice;
1301
1302         /* Part specific restrictions. */
1303         if (IS_GEN(i915, 11)) {
1304                 unsigned int hw_s = hweight8(device->slice_mask);
1305                 unsigned int hw_ss_per_s = hweight8(device->subslice_mask[0]);
1306                 unsigned int req_s = hweight8(context->slice_mask);
1307                 unsigned int req_ss = hweight8(context->subslice_mask);
1308
1309                 /*
1310                  * Only full subslice enablement is possible if more than one
1311                  * slice is turned on.
1312                  */
1313                 if (req_s > 1 && req_ss != hw_ss_per_s)
1314                         return -EINVAL;
1315
1316                 /*
1317                  * If more than four (SScount bitfield limit) subslices are
1318                  * requested then the number has to be even.
1319                  */
1320                 if (req_ss > 4 && (req_ss & 1))
1321                         return -EINVAL;
1322
1323                 /*
1324                  * If only one slice is enabled and subslice count is below the
1325                  * device full enablement, it must be at most half of the all
1326                  * available subslices.
1327                  */
1328                 if (req_s == 1 && req_ss < hw_ss_per_s &&
1329                     req_ss > (hw_ss_per_s / 2))
1330                         return -EINVAL;
1331
1332                 /* ABI restriction - VME use case only. */
1333
1334                 /* All slices or one slice only. */
1335                 if (req_s != 1 && req_s != hw_s)
1336                         return -EINVAL;
1337
1338                 /*
1339                  * Half subslices or full enablement only when one slice is
1340                  * enabled.
1341                  */
1342                 if (req_s == 1 &&
1343                     (req_ss != hw_ss_per_s && req_ss != (hw_ss_per_s / 2)))
1344                         return -EINVAL;
1345
1346                 /* No EU configuration changes. */
1347                 if ((user->min_eus_per_subslice !=
1348                      device->max_eus_per_subslice) ||
1349                     (user->max_eus_per_subslice !=
1350                      device->max_eus_per_subslice))
1351                         return -EINVAL;
1352         }
1353
1354         return 0;
1355 }
1356
1357 static int set_sseu(struct i915_gem_context *ctx,
1358                     struct drm_i915_gem_context_param *args)
1359 {
1360         struct drm_i915_private *i915 = ctx->i915;
1361         struct drm_i915_gem_context_param_sseu user_sseu;
1362         struct intel_context *ce;
1363         struct intel_sseu sseu;
1364         unsigned long lookup;
1365         int ret;
1366
1367         if (args->size < sizeof(user_sseu))
1368                 return -EINVAL;
1369
1370         if (!IS_GEN(i915, 11))
1371                 return -ENODEV;
1372
1373         if (copy_from_user(&user_sseu, u64_to_user_ptr(args->value),
1374                            sizeof(user_sseu)))
1375                 return -EFAULT;
1376
1377         if (user_sseu.rsvd)
1378                 return -EINVAL;
1379
1380         if (user_sseu.flags & ~(I915_CONTEXT_SSEU_FLAG_ENGINE_INDEX))
1381                 return -EINVAL;
1382
1383         lookup = 0;
1384         if (user_sseu.flags & I915_CONTEXT_SSEU_FLAG_ENGINE_INDEX)
1385                 lookup |= LOOKUP_USER_INDEX;
1386
1387         ce = lookup_user_engine(ctx, lookup, &user_sseu.engine);
1388         if (IS_ERR(ce))
1389                 return PTR_ERR(ce);
1390
1391         /* Only render engine supports RPCS configuration. */
1392         if (ce->engine->class != RENDER_CLASS) {
1393                 ret = -ENODEV;
1394                 goto out_ce;
1395         }
1396
1397         ret = user_to_context_sseu(i915, &user_sseu, &sseu);
1398         if (ret)
1399                 goto out_ce;
1400
1401         ret = intel_context_reconfigure_sseu(ce, sseu);
1402         if (ret)
1403                 goto out_ce;
1404
1405         args->size = sizeof(user_sseu);
1406
1407 out_ce:
1408         intel_context_put(ce);
1409         return ret;
1410 }
1411
1412 struct set_engines {
1413         struct i915_gem_context *ctx;
1414         struct i915_gem_engines *engines;
1415 };
1416
1417 static int
1418 set_engines__load_balance(struct i915_user_extension __user *base, void *data)
1419 {
1420         struct i915_context_engines_load_balance __user *ext =
1421                 container_of_user(base, typeof(*ext), base);
1422         const struct set_engines *set = data;
1423         struct intel_engine_cs *stack[16];
1424         struct intel_engine_cs **siblings;
1425         struct intel_context *ce;
1426         u16 num_siblings, idx;
1427         unsigned int n;
1428         int err;
1429
1430         if (!HAS_EXECLISTS(set->ctx->i915))
1431                 return -ENODEV;
1432
1433         if (USES_GUC_SUBMISSION(set->ctx->i915))
1434                 return -ENODEV; /* not implement yet */
1435
1436         if (get_user(idx, &ext->engine_index))
1437                 return -EFAULT;
1438
1439         if (idx >= set->engines->num_engines) {
1440                 DRM_DEBUG("Invalid placement value, %d >= %d\n",
1441                           idx, set->engines->num_engines);
1442                 return -EINVAL;
1443         }
1444
1445         idx = array_index_nospec(idx, set->engines->num_engines);
1446         if (set->engines->engines[idx]) {
1447                 DRM_DEBUG("Invalid placement[%d], already occupied\n", idx);
1448                 return -EEXIST;
1449         }
1450
1451         if (get_user(num_siblings, &ext->num_siblings))
1452                 return -EFAULT;
1453
1454         err = check_user_mbz(&ext->flags);
1455         if (err)
1456                 return err;
1457
1458         err = check_user_mbz(&ext->mbz64);
1459         if (err)
1460                 return err;
1461
1462         siblings = stack;
1463         if (num_siblings > ARRAY_SIZE(stack)) {
1464                 siblings = kmalloc_array(num_siblings,
1465                                          sizeof(*siblings),
1466                                          GFP_KERNEL);
1467                 if (!siblings)
1468                         return -ENOMEM;
1469         }
1470
1471         for (n = 0; n < num_siblings; n++) {
1472                 struct i915_engine_class_instance ci;
1473
1474                 if (copy_from_user(&ci, &ext->engines[n], sizeof(ci))) {
1475                         err = -EFAULT;
1476                         goto out_siblings;
1477                 }
1478
1479                 siblings[n] = intel_engine_lookup_user(set->ctx->i915,
1480                                                        ci.engine_class,
1481                                                        ci.engine_instance);
1482                 if (!siblings[n]) {
1483                         DRM_DEBUG("Invalid sibling[%d]: { class:%d, inst:%d }\n",
1484                                   n, ci.engine_class, ci.engine_instance);
1485                         err = -EINVAL;
1486                         goto out_siblings;
1487                 }
1488         }
1489
1490         ce = intel_execlists_create_virtual(set->ctx, siblings, n);
1491         if (IS_ERR(ce)) {
1492                 err = PTR_ERR(ce);
1493                 goto out_siblings;
1494         }
1495
1496         if (cmpxchg(&set->engines->engines[idx], NULL, ce)) {
1497                 intel_context_put(ce);
1498                 err = -EEXIST;
1499                 goto out_siblings;
1500         }
1501
1502 out_siblings:
1503         if (siblings != stack)
1504                 kfree(siblings);
1505
1506         return err;
1507 }
1508
1509 static int
1510 set_engines__bond(struct i915_user_extension __user *base, void *data)
1511 {
1512         struct i915_context_engines_bond __user *ext =
1513                 container_of_user(base, typeof(*ext), base);
1514         const struct set_engines *set = data;
1515         struct i915_engine_class_instance ci;
1516         struct intel_engine_cs *virtual;
1517         struct intel_engine_cs *master;
1518         u16 idx, num_bonds;
1519         int err, n;
1520
1521         if (get_user(idx, &ext->virtual_index))
1522                 return -EFAULT;
1523
1524         if (idx >= set->engines->num_engines) {
1525                 DRM_DEBUG("Invalid index for virtual engine: %d >= %d\n",
1526                           idx, set->engines->num_engines);
1527                 return -EINVAL;
1528         }
1529
1530         idx = array_index_nospec(idx, set->engines->num_engines);
1531         if (!set->engines->engines[idx]) {
1532                 DRM_DEBUG("Invalid engine at %d\n", idx);
1533                 return -EINVAL;
1534         }
1535         virtual = set->engines->engines[idx]->engine;
1536
1537         err = check_user_mbz(&ext->flags);
1538         if (err)
1539                 return err;
1540
1541         for (n = 0; n < ARRAY_SIZE(ext->mbz64); n++) {
1542                 err = check_user_mbz(&ext->mbz64[n]);
1543                 if (err)
1544                         return err;
1545         }
1546
1547         if (copy_from_user(&ci, &ext->master, sizeof(ci)))
1548                 return -EFAULT;
1549
1550         master = intel_engine_lookup_user(set->ctx->i915,
1551                                           ci.engine_class, ci.engine_instance);
1552         if (!master) {
1553                 DRM_DEBUG("Unrecognised master engine: { class:%u, instance:%u }\n",
1554                           ci.engine_class, ci.engine_instance);
1555                 return -EINVAL;
1556         }
1557
1558         if (get_user(num_bonds, &ext->num_bonds))
1559                 return -EFAULT;
1560
1561         for (n = 0; n < num_bonds; n++) {
1562                 struct intel_engine_cs *bond;
1563
1564                 if (copy_from_user(&ci, &ext->engines[n], sizeof(ci)))
1565                         return -EFAULT;
1566
1567                 bond = intel_engine_lookup_user(set->ctx->i915,
1568                                                 ci.engine_class,
1569                                                 ci.engine_instance);
1570                 if (!bond) {
1571                         DRM_DEBUG("Unrecognised engine[%d] for bonding: { class:%d, instance: %d }\n",
1572                                   n, ci.engine_class, ci.engine_instance);
1573                         return -EINVAL;
1574                 }
1575
1576                 /*
1577                  * A non-virtual engine has no siblings to choose between; and
1578                  * a submit fence will always be directed to the one engine.
1579                  */
1580                 if (intel_engine_is_virtual(virtual)) {
1581                         err = intel_virtual_engine_attach_bond(virtual,
1582                                                                master,
1583                                                                bond);
1584                         if (err)
1585                                 return err;
1586                 }
1587         }
1588
1589         return 0;
1590 }
1591
1592 static const i915_user_extension_fn set_engines__extensions[] = {
1593         [I915_CONTEXT_ENGINES_EXT_LOAD_BALANCE] = set_engines__load_balance,
1594         [I915_CONTEXT_ENGINES_EXT_BOND] = set_engines__bond,
1595 };
1596
1597 static int
1598 set_engines(struct i915_gem_context *ctx,
1599             const struct drm_i915_gem_context_param *args)
1600 {
1601         struct i915_context_param_engines __user *user =
1602                 u64_to_user_ptr(args->value);
1603         struct set_engines set = { .ctx = ctx };
1604         unsigned int num_engines, n;
1605         u64 extensions;
1606         int err;
1607
1608         if (!args->size) { /* switch back to legacy user_ring_map */
1609                 if (!i915_gem_context_user_engines(ctx))
1610                         return 0;
1611
1612                 set.engines = default_engines(ctx);
1613                 if (IS_ERR(set.engines))
1614                         return PTR_ERR(set.engines);
1615
1616                 goto replace;
1617         }
1618
1619         BUILD_BUG_ON(!IS_ALIGNED(sizeof(*user), sizeof(*user->engines)));
1620         if (args->size < sizeof(*user) ||
1621             !IS_ALIGNED(args->size, sizeof(*user->engines))) {
1622                 DRM_DEBUG("Invalid size for engine array: %d\n",
1623                           args->size);
1624                 return -EINVAL;
1625         }
1626
1627         /*
1628          * Note that I915_EXEC_RING_MASK limits execbuf to only using the
1629          * first 64 engines defined here.
1630          */
1631         num_engines = (args->size - sizeof(*user)) / sizeof(*user->engines);
1632
1633         set.engines = kmalloc(struct_size(set.engines, engines, num_engines),
1634                               GFP_KERNEL);
1635         if (!set.engines)
1636                 return -ENOMEM;
1637
1638         init_rcu_head(&set.engines->rcu);
1639         for (n = 0; n < num_engines; n++) {
1640                 struct i915_engine_class_instance ci;
1641                 struct intel_engine_cs *engine;
1642
1643                 if (copy_from_user(&ci, &user->engines[n], sizeof(ci))) {
1644                         __free_engines(set.engines, n);
1645                         return -EFAULT;
1646                 }
1647
1648                 if (ci.engine_class == (u16)I915_ENGINE_CLASS_INVALID &&
1649                     ci.engine_instance == (u16)I915_ENGINE_CLASS_INVALID_NONE) {
1650                         set.engines->engines[n] = NULL;
1651                         continue;
1652                 }
1653
1654                 engine = intel_engine_lookup_user(ctx->i915,
1655                                                   ci.engine_class,
1656                                                   ci.engine_instance);
1657                 if (!engine) {
1658                         DRM_DEBUG("Invalid engine[%d]: { class:%d, instance:%d }\n",
1659                                   n, ci.engine_class, ci.engine_instance);
1660                         __free_engines(set.engines, n);
1661                         return -ENOENT;
1662                 }
1663
1664                 set.engines->engines[n] = intel_context_create(ctx, engine);
1665                 if (!set.engines->engines[n]) {
1666                         __free_engines(set.engines, n);
1667                         return -ENOMEM;
1668                 }
1669         }
1670         set.engines->num_engines = num_engines;
1671
1672         err = -EFAULT;
1673         if (!get_user(extensions, &user->extensions))
1674                 err = i915_user_extensions(u64_to_user_ptr(extensions),
1675                                            set_engines__extensions,
1676                                            ARRAY_SIZE(set_engines__extensions),
1677                                            &set);
1678         if (err) {
1679                 free_engines(set.engines);
1680                 return err;
1681         }
1682
1683 replace:
1684         mutex_lock(&ctx->engines_mutex);
1685         if (args->size)
1686                 i915_gem_context_set_user_engines(ctx);
1687         else
1688                 i915_gem_context_clear_user_engines(ctx);
1689         rcu_swap_protected(ctx->engines, set.engines, 1);
1690         mutex_unlock(&ctx->engines_mutex);
1691
1692         call_rcu(&set.engines->rcu, free_engines_rcu);
1693
1694         return 0;
1695 }
1696
1697 static struct i915_gem_engines *
1698 __copy_engines(struct i915_gem_engines *e)
1699 {
1700         struct i915_gem_engines *copy;
1701         unsigned int n;
1702
1703         copy = kmalloc(struct_size(e, engines, e->num_engines), GFP_KERNEL);
1704         if (!copy)
1705                 return ERR_PTR(-ENOMEM);
1706
1707         init_rcu_head(&copy->rcu);
1708         for (n = 0; n < e->num_engines; n++) {
1709                 if (e->engines[n])
1710                         copy->engines[n] = intel_context_get(e->engines[n]);
1711                 else
1712                         copy->engines[n] = NULL;
1713         }
1714         copy->num_engines = n;
1715
1716         return copy;
1717 }
1718
1719 static int
1720 get_engines(struct i915_gem_context *ctx,
1721             struct drm_i915_gem_context_param *args)
1722 {
1723         struct i915_context_param_engines __user *user;
1724         struct i915_gem_engines *e;
1725         size_t n, count, size;
1726         int err = 0;
1727
1728         err = mutex_lock_interruptible(&ctx->engines_mutex);
1729         if (err)
1730                 return err;
1731
1732         e = NULL;
1733         if (i915_gem_context_user_engines(ctx))
1734                 e = __copy_engines(i915_gem_context_engines(ctx));
1735         mutex_unlock(&ctx->engines_mutex);
1736         if (IS_ERR_OR_NULL(e)) {
1737                 args->size = 0;
1738                 return PTR_ERR_OR_ZERO(e);
1739         }
1740
1741         count = e->num_engines;
1742
1743         /* Be paranoid in case we have an impedance mismatch */
1744         if (!check_struct_size(user, engines, count, &size)) {
1745                 err = -EINVAL;
1746                 goto err_free;
1747         }
1748         if (overflows_type(size, args->size)) {
1749                 err = -EINVAL;
1750                 goto err_free;
1751         }
1752
1753         if (!args->size) {
1754                 args->size = size;
1755                 goto err_free;
1756         }
1757
1758         if (args->size < size) {
1759                 err = -EINVAL;
1760                 goto err_free;
1761         }
1762
1763         user = u64_to_user_ptr(args->value);
1764         if (!access_ok(user, size)) {
1765                 err = -EFAULT;
1766                 goto err_free;
1767         }
1768
1769         if (put_user(0, &user->extensions)) {
1770                 err = -EFAULT;
1771                 goto err_free;
1772         }
1773
1774         for (n = 0; n < count; n++) {
1775                 struct i915_engine_class_instance ci = {
1776                         .engine_class = I915_ENGINE_CLASS_INVALID,
1777                         .engine_instance = I915_ENGINE_CLASS_INVALID_NONE,
1778                 };
1779
1780                 if (e->engines[n]) {
1781                         ci.engine_class = e->engines[n]->engine->uabi_class;
1782                         ci.engine_instance = e->engines[n]->engine->instance;
1783                 }
1784
1785                 if (copy_to_user(&user->engines[n], &ci, sizeof(ci))) {
1786                         err = -EFAULT;
1787                         goto err_free;
1788                 }
1789         }
1790
1791         args->size = size;
1792
1793 err_free:
1794         free_engines(e);
1795         return err;
1796 }
1797
1798 static int ctx_setparam(struct drm_i915_file_private *fpriv,
1799                         struct i915_gem_context *ctx,
1800                         struct drm_i915_gem_context_param *args)
1801 {
1802         int ret = 0;
1803
1804         switch (args->param) {
1805         case I915_CONTEXT_PARAM_NO_ZEROMAP:
1806                 if (args->size)
1807                         ret = -EINVAL;
1808                 else if (args->value)
1809                         set_bit(UCONTEXT_NO_ZEROMAP, &ctx->user_flags);
1810                 else
1811                         clear_bit(UCONTEXT_NO_ZEROMAP, &ctx->user_flags);
1812                 break;
1813
1814         case I915_CONTEXT_PARAM_NO_ERROR_CAPTURE:
1815                 if (args->size)
1816                         ret = -EINVAL;
1817                 else if (args->value)
1818                         i915_gem_context_set_no_error_capture(ctx);
1819                 else
1820                         i915_gem_context_clear_no_error_capture(ctx);
1821                 break;
1822
1823         case I915_CONTEXT_PARAM_BANNABLE:
1824                 if (args->size)
1825                         ret = -EINVAL;
1826                 else if (!capable(CAP_SYS_ADMIN) && !args->value)
1827                         ret = -EPERM;
1828                 else if (args->value)
1829                         i915_gem_context_set_bannable(ctx);
1830                 else
1831                         i915_gem_context_clear_bannable(ctx);
1832                 break;
1833
1834         case I915_CONTEXT_PARAM_RECOVERABLE:
1835                 if (args->size)
1836                         ret = -EINVAL;
1837                 else if (args->value)
1838                         i915_gem_context_set_recoverable(ctx);
1839                 else
1840                         i915_gem_context_clear_recoverable(ctx);
1841                 break;
1842
1843         case I915_CONTEXT_PARAM_PRIORITY:
1844                 {
1845                         s64 priority = args->value;
1846
1847                         if (args->size)
1848                                 ret = -EINVAL;
1849                         else if (!(ctx->i915->caps.scheduler & I915_SCHEDULER_CAP_PRIORITY))
1850                                 ret = -ENODEV;
1851                         else if (priority > I915_CONTEXT_MAX_USER_PRIORITY ||
1852                                  priority < I915_CONTEXT_MIN_USER_PRIORITY)
1853                                 ret = -EINVAL;
1854                         else if (priority > I915_CONTEXT_DEFAULT_PRIORITY &&
1855                                  !capable(CAP_SYS_NICE))
1856                                 ret = -EPERM;
1857                         else
1858                                 ctx->sched.priority =
1859                                         I915_USER_PRIORITY(priority);
1860                 }
1861                 break;
1862
1863         case I915_CONTEXT_PARAM_SSEU:
1864                 ret = set_sseu(ctx, args);
1865                 break;
1866
1867         case I915_CONTEXT_PARAM_VM:
1868                 ret = set_ppgtt(fpriv, ctx, args);
1869                 break;
1870
1871         case I915_CONTEXT_PARAM_ENGINES:
1872                 ret = set_engines(ctx, args);
1873                 break;
1874
1875         case I915_CONTEXT_PARAM_BAN_PERIOD:
1876         default:
1877                 ret = -EINVAL;
1878                 break;
1879         }
1880
1881         return ret;
1882 }
1883
1884 struct create_ext {
1885         struct i915_gem_context *ctx;
1886         struct drm_i915_file_private *fpriv;
1887 };
1888
1889 static int create_setparam(struct i915_user_extension __user *ext, void *data)
1890 {
1891         struct drm_i915_gem_context_create_ext_setparam local;
1892         const struct create_ext *arg = data;
1893
1894         if (copy_from_user(&local, ext, sizeof(local)))
1895                 return -EFAULT;
1896
1897         if (local.param.ctx_id)
1898                 return -EINVAL;
1899
1900         return ctx_setparam(arg->fpriv, arg->ctx, &local.param);
1901 }
1902
1903 static int clone_engines(struct i915_gem_context *dst,
1904                          struct i915_gem_context *src)
1905 {
1906         struct i915_gem_engines *e = i915_gem_context_lock_engines(src);
1907         struct i915_gem_engines *clone;
1908         bool user_engines;
1909         unsigned long n;
1910
1911         clone = kmalloc(struct_size(e, engines, e->num_engines), GFP_KERNEL);
1912         if (!clone)
1913                 goto err_unlock;
1914
1915         init_rcu_head(&clone->rcu);
1916         for (n = 0; n < e->num_engines; n++) {
1917                 struct intel_engine_cs *engine;
1918
1919                 if (!e->engines[n]) {
1920                         clone->engines[n] = NULL;
1921                         continue;
1922                 }
1923                 engine = e->engines[n]->engine;
1924
1925                 /*
1926                  * Virtual engines are singletons; they can only exist
1927                  * inside a single context, because they embed their
1928                  * HW context... As each virtual context implies a single
1929                  * timeline (each engine can only dequeue a single request
1930                  * at any time), it would be surprising for two contexts
1931                  * to use the same engine. So let's create a copy of
1932                  * the virtual engine instead.
1933                  */
1934                 if (intel_engine_is_virtual(engine))
1935                         clone->engines[n] =
1936                                 intel_execlists_clone_virtual(dst, engine);
1937                 else
1938                         clone->engines[n] = intel_context_create(dst, engine);
1939                 if (IS_ERR_OR_NULL(clone->engines[n])) {
1940                         __free_engines(clone, n);
1941                         goto err_unlock;
1942                 }
1943         }
1944         clone->num_engines = n;
1945
1946         user_engines = i915_gem_context_user_engines(src);
1947         i915_gem_context_unlock_engines(src);
1948
1949         free_engines(dst->engines);
1950         RCU_INIT_POINTER(dst->engines, clone);
1951         if (user_engines)
1952                 i915_gem_context_set_user_engines(dst);
1953         else
1954                 i915_gem_context_clear_user_engines(dst);
1955         return 0;
1956
1957 err_unlock:
1958         i915_gem_context_unlock_engines(src);
1959         return -ENOMEM;
1960 }
1961
1962 static int clone_flags(struct i915_gem_context *dst,
1963                        struct i915_gem_context *src)
1964 {
1965         dst->user_flags = src->user_flags;
1966         return 0;
1967 }
1968
1969 static int clone_schedattr(struct i915_gem_context *dst,
1970                            struct i915_gem_context *src)
1971 {
1972         dst->sched = src->sched;
1973         return 0;
1974 }
1975
1976 static int clone_sseu(struct i915_gem_context *dst,
1977                       struct i915_gem_context *src)
1978 {
1979         struct i915_gem_engines *e = i915_gem_context_lock_engines(src);
1980         struct i915_gem_engines *clone;
1981         unsigned long n;
1982         int err;
1983
1984         clone = dst->engines; /* no locking required; sole access */
1985         if (e->num_engines != clone->num_engines) {
1986                 err = -EINVAL;
1987                 goto unlock;
1988         }
1989
1990         for (n = 0; n < e->num_engines; n++) {
1991                 struct intel_context *ce = e->engines[n];
1992
1993                 if (clone->engines[n]->engine->class != ce->engine->class) {
1994                         /* Must have compatible engine maps! */
1995                         err = -EINVAL;
1996                         goto unlock;
1997                 }
1998
1999                 /* serialises with set_sseu */
2000                 err = intel_context_lock_pinned(ce);
2001                 if (err)
2002                         goto unlock;
2003
2004                 clone->engines[n]->sseu = ce->sseu;
2005                 intel_context_unlock_pinned(ce);
2006         }
2007
2008         err = 0;
2009 unlock:
2010         i915_gem_context_unlock_engines(src);
2011         return err;
2012 }
2013
2014 static int clone_timeline(struct i915_gem_context *dst,
2015                           struct i915_gem_context *src)
2016 {
2017         if (src->timeline) {
2018                 GEM_BUG_ON(src->timeline == dst->timeline);
2019
2020                 if (dst->timeline)
2021                         intel_timeline_put(dst->timeline);
2022                 dst->timeline = intel_timeline_get(src->timeline);
2023         }
2024
2025         return 0;
2026 }
2027
2028 static int clone_vm(struct i915_gem_context *dst,
2029                     struct i915_gem_context *src)
2030 {
2031         struct i915_address_space *vm;
2032
2033         rcu_read_lock();
2034         do {
2035                 vm = READ_ONCE(src->vm);
2036                 if (!vm)
2037                         break;
2038
2039                 if (!kref_get_unless_zero(&vm->ref))
2040                         continue;
2041
2042                 /*
2043                  * This ppgtt may have be reallocated between
2044                  * the read and the kref, and reassigned to a third
2045                  * context. In order to avoid inadvertent sharing
2046                  * of this ppgtt with that third context (and not
2047                  * src), we have to confirm that we have the same
2048                  * ppgtt after passing through the strong memory
2049                  * barrier implied by a successful
2050                  * kref_get_unless_zero().
2051                  *
2052                  * Once we have acquired the current ppgtt of src,
2053                  * we no longer care if it is released from src, as
2054                  * it cannot be reallocated elsewhere.
2055                  */
2056
2057                 if (vm == READ_ONCE(src->vm))
2058                         break;
2059
2060                 i915_vm_put(vm);
2061         } while (1);
2062         rcu_read_unlock();
2063
2064         if (vm) {
2065                 __assign_ppgtt(dst, vm);
2066                 i915_vm_put(vm);
2067         }
2068
2069         return 0;
2070 }
2071
2072 static int create_clone(struct i915_user_extension __user *ext, void *data)
2073 {
2074         static int (* const fn[])(struct i915_gem_context *dst,
2075                                   struct i915_gem_context *src) = {
2076 #define MAP(x, y) [ilog2(I915_CONTEXT_CLONE_##x)] = y
2077                 MAP(ENGINES, clone_engines),
2078                 MAP(FLAGS, clone_flags),
2079                 MAP(SCHEDATTR, clone_schedattr),
2080                 MAP(SSEU, clone_sseu),
2081                 MAP(TIMELINE, clone_timeline),
2082                 MAP(VM, clone_vm),
2083 #undef MAP
2084         };
2085         struct drm_i915_gem_context_create_ext_clone local;
2086         const struct create_ext *arg = data;
2087         struct i915_gem_context *dst = arg->ctx;
2088         struct i915_gem_context *src;
2089         int err, bit;
2090
2091         if (copy_from_user(&local, ext, sizeof(local)))
2092                 return -EFAULT;
2093
2094         BUILD_BUG_ON(GENMASK(BITS_PER_TYPE(local.flags) - 1, ARRAY_SIZE(fn)) !=
2095                      I915_CONTEXT_CLONE_UNKNOWN);
2096
2097         if (local.flags & I915_CONTEXT_CLONE_UNKNOWN)
2098                 return -EINVAL;
2099
2100         if (local.rsvd)
2101                 return -EINVAL;
2102
2103         rcu_read_lock();
2104         src = __i915_gem_context_lookup_rcu(arg->fpriv, local.clone_id);
2105         rcu_read_unlock();
2106         if (!src)
2107                 return -ENOENT;
2108
2109         GEM_BUG_ON(src == dst);
2110
2111         for (bit = 0; bit < ARRAY_SIZE(fn); bit++) {
2112                 if (!(local.flags & BIT(bit)))
2113                         continue;
2114
2115                 err = fn[bit](dst, src);
2116                 if (err)
2117                         return err;
2118         }
2119
2120         return 0;
2121 }
2122
2123 static const i915_user_extension_fn create_extensions[] = {
2124         [I915_CONTEXT_CREATE_EXT_SETPARAM] = create_setparam,
2125         [I915_CONTEXT_CREATE_EXT_CLONE] = create_clone,
2126 };
2127
2128 static bool client_is_banned(struct drm_i915_file_private *file_priv)
2129 {
2130         return atomic_read(&file_priv->ban_score) >= I915_CLIENT_SCORE_BANNED;
2131 }
2132
2133 int i915_gem_context_create_ioctl(struct drm_device *dev, void *data,
2134                                   struct drm_file *file)
2135 {
2136         struct drm_i915_private *i915 = to_i915(dev);
2137         struct drm_i915_gem_context_create_ext *args = data;
2138         struct create_ext ext_data;
2139         int ret;
2140
2141         if (!DRIVER_CAPS(i915)->has_logical_contexts)
2142                 return -ENODEV;
2143
2144         if (args->flags & I915_CONTEXT_CREATE_FLAGS_UNKNOWN)
2145                 return -EINVAL;
2146
2147         ret = i915_terminally_wedged(i915);
2148         if (ret)
2149                 return ret;
2150
2151         ext_data.fpriv = file->driver_priv;
2152         if (client_is_banned(ext_data.fpriv)) {
2153                 DRM_DEBUG("client %s[%d] banned from creating ctx\n",
2154                           current->comm,
2155                           pid_nr(get_task_pid(current, PIDTYPE_PID)));
2156                 return -EIO;
2157         }
2158
2159         ret = i915_mutex_lock_interruptible(dev);
2160         if (ret)
2161                 return ret;
2162
2163         ext_data.ctx = i915_gem_create_context(i915, args->flags);
2164         mutex_unlock(&dev->struct_mutex);
2165         if (IS_ERR(ext_data.ctx))
2166                 return PTR_ERR(ext_data.ctx);
2167
2168         if (args->flags & I915_CONTEXT_CREATE_FLAGS_USE_EXTENSIONS) {
2169                 ret = i915_user_extensions(u64_to_user_ptr(args->extensions),
2170                                            create_extensions,
2171                                            ARRAY_SIZE(create_extensions),
2172                                            &ext_data);
2173                 if (ret)
2174                         goto err_ctx;
2175         }
2176
2177         ret = gem_context_register(ext_data.ctx, ext_data.fpriv);
2178         if (ret < 0)
2179                 goto err_ctx;
2180
2181         args->ctx_id = ret;
2182         DRM_DEBUG("HW context %d created\n", args->ctx_id);
2183
2184         return 0;
2185
2186 err_ctx:
2187         context_close(ext_data.ctx);
2188         return ret;
2189 }
2190
2191 int i915_gem_context_destroy_ioctl(struct drm_device *dev, void *data,
2192                                    struct drm_file *file)
2193 {
2194         struct drm_i915_gem_context_destroy *args = data;
2195         struct drm_i915_file_private *file_priv = file->driver_priv;
2196         struct i915_gem_context *ctx;
2197
2198         if (args->pad != 0)
2199                 return -EINVAL;
2200
2201         if (!args->ctx_id)
2202                 return -ENOENT;
2203
2204         if (mutex_lock_interruptible(&file_priv->context_idr_lock))
2205                 return -EINTR;
2206
2207         ctx = idr_remove(&file_priv->context_idr, args->ctx_id);
2208         mutex_unlock(&file_priv->context_idr_lock);
2209         if (!ctx)
2210                 return -ENOENT;
2211
2212         context_close(ctx);
2213         return 0;
2214 }
2215
2216 static int get_sseu(struct i915_gem_context *ctx,
2217                     struct drm_i915_gem_context_param *args)
2218 {
2219         struct drm_i915_gem_context_param_sseu user_sseu;
2220         struct intel_context *ce;
2221         unsigned long lookup;
2222         int err;
2223
2224         if (args->size == 0)
2225                 goto out;
2226         else if (args->size < sizeof(user_sseu))
2227                 return -EINVAL;
2228
2229         if (copy_from_user(&user_sseu, u64_to_user_ptr(args->value),
2230                            sizeof(user_sseu)))
2231                 return -EFAULT;
2232
2233         if (user_sseu.rsvd)
2234                 return -EINVAL;
2235
2236         if (user_sseu.flags & ~(I915_CONTEXT_SSEU_FLAG_ENGINE_INDEX))
2237                 return -EINVAL;
2238
2239         lookup = 0;
2240         if (user_sseu.flags & I915_CONTEXT_SSEU_FLAG_ENGINE_INDEX)
2241                 lookup |= LOOKUP_USER_INDEX;
2242
2243         ce = lookup_user_engine(ctx, lookup, &user_sseu.engine);
2244         if (IS_ERR(ce))
2245                 return PTR_ERR(ce);
2246
2247         err = intel_context_lock_pinned(ce); /* serialises with set_sseu */
2248         if (err) {
2249                 intel_context_put(ce);
2250                 return err;
2251         }
2252
2253         user_sseu.slice_mask = ce->sseu.slice_mask;
2254         user_sseu.subslice_mask = ce->sseu.subslice_mask;
2255         user_sseu.min_eus_per_subslice = ce->sseu.min_eus_per_subslice;
2256         user_sseu.max_eus_per_subslice = ce->sseu.max_eus_per_subslice;
2257
2258         intel_context_unlock_pinned(ce);
2259         intel_context_put(ce);
2260
2261         if (copy_to_user(u64_to_user_ptr(args->value), &user_sseu,
2262                          sizeof(user_sseu)))
2263                 return -EFAULT;
2264
2265 out:
2266         args->size = sizeof(user_sseu);
2267
2268         return 0;
2269 }
2270
2271 int i915_gem_context_getparam_ioctl(struct drm_device *dev, void *data,
2272                                     struct drm_file *file)
2273 {
2274         struct drm_i915_file_private *file_priv = file->driver_priv;
2275         struct drm_i915_gem_context_param *args = data;
2276         struct i915_gem_context *ctx;
2277         int ret = 0;
2278
2279         ctx = i915_gem_context_lookup(file_priv, args->ctx_id);
2280         if (!ctx)
2281                 return -ENOENT;
2282
2283         switch (args->param) {
2284         case I915_CONTEXT_PARAM_NO_ZEROMAP:
2285                 args->size = 0;
2286                 args->value = test_bit(UCONTEXT_NO_ZEROMAP, &ctx->user_flags);
2287                 break;
2288
2289         case I915_CONTEXT_PARAM_GTT_SIZE:
2290                 args->size = 0;
2291                 if (ctx->vm)
2292                         args->value = ctx->vm->total;
2293                 else if (to_i915(dev)->mm.aliasing_ppgtt)
2294                         args->value = to_i915(dev)->mm.aliasing_ppgtt->vm.total;
2295                 else
2296                         args->value = to_i915(dev)->ggtt.vm.total;
2297                 break;
2298
2299         case I915_CONTEXT_PARAM_NO_ERROR_CAPTURE:
2300                 args->size = 0;
2301                 args->value = i915_gem_context_no_error_capture(ctx);
2302                 break;
2303
2304         case I915_CONTEXT_PARAM_BANNABLE:
2305                 args->size = 0;
2306                 args->value = i915_gem_context_is_bannable(ctx);
2307                 break;
2308
2309         case I915_CONTEXT_PARAM_RECOVERABLE:
2310                 args->size = 0;
2311                 args->value = i915_gem_context_is_recoverable(ctx);
2312                 break;
2313
2314         case I915_CONTEXT_PARAM_PRIORITY:
2315                 args->size = 0;
2316                 args->value = ctx->sched.priority >> I915_USER_PRIORITY_SHIFT;
2317                 break;
2318
2319         case I915_CONTEXT_PARAM_SSEU:
2320                 ret = get_sseu(ctx, args);
2321                 break;
2322
2323         case I915_CONTEXT_PARAM_VM:
2324                 ret = get_ppgtt(file_priv, ctx, args);
2325                 break;
2326
2327         case I915_CONTEXT_PARAM_ENGINES:
2328                 ret = get_engines(ctx, args);
2329                 break;
2330
2331         case I915_CONTEXT_PARAM_BAN_PERIOD:
2332         default:
2333                 ret = -EINVAL;
2334                 break;
2335         }
2336
2337         i915_gem_context_put(ctx);
2338         return ret;
2339 }
2340
2341 int i915_gem_context_setparam_ioctl(struct drm_device *dev, void *data,
2342                                     struct drm_file *file)
2343 {
2344         struct drm_i915_file_private *file_priv = file->driver_priv;
2345         struct drm_i915_gem_context_param *args = data;
2346         struct i915_gem_context *ctx;
2347         int ret;
2348
2349         ctx = i915_gem_context_lookup(file_priv, args->ctx_id);
2350         if (!ctx)
2351                 return -ENOENT;
2352
2353         ret = ctx_setparam(file_priv, ctx, args);
2354
2355         i915_gem_context_put(ctx);
2356         return ret;
2357 }
2358
2359 int i915_gem_context_reset_stats_ioctl(struct drm_device *dev,
2360                                        void *data, struct drm_file *file)
2361 {
2362         struct drm_i915_private *dev_priv = to_i915(dev);
2363         struct drm_i915_reset_stats *args = data;
2364         struct i915_gem_context *ctx;
2365         int ret;
2366
2367         if (args->flags || args->pad)
2368                 return -EINVAL;
2369
2370         ret = -ENOENT;
2371         rcu_read_lock();
2372         ctx = __i915_gem_context_lookup_rcu(file->driver_priv, args->ctx_id);
2373         if (!ctx)
2374                 goto out;
2375
2376         /*
2377          * We opt for unserialised reads here. This may result in tearing
2378          * in the extremely unlikely event of a GPU hang on this context
2379          * as we are querying them. If we need that extra layer of protection,
2380          * we should wrap the hangstats with a seqlock.
2381          */
2382
2383         if (capable(CAP_SYS_ADMIN))
2384                 args->reset_count = i915_reset_count(&dev_priv->gpu_error);
2385         else
2386                 args->reset_count = 0;
2387
2388         args->batch_active = atomic_read(&ctx->guilty_count);
2389         args->batch_pending = atomic_read(&ctx->active_count);
2390
2391         ret = 0;
2392 out:
2393         rcu_read_unlock();
2394         return ret;
2395 }
2396
2397 int __i915_gem_context_pin_hw_id(struct i915_gem_context *ctx)
2398 {
2399         struct drm_i915_private *i915 = ctx->i915;
2400         int err = 0;
2401
2402         mutex_lock(&i915->contexts.mutex);
2403
2404         GEM_BUG_ON(i915_gem_context_is_closed(ctx));
2405
2406         if (list_empty(&ctx->hw_id_link)) {
2407                 GEM_BUG_ON(atomic_read(&ctx->hw_id_pin_count));
2408
2409                 err = assign_hw_id(i915, &ctx->hw_id);
2410                 if (err)
2411                         goto out_unlock;
2412
2413                 list_add_tail(&ctx->hw_id_link, &i915->contexts.hw_id_list);
2414         }
2415
2416         GEM_BUG_ON(atomic_read(&ctx->hw_id_pin_count) == ~0u);
2417         atomic_inc(&ctx->hw_id_pin_count);
2418
2419 out_unlock:
2420         mutex_unlock(&i915->contexts.mutex);
2421         return err;
2422 }
2423
2424 /* GEM context-engines iterator: for_each_gem_engine() */
2425 struct intel_context *
2426 i915_gem_engines_iter_next(struct i915_gem_engines_iter *it)
2427 {
2428         const struct i915_gem_engines *e = it->engines;
2429         struct intel_context *ctx;
2430
2431         do {
2432                 if (it->idx >= e->num_engines)
2433                         return NULL;
2434
2435                 ctx = e->engines[it->idx++];
2436         } while (!ctx);
2437
2438         return ctx;
2439 }
2440
2441 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
2442 #include "selftests/mock_context.c"
2443 #include "selftests/i915_gem_context.c"
2444 #endif
2445
2446 static void i915_global_gem_context_shrink(void)
2447 {
2448         kmem_cache_shrink(global.slab_luts);
2449 }
2450
2451 static void i915_global_gem_context_exit(void)
2452 {
2453         kmem_cache_destroy(global.slab_luts);
2454 }
2455
2456 static struct i915_global_gem_context global = { {
2457         .shrink = i915_global_gem_context_shrink,
2458         .exit = i915_global_gem_context_exit,
2459 } };
2460
2461 int __init i915_global_gem_context_init(void)
2462 {
2463         global.slab_luts = KMEM_CACHE(i915_lut_handle, 0);
2464         if (!global.slab_luts)
2465                 return -ENOMEM;
2466
2467         i915_global_register(&global.base);
2468         return 0;
2469 }