xref: /linux/drivers/gpu/drm/xe/xe_guc_submit.c (revision e7e86d7697c6ed1dbbde18d7185c35b6967945ed)
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright © 2022 Intel Corporation
4  */
5 
6 #include "xe_guc_submit.h"
7 
8 #include <linux/bitfield.h>
9 #include <linux/bitmap.h>
10 #include <linux/circ_buf.h>
11 #include <linux/delay.h>
12 #include <linux/dma-fence-array.h>
13 #include <linux/math64.h>
14 
15 #include <drm/drm_managed.h>
16 
17 #include "abi/guc_actions_abi.h"
18 #include "abi/guc_actions_slpc_abi.h"
19 #include "abi/guc_klvs_abi.h"
20 #include "regs/xe_lrc_layout.h"
21 #include "xe_assert.h"
22 #include "xe_devcoredump.h"
23 #include "xe_device.h"
24 #include "xe_exec_queue.h"
25 #include "xe_force_wake.h"
26 #include "xe_gpu_scheduler.h"
27 #include "xe_gt.h"
28 #include "xe_gt_clock.h"
29 #include "xe_gt_printk.h"
30 #include "xe_guc.h"
31 #include "xe_guc_capture.h"
32 #include "xe_guc_ct.h"
33 #include "xe_guc_exec_queue_types.h"
34 #include "xe_guc_id_mgr.h"
35 #include "xe_guc_klv_helpers.h"
36 #include "xe_guc_submit_types.h"
37 #include "xe_hw_engine.h"
38 #include "xe_hw_fence.h"
39 #include "xe_lrc.h"
40 #include "xe_macros.h"
41 #include "xe_map.h"
42 #include "xe_mocs.h"
43 #include "xe_pm.h"
44 #include "xe_ring_ops_types.h"
45 #include "xe_sched_job.h"
46 #include "xe_trace.h"
47 #include "xe_vm.h"
48 
49 static struct xe_guc *
50 exec_queue_to_guc(struct xe_exec_queue *q)
51 {
52 	return &q->gt->uc.guc;
53 }
54 
55 /*
56  * Helpers for engine state, using an atomic as some of the bits can transition
57  * as the same time (e.g. a suspend can be happning at the same time as schedule
58  * engine done being processed).
59  */
60 #define EXEC_QUEUE_STATE_REGISTERED		(1 << 0)
61 #define EXEC_QUEUE_STATE_ENABLED		(1 << 1)
62 #define EXEC_QUEUE_STATE_PENDING_ENABLE		(1 << 2)
63 #define EXEC_QUEUE_STATE_PENDING_DISABLE	(1 << 3)
64 #define EXEC_QUEUE_STATE_DESTROYED		(1 << 4)
65 #define EXEC_QUEUE_STATE_SUSPENDED		(1 << 5)
66 #define EXEC_QUEUE_STATE_RESET			(1 << 6)
67 #define EXEC_QUEUE_STATE_KILLED			(1 << 7)
68 #define EXEC_QUEUE_STATE_WEDGED			(1 << 8)
69 #define EXEC_QUEUE_STATE_BANNED			(1 << 9)
70 #define EXEC_QUEUE_STATE_CHECK_TIMEOUT		(1 << 10)
71 #define EXEC_QUEUE_STATE_EXTRA_REF		(1 << 11)
72 
73 static bool exec_queue_registered(struct xe_exec_queue *q)
74 {
75 	return atomic_read(&q->guc->state) & EXEC_QUEUE_STATE_REGISTERED;
76 }
77 
78 static void set_exec_queue_registered(struct xe_exec_queue *q)
79 {
80 	atomic_or(EXEC_QUEUE_STATE_REGISTERED, &q->guc->state);
81 }
82 
83 static void clear_exec_queue_registered(struct xe_exec_queue *q)
84 {
85 	atomic_and(~EXEC_QUEUE_STATE_REGISTERED, &q->guc->state);
86 }
87 
88 static bool exec_queue_enabled(struct xe_exec_queue *q)
89 {
90 	return atomic_read(&q->guc->state) & EXEC_QUEUE_STATE_ENABLED;
91 }
92 
93 static void set_exec_queue_enabled(struct xe_exec_queue *q)
94 {
95 	atomic_or(EXEC_QUEUE_STATE_ENABLED, &q->guc->state);
96 }
97 
98 static void clear_exec_queue_enabled(struct xe_exec_queue *q)
99 {
100 	atomic_and(~EXEC_QUEUE_STATE_ENABLED, &q->guc->state);
101 }
102 
103 static bool exec_queue_pending_enable(struct xe_exec_queue *q)
104 {
105 	return atomic_read(&q->guc->state) & EXEC_QUEUE_STATE_PENDING_ENABLE;
106 }
107 
108 static void set_exec_queue_pending_enable(struct xe_exec_queue *q)
109 {
110 	atomic_or(EXEC_QUEUE_STATE_PENDING_ENABLE, &q->guc->state);
111 }
112 
113 static void clear_exec_queue_pending_enable(struct xe_exec_queue *q)
114 {
115 	atomic_and(~EXEC_QUEUE_STATE_PENDING_ENABLE, &q->guc->state);
116 }
117 
118 static bool exec_queue_pending_disable(struct xe_exec_queue *q)
119 {
120 	return atomic_read(&q->guc->state) & EXEC_QUEUE_STATE_PENDING_DISABLE;
121 }
122 
123 static void set_exec_queue_pending_disable(struct xe_exec_queue *q)
124 {
125 	atomic_or(EXEC_QUEUE_STATE_PENDING_DISABLE, &q->guc->state);
126 }
127 
128 static void clear_exec_queue_pending_disable(struct xe_exec_queue *q)
129 {
130 	atomic_and(~EXEC_QUEUE_STATE_PENDING_DISABLE, &q->guc->state);
131 }
132 
133 static bool exec_queue_destroyed(struct xe_exec_queue *q)
134 {
135 	return atomic_read(&q->guc->state) & EXEC_QUEUE_STATE_DESTROYED;
136 }
137 
138 static void set_exec_queue_destroyed(struct xe_exec_queue *q)
139 {
140 	atomic_or(EXEC_QUEUE_STATE_DESTROYED, &q->guc->state);
141 }
142 
143 static bool exec_queue_banned(struct xe_exec_queue *q)
144 {
145 	return atomic_read(&q->guc->state) & EXEC_QUEUE_STATE_BANNED;
146 }
147 
148 static void set_exec_queue_banned(struct xe_exec_queue *q)
149 {
150 	atomic_or(EXEC_QUEUE_STATE_BANNED, &q->guc->state);
151 }
152 
153 static bool exec_queue_suspended(struct xe_exec_queue *q)
154 {
155 	return atomic_read(&q->guc->state) & EXEC_QUEUE_STATE_SUSPENDED;
156 }
157 
158 static void set_exec_queue_suspended(struct xe_exec_queue *q)
159 {
160 	atomic_or(EXEC_QUEUE_STATE_SUSPENDED, &q->guc->state);
161 }
162 
163 static void clear_exec_queue_suspended(struct xe_exec_queue *q)
164 {
165 	atomic_and(~EXEC_QUEUE_STATE_SUSPENDED, &q->guc->state);
166 }
167 
168 static bool exec_queue_reset(struct xe_exec_queue *q)
169 {
170 	return atomic_read(&q->guc->state) & EXEC_QUEUE_STATE_RESET;
171 }
172 
173 static void set_exec_queue_reset(struct xe_exec_queue *q)
174 {
175 	atomic_or(EXEC_QUEUE_STATE_RESET, &q->guc->state);
176 }
177 
178 static bool exec_queue_killed(struct xe_exec_queue *q)
179 {
180 	return atomic_read(&q->guc->state) & EXEC_QUEUE_STATE_KILLED;
181 }
182 
183 static void set_exec_queue_killed(struct xe_exec_queue *q)
184 {
185 	atomic_or(EXEC_QUEUE_STATE_KILLED, &q->guc->state);
186 }
187 
188 static bool exec_queue_wedged(struct xe_exec_queue *q)
189 {
190 	return atomic_read(&q->guc->state) & EXEC_QUEUE_STATE_WEDGED;
191 }
192 
193 static void set_exec_queue_wedged(struct xe_exec_queue *q)
194 {
195 	atomic_or(EXEC_QUEUE_STATE_WEDGED, &q->guc->state);
196 }
197 
198 static bool exec_queue_check_timeout(struct xe_exec_queue *q)
199 {
200 	return atomic_read(&q->guc->state) & EXEC_QUEUE_STATE_CHECK_TIMEOUT;
201 }
202 
203 static void set_exec_queue_check_timeout(struct xe_exec_queue *q)
204 {
205 	atomic_or(EXEC_QUEUE_STATE_CHECK_TIMEOUT, &q->guc->state);
206 }
207 
208 static void clear_exec_queue_check_timeout(struct xe_exec_queue *q)
209 {
210 	atomic_and(~EXEC_QUEUE_STATE_CHECK_TIMEOUT, &q->guc->state);
211 }
212 
213 static bool exec_queue_extra_ref(struct xe_exec_queue *q)
214 {
215 	return atomic_read(&q->guc->state) & EXEC_QUEUE_STATE_EXTRA_REF;
216 }
217 
218 static void set_exec_queue_extra_ref(struct xe_exec_queue *q)
219 {
220 	atomic_or(EXEC_QUEUE_STATE_EXTRA_REF, &q->guc->state);
221 }
222 
223 static bool exec_queue_killed_or_banned_or_wedged(struct xe_exec_queue *q)
224 {
225 	return (atomic_read(&q->guc->state) &
226 		(EXEC_QUEUE_STATE_WEDGED | EXEC_QUEUE_STATE_KILLED |
227 		 EXEC_QUEUE_STATE_BANNED));
228 }
229 
230 static void guc_submit_fini(struct drm_device *drm, void *arg)
231 {
232 	struct xe_guc *guc = arg;
233 	struct xe_device *xe = guc_to_xe(guc);
234 	struct xe_gt *gt = guc_to_gt(guc);
235 	int ret;
236 
237 	ret = wait_event_timeout(guc->submission_state.fini_wq,
238 				 xa_empty(&guc->submission_state.exec_queue_lookup),
239 				 HZ * 5);
240 
241 	drain_workqueue(xe->destroy_wq);
242 
243 	xe_gt_assert(gt, ret);
244 
245 	xa_destroy(&guc->submission_state.exec_queue_lookup);
246 }
247 
248 static void guc_submit_wedged_fini(void *arg)
249 {
250 	struct xe_guc *guc = arg;
251 	struct xe_exec_queue *q;
252 	unsigned long index;
253 
254 	mutex_lock(&guc->submission_state.lock);
255 	xa_for_each(&guc->submission_state.exec_queue_lookup, index, q) {
256 		if (exec_queue_wedged(q)) {
257 			mutex_unlock(&guc->submission_state.lock);
258 			xe_exec_queue_put(q);
259 			mutex_lock(&guc->submission_state.lock);
260 		}
261 	}
262 	mutex_unlock(&guc->submission_state.lock);
263 }
264 
265 static const struct xe_exec_queue_ops guc_exec_queue_ops;
266 
267 static void primelockdep(struct xe_guc *guc)
268 {
269 	if (!IS_ENABLED(CONFIG_LOCKDEP))
270 		return;
271 
272 	fs_reclaim_acquire(GFP_KERNEL);
273 
274 	mutex_lock(&guc->submission_state.lock);
275 	mutex_unlock(&guc->submission_state.lock);
276 
277 	fs_reclaim_release(GFP_KERNEL);
278 }
279 
280 /**
281  * xe_guc_submit_init() - Initialize GuC submission.
282  * @guc: the &xe_guc to initialize
283  * @num_ids: number of GuC context IDs to use
284  *
285  * The bare-metal or PF driver can pass ~0 as &num_ids to indicate that all
286  * GuC context IDs supported by the GuC firmware should be used for submission.
287  *
288  * Only VF drivers will have to provide explicit number of GuC context IDs
289  * that they can use for submission.
290  *
291  * Return: 0 on success or a negative error code on failure.
292  */
293 int xe_guc_submit_init(struct xe_guc *guc, unsigned int num_ids)
294 {
295 	struct xe_device *xe = guc_to_xe(guc);
296 	struct xe_gt *gt = guc_to_gt(guc);
297 	int err;
298 
299 	err = drmm_mutex_init(&xe->drm, &guc->submission_state.lock);
300 	if (err)
301 		return err;
302 
303 	err = xe_guc_id_mgr_init(&guc->submission_state.idm, num_ids);
304 	if (err)
305 		return err;
306 
307 	gt->exec_queue_ops = &guc_exec_queue_ops;
308 
309 	xa_init(&guc->submission_state.exec_queue_lookup);
310 
311 	init_waitqueue_head(&guc->submission_state.fini_wq);
312 
313 	primelockdep(guc);
314 
315 	guc->submission_state.initialized = true;
316 
317 	return drmm_add_action_or_reset(&xe->drm, guc_submit_fini, guc);
318 }
319 
320 /*
321  * Given that we want to guarantee enough RCS throughput to avoid missing
322  * frames, we set the yield policy to 20% of each 80ms interval.
323  */
324 #define RC_YIELD_DURATION	80	/* in ms */
325 #define RC_YIELD_RATIO		20	/* in percent */
326 static u32 *emit_render_compute_yield_klv(u32 *emit)
327 {
328 	*emit++ = PREP_GUC_KLV_TAG(SCHEDULING_POLICIES_RENDER_COMPUTE_YIELD);
329 	*emit++ = RC_YIELD_DURATION;
330 	*emit++ = RC_YIELD_RATIO;
331 
332 	return emit;
333 }
334 
335 #define SCHEDULING_POLICY_MAX_DWORDS 16
336 static int guc_init_global_schedule_policy(struct xe_guc *guc)
337 {
338 	u32 data[SCHEDULING_POLICY_MAX_DWORDS];
339 	u32 *emit = data;
340 	u32 count = 0;
341 	int ret;
342 
343 	if (GUC_SUBMIT_VER(guc) < MAKE_GUC_VER(1, 1, 0))
344 		return 0;
345 
346 	*emit++ = XE_GUC_ACTION_UPDATE_SCHEDULING_POLICIES_KLV;
347 
348 	if (CCS_MASK(guc_to_gt(guc)))
349 		emit = emit_render_compute_yield_klv(emit);
350 
351 	count = emit - data;
352 	if (count > 1) {
353 		xe_assert(guc_to_xe(guc), count <= SCHEDULING_POLICY_MAX_DWORDS);
354 
355 		ret = xe_guc_ct_send_block(&guc->ct, data, count);
356 		if (ret < 0) {
357 			xe_gt_err(guc_to_gt(guc),
358 				  "failed to enable GuC sheduling policies: %pe\n",
359 				  ERR_PTR(ret));
360 			return ret;
361 		}
362 	}
363 
364 	return 0;
365 }
366 
367 int xe_guc_submit_enable(struct xe_guc *guc)
368 {
369 	int ret;
370 
371 	ret = guc_init_global_schedule_policy(guc);
372 	if (ret)
373 		return ret;
374 
375 	guc->submission_state.enabled = true;
376 
377 	return 0;
378 }
379 
380 void xe_guc_submit_disable(struct xe_guc *guc)
381 {
382 	guc->submission_state.enabled = false;
383 }
384 
385 static void __release_guc_id(struct xe_guc *guc, struct xe_exec_queue *q, u32 xa_count)
386 {
387 	int i;
388 
389 	lockdep_assert_held(&guc->submission_state.lock);
390 
391 	for (i = 0; i < xa_count; ++i)
392 		xa_erase(&guc->submission_state.exec_queue_lookup, q->guc->id + i);
393 
394 	xe_guc_id_mgr_release_locked(&guc->submission_state.idm,
395 				     q->guc->id, q->width);
396 
397 	if (xa_empty(&guc->submission_state.exec_queue_lookup))
398 		wake_up(&guc->submission_state.fini_wq);
399 }
400 
401 static int alloc_guc_id(struct xe_guc *guc, struct xe_exec_queue *q)
402 {
403 	int ret;
404 	int i;
405 
406 	/*
407 	 * Must use GFP_NOWAIT as this lock is in the dma fence signalling path,
408 	 * worse case user gets -ENOMEM on engine create and has to try again.
409 	 *
410 	 * FIXME: Have caller pre-alloc or post-alloc /w GFP_KERNEL to prevent
411 	 * failure.
412 	 */
413 	lockdep_assert_held(&guc->submission_state.lock);
414 
415 	ret = xe_guc_id_mgr_reserve_locked(&guc->submission_state.idm,
416 					   q->width);
417 	if (ret < 0)
418 		return ret;
419 
420 	q->guc->id = ret;
421 
422 	for (i = 0; i < q->width; ++i) {
423 		ret = xa_err(xa_store(&guc->submission_state.exec_queue_lookup,
424 				      q->guc->id + i, q, GFP_NOWAIT));
425 		if (ret)
426 			goto err_release;
427 	}
428 
429 	return 0;
430 
431 err_release:
432 	__release_guc_id(guc, q, i);
433 
434 	return ret;
435 }
436 
437 static void release_guc_id(struct xe_guc *guc, struct xe_exec_queue *q)
438 {
439 	mutex_lock(&guc->submission_state.lock);
440 	__release_guc_id(guc, q, q->width);
441 	mutex_unlock(&guc->submission_state.lock);
442 }
443 
444 struct exec_queue_policy {
445 	u32 count;
446 	struct guc_update_exec_queue_policy h2g;
447 };
448 
449 static u32 __guc_exec_queue_policy_action_size(struct exec_queue_policy *policy)
450 {
451 	size_t bytes = sizeof(policy->h2g.header) +
452 		       (sizeof(policy->h2g.klv[0]) * policy->count);
453 
454 	return bytes / sizeof(u32);
455 }
456 
457 static void __guc_exec_queue_policy_start_klv(struct exec_queue_policy *policy,
458 					      u16 guc_id)
459 {
460 	policy->h2g.header.action =
461 		XE_GUC_ACTION_HOST2GUC_UPDATE_CONTEXT_POLICIES;
462 	policy->h2g.header.guc_id = guc_id;
463 	policy->count = 0;
464 }
465 
466 #define MAKE_EXEC_QUEUE_POLICY_ADD(func, id) \
467 static void __guc_exec_queue_policy_add_##func(struct exec_queue_policy *policy, \
468 					   u32 data) \
469 { \
470 	XE_WARN_ON(policy->count >= GUC_CONTEXT_POLICIES_KLV_NUM_IDS); \
471 \
472 	policy->h2g.klv[policy->count].kl = \
473 		FIELD_PREP(GUC_KLV_0_KEY, \
474 			   GUC_CONTEXT_POLICIES_KLV_ID_##id) | \
475 		FIELD_PREP(GUC_KLV_0_LEN, 1); \
476 	policy->h2g.klv[policy->count].value = data; \
477 	policy->count++; \
478 }
479 
480 MAKE_EXEC_QUEUE_POLICY_ADD(execution_quantum, EXECUTION_QUANTUM)
481 MAKE_EXEC_QUEUE_POLICY_ADD(preemption_timeout, PREEMPTION_TIMEOUT)
482 MAKE_EXEC_QUEUE_POLICY_ADD(priority, SCHEDULING_PRIORITY)
483 MAKE_EXEC_QUEUE_POLICY_ADD(slpc_exec_queue_freq_req, SLPM_GT_FREQUENCY)
484 #undef MAKE_EXEC_QUEUE_POLICY_ADD
485 
486 static const int xe_exec_queue_prio_to_guc[] = {
487 	[XE_EXEC_QUEUE_PRIORITY_LOW] = GUC_CLIENT_PRIORITY_NORMAL,
488 	[XE_EXEC_QUEUE_PRIORITY_NORMAL] = GUC_CLIENT_PRIORITY_KMD_NORMAL,
489 	[XE_EXEC_QUEUE_PRIORITY_HIGH] = GUC_CLIENT_PRIORITY_HIGH,
490 	[XE_EXEC_QUEUE_PRIORITY_KERNEL] = GUC_CLIENT_PRIORITY_KMD_HIGH,
491 };
492 
493 static void init_policies(struct xe_guc *guc, struct xe_exec_queue *q)
494 {
495 	struct exec_queue_policy policy;
496 	enum xe_exec_queue_priority prio = q->sched_props.priority;
497 	u32 timeslice_us = q->sched_props.timeslice_us;
498 	u32 slpc_exec_queue_freq_req = 0;
499 	u32 preempt_timeout_us = q->sched_props.preempt_timeout_us;
500 
501 	xe_gt_assert(guc_to_gt(guc), exec_queue_registered(q));
502 
503 	if (q->flags & EXEC_QUEUE_FLAG_LOW_LATENCY)
504 		slpc_exec_queue_freq_req |= SLPC_CTX_FREQ_REQ_IS_COMPUTE;
505 
506 	__guc_exec_queue_policy_start_klv(&policy, q->guc->id);
507 	__guc_exec_queue_policy_add_priority(&policy, xe_exec_queue_prio_to_guc[prio]);
508 	__guc_exec_queue_policy_add_execution_quantum(&policy, timeslice_us);
509 	__guc_exec_queue_policy_add_preemption_timeout(&policy, preempt_timeout_us);
510 	__guc_exec_queue_policy_add_slpc_exec_queue_freq_req(&policy,
511 							     slpc_exec_queue_freq_req);
512 
513 	xe_guc_ct_send(&guc->ct, (u32 *)&policy.h2g,
514 		       __guc_exec_queue_policy_action_size(&policy), 0, 0);
515 }
516 
517 static void set_min_preemption_timeout(struct xe_guc *guc, struct xe_exec_queue *q)
518 {
519 	struct exec_queue_policy policy;
520 
521 	__guc_exec_queue_policy_start_klv(&policy, q->guc->id);
522 	__guc_exec_queue_policy_add_preemption_timeout(&policy, 1);
523 
524 	xe_guc_ct_send(&guc->ct, (u32 *)&policy.h2g,
525 		       __guc_exec_queue_policy_action_size(&policy), 0, 0);
526 }
527 
528 #define parallel_read(xe_, map_, field_) \
529 	xe_map_rd_field(xe_, &map_, 0, struct guc_submit_parallel_scratch, \
530 			field_)
531 #define parallel_write(xe_, map_, field_, val_) \
532 	xe_map_wr_field(xe_, &map_, 0, struct guc_submit_parallel_scratch, \
533 			field_, val_)
534 
535 static void __register_mlrc_exec_queue(struct xe_guc *guc,
536 				       struct xe_exec_queue *q,
537 				       struct guc_ctxt_registration_info *info)
538 {
539 #define MAX_MLRC_REG_SIZE      (13 + XE_HW_ENGINE_MAX_INSTANCE * 2)
540 	u32 action[MAX_MLRC_REG_SIZE];
541 	int len = 0;
542 	int i;
543 
544 	xe_gt_assert(guc_to_gt(guc), xe_exec_queue_is_parallel(q));
545 
546 	action[len++] = XE_GUC_ACTION_REGISTER_CONTEXT_MULTI_LRC;
547 	action[len++] = info->flags;
548 	action[len++] = info->context_idx;
549 	action[len++] = info->engine_class;
550 	action[len++] = info->engine_submit_mask;
551 	action[len++] = info->wq_desc_lo;
552 	action[len++] = info->wq_desc_hi;
553 	action[len++] = info->wq_base_lo;
554 	action[len++] = info->wq_base_hi;
555 	action[len++] = info->wq_size;
556 	action[len++] = q->width;
557 	action[len++] = info->hwlrca_lo;
558 	action[len++] = info->hwlrca_hi;
559 
560 	for (i = 1; i < q->width; ++i) {
561 		struct xe_lrc *lrc = q->lrc[i];
562 
563 		action[len++] = lower_32_bits(xe_lrc_descriptor(lrc));
564 		action[len++] = upper_32_bits(xe_lrc_descriptor(lrc));
565 	}
566 
567 	/* explicitly checks some fields that we might fixup later */
568 	xe_gt_assert(guc_to_gt(guc), info->wq_desc_lo ==
569 		     action[XE_GUC_REGISTER_CONTEXT_MULTI_LRC_DATA_5_WQ_DESC_ADDR_LOWER]);
570 	xe_gt_assert(guc_to_gt(guc), info->wq_base_lo ==
571 		     action[XE_GUC_REGISTER_CONTEXT_MULTI_LRC_DATA_7_WQ_BUF_BASE_LOWER]);
572 	xe_gt_assert(guc_to_gt(guc), q->width ==
573 		     action[XE_GUC_REGISTER_CONTEXT_MULTI_LRC_DATA_10_NUM_CTXS]);
574 	xe_gt_assert(guc_to_gt(guc), info->hwlrca_lo ==
575 		     action[XE_GUC_REGISTER_CONTEXT_MULTI_LRC_DATA_11_HW_LRC_ADDR]);
576 	xe_gt_assert(guc_to_gt(guc), len <= MAX_MLRC_REG_SIZE);
577 #undef MAX_MLRC_REG_SIZE
578 
579 	xe_guc_ct_send(&guc->ct, action, len, 0, 0);
580 }
581 
582 static void __register_exec_queue(struct xe_guc *guc,
583 				  struct guc_ctxt_registration_info *info)
584 {
585 	u32 action[] = {
586 		XE_GUC_ACTION_REGISTER_CONTEXT,
587 		info->flags,
588 		info->context_idx,
589 		info->engine_class,
590 		info->engine_submit_mask,
591 		info->wq_desc_lo,
592 		info->wq_desc_hi,
593 		info->wq_base_lo,
594 		info->wq_base_hi,
595 		info->wq_size,
596 		info->hwlrca_lo,
597 		info->hwlrca_hi,
598 	};
599 
600 	/* explicitly checks some fields that we might fixup later */
601 	xe_gt_assert(guc_to_gt(guc), info->wq_desc_lo ==
602 		     action[XE_GUC_REGISTER_CONTEXT_DATA_5_WQ_DESC_ADDR_LOWER]);
603 	xe_gt_assert(guc_to_gt(guc), info->wq_base_lo ==
604 		     action[XE_GUC_REGISTER_CONTEXT_DATA_7_WQ_BUF_BASE_LOWER]);
605 	xe_gt_assert(guc_to_gt(guc), info->hwlrca_lo ==
606 		     action[XE_GUC_REGISTER_CONTEXT_DATA_10_HW_LRC_ADDR]);
607 
608 	xe_guc_ct_send(&guc->ct, action, ARRAY_SIZE(action), 0, 0);
609 }
610 
611 static void register_exec_queue(struct xe_exec_queue *q)
612 {
613 	struct xe_guc *guc = exec_queue_to_guc(q);
614 	struct xe_device *xe = guc_to_xe(guc);
615 	struct xe_lrc *lrc = q->lrc[0];
616 	struct guc_ctxt_registration_info info;
617 
618 	xe_gt_assert(guc_to_gt(guc), !exec_queue_registered(q));
619 
620 	memset(&info, 0, sizeof(info));
621 	info.context_idx = q->guc->id;
622 	info.engine_class = xe_engine_class_to_guc_class(q->class);
623 	info.engine_submit_mask = q->logical_mask;
624 	info.hwlrca_lo = lower_32_bits(xe_lrc_descriptor(lrc));
625 	info.hwlrca_hi = upper_32_bits(xe_lrc_descriptor(lrc));
626 	info.flags = CONTEXT_REGISTRATION_FLAG_KMD;
627 
628 	if (xe_exec_queue_is_parallel(q)) {
629 		u64 ggtt_addr = xe_lrc_parallel_ggtt_addr(lrc);
630 		struct iosys_map map = xe_lrc_parallel_map(lrc);
631 
632 		info.wq_desc_lo = lower_32_bits(ggtt_addr +
633 			offsetof(struct guc_submit_parallel_scratch, wq_desc));
634 		info.wq_desc_hi = upper_32_bits(ggtt_addr +
635 			offsetof(struct guc_submit_parallel_scratch, wq_desc));
636 		info.wq_base_lo = lower_32_bits(ggtt_addr +
637 			offsetof(struct guc_submit_parallel_scratch, wq[0]));
638 		info.wq_base_hi = upper_32_bits(ggtt_addr +
639 			offsetof(struct guc_submit_parallel_scratch, wq[0]));
640 		info.wq_size = WQ_SIZE;
641 
642 		q->guc->wqi_head = 0;
643 		q->guc->wqi_tail = 0;
644 		xe_map_memset(xe, &map, 0, 0, PARALLEL_SCRATCH_SIZE - WQ_SIZE);
645 		parallel_write(xe, map, wq_desc.wq_status, WQ_STATUS_ACTIVE);
646 	}
647 
648 	/*
649 	 * We must keep a reference for LR engines if engine is registered with
650 	 * the GuC as jobs signal immediately and can't destroy an engine if the
651 	 * GuC has a reference to it.
652 	 */
653 	if (xe_exec_queue_is_lr(q))
654 		xe_exec_queue_get(q);
655 
656 	set_exec_queue_registered(q);
657 	trace_xe_exec_queue_register(q);
658 	if (xe_exec_queue_is_parallel(q))
659 		__register_mlrc_exec_queue(guc, q, &info);
660 	else
661 		__register_exec_queue(guc, &info);
662 	init_policies(guc, q);
663 }
664 
665 static u32 wq_space_until_wrap(struct xe_exec_queue *q)
666 {
667 	return (WQ_SIZE - q->guc->wqi_tail);
668 }
669 
670 static int wq_wait_for_space(struct xe_exec_queue *q, u32 wqi_size)
671 {
672 	struct xe_guc *guc = exec_queue_to_guc(q);
673 	struct xe_device *xe = guc_to_xe(guc);
674 	struct iosys_map map = xe_lrc_parallel_map(q->lrc[0]);
675 	unsigned int sleep_period_ms = 1;
676 
677 #define AVAILABLE_SPACE \
678 	CIRC_SPACE(q->guc->wqi_tail, q->guc->wqi_head, WQ_SIZE)
679 	if (wqi_size > AVAILABLE_SPACE) {
680 try_again:
681 		q->guc->wqi_head = parallel_read(xe, map, wq_desc.head);
682 		if (wqi_size > AVAILABLE_SPACE) {
683 			if (sleep_period_ms == 1024) {
684 				xe_gt_reset_async(q->gt);
685 				return -ENODEV;
686 			}
687 
688 			msleep(sleep_period_ms);
689 			sleep_period_ms <<= 1;
690 			goto try_again;
691 		}
692 	}
693 #undef AVAILABLE_SPACE
694 
695 	return 0;
696 }
697 
698 static int wq_noop_append(struct xe_exec_queue *q)
699 {
700 	struct xe_guc *guc = exec_queue_to_guc(q);
701 	struct xe_device *xe = guc_to_xe(guc);
702 	struct iosys_map map = xe_lrc_parallel_map(q->lrc[0]);
703 	u32 len_dw = wq_space_until_wrap(q) / sizeof(u32) - 1;
704 
705 	if (wq_wait_for_space(q, wq_space_until_wrap(q)))
706 		return -ENODEV;
707 
708 	xe_gt_assert(guc_to_gt(guc), FIELD_FIT(WQ_LEN_MASK, len_dw));
709 
710 	parallel_write(xe, map, wq[q->guc->wqi_tail / sizeof(u32)],
711 		       FIELD_PREP(WQ_TYPE_MASK, WQ_TYPE_NOOP) |
712 		       FIELD_PREP(WQ_LEN_MASK, len_dw));
713 	q->guc->wqi_tail = 0;
714 
715 	return 0;
716 }
717 
718 static void wq_item_append(struct xe_exec_queue *q)
719 {
720 	struct xe_guc *guc = exec_queue_to_guc(q);
721 	struct xe_device *xe = guc_to_xe(guc);
722 	struct iosys_map map = xe_lrc_parallel_map(q->lrc[0]);
723 #define WQ_HEADER_SIZE	4	/* Includes 1 LRC address too */
724 	u32 wqi[XE_HW_ENGINE_MAX_INSTANCE + (WQ_HEADER_SIZE - 1)];
725 	u32 wqi_size = (q->width + (WQ_HEADER_SIZE - 1)) * sizeof(u32);
726 	u32 len_dw = (wqi_size / sizeof(u32)) - 1;
727 	int i = 0, j;
728 
729 	if (wqi_size > wq_space_until_wrap(q)) {
730 		if (wq_noop_append(q))
731 			return;
732 	}
733 	if (wq_wait_for_space(q, wqi_size))
734 		return;
735 
736 	wqi[i++] = FIELD_PREP(WQ_TYPE_MASK, WQ_TYPE_MULTI_LRC) |
737 		FIELD_PREP(WQ_LEN_MASK, len_dw);
738 	wqi[i++] = xe_lrc_descriptor(q->lrc[0]);
739 	wqi[i++] = FIELD_PREP(WQ_GUC_ID_MASK, q->guc->id) |
740 		FIELD_PREP(WQ_RING_TAIL_MASK, q->lrc[0]->ring.tail / sizeof(u64));
741 	wqi[i++] = 0;
742 	for (j = 1; j < q->width; ++j) {
743 		struct xe_lrc *lrc = q->lrc[j];
744 
745 		wqi[i++] = lrc->ring.tail / sizeof(u64);
746 	}
747 
748 	xe_gt_assert(guc_to_gt(guc), i == wqi_size / sizeof(u32));
749 
750 	iosys_map_incr(&map, offsetof(struct guc_submit_parallel_scratch,
751 				      wq[q->guc->wqi_tail / sizeof(u32)]));
752 	xe_map_memcpy_to(xe, &map, 0, wqi, wqi_size);
753 	q->guc->wqi_tail += wqi_size;
754 	xe_gt_assert(guc_to_gt(guc), q->guc->wqi_tail <= WQ_SIZE);
755 
756 	xe_device_wmb(xe);
757 
758 	map = xe_lrc_parallel_map(q->lrc[0]);
759 	parallel_write(xe, map, wq_desc.tail, q->guc->wqi_tail);
760 }
761 
762 #define RESUME_PENDING	~0x0ull
763 static void submit_exec_queue(struct xe_exec_queue *q)
764 {
765 	struct xe_guc *guc = exec_queue_to_guc(q);
766 	struct xe_lrc *lrc = q->lrc[0];
767 	u32 action[3];
768 	u32 g2h_len = 0;
769 	u32 num_g2h = 0;
770 	int len = 0;
771 	bool extra_submit = false;
772 
773 	xe_gt_assert(guc_to_gt(guc), exec_queue_registered(q));
774 
775 	if (xe_exec_queue_is_parallel(q))
776 		wq_item_append(q);
777 	else
778 		xe_lrc_set_ring_tail(lrc, lrc->ring.tail);
779 
780 	if (exec_queue_suspended(q) && !xe_exec_queue_is_parallel(q))
781 		return;
782 
783 	if (!exec_queue_enabled(q) && !exec_queue_suspended(q)) {
784 		action[len++] = XE_GUC_ACTION_SCHED_CONTEXT_MODE_SET;
785 		action[len++] = q->guc->id;
786 		action[len++] = GUC_CONTEXT_ENABLE;
787 		g2h_len = G2H_LEN_DW_SCHED_CONTEXT_MODE_SET;
788 		num_g2h = 1;
789 		if (xe_exec_queue_is_parallel(q))
790 			extra_submit = true;
791 
792 		q->guc->resume_time = RESUME_PENDING;
793 		set_exec_queue_pending_enable(q);
794 		set_exec_queue_enabled(q);
795 		trace_xe_exec_queue_scheduling_enable(q);
796 	} else {
797 		action[len++] = XE_GUC_ACTION_SCHED_CONTEXT;
798 		action[len++] = q->guc->id;
799 		trace_xe_exec_queue_submit(q);
800 	}
801 
802 	xe_guc_ct_send(&guc->ct, action, len, g2h_len, num_g2h);
803 
804 	if (extra_submit) {
805 		len = 0;
806 		action[len++] = XE_GUC_ACTION_SCHED_CONTEXT;
807 		action[len++] = q->guc->id;
808 		trace_xe_exec_queue_submit(q);
809 
810 		xe_guc_ct_send(&guc->ct, action, len, 0, 0);
811 	}
812 }
813 
814 static struct dma_fence *
815 guc_exec_queue_run_job(struct drm_sched_job *drm_job)
816 {
817 	struct xe_sched_job *job = to_xe_sched_job(drm_job);
818 	struct xe_exec_queue *q = job->q;
819 	struct xe_guc *guc = exec_queue_to_guc(q);
820 	struct dma_fence *fence = NULL;
821 	bool lr = xe_exec_queue_is_lr(q);
822 
823 	xe_gt_assert(guc_to_gt(guc), !(exec_queue_destroyed(q) || exec_queue_pending_disable(q)) ||
824 		     exec_queue_banned(q) || exec_queue_suspended(q));
825 
826 	trace_xe_sched_job_run(job);
827 
828 	if (!exec_queue_killed_or_banned_or_wedged(q) && !xe_sched_job_is_error(job)) {
829 		if (!exec_queue_registered(q))
830 			register_exec_queue(q);
831 		if (!lr)	/* LR jobs are emitted in the exec IOCTL */
832 			q->ring_ops->emit_job(job);
833 		submit_exec_queue(q);
834 	}
835 
836 	if (lr) {
837 		xe_sched_job_set_error(job, -EOPNOTSUPP);
838 		dma_fence_put(job->fence);	/* Drop ref from xe_sched_job_arm */
839 	} else {
840 		fence = job->fence;
841 	}
842 
843 	return fence;
844 }
845 
846 static void guc_exec_queue_free_job(struct drm_sched_job *drm_job)
847 {
848 	struct xe_sched_job *job = to_xe_sched_job(drm_job);
849 
850 	trace_xe_sched_job_free(job);
851 	xe_sched_job_put(job);
852 }
853 
854 int xe_guc_read_stopped(struct xe_guc *guc)
855 {
856 	return atomic_read(&guc->submission_state.stopped);
857 }
858 
859 #define MAKE_SCHED_CONTEXT_ACTION(q, enable_disable)			\
860 	u32 action[] = {						\
861 		XE_GUC_ACTION_SCHED_CONTEXT_MODE_SET,			\
862 		q->guc->id,						\
863 		GUC_CONTEXT_##enable_disable,				\
864 	}
865 
866 static void disable_scheduling_deregister(struct xe_guc *guc,
867 					  struct xe_exec_queue *q)
868 {
869 	MAKE_SCHED_CONTEXT_ACTION(q, DISABLE);
870 	int ret;
871 
872 	set_min_preemption_timeout(guc, q);
873 	smp_rmb();
874 	ret = wait_event_timeout(guc->ct.wq,
875 				 (!exec_queue_pending_enable(q) &&
876 				  !exec_queue_pending_disable(q)) ||
877 					 xe_guc_read_stopped(guc),
878 				 HZ * 5);
879 	if (!ret) {
880 		struct xe_gpu_scheduler *sched = &q->guc->sched;
881 
882 		xe_gt_warn(q->gt, "Pending enable/disable failed to respond\n");
883 		xe_sched_submission_start(sched);
884 		xe_gt_reset_async(q->gt);
885 		xe_sched_tdr_queue_imm(sched);
886 		return;
887 	}
888 
889 	clear_exec_queue_enabled(q);
890 	set_exec_queue_pending_disable(q);
891 	set_exec_queue_destroyed(q);
892 	trace_xe_exec_queue_scheduling_disable(q);
893 
894 	/*
895 	 * Reserve space for both G2H here as the 2nd G2H is sent from a G2H
896 	 * handler and we are not allowed to reserved G2H space in handlers.
897 	 */
898 	xe_guc_ct_send(&guc->ct, action, ARRAY_SIZE(action),
899 		       G2H_LEN_DW_SCHED_CONTEXT_MODE_SET +
900 		       G2H_LEN_DW_DEREGISTER_CONTEXT, 2);
901 }
902 
903 static void xe_guc_exec_queue_trigger_cleanup(struct xe_exec_queue *q)
904 {
905 	struct xe_guc *guc = exec_queue_to_guc(q);
906 	struct xe_device *xe = guc_to_xe(guc);
907 
908 	/** to wakeup xe_wait_user_fence ioctl if exec queue is reset */
909 	wake_up_all(&xe->ufence_wq);
910 
911 	if (xe_exec_queue_is_lr(q))
912 		queue_work(guc_to_gt(guc)->ordered_wq, &q->guc->lr_tdr);
913 	else
914 		xe_sched_tdr_queue_imm(&q->guc->sched);
915 }
916 
917 /**
918  * xe_guc_submit_wedge() - Wedge GuC submission
919  * @guc: the GuC object
920  *
921  * Save exec queue's registered with GuC state by taking a ref to each queue.
922  * Register a DRMM handler to drop refs upon driver unload.
923  */
924 void xe_guc_submit_wedge(struct xe_guc *guc)
925 {
926 	struct xe_gt *gt = guc_to_gt(guc);
927 	struct xe_exec_queue *q;
928 	unsigned long index;
929 	int err;
930 
931 	xe_gt_assert(guc_to_gt(guc), guc_to_xe(guc)->wedged.mode);
932 
933 	/*
934 	 * If device is being wedged even before submission_state is
935 	 * initialized, there's nothing to do here.
936 	 */
937 	if (!guc->submission_state.initialized)
938 		return;
939 
940 	err = devm_add_action_or_reset(guc_to_xe(guc)->drm.dev,
941 				       guc_submit_wedged_fini, guc);
942 	if (err) {
943 		xe_gt_err(gt, "Failed to register clean-up on wedged.mode=2; "
944 			  "Although device is wedged.\n");
945 		return;
946 	}
947 
948 	mutex_lock(&guc->submission_state.lock);
949 	xa_for_each(&guc->submission_state.exec_queue_lookup, index, q)
950 		if (xe_exec_queue_get_unless_zero(q))
951 			set_exec_queue_wedged(q);
952 	mutex_unlock(&guc->submission_state.lock);
953 }
954 
955 static bool guc_submit_hint_wedged(struct xe_guc *guc)
956 {
957 	struct xe_device *xe = guc_to_xe(guc);
958 
959 	if (xe->wedged.mode != 2)
960 		return false;
961 
962 	if (xe_device_wedged(xe))
963 		return true;
964 
965 	xe_device_declare_wedged(xe);
966 
967 	return true;
968 }
969 
970 static void xe_guc_exec_queue_lr_cleanup(struct work_struct *w)
971 {
972 	struct xe_guc_exec_queue *ge =
973 		container_of(w, struct xe_guc_exec_queue, lr_tdr);
974 	struct xe_exec_queue *q = ge->q;
975 	struct xe_guc *guc = exec_queue_to_guc(q);
976 	struct xe_gpu_scheduler *sched = &ge->sched;
977 	bool wedged = false;
978 
979 	xe_gt_assert(guc_to_gt(guc), xe_exec_queue_is_lr(q));
980 	trace_xe_exec_queue_lr_cleanup(q);
981 
982 	if (!exec_queue_killed(q))
983 		wedged = guc_submit_hint_wedged(exec_queue_to_guc(q));
984 
985 	/* Kill the run_job / process_msg entry points */
986 	xe_sched_submission_stop(sched);
987 
988 	/*
989 	 * Engine state now mostly stable, disable scheduling / deregister if
990 	 * needed. This cleanup routine might be called multiple times, where
991 	 * the actual async engine deregister drops the final engine ref.
992 	 * Calling disable_scheduling_deregister will mark the engine as
993 	 * destroyed and fire off the CT requests to disable scheduling /
994 	 * deregister, which we only want to do once. We also don't want to mark
995 	 * the engine as pending_disable again as this may race with the
996 	 * xe_guc_deregister_done_handler() which treats it as an unexpected
997 	 * state.
998 	 */
999 	if (!wedged && exec_queue_registered(q) && !exec_queue_destroyed(q)) {
1000 		struct xe_guc *guc = exec_queue_to_guc(q);
1001 		int ret;
1002 
1003 		set_exec_queue_banned(q);
1004 		disable_scheduling_deregister(guc, q);
1005 
1006 		/*
1007 		 * Must wait for scheduling to be disabled before signalling
1008 		 * any fences, if GT broken the GT reset code should signal us.
1009 		 */
1010 		ret = wait_event_timeout(guc->ct.wq,
1011 					 !exec_queue_pending_disable(q) ||
1012 					 xe_guc_read_stopped(guc), HZ * 5);
1013 		if (!ret) {
1014 			xe_gt_warn(q->gt, "Schedule disable failed to respond, guc_id=%d\n",
1015 				   q->guc->id);
1016 			xe_devcoredump(q, NULL, "Schedule disable failed to respond, guc_id=%d\n",
1017 				       q->guc->id);
1018 			xe_sched_submission_start(sched);
1019 			xe_gt_reset_async(q->gt);
1020 			return;
1021 		}
1022 	}
1023 
1024 	if (!exec_queue_killed(q) && !xe_lrc_ring_is_idle(q->lrc[0]))
1025 		xe_devcoredump(q, NULL, "LR job cleanup, guc_id=%d", q->guc->id);
1026 
1027 	xe_sched_submission_start(sched);
1028 }
1029 
1030 #define ADJUST_FIVE_PERCENT(__t)	mul_u64_u32_div(__t, 105, 100)
1031 
1032 static bool check_timeout(struct xe_exec_queue *q, struct xe_sched_job *job)
1033 {
1034 	struct xe_gt *gt = guc_to_gt(exec_queue_to_guc(q));
1035 	u32 ctx_timestamp, ctx_job_timestamp;
1036 	u32 timeout_ms = q->sched_props.job_timeout_ms;
1037 	u32 diff;
1038 	u64 running_time_ms;
1039 
1040 	if (!xe_sched_job_started(job)) {
1041 		xe_gt_warn(gt, "Check job timeout: seqno=%u, lrc_seqno=%u, guc_id=%d, not started",
1042 			   xe_sched_job_seqno(job), xe_sched_job_lrc_seqno(job),
1043 			   q->guc->id);
1044 
1045 		return xe_sched_invalidate_job(job, 2);
1046 	}
1047 
1048 	ctx_timestamp = lower_32_bits(xe_lrc_ctx_timestamp(q->lrc[0]));
1049 	ctx_job_timestamp = xe_lrc_ctx_job_timestamp(q->lrc[0]);
1050 
1051 	/*
1052 	 * Counter wraps at ~223s at the usual 19.2MHz, be paranoid catch
1053 	 * possible overflows with a high timeout.
1054 	 */
1055 	xe_gt_assert(gt, timeout_ms < 100 * MSEC_PER_SEC);
1056 
1057 	diff = ctx_timestamp - ctx_job_timestamp;
1058 
1059 	/*
1060 	 * Ensure timeout is within 5% to account for an GuC scheduling latency
1061 	 */
1062 	running_time_ms =
1063 		ADJUST_FIVE_PERCENT(xe_gt_clock_interval_to_ms(gt, diff));
1064 
1065 	xe_gt_dbg(gt,
1066 		  "Check job timeout: seqno=%u, lrc_seqno=%u, guc_id=%d, running_time_ms=%llu, timeout_ms=%u, diff=0x%08x",
1067 		  xe_sched_job_seqno(job), xe_sched_job_lrc_seqno(job),
1068 		  q->guc->id, running_time_ms, timeout_ms, diff);
1069 
1070 	return running_time_ms >= timeout_ms;
1071 }
1072 
1073 static void enable_scheduling(struct xe_exec_queue *q)
1074 {
1075 	MAKE_SCHED_CONTEXT_ACTION(q, ENABLE);
1076 	struct xe_guc *guc = exec_queue_to_guc(q);
1077 	int ret;
1078 
1079 	xe_gt_assert(guc_to_gt(guc), !exec_queue_destroyed(q));
1080 	xe_gt_assert(guc_to_gt(guc), exec_queue_registered(q));
1081 	xe_gt_assert(guc_to_gt(guc), !exec_queue_pending_disable(q));
1082 	xe_gt_assert(guc_to_gt(guc), !exec_queue_pending_enable(q));
1083 
1084 	set_exec_queue_pending_enable(q);
1085 	set_exec_queue_enabled(q);
1086 	trace_xe_exec_queue_scheduling_enable(q);
1087 
1088 	xe_guc_ct_send(&guc->ct, action, ARRAY_SIZE(action),
1089 		       G2H_LEN_DW_SCHED_CONTEXT_MODE_SET, 1);
1090 
1091 	ret = wait_event_timeout(guc->ct.wq,
1092 				 !exec_queue_pending_enable(q) ||
1093 				 xe_guc_read_stopped(guc), HZ * 5);
1094 	if (!ret || xe_guc_read_stopped(guc)) {
1095 		xe_gt_warn(guc_to_gt(guc), "Schedule enable failed to respond");
1096 		set_exec_queue_banned(q);
1097 		xe_gt_reset_async(q->gt);
1098 		xe_sched_tdr_queue_imm(&q->guc->sched);
1099 	}
1100 }
1101 
1102 static void disable_scheduling(struct xe_exec_queue *q, bool immediate)
1103 {
1104 	MAKE_SCHED_CONTEXT_ACTION(q, DISABLE);
1105 	struct xe_guc *guc = exec_queue_to_guc(q);
1106 
1107 	xe_gt_assert(guc_to_gt(guc), !exec_queue_destroyed(q));
1108 	xe_gt_assert(guc_to_gt(guc), exec_queue_registered(q));
1109 	xe_gt_assert(guc_to_gt(guc), !exec_queue_pending_disable(q));
1110 
1111 	if (immediate)
1112 		set_min_preemption_timeout(guc, q);
1113 	clear_exec_queue_enabled(q);
1114 	set_exec_queue_pending_disable(q);
1115 	trace_xe_exec_queue_scheduling_disable(q);
1116 
1117 	xe_guc_ct_send(&guc->ct, action, ARRAY_SIZE(action),
1118 		       G2H_LEN_DW_SCHED_CONTEXT_MODE_SET, 1);
1119 }
1120 
1121 static void __deregister_exec_queue(struct xe_guc *guc, struct xe_exec_queue *q)
1122 {
1123 	u32 action[] = {
1124 		XE_GUC_ACTION_DEREGISTER_CONTEXT,
1125 		q->guc->id,
1126 	};
1127 
1128 	xe_gt_assert(guc_to_gt(guc), !exec_queue_destroyed(q));
1129 	xe_gt_assert(guc_to_gt(guc), exec_queue_registered(q));
1130 	xe_gt_assert(guc_to_gt(guc), !exec_queue_pending_enable(q));
1131 	xe_gt_assert(guc_to_gt(guc), !exec_queue_pending_disable(q));
1132 
1133 	set_exec_queue_destroyed(q);
1134 	trace_xe_exec_queue_deregister(q);
1135 
1136 	xe_guc_ct_send(&guc->ct, action, ARRAY_SIZE(action),
1137 		       G2H_LEN_DW_DEREGISTER_CONTEXT, 1);
1138 }
1139 
1140 static enum drm_gpu_sched_stat
1141 guc_exec_queue_timedout_job(struct drm_sched_job *drm_job)
1142 {
1143 	struct xe_sched_job *job = to_xe_sched_job(drm_job);
1144 	struct xe_sched_job *tmp_job;
1145 	struct xe_exec_queue *q = job->q;
1146 	struct xe_gpu_scheduler *sched = &q->guc->sched;
1147 	struct xe_guc *guc = exec_queue_to_guc(q);
1148 	const char *process_name = "no process";
1149 	struct xe_device *xe = guc_to_xe(guc);
1150 	unsigned int fw_ref;
1151 	int err = -ETIME;
1152 	pid_t pid = -1;
1153 	int i = 0;
1154 	bool wedged = false, skip_timeout_check;
1155 
1156 	/*
1157 	 * TDR has fired before free job worker. Common if exec queue
1158 	 * immediately closed after last fence signaled. Add back to pending
1159 	 * list so job can be freed and kick scheduler ensuring free job is not
1160 	 * lost.
1161 	 */
1162 	if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &job->fence->flags))
1163 		return DRM_GPU_SCHED_STAT_NO_HANG;
1164 
1165 	/* Kill the run_job entry point */
1166 	xe_sched_submission_stop(sched);
1167 
1168 	/* Must check all state after stopping scheduler */
1169 	skip_timeout_check = exec_queue_reset(q) ||
1170 		exec_queue_killed_or_banned_or_wedged(q) ||
1171 		exec_queue_destroyed(q);
1172 
1173 	/*
1174 	 * If devcoredump not captured and GuC capture for the job is not ready
1175 	 * do manual capture first and decide later if we need to use it
1176 	 */
1177 	if (!exec_queue_killed(q) && !xe->devcoredump.captured &&
1178 	    !xe_guc_capture_get_matching_and_lock(q)) {
1179 		/* take force wake before engine register manual capture */
1180 		fw_ref = xe_force_wake_get(gt_to_fw(q->gt), XE_FORCEWAKE_ALL);
1181 		if (!xe_force_wake_ref_has_domain(fw_ref, XE_FORCEWAKE_ALL))
1182 			xe_gt_info(q->gt, "failed to get forcewake for coredump capture\n");
1183 
1184 		xe_engine_snapshot_capture_for_queue(q);
1185 
1186 		xe_force_wake_put(gt_to_fw(q->gt), fw_ref);
1187 	}
1188 
1189 	/*
1190 	 * XXX: Sampling timeout doesn't work in wedged mode as we have to
1191 	 * modify scheduling state to read timestamp. We could read the
1192 	 * timestamp from a register to accumulate current running time but this
1193 	 * doesn't work for SRIOV. For now assuming timeouts in wedged mode are
1194 	 * genuine timeouts.
1195 	 */
1196 	if (!exec_queue_killed(q))
1197 		wedged = guc_submit_hint_wedged(exec_queue_to_guc(q));
1198 
1199 	/* Engine state now stable, disable scheduling to check timestamp */
1200 	if (!wedged && exec_queue_registered(q)) {
1201 		int ret;
1202 
1203 		if (exec_queue_reset(q))
1204 			err = -EIO;
1205 
1206 		if (!exec_queue_destroyed(q)) {
1207 			/*
1208 			 * Wait for any pending G2H to flush out before
1209 			 * modifying state
1210 			 */
1211 			ret = wait_event_timeout(guc->ct.wq,
1212 						 (!exec_queue_pending_enable(q) &&
1213 						  !exec_queue_pending_disable(q)) ||
1214 						 xe_guc_read_stopped(guc), HZ * 5);
1215 			if (!ret || xe_guc_read_stopped(guc))
1216 				goto trigger_reset;
1217 
1218 			/*
1219 			 * Flag communicates to G2H handler that schedule
1220 			 * disable originated from a timeout check. The G2H then
1221 			 * avoid triggering cleanup or deregistering the exec
1222 			 * queue.
1223 			 */
1224 			set_exec_queue_check_timeout(q);
1225 			disable_scheduling(q, skip_timeout_check);
1226 		}
1227 
1228 		/*
1229 		 * Must wait for scheduling to be disabled before signalling
1230 		 * any fences, if GT broken the GT reset code should signal us.
1231 		 *
1232 		 * FIXME: Tests can generate a ton of 0x6000 (IOMMU CAT fault
1233 		 * error) messages which can cause the schedule disable to get
1234 		 * lost. If this occurs, trigger a GT reset to recover.
1235 		 */
1236 		smp_rmb();
1237 		ret = wait_event_timeout(guc->ct.wq,
1238 					 !exec_queue_pending_disable(q) ||
1239 					 xe_guc_read_stopped(guc), HZ * 5);
1240 		if (!ret || xe_guc_read_stopped(guc)) {
1241 trigger_reset:
1242 			if (!ret)
1243 				xe_gt_warn(guc_to_gt(guc),
1244 					   "Schedule disable failed to respond, guc_id=%d",
1245 					   q->guc->id);
1246 			xe_devcoredump(q, job,
1247 				       "Schedule disable failed to respond, guc_id=%d, ret=%d, guc_read=%d",
1248 				       q->guc->id, ret, xe_guc_read_stopped(guc));
1249 			set_exec_queue_extra_ref(q);
1250 			xe_exec_queue_get(q);	/* GT reset owns this */
1251 			set_exec_queue_banned(q);
1252 			xe_gt_reset_async(q->gt);
1253 			xe_sched_tdr_queue_imm(sched);
1254 			goto rearm;
1255 		}
1256 	}
1257 
1258 	/*
1259 	 * Check if job is actually timed out, if so restart job execution and TDR
1260 	 */
1261 	if (!wedged && !skip_timeout_check && !check_timeout(q, job) &&
1262 	    !exec_queue_reset(q) && exec_queue_registered(q)) {
1263 		clear_exec_queue_check_timeout(q);
1264 		goto sched_enable;
1265 	}
1266 
1267 	if (q->vm && q->vm->xef) {
1268 		process_name = q->vm->xef->process_name;
1269 		pid = q->vm->xef->pid;
1270 	}
1271 
1272 	if (!exec_queue_killed(q))
1273 		xe_gt_notice(guc_to_gt(guc),
1274 			     "Timedout job: seqno=%u, lrc_seqno=%u, guc_id=%d, flags=0x%lx in %s [%d]",
1275 			     xe_sched_job_seqno(job), xe_sched_job_lrc_seqno(job),
1276 			     q->guc->id, q->flags, process_name, pid);
1277 
1278 	trace_xe_sched_job_timedout(job);
1279 
1280 	if (!exec_queue_killed(q))
1281 		xe_devcoredump(q, job,
1282 			       "Timedout job - seqno=%u, lrc_seqno=%u, guc_id=%d, flags=0x%lx",
1283 			       xe_sched_job_seqno(job), xe_sched_job_lrc_seqno(job),
1284 			       q->guc->id, q->flags);
1285 
1286 	/*
1287 	 * Kernel jobs should never fail, nor should VM jobs if they do
1288 	 * somethings has gone wrong and the GT needs a reset
1289 	 */
1290 	xe_gt_WARN(q->gt, q->flags & EXEC_QUEUE_FLAG_KERNEL,
1291 		   "Kernel-submitted job timed out\n");
1292 	xe_gt_WARN(q->gt, q->flags & EXEC_QUEUE_FLAG_VM && !exec_queue_killed(q),
1293 		   "VM job timed out on non-killed execqueue\n");
1294 	if (!wedged && (q->flags & EXEC_QUEUE_FLAG_KERNEL ||
1295 			(q->flags & EXEC_QUEUE_FLAG_VM && !exec_queue_killed(q)))) {
1296 		if (!xe_sched_invalidate_job(job, 2)) {
1297 			clear_exec_queue_check_timeout(q);
1298 			xe_gt_reset_async(q->gt);
1299 			goto rearm;
1300 		}
1301 	}
1302 
1303 	/* Finish cleaning up exec queue via deregister */
1304 	set_exec_queue_banned(q);
1305 	if (!wedged && exec_queue_registered(q) && !exec_queue_destroyed(q)) {
1306 		set_exec_queue_extra_ref(q);
1307 		xe_exec_queue_get(q);
1308 		__deregister_exec_queue(guc, q);
1309 	}
1310 
1311 	/* Stop fence signaling */
1312 	xe_hw_fence_irq_stop(q->fence_irq);
1313 
1314 	/*
1315 	 * Fence state now stable, stop / start scheduler which cleans up any
1316 	 * fences that are complete
1317 	 */
1318 	xe_sched_add_pending_job(sched, job);
1319 	xe_sched_submission_start(sched);
1320 
1321 	xe_guc_exec_queue_trigger_cleanup(q);
1322 
1323 	/* Mark all outstanding jobs as bad, thus completing them */
1324 	spin_lock(&sched->base.job_list_lock);
1325 	list_for_each_entry(tmp_job, &sched->base.pending_list, drm.list)
1326 		xe_sched_job_set_error(tmp_job, !i++ ? err : -ECANCELED);
1327 	spin_unlock(&sched->base.job_list_lock);
1328 
1329 	/* Start fence signaling */
1330 	xe_hw_fence_irq_start(q->fence_irq);
1331 
1332 	return DRM_GPU_SCHED_STAT_RESET;
1333 
1334 sched_enable:
1335 	enable_scheduling(q);
1336 rearm:
1337 	/*
1338 	 * XXX: Ideally want to adjust timeout based on current execution time
1339 	 * but there is not currently an easy way to do in DRM scheduler. With
1340 	 * some thought, do this in a follow up.
1341 	 */
1342 	xe_sched_submission_start(sched);
1343 	return DRM_GPU_SCHED_STAT_NO_HANG;
1344 }
1345 
1346 static void guc_exec_queue_fini(struct xe_exec_queue *q)
1347 {
1348 	struct xe_guc_exec_queue *ge = q->guc;
1349 	struct xe_guc *guc = exec_queue_to_guc(q);
1350 
1351 	release_guc_id(guc, q);
1352 	xe_sched_entity_fini(&ge->entity);
1353 	xe_sched_fini(&ge->sched);
1354 
1355 	/*
1356 	 * RCU free due sched being exported via DRM scheduler fences
1357 	 * (timeline name).
1358 	 */
1359 	kfree_rcu(ge, rcu);
1360 }
1361 
1362 static void __guc_exec_queue_destroy_async(struct work_struct *w)
1363 {
1364 	struct xe_guc_exec_queue *ge =
1365 		container_of(w, struct xe_guc_exec_queue, destroy_async);
1366 	struct xe_exec_queue *q = ge->q;
1367 	struct xe_guc *guc = exec_queue_to_guc(q);
1368 
1369 	xe_pm_runtime_get(guc_to_xe(guc));
1370 	trace_xe_exec_queue_destroy(q);
1371 
1372 	if (xe_exec_queue_is_lr(q))
1373 		cancel_work_sync(&ge->lr_tdr);
1374 	/* Confirm no work left behind accessing device structures */
1375 	cancel_delayed_work_sync(&ge->sched.base.work_tdr);
1376 
1377 	xe_exec_queue_fini(q);
1378 
1379 	xe_pm_runtime_put(guc_to_xe(guc));
1380 }
1381 
1382 static void guc_exec_queue_destroy_async(struct xe_exec_queue *q)
1383 {
1384 	struct xe_guc *guc = exec_queue_to_guc(q);
1385 	struct xe_device *xe = guc_to_xe(guc);
1386 
1387 	INIT_WORK(&q->guc->destroy_async, __guc_exec_queue_destroy_async);
1388 
1389 	/* We must block on kernel engines so slabs are empty on driver unload */
1390 	if (q->flags & EXEC_QUEUE_FLAG_PERMANENT || exec_queue_wedged(q))
1391 		__guc_exec_queue_destroy_async(&q->guc->destroy_async);
1392 	else
1393 		queue_work(xe->destroy_wq, &q->guc->destroy_async);
1394 }
1395 
1396 static void __guc_exec_queue_destroy(struct xe_guc *guc, struct xe_exec_queue *q)
1397 {
1398 	/*
1399 	 * Might be done from within the GPU scheduler, need to do async as we
1400 	 * fini the scheduler when the engine is fini'd, the scheduler can't
1401 	 * complete fini within itself (circular dependency). Async resolves
1402 	 * this we and don't really care when everything is fini'd, just that it
1403 	 * is.
1404 	 */
1405 	guc_exec_queue_destroy_async(q);
1406 }
1407 
1408 static void __guc_exec_queue_process_msg_cleanup(struct xe_sched_msg *msg)
1409 {
1410 	struct xe_exec_queue *q = msg->private_data;
1411 	struct xe_guc *guc = exec_queue_to_guc(q);
1412 
1413 	xe_gt_assert(guc_to_gt(guc), !(q->flags & EXEC_QUEUE_FLAG_PERMANENT));
1414 	trace_xe_exec_queue_cleanup_entity(q);
1415 
1416 	if (exec_queue_registered(q))
1417 		disable_scheduling_deregister(guc, q);
1418 	else
1419 		__guc_exec_queue_destroy(guc, q);
1420 }
1421 
1422 static bool guc_exec_queue_allowed_to_change_state(struct xe_exec_queue *q)
1423 {
1424 	return !exec_queue_killed_or_banned_or_wedged(q) && exec_queue_registered(q);
1425 }
1426 
1427 static void __guc_exec_queue_process_msg_set_sched_props(struct xe_sched_msg *msg)
1428 {
1429 	struct xe_exec_queue *q = msg->private_data;
1430 	struct xe_guc *guc = exec_queue_to_guc(q);
1431 
1432 	if (guc_exec_queue_allowed_to_change_state(q))
1433 		init_policies(guc, q);
1434 	kfree(msg);
1435 }
1436 
1437 static void __suspend_fence_signal(struct xe_exec_queue *q)
1438 {
1439 	if (!q->guc->suspend_pending)
1440 		return;
1441 
1442 	WRITE_ONCE(q->guc->suspend_pending, false);
1443 	wake_up(&q->guc->suspend_wait);
1444 }
1445 
1446 static void suspend_fence_signal(struct xe_exec_queue *q)
1447 {
1448 	struct xe_guc *guc = exec_queue_to_guc(q);
1449 
1450 	xe_gt_assert(guc_to_gt(guc), exec_queue_suspended(q) || exec_queue_killed(q) ||
1451 		     xe_guc_read_stopped(guc));
1452 	xe_gt_assert(guc_to_gt(guc), q->guc->suspend_pending);
1453 
1454 	__suspend_fence_signal(q);
1455 }
1456 
1457 static void __guc_exec_queue_process_msg_suspend(struct xe_sched_msg *msg)
1458 {
1459 	struct xe_exec_queue *q = msg->private_data;
1460 	struct xe_guc *guc = exec_queue_to_guc(q);
1461 
1462 	if (guc_exec_queue_allowed_to_change_state(q) && !exec_queue_suspended(q) &&
1463 	    exec_queue_enabled(q)) {
1464 		wait_event(guc->ct.wq, (q->guc->resume_time != RESUME_PENDING ||
1465 			   xe_guc_read_stopped(guc)) && !exec_queue_pending_disable(q));
1466 
1467 		if (!xe_guc_read_stopped(guc)) {
1468 			s64 since_resume_ms =
1469 				ktime_ms_delta(ktime_get(),
1470 					       q->guc->resume_time);
1471 			s64 wait_ms = q->vm->preempt.min_run_period_ms -
1472 				since_resume_ms;
1473 
1474 			if (wait_ms > 0 && q->guc->resume_time)
1475 				msleep(wait_ms);
1476 
1477 			set_exec_queue_suspended(q);
1478 			disable_scheduling(q, false);
1479 		}
1480 	} else if (q->guc->suspend_pending) {
1481 		set_exec_queue_suspended(q);
1482 		suspend_fence_signal(q);
1483 	}
1484 }
1485 
1486 static void __guc_exec_queue_process_msg_resume(struct xe_sched_msg *msg)
1487 {
1488 	struct xe_exec_queue *q = msg->private_data;
1489 
1490 	if (guc_exec_queue_allowed_to_change_state(q)) {
1491 		clear_exec_queue_suspended(q);
1492 		if (!exec_queue_enabled(q)) {
1493 			q->guc->resume_time = RESUME_PENDING;
1494 			enable_scheduling(q);
1495 		}
1496 	} else {
1497 		clear_exec_queue_suspended(q);
1498 	}
1499 }
1500 
1501 #define CLEANUP		1	/* Non-zero values to catch uninitialized msg */
1502 #define SET_SCHED_PROPS	2
1503 #define SUSPEND		3
1504 #define RESUME		4
1505 #define OPCODE_MASK	0xf
1506 #define MSG_LOCKED	BIT(8)
1507 
1508 static void guc_exec_queue_process_msg(struct xe_sched_msg *msg)
1509 {
1510 	struct xe_device *xe = guc_to_xe(exec_queue_to_guc(msg->private_data));
1511 
1512 	trace_xe_sched_msg_recv(msg);
1513 
1514 	switch (msg->opcode) {
1515 	case CLEANUP:
1516 		__guc_exec_queue_process_msg_cleanup(msg);
1517 		break;
1518 	case SET_SCHED_PROPS:
1519 		__guc_exec_queue_process_msg_set_sched_props(msg);
1520 		break;
1521 	case SUSPEND:
1522 		__guc_exec_queue_process_msg_suspend(msg);
1523 		break;
1524 	case RESUME:
1525 		__guc_exec_queue_process_msg_resume(msg);
1526 		break;
1527 	default:
1528 		XE_WARN_ON("Unknown message type");
1529 	}
1530 
1531 	xe_pm_runtime_put(xe);
1532 }
1533 
1534 static const struct drm_sched_backend_ops drm_sched_ops = {
1535 	.run_job = guc_exec_queue_run_job,
1536 	.free_job = guc_exec_queue_free_job,
1537 	.timedout_job = guc_exec_queue_timedout_job,
1538 };
1539 
1540 static const struct xe_sched_backend_ops xe_sched_ops = {
1541 	.process_msg = guc_exec_queue_process_msg,
1542 };
1543 
1544 static int guc_exec_queue_init(struct xe_exec_queue *q)
1545 {
1546 	struct xe_gpu_scheduler *sched;
1547 	struct xe_guc *guc = exec_queue_to_guc(q);
1548 	struct xe_guc_exec_queue *ge;
1549 	long timeout;
1550 	int err, i;
1551 
1552 	xe_gt_assert(guc_to_gt(guc), xe_device_uc_enabled(guc_to_xe(guc)));
1553 
1554 	ge = kzalloc(sizeof(*ge), GFP_KERNEL);
1555 	if (!ge)
1556 		return -ENOMEM;
1557 
1558 	q->guc = ge;
1559 	ge->q = q;
1560 	init_rcu_head(&ge->rcu);
1561 	init_waitqueue_head(&ge->suspend_wait);
1562 
1563 	for (i = 0; i < MAX_STATIC_MSG_TYPE; ++i)
1564 		INIT_LIST_HEAD(&ge->static_msgs[i].link);
1565 
1566 	timeout = (q->vm && xe_vm_in_lr_mode(q->vm)) ? MAX_SCHEDULE_TIMEOUT :
1567 		  msecs_to_jiffies(q->sched_props.job_timeout_ms);
1568 	err = xe_sched_init(&ge->sched, &drm_sched_ops, &xe_sched_ops,
1569 			    NULL, q->lrc[0]->ring.size / MAX_JOB_SIZE_BYTES, 64,
1570 			    timeout, guc_to_gt(guc)->ordered_wq, NULL,
1571 			    q->name, gt_to_xe(q->gt)->drm.dev);
1572 	if (err)
1573 		goto err_free;
1574 
1575 	sched = &ge->sched;
1576 	err = xe_sched_entity_init(&ge->entity, sched);
1577 	if (err)
1578 		goto err_sched;
1579 
1580 	if (xe_exec_queue_is_lr(q))
1581 		INIT_WORK(&q->guc->lr_tdr, xe_guc_exec_queue_lr_cleanup);
1582 
1583 	mutex_lock(&guc->submission_state.lock);
1584 
1585 	err = alloc_guc_id(guc, q);
1586 	if (err)
1587 		goto err_entity;
1588 
1589 	q->entity = &ge->entity;
1590 
1591 	if (xe_guc_read_stopped(guc))
1592 		xe_sched_stop(sched);
1593 
1594 	mutex_unlock(&guc->submission_state.lock);
1595 
1596 	xe_exec_queue_assign_name(q, q->guc->id);
1597 
1598 	trace_xe_exec_queue_create(q);
1599 
1600 	return 0;
1601 
1602 err_entity:
1603 	mutex_unlock(&guc->submission_state.lock);
1604 	xe_sched_entity_fini(&ge->entity);
1605 err_sched:
1606 	xe_sched_fini(&ge->sched);
1607 err_free:
1608 	kfree(ge);
1609 
1610 	return err;
1611 }
1612 
1613 static void guc_exec_queue_kill(struct xe_exec_queue *q)
1614 {
1615 	trace_xe_exec_queue_kill(q);
1616 	set_exec_queue_killed(q);
1617 	__suspend_fence_signal(q);
1618 	xe_guc_exec_queue_trigger_cleanup(q);
1619 }
1620 
1621 static void guc_exec_queue_add_msg(struct xe_exec_queue *q, struct xe_sched_msg *msg,
1622 				   u32 opcode)
1623 {
1624 	xe_pm_runtime_get_noresume(guc_to_xe(exec_queue_to_guc(q)));
1625 
1626 	INIT_LIST_HEAD(&msg->link);
1627 	msg->opcode = opcode & OPCODE_MASK;
1628 	msg->private_data = q;
1629 
1630 	trace_xe_sched_msg_add(msg);
1631 	if (opcode & MSG_LOCKED)
1632 		xe_sched_add_msg_locked(&q->guc->sched, msg);
1633 	else
1634 		xe_sched_add_msg(&q->guc->sched, msg);
1635 }
1636 
1637 static bool guc_exec_queue_try_add_msg(struct xe_exec_queue *q,
1638 				       struct xe_sched_msg *msg,
1639 				       u32 opcode)
1640 {
1641 	if (!list_empty(&msg->link))
1642 		return false;
1643 
1644 	guc_exec_queue_add_msg(q, msg, opcode | MSG_LOCKED);
1645 
1646 	return true;
1647 }
1648 
1649 #define STATIC_MSG_CLEANUP	0
1650 #define STATIC_MSG_SUSPEND	1
1651 #define STATIC_MSG_RESUME	2
1652 static void guc_exec_queue_destroy(struct xe_exec_queue *q)
1653 {
1654 	struct xe_sched_msg *msg = q->guc->static_msgs + STATIC_MSG_CLEANUP;
1655 
1656 	if (!(q->flags & EXEC_QUEUE_FLAG_PERMANENT) && !exec_queue_wedged(q))
1657 		guc_exec_queue_add_msg(q, msg, CLEANUP);
1658 	else
1659 		__guc_exec_queue_destroy(exec_queue_to_guc(q), q);
1660 }
1661 
1662 static int guc_exec_queue_set_priority(struct xe_exec_queue *q,
1663 				       enum xe_exec_queue_priority priority)
1664 {
1665 	struct xe_sched_msg *msg;
1666 
1667 	if (q->sched_props.priority == priority ||
1668 	    exec_queue_killed_or_banned_or_wedged(q))
1669 		return 0;
1670 
1671 	msg = kmalloc(sizeof(*msg), GFP_KERNEL);
1672 	if (!msg)
1673 		return -ENOMEM;
1674 
1675 	q->sched_props.priority = priority;
1676 	guc_exec_queue_add_msg(q, msg, SET_SCHED_PROPS);
1677 
1678 	return 0;
1679 }
1680 
1681 static int guc_exec_queue_set_timeslice(struct xe_exec_queue *q, u32 timeslice_us)
1682 {
1683 	struct xe_sched_msg *msg;
1684 
1685 	if (q->sched_props.timeslice_us == timeslice_us ||
1686 	    exec_queue_killed_or_banned_or_wedged(q))
1687 		return 0;
1688 
1689 	msg = kmalloc(sizeof(*msg), GFP_KERNEL);
1690 	if (!msg)
1691 		return -ENOMEM;
1692 
1693 	q->sched_props.timeslice_us = timeslice_us;
1694 	guc_exec_queue_add_msg(q, msg, SET_SCHED_PROPS);
1695 
1696 	return 0;
1697 }
1698 
1699 static int guc_exec_queue_set_preempt_timeout(struct xe_exec_queue *q,
1700 					      u32 preempt_timeout_us)
1701 {
1702 	struct xe_sched_msg *msg;
1703 
1704 	if (q->sched_props.preempt_timeout_us == preempt_timeout_us ||
1705 	    exec_queue_killed_or_banned_or_wedged(q))
1706 		return 0;
1707 
1708 	msg = kmalloc(sizeof(*msg), GFP_KERNEL);
1709 	if (!msg)
1710 		return -ENOMEM;
1711 
1712 	q->sched_props.preempt_timeout_us = preempt_timeout_us;
1713 	guc_exec_queue_add_msg(q, msg, SET_SCHED_PROPS);
1714 
1715 	return 0;
1716 }
1717 
1718 static int guc_exec_queue_suspend(struct xe_exec_queue *q)
1719 {
1720 	struct xe_gpu_scheduler *sched = &q->guc->sched;
1721 	struct xe_sched_msg *msg = q->guc->static_msgs + STATIC_MSG_SUSPEND;
1722 
1723 	if (exec_queue_killed_or_banned_or_wedged(q))
1724 		return -EINVAL;
1725 
1726 	xe_sched_msg_lock(sched);
1727 	if (guc_exec_queue_try_add_msg(q, msg, SUSPEND))
1728 		q->guc->suspend_pending = true;
1729 	xe_sched_msg_unlock(sched);
1730 
1731 	return 0;
1732 }
1733 
1734 static int guc_exec_queue_suspend_wait(struct xe_exec_queue *q)
1735 {
1736 	struct xe_guc *guc = exec_queue_to_guc(q);
1737 	int ret;
1738 
1739 	/*
1740 	 * Likely don't need to check exec_queue_killed() as we clear
1741 	 * suspend_pending upon kill but to be paranoid but races in which
1742 	 * suspend_pending is set after kill also check kill here.
1743 	 */
1744 	ret = wait_event_interruptible_timeout(q->guc->suspend_wait,
1745 					       !READ_ONCE(q->guc->suspend_pending) ||
1746 					       exec_queue_killed(q) ||
1747 					       xe_guc_read_stopped(guc),
1748 					       HZ * 5);
1749 
1750 	if (!ret) {
1751 		xe_gt_warn(guc_to_gt(guc),
1752 			   "Suspend fence, guc_id=%d, failed to respond",
1753 			   q->guc->id);
1754 		/* XXX: Trigger GT reset? */
1755 		return -ETIME;
1756 	}
1757 
1758 	return ret < 0 ? ret : 0;
1759 }
1760 
1761 static void guc_exec_queue_resume(struct xe_exec_queue *q)
1762 {
1763 	struct xe_gpu_scheduler *sched = &q->guc->sched;
1764 	struct xe_sched_msg *msg = q->guc->static_msgs + STATIC_MSG_RESUME;
1765 	struct xe_guc *guc = exec_queue_to_guc(q);
1766 
1767 	xe_gt_assert(guc_to_gt(guc), !q->guc->suspend_pending);
1768 
1769 	xe_sched_msg_lock(sched);
1770 	guc_exec_queue_try_add_msg(q, msg, RESUME);
1771 	xe_sched_msg_unlock(sched);
1772 }
1773 
1774 static bool guc_exec_queue_reset_status(struct xe_exec_queue *q)
1775 {
1776 	return exec_queue_reset(q) || exec_queue_killed_or_banned_or_wedged(q);
1777 }
1778 
1779 /*
1780  * All of these functions are an abstraction layer which other parts of XE can
1781  * use to trap into the GuC backend. All of these functions, aside from init,
1782  * really shouldn't do much other than trap into the DRM scheduler which
1783  * synchronizes these operations.
1784  */
1785 static const struct xe_exec_queue_ops guc_exec_queue_ops = {
1786 	.init = guc_exec_queue_init,
1787 	.kill = guc_exec_queue_kill,
1788 	.fini = guc_exec_queue_fini,
1789 	.destroy = guc_exec_queue_destroy,
1790 	.set_priority = guc_exec_queue_set_priority,
1791 	.set_timeslice = guc_exec_queue_set_timeslice,
1792 	.set_preempt_timeout = guc_exec_queue_set_preempt_timeout,
1793 	.suspend = guc_exec_queue_suspend,
1794 	.suspend_wait = guc_exec_queue_suspend_wait,
1795 	.resume = guc_exec_queue_resume,
1796 	.reset_status = guc_exec_queue_reset_status,
1797 };
1798 
1799 static void guc_exec_queue_stop(struct xe_guc *guc, struct xe_exec_queue *q)
1800 {
1801 	struct xe_gpu_scheduler *sched = &q->guc->sched;
1802 
1803 	/* Stop scheduling + flush any DRM scheduler operations */
1804 	xe_sched_submission_stop(sched);
1805 
1806 	/* Clean up lost G2H + reset engine state */
1807 	if (exec_queue_registered(q)) {
1808 		if (exec_queue_extra_ref(q) || xe_exec_queue_is_lr(q))
1809 			xe_exec_queue_put(q);
1810 		else if (exec_queue_destroyed(q))
1811 			__guc_exec_queue_destroy(guc, q);
1812 	}
1813 	if (q->guc->suspend_pending) {
1814 		set_exec_queue_suspended(q);
1815 		suspend_fence_signal(q);
1816 	}
1817 	atomic_and(EXEC_QUEUE_STATE_WEDGED | EXEC_QUEUE_STATE_BANNED |
1818 		   EXEC_QUEUE_STATE_KILLED | EXEC_QUEUE_STATE_DESTROYED |
1819 		   EXEC_QUEUE_STATE_SUSPENDED,
1820 		   &q->guc->state);
1821 	q->guc->resume_time = 0;
1822 	trace_xe_exec_queue_stop(q);
1823 
1824 	/*
1825 	 * Ban any engine (aside from kernel and engines used for VM ops) with a
1826 	 * started but not complete job or if a job has gone through a GT reset
1827 	 * more than twice.
1828 	 */
1829 	if (!(q->flags & (EXEC_QUEUE_FLAG_KERNEL | EXEC_QUEUE_FLAG_VM))) {
1830 		struct xe_sched_job *job = xe_sched_first_pending_job(sched);
1831 		bool ban = false;
1832 
1833 		if (job) {
1834 			if ((xe_sched_job_started(job) &&
1835 			    !xe_sched_job_completed(job)) ||
1836 			    xe_sched_invalidate_job(job, 2)) {
1837 				trace_xe_sched_job_ban(job);
1838 				ban = true;
1839 			}
1840 		} else if (xe_exec_queue_is_lr(q) &&
1841 			   !xe_lrc_ring_is_idle(q->lrc[0])) {
1842 			ban = true;
1843 		}
1844 
1845 		if (ban) {
1846 			set_exec_queue_banned(q);
1847 			xe_guc_exec_queue_trigger_cleanup(q);
1848 		}
1849 	}
1850 }
1851 
1852 int xe_guc_submit_reset_prepare(struct xe_guc *guc)
1853 {
1854 	int ret;
1855 
1856 	if (!guc->submission_state.initialized)
1857 		return 0;
1858 
1859 	/*
1860 	 * Using an atomic here rather than submission_state.lock as this
1861 	 * function can be called while holding the CT lock (engine reset
1862 	 * failure). submission_state.lock needs the CT lock to resubmit jobs.
1863 	 * Atomic is not ideal, but it works to prevent against concurrent reset
1864 	 * and releasing any TDRs waiting on guc->submission_state.stopped.
1865 	 */
1866 	ret = atomic_fetch_or(1, &guc->submission_state.stopped);
1867 	smp_wmb();
1868 	wake_up_all(&guc->ct.wq);
1869 
1870 	return ret;
1871 }
1872 
1873 void xe_guc_submit_reset_wait(struct xe_guc *guc)
1874 {
1875 	wait_event(guc->ct.wq, xe_device_wedged(guc_to_xe(guc)) ||
1876 		   !xe_guc_read_stopped(guc));
1877 }
1878 
1879 void xe_guc_submit_stop(struct xe_guc *guc)
1880 {
1881 	struct xe_exec_queue *q;
1882 	unsigned long index;
1883 
1884 	xe_gt_assert(guc_to_gt(guc), xe_guc_read_stopped(guc) == 1);
1885 
1886 	mutex_lock(&guc->submission_state.lock);
1887 
1888 	xa_for_each(&guc->submission_state.exec_queue_lookup, index, q) {
1889 		/* Prevent redundant attempts to stop parallel queues */
1890 		if (q->guc->id != index)
1891 			continue;
1892 
1893 		guc_exec_queue_stop(guc, q);
1894 	}
1895 
1896 	mutex_unlock(&guc->submission_state.lock);
1897 
1898 	/*
1899 	 * No one can enter the backend at this point, aside from new engine
1900 	 * creation which is protected by guc->submission_state.lock.
1901 	 */
1902 
1903 }
1904 
1905 static void guc_exec_queue_start(struct xe_exec_queue *q)
1906 {
1907 	struct xe_gpu_scheduler *sched = &q->guc->sched;
1908 
1909 	if (!exec_queue_killed_or_banned_or_wedged(q)) {
1910 		int i;
1911 
1912 		trace_xe_exec_queue_resubmit(q);
1913 		for (i = 0; i < q->width; ++i)
1914 			xe_lrc_set_ring_head(q->lrc[i], q->lrc[i]->ring.tail);
1915 		xe_sched_resubmit_jobs(sched);
1916 	}
1917 
1918 	xe_sched_submission_start(sched);
1919 	xe_sched_submission_resume_tdr(sched);
1920 }
1921 
1922 int xe_guc_submit_start(struct xe_guc *guc)
1923 {
1924 	struct xe_exec_queue *q;
1925 	unsigned long index;
1926 
1927 	xe_gt_assert(guc_to_gt(guc), xe_guc_read_stopped(guc) == 1);
1928 
1929 	mutex_lock(&guc->submission_state.lock);
1930 	atomic_dec(&guc->submission_state.stopped);
1931 	xa_for_each(&guc->submission_state.exec_queue_lookup, index, q) {
1932 		/* Prevent redundant attempts to start parallel queues */
1933 		if (q->guc->id != index)
1934 			continue;
1935 
1936 		guc_exec_queue_start(q);
1937 	}
1938 	mutex_unlock(&guc->submission_state.lock);
1939 
1940 	wake_up_all(&guc->ct.wq);
1941 
1942 	return 0;
1943 }
1944 
1945 static struct xe_exec_queue *
1946 g2h_exec_queue_lookup(struct xe_guc *guc, u32 guc_id)
1947 {
1948 	struct xe_gt *gt = guc_to_gt(guc);
1949 	struct xe_exec_queue *q;
1950 
1951 	if (unlikely(guc_id >= GUC_ID_MAX)) {
1952 		xe_gt_err(gt, "Invalid guc_id %u\n", guc_id);
1953 		return NULL;
1954 	}
1955 
1956 	q = xa_load(&guc->submission_state.exec_queue_lookup, guc_id);
1957 	if (unlikely(!q)) {
1958 		xe_gt_err(gt, "Not engine present for guc_id %u\n", guc_id);
1959 		return NULL;
1960 	}
1961 
1962 	xe_gt_assert(guc_to_gt(guc), guc_id >= q->guc->id);
1963 	xe_gt_assert(guc_to_gt(guc), guc_id < (q->guc->id + q->width));
1964 
1965 	return q;
1966 }
1967 
1968 static void deregister_exec_queue(struct xe_guc *guc, struct xe_exec_queue *q)
1969 {
1970 	u32 action[] = {
1971 		XE_GUC_ACTION_DEREGISTER_CONTEXT,
1972 		q->guc->id,
1973 	};
1974 
1975 	xe_gt_assert(guc_to_gt(guc), exec_queue_destroyed(q));
1976 	xe_gt_assert(guc_to_gt(guc), exec_queue_registered(q));
1977 	xe_gt_assert(guc_to_gt(guc), !exec_queue_pending_disable(q));
1978 	xe_gt_assert(guc_to_gt(guc), !exec_queue_pending_enable(q));
1979 
1980 	trace_xe_exec_queue_deregister(q);
1981 
1982 	xe_guc_ct_send_g2h_handler(&guc->ct, action, ARRAY_SIZE(action));
1983 }
1984 
1985 static void handle_sched_done(struct xe_guc *guc, struct xe_exec_queue *q,
1986 			      u32 runnable_state)
1987 {
1988 	trace_xe_exec_queue_scheduling_done(q);
1989 
1990 	if (runnable_state == 1) {
1991 		xe_gt_assert(guc_to_gt(guc), exec_queue_pending_enable(q));
1992 
1993 		q->guc->resume_time = ktime_get();
1994 		clear_exec_queue_pending_enable(q);
1995 		smp_wmb();
1996 		wake_up_all(&guc->ct.wq);
1997 	} else {
1998 		bool check_timeout = exec_queue_check_timeout(q);
1999 
2000 		xe_gt_assert(guc_to_gt(guc), runnable_state == 0);
2001 		xe_gt_assert(guc_to_gt(guc), exec_queue_pending_disable(q));
2002 
2003 		if (q->guc->suspend_pending) {
2004 			suspend_fence_signal(q);
2005 			clear_exec_queue_pending_disable(q);
2006 		} else {
2007 			if (exec_queue_banned(q) || check_timeout) {
2008 				smp_wmb();
2009 				wake_up_all(&guc->ct.wq);
2010 			}
2011 			if (!check_timeout && exec_queue_destroyed(q)) {
2012 				/*
2013 				 * Make sure to clear the pending_disable only
2014 				 * after sampling the destroyed state. We want
2015 				 * to ensure we don't trigger the unregister too
2016 				 * early with something intending to only
2017 				 * disable scheduling. The caller doing the
2018 				 * destroy must wait for an ongoing
2019 				 * pending_disable before marking as destroyed.
2020 				 */
2021 				clear_exec_queue_pending_disable(q);
2022 				deregister_exec_queue(guc, q);
2023 			} else {
2024 				clear_exec_queue_pending_disable(q);
2025 			}
2026 		}
2027 	}
2028 }
2029 
2030 int xe_guc_sched_done_handler(struct xe_guc *guc, u32 *msg, u32 len)
2031 {
2032 	struct xe_exec_queue *q;
2033 	u32 guc_id, runnable_state;
2034 
2035 	if (unlikely(len < 2))
2036 		return -EPROTO;
2037 
2038 	guc_id = msg[0];
2039 	runnable_state = msg[1];
2040 
2041 	q = g2h_exec_queue_lookup(guc, guc_id);
2042 	if (unlikely(!q))
2043 		return -EPROTO;
2044 
2045 	if (unlikely(!exec_queue_pending_enable(q) &&
2046 		     !exec_queue_pending_disable(q))) {
2047 		xe_gt_err(guc_to_gt(guc),
2048 			  "SCHED_DONE: Unexpected engine state 0x%04x, guc_id=%d, runnable_state=%u",
2049 			  atomic_read(&q->guc->state), q->guc->id,
2050 			  runnable_state);
2051 		return -EPROTO;
2052 	}
2053 
2054 	handle_sched_done(guc, q, runnable_state);
2055 
2056 	return 0;
2057 }
2058 
2059 static void handle_deregister_done(struct xe_guc *guc, struct xe_exec_queue *q)
2060 {
2061 	trace_xe_exec_queue_deregister_done(q);
2062 
2063 	clear_exec_queue_registered(q);
2064 
2065 	if (exec_queue_extra_ref(q) || xe_exec_queue_is_lr(q))
2066 		xe_exec_queue_put(q);
2067 	else
2068 		__guc_exec_queue_destroy(guc, q);
2069 }
2070 
2071 int xe_guc_deregister_done_handler(struct xe_guc *guc, u32 *msg, u32 len)
2072 {
2073 	struct xe_exec_queue *q;
2074 	u32 guc_id;
2075 
2076 	if (unlikely(len < 1))
2077 		return -EPROTO;
2078 
2079 	guc_id = msg[0];
2080 
2081 	q = g2h_exec_queue_lookup(guc, guc_id);
2082 	if (unlikely(!q))
2083 		return -EPROTO;
2084 
2085 	if (!exec_queue_destroyed(q) || exec_queue_pending_disable(q) ||
2086 	    exec_queue_pending_enable(q) || exec_queue_enabled(q)) {
2087 		xe_gt_err(guc_to_gt(guc),
2088 			  "DEREGISTER_DONE: Unexpected engine state 0x%04x, guc_id=%d",
2089 			  atomic_read(&q->guc->state), q->guc->id);
2090 		return -EPROTO;
2091 	}
2092 
2093 	handle_deregister_done(guc, q);
2094 
2095 	return 0;
2096 }
2097 
2098 int xe_guc_exec_queue_reset_handler(struct xe_guc *guc, u32 *msg, u32 len)
2099 {
2100 	struct xe_gt *gt = guc_to_gt(guc);
2101 	struct xe_exec_queue *q;
2102 	u32 guc_id;
2103 
2104 	if (unlikely(len < 1))
2105 		return -EPROTO;
2106 
2107 	guc_id = msg[0];
2108 
2109 	q = g2h_exec_queue_lookup(guc, guc_id);
2110 	if (unlikely(!q))
2111 		return -EPROTO;
2112 
2113 	xe_gt_info(gt, "Engine reset: engine_class=%s, logical_mask: 0x%x, guc_id=%d",
2114 		   xe_hw_engine_class_to_str(q->class), q->logical_mask, guc_id);
2115 
2116 	trace_xe_exec_queue_reset(q);
2117 
2118 	/*
2119 	 * A banned engine is a NOP at this point (came from
2120 	 * guc_exec_queue_timedout_job). Otherwise, kick drm scheduler to cancel
2121 	 * jobs by setting timeout of the job to the minimum value kicking
2122 	 * guc_exec_queue_timedout_job.
2123 	 */
2124 	set_exec_queue_reset(q);
2125 	if (!exec_queue_banned(q) && !exec_queue_check_timeout(q))
2126 		xe_guc_exec_queue_trigger_cleanup(q);
2127 
2128 	return 0;
2129 }
2130 
2131 /*
2132  * xe_guc_error_capture_handler - Handler of GuC captured message
2133  * @guc: The GuC object
2134  * @msg: Point to the message
2135  * @len: The message length
2136  *
2137  * When GuC captured data is ready, GuC will send message
2138  * XE_GUC_ACTION_STATE_CAPTURE_NOTIFICATION to host, this function will be
2139  * called 1st to check status before process the data comes with the message.
2140  *
2141  * Returns: error code. 0 if success
2142  */
2143 int xe_guc_error_capture_handler(struct xe_guc *guc, u32 *msg, u32 len)
2144 {
2145 	u32 status;
2146 
2147 	if (unlikely(len != XE_GUC_ACTION_STATE_CAPTURE_NOTIFICATION_DATA_LEN))
2148 		return -EPROTO;
2149 
2150 	status = msg[0] & XE_GUC_STATE_CAPTURE_EVENT_STATUS_MASK;
2151 	if (status == XE_GUC_STATE_CAPTURE_EVENT_STATUS_NOSPACE)
2152 		xe_gt_warn(guc_to_gt(guc), "G2H-Error capture no space");
2153 
2154 	xe_guc_capture_process(guc);
2155 
2156 	return 0;
2157 }
2158 
2159 int xe_guc_exec_queue_memory_cat_error_handler(struct xe_guc *guc, u32 *msg,
2160 					       u32 len)
2161 {
2162 	struct xe_gt *gt = guc_to_gt(guc);
2163 	struct xe_exec_queue *q;
2164 	u32 guc_id;
2165 	u32 type = XE_GUC_CAT_ERR_TYPE_INVALID;
2166 
2167 	if (unlikely(!len || len > 2))
2168 		return -EPROTO;
2169 
2170 	guc_id = msg[0];
2171 
2172 	if (len == 2)
2173 		type = msg[1];
2174 
2175 	if (guc_id == GUC_ID_UNKNOWN) {
2176 		/*
2177 		 * GuC uses GUC_ID_UNKNOWN if it can not map the CAT fault to any PF/VF
2178 		 * context. In such case only PF will be notified about that fault.
2179 		 */
2180 		xe_gt_err_ratelimited(gt, "Memory CAT error reported by GuC!\n");
2181 		return 0;
2182 	}
2183 
2184 	q = g2h_exec_queue_lookup(guc, guc_id);
2185 	if (unlikely(!q))
2186 		return -EPROTO;
2187 
2188 	/*
2189 	 * The type is HW-defined and changes based on platform, so we don't
2190 	 * decode it in the kernel and only check if it is valid.
2191 	 * See bspec 54047 and 72187 for details.
2192 	 */
2193 	if (type != XE_GUC_CAT_ERR_TYPE_INVALID)
2194 		xe_gt_dbg(gt,
2195 			  "Engine memory CAT error [%u]: class=%s, logical_mask: 0x%x, guc_id=%d",
2196 			  type, xe_hw_engine_class_to_str(q->class), q->logical_mask, guc_id);
2197 	else
2198 		xe_gt_dbg(gt,
2199 			  "Engine memory CAT error: class=%s, logical_mask: 0x%x, guc_id=%d",
2200 			  xe_hw_engine_class_to_str(q->class), q->logical_mask, guc_id);
2201 
2202 	trace_xe_exec_queue_memory_cat_error(q);
2203 
2204 	/* Treat the same as engine reset */
2205 	set_exec_queue_reset(q);
2206 	if (!exec_queue_banned(q) && !exec_queue_check_timeout(q))
2207 		xe_guc_exec_queue_trigger_cleanup(q);
2208 
2209 	return 0;
2210 }
2211 
2212 int xe_guc_exec_queue_reset_failure_handler(struct xe_guc *guc, u32 *msg, u32 len)
2213 {
2214 	struct xe_gt *gt = guc_to_gt(guc);
2215 	u8 guc_class, instance;
2216 	u32 reason;
2217 
2218 	if (unlikely(len != 3))
2219 		return -EPROTO;
2220 
2221 	guc_class = msg[0];
2222 	instance = msg[1];
2223 	reason = msg[2];
2224 
2225 	/* Unexpected failure of a hardware feature, log an actual error */
2226 	xe_gt_err(gt, "GuC engine reset request failed on %d:%d because 0x%08X",
2227 		  guc_class, instance, reason);
2228 
2229 	xe_gt_reset_async(gt);
2230 
2231 	return 0;
2232 }
2233 
2234 static void
2235 guc_exec_queue_wq_snapshot_capture(struct xe_exec_queue *q,
2236 				   struct xe_guc_submit_exec_queue_snapshot *snapshot)
2237 {
2238 	struct xe_guc *guc = exec_queue_to_guc(q);
2239 	struct xe_device *xe = guc_to_xe(guc);
2240 	struct iosys_map map = xe_lrc_parallel_map(q->lrc[0]);
2241 	int i;
2242 
2243 	snapshot->guc.wqi_head = q->guc->wqi_head;
2244 	snapshot->guc.wqi_tail = q->guc->wqi_tail;
2245 	snapshot->parallel.wq_desc.head = parallel_read(xe, map, wq_desc.head);
2246 	snapshot->parallel.wq_desc.tail = parallel_read(xe, map, wq_desc.tail);
2247 	snapshot->parallel.wq_desc.status = parallel_read(xe, map,
2248 							  wq_desc.wq_status);
2249 
2250 	if (snapshot->parallel.wq_desc.head !=
2251 	    snapshot->parallel.wq_desc.tail) {
2252 		for (i = snapshot->parallel.wq_desc.head;
2253 		     i != snapshot->parallel.wq_desc.tail;
2254 		     i = (i + sizeof(u32)) % WQ_SIZE)
2255 			snapshot->parallel.wq[i / sizeof(u32)] =
2256 				parallel_read(xe, map, wq[i / sizeof(u32)]);
2257 	}
2258 }
2259 
2260 static void
2261 guc_exec_queue_wq_snapshot_print(struct xe_guc_submit_exec_queue_snapshot *snapshot,
2262 				 struct drm_printer *p)
2263 {
2264 	int i;
2265 
2266 	drm_printf(p, "\tWQ head: %u (internal), %d (memory)\n",
2267 		   snapshot->guc.wqi_head, snapshot->parallel.wq_desc.head);
2268 	drm_printf(p, "\tWQ tail: %u (internal), %d (memory)\n",
2269 		   snapshot->guc.wqi_tail, snapshot->parallel.wq_desc.tail);
2270 	drm_printf(p, "\tWQ status: %u\n", snapshot->parallel.wq_desc.status);
2271 
2272 	if (snapshot->parallel.wq_desc.head !=
2273 	    snapshot->parallel.wq_desc.tail) {
2274 		for (i = snapshot->parallel.wq_desc.head;
2275 		     i != snapshot->parallel.wq_desc.tail;
2276 		     i = (i + sizeof(u32)) % WQ_SIZE)
2277 			drm_printf(p, "\tWQ[%zu]: 0x%08x\n", i / sizeof(u32),
2278 				   snapshot->parallel.wq[i / sizeof(u32)]);
2279 	}
2280 }
2281 
2282 /**
2283  * xe_guc_exec_queue_snapshot_capture - Take a quick snapshot of the GuC Engine.
2284  * @q: faulty exec queue
2285  *
2286  * This can be printed out in a later stage like during dev_coredump
2287  * analysis.
2288  *
2289  * Returns: a GuC Submit Engine snapshot object that must be freed by the
2290  * caller, using `xe_guc_exec_queue_snapshot_free`.
2291  */
2292 struct xe_guc_submit_exec_queue_snapshot *
2293 xe_guc_exec_queue_snapshot_capture(struct xe_exec_queue *q)
2294 {
2295 	struct xe_gpu_scheduler *sched = &q->guc->sched;
2296 	struct xe_guc_submit_exec_queue_snapshot *snapshot;
2297 	int i;
2298 
2299 	snapshot = kzalloc(sizeof(*snapshot), GFP_ATOMIC);
2300 
2301 	if (!snapshot)
2302 		return NULL;
2303 
2304 	snapshot->guc.id = q->guc->id;
2305 	memcpy(&snapshot->name, &q->name, sizeof(snapshot->name));
2306 	snapshot->class = q->class;
2307 	snapshot->logical_mask = q->logical_mask;
2308 	snapshot->width = q->width;
2309 	snapshot->refcount = kref_read(&q->refcount);
2310 	snapshot->sched_timeout = sched->base.timeout;
2311 	snapshot->sched_props.timeslice_us = q->sched_props.timeslice_us;
2312 	snapshot->sched_props.preempt_timeout_us =
2313 		q->sched_props.preempt_timeout_us;
2314 
2315 	snapshot->lrc = kmalloc_array(q->width, sizeof(struct xe_lrc_snapshot *),
2316 				      GFP_ATOMIC);
2317 
2318 	if (snapshot->lrc) {
2319 		for (i = 0; i < q->width; ++i) {
2320 			struct xe_lrc *lrc = q->lrc[i];
2321 
2322 			snapshot->lrc[i] = xe_lrc_snapshot_capture(lrc);
2323 		}
2324 	}
2325 
2326 	snapshot->schedule_state = atomic_read(&q->guc->state);
2327 	snapshot->exec_queue_flags = q->flags;
2328 
2329 	snapshot->parallel_execution = xe_exec_queue_is_parallel(q);
2330 	if (snapshot->parallel_execution)
2331 		guc_exec_queue_wq_snapshot_capture(q, snapshot);
2332 
2333 	spin_lock(&sched->base.job_list_lock);
2334 	snapshot->pending_list_size = list_count_nodes(&sched->base.pending_list);
2335 	snapshot->pending_list = kmalloc_array(snapshot->pending_list_size,
2336 					       sizeof(struct pending_list_snapshot),
2337 					       GFP_ATOMIC);
2338 
2339 	if (snapshot->pending_list) {
2340 		struct xe_sched_job *job_iter;
2341 
2342 		i = 0;
2343 		list_for_each_entry(job_iter, &sched->base.pending_list, drm.list) {
2344 			snapshot->pending_list[i].seqno =
2345 				xe_sched_job_seqno(job_iter);
2346 			snapshot->pending_list[i].fence =
2347 				dma_fence_is_signaled(job_iter->fence) ? 1 : 0;
2348 			snapshot->pending_list[i].finished =
2349 				dma_fence_is_signaled(&job_iter->drm.s_fence->finished)
2350 				? 1 : 0;
2351 			i++;
2352 		}
2353 	}
2354 
2355 	spin_unlock(&sched->base.job_list_lock);
2356 
2357 	return snapshot;
2358 }
2359 
2360 /**
2361  * xe_guc_exec_queue_snapshot_capture_delayed - Take delayed part of snapshot of the GuC Engine.
2362  * @snapshot: Previously captured snapshot of job.
2363  *
2364  * This captures some data that requires taking some locks, so it cannot be done in signaling path.
2365  */
2366 void
2367 xe_guc_exec_queue_snapshot_capture_delayed(struct xe_guc_submit_exec_queue_snapshot *snapshot)
2368 {
2369 	int i;
2370 
2371 	if (!snapshot || !snapshot->lrc)
2372 		return;
2373 
2374 	for (i = 0; i < snapshot->width; ++i)
2375 		xe_lrc_snapshot_capture_delayed(snapshot->lrc[i]);
2376 }
2377 
2378 /**
2379  * xe_guc_exec_queue_snapshot_print - Print out a given GuC Engine snapshot.
2380  * @snapshot: GuC Submit Engine snapshot object.
2381  * @p: drm_printer where it will be printed out.
2382  *
2383  * This function prints out a given GuC Submit Engine snapshot object.
2384  */
2385 void
2386 xe_guc_exec_queue_snapshot_print(struct xe_guc_submit_exec_queue_snapshot *snapshot,
2387 				 struct drm_printer *p)
2388 {
2389 	int i;
2390 
2391 	if (!snapshot)
2392 		return;
2393 
2394 	drm_printf(p, "GuC ID: %d\n", snapshot->guc.id);
2395 	drm_printf(p, "\tName: %s\n", snapshot->name);
2396 	drm_printf(p, "\tClass: %d\n", snapshot->class);
2397 	drm_printf(p, "\tLogical mask: 0x%x\n", snapshot->logical_mask);
2398 	drm_printf(p, "\tWidth: %d\n", snapshot->width);
2399 	drm_printf(p, "\tRef: %d\n", snapshot->refcount);
2400 	drm_printf(p, "\tTimeout: %ld (ms)\n", snapshot->sched_timeout);
2401 	drm_printf(p, "\tTimeslice: %u (us)\n",
2402 		   snapshot->sched_props.timeslice_us);
2403 	drm_printf(p, "\tPreempt timeout: %u (us)\n",
2404 		   snapshot->sched_props.preempt_timeout_us);
2405 
2406 	for (i = 0; snapshot->lrc && i < snapshot->width; ++i)
2407 		xe_lrc_snapshot_print(snapshot->lrc[i], p);
2408 
2409 	drm_printf(p, "\tSchedule State: 0x%x\n", snapshot->schedule_state);
2410 	drm_printf(p, "\tFlags: 0x%lx\n", snapshot->exec_queue_flags);
2411 
2412 	if (snapshot->parallel_execution)
2413 		guc_exec_queue_wq_snapshot_print(snapshot, p);
2414 
2415 	for (i = 0; snapshot->pending_list && i < snapshot->pending_list_size;
2416 	     i++)
2417 		drm_printf(p, "\tJob: seqno=%d, fence=%d, finished=%d\n",
2418 			   snapshot->pending_list[i].seqno,
2419 			   snapshot->pending_list[i].fence,
2420 			   snapshot->pending_list[i].finished);
2421 }
2422 
2423 /**
2424  * xe_guc_exec_queue_snapshot_free - Free all allocated objects for a given
2425  * snapshot.
2426  * @snapshot: GuC Submit Engine snapshot object.
2427  *
2428  * This function free all the memory that needed to be allocated at capture
2429  * time.
2430  */
2431 void xe_guc_exec_queue_snapshot_free(struct xe_guc_submit_exec_queue_snapshot *snapshot)
2432 {
2433 	int i;
2434 
2435 	if (!snapshot)
2436 		return;
2437 
2438 	if (snapshot->lrc) {
2439 		for (i = 0; i < snapshot->width; i++)
2440 			xe_lrc_snapshot_free(snapshot->lrc[i]);
2441 		kfree(snapshot->lrc);
2442 	}
2443 	kfree(snapshot->pending_list);
2444 	kfree(snapshot);
2445 }
2446 
2447 static void guc_exec_queue_print(struct xe_exec_queue *q, struct drm_printer *p)
2448 {
2449 	struct xe_guc_submit_exec_queue_snapshot *snapshot;
2450 
2451 	snapshot = xe_guc_exec_queue_snapshot_capture(q);
2452 	xe_guc_exec_queue_snapshot_print(snapshot, p);
2453 	xe_guc_exec_queue_snapshot_free(snapshot);
2454 }
2455 
2456 /**
2457  * xe_guc_submit_print - GuC Submit Print.
2458  * @guc: GuC.
2459  * @p: drm_printer where it will be printed out.
2460  *
2461  * This function capture and prints snapshots of **all** GuC Engines.
2462  */
2463 void xe_guc_submit_print(struct xe_guc *guc, struct drm_printer *p)
2464 {
2465 	struct xe_exec_queue *q;
2466 	unsigned long index;
2467 
2468 	if (!xe_device_uc_enabled(guc_to_xe(guc)))
2469 		return;
2470 
2471 	mutex_lock(&guc->submission_state.lock);
2472 	xa_for_each(&guc->submission_state.exec_queue_lookup, index, q)
2473 		guc_exec_queue_print(q, p);
2474 	mutex_unlock(&guc->submission_state.lock);
2475 }
2476