dbaeb924a43773c4fd40997686bc695bc4104ecc
[linux-2.6-microblaze.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/drm_syncobj.h>
71
72 #include "gt/gen6_ppgtt.h"
73 #include "gt/intel_context.h"
74 #include "gt/intel_context_param.h"
75 #include "gt/intel_engine_heartbeat.h"
76 #include "gt/intel_engine_user.h"
77 #include "gt/intel_gpu_commands.h"
78 #include "gt/intel_ring.h"
79
80 #include "i915_gem_context.h"
81 #include "i915_trace.h"
82 #include "i915_user_extensions.h"
83
84 #define ALL_L3_SLICES(dev) (1 << NUM_L3_SLICES(dev)) - 1
85
86 static struct kmem_cache *slab_luts;
87
88 struct i915_lut_handle *i915_lut_handle_alloc(void)
89 {
90         return kmem_cache_alloc(slab_luts, GFP_KERNEL);
91 }
92
93 void i915_lut_handle_free(struct i915_lut_handle *lut)
94 {
95         return kmem_cache_free(slab_luts, lut);
96 }
97
98 static void lut_close(struct i915_gem_context *ctx)
99 {
100         struct radix_tree_iter iter;
101         void __rcu **slot;
102
103         mutex_lock(&ctx->lut_mutex);
104         rcu_read_lock();
105         radix_tree_for_each_slot(slot, &ctx->handles_vma, &iter, 0) {
106                 struct i915_vma *vma = rcu_dereference_raw(*slot);
107                 struct drm_i915_gem_object *obj = vma->obj;
108                 struct i915_lut_handle *lut;
109
110                 if (!kref_get_unless_zero(&obj->base.refcount))
111                         continue;
112
113                 spin_lock(&obj->lut_lock);
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                 spin_unlock(&obj->lut_lock);
125
126                 if (&lut->obj_link != &obj->lut_list) {
127                         i915_lut_handle_free(lut);
128                         radix_tree_iter_delete(&ctx->handles_vma, &iter, slot);
129                         i915_vma_close(vma);
130                         i915_gem_object_put(obj);
131                 }
132
133                 i915_gem_object_put(obj);
134         }
135         rcu_read_unlock();
136         mutex_unlock(&ctx->lut_mutex);
137 }
138
139 static struct intel_context *
140 lookup_user_engine(struct i915_gem_context *ctx,
141                    unsigned long flags,
142                    const struct i915_engine_class_instance *ci)
143 #define LOOKUP_USER_INDEX BIT(0)
144 {
145         int idx;
146
147         if (!!(flags & LOOKUP_USER_INDEX) != i915_gem_context_user_engines(ctx))
148                 return ERR_PTR(-EINVAL);
149
150         if (!i915_gem_context_user_engines(ctx)) {
151                 struct intel_engine_cs *engine;
152
153                 engine = intel_engine_lookup_user(ctx->i915,
154                                                   ci->engine_class,
155                                                   ci->engine_instance);
156                 if (!engine)
157                         return ERR_PTR(-EINVAL);
158
159                 idx = engine->legacy_idx;
160         } else {
161                 idx = ci->engine_instance;
162         }
163
164         return i915_gem_context_get_engine(ctx, idx);
165 }
166
167 static int validate_priority(struct drm_i915_private *i915,
168                              const struct drm_i915_gem_context_param *args)
169 {
170         s64 priority = args->value;
171
172         if (args->size)
173                 return -EINVAL;
174
175         if (!(i915->caps.scheduler & I915_SCHEDULER_CAP_PRIORITY))
176                 return -ENODEV;
177
178         if (priority > I915_CONTEXT_MAX_USER_PRIORITY ||
179             priority < I915_CONTEXT_MIN_USER_PRIORITY)
180                 return -EINVAL;
181
182         if (priority > I915_CONTEXT_DEFAULT_PRIORITY &&
183             !capable(CAP_SYS_NICE))
184                 return -EPERM;
185
186         return 0;
187 }
188
189 static void proto_context_close(struct i915_gem_proto_context *pc)
190 {
191         int i;
192
193         if (pc->vm)
194                 i915_vm_put(pc->vm);
195         if (pc->user_engines) {
196                 for (i = 0; i < pc->num_user_engines; i++)
197                         kfree(pc->user_engines[i].siblings);
198                 kfree(pc->user_engines);
199         }
200         kfree(pc);
201 }
202
203 static int proto_context_set_persistence(struct drm_i915_private *i915,
204                                          struct i915_gem_proto_context *pc,
205                                          bool persist)
206 {
207         if (persist) {
208                 /*
209                  * Only contexts that are short-lived [that will expire or be
210                  * reset] are allowed to survive past termination. We require
211                  * hangcheck to ensure that the persistent requests are healthy.
212                  */
213                 if (!i915->params.enable_hangcheck)
214                         return -EINVAL;
215
216                 pc->user_flags |= BIT(UCONTEXT_PERSISTENCE);
217         } else {
218                 /* To cancel a context we use "preempt-to-idle" */
219                 if (!(i915->caps.scheduler & I915_SCHEDULER_CAP_PREEMPTION))
220                         return -ENODEV;
221
222                 /*
223                  * If the cancel fails, we then need to reset, cleanly!
224                  *
225                  * If the per-engine reset fails, all hope is lost! We resort
226                  * to a full GPU reset in that unlikely case, but realistically
227                  * if the engine could not reset, the full reset does not fare
228                  * much better. The damage has been done.
229                  *
230                  * However, if we cannot reset an engine by itself, we cannot
231                  * cleanup a hanging persistent context without causing
232                  * colateral damage, and we should not pretend we can by
233                  * exposing the interface.
234                  */
235                 if (!intel_has_reset_engine(&i915->gt))
236                         return -ENODEV;
237
238                 pc->user_flags &= ~BIT(UCONTEXT_PERSISTENCE);
239         }
240
241         return 0;
242 }
243
244 static struct i915_gem_proto_context *
245 proto_context_create(struct drm_i915_private *i915, unsigned int flags)
246 {
247         struct i915_gem_proto_context *pc, *err;
248
249         pc = kzalloc(sizeof(*pc), GFP_KERNEL);
250         if (!pc)
251                 return ERR_PTR(-ENOMEM);
252
253         pc->num_user_engines = -1;
254         pc->user_engines = NULL;
255         pc->user_flags = BIT(UCONTEXT_BANNABLE) |
256                          BIT(UCONTEXT_RECOVERABLE);
257         if (i915->params.enable_hangcheck)
258                 pc->user_flags |= BIT(UCONTEXT_PERSISTENCE);
259         pc->sched.priority = I915_PRIORITY_NORMAL;
260
261         if (flags & I915_CONTEXT_CREATE_FLAGS_SINGLE_TIMELINE) {
262                 if (!HAS_EXECLISTS(i915)) {
263                         err = ERR_PTR(-EINVAL);
264                         goto proto_close;
265                 }
266                 pc->single_timeline = true;
267         }
268
269         return pc;
270
271 proto_close:
272         proto_context_close(pc);
273         return err;
274 }
275
276 static int proto_context_register_locked(struct drm_i915_file_private *fpriv,
277                                          struct i915_gem_proto_context *pc,
278                                          u32 *id)
279 {
280         int ret;
281         void *old;
282
283         lockdep_assert_held(&fpriv->proto_context_lock);
284
285         ret = xa_alloc(&fpriv->context_xa, id, NULL, xa_limit_32b, GFP_KERNEL);
286         if (ret)
287                 return ret;
288
289         old = xa_store(&fpriv->proto_context_xa, *id, pc, GFP_KERNEL);
290         if (xa_is_err(old)) {
291                 xa_erase(&fpriv->context_xa, *id);
292                 return xa_err(old);
293         }
294         WARN_ON(old);
295
296         return 0;
297 }
298
299 static int proto_context_register(struct drm_i915_file_private *fpriv,
300                                   struct i915_gem_proto_context *pc,
301                                   u32 *id)
302 {
303         int ret;
304
305         mutex_lock(&fpriv->proto_context_lock);
306         ret = proto_context_register_locked(fpriv, pc, id);
307         mutex_unlock(&fpriv->proto_context_lock);
308
309         return ret;
310 }
311
312 static int set_proto_ctx_vm(struct drm_i915_file_private *fpriv,
313                             struct i915_gem_proto_context *pc,
314                             const struct drm_i915_gem_context_param *args)
315 {
316         struct drm_i915_private *i915 = fpriv->dev_priv;
317         struct i915_address_space *vm;
318
319         if (args->size)
320                 return -EINVAL;
321
322         if (!HAS_FULL_PPGTT(i915))
323                 return -ENODEV;
324
325         if (upper_32_bits(args->value))
326                 return -ENOENT;
327
328         vm = i915_gem_vm_lookup(fpriv, args->value);
329         if (!vm)
330                 return -ENOENT;
331
332         if (pc->vm)
333                 i915_vm_put(pc->vm);
334         pc->vm = vm;
335
336         return 0;
337 }
338
339 struct set_proto_ctx_engines {
340         struct drm_i915_private *i915;
341         unsigned num_engines;
342         struct i915_gem_proto_engine *engines;
343 };
344
345 static int
346 set_proto_ctx_engines_balance(struct i915_user_extension __user *base,
347                               void *data)
348 {
349         struct i915_context_engines_load_balance __user *ext =
350                 container_of_user(base, typeof(*ext), base);
351         const struct set_proto_ctx_engines *set = data;
352         struct drm_i915_private *i915 = set->i915;
353         struct intel_engine_cs **siblings;
354         u16 num_siblings, idx;
355         unsigned int n;
356         int err;
357
358         if (!HAS_EXECLISTS(i915))
359                 return -ENODEV;
360
361         if (get_user(idx, &ext->engine_index))
362                 return -EFAULT;
363
364         if (idx >= set->num_engines) {
365                 drm_dbg(&i915->drm, "Invalid placement value, %d >= %d\n",
366                         idx, set->num_engines);
367                 return -EINVAL;
368         }
369
370         idx = array_index_nospec(idx, set->num_engines);
371         if (set->engines[idx].type != I915_GEM_ENGINE_TYPE_INVALID) {
372                 drm_dbg(&i915->drm,
373                         "Invalid placement[%d], already occupied\n", idx);
374                 return -EEXIST;
375         }
376
377         if (get_user(num_siblings, &ext->num_siblings))
378                 return -EFAULT;
379
380         err = check_user_mbz(&ext->flags);
381         if (err)
382                 return err;
383
384         err = check_user_mbz(&ext->mbz64);
385         if (err)
386                 return err;
387
388         if (num_siblings == 0)
389                 return 0;
390
391         siblings = kmalloc_array(num_siblings, sizeof(*siblings), GFP_KERNEL);
392         if (!siblings)
393                 return -ENOMEM;
394
395         for (n = 0; n < num_siblings; n++) {
396                 struct i915_engine_class_instance ci;
397
398                 if (copy_from_user(&ci, &ext->engines[n], sizeof(ci))) {
399                         err = -EFAULT;
400                         goto err_siblings;
401                 }
402
403                 siblings[n] = intel_engine_lookup_user(i915,
404                                                        ci.engine_class,
405                                                        ci.engine_instance);
406                 if (!siblings[n]) {
407                         drm_dbg(&i915->drm,
408                                 "Invalid sibling[%d]: { class:%d, inst:%d }\n",
409                                 n, ci.engine_class, ci.engine_instance);
410                         err = -EINVAL;
411                         goto err_siblings;
412                 }
413         }
414
415         if (num_siblings == 1) {
416                 set->engines[idx].type = I915_GEM_ENGINE_TYPE_PHYSICAL;
417                 set->engines[idx].engine = siblings[0];
418                 kfree(siblings);
419         } else {
420                 set->engines[idx].type = I915_GEM_ENGINE_TYPE_BALANCED;
421                 set->engines[idx].num_siblings = num_siblings;
422                 set->engines[idx].siblings = siblings;
423         }
424
425         return 0;
426
427 err_siblings:
428         kfree(siblings);
429
430         return err;
431 }
432
433 static int
434 set_proto_ctx_engines_bond(struct i915_user_extension __user *base, void *data)
435 {
436         struct i915_context_engines_bond __user *ext =
437                 container_of_user(base, typeof(*ext), base);
438         const struct set_proto_ctx_engines *set = data;
439         struct drm_i915_private *i915 = set->i915;
440         struct i915_engine_class_instance ci;
441         struct intel_engine_cs *master;
442         u16 idx, num_bonds;
443         int err, n;
444
445         if (GRAPHICS_VER(i915) >= 12 && !IS_TIGERLAKE(i915) &&
446             !IS_ROCKETLAKE(i915) && !IS_ALDERLAKE_S(i915)) {
447                 drm_dbg(&i915->drm,
448                         "Bonding on gen12+ aside from TGL, RKL, and ADL_S not supported\n");
449                 return -ENODEV;
450         }
451
452         if (get_user(idx, &ext->virtual_index))
453                 return -EFAULT;
454
455         if (idx >= set->num_engines) {
456                 drm_dbg(&i915->drm,
457                         "Invalid index for virtual engine: %d >= %d\n",
458                         idx, set->num_engines);
459                 return -EINVAL;
460         }
461
462         idx = array_index_nospec(idx, set->num_engines);
463         if (set->engines[idx].type == I915_GEM_ENGINE_TYPE_INVALID) {
464                 drm_dbg(&i915->drm, "Invalid engine at %d\n", idx);
465                 return -EINVAL;
466         }
467
468         if (set->engines[idx].type != I915_GEM_ENGINE_TYPE_PHYSICAL) {
469                 drm_dbg(&i915->drm,
470                         "Bonding with virtual engines not allowed\n");
471                 return -EINVAL;
472         }
473
474         err = check_user_mbz(&ext->flags);
475         if (err)
476                 return err;
477
478         for (n = 0; n < ARRAY_SIZE(ext->mbz64); n++) {
479                 err = check_user_mbz(&ext->mbz64[n]);
480                 if (err)
481                         return err;
482         }
483
484         if (copy_from_user(&ci, &ext->master, sizeof(ci)))
485                 return -EFAULT;
486
487         master = intel_engine_lookup_user(i915,
488                                           ci.engine_class,
489                                           ci.engine_instance);
490         if (!master) {
491                 drm_dbg(&i915->drm,
492                         "Unrecognised master engine: { class:%u, instance:%u }\n",
493                         ci.engine_class, ci.engine_instance);
494                 return -EINVAL;
495         }
496
497         if (intel_engine_uses_guc(master)) {
498                 DRM_DEBUG("bonding extension not supported with GuC submission");
499                 return -ENODEV;
500         }
501
502         if (get_user(num_bonds, &ext->num_bonds))
503                 return -EFAULT;
504
505         for (n = 0; n < num_bonds; n++) {
506                 struct intel_engine_cs *bond;
507
508                 if (copy_from_user(&ci, &ext->engines[n], sizeof(ci)))
509                         return -EFAULT;
510
511                 bond = intel_engine_lookup_user(i915,
512                                                 ci.engine_class,
513                                                 ci.engine_instance);
514                 if (!bond) {
515                         drm_dbg(&i915->drm,
516                                 "Unrecognised engine[%d] for bonding: { class:%d, instance: %d }\n",
517                                 n, ci.engine_class, ci.engine_instance);
518                         return -EINVAL;
519                 }
520         }
521
522         return 0;
523 }
524
525 static const i915_user_extension_fn set_proto_ctx_engines_extensions[] = {
526         [I915_CONTEXT_ENGINES_EXT_LOAD_BALANCE] = set_proto_ctx_engines_balance,
527         [I915_CONTEXT_ENGINES_EXT_BOND] = set_proto_ctx_engines_bond,
528 };
529
530 static int set_proto_ctx_engines(struct drm_i915_file_private *fpriv,
531                                  struct i915_gem_proto_context *pc,
532                                  const struct drm_i915_gem_context_param *args)
533 {
534         struct drm_i915_private *i915 = fpriv->dev_priv;
535         struct set_proto_ctx_engines set = { .i915 = i915 };
536         struct i915_context_param_engines __user *user =
537                 u64_to_user_ptr(args->value);
538         unsigned int n;
539         u64 extensions;
540         int err;
541
542         if (pc->num_user_engines >= 0) {
543                 drm_dbg(&i915->drm, "Cannot set engines twice");
544                 return -EINVAL;
545         }
546
547         if (args->size < sizeof(*user) ||
548             !IS_ALIGNED(args->size - sizeof(*user), sizeof(*user->engines))) {
549                 drm_dbg(&i915->drm, "Invalid size for engine array: %d\n",
550                         args->size);
551                 return -EINVAL;
552         }
553
554         set.num_engines = (args->size - sizeof(*user)) / sizeof(*user->engines);
555         /* RING_MASK has no shift so we can use it directly here */
556         if (set.num_engines > I915_EXEC_RING_MASK + 1)
557                 return -EINVAL;
558
559         set.engines = kmalloc_array(set.num_engines, sizeof(*set.engines), GFP_KERNEL);
560         if (!set.engines)
561                 return -ENOMEM;
562
563         for (n = 0; n < set.num_engines; n++) {
564                 struct i915_engine_class_instance ci;
565                 struct intel_engine_cs *engine;
566
567                 if (copy_from_user(&ci, &user->engines[n], sizeof(ci))) {
568                         kfree(set.engines);
569                         return -EFAULT;
570                 }
571
572                 memset(&set.engines[n], 0, sizeof(set.engines[n]));
573
574                 if (ci.engine_class == (u16)I915_ENGINE_CLASS_INVALID &&
575                     ci.engine_instance == (u16)I915_ENGINE_CLASS_INVALID_NONE)
576                         continue;
577
578                 engine = intel_engine_lookup_user(i915,
579                                                   ci.engine_class,
580                                                   ci.engine_instance);
581                 if (!engine) {
582                         drm_dbg(&i915->drm,
583                                 "Invalid engine[%d]: { class:%d, instance:%d }\n",
584                                 n, ci.engine_class, ci.engine_instance);
585                         kfree(set.engines);
586                         return -ENOENT;
587                 }
588
589                 set.engines[n].type = I915_GEM_ENGINE_TYPE_PHYSICAL;
590                 set.engines[n].engine = engine;
591         }
592
593         err = -EFAULT;
594         if (!get_user(extensions, &user->extensions))
595                 err = i915_user_extensions(u64_to_user_ptr(extensions),
596                                            set_proto_ctx_engines_extensions,
597                                            ARRAY_SIZE(set_proto_ctx_engines_extensions),
598                                            &set);
599         if (err) {
600                 kfree(set.engines);
601                 return err;
602         }
603
604         pc->num_user_engines = set.num_engines;
605         pc->user_engines = set.engines;
606
607         return 0;
608 }
609
610 static int set_proto_ctx_sseu(struct drm_i915_file_private *fpriv,
611                               struct i915_gem_proto_context *pc,
612                               struct drm_i915_gem_context_param *args)
613 {
614         struct drm_i915_private *i915 = fpriv->dev_priv;
615         struct drm_i915_gem_context_param_sseu user_sseu;
616         struct intel_sseu *sseu;
617         int ret;
618
619         if (args->size < sizeof(user_sseu))
620                 return -EINVAL;
621
622         if (GRAPHICS_VER(i915) != 11)
623                 return -ENODEV;
624
625         if (copy_from_user(&user_sseu, u64_to_user_ptr(args->value),
626                            sizeof(user_sseu)))
627                 return -EFAULT;
628
629         if (user_sseu.rsvd)
630                 return -EINVAL;
631
632         if (user_sseu.flags & ~(I915_CONTEXT_SSEU_FLAG_ENGINE_INDEX))
633                 return -EINVAL;
634
635         if (!!(user_sseu.flags & I915_CONTEXT_SSEU_FLAG_ENGINE_INDEX) != (pc->num_user_engines >= 0))
636                 return -EINVAL;
637
638         if (pc->num_user_engines >= 0) {
639                 int idx = user_sseu.engine.engine_instance;
640                 struct i915_gem_proto_engine *pe;
641
642                 if (idx >= pc->num_user_engines)
643                         return -EINVAL;
644
645                 pe = &pc->user_engines[idx];
646
647                 /* Only render engine supports RPCS configuration. */
648                 if (pe->engine->class != RENDER_CLASS)
649                         return -EINVAL;
650
651                 sseu = &pe->sseu;
652         } else {
653                 /* Only render engine supports RPCS configuration. */
654                 if (user_sseu.engine.engine_class != I915_ENGINE_CLASS_RENDER)
655                         return -EINVAL;
656
657                 /* There is only one render engine */
658                 if (user_sseu.engine.engine_instance != 0)
659                         return -EINVAL;
660
661                 sseu = &pc->legacy_rcs_sseu;
662         }
663
664         ret = i915_gem_user_to_context_sseu(&i915->gt, &user_sseu, sseu);
665         if (ret)
666                 return ret;
667
668         args->size = sizeof(user_sseu);
669
670         return 0;
671 }
672
673 static int set_proto_ctx_param(struct drm_i915_file_private *fpriv,
674                                struct i915_gem_proto_context *pc,
675                                struct drm_i915_gem_context_param *args)
676 {
677         int ret = 0;
678
679         switch (args->param) {
680         case I915_CONTEXT_PARAM_NO_ERROR_CAPTURE:
681                 if (args->size)
682                         ret = -EINVAL;
683                 else if (args->value)
684                         pc->user_flags |= BIT(UCONTEXT_NO_ERROR_CAPTURE);
685                 else
686                         pc->user_flags &= ~BIT(UCONTEXT_NO_ERROR_CAPTURE);
687                 break;
688
689         case I915_CONTEXT_PARAM_BANNABLE:
690                 if (args->size)
691                         ret = -EINVAL;
692                 else if (!capable(CAP_SYS_ADMIN) && !args->value)
693                         ret = -EPERM;
694                 else if (args->value)
695                         pc->user_flags |= BIT(UCONTEXT_BANNABLE);
696                 else
697                         pc->user_flags &= ~BIT(UCONTEXT_BANNABLE);
698                 break;
699
700         case I915_CONTEXT_PARAM_RECOVERABLE:
701                 if (args->size)
702                         ret = -EINVAL;
703                 else if (args->value)
704                         pc->user_flags |= BIT(UCONTEXT_RECOVERABLE);
705                 else
706                         pc->user_flags &= ~BIT(UCONTEXT_RECOVERABLE);
707                 break;
708
709         case I915_CONTEXT_PARAM_PRIORITY:
710                 ret = validate_priority(fpriv->dev_priv, args);
711                 if (!ret)
712                         pc->sched.priority = args->value;
713                 break;
714
715         case I915_CONTEXT_PARAM_SSEU:
716                 ret = set_proto_ctx_sseu(fpriv, pc, args);
717                 break;
718
719         case I915_CONTEXT_PARAM_VM:
720                 ret = set_proto_ctx_vm(fpriv, pc, args);
721                 break;
722
723         case I915_CONTEXT_PARAM_ENGINES:
724                 ret = set_proto_ctx_engines(fpriv, pc, args);
725                 break;
726
727         case I915_CONTEXT_PARAM_PERSISTENCE:
728                 if (args->size)
729                         ret = -EINVAL;
730                 ret = proto_context_set_persistence(fpriv->dev_priv, pc,
731                                                     args->value);
732                 break;
733
734         case I915_CONTEXT_PARAM_NO_ZEROMAP:
735         case I915_CONTEXT_PARAM_BAN_PERIOD:
736         case I915_CONTEXT_PARAM_RINGSIZE:
737         default:
738                 ret = -EINVAL;
739                 break;
740         }
741
742         return ret;
743 }
744
745 static struct i915_address_space *
746 context_get_vm_rcu(struct i915_gem_context *ctx)
747 {
748         GEM_BUG_ON(!rcu_access_pointer(ctx->vm));
749
750         do {
751                 struct i915_address_space *vm;
752
753                 /*
754                  * We do not allow downgrading from full-ppgtt [to a shared
755                  * global gtt], so ctx->vm cannot become NULL.
756                  */
757                 vm = rcu_dereference(ctx->vm);
758                 if (!kref_get_unless_zero(&vm->ref))
759                         continue;
760
761                 /*
762                  * This ppgtt may have be reallocated between
763                  * the read and the kref, and reassigned to a third
764                  * context. In order to avoid inadvertent sharing
765                  * of this ppgtt with that third context (and not
766                  * src), we have to confirm that we have the same
767                  * ppgtt after passing through the strong memory
768                  * barrier implied by a successful
769                  * kref_get_unless_zero().
770                  *
771                  * Once we have acquired the current ppgtt of ctx,
772                  * we no longer care if it is released from ctx, as
773                  * it cannot be reallocated elsewhere.
774                  */
775
776                 if (vm == rcu_access_pointer(ctx->vm))
777                         return rcu_pointer_handoff(vm);
778
779                 i915_vm_put(vm);
780         } while (1);
781 }
782
783 static int intel_context_set_gem(struct intel_context *ce,
784                                  struct i915_gem_context *ctx,
785                                  struct intel_sseu sseu)
786 {
787         int ret = 0;
788
789         GEM_BUG_ON(rcu_access_pointer(ce->gem_context));
790         RCU_INIT_POINTER(ce->gem_context, ctx);
791
792         ce->ring_size = SZ_16K;
793
794         if (rcu_access_pointer(ctx->vm)) {
795                 struct i915_address_space *vm;
796
797                 rcu_read_lock();
798                 vm = context_get_vm_rcu(ctx); /* hmm */
799                 rcu_read_unlock();
800
801                 i915_vm_put(ce->vm);
802                 ce->vm = vm;
803         }
804
805         if (ctx->sched.priority >= I915_PRIORITY_NORMAL &&
806             intel_engine_has_timeslices(ce->engine) &&
807             intel_engine_has_semaphores(ce->engine))
808                 __set_bit(CONTEXT_USE_SEMAPHORES, &ce->flags);
809
810         if (IS_ACTIVE(CONFIG_DRM_I915_REQUEST_TIMEOUT) &&
811             ctx->i915->params.request_timeout_ms) {
812                 unsigned int timeout_ms = ctx->i915->params.request_timeout_ms;
813
814                 intel_context_set_watchdog_us(ce, (u64)timeout_ms * 1000);
815         }
816
817         /* A valid SSEU has no zero fields */
818         if (sseu.slice_mask && !WARN_ON(ce->engine->class != RENDER_CLASS))
819                 ret = intel_context_reconfigure_sseu(ce, sseu);
820
821         return ret;
822 }
823
824 static void __free_engines(struct i915_gem_engines *e, unsigned int count)
825 {
826         while (count--) {
827                 if (!e->engines[count])
828                         continue;
829
830                 intel_context_put(e->engines[count]);
831         }
832         kfree(e);
833 }
834
835 static void free_engines(struct i915_gem_engines *e)
836 {
837         __free_engines(e, e->num_engines);
838 }
839
840 static void free_engines_rcu(struct rcu_head *rcu)
841 {
842         struct i915_gem_engines *engines =
843                 container_of(rcu, struct i915_gem_engines, rcu);
844
845         i915_sw_fence_fini(&engines->fence);
846         free_engines(engines);
847 }
848
849 static int __i915_sw_fence_call
850 engines_notify(struct i915_sw_fence *fence, enum i915_sw_fence_notify state)
851 {
852         struct i915_gem_engines *engines =
853                 container_of(fence, typeof(*engines), fence);
854
855         switch (state) {
856         case FENCE_COMPLETE:
857                 if (!list_empty(&engines->link)) {
858                         struct i915_gem_context *ctx = engines->ctx;
859                         unsigned long flags;
860
861                         spin_lock_irqsave(&ctx->stale.lock, flags);
862                         list_del(&engines->link);
863                         spin_unlock_irqrestore(&ctx->stale.lock, flags);
864                 }
865                 i915_gem_context_put(engines->ctx);
866                 break;
867
868         case FENCE_FREE:
869                 init_rcu_head(&engines->rcu);
870                 call_rcu(&engines->rcu, free_engines_rcu);
871                 break;
872         }
873
874         return NOTIFY_DONE;
875 }
876
877 static struct i915_gem_engines *alloc_engines(unsigned int count)
878 {
879         struct i915_gem_engines *e;
880
881         e = kzalloc(struct_size(e, engines, count), GFP_KERNEL);
882         if (!e)
883                 return NULL;
884
885         i915_sw_fence_init(&e->fence, engines_notify);
886         return e;
887 }
888
889 static struct i915_gem_engines *default_engines(struct i915_gem_context *ctx,
890                                                 struct intel_sseu rcs_sseu)
891 {
892         const struct intel_gt *gt = &ctx->i915->gt;
893         struct intel_engine_cs *engine;
894         struct i915_gem_engines *e, *err;
895         enum intel_engine_id id;
896
897         e = alloc_engines(I915_NUM_ENGINES);
898         if (!e)
899                 return ERR_PTR(-ENOMEM);
900
901         for_each_engine(engine, gt, id) {
902                 struct intel_context *ce;
903                 struct intel_sseu sseu = {};
904                 int ret;
905
906                 if (engine->legacy_idx == INVALID_ENGINE)
907                         continue;
908
909                 GEM_BUG_ON(engine->legacy_idx >= I915_NUM_ENGINES);
910                 GEM_BUG_ON(e->engines[engine->legacy_idx]);
911
912                 ce = intel_context_create(engine);
913                 if (IS_ERR(ce)) {
914                         err = ERR_CAST(ce);
915                         goto free_engines;
916                 }
917
918                 e->engines[engine->legacy_idx] = ce;
919                 e->num_engines = max(e->num_engines, engine->legacy_idx + 1);
920
921                 if (engine->class == RENDER_CLASS)
922                         sseu = rcs_sseu;
923
924                 ret = intel_context_set_gem(ce, ctx, sseu);
925                 if (ret) {
926                         err = ERR_PTR(ret);
927                         goto free_engines;
928                 }
929
930         }
931
932         return e;
933
934 free_engines:
935         free_engines(e);
936         return err;
937 }
938
939 static struct i915_gem_engines *user_engines(struct i915_gem_context *ctx,
940                                              unsigned int num_engines,
941                                              struct i915_gem_proto_engine *pe)
942 {
943         struct i915_gem_engines *e, *err;
944         unsigned int n;
945
946         e = alloc_engines(num_engines);
947         for (n = 0; n < num_engines; n++) {
948                 struct intel_context *ce;
949                 int ret;
950
951                 switch (pe[n].type) {
952                 case I915_GEM_ENGINE_TYPE_PHYSICAL:
953                         ce = intel_context_create(pe[n].engine);
954                         break;
955
956                 case I915_GEM_ENGINE_TYPE_BALANCED:
957                         ce = intel_engine_create_virtual(pe[n].siblings,
958                                                          pe[n].num_siblings);
959                         break;
960
961                 case I915_GEM_ENGINE_TYPE_INVALID:
962                 default:
963                         GEM_WARN_ON(pe[n].type != I915_GEM_ENGINE_TYPE_INVALID);
964                         continue;
965                 }
966
967                 if (IS_ERR(ce)) {
968                         err = ERR_CAST(ce);
969                         goto free_engines;
970                 }
971
972                 e->engines[n] = ce;
973
974                 ret = intel_context_set_gem(ce, ctx, pe->sseu);
975                 if (ret) {
976                         err = ERR_PTR(ret);
977                         goto free_engines;
978                 }
979         }
980         e->num_engines = num_engines;
981
982         return e;
983
984 free_engines:
985         free_engines(e);
986         return err;
987 }
988
989 void i915_gem_context_release(struct kref *ref)
990 {
991         struct i915_gem_context *ctx = container_of(ref, typeof(*ctx), ref);
992
993         trace_i915_context_free(ctx);
994         GEM_BUG_ON(!i915_gem_context_is_closed(ctx));
995
996         mutex_destroy(&ctx->engines_mutex);
997         mutex_destroy(&ctx->lut_mutex);
998
999         put_pid(ctx->pid);
1000         mutex_destroy(&ctx->mutex);
1001
1002         kfree_rcu(ctx, rcu);
1003 }
1004
1005 static inline struct i915_gem_engines *
1006 __context_engines_static(const struct i915_gem_context *ctx)
1007 {
1008         return rcu_dereference_protected(ctx->engines, true);
1009 }
1010
1011 static void __reset_context(struct i915_gem_context *ctx,
1012                             struct intel_engine_cs *engine)
1013 {
1014         intel_gt_handle_error(engine->gt, engine->mask, 0,
1015                               "context closure in %s", ctx->name);
1016 }
1017
1018 static bool __cancel_engine(struct intel_engine_cs *engine)
1019 {
1020         /*
1021          * Send a "high priority pulse" down the engine to cause the
1022          * current request to be momentarily preempted. (If it fails to
1023          * be preempted, it will be reset). As we have marked our context
1024          * as banned, any incomplete request, including any running, will
1025          * be skipped following the preemption.
1026          *
1027          * If there is no hangchecking (one of the reasons why we try to
1028          * cancel the context) and no forced preemption, there may be no
1029          * means by which we reset the GPU and evict the persistent hog.
1030          * Ergo if we are unable to inject a preemptive pulse that can
1031          * kill the banned context, we fallback to doing a local reset
1032          * instead.
1033          */
1034         return intel_engine_pulse(engine) == 0;
1035 }
1036
1037 static struct intel_engine_cs *active_engine(struct intel_context *ce)
1038 {
1039         struct intel_engine_cs *engine = NULL;
1040         struct i915_request *rq;
1041
1042         if (intel_context_has_inflight(ce))
1043                 return intel_context_inflight(ce);
1044
1045         if (!ce->timeline)
1046                 return NULL;
1047
1048         /*
1049          * rq->link is only SLAB_TYPESAFE_BY_RCU, we need to hold a reference
1050          * to the request to prevent it being transferred to a new timeline
1051          * (and onto a new timeline->requests list).
1052          */
1053         rcu_read_lock();
1054         list_for_each_entry_reverse(rq, &ce->timeline->requests, link) {
1055                 bool found;
1056
1057                 /* timeline is already completed upto this point? */
1058                 if (!i915_request_get_rcu(rq))
1059                         break;
1060
1061                 /* Check with the backend if the request is inflight */
1062                 found = true;
1063                 if (likely(rcu_access_pointer(rq->timeline) == ce->timeline))
1064                         found = i915_request_active_engine(rq, &engine);
1065
1066                 i915_request_put(rq);
1067                 if (found)
1068                         break;
1069         }
1070         rcu_read_unlock();
1071
1072         return engine;
1073 }
1074
1075 static void kill_engines(struct i915_gem_engines *engines, bool ban)
1076 {
1077         struct i915_gem_engines_iter it;
1078         struct intel_context *ce;
1079
1080         /*
1081          * Map the user's engine back to the actual engines; one virtual
1082          * engine will be mapped to multiple engines, and using ctx->engine[]
1083          * the same engine may be have multiple instances in the user's map.
1084          * However, we only care about pending requests, so only include
1085          * engines on which there are incomplete requests.
1086          */
1087         for_each_gem_engine(ce, engines, it) {
1088                 struct intel_engine_cs *engine;
1089
1090                 if (ban && intel_context_ban(ce, NULL))
1091                         continue;
1092
1093                 /*
1094                  * Check the current active state of this context; if we
1095                  * are currently executing on the GPU we need to evict
1096                  * ourselves. On the other hand, if we haven't yet been
1097                  * submitted to the GPU or if everything is complete,
1098                  * we have nothing to do.
1099                  */
1100                 engine = active_engine(ce);
1101
1102                 /* First attempt to gracefully cancel the context */
1103                 if (engine && !__cancel_engine(engine) && ban)
1104                         /*
1105                          * If we are unable to send a preemptive pulse to bump
1106                          * the context from the GPU, we have to resort to a full
1107                          * reset. We hope the collateral damage is worth it.
1108                          */
1109                         __reset_context(engines->ctx, engine);
1110         }
1111 }
1112
1113 static void kill_context(struct i915_gem_context *ctx)
1114 {
1115         bool ban = (!i915_gem_context_is_persistent(ctx) ||
1116                     !ctx->i915->params.enable_hangcheck);
1117         struct i915_gem_engines *pos, *next;
1118
1119         spin_lock_irq(&ctx->stale.lock);
1120         GEM_BUG_ON(!i915_gem_context_is_closed(ctx));
1121         list_for_each_entry_safe(pos, next, &ctx->stale.engines, link) {
1122                 if (!i915_sw_fence_await(&pos->fence)) {
1123                         list_del_init(&pos->link);
1124                         continue;
1125                 }
1126
1127                 spin_unlock_irq(&ctx->stale.lock);
1128
1129                 kill_engines(pos, ban);
1130
1131                 spin_lock_irq(&ctx->stale.lock);
1132                 GEM_BUG_ON(i915_sw_fence_signaled(&pos->fence));
1133                 list_safe_reset_next(pos, next, link);
1134                 list_del_init(&pos->link); /* decouple from FENCE_COMPLETE */
1135
1136                 i915_sw_fence_complete(&pos->fence);
1137         }
1138         spin_unlock_irq(&ctx->stale.lock);
1139 }
1140
1141 static void engines_idle_release(struct i915_gem_context *ctx,
1142                                  struct i915_gem_engines *engines)
1143 {
1144         struct i915_gem_engines_iter it;
1145         struct intel_context *ce;
1146
1147         INIT_LIST_HEAD(&engines->link);
1148
1149         engines->ctx = i915_gem_context_get(ctx);
1150
1151         for_each_gem_engine(ce, engines, it) {
1152                 int err;
1153
1154                 /* serialises with execbuf */
1155                 set_bit(CONTEXT_CLOSED_BIT, &ce->flags);
1156                 if (!intel_context_pin_if_active(ce))
1157                         continue;
1158
1159                 /* Wait until context is finally scheduled out and retired */
1160                 err = i915_sw_fence_await_active(&engines->fence,
1161                                                  &ce->active,
1162                                                  I915_ACTIVE_AWAIT_BARRIER);
1163                 intel_context_unpin(ce);
1164                 if (err)
1165                         goto kill;
1166         }
1167
1168         spin_lock_irq(&ctx->stale.lock);
1169         if (!i915_gem_context_is_closed(ctx))
1170                 list_add_tail(&engines->link, &ctx->stale.engines);
1171         spin_unlock_irq(&ctx->stale.lock);
1172
1173 kill:
1174         if (list_empty(&engines->link)) /* raced, already closed */
1175                 kill_engines(engines, true);
1176
1177         i915_sw_fence_commit(&engines->fence);
1178 }
1179
1180 static void set_closed_name(struct i915_gem_context *ctx)
1181 {
1182         char *s;
1183
1184         /* Replace '[]' with '<>' to indicate closed in debug prints */
1185
1186         s = strrchr(ctx->name, '[');
1187         if (!s)
1188                 return;
1189
1190         *s = '<';
1191
1192         s = strchr(s + 1, ']');
1193         if (s)
1194                 *s = '>';
1195 }
1196
1197 static void context_close(struct i915_gem_context *ctx)
1198 {
1199         struct i915_address_space *vm;
1200
1201         /* Flush any concurrent set_engines() */
1202         mutex_lock(&ctx->engines_mutex);
1203         engines_idle_release(ctx, rcu_replace_pointer(ctx->engines, NULL, 1));
1204         i915_gem_context_set_closed(ctx);
1205         mutex_unlock(&ctx->engines_mutex);
1206
1207         mutex_lock(&ctx->mutex);
1208
1209         set_closed_name(ctx);
1210
1211         vm = i915_gem_context_vm(ctx);
1212         if (vm)
1213                 i915_vm_close(vm);
1214
1215         if (ctx->syncobj)
1216                 drm_syncobj_put(ctx->syncobj);
1217
1218         ctx->file_priv = ERR_PTR(-EBADF);
1219
1220         /*
1221          * The LUT uses the VMA as a backpointer to unref the object,
1222          * so we need to clear the LUT before we close all the VMA (inside
1223          * the ppgtt).
1224          */
1225         lut_close(ctx);
1226
1227         spin_lock(&ctx->i915->gem.contexts.lock);
1228         list_del(&ctx->link);
1229         spin_unlock(&ctx->i915->gem.contexts.lock);
1230
1231         mutex_unlock(&ctx->mutex);
1232
1233         /*
1234          * If the user has disabled hangchecking, we can not be sure that
1235          * the batches will ever complete after the context is closed,
1236          * keeping the context and all resources pinned forever. So in this
1237          * case we opt to forcibly kill off all remaining requests on
1238          * context close.
1239          */
1240         kill_context(ctx);
1241
1242         i915_gem_context_put(ctx);
1243 }
1244
1245 static int __context_set_persistence(struct i915_gem_context *ctx, bool state)
1246 {
1247         if (i915_gem_context_is_persistent(ctx) == state)
1248                 return 0;
1249
1250         if (state) {
1251                 /*
1252                  * Only contexts that are short-lived [that will expire or be
1253                  * reset] are allowed to survive past termination. We require
1254                  * hangcheck to ensure that the persistent requests are healthy.
1255                  */
1256                 if (!ctx->i915->params.enable_hangcheck)
1257                         return -EINVAL;
1258
1259                 i915_gem_context_set_persistence(ctx);
1260         } else {
1261                 /* To cancel a context we use "preempt-to-idle" */
1262                 if (!(ctx->i915->caps.scheduler & I915_SCHEDULER_CAP_PREEMPTION))
1263                         return -ENODEV;
1264
1265                 /*
1266                  * If the cancel fails, we then need to reset, cleanly!
1267                  *
1268                  * If the per-engine reset fails, all hope is lost! We resort
1269                  * to a full GPU reset in that unlikely case, but realistically
1270                  * if the engine could not reset, the full reset does not fare
1271                  * much better. The damage has been done.
1272                  *
1273                  * However, if we cannot reset an engine by itself, we cannot
1274                  * cleanup a hanging persistent context without causing
1275                  * colateral damage, and we should not pretend we can by
1276                  * exposing the interface.
1277                  */
1278                 if (!intel_has_reset_engine(&ctx->i915->gt))
1279                         return -ENODEV;
1280
1281                 i915_gem_context_clear_persistence(ctx);
1282         }
1283
1284         return 0;
1285 }
1286
1287 static inline struct i915_gem_engines *
1288 __context_engines_await(const struct i915_gem_context *ctx,
1289                         bool *user_engines)
1290 {
1291         struct i915_gem_engines *engines;
1292
1293         rcu_read_lock();
1294         do {
1295                 engines = rcu_dereference(ctx->engines);
1296                 GEM_BUG_ON(!engines);
1297
1298                 if (user_engines)
1299                         *user_engines = i915_gem_context_user_engines(ctx);
1300
1301                 /* successful await => strong mb */
1302                 if (unlikely(!i915_sw_fence_await(&engines->fence)))
1303                         continue;
1304
1305                 if (likely(engines == rcu_access_pointer(ctx->engines)))
1306                         break;
1307
1308                 i915_sw_fence_complete(&engines->fence);
1309         } while (1);
1310         rcu_read_unlock();
1311
1312         return engines;
1313 }
1314
1315 static void
1316 context_apply_all(struct i915_gem_context *ctx,
1317                   void (*fn)(struct intel_context *ce, void *data),
1318                   void *data)
1319 {
1320         struct i915_gem_engines_iter it;
1321         struct i915_gem_engines *e;
1322         struct intel_context *ce;
1323
1324         e = __context_engines_await(ctx, NULL);
1325         for_each_gem_engine(ce, e, it)
1326                 fn(ce, data);
1327         i915_sw_fence_complete(&e->fence);
1328 }
1329
1330 static struct i915_gem_context *
1331 i915_gem_create_context(struct drm_i915_private *i915,
1332                         const struct i915_gem_proto_context *pc)
1333 {
1334         struct i915_gem_context *ctx;
1335         struct i915_address_space *vm = NULL;
1336         struct i915_gem_engines *e;
1337         int err;
1338         int i;
1339
1340         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1341         if (!ctx)
1342                 return ERR_PTR(-ENOMEM);
1343
1344         kref_init(&ctx->ref);
1345         ctx->i915 = i915;
1346         ctx->sched = pc->sched;
1347         mutex_init(&ctx->mutex);
1348         INIT_LIST_HEAD(&ctx->link);
1349
1350         spin_lock_init(&ctx->stale.lock);
1351         INIT_LIST_HEAD(&ctx->stale.engines);
1352
1353         if (pc->vm) {
1354                 vm = i915_vm_get(pc->vm);
1355         } else if (HAS_FULL_PPGTT(i915)) {
1356                 struct i915_ppgtt *ppgtt;
1357
1358                 ppgtt = i915_ppgtt_create(&i915->gt);
1359                 if (IS_ERR(ppgtt)) {
1360                         drm_dbg(&i915->drm, "PPGTT setup failed (%ld)\n",
1361                                 PTR_ERR(ppgtt));
1362                         err = PTR_ERR(ppgtt);
1363                         goto err_ctx;
1364                 }
1365                 vm = &ppgtt->vm;
1366         }
1367         if (vm) {
1368                 RCU_INIT_POINTER(ctx->vm, i915_vm_open(vm));
1369
1370                 /* i915_vm_open() takes a reference */
1371                 i915_vm_put(vm);
1372         }
1373
1374         mutex_init(&ctx->engines_mutex);
1375         if (pc->num_user_engines >= 0) {
1376                 i915_gem_context_set_user_engines(ctx);
1377                 e = user_engines(ctx, pc->num_user_engines, pc->user_engines);
1378         } else {
1379                 i915_gem_context_clear_user_engines(ctx);
1380                 e = default_engines(ctx, pc->legacy_rcs_sseu);
1381         }
1382         if (IS_ERR(e)) {
1383                 err = PTR_ERR(e);
1384                 goto err_vm;
1385         }
1386         RCU_INIT_POINTER(ctx->engines, e);
1387
1388         INIT_RADIX_TREE(&ctx->handles_vma, GFP_KERNEL);
1389         mutex_init(&ctx->lut_mutex);
1390
1391         /* NB: Mark all slices as needing a remap so that when the context first
1392          * loads it will restore whatever remap state already exists. If there
1393          * is no remap info, it will be a NOP. */
1394         ctx->remap_slice = ALL_L3_SLICES(i915);
1395
1396         ctx->user_flags = pc->user_flags;
1397
1398         for (i = 0; i < ARRAY_SIZE(ctx->hang_timestamp); i++)
1399                 ctx->hang_timestamp[i] = jiffies - CONTEXT_FAST_HANG_JIFFIES;
1400
1401         if (pc->single_timeline) {
1402                 err = drm_syncobj_create(&ctx->syncobj,
1403                                          DRM_SYNCOBJ_CREATE_SIGNALED,
1404                                          NULL);
1405                 if (err)
1406                         goto err_engines;
1407         }
1408
1409         trace_i915_context_create(ctx);
1410
1411         return ctx;
1412
1413 err_engines:
1414         free_engines(e);
1415 err_vm:
1416         if (ctx->vm)
1417                 i915_vm_close(ctx->vm);
1418 err_ctx:
1419         kfree(ctx);
1420         return ERR_PTR(err);
1421 }
1422
1423 static void init_contexts(struct i915_gem_contexts *gc)
1424 {
1425         spin_lock_init(&gc->lock);
1426         INIT_LIST_HEAD(&gc->list);
1427 }
1428
1429 void i915_gem_init__contexts(struct drm_i915_private *i915)
1430 {
1431         init_contexts(&i915->gem.contexts);
1432 }
1433
1434 static void gem_context_register(struct i915_gem_context *ctx,
1435                                  struct drm_i915_file_private *fpriv,
1436                                  u32 id)
1437 {
1438         struct drm_i915_private *i915 = ctx->i915;
1439         void *old;
1440
1441         ctx->file_priv = fpriv;
1442
1443         ctx->pid = get_task_pid(current, PIDTYPE_PID);
1444         snprintf(ctx->name, sizeof(ctx->name), "%s[%d]",
1445                  current->comm, pid_nr(ctx->pid));
1446
1447         /* And finally expose ourselves to userspace via the idr */
1448         old = xa_store(&fpriv->context_xa, id, ctx, GFP_KERNEL);
1449         WARN_ON(old);
1450
1451         spin_lock(&i915->gem.contexts.lock);
1452         list_add_tail(&ctx->link, &i915->gem.contexts.list);
1453         spin_unlock(&i915->gem.contexts.lock);
1454 }
1455
1456 int i915_gem_context_open(struct drm_i915_private *i915,
1457                           struct drm_file *file)
1458 {
1459         struct drm_i915_file_private *file_priv = file->driver_priv;
1460         struct i915_gem_proto_context *pc;
1461         struct i915_gem_context *ctx;
1462         int err;
1463
1464         mutex_init(&file_priv->proto_context_lock);
1465         xa_init_flags(&file_priv->proto_context_xa, XA_FLAGS_ALLOC);
1466
1467         /* 0 reserved for the default context */
1468         xa_init_flags(&file_priv->context_xa, XA_FLAGS_ALLOC1);
1469
1470         /* 0 reserved for invalid/unassigned ppgtt */
1471         xa_init_flags(&file_priv->vm_xa, XA_FLAGS_ALLOC1);
1472
1473         pc = proto_context_create(i915, 0);
1474         if (IS_ERR(pc)) {
1475                 err = PTR_ERR(pc);
1476                 goto err;
1477         }
1478
1479         ctx = i915_gem_create_context(i915, pc);
1480         proto_context_close(pc);
1481         if (IS_ERR(ctx)) {
1482                 err = PTR_ERR(ctx);
1483                 goto err;
1484         }
1485
1486         gem_context_register(ctx, file_priv, 0);
1487
1488         return 0;
1489
1490 err:
1491         xa_destroy(&file_priv->vm_xa);
1492         xa_destroy(&file_priv->context_xa);
1493         xa_destroy(&file_priv->proto_context_xa);
1494         mutex_destroy(&file_priv->proto_context_lock);
1495         return err;
1496 }
1497
1498 void i915_gem_context_close(struct drm_file *file)
1499 {
1500         struct drm_i915_file_private *file_priv = file->driver_priv;
1501         struct i915_gem_proto_context *pc;
1502         struct i915_address_space *vm;
1503         struct i915_gem_context *ctx;
1504         unsigned long idx;
1505
1506         xa_for_each(&file_priv->proto_context_xa, idx, pc)
1507                 proto_context_close(pc);
1508         xa_destroy(&file_priv->proto_context_xa);
1509         mutex_destroy(&file_priv->proto_context_lock);
1510
1511         xa_for_each(&file_priv->context_xa, idx, ctx)
1512                 context_close(ctx);
1513         xa_destroy(&file_priv->context_xa);
1514
1515         xa_for_each(&file_priv->vm_xa, idx, vm)
1516                 i915_vm_put(vm);
1517         xa_destroy(&file_priv->vm_xa);
1518 }
1519
1520 int i915_gem_vm_create_ioctl(struct drm_device *dev, void *data,
1521                              struct drm_file *file)
1522 {
1523         struct drm_i915_private *i915 = to_i915(dev);
1524         struct drm_i915_gem_vm_control *args = data;
1525         struct drm_i915_file_private *file_priv = file->driver_priv;
1526         struct i915_ppgtt *ppgtt;
1527         u32 id;
1528         int err;
1529
1530         if (!HAS_FULL_PPGTT(i915))
1531                 return -ENODEV;
1532
1533         if (args->flags)
1534                 return -EINVAL;
1535
1536         ppgtt = i915_ppgtt_create(&i915->gt);
1537         if (IS_ERR(ppgtt))
1538                 return PTR_ERR(ppgtt);
1539
1540         if (args->extensions) {
1541                 err = i915_user_extensions(u64_to_user_ptr(args->extensions),
1542                                            NULL, 0,
1543                                            ppgtt);
1544                 if (err)
1545                         goto err_put;
1546         }
1547
1548         err = xa_alloc(&file_priv->vm_xa, &id, &ppgtt->vm,
1549                        xa_limit_32b, GFP_KERNEL);
1550         if (err)
1551                 goto err_put;
1552
1553         GEM_BUG_ON(id == 0); /* reserved for invalid/unassigned ppgtt */
1554         args->vm_id = id;
1555         return 0;
1556
1557 err_put:
1558         i915_vm_put(&ppgtt->vm);
1559         return err;
1560 }
1561
1562 int i915_gem_vm_destroy_ioctl(struct drm_device *dev, void *data,
1563                               struct drm_file *file)
1564 {
1565         struct drm_i915_file_private *file_priv = file->driver_priv;
1566         struct drm_i915_gem_vm_control *args = data;
1567         struct i915_address_space *vm;
1568
1569         if (args->flags)
1570                 return -EINVAL;
1571
1572         if (args->extensions)
1573                 return -EINVAL;
1574
1575         vm = xa_erase(&file_priv->vm_xa, args->vm_id);
1576         if (!vm)
1577                 return -ENOENT;
1578
1579         i915_vm_put(vm);
1580         return 0;
1581 }
1582
1583 static int get_ppgtt(struct drm_i915_file_private *file_priv,
1584                      struct i915_gem_context *ctx,
1585                      struct drm_i915_gem_context_param *args)
1586 {
1587         struct i915_address_space *vm;
1588         int err;
1589         u32 id;
1590
1591         if (!rcu_access_pointer(ctx->vm))
1592                 return -ENODEV;
1593
1594         rcu_read_lock();
1595         vm = context_get_vm_rcu(ctx);
1596         rcu_read_unlock();
1597         if (!vm)
1598                 return -ENODEV;
1599
1600         err = xa_alloc(&file_priv->vm_xa, &id, vm, xa_limit_32b, GFP_KERNEL);
1601         if (err)
1602                 goto err_put;
1603
1604         i915_vm_open(vm);
1605
1606         GEM_BUG_ON(id == 0); /* reserved for invalid/unassigned ppgtt */
1607         args->value = id;
1608         args->size = 0;
1609
1610 err_put:
1611         i915_vm_put(vm);
1612         return err;
1613 }
1614
1615 int
1616 i915_gem_user_to_context_sseu(struct intel_gt *gt,
1617                               const struct drm_i915_gem_context_param_sseu *user,
1618                               struct intel_sseu *context)
1619 {
1620         const struct sseu_dev_info *device = &gt->info.sseu;
1621         struct drm_i915_private *i915 = gt->i915;
1622
1623         /* No zeros in any field. */
1624         if (!user->slice_mask || !user->subslice_mask ||
1625             !user->min_eus_per_subslice || !user->max_eus_per_subslice)
1626                 return -EINVAL;
1627
1628         /* Max > min. */
1629         if (user->max_eus_per_subslice < user->min_eus_per_subslice)
1630                 return -EINVAL;
1631
1632         /*
1633          * Some future proofing on the types since the uAPI is wider than the
1634          * current internal implementation.
1635          */
1636         if (overflows_type(user->slice_mask, context->slice_mask) ||
1637             overflows_type(user->subslice_mask, context->subslice_mask) ||
1638             overflows_type(user->min_eus_per_subslice,
1639                            context->min_eus_per_subslice) ||
1640             overflows_type(user->max_eus_per_subslice,
1641                            context->max_eus_per_subslice))
1642                 return -EINVAL;
1643
1644         /* Check validity against hardware. */
1645         if (user->slice_mask & ~device->slice_mask)
1646                 return -EINVAL;
1647
1648         if (user->subslice_mask & ~device->subslice_mask[0])
1649                 return -EINVAL;
1650
1651         if (user->max_eus_per_subslice > device->max_eus_per_subslice)
1652                 return -EINVAL;
1653
1654         context->slice_mask = user->slice_mask;
1655         context->subslice_mask = user->subslice_mask;
1656         context->min_eus_per_subslice = user->min_eus_per_subslice;
1657         context->max_eus_per_subslice = user->max_eus_per_subslice;
1658
1659         /* Part specific restrictions. */
1660         if (GRAPHICS_VER(i915) == 11) {
1661                 unsigned int hw_s = hweight8(device->slice_mask);
1662                 unsigned int hw_ss_per_s = hweight8(device->subslice_mask[0]);
1663                 unsigned int req_s = hweight8(context->slice_mask);
1664                 unsigned int req_ss = hweight8(context->subslice_mask);
1665
1666                 /*
1667                  * Only full subslice enablement is possible if more than one
1668                  * slice is turned on.
1669                  */
1670                 if (req_s > 1 && req_ss != hw_ss_per_s)
1671                         return -EINVAL;
1672
1673                 /*
1674                  * If more than four (SScount bitfield limit) subslices are
1675                  * requested then the number has to be even.
1676                  */
1677                 if (req_ss > 4 && (req_ss & 1))
1678                         return -EINVAL;
1679
1680                 /*
1681                  * If only one slice is enabled and subslice count is below the
1682                  * device full enablement, it must be at most half of the all
1683                  * available subslices.
1684                  */
1685                 if (req_s == 1 && req_ss < hw_ss_per_s &&
1686                     req_ss > (hw_ss_per_s / 2))
1687                         return -EINVAL;
1688
1689                 /* ABI restriction - VME use case only. */
1690
1691                 /* All slices or one slice only. */
1692                 if (req_s != 1 && req_s != hw_s)
1693                         return -EINVAL;
1694
1695                 /*
1696                  * Half subslices or full enablement only when one slice is
1697                  * enabled.
1698                  */
1699                 if (req_s == 1 &&
1700                     (req_ss != hw_ss_per_s && req_ss != (hw_ss_per_s / 2)))
1701                         return -EINVAL;
1702
1703                 /* No EU configuration changes. */
1704                 if ((user->min_eus_per_subslice !=
1705                      device->max_eus_per_subslice) ||
1706                     (user->max_eus_per_subslice !=
1707                      device->max_eus_per_subslice))
1708                         return -EINVAL;
1709         }
1710
1711         return 0;
1712 }
1713
1714 static int set_sseu(struct i915_gem_context *ctx,
1715                     struct drm_i915_gem_context_param *args)
1716 {
1717         struct drm_i915_private *i915 = ctx->i915;
1718         struct drm_i915_gem_context_param_sseu user_sseu;
1719         struct intel_context *ce;
1720         struct intel_sseu sseu;
1721         unsigned long lookup;
1722         int ret;
1723
1724         if (args->size < sizeof(user_sseu))
1725                 return -EINVAL;
1726
1727         if (GRAPHICS_VER(i915) != 11)
1728                 return -ENODEV;
1729
1730         if (copy_from_user(&user_sseu, u64_to_user_ptr(args->value),
1731                            sizeof(user_sseu)))
1732                 return -EFAULT;
1733
1734         if (user_sseu.rsvd)
1735                 return -EINVAL;
1736
1737         if (user_sseu.flags & ~(I915_CONTEXT_SSEU_FLAG_ENGINE_INDEX))
1738                 return -EINVAL;
1739
1740         lookup = 0;
1741         if (user_sseu.flags & I915_CONTEXT_SSEU_FLAG_ENGINE_INDEX)
1742                 lookup |= LOOKUP_USER_INDEX;
1743
1744         ce = lookup_user_engine(ctx, lookup, &user_sseu.engine);
1745         if (IS_ERR(ce))
1746                 return PTR_ERR(ce);
1747
1748         /* Only render engine supports RPCS configuration. */
1749         if (ce->engine->class != RENDER_CLASS) {
1750                 ret = -ENODEV;
1751                 goto out_ce;
1752         }
1753
1754         ret = i915_gem_user_to_context_sseu(ce->engine->gt, &user_sseu, &sseu);
1755         if (ret)
1756                 goto out_ce;
1757
1758         ret = intel_context_reconfigure_sseu(ce, sseu);
1759         if (ret)
1760                 goto out_ce;
1761
1762         args->size = sizeof(user_sseu);
1763
1764 out_ce:
1765         intel_context_put(ce);
1766         return ret;
1767 }
1768
1769 static int
1770 set_persistence(struct i915_gem_context *ctx,
1771                 const struct drm_i915_gem_context_param *args)
1772 {
1773         if (args->size)
1774                 return -EINVAL;
1775
1776         return __context_set_persistence(ctx, args->value);
1777 }
1778
1779 static void __apply_priority(struct intel_context *ce, void *arg)
1780 {
1781         struct i915_gem_context *ctx = arg;
1782
1783         if (!intel_engine_has_timeslices(ce->engine))
1784                 return;
1785
1786         if (ctx->sched.priority >= I915_PRIORITY_NORMAL &&
1787             intel_engine_has_semaphores(ce->engine))
1788                 intel_context_set_use_semaphores(ce);
1789         else
1790                 intel_context_clear_use_semaphores(ce);
1791 }
1792
1793 static int set_priority(struct i915_gem_context *ctx,
1794                         const struct drm_i915_gem_context_param *args)
1795 {
1796         int err;
1797
1798         err = validate_priority(ctx->i915, args);
1799         if (err)
1800                 return err;
1801
1802         ctx->sched.priority = args->value;
1803         context_apply_all(ctx, __apply_priority, ctx);
1804
1805         return 0;
1806 }
1807
1808 static int ctx_setparam(struct drm_i915_file_private *fpriv,
1809                         struct i915_gem_context *ctx,
1810                         struct drm_i915_gem_context_param *args)
1811 {
1812         int ret = 0;
1813
1814         switch (args->param) {
1815         case I915_CONTEXT_PARAM_NO_ERROR_CAPTURE:
1816                 if (args->size)
1817                         ret = -EINVAL;
1818                 else if (args->value)
1819                         i915_gem_context_set_no_error_capture(ctx);
1820                 else
1821                         i915_gem_context_clear_no_error_capture(ctx);
1822                 break;
1823
1824         case I915_CONTEXT_PARAM_BANNABLE:
1825                 if (args->size)
1826                         ret = -EINVAL;
1827                 else if (!capable(CAP_SYS_ADMIN) && !args->value)
1828                         ret = -EPERM;
1829                 else if (args->value)
1830                         i915_gem_context_set_bannable(ctx);
1831                 else
1832                         i915_gem_context_clear_bannable(ctx);
1833                 break;
1834
1835         case I915_CONTEXT_PARAM_RECOVERABLE:
1836                 if (args->size)
1837                         ret = -EINVAL;
1838                 else if (args->value)
1839                         i915_gem_context_set_recoverable(ctx);
1840                 else
1841                         i915_gem_context_clear_recoverable(ctx);
1842                 break;
1843
1844         case I915_CONTEXT_PARAM_PRIORITY:
1845                 ret = set_priority(ctx, args);
1846                 break;
1847
1848         case I915_CONTEXT_PARAM_SSEU:
1849                 ret = set_sseu(ctx, args);
1850                 break;
1851
1852         case I915_CONTEXT_PARAM_PERSISTENCE:
1853                 ret = set_persistence(ctx, args);
1854                 break;
1855
1856         case I915_CONTEXT_PARAM_NO_ZEROMAP:
1857         case I915_CONTEXT_PARAM_BAN_PERIOD:
1858         case I915_CONTEXT_PARAM_RINGSIZE:
1859         case I915_CONTEXT_PARAM_VM:
1860         case I915_CONTEXT_PARAM_ENGINES:
1861         default:
1862                 ret = -EINVAL;
1863                 break;
1864         }
1865
1866         return ret;
1867 }
1868
1869 struct create_ext {
1870         struct i915_gem_proto_context *pc;
1871         struct drm_i915_file_private *fpriv;
1872 };
1873
1874 static int create_setparam(struct i915_user_extension __user *ext, void *data)
1875 {
1876         struct drm_i915_gem_context_create_ext_setparam local;
1877         const struct create_ext *arg = data;
1878
1879         if (copy_from_user(&local, ext, sizeof(local)))
1880                 return -EFAULT;
1881
1882         if (local.param.ctx_id)
1883                 return -EINVAL;
1884
1885         return set_proto_ctx_param(arg->fpriv, arg->pc, &local.param);
1886 }
1887
1888 static int invalid_ext(struct i915_user_extension __user *ext, void *data)
1889 {
1890         return -EINVAL;
1891 }
1892
1893 static const i915_user_extension_fn create_extensions[] = {
1894         [I915_CONTEXT_CREATE_EXT_SETPARAM] = create_setparam,
1895         [I915_CONTEXT_CREATE_EXT_CLONE] = invalid_ext,
1896 };
1897
1898 static bool client_is_banned(struct drm_i915_file_private *file_priv)
1899 {
1900         return atomic_read(&file_priv->ban_score) >= I915_CLIENT_SCORE_BANNED;
1901 }
1902
1903 static inline struct i915_gem_context *
1904 __context_lookup(struct drm_i915_file_private *file_priv, u32 id)
1905 {
1906         struct i915_gem_context *ctx;
1907
1908         rcu_read_lock();
1909         ctx = xa_load(&file_priv->context_xa, id);
1910         if (ctx && !kref_get_unless_zero(&ctx->ref))
1911                 ctx = NULL;
1912         rcu_read_unlock();
1913
1914         return ctx;
1915 }
1916
1917 static struct i915_gem_context *
1918 finalize_create_context_locked(struct drm_i915_file_private *file_priv,
1919                                struct i915_gem_proto_context *pc, u32 id)
1920 {
1921         struct i915_gem_context *ctx;
1922         void *old;
1923
1924         lockdep_assert_held(&file_priv->proto_context_lock);
1925
1926         ctx = i915_gem_create_context(file_priv->dev_priv, pc);
1927         if (IS_ERR(ctx))
1928                 return ctx;
1929
1930         gem_context_register(ctx, file_priv, id);
1931
1932         old = xa_erase(&file_priv->proto_context_xa, id);
1933         GEM_BUG_ON(old != pc);
1934         proto_context_close(pc);
1935
1936         /* One for the xarray and one for the caller */
1937         return i915_gem_context_get(ctx);
1938 }
1939
1940 struct i915_gem_context *
1941 i915_gem_context_lookup(struct drm_i915_file_private *file_priv, u32 id)
1942 {
1943         struct i915_gem_proto_context *pc;
1944         struct i915_gem_context *ctx;
1945
1946         ctx = __context_lookup(file_priv, id);
1947         if (ctx)
1948                 return ctx;
1949
1950         mutex_lock(&file_priv->proto_context_lock);
1951         /* Try one more time under the lock */
1952         ctx = __context_lookup(file_priv, id);
1953         if (!ctx) {
1954                 pc = xa_load(&file_priv->proto_context_xa, id);
1955                 if (!pc)
1956                         ctx = ERR_PTR(-ENOENT);
1957                 else
1958                         ctx = finalize_create_context_locked(file_priv, pc, id);
1959         }
1960         mutex_unlock(&file_priv->proto_context_lock);
1961
1962         return ctx;
1963 }
1964
1965 int i915_gem_context_create_ioctl(struct drm_device *dev, void *data,
1966                                   struct drm_file *file)
1967 {
1968         struct drm_i915_private *i915 = to_i915(dev);
1969         struct drm_i915_gem_context_create_ext *args = data;
1970         struct create_ext ext_data;
1971         int ret;
1972         u32 id;
1973
1974         if (!DRIVER_CAPS(i915)->has_logical_contexts)
1975                 return -ENODEV;
1976
1977         if (args->flags & I915_CONTEXT_CREATE_FLAGS_UNKNOWN)
1978                 return -EINVAL;
1979
1980         ret = intel_gt_terminally_wedged(&i915->gt);
1981         if (ret)
1982                 return ret;
1983
1984         ext_data.fpriv = file->driver_priv;
1985         if (client_is_banned(ext_data.fpriv)) {
1986                 drm_dbg(&i915->drm,
1987                         "client %s[%d] banned from creating ctx\n",
1988                         current->comm, task_pid_nr(current));
1989                 return -EIO;
1990         }
1991
1992         ext_data.pc = proto_context_create(i915, args->flags);
1993         if (IS_ERR(ext_data.pc))
1994                 return PTR_ERR(ext_data.pc);
1995
1996         if (args->flags & I915_CONTEXT_CREATE_FLAGS_USE_EXTENSIONS) {
1997                 ret = i915_user_extensions(u64_to_user_ptr(args->extensions),
1998                                            create_extensions,
1999                                            ARRAY_SIZE(create_extensions),
2000                                            &ext_data);
2001                 if (ret)
2002                         goto err_pc;
2003         }
2004
2005         if (GRAPHICS_VER(i915) > 12) {
2006                 struct i915_gem_context *ctx;
2007
2008                 /* Get ourselves a context ID */
2009                 ret = xa_alloc(&ext_data.fpriv->context_xa, &id, NULL,
2010                                xa_limit_32b, GFP_KERNEL);
2011                 if (ret)
2012                         goto err_pc;
2013
2014                 ctx = i915_gem_create_context(i915, ext_data.pc);
2015                 if (IS_ERR(ctx)) {
2016                         ret = PTR_ERR(ctx);
2017                         goto err_pc;
2018                 }
2019
2020                 proto_context_close(ext_data.pc);
2021                 gem_context_register(ctx, ext_data.fpriv, id);
2022         } else {
2023                 ret = proto_context_register(ext_data.fpriv, ext_data.pc, &id);
2024                 if (ret < 0)
2025                         goto err_pc;
2026         }
2027
2028         args->ctx_id = id;
2029         drm_dbg(&i915->drm, "HW context %d created\n", args->ctx_id);
2030
2031         return 0;
2032
2033 err_pc:
2034         proto_context_close(ext_data.pc);
2035         return ret;
2036 }
2037
2038 int i915_gem_context_destroy_ioctl(struct drm_device *dev, void *data,
2039                                    struct drm_file *file)
2040 {
2041         struct drm_i915_gem_context_destroy *args = data;
2042         struct drm_i915_file_private *file_priv = file->driver_priv;
2043         struct i915_gem_proto_context *pc;
2044         struct i915_gem_context *ctx;
2045
2046         if (args->pad != 0)
2047                 return -EINVAL;
2048
2049         if (!args->ctx_id)
2050                 return -ENOENT;
2051
2052         /* We need to hold the proto-context lock here to prevent races
2053          * with finalize_create_context_locked().
2054          */
2055         mutex_lock(&file_priv->proto_context_lock);
2056         ctx = xa_erase(&file_priv->context_xa, args->ctx_id);
2057         pc = xa_erase(&file_priv->proto_context_xa, args->ctx_id);
2058         mutex_unlock(&file_priv->proto_context_lock);
2059
2060         if (!ctx && !pc)
2061                 return -ENOENT;
2062         GEM_WARN_ON(ctx && pc);
2063
2064         if (pc)
2065                 proto_context_close(pc);
2066
2067         if (ctx)
2068                 context_close(ctx);
2069
2070         return 0;
2071 }
2072
2073 static int get_sseu(struct i915_gem_context *ctx,
2074                     struct drm_i915_gem_context_param *args)
2075 {
2076         struct drm_i915_gem_context_param_sseu user_sseu;
2077         struct intel_context *ce;
2078         unsigned long lookup;
2079         int err;
2080
2081         if (args->size == 0)
2082                 goto out;
2083         else if (args->size < sizeof(user_sseu))
2084                 return -EINVAL;
2085
2086         if (copy_from_user(&user_sseu, u64_to_user_ptr(args->value),
2087                            sizeof(user_sseu)))
2088                 return -EFAULT;
2089
2090         if (user_sseu.rsvd)
2091                 return -EINVAL;
2092
2093         if (user_sseu.flags & ~(I915_CONTEXT_SSEU_FLAG_ENGINE_INDEX))
2094                 return -EINVAL;
2095
2096         lookup = 0;
2097         if (user_sseu.flags & I915_CONTEXT_SSEU_FLAG_ENGINE_INDEX)
2098                 lookup |= LOOKUP_USER_INDEX;
2099
2100         ce = lookup_user_engine(ctx, lookup, &user_sseu.engine);
2101         if (IS_ERR(ce))
2102                 return PTR_ERR(ce);
2103
2104         err = intel_context_lock_pinned(ce); /* serialises with set_sseu */
2105         if (err) {
2106                 intel_context_put(ce);
2107                 return err;
2108         }
2109
2110         user_sseu.slice_mask = ce->sseu.slice_mask;
2111         user_sseu.subslice_mask = ce->sseu.subslice_mask;
2112         user_sseu.min_eus_per_subslice = ce->sseu.min_eus_per_subslice;
2113         user_sseu.max_eus_per_subslice = ce->sseu.max_eus_per_subslice;
2114
2115         intel_context_unlock_pinned(ce);
2116         intel_context_put(ce);
2117
2118         if (copy_to_user(u64_to_user_ptr(args->value), &user_sseu,
2119                          sizeof(user_sseu)))
2120                 return -EFAULT;
2121
2122 out:
2123         args->size = sizeof(user_sseu);
2124
2125         return 0;
2126 }
2127
2128 int i915_gem_context_getparam_ioctl(struct drm_device *dev, void *data,
2129                                     struct drm_file *file)
2130 {
2131         struct drm_i915_file_private *file_priv = file->driver_priv;
2132         struct drm_i915_gem_context_param *args = data;
2133         struct i915_gem_context *ctx;
2134         int ret = 0;
2135
2136         ctx = i915_gem_context_lookup(file_priv, args->ctx_id);
2137         if (IS_ERR(ctx))
2138                 return PTR_ERR(ctx);
2139
2140         switch (args->param) {
2141         case I915_CONTEXT_PARAM_GTT_SIZE:
2142                 args->size = 0;
2143                 rcu_read_lock();
2144                 if (rcu_access_pointer(ctx->vm))
2145                         args->value = rcu_dereference(ctx->vm)->total;
2146                 else
2147                         args->value = to_i915(dev)->ggtt.vm.total;
2148                 rcu_read_unlock();
2149                 break;
2150
2151         case I915_CONTEXT_PARAM_NO_ERROR_CAPTURE:
2152                 args->size = 0;
2153                 args->value = i915_gem_context_no_error_capture(ctx);
2154                 break;
2155
2156         case I915_CONTEXT_PARAM_BANNABLE:
2157                 args->size = 0;
2158                 args->value = i915_gem_context_is_bannable(ctx);
2159                 break;
2160
2161         case I915_CONTEXT_PARAM_RECOVERABLE:
2162                 args->size = 0;
2163                 args->value = i915_gem_context_is_recoverable(ctx);
2164                 break;
2165
2166         case I915_CONTEXT_PARAM_PRIORITY:
2167                 args->size = 0;
2168                 args->value = ctx->sched.priority;
2169                 break;
2170
2171         case I915_CONTEXT_PARAM_SSEU:
2172                 ret = get_sseu(ctx, args);
2173                 break;
2174
2175         case I915_CONTEXT_PARAM_VM:
2176                 ret = get_ppgtt(file_priv, ctx, args);
2177                 break;
2178
2179         case I915_CONTEXT_PARAM_PERSISTENCE:
2180                 args->size = 0;
2181                 args->value = i915_gem_context_is_persistent(ctx);
2182                 break;
2183
2184         case I915_CONTEXT_PARAM_NO_ZEROMAP:
2185         case I915_CONTEXT_PARAM_BAN_PERIOD:
2186         case I915_CONTEXT_PARAM_ENGINES:
2187         case I915_CONTEXT_PARAM_RINGSIZE:
2188         default:
2189                 ret = -EINVAL;
2190                 break;
2191         }
2192
2193         i915_gem_context_put(ctx);
2194         return ret;
2195 }
2196
2197 int i915_gem_context_setparam_ioctl(struct drm_device *dev, void *data,
2198                                     struct drm_file *file)
2199 {
2200         struct drm_i915_file_private *file_priv = file->driver_priv;
2201         struct drm_i915_gem_context_param *args = data;
2202         struct i915_gem_proto_context *pc;
2203         struct i915_gem_context *ctx;
2204         int ret = 0;
2205
2206         mutex_lock(&file_priv->proto_context_lock);
2207         ctx = __context_lookup(file_priv, args->ctx_id);
2208         if (!ctx) {
2209                 pc = xa_load(&file_priv->proto_context_xa, args->ctx_id);
2210                 if (pc) {
2211                         /* Contexts should be finalized inside
2212                          * GEM_CONTEXT_CREATE starting with graphics
2213                          * version 13.
2214                          */
2215                         WARN_ON(GRAPHICS_VER(file_priv->dev_priv) > 12);
2216                         ret = set_proto_ctx_param(file_priv, pc, args);
2217                 } else {
2218                         ret = -ENOENT;
2219                 }
2220         }
2221         mutex_unlock(&file_priv->proto_context_lock);
2222
2223         if (ctx) {
2224                 ret = ctx_setparam(file_priv, ctx, args);
2225                 i915_gem_context_put(ctx);
2226         }
2227
2228         return ret;
2229 }
2230
2231 int i915_gem_context_reset_stats_ioctl(struct drm_device *dev,
2232                                        void *data, struct drm_file *file)
2233 {
2234         struct drm_i915_private *i915 = to_i915(dev);
2235         struct drm_i915_reset_stats *args = data;
2236         struct i915_gem_context *ctx;
2237
2238         if (args->flags || args->pad)
2239                 return -EINVAL;
2240
2241         ctx = i915_gem_context_lookup(file->driver_priv, args->ctx_id);
2242         if (IS_ERR(ctx))
2243                 return PTR_ERR(ctx);
2244
2245         /*
2246          * We opt for unserialised reads here. This may result in tearing
2247          * in the extremely unlikely event of a GPU hang on this context
2248          * as we are querying them. If we need that extra layer of protection,
2249          * we should wrap the hangstats with a seqlock.
2250          */
2251
2252         if (capable(CAP_SYS_ADMIN))
2253                 args->reset_count = i915_reset_count(&i915->gpu_error);
2254         else
2255                 args->reset_count = 0;
2256
2257         args->batch_active = atomic_read(&ctx->guilty_count);
2258         args->batch_pending = atomic_read(&ctx->active_count);
2259
2260         i915_gem_context_put(ctx);
2261         return 0;
2262 }
2263
2264 /* GEM context-engines iterator: for_each_gem_engine() */
2265 struct intel_context *
2266 i915_gem_engines_iter_next(struct i915_gem_engines_iter *it)
2267 {
2268         const struct i915_gem_engines *e = it->engines;
2269         struct intel_context *ctx;
2270
2271         if (unlikely(!e))
2272                 return NULL;
2273
2274         do {
2275                 if (it->idx >= e->num_engines)
2276                         return NULL;
2277
2278                 ctx = e->engines[it->idx++];
2279         } while (!ctx);
2280
2281         return ctx;
2282 }
2283
2284 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
2285 #include "selftests/mock_context.c"
2286 #include "selftests/i915_gem_context.c"
2287 #endif
2288
2289 void i915_gem_context_module_exit(void)
2290 {
2291         kmem_cache_destroy(slab_luts);
2292 }
2293
2294 int __init i915_gem_context_module_init(void)
2295 {
2296         slab_luts = KMEM_CACHE(i915_lut_handle, 0);
2297         if (!slab_luts)
2298                 return -ENOMEM;
2299
2300         return 0;
2301 }