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