Merge drm/drm-next into drm-intel-next-queued
[sfrench/cifs-2.6.git] / drivers / gpu / drm / i915 / 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 <drm/drmP.h>
137 #include <drm/i915_drm.h>
138 #include "i915_drv.h"
139 #include "i915_gem_render_state.h"
140 #include "intel_lrc_reg.h"
141 #include "intel_mocs.h"
142 #include "intel_workarounds.h"
143
144 #define RING_EXECLIST_QFULL             (1 << 0x2)
145 #define RING_EXECLIST1_VALID            (1 << 0x3)
146 #define RING_EXECLIST0_VALID            (1 << 0x4)
147 #define RING_EXECLIST_ACTIVE_STATUS     (3 << 0xE)
148 #define RING_EXECLIST1_ACTIVE           (1 << 0x11)
149 #define RING_EXECLIST0_ACTIVE           (1 << 0x12)
150
151 #define GEN8_CTX_STATUS_IDLE_ACTIVE     (1 << 0)
152 #define GEN8_CTX_STATUS_PREEMPTED       (1 << 1)
153 #define GEN8_CTX_STATUS_ELEMENT_SWITCH  (1 << 2)
154 #define GEN8_CTX_STATUS_ACTIVE_IDLE     (1 << 3)
155 #define GEN8_CTX_STATUS_COMPLETE        (1 << 4)
156 #define GEN8_CTX_STATUS_LITE_RESTORE    (1 << 15)
157
158 #define GEN8_CTX_STATUS_COMPLETED_MASK \
159          (GEN8_CTX_STATUS_COMPLETE | GEN8_CTX_STATUS_PREEMPTED)
160
161 /* Typical size of the average request (2 pipecontrols and a MI_BB) */
162 #define EXECLISTS_REQUEST_SIZE 64 /* bytes */
163 #define WA_TAIL_DWORDS 2
164 #define WA_TAIL_BYTES (sizeof(u32) * WA_TAIL_DWORDS)
165
166 static int execlists_context_deferred_alloc(struct i915_gem_context *ctx,
167                                             struct intel_engine_cs *engine);
168 static void execlists_init_reg_state(u32 *reg_state,
169                                      struct i915_gem_context *ctx,
170                                      struct intel_engine_cs *engine,
171                                      struct intel_ring *ring);
172
173 static inline struct i915_priolist *to_priolist(struct rb_node *rb)
174 {
175         return rb_entry(rb, struct i915_priolist, node);
176 }
177
178 static inline int rq_prio(const struct i915_request *rq)
179 {
180         return rq->sched.attr.priority;
181 }
182
183 static inline bool need_preempt(const struct intel_engine_cs *engine,
184                                 const struct i915_request *last,
185                                 int prio)
186 {
187         return (intel_engine_has_preemption(engine) &&
188                 __execlists_need_preempt(prio, rq_prio(last)) &&
189                 !i915_request_completed(last));
190 }
191
192 /**
193  * intel_lr_context_descriptor_update() - calculate & cache the descriptor
194  *                                        descriptor for a pinned context
195  * @ctx: Context to work on
196  * @engine: Engine the descriptor will be used with
197  *
198  * The context descriptor encodes various attributes of a context,
199  * including its GTT address and some flags. Because it's fairly
200  * expensive to calculate, we'll just do it once and cache the result,
201  * which remains valid until the context is unpinned.
202  *
203  * This is what a descriptor looks like, from LSB to MSB::
204  *
205  *      bits  0-11:    flags, GEN8_CTX_* (cached in ctx->desc_template)
206  *      bits 12-31:    LRCA, GTT address of (the HWSP of) this context
207  *      bits 32-52:    ctx ID, a globally unique tag
208  *      bits 53-54:    mbz, reserved for use by hardware
209  *      bits 55-63:    group ID, currently unused and set to 0
210  *
211  * Starting from Gen11, the upper dword of the descriptor has a new format:
212  *
213  *      bits 32-36:    reserved
214  *      bits 37-47:    SW context ID
215  *      bits 48:53:    engine instance
216  *      bit 54:        mbz, reserved for use by hardware
217  *      bits 55-60:    SW counter
218  *      bits 61-63:    engine class
219  *
220  * engine info, SW context ID and SW counter need to form a unique number
221  * (Context ID) per lrc.
222  */
223 static void
224 intel_lr_context_descriptor_update(struct i915_gem_context *ctx,
225                                    struct intel_engine_cs *engine)
226 {
227         struct intel_context *ce = to_intel_context(ctx, engine);
228         u64 desc;
229
230         BUILD_BUG_ON(MAX_CONTEXT_HW_ID > (BIT(GEN8_CTX_ID_WIDTH)));
231         BUILD_BUG_ON(GEN11_MAX_CONTEXT_HW_ID > (BIT(GEN11_SW_CTX_ID_WIDTH)));
232
233         desc = ctx->desc_template;                              /* bits  0-11 */
234         GEM_BUG_ON(desc & GENMASK_ULL(63, 12));
235
236         desc |= i915_ggtt_offset(ce->state) + LRC_HEADER_PAGES * PAGE_SIZE;
237                                                                 /* bits 12-31 */
238         GEM_BUG_ON(desc & GENMASK_ULL(63, 32));
239
240         if (INTEL_GEN(ctx->i915) >= 11) {
241                 GEM_BUG_ON(ctx->hw_id >= BIT(GEN11_SW_CTX_ID_WIDTH));
242                 desc |= (u64)ctx->hw_id << GEN11_SW_CTX_ID_SHIFT;
243                                                                 /* bits 37-47 */
244
245                 desc |= (u64)engine->instance << GEN11_ENGINE_INSTANCE_SHIFT;
246                                                                 /* bits 48-53 */
247
248                 /* TODO: decide what to do with SW counter (bits 55-60) */
249
250                 desc |= (u64)engine->class << GEN11_ENGINE_CLASS_SHIFT;
251                                                                 /* bits 61-63 */
252         } else {
253                 GEM_BUG_ON(ctx->hw_id >= BIT(GEN8_CTX_ID_WIDTH));
254                 desc |= (u64)ctx->hw_id << GEN8_CTX_ID_SHIFT;   /* bits 32-52 */
255         }
256
257         ce->lrc_desc = desc;
258 }
259
260 static struct i915_priolist *
261 lookup_priolist(struct intel_engine_cs *engine,
262                 struct i915_sched_node *node,
263                 int prio)
264 {
265         struct intel_engine_execlists * const execlists = &engine->execlists;
266         struct i915_priolist *p;
267         struct rb_node **parent, *rb;
268         bool first = true;
269
270         if (unlikely(execlists->no_priolist))
271                 prio = I915_PRIORITY_NORMAL;
272
273 find_priolist:
274         /* most positive priority is scheduled first, equal priorities fifo */
275         rb = NULL;
276         parent = &execlists->queue.rb_node;
277         while (*parent) {
278                 rb = *parent;
279                 p = to_priolist(rb);
280                 if (prio > p->priority) {
281                         parent = &rb->rb_left;
282                 } else if (prio < p->priority) {
283                         parent = &rb->rb_right;
284                         first = false;
285                 } else {
286                         return p;
287                 }
288         }
289
290         if (prio == I915_PRIORITY_NORMAL) {
291                 p = &execlists->default_priolist;
292         } else {
293                 p = kmem_cache_alloc(engine->i915->priorities, GFP_ATOMIC);
294                 /* Convert an allocation failure to a priority bump */
295                 if (unlikely(!p)) {
296                         prio = I915_PRIORITY_NORMAL; /* recurses just once */
297
298                         /* To maintain ordering with all rendering, after an
299                          * allocation failure we have to disable all scheduling.
300                          * Requests will then be executed in fifo, and schedule
301                          * will ensure that dependencies are emitted in fifo.
302                          * There will be still some reordering with existing
303                          * requests, so if userspace lied about their
304                          * dependencies that reordering may be visible.
305                          */
306                         execlists->no_priolist = true;
307                         goto find_priolist;
308                 }
309         }
310
311         p->priority = prio;
312         INIT_LIST_HEAD(&p->requests);
313         rb_link_node(&p->node, rb, parent);
314         rb_insert_color(&p->node, &execlists->queue);
315
316         if (first)
317                 execlists->first = &p->node;
318
319         return p;
320 }
321
322 static void unwind_wa_tail(struct i915_request *rq)
323 {
324         rq->tail = intel_ring_wrap(rq->ring, rq->wa_tail - WA_TAIL_BYTES);
325         assert_ring_tail_valid(rq->ring, rq->tail);
326 }
327
328 static void __unwind_incomplete_requests(struct intel_engine_cs *engine)
329 {
330         struct i915_request *rq, *rn;
331         struct i915_priolist *uninitialized_var(p);
332         int last_prio = I915_PRIORITY_INVALID;
333
334         lockdep_assert_held(&engine->timeline->lock);
335
336         list_for_each_entry_safe_reverse(rq, rn,
337                                          &engine->timeline->requests,
338                                          link) {
339                 if (i915_request_completed(rq))
340                         return;
341
342                 __i915_request_unsubmit(rq);
343                 unwind_wa_tail(rq);
344
345                 GEM_BUG_ON(rq_prio(rq) == I915_PRIORITY_INVALID);
346                 if (rq_prio(rq) != last_prio) {
347                         last_prio = rq_prio(rq);
348                         p = lookup_priolist(engine, &rq->sched, last_prio);
349                 }
350
351                 list_add(&rq->sched.link, &p->requests);
352         }
353 }
354
355 void
356 execlists_unwind_incomplete_requests(struct intel_engine_execlists *execlists)
357 {
358         struct intel_engine_cs *engine =
359                 container_of(execlists, typeof(*engine), execlists);
360
361         spin_lock_irq(&engine->timeline->lock);
362         __unwind_incomplete_requests(engine);
363         spin_unlock_irq(&engine->timeline->lock);
364 }
365
366 static inline void
367 execlists_context_status_change(struct i915_request *rq, unsigned long status)
368 {
369         /*
370          * Only used when GVT-g is enabled now. When GVT-g is disabled,
371          * The compiler should eliminate this function as dead-code.
372          */
373         if (!IS_ENABLED(CONFIG_DRM_I915_GVT))
374                 return;
375
376         atomic_notifier_call_chain(&rq->engine->context_status_notifier,
377                                    status, rq);
378 }
379
380 inline void
381 execlists_user_begin(struct intel_engine_execlists *execlists,
382                      const struct execlist_port *port)
383 {
384         execlists_set_active_once(execlists, EXECLISTS_ACTIVE_USER);
385 }
386
387 inline void
388 execlists_user_end(struct intel_engine_execlists *execlists)
389 {
390         execlists_clear_active(execlists, EXECLISTS_ACTIVE_USER);
391 }
392
393 static inline void
394 execlists_context_schedule_in(struct i915_request *rq)
395 {
396         execlists_context_status_change(rq, INTEL_CONTEXT_SCHEDULE_IN);
397         intel_engine_context_in(rq->engine);
398 }
399
400 static inline void
401 execlists_context_schedule_out(struct i915_request *rq)
402 {
403         intel_engine_context_out(rq->engine);
404         execlists_context_status_change(rq, INTEL_CONTEXT_SCHEDULE_OUT);
405 }
406
407 static void
408 execlists_update_context_pdps(struct i915_hw_ppgtt *ppgtt, u32 *reg_state)
409 {
410         ASSIGN_CTX_PDP(ppgtt, reg_state, 3);
411         ASSIGN_CTX_PDP(ppgtt, reg_state, 2);
412         ASSIGN_CTX_PDP(ppgtt, reg_state, 1);
413         ASSIGN_CTX_PDP(ppgtt, reg_state, 0);
414 }
415
416 static u64 execlists_update_context(struct i915_request *rq)
417 {
418         struct intel_context *ce = to_intel_context(rq->ctx, rq->engine);
419         struct i915_hw_ppgtt *ppgtt =
420                 rq->ctx->ppgtt ?: rq->i915->mm.aliasing_ppgtt;
421         u32 *reg_state = ce->lrc_reg_state;
422
423         reg_state[CTX_RING_TAIL+1] = intel_ring_set_tail(rq->ring, rq->tail);
424
425         /* True 32b PPGTT with dynamic page allocation: update PDP
426          * registers and point the unallocated PDPs to scratch page.
427          * PML4 is allocated during ppgtt init, so this is not needed
428          * in 48-bit mode.
429          */
430         if (ppgtt && !i915_vm_is_48bit(&ppgtt->base))
431                 execlists_update_context_pdps(ppgtt, reg_state);
432
433         return ce->lrc_desc;
434 }
435
436 static inline void write_desc(struct intel_engine_execlists *execlists, u64 desc, u32 port)
437 {
438         if (execlists->ctrl_reg) {
439                 writel(lower_32_bits(desc), execlists->submit_reg + port * 2);
440                 writel(upper_32_bits(desc), execlists->submit_reg + port * 2 + 1);
441         } else {
442                 writel(upper_32_bits(desc), execlists->submit_reg);
443                 writel(lower_32_bits(desc), execlists->submit_reg);
444         }
445 }
446
447 static void execlists_submit_ports(struct intel_engine_cs *engine)
448 {
449         struct intel_engine_execlists *execlists = &engine->execlists;
450         struct execlist_port *port = execlists->port;
451         unsigned int n;
452
453         /*
454          * ELSQ note: the submit queue is not cleared after being submitted
455          * to the HW so we need to make sure we always clean it up. This is
456          * currently ensured by the fact that we always write the same number
457          * of elsq entries, keep this in mind before changing the loop below.
458          */
459         for (n = execlists_num_ports(execlists); n--; ) {
460                 struct i915_request *rq;
461                 unsigned int count;
462                 u64 desc;
463
464                 rq = port_unpack(&port[n], &count);
465                 if (rq) {
466                         GEM_BUG_ON(count > !n);
467                         if (!count++)
468                                 execlists_context_schedule_in(rq);
469                         port_set(&port[n], port_pack(rq, count));
470                         desc = execlists_update_context(rq);
471                         GEM_DEBUG_EXEC(port[n].context_id = upper_32_bits(desc));
472
473                         GEM_TRACE("%s in[%d]:  ctx=%d.%d, global=%d (fence %llx:%d) (current %d), prio=%d\n",
474                                   engine->name, n,
475                                   port[n].context_id, count,
476                                   rq->global_seqno,
477                                   rq->fence.context, rq->fence.seqno,
478                                   intel_engine_get_seqno(engine),
479                                   rq_prio(rq));
480                 } else {
481                         GEM_BUG_ON(!n);
482                         desc = 0;
483                 }
484
485                 write_desc(execlists, desc, n);
486         }
487
488         /* we need to manually load the submit queue */
489         if (execlists->ctrl_reg)
490                 writel(EL_CTRL_LOAD, execlists->ctrl_reg);
491
492         execlists_clear_active(execlists, EXECLISTS_ACTIVE_HWACK);
493 }
494
495 static bool ctx_single_port_submission(const struct i915_gem_context *ctx)
496 {
497         return (IS_ENABLED(CONFIG_DRM_I915_GVT) &&
498                 i915_gem_context_force_single_submission(ctx));
499 }
500
501 static bool can_merge_ctx(const struct i915_gem_context *prev,
502                           const struct i915_gem_context *next)
503 {
504         if (prev != next)
505                 return false;
506
507         if (ctx_single_port_submission(prev))
508                 return false;
509
510         return true;
511 }
512
513 static void port_assign(struct execlist_port *port, struct i915_request *rq)
514 {
515         GEM_BUG_ON(rq == port_request(port));
516
517         if (port_isset(port))
518                 i915_request_put(port_request(port));
519
520         port_set(port, port_pack(i915_request_get(rq), port_count(port)));
521 }
522
523 static void inject_preempt_context(struct intel_engine_cs *engine)
524 {
525         struct intel_engine_execlists *execlists = &engine->execlists;
526         struct intel_context *ce =
527                 to_intel_context(engine->i915->preempt_context, engine);
528         unsigned int n;
529
530         GEM_BUG_ON(execlists->preempt_complete_status !=
531                    upper_32_bits(ce->lrc_desc));
532         GEM_BUG_ON((ce->lrc_reg_state[CTX_CONTEXT_CONTROL + 1] &
533                     _MASKED_BIT_ENABLE(CTX_CTRL_ENGINE_CTX_RESTORE_INHIBIT |
534                                        CTX_CTRL_ENGINE_CTX_SAVE_INHIBIT)) !=
535                    _MASKED_BIT_ENABLE(CTX_CTRL_ENGINE_CTX_RESTORE_INHIBIT |
536                                       CTX_CTRL_ENGINE_CTX_SAVE_INHIBIT));
537
538         /*
539          * Switch to our empty preempt context so
540          * the state of the GPU is known (idle).
541          */
542         GEM_TRACE("%s\n", engine->name);
543         for (n = execlists_num_ports(execlists); --n; )
544                 write_desc(execlists, 0, n);
545
546         write_desc(execlists, ce->lrc_desc, n);
547
548         /* we need to manually load the submit queue */
549         if (execlists->ctrl_reg)
550                 writel(EL_CTRL_LOAD, execlists->ctrl_reg);
551
552         execlists_clear_active(&engine->execlists, EXECLISTS_ACTIVE_HWACK);
553         execlists_set_active(&engine->execlists, EXECLISTS_ACTIVE_PREEMPT);
554 }
555
556 static void execlists_dequeue(struct intel_engine_cs *engine)
557 {
558         struct intel_engine_execlists * const execlists = &engine->execlists;
559         struct execlist_port *port = execlists->port;
560         const struct execlist_port * const last_port =
561                 &execlists->port[execlists->port_mask];
562         struct i915_request *last = port_request(port);
563         struct rb_node *rb;
564         bool submit = false;
565
566         /* Hardware submission is through 2 ports. Conceptually each port
567          * has a (RING_START, RING_HEAD, RING_TAIL) tuple. RING_START is
568          * static for a context, and unique to each, so we only execute
569          * requests belonging to a single context from each ring. RING_HEAD
570          * is maintained by the CS in the context image, it marks the place
571          * where it got up to last time, and through RING_TAIL we tell the CS
572          * where we want to execute up to this time.
573          *
574          * In this list the requests are in order of execution. Consecutive
575          * requests from the same context are adjacent in the ringbuffer. We
576          * can combine these requests into a single RING_TAIL update:
577          *
578          *              RING_HEAD...req1...req2
579          *                                    ^- RING_TAIL
580          * since to execute req2 the CS must first execute req1.
581          *
582          * Our goal then is to point each port to the end of a consecutive
583          * sequence of requests as being the most optimal (fewest wake ups
584          * and context switches) submission.
585          */
586
587         spin_lock_irq(&engine->timeline->lock);
588         rb = execlists->first;
589         GEM_BUG_ON(rb_first(&execlists->queue) != rb);
590
591         if (last) {
592                 /*
593                  * Don't resubmit or switch until all outstanding
594                  * preemptions (lite-restore) are seen. Then we
595                  * know the next preemption status we see corresponds
596                  * to this ELSP update.
597                  */
598                 GEM_BUG_ON(!execlists_is_active(execlists,
599                                                 EXECLISTS_ACTIVE_USER));
600                 GEM_BUG_ON(!port_count(&port[0]));
601                 if (port_count(&port[0]) > 1)
602                         goto unlock;
603
604                 /*
605                  * If we write to ELSP a second time before the HW has had
606                  * a chance to respond to the previous write, we can confuse
607                  * the HW and hit "undefined behaviour". After writing to ELSP,
608                  * we must then wait until we see a context-switch event from
609                  * the HW to indicate that it has had a chance to respond.
610                  */
611                 if (!execlists_is_active(execlists, EXECLISTS_ACTIVE_HWACK))
612                         goto unlock;
613
614                 if (need_preempt(engine, last, execlists->queue_priority)) {
615                         inject_preempt_context(engine);
616                         goto unlock;
617                 }
618
619                 /*
620                  * In theory, we could coalesce more requests onto
621                  * the second port (the first port is active, with
622                  * no preemptions pending). However, that means we
623                  * then have to deal with the possible lite-restore
624                  * of the second port (as we submit the ELSP, there
625                  * may be a context-switch) but also we may complete
626                  * the resubmission before the context-switch. Ergo,
627                  * coalescing onto the second port will cause a
628                  * preemption event, but we cannot predict whether
629                  * that will affect port[0] or port[1].
630                  *
631                  * If the second port is already active, we can wait
632                  * until the next context-switch before contemplating
633                  * new requests. The GPU will be busy and we should be
634                  * able to resubmit the new ELSP before it idles,
635                  * avoiding pipeline bubbles (momentary pauses where
636                  * the driver is unable to keep up the supply of new
637                  * work). However, we have to double check that the
638                  * priorities of the ports haven't been switch.
639                  */
640                 if (port_count(&port[1]))
641                         goto unlock;
642
643                 /*
644                  * WaIdleLiteRestore:bdw,skl
645                  * Apply the wa NOOPs to prevent
646                  * ring:HEAD == rq:TAIL as we resubmit the
647                  * request. See gen8_emit_breadcrumb() for
648                  * where we prepare the padding after the
649                  * end of the request.
650                  */
651                 last->tail = last->wa_tail;
652         }
653
654         while (rb) {
655                 struct i915_priolist *p = to_priolist(rb);
656                 struct i915_request *rq, *rn;
657
658                 list_for_each_entry_safe(rq, rn, &p->requests, sched.link) {
659                         /*
660                          * Can we combine this request with the current port?
661                          * It has to be the same context/ringbuffer and not
662                          * have any exceptions (e.g. GVT saying never to
663                          * combine contexts).
664                          *
665                          * If we can combine the requests, we can execute both
666                          * by updating the RING_TAIL to point to the end of the
667                          * second request, and so we never need to tell the
668                          * hardware about the first.
669                          */
670                         if (last && !can_merge_ctx(rq->ctx, last->ctx)) {
671                                 /*
672                                  * If we are on the second port and cannot
673                                  * combine this request with the last, then we
674                                  * are done.
675                                  */
676                                 if (port == last_port) {
677                                         __list_del_many(&p->requests,
678                                                         &rq->sched.link);
679                                         goto done;
680                                 }
681
682                                 /*
683                                  * If GVT overrides us we only ever submit
684                                  * port[0], leaving port[1] empty. Note that we
685                                  * also have to be careful that we don't queue
686                                  * the same context (even though a different
687                                  * request) to the second port.
688                                  */
689                                 if (ctx_single_port_submission(last->ctx) ||
690                                     ctx_single_port_submission(rq->ctx)) {
691                                         __list_del_many(&p->requests,
692                                                         &rq->sched.link);
693                                         goto done;
694                                 }
695
696                                 GEM_BUG_ON(last->ctx == rq->ctx);
697
698                                 if (submit)
699                                         port_assign(port, last);
700                                 port++;
701
702                                 GEM_BUG_ON(port_isset(port));
703                         }
704
705                         INIT_LIST_HEAD(&rq->sched.link);
706                         __i915_request_submit(rq);
707                         trace_i915_request_in(rq, port_index(port, execlists));
708                         last = rq;
709                         submit = true;
710                 }
711
712                 rb = rb_next(rb);
713                 rb_erase(&p->node, &execlists->queue);
714                 INIT_LIST_HEAD(&p->requests);
715                 if (p->priority != I915_PRIORITY_NORMAL)
716                         kmem_cache_free(engine->i915->priorities, p);
717         }
718
719 done:
720         /*
721          * Here be a bit of magic! Or sleight-of-hand, whichever you prefer.
722          *
723          * We choose queue_priority such that if we add a request of greater
724          * priority than this, we kick the submission tasklet to decide on
725          * the right order of submitting the requests to hardware. We must
726          * also be prepared to reorder requests as they are in-flight on the
727          * HW. We derive the queue_priority then as the first "hole" in
728          * the HW submission ports and if there are no available slots,
729          * the priority of the lowest executing request, i.e. last.
730          *
731          * When we do receive a higher priority request ready to run from the
732          * user, see queue_request(), the queue_priority is bumped to that
733          * request triggering preemption on the next dequeue (or subsequent
734          * interrupt for secondary ports).
735          */
736         execlists->queue_priority =
737                 port != execlists->port ? rq_prio(last) : INT_MIN;
738
739         execlists->first = rb;
740         if (submit)
741                 port_assign(port, last);
742
743         /* We must always keep the beast fed if we have work piled up */
744         GEM_BUG_ON(execlists->first && !port_isset(execlists->port));
745
746 unlock:
747         spin_unlock_irq(&engine->timeline->lock);
748
749         if (submit) {
750                 execlists_user_begin(execlists, execlists->port);
751                 execlists_submit_ports(engine);
752         }
753
754         GEM_BUG_ON(port_isset(execlists->port) &&
755                    !execlists_is_active(execlists, EXECLISTS_ACTIVE_USER));
756 }
757
758 void
759 execlists_cancel_port_requests(struct intel_engine_execlists * const execlists)
760 {
761         struct execlist_port *port = execlists->port;
762         unsigned int num_ports = execlists_num_ports(execlists);
763
764         while (num_ports-- && port_isset(port)) {
765                 struct i915_request *rq = port_request(port);
766
767                 GEM_TRACE("%s:port%u global=%d (fence %llx:%d), (current %d)\n",
768                           rq->engine->name,
769                           (unsigned int)(port - execlists->port),
770                           rq->global_seqno,
771                           rq->fence.context, rq->fence.seqno,
772                           intel_engine_get_seqno(rq->engine));
773
774                 GEM_BUG_ON(!execlists->active);
775                 intel_engine_context_out(rq->engine);
776
777                 execlists_context_status_change(rq,
778                                                 i915_request_completed(rq) ?
779                                                 INTEL_CONTEXT_SCHEDULE_OUT :
780                                                 INTEL_CONTEXT_SCHEDULE_PREEMPTED);
781
782                 i915_request_put(rq);
783
784                 memset(port, 0, sizeof(*port));
785                 port++;
786         }
787
788         execlists_clear_active(execlists, EXECLISTS_ACTIVE_USER);
789         execlists_user_end(execlists);
790 }
791
792 static void clear_gtiir(struct intel_engine_cs *engine)
793 {
794         struct drm_i915_private *dev_priv = engine->i915;
795         int i;
796
797         /*
798          * Clear any pending interrupt state.
799          *
800          * We do it twice out of paranoia that some of the IIR are
801          * double buffered, and so if we only reset it once there may
802          * still be an interrupt pending.
803          */
804         if (INTEL_GEN(dev_priv) >= 11) {
805                 static const struct {
806                         u8 bank;
807                         u8 bit;
808                 } gen11_gtiir[] = {
809                         [RCS] = {0, GEN11_RCS0},
810                         [BCS] = {0, GEN11_BCS},
811                         [_VCS(0)] = {1, GEN11_VCS(0)},
812                         [_VCS(1)] = {1, GEN11_VCS(1)},
813                         [_VCS(2)] = {1, GEN11_VCS(2)},
814                         [_VCS(3)] = {1, GEN11_VCS(3)},
815                         [_VECS(0)] = {1, GEN11_VECS(0)},
816                         [_VECS(1)] = {1, GEN11_VECS(1)},
817                 };
818                 unsigned long irqflags;
819
820                 GEM_BUG_ON(engine->id >= ARRAY_SIZE(gen11_gtiir));
821
822                 spin_lock_irqsave(&dev_priv->irq_lock, irqflags);
823                 for (i = 0; i < 2; i++) {
824                         gen11_reset_one_iir(dev_priv,
825                                             gen11_gtiir[engine->id].bank,
826                                             gen11_gtiir[engine->id].bit);
827                 }
828                 spin_unlock_irqrestore(&dev_priv->irq_lock, irqflags);
829         } else {
830                 static const u8 gtiir[] = {
831                         [RCS]  = 0,
832                         [BCS]  = 0,
833                         [VCS]  = 1,
834                         [VCS2] = 1,
835                         [VECS] = 3,
836                 };
837
838                 GEM_BUG_ON(engine->id >= ARRAY_SIZE(gtiir));
839
840                 for (i = 0; i < 2; i++) {
841                         I915_WRITE(GEN8_GT_IIR(gtiir[engine->id]),
842                                    engine->irq_keep_mask);
843                         POSTING_READ(GEN8_GT_IIR(gtiir[engine->id]));
844                 }
845                 GEM_BUG_ON(I915_READ(GEN8_GT_IIR(gtiir[engine->id])) &
846                            engine->irq_keep_mask);
847         }
848 }
849
850 static void reset_irq(struct intel_engine_cs *engine)
851 {
852         /* Mark all CS interrupts as complete */
853         smp_store_mb(engine->execlists.active, 0);
854         synchronize_hardirq(engine->i915->drm.irq);
855
856         clear_gtiir(engine);
857
858         /*
859          * The port is checked prior to scheduling a tasklet, but
860          * just in case we have suspended the tasklet to do the
861          * wedging make sure that when it wakes, it decides there
862          * is no work to do by clearing the irq_posted bit.
863          */
864         clear_bit(ENGINE_IRQ_EXECLIST, &engine->irq_posted);
865 }
866
867 static void execlists_cancel_requests(struct intel_engine_cs *engine)
868 {
869         struct intel_engine_execlists * const execlists = &engine->execlists;
870         struct i915_request *rq, *rn;
871         struct rb_node *rb;
872         unsigned long flags;
873
874         GEM_TRACE("%s current %d\n",
875                   engine->name, intel_engine_get_seqno(engine));
876
877         /*
878          * Before we call engine->cancel_requests(), we should have exclusive
879          * access to the submission state. This is arranged for us by the
880          * caller disabling the interrupt generation, the tasklet and other
881          * threads that may then access the same state, giving us a free hand
882          * to reset state. However, we still need to let lockdep be aware that
883          * we know this state may be accessed in hardirq context, so we
884          * disable the irq around this manipulation and we want to keep
885          * the spinlock focused on its duties and not accidentally conflate
886          * coverage to the submission's irq state. (Similarly, although we
887          * shouldn't need to disable irq around the manipulation of the
888          * submission's irq state, we also wish to remind ourselves that
889          * it is irq state.)
890          */
891         local_irq_save(flags);
892
893         /* Cancel the requests on the HW and clear the ELSP tracker. */
894         execlists_cancel_port_requests(execlists);
895         reset_irq(engine);
896
897         spin_lock(&engine->timeline->lock);
898
899         /* Mark all executing requests as skipped. */
900         list_for_each_entry(rq, &engine->timeline->requests, link) {
901                 GEM_BUG_ON(!rq->global_seqno);
902                 if (!i915_request_completed(rq))
903                         dma_fence_set_error(&rq->fence, -EIO);
904         }
905
906         /* Flush the queued requests to the timeline list (for retiring). */
907         rb = execlists->first;
908         while (rb) {
909                 struct i915_priolist *p = to_priolist(rb);
910
911                 list_for_each_entry_safe(rq, rn, &p->requests, sched.link) {
912                         INIT_LIST_HEAD(&rq->sched.link);
913
914                         dma_fence_set_error(&rq->fence, -EIO);
915                         __i915_request_submit(rq);
916                 }
917
918                 rb = rb_next(rb);
919                 rb_erase(&p->node, &execlists->queue);
920                 INIT_LIST_HEAD(&p->requests);
921                 if (p->priority != I915_PRIORITY_NORMAL)
922                         kmem_cache_free(engine->i915->priorities, p);
923         }
924
925         /* Remaining _unready_ requests will be nop'ed when submitted */
926
927         execlists->queue_priority = INT_MIN;
928         execlists->queue = RB_ROOT;
929         execlists->first = NULL;
930         GEM_BUG_ON(port_isset(execlists->port));
931
932         spin_unlock(&engine->timeline->lock);
933
934         local_irq_restore(flags);
935 }
936
937 /*
938  * Check the unread Context Status Buffers and manage the submission of new
939  * contexts to the ELSP accordingly.
940  */
941 static void execlists_submission_tasklet(unsigned long data)
942 {
943         struct intel_engine_cs * const engine = (struct intel_engine_cs *)data;
944         struct intel_engine_execlists * const execlists = &engine->execlists;
945         struct execlist_port *port = execlists->port;
946         struct drm_i915_private *dev_priv = engine->i915;
947         bool fw = false;
948
949         /*
950          * We can skip acquiring intel_runtime_pm_get() here as it was taken
951          * on our behalf by the request (see i915_gem_mark_busy()) and it will
952          * not be relinquished until the device is idle (see
953          * i915_gem_idle_work_handler()). As a precaution, we make sure
954          * that all ELSP are drained i.e. we have processed the CSB,
955          * before allowing ourselves to idle and calling intel_runtime_pm_put().
956          */
957         GEM_BUG_ON(!dev_priv->gt.awake);
958
959         /*
960          * Prefer doing test_and_clear_bit() as a two stage operation to avoid
961          * imposing the cost of a locked atomic transaction when submitting a
962          * new request (outside of the context-switch interrupt).
963          */
964         while (test_bit(ENGINE_IRQ_EXECLIST, &engine->irq_posted)) {
965                 /* The HWSP contains a (cacheable) mirror of the CSB */
966                 const u32 *buf =
967                         &engine->status_page.page_addr[I915_HWS_CSB_BUF0_INDEX];
968                 unsigned int head, tail;
969
970                 if (unlikely(execlists->csb_use_mmio)) {
971                         buf = (u32 * __force)
972                                 (dev_priv->regs + i915_mmio_reg_offset(RING_CONTEXT_STATUS_BUF_LO(engine, 0)));
973                         execlists->csb_head = -1; /* force mmio read of CSB ptrs */
974                 }
975
976                 /* Clear before reading to catch new interrupts */
977                 clear_bit(ENGINE_IRQ_EXECLIST, &engine->irq_posted);
978                 smp_mb__after_atomic();
979
980                 if (unlikely(execlists->csb_head == -1)) { /* following a reset */
981                         if (!fw) {
982                                 intel_uncore_forcewake_get(dev_priv,
983                                                            execlists->fw_domains);
984                                 fw = true;
985                         }
986
987                         head = readl(dev_priv->regs + i915_mmio_reg_offset(RING_CONTEXT_STATUS_PTR(engine)));
988                         tail = GEN8_CSB_WRITE_PTR(head);
989                         head = GEN8_CSB_READ_PTR(head);
990                         execlists->csb_head = head;
991                 } else {
992                         const int write_idx =
993                                 intel_hws_csb_write_index(dev_priv) -
994                                 I915_HWS_CSB_BUF0_INDEX;
995
996                         head = execlists->csb_head;
997                         tail = READ_ONCE(buf[write_idx]);
998                 }
999                 GEM_TRACE("%s cs-irq head=%d [%d%s], tail=%d [%d%s]\n",
1000                           engine->name,
1001                           head, GEN8_CSB_READ_PTR(readl(dev_priv->regs + i915_mmio_reg_offset(RING_CONTEXT_STATUS_PTR(engine)))), fw ? "" : "?",
1002                           tail, GEN8_CSB_WRITE_PTR(readl(dev_priv->regs + i915_mmio_reg_offset(RING_CONTEXT_STATUS_PTR(engine)))), fw ? "" : "?");
1003
1004                 while (head != tail) {
1005                         struct i915_request *rq;
1006                         unsigned int status;
1007                         unsigned int count;
1008
1009                         if (++head == GEN8_CSB_ENTRIES)
1010                                 head = 0;
1011
1012                         /* We are flying near dragons again.
1013                          *
1014                          * We hold a reference to the request in execlist_port[]
1015                          * but no more than that. We are operating in softirq
1016                          * context and so cannot hold any mutex or sleep. That
1017                          * prevents us stopping the requests we are processing
1018                          * in port[] from being retired simultaneously (the
1019                          * breadcrumb will be complete before we see the
1020                          * context-switch). As we only hold the reference to the
1021                          * request, any pointer chasing underneath the request
1022                          * is subject to a potential use-after-free. Thus we
1023                          * store all of the bookkeeping within port[] as
1024                          * required, and avoid using unguarded pointers beneath
1025                          * request itself. The same applies to the atomic
1026                          * status notifier.
1027                          */
1028
1029                         status = READ_ONCE(buf[2 * head]); /* maybe mmio! */
1030                         GEM_TRACE("%s csb[%d]: status=0x%08x:0x%08x, active=0x%x\n",
1031                                   engine->name, head,
1032                                   status, buf[2*head + 1],
1033                                   execlists->active);
1034
1035                         if (status & (GEN8_CTX_STATUS_IDLE_ACTIVE |
1036                                       GEN8_CTX_STATUS_PREEMPTED))
1037                                 execlists_set_active(execlists,
1038                                                      EXECLISTS_ACTIVE_HWACK);
1039                         if (status & GEN8_CTX_STATUS_ACTIVE_IDLE)
1040                                 execlists_clear_active(execlists,
1041                                                        EXECLISTS_ACTIVE_HWACK);
1042
1043                         if (!(status & GEN8_CTX_STATUS_COMPLETED_MASK))
1044                                 continue;
1045
1046                         /* We should never get a COMPLETED | IDLE_ACTIVE! */
1047                         GEM_BUG_ON(status & GEN8_CTX_STATUS_IDLE_ACTIVE);
1048
1049                         if (status & GEN8_CTX_STATUS_COMPLETE &&
1050                             buf[2*head + 1] == execlists->preempt_complete_status) {
1051                                 GEM_TRACE("%s preempt-idle\n", engine->name);
1052
1053                                 execlists_cancel_port_requests(execlists);
1054                                 execlists_unwind_incomplete_requests(execlists);
1055
1056                                 GEM_BUG_ON(!execlists_is_active(execlists,
1057                                                                 EXECLISTS_ACTIVE_PREEMPT));
1058                                 execlists_clear_active(execlists,
1059                                                        EXECLISTS_ACTIVE_PREEMPT);
1060                                 continue;
1061                         }
1062
1063                         if (status & GEN8_CTX_STATUS_PREEMPTED &&
1064                             execlists_is_active(execlists,
1065                                                 EXECLISTS_ACTIVE_PREEMPT))
1066                                 continue;
1067
1068                         GEM_BUG_ON(!execlists_is_active(execlists,
1069                                                         EXECLISTS_ACTIVE_USER));
1070
1071                         rq = port_unpack(port, &count);
1072                         GEM_TRACE("%s out[0]: ctx=%d.%d, global=%d (fence %llx:%d) (current %d), prio=%d\n",
1073                                   engine->name,
1074                                   port->context_id, count,
1075                                   rq ? rq->global_seqno : 0,
1076                                   rq ? rq->fence.context : 0,
1077                                   rq ? rq->fence.seqno : 0,
1078                                   intel_engine_get_seqno(engine),
1079                                   rq ? rq_prio(rq) : 0);
1080
1081                         /* Check the context/desc id for this event matches */
1082                         GEM_DEBUG_BUG_ON(buf[2 * head + 1] != port->context_id);
1083
1084                         GEM_BUG_ON(count == 0);
1085                         if (--count == 0) {
1086                                 /*
1087                                  * On the final event corresponding to the
1088                                  * submission of this context, we expect either
1089                                  * an element-switch event or a completion
1090                                  * event (and on completion, the active-idle
1091                                  * marker). No more preemptions, lite-restore
1092                                  * or otherwise.
1093                                  */
1094                                 GEM_BUG_ON(status & GEN8_CTX_STATUS_PREEMPTED);
1095                                 GEM_BUG_ON(port_isset(&port[1]) &&
1096                                            !(status & GEN8_CTX_STATUS_ELEMENT_SWITCH));
1097                                 GEM_BUG_ON(!port_isset(&port[1]) &&
1098                                            !(status & GEN8_CTX_STATUS_ACTIVE_IDLE));
1099
1100                                 /*
1101                                  * We rely on the hardware being strongly
1102                                  * ordered, that the breadcrumb write is
1103                                  * coherent (visible from the CPU) before the
1104                                  * user interrupt and CSB is processed.
1105                                  */
1106                                 GEM_BUG_ON(!i915_request_completed(rq));
1107
1108                                 execlists_context_schedule_out(rq);
1109                                 trace_i915_request_out(rq);
1110                                 i915_request_put(rq);
1111
1112                                 GEM_TRACE("%s completed ctx=%d\n",
1113                                           engine->name, port->context_id);
1114
1115                                 port = execlists_port_complete(execlists, port);
1116                                 if (port_isset(port))
1117                                         execlists_user_begin(execlists, port);
1118                                 else
1119                                         execlists_user_end(execlists);
1120                         } else {
1121                                 port_set(port, port_pack(rq, count));
1122                         }
1123                 }
1124
1125                 if (head != execlists->csb_head) {
1126                         execlists->csb_head = head;
1127                         writel(_MASKED_FIELD(GEN8_CSB_READ_PTR_MASK, head << 8),
1128                                dev_priv->regs + i915_mmio_reg_offset(RING_CONTEXT_STATUS_PTR(engine)));
1129                 }
1130         }
1131
1132         if (!execlists_is_active(execlists, EXECLISTS_ACTIVE_PREEMPT))
1133                 execlists_dequeue(engine);
1134
1135         if (fw)
1136                 intel_uncore_forcewake_put(dev_priv, execlists->fw_domains);
1137
1138         /* If the engine is now idle, so should be the flag; and vice versa. */
1139         GEM_BUG_ON(execlists_is_active(&engine->execlists,
1140                                        EXECLISTS_ACTIVE_USER) ==
1141                    !port_isset(engine->execlists.port));
1142 }
1143
1144 static void queue_request(struct intel_engine_cs *engine,
1145                           struct i915_sched_node *node,
1146                           int prio)
1147 {
1148         list_add_tail(&node->link,
1149                       &lookup_priolist(engine, node, prio)->requests);
1150 }
1151
1152 static void __submit_queue(struct intel_engine_cs *engine, int prio)
1153 {
1154         engine->execlists.queue_priority = prio;
1155         tasklet_hi_schedule(&engine->execlists.tasklet);
1156 }
1157
1158 static void submit_queue(struct intel_engine_cs *engine, int prio)
1159 {
1160         if (prio > engine->execlists.queue_priority)
1161                 __submit_queue(engine, prio);
1162 }
1163
1164 static void execlists_submit_request(struct i915_request *request)
1165 {
1166         struct intel_engine_cs *engine = request->engine;
1167         unsigned long flags;
1168
1169         /* Will be called from irq-context when using foreign fences. */
1170         spin_lock_irqsave(&engine->timeline->lock, flags);
1171
1172         queue_request(engine, &request->sched, rq_prio(request));
1173         submit_queue(engine, rq_prio(request));
1174
1175         GEM_BUG_ON(!engine->execlists.first);
1176         GEM_BUG_ON(list_empty(&request->sched.link));
1177
1178         spin_unlock_irqrestore(&engine->timeline->lock, flags);
1179 }
1180
1181 static struct i915_request *sched_to_request(struct i915_sched_node *node)
1182 {
1183         return container_of(node, struct i915_request, sched);
1184 }
1185
1186 static struct intel_engine_cs *
1187 sched_lock_engine(struct i915_sched_node *node, struct intel_engine_cs *locked)
1188 {
1189         struct intel_engine_cs *engine = sched_to_request(node)->engine;
1190
1191         GEM_BUG_ON(!locked);
1192
1193         if (engine != locked) {
1194                 spin_unlock(&locked->timeline->lock);
1195                 spin_lock(&engine->timeline->lock);
1196         }
1197
1198         return engine;
1199 }
1200
1201 static void execlists_schedule(struct i915_request *request,
1202                                const struct i915_sched_attr *attr)
1203 {
1204         struct intel_engine_cs *engine;
1205         struct i915_dependency *dep, *p;
1206         struct i915_dependency stack;
1207         const int prio = attr->priority;
1208         LIST_HEAD(dfs);
1209
1210         GEM_BUG_ON(prio == I915_PRIORITY_INVALID);
1211
1212         if (i915_request_completed(request))
1213                 return;
1214
1215         if (prio <= READ_ONCE(request->sched.attr.priority))
1216                 return;
1217
1218         /* Need BKL in order to use the temporary link inside i915_dependency */
1219         lockdep_assert_held(&request->i915->drm.struct_mutex);
1220
1221         stack.signaler = &request->sched;
1222         list_add(&stack.dfs_link, &dfs);
1223
1224         /*
1225          * Recursively bump all dependent priorities to match the new request.
1226          *
1227          * A naive approach would be to use recursion:
1228          * static void update_priorities(struct i915_sched_node *node, prio) {
1229          *      list_for_each_entry(dep, &node->signalers_list, signal_link)
1230          *              update_priorities(dep->signal, prio)
1231          *      queue_request(node);
1232          * }
1233          * but that may have unlimited recursion depth and so runs a very
1234          * real risk of overunning the kernel stack. Instead, we build
1235          * a flat list of all dependencies starting with the current request.
1236          * As we walk the list of dependencies, we add all of its dependencies
1237          * to the end of the list (this may include an already visited
1238          * request) and continue to walk onwards onto the new dependencies. The
1239          * end result is a topological list of requests in reverse order, the
1240          * last element in the list is the request we must execute first.
1241          */
1242         list_for_each_entry(dep, &dfs, dfs_link) {
1243                 struct i915_sched_node *node = dep->signaler;
1244
1245                 /*
1246                  * Within an engine, there can be no cycle, but we may
1247                  * refer to the same dependency chain multiple times
1248                  * (redundant dependencies are not eliminated) and across
1249                  * engines.
1250                  */
1251                 list_for_each_entry(p, &node->signalers_list, signal_link) {
1252                         GEM_BUG_ON(p == dep); /* no cycles! */
1253
1254                         if (i915_sched_node_signaled(p->signaler))
1255                                 continue;
1256
1257                         GEM_BUG_ON(p->signaler->attr.priority < node->attr.priority);
1258                         if (prio > READ_ONCE(p->signaler->attr.priority))
1259                                 list_move_tail(&p->dfs_link, &dfs);
1260                 }
1261         }
1262
1263         /*
1264          * If we didn't need to bump any existing priorities, and we haven't
1265          * yet submitted this request (i.e. there is no potential race with
1266          * execlists_submit_request()), we can set our own priority and skip
1267          * acquiring the engine locks.
1268          */
1269         if (request->sched.attr.priority == I915_PRIORITY_INVALID) {
1270                 GEM_BUG_ON(!list_empty(&request->sched.link));
1271                 request->sched.attr = *attr;
1272                 if (stack.dfs_link.next == stack.dfs_link.prev)
1273                         return;
1274                 __list_del_entry(&stack.dfs_link);
1275         }
1276
1277         engine = request->engine;
1278         spin_lock_irq(&engine->timeline->lock);
1279
1280         /* Fifo and depth-first replacement ensure our deps execute before us */
1281         list_for_each_entry_safe_reverse(dep, p, &dfs, dfs_link) {
1282                 struct i915_sched_node *node = dep->signaler;
1283
1284                 INIT_LIST_HEAD(&dep->dfs_link);
1285
1286                 engine = sched_lock_engine(node, engine);
1287
1288                 if (prio <= node->attr.priority)
1289                         continue;
1290
1291                 node->attr.priority = prio;
1292                 if (!list_empty(&node->link)) {
1293                         __list_del_entry(&node->link);
1294                         queue_request(engine, node, prio);
1295                 }
1296
1297                 if (prio > engine->execlists.queue_priority &&
1298                     i915_sw_fence_done(&sched_to_request(node)->submit))
1299                         __submit_queue(engine, prio);
1300         }
1301
1302         spin_unlock_irq(&engine->timeline->lock);
1303 }
1304
1305 static int __context_pin(struct i915_gem_context *ctx, struct i915_vma *vma)
1306 {
1307         unsigned int flags;
1308         int err;
1309
1310         /*
1311          * Clear this page out of any CPU caches for coherent swap-in/out.
1312          * We only want to do this on the first bind so that we do not stall
1313          * on an active context (which by nature is already on the GPU).
1314          */
1315         if (!(vma->flags & I915_VMA_GLOBAL_BIND)) {
1316                 err = i915_gem_object_set_to_gtt_domain(vma->obj, true);
1317                 if (err)
1318                         return err;
1319         }
1320
1321         flags = PIN_GLOBAL | PIN_HIGH;
1322         if (ctx->ggtt_offset_bias)
1323                 flags |= PIN_OFFSET_BIAS | ctx->ggtt_offset_bias;
1324
1325         return i915_vma_pin(vma, 0, GEN8_LR_CONTEXT_ALIGN, flags);
1326 }
1327
1328 static struct intel_ring *
1329 execlists_context_pin(struct intel_engine_cs *engine,
1330                       struct i915_gem_context *ctx)
1331 {
1332         struct intel_context *ce = to_intel_context(ctx, engine);
1333         void *vaddr;
1334         int ret;
1335
1336         lockdep_assert_held(&ctx->i915->drm.struct_mutex);
1337
1338         if (likely(ce->pin_count++))
1339                 goto out;
1340         GEM_BUG_ON(!ce->pin_count); /* no overflow please! */
1341
1342         ret = execlists_context_deferred_alloc(ctx, engine);
1343         if (ret)
1344                 goto err;
1345         GEM_BUG_ON(!ce->state);
1346
1347         ret = __context_pin(ctx, ce->state);
1348         if (ret)
1349                 goto err;
1350
1351         vaddr = i915_gem_object_pin_map(ce->state->obj, I915_MAP_WB);
1352         if (IS_ERR(vaddr)) {
1353                 ret = PTR_ERR(vaddr);
1354                 goto unpin_vma;
1355         }
1356
1357         ret = intel_ring_pin(ce->ring, ctx->i915, ctx->ggtt_offset_bias);
1358         if (ret)
1359                 goto unpin_map;
1360
1361         intel_lr_context_descriptor_update(ctx, engine);
1362
1363         ce->lrc_reg_state = vaddr + LRC_STATE_PN * PAGE_SIZE;
1364         ce->lrc_reg_state[CTX_RING_BUFFER_START+1] =
1365                 i915_ggtt_offset(ce->ring->vma);
1366         ce->lrc_reg_state[CTX_RING_HEAD+1] = ce->ring->head;
1367
1368         ce->state->obj->pin_global++;
1369         i915_gem_context_get(ctx);
1370 out:
1371         return ce->ring;
1372
1373 unpin_map:
1374         i915_gem_object_unpin_map(ce->state->obj);
1375 unpin_vma:
1376         __i915_vma_unpin(ce->state);
1377 err:
1378         ce->pin_count = 0;
1379         return ERR_PTR(ret);
1380 }
1381
1382 static void execlists_context_unpin(struct intel_engine_cs *engine,
1383                                     struct i915_gem_context *ctx)
1384 {
1385         struct intel_context *ce = to_intel_context(ctx, engine);
1386
1387         lockdep_assert_held(&ctx->i915->drm.struct_mutex);
1388         GEM_BUG_ON(ce->pin_count == 0);
1389
1390         if (--ce->pin_count)
1391                 return;
1392
1393         intel_ring_unpin(ce->ring);
1394
1395         ce->state->obj->pin_global--;
1396         i915_gem_object_unpin_map(ce->state->obj);
1397         i915_vma_unpin(ce->state);
1398
1399         i915_gem_context_put(ctx);
1400 }
1401
1402 static int execlists_request_alloc(struct i915_request *request)
1403 {
1404         struct intel_context *ce =
1405                 to_intel_context(request->ctx, request->engine);
1406         int ret;
1407
1408         GEM_BUG_ON(!ce->pin_count);
1409
1410         /* Flush enough space to reduce the likelihood of waiting after
1411          * we start building the request - in which case we will just
1412          * have to repeat work.
1413          */
1414         request->reserved_space += EXECLISTS_REQUEST_SIZE;
1415
1416         ret = intel_ring_wait_for_space(request->ring, request->reserved_space);
1417         if (ret)
1418                 return ret;
1419
1420         /* Note that after this point, we have committed to using
1421          * this request as it is being used to both track the
1422          * state of engine initialisation and liveness of the
1423          * golden renderstate above. Think twice before you try
1424          * to cancel/unwind this request now.
1425          */
1426
1427         request->reserved_space -= EXECLISTS_REQUEST_SIZE;
1428         return 0;
1429 }
1430
1431 /*
1432  * In this WA we need to set GEN8_L3SQCREG4[21:21] and reset it after
1433  * PIPE_CONTROL instruction. This is required for the flush to happen correctly
1434  * but there is a slight complication as this is applied in WA batch where the
1435  * values are only initialized once so we cannot take register value at the
1436  * beginning and reuse it further; hence we save its value to memory, upload a
1437  * constant value with bit21 set and then we restore it back with the saved value.
1438  * To simplify the WA, a constant value is formed by using the default value
1439  * of this register. This shouldn't be a problem because we are only modifying
1440  * it for a short period and this batch in non-premptible. We can ofcourse
1441  * use additional instructions that read the actual value of the register
1442  * at that time and set our bit of interest but it makes the WA complicated.
1443  *
1444  * This WA is also required for Gen9 so extracting as a function avoids
1445  * code duplication.
1446  */
1447 static u32 *
1448 gen8_emit_flush_coherentl3_wa(struct intel_engine_cs *engine, u32 *batch)
1449 {
1450         *batch++ = MI_STORE_REGISTER_MEM_GEN8 | MI_SRM_LRM_GLOBAL_GTT;
1451         *batch++ = i915_mmio_reg_offset(GEN8_L3SQCREG4);
1452         *batch++ = i915_ggtt_offset(engine->scratch) + 256;
1453         *batch++ = 0;
1454
1455         *batch++ = MI_LOAD_REGISTER_IMM(1);
1456         *batch++ = i915_mmio_reg_offset(GEN8_L3SQCREG4);
1457         *batch++ = 0x40400000 | GEN8_LQSC_FLUSH_COHERENT_LINES;
1458
1459         batch = gen8_emit_pipe_control(batch,
1460                                        PIPE_CONTROL_CS_STALL |
1461                                        PIPE_CONTROL_DC_FLUSH_ENABLE,
1462                                        0);
1463
1464         *batch++ = MI_LOAD_REGISTER_MEM_GEN8 | MI_SRM_LRM_GLOBAL_GTT;
1465         *batch++ = i915_mmio_reg_offset(GEN8_L3SQCREG4);
1466         *batch++ = i915_ggtt_offset(engine->scratch) + 256;
1467         *batch++ = 0;
1468
1469         return batch;
1470 }
1471
1472 /*
1473  * Typically we only have one indirect_ctx and per_ctx batch buffer which are
1474  * initialized at the beginning and shared across all contexts but this field
1475  * helps us to have multiple batches at different offsets and select them based
1476  * on a criteria. At the moment this batch always start at the beginning of the page
1477  * and at this point we don't have multiple wa_ctx batch buffers.
1478  *
1479  * The number of WA applied are not known at the beginning; we use this field
1480  * to return the no of DWORDS written.
1481  *
1482  * It is to be noted that this batch does not contain MI_BATCH_BUFFER_END
1483  * so it adds NOOPs as padding to make it cacheline aligned.
1484  * MI_BATCH_BUFFER_END will be added to perctx batch and both of them together
1485  * makes a complete batch buffer.
1486  */
1487 static u32 *gen8_init_indirectctx_bb(struct intel_engine_cs *engine, u32 *batch)
1488 {
1489         /* WaDisableCtxRestoreArbitration:bdw,chv */
1490         *batch++ = MI_ARB_ON_OFF | MI_ARB_DISABLE;
1491
1492         /* WaFlushCoherentL3CacheLinesAtContextSwitch:bdw */
1493         if (IS_BROADWELL(engine->i915))
1494                 batch = gen8_emit_flush_coherentl3_wa(engine, batch);
1495
1496         /* WaClearSlmSpaceAtContextSwitch:bdw,chv */
1497         /* Actual scratch location is at 128 bytes offset */
1498         batch = gen8_emit_pipe_control(batch,
1499                                        PIPE_CONTROL_FLUSH_L3 |
1500                                        PIPE_CONTROL_GLOBAL_GTT_IVB |
1501                                        PIPE_CONTROL_CS_STALL |
1502                                        PIPE_CONTROL_QW_WRITE,
1503                                        i915_ggtt_offset(engine->scratch) +
1504                                        2 * CACHELINE_BYTES);
1505
1506         *batch++ = MI_ARB_ON_OFF | MI_ARB_ENABLE;
1507
1508         /* Pad to end of cacheline */
1509         while ((unsigned long)batch % CACHELINE_BYTES)
1510                 *batch++ = MI_NOOP;
1511
1512         /*
1513          * MI_BATCH_BUFFER_END is not required in Indirect ctx BB because
1514          * execution depends on the length specified in terms of cache lines
1515          * in the register CTX_RCS_INDIRECT_CTX
1516          */
1517
1518         return batch;
1519 }
1520
1521 static u32 *gen9_init_indirectctx_bb(struct intel_engine_cs *engine, u32 *batch)
1522 {
1523         *batch++ = MI_ARB_ON_OFF | MI_ARB_DISABLE;
1524
1525         /* WaFlushCoherentL3CacheLinesAtContextSwitch:skl,bxt,glk */
1526         batch = gen8_emit_flush_coherentl3_wa(engine, batch);
1527
1528         /* WaDisableGatherAtSetShaderCommonSlice:skl,bxt,kbl,glk */
1529         *batch++ = MI_LOAD_REGISTER_IMM(1);
1530         *batch++ = i915_mmio_reg_offset(COMMON_SLICE_CHICKEN2);
1531         *batch++ = _MASKED_BIT_DISABLE(
1532                         GEN9_DISABLE_GATHER_AT_SET_SHADER_COMMON_SLICE);
1533         *batch++ = MI_NOOP;
1534
1535         /* WaClearSlmSpaceAtContextSwitch:kbl */
1536         /* Actual scratch location is at 128 bytes offset */
1537         if (IS_KBL_REVID(engine->i915, 0, KBL_REVID_A0)) {
1538                 batch = gen8_emit_pipe_control(batch,
1539                                                PIPE_CONTROL_FLUSH_L3 |
1540                                                PIPE_CONTROL_GLOBAL_GTT_IVB |
1541                                                PIPE_CONTROL_CS_STALL |
1542                                                PIPE_CONTROL_QW_WRITE,
1543                                                i915_ggtt_offset(engine->scratch)
1544                                                + 2 * CACHELINE_BYTES);
1545         }
1546
1547         /* WaMediaPoolStateCmdInWABB:bxt,glk */
1548         if (HAS_POOLED_EU(engine->i915)) {
1549                 /*
1550                  * EU pool configuration is setup along with golden context
1551                  * during context initialization. This value depends on
1552                  * device type (2x6 or 3x6) and needs to be updated based
1553                  * on which subslice is disabled especially for 2x6
1554                  * devices, however it is safe to load default
1555                  * configuration of 3x6 device instead of masking off
1556                  * corresponding bits because HW ignores bits of a disabled
1557                  * subslice and drops down to appropriate config. Please
1558                  * see render_state_setup() in i915_gem_render_state.c for
1559                  * possible configurations, to avoid duplication they are
1560                  * not shown here again.
1561                  */
1562                 *batch++ = GEN9_MEDIA_POOL_STATE;
1563                 *batch++ = GEN9_MEDIA_POOL_ENABLE;
1564                 *batch++ = 0x00777000;
1565                 *batch++ = 0;
1566                 *batch++ = 0;
1567                 *batch++ = 0;
1568         }
1569
1570         *batch++ = MI_ARB_ON_OFF | MI_ARB_ENABLE;
1571
1572         /* Pad to end of cacheline */
1573         while ((unsigned long)batch % CACHELINE_BYTES)
1574                 *batch++ = MI_NOOP;
1575
1576         return batch;
1577 }
1578
1579 static u32 *
1580 gen10_init_indirectctx_bb(struct intel_engine_cs *engine, u32 *batch)
1581 {
1582         int i;
1583
1584         /*
1585          * WaPipeControlBefore3DStateSamplePattern: cnl
1586          *
1587          * Ensure the engine is idle prior to programming a
1588          * 3DSTATE_SAMPLE_PATTERN during a context restore.
1589          */
1590         batch = gen8_emit_pipe_control(batch,
1591                                        PIPE_CONTROL_CS_STALL,
1592                                        0);
1593         /*
1594          * WaPipeControlBefore3DStateSamplePattern says we need 4 dwords for
1595          * the PIPE_CONTROL followed by 12 dwords of 0x0, so 16 dwords in
1596          * total. However, a PIPE_CONTROL is 6 dwords long, not 4, which is
1597          * confusing. Since gen8_emit_pipe_control() already advances the
1598          * batch by 6 dwords, we advance the other 10 here, completing a
1599          * cacheline. It's not clear if the workaround requires this padding
1600          * before other commands, or if it's just the regular padding we would
1601          * already have for the workaround bb, so leave it here for now.
1602          */
1603         for (i = 0; i < 10; i++)
1604                 *batch++ = MI_NOOP;
1605
1606         /* Pad to end of cacheline */
1607         while ((unsigned long)batch % CACHELINE_BYTES)
1608                 *batch++ = MI_NOOP;
1609
1610         return batch;
1611 }
1612
1613 #define CTX_WA_BB_OBJ_SIZE (PAGE_SIZE)
1614
1615 static int lrc_setup_wa_ctx(struct intel_engine_cs *engine)
1616 {
1617         struct drm_i915_gem_object *obj;
1618         struct i915_vma *vma;
1619         int err;
1620
1621         obj = i915_gem_object_create(engine->i915, CTX_WA_BB_OBJ_SIZE);
1622         if (IS_ERR(obj))
1623                 return PTR_ERR(obj);
1624
1625         vma = i915_vma_instance(obj, &engine->i915->ggtt.base, NULL);
1626         if (IS_ERR(vma)) {
1627                 err = PTR_ERR(vma);
1628                 goto err;
1629         }
1630
1631         err = i915_vma_pin(vma, 0, PAGE_SIZE, PIN_GLOBAL | PIN_HIGH);
1632         if (err)
1633                 goto err;
1634
1635         engine->wa_ctx.vma = vma;
1636         return 0;
1637
1638 err:
1639         i915_gem_object_put(obj);
1640         return err;
1641 }
1642
1643 static void lrc_destroy_wa_ctx(struct intel_engine_cs *engine)
1644 {
1645         i915_vma_unpin_and_release(&engine->wa_ctx.vma);
1646 }
1647
1648 typedef u32 *(*wa_bb_func_t)(struct intel_engine_cs *engine, u32 *batch);
1649
1650 static int intel_init_workaround_bb(struct intel_engine_cs *engine)
1651 {
1652         struct i915_ctx_workarounds *wa_ctx = &engine->wa_ctx;
1653         struct i915_wa_ctx_bb *wa_bb[2] = { &wa_ctx->indirect_ctx,
1654                                             &wa_ctx->per_ctx };
1655         wa_bb_func_t wa_bb_fn[2];
1656         struct page *page;
1657         void *batch, *batch_ptr;
1658         unsigned int i;
1659         int ret;
1660
1661         if (GEM_WARN_ON(engine->id != RCS))
1662                 return -EINVAL;
1663
1664         switch (INTEL_GEN(engine->i915)) {
1665         case 10:
1666                 wa_bb_fn[0] = gen10_init_indirectctx_bb;
1667                 wa_bb_fn[1] = NULL;
1668                 break;
1669         case 9:
1670                 wa_bb_fn[0] = gen9_init_indirectctx_bb;
1671                 wa_bb_fn[1] = NULL;
1672                 break;
1673         case 8:
1674                 wa_bb_fn[0] = gen8_init_indirectctx_bb;
1675                 wa_bb_fn[1] = NULL;
1676                 break;
1677         default:
1678                 MISSING_CASE(INTEL_GEN(engine->i915));
1679                 return 0;
1680         }
1681
1682         ret = lrc_setup_wa_ctx(engine);
1683         if (ret) {
1684                 DRM_DEBUG_DRIVER("Failed to setup context WA page: %d\n", ret);
1685                 return ret;
1686         }
1687
1688         page = i915_gem_object_get_dirty_page(wa_ctx->vma->obj, 0);
1689         batch = batch_ptr = kmap_atomic(page);
1690
1691         /*
1692          * Emit the two workaround batch buffers, recording the offset from the
1693          * start of the workaround batch buffer object for each and their
1694          * respective sizes.
1695          */
1696         for (i = 0; i < ARRAY_SIZE(wa_bb_fn); i++) {
1697                 wa_bb[i]->offset = batch_ptr - batch;
1698                 if (GEM_WARN_ON(!IS_ALIGNED(wa_bb[i]->offset,
1699                                             CACHELINE_BYTES))) {
1700                         ret = -EINVAL;
1701                         break;
1702                 }
1703                 if (wa_bb_fn[i])
1704                         batch_ptr = wa_bb_fn[i](engine, batch_ptr);
1705                 wa_bb[i]->size = batch_ptr - (batch + wa_bb[i]->offset);
1706         }
1707
1708         BUG_ON(batch_ptr - batch > CTX_WA_BB_OBJ_SIZE);
1709
1710         kunmap_atomic(batch);
1711         if (ret)
1712                 lrc_destroy_wa_ctx(engine);
1713
1714         return ret;
1715 }
1716
1717 static void enable_execlists(struct intel_engine_cs *engine)
1718 {
1719         struct drm_i915_private *dev_priv = engine->i915;
1720
1721         I915_WRITE(RING_HWSTAM(engine->mmio_base), 0xffffffff);
1722
1723         /*
1724          * Make sure we're not enabling the new 12-deep CSB
1725          * FIFO as that requires a slightly updated handling
1726          * in the ctx switch irq. Since we're currently only
1727          * using only 2 elements of the enhanced execlists the
1728          * deeper FIFO it's not needed and it's not worth adding
1729          * more statements to the irq handler to support it.
1730          */
1731         if (INTEL_GEN(dev_priv) >= 11)
1732                 I915_WRITE(RING_MODE_GEN7(engine),
1733                            _MASKED_BIT_DISABLE(GEN11_GFX_DISABLE_LEGACY_MODE));
1734         else
1735                 I915_WRITE(RING_MODE_GEN7(engine),
1736                            _MASKED_BIT_ENABLE(GFX_RUN_LIST_ENABLE));
1737
1738         I915_WRITE(RING_HWS_PGA(engine->mmio_base),
1739                    engine->status_page.ggtt_offset);
1740         POSTING_READ(RING_HWS_PGA(engine->mmio_base));
1741
1742         /* Following the reset, we need to reload the CSB read/write pointers */
1743         engine->execlists.csb_head = -1;
1744 }
1745
1746 static int gen8_init_common_ring(struct intel_engine_cs *engine)
1747 {
1748         struct intel_engine_execlists * const execlists = &engine->execlists;
1749         int ret;
1750
1751         ret = intel_mocs_init_engine(engine);
1752         if (ret)
1753                 return ret;
1754
1755         intel_engine_reset_breadcrumbs(engine);
1756         intel_engine_init_hangcheck(engine);
1757
1758         enable_execlists(engine);
1759
1760         /* After a GPU reset, we may have requests to replay */
1761         if (execlists->first)
1762                 tasklet_schedule(&execlists->tasklet);
1763
1764         return 0;
1765 }
1766
1767 static int gen8_init_render_ring(struct intel_engine_cs *engine)
1768 {
1769         struct drm_i915_private *dev_priv = engine->i915;
1770         int ret;
1771
1772         ret = gen8_init_common_ring(engine);
1773         if (ret)
1774                 return ret;
1775
1776         intel_whitelist_workarounds_apply(engine);
1777
1778         /* We need to disable the AsyncFlip performance optimisations in order
1779          * to use MI_WAIT_FOR_EVENT within the CS. It should already be
1780          * programmed to '1' on all products.
1781          *
1782          * WaDisableAsyncFlipPerfMode:snb,ivb,hsw,vlv,bdw,chv
1783          */
1784         I915_WRITE(MI_MODE, _MASKED_BIT_ENABLE(ASYNC_FLIP_PERF_DISABLE));
1785
1786         I915_WRITE(INSTPM, _MASKED_BIT_ENABLE(INSTPM_FORCE_ORDERING));
1787
1788         return 0;
1789 }
1790
1791 static int gen9_init_render_ring(struct intel_engine_cs *engine)
1792 {
1793         int ret;
1794
1795         ret = gen8_init_common_ring(engine);
1796         if (ret)
1797                 return ret;
1798
1799         intel_whitelist_workarounds_apply(engine);
1800
1801         return 0;
1802 }
1803
1804 static void reset_common_ring(struct intel_engine_cs *engine,
1805                               struct i915_request *request)
1806 {
1807         struct intel_engine_execlists * const execlists = &engine->execlists;
1808         unsigned long flags;
1809         u32 *regs;
1810
1811         GEM_TRACE("%s request global=%x, current=%d\n",
1812                   engine->name, request ? request->global_seqno : 0,
1813                   intel_engine_get_seqno(engine));
1814
1815         /* See execlists_cancel_requests() for the irq/spinlock split. */
1816         local_irq_save(flags);
1817
1818         /*
1819          * Catch up with any missed context-switch interrupts.
1820          *
1821          * Ideally we would just read the remaining CSB entries now that we
1822          * know the gpu is idle. However, the CSB registers are sometimes^W
1823          * often trashed across a GPU reset! Instead we have to rely on
1824          * guessing the missed context-switch events by looking at what
1825          * requests were completed.
1826          */
1827         execlists_cancel_port_requests(execlists);
1828         reset_irq(engine);
1829
1830         /* Push back any incomplete requests for replay after the reset. */
1831         spin_lock(&engine->timeline->lock);
1832         __unwind_incomplete_requests(engine);
1833         spin_unlock(&engine->timeline->lock);
1834
1835         local_irq_restore(flags);
1836
1837         /*
1838          * If the request was innocent, we leave the request in the ELSP
1839          * and will try to replay it on restarting. The context image may
1840          * have been corrupted by the reset, in which case we may have
1841          * to service a new GPU hang, but more likely we can continue on
1842          * without impact.
1843          *
1844          * If the request was guilty, we presume the context is corrupt
1845          * and have to at least restore the RING register in the context
1846          * image back to the expected values to skip over the guilty request.
1847          */
1848         if (!request || request->fence.error != -EIO)
1849                 return;
1850
1851         /*
1852          * We want a simple context + ring to execute the breadcrumb update.
1853          * We cannot rely on the context being intact across the GPU hang,
1854          * so clear it and rebuild just what we need for the breadcrumb.
1855          * All pending requests for this context will be zapped, and any
1856          * future request will be after userspace has had the opportunity
1857          * to recreate its own state.
1858          */
1859         regs = to_intel_context(request->ctx, engine)->lrc_reg_state;
1860         if (engine->default_state) {
1861                 void *defaults;
1862
1863                 defaults = i915_gem_object_pin_map(engine->default_state,
1864                                                    I915_MAP_WB);
1865                 if (!IS_ERR(defaults)) {
1866                         memcpy(regs, /* skip restoring the vanilla PPHWSP */
1867                                defaults + LRC_STATE_PN * PAGE_SIZE,
1868                                engine->context_size - PAGE_SIZE);
1869                         i915_gem_object_unpin_map(engine->default_state);
1870                 }
1871         }
1872         execlists_init_reg_state(regs, request->ctx, engine, request->ring);
1873
1874         /* Move the RING_HEAD onto the breadcrumb, past the hanging batch */
1875         regs[CTX_RING_BUFFER_START + 1] = i915_ggtt_offset(request->ring->vma);
1876         regs[CTX_RING_HEAD + 1] = request->postfix;
1877
1878         request->ring->head = request->postfix;
1879         intel_ring_update_space(request->ring);
1880
1881         /* Reset WaIdleLiteRestore:bdw,skl as well */
1882         unwind_wa_tail(request);
1883 }
1884
1885 static int intel_logical_ring_emit_pdps(struct i915_request *rq)
1886 {
1887         struct i915_hw_ppgtt *ppgtt = rq->ctx->ppgtt;
1888         struct intel_engine_cs *engine = rq->engine;
1889         const int num_lri_cmds = GEN8_3LVL_PDPES * 2;
1890         u32 *cs;
1891         int i;
1892
1893         cs = intel_ring_begin(rq, num_lri_cmds * 2 + 2);
1894         if (IS_ERR(cs))
1895                 return PTR_ERR(cs);
1896
1897         *cs++ = MI_LOAD_REGISTER_IMM(num_lri_cmds);
1898         for (i = GEN8_3LVL_PDPES - 1; i >= 0; i--) {
1899                 const dma_addr_t pd_daddr = i915_page_dir_dma_addr(ppgtt, i);
1900
1901                 *cs++ = i915_mmio_reg_offset(GEN8_RING_PDP_UDW(engine, i));
1902                 *cs++ = upper_32_bits(pd_daddr);
1903                 *cs++ = i915_mmio_reg_offset(GEN8_RING_PDP_LDW(engine, i));
1904                 *cs++ = lower_32_bits(pd_daddr);
1905         }
1906
1907         *cs++ = MI_NOOP;
1908         intel_ring_advance(rq, cs);
1909
1910         return 0;
1911 }
1912
1913 static int gen8_emit_bb_start(struct i915_request *rq,
1914                               u64 offset, u32 len,
1915                               const unsigned int flags)
1916 {
1917         u32 *cs;
1918         int ret;
1919
1920         /* Don't rely in hw updating PDPs, specially in lite-restore.
1921          * Ideally, we should set Force PD Restore in ctx descriptor,
1922          * but we can't. Force Restore would be a second option, but
1923          * it is unsafe in case of lite-restore (because the ctx is
1924          * not idle). PML4 is allocated during ppgtt init so this is
1925          * not needed in 48-bit.*/
1926         if (rq->ctx->ppgtt &&
1927             (intel_engine_flag(rq->engine) & rq->ctx->ppgtt->pd_dirty_rings) &&
1928             !i915_vm_is_48bit(&rq->ctx->ppgtt->base) &&
1929             !intel_vgpu_active(rq->i915)) {
1930                 ret = intel_logical_ring_emit_pdps(rq);
1931                 if (ret)
1932                         return ret;
1933
1934                 rq->ctx->ppgtt->pd_dirty_rings &= ~intel_engine_flag(rq->engine);
1935         }
1936
1937         cs = intel_ring_begin(rq, 4);
1938         if (IS_ERR(cs))
1939                 return PTR_ERR(cs);
1940
1941         /*
1942          * WaDisableCtxRestoreArbitration:bdw,chv
1943          *
1944          * We don't need to perform MI_ARB_ENABLE as often as we do (in
1945          * particular all the gen that do not need the w/a at all!), if we
1946          * took care to make sure that on every switch into this context
1947          * (both ordinary and for preemption) that arbitrartion was enabled
1948          * we would be fine. However, there doesn't seem to be a downside to
1949          * being paranoid and making sure it is set before each batch and
1950          * every context-switch.
1951          *
1952          * Note that if we fail to enable arbitration before the request
1953          * is complete, then we do not see the context-switch interrupt and
1954          * the engine hangs (with RING_HEAD == RING_TAIL).
1955          *
1956          * That satisfies both the GPGPU w/a and our heavy-handed paranoia.
1957          */
1958         *cs++ = MI_ARB_ON_OFF | MI_ARB_ENABLE;
1959
1960         /* FIXME(BDW): Address space and security selectors. */
1961         *cs++ = MI_BATCH_BUFFER_START_GEN8 |
1962                 (flags & I915_DISPATCH_SECURE ? 0 : BIT(8)) |
1963                 (flags & I915_DISPATCH_RS ? MI_BATCH_RESOURCE_STREAMER : 0);
1964         *cs++ = lower_32_bits(offset);
1965         *cs++ = upper_32_bits(offset);
1966         intel_ring_advance(rq, cs);
1967
1968         return 0;
1969 }
1970
1971 static void gen8_logical_ring_enable_irq(struct intel_engine_cs *engine)
1972 {
1973         struct drm_i915_private *dev_priv = engine->i915;
1974         I915_WRITE_IMR(engine,
1975                        ~(engine->irq_enable_mask | engine->irq_keep_mask));
1976         POSTING_READ_FW(RING_IMR(engine->mmio_base));
1977 }
1978
1979 static void gen8_logical_ring_disable_irq(struct intel_engine_cs *engine)
1980 {
1981         struct drm_i915_private *dev_priv = engine->i915;
1982         I915_WRITE_IMR(engine, ~engine->irq_keep_mask);
1983 }
1984
1985 static int gen8_emit_flush(struct i915_request *request, u32 mode)
1986 {
1987         u32 cmd, *cs;
1988
1989         cs = intel_ring_begin(request, 4);
1990         if (IS_ERR(cs))
1991                 return PTR_ERR(cs);
1992
1993         cmd = MI_FLUSH_DW + 1;
1994
1995         /* We always require a command barrier so that subsequent
1996          * commands, such as breadcrumb interrupts, are strictly ordered
1997          * wrt the contents of the write cache being flushed to memory
1998          * (and thus being coherent from the CPU).
1999          */
2000         cmd |= MI_FLUSH_DW_STORE_INDEX | MI_FLUSH_DW_OP_STOREDW;
2001
2002         if (mode & EMIT_INVALIDATE) {
2003                 cmd |= MI_INVALIDATE_TLB;
2004                 if (request->engine->id == VCS)
2005                         cmd |= MI_INVALIDATE_BSD;
2006         }
2007
2008         *cs++ = cmd;
2009         *cs++ = I915_GEM_HWS_SCRATCH_ADDR | MI_FLUSH_DW_USE_GTT;
2010         *cs++ = 0; /* upper addr */
2011         *cs++ = 0; /* value */
2012         intel_ring_advance(request, cs);
2013
2014         return 0;
2015 }
2016
2017 static int gen8_emit_flush_render(struct i915_request *request,
2018                                   u32 mode)
2019 {
2020         struct intel_engine_cs *engine = request->engine;
2021         u32 scratch_addr =
2022                 i915_ggtt_offset(engine->scratch) + 2 * CACHELINE_BYTES;
2023         bool vf_flush_wa = false, dc_flush_wa = false;
2024         u32 *cs, flags = 0;
2025         int len;
2026
2027         flags |= PIPE_CONTROL_CS_STALL;
2028
2029         if (mode & EMIT_FLUSH) {
2030                 flags |= PIPE_CONTROL_RENDER_TARGET_CACHE_FLUSH;
2031                 flags |= PIPE_CONTROL_DEPTH_CACHE_FLUSH;
2032                 flags |= PIPE_CONTROL_DC_FLUSH_ENABLE;
2033                 flags |= PIPE_CONTROL_FLUSH_ENABLE;
2034         }
2035
2036         if (mode & EMIT_INVALIDATE) {
2037                 flags |= PIPE_CONTROL_TLB_INVALIDATE;
2038                 flags |= PIPE_CONTROL_INSTRUCTION_CACHE_INVALIDATE;
2039                 flags |= PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE;
2040                 flags |= PIPE_CONTROL_VF_CACHE_INVALIDATE;
2041                 flags |= PIPE_CONTROL_CONST_CACHE_INVALIDATE;
2042                 flags |= PIPE_CONTROL_STATE_CACHE_INVALIDATE;
2043                 flags |= PIPE_CONTROL_QW_WRITE;
2044                 flags |= PIPE_CONTROL_GLOBAL_GTT_IVB;
2045
2046                 /*
2047                  * On GEN9: before VF_CACHE_INVALIDATE we need to emit a NULL
2048                  * pipe control.
2049                  */
2050                 if (IS_GEN9(request->i915))
2051                         vf_flush_wa = true;
2052
2053                 /* WaForGAMHang:kbl */
2054                 if (IS_KBL_REVID(request->i915, 0, KBL_REVID_B0))
2055                         dc_flush_wa = true;
2056         }
2057
2058         len = 6;
2059
2060         if (vf_flush_wa)
2061                 len += 6;
2062
2063         if (dc_flush_wa)
2064                 len += 12;
2065
2066         cs = intel_ring_begin(request, len);
2067         if (IS_ERR(cs))
2068                 return PTR_ERR(cs);
2069
2070         if (vf_flush_wa)
2071                 cs = gen8_emit_pipe_control(cs, 0, 0);
2072
2073         if (dc_flush_wa)
2074                 cs = gen8_emit_pipe_control(cs, PIPE_CONTROL_DC_FLUSH_ENABLE,
2075                                             0);
2076
2077         cs = gen8_emit_pipe_control(cs, flags, scratch_addr);
2078
2079         if (dc_flush_wa)
2080                 cs = gen8_emit_pipe_control(cs, PIPE_CONTROL_CS_STALL, 0);
2081
2082         intel_ring_advance(request, cs);
2083
2084         return 0;
2085 }
2086
2087 /*
2088  * Reserve space for 2 NOOPs at the end of each request to be
2089  * used as a workaround for not being allowed to do lite
2090  * restore with HEAD==TAIL (WaIdleLiteRestore).
2091  */
2092 static void gen8_emit_wa_tail(struct i915_request *request, u32 *cs)
2093 {
2094         /* Ensure there's always at least one preemption point per-request. */
2095         *cs++ = MI_ARB_CHECK;
2096         *cs++ = MI_NOOP;
2097         request->wa_tail = intel_ring_offset(request, cs);
2098 }
2099
2100 static void gen8_emit_breadcrumb(struct i915_request *request, u32 *cs)
2101 {
2102         /* w/a: bit 5 needs to be zero for MI_FLUSH_DW address. */
2103         BUILD_BUG_ON(I915_GEM_HWS_INDEX_ADDR & (1 << 5));
2104
2105         cs = gen8_emit_ggtt_write(cs, request->global_seqno,
2106                                   intel_hws_seqno_address(request->engine));
2107         *cs++ = MI_USER_INTERRUPT;
2108         *cs++ = MI_NOOP;
2109         request->tail = intel_ring_offset(request, cs);
2110         assert_ring_tail_valid(request->ring, request->tail);
2111
2112         gen8_emit_wa_tail(request, cs);
2113 }
2114 static const int gen8_emit_breadcrumb_sz = 6 + WA_TAIL_DWORDS;
2115
2116 static void gen8_emit_breadcrumb_rcs(struct i915_request *request, u32 *cs)
2117 {
2118         /* We're using qword write, seqno should be aligned to 8 bytes. */
2119         BUILD_BUG_ON(I915_GEM_HWS_INDEX & 1);
2120
2121         cs = gen8_emit_ggtt_write_rcs(cs, request->global_seqno,
2122                                       intel_hws_seqno_address(request->engine));
2123         *cs++ = MI_USER_INTERRUPT;
2124         *cs++ = MI_NOOP;
2125         request->tail = intel_ring_offset(request, cs);
2126         assert_ring_tail_valid(request->ring, request->tail);
2127
2128         gen8_emit_wa_tail(request, cs);
2129 }
2130 static const int gen8_emit_breadcrumb_rcs_sz = 8 + WA_TAIL_DWORDS;
2131
2132 static int gen8_init_rcs_context(struct i915_request *rq)
2133 {
2134         int ret;
2135
2136         ret = intel_ctx_workarounds_emit(rq);
2137         if (ret)
2138                 return ret;
2139
2140         ret = intel_rcs_context_init_mocs(rq);
2141         /*
2142          * Failing to program the MOCS is non-fatal.The system will not
2143          * run at peak performance. So generate an error and carry on.
2144          */
2145         if (ret)
2146                 DRM_ERROR("MOCS failed to program: expect performance issues.\n");
2147
2148         return i915_gem_render_state_emit(rq);
2149 }
2150
2151 /**
2152  * intel_logical_ring_cleanup() - deallocate the Engine Command Streamer
2153  * @engine: Engine Command Streamer.
2154  */
2155 void intel_logical_ring_cleanup(struct intel_engine_cs *engine)
2156 {
2157         struct drm_i915_private *dev_priv;
2158
2159         /*
2160          * Tasklet cannot be active at this point due intel_mark_active/idle
2161          * so this is just for documentation.
2162          */
2163         if (WARN_ON(test_bit(TASKLET_STATE_SCHED,
2164                              &engine->execlists.tasklet.state)))
2165                 tasklet_kill(&engine->execlists.tasklet);
2166
2167         dev_priv = engine->i915;
2168
2169         if (engine->buffer) {
2170                 WARN_ON((I915_READ_MODE(engine) & MODE_IDLE) == 0);
2171         }
2172
2173         if (engine->cleanup)
2174                 engine->cleanup(engine);
2175
2176         intel_engine_cleanup_common(engine);
2177
2178         lrc_destroy_wa_ctx(engine);
2179
2180         engine->i915 = NULL;
2181         dev_priv->engine[engine->id] = NULL;
2182         kfree(engine);
2183 }
2184
2185 static void execlists_set_default_submission(struct intel_engine_cs *engine)
2186 {
2187         engine->submit_request = execlists_submit_request;
2188         engine->cancel_requests = execlists_cancel_requests;
2189         engine->schedule = execlists_schedule;
2190         engine->execlists.tasklet.func = execlists_submission_tasklet;
2191
2192         engine->park = NULL;
2193         engine->unpark = NULL;
2194
2195         engine->flags |= I915_ENGINE_SUPPORTS_STATS;
2196         if (engine->i915->preempt_context)
2197                 engine->flags |= I915_ENGINE_HAS_PREEMPTION;
2198
2199         engine->i915->caps.scheduler =
2200                 I915_SCHEDULER_CAP_ENABLED |
2201                 I915_SCHEDULER_CAP_PRIORITY;
2202         if (intel_engine_has_preemption(engine))
2203                 engine->i915->caps.scheduler |= I915_SCHEDULER_CAP_PREEMPTION;
2204 }
2205
2206 static void
2207 logical_ring_default_vfuncs(struct intel_engine_cs *engine)
2208 {
2209         /* Default vfuncs which can be overriden by each engine. */
2210         engine->init_hw = gen8_init_common_ring;
2211         engine->reset_hw = reset_common_ring;
2212
2213         engine->context_pin = execlists_context_pin;
2214         engine->context_unpin = execlists_context_unpin;
2215
2216         engine->request_alloc = execlists_request_alloc;
2217
2218         engine->emit_flush = gen8_emit_flush;
2219         engine->emit_breadcrumb = gen8_emit_breadcrumb;
2220         engine->emit_breadcrumb_sz = gen8_emit_breadcrumb_sz;
2221
2222         engine->set_default_submission = execlists_set_default_submission;
2223
2224         if (INTEL_GEN(engine->i915) < 11) {
2225                 engine->irq_enable = gen8_logical_ring_enable_irq;
2226                 engine->irq_disable = gen8_logical_ring_disable_irq;
2227         } else {
2228                 /*
2229                  * TODO: On Gen11 interrupt masks need to be clear
2230                  * to allow C6 entry. Keep interrupts enabled at
2231                  * and take the hit of generating extra interrupts
2232                  * until a more refined solution exists.
2233                  */
2234         }
2235         engine->emit_bb_start = gen8_emit_bb_start;
2236 }
2237
2238 static inline void
2239 logical_ring_default_irqs(struct intel_engine_cs *engine)
2240 {
2241         unsigned int shift = 0;
2242
2243         if (INTEL_GEN(engine->i915) < 11) {
2244                 const u8 irq_shifts[] = {
2245                         [RCS]  = GEN8_RCS_IRQ_SHIFT,
2246                         [BCS]  = GEN8_BCS_IRQ_SHIFT,
2247                         [VCS]  = GEN8_VCS1_IRQ_SHIFT,
2248                         [VCS2] = GEN8_VCS2_IRQ_SHIFT,
2249                         [VECS] = GEN8_VECS_IRQ_SHIFT,
2250                 };
2251
2252                 shift = irq_shifts[engine->id];
2253         }
2254
2255         engine->irq_enable_mask = GT_RENDER_USER_INTERRUPT << shift;
2256         engine->irq_keep_mask = GT_CONTEXT_SWITCH_INTERRUPT << shift;
2257 }
2258
2259 static void
2260 logical_ring_setup(struct intel_engine_cs *engine)
2261 {
2262         struct drm_i915_private *dev_priv = engine->i915;
2263         enum forcewake_domains fw_domains;
2264
2265         intel_engine_setup_common(engine);
2266
2267         /* Intentionally left blank. */
2268         engine->buffer = NULL;
2269
2270         fw_domains = intel_uncore_forcewake_for_reg(dev_priv,
2271                                                     RING_ELSP(engine),
2272                                                     FW_REG_WRITE);
2273
2274         fw_domains |= intel_uncore_forcewake_for_reg(dev_priv,
2275                                                      RING_CONTEXT_STATUS_PTR(engine),
2276                                                      FW_REG_READ | FW_REG_WRITE);
2277
2278         fw_domains |= intel_uncore_forcewake_for_reg(dev_priv,
2279                                                      RING_CONTEXT_STATUS_BUF_BASE(engine),
2280                                                      FW_REG_READ);
2281
2282         engine->execlists.fw_domains = fw_domains;
2283
2284         tasklet_init(&engine->execlists.tasklet,
2285                      execlists_submission_tasklet, (unsigned long)engine);
2286
2287         logical_ring_default_vfuncs(engine);
2288         logical_ring_default_irqs(engine);
2289 }
2290
2291 static int logical_ring_init(struct intel_engine_cs *engine)
2292 {
2293         int ret;
2294
2295         ret = intel_engine_init_common(engine);
2296         if (ret)
2297                 goto error;
2298
2299         if (HAS_LOGICAL_RING_ELSQ(engine->i915)) {
2300                 engine->execlists.submit_reg = engine->i915->regs +
2301                         i915_mmio_reg_offset(RING_EXECLIST_SQ_CONTENTS(engine));
2302                 engine->execlists.ctrl_reg = engine->i915->regs +
2303                         i915_mmio_reg_offset(RING_EXECLIST_CONTROL(engine));
2304         } else {
2305                 engine->execlists.submit_reg = engine->i915->regs +
2306                         i915_mmio_reg_offset(RING_ELSP(engine));
2307         }
2308
2309         engine->execlists.preempt_complete_status = ~0u;
2310         if (engine->i915->preempt_context) {
2311                 struct intel_context *ce =
2312                         to_intel_context(engine->i915->preempt_context, engine);
2313
2314                 engine->execlists.preempt_complete_status =
2315                         upper_32_bits(ce->lrc_desc);
2316         }
2317
2318         return 0;
2319
2320 error:
2321         intel_logical_ring_cleanup(engine);
2322         return ret;
2323 }
2324
2325 int logical_render_ring_init(struct intel_engine_cs *engine)
2326 {
2327         struct drm_i915_private *dev_priv = engine->i915;
2328         int ret;
2329
2330         logical_ring_setup(engine);
2331
2332         if (HAS_L3_DPF(dev_priv))
2333                 engine->irq_keep_mask |= GT_RENDER_L3_PARITY_ERROR_INTERRUPT;
2334
2335         /* Override some for render ring. */
2336         if (INTEL_GEN(dev_priv) >= 9)
2337                 engine->init_hw = gen9_init_render_ring;
2338         else
2339                 engine->init_hw = gen8_init_render_ring;
2340         engine->init_context = gen8_init_rcs_context;
2341         engine->emit_flush = gen8_emit_flush_render;
2342         engine->emit_breadcrumb = gen8_emit_breadcrumb_rcs;
2343         engine->emit_breadcrumb_sz = gen8_emit_breadcrumb_rcs_sz;
2344
2345         ret = intel_engine_create_scratch(engine, PAGE_SIZE);
2346         if (ret)
2347                 return ret;
2348
2349         ret = intel_init_workaround_bb(engine);
2350         if (ret) {
2351                 /*
2352                  * We continue even if we fail to initialize WA batch
2353                  * because we only expect rare glitches but nothing
2354                  * critical to prevent us from using GPU
2355                  */
2356                 DRM_ERROR("WA batch buffer initialization failed: %d\n",
2357                           ret);
2358         }
2359
2360         return logical_ring_init(engine);
2361 }
2362
2363 int logical_xcs_ring_init(struct intel_engine_cs *engine)
2364 {
2365         logical_ring_setup(engine);
2366
2367         return logical_ring_init(engine);
2368 }
2369
2370 static u32
2371 make_rpcs(struct drm_i915_private *dev_priv)
2372 {
2373         u32 rpcs = 0;
2374
2375         /*
2376          * No explicit RPCS request is needed to ensure full
2377          * slice/subslice/EU enablement prior to Gen9.
2378         */
2379         if (INTEL_GEN(dev_priv) < 9)
2380                 return 0;
2381
2382         /*
2383          * Starting in Gen9, render power gating can leave
2384          * slice/subslice/EU in a partially enabled state. We
2385          * must make an explicit request through RPCS for full
2386          * enablement.
2387         */
2388         if (INTEL_INFO(dev_priv)->sseu.has_slice_pg) {
2389                 rpcs |= GEN8_RPCS_S_CNT_ENABLE;
2390                 rpcs |= hweight8(INTEL_INFO(dev_priv)->sseu.slice_mask) <<
2391                         GEN8_RPCS_S_CNT_SHIFT;
2392                 rpcs |= GEN8_RPCS_ENABLE;
2393         }
2394
2395         if (INTEL_INFO(dev_priv)->sseu.has_subslice_pg) {
2396                 rpcs |= GEN8_RPCS_SS_CNT_ENABLE;
2397                 rpcs |= hweight8(INTEL_INFO(dev_priv)->sseu.subslice_mask[0]) <<
2398                         GEN8_RPCS_SS_CNT_SHIFT;
2399                 rpcs |= GEN8_RPCS_ENABLE;
2400         }
2401
2402         if (INTEL_INFO(dev_priv)->sseu.has_eu_pg) {
2403                 rpcs |= INTEL_INFO(dev_priv)->sseu.eu_per_subslice <<
2404                         GEN8_RPCS_EU_MIN_SHIFT;
2405                 rpcs |= INTEL_INFO(dev_priv)->sseu.eu_per_subslice <<
2406                         GEN8_RPCS_EU_MAX_SHIFT;
2407                 rpcs |= GEN8_RPCS_ENABLE;
2408         }
2409
2410         return rpcs;
2411 }
2412
2413 static u32 intel_lr_indirect_ctx_offset(struct intel_engine_cs *engine)
2414 {
2415         u32 indirect_ctx_offset;
2416
2417         switch (INTEL_GEN(engine->i915)) {
2418         default:
2419                 MISSING_CASE(INTEL_GEN(engine->i915));
2420                 /* fall through */
2421         case 11:
2422                 indirect_ctx_offset =
2423                         GEN11_CTX_RCS_INDIRECT_CTX_OFFSET_DEFAULT;
2424                 break;
2425         case 10:
2426                 indirect_ctx_offset =
2427                         GEN10_CTX_RCS_INDIRECT_CTX_OFFSET_DEFAULT;
2428                 break;
2429         case 9:
2430                 indirect_ctx_offset =
2431                         GEN9_CTX_RCS_INDIRECT_CTX_OFFSET_DEFAULT;
2432                 break;
2433         case 8:
2434                 indirect_ctx_offset =
2435                         GEN8_CTX_RCS_INDIRECT_CTX_OFFSET_DEFAULT;
2436                 break;
2437         }
2438
2439         return indirect_ctx_offset;
2440 }
2441
2442 static void execlists_init_reg_state(u32 *regs,
2443                                      struct i915_gem_context *ctx,
2444                                      struct intel_engine_cs *engine,
2445                                      struct intel_ring *ring)
2446 {
2447         struct drm_i915_private *dev_priv = engine->i915;
2448         struct i915_hw_ppgtt *ppgtt = ctx->ppgtt ?: dev_priv->mm.aliasing_ppgtt;
2449         u32 base = engine->mmio_base;
2450         bool rcs = engine->id == RCS;
2451
2452         /* A context is actually a big batch buffer with several
2453          * MI_LOAD_REGISTER_IMM commands followed by (reg, value) pairs. The
2454          * values we are setting here are only for the first context restore:
2455          * on a subsequent save, the GPU will recreate this batchbuffer with new
2456          * values (including all the missing MI_LOAD_REGISTER_IMM commands that
2457          * we are not initializing here).
2458          */
2459         regs[CTX_LRI_HEADER_0] = MI_LOAD_REGISTER_IMM(rcs ? 14 : 11) |
2460                                  MI_LRI_FORCE_POSTED;
2461
2462         CTX_REG(regs, CTX_CONTEXT_CONTROL, RING_CONTEXT_CONTROL(engine),
2463                 _MASKED_BIT_DISABLE(CTX_CTRL_ENGINE_CTX_RESTORE_INHIBIT |
2464                                     CTX_CTRL_ENGINE_CTX_SAVE_INHIBIT) |
2465                 _MASKED_BIT_ENABLE(CTX_CTRL_INHIBIT_SYN_CTX_SWITCH |
2466                                    (HAS_RESOURCE_STREAMER(dev_priv) ?
2467                                    CTX_CTRL_RS_CTX_ENABLE : 0)));
2468         CTX_REG(regs, CTX_RING_HEAD, RING_HEAD(base), 0);
2469         CTX_REG(regs, CTX_RING_TAIL, RING_TAIL(base), 0);
2470         CTX_REG(regs, CTX_RING_BUFFER_START, RING_START(base), 0);
2471         CTX_REG(regs, CTX_RING_BUFFER_CONTROL, RING_CTL(base),
2472                 RING_CTL_SIZE(ring->size) | RING_VALID);
2473         CTX_REG(regs, CTX_BB_HEAD_U, RING_BBADDR_UDW(base), 0);
2474         CTX_REG(regs, CTX_BB_HEAD_L, RING_BBADDR(base), 0);
2475         CTX_REG(regs, CTX_BB_STATE, RING_BBSTATE(base), RING_BB_PPGTT);
2476         CTX_REG(regs, CTX_SECOND_BB_HEAD_U, RING_SBBADDR_UDW(base), 0);
2477         CTX_REG(regs, CTX_SECOND_BB_HEAD_L, RING_SBBADDR(base), 0);
2478         CTX_REG(regs, CTX_SECOND_BB_STATE, RING_SBBSTATE(base), 0);
2479         if (rcs) {
2480                 struct i915_ctx_workarounds *wa_ctx = &engine->wa_ctx;
2481
2482                 CTX_REG(regs, CTX_RCS_INDIRECT_CTX, RING_INDIRECT_CTX(base), 0);
2483                 CTX_REG(regs, CTX_RCS_INDIRECT_CTX_OFFSET,
2484                         RING_INDIRECT_CTX_OFFSET(base), 0);
2485                 if (wa_ctx->indirect_ctx.size) {
2486                         u32 ggtt_offset = i915_ggtt_offset(wa_ctx->vma);
2487
2488                         regs[CTX_RCS_INDIRECT_CTX + 1] =
2489                                 (ggtt_offset + wa_ctx->indirect_ctx.offset) |
2490                                 (wa_ctx->indirect_ctx.size / CACHELINE_BYTES);
2491
2492                         regs[CTX_RCS_INDIRECT_CTX_OFFSET + 1] =
2493                                 intel_lr_indirect_ctx_offset(engine) << 6;
2494                 }
2495
2496                 CTX_REG(regs, CTX_BB_PER_CTX_PTR, RING_BB_PER_CTX_PTR(base), 0);
2497                 if (wa_ctx->per_ctx.size) {
2498                         u32 ggtt_offset = i915_ggtt_offset(wa_ctx->vma);
2499
2500                         regs[CTX_BB_PER_CTX_PTR + 1] =
2501                                 (ggtt_offset + wa_ctx->per_ctx.offset) | 0x01;
2502                 }
2503         }
2504
2505         regs[CTX_LRI_HEADER_1] = MI_LOAD_REGISTER_IMM(9) | MI_LRI_FORCE_POSTED;
2506
2507         CTX_REG(regs, CTX_CTX_TIMESTAMP, RING_CTX_TIMESTAMP(base), 0);
2508         /* PDP values well be assigned later if needed */
2509         CTX_REG(regs, CTX_PDP3_UDW, GEN8_RING_PDP_UDW(engine, 3), 0);
2510         CTX_REG(regs, CTX_PDP3_LDW, GEN8_RING_PDP_LDW(engine, 3), 0);
2511         CTX_REG(regs, CTX_PDP2_UDW, GEN8_RING_PDP_UDW(engine, 2), 0);
2512         CTX_REG(regs, CTX_PDP2_LDW, GEN8_RING_PDP_LDW(engine, 2), 0);
2513         CTX_REG(regs, CTX_PDP1_UDW, GEN8_RING_PDP_UDW(engine, 1), 0);
2514         CTX_REG(regs, CTX_PDP1_LDW, GEN8_RING_PDP_LDW(engine, 1), 0);
2515         CTX_REG(regs, CTX_PDP0_UDW, GEN8_RING_PDP_UDW(engine, 0), 0);
2516         CTX_REG(regs, CTX_PDP0_LDW, GEN8_RING_PDP_LDW(engine, 0), 0);
2517
2518         if (ppgtt && i915_vm_is_48bit(&ppgtt->base)) {
2519                 /* 64b PPGTT (48bit canonical)
2520                  * PDP0_DESCRIPTOR contains the base address to PML4 and
2521                  * other PDP Descriptors are ignored.
2522                  */
2523                 ASSIGN_CTX_PML4(ppgtt, regs);
2524         }
2525
2526         if (rcs) {
2527                 regs[CTX_LRI_HEADER_2] = MI_LOAD_REGISTER_IMM(1);
2528                 CTX_REG(regs, CTX_R_PWR_CLK_STATE, GEN8_R_PWR_CLK_STATE,
2529                         make_rpcs(dev_priv));
2530
2531                 i915_oa_init_reg_state(engine, ctx, regs);
2532         }
2533 }
2534
2535 static int
2536 populate_lr_context(struct i915_gem_context *ctx,
2537                     struct drm_i915_gem_object *ctx_obj,
2538                     struct intel_engine_cs *engine,
2539                     struct intel_ring *ring)
2540 {
2541         void *vaddr;
2542         u32 *regs;
2543         int ret;
2544
2545         ret = i915_gem_object_set_to_cpu_domain(ctx_obj, true);
2546         if (ret) {
2547                 DRM_DEBUG_DRIVER("Could not set to CPU domain\n");
2548                 return ret;
2549         }
2550
2551         vaddr = i915_gem_object_pin_map(ctx_obj, I915_MAP_WB);
2552         if (IS_ERR(vaddr)) {
2553                 ret = PTR_ERR(vaddr);
2554                 DRM_DEBUG_DRIVER("Could not map object pages! (%d)\n", ret);
2555                 return ret;
2556         }
2557         ctx_obj->mm.dirty = true;
2558
2559         if (engine->default_state) {
2560                 /*
2561                  * We only want to copy over the template context state;
2562                  * skipping over the headers reserved for GuC communication,
2563                  * leaving those as zero.
2564                  */
2565                 const unsigned long start = LRC_HEADER_PAGES * PAGE_SIZE;
2566                 void *defaults;
2567
2568                 defaults = i915_gem_object_pin_map(engine->default_state,
2569                                                    I915_MAP_WB);
2570                 if (IS_ERR(defaults))
2571                         return PTR_ERR(defaults);
2572
2573                 memcpy(vaddr + start, defaults + start, engine->context_size);
2574                 i915_gem_object_unpin_map(engine->default_state);
2575         }
2576
2577         /* The second page of the context object contains some fields which must
2578          * be set up prior to the first execution. */
2579         regs = vaddr + LRC_STATE_PN * PAGE_SIZE;
2580         execlists_init_reg_state(regs, ctx, engine, ring);
2581         if (!engine->default_state)
2582                 regs[CTX_CONTEXT_CONTROL + 1] |=
2583                         _MASKED_BIT_ENABLE(CTX_CTRL_ENGINE_CTX_RESTORE_INHIBIT);
2584         if (ctx == ctx->i915->preempt_context && INTEL_GEN(engine->i915) < 11)
2585                 regs[CTX_CONTEXT_CONTROL + 1] |=
2586                         _MASKED_BIT_ENABLE(CTX_CTRL_ENGINE_CTX_RESTORE_INHIBIT |
2587                                            CTX_CTRL_ENGINE_CTX_SAVE_INHIBIT);
2588
2589         i915_gem_object_unpin_map(ctx_obj);
2590
2591         return 0;
2592 }
2593
2594 static int execlists_context_deferred_alloc(struct i915_gem_context *ctx,
2595                                             struct intel_engine_cs *engine)
2596 {
2597         struct drm_i915_gem_object *ctx_obj;
2598         struct intel_context *ce = to_intel_context(ctx, engine);
2599         struct i915_vma *vma;
2600         uint32_t context_size;
2601         struct intel_ring *ring;
2602         int ret;
2603
2604         if (ce->state)
2605                 return 0;
2606
2607         context_size = round_up(engine->context_size, I915_GTT_PAGE_SIZE);
2608
2609         /*
2610          * Before the actual start of the context image, we insert a few pages
2611          * for our own use and for sharing with the GuC.
2612          */
2613         context_size += LRC_HEADER_PAGES * PAGE_SIZE;
2614
2615         ctx_obj = i915_gem_object_create(ctx->i915, context_size);
2616         if (IS_ERR(ctx_obj)) {
2617                 DRM_DEBUG_DRIVER("Alloc LRC backing obj failed.\n");
2618                 return PTR_ERR(ctx_obj);
2619         }
2620
2621         vma = i915_vma_instance(ctx_obj, &ctx->i915->ggtt.base, NULL);
2622         if (IS_ERR(vma)) {
2623                 ret = PTR_ERR(vma);
2624                 goto error_deref_obj;
2625         }
2626
2627         ring = intel_engine_create_ring(engine, ctx->ring_size);
2628         if (IS_ERR(ring)) {
2629                 ret = PTR_ERR(ring);
2630                 goto error_deref_obj;
2631         }
2632
2633         ret = populate_lr_context(ctx, ctx_obj, engine, ring);
2634         if (ret) {
2635                 DRM_DEBUG_DRIVER("Failed to populate LRC: %d\n", ret);
2636                 goto error_ring_free;
2637         }
2638
2639         ce->ring = ring;
2640         ce->state = vma;
2641
2642         return 0;
2643
2644 error_ring_free:
2645         intel_ring_free(ring);
2646 error_deref_obj:
2647         i915_gem_object_put(ctx_obj);
2648         return ret;
2649 }
2650
2651 void intel_lr_context_resume(struct drm_i915_private *dev_priv)
2652 {
2653         struct intel_engine_cs *engine;
2654         struct i915_gem_context *ctx;
2655         enum intel_engine_id id;
2656
2657         /* Because we emit WA_TAIL_DWORDS there may be a disparity
2658          * between our bookkeeping in ce->ring->head and ce->ring->tail and
2659          * that stored in context. As we only write new commands from
2660          * ce->ring->tail onwards, everything before that is junk. If the GPU
2661          * starts reading from its RING_HEAD from the context, it may try to
2662          * execute that junk and die.
2663          *
2664          * So to avoid that we reset the context images upon resume. For
2665          * simplicity, we just zero everything out.
2666          */
2667         list_for_each_entry(ctx, &dev_priv->contexts.list, link) {
2668                 for_each_engine(engine, dev_priv, id) {
2669                         struct intel_context *ce =
2670                                 to_intel_context(ctx, engine);
2671                         u32 *reg;
2672
2673                         if (!ce->state)
2674                                 continue;
2675
2676                         reg = i915_gem_object_pin_map(ce->state->obj,
2677                                                       I915_MAP_WB);
2678                         if (WARN_ON(IS_ERR(reg)))
2679                                 continue;
2680
2681                         reg += LRC_STATE_PN * PAGE_SIZE / sizeof(*reg);
2682                         reg[CTX_RING_HEAD+1] = 0;
2683                         reg[CTX_RING_TAIL+1] = 0;
2684
2685                         ce->state->obj->mm.dirty = true;
2686                         i915_gem_object_unpin_map(ce->state->obj);
2687
2688                         intel_ring_reset(ce->ring, 0);
2689                 }
2690         }
2691 }
2692
2693 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
2694 #include "selftests/intel_lrc.c"
2695 #endif