1 /*
2  * Copyright © 2016 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  */
24 
25 #include <drm/drm_print.h>
26 
27 #include "i915_drv.h"
28 
29 #include "intel_engine.h"
30 #include "intel_engine_pm.h"
31 #include "intel_lrc.h"
32 #include "intel_reset.h"
33 
34 /* Haswell does have the CXT_SIZE register however it does not appear to be
35  * valid. Now, docs explain in dwords what is in the context object. The full
36  * size is 70720 bytes, however, the power context and execlist context will
37  * never be saved (power context is stored elsewhere, and execlists don't work
38  * on HSW) - so the final size, including the extra state required for the
39  * Resource Streamer, is 66944 bytes, which rounds to 17 pages.
40  */
41 #define HSW_CXT_TOTAL_SIZE		(17 * PAGE_SIZE)
42 
43 #define DEFAULT_LR_CONTEXT_RENDER_SIZE	(22 * PAGE_SIZE)
44 #define GEN8_LR_CONTEXT_RENDER_SIZE	(20 * PAGE_SIZE)
45 #define GEN9_LR_CONTEXT_RENDER_SIZE	(22 * PAGE_SIZE)
46 #define GEN10_LR_CONTEXT_RENDER_SIZE	(18 * PAGE_SIZE)
47 #define GEN11_LR_CONTEXT_RENDER_SIZE	(14 * PAGE_SIZE)
48 
49 #define GEN8_LR_CONTEXT_OTHER_SIZE	( 2 * PAGE_SIZE)
50 
51 struct engine_class_info {
52 	const char *name;
53 	u8 uabi_class;
54 };
55 
56 static const struct engine_class_info intel_engine_classes[] = {
57 	[RENDER_CLASS] = {
58 		.name = "rcs",
59 		.uabi_class = I915_ENGINE_CLASS_RENDER,
60 	},
61 	[COPY_ENGINE_CLASS] = {
62 		.name = "bcs",
63 		.uabi_class = I915_ENGINE_CLASS_COPY,
64 	},
65 	[VIDEO_DECODE_CLASS] = {
66 		.name = "vcs",
67 		.uabi_class = I915_ENGINE_CLASS_VIDEO,
68 	},
69 	[VIDEO_ENHANCEMENT_CLASS] = {
70 		.name = "vecs",
71 		.uabi_class = I915_ENGINE_CLASS_VIDEO_ENHANCE,
72 	},
73 };
74 
75 #define MAX_MMIO_BASES 3
76 struct engine_info {
77 	unsigned int hw_id;
78 	u8 class;
79 	u8 instance;
80 	/* mmio bases table *must* be sorted in reverse gen order */
81 	struct engine_mmio_base {
82 		u32 gen : 8;
83 		u32 base : 24;
84 	} mmio_bases[MAX_MMIO_BASES];
85 };
86 
87 static const struct engine_info intel_engines[] = {
88 	[RCS0] = {
89 		.hw_id = RCS0_HW,
90 		.class = RENDER_CLASS,
91 		.instance = 0,
92 		.mmio_bases = {
93 			{ .gen = 1, .base = RENDER_RING_BASE }
94 		},
95 	},
96 	[BCS0] = {
97 		.hw_id = BCS0_HW,
98 		.class = COPY_ENGINE_CLASS,
99 		.instance = 0,
100 		.mmio_bases = {
101 			{ .gen = 6, .base = BLT_RING_BASE }
102 		},
103 	},
104 	[VCS0] = {
105 		.hw_id = VCS0_HW,
106 		.class = VIDEO_DECODE_CLASS,
107 		.instance = 0,
108 		.mmio_bases = {
109 			{ .gen = 11, .base = GEN11_BSD_RING_BASE },
110 			{ .gen = 6, .base = GEN6_BSD_RING_BASE },
111 			{ .gen = 4, .base = BSD_RING_BASE }
112 		},
113 	},
114 	[VCS1] = {
115 		.hw_id = VCS1_HW,
116 		.class = VIDEO_DECODE_CLASS,
117 		.instance = 1,
118 		.mmio_bases = {
119 			{ .gen = 11, .base = GEN11_BSD2_RING_BASE },
120 			{ .gen = 8, .base = GEN8_BSD2_RING_BASE }
121 		},
122 	},
123 	[VCS2] = {
124 		.hw_id = VCS2_HW,
125 		.class = VIDEO_DECODE_CLASS,
126 		.instance = 2,
127 		.mmio_bases = {
128 			{ .gen = 11, .base = GEN11_BSD3_RING_BASE }
129 		},
130 	},
131 	[VCS3] = {
132 		.hw_id = VCS3_HW,
133 		.class = VIDEO_DECODE_CLASS,
134 		.instance = 3,
135 		.mmio_bases = {
136 			{ .gen = 11, .base = GEN11_BSD4_RING_BASE }
137 		},
138 	},
139 	[VECS0] = {
140 		.hw_id = VECS0_HW,
141 		.class = VIDEO_ENHANCEMENT_CLASS,
142 		.instance = 0,
143 		.mmio_bases = {
144 			{ .gen = 11, .base = GEN11_VEBOX_RING_BASE },
145 			{ .gen = 7, .base = VEBOX_RING_BASE }
146 		},
147 	},
148 	[VECS1] = {
149 		.hw_id = VECS1_HW,
150 		.class = VIDEO_ENHANCEMENT_CLASS,
151 		.instance = 1,
152 		.mmio_bases = {
153 			{ .gen = 11, .base = GEN11_VEBOX2_RING_BASE }
154 		},
155 	},
156 };
157 
158 /**
159  * ___intel_engine_context_size() - return the size of the context for an engine
160  * @dev_priv: i915 device private
161  * @class: engine class
162  *
163  * Each engine class may require a different amount of space for a context
164  * image.
165  *
166  * Return: size (in bytes) of an engine class specific context image
167  *
168  * Note: this size includes the HWSP, which is part of the context image
169  * in LRC mode, but does not include the "shared data page" used with
170  * GuC submission. The caller should account for this if using the GuC.
171  */
172 static u32
173 __intel_engine_context_size(struct drm_i915_private *dev_priv, u8 class)
174 {
175 	u32 cxt_size;
176 
177 	BUILD_BUG_ON(I915_GTT_PAGE_SIZE != PAGE_SIZE);
178 
179 	switch (class) {
180 	case RENDER_CLASS:
181 		switch (INTEL_GEN(dev_priv)) {
182 		default:
183 			MISSING_CASE(INTEL_GEN(dev_priv));
184 			return DEFAULT_LR_CONTEXT_RENDER_SIZE;
185 		case 11:
186 			return GEN11_LR_CONTEXT_RENDER_SIZE;
187 		case 10:
188 			return GEN10_LR_CONTEXT_RENDER_SIZE;
189 		case 9:
190 			return GEN9_LR_CONTEXT_RENDER_SIZE;
191 		case 8:
192 			return GEN8_LR_CONTEXT_RENDER_SIZE;
193 		case 7:
194 			if (IS_HASWELL(dev_priv))
195 				return HSW_CXT_TOTAL_SIZE;
196 
197 			cxt_size = I915_READ(GEN7_CXT_SIZE);
198 			return round_up(GEN7_CXT_TOTAL_SIZE(cxt_size) * 64,
199 					PAGE_SIZE);
200 		case 6:
201 			cxt_size = I915_READ(CXT_SIZE);
202 			return round_up(GEN6_CXT_TOTAL_SIZE(cxt_size) * 64,
203 					PAGE_SIZE);
204 		case 5:
205 		case 4:
206 			/*
207 			 * There is a discrepancy here between the size reported
208 			 * by the register and the size of the context layout
209 			 * in the docs. Both are described as authorative!
210 			 *
211 			 * The discrepancy is on the order of a few cachelines,
212 			 * but the total is under one page (4k), which is our
213 			 * minimum allocation anyway so it should all come
214 			 * out in the wash.
215 			 */
216 			cxt_size = I915_READ(CXT_SIZE) + 1;
217 			DRM_DEBUG_DRIVER("gen%d CXT_SIZE = %d bytes [0x%08x]\n",
218 					 INTEL_GEN(dev_priv),
219 					 cxt_size * 64,
220 					 cxt_size - 1);
221 			return round_up(cxt_size * 64, PAGE_SIZE);
222 		case 3:
223 		case 2:
224 		/* For the special day when i810 gets merged. */
225 		case 1:
226 			return 0;
227 		}
228 		break;
229 	default:
230 		MISSING_CASE(class);
231 		/* fall through */
232 	case VIDEO_DECODE_CLASS:
233 	case VIDEO_ENHANCEMENT_CLASS:
234 	case COPY_ENGINE_CLASS:
235 		if (INTEL_GEN(dev_priv) < 8)
236 			return 0;
237 		return GEN8_LR_CONTEXT_OTHER_SIZE;
238 	}
239 }
240 
241 static u32 __engine_mmio_base(struct drm_i915_private *i915,
242 			      const struct engine_mmio_base *bases)
243 {
244 	int i;
245 
246 	for (i = 0; i < MAX_MMIO_BASES; i++)
247 		if (INTEL_GEN(i915) >= bases[i].gen)
248 			break;
249 
250 	GEM_BUG_ON(i == MAX_MMIO_BASES);
251 	GEM_BUG_ON(!bases[i].base);
252 
253 	return bases[i].base;
254 }
255 
256 static void __sprint_engine_name(char *name, const struct engine_info *info)
257 {
258 	WARN_ON(snprintf(name, INTEL_ENGINE_CS_MAX_NAME, "%s%u",
259 			 intel_engine_classes[info->class].name,
260 			 info->instance) >= INTEL_ENGINE_CS_MAX_NAME);
261 }
262 
263 void intel_engine_set_hwsp_writemask(struct intel_engine_cs *engine, u32 mask)
264 {
265 	/*
266 	 * Though they added more rings on g4x/ilk, they did not add
267 	 * per-engine HWSTAM until gen6.
268 	 */
269 	if (INTEL_GEN(engine->i915) < 6 && engine->class != RENDER_CLASS)
270 		return;
271 
272 	if (INTEL_GEN(engine->i915) >= 3)
273 		ENGINE_WRITE(engine, RING_HWSTAM, mask);
274 	else
275 		ENGINE_WRITE16(engine, RING_HWSTAM, mask);
276 }
277 
278 static void intel_engine_sanitize_mmio(struct intel_engine_cs *engine)
279 {
280 	/* Mask off all writes into the unknown HWSP */
281 	intel_engine_set_hwsp_writemask(engine, ~0u);
282 }
283 
284 static int
285 intel_engine_setup(struct drm_i915_private *dev_priv,
286 		   enum intel_engine_id id)
287 {
288 	const struct engine_info *info = &intel_engines[id];
289 	struct intel_engine_cs *engine;
290 
291 	GEM_BUG_ON(info->class >= ARRAY_SIZE(intel_engine_classes));
292 
293 	BUILD_BUG_ON(MAX_ENGINE_CLASS >= BIT(GEN11_ENGINE_CLASS_WIDTH));
294 	BUILD_BUG_ON(MAX_ENGINE_INSTANCE >= BIT(GEN11_ENGINE_INSTANCE_WIDTH));
295 
296 	if (GEM_DEBUG_WARN_ON(info->class > MAX_ENGINE_CLASS))
297 		return -EINVAL;
298 
299 	if (GEM_DEBUG_WARN_ON(info->instance > MAX_ENGINE_INSTANCE))
300 		return -EINVAL;
301 
302 	if (GEM_DEBUG_WARN_ON(dev_priv->engine_class[info->class][info->instance]))
303 		return -EINVAL;
304 
305 	GEM_BUG_ON(dev_priv->engine[id]);
306 	engine = kzalloc(sizeof(*engine), GFP_KERNEL);
307 	if (!engine)
308 		return -ENOMEM;
309 
310 	BUILD_BUG_ON(BITS_PER_TYPE(engine->mask) < I915_NUM_ENGINES);
311 
312 	engine->id = id;
313 	engine->mask = BIT(id);
314 	engine->i915 = dev_priv;
315 	engine->uncore = &dev_priv->uncore;
316 	__sprint_engine_name(engine->name, info);
317 	engine->hw_id = engine->guc_id = info->hw_id;
318 	engine->mmio_base = __engine_mmio_base(dev_priv, info->mmio_bases);
319 	engine->class = info->class;
320 	engine->instance = info->instance;
321 
322 	/*
323 	 * To be overridden by the backend on setup. However to facilitate
324 	 * cleanup on error during setup, we always provide the destroy vfunc.
325 	 */
326 	engine->destroy = (typeof(engine->destroy))kfree;
327 
328 	engine->uabi_class = intel_engine_classes[info->class].uabi_class;
329 
330 	engine->context_size = __intel_engine_context_size(dev_priv,
331 							   engine->class);
332 	if (WARN_ON(engine->context_size > BIT(20)))
333 		engine->context_size = 0;
334 	if (engine->context_size)
335 		DRIVER_CAPS(dev_priv)->has_logical_contexts = true;
336 
337 	/* Nothing to do here, execute in order of dependencies */
338 	engine->schedule = NULL;
339 
340 	seqlock_init(&engine->stats.lock);
341 
342 	ATOMIC_INIT_NOTIFIER_HEAD(&engine->context_status_notifier);
343 
344 	/* Scrub mmio state on takeover */
345 	intel_engine_sanitize_mmio(engine);
346 
347 	dev_priv->engine_class[info->class][info->instance] = engine;
348 	dev_priv->engine[id] = engine;
349 	return 0;
350 }
351 
352 static void __setup_engine_capabilities(struct intel_engine_cs *engine)
353 {
354 	struct drm_i915_private *i915 = engine->i915;
355 
356 	if (engine->class == VIDEO_DECODE_CLASS) {
357 		/*
358 		 * HEVC support is present on first engine instance
359 		 * before Gen11 and on all instances afterwards.
360 		 */
361 		if (INTEL_GEN(i915) >= 11 ||
362 		    (INTEL_GEN(i915) >= 9 && engine->instance == 0))
363 			engine->uabi_capabilities |=
364 				I915_VIDEO_CLASS_CAPABILITY_HEVC;
365 
366 		/*
367 		 * SFC block is present only on even logical engine
368 		 * instances.
369 		 */
370 		if ((INTEL_GEN(i915) >= 11 &&
371 		     RUNTIME_INFO(i915)->vdbox_sfc_access & engine->mask) ||
372 		    (INTEL_GEN(i915) >= 9 && engine->instance == 0))
373 			engine->uabi_capabilities |=
374 				I915_VIDEO_AND_ENHANCE_CLASS_CAPABILITY_SFC;
375 	} else if (engine->class == VIDEO_ENHANCEMENT_CLASS) {
376 		if (INTEL_GEN(i915) >= 9)
377 			engine->uabi_capabilities |=
378 				I915_VIDEO_AND_ENHANCE_CLASS_CAPABILITY_SFC;
379 	}
380 }
381 
382 static void intel_setup_engine_capabilities(struct drm_i915_private *i915)
383 {
384 	struct intel_engine_cs *engine;
385 	enum intel_engine_id id;
386 
387 	for_each_engine(engine, i915, id)
388 		__setup_engine_capabilities(engine);
389 }
390 
391 /**
392  * intel_engines_cleanup() - free the resources allocated for Command Streamers
393  * @i915: the i915 devic
394  */
395 void intel_engines_cleanup(struct drm_i915_private *i915)
396 {
397 	struct intel_engine_cs *engine;
398 	enum intel_engine_id id;
399 
400 	for_each_engine(engine, i915, id) {
401 		engine->destroy(engine);
402 		i915->engine[id] = NULL;
403 	}
404 }
405 
406 /**
407  * intel_engines_init_mmio() - allocate and prepare the Engine Command Streamers
408  * @i915: the i915 device
409  *
410  * Return: non-zero if the initialization failed.
411  */
412 int intel_engines_init_mmio(struct drm_i915_private *i915)
413 {
414 	struct intel_device_info *device_info = mkwrite_device_info(i915);
415 	const unsigned int engine_mask = INTEL_INFO(i915)->engine_mask;
416 	unsigned int mask = 0;
417 	unsigned int i;
418 	int err;
419 
420 	WARN_ON(engine_mask == 0);
421 	WARN_ON(engine_mask &
422 		GENMASK(BITS_PER_TYPE(mask) - 1, I915_NUM_ENGINES));
423 
424 	if (i915_inject_load_failure())
425 		return -ENODEV;
426 
427 	for (i = 0; i < ARRAY_SIZE(intel_engines); i++) {
428 		if (!HAS_ENGINE(i915, i))
429 			continue;
430 
431 		err = intel_engine_setup(i915, i);
432 		if (err)
433 			goto cleanup;
434 
435 		mask |= BIT(i);
436 	}
437 
438 	/*
439 	 * Catch failures to update intel_engines table when the new engines
440 	 * are added to the driver by a warning and disabling the forgotten
441 	 * engines.
442 	 */
443 	if (WARN_ON(mask != engine_mask))
444 		device_info->engine_mask = mask;
445 
446 	/* We always presume we have at least RCS available for later probing */
447 	if (WARN_ON(!HAS_ENGINE(i915, RCS0))) {
448 		err = -ENODEV;
449 		goto cleanup;
450 	}
451 
452 	RUNTIME_INFO(i915)->num_engines = hweight32(mask);
453 
454 	i915_check_and_clear_faults(i915);
455 
456 	intel_setup_engine_capabilities(i915);
457 
458 	return 0;
459 
460 cleanup:
461 	intel_engines_cleanup(i915);
462 	return err;
463 }
464 
465 /**
466  * intel_engines_init() - init the Engine Command Streamers
467  * @i915: i915 device private
468  *
469  * Return: non-zero if the initialization failed.
470  */
471 int intel_engines_init(struct drm_i915_private *i915)
472 {
473 	int (*init)(struct intel_engine_cs *engine);
474 	struct intel_engine_cs *engine;
475 	enum intel_engine_id id;
476 	int err;
477 
478 	if (HAS_EXECLISTS(i915))
479 		init = intel_execlists_submission_init;
480 	else
481 		init = intel_ring_submission_init;
482 
483 	for_each_engine(engine, i915, id) {
484 		err = init(engine);
485 		if (err)
486 			goto cleanup;
487 	}
488 
489 	return 0;
490 
491 cleanup:
492 	intel_engines_cleanup(i915);
493 	return err;
494 }
495 
496 static void intel_engine_init_batch_pool(struct intel_engine_cs *engine)
497 {
498 	i915_gem_batch_pool_init(&engine->batch_pool, engine);
499 }
500 
501 void intel_engine_init_execlists(struct intel_engine_cs *engine)
502 {
503 	struct intel_engine_execlists * const execlists = &engine->execlists;
504 
505 	execlists->port_mask = 1;
506 	GEM_BUG_ON(!is_power_of_2(execlists_num_ports(execlists)));
507 	GEM_BUG_ON(execlists_num_ports(execlists) > EXECLIST_MAX_PORTS);
508 
509 	execlists->queue_priority_hint = INT_MIN;
510 	execlists->queue = RB_ROOT_CACHED;
511 }
512 
513 static void cleanup_status_page(struct intel_engine_cs *engine)
514 {
515 	struct i915_vma *vma;
516 
517 	/* Prevent writes into HWSP after returning the page to the system */
518 	intel_engine_set_hwsp_writemask(engine, ~0u);
519 
520 	vma = fetch_and_zero(&engine->status_page.vma);
521 	if (!vma)
522 		return;
523 
524 	if (!HWS_NEEDS_PHYSICAL(engine->i915))
525 		i915_vma_unpin(vma);
526 
527 	i915_gem_object_unpin_map(vma->obj);
528 	__i915_gem_object_release_unless_active(vma->obj);
529 }
530 
531 static int pin_ggtt_status_page(struct intel_engine_cs *engine,
532 				struct i915_vma *vma)
533 {
534 	unsigned int flags;
535 
536 	flags = PIN_GLOBAL;
537 	if (!HAS_LLC(engine->i915))
538 		/*
539 		 * On g33, we cannot place HWS above 256MiB, so
540 		 * restrict its pinning to the low mappable arena.
541 		 * Though this restriction is not documented for
542 		 * gen4, gen5, or byt, they also behave similarly
543 		 * and hang if the HWS is placed at the top of the
544 		 * GTT. To generalise, it appears that all !llc
545 		 * platforms have issues with us placing the HWS
546 		 * above the mappable region (even though we never
547 		 * actually map it).
548 		 */
549 		flags |= PIN_MAPPABLE;
550 	else
551 		flags |= PIN_HIGH;
552 
553 	return i915_vma_pin(vma, 0, 0, flags);
554 }
555 
556 static int init_status_page(struct intel_engine_cs *engine)
557 {
558 	struct drm_i915_gem_object *obj;
559 	struct i915_vma *vma;
560 	void *vaddr;
561 	int ret;
562 
563 	/*
564 	 * Though the HWS register does support 36bit addresses, historically
565 	 * we have had hangs and corruption reported due to wild writes if
566 	 * the HWS is placed above 4G. We only allow objects to be allocated
567 	 * in GFP_DMA32 for i965, and no earlier physical address users had
568 	 * access to more than 4G.
569 	 */
570 	obj = i915_gem_object_create_internal(engine->i915, PAGE_SIZE);
571 	if (IS_ERR(obj)) {
572 		DRM_ERROR("Failed to allocate status page\n");
573 		return PTR_ERR(obj);
574 	}
575 
576 	i915_gem_object_set_cache_coherency(obj, I915_CACHE_LLC);
577 
578 	vma = i915_vma_instance(obj, &engine->i915->ggtt.vm, NULL);
579 	if (IS_ERR(vma)) {
580 		ret = PTR_ERR(vma);
581 		goto err;
582 	}
583 
584 	vaddr = i915_gem_object_pin_map(obj, I915_MAP_WB);
585 	if (IS_ERR(vaddr)) {
586 		ret = PTR_ERR(vaddr);
587 		goto err;
588 	}
589 
590 	engine->status_page.addr = memset(vaddr, 0, PAGE_SIZE);
591 	engine->status_page.vma = vma;
592 
593 	if (!HWS_NEEDS_PHYSICAL(engine->i915)) {
594 		ret = pin_ggtt_status_page(engine, vma);
595 		if (ret)
596 			goto err_unpin;
597 	}
598 
599 	return 0;
600 
601 err_unpin:
602 	i915_gem_object_unpin_map(obj);
603 err:
604 	i915_gem_object_put(obj);
605 	return ret;
606 }
607 
608 static int intel_engine_setup_common(struct intel_engine_cs *engine)
609 {
610 	int err;
611 
612 	err = init_status_page(engine);
613 	if (err)
614 		return err;
615 
616 	err = i915_timeline_init(engine->i915,
617 				 &engine->timeline,
618 				 engine->status_page.vma);
619 	if (err)
620 		goto err_hwsp;
621 
622 	i915_timeline_set_subclass(&engine->timeline, TIMELINE_ENGINE);
623 
624 	intel_engine_init_breadcrumbs(engine);
625 	intel_engine_init_execlists(engine);
626 	intel_engine_init_hangcheck(engine);
627 	intel_engine_init_batch_pool(engine);
628 	intel_engine_init_cmd_parser(engine);
629 	intel_engine_init__pm(engine);
630 
631 	/* Use the whole device by default */
632 	engine->sseu =
633 		intel_sseu_from_device_info(&RUNTIME_INFO(engine->i915)->sseu);
634 
635 	return 0;
636 
637 err_hwsp:
638 	cleanup_status_page(engine);
639 	return err;
640 }
641 
642 /**
643  * intel_engines_setup- setup engine state not requiring hw access
644  * @i915: Device to setup.
645  *
646  * Initializes engine structure members shared between legacy and execlists
647  * submission modes which do not require hardware access.
648  *
649  * Typically done early in the submission mode specific engine setup stage.
650  */
651 int intel_engines_setup(struct drm_i915_private *i915)
652 {
653 	int (*setup)(struct intel_engine_cs *engine);
654 	struct intel_engine_cs *engine;
655 	enum intel_engine_id id;
656 	int err;
657 
658 	if (HAS_EXECLISTS(i915))
659 		setup = intel_execlists_submission_setup;
660 	else
661 		setup = intel_ring_submission_setup;
662 
663 	for_each_engine(engine, i915, id) {
664 		err = intel_engine_setup_common(engine);
665 		if (err)
666 			goto cleanup;
667 
668 		err = setup(engine);
669 		if (err)
670 			goto cleanup;
671 
672 		/* We expect the backend to take control over its state */
673 		GEM_BUG_ON(engine->destroy == (typeof(engine->destroy))kfree);
674 
675 		GEM_BUG_ON(!engine->cops);
676 	}
677 
678 	return 0;
679 
680 cleanup:
681 	intel_engines_cleanup(i915);
682 	return err;
683 }
684 
685 void intel_engines_set_scheduler_caps(struct drm_i915_private *i915)
686 {
687 	static const struct {
688 		u8 engine;
689 		u8 sched;
690 	} map[] = {
691 #define MAP(x, y) { ilog2(I915_ENGINE_HAS_##x), ilog2(I915_SCHEDULER_CAP_##y) }
692 		MAP(PREEMPTION, PREEMPTION),
693 		MAP(SEMAPHORES, SEMAPHORES),
694 #undef MAP
695 	};
696 	struct intel_engine_cs *engine;
697 	enum intel_engine_id id;
698 	u32 enabled, disabled;
699 
700 	enabled = 0;
701 	disabled = 0;
702 	for_each_engine(engine, i915, id) { /* all engines must agree! */
703 		int i;
704 
705 		if (engine->schedule)
706 			enabled |= (I915_SCHEDULER_CAP_ENABLED |
707 				    I915_SCHEDULER_CAP_PRIORITY);
708 		else
709 			disabled |= (I915_SCHEDULER_CAP_ENABLED |
710 				     I915_SCHEDULER_CAP_PRIORITY);
711 
712 		for (i = 0; i < ARRAY_SIZE(map); i++) {
713 			if (engine->flags & BIT(map[i].engine))
714 				enabled |= BIT(map[i].sched);
715 			else
716 				disabled |= BIT(map[i].sched);
717 		}
718 	}
719 
720 	i915->caps.scheduler = enabled & ~disabled;
721 	if (!(i915->caps.scheduler & I915_SCHEDULER_CAP_ENABLED))
722 		i915->caps.scheduler = 0;
723 }
724 
725 struct measure_breadcrumb {
726 	struct i915_request rq;
727 	struct i915_timeline timeline;
728 	struct intel_ring ring;
729 	u32 cs[1024];
730 };
731 
732 static int measure_breadcrumb_dw(struct intel_engine_cs *engine)
733 {
734 	struct measure_breadcrumb *frame;
735 	int dw = -ENOMEM;
736 
737 	GEM_BUG_ON(!engine->i915->gt.scratch);
738 
739 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
740 	if (!frame)
741 		return -ENOMEM;
742 
743 	if (i915_timeline_init(engine->i915,
744 			       &frame->timeline,
745 			       engine->status_page.vma))
746 		goto out_frame;
747 
748 	INIT_LIST_HEAD(&frame->ring.request_list);
749 	frame->ring.timeline = &frame->timeline;
750 	frame->ring.vaddr = frame->cs;
751 	frame->ring.size = sizeof(frame->cs);
752 	frame->ring.effective_size = frame->ring.size;
753 	intel_ring_update_space(&frame->ring);
754 
755 	frame->rq.i915 = engine->i915;
756 	frame->rq.engine = engine;
757 	frame->rq.ring = &frame->ring;
758 	frame->rq.timeline = &frame->timeline;
759 
760 	dw = i915_timeline_pin(&frame->timeline);
761 	if (dw < 0)
762 		goto out_timeline;
763 
764 	dw = engine->emit_fini_breadcrumb(&frame->rq, frame->cs) - frame->cs;
765 	GEM_BUG_ON(dw & 1); /* RING_TAIL must be qword aligned */
766 
767 	i915_timeline_unpin(&frame->timeline);
768 
769 out_timeline:
770 	i915_timeline_fini(&frame->timeline);
771 out_frame:
772 	kfree(frame);
773 	return dw;
774 }
775 
776 static int pin_context(struct i915_gem_context *ctx,
777 		       struct intel_engine_cs *engine,
778 		       struct intel_context **out)
779 {
780 	struct intel_context *ce;
781 	int err;
782 
783 	ce = i915_gem_context_get_engine(ctx, engine->id);
784 	if (IS_ERR(ce))
785 		return PTR_ERR(ce);
786 
787 	err = intel_context_pin(ce);
788 	intel_context_put(ce);
789 	if (err)
790 		return err;
791 
792 	*out = ce;
793 	return 0;
794 }
795 
796 /**
797  * intel_engines_init_common - initialize cengine state which might require hw access
798  * @engine: Engine to initialize.
799  *
800  * Initializes @engine@ structure members shared between legacy and execlists
801  * submission modes which do require hardware access.
802  *
803  * Typcally done at later stages of submission mode specific engine setup.
804  *
805  * Returns zero on success or an error code on failure.
806  */
807 int intel_engine_init_common(struct intel_engine_cs *engine)
808 {
809 	struct drm_i915_private *i915 = engine->i915;
810 	int ret;
811 
812 	/* We may need to do things with the shrinker which
813 	 * require us to immediately switch back to the default
814 	 * context. This can cause a problem as pinning the
815 	 * default context also requires GTT space which may not
816 	 * be available. To avoid this we always pin the default
817 	 * context.
818 	 */
819 	ret = pin_context(i915->kernel_context, engine,
820 			  &engine->kernel_context);
821 	if (ret)
822 		return ret;
823 
824 	/*
825 	 * Similarly the preempt context must always be available so that
826 	 * we can interrupt the engine at any time. However, as preemption
827 	 * is optional, we allow it to fail.
828 	 */
829 	if (i915->preempt_context)
830 		pin_context(i915->preempt_context, engine,
831 			    &engine->preempt_context);
832 
833 	ret = measure_breadcrumb_dw(engine);
834 	if (ret < 0)
835 		goto err_unpin;
836 
837 	engine->emit_fini_breadcrumb_dw = ret;
838 
839 	engine->set_default_submission(engine);
840 
841 	return 0;
842 
843 err_unpin:
844 	if (engine->preempt_context)
845 		intel_context_unpin(engine->preempt_context);
846 	intel_context_unpin(engine->kernel_context);
847 	return ret;
848 }
849 
850 /**
851  * intel_engines_cleanup_common - cleans up the engine state created by
852  *                                the common initiailizers.
853  * @engine: Engine to cleanup.
854  *
855  * This cleans up everything created by the common helpers.
856  */
857 void intel_engine_cleanup_common(struct intel_engine_cs *engine)
858 {
859 	cleanup_status_page(engine);
860 
861 	intel_engine_fini_breadcrumbs(engine);
862 	intel_engine_cleanup_cmd_parser(engine);
863 	i915_gem_batch_pool_fini(&engine->batch_pool);
864 
865 	if (engine->default_state)
866 		i915_gem_object_put(engine->default_state);
867 
868 	if (engine->preempt_context)
869 		intel_context_unpin(engine->preempt_context);
870 	intel_context_unpin(engine->kernel_context);
871 
872 	i915_timeline_fini(&engine->timeline);
873 
874 	intel_wa_list_free(&engine->ctx_wa_list);
875 	intel_wa_list_free(&engine->wa_list);
876 	intel_wa_list_free(&engine->whitelist);
877 }
878 
879 u64 intel_engine_get_active_head(const struct intel_engine_cs *engine)
880 {
881 	struct drm_i915_private *i915 = engine->i915;
882 
883 	u64 acthd;
884 
885 	if (INTEL_GEN(i915) >= 8)
886 		acthd = ENGINE_READ64(engine, RING_ACTHD, RING_ACTHD_UDW);
887 	else if (INTEL_GEN(i915) >= 4)
888 		acthd = ENGINE_READ(engine, RING_ACTHD);
889 	else
890 		acthd = ENGINE_READ(engine, ACTHD);
891 
892 	return acthd;
893 }
894 
895 u64 intel_engine_get_last_batch_head(const struct intel_engine_cs *engine)
896 {
897 	u64 bbaddr;
898 
899 	if (INTEL_GEN(engine->i915) >= 8)
900 		bbaddr = ENGINE_READ64(engine, RING_BBADDR, RING_BBADDR_UDW);
901 	else
902 		bbaddr = ENGINE_READ(engine, RING_BBADDR);
903 
904 	return bbaddr;
905 }
906 
907 int intel_engine_stop_cs(struct intel_engine_cs *engine)
908 {
909 	struct intel_uncore *uncore = engine->uncore;
910 	const u32 base = engine->mmio_base;
911 	const i915_reg_t mode = RING_MI_MODE(base);
912 	int err;
913 
914 	if (INTEL_GEN(engine->i915) < 3)
915 		return -ENODEV;
916 
917 	GEM_TRACE("%s\n", engine->name);
918 
919 	intel_uncore_write_fw(uncore, mode, _MASKED_BIT_ENABLE(STOP_RING));
920 
921 	err = 0;
922 	if (__intel_wait_for_register_fw(uncore,
923 					 mode, MODE_IDLE, MODE_IDLE,
924 					 1000, 0,
925 					 NULL)) {
926 		GEM_TRACE("%s: timed out on STOP_RING -> IDLE\n", engine->name);
927 		err = -ETIMEDOUT;
928 	}
929 
930 	/* A final mmio read to let GPU writes be hopefully flushed to memory */
931 	intel_uncore_posting_read_fw(uncore, mode);
932 
933 	return err;
934 }
935 
936 void intel_engine_cancel_stop_cs(struct intel_engine_cs *engine)
937 {
938 	GEM_TRACE("%s\n", engine->name);
939 
940 	ENGINE_WRITE_FW(engine, RING_MI_MODE, _MASKED_BIT_DISABLE(STOP_RING));
941 }
942 
943 const char *i915_cache_level_str(struct drm_i915_private *i915, int type)
944 {
945 	switch (type) {
946 	case I915_CACHE_NONE: return " uncached";
947 	case I915_CACHE_LLC: return HAS_LLC(i915) ? " LLC" : " snooped";
948 	case I915_CACHE_L3_LLC: return " L3+LLC";
949 	case I915_CACHE_WT: return " WT";
950 	default: return "";
951 	}
952 }
953 
954 u32 intel_calculate_mcr_s_ss_select(struct drm_i915_private *dev_priv)
955 {
956 	const struct sseu_dev_info *sseu = &RUNTIME_INFO(dev_priv)->sseu;
957 	u32 mcr_s_ss_select;
958 	u32 slice = fls(sseu->slice_mask);
959 	u32 subslice = fls(sseu->subslice_mask[slice]);
960 
961 	if (IS_GEN(dev_priv, 10))
962 		mcr_s_ss_select = GEN8_MCR_SLICE(slice) |
963 				  GEN8_MCR_SUBSLICE(subslice);
964 	else if (INTEL_GEN(dev_priv) >= 11)
965 		mcr_s_ss_select = GEN11_MCR_SLICE(slice) |
966 				  GEN11_MCR_SUBSLICE(subslice);
967 	else
968 		mcr_s_ss_select = 0;
969 
970 	return mcr_s_ss_select;
971 }
972 
973 static inline u32
974 read_subslice_reg(struct drm_i915_private *dev_priv, int slice,
975 		  int subslice, i915_reg_t reg)
976 {
977 	struct intel_uncore *uncore = &dev_priv->uncore;
978 	u32 mcr_slice_subslice_mask;
979 	u32 mcr_slice_subslice_select;
980 	u32 default_mcr_s_ss_select;
981 	u32 mcr;
982 	u32 ret;
983 	enum forcewake_domains fw_domains;
984 
985 	if (INTEL_GEN(dev_priv) >= 11) {
986 		mcr_slice_subslice_mask = GEN11_MCR_SLICE_MASK |
987 					  GEN11_MCR_SUBSLICE_MASK;
988 		mcr_slice_subslice_select = GEN11_MCR_SLICE(slice) |
989 					    GEN11_MCR_SUBSLICE(subslice);
990 	} else {
991 		mcr_slice_subslice_mask = GEN8_MCR_SLICE_MASK |
992 					  GEN8_MCR_SUBSLICE_MASK;
993 		mcr_slice_subslice_select = GEN8_MCR_SLICE(slice) |
994 					    GEN8_MCR_SUBSLICE(subslice);
995 	}
996 
997 	default_mcr_s_ss_select = intel_calculate_mcr_s_ss_select(dev_priv);
998 
999 	fw_domains = intel_uncore_forcewake_for_reg(uncore, reg,
1000 						    FW_REG_READ);
1001 	fw_domains |= intel_uncore_forcewake_for_reg(uncore,
1002 						     GEN8_MCR_SELECTOR,
1003 						     FW_REG_READ | FW_REG_WRITE);
1004 
1005 	spin_lock_irq(&uncore->lock);
1006 	intel_uncore_forcewake_get__locked(uncore, fw_domains);
1007 
1008 	mcr = intel_uncore_read_fw(uncore, GEN8_MCR_SELECTOR);
1009 
1010 	WARN_ON_ONCE((mcr & mcr_slice_subslice_mask) !=
1011 		     default_mcr_s_ss_select);
1012 
1013 	mcr &= ~mcr_slice_subslice_mask;
1014 	mcr |= mcr_slice_subslice_select;
1015 	intel_uncore_write_fw(uncore, GEN8_MCR_SELECTOR, mcr);
1016 
1017 	ret = intel_uncore_read_fw(uncore, reg);
1018 
1019 	mcr &= ~mcr_slice_subslice_mask;
1020 	mcr |= default_mcr_s_ss_select;
1021 
1022 	intel_uncore_write_fw(uncore, GEN8_MCR_SELECTOR, mcr);
1023 
1024 	intel_uncore_forcewake_put__locked(uncore, fw_domains);
1025 	spin_unlock_irq(&uncore->lock);
1026 
1027 	return ret;
1028 }
1029 
1030 /* NB: please notice the memset */
1031 void intel_engine_get_instdone(struct intel_engine_cs *engine,
1032 			       struct intel_instdone *instdone)
1033 {
1034 	struct drm_i915_private *dev_priv = engine->i915;
1035 	struct intel_uncore *uncore = engine->uncore;
1036 	u32 mmio_base = engine->mmio_base;
1037 	int slice;
1038 	int subslice;
1039 
1040 	memset(instdone, 0, sizeof(*instdone));
1041 
1042 	switch (INTEL_GEN(dev_priv)) {
1043 	default:
1044 		instdone->instdone =
1045 			intel_uncore_read(uncore, RING_INSTDONE(mmio_base));
1046 
1047 		if (engine->id != RCS0)
1048 			break;
1049 
1050 		instdone->slice_common =
1051 			intel_uncore_read(uncore, GEN7_SC_INSTDONE);
1052 		for_each_instdone_slice_subslice(dev_priv, slice, subslice) {
1053 			instdone->sampler[slice][subslice] =
1054 				read_subslice_reg(dev_priv, slice, subslice,
1055 						  GEN7_SAMPLER_INSTDONE);
1056 			instdone->row[slice][subslice] =
1057 				read_subslice_reg(dev_priv, slice, subslice,
1058 						  GEN7_ROW_INSTDONE);
1059 		}
1060 		break;
1061 	case 7:
1062 		instdone->instdone =
1063 			intel_uncore_read(uncore, RING_INSTDONE(mmio_base));
1064 
1065 		if (engine->id != RCS0)
1066 			break;
1067 
1068 		instdone->slice_common =
1069 			intel_uncore_read(uncore, GEN7_SC_INSTDONE);
1070 		instdone->sampler[0][0] =
1071 			intel_uncore_read(uncore, GEN7_SAMPLER_INSTDONE);
1072 		instdone->row[0][0] =
1073 			intel_uncore_read(uncore, GEN7_ROW_INSTDONE);
1074 
1075 		break;
1076 	case 6:
1077 	case 5:
1078 	case 4:
1079 		instdone->instdone =
1080 			intel_uncore_read(uncore, RING_INSTDONE(mmio_base));
1081 		if (engine->id == RCS0)
1082 			/* HACK: Using the wrong struct member */
1083 			instdone->slice_common =
1084 				intel_uncore_read(uncore, GEN4_INSTDONE1);
1085 		break;
1086 	case 3:
1087 	case 2:
1088 		instdone->instdone = intel_uncore_read(uncore, GEN2_INSTDONE);
1089 		break;
1090 	}
1091 }
1092 
1093 static bool ring_is_idle(struct intel_engine_cs *engine)
1094 {
1095 	struct drm_i915_private *dev_priv = engine->i915;
1096 	intel_wakeref_t wakeref;
1097 	bool idle = true;
1098 
1099 	if (I915_SELFTEST_ONLY(!engine->mmio_base))
1100 		return true;
1101 
1102 	/* If the whole device is asleep, the engine must be idle */
1103 	wakeref = intel_runtime_pm_get_if_in_use(dev_priv);
1104 	if (!wakeref)
1105 		return true;
1106 
1107 	/* First check that no commands are left in the ring */
1108 	if ((ENGINE_READ(engine, RING_HEAD) & HEAD_ADDR) !=
1109 	    (ENGINE_READ(engine, RING_TAIL) & TAIL_ADDR))
1110 		idle = false;
1111 
1112 	/* No bit for gen2, so assume the CS parser is idle */
1113 	if (INTEL_GEN(dev_priv) > 2 &&
1114 	    !(ENGINE_READ(engine, RING_MI_MODE) & MODE_IDLE))
1115 		idle = false;
1116 
1117 	intel_runtime_pm_put(dev_priv, wakeref);
1118 
1119 	return idle;
1120 }
1121 
1122 /**
1123  * intel_engine_is_idle() - Report if the engine has finished process all work
1124  * @engine: the intel_engine_cs
1125  *
1126  * Return true if there are no requests pending, nothing left to be submitted
1127  * to hardware, and that the engine is idle.
1128  */
1129 bool intel_engine_is_idle(struct intel_engine_cs *engine)
1130 {
1131 	/* More white lies, if wedged, hw state is inconsistent */
1132 	if (i915_reset_failed(engine->i915))
1133 		return true;
1134 
1135 	if (!intel_wakeref_active(&engine->wakeref))
1136 		return true;
1137 
1138 	/* Waiting to drain ELSP? */
1139 	if (READ_ONCE(engine->execlists.active)) {
1140 		struct tasklet_struct *t = &engine->execlists.tasklet;
1141 
1142 		synchronize_hardirq(engine->i915->drm.irq);
1143 
1144 		local_bh_disable();
1145 		if (tasklet_trylock(t)) {
1146 			/* Must wait for any GPU reset in progress. */
1147 			if (__tasklet_is_enabled(t))
1148 				t->func(t->data);
1149 			tasklet_unlock(t);
1150 		}
1151 		local_bh_enable();
1152 
1153 		/* Otherwise flush the tasklet if it was on another cpu */
1154 		tasklet_unlock_wait(t);
1155 
1156 		if (READ_ONCE(engine->execlists.active))
1157 			return false;
1158 	}
1159 
1160 	/* ELSP is empty, but there are ready requests? E.g. after reset */
1161 	if (!RB_EMPTY_ROOT(&engine->execlists.queue.rb_root))
1162 		return false;
1163 
1164 	/* Ring stopped? */
1165 	return ring_is_idle(engine);
1166 }
1167 
1168 bool intel_engines_are_idle(struct drm_i915_private *i915)
1169 {
1170 	struct intel_engine_cs *engine;
1171 	enum intel_engine_id id;
1172 
1173 	/*
1174 	 * If the driver is wedged, HW state may be very inconsistent and
1175 	 * report that it is still busy, even though we have stopped using it.
1176 	 */
1177 	if (i915_reset_failed(i915))
1178 		return true;
1179 
1180 	/* Already parked (and passed an idleness test); must still be idle */
1181 	if (!READ_ONCE(i915->gt.awake))
1182 		return true;
1183 
1184 	for_each_engine(engine, i915, id) {
1185 		if (!intel_engine_is_idle(engine))
1186 			return false;
1187 	}
1188 
1189 	return true;
1190 }
1191 
1192 void intel_engines_reset_default_submission(struct drm_i915_private *i915)
1193 {
1194 	struct intel_engine_cs *engine;
1195 	enum intel_engine_id id;
1196 
1197 	for_each_engine(engine, i915, id)
1198 		engine->set_default_submission(engine);
1199 }
1200 
1201 /**
1202  * intel_engine_lost_context: called when the GPU is reset into unknown state
1203  * @engine: the engine
1204  *
1205  * We have either reset the GPU or otherwise about to lose state tracking of
1206  * the current GPU logical state (e.g. suspend). On next use, it is therefore
1207  * imperative that we make no presumptions about the current state and load
1208  * from scratch.
1209  */
1210 void intel_engine_lost_context(struct intel_engine_cs *engine)
1211 {
1212 	struct intel_context *ce;
1213 
1214 	lockdep_assert_held(&engine->i915->drm.struct_mutex);
1215 
1216 	ce = fetch_and_zero(&engine->last_retired_context);
1217 	if (ce)
1218 		intel_context_unpin(ce);
1219 }
1220 
1221 bool intel_engine_can_store_dword(struct intel_engine_cs *engine)
1222 {
1223 	switch (INTEL_GEN(engine->i915)) {
1224 	case 2:
1225 		return false; /* uses physical not virtual addresses */
1226 	case 3:
1227 		/* maybe only uses physical not virtual addresses */
1228 		return !(IS_I915G(engine->i915) || IS_I915GM(engine->i915));
1229 	case 6:
1230 		return engine->class != VIDEO_DECODE_CLASS; /* b0rked */
1231 	default:
1232 		return true;
1233 	}
1234 }
1235 
1236 unsigned int intel_engines_has_context_isolation(struct drm_i915_private *i915)
1237 {
1238 	struct intel_engine_cs *engine;
1239 	enum intel_engine_id id;
1240 	unsigned int which;
1241 
1242 	which = 0;
1243 	for_each_engine(engine, i915, id)
1244 		if (engine->default_state)
1245 			which |= BIT(engine->uabi_class);
1246 
1247 	return which;
1248 }
1249 
1250 static int print_sched_attr(struct drm_i915_private *i915,
1251 			    const struct i915_sched_attr *attr,
1252 			    char *buf, int x, int len)
1253 {
1254 	if (attr->priority == I915_PRIORITY_INVALID)
1255 		return x;
1256 
1257 	x += snprintf(buf + x, len - x,
1258 		      " prio=%d", attr->priority);
1259 
1260 	return x;
1261 }
1262 
1263 static void print_request(struct drm_printer *m,
1264 			  struct i915_request *rq,
1265 			  const char *prefix)
1266 {
1267 	const char *name = rq->fence.ops->get_timeline_name(&rq->fence);
1268 	char buf[80] = "";
1269 	int x = 0;
1270 
1271 	x = print_sched_attr(rq->i915, &rq->sched.attr, buf, x, sizeof(buf));
1272 
1273 	drm_printf(m, "%s %llx:%llx%s%s %s @ %dms: %s\n",
1274 		   prefix,
1275 		   rq->fence.context, rq->fence.seqno,
1276 		   i915_request_completed(rq) ? "!" :
1277 		   i915_request_started(rq) ? "*" :
1278 		   "",
1279 		   test_bit(DMA_FENCE_FLAG_SIGNALED_BIT,
1280 			    &rq->fence.flags) ? "+" :
1281 		   test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT,
1282 			    &rq->fence.flags) ? "-" :
1283 		   "",
1284 		   buf,
1285 		   jiffies_to_msecs(jiffies - rq->emitted_jiffies),
1286 		   name);
1287 }
1288 
1289 static void hexdump(struct drm_printer *m, const void *buf, size_t len)
1290 {
1291 	const size_t rowsize = 8 * sizeof(u32);
1292 	const void *prev = NULL;
1293 	bool skip = false;
1294 	size_t pos;
1295 
1296 	for (pos = 0; pos < len; pos += rowsize) {
1297 		char line[128];
1298 
1299 		if (prev && !memcmp(prev, buf + pos, rowsize)) {
1300 			if (!skip) {
1301 				drm_printf(m, "*\n");
1302 				skip = true;
1303 			}
1304 			continue;
1305 		}
1306 
1307 		WARN_ON_ONCE(hex_dump_to_buffer(buf + pos, len - pos,
1308 						rowsize, sizeof(u32),
1309 						line, sizeof(line),
1310 						false) >= sizeof(line));
1311 		drm_printf(m, "[%04zx] %s\n", pos, line);
1312 
1313 		prev = buf + pos;
1314 		skip = false;
1315 	}
1316 }
1317 
1318 static void intel_engine_print_registers(const struct intel_engine_cs *engine,
1319 					 struct drm_printer *m)
1320 {
1321 	struct drm_i915_private *dev_priv = engine->i915;
1322 	const struct intel_engine_execlists * const execlists =
1323 		&engine->execlists;
1324 	u64 addr;
1325 
1326 	if (engine->id == RCS0 && IS_GEN_RANGE(dev_priv, 4, 7))
1327 		drm_printf(m, "\tCCID: 0x%08x\n", ENGINE_READ(engine, CCID));
1328 	drm_printf(m, "\tRING_START: 0x%08x\n",
1329 		   ENGINE_READ(engine, RING_START));
1330 	drm_printf(m, "\tRING_HEAD:  0x%08x\n",
1331 		   ENGINE_READ(engine, RING_HEAD) & HEAD_ADDR);
1332 	drm_printf(m, "\tRING_TAIL:  0x%08x\n",
1333 		   ENGINE_READ(engine, RING_TAIL) & TAIL_ADDR);
1334 	drm_printf(m, "\tRING_CTL:   0x%08x%s\n",
1335 		   ENGINE_READ(engine, RING_CTL),
1336 		   ENGINE_READ(engine, RING_CTL) & (RING_WAIT | RING_WAIT_SEMAPHORE) ? " [waiting]" : "");
1337 	if (INTEL_GEN(engine->i915) > 2) {
1338 		drm_printf(m, "\tRING_MODE:  0x%08x%s\n",
1339 			   ENGINE_READ(engine, RING_MI_MODE),
1340 			   ENGINE_READ(engine, RING_MI_MODE) & (MODE_IDLE) ? " [idle]" : "");
1341 	}
1342 
1343 	if (INTEL_GEN(dev_priv) >= 6) {
1344 		drm_printf(m, "\tRING_IMR: %08x\n",
1345 			   ENGINE_READ(engine, RING_IMR));
1346 	}
1347 
1348 	addr = intel_engine_get_active_head(engine);
1349 	drm_printf(m, "\tACTHD:  0x%08x_%08x\n",
1350 		   upper_32_bits(addr), lower_32_bits(addr));
1351 	addr = intel_engine_get_last_batch_head(engine);
1352 	drm_printf(m, "\tBBADDR: 0x%08x_%08x\n",
1353 		   upper_32_bits(addr), lower_32_bits(addr));
1354 	if (INTEL_GEN(dev_priv) >= 8)
1355 		addr = ENGINE_READ64(engine, RING_DMA_FADD, RING_DMA_FADD_UDW);
1356 	else if (INTEL_GEN(dev_priv) >= 4)
1357 		addr = ENGINE_READ(engine, RING_DMA_FADD);
1358 	else
1359 		addr = ENGINE_READ(engine, DMA_FADD_I8XX);
1360 	drm_printf(m, "\tDMA_FADDR: 0x%08x_%08x\n",
1361 		   upper_32_bits(addr), lower_32_bits(addr));
1362 	if (INTEL_GEN(dev_priv) >= 4) {
1363 		drm_printf(m, "\tIPEIR: 0x%08x\n",
1364 			   ENGINE_READ(engine, RING_IPEIR));
1365 		drm_printf(m, "\tIPEHR: 0x%08x\n",
1366 			   ENGINE_READ(engine, RING_IPEHR));
1367 	} else {
1368 		drm_printf(m, "\tIPEIR: 0x%08x\n", ENGINE_READ(engine, IPEIR));
1369 		drm_printf(m, "\tIPEHR: 0x%08x\n", ENGINE_READ(engine, IPEHR));
1370 	}
1371 
1372 	if (HAS_EXECLISTS(dev_priv)) {
1373 		const u32 *hws =
1374 			&engine->status_page.addr[I915_HWS_CSB_BUF0_INDEX];
1375 		const u8 num_entries = execlists->csb_size;
1376 		unsigned int idx;
1377 		u8 read, write;
1378 
1379 		drm_printf(m, "\tExeclist status: 0x%08x %08x, entries %u\n",
1380 			   ENGINE_READ(engine, RING_EXECLIST_STATUS_LO),
1381 			   ENGINE_READ(engine, RING_EXECLIST_STATUS_HI),
1382 			   num_entries);
1383 
1384 		read = execlists->csb_head;
1385 		write = READ_ONCE(*execlists->csb_write);
1386 
1387 		drm_printf(m, "\tExeclist CSB read %d, write %d, tasklet queued? %s (%s)\n",
1388 			   read, write,
1389 			   yesno(test_bit(TASKLET_STATE_SCHED,
1390 					  &engine->execlists.tasklet.state)),
1391 			   enableddisabled(!atomic_read(&engine->execlists.tasklet.count)));
1392 		if (read >= num_entries)
1393 			read = 0;
1394 		if (write >= num_entries)
1395 			write = 0;
1396 		if (read > write)
1397 			write += num_entries;
1398 		while (read < write) {
1399 			idx = ++read % num_entries;
1400 			drm_printf(m, "\tExeclist CSB[%d]: 0x%08x, context: %d\n",
1401 				   idx, hws[idx * 2], hws[idx * 2 + 1]);
1402 		}
1403 
1404 		rcu_read_lock();
1405 		for (idx = 0; idx < execlists_num_ports(execlists); idx++) {
1406 			struct i915_request *rq;
1407 			unsigned int count;
1408 
1409 			rq = port_unpack(&execlists->port[idx], &count);
1410 			if (rq) {
1411 				char hdr[80];
1412 
1413 				snprintf(hdr, sizeof(hdr),
1414 					 "\t\tELSP[%d] count=%d, ring:{start:%08x, hwsp:%08x, seqno:%08x}, rq: ",
1415 					 idx, count,
1416 					 i915_ggtt_offset(rq->ring->vma),
1417 					 rq->timeline->hwsp_offset,
1418 					 hwsp_seqno(rq));
1419 				print_request(m, rq, hdr);
1420 			} else {
1421 				drm_printf(m, "\t\tELSP[%d] idle\n", idx);
1422 			}
1423 		}
1424 		drm_printf(m, "\t\tHW active? 0x%x\n", execlists->active);
1425 		rcu_read_unlock();
1426 	} else if (INTEL_GEN(dev_priv) > 6) {
1427 		drm_printf(m, "\tPP_DIR_BASE: 0x%08x\n",
1428 			   ENGINE_READ(engine, RING_PP_DIR_BASE));
1429 		drm_printf(m, "\tPP_DIR_BASE_READ: 0x%08x\n",
1430 			   ENGINE_READ(engine, RING_PP_DIR_BASE_READ));
1431 		drm_printf(m, "\tPP_DIR_DCLV: 0x%08x\n",
1432 			   ENGINE_READ(engine, RING_PP_DIR_DCLV));
1433 	}
1434 }
1435 
1436 static void print_request_ring(struct drm_printer *m, struct i915_request *rq)
1437 {
1438 	void *ring;
1439 	int size;
1440 
1441 	drm_printf(m,
1442 		   "[head %04x, postfix %04x, tail %04x, batch 0x%08x_%08x]:\n",
1443 		   rq->head, rq->postfix, rq->tail,
1444 		   rq->batch ? upper_32_bits(rq->batch->node.start) : ~0u,
1445 		   rq->batch ? lower_32_bits(rq->batch->node.start) : ~0u);
1446 
1447 	size = rq->tail - rq->head;
1448 	if (rq->tail < rq->head)
1449 		size += rq->ring->size;
1450 
1451 	ring = kmalloc(size, GFP_ATOMIC);
1452 	if (ring) {
1453 		const void *vaddr = rq->ring->vaddr;
1454 		unsigned int head = rq->head;
1455 		unsigned int len = 0;
1456 
1457 		if (rq->tail < head) {
1458 			len = rq->ring->size - head;
1459 			memcpy(ring, vaddr + head, len);
1460 			head = 0;
1461 		}
1462 		memcpy(ring + len, vaddr + head, size - len);
1463 
1464 		hexdump(m, ring, size);
1465 		kfree(ring);
1466 	}
1467 }
1468 
1469 void intel_engine_dump(struct intel_engine_cs *engine,
1470 		       struct drm_printer *m,
1471 		       const char *header, ...)
1472 {
1473 	struct i915_gpu_error * const error = &engine->i915->gpu_error;
1474 	struct i915_request *rq;
1475 	intel_wakeref_t wakeref;
1476 
1477 	if (header) {
1478 		va_list ap;
1479 
1480 		va_start(ap, header);
1481 		drm_vprintf(m, header, &ap);
1482 		va_end(ap);
1483 	}
1484 
1485 	if (i915_reset_failed(engine->i915))
1486 		drm_printf(m, "*** WEDGED ***\n");
1487 
1488 	drm_printf(m, "\tAwake? %d\n", atomic_read(&engine->wakeref.count));
1489 	drm_printf(m, "\tHangcheck: %d ms ago\n",
1490 		   jiffies_to_msecs(jiffies - engine->hangcheck.action_timestamp));
1491 	drm_printf(m, "\tReset count: %d (global %d)\n",
1492 		   i915_reset_engine_count(error, engine),
1493 		   i915_reset_count(error));
1494 
1495 	rcu_read_lock();
1496 
1497 	drm_printf(m, "\tRequests:\n");
1498 
1499 	rq = list_first_entry(&engine->timeline.requests,
1500 			      struct i915_request, link);
1501 	if (&rq->link != &engine->timeline.requests)
1502 		print_request(m, rq, "\t\tfirst  ");
1503 
1504 	rq = list_last_entry(&engine->timeline.requests,
1505 			     struct i915_request, link);
1506 	if (&rq->link != &engine->timeline.requests)
1507 		print_request(m, rq, "\t\tlast   ");
1508 
1509 	rq = intel_engine_find_active_request(engine);
1510 	if (rq) {
1511 		print_request(m, rq, "\t\tactive ");
1512 
1513 		drm_printf(m, "\t\tring->start:  0x%08x\n",
1514 			   i915_ggtt_offset(rq->ring->vma));
1515 		drm_printf(m, "\t\tring->head:   0x%08x\n",
1516 			   rq->ring->head);
1517 		drm_printf(m, "\t\tring->tail:   0x%08x\n",
1518 			   rq->ring->tail);
1519 		drm_printf(m, "\t\tring->emit:   0x%08x\n",
1520 			   rq->ring->emit);
1521 		drm_printf(m, "\t\tring->space:  0x%08x\n",
1522 			   rq->ring->space);
1523 		drm_printf(m, "\t\tring->hwsp:   0x%08x\n",
1524 			   rq->timeline->hwsp_offset);
1525 
1526 		print_request_ring(m, rq);
1527 	}
1528 
1529 	rcu_read_unlock();
1530 
1531 	wakeref = intel_runtime_pm_get_if_in_use(engine->i915);
1532 	if (wakeref) {
1533 		intel_engine_print_registers(engine, m);
1534 		intel_runtime_pm_put(engine->i915, wakeref);
1535 	} else {
1536 		drm_printf(m, "\tDevice is asleep; skipping register dump\n");
1537 	}
1538 
1539 	intel_execlists_show_requests(engine, m, print_request, 8);
1540 
1541 	drm_printf(m, "HWSP:\n");
1542 	hexdump(m, engine->status_page.addr, PAGE_SIZE);
1543 
1544 	drm_printf(m, "Idle? %s\n", yesno(intel_engine_is_idle(engine)));
1545 
1546 	intel_engine_print_breadcrumbs(engine, m);
1547 }
1548 
1549 static u8 user_class_map[] = {
1550 	[I915_ENGINE_CLASS_RENDER] = RENDER_CLASS,
1551 	[I915_ENGINE_CLASS_COPY] = COPY_ENGINE_CLASS,
1552 	[I915_ENGINE_CLASS_VIDEO] = VIDEO_DECODE_CLASS,
1553 	[I915_ENGINE_CLASS_VIDEO_ENHANCE] = VIDEO_ENHANCEMENT_CLASS,
1554 };
1555 
1556 struct intel_engine_cs *
1557 intel_engine_lookup_user(struct drm_i915_private *i915, u8 class, u8 instance)
1558 {
1559 	if (class >= ARRAY_SIZE(user_class_map))
1560 		return NULL;
1561 
1562 	class = user_class_map[class];
1563 
1564 	GEM_BUG_ON(class > MAX_ENGINE_CLASS);
1565 
1566 	if (instance > MAX_ENGINE_INSTANCE)
1567 		return NULL;
1568 
1569 	return i915->engine_class[class][instance];
1570 }
1571 
1572 /**
1573  * intel_enable_engine_stats() - Enable engine busy tracking on engine
1574  * @engine: engine to enable stats collection
1575  *
1576  * Start collecting the engine busyness data for @engine.
1577  *
1578  * Returns 0 on success or a negative error code.
1579  */
1580 int intel_enable_engine_stats(struct intel_engine_cs *engine)
1581 {
1582 	struct intel_engine_execlists *execlists = &engine->execlists;
1583 	unsigned long flags;
1584 	int err = 0;
1585 
1586 	if (!intel_engine_supports_stats(engine))
1587 		return -ENODEV;
1588 
1589 	spin_lock_irqsave(&engine->timeline.lock, flags);
1590 	write_seqlock(&engine->stats.lock);
1591 
1592 	if (unlikely(engine->stats.enabled == ~0)) {
1593 		err = -EBUSY;
1594 		goto unlock;
1595 	}
1596 
1597 	if (engine->stats.enabled++ == 0) {
1598 		const struct execlist_port *port = execlists->port;
1599 		unsigned int num_ports = execlists_num_ports(execlists);
1600 
1601 		engine->stats.enabled_at = ktime_get();
1602 
1603 		/* XXX submission method oblivious? */
1604 		while (num_ports-- && port_isset(port)) {
1605 			engine->stats.active++;
1606 			port++;
1607 		}
1608 
1609 		if (engine->stats.active)
1610 			engine->stats.start = engine->stats.enabled_at;
1611 	}
1612 
1613 unlock:
1614 	write_sequnlock(&engine->stats.lock);
1615 	spin_unlock_irqrestore(&engine->timeline.lock, flags);
1616 
1617 	return err;
1618 }
1619 
1620 static ktime_t __intel_engine_get_busy_time(struct intel_engine_cs *engine)
1621 {
1622 	ktime_t total = engine->stats.total;
1623 
1624 	/*
1625 	 * If the engine is executing something at the moment
1626 	 * add it to the total.
1627 	 */
1628 	if (engine->stats.active)
1629 		total = ktime_add(total,
1630 				  ktime_sub(ktime_get(), engine->stats.start));
1631 
1632 	return total;
1633 }
1634 
1635 /**
1636  * intel_engine_get_busy_time() - Return current accumulated engine busyness
1637  * @engine: engine to report on
1638  *
1639  * Returns accumulated time @engine was busy since engine stats were enabled.
1640  */
1641 ktime_t intel_engine_get_busy_time(struct intel_engine_cs *engine)
1642 {
1643 	unsigned int seq;
1644 	ktime_t total;
1645 
1646 	do {
1647 		seq = read_seqbegin(&engine->stats.lock);
1648 		total = __intel_engine_get_busy_time(engine);
1649 	} while (read_seqretry(&engine->stats.lock, seq));
1650 
1651 	return total;
1652 }
1653 
1654 /**
1655  * intel_disable_engine_stats() - Disable engine busy tracking on engine
1656  * @engine: engine to disable stats collection
1657  *
1658  * Stops collecting the engine busyness data for @engine.
1659  */
1660 void intel_disable_engine_stats(struct intel_engine_cs *engine)
1661 {
1662 	unsigned long flags;
1663 
1664 	if (!intel_engine_supports_stats(engine))
1665 		return;
1666 
1667 	write_seqlock_irqsave(&engine->stats.lock, flags);
1668 	WARN_ON_ONCE(engine->stats.enabled == 0);
1669 	if (--engine->stats.enabled == 0) {
1670 		engine->stats.total = __intel_engine_get_busy_time(engine);
1671 		engine->stats.active = 0;
1672 	}
1673 	write_sequnlock_irqrestore(&engine->stats.lock, flags);
1674 }
1675 
1676 static bool match_ring(struct i915_request *rq)
1677 {
1678 	u32 ring = ENGINE_READ(rq->engine, RING_START);
1679 
1680 	return ring == i915_ggtt_offset(rq->ring->vma);
1681 }
1682 
1683 struct i915_request *
1684 intel_engine_find_active_request(struct intel_engine_cs *engine)
1685 {
1686 	struct i915_request *request, *active = NULL;
1687 	unsigned long flags;
1688 
1689 	/*
1690 	 * We are called by the error capture, reset and to dump engine
1691 	 * state at random points in time. In particular, note that neither is
1692 	 * crucially ordered with an interrupt. After a hang, the GPU is dead
1693 	 * and we assume that no more writes can happen (we waited long enough
1694 	 * for all writes that were in transaction to be flushed) - adding an
1695 	 * extra delay for a recent interrupt is pointless. Hence, we do
1696 	 * not need an engine->irq_seqno_barrier() before the seqno reads.
1697 	 * At all other times, we must assume the GPU is still running, but
1698 	 * we only care about the snapshot of this moment.
1699 	 */
1700 	spin_lock_irqsave(&engine->timeline.lock, flags);
1701 	list_for_each_entry(request, &engine->timeline.requests, link) {
1702 		if (i915_request_completed(request))
1703 			continue;
1704 
1705 		if (!i915_request_started(request))
1706 			break;
1707 
1708 		/* More than one preemptible request may match! */
1709 		if (!match_ring(request))
1710 			break;
1711 
1712 		active = request;
1713 		break;
1714 	}
1715 	spin_unlock_irqrestore(&engine->timeline.lock, flags);
1716 
1717 	return active;
1718 }
1719 
1720 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
1721 #include "selftest_engine_cs.c"
1722 #endif
1723