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