xref: /linux/drivers/gpu/drm/xe/xe_guc_capture.c (revision 7d8d6ad659c02ed5d2387777194c22e8e81dbb2b)
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright © 2021-2024 Intel Corporation
4  */
5 
6 #include <linux/types.h>
7 
8 #include <drm/drm_managed.h>
9 #include <drm/drm_print.h>
10 
11 #include "abi/guc_actions_abi.h"
12 #include "abi/guc_capture_abi.h"
13 #include "abi/guc_log_abi.h"
14 #include "regs/xe_engine_regs.h"
15 #include "regs/xe_gt_regs.h"
16 
17 #include "xe_bo_types.h"
18 #include "xe_device.h"
19 #include "xe_exec_queue_types.h"
20 #include "xe_gt.h"
21 #include "xe_gt_mcr.h"
22 #include "xe_gt_printk.h"
23 #include "xe_guc.h"
24 #include "xe_guc_capture.h"
25 #include "xe_guc_capture_types.h"
26 #include "xe_guc_ct.h"
27 #include "xe_guc_exec_queue_types.h"
28 #include "xe_guc_log.h"
29 #include "xe_guc_submit_types.h"
30 #include "xe_guc_submit.h"
31 #include "xe_hw_engine_types.h"
32 #include "xe_hw_engine.h"
33 #include "xe_lrc.h"
34 #include "xe_macros.h"
35 #include "xe_map.h"
36 #include "xe_mmio.h"
37 #include "xe_sched_job.h"
38 
39 /*
40  * struct __guc_capture_bufstate
41  *
42  * Book-keeping structure used to track read and write pointers
43  * as we extract error capture data from the GuC-log-buffer's
44  * error-capture region as a stream of dwords.
45  */
46 struct __guc_capture_bufstate {
47 	u32 size;
48 	u32 data_offset;
49 	u32 rd;
50 	u32 wr;
51 };
52 
53 /*
54  * struct __guc_capture_parsed_output - extracted error capture node
55  *
56  * A single unit of extracted error-capture output data grouped together
57  * at an engine-instance level. We keep these nodes in a linked list.
58  * See cachelist and outlist below.
59  */
60 struct __guc_capture_parsed_output {
61 	/*
62 	 * A single set of 3 capture lists: a global-list
63 	 * an engine-class-list and an engine-instance list.
64 	 * outlist in __guc_capture_parsed_output will keep
65 	 * a linked list of these nodes that will eventually
66 	 * be detached from outlist and attached into to
67 	 * xe_codedump in response to a context reset
68 	 */
69 	struct list_head link;
70 	bool is_partial;
71 	u32 eng_class;
72 	u32 eng_inst;
73 	u32 guc_id;
74 	u32 lrca;
75 	u32 type;
76 	bool locked;
77 	enum xe_hw_engine_snapshot_source_id source;
78 	struct gcap_reg_list_info {
79 		u32 vfid;
80 		u32 num_regs;
81 		struct guc_mmio_reg *regs;
82 	} reginfo[GUC_STATE_CAPTURE_TYPE_MAX];
83 #define GCAP_PARSED_REGLIST_INDEX_GLOBAL   BIT(GUC_STATE_CAPTURE_TYPE_GLOBAL)
84 #define GCAP_PARSED_REGLIST_INDEX_ENGCLASS BIT(GUC_STATE_CAPTURE_TYPE_ENGINE_CLASS)
85 };
86 
87 /*
88  * Define all device tables of GuC error capture register lists
89  * NOTE:
90  *     For engine-registers, GuC only needs the register offsets
91  *     from the engine-mmio-base
92  *
93  *     64 bit registers need 2 entries for low 32 bit register and high 32 bit
94  *     register, for example:
95  *       Register           data_type       flags   mask    Register name
96  *     { XXX_REG_LO(0),  REG_64BIT_LOW_DW,    0,      0,      NULL},
97  *     { XXX_REG_HI(0),  REG_64BIT_HI_DW,,    0,      0,      "XXX_REG"},
98  *     1. data_type: Indicate is hi/low 32 bit for a 64 bit register
99  *                   A 64 bit register define requires 2 consecutive entries,
100  *                   with low dword first and hi dword the second.
101  *     2. Register name: null for incompleted define
102  *     3. Incorrect order will trigger XE_WARN.
103  */
104 #define COMMON_XELP_BASE_GLOBAL \
105 	{ FORCEWAKE_GT,			REG_32BIT,	0,	0,	0,	"FORCEWAKE_GT"}
106 
107 #define COMMON_BASE_ENGINE_INSTANCE \
108 	{ RING_HWSTAM(0),		REG_32BIT,	0,	0,	0,	"HWSTAM"}, \
109 	{ RING_HWS_PGA(0),		REG_32BIT,	0,	0,	0,	"RING_HWS_PGA"}, \
110 	{ RING_HEAD(0),			REG_32BIT,	0,	0,	0,	"RING_HEAD"}, \
111 	{ RING_TAIL(0),			REG_32BIT,	0,	0,	0,	"RING_TAIL"}, \
112 	{ RING_CTL(0),			REG_32BIT,	0,	0,	0,	"RING_CTL"}, \
113 	{ RING_MI_MODE(0),		REG_32BIT,	0,	0,	0,	"RING_MI_MODE"}, \
114 	{ GFX_MODE(0),			REG_32BIT,	0,	0,	0,	"GFX_MODE"}, \
115 	{ RING_ESR(0),			REG_32BIT,	0,	0,	0,	"RING_ESR"}, \
116 	{ RING_EMR(0),			REG_32BIT,	0,	0,	0,	"RING_EMR"}, \
117 	{ RING_EIR(0),			REG_32BIT,	0,	0,	0,	"RING_EIR"}, \
118 	{ RING_IMR(0),			REG_32BIT,	0,	0,	0,	"RING_IMR"}, \
119 	{ RING_IPEHR(0),		REG_32BIT,	0,	0,	0,	"IPEHR"}, \
120 	{ RING_INSTDONE(0),		REG_32BIT,	0,	0,	0,	"RING_INSTDONE"}, \
121 	{ INDIRECT_RING_STATE(0),	REG_32BIT,	0,	0,	0,	"INDIRECT_RING_STATE"}, \
122 	{ RING_CURRENT_LRCA(0),		REG_32BIT,	0,	0,	0,	"CURRENT_LRCA"}, \
123 	{ RING_ACTHD(0),		REG_64BIT_LOW_DW, 0,	0,	0,	NULL}, \
124 	{ RING_ACTHD_UDW(0),		REG_64BIT_HI_DW, 0,	0,	0,	"ACTHD"}, \
125 	{ RING_BBADDR(0),		REG_64BIT_LOW_DW, 0,	0,	0,	NULL}, \
126 	{ RING_BBADDR_UDW(0),		REG_64BIT_HI_DW, 0,	0,	0,	"RING_BBADDR"}, \
127 	{ RING_START(0),		REG_64BIT_LOW_DW, 0,	0,	0,	NULL}, \
128 	{ RING_START_UDW(0),		REG_64BIT_HI_DW, 0,	0,	0,	"RING_START"}, \
129 	{ RING_DMA_FADD(0),		REG_64BIT_LOW_DW, 0,	0,	0,	NULL}, \
130 	{ RING_DMA_FADD_UDW(0),		REG_64BIT_HI_DW, 0,	0,	0,	"RING_DMA_FADD"}, \
131 	{ RING_EXECLIST_STATUS_LO(0),	REG_64BIT_LOW_DW, 0,	0,	0,	NULL}, \
132 	{ RING_EXECLIST_STATUS_HI(0),	REG_64BIT_HI_DW, 0,	0,	0,	"RING_EXECLIST_STATUS"}, \
133 	{ RING_EXECLIST_SQ_CONTENTS_LO(0), REG_64BIT_LOW_DW, 0,	0,	0,	NULL}, \
134 	{ RING_EXECLIST_SQ_CONTENTS_HI(0), REG_64BIT_HI_DW, 0,	0,	0,	"RING_EXECLIST_SQ_CONTENTS"}
135 
136 #define COMMON_XELP_RC_CLASS \
137 	{ RCU_MODE,			REG_32BIT,	0,	0,	0,	"RCU_MODE"}
138 
139 #define COMMON_XELP_RC_CLASS_INSTDONE \
140 	{ SC_INSTDONE,			REG_32BIT,	0,	0,	0,	"SC_INSTDONE"}, \
141 	{ SC_INSTDONE_EXTRA,		REG_32BIT,	0,	0,	0,	"SC_INSTDONE_EXTRA"}, \
142 	{ SC_INSTDONE_EXTRA2,		REG_32BIT,	0,	0,	0,	"SC_INSTDONE_EXTRA2"}
143 
144 #define XELP_VEC_CLASS_REGS \
145 	{ SFC_DONE(0),			0,	0,	0,	0,	"SFC_DONE[0]"}, \
146 	{ SFC_DONE(1),			0,	0,	0,	0,	"SFC_DONE[1]"}, \
147 	{ SFC_DONE(2),			0,	0,	0,	0,	"SFC_DONE[2]"}, \
148 	{ SFC_DONE(3),			0,	0,	0,	0,	"SFC_DONE[3]"}
149 
150 #define XE3P_BASE_ENGINE_INSTANCE \
151 	{ RING_CSMQDEBUG(0),		REG_32BIT,	0,	0,	0,	"CSMQDEBUG"}
152 
153 /* XE_LP Global */
154 static const struct __guc_mmio_reg_descr xe_lp_global_regs[] = {
155 	COMMON_XELP_BASE_GLOBAL,
156 };
157 
158 /* Render / Compute Per-Engine-Instance */
159 static const struct __guc_mmio_reg_descr xe_rc_inst_regs[] = {
160 	COMMON_BASE_ENGINE_INSTANCE,
161 };
162 
163 /* Render / Compute Engine-Class */
164 static const struct __guc_mmio_reg_descr xe_rc_class_regs[] = {
165 	COMMON_XELP_RC_CLASS,
166 	COMMON_XELP_RC_CLASS_INSTDONE,
167 };
168 
169 /* Render / Compute Engine-Class for xehpg */
170 static const struct __guc_mmio_reg_descr xe_hpg_rc_class_regs[] = {
171 	COMMON_XELP_RC_CLASS,
172 };
173 
174 /* Media Decode/Encode Per-Engine-Instance */
175 static const struct __guc_mmio_reg_descr xe_vd_inst_regs[] = {
176 	COMMON_BASE_ENGINE_INSTANCE,
177 };
178 
179 /* Video Enhancement Engine-Class */
180 static const struct __guc_mmio_reg_descr xe_vec_class_regs[] = {
181 	XELP_VEC_CLASS_REGS,
182 };
183 
184 /* Video Enhancement Per-Engine-Instance */
185 static const struct __guc_mmio_reg_descr xe_vec_inst_regs[] = {
186 	COMMON_BASE_ENGINE_INSTANCE,
187 };
188 
189 /* Blitter Per-Engine-Instance */
190 static const struct __guc_mmio_reg_descr xe_blt_inst_regs[] = {
191 	COMMON_BASE_ENGINE_INSTANCE,
192 };
193 
194 /* XE_LP - GSC Per-Engine-Instance */
195 static const struct __guc_mmio_reg_descr xe_lp_gsc_inst_regs[] = {
196 	COMMON_BASE_ENGINE_INSTANCE,
197 };
198 
199 /* Render / Compute Per-Engine-Instance */
200 static const struct __guc_mmio_reg_descr xe3p_rc_inst_regs[] = {
201 	COMMON_BASE_ENGINE_INSTANCE,
202 	XE3P_BASE_ENGINE_INSTANCE,
203 };
204 
205 /*
206  * Empty list to prevent warnings about unknown class/instance types
207  * as not all class/instance types have entries on all platforms.
208  */
209 static const struct __guc_mmio_reg_descr empty_regs_list[] = {
210 };
211 
212 #define TO_GCAP_DEF_OWNER(x) (GUC_CAPTURE_LIST_INDEX_##x)
213 #define TO_GCAP_DEF_TYPE(x) (GUC_STATE_CAPTURE_TYPE_##x)
214 #define MAKE_REGLIST(regslist, regsowner, regstype, class) \
215 	{ \
216 		regslist, \
217 		ARRAY_SIZE(regslist), \
218 		TO_GCAP_DEF_OWNER(regsowner), \
219 		TO_GCAP_DEF_TYPE(regstype), \
220 		class \
221 	}
222 
223 /* List of lists for legacy graphic product version < 1255 */
224 static const struct __guc_mmio_reg_descr_group xe_lp_lists[] = {
225 	MAKE_REGLIST(xe_lp_global_regs, PF, GLOBAL, 0),
226 	MAKE_REGLIST(xe_rc_class_regs, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_RENDER_COMPUTE),
227 	MAKE_REGLIST(xe_rc_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_RENDER_COMPUTE),
228 	MAKE_REGLIST(empty_regs_list, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_VIDEO),
229 	MAKE_REGLIST(xe_vd_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_VIDEO),
230 	MAKE_REGLIST(xe_vec_class_regs, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_VIDEOENHANCE),
231 	MAKE_REGLIST(xe_vec_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_VIDEOENHANCE),
232 	MAKE_REGLIST(empty_regs_list, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_BLITTER),
233 	MAKE_REGLIST(xe_blt_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_BLITTER),
234 	MAKE_REGLIST(empty_regs_list, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_GSC_OTHER),
235 	MAKE_REGLIST(xe_lp_gsc_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_GSC_OTHER),
236 	{}
237 };
238 
239  /* List of lists for graphic product version >= 1255 */
240 static const struct __guc_mmio_reg_descr_group xe_hpg_lists[] = {
241 	MAKE_REGLIST(xe_lp_global_regs, PF, GLOBAL, 0),
242 	MAKE_REGLIST(xe_hpg_rc_class_regs, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_RENDER_COMPUTE),
243 	MAKE_REGLIST(xe_rc_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_RENDER_COMPUTE),
244 	MAKE_REGLIST(empty_regs_list, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_VIDEO),
245 	MAKE_REGLIST(xe_vd_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_VIDEO),
246 	MAKE_REGLIST(xe_vec_class_regs, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_VIDEOENHANCE),
247 	MAKE_REGLIST(xe_vec_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_VIDEOENHANCE),
248 	MAKE_REGLIST(empty_regs_list, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_BLITTER),
249 	MAKE_REGLIST(xe_blt_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_BLITTER),
250 	MAKE_REGLIST(empty_regs_list, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_GSC_OTHER),
251 	MAKE_REGLIST(xe_lp_gsc_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_GSC_OTHER),
252 	{}
253 };
254 
255  /* List of lists for Xe3p and beyond */
256 static const struct __guc_mmio_reg_descr_group xe3p_lists[] = {
257 	MAKE_REGLIST(xe_lp_global_regs, PF, GLOBAL, 0),
258 	MAKE_REGLIST(xe_hpg_rc_class_regs, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_RENDER_COMPUTE),
259 	MAKE_REGLIST(xe3p_rc_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_RENDER_COMPUTE),
260 	MAKE_REGLIST(empty_regs_list, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_VIDEO),
261 	MAKE_REGLIST(xe_vd_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_VIDEO),
262 	MAKE_REGLIST(xe_vec_class_regs, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_VIDEOENHANCE),
263 	MAKE_REGLIST(xe_vec_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_VIDEOENHANCE),
264 	MAKE_REGLIST(empty_regs_list, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_BLITTER),
265 	MAKE_REGLIST(xe_blt_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_BLITTER),
266 	MAKE_REGLIST(empty_regs_list, PF, ENGINE_CLASS, GUC_CAPTURE_LIST_CLASS_GSC_OTHER),
267 	MAKE_REGLIST(xe_lp_gsc_inst_regs, PF, ENGINE_INSTANCE, GUC_CAPTURE_LIST_CLASS_GSC_OTHER),
268 	{}
269 };
270 static const char * const capture_list_type_names[] = {
271 	"Global",
272 	"Class",
273 	"Instance",
274 };
275 
276 static const char * const capture_engine_class_names[] = {
277 	"Render/Compute",
278 	"Video",
279 	"VideoEnhance",
280 	"Blitter",
281 	"GSC-Other",
282 };
283 
284 struct __guc_capture_ads_cache {
285 	bool is_valid;
286 	void *ptr;
287 	size_t size;
288 	int status;
289 };
290 
291 struct xe_guc_state_capture {
292 	const struct __guc_mmio_reg_descr_group *reglists;
293 	/**
294 	 * NOTE: steered registers have multiple instances depending on the HW configuration
295 	 * (slices or dual-sub-slices) and thus depends on HW fuses discovered
296 	 */
297 	struct __guc_mmio_reg_descr_group *extlists;
298 	struct __guc_capture_ads_cache ads_cache[GUC_CAPTURE_LIST_INDEX_MAX]
299 						[GUC_STATE_CAPTURE_TYPE_MAX]
300 						[GUC_CAPTURE_LIST_CLASS_MAX];
301 	void *ads_null_cache;
302 	struct list_head cachelist;
303 #define PREALLOC_NODES_MAX_COUNT (3 * GUC_MAX_ENGINE_CLASSES * GUC_MAX_INSTANCES_PER_CLASS)
304 #define PREALLOC_NODES_DEFAULT_NUMREGS 64
305 
306 	int max_mmio_per_node;
307 	struct list_head outlist;
308 };
309 
310 static void
311 guc_capture_remove_stale_matches_from_list(struct xe_guc_state_capture *gc,
312 					   struct __guc_capture_parsed_output *node);
313 
314 static const struct __guc_mmio_reg_descr_group *
315 guc_capture_get_device_reglist(struct xe_device *xe)
316 {
317 	if (GRAPHICS_VER(xe) >= 35)
318 		return xe3p_lists;
319 	else if (GRAPHICS_VERx100(xe) >= 1255)
320 		return xe_hpg_lists;
321 	else
322 		return xe_lp_lists;
323 }
324 
325 static const struct __guc_mmio_reg_descr_group *
326 guc_capture_get_one_list(const struct __guc_mmio_reg_descr_group *reglists,
327 			 u32 owner, u32 type, enum guc_capture_list_class_type capture_class)
328 {
329 	int i;
330 
331 	if (!reglists)
332 		return NULL;
333 
334 	for (i = 0; reglists[i].list; ++i) {
335 		if (reglists[i].owner == owner && reglists[i].type == type &&
336 		    (reglists[i].engine == capture_class ||
337 		     reglists[i].type == GUC_STATE_CAPTURE_TYPE_GLOBAL))
338 			return &reglists[i];
339 	}
340 
341 	return NULL;
342 }
343 
344 const struct __guc_mmio_reg_descr_group *
345 xe_guc_capture_get_reg_desc_list(struct xe_gt *gt, u32 owner, u32 type,
346 				 enum guc_capture_list_class_type capture_class, bool is_ext)
347 {
348 	const struct __guc_mmio_reg_descr_group *reglists;
349 
350 	if (is_ext) {
351 		struct xe_guc *guc = &gt->uc.guc;
352 
353 		reglists = guc->capture->extlists;
354 	} else {
355 		reglists = guc_capture_get_device_reglist(gt_to_xe(gt));
356 	}
357 	return guc_capture_get_one_list(reglists, owner, type, capture_class);
358 }
359 
360 struct __ext_steer_reg {
361 	const char *name;
362 	struct xe_reg_mcr reg;
363 };
364 
365 static const struct __ext_steer_reg xe_extregs[] = {
366 	{"SAMPLER_INSTDONE",		SAMPLER_INSTDONE},
367 	{"ROW_INSTDONE",		ROW_INSTDONE}
368 };
369 
370 static const struct __ext_steer_reg xehpg_extregs[] = {
371 	{"SC_INSTDONE",			XEHPG_SC_INSTDONE},
372 	{"SC_INSTDONE_EXTRA",		XEHPG_SC_INSTDONE_EXTRA},
373 	{"SC_INSTDONE_EXTRA2",		XEHPG_SC_INSTDONE_EXTRA2},
374 	{"INSTDONE_GEOM_SVGUNIT",	XEHPG_INSTDONE_GEOM_SVGUNIT}
375 };
376 
377 static void __fill_ext_reg(struct __guc_mmio_reg_descr *ext,
378 			   const struct __ext_steer_reg *extlist,
379 			   u32 dss_id, u16 slice_id, u16 subslice_id)
380 {
381 	if (!ext || !extlist)
382 		return;
383 
384 	ext->reg = XE_REG(extlist->reg.__reg.addr);
385 	ext->flags = FIELD_PREP(GUC_REGSET_STEERING_NEEDED, 1);
386 	ext->flags |= FIELD_PREP(GUC_REGSET_STEERING_GROUP, slice_id);
387 	ext->flags |= FIELD_PREP(GUC_REGSET_STEERING_INSTANCE, subslice_id);
388 	ext->dss_id = dss_id;
389 	ext->regname = extlist->name;
390 }
391 
392 static int
393 __alloc_ext_regs(struct drm_device *drm, struct __guc_mmio_reg_descr_group *newlist,
394 		 const struct __guc_mmio_reg_descr_group *rootlist, int num_regs)
395 {
396 	struct __guc_mmio_reg_descr *list;
397 
398 	list = drmm_kzalloc(drm, num_regs * sizeof(struct __guc_mmio_reg_descr), GFP_KERNEL);
399 	if (!list)
400 		return -ENOMEM;
401 
402 	newlist->list = list;
403 	newlist->num_regs = num_regs;
404 	newlist->owner = rootlist->owner;
405 	newlist->engine = rootlist->engine;
406 	newlist->type = rootlist->type;
407 
408 	return 0;
409 }
410 
411 static int guc_capture_get_steer_reg_num(struct xe_device *xe)
412 {
413 	int num = ARRAY_SIZE(xe_extregs);
414 
415 	if (GRAPHICS_VERx100(xe) >= 1255)
416 		num += ARRAY_SIZE(xehpg_extregs);
417 
418 	return num;
419 }
420 
421 static void guc_capture_alloc_steered_lists(struct xe_guc *guc)
422 {
423 	struct xe_gt *gt = guc_to_gt(guc);
424 	u16 slice, subslice;
425 	int dss, i, total = 0;
426 	const struct __guc_mmio_reg_descr_group *lists = guc->capture->reglists;
427 	const struct __guc_mmio_reg_descr_group *list;
428 	struct __guc_mmio_reg_descr_group *extlists;
429 	struct __guc_mmio_reg_descr *extarray;
430 	bool has_xehpg_extregs = GRAPHICS_VERx100(gt_to_xe(gt)) >= 1255;
431 	struct drm_device *drm = &gt_to_xe(gt)->drm;
432 	bool has_rcs_ccs = false;
433 	struct xe_hw_engine *hwe;
434 	enum xe_hw_engine_id id;
435 
436 	/*
437 	 * If GT has no rcs/ccs, no need to alloc steered list.
438 	 * Currently, only rcs/ccs has steering register, if in the future,
439 	 * other engine types has steering register, this condition check need
440 	 * to be extended
441 	 */
442 	for_each_hw_engine(hwe, gt, id) {
443 		if (xe_engine_class_to_guc_capture_class(hwe->class) ==
444 		    GUC_CAPTURE_LIST_CLASS_RENDER_COMPUTE) {
445 			has_rcs_ccs = true;
446 			break;
447 		}
448 	}
449 
450 	if (!has_rcs_ccs)
451 		return;
452 
453 	/* steered registers currently only exist for the render-class */
454 	list = guc_capture_get_one_list(lists, GUC_CAPTURE_LIST_INDEX_PF,
455 					GUC_STATE_CAPTURE_TYPE_ENGINE_CLASS,
456 					GUC_CAPTURE_LIST_CLASS_RENDER_COMPUTE);
457 	/*
458 	 * Skip if this platform has no engine class registers or if extlists
459 	 * was previously allocated
460 	 */
461 	if (!list || guc->capture->extlists)
462 		return;
463 
464 	{
465 		xe_dss_mask_t all_dss;
466 
467 		total = bitmap_weighted_or(all_dss, gt->fuse_topo.g_dss_mask,
468 					   gt->fuse_topo.c_dss_mask,
469 					   XE_MAX_DSS_FUSE_BITS) *
470 			guc_capture_get_steer_reg_num(guc_to_xe(guc));
471 	}
472 
473 	if (!total)
474 		return;
475 
476 	/* allocate an extra for an end marker */
477 	extlists = drmm_kzalloc(drm, 2 * sizeof(struct __guc_mmio_reg_descr_group), GFP_KERNEL);
478 	if (!extlists)
479 		return;
480 
481 	if (__alloc_ext_regs(drm, &extlists[0], list, total)) {
482 		drmm_kfree(drm, extlists);
483 		return;
484 	}
485 
486 	/* For steering registers, the list is generated at run-time */
487 	extarray = (struct __guc_mmio_reg_descr *)extlists[0].list;
488 	for_each_dss_steering(dss, gt, slice, subslice) {
489 		for (i = 0; i < ARRAY_SIZE(xe_extregs); ++i) {
490 			__fill_ext_reg(extarray, &xe_extregs[i], dss, slice, subslice);
491 			++extarray;
492 		}
493 
494 		if (has_xehpg_extregs)
495 			for (i = 0; i < ARRAY_SIZE(xehpg_extregs); ++i) {
496 				__fill_ext_reg(extarray, &xehpg_extregs[i], dss, slice, subslice);
497 				++extarray;
498 			}
499 	}
500 
501 	extlists[0].num_regs = total;
502 
503 	xe_gt_dbg(guc_to_gt(guc), "capture found %d ext-regs.\n", total);
504 	guc->capture->extlists = extlists;
505 }
506 
507 static int
508 guc_capture_list_init(struct xe_guc *guc, u32 owner, u32 type,
509 		      enum guc_capture_list_class_type capture_class, struct guc_mmio_reg *ptr,
510 		      u16 num_entries)
511 {
512 	u32 ptr_idx = 0, list_idx = 0;
513 	const struct __guc_mmio_reg_descr_group *reglists = guc->capture->reglists;
514 	struct __guc_mmio_reg_descr_group *extlists = guc->capture->extlists;
515 	const struct __guc_mmio_reg_descr_group *match;
516 	u32 list_num;
517 
518 	if (!reglists)
519 		return -ENODEV;
520 
521 	match = guc_capture_get_one_list(reglists, owner, type, capture_class);
522 	if (!match)
523 		return -ENODATA;
524 
525 	list_num = match->num_regs;
526 	for (list_idx = 0; ptr_idx < num_entries && list_idx < list_num; ++list_idx, ++ptr_idx) {
527 		ptr[ptr_idx].offset = match->list[list_idx].reg.addr;
528 		ptr[ptr_idx].value = 0xDEADF00D;
529 		ptr[ptr_idx].flags = match->list[list_idx].flags;
530 		ptr[ptr_idx].mask = match->list[list_idx].mask;
531 	}
532 
533 	match = guc_capture_get_one_list(extlists, owner, type, capture_class);
534 	if (match)
535 		for (ptr_idx = list_num, list_idx = 0;
536 		     ptr_idx < num_entries && list_idx < match->num_regs;
537 		     ++ptr_idx, ++list_idx) {
538 			ptr[ptr_idx].offset = match->list[list_idx].reg.addr;
539 			ptr[ptr_idx].value = 0xDEADF00D;
540 			ptr[ptr_idx].flags = match->list[list_idx].flags;
541 			ptr[ptr_idx].mask = match->list[list_idx].mask;
542 		}
543 
544 	if (ptr_idx < num_entries)
545 		xe_gt_dbg(guc_to_gt(guc), "Got short capture reglist init: %d out-of %d.\n",
546 			  ptr_idx, num_entries);
547 
548 	return 0;
549 }
550 
551 static int
552 guc_cap_list_num_regs(struct xe_guc *guc, u32 owner, u32 type,
553 		      enum guc_capture_list_class_type capture_class)
554 {
555 	const struct __guc_mmio_reg_descr_group *match;
556 	int num_regs = 0;
557 
558 	match = guc_capture_get_one_list(guc->capture->reglists, owner, type, capture_class);
559 	if (match)
560 		num_regs = match->num_regs;
561 
562 	match = guc_capture_get_one_list(guc->capture->extlists, owner, type, capture_class);
563 	if (match)
564 		num_regs += match->num_regs;
565 	else
566 		/*
567 		 * If a caller wants the full register dump size but we have
568 		 * not yet got the hw-config, which is before max_mmio_per_node
569 		 * is initialized, then provide a worst-case number for
570 		 * extlists based on max dss fuse bits, but only ever for
571 		 * render/compute
572 		 */
573 		if (owner == GUC_CAPTURE_LIST_INDEX_PF &&
574 		    type == GUC_STATE_CAPTURE_TYPE_ENGINE_CLASS &&
575 		    capture_class == GUC_CAPTURE_LIST_CLASS_RENDER_COMPUTE &&
576 		    !guc->capture->max_mmio_per_node)
577 			num_regs += guc_capture_get_steer_reg_num(guc_to_xe(guc)) *
578 				    XE_MAX_DSS_FUSE_BITS;
579 
580 	return num_regs;
581 }
582 
583 static int
584 guc_capture_getlistsize(struct xe_guc *guc, u32 owner, u32 type,
585 			enum guc_capture_list_class_type capture_class,
586 			size_t *size, bool is_purpose_est)
587 {
588 	struct xe_guc_state_capture *gc = guc->capture;
589 	struct xe_gt *gt = guc_to_gt(guc);
590 	struct __guc_capture_ads_cache *cache;
591 	int num_regs;
592 
593 	xe_gt_assert(gt, type < GUC_STATE_CAPTURE_TYPE_MAX);
594 	xe_gt_assert(gt, capture_class < GUC_CAPTURE_LIST_CLASS_MAX);
595 
596 	cache = &gc->ads_cache[owner][type][capture_class];
597 	if (!gc->reglists) {
598 		xe_gt_warn(gt, "No capture reglist for this device\n");
599 		return -ENODEV;
600 	}
601 
602 	if (cache->is_valid) {
603 		*size = cache->size;
604 		return cache->status;
605 	}
606 
607 	if (!is_purpose_est && owner == GUC_CAPTURE_LIST_INDEX_PF &&
608 	    !guc_capture_get_one_list(gc->reglists, owner, type, capture_class)) {
609 		if (type == GUC_STATE_CAPTURE_TYPE_GLOBAL)
610 			xe_gt_warn(gt, "Missing capture reglist: global!\n");
611 		else
612 			xe_gt_warn(gt, "Missing capture reglist: %s(%u):%s(%u)!\n",
613 				   capture_list_type_names[type], type,
614 				   capture_engine_class_names[capture_class], capture_class);
615 		return -ENODEV;
616 	}
617 
618 	num_regs = guc_cap_list_num_regs(guc, owner, type, capture_class);
619 	/* intentional empty lists can exist depending on hw config */
620 	if (!num_regs)
621 		return -ENODATA;
622 
623 	if (size)
624 		*size = PAGE_ALIGN((sizeof(struct guc_debug_capture_list)) +
625 				   (num_regs * sizeof(struct guc_mmio_reg)));
626 
627 	return 0;
628 }
629 
630 /**
631  * xe_guc_capture_getlistsize - Get list size for owner/type/class combination
632  * @guc: The GuC object
633  * @owner: PF/VF owner
634  * @type: GuC capture register type
635  * @capture_class: GuC capture engine class id
636  * @size: Point to the size
637  *
638  * This function will get the list for the owner/type/class combination, and
639  * return the page aligned list size.
640  *
641  * Returns: 0 on success or a negative error code on failure.
642  */
643 int
644 xe_guc_capture_getlistsize(struct xe_guc *guc, u32 owner, u32 type,
645 			   enum guc_capture_list_class_type capture_class, size_t *size)
646 {
647 	return guc_capture_getlistsize(guc, owner, type, capture_class, size, false);
648 }
649 
650 /**
651  * xe_guc_capture_getlist - Get register capture list for owner/type/class
652  * combination
653  * @guc:	The GuC object
654  * @owner:	PF/VF owner
655  * @type:	GuC capture register type
656  * @capture_class:	GuC capture engine class id
657  * @outptr:	Point to cached register capture list
658  *
659  * This function will get the register capture list for the owner/type/class
660  * combination.
661  *
662  * Returns: 0 on success or a negative error code on failure.
663  */
664 int
665 xe_guc_capture_getlist(struct xe_guc *guc, u32 owner, u32 type,
666 		       enum guc_capture_list_class_type capture_class, void **outptr)
667 {
668 	struct xe_guc_state_capture *gc = guc->capture;
669 	struct __guc_capture_ads_cache *cache = &gc->ads_cache[owner][type][capture_class];
670 	struct guc_debug_capture_list *listnode;
671 	int ret, num_regs;
672 	u8 *caplist, *tmp;
673 	size_t size = 0;
674 
675 	if (!gc->reglists)
676 		return -ENODEV;
677 
678 	if (cache->is_valid) {
679 		*outptr = cache->ptr;
680 		return cache->status;
681 	}
682 
683 	ret = xe_guc_capture_getlistsize(guc, owner, type, capture_class, &size);
684 	if (ret) {
685 		cache->is_valid = true;
686 		cache->ptr = NULL;
687 		cache->size = 0;
688 		cache->status = ret;
689 		return ret;
690 	}
691 
692 	caplist = drmm_kzalloc(guc_to_drm(guc), size, GFP_KERNEL);
693 	if (!caplist)
694 		return -ENOMEM;
695 
696 	/* populate capture list header */
697 	tmp = caplist;
698 	num_regs = guc_cap_list_num_regs(guc, owner, type, capture_class);
699 	listnode = (struct guc_debug_capture_list *)tmp;
700 	listnode->header.info = FIELD_PREP(GUC_CAPTURELISTHDR_NUMDESCR, (u32)num_regs);
701 
702 	/* populate list of register descriptor */
703 	tmp += sizeof(struct guc_debug_capture_list);
704 	guc_capture_list_init(guc, owner, type, capture_class,
705 			      (struct guc_mmio_reg *)tmp, num_regs);
706 
707 	/* cache this list */
708 	cache->is_valid = true;
709 	cache->ptr = caplist;
710 	cache->size = size;
711 	cache->status = 0;
712 
713 	*outptr = caplist;
714 
715 	return 0;
716 }
717 
718 /**
719  * xe_guc_capture_getnullheader - Get a null list for register capture
720  * @guc:	The GuC object
721  * @outptr:	Point to cached register capture list
722  * @size:	Point to the size
723  *
724  * This function will alloc for a null list for register capture.
725  *
726  * Returns: 0 on success or a negative error code on failure.
727  */
728 int
729 xe_guc_capture_getnullheader(struct xe_guc *guc, void **outptr, size_t *size)
730 {
731 	struct xe_guc_state_capture *gc = guc->capture;
732 	int tmp = sizeof(u32) * 4;
733 	void *null_header;
734 
735 	if (gc->ads_null_cache) {
736 		*outptr = gc->ads_null_cache;
737 		*size = tmp;
738 		return 0;
739 	}
740 
741 	null_header = drmm_kzalloc(guc_to_drm(guc), tmp, GFP_KERNEL);
742 	if (!null_header)
743 		return -ENOMEM;
744 
745 	gc->ads_null_cache = null_header;
746 	*outptr = null_header;
747 	*size = tmp;
748 
749 	return 0;
750 }
751 
752 /**
753  * xe_guc_capture_ads_input_worst_size - Calculate the worst size for GuC register capture
754  * @guc: point to xe_guc structure
755  *
756  * Calculate the worst size for GuC register capture by including all possible engines classes.
757  *
758  * Returns: Calculated size
759  */
760 size_t xe_guc_capture_ads_input_worst_size(struct xe_guc *guc)
761 {
762 	size_t total_size, class_size, instance_size, global_size;
763 	int i, j;
764 
765 	/*
766 	 * This function calculates the worst case register lists size by
767 	 * including all possible engines classes. It is called during the
768 	 * first of a two-phase GuC (and ADS-population) initialization
769 	 * sequence, that is, during the pre-hwconfig phase before we have
770 	 * the exact engine fusing info.
771 	 */
772 	total_size = PAGE_SIZE;	/* Pad a page in front for empty lists */
773 	for (i = 0; i < GUC_CAPTURE_LIST_INDEX_MAX; i++) {
774 		for (j = 0; j < GUC_CAPTURE_LIST_CLASS_MAX; j++) {
775 			if (xe_guc_capture_getlistsize(guc, i,
776 						       GUC_STATE_CAPTURE_TYPE_ENGINE_CLASS,
777 						       j, &class_size) < 0)
778 				class_size = 0;
779 			if (xe_guc_capture_getlistsize(guc, i,
780 						       GUC_STATE_CAPTURE_TYPE_ENGINE_INSTANCE,
781 						       j, &instance_size) < 0)
782 				instance_size = 0;
783 			total_size += class_size + instance_size;
784 		}
785 		if (xe_guc_capture_getlistsize(guc, i,
786 					       GUC_STATE_CAPTURE_TYPE_GLOBAL,
787 					       0, &global_size) < 0)
788 			global_size = 0;
789 		total_size += global_size;
790 	}
791 
792 	return PAGE_ALIGN(total_size);
793 }
794 
795 static int guc_capture_output_size_est(struct xe_guc *guc)
796 {
797 	struct xe_gt *gt = guc_to_gt(guc);
798 	struct xe_hw_engine *hwe;
799 	enum xe_hw_engine_id id;
800 
801 	int capture_size = 0;
802 	size_t tmp = 0;
803 
804 	if (!guc->capture)
805 		return -ENODEV;
806 
807 	/*
808 	 * If every single engine-instance suffered a failure in quick succession but
809 	 * were all unrelated, then a burst of multiple error-capture events would dump
810 	 * registers for every one engine instance, one at a time. In this case, GuC
811 	 * would even dump the global-registers repeatedly.
812 	 *
813 	 * For each engine instance, there would be 1 x guc_state_capture_group_t output
814 	 * followed by 3 x guc_state_capture_t lists. The latter is how the register
815 	 * dumps are split across different register types (where the '3' are global vs class
816 	 * vs instance).
817 	 */
818 	for_each_hw_engine(hwe, gt, id) {
819 		enum guc_capture_list_class_type capture_class;
820 
821 		capture_class = xe_engine_class_to_guc_capture_class(hwe->class);
822 		capture_size += sizeof(struct guc_state_capture_group_header_t) +
823 					 (3 * sizeof(struct guc_state_capture_header_t));
824 
825 		if (!guc_capture_getlistsize(guc, 0, GUC_STATE_CAPTURE_TYPE_GLOBAL,
826 					     0, &tmp, true))
827 			capture_size += tmp;
828 		if (!guc_capture_getlistsize(guc, 0, GUC_STATE_CAPTURE_TYPE_ENGINE_CLASS,
829 					     capture_class, &tmp, true))
830 			capture_size += tmp;
831 		if (!guc_capture_getlistsize(guc, 0, GUC_STATE_CAPTURE_TYPE_ENGINE_INSTANCE,
832 					     capture_class, &tmp, true))
833 			capture_size += tmp;
834 	}
835 
836 	return capture_size;
837 }
838 
839 /*
840  * Add on a 3x multiplier to allow for multiple back-to-back captures occurring
841  * before the Xe can read the data out and process it
842  */
843 #define GUC_CAPTURE_OVERBUFFER_MULTIPLIER 3
844 
845 static void check_guc_capture_size(struct xe_guc *guc)
846 {
847 	int capture_size = guc_capture_output_size_est(guc);
848 	int spare_size = capture_size * GUC_CAPTURE_OVERBUFFER_MULTIPLIER;
849 	u32 buffer_size = XE_GUC_LOG_STATE_CAPTURE_BUFFER_SIZE;
850 
851 	/*
852 	 * NOTE: capture_size is much smaller than the capture region
853 	 * allocation (DG2: <80K vs 1MB).
854 	 * Additionally, its based on space needed to fit all engines getting
855 	 * reset at once within the same G2H handler task slot. This is very
856 	 * unlikely. However, if GuC really does run out of space for whatever
857 	 * reason, we will see an separate warning message when processing the
858 	 * G2H event capture-notification, search for:
859 	 * xe_guc_STATE_CAPTURE_EVENT_STATUS_NOSPACE.
860 	 */
861 	if (capture_size < 0)
862 		xe_gt_dbg(guc_to_gt(guc),
863 			  "Failed to calculate error state capture buffer minimum size: %d!\n",
864 			  capture_size);
865 	if (capture_size > buffer_size)
866 		xe_gt_dbg(guc_to_gt(guc), "Error state capture buffer maybe small: %d < %d\n",
867 			  buffer_size, capture_size);
868 	else if (spare_size > buffer_size)
869 		xe_gt_dbg(guc_to_gt(guc),
870 			  "Error state capture buffer lacks spare size: %d < %d (min = %d)\n",
871 			  buffer_size, spare_size, capture_size);
872 }
873 
874 static void
875 guc_capture_add_node_to_list(struct __guc_capture_parsed_output *node,
876 			     struct list_head *list)
877 {
878 	list_add(&node->link, list);
879 }
880 
881 static void
882 guc_capture_add_node_to_outlist(struct xe_guc_state_capture *gc,
883 				struct __guc_capture_parsed_output *node)
884 {
885 	guc_capture_remove_stale_matches_from_list(gc, node);
886 	guc_capture_add_node_to_list(node, &gc->outlist);
887 }
888 
889 static void
890 guc_capture_add_node_to_cachelist(struct xe_guc_state_capture *gc,
891 				  struct __guc_capture_parsed_output *node)
892 {
893 	guc_capture_add_node_to_list(node, &gc->cachelist);
894 }
895 
896 static void
897 guc_capture_free_outlist_node(struct xe_guc_state_capture *gc,
898 			      struct __guc_capture_parsed_output *n)
899 {
900 	if (n) {
901 		n->locked = 0;
902 		list_del(&n->link);
903 		/* put node back to cache list */
904 		guc_capture_add_node_to_cachelist(gc, n);
905 	}
906 }
907 
908 static void
909 guc_capture_remove_stale_matches_from_list(struct xe_guc_state_capture *gc,
910 					   struct __guc_capture_parsed_output *node)
911 {
912 	struct __guc_capture_parsed_output *n, *ntmp;
913 	int guc_id = node->guc_id;
914 
915 	list_for_each_entry_safe(n, ntmp, &gc->outlist, link) {
916 		if (n != node && !n->locked && n->guc_id == guc_id)
917 			guc_capture_free_outlist_node(gc, n);
918 	}
919 }
920 
921 static void
922 guc_capture_init_node(struct xe_guc *guc, struct __guc_capture_parsed_output *node)
923 {
924 	struct guc_mmio_reg *tmp[GUC_STATE_CAPTURE_TYPE_MAX];
925 	int i;
926 
927 	for (i = 0; i < GUC_STATE_CAPTURE_TYPE_MAX; ++i) {
928 		tmp[i] = node->reginfo[i].regs;
929 		memset(tmp[i], 0, sizeof(struct guc_mmio_reg) *
930 		       guc->capture->max_mmio_per_node);
931 	}
932 	memset(node, 0, sizeof(*node));
933 	for (i = 0; i < GUC_STATE_CAPTURE_TYPE_MAX; ++i)
934 		node->reginfo[i].regs = tmp[i];
935 
936 	INIT_LIST_HEAD(&node->link);
937 }
938 
939 /**
940  * DOC: Init, G2H-event and reporting flows for GuC-error-capture
941  *
942  * KMD Init time flows:
943  * --------------------
944  *     --> alloc A: GuC input capture regs lists (registered to GuC via ADS).
945  *                  xe_guc_ads acquires the register lists by calling
946  *                  xe_guc_capture_getlistsize and xe_guc_capture_getlist 'n' times,
947  *                  where n = 1 for global-reg-list +
948  *                            num_engine_classes for class-reg-list +
949  *                            num_engine_classes for instance-reg-list
950  *                               (since all instances of the same engine-class type
951  *                                have an identical engine-instance register-list).
952  *                  ADS module also calls separately for PF vs VF.
953  *
954  *     --> alloc B: GuC output capture buf (registered via guc_init_params(log_param))
955  *                  Size = XE_GUC_LOG_STATE_CAPTURE_BUFFER_SIZE (warns if on too-small)
956  *                  Note2: 'x 3' to hold multiple capture groups
957  *
958  * GUC Runtime notify capture:
959  * --------------------------
960  *     --> G2H STATE_CAPTURE_NOTIFICATION
961  *                   L--> xe_guc_capture_process
962  *                           L--> Loop through B (head..tail) and for each engine instance's
963  *                                err-state-captured register-list we find, we alloc 'C':
964  *      --> alloc C: A capture-output-node structure that includes misc capture info along
965  *                   with 3 register list dumps (global, engine-class and engine-instance)
966  *                   This node is created from a pre-allocated list of blank nodes in
967  *                   guc->capture->cachelist and populated with the error-capture
968  *                   data from GuC and then it's added into guc->capture->outlist linked
969  *                   list. This list is used for matchup and printout by xe_devcoredump_read
970  *                   and xe_engine_snapshot_print, (when user invokes the devcoredump sysfs).
971  *
972  * GUC --> notify context reset:
973  * -----------------------------
974  *     --> guc_exec_queue_timedout_job
975  *                   L--> xe_devcoredump
976  *                          L--> devcoredump_snapshot
977  *                               --> xe_hw_engine_snapshot_capture
978  *                               --> xe_engine_manual_capture(For manual capture)
979  *
980  * User Sysfs / Debugfs
981  * --------------------
982  *      --> xe_devcoredump_read->
983  *             L--> xxx_snapshot_print
984  *                    L--> xe_engine_snapshot_print
985  *                         Print register lists values saved at
986  *                         guc->capture->outlist
987  *
988  */
989 
990 static int guc_capture_buf_cnt(struct __guc_capture_bufstate *buf)
991 {
992 	if (buf->wr >= buf->rd)
993 		return (buf->wr - buf->rd);
994 	return (buf->size - buf->rd) + buf->wr;
995 }
996 
997 static int guc_capture_buf_cnt_to_end(struct __guc_capture_bufstate *buf)
998 {
999 	if (buf->rd > buf->wr)
1000 		return (buf->size - buf->rd);
1001 	return (buf->wr - buf->rd);
1002 }
1003 
1004 /*
1005  * GuC's error-capture output is a ring buffer populated in a byte-stream fashion:
1006  *
1007  * The GuC Log buffer region for error-capture is managed like a ring buffer.
1008  * The GuC firmware dumps error capture logs into this ring in a byte-stream flow.
1009  * Additionally, as per the current and foreseeable future, all packed error-
1010  * capture output structures are dword aligned.
1011  *
1012  * That said, if the GuC firmware is in the midst of writing a structure that is larger
1013  * than one dword but the tail end of the err-capture buffer-region has lesser space left,
1014  * we would need to extract that structure one dword at a time straddled across the end,
1015  * onto the start of the ring.
1016  *
1017  * Below function, guc_capture_log_remove_bytes is a helper for that. All callers of this
1018  * function would typically do a straight-up memcpy from the ring contents and will only
1019  * call this helper if their structure-extraction is straddling across the end of the
1020  * ring. GuC firmware does not add any padding. The reason for the no-padding is to ease
1021  * scalability for future expansion of output data types without requiring a redesign
1022  * of the flow controls.
1023  */
1024 static int
1025 guc_capture_log_remove_bytes(struct xe_guc *guc, struct __guc_capture_bufstate *buf,
1026 			     void *out, int bytes_needed)
1027 {
1028 #define GUC_CAPTURE_LOG_BUF_COPY_RETRY_MAX	3
1029 
1030 	int fill_size = 0, tries = GUC_CAPTURE_LOG_BUF_COPY_RETRY_MAX;
1031 	int copy_size, avail;
1032 
1033 	xe_assert(guc_to_xe(guc), bytes_needed % sizeof(u32) == 0);
1034 
1035 	if (bytes_needed > guc_capture_buf_cnt(buf))
1036 		return -1;
1037 
1038 	while (bytes_needed > 0 && tries--) {
1039 		int misaligned;
1040 
1041 		avail = guc_capture_buf_cnt_to_end(buf);
1042 		misaligned = avail % sizeof(u32);
1043 		/* wrap if at end */
1044 		if (!avail) {
1045 			/* output stream clipped */
1046 			if (!buf->rd)
1047 				return fill_size;
1048 			buf->rd = 0;
1049 			continue;
1050 		}
1051 
1052 		/* Only copy to u32 aligned data */
1053 		copy_size = avail < bytes_needed ? avail - misaligned : bytes_needed;
1054 		xe_map_memcpy_from(guc_to_xe(guc), out + fill_size, &guc->log.bo->vmap,
1055 				   buf->data_offset + buf->rd, copy_size);
1056 		buf->rd += copy_size;
1057 		fill_size += copy_size;
1058 		bytes_needed -= copy_size;
1059 
1060 		if (misaligned)
1061 			xe_gt_warn(guc_to_gt(guc),
1062 				   "Bytes extraction not dword aligned, clipping.\n");
1063 	}
1064 
1065 	return fill_size;
1066 }
1067 
1068 static int
1069 guc_capture_log_get_group_hdr(struct xe_guc *guc, struct __guc_capture_bufstate *buf,
1070 			      struct guc_state_capture_group_header_t *ghdr)
1071 {
1072 	int fullsize = sizeof(struct guc_state_capture_group_header_t);
1073 
1074 	if (guc_capture_log_remove_bytes(guc, buf, ghdr, fullsize) != fullsize)
1075 		return -1;
1076 	return 0;
1077 }
1078 
1079 static int
1080 guc_capture_log_get_data_hdr(struct xe_guc *guc, struct __guc_capture_bufstate *buf,
1081 			     struct guc_state_capture_header_t *hdr)
1082 {
1083 	int fullsize = sizeof(struct guc_state_capture_header_t);
1084 
1085 	if (guc_capture_log_remove_bytes(guc, buf, hdr, fullsize) != fullsize)
1086 		return -1;
1087 	return 0;
1088 }
1089 
1090 static int
1091 guc_capture_log_get_register(struct xe_guc *guc, struct __guc_capture_bufstate *buf,
1092 			     struct guc_mmio_reg *reg)
1093 {
1094 	int fullsize = sizeof(struct guc_mmio_reg);
1095 
1096 	if (guc_capture_log_remove_bytes(guc, buf, reg, fullsize) != fullsize)
1097 		return -1;
1098 	return 0;
1099 }
1100 
1101 static struct __guc_capture_parsed_output *
1102 guc_capture_get_prealloc_node(struct xe_guc *guc)
1103 {
1104 	struct __guc_capture_parsed_output *found = NULL;
1105 
1106 	if (!list_empty(&guc->capture->cachelist)) {
1107 		struct __guc_capture_parsed_output *n, *ntmp;
1108 
1109 		/* get first avail node from the cache list */
1110 		list_for_each_entry_safe(n, ntmp, &guc->capture->cachelist, link) {
1111 			found = n;
1112 			break;
1113 		}
1114 	} else {
1115 		struct __guc_capture_parsed_output *n, *ntmp;
1116 
1117 		/*
1118 		 * traverse reversed and steal back the oldest node already
1119 		 * allocated
1120 		 */
1121 		list_for_each_entry_safe_reverse(n, ntmp, &guc->capture->outlist, link) {
1122 			if (!n->locked)
1123 				found = n;
1124 		}
1125 	}
1126 	if (found) {
1127 		list_del(&found->link);
1128 		guc_capture_init_node(guc, found);
1129 	}
1130 
1131 	return found;
1132 }
1133 
1134 static struct __guc_capture_parsed_output *
1135 guc_capture_clone_node(struct xe_guc *guc, struct __guc_capture_parsed_output *original,
1136 		       u32 keep_reglist_mask)
1137 {
1138 	struct __guc_capture_parsed_output *new;
1139 	int i;
1140 
1141 	new = guc_capture_get_prealloc_node(guc);
1142 	if (!new)
1143 		return NULL;
1144 	if (!original)
1145 		return new;
1146 
1147 	new->is_partial = original->is_partial;
1148 
1149 	/* copy reg-lists that we want to clone */
1150 	for (i = 0; i < GUC_STATE_CAPTURE_TYPE_MAX; ++i) {
1151 		if (keep_reglist_mask & BIT(i)) {
1152 			XE_WARN_ON(original->reginfo[i].num_regs  >
1153 				   guc->capture->max_mmio_per_node);
1154 
1155 			memcpy(new->reginfo[i].regs, original->reginfo[i].regs,
1156 			       original->reginfo[i].num_regs * sizeof(struct guc_mmio_reg));
1157 
1158 			new->reginfo[i].num_regs = original->reginfo[i].num_regs;
1159 			new->reginfo[i].vfid  = original->reginfo[i].vfid;
1160 
1161 			if (i == GUC_STATE_CAPTURE_TYPE_ENGINE_CLASS) {
1162 				new->eng_class = original->eng_class;
1163 			} else if (i == GUC_STATE_CAPTURE_TYPE_ENGINE_INSTANCE) {
1164 				new->eng_inst = original->eng_inst;
1165 				new->guc_id = original->guc_id;
1166 				new->lrca = original->lrca;
1167 			}
1168 		}
1169 	}
1170 
1171 	return new;
1172 }
1173 
1174 static int
1175 guc_capture_extract_reglists(struct xe_guc *guc, struct __guc_capture_bufstate *buf)
1176 {
1177 	struct xe_gt *gt = guc_to_gt(guc);
1178 	struct guc_state_capture_group_header_t ghdr = {0};
1179 	struct guc_state_capture_header_t hdr = {0};
1180 	struct __guc_capture_parsed_output *node = NULL;
1181 	struct guc_mmio_reg *regs = NULL;
1182 	int i, numlists, numregs, ret = 0;
1183 	enum guc_state_capture_type datatype;
1184 	struct guc_mmio_reg tmp;
1185 	bool is_partial = false;
1186 
1187 	i = guc_capture_buf_cnt(buf);
1188 	if (!i)
1189 		return -ENODATA;
1190 
1191 	if (i % sizeof(u32)) {
1192 		xe_gt_warn(gt, "Got mis-aligned register capture entries\n");
1193 		ret = -EIO;
1194 		goto bailout;
1195 	}
1196 
1197 	/* first get the capture group header */
1198 	if (guc_capture_log_get_group_hdr(guc, buf, &ghdr)) {
1199 		ret = -EIO;
1200 		goto bailout;
1201 	}
1202 	/*
1203 	 * we would typically expect a layout as below where n would be expected to be
1204 	 * anywhere between 3 to n where n > 3 if we are seeing multiple dependent engine
1205 	 * instances being reset together.
1206 	 * ____________________________________________
1207 	 * | Capture Group                            |
1208 	 * | ________________________________________ |
1209 	 * | | Capture Group Header:                | |
1210 	 * | |  - num_captures = 5                  | |
1211 	 * | |______________________________________| |
1212 	 * | ________________________________________ |
1213 	 * | | Capture1:                            | |
1214 	 * | |  Hdr: GLOBAL, numregs=a              | |
1215 	 * | | ____________________________________ | |
1216 	 * | | | Reglist                          | | |
1217 	 * | | | - reg1, reg2, ... rega           | | |
1218 	 * | | |__________________________________| | |
1219 	 * | |______________________________________| |
1220 	 * | ________________________________________ |
1221 	 * | | Capture2:                            | |
1222 	 * | |  Hdr: CLASS=RENDER/COMPUTE, numregs=b| |
1223 	 * | | ____________________________________ | |
1224 	 * | | | Reglist                          | | |
1225 	 * | | | - reg1, reg2, ... regb           | | |
1226 	 * | | |__________________________________| | |
1227 	 * | |______________________________________| |
1228 	 * | ________________________________________ |
1229 	 * | | Capture3:                            | |
1230 	 * | |  Hdr: INSTANCE=RCS, numregs=c        | |
1231 	 * | | ____________________________________ | |
1232 	 * | | | Reglist                          | | |
1233 	 * | | | - reg1, reg2, ... regc           | | |
1234 	 * | | |__________________________________| | |
1235 	 * | |______________________________________| |
1236 	 * | ________________________________________ |
1237 	 * | | Capture4:                            | |
1238 	 * | |  Hdr: CLASS=RENDER/COMPUTE, numregs=d| |
1239 	 * | | ____________________________________ | |
1240 	 * | | | Reglist                          | | |
1241 	 * | | | - reg1, reg2, ... regd           | | |
1242 	 * | | |__________________________________| | |
1243 	 * | |______________________________________| |
1244 	 * | ________________________________________ |
1245 	 * | | Capture5:                            | |
1246 	 * | |  Hdr: INSTANCE=CCS0, numregs=e       | |
1247 	 * | | ____________________________________ | |
1248 	 * | | | Reglist                          | | |
1249 	 * | | | - reg1, reg2, ... rege           | | |
1250 	 * | | |__________________________________| | |
1251 	 * | |______________________________________| |
1252 	 * |__________________________________________|
1253 	 */
1254 	is_partial = FIELD_GET(GUC_STATE_CAPTURE_GROUP_HEADER_CAPTURE_GROUP_TYPE, ghdr.info);
1255 	numlists = FIELD_GET(GUC_STATE_CAPTURE_GROUP_HEADER_NUM_CAPTURES, ghdr.info);
1256 
1257 	while (numlists--) {
1258 		if (guc_capture_log_get_data_hdr(guc, buf, &hdr)) {
1259 			ret = -EIO;
1260 			break;
1261 		}
1262 
1263 		datatype = FIELD_GET(GUC_STATE_CAPTURE_HEADER_CAPTURE_TYPE, hdr.info);
1264 		if (datatype > GUC_STATE_CAPTURE_TYPE_ENGINE_INSTANCE) {
1265 			/* unknown capture type - skip over to next capture set */
1266 			numregs = FIELD_GET(GUC_STATE_CAPTURE_HEADER_NUM_MMIO_ENTRIES,
1267 					    hdr.num_mmio_entries);
1268 			while (numregs--) {
1269 				if (guc_capture_log_get_register(guc, buf, &tmp)) {
1270 					ret = -EIO;
1271 					break;
1272 				}
1273 			}
1274 			continue;
1275 		} else if (node) {
1276 			/*
1277 			 * Based on the current capture type and what we have so far,
1278 			 * decide if we should add the current node into the internal
1279 			 * linked list for match-up when xe_devcoredump calls later
1280 			 * (and alloc a blank node for the next set of reglists)
1281 			 * or continue with the same node or clone the current node
1282 			 * but only retain the global or class registers (such as the
1283 			 * case of dependent engine resets).
1284 			 */
1285 			if (datatype == GUC_STATE_CAPTURE_TYPE_GLOBAL) {
1286 				guc_capture_add_node_to_outlist(guc->capture, node);
1287 				node = NULL;
1288 			} else if (datatype == GUC_STATE_CAPTURE_TYPE_ENGINE_CLASS &&
1289 				   node->reginfo[GUC_STATE_CAPTURE_TYPE_ENGINE_CLASS].num_regs) {
1290 				/* Add to list, clone node and duplicate global list */
1291 				guc_capture_add_node_to_outlist(guc->capture, node);
1292 				node = guc_capture_clone_node(guc, node,
1293 							      GCAP_PARSED_REGLIST_INDEX_GLOBAL);
1294 			} else if (datatype == GUC_STATE_CAPTURE_TYPE_ENGINE_INSTANCE &&
1295 				   node->reginfo[GUC_STATE_CAPTURE_TYPE_ENGINE_INSTANCE].num_regs) {
1296 				/* Add to list, clone node and duplicate global + class lists */
1297 				guc_capture_add_node_to_outlist(guc->capture, node);
1298 				node = guc_capture_clone_node(guc, node,
1299 							      (GCAP_PARSED_REGLIST_INDEX_GLOBAL |
1300 							      GCAP_PARSED_REGLIST_INDEX_ENGCLASS));
1301 			}
1302 		}
1303 
1304 		if (!node) {
1305 			node = guc_capture_get_prealloc_node(guc);
1306 			if (!node) {
1307 				ret = -ENOMEM;
1308 				break;
1309 			}
1310 			if (datatype != GUC_STATE_CAPTURE_TYPE_GLOBAL)
1311 				xe_gt_dbg(gt, "Register capture missing global dump: %08x!\n",
1312 					  datatype);
1313 		}
1314 		node->is_partial = is_partial;
1315 		node->reginfo[datatype].vfid = FIELD_GET(GUC_STATE_CAPTURE_HEADER_VFID, hdr.owner);
1316 		node->source = XE_ENGINE_CAPTURE_SOURCE_GUC;
1317 		node->type = datatype;
1318 
1319 		switch (datatype) {
1320 		case GUC_STATE_CAPTURE_TYPE_ENGINE_INSTANCE:
1321 			node->eng_class = FIELD_GET(GUC_STATE_CAPTURE_HEADER_ENGINE_CLASS,
1322 						    hdr.info);
1323 			node->eng_inst = FIELD_GET(GUC_STATE_CAPTURE_HEADER_ENGINE_INSTANCE,
1324 						   hdr.info);
1325 			node->lrca = hdr.lrca;
1326 			node->guc_id = hdr.guc_id;
1327 			break;
1328 		case GUC_STATE_CAPTURE_TYPE_ENGINE_CLASS:
1329 			node->eng_class = FIELD_GET(GUC_STATE_CAPTURE_HEADER_ENGINE_CLASS,
1330 						    hdr.info);
1331 			break;
1332 		default:
1333 			break;
1334 		}
1335 
1336 		numregs = FIELD_GET(GUC_STATE_CAPTURE_HEADER_NUM_MMIO_ENTRIES,
1337 				    hdr.num_mmio_entries);
1338 		if (numregs > guc->capture->max_mmio_per_node) {
1339 			xe_gt_dbg(gt, "Register capture list extraction clipped by prealloc!\n");
1340 			numregs = guc->capture->max_mmio_per_node;
1341 		}
1342 		node->reginfo[datatype].num_regs = numregs;
1343 		regs = node->reginfo[datatype].regs;
1344 		i = 0;
1345 		while (numregs--) {
1346 			if (guc_capture_log_get_register(guc, buf, &regs[i++])) {
1347 				ret = -EIO;
1348 				break;
1349 			}
1350 		}
1351 	}
1352 
1353 bailout:
1354 	if (node) {
1355 		/* If we have data, add to linked list for match-up when xe_devcoredump calls */
1356 		for (i = GUC_STATE_CAPTURE_TYPE_GLOBAL; i < GUC_STATE_CAPTURE_TYPE_MAX; ++i) {
1357 			if (node->reginfo[i].regs) {
1358 				guc_capture_add_node_to_outlist(guc->capture, node);
1359 				node = NULL;
1360 				break;
1361 			}
1362 		}
1363 		if (node) /* else return it back to cache list */
1364 			guc_capture_add_node_to_cachelist(guc->capture, node);
1365 	}
1366 	return ret;
1367 }
1368 
1369 static int __guc_capture_flushlog_complete(struct xe_guc *guc)
1370 {
1371 	u32 action[] = {
1372 		XE_GUC_ACTION_LOG_BUFFER_FILE_FLUSH_COMPLETE,
1373 		GUC_LOG_TYPE_STATE_CAPTURE
1374 	};
1375 
1376 	return xe_guc_ct_send_g2h_handler(&guc->ct, action, ARRAY_SIZE(action));
1377 }
1378 
1379 static void __guc_capture_process_output(struct xe_guc *guc)
1380 {
1381 	unsigned int buffer_size, read_offset, write_offset, full_count;
1382 	struct xe_uc *uc = container_of(guc, typeof(*uc), guc);
1383 	struct guc_log_buffer_state log_buf_state_local;
1384 	struct __guc_capture_bufstate buf;
1385 	bool new_overflow;
1386 	int ret, tmp;
1387 	u32 log_buf_state_offset;
1388 	u32 src_data_offset;
1389 
1390 	log_buf_state_offset = sizeof(struct guc_log_buffer_state) * GUC_LOG_TYPE_STATE_CAPTURE;
1391 	src_data_offset = XE_GUC_LOG_STATE_CAPTURE_OFFSET;
1392 
1393 	/*
1394 	 * Make a copy of the state structure, inside GuC log buffer
1395 	 * (which is uncached mapped), on the stack to avoid reading
1396 	 * from it multiple times.
1397 	 */
1398 	xe_map_memcpy_from(guc_to_xe(guc), &log_buf_state_local, &guc->log.bo->vmap,
1399 			   log_buf_state_offset, sizeof(struct guc_log_buffer_state));
1400 
1401 	buffer_size = XE_GUC_LOG_STATE_CAPTURE_BUFFER_SIZE;
1402 	read_offset = log_buf_state_local.read_ptr;
1403 	write_offset = log_buf_state_local.sampled_write_ptr;
1404 	full_count = FIELD_GET(GUC_LOG_BUFFER_STATE_BUFFER_FULL_CNT, log_buf_state_local.flags);
1405 
1406 	/* Bookkeeping stuff */
1407 	tmp = FIELD_GET(GUC_LOG_BUFFER_STATE_FLUSH_TO_FILE, log_buf_state_local.flags);
1408 	guc->log.stats[GUC_LOG_TYPE_STATE_CAPTURE].flush += tmp;
1409 	new_overflow = xe_guc_check_log_buf_overflow(&guc->log, GUC_LOG_TYPE_STATE_CAPTURE,
1410 						     full_count);
1411 
1412 	/* Now copy the actual logs. */
1413 	if (unlikely(new_overflow)) {
1414 		/* copy the whole buffer in case of overflow */
1415 		read_offset = 0;
1416 		write_offset = buffer_size;
1417 	} else if (unlikely((read_offset > buffer_size) ||
1418 			(write_offset > buffer_size))) {
1419 		xe_gt_err(guc_to_gt(guc),
1420 			  "Register capture buffer in invalid state: read = 0x%X, size = 0x%X!\n",
1421 			  read_offset, buffer_size);
1422 		/* copy whole buffer as offsets are unreliable */
1423 		read_offset = 0;
1424 		write_offset = buffer_size;
1425 	}
1426 
1427 	buf.size = buffer_size;
1428 	buf.rd = read_offset;
1429 	buf.wr = write_offset;
1430 	buf.data_offset = src_data_offset;
1431 
1432 	if (!xe_guc_read_stopped(guc)) {
1433 		do {
1434 			ret = guc_capture_extract_reglists(guc, &buf);
1435 			if (ret && ret != -ENODATA)
1436 				xe_gt_dbg(guc_to_gt(guc), "Capture extraction failed:%d\n", ret);
1437 		} while (ret >= 0);
1438 	}
1439 
1440 	/* Update the state of log buffer err-cap state */
1441 	xe_map_wr(guc_to_xe(guc), &guc->log.bo->vmap,
1442 		  log_buf_state_offset + offsetof(struct guc_log_buffer_state, read_ptr), u32,
1443 		  write_offset);
1444 
1445 	/*
1446 	 * Clear the flush_to_file from local first, the local was loaded by above
1447 	 * xe_map_memcpy_from, then write out the "updated local" through
1448 	 * xe_map_wr()
1449 	 */
1450 	log_buf_state_local.flags &= ~GUC_LOG_BUFFER_STATE_FLUSH_TO_FILE;
1451 	xe_map_wr(guc_to_xe(guc), &guc->log.bo->vmap,
1452 		  log_buf_state_offset + offsetof(struct guc_log_buffer_state, flags), u32,
1453 		  log_buf_state_local.flags);
1454 	__guc_capture_flushlog_complete(guc);
1455 }
1456 
1457 /*
1458  * xe_guc_capture_process - Process GuC register captured data
1459  * @guc: The GuC object
1460  *
1461  * When GuC captured data is ready, GuC will send message
1462  * XE_GUC_ACTION_STATE_CAPTURE_NOTIFICATION to host, this function will be
1463  * called to process the data comes with the message.
1464  *
1465  * Returns: None
1466  */
1467 void xe_guc_capture_process(struct xe_guc *guc)
1468 {
1469 	if (guc->capture)
1470 		__guc_capture_process_output(guc);
1471 }
1472 
1473 static struct __guc_capture_parsed_output *
1474 guc_capture_alloc_one_node(struct xe_guc *guc)
1475 {
1476 	struct drm_device *drm = guc_to_drm(guc);
1477 	struct __guc_capture_parsed_output *new;
1478 	int i;
1479 
1480 	new = drmm_kzalloc(drm, sizeof(*new), GFP_KERNEL);
1481 	if (!new)
1482 		return NULL;
1483 
1484 	for (i = 0; i < GUC_STATE_CAPTURE_TYPE_MAX; ++i) {
1485 		new->reginfo[i].regs = drmm_kzalloc(drm, guc->capture->max_mmio_per_node *
1486 						    sizeof(struct guc_mmio_reg), GFP_KERNEL);
1487 		if (!new->reginfo[i].regs) {
1488 			while (i)
1489 				drmm_kfree(drm, new->reginfo[--i].regs);
1490 			drmm_kfree(drm, new);
1491 			return NULL;
1492 		}
1493 	}
1494 	guc_capture_init_node(guc, new);
1495 
1496 	return new;
1497 }
1498 
1499 static void
1500 __guc_capture_create_prealloc_nodes(struct xe_guc *guc)
1501 {
1502 	struct __guc_capture_parsed_output *node = NULL;
1503 	int i;
1504 
1505 	for (i = 0; i < PREALLOC_NODES_MAX_COUNT; ++i) {
1506 		node = guc_capture_alloc_one_node(guc);
1507 		if (!node) {
1508 			xe_gt_warn(guc_to_gt(guc), "Register capture pre-alloc-cache failure\n");
1509 			/* dont free the priors, use what we got and cleanup at shutdown */
1510 			return;
1511 		}
1512 		guc_capture_add_node_to_cachelist(guc->capture, node);
1513 	}
1514 }
1515 
1516 static int
1517 guc_get_max_reglist_count(struct xe_guc *guc)
1518 {
1519 	int i, j, k, tmp, maxregcount = 0;
1520 
1521 	for (i = 0; i < GUC_CAPTURE_LIST_INDEX_MAX; ++i) {
1522 		for (j = 0; j < GUC_STATE_CAPTURE_TYPE_MAX; ++j) {
1523 			for (k = 0; k < GUC_CAPTURE_LIST_CLASS_MAX; ++k) {
1524 				const struct __guc_mmio_reg_descr_group *match;
1525 
1526 				if (j == GUC_STATE_CAPTURE_TYPE_GLOBAL && k > 0)
1527 					continue;
1528 
1529 				tmp = 0;
1530 				match = guc_capture_get_one_list(guc->capture->reglists, i, j, k);
1531 				if (match)
1532 					tmp = match->num_regs;
1533 
1534 				match = guc_capture_get_one_list(guc->capture->extlists, i, j, k);
1535 				if (match)
1536 					tmp += match->num_regs;
1537 
1538 				if (tmp > maxregcount)
1539 					maxregcount = tmp;
1540 			}
1541 		}
1542 	}
1543 	if (!maxregcount)
1544 		maxregcount = PREALLOC_NODES_DEFAULT_NUMREGS;
1545 
1546 	return maxregcount;
1547 }
1548 
1549 static void
1550 guc_capture_create_prealloc_nodes(struct xe_guc *guc)
1551 {
1552 	/* skip if we've already done the pre-alloc */
1553 	if (guc->capture->max_mmio_per_node)
1554 		return;
1555 
1556 	guc->capture->max_mmio_per_node = guc_get_max_reglist_count(guc);
1557 	__guc_capture_create_prealloc_nodes(guc);
1558 }
1559 
1560 static void
1561 read_reg_to_node(struct xe_hw_engine *hwe, const struct __guc_mmio_reg_descr_group *list,
1562 		 struct guc_mmio_reg *regs)
1563 {
1564 	int i;
1565 
1566 	if (!list || !list->list || list->num_regs == 0)
1567 		return;
1568 
1569 	if (!regs)
1570 		return;
1571 
1572 	for (i = 0; i < list->num_regs; i++) {
1573 		struct __guc_mmio_reg_descr desc = list->list[i];
1574 		u32 value;
1575 
1576 		if (list->type == GUC_STATE_CAPTURE_TYPE_ENGINE_INSTANCE) {
1577 			value = xe_hw_engine_mmio_read32(hwe, desc.reg);
1578 		} else {
1579 			if (list->type == GUC_STATE_CAPTURE_TYPE_ENGINE_CLASS &&
1580 			    FIELD_GET(GUC_REGSET_STEERING_NEEDED, desc.flags)) {
1581 				int group, instance;
1582 
1583 				group = FIELD_GET(GUC_REGSET_STEERING_GROUP, desc.flags);
1584 				instance = FIELD_GET(GUC_REGSET_STEERING_INSTANCE, desc.flags);
1585 				value = xe_gt_mcr_unicast_read(hwe->gt, XE_REG_MCR(desc.reg.addr),
1586 							       group, instance);
1587 			} else {
1588 				value = xe_mmio_read32(&hwe->gt->mmio, desc.reg);
1589 			}
1590 		}
1591 
1592 		regs[i].value = value;
1593 		regs[i].offset = desc.reg.addr;
1594 		regs[i].flags = desc.flags;
1595 		regs[i].mask = desc.mask;
1596 	}
1597 }
1598 
1599 /**
1600  * xe_engine_manual_capture - Take a manual engine snapshot from engine.
1601  * @hwe: Xe HW Engine.
1602  * @snapshot: The engine snapshot
1603  *
1604  * Take engine snapshot from engine read.
1605  *
1606  * Returns: None
1607  */
1608 void
1609 xe_engine_manual_capture(struct xe_hw_engine *hwe, struct xe_hw_engine_snapshot *snapshot)
1610 {
1611 	struct xe_gt *gt = hwe->gt;
1612 	struct xe_device *xe = gt_to_xe(gt);
1613 	struct xe_guc *guc = &gt->uc.guc;
1614 	struct xe_devcoredump *devcoredump = &xe->devcoredump;
1615 	enum guc_capture_list_class_type capture_class;
1616 	const struct __guc_mmio_reg_descr_group *list;
1617 	struct __guc_capture_parsed_output *new;
1618 	enum guc_state_capture_type type;
1619 	u16 guc_id = 0;
1620 	u32 lrca = 0;
1621 
1622 	if (IS_SRIOV_VF(xe))
1623 		return;
1624 
1625 	new = guc_capture_get_prealloc_node(guc);
1626 	if (!new)
1627 		return;
1628 
1629 	capture_class = xe_engine_class_to_guc_capture_class(hwe->class);
1630 	for (type = GUC_STATE_CAPTURE_TYPE_GLOBAL; type < GUC_STATE_CAPTURE_TYPE_MAX; type++) {
1631 		struct gcap_reg_list_info *reginfo = &new->reginfo[type];
1632 		/*
1633 		 * regsinfo->regs is allocated based on guc->capture->max_mmio_per_node
1634 		 * which is based on the descriptor list driving the population so
1635 		 * should not overflow
1636 		 */
1637 
1638 		/* Get register list for the type/class */
1639 		list = xe_guc_capture_get_reg_desc_list(gt, GUC_CAPTURE_LIST_INDEX_PF, type,
1640 							capture_class, false);
1641 		if (!list) {
1642 			xe_gt_dbg(gt, "Empty GuC capture register descriptor for %s",
1643 				  hwe->name);
1644 			continue;
1645 		}
1646 
1647 		read_reg_to_node(hwe, list, reginfo->regs);
1648 		reginfo->num_regs = list->num_regs;
1649 
1650 		/* Capture steering registers for rcs/ccs */
1651 		if (capture_class == GUC_CAPTURE_LIST_CLASS_RENDER_COMPUTE) {
1652 			list = xe_guc_capture_get_reg_desc_list(gt, GUC_CAPTURE_LIST_INDEX_PF,
1653 								type, capture_class, true);
1654 			if (list) {
1655 				read_reg_to_node(hwe, list, &reginfo->regs[reginfo->num_regs]);
1656 				reginfo->num_regs += list->num_regs;
1657 			}
1658 		}
1659 	}
1660 
1661 	if (devcoredump && devcoredump->captured) {
1662 		struct xe_guc_submit_exec_queue_snapshot *ge = devcoredump->snapshot.ge;
1663 
1664 		if (ge) {
1665 			guc_id = ge->guc.id;
1666 			if (ge->lrc[0])
1667 				lrca = ge->lrc[0]->context_desc;
1668 		}
1669 	}
1670 
1671 	new->eng_class = xe_engine_class_to_guc_class(hwe->class);
1672 	new->eng_inst = hwe->instance;
1673 	new->guc_id = guc_id;
1674 	new->lrca = lrca;
1675 	new->is_partial = 0;
1676 	new->locked = 1;
1677 	new->source = XE_ENGINE_CAPTURE_SOURCE_MANUAL;
1678 
1679 	guc_capture_add_node_to_outlist(guc->capture, new);
1680 	devcoredump->snapshot.matched_node = new;
1681 }
1682 
1683 static struct guc_mmio_reg *
1684 guc_capture_find_reg(struct gcap_reg_list_info *reginfo, u32 addr, u32 flags)
1685 {
1686 	int i;
1687 
1688 	if (reginfo && reginfo->num_regs > 0) {
1689 		struct guc_mmio_reg *regs = reginfo->regs;
1690 
1691 		if (regs)
1692 			for (i = 0; i < reginfo->num_regs; i++)
1693 				if (regs[i].offset == addr && regs[i].flags == flags)
1694 					return &regs[i];
1695 	}
1696 
1697 	return NULL;
1698 }
1699 
1700 static void
1701 snapshot_print_by_list_order(struct xe_hw_engine_snapshot *snapshot, struct drm_printer *p,
1702 			     u32 type, const struct __guc_mmio_reg_descr_group *list)
1703 {
1704 	struct xe_gt *gt = snapshot->hwe->gt;
1705 	struct xe_device *xe = gt_to_xe(gt);
1706 	struct xe_devcoredump *devcoredump = &xe->devcoredump;
1707 	struct xe_devcoredump_snapshot *devcore_snapshot = &devcoredump->snapshot;
1708 	struct gcap_reg_list_info *reginfo = NULL;
1709 	u32 i, last_value = 0;
1710 	bool low32_ready = false;
1711 
1712 	if (!list || !list->list || list->num_regs == 0)
1713 		return;
1714 	XE_WARN_ON(!devcore_snapshot->matched_node);
1715 
1716 	reginfo = &devcore_snapshot->matched_node->reginfo[type];
1717 
1718 	/*
1719 	 * loop through descriptor first and find the register in the node
1720 	 * this is more scalable for developer maintenance as it will ensure
1721 	 * the printout matched the ordering of the static descriptor
1722 	 * table-of-lists
1723 	 */
1724 	for (i = 0; i < list->num_regs; i++) {
1725 		const struct __guc_mmio_reg_descr *reg_desc = &list->list[i];
1726 		struct guc_mmio_reg *reg;
1727 		u32 value;
1728 
1729 		reg = guc_capture_find_reg(reginfo, reg_desc->reg.addr, reg_desc->flags);
1730 		if (!reg)
1731 			continue;
1732 
1733 		value = reg->value;
1734 		switch (reg_desc->data_type) {
1735 		case REG_64BIT_LOW_DW:
1736 			last_value = value;
1737 
1738 			/*
1739 			 * A 64 bit register define requires 2 consecutive
1740 			 * entries in register list, with low dword first
1741 			 * and hi dword the second, like:
1742 			 *  { XXX_REG_LO(0), REG_64BIT_LOW_DW, 0, 0, NULL},
1743 			 *  { XXX_REG_HI(0), REG_64BIT_HI_DW,  0, 0, "XXX_REG"},
1744 			 *
1745 			 * Incorrect order will trigger XE_WARN.
1746 			 *
1747 			 * Possible double low here, for example:
1748 			 *  { XXX_REG_LO(0), REG_64BIT_LOW_DW, 0, 0, NULL},
1749 			 *  { XXX_REG_LO(0), REG_64BIT_LOW_DW, 0, 0, NULL},
1750 			 */
1751 			XE_WARN_ON(low32_ready);
1752 			low32_ready = true;
1753 			/* Low 32 bit dword saved, continue for high 32 bit */
1754 			break;
1755 
1756 		case REG_64BIT_HI_DW: {
1757 			u64 value_qw = ((u64)value << 32) | last_value;
1758 
1759 			/*
1760 			 * Incorrect 64bit register order. Possible missing low.
1761 			 * for example:
1762 			 *  { XXX_REG(0), REG_32BIT, 0, 0, NULL},
1763 			 *  { XXX_REG_HI(0), REG_64BIT_HI_DW, 0, 0, NULL},
1764 			 */
1765 			XE_WARN_ON(!low32_ready);
1766 			low32_ready = false;
1767 
1768 			drm_printf(p, "\t%s: 0x%016llx\n", reg_desc->regname, value_qw);
1769 			break;
1770 		}
1771 
1772 		case REG_32BIT:
1773 			/*
1774 			 * Incorrect 64bit register order. Possible missing high.
1775 			 * for example:
1776 			 *  { XXX_REG_LO(0), REG_64BIT_LOW_DW, 0, 0, NULL},
1777 			 *  { XXX_REG(0), REG_32BIT, 0, 0, "XXX_REG"},
1778 			 */
1779 			XE_WARN_ON(low32_ready);
1780 
1781 			if (FIELD_GET(GUC_REGSET_STEERING_NEEDED, reg_desc->flags))
1782 				drm_printf(p, "\t%s[%u]: 0x%08x\n", reg_desc->regname,
1783 					   reg_desc->dss_id, value);
1784 			else
1785 				drm_printf(p, "\t%s: 0x%08x\n", reg_desc->regname, value);
1786 
1787 			break;
1788 		}
1789 	}
1790 
1791 	/*
1792 	 * Incorrect 64bit register order. Possible missing high.
1793 	 * for example:
1794 	 *  { XXX_REG_LO(0), REG_64BIT_LOW_DW, 0, 0, NULL},
1795 	 *  } // <- Register list end
1796 	 */
1797 	XE_WARN_ON(low32_ready);
1798 }
1799 
1800 /**
1801  * xe_engine_snapshot_print - Print out a given Xe HW Engine snapshot.
1802  * @snapshot: Xe HW Engine snapshot object.
1803  * @p: drm_printer where it will be printed out.
1804  *
1805  * This function prints out a given Xe HW Engine snapshot object.
1806  */
1807 void xe_engine_snapshot_print(struct xe_hw_engine_snapshot *snapshot, struct drm_printer *p)
1808 {
1809 	const char *grptype[GUC_STATE_CAPTURE_GROUP_TYPE_MAX] = {
1810 		"full-capture",
1811 		"partial-capture"
1812 	};
1813 	int type;
1814 	const struct __guc_mmio_reg_descr_group *list;
1815 	enum guc_capture_list_class_type capture_class;
1816 
1817 	struct xe_gt *gt;
1818 	struct xe_device *xe;
1819 	struct xe_devcoredump *devcoredump;
1820 	struct xe_devcoredump_snapshot *devcore_snapshot;
1821 
1822 	if (!snapshot)
1823 		return;
1824 
1825 	gt = snapshot->hwe->gt;
1826 	xe = gt_to_xe(gt);
1827 	devcoredump = &xe->devcoredump;
1828 	devcore_snapshot = &devcoredump->snapshot;
1829 
1830 	if (!devcore_snapshot->matched_node)
1831 		return;
1832 
1833 	xe_gt_assert(gt, snapshot->hwe);
1834 
1835 	capture_class = xe_engine_class_to_guc_capture_class(snapshot->hwe->class);
1836 
1837 	drm_printf(p, "%s (physical), logical instance=%d\n",
1838 		   snapshot->name ? snapshot->name : "",
1839 		   snapshot->logical_instance);
1840 	drm_printf(p, "\tCapture_source: %s\n",
1841 		   devcore_snapshot->matched_node->source == XE_ENGINE_CAPTURE_SOURCE_GUC ?
1842 		   "GuC" : "Manual");
1843 	drm_printf(p, "\tCoverage: %s\n", grptype[devcore_snapshot->matched_node->is_partial]);
1844 	drm_printf(p, "\tForcewake: domain 0x%x, ref %d\n",
1845 		   snapshot->forcewake.domain, snapshot->forcewake.ref);
1846 	drm_printf(p, "\tReserved: %s\n",
1847 		   str_yes_no(snapshot->kernel_reserved));
1848 
1849 	for (type = GUC_STATE_CAPTURE_TYPE_GLOBAL; type < GUC_STATE_CAPTURE_TYPE_MAX; type++) {
1850 		list = xe_guc_capture_get_reg_desc_list(gt, GUC_CAPTURE_LIST_INDEX_PF, type,
1851 							capture_class, false);
1852 		snapshot_print_by_list_order(snapshot, p, type, list);
1853 	}
1854 
1855 	if (capture_class == GUC_CAPTURE_LIST_CLASS_RENDER_COMPUTE) {
1856 		list = xe_guc_capture_get_reg_desc_list(gt, GUC_CAPTURE_LIST_INDEX_PF,
1857 							GUC_STATE_CAPTURE_TYPE_ENGINE_CLASS,
1858 							capture_class, true);
1859 		snapshot_print_by_list_order(snapshot, p, GUC_STATE_CAPTURE_TYPE_ENGINE_CLASS,
1860 					     list);
1861 	}
1862 
1863 	drm_puts(p, "\n");
1864 }
1865 
1866 /**
1867  * xe_guc_capture_get_matching_and_lock - Matching GuC capture for the queue.
1868  * @q: The exec queue object
1869  *
1870  * Search within the capture outlist for the queue, could be used for check if
1871  * GuC capture is ready for the queue.
1872  * If found, the locked boolean of the node will be flagged.
1873  *
1874  * Returns: found guc-capture node ptr else NULL
1875  */
1876 struct __guc_capture_parsed_output *
1877 xe_guc_capture_get_matching_and_lock(struct xe_exec_queue *q)
1878 {
1879 	struct xe_hw_engine *hwe;
1880 	enum xe_hw_engine_id id;
1881 	struct xe_device *xe;
1882 	u16 guc_class = GUC_LAST_ENGINE_CLASS + 1;
1883 	struct xe_devcoredump_snapshot *ss;
1884 
1885 	if (!q || !q->gt)
1886 		return NULL;
1887 
1888 	xe = gt_to_xe(q->gt);
1889 
1890 	if (xe->wedged.mode == XE_WEDGED_MODE_UPON_ANY_HANG_NO_RESET)
1891 		return NULL;
1892 
1893 	if (!xe_device_uc_enabled(xe))
1894 		return NULL;
1895 
1896 	if (IS_SRIOV_VF(xe))
1897 		return NULL;
1898 
1899 	ss = &xe->devcoredump.snapshot;
1900 	if (ss->matched_node && ss->matched_node->source == XE_ENGINE_CAPTURE_SOURCE_GUC)
1901 		return ss->matched_node;
1902 
1903 	/* Find hwe for the queue */
1904 	for_each_hw_engine(hwe, q->gt, id) {
1905 		if (hwe != q->hwe)
1906 			continue;
1907 		guc_class = xe_engine_class_to_guc_class(hwe->class);
1908 		break;
1909 	}
1910 
1911 	if (guc_class <= GUC_LAST_ENGINE_CLASS) {
1912 		struct __guc_capture_parsed_output *n, *ntmp;
1913 		struct xe_guc *guc =  &q->gt->uc.guc;
1914 		u16 guc_id = q->guc->id;
1915 		u32 lrca = xe_lrc_ggtt_addr(q->lrc[0]);
1916 
1917 		/*
1918 		 * Look for a matching GuC reported error capture node from
1919 		 * the internal output link-list based on engine, guc id and
1920 		 * lrca info.
1921 		 */
1922 		list_for_each_entry_safe(n, ntmp, &guc->capture->outlist, link) {
1923 			if (n->eng_class == guc_class && n->eng_inst == hwe->instance &&
1924 			    n->guc_id == guc_id && n->lrca == lrca &&
1925 			    n->source == XE_ENGINE_CAPTURE_SOURCE_GUC) {
1926 				n->locked = 1;
1927 				return n;
1928 			}
1929 		}
1930 	}
1931 	return NULL;
1932 }
1933 
1934 /**
1935  * xe_engine_snapshot_capture_for_queue - Take snapshot of associated engine
1936  * @q: The exec queue object
1937  *
1938  * Take snapshot of associated HW Engine
1939  *
1940  * Returns: None.
1941  */
1942 void
1943 xe_engine_snapshot_capture_for_queue(struct xe_exec_queue *q)
1944 {
1945 	struct xe_device *xe = gt_to_xe(q->gt);
1946 	struct xe_devcoredump *coredump = &xe->devcoredump;
1947 	struct xe_hw_engine *hwe;
1948 	enum xe_hw_engine_id id;
1949 	u32 adj_logical_mask = q->logical_mask;
1950 
1951 	if (IS_SRIOV_VF(xe))
1952 		return;
1953 
1954 	for_each_hw_engine(hwe, q->gt, id) {
1955 		if (hwe->class != q->hwe->class ||
1956 		    !(BIT(hwe->logical_instance) & adj_logical_mask)) {
1957 			coredump->snapshot.hwe[id] = NULL;
1958 			continue;
1959 		}
1960 
1961 		if (!coredump->snapshot.hwe[id]) {
1962 			coredump->snapshot.hwe[id] =
1963 				xe_hw_engine_snapshot_capture(hwe, q);
1964 		} else {
1965 			struct __guc_capture_parsed_output *new;
1966 
1967 			new = xe_guc_capture_get_matching_and_lock(q);
1968 			if (new) {
1969 				struct xe_guc *guc =  &q->gt->uc.guc;
1970 
1971 				/*
1972 				 * If we are in here, it means we found a fresh
1973 				 * GuC-err-capture node for this engine after
1974 				 * previously failing to find a match in the
1975 				 * early part of guc_exec_queue_timedout_job.
1976 				 * Thus we must free the manually captured node
1977 				 */
1978 				guc_capture_free_outlist_node(guc->capture,
1979 							      coredump->snapshot.matched_node);
1980 				coredump->snapshot.matched_node = new;
1981 			}
1982 		}
1983 
1984 		break;
1985 	}
1986 }
1987 
1988 /*
1989  * xe_guc_capture_put_matched_nodes - Cleanup matched nodes
1990  * @guc: The GuC object
1991  *
1992  * Free matched node and all nodes with the equal guc_id from
1993  * GuC captured outlist
1994  */
1995 void xe_guc_capture_put_matched_nodes(struct xe_guc *guc)
1996 {
1997 	struct xe_device *xe = guc_to_xe(guc);
1998 	struct xe_devcoredump *devcoredump = &xe->devcoredump;
1999 	struct __guc_capture_parsed_output *n = devcoredump->snapshot.matched_node;
2000 
2001 	if (n) {
2002 		guc_capture_remove_stale_matches_from_list(guc->capture, n);
2003 		guc_capture_free_outlist_node(guc->capture, n);
2004 		devcoredump->snapshot.matched_node = NULL;
2005 	}
2006 }
2007 
2008 /*
2009  * xe_guc_capture_steered_list_init - Init steering register list
2010  * @guc: The GuC object
2011  *
2012  * Init steering register list for GuC register capture, create pre-alloc node
2013  */
2014 void xe_guc_capture_steered_list_init(struct xe_guc *guc)
2015 {
2016 	/*
2017 	 * For certain engine classes, there are slice and subslice
2018 	 * level registers requiring steering. We allocate and populate
2019 	 * these based on hw config and add it as an extension list at
2020 	 * the end of the pre-populated render list.
2021 	 */
2022 	guc_capture_alloc_steered_lists(guc);
2023 	check_guc_capture_size(guc);
2024 	guc_capture_create_prealloc_nodes(guc);
2025 }
2026 
2027 /*
2028  * xe_guc_capture_init - Init for GuC register capture
2029  * @guc: The GuC object
2030  *
2031  * Init for GuC register capture, alloc memory for capture data structure.
2032  *
2033  * Returns: 0 if success.
2034  *	    -ENOMEM if out of memory
2035  */
2036 int xe_guc_capture_init(struct xe_guc *guc)
2037 {
2038 	guc->capture = drmm_kzalloc(guc_to_drm(guc), sizeof(*guc->capture), GFP_KERNEL);
2039 	if (!guc->capture)
2040 		return -ENOMEM;
2041 
2042 	guc->capture->reglists = guc_capture_get_device_reglist(guc_to_xe(guc));
2043 
2044 	INIT_LIST_HEAD(&guc->capture->outlist);
2045 	INIT_LIST_HEAD(&guc->capture->cachelist);
2046 
2047 	return 0;
2048 }
2049