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