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