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