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