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