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