1 /*
2  * Copyright © 2011-2012 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  *
23  * Authors:
24  *    Ben Widawsky <ben@bwidawsk.net>
25  *
26  */
27 
28 /*
29  * This file implements HW context support. On gen5+ a HW context consists of an
30  * opaque GPU object which is referenced at times of context saves and restores.
31  * With RC6 enabled, the context is also referenced as the GPU enters and exists
32  * from RC6 (GPU has it's own internal power context, except on gen5). Though
33  * something like a context does exist for the media ring, the code only
34  * supports contexts for the render ring.
35  *
36  * In software, there is a distinction between contexts created by the user,
37  * and the default HW context. The default HW context is used by GPU clients
38  * that do not request setup of their own hardware context. The default
39  * context's state is never restored to help prevent programming errors. This
40  * would happen if a client ran and piggy-backed off another clients GPU state.
41  * The default context only exists to give the GPU some offset to load as the
42  * current to invoke a save of the context we actually care about. In fact, the
43  * code could likely be constructed, albeit in a more complicated fashion, to
44  * never use the default context, though that limits the driver's ability to
45  * swap out, and/or destroy other contexts.
46  *
47  * All other contexts are created as a request by the GPU client. These contexts
48  * store GPU state, and thus allow GPU clients to not re-emit state (and
49  * potentially query certain state) at any time. The kernel driver makes
50  * certain that the appropriate commands are inserted.
51  *
52  * The context life cycle is semi-complicated in that context BOs may live
53  * longer than the context itself because of the way the hardware, and object
54  * tracking works. Below is a very crude representation of the state machine
55  * describing the context life.
56  *                                         refcount     pincount     active
57  * S0: initial state                          0            0           0
58  * S1: context created                        1            0           0
59  * S2: context is currently running           2            1           X
60  * S3: GPU referenced, but not current        2            0           1
61  * S4: context is current, but destroyed      1            1           0
62  * S5: like S3, but destroyed                 1            0           1
63  *
64  * The most common (but not all) transitions:
65  * S0->S1: client creates a context
66  * S1->S2: client submits execbuf with context
67  * S2->S3: other clients submits execbuf with context
68  * S3->S1: context object was retired
69  * S3->S2: clients submits another execbuf
70  * S2->S4: context destroy called with current context
71  * S3->S5->S0: destroy path
72  * S4->S5->S0: destroy path on current context
73  *
74  * There are two confusing terms used above:
75  *  The "current context" means the context which is currently running on the
76  *  GPU. The GPU has loaded its state already and has stored away the gtt
77  *  offset of the BO. The GPU is not actively referencing the data at this
78  *  offset, but it will on the next context switch. The only way to avoid this
79  *  is to do a GPU reset.
80  *
81  *  An "active context' is one which was previously the "current context" and is
82  *  on the active list waiting for the next context switch to occur. Until this
83  *  happens, the object must remain at the same gtt offset. It is therefore
84  *  possible to destroy a context, but it is still active.
85  *
86  */
87 
88 #include <linux/log2.h>
89 #include <drm/drmP.h>
90 #include <drm/i915_drm.h>
91 #include "i915_drv.h"
92 #include "i915_trace.h"
93 #include "intel_workarounds.h"
94 
95 #define ALL_L3_SLICES(dev) (1 << NUM_L3_SLICES(dev)) - 1
96 
lut_close(struct i915_gem_context * ctx)97 static void lut_close(struct i915_gem_context *ctx)
98 {
99 	struct i915_lut_handle *lut, *ln;
100 	struct radix_tree_iter iter;
101 	void __rcu **slot;
102 
103 	list_for_each_entry_safe(lut, ln, &ctx->handles_list, ctx_link) {
104 		list_del(&lut->obj_link);
105 		kmem_cache_free(ctx->i915->luts, lut);
106 	}
107 
108 	rcu_read_lock();
109 	radix_tree_for_each_slot(slot, &ctx->handles_vma, &iter, 0) {
110 		struct i915_vma *vma = rcu_dereference_raw(*slot);
111 
112 		radix_tree_iter_delete(&ctx->handles_vma, &iter, slot);
113 		__i915_gem_object_release_unless_active(vma->obj);
114 	}
115 	rcu_read_unlock();
116 }
117 
i915_gem_context_free(struct i915_gem_context * ctx)118 static void i915_gem_context_free(struct i915_gem_context *ctx)
119 {
120 	unsigned int n;
121 
122 	lockdep_assert_held(&ctx->i915->drm.struct_mutex);
123 	GEM_BUG_ON(!i915_gem_context_is_closed(ctx));
124 
125 	i915_ppgtt_put(ctx->ppgtt);
126 
127 	for (n = 0; n < ARRAY_SIZE(ctx->__engine); n++) {
128 		struct intel_context *ce = &ctx->__engine[n];
129 
130 		if (ce->ops)
131 			ce->ops->destroy(ce);
132 	}
133 
134 	kfree(ctx->name);
135 	put_pid(ctx->pid);
136 
137 	list_del(&ctx->link);
138 
139 	ida_simple_remove(&ctx->i915->contexts.hw_ida, ctx->hw_id);
140 	kfree_rcu(ctx, rcu);
141 }
142 
contexts_free(struct drm_i915_private * i915)143 static void contexts_free(struct drm_i915_private *i915)
144 {
145 	struct llist_node *freed = llist_del_all(&i915->contexts.free_list);
146 	struct i915_gem_context *ctx, *cn;
147 
148 	lockdep_assert_held(&i915->drm.struct_mutex);
149 
150 	llist_for_each_entry_safe(ctx, cn, freed, free_link)
151 		i915_gem_context_free(ctx);
152 }
153 
contexts_free_first(struct drm_i915_private * i915)154 static void contexts_free_first(struct drm_i915_private *i915)
155 {
156 	struct i915_gem_context *ctx;
157 	struct llist_node *freed;
158 
159 	lockdep_assert_held(&i915->drm.struct_mutex);
160 
161 	freed = llist_del_first(&i915->contexts.free_list);
162 	if (!freed)
163 		return;
164 
165 	ctx = container_of(freed, typeof(*ctx), free_link);
166 	i915_gem_context_free(ctx);
167 }
168 
contexts_free_worker(struct work_struct * work)169 static void contexts_free_worker(struct work_struct *work)
170 {
171 	struct drm_i915_private *i915 =
172 		container_of(work, typeof(*i915), contexts.free_work);
173 
174 	mutex_lock(&i915->drm.struct_mutex);
175 	contexts_free(i915);
176 	mutex_unlock(&i915->drm.struct_mutex);
177 }
178 
i915_gem_context_release(struct kref * ref)179 void i915_gem_context_release(struct kref *ref)
180 {
181 	struct i915_gem_context *ctx = container_of(ref, typeof(*ctx), ref);
182 	struct drm_i915_private *i915 = ctx->i915;
183 
184 	trace_i915_context_free(ctx);
185 	if (llist_add(&ctx->free_link, &i915->contexts.free_list))
186 		queue_work(i915->wq, &i915->contexts.free_work);
187 }
188 
context_close(struct i915_gem_context * ctx)189 static void context_close(struct i915_gem_context *ctx)
190 {
191 	i915_gem_context_set_closed(ctx);
192 
193 	/*
194 	 * The LUT uses the VMA as a backpointer to unref the object,
195 	 * so we need to clear the LUT before we close all the VMA (inside
196 	 * the ppgtt).
197 	 */
198 	lut_close(ctx);
199 	if (ctx->ppgtt)
200 		i915_ppgtt_close(&ctx->ppgtt->vm);
201 
202 	ctx->file_priv = ERR_PTR(-EBADF);
203 	i915_gem_context_put(ctx);
204 }
205 
assign_hw_id(struct drm_i915_private * dev_priv,unsigned * out)206 static int assign_hw_id(struct drm_i915_private *dev_priv, unsigned *out)
207 {
208 	int ret;
209 	unsigned int max;
210 
211 	if (INTEL_GEN(dev_priv) >= 11) {
212 		max = GEN11_MAX_CONTEXT_HW_ID;
213 	} else {
214 		/*
215 		 * When using GuC in proxy submission, GuC consumes the
216 		 * highest bit in the context id to indicate proxy submission.
217 		 */
218 		if (USES_GUC_SUBMISSION(dev_priv))
219 			max = MAX_GUC_CONTEXT_HW_ID;
220 		else
221 			max = MAX_CONTEXT_HW_ID;
222 	}
223 
224 
225 	ret = ida_simple_get(&dev_priv->contexts.hw_ida,
226 			     0, max, GFP_KERNEL);
227 	if (ret < 0) {
228 		/* Contexts are only released when no longer active.
229 		 * Flush any pending retires to hopefully release some
230 		 * stale contexts and try again.
231 		 */
232 		i915_retire_requests(dev_priv);
233 		ret = ida_simple_get(&dev_priv->contexts.hw_ida,
234 				     0, max, GFP_KERNEL);
235 		if (ret < 0)
236 			return ret;
237 	}
238 
239 	*out = ret;
240 	return 0;
241 }
242 
default_desc_template(const struct drm_i915_private * i915,const struct i915_hw_ppgtt * ppgtt)243 static u32 default_desc_template(const struct drm_i915_private *i915,
244 				 const struct i915_hw_ppgtt *ppgtt)
245 {
246 	u32 address_mode;
247 	u32 desc;
248 
249 	desc = GEN8_CTX_VALID | GEN8_CTX_PRIVILEGE;
250 
251 	address_mode = INTEL_LEGACY_32B_CONTEXT;
252 	if (ppgtt && i915_vm_is_48bit(&ppgtt->vm))
253 		address_mode = INTEL_LEGACY_64B_CONTEXT;
254 	desc |= address_mode << GEN8_CTX_ADDRESSING_MODE_SHIFT;
255 
256 	if (IS_GEN8(i915))
257 		desc |= GEN8_CTX_L3LLC_COHERENT;
258 
259 	/* TODO: WaDisableLiteRestore when we start using semaphore
260 	 * signalling between Command Streamers
261 	 * ring->ctx_desc_template |= GEN8_CTX_FORCE_RESTORE;
262 	 */
263 
264 	return desc;
265 }
266 
267 static struct i915_gem_context *
__create_hw_context(struct drm_i915_private * dev_priv,struct drm_i915_file_private * file_priv)268 __create_hw_context(struct drm_i915_private *dev_priv,
269 		    struct drm_i915_file_private *file_priv)
270 {
271 	struct i915_gem_context *ctx;
272 	unsigned int n;
273 	int ret;
274 
275 	ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
276 	if (ctx == NULL)
277 		return ERR_PTR(-ENOMEM);
278 
279 	ret = assign_hw_id(dev_priv, &ctx->hw_id);
280 	if (ret) {
281 		kfree(ctx);
282 		return ERR_PTR(ret);
283 	}
284 
285 	kref_init(&ctx->ref);
286 	list_add_tail(&ctx->link, &dev_priv->contexts.list);
287 	ctx->i915 = dev_priv;
288 	ctx->sched.priority = I915_PRIORITY_NORMAL;
289 
290 	for (n = 0; n < ARRAY_SIZE(ctx->__engine); n++) {
291 		struct intel_context *ce = &ctx->__engine[n];
292 
293 		ce->gem_context = ctx;
294 	}
295 
296 	INIT_RADIX_TREE(&ctx->handles_vma, GFP_KERNEL);
297 	INIT_LIST_HEAD(&ctx->handles_list);
298 
299 	/* Default context will never have a file_priv */
300 	ret = DEFAULT_CONTEXT_HANDLE;
301 	if (file_priv) {
302 		ret = idr_alloc(&file_priv->context_idr, ctx,
303 				DEFAULT_CONTEXT_HANDLE, 0, GFP_KERNEL);
304 		if (ret < 0)
305 			goto err_lut;
306 	}
307 	ctx->user_handle = ret;
308 
309 	ctx->file_priv = file_priv;
310 	if (file_priv) {
311 		ctx->pid = get_task_pid(current, PIDTYPE_PID);
312 		ctx->name = kasprintf(GFP_KERNEL, "%s[%d]/%x",
313 				      current->comm,
314 				      pid_nr(ctx->pid),
315 				      ctx->user_handle);
316 		if (!ctx->name) {
317 			ret = -ENOMEM;
318 			goto err_pid;
319 		}
320 	}
321 
322 	/* NB: Mark all slices as needing a remap so that when the context first
323 	 * loads it will restore whatever remap state already exists. If there
324 	 * is no remap info, it will be a NOP. */
325 	ctx->remap_slice = ALL_L3_SLICES(dev_priv);
326 
327 	i915_gem_context_set_bannable(ctx);
328 	ctx->ring_size = 4 * PAGE_SIZE;
329 	ctx->desc_template =
330 		default_desc_template(dev_priv, dev_priv->mm.aliasing_ppgtt);
331 
332 	/*
333 	 * GuC requires the ring to be placed in Non-WOPCM memory. If GuC is not
334 	 * present or not in use we still need a small bias as ring wraparound
335 	 * at offset 0 sometimes hangs. No idea why.
336 	 */
337 	if (USES_GUC(dev_priv))
338 		ctx->ggtt_offset_bias = dev_priv->guc.ggtt_pin_bias;
339 	else
340 		ctx->ggtt_offset_bias = I915_GTT_PAGE_SIZE;
341 
342 	return ctx;
343 
344 err_pid:
345 	put_pid(ctx->pid);
346 	idr_remove(&file_priv->context_idr, ctx->user_handle);
347 err_lut:
348 	context_close(ctx);
349 	return ERR_PTR(ret);
350 }
351 
__destroy_hw_context(struct i915_gem_context * ctx,struct drm_i915_file_private * file_priv)352 static void __destroy_hw_context(struct i915_gem_context *ctx,
353 				 struct drm_i915_file_private *file_priv)
354 {
355 	idr_remove(&file_priv->context_idr, ctx->user_handle);
356 	context_close(ctx);
357 }
358 
359 static struct i915_gem_context *
i915_gem_create_context(struct drm_i915_private * dev_priv,struct drm_i915_file_private * file_priv)360 i915_gem_create_context(struct drm_i915_private *dev_priv,
361 			struct drm_i915_file_private *file_priv)
362 {
363 	struct i915_gem_context *ctx;
364 
365 	lockdep_assert_held(&dev_priv->drm.struct_mutex);
366 
367 	/* Reap the most stale context */
368 	contexts_free_first(dev_priv);
369 
370 	ctx = __create_hw_context(dev_priv, file_priv);
371 	if (IS_ERR(ctx))
372 		return ctx;
373 
374 	if (USES_FULL_PPGTT(dev_priv)) {
375 		struct i915_hw_ppgtt *ppgtt;
376 
377 		ppgtt = i915_ppgtt_create(dev_priv, file_priv);
378 		if (IS_ERR(ppgtt)) {
379 			DRM_DEBUG_DRIVER("PPGTT setup failed (%ld)\n",
380 					 PTR_ERR(ppgtt));
381 			__destroy_hw_context(ctx, file_priv);
382 			return ERR_CAST(ppgtt);
383 		}
384 
385 		ctx->ppgtt = ppgtt;
386 		ctx->desc_template = default_desc_template(dev_priv, ppgtt);
387 	}
388 
389 	trace_i915_context_create(ctx);
390 
391 	return ctx;
392 }
393 
394 /**
395  * i915_gem_context_create_gvt - create a GVT GEM context
396  * @dev: drm device *
397  *
398  * This function is used to create a GVT specific GEM context.
399  *
400  * Returns:
401  * pointer to i915_gem_context on success, error pointer if failed
402  *
403  */
404 struct i915_gem_context *
i915_gem_context_create_gvt(struct drm_device * dev)405 i915_gem_context_create_gvt(struct drm_device *dev)
406 {
407 	struct i915_gem_context *ctx;
408 	int ret;
409 
410 	if (!IS_ENABLED(CONFIG_DRM_I915_GVT))
411 		return ERR_PTR(-ENODEV);
412 
413 	ret = i915_mutex_lock_interruptible(dev);
414 	if (ret)
415 		return ERR_PTR(ret);
416 
417 	ctx = __create_hw_context(to_i915(dev), NULL);
418 	if (IS_ERR(ctx))
419 		goto out;
420 
421 	ctx->file_priv = ERR_PTR(-EBADF);
422 	i915_gem_context_set_closed(ctx); /* not user accessible */
423 	i915_gem_context_clear_bannable(ctx);
424 	i915_gem_context_set_force_single_submission(ctx);
425 	if (!USES_GUC_SUBMISSION(to_i915(dev)))
426 		ctx->ring_size = 512 * PAGE_SIZE; /* Max ring buffer size */
427 
428 	GEM_BUG_ON(i915_gem_context_is_kernel(ctx));
429 out:
430 	mutex_unlock(&dev->struct_mutex);
431 	return ctx;
432 }
433 
434 struct i915_gem_context *
i915_gem_context_create_kernel(struct drm_i915_private * i915,int prio)435 i915_gem_context_create_kernel(struct drm_i915_private *i915, int prio)
436 {
437 	struct i915_gem_context *ctx;
438 
439 	ctx = i915_gem_create_context(i915, NULL);
440 	if (IS_ERR(ctx))
441 		return ctx;
442 
443 	i915_gem_context_clear_bannable(ctx);
444 	ctx->sched.priority = prio;
445 	ctx->ring_size = PAGE_SIZE;
446 
447 	GEM_BUG_ON(!i915_gem_context_is_kernel(ctx));
448 
449 	return ctx;
450 }
451 
452 static void
destroy_kernel_context(struct i915_gem_context ** ctxp)453 destroy_kernel_context(struct i915_gem_context **ctxp)
454 {
455 	struct i915_gem_context *ctx;
456 
457 	/* Keep the context ref so that we can free it immediately ourselves */
458 	ctx = i915_gem_context_get(fetch_and_zero(ctxp));
459 	GEM_BUG_ON(!i915_gem_context_is_kernel(ctx));
460 
461 	context_close(ctx);
462 	i915_gem_context_free(ctx);
463 }
464 
needs_preempt_context(struct drm_i915_private * i915)465 static bool needs_preempt_context(struct drm_i915_private *i915)
466 {
467 	return HAS_LOGICAL_RING_PREEMPTION(i915);
468 }
469 
i915_gem_contexts_init(struct drm_i915_private * dev_priv)470 int i915_gem_contexts_init(struct drm_i915_private *dev_priv)
471 {
472 	struct i915_gem_context *ctx;
473 	int ret;
474 
475 	/* Reassure ourselves we are only called once */
476 	GEM_BUG_ON(dev_priv->kernel_context);
477 	GEM_BUG_ON(dev_priv->preempt_context);
478 
479 	ret = intel_ctx_workarounds_init(dev_priv);
480 	if (ret)
481 		return ret;
482 
483 	INIT_LIST_HEAD(&dev_priv->contexts.list);
484 	INIT_WORK(&dev_priv->contexts.free_work, contexts_free_worker);
485 	init_llist_head(&dev_priv->contexts.free_list);
486 
487 	/* Using the simple ida interface, the max is limited by sizeof(int) */
488 	BUILD_BUG_ON(MAX_CONTEXT_HW_ID > INT_MAX);
489 	BUILD_BUG_ON(GEN11_MAX_CONTEXT_HW_ID > INT_MAX);
490 	ida_init(&dev_priv->contexts.hw_ida);
491 
492 	/* lowest priority; idle task */
493 	ctx = i915_gem_context_create_kernel(dev_priv, I915_PRIORITY_MIN);
494 	if (IS_ERR(ctx)) {
495 		DRM_ERROR("Failed to create default global context\n");
496 		return PTR_ERR(ctx);
497 	}
498 	/*
499 	 * For easy recognisablity, we want the kernel context to be 0 and then
500 	 * all user contexts will have non-zero hw_id.
501 	 */
502 	GEM_BUG_ON(ctx->hw_id);
503 	dev_priv->kernel_context = ctx;
504 
505 	/* highest priority; preempting task */
506 	if (needs_preempt_context(dev_priv)) {
507 		ctx = i915_gem_context_create_kernel(dev_priv, INT_MAX);
508 		if (!IS_ERR(ctx))
509 			dev_priv->preempt_context = ctx;
510 		else
511 			DRM_ERROR("Failed to create preempt context; disabling preemption\n");
512 	}
513 
514 	DRM_DEBUG_DRIVER("%s context support initialized\n",
515 			 DRIVER_CAPS(dev_priv)->has_logical_contexts ?
516 			 "logical" : "fake");
517 	return 0;
518 }
519 
i915_gem_contexts_lost(struct drm_i915_private * dev_priv)520 void i915_gem_contexts_lost(struct drm_i915_private *dev_priv)
521 {
522 	struct intel_engine_cs *engine;
523 	enum intel_engine_id id;
524 
525 	lockdep_assert_held(&dev_priv->drm.struct_mutex);
526 
527 	for_each_engine(engine, dev_priv, id)
528 		intel_engine_lost_context(engine);
529 }
530 
i915_gem_contexts_fini(struct drm_i915_private * i915)531 void i915_gem_contexts_fini(struct drm_i915_private *i915)
532 {
533 	lockdep_assert_held(&i915->drm.struct_mutex);
534 
535 	if (i915->preempt_context)
536 		destroy_kernel_context(&i915->preempt_context);
537 	destroy_kernel_context(&i915->kernel_context);
538 
539 	/* Must free all deferred contexts (via flush_workqueue) first */
540 	ida_destroy(&i915->contexts.hw_ida);
541 }
542 
context_idr_cleanup(int id,void * p,void * data)543 static int context_idr_cleanup(int id, void *p, void *data)
544 {
545 	struct i915_gem_context *ctx = p;
546 
547 	context_close(ctx);
548 	return 0;
549 }
550 
i915_gem_context_open(struct drm_i915_private * i915,struct drm_file * file)551 int i915_gem_context_open(struct drm_i915_private *i915,
552 			  struct drm_file *file)
553 {
554 	struct drm_i915_file_private *file_priv = file->driver_priv;
555 	struct i915_gem_context *ctx;
556 
557 	idr_init(&file_priv->context_idr);
558 
559 	mutex_lock(&i915->drm.struct_mutex);
560 	ctx = i915_gem_create_context(i915, file_priv);
561 	mutex_unlock(&i915->drm.struct_mutex);
562 	if (IS_ERR(ctx)) {
563 		idr_destroy(&file_priv->context_idr);
564 		return PTR_ERR(ctx);
565 	}
566 
567 	GEM_BUG_ON(i915_gem_context_is_kernel(ctx));
568 
569 	return 0;
570 }
571 
i915_gem_context_close(struct drm_file * file)572 void i915_gem_context_close(struct drm_file *file)
573 {
574 	struct drm_i915_file_private *file_priv = file->driver_priv;
575 
576 	lockdep_assert_held(&file_priv->dev_priv->drm.struct_mutex);
577 
578 	idr_for_each(&file_priv->context_idr, context_idr_cleanup, NULL);
579 	idr_destroy(&file_priv->context_idr);
580 }
581 
582 static struct i915_request *
last_request_on_engine(struct i915_timeline * timeline,struct intel_engine_cs * engine)583 last_request_on_engine(struct i915_timeline *timeline,
584 		       struct intel_engine_cs *engine)
585 {
586 	struct i915_request *rq;
587 
588 	GEM_BUG_ON(timeline == &engine->timeline);
589 
590 	rq = i915_gem_active_raw(&timeline->last_request,
591 				 &engine->i915->drm.struct_mutex);
592 	if (rq && rq->engine == engine) {
593 		GEM_TRACE("last request for %s on engine %s: %llx:%d\n",
594 			  timeline->name, engine->name,
595 			  rq->fence.context, rq->fence.seqno);
596 		GEM_BUG_ON(rq->timeline != timeline);
597 		return rq;
598 	}
599 
600 	return NULL;
601 }
602 
engine_has_kernel_context_barrier(struct intel_engine_cs * engine)603 static bool engine_has_kernel_context_barrier(struct intel_engine_cs *engine)
604 {
605 	struct drm_i915_private *i915 = engine->i915;
606 	const struct intel_context * const ce =
607 		to_intel_context(i915->kernel_context, engine);
608 	struct i915_timeline *barrier = ce->ring->timeline;
609 	struct intel_ring *ring;
610 	bool any_active = false;
611 
612 	lockdep_assert_held(&i915->drm.struct_mutex);
613 	list_for_each_entry(ring, &i915->gt.active_rings, active_link) {
614 		struct i915_request *rq;
615 
616 		rq = last_request_on_engine(ring->timeline, engine);
617 		if (!rq)
618 			continue;
619 
620 		any_active = true;
621 
622 		if (rq->hw_context == ce)
623 			continue;
624 
625 		/*
626 		 * Was this request submitted after the previous
627 		 * switch-to-kernel-context?
628 		 */
629 		if (!i915_timeline_sync_is_later(barrier, &rq->fence)) {
630 			GEM_TRACE("%s needs barrier for %llx:%d\n",
631 				  ring->timeline->name,
632 				  rq->fence.context,
633 				  rq->fence.seqno);
634 			return false;
635 		}
636 
637 		GEM_TRACE("%s has barrier after %llx:%d\n",
638 			  ring->timeline->name,
639 			  rq->fence.context,
640 			  rq->fence.seqno);
641 	}
642 
643 	/*
644 	 * If any other timeline was still active and behind the last barrier,
645 	 * then our last switch-to-kernel-context must still be queued and
646 	 * will run last (leaving the engine in the kernel context when it
647 	 * eventually idles).
648 	 */
649 	if (any_active)
650 		return true;
651 
652 	/* The engine is idle; check that it is idling in the kernel context. */
653 	return engine->last_retired_context == ce;
654 }
655 
i915_gem_switch_to_kernel_context(struct drm_i915_private * i915)656 int i915_gem_switch_to_kernel_context(struct drm_i915_private *i915)
657 {
658 	struct intel_engine_cs *engine;
659 	enum intel_engine_id id;
660 
661 	GEM_TRACE("awake?=%s\n", yesno(i915->gt.awake));
662 
663 	lockdep_assert_held(&i915->drm.struct_mutex);
664 	GEM_BUG_ON(!i915->kernel_context);
665 
666 	i915_retire_requests(i915);
667 
668 	for_each_engine(engine, i915, id) {
669 		struct intel_ring *ring;
670 		struct i915_request *rq;
671 
672 		GEM_BUG_ON(!to_intel_context(i915->kernel_context, engine));
673 		if (engine_has_kernel_context_barrier(engine))
674 			continue;
675 
676 		GEM_TRACE("emit barrier on %s\n", engine->name);
677 
678 		rq = i915_request_alloc(engine, i915->kernel_context);
679 		if (IS_ERR(rq))
680 			return PTR_ERR(rq);
681 
682 		/* Queue this switch after all other activity */
683 		list_for_each_entry(ring, &i915->gt.active_rings, active_link) {
684 			struct i915_request *prev;
685 
686 			prev = last_request_on_engine(ring->timeline, engine);
687 			if (!prev)
688 				continue;
689 
690 			if (prev->gem_context == i915->kernel_context)
691 				continue;
692 
693 			GEM_TRACE("add barrier on %s for %llx:%d\n",
694 				  engine->name,
695 				  prev->fence.context,
696 				  prev->fence.seqno);
697 			i915_sw_fence_await_sw_fence_gfp(&rq->submit,
698 							 &prev->submit,
699 							 I915_FENCE_GFP);
700 			i915_timeline_sync_set(rq->timeline, &prev->fence);
701 		}
702 
703 		i915_request_add(rq);
704 	}
705 
706 	return 0;
707 }
708 
client_is_banned(struct drm_i915_file_private * file_priv)709 static bool client_is_banned(struct drm_i915_file_private *file_priv)
710 {
711 	return atomic_read(&file_priv->ban_score) >= I915_CLIENT_SCORE_BANNED;
712 }
713 
i915_gem_context_create_ioctl(struct drm_device * dev,void * data,struct drm_file * file)714 int i915_gem_context_create_ioctl(struct drm_device *dev, void *data,
715 				  struct drm_file *file)
716 {
717 	struct drm_i915_private *dev_priv = to_i915(dev);
718 	struct drm_i915_gem_context_create *args = data;
719 	struct drm_i915_file_private *file_priv = file->driver_priv;
720 	struct i915_gem_context *ctx;
721 	int ret;
722 
723 	if (!DRIVER_CAPS(dev_priv)->has_logical_contexts)
724 		return -ENODEV;
725 
726 	if (args->pad != 0)
727 		return -EINVAL;
728 
729 	if (client_is_banned(file_priv)) {
730 		DRM_DEBUG("client %s[%d] banned from creating ctx\n",
731 			  current->comm,
732 			  pid_nr(get_task_pid(current, PIDTYPE_PID)));
733 
734 		return -EIO;
735 	}
736 
737 	ret = i915_mutex_lock_interruptible(dev);
738 	if (ret)
739 		return ret;
740 
741 	ctx = i915_gem_create_context(dev_priv, file_priv);
742 	mutex_unlock(&dev->struct_mutex);
743 	if (IS_ERR(ctx))
744 		return PTR_ERR(ctx);
745 
746 	GEM_BUG_ON(i915_gem_context_is_kernel(ctx));
747 
748 	args->ctx_id = ctx->user_handle;
749 	DRM_DEBUG("HW context %d created\n", args->ctx_id);
750 
751 	return 0;
752 }
753 
i915_gem_context_destroy_ioctl(struct drm_device * dev,void * data,struct drm_file * file)754 int i915_gem_context_destroy_ioctl(struct drm_device *dev, void *data,
755 				   struct drm_file *file)
756 {
757 	struct drm_i915_gem_context_destroy *args = data;
758 	struct drm_i915_file_private *file_priv = file->driver_priv;
759 	struct i915_gem_context *ctx;
760 	int ret;
761 
762 	if (args->pad != 0)
763 		return -EINVAL;
764 
765 	if (args->ctx_id == DEFAULT_CONTEXT_HANDLE)
766 		return -ENOENT;
767 
768 	ctx = i915_gem_context_lookup(file_priv, args->ctx_id);
769 	if (!ctx)
770 		return -ENOENT;
771 
772 	ret = mutex_lock_interruptible(&dev->struct_mutex);
773 	if (ret)
774 		goto out;
775 
776 	__destroy_hw_context(ctx, file_priv);
777 	mutex_unlock(&dev->struct_mutex);
778 
779 out:
780 	i915_gem_context_put(ctx);
781 	return 0;
782 }
783 
i915_gem_context_getparam_ioctl(struct drm_device * dev,void * data,struct drm_file * file)784 int i915_gem_context_getparam_ioctl(struct drm_device *dev, void *data,
785 				    struct drm_file *file)
786 {
787 	struct drm_i915_file_private *file_priv = file->driver_priv;
788 	struct drm_i915_gem_context_param *args = data;
789 	struct i915_gem_context *ctx;
790 	int ret = 0;
791 
792 	ctx = i915_gem_context_lookup(file_priv, args->ctx_id);
793 	if (!ctx)
794 		return -ENOENT;
795 
796 	args->size = 0;
797 	switch (args->param) {
798 	case I915_CONTEXT_PARAM_BAN_PERIOD:
799 		ret = -EINVAL;
800 		break;
801 	case I915_CONTEXT_PARAM_NO_ZEROMAP:
802 		args->value = ctx->flags & CONTEXT_NO_ZEROMAP;
803 		break;
804 	case I915_CONTEXT_PARAM_GTT_SIZE:
805 		if (ctx->ppgtt)
806 			args->value = ctx->ppgtt->vm.total;
807 		else if (to_i915(dev)->mm.aliasing_ppgtt)
808 			args->value = to_i915(dev)->mm.aliasing_ppgtt->vm.total;
809 		else
810 			args->value = to_i915(dev)->ggtt.vm.total;
811 		break;
812 	case I915_CONTEXT_PARAM_NO_ERROR_CAPTURE:
813 		args->value = i915_gem_context_no_error_capture(ctx);
814 		break;
815 	case I915_CONTEXT_PARAM_BANNABLE:
816 		args->value = i915_gem_context_is_bannable(ctx);
817 		break;
818 	case I915_CONTEXT_PARAM_PRIORITY:
819 		args->value = ctx->sched.priority;
820 		break;
821 	default:
822 		ret = -EINVAL;
823 		break;
824 	}
825 
826 	i915_gem_context_put(ctx);
827 	return ret;
828 }
829 
i915_gem_context_setparam_ioctl(struct drm_device * dev,void * data,struct drm_file * file)830 int i915_gem_context_setparam_ioctl(struct drm_device *dev, void *data,
831 				    struct drm_file *file)
832 {
833 	struct drm_i915_file_private *file_priv = file->driver_priv;
834 	struct drm_i915_gem_context_param *args = data;
835 	struct i915_gem_context *ctx;
836 	int ret;
837 
838 	ctx = i915_gem_context_lookup(file_priv, args->ctx_id);
839 	if (!ctx)
840 		return -ENOENT;
841 
842 	ret = i915_mutex_lock_interruptible(dev);
843 	if (ret)
844 		goto out;
845 
846 	switch (args->param) {
847 	case I915_CONTEXT_PARAM_BAN_PERIOD:
848 		ret = -EINVAL;
849 		break;
850 	case I915_CONTEXT_PARAM_NO_ZEROMAP:
851 		if (args->size) {
852 			ret = -EINVAL;
853 		} else {
854 			ctx->flags &= ~CONTEXT_NO_ZEROMAP;
855 			ctx->flags |= args->value ? CONTEXT_NO_ZEROMAP : 0;
856 		}
857 		break;
858 	case I915_CONTEXT_PARAM_NO_ERROR_CAPTURE:
859 		if (args->size)
860 			ret = -EINVAL;
861 		else if (args->value)
862 			i915_gem_context_set_no_error_capture(ctx);
863 		else
864 			i915_gem_context_clear_no_error_capture(ctx);
865 		break;
866 	case I915_CONTEXT_PARAM_BANNABLE:
867 		if (args->size)
868 			ret = -EINVAL;
869 		else if (!capable(CAP_SYS_ADMIN) && !args->value)
870 			ret = -EPERM;
871 		else if (args->value)
872 			i915_gem_context_set_bannable(ctx);
873 		else
874 			i915_gem_context_clear_bannable(ctx);
875 		break;
876 
877 	case I915_CONTEXT_PARAM_PRIORITY:
878 		{
879 			s64 priority = args->value;
880 
881 			if (args->size)
882 				ret = -EINVAL;
883 			else if (!(to_i915(dev)->caps.scheduler & I915_SCHEDULER_CAP_PRIORITY))
884 				ret = -ENODEV;
885 			else if (priority > I915_CONTEXT_MAX_USER_PRIORITY ||
886 				 priority < I915_CONTEXT_MIN_USER_PRIORITY)
887 				ret = -EINVAL;
888 			else if (priority > I915_CONTEXT_DEFAULT_PRIORITY &&
889 				 !capable(CAP_SYS_NICE))
890 				ret = -EPERM;
891 			else
892 				ctx->sched.priority = priority;
893 		}
894 		break;
895 
896 	default:
897 		ret = -EINVAL;
898 		break;
899 	}
900 	mutex_unlock(&dev->struct_mutex);
901 
902 out:
903 	i915_gem_context_put(ctx);
904 	return ret;
905 }
906 
i915_gem_context_reset_stats_ioctl(struct drm_device * dev,void * data,struct drm_file * file)907 int i915_gem_context_reset_stats_ioctl(struct drm_device *dev,
908 				       void *data, struct drm_file *file)
909 {
910 	struct drm_i915_private *dev_priv = to_i915(dev);
911 	struct drm_i915_reset_stats *args = data;
912 	struct i915_gem_context *ctx;
913 	int ret;
914 
915 	if (args->flags || args->pad)
916 		return -EINVAL;
917 
918 	ret = -ENOENT;
919 	rcu_read_lock();
920 	ctx = __i915_gem_context_lookup_rcu(file->driver_priv, args->ctx_id);
921 	if (!ctx)
922 		goto out;
923 
924 	/*
925 	 * We opt for unserialised reads here. This may result in tearing
926 	 * in the extremely unlikely event of a GPU hang on this context
927 	 * as we are querying them. If we need that extra layer of protection,
928 	 * we should wrap the hangstats with a seqlock.
929 	 */
930 
931 	if (capable(CAP_SYS_ADMIN))
932 		args->reset_count = i915_reset_count(&dev_priv->gpu_error);
933 	else
934 		args->reset_count = 0;
935 
936 	args->batch_active = atomic_read(&ctx->guilty_count);
937 	args->batch_pending = atomic_read(&ctx->active_count);
938 
939 	ret = 0;
940 out:
941 	rcu_read_unlock();
942 	return ret;
943 }
944 
945 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
946 #include "selftests/mock_context.c"
947 #include "selftests/i915_gem_context.c"
948 #endif
949