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