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