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