xref: /linux/drivers/gpu/drm/xe/xe_guc_submit.c (revision 3a2c4d55e32ad65efebdb6de44eef3bfa08bb49d)
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/dma-fence-array.h>
12 
13 #include <drm/drm_drv.h>
14 #include <drm/drm_managed.h>
15 
16 #include "abi/guc_actions_abi.h"
17 #include "abi/guc_actions_slpc_abi.h"
18 #include "abi/guc_klvs_abi.h"
19 #include "xe_assert.h"
20 #include "xe_bo.h"
21 #include "xe_devcoredump.h"
22 #include "xe_device.h"
23 #include "xe_exec_queue.h"
24 #include "xe_force_wake.h"
25 #include "xe_gpu_scheduler.h"
26 #include "xe_gt.h"
27 #include "xe_gt_clock.h"
28 #include "xe_gt_printk.h"
29 #include "xe_guc.h"
30 #include "xe_guc_capture.h"
31 #include "xe_guc_ct.h"
32 #include "xe_guc_exec_queue_types.h"
33 #include "xe_guc_id_mgr.h"
34 #include "xe_guc_klv_helpers.h"
35 #include "xe_guc_submit_types.h"
36 #include "xe_hw_engine.h"
37 #include "xe_lrc.h"
38 #include "xe_macros.h"
39 #include "xe_map.h"
40 #include "xe_mocs.h"
41 #include "xe_module.h"
42 #include "xe_pm.h"
43 #include "xe_ring_ops_types.h"
44 #include "xe_sched_job.h"
45 #include "xe_sleep.h"
46 #include "xe_trace.h"
47 #include "xe_uc_fw.h"
48 #include "xe_vm.h"
49 
50 #define XE_GUC_EXEC_QUEUE_CGP_CONTEXT_ERROR_LEN		6
51 
52 static int guc_submit_reset_prepare(struct xe_guc *guc);
53 
54 static struct xe_guc *
55 exec_queue_to_guc(struct xe_exec_queue *q)
56 {
57 	return &q->gt->uc.guc;
58 }
59 
60 /*
61  * Helpers for engine state, using an atomic as some of the bits can transition
62  * as the same time (e.g. a suspend can be happning at the same time as schedule
63  * engine done being processed).
64  */
65 #define EXEC_QUEUE_STATE_REGISTERED		(1 << 0)
66 #define EXEC_QUEUE_STATE_ENABLED		(1 << 1)
67 #define EXEC_QUEUE_STATE_PENDING_ENABLE		(1 << 2)
68 #define EXEC_QUEUE_STATE_PENDING_DISABLE	(1 << 3)
69 #define EXEC_QUEUE_STATE_DESTROYED		(1 << 4)
70 #define EXEC_QUEUE_STATE_SUSPENDED		(1 << 5)
71 #define EXEC_QUEUE_STATE_RESET			(1 << 6)
72 #define EXEC_QUEUE_STATE_KILLED			(1 << 7)
73 #define EXEC_QUEUE_STATE_WEDGED			(1 << 8)
74 #define EXEC_QUEUE_STATE_BANNED			(1 << 9)
75 #define EXEC_QUEUE_STATE_PENDING_RESUME		(1 << 10)
76 
77 static bool exec_queue_registered(struct xe_exec_queue *q)
78 {
79 	return atomic_read(&q->guc->state) & EXEC_QUEUE_STATE_REGISTERED;
80 }
81 
82 static void set_exec_queue_registered(struct xe_exec_queue *q)
83 {
84 	atomic_or(EXEC_QUEUE_STATE_REGISTERED, &q->guc->state);
85 }
86 
87 static void clear_exec_queue_registered(struct xe_exec_queue *q)
88 {
89 	atomic_and(~EXEC_QUEUE_STATE_REGISTERED, &q->guc->state);
90 }
91 
92 static bool exec_queue_enabled(struct xe_exec_queue *q)
93 {
94 	return atomic_read(&q->guc->state) & EXEC_QUEUE_STATE_ENABLED;
95 }
96 
97 static void set_exec_queue_enabled(struct xe_exec_queue *q)
98 {
99 	atomic_or(EXEC_QUEUE_STATE_ENABLED, &q->guc->state);
100 }
101 
102 static void clear_exec_queue_enabled(struct xe_exec_queue *q)
103 {
104 	atomic_and(~EXEC_QUEUE_STATE_ENABLED, &q->guc->state);
105 }
106 
107 static bool exec_queue_pending_enable(struct xe_exec_queue *q)
108 {
109 	return atomic_read(&q->guc->state) & EXEC_QUEUE_STATE_PENDING_ENABLE;
110 }
111 
112 static void set_exec_queue_pending_enable(struct xe_exec_queue *q)
113 {
114 	atomic_or(EXEC_QUEUE_STATE_PENDING_ENABLE, &q->guc->state);
115 }
116 
117 static void clear_exec_queue_pending_enable(struct xe_exec_queue *q)
118 {
119 	atomic_and(~EXEC_QUEUE_STATE_PENDING_ENABLE, &q->guc->state);
120 }
121 
122 static bool exec_queue_pending_disable(struct xe_exec_queue *q)
123 {
124 	return atomic_read(&q->guc->state) & EXEC_QUEUE_STATE_PENDING_DISABLE;
125 }
126 
127 static void set_exec_queue_pending_disable(struct xe_exec_queue *q)
128 {
129 	atomic_or(EXEC_QUEUE_STATE_PENDING_DISABLE, &q->guc->state);
130 }
131 
132 static void clear_exec_queue_pending_disable(struct xe_exec_queue *q)
133 {
134 	atomic_and(~EXEC_QUEUE_STATE_PENDING_DISABLE, &q->guc->state);
135 }
136 
137 static bool exec_queue_destroyed(struct xe_exec_queue *q)
138 {
139 	return atomic_read(&q->guc->state) & EXEC_QUEUE_STATE_DESTROYED;
140 }
141 
142 static void set_exec_queue_destroyed(struct xe_exec_queue *q)
143 {
144 	atomic_or(EXEC_QUEUE_STATE_DESTROYED, &q->guc->state);
145 }
146 
147 static void clear_exec_queue_destroyed(struct xe_exec_queue *q)
148 {
149 	atomic_and(~EXEC_QUEUE_STATE_DESTROYED, &q->guc->state);
150 }
151 
152 static bool exec_queue_banned(struct xe_exec_queue *q)
153 {
154 	return atomic_read(&q->guc->state) & EXEC_QUEUE_STATE_BANNED;
155 }
156 
157 static void set_exec_queue_banned(struct xe_exec_queue *q)
158 {
159 	atomic_or(EXEC_QUEUE_STATE_BANNED, &q->guc->state);
160 }
161 
162 static void clear_exec_queue_banned(struct xe_exec_queue *q)
163 {
164 	atomic_andnot(EXEC_QUEUE_STATE_BANNED, &q->guc->state);
165 }
166 
167 static bool exec_queue_suspended(struct xe_exec_queue *q)
168 {
169 	return atomic_read(&q->guc->state) & EXEC_QUEUE_STATE_SUSPENDED;
170 }
171 
172 static void set_exec_queue_suspended(struct xe_exec_queue *q)
173 {
174 	atomic_or(EXEC_QUEUE_STATE_SUSPENDED, &q->guc->state);
175 }
176 
177 static void clear_exec_queue_suspended(struct xe_exec_queue *q)
178 {
179 	atomic_and(~EXEC_QUEUE_STATE_SUSPENDED, &q->guc->state);
180 }
181 
182 static bool exec_queue_reset(struct xe_exec_queue *q)
183 {
184 	return atomic_read(&q->guc->state) & EXEC_QUEUE_STATE_RESET;
185 }
186 
187 static void set_exec_queue_reset(struct xe_exec_queue *q)
188 {
189 	atomic_or(EXEC_QUEUE_STATE_RESET, &q->guc->state);
190 }
191 
192 static bool exec_queue_killed(struct xe_exec_queue *q)
193 {
194 	return atomic_read(&q->guc->state) & EXEC_QUEUE_STATE_KILLED;
195 }
196 
197 static void set_exec_queue_killed(struct xe_exec_queue *q)
198 {
199 	atomic_or(EXEC_QUEUE_STATE_KILLED, &q->guc->state);
200 }
201 
202 static bool exec_queue_wedged(struct xe_exec_queue *q)
203 {
204 	return atomic_read(&q->guc->state) & EXEC_QUEUE_STATE_WEDGED;
205 }
206 
207 static void set_exec_queue_wedged(struct xe_exec_queue *q)
208 {
209 	atomic_or(EXEC_QUEUE_STATE_WEDGED, &q->guc->state);
210 }
211 
212 static bool exec_queue_pending_resume(struct xe_exec_queue *q)
213 {
214 	return atomic_read(&q->guc->state) & EXEC_QUEUE_STATE_PENDING_RESUME;
215 }
216 
217 static void set_exec_queue_pending_resume(struct xe_exec_queue *q)
218 {
219 	atomic_or(EXEC_QUEUE_STATE_PENDING_RESUME, &q->guc->state);
220 }
221 
222 static void clear_exec_queue_pending_resume(struct xe_exec_queue *q)
223 {
224 	atomic_and(~EXEC_QUEUE_STATE_PENDING_RESUME, &q->guc->state);
225 }
226 
227 static bool exec_queue_killed_or_banned_or_wedged(struct xe_exec_queue *q)
228 {
229 	return (atomic_read(&q->guc->state) &
230 		(EXEC_QUEUE_STATE_WEDGED | EXEC_QUEUE_STATE_KILLED |
231 		 EXEC_QUEUE_STATE_BANNED));
232 }
233 
234 static void guc_submit_sw_fini(struct drm_device *drm, void *arg)
235 {
236 	struct xe_guc *guc = arg;
237 	struct xe_gt *gt = guc_to_gt(guc);
238 
239 	xe_gt_assert(gt, xa_empty(&guc->submission_state.exec_queue_lookup));
240 
241 	xa_destroy(&guc->submission_state.exec_queue_lookup);
242 }
243 
244 static void guc_submit_fini(void *arg)
245 {
246 	struct xe_guc *guc = arg;
247 	struct xe_exec_queue *q;
248 	unsigned long index;
249 
250 	/* Drop any wedged queue refs */
251 	mutex_lock(&guc->submission_state.lock);
252 	xa_for_each(&guc->submission_state.exec_queue_lookup, index, q) {
253 		if (exec_queue_wedged(q)) {
254 			mutex_unlock(&guc->submission_state.lock);
255 			xe_exec_queue_put(q);
256 			mutex_lock(&guc->submission_state.lock);
257 		}
258 	}
259 	mutex_unlock(&guc->submission_state.lock);
260 
261 	/* Forcefully kill any remaining exec queues */
262 	xe_guc_ct_stop(&guc->ct);
263 	guc_submit_reset_prepare(guc);
264 	xe_guc_softreset(guc);
265 	xe_guc_submit_stop(guc);
266 	xe_uc_fw_sanitize(&guc->fw);
267 	xe_guc_submit_pause_abort(guc);
268 }
269 
270 static const struct xe_exec_queue_ops guc_exec_queue_ops;
271 
272 static void primelockdep(struct xe_guc *guc)
273 {
274 	if (!IS_ENABLED(CONFIG_LOCKDEP))
275 		return;
276 
277 	fs_reclaim_acquire(GFP_KERNEL);
278 
279 	mutex_lock(&guc->submission_state.lock);
280 	mutex_unlock(&guc->submission_state.lock);
281 
282 	fs_reclaim_release(GFP_KERNEL);
283 }
284 
285 /**
286  * xe_guc_submit_init() - Initialize GuC submission.
287  * @guc: the &xe_guc to initialize
288  * @num_ids: number of GuC context IDs to use
289  *
290  * The bare-metal or PF driver can pass ~0 as &num_ids to indicate that all
291  * GuC context IDs supported by the GuC firmware should be used for submission.
292  *
293  * Only VF drivers will have to provide explicit number of GuC context IDs
294  * that they can use for submission.
295  *
296  * Return: 0 on success or a negative error code on failure.
297  */
298 int xe_guc_submit_init(struct xe_guc *guc, unsigned int num_ids)
299 {
300 	struct xe_device *xe = guc_to_xe(guc);
301 	struct xe_gt *gt = guc_to_gt(guc);
302 	int err;
303 
304 	err = drmm_mutex_init(&xe->drm, &guc->submission_state.lock);
305 	if (err)
306 		return err;
307 
308 	err = xe_guc_id_mgr_init(&guc->submission_state.idm, num_ids);
309 	if (err)
310 		return err;
311 
312 	gt->exec_queue_ops = &guc_exec_queue_ops;
313 
314 	xa_init(&guc->submission_state.exec_queue_lookup);
315 
316 	primelockdep(guc);
317 
318 	guc->submission_state.initialized = true;
319 
320 	err = drmm_add_action_or_reset(&xe->drm, guc_submit_sw_fini, guc);
321 	if (err)
322 		return err;
323 
324 	return devm_add_action_or_reset(xe->drm.dev, guc_submit_fini, guc);
325 }
326 
327 /*
328  * Given that we want to guarantee enough RCS throughput to avoid missing
329  * frames, we set the yield policy to 20% of each 80ms interval.
330  */
331 #define RC_YIELD_DURATION	80	/* in ms */
332 #define RC_YIELD_RATIO		20	/* in percent */
333 static u32 *emit_render_compute_yield_klv(u32 *emit)
334 {
335 	*emit++ = PREP_GUC_KLV_TAG(SCHEDULING_POLICIES_RENDER_COMPUTE_YIELD);
336 	*emit++ = RC_YIELD_DURATION;
337 	*emit++ = RC_YIELD_RATIO;
338 
339 	return emit;
340 }
341 
342 #define SCHEDULING_POLICY_MAX_DWORDS 16
343 static int guc_init_global_schedule_policy(struct xe_guc *guc)
344 {
345 	u32 data[SCHEDULING_POLICY_MAX_DWORDS];
346 	u32 *emit = data;
347 	u32 count = 0;
348 	int ret;
349 
350 	if (GUC_SUBMIT_VER(guc) < MAKE_GUC_VER(1, 1, 0))
351 		return 0;
352 
353 	*emit++ = XE_GUC_ACTION_UPDATE_SCHEDULING_POLICIES_KLV;
354 
355 	if (CCS_INSTANCES(guc_to_gt(guc)))
356 		emit = emit_render_compute_yield_klv(emit);
357 
358 	count = emit - data;
359 	if (count > 1) {
360 		xe_assert(guc_to_xe(guc), count <= SCHEDULING_POLICY_MAX_DWORDS);
361 
362 		ret = xe_guc_ct_send_block(&guc->ct, data, count);
363 		if (ret < 0) {
364 			xe_gt_err(guc_to_gt(guc),
365 				  "failed to enable GuC scheduling policies: %pe\n",
366 				  ERR_PTR(ret));
367 			return ret;
368 		}
369 	}
370 
371 	return 0;
372 }
373 
374 int xe_guc_submit_enable(struct xe_guc *guc)
375 {
376 	int ret;
377 
378 	ret = guc_init_global_schedule_policy(guc);
379 	if (ret)
380 		return ret;
381 
382 	guc->submission_state.enabled = true;
383 
384 	return 0;
385 }
386 
387 void xe_guc_submit_disable(struct xe_guc *guc)
388 {
389 	guc->submission_state.enabled = false;
390 }
391 
392 static void __release_guc_id(struct xe_guc *guc, struct xe_exec_queue *q,
393 			     int count)
394 {
395 	int i;
396 
397 	mutex_lock(&guc->submission_state.lock);
398 
399 	for (i = 0; i < count; ++i)
400 		xa_erase(&guc->submission_state.exec_queue_lookup,
401 			 q->guc->id + i);
402 
403 	xe_guc_id_mgr_release_locked(&guc->submission_state.idm,
404 				     q->guc->id, q->width);
405 
406 	mutex_unlock(&guc->submission_state.lock);
407 }
408 
409 static int alloc_guc_id(struct xe_guc *guc, struct xe_exec_queue *q)
410 {
411 	int ret, i;
412 
413 	mutex_lock(&guc->submission_state.lock);
414 	ret = xe_guc_id_mgr_reserve_locked(&guc->submission_state.idm,
415 					   q->width);
416 	mutex_unlock(&guc->submission_state.lock);
417 	if (ret < 0)
418 		return ret;
419 
420 	q->guc->id = ret;
421 
422 	/* Reserve empty slots. */
423 	for (i = 0; i < q->width; ++i) {
424 		ret = xa_insert(&guc->submission_state.exec_queue_lookup,
425 				 q->guc->id + i, NULL, GFP_KERNEL);
426 		if (ret)
427 			goto err_release;
428 	}
429 
430 	return 0;
431 
432 err_release:
433 	__release_guc_id(guc, q, i);
434 
435 	return ret;
436 }
437 
438 static void publish_guc_id(struct xe_guc *guc, struct xe_exec_queue *q)
439 {
440 	int i;
441 
442 	lockdep_assert_held(&guc->submission_state.lock);
443 
444 	for (i = 0; i < q->width; ++i) {
445 		void *old;
446 
447 		old = xa_store(&guc->submission_state.exec_queue_lookup,
448 			       q->guc->id + i, q, GFP_NOWAIT);
449 		XE_WARN_ON(old || xa_is_err(old));
450 	}
451 }
452 
453 static void release_guc_id(struct xe_guc *guc, struct xe_exec_queue *q)
454 {
455 	__release_guc_id(guc, q, q->width);
456 }
457 
458 struct exec_queue_policy {
459 	u32 count;
460 	struct guc_update_exec_queue_policy h2g;
461 };
462 
463 static u32 __guc_exec_queue_policy_action_size(struct exec_queue_policy *policy)
464 {
465 	size_t bytes = sizeof(policy->h2g.header) +
466 		       (sizeof(policy->h2g.klv[0]) * policy->count);
467 
468 	return bytes / sizeof(u32);
469 }
470 
471 static void __guc_exec_queue_policy_start_klv(struct exec_queue_policy *policy,
472 					      u16 guc_id)
473 {
474 	policy->h2g.header.action =
475 		XE_GUC_ACTION_HOST2GUC_UPDATE_CONTEXT_POLICIES;
476 	policy->h2g.header.guc_id = guc_id;
477 	policy->count = 0;
478 }
479 
480 #define MAKE_EXEC_QUEUE_POLICY_ADD(func, id) \
481 static void __guc_exec_queue_policy_add_##func(struct exec_queue_policy *policy, \
482 					   u32 data) \
483 { \
484 	XE_WARN_ON(policy->count >= GUC_CONTEXT_POLICIES_KLV_NUM_IDS); \
485 \
486 	policy->h2g.klv[policy->count].kl = \
487 		FIELD_PREP(GUC_KLV_0_KEY, \
488 			   GUC_CONTEXT_POLICIES_KLV_ID_##id) | \
489 		FIELD_PREP(GUC_KLV_0_LEN, 1); \
490 	policy->h2g.klv[policy->count].value = data; \
491 	policy->count++; \
492 }
493 
494 MAKE_EXEC_QUEUE_POLICY_ADD(execution_quantum, EXECUTION_QUANTUM)
495 MAKE_EXEC_QUEUE_POLICY_ADD(preemption_timeout, PREEMPTION_TIMEOUT)
496 MAKE_EXEC_QUEUE_POLICY_ADD(priority, SCHEDULING_PRIORITY)
497 MAKE_EXEC_QUEUE_POLICY_ADD(slpc_exec_queue_freq_req, SLPM_GT_FREQUENCY)
498 #undef MAKE_EXEC_QUEUE_POLICY_ADD
499 
500 static const int xe_exec_queue_prio_to_guc[] = {
501 	[XE_EXEC_QUEUE_PRIORITY_LOW] = GUC_CLIENT_PRIORITY_NORMAL,
502 	[XE_EXEC_QUEUE_PRIORITY_NORMAL] = GUC_CLIENT_PRIORITY_KMD_NORMAL,
503 	[XE_EXEC_QUEUE_PRIORITY_HIGH] = GUC_CLIENT_PRIORITY_HIGH,
504 	[XE_EXEC_QUEUE_PRIORITY_KERNEL] = GUC_CLIENT_PRIORITY_KMD_HIGH,
505 };
506 
507 static void init_policies(struct xe_guc *guc, struct xe_exec_queue *q)
508 {
509 	struct exec_queue_policy policy;
510 	enum xe_exec_queue_priority prio = q->sched_props.priority;
511 	u32 timeslice_us = q->sched_props.timeslice_us;
512 	u32 slpc_exec_queue_freq_req = 0;
513 	u32 preempt_timeout_us = q->sched_props.preempt_timeout_us;
514 
515 	xe_gt_assert(guc_to_gt(guc), exec_queue_registered(q) &&
516 		     !xe_exec_queue_is_multi_queue_secondary(q));
517 
518 	if (q->flags & EXEC_QUEUE_FLAG_LOW_LATENCY)
519 		slpc_exec_queue_freq_req |= SLPC_CTX_FREQ_REQ_IS_COMPUTE;
520 
521 	__guc_exec_queue_policy_start_klv(&policy, q->guc->id);
522 	__guc_exec_queue_policy_add_priority(&policy, xe_exec_queue_prio_to_guc[prio]);
523 	__guc_exec_queue_policy_add_execution_quantum(&policy, timeslice_us);
524 	__guc_exec_queue_policy_add_preemption_timeout(&policy, preempt_timeout_us);
525 	__guc_exec_queue_policy_add_slpc_exec_queue_freq_req(&policy,
526 							     slpc_exec_queue_freq_req);
527 
528 	xe_guc_ct_send(&guc->ct, (u32 *)&policy.h2g,
529 		       __guc_exec_queue_policy_action_size(&policy), 0, 0);
530 }
531 
532 static void set_min_preemption_timeout(struct xe_guc *guc, struct xe_exec_queue *q)
533 {
534 	struct exec_queue_policy policy;
535 
536 	xe_assert(guc_to_xe(guc), !xe_exec_queue_is_multi_queue_secondary(q));
537 
538 	__guc_exec_queue_policy_start_klv(&policy, q->guc->id);
539 	__guc_exec_queue_policy_add_preemption_timeout(&policy, 1);
540 
541 	xe_guc_ct_send(&guc->ct, (u32 *)&policy.h2g,
542 		       __guc_exec_queue_policy_action_size(&policy), 0, 0);
543 }
544 
545 static bool vf_recovery(struct xe_guc *guc)
546 {
547 	return xe_gt_recovery_pending(guc_to_gt(guc));
548 }
549 
550 static void xe_guc_exec_queue_trigger_cleanup(struct xe_exec_queue *q)
551 {
552 	struct xe_guc *guc = exec_queue_to_guc(q);
553 	struct xe_device *xe = guc_to_xe(guc);
554 
555 	/** to wakeup xe_wait_user_fence ioctl if exec queue is reset */
556 	wake_up_all(&xe->ufence_wq);
557 
558 	xe_sched_tdr_queue_imm(&q->guc->sched);
559 }
560 
561 static void xe_guc_exec_queue_group_stop(struct xe_exec_queue *q)
562 {
563 	struct xe_exec_queue *primary = xe_exec_queue_multi_queue_primary(q);
564 	struct xe_exec_queue_group *group = q->multi_queue.group;
565 	struct xe_exec_queue *eq, *next;
566 	LIST_HEAD(tmp);
567 
568 	xe_gt_assert(guc_to_gt(exec_queue_to_guc(q)),
569 		     xe_exec_queue_is_multi_queue(q));
570 
571 	mutex_lock(&group->list_lock);
572 
573 	/*
574 	 * Stop all future queues being from executing while group is stopped.
575 	 */
576 	group->stopped = true;
577 
578 	list_for_each_entry_safe(eq, next, &group->list, multi_queue.link)
579 		/*
580 		 * Refcount prevents an attempted removal from &group->list,
581 		 * temporary list allows safe iteration after dropping
582 		 * &group->list_lock.
583 		 */
584 		if (xe_exec_queue_get_unless_zero(eq))
585 			list_move_tail(&eq->multi_queue.link, &tmp);
586 
587 	mutex_unlock(&group->list_lock);
588 
589 	/* We cannot stop under list lock without getting inversions */
590 	xe_sched_submission_stop(&primary->guc->sched);
591 	list_for_each_entry(eq, &tmp, multi_queue.link)
592 		xe_sched_submission_stop(&eq->guc->sched);
593 
594 	mutex_lock(&group->list_lock);
595 	list_for_each_entry_safe(eq, next, &tmp, multi_queue.link) {
596 		/*
597 		 * Corner where we got banned while stopping and not on
598 		 * &group->list
599 		 */
600 		if (READ_ONCE(group->banned))
601 			xe_guc_exec_queue_trigger_cleanup(eq);
602 
603 		list_move_tail(&eq->multi_queue.link, &group->list);
604 		xe_exec_queue_put(eq);
605 	}
606 	mutex_unlock(&group->list_lock);
607 }
608 
609 static void xe_guc_exec_queue_group_start(struct xe_exec_queue *q)
610 {
611 	struct xe_exec_queue *primary = xe_exec_queue_multi_queue_primary(q);
612 	struct xe_exec_queue_group *group = q->multi_queue.group;
613 	struct xe_exec_queue *eq;
614 
615 	xe_gt_assert(guc_to_gt(exec_queue_to_guc(q)),
616 		     xe_exec_queue_is_multi_queue(q));
617 
618 	xe_sched_submission_start(&primary->guc->sched);
619 
620 	mutex_lock(&group->list_lock);
621 	group->stopped = false;
622 	list_for_each_entry(eq, &group->list, multi_queue.link)
623 		xe_sched_submission_start(&eq->guc->sched);
624 	mutex_unlock(&group->list_lock);
625 }
626 
627 static void xe_guc_exec_queue_group_trigger_cleanup(struct xe_exec_queue *q)
628 {
629 	struct xe_exec_queue *primary = xe_exec_queue_multi_queue_primary(q);
630 	struct xe_exec_queue_group *group = q->multi_queue.group;
631 	struct xe_exec_queue *eq;
632 
633 	xe_gt_assert(guc_to_gt(exec_queue_to_guc(q)),
634 		     xe_exec_queue_is_multi_queue(q));
635 
636 	/* Group banned, skip timeout check in TDR */
637 	WRITE_ONCE(group->banned, true);
638 	xe_guc_exec_queue_trigger_cleanup(primary);
639 
640 	mutex_lock(&group->list_lock);
641 	list_for_each_entry(eq, &group->list, multi_queue.link)
642 		xe_guc_exec_queue_trigger_cleanup(eq);
643 	mutex_unlock(&group->list_lock);
644 }
645 
646 static void xe_guc_exec_queue_reset_trigger_cleanup(struct xe_exec_queue *q)
647 {
648 	if (xe_exec_queue_is_multi_queue(q)) {
649 		struct xe_exec_queue *primary = xe_exec_queue_multi_queue_primary(q);
650 		struct xe_exec_queue_group *group = q->multi_queue.group;
651 		struct xe_exec_queue *eq;
652 
653 		/* Group banned, skip timeout check in TDR */
654 		WRITE_ONCE(group->banned, true);
655 
656 		set_exec_queue_reset(primary);
657 		if (!exec_queue_banned(primary))
658 			xe_guc_exec_queue_trigger_cleanup(primary);
659 
660 		mutex_lock(&group->list_lock);
661 		list_for_each_entry(eq, &group->list, multi_queue.link) {
662 			set_exec_queue_reset(eq);
663 			if (!exec_queue_banned(eq))
664 				xe_guc_exec_queue_trigger_cleanup(eq);
665 		}
666 		mutex_unlock(&group->list_lock);
667 	} else {
668 		set_exec_queue_reset(q);
669 		if (!exec_queue_banned(q))
670 			xe_guc_exec_queue_trigger_cleanup(q);
671 	}
672 }
673 
674 static void set_exec_queue_group_banned(struct xe_exec_queue *q)
675 {
676 	struct xe_exec_queue *primary = xe_exec_queue_multi_queue_primary(q);
677 	struct xe_exec_queue_group *group = q->multi_queue.group;
678 	struct xe_exec_queue *eq;
679 
680 	/* Ban all queues of the multi-queue group */
681 	xe_gt_assert(guc_to_gt(exec_queue_to_guc(q)),
682 		     xe_exec_queue_is_multi_queue(q));
683 	set_exec_queue_banned(primary);
684 
685 	mutex_lock(&group->list_lock);
686 	list_for_each_entry(eq, &group->list, multi_queue.link)
687 		set_exec_queue_banned(eq);
688 	mutex_unlock(&group->list_lock);
689 }
690 
691 /* Helper for context registration H2G */
692 struct guc_ctxt_registration_info {
693 	u32 flags;
694 	u32 context_idx;
695 	u32 engine_class;
696 	u32 engine_submit_mask;
697 	u32 wq_desc_lo;
698 	u32 wq_desc_hi;
699 	u32 wq_base_lo;
700 	u32 wq_base_hi;
701 	u32 wq_size;
702 	u32 cgp_lo;
703 	u32 cgp_hi;
704 	u32 hwlrca_lo;
705 	u32 hwlrca_hi;
706 };
707 
708 #define parallel_read(xe_, map_, field_) \
709 	xe_map_rd_field(xe_, &map_, 0, struct guc_submit_parallel_scratch, \
710 			field_)
711 #define parallel_write(xe_, map_, field_, val_) \
712 	xe_map_wr_field(xe_, &map_, 0, struct guc_submit_parallel_scratch, \
713 			field_, val_)
714 
715 /**
716  * DOC: Multi Queue Group GuC interface
717  *
718  * The multi queue group coordination between KMD and GuC is through a software
719  * construct called Context Group Page (CGP). The CGP is a KMD managed 4KB page
720  * allocated in the global GTT.
721  *
722  * CGP format:
723  *
724  * +-----------+---------------------------+---------------------------------------------+
725  * | DWORD     | Name                      | Description                                 |
726  * +-----------+---------------------------+---------------------------------------------+
727  * | 0         | Version                   | Bits [15:8]=Major ver, [7:0]=Minor ver      |
728  * +-----------+---------------------------+---------------------------------------------+
729  * | 1..15     | RESERVED                  | MBZ                                         |
730  * +-----------+---------------------------+---------------------------------------------+
731  * | 16        | KMD_QUEUE_UPDATE_MASK_DW0 | KMD queue mask for queues 31..0             |
732  * +-----------+---------------------------+---------------------------------------------+
733  * | 17        | KMD_QUEUE_UPDATE_MASK_DW1 | KMD queue mask for queues 63..32            |
734  * +-----------+---------------------------+---------------------------------------------+
735  * | 18..31    | RESERVED                  | MBZ                                         |
736  * +-----------+---------------------------+---------------------------------------------+
737  * | 32        | Q0CD_DW0                  | Queue 0 context LRC descriptor lower DWORD  |
738  * +-----------+---------------------------+---------------------------------------------+
739  * | 33        | Q0ContextIndex            | Context ID for Queue 0                      |
740  * +-----------+---------------------------+---------------------------------------------+
741  * | 34        | Q1CD_DW0                  | Queue 1 context LRC descriptor lower DWORD  |
742  * +-----------+---------------------------+---------------------------------------------+
743  * | 35        | Q1ContextIndex            | Context ID for Queue 1                      |
744  * +-----------+---------------------------+---------------------------------------------+
745  * | ...       |...                        | ...                                         |
746  * +-----------+---------------------------+---------------------------------------------+
747  * | 158       | Q63CD_DW0                 | Queue 63 context LRC descriptor lower DWORD |
748  * +-----------+---------------------------+---------------------------------------------+
749  * | 159       | Q63ContextIndex           | Context ID for Queue 63                     |
750  * +-----------+---------------------------+---------------------------------------------+
751  * | 160..1024 | RESERVED                  | MBZ                                         |
752  * +-----------+---------------------------+---------------------------------------------+
753  *
754  * While registering Q0 with GuC, CGP is updated with Q0 entry and GuC is notified
755  * through XE_GUC_ACTION_REGISTER_CONTEXT_MULTI_QUEUE H2G message which specifies
756  * the CGP address. When the secondary queues are added to the group, the CGP is
757  * updated with entry for that queue and GuC is notified through the H2G interface
758  * XE_GUC_ACTION_MULTI_QUEUE_CONTEXT_CGP_SYNC. GuC responds to these H2G messages
759  * with a XE_GUC_ACTION_NOTIFY_MULTIQ_CONTEXT_CGP_SYNC_DONE G2H message. GuC also
760  * sends a XE_GUC_ACTION_NOTIFY_MULTI_QUEUE_CGP_CONTEXT_ERROR notification for any
761  * error in the CGP. Only one of these CGP update messages can be outstanding
762  * (waiting for GuC response) at any time. The bits in KMD_QUEUE_UPDATE_MASK_DW*
763  * fields indicate which queue entry is being updated in the CGP.
764  *
765  * The primary queue (Q0) represents the multi queue group context in GuC and
766  * submission on any queue of the group must be through Q0 GuC interface only.
767  *
768  * As it is not required to register secondary queues with GuC, the secondary queue
769  * context ids in the CGP are populated with Q0 context id.
770  */
771 
772 #define CGP_VERSION_MAJOR_SHIFT	8
773 
774 static void xe_guc_exec_queue_group_cgp_update(struct xe_device *xe,
775 					       struct xe_exec_queue *q)
776 {
777 	struct xe_exec_queue_group *group = q->multi_queue.group;
778 	u32 guc_id = group->primary->guc->id;
779 
780 	/* Currently implementing CGP version 1.0 */
781 	xe_map_wr(xe, &group->cgp_bo->vmap, 0, u32,
782 		  1 << CGP_VERSION_MAJOR_SHIFT);
783 
784 	xe_map_wr(xe, &group->cgp_bo->vmap,
785 		  (32 + q->multi_queue.pos * 2) * sizeof(u32),
786 		  u32, lower_32_bits(xe_lrc_descriptor(q->lrc[0])));
787 
788 	xe_map_wr(xe, &group->cgp_bo->vmap,
789 		  (33 + q->multi_queue.pos * 2) * sizeof(u32),
790 		  u32, guc_id);
791 
792 	if (q->multi_queue.pos / 32) {
793 		xe_map_wr(xe, &group->cgp_bo->vmap, 17 * sizeof(u32),
794 			  u32, BIT(q->multi_queue.pos % 32));
795 		xe_map_wr(xe, &group->cgp_bo->vmap, 16 * sizeof(u32), u32, 0);
796 	} else {
797 		xe_map_wr(xe, &group->cgp_bo->vmap, 16 * sizeof(u32),
798 			  u32, BIT(q->multi_queue.pos));
799 		xe_map_wr(xe, &group->cgp_bo->vmap, 17 * sizeof(u32), u32, 0);
800 	}
801 }
802 
803 static void xe_guc_exec_queue_group_cgp_sync(struct xe_guc *guc,
804 					     struct xe_exec_queue *q,
805 					     const u32 *action, u32 len)
806 {
807 	struct xe_exec_queue_group *group = q->multi_queue.group;
808 	struct xe_device *xe = guc_to_xe(guc);
809 	enum xe_multi_queue_priority priority;
810 	long ret;
811 
812 	/*
813 	 * As all queues of a multi queue group use single drm scheduler
814 	 * submit workqueue, CGP synchronization with GuC are serialized.
815 	 * Hence, no locking is required here.
816 	 * Wait for any pending CGP_SYNC_DONE response before updating the
817 	 * CGP page and sending CGP_SYNC message.
818 	 *
819 	 * FIXME: Support VF migration
820 	 */
821 	ret = wait_event_timeout(guc->ct.wq,
822 				 !READ_ONCE(group->sync_pending) ||
823 				 xe_guc_read_stopped(guc), HZ);
824 	if (!ret || xe_guc_read_stopped(guc)) {
825 		/* CGP_SYNC failed. Reset gt, cleanup the group */
826 		xe_gt_warn(guc_to_gt(guc), "Wait for CGP_SYNC_DONE response failed!\n");
827 		set_exec_queue_group_banned(q);
828 		xe_gt_reset_async(q->gt);
829 		xe_guc_exec_queue_group_trigger_cleanup(q);
830 		return;
831 	}
832 
833 	scoped_guard(spinlock, &q->multi_queue.lock)
834 		priority = q->multi_queue.priority;
835 
836 	xe_lrc_set_multi_queue_priority(q->lrc[0], priority);
837 	xe_guc_exec_queue_group_cgp_update(xe, q);
838 
839 	WRITE_ONCE(group->sync_pending, true);
840 	xe_guc_ct_send(&guc->ct, action, len, G2H_LEN_DW_MULTI_QUEUE_CONTEXT, 1);
841 }
842 
843 static void guc_exec_queue_send_cgp_sync(struct xe_exec_queue *q)
844 {
845 #define MAX_MULTI_QUEUE_CGP_SYNC_SIZE	(2)
846 	struct xe_guc *guc = exec_queue_to_guc(q);
847 	struct xe_exec_queue_group *group = q->multi_queue.group;
848 	u32 action[MAX_MULTI_QUEUE_CGP_SYNC_SIZE];
849 	int len = 0;
850 
851 	action[len++] = XE_GUC_ACTION_MULTI_QUEUE_CONTEXT_CGP_SYNC;
852 	action[len++] = group->primary->guc->id;
853 
854 	xe_gt_assert(guc_to_gt(guc), len <= MAX_MULTI_QUEUE_CGP_SYNC_SIZE);
855 #undef MAX_MULTI_QUEUE_CGP_SYNC_SIZE
856 
857 	xe_guc_exec_queue_group_cgp_sync(guc, q, action, len);
858 }
859 
860 static void __register_exec_queue_group(struct xe_exec_queue *q,
861 					struct guc_ctxt_registration_info *info)
862 {
863 	struct xe_guc *guc = exec_queue_to_guc(q);
864 #define MAX_MULTI_QUEUE_REG_SIZE	(8)
865 	u32 action[MAX_MULTI_QUEUE_REG_SIZE];
866 	int len = 0;
867 
868 	action[len++] = XE_GUC_ACTION_REGISTER_CONTEXT_MULTI_QUEUE;
869 	action[len++] = info->flags;
870 	action[len++] = info->context_idx;
871 	action[len++] = info->engine_class;
872 	action[len++] = info->engine_submit_mask;
873 	action[len++] = 0; /* Reserved */
874 	action[len++] = info->cgp_lo;
875 	action[len++] = info->cgp_hi;
876 
877 	xe_gt_assert(guc_to_gt(guc), len <= MAX_MULTI_QUEUE_REG_SIZE);
878 #undef MAX_MULTI_QUEUE_REG_SIZE
879 
880 	/*
881 	 * The above XE_GUC_ACTION_REGISTER_CONTEXT_MULTI_QUEUE do expect a
882 	 * XE_GUC_ACTION_NOTIFY_MULTI_QUEUE_CONTEXT_CGP_SYNC_DONE response
883 	 * from guc.
884 	 */
885 	xe_guc_exec_queue_group_cgp_sync(guc, q, action, len);
886 }
887 
888 static void __register_mlrc_exec_queue(struct xe_guc *guc,
889 				       struct xe_exec_queue *q,
890 				       struct guc_ctxt_registration_info *info)
891 {
892 #define MAX_MLRC_REG_SIZE      (13 + XE_HW_ENGINE_MAX_INSTANCE * 2)
893 	u32 action[MAX_MLRC_REG_SIZE];
894 	int len = 0;
895 	int i;
896 
897 	xe_gt_assert(guc_to_gt(guc), xe_exec_queue_is_parallel(q));
898 
899 	action[len++] = XE_GUC_ACTION_REGISTER_CONTEXT_MULTI_LRC;
900 	action[len++] = info->flags;
901 	action[len++] = info->context_idx;
902 	action[len++] = info->engine_class;
903 	action[len++] = info->engine_submit_mask;
904 	action[len++] = info->wq_desc_lo;
905 	action[len++] = info->wq_desc_hi;
906 	action[len++] = info->wq_base_lo;
907 	action[len++] = info->wq_base_hi;
908 	action[len++] = info->wq_size;
909 	action[len++] = q->width;
910 	action[len++] = info->hwlrca_lo;
911 	action[len++] = info->hwlrca_hi;
912 
913 	for (i = 1; i < q->width; ++i) {
914 		struct xe_lrc *lrc = q->lrc[i];
915 
916 		action[len++] = lower_32_bits(xe_lrc_descriptor(lrc));
917 		action[len++] = upper_32_bits(xe_lrc_descriptor(lrc));
918 	}
919 
920 	/* explicitly checks some fields that we might fixup later */
921 	xe_gt_assert(guc_to_gt(guc), info->wq_desc_lo ==
922 		     action[XE_GUC_REGISTER_CONTEXT_MULTI_LRC_DATA_5_WQ_DESC_ADDR_LOWER]);
923 	xe_gt_assert(guc_to_gt(guc), info->wq_base_lo ==
924 		     action[XE_GUC_REGISTER_CONTEXT_MULTI_LRC_DATA_7_WQ_BUF_BASE_LOWER]);
925 	xe_gt_assert(guc_to_gt(guc), q->width ==
926 		     action[XE_GUC_REGISTER_CONTEXT_MULTI_LRC_DATA_10_NUM_CTXS]);
927 	xe_gt_assert(guc_to_gt(guc), info->hwlrca_lo ==
928 		     action[XE_GUC_REGISTER_CONTEXT_MULTI_LRC_DATA_11_HW_LRC_ADDR]);
929 	xe_gt_assert(guc_to_gt(guc), len <= MAX_MLRC_REG_SIZE);
930 #undef MAX_MLRC_REG_SIZE
931 
932 	xe_guc_ct_send(&guc->ct, action, len, 0, 0);
933 }
934 
935 static void __register_exec_queue(struct xe_guc *guc,
936 				  struct guc_ctxt_registration_info *info)
937 {
938 	u32 action[] = {
939 		XE_GUC_ACTION_REGISTER_CONTEXT,
940 		info->flags,
941 		info->context_idx,
942 		info->engine_class,
943 		info->engine_submit_mask,
944 		info->wq_desc_lo,
945 		info->wq_desc_hi,
946 		info->wq_base_lo,
947 		info->wq_base_hi,
948 		info->wq_size,
949 		info->hwlrca_lo,
950 		info->hwlrca_hi,
951 	};
952 
953 	/* explicitly checks some fields that we might fixup later */
954 	xe_gt_assert(guc_to_gt(guc), info->wq_desc_lo ==
955 		     action[XE_GUC_REGISTER_CONTEXT_DATA_5_WQ_DESC_ADDR_LOWER]);
956 	xe_gt_assert(guc_to_gt(guc), info->wq_base_lo ==
957 		     action[XE_GUC_REGISTER_CONTEXT_DATA_7_WQ_BUF_BASE_LOWER]);
958 	xe_gt_assert(guc_to_gt(guc), info->hwlrca_lo ==
959 		     action[XE_GUC_REGISTER_CONTEXT_DATA_10_HW_LRC_ADDR]);
960 
961 	xe_guc_ct_send(&guc->ct, action, ARRAY_SIZE(action), 0, 0);
962 }
963 
964 static u32 xe_hwe_guc_logical_to_submit_mask(struct xe_hw_engine *hwe, u32 logical_mask)
965 {
966 	struct xe_gt *gt = hwe->gt;
967 
968 	if (xe_gt_is_usm_hwe(gt, hwe)) {
969 		int shift = gt->usm.paging_hwe0->logical_instance;
970 		u32 paging_logical_mask = gt->usm.paging_logical_mask;
971 
972 		xe_gt_assert(gt, (logical_mask & paging_logical_mask) == logical_mask);
973 
974 		/*
975 		 * Remap to GUC_PAGING_CLASS logical instance mask, if
976 		 * applicable.
977 		 */
978 		if (xe_guc_has_paging_engine(&hwe->gt->uc.guc))
979 			return logical_mask >> shift;
980 	}
981 
982 	return logical_mask;
983 }
984 
985 static void register_exec_queue(struct xe_exec_queue *q, int ctx_type)
986 {
987 	struct xe_guc *guc = exec_queue_to_guc(q);
988 	struct xe_device *xe = guc_to_xe(guc);
989 	struct xe_lrc *lrc = q->lrc[0];
990 	struct guc_ctxt_registration_info info;
991 
992 	xe_gt_assert(guc_to_gt(guc), !exec_queue_registered(q));
993 	xe_gt_assert(guc_to_gt(guc), ctx_type < GUC_CONTEXT_COUNT);
994 
995 	memset(&info, 0, sizeof(info));
996 	info.context_idx = q->guc->id;
997 	info.engine_class = xe_hwe_to_guc_class(q->hwe);
998 	info.engine_submit_mask =
999 		xe_hwe_guc_logical_to_submit_mask(q->hwe, q->logical_mask);
1000 	info.hwlrca_lo = lower_32_bits(xe_lrc_descriptor(lrc));
1001 	info.hwlrca_hi = upper_32_bits(xe_lrc_descriptor(lrc));
1002 	info.flags = CONTEXT_REGISTRATION_FLAG_KMD |
1003 		FIELD_PREP(CONTEXT_REGISTRATION_FLAG_TYPE, ctx_type);
1004 
1005 	if (xe_exec_queue_is_multi_queue(q)) {
1006 		struct xe_exec_queue_group *group = q->multi_queue.group;
1007 
1008 		info.cgp_lo = xe_bo_ggtt_addr(group->cgp_bo);
1009 		info.cgp_hi = 0;
1010 	}
1011 
1012 	if (xe_exec_queue_is_parallel(q)) {
1013 		u64 ggtt_addr = xe_lrc_parallel_ggtt_addr(lrc);
1014 		struct iosys_map map = xe_lrc_parallel_map(lrc);
1015 
1016 		info.wq_desc_lo = lower_32_bits(ggtt_addr +
1017 			offsetof(struct guc_submit_parallel_scratch, wq_desc));
1018 		info.wq_desc_hi = upper_32_bits(ggtt_addr +
1019 			offsetof(struct guc_submit_parallel_scratch, wq_desc));
1020 		info.wq_base_lo = lower_32_bits(ggtt_addr +
1021 			offsetof(struct guc_submit_parallel_scratch, wq[0]));
1022 		info.wq_base_hi = upper_32_bits(ggtt_addr +
1023 			offsetof(struct guc_submit_parallel_scratch, wq[0]));
1024 		info.wq_size = WQ_SIZE;
1025 
1026 		q->guc->wqi_head = 0;
1027 		q->guc->wqi_tail = 0;
1028 		xe_map_memset(xe, &map, 0, 0, PARALLEL_SCRATCH_SIZE - WQ_SIZE);
1029 		parallel_write(xe, map, wq_desc.wq_status, WQ_STATUS_ACTIVE);
1030 	}
1031 
1032 	set_exec_queue_registered(q);
1033 	trace_xe_exec_queue_register(q);
1034 	if (xe_exec_queue_is_multi_queue_primary(q))
1035 		__register_exec_queue_group(q, &info);
1036 	else if (xe_exec_queue_is_parallel(q))
1037 		__register_mlrc_exec_queue(guc, q, &info);
1038 	else if (!xe_exec_queue_is_multi_queue_secondary(q))
1039 		__register_exec_queue(guc, &info);
1040 
1041 	if (!xe_exec_queue_is_multi_queue_secondary(q))
1042 		init_policies(guc, q);
1043 
1044 	if (xe_exec_queue_is_multi_queue_secondary(q))
1045 		guc_exec_queue_send_cgp_sync(q);
1046 }
1047 
1048 static u32 wq_space_until_wrap(struct xe_exec_queue *q)
1049 {
1050 	return (WQ_SIZE - q->guc->wqi_tail);
1051 }
1052 
1053 static int wq_wait_for_space(struct xe_exec_queue *q, u32 wqi_size)
1054 {
1055 	struct xe_guc *guc = exec_queue_to_guc(q);
1056 	struct xe_device *xe = guc_to_xe(guc);
1057 	struct iosys_map map = xe_lrc_parallel_map(q->lrc[0]);
1058 	unsigned int sleep_period_ms = 1, sleep_total_ms = 0;
1059 
1060 #define AVAILABLE_SPACE \
1061 	CIRC_SPACE(q->guc->wqi_tail, q->guc->wqi_head, WQ_SIZE)
1062 	if (wqi_size > AVAILABLE_SPACE && !vf_recovery(guc)) {
1063 try_again:
1064 		q->guc->wqi_head = parallel_read(xe, map, wq_desc.head);
1065 		if (wqi_size > AVAILABLE_SPACE && !vf_recovery(guc)) {
1066 			if (sleep_total_ms > 2000) {
1067 				xe_gt_reset_async(q->gt);
1068 				return -ENODEV;
1069 			}
1070 
1071 			sleep_total_ms += xe_sleep_exponential_ms(&sleep_period_ms, 64);
1072 			goto try_again;
1073 		}
1074 	}
1075 #undef AVAILABLE_SPACE
1076 
1077 	return 0;
1078 }
1079 
1080 static int wq_noop_append(struct xe_exec_queue *q)
1081 {
1082 	struct xe_guc *guc = exec_queue_to_guc(q);
1083 	struct xe_device *xe = guc_to_xe(guc);
1084 	struct iosys_map map = xe_lrc_parallel_map(q->lrc[0]);
1085 	u32 len_dw = wq_space_until_wrap(q) / sizeof(u32) - 1;
1086 
1087 	if (wq_wait_for_space(q, wq_space_until_wrap(q)))
1088 		return -ENODEV;
1089 
1090 	xe_gt_assert(guc_to_gt(guc), FIELD_FIT(WQ_LEN_MASK, len_dw));
1091 
1092 	parallel_write(xe, map, wq[q->guc->wqi_tail / sizeof(u32)],
1093 		       FIELD_PREP(WQ_TYPE_MASK, WQ_TYPE_NOOP) |
1094 		       FIELD_PREP(WQ_LEN_MASK, len_dw));
1095 	q->guc->wqi_tail = 0;
1096 
1097 	return 0;
1098 }
1099 
1100 static void wq_item_append(struct xe_exec_queue *q)
1101 {
1102 	struct xe_guc *guc = exec_queue_to_guc(q);
1103 	struct xe_device *xe = guc_to_xe(guc);
1104 	struct iosys_map map = xe_lrc_parallel_map(q->lrc[0]);
1105 #define WQ_HEADER_SIZE	4	/* Includes 1 LRC address too */
1106 	u32 wqi[XE_HW_ENGINE_MAX_INSTANCE + (WQ_HEADER_SIZE - 1)];
1107 	u32 wqi_size = (q->width + (WQ_HEADER_SIZE - 1)) * sizeof(u32);
1108 	u32 len_dw = (wqi_size / sizeof(u32)) - 1;
1109 	int i = 0, j;
1110 
1111 	if (wqi_size > wq_space_until_wrap(q)) {
1112 		if (wq_noop_append(q))
1113 			return;
1114 	}
1115 	if (wq_wait_for_space(q, wqi_size))
1116 		return;
1117 
1118 	wqi[i++] = FIELD_PREP(WQ_TYPE_MASK, WQ_TYPE_MULTI_LRC) |
1119 		FIELD_PREP(WQ_LEN_MASK, len_dw);
1120 	wqi[i++] = xe_lrc_descriptor(q->lrc[0]);
1121 	wqi[i++] = FIELD_PREP(WQ_GUC_ID_MASK, q->guc->id) |
1122 		FIELD_PREP(WQ_RING_TAIL_MASK, q->lrc[0]->ring.tail / sizeof(u64));
1123 	wqi[i++] = 0;
1124 	for (j = 1; j < q->width; ++j) {
1125 		struct xe_lrc *lrc = q->lrc[j];
1126 
1127 		wqi[i++] = lrc->ring.tail / sizeof(u64);
1128 	}
1129 
1130 	xe_gt_assert(guc_to_gt(guc), i == wqi_size / sizeof(u32));
1131 
1132 	iosys_map_incr(&map, offsetof(struct guc_submit_parallel_scratch,
1133 				      wq[q->guc->wqi_tail / sizeof(u32)]));
1134 	xe_map_memcpy_to(xe, &map, 0, wqi, wqi_size);
1135 	q->guc->wqi_tail += wqi_size;
1136 	xe_gt_assert(guc_to_gt(guc), q->guc->wqi_tail <= WQ_SIZE);
1137 
1138 	xe_device_wmb(xe);
1139 
1140 	map = xe_lrc_parallel_map(q->lrc[0]);
1141 	parallel_write(xe, map, wq_desc.tail, q->guc->wqi_tail);
1142 }
1143 
1144 #define RESUME_PENDING	~0x0ull
1145 static void submit_exec_queue(struct xe_exec_queue *q, struct xe_sched_job *job)
1146 {
1147 	struct xe_guc *guc = exec_queue_to_guc(q);
1148 	struct xe_lrc *lrc = q->lrc[0];
1149 	u32 action[3];
1150 	u32 g2h_len = 0;
1151 	u32 num_g2h = 0;
1152 	int len = 0;
1153 	bool extra_submit = false;
1154 
1155 	xe_gt_assert(guc_to_gt(guc), exec_queue_registered(q));
1156 
1157 	if (!job->restore_replay || job->last_replay) {
1158 		if (xe_exec_queue_is_parallel(q))
1159 			wq_item_append(q);
1160 		else
1161 			xe_lrc_set_ring_tail(lrc, lrc->ring.tail);
1162 		job->last_replay = false;
1163 	}
1164 
1165 	if (exec_queue_suspended(q) && !xe_exec_queue_is_parallel(q))
1166 		return;
1167 
1168 	/*
1169 	 * All queues in a multi-queue group will use the primary queue
1170 	 * of the group to interface with GuC. If primay is suspended,
1171 	 * just return. Jobs will get scheduled once primary is resumed.
1172 	 */
1173 	q = xe_exec_queue_multi_queue_primary(q);
1174 	if (exec_queue_suspended(q))
1175 		return;
1176 
1177 	if (!exec_queue_enabled(q)) {
1178 		action[len++] = XE_GUC_ACTION_SCHED_CONTEXT_MODE_SET;
1179 		action[len++] = q->guc->id;
1180 		action[len++] = GUC_CONTEXT_ENABLE;
1181 		g2h_len = G2H_LEN_DW_SCHED_CONTEXT_MODE_SET;
1182 		num_g2h = 1;
1183 		if (xe_exec_queue_is_parallel(q))
1184 			extra_submit = true;
1185 
1186 		q->guc->resume_time = RESUME_PENDING;
1187 		set_exec_queue_pending_enable(q);
1188 		set_exec_queue_enabled(q);
1189 		trace_xe_exec_queue_scheduling_enable(q);
1190 	} else {
1191 		action[len++] = XE_GUC_ACTION_SCHED_CONTEXT;
1192 		action[len++] = q->guc->id;
1193 		trace_xe_exec_queue_submit(q);
1194 	}
1195 
1196 	xe_guc_ct_send(&guc->ct, action, len, g2h_len, num_g2h);
1197 
1198 	if (extra_submit) {
1199 		len = 0;
1200 		action[len++] = XE_GUC_ACTION_SCHED_CONTEXT;
1201 		action[len++] = q->guc->id;
1202 		trace_xe_exec_queue_submit(q);
1203 
1204 		xe_guc_ct_send(&guc->ct, action, len, 0, 0);
1205 	}
1206 }
1207 
1208 static struct dma_fence *
1209 guc_exec_queue_run_job(struct drm_sched_job *drm_job)
1210 {
1211 	struct xe_sched_job *job = to_xe_sched_job(drm_job);
1212 	struct xe_exec_queue *q = job->q;
1213 	struct xe_guc *guc = exec_queue_to_guc(q);
1214 	bool killed_or_banned_or_wedged =
1215 		exec_queue_killed_or_banned_or_wedged(q);
1216 
1217 	xe_gt_assert(guc_to_gt(guc), !(exec_queue_destroyed(q) || exec_queue_pending_disable(q)) ||
1218 		     exec_queue_banned(q) || exec_queue_suspended(q));
1219 
1220 	trace_xe_sched_job_run(job);
1221 
1222 	if (!killed_or_banned_or_wedged && !xe_sched_job_is_error(job)) {
1223 		if (xe_exec_queue_is_multi_queue_secondary(q)) {
1224 			struct xe_exec_queue *primary = xe_exec_queue_multi_queue_primary(q);
1225 
1226 			if (exec_queue_killed_or_banned_or_wedged(primary))
1227 				goto run_job_out;
1228 
1229 			if (!exec_queue_registered(primary))
1230 				register_exec_queue(primary, GUC_CONTEXT_NORMAL);
1231 		}
1232 
1233 		if (!exec_queue_registered(q))
1234 			register_exec_queue(q, GUC_CONTEXT_NORMAL);
1235 		if (!job->restore_replay)
1236 			q->ring_ops->emit_job(job);
1237 		submit_exec_queue(q, job);
1238 		job->restore_replay = false;
1239 	}
1240 
1241 run_job_out:
1242 
1243 	return job->fence;
1244 }
1245 
1246 static void guc_exec_queue_free_job(struct drm_sched_job *drm_job)
1247 {
1248 	struct xe_sched_job *job = to_xe_sched_job(drm_job);
1249 
1250 	trace_xe_sched_job_free(job);
1251 	xe_sched_job_put(job);
1252 }
1253 
1254 int xe_guc_read_stopped(struct xe_guc *guc)
1255 {
1256 	return atomic_read(&guc->submission_state.stopped);
1257 }
1258 
1259 static void handle_multi_queue_secondary_sched_done(struct xe_guc *guc,
1260 						    struct xe_exec_queue *q,
1261 						    u32 runnable_state);
1262 static void handle_deregister_done(struct xe_guc *guc, struct xe_exec_queue *q);
1263 
1264 #define MAKE_SCHED_CONTEXT_ACTION(q, enable_disable)			\
1265 	u32 action[] = {						\
1266 		XE_GUC_ACTION_SCHED_CONTEXT_MODE_SET,			\
1267 		q->guc->id,						\
1268 		GUC_CONTEXT_##enable_disable,				\
1269 	}
1270 
1271 static void disable_scheduling_deregister(struct xe_guc *guc,
1272 					  struct xe_exec_queue *q)
1273 {
1274 	MAKE_SCHED_CONTEXT_ACTION(q, DISABLE);
1275 	int ret;
1276 
1277 	if (!xe_exec_queue_is_multi_queue_secondary(q))
1278 		set_min_preemption_timeout(guc, q);
1279 
1280 	smp_rmb();
1281 	ret = wait_event_timeout(guc->ct.wq,
1282 				 (!exec_queue_pending_enable(q) &&
1283 				  !exec_queue_pending_disable(q)) ||
1284 					 xe_guc_read_stopped(guc) ||
1285 					 vf_recovery(guc),
1286 				 HZ * 5);
1287 	if (!ret && !vf_recovery(guc)) {
1288 		struct xe_gpu_scheduler *sched = &q->guc->sched;
1289 
1290 		xe_gt_warn(q->gt, "Pending enable/disable failed to respond\n");
1291 		xe_sched_submission_start(sched);
1292 		xe_gt_reset_async(q->gt);
1293 		xe_sched_tdr_queue_imm(sched);
1294 		return;
1295 	}
1296 
1297 	clear_exec_queue_enabled(q);
1298 	set_exec_queue_pending_disable(q);
1299 	set_exec_queue_destroyed(q);
1300 	trace_xe_exec_queue_scheduling_disable(q);
1301 
1302 	/*
1303 	 * Reserve space for both G2H here as the 2nd G2H is sent from a G2H
1304 	 * handler and we are not allowed to reserved G2H space in handlers.
1305 	 */
1306 	if (xe_exec_queue_is_multi_queue_secondary(q))
1307 		handle_multi_queue_secondary_sched_done(guc, q, 0);
1308 	else
1309 		xe_guc_ct_send(&guc->ct, action, ARRAY_SIZE(action),
1310 			       G2H_LEN_DW_SCHED_CONTEXT_MODE_SET +
1311 			       G2H_LEN_DW_DEREGISTER_CONTEXT, 2);
1312 }
1313 
1314 /**
1315  * xe_guc_submit_wedge() - Wedge GuC submission
1316  * @guc: the GuC object
1317  *
1318  * Save exec queue's registered with GuC state by taking a ref to each queue.
1319  * Register a DRMM handler to drop refs upon driver unload.
1320  */
1321 void xe_guc_submit_wedge(struct xe_guc *guc)
1322 {
1323 	struct xe_device *xe = guc_to_xe(guc);
1324 	struct xe_exec_queue *q;
1325 	unsigned long index;
1326 
1327 	xe_gt_assert(guc_to_gt(guc), guc_to_xe(guc)->wedged.mode);
1328 
1329 	/*
1330 	 * If device is being wedged even before submission_state is
1331 	 * initialized, there's nothing to do here.
1332 	 */
1333 	if (!guc->submission_state.initialized)
1334 		return;
1335 
1336 	if (xe->wedged.mode == XE_WEDGED_MODE_UPON_ANY_HANG_NO_RESET) {
1337 		mutex_lock(&guc->submission_state.lock);
1338 		xa_for_each(&guc->submission_state.exec_queue_lookup, index, q)
1339 			if (xe_exec_queue_get_unless_zero(q))
1340 				set_exec_queue_wedged(q);
1341 		mutex_unlock(&guc->submission_state.lock);
1342 	} else {
1343 		/* Forcefully kill any remaining exec queues, signal fences */
1344 		guc_submit_reset_prepare(guc);
1345 		xe_guc_submit_stop(guc);
1346 		xe_guc_softreset(guc);
1347 		xe_uc_fw_sanitize(&guc->fw);
1348 		xe_guc_submit_pause_abort(guc);
1349 	}
1350 }
1351 
1352 static bool guc_submit_hint_wedged(struct xe_guc *guc)
1353 {
1354 	struct xe_device *xe = guc_to_xe(guc);
1355 
1356 	if (xe->wedged.mode != XE_WEDGED_MODE_UPON_ANY_HANG_NO_RESET)
1357 		return false;
1358 
1359 	if (xe_device_wedged(xe))
1360 		return true;
1361 
1362 	xe_device_declare_wedged(xe);
1363 
1364 	return true;
1365 }
1366 
1367 #define ADJUST_FIVE_PERCENT(__t)	mul_u64_u32_div(__t, 105, 100)
1368 
1369 static bool check_timeout(struct xe_exec_queue *q, struct xe_sched_job *job)
1370 {
1371 	struct xe_gt *gt = guc_to_gt(exec_queue_to_guc(q));
1372 	u32 ctx_timestamp, ctx_job_timestamp;
1373 	u32 timeout_ms = q->sched_props.job_timeout_ms;
1374 	u32 diff;
1375 	u64 running_time_ms;
1376 
1377 	if (!xe_sched_job_started(job)) {
1378 		xe_gt_warn(gt, "Check job timeout: seqno=%u, lrc_seqno=%u, guc_id=%d, not started",
1379 			   xe_sched_job_seqno(job), xe_sched_job_lrc_seqno(job),
1380 			   q->guc->id);
1381 
1382 		/* GuC never scheduled this job - let the caller trigger a GT reset. */
1383 		return true;
1384 	}
1385 
1386 	ctx_timestamp = lower_32_bits(xe_lrc_timestamp(q->lrc[0]));
1387 	if (ctx_timestamp == job->sample_timestamp) {
1388 		if (IS_SRIOV_VF(gt_to_xe(gt)))
1389 			xe_gt_notice(gt, "Check job timeout: seqno=%u, lrc_seqno=%u, guc_id=%d, timestamp stuck",
1390 				     xe_sched_job_seqno(job),
1391 				     xe_sched_job_lrc_seqno(job), q->guc->id);
1392 		else
1393 			xe_gt_warn(gt, "Check job timeout: seqno=%u, lrc_seqno=%u, guc_id=%d, timestamp stuck",
1394 				   xe_sched_job_seqno(job),
1395 				   xe_sched_job_lrc_seqno(job), q->guc->id);
1396 
1397 		return xe_sched_invalidate_job(job, 0);
1398 	}
1399 
1400 	job->sample_timestamp = ctx_timestamp;
1401 	ctx_job_timestamp = xe_lrc_ctx_job_timestamp(q->lrc[0]);
1402 
1403 	/*
1404 	 * Counter wraps at ~223s at the usual 19.2MHz, be paranoid catch
1405 	 * possible overflows with a high timeout.
1406 	 */
1407 	xe_gt_assert(gt, timeout_ms < 100 * MSEC_PER_SEC);
1408 
1409 	diff = ctx_timestamp - ctx_job_timestamp;
1410 
1411 	/*
1412 	 * Ensure timeout is within 5% to account for an GuC scheduling latency
1413 	 */
1414 	running_time_ms =
1415 		ADJUST_FIVE_PERCENT(xe_gt_clock_interval_to_ms(gt, diff));
1416 
1417 	xe_gt_dbg(gt,
1418 		  "Check job timeout: seqno=%u, lrc_seqno=%u, guc_id=%d, running_time_ms=%llu, timeout_ms=%u, diff=0x%08x",
1419 		  xe_sched_job_seqno(job), xe_sched_job_lrc_seqno(job),
1420 		  q->guc->id, running_time_ms, timeout_ms, diff);
1421 
1422 	return running_time_ms >= timeout_ms;
1423 }
1424 
1425 static void enable_scheduling(struct xe_exec_queue *q)
1426 {
1427 	MAKE_SCHED_CONTEXT_ACTION(q, ENABLE);
1428 	struct xe_guc *guc = exec_queue_to_guc(q);
1429 	int ret;
1430 
1431 	xe_gt_assert(guc_to_gt(guc), !exec_queue_destroyed(q));
1432 	xe_gt_assert(guc_to_gt(guc), exec_queue_registered(q));
1433 	xe_gt_assert(guc_to_gt(guc), !exec_queue_pending_disable(q));
1434 	xe_gt_assert(guc_to_gt(guc), !exec_queue_pending_enable(q));
1435 
1436 	set_exec_queue_pending_enable(q);
1437 	set_exec_queue_enabled(q);
1438 	trace_xe_exec_queue_scheduling_enable(q);
1439 
1440 	if (xe_exec_queue_is_multi_queue_secondary(q))
1441 		handle_multi_queue_secondary_sched_done(guc, q, 1);
1442 	else
1443 		xe_guc_ct_send(&guc->ct, action, ARRAY_SIZE(action),
1444 			       G2H_LEN_DW_SCHED_CONTEXT_MODE_SET, 1);
1445 
1446 	ret = wait_event_timeout(guc->ct.wq,
1447 				 !exec_queue_pending_enable(q) ||
1448 				 xe_guc_read_stopped(guc) ||
1449 				 vf_recovery(guc), HZ * 5);
1450 	if ((!ret && !vf_recovery(guc)) || xe_guc_read_stopped(guc)) {
1451 		xe_gt_warn(guc_to_gt(guc), "Schedule enable failed to respond");
1452 		set_exec_queue_banned(q);
1453 		xe_gt_reset_async(q->gt);
1454 		xe_sched_tdr_queue_imm(&q->guc->sched);
1455 	}
1456 }
1457 
1458 static void disable_scheduling(struct xe_exec_queue *q, bool immediate)
1459 {
1460 	MAKE_SCHED_CONTEXT_ACTION(q, DISABLE);
1461 	struct xe_guc *guc = exec_queue_to_guc(q);
1462 
1463 	xe_gt_assert(guc_to_gt(guc), !exec_queue_destroyed(q));
1464 	xe_gt_assert(guc_to_gt(guc), exec_queue_registered(q));
1465 	xe_gt_assert(guc_to_gt(guc), !exec_queue_pending_disable(q));
1466 
1467 	if (immediate && !xe_exec_queue_is_multi_queue_secondary(q))
1468 		set_min_preemption_timeout(guc, q);
1469 	clear_exec_queue_enabled(q);
1470 	set_exec_queue_pending_disable(q);
1471 	trace_xe_exec_queue_scheduling_disable(q);
1472 
1473 	if (xe_exec_queue_is_multi_queue_secondary(q))
1474 		handle_multi_queue_secondary_sched_done(guc, q, 0);
1475 	else
1476 		xe_guc_ct_send(&guc->ct, action, ARRAY_SIZE(action),
1477 			       G2H_LEN_DW_SCHED_CONTEXT_MODE_SET, 1);
1478 }
1479 
1480 /*
1481  * Recover via GT reset for a kernel queue, or for a GuC scheduling failure (job
1482  * never started) on a queue that was not already killed or banned. An already
1483  * banned queue must stay banned, so its unstarted jobs do not clear the ban or
1484  * trigger a reset.
1485  */
1486 static bool timeout_needs_gt_reset(struct xe_exec_queue *q, struct xe_sched_job *job,
1487 				   bool skip_timeout_check)
1488 {
1489 	if (q->flags & EXEC_QUEUE_FLAG_KERNEL)
1490 		return true;
1491 
1492 	return !skip_timeout_check && !xe_sched_job_started(job);
1493 }
1494 
1495 static enum drm_gpu_sched_stat
1496 guc_exec_queue_timedout_job(struct drm_sched_job *drm_job)
1497 {
1498 	struct xe_sched_job *job = to_xe_sched_job(drm_job);
1499 	struct drm_sched_job *tmp_job;
1500 	struct xe_exec_queue *q = job->q, *primary;
1501 	struct xe_gpu_scheduler *sched = &q->guc->sched;
1502 	struct xe_guc *guc = exec_queue_to_guc(q);
1503 	const char *process_name = "no process";
1504 	struct xe_device *xe = guc_to_xe(guc);
1505 	int err = -ETIME;
1506 	pid_t pid = -1;
1507 	bool wedged = false, wedge_device = false, skip_timeout_check;
1508 
1509 	xe_gt_assert(guc_to_gt(guc), !exec_queue_destroyed(q));
1510 
1511 	primary = xe_exec_queue_multi_queue_primary(q);
1512 
1513 	/*
1514 	 * TDR has fired before free job worker. Common if exec queue
1515 	 * immediately closed after last fence signaled. Add back to pending
1516 	 * list so job can be freed and kick scheduler ensuring free job is not
1517 	 * lost.
1518 	 */
1519 	if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &job->fence->flags) ||
1520 	    vf_recovery(guc))
1521 		return DRM_GPU_SCHED_STAT_NO_HANG;
1522 
1523 	/* Kill the run_job entry point */
1524 	if (xe_exec_queue_is_multi_queue(q))
1525 		xe_guc_exec_queue_group_stop(q);
1526 	else
1527 		xe_sched_submission_stop(sched);
1528 
1529 	/* Must check all state after stopping scheduler */
1530 	skip_timeout_check = exec_queue_reset(q) ||
1531 		exec_queue_killed_or_banned_or_wedged(q);
1532 
1533 	/* Skip timeout check if multi-queue group is banned */
1534 	if (xe_exec_queue_is_multi_queue(q) &&
1535 	    READ_ONCE(q->multi_queue.group->banned))
1536 		skip_timeout_check = true;
1537 
1538 	/* LR jobs can only get here if queue has been killed or hit an error */
1539 	if (xe_exec_queue_is_lr(q))
1540 		xe_gt_assert(guc_to_gt(guc), skip_timeout_check);
1541 
1542 	/*
1543 	 * If devcoredump not captured and GuC capture for the job is not ready
1544 	 * do manual capture first and decide later if we need to use it
1545 	 */
1546 	if (!xe_device_is_in_reset(xe) && !exec_queue_killed(q) && !xe->devcoredump.captured &&
1547 	    !xe_guc_capture_get_matching_and_lock(q)) {
1548 		/* take force wake before engine register manual capture */
1549 		CLASS(xe_force_wake, fw_ref)(gt_to_fw(q->gt), XE_FORCEWAKE_ALL);
1550 		if (!xe_force_wake_ref_has_domain(fw_ref.domains, XE_FORCEWAKE_ALL))
1551 			xe_gt_info(q->gt, "failed to get forcewake for coredump capture\n");
1552 
1553 		xe_engine_snapshot_capture_for_queue(q);
1554 	}
1555 
1556 	/*
1557 	 * Check if job is actually timed out, if so restart job execution and TDR
1558 	 */
1559 	if (!skip_timeout_check && !check_timeout(q, job))
1560 		goto rearm;
1561 
1562 	/*
1563 	 * Killed queues must not newly wedge the device, but preserve an
1564 	 * already-wedged state to avoid warning on teardown timeouts.
1565 	 */
1566 	if (!exec_queue_killed(q))
1567 		wedged = guc_submit_hint_wedged(exec_queue_to_guc(q));
1568 	else
1569 		wedged = xe_device_wedged(xe);
1570 
1571 	set_exec_queue_banned(q);
1572 
1573 	/* Kick job / queue off hardware */
1574 	if (!xe_device_is_in_reset(xe) && !wedged &&
1575 	    (exec_queue_enabled(primary) || exec_queue_pending_disable(primary))) {
1576 		int ret;
1577 
1578 		if (exec_queue_reset(primary))
1579 			err = -EIO;
1580 
1581 		if (xe_uc_fw_is_running(&guc->fw)) {
1582 			/*
1583 			 * Wait for any pending G2H to flush out before
1584 			 * modifying state
1585 			 */
1586 			ret = wait_event_timeout(guc->ct.wq,
1587 						 (!exec_queue_pending_enable(primary) &&
1588 						  !exec_queue_pending_disable(primary)) ||
1589 						 xe_guc_read_stopped(guc) ||
1590 						 vf_recovery(guc), HZ * 5);
1591 			if (vf_recovery(guc))
1592 				goto handle_vf_resume;
1593 			if (!ret || xe_guc_read_stopped(guc))
1594 				goto trigger_reset;
1595 
1596 			disable_scheduling(primary, skip_timeout_check);
1597 		}
1598 
1599 		/*
1600 		 * Must wait for scheduling to be disabled before signalling
1601 		 * any fences, if GT broken the GT reset code should signal us.
1602 		 *
1603 		 * FIXME: Tests can generate a ton of 0x6000 (IOMMU CAT fault
1604 		 * error) messages which can cause the schedule disable to get
1605 		 * lost. If this occurs, trigger a GT reset to recover.
1606 		 */
1607 		smp_rmb();
1608 		ret = wait_event_timeout(guc->ct.wq,
1609 					 !xe_uc_fw_is_running(&guc->fw) ||
1610 					 !exec_queue_pending_disable(primary) ||
1611 					 xe_guc_read_stopped(guc) ||
1612 					 vf_recovery(guc), HZ * 5);
1613 		if (vf_recovery(guc))
1614 			goto handle_vf_resume;
1615 		if (!ret || xe_guc_read_stopped(guc)) {
1616 trigger_reset:
1617 			if (!ret)
1618 				xe_gt_warn(guc_to_gt(guc),
1619 					   "Schedule disable failed to respond, guc_id=%d",
1620 					   primary->guc->id);
1621 			xe_devcoredump(primary, job,
1622 				       "Schedule disable failed to respond, guc_id=%d, ret=%d, guc_read=%d",
1623 				       primary->guc->id, ret, xe_guc_read_stopped(guc));
1624 			xe_gt_reset_async(primary->gt);
1625 			xe_sched_tdr_queue_imm(sched);
1626 			goto rearm;
1627 		}
1628 	}
1629 
1630 	if (q->vm && q->vm->xef) {
1631 		process_name = q->vm->xef->process_name;
1632 		pid = q->vm->xef->pid;
1633 	}
1634 
1635 	if (!exec_queue_killed(q))
1636 		xe_gt_notice(guc_to_gt(guc),
1637 			     "Timedout job: seqno=%u, lrc_seqno=%u, guc_id=%d, flags=0x%lx in %s [%d]",
1638 			     xe_sched_job_seqno(job), xe_sched_job_lrc_seqno(job),
1639 			     q->guc->id, q->flags, process_name, pid);
1640 
1641 	trace_xe_sched_job_timedout(job);
1642 
1643 	/* Do not access device if in reset */
1644 	if (!xe_device_is_in_reset(xe) && !exec_queue_killed(q))
1645 		xe_devcoredump(q, job,
1646 			       "Timedout job - seqno=%u, lrc_seqno=%u, guc_id=%d, flags=0x%lx",
1647 			       xe_sched_job_seqno(job), xe_sched_job_lrc_seqno(job),
1648 			       q->guc->id, q->flags);
1649 
1650 	if (!wedged) {
1651 		if (timeout_needs_gt_reset(q, job, skip_timeout_check)) {
1652 			if (!xe_sched_invalidate_job(job, 2)) {
1653 				clear_exec_queue_banned(q);
1654 				xe_gt_reset_async(q->gt);
1655 				goto rearm;
1656 			}
1657 			if (q->flags & EXEC_QUEUE_FLAG_KERNEL) {
1658 				xe_gt_WARN(q->gt, true, "Kernel-submitted job timed out\n");
1659 				wedge_device = true;
1660 			}
1661 		} else if (q->flags & EXEC_QUEUE_FLAG_VM && !exec_queue_killed(q)) {
1662 			xe_gt_WARN(q->gt, true, "VM job timed out on non-killed execqueue\n");
1663 		}
1664 	}
1665 
1666 	/* Mark all outstanding jobs as bad, thus completing them */
1667 	xe_sched_job_set_error(job, err);
1668 	drm_sched_for_each_pending_job(tmp_job, &sched->base, NULL)
1669 		xe_sched_job_set_error(to_xe_sched_job(tmp_job), -ECANCELED);
1670 
1671 	if (xe_exec_queue_is_multi_queue(q)) {
1672 		xe_guc_exec_queue_group_start(q);
1673 		xe_guc_exec_queue_group_trigger_cleanup(q);
1674 	} else {
1675 		xe_sched_submission_start(sched);
1676 		xe_guc_exec_queue_trigger_cleanup(q);
1677 	}
1678 
1679 	if (wedge_device)
1680 		xe_device_declare_wedged(gt_to_xe(q->gt));
1681 
1682 	/*
1683 	 * We want the job added back to the pending list so it gets freed; this
1684 	 * is what DRM_GPU_SCHED_STAT_NO_HANG does.
1685 	 */
1686 	return DRM_GPU_SCHED_STAT_NO_HANG;
1687 
1688 rearm:
1689 	/*
1690 	 * XXX: Ideally want to adjust timeout based on current execution time
1691 	 * but there is not currently an easy way to do in DRM scheduler. With
1692 	 * some thought, do this in a follow up.
1693 	 */
1694 	if (xe_exec_queue_is_multi_queue(q))
1695 		xe_guc_exec_queue_group_start(q);
1696 	else
1697 		xe_sched_submission_start(sched);
1698 handle_vf_resume:
1699 	return DRM_GPU_SCHED_STAT_NO_HANG;
1700 }
1701 
1702 static void guc_exec_queue_multi_queue_drop_suspend(struct xe_exec_queue *q);
1703 static int guc_exec_queue_suspend_wait_blocking(struct xe_exec_queue *q);
1704 
1705 static void guc_exec_queue_fini(struct xe_exec_queue *q)
1706 {
1707 	struct xe_guc_exec_queue *ge = q->guc;
1708 	struct xe_guc *guc = exec_queue_to_guc(q);
1709 	struct drm_device *drm = &guc_to_xe(guc)->drm;
1710 
1711 	/*
1712 	 * A secondary can leave the group while still preempt suspended (e.g.
1713 	 * xe_vm_remove_compute_exec_queue() forces its preempt fence to signal,
1714 	 * which suspends it). It holds one forwarded suspend reference on the
1715 	 * primary, so drop it and resume the primary if it was the last member
1716 	 * that had it suspended. Primaries forward to nobody, so they don't need
1717 	 * this.
1718 	 *
1719 	 * First make sure the primary's forwarded suspend has completed. If the
1720 	 * secondary was killed/reset before its preempt fence worker ran, that
1721 	 * worker skips suspend_wait() (see preempt_fence_work_func()), leaving
1722 	 * the primary's suspend possibly in flight. drop_suspend() runs under a
1723 	 * spinlock and cannot wait, so drain it here with the uninterruptible
1724 	 * blocking wait; otherwise resuming the primary in drop_suspend() could
1725 	 * trip the !suspend_pending assert.
1726 	 */
1727 	if (xe_exec_queue_is_multi_queue_secondary(q)) {
1728 		if (READ_ONCE(q->guc->suspend_count))
1729 			guc_exec_queue_suspend_wait_blocking(q);
1730 		guc_exec_queue_multi_queue_drop_suspend(q);
1731 	}
1732 
1733 	if (xe_exec_queue_is_multi_queue_secondary(q)) {
1734 		struct xe_exec_queue_group *group = q->multi_queue.group;
1735 
1736 		mutex_lock(&group->list_lock);
1737 		list_del(&q->multi_queue.link);
1738 		mutex_unlock(&group->list_lock);
1739 	}
1740 
1741 	release_guc_id(guc, q);
1742 	xe_sched_entity_fini(&ge->entity);
1743 	xe_sched_fini(&ge->sched);
1744 
1745 	/*
1746 	 * RCU free due sched being exported via DRM scheduler fences
1747 	 * (timeline name).
1748 	 */
1749 	kfree_rcu(ge, rcu);
1750 
1751 	drm_dev_put(drm);
1752 }
1753 
1754 static void guc_exec_queue_do_destroy(struct xe_exec_queue *q)
1755 {
1756 	struct xe_guc_exec_queue *ge = q->guc;
1757 	struct xe_guc *guc = exec_queue_to_guc(q);
1758 	struct xe_device *xe = guc_to_xe(guc);
1759 	struct drm_device *drm = &xe->drm;
1760 
1761 	/*
1762 	 * guc_exec_queue_fini() drops the queue's drm_device ref.
1763 	 * Keep the device alive until the PM-runtime guard unwinds.
1764 	 */
1765 	drm_dev_get(drm);
1766 
1767 	scoped_guard(xe_pm_runtime, xe) {
1768 		trace_xe_exec_queue_destroy(q);
1769 
1770 		/* Confirm no work left behind accessing device structures */
1771 		cancel_delayed_work_sync(&ge->sched.base.work_tdr);
1772 
1773 		xe_exec_queue_fini(q);
1774 	}
1775 
1776 	drm_dev_put(drm);
1777 }
1778 
1779 static void __guc_exec_queue_destroy_async(struct work_struct *w)
1780 {
1781 	struct xe_guc_exec_queue *ge =
1782 		container_of(w, struct xe_guc_exec_queue, destroy_async);
1783 
1784 	guc_exec_queue_do_destroy(ge->q);
1785 }
1786 
1787 static void guc_exec_queue_destroy_async(struct xe_exec_queue *q)
1788 {
1789 	INIT_WORK(&q->guc->destroy_async, __guc_exec_queue_destroy_async);
1790 
1791 	/* We must block on kernel engines so slabs are empty on driver unload */
1792 	if (q->flags & EXEC_QUEUE_FLAG_PERMANENT || exec_queue_wedged(q))
1793 		guc_exec_queue_do_destroy(q);
1794 	else
1795 		xe_destroy_wq_queue(&q->guc->destroy_async);
1796 }
1797 
1798 static void __guc_exec_queue_destroy(struct xe_guc *guc, struct xe_exec_queue *q)
1799 {
1800 	/*
1801 	 * Might be done from within the GPU scheduler, need to do async as we
1802 	 * fini the scheduler when the engine is fini'd, the scheduler can't
1803 	 * complete fini within itself (circular dependency). Async resolves
1804 	 * this we and don't really care when everything is fini'd, just that it
1805 	 * is.
1806 	 */
1807 	guc_exec_queue_destroy_async(q);
1808 }
1809 
1810 static void __guc_exec_queue_process_msg_cleanup(struct xe_sched_msg *msg)
1811 {
1812 	struct xe_exec_queue *q = msg->private_data;
1813 	struct xe_guc *guc = exec_queue_to_guc(q);
1814 
1815 	xe_gt_assert(guc_to_gt(guc), !(q->flags & EXEC_QUEUE_FLAG_PERMANENT));
1816 	trace_xe_exec_queue_cleanup_entity(q);
1817 
1818 	/*
1819 	 * Expected state transitions for cleanup:
1820 	 * - If the exec queue is registered and GuC firmware is running, we must first
1821 	 *   disable scheduling and deregister the queue to ensure proper teardown and
1822 	 *   resource release in the GuC, then destroy the exec queue on driver side.
1823 	 * - If the GuC is already stopped (e.g., during driver unload or GPU reset),
1824 	 *   we cannot expect a response for the deregister request. In this case,
1825 	 *   it is safe to directly destroy the exec queue on driver side, as the GuC
1826 	 *   will not process further requests and all resources must be cleaned up locally.
1827 	 */
1828 	if (exec_queue_registered(q) && xe_uc_fw_is_running(&guc->fw))
1829 		disable_scheduling_deregister(guc, q);
1830 	else
1831 		__guc_exec_queue_destroy(guc, q);
1832 }
1833 
1834 static bool guc_exec_queue_allowed_to_change_state(struct xe_exec_queue *q)
1835 {
1836 	return !exec_queue_killed_or_banned_or_wedged(q) && exec_queue_registered(q);
1837 }
1838 
1839 static void __guc_exec_queue_process_msg_set_sched_props(struct xe_sched_msg *msg)
1840 {
1841 	struct xe_exec_queue *q = msg->private_data;
1842 	struct xe_guc *guc = exec_queue_to_guc(q);
1843 
1844 	if (guc_exec_queue_allowed_to_change_state(q))
1845 		init_policies(guc, q);
1846 	kfree(msg);
1847 }
1848 
1849 static void __suspend_fence_signal(struct xe_exec_queue *q)
1850 {
1851 	struct xe_guc *guc = exec_queue_to_guc(q);
1852 	struct xe_device *xe = guc_to_xe(guc);
1853 
1854 	if (!q->guc->suspend_pending)
1855 		return;
1856 
1857 	WRITE_ONCE(q->guc->suspend_pending, false);
1858 
1859 	/*
1860 	 * We use a GuC shared wait queue for VFs because the VF resfix start
1861 	 * interrupt must be able to wake all instances of suspend_wait. This
1862 	 * prevents the VF migration worker from being starved during
1863 	 * scheduling.
1864 	 */
1865 	if (IS_SRIOV_VF(xe))
1866 		wake_up_all(&guc->ct.wq);
1867 	else
1868 		wake_up(&q->guc->suspend_wait);
1869 }
1870 
1871 static void suspend_fence_signal(struct xe_exec_queue *q)
1872 {
1873 	struct xe_guc *guc = exec_queue_to_guc(q);
1874 
1875 	xe_gt_assert(guc_to_gt(guc), exec_queue_suspended(q) || exec_queue_killed(q) ||
1876 		     xe_guc_read_stopped(guc));
1877 	xe_gt_assert(guc_to_gt(guc), q->guc->suspend_pending);
1878 
1879 	__suspend_fence_signal(q);
1880 }
1881 
1882 static void __guc_exec_queue_process_msg_suspend(struct xe_sched_msg *msg)
1883 {
1884 	struct xe_exec_queue *q = msg->private_data;
1885 	struct xe_guc *guc = exec_queue_to_guc(q);
1886 
1887 	if (guc_exec_queue_allowed_to_change_state(q) && !exec_queue_suspended(q) &&
1888 	    exec_queue_enabled(q)) {
1889 		wait_event(guc->ct.wq, vf_recovery(guc) ||
1890 			   ((q->guc->resume_time != RESUME_PENDING ||
1891 			   xe_guc_read_stopped(guc)) && !exec_queue_pending_disable(q)));
1892 
1893 		if (!xe_guc_read_stopped(guc)) {
1894 			s64 since_resume_ms =
1895 				ktime_ms_delta(ktime_get(),
1896 					       q->guc->resume_time);
1897 			s64 wait_ms = q->vm->preempt.min_run_period_ms -
1898 				since_resume_ms;
1899 
1900 			if (wait_ms > 0 && q->guc->resume_time)
1901 				xe_sleep_relaxed_ms(wait_ms);
1902 
1903 			set_exec_queue_suspended(q);
1904 			disable_scheduling(q, false);
1905 		}
1906 	} else if (q->guc->suspend_pending) {
1907 		set_exec_queue_suspended(q);
1908 		suspend_fence_signal(q);
1909 	}
1910 }
1911 
1912 static void __guc_exec_queue_process_msg_resume(struct xe_sched_msg *msg)
1913 {
1914 	struct xe_exec_queue *q = msg->private_data;
1915 
1916 	if (guc_exec_queue_allowed_to_change_state(q)) {
1917 		clear_exec_queue_suspended(q);
1918 		if (!exec_queue_enabled(q)) {
1919 			q->guc->resume_time = RESUME_PENDING;
1920 			set_exec_queue_pending_resume(q);
1921 			enable_scheduling(q);
1922 		}
1923 	} else {
1924 		clear_exec_queue_suspended(q);
1925 	}
1926 }
1927 
1928 static void __guc_exec_queue_process_msg_set_multi_queue_priority(struct xe_sched_msg *msg)
1929 {
1930 	struct xe_exec_queue *q = msg->private_data;
1931 
1932 	if (guc_exec_queue_allowed_to_change_state(q))
1933 		guc_exec_queue_send_cgp_sync(q);
1934 
1935 	kfree(msg);
1936 }
1937 
1938 #define CLEANUP				1	/* Non-zero values to catch uninitialized msg */
1939 #define SET_SCHED_PROPS			2
1940 #define SUSPEND				3
1941 #define RESUME				4
1942 #define SET_MULTI_QUEUE_PRIORITY	5
1943 #define OPCODE_MASK	0xf
1944 #define MSG_LOCKED	BIT(8)
1945 #define MSG_HEAD	BIT(9)
1946 
1947 static void guc_exec_queue_process_msg(struct xe_sched_msg *msg)
1948 {
1949 	struct xe_device *xe = guc_to_xe(exec_queue_to_guc(msg->private_data));
1950 
1951 	trace_xe_sched_msg_recv(msg);
1952 
1953 	switch (msg->opcode) {
1954 	case CLEANUP:
1955 		__guc_exec_queue_process_msg_cleanup(msg);
1956 		break;
1957 	case SET_SCHED_PROPS:
1958 		__guc_exec_queue_process_msg_set_sched_props(msg);
1959 		break;
1960 	case SUSPEND:
1961 		__guc_exec_queue_process_msg_suspend(msg);
1962 		break;
1963 	case RESUME:
1964 		__guc_exec_queue_process_msg_resume(msg);
1965 		break;
1966 	case SET_MULTI_QUEUE_PRIORITY:
1967 		__guc_exec_queue_process_msg_set_multi_queue_priority(msg);
1968 		break;
1969 	default:
1970 		XE_WARN_ON("Unknown message type");
1971 	}
1972 
1973 	xe_pm_runtime_put(xe);
1974 }
1975 
1976 static const struct drm_sched_backend_ops drm_sched_ops = {
1977 	.run_job = guc_exec_queue_run_job,
1978 	.free_job = guc_exec_queue_free_job,
1979 	.timedout_job = guc_exec_queue_timedout_job,
1980 };
1981 
1982 static const struct xe_sched_backend_ops xe_sched_ops = {
1983 	.process_msg = guc_exec_queue_process_msg,
1984 };
1985 
1986 static int guc_exec_queue_init(struct xe_exec_queue *q)
1987 {
1988 	struct xe_gpu_scheduler *sched;
1989 	struct xe_guc *guc = exec_queue_to_guc(q);
1990 	struct drm_device *drm = &guc_to_xe(guc)->drm;
1991 	struct workqueue_struct *submit_wq = NULL;
1992 	struct xe_guc_exec_queue *ge;
1993 	long timeout;
1994 	int err, i;
1995 
1996 	xe_gt_assert(guc_to_gt(guc), xe_device_uc_enabled(guc_to_xe(guc)));
1997 
1998 	ge = kzalloc_obj(*ge);
1999 	if (!ge)
2000 		return -ENOMEM;
2001 
2002 	drm_dev_get(drm);
2003 
2004 	q->guc = ge;
2005 	ge->q = q;
2006 	init_rcu_head(&ge->rcu);
2007 	init_waitqueue_head(&ge->suspend_wait);
2008 
2009 	for (i = 0; i < MAX_STATIC_MSG_TYPE; ++i)
2010 		INIT_LIST_HEAD(&ge->static_msgs[i].link);
2011 
2012 	timeout = (q->vm && xe_vm_in_lr_mode(q->vm)) ? MAX_SCHEDULE_TIMEOUT :
2013 		  msecs_to_jiffies(q->sched_props.job_timeout_ms);
2014 
2015 	err = alloc_guc_id(guc, q);
2016 	if (err)
2017 		goto err_free;
2018 
2019 	xe_exec_queue_assign_name(q, q->guc->id);
2020 
2021 	strscpy(ge->name, q->name, sizeof(ge->name));
2022 
2023 	/*
2024 	 * Use primary queue's submit_wq for all secondary queues of a
2025 	 * multi queue group. This serialization avoids any locking around
2026 	 * CGP synchronization with GuC.
2027 	 */
2028 	if (xe_exec_queue_is_multi_queue_secondary(q)) {
2029 		struct xe_exec_queue *primary = xe_exec_queue_multi_queue_primary(q);
2030 
2031 		submit_wq = primary->guc->sched.base.submit_wq;
2032 	}
2033 
2034 	err = xe_sched_init(&ge->sched, &drm_sched_ops, &xe_sched_ops,
2035 			    submit_wq, xe_lrc_ring_size() / MAX_JOB_SIZE_BYTES, 64,
2036 			    timeout, guc_to_gt(guc)->ordered_wq, NULL,
2037 			    ge->name, gt_to_xe(q->gt)->drm.dev);
2038 	if (err)
2039 		goto err_release_id;
2040 
2041 	sched = &ge->sched;
2042 	err = xe_sched_entity_init(&ge->entity, sched);
2043 	if (err)
2044 		goto err_sched;
2045 
2046 	q->entity = &ge->entity;
2047 
2048 	mutex_lock(&guc->submission_state.lock);
2049 	if (xe_guc_read_stopped(guc) || vf_recovery(guc))
2050 		xe_sched_stop(sched);
2051 	publish_guc_id(guc, q);
2052 	mutex_unlock(&guc->submission_state.lock);
2053 
2054 	/*
2055 	 * Maintain secondary queues of the multi queue group in a list
2056 	 * for handling dependencies across the queues in the group.
2057 	 */
2058 	if (xe_exec_queue_is_multi_queue_secondary(q)) {
2059 		struct xe_exec_queue_group *group = q->multi_queue.group;
2060 
2061 		INIT_LIST_HEAD(&q->multi_queue.link);
2062 		mutex_lock(&group->list_lock);
2063 		if (group->stopped)
2064 			WRITE_ONCE(q->guc->sched.base.pause_submit, true);
2065 		list_add_tail(&q->multi_queue.link, &group->list);
2066 		mutex_unlock(&group->list_lock);
2067 	}
2068 
2069 	if (xe_exec_queue_is_multi_queue(q))
2070 		trace_xe_exec_queue_create_multi_queue(q);
2071 	else
2072 		trace_xe_exec_queue_create(q);
2073 
2074 	return 0;
2075 
2076 err_sched:
2077 	xe_sched_fini(&ge->sched);
2078 err_release_id:
2079 	release_guc_id(guc, q);
2080 err_free:
2081 	kfree(ge);
2082 	drm_dev_put(drm);
2083 
2084 	return err;
2085 }
2086 
2087 static void guc_exec_queue_kill(struct xe_exec_queue *q)
2088 {
2089 	trace_xe_exec_queue_kill(q);
2090 	set_exec_queue_killed(q);
2091 	__suspend_fence_signal(q);
2092 	xe_guc_exec_queue_trigger_cleanup(q);
2093 }
2094 
2095 static void guc_exec_queue_add_msg(struct xe_exec_queue *q, struct xe_sched_msg *msg,
2096 				   u32 opcode)
2097 {
2098 	xe_pm_runtime_get_noresume(guc_to_xe(exec_queue_to_guc(q)));
2099 
2100 	INIT_LIST_HEAD(&msg->link);
2101 	msg->opcode = opcode & OPCODE_MASK;
2102 	msg->private_data = q;
2103 
2104 	trace_xe_sched_msg_add(msg);
2105 	if (opcode & MSG_HEAD)
2106 		xe_sched_add_msg_head(&q->guc->sched, msg);
2107 	else if (opcode & MSG_LOCKED)
2108 		xe_sched_add_msg_locked(&q->guc->sched, msg);
2109 	else
2110 		xe_sched_add_msg(&q->guc->sched, msg);
2111 }
2112 
2113 static void guc_exec_queue_try_add_msg_head(struct xe_exec_queue *q,
2114 					    struct xe_sched_msg *msg,
2115 					    u32 opcode)
2116 {
2117 	if (!list_empty(&msg->link))
2118 		return;
2119 
2120 	guc_exec_queue_add_msg(q, msg, opcode | MSG_LOCKED | MSG_HEAD);
2121 }
2122 
2123 static bool guc_exec_queue_try_add_msg(struct xe_exec_queue *q,
2124 				       struct xe_sched_msg *msg,
2125 				       u32 opcode)
2126 {
2127 	if (!list_empty(&msg->link))
2128 		return false;
2129 
2130 	guc_exec_queue_add_msg(q, msg, opcode | MSG_LOCKED);
2131 
2132 	return true;
2133 }
2134 
2135 #define STATIC_MSG_CLEANUP	0
2136 #define STATIC_MSG_SUSPEND	1
2137 #define STATIC_MSG_RESUME	2
2138 static void guc_exec_queue_destroy(struct xe_exec_queue *q)
2139 {
2140 	struct xe_sched_msg *msg = q->guc->static_msgs + STATIC_MSG_CLEANUP;
2141 
2142 	if (!(q->flags & EXEC_QUEUE_FLAG_PERMANENT) && !exec_queue_wedged(q))
2143 		guc_exec_queue_add_msg(q, msg, CLEANUP);
2144 	else
2145 		__guc_exec_queue_destroy(exec_queue_to_guc(q), q);
2146 }
2147 
2148 static int guc_exec_queue_set_priority(struct xe_exec_queue *q,
2149 				       enum xe_exec_queue_priority priority)
2150 {
2151 	struct xe_sched_msg *msg;
2152 
2153 	if (q->sched_props.priority == priority ||
2154 	    exec_queue_killed_or_banned_or_wedged(q))
2155 		return 0;
2156 
2157 	msg = kmalloc_obj(*msg);
2158 	if (!msg)
2159 		return -ENOMEM;
2160 
2161 	q->sched_props.priority = priority;
2162 	guc_exec_queue_add_msg(q, msg, SET_SCHED_PROPS);
2163 
2164 	return 0;
2165 }
2166 
2167 static int guc_exec_queue_set_timeslice(struct xe_exec_queue *q, u32 timeslice_us)
2168 {
2169 	struct xe_sched_msg *msg;
2170 
2171 	if (q->sched_props.timeslice_us == timeslice_us ||
2172 	    exec_queue_killed_or_banned_or_wedged(q))
2173 		return 0;
2174 
2175 	msg = kmalloc_obj(*msg);
2176 	if (!msg)
2177 		return -ENOMEM;
2178 
2179 	q->sched_props.timeslice_us = timeslice_us;
2180 	guc_exec_queue_add_msg(q, msg, SET_SCHED_PROPS);
2181 
2182 	return 0;
2183 }
2184 
2185 static int guc_exec_queue_set_preempt_timeout(struct xe_exec_queue *q,
2186 					      u32 preempt_timeout_us)
2187 {
2188 	struct xe_sched_msg *msg;
2189 
2190 	if (q->sched_props.preempt_timeout_us == preempt_timeout_us ||
2191 	    exec_queue_killed_or_banned_or_wedged(q))
2192 		return 0;
2193 
2194 	msg = kmalloc_obj(*msg);
2195 	if (!msg)
2196 		return -ENOMEM;
2197 
2198 	q->sched_props.preempt_timeout_us = preempt_timeout_us;
2199 	guc_exec_queue_add_msg(q, msg, SET_SCHED_PROPS);
2200 
2201 	return 0;
2202 }
2203 
2204 static int guc_exec_queue_set_multi_queue_priority(struct xe_exec_queue *q,
2205 						   enum xe_multi_queue_priority priority)
2206 {
2207 	struct xe_sched_msg *msg;
2208 
2209 	xe_gt_assert(guc_to_gt(exec_queue_to_guc(q)), xe_exec_queue_is_multi_queue(q));
2210 
2211 	if (exec_queue_killed_or_banned_or_wedged(q))
2212 		return 0;
2213 
2214 	msg = kmalloc_obj(*msg);
2215 	if (!msg)
2216 		return -ENOMEM;
2217 
2218 	scoped_guard(spinlock, &q->multi_queue.lock) {
2219 		if (q->multi_queue.priority == priority) {
2220 			kfree(msg);
2221 			return 0;
2222 		}
2223 
2224 		q->multi_queue.priority = priority;
2225 	}
2226 
2227 	guc_exec_queue_add_msg(q, msg, SET_MULTI_QUEUE_PRIORITY);
2228 
2229 	return 0;
2230 }
2231 
2232 /*
2233  * Core suspend: take a suspend reference on @q and, on the first reference,
2234  * disable its GuC context so the GPU is actually preempted. Caller must have
2235  * ensured @q is not killed/banned/wedged. Returns true if this was the first
2236  * suspend reference (the 0->1 transition).
2237  */
2238 static bool __guc_exec_queue_suspend(struct xe_exec_queue *q)
2239 {
2240 	struct xe_guc_exec_queue *ge = q->guc;
2241 	struct xe_gpu_scheduler *sched = &ge->sched;
2242 	struct xe_sched_msg *msg = ge->static_msgs + STATIC_MSG_SUSPEND;
2243 	bool first;
2244 
2245 	xe_sched_msg_lock(sched);
2246 	first = (++ge->suspend_count == 1);
2247 	if (first) {
2248 		bool added = guc_exec_queue_try_add_msg(q, msg, SUSPEND);
2249 
2250 		/* slot must be free at 0->1 */
2251 		xe_gt_assert(guc_to_gt(exec_queue_to_guc(q)), added);
2252 		ge->suspend_pending = true;
2253 	}
2254 	xe_sched_msg_unlock(sched);
2255 
2256 	return first;
2257 }
2258 
2259 /*
2260  * Core resume: drop a suspend reference on @q and, on the last reference,
2261  * re-enable its GuC context. Returns true if this dropped the last suspend
2262  * reference (the 1->0 transition).
2263  */
2264 static bool __guc_exec_queue_resume(struct xe_exec_queue *q)
2265 {
2266 	struct xe_guc_exec_queue *ge = q->guc;
2267 	struct xe_gpu_scheduler *sched = &ge->sched;
2268 	struct xe_sched_msg *msg = ge->static_msgs + STATIC_MSG_RESUME;
2269 	struct xe_guc *guc = exec_queue_to_guc(q);
2270 	bool last;
2271 
2272 	xe_sched_msg_lock(sched);
2273 	xe_gt_assert(guc_to_gt(guc), !ge->suspend_pending);
2274 	xe_gt_assert(guc_to_gt(guc), ge->suspend_count > 0);
2275 	last = (--ge->suspend_count == 0);
2276 	if (last) {
2277 		bool added = guc_exec_queue_try_add_msg(q, msg, RESUME);
2278 
2279 		/* slot must be free at 1->0 */
2280 		xe_gt_assert(guc_to_gt(guc), added);
2281 	}
2282 	xe_sched_msg_unlock(sched);
2283 
2284 	return last;
2285 }
2286 
2287 static int guc_exec_queue_suspend(struct xe_exec_queue *q)
2288 {
2289 	if (exec_queue_killed_or_banned_or_wedged(q))
2290 		return -EINVAL;
2291 
2292 	/*
2293 	 * Non-multi-queue queues and multi-queue primaries suspend themselves
2294 	 * directly: their own msg_lock makes the suspend_count 0->1 transition
2295 	 * and the suspend_pending update atomic, so no group level serialization
2296 	 * is needed.
2297 	 */
2298 	if (!xe_exec_queue_is_multi_queue_secondary(q)) {
2299 		__guc_exec_queue_suspend(q);
2300 		return 0;
2301 	}
2302 
2303 	/*
2304 	 * A secondary's suspend is meaningless once the primary - which owns the
2305 	 * group's GuC context - is gone, so fail it too. This keeps the
2306 	 * secondary's effective state consistent with guc_exec_queue_reset_status(),
2307 	 * which already reports the primary's killed/banned/wedged state for
2308 	 * secondaries. A primary killed *after* this check is still handled at
2309 	 * message-processing time, where the SUSPEND is a no-op for a killed
2310 	 * context; this only covers an already-dead primary.
2311 	 */
2312 	if (exec_queue_killed_or_banned_or_wedged(xe_exec_queue_multi_queue_primary(q)))
2313 		return -EINVAL;
2314 
2315 	/*
2316 	 * A secondary doesn't interface with GuC: suspend it like any other
2317 	 * queue (its own suspend_count drives its internally handled scheduler
2318 	 * state) and, only on its own 0->1 transition, forward the suspend to the
2319 	 * primary so the GPU is actually preempted. Hold @suspend_lock so that
2320 	 * observing the secondary's transition and forwarding it to the primary
2321 	 * happen atomically; this keeps the primary's refcount paired with member
2322 	 * transitions even if the same secondary is suspended and resumed
2323 	 * concurrently across rebind cycles.
2324 	 */
2325 	scoped_guard(spinlock, &q->multi_queue.group->suspend_lock) {
2326 		if (__guc_exec_queue_suspend(q))
2327 			__guc_exec_queue_suspend(xe_exec_queue_multi_queue_primary(q));
2328 	}
2329 
2330 	return 0;
2331 }
2332 
2333 static void guc_exec_queue_suspend_timeout_ban(struct xe_exec_queue *q)
2334 {
2335 	struct xe_guc *guc = exec_queue_to_guc(q);
2336 
2337 	xe_gt_warn(guc_to_gt(guc),
2338 		   "Suspend fence, guc_id=%d, failed to respond, banning queue",
2339 		   q->guc->id);
2340 	/*
2341 	 * The GuC failed to respond to the suspend within the timeout. This is
2342 	 * not recoverable for this context, so ban it and tear it down via
2343 	 * cleanup rather than leave it suspended forever. __suspend_fence_signal
2344 	 * clears suspend_pending and wakes any waiter.
2345 	 *
2346 	 * @q is the primary here; it owns the group's GuC context, so a failure
2347 	 * to suspend it wedges the whole group. Ban and tear down the entire
2348 	 * group in the multi-queue case.
2349 	 */
2350 	if (xe_exec_queue_is_multi_queue(q)) {
2351 		set_exec_queue_group_banned(q);
2352 		__suspend_fence_signal(q);
2353 		xe_guc_exec_queue_group_trigger_cleanup(q);
2354 	} else {
2355 		set_exec_queue_banned(q);
2356 		__suspend_fence_signal(q);
2357 		xe_guc_exec_queue_trigger_cleanup(q);
2358 	}
2359 }
2360 
2361 /*
2362  * Wait for @q's own suspend to complete: suspend_pending cleared, or the queue
2363  * killed / GuC stopped. With @blocking, wait uninterruptibly and do not handle
2364  * VF recovery (for callers that must complete on behalf of a possibly
2365  * cross-process queue); otherwise wait interruptibly.
2366  *
2367  * Returns 0 on completion or -ETIME on timeout. Interruptible waits may also
2368  * return -EAGAIN (VF recovery in progress, retry) or -ERESTARTSYS (aborted by a
2369  * signal; suspend_pending may still be set, so callers must not resume()
2370  * without re-confirming the suspend).
2371  */
2372 static int guc_exec_queue_wait_suspend_done(struct xe_exec_queue *q, bool blocking)
2373 {
2374 	struct xe_guc *guc = exec_queue_to_guc(q);
2375 	struct xe_device *xe = guc_to_xe(guc);
2376 	int ret;
2377 
2378 	/*
2379 	 * Likely don't need to check exec_queue_killed() as we clear
2380 	 * suspend_pending upon kill but to be paranoid but races in which
2381 	 * suspend_pending is set after kill also check kill here.
2382 	 */
2383 #define WAIT_COND \
2384 	(!READ_ONCE(q->guc->suspend_pending) ||	exec_queue_killed(q) || \
2385 	 xe_guc_read_stopped(guc))
2386 
2387 retry:
2388 	if (blocking) {
2389 		if (IS_SRIOV_VF(xe))
2390 			ret = wait_event_timeout(guc->ct.wq, WAIT_COND, HZ * 5);
2391 		else
2392 			ret = wait_event_timeout(q->guc->suspend_wait, WAIT_COND,
2393 						 HZ * 5);
2394 	} else if (IS_SRIOV_VF(xe)) {
2395 		ret = wait_event_interruptible_timeout(guc->ct.wq, WAIT_COND ||
2396 						       vf_recovery(guc), HZ * 5);
2397 	} else {
2398 		ret = wait_event_interruptible_timeout(q->guc->suspend_wait,
2399 						       WAIT_COND, HZ * 5);
2400 	}
2401 
2402 	if (!blocking && vf_recovery(guc) && !xe_device_wedged(xe))
2403 		return -EAGAIN;
2404 
2405 	if (!ret)
2406 		return -ETIME;
2407 	else if (!blocking && IS_SRIOV_VF(xe) && !WAIT_COND)
2408 		/* Corner case on RESFIX DONE where vf_recovery() changes */
2409 		goto retry;
2410 
2411 #undef WAIT_COND
2412 
2413 	return ret < 0 ? ret : 0;
2414 }
2415 
2416 static int guc_exec_queue_suspend_wait_common(struct xe_exec_queue *q, bool blocking)
2417 {
2418 	int ret;
2419 
2420 	/*
2421 	 * A secondary's suspend rides the sched-message worker (short-circuited,
2422 	 * no GuC round-trip) and so is not synchronous with
2423 	 * guc_exec_queue_suspend(): its own suspend_pending may still be set
2424 	 * here. Waiting on the primary alone is not sufficient - if the primary
2425 	 * was already suspended, the forward is a refcount-only transition that
2426 	 * queues no new primary SUSPEND and leaves the primary's suspend_pending
2427 	 * clear, so the primary wait would return immediately while the
2428 	 * secondary's suspend is still in flight, and a later resume() would trip
2429 	 * the secondary's !suspend_pending assert. So first wait for the
2430 	 * secondary's own suspend to complete, then wait on the primary.
2431 	 *
2432 	 * A timeout on either bans the queue (being multi-queue, that tears down
2433 	 * the whole group). A secondary suspend has no real GuC round-trip, so
2434 	 * its timeout is a software scheduler stall rather than a GuC fault, but
2435 	 * banning is still the safe recovery: otherwise the queue is left with
2436 	 * suspend_pending set and a subsequent resume() trips the !suspend_pending
2437 	 * assert.
2438 	 */
2439 	if (xe_exec_queue_is_multi_queue_secondary(q)) {
2440 		ret = guc_exec_queue_wait_suspend_done(q, blocking);
2441 		if (ret == -ETIME)
2442 			guc_exec_queue_suspend_timeout_ban(q);
2443 		if (ret)
2444 			return ret;
2445 	}
2446 
2447 	q = xe_exec_queue_multi_queue_primary(q);
2448 	ret = guc_exec_queue_wait_suspend_done(q, blocking);
2449 	if (ret == -ETIME)
2450 		guc_exec_queue_suspend_timeout_ban(q);
2451 
2452 	return ret;
2453 }
2454 
2455 static int guc_exec_queue_suspend_wait(struct xe_exec_queue *q)
2456 {
2457 	return guc_exec_queue_suspend_wait_common(q, false);
2458 }
2459 
2460 /*
2461  * Uninterruptible variant of guc_exec_queue_suspend_wait() for callers that
2462  * must complete the wait on behalf of a queue possibly owned by a different
2463  * process (e.g. cleanup/undo paths). An interruptible wait could return
2464  * -ERESTARTSYS if the calling task is signalled, leaving that queue suspended
2465  * forever (cross-process DoS). VF recovery is deliberately not handled (no
2466  * -EAGAIN) since a blocking caller cannot retry.
2467  */
2468 static int guc_exec_queue_suspend_wait_blocking(struct xe_exec_queue *q)
2469 {
2470 	return guc_exec_queue_suspend_wait_common(q, true);
2471 }
2472 
2473 static void guc_exec_queue_resume(struct xe_exec_queue *q)
2474 {
2475 	/*
2476 	 * Non-multi-queue queues and multi-queue primaries resume themselves
2477 	 * directly; their own msg_lock is sufficient.
2478 	 */
2479 	if (!xe_exec_queue_is_multi_queue_secondary(q)) {
2480 		__guc_exec_queue_resume(q);
2481 		return;
2482 	}
2483 
2484 	/*
2485 	 * Mirror of guc_exec_queue_suspend(): resume the secondary like any
2486 	 * other queue and, only on its own 1->0 transition, forward the resume
2487 	 * to the primary so the primary's GuC context is re-enabled once the
2488 	 * last member that suspended it resumes. @suspend_lock keeps the
2489 	 * secondary transition and the primary forward atomic.
2490 	 */
2491 	scoped_guard(spinlock, &q->multi_queue.group->suspend_lock) {
2492 		if (__guc_exec_queue_resume(q))
2493 			__guc_exec_queue_resume(xe_exec_queue_multi_queue_primary(q));
2494 	}
2495 }
2496 
2497 /*
2498  * Drop a leaving secondary's forwarded suspend reference on the primary and
2499  * resume the primary if this was the last member that had it suspended.
2500  * See guc_exec_queue_fini().
2501  */
2502 static void guc_exec_queue_multi_queue_drop_suspend(struct xe_exec_queue *q)
2503 {
2504 	scoped_guard(spinlock, &q->multi_queue.group->suspend_lock) {
2505 		struct xe_exec_queue *primary = xe_exec_queue_multi_queue_primary(q);
2506 
2507 		/*
2508 		 * A suspended secondary holds exactly one suspend reference on the
2509 		 * primary (forwarded on its 0->1 transition). If it leaves while
2510 		 * still suspended, release that reference so the primary is not
2511 		 * kept disabled forever.
2512 		 */
2513 		if (!READ_ONCE(q->guc->suspend_count))
2514 			break;
2515 
2516 		if (exec_queue_killed_or_banned_or_wedged(primary))
2517 			break;
2518 
2519 		/*
2520 		 * No suspend_wait() here (and we can't - suspend_lock is a
2521 		 * spinlock). guc_exec_queue_fini() has already drained the
2522 		 * primary's forwarded suspend with the blocking wait, so its
2523 		 * suspend has completed (suspend_pending cleared) by the time we
2524 		 * resume it here. __guc_exec_queue_resume() asserts this.
2525 		 */
2526 		__guc_exec_queue_resume(primary);
2527 	}
2528 }
2529 
2530 static bool guc_exec_queue_reset_status(struct xe_exec_queue *q)
2531 {
2532 	if (xe_exec_queue_is_multi_queue_secondary(q) &&
2533 	    guc_exec_queue_reset_status(xe_exec_queue_multi_queue_primary(q)))
2534 		return true;
2535 
2536 	return exec_queue_reset(q) || exec_queue_killed_or_banned_or_wedged(q);
2537 }
2538 
2539 /*
2540  * All of these functions are an abstraction layer which other parts of Xe can
2541  * use to trap into the GuC backend. All of these functions, aside from init,
2542  * really shouldn't do much other than trap into the DRM scheduler which
2543  * synchronizes these operations.
2544  */
2545 static const struct xe_exec_queue_ops guc_exec_queue_ops = {
2546 	.init = guc_exec_queue_init,
2547 	.kill = guc_exec_queue_kill,
2548 	.fini = guc_exec_queue_fini,
2549 	.destroy = guc_exec_queue_destroy,
2550 	.set_priority = guc_exec_queue_set_priority,
2551 	.set_timeslice = guc_exec_queue_set_timeslice,
2552 	.set_preempt_timeout = guc_exec_queue_set_preempt_timeout,
2553 	.set_multi_queue_priority = guc_exec_queue_set_multi_queue_priority,
2554 	.suspend = guc_exec_queue_suspend,
2555 	.suspend_wait = guc_exec_queue_suspend_wait,
2556 	.suspend_wait_blocking = guc_exec_queue_suspend_wait_blocking,
2557 	.resume = guc_exec_queue_resume,
2558 	.reset_status = guc_exec_queue_reset_status,
2559 };
2560 
2561 static void guc_exec_queue_stop(struct xe_guc *guc, struct xe_exec_queue *q)
2562 {
2563 	struct xe_gpu_scheduler *sched = &q->guc->sched;
2564 	bool do_destroy = false;
2565 
2566 	/* Stop scheduling + flush any DRM scheduler operations */
2567 	xe_sched_submission_stop(sched);
2568 
2569 	/* Clean up lost G2H + reset engine state */
2570 	if (exec_queue_registered(q)) {
2571 		if (exec_queue_destroyed(q))
2572 			do_destroy = true;
2573 	}
2574 	if (q->guc->suspend_pending) {
2575 		set_exec_queue_suspended(q);
2576 		suspend_fence_signal(q);
2577 	}
2578 	atomic_and(EXEC_QUEUE_STATE_WEDGED | EXEC_QUEUE_STATE_BANNED |
2579 		   EXEC_QUEUE_STATE_KILLED | EXEC_QUEUE_STATE_DESTROYED |
2580 		   EXEC_QUEUE_STATE_SUSPENDED,
2581 		   &q->guc->state);
2582 	q->guc->resume_time = 0;
2583 	trace_xe_exec_queue_stop(q);
2584 
2585 	/*
2586 	 * Ban any engine (aside from kernel and engines used for VM ops) with a
2587 	 * started but not complete job or if a job has gone through a GT reset
2588 	 * more than twice.
2589 	 */
2590 	if (!(q->flags & (EXEC_QUEUE_FLAG_KERNEL | EXEC_QUEUE_FLAG_VM))) {
2591 		struct xe_sched_job *job = xe_sched_first_pending_job(sched);
2592 		bool ban = false;
2593 
2594 		if (job) {
2595 			if ((xe_sched_job_started(job) &&
2596 			    !xe_sched_job_completed(job)) ||
2597 			    xe_sched_invalidate_job(job, 2)) {
2598 				trace_xe_sched_job_ban(job);
2599 				ban = true;
2600 			}
2601 		}
2602 
2603 		if (ban) {
2604 			set_exec_queue_banned(q);
2605 			xe_guc_exec_queue_trigger_cleanup(q);
2606 		}
2607 	}
2608 
2609 	if (do_destroy)
2610 		__guc_exec_queue_destroy(guc, q);
2611 }
2612 
2613 static int guc_submit_reset_prepare(struct xe_guc *guc)
2614 {
2615 	int ret;
2616 
2617 	/*
2618 	 * Using an atomic here rather than submission_state.lock as this
2619 	 * function can be called while holding the CT lock (engine reset
2620 	 * failure). submission_state.lock needs the CT lock to resubmit jobs.
2621 	 * Atomic is not ideal, but it works to prevent against concurrent reset
2622 	 * and releasing any TDRs waiting on guc->submission_state.stopped.
2623 	 */
2624 	ret = atomic_fetch_or(1, &guc->submission_state.stopped);
2625 	smp_wmb();
2626 	wake_up_all(&guc->ct.wq);
2627 
2628 	return ret;
2629 }
2630 
2631 int xe_guc_submit_reset_prepare(struct xe_guc *guc)
2632 {
2633 	if (xe_gt_WARN_ON(guc_to_gt(guc), vf_recovery(guc)))
2634 		return 0;
2635 
2636 	if (!guc->submission_state.initialized)
2637 		return 0;
2638 
2639 	return guc_submit_reset_prepare(guc);
2640 }
2641 
2642 void xe_guc_submit_reset_wait(struct xe_guc *guc)
2643 {
2644 	wait_event(guc->ct.wq, xe_device_wedged(guc_to_xe(guc)) ||
2645 		   !xe_guc_read_stopped(guc));
2646 }
2647 
2648 void xe_guc_submit_stop(struct xe_guc *guc)
2649 {
2650 	struct xe_exec_queue *q;
2651 	unsigned long index;
2652 
2653 	xe_gt_assert(guc_to_gt(guc), xe_guc_read_stopped(guc) == 1);
2654 
2655 	mutex_lock(&guc->submission_state.lock);
2656 
2657 	xa_for_each(&guc->submission_state.exec_queue_lookup, index, q) {
2658 		/* Prevent redundant attempts to stop parallel queues */
2659 		if (q->guc->id != index)
2660 			continue;
2661 
2662 		guc_exec_queue_stop(guc, q);
2663 	}
2664 
2665 	mutex_unlock(&guc->submission_state.lock);
2666 
2667 	/*
2668 	 * No one can enter the backend at this point, aside from new engine
2669 	 * creation which is protected by guc->submission_state.lock.
2670 	 */
2671 
2672 }
2673 
2674 static void guc_exec_queue_revert_pending_state_change(struct xe_guc *guc,
2675 						       struct xe_exec_queue *q)
2676 {
2677 	bool pending_enable, pending_disable, pending_resume;
2678 
2679 	pending_enable = exec_queue_pending_enable(q);
2680 	pending_resume = exec_queue_pending_resume(q);
2681 
2682 	if (pending_enable && pending_resume) {
2683 		q->guc->needs_resume = true;
2684 		xe_gt_dbg(guc_to_gt(guc), "Replay RESUME - guc_id=%d",
2685 			  q->guc->id);
2686 	}
2687 
2688 	if (pending_enable && !pending_resume) {
2689 		clear_exec_queue_registered(q);
2690 		xe_gt_dbg(guc_to_gt(guc), "Replay REGISTER - guc_id=%d",
2691 			  q->guc->id);
2692 	}
2693 
2694 	if (pending_enable) {
2695 		clear_exec_queue_enabled(q);
2696 		clear_exec_queue_pending_resume(q);
2697 		clear_exec_queue_pending_enable(q);
2698 		xe_gt_dbg(guc_to_gt(guc), "Replay ENABLE - guc_id=%d",
2699 			  q->guc->id);
2700 	}
2701 
2702 	if (exec_queue_destroyed(q) && exec_queue_registered(q)) {
2703 		clear_exec_queue_destroyed(q);
2704 		q->guc->needs_cleanup = true;
2705 		xe_gt_dbg(guc_to_gt(guc), "Replay CLEANUP - guc_id=%d",
2706 			  q->guc->id);
2707 	}
2708 
2709 	pending_disable = exec_queue_pending_disable(q);
2710 
2711 	if (pending_disable && exec_queue_suspended(q)) {
2712 		clear_exec_queue_suspended(q);
2713 		q->guc->needs_suspend = true;
2714 		xe_gt_dbg(guc_to_gt(guc), "Replay SUSPEND - guc_id=%d",
2715 			  q->guc->id);
2716 	}
2717 
2718 	if (pending_disable) {
2719 		if (!pending_enable)
2720 			set_exec_queue_enabled(q);
2721 		clear_exec_queue_pending_disable(q);
2722 		xe_gt_dbg(guc_to_gt(guc), "Replay DISABLE - guc_id=%d",
2723 			  q->guc->id);
2724 	}
2725 
2726 	q->guc->resume_time = 0;
2727 }
2728 
2729 static void lrc_parallel_clear(struct xe_lrc *lrc)
2730 {
2731 	struct xe_device *xe = gt_to_xe(lrc->gt);
2732 	struct iosys_map map = xe_lrc_parallel_map(lrc);
2733 	int i;
2734 
2735 	for (i = 0; i < WQ_SIZE / sizeof(u32); ++i)
2736 		parallel_write(xe, map, wq[i],
2737 			       FIELD_PREP(WQ_TYPE_MASK, WQ_TYPE_NOOP) |
2738 			       FIELD_PREP(WQ_LEN_MASK, 0));
2739 }
2740 
2741 /*
2742  * This function is quite complex but only real way to ensure no state is lost
2743  * during VF resume flows. The function scans the queue state, make adjustments
2744  * as needed, and queues jobs / messages which replayed upon unpause.
2745  */
2746 static void guc_exec_queue_pause(struct xe_guc *guc, struct xe_exec_queue *q)
2747 {
2748 	struct xe_gpu_scheduler *sched = &q->guc->sched;
2749 	struct xe_sched_job *job;
2750 	int i;
2751 
2752 	lockdep_assert_held(&guc->submission_state.lock);
2753 
2754 	/* Stop scheduling + flush any DRM scheduler operations */
2755 	xe_sched_submission_stop(sched);
2756 	cancel_delayed_work_sync(&sched->base.work_tdr);
2757 
2758 	guc_exec_queue_revert_pending_state_change(guc, q);
2759 
2760 	if (xe_exec_queue_is_parallel(q)) {
2761 		/* Pairs with WRITE_ONCE in __xe_exec_queue_init  */
2762 		struct xe_lrc *lrc = READ_ONCE(q->lrc[0]);
2763 
2764 		/*
2765 		 * NOP existing WQ commands that may contain stale GGTT
2766 		 * addresses. These will be replayed upon unpause. The hardware
2767 		 * seems to get confused if the WQ head/tail pointers are
2768 		 * adjusted.
2769 		 */
2770 		if (lrc)
2771 			lrc_parallel_clear(lrc);
2772 	}
2773 
2774 	job = xe_sched_first_pending_job(sched);
2775 	if (job) {
2776 		job->restore_replay = true;
2777 
2778 		/*
2779 		 * Adjust software tail so jobs submitted overwrite previous
2780 		 * position in ring buffer with new GGTT addresses.
2781 		 */
2782 		for (i = 0; i < q->width; ++i)
2783 			q->lrc[i]->ring.tail = job->ptrs[i].head;
2784 	}
2785 }
2786 
2787 /**
2788  * xe_guc_submit_pause - Stop further runs of submission tasks on given GuC.
2789  * @guc: the &xe_guc struct instance whose scheduler is to be disabled
2790  */
2791 void xe_guc_submit_pause(struct xe_guc *guc)
2792 {
2793 	struct xe_exec_queue *q;
2794 	unsigned long index;
2795 
2796 	mutex_lock(&guc->submission_state.lock);
2797 	xa_for_each(&guc->submission_state.exec_queue_lookup, index, q)
2798 		xe_sched_submission_stop(&q->guc->sched);
2799 	mutex_unlock(&guc->submission_state.lock);
2800 }
2801 
2802 /**
2803  * xe_guc_submit_pause_vf - Stop further runs of submission tasks for VF.
2804  * @guc: the &xe_guc struct instance whose scheduler is to be disabled
2805  */
2806 void xe_guc_submit_pause_vf(struct xe_guc *guc)
2807 {
2808 	struct xe_exec_queue *q;
2809 	unsigned long index;
2810 
2811 	xe_gt_assert(guc_to_gt(guc), IS_SRIOV_VF(guc_to_xe(guc)));
2812 	xe_gt_assert(guc_to_gt(guc), vf_recovery(guc));
2813 
2814 	mutex_lock(&guc->submission_state.lock);
2815 	xa_for_each(&guc->submission_state.exec_queue_lookup, index, q) {
2816 		/* Prevent redundant attempts to stop parallel queues */
2817 		if (q->guc->id != index)
2818 			continue;
2819 
2820 		guc_exec_queue_pause(guc, q);
2821 	}
2822 	mutex_unlock(&guc->submission_state.lock);
2823 }
2824 
2825 static void guc_exec_queue_start(struct xe_exec_queue *q)
2826 {
2827 	struct xe_gpu_scheduler *sched = &q->guc->sched;
2828 
2829 	if (!exec_queue_killed_or_banned_or_wedged(q)) {
2830 		struct xe_sched_job *job = xe_sched_first_pending_job(sched);
2831 		int i;
2832 
2833 		trace_xe_exec_queue_resubmit(q);
2834 		if (job) {
2835 			for (i = 0; i < q->width; ++i) {
2836 				/*
2837 				 * The GuC context is unregistered at this point
2838 				 * time, adjusting software ring tail ensures
2839 				 * jobs are rewritten in original placement,
2840 				 * adjusting LRC tail ensures the newly loaded
2841 				 * GuC / contexts only view the LRC tail
2842 				 * increasing as jobs are written out.
2843 				 */
2844 				q->lrc[i]->ring.tail = job->ptrs[i].head;
2845 				xe_lrc_set_ring_tail(q->lrc[i],
2846 						     xe_lrc_ring_head(q->lrc[i]));
2847 			}
2848 		}
2849 		xe_sched_resubmit_jobs(sched);
2850 	}
2851 
2852 	xe_sched_submission_start(sched);
2853 	xe_sched_submission_resume_tdr(sched);
2854 }
2855 
2856 int xe_guc_submit_start(struct xe_guc *guc)
2857 {
2858 	struct xe_exec_queue *q;
2859 	unsigned long index;
2860 
2861 	xe_gt_assert(guc_to_gt(guc), xe_guc_read_stopped(guc) == 1);
2862 
2863 	mutex_lock(&guc->submission_state.lock);
2864 	atomic_dec(&guc->submission_state.stopped);
2865 	xa_for_each(&guc->submission_state.exec_queue_lookup, index, q) {
2866 		/* Prevent redundant attempts to start parallel queues */
2867 		if (q->guc->id != index)
2868 			continue;
2869 
2870 		guc_exec_queue_start(q);
2871 	}
2872 	mutex_unlock(&guc->submission_state.lock);
2873 
2874 	wake_up_all(&guc->ct.wq);
2875 
2876 	return 0;
2877 }
2878 
2879 static void guc_exec_queue_unpause_prepare(struct xe_guc *guc,
2880 					   struct xe_exec_queue *q)
2881 {
2882 	struct xe_gpu_scheduler *sched = &q->guc->sched;
2883 	struct xe_sched_job *job = NULL;
2884 	struct drm_sched_job *s_job;
2885 	bool restore_replay = false;
2886 
2887 	drm_sched_for_each_pending_job(s_job, &sched->base, NULL) {
2888 		job = to_xe_sched_job(s_job);
2889 		restore_replay |= job->restore_replay;
2890 		if (restore_replay) {
2891 			xe_gt_dbg(guc_to_gt(guc), "Replay JOB - guc_id=%d, seqno=%d",
2892 				  q->guc->id, xe_sched_job_seqno(job));
2893 
2894 			q->ring_ops->emit_job(job);
2895 			job->restore_replay = true;
2896 		}
2897 	}
2898 
2899 	if (job)
2900 		job->last_replay = true;
2901 }
2902 
2903 /**
2904  * xe_guc_submit_unpause_prepare_vf - Prepare unpause submission tasks for VF.
2905  * @guc: the &xe_guc struct instance whose scheduler is to be prepared for unpause
2906  */
2907 void xe_guc_submit_unpause_prepare_vf(struct xe_guc *guc)
2908 {
2909 	struct xe_exec_queue *q;
2910 	unsigned long index;
2911 
2912 	xe_gt_assert(guc_to_gt(guc), IS_SRIOV_VF(guc_to_xe(guc)));
2913 	xe_gt_assert(guc_to_gt(guc), vf_recovery(guc));
2914 
2915 	mutex_lock(&guc->submission_state.lock);
2916 	xa_for_each(&guc->submission_state.exec_queue_lookup, index, q) {
2917 		/* Prevent redundant attempts to stop parallel queues */
2918 		if (q->guc->id != index)
2919 			continue;
2920 
2921 		guc_exec_queue_unpause_prepare(guc, q);
2922 	}
2923 	mutex_unlock(&guc->submission_state.lock);
2924 }
2925 
2926 static void guc_exec_queue_replay_pending_state_change(struct xe_exec_queue *q)
2927 {
2928 	struct xe_gpu_scheduler *sched = &q->guc->sched;
2929 	struct xe_sched_msg *msg;
2930 
2931 	if (q->guc->needs_cleanup) {
2932 		msg = q->guc->static_msgs + STATIC_MSG_CLEANUP;
2933 
2934 		guc_exec_queue_add_msg(q, msg, CLEANUP);
2935 		q->guc->needs_cleanup = false;
2936 	}
2937 
2938 	if (q->guc->needs_suspend) {
2939 		msg = q->guc->static_msgs + STATIC_MSG_SUSPEND;
2940 
2941 		xe_sched_msg_lock(sched);
2942 		guc_exec_queue_try_add_msg_head(q, msg, SUSPEND);
2943 		xe_sched_msg_unlock(sched);
2944 
2945 		q->guc->needs_suspend = false;
2946 	}
2947 
2948 	/*
2949 	 * The resume must be in the message queue before the suspend as it is
2950 	 * not possible for a resume to be issued if a suspend pending is, but
2951 	 * the inverse is possible.
2952 	 */
2953 	if (q->guc->needs_resume) {
2954 		msg = q->guc->static_msgs + STATIC_MSG_RESUME;
2955 
2956 		xe_sched_msg_lock(sched);
2957 		guc_exec_queue_try_add_msg_head(q, msg, RESUME);
2958 		xe_sched_msg_unlock(sched);
2959 
2960 		q->guc->needs_resume = false;
2961 	}
2962 }
2963 
2964 static void guc_exec_queue_unpause(struct xe_guc *guc, struct xe_exec_queue *q)
2965 {
2966 	struct xe_gpu_scheduler *sched = &q->guc->sched;
2967 	bool needs_tdr = exec_queue_killed_or_banned_or_wedged(q);
2968 
2969 	lockdep_assert_held(&guc->submission_state.lock);
2970 
2971 	xe_sched_resubmit_jobs(sched);
2972 	guc_exec_queue_replay_pending_state_change(q);
2973 	xe_sched_submission_start(sched);
2974 	if (needs_tdr)
2975 		xe_guc_exec_queue_trigger_cleanup(q);
2976 	xe_sched_submission_resume_tdr(sched);
2977 }
2978 
2979 /**
2980  * xe_guc_submit_unpause - Allow further runs of submission tasks on given GuC.
2981  * @guc: the &xe_guc struct instance whose scheduler is to be enabled
2982  */
2983 void xe_guc_submit_unpause(struct xe_guc *guc)
2984 {
2985 	struct xe_exec_queue *q;
2986 	unsigned long index;
2987 
2988 	mutex_lock(&guc->submission_state.lock);
2989 	xa_for_each(&guc->submission_state.exec_queue_lookup, index, q)
2990 		xe_sched_submission_start(&q->guc->sched);
2991 	mutex_unlock(&guc->submission_state.lock);
2992 }
2993 
2994 /**
2995  * xe_guc_submit_unpause_vf - Allow further runs of submission tasks for VF.
2996  * @guc: the &xe_guc struct instance whose scheduler is to be enabled
2997  */
2998 void xe_guc_submit_unpause_vf(struct xe_guc *guc)
2999 {
3000 	struct xe_exec_queue *q;
3001 	unsigned long index;
3002 
3003 	xe_gt_assert(guc_to_gt(guc), IS_SRIOV_VF(guc_to_xe(guc)));
3004 
3005 	mutex_lock(&guc->submission_state.lock);
3006 	xa_for_each(&guc->submission_state.exec_queue_lookup, index, q) {
3007 		/*
3008 		 * Prevent redundant attempts to stop parallel queues, or queues
3009 		 * created after resfix done.
3010 		 */
3011 		if (q->guc->id != index ||
3012 		    !drm_sched_is_stopped(&q->guc->sched.base))
3013 			continue;
3014 
3015 		guc_exec_queue_unpause(guc, q);
3016 	}
3017 	mutex_unlock(&guc->submission_state.lock);
3018 }
3019 
3020 /**
3021  * xe_guc_submit_pause_abort - Abort all paused submission task on given GuC.
3022  * @guc: the &xe_guc struct instance whose scheduler is to be aborted
3023  */
3024 void xe_guc_submit_pause_abort(struct xe_guc *guc)
3025 {
3026 	struct xe_exec_queue *q;
3027 	unsigned long index;
3028 
3029 	mutex_lock(&guc->submission_state.lock);
3030 	xa_for_each(&guc->submission_state.exec_queue_lookup, index, q) {
3031 		struct xe_gpu_scheduler *sched = &q->guc->sched;
3032 
3033 		/* Prevent redundant attempts to stop parallel queues */
3034 		if (q->guc->id != index)
3035 			continue;
3036 
3037 		xe_sched_submission_start(sched);
3038 		guc_exec_queue_kill(q);
3039 	}
3040 	mutex_unlock(&guc->submission_state.lock);
3041 }
3042 
3043 static struct xe_exec_queue *
3044 g2h_exec_queue_lookup(struct xe_guc *guc, u32 guc_id)
3045 {
3046 	struct xe_gt *gt = guc_to_gt(guc);
3047 	struct xe_exec_queue *q;
3048 
3049 	if (unlikely(guc_id >= GUC_ID_MAX)) {
3050 		xe_gt_err(gt, "Invalid guc_id %u\n", guc_id);
3051 		return NULL;
3052 	}
3053 
3054 	q = xa_load(&guc->submission_state.exec_queue_lookup, guc_id);
3055 	if (unlikely(!q)) {
3056 		xe_gt_err(gt, "No exec queue found for guc_id %u\n", guc_id);
3057 		return NULL;
3058 	}
3059 
3060 	xe_gt_assert(guc_to_gt(guc), guc_id >= q->guc->id);
3061 	xe_gt_assert(guc_to_gt(guc), guc_id < (q->guc->id + q->width));
3062 
3063 	return q;
3064 }
3065 
3066 static void deregister_exec_queue(struct xe_guc *guc, struct xe_exec_queue *q)
3067 {
3068 	u32 action[] = {
3069 		XE_GUC_ACTION_DEREGISTER_CONTEXT,
3070 		q->guc->id,
3071 	};
3072 
3073 	xe_gt_assert(guc_to_gt(guc), exec_queue_destroyed(q));
3074 	xe_gt_assert(guc_to_gt(guc), exec_queue_registered(q));
3075 	xe_gt_assert(guc_to_gt(guc), !exec_queue_pending_disable(q));
3076 	xe_gt_assert(guc_to_gt(guc), !exec_queue_pending_enable(q));
3077 
3078 	trace_xe_exec_queue_deregister(q);
3079 
3080 	if (xe_exec_queue_is_multi_queue_secondary(q))
3081 		handle_deregister_done(guc, q);
3082 	else
3083 		xe_guc_ct_send_g2h_handler(&guc->ct, action,
3084 					   ARRAY_SIZE(action));
3085 }
3086 
3087 static void handle_sched_done(struct xe_guc *guc, struct xe_exec_queue *q,
3088 			      u32 runnable_state)
3089 {
3090 	trace_xe_exec_queue_scheduling_done(q);
3091 
3092 	if (runnable_state == 1) {
3093 		xe_gt_assert(guc_to_gt(guc), exec_queue_pending_enable(q));
3094 
3095 		q->guc->resume_time = ktime_get();
3096 		clear_exec_queue_pending_resume(q);
3097 		clear_exec_queue_pending_enable(q);
3098 		smp_wmb();
3099 		wake_up_all(&guc->ct.wq);
3100 	} else {
3101 		xe_gt_assert(guc_to_gt(guc), runnable_state == 0);
3102 		xe_gt_assert(guc_to_gt(guc), exec_queue_pending_disable(q));
3103 
3104 		if (q->guc->suspend_pending) {
3105 			clear_exec_queue_pending_disable(q);
3106 			suspend_fence_signal(q);
3107 		} else {
3108 			if (exec_queue_banned(q)) {
3109 				smp_wmb();
3110 				wake_up_all(&guc->ct.wq);
3111 			}
3112 			if (exec_queue_destroyed(q)) {
3113 				/*
3114 				 * Make sure to clear the pending_disable only
3115 				 * after sampling the destroyed state. We want
3116 				 * to ensure we don't trigger the unregister too
3117 				 * early with something intending to only
3118 				 * disable scheduling. The caller doing the
3119 				 * destroy must wait for an ongoing
3120 				 * pending_disable before marking as destroyed.
3121 				 */
3122 				clear_exec_queue_pending_disable(q);
3123 				deregister_exec_queue(guc, q);
3124 			} else {
3125 				clear_exec_queue_pending_disable(q);
3126 			}
3127 		}
3128 	}
3129 }
3130 
3131 static void handle_multi_queue_secondary_sched_done(struct xe_guc *guc,
3132 						    struct xe_exec_queue *q,
3133 						    u32 runnable_state)
3134 {
3135 	/* Take CT lock here as handle_sched_done() do send a h2g message */
3136 	mutex_lock(&guc->ct.lock);
3137 	handle_sched_done(guc, q, runnable_state);
3138 	mutex_unlock(&guc->ct.lock);
3139 }
3140 
3141 int xe_guc_sched_done_handler(struct xe_guc *guc, u32 *msg, u32 len)
3142 {
3143 	struct xe_exec_queue *q;
3144 	u32 guc_id, runnable_state;
3145 
3146 	if (unlikely(len < 2))
3147 		return -EPROTO;
3148 
3149 	guc_id = msg[0];
3150 	runnable_state = msg[1];
3151 
3152 	q = g2h_exec_queue_lookup(guc, guc_id);
3153 	if (unlikely(!q))
3154 		return -EPROTO;
3155 
3156 	if (unlikely(!exec_queue_pending_enable(q) &&
3157 		     !exec_queue_pending_disable(q))) {
3158 		xe_gt_err(guc_to_gt(guc),
3159 			  "SCHED_DONE: Unexpected engine state 0x%04x, guc_id=%d, runnable_state=%u",
3160 			  atomic_read(&q->guc->state), q->guc->id,
3161 			  runnable_state);
3162 		return -EPROTO;
3163 	}
3164 
3165 	handle_sched_done(guc, q, runnable_state);
3166 
3167 	return 0;
3168 }
3169 
3170 static void handle_deregister_done(struct xe_guc *guc, struct xe_exec_queue *q)
3171 {
3172 	trace_xe_exec_queue_deregister_done(q);
3173 
3174 	clear_exec_queue_registered(q);
3175 	__guc_exec_queue_destroy(guc, q);
3176 }
3177 
3178 int xe_guc_deregister_done_handler(struct xe_guc *guc, u32 *msg, u32 len)
3179 {
3180 	struct xe_exec_queue *q;
3181 	u32 guc_id;
3182 
3183 	if (unlikely(len < 1))
3184 		return -EPROTO;
3185 
3186 	guc_id = msg[0];
3187 
3188 	q = g2h_exec_queue_lookup(guc, guc_id);
3189 	if (unlikely(!q))
3190 		return -EPROTO;
3191 
3192 	if (!exec_queue_destroyed(q) || exec_queue_pending_disable(q) ||
3193 	    exec_queue_pending_enable(q) || exec_queue_enabled(q)) {
3194 		xe_gt_err(guc_to_gt(guc),
3195 			  "DEREGISTER_DONE: Unexpected engine state 0x%04x, guc_id=%d",
3196 			  atomic_read(&q->guc->state), q->guc->id);
3197 		return -EPROTO;
3198 	}
3199 
3200 	handle_deregister_done(guc, q);
3201 
3202 	return 0;
3203 }
3204 
3205 int xe_guc_exec_queue_reset_handler(struct xe_guc *guc, u32 *msg, u32 len)
3206 {
3207 	struct xe_gt *gt = guc_to_gt(guc);
3208 	struct xe_exec_queue *q;
3209 	u32 guc_id;
3210 
3211 	if (unlikely(len < 1))
3212 		return -EPROTO;
3213 
3214 	guc_id = msg[0];
3215 
3216 	q = g2h_exec_queue_lookup(guc, guc_id);
3217 	if (unlikely(!q))
3218 		return -EPROTO;
3219 
3220 	if (!exec_queue_killed(q))
3221 		xe_gt_info(gt, "Engine reset: engine_class=%s, logical_mask: 0x%x, guc_id=%d, state=0x%0x",
3222 			   xe_hw_engine_class_to_str(q->class), q->logical_mask, guc_id,
3223 			   atomic_read(&q->guc->state));
3224 
3225 	trace_xe_exec_queue_reset(q);
3226 
3227 	/*
3228 	 * A banned engine is a NOP at this point (came from
3229 	 * guc_exec_queue_timedout_job). Otherwise, kick drm scheduler to cancel
3230 	 * jobs by setting timeout of the job to the minimum value kicking
3231 	 * guc_exec_queue_timedout_job.
3232 	 */
3233 	xe_guc_exec_queue_reset_trigger_cleanup(q);
3234 
3235 	return 0;
3236 }
3237 
3238 /*
3239  * xe_guc_error_capture_handler - Handler of GuC captured message
3240  * @guc: The GuC object
3241  * @msg: Point to the message
3242  * @len: The message length
3243  *
3244  * When GuC captured data is ready, GuC will send message
3245  * XE_GUC_ACTION_STATE_CAPTURE_NOTIFICATION to host, this function will be
3246  * called 1st to check status before process the data comes with the message.
3247  *
3248  * Returns: error code. 0 if success
3249  */
3250 int xe_guc_error_capture_handler(struct xe_guc *guc, u32 *msg, u32 len)
3251 {
3252 	u32 status;
3253 
3254 	if (unlikely(len != XE_GUC_ACTION_STATE_CAPTURE_NOTIFICATION_DATA_LEN))
3255 		return -EPROTO;
3256 
3257 	status = msg[0] & XE_GUC_STATE_CAPTURE_EVENT_STATUS_MASK;
3258 	if (status == XE_GUC_STATE_CAPTURE_EVENT_STATUS_NOSPACE)
3259 		xe_gt_warn(guc_to_gt(guc), "G2H-Error capture no space");
3260 
3261 	xe_guc_capture_process(guc);
3262 
3263 	return 0;
3264 }
3265 
3266 int xe_guc_exec_queue_memory_cat_error_handler(struct xe_guc *guc, u32 *msg,
3267 					       u32 len)
3268 {
3269 	struct xe_gt *gt = guc_to_gt(guc);
3270 	struct xe_exec_queue *q;
3271 	u32 guc_id;
3272 	u32 type = XE_GUC_CAT_ERR_TYPE_INVALID;
3273 
3274 	if (unlikely(!len || len > 2))
3275 		return -EPROTO;
3276 
3277 	guc_id = msg[0];
3278 
3279 	if (len == 2)
3280 		type = msg[1];
3281 
3282 	if (guc_id == GUC_ID_UNKNOWN) {
3283 		/*
3284 		 * GuC uses GUC_ID_UNKNOWN if it can not map the CAT fault to any PF/VF
3285 		 * context. In such case only PF will be notified about that fault.
3286 		 */
3287 		xe_gt_err_ratelimited(gt, "Memory CAT error reported by GuC!\n");
3288 		return 0;
3289 	}
3290 
3291 	q = g2h_exec_queue_lookup(guc, guc_id);
3292 	if (unlikely(!q))
3293 		return -EPROTO;
3294 
3295 	/*
3296 	 * The type is HW-defined and changes based on platform, so we don't
3297 	 * decode it in the kernel and only check if it is valid.
3298 	 * See bspec 54047 and 72187 for details.
3299 	 */
3300 	if (type != XE_GUC_CAT_ERR_TYPE_INVALID)
3301 		xe_gt_info(gt,
3302 			   "Engine memory CAT error [%u]: class=%s, logical_mask: 0x%x, guc_id=%d",
3303 			   type, xe_hw_engine_class_to_str(q->class), q->logical_mask, guc_id);
3304 	else
3305 		xe_gt_info(gt,
3306 			   "Engine memory CAT error: class=%s, logical_mask: 0x%x, guc_id=%d",
3307 			   xe_hw_engine_class_to_str(q->class), q->logical_mask, guc_id);
3308 
3309 	trace_xe_exec_queue_memory_cat_error(q);
3310 
3311 	/* Treat the same as engine reset */
3312 	xe_guc_exec_queue_reset_trigger_cleanup(q);
3313 
3314 	return 0;
3315 }
3316 
3317 int xe_guc_uncorrectable_error_handler(struct xe_guc *guc, u32 *msg, u32 len)
3318 {
3319 	struct xe_gt *gt = guc_to_gt(guc);
3320 	struct xe_exec_queue *q;
3321 	u32 guc_id;
3322 
3323 	if (unlikely(!len || len > 1))
3324 		return -EPROTO;
3325 
3326 	guc_id = msg[0];
3327 
3328 	if (guc_id == GUC_ID_UNKNOWN) {
3329 		xe_gt_err(gt, "GuC: Uncorrectable local error with unknown GuC id\n");
3330 		return 0;
3331 	}
3332 
3333 	q = g2h_exec_queue_lookup(guc, guc_id);
3334 	if (unlikely(!q))
3335 		return -EPROTO;
3336 
3337 	xe_gt_err(gt,
3338 		  "GuC: Uncorrectable local error! guc_id=%d class=%s, logical_mask=0x%x",
3339 		  guc_id, xe_hw_engine_class_to_str(q->class), q->logical_mask);
3340 
3341 	trace_xe_guc_uncorrectable_error(q);
3342 
3343 	/* Treat the same as engine reset */
3344 	xe_guc_exec_queue_reset_trigger_cleanup(q);
3345 
3346 	return 0;
3347 }
3348 
3349 int xe_guc_exec_queue_reset_failure_handler(struct xe_guc *guc, u32 *msg, u32 len)
3350 {
3351 	struct xe_gt *gt = guc_to_gt(guc);
3352 	u8 guc_class, instance;
3353 	u32 reason;
3354 
3355 	if (unlikely(len != 3))
3356 		return -EPROTO;
3357 
3358 	guc_class = msg[0];
3359 	instance = msg[1];
3360 	reason = msg[2];
3361 
3362 	/* Unexpected failure of a hardware feature, log an actual error */
3363 	xe_gt_err(gt, "GuC engine reset request failed on %d:%d because 0x%08X",
3364 		  guc_class, instance, reason);
3365 
3366 	xe_gt_reset_async(gt);
3367 
3368 	return 0;
3369 }
3370 
3371 int xe_guc_exec_queue_cgp_context_error_handler(struct xe_guc *guc, u32 *msg,
3372 						u32 len)
3373 {
3374 	struct xe_gt *gt = guc_to_gt(guc);
3375 	struct xe_device *xe = guc_to_xe(guc);
3376 	struct xe_exec_queue *q;
3377 	u32 guc_id = msg[2];
3378 
3379 	if (unlikely(len != XE_GUC_EXEC_QUEUE_CGP_CONTEXT_ERROR_LEN)) {
3380 		drm_err(&xe->drm, "Invalid length %u", len);
3381 		return -EPROTO;
3382 	}
3383 
3384 	q = g2h_exec_queue_lookup(guc, guc_id);
3385 	if (unlikely(!q))
3386 		return -EPROTO;
3387 
3388 	xe_gt_dbg(gt,
3389 		  "CGP context error: [%s] err=0x%x, q0_id=0x%x LRCA=0x%x guc_id=0x%x",
3390 		  msg[0] & 1 ? "uc" : "kmd", msg[1], msg[2], msg[3], msg[4]);
3391 
3392 	trace_xe_exec_queue_cgp_context_error(q);
3393 
3394 	/* Treat the same as engine reset */
3395 	xe_guc_exec_queue_reset_trigger_cleanup(q);
3396 
3397 	return 0;
3398 }
3399 
3400 /**
3401  * xe_guc_exec_queue_cgp_sync_done_handler - CGP synchronization done handler
3402  * @guc: guc
3403  * @msg: message indicating CGP sync done
3404  * @len: length of message
3405  *
3406  * Set multi queue group's sync_pending flag to false and wakeup anyone waiting
3407  * for CGP synchronization to complete.
3408  *
3409  * Return: 0 on success, -EPROTO for malformed messages.
3410  */
3411 int xe_guc_exec_queue_cgp_sync_done_handler(struct xe_guc *guc, u32 *msg, u32 len)
3412 {
3413 	struct xe_device *xe = guc_to_xe(guc);
3414 	struct xe_exec_queue *q;
3415 	u32 guc_id = msg[0];
3416 
3417 	if (unlikely(len < 1)) {
3418 		drm_err(&xe->drm, "Invalid CGP_SYNC_DONE length %u", len);
3419 		return -EPROTO;
3420 	}
3421 
3422 	q = g2h_exec_queue_lookup(guc, guc_id);
3423 	if (unlikely(!q))
3424 		return -EPROTO;
3425 
3426 	if (!xe_exec_queue_is_multi_queue_primary(q)) {
3427 		drm_err(&xe->drm, "Unexpected CGP_SYNC_DONE response");
3428 		return -EPROTO;
3429 	}
3430 
3431 	/* Wakeup the serialized cgp update wait */
3432 	WRITE_ONCE(q->multi_queue.group->sync_pending, false);
3433 	xe_guc_ct_wake_waiters(&guc->ct);
3434 
3435 	return 0;
3436 }
3437 
3438 static void
3439 guc_exec_queue_wq_snapshot_capture(struct xe_exec_queue *q,
3440 				   struct xe_guc_submit_exec_queue_snapshot *snapshot)
3441 {
3442 	struct xe_guc *guc = exec_queue_to_guc(q);
3443 	struct xe_device *xe = guc_to_xe(guc);
3444 	struct iosys_map map = xe_lrc_parallel_map(q->lrc[0]);
3445 	int i;
3446 
3447 	snapshot->guc.wqi_head = q->guc->wqi_head;
3448 	snapshot->guc.wqi_tail = q->guc->wqi_tail;
3449 	snapshot->parallel.wq_desc.head = parallel_read(xe, map, wq_desc.head);
3450 	snapshot->parallel.wq_desc.tail = parallel_read(xe, map, wq_desc.tail);
3451 	snapshot->parallel.wq_desc.status = parallel_read(xe, map,
3452 							  wq_desc.wq_status);
3453 
3454 	if (snapshot->parallel.wq_desc.head !=
3455 	    snapshot->parallel.wq_desc.tail) {
3456 		for (i = snapshot->parallel.wq_desc.head;
3457 		     i != snapshot->parallel.wq_desc.tail;
3458 		     i = (i + sizeof(u32)) % WQ_SIZE)
3459 			snapshot->parallel.wq[i / sizeof(u32)] =
3460 				parallel_read(xe, map, wq[i / sizeof(u32)]);
3461 	}
3462 }
3463 
3464 static void
3465 guc_exec_queue_wq_snapshot_print(struct xe_guc_submit_exec_queue_snapshot *snapshot,
3466 				 struct drm_printer *p)
3467 {
3468 	int i;
3469 
3470 	drm_printf(p, "\tWQ head: %u (internal), %d (memory)\n",
3471 		   snapshot->guc.wqi_head, snapshot->parallel.wq_desc.head);
3472 	drm_printf(p, "\tWQ tail: %u (internal), %d (memory)\n",
3473 		   snapshot->guc.wqi_tail, snapshot->parallel.wq_desc.tail);
3474 	drm_printf(p, "\tWQ status: %u\n", snapshot->parallel.wq_desc.status);
3475 
3476 	if (snapshot->parallel.wq_desc.head !=
3477 	    snapshot->parallel.wq_desc.tail) {
3478 		for (i = snapshot->parallel.wq_desc.head;
3479 		     i != snapshot->parallel.wq_desc.tail;
3480 		     i = (i + sizeof(u32)) % WQ_SIZE)
3481 			drm_printf(p, "\tWQ[%zu]: 0x%08x\n", i / sizeof(u32),
3482 				   snapshot->parallel.wq[i / sizeof(u32)]);
3483 	}
3484 }
3485 
3486 /**
3487  * xe_guc_exec_queue_snapshot_capture - Take a quick snapshot of the GuC Engine.
3488  * @q: faulty exec queue
3489  *
3490  * This can be printed out in a later stage like during dev_coredump
3491  * analysis.
3492  *
3493  * Returns: a GuC Submit Engine snapshot object that must be freed by the
3494  * caller, using `xe_guc_exec_queue_snapshot_free`.
3495  */
3496 struct xe_guc_submit_exec_queue_snapshot *
3497 xe_guc_exec_queue_snapshot_capture(struct xe_exec_queue *q)
3498 {
3499 	struct xe_gpu_scheduler *sched = &q->guc->sched;
3500 	struct xe_guc_submit_exec_queue_snapshot *snapshot;
3501 	int i;
3502 
3503 	snapshot = kzalloc_obj(*snapshot, GFP_ATOMIC);
3504 
3505 	if (!snapshot)
3506 		return NULL;
3507 
3508 	snapshot->guc.id = q->guc->id;
3509 	memcpy(&snapshot->name, &q->name, sizeof(snapshot->name));
3510 	snapshot->class = q->class;
3511 	snapshot->logical_mask = q->logical_mask;
3512 	snapshot->width = q->width;
3513 	snapshot->refcount = kref_read(&q->refcount);
3514 	snapshot->sched_timeout = sched->base.timeout;
3515 	snapshot->sched_props.timeslice_us = q->sched_props.timeslice_us;
3516 	snapshot->sched_props.preempt_timeout_us =
3517 		q->sched_props.preempt_timeout_us;
3518 
3519 	snapshot->lrc = kmalloc_objs(struct xe_lrc_snapshot *, q->width,
3520 				     GFP_ATOMIC);
3521 
3522 	if (snapshot->lrc) {
3523 		for (i = 0; i < q->width; ++i) {
3524 			struct xe_lrc *lrc = q->lrc[i];
3525 
3526 			snapshot->lrc[i] = xe_lrc_snapshot_capture(lrc);
3527 		}
3528 	}
3529 
3530 	snapshot->schedule_state = atomic_read(&q->guc->state);
3531 	snapshot->exec_queue_flags = q->flags;
3532 
3533 	snapshot->parallel_execution = xe_exec_queue_is_parallel(q);
3534 	if (snapshot->parallel_execution)
3535 		guc_exec_queue_wq_snapshot_capture(q, snapshot);
3536 
3537 	if (xe_exec_queue_is_multi_queue(q)) {
3538 		snapshot->multi_queue.valid = true;
3539 		snapshot->multi_queue.primary = xe_exec_queue_multi_queue_primary(q)->guc->id;
3540 		snapshot->multi_queue.pos = q->multi_queue.pos;
3541 	}
3542 
3543 	return snapshot;
3544 }
3545 
3546 /**
3547  * xe_guc_exec_queue_snapshot_capture_delayed - Take delayed part of snapshot of the GuC Engine.
3548  * @snapshot: Previously captured snapshot of job.
3549  *
3550  * This captures some data that requires taking some locks, so it cannot be done in signaling path.
3551  */
3552 void
3553 xe_guc_exec_queue_snapshot_capture_delayed(struct xe_guc_submit_exec_queue_snapshot *snapshot)
3554 {
3555 	int i;
3556 
3557 	if (!snapshot || !snapshot->lrc)
3558 		return;
3559 
3560 	for (i = 0; i < snapshot->width; ++i)
3561 		xe_lrc_snapshot_capture_delayed(snapshot->lrc[i]);
3562 }
3563 
3564 /**
3565  * xe_guc_exec_queue_snapshot_print - Print out a given GuC Engine snapshot.
3566  * @snapshot: GuC Submit Engine snapshot object.
3567  * @p: drm_printer where it will be printed out.
3568  *
3569  * This function prints out a given GuC Submit Engine snapshot object.
3570  */
3571 void
3572 xe_guc_exec_queue_snapshot_print(struct xe_guc_submit_exec_queue_snapshot *snapshot,
3573 				 struct drm_printer *p)
3574 {
3575 	int i;
3576 
3577 	if (!snapshot)
3578 		return;
3579 
3580 	drm_printf(p, "GuC ID: %d\n", snapshot->guc.id);
3581 	drm_printf(p, "\tName: %s\n", snapshot->name);
3582 	drm_printf(p, "\tClass: %d\n", snapshot->class);
3583 	drm_printf(p, "\tLogical mask: 0x%x\n", snapshot->logical_mask);
3584 	drm_printf(p, "\tWidth: %d\n", snapshot->width);
3585 	drm_printf(p, "\tRef: %d\n", snapshot->refcount);
3586 	drm_printf(p, "\tTimeout: %ld (ms)\n", snapshot->sched_timeout);
3587 	drm_printf(p, "\tTimeslice: %u (us)\n",
3588 		   snapshot->sched_props.timeslice_us);
3589 	drm_printf(p, "\tPreempt timeout: %u (us)\n",
3590 		   snapshot->sched_props.preempt_timeout_us);
3591 
3592 	for (i = 0; snapshot->lrc && i < snapshot->width; ++i)
3593 		xe_lrc_snapshot_print(snapshot->lrc[i], p);
3594 
3595 	drm_printf(p, "\tSchedule State: 0x%x\n", snapshot->schedule_state);
3596 	drm_printf(p, "\tFlags: 0x%lx\n", snapshot->exec_queue_flags);
3597 
3598 	if (snapshot->parallel_execution)
3599 		guc_exec_queue_wq_snapshot_print(snapshot, p);
3600 
3601 	if (snapshot->multi_queue.valid) {
3602 		drm_printf(p, "\tMulti queue primary GuC ID: %d\n", snapshot->multi_queue.primary);
3603 		drm_printf(p, "\tMulti queue position: %d\n", snapshot->multi_queue.pos);
3604 	}
3605 }
3606 
3607 /**
3608  * xe_guc_exec_queue_snapshot_free - Free all allocated objects for a given
3609  * snapshot.
3610  * @snapshot: GuC Submit Engine snapshot object.
3611  *
3612  * This function free all the memory that needed to be allocated at capture
3613  * time.
3614  */
3615 void xe_guc_exec_queue_snapshot_free(struct xe_guc_submit_exec_queue_snapshot *snapshot)
3616 {
3617 	int i;
3618 
3619 	if (!snapshot)
3620 		return;
3621 
3622 	if (snapshot->lrc) {
3623 		for (i = 0; i < snapshot->width; i++)
3624 			xe_lrc_snapshot_free(snapshot->lrc[i]);
3625 		kfree(snapshot->lrc);
3626 	}
3627 	kfree(snapshot);
3628 }
3629 
3630 static void guc_exec_queue_print(struct xe_exec_queue *q, struct drm_printer *p)
3631 {
3632 	struct xe_guc_submit_exec_queue_snapshot *snapshot;
3633 
3634 	snapshot = xe_guc_exec_queue_snapshot_capture(q);
3635 	xe_guc_exec_queue_snapshot_print(snapshot, p);
3636 	xe_guc_exec_queue_snapshot_free(snapshot);
3637 }
3638 
3639 /**
3640  * xe_guc_register_vf_exec_queue - Register exec queue for a given context type.
3641  * @q: Execution queue
3642  * @ctx_type: Type of the context
3643  *
3644  * This function registers the execution queue with the guc. Special context
3645  * types like GUC_CONTEXT_COMPRESSION_SAVE and GUC_CONTEXT_COMPRESSION_RESTORE
3646  * are only applicable for IGPU and in the VF.
3647  * Submits the execution queue to GUC after registering it.
3648  *
3649  * Returns - None.
3650  */
3651 void xe_guc_register_vf_exec_queue(struct xe_exec_queue *q, int ctx_type)
3652 {
3653 	struct xe_guc *guc = exec_queue_to_guc(q);
3654 	struct xe_device *xe = guc_to_xe(guc);
3655 	struct xe_gt *gt = guc_to_gt(guc);
3656 
3657 	xe_gt_assert(gt, IS_SRIOV_VF(xe));
3658 	xe_gt_assert(gt, !IS_DGFX(xe));
3659 	xe_gt_assert(gt, ctx_type == GUC_CONTEXT_COMPRESSION_SAVE ||
3660 		     ctx_type == GUC_CONTEXT_COMPRESSION_RESTORE);
3661 	xe_gt_assert(gt, GUC_SUBMIT_VER(guc) >= MAKE_GUC_VER(1, 23, 0));
3662 
3663 	register_exec_queue(q, ctx_type);
3664 	enable_scheduling(q);
3665 }
3666 
3667 /**
3668  * xe_guc_submit_print - GuC Submit Print.
3669  * @guc: GuC.
3670  * @p: drm_printer where it will be printed out.
3671  *
3672  * This function capture and prints snapshots of **all** GuC Engines.
3673  */
3674 void xe_guc_submit_print(struct xe_guc *guc, struct drm_printer *p)
3675 {
3676 	struct xe_exec_queue *q;
3677 	unsigned long index;
3678 
3679 	if (!xe_device_uc_enabled(guc_to_xe(guc)))
3680 		return;
3681 
3682 	mutex_lock(&guc->submission_state.lock);
3683 	xa_for_each(&guc->submission_state.exec_queue_lookup, index, q)
3684 		guc_exec_queue_print(q, p);
3685 	mutex_unlock(&guc->submission_state.lock);
3686 }
3687 
3688 /**
3689  * xe_guc_has_registered_mlrc_queues - check whether there are any MLRC queues
3690  * registered with the GuC
3691  * @guc: GuC.
3692  *
3693  * Return: true if any MLRC queue is registered with the GuC, false otherwise.
3694  */
3695 bool xe_guc_has_registered_mlrc_queues(struct xe_guc *guc)
3696 {
3697 	struct xe_exec_queue *q;
3698 	unsigned long index;
3699 
3700 	guard(mutex)(&guc->submission_state.lock);
3701 
3702 	xa_for_each(&guc->submission_state.exec_queue_lookup, index, q)
3703 		if (q->width > 1)
3704 			return true;
3705 
3706 	return false;
3707 }
3708 
3709 /**
3710  * xe_guc_contexts_hwsp_rebase - Re-compute GGTT references within all
3711  * exec queues registered to given GuC.
3712  * @guc: the &xe_guc struct instance
3713  * @scratch: scratch buffer to be used as temporary storage
3714  *
3715  * Returns: zero on success, negative error code on failure.
3716  */
3717 int xe_guc_contexts_hwsp_rebase(struct xe_guc *guc, void *scratch)
3718 {
3719 	struct xe_exec_queue *q;
3720 	unsigned long index;
3721 	int err = 0;
3722 
3723 	mutex_lock(&guc->submission_state.lock);
3724 	xa_for_each(&guc->submission_state.exec_queue_lookup, index, q) {
3725 		/* Prevent redundant attempts to stop parallel queues */
3726 		if (q->guc->id != index)
3727 			continue;
3728 
3729 		err = xe_exec_queue_contexts_hwsp_rebase(q, scratch);
3730 		if (err)
3731 			break;
3732 	}
3733 	mutex_unlock(&guc->submission_state.lock);
3734 
3735 	return err;
3736 }
3737