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