xref: /linux/drivers/gpu/drm/i915/gt/intel_execlists_submission.c (revision 2c1ed907520c50326b8f604907a8478b27881a2e)
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright © 2014 Intel Corporation
4  */
5 
6 /**
7  * DOC: Logical Rings, Logical Ring Contexts and Execlists
8  *
9  * Motivation:
10  * GEN8 brings an expansion of the HW contexts: "Logical Ring Contexts".
11  * These expanded contexts enable a number of new abilities, especially
12  * "Execlists" (also implemented in this file).
13  *
14  * One of the main differences with the legacy HW contexts is that logical
15  * ring contexts incorporate many more things to the context's state, like
16  * PDPs or ringbuffer control registers:
17  *
18  * The reason why PDPs are included in the context is straightforward: as
19  * PPGTTs (per-process GTTs) are actually per-context, having the PDPs
20  * contained there mean you don't need to do a ppgtt->switch_mm yourself,
21  * instead, the GPU will do it for you on the context switch.
22  *
23  * But, what about the ringbuffer control registers (head, tail, etc..)?
24  * shouldn't we just need a set of those per engine command streamer? This is
25  * where the name "Logical Rings" starts to make sense: by virtualizing the
26  * rings, the engine cs shifts to a new "ring buffer" with every context
27  * switch. When you want to submit a workload to the GPU you: A) choose your
28  * context, B) find its appropriate virtualized ring, C) write commands to it
29  * and then, finally, D) tell the GPU to switch to that context.
30  *
31  * Instead of the legacy MI_SET_CONTEXT, the way you tell the GPU to switch
32  * to a contexts is via a context execution list, ergo "Execlists".
33  *
34  * LRC implementation:
35  * Regarding the creation of contexts, we have:
36  *
37  * - One global default context.
38  * - One local default context for each opened fd.
39  * - One local extra context for each context create ioctl call.
40  *
41  * Now that ringbuffers belong per-context (and not per-engine, like before)
42  * and that contexts are uniquely tied to a given engine (and not reusable,
43  * like before) we need:
44  *
45  * - One ringbuffer per-engine inside each context.
46  * - One backing object per-engine inside each context.
47  *
48  * The global default context starts its life with these new objects fully
49  * allocated and populated. The local default context for each opened fd is
50  * more complex, because we don't know at creation time which engine is going
51  * to use them. To handle this, we have implemented a deferred creation of LR
52  * contexts:
53  *
54  * The local context starts its life as a hollow or blank holder, that only
55  * gets populated for a given engine once we receive an execbuffer. If later
56  * on we receive another execbuffer ioctl for the same context but a different
57  * engine, we allocate/populate a new ringbuffer and context backing object and
58  * so on.
59  *
60  * Finally, regarding local contexts created using the ioctl call: as they are
61  * only allowed with the render ring, we can allocate & populate them right
62  * away (no need to defer anything, at least for now).
63  *
64  * Execlists implementation:
65  * Execlists are the new method by which, on gen8+ hardware, workloads are
66  * submitted for execution (as opposed to the legacy, ringbuffer-based, method).
67  * This method works as follows:
68  *
69  * When a request is committed, its commands (the BB start and any leading or
70  * trailing commands, like the seqno breadcrumbs) are placed in the ringbuffer
71  * for the appropriate context. The tail pointer in the hardware context is not
72  * updated at this time, but instead, kept by the driver in the ringbuffer
73  * structure. A structure representing this request is added to a request queue
74  * for the appropriate engine: this structure contains a copy of the context's
75  * tail after the request was written to the ring buffer and a pointer to the
76  * context itself.
77  *
78  * If the engine's request queue was empty before the request was added, the
79  * queue is processed immediately. Otherwise the queue will be processed during
80  * a context switch interrupt. In any case, elements on the queue will get sent
81  * (in pairs) to the GPU's ExecLists Submit Port (ELSP, for short) with a
82  * globally unique 20-bits submission ID.
83  *
84  * When execution of a request completes, the GPU updates the context status
85  * buffer with a context complete event and generates a context switch interrupt.
86  * During the interrupt handling, the driver examines the events in the buffer:
87  * for each context complete event, if the announced ID matches that on the head
88  * of the request queue, then that request is retired and removed from the queue.
89  *
90  * After processing, if any requests were retired and the queue is not empty
91  * then a new execution list can be submitted. The two requests at the front of
92  * the queue are next to be submitted but since a context may not occur twice in
93  * an execution list, if subsequent requests have the same ID as the first then
94  * the two requests must be combined. This is done simply by discarding requests
95  * at the head of the queue until either only one requests is left (in which case
96  * we use a NULL second context) or the first two requests have unique IDs.
97  *
98  * By always executing the first two requests in the queue the driver ensures
99  * that the GPU is kept as busy as possible. In the case where a single context
100  * completes but a second context is still executing, the request for this second
101  * context will be at the head of the queue when we remove the first one. This
102  * request will then be resubmitted along with a new request for a different context,
103  * which will cause the hardware to continue executing the second request and queue
104  * the new request (the GPU detects the condition of a context getting preempted
105  * with the same context and optimizes the context switch flow by not doing
106  * preemption, but just sampling the new tail pointer).
107  *
108  */
109 #include <linux/interrupt.h>
110 #include <linux/string_helpers.h>
111 
112 #include "i915_drv.h"
113 #include "i915_reg.h"
114 #include "i915_trace.h"
115 #include "i915_vgpu.h"
116 #include "gen8_engine_cs.h"
117 #include "intel_breadcrumbs.h"
118 #include "intel_context.h"
119 #include "intel_engine_heartbeat.h"
120 #include "intel_engine_pm.h"
121 #include "intel_engine_regs.h"
122 #include "intel_engine_stats.h"
123 #include "intel_execlists_submission.h"
124 #include "intel_gt.h"
125 #include "intel_gt_irq.h"
126 #include "intel_gt_pm.h"
127 #include "intel_gt_regs.h"
128 #include "intel_gt_requests.h"
129 #include "intel_lrc.h"
130 #include "intel_lrc_reg.h"
131 #include "intel_mocs.h"
132 #include "intel_reset.h"
133 #include "intel_ring.h"
134 #include "intel_workarounds.h"
135 #include "shmem_utils.h"
136 
137 #define RING_EXECLIST_QFULL		(1 << 0x2)
138 #define RING_EXECLIST1_VALID		(1 << 0x3)
139 #define RING_EXECLIST0_VALID		(1 << 0x4)
140 #define RING_EXECLIST_ACTIVE_STATUS	(3 << 0xE)
141 #define RING_EXECLIST1_ACTIVE		(1 << 0x11)
142 #define RING_EXECLIST0_ACTIVE		(1 << 0x12)
143 
144 #define GEN8_CTX_STATUS_IDLE_ACTIVE	(1 << 0)
145 #define GEN8_CTX_STATUS_PREEMPTED	(1 << 1)
146 #define GEN8_CTX_STATUS_ELEMENT_SWITCH	(1 << 2)
147 #define GEN8_CTX_STATUS_ACTIVE_IDLE	(1 << 3)
148 #define GEN8_CTX_STATUS_COMPLETE	(1 << 4)
149 #define GEN8_CTX_STATUS_LITE_RESTORE	(1 << 15)
150 
151 #define GEN8_CTX_STATUS_COMPLETED_MASK \
152 	 (GEN8_CTX_STATUS_COMPLETE | GEN8_CTX_STATUS_PREEMPTED)
153 
154 #define GEN12_CTX_STATUS_SWITCHED_TO_NEW_QUEUE	(0x1) /* lower csb dword */
155 #define GEN12_CTX_SWITCH_DETAIL(csb_dw)	((csb_dw) & 0xF) /* upper csb dword */
156 #define GEN12_CSB_SW_CTX_ID_MASK		GENMASK(25, 15)
157 #define GEN12_IDLE_CTX_ID		0x7FF
158 #define GEN12_CSB_CTX_VALID(csb_dw) \
159 	(FIELD_GET(GEN12_CSB_SW_CTX_ID_MASK, csb_dw) != GEN12_IDLE_CTX_ID)
160 
161 #define XEHP_CTX_STATUS_SWITCHED_TO_NEW_QUEUE	BIT(1) /* upper csb dword */
162 #define XEHP_CSB_SW_CTX_ID_MASK			GENMASK(31, 10)
163 #define XEHP_IDLE_CTX_ID			0xFFFF
164 #define XEHP_CSB_CTX_VALID(csb_dw) \
165 	(FIELD_GET(XEHP_CSB_SW_CTX_ID_MASK, csb_dw) != XEHP_IDLE_CTX_ID)
166 
167 /* Typical size of the average request (2 pipecontrols and a MI_BB) */
168 #define EXECLISTS_REQUEST_SIZE 64 /* bytes */
169 
170 struct virtual_engine {
171 	struct intel_engine_cs base;
172 	struct intel_context context;
173 	struct rcu_work rcu;
174 
175 	/*
176 	 * We allow only a single request through the virtual engine at a time
177 	 * (each request in the timeline waits for the completion fence of
178 	 * the previous before being submitted). By restricting ourselves to
179 	 * only submitting a single request, each request is placed on to a
180 	 * physical to maximise load spreading (by virtue of the late greedy
181 	 * scheduling -- each real engine takes the next available request
182 	 * upon idling).
183 	 */
184 	struct i915_request *request;
185 
186 	/*
187 	 * We keep a rbtree of available virtual engines inside each physical
188 	 * engine, sorted by priority. Here we preallocate the nodes we need
189 	 * for the virtual engine, indexed by physical_engine->id.
190 	 */
191 	struct ve_node {
192 		struct rb_node rb;
193 		int prio;
194 	} nodes[I915_NUM_ENGINES];
195 
196 	/* And finally, which physical engines this virtual engine maps onto. */
197 	unsigned int num_siblings;
198 	struct intel_engine_cs *siblings[];
199 };
200 
to_virtual_engine(struct intel_engine_cs * engine)201 static struct virtual_engine *to_virtual_engine(struct intel_engine_cs *engine)
202 {
203 	GEM_BUG_ON(!intel_engine_is_virtual(engine));
204 	return container_of(engine, struct virtual_engine, base);
205 }
206 
207 static struct intel_context *
208 execlists_create_virtual(struct intel_engine_cs **siblings, unsigned int count,
209 			 unsigned long flags);
210 
211 static struct i915_request *
__active_request(const struct intel_timeline * const tl,struct i915_request * rq,int error)212 __active_request(const struct intel_timeline * const tl,
213 		 struct i915_request *rq,
214 		 int error)
215 {
216 	struct i915_request *active = rq;
217 
218 	list_for_each_entry_from_reverse(rq, &tl->requests, link) {
219 		if (__i915_request_is_complete(rq))
220 			break;
221 
222 		if (error) {
223 			i915_request_set_error_once(rq, error);
224 			__i915_request_skip(rq);
225 		}
226 		active = rq;
227 	}
228 
229 	return active;
230 }
231 
232 static struct i915_request *
active_request(const struct intel_timeline * const tl,struct i915_request * rq)233 active_request(const struct intel_timeline * const tl, struct i915_request *rq)
234 {
235 	return __active_request(tl, rq, 0);
236 }
237 
ring_set_paused(const struct intel_engine_cs * engine,int state)238 static void ring_set_paused(const struct intel_engine_cs *engine, int state)
239 {
240 	/*
241 	 * We inspect HWS_PREEMPT with a semaphore inside
242 	 * engine->emit_fini_breadcrumb. If the dword is true,
243 	 * the ring is paused as the semaphore will busywait
244 	 * until the dword is false.
245 	 */
246 	engine->status_page.addr[I915_GEM_HWS_PREEMPT] = state;
247 	if (state)
248 		wmb();
249 }
250 
to_priolist(struct rb_node * rb)251 static struct i915_priolist *to_priolist(struct rb_node *rb)
252 {
253 	return rb_entry(rb, struct i915_priolist, node);
254 }
255 
rq_prio(const struct i915_request * rq)256 static int rq_prio(const struct i915_request *rq)
257 {
258 	return READ_ONCE(rq->sched.attr.priority);
259 }
260 
effective_prio(const struct i915_request * rq)261 static int effective_prio(const struct i915_request *rq)
262 {
263 	int prio = rq_prio(rq);
264 
265 	/*
266 	 * If this request is special and must not be interrupted at any
267 	 * cost, so be it. Note we are only checking the most recent request
268 	 * in the context and so may be masking an earlier vip request. It
269 	 * is hoped that under the conditions where nopreempt is used, this
270 	 * will not matter (i.e. all requests to that context will be
271 	 * nopreempt for as long as desired).
272 	 */
273 	if (i915_request_has_nopreempt(rq))
274 		prio = I915_PRIORITY_UNPREEMPTABLE;
275 
276 	return prio;
277 }
278 
queue_prio(const struct i915_sched_engine * sched_engine)279 static int queue_prio(const struct i915_sched_engine *sched_engine)
280 {
281 	struct rb_node *rb;
282 
283 	rb = rb_first_cached(&sched_engine->queue);
284 	if (!rb)
285 		return INT_MIN;
286 
287 	return to_priolist(rb)->priority;
288 }
289 
virtual_prio(const struct intel_engine_execlists * el)290 static int virtual_prio(const struct intel_engine_execlists *el)
291 {
292 	struct rb_node *rb = rb_first_cached(&el->virtual);
293 
294 	return rb ? rb_entry(rb, struct ve_node, rb)->prio : INT_MIN;
295 }
296 
need_preempt(const struct intel_engine_cs * engine,const struct i915_request * rq)297 static bool need_preempt(const struct intel_engine_cs *engine,
298 			 const struct i915_request *rq)
299 {
300 	int last_prio;
301 
302 	if (!intel_engine_has_semaphores(engine))
303 		return false;
304 
305 	/*
306 	 * Check if the current priority hint merits a preemption attempt.
307 	 *
308 	 * We record the highest value priority we saw during rescheduling
309 	 * prior to this dequeue, therefore we know that if it is strictly
310 	 * less than the current tail of ESLP[0], we do not need to force
311 	 * a preempt-to-idle cycle.
312 	 *
313 	 * However, the priority hint is a mere hint that we may need to
314 	 * preempt. If that hint is stale or we may be trying to preempt
315 	 * ourselves, ignore the request.
316 	 *
317 	 * More naturally we would write
318 	 *      prio >= max(0, last);
319 	 * except that we wish to prevent triggering preemption at the same
320 	 * priority level: the task that is running should remain running
321 	 * to preserve FIFO ordering of dependencies.
322 	 */
323 	last_prio = max(effective_prio(rq), I915_PRIORITY_NORMAL - 1);
324 	if (engine->sched_engine->queue_priority_hint <= last_prio)
325 		return false;
326 
327 	/*
328 	 * Check against the first request in ELSP[1], it will, thanks to the
329 	 * power of PI, be the highest priority of that context.
330 	 */
331 	if (!list_is_last(&rq->sched.link, &engine->sched_engine->requests) &&
332 	    rq_prio(list_next_entry(rq, sched.link)) > last_prio)
333 		return true;
334 
335 	/*
336 	 * If the inflight context did not trigger the preemption, then maybe
337 	 * it was the set of queued requests? Pick the highest priority in
338 	 * the queue (the first active priolist) and see if it deserves to be
339 	 * running instead of ELSP[0].
340 	 *
341 	 * The highest priority request in the queue can not be either
342 	 * ELSP[0] or ELSP[1] as, thanks again to PI, if it was the same
343 	 * context, it's priority would not exceed ELSP[0] aka last_prio.
344 	 */
345 	return max(virtual_prio(&engine->execlists),
346 		   queue_prio(engine->sched_engine)) > last_prio;
347 }
348 
349 __maybe_unused static bool
assert_priority_queue(const struct i915_request * prev,const struct i915_request * next)350 assert_priority_queue(const struct i915_request *prev,
351 		      const struct i915_request *next)
352 {
353 	/*
354 	 * Without preemption, the prev may refer to the still active element
355 	 * which we refuse to let go.
356 	 *
357 	 * Even with preemption, there are times when we think it is better not
358 	 * to preempt and leave an ostensibly lower priority request in flight.
359 	 */
360 	if (i915_request_is_active(prev))
361 		return true;
362 
363 	return rq_prio(prev) >= rq_prio(next);
364 }
365 
366 static struct i915_request *
__unwind_incomplete_requests(struct intel_engine_cs * engine)367 __unwind_incomplete_requests(struct intel_engine_cs *engine)
368 {
369 	struct i915_request *rq, *rn, *active = NULL;
370 	struct list_head *pl;
371 	int prio = I915_PRIORITY_INVALID;
372 
373 	lockdep_assert_held(&engine->sched_engine->lock);
374 
375 	list_for_each_entry_safe_reverse(rq, rn,
376 					 &engine->sched_engine->requests,
377 					 sched.link) {
378 		if (__i915_request_is_complete(rq)) {
379 			list_del_init(&rq->sched.link);
380 			continue;
381 		}
382 
383 		__i915_request_unsubmit(rq);
384 
385 		GEM_BUG_ON(rq_prio(rq) == I915_PRIORITY_INVALID);
386 		if (rq_prio(rq) != prio) {
387 			prio = rq_prio(rq);
388 			pl = i915_sched_lookup_priolist(engine->sched_engine,
389 							prio);
390 		}
391 		GEM_BUG_ON(i915_sched_engine_is_empty(engine->sched_engine));
392 
393 		list_move(&rq->sched.link, pl);
394 		set_bit(I915_FENCE_FLAG_PQUEUE, &rq->fence.flags);
395 
396 		/* Check in case we rollback so far we wrap [size/2] */
397 		if (intel_ring_direction(rq->ring,
398 					 rq->tail,
399 					 rq->ring->tail + 8) > 0)
400 			rq->context->lrc.desc |= CTX_DESC_FORCE_RESTORE;
401 
402 		active = rq;
403 	}
404 
405 	return active;
406 }
407 
408 static void
execlists_context_status_change(struct i915_request * rq,unsigned long status)409 execlists_context_status_change(struct i915_request *rq, unsigned long status)
410 {
411 	/*
412 	 * Only used when GVT-g is enabled now. When GVT-g is disabled,
413 	 * The compiler should eliminate this function as dead-code.
414 	 */
415 	if (!IS_ENABLED(CONFIG_DRM_I915_GVT))
416 		return;
417 
418 	atomic_notifier_call_chain(&rq->engine->context_status_notifier,
419 				   status, rq);
420 }
421 
reset_active(struct i915_request * rq,struct intel_engine_cs * engine)422 static void reset_active(struct i915_request *rq,
423 			 struct intel_engine_cs *engine)
424 {
425 	struct intel_context * const ce = rq->context;
426 	u32 head;
427 
428 	/*
429 	 * The executing context has been cancelled. We want to prevent
430 	 * further execution along this context and propagate the error on
431 	 * to anything depending on its results.
432 	 *
433 	 * In __i915_request_submit(), we apply the -EIO and remove the
434 	 * requests' payloads for any banned requests. But first, we must
435 	 * rewind the context back to the start of the incomplete request so
436 	 * that we do not jump back into the middle of the batch.
437 	 *
438 	 * We preserve the breadcrumbs and semaphores of the incomplete
439 	 * requests so that inter-timeline dependencies (i.e other timelines)
440 	 * remain correctly ordered. And we defer to __i915_request_submit()
441 	 * so that all asynchronous waits are correctly handled.
442 	 */
443 	ENGINE_TRACE(engine, "{ reset rq=%llx:%lld }\n",
444 		     rq->fence.context, rq->fence.seqno);
445 
446 	/* On resubmission of the active request, payload will be scrubbed */
447 	if (__i915_request_is_complete(rq))
448 		head = rq->tail;
449 	else
450 		head = __active_request(ce->timeline, rq, -EIO)->head;
451 	head = intel_ring_wrap(ce->ring, head);
452 
453 	/* Scrub the context image to prevent replaying the previous batch */
454 	lrc_init_regs(ce, engine, true);
455 
456 	/* We've switched away, so this should be a no-op, but intent matters */
457 	ce->lrc.lrca = lrc_update_regs(ce, engine, head);
458 }
459 
bad_request(const struct i915_request * rq)460 static bool bad_request(const struct i915_request *rq)
461 {
462 	return rq->fence.error && i915_request_started(rq);
463 }
464 
465 static struct intel_engine_cs *
__execlists_schedule_in(struct i915_request * rq)466 __execlists_schedule_in(struct i915_request *rq)
467 {
468 	struct intel_engine_cs * const engine = rq->engine;
469 	struct intel_context * const ce = rq->context;
470 
471 	intel_context_get(ce);
472 
473 	if (unlikely(intel_context_is_closed(ce) &&
474 		     !intel_engine_has_heartbeat(engine)))
475 		intel_context_set_exiting(ce);
476 
477 	if (unlikely(!intel_context_is_schedulable(ce) || bad_request(rq)))
478 		reset_active(rq, engine);
479 
480 	if (IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM))
481 		lrc_check_regs(ce, engine, "before");
482 
483 	if (ce->tag) {
484 		/* Use a fixed tag for OA and friends */
485 		GEM_BUG_ON(ce->tag <= BITS_PER_LONG);
486 		ce->lrc.ccid = ce->tag;
487 	} else if (GRAPHICS_VER_FULL(engine->i915) >= IP_VER(12, 55)) {
488 		/* We don't need a strict matching tag, just different values */
489 		unsigned int tag = ffs(READ_ONCE(engine->context_tag));
490 
491 		GEM_BUG_ON(tag == 0 || tag >= BITS_PER_LONG);
492 		clear_bit(tag - 1, &engine->context_tag);
493 		ce->lrc.ccid = tag << (XEHP_SW_CTX_ID_SHIFT - 32);
494 
495 		BUILD_BUG_ON(BITS_PER_LONG > GEN12_MAX_CONTEXT_HW_ID);
496 
497 	} else {
498 		/* We don't need a strict matching tag, just different values */
499 		unsigned int tag = __ffs(engine->context_tag);
500 
501 		GEM_BUG_ON(tag >= BITS_PER_LONG);
502 		__clear_bit(tag, &engine->context_tag);
503 		ce->lrc.ccid = (1 + tag) << (GEN11_SW_CTX_ID_SHIFT - 32);
504 
505 		BUILD_BUG_ON(BITS_PER_LONG > GEN12_MAX_CONTEXT_HW_ID);
506 	}
507 
508 	ce->lrc.ccid |= engine->execlists.ccid;
509 
510 	__intel_gt_pm_get(engine->gt);
511 	if (engine->fw_domain && !engine->fw_active++)
512 		intel_uncore_forcewake_get(engine->uncore, engine->fw_domain);
513 	execlists_context_status_change(rq, INTEL_CONTEXT_SCHEDULE_IN);
514 	intel_engine_context_in(engine);
515 
516 	CE_TRACE(ce, "schedule-in, ccid:%x\n", ce->lrc.ccid);
517 
518 	return engine;
519 }
520 
execlists_schedule_in(struct i915_request * rq,int idx)521 static void execlists_schedule_in(struct i915_request *rq, int idx)
522 {
523 	struct intel_context * const ce = rq->context;
524 	struct intel_engine_cs *old;
525 
526 	GEM_BUG_ON(!intel_engine_pm_is_awake(rq->engine));
527 	trace_i915_request_in(rq, idx);
528 
529 	old = ce->inflight;
530 	if (!old)
531 		old = __execlists_schedule_in(rq);
532 	WRITE_ONCE(ce->inflight, ptr_inc(old));
533 
534 	GEM_BUG_ON(intel_context_inflight(ce) != rq->engine);
535 }
536 
537 static void
resubmit_virtual_request(struct i915_request * rq,struct virtual_engine * ve)538 resubmit_virtual_request(struct i915_request *rq, struct virtual_engine *ve)
539 {
540 	struct intel_engine_cs *engine = rq->engine;
541 
542 	spin_lock_irq(&engine->sched_engine->lock);
543 
544 	clear_bit(I915_FENCE_FLAG_PQUEUE, &rq->fence.flags);
545 	WRITE_ONCE(rq->engine, &ve->base);
546 	ve->base.submit_request(rq);
547 
548 	spin_unlock_irq(&engine->sched_engine->lock);
549 }
550 
kick_siblings(struct i915_request * rq,struct intel_context * ce)551 static void kick_siblings(struct i915_request *rq, struct intel_context *ce)
552 {
553 	struct virtual_engine *ve = container_of(ce, typeof(*ve), context);
554 	struct intel_engine_cs *engine = rq->engine;
555 
556 	/*
557 	 * After this point, the rq may be transferred to a new sibling, so
558 	 * before we clear ce->inflight make sure that the context has been
559 	 * removed from the b->signalers and furthermore we need to make sure
560 	 * that the concurrent iterator in signal_irq_work is no longer
561 	 * following ce->signal_link.
562 	 */
563 	if (!list_empty(&ce->signals))
564 		intel_context_remove_breadcrumbs(ce, engine->breadcrumbs);
565 
566 	/*
567 	 * This engine is now too busy to run this virtual request, so
568 	 * see if we can find an alternative engine for it to execute on.
569 	 * Once a request has become bonded to this engine, we treat it the
570 	 * same as other native request.
571 	 */
572 	if (i915_request_in_priority_queue(rq) &&
573 	    rq->execution_mask != engine->mask)
574 		resubmit_virtual_request(rq, ve);
575 
576 	if (READ_ONCE(ve->request))
577 		tasklet_hi_schedule(&ve->base.sched_engine->tasklet);
578 }
579 
__execlists_schedule_out(struct i915_request * const rq,struct intel_context * const ce)580 static void __execlists_schedule_out(struct i915_request * const rq,
581 				     struct intel_context * const ce)
582 {
583 	struct intel_engine_cs * const engine = rq->engine;
584 	unsigned int ccid;
585 
586 	/*
587 	 * NB process_csb() is not under the engine->sched_engine->lock and hence
588 	 * schedule_out can race with schedule_in meaning that we should
589 	 * refrain from doing non-trivial work here.
590 	 */
591 
592 	CE_TRACE(ce, "schedule-out, ccid:%x\n", ce->lrc.ccid);
593 	GEM_BUG_ON(ce->inflight != engine);
594 
595 	if (IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM))
596 		lrc_check_regs(ce, engine, "after");
597 
598 	/*
599 	 * If we have just completed this context, the engine may now be
600 	 * idle and we want to re-enter powersaving.
601 	 */
602 	if (intel_timeline_is_last(ce->timeline, rq) &&
603 	    __i915_request_is_complete(rq))
604 		intel_engine_add_retire(engine, ce->timeline);
605 
606 	ccid = ce->lrc.ccid;
607 	if (GRAPHICS_VER_FULL(engine->i915) >= IP_VER(12, 55)) {
608 		ccid >>= XEHP_SW_CTX_ID_SHIFT - 32;
609 		ccid &= XEHP_MAX_CONTEXT_HW_ID;
610 	} else {
611 		ccid >>= GEN11_SW_CTX_ID_SHIFT - 32;
612 		ccid &= GEN12_MAX_CONTEXT_HW_ID;
613 	}
614 
615 	if (ccid < BITS_PER_LONG) {
616 		GEM_BUG_ON(ccid == 0);
617 		GEM_BUG_ON(test_bit(ccid - 1, &engine->context_tag));
618 		__set_bit(ccid - 1, &engine->context_tag);
619 	}
620 	intel_engine_context_out(engine);
621 	execlists_context_status_change(rq, INTEL_CONTEXT_SCHEDULE_OUT);
622 	if (engine->fw_domain && !--engine->fw_active)
623 		intel_uncore_forcewake_put(engine->uncore, engine->fw_domain);
624 	intel_gt_pm_put_async_untracked(engine->gt);
625 
626 	/*
627 	 * If this is part of a virtual engine, its next request may
628 	 * have been blocked waiting for access to the active context.
629 	 * We have to kick all the siblings again in case we need to
630 	 * switch (e.g. the next request is not runnable on this
631 	 * engine). Hopefully, we will already have submitted the next
632 	 * request before the tasklet runs and do not need to rebuild
633 	 * each virtual tree and kick everyone again.
634 	 */
635 	if (ce->engine != engine)
636 		kick_siblings(rq, ce);
637 
638 	WRITE_ONCE(ce->inflight, NULL);
639 	intel_context_put(ce);
640 }
641 
execlists_schedule_out(struct i915_request * rq)642 static inline void execlists_schedule_out(struct i915_request *rq)
643 {
644 	struct intel_context * const ce = rq->context;
645 
646 	trace_i915_request_out(rq);
647 
648 	GEM_BUG_ON(!ce->inflight);
649 	ce->inflight = ptr_dec(ce->inflight);
650 	if (!__intel_context_inflight_count(ce->inflight))
651 		__execlists_schedule_out(rq, ce);
652 
653 	i915_request_put(rq);
654 }
655 
map_i915_prio_to_lrc_desc_prio(int prio)656 static u32 map_i915_prio_to_lrc_desc_prio(int prio)
657 {
658 	if (prio > I915_PRIORITY_NORMAL)
659 		return GEN12_CTX_PRIORITY_HIGH;
660 	else if (prio < I915_PRIORITY_NORMAL)
661 		return GEN12_CTX_PRIORITY_LOW;
662 	else
663 		return GEN12_CTX_PRIORITY_NORMAL;
664 }
665 
execlists_update_context(struct i915_request * rq)666 static u64 execlists_update_context(struct i915_request *rq)
667 {
668 	struct intel_context *ce = rq->context;
669 	u64 desc;
670 	u32 tail, prev;
671 
672 	desc = ce->lrc.desc;
673 	if (rq->engine->flags & I915_ENGINE_HAS_EU_PRIORITY)
674 		desc |= map_i915_prio_to_lrc_desc_prio(rq_prio(rq));
675 
676 	/*
677 	 * WaIdleLiteRestore:bdw,skl
678 	 *
679 	 * We should never submit the context with the same RING_TAIL twice
680 	 * just in case we submit an empty ring, which confuses the HW.
681 	 *
682 	 * We append a couple of NOOPs (gen8_emit_wa_tail) after the end of
683 	 * the normal request to be able to always advance the RING_TAIL on
684 	 * subsequent resubmissions (for lite restore). Should that fail us,
685 	 * and we try and submit the same tail again, force the context
686 	 * reload.
687 	 *
688 	 * If we need to return to a preempted context, we need to skip the
689 	 * lite-restore and force it to reload the RING_TAIL. Otherwise, the
690 	 * HW has a tendency to ignore us rewinding the TAIL to the end of
691 	 * an earlier request.
692 	 */
693 	GEM_BUG_ON(ce->lrc_reg_state[CTX_RING_TAIL] != rq->ring->tail);
694 	prev = rq->ring->tail;
695 	tail = intel_ring_set_tail(rq->ring, rq->tail);
696 	if (unlikely(intel_ring_direction(rq->ring, tail, prev) <= 0))
697 		desc |= CTX_DESC_FORCE_RESTORE;
698 	ce->lrc_reg_state[CTX_RING_TAIL] = tail;
699 	rq->tail = rq->wa_tail;
700 
701 	/*
702 	 * Make sure the context image is complete before we submit it to HW.
703 	 *
704 	 * Ostensibly, writes (including the WCB) should be flushed prior to
705 	 * an uncached write such as our mmio register access, the empirical
706 	 * evidence (esp. on Braswell) suggests that the WC write into memory
707 	 * may not be visible to the HW prior to the completion of the UC
708 	 * register write and that we may begin execution from the context
709 	 * before its image is complete leading to invalid PD chasing.
710 	 */
711 	wmb();
712 
713 	ce->lrc.desc &= ~CTX_DESC_FORCE_RESTORE;
714 	return desc;
715 }
716 
write_desc(struct intel_engine_execlists * execlists,u64 desc,u32 port)717 static void write_desc(struct intel_engine_execlists *execlists, u64 desc, u32 port)
718 {
719 	if (execlists->ctrl_reg) {
720 		writel(lower_32_bits(desc), execlists->submit_reg + port * 2);
721 		writel(upper_32_bits(desc), execlists->submit_reg + port * 2 + 1);
722 	} else {
723 		writel(upper_32_bits(desc), execlists->submit_reg);
724 		writel(lower_32_bits(desc), execlists->submit_reg);
725 	}
726 }
727 
728 static __maybe_unused char *
dump_port(char * buf,int buflen,const char * prefix,struct i915_request * rq)729 dump_port(char *buf, int buflen, const char *prefix, struct i915_request *rq)
730 {
731 	if (!rq)
732 		return "";
733 
734 	snprintf(buf, buflen, "%sccid:%x %llx:%lld%s prio %d",
735 		 prefix,
736 		 rq->context->lrc.ccid,
737 		 rq->fence.context, rq->fence.seqno,
738 		 __i915_request_is_complete(rq) ? "!" :
739 		 __i915_request_has_started(rq) ? "*" :
740 		 "",
741 		 rq_prio(rq));
742 
743 	return buf;
744 }
745 
746 static __maybe_unused noinline void
trace_ports(const struct intel_engine_execlists * execlists,const char * msg,struct i915_request * const * ports)747 trace_ports(const struct intel_engine_execlists *execlists,
748 	    const char *msg,
749 	    struct i915_request * const *ports)
750 {
751 	const struct intel_engine_cs *engine =
752 		container_of(execlists, typeof(*engine), execlists);
753 	char __maybe_unused p0[40], p1[40];
754 
755 	if (!ports[0])
756 		return;
757 
758 	ENGINE_TRACE(engine, "%s { %s%s }\n", msg,
759 		     dump_port(p0, sizeof(p0), "", ports[0]),
760 		     dump_port(p1, sizeof(p1), ", ", ports[1]));
761 }
762 
763 static bool
reset_in_progress(const struct intel_engine_cs * engine)764 reset_in_progress(const struct intel_engine_cs *engine)
765 {
766 	return unlikely(!__tasklet_is_enabled(&engine->sched_engine->tasklet));
767 }
768 
769 static __maybe_unused noinline bool
assert_pending_valid(const struct intel_engine_execlists * execlists,const char * msg)770 assert_pending_valid(const struct intel_engine_execlists *execlists,
771 		     const char *msg)
772 {
773 	struct intel_engine_cs *engine =
774 		container_of(execlists, typeof(*engine), execlists);
775 	struct i915_request * const *port, *rq, *prev = NULL;
776 	struct intel_context *ce = NULL;
777 	u32 ccid = -1;
778 
779 	trace_ports(execlists, msg, execlists->pending);
780 
781 	/* We may be messing around with the lists during reset, lalala */
782 	if (reset_in_progress(engine))
783 		return true;
784 
785 	if (!execlists->pending[0]) {
786 		GEM_TRACE_ERR("%s: Nothing pending for promotion!\n",
787 			      engine->name);
788 		return false;
789 	}
790 
791 	if (execlists->pending[execlists_num_ports(execlists)]) {
792 		GEM_TRACE_ERR("%s: Excess pending[%d] for promotion!\n",
793 			      engine->name, execlists_num_ports(execlists));
794 		return false;
795 	}
796 
797 	for (port = execlists->pending; (rq = *port); port++) {
798 		unsigned long flags;
799 		bool ok = true;
800 
801 		GEM_BUG_ON(!kref_read(&rq->fence.refcount));
802 		GEM_BUG_ON(!i915_request_is_active(rq));
803 
804 		if (ce == rq->context) {
805 			GEM_TRACE_ERR("%s: Dup context:%llx in pending[%zd]\n",
806 				      engine->name,
807 				      ce->timeline->fence_context,
808 				      port - execlists->pending);
809 			return false;
810 		}
811 		ce = rq->context;
812 
813 		if (ccid == ce->lrc.ccid) {
814 			GEM_TRACE_ERR("%s: Dup ccid:%x context:%llx in pending[%zd]\n",
815 				      engine->name,
816 				      ccid, ce->timeline->fence_context,
817 				      port - execlists->pending);
818 			return false;
819 		}
820 		ccid = ce->lrc.ccid;
821 
822 		/*
823 		 * Sentinels are supposed to be the last request so they flush
824 		 * the current execution off the HW. Check that they are the only
825 		 * request in the pending submission.
826 		 *
827 		 * NB: Due to the async nature of preempt-to-busy and request
828 		 * cancellation we need to handle the case where request
829 		 * becomes a sentinel in parallel to CSB processing.
830 		 */
831 		if (prev && i915_request_has_sentinel(prev) &&
832 		    !READ_ONCE(prev->fence.error)) {
833 			GEM_TRACE_ERR("%s: context:%llx after sentinel in pending[%zd]\n",
834 				      engine->name,
835 				      ce->timeline->fence_context,
836 				      port - execlists->pending);
837 			return false;
838 		}
839 		prev = rq;
840 
841 		/*
842 		 * We want virtual requests to only be in the first slot so
843 		 * that they are never stuck behind a hog and can be immediately
844 		 * transferred onto the next idle engine.
845 		 */
846 		if (rq->execution_mask != engine->mask &&
847 		    port != execlists->pending) {
848 			GEM_TRACE_ERR("%s: virtual engine:%llx not in prime position[%zd]\n",
849 				      engine->name,
850 				      ce->timeline->fence_context,
851 				      port - execlists->pending);
852 			return false;
853 		}
854 
855 		/* Hold tightly onto the lock to prevent concurrent retires! */
856 		if (!spin_trylock_irqsave(&rq->lock, flags))
857 			continue;
858 
859 		if (__i915_request_is_complete(rq))
860 			goto unlock;
861 
862 		if (i915_active_is_idle(&ce->active) &&
863 		    !intel_context_is_barrier(ce)) {
864 			GEM_TRACE_ERR("%s: Inactive context:%llx in pending[%zd]\n",
865 				      engine->name,
866 				      ce->timeline->fence_context,
867 				      port - execlists->pending);
868 			ok = false;
869 			goto unlock;
870 		}
871 
872 		if (!i915_vma_is_pinned(ce->state)) {
873 			GEM_TRACE_ERR("%s: Unpinned context:%llx in pending[%zd]\n",
874 				      engine->name,
875 				      ce->timeline->fence_context,
876 				      port - execlists->pending);
877 			ok = false;
878 			goto unlock;
879 		}
880 
881 		if (!i915_vma_is_pinned(ce->ring->vma)) {
882 			GEM_TRACE_ERR("%s: Unpinned ring:%llx in pending[%zd]\n",
883 				      engine->name,
884 				      ce->timeline->fence_context,
885 				      port - execlists->pending);
886 			ok = false;
887 			goto unlock;
888 		}
889 
890 unlock:
891 		spin_unlock_irqrestore(&rq->lock, flags);
892 		if (!ok)
893 			return false;
894 	}
895 
896 	return ce;
897 }
898 
execlists_submit_ports(struct intel_engine_cs * engine)899 static void execlists_submit_ports(struct intel_engine_cs *engine)
900 {
901 	struct intel_engine_execlists *execlists = &engine->execlists;
902 	unsigned int n;
903 
904 	GEM_BUG_ON(!assert_pending_valid(execlists, "submit"));
905 
906 	/*
907 	 * We can skip acquiring intel_runtime_pm_get() here as it was taken
908 	 * on our behalf by the request (see i915_gem_mark_busy()) and it will
909 	 * not be relinquished until the device is idle (see
910 	 * i915_gem_idle_work_handler()). As a precaution, we make sure
911 	 * that all ELSP are drained i.e. we have processed the CSB,
912 	 * before allowing ourselves to idle and calling intel_runtime_pm_put().
913 	 */
914 	GEM_BUG_ON(!intel_engine_pm_is_awake(engine));
915 
916 	/*
917 	 * ELSQ note: the submit queue is not cleared after being submitted
918 	 * to the HW so we need to make sure we always clean it up. This is
919 	 * currently ensured by the fact that we always write the same number
920 	 * of elsq entries, keep this in mind before changing the loop below.
921 	 */
922 	for (n = execlists_num_ports(execlists); n--; ) {
923 		struct i915_request *rq = execlists->pending[n];
924 
925 		write_desc(execlists,
926 			   rq ? execlists_update_context(rq) : 0,
927 			   n);
928 	}
929 
930 	/* we need to manually load the submit queue */
931 	if (execlists->ctrl_reg)
932 		writel(EL_CTRL_LOAD, execlists->ctrl_reg);
933 }
934 
ctx_single_port_submission(const struct intel_context * ce)935 static bool ctx_single_port_submission(const struct intel_context *ce)
936 {
937 	return (IS_ENABLED(CONFIG_DRM_I915_GVT) &&
938 		intel_context_force_single_submission(ce));
939 }
940 
can_merge_ctx(const struct intel_context * prev,const struct intel_context * next)941 static bool can_merge_ctx(const struct intel_context *prev,
942 			  const struct intel_context *next)
943 {
944 	if (prev != next)
945 		return false;
946 
947 	if (ctx_single_port_submission(prev))
948 		return false;
949 
950 	return true;
951 }
952 
i915_request_flags(const struct i915_request * rq)953 static unsigned long i915_request_flags(const struct i915_request *rq)
954 {
955 	return READ_ONCE(rq->fence.flags);
956 }
957 
can_merge_rq(const struct i915_request * prev,const struct i915_request * next)958 static bool can_merge_rq(const struct i915_request *prev,
959 			 const struct i915_request *next)
960 {
961 	GEM_BUG_ON(prev == next);
962 	GEM_BUG_ON(!assert_priority_queue(prev, next));
963 
964 	/*
965 	 * We do not submit known completed requests. Therefore if the next
966 	 * request is already completed, we can pretend to merge it in
967 	 * with the previous context (and we will skip updating the ELSP
968 	 * and tracking). Thus hopefully keeping the ELSP full with active
969 	 * contexts, despite the best efforts of preempt-to-busy to confuse
970 	 * us.
971 	 */
972 	if (__i915_request_is_complete(next))
973 		return true;
974 
975 	if (unlikely((i915_request_flags(prev) | i915_request_flags(next)) &
976 		     (BIT(I915_FENCE_FLAG_NOPREEMPT) |
977 		      BIT(I915_FENCE_FLAG_SENTINEL))))
978 		return false;
979 
980 	if (!can_merge_ctx(prev->context, next->context))
981 		return false;
982 
983 	GEM_BUG_ON(i915_seqno_passed(prev->fence.seqno, next->fence.seqno));
984 	return true;
985 }
986 
virtual_matches(const struct virtual_engine * ve,const struct i915_request * rq,const struct intel_engine_cs * engine)987 static bool virtual_matches(const struct virtual_engine *ve,
988 			    const struct i915_request *rq,
989 			    const struct intel_engine_cs *engine)
990 {
991 	const struct intel_engine_cs *inflight;
992 
993 	if (!rq)
994 		return false;
995 
996 	if (!(rq->execution_mask & engine->mask)) /* We peeked too soon! */
997 		return false;
998 
999 	/*
1000 	 * We track when the HW has completed saving the context image
1001 	 * (i.e. when we have seen the final CS event switching out of
1002 	 * the context) and must not overwrite the context image before
1003 	 * then. This restricts us to only using the active engine
1004 	 * while the previous virtualized request is inflight (so
1005 	 * we reuse the register offsets). This is a very small
1006 	 * hystersis on the greedy seelction algorithm.
1007 	 */
1008 	inflight = intel_context_inflight(&ve->context);
1009 	if (inflight && inflight != engine)
1010 		return false;
1011 
1012 	return true;
1013 }
1014 
1015 static struct virtual_engine *
first_virtual_engine(struct intel_engine_cs * engine)1016 first_virtual_engine(struct intel_engine_cs *engine)
1017 {
1018 	struct intel_engine_execlists *el = &engine->execlists;
1019 	struct rb_node *rb = rb_first_cached(&el->virtual);
1020 
1021 	while (rb) {
1022 		struct virtual_engine *ve =
1023 			rb_entry(rb, typeof(*ve), nodes[engine->id].rb);
1024 		struct i915_request *rq = READ_ONCE(ve->request);
1025 
1026 		/* lazily cleanup after another engine handled rq */
1027 		if (!rq || !virtual_matches(ve, rq, engine)) {
1028 			rb_erase_cached(rb, &el->virtual);
1029 			RB_CLEAR_NODE(rb);
1030 			rb = rb_first_cached(&el->virtual);
1031 			continue;
1032 		}
1033 
1034 		return ve;
1035 	}
1036 
1037 	return NULL;
1038 }
1039 
virtual_xfer_context(struct virtual_engine * ve,struct intel_engine_cs * engine)1040 static void virtual_xfer_context(struct virtual_engine *ve,
1041 				 struct intel_engine_cs *engine)
1042 {
1043 	unsigned int n;
1044 
1045 	if (likely(engine == ve->siblings[0]))
1046 		return;
1047 
1048 	GEM_BUG_ON(READ_ONCE(ve->context.inflight));
1049 	if (!intel_engine_has_relative_mmio(engine))
1050 		lrc_update_offsets(&ve->context, engine);
1051 
1052 	/*
1053 	 * Move the bound engine to the top of the list for
1054 	 * future execution. We then kick this tasklet first
1055 	 * before checking others, so that we preferentially
1056 	 * reuse this set of bound registers.
1057 	 */
1058 	for (n = 1; n < ve->num_siblings; n++) {
1059 		if (ve->siblings[n] == engine) {
1060 			swap(ve->siblings[n], ve->siblings[0]);
1061 			break;
1062 		}
1063 	}
1064 }
1065 
defer_request(struct i915_request * rq,struct list_head * const pl)1066 static void defer_request(struct i915_request *rq, struct list_head * const pl)
1067 {
1068 	LIST_HEAD(list);
1069 
1070 	/*
1071 	 * We want to move the interrupted request to the back of
1072 	 * the round-robin list (i.e. its priority level), but
1073 	 * in doing so, we must then move all requests that were in
1074 	 * flight and were waiting for the interrupted request to
1075 	 * be run after it again.
1076 	 */
1077 	do {
1078 		struct i915_dependency *p;
1079 
1080 		GEM_BUG_ON(i915_request_is_active(rq));
1081 		list_move_tail(&rq->sched.link, pl);
1082 
1083 		for_each_waiter(p, rq) {
1084 			struct i915_request *w =
1085 				container_of(p->waiter, typeof(*w), sched);
1086 
1087 			if (p->flags & I915_DEPENDENCY_WEAK)
1088 				continue;
1089 
1090 			/* Leave semaphores spinning on the other engines */
1091 			if (w->engine != rq->engine)
1092 				continue;
1093 
1094 			/* No waiter should start before its signaler */
1095 			GEM_BUG_ON(i915_request_has_initial_breadcrumb(w) &&
1096 				   __i915_request_has_started(w) &&
1097 				   !__i915_request_is_complete(rq));
1098 
1099 			if (!i915_request_is_ready(w))
1100 				continue;
1101 
1102 			if (rq_prio(w) < rq_prio(rq))
1103 				continue;
1104 
1105 			GEM_BUG_ON(rq_prio(w) > rq_prio(rq));
1106 			GEM_BUG_ON(i915_request_is_active(w));
1107 			list_move_tail(&w->sched.link, &list);
1108 		}
1109 
1110 		rq = list_first_entry_or_null(&list, typeof(*rq), sched.link);
1111 	} while (rq);
1112 }
1113 
defer_active(struct intel_engine_cs * engine)1114 static void defer_active(struct intel_engine_cs *engine)
1115 {
1116 	struct i915_request *rq;
1117 
1118 	rq = __unwind_incomplete_requests(engine);
1119 	if (!rq)
1120 		return;
1121 
1122 	defer_request(rq, i915_sched_lookup_priolist(engine->sched_engine,
1123 						     rq_prio(rq)));
1124 }
1125 
1126 static bool
timeslice_yield(const struct intel_engine_execlists * el,const struct i915_request * rq)1127 timeslice_yield(const struct intel_engine_execlists *el,
1128 		const struct i915_request *rq)
1129 {
1130 	/*
1131 	 * Once bitten, forever smitten!
1132 	 *
1133 	 * If the active context ever busy-waited on a semaphore,
1134 	 * it will be treated as a hog until the end of its timeslice (i.e.
1135 	 * until it is scheduled out and replaced by a new submission,
1136 	 * possibly even its own lite-restore). The HW only sends an interrupt
1137 	 * on the first miss, and we do know if that semaphore has been
1138 	 * signaled, or even if it is now stuck on another semaphore. Play
1139 	 * safe, yield if it might be stuck -- it will be given a fresh
1140 	 * timeslice in the near future.
1141 	 */
1142 	return rq->context->lrc.ccid == READ_ONCE(el->yield);
1143 }
1144 
needs_timeslice(const struct intel_engine_cs * engine,const struct i915_request * rq)1145 static bool needs_timeslice(const struct intel_engine_cs *engine,
1146 			    const struct i915_request *rq)
1147 {
1148 	if (!intel_engine_has_timeslices(engine))
1149 		return false;
1150 
1151 	/* If not currently active, or about to switch, wait for next event */
1152 	if (!rq || __i915_request_is_complete(rq))
1153 		return false;
1154 
1155 	/* We do not need to start the timeslice until after the ACK */
1156 	if (READ_ONCE(engine->execlists.pending[0]))
1157 		return false;
1158 
1159 	/* If ELSP[1] is occupied, always check to see if worth slicing */
1160 	if (!list_is_last_rcu(&rq->sched.link,
1161 			      &engine->sched_engine->requests)) {
1162 		ENGINE_TRACE(engine, "timeslice required for second inflight context\n");
1163 		return true;
1164 	}
1165 
1166 	/* Otherwise, ELSP[0] is by itself, but may be waiting in the queue */
1167 	if (!i915_sched_engine_is_empty(engine->sched_engine)) {
1168 		ENGINE_TRACE(engine, "timeslice required for queue\n");
1169 		return true;
1170 	}
1171 
1172 	if (!RB_EMPTY_ROOT(&engine->execlists.virtual.rb_root)) {
1173 		ENGINE_TRACE(engine, "timeslice required for virtual\n");
1174 		return true;
1175 	}
1176 
1177 	return false;
1178 }
1179 
1180 static bool
timeslice_expired(struct intel_engine_cs * engine,const struct i915_request * rq)1181 timeslice_expired(struct intel_engine_cs *engine, const struct i915_request *rq)
1182 {
1183 	const struct intel_engine_execlists *el = &engine->execlists;
1184 
1185 	if (i915_request_has_nopreempt(rq) && __i915_request_has_started(rq))
1186 		return false;
1187 
1188 	if (!needs_timeslice(engine, rq))
1189 		return false;
1190 
1191 	return timer_expired(&el->timer) || timeslice_yield(el, rq);
1192 }
1193 
timeslice(const struct intel_engine_cs * engine)1194 static unsigned long timeslice(const struct intel_engine_cs *engine)
1195 {
1196 	return READ_ONCE(engine->props.timeslice_duration_ms);
1197 }
1198 
start_timeslice(struct intel_engine_cs * engine)1199 static void start_timeslice(struct intel_engine_cs *engine)
1200 {
1201 	struct intel_engine_execlists *el = &engine->execlists;
1202 	unsigned long duration;
1203 
1204 	/* Disable the timer if there is nothing to switch to */
1205 	duration = 0;
1206 	if (needs_timeslice(engine, *el->active)) {
1207 		/* Avoid continually prolonging an active timeslice */
1208 		if (timer_active(&el->timer)) {
1209 			/*
1210 			 * If we just submitted a new ELSP after an old
1211 			 * context, that context may have already consumed
1212 			 * its timeslice, so recheck.
1213 			 */
1214 			if (!timer_pending(&el->timer))
1215 				tasklet_hi_schedule(&engine->sched_engine->tasklet);
1216 			return;
1217 		}
1218 
1219 		duration = timeslice(engine);
1220 	}
1221 
1222 	set_timer_ms(&el->timer, duration);
1223 }
1224 
record_preemption(struct intel_engine_execlists * execlists)1225 static void record_preemption(struct intel_engine_execlists *execlists)
1226 {
1227 	(void)I915_SELFTEST_ONLY(execlists->preempt_hang.count++);
1228 }
1229 
active_preempt_timeout(struct intel_engine_cs * engine,const struct i915_request * rq)1230 static unsigned long active_preempt_timeout(struct intel_engine_cs *engine,
1231 					    const struct i915_request *rq)
1232 {
1233 	if (!rq)
1234 		return 0;
1235 
1236 	/* Only allow ourselves to force reset the currently active context */
1237 	engine->execlists.preempt_target = rq;
1238 
1239 	/* Force a fast reset for terminated contexts (ignoring sysfs!) */
1240 	if (unlikely(intel_context_is_banned(rq->context) || bad_request(rq)))
1241 		return INTEL_CONTEXT_BANNED_PREEMPT_TIMEOUT_MS;
1242 
1243 	return READ_ONCE(engine->props.preempt_timeout_ms);
1244 }
1245 
set_preempt_timeout(struct intel_engine_cs * engine,const struct i915_request * rq)1246 static void set_preempt_timeout(struct intel_engine_cs *engine,
1247 				const struct i915_request *rq)
1248 {
1249 	if (!intel_engine_has_preempt_reset(engine))
1250 		return;
1251 
1252 	set_timer_ms(&engine->execlists.preempt,
1253 		     active_preempt_timeout(engine, rq));
1254 }
1255 
completed(const struct i915_request * rq)1256 static bool completed(const struct i915_request *rq)
1257 {
1258 	if (i915_request_has_sentinel(rq))
1259 		return false;
1260 
1261 	return __i915_request_is_complete(rq);
1262 }
1263 
execlists_dequeue(struct intel_engine_cs * engine)1264 static void execlists_dequeue(struct intel_engine_cs *engine)
1265 {
1266 	struct intel_engine_execlists * const execlists = &engine->execlists;
1267 	struct i915_sched_engine * const sched_engine = engine->sched_engine;
1268 	struct i915_request **port = execlists->pending;
1269 	struct i915_request ** const last_port = port + execlists->port_mask;
1270 	struct i915_request *last, * const *active;
1271 	struct virtual_engine *ve;
1272 	struct rb_node *rb;
1273 	bool submit = false;
1274 
1275 	/*
1276 	 * Hardware submission is through 2 ports. Conceptually each port
1277 	 * has a (RING_START, RING_HEAD, RING_TAIL) tuple. RING_START is
1278 	 * static for a context, and unique to each, so we only execute
1279 	 * requests belonging to a single context from each ring. RING_HEAD
1280 	 * is maintained by the CS in the context image, it marks the place
1281 	 * where it got up to last time, and through RING_TAIL we tell the CS
1282 	 * where we want to execute up to this time.
1283 	 *
1284 	 * In this list the requests are in order of execution. Consecutive
1285 	 * requests from the same context are adjacent in the ringbuffer. We
1286 	 * can combine these requests into a single RING_TAIL update:
1287 	 *
1288 	 *              RING_HEAD...req1...req2
1289 	 *                                    ^- RING_TAIL
1290 	 * since to execute req2 the CS must first execute req1.
1291 	 *
1292 	 * Our goal then is to point each port to the end of a consecutive
1293 	 * sequence of requests as being the most optimal (fewest wake ups
1294 	 * and context switches) submission.
1295 	 */
1296 
1297 	spin_lock(&sched_engine->lock);
1298 
1299 	/*
1300 	 * If the queue is higher priority than the last
1301 	 * request in the currently active context, submit afresh.
1302 	 * We will resubmit again afterwards in case we need to split
1303 	 * the active context to interject the preemption request,
1304 	 * i.e. we will retrigger preemption following the ack in case
1305 	 * of trouble.
1306 	 *
1307 	 */
1308 	active = execlists->active;
1309 	while ((last = *active) && completed(last))
1310 		active++;
1311 
1312 	if (last) {
1313 		if (need_preempt(engine, last)) {
1314 			ENGINE_TRACE(engine,
1315 				     "preempting last=%llx:%lld, prio=%d, hint=%d\n",
1316 				     last->fence.context,
1317 				     last->fence.seqno,
1318 				     last->sched.attr.priority,
1319 				     sched_engine->queue_priority_hint);
1320 			record_preemption(execlists);
1321 
1322 			/*
1323 			 * Don't let the RING_HEAD advance past the breadcrumb
1324 			 * as we unwind (and until we resubmit) so that we do
1325 			 * not accidentally tell it to go backwards.
1326 			 */
1327 			ring_set_paused(engine, 1);
1328 
1329 			/*
1330 			 * Note that we have not stopped the GPU at this point,
1331 			 * so we are unwinding the incomplete requests as they
1332 			 * remain inflight and so by the time we do complete
1333 			 * the preemption, some of the unwound requests may
1334 			 * complete!
1335 			 */
1336 			__unwind_incomplete_requests(engine);
1337 
1338 			last = NULL;
1339 		} else if (timeslice_expired(engine, last)) {
1340 			ENGINE_TRACE(engine,
1341 				     "expired:%s last=%llx:%lld, prio=%d, hint=%d, yield?=%s\n",
1342 				     str_yes_no(timer_expired(&execlists->timer)),
1343 				     last->fence.context, last->fence.seqno,
1344 				     rq_prio(last),
1345 				     sched_engine->queue_priority_hint,
1346 				     str_yes_no(timeslice_yield(execlists, last)));
1347 
1348 			/*
1349 			 * Consume this timeslice; ensure we start a new one.
1350 			 *
1351 			 * The timeslice expired, and we will unwind the
1352 			 * running contexts and recompute the next ELSP.
1353 			 * If that submit will be the same pair of contexts
1354 			 * (due to dependency ordering), we will skip the
1355 			 * submission. If we don't cancel the timer now,
1356 			 * we will see that the timer has expired and
1357 			 * reschedule the tasklet; continually until the
1358 			 * next context switch or other preemption event.
1359 			 *
1360 			 * Since we have decided to reschedule based on
1361 			 * consumption of this timeslice, if we submit the
1362 			 * same context again, grant it a full timeslice.
1363 			 */
1364 			cancel_timer(&execlists->timer);
1365 			ring_set_paused(engine, 1);
1366 			defer_active(engine);
1367 
1368 			/*
1369 			 * Unlike for preemption, if we rewind and continue
1370 			 * executing the same context as previously active,
1371 			 * the order of execution will remain the same and
1372 			 * the tail will only advance. We do not need to
1373 			 * force a full context restore, as a lite-restore
1374 			 * is sufficient to resample the monotonic TAIL.
1375 			 *
1376 			 * If we switch to any other context, similarly we
1377 			 * will not rewind TAIL of current context, and
1378 			 * normal save/restore will preserve state and allow
1379 			 * us to later continue executing the same request.
1380 			 */
1381 			last = NULL;
1382 		} else {
1383 			/*
1384 			 * Otherwise if we already have a request pending
1385 			 * for execution after the current one, we can
1386 			 * just wait until the next CS event before
1387 			 * queuing more. In either case we will force a
1388 			 * lite-restore preemption event, but if we wait
1389 			 * we hopefully coalesce several updates into a single
1390 			 * submission.
1391 			 */
1392 			if (active[1]) {
1393 				/*
1394 				 * Even if ELSP[1] is occupied and not worthy
1395 				 * of timeslices, our queue might be.
1396 				 */
1397 				spin_unlock(&sched_engine->lock);
1398 				return;
1399 			}
1400 		}
1401 	}
1402 
1403 	/* XXX virtual is always taking precedence */
1404 	while ((ve = first_virtual_engine(engine))) {
1405 		struct i915_request *rq;
1406 
1407 		spin_lock(&ve->base.sched_engine->lock);
1408 
1409 		rq = ve->request;
1410 		if (unlikely(!virtual_matches(ve, rq, engine)))
1411 			goto unlock; /* lost the race to a sibling */
1412 
1413 		GEM_BUG_ON(rq->engine != &ve->base);
1414 		GEM_BUG_ON(rq->context != &ve->context);
1415 
1416 		if (unlikely(rq_prio(rq) < queue_prio(sched_engine))) {
1417 			spin_unlock(&ve->base.sched_engine->lock);
1418 			break;
1419 		}
1420 
1421 		if (last && !can_merge_rq(last, rq)) {
1422 			spin_unlock(&ve->base.sched_engine->lock);
1423 			spin_unlock(&engine->sched_engine->lock);
1424 			return; /* leave this for another sibling */
1425 		}
1426 
1427 		ENGINE_TRACE(engine,
1428 			     "virtual rq=%llx:%lld%s, new engine? %s\n",
1429 			     rq->fence.context,
1430 			     rq->fence.seqno,
1431 			     __i915_request_is_complete(rq) ? "!" :
1432 			     __i915_request_has_started(rq) ? "*" :
1433 			     "",
1434 			     str_yes_no(engine != ve->siblings[0]));
1435 
1436 		WRITE_ONCE(ve->request, NULL);
1437 		WRITE_ONCE(ve->base.sched_engine->queue_priority_hint, INT_MIN);
1438 
1439 		rb = &ve->nodes[engine->id].rb;
1440 		rb_erase_cached(rb, &execlists->virtual);
1441 		RB_CLEAR_NODE(rb);
1442 
1443 		GEM_BUG_ON(!(rq->execution_mask & engine->mask));
1444 		WRITE_ONCE(rq->engine, engine);
1445 
1446 		if (__i915_request_submit(rq)) {
1447 			/*
1448 			 * Only after we confirm that we will submit
1449 			 * this request (i.e. it has not already
1450 			 * completed), do we want to update the context.
1451 			 *
1452 			 * This serves two purposes. It avoids
1453 			 * unnecessary work if we are resubmitting an
1454 			 * already completed request after timeslicing.
1455 			 * But more importantly, it prevents us altering
1456 			 * ve->siblings[] on an idle context, where
1457 			 * we may be using ve->siblings[] in
1458 			 * virtual_context_enter / virtual_context_exit.
1459 			 */
1460 			virtual_xfer_context(ve, engine);
1461 			GEM_BUG_ON(ve->siblings[0] != engine);
1462 
1463 			submit = true;
1464 			last = rq;
1465 		}
1466 
1467 		i915_request_put(rq);
1468 unlock:
1469 		spin_unlock(&ve->base.sched_engine->lock);
1470 
1471 		/*
1472 		 * Hmm, we have a bunch of virtual engine requests,
1473 		 * but the first one was already completed (thanks
1474 		 * preempt-to-busy!). Keep looking at the veng queue
1475 		 * until we have no more relevant requests (i.e.
1476 		 * the normal submit queue has higher priority).
1477 		 */
1478 		if (submit)
1479 			break;
1480 	}
1481 
1482 	while ((rb = rb_first_cached(&sched_engine->queue))) {
1483 		struct i915_priolist *p = to_priolist(rb);
1484 		struct i915_request *rq, *rn;
1485 
1486 		priolist_for_each_request_consume(rq, rn, p) {
1487 			bool merge = true;
1488 
1489 			/*
1490 			 * Can we combine this request with the current port?
1491 			 * It has to be the same context/ringbuffer and not
1492 			 * have any exceptions (e.g. GVT saying never to
1493 			 * combine contexts).
1494 			 *
1495 			 * If we can combine the requests, we can execute both
1496 			 * by updating the RING_TAIL to point to the end of the
1497 			 * second request, and so we never need to tell the
1498 			 * hardware about the first.
1499 			 */
1500 			if (last && !can_merge_rq(last, rq)) {
1501 				/*
1502 				 * If we are on the second port and cannot
1503 				 * combine this request with the last, then we
1504 				 * are done.
1505 				 */
1506 				if (port == last_port)
1507 					goto done;
1508 
1509 				/*
1510 				 * We must not populate both ELSP[] with the
1511 				 * same LRCA, i.e. we must submit 2 different
1512 				 * contexts if we submit 2 ELSP.
1513 				 */
1514 				if (last->context == rq->context)
1515 					goto done;
1516 
1517 				if (i915_request_has_sentinel(last))
1518 					goto done;
1519 
1520 				/*
1521 				 * We avoid submitting virtual requests into
1522 				 * the secondary ports so that we can migrate
1523 				 * the request immediately to another engine
1524 				 * rather than wait for the primary request.
1525 				 */
1526 				if (rq->execution_mask != engine->mask)
1527 					goto done;
1528 
1529 				/*
1530 				 * If GVT overrides us we only ever submit
1531 				 * port[0], leaving port[1] empty. Note that we
1532 				 * also have to be careful that we don't queue
1533 				 * the same context (even though a different
1534 				 * request) to the second port.
1535 				 */
1536 				if (ctx_single_port_submission(last->context) ||
1537 				    ctx_single_port_submission(rq->context))
1538 					goto done;
1539 
1540 				merge = false;
1541 			}
1542 
1543 			if (__i915_request_submit(rq)) {
1544 				if (!merge) {
1545 					*port++ = i915_request_get(last);
1546 					last = NULL;
1547 				}
1548 
1549 				GEM_BUG_ON(last &&
1550 					   !can_merge_ctx(last->context,
1551 							  rq->context));
1552 				GEM_BUG_ON(last &&
1553 					   i915_seqno_passed(last->fence.seqno,
1554 							     rq->fence.seqno));
1555 
1556 				submit = true;
1557 				last = rq;
1558 			}
1559 		}
1560 
1561 		rb_erase_cached(&p->node, &sched_engine->queue);
1562 		i915_priolist_free(p);
1563 	}
1564 done:
1565 	*port++ = i915_request_get(last);
1566 
1567 	/*
1568 	 * Here be a bit of magic! Or sleight-of-hand, whichever you prefer.
1569 	 *
1570 	 * We choose the priority hint such that if we add a request of greater
1571 	 * priority than this, we kick the submission tasklet to decide on
1572 	 * the right order of submitting the requests to hardware. We must
1573 	 * also be prepared to reorder requests as they are in-flight on the
1574 	 * HW. We derive the priority hint then as the first "hole" in
1575 	 * the HW submission ports and if there are no available slots,
1576 	 * the priority of the lowest executing request, i.e. last.
1577 	 *
1578 	 * When we do receive a higher priority request ready to run from the
1579 	 * user, see queue_request(), the priority hint is bumped to that
1580 	 * request triggering preemption on the next dequeue (or subsequent
1581 	 * interrupt for secondary ports).
1582 	 */
1583 	sched_engine->queue_priority_hint = queue_prio(sched_engine);
1584 	i915_sched_engine_reset_on_empty(sched_engine);
1585 	spin_unlock(&sched_engine->lock);
1586 
1587 	/*
1588 	 * We can skip poking the HW if we ended up with exactly the same set
1589 	 * of requests as currently running, e.g. trying to timeslice a pair
1590 	 * of ordered contexts.
1591 	 */
1592 	if (submit &&
1593 	    memcmp(active,
1594 		   execlists->pending,
1595 		   (port - execlists->pending) * sizeof(*port))) {
1596 		*port = NULL;
1597 		while (port-- != execlists->pending)
1598 			execlists_schedule_in(*port, port - execlists->pending);
1599 
1600 		WRITE_ONCE(execlists->yield, -1);
1601 		set_preempt_timeout(engine, *active);
1602 		execlists_submit_ports(engine);
1603 	} else {
1604 		ring_set_paused(engine, 0);
1605 		while (port-- != execlists->pending)
1606 			i915_request_put(*port);
1607 		*execlists->pending = NULL;
1608 	}
1609 }
1610 
execlists_dequeue_irq(struct intel_engine_cs * engine)1611 static void execlists_dequeue_irq(struct intel_engine_cs *engine)
1612 {
1613 	local_irq_disable(); /* Suspend interrupts across request submission */
1614 	execlists_dequeue(engine);
1615 	local_irq_enable(); /* flush irq_work (e.g. breadcrumb enabling) */
1616 }
1617 
clear_ports(struct i915_request ** ports,int count)1618 static void clear_ports(struct i915_request **ports, int count)
1619 {
1620 	memset_p((void **)ports, NULL, count);
1621 }
1622 
1623 static void
copy_ports(struct i915_request ** dst,struct i915_request ** src,int count)1624 copy_ports(struct i915_request **dst, struct i915_request **src, int count)
1625 {
1626 	/* A memcpy_p() would be very useful here! */
1627 	while (count--)
1628 		WRITE_ONCE(*dst++, *src++); /* avoid write tearing */
1629 }
1630 
1631 static struct i915_request **
cancel_port_requests(struct intel_engine_execlists * const execlists,struct i915_request ** inactive)1632 cancel_port_requests(struct intel_engine_execlists * const execlists,
1633 		     struct i915_request **inactive)
1634 {
1635 	struct i915_request * const *port;
1636 
1637 	for (port = execlists->pending; *port; port++)
1638 		*inactive++ = *port;
1639 	clear_ports(execlists->pending, ARRAY_SIZE(execlists->pending));
1640 
1641 	/* Mark the end of active before we overwrite *active */
1642 	for (port = xchg(&execlists->active, execlists->pending); *port; port++)
1643 		*inactive++ = *port;
1644 	clear_ports(execlists->inflight, ARRAY_SIZE(execlists->inflight));
1645 
1646 	smp_wmb(); /* complete the seqlock for execlists_active() */
1647 	WRITE_ONCE(execlists->active, execlists->inflight);
1648 
1649 	/* Having cancelled all outstanding process_csb(), stop their timers */
1650 	GEM_BUG_ON(execlists->pending[0]);
1651 	cancel_timer(&execlists->timer);
1652 	cancel_timer(&execlists->preempt);
1653 
1654 	return inactive;
1655 }
1656 
1657 /*
1658  * Starting with Gen12, the status has a new format:
1659  *
1660  *     bit  0:     switched to new queue
1661  *     bit  1:     reserved
1662  *     bit  2:     semaphore wait mode (poll or signal), only valid when
1663  *                 switch detail is set to "wait on semaphore"
1664  *     bits 3-5:   engine class
1665  *     bits 6-11:  engine instance
1666  *     bits 12-14: reserved
1667  *     bits 15-25: sw context id of the lrc the GT switched to
1668  *     bits 26-31: sw counter of the lrc the GT switched to
1669  *     bits 32-35: context switch detail
1670  *                  - 0: ctx complete
1671  *                  - 1: wait on sync flip
1672  *                  - 2: wait on vblank
1673  *                  - 3: wait on scanline
1674  *                  - 4: wait on semaphore
1675  *                  - 5: context preempted (not on SEMAPHORE_WAIT or
1676  *                       WAIT_FOR_EVENT)
1677  *     bit  36:    reserved
1678  *     bits 37-43: wait detail (for switch detail 1 to 4)
1679  *     bits 44-46: reserved
1680  *     bits 47-57: sw context id of the lrc the GT switched away from
1681  *     bits 58-63: sw counter of the lrc the GT switched away from
1682  *
1683  * Xe_HP csb shuffles things around compared to TGL:
1684  *
1685  *     bits 0-3:   context switch detail (same possible values as TGL)
1686  *     bits 4-9:   engine instance
1687  *     bits 10-25: sw context id of the lrc the GT switched to
1688  *     bits 26-31: sw counter of the lrc the GT switched to
1689  *     bit  32:    semaphore wait mode (poll or signal), Only valid when
1690  *                 switch detail is set to "wait on semaphore"
1691  *     bit  33:    switched to new queue
1692  *     bits 34-41: wait detail (for switch detail 1 to 4)
1693  *     bits 42-57: sw context id of the lrc the GT switched away from
1694  *     bits 58-63: sw counter of the lrc the GT switched away from
1695  */
1696 static inline bool
__gen12_csb_parse(bool ctx_to_valid,bool ctx_away_valid,bool new_queue,u8 switch_detail)1697 __gen12_csb_parse(bool ctx_to_valid, bool ctx_away_valid, bool new_queue,
1698 		  u8 switch_detail)
1699 {
1700 	/*
1701 	 * The context switch detail is not guaranteed to be 5 when a preemption
1702 	 * occurs, so we can't just check for that. The check below works for
1703 	 * all the cases we care about, including preemptions of WAIT
1704 	 * instructions and lite-restore. Preempt-to-idle via the CTRL register
1705 	 * would require some extra handling, but we don't support that.
1706 	 */
1707 	if (!ctx_away_valid || new_queue) {
1708 		GEM_BUG_ON(!ctx_to_valid);
1709 		return true;
1710 	}
1711 
1712 	/*
1713 	 * switch detail = 5 is covered by the case above and we do not expect a
1714 	 * context switch on an unsuccessful wait instruction since we always
1715 	 * use polling mode.
1716 	 */
1717 	GEM_BUG_ON(switch_detail);
1718 	return false;
1719 }
1720 
xehp_csb_parse(const u64 csb)1721 static bool xehp_csb_parse(const u64 csb)
1722 {
1723 	return __gen12_csb_parse(XEHP_CSB_CTX_VALID(lower_32_bits(csb)), /* cxt to */
1724 				 XEHP_CSB_CTX_VALID(upper_32_bits(csb)), /* cxt away */
1725 				 upper_32_bits(csb) & XEHP_CTX_STATUS_SWITCHED_TO_NEW_QUEUE,
1726 				 GEN12_CTX_SWITCH_DETAIL(lower_32_bits(csb)));
1727 }
1728 
gen12_csb_parse(const u64 csb)1729 static bool gen12_csb_parse(const u64 csb)
1730 {
1731 	return __gen12_csb_parse(GEN12_CSB_CTX_VALID(lower_32_bits(csb)), /* cxt to */
1732 				 GEN12_CSB_CTX_VALID(upper_32_bits(csb)), /* cxt away */
1733 				 lower_32_bits(csb) & GEN12_CTX_STATUS_SWITCHED_TO_NEW_QUEUE,
1734 				 GEN12_CTX_SWITCH_DETAIL(upper_32_bits(csb)));
1735 }
1736 
gen8_csb_parse(const u64 csb)1737 static bool gen8_csb_parse(const u64 csb)
1738 {
1739 	return csb & (GEN8_CTX_STATUS_IDLE_ACTIVE | GEN8_CTX_STATUS_PREEMPTED);
1740 }
1741 
1742 static noinline u64
wa_csb_read(const struct intel_engine_cs * engine,u64 * const csb)1743 wa_csb_read(const struct intel_engine_cs *engine, u64 * const csb)
1744 {
1745 	u64 entry;
1746 
1747 	/*
1748 	 * Reading from the HWSP has one particular advantage: we can detect
1749 	 * a stale entry. Since the write into HWSP is broken, we have no reason
1750 	 * to trust the HW at all, the mmio entry may equally be unordered, so
1751 	 * we prefer the path that is self-checking and as a last resort,
1752 	 * return the mmio value.
1753 	 *
1754 	 * tgl,dg1:HSDES#22011327657
1755 	 */
1756 	preempt_disable();
1757 	if (wait_for_atomic_us((entry = READ_ONCE(*csb)) != -1, 10)) {
1758 		int idx = csb - engine->execlists.csb_status;
1759 		int status;
1760 
1761 		status = GEN8_EXECLISTS_STATUS_BUF;
1762 		if (idx >= 6) {
1763 			status = GEN11_EXECLISTS_STATUS_BUF2;
1764 			idx -= 6;
1765 		}
1766 		status += sizeof(u64) * idx;
1767 
1768 		entry = intel_uncore_read64(engine->uncore,
1769 					    _MMIO(engine->mmio_base + status));
1770 	}
1771 	preempt_enable();
1772 
1773 	return entry;
1774 }
1775 
csb_read(const struct intel_engine_cs * engine,u64 * const csb)1776 static u64 csb_read(const struct intel_engine_cs *engine, u64 * const csb)
1777 {
1778 	u64 entry = READ_ONCE(*csb);
1779 
1780 	/*
1781 	 * Unfortunately, the GPU does not always serialise its write
1782 	 * of the CSB entries before its write of the CSB pointer, at least
1783 	 * from the perspective of the CPU, using what is known as a Global
1784 	 * Observation Point. We may read a new CSB tail pointer, but then
1785 	 * read the stale CSB entries, causing us to misinterpret the
1786 	 * context-switch events, and eventually declare the GPU hung.
1787 	 *
1788 	 * icl:HSDES#1806554093
1789 	 * tgl:HSDES#22011248461
1790 	 */
1791 	if (unlikely(entry == -1))
1792 		entry = wa_csb_read(engine, csb);
1793 
1794 	/* Consume this entry so that we can spot its future reuse. */
1795 	WRITE_ONCE(*csb, -1);
1796 
1797 	/* ELSP is an implicit wmb() before the GPU wraps and overwrites csb */
1798 	return entry;
1799 }
1800 
new_timeslice(struct intel_engine_execlists * el)1801 static void new_timeslice(struct intel_engine_execlists *el)
1802 {
1803 	/* By cancelling, we will start afresh in start_timeslice() */
1804 	cancel_timer(&el->timer);
1805 }
1806 
1807 static struct i915_request **
process_csb(struct intel_engine_cs * engine,struct i915_request ** inactive)1808 process_csb(struct intel_engine_cs *engine, struct i915_request **inactive)
1809 {
1810 	struct intel_engine_execlists * const execlists = &engine->execlists;
1811 	u64 * const buf = execlists->csb_status;
1812 	const u8 num_entries = execlists->csb_size;
1813 	struct i915_request **prev;
1814 	u8 head, tail;
1815 
1816 	/*
1817 	 * As we modify our execlists state tracking we require exclusive
1818 	 * access. Either we are inside the tasklet, or the tasklet is disabled
1819 	 * and we assume that is only inside the reset paths and so serialised.
1820 	 */
1821 	GEM_BUG_ON(!tasklet_is_locked(&engine->sched_engine->tasklet) &&
1822 		   !reset_in_progress(engine));
1823 
1824 	/*
1825 	 * Note that csb_write, csb_status may be either in HWSP or mmio.
1826 	 * When reading from the csb_write mmio register, we have to be
1827 	 * careful to only use the GEN8_CSB_WRITE_PTR portion, which is
1828 	 * the low 4bits. As it happens we know the next 4bits are always
1829 	 * zero and so we can simply masked off the low u8 of the register
1830 	 * and treat it identically to reading from the HWSP (without having
1831 	 * to use explicit shifting and masking, and probably bifurcating
1832 	 * the code to handle the legacy mmio read).
1833 	 */
1834 	head = execlists->csb_head;
1835 	tail = READ_ONCE(*execlists->csb_write);
1836 	if (unlikely(head == tail))
1837 		return inactive;
1838 
1839 	/*
1840 	 * We will consume all events from HW, or at least pretend to.
1841 	 *
1842 	 * The sequence of events from the HW is deterministic, and derived
1843 	 * from our writes to the ELSP, with a smidgen of variability for
1844 	 * the arrival of the asynchronous requests wrt to the inflight
1845 	 * execution. If the HW sends an event that does not correspond with
1846 	 * the one we are expecting, we have to abandon all hope as we lose
1847 	 * all tracking of what the engine is actually executing. We will
1848 	 * only detect we are out of sequence with the HW when we get an
1849 	 * 'impossible' event because we have already drained our own
1850 	 * preemption/promotion queue. If this occurs, we know that we likely
1851 	 * lost track of execution earlier and must unwind and restart, the
1852 	 * simplest way is by stop processing the event queue and force the
1853 	 * engine to reset.
1854 	 */
1855 	execlists->csb_head = tail;
1856 	ENGINE_TRACE(engine, "cs-irq head=%d, tail=%d\n", head, tail);
1857 
1858 	/*
1859 	 * Hopefully paired with a wmb() in HW!
1860 	 *
1861 	 * We must complete the read of the write pointer before any reads
1862 	 * from the CSB, so that we do not see stale values. Without an rmb
1863 	 * (lfence) the HW may speculatively perform the CSB[] reads *before*
1864 	 * we perform the READ_ONCE(*csb_write).
1865 	 */
1866 	rmb();
1867 
1868 	/* Remember who was last running under the timer */
1869 	prev = inactive;
1870 	*prev = NULL;
1871 
1872 	do {
1873 		bool promote;
1874 		u64 csb;
1875 
1876 		if (++head == num_entries)
1877 			head = 0;
1878 
1879 		/*
1880 		 * We are flying near dragons again.
1881 		 *
1882 		 * We hold a reference to the request in execlist_port[]
1883 		 * but no more than that. We are operating in softirq
1884 		 * context and so cannot hold any mutex or sleep. That
1885 		 * prevents us stopping the requests we are processing
1886 		 * in port[] from being retired simultaneously (the
1887 		 * breadcrumb will be complete before we see the
1888 		 * context-switch). As we only hold the reference to the
1889 		 * request, any pointer chasing underneath the request
1890 		 * is subject to a potential use-after-free. Thus we
1891 		 * store all of the bookkeeping within port[] as
1892 		 * required, and avoid using unguarded pointers beneath
1893 		 * request itself. The same applies to the atomic
1894 		 * status notifier.
1895 		 */
1896 
1897 		csb = csb_read(engine, buf + head);
1898 		ENGINE_TRACE(engine, "csb[%d]: status=0x%08x:0x%08x\n",
1899 			     head, upper_32_bits(csb), lower_32_bits(csb));
1900 
1901 		if (GRAPHICS_VER_FULL(engine->i915) >= IP_VER(12, 55))
1902 			promote = xehp_csb_parse(csb);
1903 		else if (GRAPHICS_VER(engine->i915) >= 12)
1904 			promote = gen12_csb_parse(csb);
1905 		else
1906 			promote = gen8_csb_parse(csb);
1907 		if (promote) {
1908 			struct i915_request * const *old = execlists->active;
1909 
1910 			if (GEM_WARN_ON(!*execlists->pending)) {
1911 				execlists->error_interrupt |= ERROR_CSB;
1912 				break;
1913 			}
1914 
1915 			ring_set_paused(engine, 0);
1916 
1917 			/* Point active to the new ELSP; prevent overwriting */
1918 			WRITE_ONCE(execlists->active, execlists->pending);
1919 			smp_wmb(); /* notify execlists_active() */
1920 
1921 			/* cancel old inflight, prepare for switch */
1922 			trace_ports(execlists, "preempted", old);
1923 			while (*old)
1924 				*inactive++ = *old++;
1925 
1926 			/* switch pending to inflight */
1927 			GEM_BUG_ON(!assert_pending_valid(execlists, "promote"));
1928 			copy_ports(execlists->inflight,
1929 				   execlists->pending,
1930 				   execlists_num_ports(execlists));
1931 			smp_wmb(); /* complete the seqlock */
1932 			WRITE_ONCE(execlists->active, execlists->inflight);
1933 
1934 			/* XXX Magic delay for tgl */
1935 			ENGINE_POSTING_READ(engine, RING_CONTEXT_STATUS_PTR);
1936 
1937 			WRITE_ONCE(execlists->pending[0], NULL);
1938 		} else {
1939 			if (GEM_WARN_ON(!*execlists->active)) {
1940 				execlists->error_interrupt |= ERROR_CSB;
1941 				break;
1942 			}
1943 
1944 			/* port0 completed, advanced to port1 */
1945 			trace_ports(execlists, "completed", execlists->active);
1946 
1947 			/*
1948 			 * We rely on the hardware being strongly
1949 			 * ordered, that the breadcrumb write is
1950 			 * coherent (visible from the CPU) before the
1951 			 * user interrupt is processed. One might assume
1952 			 * that the breadcrumb write being before the
1953 			 * user interrupt and the CS event for the context
1954 			 * switch would therefore be before the CS event
1955 			 * itself...
1956 			 */
1957 			if (GEM_SHOW_DEBUG() &&
1958 			    !__i915_request_is_complete(*execlists->active)) {
1959 				struct i915_request *rq = *execlists->active;
1960 				const u32 *regs __maybe_unused =
1961 					rq->context->lrc_reg_state;
1962 
1963 				ENGINE_TRACE(engine,
1964 					     "context completed before request!\n");
1965 				ENGINE_TRACE(engine,
1966 					     "ring:{start:0x%08x, head:%04x, tail:%04x, ctl:%08x, mode:%08x}\n",
1967 					     ENGINE_READ(engine, RING_START),
1968 					     ENGINE_READ(engine, RING_HEAD) & HEAD_ADDR,
1969 					     ENGINE_READ(engine, RING_TAIL) & TAIL_ADDR,
1970 					     ENGINE_READ(engine, RING_CTL),
1971 					     ENGINE_READ(engine, RING_MI_MODE));
1972 				ENGINE_TRACE(engine,
1973 					     "rq:{start:%08x, head:%04x, tail:%04x, seqno:%llx:%d, hwsp:%d}, ",
1974 					     i915_ggtt_offset(rq->ring->vma),
1975 					     rq->head, rq->tail,
1976 					     rq->fence.context,
1977 					     lower_32_bits(rq->fence.seqno),
1978 					     hwsp_seqno(rq));
1979 				ENGINE_TRACE(engine,
1980 					     "ctx:{start:%08x, head:%04x, tail:%04x}, ",
1981 					     regs[CTX_RING_START],
1982 					     regs[CTX_RING_HEAD],
1983 					     regs[CTX_RING_TAIL]);
1984 			}
1985 
1986 			*inactive++ = *execlists->active++;
1987 
1988 			GEM_BUG_ON(execlists->active - execlists->inflight >
1989 				   execlists_num_ports(execlists));
1990 		}
1991 	} while (head != tail);
1992 
1993 	/*
1994 	 * Gen11 has proven to fail wrt global observation point between
1995 	 * entry and tail update, failing on the ordering and thus
1996 	 * we see an old entry in the context status buffer.
1997 	 *
1998 	 * Forcibly evict out entries for the next gpu csb update,
1999 	 * to increase the odds that we get a fresh entries with non
2000 	 * working hardware. The cost for doing so comes out mostly with
2001 	 * the wash as hardware, working or not, will need to do the
2002 	 * invalidation before.
2003 	 */
2004 	drm_clflush_virt_range(&buf[0], num_entries * sizeof(buf[0]));
2005 
2006 	/*
2007 	 * We assume that any event reflects a change in context flow
2008 	 * and merits a fresh timeslice. We reinstall the timer after
2009 	 * inspecting the queue to see if we need to resumbit.
2010 	 */
2011 	if (*prev != *execlists->active) { /* elide lite-restores */
2012 		struct intel_context *prev_ce = NULL, *active_ce = NULL;
2013 
2014 		/*
2015 		 * Note the inherent discrepancy between the HW runtime,
2016 		 * recorded as part of the context switch, and the CPU
2017 		 * adjustment for active contexts. We have to hope that
2018 		 * the delay in processing the CS event is very small
2019 		 * and consistent. It works to our advantage to have
2020 		 * the CPU adjustment _undershoot_ (i.e. start later than)
2021 		 * the CS timestamp so we never overreport the runtime
2022 		 * and correct overselves later when updating from HW.
2023 		 */
2024 		if (*prev)
2025 			prev_ce = (*prev)->context;
2026 		if (*execlists->active)
2027 			active_ce = (*execlists->active)->context;
2028 		if (prev_ce != active_ce) {
2029 			if (prev_ce)
2030 				lrc_runtime_stop(prev_ce);
2031 			if (active_ce)
2032 				lrc_runtime_start(active_ce);
2033 		}
2034 		new_timeslice(execlists);
2035 	}
2036 
2037 	return inactive;
2038 }
2039 
post_process_csb(struct i915_request ** port,struct i915_request ** last)2040 static void post_process_csb(struct i915_request **port,
2041 			     struct i915_request **last)
2042 {
2043 	while (port != last)
2044 		execlists_schedule_out(*port++);
2045 }
2046 
__execlists_hold(struct i915_request * rq)2047 static void __execlists_hold(struct i915_request *rq)
2048 {
2049 	LIST_HEAD(list);
2050 
2051 	do {
2052 		struct i915_dependency *p;
2053 
2054 		if (i915_request_is_active(rq))
2055 			__i915_request_unsubmit(rq);
2056 
2057 		clear_bit(I915_FENCE_FLAG_PQUEUE, &rq->fence.flags);
2058 		list_move_tail(&rq->sched.link,
2059 			       &rq->engine->sched_engine->hold);
2060 		i915_request_set_hold(rq);
2061 		RQ_TRACE(rq, "on hold\n");
2062 
2063 		for_each_waiter(p, rq) {
2064 			struct i915_request *w =
2065 				container_of(p->waiter, typeof(*w), sched);
2066 
2067 			if (p->flags & I915_DEPENDENCY_WEAK)
2068 				continue;
2069 
2070 			/* Leave semaphores spinning on the other engines */
2071 			if (w->engine != rq->engine)
2072 				continue;
2073 
2074 			if (!i915_request_is_ready(w))
2075 				continue;
2076 
2077 			if (__i915_request_is_complete(w))
2078 				continue;
2079 
2080 			if (i915_request_on_hold(w))
2081 				continue;
2082 
2083 			list_move_tail(&w->sched.link, &list);
2084 		}
2085 
2086 		rq = list_first_entry_or_null(&list, typeof(*rq), sched.link);
2087 	} while (rq);
2088 }
2089 
execlists_hold(struct intel_engine_cs * engine,struct i915_request * rq)2090 static bool execlists_hold(struct intel_engine_cs *engine,
2091 			   struct i915_request *rq)
2092 {
2093 	if (i915_request_on_hold(rq))
2094 		return false;
2095 
2096 	spin_lock_irq(&engine->sched_engine->lock);
2097 
2098 	if (__i915_request_is_complete(rq)) { /* too late! */
2099 		rq = NULL;
2100 		goto unlock;
2101 	}
2102 
2103 	/*
2104 	 * Transfer this request onto the hold queue to prevent it
2105 	 * being resumbitted to HW (and potentially completed) before we have
2106 	 * released it. Since we may have already submitted following
2107 	 * requests, we need to remove those as well.
2108 	 */
2109 	GEM_BUG_ON(i915_request_on_hold(rq));
2110 	GEM_BUG_ON(rq->engine != engine);
2111 	__execlists_hold(rq);
2112 	GEM_BUG_ON(list_empty(&engine->sched_engine->hold));
2113 
2114 unlock:
2115 	spin_unlock_irq(&engine->sched_engine->lock);
2116 	return rq;
2117 }
2118 
hold_request(const struct i915_request * rq)2119 static bool hold_request(const struct i915_request *rq)
2120 {
2121 	struct i915_dependency *p;
2122 	bool result = false;
2123 
2124 	/*
2125 	 * If one of our ancestors is on hold, we must also be on hold,
2126 	 * otherwise we will bypass it and execute before it.
2127 	 */
2128 	rcu_read_lock();
2129 	for_each_signaler(p, rq) {
2130 		const struct i915_request *s =
2131 			container_of(p->signaler, typeof(*s), sched);
2132 
2133 		if (s->engine != rq->engine)
2134 			continue;
2135 
2136 		result = i915_request_on_hold(s);
2137 		if (result)
2138 			break;
2139 	}
2140 	rcu_read_unlock();
2141 
2142 	return result;
2143 }
2144 
__execlists_unhold(struct i915_request * rq)2145 static void __execlists_unhold(struct i915_request *rq)
2146 {
2147 	LIST_HEAD(list);
2148 
2149 	do {
2150 		struct i915_dependency *p;
2151 
2152 		RQ_TRACE(rq, "hold release\n");
2153 
2154 		GEM_BUG_ON(!i915_request_on_hold(rq));
2155 		GEM_BUG_ON(!i915_sw_fence_signaled(&rq->submit));
2156 
2157 		i915_request_clear_hold(rq);
2158 		list_move_tail(&rq->sched.link,
2159 			       i915_sched_lookup_priolist(rq->engine->sched_engine,
2160 							  rq_prio(rq)));
2161 		set_bit(I915_FENCE_FLAG_PQUEUE, &rq->fence.flags);
2162 
2163 		/* Also release any children on this engine that are ready */
2164 		for_each_waiter(p, rq) {
2165 			struct i915_request *w =
2166 				container_of(p->waiter, typeof(*w), sched);
2167 
2168 			if (p->flags & I915_DEPENDENCY_WEAK)
2169 				continue;
2170 
2171 			if (w->engine != rq->engine)
2172 				continue;
2173 
2174 			if (!i915_request_on_hold(w))
2175 				continue;
2176 
2177 			/* Check that no other parents are also on hold */
2178 			if (hold_request(w))
2179 				continue;
2180 
2181 			list_move_tail(&w->sched.link, &list);
2182 		}
2183 
2184 		rq = list_first_entry_or_null(&list, typeof(*rq), sched.link);
2185 	} while (rq);
2186 }
2187 
execlists_unhold(struct intel_engine_cs * engine,struct i915_request * rq)2188 static void execlists_unhold(struct intel_engine_cs *engine,
2189 			     struct i915_request *rq)
2190 {
2191 	spin_lock_irq(&engine->sched_engine->lock);
2192 
2193 	/*
2194 	 * Move this request back to the priority queue, and all of its
2195 	 * children and grandchildren that were suspended along with it.
2196 	 */
2197 	__execlists_unhold(rq);
2198 
2199 	if (rq_prio(rq) > engine->sched_engine->queue_priority_hint) {
2200 		engine->sched_engine->queue_priority_hint = rq_prio(rq);
2201 		tasklet_hi_schedule(&engine->sched_engine->tasklet);
2202 	}
2203 
2204 	spin_unlock_irq(&engine->sched_engine->lock);
2205 }
2206 
2207 struct execlists_capture {
2208 	struct work_struct work;
2209 	struct i915_request *rq;
2210 	struct i915_gpu_coredump *error;
2211 };
2212 
execlists_capture_work(struct work_struct * work)2213 static void execlists_capture_work(struct work_struct *work)
2214 {
2215 	struct execlists_capture *cap = container_of(work, typeof(*cap), work);
2216 	const gfp_t gfp = __GFP_KSWAPD_RECLAIM | __GFP_RETRY_MAYFAIL |
2217 		__GFP_NOWARN;
2218 	struct intel_engine_cs *engine = cap->rq->engine;
2219 	struct intel_gt_coredump *gt = cap->error->gt;
2220 	struct intel_engine_capture_vma *vma;
2221 
2222 	/* Compress all the objects attached to the request, slow! */
2223 	vma = intel_engine_coredump_add_request(gt->engine, cap->rq, gfp);
2224 	if (vma) {
2225 		struct i915_vma_compress *compress =
2226 			i915_vma_capture_prepare(gt);
2227 
2228 		intel_engine_coredump_add_vma(gt->engine, vma, compress);
2229 		i915_vma_capture_finish(gt, compress);
2230 	}
2231 
2232 	gt->simulated = gt->engine->simulated;
2233 	cap->error->simulated = gt->simulated;
2234 
2235 	/* Publish the error state, and announce it to the world */
2236 	i915_error_state_store(cap->error);
2237 	i915_gpu_coredump_put(cap->error);
2238 
2239 	/* Return this request and all that depend upon it for signaling */
2240 	execlists_unhold(engine, cap->rq);
2241 	i915_request_put(cap->rq);
2242 
2243 	kfree(cap);
2244 }
2245 
capture_regs(struct intel_engine_cs * engine)2246 static struct execlists_capture *capture_regs(struct intel_engine_cs *engine)
2247 {
2248 	const gfp_t gfp = GFP_ATOMIC | __GFP_NOWARN;
2249 	struct execlists_capture *cap;
2250 
2251 	cap = kmalloc(sizeof(*cap), gfp);
2252 	if (!cap)
2253 		return NULL;
2254 
2255 	cap->error = i915_gpu_coredump_alloc(engine->i915, gfp);
2256 	if (!cap->error)
2257 		goto err_cap;
2258 
2259 	cap->error->gt = intel_gt_coredump_alloc(engine->gt, gfp, CORE_DUMP_FLAG_NONE);
2260 	if (!cap->error->gt)
2261 		goto err_gpu;
2262 
2263 	cap->error->gt->engine = intel_engine_coredump_alloc(engine, gfp, CORE_DUMP_FLAG_NONE);
2264 	if (!cap->error->gt->engine)
2265 		goto err_gt;
2266 
2267 	cap->error->gt->engine->hung = true;
2268 
2269 	return cap;
2270 
2271 err_gt:
2272 	kfree(cap->error->gt);
2273 err_gpu:
2274 	kfree(cap->error);
2275 err_cap:
2276 	kfree(cap);
2277 	return NULL;
2278 }
2279 
2280 static struct i915_request *
active_context(struct intel_engine_cs * engine,u32 ccid)2281 active_context(struct intel_engine_cs *engine, u32 ccid)
2282 {
2283 	const struct intel_engine_execlists * const el = &engine->execlists;
2284 	struct i915_request * const *port, *rq;
2285 
2286 	/*
2287 	 * Use the most recent result from process_csb(), but just in case
2288 	 * we trigger an error (via interrupt) before the first CS event has
2289 	 * been written, peek at the next submission.
2290 	 */
2291 
2292 	for (port = el->active; (rq = *port); port++) {
2293 		if (rq->context->lrc.ccid == ccid) {
2294 			ENGINE_TRACE(engine,
2295 				     "ccid:%x found at active:%zd\n",
2296 				     ccid, port - el->active);
2297 			return rq;
2298 		}
2299 	}
2300 
2301 	for (port = el->pending; (rq = *port); port++) {
2302 		if (rq->context->lrc.ccid == ccid) {
2303 			ENGINE_TRACE(engine,
2304 				     "ccid:%x found at pending:%zd\n",
2305 				     ccid, port - el->pending);
2306 			return rq;
2307 		}
2308 	}
2309 
2310 	ENGINE_TRACE(engine, "ccid:%x not found\n", ccid);
2311 	return NULL;
2312 }
2313 
active_ccid(struct intel_engine_cs * engine)2314 static u32 active_ccid(struct intel_engine_cs *engine)
2315 {
2316 	return ENGINE_READ_FW(engine, RING_EXECLIST_STATUS_HI);
2317 }
2318 
execlists_capture(struct intel_engine_cs * engine)2319 static void execlists_capture(struct intel_engine_cs *engine)
2320 {
2321 	struct drm_i915_private *i915 = engine->i915;
2322 	struct execlists_capture *cap;
2323 
2324 	if (!IS_ENABLED(CONFIG_DRM_I915_CAPTURE_ERROR))
2325 		return;
2326 
2327 	/*
2328 	 * We need to _quickly_ capture the engine state before we reset.
2329 	 * We are inside an atomic section (softirq) here and we are delaying
2330 	 * the forced preemption event.
2331 	 */
2332 	cap = capture_regs(engine);
2333 	if (!cap)
2334 		return;
2335 
2336 	spin_lock_irq(&engine->sched_engine->lock);
2337 	cap->rq = active_context(engine, active_ccid(engine));
2338 	if (cap->rq) {
2339 		cap->rq = active_request(cap->rq->context->timeline, cap->rq);
2340 		cap->rq = i915_request_get_rcu(cap->rq);
2341 	}
2342 	spin_unlock_irq(&engine->sched_engine->lock);
2343 	if (!cap->rq)
2344 		goto err_free;
2345 
2346 	/*
2347 	 * Remove the request from the execlists queue, and take ownership
2348 	 * of the request. We pass it to our worker who will _slowly_ compress
2349 	 * all the pages the _user_ requested for debugging their batch, after
2350 	 * which we return it to the queue for signaling.
2351 	 *
2352 	 * By removing them from the execlists queue, we also remove the
2353 	 * requests from being processed by __unwind_incomplete_requests()
2354 	 * during the intel_engine_reset(), and so they will *not* be replayed
2355 	 * afterwards.
2356 	 *
2357 	 * Note that because we have not yet reset the engine at this point,
2358 	 * it is possible for the request that we have identified as being
2359 	 * guilty, did in fact complete and we will then hit an arbitration
2360 	 * point allowing the outstanding preemption to succeed. The likelihood
2361 	 * of that is very low (as capturing of the engine registers should be
2362 	 * fast enough to run inside an irq-off atomic section!), so we will
2363 	 * simply hold that request accountable for being non-preemptible
2364 	 * long enough to force the reset.
2365 	 */
2366 	if (!execlists_hold(engine, cap->rq))
2367 		goto err_rq;
2368 
2369 	INIT_WORK(&cap->work, execlists_capture_work);
2370 	queue_work(i915->unordered_wq, &cap->work);
2371 	return;
2372 
2373 err_rq:
2374 	i915_request_put(cap->rq);
2375 err_free:
2376 	i915_gpu_coredump_put(cap->error);
2377 	kfree(cap);
2378 }
2379 
execlists_reset(struct intel_engine_cs * engine,const char * msg)2380 static void execlists_reset(struct intel_engine_cs *engine, const char *msg)
2381 {
2382 	const unsigned int bit = I915_RESET_ENGINE + engine->id;
2383 	unsigned long *lock = &engine->gt->reset.flags;
2384 
2385 	if (!intel_has_reset_engine(engine->gt))
2386 		return;
2387 
2388 	if (test_and_set_bit(bit, lock))
2389 		return;
2390 
2391 	ENGINE_TRACE(engine, "reset for %s\n", msg);
2392 
2393 	/* Mark this tasklet as disabled to avoid waiting for it to complete */
2394 	tasklet_disable_nosync(&engine->sched_engine->tasklet);
2395 
2396 	ring_set_paused(engine, 1); /* Freeze the current request in place */
2397 	execlists_capture(engine);
2398 	intel_engine_reset(engine, msg);
2399 
2400 	tasklet_enable(&engine->sched_engine->tasklet);
2401 	clear_and_wake_up_bit(bit, lock);
2402 }
2403 
preempt_timeout(const struct intel_engine_cs * const engine)2404 static bool preempt_timeout(const struct intel_engine_cs *const engine)
2405 {
2406 	const struct timer_list *t = &engine->execlists.preempt;
2407 
2408 	if (!CONFIG_DRM_I915_PREEMPT_TIMEOUT)
2409 		return false;
2410 
2411 	if (!timer_expired(t))
2412 		return false;
2413 
2414 	return engine->execlists.pending[0];
2415 }
2416 
2417 /*
2418  * Check the unread Context Status Buffers and manage the submission of new
2419  * contexts to the ELSP accordingly.
2420  */
execlists_submission_tasklet(struct tasklet_struct * t)2421 static void execlists_submission_tasklet(struct tasklet_struct *t)
2422 {
2423 	struct i915_sched_engine *sched_engine =
2424 		from_tasklet(sched_engine, t, tasklet);
2425 	struct intel_engine_cs * const engine = sched_engine->private_data;
2426 	struct i915_request *post[2 * EXECLIST_MAX_PORTS];
2427 	struct i915_request **inactive;
2428 
2429 	rcu_read_lock();
2430 	inactive = process_csb(engine, post);
2431 	GEM_BUG_ON(inactive - post > ARRAY_SIZE(post));
2432 
2433 	if (unlikely(preempt_timeout(engine))) {
2434 		const struct i915_request *rq = *engine->execlists.active;
2435 
2436 		/*
2437 		 * If after the preempt-timeout expired, we are still on the
2438 		 * same active request/context as before we initiated the
2439 		 * preemption, reset the engine.
2440 		 *
2441 		 * However, if we have processed a CS event to switch contexts,
2442 		 * but not yet processed the CS event for the pending
2443 		 * preemption, reset the timer allowing the new context to
2444 		 * gracefully exit.
2445 		 */
2446 		cancel_timer(&engine->execlists.preempt);
2447 		if (rq == engine->execlists.preempt_target)
2448 			engine->execlists.error_interrupt |= ERROR_PREEMPT;
2449 		else
2450 			set_timer_ms(&engine->execlists.preempt,
2451 				     active_preempt_timeout(engine, rq));
2452 	}
2453 
2454 	if (unlikely(READ_ONCE(engine->execlists.error_interrupt))) {
2455 		const char *msg;
2456 
2457 		/* Generate the error message in priority wrt to the user! */
2458 		if (engine->execlists.error_interrupt & GENMASK(15, 0))
2459 			msg = "CS error"; /* thrown by a user payload */
2460 		else if (engine->execlists.error_interrupt & ERROR_CSB)
2461 			msg = "invalid CSB event";
2462 		else if (engine->execlists.error_interrupt & ERROR_PREEMPT)
2463 			msg = "preemption time out";
2464 		else
2465 			msg = "internal error";
2466 
2467 		engine->execlists.error_interrupt = 0;
2468 		execlists_reset(engine, msg);
2469 	}
2470 
2471 	if (!engine->execlists.pending[0]) {
2472 		execlists_dequeue_irq(engine);
2473 		start_timeslice(engine);
2474 	}
2475 
2476 	post_process_csb(post, inactive);
2477 	rcu_read_unlock();
2478 }
2479 
execlists_irq_handler(struct intel_engine_cs * engine,u16 iir)2480 static void execlists_irq_handler(struct intel_engine_cs *engine, u16 iir)
2481 {
2482 	bool tasklet = false;
2483 
2484 	if (unlikely(iir & GT_CS_MASTER_ERROR_INTERRUPT)) {
2485 		u32 eir;
2486 
2487 		/* Upper 16b are the enabling mask, rsvd for internal errors */
2488 		eir = ENGINE_READ(engine, RING_EIR) & GENMASK(15, 0);
2489 		ENGINE_TRACE(engine, "CS error: %x\n", eir);
2490 
2491 		/* Disable the error interrupt until after the reset */
2492 		if (likely(eir)) {
2493 			ENGINE_WRITE(engine, RING_EMR, ~0u);
2494 			ENGINE_WRITE(engine, RING_EIR, eir);
2495 			WRITE_ONCE(engine->execlists.error_interrupt, eir);
2496 			tasklet = true;
2497 		}
2498 	}
2499 
2500 	if (iir & GT_WAIT_SEMAPHORE_INTERRUPT) {
2501 		WRITE_ONCE(engine->execlists.yield,
2502 			   ENGINE_READ_FW(engine, RING_EXECLIST_STATUS_HI));
2503 		ENGINE_TRACE(engine, "semaphore yield: %08x\n",
2504 			     engine->execlists.yield);
2505 		if (del_timer(&engine->execlists.timer))
2506 			tasklet = true;
2507 	}
2508 
2509 	if (iir & GT_CONTEXT_SWITCH_INTERRUPT)
2510 		tasklet = true;
2511 
2512 	if (iir & GT_RENDER_USER_INTERRUPT)
2513 		intel_engine_signal_breadcrumbs(engine);
2514 
2515 	if (tasklet)
2516 		tasklet_hi_schedule(&engine->sched_engine->tasklet);
2517 }
2518 
__execlists_kick(struct intel_engine_execlists * execlists)2519 static void __execlists_kick(struct intel_engine_execlists *execlists)
2520 {
2521 	struct intel_engine_cs *engine =
2522 		container_of(execlists, typeof(*engine), execlists);
2523 
2524 	/* Kick the tasklet for some interrupt coalescing and reset handling */
2525 	tasklet_hi_schedule(&engine->sched_engine->tasklet);
2526 }
2527 
2528 #define execlists_kick(t, member) \
2529 	__execlists_kick(container_of(t, struct intel_engine_execlists, member))
2530 
execlists_timeslice(struct timer_list * timer)2531 static void execlists_timeslice(struct timer_list *timer)
2532 {
2533 	execlists_kick(timer, timer);
2534 }
2535 
execlists_preempt(struct timer_list * timer)2536 static void execlists_preempt(struct timer_list *timer)
2537 {
2538 	execlists_kick(timer, preempt);
2539 }
2540 
queue_request(struct intel_engine_cs * engine,struct i915_request * rq)2541 static void queue_request(struct intel_engine_cs *engine,
2542 			  struct i915_request *rq)
2543 {
2544 	GEM_BUG_ON(!list_empty(&rq->sched.link));
2545 	list_add_tail(&rq->sched.link,
2546 		      i915_sched_lookup_priolist(engine->sched_engine,
2547 						 rq_prio(rq)));
2548 	set_bit(I915_FENCE_FLAG_PQUEUE, &rq->fence.flags);
2549 }
2550 
submit_queue(struct intel_engine_cs * engine,const struct i915_request * rq)2551 static bool submit_queue(struct intel_engine_cs *engine,
2552 			 const struct i915_request *rq)
2553 {
2554 	struct i915_sched_engine *sched_engine = engine->sched_engine;
2555 
2556 	if (rq_prio(rq) <= sched_engine->queue_priority_hint)
2557 		return false;
2558 
2559 	sched_engine->queue_priority_hint = rq_prio(rq);
2560 	return true;
2561 }
2562 
ancestor_on_hold(const struct intel_engine_cs * engine,const struct i915_request * rq)2563 static bool ancestor_on_hold(const struct intel_engine_cs *engine,
2564 			     const struct i915_request *rq)
2565 {
2566 	GEM_BUG_ON(i915_request_on_hold(rq));
2567 	return !list_empty(&engine->sched_engine->hold) && hold_request(rq);
2568 }
2569 
execlists_submit_request(struct i915_request * request)2570 static void execlists_submit_request(struct i915_request *request)
2571 {
2572 	struct intel_engine_cs *engine = request->engine;
2573 	unsigned long flags;
2574 
2575 	/* Will be called from irq-context when using foreign fences. */
2576 	spin_lock_irqsave(&engine->sched_engine->lock, flags);
2577 
2578 	if (unlikely(ancestor_on_hold(engine, request))) {
2579 		RQ_TRACE(request, "ancestor on hold\n");
2580 		list_add_tail(&request->sched.link,
2581 			      &engine->sched_engine->hold);
2582 		i915_request_set_hold(request);
2583 	} else {
2584 		queue_request(engine, request);
2585 
2586 		GEM_BUG_ON(i915_sched_engine_is_empty(engine->sched_engine));
2587 		GEM_BUG_ON(list_empty(&request->sched.link));
2588 
2589 		if (submit_queue(engine, request))
2590 			__execlists_kick(&engine->execlists);
2591 	}
2592 
2593 	spin_unlock_irqrestore(&engine->sched_engine->lock, flags);
2594 }
2595 
2596 static int
__execlists_context_pre_pin(struct intel_context * ce,struct intel_engine_cs * engine,struct i915_gem_ww_ctx * ww,void ** vaddr)2597 __execlists_context_pre_pin(struct intel_context *ce,
2598 			    struct intel_engine_cs *engine,
2599 			    struct i915_gem_ww_ctx *ww, void **vaddr)
2600 {
2601 	int err;
2602 
2603 	err = lrc_pre_pin(ce, engine, ww, vaddr);
2604 	if (err)
2605 		return err;
2606 
2607 	if (!__test_and_set_bit(CONTEXT_INIT_BIT, &ce->flags)) {
2608 		lrc_init_state(ce, engine, *vaddr);
2609 
2610 		__i915_gem_object_flush_map(ce->state->obj, 0, engine->context_size);
2611 	}
2612 
2613 	return 0;
2614 }
2615 
execlists_context_pre_pin(struct intel_context * ce,struct i915_gem_ww_ctx * ww,void ** vaddr)2616 static int execlists_context_pre_pin(struct intel_context *ce,
2617 				     struct i915_gem_ww_ctx *ww,
2618 				     void **vaddr)
2619 {
2620 	return __execlists_context_pre_pin(ce, ce->engine, ww, vaddr);
2621 }
2622 
execlists_context_pin(struct intel_context * ce,void * vaddr)2623 static int execlists_context_pin(struct intel_context *ce, void *vaddr)
2624 {
2625 	return lrc_pin(ce, ce->engine, vaddr);
2626 }
2627 
execlists_context_alloc(struct intel_context * ce)2628 static int execlists_context_alloc(struct intel_context *ce)
2629 {
2630 	return lrc_alloc(ce, ce->engine);
2631 }
2632 
execlists_context_cancel_request(struct intel_context * ce,struct i915_request * rq)2633 static void execlists_context_cancel_request(struct intel_context *ce,
2634 					     struct i915_request *rq)
2635 {
2636 	struct intel_engine_cs *engine = NULL;
2637 
2638 	i915_request_active_engine(rq, &engine);
2639 
2640 	if (engine && intel_engine_pulse(engine))
2641 		intel_gt_handle_error(engine->gt, engine->mask, 0,
2642 				      "request cancellation by %s",
2643 				      current->comm);
2644 }
2645 
2646 static struct intel_context *
execlists_create_parallel(struct intel_engine_cs ** engines,unsigned int num_siblings,unsigned int width)2647 execlists_create_parallel(struct intel_engine_cs **engines,
2648 			  unsigned int num_siblings,
2649 			  unsigned int width)
2650 {
2651 	struct intel_context *parent = NULL, *ce, *err;
2652 	int i;
2653 
2654 	GEM_BUG_ON(num_siblings != 1);
2655 
2656 	for (i = 0; i < width; ++i) {
2657 		ce = intel_context_create(engines[i]);
2658 		if (IS_ERR(ce)) {
2659 			err = ce;
2660 			goto unwind;
2661 		}
2662 
2663 		if (i == 0)
2664 			parent = ce;
2665 		else
2666 			intel_context_bind_parent_child(parent, ce);
2667 	}
2668 
2669 	parent->parallel.fence_context = dma_fence_context_alloc(1);
2670 
2671 	intel_context_set_nopreempt(parent);
2672 	for_each_child(parent, ce)
2673 		intel_context_set_nopreempt(ce);
2674 
2675 	return parent;
2676 
2677 unwind:
2678 	if (parent)
2679 		intel_context_put(parent);
2680 	return err;
2681 }
2682 
2683 static const struct intel_context_ops execlists_context_ops = {
2684 	.flags = COPS_HAS_INFLIGHT | COPS_RUNTIME_CYCLES,
2685 
2686 	.alloc = execlists_context_alloc,
2687 
2688 	.cancel_request = execlists_context_cancel_request,
2689 
2690 	.pre_pin = execlists_context_pre_pin,
2691 	.pin = execlists_context_pin,
2692 	.unpin = lrc_unpin,
2693 	.post_unpin = lrc_post_unpin,
2694 
2695 	.enter = intel_context_enter_engine,
2696 	.exit = intel_context_exit_engine,
2697 
2698 	.reset = lrc_reset,
2699 	.destroy = lrc_destroy,
2700 
2701 	.create_parallel = execlists_create_parallel,
2702 	.create_virtual = execlists_create_virtual,
2703 };
2704 
emit_pdps(struct i915_request * rq)2705 static int emit_pdps(struct i915_request *rq)
2706 {
2707 	const struct intel_engine_cs * const engine = rq->engine;
2708 	struct i915_ppgtt * const ppgtt = i915_vm_to_ppgtt(rq->context->vm);
2709 	int err, i;
2710 	u32 *cs;
2711 
2712 	GEM_BUG_ON(intel_vgpu_active(rq->i915));
2713 
2714 	/*
2715 	 * Beware ye of the dragons, this sequence is magic!
2716 	 *
2717 	 * Small changes to this sequence can cause anything from
2718 	 * GPU hangs to forcewake errors and machine lockups!
2719 	 */
2720 
2721 	cs = intel_ring_begin(rq, 2);
2722 	if (IS_ERR(cs))
2723 		return PTR_ERR(cs);
2724 
2725 	*cs++ = MI_ARB_ON_OFF | MI_ARB_DISABLE;
2726 	*cs++ = MI_NOOP;
2727 	intel_ring_advance(rq, cs);
2728 
2729 	/* Flush any residual operations from the context load */
2730 	err = engine->emit_flush(rq, EMIT_FLUSH);
2731 	if (err)
2732 		return err;
2733 
2734 	/* Magic required to prevent forcewake errors! */
2735 	err = engine->emit_flush(rq, EMIT_INVALIDATE);
2736 	if (err)
2737 		return err;
2738 
2739 	cs = intel_ring_begin(rq, 4 * GEN8_3LVL_PDPES + 2);
2740 	if (IS_ERR(cs))
2741 		return PTR_ERR(cs);
2742 
2743 	/* Ensure the LRI have landed before we invalidate & continue */
2744 	*cs++ = MI_LOAD_REGISTER_IMM(2 * GEN8_3LVL_PDPES) | MI_LRI_FORCE_POSTED;
2745 	for (i = GEN8_3LVL_PDPES; i--; ) {
2746 		const dma_addr_t pd_daddr = i915_page_dir_dma_addr(ppgtt, i);
2747 		u32 base = engine->mmio_base;
2748 
2749 		*cs++ = i915_mmio_reg_offset(GEN8_RING_PDP_UDW(base, i));
2750 		*cs++ = upper_32_bits(pd_daddr);
2751 		*cs++ = i915_mmio_reg_offset(GEN8_RING_PDP_LDW(base, i));
2752 		*cs++ = lower_32_bits(pd_daddr);
2753 	}
2754 	*cs++ = MI_ARB_ON_OFF | MI_ARB_ENABLE;
2755 	intel_ring_advance(rq, cs);
2756 
2757 	intel_ring_advance(rq, cs);
2758 
2759 	return 0;
2760 }
2761 
execlists_request_alloc(struct i915_request * request)2762 static int execlists_request_alloc(struct i915_request *request)
2763 {
2764 	int ret;
2765 
2766 	GEM_BUG_ON(!intel_context_is_pinned(request->context));
2767 
2768 	/*
2769 	 * Flush enough space to reduce the likelihood of waiting after
2770 	 * we start building the request - in which case we will just
2771 	 * have to repeat work.
2772 	 */
2773 	request->reserved_space += EXECLISTS_REQUEST_SIZE;
2774 
2775 	/*
2776 	 * Note that after this point, we have committed to using
2777 	 * this request as it is being used to both track the
2778 	 * state of engine initialisation and liveness of the
2779 	 * golden renderstate above. Think twice before you try
2780 	 * to cancel/unwind this request now.
2781 	 */
2782 
2783 	if (!i915_vm_is_4lvl(request->context->vm)) {
2784 		ret = emit_pdps(request);
2785 		if (ret)
2786 			return ret;
2787 	}
2788 
2789 	/* Unconditionally invalidate GPU caches and TLBs. */
2790 	ret = request->engine->emit_flush(request, EMIT_INVALIDATE);
2791 	if (ret)
2792 		return ret;
2793 
2794 	request->reserved_space -= EXECLISTS_REQUEST_SIZE;
2795 	return 0;
2796 }
2797 
reset_csb_pointers(struct intel_engine_cs * engine)2798 static void reset_csb_pointers(struct intel_engine_cs *engine)
2799 {
2800 	struct intel_engine_execlists * const execlists = &engine->execlists;
2801 	const unsigned int reset_value = execlists->csb_size - 1;
2802 
2803 	ring_set_paused(engine, 0);
2804 
2805 	/*
2806 	 * Sometimes Icelake forgets to reset its pointers on a GPU reset.
2807 	 * Bludgeon them with a mmio update to be sure.
2808 	 */
2809 	ENGINE_WRITE(engine, RING_CONTEXT_STATUS_PTR,
2810 		     0xffff << 16 | reset_value << 8 | reset_value);
2811 	ENGINE_POSTING_READ(engine, RING_CONTEXT_STATUS_PTR);
2812 
2813 	/*
2814 	 * After a reset, the HW starts writing into CSB entry [0]. We
2815 	 * therefore have to set our HEAD pointer back one entry so that
2816 	 * the *first* entry we check is entry 0. To complicate this further,
2817 	 * as we don't wait for the first interrupt after reset, we have to
2818 	 * fake the HW write to point back to the last entry so that our
2819 	 * inline comparison of our cached head position against the last HW
2820 	 * write works even before the first interrupt.
2821 	 */
2822 	execlists->csb_head = reset_value;
2823 	WRITE_ONCE(*execlists->csb_write, reset_value);
2824 	wmb(); /* Make sure this is visible to HW (paranoia?) */
2825 
2826 	/* Check that the GPU does indeed update the CSB entries! */
2827 	memset(execlists->csb_status, -1, (reset_value + 1) * sizeof(u64));
2828 	drm_clflush_virt_range(execlists->csb_status,
2829 			       execlists->csb_size *
2830 			       sizeof(execlists->csb_status));
2831 
2832 	/* Once more for luck and our trusty paranoia */
2833 	ENGINE_WRITE(engine, RING_CONTEXT_STATUS_PTR,
2834 		     0xffff << 16 | reset_value << 8 | reset_value);
2835 	ENGINE_POSTING_READ(engine, RING_CONTEXT_STATUS_PTR);
2836 
2837 	GEM_BUG_ON(READ_ONCE(*execlists->csb_write) != reset_value);
2838 }
2839 
sanitize_hwsp(struct intel_engine_cs * engine)2840 static void sanitize_hwsp(struct intel_engine_cs *engine)
2841 {
2842 	struct intel_timeline *tl;
2843 
2844 	list_for_each_entry(tl, &engine->status_page.timelines, engine_link)
2845 		intel_timeline_reset_seqno(tl);
2846 }
2847 
execlists_sanitize(struct intel_engine_cs * engine)2848 static void execlists_sanitize(struct intel_engine_cs *engine)
2849 {
2850 	GEM_BUG_ON(execlists_active(&engine->execlists));
2851 
2852 	/*
2853 	 * Poison residual state on resume, in case the suspend didn't!
2854 	 *
2855 	 * We have to assume that across suspend/resume (or other loss
2856 	 * of control) that the contents of our pinned buffers has been
2857 	 * lost, replaced by garbage. Since this doesn't always happen,
2858 	 * let's poison such state so that we more quickly spot when
2859 	 * we falsely assume it has been preserved.
2860 	 */
2861 	if (IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM))
2862 		memset(engine->status_page.addr, POISON_INUSE, PAGE_SIZE);
2863 
2864 	reset_csb_pointers(engine);
2865 
2866 	/*
2867 	 * The kernel_context HWSP is stored in the status_page. As above,
2868 	 * that may be lost on resume/initialisation, and so we need to
2869 	 * reset the value in the HWSP.
2870 	 */
2871 	sanitize_hwsp(engine);
2872 
2873 	/* And scrub the dirty cachelines for the HWSP */
2874 	drm_clflush_virt_range(engine->status_page.addr, PAGE_SIZE);
2875 
2876 	intel_engine_reset_pinned_contexts(engine);
2877 }
2878 
enable_error_interrupt(struct intel_engine_cs * engine)2879 static void enable_error_interrupt(struct intel_engine_cs *engine)
2880 {
2881 	u32 status;
2882 
2883 	engine->execlists.error_interrupt = 0;
2884 	ENGINE_WRITE(engine, RING_EMR, ~0u);
2885 	ENGINE_WRITE(engine, RING_EIR, ~0u); /* clear all existing errors */
2886 
2887 	status = ENGINE_READ(engine, RING_ESR);
2888 	if (unlikely(status)) {
2889 		drm_err(&engine->i915->drm,
2890 			"engine '%s' resumed still in error: %08x\n",
2891 			engine->name, status);
2892 		intel_gt_reset_engine(engine);
2893 	}
2894 
2895 	/*
2896 	 * On current gen8+, we have 2 signals to play with
2897 	 *
2898 	 * - I915_ERROR_INSTUCTION (bit 0)
2899 	 *
2900 	 *    Generate an error if the command parser encounters an invalid
2901 	 *    instruction
2902 	 *
2903 	 *    This is a fatal error.
2904 	 *
2905 	 * - CP_PRIV (bit 2)
2906 	 *
2907 	 *    Generate an error on privilege violation (where the CP replaces
2908 	 *    the instruction with a no-op). This also fires for writes into
2909 	 *    read-only scratch pages.
2910 	 *
2911 	 *    This is a non-fatal error, parsing continues.
2912 	 *
2913 	 * * there are a few others defined for odd HW that we do not use
2914 	 *
2915 	 * Since CP_PRIV fires for cases where we have chosen to ignore the
2916 	 * error (as the HW is validating and suppressing the mistakes), we
2917 	 * only unmask the instruction error bit.
2918 	 */
2919 	ENGINE_WRITE(engine, RING_EMR, ~I915_ERROR_INSTRUCTION);
2920 }
2921 
enable_execlists(struct intel_engine_cs * engine)2922 static void enable_execlists(struct intel_engine_cs *engine)
2923 {
2924 	u32 mode;
2925 
2926 	assert_forcewakes_active(engine->uncore, FORCEWAKE_ALL);
2927 
2928 	intel_engine_set_hwsp_writemask(engine, ~0u); /* HWSTAM */
2929 
2930 	if (GRAPHICS_VER(engine->i915) >= 11)
2931 		mode = _MASKED_BIT_ENABLE(GEN11_GFX_DISABLE_LEGACY_MODE);
2932 	else
2933 		mode = _MASKED_BIT_ENABLE(GFX_RUN_LIST_ENABLE);
2934 	ENGINE_WRITE_FW(engine, RING_MODE_GEN7, mode);
2935 
2936 	ENGINE_WRITE_FW(engine, RING_MI_MODE, _MASKED_BIT_DISABLE(STOP_RING));
2937 
2938 	ENGINE_WRITE_FW(engine,
2939 			RING_HWS_PGA,
2940 			i915_ggtt_offset(engine->status_page.vma));
2941 	ENGINE_POSTING_READ(engine, RING_HWS_PGA);
2942 
2943 	enable_error_interrupt(engine);
2944 }
2945 
execlists_resume(struct intel_engine_cs * engine)2946 static int execlists_resume(struct intel_engine_cs *engine)
2947 {
2948 	intel_mocs_init_engine(engine);
2949 	intel_breadcrumbs_reset(engine->breadcrumbs);
2950 
2951 	enable_execlists(engine);
2952 
2953 	if (engine->flags & I915_ENGINE_FIRST_RENDER_COMPUTE)
2954 		xehp_enable_ccs_engines(engine);
2955 
2956 	return 0;
2957 }
2958 
execlists_reset_prepare(struct intel_engine_cs * engine)2959 static void execlists_reset_prepare(struct intel_engine_cs *engine)
2960 {
2961 	ENGINE_TRACE(engine, "depth<-%d\n",
2962 		     atomic_read(&engine->sched_engine->tasklet.count));
2963 
2964 	/*
2965 	 * Prevent request submission to the hardware until we have
2966 	 * completed the reset in i915_gem_reset_finish(). If a request
2967 	 * is completed by one engine, it may then queue a request
2968 	 * to a second via its execlists->tasklet *just* as we are
2969 	 * calling engine->resume() and also writing the ELSP.
2970 	 * Turning off the execlists->tasklet until the reset is over
2971 	 * prevents the race.
2972 	 */
2973 	__tasklet_disable_sync_once(&engine->sched_engine->tasklet);
2974 	GEM_BUG_ON(!reset_in_progress(engine));
2975 
2976 	/*
2977 	 * We stop engines, otherwise we might get failed reset and a
2978 	 * dead gpu (on elk). Also as modern gpu as kbl can suffer
2979 	 * from system hang if batchbuffer is progressing when
2980 	 * the reset is issued, regardless of READY_TO_RESET ack.
2981 	 * Thus assume it is best to stop engines on all gens
2982 	 * where we have a gpu reset.
2983 	 *
2984 	 * WaKBLVECSSemaphoreWaitPoll:kbl (on ALL_ENGINES)
2985 	 *
2986 	 * FIXME: Wa for more modern gens needs to be validated
2987 	 */
2988 	ring_set_paused(engine, 1);
2989 	intel_engine_stop_cs(engine);
2990 
2991 	/*
2992 	 * Wa_22011802037: In addition to stopping the cs, we need
2993 	 * to wait for any pending mi force wakeups
2994 	 */
2995 	if (intel_engine_reset_needs_wa_22011802037(engine->gt))
2996 		intel_engine_wait_for_pending_mi_fw(engine);
2997 
2998 	engine->execlists.reset_ccid = active_ccid(engine);
2999 }
3000 
3001 static struct i915_request **
reset_csb(struct intel_engine_cs * engine,struct i915_request ** inactive)3002 reset_csb(struct intel_engine_cs *engine, struct i915_request **inactive)
3003 {
3004 	struct intel_engine_execlists * const execlists = &engine->execlists;
3005 
3006 	drm_clflush_virt_range(execlists->csb_write,
3007 			       sizeof(execlists->csb_write[0]));
3008 
3009 	inactive = process_csb(engine, inactive); /* drain preemption events */
3010 
3011 	/* Following the reset, we need to reload the CSB read/write pointers */
3012 	reset_csb_pointers(engine);
3013 
3014 	return inactive;
3015 }
3016 
3017 static void
execlists_reset_active(struct intel_engine_cs * engine,bool stalled)3018 execlists_reset_active(struct intel_engine_cs *engine, bool stalled)
3019 {
3020 	struct intel_context *ce;
3021 	struct i915_request *rq;
3022 	u32 head;
3023 
3024 	/*
3025 	 * Save the currently executing context, even if we completed
3026 	 * its request, it was still running at the time of the
3027 	 * reset and will have been clobbered.
3028 	 */
3029 	rq = active_context(engine, engine->execlists.reset_ccid);
3030 	if (!rq)
3031 		return;
3032 
3033 	ce = rq->context;
3034 	GEM_BUG_ON(!i915_vma_is_pinned(ce->state));
3035 
3036 	if (__i915_request_is_complete(rq)) {
3037 		/* Idle context; tidy up the ring so we can restart afresh */
3038 		head = intel_ring_wrap(ce->ring, rq->tail);
3039 		goto out_replay;
3040 	}
3041 
3042 	/* We still have requests in-flight; the engine should be active */
3043 	GEM_BUG_ON(!intel_engine_pm_is_awake(engine));
3044 
3045 	/* Context has requests still in-flight; it should not be idle! */
3046 	GEM_BUG_ON(i915_active_is_idle(&ce->active));
3047 
3048 	rq = active_request(ce->timeline, rq);
3049 	head = intel_ring_wrap(ce->ring, rq->head);
3050 	GEM_BUG_ON(head == ce->ring->tail);
3051 
3052 	/*
3053 	 * If this request hasn't started yet, e.g. it is waiting on a
3054 	 * semaphore, we need to avoid skipping the request or else we
3055 	 * break the signaling chain. However, if the context is corrupt
3056 	 * the request will not restart and we will be stuck with a wedged
3057 	 * device. It is quite often the case that if we issue a reset
3058 	 * while the GPU is loading the context image, that the context
3059 	 * image becomes corrupt.
3060 	 *
3061 	 * Otherwise, if we have not started yet, the request should replay
3062 	 * perfectly and we do not need to flag the result as being erroneous.
3063 	 */
3064 	if (!__i915_request_has_started(rq))
3065 		goto out_replay;
3066 
3067 	/*
3068 	 * If the request was innocent, we leave the request in the ELSP
3069 	 * and will try to replay it on restarting. The context image may
3070 	 * have been corrupted by the reset, in which case we may have
3071 	 * to service a new GPU hang, but more likely we can continue on
3072 	 * without impact.
3073 	 *
3074 	 * If the request was guilty, we presume the context is corrupt
3075 	 * and have to at least restore the RING register in the context
3076 	 * image back to the expected values to skip over the guilty request.
3077 	 */
3078 	__i915_request_reset(rq, stalled);
3079 
3080 	/*
3081 	 * We want a simple context + ring to execute the breadcrumb update.
3082 	 * We cannot rely on the context being intact across the GPU hang,
3083 	 * so clear it and rebuild just what we need for the breadcrumb.
3084 	 * All pending requests for this context will be zapped, and any
3085 	 * future request will be after userspace has had the opportunity
3086 	 * to recreate its own state.
3087 	 */
3088 out_replay:
3089 	ENGINE_TRACE(engine, "replay {head:%04x, tail:%04x}\n",
3090 		     head, ce->ring->tail);
3091 	lrc_reset_regs(ce, engine);
3092 	ce->lrc.lrca = lrc_update_regs(ce, engine, head);
3093 }
3094 
execlists_reset_csb(struct intel_engine_cs * engine,bool stalled)3095 static void execlists_reset_csb(struct intel_engine_cs *engine, bool stalled)
3096 {
3097 	struct intel_engine_execlists * const execlists = &engine->execlists;
3098 	struct i915_request *post[2 * EXECLIST_MAX_PORTS];
3099 	struct i915_request **inactive;
3100 
3101 	rcu_read_lock();
3102 	inactive = reset_csb(engine, post);
3103 
3104 	execlists_reset_active(engine, true);
3105 
3106 	inactive = cancel_port_requests(execlists, inactive);
3107 	post_process_csb(post, inactive);
3108 	rcu_read_unlock();
3109 }
3110 
execlists_reset_rewind(struct intel_engine_cs * engine,bool stalled)3111 static void execlists_reset_rewind(struct intel_engine_cs *engine, bool stalled)
3112 {
3113 	unsigned long flags;
3114 
3115 	ENGINE_TRACE(engine, "\n");
3116 
3117 	/* Process the csb, find the guilty context and throw away */
3118 	execlists_reset_csb(engine, stalled);
3119 
3120 	/* Push back any incomplete requests for replay after the reset. */
3121 	rcu_read_lock();
3122 	spin_lock_irqsave(&engine->sched_engine->lock, flags);
3123 	__unwind_incomplete_requests(engine);
3124 	spin_unlock_irqrestore(&engine->sched_engine->lock, flags);
3125 	rcu_read_unlock();
3126 }
3127 
nop_submission_tasklet(struct tasklet_struct * t)3128 static void nop_submission_tasklet(struct tasklet_struct *t)
3129 {
3130 	struct i915_sched_engine *sched_engine =
3131 		from_tasklet(sched_engine, t, tasklet);
3132 	struct intel_engine_cs * const engine = sched_engine->private_data;
3133 
3134 	/* The driver is wedged; don't process any more events. */
3135 	WRITE_ONCE(engine->sched_engine->queue_priority_hint, INT_MIN);
3136 }
3137 
execlists_reset_cancel(struct intel_engine_cs * engine)3138 static void execlists_reset_cancel(struct intel_engine_cs *engine)
3139 {
3140 	struct intel_engine_execlists * const execlists = &engine->execlists;
3141 	struct i915_sched_engine * const sched_engine = engine->sched_engine;
3142 	struct i915_request *rq, *rn;
3143 	struct rb_node *rb;
3144 	unsigned long flags;
3145 
3146 	ENGINE_TRACE(engine, "\n");
3147 
3148 	/*
3149 	 * Before we call engine->cancel_requests(), we should have exclusive
3150 	 * access to the submission state. This is arranged for us by the
3151 	 * caller disabling the interrupt generation, the tasklet and other
3152 	 * threads that may then access the same state, giving us a free hand
3153 	 * to reset state. However, we still need to let lockdep be aware that
3154 	 * we know this state may be accessed in hardirq context, so we
3155 	 * disable the irq around this manipulation and we want to keep
3156 	 * the spinlock focused on its duties and not accidentally conflate
3157 	 * coverage to the submission's irq state. (Similarly, although we
3158 	 * shouldn't need to disable irq around the manipulation of the
3159 	 * submission's irq state, we also wish to remind ourselves that
3160 	 * it is irq state.)
3161 	 */
3162 	execlists_reset_csb(engine, true);
3163 
3164 	rcu_read_lock();
3165 	spin_lock_irqsave(&engine->sched_engine->lock, flags);
3166 
3167 	/* Mark all executing requests as skipped. */
3168 	list_for_each_entry(rq, &engine->sched_engine->requests, sched.link)
3169 		i915_request_put(i915_request_mark_eio(rq));
3170 	intel_engine_signal_breadcrumbs(engine);
3171 
3172 	/* Flush the queued requests to the timeline list (for retiring). */
3173 	while ((rb = rb_first_cached(&sched_engine->queue))) {
3174 		struct i915_priolist *p = to_priolist(rb);
3175 
3176 		priolist_for_each_request_consume(rq, rn, p) {
3177 			if (i915_request_mark_eio(rq)) {
3178 				__i915_request_submit(rq);
3179 				i915_request_put(rq);
3180 			}
3181 		}
3182 
3183 		rb_erase_cached(&p->node, &sched_engine->queue);
3184 		i915_priolist_free(p);
3185 	}
3186 
3187 	/* On-hold requests will be flushed to timeline upon their release */
3188 	list_for_each_entry(rq, &sched_engine->hold, sched.link)
3189 		i915_request_put(i915_request_mark_eio(rq));
3190 
3191 	/* Cancel all attached virtual engines */
3192 	while ((rb = rb_first_cached(&execlists->virtual))) {
3193 		struct virtual_engine *ve =
3194 			rb_entry(rb, typeof(*ve), nodes[engine->id].rb);
3195 
3196 		rb_erase_cached(rb, &execlists->virtual);
3197 		RB_CLEAR_NODE(rb);
3198 
3199 		spin_lock(&ve->base.sched_engine->lock);
3200 		rq = fetch_and_zero(&ve->request);
3201 		if (rq) {
3202 			if (i915_request_mark_eio(rq)) {
3203 				rq->engine = engine;
3204 				__i915_request_submit(rq);
3205 				i915_request_put(rq);
3206 			}
3207 			i915_request_put(rq);
3208 
3209 			ve->base.sched_engine->queue_priority_hint = INT_MIN;
3210 		}
3211 		spin_unlock(&ve->base.sched_engine->lock);
3212 	}
3213 
3214 	/* Remaining _unready_ requests will be nop'ed when submitted */
3215 
3216 	sched_engine->queue_priority_hint = INT_MIN;
3217 	sched_engine->queue = RB_ROOT_CACHED;
3218 
3219 	GEM_BUG_ON(__tasklet_is_enabled(&engine->sched_engine->tasklet));
3220 	engine->sched_engine->tasklet.callback = nop_submission_tasklet;
3221 
3222 	spin_unlock_irqrestore(&engine->sched_engine->lock, flags);
3223 	rcu_read_unlock();
3224 }
3225 
execlists_reset_finish(struct intel_engine_cs * engine)3226 static void execlists_reset_finish(struct intel_engine_cs *engine)
3227 {
3228 	struct intel_engine_execlists * const execlists = &engine->execlists;
3229 
3230 	/*
3231 	 * After a GPU reset, we may have requests to replay. Do so now while
3232 	 * we still have the forcewake to be sure that the GPU is not allowed
3233 	 * to sleep before we restart and reload a context.
3234 	 *
3235 	 * If the GPU reset fails, the engine may still be alive with requests
3236 	 * inflight. We expect those to complete, or for the device to be
3237 	 * reset as the next level of recovery, and as a final resort we
3238 	 * will declare the device wedged.
3239 	 */
3240 	GEM_BUG_ON(!reset_in_progress(engine));
3241 
3242 	/* And kick in case we missed a new request submission. */
3243 	if (__tasklet_enable(&engine->sched_engine->tasklet))
3244 		__execlists_kick(execlists);
3245 
3246 	ENGINE_TRACE(engine, "depth->%d\n",
3247 		     atomic_read(&engine->sched_engine->tasklet.count));
3248 }
3249 
gen8_logical_ring_enable_irq(struct intel_engine_cs * engine)3250 static void gen8_logical_ring_enable_irq(struct intel_engine_cs *engine)
3251 {
3252 	ENGINE_WRITE(engine, RING_IMR,
3253 		     ~(engine->irq_enable_mask | engine->irq_keep_mask));
3254 	ENGINE_POSTING_READ(engine, RING_IMR);
3255 }
3256 
gen8_logical_ring_disable_irq(struct intel_engine_cs * engine)3257 static void gen8_logical_ring_disable_irq(struct intel_engine_cs *engine)
3258 {
3259 	ENGINE_WRITE(engine, RING_IMR, ~engine->irq_keep_mask);
3260 }
3261 
execlists_park(struct intel_engine_cs * engine)3262 static void execlists_park(struct intel_engine_cs *engine)
3263 {
3264 	cancel_timer(&engine->execlists.timer);
3265 	cancel_timer(&engine->execlists.preempt);
3266 
3267 	/* Reset upon idling, or we may delay the busy wakeup. */
3268 	WRITE_ONCE(engine->sched_engine->queue_priority_hint, INT_MIN);
3269 }
3270 
add_to_engine(struct i915_request * rq)3271 static void add_to_engine(struct i915_request *rq)
3272 {
3273 	lockdep_assert_held(&rq->engine->sched_engine->lock);
3274 	list_move_tail(&rq->sched.link, &rq->engine->sched_engine->requests);
3275 }
3276 
remove_from_engine(struct i915_request * rq)3277 static void remove_from_engine(struct i915_request *rq)
3278 {
3279 	struct intel_engine_cs *engine, *locked;
3280 
3281 	/*
3282 	 * Virtual engines complicate acquiring the engine timeline lock,
3283 	 * as their rq->engine pointer is not stable until under that
3284 	 * engine lock. The simple ploy we use is to take the lock then
3285 	 * check that the rq still belongs to the newly locked engine.
3286 	 */
3287 	locked = READ_ONCE(rq->engine);
3288 	spin_lock_irq(&locked->sched_engine->lock);
3289 	while (unlikely(locked != (engine = READ_ONCE(rq->engine)))) {
3290 		spin_unlock(&locked->sched_engine->lock);
3291 		spin_lock(&engine->sched_engine->lock);
3292 		locked = engine;
3293 	}
3294 	list_del_init(&rq->sched.link);
3295 
3296 	clear_bit(I915_FENCE_FLAG_PQUEUE, &rq->fence.flags);
3297 	clear_bit(I915_FENCE_FLAG_HOLD, &rq->fence.flags);
3298 
3299 	/* Prevent further __await_execution() registering a cb, then flush */
3300 	set_bit(I915_FENCE_FLAG_ACTIVE, &rq->fence.flags);
3301 
3302 	spin_unlock_irq(&locked->sched_engine->lock);
3303 
3304 	i915_request_notify_execute_cb_imm(rq);
3305 }
3306 
can_preempt(struct intel_engine_cs * engine)3307 static bool can_preempt(struct intel_engine_cs *engine)
3308 {
3309 	return GRAPHICS_VER(engine->i915) > 8;
3310 }
3311 
kick_execlists(const struct i915_request * rq,int prio)3312 static void kick_execlists(const struct i915_request *rq, int prio)
3313 {
3314 	struct intel_engine_cs *engine = rq->engine;
3315 	struct i915_sched_engine *sched_engine = engine->sched_engine;
3316 	const struct i915_request *inflight;
3317 
3318 	/*
3319 	 * We only need to kick the tasklet once for the high priority
3320 	 * new context we add into the queue.
3321 	 */
3322 	if (prio <= sched_engine->queue_priority_hint)
3323 		return;
3324 
3325 	rcu_read_lock();
3326 
3327 	/* Nothing currently active? We're overdue for a submission! */
3328 	inflight = execlists_active(&engine->execlists);
3329 	if (!inflight)
3330 		goto unlock;
3331 
3332 	/*
3333 	 * If we are already the currently executing context, don't
3334 	 * bother evaluating if we should preempt ourselves.
3335 	 */
3336 	if (inflight->context == rq->context)
3337 		goto unlock;
3338 
3339 	ENGINE_TRACE(engine,
3340 		     "bumping queue-priority-hint:%d for rq:%llx:%lld, inflight:%llx:%lld prio %d\n",
3341 		     prio,
3342 		     rq->fence.context, rq->fence.seqno,
3343 		     inflight->fence.context, inflight->fence.seqno,
3344 		     inflight->sched.attr.priority);
3345 
3346 	sched_engine->queue_priority_hint = prio;
3347 
3348 	/*
3349 	 * Allow preemption of low -> normal -> high, but we do
3350 	 * not allow low priority tasks to preempt other low priority
3351 	 * tasks under the impression that latency for low priority
3352 	 * tasks does not matter (as much as background throughput),
3353 	 * so kiss.
3354 	 */
3355 	if (prio >= max(I915_PRIORITY_NORMAL, rq_prio(inflight)))
3356 		tasklet_hi_schedule(&sched_engine->tasklet);
3357 
3358 unlock:
3359 	rcu_read_unlock();
3360 }
3361 
execlists_set_default_submission(struct intel_engine_cs * engine)3362 static void execlists_set_default_submission(struct intel_engine_cs *engine)
3363 {
3364 	engine->submit_request = execlists_submit_request;
3365 	engine->sched_engine->schedule = i915_schedule;
3366 	engine->sched_engine->kick_backend = kick_execlists;
3367 	engine->sched_engine->tasklet.callback = execlists_submission_tasklet;
3368 }
3369 
execlists_shutdown(struct intel_engine_cs * engine)3370 static void execlists_shutdown(struct intel_engine_cs *engine)
3371 {
3372 	/* Synchronise with residual timers and any softirq they raise */
3373 	del_timer_sync(&engine->execlists.timer);
3374 	del_timer_sync(&engine->execlists.preempt);
3375 	tasklet_kill(&engine->sched_engine->tasklet);
3376 }
3377 
execlists_release(struct intel_engine_cs * engine)3378 static void execlists_release(struct intel_engine_cs *engine)
3379 {
3380 	engine->sanitize = NULL; /* no longer in control, nothing to sanitize */
3381 
3382 	execlists_shutdown(engine);
3383 
3384 	intel_engine_cleanup_common(engine);
3385 	lrc_fini_wa_ctx(engine);
3386 }
3387 
__execlists_engine_busyness(struct intel_engine_cs * engine,ktime_t * now)3388 static ktime_t __execlists_engine_busyness(struct intel_engine_cs *engine,
3389 					   ktime_t *now)
3390 {
3391 	struct intel_engine_execlists_stats *stats = &engine->stats.execlists;
3392 	ktime_t total = stats->total;
3393 
3394 	/*
3395 	 * If the engine is executing something at the moment
3396 	 * add it to the total.
3397 	 */
3398 	*now = ktime_get();
3399 	if (READ_ONCE(stats->active))
3400 		total = ktime_add(total, ktime_sub(*now, stats->start));
3401 
3402 	return total;
3403 }
3404 
execlists_engine_busyness(struct intel_engine_cs * engine,ktime_t * now)3405 static ktime_t execlists_engine_busyness(struct intel_engine_cs *engine,
3406 					 ktime_t *now)
3407 {
3408 	struct intel_engine_execlists_stats *stats = &engine->stats.execlists;
3409 	unsigned int seq;
3410 	ktime_t total;
3411 
3412 	do {
3413 		seq = read_seqcount_begin(&stats->lock);
3414 		total = __execlists_engine_busyness(engine, now);
3415 	} while (read_seqcount_retry(&stats->lock, seq));
3416 
3417 	return total;
3418 }
3419 
3420 static void
logical_ring_default_vfuncs(struct intel_engine_cs * engine)3421 logical_ring_default_vfuncs(struct intel_engine_cs *engine)
3422 {
3423 	/* Default vfuncs which can be overridden by each engine. */
3424 
3425 	engine->resume = execlists_resume;
3426 
3427 	engine->cops = &execlists_context_ops;
3428 	engine->request_alloc = execlists_request_alloc;
3429 	engine->add_active_request = add_to_engine;
3430 	engine->remove_active_request = remove_from_engine;
3431 
3432 	engine->reset.prepare = execlists_reset_prepare;
3433 	engine->reset.rewind = execlists_reset_rewind;
3434 	engine->reset.cancel = execlists_reset_cancel;
3435 	engine->reset.finish = execlists_reset_finish;
3436 
3437 	engine->park = execlists_park;
3438 	engine->unpark = NULL;
3439 
3440 	engine->emit_flush = gen8_emit_flush_xcs;
3441 	engine->emit_init_breadcrumb = gen8_emit_init_breadcrumb;
3442 	engine->emit_fini_breadcrumb = gen8_emit_fini_breadcrumb_xcs;
3443 	if (GRAPHICS_VER(engine->i915) >= 12) {
3444 		engine->emit_fini_breadcrumb = gen12_emit_fini_breadcrumb_xcs;
3445 		engine->emit_flush = gen12_emit_flush_xcs;
3446 	}
3447 	engine->set_default_submission = execlists_set_default_submission;
3448 
3449 	if (GRAPHICS_VER(engine->i915) < 11) {
3450 		engine->irq_enable = gen8_logical_ring_enable_irq;
3451 		engine->irq_disable = gen8_logical_ring_disable_irq;
3452 	} else {
3453 		/*
3454 		 * TODO: On Gen11 interrupt masks need to be clear
3455 		 * to allow C6 entry. Keep interrupts enabled at
3456 		 * and take the hit of generating extra interrupts
3457 		 * until a more refined solution exists.
3458 		 */
3459 	}
3460 	intel_engine_set_irq_handler(engine, execlists_irq_handler);
3461 
3462 	engine->flags |= I915_ENGINE_SUPPORTS_STATS;
3463 	if (!intel_vgpu_active(engine->i915)) {
3464 		engine->flags |= I915_ENGINE_HAS_SEMAPHORES;
3465 		if (can_preempt(engine)) {
3466 			engine->flags |= I915_ENGINE_HAS_PREEMPTION;
3467 			if (CONFIG_DRM_I915_TIMESLICE_DURATION)
3468 				engine->flags |= I915_ENGINE_HAS_TIMESLICES;
3469 		}
3470 	}
3471 
3472 	if (GRAPHICS_VER_FULL(engine->i915) >= IP_VER(12, 55)) {
3473 		if (intel_engine_has_preemption(engine))
3474 			engine->emit_bb_start = xehp_emit_bb_start;
3475 		else
3476 			engine->emit_bb_start = xehp_emit_bb_start_noarb;
3477 	} else {
3478 		if (intel_engine_has_preemption(engine))
3479 			engine->emit_bb_start = gen8_emit_bb_start;
3480 		else
3481 			engine->emit_bb_start = gen8_emit_bb_start_noarb;
3482 	}
3483 
3484 	engine->busyness = execlists_engine_busyness;
3485 }
3486 
logical_ring_default_irqs(struct intel_engine_cs * engine)3487 static void logical_ring_default_irqs(struct intel_engine_cs *engine)
3488 {
3489 	unsigned int shift = 0;
3490 
3491 	if (GRAPHICS_VER(engine->i915) < 11) {
3492 		const u8 irq_shifts[] = {
3493 			[RCS0]  = GEN8_RCS_IRQ_SHIFT,
3494 			[BCS0]  = GEN8_BCS_IRQ_SHIFT,
3495 			[VCS0]  = GEN8_VCS0_IRQ_SHIFT,
3496 			[VCS1]  = GEN8_VCS1_IRQ_SHIFT,
3497 			[VECS0] = GEN8_VECS_IRQ_SHIFT,
3498 		};
3499 
3500 		shift = irq_shifts[engine->id];
3501 	}
3502 
3503 	engine->irq_enable_mask = GT_RENDER_USER_INTERRUPT << shift;
3504 	engine->irq_keep_mask = GT_CONTEXT_SWITCH_INTERRUPT << shift;
3505 	engine->irq_keep_mask |= GT_CS_MASTER_ERROR_INTERRUPT << shift;
3506 	engine->irq_keep_mask |= GT_WAIT_SEMAPHORE_INTERRUPT << shift;
3507 }
3508 
rcs_submission_override(struct intel_engine_cs * engine)3509 static void rcs_submission_override(struct intel_engine_cs *engine)
3510 {
3511 	switch (GRAPHICS_VER(engine->i915)) {
3512 	case 12:
3513 		engine->emit_flush = gen12_emit_flush_rcs;
3514 		engine->emit_fini_breadcrumb = gen12_emit_fini_breadcrumb_rcs;
3515 		break;
3516 	case 11:
3517 		engine->emit_flush = gen11_emit_flush_rcs;
3518 		engine->emit_fini_breadcrumb = gen11_emit_fini_breadcrumb_rcs;
3519 		break;
3520 	default:
3521 		engine->emit_flush = gen8_emit_flush_rcs;
3522 		engine->emit_fini_breadcrumb = gen8_emit_fini_breadcrumb_rcs;
3523 		break;
3524 	}
3525 }
3526 
intel_execlists_submission_setup(struct intel_engine_cs * engine)3527 int intel_execlists_submission_setup(struct intel_engine_cs *engine)
3528 {
3529 	struct intel_engine_execlists * const execlists = &engine->execlists;
3530 	struct drm_i915_private *i915 = engine->i915;
3531 	struct intel_uncore *uncore = engine->uncore;
3532 	u32 base = engine->mmio_base;
3533 
3534 	tasklet_setup(&engine->sched_engine->tasklet, execlists_submission_tasklet);
3535 	timer_setup(&engine->execlists.timer, execlists_timeslice, 0);
3536 	timer_setup(&engine->execlists.preempt, execlists_preempt, 0);
3537 
3538 	logical_ring_default_vfuncs(engine);
3539 	logical_ring_default_irqs(engine);
3540 
3541 	seqcount_init(&engine->stats.execlists.lock);
3542 
3543 	if (engine->flags & I915_ENGINE_HAS_RCS_REG_STATE)
3544 		rcs_submission_override(engine);
3545 
3546 	lrc_init_wa_ctx(engine);
3547 
3548 	if (HAS_LOGICAL_RING_ELSQ(i915)) {
3549 		execlists->submit_reg = intel_uncore_regs(uncore) +
3550 			i915_mmio_reg_offset(RING_EXECLIST_SQ_CONTENTS(base));
3551 		execlists->ctrl_reg = intel_uncore_regs(uncore) +
3552 			i915_mmio_reg_offset(RING_EXECLIST_CONTROL(base));
3553 
3554 		engine->fw_domain = intel_uncore_forcewake_for_reg(engine->uncore,
3555 				    RING_EXECLIST_CONTROL(engine->mmio_base),
3556 				    FW_REG_WRITE);
3557 	} else {
3558 		execlists->submit_reg = intel_uncore_regs(uncore) +
3559 			i915_mmio_reg_offset(RING_ELSP(base));
3560 	}
3561 
3562 	execlists->csb_status =
3563 		(u64 *)&engine->status_page.addr[I915_HWS_CSB_BUF0_INDEX];
3564 
3565 	execlists->csb_write =
3566 		&engine->status_page.addr[INTEL_HWS_CSB_WRITE_INDEX(i915)];
3567 
3568 	if (GRAPHICS_VER(i915) < 11)
3569 		execlists->csb_size = GEN8_CSB_ENTRIES;
3570 	else
3571 		execlists->csb_size = GEN11_CSB_ENTRIES;
3572 
3573 	engine->context_tag = GENMASK(BITS_PER_LONG - 2, 0);
3574 	if (GRAPHICS_VER(engine->i915) >= 11 &&
3575 	    GRAPHICS_VER_FULL(engine->i915) < IP_VER(12, 55)) {
3576 		execlists->ccid |= engine->instance << (GEN11_ENGINE_INSTANCE_SHIFT - 32);
3577 		execlists->ccid |= engine->class << (GEN11_ENGINE_CLASS_SHIFT - 32);
3578 	}
3579 
3580 	/* Finally, take ownership and responsibility for cleanup! */
3581 	engine->sanitize = execlists_sanitize;
3582 	engine->release = execlists_release;
3583 
3584 	return 0;
3585 }
3586 
virtual_queue(struct virtual_engine * ve)3587 static struct list_head *virtual_queue(struct virtual_engine *ve)
3588 {
3589 	return &ve->base.sched_engine->default_priolist.requests;
3590 }
3591 
rcu_virtual_context_destroy(struct work_struct * wrk)3592 static void rcu_virtual_context_destroy(struct work_struct *wrk)
3593 {
3594 	struct virtual_engine *ve =
3595 		container_of(wrk, typeof(*ve), rcu.work);
3596 	unsigned int n;
3597 
3598 	GEM_BUG_ON(ve->context.inflight);
3599 
3600 	/* Preempt-to-busy may leave a stale request behind. */
3601 	if (unlikely(ve->request)) {
3602 		struct i915_request *old;
3603 
3604 		spin_lock_irq(&ve->base.sched_engine->lock);
3605 
3606 		old = fetch_and_zero(&ve->request);
3607 		if (old) {
3608 			GEM_BUG_ON(!__i915_request_is_complete(old));
3609 			__i915_request_submit(old);
3610 			i915_request_put(old);
3611 		}
3612 
3613 		spin_unlock_irq(&ve->base.sched_engine->lock);
3614 	}
3615 
3616 	/*
3617 	 * Flush the tasklet in case it is still running on another core.
3618 	 *
3619 	 * This needs to be done before we remove ourselves from the siblings'
3620 	 * rbtrees as in the case it is running in parallel, it may reinsert
3621 	 * the rb_node into a sibling.
3622 	 */
3623 	tasklet_kill(&ve->base.sched_engine->tasklet);
3624 
3625 	/* Decouple ourselves from the siblings, no more access allowed. */
3626 	for (n = 0; n < ve->num_siblings; n++) {
3627 		struct intel_engine_cs *sibling = ve->siblings[n];
3628 		struct rb_node *node = &ve->nodes[sibling->id].rb;
3629 
3630 		if (RB_EMPTY_NODE(node))
3631 			continue;
3632 
3633 		spin_lock_irq(&sibling->sched_engine->lock);
3634 
3635 		/* Detachment is lazily performed in the sched_engine->tasklet */
3636 		if (!RB_EMPTY_NODE(node))
3637 			rb_erase_cached(node, &sibling->execlists.virtual);
3638 
3639 		spin_unlock_irq(&sibling->sched_engine->lock);
3640 	}
3641 	GEM_BUG_ON(__tasklet_is_scheduled(&ve->base.sched_engine->tasklet));
3642 	GEM_BUG_ON(!list_empty(virtual_queue(ve)));
3643 
3644 	lrc_fini(&ve->context);
3645 	intel_context_fini(&ve->context);
3646 
3647 	if (ve->base.breadcrumbs)
3648 		intel_breadcrumbs_put(ve->base.breadcrumbs);
3649 	if (ve->base.sched_engine)
3650 		i915_sched_engine_put(ve->base.sched_engine);
3651 	intel_engine_free_request_pool(&ve->base);
3652 
3653 	kfree(ve);
3654 }
3655 
virtual_context_destroy(struct kref * kref)3656 static void virtual_context_destroy(struct kref *kref)
3657 {
3658 	struct virtual_engine *ve =
3659 		container_of(kref, typeof(*ve), context.ref);
3660 
3661 	GEM_BUG_ON(!list_empty(&ve->context.signals));
3662 
3663 	/*
3664 	 * When destroying the virtual engine, we have to be aware that
3665 	 * it may still be in use from an hardirq/softirq context causing
3666 	 * the resubmission of a completed request (background completion
3667 	 * due to preempt-to-busy). Before we can free the engine, we need
3668 	 * to flush the submission code and tasklets that are still potentially
3669 	 * accessing the engine. Flushing the tasklets requires process context,
3670 	 * and since we can guard the resubmit onto the engine with an RCU read
3671 	 * lock, we can delegate the free of the engine to an RCU worker.
3672 	 */
3673 	INIT_RCU_WORK(&ve->rcu, rcu_virtual_context_destroy);
3674 	queue_rcu_work(ve->context.engine->i915->unordered_wq, &ve->rcu);
3675 }
3676 
virtual_engine_initial_hint(struct virtual_engine * ve)3677 static void virtual_engine_initial_hint(struct virtual_engine *ve)
3678 {
3679 	int swp;
3680 
3681 	/*
3682 	 * Pick a random sibling on starting to help spread the load around.
3683 	 *
3684 	 * New contexts are typically created with exactly the same order
3685 	 * of siblings, and often started in batches. Due to the way we iterate
3686 	 * the array of sibling when submitting requests, sibling[0] is
3687 	 * prioritised for dequeuing. If we make sure that sibling[0] is fairly
3688 	 * randomised across the system, we also help spread the load by the
3689 	 * first engine we inspect being different each time.
3690 	 *
3691 	 * NB This does not force us to execute on this engine, it will just
3692 	 * typically be the first we inspect for submission.
3693 	 */
3694 	swp = get_random_u32_below(ve->num_siblings);
3695 	if (swp)
3696 		swap(ve->siblings[swp], ve->siblings[0]);
3697 }
3698 
virtual_context_alloc(struct intel_context * ce)3699 static int virtual_context_alloc(struct intel_context *ce)
3700 {
3701 	struct virtual_engine *ve = container_of(ce, typeof(*ve), context);
3702 
3703 	return lrc_alloc(ce, ve->siblings[0]);
3704 }
3705 
virtual_context_pre_pin(struct intel_context * ce,struct i915_gem_ww_ctx * ww,void ** vaddr)3706 static int virtual_context_pre_pin(struct intel_context *ce,
3707 				   struct i915_gem_ww_ctx *ww,
3708 				   void **vaddr)
3709 {
3710 	struct virtual_engine *ve = container_of(ce, typeof(*ve), context);
3711 
3712 	 /* Note: we must use a real engine class for setting up reg state */
3713 	return __execlists_context_pre_pin(ce, ve->siblings[0], ww, vaddr);
3714 }
3715 
virtual_context_pin(struct intel_context * ce,void * vaddr)3716 static int virtual_context_pin(struct intel_context *ce, void *vaddr)
3717 {
3718 	struct virtual_engine *ve = container_of(ce, typeof(*ve), context);
3719 
3720 	return lrc_pin(ce, ve->siblings[0], vaddr);
3721 }
3722 
virtual_context_enter(struct intel_context * ce)3723 static void virtual_context_enter(struct intel_context *ce)
3724 {
3725 	struct virtual_engine *ve = container_of(ce, typeof(*ve), context);
3726 	unsigned int n;
3727 
3728 	for (n = 0; n < ve->num_siblings; n++)
3729 		intel_engine_pm_get(ve->siblings[n]);
3730 
3731 	intel_timeline_enter(ce->timeline);
3732 }
3733 
virtual_context_exit(struct intel_context * ce)3734 static void virtual_context_exit(struct intel_context *ce)
3735 {
3736 	struct virtual_engine *ve = container_of(ce, typeof(*ve), context);
3737 	unsigned int n;
3738 
3739 	intel_timeline_exit(ce->timeline);
3740 
3741 	for (n = 0; n < ve->num_siblings; n++)
3742 		intel_engine_pm_put(ve->siblings[n]);
3743 }
3744 
3745 static struct intel_engine_cs *
virtual_get_sibling(struct intel_engine_cs * engine,unsigned int sibling)3746 virtual_get_sibling(struct intel_engine_cs *engine, unsigned int sibling)
3747 {
3748 	struct virtual_engine *ve = to_virtual_engine(engine);
3749 
3750 	if (sibling >= ve->num_siblings)
3751 		return NULL;
3752 
3753 	return ve->siblings[sibling];
3754 }
3755 
3756 static const struct intel_context_ops virtual_context_ops = {
3757 	.flags = COPS_HAS_INFLIGHT | COPS_RUNTIME_CYCLES,
3758 
3759 	.alloc = virtual_context_alloc,
3760 
3761 	.cancel_request = execlists_context_cancel_request,
3762 
3763 	.pre_pin = virtual_context_pre_pin,
3764 	.pin = virtual_context_pin,
3765 	.unpin = lrc_unpin,
3766 	.post_unpin = lrc_post_unpin,
3767 
3768 	.enter = virtual_context_enter,
3769 	.exit = virtual_context_exit,
3770 
3771 	.destroy = virtual_context_destroy,
3772 
3773 	.get_sibling = virtual_get_sibling,
3774 };
3775 
virtual_submission_mask(struct virtual_engine * ve)3776 static intel_engine_mask_t virtual_submission_mask(struct virtual_engine *ve)
3777 {
3778 	struct i915_request *rq;
3779 	intel_engine_mask_t mask;
3780 
3781 	rq = READ_ONCE(ve->request);
3782 	if (!rq)
3783 		return 0;
3784 
3785 	/* The rq is ready for submission; rq->execution_mask is now stable. */
3786 	mask = rq->execution_mask;
3787 	if (unlikely(!mask)) {
3788 		/* Invalid selection, submit to a random engine in error */
3789 		i915_request_set_error_once(rq, -ENODEV);
3790 		mask = ve->siblings[0]->mask;
3791 	}
3792 
3793 	ENGINE_TRACE(&ve->base, "rq=%llx:%lld, mask=%x, prio=%d\n",
3794 		     rq->fence.context, rq->fence.seqno,
3795 		     mask, ve->base.sched_engine->queue_priority_hint);
3796 
3797 	return mask;
3798 }
3799 
virtual_submission_tasklet(struct tasklet_struct * t)3800 static void virtual_submission_tasklet(struct tasklet_struct *t)
3801 {
3802 	struct i915_sched_engine *sched_engine =
3803 		from_tasklet(sched_engine, t, tasklet);
3804 	struct virtual_engine * const ve =
3805 		(struct virtual_engine *)sched_engine->private_data;
3806 	const int prio = READ_ONCE(sched_engine->queue_priority_hint);
3807 	intel_engine_mask_t mask;
3808 	unsigned int n;
3809 
3810 	rcu_read_lock();
3811 	mask = virtual_submission_mask(ve);
3812 	rcu_read_unlock();
3813 	if (unlikely(!mask))
3814 		return;
3815 
3816 	for (n = 0; n < ve->num_siblings; n++) {
3817 		struct intel_engine_cs *sibling = READ_ONCE(ve->siblings[n]);
3818 		struct ve_node * const node = &ve->nodes[sibling->id];
3819 		struct rb_node **parent, *rb;
3820 		bool first;
3821 
3822 		if (!READ_ONCE(ve->request))
3823 			break; /* already handled by a sibling's tasklet */
3824 
3825 		spin_lock_irq(&sibling->sched_engine->lock);
3826 
3827 		if (unlikely(!(mask & sibling->mask))) {
3828 			if (!RB_EMPTY_NODE(&node->rb)) {
3829 				rb_erase_cached(&node->rb,
3830 						&sibling->execlists.virtual);
3831 				RB_CLEAR_NODE(&node->rb);
3832 			}
3833 
3834 			goto unlock_engine;
3835 		}
3836 
3837 		if (unlikely(!RB_EMPTY_NODE(&node->rb))) {
3838 			/*
3839 			 * Cheat and avoid rebalancing the tree if we can
3840 			 * reuse this node in situ.
3841 			 */
3842 			first = rb_first_cached(&sibling->execlists.virtual) ==
3843 				&node->rb;
3844 			if (prio == node->prio || (prio > node->prio && first))
3845 				goto submit_engine;
3846 
3847 			rb_erase_cached(&node->rb, &sibling->execlists.virtual);
3848 		}
3849 
3850 		rb = NULL;
3851 		first = true;
3852 		parent = &sibling->execlists.virtual.rb_root.rb_node;
3853 		while (*parent) {
3854 			struct ve_node *other;
3855 
3856 			rb = *parent;
3857 			other = rb_entry(rb, typeof(*other), rb);
3858 			if (prio > other->prio) {
3859 				parent = &rb->rb_left;
3860 			} else {
3861 				parent = &rb->rb_right;
3862 				first = false;
3863 			}
3864 		}
3865 
3866 		rb_link_node(&node->rb, rb, parent);
3867 		rb_insert_color_cached(&node->rb,
3868 				       &sibling->execlists.virtual,
3869 				       first);
3870 
3871 submit_engine:
3872 		GEM_BUG_ON(RB_EMPTY_NODE(&node->rb));
3873 		node->prio = prio;
3874 		if (first && prio > sibling->sched_engine->queue_priority_hint)
3875 			tasklet_hi_schedule(&sibling->sched_engine->tasklet);
3876 
3877 unlock_engine:
3878 		spin_unlock_irq(&sibling->sched_engine->lock);
3879 
3880 		if (intel_context_inflight(&ve->context))
3881 			break;
3882 	}
3883 }
3884 
virtual_submit_request(struct i915_request * rq)3885 static void virtual_submit_request(struct i915_request *rq)
3886 {
3887 	struct virtual_engine *ve = to_virtual_engine(rq->engine);
3888 	unsigned long flags;
3889 
3890 	ENGINE_TRACE(&ve->base, "rq=%llx:%lld\n",
3891 		     rq->fence.context,
3892 		     rq->fence.seqno);
3893 
3894 	GEM_BUG_ON(ve->base.submit_request != virtual_submit_request);
3895 
3896 	spin_lock_irqsave(&ve->base.sched_engine->lock, flags);
3897 
3898 	/* By the time we resubmit a request, it may be completed */
3899 	if (__i915_request_is_complete(rq)) {
3900 		__i915_request_submit(rq);
3901 		goto unlock;
3902 	}
3903 
3904 	if (ve->request) { /* background completion from preempt-to-busy */
3905 		GEM_BUG_ON(!__i915_request_is_complete(ve->request));
3906 		__i915_request_submit(ve->request);
3907 		i915_request_put(ve->request);
3908 	}
3909 
3910 	ve->base.sched_engine->queue_priority_hint = rq_prio(rq);
3911 	ve->request = i915_request_get(rq);
3912 
3913 	GEM_BUG_ON(!list_empty(virtual_queue(ve)));
3914 	list_move_tail(&rq->sched.link, virtual_queue(ve));
3915 
3916 	tasklet_hi_schedule(&ve->base.sched_engine->tasklet);
3917 
3918 unlock:
3919 	spin_unlock_irqrestore(&ve->base.sched_engine->lock, flags);
3920 }
3921 
3922 static struct intel_context *
execlists_create_virtual(struct intel_engine_cs ** siblings,unsigned int count,unsigned long flags)3923 execlists_create_virtual(struct intel_engine_cs **siblings, unsigned int count,
3924 			 unsigned long flags)
3925 {
3926 	struct drm_i915_private *i915 = siblings[0]->i915;
3927 	struct virtual_engine *ve;
3928 	unsigned int n;
3929 	int err;
3930 
3931 	ve = kzalloc(struct_size(ve, siblings, count), GFP_KERNEL);
3932 	if (!ve)
3933 		return ERR_PTR(-ENOMEM);
3934 
3935 	ve->base.i915 = i915;
3936 	ve->base.gt = siblings[0]->gt;
3937 	ve->base.uncore = siblings[0]->uncore;
3938 	ve->base.id = -1;
3939 
3940 	ve->base.class = OTHER_CLASS;
3941 	ve->base.uabi_class = I915_ENGINE_CLASS_INVALID;
3942 	ve->base.instance = I915_ENGINE_CLASS_INVALID_VIRTUAL;
3943 	ve->base.uabi_instance = I915_ENGINE_CLASS_INVALID_VIRTUAL;
3944 
3945 	/*
3946 	 * The decision on whether to submit a request using semaphores
3947 	 * depends on the saturated state of the engine. We only compute
3948 	 * this during HW submission of the request, and we need for this
3949 	 * state to be globally applied to all requests being submitted
3950 	 * to this engine. Virtual engines encompass more than one physical
3951 	 * engine and so we cannot accurately tell in advance if one of those
3952 	 * engines is already saturated and so cannot afford to use a semaphore
3953 	 * and be pessimized in priority for doing so -- if we are the only
3954 	 * context using semaphores after all other clients have stopped, we
3955 	 * will be starved on the saturated system. Such a global switch for
3956 	 * semaphores is less than ideal, but alas is the current compromise.
3957 	 */
3958 	ve->base.saturated = ALL_ENGINES;
3959 
3960 	snprintf(ve->base.name, sizeof(ve->base.name), "virtual");
3961 
3962 	intel_engine_init_execlists(&ve->base);
3963 
3964 	ve->base.sched_engine = i915_sched_engine_create(ENGINE_VIRTUAL);
3965 	if (!ve->base.sched_engine) {
3966 		err = -ENOMEM;
3967 		goto err_put;
3968 	}
3969 	ve->base.sched_engine->private_data = &ve->base;
3970 
3971 	ve->base.cops = &virtual_context_ops;
3972 	ve->base.request_alloc = execlists_request_alloc;
3973 
3974 	ve->base.sched_engine->schedule = i915_schedule;
3975 	ve->base.sched_engine->kick_backend = kick_execlists;
3976 	ve->base.submit_request = virtual_submit_request;
3977 
3978 	INIT_LIST_HEAD(virtual_queue(ve));
3979 	tasklet_setup(&ve->base.sched_engine->tasklet, virtual_submission_tasklet);
3980 
3981 	intel_context_init(&ve->context, &ve->base);
3982 
3983 	ve->base.breadcrumbs = intel_breadcrumbs_create(NULL);
3984 	if (!ve->base.breadcrumbs) {
3985 		err = -ENOMEM;
3986 		goto err_put;
3987 	}
3988 
3989 	for (n = 0; n < count; n++) {
3990 		struct intel_engine_cs *sibling = siblings[n];
3991 
3992 		GEM_BUG_ON(!is_power_of_2(sibling->mask));
3993 		if (sibling->mask & ve->base.mask) {
3994 			drm_dbg(&i915->drm,
3995 				"duplicate %s entry in load balancer\n",
3996 				sibling->name);
3997 			err = -EINVAL;
3998 			goto err_put;
3999 		}
4000 
4001 		/*
4002 		 * The virtual engine implementation is tightly coupled to
4003 		 * the execlists backend -- we push out request directly
4004 		 * into a tree inside each physical engine. We could support
4005 		 * layering if we handle cloning of the requests and
4006 		 * submitting a copy into each backend.
4007 		 */
4008 		if (sibling->sched_engine->tasklet.callback !=
4009 		    execlists_submission_tasklet) {
4010 			err = -ENODEV;
4011 			goto err_put;
4012 		}
4013 
4014 		GEM_BUG_ON(RB_EMPTY_NODE(&ve->nodes[sibling->id].rb));
4015 		RB_CLEAR_NODE(&ve->nodes[sibling->id].rb);
4016 
4017 		ve->siblings[ve->num_siblings++] = sibling;
4018 		ve->base.mask |= sibling->mask;
4019 		ve->base.logical_mask |= sibling->logical_mask;
4020 
4021 		/*
4022 		 * All physical engines must be compatible for their emission
4023 		 * functions (as we build the instructions during request
4024 		 * construction and do not alter them before submission
4025 		 * on the physical engine). We use the engine class as a guide
4026 		 * here, although that could be refined.
4027 		 */
4028 		if (ve->base.class != OTHER_CLASS) {
4029 			if (ve->base.class != sibling->class) {
4030 				drm_dbg(&i915->drm,
4031 					"invalid mixing of engine class, sibling %d, already %d\n",
4032 					sibling->class, ve->base.class);
4033 				err = -EINVAL;
4034 				goto err_put;
4035 			}
4036 			continue;
4037 		}
4038 
4039 		ve->base.class = sibling->class;
4040 		ve->base.uabi_class = sibling->uabi_class;
4041 		snprintf(ve->base.name, sizeof(ve->base.name),
4042 			 "v%dx%d", ve->base.class, count);
4043 		ve->base.context_size = sibling->context_size;
4044 
4045 		ve->base.add_active_request = sibling->add_active_request;
4046 		ve->base.remove_active_request = sibling->remove_active_request;
4047 		ve->base.emit_bb_start = sibling->emit_bb_start;
4048 		ve->base.emit_flush = sibling->emit_flush;
4049 		ve->base.emit_init_breadcrumb = sibling->emit_init_breadcrumb;
4050 		ve->base.emit_fini_breadcrumb = sibling->emit_fini_breadcrumb;
4051 		ve->base.emit_fini_breadcrumb_dw =
4052 			sibling->emit_fini_breadcrumb_dw;
4053 
4054 		ve->base.flags = sibling->flags;
4055 	}
4056 
4057 	ve->base.flags |= I915_ENGINE_IS_VIRTUAL;
4058 
4059 	virtual_engine_initial_hint(ve);
4060 	return &ve->context;
4061 
4062 err_put:
4063 	intel_context_put(&ve->context);
4064 	return ERR_PTR(err);
4065 }
4066 
intel_execlists_show_requests(struct intel_engine_cs * engine,struct drm_printer * m,void (* show_request)(struct drm_printer * m,const struct i915_request * rq,const char * prefix,int indent),unsigned int max)4067 void intel_execlists_show_requests(struct intel_engine_cs *engine,
4068 				   struct drm_printer *m,
4069 				   void (*show_request)(struct drm_printer *m,
4070 							const struct i915_request *rq,
4071 							const char *prefix,
4072 							int indent),
4073 				   unsigned int max)
4074 {
4075 	const struct intel_engine_execlists *execlists = &engine->execlists;
4076 	struct i915_sched_engine *sched_engine = engine->sched_engine;
4077 	struct i915_request *rq, *last;
4078 	unsigned long flags;
4079 	unsigned int count;
4080 	struct rb_node *rb;
4081 
4082 	spin_lock_irqsave(&sched_engine->lock, flags);
4083 
4084 	last = NULL;
4085 	count = 0;
4086 	list_for_each_entry(rq, &sched_engine->requests, sched.link) {
4087 		if (count++ < max - 1)
4088 			show_request(m, rq, "\t\t", 0);
4089 		else
4090 			last = rq;
4091 	}
4092 	if (last) {
4093 		if (count > max) {
4094 			drm_printf(m,
4095 				   "\t\t...skipping %d executing requests...\n",
4096 				   count - max);
4097 		}
4098 		show_request(m, last, "\t\t", 0);
4099 	}
4100 
4101 	if (sched_engine->queue_priority_hint != INT_MIN)
4102 		drm_printf(m, "\t\tQueue priority hint: %d\n",
4103 			   READ_ONCE(sched_engine->queue_priority_hint));
4104 
4105 	last = NULL;
4106 	count = 0;
4107 	for (rb = rb_first_cached(&sched_engine->queue); rb; rb = rb_next(rb)) {
4108 		struct i915_priolist *p = rb_entry(rb, typeof(*p), node);
4109 
4110 		priolist_for_each_request(rq, p) {
4111 			if (count++ < max - 1)
4112 				show_request(m, rq, "\t\t", 0);
4113 			else
4114 				last = rq;
4115 		}
4116 	}
4117 	if (last) {
4118 		if (count > max) {
4119 			drm_printf(m,
4120 				   "\t\t...skipping %d queued requests...\n",
4121 				   count - max);
4122 		}
4123 		show_request(m, last, "\t\t", 0);
4124 	}
4125 
4126 	last = NULL;
4127 	count = 0;
4128 	for (rb = rb_first_cached(&execlists->virtual); rb; rb = rb_next(rb)) {
4129 		struct virtual_engine *ve =
4130 			rb_entry(rb, typeof(*ve), nodes[engine->id].rb);
4131 		struct i915_request *rq = READ_ONCE(ve->request);
4132 
4133 		if (rq) {
4134 			if (count++ < max - 1)
4135 				show_request(m, rq, "\t\t", 0);
4136 			else
4137 				last = rq;
4138 		}
4139 	}
4140 	if (last) {
4141 		if (count > max) {
4142 			drm_printf(m,
4143 				   "\t\t...skipping %d virtual requests...\n",
4144 				   count - max);
4145 		}
4146 		show_request(m, last, "\t\t", 0);
4147 	}
4148 
4149 	spin_unlock_irqrestore(&sched_engine->lock, flags);
4150 }
4151 
intel_execlists_dump_active_requests(struct intel_engine_cs * engine,struct i915_request * hung_rq,struct drm_printer * m)4152 void intel_execlists_dump_active_requests(struct intel_engine_cs *engine,
4153 					  struct i915_request *hung_rq,
4154 					  struct drm_printer *m)
4155 {
4156 	unsigned long flags;
4157 
4158 	spin_lock_irqsave(&engine->sched_engine->lock, flags);
4159 
4160 	intel_engine_dump_active_requests(&engine->sched_engine->requests, hung_rq, m);
4161 
4162 	drm_printf(m, "\tOn hold?: %zu\n",
4163 		   list_count_nodes(&engine->sched_engine->hold));
4164 
4165 	spin_unlock_irqrestore(&engine->sched_engine->lock, flags);
4166 }
4167 
4168 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
4169 #include "selftest_execlists.c"
4170 #endif
4171