2 * Copyright © 2014 Intel Corporation
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:
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
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
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>
32 * DOC: Logical Rings, Logical Ring Contexts and Execlists
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).
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:
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.
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.
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".
60 * Regarding the creation of contexts, we have:
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.
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:
70 * - One ringbuffer per-engine inside each context.
71 * - One backing object per-engine inside each context.
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
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
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).
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:
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
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.
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.
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.
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).
134 #include <linux/interrupt.h>
136 #include "gem/i915_gem_context.h"
138 #include "i915_drv.h"
139 #include "i915_gem_render_state.h"
140 #include "i915_vgpu.h"
141 #include "intel_engine_pm.h"
142 #include "intel_lrc_reg.h"
143 #include "intel_mocs.h"
144 #include "intel_reset.h"
145 #include "intel_workarounds.h"
147 #define RING_EXECLIST_QFULL (1 << 0x2)
148 #define RING_EXECLIST1_VALID (1 << 0x3)
149 #define RING_EXECLIST0_VALID (1 << 0x4)
150 #define RING_EXECLIST_ACTIVE_STATUS (3 << 0xE)
151 #define RING_EXECLIST1_ACTIVE (1 << 0x11)
152 #define RING_EXECLIST0_ACTIVE (1 << 0x12)
154 #define GEN8_CTX_STATUS_IDLE_ACTIVE (1 << 0)
155 #define GEN8_CTX_STATUS_PREEMPTED (1 << 1)
156 #define GEN8_CTX_STATUS_ELEMENT_SWITCH (1 << 2)
157 #define GEN8_CTX_STATUS_ACTIVE_IDLE (1 << 3)
158 #define GEN8_CTX_STATUS_COMPLETE (1 << 4)
159 #define GEN8_CTX_STATUS_LITE_RESTORE (1 << 15)
161 #define GEN8_CTX_STATUS_COMPLETED_MASK \
162 (GEN8_CTX_STATUS_COMPLETE | GEN8_CTX_STATUS_PREEMPTED)
164 /* Typical size of the average request (2 pipecontrols and a MI_BB) */
165 #define EXECLISTS_REQUEST_SIZE 64 /* bytes */
166 #define WA_TAIL_DWORDS 2
167 #define WA_TAIL_BYTES (sizeof(u32) * WA_TAIL_DWORDS)
169 struct virtual_engine {
170 struct intel_engine_cs base;
171 struct intel_context context;
174 * We allow only a single request through the virtual engine at a time
175 * (each request in the timeline waits for the completion fence of
176 * the previous before being submitted). By restricting ourselves to
177 * only submitting a single request, each request is placed on to a
178 * physical to maximise load spreading (by virtue of the late greedy
179 * scheduling -- each real engine takes the next available request
182 struct i915_request *request;
185 * We keep a rbtree of available virtual engines inside each physical
186 * engine, sorted by priority. Here we preallocate the nodes we need
187 * for the virtual engine, indexed by physical_engine->id.
192 } nodes[I915_NUM_ENGINES];
195 * Keep track of bonded pairs -- restrictions upon on our selection
196 * of physical engines any particular request may be submitted to.
197 * If we receive a submit-fence from a master engine, we will only
198 * use one of sibling_mask physical engines.
201 const struct intel_engine_cs *master;
202 intel_engine_mask_t sibling_mask;
204 unsigned int num_bonds;
206 /* And finally, which physical engines this virtual engine maps onto. */
207 unsigned int num_siblings;
208 struct intel_engine_cs *siblings[0];
211 static struct virtual_engine *to_virtual_engine(struct intel_engine_cs *engine)
213 GEM_BUG_ON(!intel_engine_is_virtual(engine));
214 return container_of(engine, struct virtual_engine, base);
217 static int execlists_context_deferred_alloc(struct intel_context *ce,
218 struct intel_engine_cs *engine);
219 static void execlists_init_reg_state(u32 *reg_state,
220 struct intel_context *ce,
221 struct intel_engine_cs *engine,
222 struct intel_ring *ring);
224 static inline struct i915_priolist *to_priolist(struct rb_node *rb)
226 return rb_entry(rb, struct i915_priolist, node);
229 static inline int rq_prio(const struct i915_request *rq)
231 return rq->sched.attr.priority;
234 static int effective_prio(const struct i915_request *rq)
236 int prio = rq_prio(rq);
239 * On unwinding the active request, we give it a priority bump
240 * if it has completed waiting on any semaphore. If we know that
241 * the request has already started, we can prevent an unwanted
242 * preempt-to-idle cycle by taking that into account now.
244 if (__i915_request_has_started(rq))
245 prio |= I915_PRIORITY_NOSEMAPHORE;
247 /* Restrict mere WAIT boosts from triggering preemption */
248 return prio | __NO_PREEMPTION;
251 static int queue_prio(const struct intel_engine_execlists *execlists)
253 struct i915_priolist *p;
256 rb = rb_first_cached(&execlists->queue);
261 * As the priolist[] are inverted, with the highest priority in [0],
262 * we have to flip the index value to become priority.
265 return ((p->priority + 1) << I915_USER_PRIORITY_SHIFT) - ffs(p->used);
268 static inline bool need_preempt(const struct intel_engine_cs *engine,
269 const struct i915_request *rq,
274 if (!engine->preempt_context)
277 if (i915_request_completed(rq))
281 * Check if the current priority hint merits a preemption attempt.
283 * We record the highest value priority we saw during rescheduling
284 * prior to this dequeue, therefore we know that if it is strictly
285 * less than the current tail of ESLP[0], we do not need to force
286 * a preempt-to-idle cycle.
288 * However, the priority hint is a mere hint that we may need to
289 * preempt. If that hint is stale or we may be trying to preempt
290 * ourselves, ignore the request.
292 last_prio = effective_prio(rq);
293 if (!i915_scheduler_need_preempt(engine->execlists.queue_priority_hint,
298 * Check against the first request in ELSP[1], it will, thanks to the
299 * power of PI, be the highest priority of that context.
301 if (!list_is_last(&rq->sched.link, &engine->active.requests) &&
302 rq_prio(list_next_entry(rq, sched.link)) > last_prio)
306 struct virtual_engine *ve =
307 rb_entry(rb, typeof(*ve), nodes[engine->id].rb);
308 bool preempt = false;
310 if (engine == ve->siblings[0]) { /* only preempt one sibling */
311 struct i915_request *next;
314 next = READ_ONCE(ve->request);
316 preempt = rq_prio(next) > last_prio;
325 * If the inflight context did not trigger the preemption, then maybe
326 * it was the set of queued requests? Pick the highest priority in
327 * the queue (the first active priolist) and see if it deserves to be
328 * running instead of ELSP[0].
330 * The highest priority request in the queue can not be either
331 * ELSP[0] or ELSP[1] as, thanks again to PI, if it was the same
332 * context, it's priority would not exceed ELSP[0] aka last_prio.
334 return queue_prio(&engine->execlists) > last_prio;
337 __maybe_unused static inline bool
338 assert_priority_queue(const struct i915_request *prev,
339 const struct i915_request *next)
341 const struct intel_engine_execlists *execlists =
342 &prev->engine->execlists;
345 * Without preemption, the prev may refer to the still active element
346 * which we refuse to let go.
348 * Even with preemption, there are times when we think it is better not
349 * to preempt and leave an ostensibly lower priority request in flight.
351 if (port_request(execlists->port) == prev)
354 return rq_prio(prev) >= rq_prio(next);
358 * The context descriptor encodes various attributes of a context,
359 * including its GTT address and some flags. Because it's fairly
360 * expensive to calculate, we'll just do it once and cache the result,
361 * which remains valid until the context is unpinned.
363 * This is what a descriptor looks like, from LSB to MSB::
365 * bits 0-11: flags, GEN8_CTX_* (cached in ctx->desc_template)
366 * bits 12-31: LRCA, GTT address of (the HWSP of) this context
367 * bits 32-52: ctx ID, a globally unique tag (highest bit used by GuC)
368 * bits 53-54: mbz, reserved for use by hardware
369 * bits 55-63: group ID, currently unused and set to 0
371 * Starting from Gen11, the upper dword of the descriptor has a new format:
373 * bits 32-36: reserved
374 * bits 37-47: SW context ID
375 * bits 48:53: engine instance
376 * bit 54: mbz, reserved for use by hardware
377 * bits 55-60: SW counter
378 * bits 61-63: engine class
380 * engine info, SW context ID and SW counter need to form a unique number
381 * (Context ID) per lrc.
384 lrc_descriptor(struct intel_context *ce, struct intel_engine_cs *engine)
386 struct i915_gem_context *ctx = ce->gem_context;
389 BUILD_BUG_ON(MAX_CONTEXT_HW_ID > (BIT(GEN8_CTX_ID_WIDTH)));
390 BUILD_BUG_ON(GEN11_MAX_CONTEXT_HW_ID > (BIT(GEN11_SW_CTX_ID_WIDTH)));
392 desc = ctx->desc_template; /* bits 0-11 */
393 GEM_BUG_ON(desc & GENMASK_ULL(63, 12));
395 desc |= i915_ggtt_offset(ce->state) + LRC_HEADER_PAGES * PAGE_SIZE;
397 GEM_BUG_ON(desc & GENMASK_ULL(63, 32));
400 * The following 32bits are copied into the OA reports (dword 2).
401 * Consider updating oa_get_render_ctx_id in i915_perf.c when changing
404 if (INTEL_GEN(engine->i915) >= 11) {
405 GEM_BUG_ON(ctx->hw_id >= BIT(GEN11_SW_CTX_ID_WIDTH));
406 desc |= (u64)ctx->hw_id << GEN11_SW_CTX_ID_SHIFT;
409 desc |= (u64)engine->instance << GEN11_ENGINE_INSTANCE_SHIFT;
412 /* TODO: decide what to do with SW counter (bits 55-60) */
414 desc |= (u64)engine->class << GEN11_ENGINE_CLASS_SHIFT;
417 GEM_BUG_ON(ctx->hw_id >= BIT(GEN8_CTX_ID_WIDTH));
418 desc |= (u64)ctx->hw_id << GEN8_CTX_ID_SHIFT; /* bits 32-52 */
424 static void unwind_wa_tail(struct i915_request *rq)
426 rq->tail = intel_ring_wrap(rq->ring, rq->wa_tail - WA_TAIL_BYTES);
427 assert_ring_tail_valid(rq->ring, rq->tail);
430 static struct i915_request *
431 __unwind_incomplete_requests(struct intel_engine_cs *engine)
433 struct i915_request *rq, *rn, *active = NULL;
434 struct list_head *uninitialized_var(pl);
435 int prio = I915_PRIORITY_INVALID;
437 lockdep_assert_held(&engine->active.lock);
439 list_for_each_entry_safe_reverse(rq, rn,
440 &engine->active.requests,
442 struct intel_engine_cs *owner;
444 if (i915_request_completed(rq))
447 __i915_request_unsubmit(rq);
450 GEM_BUG_ON(rq->hw_context->inflight);
453 * Push the request back into the queue for later resubmission.
454 * If this request is not native to this physical engine (i.e.
455 * it came from a virtual source), push it back onto the virtual
456 * engine so that it can be moved across onto another physical
457 * engine as load dictates.
459 owner = rq->hw_context->engine;
460 if (likely(owner == engine)) {
461 GEM_BUG_ON(rq_prio(rq) == I915_PRIORITY_INVALID);
462 if (rq_prio(rq) != prio) {
464 pl = i915_sched_lookup_priolist(engine, prio);
466 GEM_BUG_ON(RB_EMPTY_ROOT(&engine->execlists.queue.rb_root));
468 list_move(&rq->sched.link, pl);
472 owner->submit_request(rq);
480 struct i915_request *
481 execlists_unwind_incomplete_requests(struct intel_engine_execlists *execlists)
483 struct intel_engine_cs *engine =
484 container_of(execlists, typeof(*engine), execlists);
486 return __unwind_incomplete_requests(engine);
490 execlists_context_status_change(struct i915_request *rq, unsigned long status)
493 * Only used when GVT-g is enabled now. When GVT-g is disabled,
494 * The compiler should eliminate this function as dead-code.
496 if (!IS_ENABLED(CONFIG_DRM_I915_GVT))
499 atomic_notifier_call_chain(&rq->engine->context_status_notifier,
504 execlists_user_begin(struct intel_engine_execlists *execlists,
505 const struct execlist_port *port)
507 execlists_set_active_once(execlists, EXECLISTS_ACTIVE_USER);
511 execlists_user_end(struct intel_engine_execlists *execlists)
513 execlists_clear_active(execlists, EXECLISTS_ACTIVE_USER);
517 execlists_context_schedule_in(struct i915_request *rq)
519 GEM_BUG_ON(rq->hw_context->inflight);
521 execlists_context_status_change(rq, INTEL_CONTEXT_SCHEDULE_IN);
522 intel_engine_context_in(rq->engine);
523 rq->hw_context->inflight = rq->engine;
526 static void kick_siblings(struct i915_request *rq)
528 struct virtual_engine *ve = to_virtual_engine(rq->hw_context->engine);
529 struct i915_request *next = READ_ONCE(ve->request);
531 if (next && next->execution_mask & ~rq->execution_mask)
532 tasklet_schedule(&ve->base.execlists.tasklet);
536 execlists_context_schedule_out(struct i915_request *rq, unsigned long status)
538 rq->hw_context->inflight = NULL;
539 intel_engine_context_out(rq->engine);
540 execlists_context_status_change(rq, status);
541 trace_i915_request_out(rq);
544 * If this is part of a virtual engine, its next request may have
545 * been blocked waiting for access to the active context. We have
546 * to kick all the siblings again in case we need to switch (e.g.
547 * the next request is not runnable on this engine). Hopefully,
548 * we will already have submitted the next request before the
549 * tasklet runs and do not need to rebuild each virtual tree
550 * and kick everyone again.
552 if (rq->engine != rq->hw_context->engine)
556 static u64 execlists_update_context(struct i915_request *rq)
558 struct intel_context *ce = rq->hw_context;
560 ce->lrc_reg_state[CTX_RING_TAIL + 1] =
561 intel_ring_set_tail(rq->ring, rq->tail);
564 * Make sure the context image is complete before we submit it to HW.
566 * Ostensibly, writes (including the WCB) should be flushed prior to
567 * an uncached write such as our mmio register access, the empirical
568 * evidence (esp. on Braswell) suggests that the WC write into memory
569 * may not be visible to the HW prior to the completion of the UC
570 * register write and that we may begin execution from the context
571 * before its image is complete leading to invalid PD chasing.
573 * Furthermore, Braswell, at least, wants a full mb to be sure that
574 * the writes are coherent in memory (visible to the GPU) prior to
575 * execution, and not just visible to other CPUs (as is the result of
582 static inline void write_desc(struct intel_engine_execlists *execlists, u64 desc, u32 port)
584 if (execlists->ctrl_reg) {
585 writel(lower_32_bits(desc), execlists->submit_reg + port * 2);
586 writel(upper_32_bits(desc), execlists->submit_reg + port * 2 + 1);
588 writel(upper_32_bits(desc), execlists->submit_reg);
589 writel(lower_32_bits(desc), execlists->submit_reg);
593 static void execlists_submit_ports(struct intel_engine_cs *engine)
595 struct intel_engine_execlists *execlists = &engine->execlists;
596 struct execlist_port *port = execlists->port;
600 * We can skip acquiring intel_runtime_pm_get() here as it was taken
601 * on our behalf by the request (see i915_gem_mark_busy()) and it will
602 * not be relinquished until the device is idle (see
603 * i915_gem_idle_work_handler()). As a precaution, we make sure
604 * that all ELSP are drained i.e. we have processed the CSB,
605 * before allowing ourselves to idle and calling intel_runtime_pm_put().
607 GEM_BUG_ON(!intel_wakeref_active(&engine->wakeref));
610 * ELSQ note: the submit queue is not cleared after being submitted
611 * to the HW so we need to make sure we always clean it up. This is
612 * currently ensured by the fact that we always write the same number
613 * of elsq entries, keep this in mind before changing the loop below.
615 for (n = execlists_num_ports(execlists); n--; ) {
616 struct i915_request *rq;
620 rq = port_unpack(&port[n], &count);
622 GEM_BUG_ON(count > !n);
624 execlists_context_schedule_in(rq);
625 port_set(&port[n], port_pack(rq, count));
626 desc = execlists_update_context(rq);
627 GEM_DEBUG_EXEC(port[n].context_id = upper_32_bits(desc));
629 GEM_TRACE("%s in[%d]: ctx=%d.%d, fence %llx:%lld (current %d), prio=%d\n",
631 port[n].context_id, count,
632 rq->fence.context, rq->fence.seqno,
640 write_desc(execlists, desc, n);
643 /* we need to manually load the submit queue */
644 if (execlists->ctrl_reg)
645 writel(EL_CTRL_LOAD, execlists->ctrl_reg);
647 execlists_clear_active(execlists, EXECLISTS_ACTIVE_HWACK);
650 static bool ctx_single_port_submission(const struct intel_context *ce)
652 return (IS_ENABLED(CONFIG_DRM_I915_GVT) &&
653 i915_gem_context_force_single_submission(ce->gem_context));
656 static bool can_merge_ctx(const struct intel_context *prev,
657 const struct intel_context *next)
662 if (ctx_single_port_submission(prev))
668 static bool can_merge_rq(const struct i915_request *prev,
669 const struct i915_request *next)
671 GEM_BUG_ON(!assert_priority_queue(prev, next));
673 if (!can_merge_ctx(prev->hw_context, next->hw_context))
679 static void port_assign(struct execlist_port *port, struct i915_request *rq)
681 GEM_BUG_ON(rq == port_request(port));
683 if (port_isset(port))
684 i915_request_put(port_request(port));
686 port_set(port, port_pack(i915_request_get(rq), port_count(port)));
689 static void inject_preempt_context(struct intel_engine_cs *engine)
691 struct intel_engine_execlists *execlists = &engine->execlists;
692 struct intel_context *ce = engine->preempt_context;
695 GEM_BUG_ON(execlists->preempt_complete_status !=
696 upper_32_bits(ce->lrc_desc));
699 * Switch to our empty preempt context so
700 * the state of the GPU is known (idle).
702 GEM_TRACE("%s\n", engine->name);
703 for (n = execlists_num_ports(execlists); --n; )
704 write_desc(execlists, 0, n);
706 write_desc(execlists, ce->lrc_desc, n);
708 /* we need to manually load the submit queue */
709 if (execlists->ctrl_reg)
710 writel(EL_CTRL_LOAD, execlists->ctrl_reg);
712 execlists_clear_active(execlists, EXECLISTS_ACTIVE_HWACK);
713 execlists_set_active(execlists, EXECLISTS_ACTIVE_PREEMPT);
715 (void)I915_SELFTEST_ONLY(execlists->preempt_hang.count++);
718 static void complete_preempt_context(struct intel_engine_execlists *execlists)
720 GEM_BUG_ON(!execlists_is_active(execlists, EXECLISTS_ACTIVE_PREEMPT));
722 if (inject_preempt_hang(execlists))
725 execlists_cancel_port_requests(execlists);
726 __unwind_incomplete_requests(container_of(execlists,
727 struct intel_engine_cs,
731 static void virtual_update_register_offsets(u32 *regs,
732 struct intel_engine_cs *engine)
734 u32 base = engine->mmio_base;
736 /* Must match execlists_init_reg_state()! */
738 regs[CTX_CONTEXT_CONTROL] =
739 i915_mmio_reg_offset(RING_CONTEXT_CONTROL(base));
740 regs[CTX_RING_HEAD] = i915_mmio_reg_offset(RING_HEAD(base));
741 regs[CTX_RING_TAIL] = i915_mmio_reg_offset(RING_TAIL(base));
742 regs[CTX_RING_BUFFER_START] = i915_mmio_reg_offset(RING_START(base));
743 regs[CTX_RING_BUFFER_CONTROL] = i915_mmio_reg_offset(RING_CTL(base));
745 regs[CTX_BB_HEAD_U] = i915_mmio_reg_offset(RING_BBADDR_UDW(base));
746 regs[CTX_BB_HEAD_L] = i915_mmio_reg_offset(RING_BBADDR(base));
747 regs[CTX_BB_STATE] = i915_mmio_reg_offset(RING_BBSTATE(base));
748 regs[CTX_SECOND_BB_HEAD_U] =
749 i915_mmio_reg_offset(RING_SBBADDR_UDW(base));
750 regs[CTX_SECOND_BB_HEAD_L] = i915_mmio_reg_offset(RING_SBBADDR(base));
751 regs[CTX_SECOND_BB_STATE] = i915_mmio_reg_offset(RING_SBBSTATE(base));
753 regs[CTX_CTX_TIMESTAMP] =
754 i915_mmio_reg_offset(RING_CTX_TIMESTAMP(base));
755 regs[CTX_PDP3_UDW] = i915_mmio_reg_offset(GEN8_RING_PDP_UDW(base, 3));
756 regs[CTX_PDP3_LDW] = i915_mmio_reg_offset(GEN8_RING_PDP_LDW(base, 3));
757 regs[CTX_PDP2_UDW] = i915_mmio_reg_offset(GEN8_RING_PDP_UDW(base, 2));
758 regs[CTX_PDP2_LDW] = i915_mmio_reg_offset(GEN8_RING_PDP_LDW(base, 2));
759 regs[CTX_PDP1_UDW] = i915_mmio_reg_offset(GEN8_RING_PDP_UDW(base, 1));
760 regs[CTX_PDP1_LDW] = i915_mmio_reg_offset(GEN8_RING_PDP_LDW(base, 1));
761 regs[CTX_PDP0_UDW] = i915_mmio_reg_offset(GEN8_RING_PDP_UDW(base, 0));
762 regs[CTX_PDP0_LDW] = i915_mmio_reg_offset(GEN8_RING_PDP_LDW(base, 0));
764 if (engine->class == RENDER_CLASS) {
765 regs[CTX_RCS_INDIRECT_CTX] =
766 i915_mmio_reg_offset(RING_INDIRECT_CTX(base));
767 regs[CTX_RCS_INDIRECT_CTX_OFFSET] =
768 i915_mmio_reg_offset(RING_INDIRECT_CTX_OFFSET(base));
769 regs[CTX_BB_PER_CTX_PTR] =
770 i915_mmio_reg_offset(RING_BB_PER_CTX_PTR(base));
772 regs[CTX_R_PWR_CLK_STATE] =
773 i915_mmio_reg_offset(GEN8_R_PWR_CLK_STATE);
777 static bool virtual_matches(const struct virtual_engine *ve,
778 const struct i915_request *rq,
779 const struct intel_engine_cs *engine)
781 const struct intel_engine_cs *inflight;
783 if (!(rq->execution_mask & engine->mask)) /* We peeked too soon! */
787 * We track when the HW has completed saving the context image
788 * (i.e. when we have seen the final CS event switching out of
789 * the context) and must not overwrite the context image before
790 * then. This restricts us to only using the active engine
791 * while the previous virtualized request is inflight (so
792 * we reuse the register offsets). This is a very small
793 * hystersis on the greedy seelction algorithm.
795 inflight = READ_ONCE(ve->context.inflight);
796 if (inflight && inflight != engine)
802 static void virtual_xfer_breadcrumbs(struct virtual_engine *ve,
803 struct intel_engine_cs *engine)
805 struct intel_engine_cs *old = ve->siblings[0];
807 /* All unattached (rq->engine == old) must already be completed */
809 spin_lock(&old->breadcrumbs.irq_lock);
810 if (!list_empty(&ve->context.signal_link)) {
811 list_move_tail(&ve->context.signal_link,
812 &engine->breadcrumbs.signalers);
813 intel_engine_queue_breadcrumbs(engine);
815 spin_unlock(&old->breadcrumbs.irq_lock);
818 static void execlists_dequeue(struct intel_engine_cs *engine)
820 struct intel_engine_execlists * const execlists = &engine->execlists;
821 struct execlist_port *port = execlists->port;
822 const struct execlist_port * const last_port =
823 &execlists->port[execlists->port_mask];
824 struct i915_request *last = port_request(port);
829 * Hardware submission is through 2 ports. Conceptually each port
830 * has a (RING_START, RING_HEAD, RING_TAIL) tuple. RING_START is
831 * static for a context, and unique to each, so we only execute
832 * requests belonging to a single context from each ring. RING_HEAD
833 * is maintained by the CS in the context image, it marks the place
834 * where it got up to last time, and through RING_TAIL we tell the CS
835 * where we want to execute up to this time.
837 * In this list the requests are in order of execution. Consecutive
838 * requests from the same context are adjacent in the ringbuffer. We
839 * can combine these requests into a single RING_TAIL update:
841 * RING_HEAD...req1...req2
843 * since to execute req2 the CS must first execute req1.
845 * Our goal then is to point each port to the end of a consecutive
846 * sequence of requests as being the most optimal (fewest wake ups
847 * and context switches) submission.
850 for (rb = rb_first_cached(&execlists->virtual); rb; ) {
851 struct virtual_engine *ve =
852 rb_entry(rb, typeof(*ve), nodes[engine->id].rb);
853 struct i915_request *rq = READ_ONCE(ve->request);
855 if (!rq) { /* lazily cleanup after another engine handled rq */
856 rb_erase_cached(rb, &execlists->virtual);
858 rb = rb_first_cached(&execlists->virtual);
862 if (!virtual_matches(ve, rq, engine)) {
872 * Don't resubmit or switch until all outstanding
873 * preemptions (lite-restore) are seen. Then we
874 * know the next preemption status we see corresponds
875 * to this ELSP update.
877 GEM_BUG_ON(!execlists_is_active(execlists,
878 EXECLISTS_ACTIVE_USER));
879 GEM_BUG_ON(!port_count(&port[0]));
882 * If we write to ELSP a second time before the HW has had
883 * a chance to respond to the previous write, we can confuse
884 * the HW and hit "undefined behaviour". After writing to ELSP,
885 * we must then wait until we see a context-switch event from
886 * the HW to indicate that it has had a chance to respond.
888 if (!execlists_is_active(execlists, EXECLISTS_ACTIVE_HWACK))
891 if (need_preempt(engine, last, rb)) {
892 inject_preempt_context(engine);
897 * In theory, we could coalesce more requests onto
898 * the second port (the first port is active, with
899 * no preemptions pending). However, that means we
900 * then have to deal with the possible lite-restore
901 * of the second port (as we submit the ELSP, there
902 * may be a context-switch) but also we may complete
903 * the resubmission before the context-switch. Ergo,
904 * coalescing onto the second port will cause a
905 * preemption event, but we cannot predict whether
906 * that will affect port[0] or port[1].
908 * If the second port is already active, we can wait
909 * until the next context-switch before contemplating
910 * new requests. The GPU will be busy and we should be
911 * able to resubmit the new ELSP before it idles,
912 * avoiding pipeline bubbles (momentary pauses where
913 * the driver is unable to keep up the supply of new
914 * work). However, we have to double check that the
915 * priorities of the ports haven't been switch.
917 if (port_count(&port[1]))
921 * WaIdleLiteRestore:bdw,skl
922 * Apply the wa NOOPs to prevent
923 * ring:HEAD == rq:TAIL as we resubmit the
924 * request. See gen8_emit_fini_breadcrumb() for
925 * where we prepare the padding after the
926 * end of the request.
928 last->tail = last->wa_tail;
931 while (rb) { /* XXX virtual is always taking precedence */
932 struct virtual_engine *ve =
933 rb_entry(rb, typeof(*ve), nodes[engine->id].rb);
934 struct i915_request *rq;
936 spin_lock(&ve->base.active.lock);
939 if (unlikely(!rq)) { /* lost the race to a sibling */
940 spin_unlock(&ve->base.active.lock);
941 rb_erase_cached(rb, &execlists->virtual);
943 rb = rb_first_cached(&execlists->virtual);
947 GEM_BUG_ON(rq != ve->request);
948 GEM_BUG_ON(rq->engine != &ve->base);
949 GEM_BUG_ON(rq->hw_context != &ve->context);
951 if (rq_prio(rq) >= queue_prio(execlists)) {
952 if (!virtual_matches(ve, rq, engine)) {
953 spin_unlock(&ve->base.active.lock);
958 if (last && !can_merge_rq(last, rq)) {
959 spin_unlock(&ve->base.active.lock);
960 return; /* leave this rq for another engine */
963 GEM_TRACE("%s: virtual rq=%llx:%lld%s, new engine? %s\n",
967 i915_request_completed(rq) ? "!" :
968 i915_request_started(rq) ? "*" :
970 yesno(engine != ve->siblings[0]));
973 ve->base.execlists.queue_priority_hint = INT_MIN;
974 rb_erase_cached(rb, &execlists->virtual);
977 GEM_BUG_ON(!(rq->execution_mask & engine->mask));
980 if (engine != ve->siblings[0]) {
981 u32 *regs = ve->context.lrc_reg_state;
984 GEM_BUG_ON(READ_ONCE(ve->context.inflight));
985 virtual_update_register_offsets(regs, engine);
987 if (!list_empty(&ve->context.signals))
988 virtual_xfer_breadcrumbs(ve, engine);
991 * Move the bound engine to the top of the list
992 * for future execution. We then kick this
993 * tasklet first before checking others, so that
994 * we preferentially reuse this set of bound
997 for (n = 1; n < ve->num_siblings; n++) {
998 if (ve->siblings[n] == engine) {
999 swap(ve->siblings[n],
1005 GEM_BUG_ON(ve->siblings[0] != engine);
1008 __i915_request_submit(rq);
1009 trace_i915_request_in(rq, port_index(port, execlists));
1014 spin_unlock(&ve->base.active.lock);
1018 while ((rb = rb_first_cached(&execlists->queue))) {
1019 struct i915_priolist *p = to_priolist(rb);
1020 struct i915_request *rq, *rn;
1023 priolist_for_each_request_consume(rq, rn, p, i) {
1025 * Can we combine this request with the current port?
1026 * It has to be the same context/ringbuffer and not
1027 * have any exceptions (e.g. GVT saying never to
1028 * combine contexts).
1030 * If we can combine the requests, we can execute both
1031 * by updating the RING_TAIL to point to the end of the
1032 * second request, and so we never need to tell the
1033 * hardware about the first.
1035 if (last && !can_merge_rq(last, rq)) {
1037 * If we are on the second port and cannot
1038 * combine this request with the last, then we
1041 if (port == last_port)
1045 * We must not populate both ELSP[] with the
1046 * same LRCA, i.e. we must submit 2 different
1047 * contexts if we submit 2 ELSP.
1049 if (last->hw_context == rq->hw_context)
1053 * If GVT overrides us we only ever submit
1054 * port[0], leaving port[1] empty. Note that we
1055 * also have to be careful that we don't queue
1056 * the same context (even though a different
1057 * request) to the second port.
1059 if (ctx_single_port_submission(last->hw_context) ||
1060 ctx_single_port_submission(rq->hw_context))
1065 port_assign(port, last);
1068 GEM_BUG_ON(port_isset(port));
1071 __i915_request_submit(rq);
1072 trace_i915_request_in(rq, port_index(port, execlists));
1078 rb_erase_cached(&p->node, &execlists->queue);
1079 i915_priolist_free(p);
1084 * Here be a bit of magic! Or sleight-of-hand, whichever you prefer.
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.
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).
1099 execlists->queue_priority_hint = queue_prio(execlists);
1102 port_assign(port, last);
1103 execlists_submit_ports(engine);
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));
1110 /* Re-evaluate the executing context setup after each preemptive kick */
1112 execlists_user_begin(execlists, execlists->port);
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));
1121 execlists_cancel_port_requests(struct intel_engine_execlists * const execlists)
1123 struct execlist_port *port = execlists->port;
1124 unsigned int num_ports = execlists_num_ports(execlists);
1126 while (num_ports-- && port_isset(port)) {
1127 struct i915_request *rq = port_request(port);
1129 GEM_TRACE("%s:port%u fence %llx:%lld, (current %d)\n",
1131 (unsigned int)(port - execlists->port),
1132 rq->fence.context, rq->fence.seqno,
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);
1141 i915_request_put(rq);
1143 memset(port, 0, sizeof(*port));
1147 execlists_clear_all_active(execlists);
1151 invalidate_csb_entries(const u32 *first, const u32 *last)
1153 clflush((void *)first);
1154 clflush((void *)last);
1158 reset_in_progress(const struct intel_engine_execlists *execlists)
1160 return unlikely(!__tasklet_is_enabled(&execlists->tasklet));
1163 static void process_csb(struct intel_engine_cs *engine)
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;
1171 lockdep_assert_held(&engine->active.lock);
1172 GEM_BUG_ON(USES_GUC_SUBMISSION(engine->i915));
1175 * Note that csb_write, csb_status may be either in HWSP or mmio.
1176 * When reading from the csb_write mmio register, we have to be
1177 * careful to only use the GEN8_CSB_WRITE_PTR portion, which is
1178 * the low 4bits. As it happens we know the next 4bits are always
1179 * zero and so we can simply masked off the low u8 of the register
1180 * and treat it identically to reading from the HWSP (without having
1181 * to use explicit shifting and masking, and probably bifurcating
1182 * the code to handle the legacy mmio read).
1184 head = execlists->csb_head;
1185 tail = READ_ONCE(*execlists->csb_write);
1186 GEM_TRACE("%s cs-irq head=%d, tail=%d\n", engine->name, head, tail);
1187 if (unlikely(head == tail))
1191 * Hopefully paired with a wmb() in HW!
1193 * We must complete the read of the write pointer before any reads
1194 * from the CSB, so that we do not see stale values. Without an rmb
1195 * (lfence) the HW may speculatively perform the CSB[] reads *before*
1196 * we perform the READ_ONCE(*csb_write).
1201 struct i915_request *rq;
1202 unsigned int status;
1205 if (++head == num_entries)
1209 * We are flying near dragons again.
1211 * We hold a reference to the request in execlist_port[]
1212 * but no more than that. We are operating in softirq
1213 * context and so cannot hold any mutex or sleep. That
1214 * prevents us stopping the requests we are processing
1215 * in port[] from being retired simultaneously (the
1216 * breadcrumb will be complete before we see the
1217 * context-switch). As we only hold the reference to the
1218 * request, any pointer chasing underneath the request
1219 * is subject to a potential use-after-free. Thus we
1220 * store all of the bookkeeping within port[] as
1221 * required, and avoid using unguarded pointers beneath
1222 * request itself. The same applies to the atomic
1226 GEM_TRACE("%s csb[%d]: status=0x%08x:0x%08x, active=0x%x\n",
1228 buf[2 * head + 0], buf[2 * head + 1],
1231 status = buf[2 * head];
1232 if (status & (GEN8_CTX_STATUS_IDLE_ACTIVE |
1233 GEN8_CTX_STATUS_PREEMPTED))
1234 execlists_set_active(execlists,
1235 EXECLISTS_ACTIVE_HWACK);
1236 if (status & GEN8_CTX_STATUS_ACTIVE_IDLE)
1237 execlists_clear_active(execlists,
1238 EXECLISTS_ACTIVE_HWACK);
1240 if (!(status & GEN8_CTX_STATUS_COMPLETED_MASK))
1243 /* We should never get a COMPLETED | IDLE_ACTIVE! */
1244 GEM_BUG_ON(status & GEN8_CTX_STATUS_IDLE_ACTIVE);
1246 if (status & GEN8_CTX_STATUS_COMPLETE &&
1247 buf[2*head + 1] == execlists->preempt_complete_status) {
1248 GEM_TRACE("%s preempt-idle\n", engine->name);
1249 complete_preempt_context(execlists);
1253 if (status & GEN8_CTX_STATUS_PREEMPTED &&
1254 execlists_is_active(execlists,
1255 EXECLISTS_ACTIVE_PREEMPT))
1258 GEM_BUG_ON(!execlists_is_active(execlists,
1259 EXECLISTS_ACTIVE_USER));
1261 rq = port_unpack(port, &count);
1262 GEM_TRACE("%s out[0]: ctx=%d.%d, fence %llx:%lld (current %d), prio=%d\n",
1264 port->context_id, count,
1265 rq ? rq->fence.context : 0,
1266 rq ? rq->fence.seqno : 0,
1267 rq ? hwsp_seqno(rq) : 0,
1268 rq ? rq_prio(rq) : 0);
1270 /* Check the context/desc id for this event matches */
1271 GEM_DEBUG_BUG_ON(buf[2 * head + 1] != port->context_id);
1273 GEM_BUG_ON(count == 0);
1276 * On the final event corresponding to the
1277 * submission of this context, we expect either
1278 * an element-switch event or a completion
1279 * event (and on completion, the active-idle
1280 * marker). No more preemptions, lite-restore
1283 GEM_BUG_ON(status & GEN8_CTX_STATUS_PREEMPTED);
1284 GEM_BUG_ON(port_isset(&port[1]) &&
1285 !(status & GEN8_CTX_STATUS_ELEMENT_SWITCH));
1286 GEM_BUG_ON(!port_isset(&port[1]) &&
1287 !(status & GEN8_CTX_STATUS_ACTIVE_IDLE));
1290 * We rely on the hardware being strongly
1291 * ordered, that the breadcrumb write is
1292 * coherent (visible from the CPU) before the
1293 * user interrupt and CSB is processed.
1295 GEM_BUG_ON(!i915_request_completed(rq));
1297 execlists_context_schedule_out(rq,
1298 INTEL_CONTEXT_SCHEDULE_OUT);
1299 i915_request_put(rq);
1301 GEM_TRACE("%s completed ctx=%d\n",
1302 engine->name, port->context_id);
1304 port = execlists_port_complete(execlists, port);
1305 if (port_isset(port))
1306 execlists_user_begin(execlists, port);
1308 execlists_user_end(execlists);
1310 port_set(port, port_pack(rq, count));
1312 } while (head != tail);
1314 execlists->csb_head = head;
1317 * Gen11 has proven to fail wrt global observation point between
1318 * entry and tail update, failing on the ordering and thus
1319 * we see an old entry in the context status buffer.
1321 * Forcibly evict out entries for the next gpu csb update,
1322 * to increase the odds that we get a fresh entries with non
1323 * working hardware. The cost for doing so comes out mostly with
1324 * the wash as hardware, working or not, will need to do the
1325 * invalidation before.
1327 invalidate_csb_entries(&buf[0], &buf[num_entries - 1]);
1330 static void __execlists_submission_tasklet(struct intel_engine_cs *const engine)
1332 lockdep_assert_held(&engine->active.lock);
1334 process_csb(engine);
1335 if (!execlists_is_active(&engine->execlists, EXECLISTS_ACTIVE_PREEMPT))
1336 execlists_dequeue(engine);
1340 * Check the unread Context Status Buffers and manage the submission of new
1341 * contexts to the ELSP accordingly.
1343 static void execlists_submission_tasklet(unsigned long data)
1345 struct intel_engine_cs * const engine = (struct intel_engine_cs *)data;
1346 unsigned long flags;
1348 GEM_TRACE("%s awake?=%d, active=%x\n",
1350 !!intel_wakeref_active(&engine->wakeref),
1351 engine->execlists.active);
1353 spin_lock_irqsave(&engine->active.lock, flags);
1354 __execlists_submission_tasklet(engine);
1355 spin_unlock_irqrestore(&engine->active.lock, flags);
1358 static void queue_request(struct intel_engine_cs *engine,
1359 struct i915_sched_node *node,
1362 GEM_BUG_ON(!list_empty(&node->link));
1363 list_add_tail(&node->link, i915_sched_lookup_priolist(engine, prio));
1366 static void __submit_queue_imm(struct intel_engine_cs *engine)
1368 struct intel_engine_execlists * const execlists = &engine->execlists;
1370 if (reset_in_progress(execlists))
1371 return; /* defer until we restart the engine following reset */
1373 if (execlists->tasklet.func == execlists_submission_tasklet)
1374 __execlists_submission_tasklet(engine);
1376 tasklet_hi_schedule(&execlists->tasklet);
1379 static void submit_queue(struct intel_engine_cs *engine, int prio)
1381 if (prio > engine->execlists.queue_priority_hint) {
1382 engine->execlists.queue_priority_hint = prio;
1383 __submit_queue_imm(engine);
1387 static void execlists_submit_request(struct i915_request *request)
1389 struct intel_engine_cs *engine = request->engine;
1390 unsigned long flags;
1392 /* Will be called from irq-context when using foreign fences. */
1393 spin_lock_irqsave(&engine->active.lock, flags);
1395 queue_request(engine, &request->sched, rq_prio(request));
1397 GEM_BUG_ON(RB_EMPTY_ROOT(&engine->execlists.queue.rb_root));
1398 GEM_BUG_ON(list_empty(&request->sched.link));
1400 submit_queue(engine, rq_prio(request));
1402 spin_unlock_irqrestore(&engine->active.lock, flags);
1405 static void __execlists_context_fini(struct intel_context *ce)
1407 intel_ring_put(ce->ring);
1409 GEM_BUG_ON(i915_gem_object_is_active(ce->state->obj));
1410 i915_gem_object_put(ce->state->obj);
1413 static void execlists_context_destroy(struct kref *kref)
1415 struct intel_context *ce = container_of(kref, typeof(*ce), ref);
1417 GEM_BUG_ON(!i915_active_is_idle(&ce->active));
1418 GEM_BUG_ON(intel_context_is_pinned(ce));
1421 __execlists_context_fini(ce);
1423 intel_context_free(ce);
1426 static void execlists_context_unpin(struct intel_context *ce)
1428 i915_gem_context_unpin_hw_id(ce->gem_context);
1429 i915_gem_object_unpin_map(ce->state->obj);
1433 __execlists_update_reg_state(struct intel_context *ce,
1434 struct intel_engine_cs *engine)
1436 struct intel_ring *ring = ce->ring;
1437 u32 *regs = ce->lrc_reg_state;
1439 GEM_BUG_ON(!intel_ring_offset_valid(ring, ring->head));
1440 GEM_BUG_ON(!intel_ring_offset_valid(ring, ring->tail));
1442 regs[CTX_RING_BUFFER_START + 1] = i915_ggtt_offset(ring->vma);
1443 regs[CTX_RING_HEAD + 1] = ring->head;
1444 regs[CTX_RING_TAIL + 1] = ring->tail;
1447 if (engine->class == RENDER_CLASS)
1448 regs[CTX_R_PWR_CLK_STATE + 1] =
1449 intel_sseu_make_rpcs(engine->i915, &ce->sseu);
1453 __execlists_context_pin(struct intel_context *ce,
1454 struct intel_engine_cs *engine)
1459 GEM_BUG_ON(!ce->gem_context->vm);
1461 ret = execlists_context_deferred_alloc(ce, engine);
1464 GEM_BUG_ON(!ce->state);
1466 ret = intel_context_active_acquire(ce,
1467 engine->i915->ggtt.pin_bias |
1473 vaddr = i915_gem_object_pin_map(ce->state->obj,
1474 i915_coherent_map_type(engine->i915) |
1476 if (IS_ERR(vaddr)) {
1477 ret = PTR_ERR(vaddr);
1481 ret = i915_gem_context_pin_hw_id(ce->gem_context);
1485 ce->lrc_desc = lrc_descriptor(ce, engine);
1486 ce->lrc_reg_state = vaddr + LRC_STATE_PN * PAGE_SIZE;
1487 __execlists_update_reg_state(ce, engine);
1492 i915_gem_object_unpin_map(ce->state->obj);
1494 intel_context_active_release(ce);
1499 static int execlists_context_pin(struct intel_context *ce)
1501 return __execlists_context_pin(ce, ce->engine);
1504 static void execlists_context_reset(struct intel_context *ce)
1507 * Because we emit WA_TAIL_DWORDS there may be a disparity
1508 * between our bookkeeping in ce->ring->head and ce->ring->tail and
1509 * that stored in context. As we only write new commands from
1510 * ce->ring->tail onwards, everything before that is junk. If the GPU
1511 * starts reading from its RING_HEAD from the context, it may try to
1512 * execute that junk and die.
1514 * The contexts that are stilled pinned on resume belong to the
1515 * kernel, and are local to each engine. All other contexts will
1516 * have their head/tail sanitized upon pinning before use, so they
1517 * will never see garbage,
1519 * So to avoid that we reset the context images upon resume. For
1520 * simplicity, we just zero everything out.
1522 intel_ring_reset(ce->ring, 0);
1523 __execlists_update_reg_state(ce, ce->engine);
1526 static const struct intel_context_ops execlists_context_ops = {
1527 .pin = execlists_context_pin,
1528 .unpin = execlists_context_unpin,
1530 .enter = intel_context_enter_engine,
1531 .exit = intel_context_exit_engine,
1533 .reset = execlists_context_reset,
1534 .destroy = execlists_context_destroy,
1537 static int gen8_emit_init_breadcrumb(struct i915_request *rq)
1541 GEM_BUG_ON(!rq->timeline->has_initial_breadcrumb);
1543 cs = intel_ring_begin(rq, 6);
1548 * Check if we have been preempted before we even get started.
1550 * After this point i915_request_started() reports true, even if
1551 * we get preempted and so are no longer running.
1553 *cs++ = MI_ARB_CHECK;
1556 *cs++ = MI_STORE_DWORD_IMM_GEN4 | MI_USE_GGTT;
1557 *cs++ = rq->timeline->hwsp_offset;
1559 *cs++ = rq->fence.seqno - 1;
1561 intel_ring_advance(rq, cs);
1563 /* Record the updated position of the request's payload */
1564 rq->infix = intel_ring_offset(rq, cs);
1569 static int emit_pdps(struct i915_request *rq)
1571 const struct intel_engine_cs * const engine = rq->engine;
1572 struct i915_ppgtt * const ppgtt =
1573 i915_vm_to_ppgtt(rq->gem_context->vm);
1577 GEM_BUG_ON(intel_vgpu_active(rq->i915));
1580 * Beware ye of the dragons, this sequence is magic!
1582 * Small changes to this sequence can cause anything from
1583 * GPU hangs to forcewake errors and machine lockups!
1586 /* Flush any residual operations from the context load */
1587 err = engine->emit_flush(rq, EMIT_FLUSH);
1591 /* Magic required to prevent forcewake errors! */
1592 err = engine->emit_flush(rq, EMIT_INVALIDATE);
1596 cs = intel_ring_begin(rq, 4 * GEN8_3LVL_PDPES + 2);
1600 /* Ensure the LRI have landed before we invalidate & continue */
1601 *cs++ = MI_LOAD_REGISTER_IMM(2 * GEN8_3LVL_PDPES) | MI_LRI_FORCE_POSTED;
1602 for (i = GEN8_3LVL_PDPES; i--; ) {
1603 const dma_addr_t pd_daddr = i915_page_dir_dma_addr(ppgtt, i);
1604 u32 base = engine->mmio_base;
1606 *cs++ = i915_mmio_reg_offset(GEN8_RING_PDP_UDW(base, i));
1607 *cs++ = upper_32_bits(pd_daddr);
1608 *cs++ = i915_mmio_reg_offset(GEN8_RING_PDP_LDW(base, i));
1609 *cs++ = lower_32_bits(pd_daddr);
1613 intel_ring_advance(rq, cs);
1615 /* Be doubly sure the LRI have landed before proceeding */
1616 err = engine->emit_flush(rq, EMIT_FLUSH);
1620 /* Re-invalidate the TLB for luck */
1621 return engine->emit_flush(rq, EMIT_INVALIDATE);
1624 static int execlists_request_alloc(struct i915_request *request)
1628 GEM_BUG_ON(!intel_context_is_pinned(request->hw_context));
1631 * Flush enough space to reduce the likelihood of waiting after
1632 * we start building the request - in which case we will just
1633 * have to repeat work.
1635 request->reserved_space += EXECLISTS_REQUEST_SIZE;
1638 * Note that after this point, we have committed to using
1639 * this request as it is being used to both track the
1640 * state of engine initialisation and liveness of the
1641 * golden renderstate above. Think twice before you try
1642 * to cancel/unwind this request now.
1645 /* Unconditionally invalidate GPU caches and TLBs. */
1646 if (i915_vm_is_4lvl(request->gem_context->vm))
1647 ret = request->engine->emit_flush(request, EMIT_INVALIDATE);
1649 ret = emit_pdps(request);
1653 request->reserved_space -= EXECLISTS_REQUEST_SIZE;
1658 * In this WA we need to set GEN8_L3SQCREG4[21:21] and reset it after
1659 * PIPE_CONTROL instruction. This is required for the flush to happen correctly
1660 * but there is a slight complication as this is applied in WA batch where the
1661 * values are only initialized once so we cannot take register value at the
1662 * beginning and reuse it further; hence we save its value to memory, upload a
1663 * constant value with bit21 set and then we restore it back with the saved value.
1664 * To simplify the WA, a constant value is formed by using the default value
1665 * of this register. This shouldn't be a problem because we are only modifying
1666 * it for a short period and this batch in non-premptible. We can ofcourse
1667 * use additional instructions that read the actual value of the register
1668 * at that time and set our bit of interest but it makes the WA complicated.
1670 * This WA is also required for Gen9 so extracting as a function avoids
1674 gen8_emit_flush_coherentl3_wa(struct intel_engine_cs *engine, u32 *batch)
1676 /* NB no one else is allowed to scribble over scratch + 256! */
1677 *batch++ = MI_STORE_REGISTER_MEM_GEN8 | MI_SRM_LRM_GLOBAL_GTT;
1678 *batch++ = i915_mmio_reg_offset(GEN8_L3SQCREG4);
1679 *batch++ = i915_scratch_offset(engine->i915) + 256;
1682 *batch++ = MI_LOAD_REGISTER_IMM(1);
1683 *batch++ = i915_mmio_reg_offset(GEN8_L3SQCREG4);
1684 *batch++ = 0x40400000 | GEN8_LQSC_FLUSH_COHERENT_LINES;
1686 batch = gen8_emit_pipe_control(batch,
1687 PIPE_CONTROL_CS_STALL |
1688 PIPE_CONTROL_DC_FLUSH_ENABLE,
1691 *batch++ = MI_LOAD_REGISTER_MEM_GEN8 | MI_SRM_LRM_GLOBAL_GTT;
1692 *batch++ = i915_mmio_reg_offset(GEN8_L3SQCREG4);
1693 *batch++ = i915_scratch_offset(engine->i915) + 256;
1700 * Typically we only have one indirect_ctx and per_ctx batch buffer which are
1701 * initialized at the beginning and shared across all contexts but this field
1702 * helps us to have multiple batches at different offsets and select them based
1703 * on a criteria. At the moment this batch always start at the beginning of the page
1704 * and at this point we don't have multiple wa_ctx batch buffers.
1706 * The number of WA applied are not known at the beginning; we use this field
1707 * to return the no of DWORDS written.
1709 * It is to be noted that this batch does not contain MI_BATCH_BUFFER_END
1710 * so it adds NOOPs as padding to make it cacheline aligned.
1711 * MI_BATCH_BUFFER_END will be added to perctx batch and both of them together
1712 * makes a complete batch buffer.
1714 static u32 *gen8_init_indirectctx_bb(struct intel_engine_cs *engine, u32 *batch)
1716 /* WaDisableCtxRestoreArbitration:bdw,chv */
1717 *batch++ = MI_ARB_ON_OFF | MI_ARB_DISABLE;
1719 /* WaFlushCoherentL3CacheLinesAtContextSwitch:bdw */
1720 if (IS_BROADWELL(engine->i915))
1721 batch = gen8_emit_flush_coherentl3_wa(engine, batch);
1723 /* WaClearSlmSpaceAtContextSwitch:bdw,chv */
1724 /* Actual scratch location is at 128 bytes offset */
1725 batch = gen8_emit_pipe_control(batch,
1726 PIPE_CONTROL_FLUSH_L3 |
1727 PIPE_CONTROL_GLOBAL_GTT_IVB |
1728 PIPE_CONTROL_CS_STALL |
1729 PIPE_CONTROL_QW_WRITE,
1730 i915_scratch_offset(engine->i915) +
1731 2 * CACHELINE_BYTES);
1733 *batch++ = MI_ARB_ON_OFF | MI_ARB_ENABLE;
1735 /* Pad to end of cacheline */
1736 while ((unsigned long)batch % CACHELINE_BYTES)
1740 * MI_BATCH_BUFFER_END is not required in Indirect ctx BB because
1741 * execution depends on the length specified in terms of cache lines
1742 * in the register CTX_RCS_INDIRECT_CTX
1753 static u32 *emit_lri(u32 *batch, const struct lri *lri, unsigned int count)
1755 GEM_BUG_ON(!count || count > 63);
1757 *batch++ = MI_LOAD_REGISTER_IMM(count);
1759 *batch++ = i915_mmio_reg_offset(lri->reg);
1760 *batch++ = lri->value;
1761 } while (lri++, --count);
1767 static u32 *gen9_init_indirectctx_bb(struct intel_engine_cs *engine, u32 *batch)
1769 static const struct lri lri[] = {
1770 /* WaDisableGatherAtSetShaderCommonSlice:skl,bxt,kbl,glk */
1772 COMMON_SLICE_CHICKEN2,
1773 __MASKED_FIELD(GEN9_DISABLE_GATHER_AT_SET_SHADER_COMMON_SLICE,
1780 __MASKED_FIELD(FF_SLICE_CHICKEN_CL_PROVOKING_VERTEX_FIX,
1781 FF_SLICE_CHICKEN_CL_PROVOKING_VERTEX_FIX),
1787 __MASKED_FIELD(_3D_CHICKEN_SF_PROVOKING_VERTEX_FIX,
1788 _3D_CHICKEN_SF_PROVOKING_VERTEX_FIX),
1792 *batch++ = MI_ARB_ON_OFF | MI_ARB_DISABLE;
1794 /* WaFlushCoherentL3CacheLinesAtContextSwitch:skl,bxt,glk */
1795 batch = gen8_emit_flush_coherentl3_wa(engine, batch);
1797 batch = emit_lri(batch, lri, ARRAY_SIZE(lri));
1799 /* WaMediaPoolStateCmdInWABB:bxt,glk */
1800 if (HAS_POOLED_EU(engine->i915)) {
1802 * EU pool configuration is setup along with golden context
1803 * during context initialization. This value depends on
1804 * device type (2x6 or 3x6) and needs to be updated based
1805 * on which subslice is disabled especially for 2x6
1806 * devices, however it is safe to load default
1807 * configuration of 3x6 device instead of masking off
1808 * corresponding bits because HW ignores bits of a disabled
1809 * subslice and drops down to appropriate config. Please
1810 * see render_state_setup() in i915_gem_render_state.c for
1811 * possible configurations, to avoid duplication they are
1812 * not shown here again.
1814 *batch++ = GEN9_MEDIA_POOL_STATE;
1815 *batch++ = GEN9_MEDIA_POOL_ENABLE;
1816 *batch++ = 0x00777000;
1822 *batch++ = MI_ARB_ON_OFF | MI_ARB_ENABLE;
1824 /* Pad to end of cacheline */
1825 while ((unsigned long)batch % CACHELINE_BYTES)
1832 gen10_init_indirectctx_bb(struct intel_engine_cs *engine, u32 *batch)
1837 * WaPipeControlBefore3DStateSamplePattern: cnl
1839 * Ensure the engine is idle prior to programming a
1840 * 3DSTATE_SAMPLE_PATTERN during a context restore.
1842 batch = gen8_emit_pipe_control(batch,
1843 PIPE_CONTROL_CS_STALL,
1846 * WaPipeControlBefore3DStateSamplePattern says we need 4 dwords for
1847 * the PIPE_CONTROL followed by 12 dwords of 0x0, so 16 dwords in
1848 * total. However, a PIPE_CONTROL is 6 dwords long, not 4, which is
1849 * confusing. Since gen8_emit_pipe_control() already advances the
1850 * batch by 6 dwords, we advance the other 10 here, completing a
1851 * cacheline. It's not clear if the workaround requires this padding
1852 * before other commands, or if it's just the regular padding we would
1853 * already have for the workaround bb, so leave it here for now.
1855 for (i = 0; i < 10; i++)
1858 /* Pad to end of cacheline */
1859 while ((unsigned long)batch % CACHELINE_BYTES)
1865 #define CTX_WA_BB_OBJ_SIZE (PAGE_SIZE)
1867 static int lrc_setup_wa_ctx(struct intel_engine_cs *engine)
1869 struct drm_i915_gem_object *obj;
1870 struct i915_vma *vma;
1873 obj = i915_gem_object_create_shmem(engine->i915, CTX_WA_BB_OBJ_SIZE);
1875 return PTR_ERR(obj);
1877 vma = i915_vma_instance(obj, &engine->i915->ggtt.vm, NULL);
1883 err = i915_vma_pin(vma, 0, 0, PIN_GLOBAL | PIN_HIGH);
1887 engine->wa_ctx.vma = vma;
1891 i915_gem_object_put(obj);
1895 static void lrc_destroy_wa_ctx(struct intel_engine_cs *engine)
1897 i915_vma_unpin_and_release(&engine->wa_ctx.vma, 0);
1900 typedef u32 *(*wa_bb_func_t)(struct intel_engine_cs *engine, u32 *batch);
1902 static int intel_init_workaround_bb(struct intel_engine_cs *engine)
1904 struct i915_ctx_workarounds *wa_ctx = &engine->wa_ctx;
1905 struct i915_wa_ctx_bb *wa_bb[2] = { &wa_ctx->indirect_ctx,
1907 wa_bb_func_t wa_bb_fn[2];
1909 void *batch, *batch_ptr;
1913 if (engine->class != RENDER_CLASS)
1916 switch (INTEL_GEN(engine->i915)) {
1920 wa_bb_fn[0] = gen10_init_indirectctx_bb;
1924 wa_bb_fn[0] = gen9_init_indirectctx_bb;
1928 wa_bb_fn[0] = gen8_init_indirectctx_bb;
1932 MISSING_CASE(INTEL_GEN(engine->i915));
1936 ret = lrc_setup_wa_ctx(engine);
1938 DRM_DEBUG_DRIVER("Failed to setup context WA page: %d\n", ret);
1942 page = i915_gem_object_get_dirty_page(wa_ctx->vma->obj, 0);
1943 batch = batch_ptr = kmap_atomic(page);
1946 * Emit the two workaround batch buffers, recording the offset from the
1947 * start of the workaround batch buffer object for each and their
1950 for (i = 0; i < ARRAY_SIZE(wa_bb_fn); i++) {
1951 wa_bb[i]->offset = batch_ptr - batch;
1952 if (GEM_DEBUG_WARN_ON(!IS_ALIGNED(wa_bb[i]->offset,
1953 CACHELINE_BYTES))) {
1958 batch_ptr = wa_bb_fn[i](engine, batch_ptr);
1959 wa_bb[i]->size = batch_ptr - (batch + wa_bb[i]->offset);
1962 BUG_ON(batch_ptr - batch > CTX_WA_BB_OBJ_SIZE);
1964 kunmap_atomic(batch);
1966 lrc_destroy_wa_ctx(engine);
1971 static void enable_execlists(struct intel_engine_cs *engine)
1973 intel_engine_set_hwsp_writemask(engine, ~0u); /* HWSTAM */
1975 if (INTEL_GEN(engine->i915) >= 11)
1976 ENGINE_WRITE(engine,
1978 _MASKED_BIT_ENABLE(GEN11_GFX_DISABLE_LEGACY_MODE));
1980 ENGINE_WRITE(engine,
1982 _MASKED_BIT_ENABLE(GFX_RUN_LIST_ENABLE));
1984 ENGINE_WRITE(engine, RING_MI_MODE, _MASKED_BIT_DISABLE(STOP_RING));
1986 ENGINE_WRITE(engine,
1988 i915_ggtt_offset(engine->status_page.vma));
1989 ENGINE_POSTING_READ(engine, RING_HWS_PGA);
1992 static bool unexpected_starting_state(struct intel_engine_cs *engine)
1994 bool unexpected = false;
1996 if (ENGINE_READ(engine, RING_MI_MODE) & STOP_RING) {
1997 DRM_DEBUG_DRIVER("STOP_RING still set in RING_MI_MODE\n");
2004 static int execlists_resume(struct intel_engine_cs *engine)
2006 intel_engine_apply_workarounds(engine);
2007 intel_engine_apply_whitelist(engine);
2009 intel_mocs_init_engine(engine);
2011 intel_engine_reset_breadcrumbs(engine);
2013 if (GEM_SHOW_DEBUG() && unexpected_starting_state(engine)) {
2014 struct drm_printer p = drm_debug_printer(__func__);
2016 intel_engine_dump(engine, &p, NULL);
2019 enable_execlists(engine);
2024 static void execlists_reset_prepare(struct intel_engine_cs *engine)
2026 struct intel_engine_execlists * const execlists = &engine->execlists;
2027 unsigned long flags;
2029 GEM_TRACE("%s: depth<-%d\n", engine->name,
2030 atomic_read(&execlists->tasklet.count));
2033 * Prevent request submission to the hardware until we have
2034 * completed the reset in i915_gem_reset_finish(). If a request
2035 * is completed by one engine, it may then queue a request
2036 * to a second via its execlists->tasklet *just* as we are
2037 * calling engine->resume() and also writing the ELSP.
2038 * Turning off the execlists->tasklet until the reset is over
2039 * prevents the race.
2041 __tasklet_disable_sync_once(&execlists->tasklet);
2042 GEM_BUG_ON(!reset_in_progress(execlists));
2044 intel_engine_stop_cs(engine);
2046 /* And flush any current direct submission. */
2047 spin_lock_irqsave(&engine->active.lock, flags);
2048 spin_unlock_irqrestore(&engine->active.lock, flags);
2051 static bool lrc_regs_ok(const struct i915_request *rq)
2053 const struct intel_ring *ring = rq->ring;
2054 const u32 *regs = rq->hw_context->lrc_reg_state;
2056 /* Quick spot check for the common signs of context corruption */
2058 if (regs[CTX_RING_BUFFER_CONTROL + 1] !=
2059 (RING_CTL_SIZE(ring->size) | RING_VALID))
2062 if (regs[CTX_RING_BUFFER_START + 1] != i915_ggtt_offset(ring->vma))
2068 static void reset_csb_pointers(struct intel_engine_execlists *execlists)
2070 const unsigned int reset_value = execlists->csb_size - 1;
2073 * After a reset, the HW starts writing into CSB entry [0]. We
2074 * therefore have to set our HEAD pointer back one entry so that
2075 * the *first* entry we check is entry 0. To complicate this further,
2076 * as we don't wait for the first interrupt after reset, we have to
2077 * fake the HW write to point back to the last entry so that our
2078 * inline comparison of our cached head position against the last HW
2079 * write works even before the first interrupt.
2081 execlists->csb_head = reset_value;
2082 WRITE_ONCE(*execlists->csb_write, reset_value);
2083 wmb(); /* Make sure this is visible to HW (paranoia?) */
2085 invalidate_csb_entries(&execlists->csb_status[0],
2086 &execlists->csb_status[reset_value]);
2089 static struct i915_request *active_request(struct i915_request *rq)
2091 const struct list_head * const list = &rq->engine->active.requests;
2092 const struct intel_context * const context = rq->hw_context;
2093 struct i915_request *active = NULL;
2095 list_for_each_entry_from_reverse(rq, list, sched.link) {
2096 if (i915_request_completed(rq))
2099 if (rq->hw_context != context)
2108 static void __execlists_reset(struct intel_engine_cs *engine, bool stalled)
2110 struct intel_engine_execlists * const execlists = &engine->execlists;
2111 struct intel_context *ce;
2112 struct i915_request *rq;
2115 process_csb(engine); /* drain preemption events */
2117 /* Following the reset, we need to reload the CSB read/write pointers */
2118 reset_csb_pointers(&engine->execlists);
2121 * Save the currently executing context, even if we completed
2122 * its request, it was still running at the time of the
2123 * reset and will have been clobbered.
2125 if (!port_isset(execlists->port))
2128 rq = port_request(execlists->port);
2129 ce = rq->hw_context;
2132 * Catch up with any missed context-switch interrupts.
2134 * Ideally we would just read the remaining CSB entries now that we
2135 * know the gpu is idle. However, the CSB registers are sometimes^W
2136 * often trashed across a GPU reset! Instead we have to rely on
2137 * guessing the missed context-switch events by looking at what
2138 * requests were completed.
2140 execlists_cancel_port_requests(execlists);
2142 rq = active_request(rq);
2147 * If this request hasn't started yet, e.g. it is waiting on a
2148 * semaphore, we need to avoid skipping the request or else we
2149 * break the signaling chain. However, if the context is corrupt
2150 * the request will not restart and we will be stuck with a wedged
2151 * device. It is quite often the case that if we issue a reset
2152 * while the GPU is loading the context image, that the context
2153 * image becomes corrupt.
2155 * Otherwise, if we have not started yet, the request should replay
2156 * perfectly and we do not need to flag the result as being erroneous.
2158 if (!i915_request_started(rq) && lrc_regs_ok(rq))
2162 * If the request was innocent, we leave the request in the ELSP
2163 * and will try to replay it on restarting. The context image may
2164 * have been corrupted by the reset, in which case we may have
2165 * to service a new GPU hang, but more likely we can continue on
2168 * If the request was guilty, we presume the context is corrupt
2169 * and have to at least restore the RING register in the context
2170 * image back to the expected values to skip over the guilty request.
2172 i915_reset_request(rq, stalled);
2173 if (!stalled && lrc_regs_ok(rq))
2177 * We want a simple context + ring to execute the breadcrumb update.
2178 * We cannot rely on the context being intact across the GPU hang,
2179 * so clear it and rebuild just what we need for the breadcrumb.
2180 * All pending requests for this context will be zapped, and any
2181 * future request will be after userspace has had the opportunity
2182 * to recreate its own state.
2184 regs = ce->lrc_reg_state;
2185 if (engine->pinned_default_state) {
2186 memcpy(regs, /* skip restoring the vanilla PPHWSP */
2187 engine->pinned_default_state + LRC_STATE_PN * PAGE_SIZE,
2188 engine->context_size - PAGE_SIZE);
2190 execlists_init_reg_state(regs, ce, engine, ce->ring);
2193 /* Rerun the request; its payload has been neutered (if guilty). */
2195 rq ? intel_ring_wrap(ce->ring, rq->head) : ce->ring->tail;
2196 intel_ring_update_space(ce->ring);
2197 __execlists_update_reg_state(ce, engine);
2199 /* Push back any incomplete requests for replay after the reset. */
2200 __unwind_incomplete_requests(engine);
2203 execlists_clear_all_active(execlists);
2206 static void execlists_reset(struct intel_engine_cs *engine, bool stalled)
2208 unsigned long flags;
2210 GEM_TRACE("%s\n", engine->name);
2212 spin_lock_irqsave(&engine->active.lock, flags);
2214 __execlists_reset(engine, stalled);
2216 spin_unlock_irqrestore(&engine->active.lock, flags);
2219 static void nop_submission_tasklet(unsigned long data)
2221 /* The driver is wedged; don't process any more events. */
2224 static void execlists_cancel_requests(struct intel_engine_cs *engine)
2226 struct intel_engine_execlists * const execlists = &engine->execlists;
2227 struct i915_request *rq, *rn;
2229 unsigned long flags;
2231 GEM_TRACE("%s\n", engine->name);
2234 * Before we call engine->cancel_requests(), we should have exclusive
2235 * access to the submission state. This is arranged for us by the
2236 * caller disabling the interrupt generation, the tasklet and other
2237 * threads that may then access the same state, giving us a free hand
2238 * to reset state. However, we still need to let lockdep be aware that
2239 * we know this state may be accessed in hardirq context, so we
2240 * disable the irq around this manipulation and we want to keep
2241 * the spinlock focused on its duties and not accidentally conflate
2242 * coverage to the submission's irq state. (Similarly, although we
2243 * shouldn't need to disable irq around the manipulation of the
2244 * submission's irq state, we also wish to remind ourselves that
2247 spin_lock_irqsave(&engine->active.lock, flags);
2249 __execlists_reset(engine, true);
2251 /* Mark all executing requests as skipped. */
2252 list_for_each_entry(rq, &engine->active.requests, sched.link) {
2253 if (!i915_request_signaled(rq))
2254 dma_fence_set_error(&rq->fence, -EIO);
2256 i915_request_mark_complete(rq);
2259 /* Flush the queued requests to the timeline list (for retiring). */
2260 while ((rb = rb_first_cached(&execlists->queue))) {
2261 struct i915_priolist *p = to_priolist(rb);
2264 priolist_for_each_request_consume(rq, rn, p, i) {
2265 list_del_init(&rq->sched.link);
2266 __i915_request_submit(rq);
2267 dma_fence_set_error(&rq->fence, -EIO);
2268 i915_request_mark_complete(rq);
2271 rb_erase_cached(&p->node, &execlists->queue);
2272 i915_priolist_free(p);
2275 /* Cancel all attached virtual engines */
2276 while ((rb = rb_first_cached(&execlists->virtual))) {
2277 struct virtual_engine *ve =
2278 rb_entry(rb, typeof(*ve), nodes[engine->id].rb);
2280 rb_erase_cached(rb, &execlists->virtual);
2283 spin_lock(&ve->base.active.lock);
2285 ve->request->engine = engine;
2286 __i915_request_submit(ve->request);
2287 dma_fence_set_error(&ve->request->fence, -EIO);
2288 i915_request_mark_complete(ve->request);
2289 ve->base.execlists.queue_priority_hint = INT_MIN;
2292 spin_unlock(&ve->base.active.lock);
2295 /* Remaining _unready_ requests will be nop'ed when submitted */
2297 execlists->queue_priority_hint = INT_MIN;
2298 execlists->queue = RB_ROOT_CACHED;
2299 GEM_BUG_ON(port_isset(execlists->port));
2301 GEM_BUG_ON(__tasklet_is_enabled(&execlists->tasklet));
2302 execlists->tasklet.func = nop_submission_tasklet;
2304 spin_unlock_irqrestore(&engine->active.lock, flags);
2307 static void execlists_reset_finish(struct intel_engine_cs *engine)
2309 struct intel_engine_execlists * const execlists = &engine->execlists;
2312 * After a GPU reset, we may have requests to replay. Do so now while
2313 * we still have the forcewake to be sure that the GPU is not allowed
2314 * to sleep before we restart and reload a context.
2316 GEM_BUG_ON(!reset_in_progress(execlists));
2317 if (!RB_EMPTY_ROOT(&execlists->queue.rb_root))
2318 execlists->tasklet.func(execlists->tasklet.data);
2320 if (__tasklet_enable(&execlists->tasklet))
2321 /* And kick in case we missed a new request submission. */
2322 tasklet_hi_schedule(&execlists->tasklet);
2323 GEM_TRACE("%s: depth->%d\n", engine->name,
2324 atomic_read(&execlists->tasklet.count));
2327 static int gen8_emit_bb_start(struct i915_request *rq,
2328 u64 offset, u32 len,
2329 const unsigned int flags)
2333 cs = intel_ring_begin(rq, 4);
2338 * WaDisableCtxRestoreArbitration:bdw,chv
2340 * We don't need to perform MI_ARB_ENABLE as often as we do (in
2341 * particular all the gen that do not need the w/a at all!), if we
2342 * took care to make sure that on every switch into this context
2343 * (both ordinary and for preemption) that arbitrartion was enabled
2344 * we would be fine. However, for gen8 there is another w/a that
2345 * requires us to not preempt inside GPGPU execution, so we keep
2346 * arbitration disabled for gen8 batches. Arbitration will be
2347 * re-enabled before we close the request
2348 * (engine->emit_fini_breadcrumb).
2350 *cs++ = MI_ARB_ON_OFF | MI_ARB_DISABLE;
2352 /* FIXME(BDW+): Address space and security selectors. */
2353 *cs++ = MI_BATCH_BUFFER_START_GEN8 |
2354 (flags & I915_DISPATCH_SECURE ? 0 : BIT(8));
2355 *cs++ = lower_32_bits(offset);
2356 *cs++ = upper_32_bits(offset);
2358 intel_ring_advance(rq, cs);
2363 static int gen9_emit_bb_start(struct i915_request *rq,
2364 u64 offset, u32 len,
2365 const unsigned int flags)
2369 cs = intel_ring_begin(rq, 6);
2373 *cs++ = MI_ARB_ON_OFF | MI_ARB_ENABLE;
2375 *cs++ = MI_BATCH_BUFFER_START_GEN8 |
2376 (flags & I915_DISPATCH_SECURE ? 0 : BIT(8));
2377 *cs++ = lower_32_bits(offset);
2378 *cs++ = upper_32_bits(offset);
2380 *cs++ = MI_ARB_ON_OFF | MI_ARB_DISABLE;
2383 intel_ring_advance(rq, cs);
2388 static void gen8_logical_ring_enable_irq(struct intel_engine_cs *engine)
2390 ENGINE_WRITE(engine, RING_IMR,
2391 ~(engine->irq_enable_mask | engine->irq_keep_mask));
2392 ENGINE_POSTING_READ(engine, RING_IMR);
2395 static void gen8_logical_ring_disable_irq(struct intel_engine_cs *engine)
2397 ENGINE_WRITE(engine, RING_IMR, ~engine->irq_keep_mask);
2400 static int gen8_emit_flush(struct i915_request *request, u32 mode)
2404 cs = intel_ring_begin(request, 4);
2408 cmd = MI_FLUSH_DW + 1;
2410 /* We always require a command barrier so that subsequent
2411 * commands, such as breadcrumb interrupts, are strictly ordered
2412 * wrt the contents of the write cache being flushed to memory
2413 * (and thus being coherent from the CPU).
2415 cmd |= MI_FLUSH_DW_STORE_INDEX | MI_FLUSH_DW_OP_STOREDW;
2417 if (mode & EMIT_INVALIDATE) {
2418 cmd |= MI_INVALIDATE_TLB;
2419 if (request->engine->class == VIDEO_DECODE_CLASS)
2420 cmd |= MI_INVALIDATE_BSD;
2424 *cs++ = I915_GEM_HWS_SCRATCH_ADDR | MI_FLUSH_DW_USE_GTT;
2425 *cs++ = 0; /* upper addr */
2426 *cs++ = 0; /* value */
2427 intel_ring_advance(request, cs);
2432 static int gen8_emit_flush_render(struct i915_request *request,
2435 struct intel_engine_cs *engine = request->engine;
2437 i915_scratch_offset(engine->i915) + 2 * CACHELINE_BYTES;
2438 bool vf_flush_wa = false, dc_flush_wa = false;
2442 flags |= PIPE_CONTROL_CS_STALL;
2444 if (mode & EMIT_FLUSH) {
2445 flags |= PIPE_CONTROL_RENDER_TARGET_CACHE_FLUSH;
2446 flags |= PIPE_CONTROL_DEPTH_CACHE_FLUSH;
2447 flags |= PIPE_CONTROL_DC_FLUSH_ENABLE;
2448 flags |= PIPE_CONTROL_FLUSH_ENABLE;
2451 if (mode & EMIT_INVALIDATE) {
2452 flags |= PIPE_CONTROL_TLB_INVALIDATE;
2453 flags |= PIPE_CONTROL_INSTRUCTION_CACHE_INVALIDATE;
2454 flags |= PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE;
2455 flags |= PIPE_CONTROL_VF_CACHE_INVALIDATE;
2456 flags |= PIPE_CONTROL_CONST_CACHE_INVALIDATE;
2457 flags |= PIPE_CONTROL_STATE_CACHE_INVALIDATE;
2458 flags |= PIPE_CONTROL_QW_WRITE;
2459 flags |= PIPE_CONTROL_GLOBAL_GTT_IVB;
2462 * On GEN9: before VF_CACHE_INVALIDATE we need to emit a NULL
2465 if (IS_GEN(request->i915, 9))
2468 /* WaForGAMHang:kbl */
2469 if (IS_KBL_REVID(request->i915, 0, KBL_REVID_B0))
2481 cs = intel_ring_begin(request, len);
2486 cs = gen8_emit_pipe_control(cs, 0, 0);
2489 cs = gen8_emit_pipe_control(cs, PIPE_CONTROL_DC_FLUSH_ENABLE,
2492 cs = gen8_emit_pipe_control(cs, flags, scratch_addr);
2495 cs = gen8_emit_pipe_control(cs, PIPE_CONTROL_CS_STALL, 0);
2497 intel_ring_advance(request, cs);
2503 * Reserve space for 2 NOOPs at the end of each request to be
2504 * used as a workaround for not being allowed to do lite
2505 * restore with HEAD==TAIL (WaIdleLiteRestore).
2507 static u32 *gen8_emit_wa_tail(struct i915_request *request, u32 *cs)
2509 /* Ensure there's always at least one preemption point per-request. */
2510 *cs++ = MI_ARB_CHECK;
2512 request->wa_tail = intel_ring_offset(request, cs);
2517 static u32 *gen8_emit_fini_breadcrumb(struct i915_request *request, u32 *cs)
2519 cs = gen8_emit_ggtt_write(cs,
2520 request->fence.seqno,
2521 request->timeline->hwsp_offset,
2524 *cs++ = MI_USER_INTERRUPT;
2525 *cs++ = MI_ARB_ON_OFF | MI_ARB_ENABLE;
2527 request->tail = intel_ring_offset(request, cs);
2528 assert_ring_tail_valid(request->ring, request->tail);
2530 return gen8_emit_wa_tail(request, cs);
2533 static u32 *gen8_emit_fini_breadcrumb_rcs(struct i915_request *request, u32 *cs)
2535 /* XXX flush+write+CS_STALL all in one upsets gem_concurrent_blt:kbl */
2536 cs = gen8_emit_ggtt_write_rcs(cs,
2537 request->fence.seqno,
2538 request->timeline->hwsp_offset,
2539 PIPE_CONTROL_RENDER_TARGET_CACHE_FLUSH |
2540 PIPE_CONTROL_DEPTH_CACHE_FLUSH |
2541 PIPE_CONTROL_DC_FLUSH_ENABLE);
2542 cs = gen8_emit_pipe_control(cs,
2543 PIPE_CONTROL_FLUSH_ENABLE |
2544 PIPE_CONTROL_CS_STALL,
2547 *cs++ = MI_USER_INTERRUPT;
2548 *cs++ = MI_ARB_ON_OFF | MI_ARB_ENABLE;
2550 request->tail = intel_ring_offset(request, cs);
2551 assert_ring_tail_valid(request->ring, request->tail);
2553 return gen8_emit_wa_tail(request, cs);
2556 static int gen8_init_rcs_context(struct i915_request *rq)
2560 ret = intel_engine_emit_ctx_wa(rq);
2564 ret = intel_rcs_context_init_mocs(rq);
2566 * Failing to program the MOCS is non-fatal.The system will not
2567 * run at peak performance. So generate an error and carry on.
2570 DRM_ERROR("MOCS failed to program: expect performance issues.\n");
2572 return i915_gem_render_state_emit(rq);
2575 static void execlists_park(struct intel_engine_cs *engine)
2577 intel_engine_park(engine);
2580 void intel_execlists_set_default_submission(struct intel_engine_cs *engine)
2582 engine->submit_request = execlists_submit_request;
2583 engine->cancel_requests = execlists_cancel_requests;
2584 engine->schedule = i915_schedule;
2585 engine->execlists.tasklet.func = execlists_submission_tasklet;
2587 engine->reset.prepare = execlists_reset_prepare;
2588 engine->reset.reset = execlists_reset;
2589 engine->reset.finish = execlists_reset_finish;
2591 engine->park = execlists_park;
2592 engine->unpark = NULL;
2594 engine->flags |= I915_ENGINE_SUPPORTS_STATS;
2595 if (!intel_vgpu_active(engine->i915))
2596 engine->flags |= I915_ENGINE_HAS_SEMAPHORES;
2597 if (engine->preempt_context &&
2598 HAS_LOGICAL_RING_PREEMPTION(engine->i915))
2599 engine->flags |= I915_ENGINE_HAS_PREEMPTION;
2602 static void execlists_destroy(struct intel_engine_cs *engine)
2604 intel_engine_cleanup_common(engine);
2605 lrc_destroy_wa_ctx(engine);
2610 logical_ring_default_vfuncs(struct intel_engine_cs *engine)
2612 /* Default vfuncs which can be overriden by each engine. */
2614 engine->destroy = execlists_destroy;
2615 engine->resume = execlists_resume;
2617 engine->reset.prepare = execlists_reset_prepare;
2618 engine->reset.reset = execlists_reset;
2619 engine->reset.finish = execlists_reset_finish;
2621 engine->cops = &execlists_context_ops;
2622 engine->request_alloc = execlists_request_alloc;
2624 engine->emit_flush = gen8_emit_flush;
2625 engine->emit_init_breadcrumb = gen8_emit_init_breadcrumb;
2626 engine->emit_fini_breadcrumb = gen8_emit_fini_breadcrumb;
2628 engine->set_default_submission = intel_execlists_set_default_submission;
2630 if (INTEL_GEN(engine->i915) < 11) {
2631 engine->irq_enable = gen8_logical_ring_enable_irq;
2632 engine->irq_disable = gen8_logical_ring_disable_irq;
2635 * TODO: On Gen11 interrupt masks need to be clear
2636 * to allow C6 entry. Keep interrupts enabled at
2637 * and take the hit of generating extra interrupts
2638 * until a more refined solution exists.
2641 if (IS_GEN(engine->i915, 8))
2642 engine->emit_bb_start = gen8_emit_bb_start;
2644 engine->emit_bb_start = gen9_emit_bb_start;
2648 logical_ring_default_irqs(struct intel_engine_cs *engine)
2650 unsigned int shift = 0;
2652 if (INTEL_GEN(engine->i915) < 11) {
2653 const u8 irq_shifts[] = {
2654 [RCS0] = GEN8_RCS_IRQ_SHIFT,
2655 [BCS0] = GEN8_BCS_IRQ_SHIFT,
2656 [VCS0] = GEN8_VCS0_IRQ_SHIFT,
2657 [VCS1] = GEN8_VCS1_IRQ_SHIFT,
2658 [VECS0] = GEN8_VECS_IRQ_SHIFT,
2661 shift = irq_shifts[engine->id];
2664 engine->irq_enable_mask = GT_RENDER_USER_INTERRUPT << shift;
2665 engine->irq_keep_mask = GT_CONTEXT_SWITCH_INTERRUPT << shift;
2668 int intel_execlists_submission_setup(struct intel_engine_cs *engine)
2670 /* Intentionally left blank. */
2671 engine->buffer = NULL;
2673 tasklet_init(&engine->execlists.tasklet,
2674 execlists_submission_tasklet, (unsigned long)engine);
2676 logical_ring_default_vfuncs(engine);
2677 logical_ring_default_irqs(engine);
2679 if (engine->class == RENDER_CLASS) {
2680 engine->init_context = gen8_init_rcs_context;
2681 engine->emit_flush = gen8_emit_flush_render;
2682 engine->emit_fini_breadcrumb = gen8_emit_fini_breadcrumb_rcs;
2688 int intel_execlists_submission_init(struct intel_engine_cs *engine)
2690 struct intel_engine_execlists * const execlists = &engine->execlists;
2691 struct drm_i915_private *i915 = engine->i915;
2692 struct intel_uncore *uncore = engine->uncore;
2693 u32 base = engine->mmio_base;
2696 ret = intel_engine_init_common(engine);
2700 intel_engine_init_workarounds(engine);
2701 intel_engine_init_whitelist(engine);
2703 if (intel_init_workaround_bb(engine))
2705 * We continue even if we fail to initialize WA batch
2706 * because we only expect rare glitches but nothing
2707 * critical to prevent us from using GPU
2709 DRM_ERROR("WA batch buffer initialization failed\n");
2711 if (HAS_LOGICAL_RING_ELSQ(i915)) {
2712 execlists->submit_reg = uncore->regs +
2713 i915_mmio_reg_offset(RING_EXECLIST_SQ_CONTENTS(base));
2714 execlists->ctrl_reg = uncore->regs +
2715 i915_mmio_reg_offset(RING_EXECLIST_CONTROL(base));
2717 execlists->submit_reg = uncore->regs +
2718 i915_mmio_reg_offset(RING_ELSP(base));
2721 execlists->preempt_complete_status = ~0u;
2722 if (engine->preempt_context)
2723 execlists->preempt_complete_status =
2724 upper_32_bits(engine->preempt_context->lrc_desc);
2726 execlists->csb_status =
2727 &engine->status_page.addr[I915_HWS_CSB_BUF0_INDEX];
2729 execlists->csb_write =
2730 &engine->status_page.addr[intel_hws_csb_write_index(i915)];
2732 if (INTEL_GEN(i915) < 11)
2733 execlists->csb_size = GEN8_CSB_ENTRIES;
2735 execlists->csb_size = GEN11_CSB_ENTRIES;
2737 reset_csb_pointers(execlists);
2742 static u32 intel_lr_indirect_ctx_offset(struct intel_engine_cs *engine)
2744 u32 indirect_ctx_offset;
2746 switch (INTEL_GEN(engine->i915)) {
2748 MISSING_CASE(INTEL_GEN(engine->i915));
2751 indirect_ctx_offset =
2752 GEN11_CTX_RCS_INDIRECT_CTX_OFFSET_DEFAULT;
2755 indirect_ctx_offset =
2756 GEN10_CTX_RCS_INDIRECT_CTX_OFFSET_DEFAULT;
2759 indirect_ctx_offset =
2760 GEN9_CTX_RCS_INDIRECT_CTX_OFFSET_DEFAULT;
2763 indirect_ctx_offset =
2764 GEN8_CTX_RCS_INDIRECT_CTX_OFFSET_DEFAULT;
2768 return indirect_ctx_offset;
2771 static void execlists_init_reg_state(u32 *regs,
2772 struct intel_context *ce,
2773 struct intel_engine_cs *engine,
2774 struct intel_ring *ring)
2776 struct i915_ppgtt *ppgtt = i915_vm_to_ppgtt(ce->gem_context->vm);
2777 bool rcs = engine->class == RENDER_CLASS;
2778 u32 base = engine->mmio_base;
2781 * A context is actually a big batch buffer with several
2782 * MI_LOAD_REGISTER_IMM commands followed by (reg, value) pairs. The
2783 * values we are setting here are only for the first context restore:
2784 * on a subsequent save, the GPU will recreate this batchbuffer with new
2785 * values (including all the missing MI_LOAD_REGISTER_IMM commands that
2786 * we are not initializing here).
2788 * Must keep consistent with virtual_update_register_offsets().
2790 regs[CTX_LRI_HEADER_0] = MI_LOAD_REGISTER_IMM(rcs ? 14 : 11) |
2791 MI_LRI_FORCE_POSTED;
2793 CTX_REG(regs, CTX_CONTEXT_CONTROL, RING_CONTEXT_CONTROL(base),
2794 _MASKED_BIT_DISABLE(CTX_CTRL_ENGINE_CTX_RESTORE_INHIBIT) |
2795 _MASKED_BIT_ENABLE(CTX_CTRL_INHIBIT_SYN_CTX_SWITCH));
2796 if (INTEL_GEN(engine->i915) < 11) {
2797 regs[CTX_CONTEXT_CONTROL + 1] |=
2798 _MASKED_BIT_DISABLE(CTX_CTRL_ENGINE_CTX_SAVE_INHIBIT |
2799 CTX_CTRL_RS_CTX_ENABLE);
2801 CTX_REG(regs, CTX_RING_HEAD, RING_HEAD(base), 0);
2802 CTX_REG(regs, CTX_RING_TAIL, RING_TAIL(base), 0);
2803 CTX_REG(regs, CTX_RING_BUFFER_START, RING_START(base), 0);
2804 CTX_REG(regs, CTX_RING_BUFFER_CONTROL, RING_CTL(base),
2805 RING_CTL_SIZE(ring->size) | RING_VALID);
2806 CTX_REG(regs, CTX_BB_HEAD_U, RING_BBADDR_UDW(base), 0);
2807 CTX_REG(regs, CTX_BB_HEAD_L, RING_BBADDR(base), 0);
2808 CTX_REG(regs, CTX_BB_STATE, RING_BBSTATE(base), RING_BB_PPGTT);
2809 CTX_REG(regs, CTX_SECOND_BB_HEAD_U, RING_SBBADDR_UDW(base), 0);
2810 CTX_REG(regs, CTX_SECOND_BB_HEAD_L, RING_SBBADDR(base), 0);
2811 CTX_REG(regs, CTX_SECOND_BB_STATE, RING_SBBSTATE(base), 0);
2813 struct i915_ctx_workarounds *wa_ctx = &engine->wa_ctx;
2815 CTX_REG(regs, CTX_RCS_INDIRECT_CTX, RING_INDIRECT_CTX(base), 0);
2816 CTX_REG(regs, CTX_RCS_INDIRECT_CTX_OFFSET,
2817 RING_INDIRECT_CTX_OFFSET(base), 0);
2818 if (wa_ctx->indirect_ctx.size) {
2819 u32 ggtt_offset = i915_ggtt_offset(wa_ctx->vma);
2821 regs[CTX_RCS_INDIRECT_CTX + 1] =
2822 (ggtt_offset + wa_ctx->indirect_ctx.offset) |
2823 (wa_ctx->indirect_ctx.size / CACHELINE_BYTES);
2825 regs[CTX_RCS_INDIRECT_CTX_OFFSET + 1] =
2826 intel_lr_indirect_ctx_offset(engine) << 6;
2829 CTX_REG(regs, CTX_BB_PER_CTX_PTR, RING_BB_PER_CTX_PTR(base), 0);
2830 if (wa_ctx->per_ctx.size) {
2831 u32 ggtt_offset = i915_ggtt_offset(wa_ctx->vma);
2833 regs[CTX_BB_PER_CTX_PTR + 1] =
2834 (ggtt_offset + wa_ctx->per_ctx.offset) | 0x01;
2838 regs[CTX_LRI_HEADER_1] = MI_LOAD_REGISTER_IMM(9) | MI_LRI_FORCE_POSTED;
2840 CTX_REG(regs, CTX_CTX_TIMESTAMP, RING_CTX_TIMESTAMP(base), 0);
2841 /* PDP values well be assigned later if needed */
2842 CTX_REG(regs, CTX_PDP3_UDW, GEN8_RING_PDP_UDW(base, 3), 0);
2843 CTX_REG(regs, CTX_PDP3_LDW, GEN8_RING_PDP_LDW(base, 3), 0);
2844 CTX_REG(regs, CTX_PDP2_UDW, GEN8_RING_PDP_UDW(base, 2), 0);
2845 CTX_REG(regs, CTX_PDP2_LDW, GEN8_RING_PDP_LDW(base, 2), 0);
2846 CTX_REG(regs, CTX_PDP1_UDW, GEN8_RING_PDP_UDW(base, 1), 0);
2847 CTX_REG(regs, CTX_PDP1_LDW, GEN8_RING_PDP_LDW(base, 1), 0);
2848 CTX_REG(regs, CTX_PDP0_UDW, GEN8_RING_PDP_UDW(base, 0), 0);
2849 CTX_REG(regs, CTX_PDP0_LDW, GEN8_RING_PDP_LDW(base, 0), 0);
2851 if (i915_vm_is_4lvl(&ppgtt->vm)) {
2852 /* 64b PPGTT (48bit canonical)
2853 * PDP0_DESCRIPTOR contains the base address to PML4 and
2854 * other PDP Descriptors are ignored.
2856 ASSIGN_CTX_PML4(ppgtt, regs);
2858 ASSIGN_CTX_PDP(ppgtt, regs, 3);
2859 ASSIGN_CTX_PDP(ppgtt, regs, 2);
2860 ASSIGN_CTX_PDP(ppgtt, regs, 1);
2861 ASSIGN_CTX_PDP(ppgtt, regs, 0);
2865 regs[CTX_LRI_HEADER_2] = MI_LOAD_REGISTER_IMM(1);
2866 CTX_REG(regs, CTX_R_PWR_CLK_STATE, GEN8_R_PWR_CLK_STATE, 0);
2868 i915_oa_init_reg_state(engine, ce, regs);
2871 regs[CTX_END] = MI_BATCH_BUFFER_END;
2872 if (INTEL_GEN(engine->i915) >= 10)
2873 regs[CTX_END] |= BIT(0);
2877 populate_lr_context(struct intel_context *ce,
2878 struct drm_i915_gem_object *ctx_obj,
2879 struct intel_engine_cs *engine,
2880 struct intel_ring *ring)
2886 vaddr = i915_gem_object_pin_map(ctx_obj, I915_MAP_WB);
2887 if (IS_ERR(vaddr)) {
2888 ret = PTR_ERR(vaddr);
2889 DRM_DEBUG_DRIVER("Could not map object pages! (%d)\n", ret);
2893 if (engine->default_state) {
2895 * We only want to copy over the template context state;
2896 * skipping over the headers reserved for GuC communication,
2897 * leaving those as zero.
2899 const unsigned long start = LRC_HEADER_PAGES * PAGE_SIZE;
2902 defaults = i915_gem_object_pin_map(engine->default_state,
2904 if (IS_ERR(defaults)) {
2905 ret = PTR_ERR(defaults);
2909 memcpy(vaddr + start, defaults + start, engine->context_size);
2910 i915_gem_object_unpin_map(engine->default_state);
2913 /* The second page of the context object contains some fields which must
2914 * be set up prior to the first execution. */
2915 regs = vaddr + LRC_STATE_PN * PAGE_SIZE;
2916 execlists_init_reg_state(regs, ce, engine, ring);
2917 if (!engine->default_state)
2918 regs[CTX_CONTEXT_CONTROL + 1] |=
2919 _MASKED_BIT_ENABLE(CTX_CTRL_ENGINE_CTX_RESTORE_INHIBIT);
2920 if (ce->gem_context == engine->i915->preempt_context &&
2921 INTEL_GEN(engine->i915) < 11)
2922 regs[CTX_CONTEXT_CONTROL + 1] |=
2923 _MASKED_BIT_ENABLE(CTX_CTRL_ENGINE_CTX_RESTORE_INHIBIT |
2924 CTX_CTRL_ENGINE_CTX_SAVE_INHIBIT);
2928 __i915_gem_object_flush_map(ctx_obj,
2929 LRC_HEADER_PAGES * PAGE_SIZE,
2930 engine->context_size);
2931 i915_gem_object_unpin_map(ctx_obj);
2935 static struct i915_timeline *get_timeline(struct i915_gem_context *ctx)
2938 return i915_timeline_get(ctx->timeline);
2940 return i915_timeline_create(ctx->i915, NULL);
2943 static int execlists_context_deferred_alloc(struct intel_context *ce,
2944 struct intel_engine_cs *engine)
2946 struct drm_i915_gem_object *ctx_obj;
2947 struct i915_vma *vma;
2949 struct intel_ring *ring;
2950 struct i915_timeline *timeline;
2956 context_size = round_up(engine->context_size, I915_GTT_PAGE_SIZE);
2959 * Before the actual start of the context image, we insert a few pages
2960 * for our own use and for sharing with the GuC.
2962 context_size += LRC_HEADER_PAGES * PAGE_SIZE;
2964 ctx_obj = i915_gem_object_create_shmem(engine->i915, context_size);
2965 if (IS_ERR(ctx_obj))
2966 return PTR_ERR(ctx_obj);
2968 vma = i915_vma_instance(ctx_obj, &engine->i915->ggtt.vm, NULL);
2971 goto error_deref_obj;
2974 timeline = get_timeline(ce->gem_context);
2975 if (IS_ERR(timeline)) {
2976 ret = PTR_ERR(timeline);
2977 goto error_deref_obj;
2980 ring = intel_engine_create_ring(engine,
2982 ce->gem_context->ring_size);
2983 i915_timeline_put(timeline);
2985 ret = PTR_ERR(ring);
2986 goto error_deref_obj;
2989 ret = populate_lr_context(ce, ctx_obj, engine, ring);
2991 DRM_DEBUG_DRIVER("Failed to populate LRC: %d\n", ret);
2992 goto error_ring_free;
3001 intel_ring_put(ring);
3003 i915_gem_object_put(ctx_obj);
3007 static struct list_head *virtual_queue(struct virtual_engine *ve)
3009 return &ve->base.execlists.default_priolist.requests[0];
3012 static void virtual_context_destroy(struct kref *kref)
3014 struct virtual_engine *ve =
3015 container_of(kref, typeof(*ve), context.ref);
3018 GEM_BUG_ON(!list_empty(virtual_queue(ve)));
3019 GEM_BUG_ON(ve->request);
3020 GEM_BUG_ON(ve->context.inflight);
3022 for (n = 0; n < ve->num_siblings; n++) {
3023 struct intel_engine_cs *sibling = ve->siblings[n];
3024 struct rb_node *node = &ve->nodes[sibling->id].rb;
3026 if (RB_EMPTY_NODE(node))
3029 spin_lock_irq(&sibling->active.lock);
3031 /* Detachment is lazily performed in the execlists tasklet */
3032 if (!RB_EMPTY_NODE(node))
3033 rb_erase_cached(node, &sibling->execlists.virtual);
3035 spin_unlock_irq(&sibling->active.lock);
3037 GEM_BUG_ON(__tasklet_is_scheduled(&ve->base.execlists.tasklet));
3039 if (ve->context.state)
3040 __execlists_context_fini(&ve->context);
3046 static void virtual_engine_initial_hint(struct virtual_engine *ve)
3051 * Pick a random sibling on starting to help spread the load around.
3053 * New contexts are typically created with exactly the same order
3054 * of siblings, and often started in batches. Due to the way we iterate
3055 * the array of sibling when submitting requests, sibling[0] is
3056 * prioritised for dequeuing. If we make sure that sibling[0] is fairly
3057 * randomised across the system, we also help spread the load by the
3058 * first engine we inspect being different each time.
3060 * NB This does not force us to execute on this engine, it will just
3061 * typically be the first we inspect for submission.
3063 swp = prandom_u32_max(ve->num_siblings);
3067 swap(ve->siblings[swp], ve->siblings[0]);
3068 virtual_update_register_offsets(ve->context.lrc_reg_state,
3072 static int virtual_context_pin(struct intel_context *ce)
3074 struct virtual_engine *ve = container_of(ce, typeof(*ve), context);
3077 /* Note: we must use a real engine class for setting up reg state */
3078 err = __execlists_context_pin(ce, ve->siblings[0]);
3082 virtual_engine_initial_hint(ve);
3086 static void virtual_context_enter(struct intel_context *ce)
3088 struct virtual_engine *ve = container_of(ce, typeof(*ve), context);
3091 for (n = 0; n < ve->num_siblings; n++)
3092 intel_engine_pm_get(ve->siblings[n]);
3095 static void virtual_context_exit(struct intel_context *ce)
3097 struct virtual_engine *ve = container_of(ce, typeof(*ve), context);
3100 for (n = 0; n < ve->num_siblings; n++)
3101 intel_engine_pm_put(ve->siblings[n]);
3104 static const struct intel_context_ops virtual_context_ops = {
3105 .pin = virtual_context_pin,
3106 .unpin = execlists_context_unpin,
3108 .enter = virtual_context_enter,
3109 .exit = virtual_context_exit,
3111 .destroy = virtual_context_destroy,
3114 static intel_engine_mask_t virtual_submission_mask(struct virtual_engine *ve)
3116 struct i915_request *rq;
3117 intel_engine_mask_t mask;
3119 rq = READ_ONCE(ve->request);
3123 /* The rq is ready for submission; rq->execution_mask is now stable. */
3124 mask = rq->execution_mask;
3125 if (unlikely(!mask)) {
3126 /* Invalid selection, submit to a random engine in error */
3127 i915_request_skip(rq, -ENODEV);
3128 mask = ve->siblings[0]->mask;
3131 GEM_TRACE("%s: rq=%llx:%lld, mask=%x, prio=%d\n",
3133 rq->fence.context, rq->fence.seqno,
3134 mask, ve->base.execlists.queue_priority_hint);
3139 static void virtual_submission_tasklet(unsigned long data)
3141 struct virtual_engine * const ve = (struct virtual_engine *)data;
3142 const int prio = ve->base.execlists.queue_priority_hint;
3143 intel_engine_mask_t mask;
3147 mask = virtual_submission_mask(ve);
3149 if (unlikely(!mask))
3152 local_irq_disable();
3153 for (n = 0; READ_ONCE(ve->request) && n < ve->num_siblings; n++) {
3154 struct intel_engine_cs *sibling = ve->siblings[n];
3155 struct ve_node * const node = &ve->nodes[sibling->id];
3156 struct rb_node **parent, *rb;
3159 if (unlikely(!(mask & sibling->mask))) {
3160 if (!RB_EMPTY_NODE(&node->rb)) {
3161 spin_lock(&sibling->active.lock);
3162 rb_erase_cached(&node->rb,
3163 &sibling->execlists.virtual);
3164 RB_CLEAR_NODE(&node->rb);
3165 spin_unlock(&sibling->active.lock);
3170 spin_lock(&sibling->active.lock);
3172 if (!RB_EMPTY_NODE(&node->rb)) {
3174 * Cheat and avoid rebalancing the tree if we can
3175 * reuse this node in situ.
3177 first = rb_first_cached(&sibling->execlists.virtual) ==
3179 if (prio == node->prio || (prio > node->prio && first))
3182 rb_erase_cached(&node->rb, &sibling->execlists.virtual);
3187 parent = &sibling->execlists.virtual.rb_root.rb_node;
3189 struct ve_node *other;
3192 other = rb_entry(rb, typeof(*other), rb);
3193 if (prio > other->prio) {
3194 parent = &rb->rb_left;
3196 parent = &rb->rb_right;
3201 rb_link_node(&node->rb, rb, parent);
3202 rb_insert_color_cached(&node->rb,
3203 &sibling->execlists.virtual,
3207 GEM_BUG_ON(RB_EMPTY_NODE(&node->rb));
3209 if (first && prio > sibling->execlists.queue_priority_hint) {
3210 sibling->execlists.queue_priority_hint = prio;
3211 tasklet_hi_schedule(&sibling->execlists.tasklet);
3214 spin_unlock(&sibling->active.lock);
3219 static void virtual_submit_request(struct i915_request *rq)
3221 struct virtual_engine *ve = to_virtual_engine(rq->engine);
3223 GEM_TRACE("%s: rq=%llx:%lld\n",
3228 GEM_BUG_ON(ve->base.submit_request != virtual_submit_request);
3230 GEM_BUG_ON(ve->request);
3231 GEM_BUG_ON(!list_empty(virtual_queue(ve)));
3233 ve->base.execlists.queue_priority_hint = rq_prio(rq);
3234 WRITE_ONCE(ve->request, rq);
3236 list_move_tail(&rq->sched.link, virtual_queue(ve));
3238 tasklet_schedule(&ve->base.execlists.tasklet);
3241 static struct ve_bond *
3242 virtual_find_bond(struct virtual_engine *ve,
3243 const struct intel_engine_cs *master)
3247 for (i = 0; i < ve->num_bonds; i++) {
3248 if (ve->bonds[i].master == master)
3249 return &ve->bonds[i];
3256 virtual_bond_execute(struct i915_request *rq, struct dma_fence *signal)
3258 struct virtual_engine *ve = to_virtual_engine(rq->engine);
3259 struct ve_bond *bond;
3261 bond = virtual_find_bond(ve, to_request(signal)->engine);
3263 intel_engine_mask_t old, new, cmp;
3265 cmp = READ_ONCE(rq->execution_mask);
3268 new = cmp & bond->sibling_mask;
3269 } while ((cmp = cmpxchg(&rq->execution_mask, old, new)) != old);
3273 struct intel_context *
3274 intel_execlists_create_virtual(struct i915_gem_context *ctx,
3275 struct intel_engine_cs **siblings,
3278 struct virtual_engine *ve;
3283 return ERR_PTR(-EINVAL);
3286 return intel_context_create(ctx, siblings[0]);
3288 ve = kzalloc(struct_size(ve, siblings, count), GFP_KERNEL);
3290 return ERR_PTR(-ENOMEM);
3292 ve->base.i915 = ctx->i915;
3294 ve->base.class = OTHER_CLASS;
3295 ve->base.uabi_class = I915_ENGINE_CLASS_INVALID;
3296 ve->base.instance = I915_ENGINE_CLASS_INVALID_VIRTUAL;
3297 ve->base.flags = I915_ENGINE_IS_VIRTUAL;
3300 * The decision on whether to submit a request using semaphores
3301 * depends on the saturated state of the engine. We only compute
3302 * this during HW submission of the request, and we need for this
3303 * state to be globally applied to all requests being submitted
3304 * to this engine. Virtual engines encompass more than one physical
3305 * engine and so we cannot accurately tell in advance if one of those
3306 * engines is already saturated and so cannot afford to use a semaphore
3307 * and be pessimized in priority for doing so -- if we are the only
3308 * context using semaphores after all other clients have stopped, we
3309 * will be starved on the saturated system. Such a global switch for
3310 * semaphores is less than ideal, but alas is the current compromise.
3312 ve->base.saturated = ALL_ENGINES;
3314 snprintf(ve->base.name, sizeof(ve->base.name), "virtual");
3316 intel_engine_init_active(&ve->base, ENGINE_VIRTUAL);
3318 intel_engine_init_execlists(&ve->base);
3320 ve->base.cops = &virtual_context_ops;
3321 ve->base.request_alloc = execlists_request_alloc;
3323 ve->base.schedule = i915_schedule;
3324 ve->base.submit_request = virtual_submit_request;
3325 ve->base.bond_execute = virtual_bond_execute;
3327 INIT_LIST_HEAD(virtual_queue(ve));
3328 ve->base.execlists.queue_priority_hint = INT_MIN;
3329 tasklet_init(&ve->base.execlists.tasklet,
3330 virtual_submission_tasklet,
3333 intel_context_init(&ve->context, ctx, &ve->base);
3335 for (n = 0; n < count; n++) {
3336 struct intel_engine_cs *sibling = siblings[n];
3338 GEM_BUG_ON(!is_power_of_2(sibling->mask));
3339 if (sibling->mask & ve->base.mask) {
3340 DRM_DEBUG("duplicate %s entry in load balancer\n",
3347 * The virtual engine implementation is tightly coupled to
3348 * the execlists backend -- we push out request directly
3349 * into a tree inside each physical engine. We could support
3350 * layering if we handle cloning of the requests and
3351 * submitting a copy into each backend.
3353 if (sibling->execlists.tasklet.func !=
3354 execlists_submission_tasklet) {
3359 GEM_BUG_ON(RB_EMPTY_NODE(&ve->nodes[sibling->id].rb));
3360 RB_CLEAR_NODE(&ve->nodes[sibling->id].rb);
3362 ve->siblings[ve->num_siblings++] = sibling;
3363 ve->base.mask |= sibling->mask;
3366 * All physical engines must be compatible for their emission
3367 * functions (as we build the instructions during request
3368 * construction and do not alter them before submission
3369 * on the physical engine). We use the engine class as a guide
3370 * here, although that could be refined.
3372 if (ve->base.class != OTHER_CLASS) {
3373 if (ve->base.class != sibling->class) {
3374 DRM_DEBUG("invalid mixing of engine class, sibling %d, already %d\n",
3375 sibling->class, ve->base.class);
3382 ve->base.class = sibling->class;
3383 ve->base.uabi_class = sibling->uabi_class;
3384 snprintf(ve->base.name, sizeof(ve->base.name),
3385 "v%dx%d", ve->base.class, count);
3386 ve->base.context_size = sibling->context_size;
3388 ve->base.emit_bb_start = sibling->emit_bb_start;
3389 ve->base.emit_flush = sibling->emit_flush;
3390 ve->base.emit_init_breadcrumb = sibling->emit_init_breadcrumb;
3391 ve->base.emit_fini_breadcrumb = sibling->emit_fini_breadcrumb;
3392 ve->base.emit_fini_breadcrumb_dw =
3393 sibling->emit_fini_breadcrumb_dw;
3396 return &ve->context;
3399 intel_context_put(&ve->context);
3400 return ERR_PTR(err);
3403 struct intel_context *
3404 intel_execlists_clone_virtual(struct i915_gem_context *ctx,
3405 struct intel_engine_cs *src)
3407 struct virtual_engine *se = to_virtual_engine(src);
3408 struct intel_context *dst;
3410 dst = intel_execlists_create_virtual(ctx,
3416 if (se->num_bonds) {
3417 struct virtual_engine *de = to_virtual_engine(dst->engine);
3419 de->bonds = kmemdup(se->bonds,
3420 sizeof(*se->bonds) * se->num_bonds,
3423 intel_context_put(dst);
3424 return ERR_PTR(-ENOMEM);
3427 de->num_bonds = se->num_bonds;
3433 int intel_virtual_engine_attach_bond(struct intel_engine_cs *engine,
3434 const struct intel_engine_cs *master,
3435 const struct intel_engine_cs *sibling)
3437 struct virtual_engine *ve = to_virtual_engine(engine);
3438 struct ve_bond *bond;
3441 /* Sanity check the sibling is part of the virtual engine */
3442 for (n = 0; n < ve->num_siblings; n++)
3443 if (sibling == ve->siblings[n])
3445 if (n == ve->num_siblings)
3448 bond = virtual_find_bond(ve, master);
3450 bond->sibling_mask |= sibling->mask;
3454 bond = krealloc(ve->bonds,
3455 sizeof(*bond) * (ve->num_bonds + 1),
3460 bond[ve->num_bonds].master = master;
3461 bond[ve->num_bonds].sibling_mask = sibling->mask;
3469 void intel_execlists_show_requests(struct intel_engine_cs *engine,
3470 struct drm_printer *m,
3471 void (*show_request)(struct drm_printer *m,
3472 struct i915_request *rq,
3473 const char *prefix),
3476 const struct intel_engine_execlists *execlists = &engine->execlists;
3477 struct i915_request *rq, *last;
3478 unsigned long flags;
3482 spin_lock_irqsave(&engine->active.lock, flags);
3486 list_for_each_entry(rq, &engine->active.requests, sched.link) {
3487 if (count++ < max - 1)
3488 show_request(m, rq, "\t\tE ");
3495 "\t\t...skipping %d executing requests...\n",
3498 show_request(m, last, "\t\tE ");
3503 if (execlists->queue_priority_hint != INT_MIN)
3504 drm_printf(m, "\t\tQueue priority hint: %d\n",
3505 execlists->queue_priority_hint);
3506 for (rb = rb_first_cached(&execlists->queue); rb; rb = rb_next(rb)) {
3507 struct i915_priolist *p = rb_entry(rb, typeof(*p), node);
3510 priolist_for_each_request(rq, p, i) {
3511 if (count++ < max - 1)
3512 show_request(m, rq, "\t\tQ ");
3520 "\t\t...skipping %d queued requests...\n",
3523 show_request(m, last, "\t\tQ ");
3528 for (rb = rb_first_cached(&execlists->virtual); rb; rb = rb_next(rb)) {
3529 struct virtual_engine *ve =
3530 rb_entry(rb, typeof(*ve), nodes[engine->id].rb);
3531 struct i915_request *rq = READ_ONCE(ve->request);
3534 if (count++ < max - 1)
3535 show_request(m, rq, "\t\tV ");
3543 "\t\t...skipping %d virtual requests...\n",
3546 show_request(m, last, "\t\tV ");
3549 spin_unlock_irqrestore(&engine->active.lock, flags);
3552 void intel_lr_context_reset(struct intel_engine_cs *engine,
3553 struct intel_context *ce,
3558 * We want a simple context + ring to execute the breadcrumb update.
3559 * We cannot rely on the context being intact across the GPU hang,
3560 * so clear it and rebuild just what we need for the breadcrumb.
3561 * All pending requests for this context will be zapped, and any
3562 * future request will be after userspace has had the opportunity
3563 * to recreate its own state.
3566 u32 *regs = ce->lrc_reg_state;
3568 if (engine->pinned_default_state) {
3569 memcpy(regs, /* skip restoring the vanilla PPHWSP */
3570 engine->pinned_default_state + LRC_STATE_PN * PAGE_SIZE,
3571 engine->context_size - PAGE_SIZE);
3573 execlists_init_reg_state(regs, ce, engine, ce->ring);
3576 /* Rerun the request; its payload has been neutered (if guilty). */
3577 ce->ring->head = head;
3578 intel_ring_update_space(ce->ring);
3580 __execlists_update_reg_state(ce, engine);
3583 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
3584 #include "selftest_lrc.c"