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