xref: /linux/drivers/gpu/drm/i915/gt/intel_engine_cs.c (revision 9a6b55ac)
1 /*
2  * Copyright © 2016 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  *
23  */
24 
25 #include <drm/drm_print.h>
26 
27 #include "gem/i915_gem_context.h"
28 
29 #include "i915_drv.h"
30 
31 #include "intel_context.h"
32 #include "intel_engine.h"
33 #include "intel_engine_pm.h"
34 #include "intel_engine_pool.h"
35 #include "intel_engine_user.h"
36 #include "intel_gt.h"
37 #include "intel_gt_requests.h"
38 #include "intel_lrc.h"
39 #include "intel_reset.h"
40 #include "intel_ring.h"
41 
42 /* Haswell does have the CXT_SIZE register however it does not appear to be
43  * valid. Now, docs explain in dwords what is in the context object. The full
44  * size is 70720 bytes, however, the power context and execlist context will
45  * never be saved (power context is stored elsewhere, and execlists don't work
46  * on HSW) - so the final size, including the extra state required for the
47  * Resource Streamer, is 66944 bytes, which rounds to 17 pages.
48  */
49 #define HSW_CXT_TOTAL_SIZE		(17 * PAGE_SIZE)
50 
51 #define DEFAULT_LR_CONTEXT_RENDER_SIZE	(22 * PAGE_SIZE)
52 #define GEN8_LR_CONTEXT_RENDER_SIZE	(20 * PAGE_SIZE)
53 #define GEN9_LR_CONTEXT_RENDER_SIZE	(22 * PAGE_SIZE)
54 #define GEN10_LR_CONTEXT_RENDER_SIZE	(18 * PAGE_SIZE)
55 #define GEN11_LR_CONTEXT_RENDER_SIZE	(14 * PAGE_SIZE)
56 
57 #define GEN8_LR_CONTEXT_OTHER_SIZE	( 2 * PAGE_SIZE)
58 
59 #define MAX_MMIO_BASES 3
60 struct engine_info {
61 	unsigned int hw_id;
62 	u8 class;
63 	u8 instance;
64 	/* mmio bases table *must* be sorted in reverse gen order */
65 	struct engine_mmio_base {
66 		u32 gen : 8;
67 		u32 base : 24;
68 	} mmio_bases[MAX_MMIO_BASES];
69 };
70 
71 static const struct engine_info intel_engines[] = {
72 	[RCS0] = {
73 		.hw_id = RCS0_HW,
74 		.class = RENDER_CLASS,
75 		.instance = 0,
76 		.mmio_bases = {
77 			{ .gen = 1, .base = RENDER_RING_BASE }
78 		},
79 	},
80 	[BCS0] = {
81 		.hw_id = BCS0_HW,
82 		.class = COPY_ENGINE_CLASS,
83 		.instance = 0,
84 		.mmio_bases = {
85 			{ .gen = 6, .base = BLT_RING_BASE }
86 		},
87 	},
88 	[VCS0] = {
89 		.hw_id = VCS0_HW,
90 		.class = VIDEO_DECODE_CLASS,
91 		.instance = 0,
92 		.mmio_bases = {
93 			{ .gen = 11, .base = GEN11_BSD_RING_BASE },
94 			{ .gen = 6, .base = GEN6_BSD_RING_BASE },
95 			{ .gen = 4, .base = BSD_RING_BASE }
96 		},
97 	},
98 	[VCS1] = {
99 		.hw_id = VCS1_HW,
100 		.class = VIDEO_DECODE_CLASS,
101 		.instance = 1,
102 		.mmio_bases = {
103 			{ .gen = 11, .base = GEN11_BSD2_RING_BASE },
104 			{ .gen = 8, .base = GEN8_BSD2_RING_BASE }
105 		},
106 	},
107 	[VCS2] = {
108 		.hw_id = VCS2_HW,
109 		.class = VIDEO_DECODE_CLASS,
110 		.instance = 2,
111 		.mmio_bases = {
112 			{ .gen = 11, .base = GEN11_BSD3_RING_BASE }
113 		},
114 	},
115 	[VCS3] = {
116 		.hw_id = VCS3_HW,
117 		.class = VIDEO_DECODE_CLASS,
118 		.instance = 3,
119 		.mmio_bases = {
120 			{ .gen = 11, .base = GEN11_BSD4_RING_BASE }
121 		},
122 	},
123 	[VECS0] = {
124 		.hw_id = VECS0_HW,
125 		.class = VIDEO_ENHANCEMENT_CLASS,
126 		.instance = 0,
127 		.mmio_bases = {
128 			{ .gen = 11, .base = GEN11_VEBOX_RING_BASE },
129 			{ .gen = 7, .base = VEBOX_RING_BASE }
130 		},
131 	},
132 	[VECS1] = {
133 		.hw_id = VECS1_HW,
134 		.class = VIDEO_ENHANCEMENT_CLASS,
135 		.instance = 1,
136 		.mmio_bases = {
137 			{ .gen = 11, .base = GEN11_VEBOX2_RING_BASE }
138 		},
139 	},
140 };
141 
142 /**
143  * intel_engine_context_size() - return the size of the context for an engine
144  * @dev_priv: i915 device private
145  * @class: engine class
146  *
147  * Each engine class may require a different amount of space for a context
148  * image.
149  *
150  * Return: size (in bytes) of an engine class specific context image
151  *
152  * Note: this size includes the HWSP, which is part of the context image
153  * in LRC mode, but does not include the "shared data page" used with
154  * GuC submission. The caller should account for this if using the GuC.
155  */
156 u32 intel_engine_context_size(struct drm_i915_private *dev_priv, u8 class)
157 {
158 	u32 cxt_size;
159 
160 	BUILD_BUG_ON(I915_GTT_PAGE_SIZE != PAGE_SIZE);
161 
162 	switch (class) {
163 	case RENDER_CLASS:
164 		switch (INTEL_GEN(dev_priv)) {
165 		default:
166 			MISSING_CASE(INTEL_GEN(dev_priv));
167 			return DEFAULT_LR_CONTEXT_RENDER_SIZE;
168 		case 12:
169 		case 11:
170 			return GEN11_LR_CONTEXT_RENDER_SIZE;
171 		case 10:
172 			return GEN10_LR_CONTEXT_RENDER_SIZE;
173 		case 9:
174 			return GEN9_LR_CONTEXT_RENDER_SIZE;
175 		case 8:
176 			return GEN8_LR_CONTEXT_RENDER_SIZE;
177 		case 7:
178 			if (IS_HASWELL(dev_priv))
179 				return HSW_CXT_TOTAL_SIZE;
180 
181 			cxt_size = I915_READ(GEN7_CXT_SIZE);
182 			return round_up(GEN7_CXT_TOTAL_SIZE(cxt_size) * 64,
183 					PAGE_SIZE);
184 		case 6:
185 			cxt_size = I915_READ(CXT_SIZE);
186 			return round_up(GEN6_CXT_TOTAL_SIZE(cxt_size) * 64,
187 					PAGE_SIZE);
188 		case 5:
189 		case 4:
190 			/*
191 			 * There is a discrepancy here between the size reported
192 			 * by the register and the size of the context layout
193 			 * in the docs. Both are described as authorative!
194 			 *
195 			 * The discrepancy is on the order of a few cachelines,
196 			 * but the total is under one page (4k), which is our
197 			 * minimum allocation anyway so it should all come
198 			 * out in the wash.
199 			 */
200 			cxt_size = I915_READ(CXT_SIZE) + 1;
201 			DRM_DEBUG_DRIVER("gen%d CXT_SIZE = %d bytes [0x%08x]\n",
202 					 INTEL_GEN(dev_priv),
203 					 cxt_size * 64,
204 					 cxt_size - 1);
205 			return round_up(cxt_size * 64, PAGE_SIZE);
206 		case 3:
207 		case 2:
208 		/* For the special day when i810 gets merged. */
209 		case 1:
210 			return 0;
211 		}
212 		break;
213 	default:
214 		MISSING_CASE(class);
215 		/* fall through */
216 	case VIDEO_DECODE_CLASS:
217 	case VIDEO_ENHANCEMENT_CLASS:
218 	case COPY_ENGINE_CLASS:
219 		if (INTEL_GEN(dev_priv) < 8)
220 			return 0;
221 		return GEN8_LR_CONTEXT_OTHER_SIZE;
222 	}
223 }
224 
225 static u32 __engine_mmio_base(struct drm_i915_private *i915,
226 			      const struct engine_mmio_base *bases)
227 {
228 	int i;
229 
230 	for (i = 0; i < MAX_MMIO_BASES; i++)
231 		if (INTEL_GEN(i915) >= bases[i].gen)
232 			break;
233 
234 	GEM_BUG_ON(i == MAX_MMIO_BASES);
235 	GEM_BUG_ON(!bases[i].base);
236 
237 	return bases[i].base;
238 }
239 
240 static void __sprint_engine_name(struct intel_engine_cs *engine)
241 {
242 	/*
243 	 * Before we know what the uABI name for this engine will be,
244 	 * we still would like to keep track of this engine in the debug logs.
245 	 * We throw in a ' here as a reminder that this isn't its final name.
246 	 */
247 	GEM_WARN_ON(snprintf(engine->name, sizeof(engine->name), "%s'%u",
248 			     intel_engine_class_repr(engine->class),
249 			     engine->instance) >= sizeof(engine->name));
250 }
251 
252 void intel_engine_set_hwsp_writemask(struct intel_engine_cs *engine, u32 mask)
253 {
254 	/*
255 	 * Though they added more rings on g4x/ilk, they did not add
256 	 * per-engine HWSTAM until gen6.
257 	 */
258 	if (INTEL_GEN(engine->i915) < 6 && engine->class != RENDER_CLASS)
259 		return;
260 
261 	if (INTEL_GEN(engine->i915) >= 3)
262 		ENGINE_WRITE(engine, RING_HWSTAM, mask);
263 	else
264 		ENGINE_WRITE16(engine, RING_HWSTAM, mask);
265 }
266 
267 static void intel_engine_sanitize_mmio(struct intel_engine_cs *engine)
268 {
269 	/* Mask off all writes into the unknown HWSP */
270 	intel_engine_set_hwsp_writemask(engine, ~0u);
271 }
272 
273 static int intel_engine_setup(struct intel_gt *gt, enum intel_engine_id id)
274 {
275 	const struct engine_info *info = &intel_engines[id];
276 	struct intel_engine_cs *engine;
277 
278 	BUILD_BUG_ON(MAX_ENGINE_CLASS >= BIT(GEN11_ENGINE_CLASS_WIDTH));
279 	BUILD_BUG_ON(MAX_ENGINE_INSTANCE >= BIT(GEN11_ENGINE_INSTANCE_WIDTH));
280 
281 	if (GEM_DEBUG_WARN_ON(id >= ARRAY_SIZE(gt->engine)))
282 		return -EINVAL;
283 
284 	if (GEM_DEBUG_WARN_ON(info->class > MAX_ENGINE_CLASS))
285 		return -EINVAL;
286 
287 	if (GEM_DEBUG_WARN_ON(info->instance > MAX_ENGINE_INSTANCE))
288 		return -EINVAL;
289 
290 	if (GEM_DEBUG_WARN_ON(gt->engine_class[info->class][info->instance]))
291 		return -EINVAL;
292 
293 	engine = kzalloc(sizeof(*engine), GFP_KERNEL);
294 	if (!engine)
295 		return -ENOMEM;
296 
297 	BUILD_BUG_ON(BITS_PER_TYPE(engine->mask) < I915_NUM_ENGINES);
298 
299 	engine->id = id;
300 	engine->legacy_idx = INVALID_ENGINE;
301 	engine->mask = BIT(id);
302 	engine->i915 = gt->i915;
303 	engine->gt = gt;
304 	engine->uncore = gt->uncore;
305 	engine->hw_id = engine->guc_id = info->hw_id;
306 	engine->mmio_base = __engine_mmio_base(gt->i915, info->mmio_bases);
307 
308 	engine->class = info->class;
309 	engine->instance = info->instance;
310 	__sprint_engine_name(engine);
311 
312 	engine->props.heartbeat_interval_ms =
313 		CONFIG_DRM_I915_HEARTBEAT_INTERVAL;
314 	engine->props.preempt_timeout_ms =
315 		CONFIG_DRM_I915_PREEMPT_TIMEOUT;
316 	engine->props.stop_timeout_ms =
317 		CONFIG_DRM_I915_STOP_TIMEOUT;
318 	engine->props.timeslice_duration_ms =
319 		CONFIG_DRM_I915_TIMESLICE_DURATION;
320 
321 	/*
322 	 * To be overridden by the backend on setup. However to facilitate
323 	 * cleanup on error during setup, we always provide the destroy vfunc.
324 	 */
325 	engine->destroy = (typeof(engine->destroy))kfree;
326 
327 	engine->context_size = intel_engine_context_size(gt->i915,
328 							 engine->class);
329 	if (WARN_ON(engine->context_size > BIT(20)))
330 		engine->context_size = 0;
331 	if (engine->context_size)
332 		DRIVER_CAPS(gt->i915)->has_logical_contexts = true;
333 
334 	/* Nothing to do here, execute in order of dependencies */
335 	engine->schedule = NULL;
336 
337 	seqlock_init(&engine->stats.lock);
338 
339 	ATOMIC_INIT_NOTIFIER_HEAD(&engine->context_status_notifier);
340 
341 	/* Scrub mmio state on takeover */
342 	intel_engine_sanitize_mmio(engine);
343 
344 	gt->engine_class[info->class][info->instance] = engine;
345 	gt->engine[id] = engine;
346 
347 	intel_engine_add_user(engine);
348 	gt->i915->engine[id] = engine;
349 
350 	return 0;
351 }
352 
353 static void __setup_engine_capabilities(struct intel_engine_cs *engine)
354 {
355 	struct drm_i915_private *i915 = engine->i915;
356 
357 	if (engine->class == VIDEO_DECODE_CLASS) {
358 		/*
359 		 * HEVC support is present on first engine instance
360 		 * before Gen11 and on all instances afterwards.
361 		 */
362 		if (INTEL_GEN(i915) >= 11 ||
363 		    (INTEL_GEN(i915) >= 9 && engine->instance == 0))
364 			engine->uabi_capabilities |=
365 				I915_VIDEO_CLASS_CAPABILITY_HEVC;
366 
367 		/*
368 		 * SFC block is present only on even logical engine
369 		 * instances.
370 		 */
371 		if ((INTEL_GEN(i915) >= 11 &&
372 		     RUNTIME_INFO(i915)->vdbox_sfc_access & engine->mask) ||
373 		    (INTEL_GEN(i915) >= 9 && engine->instance == 0))
374 			engine->uabi_capabilities |=
375 				I915_VIDEO_AND_ENHANCE_CLASS_CAPABILITY_SFC;
376 	} else if (engine->class == VIDEO_ENHANCEMENT_CLASS) {
377 		if (INTEL_GEN(i915) >= 9)
378 			engine->uabi_capabilities |=
379 				I915_VIDEO_AND_ENHANCE_CLASS_CAPABILITY_SFC;
380 	}
381 }
382 
383 static void intel_setup_engine_capabilities(struct intel_gt *gt)
384 {
385 	struct intel_engine_cs *engine;
386 	enum intel_engine_id id;
387 
388 	for_each_engine(engine, gt, id)
389 		__setup_engine_capabilities(engine);
390 }
391 
392 /**
393  * intel_engines_cleanup() - free the resources allocated for Command Streamers
394  * @gt: pointer to struct intel_gt
395  */
396 void intel_engines_cleanup(struct intel_gt *gt)
397 {
398 	struct intel_engine_cs *engine;
399 	enum intel_engine_id id;
400 
401 	for_each_engine(engine, gt, id) {
402 		engine->destroy(engine);
403 		gt->engine[id] = NULL;
404 		gt->i915->engine[id] = NULL;
405 	}
406 }
407 
408 /**
409  * intel_engines_init_mmio() - allocate and prepare the Engine Command Streamers
410  * @gt: pointer to struct intel_gt
411  *
412  * Return: non-zero if the initialization failed.
413  */
414 int intel_engines_init_mmio(struct intel_gt *gt)
415 {
416 	struct drm_i915_private *i915 = gt->i915;
417 	struct intel_device_info *device_info = mkwrite_device_info(i915);
418 	const unsigned int engine_mask = INTEL_INFO(i915)->engine_mask;
419 	unsigned int mask = 0;
420 	unsigned int i;
421 	int err;
422 
423 	WARN_ON(engine_mask == 0);
424 	WARN_ON(engine_mask &
425 		GENMASK(BITS_PER_TYPE(mask) - 1, I915_NUM_ENGINES));
426 
427 	if (i915_inject_probe_failure(i915))
428 		return -ENODEV;
429 
430 	for (i = 0; i < ARRAY_SIZE(intel_engines); i++) {
431 		if (!HAS_ENGINE(i915, i))
432 			continue;
433 
434 		err = intel_engine_setup(gt, i);
435 		if (err)
436 			goto cleanup;
437 
438 		mask |= BIT(i);
439 	}
440 
441 	/*
442 	 * Catch failures to update intel_engines table when the new engines
443 	 * are added to the driver by a warning and disabling the forgotten
444 	 * engines.
445 	 */
446 	if (WARN_ON(mask != engine_mask))
447 		device_info->engine_mask = mask;
448 
449 	RUNTIME_INFO(i915)->num_engines = hweight32(mask);
450 
451 	intel_gt_check_and_clear_faults(gt);
452 
453 	intel_setup_engine_capabilities(gt);
454 
455 	return 0;
456 
457 cleanup:
458 	intel_engines_cleanup(gt);
459 	return err;
460 }
461 
462 /**
463  * intel_engines_init() - init the Engine Command Streamers
464  * @gt: pointer to struct intel_gt
465  *
466  * Return: non-zero if the initialization failed.
467  */
468 int intel_engines_init(struct intel_gt *gt)
469 {
470 	int (*init)(struct intel_engine_cs *engine);
471 	struct intel_engine_cs *engine;
472 	enum intel_engine_id id;
473 	int err;
474 
475 	if (HAS_EXECLISTS(gt->i915))
476 		init = intel_execlists_submission_init;
477 	else
478 		init = intel_ring_submission_init;
479 
480 	for_each_engine(engine, gt, id) {
481 		err = init(engine);
482 		if (err)
483 			goto cleanup;
484 	}
485 
486 	return 0;
487 
488 cleanup:
489 	intel_engines_cleanup(gt);
490 	return err;
491 }
492 
493 void intel_engine_init_execlists(struct intel_engine_cs *engine)
494 {
495 	struct intel_engine_execlists * const execlists = &engine->execlists;
496 
497 	execlists->port_mask = 1;
498 	GEM_BUG_ON(!is_power_of_2(execlists_num_ports(execlists)));
499 	GEM_BUG_ON(execlists_num_ports(execlists) > EXECLIST_MAX_PORTS);
500 
501 	memset(execlists->pending, 0, sizeof(execlists->pending));
502 	execlists->active =
503 		memset(execlists->inflight, 0, sizeof(execlists->inflight));
504 
505 	execlists->queue_priority_hint = INT_MIN;
506 	execlists->queue = RB_ROOT_CACHED;
507 }
508 
509 static void cleanup_status_page(struct intel_engine_cs *engine)
510 {
511 	struct i915_vma *vma;
512 
513 	/* Prevent writes into HWSP after returning the page to the system */
514 	intel_engine_set_hwsp_writemask(engine, ~0u);
515 
516 	vma = fetch_and_zero(&engine->status_page.vma);
517 	if (!vma)
518 		return;
519 
520 	if (!HWS_NEEDS_PHYSICAL(engine->i915))
521 		i915_vma_unpin(vma);
522 
523 	i915_gem_object_unpin_map(vma->obj);
524 	i915_gem_object_put(vma->obj);
525 }
526 
527 static int pin_ggtt_status_page(struct intel_engine_cs *engine,
528 				struct i915_vma *vma)
529 {
530 	unsigned int flags;
531 
532 	flags = PIN_GLOBAL;
533 	if (!HAS_LLC(engine->i915) && i915_ggtt_has_aperture(engine->gt->ggtt))
534 		/*
535 		 * On g33, we cannot place HWS above 256MiB, so
536 		 * restrict its pinning to the low mappable arena.
537 		 * Though this restriction is not documented for
538 		 * gen4, gen5, or byt, they also behave similarly
539 		 * and hang if the HWS is placed at the top of the
540 		 * GTT. To generalise, it appears that all !llc
541 		 * platforms have issues with us placing the HWS
542 		 * above the mappable region (even though we never
543 		 * actually map it).
544 		 */
545 		flags |= PIN_MAPPABLE;
546 	else
547 		flags |= PIN_HIGH;
548 
549 	return i915_vma_pin(vma, 0, 0, flags);
550 }
551 
552 static int init_status_page(struct intel_engine_cs *engine)
553 {
554 	struct drm_i915_gem_object *obj;
555 	struct i915_vma *vma;
556 	void *vaddr;
557 	int ret;
558 
559 	/*
560 	 * Though the HWS register does support 36bit addresses, historically
561 	 * we have had hangs and corruption reported due to wild writes if
562 	 * the HWS is placed above 4G. We only allow objects to be allocated
563 	 * in GFP_DMA32 for i965, and no earlier physical address users had
564 	 * access to more than 4G.
565 	 */
566 	obj = i915_gem_object_create_internal(engine->i915, PAGE_SIZE);
567 	if (IS_ERR(obj)) {
568 		DRM_ERROR("Failed to allocate status page\n");
569 		return PTR_ERR(obj);
570 	}
571 
572 	i915_gem_object_set_cache_coherency(obj, I915_CACHE_LLC);
573 
574 	vma = i915_vma_instance(obj, &engine->gt->ggtt->vm, NULL);
575 	if (IS_ERR(vma)) {
576 		ret = PTR_ERR(vma);
577 		goto err;
578 	}
579 
580 	vaddr = i915_gem_object_pin_map(obj, I915_MAP_WB);
581 	if (IS_ERR(vaddr)) {
582 		ret = PTR_ERR(vaddr);
583 		goto err;
584 	}
585 
586 	engine->status_page.addr = memset(vaddr, 0, PAGE_SIZE);
587 	engine->status_page.vma = vma;
588 
589 	if (!HWS_NEEDS_PHYSICAL(engine->i915)) {
590 		ret = pin_ggtt_status_page(engine, vma);
591 		if (ret)
592 			goto err_unpin;
593 	}
594 
595 	return 0;
596 
597 err_unpin:
598 	i915_gem_object_unpin_map(obj);
599 err:
600 	i915_gem_object_put(obj);
601 	return ret;
602 }
603 
604 static int intel_engine_setup_common(struct intel_engine_cs *engine)
605 {
606 	int err;
607 
608 	init_llist_head(&engine->barrier_tasks);
609 
610 	err = init_status_page(engine);
611 	if (err)
612 		return err;
613 
614 	intel_engine_init_active(engine, ENGINE_PHYSICAL);
615 	intel_engine_init_breadcrumbs(engine);
616 	intel_engine_init_execlists(engine);
617 	intel_engine_init_cmd_parser(engine);
618 	intel_engine_init__pm(engine);
619 	intel_engine_init_retire(engine);
620 
621 	intel_engine_pool_init(&engine->pool);
622 
623 	/* Use the whole device by default */
624 	engine->sseu =
625 		intel_sseu_from_device_info(&RUNTIME_INFO(engine->i915)->sseu);
626 
627 	intel_engine_init_workarounds(engine);
628 	intel_engine_init_whitelist(engine);
629 	intel_engine_init_ctx_wa(engine);
630 
631 	return 0;
632 }
633 
634 /**
635  * intel_engines_setup- setup engine state not requiring hw access
636  * @gt: pointer to struct intel_gt
637  *
638  * Initializes engine structure members shared between legacy and execlists
639  * submission modes which do not require hardware access.
640  *
641  * Typically done early in the submission mode specific engine setup stage.
642  */
643 int intel_engines_setup(struct intel_gt *gt)
644 {
645 	int (*setup)(struct intel_engine_cs *engine);
646 	struct intel_engine_cs *engine;
647 	enum intel_engine_id id;
648 	int err;
649 
650 	if (HAS_EXECLISTS(gt->i915))
651 		setup = intel_execlists_submission_setup;
652 	else
653 		setup = intel_ring_submission_setup;
654 
655 	for_each_engine(engine, gt, id) {
656 		err = intel_engine_setup_common(engine);
657 		if (err)
658 			goto cleanup;
659 
660 		err = setup(engine);
661 		if (err)
662 			goto cleanup;
663 
664 		/* We expect the backend to take control over its state */
665 		GEM_BUG_ON(engine->destroy == (typeof(engine->destroy))kfree);
666 
667 		GEM_BUG_ON(!engine->cops);
668 	}
669 
670 	return 0;
671 
672 cleanup:
673 	intel_engines_cleanup(gt);
674 	return err;
675 }
676 
677 struct measure_breadcrumb {
678 	struct i915_request rq;
679 	struct intel_timeline timeline;
680 	struct intel_ring ring;
681 	u32 cs[1024];
682 };
683 
684 static int measure_breadcrumb_dw(struct intel_engine_cs *engine)
685 {
686 	struct measure_breadcrumb *frame;
687 	int dw = -ENOMEM;
688 
689 	GEM_BUG_ON(!engine->gt->scratch);
690 
691 	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
692 	if (!frame)
693 		return -ENOMEM;
694 
695 	if (intel_timeline_init(&frame->timeline,
696 				engine->gt,
697 				engine->status_page.vma))
698 		goto out_frame;
699 
700 	mutex_lock(&frame->timeline.mutex);
701 
702 	frame->ring.vaddr = frame->cs;
703 	frame->ring.size = sizeof(frame->cs);
704 	frame->ring.effective_size = frame->ring.size;
705 	intel_ring_update_space(&frame->ring);
706 
707 	frame->rq.i915 = engine->i915;
708 	frame->rq.engine = engine;
709 	frame->rq.ring = &frame->ring;
710 	rcu_assign_pointer(frame->rq.timeline, &frame->timeline);
711 
712 	dw = intel_timeline_pin(&frame->timeline);
713 	if (dw < 0)
714 		goto out_timeline;
715 
716 	spin_lock_irq(&engine->active.lock);
717 	dw = engine->emit_fini_breadcrumb(&frame->rq, frame->cs) - frame->cs;
718 	spin_unlock_irq(&engine->active.lock);
719 
720 	GEM_BUG_ON(dw & 1); /* RING_TAIL must be qword aligned */
721 
722 	intel_timeline_unpin(&frame->timeline);
723 
724 out_timeline:
725 	mutex_unlock(&frame->timeline.mutex);
726 	intel_timeline_fini(&frame->timeline);
727 out_frame:
728 	kfree(frame);
729 	return dw;
730 }
731 
732 void
733 intel_engine_init_active(struct intel_engine_cs *engine, unsigned int subclass)
734 {
735 	INIT_LIST_HEAD(&engine->active.requests);
736 
737 	spin_lock_init(&engine->active.lock);
738 	lockdep_set_subclass(&engine->active.lock, subclass);
739 
740 	/*
741 	 * Due to an interesting quirk in lockdep's internal debug tracking,
742 	 * after setting a subclass we must ensure the lock is used. Otherwise,
743 	 * nr_unused_locks is incremented once too often.
744 	 */
745 #ifdef CONFIG_DEBUG_LOCK_ALLOC
746 	local_irq_disable();
747 	lock_map_acquire(&engine->active.lock.dep_map);
748 	lock_map_release(&engine->active.lock.dep_map);
749 	local_irq_enable();
750 #endif
751 }
752 
753 static struct intel_context *
754 create_kernel_context(struct intel_engine_cs *engine)
755 {
756 	static struct lock_class_key kernel;
757 	struct intel_context *ce;
758 	int err;
759 
760 	ce = intel_context_create(engine->i915->kernel_context, engine);
761 	if (IS_ERR(ce))
762 		return ce;
763 
764 	ce->ring = __intel_context_ring_size(SZ_4K);
765 
766 	err = intel_context_pin(ce);
767 	if (err) {
768 		intel_context_put(ce);
769 		return ERR_PTR(err);
770 	}
771 
772 	/*
773 	 * Give our perma-pinned kernel timelines a separate lockdep class,
774 	 * so that we can use them from within the normal user timelines
775 	 * should we need to inject GPU operations during their request
776 	 * construction.
777 	 */
778 	lockdep_set_class(&ce->timeline->mutex, &kernel);
779 
780 	return ce;
781 }
782 
783 /**
784  * intel_engines_init_common - initialize cengine state which might require hw access
785  * @engine: Engine to initialize.
786  *
787  * Initializes @engine@ structure members shared between legacy and execlists
788  * submission modes which do require hardware access.
789  *
790  * Typcally done at later stages of submission mode specific engine setup.
791  *
792  * Returns zero on success or an error code on failure.
793  */
794 int intel_engine_init_common(struct intel_engine_cs *engine)
795 {
796 	struct intel_context *ce;
797 	int ret;
798 
799 	engine->set_default_submission(engine);
800 
801 	/*
802 	 * We may need to do things with the shrinker which
803 	 * require us to immediately switch back to the default
804 	 * context. This can cause a problem as pinning the
805 	 * default context also requires GTT space which may not
806 	 * be available. To avoid this we always pin the default
807 	 * context.
808 	 */
809 	ce = create_kernel_context(engine);
810 	if (IS_ERR(ce))
811 		return PTR_ERR(ce);
812 
813 	engine->kernel_context = ce;
814 
815 	ret = measure_breadcrumb_dw(engine);
816 	if (ret < 0)
817 		goto err_unpin;
818 
819 	engine->emit_fini_breadcrumb_dw = ret;
820 
821 	return 0;
822 
823 err_unpin:
824 	intel_context_unpin(ce);
825 	intel_context_put(ce);
826 	return ret;
827 }
828 
829 /**
830  * intel_engines_cleanup_common - cleans up the engine state created by
831  *                                the common initiailizers.
832  * @engine: Engine to cleanup.
833  *
834  * This cleans up everything created by the common helpers.
835  */
836 void intel_engine_cleanup_common(struct intel_engine_cs *engine)
837 {
838 	GEM_BUG_ON(!list_empty(&engine->active.requests));
839 
840 	cleanup_status_page(engine);
841 
842 	intel_engine_fini_retire(engine);
843 	intel_engine_pool_fini(&engine->pool);
844 	intel_engine_fini_breadcrumbs(engine);
845 	intel_engine_cleanup_cmd_parser(engine);
846 
847 	if (engine->default_state)
848 		i915_gem_object_put(engine->default_state);
849 
850 	if (engine->kernel_context) {
851 		intel_context_unpin(engine->kernel_context);
852 		intel_context_put(engine->kernel_context);
853 	}
854 	GEM_BUG_ON(!llist_empty(&engine->barrier_tasks));
855 
856 	intel_wa_list_free(&engine->ctx_wa_list);
857 	intel_wa_list_free(&engine->wa_list);
858 	intel_wa_list_free(&engine->whitelist);
859 }
860 
861 u64 intel_engine_get_active_head(const struct intel_engine_cs *engine)
862 {
863 	struct drm_i915_private *i915 = engine->i915;
864 
865 	u64 acthd;
866 
867 	if (INTEL_GEN(i915) >= 8)
868 		acthd = ENGINE_READ64(engine, RING_ACTHD, RING_ACTHD_UDW);
869 	else if (INTEL_GEN(i915) >= 4)
870 		acthd = ENGINE_READ(engine, RING_ACTHD);
871 	else
872 		acthd = ENGINE_READ(engine, ACTHD);
873 
874 	return acthd;
875 }
876 
877 u64 intel_engine_get_last_batch_head(const struct intel_engine_cs *engine)
878 {
879 	u64 bbaddr;
880 
881 	if (INTEL_GEN(engine->i915) >= 8)
882 		bbaddr = ENGINE_READ64(engine, RING_BBADDR, RING_BBADDR_UDW);
883 	else
884 		bbaddr = ENGINE_READ(engine, RING_BBADDR);
885 
886 	return bbaddr;
887 }
888 
889 static unsigned long stop_timeout(const struct intel_engine_cs *engine)
890 {
891 	if (in_atomic() || irqs_disabled()) /* inside atomic preempt-reset? */
892 		return 0;
893 
894 	/*
895 	 * If we are doing a normal GPU reset, we can take our time and allow
896 	 * the engine to quiesce. We've stopped submission to the engine, and
897 	 * if we wait long enough an innocent context should complete and
898 	 * leave the engine idle. So they should not be caught unaware by
899 	 * the forthcoming GPU reset (which usually follows the stop_cs)!
900 	 */
901 	return READ_ONCE(engine->props.stop_timeout_ms);
902 }
903 
904 int intel_engine_stop_cs(struct intel_engine_cs *engine)
905 {
906 	struct intel_uncore *uncore = engine->uncore;
907 	const u32 base = engine->mmio_base;
908 	const i915_reg_t mode = RING_MI_MODE(base);
909 	int err;
910 
911 	if (INTEL_GEN(engine->i915) < 3)
912 		return -ENODEV;
913 
914 	GEM_TRACE("%s\n", engine->name);
915 
916 	intel_uncore_write_fw(uncore, mode, _MASKED_BIT_ENABLE(STOP_RING));
917 
918 	err = 0;
919 	if (__intel_wait_for_register_fw(uncore,
920 					 mode, MODE_IDLE, MODE_IDLE,
921 					 1000, stop_timeout(engine),
922 					 NULL)) {
923 		GEM_TRACE("%s: timed out on STOP_RING -> IDLE\n", engine->name);
924 		err = -ETIMEDOUT;
925 	}
926 
927 	/* A final mmio read to let GPU writes be hopefully flushed to memory */
928 	intel_uncore_posting_read_fw(uncore, mode);
929 
930 	return err;
931 }
932 
933 void intel_engine_cancel_stop_cs(struct intel_engine_cs *engine)
934 {
935 	GEM_TRACE("%s\n", engine->name);
936 
937 	ENGINE_WRITE_FW(engine, RING_MI_MODE, _MASKED_BIT_DISABLE(STOP_RING));
938 }
939 
940 const char *i915_cache_level_str(struct drm_i915_private *i915, int type)
941 {
942 	switch (type) {
943 	case I915_CACHE_NONE: return " uncached";
944 	case I915_CACHE_LLC: return HAS_LLC(i915) ? " LLC" : " snooped";
945 	case I915_CACHE_L3_LLC: return " L3+LLC";
946 	case I915_CACHE_WT: return " WT";
947 	default: return "";
948 	}
949 }
950 
951 static u32
952 read_subslice_reg(struct intel_engine_cs *engine, int slice, int subslice,
953 		  i915_reg_t reg)
954 {
955 	struct drm_i915_private *i915 = engine->i915;
956 	struct intel_uncore *uncore = engine->uncore;
957 	u32 mcr_mask, mcr_ss, mcr, old_mcr, val;
958 	enum forcewake_domains fw_domains;
959 
960 	if (INTEL_GEN(i915) >= 11) {
961 		mcr_mask = GEN11_MCR_SLICE_MASK | GEN11_MCR_SUBSLICE_MASK;
962 		mcr_ss = GEN11_MCR_SLICE(slice) | GEN11_MCR_SUBSLICE(subslice);
963 	} else {
964 		mcr_mask = GEN8_MCR_SLICE_MASK | GEN8_MCR_SUBSLICE_MASK;
965 		mcr_ss = GEN8_MCR_SLICE(slice) | GEN8_MCR_SUBSLICE(subslice);
966 	}
967 
968 	fw_domains = intel_uncore_forcewake_for_reg(uncore, reg,
969 						    FW_REG_READ);
970 	fw_domains |= intel_uncore_forcewake_for_reg(uncore,
971 						     GEN8_MCR_SELECTOR,
972 						     FW_REG_READ | FW_REG_WRITE);
973 
974 	spin_lock_irq(&uncore->lock);
975 	intel_uncore_forcewake_get__locked(uncore, fw_domains);
976 
977 	old_mcr = mcr = intel_uncore_read_fw(uncore, GEN8_MCR_SELECTOR);
978 
979 	mcr &= ~mcr_mask;
980 	mcr |= mcr_ss;
981 	intel_uncore_write_fw(uncore, GEN8_MCR_SELECTOR, mcr);
982 
983 	val = intel_uncore_read_fw(uncore, reg);
984 
985 	mcr &= ~mcr_mask;
986 	mcr |= old_mcr & mcr_mask;
987 
988 	intel_uncore_write_fw(uncore, GEN8_MCR_SELECTOR, mcr);
989 
990 	intel_uncore_forcewake_put__locked(uncore, fw_domains);
991 	spin_unlock_irq(&uncore->lock);
992 
993 	return val;
994 }
995 
996 /* NB: please notice the memset */
997 void intel_engine_get_instdone(struct intel_engine_cs *engine,
998 			       struct intel_instdone *instdone)
999 {
1000 	struct drm_i915_private *i915 = engine->i915;
1001 	const struct sseu_dev_info *sseu = &RUNTIME_INFO(i915)->sseu;
1002 	struct intel_uncore *uncore = engine->uncore;
1003 	u32 mmio_base = engine->mmio_base;
1004 	int slice;
1005 	int subslice;
1006 
1007 	memset(instdone, 0, sizeof(*instdone));
1008 
1009 	switch (INTEL_GEN(i915)) {
1010 	default:
1011 		instdone->instdone =
1012 			intel_uncore_read(uncore, RING_INSTDONE(mmio_base));
1013 
1014 		if (engine->id != RCS0)
1015 			break;
1016 
1017 		instdone->slice_common =
1018 			intel_uncore_read(uncore, GEN7_SC_INSTDONE);
1019 		for_each_instdone_slice_subslice(i915, sseu, slice, subslice) {
1020 			instdone->sampler[slice][subslice] =
1021 				read_subslice_reg(engine, slice, subslice,
1022 						  GEN7_SAMPLER_INSTDONE);
1023 			instdone->row[slice][subslice] =
1024 				read_subslice_reg(engine, slice, subslice,
1025 						  GEN7_ROW_INSTDONE);
1026 		}
1027 		break;
1028 	case 7:
1029 		instdone->instdone =
1030 			intel_uncore_read(uncore, RING_INSTDONE(mmio_base));
1031 
1032 		if (engine->id != RCS0)
1033 			break;
1034 
1035 		instdone->slice_common =
1036 			intel_uncore_read(uncore, GEN7_SC_INSTDONE);
1037 		instdone->sampler[0][0] =
1038 			intel_uncore_read(uncore, GEN7_SAMPLER_INSTDONE);
1039 		instdone->row[0][0] =
1040 			intel_uncore_read(uncore, GEN7_ROW_INSTDONE);
1041 
1042 		break;
1043 	case 6:
1044 	case 5:
1045 	case 4:
1046 		instdone->instdone =
1047 			intel_uncore_read(uncore, RING_INSTDONE(mmio_base));
1048 		if (engine->id == RCS0)
1049 			/* HACK: Using the wrong struct member */
1050 			instdone->slice_common =
1051 				intel_uncore_read(uncore, GEN4_INSTDONE1);
1052 		break;
1053 	case 3:
1054 	case 2:
1055 		instdone->instdone = intel_uncore_read(uncore, GEN2_INSTDONE);
1056 		break;
1057 	}
1058 }
1059 
1060 static bool ring_is_idle(struct intel_engine_cs *engine)
1061 {
1062 	bool idle = true;
1063 
1064 	if (I915_SELFTEST_ONLY(!engine->mmio_base))
1065 		return true;
1066 
1067 	if (!intel_engine_pm_get_if_awake(engine))
1068 		return true;
1069 
1070 	/* First check that no commands are left in the ring */
1071 	if ((ENGINE_READ(engine, RING_HEAD) & HEAD_ADDR) !=
1072 	    (ENGINE_READ(engine, RING_TAIL) & TAIL_ADDR))
1073 		idle = false;
1074 
1075 	/* No bit for gen2, so assume the CS parser is idle */
1076 	if (INTEL_GEN(engine->i915) > 2 &&
1077 	    !(ENGINE_READ(engine, RING_MI_MODE) & MODE_IDLE))
1078 		idle = false;
1079 
1080 	intel_engine_pm_put(engine);
1081 
1082 	return idle;
1083 }
1084 
1085 void intel_engine_flush_submission(struct intel_engine_cs *engine)
1086 {
1087 	struct tasklet_struct *t = &engine->execlists.tasklet;
1088 
1089 	if (__tasklet_is_scheduled(t)) {
1090 		local_bh_disable();
1091 		if (tasklet_trylock(t)) {
1092 			/* Must wait for any GPU reset in progress. */
1093 			if (__tasklet_is_enabled(t))
1094 				t->func(t->data);
1095 			tasklet_unlock(t);
1096 		}
1097 		local_bh_enable();
1098 	}
1099 
1100 	/* Otherwise flush the tasklet if it was running on another cpu */
1101 	tasklet_unlock_wait(t);
1102 }
1103 
1104 /**
1105  * intel_engine_is_idle() - Report if the engine has finished process all work
1106  * @engine: the intel_engine_cs
1107  *
1108  * Return true if there are no requests pending, nothing left to be submitted
1109  * to hardware, and that the engine is idle.
1110  */
1111 bool intel_engine_is_idle(struct intel_engine_cs *engine)
1112 {
1113 	/* More white lies, if wedged, hw state is inconsistent */
1114 	if (intel_gt_is_wedged(engine->gt))
1115 		return true;
1116 
1117 	if (!intel_engine_pm_is_awake(engine))
1118 		return true;
1119 
1120 	/* Waiting to drain ELSP? */
1121 	if (execlists_active(&engine->execlists)) {
1122 		synchronize_hardirq(engine->i915->drm.pdev->irq);
1123 
1124 		intel_engine_flush_submission(engine);
1125 
1126 		if (execlists_active(&engine->execlists))
1127 			return false;
1128 	}
1129 
1130 	/* ELSP is empty, but there are ready requests? E.g. after reset */
1131 	if (!RB_EMPTY_ROOT(&engine->execlists.queue.rb_root))
1132 		return false;
1133 
1134 	/* Ring stopped? */
1135 	return ring_is_idle(engine);
1136 }
1137 
1138 bool intel_engines_are_idle(struct intel_gt *gt)
1139 {
1140 	struct intel_engine_cs *engine;
1141 	enum intel_engine_id id;
1142 
1143 	/*
1144 	 * If the driver is wedged, HW state may be very inconsistent and
1145 	 * report that it is still busy, even though we have stopped using it.
1146 	 */
1147 	if (intel_gt_is_wedged(gt))
1148 		return true;
1149 
1150 	/* Already parked (and passed an idleness test); must still be idle */
1151 	if (!READ_ONCE(gt->awake))
1152 		return true;
1153 
1154 	for_each_engine(engine, gt, id) {
1155 		if (!intel_engine_is_idle(engine))
1156 			return false;
1157 	}
1158 
1159 	return true;
1160 }
1161 
1162 void intel_engines_reset_default_submission(struct intel_gt *gt)
1163 {
1164 	struct intel_engine_cs *engine;
1165 	enum intel_engine_id id;
1166 
1167 	for_each_engine(engine, gt, id)
1168 		engine->set_default_submission(engine);
1169 }
1170 
1171 bool intel_engine_can_store_dword(struct intel_engine_cs *engine)
1172 {
1173 	switch (INTEL_GEN(engine->i915)) {
1174 	case 2:
1175 		return false; /* uses physical not virtual addresses */
1176 	case 3:
1177 		/* maybe only uses physical not virtual addresses */
1178 		return !(IS_I915G(engine->i915) || IS_I915GM(engine->i915));
1179 	case 4:
1180 		return !IS_I965G(engine->i915); /* who knows! */
1181 	case 6:
1182 		return engine->class != VIDEO_DECODE_CLASS; /* b0rked */
1183 	default:
1184 		return true;
1185 	}
1186 }
1187 
1188 static int print_sched_attr(struct drm_i915_private *i915,
1189 			    const struct i915_sched_attr *attr,
1190 			    char *buf, int x, int len)
1191 {
1192 	if (attr->priority == I915_PRIORITY_INVALID)
1193 		return x;
1194 
1195 	x += snprintf(buf + x, len - x,
1196 		      " prio=%d", attr->priority);
1197 
1198 	return x;
1199 }
1200 
1201 static void print_request(struct drm_printer *m,
1202 			  struct i915_request *rq,
1203 			  const char *prefix)
1204 {
1205 	const char *name = rq->fence.ops->get_timeline_name(&rq->fence);
1206 	char buf[80] = "";
1207 	int x = 0;
1208 
1209 	x = print_sched_attr(rq->i915, &rq->sched.attr, buf, x, sizeof(buf));
1210 
1211 	drm_printf(m, "%s %llx:%llx%s%s %s @ %dms: %s\n",
1212 		   prefix,
1213 		   rq->fence.context, rq->fence.seqno,
1214 		   i915_request_completed(rq) ? "!" :
1215 		   i915_request_started(rq) ? "*" :
1216 		   "",
1217 		   test_bit(DMA_FENCE_FLAG_SIGNALED_BIT,
1218 			    &rq->fence.flags) ? "+" :
1219 		   test_bit(DMA_FENCE_FLAG_ENABLE_SIGNAL_BIT,
1220 			    &rq->fence.flags) ? "-" :
1221 		   "",
1222 		   buf,
1223 		   jiffies_to_msecs(jiffies - rq->emitted_jiffies),
1224 		   name);
1225 }
1226 
1227 static void hexdump(struct drm_printer *m, const void *buf, size_t len)
1228 {
1229 	const size_t rowsize = 8 * sizeof(u32);
1230 	const void *prev = NULL;
1231 	bool skip = false;
1232 	size_t pos;
1233 
1234 	for (pos = 0; pos < len; pos += rowsize) {
1235 		char line[128];
1236 
1237 		if (prev && !memcmp(prev, buf + pos, rowsize)) {
1238 			if (!skip) {
1239 				drm_printf(m, "*\n");
1240 				skip = true;
1241 			}
1242 			continue;
1243 		}
1244 
1245 		WARN_ON_ONCE(hex_dump_to_buffer(buf + pos, len - pos,
1246 						rowsize, sizeof(u32),
1247 						line, sizeof(line),
1248 						false) >= sizeof(line));
1249 		drm_printf(m, "[%04zx] %s\n", pos, line);
1250 
1251 		prev = buf + pos;
1252 		skip = false;
1253 	}
1254 }
1255 
1256 static struct intel_timeline *get_timeline(struct i915_request *rq)
1257 {
1258 	struct intel_timeline *tl;
1259 
1260 	/*
1261 	 * Even though we are holding the engine->active.lock here, there
1262 	 * is no control over the submission queue per-se and we are
1263 	 * inspecting the active state at a random point in time, with an
1264 	 * unknown queue. Play safe and make sure the timeline remains valid.
1265 	 * (Only being used for pretty printing, one extra kref shouldn't
1266 	 * cause a camel stampede!)
1267 	 */
1268 	rcu_read_lock();
1269 	tl = rcu_dereference(rq->timeline);
1270 	if (!kref_get_unless_zero(&tl->kref))
1271 		tl = NULL;
1272 	rcu_read_unlock();
1273 
1274 	return tl;
1275 }
1276 
1277 static const char *repr_timer(const struct timer_list *t)
1278 {
1279 	if (!READ_ONCE(t->expires))
1280 		return "inactive";
1281 
1282 	if (timer_pending(t))
1283 		return "active";
1284 
1285 	return "expired";
1286 }
1287 
1288 static void intel_engine_print_registers(struct intel_engine_cs *engine,
1289 					 struct drm_printer *m)
1290 {
1291 	struct drm_i915_private *dev_priv = engine->i915;
1292 	struct intel_engine_execlists * const execlists = &engine->execlists;
1293 	u64 addr;
1294 
1295 	if (engine->id == RENDER_CLASS && IS_GEN_RANGE(dev_priv, 4, 7))
1296 		drm_printf(m, "\tCCID: 0x%08x\n", ENGINE_READ(engine, CCID));
1297 	drm_printf(m, "\tRING_START: 0x%08x\n",
1298 		   ENGINE_READ(engine, RING_START));
1299 	drm_printf(m, "\tRING_HEAD:  0x%08x\n",
1300 		   ENGINE_READ(engine, RING_HEAD) & HEAD_ADDR);
1301 	drm_printf(m, "\tRING_TAIL:  0x%08x\n",
1302 		   ENGINE_READ(engine, RING_TAIL) & TAIL_ADDR);
1303 	drm_printf(m, "\tRING_CTL:   0x%08x%s\n",
1304 		   ENGINE_READ(engine, RING_CTL),
1305 		   ENGINE_READ(engine, RING_CTL) & (RING_WAIT | RING_WAIT_SEMAPHORE) ? " [waiting]" : "");
1306 	if (INTEL_GEN(engine->i915) > 2) {
1307 		drm_printf(m, "\tRING_MODE:  0x%08x%s\n",
1308 			   ENGINE_READ(engine, RING_MI_MODE),
1309 			   ENGINE_READ(engine, RING_MI_MODE) & (MODE_IDLE) ? " [idle]" : "");
1310 	}
1311 
1312 	if (INTEL_GEN(dev_priv) >= 6) {
1313 		drm_printf(m, "\tRING_IMR: %08x\n",
1314 			   ENGINE_READ(engine, RING_IMR));
1315 	}
1316 
1317 	addr = intel_engine_get_active_head(engine);
1318 	drm_printf(m, "\tACTHD:  0x%08x_%08x\n",
1319 		   upper_32_bits(addr), lower_32_bits(addr));
1320 	addr = intel_engine_get_last_batch_head(engine);
1321 	drm_printf(m, "\tBBADDR: 0x%08x_%08x\n",
1322 		   upper_32_bits(addr), lower_32_bits(addr));
1323 	if (INTEL_GEN(dev_priv) >= 8)
1324 		addr = ENGINE_READ64(engine, RING_DMA_FADD, RING_DMA_FADD_UDW);
1325 	else if (INTEL_GEN(dev_priv) >= 4)
1326 		addr = ENGINE_READ(engine, RING_DMA_FADD);
1327 	else
1328 		addr = ENGINE_READ(engine, DMA_FADD_I8XX);
1329 	drm_printf(m, "\tDMA_FADDR: 0x%08x_%08x\n",
1330 		   upper_32_bits(addr), lower_32_bits(addr));
1331 	if (INTEL_GEN(dev_priv) >= 4) {
1332 		drm_printf(m, "\tIPEIR: 0x%08x\n",
1333 			   ENGINE_READ(engine, RING_IPEIR));
1334 		drm_printf(m, "\tIPEHR: 0x%08x\n",
1335 			   ENGINE_READ(engine, RING_IPEHR));
1336 	} else {
1337 		drm_printf(m, "\tIPEIR: 0x%08x\n", ENGINE_READ(engine, IPEIR));
1338 		drm_printf(m, "\tIPEHR: 0x%08x\n", ENGINE_READ(engine, IPEHR));
1339 	}
1340 
1341 	if (HAS_EXECLISTS(dev_priv)) {
1342 		struct i915_request * const *port, *rq;
1343 		const u32 *hws =
1344 			&engine->status_page.addr[I915_HWS_CSB_BUF0_INDEX];
1345 		const u8 num_entries = execlists->csb_size;
1346 		unsigned int idx;
1347 		u8 read, write;
1348 
1349 		drm_printf(m, "\tExeclist tasklet queued? %s (%s), preempt? %s, timeslice? %s\n",
1350 			   yesno(test_bit(TASKLET_STATE_SCHED,
1351 					  &engine->execlists.tasklet.state)),
1352 			   enableddisabled(!atomic_read(&engine->execlists.tasklet.count)),
1353 			   repr_timer(&engine->execlists.preempt),
1354 			   repr_timer(&engine->execlists.timer));
1355 
1356 		read = execlists->csb_head;
1357 		write = READ_ONCE(*execlists->csb_write);
1358 
1359 		drm_printf(m, "\tExeclist status: 0x%08x %08x; CSB read:%d, write:%d, entries:%d\n",
1360 			   ENGINE_READ(engine, RING_EXECLIST_STATUS_LO),
1361 			   ENGINE_READ(engine, RING_EXECLIST_STATUS_HI),
1362 			   read, write, num_entries);
1363 
1364 		if (read >= num_entries)
1365 			read = 0;
1366 		if (write >= num_entries)
1367 			write = 0;
1368 		if (read > write)
1369 			write += num_entries;
1370 		while (read < write) {
1371 			idx = ++read % num_entries;
1372 			drm_printf(m, "\tExeclist CSB[%d]: 0x%08x, context: %d\n",
1373 				   idx, hws[idx * 2], hws[idx * 2 + 1]);
1374 		}
1375 
1376 		execlists_active_lock_bh(execlists);
1377 		rcu_read_lock();
1378 		for (port = execlists->active; (rq = *port); port++) {
1379 			char hdr[80];
1380 			int len;
1381 
1382 			len = snprintf(hdr, sizeof(hdr),
1383 				       "\t\tActive[%d]: ",
1384 				       (int)(port - execlists->active));
1385 			if (!i915_request_signaled(rq)) {
1386 				struct intel_timeline *tl = get_timeline(rq);
1387 
1388 				len += snprintf(hdr + len, sizeof(hdr) - len,
1389 						"ring:{start:%08x, hwsp:%08x, seqno:%08x}, ",
1390 						i915_ggtt_offset(rq->ring->vma),
1391 						tl ? tl->hwsp_offset : 0,
1392 						hwsp_seqno(rq));
1393 
1394 				if (tl)
1395 					intel_timeline_put(tl);
1396 			}
1397 			snprintf(hdr + len, sizeof(hdr) - len, "rq: ");
1398 			print_request(m, rq, hdr);
1399 		}
1400 		for (port = execlists->pending; (rq = *port); port++) {
1401 			struct intel_timeline *tl = get_timeline(rq);
1402 			char hdr[80];
1403 
1404 			snprintf(hdr, sizeof(hdr),
1405 				 "\t\tPending[%d] ring:{start:%08x, hwsp:%08x, seqno:%08x}, rq: ",
1406 				 (int)(port - execlists->pending),
1407 				 i915_ggtt_offset(rq->ring->vma),
1408 				 tl ? tl->hwsp_offset : 0,
1409 				 hwsp_seqno(rq));
1410 			print_request(m, rq, hdr);
1411 
1412 			if (tl)
1413 				intel_timeline_put(tl);
1414 		}
1415 		rcu_read_unlock();
1416 		execlists_active_unlock_bh(execlists);
1417 	} else if (INTEL_GEN(dev_priv) > 6) {
1418 		drm_printf(m, "\tPP_DIR_BASE: 0x%08x\n",
1419 			   ENGINE_READ(engine, RING_PP_DIR_BASE));
1420 		drm_printf(m, "\tPP_DIR_BASE_READ: 0x%08x\n",
1421 			   ENGINE_READ(engine, RING_PP_DIR_BASE_READ));
1422 		drm_printf(m, "\tPP_DIR_DCLV: 0x%08x\n",
1423 			   ENGINE_READ(engine, RING_PP_DIR_DCLV));
1424 	}
1425 }
1426 
1427 static void print_request_ring(struct drm_printer *m, struct i915_request *rq)
1428 {
1429 	void *ring;
1430 	int size;
1431 
1432 	drm_printf(m,
1433 		   "[head %04x, postfix %04x, tail %04x, batch 0x%08x_%08x]:\n",
1434 		   rq->head, rq->postfix, rq->tail,
1435 		   rq->batch ? upper_32_bits(rq->batch->node.start) : ~0u,
1436 		   rq->batch ? lower_32_bits(rq->batch->node.start) : ~0u);
1437 
1438 	size = rq->tail - rq->head;
1439 	if (rq->tail < rq->head)
1440 		size += rq->ring->size;
1441 
1442 	ring = kmalloc(size, GFP_ATOMIC);
1443 	if (ring) {
1444 		const void *vaddr = rq->ring->vaddr;
1445 		unsigned int head = rq->head;
1446 		unsigned int len = 0;
1447 
1448 		if (rq->tail < head) {
1449 			len = rq->ring->size - head;
1450 			memcpy(ring, vaddr + head, len);
1451 			head = 0;
1452 		}
1453 		memcpy(ring + len, vaddr + head, size - len);
1454 
1455 		hexdump(m, ring, size);
1456 		kfree(ring);
1457 	}
1458 }
1459 
1460 void intel_engine_dump(struct intel_engine_cs *engine,
1461 		       struct drm_printer *m,
1462 		       const char *header, ...)
1463 {
1464 	struct i915_gpu_error * const error = &engine->i915->gpu_error;
1465 	struct i915_request *rq;
1466 	intel_wakeref_t wakeref;
1467 	unsigned long flags;
1468 
1469 	if (header) {
1470 		va_list ap;
1471 
1472 		va_start(ap, header);
1473 		drm_vprintf(m, header, &ap);
1474 		va_end(ap);
1475 	}
1476 
1477 	if (intel_gt_is_wedged(engine->gt))
1478 		drm_printf(m, "*** WEDGED ***\n");
1479 
1480 	drm_printf(m, "\tAwake? %d\n", atomic_read(&engine->wakeref.count));
1481 
1482 	rcu_read_lock();
1483 	rq = READ_ONCE(engine->heartbeat.systole);
1484 	if (rq)
1485 		drm_printf(m, "\tHeartbeat: %d ms ago\n",
1486 			   jiffies_to_msecs(jiffies - rq->emitted_jiffies));
1487 	rcu_read_unlock();
1488 	drm_printf(m, "\tReset count: %d (global %d)\n",
1489 		   i915_reset_engine_count(error, engine),
1490 		   i915_reset_count(error));
1491 
1492 	drm_printf(m, "\tRequests:\n");
1493 
1494 	spin_lock_irqsave(&engine->active.lock, flags);
1495 	rq = intel_engine_find_active_request(engine);
1496 	if (rq) {
1497 		struct intel_timeline *tl = get_timeline(rq);
1498 
1499 		print_request(m, rq, "\t\tactive ");
1500 
1501 		drm_printf(m, "\t\tring->start:  0x%08x\n",
1502 			   i915_ggtt_offset(rq->ring->vma));
1503 		drm_printf(m, "\t\tring->head:   0x%08x\n",
1504 			   rq->ring->head);
1505 		drm_printf(m, "\t\tring->tail:   0x%08x\n",
1506 			   rq->ring->tail);
1507 		drm_printf(m, "\t\tring->emit:   0x%08x\n",
1508 			   rq->ring->emit);
1509 		drm_printf(m, "\t\tring->space:  0x%08x\n",
1510 			   rq->ring->space);
1511 
1512 		if (tl) {
1513 			drm_printf(m, "\t\tring->hwsp:   0x%08x\n",
1514 				   tl->hwsp_offset);
1515 			intel_timeline_put(tl);
1516 		}
1517 
1518 		print_request_ring(m, rq);
1519 
1520 		if (rq->hw_context->lrc_reg_state) {
1521 			drm_printf(m, "Logical Ring Context:\n");
1522 			hexdump(m, rq->hw_context->lrc_reg_state, PAGE_SIZE);
1523 		}
1524 	}
1525 	spin_unlock_irqrestore(&engine->active.lock, flags);
1526 
1527 	drm_printf(m, "\tMMIO base:  0x%08x\n", engine->mmio_base);
1528 	wakeref = intel_runtime_pm_get_if_in_use(engine->uncore->rpm);
1529 	if (wakeref) {
1530 		intel_engine_print_registers(engine, m);
1531 		intel_runtime_pm_put(engine->uncore->rpm, wakeref);
1532 	} else {
1533 		drm_printf(m, "\tDevice is asleep; skipping register dump\n");
1534 	}
1535 
1536 	intel_execlists_show_requests(engine, m, print_request, 8);
1537 
1538 	drm_printf(m, "HWSP:\n");
1539 	hexdump(m, engine->status_page.addr, PAGE_SIZE);
1540 
1541 	drm_printf(m, "Idle? %s\n", yesno(intel_engine_is_idle(engine)));
1542 
1543 	intel_engine_print_breadcrumbs(engine, m);
1544 }
1545 
1546 /**
1547  * intel_enable_engine_stats() - Enable engine busy tracking on engine
1548  * @engine: engine to enable stats collection
1549  *
1550  * Start collecting the engine busyness data for @engine.
1551  *
1552  * Returns 0 on success or a negative error code.
1553  */
1554 int intel_enable_engine_stats(struct intel_engine_cs *engine)
1555 {
1556 	struct intel_engine_execlists *execlists = &engine->execlists;
1557 	unsigned long flags;
1558 	int err = 0;
1559 
1560 	if (!intel_engine_supports_stats(engine))
1561 		return -ENODEV;
1562 
1563 	execlists_active_lock_bh(execlists);
1564 	write_seqlock_irqsave(&engine->stats.lock, flags);
1565 
1566 	if (unlikely(engine->stats.enabled == ~0)) {
1567 		err = -EBUSY;
1568 		goto unlock;
1569 	}
1570 
1571 	if (engine->stats.enabled++ == 0) {
1572 		struct i915_request * const *port;
1573 		struct i915_request *rq;
1574 
1575 		engine->stats.enabled_at = ktime_get();
1576 
1577 		/* XXX submission method oblivious? */
1578 		for (port = execlists->active; (rq = *port); port++)
1579 			engine->stats.active++;
1580 
1581 		for (port = execlists->pending; (rq = *port); port++) {
1582 			/* Exclude any contexts already counted in active */
1583 			if (!intel_context_inflight_count(rq->hw_context))
1584 				engine->stats.active++;
1585 		}
1586 
1587 		if (engine->stats.active)
1588 			engine->stats.start = engine->stats.enabled_at;
1589 	}
1590 
1591 unlock:
1592 	write_sequnlock_irqrestore(&engine->stats.lock, flags);
1593 	execlists_active_unlock_bh(execlists);
1594 
1595 	return err;
1596 }
1597 
1598 static ktime_t __intel_engine_get_busy_time(struct intel_engine_cs *engine)
1599 {
1600 	ktime_t total = engine->stats.total;
1601 
1602 	/*
1603 	 * If the engine is executing something at the moment
1604 	 * add it to the total.
1605 	 */
1606 	if (engine->stats.active)
1607 		total = ktime_add(total,
1608 				  ktime_sub(ktime_get(), engine->stats.start));
1609 
1610 	return total;
1611 }
1612 
1613 /**
1614  * intel_engine_get_busy_time() - Return current accumulated engine busyness
1615  * @engine: engine to report on
1616  *
1617  * Returns accumulated time @engine was busy since engine stats were enabled.
1618  */
1619 ktime_t intel_engine_get_busy_time(struct intel_engine_cs *engine)
1620 {
1621 	unsigned int seq;
1622 	ktime_t total;
1623 
1624 	do {
1625 		seq = read_seqbegin(&engine->stats.lock);
1626 		total = __intel_engine_get_busy_time(engine);
1627 	} while (read_seqretry(&engine->stats.lock, seq));
1628 
1629 	return total;
1630 }
1631 
1632 /**
1633  * intel_disable_engine_stats() - Disable engine busy tracking on engine
1634  * @engine: engine to disable stats collection
1635  *
1636  * Stops collecting the engine busyness data for @engine.
1637  */
1638 void intel_disable_engine_stats(struct intel_engine_cs *engine)
1639 {
1640 	unsigned long flags;
1641 
1642 	if (!intel_engine_supports_stats(engine))
1643 		return;
1644 
1645 	write_seqlock_irqsave(&engine->stats.lock, flags);
1646 	WARN_ON_ONCE(engine->stats.enabled == 0);
1647 	if (--engine->stats.enabled == 0) {
1648 		engine->stats.total = __intel_engine_get_busy_time(engine);
1649 		engine->stats.active = 0;
1650 	}
1651 	write_sequnlock_irqrestore(&engine->stats.lock, flags);
1652 }
1653 
1654 static bool match_ring(struct i915_request *rq)
1655 {
1656 	u32 ring = ENGINE_READ(rq->engine, RING_START);
1657 
1658 	return ring == i915_ggtt_offset(rq->ring->vma);
1659 }
1660 
1661 struct i915_request *
1662 intel_engine_find_active_request(struct intel_engine_cs *engine)
1663 {
1664 	struct i915_request *request, *active = NULL;
1665 
1666 	/*
1667 	 * We are called by the error capture, reset and to dump engine
1668 	 * state at random points in time. In particular, note that neither is
1669 	 * crucially ordered with an interrupt. After a hang, the GPU is dead
1670 	 * and we assume that no more writes can happen (we waited long enough
1671 	 * for all writes that were in transaction to be flushed) - adding an
1672 	 * extra delay for a recent interrupt is pointless. Hence, we do
1673 	 * not need an engine->irq_seqno_barrier() before the seqno reads.
1674 	 * At all other times, we must assume the GPU is still running, but
1675 	 * we only care about the snapshot of this moment.
1676 	 */
1677 	lockdep_assert_held(&engine->active.lock);
1678 	list_for_each_entry(request, &engine->active.requests, sched.link) {
1679 		if (i915_request_completed(request))
1680 			continue;
1681 
1682 		if (!i915_request_started(request))
1683 			continue;
1684 
1685 		/* More than one preemptible request may match! */
1686 		if (!match_ring(request))
1687 			continue;
1688 
1689 		active = request;
1690 		break;
1691 	}
1692 
1693 	return active;
1694 }
1695 
1696 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
1697 #include "mock_engine.c"
1698 #include "selftest_engine.c"
1699 #include "selftest_engine_cs.c"
1700 #endif
1701