037e94c5ab427c9d4d807bb64b987003d8f82068
[cascardo/linux.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
135 #include <drm/drmP.h>
136 #include <drm/i915_drm.h>
137 #include "i915_drv.h"
138
139 #define GEN9_LR_CONTEXT_RENDER_SIZE (22 * PAGE_SIZE)
140 #define GEN8_LR_CONTEXT_RENDER_SIZE (20 * PAGE_SIZE)
141 #define GEN8_LR_CONTEXT_OTHER_SIZE (2 * PAGE_SIZE)
142
143 #define RING_EXECLIST_QFULL             (1 << 0x2)
144 #define RING_EXECLIST1_VALID            (1 << 0x3)
145 #define RING_EXECLIST0_VALID            (1 << 0x4)
146 #define RING_EXECLIST_ACTIVE_STATUS     (3 << 0xE)
147 #define RING_EXECLIST1_ACTIVE           (1 << 0x11)
148 #define RING_EXECLIST0_ACTIVE           (1 << 0x12)
149
150 #define GEN8_CTX_STATUS_IDLE_ACTIVE     (1 << 0)
151 #define GEN8_CTX_STATUS_PREEMPTED       (1 << 1)
152 #define GEN8_CTX_STATUS_ELEMENT_SWITCH  (1 << 2)
153 #define GEN8_CTX_STATUS_ACTIVE_IDLE     (1 << 3)
154 #define GEN8_CTX_STATUS_COMPLETE        (1 << 4)
155 #define GEN8_CTX_STATUS_LITE_RESTORE    (1 << 15)
156
157 #define CTX_LRI_HEADER_0                0x01
158 #define CTX_CONTEXT_CONTROL             0x02
159 #define CTX_RING_HEAD                   0x04
160 #define CTX_RING_TAIL                   0x06
161 #define CTX_RING_BUFFER_START           0x08
162 #define CTX_RING_BUFFER_CONTROL         0x0a
163 #define CTX_BB_HEAD_U                   0x0c
164 #define CTX_BB_HEAD_L                   0x0e
165 #define CTX_BB_STATE                    0x10
166 #define CTX_SECOND_BB_HEAD_U            0x12
167 #define CTX_SECOND_BB_HEAD_L            0x14
168 #define CTX_SECOND_BB_STATE             0x16
169 #define CTX_BB_PER_CTX_PTR              0x18
170 #define CTX_RCS_INDIRECT_CTX            0x1a
171 #define CTX_RCS_INDIRECT_CTX_OFFSET     0x1c
172 #define CTX_LRI_HEADER_1                0x21
173 #define CTX_CTX_TIMESTAMP               0x22
174 #define CTX_PDP3_UDW                    0x24
175 #define CTX_PDP3_LDW                    0x26
176 #define CTX_PDP2_UDW                    0x28
177 #define CTX_PDP2_LDW                    0x2a
178 #define CTX_PDP1_UDW                    0x2c
179 #define CTX_PDP1_LDW                    0x2e
180 #define CTX_PDP0_UDW                    0x30
181 #define CTX_PDP0_LDW                    0x32
182 #define CTX_LRI_HEADER_2                0x41
183 #define CTX_R_PWR_CLK_STATE             0x42
184 #define CTX_GPGPU_CSR_BASE_ADDRESS      0x44
185
186 #define GEN8_CTX_VALID (1<<0)
187 #define GEN8_CTX_FORCE_PD_RESTORE (1<<1)
188 #define GEN8_CTX_FORCE_RESTORE (1<<2)
189 #define GEN8_CTX_L3LLC_COHERENT (1<<5)
190 #define GEN8_CTX_PRIVILEGE (1<<8)
191
192 #define ASSIGN_CTX_PDP(ppgtt, reg_state, n) { \
193         const u64 _addr = test_bit(n, ppgtt->pdp.used_pdpes) ? \
194                 ppgtt->pdp.page_directory[n]->daddr : \
195                 ppgtt->scratch_pd->daddr; \
196         reg_state[CTX_PDP ## n ## _UDW+1] = upper_32_bits(_addr); \
197         reg_state[CTX_PDP ## n ## _LDW+1] = lower_32_bits(_addr); \
198 }
199
200 enum {
201         ADVANCED_CONTEXT = 0,
202         LEGACY_CONTEXT,
203         ADVANCED_AD_CONTEXT,
204         LEGACY_64B_CONTEXT
205 };
206 #define GEN8_CTX_MODE_SHIFT 3
207 enum {
208         FAULT_AND_HANG = 0,
209         FAULT_AND_HALT, /* Debug only */
210         FAULT_AND_STREAM,
211         FAULT_AND_CONTINUE /* Unsupported */
212 };
213 #define GEN8_CTX_ID_SHIFT 32
214
215 static int intel_lr_context_pin(struct intel_engine_cs *ring,
216                 struct intel_context *ctx);
217
218 /**
219  * intel_sanitize_enable_execlists() - sanitize i915.enable_execlists
220  * @dev: DRM device.
221  * @enable_execlists: value of i915.enable_execlists module parameter.
222  *
223  * Only certain platforms support Execlists (the prerequisites being
224  * support for Logical Ring Contexts and Aliasing PPGTT or better).
225  *
226  * Return: 1 if Execlists is supported and has to be enabled.
227  */
228 int intel_sanitize_enable_execlists(struct drm_device *dev, int enable_execlists)
229 {
230         WARN_ON(i915.enable_ppgtt == -1);
231
232         if (INTEL_INFO(dev)->gen >= 9)
233                 return 1;
234
235         if (enable_execlists == 0)
236                 return 0;
237
238         if (HAS_LOGICAL_RING_CONTEXTS(dev) && USES_PPGTT(dev) &&
239             i915.use_mmio_flip >= 0)
240                 return 1;
241
242         return 0;
243 }
244
245 /**
246  * intel_execlists_ctx_id() - get the Execlists Context ID
247  * @ctx_obj: Logical Ring Context backing object.
248  *
249  * Do not confuse with ctx->id! Unfortunately we have a name overload
250  * here: the old context ID we pass to userspace as a handler so that
251  * they can refer to a context, and the new context ID we pass to the
252  * ELSP so that the GPU can inform us of the context status via
253  * interrupts.
254  *
255  * Return: 20-bits globally unique context ID.
256  */
257 u32 intel_execlists_ctx_id(struct drm_i915_gem_object *ctx_obj)
258 {
259         u32 lrca = i915_gem_obj_ggtt_offset(ctx_obj);
260
261         /* LRCA is required to be 4K aligned so the more significant 20 bits
262          * are globally unique */
263         return lrca >> 12;
264 }
265
266 static uint64_t execlists_ctx_descriptor(struct intel_engine_cs *ring,
267                                          struct drm_i915_gem_object *ctx_obj)
268 {
269         struct drm_device *dev = ring->dev;
270         uint64_t desc;
271         uint64_t lrca = i915_gem_obj_ggtt_offset(ctx_obj);
272
273         WARN_ON(lrca & 0xFFFFFFFF00000FFFULL);
274
275         desc = GEN8_CTX_VALID;
276         desc |= LEGACY_CONTEXT << GEN8_CTX_MODE_SHIFT;
277         if (IS_GEN8(ctx_obj->base.dev))
278                 desc |= GEN8_CTX_L3LLC_COHERENT;
279         desc |= GEN8_CTX_PRIVILEGE;
280         desc |= lrca;
281         desc |= (u64)intel_execlists_ctx_id(ctx_obj) << GEN8_CTX_ID_SHIFT;
282
283         /* TODO: WaDisableLiteRestore when we start using semaphore
284          * signalling between Command Streamers */
285         /* desc |= GEN8_CTX_FORCE_RESTORE; */
286
287         /* WaEnableForceRestoreInCtxtDescForVCS:skl */
288         if (IS_GEN9(dev) &&
289             INTEL_REVID(dev) <= SKL_REVID_B0 &&
290             (ring->id == BCS || ring->id == VCS ||
291             ring->id == VECS || ring->id == VCS2))
292                 desc |= GEN8_CTX_FORCE_RESTORE;
293
294         return desc;
295 }
296
297 static void execlists_elsp_write(struct intel_engine_cs *ring,
298                                  struct drm_i915_gem_object *ctx_obj0,
299                                  struct drm_i915_gem_object *ctx_obj1)
300 {
301         struct drm_device *dev = ring->dev;
302         struct drm_i915_private *dev_priv = dev->dev_private;
303         uint64_t temp = 0;
304         uint32_t desc[4];
305
306         /* XXX: You must always write both descriptors in the order below. */
307         if (ctx_obj1)
308                 temp = execlists_ctx_descriptor(ring, ctx_obj1);
309         else
310                 temp = 0;
311         desc[1] = (u32)(temp >> 32);
312         desc[0] = (u32)temp;
313
314         temp = execlists_ctx_descriptor(ring, ctx_obj0);
315         desc[3] = (u32)(temp >> 32);
316         desc[2] = (u32)temp;
317
318         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
319         I915_WRITE(RING_ELSP(ring), desc[1]);
320         I915_WRITE(RING_ELSP(ring), desc[0]);
321         I915_WRITE(RING_ELSP(ring), desc[3]);
322
323         /* The context is automatically loaded after the following */
324         I915_WRITE(RING_ELSP(ring), desc[2]);
325
326         /* ELSP is a wo register, so use another nearby reg for posting instead */
327         POSTING_READ(RING_EXECLIST_STATUS(ring));
328         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
329 }
330
331 static int execlists_update_context(struct drm_i915_gem_object *ctx_obj,
332                                     struct drm_i915_gem_object *ring_obj,
333                                     struct i915_hw_ppgtt *ppgtt,
334                                     u32 tail)
335 {
336         struct page *page;
337         uint32_t *reg_state;
338
339         page = i915_gem_object_get_page(ctx_obj, 1);
340         reg_state = kmap_atomic(page);
341
342         reg_state[CTX_RING_TAIL+1] = tail;
343         reg_state[CTX_RING_BUFFER_START+1] = i915_gem_obj_ggtt_offset(ring_obj);
344
345         /* True PPGTT with dynamic page allocation: update PDP registers and
346          * point the unallocated PDPs to the scratch page
347          */
348         if (ppgtt) {
349                 ASSIGN_CTX_PDP(ppgtt, reg_state, 3);
350                 ASSIGN_CTX_PDP(ppgtt, reg_state, 2);
351                 ASSIGN_CTX_PDP(ppgtt, reg_state, 1);
352                 ASSIGN_CTX_PDP(ppgtt, reg_state, 0);
353         }
354
355         kunmap_atomic(reg_state);
356
357         return 0;
358 }
359
360 static void execlists_submit_contexts(struct intel_engine_cs *ring,
361                                       struct intel_context *to0, u32 tail0,
362                                       struct intel_context *to1, u32 tail1)
363 {
364         struct drm_i915_gem_object *ctx_obj0 = to0->engine[ring->id].state;
365         struct intel_ringbuffer *ringbuf0 = to0->engine[ring->id].ringbuf;
366         struct drm_i915_gem_object *ctx_obj1 = NULL;
367         struct intel_ringbuffer *ringbuf1 = NULL;
368
369         BUG_ON(!ctx_obj0);
370         WARN_ON(!i915_gem_obj_is_pinned(ctx_obj0));
371         WARN_ON(!i915_gem_obj_is_pinned(ringbuf0->obj));
372
373         execlists_update_context(ctx_obj0, ringbuf0->obj, to0->ppgtt, tail0);
374
375         if (to1) {
376                 ringbuf1 = to1->engine[ring->id].ringbuf;
377                 ctx_obj1 = to1->engine[ring->id].state;
378                 BUG_ON(!ctx_obj1);
379                 WARN_ON(!i915_gem_obj_is_pinned(ctx_obj1));
380                 WARN_ON(!i915_gem_obj_is_pinned(ringbuf1->obj));
381
382                 execlists_update_context(ctx_obj1, ringbuf1->obj, to1->ppgtt, tail1);
383         }
384
385         execlists_elsp_write(ring, ctx_obj0, ctx_obj1);
386 }
387
388 static void execlists_context_unqueue(struct intel_engine_cs *ring)
389 {
390         struct drm_i915_gem_request *req0 = NULL, *req1 = NULL;
391         struct drm_i915_gem_request *cursor = NULL, *tmp = NULL;
392
393         assert_spin_locked(&ring->execlist_lock);
394
395         if (list_empty(&ring->execlist_queue))
396                 return;
397
398         /* Try to read in pairs */
399         list_for_each_entry_safe(cursor, tmp, &ring->execlist_queue,
400                                  execlist_link) {
401                 if (!req0) {
402                         req0 = cursor;
403                 } else if (req0->ctx == cursor->ctx) {
404                         /* Same ctx: ignore first request, as second request
405                          * will update tail past first request's workload */
406                         cursor->elsp_submitted = req0->elsp_submitted;
407                         list_del(&req0->execlist_link);
408                         list_add_tail(&req0->execlist_link,
409                                 &ring->execlist_retired_req_list);
410                         req0 = cursor;
411                 } else {
412                         req1 = cursor;
413                         break;
414                 }
415         }
416
417         WARN_ON(req1 && req1->elsp_submitted);
418
419         execlists_submit_contexts(ring, req0->ctx, req0->tail,
420                                   req1 ? req1->ctx : NULL,
421                                   req1 ? req1->tail : 0);
422
423         req0->elsp_submitted++;
424         if (req1)
425                 req1->elsp_submitted++;
426 }
427
428 static bool execlists_check_remove_request(struct intel_engine_cs *ring,
429                                            u32 request_id)
430 {
431         struct drm_i915_gem_request *head_req;
432
433         assert_spin_locked(&ring->execlist_lock);
434
435         head_req = list_first_entry_or_null(&ring->execlist_queue,
436                                             struct drm_i915_gem_request,
437                                             execlist_link);
438
439         if (head_req != NULL) {
440                 struct drm_i915_gem_object *ctx_obj =
441                                 head_req->ctx->engine[ring->id].state;
442                 if (intel_execlists_ctx_id(ctx_obj) == request_id) {
443                         WARN(head_req->elsp_submitted == 0,
444                              "Never submitted head request\n");
445
446                         if (--head_req->elsp_submitted <= 0) {
447                                 list_del(&head_req->execlist_link);
448                                 list_add_tail(&head_req->execlist_link,
449                                         &ring->execlist_retired_req_list);
450                                 return true;
451                         }
452                 }
453         }
454
455         return false;
456 }
457
458 /**
459  * intel_lrc_irq_handler() - handle Context Switch interrupts
460  * @ring: Engine Command Streamer to handle.
461  *
462  * Check the unread Context Status Buffers and manage the submission of new
463  * contexts to the ELSP accordingly.
464  */
465 void intel_lrc_irq_handler(struct intel_engine_cs *ring)
466 {
467         struct drm_i915_private *dev_priv = ring->dev->dev_private;
468         u32 status_pointer;
469         u8 read_pointer;
470         u8 write_pointer;
471         u32 status;
472         u32 status_id;
473         u32 submit_contexts = 0;
474
475         status_pointer = I915_READ(RING_CONTEXT_STATUS_PTR(ring));
476
477         read_pointer = ring->next_context_status_buffer;
478         write_pointer = status_pointer & 0x07;
479         if (read_pointer > write_pointer)
480                 write_pointer += 6;
481
482         spin_lock(&ring->execlist_lock);
483
484         while (read_pointer < write_pointer) {
485                 read_pointer++;
486                 status = I915_READ(RING_CONTEXT_STATUS_BUF(ring) +
487                                 (read_pointer % 6) * 8);
488                 status_id = I915_READ(RING_CONTEXT_STATUS_BUF(ring) +
489                                 (read_pointer % 6) * 8 + 4);
490
491                 if (status & GEN8_CTX_STATUS_PREEMPTED) {
492                         if (status & GEN8_CTX_STATUS_LITE_RESTORE) {
493                                 if (execlists_check_remove_request(ring, status_id))
494                                         WARN(1, "Lite Restored request removed from queue\n");
495                         } else
496                                 WARN(1, "Preemption without Lite Restore\n");
497                 }
498
499                  if ((status & GEN8_CTX_STATUS_ACTIVE_IDLE) ||
500                      (status & GEN8_CTX_STATUS_ELEMENT_SWITCH)) {
501                         if (execlists_check_remove_request(ring, status_id))
502                                 submit_contexts++;
503                 }
504         }
505
506         if (submit_contexts != 0)
507                 execlists_context_unqueue(ring);
508
509         spin_unlock(&ring->execlist_lock);
510
511         WARN(submit_contexts > 2, "More than two context complete events?\n");
512         ring->next_context_status_buffer = write_pointer % 6;
513
514         I915_WRITE(RING_CONTEXT_STATUS_PTR(ring),
515                    ((u32)ring->next_context_status_buffer & 0x07) << 8);
516 }
517
518 static int execlists_context_queue(struct intel_engine_cs *ring,
519                                    struct intel_context *to,
520                                    u32 tail,
521                                    struct drm_i915_gem_request *request)
522 {
523         struct drm_i915_gem_request *cursor;
524         struct drm_i915_private *dev_priv = ring->dev->dev_private;
525         int num_elements = 0;
526
527         if (to != ring->default_context)
528                 intel_lr_context_pin(ring, to);
529
530         if (!request) {
531                 /*
532                  * If there isn't a request associated with this submission,
533                  * create one as a temporary holder.
534                  */
535                 request = kzalloc(sizeof(*request), GFP_KERNEL);
536                 if (request == NULL)
537                         return -ENOMEM;
538                 request->ring = ring;
539                 request->ctx = to;
540                 kref_init(&request->ref);
541                 request->uniq = dev_priv->request_uniq++;
542                 i915_gem_context_reference(request->ctx);
543         } else {
544                 i915_gem_request_reference(request);
545                 WARN_ON(to != request->ctx);
546         }
547         request->tail = tail;
548
549         spin_lock_irq(&ring->execlist_lock);
550
551         list_for_each_entry(cursor, &ring->execlist_queue, execlist_link)
552                 if (++num_elements > 2)
553                         break;
554
555         if (num_elements > 2) {
556                 struct drm_i915_gem_request *tail_req;
557
558                 tail_req = list_last_entry(&ring->execlist_queue,
559                                            struct drm_i915_gem_request,
560                                            execlist_link);
561
562                 if (to == tail_req->ctx) {
563                         WARN(tail_req->elsp_submitted != 0,
564                                 "More than 2 already-submitted reqs queued\n");
565                         list_del(&tail_req->execlist_link);
566                         list_add_tail(&tail_req->execlist_link,
567                                 &ring->execlist_retired_req_list);
568                 }
569         }
570
571         list_add_tail(&request->execlist_link, &ring->execlist_queue);
572         if (num_elements == 0)
573                 execlists_context_unqueue(ring);
574
575         spin_unlock_irq(&ring->execlist_lock);
576
577         return 0;
578 }
579
580 static int logical_ring_invalidate_all_caches(struct intel_ringbuffer *ringbuf,
581                                               struct intel_context *ctx)
582 {
583         struct intel_engine_cs *ring = ringbuf->ring;
584         uint32_t flush_domains;
585         int ret;
586
587         flush_domains = 0;
588         if (ring->gpu_caches_dirty)
589                 flush_domains = I915_GEM_GPU_DOMAINS;
590
591         ret = ring->emit_flush(ringbuf, ctx,
592                                I915_GEM_GPU_DOMAINS, flush_domains);
593         if (ret)
594                 return ret;
595
596         ring->gpu_caches_dirty = false;
597         return 0;
598 }
599
600 static int execlists_move_to_gpu(struct intel_ringbuffer *ringbuf,
601                                  struct intel_context *ctx,
602                                  struct list_head *vmas)
603 {
604         struct intel_engine_cs *ring = ringbuf->ring;
605         struct i915_vma *vma;
606         uint32_t flush_domains = 0;
607         bool flush_chipset = false;
608         int ret;
609
610         list_for_each_entry(vma, vmas, exec_list) {
611                 struct drm_i915_gem_object *obj = vma->obj;
612
613                 ret = i915_gem_object_sync(obj, ring);
614                 if (ret)
615                         return ret;
616
617                 if (obj->base.write_domain & I915_GEM_DOMAIN_CPU)
618                         flush_chipset |= i915_gem_clflush_object(obj, false);
619
620                 flush_domains |= obj->base.write_domain;
621         }
622
623         if (flush_domains & I915_GEM_DOMAIN_GTT)
624                 wmb();
625
626         /* Unconditionally invalidate gpu caches and ensure that we do flush
627          * any residual writes from the previous batch.
628          */
629         return logical_ring_invalidate_all_caches(ringbuf, ctx);
630 }
631
632 int intel_logical_ring_alloc_request_extras(struct drm_i915_gem_request *request,
633                                             struct intel_context *ctx)
634 {
635         int ret;
636
637         if (ctx != request->ring->default_context) {
638                 ret = intel_lr_context_pin(request->ring, ctx);
639                 if (ret)
640                         return ret;
641         }
642
643         request->ringbuf = ctx->engine[request->ring->id].ringbuf;
644         request->ctx     = ctx;
645         i915_gem_context_reference(request->ctx);
646
647         return 0;
648 }
649
650 static int logical_ring_wait_for_space(struct intel_ringbuffer *ringbuf,
651                                        struct intel_context *ctx,
652                                        int bytes)
653 {
654         struct intel_engine_cs *ring = ringbuf->ring;
655         struct drm_i915_gem_request *request;
656         int ret, new_space;
657
658         if (intel_ring_space(ringbuf) >= bytes)
659                 return 0;
660
661         list_for_each_entry(request, &ring->request_list, list) {
662                 /*
663                  * The request queue is per-engine, so can contain requests
664                  * from multiple ringbuffers. Here, we must ignore any that
665                  * aren't from the ringbuffer we're considering.
666                  */
667                 struct intel_context *ctx = request->ctx;
668                 if (ctx->engine[ring->id].ringbuf != ringbuf)
669                         continue;
670
671                 /* Would completion of this request free enough space? */
672                 new_space = __intel_ring_space(request->postfix, ringbuf->tail,
673                                        ringbuf->size);
674                 if (new_space >= bytes)
675                         break;
676         }
677
678         if (WARN_ON(&request->list == &ring->request_list))
679                 return -ENOSPC;
680
681         ret = i915_wait_request(request);
682         if (ret)
683                 return ret;
684
685         i915_gem_retire_requests_ring(ring);
686
687         WARN_ON(intel_ring_space(ringbuf) < new_space);
688
689         return intel_ring_space(ringbuf) >= bytes ? 0 : -ENOSPC;
690 }
691
692 /*
693  * intel_logical_ring_advance_and_submit() - advance the tail and submit the workload
694  * @ringbuf: Logical Ringbuffer to advance.
695  *
696  * The tail is updated in our logical ringbuffer struct, not in the actual context. What
697  * really happens during submission is that the context and current tail will be placed
698  * on a queue waiting for the ELSP to be ready to accept a new context submission. At that
699  * point, the tail *inside* the context is updated and the ELSP written to.
700  */
701 static void
702 intel_logical_ring_advance_and_submit(struct intel_ringbuffer *ringbuf,
703                                       struct intel_context *ctx,
704                                       struct drm_i915_gem_request *request)
705 {
706         struct intel_engine_cs *ring = ringbuf->ring;
707
708         intel_logical_ring_advance(ringbuf);
709
710         if (intel_ring_stopped(ring))
711                 return;
712
713         execlists_context_queue(ring, ctx, ringbuf->tail, request);
714 }
715
716 static int logical_ring_wrap_buffer(struct intel_ringbuffer *ringbuf,
717                                     struct intel_context *ctx)
718 {
719         uint32_t __iomem *virt;
720         int rem = ringbuf->size - ringbuf->tail;
721
722         if (ringbuf->space < rem) {
723                 int ret = logical_ring_wait_for_space(ringbuf, ctx, rem);
724
725                 if (ret)
726                         return ret;
727         }
728
729         virt = ringbuf->virtual_start + ringbuf->tail;
730         rem /= 4;
731         while (rem--)
732                 iowrite32(MI_NOOP, virt++);
733
734         ringbuf->tail = 0;
735         intel_ring_update_space(ringbuf);
736
737         return 0;
738 }
739
740 static int logical_ring_prepare(struct intel_ringbuffer *ringbuf,
741                                 struct intel_context *ctx, int bytes)
742 {
743         int ret;
744
745         if (unlikely(ringbuf->tail + bytes > ringbuf->effective_size)) {
746                 ret = logical_ring_wrap_buffer(ringbuf, ctx);
747                 if (unlikely(ret))
748                         return ret;
749         }
750
751         if (unlikely(ringbuf->space < bytes)) {
752                 ret = logical_ring_wait_for_space(ringbuf, ctx, bytes);
753                 if (unlikely(ret))
754                         return ret;
755         }
756
757         return 0;
758 }
759
760 /**
761  * intel_logical_ring_begin() - prepare the logical ringbuffer to accept some commands
762  *
763  * @ringbuf: Logical ringbuffer.
764  * @num_dwords: number of DWORDs that we plan to write to the ringbuffer.
765  *
766  * The ringbuffer might not be ready to accept the commands right away (maybe it needs to
767  * be wrapped, or wait a bit for the tail to be updated). This function takes care of that
768  * and also preallocates a request (every workload submission is still mediated through
769  * requests, same as it did with legacy ringbuffer submission).
770  *
771  * Return: non-zero if the ringbuffer is not ready to be written to.
772  */
773 static int intel_logical_ring_begin(struct intel_ringbuffer *ringbuf,
774                                     struct intel_context *ctx, int num_dwords)
775 {
776         struct intel_engine_cs *ring = ringbuf->ring;
777         struct drm_device *dev = ring->dev;
778         struct drm_i915_private *dev_priv = dev->dev_private;
779         int ret;
780
781         ret = i915_gem_check_wedge(&dev_priv->gpu_error,
782                                    dev_priv->mm.interruptible);
783         if (ret)
784                 return ret;
785
786         ret = logical_ring_prepare(ringbuf, ctx, num_dwords * sizeof(uint32_t));
787         if (ret)
788                 return ret;
789
790         /* Preallocate the olr before touching the ring */
791         ret = i915_gem_request_alloc(ring, ctx);
792         if (ret)
793                 return ret;
794
795         ringbuf->space -= num_dwords * sizeof(uint32_t);
796         return 0;
797 }
798
799 /**
800  * execlists_submission() - submit a batchbuffer for execution, Execlists style
801  * @dev: DRM device.
802  * @file: DRM file.
803  * @ring: Engine Command Streamer to submit to.
804  * @ctx: Context to employ for this submission.
805  * @args: execbuffer call arguments.
806  * @vmas: list of vmas.
807  * @batch_obj: the batchbuffer to submit.
808  * @exec_start: batchbuffer start virtual address pointer.
809  * @dispatch_flags: translated execbuffer call flags.
810  *
811  * This is the evil twin version of i915_gem_ringbuffer_submission. It abstracts
812  * away the submission details of the execbuffer ioctl call.
813  *
814  * Return: non-zero if the submission fails.
815  */
816 int intel_execlists_submission(struct drm_device *dev, struct drm_file *file,
817                                struct intel_engine_cs *ring,
818                                struct intel_context *ctx,
819                                struct drm_i915_gem_execbuffer2 *args,
820                                struct list_head *vmas,
821                                struct drm_i915_gem_object *batch_obj,
822                                u64 exec_start, u32 dispatch_flags)
823 {
824         struct drm_i915_private *dev_priv = dev->dev_private;
825         struct intel_ringbuffer *ringbuf = ctx->engine[ring->id].ringbuf;
826         int instp_mode;
827         u32 instp_mask;
828         int ret;
829
830         instp_mode = args->flags & I915_EXEC_CONSTANTS_MASK;
831         instp_mask = I915_EXEC_CONSTANTS_MASK;
832         switch (instp_mode) {
833         case I915_EXEC_CONSTANTS_REL_GENERAL:
834         case I915_EXEC_CONSTANTS_ABSOLUTE:
835         case I915_EXEC_CONSTANTS_REL_SURFACE:
836                 if (instp_mode != 0 && ring != &dev_priv->ring[RCS]) {
837                         DRM_DEBUG("non-0 rel constants mode on non-RCS\n");
838                         return -EINVAL;
839                 }
840
841                 if (instp_mode != dev_priv->relative_constants_mode) {
842                         if (instp_mode == I915_EXEC_CONSTANTS_REL_SURFACE) {
843                                 DRM_DEBUG("rel surface constants mode invalid on gen5+\n");
844                                 return -EINVAL;
845                         }
846
847                         /* The HW changed the meaning on this bit on gen6 */
848                         instp_mask &= ~I915_EXEC_CONSTANTS_REL_SURFACE;
849                 }
850                 break;
851         default:
852                 DRM_DEBUG("execbuf with unknown constants: %d\n", instp_mode);
853                 return -EINVAL;
854         }
855
856         if (args->num_cliprects != 0) {
857                 DRM_DEBUG("clip rectangles are only valid on pre-gen5\n");
858                 return -EINVAL;
859         } else {
860                 if (args->DR4 == 0xffffffff) {
861                         DRM_DEBUG("UXA submitting garbage DR4, fixing up\n");
862                         args->DR4 = 0;
863                 }
864
865                 if (args->DR1 || args->DR4 || args->cliprects_ptr) {
866                         DRM_DEBUG("0 cliprects but dirt in cliprects fields\n");
867                         return -EINVAL;
868                 }
869         }
870
871         if (args->flags & I915_EXEC_GEN7_SOL_RESET) {
872                 DRM_DEBUG("sol reset is gen7 only\n");
873                 return -EINVAL;
874         }
875
876         ret = execlists_move_to_gpu(ringbuf, ctx, vmas);
877         if (ret)
878                 return ret;
879
880         if (ring == &dev_priv->ring[RCS] &&
881             instp_mode != dev_priv->relative_constants_mode) {
882                 ret = intel_logical_ring_begin(ringbuf, ctx, 4);
883                 if (ret)
884                         return ret;
885
886                 intel_logical_ring_emit(ringbuf, MI_NOOP);
887                 intel_logical_ring_emit(ringbuf, MI_LOAD_REGISTER_IMM(1));
888                 intel_logical_ring_emit(ringbuf, INSTPM);
889                 intel_logical_ring_emit(ringbuf, instp_mask << 16 | instp_mode);
890                 intel_logical_ring_advance(ringbuf);
891
892                 dev_priv->relative_constants_mode = instp_mode;
893         }
894
895         ret = ring->emit_bb_start(ringbuf, ctx, exec_start, dispatch_flags);
896         if (ret)
897                 return ret;
898
899         trace_i915_gem_ring_dispatch(intel_ring_get_request(ring), dispatch_flags);
900
901         i915_gem_execbuffer_move_to_active(vmas, ring);
902         i915_gem_execbuffer_retire_commands(dev, file, ring, batch_obj);
903
904         return 0;
905 }
906
907 void intel_execlists_retire_requests(struct intel_engine_cs *ring)
908 {
909         struct drm_i915_gem_request *req, *tmp;
910         struct list_head retired_list;
911
912         WARN_ON(!mutex_is_locked(&ring->dev->struct_mutex));
913         if (list_empty(&ring->execlist_retired_req_list))
914                 return;
915
916         INIT_LIST_HEAD(&retired_list);
917         spin_lock_irq(&ring->execlist_lock);
918         list_replace_init(&ring->execlist_retired_req_list, &retired_list);
919         spin_unlock_irq(&ring->execlist_lock);
920
921         list_for_each_entry_safe(req, tmp, &retired_list, execlist_link) {
922                 struct intel_context *ctx = req->ctx;
923                 struct drm_i915_gem_object *ctx_obj =
924                                 ctx->engine[ring->id].state;
925
926                 if (ctx_obj && (ctx != ring->default_context))
927                         intel_lr_context_unpin(ring, ctx);
928                 list_del(&req->execlist_link);
929                 i915_gem_request_unreference(req);
930         }
931 }
932
933 void intel_logical_ring_stop(struct intel_engine_cs *ring)
934 {
935         struct drm_i915_private *dev_priv = ring->dev->dev_private;
936         int ret;
937
938         if (!intel_ring_initialized(ring))
939                 return;
940
941         ret = intel_ring_idle(ring);
942         if (ret && !i915_reset_in_progress(&to_i915(ring->dev)->gpu_error))
943                 DRM_ERROR("failed to quiesce %s whilst cleaning up: %d\n",
944                           ring->name, ret);
945
946         /* TODO: Is this correct with Execlists enabled? */
947         I915_WRITE_MODE(ring, _MASKED_BIT_ENABLE(STOP_RING));
948         if (wait_for_atomic((I915_READ_MODE(ring) & MODE_IDLE) != 0, 1000)) {
949                 DRM_ERROR("%s :timed out trying to stop ring\n", ring->name);
950                 return;
951         }
952         I915_WRITE_MODE(ring, _MASKED_BIT_DISABLE(STOP_RING));
953 }
954
955 int logical_ring_flush_all_caches(struct intel_ringbuffer *ringbuf,
956                                   struct intel_context *ctx)
957 {
958         struct intel_engine_cs *ring = ringbuf->ring;
959         int ret;
960
961         if (!ring->gpu_caches_dirty)
962                 return 0;
963
964         ret = ring->emit_flush(ringbuf, ctx, 0, I915_GEM_GPU_DOMAINS);
965         if (ret)
966                 return ret;
967
968         ring->gpu_caches_dirty = false;
969         return 0;
970 }
971
972 static int intel_lr_context_pin(struct intel_engine_cs *ring,
973                 struct intel_context *ctx)
974 {
975         struct drm_i915_gem_object *ctx_obj = ctx->engine[ring->id].state;
976         struct intel_ringbuffer *ringbuf = ctx->engine[ring->id].ringbuf;
977         int ret = 0;
978
979         WARN_ON(!mutex_is_locked(&ring->dev->struct_mutex));
980         if (ctx->engine[ring->id].pin_count++ == 0) {
981                 ret = i915_gem_obj_ggtt_pin(ctx_obj,
982                                 GEN8_LR_CONTEXT_ALIGN, 0);
983                 if (ret)
984                         goto reset_pin_count;
985
986                 ret = intel_pin_and_map_ringbuffer_obj(ring->dev, ringbuf);
987                 if (ret)
988                         goto unpin_ctx_obj;
989         }
990
991         return ret;
992
993 unpin_ctx_obj:
994         i915_gem_object_ggtt_unpin(ctx_obj);
995 reset_pin_count:
996         ctx->engine[ring->id].pin_count = 0;
997
998         return ret;
999 }
1000
1001 void intel_lr_context_unpin(struct intel_engine_cs *ring,
1002                 struct intel_context *ctx)
1003 {
1004         struct drm_i915_gem_object *ctx_obj = ctx->engine[ring->id].state;
1005         struct intel_ringbuffer *ringbuf = ctx->engine[ring->id].ringbuf;
1006
1007         if (ctx_obj) {
1008                 WARN_ON(!mutex_is_locked(&ring->dev->struct_mutex));
1009                 if (--ctx->engine[ring->id].pin_count == 0) {
1010                         intel_unpin_ringbuffer_obj(ringbuf);
1011                         i915_gem_object_ggtt_unpin(ctx_obj);
1012                 }
1013         }
1014 }
1015
1016 static int intel_logical_ring_workarounds_emit(struct intel_engine_cs *ring,
1017                                                struct intel_context *ctx)
1018 {
1019         int ret, i;
1020         struct intel_ringbuffer *ringbuf = ctx->engine[ring->id].ringbuf;
1021         struct drm_device *dev = ring->dev;
1022         struct drm_i915_private *dev_priv = dev->dev_private;
1023         struct i915_workarounds *w = &dev_priv->workarounds;
1024
1025         if (WARN_ON_ONCE(w->count == 0))
1026                 return 0;
1027
1028         ring->gpu_caches_dirty = true;
1029         ret = logical_ring_flush_all_caches(ringbuf, ctx);
1030         if (ret)
1031                 return ret;
1032
1033         ret = intel_logical_ring_begin(ringbuf, ctx, w->count * 2 + 2);
1034         if (ret)
1035                 return ret;
1036
1037         intel_logical_ring_emit(ringbuf, MI_LOAD_REGISTER_IMM(w->count));
1038         for (i = 0; i < w->count; i++) {
1039                 intel_logical_ring_emit(ringbuf, w->reg[i].addr);
1040                 intel_logical_ring_emit(ringbuf, w->reg[i].value);
1041         }
1042         intel_logical_ring_emit(ringbuf, MI_NOOP);
1043
1044         intel_logical_ring_advance(ringbuf);
1045
1046         ring->gpu_caches_dirty = true;
1047         ret = logical_ring_flush_all_caches(ringbuf, ctx);
1048         if (ret)
1049                 return ret;
1050
1051         return 0;
1052 }
1053
1054 static int gen8_init_common_ring(struct intel_engine_cs *ring)
1055 {
1056         struct drm_device *dev = ring->dev;
1057         struct drm_i915_private *dev_priv = dev->dev_private;
1058
1059         I915_WRITE_IMR(ring, ~(ring->irq_enable_mask | ring->irq_keep_mask));
1060         I915_WRITE(RING_HWSTAM(ring->mmio_base), 0xffffffff);
1061
1062         I915_WRITE(RING_MODE_GEN7(ring),
1063                    _MASKED_BIT_DISABLE(GFX_REPLAY_MODE) |
1064                    _MASKED_BIT_ENABLE(GFX_RUN_LIST_ENABLE));
1065         POSTING_READ(RING_MODE_GEN7(ring));
1066         ring->next_context_status_buffer = 0;
1067         DRM_DEBUG_DRIVER("Execlists enabled for %s\n", ring->name);
1068
1069         memset(&ring->hangcheck, 0, sizeof(ring->hangcheck));
1070
1071         return 0;
1072 }
1073
1074 static int gen8_init_render_ring(struct intel_engine_cs *ring)
1075 {
1076         struct drm_device *dev = ring->dev;
1077         struct drm_i915_private *dev_priv = dev->dev_private;
1078         int ret;
1079
1080         ret = gen8_init_common_ring(ring);
1081         if (ret)
1082                 return ret;
1083
1084         /* We need to disable the AsyncFlip performance optimisations in order
1085          * to use MI_WAIT_FOR_EVENT within the CS. It should already be
1086          * programmed to '1' on all products.
1087          *
1088          * WaDisableAsyncFlipPerfMode:snb,ivb,hsw,vlv,bdw,chv
1089          */
1090         I915_WRITE(MI_MODE, _MASKED_BIT_ENABLE(ASYNC_FLIP_PERF_DISABLE));
1091
1092         I915_WRITE(INSTPM, _MASKED_BIT_ENABLE(INSTPM_FORCE_ORDERING));
1093
1094         return init_workarounds_ring(ring);
1095 }
1096
1097 static int gen9_init_render_ring(struct intel_engine_cs *ring)
1098 {
1099         int ret;
1100
1101         ret = gen8_init_common_ring(ring);
1102         if (ret)
1103                 return ret;
1104
1105         return init_workarounds_ring(ring);
1106 }
1107
1108 static int gen8_emit_bb_start(struct intel_ringbuffer *ringbuf,
1109                               struct intel_context *ctx,
1110                               u64 offset, unsigned dispatch_flags)
1111 {
1112         bool ppgtt = !(dispatch_flags & I915_DISPATCH_SECURE);
1113         int ret;
1114
1115         ret = intel_logical_ring_begin(ringbuf, ctx, 4);
1116         if (ret)
1117                 return ret;
1118
1119         /* FIXME(BDW): Address space and security selectors. */
1120         intel_logical_ring_emit(ringbuf, MI_BATCH_BUFFER_START_GEN8 | (ppgtt<<8));
1121         intel_logical_ring_emit(ringbuf, lower_32_bits(offset));
1122         intel_logical_ring_emit(ringbuf, upper_32_bits(offset));
1123         intel_logical_ring_emit(ringbuf, MI_NOOP);
1124         intel_logical_ring_advance(ringbuf);
1125
1126         return 0;
1127 }
1128
1129 static bool gen8_logical_ring_get_irq(struct intel_engine_cs *ring)
1130 {
1131         struct drm_device *dev = ring->dev;
1132         struct drm_i915_private *dev_priv = dev->dev_private;
1133         unsigned long flags;
1134
1135         if (WARN_ON(!intel_irqs_enabled(dev_priv)))
1136                 return false;
1137
1138         spin_lock_irqsave(&dev_priv->irq_lock, flags);
1139         if (ring->irq_refcount++ == 0) {
1140                 I915_WRITE_IMR(ring, ~(ring->irq_enable_mask | ring->irq_keep_mask));
1141                 POSTING_READ(RING_IMR(ring->mmio_base));
1142         }
1143         spin_unlock_irqrestore(&dev_priv->irq_lock, flags);
1144
1145         return true;
1146 }
1147
1148 static void gen8_logical_ring_put_irq(struct intel_engine_cs *ring)
1149 {
1150         struct drm_device *dev = ring->dev;
1151         struct drm_i915_private *dev_priv = dev->dev_private;
1152         unsigned long flags;
1153
1154         spin_lock_irqsave(&dev_priv->irq_lock, flags);
1155         if (--ring->irq_refcount == 0) {
1156                 I915_WRITE_IMR(ring, ~ring->irq_keep_mask);
1157                 POSTING_READ(RING_IMR(ring->mmio_base));
1158         }
1159         spin_unlock_irqrestore(&dev_priv->irq_lock, flags);
1160 }
1161
1162 static int gen8_emit_flush(struct intel_ringbuffer *ringbuf,
1163                            struct intel_context *ctx,
1164                            u32 invalidate_domains,
1165                            u32 unused)
1166 {
1167         struct intel_engine_cs *ring = ringbuf->ring;
1168         struct drm_device *dev = ring->dev;
1169         struct drm_i915_private *dev_priv = dev->dev_private;
1170         uint32_t cmd;
1171         int ret;
1172
1173         ret = intel_logical_ring_begin(ringbuf, ctx, 4);
1174         if (ret)
1175                 return ret;
1176
1177         cmd = MI_FLUSH_DW + 1;
1178
1179         /* We always require a command barrier so that subsequent
1180          * commands, such as breadcrumb interrupts, are strictly ordered
1181          * wrt the contents of the write cache being flushed to memory
1182          * (and thus being coherent from the CPU).
1183          */
1184         cmd |= MI_FLUSH_DW_STORE_INDEX | MI_FLUSH_DW_OP_STOREDW;
1185
1186         if (invalidate_domains & I915_GEM_GPU_DOMAINS) {
1187                 cmd |= MI_INVALIDATE_TLB;
1188                 if (ring == &dev_priv->ring[VCS])
1189                         cmd |= MI_INVALIDATE_BSD;
1190         }
1191
1192         intel_logical_ring_emit(ringbuf, cmd);
1193         intel_logical_ring_emit(ringbuf,
1194                                 I915_GEM_HWS_SCRATCH_ADDR |
1195                                 MI_FLUSH_DW_USE_GTT);
1196         intel_logical_ring_emit(ringbuf, 0); /* upper addr */
1197         intel_logical_ring_emit(ringbuf, 0); /* value */
1198         intel_logical_ring_advance(ringbuf);
1199
1200         return 0;
1201 }
1202
1203 static int gen8_emit_flush_render(struct intel_ringbuffer *ringbuf,
1204                                   struct intel_context *ctx,
1205                                   u32 invalidate_domains,
1206                                   u32 flush_domains)
1207 {
1208         struct intel_engine_cs *ring = ringbuf->ring;
1209         u32 scratch_addr = ring->scratch.gtt_offset + 2 * CACHELINE_BYTES;
1210         u32 flags = 0;
1211         int ret;
1212
1213         flags |= PIPE_CONTROL_CS_STALL;
1214
1215         if (flush_domains) {
1216                 flags |= PIPE_CONTROL_RENDER_TARGET_CACHE_FLUSH;
1217                 flags |= PIPE_CONTROL_DEPTH_CACHE_FLUSH;
1218         }
1219
1220         if (invalidate_domains) {
1221                 flags |= PIPE_CONTROL_TLB_INVALIDATE;
1222                 flags |= PIPE_CONTROL_INSTRUCTION_CACHE_INVALIDATE;
1223                 flags |= PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE;
1224                 flags |= PIPE_CONTROL_VF_CACHE_INVALIDATE;
1225                 flags |= PIPE_CONTROL_CONST_CACHE_INVALIDATE;
1226                 flags |= PIPE_CONTROL_STATE_CACHE_INVALIDATE;
1227                 flags |= PIPE_CONTROL_QW_WRITE;
1228                 flags |= PIPE_CONTROL_GLOBAL_GTT_IVB;
1229         }
1230
1231         ret = intel_logical_ring_begin(ringbuf, ctx, 6);
1232         if (ret)
1233                 return ret;
1234
1235         intel_logical_ring_emit(ringbuf, GFX_OP_PIPE_CONTROL(6));
1236         intel_logical_ring_emit(ringbuf, flags);
1237         intel_logical_ring_emit(ringbuf, scratch_addr);
1238         intel_logical_ring_emit(ringbuf, 0);
1239         intel_logical_ring_emit(ringbuf, 0);
1240         intel_logical_ring_emit(ringbuf, 0);
1241         intel_logical_ring_advance(ringbuf);
1242
1243         return 0;
1244 }
1245
1246 static u32 gen8_get_seqno(struct intel_engine_cs *ring, bool lazy_coherency)
1247 {
1248         return intel_read_status_page(ring, I915_GEM_HWS_INDEX);
1249 }
1250
1251 static void gen8_set_seqno(struct intel_engine_cs *ring, u32 seqno)
1252 {
1253         intel_write_status_page(ring, I915_GEM_HWS_INDEX, seqno);
1254 }
1255
1256 static int gen8_emit_request(struct intel_ringbuffer *ringbuf,
1257                              struct drm_i915_gem_request *request)
1258 {
1259         struct intel_engine_cs *ring = ringbuf->ring;
1260         u32 cmd;
1261         int ret;
1262
1263         ret = intel_logical_ring_begin(ringbuf, request->ctx, 6);
1264         if (ret)
1265                 return ret;
1266
1267         cmd = MI_STORE_DWORD_IMM_GEN4;
1268         cmd |= MI_GLOBAL_GTT;
1269
1270         intel_logical_ring_emit(ringbuf, cmd);
1271         intel_logical_ring_emit(ringbuf,
1272                                 (ring->status_page.gfx_addr +
1273                                 (I915_GEM_HWS_INDEX << MI_STORE_DWORD_INDEX_SHIFT)));
1274         intel_logical_ring_emit(ringbuf, 0);
1275         intel_logical_ring_emit(ringbuf,
1276                 i915_gem_request_get_seqno(ring->outstanding_lazy_request));
1277         intel_logical_ring_emit(ringbuf, MI_USER_INTERRUPT);
1278         intel_logical_ring_emit(ringbuf, MI_NOOP);
1279         intel_logical_ring_advance_and_submit(ringbuf, request->ctx, request);
1280
1281         return 0;
1282 }
1283
1284 static int intel_lr_context_render_state_init(struct intel_engine_cs *ring,
1285                                               struct intel_context *ctx)
1286 {
1287         struct intel_ringbuffer *ringbuf = ctx->engine[ring->id].ringbuf;
1288         struct render_state so;
1289         struct drm_i915_file_private *file_priv = ctx->file_priv;
1290         struct drm_file *file = file_priv ? file_priv->file : NULL;
1291         int ret;
1292
1293         ret = i915_gem_render_state_prepare(ring, &so);
1294         if (ret)
1295                 return ret;
1296
1297         if (so.rodata == NULL)
1298                 return 0;
1299
1300         ret = ring->emit_bb_start(ringbuf,
1301                         ctx,
1302                         so.ggtt_offset,
1303                         I915_DISPATCH_SECURE);
1304         if (ret)
1305                 goto out;
1306
1307         i915_vma_move_to_active(i915_gem_obj_to_ggtt(so.obj), ring);
1308
1309         ret = __i915_add_request(ring, file, so.obj);
1310         /* intel_logical_ring_add_request moves object to inactive if it
1311          * fails */
1312 out:
1313         i915_gem_render_state_fini(&so);
1314         return ret;
1315 }
1316
1317 static int gen8_init_rcs_context(struct intel_engine_cs *ring,
1318                        struct intel_context *ctx)
1319 {
1320         int ret;
1321
1322         ret = intel_logical_ring_workarounds_emit(ring, ctx);
1323         if (ret)
1324                 return ret;
1325
1326         return intel_lr_context_render_state_init(ring, ctx);
1327 }
1328
1329 /**
1330  * intel_logical_ring_cleanup() - deallocate the Engine Command Streamer
1331  *
1332  * @ring: Engine Command Streamer.
1333  *
1334  */
1335 void intel_logical_ring_cleanup(struct intel_engine_cs *ring)
1336 {
1337         struct drm_i915_private *dev_priv;
1338
1339         if (!intel_ring_initialized(ring))
1340                 return;
1341
1342         dev_priv = ring->dev->dev_private;
1343
1344         intel_logical_ring_stop(ring);
1345         WARN_ON((I915_READ_MODE(ring) & MODE_IDLE) == 0);
1346         i915_gem_request_assign(&ring->outstanding_lazy_request, NULL);
1347
1348         if (ring->cleanup)
1349                 ring->cleanup(ring);
1350
1351         i915_cmd_parser_fini_ring(ring);
1352         i915_gem_batch_pool_fini(&ring->batch_pool);
1353
1354         if (ring->status_page.obj) {
1355                 kunmap(sg_page(ring->status_page.obj->pages->sgl));
1356                 ring->status_page.obj = NULL;
1357         }
1358 }
1359
1360 static int logical_ring_init(struct drm_device *dev, struct intel_engine_cs *ring)
1361 {
1362         int ret;
1363
1364         /* Intentionally left blank. */
1365         ring->buffer = NULL;
1366
1367         ring->dev = dev;
1368         INIT_LIST_HEAD(&ring->active_list);
1369         INIT_LIST_HEAD(&ring->request_list);
1370         i915_gem_batch_pool_init(dev, &ring->batch_pool);
1371         init_waitqueue_head(&ring->irq_queue);
1372
1373         INIT_LIST_HEAD(&ring->execlist_queue);
1374         INIT_LIST_HEAD(&ring->execlist_retired_req_list);
1375         spin_lock_init(&ring->execlist_lock);
1376
1377         ret = i915_cmd_parser_init_ring(ring);
1378         if (ret)
1379                 return ret;
1380
1381         ret = intel_lr_context_deferred_create(ring->default_context, ring);
1382
1383         return ret;
1384 }
1385
1386 static int logical_render_ring_init(struct drm_device *dev)
1387 {
1388         struct drm_i915_private *dev_priv = dev->dev_private;
1389         struct intel_engine_cs *ring = &dev_priv->ring[RCS];
1390         int ret;
1391
1392         ring->name = "render ring";
1393         ring->id = RCS;
1394         ring->mmio_base = RENDER_RING_BASE;
1395         ring->irq_enable_mask =
1396                 GT_RENDER_USER_INTERRUPT << GEN8_RCS_IRQ_SHIFT;
1397         ring->irq_keep_mask =
1398                 GT_CONTEXT_SWITCH_INTERRUPT << GEN8_RCS_IRQ_SHIFT;
1399         if (HAS_L3_DPF(dev))
1400                 ring->irq_keep_mask |= GT_RENDER_L3_PARITY_ERROR_INTERRUPT;
1401
1402         if (INTEL_INFO(dev)->gen >= 9)
1403                 ring->init_hw = gen9_init_render_ring;
1404         else
1405                 ring->init_hw = gen8_init_render_ring;
1406         ring->init_context = gen8_init_rcs_context;
1407         ring->cleanup = intel_fini_pipe_control;
1408         ring->get_seqno = gen8_get_seqno;
1409         ring->set_seqno = gen8_set_seqno;
1410         ring->emit_request = gen8_emit_request;
1411         ring->emit_flush = gen8_emit_flush_render;
1412         ring->irq_get = gen8_logical_ring_get_irq;
1413         ring->irq_put = gen8_logical_ring_put_irq;
1414         ring->emit_bb_start = gen8_emit_bb_start;
1415
1416         ring->dev = dev;
1417         ret = logical_ring_init(dev, ring);
1418         if (ret)
1419                 return ret;
1420
1421         return intel_init_pipe_control(ring);
1422 }
1423
1424 static int logical_bsd_ring_init(struct drm_device *dev)
1425 {
1426         struct drm_i915_private *dev_priv = dev->dev_private;
1427         struct intel_engine_cs *ring = &dev_priv->ring[VCS];
1428
1429         ring->name = "bsd ring";
1430         ring->id = VCS;
1431         ring->mmio_base = GEN6_BSD_RING_BASE;
1432         ring->irq_enable_mask =
1433                 GT_RENDER_USER_INTERRUPT << GEN8_VCS1_IRQ_SHIFT;
1434         ring->irq_keep_mask =
1435                 GT_CONTEXT_SWITCH_INTERRUPT << GEN8_VCS1_IRQ_SHIFT;
1436
1437         ring->init_hw = gen8_init_common_ring;
1438         ring->get_seqno = gen8_get_seqno;
1439         ring->set_seqno = gen8_set_seqno;
1440         ring->emit_request = gen8_emit_request;
1441         ring->emit_flush = gen8_emit_flush;
1442         ring->irq_get = gen8_logical_ring_get_irq;
1443         ring->irq_put = gen8_logical_ring_put_irq;
1444         ring->emit_bb_start = gen8_emit_bb_start;
1445
1446         return logical_ring_init(dev, ring);
1447 }
1448
1449 static int logical_bsd2_ring_init(struct drm_device *dev)
1450 {
1451         struct drm_i915_private *dev_priv = dev->dev_private;
1452         struct intel_engine_cs *ring = &dev_priv->ring[VCS2];
1453
1454         ring->name = "bds2 ring";
1455         ring->id = VCS2;
1456         ring->mmio_base = GEN8_BSD2_RING_BASE;
1457         ring->irq_enable_mask =
1458                 GT_RENDER_USER_INTERRUPT << GEN8_VCS2_IRQ_SHIFT;
1459         ring->irq_keep_mask =
1460                 GT_CONTEXT_SWITCH_INTERRUPT << GEN8_VCS2_IRQ_SHIFT;
1461
1462         ring->init_hw = gen8_init_common_ring;
1463         ring->get_seqno = gen8_get_seqno;
1464         ring->set_seqno = gen8_set_seqno;
1465         ring->emit_request = gen8_emit_request;
1466         ring->emit_flush = gen8_emit_flush;
1467         ring->irq_get = gen8_logical_ring_get_irq;
1468         ring->irq_put = gen8_logical_ring_put_irq;
1469         ring->emit_bb_start = gen8_emit_bb_start;
1470
1471         return logical_ring_init(dev, ring);
1472 }
1473
1474 static int logical_blt_ring_init(struct drm_device *dev)
1475 {
1476         struct drm_i915_private *dev_priv = dev->dev_private;
1477         struct intel_engine_cs *ring = &dev_priv->ring[BCS];
1478
1479         ring->name = "blitter ring";
1480         ring->id = BCS;
1481         ring->mmio_base = BLT_RING_BASE;
1482         ring->irq_enable_mask =
1483                 GT_RENDER_USER_INTERRUPT << GEN8_BCS_IRQ_SHIFT;
1484         ring->irq_keep_mask =
1485                 GT_CONTEXT_SWITCH_INTERRUPT << GEN8_BCS_IRQ_SHIFT;
1486
1487         ring->init_hw = gen8_init_common_ring;
1488         ring->get_seqno = gen8_get_seqno;
1489         ring->set_seqno = gen8_set_seqno;
1490         ring->emit_request = gen8_emit_request;
1491         ring->emit_flush = gen8_emit_flush;
1492         ring->irq_get = gen8_logical_ring_get_irq;
1493         ring->irq_put = gen8_logical_ring_put_irq;
1494         ring->emit_bb_start = gen8_emit_bb_start;
1495
1496         return logical_ring_init(dev, ring);
1497 }
1498
1499 static int logical_vebox_ring_init(struct drm_device *dev)
1500 {
1501         struct drm_i915_private *dev_priv = dev->dev_private;
1502         struct intel_engine_cs *ring = &dev_priv->ring[VECS];
1503
1504         ring->name = "video enhancement ring";
1505         ring->id = VECS;
1506         ring->mmio_base = VEBOX_RING_BASE;
1507         ring->irq_enable_mask =
1508                 GT_RENDER_USER_INTERRUPT << GEN8_VECS_IRQ_SHIFT;
1509         ring->irq_keep_mask =
1510                 GT_CONTEXT_SWITCH_INTERRUPT << GEN8_VECS_IRQ_SHIFT;
1511
1512         ring->init_hw = gen8_init_common_ring;
1513         ring->get_seqno = gen8_get_seqno;
1514         ring->set_seqno = gen8_set_seqno;
1515         ring->emit_request = gen8_emit_request;
1516         ring->emit_flush = gen8_emit_flush;
1517         ring->irq_get = gen8_logical_ring_get_irq;
1518         ring->irq_put = gen8_logical_ring_put_irq;
1519         ring->emit_bb_start = gen8_emit_bb_start;
1520
1521         return logical_ring_init(dev, ring);
1522 }
1523
1524 /**
1525  * intel_logical_rings_init() - allocate, populate and init the Engine Command Streamers
1526  * @dev: DRM device.
1527  *
1528  * This function inits the engines for an Execlists submission style (the equivalent in the
1529  * legacy ringbuffer submission world would be i915_gem_init_rings). It does it only for
1530  * those engines that are present in the hardware.
1531  *
1532  * Return: non-zero if the initialization failed.
1533  */
1534 int intel_logical_rings_init(struct drm_device *dev)
1535 {
1536         struct drm_i915_private *dev_priv = dev->dev_private;
1537         int ret;
1538
1539         ret = logical_render_ring_init(dev);
1540         if (ret)
1541                 return ret;
1542
1543         if (HAS_BSD(dev)) {
1544                 ret = logical_bsd_ring_init(dev);
1545                 if (ret)
1546                         goto cleanup_render_ring;
1547         }
1548
1549         if (HAS_BLT(dev)) {
1550                 ret = logical_blt_ring_init(dev);
1551                 if (ret)
1552                         goto cleanup_bsd_ring;
1553         }
1554
1555         if (HAS_VEBOX(dev)) {
1556                 ret = logical_vebox_ring_init(dev);
1557                 if (ret)
1558                         goto cleanup_blt_ring;
1559         }
1560
1561         if (HAS_BSD2(dev)) {
1562                 ret = logical_bsd2_ring_init(dev);
1563                 if (ret)
1564                         goto cleanup_vebox_ring;
1565         }
1566
1567         ret = i915_gem_set_seqno(dev, ((u32)~0 - 0x1000));
1568         if (ret)
1569                 goto cleanup_bsd2_ring;
1570
1571         return 0;
1572
1573 cleanup_bsd2_ring:
1574         intel_logical_ring_cleanup(&dev_priv->ring[VCS2]);
1575 cleanup_vebox_ring:
1576         intel_logical_ring_cleanup(&dev_priv->ring[VECS]);
1577 cleanup_blt_ring:
1578         intel_logical_ring_cleanup(&dev_priv->ring[BCS]);
1579 cleanup_bsd_ring:
1580         intel_logical_ring_cleanup(&dev_priv->ring[VCS]);
1581 cleanup_render_ring:
1582         intel_logical_ring_cleanup(&dev_priv->ring[RCS]);
1583
1584         return ret;
1585 }
1586
1587 static u32
1588 make_rpcs(struct drm_device *dev)
1589 {
1590         u32 rpcs = 0;
1591
1592         /*
1593          * No explicit RPCS request is needed to ensure full
1594          * slice/subslice/EU enablement prior to Gen9.
1595         */
1596         if (INTEL_INFO(dev)->gen < 9)
1597                 return 0;
1598
1599         /*
1600          * Starting in Gen9, render power gating can leave
1601          * slice/subslice/EU in a partially enabled state. We
1602          * must make an explicit request through RPCS for full
1603          * enablement.
1604         */
1605         if (INTEL_INFO(dev)->has_slice_pg) {
1606                 rpcs |= GEN8_RPCS_S_CNT_ENABLE;
1607                 rpcs |= INTEL_INFO(dev)->slice_total <<
1608                         GEN8_RPCS_S_CNT_SHIFT;
1609                 rpcs |= GEN8_RPCS_ENABLE;
1610         }
1611
1612         if (INTEL_INFO(dev)->has_subslice_pg) {
1613                 rpcs |= GEN8_RPCS_SS_CNT_ENABLE;
1614                 rpcs |= INTEL_INFO(dev)->subslice_per_slice <<
1615                         GEN8_RPCS_SS_CNT_SHIFT;
1616                 rpcs |= GEN8_RPCS_ENABLE;
1617         }
1618
1619         if (INTEL_INFO(dev)->has_eu_pg) {
1620                 rpcs |= INTEL_INFO(dev)->eu_per_subslice <<
1621                         GEN8_RPCS_EU_MIN_SHIFT;
1622                 rpcs |= INTEL_INFO(dev)->eu_per_subslice <<
1623                         GEN8_RPCS_EU_MAX_SHIFT;
1624                 rpcs |= GEN8_RPCS_ENABLE;
1625         }
1626
1627         return rpcs;
1628 }
1629
1630 static int
1631 populate_lr_context(struct intel_context *ctx, struct drm_i915_gem_object *ctx_obj,
1632                     struct intel_engine_cs *ring, struct intel_ringbuffer *ringbuf)
1633 {
1634         struct drm_device *dev = ring->dev;
1635         struct drm_i915_private *dev_priv = dev->dev_private;
1636         struct i915_hw_ppgtt *ppgtt = ctx->ppgtt;
1637         struct page *page;
1638         uint32_t *reg_state;
1639         int ret;
1640
1641         if (!ppgtt)
1642                 ppgtt = dev_priv->mm.aliasing_ppgtt;
1643
1644         ret = i915_gem_object_set_to_cpu_domain(ctx_obj, true);
1645         if (ret) {
1646                 DRM_DEBUG_DRIVER("Could not set to CPU domain\n");
1647                 return ret;
1648         }
1649
1650         ret = i915_gem_object_get_pages(ctx_obj);
1651         if (ret) {
1652                 DRM_DEBUG_DRIVER("Could not get object pages\n");
1653                 return ret;
1654         }
1655
1656         i915_gem_object_pin_pages(ctx_obj);
1657
1658         /* The second page of the context object contains some fields which must
1659          * be set up prior to the first execution. */
1660         page = i915_gem_object_get_page(ctx_obj, 1);
1661         reg_state = kmap_atomic(page);
1662
1663         /* A context is actually a big batch buffer with several MI_LOAD_REGISTER_IMM
1664          * commands followed by (reg, value) pairs. The values we are setting here are
1665          * only for the first context restore: on a subsequent save, the GPU will
1666          * recreate this batchbuffer with new values (including all the missing
1667          * MI_LOAD_REGISTER_IMM commands that we are not initializing here). */
1668         if (ring->id == RCS)
1669                 reg_state[CTX_LRI_HEADER_0] = MI_LOAD_REGISTER_IMM(14);
1670         else
1671                 reg_state[CTX_LRI_HEADER_0] = MI_LOAD_REGISTER_IMM(11);
1672         reg_state[CTX_LRI_HEADER_0] |= MI_LRI_FORCE_POSTED;
1673         reg_state[CTX_CONTEXT_CONTROL] = RING_CONTEXT_CONTROL(ring);
1674         reg_state[CTX_CONTEXT_CONTROL+1] =
1675                 _MASKED_BIT_ENABLE(CTX_CTRL_INHIBIT_SYN_CTX_SWITCH |
1676                                 CTX_CTRL_ENGINE_CTX_RESTORE_INHIBIT);
1677         reg_state[CTX_RING_HEAD] = RING_HEAD(ring->mmio_base);
1678         reg_state[CTX_RING_HEAD+1] = 0;
1679         reg_state[CTX_RING_TAIL] = RING_TAIL(ring->mmio_base);
1680         reg_state[CTX_RING_TAIL+1] = 0;
1681         reg_state[CTX_RING_BUFFER_START] = RING_START(ring->mmio_base);
1682         /* Ring buffer start address is not known until the buffer is pinned.
1683          * It is written to the context image in execlists_update_context()
1684          */
1685         reg_state[CTX_RING_BUFFER_CONTROL] = RING_CTL(ring->mmio_base);
1686         reg_state[CTX_RING_BUFFER_CONTROL+1] =
1687                         ((ringbuf->size - PAGE_SIZE) & RING_NR_PAGES) | RING_VALID;
1688         reg_state[CTX_BB_HEAD_U] = ring->mmio_base + 0x168;
1689         reg_state[CTX_BB_HEAD_U+1] = 0;
1690         reg_state[CTX_BB_HEAD_L] = ring->mmio_base + 0x140;
1691         reg_state[CTX_BB_HEAD_L+1] = 0;
1692         reg_state[CTX_BB_STATE] = ring->mmio_base + 0x110;
1693         reg_state[CTX_BB_STATE+1] = (1<<5);
1694         reg_state[CTX_SECOND_BB_HEAD_U] = ring->mmio_base + 0x11c;
1695         reg_state[CTX_SECOND_BB_HEAD_U+1] = 0;
1696         reg_state[CTX_SECOND_BB_HEAD_L] = ring->mmio_base + 0x114;
1697         reg_state[CTX_SECOND_BB_HEAD_L+1] = 0;
1698         reg_state[CTX_SECOND_BB_STATE] = ring->mmio_base + 0x118;
1699         reg_state[CTX_SECOND_BB_STATE+1] = 0;
1700         if (ring->id == RCS) {
1701                 /* TODO: according to BSpec, the register state context
1702                  * for CHV does not have these. OTOH, these registers do
1703                  * exist in CHV. I'm waiting for a clarification */
1704                 reg_state[CTX_BB_PER_CTX_PTR] = ring->mmio_base + 0x1c0;
1705                 reg_state[CTX_BB_PER_CTX_PTR+1] = 0;
1706                 reg_state[CTX_RCS_INDIRECT_CTX] = ring->mmio_base + 0x1c4;
1707                 reg_state[CTX_RCS_INDIRECT_CTX+1] = 0;
1708                 reg_state[CTX_RCS_INDIRECT_CTX_OFFSET] = ring->mmio_base + 0x1c8;
1709                 reg_state[CTX_RCS_INDIRECT_CTX_OFFSET+1] = 0;
1710         }
1711         reg_state[CTX_LRI_HEADER_1] = MI_LOAD_REGISTER_IMM(9);
1712         reg_state[CTX_LRI_HEADER_1] |= MI_LRI_FORCE_POSTED;
1713         reg_state[CTX_CTX_TIMESTAMP] = ring->mmio_base + 0x3a8;
1714         reg_state[CTX_CTX_TIMESTAMP+1] = 0;
1715         reg_state[CTX_PDP3_UDW] = GEN8_RING_PDP_UDW(ring, 3);
1716         reg_state[CTX_PDP3_LDW] = GEN8_RING_PDP_LDW(ring, 3);
1717         reg_state[CTX_PDP2_UDW] = GEN8_RING_PDP_UDW(ring, 2);
1718         reg_state[CTX_PDP2_LDW] = GEN8_RING_PDP_LDW(ring, 2);
1719         reg_state[CTX_PDP1_UDW] = GEN8_RING_PDP_UDW(ring, 1);
1720         reg_state[CTX_PDP1_LDW] = GEN8_RING_PDP_LDW(ring, 1);
1721         reg_state[CTX_PDP0_UDW] = GEN8_RING_PDP_UDW(ring, 0);
1722         reg_state[CTX_PDP0_LDW] = GEN8_RING_PDP_LDW(ring, 0);
1723
1724         /* With dynamic page allocation, PDPs may not be allocated at this point,
1725          * Point the unallocated PDPs to the scratch page
1726          */
1727         ASSIGN_CTX_PDP(ppgtt, reg_state, 3);
1728         ASSIGN_CTX_PDP(ppgtt, reg_state, 2);
1729         ASSIGN_CTX_PDP(ppgtt, reg_state, 1);
1730         ASSIGN_CTX_PDP(ppgtt, reg_state, 0);
1731         if (ring->id == RCS) {
1732                 reg_state[CTX_LRI_HEADER_2] = MI_LOAD_REGISTER_IMM(1);
1733                 reg_state[CTX_R_PWR_CLK_STATE] = GEN8_R_PWR_CLK_STATE;
1734                 reg_state[CTX_R_PWR_CLK_STATE+1] = make_rpcs(dev);
1735         }
1736
1737         kunmap_atomic(reg_state);
1738
1739         ctx_obj->dirty = 1;
1740         set_page_dirty(page);
1741         i915_gem_object_unpin_pages(ctx_obj);
1742
1743         return 0;
1744 }
1745
1746 /**
1747  * intel_lr_context_free() - free the LRC specific bits of a context
1748  * @ctx: the LR context to free.
1749  *
1750  * The real context freeing is done in i915_gem_context_free: this only
1751  * takes care of the bits that are LRC related: the per-engine backing
1752  * objects and the logical ringbuffer.
1753  */
1754 void intel_lr_context_free(struct intel_context *ctx)
1755 {
1756         int i;
1757
1758         for (i = 0; i < I915_NUM_RINGS; i++) {
1759                 struct drm_i915_gem_object *ctx_obj = ctx->engine[i].state;
1760
1761                 if (ctx_obj) {
1762                         struct intel_ringbuffer *ringbuf =
1763                                         ctx->engine[i].ringbuf;
1764                         struct intel_engine_cs *ring = ringbuf->ring;
1765
1766                         if (ctx == ring->default_context) {
1767                                 intel_unpin_ringbuffer_obj(ringbuf);
1768                                 i915_gem_object_ggtt_unpin(ctx_obj);
1769                         }
1770                         WARN_ON(ctx->engine[ring->id].pin_count);
1771                         intel_destroy_ringbuffer_obj(ringbuf);
1772                         kfree(ringbuf);
1773                         drm_gem_object_unreference(&ctx_obj->base);
1774                 }
1775         }
1776 }
1777
1778 static uint32_t get_lr_context_size(struct intel_engine_cs *ring)
1779 {
1780         int ret = 0;
1781
1782         WARN_ON(INTEL_INFO(ring->dev)->gen < 8);
1783
1784         switch (ring->id) {
1785         case RCS:
1786                 if (INTEL_INFO(ring->dev)->gen >= 9)
1787                         ret = GEN9_LR_CONTEXT_RENDER_SIZE;
1788                 else
1789                         ret = GEN8_LR_CONTEXT_RENDER_SIZE;
1790                 break;
1791         case VCS:
1792         case BCS:
1793         case VECS:
1794         case VCS2:
1795                 ret = GEN8_LR_CONTEXT_OTHER_SIZE;
1796                 break;
1797         }
1798
1799         return ret;
1800 }
1801
1802 static void lrc_setup_hardware_status_page(struct intel_engine_cs *ring,
1803                 struct drm_i915_gem_object *default_ctx_obj)
1804 {
1805         struct drm_i915_private *dev_priv = ring->dev->dev_private;
1806
1807         /* The status page is offset 0 from the default context object
1808          * in LRC mode. */
1809         ring->status_page.gfx_addr = i915_gem_obj_ggtt_offset(default_ctx_obj);
1810         ring->status_page.page_addr =
1811                         kmap(sg_page(default_ctx_obj->pages->sgl));
1812         ring->status_page.obj = default_ctx_obj;
1813
1814         I915_WRITE(RING_HWS_PGA(ring->mmio_base),
1815                         (u32)ring->status_page.gfx_addr);
1816         POSTING_READ(RING_HWS_PGA(ring->mmio_base));
1817 }
1818
1819 /**
1820  * intel_lr_context_deferred_create() - create the LRC specific bits of a context
1821  * @ctx: LR context to create.
1822  * @ring: engine to be used with the context.
1823  *
1824  * This function can be called more than once, with different engines, if we plan
1825  * to use the context with them. The context backing objects and the ringbuffers
1826  * (specially the ringbuffer backing objects) suck a lot of memory up, and that's why
1827  * the creation is a deferred call: it's better to make sure first that we need to use
1828  * a given ring with the context.
1829  *
1830  * Return: non-zero on error.
1831  */
1832 int intel_lr_context_deferred_create(struct intel_context *ctx,
1833                                      struct intel_engine_cs *ring)
1834 {
1835         const bool is_global_default_ctx = (ctx == ring->default_context);
1836         struct drm_device *dev = ring->dev;
1837         struct drm_i915_gem_object *ctx_obj;
1838         uint32_t context_size;
1839         struct intel_ringbuffer *ringbuf;
1840         int ret;
1841
1842         WARN_ON(ctx->legacy_hw_ctx.rcs_state != NULL);
1843         WARN_ON(ctx->engine[ring->id].state);
1844
1845         context_size = round_up(get_lr_context_size(ring), 4096);
1846
1847         ctx_obj = i915_gem_alloc_context_obj(dev, context_size);
1848         if (IS_ERR(ctx_obj)) {
1849                 ret = PTR_ERR(ctx_obj);
1850                 DRM_DEBUG_DRIVER("Alloc LRC backing obj failed: %d\n", ret);
1851                 return ret;
1852         }
1853
1854         if (is_global_default_ctx) {
1855                 ret = i915_gem_obj_ggtt_pin(ctx_obj, GEN8_LR_CONTEXT_ALIGN, 0);
1856                 if (ret) {
1857                         DRM_DEBUG_DRIVER("Pin LRC backing obj failed: %d\n",
1858                                         ret);
1859                         drm_gem_object_unreference(&ctx_obj->base);
1860                         return ret;
1861                 }
1862         }
1863
1864         ringbuf = kzalloc(sizeof(*ringbuf), GFP_KERNEL);
1865         if (!ringbuf) {
1866                 DRM_DEBUG_DRIVER("Failed to allocate ringbuffer %s\n",
1867                                 ring->name);
1868                 ret = -ENOMEM;
1869                 goto error_unpin_ctx;
1870         }
1871
1872         ringbuf->ring = ring;
1873
1874         ringbuf->size = 32 * PAGE_SIZE;
1875         ringbuf->effective_size = ringbuf->size;
1876         ringbuf->head = 0;
1877         ringbuf->tail = 0;
1878         ringbuf->last_retired_head = -1;
1879         intel_ring_update_space(ringbuf);
1880
1881         if (ringbuf->obj == NULL) {
1882                 ret = intel_alloc_ringbuffer_obj(dev, ringbuf);
1883                 if (ret) {
1884                         DRM_DEBUG_DRIVER(
1885                                 "Failed to allocate ringbuffer obj %s: %d\n",
1886                                 ring->name, ret);
1887                         goto error_free_rbuf;
1888                 }
1889
1890                 if (is_global_default_ctx) {
1891                         ret = intel_pin_and_map_ringbuffer_obj(dev, ringbuf);
1892                         if (ret) {
1893                                 DRM_ERROR(
1894                                         "Failed to pin and map ringbuffer %s: %d\n",
1895                                         ring->name, ret);
1896                                 goto error_destroy_rbuf;
1897                         }
1898                 }
1899
1900         }
1901
1902         ret = populate_lr_context(ctx, ctx_obj, ring, ringbuf);
1903         if (ret) {
1904                 DRM_DEBUG_DRIVER("Failed to populate LRC: %d\n", ret);
1905                 goto error;
1906         }
1907
1908         ctx->engine[ring->id].ringbuf = ringbuf;
1909         ctx->engine[ring->id].state = ctx_obj;
1910
1911         if (ctx == ring->default_context)
1912                 lrc_setup_hardware_status_page(ring, ctx_obj);
1913         else if (ring->id == RCS && !ctx->rcs_initialized) {
1914                 if (ring->init_context) {
1915                         ret = ring->init_context(ring, ctx);
1916                         if (ret) {
1917                                 DRM_ERROR("ring init context: %d\n", ret);
1918                                 ctx->engine[ring->id].ringbuf = NULL;
1919                                 ctx->engine[ring->id].state = NULL;
1920                                 goto error;
1921                         }
1922                 }
1923
1924                 ctx->rcs_initialized = true;
1925         }
1926
1927         return 0;
1928
1929 error:
1930         if (is_global_default_ctx)
1931                 intel_unpin_ringbuffer_obj(ringbuf);
1932 error_destroy_rbuf:
1933         intel_destroy_ringbuffer_obj(ringbuf);
1934 error_free_rbuf:
1935         kfree(ringbuf);
1936 error_unpin_ctx:
1937         if (is_global_default_ctx)
1938                 i915_gem_object_ggtt_unpin(ctx_obj);
1939         drm_gem_object_unreference(&ctx_obj->base);
1940         return ret;
1941 }
1942
1943 void intel_lr_context_reset(struct drm_device *dev,
1944                         struct intel_context *ctx)
1945 {
1946         struct drm_i915_private *dev_priv = dev->dev_private;
1947         struct intel_engine_cs *ring;
1948         int i;
1949
1950         for_each_ring(ring, dev_priv, i) {
1951                 struct drm_i915_gem_object *ctx_obj =
1952                                 ctx->engine[ring->id].state;
1953                 struct intel_ringbuffer *ringbuf =
1954                                 ctx->engine[ring->id].ringbuf;
1955                 uint32_t *reg_state;
1956                 struct page *page;
1957
1958                 if (!ctx_obj)
1959                         continue;
1960
1961                 if (i915_gem_object_get_pages(ctx_obj)) {
1962                         WARN(1, "Failed get_pages for context obj\n");
1963                         continue;
1964                 }
1965                 page = i915_gem_object_get_page(ctx_obj, 1);
1966                 reg_state = kmap_atomic(page);
1967
1968                 reg_state[CTX_RING_HEAD+1] = 0;
1969                 reg_state[CTX_RING_TAIL+1] = 0;
1970
1971                 kunmap_atomic(reg_state);
1972
1973                 ringbuf->head = 0;
1974                 ringbuf->tail = 0;
1975         }
1976 }