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