xref: /linux/drivers/gpu/drm/i915/gt/intel_lrc.c (revision ebf68996de0ab250c5d520eb2291ab65643e9a1e)
1 /*
2  * Copyright © 2014 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  *
23  * Authors:
24  *    Ben Widawsky <ben@bwidawsk.net>
25  *    Michel Thierry <michel.thierry@intel.com>
26  *    Thomas Daniel <thomas.daniel@intel.com>
27  *    Oscar Mateo <oscar.mateo@intel.com>
28  *
29  */
30 
31 /**
32  * DOC: Logical Rings, Logical Ring Contexts and Execlists
33  *
34  * Motivation:
35  * GEN8 brings an expansion of the HW contexts: "Logical Ring Contexts".
36  * These expanded contexts enable a number of new abilities, especially
37  * "Execlists" (also implemented in this file).
38  *
39  * One of the main differences with the legacy HW contexts is that logical
40  * ring contexts incorporate many more things to the context's state, like
41  * PDPs or ringbuffer control registers:
42  *
43  * The reason why PDPs are included in the context is straightforward: as
44  * PPGTTs (per-process GTTs) are actually per-context, having the PDPs
45  * contained there mean you don't need to do a ppgtt->switch_mm yourself,
46  * instead, the GPU will do it for you on the context switch.
47  *
48  * But, what about the ringbuffer control registers (head, tail, etc..)?
49  * shouldn't we just need a set of those per engine command streamer? This is
50  * where the name "Logical Rings" starts to make sense: by virtualizing the
51  * rings, the engine cs shifts to a new "ring buffer" with every context
52  * switch. When you want to submit a workload to the GPU you: A) choose your
53  * context, B) find its appropriate virtualized ring, C) write commands to it
54  * and then, finally, D) tell the GPU to switch to that context.
55  *
56  * Instead of the legacy MI_SET_CONTEXT, the way you tell the GPU to switch
57  * to a contexts is via a context execution list, ergo "Execlists".
58  *
59  * LRC implementation:
60  * Regarding the creation of contexts, we have:
61  *
62  * - One global default context.
63  * - One local default context for each opened fd.
64  * - One local extra context for each context create ioctl call.
65  *
66  * Now that ringbuffers belong per-context (and not per-engine, like before)
67  * and that contexts are uniquely tied to a given engine (and not reusable,
68  * like before) we need:
69  *
70  * - One ringbuffer per-engine inside each context.
71  * - One backing object per-engine inside each context.
72  *
73  * The global default context starts its life with these new objects fully
74  * allocated and populated. The local default context for each opened fd is
75  * more complex, because we don't know at creation time which engine is going
76  * to use them. To handle this, we have implemented a deferred creation of LR
77  * contexts:
78  *
79  * The local context starts its life as a hollow or blank holder, that only
80  * gets populated for a given engine once we receive an execbuffer. If later
81  * on we receive another execbuffer ioctl for the same context but a different
82  * engine, we allocate/populate a new ringbuffer and context backing object and
83  * so on.
84  *
85  * Finally, regarding local contexts created using the ioctl call: as they are
86  * only allowed with the render ring, we can allocate & populate them right
87  * away (no need to defer anything, at least for now).
88  *
89  * Execlists implementation:
90  * Execlists are the new method by which, on gen8+ hardware, workloads are
91  * submitted for execution (as opposed to the legacy, ringbuffer-based, method).
92  * This method works as follows:
93  *
94  * When a request is committed, its commands (the BB start and any leading or
95  * trailing commands, like the seqno breadcrumbs) are placed in the ringbuffer
96  * for the appropriate context. The tail pointer in the hardware context is not
97  * updated at this time, but instead, kept by the driver in the ringbuffer
98  * structure. A structure representing this request is added to a request queue
99  * for the appropriate engine: this structure contains a copy of the context's
100  * tail after the request was written to the ring buffer and a pointer to the
101  * context itself.
102  *
103  * If the engine's request queue was empty before the request was added, the
104  * queue is processed immediately. Otherwise the queue will be processed during
105  * a context switch interrupt. In any case, elements on the queue will get sent
106  * (in pairs) to the GPU's ExecLists Submit Port (ELSP, for short) with a
107  * globally unique 20-bits submission ID.
108  *
109  * When execution of a request completes, the GPU updates the context status
110  * buffer with a context complete event and generates a context switch interrupt.
111  * During the interrupt handling, the driver examines the events in the buffer:
112  * for each context complete event, if the announced ID matches that on the head
113  * of the request queue, then that request is retired and removed from the queue.
114  *
115  * After processing, if any requests were retired and the queue is not empty
116  * then a new execution list can be submitted. The two requests at the front of
117  * the queue are next to be submitted but since a context may not occur twice in
118  * an execution list, if subsequent requests have the same ID as the first then
119  * the two requests must be combined. This is done simply by discarding requests
120  * at the head of the queue until either only one requests is left (in which case
121  * we use a NULL second context) or the first two requests have unique IDs.
122  *
123  * By always executing the first two requests in the queue the driver ensures
124  * that the GPU is kept as busy as possible. In the case where a single context
125  * completes but a second context is still executing, the request for this second
126  * context will be at the head of the queue when we remove the first one. This
127  * request will then be resubmitted along with a new request for a different context,
128  * which will cause the hardware to continue executing the second request and queue
129  * the new request (the GPU detects the condition of a context getting preempted
130  * with the same context and optimizes the context switch flow by not doing
131  * preemption, but just sampling the new tail pointer).
132  *
133  */
134 #include <linux/interrupt.h>
135 
136 #include "i915_drv.h"
137 #include "i915_gem_render_state.h"
138 #include "i915_vgpu.h"
139 #include "intel_engine_pm.h"
140 #include "intel_lrc_reg.h"
141 #include "intel_mocs.h"
142 #include "intel_reset.h"
143 #include "intel_workarounds.h"
144 
145 #define RING_EXECLIST_QFULL		(1 << 0x2)
146 #define RING_EXECLIST1_VALID		(1 << 0x3)
147 #define RING_EXECLIST0_VALID		(1 << 0x4)
148 #define RING_EXECLIST_ACTIVE_STATUS	(3 << 0xE)
149 #define RING_EXECLIST1_ACTIVE		(1 << 0x11)
150 #define RING_EXECLIST0_ACTIVE		(1 << 0x12)
151 
152 #define GEN8_CTX_STATUS_IDLE_ACTIVE	(1 << 0)
153 #define GEN8_CTX_STATUS_PREEMPTED	(1 << 1)
154 #define GEN8_CTX_STATUS_ELEMENT_SWITCH	(1 << 2)
155 #define GEN8_CTX_STATUS_ACTIVE_IDLE	(1 << 3)
156 #define GEN8_CTX_STATUS_COMPLETE	(1 << 4)
157 #define GEN8_CTX_STATUS_LITE_RESTORE	(1 << 15)
158 
159 #define GEN8_CTX_STATUS_COMPLETED_MASK \
160 	 (GEN8_CTX_STATUS_COMPLETE | GEN8_CTX_STATUS_PREEMPTED)
161 
162 /* Typical size of the average request (2 pipecontrols and a MI_BB) */
163 #define EXECLISTS_REQUEST_SIZE 64 /* bytes */
164 #define WA_TAIL_DWORDS 2
165 #define WA_TAIL_BYTES (sizeof(u32) * WA_TAIL_DWORDS)
166 
167 struct virtual_engine {
168 	struct intel_engine_cs base;
169 	struct intel_context context;
170 
171 	/*
172 	 * We allow only a single request through the virtual engine at a time
173 	 * (each request in the timeline waits for the completion fence of
174 	 * the previous before being submitted). By restricting ourselves to
175 	 * only submitting a single request, each request is placed on to a
176 	 * physical to maximise load spreading (by virtue of the late greedy
177 	 * scheduling -- each real engine takes the next available request
178 	 * upon idling).
179 	 */
180 	struct i915_request *request;
181 
182 	/*
183 	 * We keep a rbtree of available virtual engines inside each physical
184 	 * engine, sorted by priority. Here we preallocate the nodes we need
185 	 * for the virtual engine, indexed by physical_engine->id.
186 	 */
187 	struct ve_node {
188 		struct rb_node rb;
189 		int prio;
190 	} nodes[I915_NUM_ENGINES];
191 
192 	/*
193 	 * Keep track of bonded pairs -- restrictions upon on our selection
194 	 * of physical engines any particular request may be submitted to.
195 	 * If we receive a submit-fence from a master engine, we will only
196 	 * use one of sibling_mask physical engines.
197 	 */
198 	struct ve_bond {
199 		const struct intel_engine_cs *master;
200 		intel_engine_mask_t sibling_mask;
201 	} *bonds;
202 	unsigned int num_bonds;
203 
204 	/* And finally, which physical engines this virtual engine maps onto. */
205 	unsigned int num_siblings;
206 	struct intel_engine_cs *siblings[0];
207 };
208 
209 static struct virtual_engine *to_virtual_engine(struct intel_engine_cs *engine)
210 {
211 	GEM_BUG_ON(!intel_engine_is_virtual(engine));
212 	return container_of(engine, struct virtual_engine, base);
213 }
214 
215 static int execlists_context_deferred_alloc(struct intel_context *ce,
216 					    struct intel_engine_cs *engine);
217 static void execlists_init_reg_state(u32 *reg_state,
218 				     struct intel_context *ce,
219 				     struct intel_engine_cs *engine,
220 				     struct intel_ring *ring);
221 
222 static inline struct i915_priolist *to_priolist(struct rb_node *rb)
223 {
224 	return rb_entry(rb, struct i915_priolist, node);
225 }
226 
227 static inline int rq_prio(const struct i915_request *rq)
228 {
229 	return rq->sched.attr.priority;
230 }
231 
232 static int effective_prio(const struct i915_request *rq)
233 {
234 	int prio = rq_prio(rq);
235 
236 	/*
237 	 * On unwinding the active request, we give it a priority bump
238 	 * if it has completed waiting on any semaphore. If we know that
239 	 * the request has already started, we can prevent an unwanted
240 	 * preempt-to-idle cycle by taking that into account now.
241 	 */
242 	if (__i915_request_has_started(rq))
243 		prio |= I915_PRIORITY_NOSEMAPHORE;
244 
245 	/* Restrict mere WAIT boosts from triggering preemption */
246 	return prio | __NO_PREEMPTION;
247 }
248 
249 static int queue_prio(const struct intel_engine_execlists *execlists)
250 {
251 	struct i915_priolist *p;
252 	struct rb_node *rb;
253 
254 	rb = rb_first_cached(&execlists->queue);
255 	if (!rb)
256 		return INT_MIN;
257 
258 	/*
259 	 * As the priolist[] are inverted, with the highest priority in [0],
260 	 * we have to flip the index value to become priority.
261 	 */
262 	p = to_priolist(rb);
263 	return ((p->priority + 1) << I915_USER_PRIORITY_SHIFT) - ffs(p->used);
264 }
265 
266 static inline bool need_preempt(const struct intel_engine_cs *engine,
267 				const struct i915_request *rq,
268 				struct rb_node *rb)
269 {
270 	int last_prio;
271 
272 	if (!engine->preempt_context)
273 		return false;
274 
275 	if (i915_request_completed(rq))
276 		return false;
277 
278 	/*
279 	 * Check if the current priority hint merits a preemption attempt.
280 	 *
281 	 * We record the highest value priority we saw during rescheduling
282 	 * prior to this dequeue, therefore we know that if it is strictly
283 	 * less than the current tail of ESLP[0], we do not need to force
284 	 * a preempt-to-idle cycle.
285 	 *
286 	 * However, the priority hint is a mere hint that we may need to
287 	 * preempt. If that hint is stale or we may be trying to preempt
288 	 * ourselves, ignore the request.
289 	 */
290 	last_prio = effective_prio(rq);
291 	if (!i915_scheduler_need_preempt(engine->execlists.queue_priority_hint,
292 					 last_prio))
293 		return false;
294 
295 	/*
296 	 * Check against the first request in ELSP[1], it will, thanks to the
297 	 * power of PI, be the highest priority of that context.
298 	 */
299 	if (!list_is_last(&rq->link, &engine->timeline.requests) &&
300 	    rq_prio(list_next_entry(rq, link)) > last_prio)
301 		return true;
302 
303 	if (rb) {
304 		struct virtual_engine *ve =
305 			rb_entry(rb, typeof(*ve), nodes[engine->id].rb);
306 		bool preempt = false;
307 
308 		if (engine == ve->siblings[0]) { /* only preempt one sibling */
309 			struct i915_request *next;
310 
311 			rcu_read_lock();
312 			next = READ_ONCE(ve->request);
313 			if (next)
314 				preempt = rq_prio(next) > last_prio;
315 			rcu_read_unlock();
316 		}
317 
318 		if (preempt)
319 			return preempt;
320 	}
321 
322 	/*
323 	 * If the inflight context did not trigger the preemption, then maybe
324 	 * it was the set of queued requests? Pick the highest priority in
325 	 * the queue (the first active priolist) and see if it deserves to be
326 	 * running instead of ELSP[0].
327 	 *
328 	 * The highest priority request in the queue can not be either
329 	 * ELSP[0] or ELSP[1] as, thanks again to PI, if it was the same
330 	 * context, it's priority would not exceed ELSP[0] aka last_prio.
331 	 */
332 	return queue_prio(&engine->execlists) > last_prio;
333 }
334 
335 __maybe_unused static inline bool
336 assert_priority_queue(const struct i915_request *prev,
337 		      const struct i915_request *next)
338 {
339 	const struct intel_engine_execlists *execlists =
340 		&prev->engine->execlists;
341 
342 	/*
343 	 * Without preemption, the prev may refer to the still active element
344 	 * which we refuse to let go.
345 	 *
346 	 * Even with preemption, there are times when we think it is better not
347 	 * to preempt and leave an ostensibly lower priority request in flight.
348 	 */
349 	if (port_request(execlists->port) == prev)
350 		return true;
351 
352 	return rq_prio(prev) >= rq_prio(next);
353 }
354 
355 /*
356  * The context descriptor encodes various attributes of a context,
357  * including its GTT address and some flags. Because it's fairly
358  * expensive to calculate, we'll just do it once and cache the result,
359  * which remains valid until the context is unpinned.
360  *
361  * This is what a descriptor looks like, from LSB to MSB::
362  *
363  *      bits  0-11:    flags, GEN8_CTX_* (cached in ctx->desc_template)
364  *      bits 12-31:    LRCA, GTT address of (the HWSP of) this context
365  *      bits 32-52:    ctx ID, a globally unique tag (highest bit used by GuC)
366  *      bits 53-54:    mbz, reserved for use by hardware
367  *      bits 55-63:    group ID, currently unused and set to 0
368  *
369  * Starting from Gen11, the upper dword of the descriptor has a new format:
370  *
371  *      bits 32-36:    reserved
372  *      bits 37-47:    SW context ID
373  *      bits 48:53:    engine instance
374  *      bit 54:        mbz, reserved for use by hardware
375  *      bits 55-60:    SW counter
376  *      bits 61-63:    engine class
377  *
378  * engine info, SW context ID and SW counter need to form a unique number
379  * (Context ID) per lrc.
380  */
381 static u64
382 lrc_descriptor(struct intel_context *ce, struct intel_engine_cs *engine)
383 {
384 	struct i915_gem_context *ctx = ce->gem_context;
385 	u64 desc;
386 
387 	BUILD_BUG_ON(MAX_CONTEXT_HW_ID > (BIT(GEN8_CTX_ID_WIDTH)));
388 	BUILD_BUG_ON(GEN11_MAX_CONTEXT_HW_ID > (BIT(GEN11_SW_CTX_ID_WIDTH)));
389 
390 	desc = ctx->desc_template;				/* bits  0-11 */
391 	GEM_BUG_ON(desc & GENMASK_ULL(63, 12));
392 
393 	desc |= i915_ggtt_offset(ce->state) + LRC_HEADER_PAGES * PAGE_SIZE;
394 								/* bits 12-31 */
395 	GEM_BUG_ON(desc & GENMASK_ULL(63, 32));
396 
397 	/*
398 	 * The following 32bits are copied into the OA reports (dword 2).
399 	 * Consider updating oa_get_render_ctx_id in i915_perf.c when changing
400 	 * anything below.
401 	 */
402 	if (INTEL_GEN(engine->i915) >= 11) {
403 		GEM_BUG_ON(ctx->hw_id >= BIT(GEN11_SW_CTX_ID_WIDTH));
404 		desc |= (u64)ctx->hw_id << GEN11_SW_CTX_ID_SHIFT;
405 								/* bits 37-47 */
406 
407 		desc |= (u64)engine->instance << GEN11_ENGINE_INSTANCE_SHIFT;
408 								/* bits 48-53 */
409 
410 		/* TODO: decide what to do with SW counter (bits 55-60) */
411 
412 		desc |= (u64)engine->class << GEN11_ENGINE_CLASS_SHIFT;
413 								/* bits 61-63 */
414 	} else {
415 		GEM_BUG_ON(ctx->hw_id >= BIT(GEN8_CTX_ID_WIDTH));
416 		desc |= (u64)ctx->hw_id << GEN8_CTX_ID_SHIFT;	/* bits 32-52 */
417 	}
418 
419 	return desc;
420 }
421 
422 static void unwind_wa_tail(struct i915_request *rq)
423 {
424 	rq->tail = intel_ring_wrap(rq->ring, rq->wa_tail - WA_TAIL_BYTES);
425 	assert_ring_tail_valid(rq->ring, rq->tail);
426 }
427 
428 static struct i915_request *
429 __unwind_incomplete_requests(struct intel_engine_cs *engine)
430 {
431 	struct i915_request *rq, *rn, *active = NULL;
432 	struct list_head *uninitialized_var(pl);
433 	int prio = I915_PRIORITY_INVALID;
434 
435 	lockdep_assert_held(&engine->timeline.lock);
436 
437 	list_for_each_entry_safe_reverse(rq, rn,
438 					 &engine->timeline.requests,
439 					 link) {
440 		struct intel_engine_cs *owner;
441 
442 		if (i915_request_completed(rq))
443 			break;
444 
445 		__i915_request_unsubmit(rq);
446 		unwind_wa_tail(rq);
447 
448 		GEM_BUG_ON(rq->hw_context->active);
449 
450 		/*
451 		 * Push the request back into the queue for later resubmission.
452 		 * If this request is not native to this physical engine (i.e.
453 		 * it came from a virtual source), push it back onto the virtual
454 		 * engine so that it can be moved across onto another physical
455 		 * engine as load dictates.
456 		 */
457 		owner = rq->hw_context->engine;
458 		if (likely(owner == engine)) {
459 			GEM_BUG_ON(rq_prio(rq) == I915_PRIORITY_INVALID);
460 			if (rq_prio(rq) != prio) {
461 				prio = rq_prio(rq);
462 				pl = i915_sched_lookup_priolist(engine, prio);
463 			}
464 			GEM_BUG_ON(RB_EMPTY_ROOT(&engine->execlists.queue.rb_root));
465 
466 			list_add(&rq->sched.link, pl);
467 			active = rq;
468 		} else {
469 			rq->engine = owner;
470 			owner->submit_request(rq);
471 			active = NULL;
472 		}
473 	}
474 
475 	return active;
476 }
477 
478 struct i915_request *
479 execlists_unwind_incomplete_requests(struct intel_engine_execlists *execlists)
480 {
481 	struct intel_engine_cs *engine =
482 		container_of(execlists, typeof(*engine), execlists);
483 
484 	return __unwind_incomplete_requests(engine);
485 }
486 
487 static inline void
488 execlists_context_status_change(struct i915_request *rq, unsigned long status)
489 {
490 	/*
491 	 * Only used when GVT-g is enabled now. When GVT-g is disabled,
492 	 * The compiler should eliminate this function as dead-code.
493 	 */
494 	if (!IS_ENABLED(CONFIG_DRM_I915_GVT))
495 		return;
496 
497 	atomic_notifier_call_chain(&rq->engine->context_status_notifier,
498 				   status, rq);
499 }
500 
501 inline void
502 execlists_user_begin(struct intel_engine_execlists *execlists,
503 		     const struct execlist_port *port)
504 {
505 	execlists_set_active_once(execlists, EXECLISTS_ACTIVE_USER);
506 }
507 
508 inline void
509 execlists_user_end(struct intel_engine_execlists *execlists)
510 {
511 	execlists_clear_active(execlists, EXECLISTS_ACTIVE_USER);
512 }
513 
514 static inline void
515 execlists_context_schedule_in(struct i915_request *rq)
516 {
517 	GEM_BUG_ON(rq->hw_context->active);
518 
519 	execlists_context_status_change(rq, INTEL_CONTEXT_SCHEDULE_IN);
520 	intel_engine_context_in(rq->engine);
521 	rq->hw_context->active = rq->engine;
522 }
523 
524 static void kick_siblings(struct i915_request *rq)
525 {
526 	struct virtual_engine *ve = to_virtual_engine(rq->hw_context->engine);
527 	struct i915_request *next = READ_ONCE(ve->request);
528 
529 	if (next && next->execution_mask & ~rq->execution_mask)
530 		tasklet_schedule(&ve->base.execlists.tasklet);
531 }
532 
533 static inline void
534 execlists_context_schedule_out(struct i915_request *rq, unsigned long status)
535 {
536 	rq->hw_context->active = NULL;
537 	intel_engine_context_out(rq->engine);
538 	execlists_context_status_change(rq, status);
539 	trace_i915_request_out(rq);
540 
541 	/*
542 	 * If this is part of a virtual engine, its next request may have
543 	 * been blocked waiting for access to the active context. We have
544 	 * to kick all the siblings again in case we need to switch (e.g.
545 	 * the next request is not runnable on this engine). Hopefully,
546 	 * we will already have submitted the next request before the
547 	 * tasklet runs and do not need to rebuild each virtual tree
548 	 * and kick everyone again.
549 	 */
550 	if (rq->engine != rq->hw_context->engine)
551 		kick_siblings(rq);
552 }
553 
554 static u64 execlists_update_context(struct i915_request *rq)
555 {
556 	struct intel_context *ce = rq->hw_context;
557 
558 	ce->lrc_reg_state[CTX_RING_TAIL + 1] =
559 		intel_ring_set_tail(rq->ring, rq->tail);
560 
561 	/*
562 	 * Make sure the context image is complete before we submit it to HW.
563 	 *
564 	 * Ostensibly, writes (including the WCB) should be flushed prior to
565 	 * an uncached write such as our mmio register access, the empirical
566 	 * evidence (esp. on Braswell) suggests that the WC write into memory
567 	 * may not be visible to the HW prior to the completion of the UC
568 	 * register write and that we may begin execution from the context
569 	 * before its image is complete leading to invalid PD chasing.
570 	 *
571 	 * Furthermore, Braswell, at least, wants a full mb to be sure that
572 	 * the writes are coherent in memory (visible to the GPU) prior to
573 	 * execution, and not just visible to other CPUs (as is the result of
574 	 * wmb).
575 	 */
576 	mb();
577 	return ce->lrc_desc;
578 }
579 
580 static inline void write_desc(struct intel_engine_execlists *execlists, u64 desc, u32 port)
581 {
582 	if (execlists->ctrl_reg) {
583 		writel(lower_32_bits(desc), execlists->submit_reg + port * 2);
584 		writel(upper_32_bits(desc), execlists->submit_reg + port * 2 + 1);
585 	} else {
586 		writel(upper_32_bits(desc), execlists->submit_reg);
587 		writel(lower_32_bits(desc), execlists->submit_reg);
588 	}
589 }
590 
591 static void execlists_submit_ports(struct intel_engine_cs *engine)
592 {
593 	struct intel_engine_execlists *execlists = &engine->execlists;
594 	struct execlist_port *port = execlists->port;
595 	unsigned int n;
596 
597 	/*
598 	 * We can skip acquiring intel_runtime_pm_get() here as it was taken
599 	 * on our behalf by the request (see i915_gem_mark_busy()) and it will
600 	 * not be relinquished until the device is idle (see
601 	 * i915_gem_idle_work_handler()). As a precaution, we make sure
602 	 * that all ELSP are drained i.e. we have processed the CSB,
603 	 * before allowing ourselves to idle and calling intel_runtime_pm_put().
604 	 */
605 	GEM_BUG_ON(!intel_wakeref_active(&engine->wakeref));
606 
607 	/*
608 	 * ELSQ note: the submit queue is not cleared after being submitted
609 	 * to the HW so we need to make sure we always clean it up. This is
610 	 * currently ensured by the fact that we always write the same number
611 	 * of elsq entries, keep this in mind before changing the loop below.
612 	 */
613 	for (n = execlists_num_ports(execlists); n--; ) {
614 		struct i915_request *rq;
615 		unsigned int count;
616 		u64 desc;
617 
618 		rq = port_unpack(&port[n], &count);
619 		if (rq) {
620 			GEM_BUG_ON(count > !n);
621 			if (!count++)
622 				execlists_context_schedule_in(rq);
623 			port_set(&port[n], port_pack(rq, count));
624 			desc = execlists_update_context(rq);
625 			GEM_DEBUG_EXEC(port[n].context_id = upper_32_bits(desc));
626 
627 			GEM_TRACE("%s in[%d]:  ctx=%d.%d, fence %llx:%lld (current %d), prio=%d\n",
628 				  engine->name, n,
629 				  port[n].context_id, count,
630 				  rq->fence.context, rq->fence.seqno,
631 				  hwsp_seqno(rq),
632 				  rq_prio(rq));
633 		} else {
634 			GEM_BUG_ON(!n);
635 			desc = 0;
636 		}
637 
638 		write_desc(execlists, desc, n);
639 	}
640 
641 	/* we need to manually load the submit queue */
642 	if (execlists->ctrl_reg)
643 		writel(EL_CTRL_LOAD, execlists->ctrl_reg);
644 
645 	execlists_clear_active(execlists, EXECLISTS_ACTIVE_HWACK);
646 }
647 
648 static bool ctx_single_port_submission(const struct intel_context *ce)
649 {
650 	return (IS_ENABLED(CONFIG_DRM_I915_GVT) &&
651 		i915_gem_context_force_single_submission(ce->gem_context));
652 }
653 
654 static bool can_merge_ctx(const struct intel_context *prev,
655 			  const struct intel_context *next)
656 {
657 	if (prev != next)
658 		return false;
659 
660 	if (ctx_single_port_submission(prev))
661 		return false;
662 
663 	return true;
664 }
665 
666 static bool can_merge_rq(const struct i915_request *prev,
667 			 const struct i915_request *next)
668 {
669 	GEM_BUG_ON(!assert_priority_queue(prev, next));
670 
671 	if (!can_merge_ctx(prev->hw_context, next->hw_context))
672 		return false;
673 
674 	return true;
675 }
676 
677 static void port_assign(struct execlist_port *port, struct i915_request *rq)
678 {
679 	GEM_BUG_ON(rq == port_request(port));
680 
681 	if (port_isset(port))
682 		i915_request_put(port_request(port));
683 
684 	port_set(port, port_pack(i915_request_get(rq), port_count(port)));
685 }
686 
687 static void inject_preempt_context(struct intel_engine_cs *engine)
688 {
689 	struct intel_engine_execlists *execlists = &engine->execlists;
690 	struct intel_context *ce = engine->preempt_context;
691 	unsigned int n;
692 
693 	GEM_BUG_ON(execlists->preempt_complete_status !=
694 		   upper_32_bits(ce->lrc_desc));
695 
696 	/*
697 	 * Switch to our empty preempt context so
698 	 * the state of the GPU is known (idle).
699 	 */
700 	GEM_TRACE("%s\n", engine->name);
701 	for (n = execlists_num_ports(execlists); --n; )
702 		write_desc(execlists, 0, n);
703 
704 	write_desc(execlists, ce->lrc_desc, n);
705 
706 	/* we need to manually load the submit queue */
707 	if (execlists->ctrl_reg)
708 		writel(EL_CTRL_LOAD, execlists->ctrl_reg);
709 
710 	execlists_clear_active(execlists, EXECLISTS_ACTIVE_HWACK);
711 	execlists_set_active(execlists, EXECLISTS_ACTIVE_PREEMPT);
712 
713 	(void)I915_SELFTEST_ONLY(execlists->preempt_hang.count++);
714 }
715 
716 static void complete_preempt_context(struct intel_engine_execlists *execlists)
717 {
718 	GEM_BUG_ON(!execlists_is_active(execlists, EXECLISTS_ACTIVE_PREEMPT));
719 
720 	if (inject_preempt_hang(execlists))
721 		return;
722 
723 	execlists_cancel_port_requests(execlists);
724 	__unwind_incomplete_requests(container_of(execlists,
725 						  struct intel_engine_cs,
726 						  execlists));
727 }
728 
729 static void virtual_update_register_offsets(u32 *regs,
730 					    struct intel_engine_cs *engine)
731 {
732 	u32 base = engine->mmio_base;
733 
734 	/* Must match execlists_init_reg_state()! */
735 
736 	regs[CTX_CONTEXT_CONTROL] =
737 		i915_mmio_reg_offset(RING_CONTEXT_CONTROL(base));
738 	regs[CTX_RING_HEAD] = i915_mmio_reg_offset(RING_HEAD(base));
739 	regs[CTX_RING_TAIL] = i915_mmio_reg_offset(RING_TAIL(base));
740 	regs[CTX_RING_BUFFER_START] = i915_mmio_reg_offset(RING_START(base));
741 	regs[CTX_RING_BUFFER_CONTROL] = i915_mmio_reg_offset(RING_CTL(base));
742 
743 	regs[CTX_BB_HEAD_U] = i915_mmio_reg_offset(RING_BBADDR_UDW(base));
744 	regs[CTX_BB_HEAD_L] = i915_mmio_reg_offset(RING_BBADDR(base));
745 	regs[CTX_BB_STATE] = i915_mmio_reg_offset(RING_BBSTATE(base));
746 	regs[CTX_SECOND_BB_HEAD_U] =
747 		i915_mmio_reg_offset(RING_SBBADDR_UDW(base));
748 	regs[CTX_SECOND_BB_HEAD_L] = i915_mmio_reg_offset(RING_SBBADDR(base));
749 	regs[CTX_SECOND_BB_STATE] = i915_mmio_reg_offset(RING_SBBSTATE(base));
750 
751 	regs[CTX_CTX_TIMESTAMP] =
752 		i915_mmio_reg_offset(RING_CTX_TIMESTAMP(base));
753 	regs[CTX_PDP3_UDW] = i915_mmio_reg_offset(GEN8_RING_PDP_UDW(base, 3));
754 	regs[CTX_PDP3_LDW] = i915_mmio_reg_offset(GEN8_RING_PDP_LDW(base, 3));
755 	regs[CTX_PDP2_UDW] = i915_mmio_reg_offset(GEN8_RING_PDP_UDW(base, 2));
756 	regs[CTX_PDP2_LDW] = i915_mmio_reg_offset(GEN8_RING_PDP_LDW(base, 2));
757 	regs[CTX_PDP1_UDW] = i915_mmio_reg_offset(GEN8_RING_PDP_UDW(base, 1));
758 	regs[CTX_PDP1_LDW] = i915_mmio_reg_offset(GEN8_RING_PDP_LDW(base, 1));
759 	regs[CTX_PDP0_UDW] = i915_mmio_reg_offset(GEN8_RING_PDP_UDW(base, 0));
760 	regs[CTX_PDP0_LDW] = i915_mmio_reg_offset(GEN8_RING_PDP_LDW(base, 0));
761 
762 	if (engine->class == RENDER_CLASS) {
763 		regs[CTX_RCS_INDIRECT_CTX] =
764 			i915_mmio_reg_offset(RING_INDIRECT_CTX(base));
765 		regs[CTX_RCS_INDIRECT_CTX_OFFSET] =
766 			i915_mmio_reg_offset(RING_INDIRECT_CTX_OFFSET(base));
767 		regs[CTX_BB_PER_CTX_PTR] =
768 			i915_mmio_reg_offset(RING_BB_PER_CTX_PTR(base));
769 
770 		regs[CTX_R_PWR_CLK_STATE] =
771 			i915_mmio_reg_offset(GEN8_R_PWR_CLK_STATE);
772 	}
773 }
774 
775 static bool virtual_matches(const struct virtual_engine *ve,
776 			    const struct i915_request *rq,
777 			    const struct intel_engine_cs *engine)
778 {
779 	const struct intel_engine_cs *active;
780 
781 	if (!(rq->execution_mask & engine->mask)) /* We peeked too soon! */
782 		return false;
783 
784 	/*
785 	 * We track when the HW has completed saving the context image
786 	 * (i.e. when we have seen the final CS event switching out of
787 	 * the context) and must not overwrite the context image before
788 	 * then. This restricts us to only using the active engine
789 	 * while the previous virtualized request is inflight (so
790 	 * we reuse the register offsets). This is a very small
791 	 * hystersis on the greedy seelction algorithm.
792 	 */
793 	active = READ_ONCE(ve->context.active);
794 	if (active && active != engine)
795 		return false;
796 
797 	return true;
798 }
799 
800 static void virtual_xfer_breadcrumbs(struct virtual_engine *ve,
801 				     struct intel_engine_cs *engine)
802 {
803 	struct intel_engine_cs *old = ve->siblings[0];
804 
805 	/* All unattached (rq->engine == old) must already be completed */
806 
807 	spin_lock(&old->breadcrumbs.irq_lock);
808 	if (!list_empty(&ve->context.signal_link)) {
809 		list_move_tail(&ve->context.signal_link,
810 			       &engine->breadcrumbs.signalers);
811 		intel_engine_queue_breadcrumbs(engine);
812 	}
813 	spin_unlock(&old->breadcrumbs.irq_lock);
814 }
815 
816 static void execlists_dequeue(struct intel_engine_cs *engine)
817 {
818 	struct intel_engine_execlists * const execlists = &engine->execlists;
819 	struct execlist_port *port = execlists->port;
820 	const struct execlist_port * const last_port =
821 		&execlists->port[execlists->port_mask];
822 	struct i915_request *last = port_request(port);
823 	struct rb_node *rb;
824 	bool submit = false;
825 
826 	/*
827 	 * Hardware submission is through 2 ports. Conceptually each port
828 	 * has a (RING_START, RING_HEAD, RING_TAIL) tuple. RING_START is
829 	 * static for a context, and unique to each, so we only execute
830 	 * requests belonging to a single context from each ring. RING_HEAD
831 	 * is maintained by the CS in the context image, it marks the place
832 	 * where it got up to last time, and through RING_TAIL we tell the CS
833 	 * where we want to execute up to this time.
834 	 *
835 	 * In this list the requests are in order of execution. Consecutive
836 	 * requests from the same context are adjacent in the ringbuffer. We
837 	 * can combine these requests into a single RING_TAIL update:
838 	 *
839 	 *              RING_HEAD...req1...req2
840 	 *                                    ^- RING_TAIL
841 	 * since to execute req2 the CS must first execute req1.
842 	 *
843 	 * Our goal then is to point each port to the end of a consecutive
844 	 * sequence of requests as being the most optimal (fewest wake ups
845 	 * and context switches) submission.
846 	 */
847 
848 	for (rb = rb_first_cached(&execlists->virtual); rb; ) {
849 		struct virtual_engine *ve =
850 			rb_entry(rb, typeof(*ve), nodes[engine->id].rb);
851 		struct i915_request *rq = READ_ONCE(ve->request);
852 
853 		if (!rq) { /* lazily cleanup after another engine handled rq */
854 			rb_erase_cached(rb, &execlists->virtual);
855 			RB_CLEAR_NODE(rb);
856 			rb = rb_first_cached(&execlists->virtual);
857 			continue;
858 		}
859 
860 		if (!virtual_matches(ve, rq, engine)) {
861 			rb = rb_next(rb);
862 			continue;
863 		}
864 
865 		break;
866 	}
867 
868 	if (last) {
869 		/*
870 		 * Don't resubmit or switch until all outstanding
871 		 * preemptions (lite-restore) are seen. Then we
872 		 * know the next preemption status we see corresponds
873 		 * to this ELSP update.
874 		 */
875 		GEM_BUG_ON(!execlists_is_active(execlists,
876 						EXECLISTS_ACTIVE_USER));
877 		GEM_BUG_ON(!port_count(&port[0]));
878 
879 		/*
880 		 * If we write to ELSP a second time before the HW has had
881 		 * a chance to respond to the previous write, we can confuse
882 		 * the HW and hit "undefined behaviour". After writing to ELSP,
883 		 * we must then wait until we see a context-switch event from
884 		 * the HW to indicate that it has had a chance to respond.
885 		 */
886 		if (!execlists_is_active(execlists, EXECLISTS_ACTIVE_HWACK))
887 			return;
888 
889 		if (need_preempt(engine, last, rb)) {
890 			inject_preempt_context(engine);
891 			return;
892 		}
893 
894 		/*
895 		 * In theory, we could coalesce more requests onto
896 		 * the second port (the first port is active, with
897 		 * no preemptions pending). However, that means we
898 		 * then have to deal with the possible lite-restore
899 		 * of the second port (as we submit the ELSP, there
900 		 * may be a context-switch) but also we may complete
901 		 * the resubmission before the context-switch. Ergo,
902 		 * coalescing onto the second port will cause a
903 		 * preemption event, but we cannot predict whether
904 		 * that will affect port[0] or port[1].
905 		 *
906 		 * If the second port is already active, we can wait
907 		 * until the next context-switch before contemplating
908 		 * new requests. The GPU will be busy and we should be
909 		 * able to resubmit the new ELSP before it idles,
910 		 * avoiding pipeline bubbles (momentary pauses where
911 		 * the driver is unable to keep up the supply of new
912 		 * work). However, we have to double check that the
913 		 * priorities of the ports haven't been switch.
914 		 */
915 		if (port_count(&port[1]))
916 			return;
917 
918 		/*
919 		 * WaIdleLiteRestore:bdw,skl
920 		 * Apply the wa NOOPs to prevent
921 		 * ring:HEAD == rq:TAIL as we resubmit the
922 		 * request. See gen8_emit_fini_breadcrumb() for
923 		 * where we prepare the padding after the
924 		 * end of the request.
925 		 */
926 		last->tail = last->wa_tail;
927 	}
928 
929 	while (rb) { /* XXX virtual is always taking precedence */
930 		struct virtual_engine *ve =
931 			rb_entry(rb, typeof(*ve), nodes[engine->id].rb);
932 		struct i915_request *rq;
933 
934 		spin_lock(&ve->base.timeline.lock);
935 
936 		rq = ve->request;
937 		if (unlikely(!rq)) { /* lost the race to a sibling */
938 			spin_unlock(&ve->base.timeline.lock);
939 			rb_erase_cached(rb, &execlists->virtual);
940 			RB_CLEAR_NODE(rb);
941 			rb = rb_first_cached(&execlists->virtual);
942 			continue;
943 		}
944 
945 		GEM_BUG_ON(rq != ve->request);
946 		GEM_BUG_ON(rq->engine != &ve->base);
947 		GEM_BUG_ON(rq->hw_context != &ve->context);
948 
949 		if (rq_prio(rq) >= queue_prio(execlists)) {
950 			if (!virtual_matches(ve, rq, engine)) {
951 				spin_unlock(&ve->base.timeline.lock);
952 				rb = rb_next(rb);
953 				continue;
954 			}
955 
956 			if (last && !can_merge_rq(last, rq)) {
957 				spin_unlock(&ve->base.timeline.lock);
958 				return; /* leave this rq for another engine */
959 			}
960 
961 			GEM_TRACE("%s: virtual rq=%llx:%lld%s, new engine? %s\n",
962 				  engine->name,
963 				  rq->fence.context,
964 				  rq->fence.seqno,
965 				  i915_request_completed(rq) ? "!" :
966 				  i915_request_started(rq) ? "*" :
967 				  "",
968 				  yesno(engine != ve->siblings[0]));
969 
970 			ve->request = NULL;
971 			ve->base.execlists.queue_priority_hint = INT_MIN;
972 			rb_erase_cached(rb, &execlists->virtual);
973 			RB_CLEAR_NODE(rb);
974 
975 			GEM_BUG_ON(!(rq->execution_mask & engine->mask));
976 			rq->engine = engine;
977 
978 			if (engine != ve->siblings[0]) {
979 				u32 *regs = ve->context.lrc_reg_state;
980 				unsigned int n;
981 
982 				GEM_BUG_ON(READ_ONCE(ve->context.active));
983 				virtual_update_register_offsets(regs, engine);
984 
985 				if (!list_empty(&ve->context.signals))
986 					virtual_xfer_breadcrumbs(ve, engine);
987 
988 				/*
989 				 * Move the bound engine to the top of the list
990 				 * for future execution. We then kick this
991 				 * tasklet first before checking others, so that
992 				 * we preferentially reuse this set of bound
993 				 * registers.
994 				 */
995 				for (n = 1; n < ve->num_siblings; n++) {
996 					if (ve->siblings[n] == engine) {
997 						swap(ve->siblings[n],
998 						     ve->siblings[0]);
999 						break;
1000 					}
1001 				}
1002 
1003 				GEM_BUG_ON(ve->siblings[0] != engine);
1004 			}
1005 
1006 			__i915_request_submit(rq);
1007 			trace_i915_request_in(rq, port_index(port, execlists));
1008 			submit = true;
1009 			last = rq;
1010 		}
1011 
1012 		spin_unlock(&ve->base.timeline.lock);
1013 		break;
1014 	}
1015 
1016 	while ((rb = rb_first_cached(&execlists->queue))) {
1017 		struct i915_priolist *p = to_priolist(rb);
1018 		struct i915_request *rq, *rn;
1019 		int i;
1020 
1021 		priolist_for_each_request_consume(rq, rn, p, i) {
1022 			/*
1023 			 * Can we combine this request with the current port?
1024 			 * It has to be the same context/ringbuffer and not
1025 			 * have any exceptions (e.g. GVT saying never to
1026 			 * combine contexts).
1027 			 *
1028 			 * If we can combine the requests, we can execute both
1029 			 * by updating the RING_TAIL to point to the end of the
1030 			 * second request, and so we never need to tell the
1031 			 * hardware about the first.
1032 			 */
1033 			if (last && !can_merge_rq(last, rq)) {
1034 				/*
1035 				 * If we are on the second port and cannot
1036 				 * combine this request with the last, then we
1037 				 * are done.
1038 				 */
1039 				if (port == last_port)
1040 					goto done;
1041 
1042 				/*
1043 				 * We must not populate both ELSP[] with the
1044 				 * same LRCA, i.e. we must submit 2 different
1045 				 * contexts if we submit 2 ELSP.
1046 				 */
1047 				if (last->hw_context == rq->hw_context)
1048 					goto done;
1049 
1050 				/*
1051 				 * If GVT overrides us we only ever submit
1052 				 * port[0], leaving port[1] empty. Note that we
1053 				 * also have to be careful that we don't queue
1054 				 * the same context (even though a different
1055 				 * request) to the second port.
1056 				 */
1057 				if (ctx_single_port_submission(last->hw_context) ||
1058 				    ctx_single_port_submission(rq->hw_context))
1059 					goto done;
1060 
1061 
1062 				if (submit)
1063 					port_assign(port, last);
1064 				port++;
1065 
1066 				GEM_BUG_ON(port_isset(port));
1067 			}
1068 
1069 			list_del_init(&rq->sched.link);
1070 
1071 			__i915_request_submit(rq);
1072 			trace_i915_request_in(rq, port_index(port, execlists));
1073 
1074 			last = rq;
1075 			submit = true;
1076 		}
1077 
1078 		rb_erase_cached(&p->node, &execlists->queue);
1079 		i915_priolist_free(p);
1080 	}
1081 
1082 done:
1083 	/*
1084 	 * Here be a bit of magic! Or sleight-of-hand, whichever you prefer.
1085 	 *
1086 	 * We choose the priority hint such that if we add a request of greater
1087 	 * priority than this, we kick the submission tasklet to decide on
1088 	 * the right order of submitting the requests to hardware. We must
1089 	 * also be prepared to reorder requests as they are in-flight on the
1090 	 * HW. We derive the priority hint then as the first "hole" in
1091 	 * the HW submission ports and if there are no available slots,
1092 	 * the priority of the lowest executing request, i.e. last.
1093 	 *
1094 	 * When we do receive a higher priority request ready to run from the
1095 	 * user, see queue_request(), the priority hint is bumped to that
1096 	 * request triggering preemption on the next dequeue (or subsequent
1097 	 * interrupt for secondary ports).
1098 	 */
1099 	execlists->queue_priority_hint = queue_prio(execlists);
1100 
1101 	if (submit) {
1102 		port_assign(port, last);
1103 		execlists_submit_ports(engine);
1104 	}
1105 
1106 	/* We must always keep the beast fed if we have work piled up */
1107 	GEM_BUG_ON(rb_first_cached(&execlists->queue) &&
1108 		   !port_isset(execlists->port));
1109 
1110 	/* Re-evaluate the executing context setup after each preemptive kick */
1111 	if (last)
1112 		execlists_user_begin(execlists, execlists->port);
1113 
1114 	/* If the engine is now idle, so should be the flag; and vice versa. */
1115 	GEM_BUG_ON(execlists_is_active(&engine->execlists,
1116 				       EXECLISTS_ACTIVE_USER) ==
1117 		   !port_isset(engine->execlists.port));
1118 }
1119 
1120 void
1121 execlists_cancel_port_requests(struct intel_engine_execlists * const execlists)
1122 {
1123 	struct execlist_port *port = execlists->port;
1124 	unsigned int num_ports = execlists_num_ports(execlists);
1125 
1126 	while (num_ports-- && port_isset(port)) {
1127 		struct i915_request *rq = port_request(port);
1128 
1129 		GEM_TRACE("%s:port%u fence %llx:%lld, (current %d)\n",
1130 			  rq->engine->name,
1131 			  (unsigned int)(port - execlists->port),
1132 			  rq->fence.context, rq->fence.seqno,
1133 			  hwsp_seqno(rq));
1134 
1135 		GEM_BUG_ON(!execlists->active);
1136 		execlists_context_schedule_out(rq,
1137 					       i915_request_completed(rq) ?
1138 					       INTEL_CONTEXT_SCHEDULE_OUT :
1139 					       INTEL_CONTEXT_SCHEDULE_PREEMPTED);
1140 
1141 		i915_request_put(rq);
1142 
1143 		memset(port, 0, sizeof(*port));
1144 		port++;
1145 	}
1146 
1147 	execlists_clear_all_active(execlists);
1148 }
1149 
1150 static inline void
1151 invalidate_csb_entries(const u32 *first, const u32 *last)
1152 {
1153 	clflush((void *)first);
1154 	clflush((void *)last);
1155 }
1156 
1157 static inline bool
1158 reset_in_progress(const struct intel_engine_execlists *execlists)
1159 {
1160 	return unlikely(!__tasklet_is_enabled(&execlists->tasklet));
1161 }
1162 
1163 static void process_csb(struct intel_engine_cs *engine)
1164 {
1165 	struct intel_engine_execlists * const execlists = &engine->execlists;
1166 	struct execlist_port *port = execlists->port;
1167 	const u32 * const buf = execlists->csb_status;
1168 	const u8 num_entries = execlists->csb_size;
1169 	u8 head, tail;
1170 
1171 	lockdep_assert_held(&engine->timeline.lock);
1172 
1173 	/*
1174 	 * Note that csb_write, csb_status may be either in HWSP or mmio.
1175 	 * When reading from the csb_write mmio register, we have to be
1176 	 * careful to only use the GEN8_CSB_WRITE_PTR portion, which is
1177 	 * the low 4bits. As it happens we know the next 4bits are always
1178 	 * zero and so we can simply masked off the low u8 of the register
1179 	 * and treat it identically to reading from the HWSP (without having
1180 	 * to use explicit shifting and masking, and probably bifurcating
1181 	 * the code to handle the legacy mmio read).
1182 	 */
1183 	head = execlists->csb_head;
1184 	tail = READ_ONCE(*execlists->csb_write);
1185 	GEM_TRACE("%s cs-irq head=%d, tail=%d\n", engine->name, head, tail);
1186 	if (unlikely(head == tail))
1187 		return;
1188 
1189 	/*
1190 	 * Hopefully paired with a wmb() in HW!
1191 	 *
1192 	 * We must complete the read of the write pointer before any reads
1193 	 * from the CSB, so that we do not see stale values. Without an rmb
1194 	 * (lfence) the HW may speculatively perform the CSB[] reads *before*
1195 	 * we perform the READ_ONCE(*csb_write).
1196 	 */
1197 	rmb();
1198 
1199 	do {
1200 		struct i915_request *rq;
1201 		unsigned int status;
1202 		unsigned int count;
1203 
1204 		if (++head == num_entries)
1205 			head = 0;
1206 
1207 		/*
1208 		 * We are flying near dragons again.
1209 		 *
1210 		 * We hold a reference to the request in execlist_port[]
1211 		 * but no more than that. We are operating in softirq
1212 		 * context and so cannot hold any mutex or sleep. That
1213 		 * prevents us stopping the requests we are processing
1214 		 * in port[] from being retired simultaneously (the
1215 		 * breadcrumb will be complete before we see the
1216 		 * context-switch). As we only hold the reference to the
1217 		 * request, any pointer chasing underneath the request
1218 		 * is subject to a potential use-after-free. Thus we
1219 		 * store all of the bookkeeping within port[] as
1220 		 * required, and avoid using unguarded pointers beneath
1221 		 * request itself. The same applies to the atomic
1222 		 * status notifier.
1223 		 */
1224 
1225 		GEM_TRACE("%s csb[%d]: status=0x%08x:0x%08x, active=0x%x\n",
1226 			  engine->name, head,
1227 			  buf[2 * head + 0], buf[2 * head + 1],
1228 			  execlists->active);
1229 
1230 		status = buf[2 * head];
1231 		if (status & (GEN8_CTX_STATUS_IDLE_ACTIVE |
1232 			      GEN8_CTX_STATUS_PREEMPTED))
1233 			execlists_set_active(execlists,
1234 					     EXECLISTS_ACTIVE_HWACK);
1235 		if (status & GEN8_CTX_STATUS_ACTIVE_IDLE)
1236 			execlists_clear_active(execlists,
1237 					       EXECLISTS_ACTIVE_HWACK);
1238 
1239 		if (!(status & GEN8_CTX_STATUS_COMPLETED_MASK))
1240 			continue;
1241 
1242 		/* We should never get a COMPLETED | IDLE_ACTIVE! */
1243 		GEM_BUG_ON(status & GEN8_CTX_STATUS_IDLE_ACTIVE);
1244 
1245 		if (status & GEN8_CTX_STATUS_COMPLETE &&
1246 		    buf[2*head + 1] == execlists->preempt_complete_status) {
1247 			GEM_TRACE("%s preempt-idle\n", engine->name);
1248 			complete_preempt_context(execlists);
1249 			continue;
1250 		}
1251 
1252 		if (status & GEN8_CTX_STATUS_PREEMPTED &&
1253 		    execlists_is_active(execlists,
1254 					EXECLISTS_ACTIVE_PREEMPT))
1255 			continue;
1256 
1257 		GEM_BUG_ON(!execlists_is_active(execlists,
1258 						EXECLISTS_ACTIVE_USER));
1259 
1260 		rq = port_unpack(port, &count);
1261 		GEM_TRACE("%s out[0]: ctx=%d.%d, fence %llx:%lld (current %d), prio=%d\n",
1262 			  engine->name,
1263 			  port->context_id, count,
1264 			  rq ? rq->fence.context : 0,
1265 			  rq ? rq->fence.seqno : 0,
1266 			  rq ? hwsp_seqno(rq) : 0,
1267 			  rq ? rq_prio(rq) : 0);
1268 
1269 		/* Check the context/desc id for this event matches */
1270 		GEM_DEBUG_BUG_ON(buf[2 * head + 1] != port->context_id);
1271 
1272 		GEM_BUG_ON(count == 0);
1273 		if (--count == 0) {
1274 			/*
1275 			 * On the final event corresponding to the
1276 			 * submission of this context, we expect either
1277 			 * an element-switch event or a completion
1278 			 * event (and on completion, the active-idle
1279 			 * marker). No more preemptions, lite-restore
1280 			 * or otherwise.
1281 			 */
1282 			GEM_BUG_ON(status & GEN8_CTX_STATUS_PREEMPTED);
1283 			GEM_BUG_ON(port_isset(&port[1]) &&
1284 				   !(status & GEN8_CTX_STATUS_ELEMENT_SWITCH));
1285 			GEM_BUG_ON(!port_isset(&port[1]) &&
1286 				   !(status & GEN8_CTX_STATUS_ACTIVE_IDLE));
1287 
1288 			/*
1289 			 * We rely on the hardware being strongly
1290 			 * ordered, that the breadcrumb write is
1291 			 * coherent (visible from the CPU) before the
1292 			 * user interrupt and CSB is processed.
1293 			 */
1294 			GEM_BUG_ON(!i915_request_completed(rq));
1295 
1296 			execlists_context_schedule_out(rq,
1297 						       INTEL_CONTEXT_SCHEDULE_OUT);
1298 			i915_request_put(rq);
1299 
1300 			GEM_TRACE("%s completed ctx=%d\n",
1301 				  engine->name, port->context_id);
1302 
1303 			port = execlists_port_complete(execlists, port);
1304 			if (port_isset(port))
1305 				execlists_user_begin(execlists, port);
1306 			else
1307 				execlists_user_end(execlists);
1308 		} else {
1309 			port_set(port, port_pack(rq, count));
1310 		}
1311 	} while (head != tail);
1312 
1313 	execlists->csb_head = head;
1314 
1315 	/*
1316 	 * Gen11 has proven to fail wrt global observation point between
1317 	 * entry and tail update, failing on the ordering and thus
1318 	 * we see an old entry in the context status buffer.
1319 	 *
1320 	 * Forcibly evict out entries for the next gpu csb update,
1321 	 * to increase the odds that we get a fresh entries with non
1322 	 * working hardware. The cost for doing so comes out mostly with
1323 	 * the wash as hardware, working or not, will need to do the
1324 	 * invalidation before.
1325 	 */
1326 	invalidate_csb_entries(&buf[0], &buf[num_entries - 1]);
1327 }
1328 
1329 static void __execlists_submission_tasklet(struct intel_engine_cs *const engine)
1330 {
1331 	lockdep_assert_held(&engine->timeline.lock);
1332 
1333 	process_csb(engine);
1334 	if (!execlists_is_active(&engine->execlists, EXECLISTS_ACTIVE_PREEMPT))
1335 		execlists_dequeue(engine);
1336 }
1337 
1338 /*
1339  * Check the unread Context Status Buffers and manage the submission of new
1340  * contexts to the ELSP accordingly.
1341  */
1342 static void execlists_submission_tasklet(unsigned long data)
1343 {
1344 	struct intel_engine_cs * const engine = (struct intel_engine_cs *)data;
1345 	unsigned long flags;
1346 
1347 	GEM_TRACE("%s awake?=%d, active=%x\n",
1348 		  engine->name,
1349 		  !!intel_wakeref_active(&engine->wakeref),
1350 		  engine->execlists.active);
1351 
1352 	spin_lock_irqsave(&engine->timeline.lock, flags);
1353 	__execlists_submission_tasklet(engine);
1354 	spin_unlock_irqrestore(&engine->timeline.lock, flags);
1355 }
1356 
1357 static void queue_request(struct intel_engine_cs *engine,
1358 			  struct i915_sched_node *node,
1359 			  int prio)
1360 {
1361 	list_add_tail(&node->link, i915_sched_lookup_priolist(engine, prio));
1362 }
1363 
1364 static void __submit_queue_imm(struct intel_engine_cs *engine)
1365 {
1366 	struct intel_engine_execlists * const execlists = &engine->execlists;
1367 
1368 	if (reset_in_progress(execlists))
1369 		return; /* defer until we restart the engine following reset */
1370 
1371 	if (execlists->tasklet.func == execlists_submission_tasklet)
1372 		__execlists_submission_tasklet(engine);
1373 	else
1374 		tasklet_hi_schedule(&execlists->tasklet);
1375 }
1376 
1377 static void submit_queue(struct intel_engine_cs *engine, int prio)
1378 {
1379 	if (prio > engine->execlists.queue_priority_hint) {
1380 		engine->execlists.queue_priority_hint = prio;
1381 		__submit_queue_imm(engine);
1382 	}
1383 }
1384 
1385 static void execlists_submit_request(struct i915_request *request)
1386 {
1387 	struct intel_engine_cs *engine = request->engine;
1388 	unsigned long flags;
1389 
1390 	/* Will be called from irq-context when using foreign fences. */
1391 	spin_lock_irqsave(&engine->timeline.lock, flags);
1392 
1393 	queue_request(engine, &request->sched, rq_prio(request));
1394 
1395 	GEM_BUG_ON(RB_EMPTY_ROOT(&engine->execlists.queue.rb_root));
1396 	GEM_BUG_ON(list_empty(&request->sched.link));
1397 
1398 	submit_queue(engine, rq_prio(request));
1399 
1400 	spin_unlock_irqrestore(&engine->timeline.lock, flags);
1401 }
1402 
1403 static void __execlists_context_fini(struct intel_context *ce)
1404 {
1405 	intel_ring_put(ce->ring);
1406 
1407 	GEM_BUG_ON(i915_gem_object_is_active(ce->state->obj));
1408 	i915_gem_object_put(ce->state->obj);
1409 }
1410 
1411 static void execlists_context_destroy(struct kref *kref)
1412 {
1413 	struct intel_context *ce = container_of(kref, typeof(*ce), ref);
1414 
1415 	GEM_BUG_ON(intel_context_is_pinned(ce));
1416 
1417 	if (ce->state)
1418 		__execlists_context_fini(ce);
1419 
1420 	intel_context_free(ce);
1421 }
1422 
1423 static int __context_pin(struct i915_vma *vma)
1424 {
1425 	unsigned int flags;
1426 	int err;
1427 
1428 	flags = PIN_GLOBAL | PIN_HIGH;
1429 	flags |= PIN_OFFSET_BIAS | i915_ggtt_pin_bias(vma);
1430 
1431 	err = i915_vma_pin(vma, 0, 0, flags);
1432 	if (err)
1433 		return err;
1434 
1435 	vma->obj->pin_global++;
1436 	vma->obj->mm.dirty = true;
1437 
1438 	return 0;
1439 }
1440 
1441 static void __context_unpin(struct i915_vma *vma)
1442 {
1443 	vma->obj->pin_global--;
1444 	__i915_vma_unpin(vma);
1445 }
1446 
1447 static void execlists_context_unpin(struct intel_context *ce)
1448 {
1449 	struct intel_engine_cs *engine;
1450 
1451 	/*
1452 	 * The tasklet may still be using a pointer to our state, via an
1453 	 * old request. However, since we know we only unpin the context
1454 	 * on retirement of the following request, we know that the last
1455 	 * request referencing us will have had a completion CS interrupt.
1456 	 * If we see that it is still active, it means that the tasklet hasn't
1457 	 * had the chance to run yet; let it run before we teardown the
1458 	 * reference it may use.
1459 	 */
1460 	engine = READ_ONCE(ce->active);
1461 	if (unlikely(engine)) {
1462 		unsigned long flags;
1463 
1464 		spin_lock_irqsave(&engine->timeline.lock, flags);
1465 		process_csb(engine);
1466 		spin_unlock_irqrestore(&engine->timeline.lock, flags);
1467 
1468 		GEM_BUG_ON(READ_ONCE(ce->active));
1469 	}
1470 
1471 	i915_gem_context_unpin_hw_id(ce->gem_context);
1472 
1473 	intel_ring_unpin(ce->ring);
1474 
1475 	i915_gem_object_unpin_map(ce->state->obj);
1476 	__context_unpin(ce->state);
1477 }
1478 
1479 static void
1480 __execlists_update_reg_state(struct intel_context *ce,
1481 			     struct intel_engine_cs *engine)
1482 {
1483 	struct intel_ring *ring = ce->ring;
1484 	u32 *regs = ce->lrc_reg_state;
1485 
1486 	GEM_BUG_ON(!intel_ring_offset_valid(ring, ring->head));
1487 	GEM_BUG_ON(!intel_ring_offset_valid(ring, ring->tail));
1488 
1489 	regs[CTX_RING_BUFFER_START + 1] = i915_ggtt_offset(ring->vma);
1490 	regs[CTX_RING_HEAD + 1] = ring->head;
1491 	regs[CTX_RING_TAIL + 1] = ring->tail;
1492 
1493 	/* RPCS */
1494 	if (engine->class == RENDER_CLASS)
1495 		regs[CTX_R_PWR_CLK_STATE + 1] =
1496 			intel_sseu_make_rpcs(engine->i915, &ce->sseu);
1497 }
1498 
1499 static int
1500 __execlists_context_pin(struct intel_context *ce,
1501 			struct intel_engine_cs *engine)
1502 {
1503 	void *vaddr;
1504 	int ret;
1505 
1506 	GEM_BUG_ON(!ce->gem_context->ppgtt);
1507 
1508 	ret = execlists_context_deferred_alloc(ce, engine);
1509 	if (ret)
1510 		goto err;
1511 	GEM_BUG_ON(!ce->state);
1512 
1513 	ret = __context_pin(ce->state);
1514 	if (ret)
1515 		goto err;
1516 
1517 	vaddr = i915_gem_object_pin_map(ce->state->obj,
1518 					i915_coherent_map_type(engine->i915) |
1519 					I915_MAP_OVERRIDE);
1520 	if (IS_ERR(vaddr)) {
1521 		ret = PTR_ERR(vaddr);
1522 		goto unpin_vma;
1523 	}
1524 
1525 	ret = intel_ring_pin(ce->ring);
1526 	if (ret)
1527 		goto unpin_map;
1528 
1529 	ret = i915_gem_context_pin_hw_id(ce->gem_context);
1530 	if (ret)
1531 		goto unpin_ring;
1532 
1533 	ce->lrc_desc = lrc_descriptor(ce, engine);
1534 	ce->lrc_reg_state = vaddr + LRC_STATE_PN * PAGE_SIZE;
1535 	__execlists_update_reg_state(ce, engine);
1536 
1537 	return 0;
1538 
1539 unpin_ring:
1540 	intel_ring_unpin(ce->ring);
1541 unpin_map:
1542 	i915_gem_object_unpin_map(ce->state->obj);
1543 unpin_vma:
1544 	__context_unpin(ce->state);
1545 err:
1546 	return ret;
1547 }
1548 
1549 static int execlists_context_pin(struct intel_context *ce)
1550 {
1551 	return __execlists_context_pin(ce, ce->engine);
1552 }
1553 
1554 static void execlists_context_reset(struct intel_context *ce)
1555 {
1556 	/*
1557 	 * Because we emit WA_TAIL_DWORDS there may be a disparity
1558 	 * between our bookkeeping in ce->ring->head and ce->ring->tail and
1559 	 * that stored in context. As we only write new commands from
1560 	 * ce->ring->tail onwards, everything before that is junk. If the GPU
1561 	 * starts reading from its RING_HEAD from the context, it may try to
1562 	 * execute that junk and die.
1563 	 *
1564 	 * The contexts that are stilled pinned on resume belong to the
1565 	 * kernel, and are local to each engine. All other contexts will
1566 	 * have their head/tail sanitized upon pinning before use, so they
1567 	 * will never see garbage,
1568 	 *
1569 	 * So to avoid that we reset the context images upon resume. For
1570 	 * simplicity, we just zero everything out.
1571 	 */
1572 	intel_ring_reset(ce->ring, 0);
1573 	__execlists_update_reg_state(ce, ce->engine);
1574 }
1575 
1576 static const struct intel_context_ops execlists_context_ops = {
1577 	.pin = execlists_context_pin,
1578 	.unpin = execlists_context_unpin,
1579 
1580 	.enter = intel_context_enter_engine,
1581 	.exit = intel_context_exit_engine,
1582 
1583 	.reset = execlists_context_reset,
1584 	.destroy = execlists_context_destroy,
1585 };
1586 
1587 static int gen8_emit_init_breadcrumb(struct i915_request *rq)
1588 {
1589 	u32 *cs;
1590 
1591 	GEM_BUG_ON(!rq->timeline->has_initial_breadcrumb);
1592 
1593 	cs = intel_ring_begin(rq, 6);
1594 	if (IS_ERR(cs))
1595 		return PTR_ERR(cs);
1596 
1597 	/*
1598 	 * Check if we have been preempted before we even get started.
1599 	 *
1600 	 * After this point i915_request_started() reports true, even if
1601 	 * we get preempted and so are no longer running.
1602 	 */
1603 	*cs++ = MI_ARB_CHECK;
1604 	*cs++ = MI_NOOP;
1605 
1606 	*cs++ = MI_STORE_DWORD_IMM_GEN4 | MI_USE_GGTT;
1607 	*cs++ = rq->timeline->hwsp_offset;
1608 	*cs++ = 0;
1609 	*cs++ = rq->fence.seqno - 1;
1610 
1611 	intel_ring_advance(rq, cs);
1612 
1613 	/* Record the updated position of the request's payload */
1614 	rq->infix = intel_ring_offset(rq, cs);
1615 
1616 	return 0;
1617 }
1618 
1619 static int emit_pdps(struct i915_request *rq)
1620 {
1621 	const struct intel_engine_cs * const engine = rq->engine;
1622 	struct i915_hw_ppgtt * const ppgtt = rq->gem_context->ppgtt;
1623 	int err, i;
1624 	u32 *cs;
1625 
1626 	GEM_BUG_ON(intel_vgpu_active(rq->i915));
1627 
1628 	/*
1629 	 * Beware ye of the dragons, this sequence is magic!
1630 	 *
1631 	 * Small changes to this sequence can cause anything from
1632 	 * GPU hangs to forcewake errors and machine lockups!
1633 	 */
1634 
1635 	/* Flush any residual operations from the context load */
1636 	err = engine->emit_flush(rq, EMIT_FLUSH);
1637 	if (err)
1638 		return err;
1639 
1640 	/* Magic required to prevent forcewake errors! */
1641 	err = engine->emit_flush(rq, EMIT_INVALIDATE);
1642 	if (err)
1643 		return err;
1644 
1645 	cs = intel_ring_begin(rq, 4 * GEN8_3LVL_PDPES + 2);
1646 	if (IS_ERR(cs))
1647 		return PTR_ERR(cs);
1648 
1649 	/* Ensure the LRI have landed before we invalidate & continue */
1650 	*cs++ = MI_LOAD_REGISTER_IMM(2 * GEN8_3LVL_PDPES) | MI_LRI_FORCE_POSTED;
1651 	for (i = GEN8_3LVL_PDPES; i--; ) {
1652 		const dma_addr_t pd_daddr = i915_page_dir_dma_addr(ppgtt, i);
1653 		u32 base = engine->mmio_base;
1654 
1655 		*cs++ = i915_mmio_reg_offset(GEN8_RING_PDP_UDW(base, i));
1656 		*cs++ = upper_32_bits(pd_daddr);
1657 		*cs++ = i915_mmio_reg_offset(GEN8_RING_PDP_LDW(base, i));
1658 		*cs++ = lower_32_bits(pd_daddr);
1659 	}
1660 	*cs++ = MI_NOOP;
1661 
1662 	intel_ring_advance(rq, cs);
1663 
1664 	/* Be doubly sure the LRI have landed before proceeding */
1665 	err = engine->emit_flush(rq, EMIT_FLUSH);
1666 	if (err)
1667 		return err;
1668 
1669 	/* Re-invalidate the TLB for luck */
1670 	return engine->emit_flush(rq, EMIT_INVALIDATE);
1671 }
1672 
1673 static int execlists_request_alloc(struct i915_request *request)
1674 {
1675 	int ret;
1676 
1677 	GEM_BUG_ON(!intel_context_is_pinned(request->hw_context));
1678 
1679 	/*
1680 	 * Flush enough space to reduce the likelihood of waiting after
1681 	 * we start building the request - in which case we will just
1682 	 * have to repeat work.
1683 	 */
1684 	request->reserved_space += EXECLISTS_REQUEST_SIZE;
1685 
1686 	/*
1687 	 * Note that after this point, we have committed to using
1688 	 * this request as it is being used to both track the
1689 	 * state of engine initialisation and liveness of the
1690 	 * golden renderstate above. Think twice before you try
1691 	 * to cancel/unwind this request now.
1692 	 */
1693 
1694 	/* Unconditionally invalidate GPU caches and TLBs. */
1695 	if (i915_vm_is_4lvl(&request->gem_context->ppgtt->vm))
1696 		ret = request->engine->emit_flush(request, EMIT_INVALIDATE);
1697 	else
1698 		ret = emit_pdps(request);
1699 	if (ret)
1700 		return ret;
1701 
1702 	request->reserved_space -= EXECLISTS_REQUEST_SIZE;
1703 	return 0;
1704 }
1705 
1706 /*
1707  * In this WA we need to set GEN8_L3SQCREG4[21:21] and reset it after
1708  * PIPE_CONTROL instruction. This is required for the flush to happen correctly
1709  * but there is a slight complication as this is applied in WA batch where the
1710  * values are only initialized once so we cannot take register value at the
1711  * beginning and reuse it further; hence we save its value to memory, upload a
1712  * constant value with bit21 set and then we restore it back with the saved value.
1713  * To simplify the WA, a constant value is formed by using the default value
1714  * of this register. This shouldn't be a problem because we are only modifying
1715  * it for a short period and this batch in non-premptible. We can ofcourse
1716  * use additional instructions that read the actual value of the register
1717  * at that time and set our bit of interest but it makes the WA complicated.
1718  *
1719  * This WA is also required for Gen9 so extracting as a function avoids
1720  * code duplication.
1721  */
1722 static u32 *
1723 gen8_emit_flush_coherentl3_wa(struct intel_engine_cs *engine, u32 *batch)
1724 {
1725 	/* NB no one else is allowed to scribble over scratch + 256! */
1726 	*batch++ = MI_STORE_REGISTER_MEM_GEN8 | MI_SRM_LRM_GLOBAL_GTT;
1727 	*batch++ = i915_mmio_reg_offset(GEN8_L3SQCREG4);
1728 	*batch++ = i915_scratch_offset(engine->i915) + 256;
1729 	*batch++ = 0;
1730 
1731 	*batch++ = MI_LOAD_REGISTER_IMM(1);
1732 	*batch++ = i915_mmio_reg_offset(GEN8_L3SQCREG4);
1733 	*batch++ = 0x40400000 | GEN8_LQSC_FLUSH_COHERENT_LINES;
1734 
1735 	batch = gen8_emit_pipe_control(batch,
1736 				       PIPE_CONTROL_CS_STALL |
1737 				       PIPE_CONTROL_DC_FLUSH_ENABLE,
1738 				       0);
1739 
1740 	*batch++ = MI_LOAD_REGISTER_MEM_GEN8 | MI_SRM_LRM_GLOBAL_GTT;
1741 	*batch++ = i915_mmio_reg_offset(GEN8_L3SQCREG4);
1742 	*batch++ = i915_scratch_offset(engine->i915) + 256;
1743 	*batch++ = 0;
1744 
1745 	return batch;
1746 }
1747 
1748 /*
1749  * Typically we only have one indirect_ctx and per_ctx batch buffer which are
1750  * initialized at the beginning and shared across all contexts but this field
1751  * helps us to have multiple batches at different offsets and select them based
1752  * on a criteria. At the moment this batch always start at the beginning of the page
1753  * and at this point we don't have multiple wa_ctx batch buffers.
1754  *
1755  * The number of WA applied are not known at the beginning; we use this field
1756  * to return the no of DWORDS written.
1757  *
1758  * It is to be noted that this batch does not contain MI_BATCH_BUFFER_END
1759  * so it adds NOOPs as padding to make it cacheline aligned.
1760  * MI_BATCH_BUFFER_END will be added to perctx batch and both of them together
1761  * makes a complete batch buffer.
1762  */
1763 static u32 *gen8_init_indirectctx_bb(struct intel_engine_cs *engine, u32 *batch)
1764 {
1765 	/* WaDisableCtxRestoreArbitration:bdw,chv */
1766 	*batch++ = MI_ARB_ON_OFF | MI_ARB_DISABLE;
1767 
1768 	/* WaFlushCoherentL3CacheLinesAtContextSwitch:bdw */
1769 	if (IS_BROADWELL(engine->i915))
1770 		batch = gen8_emit_flush_coherentl3_wa(engine, batch);
1771 
1772 	/* WaClearSlmSpaceAtContextSwitch:bdw,chv */
1773 	/* Actual scratch location is at 128 bytes offset */
1774 	batch = gen8_emit_pipe_control(batch,
1775 				       PIPE_CONTROL_FLUSH_L3 |
1776 				       PIPE_CONTROL_GLOBAL_GTT_IVB |
1777 				       PIPE_CONTROL_CS_STALL |
1778 				       PIPE_CONTROL_QW_WRITE,
1779 				       i915_scratch_offset(engine->i915) +
1780 				       2 * CACHELINE_BYTES);
1781 
1782 	*batch++ = MI_ARB_ON_OFF | MI_ARB_ENABLE;
1783 
1784 	/* Pad to end of cacheline */
1785 	while ((unsigned long)batch % CACHELINE_BYTES)
1786 		*batch++ = MI_NOOP;
1787 
1788 	/*
1789 	 * MI_BATCH_BUFFER_END is not required in Indirect ctx BB because
1790 	 * execution depends on the length specified in terms of cache lines
1791 	 * in the register CTX_RCS_INDIRECT_CTX
1792 	 */
1793 
1794 	return batch;
1795 }
1796 
1797 struct lri {
1798 	i915_reg_t reg;
1799 	u32 value;
1800 };
1801 
1802 static u32 *emit_lri(u32 *batch, const struct lri *lri, unsigned int count)
1803 {
1804 	GEM_BUG_ON(!count || count > 63);
1805 
1806 	*batch++ = MI_LOAD_REGISTER_IMM(count);
1807 	do {
1808 		*batch++ = i915_mmio_reg_offset(lri->reg);
1809 		*batch++ = lri->value;
1810 	} while (lri++, --count);
1811 	*batch++ = MI_NOOP;
1812 
1813 	return batch;
1814 }
1815 
1816 static u32 *gen9_init_indirectctx_bb(struct intel_engine_cs *engine, u32 *batch)
1817 {
1818 	static const struct lri lri[] = {
1819 		/* WaDisableGatherAtSetShaderCommonSlice:skl,bxt,kbl,glk */
1820 		{
1821 			COMMON_SLICE_CHICKEN2,
1822 			__MASKED_FIELD(GEN9_DISABLE_GATHER_AT_SET_SHADER_COMMON_SLICE,
1823 				       0),
1824 		},
1825 
1826 		/* BSpec: 11391 */
1827 		{
1828 			FF_SLICE_CHICKEN,
1829 			__MASKED_FIELD(FF_SLICE_CHICKEN_CL_PROVOKING_VERTEX_FIX,
1830 				       FF_SLICE_CHICKEN_CL_PROVOKING_VERTEX_FIX),
1831 		},
1832 
1833 		/* BSpec: 11299 */
1834 		{
1835 			_3D_CHICKEN3,
1836 			__MASKED_FIELD(_3D_CHICKEN_SF_PROVOKING_VERTEX_FIX,
1837 				       _3D_CHICKEN_SF_PROVOKING_VERTEX_FIX),
1838 		}
1839 	};
1840 
1841 	*batch++ = MI_ARB_ON_OFF | MI_ARB_DISABLE;
1842 
1843 	/* WaFlushCoherentL3CacheLinesAtContextSwitch:skl,bxt,glk */
1844 	batch = gen8_emit_flush_coherentl3_wa(engine, batch);
1845 
1846 	batch = emit_lri(batch, lri, ARRAY_SIZE(lri));
1847 
1848 	/* WaMediaPoolStateCmdInWABB:bxt,glk */
1849 	if (HAS_POOLED_EU(engine->i915)) {
1850 		/*
1851 		 * EU pool configuration is setup along with golden context
1852 		 * during context initialization. This value depends on
1853 		 * device type (2x6 or 3x6) and needs to be updated based
1854 		 * on which subslice is disabled especially for 2x6
1855 		 * devices, however it is safe to load default
1856 		 * configuration of 3x6 device instead of masking off
1857 		 * corresponding bits because HW ignores bits of a disabled
1858 		 * subslice and drops down to appropriate config. Please
1859 		 * see render_state_setup() in i915_gem_render_state.c for
1860 		 * possible configurations, to avoid duplication they are
1861 		 * not shown here again.
1862 		 */
1863 		*batch++ = GEN9_MEDIA_POOL_STATE;
1864 		*batch++ = GEN9_MEDIA_POOL_ENABLE;
1865 		*batch++ = 0x00777000;
1866 		*batch++ = 0;
1867 		*batch++ = 0;
1868 		*batch++ = 0;
1869 	}
1870 
1871 	*batch++ = MI_ARB_ON_OFF | MI_ARB_ENABLE;
1872 
1873 	/* Pad to end of cacheline */
1874 	while ((unsigned long)batch % CACHELINE_BYTES)
1875 		*batch++ = MI_NOOP;
1876 
1877 	return batch;
1878 }
1879 
1880 static u32 *
1881 gen10_init_indirectctx_bb(struct intel_engine_cs *engine, u32 *batch)
1882 {
1883 	int i;
1884 
1885 	/*
1886 	 * WaPipeControlBefore3DStateSamplePattern: cnl
1887 	 *
1888 	 * Ensure the engine is idle prior to programming a
1889 	 * 3DSTATE_SAMPLE_PATTERN during a context restore.
1890 	 */
1891 	batch = gen8_emit_pipe_control(batch,
1892 				       PIPE_CONTROL_CS_STALL,
1893 				       0);
1894 	/*
1895 	 * WaPipeControlBefore3DStateSamplePattern says we need 4 dwords for
1896 	 * the PIPE_CONTROL followed by 12 dwords of 0x0, so 16 dwords in
1897 	 * total. However, a PIPE_CONTROL is 6 dwords long, not 4, which is
1898 	 * confusing. Since gen8_emit_pipe_control() already advances the
1899 	 * batch by 6 dwords, we advance the other 10 here, completing a
1900 	 * cacheline. It's not clear if the workaround requires this padding
1901 	 * before other commands, or if it's just the regular padding we would
1902 	 * already have for the workaround bb, so leave it here for now.
1903 	 */
1904 	for (i = 0; i < 10; i++)
1905 		*batch++ = MI_NOOP;
1906 
1907 	/* Pad to end of cacheline */
1908 	while ((unsigned long)batch % CACHELINE_BYTES)
1909 		*batch++ = MI_NOOP;
1910 
1911 	return batch;
1912 }
1913 
1914 #define CTX_WA_BB_OBJ_SIZE (PAGE_SIZE)
1915 
1916 static int lrc_setup_wa_ctx(struct intel_engine_cs *engine)
1917 {
1918 	struct drm_i915_gem_object *obj;
1919 	struct i915_vma *vma;
1920 	int err;
1921 
1922 	obj = i915_gem_object_create(engine->i915, CTX_WA_BB_OBJ_SIZE);
1923 	if (IS_ERR(obj))
1924 		return PTR_ERR(obj);
1925 
1926 	vma = i915_vma_instance(obj, &engine->i915->ggtt.vm, NULL);
1927 	if (IS_ERR(vma)) {
1928 		err = PTR_ERR(vma);
1929 		goto err;
1930 	}
1931 
1932 	err = i915_vma_pin(vma, 0, 0, PIN_GLOBAL | PIN_HIGH);
1933 	if (err)
1934 		goto err;
1935 
1936 	engine->wa_ctx.vma = vma;
1937 	return 0;
1938 
1939 err:
1940 	i915_gem_object_put(obj);
1941 	return err;
1942 }
1943 
1944 static void lrc_destroy_wa_ctx(struct intel_engine_cs *engine)
1945 {
1946 	i915_vma_unpin_and_release(&engine->wa_ctx.vma, 0);
1947 }
1948 
1949 typedef u32 *(*wa_bb_func_t)(struct intel_engine_cs *engine, u32 *batch);
1950 
1951 static int intel_init_workaround_bb(struct intel_engine_cs *engine)
1952 {
1953 	struct i915_ctx_workarounds *wa_ctx = &engine->wa_ctx;
1954 	struct i915_wa_ctx_bb *wa_bb[2] = { &wa_ctx->indirect_ctx,
1955 					    &wa_ctx->per_ctx };
1956 	wa_bb_func_t wa_bb_fn[2];
1957 	struct page *page;
1958 	void *batch, *batch_ptr;
1959 	unsigned int i;
1960 	int ret;
1961 
1962 	if (engine->class != RENDER_CLASS)
1963 		return 0;
1964 
1965 	switch (INTEL_GEN(engine->i915)) {
1966 	case 11:
1967 		return 0;
1968 	case 10:
1969 		wa_bb_fn[0] = gen10_init_indirectctx_bb;
1970 		wa_bb_fn[1] = NULL;
1971 		break;
1972 	case 9:
1973 		wa_bb_fn[0] = gen9_init_indirectctx_bb;
1974 		wa_bb_fn[1] = NULL;
1975 		break;
1976 	case 8:
1977 		wa_bb_fn[0] = gen8_init_indirectctx_bb;
1978 		wa_bb_fn[1] = NULL;
1979 		break;
1980 	default:
1981 		MISSING_CASE(INTEL_GEN(engine->i915));
1982 		return 0;
1983 	}
1984 
1985 	ret = lrc_setup_wa_ctx(engine);
1986 	if (ret) {
1987 		DRM_DEBUG_DRIVER("Failed to setup context WA page: %d\n", ret);
1988 		return ret;
1989 	}
1990 
1991 	page = i915_gem_object_get_dirty_page(wa_ctx->vma->obj, 0);
1992 	batch = batch_ptr = kmap_atomic(page);
1993 
1994 	/*
1995 	 * Emit the two workaround batch buffers, recording the offset from the
1996 	 * start of the workaround batch buffer object for each and their
1997 	 * respective sizes.
1998 	 */
1999 	for (i = 0; i < ARRAY_SIZE(wa_bb_fn); i++) {
2000 		wa_bb[i]->offset = batch_ptr - batch;
2001 		if (GEM_DEBUG_WARN_ON(!IS_ALIGNED(wa_bb[i]->offset,
2002 						  CACHELINE_BYTES))) {
2003 			ret = -EINVAL;
2004 			break;
2005 		}
2006 		if (wa_bb_fn[i])
2007 			batch_ptr = wa_bb_fn[i](engine, batch_ptr);
2008 		wa_bb[i]->size = batch_ptr - (batch + wa_bb[i]->offset);
2009 	}
2010 
2011 	BUG_ON(batch_ptr - batch > CTX_WA_BB_OBJ_SIZE);
2012 
2013 	kunmap_atomic(batch);
2014 	if (ret)
2015 		lrc_destroy_wa_ctx(engine);
2016 
2017 	return ret;
2018 }
2019 
2020 static void enable_execlists(struct intel_engine_cs *engine)
2021 {
2022 	struct drm_i915_private *dev_priv = engine->i915;
2023 
2024 	intel_engine_set_hwsp_writemask(engine, ~0u); /* HWSTAM */
2025 
2026 	if (INTEL_GEN(dev_priv) >= 11)
2027 		I915_WRITE(RING_MODE_GEN7(engine),
2028 			   _MASKED_BIT_ENABLE(GEN11_GFX_DISABLE_LEGACY_MODE));
2029 	else
2030 		I915_WRITE(RING_MODE_GEN7(engine),
2031 			   _MASKED_BIT_ENABLE(GFX_RUN_LIST_ENABLE));
2032 
2033 	I915_WRITE(RING_MI_MODE(engine->mmio_base),
2034 		   _MASKED_BIT_DISABLE(STOP_RING));
2035 
2036 	I915_WRITE(RING_HWS_PGA(engine->mmio_base),
2037 		   i915_ggtt_offset(engine->status_page.vma));
2038 	POSTING_READ(RING_HWS_PGA(engine->mmio_base));
2039 }
2040 
2041 static bool unexpected_starting_state(struct intel_engine_cs *engine)
2042 {
2043 	struct drm_i915_private *dev_priv = engine->i915;
2044 	bool unexpected = false;
2045 
2046 	if (I915_READ(RING_MI_MODE(engine->mmio_base)) & STOP_RING) {
2047 		DRM_DEBUG_DRIVER("STOP_RING still set in RING_MI_MODE\n");
2048 		unexpected = true;
2049 	}
2050 
2051 	return unexpected;
2052 }
2053 
2054 static int execlists_resume(struct intel_engine_cs *engine)
2055 {
2056 	intel_engine_apply_workarounds(engine);
2057 	intel_engine_apply_whitelist(engine);
2058 
2059 	intel_mocs_init_engine(engine);
2060 
2061 	intel_engine_reset_breadcrumbs(engine);
2062 
2063 	if (GEM_SHOW_DEBUG() && unexpected_starting_state(engine)) {
2064 		struct drm_printer p = drm_debug_printer(__func__);
2065 
2066 		intel_engine_dump(engine, &p, NULL);
2067 	}
2068 
2069 	enable_execlists(engine);
2070 
2071 	return 0;
2072 }
2073 
2074 static void execlists_reset_prepare(struct intel_engine_cs *engine)
2075 {
2076 	struct intel_engine_execlists * const execlists = &engine->execlists;
2077 	unsigned long flags;
2078 
2079 	GEM_TRACE("%s: depth<-%d\n", engine->name,
2080 		  atomic_read(&execlists->tasklet.count));
2081 
2082 	/*
2083 	 * Prevent request submission to the hardware until we have
2084 	 * completed the reset in i915_gem_reset_finish(). If a request
2085 	 * is completed by one engine, it may then queue a request
2086 	 * to a second via its execlists->tasklet *just* as we are
2087 	 * calling engine->resume() and also writing the ELSP.
2088 	 * Turning off the execlists->tasklet until the reset is over
2089 	 * prevents the race.
2090 	 */
2091 	__tasklet_disable_sync_once(&execlists->tasklet);
2092 	GEM_BUG_ON(!reset_in_progress(execlists));
2093 
2094 	intel_engine_stop_cs(engine);
2095 
2096 	/* And flush any current direct submission. */
2097 	spin_lock_irqsave(&engine->timeline.lock, flags);
2098 	spin_unlock_irqrestore(&engine->timeline.lock, flags);
2099 }
2100 
2101 static bool lrc_regs_ok(const struct i915_request *rq)
2102 {
2103 	const struct intel_ring *ring = rq->ring;
2104 	const u32 *regs = rq->hw_context->lrc_reg_state;
2105 
2106 	/* Quick spot check for the common signs of context corruption */
2107 
2108 	if (regs[CTX_RING_BUFFER_CONTROL + 1] !=
2109 	    (RING_CTL_SIZE(ring->size) | RING_VALID))
2110 		return false;
2111 
2112 	if (regs[CTX_RING_BUFFER_START + 1] != i915_ggtt_offset(ring->vma))
2113 		return false;
2114 
2115 	return true;
2116 }
2117 
2118 static void reset_csb_pointers(struct intel_engine_execlists *execlists)
2119 {
2120 	const unsigned int reset_value = execlists->csb_size - 1;
2121 
2122 	/*
2123 	 * After a reset, the HW starts writing into CSB entry [0]. We
2124 	 * therefore have to set our HEAD pointer back one entry so that
2125 	 * the *first* entry we check is entry 0. To complicate this further,
2126 	 * as we don't wait for the first interrupt after reset, we have to
2127 	 * fake the HW write to point back to the last entry so that our
2128 	 * inline comparison of our cached head position against the last HW
2129 	 * write works even before the first interrupt.
2130 	 */
2131 	execlists->csb_head = reset_value;
2132 	WRITE_ONCE(*execlists->csb_write, reset_value);
2133 	wmb(); /* Make sure this is visible to HW (paranoia?) */
2134 
2135 	invalidate_csb_entries(&execlists->csb_status[0],
2136 			       &execlists->csb_status[reset_value]);
2137 }
2138 
2139 static struct i915_request *active_request(struct i915_request *rq)
2140 {
2141 	const struct list_head * const list = &rq->engine->timeline.requests;
2142 	const struct intel_context * const context = rq->hw_context;
2143 	struct i915_request *active = NULL;
2144 
2145 	list_for_each_entry_from_reverse(rq, list, link) {
2146 		if (i915_request_completed(rq))
2147 			break;
2148 
2149 		if (rq->hw_context != context)
2150 			break;
2151 
2152 		active = rq;
2153 	}
2154 
2155 	return active;
2156 }
2157 
2158 static void __execlists_reset(struct intel_engine_cs *engine, bool stalled)
2159 {
2160 	struct intel_engine_execlists * const execlists = &engine->execlists;
2161 	struct intel_context *ce;
2162 	struct i915_request *rq;
2163 	u32 *regs;
2164 
2165 	process_csb(engine); /* drain preemption events */
2166 
2167 	/* Following the reset, we need to reload the CSB read/write pointers */
2168 	reset_csb_pointers(&engine->execlists);
2169 
2170 	/*
2171 	 * Save the currently executing context, even if we completed
2172 	 * its request, it was still running at the time of the
2173 	 * reset and will have been clobbered.
2174 	 */
2175 	if (!port_isset(execlists->port))
2176 		goto out_clear;
2177 
2178 	rq = port_request(execlists->port);
2179 	ce = rq->hw_context;
2180 
2181 	/*
2182 	 * Catch up with any missed context-switch interrupts.
2183 	 *
2184 	 * Ideally we would just read the remaining CSB entries now that we
2185 	 * know the gpu is idle. However, the CSB registers are sometimes^W
2186 	 * often trashed across a GPU reset! Instead we have to rely on
2187 	 * guessing the missed context-switch events by looking at what
2188 	 * requests were completed.
2189 	 */
2190 	execlists_cancel_port_requests(execlists);
2191 
2192 	rq = active_request(rq);
2193 	if (!rq)
2194 		goto out_replay;
2195 
2196 	/*
2197 	 * If this request hasn't started yet, e.g. it is waiting on a
2198 	 * semaphore, we need to avoid skipping the request or else we
2199 	 * break the signaling chain. However, if the context is corrupt
2200 	 * the request will not restart and we will be stuck with a wedged
2201 	 * device. It is quite often the case that if we issue a reset
2202 	 * while the GPU is loading the context image, that the context
2203 	 * image becomes corrupt.
2204 	 *
2205 	 * Otherwise, if we have not started yet, the request should replay
2206 	 * perfectly and we do not need to flag the result as being erroneous.
2207 	 */
2208 	if (!i915_request_started(rq) && lrc_regs_ok(rq))
2209 		goto out_replay;
2210 
2211 	/*
2212 	 * If the request was innocent, we leave the request in the ELSP
2213 	 * and will try to replay it on restarting. The context image may
2214 	 * have been corrupted by the reset, in which case we may have
2215 	 * to service a new GPU hang, but more likely we can continue on
2216 	 * without impact.
2217 	 *
2218 	 * If the request was guilty, we presume the context is corrupt
2219 	 * and have to at least restore the RING register in the context
2220 	 * image back to the expected values to skip over the guilty request.
2221 	 */
2222 	i915_reset_request(rq, stalled);
2223 	if (!stalled && lrc_regs_ok(rq))
2224 		goto out_replay;
2225 
2226 	/*
2227 	 * We want a simple context + ring to execute the breadcrumb update.
2228 	 * We cannot rely on the context being intact across the GPU hang,
2229 	 * so clear it and rebuild just what we need for the breadcrumb.
2230 	 * All pending requests for this context will be zapped, and any
2231 	 * future request will be after userspace has had the opportunity
2232 	 * to recreate its own state.
2233 	 */
2234 	regs = ce->lrc_reg_state;
2235 	if (engine->pinned_default_state) {
2236 		memcpy(regs, /* skip restoring the vanilla PPHWSP */
2237 		       engine->pinned_default_state + LRC_STATE_PN * PAGE_SIZE,
2238 		       engine->context_size - PAGE_SIZE);
2239 	}
2240 	execlists_init_reg_state(regs, ce, engine, ce->ring);
2241 
2242 out_replay:
2243 	/* Rerun the request; its payload has been neutered (if guilty). */
2244 	ce->ring->head =
2245 		rq ? intel_ring_wrap(ce->ring, rq->head) : ce->ring->tail;
2246 	intel_ring_update_space(ce->ring);
2247 	__execlists_update_reg_state(ce, engine);
2248 
2249 	/* Push back any incomplete requests for replay after the reset. */
2250 	__unwind_incomplete_requests(engine);
2251 
2252 out_clear:
2253 	execlists_clear_all_active(execlists);
2254 }
2255 
2256 static void execlists_reset(struct intel_engine_cs *engine, bool stalled)
2257 {
2258 	unsigned long flags;
2259 
2260 	GEM_TRACE("%s\n", engine->name);
2261 
2262 	spin_lock_irqsave(&engine->timeline.lock, flags);
2263 
2264 	__execlists_reset(engine, stalled);
2265 
2266 	spin_unlock_irqrestore(&engine->timeline.lock, flags);
2267 }
2268 
2269 static void nop_submission_tasklet(unsigned long data)
2270 {
2271 	/* The driver is wedged; don't process any more events. */
2272 }
2273 
2274 static void execlists_cancel_requests(struct intel_engine_cs *engine)
2275 {
2276 	struct intel_engine_execlists * const execlists = &engine->execlists;
2277 	struct i915_request *rq, *rn;
2278 	struct rb_node *rb;
2279 	unsigned long flags;
2280 
2281 	GEM_TRACE("%s\n", engine->name);
2282 
2283 	/*
2284 	 * Before we call engine->cancel_requests(), we should have exclusive
2285 	 * access to the submission state. This is arranged for us by the
2286 	 * caller disabling the interrupt generation, the tasklet and other
2287 	 * threads that may then access the same state, giving us a free hand
2288 	 * to reset state. However, we still need to let lockdep be aware that
2289 	 * we know this state may be accessed in hardirq context, so we
2290 	 * disable the irq around this manipulation and we want to keep
2291 	 * the spinlock focused on its duties and not accidentally conflate
2292 	 * coverage to the submission's irq state. (Similarly, although we
2293 	 * shouldn't need to disable irq around the manipulation of the
2294 	 * submission's irq state, we also wish to remind ourselves that
2295 	 * it is irq state.)
2296 	 */
2297 	spin_lock_irqsave(&engine->timeline.lock, flags);
2298 
2299 	__execlists_reset(engine, true);
2300 
2301 	/* Mark all executing requests as skipped. */
2302 	list_for_each_entry(rq, &engine->timeline.requests, link) {
2303 		if (!i915_request_signaled(rq))
2304 			dma_fence_set_error(&rq->fence, -EIO);
2305 
2306 		i915_request_mark_complete(rq);
2307 	}
2308 
2309 	/* Flush the queued requests to the timeline list (for retiring). */
2310 	while ((rb = rb_first_cached(&execlists->queue))) {
2311 		struct i915_priolist *p = to_priolist(rb);
2312 		int i;
2313 
2314 		priolist_for_each_request_consume(rq, rn, p, i) {
2315 			list_del_init(&rq->sched.link);
2316 			__i915_request_submit(rq);
2317 			dma_fence_set_error(&rq->fence, -EIO);
2318 			i915_request_mark_complete(rq);
2319 		}
2320 
2321 		rb_erase_cached(&p->node, &execlists->queue);
2322 		i915_priolist_free(p);
2323 	}
2324 
2325 	/* Cancel all attached virtual engines */
2326 	while ((rb = rb_first_cached(&execlists->virtual))) {
2327 		struct virtual_engine *ve =
2328 			rb_entry(rb, typeof(*ve), nodes[engine->id].rb);
2329 
2330 		rb_erase_cached(rb, &execlists->virtual);
2331 		RB_CLEAR_NODE(rb);
2332 
2333 		spin_lock(&ve->base.timeline.lock);
2334 		if (ve->request) {
2335 			ve->request->engine = engine;
2336 			__i915_request_submit(ve->request);
2337 			dma_fence_set_error(&ve->request->fence, -EIO);
2338 			i915_request_mark_complete(ve->request);
2339 			ve->base.execlists.queue_priority_hint = INT_MIN;
2340 			ve->request = NULL;
2341 		}
2342 		spin_unlock(&ve->base.timeline.lock);
2343 	}
2344 
2345 	/* Remaining _unready_ requests will be nop'ed when submitted */
2346 
2347 	execlists->queue_priority_hint = INT_MIN;
2348 	execlists->queue = RB_ROOT_CACHED;
2349 	GEM_BUG_ON(port_isset(execlists->port));
2350 
2351 	GEM_BUG_ON(__tasklet_is_enabled(&execlists->tasklet));
2352 	execlists->tasklet.func = nop_submission_tasklet;
2353 
2354 	spin_unlock_irqrestore(&engine->timeline.lock, flags);
2355 }
2356 
2357 static void execlists_reset_finish(struct intel_engine_cs *engine)
2358 {
2359 	struct intel_engine_execlists * const execlists = &engine->execlists;
2360 
2361 	/*
2362 	 * After a GPU reset, we may have requests to replay. Do so now while
2363 	 * we still have the forcewake to be sure that the GPU is not allowed
2364 	 * to sleep before we restart and reload a context.
2365 	 */
2366 	GEM_BUG_ON(!reset_in_progress(execlists));
2367 	if (!RB_EMPTY_ROOT(&execlists->queue.rb_root))
2368 		execlists->tasklet.func(execlists->tasklet.data);
2369 
2370 	if (__tasklet_enable(&execlists->tasklet))
2371 		/* And kick in case we missed a new request submission. */
2372 		tasklet_hi_schedule(&execlists->tasklet);
2373 	GEM_TRACE("%s: depth->%d\n", engine->name,
2374 		  atomic_read(&execlists->tasklet.count));
2375 }
2376 
2377 static int gen8_emit_bb_start(struct i915_request *rq,
2378 			      u64 offset, u32 len,
2379 			      const unsigned int flags)
2380 {
2381 	u32 *cs;
2382 
2383 	cs = intel_ring_begin(rq, 4);
2384 	if (IS_ERR(cs))
2385 		return PTR_ERR(cs);
2386 
2387 	/*
2388 	 * WaDisableCtxRestoreArbitration:bdw,chv
2389 	 *
2390 	 * We don't need to perform MI_ARB_ENABLE as often as we do (in
2391 	 * particular all the gen that do not need the w/a at all!), if we
2392 	 * took care to make sure that on every switch into this context
2393 	 * (both ordinary and for preemption) that arbitrartion was enabled
2394 	 * we would be fine.  However, for gen8 there is another w/a that
2395 	 * requires us to not preempt inside GPGPU execution, so we keep
2396 	 * arbitration disabled for gen8 batches. Arbitration will be
2397 	 * re-enabled before we close the request
2398 	 * (engine->emit_fini_breadcrumb).
2399 	 */
2400 	*cs++ = MI_ARB_ON_OFF | MI_ARB_DISABLE;
2401 
2402 	/* FIXME(BDW+): Address space and security selectors. */
2403 	*cs++ = MI_BATCH_BUFFER_START_GEN8 |
2404 		(flags & I915_DISPATCH_SECURE ? 0 : BIT(8));
2405 	*cs++ = lower_32_bits(offset);
2406 	*cs++ = upper_32_bits(offset);
2407 
2408 	intel_ring_advance(rq, cs);
2409 
2410 	return 0;
2411 }
2412 
2413 static int gen9_emit_bb_start(struct i915_request *rq,
2414 			      u64 offset, u32 len,
2415 			      const unsigned int flags)
2416 {
2417 	u32 *cs;
2418 
2419 	cs = intel_ring_begin(rq, 6);
2420 	if (IS_ERR(cs))
2421 		return PTR_ERR(cs);
2422 
2423 	*cs++ = MI_ARB_ON_OFF | MI_ARB_ENABLE;
2424 
2425 	*cs++ = MI_BATCH_BUFFER_START_GEN8 |
2426 		(flags & I915_DISPATCH_SECURE ? 0 : BIT(8));
2427 	*cs++ = lower_32_bits(offset);
2428 	*cs++ = upper_32_bits(offset);
2429 
2430 	*cs++ = MI_ARB_ON_OFF | MI_ARB_DISABLE;
2431 	*cs++ = MI_NOOP;
2432 
2433 	intel_ring_advance(rq, cs);
2434 
2435 	return 0;
2436 }
2437 
2438 static void gen8_logical_ring_enable_irq(struct intel_engine_cs *engine)
2439 {
2440 	ENGINE_WRITE(engine, RING_IMR,
2441 		     ~(engine->irq_enable_mask | engine->irq_keep_mask));
2442 	ENGINE_POSTING_READ(engine, RING_IMR);
2443 }
2444 
2445 static void gen8_logical_ring_disable_irq(struct intel_engine_cs *engine)
2446 {
2447 	ENGINE_WRITE(engine, RING_IMR, ~engine->irq_keep_mask);
2448 }
2449 
2450 static int gen8_emit_flush(struct i915_request *request, u32 mode)
2451 {
2452 	u32 cmd, *cs;
2453 
2454 	cs = intel_ring_begin(request, 4);
2455 	if (IS_ERR(cs))
2456 		return PTR_ERR(cs);
2457 
2458 	cmd = MI_FLUSH_DW + 1;
2459 
2460 	/* We always require a command barrier so that subsequent
2461 	 * commands, such as breadcrumb interrupts, are strictly ordered
2462 	 * wrt the contents of the write cache being flushed to memory
2463 	 * (and thus being coherent from the CPU).
2464 	 */
2465 	cmd |= MI_FLUSH_DW_STORE_INDEX | MI_FLUSH_DW_OP_STOREDW;
2466 
2467 	if (mode & EMIT_INVALIDATE) {
2468 		cmd |= MI_INVALIDATE_TLB;
2469 		if (request->engine->class == VIDEO_DECODE_CLASS)
2470 			cmd |= MI_INVALIDATE_BSD;
2471 	}
2472 
2473 	*cs++ = cmd;
2474 	*cs++ = I915_GEM_HWS_SCRATCH_ADDR | MI_FLUSH_DW_USE_GTT;
2475 	*cs++ = 0; /* upper addr */
2476 	*cs++ = 0; /* value */
2477 	intel_ring_advance(request, cs);
2478 
2479 	return 0;
2480 }
2481 
2482 static int gen8_emit_flush_render(struct i915_request *request,
2483 				  u32 mode)
2484 {
2485 	struct intel_engine_cs *engine = request->engine;
2486 	u32 scratch_addr =
2487 		i915_scratch_offset(engine->i915) + 2 * CACHELINE_BYTES;
2488 	bool vf_flush_wa = false, dc_flush_wa = false;
2489 	u32 *cs, flags = 0;
2490 	int len;
2491 
2492 	flags |= PIPE_CONTROL_CS_STALL;
2493 
2494 	if (mode & EMIT_FLUSH) {
2495 		flags |= PIPE_CONTROL_RENDER_TARGET_CACHE_FLUSH;
2496 		flags |= PIPE_CONTROL_DEPTH_CACHE_FLUSH;
2497 		flags |= PIPE_CONTROL_DC_FLUSH_ENABLE;
2498 		flags |= PIPE_CONTROL_FLUSH_ENABLE;
2499 	}
2500 
2501 	if (mode & EMIT_INVALIDATE) {
2502 		flags |= PIPE_CONTROL_TLB_INVALIDATE;
2503 		flags |= PIPE_CONTROL_INSTRUCTION_CACHE_INVALIDATE;
2504 		flags |= PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE;
2505 		flags |= PIPE_CONTROL_VF_CACHE_INVALIDATE;
2506 		flags |= PIPE_CONTROL_CONST_CACHE_INVALIDATE;
2507 		flags |= PIPE_CONTROL_STATE_CACHE_INVALIDATE;
2508 		flags |= PIPE_CONTROL_QW_WRITE;
2509 		flags |= PIPE_CONTROL_GLOBAL_GTT_IVB;
2510 
2511 		/*
2512 		 * On GEN9: before VF_CACHE_INVALIDATE we need to emit a NULL
2513 		 * pipe control.
2514 		 */
2515 		if (IS_GEN(request->i915, 9))
2516 			vf_flush_wa = true;
2517 
2518 		/* WaForGAMHang:kbl */
2519 		if (IS_KBL_REVID(request->i915, 0, KBL_REVID_B0))
2520 			dc_flush_wa = true;
2521 	}
2522 
2523 	len = 6;
2524 
2525 	if (vf_flush_wa)
2526 		len += 6;
2527 
2528 	if (dc_flush_wa)
2529 		len += 12;
2530 
2531 	cs = intel_ring_begin(request, len);
2532 	if (IS_ERR(cs))
2533 		return PTR_ERR(cs);
2534 
2535 	if (vf_flush_wa)
2536 		cs = gen8_emit_pipe_control(cs, 0, 0);
2537 
2538 	if (dc_flush_wa)
2539 		cs = gen8_emit_pipe_control(cs, PIPE_CONTROL_DC_FLUSH_ENABLE,
2540 					    0);
2541 
2542 	cs = gen8_emit_pipe_control(cs, flags, scratch_addr);
2543 
2544 	if (dc_flush_wa)
2545 		cs = gen8_emit_pipe_control(cs, PIPE_CONTROL_CS_STALL, 0);
2546 
2547 	intel_ring_advance(request, cs);
2548 
2549 	return 0;
2550 }
2551 
2552 /*
2553  * Reserve space for 2 NOOPs at the end of each request to be
2554  * used as a workaround for not being allowed to do lite
2555  * restore with HEAD==TAIL (WaIdleLiteRestore).
2556  */
2557 static u32 *gen8_emit_wa_tail(struct i915_request *request, u32 *cs)
2558 {
2559 	/* Ensure there's always at least one preemption point per-request. */
2560 	*cs++ = MI_ARB_CHECK;
2561 	*cs++ = MI_NOOP;
2562 	request->wa_tail = intel_ring_offset(request, cs);
2563 
2564 	return cs;
2565 }
2566 
2567 static u32 *gen8_emit_fini_breadcrumb(struct i915_request *request, u32 *cs)
2568 {
2569 	cs = gen8_emit_ggtt_write(cs,
2570 				  request->fence.seqno,
2571 				  request->timeline->hwsp_offset,
2572 				  0);
2573 
2574 	*cs++ = MI_USER_INTERRUPT;
2575 	*cs++ = MI_ARB_ON_OFF | MI_ARB_ENABLE;
2576 
2577 	request->tail = intel_ring_offset(request, cs);
2578 	assert_ring_tail_valid(request->ring, request->tail);
2579 
2580 	return gen8_emit_wa_tail(request, cs);
2581 }
2582 
2583 static u32 *gen8_emit_fini_breadcrumb_rcs(struct i915_request *request, u32 *cs)
2584 {
2585 	/* XXX flush+write+CS_STALL all in one upsets gem_concurrent_blt:kbl */
2586 	cs = gen8_emit_ggtt_write_rcs(cs,
2587 				      request->fence.seqno,
2588 				      request->timeline->hwsp_offset,
2589 				      PIPE_CONTROL_RENDER_TARGET_CACHE_FLUSH |
2590 				      PIPE_CONTROL_DEPTH_CACHE_FLUSH |
2591 				      PIPE_CONTROL_DC_FLUSH_ENABLE);
2592 	cs = gen8_emit_pipe_control(cs,
2593 				    PIPE_CONTROL_FLUSH_ENABLE |
2594 				    PIPE_CONTROL_CS_STALL,
2595 				    0);
2596 
2597 	*cs++ = MI_USER_INTERRUPT;
2598 	*cs++ = MI_ARB_ON_OFF | MI_ARB_ENABLE;
2599 
2600 	request->tail = intel_ring_offset(request, cs);
2601 	assert_ring_tail_valid(request->ring, request->tail);
2602 
2603 	return gen8_emit_wa_tail(request, cs);
2604 }
2605 
2606 static int gen8_init_rcs_context(struct i915_request *rq)
2607 {
2608 	int ret;
2609 
2610 	ret = intel_engine_emit_ctx_wa(rq);
2611 	if (ret)
2612 		return ret;
2613 
2614 	ret = intel_rcs_context_init_mocs(rq);
2615 	/*
2616 	 * Failing to program the MOCS is non-fatal.The system will not
2617 	 * run at peak performance. So generate an error and carry on.
2618 	 */
2619 	if (ret)
2620 		DRM_ERROR("MOCS failed to program: expect performance issues.\n");
2621 
2622 	return i915_gem_render_state_emit(rq);
2623 }
2624 
2625 static void execlists_park(struct intel_engine_cs *engine)
2626 {
2627 	intel_engine_park(engine);
2628 }
2629 
2630 void intel_execlists_set_default_submission(struct intel_engine_cs *engine)
2631 {
2632 	engine->submit_request = execlists_submit_request;
2633 	engine->cancel_requests = execlists_cancel_requests;
2634 	engine->schedule = i915_schedule;
2635 	engine->execlists.tasklet.func = execlists_submission_tasklet;
2636 
2637 	engine->reset.prepare = execlists_reset_prepare;
2638 	engine->reset.reset = execlists_reset;
2639 	engine->reset.finish = execlists_reset_finish;
2640 
2641 	engine->park = execlists_park;
2642 	engine->unpark = NULL;
2643 
2644 	engine->flags |= I915_ENGINE_SUPPORTS_STATS;
2645 	if (!intel_vgpu_active(engine->i915))
2646 		engine->flags |= I915_ENGINE_HAS_SEMAPHORES;
2647 	if (engine->preempt_context &&
2648 	    HAS_LOGICAL_RING_PREEMPTION(engine->i915))
2649 		engine->flags |= I915_ENGINE_HAS_PREEMPTION;
2650 }
2651 
2652 static void execlists_destroy(struct intel_engine_cs *engine)
2653 {
2654 	intel_engine_cleanup_common(engine);
2655 	lrc_destroy_wa_ctx(engine);
2656 	kfree(engine);
2657 }
2658 
2659 static void
2660 logical_ring_default_vfuncs(struct intel_engine_cs *engine)
2661 {
2662 	/* Default vfuncs which can be overriden by each engine. */
2663 
2664 	engine->destroy = execlists_destroy;
2665 	engine->resume = execlists_resume;
2666 
2667 	engine->reset.prepare = execlists_reset_prepare;
2668 	engine->reset.reset = execlists_reset;
2669 	engine->reset.finish = execlists_reset_finish;
2670 
2671 	engine->cops = &execlists_context_ops;
2672 	engine->request_alloc = execlists_request_alloc;
2673 
2674 	engine->emit_flush = gen8_emit_flush;
2675 	engine->emit_init_breadcrumb = gen8_emit_init_breadcrumb;
2676 	engine->emit_fini_breadcrumb = gen8_emit_fini_breadcrumb;
2677 
2678 	engine->set_default_submission = intel_execlists_set_default_submission;
2679 
2680 	if (INTEL_GEN(engine->i915) < 11) {
2681 		engine->irq_enable = gen8_logical_ring_enable_irq;
2682 		engine->irq_disable = gen8_logical_ring_disable_irq;
2683 	} else {
2684 		/*
2685 		 * TODO: On Gen11 interrupt masks need to be clear
2686 		 * to allow C6 entry. Keep interrupts enabled at
2687 		 * and take the hit of generating extra interrupts
2688 		 * until a more refined solution exists.
2689 		 */
2690 	}
2691 	if (IS_GEN(engine->i915, 8))
2692 		engine->emit_bb_start = gen8_emit_bb_start;
2693 	else
2694 		engine->emit_bb_start = gen9_emit_bb_start;
2695 }
2696 
2697 static inline void
2698 logical_ring_default_irqs(struct intel_engine_cs *engine)
2699 {
2700 	unsigned int shift = 0;
2701 
2702 	if (INTEL_GEN(engine->i915) < 11) {
2703 		const u8 irq_shifts[] = {
2704 			[RCS0]  = GEN8_RCS_IRQ_SHIFT,
2705 			[BCS0]  = GEN8_BCS_IRQ_SHIFT,
2706 			[VCS0]  = GEN8_VCS0_IRQ_SHIFT,
2707 			[VCS1]  = GEN8_VCS1_IRQ_SHIFT,
2708 			[VECS0] = GEN8_VECS_IRQ_SHIFT,
2709 		};
2710 
2711 		shift = irq_shifts[engine->id];
2712 	}
2713 
2714 	engine->irq_enable_mask = GT_RENDER_USER_INTERRUPT << shift;
2715 	engine->irq_keep_mask = GT_CONTEXT_SWITCH_INTERRUPT << shift;
2716 }
2717 
2718 int intel_execlists_submission_setup(struct intel_engine_cs *engine)
2719 {
2720 	/* Intentionally left blank. */
2721 	engine->buffer = NULL;
2722 
2723 	tasklet_init(&engine->execlists.tasklet,
2724 		     execlists_submission_tasklet, (unsigned long)engine);
2725 
2726 	logical_ring_default_vfuncs(engine);
2727 	logical_ring_default_irqs(engine);
2728 
2729 	if (engine->class == RENDER_CLASS) {
2730 		engine->init_context = gen8_init_rcs_context;
2731 		engine->emit_flush = gen8_emit_flush_render;
2732 		engine->emit_fini_breadcrumb = gen8_emit_fini_breadcrumb_rcs;
2733 	}
2734 
2735 	return 0;
2736 }
2737 
2738 int intel_execlists_submission_init(struct intel_engine_cs *engine)
2739 {
2740 	struct drm_i915_private *i915 = engine->i915;
2741 	struct intel_engine_execlists * const execlists = &engine->execlists;
2742 	u32 base = engine->mmio_base;
2743 	int ret;
2744 
2745 	ret = intel_engine_init_common(engine);
2746 	if (ret)
2747 		return ret;
2748 
2749 	intel_engine_init_workarounds(engine);
2750 	intel_engine_init_whitelist(engine);
2751 
2752 	if (intel_init_workaround_bb(engine))
2753 		/*
2754 		 * We continue even if we fail to initialize WA batch
2755 		 * because we only expect rare glitches but nothing
2756 		 * critical to prevent us from using GPU
2757 		 */
2758 		DRM_ERROR("WA batch buffer initialization failed\n");
2759 
2760 	if (HAS_LOGICAL_RING_ELSQ(i915)) {
2761 		execlists->submit_reg = i915->uncore.regs +
2762 			i915_mmio_reg_offset(RING_EXECLIST_SQ_CONTENTS(base));
2763 		execlists->ctrl_reg = i915->uncore.regs +
2764 			i915_mmio_reg_offset(RING_EXECLIST_CONTROL(base));
2765 	} else {
2766 		execlists->submit_reg = i915->uncore.regs +
2767 			i915_mmio_reg_offset(RING_ELSP(base));
2768 	}
2769 
2770 	execlists->preempt_complete_status = ~0u;
2771 	if (engine->preempt_context)
2772 		execlists->preempt_complete_status =
2773 			upper_32_bits(engine->preempt_context->lrc_desc);
2774 
2775 	execlists->csb_status =
2776 		&engine->status_page.addr[I915_HWS_CSB_BUF0_INDEX];
2777 
2778 	execlists->csb_write =
2779 		&engine->status_page.addr[intel_hws_csb_write_index(i915)];
2780 
2781 	if (INTEL_GEN(engine->i915) < 11)
2782 		execlists->csb_size = GEN8_CSB_ENTRIES;
2783 	else
2784 		execlists->csb_size = GEN11_CSB_ENTRIES;
2785 
2786 	reset_csb_pointers(execlists);
2787 
2788 	return 0;
2789 }
2790 
2791 static u32 intel_lr_indirect_ctx_offset(struct intel_engine_cs *engine)
2792 {
2793 	u32 indirect_ctx_offset;
2794 
2795 	switch (INTEL_GEN(engine->i915)) {
2796 	default:
2797 		MISSING_CASE(INTEL_GEN(engine->i915));
2798 		/* fall through */
2799 	case 11:
2800 		indirect_ctx_offset =
2801 			GEN11_CTX_RCS_INDIRECT_CTX_OFFSET_DEFAULT;
2802 		break;
2803 	case 10:
2804 		indirect_ctx_offset =
2805 			GEN10_CTX_RCS_INDIRECT_CTX_OFFSET_DEFAULT;
2806 		break;
2807 	case 9:
2808 		indirect_ctx_offset =
2809 			GEN9_CTX_RCS_INDIRECT_CTX_OFFSET_DEFAULT;
2810 		break;
2811 	case 8:
2812 		indirect_ctx_offset =
2813 			GEN8_CTX_RCS_INDIRECT_CTX_OFFSET_DEFAULT;
2814 		break;
2815 	}
2816 
2817 	return indirect_ctx_offset;
2818 }
2819 
2820 static void execlists_init_reg_state(u32 *regs,
2821 				     struct intel_context *ce,
2822 				     struct intel_engine_cs *engine,
2823 				     struct intel_ring *ring)
2824 {
2825 	struct i915_hw_ppgtt *ppgtt = ce->gem_context->ppgtt;
2826 	bool rcs = engine->class == RENDER_CLASS;
2827 	u32 base = engine->mmio_base;
2828 
2829 	/*
2830 	 * A context is actually a big batch buffer with several
2831 	 * MI_LOAD_REGISTER_IMM commands followed by (reg, value) pairs. The
2832 	 * values we are setting here are only for the first context restore:
2833 	 * on a subsequent save, the GPU will recreate this batchbuffer with new
2834 	 * values (including all the missing MI_LOAD_REGISTER_IMM commands that
2835 	 * we are not initializing here).
2836 	 *
2837 	 * Must keep consistent with virtual_update_register_offsets().
2838 	 */
2839 	regs[CTX_LRI_HEADER_0] = MI_LOAD_REGISTER_IMM(rcs ? 14 : 11) |
2840 				 MI_LRI_FORCE_POSTED;
2841 
2842 	CTX_REG(regs, CTX_CONTEXT_CONTROL, RING_CONTEXT_CONTROL(base),
2843 		_MASKED_BIT_DISABLE(CTX_CTRL_ENGINE_CTX_RESTORE_INHIBIT) |
2844 		_MASKED_BIT_ENABLE(CTX_CTRL_INHIBIT_SYN_CTX_SWITCH));
2845 	if (INTEL_GEN(engine->i915) < 11) {
2846 		regs[CTX_CONTEXT_CONTROL + 1] |=
2847 			_MASKED_BIT_DISABLE(CTX_CTRL_ENGINE_CTX_SAVE_INHIBIT |
2848 					    CTX_CTRL_RS_CTX_ENABLE);
2849 	}
2850 	CTX_REG(regs, CTX_RING_HEAD, RING_HEAD(base), 0);
2851 	CTX_REG(regs, CTX_RING_TAIL, RING_TAIL(base), 0);
2852 	CTX_REG(regs, CTX_RING_BUFFER_START, RING_START(base), 0);
2853 	CTX_REG(regs, CTX_RING_BUFFER_CONTROL, RING_CTL(base),
2854 		RING_CTL_SIZE(ring->size) | RING_VALID);
2855 	CTX_REG(regs, CTX_BB_HEAD_U, RING_BBADDR_UDW(base), 0);
2856 	CTX_REG(regs, CTX_BB_HEAD_L, RING_BBADDR(base), 0);
2857 	CTX_REG(regs, CTX_BB_STATE, RING_BBSTATE(base), RING_BB_PPGTT);
2858 	CTX_REG(regs, CTX_SECOND_BB_HEAD_U, RING_SBBADDR_UDW(base), 0);
2859 	CTX_REG(regs, CTX_SECOND_BB_HEAD_L, RING_SBBADDR(base), 0);
2860 	CTX_REG(regs, CTX_SECOND_BB_STATE, RING_SBBSTATE(base), 0);
2861 	if (rcs) {
2862 		struct i915_ctx_workarounds *wa_ctx = &engine->wa_ctx;
2863 
2864 		CTX_REG(regs, CTX_RCS_INDIRECT_CTX, RING_INDIRECT_CTX(base), 0);
2865 		CTX_REG(regs, CTX_RCS_INDIRECT_CTX_OFFSET,
2866 			RING_INDIRECT_CTX_OFFSET(base), 0);
2867 		if (wa_ctx->indirect_ctx.size) {
2868 			u32 ggtt_offset = i915_ggtt_offset(wa_ctx->vma);
2869 
2870 			regs[CTX_RCS_INDIRECT_CTX + 1] =
2871 				(ggtt_offset + wa_ctx->indirect_ctx.offset) |
2872 				(wa_ctx->indirect_ctx.size / CACHELINE_BYTES);
2873 
2874 			regs[CTX_RCS_INDIRECT_CTX_OFFSET + 1] =
2875 				intel_lr_indirect_ctx_offset(engine) << 6;
2876 		}
2877 
2878 		CTX_REG(regs, CTX_BB_PER_CTX_PTR, RING_BB_PER_CTX_PTR(base), 0);
2879 		if (wa_ctx->per_ctx.size) {
2880 			u32 ggtt_offset = i915_ggtt_offset(wa_ctx->vma);
2881 
2882 			regs[CTX_BB_PER_CTX_PTR + 1] =
2883 				(ggtt_offset + wa_ctx->per_ctx.offset) | 0x01;
2884 		}
2885 	}
2886 
2887 	regs[CTX_LRI_HEADER_1] = MI_LOAD_REGISTER_IMM(9) | MI_LRI_FORCE_POSTED;
2888 
2889 	CTX_REG(regs, CTX_CTX_TIMESTAMP, RING_CTX_TIMESTAMP(base), 0);
2890 	/* PDP values well be assigned later if needed */
2891 	CTX_REG(regs, CTX_PDP3_UDW, GEN8_RING_PDP_UDW(base, 3), 0);
2892 	CTX_REG(regs, CTX_PDP3_LDW, GEN8_RING_PDP_LDW(base, 3), 0);
2893 	CTX_REG(regs, CTX_PDP2_UDW, GEN8_RING_PDP_UDW(base, 2), 0);
2894 	CTX_REG(regs, CTX_PDP2_LDW, GEN8_RING_PDP_LDW(base, 2), 0);
2895 	CTX_REG(regs, CTX_PDP1_UDW, GEN8_RING_PDP_UDW(base, 1), 0);
2896 	CTX_REG(regs, CTX_PDP1_LDW, GEN8_RING_PDP_LDW(base, 1), 0);
2897 	CTX_REG(regs, CTX_PDP0_UDW, GEN8_RING_PDP_UDW(base, 0), 0);
2898 	CTX_REG(regs, CTX_PDP0_LDW, GEN8_RING_PDP_LDW(base, 0), 0);
2899 
2900 	if (i915_vm_is_4lvl(&ppgtt->vm)) {
2901 		/* 64b PPGTT (48bit canonical)
2902 		 * PDP0_DESCRIPTOR contains the base address to PML4 and
2903 		 * other PDP Descriptors are ignored.
2904 		 */
2905 		ASSIGN_CTX_PML4(ppgtt, regs);
2906 	} else {
2907 		ASSIGN_CTX_PDP(ppgtt, regs, 3);
2908 		ASSIGN_CTX_PDP(ppgtt, regs, 2);
2909 		ASSIGN_CTX_PDP(ppgtt, regs, 1);
2910 		ASSIGN_CTX_PDP(ppgtt, regs, 0);
2911 	}
2912 
2913 	if (rcs) {
2914 		regs[CTX_LRI_HEADER_2] = MI_LOAD_REGISTER_IMM(1);
2915 		CTX_REG(regs, CTX_R_PWR_CLK_STATE, GEN8_R_PWR_CLK_STATE, 0);
2916 
2917 		i915_oa_init_reg_state(engine, ce, regs);
2918 	}
2919 
2920 	regs[CTX_END] = MI_BATCH_BUFFER_END;
2921 	if (INTEL_GEN(engine->i915) >= 10)
2922 		regs[CTX_END] |= BIT(0);
2923 }
2924 
2925 static int
2926 populate_lr_context(struct intel_context *ce,
2927 		    struct drm_i915_gem_object *ctx_obj,
2928 		    struct intel_engine_cs *engine,
2929 		    struct intel_ring *ring)
2930 {
2931 	void *vaddr;
2932 	u32 *regs;
2933 	int ret;
2934 
2935 	vaddr = i915_gem_object_pin_map(ctx_obj, I915_MAP_WB);
2936 	if (IS_ERR(vaddr)) {
2937 		ret = PTR_ERR(vaddr);
2938 		DRM_DEBUG_DRIVER("Could not map object pages! (%d)\n", ret);
2939 		return ret;
2940 	}
2941 
2942 	if (engine->default_state) {
2943 		/*
2944 		 * We only want to copy over the template context state;
2945 		 * skipping over the headers reserved for GuC communication,
2946 		 * leaving those as zero.
2947 		 */
2948 		const unsigned long start = LRC_HEADER_PAGES * PAGE_SIZE;
2949 		void *defaults;
2950 
2951 		defaults = i915_gem_object_pin_map(engine->default_state,
2952 						   I915_MAP_WB);
2953 		if (IS_ERR(defaults)) {
2954 			ret = PTR_ERR(defaults);
2955 			goto err_unpin_ctx;
2956 		}
2957 
2958 		memcpy(vaddr + start, defaults + start, engine->context_size);
2959 		i915_gem_object_unpin_map(engine->default_state);
2960 	}
2961 
2962 	/* The second page of the context object contains some fields which must
2963 	 * be set up prior to the first execution. */
2964 	regs = vaddr + LRC_STATE_PN * PAGE_SIZE;
2965 	execlists_init_reg_state(regs, ce, engine, ring);
2966 	if (!engine->default_state)
2967 		regs[CTX_CONTEXT_CONTROL + 1] |=
2968 			_MASKED_BIT_ENABLE(CTX_CTRL_ENGINE_CTX_RESTORE_INHIBIT);
2969 	if (ce->gem_context == engine->i915->preempt_context &&
2970 	    INTEL_GEN(engine->i915) < 11)
2971 		regs[CTX_CONTEXT_CONTROL + 1] |=
2972 			_MASKED_BIT_ENABLE(CTX_CTRL_ENGINE_CTX_RESTORE_INHIBIT |
2973 					   CTX_CTRL_ENGINE_CTX_SAVE_INHIBIT);
2974 
2975 	ret = 0;
2976 err_unpin_ctx:
2977 	__i915_gem_object_flush_map(ctx_obj,
2978 				    LRC_HEADER_PAGES * PAGE_SIZE,
2979 				    engine->context_size);
2980 	i915_gem_object_unpin_map(ctx_obj);
2981 	return ret;
2982 }
2983 
2984 static struct i915_timeline *get_timeline(struct i915_gem_context *ctx)
2985 {
2986 	if (ctx->timeline)
2987 		return i915_timeline_get(ctx->timeline);
2988 	else
2989 		return i915_timeline_create(ctx->i915, NULL);
2990 }
2991 
2992 static int execlists_context_deferred_alloc(struct intel_context *ce,
2993 					    struct intel_engine_cs *engine)
2994 {
2995 	struct drm_i915_gem_object *ctx_obj;
2996 	struct i915_vma *vma;
2997 	u32 context_size;
2998 	struct intel_ring *ring;
2999 	struct i915_timeline *timeline;
3000 	int ret;
3001 
3002 	if (ce->state)
3003 		return 0;
3004 
3005 	context_size = round_up(engine->context_size, I915_GTT_PAGE_SIZE);
3006 
3007 	/*
3008 	 * Before the actual start of the context image, we insert a few pages
3009 	 * for our own use and for sharing with the GuC.
3010 	 */
3011 	context_size += LRC_HEADER_PAGES * PAGE_SIZE;
3012 
3013 	ctx_obj = i915_gem_object_create(engine->i915, context_size);
3014 	if (IS_ERR(ctx_obj))
3015 		return PTR_ERR(ctx_obj);
3016 
3017 	vma = i915_vma_instance(ctx_obj, &engine->i915->ggtt.vm, NULL);
3018 	if (IS_ERR(vma)) {
3019 		ret = PTR_ERR(vma);
3020 		goto error_deref_obj;
3021 	}
3022 
3023 	timeline = get_timeline(ce->gem_context);
3024 	if (IS_ERR(timeline)) {
3025 		ret = PTR_ERR(timeline);
3026 		goto error_deref_obj;
3027 	}
3028 
3029 	ring = intel_engine_create_ring(engine,
3030 					timeline,
3031 					ce->gem_context->ring_size);
3032 	i915_timeline_put(timeline);
3033 	if (IS_ERR(ring)) {
3034 		ret = PTR_ERR(ring);
3035 		goto error_deref_obj;
3036 	}
3037 
3038 	ret = populate_lr_context(ce, ctx_obj, engine, ring);
3039 	if (ret) {
3040 		DRM_DEBUG_DRIVER("Failed to populate LRC: %d\n", ret);
3041 		goto error_ring_free;
3042 	}
3043 
3044 	ce->ring = ring;
3045 	ce->state = vma;
3046 
3047 	return 0;
3048 
3049 error_ring_free:
3050 	intel_ring_put(ring);
3051 error_deref_obj:
3052 	i915_gem_object_put(ctx_obj);
3053 	return ret;
3054 }
3055 
3056 static void virtual_context_destroy(struct kref *kref)
3057 {
3058 	struct virtual_engine *ve =
3059 		container_of(kref, typeof(*ve), context.ref);
3060 	unsigned int n;
3061 
3062 	GEM_BUG_ON(ve->request);
3063 	GEM_BUG_ON(ve->context.active);
3064 
3065 	for (n = 0; n < ve->num_siblings; n++) {
3066 		struct intel_engine_cs *sibling = ve->siblings[n];
3067 		struct rb_node *node = &ve->nodes[sibling->id].rb;
3068 
3069 		if (RB_EMPTY_NODE(node))
3070 			continue;
3071 
3072 		spin_lock_irq(&sibling->timeline.lock);
3073 
3074 		/* Detachment is lazily performed in the execlists tasklet */
3075 		if (!RB_EMPTY_NODE(node))
3076 			rb_erase_cached(node, &sibling->execlists.virtual);
3077 
3078 		spin_unlock_irq(&sibling->timeline.lock);
3079 	}
3080 	GEM_BUG_ON(__tasklet_is_scheduled(&ve->base.execlists.tasklet));
3081 
3082 	if (ve->context.state)
3083 		__execlists_context_fini(&ve->context);
3084 
3085 	kfree(ve->bonds);
3086 
3087 	i915_timeline_fini(&ve->base.timeline);
3088 	kfree(ve);
3089 }
3090 
3091 static void virtual_engine_initial_hint(struct virtual_engine *ve)
3092 {
3093 	int swp;
3094 
3095 	/*
3096 	 * Pick a random sibling on starting to help spread the load around.
3097 	 *
3098 	 * New contexts are typically created with exactly the same order
3099 	 * of siblings, and often started in batches. Due to the way we iterate
3100 	 * the array of sibling when submitting requests, sibling[0] is
3101 	 * prioritised for dequeuing. If we make sure that sibling[0] is fairly
3102 	 * randomised across the system, we also help spread the load by the
3103 	 * first engine we inspect being different each time.
3104 	 *
3105 	 * NB This does not force us to execute on this engine, it will just
3106 	 * typically be the first we inspect for submission.
3107 	 */
3108 	swp = prandom_u32_max(ve->num_siblings);
3109 	if (!swp)
3110 		return;
3111 
3112 	swap(ve->siblings[swp], ve->siblings[0]);
3113 	virtual_update_register_offsets(ve->context.lrc_reg_state,
3114 					ve->siblings[0]);
3115 }
3116 
3117 static int virtual_context_pin(struct intel_context *ce)
3118 {
3119 	struct virtual_engine *ve = container_of(ce, typeof(*ve), context);
3120 	int err;
3121 
3122 	/* Note: we must use a real engine class for setting up reg state */
3123 	err = __execlists_context_pin(ce, ve->siblings[0]);
3124 	if (err)
3125 		return err;
3126 
3127 	virtual_engine_initial_hint(ve);
3128 	return 0;
3129 }
3130 
3131 static void virtual_context_enter(struct intel_context *ce)
3132 {
3133 	struct virtual_engine *ve = container_of(ce, typeof(*ve), context);
3134 	unsigned int n;
3135 
3136 	for (n = 0; n < ve->num_siblings; n++)
3137 		intel_engine_pm_get(ve->siblings[n]);
3138 }
3139 
3140 static void virtual_context_exit(struct intel_context *ce)
3141 {
3142 	struct virtual_engine *ve = container_of(ce, typeof(*ve), context);
3143 	unsigned int n;
3144 
3145 	ce->saturated = 0;
3146 	for (n = 0; n < ve->num_siblings; n++)
3147 		intel_engine_pm_put(ve->siblings[n]);
3148 }
3149 
3150 static const struct intel_context_ops virtual_context_ops = {
3151 	.pin = virtual_context_pin,
3152 	.unpin = execlists_context_unpin,
3153 
3154 	.enter = virtual_context_enter,
3155 	.exit = virtual_context_exit,
3156 
3157 	.destroy = virtual_context_destroy,
3158 };
3159 
3160 static intel_engine_mask_t virtual_submission_mask(struct virtual_engine *ve)
3161 {
3162 	struct i915_request *rq;
3163 	intel_engine_mask_t mask;
3164 
3165 	rq = READ_ONCE(ve->request);
3166 	if (!rq)
3167 		return 0;
3168 
3169 	/* The rq is ready for submission; rq->execution_mask is now stable. */
3170 	mask = rq->execution_mask;
3171 	if (unlikely(!mask)) {
3172 		/* Invalid selection, submit to a random engine in error */
3173 		i915_request_skip(rq, -ENODEV);
3174 		mask = ve->siblings[0]->mask;
3175 	}
3176 
3177 	GEM_TRACE("%s: rq=%llx:%lld, mask=%x, prio=%d\n",
3178 		  ve->base.name,
3179 		  rq->fence.context, rq->fence.seqno,
3180 		  mask, ve->base.execlists.queue_priority_hint);
3181 
3182 	return mask;
3183 }
3184 
3185 static void virtual_submission_tasklet(unsigned long data)
3186 {
3187 	struct virtual_engine * const ve = (struct virtual_engine *)data;
3188 	const int prio = ve->base.execlists.queue_priority_hint;
3189 	intel_engine_mask_t mask;
3190 	unsigned int n;
3191 
3192 	rcu_read_lock();
3193 	mask = virtual_submission_mask(ve);
3194 	rcu_read_unlock();
3195 	if (unlikely(!mask))
3196 		return;
3197 
3198 	local_irq_disable();
3199 	for (n = 0; READ_ONCE(ve->request) && n < ve->num_siblings; n++) {
3200 		struct intel_engine_cs *sibling = ve->siblings[n];
3201 		struct ve_node * const node = &ve->nodes[sibling->id];
3202 		struct rb_node **parent, *rb;
3203 		bool first;
3204 
3205 		if (unlikely(!(mask & sibling->mask))) {
3206 			if (!RB_EMPTY_NODE(&node->rb)) {
3207 				spin_lock(&sibling->timeline.lock);
3208 				rb_erase_cached(&node->rb,
3209 						&sibling->execlists.virtual);
3210 				RB_CLEAR_NODE(&node->rb);
3211 				spin_unlock(&sibling->timeline.lock);
3212 			}
3213 			continue;
3214 		}
3215 
3216 		spin_lock(&sibling->timeline.lock);
3217 
3218 		if (!RB_EMPTY_NODE(&node->rb)) {
3219 			/*
3220 			 * Cheat and avoid rebalancing the tree if we can
3221 			 * reuse this node in situ.
3222 			 */
3223 			first = rb_first_cached(&sibling->execlists.virtual) ==
3224 				&node->rb;
3225 			if (prio == node->prio || (prio > node->prio && first))
3226 				goto submit_engine;
3227 
3228 			rb_erase_cached(&node->rb, &sibling->execlists.virtual);
3229 		}
3230 
3231 		rb = NULL;
3232 		first = true;
3233 		parent = &sibling->execlists.virtual.rb_root.rb_node;
3234 		while (*parent) {
3235 			struct ve_node *other;
3236 
3237 			rb = *parent;
3238 			other = rb_entry(rb, typeof(*other), rb);
3239 			if (prio > other->prio) {
3240 				parent = &rb->rb_left;
3241 			} else {
3242 				parent = &rb->rb_right;
3243 				first = false;
3244 			}
3245 		}
3246 
3247 		rb_link_node(&node->rb, rb, parent);
3248 		rb_insert_color_cached(&node->rb,
3249 				       &sibling->execlists.virtual,
3250 				       first);
3251 
3252 submit_engine:
3253 		GEM_BUG_ON(RB_EMPTY_NODE(&node->rb));
3254 		node->prio = prio;
3255 		if (first && prio > sibling->execlists.queue_priority_hint) {
3256 			sibling->execlists.queue_priority_hint = prio;
3257 			tasklet_hi_schedule(&sibling->execlists.tasklet);
3258 		}
3259 
3260 		spin_unlock(&sibling->timeline.lock);
3261 	}
3262 	local_irq_enable();
3263 }
3264 
3265 static void virtual_submit_request(struct i915_request *rq)
3266 {
3267 	struct virtual_engine *ve = to_virtual_engine(rq->engine);
3268 
3269 	GEM_TRACE("%s: rq=%llx:%lld\n",
3270 		  ve->base.name,
3271 		  rq->fence.context,
3272 		  rq->fence.seqno);
3273 
3274 	GEM_BUG_ON(ve->base.submit_request != virtual_submit_request);
3275 
3276 	GEM_BUG_ON(ve->request);
3277 	ve->base.execlists.queue_priority_hint = rq_prio(rq);
3278 	WRITE_ONCE(ve->request, rq);
3279 
3280 	tasklet_schedule(&ve->base.execlists.tasklet);
3281 }
3282 
3283 static struct ve_bond *
3284 virtual_find_bond(struct virtual_engine *ve,
3285 		  const struct intel_engine_cs *master)
3286 {
3287 	int i;
3288 
3289 	for (i = 0; i < ve->num_bonds; i++) {
3290 		if (ve->bonds[i].master == master)
3291 			return &ve->bonds[i];
3292 	}
3293 
3294 	return NULL;
3295 }
3296 
3297 static void
3298 virtual_bond_execute(struct i915_request *rq, struct dma_fence *signal)
3299 {
3300 	struct virtual_engine *ve = to_virtual_engine(rq->engine);
3301 	struct ve_bond *bond;
3302 
3303 	bond = virtual_find_bond(ve, to_request(signal)->engine);
3304 	if (bond) {
3305 		intel_engine_mask_t old, new, cmp;
3306 
3307 		cmp = READ_ONCE(rq->execution_mask);
3308 		do {
3309 			old = cmp;
3310 			new = cmp & bond->sibling_mask;
3311 		} while ((cmp = cmpxchg(&rq->execution_mask, old, new)) != old);
3312 	}
3313 }
3314 
3315 struct intel_context *
3316 intel_execlists_create_virtual(struct i915_gem_context *ctx,
3317 			       struct intel_engine_cs **siblings,
3318 			       unsigned int count)
3319 {
3320 	struct virtual_engine *ve;
3321 	unsigned int n;
3322 	int err;
3323 
3324 	if (count == 0)
3325 		return ERR_PTR(-EINVAL);
3326 
3327 	if (count == 1)
3328 		return intel_context_create(ctx, siblings[0]);
3329 
3330 	ve = kzalloc(struct_size(ve, siblings, count), GFP_KERNEL);
3331 	if (!ve)
3332 		return ERR_PTR(-ENOMEM);
3333 
3334 	ve->base.i915 = ctx->i915;
3335 	ve->base.id = -1;
3336 	ve->base.class = OTHER_CLASS;
3337 	ve->base.uabi_class = I915_ENGINE_CLASS_INVALID;
3338 	ve->base.instance = I915_ENGINE_CLASS_INVALID_VIRTUAL;
3339 	ve->base.flags = I915_ENGINE_IS_VIRTUAL;
3340 
3341 	snprintf(ve->base.name, sizeof(ve->base.name), "virtual");
3342 
3343 	err = i915_timeline_init(ctx->i915, &ve->base.timeline, NULL);
3344 	if (err)
3345 		goto err_put;
3346 	i915_timeline_set_subclass(&ve->base.timeline, TIMELINE_VIRTUAL);
3347 
3348 	intel_engine_init_execlists(&ve->base);
3349 
3350 	ve->base.cops = &virtual_context_ops;
3351 	ve->base.request_alloc = execlists_request_alloc;
3352 
3353 	ve->base.schedule = i915_schedule;
3354 	ve->base.submit_request = virtual_submit_request;
3355 	ve->base.bond_execute = virtual_bond_execute;
3356 
3357 	ve->base.execlists.queue_priority_hint = INT_MIN;
3358 	tasklet_init(&ve->base.execlists.tasklet,
3359 		     virtual_submission_tasklet,
3360 		     (unsigned long)ve);
3361 
3362 	intel_context_init(&ve->context, ctx, &ve->base);
3363 
3364 	for (n = 0; n < count; n++) {
3365 		struct intel_engine_cs *sibling = siblings[n];
3366 
3367 		GEM_BUG_ON(!is_power_of_2(sibling->mask));
3368 		if (sibling->mask & ve->base.mask) {
3369 			DRM_DEBUG("duplicate %s entry in load balancer\n",
3370 				  sibling->name);
3371 			err = -EINVAL;
3372 			goto err_put;
3373 		}
3374 
3375 		/*
3376 		 * The virtual engine implementation is tightly coupled to
3377 		 * the execlists backend -- we push out request directly
3378 		 * into a tree inside each physical engine. We could support
3379 		 * layering if we handle cloning of the requests and
3380 		 * submitting a copy into each backend.
3381 		 */
3382 		if (sibling->execlists.tasklet.func !=
3383 		    execlists_submission_tasklet) {
3384 			err = -ENODEV;
3385 			goto err_put;
3386 		}
3387 
3388 		GEM_BUG_ON(RB_EMPTY_NODE(&ve->nodes[sibling->id].rb));
3389 		RB_CLEAR_NODE(&ve->nodes[sibling->id].rb);
3390 
3391 		ve->siblings[ve->num_siblings++] = sibling;
3392 		ve->base.mask |= sibling->mask;
3393 
3394 		/*
3395 		 * All physical engines must be compatible for their emission
3396 		 * functions (as we build the instructions during request
3397 		 * construction and do not alter them before submission
3398 		 * on the physical engine). We use the engine class as a guide
3399 		 * here, although that could be refined.
3400 		 */
3401 		if (ve->base.class != OTHER_CLASS) {
3402 			if (ve->base.class != sibling->class) {
3403 				DRM_DEBUG("invalid mixing of engine class, sibling %d, already %d\n",
3404 					  sibling->class, ve->base.class);
3405 				err = -EINVAL;
3406 				goto err_put;
3407 			}
3408 			continue;
3409 		}
3410 
3411 		ve->base.class = sibling->class;
3412 		ve->base.uabi_class = sibling->uabi_class;
3413 		snprintf(ve->base.name, sizeof(ve->base.name),
3414 			 "v%dx%d", ve->base.class, count);
3415 		ve->base.context_size = sibling->context_size;
3416 
3417 		ve->base.emit_bb_start = sibling->emit_bb_start;
3418 		ve->base.emit_flush = sibling->emit_flush;
3419 		ve->base.emit_init_breadcrumb = sibling->emit_init_breadcrumb;
3420 		ve->base.emit_fini_breadcrumb = sibling->emit_fini_breadcrumb;
3421 		ve->base.emit_fini_breadcrumb_dw =
3422 			sibling->emit_fini_breadcrumb_dw;
3423 	}
3424 
3425 	return &ve->context;
3426 
3427 err_put:
3428 	intel_context_put(&ve->context);
3429 	return ERR_PTR(err);
3430 }
3431 
3432 struct intel_context *
3433 intel_execlists_clone_virtual(struct i915_gem_context *ctx,
3434 			      struct intel_engine_cs *src)
3435 {
3436 	struct virtual_engine *se = to_virtual_engine(src);
3437 	struct intel_context *dst;
3438 
3439 	dst = intel_execlists_create_virtual(ctx,
3440 					     se->siblings,
3441 					     se->num_siblings);
3442 	if (IS_ERR(dst))
3443 		return dst;
3444 
3445 	if (se->num_bonds) {
3446 		struct virtual_engine *de = to_virtual_engine(dst->engine);
3447 
3448 		de->bonds = kmemdup(se->bonds,
3449 				    sizeof(*se->bonds) * se->num_bonds,
3450 				    GFP_KERNEL);
3451 		if (!de->bonds) {
3452 			intel_context_put(dst);
3453 			return ERR_PTR(-ENOMEM);
3454 		}
3455 
3456 		de->num_bonds = se->num_bonds;
3457 	}
3458 
3459 	return dst;
3460 }
3461 
3462 int intel_virtual_engine_attach_bond(struct intel_engine_cs *engine,
3463 				     const struct intel_engine_cs *master,
3464 				     const struct intel_engine_cs *sibling)
3465 {
3466 	struct virtual_engine *ve = to_virtual_engine(engine);
3467 	struct ve_bond *bond;
3468 	int n;
3469 
3470 	/* Sanity check the sibling is part of the virtual engine */
3471 	for (n = 0; n < ve->num_siblings; n++)
3472 		if (sibling == ve->siblings[n])
3473 			break;
3474 	if (n == ve->num_siblings)
3475 		return -EINVAL;
3476 
3477 	bond = virtual_find_bond(ve, master);
3478 	if (bond) {
3479 		bond->sibling_mask |= sibling->mask;
3480 		return 0;
3481 	}
3482 
3483 	bond = krealloc(ve->bonds,
3484 			sizeof(*bond) * (ve->num_bonds + 1),
3485 			GFP_KERNEL);
3486 	if (!bond)
3487 		return -ENOMEM;
3488 
3489 	bond[ve->num_bonds].master = master;
3490 	bond[ve->num_bonds].sibling_mask = sibling->mask;
3491 
3492 	ve->bonds = bond;
3493 	ve->num_bonds++;
3494 
3495 	return 0;
3496 }
3497 
3498 void intel_execlists_show_requests(struct intel_engine_cs *engine,
3499 				   struct drm_printer *m,
3500 				   void (*show_request)(struct drm_printer *m,
3501 							struct i915_request *rq,
3502 							const char *prefix),
3503 				   unsigned int max)
3504 {
3505 	const struct intel_engine_execlists *execlists = &engine->execlists;
3506 	struct i915_request *rq, *last;
3507 	unsigned long flags;
3508 	unsigned int count;
3509 	struct rb_node *rb;
3510 
3511 	spin_lock_irqsave(&engine->timeline.lock, flags);
3512 
3513 	last = NULL;
3514 	count = 0;
3515 	list_for_each_entry(rq, &engine->timeline.requests, link) {
3516 		if (count++ < max - 1)
3517 			show_request(m, rq, "\t\tE ");
3518 		else
3519 			last = rq;
3520 	}
3521 	if (last) {
3522 		if (count > max) {
3523 			drm_printf(m,
3524 				   "\t\t...skipping %d executing requests...\n",
3525 				   count - max);
3526 		}
3527 		show_request(m, last, "\t\tE ");
3528 	}
3529 
3530 	last = NULL;
3531 	count = 0;
3532 	if (execlists->queue_priority_hint != INT_MIN)
3533 		drm_printf(m, "\t\tQueue priority hint: %d\n",
3534 			   execlists->queue_priority_hint);
3535 	for (rb = rb_first_cached(&execlists->queue); rb; rb = rb_next(rb)) {
3536 		struct i915_priolist *p = rb_entry(rb, typeof(*p), node);
3537 		int i;
3538 
3539 		priolist_for_each_request(rq, p, i) {
3540 			if (count++ < max - 1)
3541 				show_request(m, rq, "\t\tQ ");
3542 			else
3543 				last = rq;
3544 		}
3545 	}
3546 	if (last) {
3547 		if (count > max) {
3548 			drm_printf(m,
3549 				   "\t\t...skipping %d queued requests...\n",
3550 				   count - max);
3551 		}
3552 		show_request(m, last, "\t\tQ ");
3553 	}
3554 
3555 	last = NULL;
3556 	count = 0;
3557 	for (rb = rb_first_cached(&execlists->virtual); rb; rb = rb_next(rb)) {
3558 		struct virtual_engine *ve =
3559 			rb_entry(rb, typeof(*ve), nodes[engine->id].rb);
3560 		struct i915_request *rq = READ_ONCE(ve->request);
3561 
3562 		if (rq) {
3563 			if (count++ < max - 1)
3564 				show_request(m, rq, "\t\tV ");
3565 			else
3566 				last = rq;
3567 		}
3568 	}
3569 	if (last) {
3570 		if (count > max) {
3571 			drm_printf(m,
3572 				   "\t\t...skipping %d virtual requests...\n",
3573 				   count - max);
3574 		}
3575 		show_request(m, last, "\t\tV ");
3576 	}
3577 
3578 	spin_unlock_irqrestore(&engine->timeline.lock, flags);
3579 }
3580 
3581 void intel_lr_context_reset(struct intel_engine_cs *engine,
3582 			    struct intel_context *ce,
3583 			    u32 head,
3584 			    bool scrub)
3585 {
3586 	/*
3587 	 * We want a simple context + ring to execute the breadcrumb update.
3588 	 * We cannot rely on the context being intact across the GPU hang,
3589 	 * so clear it and rebuild just what we need for the breadcrumb.
3590 	 * All pending requests for this context will be zapped, and any
3591 	 * future request will be after userspace has had the opportunity
3592 	 * to recreate its own state.
3593 	 */
3594 	if (scrub) {
3595 		u32 *regs = ce->lrc_reg_state;
3596 
3597 		if (engine->pinned_default_state) {
3598 			memcpy(regs, /* skip restoring the vanilla PPHWSP */
3599 			       engine->pinned_default_state + LRC_STATE_PN * PAGE_SIZE,
3600 			       engine->context_size - PAGE_SIZE);
3601 		}
3602 		execlists_init_reg_state(regs, ce, engine, ce->ring);
3603 	}
3604 
3605 	/* Rerun the request; its payload has been neutered (if guilty). */
3606 	ce->ring->head = head;
3607 	intel_ring_update_space(ce->ring);
3608 
3609 	__execlists_update_reg_state(ce, engine);
3610 }
3611 
3612 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
3613 #include "selftest_lrc.c"
3614 #endif
3615