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