1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright © 2016 Intel Corporation
4  */
5 
6 #include <linux/string_helpers.h>
7 
8 #include <drm/drm_print.h>
9 
10 #include "gem/i915_gem_context.h"
11 #include "gem/i915_gem_internal.h"
12 #include "gt/intel_gt_print.h"
13 #include "gt/intel_gt_regs.h"
14 
15 #include "i915_cmd_parser.h"
16 #include "i915_drv.h"
17 #include "i915_irq.h"
18 #include "i915_reg.h"
19 #include "intel_breadcrumbs.h"
20 #include "intel_context.h"
21 #include "intel_engine.h"
22 #include "intel_engine_pm.h"
23 #include "intel_engine_regs.h"
24 #include "intel_engine_user.h"
25 #include "intel_execlists_submission.h"
26 #include "intel_gt.h"
27 #include "intel_gt_mcr.h"
28 #include "intel_gt_pm.h"
29 #include "intel_gt_requests.h"
30 #include "intel_lrc.h"
31 #include "intel_lrc_reg.h"
32 #include "intel_reset.h"
33 #include "intel_ring.h"
34 #include "uc/intel_guc_submission.h"
35 
36 /* Haswell does have the CXT_SIZE register however it does not appear to be
37  * valid. Now, docs explain in dwords what is in the context object. The full
38  * size is 70720 bytes, however, the power context and execlist context will
39  * never be saved (power context is stored elsewhere, and execlists don't work
40  * on HSW) - so the final size, including the extra state required for the
41  * Resource Streamer, is 66944 bytes, which rounds to 17 pages.
42  */
43 #define HSW_CXT_TOTAL_SIZE		(17 * PAGE_SIZE)
44 
45 #define DEFAULT_LR_CONTEXT_RENDER_SIZE	(22 * PAGE_SIZE)
46 #define GEN8_LR_CONTEXT_RENDER_SIZE	(20 * PAGE_SIZE)
47 #define GEN9_LR_CONTEXT_RENDER_SIZE	(22 * PAGE_SIZE)
48 #define GEN11_LR_CONTEXT_RENDER_SIZE	(14 * PAGE_SIZE)
49 
50 #define GEN8_LR_CONTEXT_OTHER_SIZE	( 2 * PAGE_SIZE)
51 
52 #define MAX_MMIO_BASES 3
53 struct engine_info {
54 	u8 class;
55 	u8 instance;
56 	/* mmio bases table *must* be sorted in reverse graphics_ver order */
57 	struct engine_mmio_base {
58 		u32 graphics_ver : 8;
59 		u32 base : 24;
60 	} mmio_bases[MAX_MMIO_BASES];
61 };
62 
63 static const struct engine_info intel_engines[] = {
64 	[RCS0] = {
65 		.class = RENDER_CLASS,
66 		.instance = 0,
67 		.mmio_bases = {
68 			{ .graphics_ver = 1, .base = RENDER_RING_BASE }
69 		},
70 	},
71 	[BCS0] = {
72 		.class = COPY_ENGINE_CLASS,
73 		.instance = 0,
74 		.mmio_bases = {
75 			{ .graphics_ver = 6, .base = BLT_RING_BASE }
76 		},
77 	},
78 	[BCS1] = {
79 		.class = COPY_ENGINE_CLASS,
80 		.instance = 1,
81 		.mmio_bases = {
82 			{ .graphics_ver = 12, .base = XEHPC_BCS1_RING_BASE }
83 		},
84 	},
85 	[BCS2] = {
86 		.class = COPY_ENGINE_CLASS,
87 		.instance = 2,
88 		.mmio_bases = {
89 			{ .graphics_ver = 12, .base = XEHPC_BCS2_RING_BASE }
90 		},
91 	},
92 	[BCS3] = {
93 		.class = COPY_ENGINE_CLASS,
94 		.instance = 3,
95 		.mmio_bases = {
96 			{ .graphics_ver = 12, .base = XEHPC_BCS3_RING_BASE }
97 		},
98 	},
99 	[BCS4] = {
100 		.class = COPY_ENGINE_CLASS,
101 		.instance = 4,
102 		.mmio_bases = {
103 			{ .graphics_ver = 12, .base = XEHPC_BCS4_RING_BASE }
104 		},
105 	},
106 	[BCS5] = {
107 		.class = COPY_ENGINE_CLASS,
108 		.instance = 5,
109 		.mmio_bases = {
110 			{ .graphics_ver = 12, .base = XEHPC_BCS5_RING_BASE }
111 		},
112 	},
113 	[BCS6] = {
114 		.class = COPY_ENGINE_CLASS,
115 		.instance = 6,
116 		.mmio_bases = {
117 			{ .graphics_ver = 12, .base = XEHPC_BCS6_RING_BASE }
118 		},
119 	},
120 	[BCS7] = {
121 		.class = COPY_ENGINE_CLASS,
122 		.instance = 7,
123 		.mmio_bases = {
124 			{ .graphics_ver = 12, .base = XEHPC_BCS7_RING_BASE }
125 		},
126 	},
127 	[BCS8] = {
128 		.class = COPY_ENGINE_CLASS,
129 		.instance = 8,
130 		.mmio_bases = {
131 			{ .graphics_ver = 12, .base = XEHPC_BCS8_RING_BASE }
132 		},
133 	},
134 	[VCS0] = {
135 		.class = VIDEO_DECODE_CLASS,
136 		.instance = 0,
137 		.mmio_bases = {
138 			{ .graphics_ver = 11, .base = GEN11_BSD_RING_BASE },
139 			{ .graphics_ver = 6, .base = GEN6_BSD_RING_BASE },
140 			{ .graphics_ver = 4, .base = BSD_RING_BASE }
141 		},
142 	},
143 	[VCS1] = {
144 		.class = VIDEO_DECODE_CLASS,
145 		.instance = 1,
146 		.mmio_bases = {
147 			{ .graphics_ver = 11, .base = GEN11_BSD2_RING_BASE },
148 			{ .graphics_ver = 8, .base = GEN8_BSD2_RING_BASE }
149 		},
150 	},
151 	[VCS2] = {
152 		.class = VIDEO_DECODE_CLASS,
153 		.instance = 2,
154 		.mmio_bases = {
155 			{ .graphics_ver = 11, .base = GEN11_BSD3_RING_BASE }
156 		},
157 	},
158 	[VCS3] = {
159 		.class = VIDEO_DECODE_CLASS,
160 		.instance = 3,
161 		.mmio_bases = {
162 			{ .graphics_ver = 11, .base = GEN11_BSD4_RING_BASE }
163 		},
164 	},
165 	[VCS4] = {
166 		.class = VIDEO_DECODE_CLASS,
167 		.instance = 4,
168 		.mmio_bases = {
169 			{ .graphics_ver = 12, .base = XEHP_BSD5_RING_BASE }
170 		},
171 	},
172 	[VCS5] = {
173 		.class = VIDEO_DECODE_CLASS,
174 		.instance = 5,
175 		.mmio_bases = {
176 			{ .graphics_ver = 12, .base = XEHP_BSD6_RING_BASE }
177 		},
178 	},
179 	[VCS6] = {
180 		.class = VIDEO_DECODE_CLASS,
181 		.instance = 6,
182 		.mmio_bases = {
183 			{ .graphics_ver = 12, .base = XEHP_BSD7_RING_BASE }
184 		},
185 	},
186 	[VCS7] = {
187 		.class = VIDEO_DECODE_CLASS,
188 		.instance = 7,
189 		.mmio_bases = {
190 			{ .graphics_ver = 12, .base = XEHP_BSD8_RING_BASE }
191 		},
192 	},
193 	[VECS0] = {
194 		.class = VIDEO_ENHANCEMENT_CLASS,
195 		.instance = 0,
196 		.mmio_bases = {
197 			{ .graphics_ver = 11, .base = GEN11_VEBOX_RING_BASE },
198 			{ .graphics_ver = 7, .base = VEBOX_RING_BASE }
199 		},
200 	},
201 	[VECS1] = {
202 		.class = VIDEO_ENHANCEMENT_CLASS,
203 		.instance = 1,
204 		.mmio_bases = {
205 			{ .graphics_ver = 11, .base = GEN11_VEBOX2_RING_BASE }
206 		},
207 	},
208 	[VECS2] = {
209 		.class = VIDEO_ENHANCEMENT_CLASS,
210 		.instance = 2,
211 		.mmio_bases = {
212 			{ .graphics_ver = 12, .base = XEHP_VEBOX3_RING_BASE }
213 		},
214 	},
215 	[VECS3] = {
216 		.class = VIDEO_ENHANCEMENT_CLASS,
217 		.instance = 3,
218 		.mmio_bases = {
219 			{ .graphics_ver = 12, .base = XEHP_VEBOX4_RING_BASE }
220 		},
221 	},
222 	[CCS0] = {
223 		.class = COMPUTE_CLASS,
224 		.instance = 0,
225 		.mmio_bases = {
226 			{ .graphics_ver = 12, .base = GEN12_COMPUTE0_RING_BASE }
227 		}
228 	},
229 	[CCS1] = {
230 		.class = COMPUTE_CLASS,
231 		.instance = 1,
232 		.mmio_bases = {
233 			{ .graphics_ver = 12, .base = GEN12_COMPUTE1_RING_BASE }
234 		}
235 	},
236 	[CCS2] = {
237 		.class = COMPUTE_CLASS,
238 		.instance = 2,
239 		.mmio_bases = {
240 			{ .graphics_ver = 12, .base = GEN12_COMPUTE2_RING_BASE }
241 		}
242 	},
243 	[CCS3] = {
244 		.class = COMPUTE_CLASS,
245 		.instance = 3,
246 		.mmio_bases = {
247 			{ .graphics_ver = 12, .base = GEN12_COMPUTE3_RING_BASE }
248 		}
249 	},
250 	[GSC0] = {
251 		.class = OTHER_CLASS,
252 		.instance = OTHER_GSC_INSTANCE,
253 		.mmio_bases = {
254 			{ .graphics_ver = 12, .base = MTL_GSC_RING_BASE }
255 		}
256 	},
257 };
258 
259 /**
260  * intel_engine_context_size() - return the size of the context for an engine
261  * @gt: the gt
262  * @class: engine class
263  *
264  * Each engine class may require a different amount of space for a context
265  * image.
266  *
267  * Return: size (in bytes) of an engine class specific context image
268  *
269  * Note: this size includes the HWSP, which is part of the context image
270  * in LRC mode, but does not include the "shared data page" used with
271  * GuC submission. The caller should account for this if using the GuC.
272  */
273 u32 intel_engine_context_size(struct intel_gt *gt, u8 class)
274 {
275 	struct intel_uncore *uncore = gt->uncore;
276 	u32 cxt_size;
277 
278 	BUILD_BUG_ON(I915_GTT_PAGE_SIZE != PAGE_SIZE);
279 
280 	switch (class) {
281 	case COMPUTE_CLASS:
282 		fallthrough;
283 	case RENDER_CLASS:
284 		switch (GRAPHICS_VER(gt->i915)) {
285 		default:
286 			MISSING_CASE(GRAPHICS_VER(gt->i915));
287 			return DEFAULT_LR_CONTEXT_RENDER_SIZE;
288 		case 12:
289 		case 11:
290 			return GEN11_LR_CONTEXT_RENDER_SIZE;
291 		case 9:
292 			return GEN9_LR_CONTEXT_RENDER_SIZE;
293 		case 8:
294 			return GEN8_LR_CONTEXT_RENDER_SIZE;
295 		case 7:
296 			if (IS_HASWELL(gt->i915))
297 				return HSW_CXT_TOTAL_SIZE;
298 
299 			cxt_size = intel_uncore_read(uncore, GEN7_CXT_SIZE);
300 			return round_up(GEN7_CXT_TOTAL_SIZE(cxt_size) * 64,
301 					PAGE_SIZE);
302 		case 6:
303 			cxt_size = intel_uncore_read(uncore, CXT_SIZE);
304 			return round_up(GEN6_CXT_TOTAL_SIZE(cxt_size) * 64,
305 					PAGE_SIZE);
306 		case 5:
307 		case 4:
308 			/*
309 			 * There is a discrepancy here between the size reported
310 			 * by the register and the size of the context layout
311 			 * in the docs. Both are described as authorative!
312 			 *
313 			 * The discrepancy is on the order of a few cachelines,
314 			 * but the total is under one page (4k), which is our
315 			 * minimum allocation anyway so it should all come
316 			 * out in the wash.
317 			 */
318 			cxt_size = intel_uncore_read(uncore, CXT_SIZE) + 1;
319 			drm_dbg(&gt->i915->drm,
320 				"graphics_ver = %d CXT_SIZE = %d bytes [0x%08x]\n",
321 				GRAPHICS_VER(gt->i915), cxt_size * 64,
322 				cxt_size - 1);
323 			return round_up(cxt_size * 64, PAGE_SIZE);
324 		case 3:
325 		case 2:
326 		/* For the special day when i810 gets merged. */
327 		case 1:
328 			return 0;
329 		}
330 		break;
331 	default:
332 		MISSING_CASE(class);
333 		fallthrough;
334 	case VIDEO_DECODE_CLASS:
335 	case VIDEO_ENHANCEMENT_CLASS:
336 	case COPY_ENGINE_CLASS:
337 	case OTHER_CLASS:
338 		if (GRAPHICS_VER(gt->i915) < 8)
339 			return 0;
340 		return GEN8_LR_CONTEXT_OTHER_SIZE;
341 	}
342 }
343 
344 static u32 __engine_mmio_base(struct drm_i915_private *i915,
345 			      const struct engine_mmio_base *bases)
346 {
347 	int i;
348 
349 	for (i = 0; i < MAX_MMIO_BASES; i++)
350 		if (GRAPHICS_VER(i915) >= bases[i].graphics_ver)
351 			break;
352 
353 	GEM_BUG_ON(i == MAX_MMIO_BASES);
354 	GEM_BUG_ON(!bases[i].base);
355 
356 	return bases[i].base;
357 }
358 
359 static void __sprint_engine_name(struct intel_engine_cs *engine)
360 {
361 	/*
362 	 * Before we know what the uABI name for this engine will be,
363 	 * we still would like to keep track of this engine in the debug logs.
364 	 * We throw in a ' here as a reminder that this isn't its final name.
365 	 */
366 	GEM_WARN_ON(snprintf(engine->name, sizeof(engine->name), "%s'%u",
367 			     intel_engine_class_repr(engine->class),
368 			     engine->instance) >= sizeof(engine->name));
369 }
370 
371 void intel_engine_set_hwsp_writemask(struct intel_engine_cs *engine, u32 mask)
372 {
373 	/*
374 	 * Though they added more rings on g4x/ilk, they did not add
375 	 * per-engine HWSTAM until gen6.
376 	 */
377 	if (GRAPHICS_VER(engine->i915) < 6 && engine->class != RENDER_CLASS)
378 		return;
379 
380 	if (GRAPHICS_VER(engine->i915) >= 3)
381 		ENGINE_WRITE(engine, RING_HWSTAM, mask);
382 	else
383 		ENGINE_WRITE16(engine, RING_HWSTAM, mask);
384 }
385 
386 static void intel_engine_sanitize_mmio(struct intel_engine_cs *engine)
387 {
388 	/* Mask off all writes into the unknown HWSP */
389 	intel_engine_set_hwsp_writemask(engine, ~0u);
390 }
391 
392 static void nop_irq_handler(struct intel_engine_cs *engine, u16 iir)
393 {
394 	GEM_DEBUG_WARN_ON(iir);
395 }
396 
397 static u32 get_reset_domain(u8 ver, enum intel_engine_id id)
398 {
399 	u32 reset_domain;
400 
401 	if (ver >= 11) {
402 		static const u32 engine_reset_domains[] = {
403 			[RCS0]  = GEN11_GRDOM_RENDER,
404 			[BCS0]  = GEN11_GRDOM_BLT,
405 			[BCS1]  = XEHPC_GRDOM_BLT1,
406 			[BCS2]  = XEHPC_GRDOM_BLT2,
407 			[BCS3]  = XEHPC_GRDOM_BLT3,
408 			[BCS4]  = XEHPC_GRDOM_BLT4,
409 			[BCS5]  = XEHPC_GRDOM_BLT5,
410 			[BCS6]  = XEHPC_GRDOM_BLT6,
411 			[BCS7]  = XEHPC_GRDOM_BLT7,
412 			[BCS8]  = XEHPC_GRDOM_BLT8,
413 			[VCS0]  = GEN11_GRDOM_MEDIA,
414 			[VCS1]  = GEN11_GRDOM_MEDIA2,
415 			[VCS2]  = GEN11_GRDOM_MEDIA3,
416 			[VCS3]  = GEN11_GRDOM_MEDIA4,
417 			[VCS4]  = GEN11_GRDOM_MEDIA5,
418 			[VCS5]  = GEN11_GRDOM_MEDIA6,
419 			[VCS6]  = GEN11_GRDOM_MEDIA7,
420 			[VCS7]  = GEN11_GRDOM_MEDIA8,
421 			[VECS0] = GEN11_GRDOM_VECS,
422 			[VECS1] = GEN11_GRDOM_VECS2,
423 			[VECS2] = GEN11_GRDOM_VECS3,
424 			[VECS3] = GEN11_GRDOM_VECS4,
425 			[CCS0]  = GEN11_GRDOM_RENDER,
426 			[CCS1]  = GEN11_GRDOM_RENDER,
427 			[CCS2]  = GEN11_GRDOM_RENDER,
428 			[CCS3]  = GEN11_GRDOM_RENDER,
429 			[GSC0]  = GEN12_GRDOM_GSC,
430 		};
431 		GEM_BUG_ON(id >= ARRAY_SIZE(engine_reset_domains) ||
432 			   !engine_reset_domains[id]);
433 		reset_domain = engine_reset_domains[id];
434 	} else {
435 		static const u32 engine_reset_domains[] = {
436 			[RCS0]  = GEN6_GRDOM_RENDER,
437 			[BCS0]  = GEN6_GRDOM_BLT,
438 			[VCS0]  = GEN6_GRDOM_MEDIA,
439 			[VCS1]  = GEN8_GRDOM_MEDIA2,
440 			[VECS0] = GEN6_GRDOM_VECS,
441 		};
442 		GEM_BUG_ON(id >= ARRAY_SIZE(engine_reset_domains) ||
443 			   !engine_reset_domains[id]);
444 		reset_domain = engine_reset_domains[id];
445 	}
446 
447 	return reset_domain;
448 }
449 
450 static int intel_engine_setup(struct intel_gt *gt, enum intel_engine_id id,
451 			      u8 logical_instance)
452 {
453 	const struct engine_info *info = &intel_engines[id];
454 	struct drm_i915_private *i915 = gt->i915;
455 	struct intel_engine_cs *engine;
456 	u8 guc_class;
457 
458 	BUILD_BUG_ON(MAX_ENGINE_CLASS >= BIT(GEN11_ENGINE_CLASS_WIDTH));
459 	BUILD_BUG_ON(MAX_ENGINE_INSTANCE >= BIT(GEN11_ENGINE_INSTANCE_WIDTH));
460 	BUILD_BUG_ON(I915_MAX_VCS > (MAX_ENGINE_INSTANCE + 1));
461 	BUILD_BUG_ON(I915_MAX_VECS > (MAX_ENGINE_INSTANCE + 1));
462 
463 	if (GEM_DEBUG_WARN_ON(id >= ARRAY_SIZE(gt->engine)))
464 		return -EINVAL;
465 
466 	if (GEM_DEBUG_WARN_ON(info->class > MAX_ENGINE_CLASS))
467 		return -EINVAL;
468 
469 	if (GEM_DEBUG_WARN_ON(info->instance > MAX_ENGINE_INSTANCE))
470 		return -EINVAL;
471 
472 	if (GEM_DEBUG_WARN_ON(gt->engine_class[info->class][info->instance]))
473 		return -EINVAL;
474 
475 	engine = kzalloc(sizeof(*engine), GFP_KERNEL);
476 	if (!engine)
477 		return -ENOMEM;
478 
479 	BUILD_BUG_ON(BITS_PER_TYPE(engine->mask) < I915_NUM_ENGINES);
480 
481 	INIT_LIST_HEAD(&engine->pinned_contexts_list);
482 	engine->id = id;
483 	engine->legacy_idx = INVALID_ENGINE;
484 	engine->mask = BIT(id);
485 	engine->reset_domain = get_reset_domain(GRAPHICS_VER(gt->i915),
486 						id);
487 	engine->i915 = i915;
488 	engine->gt = gt;
489 	engine->uncore = gt->uncore;
490 	guc_class = engine_class_to_guc_class(info->class);
491 	engine->guc_id = MAKE_GUC_ID(guc_class, info->instance);
492 	engine->mmio_base = __engine_mmio_base(i915, info->mmio_bases);
493 
494 	engine->irq_handler = nop_irq_handler;
495 
496 	engine->class = info->class;
497 	engine->instance = info->instance;
498 	engine->logical_mask = BIT(logical_instance);
499 	__sprint_engine_name(engine);
500 
501 	if ((engine->class == COMPUTE_CLASS && !RCS_MASK(engine->gt) &&
502 	     __ffs(CCS_MASK(engine->gt)) == engine->instance) ||
503 	     engine->class == RENDER_CLASS)
504 		engine->flags |= I915_ENGINE_FIRST_RENDER_COMPUTE;
505 
506 	/* features common between engines sharing EUs */
507 	if (engine->class == RENDER_CLASS || engine->class == COMPUTE_CLASS) {
508 		engine->flags |= I915_ENGINE_HAS_RCS_REG_STATE;
509 		engine->flags |= I915_ENGINE_HAS_EU_PRIORITY;
510 	}
511 
512 	engine->props.heartbeat_interval_ms =
513 		CONFIG_DRM_I915_HEARTBEAT_INTERVAL;
514 	engine->props.max_busywait_duration_ns =
515 		CONFIG_DRM_I915_MAX_REQUEST_BUSYWAIT;
516 	engine->props.preempt_timeout_ms =
517 		CONFIG_DRM_I915_PREEMPT_TIMEOUT;
518 	engine->props.stop_timeout_ms =
519 		CONFIG_DRM_I915_STOP_TIMEOUT;
520 	engine->props.timeslice_duration_ms =
521 		CONFIG_DRM_I915_TIMESLICE_DURATION;
522 
523 	/*
524 	 * Mid-thread pre-emption is not available in Gen12. Unfortunately,
525 	 * some compute workloads run quite long threads. That means they get
526 	 * reset due to not pre-empting in a timely manner. So, bump the
527 	 * pre-emption timeout value to be much higher for compute engines.
528 	 */
529 	if (GRAPHICS_VER(i915) == 12 && (engine->flags & I915_ENGINE_HAS_RCS_REG_STATE))
530 		engine->props.preempt_timeout_ms = CONFIG_DRM_I915_PREEMPT_TIMEOUT_COMPUTE;
531 
532 	/* Cap properties according to any system limits */
533 #define CLAMP_PROP(field) \
534 	do { \
535 		u64 clamp = intel_clamp_##field(engine, engine->props.field); \
536 		if (clamp != engine->props.field) { \
537 			drm_notice(&engine->i915->drm, \
538 				   "Warning, clamping %s to %lld to prevent overflow\n", \
539 				   #field, clamp); \
540 			engine->props.field = clamp; \
541 		} \
542 	} while (0)
543 
544 	CLAMP_PROP(heartbeat_interval_ms);
545 	CLAMP_PROP(max_busywait_duration_ns);
546 	CLAMP_PROP(preempt_timeout_ms);
547 	CLAMP_PROP(stop_timeout_ms);
548 	CLAMP_PROP(timeslice_duration_ms);
549 
550 #undef CLAMP_PROP
551 
552 	engine->defaults = engine->props; /* never to change again */
553 
554 	engine->context_size = intel_engine_context_size(gt, engine->class);
555 	if (WARN_ON(engine->context_size > BIT(20)))
556 		engine->context_size = 0;
557 	if (engine->context_size)
558 		DRIVER_CAPS(i915)->has_logical_contexts = true;
559 
560 	ewma__engine_latency_init(&engine->latency);
561 	seqcount_init(&engine->stats.execlists.lock);
562 
563 	ATOMIC_INIT_NOTIFIER_HEAD(&engine->context_status_notifier);
564 
565 	/* Scrub mmio state on takeover */
566 	intel_engine_sanitize_mmio(engine);
567 
568 	gt->engine_class[info->class][info->instance] = engine;
569 	gt->engine[id] = engine;
570 
571 	return 0;
572 }
573 
574 u64 intel_clamp_heartbeat_interval_ms(struct intel_engine_cs *engine, u64 value)
575 {
576 	value = min_t(u64, value, jiffies_to_msecs(MAX_SCHEDULE_TIMEOUT));
577 
578 	return value;
579 }
580 
581 u64 intel_clamp_max_busywait_duration_ns(struct intel_engine_cs *engine, u64 value)
582 {
583 	value = min(value, jiffies_to_nsecs(2));
584 
585 	return value;
586 }
587 
588 u64 intel_clamp_preempt_timeout_ms(struct intel_engine_cs *engine, u64 value)
589 {
590 	/*
591 	 * NB: The GuC API only supports 32bit values. However, the limit is further
592 	 * reduced due to internal calculations which would otherwise overflow.
593 	 */
594 	if (intel_guc_submission_is_wanted(&engine->gt->uc.guc))
595 		value = min_t(u64, value, guc_policy_max_preempt_timeout_ms());
596 
597 	value = min_t(u64, value, jiffies_to_msecs(MAX_SCHEDULE_TIMEOUT));
598 
599 	return value;
600 }
601 
602 u64 intel_clamp_stop_timeout_ms(struct intel_engine_cs *engine, u64 value)
603 {
604 	value = min_t(u64, value, jiffies_to_msecs(MAX_SCHEDULE_TIMEOUT));
605 
606 	return value;
607 }
608 
609 u64 intel_clamp_timeslice_duration_ms(struct intel_engine_cs *engine, u64 value)
610 {
611 	/*
612 	 * NB: The GuC API only supports 32bit values. However, the limit is further
613 	 * reduced due to internal calculations which would otherwise overflow.
614 	 */
615 	if (intel_guc_submission_is_wanted(&engine->gt->uc.guc))
616 		value = min_t(u64, value, guc_policy_max_exec_quantum_ms());
617 
618 	value = min_t(u64, value, jiffies_to_msecs(MAX_SCHEDULE_TIMEOUT));
619 
620 	return value;
621 }
622 
623 static void __setup_engine_capabilities(struct intel_engine_cs *engine)
624 {
625 	struct drm_i915_private *i915 = engine->i915;
626 
627 	if (engine->class == VIDEO_DECODE_CLASS) {
628 		/*
629 		 * HEVC support is present on first engine instance
630 		 * before Gen11 and on all instances afterwards.
631 		 */
632 		if (GRAPHICS_VER(i915) >= 11 ||
633 		    (GRAPHICS_VER(i915) >= 9 && engine->instance == 0))
634 			engine->uabi_capabilities |=
635 				I915_VIDEO_CLASS_CAPABILITY_HEVC;
636 
637 		/*
638 		 * SFC block is present only on even logical engine
639 		 * instances.
640 		 */
641 		if ((GRAPHICS_VER(i915) >= 11 &&
642 		     (engine->gt->info.vdbox_sfc_access &
643 		      BIT(engine->instance))) ||
644 		    (GRAPHICS_VER(i915) >= 9 && engine->instance == 0))
645 			engine->uabi_capabilities |=
646 				I915_VIDEO_AND_ENHANCE_CLASS_CAPABILITY_SFC;
647 	} else if (engine->class == VIDEO_ENHANCEMENT_CLASS) {
648 		if (GRAPHICS_VER(i915) >= 9 &&
649 		    engine->gt->info.sfc_mask & BIT(engine->instance))
650 			engine->uabi_capabilities |=
651 				I915_VIDEO_AND_ENHANCE_CLASS_CAPABILITY_SFC;
652 	}
653 }
654 
655 static void intel_setup_engine_capabilities(struct intel_gt *gt)
656 {
657 	struct intel_engine_cs *engine;
658 	enum intel_engine_id id;
659 
660 	for_each_engine(engine, gt, id)
661 		__setup_engine_capabilities(engine);
662 }
663 
664 /**
665  * intel_engines_release() - free the resources allocated for Command Streamers
666  * @gt: pointer to struct intel_gt
667  */
668 void intel_engines_release(struct intel_gt *gt)
669 {
670 	struct intel_engine_cs *engine;
671 	enum intel_engine_id id;
672 
673 	/*
674 	 * Before we release the resources held by engine, we must be certain
675 	 * that the HW is no longer accessing them -- having the GPU scribble
676 	 * to or read from a page being used for something else causes no end
677 	 * of fun.
678 	 *
679 	 * The GPU should be reset by this point, but assume the worst just
680 	 * in case we aborted before completely initialising the engines.
681 	 */
682 	GEM_BUG_ON(intel_gt_pm_is_awake(gt));
683 	if (!INTEL_INFO(gt->i915)->gpu_reset_clobbers_display)
684 		__intel_gt_reset(gt, ALL_ENGINES);
685 
686 	/* Decouple the backend; but keep the layout for late GPU resets */
687 	for_each_engine(engine, gt, id) {
688 		if (!engine->release)
689 			continue;
690 
691 		intel_wakeref_wait_for_idle(&engine->wakeref);
692 		GEM_BUG_ON(intel_engine_pm_is_awake(engine));
693 
694 		engine->release(engine);
695 		engine->release = NULL;
696 
697 		memset(&engine->reset, 0, sizeof(engine->reset));
698 	}
699 }
700 
701 void intel_engine_free_request_pool(struct intel_engine_cs *engine)
702 {
703 	if (!engine->request_pool)
704 		return;
705 
706 	kmem_cache_free(i915_request_slab_cache(), engine->request_pool);
707 }
708 
709 void intel_engines_free(struct intel_gt *gt)
710 {
711 	struct intel_engine_cs *engine;
712 	enum intel_engine_id id;
713 
714 	/* Free the requests! dma-resv keeps fences around for an eternity */
715 	rcu_barrier();
716 
717 	for_each_engine(engine, gt, id) {
718 		intel_engine_free_request_pool(engine);
719 		kfree(engine);
720 		gt->engine[id] = NULL;
721 	}
722 }
723 
724 static
725 bool gen11_vdbox_has_sfc(struct intel_gt *gt,
726 			 unsigned int physical_vdbox,
727 			 unsigned int logical_vdbox, u16 vdbox_mask)
728 {
729 	struct drm_i915_private *i915 = gt->i915;
730 
731 	/*
732 	 * In Gen11, only even numbered logical VDBOXes are hooked
733 	 * up to an SFC (Scaler & Format Converter) unit.
734 	 * In Gen12, Even numbered physical instance always are connected
735 	 * to an SFC. Odd numbered physical instances have SFC only if
736 	 * previous even instance is fused off.
737 	 *
738 	 * Starting with Xe_HP, there's also a dedicated SFC_ENABLE field
739 	 * in the fuse register that tells us whether a specific SFC is present.
740 	 */
741 	if ((gt->info.sfc_mask & BIT(physical_vdbox / 2)) == 0)
742 		return false;
743 	else if (MEDIA_VER(i915) >= 12)
744 		return (physical_vdbox % 2 == 0) ||
745 			!(BIT(physical_vdbox - 1) & vdbox_mask);
746 	else if (MEDIA_VER(i915) == 11)
747 		return logical_vdbox % 2 == 0;
748 
749 	return false;
750 }
751 
752 static void engine_mask_apply_media_fuses(struct intel_gt *gt)
753 {
754 	struct drm_i915_private *i915 = gt->i915;
755 	unsigned int logical_vdbox = 0;
756 	unsigned int i;
757 	u32 media_fuse, fuse1;
758 	u16 vdbox_mask;
759 	u16 vebox_mask;
760 
761 	if (MEDIA_VER(gt->i915) < 11)
762 		return;
763 
764 	/*
765 	 * On newer platforms the fusing register is called 'enable' and has
766 	 * enable semantics, while on older platforms it is called 'disable'
767 	 * and bits have disable semantices.
768 	 */
769 	media_fuse = intel_uncore_read(gt->uncore, GEN11_GT_VEBOX_VDBOX_DISABLE);
770 	if (MEDIA_VER_FULL(i915) < IP_VER(12, 50))
771 		media_fuse = ~media_fuse;
772 
773 	vdbox_mask = media_fuse & GEN11_GT_VDBOX_DISABLE_MASK;
774 	vebox_mask = (media_fuse & GEN11_GT_VEBOX_DISABLE_MASK) >>
775 		      GEN11_GT_VEBOX_DISABLE_SHIFT;
776 
777 	if (MEDIA_VER_FULL(i915) >= IP_VER(12, 50)) {
778 		fuse1 = intel_uncore_read(gt->uncore, HSW_PAVP_FUSE1);
779 		gt->info.sfc_mask = REG_FIELD_GET(XEHP_SFC_ENABLE_MASK, fuse1);
780 	} else {
781 		gt->info.sfc_mask = ~0;
782 	}
783 
784 	for (i = 0; i < I915_MAX_VCS; i++) {
785 		if (!HAS_ENGINE(gt, _VCS(i))) {
786 			vdbox_mask &= ~BIT(i);
787 			continue;
788 		}
789 
790 		if (!(BIT(i) & vdbox_mask)) {
791 			gt->info.engine_mask &= ~BIT(_VCS(i));
792 			drm_dbg(&i915->drm, "vcs%u fused off\n", i);
793 			continue;
794 		}
795 
796 		if (gen11_vdbox_has_sfc(gt, i, logical_vdbox, vdbox_mask))
797 			gt->info.vdbox_sfc_access |= BIT(i);
798 		logical_vdbox++;
799 	}
800 	drm_dbg(&i915->drm, "vdbox enable: %04x, instances: %04lx\n",
801 		vdbox_mask, VDBOX_MASK(gt));
802 	GEM_BUG_ON(vdbox_mask != VDBOX_MASK(gt));
803 
804 	for (i = 0; i < I915_MAX_VECS; i++) {
805 		if (!HAS_ENGINE(gt, _VECS(i))) {
806 			vebox_mask &= ~BIT(i);
807 			continue;
808 		}
809 
810 		if (!(BIT(i) & vebox_mask)) {
811 			gt->info.engine_mask &= ~BIT(_VECS(i));
812 			drm_dbg(&i915->drm, "vecs%u fused off\n", i);
813 		}
814 	}
815 	drm_dbg(&i915->drm, "vebox enable: %04x, instances: %04lx\n",
816 		vebox_mask, VEBOX_MASK(gt));
817 	GEM_BUG_ON(vebox_mask != VEBOX_MASK(gt));
818 }
819 
820 static void engine_mask_apply_compute_fuses(struct intel_gt *gt)
821 {
822 	struct drm_i915_private *i915 = gt->i915;
823 	struct intel_gt_info *info = &gt->info;
824 	int ss_per_ccs = info->sseu.max_subslices / I915_MAX_CCS;
825 	unsigned long ccs_mask;
826 	unsigned int i;
827 
828 	if (GRAPHICS_VER(i915) < 11)
829 		return;
830 
831 	if (hweight32(CCS_MASK(gt)) <= 1)
832 		return;
833 
834 	ccs_mask = intel_slicemask_from_xehp_dssmask(info->sseu.compute_subslice_mask,
835 						     ss_per_ccs);
836 	/*
837 	 * If all DSS in a quadrant are fused off, the corresponding CCS
838 	 * engine is not available for use.
839 	 */
840 	for_each_clear_bit(i, &ccs_mask, I915_MAX_CCS) {
841 		info->engine_mask &= ~BIT(_CCS(i));
842 		drm_dbg(&i915->drm, "ccs%u fused off\n", i);
843 	}
844 }
845 
846 static void engine_mask_apply_copy_fuses(struct intel_gt *gt)
847 {
848 	struct drm_i915_private *i915 = gt->i915;
849 	struct intel_gt_info *info = &gt->info;
850 	unsigned long meml3_mask;
851 	unsigned long quad;
852 
853 	if (!(GRAPHICS_VER_FULL(i915) >= IP_VER(12, 60) &&
854 	      GRAPHICS_VER_FULL(i915) < IP_VER(12, 70)))
855 		return;
856 
857 	meml3_mask = intel_uncore_read(gt->uncore, GEN10_MIRROR_FUSE3);
858 	meml3_mask = REG_FIELD_GET(GEN12_MEML3_EN_MASK, meml3_mask);
859 
860 	/*
861 	 * Link Copy engines may be fused off according to meml3_mask. Each
862 	 * bit is a quad that houses 2 Link Copy and two Sub Copy engines.
863 	 */
864 	for_each_clear_bit(quad, &meml3_mask, GEN12_MAX_MSLICES) {
865 		unsigned int instance = quad * 2 + 1;
866 		intel_engine_mask_t mask = GENMASK(_BCS(instance + 1),
867 						   _BCS(instance));
868 
869 		if (mask & info->engine_mask) {
870 			drm_dbg(&i915->drm, "bcs%u fused off\n", instance);
871 			drm_dbg(&i915->drm, "bcs%u fused off\n", instance + 1);
872 
873 			info->engine_mask &= ~mask;
874 		}
875 	}
876 }
877 
878 /*
879  * Determine which engines are fused off in our particular hardware.
880  * Note that we have a catch-22 situation where we need to be able to access
881  * the blitter forcewake domain to read the engine fuses, but at the same time
882  * we need to know which engines are available on the system to know which
883  * forcewake domains are present. We solve this by intializing the forcewake
884  * domains based on the full engine mask in the platform capabilities before
885  * calling this function and pruning the domains for fused-off engines
886  * afterwards.
887  */
888 static intel_engine_mask_t init_engine_mask(struct intel_gt *gt)
889 {
890 	struct intel_gt_info *info = &gt->info;
891 
892 	GEM_BUG_ON(!info->engine_mask);
893 
894 	engine_mask_apply_media_fuses(gt);
895 	engine_mask_apply_compute_fuses(gt);
896 	engine_mask_apply_copy_fuses(gt);
897 
898 	/*
899 	 * The only use of the GSC CS is to load and communicate with the GSC
900 	 * FW, so we have no use for it if we don't have the FW.
901 	 *
902 	 * IMPORTANT: in cases where we don't have the GSC FW, we have a
903 	 * catch-22 situation that breaks media C6 due to 2 requirements:
904 	 * 1) once turned on, the GSC power well will not go to sleep unless the
905 	 *    GSC FW is loaded.
906 	 * 2) to enable idling (which is required for media C6) we need to
907 	 *    initialize the IDLE_MSG register for the GSC CS and do at least 1
908 	 *    submission, which will wake up the GSC power well.
909 	 */
910 	if (__HAS_ENGINE(info->engine_mask, GSC0) && !intel_uc_wants_gsc_uc(&gt->uc)) {
911 		drm_notice(&gt->i915->drm,
912 			   "No GSC FW selected, disabling GSC CS and media C6\n");
913 		info->engine_mask &= ~BIT(GSC0);
914 	}
915 
916 	return info->engine_mask;
917 }
918 
919 static void populate_logical_ids(struct intel_gt *gt, u8 *logical_ids,
920 				 u8 class, const u8 *map, u8 num_instances)
921 {
922 	int i, j;
923 	u8 current_logical_id = 0;
924 
925 	for (j = 0; j < num_instances; ++j) {
926 		for (i = 0; i < ARRAY_SIZE(intel_engines); ++i) {
927 			if (!HAS_ENGINE(gt, i) ||
928 			    intel_engines[i].class != class)
929 				continue;
930 
931 			if (intel_engines[i].instance == map[j]) {
932 				logical_ids[intel_engines[i].instance] =
933 					current_logical_id++;
934 				break;
935 			}
936 		}
937 	}
938 }
939 
940 static void setup_logical_ids(struct intel_gt *gt, u8 *logical_ids, u8 class)
941 {
942 	/*
943 	 * Logical to physical mapping is needed for proper support
944 	 * to split-frame feature.
945 	 */
946 	if (MEDIA_VER(gt->i915) >= 11 && class == VIDEO_DECODE_CLASS) {
947 		const u8 map[] = { 0, 2, 4, 6, 1, 3, 5, 7 };
948 
949 		populate_logical_ids(gt, logical_ids, class,
950 				     map, ARRAY_SIZE(map));
951 	} else {
952 		int i;
953 		u8 map[MAX_ENGINE_INSTANCE + 1];
954 
955 		for (i = 0; i < MAX_ENGINE_INSTANCE + 1; ++i)
956 			map[i] = i;
957 		populate_logical_ids(gt, logical_ids, class,
958 				     map, ARRAY_SIZE(map));
959 	}
960 }
961 
962 /**
963  * intel_engines_init_mmio() - allocate and prepare the Engine Command Streamers
964  * @gt: pointer to struct intel_gt
965  *
966  * Return: non-zero if the initialization failed.
967  */
968 int intel_engines_init_mmio(struct intel_gt *gt)
969 {
970 	struct drm_i915_private *i915 = gt->i915;
971 	const unsigned int engine_mask = init_engine_mask(gt);
972 	unsigned int mask = 0;
973 	unsigned int i, class;
974 	u8 logical_ids[MAX_ENGINE_INSTANCE + 1];
975 	int err;
976 
977 	drm_WARN_ON(&i915->drm, engine_mask == 0);
978 	drm_WARN_ON(&i915->drm, engine_mask &
979 		    GENMASK(BITS_PER_TYPE(mask) - 1, I915_NUM_ENGINES));
980 
981 	if (i915_inject_probe_failure(i915))
982 		return -ENODEV;
983 
984 	for (class = 0; class < MAX_ENGINE_CLASS + 1; ++class) {
985 		setup_logical_ids(gt, logical_ids, class);
986 
987 		for (i = 0; i < ARRAY_SIZE(intel_engines); ++i) {
988 			u8 instance = intel_engines[i].instance;
989 
990 			if (intel_engines[i].class != class ||
991 			    !HAS_ENGINE(gt, i))
992 				continue;
993 
994 			err = intel_engine_setup(gt, i,
995 						 logical_ids[instance]);
996 			if (err)
997 				goto cleanup;
998 
999 			mask |= BIT(i);
1000 		}
1001 	}
1002 
1003 	/*
1004 	 * Catch failures to update intel_engines table when the new engines
1005 	 * are added to the driver by a warning and disabling the forgotten
1006 	 * engines.
1007 	 */
1008 	if (drm_WARN_ON(&i915->drm, mask != engine_mask))
1009 		gt->info.engine_mask = mask;
1010 
1011 	gt->info.num_engines = hweight32(mask);
1012 
1013 	intel_gt_check_and_clear_faults(gt);
1014 
1015 	intel_setup_engine_capabilities(gt);
1016 
1017 	intel_uncore_prune_engine_fw_domains(gt->uncore, gt);
1018 
1019 	return 0;
1020 
1021 cleanup:
1022 	intel_engines_free(gt);
1023 	return err;
1024 }
1025 
1026 void intel_engine_init_execlists(struct intel_engine_cs *engine)
1027 {
1028 	struct intel_engine_execlists * const execlists = &engine->execlists;
1029 
1030 	execlists->port_mask = 1;
1031 	GEM_BUG_ON(!is_power_of_2(execlists_num_ports(execlists)));
1032 	GEM_BUG_ON(execlists_num_ports(execlists) > EXECLIST_MAX_PORTS);
1033 
1034 	memset(execlists->pending, 0, sizeof(execlists->pending));
1035 	execlists->active =
1036 		memset(execlists->inflight, 0, sizeof(execlists->inflight));
1037 }
1038 
1039 static void cleanup_status_page(struct intel_engine_cs *engine)
1040 {
1041 	struct i915_vma *vma;
1042 
1043 	/* Prevent writes into HWSP after returning the page to the system */
1044 	intel_engine_set_hwsp_writemask(engine, ~0u);
1045 
1046 	vma = fetch_and_zero(&engine->status_page.vma);
1047 	if (!vma)
1048 		return;
1049 
1050 	if (!HWS_NEEDS_PHYSICAL(engine->i915))
1051 		i915_vma_unpin(vma);
1052 
1053 	i915_gem_object_unpin_map(vma->obj);
1054 	i915_gem_object_put(vma->obj);
1055 }
1056 
1057 static int pin_ggtt_status_page(struct intel_engine_cs *engine,
1058 				struct i915_gem_ww_ctx *ww,
1059 				struct i915_vma *vma)
1060 {
1061 	unsigned int flags;
1062 
1063 	if (!HAS_LLC(engine->i915) && i915_ggtt_has_aperture(engine->gt->ggtt))
1064 		/*
1065 		 * On g33, we cannot place HWS above 256MiB, so
1066 		 * restrict its pinning to the low mappable arena.
1067 		 * Though this restriction is not documented for
1068 		 * gen4, gen5, or byt, they also behave similarly
1069 		 * and hang if the HWS is placed at the top of the
1070 		 * GTT. To generalise, it appears that all !llc
1071 		 * platforms have issues with us placing the HWS
1072 		 * above the mappable region (even though we never
1073 		 * actually map it).
1074 		 */
1075 		flags = PIN_MAPPABLE;
1076 	else
1077 		flags = PIN_HIGH;
1078 
1079 	return i915_ggtt_pin(vma, ww, 0, flags);
1080 }
1081 
1082 static int init_status_page(struct intel_engine_cs *engine)
1083 {
1084 	struct drm_i915_gem_object *obj;
1085 	struct i915_gem_ww_ctx ww;
1086 	struct i915_vma *vma;
1087 	void *vaddr;
1088 	int ret;
1089 
1090 	INIT_LIST_HEAD(&engine->status_page.timelines);
1091 
1092 	/*
1093 	 * Though the HWS register does support 36bit addresses, historically
1094 	 * we have had hangs and corruption reported due to wild writes if
1095 	 * the HWS is placed above 4G. We only allow objects to be allocated
1096 	 * in GFP_DMA32 for i965, and no earlier physical address users had
1097 	 * access to more than 4G.
1098 	 */
1099 	obj = i915_gem_object_create_internal(engine->i915, PAGE_SIZE);
1100 	if (IS_ERR(obj)) {
1101 		drm_err(&engine->i915->drm,
1102 			"Failed to allocate status page\n");
1103 		return PTR_ERR(obj);
1104 	}
1105 
1106 	i915_gem_object_set_cache_coherency(obj, I915_CACHE_LLC);
1107 
1108 	vma = i915_vma_instance(obj, &engine->gt->ggtt->vm, NULL);
1109 	if (IS_ERR(vma)) {
1110 		ret = PTR_ERR(vma);
1111 		goto err_put;
1112 	}
1113 
1114 	i915_gem_ww_ctx_init(&ww, true);
1115 retry:
1116 	ret = i915_gem_object_lock(obj, &ww);
1117 	if (!ret && !HWS_NEEDS_PHYSICAL(engine->i915))
1118 		ret = pin_ggtt_status_page(engine, &ww, vma);
1119 	if (ret)
1120 		goto err;
1121 
1122 	vaddr = i915_gem_object_pin_map(obj, I915_MAP_WB);
1123 	if (IS_ERR(vaddr)) {
1124 		ret = PTR_ERR(vaddr);
1125 		goto err_unpin;
1126 	}
1127 
1128 	engine->status_page.addr = memset(vaddr, 0, PAGE_SIZE);
1129 	engine->status_page.vma = vma;
1130 
1131 err_unpin:
1132 	if (ret)
1133 		i915_vma_unpin(vma);
1134 err:
1135 	if (ret == -EDEADLK) {
1136 		ret = i915_gem_ww_ctx_backoff(&ww);
1137 		if (!ret)
1138 			goto retry;
1139 	}
1140 	i915_gem_ww_ctx_fini(&ww);
1141 err_put:
1142 	if (ret)
1143 		i915_gem_object_put(obj);
1144 	return ret;
1145 }
1146 
1147 static int intel_engine_init_tlb_invalidation(struct intel_engine_cs *engine)
1148 {
1149 	static const union intel_engine_tlb_inv_reg gen8_regs[] = {
1150 		[RENDER_CLASS].reg		= GEN8_RTCR,
1151 		[VIDEO_DECODE_CLASS].reg	= GEN8_M1TCR, /* , GEN8_M2TCR */
1152 		[VIDEO_ENHANCEMENT_CLASS].reg	= GEN8_VTCR,
1153 		[COPY_ENGINE_CLASS].reg		= GEN8_BTCR,
1154 	};
1155 	static const union intel_engine_tlb_inv_reg gen12_regs[] = {
1156 		[RENDER_CLASS].reg		= GEN12_GFX_TLB_INV_CR,
1157 		[VIDEO_DECODE_CLASS].reg	= GEN12_VD_TLB_INV_CR,
1158 		[VIDEO_ENHANCEMENT_CLASS].reg	= GEN12_VE_TLB_INV_CR,
1159 		[COPY_ENGINE_CLASS].reg		= GEN12_BLT_TLB_INV_CR,
1160 		[COMPUTE_CLASS].reg		= GEN12_COMPCTX_TLB_INV_CR,
1161 	};
1162 	static const union intel_engine_tlb_inv_reg xehp_regs[] = {
1163 		[RENDER_CLASS].mcr_reg		  = XEHP_GFX_TLB_INV_CR,
1164 		[VIDEO_DECODE_CLASS].mcr_reg	  = XEHP_VD_TLB_INV_CR,
1165 		[VIDEO_ENHANCEMENT_CLASS].mcr_reg = XEHP_VE_TLB_INV_CR,
1166 		[COPY_ENGINE_CLASS].mcr_reg	  = XEHP_BLT_TLB_INV_CR,
1167 		[COMPUTE_CLASS].mcr_reg		  = XEHP_COMPCTX_TLB_INV_CR,
1168 	};
1169 	static const union intel_engine_tlb_inv_reg xelpmp_regs[] = {
1170 		[VIDEO_DECODE_CLASS].reg	  = GEN12_VD_TLB_INV_CR,
1171 		[VIDEO_ENHANCEMENT_CLASS].reg     = GEN12_VE_TLB_INV_CR,
1172 		[OTHER_CLASS].reg		  = XELPMP_GSC_TLB_INV_CR,
1173 	};
1174 	struct drm_i915_private *i915 = engine->i915;
1175 	const unsigned int instance = engine->instance;
1176 	const unsigned int class = engine->class;
1177 	const union intel_engine_tlb_inv_reg *regs;
1178 	union intel_engine_tlb_inv_reg reg;
1179 	unsigned int num = 0;
1180 	u32 val;
1181 
1182 	/*
1183 	 * New platforms should not be added with catch-all-newer (>=)
1184 	 * condition so that any later platform added triggers the below warning
1185 	 * and in turn mandates a human cross-check of whether the invalidation
1186 	 * flows have compatible semantics.
1187 	 *
1188 	 * For instance with the 11.00 -> 12.00 transition three out of five
1189 	 * respective engine registers were moved to masked type. Then after the
1190 	 * 12.00 -> 12.50 transition multi cast handling is required too.
1191 	 */
1192 
1193 	if (engine->gt->type == GT_MEDIA) {
1194 		if (MEDIA_VER_FULL(i915) == IP_VER(13, 0)) {
1195 			regs = xelpmp_regs;
1196 			num = ARRAY_SIZE(xelpmp_regs);
1197 		}
1198 	} else {
1199 		if (GRAPHICS_VER_FULL(i915) == IP_VER(12, 71) ||
1200 		    GRAPHICS_VER_FULL(i915) == IP_VER(12, 70) ||
1201 		    GRAPHICS_VER_FULL(i915) == IP_VER(12, 50) ||
1202 		    GRAPHICS_VER_FULL(i915) == IP_VER(12, 55)) {
1203 			regs = xehp_regs;
1204 			num = ARRAY_SIZE(xehp_regs);
1205 		} else if (GRAPHICS_VER_FULL(i915) == IP_VER(12, 0) ||
1206 			   GRAPHICS_VER_FULL(i915) == IP_VER(12, 10)) {
1207 			regs = gen12_regs;
1208 			num = ARRAY_SIZE(gen12_regs);
1209 		} else if (GRAPHICS_VER(i915) >= 8 && GRAPHICS_VER(i915) <= 11) {
1210 			regs = gen8_regs;
1211 			num = ARRAY_SIZE(gen8_regs);
1212 		} else if (GRAPHICS_VER(i915) < 8) {
1213 			return 0;
1214 		}
1215 	}
1216 
1217 	if (gt_WARN_ONCE(engine->gt, !num,
1218 			 "Platform does not implement TLB invalidation!"))
1219 		return -ENODEV;
1220 
1221 	if (gt_WARN_ON_ONCE(engine->gt,
1222 			    class >= num ||
1223 			    (!regs[class].reg.reg &&
1224 			     !regs[class].mcr_reg.reg)))
1225 		return -ERANGE;
1226 
1227 	reg = regs[class];
1228 
1229 	if (regs == xelpmp_regs && class == OTHER_CLASS) {
1230 		/*
1231 		 * There's only a single GSC instance, but it uses register bit
1232 		 * 1 instead of either 0 or OTHER_GSC_INSTANCE.
1233 		 */
1234 		GEM_WARN_ON(instance != OTHER_GSC_INSTANCE);
1235 		val = 1;
1236 	} else if (regs == gen8_regs && class == VIDEO_DECODE_CLASS && instance == 1) {
1237 		reg.reg = GEN8_M2TCR;
1238 		val = 0;
1239 	} else {
1240 		val = instance;
1241 	}
1242 
1243 	val = BIT(val);
1244 
1245 	engine->tlb_inv.mcr = regs == xehp_regs;
1246 	engine->tlb_inv.reg = reg;
1247 	engine->tlb_inv.done = val;
1248 
1249 	if (GRAPHICS_VER(i915) >= 12 &&
1250 	    (engine->class == VIDEO_DECODE_CLASS ||
1251 	     engine->class == VIDEO_ENHANCEMENT_CLASS ||
1252 	     engine->class == COMPUTE_CLASS ||
1253 	     engine->class == OTHER_CLASS))
1254 		engine->tlb_inv.request = _MASKED_BIT_ENABLE(val);
1255 	else
1256 		engine->tlb_inv.request = val;
1257 
1258 	return 0;
1259 }
1260 
1261 static int engine_setup_common(struct intel_engine_cs *engine)
1262 {
1263 	int err;
1264 
1265 	init_llist_head(&engine->barrier_tasks);
1266 
1267 	err = intel_engine_init_tlb_invalidation(engine);
1268 	if (err)
1269 		return err;
1270 
1271 	err = init_status_page(engine);
1272 	if (err)
1273 		return err;
1274 
1275 	engine->breadcrumbs = intel_breadcrumbs_create(engine);
1276 	if (!engine->breadcrumbs) {
1277 		err = -ENOMEM;
1278 		goto err_status;
1279 	}
1280 
1281 	engine->sched_engine = i915_sched_engine_create(ENGINE_PHYSICAL);
1282 	if (!engine->sched_engine) {
1283 		err = -ENOMEM;
1284 		goto err_sched_engine;
1285 	}
1286 	engine->sched_engine->private_data = engine;
1287 
1288 	err = intel_engine_init_cmd_parser(engine);
1289 	if (err)
1290 		goto err_cmd_parser;
1291 
1292 	intel_engine_init_execlists(engine);
1293 	intel_engine_init__pm(engine);
1294 	intel_engine_init_retire(engine);
1295 
1296 	/* Use the whole device by default */
1297 	engine->sseu =
1298 		intel_sseu_from_device_info(&engine->gt->info.sseu);
1299 
1300 	intel_engine_init_workarounds(engine);
1301 	intel_engine_init_whitelist(engine);
1302 	intel_engine_init_ctx_wa(engine);
1303 
1304 	if (GRAPHICS_VER(engine->i915) >= 12)
1305 		engine->flags |= I915_ENGINE_HAS_RELATIVE_MMIO;
1306 
1307 	return 0;
1308 
1309 err_cmd_parser:
1310 	i915_sched_engine_put(engine->sched_engine);
1311 err_sched_engine:
1312 	intel_breadcrumbs_put(engine->breadcrumbs);
1313 err_status:
1314 	cleanup_status_page(engine);
1315 	return err;
1316 }
1317 
1318 struct measure_breadcrumb {
1319 	struct i915_request rq;
1320 	struct intel_ring ring;
1321 	u32 cs[2048];
1322 };
1323 
1324 static int measure_breadcrumb_dw(struct intel_context *ce)
1325 {
1326 	struct intel_engine_cs *engine = ce->engine;
1327 	struct measure_breadcrumb *frame;
1328 	int dw;
1329 
1330 	GEM_BUG_ON(!engine->gt->scratch);
1331 
1332 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1333 	if (!frame)
1334 		return -ENOMEM;
1335 
1336 	frame->rq.engine = engine;
1337 	frame->rq.context = ce;
1338 	rcu_assign_pointer(frame->rq.timeline, ce->timeline);
1339 	frame->rq.hwsp_seqno = ce->timeline->hwsp_seqno;
1340 
1341 	frame->ring.vaddr = frame->cs;
1342 	frame->ring.size = sizeof(frame->cs);
1343 	frame->ring.wrap =
1344 		BITS_PER_TYPE(frame->ring.size) - ilog2(frame->ring.size);
1345 	frame->ring.effective_size = frame->ring.size;
1346 	intel_ring_update_space(&frame->ring);
1347 	frame->rq.ring = &frame->ring;
1348 
1349 	mutex_lock(&ce->timeline->mutex);
1350 	spin_lock_irq(&engine->sched_engine->lock);
1351 
1352 	dw = engine->emit_fini_breadcrumb(&frame->rq, frame->cs) - frame->cs;
1353 
1354 	spin_unlock_irq(&engine->sched_engine->lock);
1355 	mutex_unlock(&ce->timeline->mutex);
1356 
1357 	GEM_BUG_ON(dw & 1); /* RING_TAIL must be qword aligned */
1358 
1359 	kfree(frame);
1360 	return dw;
1361 }
1362 
1363 struct intel_context *
1364 intel_engine_create_pinned_context(struct intel_engine_cs *engine,
1365 				   struct i915_address_space *vm,
1366 				   unsigned int ring_size,
1367 				   unsigned int hwsp,
1368 				   struct lock_class_key *key,
1369 				   const char *name)
1370 {
1371 	struct intel_context *ce;
1372 	int err;
1373 
1374 	ce = intel_context_create(engine);
1375 	if (IS_ERR(ce))
1376 		return ce;
1377 
1378 	__set_bit(CONTEXT_BARRIER_BIT, &ce->flags);
1379 	ce->timeline = page_pack_bits(NULL, hwsp);
1380 	ce->ring = NULL;
1381 	ce->ring_size = ring_size;
1382 
1383 	i915_vm_put(ce->vm);
1384 	ce->vm = i915_vm_get(vm);
1385 
1386 	err = intel_context_pin(ce); /* perma-pin so it is always available */
1387 	if (err) {
1388 		intel_context_put(ce);
1389 		return ERR_PTR(err);
1390 	}
1391 
1392 	list_add_tail(&ce->pinned_contexts_link, &engine->pinned_contexts_list);
1393 
1394 	/*
1395 	 * Give our perma-pinned kernel timelines a separate lockdep class,
1396 	 * so that we can use them from within the normal user timelines
1397 	 * should we need to inject GPU operations during their request
1398 	 * construction.
1399 	 */
1400 	lockdep_set_class_and_name(&ce->timeline->mutex, key, name);
1401 
1402 	return ce;
1403 }
1404 
1405 void intel_engine_destroy_pinned_context(struct intel_context *ce)
1406 {
1407 	struct intel_engine_cs *engine = ce->engine;
1408 	struct i915_vma *hwsp = engine->status_page.vma;
1409 
1410 	GEM_BUG_ON(ce->timeline->hwsp_ggtt != hwsp);
1411 
1412 	mutex_lock(&hwsp->vm->mutex);
1413 	list_del(&ce->timeline->engine_link);
1414 	mutex_unlock(&hwsp->vm->mutex);
1415 
1416 	list_del(&ce->pinned_contexts_link);
1417 	intel_context_unpin(ce);
1418 	intel_context_put(ce);
1419 }
1420 
1421 static struct intel_context *
1422 create_kernel_context(struct intel_engine_cs *engine)
1423 {
1424 	static struct lock_class_key kernel;
1425 
1426 	return intel_engine_create_pinned_context(engine, engine->gt->vm, SZ_4K,
1427 						  I915_GEM_HWS_SEQNO_ADDR,
1428 						  &kernel, "kernel_context");
1429 }
1430 
1431 /*
1432  * engine_init_common - initialize engine state which might require hw access
1433  * @engine: Engine to initialize.
1434  *
1435  * Initializes @engine@ structure members shared between legacy and execlists
1436  * submission modes which do require hardware access.
1437  *
1438  * Typcally done at later stages of submission mode specific engine setup.
1439  *
1440  * Returns zero on success or an error code on failure.
1441  */
1442 static int engine_init_common(struct intel_engine_cs *engine)
1443 {
1444 	struct intel_context *ce;
1445 	int ret;
1446 
1447 	engine->set_default_submission(engine);
1448 
1449 	/*
1450 	 * We may need to do things with the shrinker which
1451 	 * require us to immediately switch back to the default
1452 	 * context. This can cause a problem as pinning the
1453 	 * default context also requires GTT space which may not
1454 	 * be available. To avoid this we always pin the default
1455 	 * context.
1456 	 */
1457 	ce = create_kernel_context(engine);
1458 	if (IS_ERR(ce))
1459 		return PTR_ERR(ce);
1460 
1461 	ret = measure_breadcrumb_dw(ce);
1462 	if (ret < 0)
1463 		goto err_context;
1464 
1465 	engine->emit_fini_breadcrumb_dw = ret;
1466 	engine->kernel_context = ce;
1467 
1468 	return 0;
1469 
1470 err_context:
1471 	intel_engine_destroy_pinned_context(ce);
1472 	return ret;
1473 }
1474 
1475 int intel_engines_init(struct intel_gt *gt)
1476 {
1477 	int (*setup)(struct intel_engine_cs *engine);
1478 	struct intel_engine_cs *engine;
1479 	enum intel_engine_id id;
1480 	int err;
1481 
1482 	if (intel_uc_uses_guc_submission(&gt->uc)) {
1483 		gt->submission_method = INTEL_SUBMISSION_GUC;
1484 		setup = intel_guc_submission_setup;
1485 	} else if (HAS_EXECLISTS(gt->i915)) {
1486 		gt->submission_method = INTEL_SUBMISSION_ELSP;
1487 		setup = intel_execlists_submission_setup;
1488 	} else {
1489 		gt->submission_method = INTEL_SUBMISSION_RING;
1490 		setup = intel_ring_submission_setup;
1491 	}
1492 
1493 	for_each_engine(engine, gt, id) {
1494 		err = engine_setup_common(engine);
1495 		if (err)
1496 			return err;
1497 
1498 		err = setup(engine);
1499 		if (err) {
1500 			intel_engine_cleanup_common(engine);
1501 			return err;
1502 		}
1503 
1504 		/* The backend should now be responsible for cleanup */
1505 		GEM_BUG_ON(engine->release == NULL);
1506 
1507 		err = engine_init_common(engine);
1508 		if (err)
1509 			return err;
1510 
1511 		intel_engine_add_user(engine);
1512 	}
1513 
1514 	return 0;
1515 }
1516 
1517 /**
1518  * intel_engines_cleanup_common - cleans up the engine state created by
1519  *                                the common initiailizers.
1520  * @engine: Engine to cleanup.
1521  *
1522  * This cleans up everything created by the common helpers.
1523  */
1524 void intel_engine_cleanup_common(struct intel_engine_cs *engine)
1525 {
1526 	GEM_BUG_ON(!list_empty(&engine->sched_engine->requests));
1527 
1528 	i915_sched_engine_put(engine->sched_engine);
1529 	intel_breadcrumbs_put(engine->breadcrumbs);
1530 
1531 	intel_engine_fini_retire(engine);
1532 	intel_engine_cleanup_cmd_parser(engine);
1533 
1534 	if (engine->default_state)
1535 		fput(engine->default_state);
1536 
1537 	if (engine->kernel_context)
1538 		intel_engine_destroy_pinned_context(engine->kernel_context);
1539 
1540 	GEM_BUG_ON(!llist_empty(&engine->barrier_tasks));
1541 	cleanup_status_page(engine);
1542 
1543 	intel_wa_list_free(&engine->ctx_wa_list);
1544 	intel_wa_list_free(&engine->wa_list);
1545 	intel_wa_list_free(&engine->whitelist);
1546 }
1547 
1548 /**
1549  * intel_engine_resume - re-initializes the HW state of the engine
1550  * @engine: Engine to resume.
1551  *
1552  * Returns zero on success or an error code on failure.
1553  */
1554 int intel_engine_resume(struct intel_engine_cs *engine)
1555 {
1556 	intel_engine_apply_workarounds(engine);
1557 	intel_engine_apply_whitelist(engine);
1558 
1559 	return engine->resume(engine);
1560 }
1561 
1562 u64 intel_engine_get_active_head(const struct intel_engine_cs *engine)
1563 {
1564 	struct drm_i915_private *i915 = engine->i915;
1565 
1566 	u64 acthd;
1567 
1568 	if (GRAPHICS_VER(i915) >= 8)
1569 		acthd = ENGINE_READ64(engine, RING_ACTHD, RING_ACTHD_UDW);
1570 	else if (GRAPHICS_VER(i915) >= 4)
1571 		acthd = ENGINE_READ(engine, RING_ACTHD);
1572 	else
1573 		acthd = ENGINE_READ(engine, ACTHD);
1574 
1575 	return acthd;
1576 }
1577 
1578 u64 intel_engine_get_last_batch_head(const struct intel_engine_cs *engine)
1579 {
1580 	u64 bbaddr;
1581 
1582 	if (GRAPHICS_VER(engine->i915) >= 8)
1583 		bbaddr = ENGINE_READ64(engine, RING_BBADDR, RING_BBADDR_UDW);
1584 	else
1585 		bbaddr = ENGINE_READ(engine, RING_BBADDR);
1586 
1587 	return bbaddr;
1588 }
1589 
1590 static unsigned long stop_timeout(const struct intel_engine_cs *engine)
1591 {
1592 	if (in_atomic() || irqs_disabled()) /* inside atomic preempt-reset? */
1593 		return 0;
1594 
1595 	/*
1596 	 * If we are doing a normal GPU reset, we can take our time and allow
1597 	 * the engine to quiesce. We've stopped submission to the engine, and
1598 	 * if we wait long enough an innocent context should complete and
1599 	 * leave the engine idle. So they should not be caught unaware by
1600 	 * the forthcoming GPU reset (which usually follows the stop_cs)!
1601 	 */
1602 	return READ_ONCE(engine->props.stop_timeout_ms);
1603 }
1604 
1605 static int __intel_engine_stop_cs(struct intel_engine_cs *engine,
1606 				  int fast_timeout_us,
1607 				  int slow_timeout_ms)
1608 {
1609 	struct intel_uncore *uncore = engine->uncore;
1610 	const i915_reg_t mode = RING_MI_MODE(engine->mmio_base);
1611 	int err;
1612 
1613 	intel_uncore_write_fw(uncore, mode, _MASKED_BIT_ENABLE(STOP_RING));
1614 
1615 	/*
1616 	 * Wa_22011802037: Prior to doing a reset, ensure CS is
1617 	 * stopped, set ring stop bit and prefetch disable bit to halt CS
1618 	 */
1619 	if (IS_MTL_GRAPHICS_STEP(engine->i915, M, STEP_A0, STEP_B0) ||
1620 	    (GRAPHICS_VER(engine->i915) >= 11 &&
1621 	    GRAPHICS_VER_FULL(engine->i915) < IP_VER(12, 70)))
1622 		intel_uncore_write_fw(uncore, RING_MODE_GEN7(engine->mmio_base),
1623 				      _MASKED_BIT_ENABLE(GEN12_GFX_PREFETCH_DISABLE));
1624 
1625 	err = __intel_wait_for_register_fw(engine->uncore, mode,
1626 					   MODE_IDLE, MODE_IDLE,
1627 					   fast_timeout_us,
1628 					   slow_timeout_ms,
1629 					   NULL);
1630 
1631 	/* A final mmio read to let GPU writes be hopefully flushed to memory */
1632 	intel_uncore_posting_read_fw(uncore, mode);
1633 	return err;
1634 }
1635 
1636 int intel_engine_stop_cs(struct intel_engine_cs *engine)
1637 {
1638 	int err = 0;
1639 
1640 	if (GRAPHICS_VER(engine->i915) < 3)
1641 		return -ENODEV;
1642 
1643 	ENGINE_TRACE(engine, "\n");
1644 	/*
1645 	 * TODO: Find out why occasionally stopping the CS times out. Seen
1646 	 * especially with gem_eio tests.
1647 	 *
1648 	 * Occasionally trying to stop the cs times out, but does not adversely
1649 	 * affect functionality. The timeout is set as a config parameter that
1650 	 * defaults to 100ms. In most cases the follow up operation is to wait
1651 	 * for pending MI_FORCE_WAKES. The assumption is that this timeout is
1652 	 * sufficient for any pending MI_FORCEWAKEs to complete. Once root
1653 	 * caused, the caller must check and handle the return from this
1654 	 * function.
1655 	 */
1656 	if (__intel_engine_stop_cs(engine, 1000, stop_timeout(engine))) {
1657 		ENGINE_TRACE(engine,
1658 			     "timed out on STOP_RING -> IDLE; HEAD:%04x, TAIL:%04x\n",
1659 			     ENGINE_READ_FW(engine, RING_HEAD) & HEAD_ADDR,
1660 			     ENGINE_READ_FW(engine, RING_TAIL) & TAIL_ADDR);
1661 
1662 		/*
1663 		 * Sometimes we observe that the idle flag is not
1664 		 * set even though the ring is empty. So double
1665 		 * check before giving up.
1666 		 */
1667 		if ((ENGINE_READ_FW(engine, RING_HEAD) & HEAD_ADDR) !=
1668 		    (ENGINE_READ_FW(engine, RING_TAIL) & TAIL_ADDR))
1669 			err = -ETIMEDOUT;
1670 	}
1671 
1672 	return err;
1673 }
1674 
1675 void intel_engine_cancel_stop_cs(struct intel_engine_cs *engine)
1676 {
1677 	ENGINE_TRACE(engine, "\n");
1678 
1679 	ENGINE_WRITE_FW(engine, RING_MI_MODE, _MASKED_BIT_DISABLE(STOP_RING));
1680 }
1681 
1682 static u32 __cs_pending_mi_force_wakes(struct intel_engine_cs *engine)
1683 {
1684 	static const i915_reg_t _reg[I915_NUM_ENGINES] = {
1685 		[RCS0] = MSG_IDLE_CS,
1686 		[BCS0] = MSG_IDLE_BCS,
1687 		[VCS0] = MSG_IDLE_VCS0,
1688 		[VCS1] = MSG_IDLE_VCS1,
1689 		[VCS2] = MSG_IDLE_VCS2,
1690 		[VCS3] = MSG_IDLE_VCS3,
1691 		[VCS4] = MSG_IDLE_VCS4,
1692 		[VCS5] = MSG_IDLE_VCS5,
1693 		[VCS6] = MSG_IDLE_VCS6,
1694 		[VCS7] = MSG_IDLE_VCS7,
1695 		[VECS0] = MSG_IDLE_VECS0,
1696 		[VECS1] = MSG_IDLE_VECS1,
1697 		[VECS2] = MSG_IDLE_VECS2,
1698 		[VECS3] = MSG_IDLE_VECS3,
1699 		[CCS0] = MSG_IDLE_CS,
1700 		[CCS1] = MSG_IDLE_CS,
1701 		[CCS2] = MSG_IDLE_CS,
1702 		[CCS3] = MSG_IDLE_CS,
1703 	};
1704 	u32 val;
1705 
1706 	if (!_reg[engine->id].reg)
1707 		return 0;
1708 
1709 	val = intel_uncore_read(engine->uncore, _reg[engine->id]);
1710 
1711 	/* bits[29:25] & bits[13:9] >> shift */
1712 	return (val & (val >> 16) & MSG_IDLE_FW_MASK) >> MSG_IDLE_FW_SHIFT;
1713 }
1714 
1715 static void __gpm_wait_for_fw_complete(struct intel_gt *gt, u32 fw_mask)
1716 {
1717 	int ret;
1718 
1719 	/* Ensure GPM receives fw up/down after CS is stopped */
1720 	udelay(1);
1721 
1722 	/* Wait for forcewake request to complete in GPM */
1723 	ret =  __intel_wait_for_register_fw(gt->uncore,
1724 					    GEN9_PWRGT_DOMAIN_STATUS,
1725 					    fw_mask, fw_mask, 5000, 0, NULL);
1726 
1727 	/* Ensure CS receives fw ack from GPM */
1728 	udelay(1);
1729 
1730 	if (ret)
1731 		GT_TRACE(gt, "Failed to complete pending forcewake %d\n", ret);
1732 }
1733 
1734 /*
1735  * Wa_22011802037:gen12: In addition to stopping the cs, we need to wait for any
1736  * pending MI_FORCE_WAKEUP requests that the CS has initiated to complete. The
1737  * pending status is indicated by bits[13:9] (masked by bits[29:25]) in the
1738  * MSG_IDLE register. There's one MSG_IDLE register per reset domain. Since we
1739  * are concerned only with the gt reset here, we use a logical OR of pending
1740  * forcewakeups from all reset domains and then wait for them to complete by
1741  * querying PWRGT_DOMAIN_STATUS.
1742  */
1743 void intel_engine_wait_for_pending_mi_fw(struct intel_engine_cs *engine)
1744 {
1745 	u32 fw_pending = __cs_pending_mi_force_wakes(engine);
1746 
1747 	if (fw_pending)
1748 		__gpm_wait_for_fw_complete(engine->gt, fw_pending);
1749 }
1750 
1751 /* NB: please notice the memset */
1752 void intel_engine_get_instdone(const struct intel_engine_cs *engine,
1753 			       struct intel_instdone *instdone)
1754 {
1755 	struct drm_i915_private *i915 = engine->i915;
1756 	struct intel_uncore *uncore = engine->uncore;
1757 	u32 mmio_base = engine->mmio_base;
1758 	int slice;
1759 	int subslice;
1760 	int iter;
1761 
1762 	memset(instdone, 0, sizeof(*instdone));
1763 
1764 	if (GRAPHICS_VER(i915) >= 8) {
1765 		instdone->instdone =
1766 			intel_uncore_read(uncore, RING_INSTDONE(mmio_base));
1767 
1768 		if (engine->id != RCS0)
1769 			return;
1770 
1771 		instdone->slice_common =
1772 			intel_uncore_read(uncore, GEN7_SC_INSTDONE);
1773 		if (GRAPHICS_VER(i915) >= 12) {
1774 			instdone->slice_common_extra[0] =
1775 				intel_uncore_read(uncore, GEN12_SC_INSTDONE_EXTRA);
1776 			instdone->slice_common_extra[1] =
1777 				intel_uncore_read(uncore, GEN12_SC_INSTDONE_EXTRA2);
1778 		}
1779 
1780 		for_each_ss_steering(iter, engine->gt, slice, subslice) {
1781 			instdone->sampler[slice][subslice] =
1782 				intel_gt_mcr_read(engine->gt,
1783 						  GEN8_SAMPLER_INSTDONE,
1784 						  slice, subslice);
1785 			instdone->row[slice][subslice] =
1786 				intel_gt_mcr_read(engine->gt,
1787 						  GEN8_ROW_INSTDONE,
1788 						  slice, subslice);
1789 		}
1790 
1791 		if (GRAPHICS_VER_FULL(i915) >= IP_VER(12, 55)) {
1792 			for_each_ss_steering(iter, engine->gt, slice, subslice)
1793 				instdone->geom_svg[slice][subslice] =
1794 					intel_gt_mcr_read(engine->gt,
1795 							  XEHPG_INSTDONE_GEOM_SVG,
1796 							  slice, subslice);
1797 		}
1798 	} else if (GRAPHICS_VER(i915) >= 7) {
1799 		instdone->instdone =
1800 			intel_uncore_read(uncore, RING_INSTDONE(mmio_base));
1801 
1802 		if (engine->id != RCS0)
1803 			return;
1804 
1805 		instdone->slice_common =
1806 			intel_uncore_read(uncore, GEN7_SC_INSTDONE);
1807 		instdone->sampler[0][0] =
1808 			intel_uncore_read(uncore, GEN7_SAMPLER_INSTDONE);
1809 		instdone->row[0][0] =
1810 			intel_uncore_read(uncore, GEN7_ROW_INSTDONE);
1811 	} else if (GRAPHICS_VER(i915) >= 4) {
1812 		instdone->instdone =
1813 			intel_uncore_read(uncore, RING_INSTDONE(mmio_base));
1814 		if (engine->id == RCS0)
1815 			/* HACK: Using the wrong struct member */
1816 			instdone->slice_common =
1817 				intel_uncore_read(uncore, GEN4_INSTDONE1);
1818 	} else {
1819 		instdone->instdone = intel_uncore_read(uncore, GEN2_INSTDONE);
1820 	}
1821 }
1822 
1823 static bool ring_is_idle(struct intel_engine_cs *engine)
1824 {
1825 	bool idle = true;
1826 
1827 	if (I915_SELFTEST_ONLY(!engine->mmio_base))
1828 		return true;
1829 
1830 	if (!intel_engine_pm_get_if_awake(engine))
1831 		return true;
1832 
1833 	/* First check that no commands are left in the ring */
1834 	if ((ENGINE_READ(engine, RING_HEAD) & HEAD_ADDR) !=
1835 	    (ENGINE_READ(engine, RING_TAIL) & TAIL_ADDR))
1836 		idle = false;
1837 
1838 	/* No bit for gen2, so assume the CS parser is idle */
1839 	if (GRAPHICS_VER(engine->i915) > 2 &&
1840 	    !(ENGINE_READ(engine, RING_MI_MODE) & MODE_IDLE))
1841 		idle = false;
1842 
1843 	intel_engine_pm_put(engine);
1844 
1845 	return idle;
1846 }
1847 
1848 void __intel_engine_flush_submission(struct intel_engine_cs *engine, bool sync)
1849 {
1850 	struct tasklet_struct *t = &engine->sched_engine->tasklet;
1851 
1852 	if (!t->callback)
1853 		return;
1854 
1855 	local_bh_disable();
1856 	if (tasklet_trylock(t)) {
1857 		/* Must wait for any GPU reset in progress. */
1858 		if (__tasklet_is_enabled(t))
1859 			t->callback(t);
1860 		tasklet_unlock(t);
1861 	}
1862 	local_bh_enable();
1863 
1864 	/* Synchronise and wait for the tasklet on another CPU */
1865 	if (sync)
1866 		tasklet_unlock_wait(t);
1867 }
1868 
1869 /**
1870  * intel_engine_is_idle() - Report if the engine has finished process all work
1871  * @engine: the intel_engine_cs
1872  *
1873  * Return true if there are no requests pending, nothing left to be submitted
1874  * to hardware, and that the engine is idle.
1875  */
1876 bool intel_engine_is_idle(struct intel_engine_cs *engine)
1877 {
1878 	/* More white lies, if wedged, hw state is inconsistent */
1879 	if (intel_gt_is_wedged(engine->gt))
1880 		return true;
1881 
1882 	if (!intel_engine_pm_is_awake(engine))
1883 		return true;
1884 
1885 	/* Waiting to drain ELSP? */
1886 	intel_synchronize_hardirq(engine->i915);
1887 	intel_engine_flush_submission(engine);
1888 
1889 	/* ELSP is empty, but there are ready requests? E.g. after reset */
1890 	if (!i915_sched_engine_is_empty(engine->sched_engine))
1891 		return false;
1892 
1893 	/* Ring stopped? */
1894 	return ring_is_idle(engine);
1895 }
1896 
1897 bool intel_engines_are_idle(struct intel_gt *gt)
1898 {
1899 	struct intel_engine_cs *engine;
1900 	enum intel_engine_id id;
1901 
1902 	/*
1903 	 * If the driver is wedged, HW state may be very inconsistent and
1904 	 * report that it is still busy, even though we have stopped using it.
1905 	 */
1906 	if (intel_gt_is_wedged(gt))
1907 		return true;
1908 
1909 	/* Already parked (and passed an idleness test); must still be idle */
1910 	if (!READ_ONCE(gt->awake))
1911 		return true;
1912 
1913 	for_each_engine(engine, gt, id) {
1914 		if (!intel_engine_is_idle(engine))
1915 			return false;
1916 	}
1917 
1918 	return true;
1919 }
1920 
1921 bool intel_engine_irq_enable(struct intel_engine_cs *engine)
1922 {
1923 	if (!engine->irq_enable)
1924 		return false;
1925 
1926 	/* Caller disables interrupts */
1927 	spin_lock(engine->gt->irq_lock);
1928 	engine->irq_enable(engine);
1929 	spin_unlock(engine->gt->irq_lock);
1930 
1931 	return true;
1932 }
1933 
1934 void intel_engine_irq_disable(struct intel_engine_cs *engine)
1935 {
1936 	if (!engine->irq_disable)
1937 		return;
1938 
1939 	/* Caller disables interrupts */
1940 	spin_lock(engine->gt->irq_lock);
1941 	engine->irq_disable(engine);
1942 	spin_unlock(engine->gt->irq_lock);
1943 }
1944 
1945 void intel_engines_reset_default_submission(struct intel_gt *gt)
1946 {
1947 	struct intel_engine_cs *engine;
1948 	enum intel_engine_id id;
1949 
1950 	for_each_engine(engine, gt, id) {
1951 		if (engine->sanitize)
1952 			engine->sanitize(engine);
1953 
1954 		engine->set_default_submission(engine);
1955 	}
1956 }
1957 
1958 bool intel_engine_can_store_dword(struct intel_engine_cs *engine)
1959 {
1960 	switch (GRAPHICS_VER(engine->i915)) {
1961 	case 2:
1962 		return false; /* uses physical not virtual addresses */
1963 	case 3:
1964 		/* maybe only uses physical not virtual addresses */
1965 		return !(IS_I915G(engine->i915) || IS_I915GM(engine->i915));
1966 	case 4:
1967 		return !IS_I965G(engine->i915); /* who knows! */
1968 	case 6:
1969 		return engine->class != VIDEO_DECODE_CLASS; /* b0rked */
1970 	default:
1971 		return true;
1972 	}
1973 }
1974 
1975 static struct intel_timeline *get_timeline(struct i915_request *rq)
1976 {
1977 	struct intel_timeline *tl;
1978 
1979 	/*
1980 	 * Even though we are holding the engine->sched_engine->lock here, there
1981 	 * is no control over the submission queue per-se and we are
1982 	 * inspecting the active state at a random point in time, with an
1983 	 * unknown queue. Play safe and make sure the timeline remains valid.
1984 	 * (Only being used for pretty printing, one extra kref shouldn't
1985 	 * cause a camel stampede!)
1986 	 */
1987 	rcu_read_lock();
1988 	tl = rcu_dereference(rq->timeline);
1989 	if (!kref_get_unless_zero(&tl->kref))
1990 		tl = NULL;
1991 	rcu_read_unlock();
1992 
1993 	return tl;
1994 }
1995 
1996 static int print_ring(char *buf, int sz, struct i915_request *rq)
1997 {
1998 	int len = 0;
1999 
2000 	if (!i915_request_signaled(rq)) {
2001 		struct intel_timeline *tl = get_timeline(rq);
2002 
2003 		len = scnprintf(buf, sz,
2004 				"ring:{start:%08x, hwsp:%08x, seqno:%08x, runtime:%llums}, ",
2005 				i915_ggtt_offset(rq->ring->vma),
2006 				tl ? tl->hwsp_offset : 0,
2007 				hwsp_seqno(rq),
2008 				DIV_ROUND_CLOSEST_ULL(intel_context_get_total_runtime_ns(rq->context),
2009 						      1000 * 1000));
2010 
2011 		if (tl)
2012 			intel_timeline_put(tl);
2013 	}
2014 
2015 	return len;
2016 }
2017 
2018 static void hexdump(struct drm_printer *m, const void *buf, size_t len)
2019 {
2020 	const size_t rowsize = 8 * sizeof(u32);
2021 	const void *prev = NULL;
2022 	bool skip = false;
2023 	size_t pos;
2024 
2025 	for (pos = 0; pos < len; pos += rowsize) {
2026 		char line[128];
2027 
2028 		if (prev && !memcmp(prev, buf + pos, rowsize)) {
2029 			if (!skip) {
2030 				drm_printf(m, "*\n");
2031 				skip = true;
2032 			}
2033 			continue;
2034 		}
2035 
2036 		WARN_ON_ONCE(hex_dump_to_buffer(buf + pos, len - pos,
2037 						rowsize, sizeof(u32),
2038 						line, sizeof(line),
2039 						false) >= sizeof(line));
2040 		drm_printf(m, "[%04zx] %s\n", pos, line);
2041 
2042 		prev = buf + pos;
2043 		skip = false;
2044 	}
2045 }
2046 
2047 static const char *repr_timer(const struct timer_list *t)
2048 {
2049 	if (!READ_ONCE(t->expires))
2050 		return "inactive";
2051 
2052 	if (timer_pending(t))
2053 		return "active";
2054 
2055 	return "expired";
2056 }
2057 
2058 static void intel_engine_print_registers(struct intel_engine_cs *engine,
2059 					 struct drm_printer *m)
2060 {
2061 	struct drm_i915_private *i915 = engine->i915;
2062 	struct intel_engine_execlists * const execlists = &engine->execlists;
2063 	u64 addr;
2064 
2065 	if (engine->id == RENDER_CLASS && IS_GRAPHICS_VER(i915, 4, 7))
2066 		drm_printf(m, "\tCCID: 0x%08x\n", ENGINE_READ(engine, CCID));
2067 	if (HAS_EXECLISTS(i915)) {
2068 		drm_printf(m, "\tEL_STAT_HI: 0x%08x\n",
2069 			   ENGINE_READ(engine, RING_EXECLIST_STATUS_HI));
2070 		drm_printf(m, "\tEL_STAT_LO: 0x%08x\n",
2071 			   ENGINE_READ(engine, RING_EXECLIST_STATUS_LO));
2072 	}
2073 	drm_printf(m, "\tRING_START: 0x%08x\n",
2074 		   ENGINE_READ(engine, RING_START));
2075 	drm_printf(m, "\tRING_HEAD:  0x%08x\n",
2076 		   ENGINE_READ(engine, RING_HEAD) & HEAD_ADDR);
2077 	drm_printf(m, "\tRING_TAIL:  0x%08x\n",
2078 		   ENGINE_READ(engine, RING_TAIL) & TAIL_ADDR);
2079 	drm_printf(m, "\tRING_CTL:   0x%08x%s\n",
2080 		   ENGINE_READ(engine, RING_CTL),
2081 		   ENGINE_READ(engine, RING_CTL) & (RING_WAIT | RING_WAIT_SEMAPHORE) ? " [waiting]" : "");
2082 	if (GRAPHICS_VER(engine->i915) > 2) {
2083 		drm_printf(m, "\tRING_MODE:  0x%08x%s\n",
2084 			   ENGINE_READ(engine, RING_MI_MODE),
2085 			   ENGINE_READ(engine, RING_MI_MODE) & (MODE_IDLE) ? " [idle]" : "");
2086 	}
2087 
2088 	if (GRAPHICS_VER(i915) >= 6) {
2089 		drm_printf(m, "\tRING_IMR:   0x%08x\n",
2090 			   ENGINE_READ(engine, RING_IMR));
2091 		drm_printf(m, "\tRING_ESR:   0x%08x\n",
2092 			   ENGINE_READ(engine, RING_ESR));
2093 		drm_printf(m, "\tRING_EMR:   0x%08x\n",
2094 			   ENGINE_READ(engine, RING_EMR));
2095 		drm_printf(m, "\tRING_EIR:   0x%08x\n",
2096 			   ENGINE_READ(engine, RING_EIR));
2097 	}
2098 
2099 	addr = intel_engine_get_active_head(engine);
2100 	drm_printf(m, "\tACTHD:  0x%08x_%08x\n",
2101 		   upper_32_bits(addr), lower_32_bits(addr));
2102 	addr = intel_engine_get_last_batch_head(engine);
2103 	drm_printf(m, "\tBBADDR: 0x%08x_%08x\n",
2104 		   upper_32_bits(addr), lower_32_bits(addr));
2105 	if (GRAPHICS_VER(i915) >= 8)
2106 		addr = ENGINE_READ64(engine, RING_DMA_FADD, RING_DMA_FADD_UDW);
2107 	else if (GRAPHICS_VER(i915) >= 4)
2108 		addr = ENGINE_READ(engine, RING_DMA_FADD);
2109 	else
2110 		addr = ENGINE_READ(engine, DMA_FADD_I8XX);
2111 	drm_printf(m, "\tDMA_FADDR: 0x%08x_%08x\n",
2112 		   upper_32_bits(addr), lower_32_bits(addr));
2113 	if (GRAPHICS_VER(i915) >= 4) {
2114 		drm_printf(m, "\tIPEIR: 0x%08x\n",
2115 			   ENGINE_READ(engine, RING_IPEIR));
2116 		drm_printf(m, "\tIPEHR: 0x%08x\n",
2117 			   ENGINE_READ(engine, RING_IPEHR));
2118 	} else {
2119 		drm_printf(m, "\tIPEIR: 0x%08x\n", ENGINE_READ(engine, IPEIR));
2120 		drm_printf(m, "\tIPEHR: 0x%08x\n", ENGINE_READ(engine, IPEHR));
2121 	}
2122 
2123 	if (HAS_EXECLISTS(i915) && !intel_engine_uses_guc(engine)) {
2124 		struct i915_request * const *port, *rq;
2125 		const u32 *hws =
2126 			&engine->status_page.addr[I915_HWS_CSB_BUF0_INDEX];
2127 		const u8 num_entries = execlists->csb_size;
2128 		unsigned int idx;
2129 		u8 read, write;
2130 
2131 		drm_printf(m, "\tExeclist tasklet queued? %s (%s), preempt? %s, timeslice? %s\n",
2132 			   str_yes_no(test_bit(TASKLET_STATE_SCHED, &engine->sched_engine->tasklet.state)),
2133 			   str_enabled_disabled(!atomic_read(&engine->sched_engine->tasklet.count)),
2134 			   repr_timer(&engine->execlists.preempt),
2135 			   repr_timer(&engine->execlists.timer));
2136 
2137 		read = execlists->csb_head;
2138 		write = READ_ONCE(*execlists->csb_write);
2139 
2140 		drm_printf(m, "\tExeclist status: 0x%08x %08x; CSB read:%d, write:%d, entries:%d\n",
2141 			   ENGINE_READ(engine, RING_EXECLIST_STATUS_LO),
2142 			   ENGINE_READ(engine, RING_EXECLIST_STATUS_HI),
2143 			   read, write, num_entries);
2144 
2145 		if (read >= num_entries)
2146 			read = 0;
2147 		if (write >= num_entries)
2148 			write = 0;
2149 		if (read > write)
2150 			write += num_entries;
2151 		while (read < write) {
2152 			idx = ++read % num_entries;
2153 			drm_printf(m, "\tExeclist CSB[%d]: 0x%08x, context: %d\n",
2154 				   idx, hws[idx * 2], hws[idx * 2 + 1]);
2155 		}
2156 
2157 		i915_sched_engine_active_lock_bh(engine->sched_engine);
2158 		rcu_read_lock();
2159 		for (port = execlists->active; (rq = *port); port++) {
2160 			char hdr[160];
2161 			int len;
2162 
2163 			len = scnprintf(hdr, sizeof(hdr),
2164 					"\t\tActive[%d]:  ccid:%08x%s%s, ",
2165 					(int)(port - execlists->active),
2166 					rq->context->lrc.ccid,
2167 					intel_context_is_closed(rq->context) ? "!" : "",
2168 					intel_context_is_banned(rq->context) ? "*" : "");
2169 			len += print_ring(hdr + len, sizeof(hdr) - len, rq);
2170 			scnprintf(hdr + len, sizeof(hdr) - len, "rq: ");
2171 			i915_request_show(m, rq, hdr, 0);
2172 		}
2173 		for (port = execlists->pending; (rq = *port); port++) {
2174 			char hdr[160];
2175 			int len;
2176 
2177 			len = scnprintf(hdr, sizeof(hdr),
2178 					"\t\tPending[%d]: ccid:%08x%s%s, ",
2179 					(int)(port - execlists->pending),
2180 					rq->context->lrc.ccid,
2181 					intel_context_is_closed(rq->context) ? "!" : "",
2182 					intel_context_is_banned(rq->context) ? "*" : "");
2183 			len += print_ring(hdr + len, sizeof(hdr) - len, rq);
2184 			scnprintf(hdr + len, sizeof(hdr) - len, "rq: ");
2185 			i915_request_show(m, rq, hdr, 0);
2186 		}
2187 		rcu_read_unlock();
2188 		i915_sched_engine_active_unlock_bh(engine->sched_engine);
2189 	} else if (GRAPHICS_VER(i915) > 6) {
2190 		drm_printf(m, "\tPP_DIR_BASE: 0x%08x\n",
2191 			   ENGINE_READ(engine, RING_PP_DIR_BASE));
2192 		drm_printf(m, "\tPP_DIR_BASE_READ: 0x%08x\n",
2193 			   ENGINE_READ(engine, RING_PP_DIR_BASE_READ));
2194 		drm_printf(m, "\tPP_DIR_DCLV: 0x%08x\n",
2195 			   ENGINE_READ(engine, RING_PP_DIR_DCLV));
2196 	}
2197 }
2198 
2199 static void print_request_ring(struct drm_printer *m, struct i915_request *rq)
2200 {
2201 	struct i915_vma_resource *vma_res = rq->batch_res;
2202 	void *ring;
2203 	int size;
2204 
2205 	drm_printf(m,
2206 		   "[head %04x, postfix %04x, tail %04x, batch 0x%08x_%08x]:\n",
2207 		   rq->head, rq->postfix, rq->tail,
2208 		   vma_res ? upper_32_bits(vma_res->start) : ~0u,
2209 		   vma_res ? lower_32_bits(vma_res->start) : ~0u);
2210 
2211 	size = rq->tail - rq->head;
2212 	if (rq->tail < rq->head)
2213 		size += rq->ring->size;
2214 
2215 	ring = kmalloc(size, GFP_ATOMIC);
2216 	if (ring) {
2217 		const void *vaddr = rq->ring->vaddr;
2218 		unsigned int head = rq->head;
2219 		unsigned int len = 0;
2220 
2221 		if (rq->tail < head) {
2222 			len = rq->ring->size - head;
2223 			memcpy(ring, vaddr + head, len);
2224 			head = 0;
2225 		}
2226 		memcpy(ring + len, vaddr + head, size - len);
2227 
2228 		hexdump(m, ring, size);
2229 		kfree(ring);
2230 	}
2231 }
2232 
2233 static unsigned long read_ul(void *p, size_t x)
2234 {
2235 	return *(unsigned long *)(p + x);
2236 }
2237 
2238 static void print_properties(struct intel_engine_cs *engine,
2239 			     struct drm_printer *m)
2240 {
2241 	static const struct pmap {
2242 		size_t offset;
2243 		const char *name;
2244 	} props[] = {
2245 #define P(x) { \
2246 	.offset = offsetof(typeof(engine->props), x), \
2247 	.name = #x \
2248 }
2249 		P(heartbeat_interval_ms),
2250 		P(max_busywait_duration_ns),
2251 		P(preempt_timeout_ms),
2252 		P(stop_timeout_ms),
2253 		P(timeslice_duration_ms),
2254 
2255 		{},
2256 #undef P
2257 	};
2258 	const struct pmap *p;
2259 
2260 	drm_printf(m, "\tProperties:\n");
2261 	for (p = props; p->name; p++)
2262 		drm_printf(m, "\t\t%s: %lu [default %lu]\n",
2263 			   p->name,
2264 			   read_ul(&engine->props, p->offset),
2265 			   read_ul(&engine->defaults, p->offset));
2266 }
2267 
2268 static void engine_dump_request(struct i915_request *rq, struct drm_printer *m, const char *msg)
2269 {
2270 	struct intel_timeline *tl = get_timeline(rq);
2271 
2272 	i915_request_show(m, rq, msg, 0);
2273 
2274 	drm_printf(m, "\t\tring->start:  0x%08x\n",
2275 		   i915_ggtt_offset(rq->ring->vma));
2276 	drm_printf(m, "\t\tring->head:   0x%08x\n",
2277 		   rq->ring->head);
2278 	drm_printf(m, "\t\tring->tail:   0x%08x\n",
2279 		   rq->ring->tail);
2280 	drm_printf(m, "\t\tring->emit:   0x%08x\n",
2281 		   rq->ring->emit);
2282 	drm_printf(m, "\t\tring->space:  0x%08x\n",
2283 		   rq->ring->space);
2284 
2285 	if (tl) {
2286 		drm_printf(m, "\t\tring->hwsp:   0x%08x\n",
2287 			   tl->hwsp_offset);
2288 		intel_timeline_put(tl);
2289 	}
2290 
2291 	print_request_ring(m, rq);
2292 
2293 	if (rq->context->lrc_reg_state) {
2294 		drm_printf(m, "Logical Ring Context:\n");
2295 		hexdump(m, rq->context->lrc_reg_state, PAGE_SIZE);
2296 	}
2297 }
2298 
2299 void intel_engine_dump_active_requests(struct list_head *requests,
2300 				       struct i915_request *hung_rq,
2301 				       struct drm_printer *m)
2302 {
2303 	struct i915_request *rq;
2304 	const char *msg;
2305 	enum i915_request_state state;
2306 
2307 	list_for_each_entry(rq, requests, sched.link) {
2308 		if (rq == hung_rq)
2309 			continue;
2310 
2311 		state = i915_test_request_state(rq);
2312 		if (state < I915_REQUEST_QUEUED)
2313 			continue;
2314 
2315 		if (state == I915_REQUEST_ACTIVE)
2316 			msg = "\t\tactive on engine";
2317 		else
2318 			msg = "\t\tactive in queue";
2319 
2320 		engine_dump_request(rq, m, msg);
2321 	}
2322 }
2323 
2324 static void engine_dump_active_requests(struct intel_engine_cs *engine,
2325 					struct drm_printer *m)
2326 {
2327 	struct intel_context *hung_ce = NULL;
2328 	struct i915_request *hung_rq = NULL;
2329 
2330 	/*
2331 	 * No need for an engine->irq_seqno_barrier() before the seqno reads.
2332 	 * The GPU is still running so requests are still executing and any
2333 	 * hardware reads will be out of date by the time they are reported.
2334 	 * But the intention here is just to report an instantaneous snapshot
2335 	 * so that's fine.
2336 	 */
2337 	intel_engine_get_hung_entity(engine, &hung_ce, &hung_rq);
2338 
2339 	drm_printf(m, "\tRequests:\n");
2340 
2341 	if (hung_rq)
2342 		engine_dump_request(hung_rq, m, "\t\thung");
2343 	else if (hung_ce)
2344 		drm_printf(m, "\t\tGot hung ce but no hung rq!\n");
2345 
2346 	if (intel_uc_uses_guc_submission(&engine->gt->uc))
2347 		intel_guc_dump_active_requests(engine, hung_rq, m);
2348 	else
2349 		intel_execlists_dump_active_requests(engine, hung_rq, m);
2350 
2351 	if (hung_rq)
2352 		i915_request_put(hung_rq);
2353 }
2354 
2355 void intel_engine_dump(struct intel_engine_cs *engine,
2356 		       struct drm_printer *m,
2357 		       const char *header, ...)
2358 {
2359 	struct i915_gpu_error * const error = &engine->i915->gpu_error;
2360 	struct i915_request *rq;
2361 	intel_wakeref_t wakeref;
2362 	ktime_t dummy;
2363 
2364 	if (header) {
2365 		va_list ap;
2366 
2367 		va_start(ap, header);
2368 		drm_vprintf(m, header, &ap);
2369 		va_end(ap);
2370 	}
2371 
2372 	if (intel_gt_is_wedged(engine->gt))
2373 		drm_printf(m, "*** WEDGED ***\n");
2374 
2375 	drm_printf(m, "\tAwake? %d\n", atomic_read(&engine->wakeref.count));
2376 	drm_printf(m, "\tBarriers?: %s\n",
2377 		   str_yes_no(!llist_empty(&engine->barrier_tasks)));
2378 	drm_printf(m, "\tLatency: %luus\n",
2379 		   ewma__engine_latency_read(&engine->latency));
2380 	if (intel_engine_supports_stats(engine))
2381 		drm_printf(m, "\tRuntime: %llums\n",
2382 			   ktime_to_ms(intel_engine_get_busy_time(engine,
2383 								  &dummy)));
2384 	drm_printf(m, "\tForcewake: %x domains, %d active\n",
2385 		   engine->fw_domain, READ_ONCE(engine->fw_active));
2386 
2387 	rcu_read_lock();
2388 	rq = READ_ONCE(engine->heartbeat.systole);
2389 	if (rq)
2390 		drm_printf(m, "\tHeartbeat: %d ms ago\n",
2391 			   jiffies_to_msecs(jiffies - rq->emitted_jiffies));
2392 	rcu_read_unlock();
2393 	drm_printf(m, "\tReset count: %d (global %d)\n",
2394 		   i915_reset_engine_count(error, engine),
2395 		   i915_reset_count(error));
2396 	print_properties(engine, m);
2397 
2398 	engine_dump_active_requests(engine, m);
2399 
2400 	drm_printf(m, "\tMMIO base:  0x%08x\n", engine->mmio_base);
2401 	wakeref = intel_runtime_pm_get_if_in_use(engine->uncore->rpm);
2402 	if (wakeref) {
2403 		intel_engine_print_registers(engine, m);
2404 		intel_runtime_pm_put(engine->uncore->rpm, wakeref);
2405 	} else {
2406 		drm_printf(m, "\tDevice is asleep; skipping register dump\n");
2407 	}
2408 
2409 	intel_execlists_show_requests(engine, m, i915_request_show, 8);
2410 
2411 	drm_printf(m, "HWSP:\n");
2412 	hexdump(m, engine->status_page.addr, PAGE_SIZE);
2413 
2414 	drm_printf(m, "Idle? %s\n", str_yes_no(intel_engine_is_idle(engine)));
2415 
2416 	intel_engine_print_breadcrumbs(engine, m);
2417 }
2418 
2419 /**
2420  * intel_engine_get_busy_time() - Return current accumulated engine busyness
2421  * @engine: engine to report on
2422  * @now: monotonic timestamp of sampling
2423  *
2424  * Returns accumulated time @engine was busy since engine stats were enabled.
2425  */
2426 ktime_t intel_engine_get_busy_time(struct intel_engine_cs *engine, ktime_t *now)
2427 {
2428 	return engine->busyness(engine, now);
2429 }
2430 
2431 struct intel_context *
2432 intel_engine_create_virtual(struct intel_engine_cs **siblings,
2433 			    unsigned int count, unsigned long flags)
2434 {
2435 	if (count == 0)
2436 		return ERR_PTR(-EINVAL);
2437 
2438 	if (count == 1 && !(flags & FORCE_VIRTUAL))
2439 		return intel_context_create(siblings[0]);
2440 
2441 	GEM_BUG_ON(!siblings[0]->cops->create_virtual);
2442 	return siblings[0]->cops->create_virtual(siblings, count, flags);
2443 }
2444 
2445 static struct i915_request *engine_execlist_find_hung_request(struct intel_engine_cs *engine)
2446 {
2447 	struct i915_request *request, *active = NULL;
2448 
2449 	/*
2450 	 * This search does not work in GuC submission mode. However, the GuC
2451 	 * will report the hanging context directly to the driver itself. So
2452 	 * the driver should never get here when in GuC mode.
2453 	 */
2454 	GEM_BUG_ON(intel_uc_uses_guc_submission(&engine->gt->uc));
2455 
2456 	/*
2457 	 * We are called by the error capture, reset and to dump engine
2458 	 * state at random points in time. In particular, note that neither is
2459 	 * crucially ordered with an interrupt. After a hang, the GPU is dead
2460 	 * and we assume that no more writes can happen (we waited long enough
2461 	 * for all writes that were in transaction to be flushed) - adding an
2462 	 * extra delay for a recent interrupt is pointless. Hence, we do
2463 	 * not need an engine->irq_seqno_barrier() before the seqno reads.
2464 	 * At all other times, we must assume the GPU is still running, but
2465 	 * we only care about the snapshot of this moment.
2466 	 */
2467 	lockdep_assert_held(&engine->sched_engine->lock);
2468 
2469 	rcu_read_lock();
2470 	request = execlists_active(&engine->execlists);
2471 	if (request) {
2472 		struct intel_timeline *tl = request->context->timeline;
2473 
2474 		list_for_each_entry_from_reverse(request, &tl->requests, link) {
2475 			if (__i915_request_is_complete(request))
2476 				break;
2477 
2478 			active = request;
2479 		}
2480 	}
2481 	rcu_read_unlock();
2482 	if (active)
2483 		return active;
2484 
2485 	list_for_each_entry(request, &engine->sched_engine->requests,
2486 			    sched.link) {
2487 		if (i915_test_request_state(request) != I915_REQUEST_ACTIVE)
2488 			continue;
2489 
2490 		active = request;
2491 		break;
2492 	}
2493 
2494 	return active;
2495 }
2496 
2497 void intel_engine_get_hung_entity(struct intel_engine_cs *engine,
2498 				  struct intel_context **ce, struct i915_request **rq)
2499 {
2500 	unsigned long flags;
2501 
2502 	*ce = intel_engine_get_hung_context(engine);
2503 	if (*ce) {
2504 		intel_engine_clear_hung_context(engine);
2505 
2506 		*rq = intel_context_get_active_request(*ce);
2507 		return;
2508 	}
2509 
2510 	/*
2511 	 * Getting here with GuC enabled means it is a forced error capture
2512 	 * with no actual hang. So, no need to attempt the execlist search.
2513 	 */
2514 	if (intel_uc_uses_guc_submission(&engine->gt->uc))
2515 		return;
2516 
2517 	spin_lock_irqsave(&engine->sched_engine->lock, flags);
2518 	*rq = engine_execlist_find_hung_request(engine);
2519 	if (*rq)
2520 		*rq = i915_request_get_rcu(*rq);
2521 	spin_unlock_irqrestore(&engine->sched_engine->lock, flags);
2522 }
2523 
2524 void xehp_enable_ccs_engines(struct intel_engine_cs *engine)
2525 {
2526 	/*
2527 	 * If there are any non-fused-off CCS engines, we need to enable CCS
2528 	 * support in the RCU_MODE register.  This only needs to be done once,
2529 	 * so for simplicity we'll take care of this in the RCS engine's
2530 	 * resume handler; since the RCS and all CCS engines belong to the
2531 	 * same reset domain and are reset together, this will also take care
2532 	 * of re-applying the setting after i915-triggered resets.
2533 	 */
2534 	if (!CCS_MASK(engine->gt))
2535 		return;
2536 
2537 	intel_uncore_write(engine->uncore, GEN12_RCU_MODE,
2538 			   _MASKED_BIT_ENABLE(GEN12_RCU_MODE_CCS_ENABLE));
2539 }
2540 
2541 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
2542 #include "mock_engine.c"
2543 #include "selftest_engine.c"
2544 #include "selftest_engine_cs.c"
2545 #endif
2546