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