1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright © 2021-2022 Intel Corporation
4  */
5 
6 #include <linux/types.h>
7 
8 #include <drm/drm_print.h>
9 
10 #include "gt/intel_engine_regs.h"
11 #include "gt/intel_gt.h"
12 #include "gt/intel_gt_mcr.h"
13 #include "gt/intel_gt_regs.h"
14 #include "gt/intel_lrc.h"
15 #include "guc_capture_fwif.h"
16 #include "intel_guc_capture.h"
17 #include "intel_guc_fwif.h"
18 #include "i915_drv.h"
19 #include "i915_gpu_error.h"
20 #include "i915_irq.h"
21 #include "i915_memcpy.h"
22 #include "i915_reg.h"
23 
24 /*
25  * Define all device tables of GuC error capture register lists
26  * NOTE: For engine-registers, GuC only needs the register offsets
27  *       from the engine-mmio-base
28  */
29 #define COMMON_BASE_GLOBAL \
30 	{ FORCEWAKE_MT,             0,      0, "FORCEWAKE" }
31 
32 #define COMMON_GEN9BASE_GLOBAL \
33 	{ GEN8_FAULT_TLB_DATA0,     0,      0, "GEN8_FAULT_TLB_DATA0" }, \
34 	{ GEN8_FAULT_TLB_DATA1,     0,      0, "GEN8_FAULT_TLB_DATA1" }, \
35 	{ ERROR_GEN6,               0,      0, "ERROR_GEN6" }, \
36 	{ DONE_REG,                 0,      0, "DONE_REG" }, \
37 	{ HSW_GTT_CACHE_EN,         0,      0, "HSW_GTT_CACHE_EN" }
38 
39 #define COMMON_GEN12BASE_GLOBAL \
40 	{ GEN12_FAULT_TLB_DATA0,    0,      0, "GEN12_FAULT_TLB_DATA0" }, \
41 	{ GEN12_FAULT_TLB_DATA1,    0,      0, "GEN12_FAULT_TLB_DATA1" }, \
42 	{ GEN12_AUX_ERR_DBG,        0,      0, "AUX_ERR_DBG" }, \
43 	{ GEN12_GAM_DONE,           0,      0, "GAM_DONE" }, \
44 	{ GEN12_RING_FAULT_REG,     0,      0, "FAULT_REG" }
45 
46 #define COMMON_BASE_ENGINE_INSTANCE \
47 	{ RING_PSMI_CTL(0),         0,      0, "RC PSMI" }, \
48 	{ RING_ESR(0),              0,      0, "ESR" }, \
49 	{ RING_DMA_FADD(0),         0,      0, "RING_DMA_FADD_LDW" }, \
50 	{ RING_DMA_FADD_UDW(0),     0,      0, "RING_DMA_FADD_UDW" }, \
51 	{ RING_IPEIR(0),            0,      0, "IPEIR" }, \
52 	{ RING_IPEHR(0),            0,      0, "IPEHR" }, \
53 	{ RING_INSTPS(0),           0,      0, "INSTPS" }, \
54 	{ RING_BBADDR(0),           0,      0, "RING_BBADDR_LOW32" }, \
55 	{ RING_BBADDR_UDW(0),       0,      0, "RING_BBADDR_UP32" }, \
56 	{ RING_BBSTATE(0),          0,      0, "BB_STATE" }, \
57 	{ CCID(0),                  0,      0, "CCID" }, \
58 	{ RING_ACTHD(0),            0,      0, "ACTHD_LDW" }, \
59 	{ RING_ACTHD_UDW(0),        0,      0, "ACTHD_UDW" }, \
60 	{ RING_INSTPM(0),           0,      0, "INSTPM" }, \
61 	{ RING_INSTDONE(0),         0,      0, "INSTDONE" }, \
62 	{ RING_NOPID(0),            0,      0, "RING_NOPID" }, \
63 	{ RING_START(0),            0,      0, "START" }, \
64 	{ RING_HEAD(0),             0,      0, "HEAD" }, \
65 	{ RING_TAIL(0),             0,      0, "TAIL" }, \
66 	{ RING_CTL(0),              0,      0, "CTL" }, \
67 	{ RING_MI_MODE(0),          0,      0, "MODE" }, \
68 	{ RING_CONTEXT_CONTROL(0),  0,      0, "RING_CONTEXT_CONTROL" }, \
69 	{ RING_HWS_PGA(0),          0,      0, "HWS" }, \
70 	{ RING_MODE_GEN7(0),        0,      0, "GFX_MODE" }, \
71 	{ GEN8_RING_PDP_LDW(0, 0),  0,      0, "PDP0_LDW" }, \
72 	{ GEN8_RING_PDP_UDW(0, 0),  0,      0, "PDP0_UDW" }, \
73 	{ GEN8_RING_PDP_LDW(0, 1),  0,      0, "PDP1_LDW" }, \
74 	{ GEN8_RING_PDP_UDW(0, 1),  0,      0, "PDP1_UDW" }, \
75 	{ GEN8_RING_PDP_LDW(0, 2),  0,      0, "PDP2_LDW" }, \
76 	{ GEN8_RING_PDP_UDW(0, 2),  0,      0, "PDP2_UDW" }, \
77 	{ GEN8_RING_PDP_LDW(0, 3),  0,      0, "PDP3_LDW" }, \
78 	{ GEN8_RING_PDP_UDW(0, 3),  0,      0, "PDP3_UDW" }
79 
80 #define COMMON_BASE_HAS_EU \
81 	{ EIR,                      0,      0, "EIR" }
82 
83 #define COMMON_BASE_RENDER \
84 	{ GEN7_SC_INSTDONE,         0,      0, "GEN7_SC_INSTDONE" }
85 
86 #define COMMON_GEN12BASE_RENDER \
87 	{ GEN12_SC_INSTDONE_EXTRA,  0,      0, "GEN12_SC_INSTDONE_EXTRA" }, \
88 	{ GEN12_SC_INSTDONE_EXTRA2, 0,      0, "GEN12_SC_INSTDONE_EXTRA2" }
89 
90 #define COMMON_GEN12BASE_VEC \
91 	{ GEN12_SFC_DONE(0),        0,      0, "SFC_DONE[0]" }, \
92 	{ GEN12_SFC_DONE(1),        0,      0, "SFC_DONE[1]" }, \
93 	{ GEN12_SFC_DONE(2),        0,      0, "SFC_DONE[2]" }, \
94 	{ GEN12_SFC_DONE(3),        0,      0, "SFC_DONE[3]" }
95 
96 /* XE_LPD - Global */
97 static const struct __guc_mmio_reg_descr xe_lpd_global_regs[] = {
98 	COMMON_BASE_GLOBAL,
99 	COMMON_GEN9BASE_GLOBAL,
100 	COMMON_GEN12BASE_GLOBAL,
101 };
102 
103 /* XE_LPD - Render / Compute Per-Class */
104 static const struct __guc_mmio_reg_descr xe_lpd_rc_class_regs[] = {
105 	COMMON_BASE_HAS_EU,
106 	COMMON_BASE_RENDER,
107 	COMMON_GEN12BASE_RENDER,
108 };
109 
110 /* GEN9/XE_LPD - Render / Compute Per-Engine-Instance */
111 static const struct __guc_mmio_reg_descr xe_lpd_rc_inst_regs[] = {
112 	COMMON_BASE_ENGINE_INSTANCE,
113 };
114 
115 /* GEN9/XE_LPD - Media Decode/Encode Per-Engine-Instance */
116 static const struct __guc_mmio_reg_descr xe_lpd_vd_inst_regs[] = {
117 	COMMON_BASE_ENGINE_INSTANCE,
118 };
119 
120 /* XE_LPD - Video Enhancement Per-Class */
121 static const struct __guc_mmio_reg_descr xe_lpd_vec_class_regs[] = {
122 	COMMON_GEN12BASE_VEC,
123 };
124 
125 /* GEN9/XE_LPD - Video Enhancement Per-Engine-Instance */
126 static const struct __guc_mmio_reg_descr xe_lpd_vec_inst_regs[] = {
127 	COMMON_BASE_ENGINE_INSTANCE,
128 };
129 
130 /* GEN9/XE_LPD - Blitter Per-Engine-Instance */
131 static const struct __guc_mmio_reg_descr xe_lpd_blt_inst_regs[] = {
132 	COMMON_BASE_ENGINE_INSTANCE,
133 };
134 
135 /* GEN9 - Global */
136 static const struct __guc_mmio_reg_descr default_global_regs[] = {
137 	COMMON_BASE_GLOBAL,
138 	COMMON_GEN9BASE_GLOBAL,
139 };
140 
141 static const struct __guc_mmio_reg_descr default_rc_class_regs[] = {
142 	COMMON_BASE_HAS_EU,
143 	COMMON_BASE_RENDER,
144 };
145 
146 /*
147  * Empty lists:
148  * GEN9/XE_LPD - Blitter Per-Class
149  * GEN9/XE_LPD - Media Decode/Encode Per-Class
150  * GEN9 - VEC Class
151  */
152 static const struct __guc_mmio_reg_descr empty_regs_list[] = {
153 };
154 
155 #define TO_GCAP_DEF_OWNER(x) (GUC_CAPTURE_LIST_INDEX_##x)
156 #define TO_GCAP_DEF_TYPE(x) (GUC_CAPTURE_LIST_TYPE_##x)
157 #define MAKE_REGLIST(regslist, regsowner, regstype, class) \
158 	{ \
159 		regslist, \
160 		ARRAY_SIZE(regslist), \
161 		TO_GCAP_DEF_OWNER(regsowner), \
162 		TO_GCAP_DEF_TYPE(regstype), \
163 		class, \
164 		NULL, \
165 	}
166 
167 /* List of lists */
168 static struct __guc_mmio_reg_descr_group default_lists[] = {
169 	MAKE_REGLIST(default_global_regs, PF, GLOBAL, 0),
170 	MAKE_REGLIST(default_rc_class_regs, PF, ENGINE_CLASS, GUC_RENDER_CLASS),
171 	MAKE_REGLIST(xe_lpd_rc_inst_regs, PF, ENGINE_INSTANCE, GUC_RENDER_CLASS),
172 	MAKE_REGLIST(empty_regs_list, PF, ENGINE_CLASS, GUC_VIDEO_CLASS),
173 	MAKE_REGLIST(xe_lpd_vd_inst_regs, PF, ENGINE_INSTANCE, GUC_VIDEO_CLASS),
174 	MAKE_REGLIST(empty_regs_list, PF, ENGINE_CLASS, GUC_VIDEOENHANCE_CLASS),
175 	MAKE_REGLIST(xe_lpd_vec_inst_regs, PF, ENGINE_INSTANCE, GUC_VIDEOENHANCE_CLASS),
176 	MAKE_REGLIST(empty_regs_list, PF, ENGINE_CLASS, GUC_BLITTER_CLASS),
177 	MAKE_REGLIST(xe_lpd_blt_inst_regs, PF, ENGINE_INSTANCE, GUC_BLITTER_CLASS),
178 	{}
179 };
180 
181 static const struct __guc_mmio_reg_descr_group xe_lpd_lists[] = {
182 	MAKE_REGLIST(xe_lpd_global_regs, PF, GLOBAL, 0),
183 	MAKE_REGLIST(xe_lpd_rc_class_regs, PF, ENGINE_CLASS, GUC_RENDER_CLASS),
184 	MAKE_REGLIST(xe_lpd_rc_inst_regs, PF, ENGINE_INSTANCE, GUC_RENDER_CLASS),
185 	MAKE_REGLIST(empty_regs_list, PF, ENGINE_CLASS, GUC_VIDEO_CLASS),
186 	MAKE_REGLIST(xe_lpd_vd_inst_regs, PF, ENGINE_INSTANCE, GUC_VIDEO_CLASS),
187 	MAKE_REGLIST(xe_lpd_vec_class_regs, PF, ENGINE_CLASS, GUC_VIDEOENHANCE_CLASS),
188 	MAKE_REGLIST(xe_lpd_vec_inst_regs, PF, ENGINE_INSTANCE, GUC_VIDEOENHANCE_CLASS),
189 	MAKE_REGLIST(empty_regs_list, PF, ENGINE_CLASS, GUC_BLITTER_CLASS),
190 	MAKE_REGLIST(xe_lpd_blt_inst_regs, PF, ENGINE_INSTANCE, GUC_BLITTER_CLASS),
191 	{}
192 };
193 
194 static const struct __guc_mmio_reg_descr_group *
195 guc_capture_get_one_list(const struct __guc_mmio_reg_descr_group *reglists,
196 			 u32 owner, u32 type, u32 id)
197 {
198 	int i;
199 
200 	if (!reglists)
201 		return NULL;
202 
203 	for (i = 0; reglists[i].list; ++i) {
204 		if (reglists[i].owner == owner && reglists[i].type == type &&
205 		    (reglists[i].engine == id || reglists[i].type == GUC_CAPTURE_LIST_TYPE_GLOBAL))
206 			return &reglists[i];
207 	}
208 
209 	return NULL;
210 }
211 
212 static struct __guc_mmio_reg_descr_group *
213 guc_capture_get_one_ext_list(struct __guc_mmio_reg_descr_group *reglists,
214 			     u32 owner, u32 type, u32 id)
215 {
216 	int i;
217 
218 	if (!reglists)
219 		return NULL;
220 
221 	for (i = 0; reglists[i].extlist; ++i) {
222 		if (reglists[i].owner == owner && reglists[i].type == type &&
223 		    (reglists[i].engine == id || reglists[i].type == GUC_CAPTURE_LIST_TYPE_GLOBAL))
224 			return &reglists[i];
225 	}
226 
227 	return NULL;
228 }
229 
230 static void guc_capture_free_extlists(struct __guc_mmio_reg_descr_group *reglists)
231 {
232 	int i = 0;
233 
234 	if (!reglists)
235 		return;
236 
237 	while (reglists[i].extlist)
238 		kfree(reglists[i++].extlist);
239 }
240 
241 struct __ext_steer_reg {
242 	const char *name;
243 	i915_reg_t reg;
244 };
245 
246 static const struct __ext_steer_reg xe_extregs[] = {
247 	{"GEN7_SAMPLER_INSTDONE", GEN7_SAMPLER_INSTDONE},
248 	{"GEN7_ROW_INSTDONE", GEN7_ROW_INSTDONE}
249 };
250 
251 static void __fill_ext_reg(struct __guc_mmio_reg_descr *ext,
252 			   const struct __ext_steer_reg *extlist,
253 			   int slice_id, int subslice_id)
254 {
255 	ext->reg = extlist->reg;
256 	ext->flags = FIELD_PREP(GUC_REGSET_STEERING_GROUP, slice_id);
257 	ext->flags |= FIELD_PREP(GUC_REGSET_STEERING_INSTANCE, subslice_id);
258 	ext->regname = extlist->name;
259 }
260 
261 static int
262 __alloc_ext_regs(struct __guc_mmio_reg_descr_group *newlist,
263 		 const struct __guc_mmio_reg_descr_group *rootlist, int num_regs)
264 {
265 	struct __guc_mmio_reg_descr *list;
266 
267 	list = kcalloc(num_regs, sizeof(struct __guc_mmio_reg_descr), GFP_KERNEL);
268 	if (!list)
269 		return -ENOMEM;
270 
271 	newlist->extlist = list;
272 	newlist->num_regs = num_regs;
273 	newlist->owner = rootlist->owner;
274 	newlist->engine = rootlist->engine;
275 	newlist->type = rootlist->type;
276 
277 	return 0;
278 }
279 
280 static void
281 guc_capture_alloc_steered_lists_xe_lpd(struct intel_guc *guc,
282 				       const struct __guc_mmio_reg_descr_group *lists)
283 {
284 	struct intel_gt *gt = guc_to_gt(guc);
285 	int slice, subslice, iter, i, num_steer_regs, num_tot_regs = 0;
286 	const struct __guc_mmio_reg_descr_group *list;
287 	struct __guc_mmio_reg_descr_group *extlists;
288 	struct __guc_mmio_reg_descr *extarray;
289 	struct sseu_dev_info *sseu;
290 
291 	/* In XE_LPD we only have steered registers for the render-class */
292 	list = guc_capture_get_one_list(lists, GUC_CAPTURE_LIST_INDEX_PF,
293 					GUC_CAPTURE_LIST_TYPE_ENGINE_CLASS, GUC_RENDER_CLASS);
294 	/* skip if extlists was previously allocated */
295 	if (!list || guc->capture->extlists)
296 		return;
297 
298 	num_steer_regs = ARRAY_SIZE(xe_extregs);
299 
300 	sseu = &gt->info.sseu;
301 	for_each_ss_steering(iter, gt, slice, subslice)
302 		num_tot_regs += num_steer_regs;
303 
304 	if (!num_tot_regs)
305 		return;
306 
307 	/* allocate an extra for an end marker */
308 	extlists = kcalloc(2, sizeof(struct __guc_mmio_reg_descr_group), GFP_KERNEL);
309 	if (!extlists)
310 		return;
311 
312 	if (__alloc_ext_regs(&extlists[0], list, num_tot_regs)) {
313 		kfree(extlists);
314 		return;
315 	}
316 
317 	extarray = extlists[0].extlist;
318 	for_each_ss_steering(iter, gt, slice, subslice) {
319 		for (i = 0; i < num_steer_regs; ++i) {
320 			__fill_ext_reg(extarray, &xe_extregs[i], slice, subslice);
321 			++extarray;
322 		}
323 	}
324 
325 	guc->capture->extlists = extlists;
326 }
327 
328 static const struct __ext_steer_reg xehpg_extregs[] = {
329 	{"XEHPG_INSTDONE_GEOM_SVG", XEHPG_INSTDONE_GEOM_SVG}
330 };
331 
332 static bool __has_xehpg_extregs(u32 ipver)
333 {
334 	return (ipver >= IP_VER(12, 55));
335 }
336 
337 static void
338 guc_capture_alloc_steered_lists_xe_hpg(struct intel_guc *guc,
339 				       const struct __guc_mmio_reg_descr_group *lists,
340 				       u32 ipver)
341 {
342 	struct intel_gt *gt = guc_to_gt(guc);
343 	struct drm_i915_private *i915 = guc_to_gt(guc)->i915;
344 	struct sseu_dev_info *sseu;
345 	int slice, subslice, i, iter, num_steer_regs, num_tot_regs = 0;
346 	const struct __guc_mmio_reg_descr_group *list;
347 	struct __guc_mmio_reg_descr_group *extlists;
348 	struct __guc_mmio_reg_descr *extarray;
349 
350 	/* In XE_LP / HPG we only have render-class steering registers during error-capture */
351 	list = guc_capture_get_one_list(lists, GUC_CAPTURE_LIST_INDEX_PF,
352 					GUC_CAPTURE_LIST_TYPE_ENGINE_CLASS, GUC_RENDER_CLASS);
353 	/* skip if extlists was previously allocated */
354 	if (!list || guc->capture->extlists)
355 		return;
356 
357 	num_steer_regs = ARRAY_SIZE(xe_extregs);
358 	if (__has_xehpg_extregs(ipver))
359 		num_steer_regs += ARRAY_SIZE(xehpg_extregs);
360 
361 	sseu = &gt->info.sseu;
362 	for_each_ss_steering(iter, gt, slice, subslice)
363 		num_tot_regs += num_steer_regs;
364 
365 	if (!num_tot_regs)
366 		return;
367 
368 	/* allocate an extra for an end marker */
369 	extlists = kcalloc(2, sizeof(struct __guc_mmio_reg_descr_group), GFP_KERNEL);
370 	if (!extlists)
371 		return;
372 
373 	if (__alloc_ext_regs(&extlists[0], list, num_tot_regs)) {
374 		kfree(extlists);
375 		return;
376 	}
377 
378 	extarray = extlists[0].extlist;
379 	for_each_ss_steering(iter, gt, slice, subslice) {
380 		for (i = 0; i < ARRAY_SIZE(xe_extregs); ++i) {
381 			__fill_ext_reg(extarray, &xe_extregs[i], slice, subslice);
382 			++extarray;
383 		}
384 		if (__has_xehpg_extregs(ipver)) {
385 			for (i = 0; i < ARRAY_SIZE(xehpg_extregs); ++i) {
386 				__fill_ext_reg(extarray, &xehpg_extregs[i], slice, subslice);
387 				++extarray;
388 			}
389 		}
390 	}
391 
392 	drm_dbg(&i915->drm, "GuC-capture found %d-ext-regs.\n", num_tot_regs);
393 	guc->capture->extlists = extlists;
394 }
395 
396 static const struct __guc_mmio_reg_descr_group *
397 guc_capture_get_device_reglist(struct intel_guc *guc)
398 {
399 	struct drm_i915_private *i915 = guc_to_gt(guc)->i915;
400 
401 	if (GRAPHICS_VER(i915) > 11) {
402 		/*
403 		 * For certain engine classes, there are slice and subslice
404 		 * level registers requiring steering. We allocate and populate
405 		 * these at init time based on hw config add it as an extension
406 		 * list at the end of the pre-populated render list.
407 		 */
408 		if (IS_DG2(i915))
409 			guc_capture_alloc_steered_lists_xe_hpg(guc, xe_lpd_lists, IP_VER(12, 55));
410 		else if (IS_XEHPSDV(i915))
411 			guc_capture_alloc_steered_lists_xe_hpg(guc, xe_lpd_lists, IP_VER(12, 50));
412 		else
413 			guc_capture_alloc_steered_lists_xe_lpd(guc, xe_lpd_lists);
414 
415 		return xe_lpd_lists;
416 	}
417 
418 	/* if GuC submission is enabled on a non-POR platform, just use a common baseline */
419 	return default_lists;
420 }
421 
422 static int
423 guc_capture_list_init(struct intel_guc *guc, u32 owner, u32 type, u32 classid,
424 		      struct guc_mmio_reg *ptr, u16 num_entries)
425 {
426 	u32 i = 0, j = 0;
427 	struct drm_i915_private *i915 = guc_to_gt(guc)->i915;
428 	const struct __guc_mmio_reg_descr_group *reglists = guc->capture->reglists;
429 	struct __guc_mmio_reg_descr_group *extlists = guc->capture->extlists;
430 	const struct __guc_mmio_reg_descr_group *match;
431 	struct __guc_mmio_reg_descr_group *matchext;
432 
433 	if (!reglists)
434 		return -ENODEV;
435 
436 	match = guc_capture_get_one_list(reglists, owner, type, classid);
437 	if (!match)
438 		return -ENODATA;
439 
440 	for (i = 0; i < num_entries && i < match->num_regs; ++i) {
441 		ptr[i].offset = match->list[i].reg.reg;
442 		ptr[i].value = 0xDEADF00D;
443 		ptr[i].flags = match->list[i].flags;
444 		ptr[i].mask = match->list[i].mask;
445 	}
446 
447 	matchext = guc_capture_get_one_ext_list(extlists, owner, type, classid);
448 	if (matchext) {
449 		for (i = match->num_regs, j = 0; i < num_entries &&
450 		     i < (match->num_regs + matchext->num_regs) &&
451 			j < matchext->num_regs; ++i, ++j) {
452 			ptr[i].offset = matchext->extlist[j].reg.reg;
453 			ptr[i].value = 0xDEADF00D;
454 			ptr[i].flags = matchext->extlist[j].flags;
455 			ptr[i].mask = matchext->extlist[j].mask;
456 		}
457 	}
458 	if (i < num_entries)
459 		drm_dbg(&i915->drm, "GuC-capture: Init reglist short %d out %d.\n",
460 			(int)i, (int)num_entries);
461 
462 	return 0;
463 }
464 
465 static int
466 guc_cap_list_num_regs(struct intel_guc_state_capture *gc, u32 owner, u32 type, u32 classid)
467 {
468 	const struct __guc_mmio_reg_descr_group *match;
469 	struct __guc_mmio_reg_descr_group *matchext;
470 	int num_regs;
471 
472 	match = guc_capture_get_one_list(gc->reglists, owner, type, classid);
473 	if (!match)
474 		return 0;
475 
476 	num_regs = match->num_regs;
477 
478 	matchext = guc_capture_get_one_ext_list(gc->extlists, owner, type, classid);
479 	if (matchext)
480 		num_regs += matchext->num_regs;
481 
482 	return num_regs;
483 }
484 
485 int
486 intel_guc_capture_getlistsize(struct intel_guc *guc, u32 owner, u32 type, u32 classid,
487 			      size_t *size)
488 {
489 	struct intel_guc_state_capture *gc = guc->capture;
490 	struct __guc_capture_ads_cache *cache = &gc->ads_cache[owner][type][classid];
491 	int num_regs;
492 
493 	if (!gc->reglists)
494 		return -ENODEV;
495 
496 	if (cache->is_valid) {
497 		*size = cache->size;
498 		return cache->status;
499 	}
500 
501 	num_regs = guc_cap_list_num_regs(gc, owner, type, classid);
502 	if (!num_regs)
503 		return -ENODATA;
504 
505 	*size = PAGE_ALIGN((sizeof(struct guc_debug_capture_list)) +
506 			   (num_regs * sizeof(struct guc_mmio_reg)));
507 
508 	return 0;
509 }
510 
511 static void guc_capture_create_prealloc_nodes(struct intel_guc *guc);
512 
513 int
514 intel_guc_capture_getlist(struct intel_guc *guc, u32 owner, u32 type, u32 classid,
515 			  void **outptr)
516 {
517 	struct intel_guc_state_capture *gc = guc->capture;
518 	struct __guc_capture_ads_cache *cache = &gc->ads_cache[owner][type][classid];
519 	struct drm_i915_private *i915 = guc_to_gt(guc)->i915;
520 	struct guc_debug_capture_list *listnode;
521 	int ret, num_regs;
522 	u8 *caplist, *tmp;
523 	size_t size = 0;
524 
525 	if (!gc->reglists)
526 		return -ENODEV;
527 
528 	if (cache->is_valid) {
529 		*outptr = cache->ptr;
530 		return cache->status;
531 	}
532 
533 	/*
534 	 * ADS population of input registers is a good
535 	 * time to pre-allocate cachelist output nodes
536 	 */
537 	guc_capture_create_prealloc_nodes(guc);
538 
539 	ret = intel_guc_capture_getlistsize(guc, owner, type, classid, &size);
540 	if (ret) {
541 		cache->is_valid = true;
542 		cache->ptr = NULL;
543 		cache->size = 0;
544 		cache->status = ret;
545 		return ret;
546 	}
547 
548 	caplist = kzalloc(size, GFP_KERNEL);
549 	if (!caplist) {
550 		drm_dbg(&i915->drm, "GuC-capture: failed to alloc cached caplist");
551 		return -ENOMEM;
552 	}
553 
554 	/* populate capture list header */
555 	tmp = caplist;
556 	num_regs = guc_cap_list_num_regs(guc->capture, owner, type, classid);
557 	listnode = (struct guc_debug_capture_list *)tmp;
558 	listnode->header.info = FIELD_PREP(GUC_CAPTURELISTHDR_NUMDESCR, (u32)num_regs);
559 
560 	/* populate list of register descriptor */
561 	tmp += sizeof(struct guc_debug_capture_list);
562 	guc_capture_list_init(guc, owner, type, classid, (struct guc_mmio_reg *)tmp, num_regs);
563 
564 	/* cache this list */
565 	cache->is_valid = true;
566 	cache->ptr = caplist;
567 	cache->size = size;
568 	cache->status = 0;
569 
570 	*outptr = caplist;
571 
572 	return 0;
573 }
574 
575 int
576 intel_guc_capture_getnullheader(struct intel_guc *guc,
577 				void **outptr, size_t *size)
578 {
579 	struct intel_guc_state_capture *gc = guc->capture;
580 	struct drm_i915_private *i915 = guc_to_gt(guc)->i915;
581 	int tmp = sizeof(u32) * 4;
582 	void *null_header;
583 
584 	if (gc->ads_null_cache) {
585 		*outptr = gc->ads_null_cache;
586 		*size = tmp;
587 		return 0;
588 	}
589 
590 	null_header = kzalloc(tmp, GFP_KERNEL);
591 	if (!null_header) {
592 		drm_dbg(&i915->drm, "GuC-capture: failed to alloc cached nulllist");
593 		return -ENOMEM;
594 	}
595 
596 	gc->ads_null_cache = null_header;
597 	*outptr = null_header;
598 	*size = tmp;
599 
600 	return 0;
601 }
602 
603 #define GUC_CAPTURE_OVERBUFFER_MULTIPLIER 3
604 
605 int
606 intel_guc_capture_output_min_size_est(struct intel_guc *guc)
607 {
608 	struct intel_gt *gt = guc_to_gt(guc);
609 	struct intel_engine_cs *engine;
610 	enum intel_engine_id id;
611 	int worst_min_size = 0, num_regs = 0;
612 	size_t tmp = 0;
613 
614 	if (!guc->capture)
615 		return -ENODEV;
616 
617 	/*
618 	 * If every single engine-instance suffered a failure in quick succession but
619 	 * were all unrelated, then a burst of multiple error-capture events would dump
620 	 * registers for every one engine instance, one at a time. In this case, GuC
621 	 * would even dump the global-registers repeatedly.
622 	 *
623 	 * For each engine instance, there would be 1 x guc_state_capture_group_t output
624 	 * followed by 3 x guc_state_capture_t lists. The latter is how the register
625 	 * dumps are split across different register types (where the '3' are global vs class
626 	 * vs instance). Finally, let's multiply the whole thing by 3x (just so we are
627 	 * not limited to just 1 round of data in a worst case full register dump log)
628 	 *
629 	 * NOTE: intel_guc_log that allocates the log buffer would round this size up to
630 	 * a power of two.
631 	 */
632 
633 	for_each_engine(engine, gt, id) {
634 		worst_min_size += sizeof(struct guc_state_capture_group_header_t) +
635 					 (3 * sizeof(struct guc_state_capture_header_t));
636 
637 		if (!intel_guc_capture_getlistsize(guc, 0, GUC_CAPTURE_LIST_TYPE_GLOBAL, 0, &tmp))
638 			num_regs += tmp;
639 
640 		if (!intel_guc_capture_getlistsize(guc, 0, GUC_CAPTURE_LIST_TYPE_ENGINE_CLASS,
641 						   engine->class, &tmp)) {
642 			num_regs += tmp;
643 		}
644 		if (!intel_guc_capture_getlistsize(guc, 0, GUC_CAPTURE_LIST_TYPE_ENGINE_INSTANCE,
645 						   engine->class, &tmp)) {
646 			num_regs += tmp;
647 		}
648 	}
649 
650 	worst_min_size += (num_regs * sizeof(struct guc_mmio_reg));
651 
652 	return (worst_min_size * GUC_CAPTURE_OVERBUFFER_MULTIPLIER);
653 }
654 
655 /*
656  * KMD Init time flows:
657  * --------------------
658  *     --> alloc A: GuC input capture regs lists (registered to GuC via ADS).
659  *                  intel_guc_ads acquires the register lists by calling
660  *                  intel_guc_capture_list_size and intel_guc_capture_list_get 'n' times,
661  *                  where n = 1 for global-reg-list +
662  *                            num_engine_classes for class-reg-list +
663  *                            num_engine_classes for instance-reg-list
664  *                               (since all instances of the same engine-class type
665  *                                have an identical engine-instance register-list).
666  *                  ADS module also calls separately for PF vs VF.
667  *
668  *     --> alloc B: GuC output capture buf (registered via guc_init_params(log_param))
669  *                  Size = #define CAPTURE_BUFFER_SIZE (warns if on too-small)
670  *                  Note2: 'x 3' to hold multiple capture groups
671  *
672  * GUC Runtime notify capture:
673  * --------------------------
674  *     --> G2H STATE_CAPTURE_NOTIFICATION
675  *                   L--> intel_guc_capture_process
676  *                           L--> Loop through B (head..tail) and for each engine instance's
677  *                                err-state-captured register-list we find, we alloc 'C':
678  *      --> alloc C: A capture-output-node structure that includes misc capture info along
679  *                   with 3 register list dumps (global, engine-class and engine-instance)
680  *                   This node is created from a pre-allocated list of blank nodes in
681  *                   guc->capture->cachelist and populated with the error-capture
682  *                   data from GuC and then it's added into guc->capture->outlist linked
683  *                   list. This list is used for matchup and printout by i915_gpu_coredump
684  *                   and err_print_gt, (when user invokes the error capture sysfs).
685  *
686  * GUC --> notify context reset:
687  * -----------------------------
688  *     --> G2H CONTEXT RESET
689  *                   L--> guc_handle_context_reset --> i915_capture_error_state
690  *                          L--> i915_gpu_coredump(..IS_GUC_CAPTURE) --> gt_record_engines
691  *                               --> capture_engine(..IS_GUC_CAPTURE)
692  *                               L--> intel_guc_capture_get_matching_node is where
693  *                                    detach C from internal linked list and add it into
694  *                                    intel_engine_coredump struct (if the context and
695  *                                    engine of the event notification matches a node
696  *                                    in the link list).
697  *
698  * User Sysfs / Debugfs
699  * --------------------
700  *      --> i915_gpu_coredump_copy_to_buffer->
701  *                   L--> err_print_to_sgl --> err_print_gt
702  *                        L--> error_print_guc_captures
703  *                             L--> intel_guc_capture_print_node prints the
704  *                                  register lists values of the attached node
705  *                                  on the error-engine-dump being reported.
706  *                   L--> i915_reset_error_state ... -->__i915_gpu_coredump_free
707  *                        L--> ... cleanup_gt -->
708  *                             L--> intel_guc_capture_free_node returns the
709  *                                  capture-output-node back to the internal
710  *                                  cachelist for reuse.
711  *
712  */
713 
714 static int guc_capture_buf_cnt(struct __guc_capture_bufstate *buf)
715 {
716 	if (buf->wr >= buf->rd)
717 		return (buf->wr - buf->rd);
718 	return (buf->size - buf->rd) + buf->wr;
719 }
720 
721 static int guc_capture_buf_cnt_to_end(struct __guc_capture_bufstate *buf)
722 {
723 	if (buf->rd > buf->wr)
724 		return (buf->size - buf->rd);
725 	return (buf->wr - buf->rd);
726 }
727 
728 /*
729  * GuC's error-capture output is a ring buffer populated in a byte-stream fashion:
730  *
731  * The GuC Log buffer region for error-capture is managed like a ring buffer.
732  * The GuC firmware dumps error capture logs into this ring in a byte-stream flow.
733  * Additionally, as per the current and foreseeable future, all packed error-
734  * capture output structures are dword aligned.
735  *
736  * That said, if the GuC firmware is in the midst of writing a structure that is larger
737  * than one dword but the tail end of the err-capture buffer-region has lesser space left,
738  * we would need to extract that structure one dword at a time straddled across the end,
739  * onto the start of the ring.
740  *
741  * Below function, guc_capture_log_remove_dw is a helper for that. All callers of this
742  * function would typically do a straight-up memcpy from the ring contents and will only
743  * call this helper if their structure-extraction is straddling across the end of the
744  * ring. GuC firmware does not add any padding. The reason for the no-padding is to ease
745  * scalability for future expansion of output data types without requiring a redesign
746  * of the flow controls.
747  */
748 static int
749 guc_capture_log_remove_dw(struct intel_guc *guc, struct __guc_capture_bufstate *buf,
750 			  u32 *dw)
751 {
752 	struct drm_i915_private *i915 = guc_to_gt(guc)->i915;
753 	int tries = 2;
754 	int avail = 0;
755 	u32 *src_data;
756 
757 	if (!guc_capture_buf_cnt(buf))
758 		return 0;
759 
760 	while (tries--) {
761 		avail = guc_capture_buf_cnt_to_end(buf);
762 		if (avail >= sizeof(u32)) {
763 			src_data = (u32 *)(buf->data + buf->rd);
764 			*dw = *src_data;
765 			buf->rd += 4;
766 			return 4;
767 		}
768 		if (avail)
769 			drm_dbg(&i915->drm, "GuC-Cap-Logs not dword aligned, skipping.\n");
770 		buf->rd = 0;
771 	}
772 
773 	return 0;
774 }
775 
776 static bool
777 guc_capture_data_extracted(struct __guc_capture_bufstate *b,
778 			   int size, void *dest)
779 {
780 	if (guc_capture_buf_cnt_to_end(b) >= size) {
781 		memcpy(dest, (b->data + b->rd), size);
782 		b->rd += size;
783 		return true;
784 	}
785 	return false;
786 }
787 
788 static int
789 guc_capture_log_get_group_hdr(struct intel_guc *guc, struct __guc_capture_bufstate *buf,
790 			      struct guc_state_capture_group_header_t *ghdr)
791 {
792 	int read = 0;
793 	int fullsize = sizeof(struct guc_state_capture_group_header_t);
794 
795 	if (fullsize > guc_capture_buf_cnt(buf))
796 		return -1;
797 
798 	if (guc_capture_data_extracted(buf, fullsize, (void *)ghdr))
799 		return 0;
800 
801 	read += guc_capture_log_remove_dw(guc, buf, &ghdr->owner);
802 	read += guc_capture_log_remove_dw(guc, buf, &ghdr->info);
803 	if (read != fullsize)
804 		return -1;
805 
806 	return 0;
807 }
808 
809 static int
810 guc_capture_log_get_data_hdr(struct intel_guc *guc, struct __guc_capture_bufstate *buf,
811 			     struct guc_state_capture_header_t *hdr)
812 {
813 	int read = 0;
814 	int fullsize = sizeof(struct guc_state_capture_header_t);
815 
816 	if (fullsize > guc_capture_buf_cnt(buf))
817 		return -1;
818 
819 	if (guc_capture_data_extracted(buf, fullsize, (void *)hdr))
820 		return 0;
821 
822 	read += guc_capture_log_remove_dw(guc, buf, &hdr->owner);
823 	read += guc_capture_log_remove_dw(guc, buf, &hdr->info);
824 	read += guc_capture_log_remove_dw(guc, buf, &hdr->lrca);
825 	read += guc_capture_log_remove_dw(guc, buf, &hdr->guc_id);
826 	read += guc_capture_log_remove_dw(guc, buf, &hdr->num_mmios);
827 	if (read != fullsize)
828 		return -1;
829 
830 	return 0;
831 }
832 
833 static int
834 guc_capture_log_get_register(struct intel_guc *guc, struct __guc_capture_bufstate *buf,
835 			     struct guc_mmio_reg *reg)
836 {
837 	int read = 0;
838 	int fullsize = sizeof(struct guc_mmio_reg);
839 
840 	if (fullsize > guc_capture_buf_cnt(buf))
841 		return -1;
842 
843 	if (guc_capture_data_extracted(buf, fullsize, (void *)reg))
844 		return 0;
845 
846 	read += guc_capture_log_remove_dw(guc, buf, &reg->offset);
847 	read += guc_capture_log_remove_dw(guc, buf, &reg->value);
848 	read += guc_capture_log_remove_dw(guc, buf, &reg->flags);
849 	read += guc_capture_log_remove_dw(guc, buf, &reg->mask);
850 	if (read != fullsize)
851 		return -1;
852 
853 	return 0;
854 }
855 
856 static void
857 guc_capture_delete_one_node(struct intel_guc *guc, struct __guc_capture_parsed_output *node)
858 {
859 	int i;
860 
861 	for (i = 0; i < GUC_CAPTURE_LIST_TYPE_MAX; ++i)
862 		kfree(node->reginfo[i].regs);
863 	list_del(&node->link);
864 	kfree(node);
865 }
866 
867 static void
868 guc_capture_delete_prealloc_nodes(struct intel_guc *guc)
869 {
870 	struct __guc_capture_parsed_output *n, *ntmp;
871 
872 	/*
873 	 * NOTE: At the end of driver operation, we must assume that we
874 	 * have prealloc nodes in both the cachelist as well as outlist
875 	 * if unclaimed error capture events occurred prior to shutdown.
876 	 */
877 	list_for_each_entry_safe(n, ntmp, &guc->capture->outlist, link)
878 		guc_capture_delete_one_node(guc, n);
879 
880 	list_for_each_entry_safe(n, ntmp, &guc->capture->cachelist, link)
881 		guc_capture_delete_one_node(guc, n);
882 }
883 
884 static void
885 guc_capture_add_node_to_list(struct __guc_capture_parsed_output *node,
886 			     struct list_head *list)
887 {
888 	list_add_tail(&node->link, list);
889 }
890 
891 static void
892 guc_capture_add_node_to_outlist(struct intel_guc_state_capture *gc,
893 				struct __guc_capture_parsed_output *node)
894 {
895 	guc_capture_add_node_to_list(node, &gc->outlist);
896 }
897 
898 static void
899 guc_capture_add_node_to_cachelist(struct intel_guc_state_capture *gc,
900 				  struct __guc_capture_parsed_output *node)
901 {
902 	guc_capture_add_node_to_list(node, &gc->cachelist);
903 }
904 
905 static void
906 guc_capture_init_node(struct intel_guc *guc, struct __guc_capture_parsed_output *node)
907 {
908 	struct guc_mmio_reg *tmp[GUC_CAPTURE_LIST_TYPE_MAX];
909 	int i;
910 
911 	for (i = 0; i < GUC_CAPTURE_LIST_TYPE_MAX; ++i) {
912 		tmp[i] = node->reginfo[i].regs;
913 		memset(tmp[i], 0, sizeof(struct guc_mmio_reg) *
914 		       guc->capture->max_mmio_per_node);
915 	}
916 	memset(node, 0, sizeof(*node));
917 	for (i = 0; i < GUC_CAPTURE_LIST_TYPE_MAX; ++i)
918 		node->reginfo[i].regs = tmp[i];
919 
920 	INIT_LIST_HEAD(&node->link);
921 }
922 
923 static struct __guc_capture_parsed_output *
924 guc_capture_get_prealloc_node(struct intel_guc *guc)
925 {
926 	struct __guc_capture_parsed_output *found = NULL;
927 
928 	if (!list_empty(&guc->capture->cachelist)) {
929 		struct __guc_capture_parsed_output *n, *ntmp;
930 
931 		/* get first avail node from the cache list */
932 		list_for_each_entry_safe(n, ntmp, &guc->capture->cachelist, link) {
933 			found = n;
934 			list_del(&n->link);
935 			break;
936 		}
937 	} else {
938 		struct __guc_capture_parsed_output *n, *ntmp;
939 
940 		/* traverse down and steal back the oldest node already allocated */
941 		list_for_each_entry_safe(n, ntmp, &guc->capture->outlist, link) {
942 			found = n;
943 		}
944 		if (found)
945 			list_del(&found->link);
946 	}
947 	if (found)
948 		guc_capture_init_node(guc, found);
949 
950 	return found;
951 }
952 
953 static struct __guc_capture_parsed_output *
954 guc_capture_alloc_one_node(struct intel_guc *guc)
955 {
956 	struct __guc_capture_parsed_output *new;
957 	int i;
958 
959 	new = kzalloc(sizeof(*new), GFP_KERNEL);
960 	if (!new)
961 		return NULL;
962 
963 	for (i = 0; i < GUC_CAPTURE_LIST_TYPE_MAX; ++i) {
964 		new->reginfo[i].regs = kcalloc(guc->capture->max_mmio_per_node,
965 					       sizeof(struct guc_mmio_reg), GFP_KERNEL);
966 		if (!new->reginfo[i].regs) {
967 			while (i)
968 				kfree(new->reginfo[--i].regs);
969 			kfree(new);
970 			return NULL;
971 		}
972 	}
973 	guc_capture_init_node(guc, new);
974 
975 	return new;
976 }
977 
978 static struct __guc_capture_parsed_output *
979 guc_capture_clone_node(struct intel_guc *guc, struct __guc_capture_parsed_output *original,
980 		       u32 keep_reglist_mask)
981 {
982 	struct __guc_capture_parsed_output *new;
983 	int i;
984 
985 	new = guc_capture_get_prealloc_node(guc);
986 	if (!new)
987 		return NULL;
988 	if (!original)
989 		return new;
990 
991 	new->is_partial = original->is_partial;
992 
993 	/* copy reg-lists that we want to clone */
994 	for (i = 0; i < GUC_CAPTURE_LIST_TYPE_MAX; ++i) {
995 		if (keep_reglist_mask & BIT(i)) {
996 			GEM_BUG_ON(original->reginfo[i].num_regs  >
997 				   guc->capture->max_mmio_per_node);
998 
999 			memcpy(new->reginfo[i].regs, original->reginfo[i].regs,
1000 			       original->reginfo[i].num_regs * sizeof(struct guc_mmio_reg));
1001 
1002 			new->reginfo[i].num_regs = original->reginfo[i].num_regs;
1003 			new->reginfo[i].vfid  = original->reginfo[i].vfid;
1004 
1005 			if (i == GUC_CAPTURE_LIST_TYPE_ENGINE_CLASS) {
1006 				new->eng_class = original->eng_class;
1007 			} else if (i == GUC_CAPTURE_LIST_TYPE_ENGINE_INSTANCE) {
1008 				new->eng_inst = original->eng_inst;
1009 				new->guc_id = original->guc_id;
1010 				new->lrca = original->lrca;
1011 			}
1012 		}
1013 	}
1014 
1015 	return new;
1016 }
1017 
1018 static void
1019 __guc_capture_create_prealloc_nodes(struct intel_guc *guc)
1020 {
1021 	struct __guc_capture_parsed_output *node = NULL;
1022 	struct drm_i915_private *i915 = guc_to_gt(guc)->i915;
1023 	int i;
1024 
1025 	for (i = 0; i < PREALLOC_NODES_MAX_COUNT; ++i) {
1026 		node = guc_capture_alloc_one_node(guc);
1027 		if (!node) {
1028 			drm_warn(&i915->drm, "GuC Capture pre-alloc-cache failure\n");
1029 			/* dont free the priors, use what we got and cleanup at shutdown */
1030 			return;
1031 		}
1032 		guc_capture_add_node_to_cachelist(guc->capture, node);
1033 	}
1034 }
1035 
1036 static int
1037 guc_get_max_reglist_count(struct intel_guc *guc)
1038 {
1039 	int i, j, k, tmp, maxregcount = 0;
1040 
1041 	for (i = 0; i < GUC_CAPTURE_LIST_INDEX_MAX; ++i) {
1042 		for (j = 0; j < GUC_CAPTURE_LIST_TYPE_MAX; ++j) {
1043 			for (k = 0; k < GUC_MAX_ENGINE_CLASSES; ++k) {
1044 				if (j == GUC_CAPTURE_LIST_TYPE_GLOBAL && k > 0)
1045 					continue;
1046 
1047 				tmp = guc_cap_list_num_regs(guc->capture, i, j, k);
1048 				if (tmp > maxregcount)
1049 					maxregcount = tmp;
1050 			}
1051 		}
1052 	}
1053 	if (!maxregcount)
1054 		maxregcount = PREALLOC_NODES_DEFAULT_NUMREGS;
1055 
1056 	return maxregcount;
1057 }
1058 
1059 static void
1060 guc_capture_create_prealloc_nodes(struct intel_guc *guc)
1061 {
1062 	/* skip if we've already done the pre-alloc */
1063 	if (guc->capture->max_mmio_per_node)
1064 		return;
1065 
1066 	guc->capture->max_mmio_per_node = guc_get_max_reglist_count(guc);
1067 	__guc_capture_create_prealloc_nodes(guc);
1068 }
1069 
1070 static int
1071 guc_capture_extract_reglists(struct intel_guc *guc, struct __guc_capture_bufstate *buf)
1072 {
1073 	struct drm_i915_private *i915 = guc_to_gt(guc)->i915;
1074 	struct guc_state_capture_group_header_t ghdr = {0};
1075 	struct guc_state_capture_header_t hdr = {0};
1076 	struct __guc_capture_parsed_output *node = NULL;
1077 	struct guc_mmio_reg *regs = NULL;
1078 	int i, numlists, numregs, ret = 0;
1079 	enum guc_capture_type datatype;
1080 	struct guc_mmio_reg tmp;
1081 	bool is_partial = false;
1082 
1083 	i = guc_capture_buf_cnt(buf);
1084 	if (!i)
1085 		return -ENODATA;
1086 	if (i % sizeof(u32)) {
1087 		drm_warn(&i915->drm, "GuC Capture new entries unaligned\n");
1088 		ret = -EIO;
1089 		goto bailout;
1090 	}
1091 
1092 	/* first get the capture group header */
1093 	if (guc_capture_log_get_group_hdr(guc, buf, &ghdr)) {
1094 		ret = -EIO;
1095 		goto bailout;
1096 	}
1097 	/*
1098 	 * we would typically expect a layout as below where n would be expected to be
1099 	 * anywhere between 3 to n where n > 3 if we are seeing multiple dependent engine
1100 	 * instances being reset together.
1101 	 * ____________________________________________
1102 	 * | Capture Group                            |
1103 	 * | ________________________________________ |
1104 	 * | | Capture Group Header:                | |
1105 	 * | |  - num_captures = 5                  | |
1106 	 * | |______________________________________| |
1107 	 * | ________________________________________ |
1108 	 * | | Capture1:                            | |
1109 	 * | |  Hdr: GLOBAL, numregs=a              | |
1110 	 * | | ____________________________________ | |
1111 	 * | | | Reglist                          | | |
1112 	 * | | | - reg1, reg2, ... rega           | | |
1113 	 * | | |__________________________________| | |
1114 	 * | |______________________________________| |
1115 	 * | ________________________________________ |
1116 	 * | | Capture2:                            | |
1117 	 * | |  Hdr: CLASS=RENDER/COMPUTE, numregs=b| |
1118 	 * | | ____________________________________ | |
1119 	 * | | | Reglist                          | | |
1120 	 * | | | - reg1, reg2, ... regb           | | |
1121 	 * | | |__________________________________| | |
1122 	 * | |______________________________________| |
1123 	 * | ________________________________________ |
1124 	 * | | Capture3:                            | |
1125 	 * | |  Hdr: INSTANCE=RCS, numregs=c        | |
1126 	 * | | ____________________________________ | |
1127 	 * | | | Reglist                          | | |
1128 	 * | | | - reg1, reg2, ... regc           | | |
1129 	 * | | |__________________________________| | |
1130 	 * | |______________________________________| |
1131 	 * | ________________________________________ |
1132 	 * | | Capture4:                            | |
1133 	 * | |  Hdr: CLASS=RENDER/COMPUTE, numregs=d| |
1134 	 * | | ____________________________________ | |
1135 	 * | | | Reglist                          | | |
1136 	 * | | | - reg1, reg2, ... regd           | | |
1137 	 * | | |__________________________________| | |
1138 	 * | |______________________________________| |
1139 	 * | ________________________________________ |
1140 	 * | | Capture5:                            | |
1141 	 * | |  Hdr: INSTANCE=CCS0, numregs=e       | |
1142 	 * | | ____________________________________ | |
1143 	 * | | | Reglist                          | | |
1144 	 * | | | - reg1, reg2, ... rege           | | |
1145 	 * | | |__________________________________| | |
1146 	 * | |______________________________________| |
1147 	 * |__________________________________________|
1148 	 */
1149 	is_partial = FIELD_GET(CAP_GRP_HDR_CAPTURE_TYPE, ghdr.info);
1150 	numlists = FIELD_GET(CAP_GRP_HDR_NUM_CAPTURES, ghdr.info);
1151 
1152 	while (numlists--) {
1153 		if (guc_capture_log_get_data_hdr(guc, buf, &hdr)) {
1154 			ret = -EIO;
1155 			break;
1156 		}
1157 
1158 		datatype = FIELD_GET(CAP_HDR_CAPTURE_TYPE, hdr.info);
1159 		if (datatype > GUC_CAPTURE_LIST_TYPE_ENGINE_INSTANCE) {
1160 			/* unknown capture type - skip over to next capture set */
1161 			numregs = FIELD_GET(CAP_HDR_NUM_MMIOS, hdr.num_mmios);
1162 			while (numregs--) {
1163 				if (guc_capture_log_get_register(guc, buf, &tmp)) {
1164 					ret = -EIO;
1165 					break;
1166 				}
1167 			}
1168 			continue;
1169 		} else if (node) {
1170 			/*
1171 			 * Based on the current capture type and what we have so far,
1172 			 * decide if we should add the current node into the internal
1173 			 * linked list for match-up when i915_gpu_coredump calls later
1174 			 * (and alloc a blank node for the next set of reglists)
1175 			 * or continue with the same node or clone the current node
1176 			 * but only retain the global or class registers (such as the
1177 			 * case of dependent engine resets).
1178 			 */
1179 			if (datatype == GUC_CAPTURE_LIST_TYPE_GLOBAL) {
1180 				guc_capture_add_node_to_outlist(guc->capture, node);
1181 				node = NULL;
1182 			} else if (datatype == GUC_CAPTURE_LIST_TYPE_ENGINE_CLASS &&
1183 				   node->reginfo[GUC_CAPTURE_LIST_TYPE_ENGINE_CLASS].num_regs) {
1184 				/* Add to list, clone node and duplicate global list */
1185 				guc_capture_add_node_to_outlist(guc->capture, node);
1186 				node = guc_capture_clone_node(guc, node,
1187 							      GCAP_PARSED_REGLIST_INDEX_GLOBAL);
1188 			} else if (datatype == GUC_CAPTURE_LIST_TYPE_ENGINE_INSTANCE &&
1189 				   node->reginfo[GUC_CAPTURE_LIST_TYPE_ENGINE_INSTANCE].num_regs) {
1190 				/* Add to list, clone node and duplicate global + class lists */
1191 				guc_capture_add_node_to_outlist(guc->capture, node);
1192 				node = guc_capture_clone_node(guc, node,
1193 							      (GCAP_PARSED_REGLIST_INDEX_GLOBAL |
1194 							      GCAP_PARSED_REGLIST_INDEX_ENGCLASS));
1195 			}
1196 		}
1197 
1198 		if (!node) {
1199 			node = guc_capture_get_prealloc_node(guc);
1200 			if (!node) {
1201 				ret = -ENOMEM;
1202 				break;
1203 			}
1204 			if (datatype != GUC_CAPTURE_LIST_TYPE_GLOBAL)
1205 				drm_dbg(&i915->drm, "GuC Capture missing global dump: %08x!\n",
1206 					datatype);
1207 		}
1208 		node->is_partial = is_partial;
1209 		node->reginfo[datatype].vfid = FIELD_GET(CAP_HDR_CAPTURE_VFID, hdr.owner);
1210 		switch (datatype) {
1211 		case GUC_CAPTURE_LIST_TYPE_ENGINE_INSTANCE:
1212 			node->eng_class = FIELD_GET(CAP_HDR_ENGINE_CLASS, hdr.info);
1213 			node->eng_inst = FIELD_GET(CAP_HDR_ENGINE_INSTANCE, hdr.info);
1214 			node->lrca = hdr.lrca;
1215 			node->guc_id = hdr.guc_id;
1216 			break;
1217 		case GUC_CAPTURE_LIST_TYPE_ENGINE_CLASS:
1218 			node->eng_class = FIELD_GET(CAP_HDR_ENGINE_CLASS, hdr.info);
1219 			break;
1220 		default:
1221 			break;
1222 		}
1223 
1224 		numregs = FIELD_GET(CAP_HDR_NUM_MMIOS, hdr.num_mmios);
1225 		if (numregs > guc->capture->max_mmio_per_node) {
1226 			drm_dbg(&i915->drm, "GuC Capture list extraction clipped by prealloc!\n");
1227 			numregs = guc->capture->max_mmio_per_node;
1228 		}
1229 		node->reginfo[datatype].num_regs = numregs;
1230 		regs = node->reginfo[datatype].regs;
1231 		i = 0;
1232 		while (numregs--) {
1233 			if (guc_capture_log_get_register(guc, buf, &regs[i++])) {
1234 				ret = -EIO;
1235 				break;
1236 			}
1237 		}
1238 	}
1239 
1240 bailout:
1241 	if (node) {
1242 		/* If we have data, add to linked list for match-up when i915_gpu_coredump calls */
1243 		for (i = GUC_CAPTURE_LIST_TYPE_GLOBAL; i < GUC_CAPTURE_LIST_TYPE_MAX; ++i) {
1244 			if (node->reginfo[i].regs) {
1245 				guc_capture_add_node_to_outlist(guc->capture, node);
1246 				node = NULL;
1247 				break;
1248 			}
1249 		}
1250 		if (node) /* else return it back to cache list */
1251 			guc_capture_add_node_to_cachelist(guc->capture, node);
1252 	}
1253 	return ret;
1254 }
1255 
1256 static int __guc_capture_flushlog_complete(struct intel_guc *guc)
1257 {
1258 	u32 action[] = {
1259 		INTEL_GUC_ACTION_LOG_BUFFER_FILE_FLUSH_COMPLETE,
1260 		GUC_CAPTURE_LOG_BUFFER
1261 	};
1262 
1263 	return intel_guc_send_nb(guc, action, ARRAY_SIZE(action), 0);
1264 
1265 }
1266 
1267 static void __guc_capture_process_output(struct intel_guc *guc)
1268 {
1269 	unsigned int buffer_size, read_offset, write_offset, full_count;
1270 	struct intel_uc *uc = container_of(guc, typeof(*uc), guc);
1271 	struct drm_i915_private *i915 = guc_to_gt(guc)->i915;
1272 	struct guc_log_buffer_state log_buf_state_local;
1273 	struct guc_log_buffer_state *log_buf_state;
1274 	struct __guc_capture_bufstate buf;
1275 	void *src_data = NULL;
1276 	bool new_overflow;
1277 	int ret;
1278 
1279 	log_buf_state = guc->log.buf_addr +
1280 			(sizeof(struct guc_log_buffer_state) * GUC_CAPTURE_LOG_BUFFER);
1281 	src_data = guc->log.buf_addr + intel_guc_get_log_buffer_offset(GUC_CAPTURE_LOG_BUFFER);
1282 
1283 	/*
1284 	 * Make a copy of the state structure, inside GuC log buffer
1285 	 * (which is uncached mapped), on the stack to avoid reading
1286 	 * from it multiple times.
1287 	 */
1288 	memcpy(&log_buf_state_local, log_buf_state, sizeof(struct guc_log_buffer_state));
1289 	buffer_size = intel_guc_get_log_buffer_size(GUC_CAPTURE_LOG_BUFFER);
1290 	read_offset = log_buf_state_local.read_ptr;
1291 	write_offset = log_buf_state_local.sampled_write_ptr;
1292 	full_count = log_buf_state_local.buffer_full_cnt;
1293 
1294 	/* Bookkeeping stuff */
1295 	guc->log.stats[GUC_CAPTURE_LOG_BUFFER].flush += log_buf_state_local.flush_to_file;
1296 	new_overflow = intel_guc_check_log_buf_overflow(&guc->log, GUC_CAPTURE_LOG_BUFFER,
1297 							full_count);
1298 
1299 	/* Now copy the actual logs. */
1300 	if (unlikely(new_overflow)) {
1301 		/* copy the whole buffer in case of overflow */
1302 		read_offset = 0;
1303 		write_offset = buffer_size;
1304 	} else if (unlikely((read_offset > buffer_size) ||
1305 			(write_offset > buffer_size))) {
1306 		drm_err(&i915->drm, "invalid GuC log capture buffer state!\n");
1307 		/* copy whole buffer as offsets are unreliable */
1308 		read_offset = 0;
1309 		write_offset = buffer_size;
1310 	}
1311 
1312 	buf.size = buffer_size;
1313 	buf.rd = read_offset;
1314 	buf.wr = write_offset;
1315 	buf.data = src_data;
1316 
1317 	if (!uc->reset_in_progress) {
1318 		do {
1319 			ret = guc_capture_extract_reglists(guc, &buf);
1320 		} while (ret >= 0);
1321 	}
1322 
1323 	/* Update the state of log buffer err-cap state */
1324 	log_buf_state->read_ptr = write_offset;
1325 	log_buf_state->flush_to_file = 0;
1326 	__guc_capture_flushlog_complete(guc);
1327 }
1328 
1329 #if IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR)
1330 
1331 static const char *
1332 guc_capture_reg_to_str(const struct intel_guc *guc, u32 owner, u32 type,
1333 		       u32 class, u32 id, u32 offset, u32 *is_ext)
1334 {
1335 	const struct __guc_mmio_reg_descr_group *reglists = guc->capture->reglists;
1336 	struct __guc_mmio_reg_descr_group *extlists = guc->capture->extlists;
1337 	const struct __guc_mmio_reg_descr_group *match;
1338 	struct __guc_mmio_reg_descr_group *matchext;
1339 	int j;
1340 
1341 	*is_ext = 0;
1342 	if (!reglists)
1343 		return NULL;
1344 
1345 	match = guc_capture_get_one_list(reglists, owner, type, id);
1346 	if (!match)
1347 		return NULL;
1348 
1349 	for (j = 0; j < match->num_regs; ++j) {
1350 		if (offset == match->list[j].reg.reg)
1351 			return match->list[j].regname;
1352 	}
1353 	if (extlists) {
1354 		matchext = guc_capture_get_one_ext_list(extlists, owner, type, id);
1355 		if (!matchext)
1356 			return NULL;
1357 		for (j = 0; j < matchext->num_regs; ++j) {
1358 			if (offset == matchext->extlist[j].reg.reg) {
1359 				*is_ext = 1;
1360 				return matchext->extlist[j].regname;
1361 			}
1362 		}
1363 	}
1364 
1365 	return NULL;
1366 }
1367 
1368 #ifdef CONFIG_DRM_I915_DEBUG_GUC
1369 #define __out(a, ...) \
1370 	do { \
1371 		drm_warn((&(a)->i915->drm), __VA_ARGS__); \
1372 		i915_error_printf((a), __VA_ARGS__); \
1373 	} while (0)
1374 #else
1375 #define __out(a, ...) \
1376 	i915_error_printf(a, __VA_ARGS__)
1377 #endif
1378 
1379 #define GCAP_PRINT_INTEL_ENG_INFO(ebuf, eng) \
1380 	do { \
1381 		__out(ebuf, "    i915-Eng-Name: %s command stream\n", \
1382 		      (eng)->name); \
1383 		__out(ebuf, "    i915-Eng-Inst-Class: 0x%02x\n", (eng)->class); \
1384 		__out(ebuf, "    i915-Eng-Inst-Id: 0x%02x\n", (eng)->instance); \
1385 		__out(ebuf, "    i915-Eng-LogicalMask: 0x%08x\n", \
1386 		      (eng)->logical_mask); \
1387 	} while (0)
1388 
1389 #define GCAP_PRINT_GUC_INST_INFO(ebuf, node) \
1390 	do { \
1391 		__out(ebuf, "    GuC-Engine-Inst-Id: 0x%08x\n", \
1392 		      (node)->eng_inst); \
1393 		__out(ebuf, "    GuC-Context-Id: 0x%08x\n", (node)->guc_id); \
1394 		__out(ebuf, "    LRCA: 0x%08x\n", (node)->lrca); \
1395 	} while (0)
1396 
1397 int intel_guc_capture_print_engine_node(struct drm_i915_error_state_buf *ebuf,
1398 					const struct intel_engine_coredump *ee)
1399 {
1400 	const char *grptype[GUC_STATE_CAPTURE_GROUP_TYPE_MAX] = {
1401 		"full-capture",
1402 		"partial-capture"
1403 	};
1404 	const char *datatype[GUC_CAPTURE_LIST_TYPE_MAX] = {
1405 		"Global",
1406 		"Engine-Class",
1407 		"Engine-Instance"
1408 	};
1409 	struct intel_guc_state_capture *cap;
1410 	struct __guc_capture_parsed_output *node;
1411 	struct intel_engine_cs *eng;
1412 	struct guc_mmio_reg *regs;
1413 	struct intel_guc *guc;
1414 	const char *str;
1415 	int numregs, i, j;
1416 	u32 is_ext;
1417 
1418 	if (!ebuf || !ee)
1419 		return -EINVAL;
1420 	cap = ee->capture;
1421 	if (!cap || !ee->engine)
1422 		return -ENODEV;
1423 
1424 	guc = &ee->engine->gt->uc.guc;
1425 
1426 	__out(ebuf, "global --- GuC Error Capture on %s command stream:\n",
1427 	      ee->engine->name);
1428 
1429 	node = ee->guc_capture_node;
1430 	if (!node) {
1431 		__out(ebuf, "  No matching ee-node\n");
1432 		return 0;
1433 	}
1434 
1435 	__out(ebuf, "Coverage:  %s\n", grptype[node->is_partial]);
1436 
1437 	for (i = GUC_CAPTURE_LIST_TYPE_GLOBAL; i < GUC_CAPTURE_LIST_TYPE_MAX; ++i) {
1438 		__out(ebuf, "  RegListType: %s\n",
1439 		      datatype[i % GUC_CAPTURE_LIST_TYPE_MAX]);
1440 		__out(ebuf, "    Owner-Id: %d\n", node->reginfo[i].vfid);
1441 
1442 		switch (i) {
1443 		case GUC_CAPTURE_LIST_TYPE_GLOBAL:
1444 		default:
1445 			break;
1446 		case GUC_CAPTURE_LIST_TYPE_ENGINE_CLASS:
1447 			__out(ebuf, "    GuC-Eng-Class: %d\n", node->eng_class);
1448 			__out(ebuf, "    i915-Eng-Class: %d\n",
1449 			      guc_class_to_engine_class(node->eng_class));
1450 			break;
1451 		case GUC_CAPTURE_LIST_TYPE_ENGINE_INSTANCE:
1452 			eng = intel_guc_lookup_engine(guc, node->eng_class, node->eng_inst);
1453 			if (eng)
1454 				GCAP_PRINT_INTEL_ENG_INFO(ebuf, eng);
1455 			else
1456 				__out(ebuf, "    i915-Eng-Lookup Fail!\n");
1457 			GCAP_PRINT_GUC_INST_INFO(ebuf, node);
1458 			break;
1459 		}
1460 
1461 		numregs = node->reginfo[i].num_regs;
1462 		__out(ebuf, "    NumRegs: %d\n", numregs);
1463 		j = 0;
1464 		while (numregs--) {
1465 			regs = node->reginfo[i].regs;
1466 			str = guc_capture_reg_to_str(guc, GUC_CAPTURE_LIST_INDEX_PF, i,
1467 						     node->eng_class, 0, regs[j].offset, &is_ext);
1468 			if (!str)
1469 				__out(ebuf, "      REG-0x%08x", regs[j].offset);
1470 			else
1471 				__out(ebuf, "      %s", str);
1472 			if (is_ext)
1473 				__out(ebuf, "[%ld][%ld]",
1474 				      FIELD_GET(GUC_REGSET_STEERING_GROUP, regs[j].flags),
1475 				      FIELD_GET(GUC_REGSET_STEERING_INSTANCE, regs[j].flags));
1476 			__out(ebuf, ":  0x%08x\n", regs[j].value);
1477 			++j;
1478 		}
1479 	}
1480 	return 0;
1481 }
1482 
1483 #endif //CONFIG_DRM_I915_CAPTURE_ERROR
1484 
1485 void intel_guc_capture_free_node(struct intel_engine_coredump *ee)
1486 {
1487 	if (!ee || !ee->guc_capture_node)
1488 		return;
1489 
1490 	guc_capture_add_node_to_cachelist(ee->capture, ee->guc_capture_node);
1491 	ee->capture = NULL;
1492 	ee->guc_capture_node = NULL;
1493 }
1494 
1495 void intel_guc_capture_get_matching_node(struct intel_gt *gt,
1496 					 struct intel_engine_coredump *ee,
1497 					 struct intel_context *ce)
1498 {
1499 	struct __guc_capture_parsed_output *n, *ntmp;
1500 	struct drm_i915_private *i915;
1501 	struct intel_guc *guc;
1502 
1503 	if (!gt || !ee || !ce)
1504 		return;
1505 
1506 	i915 = gt->i915;
1507 	guc = &gt->uc.guc;
1508 	if (!guc->capture)
1509 		return;
1510 
1511 	GEM_BUG_ON(ee->guc_capture_node);
1512 	/*
1513 	 * Look for a matching GuC reported error capture node from
1514 	 * the internal output link-list based on lrca, guc-id and engine
1515 	 * identification.
1516 	 */
1517 	list_for_each_entry_safe(n, ntmp, &guc->capture->outlist, link) {
1518 		if (n->eng_inst == GUC_ID_TO_ENGINE_INSTANCE(ee->engine->guc_id) &&
1519 		    n->eng_class == GUC_ID_TO_ENGINE_CLASS(ee->engine->guc_id) &&
1520 		    n->guc_id && n->guc_id == ce->guc_id.id &&
1521 		    (n->lrca & CTX_GTT_ADDRESS_MASK) && (n->lrca & CTX_GTT_ADDRESS_MASK) ==
1522 		    (ce->lrc.lrca & CTX_GTT_ADDRESS_MASK)) {
1523 			list_del(&n->link);
1524 			ee->guc_capture_node = n;
1525 			ee->capture = guc->capture;
1526 			return;
1527 		}
1528 	}
1529 	drm_dbg(&i915->drm, "GuC capture can't match ee to node\n");
1530 }
1531 
1532 void intel_guc_capture_process(struct intel_guc *guc)
1533 {
1534 	if (guc->capture)
1535 		__guc_capture_process_output(guc);
1536 }
1537 
1538 static void
1539 guc_capture_free_ads_cache(struct intel_guc_state_capture *gc)
1540 {
1541 	int i, j, k;
1542 	struct __guc_capture_ads_cache *cache;
1543 
1544 	for (i = 0; i < GUC_CAPTURE_LIST_INDEX_MAX; ++i) {
1545 		for (j = 0; j < GUC_CAPTURE_LIST_TYPE_MAX; ++j) {
1546 			for (k = 0; k < GUC_MAX_ENGINE_CLASSES; ++k) {
1547 				cache = &gc->ads_cache[i][j][k];
1548 				if (cache->is_valid)
1549 					kfree(cache->ptr);
1550 			}
1551 		}
1552 	}
1553 	kfree(gc->ads_null_cache);
1554 }
1555 
1556 void intel_guc_capture_destroy(struct intel_guc *guc)
1557 {
1558 	if (!guc->capture)
1559 		return;
1560 
1561 	guc_capture_free_ads_cache(guc->capture);
1562 
1563 	guc_capture_delete_prealloc_nodes(guc);
1564 
1565 	guc_capture_free_extlists(guc->capture->extlists);
1566 	kfree(guc->capture->extlists);
1567 
1568 	kfree(guc->capture);
1569 	guc->capture = NULL;
1570 }
1571 
1572 int intel_guc_capture_init(struct intel_guc *guc)
1573 {
1574 	guc->capture = kzalloc(sizeof(*guc->capture), GFP_KERNEL);
1575 	if (!guc->capture)
1576 		return -ENOMEM;
1577 
1578 	guc->capture->reglists = guc_capture_get_device_reglist(guc);
1579 
1580 	INIT_LIST_HEAD(&guc->capture->outlist);
1581 	INIT_LIST_HEAD(&guc->capture->cachelist);
1582 
1583 	return 0;
1584 }
1585