OSDN Git Service

drm/i915: Convert execlist_submit_contexts() for requests
[android-x86/kernel.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 = i915_page_dir_dma_addr((ppgtt), (n)); \
194         reg_state[CTX_PDP ## n ## _UDW+1] = upper_32_bits(_addr); \
195         reg_state[CTX_PDP ## n ## _LDW+1] = lower_32_bits(_addr); \
196 }
197
198 enum {
199         ADVANCED_CONTEXT = 0,
200         LEGACY_CONTEXT,
201         ADVANCED_AD_CONTEXT,
202         LEGACY_64B_CONTEXT
203 };
204 #define GEN8_CTX_MODE_SHIFT 3
205 enum {
206         FAULT_AND_HANG = 0,
207         FAULT_AND_HALT, /* Debug only */
208         FAULT_AND_STREAM,
209         FAULT_AND_CONTINUE /* Unsupported */
210 };
211 #define GEN8_CTX_ID_SHIFT 32
212 #define CTX_RCS_INDIRECT_CTX_OFFSET_DEFAULT  0x17
213
214 static int intel_lr_context_pin(struct intel_engine_cs *ring,
215                 struct intel_context *ctx);
216
217 /**
218  * intel_sanitize_enable_execlists() - sanitize i915.enable_execlists
219  * @dev: DRM device.
220  * @enable_execlists: value of i915.enable_execlists module parameter.
221  *
222  * Only certain platforms support Execlists (the prerequisites being
223  * support for Logical Ring Contexts and Aliasing PPGTT or better).
224  *
225  * Return: 1 if Execlists is supported and has to be enabled.
226  */
227 int intel_sanitize_enable_execlists(struct drm_device *dev, int enable_execlists)
228 {
229         WARN_ON(i915.enable_ppgtt == -1);
230
231         if (INTEL_INFO(dev)->gen >= 9)
232                 return 1;
233
234         if (enable_execlists == 0)
235                 return 0;
236
237         if (HAS_LOGICAL_RING_CONTEXTS(dev) && USES_PPGTT(dev) &&
238             i915.use_mmio_flip >= 0)
239                 return 1;
240
241         return 0;
242 }
243
244 /**
245  * intel_execlists_ctx_id() - get the Execlists Context ID
246  * @ctx_obj: Logical Ring Context backing object.
247  *
248  * Do not confuse with ctx->id! Unfortunately we have a name overload
249  * here: the old context ID we pass to userspace as a handler so that
250  * they can refer to a context, and the new context ID we pass to the
251  * ELSP so that the GPU can inform us of the context status via
252  * interrupts.
253  *
254  * Return: 20-bits globally unique context ID.
255  */
256 u32 intel_execlists_ctx_id(struct drm_i915_gem_object *ctx_obj)
257 {
258         u32 lrca = i915_gem_obj_ggtt_offset(ctx_obj);
259
260         /* LRCA is required to be 4K aligned so the more significant 20 bits
261          * are globally unique */
262         return lrca >> 12;
263 }
264
265 static uint64_t execlists_ctx_descriptor(struct intel_engine_cs *ring,
266                                          struct drm_i915_gem_object *ctx_obj)
267 {
268         struct drm_device *dev = ring->dev;
269         uint64_t desc;
270         uint64_t lrca = i915_gem_obj_ggtt_offset(ctx_obj);
271
272         WARN_ON(lrca & 0xFFFFFFFF00000FFFULL);
273
274         desc = GEN8_CTX_VALID;
275         desc |= LEGACY_CONTEXT << GEN8_CTX_MODE_SHIFT;
276         if (IS_GEN8(ctx_obj->base.dev))
277                 desc |= GEN8_CTX_L3LLC_COHERENT;
278         desc |= GEN8_CTX_PRIVILEGE;
279         desc |= lrca;
280         desc |= (u64)intel_execlists_ctx_id(ctx_obj) << GEN8_CTX_ID_SHIFT;
281
282         /* TODO: WaDisableLiteRestore when we start using semaphore
283          * signalling between Command Streamers */
284         /* desc |= GEN8_CTX_FORCE_RESTORE; */
285
286         /* WaEnableForceRestoreInCtxtDescForVCS:skl */
287         if (IS_GEN9(dev) &&
288             INTEL_REVID(dev) <= SKL_REVID_B0 &&
289             (ring->id == BCS || ring->id == VCS ||
290             ring->id == VECS || ring->id == VCS2))
291                 desc |= GEN8_CTX_FORCE_RESTORE;
292
293         return desc;
294 }
295
296 static void execlists_elsp_write(struct intel_engine_cs *ring,
297                                  struct drm_i915_gem_object *ctx_obj0,
298                                  struct drm_i915_gem_object *ctx_obj1)
299 {
300         struct drm_device *dev = ring->dev;
301         struct drm_i915_private *dev_priv = dev->dev_private;
302         uint64_t temp = 0;
303         uint32_t desc[4];
304
305         /* XXX: You must always write both descriptors in the order below. */
306         if (ctx_obj1)
307                 temp = execlists_ctx_descriptor(ring, ctx_obj1);
308         else
309                 temp = 0;
310         desc[1] = (u32)(temp >> 32);
311         desc[0] = (u32)temp;
312
313         temp = execlists_ctx_descriptor(ring, ctx_obj0);
314         desc[3] = (u32)(temp >> 32);
315         desc[2] = (u32)temp;
316
317         spin_lock(&dev_priv->uncore.lock);
318         intel_uncore_forcewake_get__locked(dev_priv, FORCEWAKE_ALL);
319         I915_WRITE_FW(RING_ELSP(ring), desc[1]);
320         I915_WRITE_FW(RING_ELSP(ring), desc[0]);
321         I915_WRITE_FW(RING_ELSP(ring), desc[3]);
322
323         /* The context is automatically loaded after the following */
324         I915_WRITE_FW(RING_ELSP(ring), desc[2]);
325
326         /* ELSP is a wo register, so use another nearby reg for posting instead */
327         POSTING_READ_FW(RING_EXECLIST_STATUS(ring));
328         intel_uncore_forcewake_put__locked(dev_priv, FORCEWAKE_ALL);
329         spin_unlock(&dev_priv->uncore.lock);
330 }
331
332 static int execlists_update_context(struct drm_i915_gem_object *ctx_obj,
333                                     struct drm_i915_gem_object *ring_obj,
334                                     struct i915_hw_ppgtt *ppgtt,
335                                     u32 tail)
336 {
337         struct page *page;
338         uint32_t *reg_state;
339
340         page = i915_gem_object_get_page(ctx_obj, 1);
341         reg_state = kmap_atomic(page);
342
343         reg_state[CTX_RING_TAIL+1] = tail;
344         reg_state[CTX_RING_BUFFER_START+1] = i915_gem_obj_ggtt_offset(ring_obj);
345
346         /* True PPGTT with dynamic page allocation: update PDP registers and
347          * point the unallocated PDPs to the scratch page
348          */
349         if (ppgtt) {
350                 ASSIGN_CTX_PDP(ppgtt, reg_state, 3);
351                 ASSIGN_CTX_PDP(ppgtt, reg_state, 2);
352                 ASSIGN_CTX_PDP(ppgtt, reg_state, 1);
353                 ASSIGN_CTX_PDP(ppgtt, reg_state, 0);
354         }
355
356         kunmap_atomic(reg_state);
357
358         return 0;
359 }
360
361 static void execlists_submit_requests(struct drm_i915_gem_request *rq0,
362                                       struct drm_i915_gem_request *rq1)
363 {
364         struct intel_engine_cs *ring = rq0->ring;
365         struct drm_i915_gem_object *ctx_obj0 = rq0->ctx->engine[ring->id].state;
366         struct drm_i915_gem_object *ctx_obj1 = NULL;
367
368         BUG_ON(!ctx_obj0);
369         WARN_ON(!i915_gem_obj_is_pinned(ctx_obj0));
370         WARN_ON(!i915_gem_obj_is_pinned(rq0->ringbuf->obj));
371
372         execlists_update_context(ctx_obj1, rq0->ringbuf->obj,
373                                  rq0->ctx->ppgtt, rq0->tail);
374
375         if (rq1) {
376                 ctx_obj1 = rq1->ctx->engine[ring->id].state;
377
378                 BUG_ON(!ctx_obj1);
379                 WARN_ON(!i915_gem_obj_is_pinned(ctx_obj1));
380                 WARN_ON(!i915_gem_obj_is_pinned(rq1->ringbuf->obj));
381
382                 execlists_update_context(ctx_obj1, rq1->ringbuf->obj,
383                                          rq1->ctx->ppgtt, rq1->tail);
384         }
385
386         execlists_elsp_write(ring, ctx_obj0, ctx_obj1);
387 }
388
389 static void execlists_context_unqueue(struct intel_engine_cs *ring)
390 {
391         struct drm_i915_gem_request *req0 = NULL, *req1 = NULL;
392         struct drm_i915_gem_request *cursor = NULL, *tmp = NULL;
393
394         assert_spin_locked(&ring->execlist_lock);
395
396         /*
397          * If irqs are not active generate a warning as batches that finish
398          * without the irqs may get lost and a GPU Hang may occur.
399          */
400         WARN_ON(!intel_irqs_enabled(ring->dev->dev_private));
401
402         if (list_empty(&ring->execlist_queue))
403                 return;
404
405         /* Try to read in pairs */
406         list_for_each_entry_safe(cursor, tmp, &ring->execlist_queue,
407                                  execlist_link) {
408                 if (!req0) {
409                         req0 = cursor;
410                 } else if (req0->ctx == cursor->ctx) {
411                         /* Same ctx: ignore first request, as second request
412                          * will update tail past first request's workload */
413                         cursor->elsp_submitted = req0->elsp_submitted;
414                         list_del(&req0->execlist_link);
415                         list_add_tail(&req0->execlist_link,
416                                 &ring->execlist_retired_req_list);
417                         req0 = cursor;
418                 } else {
419                         req1 = cursor;
420                         break;
421                 }
422         }
423
424         if (IS_GEN8(ring->dev) || IS_GEN9(ring->dev)) {
425                 /*
426                  * WaIdleLiteRestore: make sure we never cause a lite
427                  * restore with HEAD==TAIL
428                  */
429                 if (req0->elsp_submitted) {
430                         /*
431                          * Apply the wa NOOPS to prevent ring:HEAD == req:TAIL
432                          * as we resubmit the request. See gen8_emit_request()
433                          * for where we prepare the padding after the end of the
434                          * request.
435                          */
436                         struct intel_ringbuffer *ringbuf;
437
438                         ringbuf = req0->ctx->engine[ring->id].ringbuf;
439                         req0->tail += 8;
440                         req0->tail &= ringbuf->size - 1;
441                 }
442         }
443
444         WARN_ON(req1 && req1->elsp_submitted);
445
446         execlists_submit_requests(req0, req1);
447
448         req0->elsp_submitted++;
449         if (req1)
450                 req1->elsp_submitted++;
451 }
452
453 static bool execlists_check_remove_request(struct intel_engine_cs *ring,
454                                            u32 request_id)
455 {
456         struct drm_i915_gem_request *head_req;
457
458         assert_spin_locked(&ring->execlist_lock);
459
460         head_req = list_first_entry_or_null(&ring->execlist_queue,
461                                             struct drm_i915_gem_request,
462                                             execlist_link);
463
464         if (head_req != NULL) {
465                 struct drm_i915_gem_object *ctx_obj =
466                                 head_req->ctx->engine[ring->id].state;
467                 if (intel_execlists_ctx_id(ctx_obj) == request_id) {
468                         WARN(head_req->elsp_submitted == 0,
469                              "Never submitted head request\n");
470
471                         if (--head_req->elsp_submitted <= 0) {
472                                 list_del(&head_req->execlist_link);
473                                 list_add_tail(&head_req->execlist_link,
474                                         &ring->execlist_retired_req_list);
475                                 return true;
476                         }
477                 }
478         }
479
480         return false;
481 }
482
483 /**
484  * intel_lrc_irq_handler() - handle Context Switch interrupts
485  * @ring: Engine Command Streamer to handle.
486  *
487  * Check the unread Context Status Buffers and manage the submission of new
488  * contexts to the ELSP accordingly.
489  */
490 void intel_lrc_irq_handler(struct intel_engine_cs *ring)
491 {
492         struct drm_i915_private *dev_priv = ring->dev->dev_private;
493         u32 status_pointer;
494         u8 read_pointer;
495         u8 write_pointer;
496         u32 status;
497         u32 status_id;
498         u32 submit_contexts = 0;
499
500         status_pointer = I915_READ(RING_CONTEXT_STATUS_PTR(ring));
501
502         read_pointer = ring->next_context_status_buffer;
503         write_pointer = status_pointer & 0x07;
504         if (read_pointer > write_pointer)
505                 write_pointer += 6;
506
507         spin_lock(&ring->execlist_lock);
508
509         while (read_pointer < write_pointer) {
510                 read_pointer++;
511                 status = I915_READ(RING_CONTEXT_STATUS_BUF(ring) +
512                                 (read_pointer % 6) * 8);
513                 status_id = I915_READ(RING_CONTEXT_STATUS_BUF(ring) +
514                                 (read_pointer % 6) * 8 + 4);
515
516                 if (status & GEN8_CTX_STATUS_PREEMPTED) {
517                         if (status & GEN8_CTX_STATUS_LITE_RESTORE) {
518                                 if (execlists_check_remove_request(ring, status_id))
519                                         WARN(1, "Lite Restored request removed from queue\n");
520                         } else
521                                 WARN(1, "Preemption without Lite Restore\n");
522                 }
523
524                  if ((status & GEN8_CTX_STATUS_ACTIVE_IDLE) ||
525                      (status & GEN8_CTX_STATUS_ELEMENT_SWITCH)) {
526                         if (execlists_check_remove_request(ring, status_id))
527                                 submit_contexts++;
528                 }
529         }
530
531         if (submit_contexts != 0)
532                 execlists_context_unqueue(ring);
533
534         spin_unlock(&ring->execlist_lock);
535
536         WARN(submit_contexts > 2, "More than two context complete events?\n");
537         ring->next_context_status_buffer = write_pointer % 6;
538
539         I915_WRITE(RING_CONTEXT_STATUS_PTR(ring),
540                    ((u32)ring->next_context_status_buffer & 0x07) << 8);
541 }
542
543 static int execlists_context_queue(struct drm_i915_gem_request *request)
544 {
545         struct intel_engine_cs *ring = request->ring;
546         struct drm_i915_gem_request *cursor;
547         int num_elements = 0;
548
549         if (request->ctx != ring->default_context)
550                 intel_lr_context_pin(ring, request->ctx);
551
552         i915_gem_request_reference(request);
553
554         request->tail = request->ringbuf->tail;
555
556         spin_lock_irq(&ring->execlist_lock);
557
558         list_for_each_entry(cursor, &ring->execlist_queue, execlist_link)
559                 if (++num_elements > 2)
560                         break;
561
562         if (num_elements > 2) {
563                 struct drm_i915_gem_request *tail_req;
564
565                 tail_req = list_last_entry(&ring->execlist_queue,
566                                            struct drm_i915_gem_request,
567                                            execlist_link);
568
569                 if (request->ctx == tail_req->ctx) {
570                         WARN(tail_req->elsp_submitted != 0,
571                                 "More than 2 already-submitted reqs queued\n");
572                         list_del(&tail_req->execlist_link);
573                         list_add_tail(&tail_req->execlist_link,
574                                 &ring->execlist_retired_req_list);
575                 }
576         }
577
578         list_add_tail(&request->execlist_link, &ring->execlist_queue);
579         if (num_elements == 0)
580                 execlists_context_unqueue(ring);
581
582         spin_unlock_irq(&ring->execlist_lock);
583
584         return 0;
585 }
586
587 static int logical_ring_invalidate_all_caches(struct drm_i915_gem_request *req)
588 {
589         struct intel_engine_cs *ring = req->ring;
590         uint32_t flush_domains;
591         int ret;
592
593         flush_domains = 0;
594         if (ring->gpu_caches_dirty)
595                 flush_domains = I915_GEM_GPU_DOMAINS;
596
597         ret = ring->emit_flush(req, I915_GEM_GPU_DOMAINS, flush_domains);
598         if (ret)
599                 return ret;
600
601         ring->gpu_caches_dirty = false;
602         return 0;
603 }
604
605 static int execlists_move_to_gpu(struct drm_i915_gem_request *req,
606                                  struct list_head *vmas)
607 {
608         const unsigned other_rings = ~intel_ring_flag(req->ring);
609         struct i915_vma *vma;
610         uint32_t flush_domains = 0;
611         bool flush_chipset = false;
612         int ret;
613
614         list_for_each_entry(vma, vmas, exec_list) {
615                 struct drm_i915_gem_object *obj = vma->obj;
616
617                 if (obj->active & other_rings) {
618                         ret = i915_gem_object_sync(obj, req->ring, &req);
619                         if (ret)
620                                 return ret;
621                 }
622
623                 if (obj->base.write_domain & I915_GEM_DOMAIN_CPU)
624                         flush_chipset |= i915_gem_clflush_object(obj, false);
625
626                 flush_domains |= obj->base.write_domain;
627         }
628
629         if (flush_domains & I915_GEM_DOMAIN_GTT)
630                 wmb();
631
632         /* Unconditionally invalidate gpu caches and ensure that we do flush
633          * any residual writes from the previous batch.
634          */
635         return logical_ring_invalidate_all_caches(req);
636 }
637
638 int intel_logical_ring_alloc_request_extras(struct drm_i915_gem_request *request)
639 {
640         int ret;
641
642         if (request->ctx != request->ring->default_context) {
643                 ret = intel_lr_context_pin(request->ring, request->ctx);
644                 if (ret)
645                         return ret;
646         }
647
648         request->ringbuf = request->ctx->engine[request->ring->id].ringbuf;
649
650         return 0;
651 }
652
653 static int logical_ring_wait_for_space(struct drm_i915_gem_request *req,
654                                        int bytes)
655 {
656         struct intel_ringbuffer *ringbuf = req->ringbuf;
657         struct intel_engine_cs *ring = req->ring;
658         struct drm_i915_gem_request *target;
659         unsigned space;
660         int ret;
661
662         if (intel_ring_space(ringbuf) >= bytes)
663                 return 0;
664
665         /* The whole point of reserving space is to not wait! */
666         WARN_ON(ringbuf->reserved_in_use);
667
668         list_for_each_entry(target, &ring->request_list, list) {
669                 /*
670                  * The request queue is per-engine, so can contain requests
671                  * from multiple ringbuffers. Here, we must ignore any that
672                  * aren't from the ringbuffer we're considering.
673                  */
674                 if (target->ringbuf != ringbuf)
675                         continue;
676
677                 /* Would completion of this request free enough space? */
678                 space = __intel_ring_space(target->postfix, ringbuf->tail,
679                                            ringbuf->size);
680                 if (space >= bytes)
681                         break;
682         }
683
684         if (WARN_ON(&target->list == &ring->request_list))
685                 return -ENOSPC;
686
687         ret = i915_wait_request(target);
688         if (ret)
689                 return ret;
690
691         ringbuf->space = space;
692         return 0;
693 }
694
695 /*
696  * intel_logical_ring_advance_and_submit() - advance the tail and submit the workload
697  * @request: Request to advance the logical ringbuffer of.
698  *
699  * The tail is updated in our logical ringbuffer struct, not in the actual context. What
700  * really happens during submission is that the context and current tail will be placed
701  * on a queue waiting for the ELSP to be ready to accept a new context submission. At that
702  * point, the tail *inside* the context is updated and the ELSP written to.
703  */
704 static void
705 intel_logical_ring_advance_and_submit(struct drm_i915_gem_request *request)
706 {
707         struct intel_engine_cs *ring = request->ring;
708
709         intel_logical_ring_advance(request->ringbuf);
710
711         if (intel_ring_stopped(ring))
712                 return;
713
714         execlists_context_queue(request);
715 }
716
717 static void __wrap_ring_buffer(struct intel_ringbuffer *ringbuf)
718 {
719         uint32_t __iomem *virt;
720         int rem = ringbuf->size - ringbuf->tail;
721
722         virt = ringbuf->virtual_start + ringbuf->tail;
723         rem /= 4;
724         while (rem--)
725                 iowrite32(MI_NOOP, virt++);
726
727         ringbuf->tail = 0;
728         intel_ring_update_space(ringbuf);
729 }
730
731 static int logical_ring_prepare(struct drm_i915_gem_request *req, int bytes)
732 {
733         struct intel_ringbuffer *ringbuf = req->ringbuf;
734         int remain_usable = ringbuf->effective_size - ringbuf->tail;
735         int remain_actual = ringbuf->size - ringbuf->tail;
736         int ret, total_bytes, wait_bytes = 0;
737         bool need_wrap = false;
738
739         if (ringbuf->reserved_in_use)
740                 total_bytes = bytes;
741         else
742                 total_bytes = bytes + ringbuf->reserved_size;
743
744         if (unlikely(bytes > remain_usable)) {
745                 /*
746                  * Not enough space for the basic request. So need to flush
747                  * out the remainder and then wait for base + reserved.
748                  */
749                 wait_bytes = remain_actual + total_bytes;
750                 need_wrap = true;
751         } else {
752                 if (unlikely(total_bytes > remain_usable)) {
753                         /*
754                          * The base request will fit but the reserved space
755                          * falls off the end. So only need to to wait for the
756                          * reserved size after flushing out the remainder.
757                          */
758                         wait_bytes = remain_actual + ringbuf->reserved_size;
759                         need_wrap = true;
760                 } else if (total_bytes > ringbuf->space) {
761                         /* No wrapping required, just waiting. */
762                         wait_bytes = total_bytes;
763                 }
764         }
765
766         if (wait_bytes) {
767                 ret = logical_ring_wait_for_space(req, wait_bytes);
768                 if (unlikely(ret))
769                         return ret;
770
771                 if (need_wrap)
772                         __wrap_ring_buffer(ringbuf);
773         }
774
775         return 0;
776 }
777
778 /**
779  * intel_logical_ring_begin() - prepare the logical ringbuffer to accept some commands
780  *
781  * @request: The request to start some new work for
782  * @ctx: Logical ring context whose ringbuffer is being prepared.
783  * @num_dwords: number of DWORDs that we plan to write to the ringbuffer.
784  *
785  * The ringbuffer might not be ready to accept the commands right away (maybe it needs to
786  * be wrapped, or wait a bit for the tail to be updated). This function takes care of that
787  * and also preallocates a request (every workload submission is still mediated through
788  * requests, same as it did with legacy ringbuffer submission).
789  *
790  * Return: non-zero if the ringbuffer is not ready to be written to.
791  */
792 static int intel_logical_ring_begin(struct drm_i915_gem_request *req,
793                                     int num_dwords)
794 {
795         struct drm_i915_private *dev_priv;
796         int ret;
797
798         WARN_ON(req == NULL);
799         dev_priv = req->ring->dev->dev_private;
800
801         ret = i915_gem_check_wedge(&dev_priv->gpu_error,
802                                    dev_priv->mm.interruptible);
803         if (ret)
804                 return ret;
805
806         ret = logical_ring_prepare(req, num_dwords * sizeof(uint32_t));
807         if (ret)
808                 return ret;
809
810         req->ringbuf->space -= num_dwords * sizeof(uint32_t);
811         return 0;
812 }
813
814 int intel_logical_ring_reserve_space(struct drm_i915_gem_request *request)
815 {
816         /*
817          * The first call merely notes the reserve request and is common for
818          * all back ends. The subsequent localised _begin() call actually
819          * ensures that the reservation is available. Without the begin, if
820          * the request creator immediately submitted the request without
821          * adding any commands to it then there might not actually be
822          * sufficient room for the submission commands.
823          */
824         intel_ring_reserved_space_reserve(request->ringbuf, MIN_SPACE_FOR_ADD_REQUEST);
825
826         return intel_logical_ring_begin(request, 0);
827 }
828
829 /**
830  * execlists_submission() - submit a batchbuffer for execution, Execlists style
831  * @dev: DRM device.
832  * @file: DRM file.
833  * @ring: Engine Command Streamer to submit to.
834  * @ctx: Context to employ for this submission.
835  * @args: execbuffer call arguments.
836  * @vmas: list of vmas.
837  * @batch_obj: the batchbuffer to submit.
838  * @exec_start: batchbuffer start virtual address pointer.
839  * @dispatch_flags: translated execbuffer call flags.
840  *
841  * This is the evil twin version of i915_gem_ringbuffer_submission. It abstracts
842  * away the submission details of the execbuffer ioctl call.
843  *
844  * Return: non-zero if the submission fails.
845  */
846 int intel_execlists_submission(struct i915_execbuffer_params *params,
847                                struct drm_i915_gem_execbuffer2 *args,
848                                struct list_head *vmas)
849 {
850         struct drm_device       *dev = params->dev;
851         struct intel_engine_cs  *ring = params->ring;
852         struct drm_i915_private *dev_priv = dev->dev_private;
853         struct intel_ringbuffer *ringbuf = params->ctx->engine[ring->id].ringbuf;
854         u64 exec_start;
855         int instp_mode;
856         u32 instp_mask;
857         int ret;
858
859         instp_mode = args->flags & I915_EXEC_CONSTANTS_MASK;
860         instp_mask = I915_EXEC_CONSTANTS_MASK;
861         switch (instp_mode) {
862         case I915_EXEC_CONSTANTS_REL_GENERAL:
863         case I915_EXEC_CONSTANTS_ABSOLUTE:
864         case I915_EXEC_CONSTANTS_REL_SURFACE:
865                 if (instp_mode != 0 && ring != &dev_priv->ring[RCS]) {
866                         DRM_DEBUG("non-0 rel constants mode on non-RCS\n");
867                         return -EINVAL;
868                 }
869
870                 if (instp_mode != dev_priv->relative_constants_mode) {
871                         if (instp_mode == I915_EXEC_CONSTANTS_REL_SURFACE) {
872                                 DRM_DEBUG("rel surface constants mode invalid on gen5+\n");
873                                 return -EINVAL;
874                         }
875
876                         /* The HW changed the meaning on this bit on gen6 */
877                         instp_mask &= ~I915_EXEC_CONSTANTS_REL_SURFACE;
878                 }
879                 break;
880         default:
881                 DRM_DEBUG("execbuf with unknown constants: %d\n", instp_mode);
882                 return -EINVAL;
883         }
884
885         if (args->num_cliprects != 0) {
886                 DRM_DEBUG("clip rectangles are only valid on pre-gen5\n");
887                 return -EINVAL;
888         } else {
889                 if (args->DR4 == 0xffffffff) {
890                         DRM_DEBUG("UXA submitting garbage DR4, fixing up\n");
891                         args->DR4 = 0;
892                 }
893
894                 if (args->DR1 || args->DR4 || args->cliprects_ptr) {
895                         DRM_DEBUG("0 cliprects but dirt in cliprects fields\n");
896                         return -EINVAL;
897                 }
898         }
899
900         if (args->flags & I915_EXEC_GEN7_SOL_RESET) {
901                 DRM_DEBUG("sol reset is gen7 only\n");
902                 return -EINVAL;
903         }
904
905         ret = execlists_move_to_gpu(params->request, vmas);
906         if (ret)
907                 return ret;
908
909         if (ring == &dev_priv->ring[RCS] &&
910             instp_mode != dev_priv->relative_constants_mode) {
911                 ret = intel_logical_ring_begin(params->request, 4);
912                 if (ret)
913                         return ret;
914
915                 intel_logical_ring_emit(ringbuf, MI_NOOP);
916                 intel_logical_ring_emit(ringbuf, MI_LOAD_REGISTER_IMM(1));
917                 intel_logical_ring_emit(ringbuf, INSTPM);
918                 intel_logical_ring_emit(ringbuf, instp_mask << 16 | instp_mode);
919                 intel_logical_ring_advance(ringbuf);
920
921                 dev_priv->relative_constants_mode = instp_mode;
922         }
923
924         exec_start = params->batch_obj_vm_offset +
925                      args->batch_start_offset;
926
927         ret = ring->emit_bb_start(params->request, exec_start, params->dispatch_flags);
928         if (ret)
929                 return ret;
930
931         trace_i915_gem_ring_dispatch(params->request, params->dispatch_flags);
932
933         i915_gem_execbuffer_move_to_active(vmas, params->request);
934         i915_gem_execbuffer_retire_commands(params);
935
936         return 0;
937 }
938
939 void intel_execlists_retire_requests(struct intel_engine_cs *ring)
940 {
941         struct drm_i915_gem_request *req, *tmp;
942         struct list_head retired_list;
943
944         WARN_ON(!mutex_is_locked(&ring->dev->struct_mutex));
945         if (list_empty(&ring->execlist_retired_req_list))
946                 return;
947
948         INIT_LIST_HEAD(&retired_list);
949         spin_lock_irq(&ring->execlist_lock);
950         list_replace_init(&ring->execlist_retired_req_list, &retired_list);
951         spin_unlock_irq(&ring->execlist_lock);
952
953         list_for_each_entry_safe(req, tmp, &retired_list, execlist_link) {
954                 struct intel_context *ctx = req->ctx;
955                 struct drm_i915_gem_object *ctx_obj =
956                                 ctx->engine[ring->id].state;
957
958                 if (ctx_obj && (ctx != ring->default_context))
959                         intel_lr_context_unpin(ring, ctx);
960                 list_del(&req->execlist_link);
961                 i915_gem_request_unreference(req);
962         }
963 }
964
965 void intel_logical_ring_stop(struct intel_engine_cs *ring)
966 {
967         struct drm_i915_private *dev_priv = ring->dev->dev_private;
968         int ret;
969
970         if (!intel_ring_initialized(ring))
971                 return;
972
973         ret = intel_ring_idle(ring);
974         if (ret && !i915_reset_in_progress(&to_i915(ring->dev)->gpu_error))
975                 DRM_ERROR("failed to quiesce %s whilst cleaning up: %d\n",
976                           ring->name, ret);
977
978         /* TODO: Is this correct with Execlists enabled? */
979         I915_WRITE_MODE(ring, _MASKED_BIT_ENABLE(STOP_RING));
980         if (wait_for_atomic((I915_READ_MODE(ring) & MODE_IDLE) != 0, 1000)) {
981                 DRM_ERROR("%s :timed out trying to stop ring\n", ring->name);
982                 return;
983         }
984         I915_WRITE_MODE(ring, _MASKED_BIT_DISABLE(STOP_RING));
985 }
986
987 int logical_ring_flush_all_caches(struct drm_i915_gem_request *req)
988 {
989         struct intel_engine_cs *ring = req->ring;
990         int ret;
991
992         if (!ring->gpu_caches_dirty)
993                 return 0;
994
995         ret = ring->emit_flush(req, 0, I915_GEM_GPU_DOMAINS);
996         if (ret)
997                 return ret;
998
999         ring->gpu_caches_dirty = false;
1000         return 0;
1001 }
1002
1003 static int intel_lr_context_pin(struct intel_engine_cs *ring,
1004                 struct intel_context *ctx)
1005 {
1006         struct drm_i915_gem_object *ctx_obj = ctx->engine[ring->id].state;
1007         struct intel_ringbuffer *ringbuf = ctx->engine[ring->id].ringbuf;
1008         int ret = 0;
1009
1010         WARN_ON(!mutex_is_locked(&ring->dev->struct_mutex));
1011         if (ctx->engine[ring->id].pin_count++ == 0) {
1012                 ret = i915_gem_obj_ggtt_pin(ctx_obj,
1013                                 GEN8_LR_CONTEXT_ALIGN, 0);
1014                 if (ret)
1015                         goto reset_pin_count;
1016
1017                 ret = intel_pin_and_map_ringbuffer_obj(ring->dev, ringbuf);
1018                 if (ret)
1019                         goto unpin_ctx_obj;
1020         }
1021
1022         return ret;
1023
1024 unpin_ctx_obj:
1025         i915_gem_object_ggtt_unpin(ctx_obj);
1026 reset_pin_count:
1027         ctx->engine[ring->id].pin_count = 0;
1028
1029         return ret;
1030 }
1031
1032 void intel_lr_context_unpin(struct intel_engine_cs *ring,
1033                 struct intel_context *ctx)
1034 {
1035         struct drm_i915_gem_object *ctx_obj = ctx->engine[ring->id].state;
1036         struct intel_ringbuffer *ringbuf = ctx->engine[ring->id].ringbuf;
1037
1038         if (ctx_obj) {
1039                 WARN_ON(!mutex_is_locked(&ring->dev->struct_mutex));
1040                 if (--ctx->engine[ring->id].pin_count == 0) {
1041                         intel_unpin_ringbuffer_obj(ringbuf);
1042                         i915_gem_object_ggtt_unpin(ctx_obj);
1043                 }
1044         }
1045 }
1046
1047 static int intel_logical_ring_workarounds_emit(struct drm_i915_gem_request *req)
1048 {
1049         int ret, i;
1050         struct intel_engine_cs *ring = req->ring;
1051         struct intel_ringbuffer *ringbuf = req->ringbuf;
1052         struct drm_device *dev = ring->dev;
1053         struct drm_i915_private *dev_priv = dev->dev_private;
1054         struct i915_workarounds *w = &dev_priv->workarounds;
1055
1056         if (WARN_ON_ONCE(w->count == 0))
1057                 return 0;
1058
1059         ring->gpu_caches_dirty = true;
1060         ret = logical_ring_flush_all_caches(req);
1061         if (ret)
1062                 return ret;
1063
1064         ret = intel_logical_ring_begin(req, w->count * 2 + 2);
1065         if (ret)
1066                 return ret;
1067
1068         intel_logical_ring_emit(ringbuf, MI_LOAD_REGISTER_IMM(w->count));
1069         for (i = 0; i < w->count; i++) {
1070                 intel_logical_ring_emit(ringbuf, w->reg[i].addr);
1071                 intel_logical_ring_emit(ringbuf, w->reg[i].value);
1072         }
1073         intel_logical_ring_emit(ringbuf, MI_NOOP);
1074
1075         intel_logical_ring_advance(ringbuf);
1076
1077         ring->gpu_caches_dirty = true;
1078         ret = logical_ring_flush_all_caches(req);
1079         if (ret)
1080                 return ret;
1081
1082         return 0;
1083 }
1084
1085 #define wa_ctx_emit(batch, cmd)                                         \
1086         do {                                                            \
1087                 if (WARN_ON(index >= (PAGE_SIZE / sizeof(uint32_t)))) { \
1088                         return -ENOSPC;                                 \
1089                 }                                                       \
1090                 batch[index++] = (cmd);                                 \
1091         } while (0)
1092
1093
1094 /*
1095  * In this WA we need to set GEN8_L3SQCREG4[21:21] and reset it after
1096  * PIPE_CONTROL instruction. This is required for the flush to happen correctly
1097  * but there is a slight complication as this is applied in WA batch where the
1098  * values are only initialized once so we cannot take register value at the
1099  * beginning and reuse it further; hence we save its value to memory, upload a
1100  * constant value with bit21 set and then we restore it back with the saved value.
1101  * To simplify the WA, a constant value is formed by using the default value
1102  * of this register. This shouldn't be a problem because we are only modifying
1103  * it for a short period and this batch in non-premptible. We can ofcourse
1104  * use additional instructions that read the actual value of the register
1105  * at that time and set our bit of interest but it makes the WA complicated.
1106  *
1107  * This WA is also required for Gen9 so extracting as a function avoids
1108  * code duplication.
1109  */
1110 static inline int gen8_emit_flush_coherentl3_wa(struct intel_engine_cs *ring,
1111                                                 uint32_t *const batch,
1112                                                 uint32_t index)
1113 {
1114         uint32_t l3sqc4_flush = (0x40400000 | GEN8_LQSC_FLUSH_COHERENT_LINES);
1115
1116         wa_ctx_emit(batch, (MI_STORE_REGISTER_MEM_GEN8(1) |
1117                             MI_SRM_LRM_GLOBAL_GTT));
1118         wa_ctx_emit(batch, GEN8_L3SQCREG4);
1119         wa_ctx_emit(batch, ring->scratch.gtt_offset + 256);
1120         wa_ctx_emit(batch, 0);
1121
1122         wa_ctx_emit(batch, MI_LOAD_REGISTER_IMM(1));
1123         wa_ctx_emit(batch, GEN8_L3SQCREG4);
1124         wa_ctx_emit(batch, l3sqc4_flush);
1125
1126         wa_ctx_emit(batch, GFX_OP_PIPE_CONTROL(6));
1127         wa_ctx_emit(batch, (PIPE_CONTROL_CS_STALL |
1128                             PIPE_CONTROL_DC_FLUSH_ENABLE));
1129         wa_ctx_emit(batch, 0);
1130         wa_ctx_emit(batch, 0);
1131         wa_ctx_emit(batch, 0);
1132         wa_ctx_emit(batch, 0);
1133
1134         wa_ctx_emit(batch, (MI_LOAD_REGISTER_MEM_GEN8(1) |
1135                             MI_SRM_LRM_GLOBAL_GTT));
1136         wa_ctx_emit(batch, GEN8_L3SQCREG4);
1137         wa_ctx_emit(batch, ring->scratch.gtt_offset + 256);
1138         wa_ctx_emit(batch, 0);
1139
1140         return index;
1141 }
1142
1143 static inline uint32_t wa_ctx_start(struct i915_wa_ctx_bb *wa_ctx,
1144                                     uint32_t offset,
1145                                     uint32_t start_alignment)
1146 {
1147         return wa_ctx->offset = ALIGN(offset, start_alignment);
1148 }
1149
1150 static inline int wa_ctx_end(struct i915_wa_ctx_bb *wa_ctx,
1151                              uint32_t offset,
1152                              uint32_t size_alignment)
1153 {
1154         wa_ctx->size = offset - wa_ctx->offset;
1155
1156         WARN(wa_ctx->size % size_alignment,
1157              "wa_ctx_bb failed sanity checks: size %d is not aligned to %d\n",
1158              wa_ctx->size, size_alignment);
1159         return 0;
1160 }
1161
1162 /**
1163  * gen8_init_indirectctx_bb() - initialize indirect ctx batch with WA
1164  *
1165  * @ring: only applicable for RCS
1166  * @wa_ctx: structure representing wa_ctx
1167  *  offset: specifies start of the batch, should be cache-aligned. This is updated
1168  *    with the offset value received as input.
1169  *  size: size of the batch in DWORDS but HW expects in terms of cachelines
1170  * @batch: page in which WA are loaded
1171  * @offset: This field specifies the start of the batch, it should be
1172  *  cache-aligned otherwise it is adjusted accordingly.
1173  *  Typically we only have one indirect_ctx and per_ctx batch buffer which are
1174  *  initialized at the beginning and shared across all contexts but this field
1175  *  helps us to have multiple batches at different offsets and select them based
1176  *  on a criteria. At the moment this batch always start at the beginning of the page
1177  *  and at this point we don't have multiple wa_ctx batch buffers.
1178  *
1179  *  The number of WA applied are not known at the beginning; we use this field
1180  *  to return the no of DWORDS written.
1181  *
1182  *  It is to be noted that this batch does not contain MI_BATCH_BUFFER_END
1183  *  so it adds NOOPs as padding to make it cacheline aligned.
1184  *  MI_BATCH_BUFFER_END will be added to perctx batch and both of them together
1185  *  makes a complete batch buffer.
1186  *
1187  * Return: non-zero if we exceed the PAGE_SIZE limit.
1188  */
1189
1190 static int gen8_init_indirectctx_bb(struct intel_engine_cs *ring,
1191                                     struct i915_wa_ctx_bb *wa_ctx,
1192                                     uint32_t *const batch,
1193                                     uint32_t *offset)
1194 {
1195         uint32_t scratch_addr;
1196         uint32_t index = wa_ctx_start(wa_ctx, *offset, CACHELINE_DWORDS);
1197
1198         /* WaDisableCtxRestoreArbitration:bdw,chv */
1199         wa_ctx_emit(batch, MI_ARB_ON_OFF | MI_ARB_DISABLE);
1200
1201         /* WaFlushCoherentL3CacheLinesAtContextSwitch:bdw */
1202         if (IS_BROADWELL(ring->dev)) {
1203                 index = gen8_emit_flush_coherentl3_wa(ring, batch, index);
1204                 if (index < 0)
1205                         return index;
1206         }
1207
1208         /* WaClearSlmSpaceAtContextSwitch:bdw,chv */
1209         /* Actual scratch location is at 128 bytes offset */
1210         scratch_addr = ring->scratch.gtt_offset + 2*CACHELINE_BYTES;
1211
1212         wa_ctx_emit(batch, GFX_OP_PIPE_CONTROL(6));
1213         wa_ctx_emit(batch, (PIPE_CONTROL_FLUSH_L3 |
1214                             PIPE_CONTROL_GLOBAL_GTT_IVB |
1215                             PIPE_CONTROL_CS_STALL |
1216                             PIPE_CONTROL_QW_WRITE));
1217         wa_ctx_emit(batch, scratch_addr);
1218         wa_ctx_emit(batch, 0);
1219         wa_ctx_emit(batch, 0);
1220         wa_ctx_emit(batch, 0);
1221
1222         /* Pad to end of cacheline */
1223         while (index % CACHELINE_DWORDS)
1224                 wa_ctx_emit(batch, MI_NOOP);
1225
1226         /*
1227          * MI_BATCH_BUFFER_END is not required in Indirect ctx BB because
1228          * execution depends on the length specified in terms of cache lines
1229          * in the register CTX_RCS_INDIRECT_CTX
1230          */
1231
1232         return wa_ctx_end(wa_ctx, *offset = index, CACHELINE_DWORDS);
1233 }
1234
1235 /**
1236  * gen8_init_perctx_bb() - initialize per ctx batch with WA
1237  *
1238  * @ring: only applicable for RCS
1239  * @wa_ctx: structure representing wa_ctx
1240  *  offset: specifies start of the batch, should be cache-aligned.
1241  *  size: size of the batch in DWORDS but HW expects in terms of cachelines
1242  * @batch: page in which WA are loaded
1243  * @offset: This field specifies the start of this batch.
1244  *   This batch is started immediately after indirect_ctx batch. Since we ensure
1245  *   that indirect_ctx ends on a cacheline this batch is aligned automatically.
1246  *
1247  *   The number of DWORDS written are returned using this field.
1248  *
1249  *  This batch is terminated with MI_BATCH_BUFFER_END and so we need not add padding
1250  *  to align it with cacheline as padding after MI_BATCH_BUFFER_END is redundant.
1251  */
1252 static int gen8_init_perctx_bb(struct intel_engine_cs *ring,
1253                                struct i915_wa_ctx_bb *wa_ctx,
1254                                uint32_t *const batch,
1255                                uint32_t *offset)
1256 {
1257         uint32_t index = wa_ctx_start(wa_ctx, *offset, CACHELINE_DWORDS);
1258
1259         /* WaDisableCtxRestoreArbitration:bdw,chv */
1260         wa_ctx_emit(batch, MI_ARB_ON_OFF | MI_ARB_ENABLE);
1261
1262         wa_ctx_emit(batch, MI_BATCH_BUFFER_END);
1263
1264         return wa_ctx_end(wa_ctx, *offset = index, 1);
1265 }
1266
1267 static int lrc_setup_wa_ctx_obj(struct intel_engine_cs *ring, u32 size)
1268 {
1269         int ret;
1270
1271         ring->wa_ctx.obj = i915_gem_alloc_object(ring->dev, PAGE_ALIGN(size));
1272         if (!ring->wa_ctx.obj) {
1273                 DRM_DEBUG_DRIVER("alloc LRC WA ctx backing obj failed.\n");
1274                 return -ENOMEM;
1275         }
1276
1277         ret = i915_gem_obj_ggtt_pin(ring->wa_ctx.obj, PAGE_SIZE, 0);
1278         if (ret) {
1279                 DRM_DEBUG_DRIVER("pin LRC WA ctx backing obj failed: %d\n",
1280                                  ret);
1281                 drm_gem_object_unreference(&ring->wa_ctx.obj->base);
1282                 return ret;
1283         }
1284
1285         return 0;
1286 }
1287
1288 static void lrc_destroy_wa_ctx_obj(struct intel_engine_cs *ring)
1289 {
1290         if (ring->wa_ctx.obj) {
1291                 i915_gem_object_ggtt_unpin(ring->wa_ctx.obj);
1292                 drm_gem_object_unreference(&ring->wa_ctx.obj->base);
1293                 ring->wa_ctx.obj = NULL;
1294         }
1295 }
1296
1297 static int intel_init_workaround_bb(struct intel_engine_cs *ring)
1298 {
1299         int ret;
1300         uint32_t *batch;
1301         uint32_t offset;
1302         struct page *page;
1303         struct i915_ctx_workarounds *wa_ctx = &ring->wa_ctx;
1304
1305         WARN_ON(ring->id != RCS);
1306
1307         /* update this when WA for higher Gen are added */
1308         if (WARN(INTEL_INFO(ring->dev)->gen > 8,
1309                  "WA batch buffer is not initialized for Gen%d\n",
1310                  INTEL_INFO(ring->dev)->gen))
1311                 return 0;
1312
1313         /* some WA perform writes to scratch page, ensure it is valid */
1314         if (ring->scratch.obj == NULL) {
1315                 DRM_ERROR("scratch page not allocated for %s\n", ring->name);
1316                 return -EINVAL;
1317         }
1318
1319         ret = lrc_setup_wa_ctx_obj(ring, PAGE_SIZE);
1320         if (ret) {
1321                 DRM_DEBUG_DRIVER("Failed to setup context WA page: %d\n", ret);
1322                 return ret;
1323         }
1324
1325         page = i915_gem_object_get_page(wa_ctx->obj, 0);
1326         batch = kmap_atomic(page);
1327         offset = 0;
1328
1329         if (INTEL_INFO(ring->dev)->gen == 8) {
1330                 ret = gen8_init_indirectctx_bb(ring,
1331                                                &wa_ctx->indirect_ctx,
1332                                                batch,
1333                                                &offset);
1334                 if (ret)
1335                         goto out;
1336
1337                 ret = gen8_init_perctx_bb(ring,
1338                                           &wa_ctx->per_ctx,
1339                                           batch,
1340                                           &offset);
1341                 if (ret)
1342                         goto out;
1343         }
1344
1345 out:
1346         kunmap_atomic(batch);
1347         if (ret)
1348                 lrc_destroy_wa_ctx_obj(ring);
1349
1350         return ret;
1351 }
1352
1353 static int gen8_init_common_ring(struct intel_engine_cs *ring)
1354 {
1355         struct drm_device *dev = ring->dev;
1356         struct drm_i915_private *dev_priv = dev->dev_private;
1357
1358         I915_WRITE_IMR(ring, ~(ring->irq_enable_mask | ring->irq_keep_mask));
1359         I915_WRITE(RING_HWSTAM(ring->mmio_base), 0xffffffff);
1360
1361         I915_WRITE(RING_MODE_GEN7(ring),
1362                    _MASKED_BIT_DISABLE(GFX_REPLAY_MODE) |
1363                    _MASKED_BIT_ENABLE(GFX_RUN_LIST_ENABLE));
1364         POSTING_READ(RING_MODE_GEN7(ring));
1365         ring->next_context_status_buffer = 0;
1366         DRM_DEBUG_DRIVER("Execlists enabled for %s\n", ring->name);
1367
1368         memset(&ring->hangcheck, 0, sizeof(ring->hangcheck));
1369
1370         return 0;
1371 }
1372
1373 static int gen8_init_render_ring(struct intel_engine_cs *ring)
1374 {
1375         struct drm_device *dev = ring->dev;
1376         struct drm_i915_private *dev_priv = dev->dev_private;
1377         int ret;
1378
1379         ret = gen8_init_common_ring(ring);
1380         if (ret)
1381                 return ret;
1382
1383         /* We need to disable the AsyncFlip performance optimisations in order
1384          * to use MI_WAIT_FOR_EVENT within the CS. It should already be
1385          * programmed to '1' on all products.
1386          *
1387          * WaDisableAsyncFlipPerfMode:snb,ivb,hsw,vlv,bdw,chv
1388          */
1389         I915_WRITE(MI_MODE, _MASKED_BIT_ENABLE(ASYNC_FLIP_PERF_DISABLE));
1390
1391         I915_WRITE(INSTPM, _MASKED_BIT_ENABLE(INSTPM_FORCE_ORDERING));
1392
1393         return init_workarounds_ring(ring);
1394 }
1395
1396 static int gen9_init_render_ring(struct intel_engine_cs *ring)
1397 {
1398         int ret;
1399
1400         ret = gen8_init_common_ring(ring);
1401         if (ret)
1402                 return ret;
1403
1404         return init_workarounds_ring(ring);
1405 }
1406
1407 static int intel_logical_ring_emit_pdps(struct drm_i915_gem_request *req)
1408 {
1409         struct i915_hw_ppgtt *ppgtt = req->ctx->ppgtt;
1410         struct intel_engine_cs *ring = req->ring;
1411         struct intel_ringbuffer *ringbuf = req->ringbuf;
1412         const int num_lri_cmds = GEN8_LEGACY_PDPES * 2;
1413         int i, ret;
1414
1415         ret = intel_logical_ring_begin(req, num_lri_cmds * 2 + 2);
1416         if (ret)
1417                 return ret;
1418
1419         intel_logical_ring_emit(ringbuf, MI_LOAD_REGISTER_IMM(num_lri_cmds));
1420         for (i = GEN8_LEGACY_PDPES - 1; i >= 0; i--) {
1421                 const dma_addr_t pd_daddr = i915_page_dir_dma_addr(ppgtt, i);
1422
1423                 intel_logical_ring_emit(ringbuf, GEN8_RING_PDP_UDW(ring, i));
1424                 intel_logical_ring_emit(ringbuf, upper_32_bits(pd_daddr));
1425                 intel_logical_ring_emit(ringbuf, GEN8_RING_PDP_LDW(ring, i));
1426                 intel_logical_ring_emit(ringbuf, lower_32_bits(pd_daddr));
1427         }
1428
1429         intel_logical_ring_emit(ringbuf, MI_NOOP);
1430         intel_logical_ring_advance(ringbuf);
1431
1432         return 0;
1433 }
1434
1435 static int gen8_emit_bb_start(struct drm_i915_gem_request *req,
1436                               u64 offset, unsigned dispatch_flags)
1437 {
1438         struct intel_ringbuffer *ringbuf = req->ringbuf;
1439         bool ppgtt = !(dispatch_flags & I915_DISPATCH_SECURE);
1440         int ret;
1441
1442         /* Don't rely in hw updating PDPs, specially in lite-restore.
1443          * Ideally, we should set Force PD Restore in ctx descriptor,
1444          * but we can't. Force Restore would be a second option, but
1445          * it is unsafe in case of lite-restore (because the ctx is
1446          * not idle). */
1447         if (req->ctx->ppgtt &&
1448             (intel_ring_flag(req->ring) & req->ctx->ppgtt->pd_dirty_rings)) {
1449                 ret = intel_logical_ring_emit_pdps(req);
1450                 if (ret)
1451                         return ret;
1452
1453                 req->ctx->ppgtt->pd_dirty_rings &= ~intel_ring_flag(req->ring);
1454         }
1455
1456         ret = intel_logical_ring_begin(req, 4);
1457         if (ret)
1458                 return ret;
1459
1460         /* FIXME(BDW): Address space and security selectors. */
1461         intel_logical_ring_emit(ringbuf, MI_BATCH_BUFFER_START_GEN8 |
1462                                 (ppgtt<<8) |
1463                                 (dispatch_flags & I915_DISPATCH_RS ?
1464                                  MI_BATCH_RESOURCE_STREAMER : 0));
1465         intel_logical_ring_emit(ringbuf, lower_32_bits(offset));
1466         intel_logical_ring_emit(ringbuf, upper_32_bits(offset));
1467         intel_logical_ring_emit(ringbuf, MI_NOOP);
1468         intel_logical_ring_advance(ringbuf);
1469
1470         return 0;
1471 }
1472
1473 static bool gen8_logical_ring_get_irq(struct intel_engine_cs *ring)
1474 {
1475         struct drm_device *dev = ring->dev;
1476         struct drm_i915_private *dev_priv = dev->dev_private;
1477         unsigned long flags;
1478
1479         if (WARN_ON(!intel_irqs_enabled(dev_priv)))
1480                 return false;
1481
1482         spin_lock_irqsave(&dev_priv->irq_lock, flags);
1483         if (ring->irq_refcount++ == 0) {
1484                 I915_WRITE_IMR(ring, ~(ring->irq_enable_mask | ring->irq_keep_mask));
1485                 POSTING_READ(RING_IMR(ring->mmio_base));
1486         }
1487         spin_unlock_irqrestore(&dev_priv->irq_lock, flags);
1488
1489         return true;
1490 }
1491
1492 static void gen8_logical_ring_put_irq(struct intel_engine_cs *ring)
1493 {
1494         struct drm_device *dev = ring->dev;
1495         struct drm_i915_private *dev_priv = dev->dev_private;
1496         unsigned long flags;
1497
1498         spin_lock_irqsave(&dev_priv->irq_lock, flags);
1499         if (--ring->irq_refcount == 0) {
1500                 I915_WRITE_IMR(ring, ~ring->irq_keep_mask);
1501                 POSTING_READ(RING_IMR(ring->mmio_base));
1502         }
1503         spin_unlock_irqrestore(&dev_priv->irq_lock, flags);
1504 }
1505
1506 static int gen8_emit_flush(struct drm_i915_gem_request *request,
1507                            u32 invalidate_domains,
1508                            u32 unused)
1509 {
1510         struct intel_ringbuffer *ringbuf = request->ringbuf;
1511         struct intel_engine_cs *ring = ringbuf->ring;
1512         struct drm_device *dev = ring->dev;
1513         struct drm_i915_private *dev_priv = dev->dev_private;
1514         uint32_t cmd;
1515         int ret;
1516
1517         ret = intel_logical_ring_begin(request, 4);
1518         if (ret)
1519                 return ret;
1520
1521         cmd = MI_FLUSH_DW + 1;
1522
1523         /* We always require a command barrier so that subsequent
1524          * commands, such as breadcrumb interrupts, are strictly ordered
1525          * wrt the contents of the write cache being flushed to memory
1526          * (and thus being coherent from the CPU).
1527          */
1528         cmd |= MI_FLUSH_DW_STORE_INDEX | MI_FLUSH_DW_OP_STOREDW;
1529
1530         if (invalidate_domains & I915_GEM_GPU_DOMAINS) {
1531                 cmd |= MI_INVALIDATE_TLB;
1532                 if (ring == &dev_priv->ring[VCS])
1533                         cmd |= MI_INVALIDATE_BSD;
1534         }
1535
1536         intel_logical_ring_emit(ringbuf, cmd);
1537         intel_logical_ring_emit(ringbuf,
1538                                 I915_GEM_HWS_SCRATCH_ADDR |
1539                                 MI_FLUSH_DW_USE_GTT);
1540         intel_logical_ring_emit(ringbuf, 0); /* upper addr */
1541         intel_logical_ring_emit(ringbuf, 0); /* value */
1542         intel_logical_ring_advance(ringbuf);
1543
1544         return 0;
1545 }
1546
1547 static int gen8_emit_flush_render(struct drm_i915_gem_request *request,
1548                                   u32 invalidate_domains,
1549                                   u32 flush_domains)
1550 {
1551         struct intel_ringbuffer *ringbuf = request->ringbuf;
1552         struct intel_engine_cs *ring = ringbuf->ring;
1553         u32 scratch_addr = ring->scratch.gtt_offset + 2 * CACHELINE_BYTES;
1554         bool vf_flush_wa;
1555         u32 flags = 0;
1556         int ret;
1557
1558         flags |= PIPE_CONTROL_CS_STALL;
1559
1560         if (flush_domains) {
1561                 flags |= PIPE_CONTROL_RENDER_TARGET_CACHE_FLUSH;
1562                 flags |= PIPE_CONTROL_DEPTH_CACHE_FLUSH;
1563         }
1564
1565         if (invalidate_domains) {
1566                 flags |= PIPE_CONTROL_TLB_INVALIDATE;
1567                 flags |= PIPE_CONTROL_INSTRUCTION_CACHE_INVALIDATE;
1568                 flags |= PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE;
1569                 flags |= PIPE_CONTROL_VF_CACHE_INVALIDATE;
1570                 flags |= PIPE_CONTROL_CONST_CACHE_INVALIDATE;
1571                 flags |= PIPE_CONTROL_STATE_CACHE_INVALIDATE;
1572                 flags |= PIPE_CONTROL_QW_WRITE;
1573                 flags |= PIPE_CONTROL_GLOBAL_GTT_IVB;
1574         }
1575
1576         /*
1577          * On GEN9+ Before VF_CACHE_INVALIDATE we need to emit a NULL pipe
1578          * control.
1579          */
1580         vf_flush_wa = INTEL_INFO(ring->dev)->gen >= 9 &&
1581                       flags & PIPE_CONTROL_VF_CACHE_INVALIDATE;
1582
1583         ret = intel_logical_ring_begin(request, vf_flush_wa ? 12 : 6);
1584         if (ret)
1585                 return ret;
1586
1587         if (vf_flush_wa) {
1588                 intel_logical_ring_emit(ringbuf, GFX_OP_PIPE_CONTROL(6));
1589                 intel_logical_ring_emit(ringbuf, 0);
1590                 intel_logical_ring_emit(ringbuf, 0);
1591                 intel_logical_ring_emit(ringbuf, 0);
1592                 intel_logical_ring_emit(ringbuf, 0);
1593                 intel_logical_ring_emit(ringbuf, 0);
1594         }
1595
1596         intel_logical_ring_emit(ringbuf, GFX_OP_PIPE_CONTROL(6));
1597         intel_logical_ring_emit(ringbuf, flags);
1598         intel_logical_ring_emit(ringbuf, scratch_addr);
1599         intel_logical_ring_emit(ringbuf, 0);
1600         intel_logical_ring_emit(ringbuf, 0);
1601         intel_logical_ring_emit(ringbuf, 0);
1602         intel_logical_ring_advance(ringbuf);
1603
1604         return 0;
1605 }
1606
1607 static u32 gen8_get_seqno(struct intel_engine_cs *ring, bool lazy_coherency)
1608 {
1609         return intel_read_status_page(ring, I915_GEM_HWS_INDEX);
1610 }
1611
1612 static void gen8_set_seqno(struct intel_engine_cs *ring, u32 seqno)
1613 {
1614         intel_write_status_page(ring, I915_GEM_HWS_INDEX, seqno);
1615 }
1616
1617 static int gen8_emit_request(struct drm_i915_gem_request *request)
1618 {
1619         struct intel_ringbuffer *ringbuf = request->ringbuf;
1620         struct intel_engine_cs *ring = ringbuf->ring;
1621         u32 cmd;
1622         int ret;
1623
1624         /*
1625          * Reserve space for 2 NOOPs at the end of each request to be
1626          * used as a workaround for not being allowed to do lite
1627          * restore with HEAD==TAIL (WaIdleLiteRestore).
1628          */
1629         ret = intel_logical_ring_begin(request, 8);
1630         if (ret)
1631                 return ret;
1632
1633         cmd = MI_STORE_DWORD_IMM_GEN4;
1634         cmd |= MI_GLOBAL_GTT;
1635
1636         intel_logical_ring_emit(ringbuf, cmd);
1637         intel_logical_ring_emit(ringbuf,
1638                                 (ring->status_page.gfx_addr +
1639                                 (I915_GEM_HWS_INDEX << MI_STORE_DWORD_INDEX_SHIFT)));
1640         intel_logical_ring_emit(ringbuf, 0);
1641         intel_logical_ring_emit(ringbuf, i915_gem_request_get_seqno(request));
1642         intel_logical_ring_emit(ringbuf, MI_USER_INTERRUPT);
1643         intel_logical_ring_emit(ringbuf, MI_NOOP);
1644         intel_logical_ring_advance_and_submit(request);
1645
1646         /*
1647          * Here we add two extra NOOPs as padding to avoid
1648          * lite restore of a context with HEAD==TAIL.
1649          */
1650         intel_logical_ring_emit(ringbuf, MI_NOOP);
1651         intel_logical_ring_emit(ringbuf, MI_NOOP);
1652         intel_logical_ring_advance(ringbuf);
1653
1654         return 0;
1655 }
1656
1657 static int intel_lr_context_render_state_init(struct drm_i915_gem_request *req)
1658 {
1659         struct render_state so;
1660         int ret;
1661
1662         ret = i915_gem_render_state_prepare(req->ring, &so);
1663         if (ret)
1664                 return ret;
1665
1666         if (so.rodata == NULL)
1667                 return 0;
1668
1669         ret = req->ring->emit_bb_start(req, so.ggtt_offset,
1670                                        I915_DISPATCH_SECURE);
1671         if (ret)
1672                 goto out;
1673
1674         i915_vma_move_to_active(i915_gem_obj_to_ggtt(so.obj), req);
1675
1676 out:
1677         i915_gem_render_state_fini(&so);
1678         return ret;
1679 }
1680
1681 static int gen8_init_rcs_context(struct drm_i915_gem_request *req)
1682 {
1683         int ret;
1684
1685         ret = intel_logical_ring_workarounds_emit(req);
1686         if (ret)
1687                 return ret;
1688
1689         return intel_lr_context_render_state_init(req);
1690 }
1691
1692 /**
1693  * intel_logical_ring_cleanup() - deallocate the Engine Command Streamer
1694  *
1695  * @ring: Engine Command Streamer.
1696  *
1697  */
1698 void intel_logical_ring_cleanup(struct intel_engine_cs *ring)
1699 {
1700         struct drm_i915_private *dev_priv;
1701
1702         if (!intel_ring_initialized(ring))
1703                 return;
1704
1705         dev_priv = ring->dev->dev_private;
1706
1707         intel_logical_ring_stop(ring);
1708         WARN_ON((I915_READ_MODE(ring) & MODE_IDLE) == 0);
1709
1710         if (ring->cleanup)
1711                 ring->cleanup(ring);
1712
1713         i915_cmd_parser_fini_ring(ring);
1714         i915_gem_batch_pool_fini(&ring->batch_pool);
1715
1716         if (ring->status_page.obj) {
1717                 kunmap(sg_page(ring->status_page.obj->pages->sgl));
1718                 ring->status_page.obj = NULL;
1719         }
1720
1721         lrc_destroy_wa_ctx_obj(ring);
1722 }
1723
1724 static int logical_ring_init(struct drm_device *dev, struct intel_engine_cs *ring)
1725 {
1726         int ret;
1727
1728         /* Intentionally left blank. */
1729         ring->buffer = NULL;
1730
1731         ring->dev = dev;
1732         INIT_LIST_HEAD(&ring->active_list);
1733         INIT_LIST_HEAD(&ring->request_list);
1734         i915_gem_batch_pool_init(dev, &ring->batch_pool);
1735         init_waitqueue_head(&ring->irq_queue);
1736
1737         INIT_LIST_HEAD(&ring->execlist_queue);
1738         INIT_LIST_HEAD(&ring->execlist_retired_req_list);
1739         spin_lock_init(&ring->execlist_lock);
1740
1741         ret = i915_cmd_parser_init_ring(ring);
1742         if (ret)
1743                 return ret;
1744
1745         ret = intel_lr_context_deferred_create(ring->default_context, ring);
1746
1747         return ret;
1748 }
1749
1750 static int logical_render_ring_init(struct drm_device *dev)
1751 {
1752         struct drm_i915_private *dev_priv = dev->dev_private;
1753         struct intel_engine_cs *ring = &dev_priv->ring[RCS];
1754         int ret;
1755
1756         ring->name = "render ring";
1757         ring->id = RCS;
1758         ring->mmio_base = RENDER_RING_BASE;
1759         ring->irq_enable_mask =
1760                 GT_RENDER_USER_INTERRUPT << GEN8_RCS_IRQ_SHIFT;
1761         ring->irq_keep_mask =
1762                 GT_CONTEXT_SWITCH_INTERRUPT << GEN8_RCS_IRQ_SHIFT;
1763         if (HAS_L3_DPF(dev))
1764                 ring->irq_keep_mask |= GT_RENDER_L3_PARITY_ERROR_INTERRUPT;
1765
1766         if (INTEL_INFO(dev)->gen >= 9)
1767                 ring->init_hw = gen9_init_render_ring;
1768         else
1769                 ring->init_hw = gen8_init_render_ring;
1770         ring->init_context = gen8_init_rcs_context;
1771         ring->cleanup = intel_fini_pipe_control;
1772         ring->get_seqno = gen8_get_seqno;
1773         ring->set_seqno = gen8_set_seqno;
1774         ring->emit_request = gen8_emit_request;
1775         ring->emit_flush = gen8_emit_flush_render;
1776         ring->irq_get = gen8_logical_ring_get_irq;
1777         ring->irq_put = gen8_logical_ring_put_irq;
1778         ring->emit_bb_start = gen8_emit_bb_start;
1779
1780         ring->dev = dev;
1781
1782         ret = intel_init_pipe_control(ring);
1783         if (ret)
1784                 return ret;
1785
1786         ret = intel_init_workaround_bb(ring);
1787         if (ret) {
1788                 /*
1789                  * We continue even if we fail to initialize WA batch
1790                  * because we only expect rare glitches but nothing
1791                  * critical to prevent us from using GPU
1792                  */
1793                 DRM_ERROR("WA batch buffer initialization failed: %d\n",
1794                           ret);
1795         }
1796
1797         ret = logical_ring_init(dev, ring);
1798         if (ret) {
1799                 lrc_destroy_wa_ctx_obj(ring);
1800         }
1801
1802         return ret;
1803 }
1804
1805 static int logical_bsd_ring_init(struct drm_device *dev)
1806 {
1807         struct drm_i915_private *dev_priv = dev->dev_private;
1808         struct intel_engine_cs *ring = &dev_priv->ring[VCS];
1809
1810         ring->name = "bsd ring";
1811         ring->id = VCS;
1812         ring->mmio_base = GEN6_BSD_RING_BASE;
1813         ring->irq_enable_mask =
1814                 GT_RENDER_USER_INTERRUPT << GEN8_VCS1_IRQ_SHIFT;
1815         ring->irq_keep_mask =
1816                 GT_CONTEXT_SWITCH_INTERRUPT << GEN8_VCS1_IRQ_SHIFT;
1817
1818         ring->init_hw = gen8_init_common_ring;
1819         ring->get_seqno = gen8_get_seqno;
1820         ring->set_seqno = gen8_set_seqno;
1821         ring->emit_request = gen8_emit_request;
1822         ring->emit_flush = gen8_emit_flush;
1823         ring->irq_get = gen8_logical_ring_get_irq;
1824         ring->irq_put = gen8_logical_ring_put_irq;
1825         ring->emit_bb_start = gen8_emit_bb_start;
1826
1827         return logical_ring_init(dev, ring);
1828 }
1829
1830 static int logical_bsd2_ring_init(struct drm_device *dev)
1831 {
1832         struct drm_i915_private *dev_priv = dev->dev_private;
1833         struct intel_engine_cs *ring = &dev_priv->ring[VCS2];
1834
1835         ring->name = "bds2 ring";
1836         ring->id = VCS2;
1837         ring->mmio_base = GEN8_BSD2_RING_BASE;
1838         ring->irq_enable_mask =
1839                 GT_RENDER_USER_INTERRUPT << GEN8_VCS2_IRQ_SHIFT;
1840         ring->irq_keep_mask =
1841                 GT_CONTEXT_SWITCH_INTERRUPT << GEN8_VCS2_IRQ_SHIFT;
1842
1843         ring->init_hw = gen8_init_common_ring;
1844         ring->get_seqno = gen8_get_seqno;
1845         ring->set_seqno = gen8_set_seqno;
1846         ring->emit_request = gen8_emit_request;
1847         ring->emit_flush = gen8_emit_flush;
1848         ring->irq_get = gen8_logical_ring_get_irq;
1849         ring->irq_put = gen8_logical_ring_put_irq;
1850         ring->emit_bb_start = gen8_emit_bb_start;
1851
1852         return logical_ring_init(dev, ring);
1853 }
1854
1855 static int logical_blt_ring_init(struct drm_device *dev)
1856 {
1857         struct drm_i915_private *dev_priv = dev->dev_private;
1858         struct intel_engine_cs *ring = &dev_priv->ring[BCS];
1859
1860         ring->name = "blitter ring";
1861         ring->id = BCS;
1862         ring->mmio_base = BLT_RING_BASE;
1863         ring->irq_enable_mask =
1864                 GT_RENDER_USER_INTERRUPT << GEN8_BCS_IRQ_SHIFT;
1865         ring->irq_keep_mask =
1866                 GT_CONTEXT_SWITCH_INTERRUPT << GEN8_BCS_IRQ_SHIFT;
1867
1868         ring->init_hw = gen8_init_common_ring;
1869         ring->get_seqno = gen8_get_seqno;
1870         ring->set_seqno = gen8_set_seqno;
1871         ring->emit_request = gen8_emit_request;
1872         ring->emit_flush = gen8_emit_flush;
1873         ring->irq_get = gen8_logical_ring_get_irq;
1874         ring->irq_put = gen8_logical_ring_put_irq;
1875         ring->emit_bb_start = gen8_emit_bb_start;
1876
1877         return logical_ring_init(dev, ring);
1878 }
1879
1880 static int logical_vebox_ring_init(struct drm_device *dev)
1881 {
1882         struct drm_i915_private *dev_priv = dev->dev_private;
1883         struct intel_engine_cs *ring = &dev_priv->ring[VECS];
1884
1885         ring->name = "video enhancement ring";
1886         ring->id = VECS;
1887         ring->mmio_base = VEBOX_RING_BASE;
1888         ring->irq_enable_mask =
1889                 GT_RENDER_USER_INTERRUPT << GEN8_VECS_IRQ_SHIFT;
1890         ring->irq_keep_mask =
1891                 GT_CONTEXT_SWITCH_INTERRUPT << GEN8_VECS_IRQ_SHIFT;
1892
1893         ring->init_hw = gen8_init_common_ring;
1894         ring->get_seqno = gen8_get_seqno;
1895         ring->set_seqno = gen8_set_seqno;
1896         ring->emit_request = gen8_emit_request;
1897         ring->emit_flush = gen8_emit_flush;
1898         ring->irq_get = gen8_logical_ring_get_irq;
1899         ring->irq_put = gen8_logical_ring_put_irq;
1900         ring->emit_bb_start = gen8_emit_bb_start;
1901
1902         return logical_ring_init(dev, ring);
1903 }
1904
1905 /**
1906  * intel_logical_rings_init() - allocate, populate and init the Engine Command Streamers
1907  * @dev: DRM device.
1908  *
1909  * This function inits the engines for an Execlists submission style (the equivalent in the
1910  * legacy ringbuffer submission world would be i915_gem_init_rings). It does it only for
1911  * those engines that are present in the hardware.
1912  *
1913  * Return: non-zero if the initialization failed.
1914  */
1915 int intel_logical_rings_init(struct drm_device *dev)
1916 {
1917         struct drm_i915_private *dev_priv = dev->dev_private;
1918         int ret;
1919
1920         ret = logical_render_ring_init(dev);
1921         if (ret)
1922                 return ret;
1923
1924         if (HAS_BSD(dev)) {
1925                 ret = logical_bsd_ring_init(dev);
1926                 if (ret)
1927                         goto cleanup_render_ring;
1928         }
1929
1930         if (HAS_BLT(dev)) {
1931                 ret = logical_blt_ring_init(dev);
1932                 if (ret)
1933                         goto cleanup_bsd_ring;
1934         }
1935
1936         if (HAS_VEBOX(dev)) {
1937                 ret = logical_vebox_ring_init(dev);
1938                 if (ret)
1939                         goto cleanup_blt_ring;
1940         }
1941
1942         if (HAS_BSD2(dev)) {
1943                 ret = logical_bsd2_ring_init(dev);
1944                 if (ret)
1945                         goto cleanup_vebox_ring;
1946         }
1947
1948         ret = i915_gem_set_seqno(dev, ((u32)~0 - 0x1000));
1949         if (ret)
1950                 goto cleanup_bsd2_ring;
1951
1952         return 0;
1953
1954 cleanup_bsd2_ring:
1955         intel_logical_ring_cleanup(&dev_priv->ring[VCS2]);
1956 cleanup_vebox_ring:
1957         intel_logical_ring_cleanup(&dev_priv->ring[VECS]);
1958 cleanup_blt_ring:
1959         intel_logical_ring_cleanup(&dev_priv->ring[BCS]);
1960 cleanup_bsd_ring:
1961         intel_logical_ring_cleanup(&dev_priv->ring[VCS]);
1962 cleanup_render_ring:
1963         intel_logical_ring_cleanup(&dev_priv->ring[RCS]);
1964
1965         return ret;
1966 }
1967
1968 static u32
1969 make_rpcs(struct drm_device *dev)
1970 {
1971         u32 rpcs = 0;
1972
1973         /*
1974          * No explicit RPCS request is needed to ensure full
1975          * slice/subslice/EU enablement prior to Gen9.
1976         */
1977         if (INTEL_INFO(dev)->gen < 9)
1978                 return 0;
1979
1980         /*
1981          * Starting in Gen9, render power gating can leave
1982          * slice/subslice/EU in a partially enabled state. We
1983          * must make an explicit request through RPCS for full
1984          * enablement.
1985         */
1986         if (INTEL_INFO(dev)->has_slice_pg) {
1987                 rpcs |= GEN8_RPCS_S_CNT_ENABLE;
1988                 rpcs |= INTEL_INFO(dev)->slice_total <<
1989                         GEN8_RPCS_S_CNT_SHIFT;
1990                 rpcs |= GEN8_RPCS_ENABLE;
1991         }
1992
1993         if (INTEL_INFO(dev)->has_subslice_pg) {
1994                 rpcs |= GEN8_RPCS_SS_CNT_ENABLE;
1995                 rpcs |= INTEL_INFO(dev)->subslice_per_slice <<
1996                         GEN8_RPCS_SS_CNT_SHIFT;
1997                 rpcs |= GEN8_RPCS_ENABLE;
1998         }
1999
2000         if (INTEL_INFO(dev)->has_eu_pg) {
2001                 rpcs |= INTEL_INFO(dev)->eu_per_subslice <<
2002                         GEN8_RPCS_EU_MIN_SHIFT;
2003                 rpcs |= INTEL_INFO(dev)->eu_per_subslice <<
2004                         GEN8_RPCS_EU_MAX_SHIFT;
2005                 rpcs |= GEN8_RPCS_ENABLE;
2006         }
2007
2008         return rpcs;
2009 }
2010
2011 static int
2012 populate_lr_context(struct intel_context *ctx, struct drm_i915_gem_object *ctx_obj,
2013                     struct intel_engine_cs *ring, struct intel_ringbuffer *ringbuf)
2014 {
2015         struct drm_device *dev = ring->dev;
2016         struct drm_i915_private *dev_priv = dev->dev_private;
2017         struct i915_hw_ppgtt *ppgtt = ctx->ppgtt;
2018         struct page *page;
2019         uint32_t *reg_state;
2020         int ret;
2021
2022         if (!ppgtt)
2023                 ppgtt = dev_priv->mm.aliasing_ppgtt;
2024
2025         ret = i915_gem_object_set_to_cpu_domain(ctx_obj, true);
2026         if (ret) {
2027                 DRM_DEBUG_DRIVER("Could not set to CPU domain\n");
2028                 return ret;
2029         }
2030
2031         ret = i915_gem_object_get_pages(ctx_obj);
2032         if (ret) {
2033                 DRM_DEBUG_DRIVER("Could not get object pages\n");
2034                 return ret;
2035         }
2036
2037         i915_gem_object_pin_pages(ctx_obj);
2038
2039         /* The second page of the context object contains some fields which must
2040          * be set up prior to the first execution. */
2041         page = i915_gem_object_get_page(ctx_obj, 1);
2042         reg_state = kmap_atomic(page);
2043
2044         /* A context is actually a big batch buffer with several MI_LOAD_REGISTER_IMM
2045          * commands followed by (reg, value) pairs. The values we are setting here are
2046          * only for the first context restore: on a subsequent save, the GPU will
2047          * recreate this batchbuffer with new values (including all the missing
2048          * MI_LOAD_REGISTER_IMM commands that we are not initializing here). */
2049         if (ring->id == RCS)
2050                 reg_state[CTX_LRI_HEADER_0] = MI_LOAD_REGISTER_IMM(14);
2051         else
2052                 reg_state[CTX_LRI_HEADER_0] = MI_LOAD_REGISTER_IMM(11);
2053         reg_state[CTX_LRI_HEADER_0] |= MI_LRI_FORCE_POSTED;
2054         reg_state[CTX_CONTEXT_CONTROL] = RING_CONTEXT_CONTROL(ring);
2055         reg_state[CTX_CONTEXT_CONTROL+1] =
2056                 _MASKED_BIT_ENABLE(CTX_CTRL_INHIBIT_SYN_CTX_SWITCH |
2057                                    CTX_CTRL_ENGINE_CTX_RESTORE_INHIBIT |
2058                                    CTX_CTRL_RS_CTX_ENABLE);
2059         reg_state[CTX_RING_HEAD] = RING_HEAD(ring->mmio_base);
2060         reg_state[CTX_RING_HEAD+1] = 0;
2061         reg_state[CTX_RING_TAIL] = RING_TAIL(ring->mmio_base);
2062         reg_state[CTX_RING_TAIL+1] = 0;
2063         reg_state[CTX_RING_BUFFER_START] = RING_START(ring->mmio_base);
2064         /* Ring buffer start address is not known until the buffer is pinned.
2065          * It is written to the context image in execlists_update_context()
2066          */
2067         reg_state[CTX_RING_BUFFER_CONTROL] = RING_CTL(ring->mmio_base);
2068         reg_state[CTX_RING_BUFFER_CONTROL+1] =
2069                         ((ringbuf->size - PAGE_SIZE) & RING_NR_PAGES) | RING_VALID;
2070         reg_state[CTX_BB_HEAD_U] = ring->mmio_base + 0x168;
2071         reg_state[CTX_BB_HEAD_U+1] = 0;
2072         reg_state[CTX_BB_HEAD_L] = ring->mmio_base + 0x140;
2073         reg_state[CTX_BB_HEAD_L+1] = 0;
2074         reg_state[CTX_BB_STATE] = ring->mmio_base + 0x110;
2075         reg_state[CTX_BB_STATE+1] = (1<<5);
2076         reg_state[CTX_SECOND_BB_HEAD_U] = ring->mmio_base + 0x11c;
2077         reg_state[CTX_SECOND_BB_HEAD_U+1] = 0;
2078         reg_state[CTX_SECOND_BB_HEAD_L] = ring->mmio_base + 0x114;
2079         reg_state[CTX_SECOND_BB_HEAD_L+1] = 0;
2080         reg_state[CTX_SECOND_BB_STATE] = ring->mmio_base + 0x118;
2081         reg_state[CTX_SECOND_BB_STATE+1] = 0;
2082         if (ring->id == RCS) {
2083                 reg_state[CTX_BB_PER_CTX_PTR] = ring->mmio_base + 0x1c0;
2084                 reg_state[CTX_BB_PER_CTX_PTR+1] = 0;
2085                 reg_state[CTX_RCS_INDIRECT_CTX] = ring->mmio_base + 0x1c4;
2086                 reg_state[CTX_RCS_INDIRECT_CTX+1] = 0;
2087                 reg_state[CTX_RCS_INDIRECT_CTX_OFFSET] = ring->mmio_base + 0x1c8;
2088                 reg_state[CTX_RCS_INDIRECT_CTX_OFFSET+1] = 0;
2089                 if (ring->wa_ctx.obj) {
2090                         struct i915_ctx_workarounds *wa_ctx = &ring->wa_ctx;
2091                         uint32_t ggtt_offset = i915_gem_obj_ggtt_offset(wa_ctx->obj);
2092
2093                         reg_state[CTX_RCS_INDIRECT_CTX+1] =
2094                                 (ggtt_offset + wa_ctx->indirect_ctx.offset * sizeof(uint32_t)) |
2095                                 (wa_ctx->indirect_ctx.size / CACHELINE_DWORDS);
2096
2097                         reg_state[CTX_RCS_INDIRECT_CTX_OFFSET+1] =
2098                                 CTX_RCS_INDIRECT_CTX_OFFSET_DEFAULT << 6;
2099
2100                         reg_state[CTX_BB_PER_CTX_PTR+1] =
2101                                 (ggtt_offset + wa_ctx->per_ctx.offset * sizeof(uint32_t)) |
2102                                 0x01;
2103                 }
2104         }
2105         reg_state[CTX_LRI_HEADER_1] = MI_LOAD_REGISTER_IMM(9);
2106         reg_state[CTX_LRI_HEADER_1] |= MI_LRI_FORCE_POSTED;
2107         reg_state[CTX_CTX_TIMESTAMP] = ring->mmio_base + 0x3a8;
2108         reg_state[CTX_CTX_TIMESTAMP+1] = 0;
2109         reg_state[CTX_PDP3_UDW] = GEN8_RING_PDP_UDW(ring, 3);
2110         reg_state[CTX_PDP3_LDW] = GEN8_RING_PDP_LDW(ring, 3);
2111         reg_state[CTX_PDP2_UDW] = GEN8_RING_PDP_UDW(ring, 2);
2112         reg_state[CTX_PDP2_LDW] = GEN8_RING_PDP_LDW(ring, 2);
2113         reg_state[CTX_PDP1_UDW] = GEN8_RING_PDP_UDW(ring, 1);
2114         reg_state[CTX_PDP1_LDW] = GEN8_RING_PDP_LDW(ring, 1);
2115         reg_state[CTX_PDP0_UDW] = GEN8_RING_PDP_UDW(ring, 0);
2116         reg_state[CTX_PDP0_LDW] = GEN8_RING_PDP_LDW(ring, 0);
2117
2118         /* With dynamic page allocation, PDPs may not be allocated at this point,
2119          * Point the unallocated PDPs to the scratch page
2120          */
2121         ASSIGN_CTX_PDP(ppgtt, reg_state, 3);
2122         ASSIGN_CTX_PDP(ppgtt, reg_state, 2);
2123         ASSIGN_CTX_PDP(ppgtt, reg_state, 1);
2124         ASSIGN_CTX_PDP(ppgtt, reg_state, 0);
2125         if (ring->id == RCS) {
2126                 reg_state[CTX_LRI_HEADER_2] = MI_LOAD_REGISTER_IMM(1);
2127                 reg_state[CTX_R_PWR_CLK_STATE] = GEN8_R_PWR_CLK_STATE;
2128                 reg_state[CTX_R_PWR_CLK_STATE+1] = make_rpcs(dev);
2129         }
2130
2131         kunmap_atomic(reg_state);
2132
2133         ctx_obj->dirty = 1;
2134         set_page_dirty(page);
2135         i915_gem_object_unpin_pages(ctx_obj);
2136
2137         return 0;
2138 }
2139
2140 /**
2141  * intel_lr_context_free() - free the LRC specific bits of a context
2142  * @ctx: the LR context to free.
2143  *
2144  * The real context freeing is done in i915_gem_context_free: this only
2145  * takes care of the bits that are LRC related: the per-engine backing
2146  * objects and the logical ringbuffer.
2147  */
2148 void intel_lr_context_free(struct intel_context *ctx)
2149 {
2150         int i;
2151
2152         for (i = 0; i < I915_NUM_RINGS; i++) {
2153                 struct drm_i915_gem_object *ctx_obj = ctx->engine[i].state;
2154
2155                 if (ctx_obj) {
2156                         struct intel_ringbuffer *ringbuf =
2157                                         ctx->engine[i].ringbuf;
2158                         struct intel_engine_cs *ring = ringbuf->ring;
2159
2160                         if (ctx == ring->default_context) {
2161                                 intel_unpin_ringbuffer_obj(ringbuf);
2162                                 i915_gem_object_ggtt_unpin(ctx_obj);
2163                         }
2164                         WARN_ON(ctx->engine[ring->id].pin_count);
2165                         intel_destroy_ringbuffer_obj(ringbuf);
2166                         kfree(ringbuf);
2167                         drm_gem_object_unreference(&ctx_obj->base);
2168                 }
2169         }
2170 }
2171
2172 static uint32_t get_lr_context_size(struct intel_engine_cs *ring)
2173 {
2174         int ret = 0;
2175
2176         WARN_ON(INTEL_INFO(ring->dev)->gen < 8);
2177
2178         switch (ring->id) {
2179         case RCS:
2180                 if (INTEL_INFO(ring->dev)->gen >= 9)
2181                         ret = GEN9_LR_CONTEXT_RENDER_SIZE;
2182                 else
2183                         ret = GEN8_LR_CONTEXT_RENDER_SIZE;
2184                 break;
2185         case VCS:
2186         case BCS:
2187         case VECS:
2188         case VCS2:
2189                 ret = GEN8_LR_CONTEXT_OTHER_SIZE;
2190                 break;
2191         }
2192
2193         return ret;
2194 }
2195
2196 static void lrc_setup_hardware_status_page(struct intel_engine_cs *ring,
2197                 struct drm_i915_gem_object *default_ctx_obj)
2198 {
2199         struct drm_i915_private *dev_priv = ring->dev->dev_private;
2200
2201         /* The status page is offset 0 from the default context object
2202          * in LRC mode. */
2203         ring->status_page.gfx_addr = i915_gem_obj_ggtt_offset(default_ctx_obj);
2204         ring->status_page.page_addr =
2205                         kmap(sg_page(default_ctx_obj->pages->sgl));
2206         ring->status_page.obj = default_ctx_obj;
2207
2208         I915_WRITE(RING_HWS_PGA(ring->mmio_base),
2209                         (u32)ring->status_page.gfx_addr);
2210         POSTING_READ(RING_HWS_PGA(ring->mmio_base));
2211 }
2212
2213 /**
2214  * intel_lr_context_deferred_create() - create the LRC specific bits of a context
2215  * @ctx: LR context to create.
2216  * @ring: engine to be used with the context.
2217  *
2218  * This function can be called more than once, with different engines, if we plan
2219  * to use the context with them. The context backing objects and the ringbuffers
2220  * (specially the ringbuffer backing objects) suck a lot of memory up, and that's why
2221  * the creation is a deferred call: it's better to make sure first that we need to use
2222  * a given ring with the context.
2223  *
2224  * Return: non-zero on error.
2225  */
2226 int intel_lr_context_deferred_create(struct intel_context *ctx,
2227                                      struct intel_engine_cs *ring)
2228 {
2229         const bool is_global_default_ctx = (ctx == ring->default_context);
2230         struct drm_device *dev = ring->dev;
2231         struct drm_i915_gem_object *ctx_obj;
2232         uint32_t context_size;
2233         struct intel_ringbuffer *ringbuf;
2234         int ret;
2235
2236         WARN_ON(ctx->legacy_hw_ctx.rcs_state != NULL);
2237         WARN_ON(ctx->engine[ring->id].state);
2238
2239         context_size = round_up(get_lr_context_size(ring), 4096);
2240
2241         ctx_obj = i915_gem_alloc_object(dev, context_size);
2242         if (!ctx_obj) {
2243                 DRM_DEBUG_DRIVER("Alloc LRC backing obj failed.\n");
2244                 return -ENOMEM;
2245         }
2246
2247         if (is_global_default_ctx) {
2248                 ret = i915_gem_obj_ggtt_pin(ctx_obj, GEN8_LR_CONTEXT_ALIGN, 0);
2249                 if (ret) {
2250                         DRM_DEBUG_DRIVER("Pin LRC backing obj failed: %d\n",
2251                                         ret);
2252                         drm_gem_object_unreference(&ctx_obj->base);
2253                         return ret;
2254                 }
2255         }
2256
2257         ringbuf = kzalloc(sizeof(*ringbuf), GFP_KERNEL);
2258         if (!ringbuf) {
2259                 DRM_DEBUG_DRIVER("Failed to allocate ringbuffer %s\n",
2260                                 ring->name);
2261                 ret = -ENOMEM;
2262                 goto error_unpin_ctx;
2263         }
2264
2265         ringbuf->ring = ring;
2266
2267         ringbuf->size = 32 * PAGE_SIZE;
2268         ringbuf->effective_size = ringbuf->size;
2269         ringbuf->head = 0;
2270         ringbuf->tail = 0;
2271         ringbuf->last_retired_head = -1;
2272         intel_ring_update_space(ringbuf);
2273
2274         if (ringbuf->obj == NULL) {
2275                 ret = intel_alloc_ringbuffer_obj(dev, ringbuf);
2276                 if (ret) {
2277                         DRM_DEBUG_DRIVER(
2278                                 "Failed to allocate ringbuffer obj %s: %d\n",
2279                                 ring->name, ret);
2280                         goto error_free_rbuf;
2281                 }
2282
2283                 if (is_global_default_ctx) {
2284                         ret = intel_pin_and_map_ringbuffer_obj(dev, ringbuf);
2285                         if (ret) {
2286                                 DRM_ERROR(
2287                                         "Failed to pin and map ringbuffer %s: %d\n",
2288                                         ring->name, ret);
2289                                 goto error_destroy_rbuf;
2290                         }
2291                 }
2292
2293         }
2294
2295         ret = populate_lr_context(ctx, ctx_obj, ring, ringbuf);
2296         if (ret) {
2297                 DRM_DEBUG_DRIVER("Failed to populate LRC: %d\n", ret);
2298                 goto error;
2299         }
2300
2301         ctx->engine[ring->id].ringbuf = ringbuf;
2302         ctx->engine[ring->id].state = ctx_obj;
2303
2304         if (ctx == ring->default_context)
2305                 lrc_setup_hardware_status_page(ring, ctx_obj);
2306         else if (ring->id == RCS && !ctx->rcs_initialized) {
2307                 if (ring->init_context) {
2308                         struct drm_i915_gem_request *req;
2309
2310                         ret = i915_gem_request_alloc(ring, ctx, &req);
2311                         if (ret)
2312                                 return ret;
2313
2314                         ret = ring->init_context(req);
2315                         if (ret) {
2316                                 DRM_ERROR("ring init context: %d\n", ret);
2317                                 i915_gem_request_cancel(req);
2318                                 ctx->engine[ring->id].ringbuf = NULL;
2319                                 ctx->engine[ring->id].state = NULL;
2320                                 goto error;
2321                         }
2322
2323                         i915_add_request_no_flush(req);
2324                 }
2325
2326                 ctx->rcs_initialized = true;
2327         }
2328
2329         return 0;
2330
2331 error:
2332         if (is_global_default_ctx)
2333                 intel_unpin_ringbuffer_obj(ringbuf);
2334 error_destroy_rbuf:
2335         intel_destroy_ringbuffer_obj(ringbuf);
2336 error_free_rbuf:
2337         kfree(ringbuf);
2338 error_unpin_ctx:
2339         if (is_global_default_ctx)
2340                 i915_gem_object_ggtt_unpin(ctx_obj);
2341         drm_gem_object_unreference(&ctx_obj->base);
2342         return ret;
2343 }
2344
2345 void intel_lr_context_reset(struct drm_device *dev,
2346                         struct intel_context *ctx)
2347 {
2348         struct drm_i915_private *dev_priv = dev->dev_private;
2349         struct intel_engine_cs *ring;
2350         int i;
2351
2352         for_each_ring(ring, dev_priv, i) {
2353                 struct drm_i915_gem_object *ctx_obj =
2354                                 ctx->engine[ring->id].state;
2355                 struct intel_ringbuffer *ringbuf =
2356                                 ctx->engine[ring->id].ringbuf;
2357                 uint32_t *reg_state;
2358                 struct page *page;
2359
2360                 if (!ctx_obj)
2361                         continue;
2362
2363                 if (i915_gem_object_get_pages(ctx_obj)) {
2364                         WARN(1, "Failed get_pages for context obj\n");
2365                         continue;
2366                 }
2367                 page = i915_gem_object_get_page(ctx_obj, 1);
2368                 reg_state = kmap_atomic(page);
2369
2370                 reg_state[CTX_RING_HEAD+1] = 0;
2371                 reg_state[CTX_RING_TAIL+1] = 0;
2372
2373                 kunmap_atomic(reg_state);
2374
2375                 ringbuf->head = 0;
2376                 ringbuf->tail = 0;
2377         }
2378 }