1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright © 2016 Intel Corporation
4  */
5 
6 #include <drm/drm_print.h>
7 
8 #include "gem/i915_gem_context.h"
9 #include "gem/i915_gem_internal.h"
10 #include "gt/intel_gt_regs.h"
11 
12 #include "i915_cmd_parser.h"
13 #include "i915_drv.h"
14 #include "intel_breadcrumbs.h"
15 #include "intel_context.h"
16 #include "intel_engine.h"
17 #include "intel_engine_pm.h"
18 #include "intel_engine_regs.h"
19 #include "intel_engine_user.h"
20 #include "intel_execlists_submission.h"
21 #include "intel_gt.h"
22 #include "intel_gt_requests.h"
23 #include "intel_gt_pm.h"
24 #include "intel_lrc_reg.h"
25 #include "intel_reset.h"
26 #include "intel_ring.h"
27 #include "uc/intel_guc_submission.h"
28 
29 /* Haswell does have the CXT_SIZE register however it does not appear to be
30  * valid. Now, docs explain in dwords what is in the context object. The full
31  * size is 70720 bytes, however, the power context and execlist context will
32  * never be saved (power context is stored elsewhere, and execlists don't work
33  * on HSW) - so the final size, including the extra state required for the
34  * Resource Streamer, is 66944 bytes, which rounds to 17 pages.
35  */
36 #define HSW_CXT_TOTAL_SIZE		(17 * PAGE_SIZE)
37 
38 #define DEFAULT_LR_CONTEXT_RENDER_SIZE	(22 * PAGE_SIZE)
39 #define GEN8_LR_CONTEXT_RENDER_SIZE	(20 * PAGE_SIZE)
40 #define GEN9_LR_CONTEXT_RENDER_SIZE	(22 * PAGE_SIZE)
41 #define GEN11_LR_CONTEXT_RENDER_SIZE	(14 * PAGE_SIZE)
42 
43 #define GEN8_LR_CONTEXT_OTHER_SIZE	( 2 * PAGE_SIZE)
44 
45 #define MAX_MMIO_BASES 3
46 struct engine_info {
47 	u8 class;
48 	u8 instance;
49 	/* mmio bases table *must* be sorted in reverse graphics_ver order */
50 	struct engine_mmio_base {
51 		u32 graphics_ver : 8;
52 		u32 base : 24;
53 	} mmio_bases[MAX_MMIO_BASES];
54 };
55 
56 static const struct engine_info intel_engines[] = {
57 	[RCS0] = {
58 		.class = RENDER_CLASS,
59 		.instance = 0,
60 		.mmio_bases = {
61 			{ .graphics_ver = 1, .base = RENDER_RING_BASE }
62 		},
63 	},
64 	[BCS0] = {
65 		.class = COPY_ENGINE_CLASS,
66 		.instance = 0,
67 		.mmio_bases = {
68 			{ .graphics_ver = 6, .base = BLT_RING_BASE }
69 		},
70 	},
71 	[VCS0] = {
72 		.class = VIDEO_DECODE_CLASS,
73 		.instance = 0,
74 		.mmio_bases = {
75 			{ .graphics_ver = 11, .base = GEN11_BSD_RING_BASE },
76 			{ .graphics_ver = 6, .base = GEN6_BSD_RING_BASE },
77 			{ .graphics_ver = 4, .base = BSD_RING_BASE }
78 		},
79 	},
80 	[VCS1] = {
81 		.class = VIDEO_DECODE_CLASS,
82 		.instance = 1,
83 		.mmio_bases = {
84 			{ .graphics_ver = 11, .base = GEN11_BSD2_RING_BASE },
85 			{ .graphics_ver = 8, .base = GEN8_BSD2_RING_BASE }
86 		},
87 	},
88 	[VCS2] = {
89 		.class = VIDEO_DECODE_CLASS,
90 		.instance = 2,
91 		.mmio_bases = {
92 			{ .graphics_ver = 11, .base = GEN11_BSD3_RING_BASE }
93 		},
94 	},
95 	[VCS3] = {
96 		.class = VIDEO_DECODE_CLASS,
97 		.instance = 3,
98 		.mmio_bases = {
99 			{ .graphics_ver = 11, .base = GEN11_BSD4_RING_BASE }
100 		},
101 	},
102 	[VCS4] = {
103 		.class = VIDEO_DECODE_CLASS,
104 		.instance = 4,
105 		.mmio_bases = {
106 			{ .graphics_ver = 12, .base = XEHP_BSD5_RING_BASE }
107 		},
108 	},
109 	[VCS5] = {
110 		.class = VIDEO_DECODE_CLASS,
111 		.instance = 5,
112 		.mmio_bases = {
113 			{ .graphics_ver = 12, .base = XEHP_BSD6_RING_BASE }
114 		},
115 	},
116 	[VCS6] = {
117 		.class = VIDEO_DECODE_CLASS,
118 		.instance = 6,
119 		.mmio_bases = {
120 			{ .graphics_ver = 12, .base = XEHP_BSD7_RING_BASE }
121 		},
122 	},
123 	[VCS7] = {
124 		.class = VIDEO_DECODE_CLASS,
125 		.instance = 7,
126 		.mmio_bases = {
127 			{ .graphics_ver = 12, .base = XEHP_BSD8_RING_BASE }
128 		},
129 	},
130 	[VECS0] = {
131 		.class = VIDEO_ENHANCEMENT_CLASS,
132 		.instance = 0,
133 		.mmio_bases = {
134 			{ .graphics_ver = 11, .base = GEN11_VEBOX_RING_BASE },
135 			{ .graphics_ver = 7, .base = VEBOX_RING_BASE }
136 		},
137 	},
138 	[VECS1] = {
139 		.class = VIDEO_ENHANCEMENT_CLASS,
140 		.instance = 1,
141 		.mmio_bases = {
142 			{ .graphics_ver = 11, .base = GEN11_VEBOX2_RING_BASE }
143 		},
144 	},
145 	[VECS2] = {
146 		.class = VIDEO_ENHANCEMENT_CLASS,
147 		.instance = 2,
148 		.mmio_bases = {
149 			{ .graphics_ver = 12, .base = XEHP_VEBOX3_RING_BASE }
150 		},
151 	},
152 	[VECS3] = {
153 		.class = VIDEO_ENHANCEMENT_CLASS,
154 		.instance = 3,
155 		.mmio_bases = {
156 			{ .graphics_ver = 12, .base = XEHP_VEBOX4_RING_BASE }
157 		},
158 	},
159 };
160 
161 /**
162  * intel_engine_context_size() - return the size of the context for an engine
163  * @gt: the gt
164  * @class: engine class
165  *
166  * Each engine class may require a different amount of space for a context
167  * image.
168  *
169  * Return: size (in bytes) of an engine class specific context image
170  *
171  * Note: this size includes the HWSP, which is part of the context image
172  * in LRC mode, but does not include the "shared data page" used with
173  * GuC submission. The caller should account for this if using the GuC.
174  */
175 u32 intel_engine_context_size(struct intel_gt *gt, u8 class)
176 {
177 	struct intel_uncore *uncore = gt->uncore;
178 	u32 cxt_size;
179 
180 	BUILD_BUG_ON(I915_GTT_PAGE_SIZE != PAGE_SIZE);
181 
182 	switch (class) {
183 	case RENDER_CLASS:
184 		switch (GRAPHICS_VER(gt->i915)) {
185 		default:
186 			MISSING_CASE(GRAPHICS_VER(gt->i915));
187 			return DEFAULT_LR_CONTEXT_RENDER_SIZE;
188 		case 12:
189 		case 11:
190 			return GEN11_LR_CONTEXT_RENDER_SIZE;
191 		case 9:
192 			return GEN9_LR_CONTEXT_RENDER_SIZE;
193 		case 8:
194 			return GEN8_LR_CONTEXT_RENDER_SIZE;
195 		case 7:
196 			if (IS_HASWELL(gt->i915))
197 				return HSW_CXT_TOTAL_SIZE;
198 
199 			cxt_size = intel_uncore_read(uncore, GEN7_CXT_SIZE);
200 			return round_up(GEN7_CXT_TOTAL_SIZE(cxt_size) * 64,
201 					PAGE_SIZE);
202 		case 6:
203 			cxt_size = intel_uncore_read(uncore, CXT_SIZE);
204 			return round_up(GEN6_CXT_TOTAL_SIZE(cxt_size) * 64,
205 					PAGE_SIZE);
206 		case 5:
207 		case 4:
208 			/*
209 			 * There is a discrepancy here between the size reported
210 			 * by the register and the size of the context layout
211 			 * in the docs. Both are described as authorative!
212 			 *
213 			 * The discrepancy is on the order of a few cachelines,
214 			 * but the total is under one page (4k), which is our
215 			 * minimum allocation anyway so it should all come
216 			 * out in the wash.
217 			 */
218 			cxt_size = intel_uncore_read(uncore, CXT_SIZE) + 1;
219 			drm_dbg(&gt->i915->drm,
220 				"graphics_ver = %d CXT_SIZE = %d bytes [0x%08x]\n",
221 				GRAPHICS_VER(gt->i915), cxt_size * 64,
222 				cxt_size - 1);
223 			return round_up(cxt_size * 64, PAGE_SIZE);
224 		case 3:
225 		case 2:
226 		/* For the special day when i810 gets merged. */
227 		case 1:
228 			return 0;
229 		}
230 		break;
231 	default:
232 		MISSING_CASE(class);
233 		fallthrough;
234 	case VIDEO_DECODE_CLASS:
235 	case VIDEO_ENHANCEMENT_CLASS:
236 	case COPY_ENGINE_CLASS:
237 		if (GRAPHICS_VER(gt->i915) < 8)
238 			return 0;
239 		return GEN8_LR_CONTEXT_OTHER_SIZE;
240 	}
241 }
242 
243 static u32 __engine_mmio_base(struct drm_i915_private *i915,
244 			      const struct engine_mmio_base *bases)
245 {
246 	int i;
247 
248 	for (i = 0; i < MAX_MMIO_BASES; i++)
249 		if (GRAPHICS_VER(i915) >= bases[i].graphics_ver)
250 			break;
251 
252 	GEM_BUG_ON(i == MAX_MMIO_BASES);
253 	GEM_BUG_ON(!bases[i].base);
254 
255 	return bases[i].base;
256 }
257 
258 static void __sprint_engine_name(struct intel_engine_cs *engine)
259 {
260 	/*
261 	 * Before we know what the uABI name for this engine will be,
262 	 * we still would like to keep track of this engine in the debug logs.
263 	 * We throw in a ' here as a reminder that this isn't its final name.
264 	 */
265 	GEM_WARN_ON(snprintf(engine->name, sizeof(engine->name), "%s'%u",
266 			     intel_engine_class_repr(engine->class),
267 			     engine->instance) >= sizeof(engine->name));
268 }
269 
270 void intel_engine_set_hwsp_writemask(struct intel_engine_cs *engine, u32 mask)
271 {
272 	/*
273 	 * Though they added more rings on g4x/ilk, they did not add
274 	 * per-engine HWSTAM until gen6.
275 	 */
276 	if (GRAPHICS_VER(engine->i915) < 6 && engine->class != RENDER_CLASS)
277 		return;
278 
279 	if (GRAPHICS_VER(engine->i915) >= 3)
280 		ENGINE_WRITE(engine, RING_HWSTAM, mask);
281 	else
282 		ENGINE_WRITE16(engine, RING_HWSTAM, mask);
283 }
284 
285 static void intel_engine_sanitize_mmio(struct intel_engine_cs *engine)
286 {
287 	/* Mask off all writes into the unknown HWSP */
288 	intel_engine_set_hwsp_writemask(engine, ~0u);
289 }
290 
291 static void nop_irq_handler(struct intel_engine_cs *engine, u16 iir)
292 {
293 	GEM_DEBUG_WARN_ON(iir);
294 }
295 
296 static int intel_engine_setup(struct intel_gt *gt, enum intel_engine_id id,
297 			      u8 logical_instance)
298 {
299 	const struct engine_info *info = &intel_engines[id];
300 	struct drm_i915_private *i915 = gt->i915;
301 	struct intel_engine_cs *engine;
302 	u8 guc_class;
303 
304 	BUILD_BUG_ON(MAX_ENGINE_CLASS >= BIT(GEN11_ENGINE_CLASS_WIDTH));
305 	BUILD_BUG_ON(MAX_ENGINE_INSTANCE >= BIT(GEN11_ENGINE_INSTANCE_WIDTH));
306 	BUILD_BUG_ON(I915_MAX_VCS > (MAX_ENGINE_INSTANCE + 1));
307 	BUILD_BUG_ON(I915_MAX_VECS > (MAX_ENGINE_INSTANCE + 1));
308 
309 	if (GEM_DEBUG_WARN_ON(id >= ARRAY_SIZE(gt->engine)))
310 		return -EINVAL;
311 
312 	if (GEM_DEBUG_WARN_ON(info->class > MAX_ENGINE_CLASS))
313 		return -EINVAL;
314 
315 	if (GEM_DEBUG_WARN_ON(info->instance > MAX_ENGINE_INSTANCE))
316 		return -EINVAL;
317 
318 	if (GEM_DEBUG_WARN_ON(gt->engine_class[info->class][info->instance]))
319 		return -EINVAL;
320 
321 	engine = kzalloc(sizeof(*engine), GFP_KERNEL);
322 	if (!engine)
323 		return -ENOMEM;
324 
325 	BUILD_BUG_ON(BITS_PER_TYPE(engine->mask) < I915_NUM_ENGINES);
326 
327 	INIT_LIST_HEAD(&engine->pinned_contexts_list);
328 	engine->id = id;
329 	engine->legacy_idx = INVALID_ENGINE;
330 	engine->mask = BIT(id);
331 	if (GRAPHICS_VER(gt->i915) >= 11) {
332 		static const u32 engine_reset_domains[] = {
333 			[RCS0]  = GEN11_GRDOM_RENDER,
334 			[BCS0]  = GEN11_GRDOM_BLT,
335 			[VCS0]  = GEN11_GRDOM_MEDIA,
336 			[VCS1]  = GEN11_GRDOM_MEDIA2,
337 			[VCS2]  = GEN11_GRDOM_MEDIA3,
338 			[VCS3]  = GEN11_GRDOM_MEDIA4,
339 			[VCS4]  = GEN11_GRDOM_MEDIA5,
340 			[VCS5]  = GEN11_GRDOM_MEDIA6,
341 			[VCS6]  = GEN11_GRDOM_MEDIA7,
342 			[VCS7]  = GEN11_GRDOM_MEDIA8,
343 			[VECS0] = GEN11_GRDOM_VECS,
344 			[VECS1] = GEN11_GRDOM_VECS2,
345 			[VECS2] = GEN11_GRDOM_VECS3,
346 			[VECS3] = GEN11_GRDOM_VECS4,
347 		};
348 		GEM_BUG_ON(id >= ARRAY_SIZE(engine_reset_domains) ||
349 			   !engine_reset_domains[id]);
350 		engine->reset_domain = engine_reset_domains[id];
351 	} else {
352 		static const u32 engine_reset_domains[] = {
353 			[RCS0]  = GEN6_GRDOM_RENDER,
354 			[BCS0]  = GEN6_GRDOM_BLT,
355 			[VCS0]  = GEN6_GRDOM_MEDIA,
356 			[VCS1]  = GEN8_GRDOM_MEDIA2,
357 			[VECS0] = GEN6_GRDOM_VECS,
358 		};
359 		GEM_BUG_ON(id >= ARRAY_SIZE(engine_reset_domains) ||
360 			   !engine_reset_domains[id]);
361 		engine->reset_domain = engine_reset_domains[id];
362 	}
363 	engine->i915 = i915;
364 	engine->gt = gt;
365 	engine->uncore = gt->uncore;
366 	guc_class = engine_class_to_guc_class(info->class);
367 	engine->guc_id = MAKE_GUC_ID(guc_class, info->instance);
368 	engine->mmio_base = __engine_mmio_base(i915, info->mmio_bases);
369 
370 	engine->irq_handler = nop_irq_handler;
371 
372 	engine->class = info->class;
373 	engine->instance = info->instance;
374 	engine->logical_mask = BIT(logical_instance);
375 	__sprint_engine_name(engine);
376 
377 	engine->props.heartbeat_interval_ms =
378 		CONFIG_DRM_I915_HEARTBEAT_INTERVAL;
379 	engine->props.max_busywait_duration_ns =
380 		CONFIG_DRM_I915_MAX_REQUEST_BUSYWAIT;
381 	engine->props.preempt_timeout_ms =
382 		CONFIG_DRM_I915_PREEMPT_TIMEOUT;
383 	engine->props.stop_timeout_ms =
384 		CONFIG_DRM_I915_STOP_TIMEOUT;
385 	engine->props.timeslice_duration_ms =
386 		CONFIG_DRM_I915_TIMESLICE_DURATION;
387 
388 	/* Override to uninterruptible for OpenCL workloads. */
389 	if (GRAPHICS_VER(i915) == 12 && engine->class == RENDER_CLASS)
390 		engine->props.preempt_timeout_ms = 0;
391 
392 	engine->defaults = engine->props; /* never to change again */
393 
394 	engine->context_size = intel_engine_context_size(gt, engine->class);
395 	if (WARN_ON(engine->context_size > BIT(20)))
396 		engine->context_size = 0;
397 	if (engine->context_size)
398 		DRIVER_CAPS(i915)->has_logical_contexts = true;
399 
400 	ewma__engine_latency_init(&engine->latency);
401 	seqcount_init(&engine->stats.execlists.lock);
402 
403 	ATOMIC_INIT_NOTIFIER_HEAD(&engine->context_status_notifier);
404 
405 	/* Scrub mmio state on takeover */
406 	intel_engine_sanitize_mmio(engine);
407 
408 	gt->engine_class[info->class][info->instance] = engine;
409 	gt->engine[id] = engine;
410 
411 	return 0;
412 }
413 
414 static void __setup_engine_capabilities(struct intel_engine_cs *engine)
415 {
416 	struct drm_i915_private *i915 = engine->i915;
417 
418 	if (engine->class == VIDEO_DECODE_CLASS) {
419 		/*
420 		 * HEVC support is present on first engine instance
421 		 * before Gen11 and on all instances afterwards.
422 		 */
423 		if (GRAPHICS_VER(i915) >= 11 ||
424 		    (GRAPHICS_VER(i915) >= 9 && engine->instance == 0))
425 			engine->uabi_capabilities |=
426 				I915_VIDEO_CLASS_CAPABILITY_HEVC;
427 
428 		/*
429 		 * SFC block is present only on even logical engine
430 		 * instances.
431 		 */
432 		if ((GRAPHICS_VER(i915) >= 11 &&
433 		     (engine->gt->info.vdbox_sfc_access &
434 		      BIT(engine->instance))) ||
435 		    (GRAPHICS_VER(i915) >= 9 && engine->instance == 0))
436 			engine->uabi_capabilities |=
437 				I915_VIDEO_AND_ENHANCE_CLASS_CAPABILITY_SFC;
438 	} else if (engine->class == VIDEO_ENHANCEMENT_CLASS) {
439 		if (GRAPHICS_VER(i915) >= 9 &&
440 		    engine->gt->info.sfc_mask & BIT(engine->instance))
441 			engine->uabi_capabilities |=
442 				I915_VIDEO_AND_ENHANCE_CLASS_CAPABILITY_SFC;
443 	}
444 }
445 
446 static void intel_setup_engine_capabilities(struct intel_gt *gt)
447 {
448 	struct intel_engine_cs *engine;
449 	enum intel_engine_id id;
450 
451 	for_each_engine(engine, gt, id)
452 		__setup_engine_capabilities(engine);
453 }
454 
455 /**
456  * intel_engines_release() - free the resources allocated for Command Streamers
457  * @gt: pointer to struct intel_gt
458  */
459 void intel_engines_release(struct intel_gt *gt)
460 {
461 	struct intel_engine_cs *engine;
462 	enum intel_engine_id id;
463 
464 	/*
465 	 * Before we release the resources held by engine, we must be certain
466 	 * that the HW is no longer accessing them -- having the GPU scribble
467 	 * to or read from a page being used for something else causes no end
468 	 * of fun.
469 	 *
470 	 * The GPU should be reset by this point, but assume the worst just
471 	 * in case we aborted before completely initialising the engines.
472 	 */
473 	GEM_BUG_ON(intel_gt_pm_is_awake(gt));
474 	if (!INTEL_INFO(gt->i915)->gpu_reset_clobbers_display)
475 		__intel_gt_reset(gt, ALL_ENGINES);
476 
477 	/* Decouple the backend; but keep the layout for late GPU resets */
478 	for_each_engine(engine, gt, id) {
479 		if (!engine->release)
480 			continue;
481 
482 		intel_wakeref_wait_for_idle(&engine->wakeref);
483 		GEM_BUG_ON(intel_engine_pm_is_awake(engine));
484 
485 		engine->release(engine);
486 		engine->release = NULL;
487 
488 		memset(&engine->reset, 0, sizeof(engine->reset));
489 	}
490 }
491 
492 void intel_engine_free_request_pool(struct intel_engine_cs *engine)
493 {
494 	if (!engine->request_pool)
495 		return;
496 
497 	kmem_cache_free(i915_request_slab_cache(), engine->request_pool);
498 }
499 
500 void intel_engines_free(struct intel_gt *gt)
501 {
502 	struct intel_engine_cs *engine;
503 	enum intel_engine_id id;
504 
505 	/* Free the requests! dma-resv keeps fences around for an eternity */
506 	rcu_barrier();
507 
508 	for_each_engine(engine, gt, id) {
509 		intel_engine_free_request_pool(engine);
510 		kfree(engine);
511 		gt->engine[id] = NULL;
512 	}
513 }
514 
515 static
516 bool gen11_vdbox_has_sfc(struct intel_gt *gt,
517 			 unsigned int physical_vdbox,
518 			 unsigned int logical_vdbox, u16 vdbox_mask)
519 {
520 	struct drm_i915_private *i915 = gt->i915;
521 
522 	/*
523 	 * In Gen11, only even numbered logical VDBOXes are hooked
524 	 * up to an SFC (Scaler & Format Converter) unit.
525 	 * In Gen12, Even numbered physical instance always are connected
526 	 * to an SFC. Odd numbered physical instances have SFC only if
527 	 * previous even instance is fused off.
528 	 *
529 	 * Starting with Xe_HP, there's also a dedicated SFC_ENABLE field
530 	 * in the fuse register that tells us whether a specific SFC is present.
531 	 */
532 	if ((gt->info.sfc_mask & BIT(physical_vdbox / 2)) == 0)
533 		return false;
534 	else if (GRAPHICS_VER(i915) == 12)
535 		return (physical_vdbox % 2 == 0) ||
536 			!(BIT(physical_vdbox - 1) & vdbox_mask);
537 	else if (GRAPHICS_VER(i915) == 11)
538 		return logical_vdbox % 2 == 0;
539 
540 	MISSING_CASE(GRAPHICS_VER(i915));
541 	return false;
542 }
543 
544 /*
545  * Determine which engines are fused off in our particular hardware.
546  * Note that we have a catch-22 situation where we need to be able to access
547  * the blitter forcewake domain to read the engine fuses, but at the same time
548  * we need to know which engines are available on the system to know which
549  * forcewake domains are present. We solve this by intializing the forcewake
550  * domains based on the full engine mask in the platform capabilities before
551  * calling this function and pruning the domains for fused-off engines
552  * afterwards.
553  */
554 static intel_engine_mask_t init_engine_mask(struct intel_gt *gt)
555 {
556 	struct drm_i915_private *i915 = gt->i915;
557 	struct intel_gt_info *info = &gt->info;
558 	struct intel_uncore *uncore = gt->uncore;
559 	unsigned int logical_vdbox = 0;
560 	unsigned int i;
561 	u32 media_fuse, fuse1;
562 	u16 vdbox_mask;
563 	u16 vebox_mask;
564 
565 	info->engine_mask = INTEL_INFO(i915)->platform_engine_mask;
566 
567 	if (GRAPHICS_VER(i915) < 11)
568 		return info->engine_mask;
569 
570 	/*
571 	 * On newer platforms the fusing register is called 'enable' and has
572 	 * enable semantics, while on older platforms it is called 'disable'
573 	 * and bits have disable semantices.
574 	 */
575 	media_fuse = intel_uncore_read(uncore, GEN11_GT_VEBOX_VDBOX_DISABLE);
576 	if (GRAPHICS_VER_FULL(i915) < IP_VER(12, 50))
577 		media_fuse = ~media_fuse;
578 
579 	vdbox_mask = media_fuse & GEN11_GT_VDBOX_DISABLE_MASK;
580 	vebox_mask = (media_fuse & GEN11_GT_VEBOX_DISABLE_MASK) >>
581 		      GEN11_GT_VEBOX_DISABLE_SHIFT;
582 
583 	if (GRAPHICS_VER_FULL(i915) >= IP_VER(12, 50)) {
584 		fuse1 = intel_uncore_read(uncore, HSW_PAVP_FUSE1);
585 		gt->info.sfc_mask = REG_FIELD_GET(XEHP_SFC_ENABLE_MASK, fuse1);
586 	} else {
587 		gt->info.sfc_mask = ~0;
588 	}
589 
590 	for (i = 0; i < I915_MAX_VCS; i++) {
591 		if (!HAS_ENGINE(gt, _VCS(i))) {
592 			vdbox_mask &= ~BIT(i);
593 			continue;
594 		}
595 
596 		if (!(BIT(i) & vdbox_mask)) {
597 			info->engine_mask &= ~BIT(_VCS(i));
598 			drm_dbg(&i915->drm, "vcs%u fused off\n", i);
599 			continue;
600 		}
601 
602 		if (gen11_vdbox_has_sfc(gt, i, logical_vdbox, vdbox_mask))
603 			gt->info.vdbox_sfc_access |= BIT(i);
604 		logical_vdbox++;
605 	}
606 	drm_dbg(&i915->drm, "vdbox enable: %04x, instances: %04lx\n",
607 		vdbox_mask, VDBOX_MASK(gt));
608 	GEM_BUG_ON(vdbox_mask != VDBOX_MASK(gt));
609 
610 	for (i = 0; i < I915_MAX_VECS; i++) {
611 		if (!HAS_ENGINE(gt, _VECS(i))) {
612 			vebox_mask &= ~BIT(i);
613 			continue;
614 		}
615 
616 		if (!(BIT(i) & vebox_mask)) {
617 			info->engine_mask &= ~BIT(_VECS(i));
618 			drm_dbg(&i915->drm, "vecs%u fused off\n", i);
619 		}
620 	}
621 	drm_dbg(&i915->drm, "vebox enable: %04x, instances: %04lx\n",
622 		vebox_mask, VEBOX_MASK(gt));
623 	GEM_BUG_ON(vebox_mask != VEBOX_MASK(gt));
624 
625 	return info->engine_mask;
626 }
627 
628 static void populate_logical_ids(struct intel_gt *gt, u8 *logical_ids,
629 				 u8 class, const u8 *map, u8 num_instances)
630 {
631 	int i, j;
632 	u8 current_logical_id = 0;
633 
634 	for (j = 0; j < num_instances; ++j) {
635 		for (i = 0; i < ARRAY_SIZE(intel_engines); ++i) {
636 			if (!HAS_ENGINE(gt, i) ||
637 			    intel_engines[i].class != class)
638 				continue;
639 
640 			if (intel_engines[i].instance == map[j]) {
641 				logical_ids[intel_engines[i].instance] =
642 					current_logical_id++;
643 				break;
644 			}
645 		}
646 	}
647 }
648 
649 static void setup_logical_ids(struct intel_gt *gt, u8 *logical_ids, u8 class)
650 {
651 	int i;
652 	u8 map[MAX_ENGINE_INSTANCE + 1];
653 
654 	for (i = 0; i < MAX_ENGINE_INSTANCE + 1; ++i)
655 		map[i] = i;
656 	populate_logical_ids(gt, logical_ids, class, map, ARRAY_SIZE(map));
657 }
658 
659 /**
660  * intel_engines_init_mmio() - allocate and prepare the Engine Command Streamers
661  * @gt: pointer to struct intel_gt
662  *
663  * Return: non-zero if the initialization failed.
664  */
665 int intel_engines_init_mmio(struct intel_gt *gt)
666 {
667 	struct drm_i915_private *i915 = gt->i915;
668 	const unsigned int engine_mask = init_engine_mask(gt);
669 	unsigned int mask = 0;
670 	unsigned int i, class;
671 	u8 logical_ids[MAX_ENGINE_INSTANCE + 1];
672 	int err;
673 
674 	drm_WARN_ON(&i915->drm, engine_mask == 0);
675 	drm_WARN_ON(&i915->drm, engine_mask &
676 		    GENMASK(BITS_PER_TYPE(mask) - 1, I915_NUM_ENGINES));
677 
678 	if (i915_inject_probe_failure(i915))
679 		return -ENODEV;
680 
681 	for (class = 0; class < MAX_ENGINE_CLASS + 1; ++class) {
682 		setup_logical_ids(gt, logical_ids, class);
683 
684 		for (i = 0; i < ARRAY_SIZE(intel_engines); ++i) {
685 			u8 instance = intel_engines[i].instance;
686 
687 			if (intel_engines[i].class != class ||
688 			    !HAS_ENGINE(gt, i))
689 				continue;
690 
691 			err = intel_engine_setup(gt, i,
692 						 logical_ids[instance]);
693 			if (err)
694 				goto cleanup;
695 
696 			mask |= BIT(i);
697 		}
698 	}
699 
700 	/*
701 	 * Catch failures to update intel_engines table when the new engines
702 	 * are added to the driver by a warning and disabling the forgotten
703 	 * engines.
704 	 */
705 	if (drm_WARN_ON(&i915->drm, mask != engine_mask))
706 		gt->info.engine_mask = mask;
707 
708 	gt->info.num_engines = hweight32(mask);
709 
710 	intel_gt_check_and_clear_faults(gt);
711 
712 	intel_setup_engine_capabilities(gt);
713 
714 	intel_uncore_prune_engine_fw_domains(gt->uncore, gt);
715 
716 	return 0;
717 
718 cleanup:
719 	intel_engines_free(gt);
720 	return err;
721 }
722 
723 void intel_engine_init_execlists(struct intel_engine_cs *engine)
724 {
725 	struct intel_engine_execlists * const execlists = &engine->execlists;
726 
727 	execlists->port_mask = 1;
728 	GEM_BUG_ON(!is_power_of_2(execlists_num_ports(execlists)));
729 	GEM_BUG_ON(execlists_num_ports(execlists) > EXECLIST_MAX_PORTS);
730 
731 	memset(execlists->pending, 0, sizeof(execlists->pending));
732 	execlists->active =
733 		memset(execlists->inflight, 0, sizeof(execlists->inflight));
734 }
735 
736 static void cleanup_status_page(struct intel_engine_cs *engine)
737 {
738 	struct i915_vma *vma;
739 
740 	/* Prevent writes into HWSP after returning the page to the system */
741 	intel_engine_set_hwsp_writemask(engine, ~0u);
742 
743 	vma = fetch_and_zero(&engine->status_page.vma);
744 	if (!vma)
745 		return;
746 
747 	if (!HWS_NEEDS_PHYSICAL(engine->i915))
748 		i915_vma_unpin(vma);
749 
750 	i915_gem_object_unpin_map(vma->obj);
751 	i915_gem_object_put(vma->obj);
752 }
753 
754 static int pin_ggtt_status_page(struct intel_engine_cs *engine,
755 				struct i915_gem_ww_ctx *ww,
756 				struct i915_vma *vma)
757 {
758 	unsigned int flags;
759 
760 	if (!HAS_LLC(engine->i915) && i915_ggtt_has_aperture(engine->gt->ggtt))
761 		/*
762 		 * On g33, we cannot place HWS above 256MiB, so
763 		 * restrict its pinning to the low mappable arena.
764 		 * Though this restriction is not documented for
765 		 * gen4, gen5, or byt, they also behave similarly
766 		 * and hang if the HWS is placed at the top of the
767 		 * GTT. To generalise, it appears that all !llc
768 		 * platforms have issues with us placing the HWS
769 		 * above the mappable region (even though we never
770 		 * actually map it).
771 		 */
772 		flags = PIN_MAPPABLE;
773 	else
774 		flags = PIN_HIGH;
775 
776 	return i915_ggtt_pin(vma, ww, 0, flags);
777 }
778 
779 static int init_status_page(struct intel_engine_cs *engine)
780 {
781 	struct drm_i915_gem_object *obj;
782 	struct i915_gem_ww_ctx ww;
783 	struct i915_vma *vma;
784 	void *vaddr;
785 	int ret;
786 
787 	INIT_LIST_HEAD(&engine->status_page.timelines);
788 
789 	/*
790 	 * Though the HWS register does support 36bit addresses, historically
791 	 * we have had hangs and corruption reported due to wild writes if
792 	 * the HWS is placed above 4G. We only allow objects to be allocated
793 	 * in GFP_DMA32 for i965, and no earlier physical address users had
794 	 * access to more than 4G.
795 	 */
796 	obj = i915_gem_object_create_internal(engine->i915, PAGE_SIZE);
797 	if (IS_ERR(obj)) {
798 		drm_err(&engine->i915->drm,
799 			"Failed to allocate status page\n");
800 		return PTR_ERR(obj);
801 	}
802 
803 	i915_gem_object_set_cache_coherency(obj, I915_CACHE_LLC);
804 
805 	vma = i915_vma_instance(obj, &engine->gt->ggtt->vm, NULL);
806 	if (IS_ERR(vma)) {
807 		ret = PTR_ERR(vma);
808 		goto err_put;
809 	}
810 
811 	i915_gem_ww_ctx_init(&ww, true);
812 retry:
813 	ret = i915_gem_object_lock(obj, &ww);
814 	if (!ret && !HWS_NEEDS_PHYSICAL(engine->i915))
815 		ret = pin_ggtt_status_page(engine, &ww, vma);
816 	if (ret)
817 		goto err;
818 
819 	vaddr = i915_gem_object_pin_map(obj, I915_MAP_WB);
820 	if (IS_ERR(vaddr)) {
821 		ret = PTR_ERR(vaddr);
822 		goto err_unpin;
823 	}
824 
825 	engine->status_page.addr = memset(vaddr, 0, PAGE_SIZE);
826 	engine->status_page.vma = vma;
827 
828 err_unpin:
829 	if (ret)
830 		i915_vma_unpin(vma);
831 err:
832 	if (ret == -EDEADLK) {
833 		ret = i915_gem_ww_ctx_backoff(&ww);
834 		if (!ret)
835 			goto retry;
836 	}
837 	i915_gem_ww_ctx_fini(&ww);
838 err_put:
839 	if (ret)
840 		i915_gem_object_put(obj);
841 	return ret;
842 }
843 
844 static int engine_setup_common(struct intel_engine_cs *engine)
845 {
846 	int err;
847 
848 	init_llist_head(&engine->barrier_tasks);
849 
850 	err = init_status_page(engine);
851 	if (err)
852 		return err;
853 
854 	engine->breadcrumbs = intel_breadcrumbs_create(engine);
855 	if (!engine->breadcrumbs) {
856 		err = -ENOMEM;
857 		goto err_status;
858 	}
859 
860 	engine->sched_engine = i915_sched_engine_create(ENGINE_PHYSICAL);
861 	if (!engine->sched_engine) {
862 		err = -ENOMEM;
863 		goto err_sched_engine;
864 	}
865 	engine->sched_engine->private_data = engine;
866 
867 	err = intel_engine_init_cmd_parser(engine);
868 	if (err)
869 		goto err_cmd_parser;
870 
871 	intel_engine_init_execlists(engine);
872 	intel_engine_init__pm(engine);
873 	intel_engine_init_retire(engine);
874 
875 	/* Use the whole device by default */
876 	engine->sseu =
877 		intel_sseu_from_device_info(&engine->gt->info.sseu);
878 
879 	intel_engine_init_workarounds(engine);
880 	intel_engine_init_whitelist(engine);
881 	intel_engine_init_ctx_wa(engine);
882 
883 	if (GRAPHICS_VER(engine->i915) >= 12)
884 		engine->flags |= I915_ENGINE_HAS_RELATIVE_MMIO;
885 
886 	return 0;
887 
888 err_cmd_parser:
889 	i915_sched_engine_put(engine->sched_engine);
890 err_sched_engine:
891 	intel_breadcrumbs_put(engine->breadcrumbs);
892 err_status:
893 	cleanup_status_page(engine);
894 	return err;
895 }
896 
897 struct measure_breadcrumb {
898 	struct i915_request rq;
899 	struct intel_ring ring;
900 	u32 cs[2048];
901 };
902 
903 static int measure_breadcrumb_dw(struct intel_context *ce)
904 {
905 	struct intel_engine_cs *engine = ce->engine;
906 	struct measure_breadcrumb *frame;
907 	int dw;
908 
909 	GEM_BUG_ON(!engine->gt->scratch);
910 
911 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
912 	if (!frame)
913 		return -ENOMEM;
914 
915 	frame->rq.engine = engine;
916 	frame->rq.context = ce;
917 	rcu_assign_pointer(frame->rq.timeline, ce->timeline);
918 	frame->rq.hwsp_seqno = ce->timeline->hwsp_seqno;
919 
920 	frame->ring.vaddr = frame->cs;
921 	frame->ring.size = sizeof(frame->cs);
922 	frame->ring.wrap =
923 		BITS_PER_TYPE(frame->ring.size) - ilog2(frame->ring.size);
924 	frame->ring.effective_size = frame->ring.size;
925 	intel_ring_update_space(&frame->ring);
926 	frame->rq.ring = &frame->ring;
927 
928 	mutex_lock(&ce->timeline->mutex);
929 	spin_lock_irq(&engine->sched_engine->lock);
930 
931 	dw = engine->emit_fini_breadcrumb(&frame->rq, frame->cs) - frame->cs;
932 
933 	spin_unlock_irq(&engine->sched_engine->lock);
934 	mutex_unlock(&ce->timeline->mutex);
935 
936 	GEM_BUG_ON(dw & 1); /* RING_TAIL must be qword aligned */
937 
938 	kfree(frame);
939 	return dw;
940 }
941 
942 struct intel_context *
943 intel_engine_create_pinned_context(struct intel_engine_cs *engine,
944 				   struct i915_address_space *vm,
945 				   unsigned int ring_size,
946 				   unsigned int hwsp,
947 				   struct lock_class_key *key,
948 				   const char *name)
949 {
950 	struct intel_context *ce;
951 	int err;
952 
953 	ce = intel_context_create(engine);
954 	if (IS_ERR(ce))
955 		return ce;
956 
957 	__set_bit(CONTEXT_BARRIER_BIT, &ce->flags);
958 	ce->timeline = page_pack_bits(NULL, hwsp);
959 	ce->ring = NULL;
960 	ce->ring_size = ring_size;
961 
962 	i915_vm_put(ce->vm);
963 	ce->vm = i915_vm_get(vm);
964 
965 	err = intel_context_pin(ce); /* perma-pin so it is always available */
966 	if (err) {
967 		intel_context_put(ce);
968 		return ERR_PTR(err);
969 	}
970 
971 	list_add_tail(&ce->pinned_contexts_link, &engine->pinned_contexts_list);
972 
973 	/*
974 	 * Give our perma-pinned kernel timelines a separate lockdep class,
975 	 * so that we can use them from within the normal user timelines
976 	 * should we need to inject GPU operations during their request
977 	 * construction.
978 	 */
979 	lockdep_set_class_and_name(&ce->timeline->mutex, key, name);
980 
981 	return ce;
982 }
983 
984 void intel_engine_destroy_pinned_context(struct intel_context *ce)
985 {
986 	struct intel_engine_cs *engine = ce->engine;
987 	struct i915_vma *hwsp = engine->status_page.vma;
988 
989 	GEM_BUG_ON(ce->timeline->hwsp_ggtt != hwsp);
990 
991 	mutex_lock(&hwsp->vm->mutex);
992 	list_del(&ce->timeline->engine_link);
993 	mutex_unlock(&hwsp->vm->mutex);
994 
995 	list_del(&ce->pinned_contexts_link);
996 	intel_context_unpin(ce);
997 	intel_context_put(ce);
998 }
999 
1000 static struct intel_context *
1001 create_kernel_context(struct intel_engine_cs *engine)
1002 {
1003 	static struct lock_class_key kernel;
1004 
1005 	return intel_engine_create_pinned_context(engine, engine->gt->vm, SZ_4K,
1006 						  I915_GEM_HWS_SEQNO_ADDR,
1007 						  &kernel, "kernel_context");
1008 }
1009 
1010 /**
1011  * intel_engines_init_common - initialize cengine state which might require hw access
1012  * @engine: Engine to initialize.
1013  *
1014  * Initializes @engine@ structure members shared between legacy and execlists
1015  * submission modes which do require hardware access.
1016  *
1017  * Typcally done at later stages of submission mode specific engine setup.
1018  *
1019  * Returns zero on success or an error code on failure.
1020  */
1021 static int engine_init_common(struct intel_engine_cs *engine)
1022 {
1023 	struct intel_context *ce;
1024 	int ret;
1025 
1026 	engine->set_default_submission(engine);
1027 
1028 	/*
1029 	 * We may need to do things with the shrinker which
1030 	 * require us to immediately switch back to the default
1031 	 * context. This can cause a problem as pinning the
1032 	 * default context also requires GTT space which may not
1033 	 * be available. To avoid this we always pin the default
1034 	 * context.
1035 	 */
1036 	ce = create_kernel_context(engine);
1037 	if (IS_ERR(ce))
1038 		return PTR_ERR(ce);
1039 
1040 	ret = measure_breadcrumb_dw(ce);
1041 	if (ret < 0)
1042 		goto err_context;
1043 
1044 	engine->emit_fini_breadcrumb_dw = ret;
1045 	engine->kernel_context = ce;
1046 
1047 	return 0;
1048 
1049 err_context:
1050 	intel_engine_destroy_pinned_context(ce);
1051 	return ret;
1052 }
1053 
1054 int intel_engines_init(struct intel_gt *gt)
1055 {
1056 	int (*setup)(struct intel_engine_cs *engine);
1057 	struct intel_engine_cs *engine;
1058 	enum intel_engine_id id;
1059 	int err;
1060 
1061 	if (intel_uc_uses_guc_submission(&gt->uc)) {
1062 		gt->submission_method = INTEL_SUBMISSION_GUC;
1063 		setup = intel_guc_submission_setup;
1064 	} else if (HAS_EXECLISTS(gt->i915)) {
1065 		gt->submission_method = INTEL_SUBMISSION_ELSP;
1066 		setup = intel_execlists_submission_setup;
1067 	} else {
1068 		gt->submission_method = INTEL_SUBMISSION_RING;
1069 		setup = intel_ring_submission_setup;
1070 	}
1071 
1072 	for_each_engine(engine, gt, id) {
1073 		err = engine_setup_common(engine);
1074 		if (err)
1075 			return err;
1076 
1077 		err = setup(engine);
1078 		if (err)
1079 			return err;
1080 
1081 		err = engine_init_common(engine);
1082 		if (err)
1083 			return err;
1084 
1085 		intel_engine_add_user(engine);
1086 	}
1087 
1088 	return 0;
1089 }
1090 
1091 /**
1092  * intel_engines_cleanup_common - cleans up the engine state created by
1093  *                                the common initiailizers.
1094  * @engine: Engine to cleanup.
1095  *
1096  * This cleans up everything created by the common helpers.
1097  */
1098 void intel_engine_cleanup_common(struct intel_engine_cs *engine)
1099 {
1100 	GEM_BUG_ON(!list_empty(&engine->sched_engine->requests));
1101 
1102 	i915_sched_engine_put(engine->sched_engine);
1103 	intel_breadcrumbs_put(engine->breadcrumbs);
1104 
1105 	intel_engine_fini_retire(engine);
1106 	intel_engine_cleanup_cmd_parser(engine);
1107 
1108 	if (engine->default_state)
1109 		fput(engine->default_state);
1110 
1111 	if (engine->kernel_context)
1112 		intel_engine_destroy_pinned_context(engine->kernel_context);
1113 
1114 	GEM_BUG_ON(!llist_empty(&engine->barrier_tasks));
1115 	cleanup_status_page(engine);
1116 
1117 	intel_wa_list_free(&engine->ctx_wa_list);
1118 	intel_wa_list_free(&engine->wa_list);
1119 	intel_wa_list_free(&engine->whitelist);
1120 }
1121 
1122 /**
1123  * intel_engine_resume - re-initializes the HW state of the engine
1124  * @engine: Engine to resume.
1125  *
1126  * Returns zero on success or an error code on failure.
1127  */
1128 int intel_engine_resume(struct intel_engine_cs *engine)
1129 {
1130 	intel_engine_apply_workarounds(engine);
1131 	intel_engine_apply_whitelist(engine);
1132 
1133 	return engine->resume(engine);
1134 }
1135 
1136 u64 intel_engine_get_active_head(const struct intel_engine_cs *engine)
1137 {
1138 	struct drm_i915_private *i915 = engine->i915;
1139 
1140 	u64 acthd;
1141 
1142 	if (GRAPHICS_VER(i915) >= 8)
1143 		acthd = ENGINE_READ64(engine, RING_ACTHD, RING_ACTHD_UDW);
1144 	else if (GRAPHICS_VER(i915) >= 4)
1145 		acthd = ENGINE_READ(engine, RING_ACTHD);
1146 	else
1147 		acthd = ENGINE_READ(engine, ACTHD);
1148 
1149 	return acthd;
1150 }
1151 
1152 u64 intel_engine_get_last_batch_head(const struct intel_engine_cs *engine)
1153 {
1154 	u64 bbaddr;
1155 
1156 	if (GRAPHICS_VER(engine->i915) >= 8)
1157 		bbaddr = ENGINE_READ64(engine, RING_BBADDR, RING_BBADDR_UDW);
1158 	else
1159 		bbaddr = ENGINE_READ(engine, RING_BBADDR);
1160 
1161 	return bbaddr;
1162 }
1163 
1164 static unsigned long stop_timeout(const struct intel_engine_cs *engine)
1165 {
1166 	if (in_atomic() || irqs_disabled()) /* inside atomic preempt-reset? */
1167 		return 0;
1168 
1169 	/*
1170 	 * If we are doing a normal GPU reset, we can take our time and allow
1171 	 * the engine to quiesce. We've stopped submission to the engine, and
1172 	 * if we wait long enough an innocent context should complete and
1173 	 * leave the engine idle. So they should not be caught unaware by
1174 	 * the forthcoming GPU reset (which usually follows the stop_cs)!
1175 	 */
1176 	return READ_ONCE(engine->props.stop_timeout_ms);
1177 }
1178 
1179 static int __intel_engine_stop_cs(struct intel_engine_cs *engine,
1180 				  int fast_timeout_us,
1181 				  int slow_timeout_ms)
1182 {
1183 	struct intel_uncore *uncore = engine->uncore;
1184 	const i915_reg_t mode = RING_MI_MODE(engine->mmio_base);
1185 	int err;
1186 
1187 	intel_uncore_write_fw(uncore, mode, _MASKED_BIT_ENABLE(STOP_RING));
1188 	err = __intel_wait_for_register_fw(engine->uncore, mode,
1189 					   MODE_IDLE, MODE_IDLE,
1190 					   fast_timeout_us,
1191 					   slow_timeout_ms,
1192 					   NULL);
1193 
1194 	/* A final mmio read to let GPU writes be hopefully flushed to memory */
1195 	intel_uncore_posting_read_fw(uncore, mode);
1196 	return err;
1197 }
1198 
1199 int intel_engine_stop_cs(struct intel_engine_cs *engine)
1200 {
1201 	int err = 0;
1202 
1203 	if (GRAPHICS_VER(engine->i915) < 3)
1204 		return -ENODEV;
1205 
1206 	ENGINE_TRACE(engine, "\n");
1207 	if (__intel_engine_stop_cs(engine, 1000, stop_timeout(engine))) {
1208 		ENGINE_TRACE(engine,
1209 			     "timed out on STOP_RING -> IDLE; HEAD:%04x, TAIL:%04x\n",
1210 			     ENGINE_READ_FW(engine, RING_HEAD) & HEAD_ADDR,
1211 			     ENGINE_READ_FW(engine, RING_TAIL) & TAIL_ADDR);
1212 
1213 		/*
1214 		 * Sometimes we observe that the idle flag is not
1215 		 * set even though the ring is empty. So double
1216 		 * check before giving up.
1217 		 */
1218 		if ((ENGINE_READ_FW(engine, RING_HEAD) & HEAD_ADDR) !=
1219 		    (ENGINE_READ_FW(engine, RING_TAIL) & TAIL_ADDR))
1220 			err = -ETIMEDOUT;
1221 	}
1222 
1223 	return err;
1224 }
1225 
1226 void intel_engine_cancel_stop_cs(struct intel_engine_cs *engine)
1227 {
1228 	ENGINE_TRACE(engine, "\n");
1229 
1230 	ENGINE_WRITE_FW(engine, RING_MI_MODE, _MASKED_BIT_DISABLE(STOP_RING));
1231 }
1232 
1233 static u32
1234 read_subslice_reg(const struct intel_engine_cs *engine,
1235 		  int slice, int subslice, i915_reg_t reg)
1236 {
1237 	return intel_uncore_read_with_mcr_steering(engine->uncore, reg,
1238 						   slice, subslice);
1239 }
1240 
1241 /* NB: please notice the memset */
1242 void intel_engine_get_instdone(const struct intel_engine_cs *engine,
1243 			       struct intel_instdone *instdone)
1244 {
1245 	struct drm_i915_private *i915 = engine->i915;
1246 	const struct sseu_dev_info *sseu = &engine->gt->info.sseu;
1247 	struct intel_uncore *uncore = engine->uncore;
1248 	u32 mmio_base = engine->mmio_base;
1249 	int slice;
1250 	int subslice;
1251 	int iter;
1252 
1253 	memset(instdone, 0, sizeof(*instdone));
1254 
1255 	if (GRAPHICS_VER(i915) >= 8) {
1256 		instdone->instdone =
1257 			intel_uncore_read(uncore, RING_INSTDONE(mmio_base));
1258 
1259 		if (engine->id != RCS0)
1260 			return;
1261 
1262 		instdone->slice_common =
1263 			intel_uncore_read(uncore, GEN7_SC_INSTDONE);
1264 		if (GRAPHICS_VER(i915) >= 12) {
1265 			instdone->slice_common_extra[0] =
1266 				intel_uncore_read(uncore, GEN12_SC_INSTDONE_EXTRA);
1267 			instdone->slice_common_extra[1] =
1268 				intel_uncore_read(uncore, GEN12_SC_INSTDONE_EXTRA2);
1269 		}
1270 
1271 		if (GRAPHICS_VER_FULL(i915) >= IP_VER(12, 50)) {
1272 			for_each_instdone_gslice_dss_xehp(i915, sseu, iter, slice, subslice) {
1273 				instdone->sampler[slice][subslice] =
1274 					read_subslice_reg(engine, slice, subslice,
1275 							  GEN7_SAMPLER_INSTDONE);
1276 				instdone->row[slice][subslice] =
1277 					read_subslice_reg(engine, slice, subslice,
1278 							  GEN7_ROW_INSTDONE);
1279 			}
1280 		} else {
1281 			for_each_instdone_slice_subslice(i915, sseu, slice, subslice) {
1282 				instdone->sampler[slice][subslice] =
1283 					read_subslice_reg(engine, slice, subslice,
1284 							  GEN7_SAMPLER_INSTDONE);
1285 				instdone->row[slice][subslice] =
1286 					read_subslice_reg(engine, slice, subslice,
1287 							  GEN7_ROW_INSTDONE);
1288 			}
1289 		}
1290 
1291 		if (GRAPHICS_VER_FULL(i915) >= IP_VER(12, 55)) {
1292 			for_each_instdone_gslice_dss_xehp(i915, sseu, iter, slice, subslice)
1293 				instdone->geom_svg[slice][subslice] =
1294 					read_subslice_reg(engine, slice, subslice,
1295 							  XEHPG_INSTDONE_GEOM_SVG);
1296 		}
1297 	} else if (GRAPHICS_VER(i915) >= 7) {
1298 		instdone->instdone =
1299 			intel_uncore_read(uncore, RING_INSTDONE(mmio_base));
1300 
1301 		if (engine->id != RCS0)
1302 			return;
1303 
1304 		instdone->slice_common =
1305 			intel_uncore_read(uncore, GEN7_SC_INSTDONE);
1306 		instdone->sampler[0][0] =
1307 			intel_uncore_read(uncore, GEN7_SAMPLER_INSTDONE);
1308 		instdone->row[0][0] =
1309 			intel_uncore_read(uncore, GEN7_ROW_INSTDONE);
1310 	} else if (GRAPHICS_VER(i915) >= 4) {
1311 		instdone->instdone =
1312 			intel_uncore_read(uncore, RING_INSTDONE(mmio_base));
1313 		if (engine->id == RCS0)
1314 			/* HACK: Using the wrong struct member */
1315 			instdone->slice_common =
1316 				intel_uncore_read(uncore, GEN4_INSTDONE1);
1317 	} else {
1318 		instdone->instdone = intel_uncore_read(uncore, GEN2_INSTDONE);
1319 	}
1320 }
1321 
1322 static bool ring_is_idle(struct intel_engine_cs *engine)
1323 {
1324 	bool idle = true;
1325 
1326 	if (I915_SELFTEST_ONLY(!engine->mmio_base))
1327 		return true;
1328 
1329 	if (!intel_engine_pm_get_if_awake(engine))
1330 		return true;
1331 
1332 	/* First check that no commands are left in the ring */
1333 	if ((ENGINE_READ(engine, RING_HEAD) & HEAD_ADDR) !=
1334 	    (ENGINE_READ(engine, RING_TAIL) & TAIL_ADDR))
1335 		idle = false;
1336 
1337 	/* No bit for gen2, so assume the CS parser is idle */
1338 	if (GRAPHICS_VER(engine->i915) > 2 &&
1339 	    !(ENGINE_READ(engine, RING_MI_MODE) & MODE_IDLE))
1340 		idle = false;
1341 
1342 	intel_engine_pm_put(engine);
1343 
1344 	return idle;
1345 }
1346 
1347 void __intel_engine_flush_submission(struct intel_engine_cs *engine, bool sync)
1348 {
1349 	struct tasklet_struct *t = &engine->sched_engine->tasklet;
1350 
1351 	if (!t->callback)
1352 		return;
1353 
1354 	local_bh_disable();
1355 	if (tasklet_trylock(t)) {
1356 		/* Must wait for any GPU reset in progress. */
1357 		if (__tasklet_is_enabled(t))
1358 			t->callback(t);
1359 		tasklet_unlock(t);
1360 	}
1361 	local_bh_enable();
1362 
1363 	/* Synchronise and wait for the tasklet on another CPU */
1364 	if (sync)
1365 		tasklet_unlock_wait(t);
1366 }
1367 
1368 /**
1369  * intel_engine_is_idle() - Report if the engine has finished process all work
1370  * @engine: the intel_engine_cs
1371  *
1372  * Return true if there are no requests pending, nothing left to be submitted
1373  * to hardware, and that the engine is idle.
1374  */
1375 bool intel_engine_is_idle(struct intel_engine_cs *engine)
1376 {
1377 	/* More white lies, if wedged, hw state is inconsistent */
1378 	if (intel_gt_is_wedged(engine->gt))
1379 		return true;
1380 
1381 	if (!intel_engine_pm_is_awake(engine))
1382 		return true;
1383 
1384 	/* Waiting to drain ELSP? */
1385 	intel_synchronize_hardirq(engine->i915);
1386 	intel_engine_flush_submission(engine);
1387 
1388 	/* ELSP is empty, but there are ready requests? E.g. after reset */
1389 	if (!i915_sched_engine_is_empty(engine->sched_engine))
1390 		return false;
1391 
1392 	/* Ring stopped? */
1393 	return ring_is_idle(engine);
1394 }
1395 
1396 bool intel_engines_are_idle(struct intel_gt *gt)
1397 {
1398 	struct intel_engine_cs *engine;
1399 	enum intel_engine_id id;
1400 
1401 	/*
1402 	 * If the driver is wedged, HW state may be very inconsistent and
1403 	 * report that it is still busy, even though we have stopped using it.
1404 	 */
1405 	if (intel_gt_is_wedged(gt))
1406 		return true;
1407 
1408 	/* Already parked (and passed an idleness test); must still be idle */
1409 	if (!READ_ONCE(gt->awake))
1410 		return true;
1411 
1412 	for_each_engine(engine, gt, id) {
1413 		if (!intel_engine_is_idle(engine))
1414 			return false;
1415 	}
1416 
1417 	return true;
1418 }
1419 
1420 bool intel_engine_irq_enable(struct intel_engine_cs *engine)
1421 {
1422 	if (!engine->irq_enable)
1423 		return false;
1424 
1425 	/* Caller disables interrupts */
1426 	spin_lock(&engine->gt->irq_lock);
1427 	engine->irq_enable(engine);
1428 	spin_unlock(&engine->gt->irq_lock);
1429 
1430 	return true;
1431 }
1432 
1433 void intel_engine_irq_disable(struct intel_engine_cs *engine)
1434 {
1435 	if (!engine->irq_disable)
1436 		return;
1437 
1438 	/* Caller disables interrupts */
1439 	spin_lock(&engine->gt->irq_lock);
1440 	engine->irq_disable(engine);
1441 	spin_unlock(&engine->gt->irq_lock);
1442 }
1443 
1444 void intel_engines_reset_default_submission(struct intel_gt *gt)
1445 {
1446 	struct intel_engine_cs *engine;
1447 	enum intel_engine_id id;
1448 
1449 	for_each_engine(engine, gt, id) {
1450 		if (engine->sanitize)
1451 			engine->sanitize(engine);
1452 
1453 		engine->set_default_submission(engine);
1454 	}
1455 }
1456 
1457 bool intel_engine_can_store_dword(struct intel_engine_cs *engine)
1458 {
1459 	switch (GRAPHICS_VER(engine->i915)) {
1460 	case 2:
1461 		return false; /* uses physical not virtual addresses */
1462 	case 3:
1463 		/* maybe only uses physical not virtual addresses */
1464 		return !(IS_I915G(engine->i915) || IS_I915GM(engine->i915));
1465 	case 4:
1466 		return !IS_I965G(engine->i915); /* who knows! */
1467 	case 6:
1468 		return engine->class != VIDEO_DECODE_CLASS; /* b0rked */
1469 	default:
1470 		return true;
1471 	}
1472 }
1473 
1474 static struct intel_timeline *get_timeline(struct i915_request *rq)
1475 {
1476 	struct intel_timeline *tl;
1477 
1478 	/*
1479 	 * Even though we are holding the engine->sched_engine->lock here, there
1480 	 * is no control over the submission queue per-se and we are
1481 	 * inspecting the active state at a random point in time, with an
1482 	 * unknown queue. Play safe and make sure the timeline remains valid.
1483 	 * (Only being used for pretty printing, one extra kref shouldn't
1484 	 * cause a camel stampede!)
1485 	 */
1486 	rcu_read_lock();
1487 	tl = rcu_dereference(rq->timeline);
1488 	if (!kref_get_unless_zero(&tl->kref))
1489 		tl = NULL;
1490 	rcu_read_unlock();
1491 
1492 	return tl;
1493 }
1494 
1495 static int print_ring(char *buf, int sz, struct i915_request *rq)
1496 {
1497 	int len = 0;
1498 
1499 	if (!i915_request_signaled(rq)) {
1500 		struct intel_timeline *tl = get_timeline(rq);
1501 
1502 		len = scnprintf(buf, sz,
1503 				"ring:{start:%08x, hwsp:%08x, seqno:%08x, runtime:%llums}, ",
1504 				i915_ggtt_offset(rq->ring->vma),
1505 				tl ? tl->hwsp_offset : 0,
1506 				hwsp_seqno(rq),
1507 				DIV_ROUND_CLOSEST_ULL(intel_context_get_total_runtime_ns(rq->context),
1508 						      1000 * 1000));
1509 
1510 		if (tl)
1511 			intel_timeline_put(tl);
1512 	}
1513 
1514 	return len;
1515 }
1516 
1517 static void hexdump(struct drm_printer *m, const void *buf, size_t len)
1518 {
1519 	const size_t rowsize = 8 * sizeof(u32);
1520 	const void *prev = NULL;
1521 	bool skip = false;
1522 	size_t pos;
1523 
1524 	for (pos = 0; pos < len; pos += rowsize) {
1525 		char line[128];
1526 
1527 		if (prev && !memcmp(prev, buf + pos, rowsize)) {
1528 			if (!skip) {
1529 				drm_printf(m, "*\n");
1530 				skip = true;
1531 			}
1532 			continue;
1533 		}
1534 
1535 		WARN_ON_ONCE(hex_dump_to_buffer(buf + pos, len - pos,
1536 						rowsize, sizeof(u32),
1537 						line, sizeof(line),
1538 						false) >= sizeof(line));
1539 		drm_printf(m, "[%04zx] %s\n", pos, line);
1540 
1541 		prev = buf + pos;
1542 		skip = false;
1543 	}
1544 }
1545 
1546 static const char *repr_timer(const struct timer_list *t)
1547 {
1548 	if (!READ_ONCE(t->expires))
1549 		return "inactive";
1550 
1551 	if (timer_pending(t))
1552 		return "active";
1553 
1554 	return "expired";
1555 }
1556 
1557 static void intel_engine_print_registers(struct intel_engine_cs *engine,
1558 					 struct drm_printer *m)
1559 {
1560 	struct drm_i915_private *dev_priv = engine->i915;
1561 	struct intel_engine_execlists * const execlists = &engine->execlists;
1562 	u64 addr;
1563 
1564 	if (engine->id == RENDER_CLASS && IS_GRAPHICS_VER(dev_priv, 4, 7))
1565 		drm_printf(m, "\tCCID: 0x%08x\n", ENGINE_READ(engine, CCID));
1566 	if (HAS_EXECLISTS(dev_priv)) {
1567 		drm_printf(m, "\tEL_STAT_HI: 0x%08x\n",
1568 			   ENGINE_READ(engine, RING_EXECLIST_STATUS_HI));
1569 		drm_printf(m, "\tEL_STAT_LO: 0x%08x\n",
1570 			   ENGINE_READ(engine, RING_EXECLIST_STATUS_LO));
1571 	}
1572 	drm_printf(m, "\tRING_START: 0x%08x\n",
1573 		   ENGINE_READ(engine, RING_START));
1574 	drm_printf(m, "\tRING_HEAD:  0x%08x\n",
1575 		   ENGINE_READ(engine, RING_HEAD) & HEAD_ADDR);
1576 	drm_printf(m, "\tRING_TAIL:  0x%08x\n",
1577 		   ENGINE_READ(engine, RING_TAIL) & TAIL_ADDR);
1578 	drm_printf(m, "\tRING_CTL:   0x%08x%s\n",
1579 		   ENGINE_READ(engine, RING_CTL),
1580 		   ENGINE_READ(engine, RING_CTL) & (RING_WAIT | RING_WAIT_SEMAPHORE) ? " [waiting]" : "");
1581 	if (GRAPHICS_VER(engine->i915) > 2) {
1582 		drm_printf(m, "\tRING_MODE:  0x%08x%s\n",
1583 			   ENGINE_READ(engine, RING_MI_MODE),
1584 			   ENGINE_READ(engine, RING_MI_MODE) & (MODE_IDLE) ? " [idle]" : "");
1585 	}
1586 
1587 	if (GRAPHICS_VER(dev_priv) >= 6) {
1588 		drm_printf(m, "\tRING_IMR:   0x%08x\n",
1589 			   ENGINE_READ(engine, RING_IMR));
1590 		drm_printf(m, "\tRING_ESR:   0x%08x\n",
1591 			   ENGINE_READ(engine, RING_ESR));
1592 		drm_printf(m, "\tRING_EMR:   0x%08x\n",
1593 			   ENGINE_READ(engine, RING_EMR));
1594 		drm_printf(m, "\tRING_EIR:   0x%08x\n",
1595 			   ENGINE_READ(engine, RING_EIR));
1596 	}
1597 
1598 	addr = intel_engine_get_active_head(engine);
1599 	drm_printf(m, "\tACTHD:  0x%08x_%08x\n",
1600 		   upper_32_bits(addr), lower_32_bits(addr));
1601 	addr = intel_engine_get_last_batch_head(engine);
1602 	drm_printf(m, "\tBBADDR: 0x%08x_%08x\n",
1603 		   upper_32_bits(addr), lower_32_bits(addr));
1604 	if (GRAPHICS_VER(dev_priv) >= 8)
1605 		addr = ENGINE_READ64(engine, RING_DMA_FADD, RING_DMA_FADD_UDW);
1606 	else if (GRAPHICS_VER(dev_priv) >= 4)
1607 		addr = ENGINE_READ(engine, RING_DMA_FADD);
1608 	else
1609 		addr = ENGINE_READ(engine, DMA_FADD_I8XX);
1610 	drm_printf(m, "\tDMA_FADDR: 0x%08x_%08x\n",
1611 		   upper_32_bits(addr), lower_32_bits(addr));
1612 	if (GRAPHICS_VER(dev_priv) >= 4) {
1613 		drm_printf(m, "\tIPEIR: 0x%08x\n",
1614 			   ENGINE_READ(engine, RING_IPEIR));
1615 		drm_printf(m, "\tIPEHR: 0x%08x\n",
1616 			   ENGINE_READ(engine, RING_IPEHR));
1617 	} else {
1618 		drm_printf(m, "\tIPEIR: 0x%08x\n", ENGINE_READ(engine, IPEIR));
1619 		drm_printf(m, "\tIPEHR: 0x%08x\n", ENGINE_READ(engine, IPEHR));
1620 	}
1621 
1622 	if (intel_engine_uses_guc(engine)) {
1623 		/* nothing to print yet */
1624 	} else if (HAS_EXECLISTS(dev_priv)) {
1625 		struct i915_request * const *port, *rq;
1626 		const u32 *hws =
1627 			&engine->status_page.addr[I915_HWS_CSB_BUF0_INDEX];
1628 		const u8 num_entries = execlists->csb_size;
1629 		unsigned int idx;
1630 		u8 read, write;
1631 
1632 		drm_printf(m, "\tExeclist tasklet queued? %s (%s), preempt? %s, timeslice? %s\n",
1633 			   yesno(test_bit(TASKLET_STATE_SCHED,
1634 					  &engine->sched_engine->tasklet.state)),
1635 			   enableddisabled(!atomic_read(&engine->sched_engine->tasklet.count)),
1636 			   repr_timer(&engine->execlists.preempt),
1637 			   repr_timer(&engine->execlists.timer));
1638 
1639 		read = execlists->csb_head;
1640 		write = READ_ONCE(*execlists->csb_write);
1641 
1642 		drm_printf(m, "\tExeclist status: 0x%08x %08x; CSB read:%d, write:%d, entries:%d\n",
1643 			   ENGINE_READ(engine, RING_EXECLIST_STATUS_LO),
1644 			   ENGINE_READ(engine, RING_EXECLIST_STATUS_HI),
1645 			   read, write, num_entries);
1646 
1647 		if (read >= num_entries)
1648 			read = 0;
1649 		if (write >= num_entries)
1650 			write = 0;
1651 		if (read > write)
1652 			write += num_entries;
1653 		while (read < write) {
1654 			idx = ++read % num_entries;
1655 			drm_printf(m, "\tExeclist CSB[%d]: 0x%08x, context: %d\n",
1656 				   idx, hws[idx * 2], hws[idx * 2 + 1]);
1657 		}
1658 
1659 		i915_sched_engine_active_lock_bh(engine->sched_engine);
1660 		rcu_read_lock();
1661 		for (port = execlists->active; (rq = *port); port++) {
1662 			char hdr[160];
1663 			int len;
1664 
1665 			len = scnprintf(hdr, sizeof(hdr),
1666 					"\t\tActive[%d]:  ccid:%08x%s%s, ",
1667 					(int)(port - execlists->active),
1668 					rq->context->lrc.ccid,
1669 					intel_context_is_closed(rq->context) ? "!" : "",
1670 					intel_context_is_banned(rq->context) ? "*" : "");
1671 			len += print_ring(hdr + len, sizeof(hdr) - len, rq);
1672 			scnprintf(hdr + len, sizeof(hdr) - len, "rq: ");
1673 			i915_request_show(m, rq, hdr, 0);
1674 		}
1675 		for (port = execlists->pending; (rq = *port); port++) {
1676 			char hdr[160];
1677 			int len;
1678 
1679 			len = scnprintf(hdr, sizeof(hdr),
1680 					"\t\tPending[%d]: ccid:%08x%s%s, ",
1681 					(int)(port - execlists->pending),
1682 					rq->context->lrc.ccid,
1683 					intel_context_is_closed(rq->context) ? "!" : "",
1684 					intel_context_is_banned(rq->context) ? "*" : "");
1685 			len += print_ring(hdr + len, sizeof(hdr) - len, rq);
1686 			scnprintf(hdr + len, sizeof(hdr) - len, "rq: ");
1687 			i915_request_show(m, rq, hdr, 0);
1688 		}
1689 		rcu_read_unlock();
1690 		i915_sched_engine_active_unlock_bh(engine->sched_engine);
1691 	} else if (GRAPHICS_VER(dev_priv) > 6) {
1692 		drm_printf(m, "\tPP_DIR_BASE: 0x%08x\n",
1693 			   ENGINE_READ(engine, RING_PP_DIR_BASE));
1694 		drm_printf(m, "\tPP_DIR_BASE_READ: 0x%08x\n",
1695 			   ENGINE_READ(engine, RING_PP_DIR_BASE_READ));
1696 		drm_printf(m, "\tPP_DIR_DCLV: 0x%08x\n",
1697 			   ENGINE_READ(engine, RING_PP_DIR_DCLV));
1698 	}
1699 }
1700 
1701 static void print_request_ring(struct drm_printer *m, struct i915_request *rq)
1702 {
1703 	struct i915_vma_resource *vma_res = rq->batch_res;
1704 	void *ring;
1705 	int size;
1706 
1707 	drm_printf(m,
1708 		   "[head %04x, postfix %04x, tail %04x, batch 0x%08x_%08x]:\n",
1709 		   rq->head, rq->postfix, rq->tail,
1710 		   vma_res ? upper_32_bits(vma_res->start) : ~0u,
1711 		   vma_res ? lower_32_bits(vma_res->start) : ~0u);
1712 
1713 	size = rq->tail - rq->head;
1714 	if (rq->tail < rq->head)
1715 		size += rq->ring->size;
1716 
1717 	ring = kmalloc(size, GFP_ATOMIC);
1718 	if (ring) {
1719 		const void *vaddr = rq->ring->vaddr;
1720 		unsigned int head = rq->head;
1721 		unsigned int len = 0;
1722 
1723 		if (rq->tail < head) {
1724 			len = rq->ring->size - head;
1725 			memcpy(ring, vaddr + head, len);
1726 			head = 0;
1727 		}
1728 		memcpy(ring + len, vaddr + head, size - len);
1729 
1730 		hexdump(m, ring, size);
1731 		kfree(ring);
1732 	}
1733 }
1734 
1735 static unsigned long list_count(struct list_head *list)
1736 {
1737 	struct list_head *pos;
1738 	unsigned long count = 0;
1739 
1740 	list_for_each(pos, list)
1741 		count++;
1742 
1743 	return count;
1744 }
1745 
1746 static unsigned long read_ul(void *p, size_t x)
1747 {
1748 	return *(unsigned long *)(p + x);
1749 }
1750 
1751 static void print_properties(struct intel_engine_cs *engine,
1752 			     struct drm_printer *m)
1753 {
1754 	static const struct pmap {
1755 		size_t offset;
1756 		const char *name;
1757 	} props[] = {
1758 #define P(x) { \
1759 	.offset = offsetof(typeof(engine->props), x), \
1760 	.name = #x \
1761 }
1762 		P(heartbeat_interval_ms),
1763 		P(max_busywait_duration_ns),
1764 		P(preempt_timeout_ms),
1765 		P(stop_timeout_ms),
1766 		P(timeslice_duration_ms),
1767 
1768 		{},
1769 #undef P
1770 	};
1771 	const struct pmap *p;
1772 
1773 	drm_printf(m, "\tProperties:\n");
1774 	for (p = props; p->name; p++)
1775 		drm_printf(m, "\t\t%s: %lu [default %lu]\n",
1776 			   p->name,
1777 			   read_ul(&engine->props, p->offset),
1778 			   read_ul(&engine->defaults, p->offset));
1779 }
1780 
1781 static void engine_dump_request(struct i915_request *rq, struct drm_printer *m, const char *msg)
1782 {
1783 	struct intel_timeline *tl = get_timeline(rq);
1784 
1785 	i915_request_show(m, rq, msg, 0);
1786 
1787 	drm_printf(m, "\t\tring->start:  0x%08x\n",
1788 		   i915_ggtt_offset(rq->ring->vma));
1789 	drm_printf(m, "\t\tring->head:   0x%08x\n",
1790 		   rq->ring->head);
1791 	drm_printf(m, "\t\tring->tail:   0x%08x\n",
1792 		   rq->ring->tail);
1793 	drm_printf(m, "\t\tring->emit:   0x%08x\n",
1794 		   rq->ring->emit);
1795 	drm_printf(m, "\t\tring->space:  0x%08x\n",
1796 		   rq->ring->space);
1797 
1798 	if (tl) {
1799 		drm_printf(m, "\t\tring->hwsp:   0x%08x\n",
1800 			   tl->hwsp_offset);
1801 		intel_timeline_put(tl);
1802 	}
1803 
1804 	print_request_ring(m, rq);
1805 
1806 	if (rq->context->lrc_reg_state) {
1807 		drm_printf(m, "Logical Ring Context:\n");
1808 		hexdump(m, rq->context->lrc_reg_state, PAGE_SIZE);
1809 	}
1810 }
1811 
1812 void intel_engine_dump_active_requests(struct list_head *requests,
1813 				       struct i915_request *hung_rq,
1814 				       struct drm_printer *m)
1815 {
1816 	struct i915_request *rq;
1817 	const char *msg;
1818 	enum i915_request_state state;
1819 
1820 	list_for_each_entry(rq, requests, sched.link) {
1821 		if (rq == hung_rq)
1822 			continue;
1823 
1824 		state = i915_test_request_state(rq);
1825 		if (state < I915_REQUEST_QUEUED)
1826 			continue;
1827 
1828 		if (state == I915_REQUEST_ACTIVE)
1829 			msg = "\t\tactive on engine";
1830 		else
1831 			msg = "\t\tactive in queue";
1832 
1833 		engine_dump_request(rq, m, msg);
1834 	}
1835 }
1836 
1837 static void engine_dump_active_requests(struct intel_engine_cs *engine, struct drm_printer *m)
1838 {
1839 	struct i915_request *hung_rq = NULL;
1840 	struct intel_context *ce;
1841 	bool guc;
1842 
1843 	/*
1844 	 * No need for an engine->irq_seqno_barrier() before the seqno reads.
1845 	 * The GPU is still running so requests are still executing and any
1846 	 * hardware reads will be out of date by the time they are reported.
1847 	 * But the intention here is just to report an instantaneous snapshot
1848 	 * so that's fine.
1849 	 */
1850 	lockdep_assert_held(&engine->sched_engine->lock);
1851 
1852 	drm_printf(m, "\tRequests:\n");
1853 
1854 	guc = intel_uc_uses_guc_submission(&engine->gt->uc);
1855 	if (guc) {
1856 		ce = intel_engine_get_hung_context(engine);
1857 		if (ce)
1858 			hung_rq = intel_context_find_active_request(ce);
1859 	} else {
1860 		hung_rq = intel_engine_execlist_find_hung_request(engine);
1861 	}
1862 
1863 	if (hung_rq)
1864 		engine_dump_request(hung_rq, m, "\t\thung");
1865 
1866 	if (guc)
1867 		intel_guc_dump_active_requests(engine, hung_rq, m);
1868 	else
1869 		intel_engine_dump_active_requests(&engine->sched_engine->requests,
1870 						  hung_rq, m);
1871 }
1872 
1873 void intel_engine_dump(struct intel_engine_cs *engine,
1874 		       struct drm_printer *m,
1875 		       const char *header, ...)
1876 {
1877 	struct i915_gpu_error * const error = &engine->i915->gpu_error;
1878 	struct i915_request *rq;
1879 	intel_wakeref_t wakeref;
1880 	unsigned long flags;
1881 	ktime_t dummy;
1882 
1883 	if (header) {
1884 		va_list ap;
1885 
1886 		va_start(ap, header);
1887 		drm_vprintf(m, header, &ap);
1888 		va_end(ap);
1889 	}
1890 
1891 	if (intel_gt_is_wedged(engine->gt))
1892 		drm_printf(m, "*** WEDGED ***\n");
1893 
1894 	drm_printf(m, "\tAwake? %d\n", atomic_read(&engine->wakeref.count));
1895 	drm_printf(m, "\tBarriers?: %s\n",
1896 		   yesno(!llist_empty(&engine->barrier_tasks)));
1897 	drm_printf(m, "\tLatency: %luus\n",
1898 		   ewma__engine_latency_read(&engine->latency));
1899 	if (intel_engine_supports_stats(engine))
1900 		drm_printf(m, "\tRuntime: %llums\n",
1901 			   ktime_to_ms(intel_engine_get_busy_time(engine,
1902 								  &dummy)));
1903 	drm_printf(m, "\tForcewake: %x domains, %d active\n",
1904 		   engine->fw_domain, READ_ONCE(engine->fw_active));
1905 
1906 	rcu_read_lock();
1907 	rq = READ_ONCE(engine->heartbeat.systole);
1908 	if (rq)
1909 		drm_printf(m, "\tHeartbeat: %d ms ago\n",
1910 			   jiffies_to_msecs(jiffies - rq->emitted_jiffies));
1911 	rcu_read_unlock();
1912 	drm_printf(m, "\tReset count: %d (global %d)\n",
1913 		   i915_reset_engine_count(error, engine),
1914 		   i915_reset_count(error));
1915 	print_properties(engine, m);
1916 
1917 	spin_lock_irqsave(&engine->sched_engine->lock, flags);
1918 	engine_dump_active_requests(engine, m);
1919 
1920 	drm_printf(m, "\tOn hold?: %lu\n",
1921 		   list_count(&engine->sched_engine->hold));
1922 	spin_unlock_irqrestore(&engine->sched_engine->lock, flags);
1923 
1924 	drm_printf(m, "\tMMIO base:  0x%08x\n", engine->mmio_base);
1925 	wakeref = intel_runtime_pm_get_if_in_use(engine->uncore->rpm);
1926 	if (wakeref) {
1927 		intel_engine_print_registers(engine, m);
1928 		intel_runtime_pm_put(engine->uncore->rpm, wakeref);
1929 	} else {
1930 		drm_printf(m, "\tDevice is asleep; skipping register dump\n");
1931 	}
1932 
1933 	intel_execlists_show_requests(engine, m, i915_request_show, 8);
1934 
1935 	drm_printf(m, "HWSP:\n");
1936 	hexdump(m, engine->status_page.addr, PAGE_SIZE);
1937 
1938 	drm_printf(m, "Idle? %s\n", yesno(intel_engine_is_idle(engine)));
1939 
1940 	intel_engine_print_breadcrumbs(engine, m);
1941 }
1942 
1943 /**
1944  * intel_engine_get_busy_time() - Return current accumulated engine busyness
1945  * @engine: engine to report on
1946  * @now: monotonic timestamp of sampling
1947  *
1948  * Returns accumulated time @engine was busy since engine stats were enabled.
1949  */
1950 ktime_t intel_engine_get_busy_time(struct intel_engine_cs *engine, ktime_t *now)
1951 {
1952 	return engine->busyness(engine, now);
1953 }
1954 
1955 struct intel_context *
1956 intel_engine_create_virtual(struct intel_engine_cs **siblings,
1957 			    unsigned int count, unsigned long flags)
1958 {
1959 	if (count == 0)
1960 		return ERR_PTR(-EINVAL);
1961 
1962 	if (count == 1 && !(flags & FORCE_VIRTUAL))
1963 		return intel_context_create(siblings[0]);
1964 
1965 	GEM_BUG_ON(!siblings[0]->cops->create_virtual);
1966 	return siblings[0]->cops->create_virtual(siblings, count, flags);
1967 }
1968 
1969 struct i915_request *
1970 intel_engine_execlist_find_hung_request(struct intel_engine_cs *engine)
1971 {
1972 	struct i915_request *request, *active = NULL;
1973 
1974 	/*
1975 	 * This search does not work in GuC submission mode. However, the GuC
1976 	 * will report the hanging context directly to the driver itself. So
1977 	 * the driver should never get here when in GuC mode.
1978 	 */
1979 	GEM_BUG_ON(intel_uc_uses_guc_submission(&engine->gt->uc));
1980 
1981 	/*
1982 	 * We are called by the error capture, reset and to dump engine
1983 	 * state at random points in time. In particular, note that neither is
1984 	 * crucially ordered with an interrupt. After a hang, the GPU is dead
1985 	 * and we assume that no more writes can happen (we waited long enough
1986 	 * for all writes that were in transaction to be flushed) - adding an
1987 	 * extra delay for a recent interrupt is pointless. Hence, we do
1988 	 * not need an engine->irq_seqno_barrier() before the seqno reads.
1989 	 * At all other times, we must assume the GPU is still running, but
1990 	 * we only care about the snapshot of this moment.
1991 	 */
1992 	lockdep_assert_held(&engine->sched_engine->lock);
1993 
1994 	rcu_read_lock();
1995 	request = execlists_active(&engine->execlists);
1996 	if (request) {
1997 		struct intel_timeline *tl = request->context->timeline;
1998 
1999 		list_for_each_entry_from_reverse(request, &tl->requests, link) {
2000 			if (__i915_request_is_complete(request))
2001 				break;
2002 
2003 			active = request;
2004 		}
2005 	}
2006 	rcu_read_unlock();
2007 	if (active)
2008 		return active;
2009 
2010 	list_for_each_entry(request, &engine->sched_engine->requests,
2011 			    sched.link) {
2012 		if (i915_test_request_state(request) != I915_REQUEST_ACTIVE)
2013 			continue;
2014 
2015 		active = request;
2016 		break;
2017 	}
2018 
2019 	return active;
2020 }
2021 
2022 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
2023 #include "mock_engine.c"
2024 #include "selftest_engine.c"
2025 #include "selftest_engine_cs.c"
2026 #endif
2027