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