1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright © 2014 Intel Corporation
4  */
5 
6 #include <linux/circ_buf.h>
7 
8 #include "gem/i915_gem_context.h"
9 #include "gem/i915_gem_lmem.h"
10 #include "gt/gen8_engine_cs.h"
11 #include "gt/intel_breadcrumbs.h"
12 #include "gt/intel_context.h"
13 #include "gt/intel_engine_heartbeat.h"
14 #include "gt/intel_engine_pm.h"
15 #include "gt/intel_engine_regs.h"
16 #include "gt/intel_gpu_commands.h"
17 #include "gt/intel_gt.h"
18 #include "gt/intel_gt_clock_utils.h"
19 #include "gt/intel_gt_irq.h"
20 #include "gt/intel_gt_pm.h"
21 #include "gt/intel_gt_regs.h"
22 #include "gt/intel_gt_requests.h"
23 #include "gt/intel_lrc.h"
24 #include "gt/intel_lrc_reg.h"
25 #include "gt/intel_mocs.h"
26 #include "gt/intel_ring.h"
27 
28 #include "intel_guc_ads.h"
29 #include "intel_guc_capture.h"
30 #include "intel_guc_print.h"
31 #include "intel_guc_submission.h"
32 
33 #include "i915_drv.h"
34 #include "i915_reg.h"
35 #include "i915_trace.h"
36 
37 /**
38  * DOC: GuC-based command submission
39  *
40  * The Scratch registers:
41  * There are 16 MMIO-based registers start from 0xC180. The kernel driver writes
42  * a value to the action register (SOFT_SCRATCH_0) along with any data. It then
43  * triggers an interrupt on the GuC via another register write (0xC4C8).
44  * Firmware writes a success/fail code back to the action register after
45  * processes the request. The kernel driver polls waiting for this update and
46  * then proceeds.
47  *
48  * Command Transport buffers (CTBs):
49  * Covered in detail in other sections but CTBs (Host to GuC - H2G, GuC to Host
50  * - G2H) are a message interface between the i915 and GuC.
51  *
52  * Context registration:
53  * Before a context can be submitted it must be registered with the GuC via a
54  * H2G. A unique guc_id is associated with each context. The context is either
55  * registered at request creation time (normal operation) or at submission time
56  * (abnormal operation, e.g. after a reset).
57  *
58  * Context submission:
59  * The i915 updates the LRC tail value in memory. The i915 must enable the
60  * scheduling of the context within the GuC for the GuC to actually consider it.
61  * Therefore, the first time a disabled context is submitted we use a schedule
62  * enable H2G, while follow up submissions are done via the context submit H2G,
63  * which informs the GuC that a previously enabled context has new work
64  * available.
65  *
66  * Context unpin:
67  * To unpin a context a H2G is used to disable scheduling. When the
68  * corresponding G2H returns indicating the scheduling disable operation has
69  * completed it is safe to unpin the context. While a disable is in flight it
70  * isn't safe to resubmit the context so a fence is used to stall all future
71  * requests of that context until the G2H is returned. Because this interaction
72  * with the GuC takes a non-zero amount of time we delay the disabling of
73  * scheduling after the pin count goes to zero by a configurable period of time
74  * (see SCHED_DISABLE_DELAY_MS). The thought is this gives the user a window of
75  * time to resubmit something on the context before doing this costly operation.
76  * This delay is only done if the context isn't closed and the guc_id usage is
77  * less than a threshold (see NUM_SCHED_DISABLE_GUC_IDS_THRESHOLD).
78  *
79  * Context deregistration:
80  * Before a context can be destroyed or if we steal its guc_id we must
81  * deregister the context with the GuC via H2G. If stealing the guc_id it isn't
82  * safe to submit anything to this guc_id until the deregister completes so a
83  * fence is used to stall all requests associated with this guc_id until the
84  * corresponding G2H returns indicating the guc_id has been deregistered.
85  *
86  * submission_state.guc_ids:
87  * Unique number associated with private GuC context data passed in during
88  * context registration / submission / deregistration. 64k available. Simple ida
89  * is used for allocation.
90  *
91  * Stealing guc_ids:
92  * If no guc_ids are available they can be stolen from another context at
93  * request creation time if that context is unpinned. If a guc_id can't be found
94  * we punt this problem to the user as we believe this is near impossible to hit
95  * during normal use cases.
96  *
97  * Locking:
98  * In the GuC submission code we have 3 basic spin locks which protect
99  * everything. Details about each below.
100  *
101  * sched_engine->lock
102  * This is the submission lock for all contexts that share an i915 schedule
103  * engine (sched_engine), thus only one of the contexts which share a
104  * sched_engine can be submitting at a time. Currently only one sched_engine is
105  * used for all of GuC submission but that could change in the future.
106  *
107  * guc->submission_state.lock
108  * Global lock for GuC submission state. Protects guc_ids and destroyed contexts
109  * list.
110  *
111  * ce->guc_state.lock
112  * Protects everything under ce->guc_state. Ensures that a context is in the
113  * correct state before issuing a H2G. e.g. We don't issue a schedule disable
114  * on a disabled context (bad idea), we don't issue a schedule enable when a
115  * schedule disable is in flight, etc... Also protects list of inflight requests
116  * on the context and the priority management state. Lock is individual to each
117  * context.
118  *
119  * Lock ordering rules:
120  * sched_engine->lock -> ce->guc_state.lock
121  * guc->submission_state.lock -> ce->guc_state.lock
122  *
123  * Reset races:
124  * When a full GT reset is triggered it is assumed that some G2H responses to
125  * H2Gs can be lost as the GuC is also reset. Losing these G2H can prove to be
126  * fatal as we do certain operations upon receiving a G2H (e.g. destroy
127  * contexts, release guc_ids, etc...). When this occurs we can scrub the
128  * context state and cleanup appropriately, however this is quite racey.
129  * To avoid races, the reset code must disable submission before scrubbing for
130  * the missing G2H, while the submission code must check for submission being
131  * disabled and skip sending H2Gs and updating context states when it is. Both
132  * sides must also make sure to hold the relevant locks.
133  */
134 
135 /* GuC Virtual Engine */
136 struct guc_virtual_engine {
137 	struct intel_engine_cs base;
138 	struct intel_context context;
139 };
140 
141 static struct intel_context *
142 guc_create_virtual(struct intel_engine_cs **siblings, unsigned int count,
143 		   unsigned long flags);
144 
145 static struct intel_context *
146 guc_create_parallel(struct intel_engine_cs **engines,
147 		    unsigned int num_siblings,
148 		    unsigned int width);
149 
150 #define GUC_REQUEST_SIZE 64 /* bytes */
151 
152 /*
153  * We reserve 1/16 of the guc_ids for multi-lrc as these need to be contiguous
154  * per the GuC submission interface. A different allocation algorithm is used
155  * (bitmap vs. ida) between multi-lrc and single-lrc hence the reason to
156  * partition the guc_id space. We believe the number of multi-lrc contexts in
157  * use should be low and 1/16 should be sufficient. Minimum of 32 guc_ids for
158  * multi-lrc.
159  */
160 #define NUMBER_MULTI_LRC_GUC_ID(guc)	\
161 	((guc)->submission_state.num_guc_ids / 16)
162 
163 /*
164  * Below is a set of functions which control the GuC scheduling state which
165  * require a lock.
166  */
167 #define SCHED_STATE_WAIT_FOR_DEREGISTER_TO_REGISTER	BIT(0)
168 #define SCHED_STATE_DESTROYED				BIT(1)
169 #define SCHED_STATE_PENDING_DISABLE			BIT(2)
170 #define SCHED_STATE_BANNED				BIT(3)
171 #define SCHED_STATE_ENABLED				BIT(4)
172 #define SCHED_STATE_PENDING_ENABLE			BIT(5)
173 #define SCHED_STATE_REGISTERED				BIT(6)
174 #define SCHED_STATE_POLICY_REQUIRED			BIT(7)
175 #define SCHED_STATE_CLOSED				BIT(8)
176 #define SCHED_STATE_BLOCKED_SHIFT			9
177 #define SCHED_STATE_BLOCKED		BIT(SCHED_STATE_BLOCKED_SHIFT)
178 #define SCHED_STATE_BLOCKED_MASK	(0xfff << SCHED_STATE_BLOCKED_SHIFT)
179 
180 static inline void init_sched_state(struct intel_context *ce)
181 {
182 	lockdep_assert_held(&ce->guc_state.lock);
183 	ce->guc_state.sched_state &= SCHED_STATE_BLOCKED_MASK;
184 }
185 
186 /*
187  * Kernel contexts can have SCHED_STATE_REGISTERED after suspend.
188  * A context close can race with the submission path, so SCHED_STATE_CLOSED
189  * can be set immediately before we try to register.
190  */
191 #define SCHED_STATE_VALID_INIT \
192 	(SCHED_STATE_BLOCKED_MASK | \
193 	 SCHED_STATE_CLOSED | \
194 	 SCHED_STATE_REGISTERED)
195 
196 __maybe_unused
197 static bool sched_state_is_init(struct intel_context *ce)
198 {
199 	return !(ce->guc_state.sched_state & ~SCHED_STATE_VALID_INIT);
200 }
201 
202 static inline bool
203 context_wait_for_deregister_to_register(struct intel_context *ce)
204 {
205 	return ce->guc_state.sched_state &
206 		SCHED_STATE_WAIT_FOR_DEREGISTER_TO_REGISTER;
207 }
208 
209 static inline void
210 set_context_wait_for_deregister_to_register(struct intel_context *ce)
211 {
212 	lockdep_assert_held(&ce->guc_state.lock);
213 	ce->guc_state.sched_state |=
214 		SCHED_STATE_WAIT_FOR_DEREGISTER_TO_REGISTER;
215 }
216 
217 static inline void
218 clr_context_wait_for_deregister_to_register(struct intel_context *ce)
219 {
220 	lockdep_assert_held(&ce->guc_state.lock);
221 	ce->guc_state.sched_state &=
222 		~SCHED_STATE_WAIT_FOR_DEREGISTER_TO_REGISTER;
223 }
224 
225 static inline bool
226 context_destroyed(struct intel_context *ce)
227 {
228 	return ce->guc_state.sched_state & SCHED_STATE_DESTROYED;
229 }
230 
231 static inline void
232 set_context_destroyed(struct intel_context *ce)
233 {
234 	lockdep_assert_held(&ce->guc_state.lock);
235 	ce->guc_state.sched_state |= SCHED_STATE_DESTROYED;
236 }
237 
238 static inline bool context_pending_disable(struct intel_context *ce)
239 {
240 	return ce->guc_state.sched_state & SCHED_STATE_PENDING_DISABLE;
241 }
242 
243 static inline void set_context_pending_disable(struct intel_context *ce)
244 {
245 	lockdep_assert_held(&ce->guc_state.lock);
246 	ce->guc_state.sched_state |= SCHED_STATE_PENDING_DISABLE;
247 }
248 
249 static inline void clr_context_pending_disable(struct intel_context *ce)
250 {
251 	lockdep_assert_held(&ce->guc_state.lock);
252 	ce->guc_state.sched_state &= ~SCHED_STATE_PENDING_DISABLE;
253 }
254 
255 static inline bool context_banned(struct intel_context *ce)
256 {
257 	return ce->guc_state.sched_state & SCHED_STATE_BANNED;
258 }
259 
260 static inline void set_context_banned(struct intel_context *ce)
261 {
262 	lockdep_assert_held(&ce->guc_state.lock);
263 	ce->guc_state.sched_state |= SCHED_STATE_BANNED;
264 }
265 
266 static inline void clr_context_banned(struct intel_context *ce)
267 {
268 	lockdep_assert_held(&ce->guc_state.lock);
269 	ce->guc_state.sched_state &= ~SCHED_STATE_BANNED;
270 }
271 
272 static inline bool context_enabled(struct intel_context *ce)
273 {
274 	return ce->guc_state.sched_state & SCHED_STATE_ENABLED;
275 }
276 
277 static inline void set_context_enabled(struct intel_context *ce)
278 {
279 	lockdep_assert_held(&ce->guc_state.lock);
280 	ce->guc_state.sched_state |= SCHED_STATE_ENABLED;
281 }
282 
283 static inline void clr_context_enabled(struct intel_context *ce)
284 {
285 	lockdep_assert_held(&ce->guc_state.lock);
286 	ce->guc_state.sched_state &= ~SCHED_STATE_ENABLED;
287 }
288 
289 static inline bool context_pending_enable(struct intel_context *ce)
290 {
291 	return ce->guc_state.sched_state & SCHED_STATE_PENDING_ENABLE;
292 }
293 
294 static inline void set_context_pending_enable(struct intel_context *ce)
295 {
296 	lockdep_assert_held(&ce->guc_state.lock);
297 	ce->guc_state.sched_state |= SCHED_STATE_PENDING_ENABLE;
298 }
299 
300 static inline void clr_context_pending_enable(struct intel_context *ce)
301 {
302 	lockdep_assert_held(&ce->guc_state.lock);
303 	ce->guc_state.sched_state &= ~SCHED_STATE_PENDING_ENABLE;
304 }
305 
306 static inline bool context_registered(struct intel_context *ce)
307 {
308 	return ce->guc_state.sched_state & SCHED_STATE_REGISTERED;
309 }
310 
311 static inline void set_context_registered(struct intel_context *ce)
312 {
313 	lockdep_assert_held(&ce->guc_state.lock);
314 	ce->guc_state.sched_state |= SCHED_STATE_REGISTERED;
315 }
316 
317 static inline void clr_context_registered(struct intel_context *ce)
318 {
319 	lockdep_assert_held(&ce->guc_state.lock);
320 	ce->guc_state.sched_state &= ~SCHED_STATE_REGISTERED;
321 }
322 
323 static inline bool context_policy_required(struct intel_context *ce)
324 {
325 	return ce->guc_state.sched_state & SCHED_STATE_POLICY_REQUIRED;
326 }
327 
328 static inline void set_context_policy_required(struct intel_context *ce)
329 {
330 	lockdep_assert_held(&ce->guc_state.lock);
331 	ce->guc_state.sched_state |= SCHED_STATE_POLICY_REQUIRED;
332 }
333 
334 static inline void clr_context_policy_required(struct intel_context *ce)
335 {
336 	lockdep_assert_held(&ce->guc_state.lock);
337 	ce->guc_state.sched_state &= ~SCHED_STATE_POLICY_REQUIRED;
338 }
339 
340 static inline bool context_close_done(struct intel_context *ce)
341 {
342 	return ce->guc_state.sched_state & SCHED_STATE_CLOSED;
343 }
344 
345 static inline void set_context_close_done(struct intel_context *ce)
346 {
347 	lockdep_assert_held(&ce->guc_state.lock);
348 	ce->guc_state.sched_state |= SCHED_STATE_CLOSED;
349 }
350 
351 static inline u32 context_blocked(struct intel_context *ce)
352 {
353 	return (ce->guc_state.sched_state & SCHED_STATE_BLOCKED_MASK) >>
354 		SCHED_STATE_BLOCKED_SHIFT;
355 }
356 
357 static inline void incr_context_blocked(struct intel_context *ce)
358 {
359 	lockdep_assert_held(&ce->guc_state.lock);
360 
361 	ce->guc_state.sched_state += SCHED_STATE_BLOCKED;
362 
363 	GEM_BUG_ON(!context_blocked(ce));	/* Overflow check */
364 }
365 
366 static inline void decr_context_blocked(struct intel_context *ce)
367 {
368 	lockdep_assert_held(&ce->guc_state.lock);
369 
370 	GEM_BUG_ON(!context_blocked(ce));	/* Underflow check */
371 
372 	ce->guc_state.sched_state -= SCHED_STATE_BLOCKED;
373 }
374 
375 static struct intel_context *
376 request_to_scheduling_context(struct i915_request *rq)
377 {
378 	return intel_context_to_parent(rq->context);
379 }
380 
381 static inline bool context_guc_id_invalid(struct intel_context *ce)
382 {
383 	return ce->guc_id.id == GUC_INVALID_CONTEXT_ID;
384 }
385 
386 static inline void set_context_guc_id_invalid(struct intel_context *ce)
387 {
388 	ce->guc_id.id = GUC_INVALID_CONTEXT_ID;
389 }
390 
391 static inline struct intel_guc *ce_to_guc(struct intel_context *ce)
392 {
393 	return &ce->engine->gt->uc.guc;
394 }
395 
396 static inline struct i915_priolist *to_priolist(struct rb_node *rb)
397 {
398 	return rb_entry(rb, struct i915_priolist, node);
399 }
400 
401 /*
402  * When using multi-lrc submission a scratch memory area is reserved in the
403  * parent's context state for the process descriptor, work queue, and handshake
404  * between the parent + children contexts to insert safe preemption points
405  * between each of the BBs. Currently the scratch area is sized to a page.
406  *
407  * The layout of this scratch area is below:
408  * 0						guc_process_desc
409  * + sizeof(struct guc_process_desc)		child go
410  * + CACHELINE_BYTES				child join[0]
411  * ...
412  * + CACHELINE_BYTES				child join[n - 1]
413  * ...						unused
414  * PARENT_SCRATCH_SIZE / 2			work queue start
415  * ...						work queue
416  * PARENT_SCRATCH_SIZE - 1			work queue end
417  */
418 #define WQ_SIZE			(PARENT_SCRATCH_SIZE / 2)
419 #define WQ_OFFSET		(PARENT_SCRATCH_SIZE - WQ_SIZE)
420 
421 struct sync_semaphore {
422 	u32 semaphore;
423 	u8 unused[CACHELINE_BYTES - sizeof(u32)];
424 };
425 
426 struct parent_scratch {
427 	union guc_descs {
428 		struct guc_sched_wq_desc wq_desc;
429 		struct guc_process_desc_v69 pdesc;
430 	} descs;
431 
432 	struct sync_semaphore go;
433 	struct sync_semaphore join[MAX_ENGINE_INSTANCE + 1];
434 
435 	u8 unused[WQ_OFFSET - sizeof(union guc_descs) -
436 		sizeof(struct sync_semaphore) * (MAX_ENGINE_INSTANCE + 2)];
437 
438 	u32 wq[WQ_SIZE / sizeof(u32)];
439 };
440 
441 static u32 __get_parent_scratch_offset(struct intel_context *ce)
442 {
443 	GEM_BUG_ON(!ce->parallel.guc.parent_page);
444 
445 	return ce->parallel.guc.parent_page * PAGE_SIZE;
446 }
447 
448 static u32 __get_wq_offset(struct intel_context *ce)
449 {
450 	BUILD_BUG_ON(offsetof(struct parent_scratch, wq) != WQ_OFFSET);
451 
452 	return __get_parent_scratch_offset(ce) + WQ_OFFSET;
453 }
454 
455 static struct parent_scratch *
456 __get_parent_scratch(struct intel_context *ce)
457 {
458 	BUILD_BUG_ON(sizeof(struct parent_scratch) != PARENT_SCRATCH_SIZE);
459 	BUILD_BUG_ON(sizeof(struct sync_semaphore) != CACHELINE_BYTES);
460 
461 	/*
462 	 * Need to subtract LRC_STATE_OFFSET here as the
463 	 * parallel.guc.parent_page is the offset into ce->state while
464 	 * ce->lrc_reg_reg is ce->state + LRC_STATE_OFFSET.
465 	 */
466 	return (struct parent_scratch *)
467 		(ce->lrc_reg_state +
468 		 ((__get_parent_scratch_offset(ce) -
469 		   LRC_STATE_OFFSET) / sizeof(u32)));
470 }
471 
472 static struct guc_process_desc_v69 *
473 __get_process_desc_v69(struct intel_context *ce)
474 {
475 	struct parent_scratch *ps = __get_parent_scratch(ce);
476 
477 	return &ps->descs.pdesc;
478 }
479 
480 static struct guc_sched_wq_desc *
481 __get_wq_desc_v70(struct intel_context *ce)
482 {
483 	struct parent_scratch *ps = __get_parent_scratch(ce);
484 
485 	return &ps->descs.wq_desc;
486 }
487 
488 static u32 *get_wq_pointer(struct intel_context *ce, u32 wqi_size)
489 {
490 	/*
491 	 * Check for space in work queue. Caching a value of head pointer in
492 	 * intel_context structure in order reduce the number accesses to shared
493 	 * GPU memory which may be across a PCIe bus.
494 	 */
495 #define AVAILABLE_SPACE	\
496 	CIRC_SPACE(ce->parallel.guc.wqi_tail, ce->parallel.guc.wqi_head, WQ_SIZE)
497 	if (wqi_size > AVAILABLE_SPACE) {
498 		ce->parallel.guc.wqi_head = READ_ONCE(*ce->parallel.guc.wq_head);
499 
500 		if (wqi_size > AVAILABLE_SPACE)
501 			return NULL;
502 	}
503 #undef AVAILABLE_SPACE
504 
505 	return &__get_parent_scratch(ce)->wq[ce->parallel.guc.wqi_tail / sizeof(u32)];
506 }
507 
508 static inline struct intel_context *__get_context(struct intel_guc *guc, u32 id)
509 {
510 	struct intel_context *ce = xa_load(&guc->context_lookup, id);
511 
512 	GEM_BUG_ON(id >= GUC_MAX_CONTEXT_ID);
513 
514 	return ce;
515 }
516 
517 static struct guc_lrc_desc_v69 *__get_lrc_desc_v69(struct intel_guc *guc, u32 index)
518 {
519 	struct guc_lrc_desc_v69 *base = guc->lrc_desc_pool_vaddr_v69;
520 
521 	if (!base)
522 		return NULL;
523 
524 	GEM_BUG_ON(index >= GUC_MAX_CONTEXT_ID);
525 
526 	return &base[index];
527 }
528 
529 static int guc_lrc_desc_pool_create_v69(struct intel_guc *guc)
530 {
531 	u32 size;
532 	int ret;
533 
534 	size = PAGE_ALIGN(sizeof(struct guc_lrc_desc_v69) *
535 			  GUC_MAX_CONTEXT_ID);
536 	ret = intel_guc_allocate_and_map_vma(guc, size, &guc->lrc_desc_pool_v69,
537 					     (void **)&guc->lrc_desc_pool_vaddr_v69);
538 	if (ret)
539 		return ret;
540 
541 	return 0;
542 }
543 
544 static void guc_lrc_desc_pool_destroy_v69(struct intel_guc *guc)
545 {
546 	if (!guc->lrc_desc_pool_vaddr_v69)
547 		return;
548 
549 	guc->lrc_desc_pool_vaddr_v69 = NULL;
550 	i915_vma_unpin_and_release(&guc->lrc_desc_pool_v69, I915_VMA_RELEASE_MAP);
551 }
552 
553 static inline bool guc_submission_initialized(struct intel_guc *guc)
554 {
555 	return guc->submission_initialized;
556 }
557 
558 static inline void _reset_lrc_desc_v69(struct intel_guc *guc, u32 id)
559 {
560 	struct guc_lrc_desc_v69 *desc = __get_lrc_desc_v69(guc, id);
561 
562 	if (desc)
563 		memset(desc, 0, sizeof(*desc));
564 }
565 
566 static inline bool ctx_id_mapped(struct intel_guc *guc, u32 id)
567 {
568 	return __get_context(guc, id);
569 }
570 
571 static inline void set_ctx_id_mapping(struct intel_guc *guc, u32 id,
572 				      struct intel_context *ce)
573 {
574 	unsigned long flags;
575 
576 	/*
577 	 * xarray API doesn't have xa_save_irqsave wrapper, so calling the
578 	 * lower level functions directly.
579 	 */
580 	xa_lock_irqsave(&guc->context_lookup, flags);
581 	__xa_store(&guc->context_lookup, id, ce, GFP_ATOMIC);
582 	xa_unlock_irqrestore(&guc->context_lookup, flags);
583 }
584 
585 static inline void clr_ctx_id_mapping(struct intel_guc *guc, u32 id)
586 {
587 	unsigned long flags;
588 
589 	if (unlikely(!guc_submission_initialized(guc)))
590 		return;
591 
592 	_reset_lrc_desc_v69(guc, id);
593 
594 	/*
595 	 * xarray API doesn't have xa_erase_irqsave wrapper, so calling
596 	 * the lower level functions directly.
597 	 */
598 	xa_lock_irqsave(&guc->context_lookup, flags);
599 	__xa_erase(&guc->context_lookup, id);
600 	xa_unlock_irqrestore(&guc->context_lookup, flags);
601 }
602 
603 static void decr_outstanding_submission_g2h(struct intel_guc *guc)
604 {
605 	if (atomic_dec_and_test(&guc->outstanding_submission_g2h))
606 		wake_up_all(&guc->ct.wq);
607 }
608 
609 static int guc_submission_send_busy_loop(struct intel_guc *guc,
610 					 const u32 *action,
611 					 u32 len,
612 					 u32 g2h_len_dw,
613 					 bool loop)
614 {
615 	/*
616 	 * We always loop when a send requires a reply (i.e. g2h_len_dw > 0),
617 	 * so we don't handle the case where we don't get a reply because we
618 	 * aborted the send due to the channel being busy.
619 	 */
620 	GEM_BUG_ON(g2h_len_dw && !loop);
621 
622 	if (g2h_len_dw)
623 		atomic_inc(&guc->outstanding_submission_g2h);
624 
625 	return intel_guc_send_busy_loop(guc, action, len, g2h_len_dw, loop);
626 }
627 
628 int intel_guc_wait_for_pending_msg(struct intel_guc *guc,
629 				   atomic_t *wait_var,
630 				   bool interruptible,
631 				   long timeout)
632 {
633 	const int state = interruptible ?
634 		TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE;
635 	DEFINE_WAIT(wait);
636 
637 	might_sleep();
638 	GEM_BUG_ON(timeout < 0);
639 
640 	if (!atomic_read(wait_var))
641 		return 0;
642 
643 	if (!timeout)
644 		return -ETIME;
645 
646 	for (;;) {
647 		prepare_to_wait(&guc->ct.wq, &wait, state);
648 
649 		if (!atomic_read(wait_var))
650 			break;
651 
652 		if (signal_pending_state(state, current)) {
653 			timeout = -EINTR;
654 			break;
655 		}
656 
657 		if (!timeout) {
658 			timeout = -ETIME;
659 			break;
660 		}
661 
662 		timeout = io_schedule_timeout(timeout);
663 	}
664 	finish_wait(&guc->ct.wq, &wait);
665 
666 	return (timeout < 0) ? timeout : 0;
667 }
668 
669 int intel_guc_wait_for_idle(struct intel_guc *guc, long timeout)
670 {
671 	if (!intel_uc_uses_guc_submission(&guc_to_gt(guc)->uc))
672 		return 0;
673 
674 	return intel_guc_wait_for_pending_msg(guc,
675 					      &guc->outstanding_submission_g2h,
676 					      true, timeout);
677 }
678 
679 static int guc_context_policy_init_v70(struct intel_context *ce, bool loop);
680 static int try_context_registration(struct intel_context *ce, bool loop);
681 
682 static int __guc_add_request(struct intel_guc *guc, struct i915_request *rq)
683 {
684 	int err = 0;
685 	struct intel_context *ce = request_to_scheduling_context(rq);
686 	u32 action[3];
687 	int len = 0;
688 	u32 g2h_len_dw = 0;
689 	bool enabled;
690 
691 	lockdep_assert_held(&rq->engine->sched_engine->lock);
692 
693 	/*
694 	 * Corner case where requests were sitting in the priority list or a
695 	 * request resubmitted after the context was banned.
696 	 */
697 	if (unlikely(!intel_context_is_schedulable(ce))) {
698 		i915_request_put(i915_request_mark_eio(rq));
699 		intel_engine_signal_breadcrumbs(ce->engine);
700 		return 0;
701 	}
702 
703 	GEM_BUG_ON(!atomic_read(&ce->guc_id.ref));
704 	GEM_BUG_ON(context_guc_id_invalid(ce));
705 
706 	if (context_policy_required(ce)) {
707 		err = guc_context_policy_init_v70(ce, false);
708 		if (err)
709 			return err;
710 	}
711 
712 	spin_lock(&ce->guc_state.lock);
713 
714 	/*
715 	 * The request / context will be run on the hardware when scheduling
716 	 * gets enabled in the unblock. For multi-lrc we still submit the
717 	 * context to move the LRC tails.
718 	 */
719 	if (unlikely(context_blocked(ce) && !intel_context_is_parent(ce)))
720 		goto out;
721 
722 	enabled = context_enabled(ce) || context_blocked(ce);
723 
724 	if (!enabled) {
725 		action[len++] = INTEL_GUC_ACTION_SCHED_CONTEXT_MODE_SET;
726 		action[len++] = ce->guc_id.id;
727 		action[len++] = GUC_CONTEXT_ENABLE;
728 		set_context_pending_enable(ce);
729 		intel_context_get(ce);
730 		g2h_len_dw = G2H_LEN_DW_SCHED_CONTEXT_MODE_SET;
731 	} else {
732 		action[len++] = INTEL_GUC_ACTION_SCHED_CONTEXT;
733 		action[len++] = ce->guc_id.id;
734 	}
735 
736 	err = intel_guc_send_nb(guc, action, len, g2h_len_dw);
737 	if (!enabled && !err) {
738 		trace_intel_context_sched_enable(ce);
739 		atomic_inc(&guc->outstanding_submission_g2h);
740 		set_context_enabled(ce);
741 
742 		/*
743 		 * Without multi-lrc KMD does the submission step (moving the
744 		 * lrc tail) so enabling scheduling is sufficient to submit the
745 		 * context. This isn't the case in multi-lrc submission as the
746 		 * GuC needs to move the tails, hence the need for another H2G
747 		 * to submit a multi-lrc context after enabling scheduling.
748 		 */
749 		if (intel_context_is_parent(ce)) {
750 			action[0] = INTEL_GUC_ACTION_SCHED_CONTEXT;
751 			err = intel_guc_send_nb(guc, action, len - 1, 0);
752 		}
753 	} else if (!enabled) {
754 		clr_context_pending_enable(ce);
755 		intel_context_put(ce);
756 	}
757 	if (likely(!err))
758 		trace_i915_request_guc_submit(rq);
759 
760 out:
761 	spin_unlock(&ce->guc_state.lock);
762 	return err;
763 }
764 
765 static int guc_add_request(struct intel_guc *guc, struct i915_request *rq)
766 {
767 	int ret = __guc_add_request(guc, rq);
768 
769 	if (unlikely(ret == -EBUSY)) {
770 		guc->stalled_request = rq;
771 		guc->submission_stall_reason = STALL_ADD_REQUEST;
772 	}
773 
774 	return ret;
775 }
776 
777 static inline void guc_set_lrc_tail(struct i915_request *rq)
778 {
779 	rq->context->lrc_reg_state[CTX_RING_TAIL] =
780 		intel_ring_set_tail(rq->ring, rq->tail);
781 }
782 
783 static inline int rq_prio(const struct i915_request *rq)
784 {
785 	return rq->sched.attr.priority;
786 }
787 
788 static bool is_multi_lrc_rq(struct i915_request *rq)
789 {
790 	return intel_context_is_parallel(rq->context);
791 }
792 
793 static bool can_merge_rq(struct i915_request *rq,
794 			 struct i915_request *last)
795 {
796 	return request_to_scheduling_context(rq) ==
797 		request_to_scheduling_context(last);
798 }
799 
800 static u32 wq_space_until_wrap(struct intel_context *ce)
801 {
802 	return (WQ_SIZE - ce->parallel.guc.wqi_tail);
803 }
804 
805 static void write_wqi(struct intel_context *ce, u32 wqi_size)
806 {
807 	BUILD_BUG_ON(!is_power_of_2(WQ_SIZE));
808 
809 	/*
810 	 * Ensure WQI are visible before updating tail
811 	 */
812 	intel_guc_write_barrier(ce_to_guc(ce));
813 
814 	ce->parallel.guc.wqi_tail = (ce->parallel.guc.wqi_tail + wqi_size) &
815 		(WQ_SIZE - 1);
816 	WRITE_ONCE(*ce->parallel.guc.wq_tail, ce->parallel.guc.wqi_tail);
817 }
818 
819 static int guc_wq_noop_append(struct intel_context *ce)
820 {
821 	u32 *wqi = get_wq_pointer(ce, wq_space_until_wrap(ce));
822 	u32 len_dw = wq_space_until_wrap(ce) / sizeof(u32) - 1;
823 
824 	if (!wqi)
825 		return -EBUSY;
826 
827 	GEM_BUG_ON(!FIELD_FIT(WQ_LEN_MASK, len_dw));
828 
829 	*wqi = FIELD_PREP(WQ_TYPE_MASK, WQ_TYPE_NOOP) |
830 		FIELD_PREP(WQ_LEN_MASK, len_dw);
831 	ce->parallel.guc.wqi_tail = 0;
832 
833 	return 0;
834 }
835 
836 static int __guc_wq_item_append(struct i915_request *rq)
837 {
838 	struct intel_context *ce = request_to_scheduling_context(rq);
839 	struct intel_context *child;
840 	unsigned int wqi_size = (ce->parallel.number_children + 4) *
841 		sizeof(u32);
842 	u32 *wqi;
843 	u32 len_dw = (wqi_size / sizeof(u32)) - 1;
844 	int ret;
845 
846 	/* Ensure context is in correct state updating work queue */
847 	GEM_BUG_ON(!atomic_read(&ce->guc_id.ref));
848 	GEM_BUG_ON(context_guc_id_invalid(ce));
849 	GEM_BUG_ON(context_wait_for_deregister_to_register(ce));
850 	GEM_BUG_ON(!ctx_id_mapped(ce_to_guc(ce), ce->guc_id.id));
851 
852 	/* Insert NOOP if this work queue item will wrap the tail pointer. */
853 	if (wqi_size > wq_space_until_wrap(ce)) {
854 		ret = guc_wq_noop_append(ce);
855 		if (ret)
856 			return ret;
857 	}
858 
859 	wqi = get_wq_pointer(ce, wqi_size);
860 	if (!wqi)
861 		return -EBUSY;
862 
863 	GEM_BUG_ON(!FIELD_FIT(WQ_LEN_MASK, len_dw));
864 
865 	*wqi++ = FIELD_PREP(WQ_TYPE_MASK, WQ_TYPE_MULTI_LRC) |
866 		FIELD_PREP(WQ_LEN_MASK, len_dw);
867 	*wqi++ = ce->lrc.lrca;
868 	*wqi++ = FIELD_PREP(WQ_GUC_ID_MASK, ce->guc_id.id) |
869 	       FIELD_PREP(WQ_RING_TAIL_MASK, ce->ring->tail / sizeof(u64));
870 	*wqi++ = 0;	/* fence_id */
871 	for_each_child(ce, child)
872 		*wqi++ = child->ring->tail / sizeof(u64);
873 
874 	write_wqi(ce, wqi_size);
875 
876 	return 0;
877 }
878 
879 static int guc_wq_item_append(struct intel_guc *guc,
880 			      struct i915_request *rq)
881 {
882 	struct intel_context *ce = request_to_scheduling_context(rq);
883 	int ret;
884 
885 	if (unlikely(!intel_context_is_schedulable(ce)))
886 		return 0;
887 
888 	ret = __guc_wq_item_append(rq);
889 	if (unlikely(ret == -EBUSY)) {
890 		guc->stalled_request = rq;
891 		guc->submission_stall_reason = STALL_MOVE_LRC_TAIL;
892 	}
893 
894 	return ret;
895 }
896 
897 static bool multi_lrc_submit(struct i915_request *rq)
898 {
899 	struct intel_context *ce = request_to_scheduling_context(rq);
900 
901 	intel_ring_set_tail(rq->ring, rq->tail);
902 
903 	/*
904 	 * We expect the front end (execbuf IOCTL) to set this flag on the last
905 	 * request generated from a multi-BB submission. This indicates to the
906 	 * backend (GuC interface) that we should submit this context thus
907 	 * submitting all the requests generated in parallel.
908 	 */
909 	return test_bit(I915_FENCE_FLAG_SUBMIT_PARALLEL, &rq->fence.flags) ||
910 	       !intel_context_is_schedulable(ce);
911 }
912 
913 static int guc_dequeue_one_context(struct intel_guc *guc)
914 {
915 	struct i915_sched_engine * const sched_engine = guc->sched_engine;
916 	struct i915_request *last = NULL;
917 	bool submit = false;
918 	struct rb_node *rb;
919 	int ret;
920 
921 	lockdep_assert_held(&sched_engine->lock);
922 
923 	if (guc->stalled_request) {
924 		submit = true;
925 		last = guc->stalled_request;
926 
927 		switch (guc->submission_stall_reason) {
928 		case STALL_REGISTER_CONTEXT:
929 			goto register_context;
930 		case STALL_MOVE_LRC_TAIL:
931 			goto move_lrc_tail;
932 		case STALL_ADD_REQUEST:
933 			goto add_request;
934 		default:
935 			MISSING_CASE(guc->submission_stall_reason);
936 		}
937 	}
938 
939 	while ((rb = rb_first_cached(&sched_engine->queue))) {
940 		struct i915_priolist *p = to_priolist(rb);
941 		struct i915_request *rq, *rn;
942 
943 		priolist_for_each_request_consume(rq, rn, p) {
944 			if (last && !can_merge_rq(rq, last))
945 				goto register_context;
946 
947 			list_del_init(&rq->sched.link);
948 
949 			__i915_request_submit(rq);
950 
951 			trace_i915_request_in(rq, 0);
952 			last = rq;
953 
954 			if (is_multi_lrc_rq(rq)) {
955 				/*
956 				 * We need to coalesce all multi-lrc requests in
957 				 * a relationship into a single H2G. We are
958 				 * guaranteed that all of these requests will be
959 				 * submitted sequentially.
960 				 */
961 				if (multi_lrc_submit(rq)) {
962 					submit = true;
963 					goto register_context;
964 				}
965 			} else {
966 				submit = true;
967 			}
968 		}
969 
970 		rb_erase_cached(&p->node, &sched_engine->queue);
971 		i915_priolist_free(p);
972 	}
973 
974 register_context:
975 	if (submit) {
976 		struct intel_context *ce = request_to_scheduling_context(last);
977 
978 		if (unlikely(!ctx_id_mapped(guc, ce->guc_id.id) &&
979 			     intel_context_is_schedulable(ce))) {
980 			ret = try_context_registration(ce, false);
981 			if (unlikely(ret == -EPIPE)) {
982 				goto deadlk;
983 			} else if (ret == -EBUSY) {
984 				guc->stalled_request = last;
985 				guc->submission_stall_reason =
986 					STALL_REGISTER_CONTEXT;
987 				goto schedule_tasklet;
988 			} else if (ret != 0) {
989 				GEM_WARN_ON(ret);	/* Unexpected */
990 				goto deadlk;
991 			}
992 		}
993 
994 move_lrc_tail:
995 		if (is_multi_lrc_rq(last)) {
996 			ret = guc_wq_item_append(guc, last);
997 			if (ret == -EBUSY) {
998 				goto schedule_tasklet;
999 			} else if (ret != 0) {
1000 				GEM_WARN_ON(ret);	/* Unexpected */
1001 				goto deadlk;
1002 			}
1003 		} else {
1004 			guc_set_lrc_tail(last);
1005 		}
1006 
1007 add_request:
1008 		ret = guc_add_request(guc, last);
1009 		if (unlikely(ret == -EPIPE)) {
1010 			goto deadlk;
1011 		} else if (ret == -EBUSY) {
1012 			goto schedule_tasklet;
1013 		} else if (ret != 0) {
1014 			GEM_WARN_ON(ret);	/* Unexpected */
1015 			goto deadlk;
1016 		}
1017 	}
1018 
1019 	guc->stalled_request = NULL;
1020 	guc->submission_stall_reason = STALL_NONE;
1021 	return submit;
1022 
1023 deadlk:
1024 	sched_engine->tasklet.callback = NULL;
1025 	tasklet_disable_nosync(&sched_engine->tasklet);
1026 	return false;
1027 
1028 schedule_tasklet:
1029 	tasklet_schedule(&sched_engine->tasklet);
1030 	return false;
1031 }
1032 
1033 static void guc_submission_tasklet(struct tasklet_struct *t)
1034 {
1035 	struct i915_sched_engine *sched_engine =
1036 		from_tasklet(sched_engine, t, tasklet);
1037 	unsigned long flags;
1038 	bool loop;
1039 
1040 	spin_lock_irqsave(&sched_engine->lock, flags);
1041 
1042 	do {
1043 		loop = guc_dequeue_one_context(sched_engine->private_data);
1044 	} while (loop);
1045 
1046 	i915_sched_engine_reset_on_empty(sched_engine);
1047 
1048 	spin_unlock_irqrestore(&sched_engine->lock, flags);
1049 }
1050 
1051 static void cs_irq_handler(struct intel_engine_cs *engine, u16 iir)
1052 {
1053 	if (iir & GT_RENDER_USER_INTERRUPT)
1054 		intel_engine_signal_breadcrumbs(engine);
1055 }
1056 
1057 static void __guc_context_destroy(struct intel_context *ce);
1058 static void release_guc_id(struct intel_guc *guc, struct intel_context *ce);
1059 static void guc_signal_context_fence(struct intel_context *ce);
1060 static void guc_cancel_context_requests(struct intel_context *ce);
1061 static void guc_blocked_fence_complete(struct intel_context *ce);
1062 
1063 static void scrub_guc_desc_for_outstanding_g2h(struct intel_guc *guc)
1064 {
1065 	struct intel_context *ce;
1066 	unsigned long index, flags;
1067 	bool pending_disable, pending_enable, deregister, destroyed, banned;
1068 
1069 	xa_lock_irqsave(&guc->context_lookup, flags);
1070 	xa_for_each(&guc->context_lookup, index, ce) {
1071 		/*
1072 		 * Corner case where the ref count on the object is zero but and
1073 		 * deregister G2H was lost. In this case we don't touch the ref
1074 		 * count and finish the destroy of the context.
1075 		 */
1076 		bool do_put = kref_get_unless_zero(&ce->ref);
1077 
1078 		xa_unlock(&guc->context_lookup);
1079 
1080 		if (test_bit(CONTEXT_GUC_INIT, &ce->flags) &&
1081 		    (cancel_delayed_work(&ce->guc_state.sched_disable_delay_work))) {
1082 			/* successful cancel so jump straight to close it */
1083 			intel_context_sched_disable_unpin(ce);
1084 		}
1085 
1086 		spin_lock(&ce->guc_state.lock);
1087 
1088 		/*
1089 		 * Once we are at this point submission_disabled() is guaranteed
1090 		 * to be visible to all callers who set the below flags (see above
1091 		 * flush and flushes in reset_prepare). If submission_disabled()
1092 		 * is set, the caller shouldn't set these flags.
1093 		 */
1094 
1095 		destroyed = context_destroyed(ce);
1096 		pending_enable = context_pending_enable(ce);
1097 		pending_disable = context_pending_disable(ce);
1098 		deregister = context_wait_for_deregister_to_register(ce);
1099 		banned = context_banned(ce);
1100 		init_sched_state(ce);
1101 
1102 		spin_unlock(&ce->guc_state.lock);
1103 
1104 		if (pending_enable || destroyed || deregister) {
1105 			decr_outstanding_submission_g2h(guc);
1106 			if (deregister)
1107 				guc_signal_context_fence(ce);
1108 			if (destroyed) {
1109 				intel_gt_pm_put_async(guc_to_gt(guc));
1110 				release_guc_id(guc, ce);
1111 				__guc_context_destroy(ce);
1112 			}
1113 			if (pending_enable || deregister)
1114 				intel_context_put(ce);
1115 		}
1116 
1117 		/* Not mutualy exclusive with above if statement. */
1118 		if (pending_disable) {
1119 			guc_signal_context_fence(ce);
1120 			if (banned) {
1121 				guc_cancel_context_requests(ce);
1122 				intel_engine_signal_breadcrumbs(ce->engine);
1123 			}
1124 			intel_context_sched_disable_unpin(ce);
1125 			decr_outstanding_submission_g2h(guc);
1126 
1127 			spin_lock(&ce->guc_state.lock);
1128 			guc_blocked_fence_complete(ce);
1129 			spin_unlock(&ce->guc_state.lock);
1130 
1131 			intel_context_put(ce);
1132 		}
1133 
1134 		if (do_put)
1135 			intel_context_put(ce);
1136 		xa_lock(&guc->context_lookup);
1137 	}
1138 	xa_unlock_irqrestore(&guc->context_lookup, flags);
1139 }
1140 
1141 /*
1142  * GuC stores busyness stats for each engine at context in/out boundaries. A
1143  * context 'in' logs execution start time, 'out' adds in -> out delta to total.
1144  * i915/kmd accesses 'start', 'total' and 'context id' from memory shared with
1145  * GuC.
1146  *
1147  * __i915_pmu_event_read samples engine busyness. When sampling, if context id
1148  * is valid (!= ~0) and start is non-zero, the engine is considered to be
1149  * active. For an active engine total busyness = total + (now - start), where
1150  * 'now' is the time at which the busyness is sampled. For inactive engine,
1151  * total busyness = total.
1152  *
1153  * All times are captured from GUCPMTIMESTAMP reg and are in gt clock domain.
1154  *
1155  * The start and total values provided by GuC are 32 bits and wrap around in a
1156  * few minutes. Since perf pmu provides busyness as 64 bit monotonically
1157  * increasing ns values, there is a need for this implementation to account for
1158  * overflows and extend the GuC provided values to 64 bits before returning
1159  * busyness to the user. In order to do that, a worker runs periodically at
1160  * frequency = 1/8th the time it takes for the timestamp to wrap (i.e. once in
1161  * 27 seconds for a gt clock frequency of 19.2 MHz).
1162  */
1163 
1164 #define WRAP_TIME_CLKS U32_MAX
1165 #define POLL_TIME_CLKS (WRAP_TIME_CLKS >> 3)
1166 
1167 static void
1168 __extend_last_switch(struct intel_guc *guc, u64 *prev_start, u32 new_start)
1169 {
1170 	u32 gt_stamp_hi = upper_32_bits(guc->timestamp.gt_stamp);
1171 	u32 gt_stamp_last = lower_32_bits(guc->timestamp.gt_stamp);
1172 
1173 	if (new_start == lower_32_bits(*prev_start))
1174 		return;
1175 
1176 	/*
1177 	 * When gt is unparked, we update the gt timestamp and start the ping
1178 	 * worker that updates the gt_stamp every POLL_TIME_CLKS. As long as gt
1179 	 * is unparked, all switched in contexts will have a start time that is
1180 	 * within +/- POLL_TIME_CLKS of the most recent gt_stamp.
1181 	 *
1182 	 * If neither gt_stamp nor new_start has rolled over, then the
1183 	 * gt_stamp_hi does not need to be adjusted, however if one of them has
1184 	 * rolled over, we need to adjust gt_stamp_hi accordingly.
1185 	 *
1186 	 * The below conditions address the cases of new_start rollover and
1187 	 * gt_stamp_last rollover respectively.
1188 	 */
1189 	if (new_start < gt_stamp_last &&
1190 	    (new_start - gt_stamp_last) <= POLL_TIME_CLKS)
1191 		gt_stamp_hi++;
1192 
1193 	if (new_start > gt_stamp_last &&
1194 	    (gt_stamp_last - new_start) <= POLL_TIME_CLKS && gt_stamp_hi)
1195 		gt_stamp_hi--;
1196 
1197 	*prev_start = ((u64)gt_stamp_hi << 32) | new_start;
1198 }
1199 
1200 #define record_read(map_, field_) \
1201 	iosys_map_rd_field(map_, 0, struct guc_engine_usage_record, field_)
1202 
1203 /*
1204  * GuC updates shared memory and KMD reads it. Since this is not synchronized,
1205  * we run into a race where the value read is inconsistent. Sometimes the
1206  * inconsistency is in reading the upper MSB bytes of the last_in value when
1207  * this race occurs. 2 types of cases are seen - upper 8 bits are zero and upper
1208  * 24 bits are zero. Since these are non-zero values, it is non-trivial to
1209  * determine validity of these values. Instead we read the values multiple times
1210  * until they are consistent. In test runs, 3 attempts results in consistent
1211  * values. The upper bound is set to 6 attempts and may need to be tuned as per
1212  * any new occurences.
1213  */
1214 static void __get_engine_usage_record(struct intel_engine_cs *engine,
1215 				      u32 *last_in, u32 *id, u32 *total)
1216 {
1217 	struct iosys_map rec_map = intel_guc_engine_usage_record_map(engine);
1218 	int i = 0;
1219 
1220 	do {
1221 		*last_in = record_read(&rec_map, last_switch_in_stamp);
1222 		*id = record_read(&rec_map, current_context_index);
1223 		*total = record_read(&rec_map, total_runtime);
1224 
1225 		if (record_read(&rec_map, last_switch_in_stamp) == *last_in &&
1226 		    record_read(&rec_map, current_context_index) == *id &&
1227 		    record_read(&rec_map, total_runtime) == *total)
1228 			break;
1229 	} while (++i < 6);
1230 }
1231 
1232 static void guc_update_engine_gt_clks(struct intel_engine_cs *engine)
1233 {
1234 	struct intel_engine_guc_stats *stats = &engine->stats.guc;
1235 	struct intel_guc *guc = &engine->gt->uc.guc;
1236 	u32 last_switch, ctx_id, total;
1237 
1238 	lockdep_assert_held(&guc->timestamp.lock);
1239 
1240 	__get_engine_usage_record(engine, &last_switch, &ctx_id, &total);
1241 
1242 	stats->running = ctx_id != ~0U && last_switch;
1243 	if (stats->running)
1244 		__extend_last_switch(guc, &stats->start_gt_clk, last_switch);
1245 
1246 	/*
1247 	 * Instead of adjusting the total for overflow, just add the
1248 	 * difference from previous sample stats->total_gt_clks
1249 	 */
1250 	if (total && total != ~0U) {
1251 		stats->total_gt_clks += (u32)(total - stats->prev_total);
1252 		stats->prev_total = total;
1253 	}
1254 }
1255 
1256 static u32 gpm_timestamp_shift(struct intel_gt *gt)
1257 {
1258 	intel_wakeref_t wakeref;
1259 	u32 reg, shift;
1260 
1261 	with_intel_runtime_pm(gt->uncore->rpm, wakeref)
1262 		reg = intel_uncore_read(gt->uncore, RPM_CONFIG0);
1263 
1264 	shift = (reg & GEN10_RPM_CONFIG0_CTC_SHIFT_PARAMETER_MASK) >>
1265 		GEN10_RPM_CONFIG0_CTC_SHIFT_PARAMETER_SHIFT;
1266 
1267 	return 3 - shift;
1268 }
1269 
1270 static void guc_update_pm_timestamp(struct intel_guc *guc, ktime_t *now)
1271 {
1272 	struct intel_gt *gt = guc_to_gt(guc);
1273 	u32 gt_stamp_lo, gt_stamp_hi;
1274 	u64 gpm_ts;
1275 
1276 	lockdep_assert_held(&guc->timestamp.lock);
1277 
1278 	gt_stamp_hi = upper_32_bits(guc->timestamp.gt_stamp);
1279 	gpm_ts = intel_uncore_read64_2x32(gt->uncore, MISC_STATUS0,
1280 					  MISC_STATUS1) >> guc->timestamp.shift;
1281 	gt_stamp_lo = lower_32_bits(gpm_ts);
1282 	*now = ktime_get();
1283 
1284 	if (gt_stamp_lo < lower_32_bits(guc->timestamp.gt_stamp))
1285 		gt_stamp_hi++;
1286 
1287 	guc->timestamp.gt_stamp = ((u64)gt_stamp_hi << 32) | gt_stamp_lo;
1288 }
1289 
1290 /*
1291  * Unlike the execlist mode of submission total and active times are in terms of
1292  * gt clocks. The *now parameter is retained to return the cpu time at which the
1293  * busyness was sampled.
1294  */
1295 static ktime_t guc_engine_busyness(struct intel_engine_cs *engine, ktime_t *now)
1296 {
1297 	struct intel_engine_guc_stats stats_saved, *stats = &engine->stats.guc;
1298 	struct i915_gpu_error *gpu_error = &engine->i915->gpu_error;
1299 	struct intel_gt *gt = engine->gt;
1300 	struct intel_guc *guc = &gt->uc.guc;
1301 	u64 total, gt_stamp_saved;
1302 	unsigned long flags;
1303 	u32 reset_count;
1304 	bool in_reset;
1305 
1306 	spin_lock_irqsave(&guc->timestamp.lock, flags);
1307 
1308 	/*
1309 	 * If a reset happened, we risk reading partially updated engine
1310 	 * busyness from GuC, so we just use the driver stored copy of busyness.
1311 	 * Synchronize with gt reset using reset_count and the
1312 	 * I915_RESET_BACKOFF flag. Note that reset flow updates the reset_count
1313 	 * after I915_RESET_BACKOFF flag, so ensure that the reset_count is
1314 	 * usable by checking the flag afterwards.
1315 	 */
1316 	reset_count = i915_reset_count(gpu_error);
1317 	in_reset = test_bit(I915_RESET_BACKOFF, &gt->reset.flags);
1318 
1319 	*now = ktime_get();
1320 
1321 	/*
1322 	 * The active busyness depends on start_gt_clk and gt_stamp.
1323 	 * gt_stamp is updated by i915 only when gt is awake and the
1324 	 * start_gt_clk is derived from GuC state. To get a consistent
1325 	 * view of activity, we query the GuC state only if gt is awake.
1326 	 */
1327 	if (!in_reset && intel_gt_pm_get_if_awake(gt)) {
1328 		stats_saved = *stats;
1329 		gt_stamp_saved = guc->timestamp.gt_stamp;
1330 		/*
1331 		 * Update gt_clks, then gt timestamp to simplify the 'gt_stamp -
1332 		 * start_gt_clk' calculation below for active engines.
1333 		 */
1334 		guc_update_engine_gt_clks(engine);
1335 		guc_update_pm_timestamp(guc, now);
1336 		intel_gt_pm_put_async(gt);
1337 		if (i915_reset_count(gpu_error) != reset_count) {
1338 			*stats = stats_saved;
1339 			guc->timestamp.gt_stamp = gt_stamp_saved;
1340 		}
1341 	}
1342 
1343 	total = intel_gt_clock_interval_to_ns(gt, stats->total_gt_clks);
1344 	if (stats->running) {
1345 		u64 clk = guc->timestamp.gt_stamp - stats->start_gt_clk;
1346 
1347 		total += intel_gt_clock_interval_to_ns(gt, clk);
1348 	}
1349 
1350 	spin_unlock_irqrestore(&guc->timestamp.lock, flags);
1351 
1352 	return ns_to_ktime(total);
1353 }
1354 
1355 static void guc_enable_busyness_worker(struct intel_guc *guc)
1356 {
1357 	mod_delayed_work(system_highpri_wq, &guc->timestamp.work, guc->timestamp.ping_delay);
1358 }
1359 
1360 static void guc_cancel_busyness_worker(struct intel_guc *guc)
1361 {
1362 	cancel_delayed_work_sync(&guc->timestamp.work);
1363 }
1364 
1365 static void __reset_guc_busyness_stats(struct intel_guc *guc)
1366 {
1367 	struct intel_gt *gt = guc_to_gt(guc);
1368 	struct intel_engine_cs *engine;
1369 	enum intel_engine_id id;
1370 	unsigned long flags;
1371 	ktime_t unused;
1372 
1373 	guc_cancel_busyness_worker(guc);
1374 
1375 	spin_lock_irqsave(&guc->timestamp.lock, flags);
1376 
1377 	guc_update_pm_timestamp(guc, &unused);
1378 	for_each_engine(engine, gt, id) {
1379 		guc_update_engine_gt_clks(engine);
1380 		engine->stats.guc.prev_total = 0;
1381 	}
1382 
1383 	spin_unlock_irqrestore(&guc->timestamp.lock, flags);
1384 }
1385 
1386 static void __update_guc_busyness_stats(struct intel_guc *guc)
1387 {
1388 	struct intel_gt *gt = guc_to_gt(guc);
1389 	struct intel_engine_cs *engine;
1390 	enum intel_engine_id id;
1391 	unsigned long flags;
1392 	ktime_t unused;
1393 
1394 	guc->timestamp.last_stat_jiffies = jiffies;
1395 
1396 	spin_lock_irqsave(&guc->timestamp.lock, flags);
1397 
1398 	guc_update_pm_timestamp(guc, &unused);
1399 	for_each_engine(engine, gt, id)
1400 		guc_update_engine_gt_clks(engine);
1401 
1402 	spin_unlock_irqrestore(&guc->timestamp.lock, flags);
1403 }
1404 
1405 static void guc_timestamp_ping(struct work_struct *wrk)
1406 {
1407 	struct intel_guc *guc = container_of(wrk, typeof(*guc),
1408 					     timestamp.work.work);
1409 	struct intel_uc *uc = container_of(guc, typeof(*uc), guc);
1410 	struct intel_gt *gt = guc_to_gt(guc);
1411 	intel_wakeref_t wakeref;
1412 	int srcu, ret;
1413 
1414 	/*
1415 	 * Synchronize with gt reset to make sure the worker does not
1416 	 * corrupt the engine/guc stats. NB: can't actually block waiting
1417 	 * for a reset to complete as the reset requires flushing out
1418 	 * this worker thread if started. So waiting would deadlock.
1419 	 */
1420 	ret = intel_gt_reset_trylock(gt, &srcu);
1421 	if (ret)
1422 		return;
1423 
1424 	with_intel_runtime_pm(&gt->i915->runtime_pm, wakeref)
1425 		__update_guc_busyness_stats(guc);
1426 
1427 	intel_gt_reset_unlock(gt, srcu);
1428 
1429 	guc_enable_busyness_worker(guc);
1430 }
1431 
1432 static int guc_action_enable_usage_stats(struct intel_guc *guc)
1433 {
1434 	u32 offset = intel_guc_engine_usage_offset(guc);
1435 	u32 action[] = {
1436 		INTEL_GUC_ACTION_SET_ENG_UTIL_BUFF,
1437 		offset,
1438 		0,
1439 	};
1440 
1441 	return intel_guc_send(guc, action, ARRAY_SIZE(action));
1442 }
1443 
1444 static int guc_init_engine_stats(struct intel_guc *guc)
1445 {
1446 	struct intel_gt *gt = guc_to_gt(guc);
1447 	intel_wakeref_t wakeref;
1448 	int ret;
1449 
1450 	with_intel_runtime_pm(&gt->i915->runtime_pm, wakeref)
1451 		ret = guc_action_enable_usage_stats(guc);
1452 
1453 	if (ret)
1454 		guc_err(guc, "Failed to enable usage stats: %pe\n", ERR_PTR(ret));
1455 	else
1456 		guc_enable_busyness_worker(guc);
1457 
1458 	return ret;
1459 }
1460 
1461 static void guc_fini_engine_stats(struct intel_guc *guc)
1462 {
1463 	guc_cancel_busyness_worker(guc);
1464 }
1465 
1466 void intel_guc_busyness_park(struct intel_gt *gt)
1467 {
1468 	struct intel_guc *guc = &gt->uc.guc;
1469 
1470 	if (!guc_submission_initialized(guc))
1471 		return;
1472 
1473 	/*
1474 	 * There is a race with suspend flow where the worker runs after suspend
1475 	 * and causes an unclaimed register access warning. Cancel the worker
1476 	 * synchronously here.
1477 	 */
1478 	guc_cancel_busyness_worker(guc);
1479 
1480 	/*
1481 	 * Before parking, we should sample engine busyness stats if we need to.
1482 	 * We can skip it if we are less than half a ping from the last time we
1483 	 * sampled the busyness stats.
1484 	 */
1485 	if (guc->timestamp.last_stat_jiffies &&
1486 	    !time_after(jiffies, guc->timestamp.last_stat_jiffies +
1487 			(guc->timestamp.ping_delay / 2)))
1488 		return;
1489 
1490 	__update_guc_busyness_stats(guc);
1491 }
1492 
1493 void intel_guc_busyness_unpark(struct intel_gt *gt)
1494 {
1495 	struct intel_guc *guc = &gt->uc.guc;
1496 	unsigned long flags;
1497 	ktime_t unused;
1498 
1499 	if (!guc_submission_initialized(guc))
1500 		return;
1501 
1502 	spin_lock_irqsave(&guc->timestamp.lock, flags);
1503 	guc_update_pm_timestamp(guc, &unused);
1504 	spin_unlock_irqrestore(&guc->timestamp.lock, flags);
1505 	guc_enable_busyness_worker(guc);
1506 }
1507 
1508 static inline bool
1509 submission_disabled(struct intel_guc *guc)
1510 {
1511 	struct i915_sched_engine * const sched_engine = guc->sched_engine;
1512 
1513 	return unlikely(!sched_engine ||
1514 			!__tasklet_is_enabled(&sched_engine->tasklet) ||
1515 			intel_gt_is_wedged(guc_to_gt(guc)));
1516 }
1517 
1518 static void disable_submission(struct intel_guc *guc)
1519 {
1520 	struct i915_sched_engine * const sched_engine = guc->sched_engine;
1521 
1522 	if (__tasklet_is_enabled(&sched_engine->tasklet)) {
1523 		GEM_BUG_ON(!guc->ct.enabled);
1524 		__tasklet_disable_sync_once(&sched_engine->tasklet);
1525 		sched_engine->tasklet.callback = NULL;
1526 	}
1527 }
1528 
1529 static void enable_submission(struct intel_guc *guc)
1530 {
1531 	struct i915_sched_engine * const sched_engine = guc->sched_engine;
1532 	unsigned long flags;
1533 
1534 	spin_lock_irqsave(&guc->sched_engine->lock, flags);
1535 	sched_engine->tasklet.callback = guc_submission_tasklet;
1536 	wmb();	/* Make sure callback visible */
1537 	if (!__tasklet_is_enabled(&sched_engine->tasklet) &&
1538 	    __tasklet_enable(&sched_engine->tasklet)) {
1539 		GEM_BUG_ON(!guc->ct.enabled);
1540 
1541 		/* And kick in case we missed a new request submission. */
1542 		tasklet_hi_schedule(&sched_engine->tasklet);
1543 	}
1544 	spin_unlock_irqrestore(&guc->sched_engine->lock, flags);
1545 }
1546 
1547 static void guc_flush_submissions(struct intel_guc *guc)
1548 {
1549 	struct i915_sched_engine * const sched_engine = guc->sched_engine;
1550 	unsigned long flags;
1551 
1552 	spin_lock_irqsave(&sched_engine->lock, flags);
1553 	spin_unlock_irqrestore(&sched_engine->lock, flags);
1554 }
1555 
1556 static void guc_flush_destroyed_contexts(struct intel_guc *guc);
1557 
1558 void intel_guc_submission_reset_prepare(struct intel_guc *guc)
1559 {
1560 	if (unlikely(!guc_submission_initialized(guc))) {
1561 		/* Reset called during driver load? GuC not yet initialised! */
1562 		return;
1563 	}
1564 
1565 	intel_gt_park_heartbeats(guc_to_gt(guc));
1566 	disable_submission(guc);
1567 	guc->interrupts.disable(guc);
1568 	__reset_guc_busyness_stats(guc);
1569 
1570 	/* Flush IRQ handler */
1571 	spin_lock_irq(guc_to_gt(guc)->irq_lock);
1572 	spin_unlock_irq(guc_to_gt(guc)->irq_lock);
1573 
1574 	guc_flush_submissions(guc);
1575 	guc_flush_destroyed_contexts(guc);
1576 	flush_work(&guc->ct.requests.worker);
1577 
1578 	scrub_guc_desc_for_outstanding_g2h(guc);
1579 }
1580 
1581 static struct intel_engine_cs *
1582 guc_virtual_get_sibling(struct intel_engine_cs *ve, unsigned int sibling)
1583 {
1584 	struct intel_engine_cs *engine;
1585 	intel_engine_mask_t tmp, mask = ve->mask;
1586 	unsigned int num_siblings = 0;
1587 
1588 	for_each_engine_masked(engine, ve->gt, mask, tmp)
1589 		if (num_siblings++ == sibling)
1590 			return engine;
1591 
1592 	return NULL;
1593 }
1594 
1595 static inline struct intel_engine_cs *
1596 __context_to_physical_engine(struct intel_context *ce)
1597 {
1598 	struct intel_engine_cs *engine = ce->engine;
1599 
1600 	if (intel_engine_is_virtual(engine))
1601 		engine = guc_virtual_get_sibling(engine, 0);
1602 
1603 	return engine;
1604 }
1605 
1606 static void guc_reset_state(struct intel_context *ce, u32 head, bool scrub)
1607 {
1608 	struct intel_engine_cs *engine = __context_to_physical_engine(ce);
1609 
1610 	if (!intel_context_is_schedulable(ce))
1611 		return;
1612 
1613 	GEM_BUG_ON(!intel_context_is_pinned(ce));
1614 
1615 	/*
1616 	 * We want a simple context + ring to execute the breadcrumb update.
1617 	 * We cannot rely on the context being intact across the GPU hang,
1618 	 * so clear it and rebuild just what we need for the breadcrumb.
1619 	 * All pending requests for this context will be zapped, and any
1620 	 * future request will be after userspace has had the opportunity
1621 	 * to recreate its own state.
1622 	 */
1623 	if (scrub)
1624 		lrc_init_regs(ce, engine, true);
1625 
1626 	/* Rerun the request; its payload has been neutered (if guilty). */
1627 	lrc_update_regs(ce, engine, head);
1628 }
1629 
1630 static void guc_engine_reset_prepare(struct intel_engine_cs *engine)
1631 {
1632 	if (!IS_GRAPHICS_VER(engine->i915, 11, 12))
1633 		return;
1634 
1635 	intel_engine_stop_cs(engine);
1636 
1637 	/*
1638 	 * Wa_22011802037: In addition to stopping the cs, we need
1639 	 * to wait for any pending mi force wakeups
1640 	 */
1641 	intel_engine_wait_for_pending_mi_fw(engine);
1642 }
1643 
1644 static void guc_reset_nop(struct intel_engine_cs *engine)
1645 {
1646 }
1647 
1648 static void guc_rewind_nop(struct intel_engine_cs *engine, bool stalled)
1649 {
1650 }
1651 
1652 static void
1653 __unwind_incomplete_requests(struct intel_context *ce)
1654 {
1655 	struct i915_request *rq, *rn;
1656 	struct list_head *pl;
1657 	int prio = I915_PRIORITY_INVALID;
1658 	struct i915_sched_engine * const sched_engine =
1659 		ce->engine->sched_engine;
1660 	unsigned long flags;
1661 
1662 	spin_lock_irqsave(&sched_engine->lock, flags);
1663 	spin_lock(&ce->guc_state.lock);
1664 	list_for_each_entry_safe_reverse(rq, rn,
1665 					 &ce->guc_state.requests,
1666 					 sched.link) {
1667 		if (i915_request_completed(rq))
1668 			continue;
1669 
1670 		list_del_init(&rq->sched.link);
1671 		__i915_request_unsubmit(rq);
1672 
1673 		/* Push the request back into the queue for later resubmission. */
1674 		GEM_BUG_ON(rq_prio(rq) == I915_PRIORITY_INVALID);
1675 		if (rq_prio(rq) != prio) {
1676 			prio = rq_prio(rq);
1677 			pl = i915_sched_lookup_priolist(sched_engine, prio);
1678 		}
1679 		GEM_BUG_ON(i915_sched_engine_is_empty(sched_engine));
1680 
1681 		list_add(&rq->sched.link, pl);
1682 		set_bit(I915_FENCE_FLAG_PQUEUE, &rq->fence.flags);
1683 	}
1684 	spin_unlock(&ce->guc_state.lock);
1685 	spin_unlock_irqrestore(&sched_engine->lock, flags);
1686 }
1687 
1688 static void __guc_reset_context(struct intel_context *ce, intel_engine_mask_t stalled)
1689 {
1690 	bool guilty;
1691 	struct i915_request *rq;
1692 	unsigned long flags;
1693 	u32 head;
1694 	int i, number_children = ce->parallel.number_children;
1695 	struct intel_context *parent = ce;
1696 
1697 	GEM_BUG_ON(intel_context_is_child(ce));
1698 
1699 	intel_context_get(ce);
1700 
1701 	/*
1702 	 * GuC will implicitly mark the context as non-schedulable when it sends
1703 	 * the reset notification. Make sure our state reflects this change. The
1704 	 * context will be marked enabled on resubmission.
1705 	 */
1706 	spin_lock_irqsave(&ce->guc_state.lock, flags);
1707 	clr_context_enabled(ce);
1708 	spin_unlock_irqrestore(&ce->guc_state.lock, flags);
1709 
1710 	/*
1711 	 * For each context in the relationship find the hanging request
1712 	 * resetting each context / request as needed
1713 	 */
1714 	for (i = 0; i < number_children + 1; ++i) {
1715 		if (!intel_context_is_pinned(ce))
1716 			goto next_context;
1717 
1718 		guilty = false;
1719 		rq = intel_context_get_active_request(ce);
1720 		if (!rq) {
1721 			head = ce->ring->tail;
1722 			goto out_replay;
1723 		}
1724 
1725 		if (i915_request_started(rq))
1726 			guilty = stalled & ce->engine->mask;
1727 
1728 		GEM_BUG_ON(i915_active_is_idle(&ce->active));
1729 		head = intel_ring_wrap(ce->ring, rq->head);
1730 
1731 		__i915_request_reset(rq, guilty);
1732 		i915_request_put(rq);
1733 out_replay:
1734 		guc_reset_state(ce, head, guilty);
1735 next_context:
1736 		if (i != number_children)
1737 			ce = list_next_entry(ce, parallel.child_link);
1738 	}
1739 
1740 	__unwind_incomplete_requests(parent);
1741 	intel_context_put(parent);
1742 }
1743 
1744 void intel_guc_submission_reset(struct intel_guc *guc, intel_engine_mask_t stalled)
1745 {
1746 	struct intel_context *ce;
1747 	unsigned long index;
1748 	unsigned long flags;
1749 
1750 	if (unlikely(!guc_submission_initialized(guc))) {
1751 		/* Reset called during driver load? GuC not yet initialised! */
1752 		return;
1753 	}
1754 
1755 	xa_lock_irqsave(&guc->context_lookup, flags);
1756 	xa_for_each(&guc->context_lookup, index, ce) {
1757 		if (!kref_get_unless_zero(&ce->ref))
1758 			continue;
1759 
1760 		xa_unlock(&guc->context_lookup);
1761 
1762 		if (intel_context_is_pinned(ce) &&
1763 		    !intel_context_is_child(ce))
1764 			__guc_reset_context(ce, stalled);
1765 
1766 		intel_context_put(ce);
1767 
1768 		xa_lock(&guc->context_lookup);
1769 	}
1770 	xa_unlock_irqrestore(&guc->context_lookup, flags);
1771 
1772 	/* GuC is blown away, drop all references to contexts */
1773 	xa_destroy(&guc->context_lookup);
1774 }
1775 
1776 static void guc_cancel_context_requests(struct intel_context *ce)
1777 {
1778 	struct i915_sched_engine *sched_engine = ce_to_guc(ce)->sched_engine;
1779 	struct i915_request *rq;
1780 	unsigned long flags;
1781 
1782 	/* Mark all executing requests as skipped. */
1783 	spin_lock_irqsave(&sched_engine->lock, flags);
1784 	spin_lock(&ce->guc_state.lock);
1785 	list_for_each_entry(rq, &ce->guc_state.requests, sched.link)
1786 		i915_request_put(i915_request_mark_eio(rq));
1787 	spin_unlock(&ce->guc_state.lock);
1788 	spin_unlock_irqrestore(&sched_engine->lock, flags);
1789 }
1790 
1791 static void
1792 guc_cancel_sched_engine_requests(struct i915_sched_engine *sched_engine)
1793 {
1794 	struct i915_request *rq, *rn;
1795 	struct rb_node *rb;
1796 	unsigned long flags;
1797 
1798 	/* Can be called during boot if GuC fails to load */
1799 	if (!sched_engine)
1800 		return;
1801 
1802 	/*
1803 	 * Before we call engine->cancel_requests(), we should have exclusive
1804 	 * access to the submission state. This is arranged for us by the
1805 	 * caller disabling the interrupt generation, the tasklet and other
1806 	 * threads that may then access the same state, giving us a free hand
1807 	 * to reset state. However, we still need to let lockdep be aware that
1808 	 * we know this state may be accessed in hardirq context, so we
1809 	 * disable the irq around this manipulation and we want to keep
1810 	 * the spinlock focused on its duties and not accidentally conflate
1811 	 * coverage to the submission's irq state. (Similarly, although we
1812 	 * shouldn't need to disable irq around the manipulation of the
1813 	 * submission's irq state, we also wish to remind ourselves that
1814 	 * it is irq state.)
1815 	 */
1816 	spin_lock_irqsave(&sched_engine->lock, flags);
1817 
1818 	/* Flush the queued requests to the timeline list (for retiring). */
1819 	while ((rb = rb_first_cached(&sched_engine->queue))) {
1820 		struct i915_priolist *p = to_priolist(rb);
1821 
1822 		priolist_for_each_request_consume(rq, rn, p) {
1823 			list_del_init(&rq->sched.link);
1824 
1825 			__i915_request_submit(rq);
1826 
1827 			i915_request_put(i915_request_mark_eio(rq));
1828 		}
1829 
1830 		rb_erase_cached(&p->node, &sched_engine->queue);
1831 		i915_priolist_free(p);
1832 	}
1833 
1834 	/* Remaining _unready_ requests will be nop'ed when submitted */
1835 
1836 	sched_engine->queue_priority_hint = INT_MIN;
1837 	sched_engine->queue = RB_ROOT_CACHED;
1838 
1839 	spin_unlock_irqrestore(&sched_engine->lock, flags);
1840 }
1841 
1842 void intel_guc_submission_cancel_requests(struct intel_guc *guc)
1843 {
1844 	struct intel_context *ce;
1845 	unsigned long index;
1846 	unsigned long flags;
1847 
1848 	xa_lock_irqsave(&guc->context_lookup, flags);
1849 	xa_for_each(&guc->context_lookup, index, ce) {
1850 		if (!kref_get_unless_zero(&ce->ref))
1851 			continue;
1852 
1853 		xa_unlock(&guc->context_lookup);
1854 
1855 		if (intel_context_is_pinned(ce) &&
1856 		    !intel_context_is_child(ce))
1857 			guc_cancel_context_requests(ce);
1858 
1859 		intel_context_put(ce);
1860 
1861 		xa_lock(&guc->context_lookup);
1862 	}
1863 	xa_unlock_irqrestore(&guc->context_lookup, flags);
1864 
1865 	guc_cancel_sched_engine_requests(guc->sched_engine);
1866 
1867 	/* GuC is blown away, drop all references to contexts */
1868 	xa_destroy(&guc->context_lookup);
1869 }
1870 
1871 void intel_guc_submission_reset_finish(struct intel_guc *guc)
1872 {
1873 	/* Reset called during driver load or during wedge? */
1874 	if (unlikely(!guc_submission_initialized(guc) ||
1875 		     intel_gt_is_wedged(guc_to_gt(guc)))) {
1876 		return;
1877 	}
1878 
1879 	/*
1880 	 * Technically possible for either of these values to be non-zero here,
1881 	 * but very unlikely + harmless. Regardless let's add a warn so we can
1882 	 * see in CI if this happens frequently / a precursor to taking down the
1883 	 * machine.
1884 	 */
1885 	GEM_WARN_ON(atomic_read(&guc->outstanding_submission_g2h));
1886 	atomic_set(&guc->outstanding_submission_g2h, 0);
1887 
1888 	intel_guc_global_policies_update(guc);
1889 	enable_submission(guc);
1890 	intel_gt_unpark_heartbeats(guc_to_gt(guc));
1891 }
1892 
1893 static void destroyed_worker_func(struct work_struct *w);
1894 static void reset_fail_worker_func(struct work_struct *w);
1895 
1896 /*
1897  * Set up the memory resources to be shared with the GuC (via the GGTT)
1898  * at firmware loading time.
1899  */
1900 int intel_guc_submission_init(struct intel_guc *guc)
1901 {
1902 	struct intel_gt *gt = guc_to_gt(guc);
1903 	int ret;
1904 
1905 	if (guc->submission_initialized)
1906 		return 0;
1907 
1908 	if (GUC_SUBMIT_VER(guc) < MAKE_GUC_VER(1, 0, 0)) {
1909 		ret = guc_lrc_desc_pool_create_v69(guc);
1910 		if (ret)
1911 			return ret;
1912 	}
1913 
1914 	guc->submission_state.guc_ids_bitmap =
1915 		bitmap_zalloc(NUMBER_MULTI_LRC_GUC_ID(guc), GFP_KERNEL);
1916 	if (!guc->submission_state.guc_ids_bitmap) {
1917 		ret = -ENOMEM;
1918 		goto destroy_pool;
1919 	}
1920 
1921 	guc->timestamp.ping_delay = (POLL_TIME_CLKS / gt->clock_frequency + 1) * HZ;
1922 	guc->timestamp.shift = gpm_timestamp_shift(gt);
1923 	guc->submission_initialized = true;
1924 
1925 	return 0;
1926 
1927 destroy_pool:
1928 	guc_lrc_desc_pool_destroy_v69(guc);
1929 
1930 	return ret;
1931 }
1932 
1933 void intel_guc_submission_fini(struct intel_guc *guc)
1934 {
1935 	if (!guc->submission_initialized)
1936 		return;
1937 
1938 	guc_flush_destroyed_contexts(guc);
1939 	guc_lrc_desc_pool_destroy_v69(guc);
1940 	i915_sched_engine_put(guc->sched_engine);
1941 	bitmap_free(guc->submission_state.guc_ids_bitmap);
1942 	guc->submission_initialized = false;
1943 }
1944 
1945 static inline void queue_request(struct i915_sched_engine *sched_engine,
1946 				 struct i915_request *rq,
1947 				 int prio)
1948 {
1949 	GEM_BUG_ON(!list_empty(&rq->sched.link));
1950 	list_add_tail(&rq->sched.link,
1951 		      i915_sched_lookup_priolist(sched_engine, prio));
1952 	set_bit(I915_FENCE_FLAG_PQUEUE, &rq->fence.flags);
1953 	tasklet_hi_schedule(&sched_engine->tasklet);
1954 }
1955 
1956 static int guc_bypass_tasklet_submit(struct intel_guc *guc,
1957 				     struct i915_request *rq)
1958 {
1959 	int ret = 0;
1960 
1961 	__i915_request_submit(rq);
1962 
1963 	trace_i915_request_in(rq, 0);
1964 
1965 	if (is_multi_lrc_rq(rq)) {
1966 		if (multi_lrc_submit(rq)) {
1967 			ret = guc_wq_item_append(guc, rq);
1968 			if (!ret)
1969 				ret = guc_add_request(guc, rq);
1970 		}
1971 	} else {
1972 		guc_set_lrc_tail(rq);
1973 		ret = guc_add_request(guc, rq);
1974 	}
1975 
1976 	if (unlikely(ret == -EPIPE))
1977 		disable_submission(guc);
1978 
1979 	return ret;
1980 }
1981 
1982 static bool need_tasklet(struct intel_guc *guc, struct i915_request *rq)
1983 {
1984 	struct i915_sched_engine *sched_engine = rq->engine->sched_engine;
1985 	struct intel_context *ce = request_to_scheduling_context(rq);
1986 
1987 	return submission_disabled(guc) || guc->stalled_request ||
1988 		!i915_sched_engine_is_empty(sched_engine) ||
1989 		!ctx_id_mapped(guc, ce->guc_id.id);
1990 }
1991 
1992 static void guc_submit_request(struct i915_request *rq)
1993 {
1994 	struct i915_sched_engine *sched_engine = rq->engine->sched_engine;
1995 	struct intel_guc *guc = &rq->engine->gt->uc.guc;
1996 	unsigned long flags;
1997 
1998 	/* Will be called from irq-context when using foreign fences. */
1999 	spin_lock_irqsave(&sched_engine->lock, flags);
2000 
2001 	if (need_tasklet(guc, rq))
2002 		queue_request(sched_engine, rq, rq_prio(rq));
2003 	else if (guc_bypass_tasklet_submit(guc, rq) == -EBUSY)
2004 		tasklet_hi_schedule(&sched_engine->tasklet);
2005 
2006 	spin_unlock_irqrestore(&sched_engine->lock, flags);
2007 }
2008 
2009 static int new_guc_id(struct intel_guc *guc, struct intel_context *ce)
2010 {
2011 	int ret;
2012 
2013 	GEM_BUG_ON(intel_context_is_child(ce));
2014 
2015 	if (intel_context_is_parent(ce))
2016 		ret = bitmap_find_free_region(guc->submission_state.guc_ids_bitmap,
2017 					      NUMBER_MULTI_LRC_GUC_ID(guc),
2018 					      order_base_2(ce->parallel.number_children
2019 							   + 1));
2020 	else
2021 		ret = ida_simple_get(&guc->submission_state.guc_ids,
2022 				     NUMBER_MULTI_LRC_GUC_ID(guc),
2023 				     guc->submission_state.num_guc_ids,
2024 				     GFP_KERNEL | __GFP_RETRY_MAYFAIL |
2025 				     __GFP_NOWARN);
2026 	if (unlikely(ret < 0))
2027 		return ret;
2028 
2029 	if (!intel_context_is_parent(ce))
2030 		++guc->submission_state.guc_ids_in_use;
2031 
2032 	ce->guc_id.id = ret;
2033 	return 0;
2034 }
2035 
2036 static void __release_guc_id(struct intel_guc *guc, struct intel_context *ce)
2037 {
2038 	GEM_BUG_ON(intel_context_is_child(ce));
2039 
2040 	if (!context_guc_id_invalid(ce)) {
2041 		if (intel_context_is_parent(ce)) {
2042 			bitmap_release_region(guc->submission_state.guc_ids_bitmap,
2043 					      ce->guc_id.id,
2044 					      order_base_2(ce->parallel.number_children
2045 							   + 1));
2046 		} else {
2047 			--guc->submission_state.guc_ids_in_use;
2048 			ida_simple_remove(&guc->submission_state.guc_ids,
2049 					  ce->guc_id.id);
2050 		}
2051 		clr_ctx_id_mapping(guc, ce->guc_id.id);
2052 		set_context_guc_id_invalid(ce);
2053 	}
2054 	if (!list_empty(&ce->guc_id.link))
2055 		list_del_init(&ce->guc_id.link);
2056 }
2057 
2058 static void release_guc_id(struct intel_guc *guc, struct intel_context *ce)
2059 {
2060 	unsigned long flags;
2061 
2062 	spin_lock_irqsave(&guc->submission_state.lock, flags);
2063 	__release_guc_id(guc, ce);
2064 	spin_unlock_irqrestore(&guc->submission_state.lock, flags);
2065 }
2066 
2067 static int steal_guc_id(struct intel_guc *guc, struct intel_context *ce)
2068 {
2069 	struct intel_context *cn;
2070 
2071 	lockdep_assert_held(&guc->submission_state.lock);
2072 	GEM_BUG_ON(intel_context_is_child(ce));
2073 	GEM_BUG_ON(intel_context_is_parent(ce));
2074 
2075 	if (!list_empty(&guc->submission_state.guc_id_list)) {
2076 		cn = list_first_entry(&guc->submission_state.guc_id_list,
2077 				      struct intel_context,
2078 				      guc_id.link);
2079 
2080 		GEM_BUG_ON(atomic_read(&cn->guc_id.ref));
2081 		GEM_BUG_ON(context_guc_id_invalid(cn));
2082 		GEM_BUG_ON(intel_context_is_child(cn));
2083 		GEM_BUG_ON(intel_context_is_parent(cn));
2084 
2085 		list_del_init(&cn->guc_id.link);
2086 		ce->guc_id.id = cn->guc_id.id;
2087 
2088 		spin_lock(&cn->guc_state.lock);
2089 		clr_context_registered(cn);
2090 		spin_unlock(&cn->guc_state.lock);
2091 
2092 		set_context_guc_id_invalid(cn);
2093 
2094 #ifdef CONFIG_DRM_I915_SELFTEST
2095 		guc->number_guc_id_stolen++;
2096 #endif
2097 
2098 		return 0;
2099 	} else {
2100 		return -EAGAIN;
2101 	}
2102 }
2103 
2104 static int assign_guc_id(struct intel_guc *guc, struct intel_context *ce)
2105 {
2106 	int ret;
2107 
2108 	lockdep_assert_held(&guc->submission_state.lock);
2109 	GEM_BUG_ON(intel_context_is_child(ce));
2110 
2111 	ret = new_guc_id(guc, ce);
2112 	if (unlikely(ret < 0)) {
2113 		if (intel_context_is_parent(ce))
2114 			return -ENOSPC;
2115 
2116 		ret = steal_guc_id(guc, ce);
2117 		if (ret < 0)
2118 			return ret;
2119 	}
2120 
2121 	if (intel_context_is_parent(ce)) {
2122 		struct intel_context *child;
2123 		int i = 1;
2124 
2125 		for_each_child(ce, child)
2126 			child->guc_id.id = ce->guc_id.id + i++;
2127 	}
2128 
2129 	return 0;
2130 }
2131 
2132 #define PIN_GUC_ID_TRIES	4
2133 static int pin_guc_id(struct intel_guc *guc, struct intel_context *ce)
2134 {
2135 	int ret = 0;
2136 	unsigned long flags, tries = PIN_GUC_ID_TRIES;
2137 
2138 	GEM_BUG_ON(atomic_read(&ce->guc_id.ref));
2139 
2140 try_again:
2141 	spin_lock_irqsave(&guc->submission_state.lock, flags);
2142 
2143 	might_lock(&ce->guc_state.lock);
2144 
2145 	if (context_guc_id_invalid(ce)) {
2146 		ret = assign_guc_id(guc, ce);
2147 		if (ret)
2148 			goto out_unlock;
2149 		ret = 1;	/* Indidcates newly assigned guc_id */
2150 	}
2151 	if (!list_empty(&ce->guc_id.link))
2152 		list_del_init(&ce->guc_id.link);
2153 	atomic_inc(&ce->guc_id.ref);
2154 
2155 out_unlock:
2156 	spin_unlock_irqrestore(&guc->submission_state.lock, flags);
2157 
2158 	/*
2159 	 * -EAGAIN indicates no guc_id are available, let's retire any
2160 	 * outstanding requests to see if that frees up a guc_id. If the first
2161 	 * retire didn't help, insert a sleep with the timeslice duration before
2162 	 * attempting to retire more requests. Double the sleep period each
2163 	 * subsequent pass before finally giving up. The sleep period has max of
2164 	 * 100ms and minimum of 1ms.
2165 	 */
2166 	if (ret == -EAGAIN && --tries) {
2167 		if (PIN_GUC_ID_TRIES - tries > 1) {
2168 			unsigned int timeslice_shifted =
2169 				ce->engine->props.timeslice_duration_ms <<
2170 				(PIN_GUC_ID_TRIES - tries - 2);
2171 			unsigned int max = min_t(unsigned int, 100,
2172 						 timeslice_shifted);
2173 
2174 			msleep(max_t(unsigned int, max, 1));
2175 		}
2176 		intel_gt_retire_requests(guc_to_gt(guc));
2177 		goto try_again;
2178 	}
2179 
2180 	return ret;
2181 }
2182 
2183 static void unpin_guc_id(struct intel_guc *guc, struct intel_context *ce)
2184 {
2185 	unsigned long flags;
2186 
2187 	GEM_BUG_ON(atomic_read(&ce->guc_id.ref) < 0);
2188 	GEM_BUG_ON(intel_context_is_child(ce));
2189 
2190 	if (unlikely(context_guc_id_invalid(ce) ||
2191 		     intel_context_is_parent(ce)))
2192 		return;
2193 
2194 	spin_lock_irqsave(&guc->submission_state.lock, flags);
2195 	if (!context_guc_id_invalid(ce) && list_empty(&ce->guc_id.link) &&
2196 	    !atomic_read(&ce->guc_id.ref))
2197 		list_add_tail(&ce->guc_id.link,
2198 			      &guc->submission_state.guc_id_list);
2199 	spin_unlock_irqrestore(&guc->submission_state.lock, flags);
2200 }
2201 
2202 static int __guc_action_register_multi_lrc_v69(struct intel_guc *guc,
2203 					       struct intel_context *ce,
2204 					       u32 guc_id,
2205 					       u32 offset,
2206 					       bool loop)
2207 {
2208 	struct intel_context *child;
2209 	u32 action[4 + MAX_ENGINE_INSTANCE];
2210 	int len = 0;
2211 
2212 	GEM_BUG_ON(ce->parallel.number_children > MAX_ENGINE_INSTANCE);
2213 
2214 	action[len++] = INTEL_GUC_ACTION_REGISTER_CONTEXT_MULTI_LRC;
2215 	action[len++] = guc_id;
2216 	action[len++] = ce->parallel.number_children + 1;
2217 	action[len++] = offset;
2218 	for_each_child(ce, child) {
2219 		offset += sizeof(struct guc_lrc_desc_v69);
2220 		action[len++] = offset;
2221 	}
2222 
2223 	return guc_submission_send_busy_loop(guc, action, len, 0, loop);
2224 }
2225 
2226 static int __guc_action_register_multi_lrc_v70(struct intel_guc *guc,
2227 					       struct intel_context *ce,
2228 					       struct guc_ctxt_registration_info *info,
2229 					       bool loop)
2230 {
2231 	struct intel_context *child;
2232 	u32 action[13 + (MAX_ENGINE_INSTANCE * 2)];
2233 	int len = 0;
2234 	u32 next_id;
2235 
2236 	GEM_BUG_ON(ce->parallel.number_children > MAX_ENGINE_INSTANCE);
2237 
2238 	action[len++] = INTEL_GUC_ACTION_REGISTER_CONTEXT_MULTI_LRC;
2239 	action[len++] = info->flags;
2240 	action[len++] = info->context_idx;
2241 	action[len++] = info->engine_class;
2242 	action[len++] = info->engine_submit_mask;
2243 	action[len++] = info->wq_desc_lo;
2244 	action[len++] = info->wq_desc_hi;
2245 	action[len++] = info->wq_base_lo;
2246 	action[len++] = info->wq_base_hi;
2247 	action[len++] = info->wq_size;
2248 	action[len++] = ce->parallel.number_children + 1;
2249 	action[len++] = info->hwlrca_lo;
2250 	action[len++] = info->hwlrca_hi;
2251 
2252 	next_id = info->context_idx + 1;
2253 	for_each_child(ce, child) {
2254 		GEM_BUG_ON(next_id++ != child->guc_id.id);
2255 
2256 		/*
2257 		 * NB: GuC interface supports 64 bit LRCA even though i915/HW
2258 		 * only supports 32 bit currently.
2259 		 */
2260 		action[len++] = lower_32_bits(child->lrc.lrca);
2261 		action[len++] = upper_32_bits(child->lrc.lrca);
2262 	}
2263 
2264 	GEM_BUG_ON(len > ARRAY_SIZE(action));
2265 
2266 	return guc_submission_send_busy_loop(guc, action, len, 0, loop);
2267 }
2268 
2269 static int __guc_action_register_context_v69(struct intel_guc *guc,
2270 					     u32 guc_id,
2271 					     u32 offset,
2272 					     bool loop)
2273 {
2274 	u32 action[] = {
2275 		INTEL_GUC_ACTION_REGISTER_CONTEXT,
2276 		guc_id,
2277 		offset,
2278 	};
2279 
2280 	return guc_submission_send_busy_loop(guc, action, ARRAY_SIZE(action),
2281 					     0, loop);
2282 }
2283 
2284 static int __guc_action_register_context_v70(struct intel_guc *guc,
2285 					     struct guc_ctxt_registration_info *info,
2286 					     bool loop)
2287 {
2288 	u32 action[] = {
2289 		INTEL_GUC_ACTION_REGISTER_CONTEXT,
2290 		info->flags,
2291 		info->context_idx,
2292 		info->engine_class,
2293 		info->engine_submit_mask,
2294 		info->wq_desc_lo,
2295 		info->wq_desc_hi,
2296 		info->wq_base_lo,
2297 		info->wq_base_hi,
2298 		info->wq_size,
2299 		info->hwlrca_lo,
2300 		info->hwlrca_hi,
2301 	};
2302 
2303 	return guc_submission_send_busy_loop(guc, action, ARRAY_SIZE(action),
2304 					     0, loop);
2305 }
2306 
2307 static void prepare_context_registration_info_v69(struct intel_context *ce);
2308 static void prepare_context_registration_info_v70(struct intel_context *ce,
2309 						  struct guc_ctxt_registration_info *info);
2310 
2311 static int
2312 register_context_v69(struct intel_guc *guc, struct intel_context *ce, bool loop)
2313 {
2314 	u32 offset = intel_guc_ggtt_offset(guc, guc->lrc_desc_pool_v69) +
2315 		ce->guc_id.id * sizeof(struct guc_lrc_desc_v69);
2316 
2317 	prepare_context_registration_info_v69(ce);
2318 
2319 	if (intel_context_is_parent(ce))
2320 		return __guc_action_register_multi_lrc_v69(guc, ce, ce->guc_id.id,
2321 							   offset, loop);
2322 	else
2323 		return __guc_action_register_context_v69(guc, ce->guc_id.id,
2324 							 offset, loop);
2325 }
2326 
2327 static int
2328 register_context_v70(struct intel_guc *guc, struct intel_context *ce, bool loop)
2329 {
2330 	struct guc_ctxt_registration_info info;
2331 
2332 	prepare_context_registration_info_v70(ce, &info);
2333 
2334 	if (intel_context_is_parent(ce))
2335 		return __guc_action_register_multi_lrc_v70(guc, ce, &info, loop);
2336 	else
2337 		return __guc_action_register_context_v70(guc, &info, loop);
2338 }
2339 
2340 static int register_context(struct intel_context *ce, bool loop)
2341 {
2342 	struct intel_guc *guc = ce_to_guc(ce);
2343 	int ret;
2344 
2345 	GEM_BUG_ON(intel_context_is_child(ce));
2346 	trace_intel_context_register(ce);
2347 
2348 	if (GUC_SUBMIT_VER(guc) >= MAKE_GUC_VER(1, 0, 0))
2349 		ret = register_context_v70(guc, ce, loop);
2350 	else
2351 		ret = register_context_v69(guc, ce, loop);
2352 
2353 	if (likely(!ret)) {
2354 		unsigned long flags;
2355 
2356 		spin_lock_irqsave(&ce->guc_state.lock, flags);
2357 		set_context_registered(ce);
2358 		spin_unlock_irqrestore(&ce->guc_state.lock, flags);
2359 
2360 		if (GUC_SUBMIT_VER(guc) >= MAKE_GUC_VER(1, 0, 0))
2361 			guc_context_policy_init_v70(ce, loop);
2362 	}
2363 
2364 	return ret;
2365 }
2366 
2367 static int __guc_action_deregister_context(struct intel_guc *guc,
2368 					   u32 guc_id)
2369 {
2370 	u32 action[] = {
2371 		INTEL_GUC_ACTION_DEREGISTER_CONTEXT,
2372 		guc_id,
2373 	};
2374 
2375 	return guc_submission_send_busy_loop(guc, action, ARRAY_SIZE(action),
2376 					     G2H_LEN_DW_DEREGISTER_CONTEXT,
2377 					     true);
2378 }
2379 
2380 static int deregister_context(struct intel_context *ce, u32 guc_id)
2381 {
2382 	struct intel_guc *guc = ce_to_guc(ce);
2383 
2384 	GEM_BUG_ON(intel_context_is_child(ce));
2385 	trace_intel_context_deregister(ce);
2386 
2387 	return __guc_action_deregister_context(guc, guc_id);
2388 }
2389 
2390 static inline void clear_children_join_go_memory(struct intel_context *ce)
2391 {
2392 	struct parent_scratch *ps = __get_parent_scratch(ce);
2393 	int i;
2394 
2395 	ps->go.semaphore = 0;
2396 	for (i = 0; i < ce->parallel.number_children + 1; ++i)
2397 		ps->join[i].semaphore = 0;
2398 }
2399 
2400 static inline u32 get_children_go_value(struct intel_context *ce)
2401 {
2402 	return __get_parent_scratch(ce)->go.semaphore;
2403 }
2404 
2405 static inline u32 get_children_join_value(struct intel_context *ce,
2406 					  u8 child_index)
2407 {
2408 	return __get_parent_scratch(ce)->join[child_index].semaphore;
2409 }
2410 
2411 struct context_policy {
2412 	u32 count;
2413 	struct guc_update_context_policy h2g;
2414 };
2415 
2416 static u32 __guc_context_policy_action_size(struct context_policy *policy)
2417 {
2418 	size_t bytes = sizeof(policy->h2g.header) +
2419 		       (sizeof(policy->h2g.klv[0]) * policy->count);
2420 
2421 	return bytes / sizeof(u32);
2422 }
2423 
2424 static void __guc_context_policy_start_klv(struct context_policy *policy, u16 guc_id)
2425 {
2426 	policy->h2g.header.action = INTEL_GUC_ACTION_HOST2GUC_UPDATE_CONTEXT_POLICIES;
2427 	policy->h2g.header.ctx_id = guc_id;
2428 	policy->count = 0;
2429 }
2430 
2431 #define MAKE_CONTEXT_POLICY_ADD(func, id) \
2432 static void __guc_context_policy_add_##func(struct context_policy *policy, u32 data) \
2433 { \
2434 	GEM_BUG_ON(policy->count >= GUC_CONTEXT_POLICIES_KLV_NUM_IDS); \
2435 	policy->h2g.klv[policy->count].kl = \
2436 		FIELD_PREP(GUC_KLV_0_KEY, GUC_CONTEXT_POLICIES_KLV_ID_##id) | \
2437 		FIELD_PREP(GUC_KLV_0_LEN, 1); \
2438 	policy->h2g.klv[policy->count].value = data; \
2439 	policy->count++; \
2440 }
2441 
2442 MAKE_CONTEXT_POLICY_ADD(execution_quantum, EXECUTION_QUANTUM)
2443 MAKE_CONTEXT_POLICY_ADD(preemption_timeout, PREEMPTION_TIMEOUT)
2444 MAKE_CONTEXT_POLICY_ADD(priority, SCHEDULING_PRIORITY)
2445 MAKE_CONTEXT_POLICY_ADD(preempt_to_idle, PREEMPT_TO_IDLE_ON_QUANTUM_EXPIRY)
2446 
2447 #undef MAKE_CONTEXT_POLICY_ADD
2448 
2449 static int __guc_context_set_context_policies(struct intel_guc *guc,
2450 					      struct context_policy *policy,
2451 					      bool loop)
2452 {
2453 	return guc_submission_send_busy_loop(guc, (u32 *)&policy->h2g,
2454 					__guc_context_policy_action_size(policy),
2455 					0, loop);
2456 }
2457 
2458 static int guc_context_policy_init_v70(struct intel_context *ce, bool loop)
2459 {
2460 	struct intel_engine_cs *engine = ce->engine;
2461 	struct intel_guc *guc = &engine->gt->uc.guc;
2462 	struct context_policy policy;
2463 	u32 execution_quantum;
2464 	u32 preemption_timeout;
2465 	unsigned long flags;
2466 	int ret;
2467 
2468 	/* NB: For both of these, zero means disabled. */
2469 	GEM_BUG_ON(overflows_type(engine->props.timeslice_duration_ms * 1000,
2470 				  execution_quantum));
2471 	GEM_BUG_ON(overflows_type(engine->props.preempt_timeout_ms * 1000,
2472 				  preemption_timeout));
2473 	execution_quantum = engine->props.timeslice_duration_ms * 1000;
2474 	preemption_timeout = engine->props.preempt_timeout_ms * 1000;
2475 
2476 	__guc_context_policy_start_klv(&policy, ce->guc_id.id);
2477 
2478 	__guc_context_policy_add_priority(&policy, ce->guc_state.prio);
2479 	__guc_context_policy_add_execution_quantum(&policy, execution_quantum);
2480 	__guc_context_policy_add_preemption_timeout(&policy, preemption_timeout);
2481 
2482 	if (engine->flags & I915_ENGINE_WANT_FORCED_PREEMPTION)
2483 		__guc_context_policy_add_preempt_to_idle(&policy, 1);
2484 
2485 	ret = __guc_context_set_context_policies(guc, &policy, loop);
2486 
2487 	spin_lock_irqsave(&ce->guc_state.lock, flags);
2488 	if (ret != 0)
2489 		set_context_policy_required(ce);
2490 	else
2491 		clr_context_policy_required(ce);
2492 	spin_unlock_irqrestore(&ce->guc_state.lock, flags);
2493 
2494 	return ret;
2495 }
2496 
2497 static void guc_context_policy_init_v69(struct intel_engine_cs *engine,
2498 					struct guc_lrc_desc_v69 *desc)
2499 {
2500 	desc->policy_flags = 0;
2501 
2502 	if (engine->flags & I915_ENGINE_WANT_FORCED_PREEMPTION)
2503 		desc->policy_flags |= CONTEXT_POLICY_FLAG_PREEMPT_TO_IDLE_V69;
2504 
2505 	/* NB: For both of these, zero means disabled. */
2506 	GEM_BUG_ON(overflows_type(engine->props.timeslice_duration_ms * 1000,
2507 				  desc->execution_quantum));
2508 	GEM_BUG_ON(overflows_type(engine->props.preempt_timeout_ms * 1000,
2509 				  desc->preemption_timeout));
2510 	desc->execution_quantum = engine->props.timeslice_duration_ms * 1000;
2511 	desc->preemption_timeout = engine->props.preempt_timeout_ms * 1000;
2512 }
2513 
2514 static u32 map_guc_prio_to_lrc_desc_prio(u8 prio)
2515 {
2516 	/*
2517 	 * this matches the mapping we do in map_i915_prio_to_guc_prio()
2518 	 * (e.g. prio < I915_PRIORITY_NORMAL maps to GUC_CLIENT_PRIORITY_NORMAL)
2519 	 */
2520 	switch (prio) {
2521 	default:
2522 		MISSING_CASE(prio);
2523 		fallthrough;
2524 	case GUC_CLIENT_PRIORITY_KMD_NORMAL:
2525 		return GEN12_CTX_PRIORITY_NORMAL;
2526 	case GUC_CLIENT_PRIORITY_NORMAL:
2527 		return GEN12_CTX_PRIORITY_LOW;
2528 	case GUC_CLIENT_PRIORITY_HIGH:
2529 	case GUC_CLIENT_PRIORITY_KMD_HIGH:
2530 		return GEN12_CTX_PRIORITY_HIGH;
2531 	}
2532 }
2533 
2534 static void prepare_context_registration_info_v69(struct intel_context *ce)
2535 {
2536 	struct intel_engine_cs *engine = ce->engine;
2537 	struct intel_guc *guc = &engine->gt->uc.guc;
2538 	u32 ctx_id = ce->guc_id.id;
2539 	struct guc_lrc_desc_v69 *desc;
2540 	struct intel_context *child;
2541 
2542 	GEM_BUG_ON(!engine->mask);
2543 
2544 	/*
2545 	 * Ensure LRC + CT vmas are is same region as write barrier is done
2546 	 * based on CT vma region.
2547 	 */
2548 	GEM_BUG_ON(i915_gem_object_is_lmem(guc->ct.vma->obj) !=
2549 		   i915_gem_object_is_lmem(ce->ring->vma->obj));
2550 
2551 	desc = __get_lrc_desc_v69(guc, ctx_id);
2552 	GEM_BUG_ON(!desc);
2553 	desc->engine_class = engine_class_to_guc_class(engine->class);
2554 	desc->engine_submit_mask = engine->logical_mask;
2555 	desc->hw_context_desc = ce->lrc.lrca;
2556 	desc->priority = ce->guc_state.prio;
2557 	desc->context_flags = CONTEXT_REGISTRATION_FLAG_KMD;
2558 	guc_context_policy_init_v69(engine, desc);
2559 
2560 	/*
2561 	 * If context is a parent, we need to register a process descriptor
2562 	 * describing a work queue and register all child contexts.
2563 	 */
2564 	if (intel_context_is_parent(ce)) {
2565 		struct guc_process_desc_v69 *pdesc;
2566 
2567 		ce->parallel.guc.wqi_tail = 0;
2568 		ce->parallel.guc.wqi_head = 0;
2569 
2570 		desc->process_desc = i915_ggtt_offset(ce->state) +
2571 			__get_parent_scratch_offset(ce);
2572 		desc->wq_addr = i915_ggtt_offset(ce->state) +
2573 			__get_wq_offset(ce);
2574 		desc->wq_size = WQ_SIZE;
2575 
2576 		pdesc = __get_process_desc_v69(ce);
2577 		memset(pdesc, 0, sizeof(*(pdesc)));
2578 		pdesc->stage_id = ce->guc_id.id;
2579 		pdesc->wq_base_addr = desc->wq_addr;
2580 		pdesc->wq_size_bytes = desc->wq_size;
2581 		pdesc->wq_status = WQ_STATUS_ACTIVE;
2582 
2583 		ce->parallel.guc.wq_head = &pdesc->head;
2584 		ce->parallel.guc.wq_tail = &pdesc->tail;
2585 		ce->parallel.guc.wq_status = &pdesc->wq_status;
2586 
2587 		for_each_child(ce, child) {
2588 			desc = __get_lrc_desc_v69(guc, child->guc_id.id);
2589 
2590 			desc->engine_class =
2591 				engine_class_to_guc_class(engine->class);
2592 			desc->hw_context_desc = child->lrc.lrca;
2593 			desc->priority = ce->guc_state.prio;
2594 			desc->context_flags = CONTEXT_REGISTRATION_FLAG_KMD;
2595 			guc_context_policy_init_v69(engine, desc);
2596 		}
2597 
2598 		clear_children_join_go_memory(ce);
2599 	}
2600 }
2601 
2602 static void prepare_context_registration_info_v70(struct intel_context *ce,
2603 						  struct guc_ctxt_registration_info *info)
2604 {
2605 	struct intel_engine_cs *engine = ce->engine;
2606 	struct intel_guc *guc = &engine->gt->uc.guc;
2607 	u32 ctx_id = ce->guc_id.id;
2608 
2609 	GEM_BUG_ON(!engine->mask);
2610 
2611 	/*
2612 	 * Ensure LRC + CT vmas are is same region as write barrier is done
2613 	 * based on CT vma region.
2614 	 */
2615 	GEM_BUG_ON(i915_gem_object_is_lmem(guc->ct.vma->obj) !=
2616 		   i915_gem_object_is_lmem(ce->ring->vma->obj));
2617 
2618 	memset(info, 0, sizeof(*info));
2619 	info->context_idx = ctx_id;
2620 	info->engine_class = engine_class_to_guc_class(engine->class);
2621 	info->engine_submit_mask = engine->logical_mask;
2622 	/*
2623 	 * NB: GuC interface supports 64 bit LRCA even though i915/HW
2624 	 * only supports 32 bit currently.
2625 	 */
2626 	info->hwlrca_lo = lower_32_bits(ce->lrc.lrca);
2627 	info->hwlrca_hi = upper_32_bits(ce->lrc.lrca);
2628 	if (engine->flags & I915_ENGINE_HAS_EU_PRIORITY)
2629 		info->hwlrca_lo |= map_guc_prio_to_lrc_desc_prio(ce->guc_state.prio);
2630 	info->flags = CONTEXT_REGISTRATION_FLAG_KMD;
2631 
2632 	/*
2633 	 * If context is a parent, we need to register a process descriptor
2634 	 * describing a work queue and register all child contexts.
2635 	 */
2636 	if (intel_context_is_parent(ce)) {
2637 		struct guc_sched_wq_desc *wq_desc;
2638 		u64 wq_desc_offset, wq_base_offset;
2639 
2640 		ce->parallel.guc.wqi_tail = 0;
2641 		ce->parallel.guc.wqi_head = 0;
2642 
2643 		wq_desc_offset = i915_ggtt_offset(ce->state) +
2644 				 __get_parent_scratch_offset(ce);
2645 		wq_base_offset = i915_ggtt_offset(ce->state) +
2646 				 __get_wq_offset(ce);
2647 		info->wq_desc_lo = lower_32_bits(wq_desc_offset);
2648 		info->wq_desc_hi = upper_32_bits(wq_desc_offset);
2649 		info->wq_base_lo = lower_32_bits(wq_base_offset);
2650 		info->wq_base_hi = upper_32_bits(wq_base_offset);
2651 		info->wq_size = WQ_SIZE;
2652 
2653 		wq_desc = __get_wq_desc_v70(ce);
2654 		memset(wq_desc, 0, sizeof(*wq_desc));
2655 		wq_desc->wq_status = WQ_STATUS_ACTIVE;
2656 
2657 		ce->parallel.guc.wq_head = &wq_desc->head;
2658 		ce->parallel.guc.wq_tail = &wq_desc->tail;
2659 		ce->parallel.guc.wq_status = &wq_desc->wq_status;
2660 
2661 		clear_children_join_go_memory(ce);
2662 	}
2663 }
2664 
2665 static int try_context_registration(struct intel_context *ce, bool loop)
2666 {
2667 	struct intel_engine_cs *engine = ce->engine;
2668 	struct intel_runtime_pm *runtime_pm = engine->uncore->rpm;
2669 	struct intel_guc *guc = &engine->gt->uc.guc;
2670 	intel_wakeref_t wakeref;
2671 	u32 ctx_id = ce->guc_id.id;
2672 	bool context_registered;
2673 	int ret = 0;
2674 
2675 	GEM_BUG_ON(!sched_state_is_init(ce));
2676 
2677 	context_registered = ctx_id_mapped(guc, ctx_id);
2678 
2679 	clr_ctx_id_mapping(guc, ctx_id);
2680 	set_ctx_id_mapping(guc, ctx_id, ce);
2681 
2682 	/*
2683 	 * The context_lookup xarray is used to determine if the hardware
2684 	 * context is currently registered. There are two cases in which it
2685 	 * could be registered either the guc_id has been stolen from another
2686 	 * context or the lrc descriptor address of this context has changed. In
2687 	 * either case the context needs to be deregistered with the GuC before
2688 	 * registering this context.
2689 	 */
2690 	if (context_registered) {
2691 		bool disabled;
2692 		unsigned long flags;
2693 
2694 		trace_intel_context_steal_guc_id(ce);
2695 		GEM_BUG_ON(!loop);
2696 
2697 		/* Seal race with Reset */
2698 		spin_lock_irqsave(&ce->guc_state.lock, flags);
2699 		disabled = submission_disabled(guc);
2700 		if (likely(!disabled)) {
2701 			set_context_wait_for_deregister_to_register(ce);
2702 			intel_context_get(ce);
2703 		}
2704 		spin_unlock_irqrestore(&ce->guc_state.lock, flags);
2705 		if (unlikely(disabled)) {
2706 			clr_ctx_id_mapping(guc, ctx_id);
2707 			return 0;	/* Will get registered later */
2708 		}
2709 
2710 		/*
2711 		 * If stealing the guc_id, this ce has the same guc_id as the
2712 		 * context whose guc_id was stolen.
2713 		 */
2714 		with_intel_runtime_pm(runtime_pm, wakeref)
2715 			ret = deregister_context(ce, ce->guc_id.id);
2716 		if (unlikely(ret == -ENODEV))
2717 			ret = 0;	/* Will get registered later */
2718 	} else {
2719 		with_intel_runtime_pm(runtime_pm, wakeref)
2720 			ret = register_context(ce, loop);
2721 		if (unlikely(ret == -EBUSY)) {
2722 			clr_ctx_id_mapping(guc, ctx_id);
2723 		} else if (unlikely(ret == -ENODEV)) {
2724 			clr_ctx_id_mapping(guc, ctx_id);
2725 			ret = 0;	/* Will get registered later */
2726 		}
2727 	}
2728 
2729 	return ret;
2730 }
2731 
2732 static int __guc_context_pre_pin(struct intel_context *ce,
2733 				 struct intel_engine_cs *engine,
2734 				 struct i915_gem_ww_ctx *ww,
2735 				 void **vaddr)
2736 {
2737 	return lrc_pre_pin(ce, engine, ww, vaddr);
2738 }
2739 
2740 static int __guc_context_pin(struct intel_context *ce,
2741 			     struct intel_engine_cs *engine,
2742 			     void *vaddr)
2743 {
2744 	if (i915_ggtt_offset(ce->state) !=
2745 	    (ce->lrc.lrca & CTX_GTT_ADDRESS_MASK))
2746 		set_bit(CONTEXT_LRCA_DIRTY, &ce->flags);
2747 
2748 	/*
2749 	 * GuC context gets pinned in guc_request_alloc. See that function for
2750 	 * explaination of why.
2751 	 */
2752 
2753 	return lrc_pin(ce, engine, vaddr);
2754 }
2755 
2756 static int guc_context_pre_pin(struct intel_context *ce,
2757 			       struct i915_gem_ww_ctx *ww,
2758 			       void **vaddr)
2759 {
2760 	return __guc_context_pre_pin(ce, ce->engine, ww, vaddr);
2761 }
2762 
2763 static int guc_context_pin(struct intel_context *ce, void *vaddr)
2764 {
2765 	int ret = __guc_context_pin(ce, ce->engine, vaddr);
2766 
2767 	if (likely(!ret && !intel_context_is_barrier(ce)))
2768 		intel_engine_pm_get(ce->engine);
2769 
2770 	return ret;
2771 }
2772 
2773 static void guc_context_unpin(struct intel_context *ce)
2774 {
2775 	struct intel_guc *guc = ce_to_guc(ce);
2776 
2777 	unpin_guc_id(guc, ce);
2778 	lrc_unpin(ce);
2779 
2780 	if (likely(!intel_context_is_barrier(ce)))
2781 		intel_engine_pm_put_async(ce->engine);
2782 }
2783 
2784 static void guc_context_post_unpin(struct intel_context *ce)
2785 {
2786 	lrc_post_unpin(ce);
2787 }
2788 
2789 static void __guc_context_sched_enable(struct intel_guc *guc,
2790 				       struct intel_context *ce)
2791 {
2792 	u32 action[] = {
2793 		INTEL_GUC_ACTION_SCHED_CONTEXT_MODE_SET,
2794 		ce->guc_id.id,
2795 		GUC_CONTEXT_ENABLE
2796 	};
2797 
2798 	trace_intel_context_sched_enable(ce);
2799 
2800 	guc_submission_send_busy_loop(guc, action, ARRAY_SIZE(action),
2801 				      G2H_LEN_DW_SCHED_CONTEXT_MODE_SET, true);
2802 }
2803 
2804 static void __guc_context_sched_disable(struct intel_guc *guc,
2805 					struct intel_context *ce,
2806 					u16 guc_id)
2807 {
2808 	u32 action[] = {
2809 		INTEL_GUC_ACTION_SCHED_CONTEXT_MODE_SET,
2810 		guc_id,	/* ce->guc_id.id not stable */
2811 		GUC_CONTEXT_DISABLE
2812 	};
2813 
2814 	GEM_BUG_ON(guc_id == GUC_INVALID_CONTEXT_ID);
2815 
2816 	GEM_BUG_ON(intel_context_is_child(ce));
2817 	trace_intel_context_sched_disable(ce);
2818 
2819 	guc_submission_send_busy_loop(guc, action, ARRAY_SIZE(action),
2820 				      G2H_LEN_DW_SCHED_CONTEXT_MODE_SET, true);
2821 }
2822 
2823 static void guc_blocked_fence_complete(struct intel_context *ce)
2824 {
2825 	lockdep_assert_held(&ce->guc_state.lock);
2826 
2827 	if (!i915_sw_fence_done(&ce->guc_state.blocked))
2828 		i915_sw_fence_complete(&ce->guc_state.blocked);
2829 }
2830 
2831 static void guc_blocked_fence_reinit(struct intel_context *ce)
2832 {
2833 	lockdep_assert_held(&ce->guc_state.lock);
2834 	GEM_BUG_ON(!i915_sw_fence_done(&ce->guc_state.blocked));
2835 
2836 	/*
2837 	 * This fence is always complete unless a pending schedule disable is
2838 	 * outstanding. We arm the fence here and complete it when we receive
2839 	 * the pending schedule disable complete message.
2840 	 */
2841 	i915_sw_fence_fini(&ce->guc_state.blocked);
2842 	i915_sw_fence_reinit(&ce->guc_state.blocked);
2843 	i915_sw_fence_await(&ce->guc_state.blocked);
2844 	i915_sw_fence_commit(&ce->guc_state.blocked);
2845 }
2846 
2847 static u16 prep_context_pending_disable(struct intel_context *ce)
2848 {
2849 	lockdep_assert_held(&ce->guc_state.lock);
2850 
2851 	set_context_pending_disable(ce);
2852 	clr_context_enabled(ce);
2853 	guc_blocked_fence_reinit(ce);
2854 	intel_context_get(ce);
2855 
2856 	return ce->guc_id.id;
2857 }
2858 
2859 static struct i915_sw_fence *guc_context_block(struct intel_context *ce)
2860 {
2861 	struct intel_guc *guc = ce_to_guc(ce);
2862 	unsigned long flags;
2863 	struct intel_runtime_pm *runtime_pm = ce->engine->uncore->rpm;
2864 	intel_wakeref_t wakeref;
2865 	u16 guc_id;
2866 	bool enabled;
2867 
2868 	GEM_BUG_ON(intel_context_is_child(ce));
2869 
2870 	spin_lock_irqsave(&ce->guc_state.lock, flags);
2871 
2872 	incr_context_blocked(ce);
2873 
2874 	enabled = context_enabled(ce);
2875 	if (unlikely(!enabled || submission_disabled(guc))) {
2876 		if (enabled)
2877 			clr_context_enabled(ce);
2878 		spin_unlock_irqrestore(&ce->guc_state.lock, flags);
2879 		return &ce->guc_state.blocked;
2880 	}
2881 
2882 	/*
2883 	 * We add +2 here as the schedule disable complete CTB handler calls
2884 	 * intel_context_sched_disable_unpin (-2 to pin_count).
2885 	 */
2886 	atomic_add(2, &ce->pin_count);
2887 
2888 	guc_id = prep_context_pending_disable(ce);
2889 
2890 	spin_unlock_irqrestore(&ce->guc_state.lock, flags);
2891 
2892 	with_intel_runtime_pm(runtime_pm, wakeref)
2893 		__guc_context_sched_disable(guc, ce, guc_id);
2894 
2895 	return &ce->guc_state.blocked;
2896 }
2897 
2898 #define SCHED_STATE_MULTI_BLOCKED_MASK \
2899 	(SCHED_STATE_BLOCKED_MASK & ~SCHED_STATE_BLOCKED)
2900 #define SCHED_STATE_NO_UNBLOCK \
2901 	(SCHED_STATE_MULTI_BLOCKED_MASK | \
2902 	 SCHED_STATE_PENDING_DISABLE | \
2903 	 SCHED_STATE_BANNED)
2904 
2905 static bool context_cant_unblock(struct intel_context *ce)
2906 {
2907 	lockdep_assert_held(&ce->guc_state.lock);
2908 
2909 	return (ce->guc_state.sched_state & SCHED_STATE_NO_UNBLOCK) ||
2910 		context_guc_id_invalid(ce) ||
2911 		!ctx_id_mapped(ce_to_guc(ce), ce->guc_id.id) ||
2912 		!intel_context_is_pinned(ce);
2913 }
2914 
2915 static void guc_context_unblock(struct intel_context *ce)
2916 {
2917 	struct intel_guc *guc = ce_to_guc(ce);
2918 	unsigned long flags;
2919 	struct intel_runtime_pm *runtime_pm = ce->engine->uncore->rpm;
2920 	intel_wakeref_t wakeref;
2921 	bool enable;
2922 
2923 	GEM_BUG_ON(context_enabled(ce));
2924 	GEM_BUG_ON(intel_context_is_child(ce));
2925 
2926 	spin_lock_irqsave(&ce->guc_state.lock, flags);
2927 
2928 	if (unlikely(submission_disabled(guc) ||
2929 		     context_cant_unblock(ce))) {
2930 		enable = false;
2931 	} else {
2932 		enable = true;
2933 		set_context_pending_enable(ce);
2934 		set_context_enabled(ce);
2935 		intel_context_get(ce);
2936 	}
2937 
2938 	decr_context_blocked(ce);
2939 
2940 	spin_unlock_irqrestore(&ce->guc_state.lock, flags);
2941 
2942 	if (enable) {
2943 		with_intel_runtime_pm(runtime_pm, wakeref)
2944 			__guc_context_sched_enable(guc, ce);
2945 	}
2946 }
2947 
2948 static void guc_context_cancel_request(struct intel_context *ce,
2949 				       struct i915_request *rq)
2950 {
2951 	struct intel_context *block_context =
2952 		request_to_scheduling_context(rq);
2953 
2954 	if (i915_sw_fence_signaled(&rq->submit)) {
2955 		struct i915_sw_fence *fence;
2956 
2957 		intel_context_get(ce);
2958 		fence = guc_context_block(block_context);
2959 		i915_sw_fence_wait(fence);
2960 		if (!i915_request_completed(rq)) {
2961 			__i915_request_skip(rq);
2962 			guc_reset_state(ce, intel_ring_wrap(ce->ring, rq->head),
2963 					true);
2964 		}
2965 
2966 		guc_context_unblock(block_context);
2967 		intel_context_put(ce);
2968 	}
2969 }
2970 
2971 static void __guc_context_set_preemption_timeout(struct intel_guc *guc,
2972 						 u16 guc_id,
2973 						 u32 preemption_timeout)
2974 {
2975 	if (GUC_SUBMIT_VER(guc) >= MAKE_GUC_VER(1, 0, 0)) {
2976 		struct context_policy policy;
2977 
2978 		__guc_context_policy_start_klv(&policy, guc_id);
2979 		__guc_context_policy_add_preemption_timeout(&policy, preemption_timeout);
2980 		__guc_context_set_context_policies(guc, &policy, true);
2981 	} else {
2982 		u32 action[] = {
2983 			INTEL_GUC_ACTION_V69_SET_CONTEXT_PREEMPTION_TIMEOUT,
2984 			guc_id,
2985 			preemption_timeout
2986 		};
2987 
2988 		intel_guc_send_busy_loop(guc, action, ARRAY_SIZE(action), 0, true);
2989 	}
2990 }
2991 
2992 static void
2993 guc_context_revoke(struct intel_context *ce, struct i915_request *rq,
2994 		   unsigned int preempt_timeout_ms)
2995 {
2996 	struct intel_guc *guc = ce_to_guc(ce);
2997 	struct intel_runtime_pm *runtime_pm =
2998 		&ce->engine->gt->i915->runtime_pm;
2999 	intel_wakeref_t wakeref;
3000 	unsigned long flags;
3001 
3002 	GEM_BUG_ON(intel_context_is_child(ce));
3003 
3004 	guc_flush_submissions(guc);
3005 
3006 	spin_lock_irqsave(&ce->guc_state.lock, flags);
3007 	set_context_banned(ce);
3008 
3009 	if (submission_disabled(guc) ||
3010 	    (!context_enabled(ce) && !context_pending_disable(ce))) {
3011 		spin_unlock_irqrestore(&ce->guc_state.lock, flags);
3012 
3013 		guc_cancel_context_requests(ce);
3014 		intel_engine_signal_breadcrumbs(ce->engine);
3015 	} else if (!context_pending_disable(ce)) {
3016 		u16 guc_id;
3017 
3018 		/*
3019 		 * We add +2 here as the schedule disable complete CTB handler
3020 		 * calls intel_context_sched_disable_unpin (-2 to pin_count).
3021 		 */
3022 		atomic_add(2, &ce->pin_count);
3023 
3024 		guc_id = prep_context_pending_disable(ce);
3025 		spin_unlock_irqrestore(&ce->guc_state.lock, flags);
3026 
3027 		/*
3028 		 * In addition to disabling scheduling, set the preemption
3029 		 * timeout to the minimum value (1 us) so the banned context
3030 		 * gets kicked off the HW ASAP.
3031 		 */
3032 		with_intel_runtime_pm(runtime_pm, wakeref) {
3033 			__guc_context_set_preemption_timeout(guc, guc_id,
3034 							     preempt_timeout_ms);
3035 			__guc_context_sched_disable(guc, ce, guc_id);
3036 		}
3037 	} else {
3038 		if (!context_guc_id_invalid(ce))
3039 			with_intel_runtime_pm(runtime_pm, wakeref)
3040 				__guc_context_set_preemption_timeout(guc,
3041 								     ce->guc_id.id,
3042 								     preempt_timeout_ms);
3043 		spin_unlock_irqrestore(&ce->guc_state.lock, flags);
3044 	}
3045 }
3046 
3047 static void do_sched_disable(struct intel_guc *guc, struct intel_context *ce,
3048 			     unsigned long flags)
3049 	__releases(ce->guc_state.lock)
3050 {
3051 	struct intel_runtime_pm *runtime_pm = &ce->engine->gt->i915->runtime_pm;
3052 	intel_wakeref_t wakeref;
3053 	u16 guc_id;
3054 
3055 	lockdep_assert_held(&ce->guc_state.lock);
3056 	guc_id = prep_context_pending_disable(ce);
3057 
3058 	spin_unlock_irqrestore(&ce->guc_state.lock, flags);
3059 
3060 	with_intel_runtime_pm(runtime_pm, wakeref)
3061 		__guc_context_sched_disable(guc, ce, guc_id);
3062 }
3063 
3064 static bool bypass_sched_disable(struct intel_guc *guc,
3065 				 struct intel_context *ce)
3066 {
3067 	lockdep_assert_held(&ce->guc_state.lock);
3068 	GEM_BUG_ON(intel_context_is_child(ce));
3069 
3070 	if (submission_disabled(guc) || context_guc_id_invalid(ce) ||
3071 	    !ctx_id_mapped(guc, ce->guc_id.id)) {
3072 		clr_context_enabled(ce);
3073 		return true;
3074 	}
3075 
3076 	return !context_enabled(ce);
3077 }
3078 
3079 static void __delay_sched_disable(struct work_struct *wrk)
3080 {
3081 	struct intel_context *ce =
3082 		container_of(wrk, typeof(*ce), guc_state.sched_disable_delay_work.work);
3083 	struct intel_guc *guc = ce_to_guc(ce);
3084 	unsigned long flags;
3085 
3086 	spin_lock_irqsave(&ce->guc_state.lock, flags);
3087 
3088 	if (bypass_sched_disable(guc, ce)) {
3089 		spin_unlock_irqrestore(&ce->guc_state.lock, flags);
3090 		intel_context_sched_disable_unpin(ce);
3091 	} else {
3092 		do_sched_disable(guc, ce, flags);
3093 	}
3094 }
3095 
3096 static bool guc_id_pressure(struct intel_guc *guc, struct intel_context *ce)
3097 {
3098 	/*
3099 	 * parent contexts are perma-pinned, if we are unpinning do schedule
3100 	 * disable immediately.
3101 	 */
3102 	if (intel_context_is_parent(ce))
3103 		return true;
3104 
3105 	/*
3106 	 * If we are beyond the threshold for avail guc_ids, do schedule disable immediately.
3107 	 */
3108 	return guc->submission_state.guc_ids_in_use >
3109 		guc->submission_state.sched_disable_gucid_threshold;
3110 }
3111 
3112 static void guc_context_sched_disable(struct intel_context *ce)
3113 {
3114 	struct intel_guc *guc = ce_to_guc(ce);
3115 	u64 delay = guc->submission_state.sched_disable_delay_ms;
3116 	unsigned long flags;
3117 
3118 	spin_lock_irqsave(&ce->guc_state.lock, flags);
3119 
3120 	if (bypass_sched_disable(guc, ce)) {
3121 		spin_unlock_irqrestore(&ce->guc_state.lock, flags);
3122 		intel_context_sched_disable_unpin(ce);
3123 	} else if (!intel_context_is_closed(ce) && !guc_id_pressure(guc, ce) &&
3124 		   delay) {
3125 		spin_unlock_irqrestore(&ce->guc_state.lock, flags);
3126 		mod_delayed_work(system_unbound_wq,
3127 				 &ce->guc_state.sched_disable_delay_work,
3128 				 msecs_to_jiffies(delay));
3129 	} else {
3130 		do_sched_disable(guc, ce, flags);
3131 	}
3132 }
3133 
3134 static void guc_context_close(struct intel_context *ce)
3135 {
3136 	unsigned long flags;
3137 
3138 	if (test_bit(CONTEXT_GUC_INIT, &ce->flags) &&
3139 	    cancel_delayed_work(&ce->guc_state.sched_disable_delay_work))
3140 		__delay_sched_disable(&ce->guc_state.sched_disable_delay_work.work);
3141 
3142 	spin_lock_irqsave(&ce->guc_state.lock, flags);
3143 	set_context_close_done(ce);
3144 	spin_unlock_irqrestore(&ce->guc_state.lock, flags);
3145 }
3146 
3147 static inline void guc_lrc_desc_unpin(struct intel_context *ce)
3148 {
3149 	struct intel_guc *guc = ce_to_guc(ce);
3150 	struct intel_gt *gt = guc_to_gt(guc);
3151 	unsigned long flags;
3152 	bool disabled;
3153 
3154 	GEM_BUG_ON(!intel_gt_pm_is_awake(gt));
3155 	GEM_BUG_ON(!ctx_id_mapped(guc, ce->guc_id.id));
3156 	GEM_BUG_ON(ce != __get_context(guc, ce->guc_id.id));
3157 	GEM_BUG_ON(context_enabled(ce));
3158 
3159 	/* Seal race with Reset */
3160 	spin_lock_irqsave(&ce->guc_state.lock, flags);
3161 	disabled = submission_disabled(guc);
3162 	if (likely(!disabled)) {
3163 		__intel_gt_pm_get(gt);
3164 		set_context_destroyed(ce);
3165 		clr_context_registered(ce);
3166 	}
3167 	spin_unlock_irqrestore(&ce->guc_state.lock, flags);
3168 	if (unlikely(disabled)) {
3169 		release_guc_id(guc, ce);
3170 		__guc_context_destroy(ce);
3171 		return;
3172 	}
3173 
3174 	deregister_context(ce, ce->guc_id.id);
3175 }
3176 
3177 static void __guc_context_destroy(struct intel_context *ce)
3178 {
3179 	GEM_BUG_ON(ce->guc_state.prio_count[GUC_CLIENT_PRIORITY_KMD_HIGH] ||
3180 		   ce->guc_state.prio_count[GUC_CLIENT_PRIORITY_HIGH] ||
3181 		   ce->guc_state.prio_count[GUC_CLIENT_PRIORITY_KMD_NORMAL] ||
3182 		   ce->guc_state.prio_count[GUC_CLIENT_PRIORITY_NORMAL]);
3183 
3184 	lrc_fini(ce);
3185 	intel_context_fini(ce);
3186 
3187 	if (intel_engine_is_virtual(ce->engine)) {
3188 		struct guc_virtual_engine *ve =
3189 			container_of(ce, typeof(*ve), context);
3190 
3191 		if (ve->base.breadcrumbs)
3192 			intel_breadcrumbs_put(ve->base.breadcrumbs);
3193 
3194 		kfree(ve);
3195 	} else {
3196 		intel_context_free(ce);
3197 	}
3198 }
3199 
3200 static void guc_flush_destroyed_contexts(struct intel_guc *guc)
3201 {
3202 	struct intel_context *ce;
3203 	unsigned long flags;
3204 
3205 	GEM_BUG_ON(!submission_disabled(guc) &&
3206 		   guc_submission_initialized(guc));
3207 
3208 	while (!list_empty(&guc->submission_state.destroyed_contexts)) {
3209 		spin_lock_irqsave(&guc->submission_state.lock, flags);
3210 		ce = list_first_entry_or_null(&guc->submission_state.destroyed_contexts,
3211 					      struct intel_context,
3212 					      destroyed_link);
3213 		if (ce)
3214 			list_del_init(&ce->destroyed_link);
3215 		spin_unlock_irqrestore(&guc->submission_state.lock, flags);
3216 
3217 		if (!ce)
3218 			break;
3219 
3220 		release_guc_id(guc, ce);
3221 		__guc_context_destroy(ce);
3222 	}
3223 }
3224 
3225 static void deregister_destroyed_contexts(struct intel_guc *guc)
3226 {
3227 	struct intel_context *ce;
3228 	unsigned long flags;
3229 
3230 	while (!list_empty(&guc->submission_state.destroyed_contexts)) {
3231 		spin_lock_irqsave(&guc->submission_state.lock, flags);
3232 		ce = list_first_entry_or_null(&guc->submission_state.destroyed_contexts,
3233 					      struct intel_context,
3234 					      destroyed_link);
3235 		if (ce)
3236 			list_del_init(&ce->destroyed_link);
3237 		spin_unlock_irqrestore(&guc->submission_state.lock, flags);
3238 
3239 		if (!ce)
3240 			break;
3241 
3242 		guc_lrc_desc_unpin(ce);
3243 	}
3244 }
3245 
3246 static void destroyed_worker_func(struct work_struct *w)
3247 {
3248 	struct intel_guc *guc = container_of(w, struct intel_guc,
3249 					     submission_state.destroyed_worker);
3250 	struct intel_gt *gt = guc_to_gt(guc);
3251 	int tmp;
3252 
3253 	with_intel_gt_pm(gt, tmp)
3254 		deregister_destroyed_contexts(guc);
3255 }
3256 
3257 static void guc_context_destroy(struct kref *kref)
3258 {
3259 	struct intel_context *ce = container_of(kref, typeof(*ce), ref);
3260 	struct intel_guc *guc = ce_to_guc(ce);
3261 	unsigned long flags;
3262 	bool destroy;
3263 
3264 	/*
3265 	 * If the guc_id is invalid this context has been stolen and we can free
3266 	 * it immediately. Also can be freed immediately if the context is not
3267 	 * registered with the GuC or the GuC is in the middle of a reset.
3268 	 */
3269 	spin_lock_irqsave(&guc->submission_state.lock, flags);
3270 	destroy = submission_disabled(guc) || context_guc_id_invalid(ce) ||
3271 		!ctx_id_mapped(guc, ce->guc_id.id);
3272 	if (likely(!destroy)) {
3273 		if (!list_empty(&ce->guc_id.link))
3274 			list_del_init(&ce->guc_id.link);
3275 		list_add_tail(&ce->destroyed_link,
3276 			      &guc->submission_state.destroyed_contexts);
3277 	} else {
3278 		__release_guc_id(guc, ce);
3279 	}
3280 	spin_unlock_irqrestore(&guc->submission_state.lock, flags);
3281 	if (unlikely(destroy)) {
3282 		__guc_context_destroy(ce);
3283 		return;
3284 	}
3285 
3286 	/*
3287 	 * We use a worker to issue the H2G to deregister the context as we can
3288 	 * take the GT PM for the first time which isn't allowed from an atomic
3289 	 * context.
3290 	 */
3291 	queue_work(system_unbound_wq, &guc->submission_state.destroyed_worker);
3292 }
3293 
3294 static int guc_context_alloc(struct intel_context *ce)
3295 {
3296 	return lrc_alloc(ce, ce->engine);
3297 }
3298 
3299 static void __guc_context_set_prio(struct intel_guc *guc,
3300 				   struct intel_context *ce)
3301 {
3302 	if (GUC_SUBMIT_VER(guc) >= MAKE_GUC_VER(1, 0, 0)) {
3303 		struct context_policy policy;
3304 
3305 		__guc_context_policy_start_klv(&policy, ce->guc_id.id);
3306 		__guc_context_policy_add_priority(&policy, ce->guc_state.prio);
3307 		__guc_context_set_context_policies(guc, &policy, true);
3308 	} else {
3309 		u32 action[] = {
3310 			INTEL_GUC_ACTION_V69_SET_CONTEXT_PRIORITY,
3311 			ce->guc_id.id,
3312 			ce->guc_state.prio,
3313 		};
3314 
3315 		guc_submission_send_busy_loop(guc, action, ARRAY_SIZE(action), 0, true);
3316 	}
3317 }
3318 
3319 static void guc_context_set_prio(struct intel_guc *guc,
3320 				 struct intel_context *ce,
3321 				 u8 prio)
3322 {
3323 	GEM_BUG_ON(prio < GUC_CLIENT_PRIORITY_KMD_HIGH ||
3324 		   prio > GUC_CLIENT_PRIORITY_NORMAL);
3325 	lockdep_assert_held(&ce->guc_state.lock);
3326 
3327 	if (ce->guc_state.prio == prio || submission_disabled(guc) ||
3328 	    !context_registered(ce)) {
3329 		ce->guc_state.prio = prio;
3330 		return;
3331 	}
3332 
3333 	ce->guc_state.prio = prio;
3334 	__guc_context_set_prio(guc, ce);
3335 
3336 	trace_intel_context_set_prio(ce);
3337 }
3338 
3339 static inline u8 map_i915_prio_to_guc_prio(int prio)
3340 {
3341 	if (prio == I915_PRIORITY_NORMAL)
3342 		return GUC_CLIENT_PRIORITY_KMD_NORMAL;
3343 	else if (prio < I915_PRIORITY_NORMAL)
3344 		return GUC_CLIENT_PRIORITY_NORMAL;
3345 	else if (prio < I915_PRIORITY_DISPLAY)
3346 		return GUC_CLIENT_PRIORITY_HIGH;
3347 	else
3348 		return GUC_CLIENT_PRIORITY_KMD_HIGH;
3349 }
3350 
3351 static inline void add_context_inflight_prio(struct intel_context *ce,
3352 					     u8 guc_prio)
3353 {
3354 	lockdep_assert_held(&ce->guc_state.lock);
3355 	GEM_BUG_ON(guc_prio >= ARRAY_SIZE(ce->guc_state.prio_count));
3356 
3357 	++ce->guc_state.prio_count[guc_prio];
3358 
3359 	/* Overflow protection */
3360 	GEM_WARN_ON(!ce->guc_state.prio_count[guc_prio]);
3361 }
3362 
3363 static inline void sub_context_inflight_prio(struct intel_context *ce,
3364 					     u8 guc_prio)
3365 {
3366 	lockdep_assert_held(&ce->guc_state.lock);
3367 	GEM_BUG_ON(guc_prio >= ARRAY_SIZE(ce->guc_state.prio_count));
3368 
3369 	/* Underflow protection */
3370 	GEM_WARN_ON(!ce->guc_state.prio_count[guc_prio]);
3371 
3372 	--ce->guc_state.prio_count[guc_prio];
3373 }
3374 
3375 static inline void update_context_prio(struct intel_context *ce)
3376 {
3377 	struct intel_guc *guc = &ce->engine->gt->uc.guc;
3378 	int i;
3379 
3380 	BUILD_BUG_ON(GUC_CLIENT_PRIORITY_KMD_HIGH != 0);
3381 	BUILD_BUG_ON(GUC_CLIENT_PRIORITY_KMD_HIGH > GUC_CLIENT_PRIORITY_NORMAL);
3382 
3383 	lockdep_assert_held(&ce->guc_state.lock);
3384 
3385 	for (i = 0; i < ARRAY_SIZE(ce->guc_state.prio_count); ++i) {
3386 		if (ce->guc_state.prio_count[i]) {
3387 			guc_context_set_prio(guc, ce, i);
3388 			break;
3389 		}
3390 	}
3391 }
3392 
3393 static inline bool new_guc_prio_higher(u8 old_guc_prio, u8 new_guc_prio)
3394 {
3395 	/* Lower value is higher priority */
3396 	return new_guc_prio < old_guc_prio;
3397 }
3398 
3399 static void add_to_context(struct i915_request *rq)
3400 {
3401 	struct intel_context *ce = request_to_scheduling_context(rq);
3402 	u8 new_guc_prio = map_i915_prio_to_guc_prio(rq_prio(rq));
3403 
3404 	GEM_BUG_ON(intel_context_is_child(ce));
3405 	GEM_BUG_ON(rq->guc_prio == GUC_PRIO_FINI);
3406 
3407 	spin_lock(&ce->guc_state.lock);
3408 	list_move_tail(&rq->sched.link, &ce->guc_state.requests);
3409 
3410 	if (rq->guc_prio == GUC_PRIO_INIT) {
3411 		rq->guc_prio = new_guc_prio;
3412 		add_context_inflight_prio(ce, rq->guc_prio);
3413 	} else if (new_guc_prio_higher(rq->guc_prio, new_guc_prio)) {
3414 		sub_context_inflight_prio(ce, rq->guc_prio);
3415 		rq->guc_prio = new_guc_prio;
3416 		add_context_inflight_prio(ce, rq->guc_prio);
3417 	}
3418 	update_context_prio(ce);
3419 
3420 	spin_unlock(&ce->guc_state.lock);
3421 }
3422 
3423 static void guc_prio_fini(struct i915_request *rq, struct intel_context *ce)
3424 {
3425 	lockdep_assert_held(&ce->guc_state.lock);
3426 
3427 	if (rq->guc_prio != GUC_PRIO_INIT &&
3428 	    rq->guc_prio != GUC_PRIO_FINI) {
3429 		sub_context_inflight_prio(ce, rq->guc_prio);
3430 		update_context_prio(ce);
3431 	}
3432 	rq->guc_prio = GUC_PRIO_FINI;
3433 }
3434 
3435 static void remove_from_context(struct i915_request *rq)
3436 {
3437 	struct intel_context *ce = request_to_scheduling_context(rq);
3438 
3439 	GEM_BUG_ON(intel_context_is_child(ce));
3440 
3441 	spin_lock_irq(&ce->guc_state.lock);
3442 
3443 	list_del_init(&rq->sched.link);
3444 	clear_bit(I915_FENCE_FLAG_PQUEUE, &rq->fence.flags);
3445 
3446 	/* Prevent further __await_execution() registering a cb, then flush */
3447 	set_bit(I915_FENCE_FLAG_ACTIVE, &rq->fence.flags);
3448 
3449 	guc_prio_fini(rq, ce);
3450 
3451 	spin_unlock_irq(&ce->guc_state.lock);
3452 
3453 	atomic_dec(&ce->guc_id.ref);
3454 	i915_request_notify_execute_cb_imm(rq);
3455 }
3456 
3457 static const struct intel_context_ops guc_context_ops = {
3458 	.alloc = guc_context_alloc,
3459 
3460 	.close = guc_context_close,
3461 
3462 	.pre_pin = guc_context_pre_pin,
3463 	.pin = guc_context_pin,
3464 	.unpin = guc_context_unpin,
3465 	.post_unpin = guc_context_post_unpin,
3466 
3467 	.revoke = guc_context_revoke,
3468 
3469 	.cancel_request = guc_context_cancel_request,
3470 
3471 	.enter = intel_context_enter_engine,
3472 	.exit = intel_context_exit_engine,
3473 
3474 	.sched_disable = guc_context_sched_disable,
3475 
3476 	.reset = lrc_reset,
3477 	.destroy = guc_context_destroy,
3478 
3479 	.create_virtual = guc_create_virtual,
3480 	.create_parallel = guc_create_parallel,
3481 };
3482 
3483 static void submit_work_cb(struct irq_work *wrk)
3484 {
3485 	struct i915_request *rq = container_of(wrk, typeof(*rq), submit_work);
3486 
3487 	might_lock(&rq->engine->sched_engine->lock);
3488 	i915_sw_fence_complete(&rq->submit);
3489 }
3490 
3491 static void __guc_signal_context_fence(struct intel_context *ce)
3492 {
3493 	struct i915_request *rq, *rn;
3494 
3495 	lockdep_assert_held(&ce->guc_state.lock);
3496 
3497 	if (!list_empty(&ce->guc_state.fences))
3498 		trace_intel_context_fence_release(ce);
3499 
3500 	/*
3501 	 * Use an IRQ to ensure locking order of sched_engine->lock ->
3502 	 * ce->guc_state.lock is preserved.
3503 	 */
3504 	list_for_each_entry_safe(rq, rn, &ce->guc_state.fences,
3505 				 guc_fence_link) {
3506 		list_del(&rq->guc_fence_link);
3507 		irq_work_queue(&rq->submit_work);
3508 	}
3509 
3510 	INIT_LIST_HEAD(&ce->guc_state.fences);
3511 }
3512 
3513 static void guc_signal_context_fence(struct intel_context *ce)
3514 {
3515 	unsigned long flags;
3516 
3517 	GEM_BUG_ON(intel_context_is_child(ce));
3518 
3519 	spin_lock_irqsave(&ce->guc_state.lock, flags);
3520 	clr_context_wait_for_deregister_to_register(ce);
3521 	__guc_signal_context_fence(ce);
3522 	spin_unlock_irqrestore(&ce->guc_state.lock, flags);
3523 }
3524 
3525 static bool context_needs_register(struct intel_context *ce, bool new_guc_id)
3526 {
3527 	return (new_guc_id || test_bit(CONTEXT_LRCA_DIRTY, &ce->flags) ||
3528 		!ctx_id_mapped(ce_to_guc(ce), ce->guc_id.id)) &&
3529 		!submission_disabled(ce_to_guc(ce));
3530 }
3531 
3532 static void guc_context_init(struct intel_context *ce)
3533 {
3534 	const struct i915_gem_context *ctx;
3535 	int prio = I915_CONTEXT_DEFAULT_PRIORITY;
3536 
3537 	rcu_read_lock();
3538 	ctx = rcu_dereference(ce->gem_context);
3539 	if (ctx)
3540 		prio = ctx->sched.priority;
3541 	rcu_read_unlock();
3542 
3543 	ce->guc_state.prio = map_i915_prio_to_guc_prio(prio);
3544 
3545 	INIT_DELAYED_WORK(&ce->guc_state.sched_disable_delay_work,
3546 			  __delay_sched_disable);
3547 
3548 	set_bit(CONTEXT_GUC_INIT, &ce->flags);
3549 }
3550 
3551 static int guc_request_alloc(struct i915_request *rq)
3552 {
3553 	struct intel_context *ce = request_to_scheduling_context(rq);
3554 	struct intel_guc *guc = ce_to_guc(ce);
3555 	unsigned long flags;
3556 	int ret;
3557 
3558 	GEM_BUG_ON(!intel_context_is_pinned(rq->context));
3559 
3560 	/*
3561 	 * Flush enough space to reduce the likelihood of waiting after
3562 	 * we start building the request - in which case we will just
3563 	 * have to repeat work.
3564 	 */
3565 	rq->reserved_space += GUC_REQUEST_SIZE;
3566 
3567 	/*
3568 	 * Note that after this point, we have committed to using
3569 	 * this request as it is being used to both track the
3570 	 * state of engine initialisation and liveness of the
3571 	 * golden renderstate above. Think twice before you try
3572 	 * to cancel/unwind this request now.
3573 	 */
3574 
3575 	/* Unconditionally invalidate GPU caches and TLBs. */
3576 	ret = rq->engine->emit_flush(rq, EMIT_INVALIDATE);
3577 	if (ret)
3578 		return ret;
3579 
3580 	rq->reserved_space -= GUC_REQUEST_SIZE;
3581 
3582 	if (unlikely(!test_bit(CONTEXT_GUC_INIT, &ce->flags)))
3583 		guc_context_init(ce);
3584 
3585 	/*
3586 	 * If the context gets closed while the execbuf is ongoing, the context
3587 	 * close code will race with the below code to cancel the delayed work.
3588 	 * If the context close wins the race and cancels the work, it will
3589 	 * immediately call the sched disable (see guc_context_close), so there
3590 	 * is a chance we can get past this check while the sched_disable code
3591 	 * is being executed. To make sure that code completes before we check
3592 	 * the status further down, we wait for the close process to complete.
3593 	 * Else, this code path could send a request down thinking that the
3594 	 * context is still in a schedule-enable mode while the GuC ends up
3595 	 * dropping the request completely because the disable did go from the
3596 	 * context_close path right to GuC just prior. In the event the CT is
3597 	 * full, we could potentially need to wait up to 1.5 seconds.
3598 	 */
3599 	if (cancel_delayed_work_sync(&ce->guc_state.sched_disable_delay_work))
3600 		intel_context_sched_disable_unpin(ce);
3601 	else if (intel_context_is_closed(ce))
3602 		if (wait_for(context_close_done(ce), 1500))
3603 			guc_warn(guc, "timed out waiting on context sched close before realloc\n");
3604 	/*
3605 	 * Call pin_guc_id here rather than in the pinning step as with
3606 	 * dma_resv, contexts can be repeatedly pinned / unpinned trashing the
3607 	 * guc_id and creating horrible race conditions. This is especially bad
3608 	 * when guc_id are being stolen due to over subscription. By the time
3609 	 * this function is reached, it is guaranteed that the guc_id will be
3610 	 * persistent until the generated request is retired. Thus, sealing these
3611 	 * race conditions. It is still safe to fail here if guc_id are
3612 	 * exhausted and return -EAGAIN to the user indicating that they can try
3613 	 * again in the future.
3614 	 *
3615 	 * There is no need for a lock here as the timeline mutex ensures at
3616 	 * most one context can be executing this code path at once. The
3617 	 * guc_id_ref is incremented once for every request in flight and
3618 	 * decremented on each retire. When it is zero, a lock around the
3619 	 * increment (in pin_guc_id) is needed to seal a race with unpin_guc_id.
3620 	 */
3621 	if (atomic_add_unless(&ce->guc_id.ref, 1, 0))
3622 		goto out;
3623 
3624 	ret = pin_guc_id(guc, ce);	/* returns 1 if new guc_id assigned */
3625 	if (unlikely(ret < 0))
3626 		return ret;
3627 	if (context_needs_register(ce, !!ret)) {
3628 		ret = try_context_registration(ce, true);
3629 		if (unlikely(ret)) {	/* unwind */
3630 			if (ret == -EPIPE) {
3631 				disable_submission(guc);
3632 				goto out;	/* GPU will be reset */
3633 			}
3634 			atomic_dec(&ce->guc_id.ref);
3635 			unpin_guc_id(guc, ce);
3636 			return ret;
3637 		}
3638 	}
3639 
3640 	clear_bit(CONTEXT_LRCA_DIRTY, &ce->flags);
3641 
3642 out:
3643 	/*
3644 	 * We block all requests on this context if a G2H is pending for a
3645 	 * schedule disable or context deregistration as the GuC will fail a
3646 	 * schedule enable or context registration if either G2H is pending
3647 	 * respectfully. Once a G2H returns, the fence is released that is
3648 	 * blocking these requests (see guc_signal_context_fence).
3649 	 */
3650 	spin_lock_irqsave(&ce->guc_state.lock, flags);
3651 	if (context_wait_for_deregister_to_register(ce) ||
3652 	    context_pending_disable(ce)) {
3653 		init_irq_work(&rq->submit_work, submit_work_cb);
3654 		i915_sw_fence_await(&rq->submit);
3655 
3656 		list_add_tail(&rq->guc_fence_link, &ce->guc_state.fences);
3657 	}
3658 	spin_unlock_irqrestore(&ce->guc_state.lock, flags);
3659 
3660 	return 0;
3661 }
3662 
3663 static int guc_virtual_context_pre_pin(struct intel_context *ce,
3664 				       struct i915_gem_ww_ctx *ww,
3665 				       void **vaddr)
3666 {
3667 	struct intel_engine_cs *engine = guc_virtual_get_sibling(ce->engine, 0);
3668 
3669 	return __guc_context_pre_pin(ce, engine, ww, vaddr);
3670 }
3671 
3672 static int guc_virtual_context_pin(struct intel_context *ce, void *vaddr)
3673 {
3674 	struct intel_engine_cs *engine = guc_virtual_get_sibling(ce->engine, 0);
3675 	int ret = __guc_context_pin(ce, engine, vaddr);
3676 	intel_engine_mask_t tmp, mask = ce->engine->mask;
3677 
3678 	if (likely(!ret))
3679 		for_each_engine_masked(engine, ce->engine->gt, mask, tmp)
3680 			intel_engine_pm_get(engine);
3681 
3682 	return ret;
3683 }
3684 
3685 static void guc_virtual_context_unpin(struct intel_context *ce)
3686 {
3687 	intel_engine_mask_t tmp, mask = ce->engine->mask;
3688 	struct intel_engine_cs *engine;
3689 	struct intel_guc *guc = ce_to_guc(ce);
3690 
3691 	GEM_BUG_ON(context_enabled(ce));
3692 	GEM_BUG_ON(intel_context_is_barrier(ce));
3693 
3694 	unpin_guc_id(guc, ce);
3695 	lrc_unpin(ce);
3696 
3697 	for_each_engine_masked(engine, ce->engine->gt, mask, tmp)
3698 		intel_engine_pm_put_async(engine);
3699 }
3700 
3701 static void guc_virtual_context_enter(struct intel_context *ce)
3702 {
3703 	intel_engine_mask_t tmp, mask = ce->engine->mask;
3704 	struct intel_engine_cs *engine;
3705 
3706 	for_each_engine_masked(engine, ce->engine->gt, mask, tmp)
3707 		intel_engine_pm_get(engine);
3708 
3709 	intel_timeline_enter(ce->timeline);
3710 }
3711 
3712 static void guc_virtual_context_exit(struct intel_context *ce)
3713 {
3714 	intel_engine_mask_t tmp, mask = ce->engine->mask;
3715 	struct intel_engine_cs *engine;
3716 
3717 	for_each_engine_masked(engine, ce->engine->gt, mask, tmp)
3718 		intel_engine_pm_put(engine);
3719 
3720 	intel_timeline_exit(ce->timeline);
3721 }
3722 
3723 static int guc_virtual_context_alloc(struct intel_context *ce)
3724 {
3725 	struct intel_engine_cs *engine = guc_virtual_get_sibling(ce->engine, 0);
3726 
3727 	return lrc_alloc(ce, engine);
3728 }
3729 
3730 static const struct intel_context_ops virtual_guc_context_ops = {
3731 	.alloc = guc_virtual_context_alloc,
3732 
3733 	.close = guc_context_close,
3734 
3735 	.pre_pin = guc_virtual_context_pre_pin,
3736 	.pin = guc_virtual_context_pin,
3737 	.unpin = guc_virtual_context_unpin,
3738 	.post_unpin = guc_context_post_unpin,
3739 
3740 	.revoke = guc_context_revoke,
3741 
3742 	.cancel_request = guc_context_cancel_request,
3743 
3744 	.enter = guc_virtual_context_enter,
3745 	.exit = guc_virtual_context_exit,
3746 
3747 	.sched_disable = guc_context_sched_disable,
3748 
3749 	.destroy = guc_context_destroy,
3750 
3751 	.get_sibling = guc_virtual_get_sibling,
3752 };
3753 
3754 static int guc_parent_context_pin(struct intel_context *ce, void *vaddr)
3755 {
3756 	struct intel_engine_cs *engine = guc_virtual_get_sibling(ce->engine, 0);
3757 	struct intel_guc *guc = ce_to_guc(ce);
3758 	int ret;
3759 
3760 	GEM_BUG_ON(!intel_context_is_parent(ce));
3761 	GEM_BUG_ON(!intel_engine_is_virtual(ce->engine));
3762 
3763 	ret = pin_guc_id(guc, ce);
3764 	if (unlikely(ret < 0))
3765 		return ret;
3766 
3767 	return __guc_context_pin(ce, engine, vaddr);
3768 }
3769 
3770 static int guc_child_context_pin(struct intel_context *ce, void *vaddr)
3771 {
3772 	struct intel_engine_cs *engine = guc_virtual_get_sibling(ce->engine, 0);
3773 
3774 	GEM_BUG_ON(!intel_context_is_child(ce));
3775 	GEM_BUG_ON(!intel_engine_is_virtual(ce->engine));
3776 
3777 	__intel_context_pin(ce->parallel.parent);
3778 	return __guc_context_pin(ce, engine, vaddr);
3779 }
3780 
3781 static void guc_parent_context_unpin(struct intel_context *ce)
3782 {
3783 	struct intel_guc *guc = ce_to_guc(ce);
3784 
3785 	GEM_BUG_ON(context_enabled(ce));
3786 	GEM_BUG_ON(intel_context_is_barrier(ce));
3787 	GEM_BUG_ON(!intel_context_is_parent(ce));
3788 	GEM_BUG_ON(!intel_engine_is_virtual(ce->engine));
3789 
3790 	unpin_guc_id(guc, ce);
3791 	lrc_unpin(ce);
3792 }
3793 
3794 static void guc_child_context_unpin(struct intel_context *ce)
3795 {
3796 	GEM_BUG_ON(context_enabled(ce));
3797 	GEM_BUG_ON(intel_context_is_barrier(ce));
3798 	GEM_BUG_ON(!intel_context_is_child(ce));
3799 	GEM_BUG_ON(!intel_engine_is_virtual(ce->engine));
3800 
3801 	lrc_unpin(ce);
3802 }
3803 
3804 static void guc_child_context_post_unpin(struct intel_context *ce)
3805 {
3806 	GEM_BUG_ON(!intel_context_is_child(ce));
3807 	GEM_BUG_ON(!intel_context_is_pinned(ce->parallel.parent));
3808 	GEM_BUG_ON(!intel_engine_is_virtual(ce->engine));
3809 
3810 	lrc_post_unpin(ce);
3811 	intel_context_unpin(ce->parallel.parent);
3812 }
3813 
3814 static void guc_child_context_destroy(struct kref *kref)
3815 {
3816 	struct intel_context *ce = container_of(kref, typeof(*ce), ref);
3817 
3818 	__guc_context_destroy(ce);
3819 }
3820 
3821 static const struct intel_context_ops virtual_parent_context_ops = {
3822 	.alloc = guc_virtual_context_alloc,
3823 
3824 	.close = guc_context_close,
3825 
3826 	.pre_pin = guc_context_pre_pin,
3827 	.pin = guc_parent_context_pin,
3828 	.unpin = guc_parent_context_unpin,
3829 	.post_unpin = guc_context_post_unpin,
3830 
3831 	.revoke = guc_context_revoke,
3832 
3833 	.cancel_request = guc_context_cancel_request,
3834 
3835 	.enter = guc_virtual_context_enter,
3836 	.exit = guc_virtual_context_exit,
3837 
3838 	.sched_disable = guc_context_sched_disable,
3839 
3840 	.destroy = guc_context_destroy,
3841 
3842 	.get_sibling = guc_virtual_get_sibling,
3843 };
3844 
3845 static const struct intel_context_ops virtual_child_context_ops = {
3846 	.alloc = guc_virtual_context_alloc,
3847 
3848 	.pre_pin = guc_context_pre_pin,
3849 	.pin = guc_child_context_pin,
3850 	.unpin = guc_child_context_unpin,
3851 	.post_unpin = guc_child_context_post_unpin,
3852 
3853 	.cancel_request = guc_context_cancel_request,
3854 
3855 	.enter = guc_virtual_context_enter,
3856 	.exit = guc_virtual_context_exit,
3857 
3858 	.destroy = guc_child_context_destroy,
3859 
3860 	.get_sibling = guc_virtual_get_sibling,
3861 };
3862 
3863 /*
3864  * The below override of the breadcrumbs is enabled when the user configures a
3865  * context for parallel submission (multi-lrc, parent-child).
3866  *
3867  * The overridden breadcrumbs implements an algorithm which allows the GuC to
3868  * safely preempt all the hw contexts configured for parallel submission
3869  * between each BB. The contract between the i915 and GuC is if the parent
3870  * context can be preempted, all the children can be preempted, and the GuC will
3871  * always try to preempt the parent before the children. A handshake between the
3872  * parent / children breadcrumbs ensures the i915 holds up its end of the deal
3873  * creating a window to preempt between each set of BBs.
3874  */
3875 static int emit_bb_start_parent_no_preempt_mid_batch(struct i915_request *rq,
3876 						     u64 offset, u32 len,
3877 						     const unsigned int flags);
3878 static int emit_bb_start_child_no_preempt_mid_batch(struct i915_request *rq,
3879 						    u64 offset, u32 len,
3880 						    const unsigned int flags);
3881 static u32 *
3882 emit_fini_breadcrumb_parent_no_preempt_mid_batch(struct i915_request *rq,
3883 						 u32 *cs);
3884 static u32 *
3885 emit_fini_breadcrumb_child_no_preempt_mid_batch(struct i915_request *rq,
3886 						u32 *cs);
3887 
3888 static struct intel_context *
3889 guc_create_parallel(struct intel_engine_cs **engines,
3890 		    unsigned int num_siblings,
3891 		    unsigned int width)
3892 {
3893 	struct intel_engine_cs **siblings = NULL;
3894 	struct intel_context *parent = NULL, *ce, *err;
3895 	int i, j;
3896 
3897 	siblings = kmalloc_array(num_siblings,
3898 				 sizeof(*siblings),
3899 				 GFP_KERNEL);
3900 	if (!siblings)
3901 		return ERR_PTR(-ENOMEM);
3902 
3903 	for (i = 0; i < width; ++i) {
3904 		for (j = 0; j < num_siblings; ++j)
3905 			siblings[j] = engines[i * num_siblings + j];
3906 
3907 		ce = intel_engine_create_virtual(siblings, num_siblings,
3908 						 FORCE_VIRTUAL);
3909 		if (IS_ERR(ce)) {
3910 			err = ERR_CAST(ce);
3911 			goto unwind;
3912 		}
3913 
3914 		if (i == 0) {
3915 			parent = ce;
3916 			parent->ops = &virtual_parent_context_ops;
3917 		} else {
3918 			ce->ops = &virtual_child_context_ops;
3919 			intel_context_bind_parent_child(parent, ce);
3920 		}
3921 	}
3922 
3923 	parent->parallel.fence_context = dma_fence_context_alloc(1);
3924 
3925 	parent->engine->emit_bb_start =
3926 		emit_bb_start_parent_no_preempt_mid_batch;
3927 	parent->engine->emit_fini_breadcrumb =
3928 		emit_fini_breadcrumb_parent_no_preempt_mid_batch;
3929 	parent->engine->emit_fini_breadcrumb_dw =
3930 		12 + 4 * parent->parallel.number_children;
3931 	for_each_child(parent, ce) {
3932 		ce->engine->emit_bb_start =
3933 			emit_bb_start_child_no_preempt_mid_batch;
3934 		ce->engine->emit_fini_breadcrumb =
3935 			emit_fini_breadcrumb_child_no_preempt_mid_batch;
3936 		ce->engine->emit_fini_breadcrumb_dw = 16;
3937 	}
3938 
3939 	kfree(siblings);
3940 	return parent;
3941 
3942 unwind:
3943 	if (parent)
3944 		intel_context_put(parent);
3945 	kfree(siblings);
3946 	return err;
3947 }
3948 
3949 static bool
3950 guc_irq_enable_breadcrumbs(struct intel_breadcrumbs *b)
3951 {
3952 	struct intel_engine_cs *sibling;
3953 	intel_engine_mask_t tmp, mask = b->engine_mask;
3954 	bool result = false;
3955 
3956 	for_each_engine_masked(sibling, b->irq_engine->gt, mask, tmp)
3957 		result |= intel_engine_irq_enable(sibling);
3958 
3959 	return result;
3960 }
3961 
3962 static void
3963 guc_irq_disable_breadcrumbs(struct intel_breadcrumbs *b)
3964 {
3965 	struct intel_engine_cs *sibling;
3966 	intel_engine_mask_t tmp, mask = b->engine_mask;
3967 
3968 	for_each_engine_masked(sibling, b->irq_engine->gt, mask, tmp)
3969 		intel_engine_irq_disable(sibling);
3970 }
3971 
3972 static void guc_init_breadcrumbs(struct intel_engine_cs *engine)
3973 {
3974 	int i;
3975 
3976 	/*
3977 	 * In GuC submission mode we do not know which physical engine a request
3978 	 * will be scheduled on, this creates a problem because the breadcrumb
3979 	 * interrupt is per physical engine. To work around this we attach
3980 	 * requests and direct all breadcrumb interrupts to the first instance
3981 	 * of an engine per class. In addition all breadcrumb interrupts are
3982 	 * enabled / disabled across an engine class in unison.
3983 	 */
3984 	for (i = 0; i < MAX_ENGINE_INSTANCE; ++i) {
3985 		struct intel_engine_cs *sibling =
3986 			engine->gt->engine_class[engine->class][i];
3987 
3988 		if (sibling) {
3989 			if (engine->breadcrumbs != sibling->breadcrumbs) {
3990 				intel_breadcrumbs_put(engine->breadcrumbs);
3991 				engine->breadcrumbs =
3992 					intel_breadcrumbs_get(sibling->breadcrumbs);
3993 			}
3994 			break;
3995 		}
3996 	}
3997 
3998 	if (engine->breadcrumbs) {
3999 		engine->breadcrumbs->engine_mask |= engine->mask;
4000 		engine->breadcrumbs->irq_enable = guc_irq_enable_breadcrumbs;
4001 		engine->breadcrumbs->irq_disable = guc_irq_disable_breadcrumbs;
4002 	}
4003 }
4004 
4005 static void guc_bump_inflight_request_prio(struct i915_request *rq,
4006 					   int prio)
4007 {
4008 	struct intel_context *ce = request_to_scheduling_context(rq);
4009 	u8 new_guc_prio = map_i915_prio_to_guc_prio(prio);
4010 
4011 	/* Short circuit function */
4012 	if (prio < I915_PRIORITY_NORMAL ||
4013 	    rq->guc_prio == GUC_PRIO_FINI ||
4014 	    (rq->guc_prio != GUC_PRIO_INIT &&
4015 	     !new_guc_prio_higher(rq->guc_prio, new_guc_prio)))
4016 		return;
4017 
4018 	spin_lock(&ce->guc_state.lock);
4019 	if (rq->guc_prio != GUC_PRIO_FINI) {
4020 		if (rq->guc_prio != GUC_PRIO_INIT)
4021 			sub_context_inflight_prio(ce, rq->guc_prio);
4022 		rq->guc_prio = new_guc_prio;
4023 		add_context_inflight_prio(ce, rq->guc_prio);
4024 		update_context_prio(ce);
4025 	}
4026 	spin_unlock(&ce->guc_state.lock);
4027 }
4028 
4029 static void guc_retire_inflight_request_prio(struct i915_request *rq)
4030 {
4031 	struct intel_context *ce = request_to_scheduling_context(rq);
4032 
4033 	spin_lock(&ce->guc_state.lock);
4034 	guc_prio_fini(rq, ce);
4035 	spin_unlock(&ce->guc_state.lock);
4036 }
4037 
4038 static void sanitize_hwsp(struct intel_engine_cs *engine)
4039 {
4040 	struct intel_timeline *tl;
4041 
4042 	list_for_each_entry(tl, &engine->status_page.timelines, engine_link)
4043 		intel_timeline_reset_seqno(tl);
4044 }
4045 
4046 static void guc_sanitize(struct intel_engine_cs *engine)
4047 {
4048 	/*
4049 	 * Poison residual state on resume, in case the suspend didn't!
4050 	 *
4051 	 * We have to assume that across suspend/resume (or other loss
4052 	 * of control) that the contents of our pinned buffers has been
4053 	 * lost, replaced by garbage. Since this doesn't always happen,
4054 	 * let's poison such state so that we more quickly spot when
4055 	 * we falsely assume it has been preserved.
4056 	 */
4057 	if (IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM))
4058 		memset(engine->status_page.addr, POISON_INUSE, PAGE_SIZE);
4059 
4060 	/*
4061 	 * The kernel_context HWSP is stored in the status_page. As above,
4062 	 * that may be lost on resume/initialisation, and so we need to
4063 	 * reset the value in the HWSP.
4064 	 */
4065 	sanitize_hwsp(engine);
4066 
4067 	/* And scrub the dirty cachelines for the HWSP */
4068 	drm_clflush_virt_range(engine->status_page.addr, PAGE_SIZE);
4069 
4070 	intel_engine_reset_pinned_contexts(engine);
4071 }
4072 
4073 static void setup_hwsp(struct intel_engine_cs *engine)
4074 {
4075 	intel_engine_set_hwsp_writemask(engine, ~0u); /* HWSTAM */
4076 
4077 	ENGINE_WRITE_FW(engine,
4078 			RING_HWS_PGA,
4079 			i915_ggtt_offset(engine->status_page.vma));
4080 }
4081 
4082 static void start_engine(struct intel_engine_cs *engine)
4083 {
4084 	ENGINE_WRITE_FW(engine,
4085 			RING_MODE_GEN7,
4086 			_MASKED_BIT_ENABLE(GEN11_GFX_DISABLE_LEGACY_MODE));
4087 
4088 	ENGINE_WRITE_FW(engine, RING_MI_MODE, _MASKED_BIT_DISABLE(STOP_RING));
4089 	ENGINE_POSTING_READ(engine, RING_MI_MODE);
4090 }
4091 
4092 static int guc_resume(struct intel_engine_cs *engine)
4093 {
4094 	assert_forcewakes_active(engine->uncore, FORCEWAKE_ALL);
4095 
4096 	intel_mocs_init_engine(engine);
4097 
4098 	intel_breadcrumbs_reset(engine->breadcrumbs);
4099 
4100 	setup_hwsp(engine);
4101 	start_engine(engine);
4102 
4103 	if (engine->flags & I915_ENGINE_FIRST_RENDER_COMPUTE)
4104 		xehp_enable_ccs_engines(engine);
4105 
4106 	return 0;
4107 }
4108 
4109 static bool guc_sched_engine_disabled(struct i915_sched_engine *sched_engine)
4110 {
4111 	return !sched_engine->tasklet.callback;
4112 }
4113 
4114 static void guc_set_default_submission(struct intel_engine_cs *engine)
4115 {
4116 	engine->submit_request = guc_submit_request;
4117 }
4118 
4119 static inline int guc_kernel_context_pin(struct intel_guc *guc,
4120 					 struct intel_context *ce)
4121 {
4122 	int ret;
4123 
4124 	/*
4125 	 * Note: we purposefully do not check the returns below because
4126 	 * the registration can only fail if a reset is just starting.
4127 	 * This is called at the end of reset so presumably another reset
4128 	 * isn't happening and even it did this code would be run again.
4129 	 */
4130 
4131 	if (context_guc_id_invalid(ce)) {
4132 		ret = pin_guc_id(guc, ce);
4133 
4134 		if (ret < 0)
4135 			return ret;
4136 	}
4137 
4138 	if (!test_bit(CONTEXT_GUC_INIT, &ce->flags))
4139 		guc_context_init(ce);
4140 
4141 	ret = try_context_registration(ce, true);
4142 	if (ret)
4143 		unpin_guc_id(guc, ce);
4144 
4145 	return ret;
4146 }
4147 
4148 static inline int guc_init_submission(struct intel_guc *guc)
4149 {
4150 	struct intel_gt *gt = guc_to_gt(guc);
4151 	struct intel_engine_cs *engine;
4152 	enum intel_engine_id id;
4153 
4154 	/* make sure all descriptors are clean... */
4155 	xa_destroy(&guc->context_lookup);
4156 
4157 	/*
4158 	 * A reset might have occurred while we had a pending stalled request,
4159 	 * so make sure we clean that up.
4160 	 */
4161 	guc->stalled_request = NULL;
4162 	guc->submission_stall_reason = STALL_NONE;
4163 
4164 	/*
4165 	 * Some contexts might have been pinned before we enabled GuC
4166 	 * submission, so we need to add them to the GuC bookeeping.
4167 	 * Also, after a reset the of the GuC we want to make sure that the
4168 	 * information shared with GuC is properly reset. The kernel LRCs are
4169 	 * not attached to the gem_context, so they need to be added separately.
4170 	 */
4171 	for_each_engine(engine, gt, id) {
4172 		struct intel_context *ce;
4173 
4174 		list_for_each_entry(ce, &engine->pinned_contexts_list,
4175 				    pinned_contexts_link) {
4176 			int ret = guc_kernel_context_pin(guc, ce);
4177 
4178 			if (ret) {
4179 				/* No point in trying to clean up as i915 will wedge on failure */
4180 				return ret;
4181 			}
4182 		}
4183 	}
4184 
4185 	return 0;
4186 }
4187 
4188 static void guc_release(struct intel_engine_cs *engine)
4189 {
4190 	engine->sanitize = NULL; /* no longer in control, nothing to sanitize */
4191 
4192 	intel_engine_cleanup_common(engine);
4193 	lrc_fini_wa_ctx(engine);
4194 }
4195 
4196 static void virtual_guc_bump_serial(struct intel_engine_cs *engine)
4197 {
4198 	struct intel_engine_cs *e;
4199 	intel_engine_mask_t tmp, mask = engine->mask;
4200 
4201 	for_each_engine_masked(e, engine->gt, mask, tmp)
4202 		e->serial++;
4203 }
4204 
4205 static void guc_default_vfuncs(struct intel_engine_cs *engine)
4206 {
4207 	/* Default vfuncs which can be overridden by each engine. */
4208 
4209 	engine->resume = guc_resume;
4210 
4211 	engine->cops = &guc_context_ops;
4212 	engine->request_alloc = guc_request_alloc;
4213 	engine->add_active_request = add_to_context;
4214 	engine->remove_active_request = remove_from_context;
4215 
4216 	engine->sched_engine->schedule = i915_schedule;
4217 
4218 	engine->reset.prepare = guc_engine_reset_prepare;
4219 	engine->reset.rewind = guc_rewind_nop;
4220 	engine->reset.cancel = guc_reset_nop;
4221 	engine->reset.finish = guc_reset_nop;
4222 
4223 	engine->emit_flush = gen8_emit_flush_xcs;
4224 	engine->emit_init_breadcrumb = gen8_emit_init_breadcrumb;
4225 	engine->emit_fini_breadcrumb = gen8_emit_fini_breadcrumb_xcs;
4226 	if (GRAPHICS_VER(engine->i915) >= 12) {
4227 		engine->emit_fini_breadcrumb = gen12_emit_fini_breadcrumb_xcs;
4228 		engine->emit_flush = gen12_emit_flush_xcs;
4229 	}
4230 	engine->set_default_submission = guc_set_default_submission;
4231 	engine->busyness = guc_engine_busyness;
4232 
4233 	engine->flags |= I915_ENGINE_SUPPORTS_STATS;
4234 	engine->flags |= I915_ENGINE_HAS_PREEMPTION;
4235 	engine->flags |= I915_ENGINE_HAS_TIMESLICES;
4236 
4237 	/* Wa_14014475959:dg2 */
4238 	if (engine->class == COMPUTE_CLASS)
4239 		if (IS_MTL_GRAPHICS_STEP(engine->i915, M, STEP_A0, STEP_B0) ||
4240 		    IS_DG2(engine->i915))
4241 			engine->flags |= I915_ENGINE_USES_WA_HOLD_CCS_SWITCHOUT;
4242 
4243 	/*
4244 	 * TODO: GuC supports timeslicing and semaphores as well, but they're
4245 	 * handled by the firmware so some minor tweaks are required before
4246 	 * enabling.
4247 	 *
4248 	 * engine->flags |= I915_ENGINE_HAS_SEMAPHORES;
4249 	 */
4250 
4251 	engine->emit_bb_start = gen8_emit_bb_start;
4252 	if (GRAPHICS_VER_FULL(engine->i915) >= IP_VER(12, 50))
4253 		engine->emit_bb_start = xehp_emit_bb_start;
4254 }
4255 
4256 static void rcs_submission_override(struct intel_engine_cs *engine)
4257 {
4258 	switch (GRAPHICS_VER(engine->i915)) {
4259 	case 12:
4260 		engine->emit_flush = gen12_emit_flush_rcs;
4261 		engine->emit_fini_breadcrumb = gen12_emit_fini_breadcrumb_rcs;
4262 		break;
4263 	case 11:
4264 		engine->emit_flush = gen11_emit_flush_rcs;
4265 		engine->emit_fini_breadcrumb = gen11_emit_fini_breadcrumb_rcs;
4266 		break;
4267 	default:
4268 		engine->emit_flush = gen8_emit_flush_rcs;
4269 		engine->emit_fini_breadcrumb = gen8_emit_fini_breadcrumb_rcs;
4270 		break;
4271 	}
4272 }
4273 
4274 static inline void guc_default_irqs(struct intel_engine_cs *engine)
4275 {
4276 	engine->irq_keep_mask = GT_RENDER_USER_INTERRUPT;
4277 	intel_engine_set_irq_handler(engine, cs_irq_handler);
4278 }
4279 
4280 static void guc_sched_engine_destroy(struct kref *kref)
4281 {
4282 	struct i915_sched_engine *sched_engine =
4283 		container_of(kref, typeof(*sched_engine), ref);
4284 	struct intel_guc *guc = sched_engine->private_data;
4285 
4286 	guc->sched_engine = NULL;
4287 	tasklet_kill(&sched_engine->tasklet); /* flush the callback */
4288 	kfree(sched_engine);
4289 }
4290 
4291 int intel_guc_submission_setup(struct intel_engine_cs *engine)
4292 {
4293 	struct drm_i915_private *i915 = engine->i915;
4294 	struct intel_guc *guc = &engine->gt->uc.guc;
4295 
4296 	/*
4297 	 * The setup relies on several assumptions (e.g. irqs always enabled)
4298 	 * that are only valid on gen11+
4299 	 */
4300 	GEM_BUG_ON(GRAPHICS_VER(i915) < 11);
4301 
4302 	if (!guc->sched_engine) {
4303 		guc->sched_engine = i915_sched_engine_create(ENGINE_VIRTUAL);
4304 		if (!guc->sched_engine)
4305 			return -ENOMEM;
4306 
4307 		guc->sched_engine->schedule = i915_schedule;
4308 		guc->sched_engine->disabled = guc_sched_engine_disabled;
4309 		guc->sched_engine->private_data = guc;
4310 		guc->sched_engine->destroy = guc_sched_engine_destroy;
4311 		guc->sched_engine->bump_inflight_request_prio =
4312 			guc_bump_inflight_request_prio;
4313 		guc->sched_engine->retire_inflight_request_prio =
4314 			guc_retire_inflight_request_prio;
4315 		tasklet_setup(&guc->sched_engine->tasklet,
4316 			      guc_submission_tasklet);
4317 	}
4318 	i915_sched_engine_put(engine->sched_engine);
4319 	engine->sched_engine = i915_sched_engine_get(guc->sched_engine);
4320 
4321 	guc_default_vfuncs(engine);
4322 	guc_default_irqs(engine);
4323 	guc_init_breadcrumbs(engine);
4324 
4325 	if (engine->flags & I915_ENGINE_HAS_RCS_REG_STATE)
4326 		rcs_submission_override(engine);
4327 
4328 	lrc_init_wa_ctx(engine);
4329 
4330 	/* Finally, take ownership and responsibility for cleanup! */
4331 	engine->sanitize = guc_sanitize;
4332 	engine->release = guc_release;
4333 
4334 	return 0;
4335 }
4336 
4337 struct scheduling_policy {
4338 	/* internal data */
4339 	u32 max_words, num_words;
4340 	u32 count;
4341 	/* API data */
4342 	struct guc_update_scheduling_policy h2g;
4343 };
4344 
4345 static u32 __guc_scheduling_policy_action_size(struct scheduling_policy *policy)
4346 {
4347 	u32 *start = (void *)&policy->h2g;
4348 	u32 *end = policy->h2g.data + policy->num_words;
4349 	size_t delta = end - start;
4350 
4351 	return delta;
4352 }
4353 
4354 static struct scheduling_policy *__guc_scheduling_policy_start_klv(struct scheduling_policy *policy)
4355 {
4356 	policy->h2g.header.action = INTEL_GUC_ACTION_UPDATE_SCHEDULING_POLICIES_KLV;
4357 	policy->max_words = ARRAY_SIZE(policy->h2g.data);
4358 	policy->num_words = 0;
4359 	policy->count = 0;
4360 
4361 	return policy;
4362 }
4363 
4364 static void __guc_scheduling_policy_add_klv(struct scheduling_policy *policy,
4365 					    u32 action, u32 *data, u32 len)
4366 {
4367 	u32 *klv_ptr = policy->h2g.data + policy->num_words;
4368 
4369 	GEM_BUG_ON((policy->num_words + 1 + len) > policy->max_words);
4370 	*(klv_ptr++) = FIELD_PREP(GUC_KLV_0_KEY, action) |
4371 		       FIELD_PREP(GUC_KLV_0_LEN, len);
4372 	memcpy(klv_ptr, data, sizeof(u32) * len);
4373 	policy->num_words += 1 + len;
4374 	policy->count++;
4375 }
4376 
4377 static int __guc_action_set_scheduling_policies(struct intel_guc *guc,
4378 						struct scheduling_policy *policy)
4379 {
4380 	int ret;
4381 
4382 	ret = intel_guc_send(guc, (u32 *)&policy->h2g,
4383 			     __guc_scheduling_policy_action_size(policy));
4384 	if (ret < 0) {
4385 		guc_probe_error(guc, "Failed to configure global scheduling policies: %pe!\n",
4386 				ERR_PTR(ret));
4387 		return ret;
4388 	}
4389 
4390 	if (ret != policy->count) {
4391 		guc_warn(guc, "global scheduler policy processed %d of %d KLVs!",
4392 			 ret, policy->count);
4393 		if (ret > policy->count)
4394 			return -EPROTO;
4395 	}
4396 
4397 	return 0;
4398 }
4399 
4400 static int guc_init_global_schedule_policy(struct intel_guc *guc)
4401 {
4402 	struct scheduling_policy policy;
4403 	struct intel_gt *gt = guc_to_gt(guc);
4404 	intel_wakeref_t wakeref;
4405 	int ret;
4406 
4407 	if (GUC_SUBMIT_VER(guc) < MAKE_GUC_VER(1, 1, 0))
4408 		return 0;
4409 
4410 	__guc_scheduling_policy_start_klv(&policy);
4411 
4412 	with_intel_runtime_pm(&gt->i915->runtime_pm, wakeref) {
4413 		u32 yield[] = {
4414 			GLOBAL_SCHEDULE_POLICY_RC_YIELD_DURATION,
4415 			GLOBAL_SCHEDULE_POLICY_RC_YIELD_RATIO,
4416 		};
4417 
4418 		__guc_scheduling_policy_add_klv(&policy,
4419 						GUC_SCHEDULING_POLICIES_KLV_ID_RENDER_COMPUTE_YIELD,
4420 						yield, ARRAY_SIZE(yield));
4421 
4422 		ret = __guc_action_set_scheduling_policies(guc, &policy);
4423 	}
4424 
4425 	return ret;
4426 }
4427 
4428 static void guc_route_semaphores(struct intel_guc *guc, bool to_guc)
4429 {
4430 	struct intel_gt *gt = guc_to_gt(guc);
4431 	u32 val;
4432 
4433 	if (GRAPHICS_VER(gt->i915) < 12)
4434 		return;
4435 
4436 	if (to_guc)
4437 		val = GUC_SEM_INTR_ROUTE_TO_GUC | GUC_SEM_INTR_ENABLE_ALL;
4438 	else
4439 		val = 0;
4440 
4441 	intel_uncore_write(gt->uncore, GEN12_GUC_SEM_INTR_ENABLES, val);
4442 }
4443 
4444 int intel_guc_submission_enable(struct intel_guc *guc)
4445 {
4446 	int ret;
4447 
4448 	/* Semaphore interrupt enable and route to GuC */
4449 	guc_route_semaphores(guc, true);
4450 
4451 	ret = guc_init_submission(guc);
4452 	if (ret)
4453 		goto fail_sem;
4454 
4455 	ret = guc_init_engine_stats(guc);
4456 	if (ret)
4457 		goto fail_sem;
4458 
4459 	ret = guc_init_global_schedule_policy(guc);
4460 	if (ret)
4461 		goto fail_stats;
4462 
4463 	return 0;
4464 
4465 fail_stats:
4466 	guc_fini_engine_stats(guc);
4467 fail_sem:
4468 	guc_route_semaphores(guc, false);
4469 	return ret;
4470 }
4471 
4472 /* Note: By the time we're here, GuC may have already been reset */
4473 void intel_guc_submission_disable(struct intel_guc *guc)
4474 {
4475 	guc_cancel_busyness_worker(guc);
4476 
4477 	/* Semaphore interrupt disable and route to host */
4478 	guc_route_semaphores(guc, false);
4479 }
4480 
4481 static bool __guc_submission_supported(struct intel_guc *guc)
4482 {
4483 	/* GuC submission is unavailable for pre-Gen11 */
4484 	return intel_guc_is_supported(guc) &&
4485 	       GRAPHICS_VER(guc_to_gt(guc)->i915) >= 11;
4486 }
4487 
4488 static bool __guc_submission_selected(struct intel_guc *guc)
4489 {
4490 	struct drm_i915_private *i915 = guc_to_gt(guc)->i915;
4491 
4492 	if (!intel_guc_submission_is_supported(guc))
4493 		return false;
4494 
4495 	return i915->params.enable_guc & ENABLE_GUC_SUBMISSION;
4496 }
4497 
4498 int intel_guc_sched_disable_gucid_threshold_max(struct intel_guc *guc)
4499 {
4500 	return guc->submission_state.num_guc_ids - NUMBER_MULTI_LRC_GUC_ID(guc);
4501 }
4502 
4503 /*
4504  * This default value of 33 milisecs (+1 milisec round up) ensures 30fps or higher
4505  * workloads are able to enjoy the latency reduction when delaying the schedule-disable
4506  * operation. This matches the 30fps game-render + encode (real world) workload this
4507  * knob was tested against.
4508  */
4509 #define SCHED_DISABLE_DELAY_MS	34
4510 
4511 /*
4512  * A threshold of 75% is a reasonable starting point considering that real world apps
4513  * generally don't get anywhere near this.
4514  */
4515 #define NUM_SCHED_DISABLE_GUCIDS_DEFAULT_THRESHOLD(__guc) \
4516 	(((intel_guc_sched_disable_gucid_threshold_max(guc)) * 3) / 4)
4517 
4518 void intel_guc_submission_init_early(struct intel_guc *guc)
4519 {
4520 	xa_init_flags(&guc->context_lookup, XA_FLAGS_LOCK_IRQ);
4521 
4522 	spin_lock_init(&guc->submission_state.lock);
4523 	INIT_LIST_HEAD(&guc->submission_state.guc_id_list);
4524 	ida_init(&guc->submission_state.guc_ids);
4525 	INIT_LIST_HEAD(&guc->submission_state.destroyed_contexts);
4526 	INIT_WORK(&guc->submission_state.destroyed_worker,
4527 		  destroyed_worker_func);
4528 	INIT_WORK(&guc->submission_state.reset_fail_worker,
4529 		  reset_fail_worker_func);
4530 
4531 	spin_lock_init(&guc->timestamp.lock);
4532 	INIT_DELAYED_WORK(&guc->timestamp.work, guc_timestamp_ping);
4533 
4534 	guc->submission_state.sched_disable_delay_ms = SCHED_DISABLE_DELAY_MS;
4535 	guc->submission_state.num_guc_ids = GUC_MAX_CONTEXT_ID;
4536 	guc->submission_state.sched_disable_gucid_threshold =
4537 		NUM_SCHED_DISABLE_GUCIDS_DEFAULT_THRESHOLD(guc);
4538 	guc->submission_supported = __guc_submission_supported(guc);
4539 	guc->submission_selected = __guc_submission_selected(guc);
4540 }
4541 
4542 static inline struct intel_context *
4543 g2h_context_lookup(struct intel_guc *guc, u32 ctx_id)
4544 {
4545 	struct intel_context *ce;
4546 
4547 	if (unlikely(ctx_id >= GUC_MAX_CONTEXT_ID)) {
4548 		guc_err(guc, "Invalid ctx_id %u\n", ctx_id);
4549 		return NULL;
4550 	}
4551 
4552 	ce = __get_context(guc, ctx_id);
4553 	if (unlikely(!ce)) {
4554 		guc_err(guc, "Context is NULL, ctx_id %u\n", ctx_id);
4555 		return NULL;
4556 	}
4557 
4558 	if (unlikely(intel_context_is_child(ce))) {
4559 		guc_err(guc, "Context is child, ctx_id %u\n", ctx_id);
4560 		return NULL;
4561 	}
4562 
4563 	return ce;
4564 }
4565 
4566 int intel_guc_deregister_done_process_msg(struct intel_guc *guc,
4567 					  const u32 *msg,
4568 					  u32 len)
4569 {
4570 	struct intel_context *ce;
4571 	u32 ctx_id;
4572 
4573 	if (unlikely(len < 1)) {
4574 		guc_err(guc, "Invalid length %u\n", len);
4575 		return -EPROTO;
4576 	}
4577 	ctx_id = msg[0];
4578 
4579 	ce = g2h_context_lookup(guc, ctx_id);
4580 	if (unlikely(!ce))
4581 		return -EPROTO;
4582 
4583 	trace_intel_context_deregister_done(ce);
4584 
4585 #ifdef CONFIG_DRM_I915_SELFTEST
4586 	if (unlikely(ce->drop_deregister)) {
4587 		ce->drop_deregister = false;
4588 		return 0;
4589 	}
4590 #endif
4591 
4592 	if (context_wait_for_deregister_to_register(ce)) {
4593 		struct intel_runtime_pm *runtime_pm =
4594 			&ce->engine->gt->i915->runtime_pm;
4595 		intel_wakeref_t wakeref;
4596 
4597 		/*
4598 		 * Previous owner of this guc_id has been deregistered, now safe
4599 		 * register this context.
4600 		 */
4601 		with_intel_runtime_pm(runtime_pm, wakeref)
4602 			register_context(ce, true);
4603 		guc_signal_context_fence(ce);
4604 		intel_context_put(ce);
4605 	} else if (context_destroyed(ce)) {
4606 		/* Context has been destroyed */
4607 		intel_gt_pm_put_async(guc_to_gt(guc));
4608 		release_guc_id(guc, ce);
4609 		__guc_context_destroy(ce);
4610 	}
4611 
4612 	decr_outstanding_submission_g2h(guc);
4613 
4614 	return 0;
4615 }
4616 
4617 int intel_guc_sched_done_process_msg(struct intel_guc *guc,
4618 				     const u32 *msg,
4619 				     u32 len)
4620 {
4621 	struct intel_context *ce;
4622 	unsigned long flags;
4623 	u32 ctx_id;
4624 
4625 	if (unlikely(len < 2)) {
4626 		guc_err(guc, "Invalid length %u\n", len);
4627 		return -EPROTO;
4628 	}
4629 	ctx_id = msg[0];
4630 
4631 	ce = g2h_context_lookup(guc, ctx_id);
4632 	if (unlikely(!ce))
4633 		return -EPROTO;
4634 
4635 	if (unlikely(context_destroyed(ce) ||
4636 		     (!context_pending_enable(ce) &&
4637 		     !context_pending_disable(ce)))) {
4638 		guc_err(guc, "Bad context sched_state 0x%x, ctx_id %u\n",
4639 			ce->guc_state.sched_state, ctx_id);
4640 		return -EPROTO;
4641 	}
4642 
4643 	trace_intel_context_sched_done(ce);
4644 
4645 	if (context_pending_enable(ce)) {
4646 #ifdef CONFIG_DRM_I915_SELFTEST
4647 		if (unlikely(ce->drop_schedule_enable)) {
4648 			ce->drop_schedule_enable = false;
4649 			return 0;
4650 		}
4651 #endif
4652 
4653 		spin_lock_irqsave(&ce->guc_state.lock, flags);
4654 		clr_context_pending_enable(ce);
4655 		spin_unlock_irqrestore(&ce->guc_state.lock, flags);
4656 	} else if (context_pending_disable(ce)) {
4657 		bool banned;
4658 
4659 #ifdef CONFIG_DRM_I915_SELFTEST
4660 		if (unlikely(ce->drop_schedule_disable)) {
4661 			ce->drop_schedule_disable = false;
4662 			return 0;
4663 		}
4664 #endif
4665 
4666 		/*
4667 		 * Unpin must be done before __guc_signal_context_fence,
4668 		 * otherwise a race exists between the requests getting
4669 		 * submitted + retired before this unpin completes resulting in
4670 		 * the pin_count going to zero and the context still being
4671 		 * enabled.
4672 		 */
4673 		intel_context_sched_disable_unpin(ce);
4674 
4675 		spin_lock_irqsave(&ce->guc_state.lock, flags);
4676 		banned = context_banned(ce);
4677 		clr_context_banned(ce);
4678 		clr_context_pending_disable(ce);
4679 		__guc_signal_context_fence(ce);
4680 		guc_blocked_fence_complete(ce);
4681 		spin_unlock_irqrestore(&ce->guc_state.lock, flags);
4682 
4683 		if (banned) {
4684 			guc_cancel_context_requests(ce);
4685 			intel_engine_signal_breadcrumbs(ce->engine);
4686 		}
4687 	}
4688 
4689 	decr_outstanding_submission_g2h(guc);
4690 	intel_context_put(ce);
4691 
4692 	return 0;
4693 }
4694 
4695 static void capture_error_state(struct intel_guc *guc,
4696 				struct intel_context *ce)
4697 {
4698 	struct intel_gt *gt = guc_to_gt(guc);
4699 	struct drm_i915_private *i915 = gt->i915;
4700 	struct intel_engine_cs *engine = __context_to_physical_engine(ce);
4701 	intel_wakeref_t wakeref;
4702 
4703 	intel_engine_set_hung_context(engine, ce);
4704 	with_intel_runtime_pm(&i915->runtime_pm, wakeref)
4705 		i915_capture_error_state(gt, engine->mask, CORE_DUMP_FLAG_IS_GUC_CAPTURE);
4706 	atomic_inc(&i915->gpu_error.reset_engine_count[engine->uabi_class]);
4707 }
4708 
4709 static void guc_context_replay(struct intel_context *ce)
4710 {
4711 	struct i915_sched_engine *sched_engine = ce->engine->sched_engine;
4712 
4713 	__guc_reset_context(ce, ce->engine->mask);
4714 	tasklet_hi_schedule(&sched_engine->tasklet);
4715 }
4716 
4717 static void guc_handle_context_reset(struct intel_guc *guc,
4718 				     struct intel_context *ce)
4719 {
4720 	trace_intel_context_reset(ce);
4721 
4722 	guc_dbg(guc, "Got context reset notification: 0x%04X on %s, exiting = %s, banned = %s\n",
4723 		ce->guc_id.id, ce->engine->name,
4724 		str_yes_no(intel_context_is_exiting(ce)),
4725 		str_yes_no(intel_context_is_banned(ce)));
4726 
4727 	if (likely(intel_context_is_schedulable(ce))) {
4728 		capture_error_state(guc, ce);
4729 		guc_context_replay(ce);
4730 	} else {
4731 		guc_info(guc, "Ignoring context reset notification of exiting context 0x%04X on %s",
4732 			 ce->guc_id.id, ce->engine->name);
4733 	}
4734 }
4735 
4736 int intel_guc_context_reset_process_msg(struct intel_guc *guc,
4737 					const u32 *msg, u32 len)
4738 {
4739 	struct intel_context *ce;
4740 	unsigned long flags;
4741 	int ctx_id;
4742 
4743 	if (unlikely(len != 1)) {
4744 		guc_err(guc, "Invalid length %u", len);
4745 		return -EPROTO;
4746 	}
4747 
4748 	ctx_id = msg[0];
4749 
4750 	/*
4751 	 * The context lookup uses the xarray but lookups only require an RCU lock
4752 	 * not the full spinlock. So take the lock explicitly and keep it until the
4753 	 * context has been reference count locked to ensure it can't be destroyed
4754 	 * asynchronously until the reset is done.
4755 	 */
4756 	xa_lock_irqsave(&guc->context_lookup, flags);
4757 	ce = g2h_context_lookup(guc, ctx_id);
4758 	if (ce)
4759 		intel_context_get(ce);
4760 	xa_unlock_irqrestore(&guc->context_lookup, flags);
4761 
4762 	if (unlikely(!ce))
4763 		return -EPROTO;
4764 
4765 	guc_handle_context_reset(guc, ce);
4766 	intel_context_put(ce);
4767 
4768 	return 0;
4769 }
4770 
4771 int intel_guc_error_capture_process_msg(struct intel_guc *guc,
4772 					const u32 *msg, u32 len)
4773 {
4774 	u32 status;
4775 
4776 	if (unlikely(len != 1)) {
4777 		guc_dbg(guc, "Invalid length %u", len);
4778 		return -EPROTO;
4779 	}
4780 
4781 	status = msg[0] & INTEL_GUC_STATE_CAPTURE_EVENT_STATUS_MASK;
4782 	if (status == INTEL_GUC_STATE_CAPTURE_EVENT_STATUS_NOSPACE)
4783 		guc_warn(guc, "No space for error capture");
4784 
4785 	intel_guc_capture_process(guc);
4786 
4787 	return 0;
4788 }
4789 
4790 struct intel_engine_cs *
4791 intel_guc_lookup_engine(struct intel_guc *guc, u8 guc_class, u8 instance)
4792 {
4793 	struct intel_gt *gt = guc_to_gt(guc);
4794 	u8 engine_class = guc_class_to_engine_class(guc_class);
4795 
4796 	/* Class index is checked in class converter */
4797 	GEM_BUG_ON(instance > MAX_ENGINE_INSTANCE);
4798 
4799 	return gt->engine_class[engine_class][instance];
4800 }
4801 
4802 static void reset_fail_worker_func(struct work_struct *w)
4803 {
4804 	struct intel_guc *guc = container_of(w, struct intel_guc,
4805 					     submission_state.reset_fail_worker);
4806 	struct intel_gt *gt = guc_to_gt(guc);
4807 	intel_engine_mask_t reset_fail_mask;
4808 	unsigned long flags;
4809 
4810 	spin_lock_irqsave(&guc->submission_state.lock, flags);
4811 	reset_fail_mask = guc->submission_state.reset_fail_mask;
4812 	guc->submission_state.reset_fail_mask = 0;
4813 	spin_unlock_irqrestore(&guc->submission_state.lock, flags);
4814 
4815 	if (likely(reset_fail_mask)) {
4816 		struct intel_engine_cs *engine;
4817 		enum intel_engine_id id;
4818 
4819 		/*
4820 		 * GuC is toast at this point - it dead loops after sending the failed
4821 		 * reset notification. So need to manually determine the guilty context.
4822 		 * Note that it should be reliable to do this here because the GuC is
4823 		 * toast and will not be scheduling behind the KMD's back.
4824 		 */
4825 		for_each_engine_masked(engine, gt, reset_fail_mask, id)
4826 			intel_guc_find_hung_context(engine);
4827 
4828 		intel_gt_handle_error(gt, reset_fail_mask,
4829 				      I915_ERROR_CAPTURE,
4830 				      "GuC failed to reset engine mask=0x%x",
4831 				      reset_fail_mask);
4832 	}
4833 }
4834 
4835 int intel_guc_engine_failure_process_msg(struct intel_guc *guc,
4836 					 const u32 *msg, u32 len)
4837 {
4838 	struct intel_engine_cs *engine;
4839 	u8 guc_class, instance;
4840 	u32 reason;
4841 	unsigned long flags;
4842 
4843 	if (unlikely(len != 3)) {
4844 		guc_err(guc, "Invalid length %u", len);
4845 		return -EPROTO;
4846 	}
4847 
4848 	guc_class = msg[0];
4849 	instance = msg[1];
4850 	reason = msg[2];
4851 
4852 	engine = intel_guc_lookup_engine(guc, guc_class, instance);
4853 	if (unlikely(!engine)) {
4854 		guc_err(guc, "Invalid engine %d:%d", guc_class, instance);
4855 		return -EPROTO;
4856 	}
4857 
4858 	/*
4859 	 * This is an unexpected failure of a hardware feature. So, log a real
4860 	 * error message not just the informational that comes with the reset.
4861 	 */
4862 	guc_err(guc, "Engine reset failed on %d:%d (%s) because 0x%08X",
4863 		guc_class, instance, engine->name, reason);
4864 
4865 	spin_lock_irqsave(&guc->submission_state.lock, flags);
4866 	guc->submission_state.reset_fail_mask |= engine->mask;
4867 	spin_unlock_irqrestore(&guc->submission_state.lock, flags);
4868 
4869 	/*
4870 	 * A GT reset flushes this worker queue (G2H handler) so we must use
4871 	 * another worker to trigger a GT reset.
4872 	 */
4873 	queue_work(system_unbound_wq, &guc->submission_state.reset_fail_worker);
4874 
4875 	return 0;
4876 }
4877 
4878 void intel_guc_find_hung_context(struct intel_engine_cs *engine)
4879 {
4880 	struct intel_guc *guc = &engine->gt->uc.guc;
4881 	struct intel_context *ce;
4882 	struct i915_request *rq;
4883 	unsigned long index;
4884 	unsigned long flags;
4885 
4886 	/* Reset called during driver load? GuC not yet initialised! */
4887 	if (unlikely(!guc_submission_initialized(guc)))
4888 		return;
4889 
4890 	xa_lock_irqsave(&guc->context_lookup, flags);
4891 	xa_for_each(&guc->context_lookup, index, ce) {
4892 		bool found;
4893 
4894 		if (!kref_get_unless_zero(&ce->ref))
4895 			continue;
4896 
4897 		xa_unlock(&guc->context_lookup);
4898 
4899 		if (!intel_context_is_pinned(ce))
4900 			goto next;
4901 
4902 		if (intel_engine_is_virtual(ce->engine)) {
4903 			if (!(ce->engine->mask & engine->mask))
4904 				goto next;
4905 		} else {
4906 			if (ce->engine != engine)
4907 				goto next;
4908 		}
4909 
4910 		found = false;
4911 		spin_lock(&ce->guc_state.lock);
4912 		list_for_each_entry(rq, &ce->guc_state.requests, sched.link) {
4913 			if (i915_test_request_state(rq) != I915_REQUEST_ACTIVE)
4914 				continue;
4915 
4916 			found = true;
4917 			break;
4918 		}
4919 		spin_unlock(&ce->guc_state.lock);
4920 
4921 		if (found) {
4922 			intel_engine_set_hung_context(engine, ce);
4923 
4924 			/* Can only cope with one hang at a time... */
4925 			intel_context_put(ce);
4926 			xa_lock(&guc->context_lookup);
4927 			goto done;
4928 		}
4929 
4930 next:
4931 		intel_context_put(ce);
4932 		xa_lock(&guc->context_lookup);
4933 	}
4934 done:
4935 	xa_unlock_irqrestore(&guc->context_lookup, flags);
4936 }
4937 
4938 void intel_guc_dump_active_requests(struct intel_engine_cs *engine,
4939 				    struct i915_request *hung_rq,
4940 				    struct drm_printer *m)
4941 {
4942 	struct intel_guc *guc = &engine->gt->uc.guc;
4943 	struct intel_context *ce;
4944 	unsigned long index;
4945 	unsigned long flags;
4946 
4947 	/* Reset called during driver load? GuC not yet initialised! */
4948 	if (unlikely(!guc_submission_initialized(guc)))
4949 		return;
4950 
4951 	xa_lock_irqsave(&guc->context_lookup, flags);
4952 	xa_for_each(&guc->context_lookup, index, ce) {
4953 		if (!kref_get_unless_zero(&ce->ref))
4954 			continue;
4955 
4956 		xa_unlock(&guc->context_lookup);
4957 
4958 		if (!intel_context_is_pinned(ce))
4959 			goto next;
4960 
4961 		if (intel_engine_is_virtual(ce->engine)) {
4962 			if (!(ce->engine->mask & engine->mask))
4963 				goto next;
4964 		} else {
4965 			if (ce->engine != engine)
4966 				goto next;
4967 		}
4968 
4969 		spin_lock(&ce->guc_state.lock);
4970 		intel_engine_dump_active_requests(&ce->guc_state.requests,
4971 						  hung_rq, m);
4972 		spin_unlock(&ce->guc_state.lock);
4973 
4974 next:
4975 		intel_context_put(ce);
4976 		xa_lock(&guc->context_lookup);
4977 	}
4978 	xa_unlock_irqrestore(&guc->context_lookup, flags);
4979 }
4980 
4981 void intel_guc_submission_print_info(struct intel_guc *guc,
4982 				     struct drm_printer *p)
4983 {
4984 	struct i915_sched_engine *sched_engine = guc->sched_engine;
4985 	struct rb_node *rb;
4986 	unsigned long flags;
4987 
4988 	if (!sched_engine)
4989 		return;
4990 
4991 	drm_printf(p, "GuC Submission API Version: %d.%d.%d\n",
4992 		   guc->submission_version.major, guc->submission_version.minor,
4993 		   guc->submission_version.patch);
4994 	drm_printf(p, "GuC Number Outstanding Submission G2H: %u\n",
4995 		   atomic_read(&guc->outstanding_submission_g2h));
4996 	drm_printf(p, "GuC tasklet count: %u\n",
4997 		   atomic_read(&sched_engine->tasklet.count));
4998 
4999 	spin_lock_irqsave(&sched_engine->lock, flags);
5000 	drm_printf(p, "Requests in GuC submit tasklet:\n");
5001 	for (rb = rb_first_cached(&sched_engine->queue); rb; rb = rb_next(rb)) {
5002 		struct i915_priolist *pl = to_priolist(rb);
5003 		struct i915_request *rq;
5004 
5005 		priolist_for_each_request(rq, pl)
5006 			drm_printf(p, "guc_id=%u, seqno=%llu\n",
5007 				   rq->context->guc_id.id,
5008 				   rq->fence.seqno);
5009 	}
5010 	spin_unlock_irqrestore(&sched_engine->lock, flags);
5011 	drm_printf(p, "\n");
5012 }
5013 
5014 static inline void guc_log_context_priority(struct drm_printer *p,
5015 					    struct intel_context *ce)
5016 {
5017 	int i;
5018 
5019 	drm_printf(p, "\t\tPriority: %d\n", ce->guc_state.prio);
5020 	drm_printf(p, "\t\tNumber Requests (lower index == higher priority)\n");
5021 	for (i = GUC_CLIENT_PRIORITY_KMD_HIGH;
5022 	     i < GUC_CLIENT_PRIORITY_NUM; ++i) {
5023 		drm_printf(p, "\t\tNumber requests in priority band[%d]: %d\n",
5024 			   i, ce->guc_state.prio_count[i]);
5025 	}
5026 	drm_printf(p, "\n");
5027 }
5028 
5029 static inline void guc_log_context(struct drm_printer *p,
5030 				   struct intel_context *ce)
5031 {
5032 	drm_printf(p, "GuC lrc descriptor %u:\n", ce->guc_id.id);
5033 	drm_printf(p, "\tHW Context Desc: 0x%08x\n", ce->lrc.lrca);
5034 	drm_printf(p, "\t\tLRC Head: Internal %u, Memory %u\n",
5035 		   ce->ring->head,
5036 		   ce->lrc_reg_state[CTX_RING_HEAD]);
5037 	drm_printf(p, "\t\tLRC Tail: Internal %u, Memory %u\n",
5038 		   ce->ring->tail,
5039 		   ce->lrc_reg_state[CTX_RING_TAIL]);
5040 	drm_printf(p, "\t\tContext Pin Count: %u\n",
5041 		   atomic_read(&ce->pin_count));
5042 	drm_printf(p, "\t\tGuC ID Ref Count: %u\n",
5043 		   atomic_read(&ce->guc_id.ref));
5044 	drm_printf(p, "\t\tSchedule State: 0x%x\n",
5045 		   ce->guc_state.sched_state);
5046 }
5047 
5048 void intel_guc_submission_print_context_info(struct intel_guc *guc,
5049 					     struct drm_printer *p)
5050 {
5051 	struct intel_context *ce;
5052 	unsigned long index;
5053 	unsigned long flags;
5054 
5055 	xa_lock_irqsave(&guc->context_lookup, flags);
5056 	xa_for_each(&guc->context_lookup, index, ce) {
5057 		GEM_BUG_ON(intel_context_is_child(ce));
5058 
5059 		guc_log_context(p, ce);
5060 		guc_log_context_priority(p, ce);
5061 
5062 		if (intel_context_is_parent(ce)) {
5063 			struct intel_context *child;
5064 
5065 			drm_printf(p, "\t\tNumber children: %u\n",
5066 				   ce->parallel.number_children);
5067 
5068 			if (ce->parallel.guc.wq_status) {
5069 				drm_printf(p, "\t\tWQI Head: %u\n",
5070 					   READ_ONCE(*ce->parallel.guc.wq_head));
5071 				drm_printf(p, "\t\tWQI Tail: %u\n",
5072 					   READ_ONCE(*ce->parallel.guc.wq_tail));
5073 				drm_printf(p, "\t\tWQI Status: %u\n",
5074 					   READ_ONCE(*ce->parallel.guc.wq_status));
5075 			}
5076 
5077 			if (ce->engine->emit_bb_start ==
5078 			    emit_bb_start_parent_no_preempt_mid_batch) {
5079 				u8 i;
5080 
5081 				drm_printf(p, "\t\tChildren Go: %u\n",
5082 					   get_children_go_value(ce));
5083 				for (i = 0; i < ce->parallel.number_children; ++i)
5084 					drm_printf(p, "\t\tChildren Join: %u\n",
5085 						   get_children_join_value(ce, i));
5086 			}
5087 
5088 			for_each_child(ce, child)
5089 				guc_log_context(p, child);
5090 		}
5091 	}
5092 	xa_unlock_irqrestore(&guc->context_lookup, flags);
5093 }
5094 
5095 static inline u32 get_children_go_addr(struct intel_context *ce)
5096 {
5097 	GEM_BUG_ON(!intel_context_is_parent(ce));
5098 
5099 	return i915_ggtt_offset(ce->state) +
5100 		__get_parent_scratch_offset(ce) +
5101 		offsetof(struct parent_scratch, go.semaphore);
5102 }
5103 
5104 static inline u32 get_children_join_addr(struct intel_context *ce,
5105 					 u8 child_index)
5106 {
5107 	GEM_BUG_ON(!intel_context_is_parent(ce));
5108 
5109 	return i915_ggtt_offset(ce->state) +
5110 		__get_parent_scratch_offset(ce) +
5111 		offsetof(struct parent_scratch, join[child_index].semaphore);
5112 }
5113 
5114 #define PARENT_GO_BB			1
5115 #define PARENT_GO_FINI_BREADCRUMB	0
5116 #define CHILD_GO_BB			1
5117 #define CHILD_GO_FINI_BREADCRUMB	0
5118 static int emit_bb_start_parent_no_preempt_mid_batch(struct i915_request *rq,
5119 						     u64 offset, u32 len,
5120 						     const unsigned int flags)
5121 {
5122 	struct intel_context *ce = rq->context;
5123 	u32 *cs;
5124 	u8 i;
5125 
5126 	GEM_BUG_ON(!intel_context_is_parent(ce));
5127 
5128 	cs = intel_ring_begin(rq, 10 + 4 * ce->parallel.number_children);
5129 	if (IS_ERR(cs))
5130 		return PTR_ERR(cs);
5131 
5132 	/* Wait on children */
5133 	for (i = 0; i < ce->parallel.number_children; ++i) {
5134 		*cs++ = (MI_SEMAPHORE_WAIT |
5135 			 MI_SEMAPHORE_GLOBAL_GTT |
5136 			 MI_SEMAPHORE_POLL |
5137 			 MI_SEMAPHORE_SAD_EQ_SDD);
5138 		*cs++ = PARENT_GO_BB;
5139 		*cs++ = get_children_join_addr(ce, i);
5140 		*cs++ = 0;
5141 	}
5142 
5143 	/* Turn off preemption */
5144 	*cs++ = MI_ARB_ON_OFF | MI_ARB_DISABLE;
5145 	*cs++ = MI_NOOP;
5146 
5147 	/* Tell children go */
5148 	cs = gen8_emit_ggtt_write(cs,
5149 				  CHILD_GO_BB,
5150 				  get_children_go_addr(ce),
5151 				  0);
5152 
5153 	/* Jump to batch */
5154 	*cs++ = MI_BATCH_BUFFER_START_GEN8 |
5155 		(flags & I915_DISPATCH_SECURE ? 0 : BIT(8));
5156 	*cs++ = lower_32_bits(offset);
5157 	*cs++ = upper_32_bits(offset);
5158 	*cs++ = MI_NOOP;
5159 
5160 	intel_ring_advance(rq, cs);
5161 
5162 	return 0;
5163 }
5164 
5165 static int emit_bb_start_child_no_preempt_mid_batch(struct i915_request *rq,
5166 						    u64 offset, u32 len,
5167 						    const unsigned int flags)
5168 {
5169 	struct intel_context *ce = rq->context;
5170 	struct intel_context *parent = intel_context_to_parent(ce);
5171 	u32 *cs;
5172 
5173 	GEM_BUG_ON(!intel_context_is_child(ce));
5174 
5175 	cs = intel_ring_begin(rq, 12);
5176 	if (IS_ERR(cs))
5177 		return PTR_ERR(cs);
5178 
5179 	/* Signal parent */
5180 	cs = gen8_emit_ggtt_write(cs,
5181 				  PARENT_GO_BB,
5182 				  get_children_join_addr(parent,
5183 							 ce->parallel.child_index),
5184 				  0);
5185 
5186 	/* Wait on parent for go */
5187 	*cs++ = (MI_SEMAPHORE_WAIT |
5188 		 MI_SEMAPHORE_GLOBAL_GTT |
5189 		 MI_SEMAPHORE_POLL |
5190 		 MI_SEMAPHORE_SAD_EQ_SDD);
5191 	*cs++ = CHILD_GO_BB;
5192 	*cs++ = get_children_go_addr(parent);
5193 	*cs++ = 0;
5194 
5195 	/* Turn off preemption */
5196 	*cs++ = MI_ARB_ON_OFF | MI_ARB_DISABLE;
5197 
5198 	/* Jump to batch */
5199 	*cs++ = MI_BATCH_BUFFER_START_GEN8 |
5200 		(flags & I915_DISPATCH_SECURE ? 0 : BIT(8));
5201 	*cs++ = lower_32_bits(offset);
5202 	*cs++ = upper_32_bits(offset);
5203 
5204 	intel_ring_advance(rq, cs);
5205 
5206 	return 0;
5207 }
5208 
5209 static u32 *
5210 __emit_fini_breadcrumb_parent_no_preempt_mid_batch(struct i915_request *rq,
5211 						   u32 *cs)
5212 {
5213 	struct intel_context *ce = rq->context;
5214 	u8 i;
5215 
5216 	GEM_BUG_ON(!intel_context_is_parent(ce));
5217 
5218 	/* Wait on children */
5219 	for (i = 0; i < ce->parallel.number_children; ++i) {
5220 		*cs++ = (MI_SEMAPHORE_WAIT |
5221 			 MI_SEMAPHORE_GLOBAL_GTT |
5222 			 MI_SEMAPHORE_POLL |
5223 			 MI_SEMAPHORE_SAD_EQ_SDD);
5224 		*cs++ = PARENT_GO_FINI_BREADCRUMB;
5225 		*cs++ = get_children_join_addr(ce, i);
5226 		*cs++ = 0;
5227 	}
5228 
5229 	/* Turn on preemption */
5230 	*cs++ = MI_ARB_ON_OFF | MI_ARB_ENABLE;
5231 	*cs++ = MI_NOOP;
5232 
5233 	/* Tell children go */
5234 	cs = gen8_emit_ggtt_write(cs,
5235 				  CHILD_GO_FINI_BREADCRUMB,
5236 				  get_children_go_addr(ce),
5237 				  0);
5238 
5239 	return cs;
5240 }
5241 
5242 /*
5243  * If this true, a submission of multi-lrc requests had an error and the
5244  * requests need to be skipped. The front end (execuf IOCTL) should've called
5245  * i915_request_skip which squashes the BB but we still need to emit the fini
5246  * breadrcrumbs seqno write. At this point we don't know how many of the
5247  * requests in the multi-lrc submission were generated so we can't do the
5248  * handshake between the parent and children (e.g. if 4 requests should be
5249  * generated but 2nd hit an error only 1 would be seen by the GuC backend).
5250  * Simply skip the handshake, but still emit the breadcrumbd seqno, if an error
5251  * has occurred on any of the requests in submission / relationship.
5252  */
5253 static inline bool skip_handshake(struct i915_request *rq)
5254 {
5255 	return test_bit(I915_FENCE_FLAG_SKIP_PARALLEL, &rq->fence.flags);
5256 }
5257 
5258 #define NON_SKIP_LEN	6
5259 static u32 *
5260 emit_fini_breadcrumb_parent_no_preempt_mid_batch(struct i915_request *rq,
5261 						 u32 *cs)
5262 {
5263 	struct intel_context *ce = rq->context;
5264 	__maybe_unused u32 *before_fini_breadcrumb_user_interrupt_cs;
5265 	__maybe_unused u32 *start_fini_breadcrumb_cs = cs;
5266 
5267 	GEM_BUG_ON(!intel_context_is_parent(ce));
5268 
5269 	if (unlikely(skip_handshake(rq))) {
5270 		/*
5271 		 * NOP everything in __emit_fini_breadcrumb_parent_no_preempt_mid_batch,
5272 		 * the NON_SKIP_LEN comes from the length of the emits below.
5273 		 */
5274 		memset(cs, 0, sizeof(u32) *
5275 		       (ce->engine->emit_fini_breadcrumb_dw - NON_SKIP_LEN));
5276 		cs += ce->engine->emit_fini_breadcrumb_dw - NON_SKIP_LEN;
5277 	} else {
5278 		cs = __emit_fini_breadcrumb_parent_no_preempt_mid_batch(rq, cs);
5279 	}
5280 
5281 	/* Emit fini breadcrumb */
5282 	before_fini_breadcrumb_user_interrupt_cs = cs;
5283 	cs = gen8_emit_ggtt_write(cs,
5284 				  rq->fence.seqno,
5285 				  i915_request_active_timeline(rq)->hwsp_offset,
5286 				  0);
5287 
5288 	/* User interrupt */
5289 	*cs++ = MI_USER_INTERRUPT;
5290 	*cs++ = MI_NOOP;
5291 
5292 	/* Ensure our math for skip + emit is correct */
5293 	GEM_BUG_ON(before_fini_breadcrumb_user_interrupt_cs + NON_SKIP_LEN !=
5294 		   cs);
5295 	GEM_BUG_ON(start_fini_breadcrumb_cs +
5296 		   ce->engine->emit_fini_breadcrumb_dw != cs);
5297 
5298 	rq->tail = intel_ring_offset(rq, cs);
5299 
5300 	return cs;
5301 }
5302 
5303 static u32 *
5304 __emit_fini_breadcrumb_child_no_preempt_mid_batch(struct i915_request *rq,
5305 						  u32 *cs)
5306 {
5307 	struct intel_context *ce = rq->context;
5308 	struct intel_context *parent = intel_context_to_parent(ce);
5309 
5310 	GEM_BUG_ON(!intel_context_is_child(ce));
5311 
5312 	/* Turn on preemption */
5313 	*cs++ = MI_ARB_ON_OFF | MI_ARB_ENABLE;
5314 	*cs++ = MI_NOOP;
5315 
5316 	/* Signal parent */
5317 	cs = gen8_emit_ggtt_write(cs,
5318 				  PARENT_GO_FINI_BREADCRUMB,
5319 				  get_children_join_addr(parent,
5320 							 ce->parallel.child_index),
5321 				  0);
5322 
5323 	/* Wait parent on for go */
5324 	*cs++ = (MI_SEMAPHORE_WAIT |
5325 		 MI_SEMAPHORE_GLOBAL_GTT |
5326 		 MI_SEMAPHORE_POLL |
5327 		 MI_SEMAPHORE_SAD_EQ_SDD);
5328 	*cs++ = CHILD_GO_FINI_BREADCRUMB;
5329 	*cs++ = get_children_go_addr(parent);
5330 	*cs++ = 0;
5331 
5332 	return cs;
5333 }
5334 
5335 static u32 *
5336 emit_fini_breadcrumb_child_no_preempt_mid_batch(struct i915_request *rq,
5337 						u32 *cs)
5338 {
5339 	struct intel_context *ce = rq->context;
5340 	__maybe_unused u32 *before_fini_breadcrumb_user_interrupt_cs;
5341 	__maybe_unused u32 *start_fini_breadcrumb_cs = cs;
5342 
5343 	GEM_BUG_ON(!intel_context_is_child(ce));
5344 
5345 	if (unlikely(skip_handshake(rq))) {
5346 		/*
5347 		 * NOP everything in __emit_fini_breadcrumb_child_no_preempt_mid_batch,
5348 		 * the NON_SKIP_LEN comes from the length of the emits below.
5349 		 */
5350 		memset(cs, 0, sizeof(u32) *
5351 		       (ce->engine->emit_fini_breadcrumb_dw - NON_SKIP_LEN));
5352 		cs += ce->engine->emit_fini_breadcrumb_dw - NON_SKIP_LEN;
5353 	} else {
5354 		cs = __emit_fini_breadcrumb_child_no_preempt_mid_batch(rq, cs);
5355 	}
5356 
5357 	/* Emit fini breadcrumb */
5358 	before_fini_breadcrumb_user_interrupt_cs = cs;
5359 	cs = gen8_emit_ggtt_write(cs,
5360 				  rq->fence.seqno,
5361 				  i915_request_active_timeline(rq)->hwsp_offset,
5362 				  0);
5363 
5364 	/* User interrupt */
5365 	*cs++ = MI_USER_INTERRUPT;
5366 	*cs++ = MI_NOOP;
5367 
5368 	/* Ensure our math for skip + emit is correct */
5369 	GEM_BUG_ON(before_fini_breadcrumb_user_interrupt_cs + NON_SKIP_LEN !=
5370 		   cs);
5371 	GEM_BUG_ON(start_fini_breadcrumb_cs +
5372 		   ce->engine->emit_fini_breadcrumb_dw != cs);
5373 
5374 	rq->tail = intel_ring_offset(rq, cs);
5375 
5376 	return cs;
5377 }
5378 
5379 #undef NON_SKIP_LEN
5380 
5381 static struct intel_context *
5382 guc_create_virtual(struct intel_engine_cs **siblings, unsigned int count,
5383 		   unsigned long flags)
5384 {
5385 	struct guc_virtual_engine *ve;
5386 	struct intel_guc *guc;
5387 	unsigned int n;
5388 	int err;
5389 
5390 	ve = kzalloc(sizeof(*ve), GFP_KERNEL);
5391 	if (!ve)
5392 		return ERR_PTR(-ENOMEM);
5393 
5394 	guc = &siblings[0]->gt->uc.guc;
5395 
5396 	ve->base.i915 = siblings[0]->i915;
5397 	ve->base.gt = siblings[0]->gt;
5398 	ve->base.uncore = siblings[0]->uncore;
5399 	ve->base.id = -1;
5400 
5401 	ve->base.uabi_class = I915_ENGINE_CLASS_INVALID;
5402 	ve->base.instance = I915_ENGINE_CLASS_INVALID_VIRTUAL;
5403 	ve->base.uabi_instance = I915_ENGINE_CLASS_INVALID_VIRTUAL;
5404 	ve->base.saturated = ALL_ENGINES;
5405 
5406 	snprintf(ve->base.name, sizeof(ve->base.name), "virtual");
5407 
5408 	ve->base.sched_engine = i915_sched_engine_get(guc->sched_engine);
5409 
5410 	ve->base.cops = &virtual_guc_context_ops;
5411 	ve->base.request_alloc = guc_request_alloc;
5412 	ve->base.bump_serial = virtual_guc_bump_serial;
5413 
5414 	ve->base.submit_request = guc_submit_request;
5415 
5416 	ve->base.flags = I915_ENGINE_IS_VIRTUAL;
5417 
5418 	intel_context_init(&ve->context, &ve->base);
5419 
5420 	for (n = 0; n < count; n++) {
5421 		struct intel_engine_cs *sibling = siblings[n];
5422 
5423 		GEM_BUG_ON(!is_power_of_2(sibling->mask));
5424 		if (sibling->mask & ve->base.mask) {
5425 			guc_dbg(guc, "duplicate %s entry in load balancer\n",
5426 				sibling->name);
5427 			err = -EINVAL;
5428 			goto err_put;
5429 		}
5430 
5431 		ve->base.mask |= sibling->mask;
5432 		ve->base.logical_mask |= sibling->logical_mask;
5433 
5434 		if (n != 0 && ve->base.class != sibling->class) {
5435 			guc_dbg(guc, "invalid mixing of engine class, sibling %d, already %d\n",
5436 				sibling->class, ve->base.class);
5437 			err = -EINVAL;
5438 			goto err_put;
5439 		} else if (n == 0) {
5440 			ve->base.class = sibling->class;
5441 			ve->base.uabi_class = sibling->uabi_class;
5442 			snprintf(ve->base.name, sizeof(ve->base.name),
5443 				 "v%dx%d", ve->base.class, count);
5444 			ve->base.context_size = sibling->context_size;
5445 
5446 			ve->base.add_active_request =
5447 				sibling->add_active_request;
5448 			ve->base.remove_active_request =
5449 				sibling->remove_active_request;
5450 			ve->base.emit_bb_start = sibling->emit_bb_start;
5451 			ve->base.emit_flush = sibling->emit_flush;
5452 			ve->base.emit_init_breadcrumb =
5453 				sibling->emit_init_breadcrumb;
5454 			ve->base.emit_fini_breadcrumb =
5455 				sibling->emit_fini_breadcrumb;
5456 			ve->base.emit_fini_breadcrumb_dw =
5457 				sibling->emit_fini_breadcrumb_dw;
5458 			ve->base.breadcrumbs =
5459 				intel_breadcrumbs_get(sibling->breadcrumbs);
5460 
5461 			ve->base.flags |= sibling->flags;
5462 
5463 			ve->base.props.timeslice_duration_ms =
5464 				sibling->props.timeslice_duration_ms;
5465 			ve->base.props.preempt_timeout_ms =
5466 				sibling->props.preempt_timeout_ms;
5467 		}
5468 	}
5469 
5470 	return &ve->context;
5471 
5472 err_put:
5473 	intel_context_put(&ve->context);
5474 	return ERR_PTR(err);
5475 }
5476 
5477 bool intel_guc_virtual_engine_has_heartbeat(const struct intel_engine_cs *ve)
5478 {
5479 	struct intel_engine_cs *engine;
5480 	intel_engine_mask_t tmp, mask = ve->mask;
5481 
5482 	for_each_engine_masked(engine, ve->gt, mask, tmp)
5483 		if (READ_ONCE(engine->props.heartbeat_interval_ms))
5484 			return true;
5485 
5486 	return false;
5487 }
5488 
5489 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
5490 #include "selftest_guc.c"
5491 #include "selftest_guc_multi_lrc.c"
5492 #include "selftest_guc_hangcheck.c"
5493 #endif
5494