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