xref: /linux/drivers/gpu/drm/xe/xe_guc_ct.c (revision e811c33b1f137be26a20444b79db8cbc1fca1c89)
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright © 2022 Intel Corporation
4  */
5 
6 #include "xe_guc_ct.h"
7 
8 #include <linux/bitfield.h>
9 #include <linux/circ_buf.h>
10 #include <linux/delay.h>
11 #include <linux/fault-inject.h>
12 
13 #include <kunit/static_stub.h>
14 
15 #include <drm/drm_managed.h>
16 
17 #include "abi/guc_actions_abi.h"
18 #include "abi/guc_actions_sriov_abi.h"
19 #include "abi/guc_klvs_abi.h"
20 #include "xe_bo.h"
21 #include "xe_devcoredump.h"
22 #include "xe_device.h"
23 #include "xe_gt.h"
24 #include "xe_gt_pagefault.h"
25 #include "xe_gt_printk.h"
26 #include "xe_gt_sriov_pf_control.h"
27 #include "xe_gt_sriov_pf_monitor.h"
28 #include "xe_gt_sriov_printk.h"
29 #include "xe_guc.h"
30 #include "xe_guc_log.h"
31 #include "xe_guc_relay.h"
32 #include "xe_guc_submit.h"
33 #include "xe_guc_tlb_inval.h"
34 #include "xe_map.h"
35 #include "xe_pm.h"
36 #include "xe_trace_guc.h"
37 
38 static void receive_g2h(struct xe_guc_ct *ct);
39 static void g2h_worker_func(struct work_struct *w);
40 static void safe_mode_worker_func(struct work_struct *w);
41 static void ct_exit_safe_mode(struct xe_guc_ct *ct);
42 static void guc_ct_change_state(struct xe_guc_ct *ct,
43 				enum xe_guc_ct_state state);
44 
45 #if IS_ENABLED(CONFIG_DRM_XE_DEBUG)
46 enum {
47 	/* Internal states, not error conditions */
48 	CT_DEAD_STATE_REARM,			/* 0x0001 */
49 	CT_DEAD_STATE_CAPTURE,			/* 0x0002 */
50 
51 	/* Error conditions */
52 	CT_DEAD_SETUP,				/* 0x0004 */
53 	CT_DEAD_H2G_WRITE,			/* 0x0008 */
54 	CT_DEAD_H2G_HAS_ROOM,			/* 0x0010 */
55 	CT_DEAD_G2H_READ,			/* 0x0020 */
56 	CT_DEAD_G2H_RECV,			/* 0x0040 */
57 	CT_DEAD_G2H_RELEASE,			/* 0x0080 */
58 	CT_DEAD_DEADLOCK,			/* 0x0100 */
59 	CT_DEAD_PROCESS_FAILED,			/* 0x0200 */
60 	CT_DEAD_FAST_G2H,			/* 0x0400 */
61 	CT_DEAD_PARSE_G2H_RESPONSE,		/* 0x0800 */
62 	CT_DEAD_PARSE_G2H_UNKNOWN,		/* 0x1000 */
63 	CT_DEAD_PARSE_G2H_ORIGIN,		/* 0x2000 */
64 	CT_DEAD_PARSE_G2H_TYPE,			/* 0x4000 */
65 	CT_DEAD_CRASH,				/* 0x8000 */
66 };
67 
68 static void ct_dead_worker_func(struct work_struct *w);
69 static void ct_dead_capture(struct xe_guc_ct *ct, struct guc_ctb *ctb, u32 reason_code);
70 
71 #define CT_DEAD(ct, ctb, reason_code)		ct_dead_capture((ct), (ctb), CT_DEAD_##reason_code)
72 #else
73 #define CT_DEAD(ct, ctb, reason)			\
74 	do {						\
75 		struct guc_ctb *_ctb = (ctb);		\
76 		if (_ctb)				\
77 			_ctb->info.broken = true;	\
78 	} while (0)
79 #endif
80 
81 /* Used when a CT send wants to block and / or receive data */
82 struct g2h_fence {
83 	u32 *response_buffer;
84 	u32 seqno;
85 	u32 response_data;
86 	u16 response_len;
87 	u16 error;
88 	u16 hint;
89 	u16 reason;
90 	bool cancel;
91 	bool retry;
92 	bool fail;
93 	bool done;
94 };
95 
96 #define make_u64(hi, lo) ((u64)((u64)(u32)(hi) << 32 | (u32)(lo)))
97 
g2h_fence_init(struct g2h_fence * g2h_fence,u32 * response_buffer)98 static void g2h_fence_init(struct g2h_fence *g2h_fence, u32 *response_buffer)
99 {
100 	memset(g2h_fence, 0, sizeof(*g2h_fence));
101 	g2h_fence->response_buffer = response_buffer;
102 	g2h_fence->seqno = ~0x0;
103 }
104 
g2h_fence_cancel(struct g2h_fence * g2h_fence)105 static void g2h_fence_cancel(struct g2h_fence *g2h_fence)
106 {
107 	g2h_fence->cancel = true;
108 	g2h_fence->fail = true;
109 	g2h_fence->done = true;
110 }
111 
g2h_fence_needs_alloc(struct g2h_fence * g2h_fence)112 static bool g2h_fence_needs_alloc(struct g2h_fence *g2h_fence)
113 {
114 	return g2h_fence->seqno == ~0x0;
115 }
116 
117 static struct xe_guc *
ct_to_guc(struct xe_guc_ct * ct)118 ct_to_guc(struct xe_guc_ct *ct)
119 {
120 	return container_of(ct, struct xe_guc, ct);
121 }
122 
123 static struct xe_gt *
ct_to_gt(struct xe_guc_ct * ct)124 ct_to_gt(struct xe_guc_ct *ct)
125 {
126 	return container_of(ct, struct xe_gt, uc.guc.ct);
127 }
128 
129 static struct xe_device *
ct_to_xe(struct xe_guc_ct * ct)130 ct_to_xe(struct xe_guc_ct *ct)
131 {
132 	return gt_to_xe(ct_to_gt(ct));
133 }
134 
135 /**
136  * DOC: GuC CTB Blob
137  *
138  * We allocate single blob to hold both CTB descriptors and buffers:
139  *
140  *      +--------+-----------------------------------------------+------+
141  *      | offset | contents                                      | size |
142  *      +========+===============================================+======+
143  *      | 0x0000 | H2G CTB Descriptor (send)                     |      |
144  *      +--------+-----------------------------------------------+  4K  |
145  *      | 0x0800 | G2H CTB Descriptor (g2h)                      |      |
146  *      +--------+-----------------------------------------------+------+
147  *      | 0x1000 | H2G CT Buffer (send)                          | n*4K |
148  *      |        |                                               |      |
149  *      +--------+-----------------------------------------------+------+
150  *      | 0x1000 | G2H CT Buffer (g2h)                           | m*4K |
151  *      | + n*4K |                                               |      |
152  *      +--------+-----------------------------------------------+------+
153  *
154  * Size of each ``CT Buffer`` must be multiple of 4K.
155  * We don't expect too many messages in flight at any time, unless we are
156  * using the GuC submission. In that case each request requires a minimum
157  * 2 dwords which gives us a maximum 256 queue'd requests. Hopefully this
158  * enough space to avoid backpressure on the driver. We increase the size
159  * of the receive buffer (relative to the send) to ensure a G2H response
160  * CTB has a landing spot.
161  *
162  * In addition to submissions, the G2H buffer needs to be able to hold
163  * enough space for recoverable page fault notifications. The number of
164  * page faults is interrupt driven and can be as much as the number of
165  * compute resources available. However, most of the actual work for these
166  * is in a separate page fault worker thread. Therefore we only need to
167  * make sure the queue has enough space to handle all of the submissions
168  * and responses and an extra buffer for incoming page faults.
169  */
170 
171 #define CTB_DESC_SIZE		ALIGN(sizeof(struct guc_ct_buffer_desc), SZ_2K)
172 #define CTB_H2G_BUFFER_SIZE	(SZ_4K)
173 #define CTB_G2H_BUFFER_SIZE	(SZ_128K)
174 #define G2H_ROOM_BUFFER_SIZE	(CTB_G2H_BUFFER_SIZE / 2)
175 
176 /**
177  * xe_guc_ct_queue_proc_time_jiffies - Return maximum time to process a full
178  * CT command queue
179  * @ct: the &xe_guc_ct. Unused at this moment but will be used in the future.
180  *
181  * Observation is that a 4KiB buffer full of commands takes a little over a
182  * second to process. Use that to calculate maximum time to process a full CT
183  * command queue.
184  *
185  * Return: Maximum time to process a full CT queue in jiffies.
186  */
xe_guc_ct_queue_proc_time_jiffies(struct xe_guc_ct * ct)187 long xe_guc_ct_queue_proc_time_jiffies(struct xe_guc_ct *ct)
188 {
189 	BUILD_BUG_ON(!IS_ALIGNED(CTB_H2G_BUFFER_SIZE, SZ_4));
190 	return (CTB_H2G_BUFFER_SIZE / SZ_4K) * HZ;
191 }
192 
guc_ct_size(void)193 static size_t guc_ct_size(void)
194 {
195 	return 2 * CTB_DESC_SIZE + CTB_H2G_BUFFER_SIZE +
196 		CTB_G2H_BUFFER_SIZE;
197 }
198 
guc_ct_fini(struct drm_device * drm,void * arg)199 static void guc_ct_fini(struct drm_device *drm, void *arg)
200 {
201 	struct xe_guc_ct *ct = arg;
202 
203 #if IS_ENABLED(CONFIG_DRM_XE_DEBUG)
204 	cancel_work_sync(&ct->dead.worker);
205 #endif
206 	ct_exit_safe_mode(ct);
207 	destroy_workqueue(ct->g2h_wq);
208 	xa_destroy(&ct->fence_lookup);
209 }
210 
primelockdep(struct xe_guc_ct * ct)211 static void primelockdep(struct xe_guc_ct *ct)
212 {
213 	if (!IS_ENABLED(CONFIG_LOCKDEP))
214 		return;
215 
216 	fs_reclaim_acquire(GFP_KERNEL);
217 	might_lock(&ct->lock);
218 	fs_reclaim_release(GFP_KERNEL);
219 }
220 
xe_guc_ct_init_noalloc(struct xe_guc_ct * ct)221 int xe_guc_ct_init_noalloc(struct xe_guc_ct *ct)
222 {
223 	struct xe_device *xe = ct_to_xe(ct);
224 	struct xe_gt *gt = ct_to_gt(ct);
225 	int err;
226 
227 	xe_gt_assert(gt, !(guc_ct_size() % PAGE_SIZE));
228 
229 	ct->g2h_wq = alloc_ordered_workqueue("xe-g2h-wq", WQ_MEM_RECLAIM);
230 	if (!ct->g2h_wq)
231 		return -ENOMEM;
232 
233 	spin_lock_init(&ct->fast_lock);
234 	xa_init(&ct->fence_lookup);
235 	INIT_WORK(&ct->g2h_worker, g2h_worker_func);
236 	INIT_DELAYED_WORK(&ct->safe_mode_worker, safe_mode_worker_func);
237 #if IS_ENABLED(CONFIG_DRM_XE_DEBUG)
238 	spin_lock_init(&ct->dead.lock);
239 	INIT_WORK(&ct->dead.worker, ct_dead_worker_func);
240 #endif
241 	init_waitqueue_head(&ct->wq);
242 	init_waitqueue_head(&ct->g2h_fence_wq);
243 
244 	err = drmm_mutex_init(&xe->drm, &ct->lock);
245 	if (err)
246 		return err;
247 
248 	primelockdep(ct);
249 
250 	err = drmm_add_action_or_reset(&xe->drm, guc_ct_fini, ct);
251 	if (err)
252 		return err;
253 
254 	xe_gt_assert(gt, ct->state == XE_GUC_CT_STATE_NOT_INITIALIZED);
255 	ct->state = XE_GUC_CT_STATE_DISABLED;
256 	return 0;
257 }
258 ALLOW_ERROR_INJECTION(xe_guc_ct_init_noalloc, ERRNO); /* See xe_pci_probe() */
259 
guc_action_disable_ct(void * arg)260 static void guc_action_disable_ct(void *arg)
261 {
262 	struct xe_guc_ct *ct = arg;
263 
264 	guc_ct_change_state(ct, XE_GUC_CT_STATE_DISABLED);
265 }
266 
xe_guc_ct_init(struct xe_guc_ct * ct)267 int xe_guc_ct_init(struct xe_guc_ct *ct)
268 {
269 	struct xe_device *xe = ct_to_xe(ct);
270 	struct xe_gt *gt = ct_to_gt(ct);
271 	struct xe_tile *tile = gt_to_tile(gt);
272 	struct xe_bo *bo;
273 
274 	bo = xe_managed_bo_create_pin_map(xe, tile, guc_ct_size(),
275 					  XE_BO_FLAG_SYSTEM |
276 					  XE_BO_FLAG_GGTT |
277 					  XE_BO_FLAG_GGTT_INVALIDATE |
278 					  XE_BO_FLAG_PINNED_NORESTORE);
279 	if (IS_ERR(bo))
280 		return PTR_ERR(bo);
281 
282 	ct->bo = bo;
283 
284 	return devm_add_action_or_reset(xe->drm.dev, guc_action_disable_ct, ct);
285 }
286 ALLOW_ERROR_INJECTION(xe_guc_ct_init, ERRNO); /* See xe_pci_probe() */
287 
288 /**
289  * xe_guc_ct_init_post_hwconfig - Reinitialize the GuC CTB in VRAM
290  * @ct: the &xe_guc_ct
291  *
292  * Allocate a new BO in VRAM and free the previous BO that was allocated
293  * in system memory (SMEM). Applicable only for DGFX products.
294  *
295  * Return: 0 on success, or a negative errno on failure.
296  */
xe_guc_ct_init_post_hwconfig(struct xe_guc_ct * ct)297 int xe_guc_ct_init_post_hwconfig(struct xe_guc_ct *ct)
298 {
299 	struct xe_device *xe = ct_to_xe(ct);
300 	struct xe_gt *gt = ct_to_gt(ct);
301 	struct xe_tile *tile = gt_to_tile(gt);
302 	int ret;
303 
304 	xe_assert(xe, !xe_guc_ct_enabled(ct));
305 
306 	if (IS_DGFX(xe)) {
307 		ret = xe_managed_bo_reinit_in_vram(xe, tile, &ct->bo);
308 		if (ret)
309 			return ret;
310 	}
311 
312 	devm_remove_action(xe->drm.dev, guc_action_disable_ct, ct);
313 	return devm_add_action_or_reset(xe->drm.dev, guc_action_disable_ct, ct);
314 }
315 
316 #define desc_read(xe_, guc_ctb__, field_)			\
317 	xe_map_rd_field(xe_, &guc_ctb__->desc, 0,		\
318 			struct guc_ct_buffer_desc, field_)
319 
320 #define desc_write(xe_, guc_ctb__, field_, val_)		\
321 	xe_map_wr_field(xe_, &guc_ctb__->desc, 0,		\
322 			struct guc_ct_buffer_desc, field_, val_)
323 
guc_ct_ctb_h2g_init(struct xe_device * xe,struct guc_ctb * h2g,struct iosys_map * map)324 static void guc_ct_ctb_h2g_init(struct xe_device *xe, struct guc_ctb *h2g,
325 				struct iosys_map *map)
326 {
327 	h2g->info.size = CTB_H2G_BUFFER_SIZE / sizeof(u32);
328 	h2g->info.resv_space = 0;
329 	h2g->info.tail = 0;
330 	h2g->info.head = 0;
331 	h2g->info.space = CIRC_SPACE(h2g->info.tail, h2g->info.head,
332 				     h2g->info.size) -
333 			  h2g->info.resv_space;
334 	h2g->info.broken = false;
335 
336 	h2g->desc = *map;
337 	xe_map_memset(xe, &h2g->desc, 0, 0, sizeof(struct guc_ct_buffer_desc));
338 
339 	h2g->cmds = IOSYS_MAP_INIT_OFFSET(map, CTB_DESC_SIZE * 2);
340 }
341 
guc_ct_ctb_g2h_init(struct xe_device * xe,struct guc_ctb * g2h,struct iosys_map * map)342 static void guc_ct_ctb_g2h_init(struct xe_device *xe, struct guc_ctb *g2h,
343 				struct iosys_map *map)
344 {
345 	g2h->info.size = CTB_G2H_BUFFER_SIZE / sizeof(u32);
346 	g2h->info.resv_space = G2H_ROOM_BUFFER_SIZE / sizeof(u32);
347 	g2h->info.head = 0;
348 	g2h->info.tail = 0;
349 	g2h->info.space = CIRC_SPACE(g2h->info.tail, g2h->info.head,
350 				     g2h->info.size) -
351 			  g2h->info.resv_space;
352 	g2h->info.broken = false;
353 
354 	g2h->desc = IOSYS_MAP_INIT_OFFSET(map, CTB_DESC_SIZE);
355 	xe_map_memset(xe, &g2h->desc, 0, 0, sizeof(struct guc_ct_buffer_desc));
356 
357 	g2h->cmds = IOSYS_MAP_INIT_OFFSET(map, CTB_DESC_SIZE * 2 +
358 					    CTB_H2G_BUFFER_SIZE);
359 }
360 
guc_ct_ctb_h2g_register(struct xe_guc_ct * ct)361 static int guc_ct_ctb_h2g_register(struct xe_guc_ct *ct)
362 {
363 	struct xe_guc *guc = ct_to_guc(ct);
364 	u32 desc_addr, ctb_addr, size;
365 	int err;
366 
367 	desc_addr = xe_bo_ggtt_addr(ct->bo);
368 	ctb_addr = xe_bo_ggtt_addr(ct->bo) + CTB_DESC_SIZE * 2;
369 	size = ct->ctbs.h2g.info.size * sizeof(u32);
370 
371 	err = xe_guc_self_cfg64(guc,
372 				GUC_KLV_SELF_CFG_H2G_CTB_DESCRIPTOR_ADDR_KEY,
373 				desc_addr);
374 	if (err)
375 		return err;
376 
377 	err = xe_guc_self_cfg64(guc,
378 				GUC_KLV_SELF_CFG_H2G_CTB_ADDR_KEY,
379 				ctb_addr);
380 	if (err)
381 		return err;
382 
383 	return xe_guc_self_cfg32(guc,
384 				 GUC_KLV_SELF_CFG_H2G_CTB_SIZE_KEY,
385 				 size);
386 }
387 
guc_ct_ctb_g2h_register(struct xe_guc_ct * ct)388 static int guc_ct_ctb_g2h_register(struct xe_guc_ct *ct)
389 {
390 	struct xe_guc *guc = ct_to_guc(ct);
391 	u32 desc_addr, ctb_addr, size;
392 	int err;
393 
394 	desc_addr = xe_bo_ggtt_addr(ct->bo) + CTB_DESC_SIZE;
395 	ctb_addr = xe_bo_ggtt_addr(ct->bo) + CTB_DESC_SIZE * 2 +
396 		CTB_H2G_BUFFER_SIZE;
397 	size = ct->ctbs.g2h.info.size * sizeof(u32);
398 
399 	err = xe_guc_self_cfg64(guc,
400 				GUC_KLV_SELF_CFG_G2H_CTB_DESCRIPTOR_ADDR_KEY,
401 				desc_addr);
402 	if (err)
403 		return err;
404 
405 	err = xe_guc_self_cfg64(guc,
406 				GUC_KLV_SELF_CFG_G2H_CTB_ADDR_KEY,
407 				ctb_addr);
408 	if (err)
409 		return err;
410 
411 	return xe_guc_self_cfg32(guc,
412 				 GUC_KLV_SELF_CFG_G2H_CTB_SIZE_KEY,
413 				 size);
414 }
415 
guc_ct_control_toggle(struct xe_guc_ct * ct,bool enable)416 static int guc_ct_control_toggle(struct xe_guc_ct *ct, bool enable)
417 {
418 	u32 request[HOST2GUC_CONTROL_CTB_REQUEST_MSG_LEN] = {
419 		FIELD_PREP(GUC_HXG_MSG_0_ORIGIN, GUC_HXG_ORIGIN_HOST) |
420 		FIELD_PREP(GUC_HXG_MSG_0_TYPE, GUC_HXG_TYPE_REQUEST) |
421 		FIELD_PREP(GUC_HXG_REQUEST_MSG_0_ACTION,
422 			   GUC_ACTION_HOST2GUC_CONTROL_CTB),
423 		FIELD_PREP(HOST2GUC_CONTROL_CTB_REQUEST_MSG_1_CONTROL,
424 			   enable ? GUC_CTB_CONTROL_ENABLE :
425 			   GUC_CTB_CONTROL_DISABLE),
426 	};
427 	int ret = xe_guc_mmio_send(ct_to_guc(ct), request, ARRAY_SIZE(request));
428 
429 	return ret > 0 ? -EPROTO : ret;
430 }
431 
guc_ct_change_state(struct xe_guc_ct * ct,enum xe_guc_ct_state state)432 static void guc_ct_change_state(struct xe_guc_ct *ct,
433 				enum xe_guc_ct_state state)
434 {
435 	struct xe_gt *gt = ct_to_gt(ct);
436 	struct g2h_fence *g2h_fence;
437 	unsigned long idx;
438 
439 	mutex_lock(&ct->lock);		/* Serialise dequeue_one_g2h() */
440 	spin_lock_irq(&ct->fast_lock);	/* Serialise CT fast-path */
441 
442 	xe_gt_assert(ct_to_gt(ct), ct->g2h_outstanding == 0 ||
443 		     state == XE_GUC_CT_STATE_STOPPED);
444 
445 	if (ct->g2h_outstanding)
446 		xe_pm_runtime_put(ct_to_xe(ct));
447 	ct->g2h_outstanding = 0;
448 	ct->state = state;
449 
450 	xe_gt_dbg(gt, "GuC CT communication channel %s\n",
451 		  state == XE_GUC_CT_STATE_STOPPED ? "stopped" :
452 		  str_enabled_disabled(state == XE_GUC_CT_STATE_ENABLED));
453 
454 	spin_unlock_irq(&ct->fast_lock);
455 
456 	/* cancel all in-flight send-recv requests */
457 	xa_for_each(&ct->fence_lookup, idx, g2h_fence)
458 		g2h_fence_cancel(g2h_fence);
459 
460 	/* make sure guc_ct_send_recv() will see g2h_fence changes */
461 	smp_mb();
462 	wake_up_all(&ct->g2h_fence_wq);
463 
464 	/*
465 	 * Lockdep doesn't like this under the fast lock and he destroy only
466 	 * needs to be serialized with the send path which ct lock provides.
467 	 */
468 	xa_destroy(&ct->fence_lookup);
469 
470 	mutex_unlock(&ct->lock);
471 }
472 
ct_needs_safe_mode(struct xe_guc_ct * ct)473 static bool ct_needs_safe_mode(struct xe_guc_ct *ct)
474 {
475 	return !pci_dev_msi_enabled(to_pci_dev(ct_to_xe(ct)->drm.dev));
476 }
477 
ct_restart_safe_mode_worker(struct xe_guc_ct * ct)478 static bool ct_restart_safe_mode_worker(struct xe_guc_ct *ct)
479 {
480 	if (!ct_needs_safe_mode(ct))
481 		return false;
482 
483 	queue_delayed_work(ct->g2h_wq, &ct->safe_mode_worker, HZ / 10);
484 	return true;
485 }
486 
safe_mode_worker_func(struct work_struct * w)487 static void safe_mode_worker_func(struct work_struct *w)
488 {
489 	struct xe_guc_ct *ct = container_of(w, struct xe_guc_ct, safe_mode_worker.work);
490 
491 	receive_g2h(ct);
492 
493 	if (!ct_restart_safe_mode_worker(ct))
494 		xe_gt_dbg(ct_to_gt(ct), "GuC CT safe-mode canceled\n");
495 }
496 
ct_enter_safe_mode(struct xe_guc_ct * ct)497 static void ct_enter_safe_mode(struct xe_guc_ct *ct)
498 {
499 	if (ct_restart_safe_mode_worker(ct))
500 		xe_gt_dbg(ct_to_gt(ct), "GuC CT safe-mode enabled\n");
501 }
502 
ct_exit_safe_mode(struct xe_guc_ct * ct)503 static void ct_exit_safe_mode(struct xe_guc_ct *ct)
504 {
505 	if (cancel_delayed_work_sync(&ct->safe_mode_worker))
506 		xe_gt_dbg(ct_to_gt(ct), "GuC CT safe-mode disabled\n");
507 }
508 
xe_guc_ct_enable(struct xe_guc_ct * ct)509 int xe_guc_ct_enable(struct xe_guc_ct *ct)
510 {
511 	struct xe_device *xe = ct_to_xe(ct);
512 	struct xe_gt *gt = ct_to_gt(ct);
513 	int err;
514 
515 	xe_gt_assert(gt, !xe_guc_ct_enabled(ct));
516 
517 	xe_map_memset(xe, &ct->bo->vmap, 0, 0, xe_bo_size(ct->bo));
518 	guc_ct_ctb_h2g_init(xe, &ct->ctbs.h2g, &ct->bo->vmap);
519 	guc_ct_ctb_g2h_init(xe, &ct->ctbs.g2h, &ct->bo->vmap);
520 
521 	err = guc_ct_ctb_h2g_register(ct);
522 	if (err)
523 		goto err_out;
524 
525 	err = guc_ct_ctb_g2h_register(ct);
526 	if (err)
527 		goto err_out;
528 
529 	err = guc_ct_control_toggle(ct, true);
530 	if (err)
531 		goto err_out;
532 
533 	guc_ct_change_state(ct, XE_GUC_CT_STATE_ENABLED);
534 
535 	smp_mb();
536 	wake_up_all(&ct->wq);
537 
538 	if (ct_needs_safe_mode(ct))
539 		ct_enter_safe_mode(ct);
540 
541 #if IS_ENABLED(CONFIG_DRM_XE_DEBUG)
542 	/*
543 	 * The CT has now been reset so the dumper can be re-armed
544 	 * after any existing dead state has been dumped.
545 	 */
546 	spin_lock_irq(&ct->dead.lock);
547 	if (ct->dead.reason) {
548 		ct->dead.reason |= (1 << CT_DEAD_STATE_REARM);
549 		queue_work(system_unbound_wq, &ct->dead.worker);
550 	}
551 	spin_unlock_irq(&ct->dead.lock);
552 #endif
553 
554 	return 0;
555 
556 err_out:
557 	xe_gt_err(gt, "Failed to enable GuC CT (%pe)\n", ERR_PTR(err));
558 	CT_DEAD(ct, NULL, SETUP);
559 
560 	return err;
561 }
562 
stop_g2h_handler(struct xe_guc_ct * ct)563 static void stop_g2h_handler(struct xe_guc_ct *ct)
564 {
565 	cancel_work_sync(&ct->g2h_worker);
566 }
567 
568 /**
569  * xe_guc_ct_disable - Set GuC to disabled state
570  * @ct: the &xe_guc_ct
571  *
572  * Set GuC CT to disabled state and stop g2h handler. No outstanding g2h expected
573  * in this transition.
574  */
xe_guc_ct_disable(struct xe_guc_ct * ct)575 void xe_guc_ct_disable(struct xe_guc_ct *ct)
576 {
577 	guc_ct_change_state(ct, XE_GUC_CT_STATE_DISABLED);
578 	ct_exit_safe_mode(ct);
579 	stop_g2h_handler(ct);
580 }
581 
582 /**
583  * xe_guc_ct_stop - Set GuC to stopped state
584  * @ct: the &xe_guc_ct
585  *
586  * Set GuC CT to stopped state, stop g2h handler, and clear any outstanding g2h
587  */
xe_guc_ct_stop(struct xe_guc_ct * ct)588 void xe_guc_ct_stop(struct xe_guc_ct *ct)
589 {
590 	if (!xe_guc_ct_initialized(ct))
591 		return;
592 
593 	guc_ct_change_state(ct, XE_GUC_CT_STATE_STOPPED);
594 	stop_g2h_handler(ct);
595 }
596 
h2g_has_room(struct xe_guc_ct * ct,u32 cmd_len)597 static bool h2g_has_room(struct xe_guc_ct *ct, u32 cmd_len)
598 {
599 	struct guc_ctb *h2g = &ct->ctbs.h2g;
600 
601 	lockdep_assert_held(&ct->lock);
602 
603 	if (cmd_len > h2g->info.space) {
604 		h2g->info.head = desc_read(ct_to_xe(ct), h2g, head);
605 
606 		if (h2g->info.head > h2g->info.size) {
607 			struct xe_device *xe = ct_to_xe(ct);
608 			u32 desc_status = desc_read(xe, h2g, status);
609 
610 			desc_write(xe, h2g, status, desc_status | GUC_CTB_STATUS_OVERFLOW);
611 
612 			xe_gt_err(ct_to_gt(ct), "CT: invalid head offset %u >= %u)\n",
613 				  h2g->info.head, h2g->info.size);
614 			CT_DEAD(ct, h2g, H2G_HAS_ROOM);
615 			return false;
616 		}
617 
618 		h2g->info.space = CIRC_SPACE(h2g->info.tail, h2g->info.head,
619 					     h2g->info.size) -
620 				  h2g->info.resv_space;
621 		if (cmd_len > h2g->info.space)
622 			return false;
623 	}
624 
625 	return true;
626 }
627 
g2h_has_room(struct xe_guc_ct * ct,u32 g2h_len)628 static bool g2h_has_room(struct xe_guc_ct *ct, u32 g2h_len)
629 {
630 	if (!g2h_len)
631 		return true;
632 
633 	lockdep_assert_held(&ct->fast_lock);
634 
635 	return ct->ctbs.g2h.info.space > g2h_len;
636 }
637 
has_room(struct xe_guc_ct * ct,u32 cmd_len,u32 g2h_len)638 static int has_room(struct xe_guc_ct *ct, u32 cmd_len, u32 g2h_len)
639 {
640 	lockdep_assert_held(&ct->lock);
641 
642 	if (!g2h_has_room(ct, g2h_len) || !h2g_has_room(ct, cmd_len))
643 		return -EBUSY;
644 
645 	return 0;
646 }
647 
h2g_reserve_space(struct xe_guc_ct * ct,u32 cmd_len)648 static void h2g_reserve_space(struct xe_guc_ct *ct, u32 cmd_len)
649 {
650 	lockdep_assert_held(&ct->lock);
651 	ct->ctbs.h2g.info.space -= cmd_len;
652 }
653 
__g2h_reserve_space(struct xe_guc_ct * ct,u32 g2h_len,u32 num_g2h)654 static void __g2h_reserve_space(struct xe_guc_ct *ct, u32 g2h_len, u32 num_g2h)
655 {
656 	xe_gt_assert(ct_to_gt(ct), g2h_len <= ct->ctbs.g2h.info.space);
657 	xe_gt_assert(ct_to_gt(ct), (!g2h_len && !num_g2h) ||
658 		     (g2h_len && num_g2h));
659 
660 	if (g2h_len) {
661 		lockdep_assert_held(&ct->fast_lock);
662 
663 		if (!ct->g2h_outstanding)
664 			xe_pm_runtime_get_noresume(ct_to_xe(ct));
665 
666 		ct->ctbs.g2h.info.space -= g2h_len;
667 		ct->g2h_outstanding += num_g2h;
668 	}
669 }
670 
__g2h_release_space(struct xe_guc_ct * ct,u32 g2h_len)671 static void __g2h_release_space(struct xe_guc_ct *ct, u32 g2h_len)
672 {
673 	bool bad = false;
674 
675 	lockdep_assert_held(&ct->fast_lock);
676 
677 	bad = ct->ctbs.g2h.info.space + g2h_len >
678 		     ct->ctbs.g2h.info.size - ct->ctbs.g2h.info.resv_space;
679 	bad |= !ct->g2h_outstanding;
680 
681 	if (bad) {
682 		xe_gt_err(ct_to_gt(ct), "Invalid G2H release: %d + %d vs %d - %d -> %d vs %d, outstanding = %d!\n",
683 			  ct->ctbs.g2h.info.space, g2h_len,
684 			  ct->ctbs.g2h.info.size, ct->ctbs.g2h.info.resv_space,
685 			  ct->ctbs.g2h.info.space + g2h_len,
686 			  ct->ctbs.g2h.info.size - ct->ctbs.g2h.info.resv_space,
687 			  ct->g2h_outstanding);
688 		CT_DEAD(ct, &ct->ctbs.g2h, G2H_RELEASE);
689 		return;
690 	}
691 
692 	ct->ctbs.g2h.info.space += g2h_len;
693 	if (!--ct->g2h_outstanding)
694 		xe_pm_runtime_put(ct_to_xe(ct));
695 }
696 
g2h_release_space(struct xe_guc_ct * ct,u32 g2h_len)697 static void g2h_release_space(struct xe_guc_ct *ct, u32 g2h_len)
698 {
699 	spin_lock_irq(&ct->fast_lock);
700 	__g2h_release_space(ct, g2h_len);
701 	spin_unlock_irq(&ct->fast_lock);
702 }
703 
704 #if IS_ENABLED(CONFIG_DRM_XE_DEBUG)
fast_req_track(struct xe_guc_ct * ct,u16 fence,u16 action)705 static void fast_req_track(struct xe_guc_ct *ct, u16 fence, u16 action)
706 {
707 	unsigned int slot = fence % ARRAY_SIZE(ct->fast_req);
708 #if IS_ENABLED(CONFIG_DRM_XE_DEBUG_GUC)
709 	unsigned long entries[SZ_32];
710 	unsigned int n;
711 
712 	n = stack_trace_save(entries, ARRAY_SIZE(entries), 1);
713 
714 	/* May be called under spinlock, so avoid sleeping */
715 	ct->fast_req[slot].stack = stack_depot_save(entries, n, GFP_NOWAIT);
716 #endif
717 	ct->fast_req[slot].fence = fence;
718 	ct->fast_req[slot].action = action;
719 }
720 #else
fast_req_track(struct xe_guc_ct * ct,u16 fence,u16 action)721 static void fast_req_track(struct xe_guc_ct *ct, u16 fence, u16 action)
722 {
723 }
724 #endif
725 
726 /*
727  * The CT protocol accepts a 16 bits fence. This field is fully owned by the
728  * driver, the GuC will just copy it to the reply message. Since we need to
729  * be able to distinguish between replies to REQUEST and FAST_REQUEST messages,
730  * we use one bit of the seqno as an indicator for that and a rolling counter
731  * for the remaining 15 bits.
732  */
733 #define CT_SEQNO_MASK GENMASK(14, 0)
734 #define CT_SEQNO_UNTRACKED BIT(15)
next_ct_seqno(struct xe_guc_ct * ct,bool is_g2h_fence)735 static u16 next_ct_seqno(struct xe_guc_ct *ct, bool is_g2h_fence)
736 {
737 	u32 seqno = ct->fence_seqno++ & CT_SEQNO_MASK;
738 
739 	if (!is_g2h_fence)
740 		seqno |= CT_SEQNO_UNTRACKED;
741 
742 	return seqno;
743 }
744 
745 #define H2G_CT_HEADERS (GUC_CTB_HDR_LEN + 1) /* one DW CTB header and one DW HxG header */
746 
h2g_write(struct xe_guc_ct * ct,const u32 * action,u32 len,u32 ct_fence_value,bool want_response)747 static int h2g_write(struct xe_guc_ct *ct, const u32 *action, u32 len,
748 		     u32 ct_fence_value, bool want_response)
749 {
750 	struct xe_device *xe = ct_to_xe(ct);
751 	struct xe_gt *gt = ct_to_gt(ct);
752 	struct guc_ctb *h2g = &ct->ctbs.h2g;
753 	u32 cmd[H2G_CT_HEADERS];
754 	u32 tail = h2g->info.tail;
755 	u32 full_len;
756 	struct iosys_map map = IOSYS_MAP_INIT_OFFSET(&h2g->cmds,
757 							 tail * sizeof(u32));
758 	u32 desc_status;
759 
760 	full_len = len + GUC_CTB_HDR_LEN;
761 
762 	lockdep_assert_held(&ct->lock);
763 	xe_gt_assert(gt, full_len <= GUC_CTB_MSG_MAX_LEN);
764 
765 	desc_status = desc_read(xe, h2g, status);
766 	if (desc_status) {
767 		xe_gt_err(gt, "CT write: non-zero status: %u\n", desc_status);
768 		goto corrupted;
769 	}
770 
771 	if (IS_ENABLED(CONFIG_DRM_XE_DEBUG)) {
772 		u32 desc_tail = desc_read(xe, h2g, tail);
773 		u32 desc_head = desc_read(xe, h2g, head);
774 
775 		if (tail != desc_tail) {
776 			desc_write(xe, h2g, status, desc_status | GUC_CTB_STATUS_MISMATCH);
777 			xe_gt_err(gt, "CT write: tail was modified %u != %u\n", desc_tail, tail);
778 			goto corrupted;
779 		}
780 
781 		if (tail > h2g->info.size) {
782 			desc_write(xe, h2g, status, desc_status | GUC_CTB_STATUS_OVERFLOW);
783 			xe_gt_err(gt, "CT write: tail out of range: %u vs %u\n",
784 				  tail, h2g->info.size);
785 			goto corrupted;
786 		}
787 
788 		if (desc_head >= h2g->info.size) {
789 			desc_write(xe, h2g, status, desc_status | GUC_CTB_STATUS_OVERFLOW);
790 			xe_gt_err(gt, "CT write: invalid head offset %u >= %u)\n",
791 				  desc_head, h2g->info.size);
792 			goto corrupted;
793 		}
794 	}
795 
796 	/* Command will wrap, zero fill (NOPs), return and check credits again */
797 	if (tail + full_len > h2g->info.size) {
798 		xe_map_memset(xe, &map, 0, 0,
799 			      (h2g->info.size - tail) * sizeof(u32));
800 		h2g_reserve_space(ct, (h2g->info.size - tail));
801 		h2g->info.tail = 0;
802 		desc_write(xe, h2g, tail, h2g->info.tail);
803 
804 		return -EAGAIN;
805 	}
806 
807 	/*
808 	 * dw0: CT header (including fence)
809 	 * dw1: HXG header (including action code)
810 	 * dw2+: action data
811 	 */
812 	cmd[0] = FIELD_PREP(GUC_CTB_MSG_0_FORMAT, GUC_CTB_FORMAT_HXG) |
813 		FIELD_PREP(GUC_CTB_MSG_0_NUM_DWORDS, len) |
814 		FIELD_PREP(GUC_CTB_MSG_0_FENCE, ct_fence_value);
815 	if (want_response) {
816 		cmd[1] =
817 			FIELD_PREP(GUC_HXG_MSG_0_TYPE, GUC_HXG_TYPE_REQUEST) |
818 			FIELD_PREP(GUC_HXG_EVENT_MSG_0_ACTION |
819 				   GUC_HXG_EVENT_MSG_0_DATA0, action[0]);
820 	} else {
821 		fast_req_track(ct, ct_fence_value,
822 			       FIELD_GET(GUC_HXG_EVENT_MSG_0_ACTION, action[0]));
823 
824 		cmd[1] =
825 			FIELD_PREP(GUC_HXG_MSG_0_TYPE, GUC_HXG_TYPE_FAST_REQUEST) |
826 			FIELD_PREP(GUC_HXG_EVENT_MSG_0_ACTION |
827 				   GUC_HXG_EVENT_MSG_0_DATA0, action[0]);
828 	}
829 
830 	/* H2G header in cmd[1] replaces action[0] so: */
831 	--len;
832 	++action;
833 
834 	/* Write H2G ensuring visible before descriptor update */
835 	xe_map_memcpy_to(xe, &map, 0, cmd, H2G_CT_HEADERS * sizeof(u32));
836 	xe_map_memcpy_to(xe, &map, H2G_CT_HEADERS * sizeof(u32), action, len * sizeof(u32));
837 	xe_device_wmb(xe);
838 
839 	/* Update local copies */
840 	h2g->info.tail = (tail + full_len) % h2g->info.size;
841 	h2g_reserve_space(ct, full_len);
842 
843 	/* Update descriptor */
844 	desc_write(xe, h2g, tail, h2g->info.tail);
845 
846 	trace_xe_guc_ctb_h2g(xe, gt->info.id, *(action - 1), full_len,
847 			     desc_read(xe, h2g, head), h2g->info.tail);
848 
849 	return 0;
850 
851 corrupted:
852 	CT_DEAD(ct, &ct->ctbs.h2g, H2G_WRITE);
853 	return -EPIPE;
854 }
855 
__guc_ct_send_locked(struct xe_guc_ct * ct,const u32 * action,u32 len,u32 g2h_len,u32 num_g2h,struct g2h_fence * g2h_fence)856 static int __guc_ct_send_locked(struct xe_guc_ct *ct, const u32 *action,
857 				u32 len, u32 g2h_len, u32 num_g2h,
858 				struct g2h_fence *g2h_fence)
859 {
860 	struct xe_gt *gt __maybe_unused = ct_to_gt(ct);
861 	u16 seqno;
862 	int ret;
863 
864 	xe_gt_assert(gt, xe_guc_ct_initialized(ct));
865 	xe_gt_assert(gt, !g2h_len || !g2h_fence);
866 	xe_gt_assert(gt, !num_g2h || !g2h_fence);
867 	xe_gt_assert(gt, !g2h_len || num_g2h);
868 	xe_gt_assert(gt, g2h_len || !num_g2h);
869 	lockdep_assert_held(&ct->lock);
870 
871 	if (unlikely(ct->ctbs.h2g.info.broken)) {
872 		ret = -EPIPE;
873 		goto out;
874 	}
875 
876 	if (ct->state == XE_GUC_CT_STATE_DISABLED) {
877 		ret = -ENODEV;
878 		goto out;
879 	}
880 
881 	if (ct->state == XE_GUC_CT_STATE_STOPPED) {
882 		ret = -ECANCELED;
883 		goto out;
884 	}
885 
886 	xe_gt_assert(gt, xe_guc_ct_enabled(ct));
887 
888 	if (g2h_fence) {
889 		g2h_len = GUC_CTB_HXG_MSG_MAX_LEN;
890 		num_g2h = 1;
891 
892 		if (g2h_fence_needs_alloc(g2h_fence)) {
893 			g2h_fence->seqno = next_ct_seqno(ct, true);
894 			ret = xa_err(xa_store(&ct->fence_lookup,
895 					      g2h_fence->seqno, g2h_fence,
896 					      GFP_ATOMIC));
897 			if (ret)
898 				goto out;
899 		}
900 
901 		seqno = g2h_fence->seqno;
902 	} else {
903 		seqno = next_ct_seqno(ct, false);
904 	}
905 
906 	if (g2h_len)
907 		spin_lock_irq(&ct->fast_lock);
908 retry:
909 	ret = has_room(ct, len + GUC_CTB_HDR_LEN, g2h_len);
910 	if (unlikely(ret))
911 		goto out_unlock;
912 
913 	ret = h2g_write(ct, action, len, seqno, !!g2h_fence);
914 	if (unlikely(ret)) {
915 		if (ret == -EAGAIN)
916 			goto retry;
917 		goto out_unlock;
918 	}
919 
920 	__g2h_reserve_space(ct, g2h_len, num_g2h);
921 	xe_guc_notify(ct_to_guc(ct));
922 out_unlock:
923 	if (g2h_len)
924 		spin_unlock_irq(&ct->fast_lock);
925 out:
926 	return ret;
927 }
928 
kick_reset(struct xe_guc_ct * ct)929 static void kick_reset(struct xe_guc_ct *ct)
930 {
931 	xe_gt_reset_async(ct_to_gt(ct));
932 }
933 
934 static int dequeue_one_g2h(struct xe_guc_ct *ct);
935 
guc_ct_send_locked(struct xe_guc_ct * ct,const u32 * action,u32 len,u32 g2h_len,u32 num_g2h,struct g2h_fence * g2h_fence)936 static int guc_ct_send_locked(struct xe_guc_ct *ct, const u32 *action, u32 len,
937 			      u32 g2h_len, u32 num_g2h,
938 			      struct g2h_fence *g2h_fence)
939 {
940 	struct xe_device *xe = ct_to_xe(ct);
941 	struct xe_gt *gt = ct_to_gt(ct);
942 	unsigned int sleep_period_ms = 1;
943 	int ret;
944 
945 	xe_gt_assert(gt, !g2h_len || !g2h_fence);
946 	lockdep_assert_held(&ct->lock);
947 	xe_device_assert_mem_access(ct_to_xe(ct));
948 
949 try_again:
950 	ret = __guc_ct_send_locked(ct, action, len, g2h_len, num_g2h,
951 				   g2h_fence);
952 
953 	/*
954 	 * We wait to try to restore credits for about 1 second before bailing.
955 	 * In the case of H2G credits we have no choice but just to wait for the
956 	 * GuC to consume H2Gs in the channel so we use a wait / sleep loop. In
957 	 * the case of G2H we process any G2H in the channel, hopefully freeing
958 	 * credits as we consume the G2H messages.
959 	 */
960 	if (unlikely(ret == -EBUSY &&
961 		     !h2g_has_room(ct, len + GUC_CTB_HDR_LEN))) {
962 		struct guc_ctb *h2g = &ct->ctbs.h2g;
963 
964 		if (sleep_period_ms == 1024)
965 			goto broken;
966 
967 		trace_xe_guc_ct_h2g_flow_control(xe, h2g->info.head, h2g->info.tail,
968 						 h2g->info.size,
969 						 h2g->info.space,
970 						 len + GUC_CTB_HDR_LEN);
971 		msleep(sleep_period_ms);
972 		sleep_period_ms <<= 1;
973 
974 		goto try_again;
975 	} else if (unlikely(ret == -EBUSY)) {
976 		struct xe_device *xe = ct_to_xe(ct);
977 		struct guc_ctb *g2h = &ct->ctbs.g2h;
978 
979 		trace_xe_guc_ct_g2h_flow_control(xe, g2h->info.head,
980 						 desc_read(xe, g2h, tail),
981 						 g2h->info.size,
982 						 g2h->info.space,
983 						 g2h_fence ?
984 						 GUC_CTB_HXG_MSG_MAX_LEN :
985 						 g2h_len);
986 
987 #define g2h_avail(ct)	\
988 	(desc_read(ct_to_xe(ct), (&ct->ctbs.g2h), tail) != ct->ctbs.g2h.info.head)
989 		if (!wait_event_timeout(ct->wq, !ct->g2h_outstanding ||
990 					g2h_avail(ct), HZ))
991 			goto broken;
992 #undef g2h_avail
993 
994 		ret = dequeue_one_g2h(ct);
995 		if (ret < 0) {
996 			if (ret != -ECANCELED)
997 				xe_gt_err(ct_to_gt(ct), "CTB receive failed (%pe)",
998 					  ERR_PTR(ret));
999 			goto broken;
1000 		}
1001 
1002 		goto try_again;
1003 	}
1004 
1005 	return ret;
1006 
1007 broken:
1008 	xe_gt_err(gt, "No forward process on H2G, reset required\n");
1009 	CT_DEAD(ct, &ct->ctbs.h2g, DEADLOCK);
1010 
1011 	return -EDEADLK;
1012 }
1013 
guc_ct_send(struct xe_guc_ct * ct,const u32 * action,u32 len,u32 g2h_len,u32 num_g2h,struct g2h_fence * g2h_fence)1014 static int guc_ct_send(struct xe_guc_ct *ct, const u32 *action, u32 len,
1015 		       u32 g2h_len, u32 num_g2h, struct g2h_fence *g2h_fence)
1016 {
1017 	int ret;
1018 
1019 	xe_gt_assert(ct_to_gt(ct), !g2h_len || !g2h_fence);
1020 
1021 	mutex_lock(&ct->lock);
1022 	ret = guc_ct_send_locked(ct, action, len, g2h_len, num_g2h, g2h_fence);
1023 	mutex_unlock(&ct->lock);
1024 
1025 	return ret;
1026 }
1027 
xe_guc_ct_send(struct xe_guc_ct * ct,const u32 * action,u32 len,u32 g2h_len,u32 num_g2h)1028 int xe_guc_ct_send(struct xe_guc_ct *ct, const u32 *action, u32 len,
1029 		   u32 g2h_len, u32 num_g2h)
1030 {
1031 	int ret;
1032 
1033 	ret = guc_ct_send(ct, action, len, g2h_len, num_g2h, NULL);
1034 	if (ret == -EDEADLK)
1035 		kick_reset(ct);
1036 
1037 	return ret;
1038 }
1039 
xe_guc_ct_send_locked(struct xe_guc_ct * ct,const u32 * action,u32 len,u32 g2h_len,u32 num_g2h)1040 int xe_guc_ct_send_locked(struct xe_guc_ct *ct, const u32 *action, u32 len,
1041 			  u32 g2h_len, u32 num_g2h)
1042 {
1043 	int ret;
1044 
1045 	ret = guc_ct_send_locked(ct, action, len, g2h_len, num_g2h, NULL);
1046 	if (ret == -EDEADLK)
1047 		kick_reset(ct);
1048 
1049 	return ret;
1050 }
1051 
xe_guc_ct_send_g2h_handler(struct xe_guc_ct * ct,const u32 * action,u32 len)1052 int xe_guc_ct_send_g2h_handler(struct xe_guc_ct *ct, const u32 *action, u32 len)
1053 {
1054 	int ret;
1055 
1056 	lockdep_assert_held(&ct->lock);
1057 
1058 	ret = guc_ct_send_locked(ct, action, len, 0, 0, NULL);
1059 	if (ret == -EDEADLK)
1060 		kick_reset(ct);
1061 
1062 	return ret;
1063 }
1064 
1065 /*
1066  * Check if a GT reset is in progress or will occur and if GT reset brought the
1067  * CT back up. Randomly picking 5 seconds for an upper limit to do a GT a reset.
1068  */
retry_failure(struct xe_guc_ct * ct,int ret)1069 static bool retry_failure(struct xe_guc_ct *ct, int ret)
1070 {
1071 	if (!(ret == -EDEADLK || ret == -EPIPE || ret == -ENODEV))
1072 		return false;
1073 
1074 #define ct_alive(ct)	\
1075 	(xe_guc_ct_enabled(ct) && !ct->ctbs.h2g.info.broken && \
1076 	 !ct->ctbs.g2h.info.broken)
1077 	if (!wait_event_interruptible_timeout(ct->wq, ct_alive(ct), HZ * 5))
1078 		return false;
1079 #undef ct_alive
1080 
1081 	return true;
1082 }
1083 
1084 #define GUC_SEND_RETRY_LIMIT	50
1085 #define GUC_SEND_RETRY_MSLEEP	5
1086 
guc_ct_send_recv(struct xe_guc_ct * ct,const u32 * action,u32 len,u32 * response_buffer,bool no_fail)1087 static int guc_ct_send_recv(struct xe_guc_ct *ct, const u32 *action, u32 len,
1088 			    u32 *response_buffer, bool no_fail)
1089 {
1090 	struct xe_gt *gt = ct_to_gt(ct);
1091 	struct g2h_fence g2h_fence;
1092 	unsigned int retries = 0;
1093 	int ret = 0;
1094 
1095 	/*
1096 	 * We use a fence to implement blocking sends / receiving response data.
1097 	 * The seqno of the fence is sent in the H2G, returned in the G2H, and
1098 	 * an xarray is used as storage media with the seqno being to key.
1099 	 * Fields in the fence hold success, failure, retry status and the
1100 	 * response data. Safe to allocate on the stack as the xarray is the
1101 	 * only reference and it cannot be present after this function exits.
1102 	 */
1103 retry:
1104 	g2h_fence_init(&g2h_fence, response_buffer);
1105 retry_same_fence:
1106 	ret = guc_ct_send(ct, action, len, 0, 0, &g2h_fence);
1107 	if (unlikely(ret == -ENOMEM)) {
1108 		/* Retry allocation /w GFP_KERNEL */
1109 		ret = xa_err(xa_store(&ct->fence_lookup, g2h_fence.seqno,
1110 				      &g2h_fence, GFP_KERNEL));
1111 		if (ret)
1112 			return ret;
1113 
1114 		goto retry_same_fence;
1115 	} else if (unlikely(ret)) {
1116 		if (ret == -EDEADLK)
1117 			kick_reset(ct);
1118 
1119 		if (no_fail && retry_failure(ct, ret))
1120 			goto retry_same_fence;
1121 
1122 		if (!g2h_fence_needs_alloc(&g2h_fence))
1123 			xa_erase(&ct->fence_lookup, g2h_fence.seqno);
1124 
1125 		return ret;
1126 	}
1127 
1128 	ret = wait_event_timeout(ct->g2h_fence_wq, g2h_fence.done, HZ);
1129 	if (!ret) {
1130 		LNL_FLUSH_WORK(&ct->g2h_worker);
1131 		if (g2h_fence.done) {
1132 			xe_gt_warn(gt, "G2H fence %u, action %04x, done\n",
1133 				   g2h_fence.seqno, action[0]);
1134 			ret = 1;
1135 		}
1136 	}
1137 
1138 	/*
1139 	 * Ensure we serialize with completion side to prevent UAF with fence going out of scope on
1140 	 * the stack, since we have no clue if it will fire after the timeout before we can erase
1141 	 * from the xa. Also we have some dependent loads and stores below for which we need the
1142 	 * correct ordering, and we lack the needed barriers.
1143 	 */
1144 	mutex_lock(&ct->lock);
1145 	if (!ret) {
1146 		xe_gt_err(gt, "Timed out wait for G2H, fence %u, action %04x, done %s",
1147 			  g2h_fence.seqno, action[0], str_yes_no(g2h_fence.done));
1148 		xa_erase(&ct->fence_lookup, g2h_fence.seqno);
1149 		mutex_unlock(&ct->lock);
1150 		return -ETIME;
1151 	}
1152 
1153 	if (g2h_fence.retry) {
1154 		xe_gt_dbg(gt, "H2G action %#x retrying: reason %#x\n",
1155 			  action[0], g2h_fence.reason);
1156 		mutex_unlock(&ct->lock);
1157 		if (++retries > GUC_SEND_RETRY_LIMIT) {
1158 			xe_gt_err(gt, "H2G action %#x reached retry limit=%u, aborting\n",
1159 				  action[0], GUC_SEND_RETRY_LIMIT);
1160 			return -ELOOP;
1161 		}
1162 		msleep(GUC_SEND_RETRY_MSLEEP * retries);
1163 		goto retry;
1164 	}
1165 	if (g2h_fence.fail) {
1166 		if (g2h_fence.cancel) {
1167 			xe_gt_dbg(gt, "H2G request %#x canceled!\n", action[0]);
1168 			ret = -ECANCELED;
1169 			goto unlock;
1170 		}
1171 		xe_gt_err(gt, "H2G request %#x failed: error %#x hint %#x\n",
1172 			  action[0], g2h_fence.error, g2h_fence.hint);
1173 		ret = -EIO;
1174 	}
1175 
1176 	if (ret > 0)
1177 		ret = response_buffer ? g2h_fence.response_len : g2h_fence.response_data;
1178 
1179 unlock:
1180 	mutex_unlock(&ct->lock);
1181 
1182 	return ret;
1183 }
1184 
1185 /**
1186  * xe_guc_ct_send_recv - Send and receive HXG to the GuC
1187  * @ct: the &xe_guc_ct
1188  * @action: the dword array with `HXG Request`_ message (can't be NULL)
1189  * @len: length of the `HXG Request`_ message (in dwords, can't be 0)
1190  * @response_buffer: placeholder for the `HXG Response`_ message (can be NULL)
1191  *
1192  * Send a `HXG Request`_ message to the GuC over CT communication channel and
1193  * blocks until GuC replies with a `HXG Response`_ message.
1194  *
1195  * For non-blocking communication with GuC use xe_guc_ct_send().
1196  *
1197  * Note: The size of &response_buffer must be at least GUC_CTB_MAX_DWORDS_.
1198  *
1199  * Return: response length (in dwords) if &response_buffer was not NULL, or
1200  *         DATA0 from `HXG Response`_ if &response_buffer was NULL, or
1201  *         a negative error code on failure.
1202  */
xe_guc_ct_send_recv(struct xe_guc_ct * ct,const u32 * action,u32 len,u32 * response_buffer)1203 int xe_guc_ct_send_recv(struct xe_guc_ct *ct, const u32 *action, u32 len,
1204 			u32 *response_buffer)
1205 {
1206 	KUNIT_STATIC_STUB_REDIRECT(xe_guc_ct_send_recv, ct, action, len, response_buffer);
1207 	return guc_ct_send_recv(ct, action, len, response_buffer, false);
1208 }
1209 ALLOW_ERROR_INJECTION(xe_guc_ct_send_recv, ERRNO);
1210 
xe_guc_ct_send_recv_no_fail(struct xe_guc_ct * ct,const u32 * action,u32 len,u32 * response_buffer)1211 int xe_guc_ct_send_recv_no_fail(struct xe_guc_ct *ct, const u32 *action,
1212 				u32 len, u32 *response_buffer)
1213 {
1214 	return guc_ct_send_recv(ct, action, len, response_buffer, true);
1215 }
1216 
msg_to_hxg(u32 * msg)1217 static u32 *msg_to_hxg(u32 *msg)
1218 {
1219 	return msg + GUC_CTB_MSG_MIN_LEN;
1220 }
1221 
msg_len_to_hxg_len(u32 len)1222 static u32 msg_len_to_hxg_len(u32 len)
1223 {
1224 	return len - GUC_CTB_MSG_MIN_LEN;
1225 }
1226 
parse_g2h_event(struct xe_guc_ct * ct,u32 * msg,u32 len)1227 static int parse_g2h_event(struct xe_guc_ct *ct, u32 *msg, u32 len)
1228 {
1229 	u32 *hxg = msg_to_hxg(msg);
1230 	u32 action = FIELD_GET(GUC_HXG_EVENT_MSG_0_ACTION, hxg[0]);
1231 
1232 	lockdep_assert_held(&ct->lock);
1233 
1234 	switch (action) {
1235 	case XE_GUC_ACTION_SCHED_CONTEXT_MODE_DONE:
1236 	case XE_GUC_ACTION_DEREGISTER_CONTEXT_DONE:
1237 	case XE_GUC_ACTION_SCHED_ENGINE_MODE_DONE:
1238 	case XE_GUC_ACTION_TLB_INVALIDATION_DONE:
1239 		g2h_release_space(ct, len);
1240 	}
1241 
1242 	return 0;
1243 }
1244 
guc_crash_process_msg(struct xe_guc_ct * ct,u32 action)1245 static int guc_crash_process_msg(struct xe_guc_ct *ct, u32 action)
1246 {
1247 	struct xe_gt *gt = ct_to_gt(ct);
1248 
1249 	if (action == XE_GUC_ACTION_NOTIFY_CRASH_DUMP_POSTED)
1250 		xe_gt_err(gt, "GuC Crash dump notification\n");
1251 	else if (action == XE_GUC_ACTION_NOTIFY_EXCEPTION)
1252 		xe_gt_err(gt, "GuC Exception notification\n");
1253 	else
1254 		xe_gt_err(gt, "Unknown GuC crash notification: 0x%04X\n", action);
1255 
1256 	CT_DEAD(ct, NULL, CRASH);
1257 
1258 	kick_reset(ct);
1259 
1260 	return 0;
1261 }
1262 
1263 #if IS_ENABLED(CONFIG_DRM_XE_DEBUG)
fast_req_report(struct xe_guc_ct * ct,u16 fence)1264 static void fast_req_report(struct xe_guc_ct *ct, u16 fence)
1265 {
1266 	u16 fence_min = U16_MAX, fence_max = 0;
1267 	struct xe_gt *gt = ct_to_gt(ct);
1268 	bool found = false;
1269 	unsigned int n;
1270 #if IS_ENABLED(CONFIG_DRM_XE_DEBUG_GUC)
1271 	char *buf;
1272 #endif
1273 
1274 	lockdep_assert_held(&ct->lock);
1275 
1276 	for (n = 0; n < ARRAY_SIZE(ct->fast_req); n++) {
1277 		if (ct->fast_req[n].fence < fence_min)
1278 			fence_min = ct->fast_req[n].fence;
1279 		if (ct->fast_req[n].fence > fence_max)
1280 			fence_max = ct->fast_req[n].fence;
1281 
1282 		if (ct->fast_req[n].fence != fence)
1283 			continue;
1284 		found = true;
1285 
1286 #if IS_ENABLED(CONFIG_DRM_XE_DEBUG_GUC)
1287 		buf = kmalloc(SZ_4K, GFP_NOWAIT);
1288 		if (buf && stack_depot_snprint(ct->fast_req[n].stack, buf, SZ_4K, 0))
1289 			xe_gt_err(gt, "Fence 0x%x was used by action %#04x sent at:\n%s",
1290 				  fence, ct->fast_req[n].action, buf);
1291 		else
1292 			xe_gt_err(gt, "Fence 0x%x was used by action %#04x [failed to retrieve stack]\n",
1293 				  fence, ct->fast_req[n].action);
1294 		kfree(buf);
1295 #else
1296 		xe_gt_err(gt, "Fence 0x%x was used by action %#04x\n",
1297 			  fence, ct->fast_req[n].action);
1298 #endif
1299 		break;
1300 	}
1301 
1302 	if (!found)
1303 		xe_gt_warn(gt, "Fence 0x%x not found - tracking buffer wrapped? [range = 0x%x -> 0x%x, next = 0x%X]\n",
1304 			   fence, fence_min, fence_max, ct->fence_seqno);
1305 }
1306 #else
fast_req_report(struct xe_guc_ct * ct,u16 fence)1307 static void fast_req_report(struct xe_guc_ct *ct, u16 fence)
1308 {
1309 }
1310 #endif
1311 
parse_g2h_response(struct xe_guc_ct * ct,u32 * msg,u32 len)1312 static int parse_g2h_response(struct xe_guc_ct *ct, u32 *msg, u32 len)
1313 {
1314 	struct xe_gt *gt =  ct_to_gt(ct);
1315 	u32 *hxg = msg_to_hxg(msg);
1316 	u32 hxg_len = msg_len_to_hxg_len(len);
1317 	u32 fence = FIELD_GET(GUC_CTB_MSG_0_FENCE, msg[0]);
1318 	u32 type = FIELD_GET(GUC_HXG_MSG_0_TYPE, hxg[0]);
1319 	struct g2h_fence *g2h_fence;
1320 
1321 	lockdep_assert_held(&ct->lock);
1322 
1323 	/*
1324 	 * Fences for FAST_REQUEST messages are not tracked in ct->fence_lookup.
1325 	 * Those messages should never fail, so if we do get an error back it
1326 	 * means we're likely doing an illegal operation and the GuC is
1327 	 * rejecting it. We have no way to inform the code that submitted the
1328 	 * H2G that the message was rejected, so we need to escalate the
1329 	 * failure to trigger a reset.
1330 	 */
1331 	if (fence & CT_SEQNO_UNTRACKED) {
1332 		if (type == GUC_HXG_TYPE_RESPONSE_FAILURE)
1333 			xe_gt_err(gt, "FAST_REQ H2G fence 0x%x failed! e=0x%x, h=%u\n",
1334 				  fence,
1335 				  FIELD_GET(GUC_HXG_FAILURE_MSG_0_ERROR, hxg[0]),
1336 				  FIELD_GET(GUC_HXG_FAILURE_MSG_0_HINT, hxg[0]));
1337 		else
1338 			xe_gt_err(gt, "unexpected response %u for FAST_REQ H2G fence 0x%x!\n",
1339 				  type, fence);
1340 
1341 		fast_req_report(ct, fence);
1342 
1343 		CT_DEAD(ct, NULL, PARSE_G2H_RESPONSE);
1344 
1345 		return -EPROTO;
1346 	}
1347 
1348 	g2h_fence = xa_erase(&ct->fence_lookup, fence);
1349 	if (unlikely(!g2h_fence)) {
1350 		/* Don't tear down channel, as send could've timed out */
1351 		/* CT_DEAD(ct, NULL, PARSE_G2H_UNKNOWN); */
1352 		xe_gt_warn(gt, "G2H fence (%u) not found!\n", fence);
1353 		g2h_release_space(ct, GUC_CTB_HXG_MSG_MAX_LEN);
1354 		return 0;
1355 	}
1356 
1357 	xe_gt_assert(gt, fence == g2h_fence->seqno);
1358 
1359 	if (type == GUC_HXG_TYPE_RESPONSE_FAILURE) {
1360 		g2h_fence->fail = true;
1361 		g2h_fence->error = FIELD_GET(GUC_HXG_FAILURE_MSG_0_ERROR, hxg[0]);
1362 		g2h_fence->hint = FIELD_GET(GUC_HXG_FAILURE_MSG_0_HINT, hxg[0]);
1363 	} else if (type == GUC_HXG_TYPE_NO_RESPONSE_RETRY) {
1364 		g2h_fence->retry = true;
1365 		g2h_fence->reason = FIELD_GET(GUC_HXG_RETRY_MSG_0_REASON, hxg[0]);
1366 	} else if (g2h_fence->response_buffer) {
1367 		g2h_fence->response_len = hxg_len;
1368 		memcpy(g2h_fence->response_buffer, hxg, hxg_len * sizeof(u32));
1369 	} else {
1370 		g2h_fence->response_data = FIELD_GET(GUC_HXG_RESPONSE_MSG_0_DATA0, hxg[0]);
1371 	}
1372 
1373 	g2h_release_space(ct, GUC_CTB_HXG_MSG_MAX_LEN);
1374 
1375 	g2h_fence->done = true;
1376 	smp_mb();
1377 
1378 	wake_up_all(&ct->g2h_fence_wq);
1379 
1380 	return 0;
1381 }
1382 
parse_g2h_msg(struct xe_guc_ct * ct,u32 * msg,u32 len)1383 static int parse_g2h_msg(struct xe_guc_ct *ct, u32 *msg, u32 len)
1384 {
1385 	struct xe_gt *gt = ct_to_gt(ct);
1386 	u32 *hxg = msg_to_hxg(msg);
1387 	u32 origin, type;
1388 	int ret;
1389 
1390 	lockdep_assert_held(&ct->lock);
1391 
1392 	origin = FIELD_GET(GUC_HXG_MSG_0_ORIGIN, hxg[0]);
1393 	if (unlikely(origin != GUC_HXG_ORIGIN_GUC)) {
1394 		xe_gt_err(gt, "G2H channel broken on read, origin=%u, reset required\n",
1395 			  origin);
1396 		CT_DEAD(ct, &ct->ctbs.g2h, PARSE_G2H_ORIGIN);
1397 
1398 		return -EPROTO;
1399 	}
1400 
1401 	type = FIELD_GET(GUC_HXG_MSG_0_TYPE, hxg[0]);
1402 	switch (type) {
1403 	case GUC_HXG_TYPE_EVENT:
1404 		ret = parse_g2h_event(ct, msg, len);
1405 		break;
1406 	case GUC_HXG_TYPE_RESPONSE_SUCCESS:
1407 	case GUC_HXG_TYPE_RESPONSE_FAILURE:
1408 	case GUC_HXG_TYPE_NO_RESPONSE_RETRY:
1409 		ret = parse_g2h_response(ct, msg, len);
1410 		break;
1411 	default:
1412 		xe_gt_err(gt, "G2H channel broken on read, type=%u, reset required\n",
1413 			  type);
1414 		CT_DEAD(ct, &ct->ctbs.g2h, PARSE_G2H_TYPE);
1415 
1416 		ret = -EOPNOTSUPP;
1417 	}
1418 
1419 	return ret;
1420 }
1421 
process_g2h_msg(struct xe_guc_ct * ct,u32 * msg,u32 len)1422 static int process_g2h_msg(struct xe_guc_ct *ct, u32 *msg, u32 len)
1423 {
1424 	struct xe_guc *guc = ct_to_guc(ct);
1425 	struct xe_gt *gt = ct_to_gt(ct);
1426 	u32 hxg_len = msg_len_to_hxg_len(len);
1427 	u32 *hxg = msg_to_hxg(msg);
1428 	u32 action, adj_len;
1429 	u32 *payload;
1430 	int ret = 0;
1431 
1432 	if (FIELD_GET(GUC_HXG_MSG_0_TYPE, hxg[0]) != GUC_HXG_TYPE_EVENT)
1433 		return 0;
1434 
1435 	action = FIELD_GET(GUC_HXG_EVENT_MSG_0_ACTION, hxg[0]);
1436 	payload = hxg + GUC_HXG_EVENT_MSG_MIN_LEN;
1437 	adj_len = hxg_len - GUC_HXG_EVENT_MSG_MIN_LEN;
1438 
1439 	switch (action) {
1440 	case XE_GUC_ACTION_SCHED_CONTEXT_MODE_DONE:
1441 		ret = xe_guc_sched_done_handler(guc, payload, adj_len);
1442 		break;
1443 	case XE_GUC_ACTION_DEREGISTER_CONTEXT_DONE:
1444 		ret = xe_guc_deregister_done_handler(guc, payload, adj_len);
1445 		break;
1446 	case XE_GUC_ACTION_CONTEXT_RESET_NOTIFICATION:
1447 		ret = xe_guc_exec_queue_reset_handler(guc, payload, adj_len);
1448 		break;
1449 	case XE_GUC_ACTION_ENGINE_FAILURE_NOTIFICATION:
1450 		ret = xe_guc_exec_queue_reset_failure_handler(guc, payload,
1451 							      adj_len);
1452 		break;
1453 	case XE_GUC_ACTION_SCHED_ENGINE_MODE_DONE:
1454 		/* Selftest only at the moment */
1455 		break;
1456 	case XE_GUC_ACTION_STATE_CAPTURE_NOTIFICATION:
1457 		ret = xe_guc_error_capture_handler(guc, payload, adj_len);
1458 		break;
1459 	case XE_GUC_ACTION_NOTIFY_FLUSH_LOG_BUFFER_TO_FILE:
1460 		/* FIXME: Handle this */
1461 		break;
1462 	case XE_GUC_ACTION_NOTIFY_MEMORY_CAT_ERROR:
1463 		ret = xe_guc_exec_queue_memory_cat_error_handler(guc, payload,
1464 								 adj_len);
1465 		break;
1466 	case XE_GUC_ACTION_REPORT_PAGE_FAULT_REQ_DESC:
1467 		ret = xe_guc_pagefault_handler(guc, payload, adj_len);
1468 		break;
1469 	case XE_GUC_ACTION_TLB_INVALIDATION_DONE:
1470 		ret = xe_guc_tlb_inval_done_handler(guc, payload, adj_len);
1471 		break;
1472 	case XE_GUC_ACTION_ACCESS_COUNTER_NOTIFY:
1473 		ret = xe_guc_access_counter_notify_handler(guc, payload,
1474 							   adj_len);
1475 		break;
1476 	case XE_GUC_ACTION_GUC2PF_RELAY_FROM_VF:
1477 		ret = xe_guc_relay_process_guc2pf(&guc->relay, hxg, hxg_len);
1478 		break;
1479 	case XE_GUC_ACTION_GUC2VF_RELAY_FROM_PF:
1480 		ret = xe_guc_relay_process_guc2vf(&guc->relay, hxg, hxg_len);
1481 		break;
1482 	case GUC_ACTION_GUC2PF_VF_STATE_NOTIFY:
1483 		ret = xe_gt_sriov_pf_control_process_guc2pf(gt, hxg, hxg_len);
1484 		break;
1485 	case GUC_ACTION_GUC2PF_ADVERSE_EVENT:
1486 		ret = xe_gt_sriov_pf_monitor_process_guc2pf(gt, hxg, hxg_len);
1487 		break;
1488 	case XE_GUC_ACTION_NOTIFY_CRASH_DUMP_POSTED:
1489 	case XE_GUC_ACTION_NOTIFY_EXCEPTION:
1490 		ret = guc_crash_process_msg(ct, action);
1491 		break;
1492 #if IS_ENABLED(CONFIG_DRM_XE_KUNIT_TEST)
1493 	case XE_GUC_ACTION_TEST_G2G_RECV:
1494 		ret = xe_guc_g2g_test_notification(guc, payload, adj_len);
1495 		break;
1496 #endif
1497 	default:
1498 		xe_gt_err(gt, "unexpected G2H action 0x%04x\n", action);
1499 	}
1500 
1501 	if (ret) {
1502 		xe_gt_err(gt, "G2H action %#04x failed (%pe) len %u msg %*ph\n",
1503 			  action, ERR_PTR(ret), hxg_len, (int)sizeof(u32) * hxg_len, hxg);
1504 		CT_DEAD(ct, NULL, PROCESS_FAILED);
1505 	}
1506 
1507 	return 0;
1508 }
1509 
g2h_read(struct xe_guc_ct * ct,u32 * msg,bool fast_path)1510 static int g2h_read(struct xe_guc_ct *ct, u32 *msg, bool fast_path)
1511 {
1512 	struct xe_device *xe = ct_to_xe(ct);
1513 	struct xe_gt *gt = ct_to_gt(ct);
1514 	struct guc_ctb *g2h = &ct->ctbs.g2h;
1515 	u32 tail, head, len, desc_status;
1516 	s32 avail;
1517 	u32 action;
1518 	u32 *hxg;
1519 
1520 	xe_gt_assert(gt, xe_guc_ct_initialized(ct));
1521 	lockdep_assert_held(&ct->fast_lock);
1522 
1523 	if (ct->state == XE_GUC_CT_STATE_DISABLED)
1524 		return -ENODEV;
1525 
1526 	if (ct->state == XE_GUC_CT_STATE_STOPPED)
1527 		return -ECANCELED;
1528 
1529 	if (g2h->info.broken)
1530 		return -EPIPE;
1531 
1532 	xe_gt_assert(gt, xe_guc_ct_enabled(ct));
1533 
1534 	desc_status = desc_read(xe, g2h, status);
1535 	if (desc_status) {
1536 		if (desc_status & GUC_CTB_STATUS_DISABLED) {
1537 			/*
1538 			 * Potentially valid if a CLIENT_RESET request resulted in
1539 			 * contexts/engines being reset. But should never happen as
1540 			 * no contexts should be active when CLIENT_RESET is sent.
1541 			 */
1542 			xe_gt_err(gt, "CT read: unexpected G2H after GuC has stopped!\n");
1543 			desc_status &= ~GUC_CTB_STATUS_DISABLED;
1544 		}
1545 
1546 		if (desc_status) {
1547 			xe_gt_err(gt, "CT read: non-zero status: %u\n", desc_status);
1548 			goto corrupted;
1549 		}
1550 	}
1551 
1552 	if (IS_ENABLED(CONFIG_DRM_XE_DEBUG)) {
1553 		u32 desc_tail = desc_read(xe, g2h, tail);
1554 		/*
1555 		u32 desc_head = desc_read(xe, g2h, head);
1556 
1557 		 * info.head and desc_head are updated back-to-back at the end of
1558 		 * this function and nowhere else. Hence, they cannot be different
1559 		 * unless two g2h_read calls are running concurrently. Which is not
1560 		 * possible because it is guarded by ct->fast_lock. And yet, some
1561 		 * discrete platforms are regularly hitting this error :(.
1562 		 *
1563 		 * desc_head rolling backwards shouldn't cause any noticeable
1564 		 * problems - just a delay in GuC being allowed to proceed past that
1565 		 * point in the queue. So for now, just disable the error until it
1566 		 * can be root caused.
1567 		 *
1568 		if (g2h->info.head != desc_head) {
1569 			desc_write(xe, g2h, status, desc_status | GUC_CTB_STATUS_MISMATCH);
1570 			xe_gt_err(gt, "CT read: head was modified %u != %u\n",
1571 				  desc_head, g2h->info.head);
1572 			goto corrupted;
1573 		}
1574 		 */
1575 
1576 		if (g2h->info.head > g2h->info.size) {
1577 			desc_write(xe, g2h, status, desc_status | GUC_CTB_STATUS_OVERFLOW);
1578 			xe_gt_err(gt, "CT read: head out of range: %u vs %u\n",
1579 				  g2h->info.head, g2h->info.size);
1580 			goto corrupted;
1581 		}
1582 
1583 		if (desc_tail >= g2h->info.size) {
1584 			desc_write(xe, g2h, status, desc_status | GUC_CTB_STATUS_OVERFLOW);
1585 			xe_gt_err(gt, "CT read: invalid tail offset %u >= %u)\n",
1586 				  desc_tail, g2h->info.size);
1587 			goto corrupted;
1588 		}
1589 	}
1590 
1591 	/* Calculate DW available to read */
1592 	tail = desc_read(xe, g2h, tail);
1593 	avail = tail - g2h->info.head;
1594 	if (unlikely(avail == 0))
1595 		return 0;
1596 
1597 	if (avail < 0)
1598 		avail += g2h->info.size;
1599 
1600 	/* Read header */
1601 	xe_map_memcpy_from(xe, msg, &g2h->cmds, sizeof(u32) * g2h->info.head,
1602 			   sizeof(u32));
1603 	len = FIELD_GET(GUC_CTB_MSG_0_NUM_DWORDS, msg[0]) + GUC_CTB_MSG_MIN_LEN;
1604 	if (len > avail) {
1605 		xe_gt_err(gt, "G2H channel broken on read, avail=%d, len=%d, reset required\n",
1606 			  avail, len);
1607 		goto corrupted;
1608 	}
1609 
1610 	head = (g2h->info.head + 1) % g2h->info.size;
1611 	avail = len - 1;
1612 
1613 	/* Read G2H message */
1614 	if (avail + head > g2h->info.size) {
1615 		u32 avail_til_wrap = g2h->info.size - head;
1616 
1617 		xe_map_memcpy_from(xe, msg + 1,
1618 				   &g2h->cmds, sizeof(u32) * head,
1619 				   avail_til_wrap * sizeof(u32));
1620 		xe_map_memcpy_from(xe, msg + 1 + avail_til_wrap,
1621 				   &g2h->cmds, 0,
1622 				   (avail - avail_til_wrap) * sizeof(u32));
1623 	} else {
1624 		xe_map_memcpy_from(xe, msg + 1,
1625 				   &g2h->cmds, sizeof(u32) * head,
1626 				   avail * sizeof(u32));
1627 	}
1628 
1629 	hxg = msg_to_hxg(msg);
1630 	action = FIELD_GET(GUC_HXG_EVENT_MSG_0_ACTION, hxg[0]);
1631 
1632 	if (fast_path) {
1633 		if (FIELD_GET(GUC_HXG_MSG_0_TYPE, hxg[0]) != GUC_HXG_TYPE_EVENT)
1634 			return 0;
1635 
1636 		switch (action) {
1637 		case XE_GUC_ACTION_REPORT_PAGE_FAULT_REQ_DESC:
1638 		case XE_GUC_ACTION_TLB_INVALIDATION_DONE:
1639 			break;	/* Process these in fast-path */
1640 		default:
1641 			return 0;
1642 		}
1643 	}
1644 
1645 	/* Update local / descriptor header */
1646 	g2h->info.head = (head + avail) % g2h->info.size;
1647 	desc_write(xe, g2h, head, g2h->info.head);
1648 
1649 	trace_xe_guc_ctb_g2h(xe, ct_to_gt(ct)->info.id,
1650 			     action, len, g2h->info.head, tail);
1651 
1652 	return len;
1653 
1654 corrupted:
1655 	CT_DEAD(ct, &ct->ctbs.g2h, G2H_READ);
1656 	return -EPROTO;
1657 }
1658 
g2h_fast_path(struct xe_guc_ct * ct,u32 * msg,u32 len)1659 static void g2h_fast_path(struct xe_guc_ct *ct, u32 *msg, u32 len)
1660 {
1661 	struct xe_gt *gt = ct_to_gt(ct);
1662 	struct xe_guc *guc = ct_to_guc(ct);
1663 	u32 hxg_len = msg_len_to_hxg_len(len);
1664 	u32 *hxg = msg_to_hxg(msg);
1665 	u32 action = FIELD_GET(GUC_HXG_EVENT_MSG_0_ACTION, hxg[0]);
1666 	u32 *payload = hxg + GUC_HXG_MSG_MIN_LEN;
1667 	u32 adj_len = hxg_len - GUC_HXG_MSG_MIN_LEN;
1668 	int ret = 0;
1669 
1670 	switch (action) {
1671 	case XE_GUC_ACTION_REPORT_PAGE_FAULT_REQ_DESC:
1672 		ret = xe_guc_pagefault_handler(guc, payload, adj_len);
1673 		break;
1674 	case XE_GUC_ACTION_TLB_INVALIDATION_DONE:
1675 		__g2h_release_space(ct, len);
1676 		ret = xe_guc_tlb_inval_done_handler(guc, payload, adj_len);
1677 		break;
1678 	default:
1679 		xe_gt_warn(gt, "NOT_POSSIBLE");
1680 	}
1681 
1682 	if (ret) {
1683 		xe_gt_err(gt, "G2H action 0x%04x failed (%pe)\n",
1684 			  action, ERR_PTR(ret));
1685 		CT_DEAD(ct, NULL, FAST_G2H);
1686 	}
1687 }
1688 
1689 /**
1690  * xe_guc_ct_fast_path - process critical G2H in the IRQ handler
1691  * @ct: GuC CT object
1692  *
1693  * Anything related to page faults is critical for performance, process these
1694  * critical G2H in the IRQ. This is safe as these handlers either just wake up
1695  * waiters or queue another worker.
1696  */
xe_guc_ct_fast_path(struct xe_guc_ct * ct)1697 void xe_guc_ct_fast_path(struct xe_guc_ct *ct)
1698 {
1699 	struct xe_device *xe = ct_to_xe(ct);
1700 	bool ongoing;
1701 	int len;
1702 
1703 	ongoing = xe_pm_runtime_get_if_active(ct_to_xe(ct));
1704 	if (!ongoing && xe_pm_read_callback_task(ct_to_xe(ct)) == NULL)
1705 		return;
1706 
1707 	spin_lock(&ct->fast_lock);
1708 	do {
1709 		len = g2h_read(ct, ct->fast_msg, true);
1710 		if (len > 0)
1711 			g2h_fast_path(ct, ct->fast_msg, len);
1712 	} while (len > 0);
1713 	spin_unlock(&ct->fast_lock);
1714 
1715 	if (ongoing)
1716 		xe_pm_runtime_put(xe);
1717 }
1718 
1719 /* Returns less than zero on error, 0 on done, 1 on more available */
dequeue_one_g2h(struct xe_guc_ct * ct)1720 static int dequeue_one_g2h(struct xe_guc_ct *ct)
1721 {
1722 	int len;
1723 	int ret;
1724 
1725 	lockdep_assert_held(&ct->lock);
1726 
1727 	spin_lock_irq(&ct->fast_lock);
1728 	len = g2h_read(ct, ct->msg, false);
1729 	spin_unlock_irq(&ct->fast_lock);
1730 	if (len <= 0)
1731 		return len;
1732 
1733 	ret = parse_g2h_msg(ct, ct->msg, len);
1734 	if (unlikely(ret < 0))
1735 		return ret;
1736 
1737 	ret = process_g2h_msg(ct, ct->msg, len);
1738 	if (unlikely(ret < 0))
1739 		return ret;
1740 
1741 	return 1;
1742 }
1743 
receive_g2h(struct xe_guc_ct * ct)1744 static void receive_g2h(struct xe_guc_ct *ct)
1745 {
1746 	bool ongoing;
1747 	int ret;
1748 
1749 	/*
1750 	 * Normal users must always hold mem_access.ref around CT calls. However
1751 	 * during the runtime pm callbacks we rely on CT to talk to the GuC, but
1752 	 * at this stage we can't rely on mem_access.ref and even the
1753 	 * callback_task will be different than current.  For such cases we just
1754 	 * need to ensure we always process the responses from any blocking
1755 	 * ct_send requests or where we otherwise expect some response when
1756 	 * initiated from those callbacks (which will need to wait for the below
1757 	 * dequeue_one_g2h()).  The dequeue_one_g2h() will gracefully fail if
1758 	 * the device has suspended to the point that the CT communication has
1759 	 * been disabled.
1760 	 *
1761 	 * If we are inside the runtime pm callback, we can be the only task
1762 	 * still issuing CT requests (since that requires having the
1763 	 * mem_access.ref).  It seems like it might in theory be possible to
1764 	 * receive unsolicited events from the GuC just as we are
1765 	 * suspending-resuming, but those will currently anyway be lost when
1766 	 * eventually exiting from suspend, hence no need to wake up the device
1767 	 * here. If we ever need something stronger than get_if_ongoing() then
1768 	 * we need to be careful with blocking the pm callbacks from getting CT
1769 	 * responses, if the worker here is blocked on those callbacks
1770 	 * completing, creating a deadlock.
1771 	 */
1772 	ongoing = xe_pm_runtime_get_if_active(ct_to_xe(ct));
1773 	if (!ongoing && xe_pm_read_callback_task(ct_to_xe(ct)) == NULL)
1774 		return;
1775 
1776 	do {
1777 		mutex_lock(&ct->lock);
1778 		ret = dequeue_one_g2h(ct);
1779 		mutex_unlock(&ct->lock);
1780 
1781 		if (unlikely(ret == -EPROTO || ret == -EOPNOTSUPP)) {
1782 			xe_gt_err(ct_to_gt(ct), "CT dequeue failed: %d", ret);
1783 			CT_DEAD(ct, NULL, G2H_RECV);
1784 			kick_reset(ct);
1785 		}
1786 	} while (ret == 1);
1787 
1788 	if (ongoing)
1789 		xe_pm_runtime_put(ct_to_xe(ct));
1790 }
1791 
g2h_worker_func(struct work_struct * w)1792 static void g2h_worker_func(struct work_struct *w)
1793 {
1794 	struct xe_guc_ct *ct = container_of(w, struct xe_guc_ct, g2h_worker);
1795 
1796 	receive_g2h(ct);
1797 }
1798 
xe_fixup_u64_in_cmds(struct xe_device * xe,struct iosys_map * cmds,u32 size,u32 idx,s64 shift)1799 static void xe_fixup_u64_in_cmds(struct xe_device *xe, struct iosys_map *cmds,
1800 				 u32 size, u32 idx, s64 shift)
1801 {
1802 	u32 hi, lo;
1803 	u64 offset;
1804 
1805 	lo = xe_map_rd_ring_u32(xe, cmds, idx, size);
1806 	hi = xe_map_rd_ring_u32(xe, cmds, idx + 1, size);
1807 	offset = make_u64(hi, lo);
1808 	offset += shift;
1809 	lo = lower_32_bits(offset);
1810 	hi = upper_32_bits(offset);
1811 	xe_map_wr_ring_u32(xe, cmds, idx, size, lo);
1812 	xe_map_wr_ring_u32(xe, cmds, idx + 1, size, hi);
1813 }
1814 
1815 /*
1816  * Shift any GGTT addresses within a single message left within CTB from
1817  * before post-migration recovery.
1818  * @ct: pointer to CT struct of the target GuC
1819  * @cmds: iomap buffer containing CT messages
1820  * @head: start of the target message within the buffer
1821  * @len: length of the target message
1822  * @size: size of the commands buffer
1823  * @shift: the address shift to be added to each GGTT reference
1824  * Return: true if the message was fixed or needed no fixups, false on failure
1825  */
ct_fixup_ggtt_in_message(struct xe_guc_ct * ct,struct iosys_map * cmds,u32 head,u32 len,u32 size,s64 shift)1826 static bool ct_fixup_ggtt_in_message(struct xe_guc_ct *ct,
1827 				     struct iosys_map *cmds, u32 head,
1828 				     u32 len, u32 size, s64 shift)
1829 {
1830 	struct xe_gt *gt = ct_to_gt(ct);
1831 	struct xe_device *xe = ct_to_xe(ct);
1832 	u32 msg[GUC_HXG_MSG_MIN_LEN];
1833 	u32 action, i, n;
1834 
1835 	xe_gt_assert(gt, len >= GUC_HXG_MSG_MIN_LEN);
1836 
1837 	msg[0] = xe_map_rd_ring_u32(xe, cmds, head, size);
1838 	action = FIELD_GET(GUC_HXG_REQUEST_MSG_0_ACTION, msg[0]);
1839 
1840 	xe_gt_sriov_dbg_verbose(gt, "fixing H2G %#x\n", action);
1841 
1842 	switch (action) {
1843 	case XE_GUC_ACTION_REGISTER_CONTEXT:
1844 		if (len != XE_GUC_REGISTER_CONTEXT_MSG_LEN)
1845 			goto err_len;
1846 		xe_fixup_u64_in_cmds(xe, cmds, size, head +
1847 				     XE_GUC_REGISTER_CONTEXT_DATA_5_WQ_DESC_ADDR_LOWER,
1848 				     shift);
1849 		xe_fixup_u64_in_cmds(xe, cmds, size, head +
1850 				     XE_GUC_REGISTER_CONTEXT_DATA_7_WQ_BUF_BASE_LOWER,
1851 				     shift);
1852 		xe_fixup_u64_in_cmds(xe, cmds, size, head +
1853 				     XE_GUC_REGISTER_CONTEXT_DATA_10_HW_LRC_ADDR, shift);
1854 		break;
1855 	case XE_GUC_ACTION_REGISTER_CONTEXT_MULTI_LRC:
1856 		if (len < XE_GUC_REGISTER_CONTEXT_MULTI_LRC_MSG_MIN_LEN)
1857 			goto err_len;
1858 		n = xe_map_rd_ring_u32(xe, cmds, head +
1859 				       XE_GUC_REGISTER_CONTEXT_MULTI_LRC_DATA_10_NUM_CTXS, size);
1860 		if (len != XE_GUC_REGISTER_CONTEXT_MULTI_LRC_MSG_MIN_LEN + 2 * n)
1861 			goto err_len;
1862 		xe_fixup_u64_in_cmds(xe, cmds, size, head +
1863 				     XE_GUC_REGISTER_CONTEXT_MULTI_LRC_DATA_5_WQ_DESC_ADDR_LOWER,
1864 				     shift);
1865 		xe_fixup_u64_in_cmds(xe, cmds, size, head +
1866 				     XE_GUC_REGISTER_CONTEXT_MULTI_LRC_DATA_7_WQ_BUF_BASE_LOWER,
1867 				     shift);
1868 		for (i = 0; i < n; i++)
1869 			xe_fixup_u64_in_cmds(xe, cmds, size, head +
1870 					     XE_GUC_REGISTER_CONTEXT_MULTI_LRC_DATA_11_HW_LRC_ADDR
1871 					     + 2 * i, shift);
1872 		break;
1873 	default:
1874 		break;
1875 	}
1876 	return true;
1877 
1878 err_len:
1879 	xe_gt_err(gt, "Skipped G2G %#x message fixups, unexpected length (%u)\n", action, len);
1880 	return false;
1881 }
1882 
1883 /*
1884  * Apply fixups to the next outgoing CT message within given CTB
1885  * @ct: the &xe_guc_ct struct instance representing the target GuC
1886  * @h2g: the &guc_ctb struct instance of the target buffer
1887  * @shift: shift to be added to all GGTT addresses within the CTB
1888  * @mhead: pointer to an integer storing message start position; the
1889  *   position is changed to next message before this function return
1890  * @avail: size of the area available for parsing, that is length
1891  *   of all remaining messages stored within the CTB
1892  * Return: size of the area available for parsing after one message
1893  *   has been parsed, that is length remaining from the updated mhead
1894  */
ct_fixup_ggtt_in_buffer(struct xe_guc_ct * ct,struct guc_ctb * h2g,s64 shift,u32 * mhead,s32 avail)1895 static int ct_fixup_ggtt_in_buffer(struct xe_guc_ct *ct, struct guc_ctb *h2g,
1896 				   s64 shift, u32 *mhead, s32 avail)
1897 {
1898 	struct xe_gt *gt = ct_to_gt(ct);
1899 	struct xe_device *xe = ct_to_xe(ct);
1900 	u32 msg[GUC_HXG_MSG_MIN_LEN];
1901 	u32 size = h2g->info.size;
1902 	u32 head = *mhead;
1903 	u32 len;
1904 
1905 	xe_gt_assert(gt, avail >= (s32)GUC_CTB_MSG_MIN_LEN);
1906 
1907 	/* Read header */
1908 	msg[0] = xe_map_rd_ring_u32(xe, &h2g->cmds, head, size);
1909 	len = FIELD_GET(GUC_CTB_MSG_0_NUM_DWORDS, msg[0]) + GUC_CTB_MSG_MIN_LEN;
1910 
1911 	if (unlikely(len > (u32)avail)) {
1912 		xe_gt_err(gt, "H2G channel broken on read, avail=%d, len=%d, fixups skipped\n",
1913 			  avail, len);
1914 		return 0;
1915 	}
1916 
1917 	head = (head + GUC_CTB_MSG_MIN_LEN) % size;
1918 	if (!ct_fixup_ggtt_in_message(ct, &h2g->cmds, head, msg_len_to_hxg_len(len), size, shift))
1919 		return 0;
1920 	*mhead = (head + msg_len_to_hxg_len(len)) % size;
1921 
1922 	return avail - len;
1923 }
1924 
1925 /**
1926  * xe_guc_ct_fixup_messages_with_ggtt - Fixup any pending H2G CTB messages
1927  * @ct: pointer to CT struct of the target GuC
1928  * @ggtt_shift: shift to be added to all GGTT addresses within the CTB
1929  *
1930  * Messages in GuC to Host CTB are owned by GuC and any fixups in them
1931  * are made by GuC. But content of the Host to GuC CTB is owned by the
1932  * KMD, so fixups to GGTT references in any pending messages need to be
1933  * applied here.
1934  * This function updates GGTT offsets in payloads of pending H2G CTB
1935  * messages (messages which were not consumed by GuC before the VF got
1936  * paused).
1937  */
xe_guc_ct_fixup_messages_with_ggtt(struct xe_guc_ct * ct,s64 ggtt_shift)1938 void xe_guc_ct_fixup_messages_with_ggtt(struct xe_guc_ct *ct, s64 ggtt_shift)
1939 {
1940 	struct guc_ctb *h2g = &ct->ctbs.h2g;
1941 	struct xe_guc *guc = ct_to_guc(ct);
1942 	struct xe_gt *gt = guc_to_gt(guc);
1943 	u32 head, tail, size;
1944 	s32 avail;
1945 
1946 	if (unlikely(h2g->info.broken))
1947 		return;
1948 
1949 	h2g->info.head = desc_read(ct_to_xe(ct), h2g, head);
1950 	head = h2g->info.head;
1951 	tail = READ_ONCE(h2g->info.tail);
1952 	size = h2g->info.size;
1953 
1954 	if (unlikely(head > size))
1955 		goto corrupted;
1956 
1957 	if (unlikely(tail >= size))
1958 		goto corrupted;
1959 
1960 	avail = tail - head;
1961 
1962 	/* beware of buffer wrap case */
1963 	if (unlikely(avail < 0))
1964 		avail += size;
1965 	xe_gt_dbg(gt, "available %d (%u:%u:%u)\n", avail, head, tail, size);
1966 	xe_gt_assert(gt, avail >= 0);
1967 
1968 	while (avail > 0)
1969 		avail = ct_fixup_ggtt_in_buffer(ct, h2g, ggtt_shift, &head, avail);
1970 
1971 	return;
1972 
1973 corrupted:
1974 	xe_gt_err(gt, "Corrupted H2G descriptor head=%u tail=%u size=%u, fixups not applied\n",
1975 		  head, tail, size);
1976 	h2g->info.broken = true;
1977 }
1978 
guc_ct_snapshot_alloc(struct xe_guc_ct * ct,bool atomic,bool want_ctb)1979 static struct xe_guc_ct_snapshot *guc_ct_snapshot_alloc(struct xe_guc_ct *ct, bool atomic,
1980 							bool want_ctb)
1981 {
1982 	struct xe_guc_ct_snapshot *snapshot;
1983 
1984 	snapshot = kzalloc(sizeof(*snapshot), atomic ? GFP_ATOMIC : GFP_KERNEL);
1985 	if (!snapshot)
1986 		return NULL;
1987 
1988 	if (ct->bo && want_ctb) {
1989 		snapshot->ctb_size = xe_bo_size(ct->bo);
1990 		snapshot->ctb = kmalloc(snapshot->ctb_size, atomic ? GFP_ATOMIC : GFP_KERNEL);
1991 	}
1992 
1993 	return snapshot;
1994 }
1995 
guc_ctb_snapshot_capture(struct xe_device * xe,struct guc_ctb * ctb,struct guc_ctb_snapshot * snapshot)1996 static void guc_ctb_snapshot_capture(struct xe_device *xe, struct guc_ctb *ctb,
1997 				     struct guc_ctb_snapshot *snapshot)
1998 {
1999 	xe_map_memcpy_from(xe, &snapshot->desc, &ctb->desc, 0,
2000 			   sizeof(struct guc_ct_buffer_desc));
2001 	memcpy(&snapshot->info, &ctb->info, sizeof(struct guc_ctb_info));
2002 }
2003 
guc_ctb_snapshot_print(struct guc_ctb_snapshot * snapshot,struct drm_printer * p)2004 static void guc_ctb_snapshot_print(struct guc_ctb_snapshot *snapshot,
2005 				   struct drm_printer *p)
2006 {
2007 	drm_printf(p, "\tsize: %d\n", snapshot->info.size);
2008 	drm_printf(p, "\tresv_space: %d\n", snapshot->info.resv_space);
2009 	drm_printf(p, "\thead: %d\n", snapshot->info.head);
2010 	drm_printf(p, "\ttail: %d\n", snapshot->info.tail);
2011 	drm_printf(p, "\tspace: %d\n", snapshot->info.space);
2012 	drm_printf(p, "\tbroken: %d\n", snapshot->info.broken);
2013 	drm_printf(p, "\thead (memory): %d\n", snapshot->desc.head);
2014 	drm_printf(p, "\ttail (memory): %d\n", snapshot->desc.tail);
2015 	drm_printf(p, "\tstatus (memory): 0x%x\n", snapshot->desc.status);
2016 }
2017 
guc_ct_snapshot_capture(struct xe_guc_ct * ct,bool atomic,bool want_ctb)2018 static struct xe_guc_ct_snapshot *guc_ct_snapshot_capture(struct xe_guc_ct *ct, bool atomic,
2019 							  bool want_ctb)
2020 {
2021 	struct xe_device *xe = ct_to_xe(ct);
2022 	struct xe_guc_ct_snapshot *snapshot;
2023 
2024 	snapshot = guc_ct_snapshot_alloc(ct, atomic, want_ctb);
2025 	if (!snapshot) {
2026 		xe_gt_err(ct_to_gt(ct), "Skipping CTB snapshot entirely.\n");
2027 		return NULL;
2028 	}
2029 
2030 	if (xe_guc_ct_enabled(ct) || ct->state == XE_GUC_CT_STATE_STOPPED) {
2031 		snapshot->ct_enabled = true;
2032 		snapshot->g2h_outstanding = READ_ONCE(ct->g2h_outstanding);
2033 		guc_ctb_snapshot_capture(xe, &ct->ctbs.h2g, &snapshot->h2g);
2034 		guc_ctb_snapshot_capture(xe, &ct->ctbs.g2h, &snapshot->g2h);
2035 	}
2036 
2037 	if (ct->bo && snapshot->ctb)
2038 		xe_map_memcpy_from(xe, snapshot->ctb, &ct->bo->vmap, 0, snapshot->ctb_size);
2039 
2040 	return snapshot;
2041 }
2042 
2043 /**
2044  * xe_guc_ct_snapshot_capture - Take a quick snapshot of the CT state.
2045  * @ct: GuC CT object.
2046  *
2047  * This can be printed out in a later stage like during dev_coredump
2048  * analysis. This is safe to be called during atomic context.
2049  *
2050  * Returns: a GuC CT snapshot object that must be freed by the caller
2051  * by using `xe_guc_ct_snapshot_free`.
2052  */
xe_guc_ct_snapshot_capture(struct xe_guc_ct * ct)2053 struct xe_guc_ct_snapshot *xe_guc_ct_snapshot_capture(struct xe_guc_ct *ct)
2054 {
2055 	return guc_ct_snapshot_capture(ct, true, true);
2056 }
2057 
2058 /**
2059  * xe_guc_ct_snapshot_print - Print out a given GuC CT snapshot.
2060  * @snapshot: GuC CT snapshot object.
2061  * @p: drm_printer where it will be printed out.
2062  *
2063  * This function prints out a given GuC CT snapshot object.
2064  */
xe_guc_ct_snapshot_print(struct xe_guc_ct_snapshot * snapshot,struct drm_printer * p)2065 void xe_guc_ct_snapshot_print(struct xe_guc_ct_snapshot *snapshot,
2066 			      struct drm_printer *p)
2067 {
2068 	if (!snapshot)
2069 		return;
2070 
2071 	if (snapshot->ct_enabled) {
2072 		drm_puts(p, "H2G CTB (all sizes in DW):\n");
2073 		guc_ctb_snapshot_print(&snapshot->h2g, p);
2074 
2075 		drm_puts(p, "G2H CTB (all sizes in DW):\n");
2076 		guc_ctb_snapshot_print(&snapshot->g2h, p);
2077 		drm_printf(p, "\tg2h outstanding: %d\n",
2078 			   snapshot->g2h_outstanding);
2079 
2080 		if (snapshot->ctb) {
2081 			drm_printf(p, "[CTB].length: 0x%zx\n", snapshot->ctb_size);
2082 			xe_print_blob_ascii85(p, "[CTB].data", '\n',
2083 					      snapshot->ctb, 0, snapshot->ctb_size);
2084 		}
2085 	} else {
2086 		drm_puts(p, "CT disabled\n");
2087 	}
2088 }
2089 
2090 /**
2091  * xe_guc_ct_snapshot_free - Free all allocated objects for a given snapshot.
2092  * @snapshot: GuC CT snapshot object.
2093  *
2094  * This function free all the memory that needed to be allocated at capture
2095  * time.
2096  */
xe_guc_ct_snapshot_free(struct xe_guc_ct_snapshot * snapshot)2097 void xe_guc_ct_snapshot_free(struct xe_guc_ct_snapshot *snapshot)
2098 {
2099 	if (!snapshot)
2100 		return;
2101 
2102 	kfree(snapshot->ctb);
2103 	kfree(snapshot);
2104 }
2105 
2106 /**
2107  * xe_guc_ct_print - GuC CT Print.
2108  * @ct: GuC CT.
2109  * @p: drm_printer where it will be printed out.
2110  * @want_ctb: Should the full CTB content be dumped (vs just the headers)
2111  *
2112  * This function will quickly capture a snapshot of the CT state
2113  * and immediately print it out.
2114  */
xe_guc_ct_print(struct xe_guc_ct * ct,struct drm_printer * p,bool want_ctb)2115 void xe_guc_ct_print(struct xe_guc_ct *ct, struct drm_printer *p, bool want_ctb)
2116 {
2117 	struct xe_guc_ct_snapshot *snapshot;
2118 
2119 	snapshot = guc_ct_snapshot_capture(ct, false, want_ctb);
2120 	xe_guc_ct_snapshot_print(snapshot, p);
2121 	xe_guc_ct_snapshot_free(snapshot);
2122 }
2123 
2124 #if IS_ENABLED(CONFIG_DRM_XE_DEBUG)
2125 
2126 #ifdef CONFIG_FUNCTION_ERROR_INJECTION
2127 /*
2128  * This is a helper function which assists the driver in identifying if a fault
2129  * injection test is currently active, allowing it to reduce unnecessary debug
2130  * output. Typically, the function returns zero, but the fault injection
2131  * framework can alter this to return an error. Since faults are injected
2132  * through this function, it's important to ensure the compiler doesn't optimize
2133  * it into an inline function. To avoid such optimization, the 'noinline'
2134  * attribute is applied. Compiler optimizes the static function defined in the
2135  * header file as an inline function.
2136  */
xe_is_injection_active(void)2137 noinline int xe_is_injection_active(void) { return 0; }
2138 ALLOW_ERROR_INJECTION(xe_is_injection_active, ERRNO);
2139 #else
xe_is_injection_active(void)2140 int xe_is_injection_active(void) { return 0; }
2141 #endif
2142 
ct_dead_capture(struct xe_guc_ct * ct,struct guc_ctb * ctb,u32 reason_code)2143 static void ct_dead_capture(struct xe_guc_ct *ct, struct guc_ctb *ctb, u32 reason_code)
2144 {
2145 	struct xe_guc_log_snapshot *snapshot_log;
2146 	struct xe_guc_ct_snapshot *snapshot_ct;
2147 	struct xe_guc *guc = ct_to_guc(ct);
2148 	unsigned long flags;
2149 	bool have_capture;
2150 
2151 	if (ctb)
2152 		ctb->info.broken = true;
2153 	/*
2154 	 * Huge dump is getting generated when injecting error for guc CT/MMIO
2155 	 * functions. So, let us suppress the dump when fault is injected.
2156 	 */
2157 	if (xe_is_injection_active())
2158 		return;
2159 
2160 	/* Ignore further errors after the first dump until a reset */
2161 	if (ct->dead.reported)
2162 		return;
2163 
2164 	spin_lock_irqsave(&ct->dead.lock, flags);
2165 
2166 	/* And only capture one dump at a time */
2167 	have_capture = ct->dead.reason & (1 << CT_DEAD_STATE_CAPTURE);
2168 	ct->dead.reason |= (1 << reason_code) |
2169 			   (1 << CT_DEAD_STATE_CAPTURE);
2170 
2171 	spin_unlock_irqrestore(&ct->dead.lock, flags);
2172 
2173 	if (have_capture)
2174 		return;
2175 
2176 	snapshot_log = xe_guc_log_snapshot_capture(&guc->log, true);
2177 	snapshot_ct = xe_guc_ct_snapshot_capture((ct));
2178 
2179 	spin_lock_irqsave(&ct->dead.lock, flags);
2180 
2181 	if (ct->dead.snapshot_log || ct->dead.snapshot_ct) {
2182 		xe_gt_err(ct_to_gt(ct), "Got unexpected dead CT capture!\n");
2183 		xe_guc_log_snapshot_free(snapshot_log);
2184 		xe_guc_ct_snapshot_free(snapshot_ct);
2185 	} else {
2186 		ct->dead.snapshot_log = snapshot_log;
2187 		ct->dead.snapshot_ct = snapshot_ct;
2188 	}
2189 
2190 	spin_unlock_irqrestore(&ct->dead.lock, flags);
2191 
2192 	queue_work(system_unbound_wq, &(ct)->dead.worker);
2193 }
2194 
ct_dead_print(struct xe_dead_ct * dead)2195 static void ct_dead_print(struct xe_dead_ct *dead)
2196 {
2197 	struct xe_guc_ct *ct = container_of(dead, struct xe_guc_ct, dead);
2198 	struct xe_device *xe = ct_to_xe(ct);
2199 	struct xe_gt *gt = ct_to_gt(ct);
2200 	static int g_count;
2201 	struct drm_printer ip = xe_gt_info_printer(gt);
2202 	struct drm_printer lp = drm_line_printer(&ip, "Capture", ++g_count);
2203 
2204 	if (!dead->reason) {
2205 		xe_gt_err(gt, "CTB is dead for no reason!?\n");
2206 		return;
2207 	}
2208 
2209 	/* Can't generate a genuine core dump at this point, so just do the good bits */
2210 	drm_puts(&lp, "**** Xe Device Coredump ****\n");
2211 	drm_printf(&lp, "Reason: CTB is dead - 0x%X\n", dead->reason);
2212 	xe_device_snapshot_print(xe, &lp);
2213 
2214 	drm_printf(&lp, "**** GT #%d ****\n", gt->info.id);
2215 	drm_printf(&lp, "\tTile: %d\n", gt->tile->id);
2216 
2217 	drm_puts(&lp, "**** GuC Log ****\n");
2218 	xe_guc_log_snapshot_print(dead->snapshot_log, &lp);
2219 
2220 	drm_puts(&lp, "**** GuC CT ****\n");
2221 	xe_guc_ct_snapshot_print(dead->snapshot_ct, &lp);
2222 
2223 	drm_puts(&lp, "Done.\n");
2224 }
2225 
ct_dead_worker_func(struct work_struct * w)2226 static void ct_dead_worker_func(struct work_struct *w)
2227 {
2228 	struct xe_guc_ct *ct = container_of(w, struct xe_guc_ct, dead.worker);
2229 
2230 	if (!ct->dead.reported) {
2231 		ct->dead.reported = true;
2232 		ct_dead_print(&ct->dead);
2233 	}
2234 
2235 	spin_lock_irq(&ct->dead.lock);
2236 
2237 	xe_guc_log_snapshot_free(ct->dead.snapshot_log);
2238 	ct->dead.snapshot_log = NULL;
2239 	xe_guc_ct_snapshot_free(ct->dead.snapshot_ct);
2240 	ct->dead.snapshot_ct = NULL;
2241 
2242 	if (ct->dead.reason & (1 << CT_DEAD_STATE_REARM)) {
2243 		/* A reset has occurred so re-arm the error reporting */
2244 		ct->dead.reason = 0;
2245 		ct->dead.reported = false;
2246 	}
2247 
2248 	spin_unlock_irq(&ct->dead.lock);
2249 }
2250 #endif
2251