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