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