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