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 <drm/drmP.h>
89#include <drm/i915_drm.h>
90#include "i915_drv.h"
91#include "i915_trace.h"
92
93/* This is a HW constraint. The value below is the largest known requirement
94 * I've seen in a spec to date, and that was a workaround for a non-shipping
95 * part. It should be safe to decrease this, but it's more future proof as is.
96 */
97#define GEN6_CONTEXT_ALIGN (64<<10)
98#define GEN7_CONTEXT_ALIGN 4096
99
100static size_t get_context_alignment(struct drm_device *dev)
101{
102	if (IS_GEN6(dev))
103		return GEN6_CONTEXT_ALIGN;
104
105	return GEN7_CONTEXT_ALIGN;
106}
107
108static int get_context_size(struct drm_device *dev)
109{
110	struct drm_i915_private *dev_priv = dev->dev_private;
111	int ret;
112	u32 reg;
113
114	switch (INTEL_INFO(dev)->gen) {
115	case 6:
116		reg = I915_READ(CXT_SIZE);
117		ret = GEN6_CXT_TOTAL_SIZE(reg) * 64;
118		break;
119	case 7:
120		reg = I915_READ(GEN7_CXT_SIZE);
121		if (IS_HASWELL(dev))
122			ret = HSW_CXT_TOTAL_SIZE;
123		else
124			ret = GEN7_CXT_TOTAL_SIZE(reg) * 64;
125		break;
126	case 8:
127		ret = GEN8_CXT_TOTAL_SIZE;
128		break;
129	default:
130		BUG();
131	}
132
133	return ret;
134}
135
136void i915_gem_context_free(struct kref *ctx_ref)
137{
138	struct intel_context *ctx = container_of(ctx_ref,
139						 typeof(*ctx), ref);
140
141	trace_i915_context_free(ctx);
142
143	if (i915.enable_execlists)
144		intel_lr_context_free(ctx);
145
146	i915_ppgtt_put(ctx->ppgtt);
147
148	if (ctx->legacy_hw_ctx.rcs_state)
149		drm_gem_object_unreference(&ctx->legacy_hw_ctx.rcs_state->base);
150	list_del(&ctx->link);
151	kfree(ctx);
152}
153
154struct drm_i915_gem_object *
155i915_gem_alloc_context_obj(struct drm_device *dev, size_t size)
156{
157	struct drm_i915_gem_object *obj;
158	int ret;
159
160	obj = i915_gem_alloc_object(dev, size);
161	if (obj == NULL)
162		return ERR_PTR(-ENOMEM);
163
164	/*
165	 * Try to make the context utilize L3 as well as LLC.
166	 *
167	 * On VLV we don't have L3 controls in the PTEs so we
168	 * shouldn't touch the cache level, especially as that
169	 * would make the object snooped which might have a
170	 * negative performance impact.
171	 */
172	if (INTEL_INFO(dev)->gen >= 7 && !IS_VALLEYVIEW(dev)) {
173		ret = i915_gem_object_set_cache_level(obj, I915_CACHE_L3_LLC);
174		/* Failure shouldn't ever happen this early */
175		if (WARN_ON(ret)) {
176			drm_gem_object_unreference(&obj->base);
177			return ERR_PTR(ret);
178		}
179	}
180
181	return obj;
182}
183
184static struct intel_context *
185__create_hw_context(struct drm_device *dev,
186		    struct drm_i915_file_private *file_priv)
187{
188	struct drm_i915_private *dev_priv = dev->dev_private;
189	struct intel_context *ctx;
190	int ret;
191
192	ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
193	if (ctx == NULL)
194		return ERR_PTR(-ENOMEM);
195
196	kref_init(&ctx->ref);
197	list_add_tail(&ctx->link, &dev_priv->context_list);
198
199	if (dev_priv->hw_context_size) {
200		struct drm_i915_gem_object *obj =
201				i915_gem_alloc_context_obj(dev, dev_priv->hw_context_size);
202		if (IS_ERR(obj)) {
203			ret = PTR_ERR(obj);
204			goto err_out;
205		}
206		ctx->legacy_hw_ctx.rcs_state = obj;
207	}
208
209	/* Default context will never have a file_priv */
210	if (file_priv != NULL) {
211		ret = idr_alloc(&file_priv->context_idr, ctx,
212				DEFAULT_CONTEXT_HANDLE, 0, GFP_KERNEL);
213		if (ret < 0)
214			goto err_out;
215	} else
216		ret = DEFAULT_CONTEXT_HANDLE;
217
218	ctx->file_priv = file_priv;
219	ctx->user_handle = ret;
220	/* NB: Mark all slices as needing a remap so that when the context first
221	 * loads it will restore whatever remap state already exists. If there
222	 * is no remap info, it will be a NOP. */
223	ctx->remap_slice = (1 << NUM_L3_SLICES(dev)) - 1;
224
225	ctx->hang_stats.ban_period_seconds = DRM_I915_CTX_BAN_PERIOD;
226
227	return ctx;
228
229err_out:
230	i915_gem_context_unreference(ctx);
231	return ERR_PTR(ret);
232}
233
234/**
235 * The default context needs to exist per ring that uses contexts. It stores the
236 * context state of the GPU for applications that don't utilize HW contexts, as
237 * well as an idle case.
238 */
239static struct intel_context *
240i915_gem_create_context(struct drm_device *dev,
241			struct drm_i915_file_private *file_priv)
242{
243	const bool is_global_default_ctx = file_priv == NULL;
244	struct intel_context *ctx;
245	int ret = 0;
246
247	BUG_ON(!mutex_is_locked(&dev->struct_mutex));
248
249	ctx = __create_hw_context(dev, file_priv);
250	if (IS_ERR(ctx))
251		return ctx;
252
253	if (is_global_default_ctx && ctx->legacy_hw_ctx.rcs_state) {
254		/* We may need to do things with the shrinker which
255		 * require us to immediately switch back to the default
256		 * context. This can cause a problem as pinning the
257		 * default context also requires GTT space which may not
258		 * be available. To avoid this we always pin the default
259		 * context.
260		 */
261		ret = i915_gem_obj_ggtt_pin(ctx->legacy_hw_ctx.rcs_state,
262					    get_context_alignment(dev), 0);
263		if (ret) {
264			DRM_DEBUG_DRIVER("Couldn't pin %d\n", ret);
265			goto err_destroy;
266		}
267	}
268
269	if (USES_FULL_PPGTT(dev)) {
270		struct i915_hw_ppgtt *ppgtt = i915_ppgtt_create(dev, file_priv);
271
272		if (IS_ERR_OR_NULL(ppgtt)) {
273			DRM_DEBUG_DRIVER("PPGTT setup failed (%ld)\n",
274					 PTR_ERR(ppgtt));
275			ret = PTR_ERR(ppgtt);
276			goto err_unpin;
277		}
278
279		ctx->ppgtt = ppgtt;
280	}
281
282	trace_i915_context_create(ctx);
283
284	return ctx;
285
286err_unpin:
287	if (is_global_default_ctx && ctx->legacy_hw_ctx.rcs_state)
288		i915_gem_object_ggtt_unpin(ctx->legacy_hw_ctx.rcs_state);
289err_destroy:
290	i915_gem_context_unreference(ctx);
291	return ERR_PTR(ret);
292}
293
294void i915_gem_context_reset(struct drm_device *dev)
295{
296	struct drm_i915_private *dev_priv = dev->dev_private;
297	int i;
298
299	if (i915.enable_execlists) {
300		struct intel_context *ctx;
301
302		list_for_each_entry(ctx, &dev_priv->context_list, link) {
303			intel_lr_context_reset(dev, ctx);
304		}
305
306		return;
307	}
308
309	for (i = 0; i < I915_NUM_RINGS; i++) {
310		struct intel_engine_cs *ring = &dev_priv->ring[i];
311		struct intel_context *lctx = ring->last_context;
312
313		if (lctx) {
314			if (lctx->legacy_hw_ctx.rcs_state && i == RCS)
315				i915_gem_object_ggtt_unpin(lctx->legacy_hw_ctx.rcs_state);
316
317			i915_gem_context_unreference(lctx);
318			ring->last_context = NULL;
319		}
320
321		/* Force the GPU state to be reinitialised on enabling */
322		if (ring->default_context)
323			ring->default_context->legacy_hw_ctx.initialized = false;
324	}
325}
326
327int i915_gem_context_init(struct drm_device *dev)
328{
329	struct drm_i915_private *dev_priv = dev->dev_private;
330	struct intel_context *ctx;
331	int i;
332
333	/* Init should only be called once per module load. Eventually the
334	 * restriction on the context_disabled check can be loosened. */
335	if (WARN_ON(dev_priv->ring[RCS].default_context))
336		return 0;
337
338	if (i915.enable_execlists) {
339		/* NB: intentionally left blank. We will allocate our own
340		 * backing objects as we need them, thank you very much */
341		dev_priv->hw_context_size = 0;
342	} else if (HAS_HW_CONTEXTS(dev)) {
343		dev_priv->hw_context_size = round_up(get_context_size(dev), 4096);
344		if (dev_priv->hw_context_size > (1<<20)) {
345			DRM_DEBUG_DRIVER("Disabling HW Contexts; invalid size %d\n",
346					 dev_priv->hw_context_size);
347			dev_priv->hw_context_size = 0;
348		}
349	}
350
351	ctx = i915_gem_create_context(dev, NULL);
352	if (IS_ERR(ctx)) {
353		DRM_ERROR("Failed to create default global context (error %ld)\n",
354			  PTR_ERR(ctx));
355		return PTR_ERR(ctx);
356	}
357
358	for (i = 0; i < I915_NUM_RINGS; i++) {
359		struct intel_engine_cs *ring = &dev_priv->ring[i];
360
361		/* NB: RCS will hold a ref for all rings */
362		ring->default_context = ctx;
363	}
364
365	DRM_DEBUG_DRIVER("%s context support initialized\n",
366			i915.enable_execlists ? "LR" :
367			dev_priv->hw_context_size ? "HW" : "fake");
368	return 0;
369}
370
371void i915_gem_context_fini(struct drm_device *dev)
372{
373	struct drm_i915_private *dev_priv = dev->dev_private;
374	struct intel_context *dctx = dev_priv->ring[RCS].default_context;
375	int i;
376
377	if (dctx->legacy_hw_ctx.rcs_state) {
378		/* The only known way to stop the gpu from accessing the hw context is
379		 * to reset it. Do this as the very last operation to avoid confusing
380		 * other code, leading to spurious errors. */
381		intel_gpu_reset(dev);
382
383		/* When default context is created and switched to, base object refcount
384		 * will be 2 (+1 from object creation and +1 from do_switch()).
385		 * i915_gem_context_fini() will be called after gpu_idle() has switched
386		 * to default context. So we need to unreference the base object once
387		 * to offset the do_switch part, so that i915_gem_context_unreference()
388		 * can then free the base object correctly. */
389		WARN_ON(!dev_priv->ring[RCS].last_context);
390		if (dev_priv->ring[RCS].last_context == dctx) {
391			/* Fake switch to NULL context */
392			WARN_ON(dctx->legacy_hw_ctx.rcs_state->active);
393			i915_gem_object_ggtt_unpin(dctx->legacy_hw_ctx.rcs_state);
394			i915_gem_context_unreference(dctx);
395			dev_priv->ring[RCS].last_context = NULL;
396		}
397
398		i915_gem_object_ggtt_unpin(dctx->legacy_hw_ctx.rcs_state);
399	}
400
401	for (i = 0; i < I915_NUM_RINGS; i++) {
402		struct intel_engine_cs *ring = &dev_priv->ring[i];
403
404		if (ring->last_context)
405			i915_gem_context_unreference(ring->last_context);
406
407		ring->default_context = NULL;
408		ring->last_context = NULL;
409	}
410
411	i915_gem_context_unreference(dctx);
412}
413
414int i915_gem_context_enable(struct drm_i915_private *dev_priv)
415{
416	struct intel_engine_cs *ring;
417	int ret, i;
418
419	BUG_ON(!dev_priv->ring[RCS].default_context);
420
421	if (i915.enable_execlists) {
422		for_each_ring(ring, dev_priv, i) {
423			if (ring->init_context) {
424				ret = ring->init_context(ring,
425						ring->default_context);
426				if (ret) {
427					DRM_ERROR("ring init context: %d\n",
428							ret);
429					return ret;
430				}
431			}
432		}
433
434	} else
435		for_each_ring(ring, dev_priv, i) {
436			ret = i915_switch_context(ring, ring->default_context);
437			if (ret)
438				return ret;
439		}
440
441	return 0;
442}
443
444static int context_idr_cleanup(int id, void *p, void *data)
445{
446	struct intel_context *ctx = p;
447
448	i915_gem_context_unreference(ctx);
449	return 0;
450}
451
452int i915_gem_context_open(struct drm_device *dev, struct drm_file *file)
453{
454	struct drm_i915_file_private *file_priv = file->driver_priv;
455	struct intel_context *ctx;
456
457	idr_init(&file_priv->context_idr);
458
459	mutex_lock(&dev->struct_mutex);
460	ctx = i915_gem_create_context(dev, file_priv);
461	mutex_unlock(&dev->struct_mutex);
462
463	if (IS_ERR(ctx)) {
464		idr_destroy(&file_priv->context_idr);
465		return PTR_ERR(ctx);
466	}
467
468	return 0;
469}
470
471void i915_gem_context_close(struct drm_device *dev, struct drm_file *file)
472{
473	struct drm_i915_file_private *file_priv = file->driver_priv;
474
475	idr_for_each(&file_priv->context_idr, context_idr_cleanup, NULL);
476	idr_destroy(&file_priv->context_idr);
477}
478
479struct intel_context *
480i915_gem_context_get(struct drm_i915_file_private *file_priv, u32 id)
481{
482	struct intel_context *ctx;
483
484	ctx = (struct intel_context *)idr_find(&file_priv->context_idr, id);
485	if (!ctx)
486		return ERR_PTR(-ENOENT);
487
488	return ctx;
489}
490
491static inline int
492mi_set_context(struct intel_engine_cs *ring,
493	       struct intel_context *new_context,
494	       u32 hw_flags)
495{
496	u32 flags = hw_flags | MI_MM_SPACE_GTT;
497	const int num_rings =
498		/* Use an extended w/a on ivb+ if signalling from other rings */
499		i915_semaphore_is_enabled(ring->dev) ?
500		hweight32(INTEL_INFO(ring->dev)->ring_mask) - 1 :
501		0;
502	int len, i, ret;
503
504	/* w/a: If Flush TLB Invalidation Mode is enabled, driver must do a TLB
505	 * invalidation prior to MI_SET_CONTEXT. On GEN6 we don't set the value
506	 * explicitly, so we rely on the value at ring init, stored in
507	 * itlb_before_ctx_switch.
508	 */
509	if (IS_GEN6(ring->dev)) {
510		ret = ring->flush(ring, I915_GEM_GPU_DOMAINS, 0);
511		if (ret)
512			return ret;
513	}
514
515	/* These flags are for resource streamer on HSW+ */
516	if (!IS_HASWELL(ring->dev) && INTEL_INFO(ring->dev)->gen < 8)
517		flags |= (MI_SAVE_EXT_STATE_EN | MI_RESTORE_EXT_STATE_EN);
518
519
520	len = 4;
521	if (INTEL_INFO(ring->dev)->gen >= 7)
522		len += 2 + (num_rings ? 4*num_rings + 2 : 0);
523
524	ret = intel_ring_begin(ring, len);
525	if (ret)
526		return ret;
527
528	/* WaProgramMiArbOnOffAroundMiSetContext:ivb,vlv,hsw,bdw,chv */
529	if (INTEL_INFO(ring->dev)->gen >= 7) {
530		intel_ring_emit(ring, MI_ARB_ON_OFF | MI_ARB_DISABLE);
531		if (num_rings) {
532			struct intel_engine_cs *signaller;
533
534			intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(num_rings));
535			for_each_ring(signaller, to_i915(ring->dev), i) {
536				if (signaller == ring)
537					continue;
538
539				intel_ring_emit(ring, RING_PSMI_CTL(signaller->mmio_base));
540				intel_ring_emit(ring, _MASKED_BIT_ENABLE(GEN6_PSMI_SLEEP_MSG_DISABLE));
541			}
542		}
543	}
544
545	intel_ring_emit(ring, MI_NOOP);
546	intel_ring_emit(ring, MI_SET_CONTEXT);
547	intel_ring_emit(ring, i915_gem_obj_ggtt_offset(new_context->legacy_hw_ctx.rcs_state) |
548			flags);
549	/*
550	 * w/a: MI_SET_CONTEXT must always be followed by MI_NOOP
551	 * WaMiSetContext_Hang:snb,ivb,vlv
552	 */
553	intel_ring_emit(ring, MI_NOOP);
554
555	if (INTEL_INFO(ring->dev)->gen >= 7) {
556		if (num_rings) {
557			struct intel_engine_cs *signaller;
558
559			intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(num_rings));
560			for_each_ring(signaller, to_i915(ring->dev), i) {
561				if (signaller == ring)
562					continue;
563
564				intel_ring_emit(ring, RING_PSMI_CTL(signaller->mmio_base));
565				intel_ring_emit(ring, _MASKED_BIT_DISABLE(GEN6_PSMI_SLEEP_MSG_DISABLE));
566			}
567		}
568		intel_ring_emit(ring, MI_ARB_ON_OFF | MI_ARB_ENABLE);
569	}
570
571	intel_ring_advance(ring);
572
573	return ret;
574}
575
576static inline bool should_skip_switch(struct intel_engine_cs *ring,
577				      struct intel_context *from,
578				      struct intel_context *to)
579{
580	struct drm_i915_private *dev_priv = ring->dev->dev_private;
581
582	if (to->remap_slice)
583		return false;
584
585	if (to->ppgtt) {
586		if (from == to && !test_bit(ring->id,
587				&to->ppgtt->pd_dirty_rings))
588			return true;
589	} else if (dev_priv->mm.aliasing_ppgtt) {
590		if (from == to && !test_bit(ring->id,
591				&dev_priv->mm.aliasing_ppgtt->pd_dirty_rings))
592			return true;
593	}
594
595	return false;
596}
597
598static bool
599needs_pd_load_pre(struct intel_engine_cs *ring, struct intel_context *to)
600{
601	struct drm_i915_private *dev_priv = ring->dev->dev_private;
602
603	if (!to->ppgtt)
604		return false;
605
606	if (INTEL_INFO(ring->dev)->gen < 8)
607		return true;
608
609	if (ring != &dev_priv->ring[RCS])
610		return true;
611
612	return false;
613}
614
615static bool
616needs_pd_load_post(struct intel_engine_cs *ring, struct intel_context *to,
617		u32 hw_flags)
618{
619	struct drm_i915_private *dev_priv = ring->dev->dev_private;
620
621	if (!to->ppgtt)
622		return false;
623
624	if (!IS_GEN8(ring->dev))
625		return false;
626
627	if (ring != &dev_priv->ring[RCS])
628		return false;
629
630	if (hw_flags & MI_RESTORE_INHIBIT)
631		return true;
632
633	return false;
634}
635
636static int do_switch(struct intel_engine_cs *ring,
637		     struct intel_context *to)
638{
639	struct drm_i915_private *dev_priv = ring->dev->dev_private;
640	struct intel_context *from = ring->last_context;
641	u32 hw_flags = 0;
642	bool uninitialized = false;
643	struct i915_vma *vma;
644	int ret, i;
645
646	if (from != NULL && ring == &dev_priv->ring[RCS]) {
647		BUG_ON(from->legacy_hw_ctx.rcs_state == NULL);
648		BUG_ON(!i915_gem_obj_is_pinned(from->legacy_hw_ctx.rcs_state));
649	}
650
651	if (should_skip_switch(ring, from, to))
652		return 0;
653
654	/* Trying to pin first makes error handling easier. */
655	if (ring == &dev_priv->ring[RCS]) {
656		ret = i915_gem_obj_ggtt_pin(to->legacy_hw_ctx.rcs_state,
657					    get_context_alignment(ring->dev), 0);
658		if (ret)
659			return ret;
660	}
661
662	/*
663	 * Pin can switch back to the default context if we end up calling into
664	 * evict_everything - as a last ditch gtt defrag effort that also
665	 * switches to the default context. Hence we need to reload from here.
666	 */
667	from = ring->last_context;
668
669	if (needs_pd_load_pre(ring, to)) {
670		/* Older GENs and non render rings still want the load first,
671		 * "PP_DCLV followed by PP_DIR_BASE register through Load
672		 * Register Immediate commands in Ring Buffer before submitting
673		 * a context."*/
674		trace_switch_mm(ring, to);
675		ret = to->ppgtt->switch_mm(to->ppgtt, ring);
676		if (ret)
677			goto unpin_out;
678
679		/* Doing a PD load always reloads the page dirs */
680		clear_bit(ring->id, &to->ppgtt->pd_dirty_rings);
681	}
682
683	if (ring != &dev_priv->ring[RCS]) {
684		if (from)
685			i915_gem_context_unreference(from);
686		goto done;
687	}
688
689	/*
690	 * Clear this page out of any CPU caches for coherent swap-in/out. Note
691	 * that thanks to write = false in this call and us not setting any gpu
692	 * write domains when putting a context object onto the active list
693	 * (when switching away from it), this won't block.
694	 *
695	 * XXX: We need a real interface to do this instead of trickery.
696	 */
697	ret = i915_gem_object_set_to_gtt_domain(to->legacy_hw_ctx.rcs_state, false);
698	if (ret)
699		goto unpin_out;
700
701	vma = i915_gem_obj_to_ggtt(to->legacy_hw_ctx.rcs_state);
702	if (!(vma->bound & GLOBAL_BIND)) {
703		ret = i915_vma_bind(vma,
704				    to->legacy_hw_ctx.rcs_state->cache_level,
705				    GLOBAL_BIND);
706		/* This shouldn't ever fail. */
707		if (WARN_ONCE(ret, "GGTT context bind failed!"))
708			goto unpin_out;
709	}
710
711	if (!to->legacy_hw_ctx.initialized || i915_gem_context_is_default(to)) {
712		hw_flags |= MI_RESTORE_INHIBIT;
713		/* NB: If we inhibit the restore, the context is not allowed to
714		 * die because future work may end up depending on valid address
715		 * space. This means we must enforce that a page table load
716		 * occur when this occurs. */
717	} else if (to->ppgtt &&
718			test_and_clear_bit(ring->id, &to->ppgtt->pd_dirty_rings))
719		hw_flags |= MI_FORCE_RESTORE;
720
721	/* We should never emit switch_mm more than once */
722	WARN_ON(needs_pd_load_pre(ring, to) &&
723			needs_pd_load_post(ring, to, hw_flags));
724
725	ret = mi_set_context(ring, to, hw_flags);
726	if (ret)
727		goto unpin_out;
728
729	/* GEN8 does *not* require an explicit reload if the PDPs have been
730	 * setup, and we do not wish to move them.
731	 */
732	if (needs_pd_load_post(ring, to, hw_flags)) {
733		trace_switch_mm(ring, to);
734		ret = to->ppgtt->switch_mm(to->ppgtt, ring);
735		/* The hardware context switch is emitted, but we haven't
736		 * actually changed the state - so it's probably safe to bail
737		 * here. Still, let the user know something dangerous has
738		 * happened.
739		 */
740		if (ret) {
741			DRM_ERROR("Failed to change address space on context switch\n");
742			goto unpin_out;
743		}
744	}
745
746	for (i = 0; i < MAX_L3_SLICES; i++) {
747		if (!(to->remap_slice & (1<<i)))
748			continue;
749
750		ret = i915_gem_l3_remap(ring, i);
751		/* If it failed, try again next round */
752		if (ret)
753			DRM_DEBUG_DRIVER("L3 remapping failed\n");
754		else
755			to->remap_slice &= ~(1<<i);
756	}
757
758	/* The backing object for the context is done after switching to the
759	 * *next* context. Therefore we cannot retire the previous context until
760	 * the next context has already started running. In fact, the below code
761	 * is a bit suboptimal because the retiring can occur simply after the
762	 * MI_SET_CONTEXT instead of when the next seqno has completed.
763	 */
764	if (from != NULL) {
765		from->legacy_hw_ctx.rcs_state->base.read_domains = I915_GEM_DOMAIN_INSTRUCTION;
766		i915_vma_move_to_active(i915_gem_obj_to_ggtt(from->legacy_hw_ctx.rcs_state), ring);
767		/* As long as MI_SET_CONTEXT is serializing, ie. it flushes the
768		 * whole damn pipeline, we don't need to explicitly mark the
769		 * object dirty. The only exception is that the context must be
770		 * correct in case the object gets swapped out. Ideally we'd be
771		 * able to defer doing this until we know the object would be
772		 * swapped, but there is no way to do that yet.
773		 */
774		from->legacy_hw_ctx.rcs_state->dirty = 1;
775		BUG_ON(i915_gem_request_get_ring(
776			from->legacy_hw_ctx.rcs_state->last_read_req) != ring);
777
778		/* obj is kept alive until the next request by its active ref */
779		i915_gem_object_ggtt_unpin(from->legacy_hw_ctx.rcs_state);
780		i915_gem_context_unreference(from);
781	}
782
783	uninitialized = !to->legacy_hw_ctx.initialized;
784	to->legacy_hw_ctx.initialized = true;
785
786done:
787	i915_gem_context_reference(to);
788	ring->last_context = to;
789
790	if (uninitialized) {
791		if (ring->init_context) {
792			ret = ring->init_context(ring, to);
793			if (ret)
794				DRM_ERROR("ring init context: %d\n", ret);
795		}
796	}
797
798	return 0;
799
800unpin_out:
801	if (ring->id == RCS)
802		i915_gem_object_ggtt_unpin(to->legacy_hw_ctx.rcs_state);
803	return ret;
804}
805
806/**
807 * i915_switch_context() - perform a GPU context switch.
808 * @ring: ring for which we'll execute the context switch
809 * @to: the context to switch to
810 *
811 * The context life cycle is simple. The context refcount is incremented and
812 * decremented by 1 and create and destroy. If the context is in use by the GPU,
813 * it will have a refcount > 1. This allows us to destroy the context abstract
814 * object while letting the normal object tracking destroy the backing BO.
815 *
816 * This function should not be used in execlists mode.  Instead the context is
817 * switched by writing to the ELSP and requests keep a reference to their
818 * context.
819 */
820int i915_switch_context(struct intel_engine_cs *ring,
821			struct intel_context *to)
822{
823	struct drm_i915_private *dev_priv = ring->dev->dev_private;
824
825	WARN_ON(i915.enable_execlists);
826	WARN_ON(!mutex_is_locked(&dev_priv->dev->struct_mutex));
827
828	if (to->legacy_hw_ctx.rcs_state == NULL) { /* We have the fake context */
829		if (to != ring->last_context) {
830			i915_gem_context_reference(to);
831			if (ring->last_context)
832				i915_gem_context_unreference(ring->last_context);
833			ring->last_context = to;
834		}
835		return 0;
836	}
837
838	return do_switch(ring, to);
839}
840
841static bool contexts_enabled(struct drm_device *dev)
842{
843	return i915.enable_execlists || to_i915(dev)->hw_context_size;
844}
845
846int i915_gem_context_create_ioctl(struct drm_device *dev, void *data,
847				  struct drm_file *file)
848{
849	struct drm_i915_gem_context_create *args = data;
850	struct drm_i915_file_private *file_priv = file->driver_priv;
851	struct intel_context *ctx;
852	int ret;
853
854	if (!contexts_enabled(dev))
855		return -ENODEV;
856
857	ret = i915_mutex_lock_interruptible(dev);
858	if (ret)
859		return ret;
860
861	ctx = i915_gem_create_context(dev, file_priv);
862	mutex_unlock(&dev->struct_mutex);
863	if (IS_ERR(ctx))
864		return PTR_ERR(ctx);
865
866	args->ctx_id = ctx->user_handle;
867	DRM_DEBUG_DRIVER("HW context %d created\n", args->ctx_id);
868
869	return 0;
870}
871
872int i915_gem_context_destroy_ioctl(struct drm_device *dev, void *data,
873				   struct drm_file *file)
874{
875	struct drm_i915_gem_context_destroy *args = data;
876	struct drm_i915_file_private *file_priv = file->driver_priv;
877	struct intel_context *ctx;
878	int ret;
879
880	if (args->ctx_id == DEFAULT_CONTEXT_HANDLE)
881		return -ENOENT;
882
883	ret = i915_mutex_lock_interruptible(dev);
884	if (ret)
885		return ret;
886
887	ctx = i915_gem_context_get(file_priv, args->ctx_id);
888	if (IS_ERR(ctx)) {
889		mutex_unlock(&dev->struct_mutex);
890		return PTR_ERR(ctx);
891	}
892
893	idr_remove(&ctx->file_priv->context_idr, ctx->user_handle);
894	i915_gem_context_unreference(ctx);
895	mutex_unlock(&dev->struct_mutex);
896
897	DRM_DEBUG_DRIVER("HW context %d destroyed\n", args->ctx_id);
898	return 0;
899}
900
901int i915_gem_context_getparam_ioctl(struct drm_device *dev, void *data,
902				    struct drm_file *file)
903{
904	struct drm_i915_file_private *file_priv = file->driver_priv;
905	struct drm_i915_gem_context_param *args = data;
906	struct intel_context *ctx;
907	int ret;
908
909	ret = i915_mutex_lock_interruptible(dev);
910	if (ret)
911		return ret;
912
913	ctx = i915_gem_context_get(file_priv, args->ctx_id);
914	if (IS_ERR(ctx)) {
915		mutex_unlock(&dev->struct_mutex);
916		return PTR_ERR(ctx);
917	}
918
919	args->size = 0;
920	switch (args->param) {
921	case I915_CONTEXT_PARAM_BAN_PERIOD:
922		args->value = ctx->hang_stats.ban_period_seconds;
923		break;
924	default:
925		ret = -EINVAL;
926		break;
927	}
928	mutex_unlock(&dev->struct_mutex);
929
930	return ret;
931}
932
933int i915_gem_context_setparam_ioctl(struct drm_device *dev, void *data,
934				    struct drm_file *file)
935{
936	struct drm_i915_file_private *file_priv = file->driver_priv;
937	struct drm_i915_gem_context_param *args = data;
938	struct intel_context *ctx;
939	int ret;
940
941	ret = i915_mutex_lock_interruptible(dev);
942	if (ret)
943		return ret;
944
945	ctx = i915_gem_context_get(file_priv, args->ctx_id);
946	if (IS_ERR(ctx)) {
947		mutex_unlock(&dev->struct_mutex);
948		return PTR_ERR(ctx);
949	}
950
951	switch (args->param) {
952	case I915_CONTEXT_PARAM_BAN_PERIOD:
953		if (args->size)
954			ret = -EINVAL;
955		else if (args->value < ctx->hang_stats.ban_period_seconds &&
956			 !capable(CAP_SYS_ADMIN))
957			ret = -EPERM;
958		else
959			ctx->hang_stats.ban_period_seconds = args->value;
960		break;
961	default:
962		ret = -EINVAL;
963		break;
964	}
965	mutex_unlock(&dev->struct_mutex);
966
967	return ret;
968}
969