]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/gpu/drm/i915/intel_ringbuffer.c
359d6af1a0b95b1de194c841b52b6e541437650d
[linux.git] / drivers / gpu / drm / i915 / intel_ringbuffer.c
1 /*
2  * Copyright © 2008-2010 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  *    Eric Anholt <eric@anholt.net>
25  *    Zou Nan hai <nanhai.zou@intel.com>
26  *    Xiang Hai hao<haihao.xiang@intel.com>
27  *
28  */
29
30 #include <linux/log2.h>
31
32 #include <drm/i915_drm.h>
33
34 #include "i915_drv.h"
35 #include "i915_gem_render_state.h"
36 #include "i915_reset.h"
37 #include "i915_trace.h"
38 #include "intel_drv.h"
39 #include "intel_workarounds.h"
40
41 /* Rough estimate of the typical request size, performing a flush,
42  * set-context and then emitting the batch.
43  */
44 #define LEGACY_REQUEST_SIZE 200
45
46 unsigned int intel_ring_update_space(struct intel_ring *ring)
47 {
48         unsigned int space;
49
50         space = __intel_ring_space(ring->head, ring->emit, ring->size);
51
52         ring->space = space;
53         return space;
54 }
55
56 static int
57 gen2_render_ring_flush(struct i915_request *rq, u32 mode)
58 {
59         unsigned int num_store_dw;
60         u32 cmd, *cs;
61
62         cmd = MI_FLUSH;
63         num_store_dw = 0;
64         if (mode & EMIT_INVALIDATE)
65                 cmd |= MI_READ_FLUSH;
66         if (mode & EMIT_FLUSH)
67                 num_store_dw = 4;
68
69         cs = intel_ring_begin(rq, 2 + 3 * num_store_dw);
70         if (IS_ERR(cs))
71                 return PTR_ERR(cs);
72
73         *cs++ = cmd;
74         while (num_store_dw--) {
75                 *cs++ = MI_STORE_DWORD_IMM | MI_MEM_VIRTUAL;
76                 *cs++ = i915_scratch_offset(rq->i915);
77                 *cs++ = 0;
78         }
79         *cs++ = MI_FLUSH | MI_NO_WRITE_FLUSH;
80
81         intel_ring_advance(rq, cs);
82
83         return 0;
84 }
85
86 static int
87 gen4_render_ring_flush(struct i915_request *rq, u32 mode)
88 {
89         u32 cmd, *cs;
90         int i;
91
92         /*
93          * read/write caches:
94          *
95          * I915_GEM_DOMAIN_RENDER is always invalidated, but is
96          * only flushed if MI_NO_WRITE_FLUSH is unset.  On 965, it is
97          * also flushed at 2d versus 3d pipeline switches.
98          *
99          * read-only caches:
100          *
101          * I915_GEM_DOMAIN_SAMPLER is flushed on pre-965 if
102          * MI_READ_FLUSH is set, and is always flushed on 965.
103          *
104          * I915_GEM_DOMAIN_COMMAND may not exist?
105          *
106          * I915_GEM_DOMAIN_INSTRUCTION, which exists on 965, is
107          * invalidated when MI_EXE_FLUSH is set.
108          *
109          * I915_GEM_DOMAIN_VERTEX, which exists on 965, is
110          * invalidated with every MI_FLUSH.
111          *
112          * TLBs:
113          *
114          * On 965, TLBs associated with I915_GEM_DOMAIN_COMMAND
115          * and I915_GEM_DOMAIN_CPU in are invalidated at PTE write and
116          * I915_GEM_DOMAIN_RENDER and I915_GEM_DOMAIN_SAMPLER
117          * are flushed at any MI_FLUSH.
118          */
119
120         cmd = MI_FLUSH;
121         if (mode & EMIT_INVALIDATE) {
122                 cmd |= MI_EXE_FLUSH;
123                 if (IS_G4X(rq->i915) || IS_GEN(rq->i915, 5))
124                         cmd |= MI_INVALIDATE_ISP;
125         }
126
127         i = 2;
128         if (mode & EMIT_INVALIDATE)
129                 i += 20;
130
131         cs = intel_ring_begin(rq, i);
132         if (IS_ERR(cs))
133                 return PTR_ERR(cs);
134
135         *cs++ = cmd;
136
137         /*
138          * A random delay to let the CS invalidate take effect? Without this
139          * delay, the GPU relocation path fails as the CS does not see
140          * the updated contents. Just as important, if we apply the flushes
141          * to the EMIT_FLUSH branch (i.e. immediately after the relocation
142          * write and before the invalidate on the next batch), the relocations
143          * still fail. This implies that is a delay following invalidation
144          * that is required to reset the caches as opposed to a delay to
145          * ensure the memory is written.
146          */
147         if (mode & EMIT_INVALIDATE) {
148                 *cs++ = GFX_OP_PIPE_CONTROL(4) | PIPE_CONTROL_QW_WRITE;
149                 *cs++ = i915_scratch_offset(rq->i915) | PIPE_CONTROL_GLOBAL_GTT;
150                 *cs++ = 0;
151                 *cs++ = 0;
152
153                 for (i = 0; i < 12; i++)
154                         *cs++ = MI_FLUSH;
155
156                 *cs++ = GFX_OP_PIPE_CONTROL(4) | PIPE_CONTROL_QW_WRITE;
157                 *cs++ = i915_scratch_offset(rq->i915) | PIPE_CONTROL_GLOBAL_GTT;
158                 *cs++ = 0;
159                 *cs++ = 0;
160         }
161
162         *cs++ = cmd;
163
164         intel_ring_advance(rq, cs);
165
166         return 0;
167 }
168
169 /*
170  * Emits a PIPE_CONTROL with a non-zero post-sync operation, for
171  * implementing two workarounds on gen6.  From section 1.4.7.1
172  * "PIPE_CONTROL" of the Sandy Bridge PRM volume 2 part 1:
173  *
174  * [DevSNB-C+{W/A}] Before any depth stall flush (including those
175  * produced by non-pipelined state commands), software needs to first
176  * send a PIPE_CONTROL with no bits set except Post-Sync Operation !=
177  * 0.
178  *
179  * [Dev-SNB{W/A}]: Before a PIPE_CONTROL with Write Cache Flush Enable
180  * =1, a PIPE_CONTROL with any non-zero post-sync-op is required.
181  *
182  * And the workaround for these two requires this workaround first:
183  *
184  * [Dev-SNB{W/A}]: Pipe-control with CS-stall bit set must be sent
185  * BEFORE the pipe-control with a post-sync op and no write-cache
186  * flushes.
187  *
188  * And this last workaround is tricky because of the requirements on
189  * that bit.  From section 1.4.7.2.3 "Stall" of the Sandy Bridge PRM
190  * volume 2 part 1:
191  *
192  *     "1 of the following must also be set:
193  *      - Render Target Cache Flush Enable ([12] of DW1)
194  *      - Depth Cache Flush Enable ([0] of DW1)
195  *      - Stall at Pixel Scoreboard ([1] of DW1)
196  *      - Depth Stall ([13] of DW1)
197  *      - Post-Sync Operation ([13] of DW1)
198  *      - Notify Enable ([8] of DW1)"
199  *
200  * The cache flushes require the workaround flush that triggered this
201  * one, so we can't use it.  Depth stall would trigger the same.
202  * Post-sync nonzero is what triggered this second workaround, so we
203  * can't use that one either.  Notify enable is IRQs, which aren't
204  * really our business.  That leaves only stall at scoreboard.
205  */
206 static int
207 gen6_emit_post_sync_nonzero_flush(struct i915_request *rq)
208 {
209         u32 scratch_addr = i915_scratch_offset(rq->i915) + 2 * CACHELINE_BYTES;
210         u32 *cs;
211
212         cs = intel_ring_begin(rq, 6);
213         if (IS_ERR(cs))
214                 return PTR_ERR(cs);
215
216         *cs++ = GFX_OP_PIPE_CONTROL(5);
217         *cs++ = PIPE_CONTROL_CS_STALL | PIPE_CONTROL_STALL_AT_SCOREBOARD;
218         *cs++ = scratch_addr | PIPE_CONTROL_GLOBAL_GTT;
219         *cs++ = 0; /* low dword */
220         *cs++ = 0; /* high dword */
221         *cs++ = MI_NOOP;
222         intel_ring_advance(rq, cs);
223
224         cs = intel_ring_begin(rq, 6);
225         if (IS_ERR(cs))
226                 return PTR_ERR(cs);
227
228         *cs++ = GFX_OP_PIPE_CONTROL(5);
229         *cs++ = PIPE_CONTROL_QW_WRITE;
230         *cs++ = scratch_addr | PIPE_CONTROL_GLOBAL_GTT;
231         *cs++ = 0;
232         *cs++ = 0;
233         *cs++ = MI_NOOP;
234         intel_ring_advance(rq, cs);
235
236         return 0;
237 }
238
239 static int
240 gen6_render_ring_flush(struct i915_request *rq, u32 mode)
241 {
242         u32 scratch_addr = i915_scratch_offset(rq->i915) + 2 * CACHELINE_BYTES;
243         u32 *cs, flags = 0;
244         int ret;
245
246         /* Force SNB workarounds for PIPE_CONTROL flushes */
247         ret = gen6_emit_post_sync_nonzero_flush(rq);
248         if (ret)
249                 return ret;
250
251         /* Just flush everything.  Experiments have shown that reducing the
252          * number of bits based on the write domains has little performance
253          * impact.
254          */
255         if (mode & EMIT_FLUSH) {
256                 flags |= PIPE_CONTROL_RENDER_TARGET_CACHE_FLUSH;
257                 flags |= PIPE_CONTROL_DEPTH_CACHE_FLUSH;
258                 /*
259                  * Ensure that any following seqno writes only happen
260                  * when the render cache is indeed flushed.
261                  */
262                 flags |= PIPE_CONTROL_CS_STALL;
263         }
264         if (mode & EMIT_INVALIDATE) {
265                 flags |= PIPE_CONTROL_TLB_INVALIDATE;
266                 flags |= PIPE_CONTROL_INSTRUCTION_CACHE_INVALIDATE;
267                 flags |= PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE;
268                 flags |= PIPE_CONTROL_VF_CACHE_INVALIDATE;
269                 flags |= PIPE_CONTROL_CONST_CACHE_INVALIDATE;
270                 flags |= PIPE_CONTROL_STATE_CACHE_INVALIDATE;
271                 /*
272                  * TLB invalidate requires a post-sync write.
273                  */
274                 flags |= PIPE_CONTROL_QW_WRITE | PIPE_CONTROL_CS_STALL;
275         }
276
277         cs = intel_ring_begin(rq, 4);
278         if (IS_ERR(cs))
279                 return PTR_ERR(cs);
280
281         *cs++ = GFX_OP_PIPE_CONTROL(4);
282         *cs++ = flags;
283         *cs++ = scratch_addr | PIPE_CONTROL_GLOBAL_GTT;
284         *cs++ = 0;
285         intel_ring_advance(rq, cs);
286
287         return 0;
288 }
289
290 static u32 *gen6_rcs_emit_breadcrumb(struct i915_request *rq, u32 *cs)
291 {
292         /* First we do the gen6_emit_post_sync_nonzero_flush w/a */
293         *cs++ = GFX_OP_PIPE_CONTROL(4);
294         *cs++ = PIPE_CONTROL_CS_STALL | PIPE_CONTROL_STALL_AT_SCOREBOARD;
295         *cs++ = 0;
296         *cs++ = 0;
297
298         *cs++ = GFX_OP_PIPE_CONTROL(4);
299         *cs++ = PIPE_CONTROL_QW_WRITE;
300         *cs++ = i915_scratch_offset(rq->i915) | PIPE_CONTROL_GLOBAL_GTT;
301         *cs++ = 0;
302
303         /* Finally we can flush and with it emit the breadcrumb */
304         *cs++ = GFX_OP_PIPE_CONTROL(4);
305         *cs++ = (PIPE_CONTROL_RENDER_TARGET_CACHE_FLUSH |
306                  PIPE_CONTROL_DEPTH_CACHE_FLUSH |
307                  PIPE_CONTROL_DC_FLUSH_ENABLE |
308                  PIPE_CONTROL_QW_WRITE |
309                  PIPE_CONTROL_CS_STALL);
310         *cs++ = rq->timeline->hwsp_offset | PIPE_CONTROL_GLOBAL_GTT;
311         *cs++ = rq->fence.seqno;
312
313         *cs++ = GFX_OP_PIPE_CONTROL(4);
314         *cs++ = PIPE_CONTROL_QW_WRITE | PIPE_CONTROL_STORE_DATA_INDEX;
315         *cs++ = I915_GEM_HWS_HANGCHECK_ADDR | PIPE_CONTROL_GLOBAL_GTT;
316         *cs++ = intel_engine_next_hangcheck_seqno(rq->engine);
317
318         *cs++ = MI_USER_INTERRUPT;
319         *cs++ = MI_NOOP;
320
321         rq->tail = intel_ring_offset(rq, cs);
322         assert_ring_tail_valid(rq->ring, rq->tail);
323
324         return cs;
325 }
326
327 static int
328 gen7_render_ring_cs_stall_wa(struct i915_request *rq)
329 {
330         u32 *cs;
331
332         cs = intel_ring_begin(rq, 4);
333         if (IS_ERR(cs))
334                 return PTR_ERR(cs);
335
336         *cs++ = GFX_OP_PIPE_CONTROL(4);
337         *cs++ = PIPE_CONTROL_CS_STALL | PIPE_CONTROL_STALL_AT_SCOREBOARD;
338         *cs++ = 0;
339         *cs++ = 0;
340         intel_ring_advance(rq, cs);
341
342         return 0;
343 }
344
345 static int
346 gen7_render_ring_flush(struct i915_request *rq, u32 mode)
347 {
348         u32 scratch_addr = i915_scratch_offset(rq->i915) + 2 * CACHELINE_BYTES;
349         u32 *cs, flags = 0;
350
351         /*
352          * Ensure that any following seqno writes only happen when the render
353          * cache is indeed flushed.
354          *
355          * Workaround: 4th PIPE_CONTROL command (except the ones with only
356          * read-cache invalidate bits set) must have the CS_STALL bit set. We
357          * don't try to be clever and just set it unconditionally.
358          */
359         flags |= PIPE_CONTROL_CS_STALL;
360
361         /* Just flush everything.  Experiments have shown that reducing the
362          * number of bits based on the write domains has little performance
363          * impact.
364          */
365         if (mode & EMIT_FLUSH) {
366                 flags |= PIPE_CONTROL_RENDER_TARGET_CACHE_FLUSH;
367                 flags |= PIPE_CONTROL_DEPTH_CACHE_FLUSH;
368                 flags |= PIPE_CONTROL_DC_FLUSH_ENABLE;
369                 flags |= PIPE_CONTROL_FLUSH_ENABLE;
370         }
371         if (mode & EMIT_INVALIDATE) {
372                 flags |= PIPE_CONTROL_TLB_INVALIDATE;
373                 flags |= PIPE_CONTROL_INSTRUCTION_CACHE_INVALIDATE;
374                 flags |= PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE;
375                 flags |= PIPE_CONTROL_VF_CACHE_INVALIDATE;
376                 flags |= PIPE_CONTROL_CONST_CACHE_INVALIDATE;
377                 flags |= PIPE_CONTROL_STATE_CACHE_INVALIDATE;
378                 flags |= PIPE_CONTROL_MEDIA_STATE_CLEAR;
379                 /*
380                  * TLB invalidate requires a post-sync write.
381                  */
382                 flags |= PIPE_CONTROL_QW_WRITE;
383                 flags |= PIPE_CONTROL_GLOBAL_GTT_IVB;
384
385                 flags |= PIPE_CONTROL_STALL_AT_SCOREBOARD;
386
387                 /* Workaround: we must issue a pipe_control with CS-stall bit
388                  * set before a pipe_control command that has the state cache
389                  * invalidate bit set. */
390                 gen7_render_ring_cs_stall_wa(rq);
391         }
392
393         cs = intel_ring_begin(rq, 4);
394         if (IS_ERR(cs))
395                 return PTR_ERR(cs);
396
397         *cs++ = GFX_OP_PIPE_CONTROL(4);
398         *cs++ = flags;
399         *cs++ = scratch_addr;
400         *cs++ = 0;
401         intel_ring_advance(rq, cs);
402
403         return 0;
404 }
405
406 static u32 *gen7_rcs_emit_breadcrumb(struct i915_request *rq, u32 *cs)
407 {
408         *cs++ = GFX_OP_PIPE_CONTROL(4);
409         *cs++ = (PIPE_CONTROL_RENDER_TARGET_CACHE_FLUSH |
410                  PIPE_CONTROL_DEPTH_CACHE_FLUSH |
411                  PIPE_CONTROL_DC_FLUSH_ENABLE |
412                  PIPE_CONTROL_FLUSH_ENABLE |
413                  PIPE_CONTROL_QW_WRITE |
414                  PIPE_CONTROL_GLOBAL_GTT_IVB |
415                  PIPE_CONTROL_CS_STALL);
416         *cs++ = rq->timeline->hwsp_offset;
417         *cs++ = rq->fence.seqno;
418
419         *cs++ = GFX_OP_PIPE_CONTROL(4);
420         *cs++ = (PIPE_CONTROL_QW_WRITE |
421                  PIPE_CONTROL_STORE_DATA_INDEX |
422                  PIPE_CONTROL_GLOBAL_GTT_IVB);
423         *cs++ = I915_GEM_HWS_HANGCHECK_ADDR;
424         *cs++ = intel_engine_next_hangcheck_seqno(rq->engine);
425
426         *cs++ = MI_USER_INTERRUPT;
427         *cs++ = MI_NOOP;
428
429         rq->tail = intel_ring_offset(rq, cs);
430         assert_ring_tail_valid(rq->ring, rq->tail);
431
432         return cs;
433 }
434
435 static u32 *gen6_xcs_emit_breadcrumb(struct i915_request *rq, u32 *cs)
436 {
437         GEM_BUG_ON(rq->timeline->hwsp_ggtt != rq->engine->status_page.vma);
438         GEM_BUG_ON(offset_in_page(rq->timeline->hwsp_offset) != I915_GEM_HWS_SEQNO_ADDR);
439
440         *cs++ = MI_FLUSH_DW | MI_FLUSH_DW_OP_STOREDW | MI_FLUSH_DW_STORE_INDEX;
441         *cs++ = I915_GEM_HWS_SEQNO_ADDR | MI_FLUSH_DW_USE_GTT;
442         *cs++ = rq->fence.seqno;
443
444         *cs++ = MI_FLUSH_DW | MI_FLUSH_DW_OP_STOREDW | MI_FLUSH_DW_STORE_INDEX;
445         *cs++ = I915_GEM_HWS_HANGCHECK_ADDR | MI_FLUSH_DW_USE_GTT;
446         *cs++ = intel_engine_next_hangcheck_seqno(rq->engine);
447
448         *cs++ = MI_USER_INTERRUPT;
449         *cs++ = MI_NOOP;
450
451         rq->tail = intel_ring_offset(rq, cs);
452         assert_ring_tail_valid(rq->ring, rq->tail);
453
454         return cs;
455 }
456
457 #define GEN7_XCS_WA 32
458 static u32 *gen7_xcs_emit_breadcrumb(struct i915_request *rq, u32 *cs)
459 {
460         int i;
461
462         GEM_BUG_ON(rq->timeline->hwsp_ggtt != rq->engine->status_page.vma);
463         GEM_BUG_ON(offset_in_page(rq->timeline->hwsp_offset) != I915_GEM_HWS_SEQNO_ADDR);
464
465         *cs++ = MI_FLUSH_DW | MI_FLUSH_DW_OP_STOREDW | MI_FLUSH_DW_STORE_INDEX;
466         *cs++ = I915_GEM_HWS_SEQNO_ADDR | MI_FLUSH_DW_USE_GTT;
467         *cs++ = rq->fence.seqno;
468
469         *cs++ = MI_FLUSH_DW | MI_FLUSH_DW_OP_STOREDW | MI_FLUSH_DW_STORE_INDEX;
470         *cs++ = I915_GEM_HWS_HANGCHECK_ADDR | MI_FLUSH_DW_USE_GTT;
471         *cs++ = intel_engine_next_hangcheck_seqno(rq->engine);
472
473         for (i = 0; i < GEN7_XCS_WA; i++) {
474                 *cs++ = MI_STORE_DWORD_INDEX;
475                 *cs++ = I915_GEM_HWS_SEQNO_ADDR;
476                 *cs++ = rq->fence.seqno;
477         }
478
479         *cs++ = MI_FLUSH_DW;
480         *cs++ = 0;
481         *cs++ = 0;
482
483         *cs++ = MI_USER_INTERRUPT;
484
485         rq->tail = intel_ring_offset(rq, cs);
486         assert_ring_tail_valid(rq->ring, rq->tail);
487
488         return cs;
489 }
490 #undef GEN7_XCS_WA
491
492 static void set_hwstam(struct intel_engine_cs *engine, u32 mask)
493 {
494         /*
495          * Keep the render interrupt unmasked as this papers over
496          * lost interrupts following a reset.
497          */
498         if (engine->class == RENDER_CLASS) {
499                 if (INTEL_GEN(engine->i915) >= 6)
500                         mask &= ~BIT(0);
501                 else
502                         mask &= ~I915_USER_INTERRUPT;
503         }
504
505         intel_engine_set_hwsp_writemask(engine, mask);
506 }
507
508 static void set_hws_pga(struct intel_engine_cs *engine, phys_addr_t phys)
509 {
510         struct drm_i915_private *dev_priv = engine->i915;
511         u32 addr;
512
513         addr = lower_32_bits(phys);
514         if (INTEL_GEN(dev_priv) >= 4)
515                 addr |= (phys >> 28) & 0xf0;
516
517         I915_WRITE(HWS_PGA, addr);
518 }
519
520 static struct page *status_page(struct intel_engine_cs *engine)
521 {
522         struct drm_i915_gem_object *obj = engine->status_page.vma->obj;
523
524         GEM_BUG_ON(!i915_gem_object_has_pinned_pages(obj));
525         return sg_page(obj->mm.pages->sgl);
526 }
527
528 static void ring_setup_phys_status_page(struct intel_engine_cs *engine)
529 {
530         set_hws_pga(engine, PFN_PHYS(page_to_pfn(status_page(engine))));
531         set_hwstam(engine, ~0u);
532 }
533
534 static void set_hwsp(struct intel_engine_cs *engine, u32 offset)
535 {
536         struct drm_i915_private *dev_priv = engine->i915;
537         i915_reg_t hwsp;
538
539         /*
540          * The ring status page addresses are no longer next to the rest of
541          * the ring registers as of gen7.
542          */
543         if (IS_GEN(dev_priv, 7)) {
544                 switch (engine->id) {
545                 /*
546                  * No more rings exist on Gen7. Default case is only to shut up
547                  * gcc switch check warning.
548                  */
549                 default:
550                         GEM_BUG_ON(engine->id);
551                         /* fallthrough */
552                 case RCS0:
553                         hwsp = RENDER_HWS_PGA_GEN7;
554                         break;
555                 case BCS0:
556                         hwsp = BLT_HWS_PGA_GEN7;
557                         break;
558                 case VCS0:
559                         hwsp = BSD_HWS_PGA_GEN7;
560                         break;
561                 case VECS0:
562                         hwsp = VEBOX_HWS_PGA_GEN7;
563                         break;
564                 }
565         } else if (IS_GEN(dev_priv, 6)) {
566                 hwsp = RING_HWS_PGA_GEN6(engine->mmio_base);
567         } else {
568                 hwsp = RING_HWS_PGA(engine->mmio_base);
569         }
570
571         I915_WRITE(hwsp, offset);
572         POSTING_READ(hwsp);
573 }
574
575 static void flush_cs_tlb(struct intel_engine_cs *engine)
576 {
577         struct drm_i915_private *dev_priv = engine->i915;
578         i915_reg_t instpm = RING_INSTPM(engine->mmio_base);
579
580         if (!IS_GEN_RANGE(dev_priv, 6, 7))
581                 return;
582
583         /* ring should be idle before issuing a sync flush*/
584         WARN_ON((I915_READ_MODE(engine) & MODE_IDLE) == 0);
585
586         I915_WRITE(instpm,
587                    _MASKED_BIT_ENABLE(INSTPM_TLB_INVALIDATE |
588                                       INSTPM_SYNC_FLUSH));
589         if (intel_wait_for_register(dev_priv,
590                                     instpm, INSTPM_SYNC_FLUSH, 0,
591                                     1000))
592                 DRM_ERROR("%s: wait for SyncFlush to complete for TLB invalidation timed out\n",
593                           engine->name);
594 }
595
596 static void ring_setup_status_page(struct intel_engine_cs *engine)
597 {
598         set_hwsp(engine, i915_ggtt_offset(engine->status_page.vma));
599         set_hwstam(engine, ~0u);
600
601         flush_cs_tlb(engine);
602 }
603
604 static bool stop_ring(struct intel_engine_cs *engine)
605 {
606         struct drm_i915_private *dev_priv = engine->i915;
607
608         if (INTEL_GEN(dev_priv) > 2) {
609                 I915_WRITE_MODE(engine, _MASKED_BIT_ENABLE(STOP_RING));
610                 if (intel_wait_for_register(dev_priv,
611                                             RING_MI_MODE(engine->mmio_base),
612                                             MODE_IDLE,
613                                             MODE_IDLE,
614                                             1000)) {
615                         DRM_ERROR("%s : timed out trying to stop ring\n",
616                                   engine->name);
617                         /* Sometimes we observe that the idle flag is not
618                          * set even though the ring is empty. So double
619                          * check before giving up.
620                          */
621                         if (I915_READ_HEAD(engine) != I915_READ_TAIL(engine))
622                                 return false;
623                 }
624         }
625
626         I915_WRITE_HEAD(engine, I915_READ_TAIL(engine));
627
628         I915_WRITE_HEAD(engine, 0);
629         I915_WRITE_TAIL(engine, 0);
630
631         /* The ring must be empty before it is disabled */
632         I915_WRITE_CTL(engine, 0);
633
634         return (I915_READ_HEAD(engine) & HEAD_ADDR) == 0;
635 }
636
637 static int init_ring_common(struct intel_engine_cs *engine)
638 {
639         struct drm_i915_private *dev_priv = engine->i915;
640         struct intel_ring *ring = engine->buffer;
641         int ret = 0;
642
643         intel_uncore_forcewake_get(&dev_priv->uncore, FORCEWAKE_ALL);
644
645         if (!stop_ring(engine)) {
646                 /* G45 ring initialization often fails to reset head to zero */
647                 DRM_DEBUG_DRIVER("%s head not reset to zero "
648                                 "ctl %08x head %08x tail %08x start %08x\n",
649                                 engine->name,
650                                 I915_READ_CTL(engine),
651                                 I915_READ_HEAD(engine),
652                                 I915_READ_TAIL(engine),
653                                 I915_READ_START(engine));
654
655                 if (!stop_ring(engine)) {
656                         DRM_ERROR("failed to set %s head to zero "
657                                   "ctl %08x head %08x tail %08x start %08x\n",
658                                   engine->name,
659                                   I915_READ_CTL(engine),
660                                   I915_READ_HEAD(engine),
661                                   I915_READ_TAIL(engine),
662                                   I915_READ_START(engine));
663                         ret = -EIO;
664                         goto out;
665                 }
666         }
667
668         if (HWS_NEEDS_PHYSICAL(dev_priv))
669                 ring_setup_phys_status_page(engine);
670         else
671                 ring_setup_status_page(engine);
672
673         intel_engine_reset_breadcrumbs(engine);
674
675         /* Enforce ordering by reading HEAD register back */
676         I915_READ_HEAD(engine);
677
678         /* Initialize the ring. This must happen _after_ we've cleared the ring
679          * registers with the above sequence (the readback of the HEAD registers
680          * also enforces ordering), otherwise the hw might lose the new ring
681          * register values. */
682         I915_WRITE_START(engine, i915_ggtt_offset(ring->vma));
683
684         /* WaClearRingBufHeadRegAtInit:ctg,elk */
685         if (I915_READ_HEAD(engine))
686                 DRM_DEBUG_DRIVER("%s initialization failed [head=%08x], fudging\n",
687                                  engine->name, I915_READ_HEAD(engine));
688
689         /* Check that the ring offsets point within the ring! */
690         GEM_BUG_ON(!intel_ring_offset_valid(ring, ring->head));
691         GEM_BUG_ON(!intel_ring_offset_valid(ring, ring->tail));
692         intel_ring_update_space(ring);
693
694         /* First wake the ring up to an empty/idle ring */
695         I915_WRITE_HEAD(engine, ring->head);
696         I915_WRITE_TAIL(engine, ring->head);
697         (void)I915_READ_TAIL(engine);
698
699         I915_WRITE_CTL(engine, RING_CTL_SIZE(ring->size) | RING_VALID);
700
701         /* If the head is still not zero, the ring is dead */
702         if (intel_wait_for_register(dev_priv, RING_CTL(engine->mmio_base),
703                                     RING_VALID, RING_VALID,
704                                     50)) {
705                 DRM_ERROR("%s initialization failed "
706                           "ctl %08x (valid? %d) head %08x [%08x] tail %08x [%08x] start %08x [expected %08x]\n",
707                           engine->name,
708                           I915_READ_CTL(engine),
709                           I915_READ_CTL(engine) & RING_VALID,
710                           I915_READ_HEAD(engine), ring->head,
711                           I915_READ_TAIL(engine), ring->tail,
712                           I915_READ_START(engine),
713                           i915_ggtt_offset(ring->vma));
714                 ret = -EIO;
715                 goto out;
716         }
717
718         if (INTEL_GEN(dev_priv) > 2)
719                 I915_WRITE_MODE(engine, _MASKED_BIT_DISABLE(STOP_RING));
720
721         /* Now awake, let it get started */
722         if (ring->tail != ring->head) {
723                 I915_WRITE_TAIL(engine, ring->tail);
724                 (void)I915_READ_TAIL(engine);
725         }
726
727         /* Papering over lost _interrupts_ immediately following the restart */
728         intel_engine_queue_breadcrumbs(engine);
729 out:
730         intel_uncore_forcewake_put(&dev_priv->uncore, FORCEWAKE_ALL);
731
732         return ret;
733 }
734
735 static void reset_prepare(struct intel_engine_cs *engine)
736 {
737         intel_engine_stop_cs(engine);
738 }
739
740 static void reset_ring(struct intel_engine_cs *engine, bool stalled)
741 {
742         struct i915_timeline *tl = &engine->timeline;
743         struct i915_request *pos, *rq;
744         unsigned long flags;
745         u32 head;
746
747         rq = NULL;
748         spin_lock_irqsave(&tl->lock, flags);
749         list_for_each_entry(pos, &tl->requests, link) {
750                 if (!i915_request_completed(pos)) {
751                         rq = pos;
752                         break;
753                 }
754         }
755
756         /*
757          * The guilty request will get skipped on a hung engine.
758          *
759          * Users of client default contexts do not rely on logical
760          * state preserved between batches so it is safe to execute
761          * queued requests following the hang. Non default contexts
762          * rely on preserved state, so skipping a batch loses the
763          * evolution of the state and it needs to be considered corrupted.
764          * Executing more queued batches on top of corrupted state is
765          * risky. But we take the risk by trying to advance through
766          * the queued requests in order to make the client behaviour
767          * more predictable around resets, by not throwing away random
768          * amount of batches it has prepared for execution. Sophisticated
769          * clients can use gem_reset_stats_ioctl and dma fence status
770          * (exported via sync_file info ioctl on explicit fences) to observe
771          * when it loses the context state and should rebuild accordingly.
772          *
773          * The context ban, and ultimately the client ban, mechanism are safety
774          * valves if client submission ends up resulting in nothing more than
775          * subsequent hangs.
776          */
777
778         if (rq) {
779                 /*
780                  * Try to restore the logical GPU state to match the
781                  * continuation of the request queue. If we skip the
782                  * context/PD restore, then the next request may try to execute
783                  * assuming that its context is valid and loaded on the GPU and
784                  * so may try to access invalid memory, prompting repeated GPU
785                  * hangs.
786                  *
787                  * If the request was guilty, we still restore the logical
788                  * state in case the next request requires it (e.g. the
789                  * aliasing ppgtt), but skip over the hung batch.
790                  *
791                  * If the request was innocent, we try to replay the request
792                  * with the restored context.
793                  */
794                 i915_reset_request(rq, stalled);
795
796                 GEM_BUG_ON(rq->ring != engine->buffer);
797                 head = rq->head;
798         } else {
799                 head = engine->buffer->tail;
800         }
801         engine->buffer->head = intel_ring_wrap(engine->buffer, head);
802
803         spin_unlock_irqrestore(&tl->lock, flags);
804 }
805
806 static void reset_finish(struct intel_engine_cs *engine)
807 {
808 }
809
810 static int intel_rcs_ctx_init(struct i915_request *rq)
811 {
812         int ret;
813
814         ret = intel_engine_emit_ctx_wa(rq);
815         if (ret != 0)
816                 return ret;
817
818         ret = i915_gem_render_state_emit(rq);
819         if (ret)
820                 return ret;
821
822         return 0;
823 }
824
825 static int init_render_ring(struct intel_engine_cs *engine)
826 {
827         struct drm_i915_private *dev_priv = engine->i915;
828         int ret = init_ring_common(engine);
829         if (ret)
830                 return ret;
831
832         /* WaTimedSingleVertexDispatch:cl,bw,ctg,elk,ilk,snb */
833         if (IS_GEN_RANGE(dev_priv, 4, 6))
834                 I915_WRITE(MI_MODE, _MASKED_BIT_ENABLE(VS_TIMER_DISPATCH));
835
836         /* We need to disable the AsyncFlip performance optimisations in order
837          * to use MI_WAIT_FOR_EVENT within the CS. It should already be
838          * programmed to '1' on all products.
839          *
840          * WaDisableAsyncFlipPerfMode:snb,ivb,hsw,vlv
841          */
842         if (IS_GEN_RANGE(dev_priv, 6, 7))
843                 I915_WRITE(MI_MODE, _MASKED_BIT_ENABLE(ASYNC_FLIP_PERF_DISABLE));
844
845         /* Required for the hardware to program scanline values for waiting */
846         /* WaEnableFlushTlbInvalidationMode:snb */
847         if (IS_GEN(dev_priv, 6))
848                 I915_WRITE(GFX_MODE,
849                            _MASKED_BIT_ENABLE(GFX_TLB_INVALIDATE_EXPLICIT));
850
851         /* WaBCSVCSTlbInvalidationMode:ivb,vlv,hsw */
852         if (IS_GEN(dev_priv, 7))
853                 I915_WRITE(GFX_MODE_GEN7,
854                            _MASKED_BIT_ENABLE(GFX_TLB_INVALIDATE_EXPLICIT) |
855                            _MASKED_BIT_ENABLE(GFX_REPLAY_MODE));
856
857         if (IS_GEN(dev_priv, 6)) {
858                 /* From the Sandybridge PRM, volume 1 part 3, page 24:
859                  * "If this bit is set, STCunit will have LRA as replacement
860                  *  policy. [...] This bit must be reset.  LRA replacement
861                  *  policy is not supported."
862                  */
863                 I915_WRITE(CACHE_MODE_0,
864                            _MASKED_BIT_DISABLE(CM0_STC_EVICT_DISABLE_LRA_SNB));
865         }
866
867         if (IS_GEN_RANGE(dev_priv, 6, 7))
868                 I915_WRITE(INSTPM, _MASKED_BIT_ENABLE(INSTPM_FORCE_ORDERING));
869
870         if (INTEL_GEN(dev_priv) >= 6)
871                 I915_WRITE_IMR(engine, ~engine->irq_keep_mask);
872
873         return 0;
874 }
875
876 static void cancel_requests(struct intel_engine_cs *engine)
877 {
878         struct i915_request *request;
879         unsigned long flags;
880
881         spin_lock_irqsave(&engine->timeline.lock, flags);
882
883         /* Mark all submitted requests as skipped. */
884         list_for_each_entry(request, &engine->timeline.requests, link) {
885                 if (!i915_request_signaled(request))
886                         dma_fence_set_error(&request->fence, -EIO);
887
888                 i915_request_mark_complete(request);
889         }
890
891         /* Remaining _unready_ requests will be nop'ed when submitted */
892
893         spin_unlock_irqrestore(&engine->timeline.lock, flags);
894 }
895
896 static void i9xx_submit_request(struct i915_request *request)
897 {
898         struct drm_i915_private *dev_priv = request->i915;
899
900         i915_request_submit(request);
901
902         I915_WRITE_TAIL(request->engine,
903                         intel_ring_set_tail(request->ring, request->tail));
904 }
905
906 static u32 *i9xx_emit_breadcrumb(struct i915_request *rq, u32 *cs)
907 {
908         GEM_BUG_ON(rq->timeline->hwsp_ggtt != rq->engine->status_page.vma);
909         GEM_BUG_ON(offset_in_page(rq->timeline->hwsp_offset) != I915_GEM_HWS_SEQNO_ADDR);
910
911         *cs++ = MI_FLUSH;
912
913         *cs++ = MI_STORE_DWORD_INDEX;
914         *cs++ = I915_GEM_HWS_SEQNO_ADDR;
915         *cs++ = rq->fence.seqno;
916
917         *cs++ = MI_STORE_DWORD_INDEX;
918         *cs++ = I915_GEM_HWS_HANGCHECK_ADDR;
919         *cs++ = intel_engine_next_hangcheck_seqno(rq->engine);
920
921         *cs++ = MI_USER_INTERRUPT;
922
923         rq->tail = intel_ring_offset(rq, cs);
924         assert_ring_tail_valid(rq->ring, rq->tail);
925
926         return cs;
927 }
928
929 #define GEN5_WA_STORES 8 /* must be at least 1! */
930 static u32 *gen5_emit_breadcrumb(struct i915_request *rq, u32 *cs)
931 {
932         int i;
933
934         GEM_BUG_ON(rq->timeline->hwsp_ggtt != rq->engine->status_page.vma);
935         GEM_BUG_ON(offset_in_page(rq->timeline->hwsp_offset) != I915_GEM_HWS_SEQNO_ADDR);
936
937         *cs++ = MI_FLUSH;
938
939         *cs++ = MI_STORE_DWORD_INDEX;
940         *cs++ = I915_GEM_HWS_HANGCHECK_ADDR;
941         *cs++ = intel_engine_next_hangcheck_seqno(rq->engine);
942
943         BUILD_BUG_ON(GEN5_WA_STORES < 1);
944         for (i = 0; i < GEN5_WA_STORES; i++) {
945                 *cs++ = MI_STORE_DWORD_INDEX;
946                 *cs++ = I915_GEM_HWS_SEQNO_ADDR;
947                 *cs++ = rq->fence.seqno;
948         }
949
950         *cs++ = MI_USER_INTERRUPT;
951         *cs++ = MI_NOOP;
952
953         rq->tail = intel_ring_offset(rq, cs);
954         assert_ring_tail_valid(rq->ring, rq->tail);
955
956         return cs;
957 }
958 #undef GEN5_WA_STORES
959
960 static void
961 gen5_irq_enable(struct intel_engine_cs *engine)
962 {
963         gen5_enable_gt_irq(engine->i915, engine->irq_enable_mask);
964 }
965
966 static void
967 gen5_irq_disable(struct intel_engine_cs *engine)
968 {
969         gen5_disable_gt_irq(engine->i915, engine->irq_enable_mask);
970 }
971
972 static void
973 i9xx_irq_enable(struct intel_engine_cs *engine)
974 {
975         struct drm_i915_private *dev_priv = engine->i915;
976
977         dev_priv->irq_mask &= ~engine->irq_enable_mask;
978         I915_WRITE(IMR, dev_priv->irq_mask);
979         POSTING_READ_FW(RING_IMR(engine->mmio_base));
980 }
981
982 static void
983 i9xx_irq_disable(struct intel_engine_cs *engine)
984 {
985         struct drm_i915_private *dev_priv = engine->i915;
986
987         dev_priv->irq_mask |= engine->irq_enable_mask;
988         I915_WRITE(IMR, dev_priv->irq_mask);
989 }
990
991 static void
992 i8xx_irq_enable(struct intel_engine_cs *engine)
993 {
994         struct drm_i915_private *dev_priv = engine->i915;
995
996         dev_priv->irq_mask &= ~engine->irq_enable_mask;
997         I915_WRITE16(IMR, dev_priv->irq_mask);
998         POSTING_READ16(RING_IMR(engine->mmio_base));
999 }
1000
1001 static void
1002 i8xx_irq_disable(struct intel_engine_cs *engine)
1003 {
1004         struct drm_i915_private *dev_priv = engine->i915;
1005
1006         dev_priv->irq_mask |= engine->irq_enable_mask;
1007         I915_WRITE16(IMR, dev_priv->irq_mask);
1008 }
1009
1010 static int
1011 bsd_ring_flush(struct i915_request *rq, u32 mode)
1012 {
1013         u32 *cs;
1014
1015         cs = intel_ring_begin(rq, 2);
1016         if (IS_ERR(cs))
1017                 return PTR_ERR(cs);
1018
1019         *cs++ = MI_FLUSH;
1020         *cs++ = MI_NOOP;
1021         intel_ring_advance(rq, cs);
1022         return 0;
1023 }
1024
1025 static void
1026 gen6_irq_enable(struct intel_engine_cs *engine)
1027 {
1028         struct drm_i915_private *dev_priv = engine->i915;
1029
1030         I915_WRITE_IMR(engine,
1031                        ~(engine->irq_enable_mask |
1032                          engine->irq_keep_mask));
1033
1034         /* Flush/delay to ensure the RING_IMR is active before the GT IMR */
1035         POSTING_READ_FW(RING_IMR(engine->mmio_base));
1036
1037         gen5_enable_gt_irq(dev_priv, engine->irq_enable_mask);
1038 }
1039
1040 static void
1041 gen6_irq_disable(struct intel_engine_cs *engine)
1042 {
1043         struct drm_i915_private *dev_priv = engine->i915;
1044
1045         I915_WRITE_IMR(engine, ~engine->irq_keep_mask);
1046         gen5_disable_gt_irq(dev_priv, engine->irq_enable_mask);
1047 }
1048
1049 static void
1050 hsw_vebox_irq_enable(struct intel_engine_cs *engine)
1051 {
1052         struct drm_i915_private *dev_priv = engine->i915;
1053
1054         I915_WRITE_IMR(engine, ~engine->irq_enable_mask);
1055
1056         /* Flush/delay to ensure the RING_IMR is active before the GT IMR */
1057         POSTING_READ_FW(RING_IMR(engine->mmio_base));
1058
1059         gen6_unmask_pm_irq(dev_priv, engine->irq_enable_mask);
1060 }
1061
1062 static void
1063 hsw_vebox_irq_disable(struct intel_engine_cs *engine)
1064 {
1065         struct drm_i915_private *dev_priv = engine->i915;
1066
1067         I915_WRITE_IMR(engine, ~0);
1068         gen6_mask_pm_irq(dev_priv, engine->irq_enable_mask);
1069 }
1070
1071 static int
1072 i965_emit_bb_start(struct i915_request *rq,
1073                    u64 offset, u32 length,
1074                    unsigned int dispatch_flags)
1075 {
1076         u32 *cs;
1077
1078         cs = intel_ring_begin(rq, 2);
1079         if (IS_ERR(cs))
1080                 return PTR_ERR(cs);
1081
1082         *cs++ = MI_BATCH_BUFFER_START | MI_BATCH_GTT | (dispatch_flags &
1083                 I915_DISPATCH_SECURE ? 0 : MI_BATCH_NON_SECURE_I965);
1084         *cs++ = offset;
1085         intel_ring_advance(rq, cs);
1086
1087         return 0;
1088 }
1089
1090 /* Just userspace ABI convention to limit the wa batch bo to a resonable size */
1091 #define I830_BATCH_LIMIT SZ_256K
1092 #define I830_TLB_ENTRIES (2)
1093 #define I830_WA_SIZE max(I830_TLB_ENTRIES*4096, I830_BATCH_LIMIT)
1094 static int
1095 i830_emit_bb_start(struct i915_request *rq,
1096                    u64 offset, u32 len,
1097                    unsigned int dispatch_flags)
1098 {
1099         u32 *cs, cs_offset = i915_scratch_offset(rq->i915);
1100
1101         GEM_BUG_ON(rq->i915->gt.scratch->size < I830_WA_SIZE);
1102
1103         cs = intel_ring_begin(rq, 6);
1104         if (IS_ERR(cs))
1105                 return PTR_ERR(cs);
1106
1107         /* Evict the invalid PTE TLBs */
1108         *cs++ = COLOR_BLT_CMD | BLT_WRITE_RGBA;
1109         *cs++ = BLT_DEPTH_32 | BLT_ROP_COLOR_COPY | 4096;
1110         *cs++ = I830_TLB_ENTRIES << 16 | 4; /* load each page */
1111         *cs++ = cs_offset;
1112         *cs++ = 0xdeadbeef;
1113         *cs++ = MI_NOOP;
1114         intel_ring_advance(rq, cs);
1115
1116         if ((dispatch_flags & I915_DISPATCH_PINNED) == 0) {
1117                 if (len > I830_BATCH_LIMIT)
1118                         return -ENOSPC;
1119
1120                 cs = intel_ring_begin(rq, 6 + 2);
1121                 if (IS_ERR(cs))
1122                         return PTR_ERR(cs);
1123
1124                 /* Blit the batch (which has now all relocs applied) to the
1125                  * stable batch scratch bo area (so that the CS never
1126                  * stumbles over its tlb invalidation bug) ...
1127                  */
1128                 *cs++ = SRC_COPY_BLT_CMD | BLT_WRITE_RGBA;
1129                 *cs++ = BLT_DEPTH_32 | BLT_ROP_SRC_COPY | 4096;
1130                 *cs++ = DIV_ROUND_UP(len, 4096) << 16 | 4096;
1131                 *cs++ = cs_offset;
1132                 *cs++ = 4096;
1133                 *cs++ = offset;
1134
1135                 *cs++ = MI_FLUSH;
1136                 *cs++ = MI_NOOP;
1137                 intel_ring_advance(rq, cs);
1138
1139                 /* ... and execute it. */
1140                 offset = cs_offset;
1141         }
1142
1143         cs = intel_ring_begin(rq, 2);
1144         if (IS_ERR(cs))
1145                 return PTR_ERR(cs);
1146
1147         *cs++ = MI_BATCH_BUFFER_START | MI_BATCH_GTT;
1148         *cs++ = offset | (dispatch_flags & I915_DISPATCH_SECURE ? 0 :
1149                 MI_BATCH_NON_SECURE);
1150         intel_ring_advance(rq, cs);
1151
1152         return 0;
1153 }
1154
1155 static int
1156 i915_emit_bb_start(struct i915_request *rq,
1157                    u64 offset, u32 len,
1158                    unsigned int dispatch_flags)
1159 {
1160         u32 *cs;
1161
1162         cs = intel_ring_begin(rq, 2);
1163         if (IS_ERR(cs))
1164                 return PTR_ERR(cs);
1165
1166         *cs++ = MI_BATCH_BUFFER_START | MI_BATCH_GTT;
1167         *cs++ = offset | (dispatch_flags & I915_DISPATCH_SECURE ? 0 :
1168                 MI_BATCH_NON_SECURE);
1169         intel_ring_advance(rq, cs);
1170
1171         return 0;
1172 }
1173
1174 int intel_ring_pin(struct intel_ring *ring)
1175 {
1176         struct i915_vma *vma = ring->vma;
1177         enum i915_map_type map = i915_coherent_map_type(vma->vm->i915);
1178         unsigned int flags;
1179         void *addr;
1180         int ret;
1181
1182         GEM_BUG_ON(ring->vaddr);
1183
1184         ret = i915_timeline_pin(ring->timeline);
1185         if (ret)
1186                 return ret;
1187
1188         flags = PIN_GLOBAL;
1189
1190         /* Ring wraparound at offset 0 sometimes hangs. No idea why. */
1191         flags |= PIN_OFFSET_BIAS | i915_ggtt_pin_bias(vma);
1192
1193         if (vma->obj->stolen)
1194                 flags |= PIN_MAPPABLE;
1195         else
1196                 flags |= PIN_HIGH;
1197
1198         ret = i915_vma_pin(vma, 0, 0, flags);
1199         if (unlikely(ret))
1200                 goto unpin_timeline;
1201
1202         if (i915_vma_is_map_and_fenceable(vma))
1203                 addr = (void __force *)i915_vma_pin_iomap(vma);
1204         else
1205                 addr = i915_gem_object_pin_map(vma->obj, map);
1206         if (IS_ERR(addr)) {
1207                 ret = PTR_ERR(addr);
1208                 goto unpin_ring;
1209         }
1210
1211         vma->obj->pin_global++;
1212
1213         ring->vaddr = addr;
1214         return 0;
1215
1216 unpin_ring:
1217         i915_vma_unpin(vma);
1218 unpin_timeline:
1219         i915_timeline_unpin(ring->timeline);
1220         return ret;
1221 }
1222
1223 void intel_ring_reset(struct intel_ring *ring, u32 tail)
1224 {
1225         GEM_BUG_ON(!intel_ring_offset_valid(ring, tail));
1226
1227         ring->tail = tail;
1228         ring->head = tail;
1229         ring->emit = tail;
1230         intel_ring_update_space(ring);
1231 }
1232
1233 void intel_ring_unpin(struct intel_ring *ring)
1234 {
1235         GEM_BUG_ON(!ring->vma);
1236         GEM_BUG_ON(!ring->vaddr);
1237
1238         /* Discard any unused bytes beyond that submitted to hw. */
1239         intel_ring_reset(ring, ring->tail);
1240
1241         if (i915_vma_is_map_and_fenceable(ring->vma))
1242                 i915_vma_unpin_iomap(ring->vma);
1243         else
1244                 i915_gem_object_unpin_map(ring->vma->obj);
1245         ring->vaddr = NULL;
1246
1247         ring->vma->obj->pin_global--;
1248         i915_vma_unpin(ring->vma);
1249
1250         i915_timeline_unpin(ring->timeline);
1251 }
1252
1253 static struct i915_vma *
1254 intel_ring_create_vma(struct drm_i915_private *dev_priv, int size)
1255 {
1256         struct i915_address_space *vm = &dev_priv->ggtt.vm;
1257         struct drm_i915_gem_object *obj;
1258         struct i915_vma *vma;
1259
1260         obj = i915_gem_object_create_stolen(dev_priv, size);
1261         if (!obj)
1262                 obj = i915_gem_object_create_internal(dev_priv, size);
1263         if (IS_ERR(obj))
1264                 return ERR_CAST(obj);
1265
1266         /*
1267          * Mark ring buffers as read-only from GPU side (so no stray overwrites)
1268          * if supported by the platform's GGTT.
1269          */
1270         if (vm->has_read_only)
1271                 i915_gem_object_set_readonly(obj);
1272
1273         vma = i915_vma_instance(obj, vm, NULL);
1274         if (IS_ERR(vma))
1275                 goto err;
1276
1277         return vma;
1278
1279 err:
1280         i915_gem_object_put(obj);
1281         return vma;
1282 }
1283
1284 struct intel_ring *
1285 intel_engine_create_ring(struct intel_engine_cs *engine,
1286                          struct i915_timeline *timeline,
1287                          int size)
1288 {
1289         struct intel_ring *ring;
1290         struct i915_vma *vma;
1291
1292         GEM_BUG_ON(!is_power_of_2(size));
1293         GEM_BUG_ON(RING_CTL_SIZE(size) & ~RING_NR_PAGES);
1294         GEM_BUG_ON(timeline == &engine->timeline);
1295         lockdep_assert_held(&engine->i915->drm.struct_mutex);
1296
1297         ring = kzalloc(sizeof(*ring), GFP_KERNEL);
1298         if (!ring)
1299                 return ERR_PTR(-ENOMEM);
1300
1301         kref_init(&ring->ref);
1302         INIT_LIST_HEAD(&ring->request_list);
1303         ring->timeline = i915_timeline_get(timeline);
1304
1305         ring->size = size;
1306         /* Workaround an erratum on the i830 which causes a hang if
1307          * the TAIL pointer points to within the last 2 cachelines
1308          * of the buffer.
1309          */
1310         ring->effective_size = size;
1311         if (IS_I830(engine->i915) || IS_I845G(engine->i915))
1312                 ring->effective_size -= 2 * CACHELINE_BYTES;
1313
1314         intel_ring_update_space(ring);
1315
1316         vma = intel_ring_create_vma(engine->i915, size);
1317         if (IS_ERR(vma)) {
1318                 kfree(ring);
1319                 return ERR_CAST(vma);
1320         }
1321         ring->vma = vma;
1322
1323         return ring;
1324 }
1325
1326 void intel_ring_free(struct kref *ref)
1327 {
1328         struct intel_ring *ring = container_of(ref, typeof(*ring), ref);
1329         struct drm_i915_gem_object *obj = ring->vma->obj;
1330
1331         i915_vma_close(ring->vma);
1332         __i915_gem_object_release_unless_active(obj);
1333
1334         i915_timeline_put(ring->timeline);
1335         kfree(ring);
1336 }
1337
1338 static void __ring_context_fini(struct intel_context *ce)
1339 {
1340         GEM_BUG_ON(i915_gem_object_is_active(ce->state->obj));
1341         i915_gem_object_put(ce->state->obj);
1342 }
1343
1344 static void ring_context_destroy(struct kref *ref)
1345 {
1346         struct intel_context *ce = container_of(ref, typeof(*ce), ref);
1347
1348         GEM_BUG_ON(intel_context_is_pinned(ce));
1349
1350         if (ce->state)
1351                 __ring_context_fini(ce);
1352
1353         intel_context_free(ce);
1354 }
1355
1356 static int __context_pin_ppgtt(struct i915_gem_context *ctx)
1357 {
1358         struct i915_hw_ppgtt *ppgtt;
1359         int err = 0;
1360
1361         ppgtt = ctx->ppgtt ?: ctx->i915->mm.aliasing_ppgtt;
1362         if (ppgtt)
1363                 err = gen6_ppgtt_pin(ppgtt);
1364
1365         return err;
1366 }
1367
1368 static void __context_unpin_ppgtt(struct i915_gem_context *ctx)
1369 {
1370         struct i915_hw_ppgtt *ppgtt;
1371
1372         ppgtt = ctx->ppgtt ?: ctx->i915->mm.aliasing_ppgtt;
1373         if (ppgtt)
1374                 gen6_ppgtt_unpin(ppgtt);
1375 }
1376
1377 static int __context_pin(struct intel_context *ce)
1378 {
1379         struct i915_vma *vma;
1380         int err;
1381
1382         vma = ce->state;
1383         if (!vma)
1384                 return 0;
1385
1386         err = i915_vma_pin(vma, 0, 0, PIN_GLOBAL | PIN_HIGH);
1387         if (err)
1388                 return err;
1389
1390         /*
1391          * And mark is as a globally pinned object to let the shrinker know
1392          * it cannot reclaim the object until we release it.
1393          */
1394         vma->obj->pin_global++;
1395         vma->obj->mm.dirty = true;
1396
1397         return 0;
1398 }
1399
1400 static void __context_unpin(struct intel_context *ce)
1401 {
1402         struct i915_vma *vma;
1403
1404         vma = ce->state;
1405         if (!vma)
1406                 return;
1407
1408         vma->obj->pin_global--;
1409         i915_vma_unpin(vma);
1410 }
1411
1412 static void ring_context_unpin(struct intel_context *ce)
1413 {
1414         __context_unpin_ppgtt(ce->gem_context);
1415         __context_unpin(ce);
1416 }
1417
1418 static struct i915_vma *
1419 alloc_context_vma(struct intel_engine_cs *engine)
1420 {
1421         struct drm_i915_private *i915 = engine->i915;
1422         struct drm_i915_gem_object *obj;
1423         struct i915_vma *vma;
1424         int err;
1425
1426         obj = i915_gem_object_create(i915, engine->context_size);
1427         if (IS_ERR(obj))
1428                 return ERR_CAST(obj);
1429
1430         /*
1431          * Try to make the context utilize L3 as well as LLC.
1432          *
1433          * On VLV we don't have L3 controls in the PTEs so we
1434          * shouldn't touch the cache level, especially as that
1435          * would make the object snooped which might have a
1436          * negative performance impact.
1437          *
1438          * Snooping is required on non-llc platforms in execlist
1439          * mode, but since all GGTT accesses use PAT entry 0 we
1440          * get snooping anyway regardless of cache_level.
1441          *
1442          * This is only applicable for Ivy Bridge devices since
1443          * later platforms don't have L3 control bits in the PTE.
1444          */
1445         if (IS_IVYBRIDGE(i915))
1446                 i915_gem_object_set_cache_coherency(obj, I915_CACHE_L3_LLC);
1447
1448         if (engine->default_state) {
1449                 void *defaults, *vaddr;
1450
1451                 vaddr = i915_gem_object_pin_map(obj, I915_MAP_WB);
1452                 if (IS_ERR(vaddr)) {
1453                         err = PTR_ERR(vaddr);
1454                         goto err_obj;
1455                 }
1456
1457                 defaults = i915_gem_object_pin_map(engine->default_state,
1458                                                    I915_MAP_WB);
1459                 if (IS_ERR(defaults)) {
1460                         err = PTR_ERR(defaults);
1461                         goto err_map;
1462                 }
1463
1464                 memcpy(vaddr, defaults, engine->context_size);
1465                 i915_gem_object_unpin_map(engine->default_state);
1466
1467                 i915_gem_object_flush_map(obj);
1468                 i915_gem_object_unpin_map(obj);
1469         }
1470
1471         vma = i915_vma_instance(obj, &i915->ggtt.vm, NULL);
1472         if (IS_ERR(vma)) {
1473                 err = PTR_ERR(vma);
1474                 goto err_obj;
1475         }
1476
1477         return vma;
1478
1479 err_map:
1480         i915_gem_object_unpin_map(obj);
1481 err_obj:
1482         i915_gem_object_put(obj);
1483         return ERR_PTR(err);
1484 }
1485
1486 static int ring_context_pin(struct intel_context *ce)
1487 {
1488         struct intel_engine_cs *engine = ce->engine;
1489         int err;
1490
1491         /* One ringbuffer to rule them all */
1492         GEM_BUG_ON(!engine->buffer);
1493         ce->ring = engine->buffer;
1494
1495         if (!ce->state && engine->context_size) {
1496                 struct i915_vma *vma;
1497
1498                 vma = alloc_context_vma(engine);
1499                 if (IS_ERR(vma))
1500                         return PTR_ERR(vma);
1501
1502                 ce->state = vma;
1503         }
1504
1505         err = __context_pin(ce);
1506         if (err)
1507                 return err;
1508
1509         err = __context_pin_ppgtt(ce->gem_context);
1510         if (err)
1511                 goto err_unpin;
1512
1513         return 0;
1514
1515 err_unpin:
1516         __context_unpin(ce);
1517         return err;
1518 }
1519
1520 static const struct intel_context_ops ring_context_ops = {
1521         .pin = ring_context_pin,
1522         .unpin = ring_context_unpin,
1523         .destroy = ring_context_destroy,
1524 };
1525
1526 static int intel_init_ring_buffer(struct intel_engine_cs *engine)
1527 {
1528         struct i915_timeline *timeline;
1529         struct intel_ring *ring;
1530         int err;
1531
1532         err = intel_engine_setup_common(engine);
1533         if (err)
1534                 return err;
1535
1536         timeline = i915_timeline_create(engine->i915, engine->status_page.vma);
1537         if (IS_ERR(timeline)) {
1538                 err = PTR_ERR(timeline);
1539                 goto err;
1540         }
1541         GEM_BUG_ON(timeline->has_initial_breadcrumb);
1542
1543         ring = intel_engine_create_ring(engine, timeline, 32 * PAGE_SIZE);
1544         i915_timeline_put(timeline);
1545         if (IS_ERR(ring)) {
1546                 err = PTR_ERR(ring);
1547                 goto err;
1548         }
1549
1550         err = intel_ring_pin(ring);
1551         if (err)
1552                 goto err_ring;
1553
1554         GEM_BUG_ON(engine->buffer);
1555         engine->buffer = ring;
1556
1557         err = intel_engine_init_common(engine);
1558         if (err)
1559                 goto err_unpin;
1560
1561         GEM_BUG_ON(ring->timeline->hwsp_ggtt != engine->status_page.vma);
1562
1563         return 0;
1564
1565 err_unpin:
1566         intel_ring_unpin(ring);
1567 err_ring:
1568         intel_ring_put(ring);
1569 err:
1570         intel_engine_cleanup_common(engine);
1571         return err;
1572 }
1573
1574 void intel_engine_cleanup(struct intel_engine_cs *engine)
1575 {
1576         struct drm_i915_private *dev_priv = engine->i915;
1577
1578         WARN_ON(INTEL_GEN(dev_priv) > 2 &&
1579                 (I915_READ_MODE(engine) & MODE_IDLE) == 0);
1580
1581         intel_ring_unpin(engine->buffer);
1582         intel_ring_put(engine->buffer);
1583
1584         if (engine->cleanup)
1585                 engine->cleanup(engine);
1586
1587         intel_engine_cleanup_common(engine);
1588
1589         dev_priv->engine[engine->id] = NULL;
1590         kfree(engine);
1591 }
1592
1593 void intel_legacy_submission_resume(struct drm_i915_private *dev_priv)
1594 {
1595         struct intel_engine_cs *engine;
1596         enum intel_engine_id id;
1597
1598         /* Restart from the beginning of the rings for convenience */
1599         for_each_engine(engine, dev_priv, id)
1600                 intel_ring_reset(engine->buffer, 0);
1601 }
1602
1603 static int load_pd_dir(struct i915_request *rq,
1604                        const struct i915_hw_ppgtt *ppgtt)
1605 {
1606         const struct intel_engine_cs * const engine = rq->engine;
1607         u32 *cs;
1608
1609         cs = intel_ring_begin(rq, 6);
1610         if (IS_ERR(cs))
1611                 return PTR_ERR(cs);
1612
1613         *cs++ = MI_LOAD_REGISTER_IMM(1);
1614         *cs++ = i915_mmio_reg_offset(RING_PP_DIR_DCLV(engine));
1615         *cs++ = PP_DIR_DCLV_2G;
1616
1617         *cs++ = MI_LOAD_REGISTER_IMM(1);
1618         *cs++ = i915_mmio_reg_offset(RING_PP_DIR_BASE(engine));
1619         *cs++ = ppgtt->pd.base.ggtt_offset << 10;
1620
1621         intel_ring_advance(rq, cs);
1622
1623         return 0;
1624 }
1625
1626 static int flush_pd_dir(struct i915_request *rq)
1627 {
1628         const struct intel_engine_cs * const engine = rq->engine;
1629         u32 *cs;
1630
1631         cs = intel_ring_begin(rq, 4);
1632         if (IS_ERR(cs))
1633                 return PTR_ERR(cs);
1634
1635         /* Stall until the page table load is complete */
1636         *cs++ = MI_STORE_REGISTER_MEM | MI_SRM_LRM_GLOBAL_GTT;
1637         *cs++ = i915_mmio_reg_offset(RING_PP_DIR_BASE(engine));
1638         *cs++ = i915_scratch_offset(rq->i915);
1639         *cs++ = MI_NOOP;
1640
1641         intel_ring_advance(rq, cs);
1642         return 0;
1643 }
1644
1645 static inline int mi_set_context(struct i915_request *rq, u32 flags)
1646 {
1647         struct drm_i915_private *i915 = rq->i915;
1648         struct intel_engine_cs *engine = rq->engine;
1649         enum intel_engine_id id;
1650         const int num_engines =
1651                 IS_HSW_GT1(i915) ? RUNTIME_INFO(i915)->num_engines - 1 : 0;
1652         bool force_restore = false;
1653         int len;
1654         u32 *cs;
1655
1656         flags |= MI_MM_SPACE_GTT;
1657         if (IS_HASWELL(i915))
1658                 /* These flags are for resource streamer on HSW+ */
1659                 flags |= HSW_MI_RS_SAVE_STATE_EN | HSW_MI_RS_RESTORE_STATE_EN;
1660         else
1661                 flags |= MI_SAVE_EXT_STATE_EN | MI_RESTORE_EXT_STATE_EN;
1662
1663         len = 4;
1664         if (IS_GEN(i915, 7))
1665                 len += 2 + (num_engines ? 4 * num_engines + 6 : 0);
1666         if (flags & MI_FORCE_RESTORE) {
1667                 GEM_BUG_ON(flags & MI_RESTORE_INHIBIT);
1668                 flags &= ~MI_FORCE_RESTORE;
1669                 force_restore = true;
1670                 len += 2;
1671         }
1672
1673         cs = intel_ring_begin(rq, len);
1674         if (IS_ERR(cs))
1675                 return PTR_ERR(cs);
1676
1677         /* WaProgramMiArbOnOffAroundMiSetContext:ivb,vlv,hsw,bdw,chv */
1678         if (IS_GEN(i915, 7)) {
1679                 *cs++ = MI_ARB_ON_OFF | MI_ARB_DISABLE;
1680                 if (num_engines) {
1681                         struct intel_engine_cs *signaller;
1682
1683                         *cs++ = MI_LOAD_REGISTER_IMM(num_engines);
1684                         for_each_engine(signaller, i915, id) {
1685                                 if (signaller == engine)
1686                                         continue;
1687
1688                                 *cs++ = i915_mmio_reg_offset(
1689                                            RING_PSMI_CTL(signaller->mmio_base));
1690                                 *cs++ = _MASKED_BIT_ENABLE(
1691                                                 GEN6_PSMI_SLEEP_MSG_DISABLE);
1692                         }
1693                 }
1694         }
1695
1696         if (force_restore) {
1697                 /*
1698                  * The HW doesn't handle being told to restore the current
1699                  * context very well. Quite often it likes goes to go off and
1700                  * sulk, especially when it is meant to be reloading PP_DIR.
1701                  * A very simple fix to force the reload is to simply switch
1702                  * away from the current context and back again.
1703                  *
1704                  * Note that the kernel_context will contain random state
1705                  * following the INHIBIT_RESTORE. We accept this since we
1706                  * never use the kernel_context state; it is merely a
1707                  * placeholder we use to flush other contexts.
1708                  */
1709                 *cs++ = MI_SET_CONTEXT;
1710                 *cs++ = i915_ggtt_offset(engine->kernel_context->state) |
1711                         MI_MM_SPACE_GTT |
1712                         MI_RESTORE_INHIBIT;
1713         }
1714
1715         *cs++ = MI_NOOP;
1716         *cs++ = MI_SET_CONTEXT;
1717         *cs++ = i915_ggtt_offset(rq->hw_context->state) | flags;
1718         /*
1719          * w/a: MI_SET_CONTEXT must always be followed by MI_NOOP
1720          * WaMiSetContext_Hang:snb,ivb,vlv
1721          */
1722         *cs++ = MI_NOOP;
1723
1724         if (IS_GEN(i915, 7)) {
1725                 if (num_engines) {
1726                         struct intel_engine_cs *signaller;
1727                         i915_reg_t last_reg = {}; /* keep gcc quiet */
1728
1729                         *cs++ = MI_LOAD_REGISTER_IMM(num_engines);
1730                         for_each_engine(signaller, i915, id) {
1731                                 if (signaller == engine)
1732                                         continue;
1733
1734                                 last_reg = RING_PSMI_CTL(signaller->mmio_base);
1735                                 *cs++ = i915_mmio_reg_offset(last_reg);
1736                                 *cs++ = _MASKED_BIT_DISABLE(
1737                                                 GEN6_PSMI_SLEEP_MSG_DISABLE);
1738                         }
1739
1740                         /* Insert a delay before the next switch! */
1741                         *cs++ = MI_STORE_REGISTER_MEM | MI_SRM_LRM_GLOBAL_GTT;
1742                         *cs++ = i915_mmio_reg_offset(last_reg);
1743                         *cs++ = i915_scratch_offset(rq->i915);
1744                         *cs++ = MI_NOOP;
1745                 }
1746                 *cs++ = MI_ARB_ON_OFF | MI_ARB_ENABLE;
1747         }
1748
1749         intel_ring_advance(rq, cs);
1750
1751         return 0;
1752 }
1753
1754 static int remap_l3(struct i915_request *rq, int slice)
1755 {
1756         u32 *cs, *remap_info = rq->i915->l3_parity.remap_info[slice];
1757         int i;
1758
1759         if (!remap_info)
1760                 return 0;
1761
1762         cs = intel_ring_begin(rq, GEN7_L3LOG_SIZE/4 * 2 + 2);
1763         if (IS_ERR(cs))
1764                 return PTR_ERR(cs);
1765
1766         /*
1767          * Note: We do not worry about the concurrent register cacheline hang
1768          * here because no other code should access these registers other than
1769          * at initialization time.
1770          */
1771         *cs++ = MI_LOAD_REGISTER_IMM(GEN7_L3LOG_SIZE/4);
1772         for (i = 0; i < GEN7_L3LOG_SIZE/4; i++) {
1773                 *cs++ = i915_mmio_reg_offset(GEN7_L3LOG(slice, i));
1774                 *cs++ = remap_info[i];
1775         }
1776         *cs++ = MI_NOOP;
1777         intel_ring_advance(rq, cs);
1778
1779         return 0;
1780 }
1781
1782 static int switch_context(struct i915_request *rq)
1783 {
1784         struct intel_engine_cs *engine = rq->engine;
1785         struct i915_gem_context *ctx = rq->gem_context;
1786         struct i915_hw_ppgtt *ppgtt = ctx->ppgtt ?: rq->i915->mm.aliasing_ppgtt;
1787         unsigned int unwind_mm = 0;
1788         u32 hw_flags = 0;
1789         int ret, i;
1790
1791         lockdep_assert_held(&rq->i915->drm.struct_mutex);
1792         GEM_BUG_ON(HAS_EXECLISTS(rq->i915));
1793
1794         if (ppgtt) {
1795                 int loops;
1796
1797                 /*
1798                  * Baytail takes a little more convincing that it really needs
1799                  * to reload the PD between contexts. It is not just a little
1800                  * longer, as adding more stalls after the load_pd_dir (i.e.
1801                  * adding a long loop around flush_pd_dir) is not as effective
1802                  * as reloading the PD umpteen times. 32 is derived from
1803                  * experimentation (gem_exec_parallel/fds) and has no good
1804                  * explanation.
1805                  */
1806                 loops = 1;
1807                 if (engine->id == BCS0 && IS_VALLEYVIEW(engine->i915))
1808                         loops = 32;
1809
1810                 do {
1811                         ret = load_pd_dir(rq, ppgtt);
1812                         if (ret)
1813                                 goto err;
1814                 } while (--loops);
1815
1816                 if (ppgtt->pd_dirty_engines & engine->mask) {
1817                         unwind_mm = engine->mask;
1818                         ppgtt->pd_dirty_engines &= ~unwind_mm;
1819                         hw_flags = MI_FORCE_RESTORE;
1820                 }
1821         }
1822
1823         if (rq->hw_context->state) {
1824                 GEM_BUG_ON(engine->id != RCS0);
1825
1826                 /*
1827                  * The kernel context(s) is treated as pure scratch and is not
1828                  * expected to retain any state (as we sacrifice it during
1829                  * suspend and on resume it may be corrupted). This is ok,
1830                  * as nothing actually executes using the kernel context; it
1831                  * is purely used for flushing user contexts.
1832                  */
1833                 if (i915_gem_context_is_kernel(ctx))
1834                         hw_flags = MI_RESTORE_INHIBIT;
1835
1836                 ret = mi_set_context(rq, hw_flags);
1837                 if (ret)
1838                         goto err_mm;
1839         }
1840
1841         if (ppgtt) {
1842                 ret = engine->emit_flush(rq, EMIT_INVALIDATE);
1843                 if (ret)
1844                         goto err_mm;
1845
1846                 ret = flush_pd_dir(rq);
1847                 if (ret)
1848                         goto err_mm;
1849
1850                 /*
1851                  * Not only do we need a full barrier (post-sync write) after
1852                  * invalidating the TLBs, but we need to wait a little bit
1853                  * longer. Whether this is merely delaying us, or the
1854                  * subsequent flush is a key part of serialising with the
1855                  * post-sync op, this extra pass appears vital before a
1856                  * mm switch!
1857                  */
1858                 ret = engine->emit_flush(rq, EMIT_INVALIDATE);
1859                 if (ret)
1860                         goto err_mm;
1861
1862                 ret = engine->emit_flush(rq, EMIT_FLUSH);
1863                 if (ret)
1864                         goto err_mm;
1865         }
1866
1867         if (ctx->remap_slice) {
1868                 for (i = 0; i < MAX_L3_SLICES; i++) {
1869                         if (!(ctx->remap_slice & BIT(i)))
1870                                 continue;
1871
1872                         ret = remap_l3(rq, i);
1873                         if (ret)
1874                                 goto err_mm;
1875                 }
1876
1877                 ctx->remap_slice = 0;
1878         }
1879
1880         return 0;
1881
1882 err_mm:
1883         if (unwind_mm)
1884                 ppgtt->pd_dirty_engines |= unwind_mm;
1885 err:
1886         return ret;
1887 }
1888
1889 static int ring_request_alloc(struct i915_request *request)
1890 {
1891         int ret;
1892
1893         GEM_BUG_ON(!intel_context_is_pinned(request->hw_context));
1894         GEM_BUG_ON(request->timeline->has_initial_breadcrumb);
1895
1896         /*
1897          * Flush enough space to reduce the likelihood of waiting after
1898          * we start building the request - in which case we will just
1899          * have to repeat work.
1900          */
1901         request->reserved_space += LEGACY_REQUEST_SIZE;
1902
1903         ret = switch_context(request);
1904         if (ret)
1905                 return ret;
1906
1907         /* Unconditionally invalidate GPU caches and TLBs. */
1908         ret = request->engine->emit_flush(request, EMIT_INVALIDATE);
1909         if (ret)
1910                 return ret;
1911
1912         request->reserved_space -= LEGACY_REQUEST_SIZE;
1913         return 0;
1914 }
1915
1916 static noinline int wait_for_space(struct intel_ring *ring, unsigned int bytes)
1917 {
1918         struct i915_request *target;
1919         long timeout;
1920
1921         lockdep_assert_held(&ring->vma->vm->i915->drm.struct_mutex);
1922
1923         if (intel_ring_update_space(ring) >= bytes)
1924                 return 0;
1925
1926         GEM_BUG_ON(list_empty(&ring->request_list));
1927         list_for_each_entry(target, &ring->request_list, ring_link) {
1928                 /* Would completion of this request free enough space? */
1929                 if (bytes <= __intel_ring_space(target->postfix,
1930                                                 ring->emit, ring->size))
1931                         break;
1932         }
1933
1934         if (WARN_ON(&target->ring_link == &ring->request_list))
1935                 return -ENOSPC;
1936
1937         timeout = i915_request_wait(target,
1938                                     I915_WAIT_INTERRUPTIBLE | I915_WAIT_LOCKED,
1939                                     MAX_SCHEDULE_TIMEOUT);
1940         if (timeout < 0)
1941                 return timeout;
1942
1943         i915_request_retire_upto(target);
1944
1945         intel_ring_update_space(ring);
1946         GEM_BUG_ON(ring->space < bytes);
1947         return 0;
1948 }
1949
1950 u32 *intel_ring_begin(struct i915_request *rq, unsigned int num_dwords)
1951 {
1952         struct intel_ring *ring = rq->ring;
1953         const unsigned int remain_usable = ring->effective_size - ring->emit;
1954         const unsigned int bytes = num_dwords * sizeof(u32);
1955         unsigned int need_wrap = 0;
1956         unsigned int total_bytes;
1957         u32 *cs;
1958
1959         /* Packets must be qword aligned. */
1960         GEM_BUG_ON(num_dwords & 1);
1961
1962         total_bytes = bytes + rq->reserved_space;
1963         GEM_BUG_ON(total_bytes > ring->effective_size);
1964
1965         if (unlikely(total_bytes > remain_usable)) {
1966                 const int remain_actual = ring->size - ring->emit;
1967
1968                 if (bytes > remain_usable) {
1969                         /*
1970                          * Not enough space for the basic request. So need to
1971                          * flush out the remainder and then wait for
1972                          * base + reserved.
1973                          */
1974                         total_bytes += remain_actual;
1975                         need_wrap = remain_actual | 1;
1976                 } else  {
1977                         /*
1978                          * The base request will fit but the reserved space
1979                          * falls off the end. So we don't need an immediate
1980                          * wrap and only need to effectively wait for the
1981                          * reserved size from the start of ringbuffer.
1982                          */
1983                         total_bytes = rq->reserved_space + remain_actual;
1984                 }
1985         }
1986
1987         if (unlikely(total_bytes > ring->space)) {
1988                 int ret;
1989
1990                 /*
1991                  * Space is reserved in the ringbuffer for finalising the
1992                  * request, as that cannot be allowed to fail. During request
1993                  * finalisation, reserved_space is set to 0 to stop the
1994                  * overallocation and the assumption is that then we never need
1995                  * to wait (which has the risk of failing with EINTR).
1996                  *
1997                  * See also i915_request_alloc() and i915_request_add().
1998                  */
1999                 GEM_BUG_ON(!rq->reserved_space);
2000
2001                 ret = wait_for_space(ring, total_bytes);
2002                 if (unlikely(ret))
2003                         return ERR_PTR(ret);
2004         }
2005
2006         if (unlikely(need_wrap)) {
2007                 need_wrap &= ~1;
2008                 GEM_BUG_ON(need_wrap > ring->space);
2009                 GEM_BUG_ON(ring->emit + need_wrap > ring->size);
2010                 GEM_BUG_ON(!IS_ALIGNED(need_wrap, sizeof(u64)));
2011
2012                 /* Fill the tail with MI_NOOP */
2013                 memset64(ring->vaddr + ring->emit, 0, need_wrap / sizeof(u64));
2014                 ring->space -= need_wrap;
2015                 ring->emit = 0;
2016         }
2017
2018         GEM_BUG_ON(ring->emit > ring->size - bytes);
2019         GEM_BUG_ON(ring->space < bytes);
2020         cs = ring->vaddr + ring->emit;
2021         GEM_DEBUG_EXEC(memset32(cs, POISON_INUSE, bytes / sizeof(*cs)));
2022         ring->emit += bytes;
2023         ring->space -= bytes;
2024
2025         return cs;
2026 }
2027
2028 /* Align the ring tail to a cacheline boundary */
2029 int intel_ring_cacheline_align(struct i915_request *rq)
2030 {
2031         int num_dwords;
2032         void *cs;
2033
2034         num_dwords = (rq->ring->emit & (CACHELINE_BYTES - 1)) / sizeof(u32);
2035         if (num_dwords == 0)
2036                 return 0;
2037
2038         num_dwords = CACHELINE_DWORDS - num_dwords;
2039         GEM_BUG_ON(num_dwords & 1);
2040
2041         cs = intel_ring_begin(rq, num_dwords);
2042         if (IS_ERR(cs))
2043                 return PTR_ERR(cs);
2044
2045         memset64(cs, (u64)MI_NOOP << 32 | MI_NOOP, num_dwords / 2);
2046         intel_ring_advance(rq, cs);
2047
2048         GEM_BUG_ON(rq->ring->emit & (CACHELINE_BYTES - 1));
2049         return 0;
2050 }
2051
2052 static void gen6_bsd_submit_request(struct i915_request *request)
2053 {
2054         struct drm_i915_private *dev_priv = request->i915;
2055
2056         intel_uncore_forcewake_get(&dev_priv->uncore, FORCEWAKE_ALL);
2057
2058        /* Every tail move must follow the sequence below */
2059
2060         /* Disable notification that the ring is IDLE. The GT
2061          * will then assume that it is busy and bring it out of rc6.
2062          */
2063         I915_WRITE_FW(GEN6_BSD_SLEEP_PSMI_CONTROL,
2064                       _MASKED_BIT_ENABLE(GEN6_BSD_SLEEP_MSG_DISABLE));
2065
2066         /* Clear the context id. Here be magic! */
2067         I915_WRITE64_FW(GEN6_BSD_RNCID, 0x0);
2068
2069         /* Wait for the ring not to be idle, i.e. for it to wake up. */
2070         if (__intel_wait_for_register_fw(dev_priv,
2071                                          GEN6_BSD_SLEEP_PSMI_CONTROL,
2072                                          GEN6_BSD_SLEEP_INDICATOR,
2073                                          0,
2074                                          1000, 0, NULL))
2075                 DRM_ERROR("timed out waiting for the BSD ring to wake up\n");
2076
2077         /* Now that the ring is fully powered up, update the tail */
2078         i9xx_submit_request(request);
2079
2080         /* Let the ring send IDLE messages to the GT again,
2081          * and so let it sleep to conserve power when idle.
2082          */
2083         I915_WRITE_FW(GEN6_BSD_SLEEP_PSMI_CONTROL,
2084                       _MASKED_BIT_DISABLE(GEN6_BSD_SLEEP_MSG_DISABLE));
2085
2086         intel_uncore_forcewake_put(&dev_priv->uncore, FORCEWAKE_ALL);
2087 }
2088
2089 static int mi_flush_dw(struct i915_request *rq, u32 flags)
2090 {
2091         u32 cmd, *cs;
2092
2093         cs = intel_ring_begin(rq, 4);
2094         if (IS_ERR(cs))
2095                 return PTR_ERR(cs);
2096
2097         cmd = MI_FLUSH_DW;
2098
2099         /*
2100          * We always require a command barrier so that subsequent
2101          * commands, such as breadcrumb interrupts, are strictly ordered
2102          * wrt the contents of the write cache being flushed to memory
2103          * (and thus being coherent from the CPU).
2104          */
2105         cmd |= MI_FLUSH_DW_STORE_INDEX | MI_FLUSH_DW_OP_STOREDW;
2106
2107         /*
2108          * Bspec vol 1c.3 - blitter engine command streamer:
2109          * "If ENABLED, all TLBs will be invalidated once the flush
2110          * operation is complete. This bit is only valid when the
2111          * Post-Sync Operation field is a value of 1h or 3h."
2112          */
2113         cmd |= flags;
2114
2115         *cs++ = cmd;
2116         *cs++ = I915_GEM_HWS_SCRATCH_ADDR | MI_FLUSH_DW_USE_GTT;
2117         *cs++ = 0;
2118         *cs++ = MI_NOOP;
2119
2120         intel_ring_advance(rq, cs);
2121
2122         return 0;
2123 }
2124
2125 static int gen6_flush_dw(struct i915_request *rq, u32 mode, u32 invflags)
2126 {
2127         return mi_flush_dw(rq, mode & EMIT_INVALIDATE ? invflags : 0);
2128 }
2129
2130 static int gen6_bsd_ring_flush(struct i915_request *rq, u32 mode)
2131 {
2132         return gen6_flush_dw(rq, mode, MI_INVALIDATE_TLB | MI_INVALIDATE_BSD);
2133 }
2134
2135 static int
2136 hsw_emit_bb_start(struct i915_request *rq,
2137                   u64 offset, u32 len,
2138                   unsigned int dispatch_flags)
2139 {
2140         u32 *cs;
2141
2142         cs = intel_ring_begin(rq, 2);
2143         if (IS_ERR(cs))
2144                 return PTR_ERR(cs);
2145
2146         *cs++ = MI_BATCH_BUFFER_START | (dispatch_flags & I915_DISPATCH_SECURE ?
2147                 0 : MI_BATCH_PPGTT_HSW | MI_BATCH_NON_SECURE_HSW);
2148         /* bit0-7 is the length on GEN6+ */
2149         *cs++ = offset;
2150         intel_ring_advance(rq, cs);
2151
2152         return 0;
2153 }
2154
2155 static int
2156 gen6_emit_bb_start(struct i915_request *rq,
2157                    u64 offset, u32 len,
2158                    unsigned int dispatch_flags)
2159 {
2160         u32 *cs;
2161
2162         cs = intel_ring_begin(rq, 2);
2163         if (IS_ERR(cs))
2164                 return PTR_ERR(cs);
2165
2166         *cs++ = MI_BATCH_BUFFER_START | (dispatch_flags & I915_DISPATCH_SECURE ?
2167                 0 : MI_BATCH_NON_SECURE_I965);
2168         /* bit0-7 is the length on GEN6+ */
2169         *cs++ = offset;
2170         intel_ring_advance(rq, cs);
2171
2172         return 0;
2173 }
2174
2175 /* Blitter support (SandyBridge+) */
2176
2177 static int gen6_ring_flush(struct i915_request *rq, u32 mode)
2178 {
2179         return gen6_flush_dw(rq, mode, MI_INVALIDATE_TLB);
2180 }
2181
2182 static void intel_ring_init_irq(struct drm_i915_private *dev_priv,
2183                                 struct intel_engine_cs *engine)
2184 {
2185         if (INTEL_GEN(dev_priv) >= 6) {
2186                 engine->irq_enable = gen6_irq_enable;
2187                 engine->irq_disable = gen6_irq_disable;
2188         } else if (INTEL_GEN(dev_priv) >= 5) {
2189                 engine->irq_enable = gen5_irq_enable;
2190                 engine->irq_disable = gen5_irq_disable;
2191         } else if (INTEL_GEN(dev_priv) >= 3) {
2192                 engine->irq_enable = i9xx_irq_enable;
2193                 engine->irq_disable = i9xx_irq_disable;
2194         } else {
2195                 engine->irq_enable = i8xx_irq_enable;
2196                 engine->irq_disable = i8xx_irq_disable;
2197         }
2198 }
2199
2200 static void i9xx_set_default_submission(struct intel_engine_cs *engine)
2201 {
2202         engine->submit_request = i9xx_submit_request;
2203         engine->cancel_requests = cancel_requests;
2204
2205         engine->park = NULL;
2206         engine->unpark = NULL;
2207 }
2208
2209 static void gen6_bsd_set_default_submission(struct intel_engine_cs *engine)
2210 {
2211         i9xx_set_default_submission(engine);
2212         engine->submit_request = gen6_bsd_submit_request;
2213 }
2214
2215 static void intel_ring_default_vfuncs(struct drm_i915_private *dev_priv,
2216                                       struct intel_engine_cs *engine)
2217 {
2218         /* gen8+ are only supported with execlists */
2219         GEM_BUG_ON(INTEL_GEN(dev_priv) >= 8);
2220
2221         intel_ring_init_irq(dev_priv, engine);
2222
2223         engine->init_hw = init_ring_common;
2224         engine->reset.prepare = reset_prepare;
2225         engine->reset.reset = reset_ring;
2226         engine->reset.finish = reset_finish;
2227
2228         engine->cops = &ring_context_ops;
2229         engine->request_alloc = ring_request_alloc;
2230
2231         /*
2232          * Using a global execution timeline; the previous final breadcrumb is
2233          * equivalent to our next initial bread so we can elide
2234          * engine->emit_init_breadcrumb().
2235          */
2236         engine->emit_fini_breadcrumb = i9xx_emit_breadcrumb;
2237         if (IS_GEN(dev_priv, 5))
2238                 engine->emit_fini_breadcrumb = gen5_emit_breadcrumb;
2239
2240         engine->set_default_submission = i9xx_set_default_submission;
2241
2242         if (INTEL_GEN(dev_priv) >= 6)
2243                 engine->emit_bb_start = gen6_emit_bb_start;
2244         else if (INTEL_GEN(dev_priv) >= 4)
2245                 engine->emit_bb_start = i965_emit_bb_start;
2246         else if (IS_I830(dev_priv) || IS_I845G(dev_priv))
2247                 engine->emit_bb_start = i830_emit_bb_start;
2248         else
2249                 engine->emit_bb_start = i915_emit_bb_start;
2250 }
2251
2252 int intel_init_render_ring_buffer(struct intel_engine_cs *engine)
2253 {
2254         struct drm_i915_private *dev_priv = engine->i915;
2255         int ret;
2256
2257         intel_ring_default_vfuncs(dev_priv, engine);
2258
2259         if (HAS_L3_DPF(dev_priv))
2260                 engine->irq_keep_mask = GT_RENDER_L3_PARITY_ERROR_INTERRUPT;
2261
2262         engine->irq_enable_mask = GT_RENDER_USER_INTERRUPT;
2263
2264         if (INTEL_GEN(dev_priv) >= 7) {
2265                 engine->init_context = intel_rcs_ctx_init;
2266                 engine->emit_flush = gen7_render_ring_flush;
2267                 engine->emit_fini_breadcrumb = gen7_rcs_emit_breadcrumb;
2268         } else if (IS_GEN(dev_priv, 6)) {
2269                 engine->init_context = intel_rcs_ctx_init;
2270                 engine->emit_flush = gen6_render_ring_flush;
2271                 engine->emit_fini_breadcrumb = gen6_rcs_emit_breadcrumb;
2272         } else if (IS_GEN(dev_priv, 5)) {
2273                 engine->emit_flush = gen4_render_ring_flush;
2274         } else {
2275                 if (INTEL_GEN(dev_priv) < 4)
2276                         engine->emit_flush = gen2_render_ring_flush;
2277                 else
2278                         engine->emit_flush = gen4_render_ring_flush;
2279                 engine->irq_enable_mask = I915_USER_INTERRUPT;
2280         }
2281
2282         if (IS_HASWELL(dev_priv))
2283                 engine->emit_bb_start = hsw_emit_bb_start;
2284
2285         engine->init_hw = init_render_ring;
2286
2287         ret = intel_init_ring_buffer(engine);
2288         if (ret)
2289                 return ret;
2290
2291         return 0;
2292 }
2293
2294 int intel_init_bsd_ring_buffer(struct intel_engine_cs *engine)
2295 {
2296         struct drm_i915_private *dev_priv = engine->i915;
2297
2298         intel_ring_default_vfuncs(dev_priv, engine);
2299
2300         if (INTEL_GEN(dev_priv) >= 6) {
2301                 /* gen6 bsd needs a special wa for tail updates */
2302                 if (IS_GEN(dev_priv, 6))
2303                         engine->set_default_submission = gen6_bsd_set_default_submission;
2304                 engine->emit_flush = gen6_bsd_ring_flush;
2305                 engine->irq_enable_mask = GT_BSD_USER_INTERRUPT;
2306
2307                 if (IS_GEN(dev_priv, 6))
2308                         engine->emit_fini_breadcrumb = gen6_xcs_emit_breadcrumb;
2309                 else
2310                         engine->emit_fini_breadcrumb = gen7_xcs_emit_breadcrumb;
2311         } else {
2312                 engine->emit_flush = bsd_ring_flush;
2313                 if (IS_GEN(dev_priv, 5))
2314                         engine->irq_enable_mask = ILK_BSD_USER_INTERRUPT;
2315                 else
2316                         engine->irq_enable_mask = I915_BSD_USER_INTERRUPT;
2317         }
2318
2319         return intel_init_ring_buffer(engine);
2320 }
2321
2322 int intel_init_blt_ring_buffer(struct intel_engine_cs *engine)
2323 {
2324         struct drm_i915_private *dev_priv = engine->i915;
2325
2326         GEM_BUG_ON(INTEL_GEN(dev_priv) < 6);
2327
2328         intel_ring_default_vfuncs(dev_priv, engine);
2329
2330         engine->emit_flush = gen6_ring_flush;
2331         engine->irq_enable_mask = GT_BLT_USER_INTERRUPT;
2332
2333         if (IS_GEN(dev_priv, 6))
2334                 engine->emit_fini_breadcrumb = gen6_xcs_emit_breadcrumb;
2335         else
2336                 engine->emit_fini_breadcrumb = gen7_xcs_emit_breadcrumb;
2337
2338         return intel_init_ring_buffer(engine);
2339 }
2340
2341 int intel_init_vebox_ring_buffer(struct intel_engine_cs *engine)
2342 {
2343         struct drm_i915_private *dev_priv = engine->i915;
2344
2345         GEM_BUG_ON(INTEL_GEN(dev_priv) < 7);
2346
2347         intel_ring_default_vfuncs(dev_priv, engine);
2348
2349         engine->emit_flush = gen6_ring_flush;
2350         engine->irq_enable_mask = PM_VEBOX_USER_INTERRUPT;
2351         engine->irq_enable = hsw_vebox_irq_enable;
2352         engine->irq_disable = hsw_vebox_irq_disable;
2353
2354         engine->emit_fini_breadcrumb = gen7_xcs_emit_breadcrumb;
2355
2356         return intel_init_ring_buffer(engine);
2357 }