drm/i915: Move the get/put irq locking into the caller
[cascardo/linux.git] / drivers / gpu / drm / i915 / intel_ringbuffer.c
1 /*
2  * Copyright © 2008-2010 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  *
23  * Authors:
24  *    Eric Anholt <eric@anholt.net>
25  *    Zou Nan hai <nanhai.zou@intel.com>
26  *    Xiang Hai hao<haihao.xiang@intel.com>
27  *
28  */
29
30 #include <linux/log2.h>
31 #include <drm/drmP.h>
32 #include "i915_drv.h"
33 #include <drm/i915_drm.h>
34 #include "i915_trace.h"
35 #include "intel_drv.h"
36
37 /* Rough estimate of the typical request size, performing a flush,
38  * set-context and then emitting the batch.
39  */
40 #define LEGACY_REQUEST_SIZE 200
41
42 int __intel_ring_space(int head, int tail, int size)
43 {
44         int space = head - tail;
45         if (space <= 0)
46                 space += size;
47         return space - I915_RING_FREE_SPACE;
48 }
49
50 void intel_ring_update_space(struct intel_ringbuffer *ringbuf)
51 {
52         if (ringbuf->last_retired_head != -1) {
53                 ringbuf->head = ringbuf->last_retired_head;
54                 ringbuf->last_retired_head = -1;
55         }
56
57         ringbuf->space = __intel_ring_space(ringbuf->head & HEAD_ADDR,
58                                             ringbuf->tail, ringbuf->size);
59 }
60
61 bool intel_engine_stopped(struct intel_engine_cs *engine)
62 {
63         struct drm_i915_private *dev_priv = engine->i915;
64         return dev_priv->gpu_error.stop_rings & intel_engine_flag(engine);
65 }
66
67 static void __intel_ring_advance(struct intel_engine_cs *engine)
68 {
69         struct intel_ringbuffer *ringbuf = engine->buffer;
70         ringbuf->tail &= ringbuf->size - 1;
71         if (intel_engine_stopped(engine))
72                 return;
73         engine->write_tail(engine, ringbuf->tail);
74 }
75
76 static int
77 gen2_render_ring_flush(struct drm_i915_gem_request *req,
78                        u32      invalidate_domains,
79                        u32      flush_domains)
80 {
81         struct intel_engine_cs *engine = req->engine;
82         u32 cmd;
83         int ret;
84
85         cmd = MI_FLUSH;
86         if (((invalidate_domains|flush_domains) & I915_GEM_DOMAIN_RENDER) == 0)
87                 cmd |= MI_NO_WRITE_FLUSH;
88
89         if (invalidate_domains & I915_GEM_DOMAIN_SAMPLER)
90                 cmd |= MI_READ_FLUSH;
91
92         ret = intel_ring_begin(req, 2);
93         if (ret)
94                 return ret;
95
96         intel_ring_emit(engine, cmd);
97         intel_ring_emit(engine, MI_NOOP);
98         intel_ring_advance(engine);
99
100         return 0;
101 }
102
103 static int
104 gen4_render_ring_flush(struct drm_i915_gem_request *req,
105                        u32      invalidate_domains,
106                        u32      flush_domains)
107 {
108         struct intel_engine_cs *engine = req->engine;
109         u32 cmd;
110         int ret;
111
112         /*
113          * read/write caches:
114          *
115          * I915_GEM_DOMAIN_RENDER is always invalidated, but is
116          * only flushed if MI_NO_WRITE_FLUSH is unset.  On 965, it is
117          * also flushed at 2d versus 3d pipeline switches.
118          *
119          * read-only caches:
120          *
121          * I915_GEM_DOMAIN_SAMPLER is flushed on pre-965 if
122          * MI_READ_FLUSH is set, and is always flushed on 965.
123          *
124          * I915_GEM_DOMAIN_COMMAND may not exist?
125          *
126          * I915_GEM_DOMAIN_INSTRUCTION, which exists on 965, is
127          * invalidated when MI_EXE_FLUSH is set.
128          *
129          * I915_GEM_DOMAIN_VERTEX, which exists on 965, is
130          * invalidated with every MI_FLUSH.
131          *
132          * TLBs:
133          *
134          * On 965, TLBs associated with I915_GEM_DOMAIN_COMMAND
135          * and I915_GEM_DOMAIN_CPU in are invalidated at PTE write and
136          * I915_GEM_DOMAIN_RENDER and I915_GEM_DOMAIN_SAMPLER
137          * are flushed at any MI_FLUSH.
138          */
139
140         cmd = MI_FLUSH | MI_NO_WRITE_FLUSH;
141         if ((invalidate_domains|flush_domains) & I915_GEM_DOMAIN_RENDER)
142                 cmd &= ~MI_NO_WRITE_FLUSH;
143         if (invalidate_domains & I915_GEM_DOMAIN_INSTRUCTION)
144                 cmd |= MI_EXE_FLUSH;
145
146         if (invalidate_domains & I915_GEM_DOMAIN_COMMAND &&
147             (IS_G4X(req->i915) || IS_GEN5(req->i915)))
148                 cmd |= MI_INVALIDATE_ISP;
149
150         ret = intel_ring_begin(req, 2);
151         if (ret)
152                 return ret;
153
154         intel_ring_emit(engine, cmd);
155         intel_ring_emit(engine, MI_NOOP);
156         intel_ring_advance(engine);
157
158         return 0;
159 }
160
161 /**
162  * Emits a PIPE_CONTROL with a non-zero post-sync operation, for
163  * implementing two workarounds on gen6.  From section 1.4.7.1
164  * "PIPE_CONTROL" of the Sandy Bridge PRM volume 2 part 1:
165  *
166  * [DevSNB-C+{W/A}] Before any depth stall flush (including those
167  * produced by non-pipelined state commands), software needs to first
168  * send a PIPE_CONTROL with no bits set except Post-Sync Operation !=
169  * 0.
170  *
171  * [Dev-SNB{W/A}]: Before a PIPE_CONTROL with Write Cache Flush Enable
172  * =1, a PIPE_CONTROL with any non-zero post-sync-op is required.
173  *
174  * And the workaround for these two requires this workaround first:
175  *
176  * [Dev-SNB{W/A}]: Pipe-control with CS-stall bit set must be sent
177  * BEFORE the pipe-control with a post-sync op and no write-cache
178  * flushes.
179  *
180  * And this last workaround is tricky because of the requirements on
181  * that bit.  From section 1.4.7.2.3 "Stall" of the Sandy Bridge PRM
182  * volume 2 part 1:
183  *
184  *     "1 of the following must also be set:
185  *      - Render Target Cache Flush Enable ([12] of DW1)
186  *      - Depth Cache Flush Enable ([0] of DW1)
187  *      - Stall at Pixel Scoreboard ([1] of DW1)
188  *      - Depth Stall ([13] of DW1)
189  *      - Post-Sync Operation ([13] of DW1)
190  *      - Notify Enable ([8] of DW1)"
191  *
192  * The cache flushes require the workaround flush that triggered this
193  * one, so we can't use it.  Depth stall would trigger the same.
194  * Post-sync nonzero is what triggered this second workaround, so we
195  * can't use that one either.  Notify enable is IRQs, which aren't
196  * really our business.  That leaves only stall at scoreboard.
197  */
198 static int
199 intel_emit_post_sync_nonzero_flush(struct drm_i915_gem_request *req)
200 {
201         struct intel_engine_cs *engine = req->engine;
202         u32 scratch_addr = engine->scratch.gtt_offset + 2 * CACHELINE_BYTES;
203         int ret;
204
205         ret = intel_ring_begin(req, 6);
206         if (ret)
207                 return ret;
208
209         intel_ring_emit(engine, GFX_OP_PIPE_CONTROL(5));
210         intel_ring_emit(engine, PIPE_CONTROL_CS_STALL |
211                         PIPE_CONTROL_STALL_AT_SCOREBOARD);
212         intel_ring_emit(engine, scratch_addr | PIPE_CONTROL_GLOBAL_GTT); /* address */
213         intel_ring_emit(engine, 0); /* low dword */
214         intel_ring_emit(engine, 0); /* high dword */
215         intel_ring_emit(engine, MI_NOOP);
216         intel_ring_advance(engine);
217
218         ret = intel_ring_begin(req, 6);
219         if (ret)
220                 return ret;
221
222         intel_ring_emit(engine, GFX_OP_PIPE_CONTROL(5));
223         intel_ring_emit(engine, PIPE_CONTROL_QW_WRITE);
224         intel_ring_emit(engine, scratch_addr | PIPE_CONTROL_GLOBAL_GTT); /* address */
225         intel_ring_emit(engine, 0);
226         intel_ring_emit(engine, 0);
227         intel_ring_emit(engine, MI_NOOP);
228         intel_ring_advance(engine);
229
230         return 0;
231 }
232
233 static int
234 gen6_render_ring_flush(struct drm_i915_gem_request *req,
235                        u32 invalidate_domains, u32 flush_domains)
236 {
237         struct intel_engine_cs *engine = req->engine;
238         u32 flags = 0;
239         u32 scratch_addr = engine->scratch.gtt_offset + 2 * CACHELINE_BYTES;
240         int ret;
241
242         /* Force SNB workarounds for PIPE_CONTROL flushes */
243         ret = intel_emit_post_sync_nonzero_flush(req);
244         if (ret)
245                 return ret;
246
247         /* Just flush everything.  Experiments have shown that reducing the
248          * number of bits based on the write domains has little performance
249          * impact.
250          */
251         if (flush_domains) {
252                 flags |= PIPE_CONTROL_RENDER_TARGET_CACHE_FLUSH;
253                 flags |= PIPE_CONTROL_DEPTH_CACHE_FLUSH;
254                 /*
255                  * Ensure that any following seqno writes only happen
256                  * when the render cache is indeed flushed.
257                  */
258                 flags |= PIPE_CONTROL_CS_STALL;
259         }
260         if (invalidate_domains) {
261                 flags |= PIPE_CONTROL_TLB_INVALIDATE;
262                 flags |= PIPE_CONTROL_INSTRUCTION_CACHE_INVALIDATE;
263                 flags |= PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE;
264                 flags |= PIPE_CONTROL_VF_CACHE_INVALIDATE;
265                 flags |= PIPE_CONTROL_CONST_CACHE_INVALIDATE;
266                 flags |= PIPE_CONTROL_STATE_CACHE_INVALIDATE;
267                 /*
268                  * TLB invalidate requires a post-sync write.
269                  */
270                 flags |= PIPE_CONTROL_QW_WRITE | PIPE_CONTROL_CS_STALL;
271         }
272
273         ret = intel_ring_begin(req, 4);
274         if (ret)
275                 return ret;
276
277         intel_ring_emit(engine, GFX_OP_PIPE_CONTROL(4));
278         intel_ring_emit(engine, flags);
279         intel_ring_emit(engine, scratch_addr | PIPE_CONTROL_GLOBAL_GTT);
280         intel_ring_emit(engine, 0);
281         intel_ring_advance(engine);
282
283         return 0;
284 }
285
286 static int
287 gen7_render_ring_cs_stall_wa(struct drm_i915_gem_request *req)
288 {
289         struct intel_engine_cs *engine = req->engine;
290         int ret;
291
292         ret = intel_ring_begin(req, 4);
293         if (ret)
294                 return ret;
295
296         intel_ring_emit(engine, GFX_OP_PIPE_CONTROL(4));
297         intel_ring_emit(engine, PIPE_CONTROL_CS_STALL |
298                               PIPE_CONTROL_STALL_AT_SCOREBOARD);
299         intel_ring_emit(engine, 0);
300         intel_ring_emit(engine, 0);
301         intel_ring_advance(engine);
302
303         return 0;
304 }
305
306 static int
307 gen7_render_ring_flush(struct drm_i915_gem_request *req,
308                        u32 invalidate_domains, u32 flush_domains)
309 {
310         struct intel_engine_cs *engine = req->engine;
311         u32 flags = 0;
312         u32 scratch_addr = engine->scratch.gtt_offset + 2 * CACHELINE_BYTES;
313         int ret;
314
315         /*
316          * Ensure that any following seqno writes only happen when the render
317          * cache is indeed flushed.
318          *
319          * Workaround: 4th PIPE_CONTROL command (except the ones with only
320          * read-cache invalidate bits set) must have the CS_STALL bit set. We
321          * don't try to be clever and just set it unconditionally.
322          */
323         flags |= PIPE_CONTROL_CS_STALL;
324
325         /* Just flush everything.  Experiments have shown that reducing the
326          * number of bits based on the write domains has little performance
327          * impact.
328          */
329         if (flush_domains) {
330                 flags |= PIPE_CONTROL_RENDER_TARGET_CACHE_FLUSH;
331                 flags |= PIPE_CONTROL_DEPTH_CACHE_FLUSH;
332                 flags |= PIPE_CONTROL_DC_FLUSH_ENABLE;
333                 flags |= PIPE_CONTROL_FLUSH_ENABLE;
334         }
335         if (invalidate_domains) {
336                 flags |= PIPE_CONTROL_TLB_INVALIDATE;
337                 flags |= PIPE_CONTROL_INSTRUCTION_CACHE_INVALIDATE;
338                 flags |= PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE;
339                 flags |= PIPE_CONTROL_VF_CACHE_INVALIDATE;
340                 flags |= PIPE_CONTROL_CONST_CACHE_INVALIDATE;
341                 flags |= PIPE_CONTROL_STATE_CACHE_INVALIDATE;
342                 flags |= PIPE_CONTROL_MEDIA_STATE_CLEAR;
343                 /*
344                  * TLB invalidate requires a post-sync write.
345                  */
346                 flags |= PIPE_CONTROL_QW_WRITE;
347                 flags |= PIPE_CONTROL_GLOBAL_GTT_IVB;
348
349                 flags |= PIPE_CONTROL_STALL_AT_SCOREBOARD;
350
351                 /* Workaround: we must issue a pipe_control with CS-stall bit
352                  * set before a pipe_control command that has the state cache
353                  * invalidate bit set. */
354                 gen7_render_ring_cs_stall_wa(req);
355         }
356
357         ret = intel_ring_begin(req, 4);
358         if (ret)
359                 return ret;
360
361         intel_ring_emit(engine, GFX_OP_PIPE_CONTROL(4));
362         intel_ring_emit(engine, flags);
363         intel_ring_emit(engine, scratch_addr);
364         intel_ring_emit(engine, 0);
365         intel_ring_advance(engine);
366
367         return 0;
368 }
369
370 static int
371 gen8_emit_pipe_control(struct drm_i915_gem_request *req,
372                        u32 flags, u32 scratch_addr)
373 {
374         struct intel_engine_cs *engine = req->engine;
375         int ret;
376
377         ret = intel_ring_begin(req, 6);
378         if (ret)
379                 return ret;
380
381         intel_ring_emit(engine, GFX_OP_PIPE_CONTROL(6));
382         intel_ring_emit(engine, flags);
383         intel_ring_emit(engine, scratch_addr);
384         intel_ring_emit(engine, 0);
385         intel_ring_emit(engine, 0);
386         intel_ring_emit(engine, 0);
387         intel_ring_advance(engine);
388
389         return 0;
390 }
391
392 static int
393 gen8_render_ring_flush(struct drm_i915_gem_request *req,
394                        u32 invalidate_domains, u32 flush_domains)
395 {
396         u32 flags = 0;
397         u32 scratch_addr = req->engine->scratch.gtt_offset + 2 * CACHELINE_BYTES;
398         int ret;
399
400         flags |= PIPE_CONTROL_CS_STALL;
401
402         if (flush_domains) {
403                 flags |= PIPE_CONTROL_RENDER_TARGET_CACHE_FLUSH;
404                 flags |= PIPE_CONTROL_DEPTH_CACHE_FLUSH;
405                 flags |= PIPE_CONTROL_DC_FLUSH_ENABLE;
406                 flags |= PIPE_CONTROL_FLUSH_ENABLE;
407         }
408         if (invalidate_domains) {
409                 flags |= PIPE_CONTROL_TLB_INVALIDATE;
410                 flags |= PIPE_CONTROL_INSTRUCTION_CACHE_INVALIDATE;
411                 flags |= PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE;
412                 flags |= PIPE_CONTROL_VF_CACHE_INVALIDATE;
413                 flags |= PIPE_CONTROL_CONST_CACHE_INVALIDATE;
414                 flags |= PIPE_CONTROL_STATE_CACHE_INVALIDATE;
415                 flags |= PIPE_CONTROL_QW_WRITE;
416                 flags |= PIPE_CONTROL_GLOBAL_GTT_IVB;
417
418                 /* WaCsStallBeforeStateCacheInvalidate:bdw,chv */
419                 ret = gen8_emit_pipe_control(req,
420                                              PIPE_CONTROL_CS_STALL |
421                                              PIPE_CONTROL_STALL_AT_SCOREBOARD,
422                                              0);
423                 if (ret)
424                         return ret;
425         }
426
427         return gen8_emit_pipe_control(req, flags, scratch_addr);
428 }
429
430 static void ring_write_tail(struct intel_engine_cs *engine,
431                             u32 value)
432 {
433         struct drm_i915_private *dev_priv = engine->i915;
434         I915_WRITE_TAIL(engine, value);
435 }
436
437 u64 intel_ring_get_active_head(struct intel_engine_cs *engine)
438 {
439         struct drm_i915_private *dev_priv = engine->i915;
440         u64 acthd;
441
442         if (INTEL_GEN(dev_priv) >= 8)
443                 acthd = I915_READ64_2x32(RING_ACTHD(engine->mmio_base),
444                                          RING_ACTHD_UDW(engine->mmio_base));
445         else if (INTEL_GEN(dev_priv) >= 4)
446                 acthd = I915_READ(RING_ACTHD(engine->mmio_base));
447         else
448                 acthd = I915_READ(ACTHD);
449
450         return acthd;
451 }
452
453 static void ring_setup_phys_status_page(struct intel_engine_cs *engine)
454 {
455         struct drm_i915_private *dev_priv = engine->i915;
456         u32 addr;
457
458         addr = dev_priv->status_page_dmah->busaddr;
459         if (INTEL_GEN(dev_priv) >= 4)
460                 addr |= (dev_priv->status_page_dmah->busaddr >> 28) & 0xf0;
461         I915_WRITE(HWS_PGA, addr);
462 }
463
464 static void intel_ring_setup_status_page(struct intel_engine_cs *engine)
465 {
466         struct drm_i915_private *dev_priv = engine->i915;
467         i915_reg_t mmio;
468
469         /* The ring status page addresses are no longer next to the rest of
470          * the ring registers as of gen7.
471          */
472         if (IS_GEN7(dev_priv)) {
473                 switch (engine->id) {
474                 case RCS:
475                         mmio = RENDER_HWS_PGA_GEN7;
476                         break;
477                 case BCS:
478                         mmio = BLT_HWS_PGA_GEN7;
479                         break;
480                 /*
481                  * VCS2 actually doesn't exist on Gen7. Only shut up
482                  * gcc switch check warning
483                  */
484                 case VCS2:
485                 case VCS:
486                         mmio = BSD_HWS_PGA_GEN7;
487                         break;
488                 case VECS:
489                         mmio = VEBOX_HWS_PGA_GEN7;
490                         break;
491                 }
492         } else if (IS_GEN6(dev_priv)) {
493                 mmio = RING_HWS_PGA_GEN6(engine->mmio_base);
494         } else {
495                 /* XXX: gen8 returns to sanity */
496                 mmio = RING_HWS_PGA(engine->mmio_base);
497         }
498
499         I915_WRITE(mmio, (u32)engine->status_page.gfx_addr);
500         POSTING_READ(mmio);
501
502         /*
503          * Flush the TLB for this page
504          *
505          * FIXME: These two bits have disappeared on gen8, so a question
506          * arises: do we still need this and if so how should we go about
507          * invalidating the TLB?
508          */
509         if (IS_GEN(dev_priv, 6, 7)) {
510                 i915_reg_t reg = RING_INSTPM(engine->mmio_base);
511
512                 /* ring should be idle before issuing a sync flush*/
513                 WARN_ON((I915_READ_MODE(engine) & MODE_IDLE) == 0);
514
515                 I915_WRITE(reg,
516                            _MASKED_BIT_ENABLE(INSTPM_TLB_INVALIDATE |
517                                               INSTPM_SYNC_FLUSH));
518                 if (intel_wait_for_register(dev_priv,
519                                             reg, INSTPM_SYNC_FLUSH, 0,
520                                             1000))
521                         DRM_ERROR("%s: wait for SyncFlush to complete for TLB invalidation timed out\n",
522                                   engine->name);
523         }
524 }
525
526 static bool stop_ring(struct intel_engine_cs *engine)
527 {
528         struct drm_i915_private *dev_priv = engine->i915;
529
530         if (!IS_GEN2(dev_priv)) {
531                 I915_WRITE_MODE(engine, _MASKED_BIT_ENABLE(STOP_RING));
532                 if (intel_wait_for_register(dev_priv,
533                                             RING_MI_MODE(engine->mmio_base),
534                                             MODE_IDLE,
535                                             MODE_IDLE,
536                                             1000)) {
537                         DRM_ERROR("%s : timed out trying to stop ring\n",
538                                   engine->name);
539                         /* Sometimes we observe that the idle flag is not
540                          * set even though the ring is empty. So double
541                          * check before giving up.
542                          */
543                         if (I915_READ_HEAD(engine) != I915_READ_TAIL(engine))
544                                 return false;
545                 }
546         }
547
548         I915_WRITE_CTL(engine, 0);
549         I915_WRITE_HEAD(engine, 0);
550         engine->write_tail(engine, 0);
551
552         if (!IS_GEN2(dev_priv)) {
553                 (void)I915_READ_CTL(engine);
554                 I915_WRITE_MODE(engine, _MASKED_BIT_DISABLE(STOP_RING));
555         }
556
557         return (I915_READ_HEAD(engine) & HEAD_ADDR) == 0;
558 }
559
560 void intel_engine_init_hangcheck(struct intel_engine_cs *engine)
561 {
562         memset(&engine->hangcheck, 0, sizeof(engine->hangcheck));
563 }
564
565 static int init_ring_common(struct intel_engine_cs *engine)
566 {
567         struct drm_i915_private *dev_priv = engine->i915;
568         struct intel_ringbuffer *ringbuf = engine->buffer;
569         struct drm_i915_gem_object *obj = ringbuf->obj;
570         int ret = 0;
571
572         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
573
574         if (!stop_ring(engine)) {
575                 /* G45 ring initialization often fails to reset head to zero */
576                 DRM_DEBUG_KMS("%s head not reset to zero "
577                               "ctl %08x head %08x tail %08x start %08x\n",
578                               engine->name,
579                               I915_READ_CTL(engine),
580                               I915_READ_HEAD(engine),
581                               I915_READ_TAIL(engine),
582                               I915_READ_START(engine));
583
584                 if (!stop_ring(engine)) {
585                         DRM_ERROR("failed to set %s head to zero "
586                                   "ctl %08x head %08x tail %08x start %08x\n",
587                                   engine->name,
588                                   I915_READ_CTL(engine),
589                                   I915_READ_HEAD(engine),
590                                   I915_READ_TAIL(engine),
591                                   I915_READ_START(engine));
592                         ret = -EIO;
593                         goto out;
594                 }
595         }
596
597         if (I915_NEED_GFX_HWS(dev_priv))
598                 intel_ring_setup_status_page(engine);
599         else
600                 ring_setup_phys_status_page(engine);
601
602         /* Enforce ordering by reading HEAD register back */
603         I915_READ_HEAD(engine);
604
605         /* Initialize the ring. This must happen _after_ we've cleared the ring
606          * registers with the above sequence (the readback of the HEAD registers
607          * also enforces ordering), otherwise the hw might lose the new ring
608          * register values. */
609         I915_WRITE_START(engine, i915_gem_obj_ggtt_offset(obj));
610
611         /* WaClearRingBufHeadRegAtInit:ctg,elk */
612         if (I915_READ_HEAD(engine))
613                 DRM_DEBUG("%s initialization failed [head=%08x], fudging\n",
614                           engine->name, I915_READ_HEAD(engine));
615         I915_WRITE_HEAD(engine, 0);
616         (void)I915_READ_HEAD(engine);
617
618         I915_WRITE_CTL(engine,
619                         ((ringbuf->size - PAGE_SIZE) & RING_NR_PAGES)
620                         | RING_VALID);
621
622         /* If the head is still not zero, the ring is dead */
623         if (wait_for((I915_READ_CTL(engine) & RING_VALID) != 0 &&
624                      I915_READ_START(engine) == i915_gem_obj_ggtt_offset(obj) &&
625                      (I915_READ_HEAD(engine) & HEAD_ADDR) == 0, 50)) {
626                 DRM_ERROR("%s initialization failed "
627                           "ctl %08x (valid? %d) head %08x tail %08x start %08x [expected %08lx]\n",
628                           engine->name,
629                           I915_READ_CTL(engine),
630                           I915_READ_CTL(engine) & RING_VALID,
631                           I915_READ_HEAD(engine), I915_READ_TAIL(engine),
632                           I915_READ_START(engine),
633                           (unsigned long)i915_gem_obj_ggtt_offset(obj));
634                 ret = -EIO;
635                 goto out;
636         }
637
638         ringbuf->last_retired_head = -1;
639         ringbuf->head = I915_READ_HEAD(engine);
640         ringbuf->tail = I915_READ_TAIL(engine) & TAIL_ADDR;
641         intel_ring_update_space(ringbuf);
642
643         intel_engine_init_hangcheck(engine);
644
645 out:
646         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
647
648         return ret;
649 }
650
651 void intel_fini_pipe_control(struct intel_engine_cs *engine)
652 {
653         if (engine->scratch.obj == NULL)
654                 return;
655
656         i915_gem_object_ggtt_unpin(engine->scratch.obj);
657         drm_gem_object_unreference(&engine->scratch.obj->base);
658         engine->scratch.obj = NULL;
659 }
660
661 int intel_init_pipe_control(struct intel_engine_cs *engine, int size)
662 {
663         struct drm_i915_gem_object *obj;
664         int ret;
665
666         WARN_ON(engine->scratch.obj);
667
668         obj = i915_gem_object_create_stolen(engine->i915->dev, size);
669         if (!obj)
670                 obj = i915_gem_object_create(engine->i915->dev, size);
671         if (IS_ERR(obj)) {
672                 DRM_ERROR("Failed to allocate scratch page\n");
673                 ret = PTR_ERR(obj);
674                 goto err;
675         }
676
677         ret = i915_gem_obj_ggtt_pin(obj, 4096, PIN_HIGH);
678         if (ret)
679                 goto err_unref;
680
681         engine->scratch.obj = obj;
682         engine->scratch.gtt_offset = i915_gem_obj_ggtt_offset(obj);
683         DRM_DEBUG_DRIVER("%s pipe control offset: 0x%08x\n",
684                          engine->name, engine->scratch.gtt_offset);
685         return 0;
686
687 err_unref:
688         drm_gem_object_unreference(&engine->scratch.obj->base);
689 err:
690         return ret;
691 }
692
693 static int intel_ring_workarounds_emit(struct drm_i915_gem_request *req)
694 {
695         struct intel_engine_cs *engine = req->engine;
696         struct i915_workarounds *w = &req->i915->workarounds;
697         int ret, i;
698
699         if (w->count == 0)
700                 return 0;
701
702         engine->gpu_caches_dirty = true;
703         ret = intel_ring_flush_all_caches(req);
704         if (ret)
705                 return ret;
706
707         ret = intel_ring_begin(req, (w->count * 2 + 2));
708         if (ret)
709                 return ret;
710
711         intel_ring_emit(engine, MI_LOAD_REGISTER_IMM(w->count));
712         for (i = 0; i < w->count; i++) {
713                 intel_ring_emit_reg(engine, w->reg[i].addr);
714                 intel_ring_emit(engine, w->reg[i].value);
715         }
716         intel_ring_emit(engine, MI_NOOP);
717
718         intel_ring_advance(engine);
719
720         engine->gpu_caches_dirty = true;
721         ret = intel_ring_flush_all_caches(req);
722         if (ret)
723                 return ret;
724
725         DRM_DEBUG_DRIVER("Number of Workarounds emitted: %d\n", w->count);
726
727         return 0;
728 }
729
730 static int intel_rcs_ctx_init(struct drm_i915_gem_request *req)
731 {
732         int ret;
733
734         ret = intel_ring_workarounds_emit(req);
735         if (ret != 0)
736                 return ret;
737
738         ret = i915_gem_render_state_init(req);
739         if (ret)
740                 return ret;
741
742         return 0;
743 }
744
745 static int wa_add(struct drm_i915_private *dev_priv,
746                   i915_reg_t addr,
747                   const u32 mask, const u32 val)
748 {
749         const u32 idx = dev_priv->workarounds.count;
750
751         if (WARN_ON(idx >= I915_MAX_WA_REGS))
752                 return -ENOSPC;
753
754         dev_priv->workarounds.reg[idx].addr = addr;
755         dev_priv->workarounds.reg[idx].value = val;
756         dev_priv->workarounds.reg[idx].mask = mask;
757
758         dev_priv->workarounds.count++;
759
760         return 0;
761 }
762
763 #define WA_REG(addr, mask, val) do { \
764                 const int r = wa_add(dev_priv, (addr), (mask), (val)); \
765                 if (r) \
766                         return r; \
767         } while (0)
768
769 #define WA_SET_BIT_MASKED(addr, mask) \
770         WA_REG(addr, (mask), _MASKED_BIT_ENABLE(mask))
771
772 #define WA_CLR_BIT_MASKED(addr, mask) \
773         WA_REG(addr, (mask), _MASKED_BIT_DISABLE(mask))
774
775 #define WA_SET_FIELD_MASKED(addr, mask, value) \
776         WA_REG(addr, mask, _MASKED_FIELD(mask, value))
777
778 #define WA_SET_BIT(addr, mask) WA_REG(addr, mask, I915_READ(addr) | (mask))
779 #define WA_CLR_BIT(addr, mask) WA_REG(addr, mask, I915_READ(addr) & ~(mask))
780
781 #define WA_WRITE(addr, val) WA_REG(addr, 0xffffffff, val)
782
783 static int wa_ring_whitelist_reg(struct intel_engine_cs *engine,
784                                  i915_reg_t reg)
785 {
786         struct drm_i915_private *dev_priv = engine->i915;
787         struct i915_workarounds *wa = &dev_priv->workarounds;
788         const uint32_t index = wa->hw_whitelist_count[engine->id];
789
790         if (WARN_ON(index >= RING_MAX_NONPRIV_SLOTS))
791                 return -EINVAL;
792
793         WA_WRITE(RING_FORCE_TO_NONPRIV(engine->mmio_base, index),
794                  i915_mmio_reg_offset(reg));
795         wa->hw_whitelist_count[engine->id]++;
796
797         return 0;
798 }
799
800 static int gen8_init_workarounds(struct intel_engine_cs *engine)
801 {
802         struct drm_i915_private *dev_priv = engine->i915;
803
804         WA_SET_BIT_MASKED(INSTPM, INSTPM_FORCE_ORDERING);
805
806         /* WaDisableAsyncFlipPerfMode:bdw,chv */
807         WA_SET_BIT_MASKED(MI_MODE, ASYNC_FLIP_PERF_DISABLE);
808
809         /* WaDisablePartialInstShootdown:bdw,chv */
810         WA_SET_BIT_MASKED(GEN8_ROW_CHICKEN,
811                           PARTIAL_INSTRUCTION_SHOOTDOWN_DISABLE);
812
813         /* Use Force Non-Coherent whenever executing a 3D context. This is a
814          * workaround for for a possible hang in the unlikely event a TLB
815          * invalidation occurs during a PSD flush.
816          */
817         /* WaForceEnableNonCoherent:bdw,chv */
818         /* WaHdcDisableFetchWhenMasked:bdw,chv */
819         WA_SET_BIT_MASKED(HDC_CHICKEN0,
820                           HDC_DONOT_FETCH_MEM_WHEN_MASKED |
821                           HDC_FORCE_NON_COHERENT);
822
823         /* From the Haswell PRM, Command Reference: Registers, CACHE_MODE_0:
824          * "The Hierarchical Z RAW Stall Optimization allows non-overlapping
825          *  polygons in the same 8x4 pixel/sample area to be processed without
826          *  stalling waiting for the earlier ones to write to Hierarchical Z
827          *  buffer."
828          *
829          * This optimization is off by default for BDW and CHV; turn it on.
830          */
831         WA_CLR_BIT_MASKED(CACHE_MODE_0_GEN7, HIZ_RAW_STALL_OPT_DISABLE);
832
833         /* Wa4x4STCOptimizationDisable:bdw,chv */
834         WA_SET_BIT_MASKED(CACHE_MODE_1, GEN8_4x4_STC_OPTIMIZATION_DISABLE);
835
836         /*
837          * BSpec recommends 8x4 when MSAA is used,
838          * however in practice 16x4 seems fastest.
839          *
840          * Note that PS/WM thread counts depend on the WIZ hashing
841          * disable bit, which we don't touch here, but it's good
842          * to keep in mind (see 3DSTATE_PS and 3DSTATE_WM).
843          */
844         WA_SET_FIELD_MASKED(GEN7_GT_MODE,
845                             GEN6_WIZ_HASHING_MASK,
846                             GEN6_WIZ_HASHING_16x4);
847
848         return 0;
849 }
850
851 static int bdw_init_workarounds(struct intel_engine_cs *engine)
852 {
853         struct drm_i915_private *dev_priv = engine->i915;
854         int ret;
855
856         ret = gen8_init_workarounds(engine);
857         if (ret)
858                 return ret;
859
860         /* WaDisableThreadStallDopClockGating:bdw (pre-production) */
861         WA_SET_BIT_MASKED(GEN8_ROW_CHICKEN, STALL_DOP_GATING_DISABLE);
862
863         /* WaDisableDopClockGating:bdw */
864         WA_SET_BIT_MASKED(GEN7_ROW_CHICKEN2,
865                           DOP_CLOCK_GATING_DISABLE);
866
867         WA_SET_BIT_MASKED(HALF_SLICE_CHICKEN3,
868                           GEN8_SAMPLER_POWER_BYPASS_DIS);
869
870         WA_SET_BIT_MASKED(HDC_CHICKEN0,
871                           /* WaForceContextSaveRestoreNonCoherent:bdw */
872                           HDC_FORCE_CONTEXT_SAVE_RESTORE_NON_COHERENT |
873                           /* WaDisableFenceDestinationToSLM:bdw (pre-prod) */
874                           (IS_BDW_GT3(dev_priv) ? HDC_FENCE_DEST_SLM_DISABLE : 0));
875
876         return 0;
877 }
878
879 static int chv_init_workarounds(struct intel_engine_cs *engine)
880 {
881         struct drm_i915_private *dev_priv = engine->i915;
882         int ret;
883
884         ret = gen8_init_workarounds(engine);
885         if (ret)
886                 return ret;
887
888         /* WaDisableThreadStallDopClockGating:chv */
889         WA_SET_BIT_MASKED(GEN8_ROW_CHICKEN, STALL_DOP_GATING_DISABLE);
890
891         /* Improve HiZ throughput on CHV. */
892         WA_SET_BIT_MASKED(HIZ_CHICKEN, CHV_HZ_8X8_MODE_IN_1X);
893
894         return 0;
895 }
896
897 static int gen9_init_workarounds(struct intel_engine_cs *engine)
898 {
899         struct drm_i915_private *dev_priv = engine->i915;
900         int ret;
901
902         /* WaConextSwitchWithConcurrentTLBInvalidate:skl,bxt,kbl */
903         I915_WRITE(GEN9_CSFE_CHICKEN1_RCS, _MASKED_BIT_ENABLE(GEN9_PREEMPT_GPGPU_SYNC_SWITCH_DISABLE));
904
905         /* WaEnableLbsSlaRetryTimerDecrement:skl,bxt,kbl */
906         I915_WRITE(BDW_SCRATCH1, I915_READ(BDW_SCRATCH1) |
907                    GEN9_LBS_SLA_RETRY_TIMER_DECREMENT_ENABLE);
908
909         /* WaDisableKillLogic:bxt,skl,kbl */
910         I915_WRITE(GAM_ECOCHK, I915_READ(GAM_ECOCHK) |
911                    ECOCHK_DIS_TLB);
912
913         /* WaClearFlowControlGpgpuContextSave:skl,bxt,kbl */
914         /* WaDisablePartialInstShootdown:skl,bxt,kbl */
915         WA_SET_BIT_MASKED(GEN8_ROW_CHICKEN,
916                           FLOW_CONTROL_ENABLE |
917                           PARTIAL_INSTRUCTION_SHOOTDOWN_DISABLE);
918
919         /* Syncing dependencies between camera and graphics:skl,bxt,kbl */
920         WA_SET_BIT_MASKED(HALF_SLICE_CHICKEN3,
921                           GEN9_DISABLE_OCL_OOB_SUPPRESS_LOGIC);
922
923         /* WaDisableDgMirrorFixInHalfSliceChicken5:skl,bxt */
924         if (IS_SKL_REVID(dev_priv, 0, SKL_REVID_B0) ||
925             IS_BXT_REVID(dev_priv, 0, BXT_REVID_A1))
926                 WA_CLR_BIT_MASKED(GEN9_HALF_SLICE_CHICKEN5,
927                                   GEN9_DG_MIRROR_FIX_ENABLE);
928
929         /* WaSetDisablePixMaskCammingAndRhwoInCommonSliceChicken:skl,bxt */
930         if (IS_SKL_REVID(dev_priv, 0, SKL_REVID_B0) ||
931             IS_BXT_REVID(dev_priv, 0, BXT_REVID_A1)) {
932                 WA_SET_BIT_MASKED(GEN7_COMMON_SLICE_CHICKEN1,
933                                   GEN9_RHWO_OPTIMIZATION_DISABLE);
934                 /*
935                  * WA also requires GEN9_SLICE_COMMON_ECO_CHICKEN0[14:14] to be set
936                  * but we do that in per ctx batchbuffer as there is an issue
937                  * with this register not getting restored on ctx restore
938                  */
939         }
940
941         /* WaEnableYV12BugFixInHalfSliceChicken7:skl,bxt,kbl */
942         /* WaEnableSamplerGPGPUPreemptionSupport:skl,bxt,kbl */
943         WA_SET_BIT_MASKED(GEN9_HALF_SLICE_CHICKEN7,
944                           GEN9_ENABLE_YV12_BUGFIX |
945                           GEN9_ENABLE_GPGPU_PREEMPTION);
946
947         /* Wa4x4STCOptimizationDisable:skl,bxt,kbl */
948         /* WaDisablePartialResolveInVc:skl,bxt,kbl */
949         WA_SET_BIT_MASKED(CACHE_MODE_1, (GEN8_4x4_STC_OPTIMIZATION_DISABLE |
950                                          GEN9_PARTIAL_RESOLVE_IN_VC_DISABLE));
951
952         /* WaCcsTlbPrefetchDisable:skl,bxt,kbl */
953         WA_CLR_BIT_MASKED(GEN9_HALF_SLICE_CHICKEN5,
954                           GEN9_CCS_TLB_PREFETCH_ENABLE);
955
956         /* WaDisableMaskBasedCammingInRCC:skl,bxt */
957         if (IS_SKL_REVID(dev_priv, SKL_REVID_C0, SKL_REVID_C0) ||
958             IS_BXT_REVID(dev_priv, 0, BXT_REVID_A1))
959                 WA_SET_BIT_MASKED(SLICE_ECO_CHICKEN0,
960                                   PIXEL_MASK_CAMMING_DISABLE);
961
962         /* WaForceContextSaveRestoreNonCoherent:skl,bxt,kbl */
963         WA_SET_BIT_MASKED(HDC_CHICKEN0,
964                           HDC_FORCE_CONTEXT_SAVE_RESTORE_NON_COHERENT |
965                           HDC_FORCE_CSR_NON_COHERENT_OVR_DISABLE);
966
967         /* WaForceEnableNonCoherent and WaDisableHDCInvalidation are
968          * both tied to WaForceContextSaveRestoreNonCoherent
969          * in some hsds for skl. We keep the tie for all gen9. The
970          * documentation is a bit hazy and so we want to get common behaviour,
971          * even though there is no clear evidence we would need both on kbl/bxt.
972          * This area has been source of system hangs so we play it safe
973          * and mimic the skl regardless of what bspec says.
974          *
975          * Use Force Non-Coherent whenever executing a 3D context. This
976          * is a workaround for a possible hang in the unlikely event
977          * a TLB invalidation occurs during a PSD flush.
978          */
979
980         /* WaForceEnableNonCoherent:skl,bxt,kbl */
981         WA_SET_BIT_MASKED(HDC_CHICKEN0,
982                           HDC_FORCE_NON_COHERENT);
983
984         /* WaDisableHDCInvalidation:skl,bxt,kbl */
985         I915_WRITE(GAM_ECOCHK, I915_READ(GAM_ECOCHK) |
986                    BDW_DISABLE_HDC_INVALIDATION);
987
988         /* WaDisableSamplerPowerBypassForSOPingPong:skl,bxt,kbl */
989         if (IS_SKYLAKE(dev_priv) ||
990             IS_KABYLAKE(dev_priv) ||
991             IS_BXT_REVID(dev_priv, 0, BXT_REVID_B0))
992                 WA_SET_BIT_MASKED(HALF_SLICE_CHICKEN3,
993                                   GEN8_SAMPLER_POWER_BYPASS_DIS);
994
995         /* WaDisableSTUnitPowerOptimization:skl,bxt,kbl */
996         WA_SET_BIT_MASKED(HALF_SLICE_CHICKEN2, GEN8_ST_PO_DISABLE);
997
998         /* WaOCLCoherentLineFlush:skl,bxt,kbl */
999         I915_WRITE(GEN8_L3SQCREG4, (I915_READ(GEN8_L3SQCREG4) |
1000                                     GEN8_LQSC_FLUSH_COHERENT_LINES));
1001
1002         /* WaVFEStateAfterPipeControlwithMediaStateClear:skl,bxt */
1003         ret = wa_ring_whitelist_reg(engine, GEN9_CTX_PREEMPT_REG);
1004         if (ret)
1005                 return ret;
1006
1007         /* WaEnablePreemptionGranularityControlByUMD:skl,bxt,kbl */
1008         ret= wa_ring_whitelist_reg(engine, GEN8_CS_CHICKEN1);
1009         if (ret)
1010                 return ret;
1011
1012         /* WaAllowUMDToModifyHDCChicken1:skl,bxt,kbl */
1013         ret = wa_ring_whitelist_reg(engine, GEN8_HDC_CHICKEN1);
1014         if (ret)
1015                 return ret;
1016
1017         return 0;
1018 }
1019
1020 static int skl_tune_iz_hashing(struct intel_engine_cs *engine)
1021 {
1022         struct drm_i915_private *dev_priv = engine->i915;
1023         u8 vals[3] = { 0, 0, 0 };
1024         unsigned int i;
1025
1026         for (i = 0; i < 3; i++) {
1027                 u8 ss;
1028
1029                 /*
1030                  * Only consider slices where one, and only one, subslice has 7
1031                  * EUs
1032                  */
1033                 if (!is_power_of_2(dev_priv->info.subslice_7eu[i]))
1034                         continue;
1035
1036                 /*
1037                  * subslice_7eu[i] != 0 (because of the check above) and
1038                  * ss_max == 4 (maximum number of subslices possible per slice)
1039                  *
1040                  * ->    0 <= ss <= 3;
1041                  */
1042                 ss = ffs(dev_priv->info.subslice_7eu[i]) - 1;
1043                 vals[i] = 3 - ss;
1044         }
1045
1046         if (vals[0] == 0 && vals[1] == 0 && vals[2] == 0)
1047                 return 0;
1048
1049         /* Tune IZ hashing. See intel_device_info_runtime_init() */
1050         WA_SET_FIELD_MASKED(GEN7_GT_MODE,
1051                             GEN9_IZ_HASHING_MASK(2) |
1052                             GEN9_IZ_HASHING_MASK(1) |
1053                             GEN9_IZ_HASHING_MASK(0),
1054                             GEN9_IZ_HASHING(2, vals[2]) |
1055                             GEN9_IZ_HASHING(1, vals[1]) |
1056                             GEN9_IZ_HASHING(0, vals[0]));
1057
1058         return 0;
1059 }
1060
1061 static int skl_init_workarounds(struct intel_engine_cs *engine)
1062 {
1063         struct drm_i915_private *dev_priv = engine->i915;
1064         int ret;
1065
1066         ret = gen9_init_workarounds(engine);
1067         if (ret)
1068                 return ret;
1069
1070         /*
1071          * Actual WA is to disable percontext preemption granularity control
1072          * until D0 which is the default case so this is equivalent to
1073          * !WaDisablePerCtxtPreemptionGranularityControl:skl
1074          */
1075         if (IS_SKL_REVID(dev_priv, SKL_REVID_E0, REVID_FOREVER)) {
1076                 I915_WRITE(GEN7_FF_SLICE_CS_CHICKEN1,
1077                            _MASKED_BIT_ENABLE(GEN9_FFSC_PERCTX_PREEMPT_CTRL));
1078         }
1079
1080         if (IS_SKL_REVID(dev_priv, 0, SKL_REVID_E0)) {
1081                 /* WaDisableChickenBitTSGBarrierAckForFFSliceCS:skl */
1082                 I915_WRITE(FF_SLICE_CS_CHICKEN2,
1083                            _MASKED_BIT_ENABLE(GEN9_TSG_BARRIER_ACK_DISABLE));
1084         }
1085
1086         /* GEN8_L3SQCREG4 has a dependency with WA batch so any new changes
1087          * involving this register should also be added to WA batch as required.
1088          */
1089         if (IS_SKL_REVID(dev_priv, 0, SKL_REVID_E0))
1090                 /* WaDisableLSQCROPERFforOCL:skl */
1091                 I915_WRITE(GEN8_L3SQCREG4, I915_READ(GEN8_L3SQCREG4) |
1092                            GEN8_LQSC_RO_PERF_DIS);
1093
1094         /* WaEnableGapsTsvCreditFix:skl */
1095         if (IS_SKL_REVID(dev_priv, SKL_REVID_C0, REVID_FOREVER)) {
1096                 I915_WRITE(GEN8_GARBCNTL, (I915_READ(GEN8_GARBCNTL) |
1097                                            GEN9_GAPS_TSV_CREDIT_DISABLE));
1098         }
1099
1100         /* WaDisablePowerCompilerClockGating:skl */
1101         if (IS_SKL_REVID(dev_priv, SKL_REVID_B0, SKL_REVID_B0))
1102                 WA_SET_BIT_MASKED(HIZ_CHICKEN,
1103                                   BDW_HIZ_POWER_COMPILER_CLOCK_GATING_DISABLE);
1104
1105         /* WaBarrierPerformanceFixDisable:skl */
1106         if (IS_SKL_REVID(dev_priv, SKL_REVID_C0, SKL_REVID_D0))
1107                 WA_SET_BIT_MASKED(HDC_CHICKEN0,
1108                                   HDC_FENCE_DEST_SLM_DISABLE |
1109                                   HDC_BARRIER_PERFORMANCE_DISABLE);
1110
1111         /* WaDisableSbeCacheDispatchPortSharing:skl */
1112         if (IS_SKL_REVID(dev_priv, 0, SKL_REVID_F0))
1113                 WA_SET_BIT_MASKED(
1114                         GEN7_HALF_SLICE_CHICKEN1,
1115                         GEN7_SBE_SS_CACHE_DISPATCH_PORT_SHARING_DISABLE);
1116
1117         /* WaDisableGafsUnitClkGating:skl */
1118         WA_SET_BIT(GEN7_UCGCTL4, GEN8_EU_GAUNIT_CLOCK_GATE_DISABLE);
1119
1120         /* WaDisableLSQCROPERFforOCL:skl */
1121         ret = wa_ring_whitelist_reg(engine, GEN8_L3SQCREG4);
1122         if (ret)
1123                 return ret;
1124
1125         return skl_tune_iz_hashing(engine);
1126 }
1127
1128 static int bxt_init_workarounds(struct intel_engine_cs *engine)
1129 {
1130         struct drm_i915_private *dev_priv = engine->i915;
1131         int ret;
1132
1133         ret = gen9_init_workarounds(engine);
1134         if (ret)
1135                 return ret;
1136
1137         /* WaStoreMultiplePTEenable:bxt */
1138         /* This is a requirement according to Hardware specification */
1139         if (IS_BXT_REVID(dev_priv, 0, BXT_REVID_A1))
1140                 I915_WRITE(TILECTL, I915_READ(TILECTL) | TILECTL_TLBPF);
1141
1142         /* WaSetClckGatingDisableMedia:bxt */
1143         if (IS_BXT_REVID(dev_priv, 0, BXT_REVID_A1)) {
1144                 I915_WRITE(GEN7_MISCCPCTL, (I915_READ(GEN7_MISCCPCTL) &
1145                                             ~GEN8_DOP_CLOCK_GATE_MEDIA_ENABLE));
1146         }
1147
1148         /* WaDisableThreadStallDopClockGating:bxt */
1149         WA_SET_BIT_MASKED(GEN8_ROW_CHICKEN,
1150                           STALL_DOP_GATING_DISABLE);
1151
1152         /* WaDisablePooledEuLoadBalancingFix:bxt */
1153         if (IS_BXT_REVID(dev_priv, BXT_REVID_B0, REVID_FOREVER)) {
1154                 WA_SET_BIT_MASKED(FF_SLICE_CS_CHICKEN2,
1155                                   GEN9_POOLED_EU_LOAD_BALANCING_FIX_DISABLE);
1156         }
1157
1158         /* WaDisableSbeCacheDispatchPortSharing:bxt */
1159         if (IS_BXT_REVID(dev_priv, 0, BXT_REVID_B0)) {
1160                 WA_SET_BIT_MASKED(
1161                         GEN7_HALF_SLICE_CHICKEN1,
1162                         GEN7_SBE_SS_CACHE_DISPATCH_PORT_SHARING_DISABLE);
1163         }
1164
1165         /* WaDisableObjectLevelPreemptionForTrifanOrPolygon:bxt */
1166         /* WaDisableObjectLevelPreemptionForInstancedDraw:bxt */
1167         /* WaDisableObjectLevelPreemtionForInstanceId:bxt */
1168         /* WaDisableLSQCROPERFforOCL:bxt */
1169         if (IS_BXT_REVID(dev_priv, 0, BXT_REVID_A1)) {
1170                 ret = wa_ring_whitelist_reg(engine, GEN9_CS_DEBUG_MODE1);
1171                 if (ret)
1172                         return ret;
1173
1174                 ret = wa_ring_whitelist_reg(engine, GEN8_L3SQCREG4);
1175                 if (ret)
1176                         return ret;
1177         }
1178
1179         /* WaProgramL3SqcReg1DefaultForPerf:bxt */
1180         if (IS_BXT_REVID(dev_priv, BXT_REVID_B0, REVID_FOREVER))
1181                 I915_WRITE(GEN8_L3SQCREG1, L3_GENERAL_PRIO_CREDITS(62) |
1182                                            L3_HIGH_PRIO_CREDITS(2));
1183
1184         /* WaInsertDummyPushConstPs:bxt */
1185         if (IS_BXT_REVID(dev_priv, 0, BXT_REVID_B0))
1186                 WA_SET_BIT_MASKED(COMMON_SLICE_CHICKEN2,
1187                                   GEN8_SBE_DISABLE_REPLAY_BUF_OPTIMIZATION);
1188
1189         return 0;
1190 }
1191
1192 static int kbl_init_workarounds(struct intel_engine_cs *engine)
1193 {
1194         struct drm_i915_private *dev_priv = engine->i915;
1195         int ret;
1196
1197         ret = gen9_init_workarounds(engine);
1198         if (ret)
1199                 return ret;
1200
1201         /* WaEnableGapsTsvCreditFix:kbl */
1202         I915_WRITE(GEN8_GARBCNTL, (I915_READ(GEN8_GARBCNTL) |
1203                                    GEN9_GAPS_TSV_CREDIT_DISABLE));
1204
1205         /* WaDisableDynamicCreditSharing:kbl */
1206         if (IS_KBL_REVID(dev_priv, 0, KBL_REVID_B0))
1207                 WA_SET_BIT(GAMT_CHKN_BIT_REG,
1208                            GAMT_CHKN_DISABLE_DYNAMIC_CREDIT_SHARING);
1209
1210         /* WaDisableFenceDestinationToSLM:kbl (pre-prod) */
1211         if (IS_KBL_REVID(dev_priv, KBL_REVID_A0, KBL_REVID_A0))
1212                 WA_SET_BIT_MASKED(HDC_CHICKEN0,
1213                                   HDC_FENCE_DEST_SLM_DISABLE);
1214
1215         /* GEN8_L3SQCREG4 has a dependency with WA batch so any new changes
1216          * involving this register should also be added to WA batch as required.
1217          */
1218         if (IS_KBL_REVID(dev_priv, 0, KBL_REVID_E0))
1219                 /* WaDisableLSQCROPERFforOCL:kbl */
1220                 I915_WRITE(GEN8_L3SQCREG4, I915_READ(GEN8_L3SQCREG4) |
1221                            GEN8_LQSC_RO_PERF_DIS);
1222
1223         /* WaInsertDummyPushConstPs:kbl */
1224         if (IS_KBL_REVID(dev_priv, 0, KBL_REVID_B0))
1225                 WA_SET_BIT_MASKED(COMMON_SLICE_CHICKEN2,
1226                                   GEN8_SBE_DISABLE_REPLAY_BUF_OPTIMIZATION);
1227
1228         /* WaDisableGafsUnitClkGating:kbl */
1229         WA_SET_BIT(GEN7_UCGCTL4, GEN8_EU_GAUNIT_CLOCK_GATE_DISABLE);
1230
1231         /* WaDisableSbeCacheDispatchPortSharing:kbl */
1232         WA_SET_BIT_MASKED(
1233                 GEN7_HALF_SLICE_CHICKEN1,
1234                 GEN7_SBE_SS_CACHE_DISPATCH_PORT_SHARING_DISABLE);
1235
1236         /* WaDisableLSQCROPERFforOCL:kbl */
1237         ret = wa_ring_whitelist_reg(engine, GEN8_L3SQCREG4);
1238         if (ret)
1239                 return ret;
1240
1241         return 0;
1242 }
1243
1244 int init_workarounds_ring(struct intel_engine_cs *engine)
1245 {
1246         struct drm_i915_private *dev_priv = engine->i915;
1247
1248         WARN_ON(engine->id != RCS);
1249
1250         dev_priv->workarounds.count = 0;
1251         dev_priv->workarounds.hw_whitelist_count[RCS] = 0;
1252
1253         if (IS_BROADWELL(dev_priv))
1254                 return bdw_init_workarounds(engine);
1255
1256         if (IS_CHERRYVIEW(dev_priv))
1257                 return chv_init_workarounds(engine);
1258
1259         if (IS_SKYLAKE(dev_priv))
1260                 return skl_init_workarounds(engine);
1261
1262         if (IS_BROXTON(dev_priv))
1263                 return bxt_init_workarounds(engine);
1264
1265         if (IS_KABYLAKE(dev_priv))
1266                 return kbl_init_workarounds(engine);
1267
1268         return 0;
1269 }
1270
1271 static int init_render_ring(struct intel_engine_cs *engine)
1272 {
1273         struct drm_i915_private *dev_priv = engine->i915;
1274         int ret = init_ring_common(engine);
1275         if (ret)
1276                 return ret;
1277
1278         /* WaTimedSingleVertexDispatch:cl,bw,ctg,elk,ilk,snb */
1279         if (IS_GEN(dev_priv, 4, 6))
1280                 I915_WRITE(MI_MODE, _MASKED_BIT_ENABLE(VS_TIMER_DISPATCH));
1281
1282         /* We need to disable the AsyncFlip performance optimisations in order
1283          * to use MI_WAIT_FOR_EVENT within the CS. It should already be
1284          * programmed to '1' on all products.
1285          *
1286          * WaDisableAsyncFlipPerfMode:snb,ivb,hsw,vlv
1287          */
1288         if (IS_GEN(dev_priv, 6, 7))
1289                 I915_WRITE(MI_MODE, _MASKED_BIT_ENABLE(ASYNC_FLIP_PERF_DISABLE));
1290
1291         /* Required for the hardware to program scanline values for waiting */
1292         /* WaEnableFlushTlbInvalidationMode:snb */
1293         if (IS_GEN6(dev_priv))
1294                 I915_WRITE(GFX_MODE,
1295                            _MASKED_BIT_ENABLE(GFX_TLB_INVALIDATE_EXPLICIT));
1296
1297         /* WaBCSVCSTlbInvalidationMode:ivb,vlv,hsw */
1298         if (IS_GEN7(dev_priv))
1299                 I915_WRITE(GFX_MODE_GEN7,
1300                            _MASKED_BIT_ENABLE(GFX_TLB_INVALIDATE_EXPLICIT) |
1301                            _MASKED_BIT_ENABLE(GFX_REPLAY_MODE));
1302
1303         if (IS_GEN6(dev_priv)) {
1304                 /* From the Sandybridge PRM, volume 1 part 3, page 24:
1305                  * "If this bit is set, STCunit will have LRA as replacement
1306                  *  policy. [...] This bit must be reset.  LRA replacement
1307                  *  policy is not supported."
1308                  */
1309                 I915_WRITE(CACHE_MODE_0,
1310                            _MASKED_BIT_DISABLE(CM0_STC_EVICT_DISABLE_LRA_SNB));
1311         }
1312
1313         if (IS_GEN(dev_priv, 6, 7))
1314                 I915_WRITE(INSTPM, _MASKED_BIT_ENABLE(INSTPM_FORCE_ORDERING));
1315
1316         if (HAS_L3_DPF(dev_priv))
1317                 I915_WRITE_IMR(engine, ~GT_PARITY_ERROR(dev_priv));
1318
1319         return init_workarounds_ring(engine);
1320 }
1321
1322 static void render_ring_cleanup(struct intel_engine_cs *engine)
1323 {
1324         struct drm_i915_private *dev_priv = engine->i915;
1325
1326         if (dev_priv->semaphore_obj) {
1327                 i915_gem_object_ggtt_unpin(dev_priv->semaphore_obj);
1328                 drm_gem_object_unreference(&dev_priv->semaphore_obj->base);
1329                 dev_priv->semaphore_obj = NULL;
1330         }
1331
1332         intel_fini_pipe_control(engine);
1333 }
1334
1335 static int gen8_rcs_signal(struct drm_i915_gem_request *signaller_req,
1336                            unsigned int num_dwords)
1337 {
1338 #define MBOX_UPDATE_DWORDS 8
1339         struct intel_engine_cs *signaller = signaller_req->engine;
1340         struct drm_i915_private *dev_priv = signaller_req->i915;
1341         struct intel_engine_cs *waiter;
1342         enum intel_engine_id id;
1343         int ret, num_rings;
1344
1345         num_rings = hweight32(INTEL_INFO(dev_priv)->ring_mask);
1346         num_dwords += (num_rings-1) * MBOX_UPDATE_DWORDS;
1347 #undef MBOX_UPDATE_DWORDS
1348
1349         ret = intel_ring_begin(signaller_req, num_dwords);
1350         if (ret)
1351                 return ret;
1352
1353         for_each_engine_id(waiter, dev_priv, id) {
1354                 u64 gtt_offset = signaller->semaphore.signal_ggtt[id];
1355                 if (gtt_offset == MI_SEMAPHORE_SYNC_INVALID)
1356                         continue;
1357
1358                 intel_ring_emit(signaller, GFX_OP_PIPE_CONTROL(6));
1359                 intel_ring_emit(signaller, PIPE_CONTROL_GLOBAL_GTT_IVB |
1360                                            PIPE_CONTROL_QW_WRITE |
1361                                            PIPE_CONTROL_CS_STALL);
1362                 intel_ring_emit(signaller, lower_32_bits(gtt_offset));
1363                 intel_ring_emit(signaller, upper_32_bits(gtt_offset));
1364                 intel_ring_emit(signaller, signaller_req->seqno);
1365                 intel_ring_emit(signaller, 0);
1366                 intel_ring_emit(signaller, MI_SEMAPHORE_SIGNAL |
1367                                            MI_SEMAPHORE_TARGET(waiter->hw_id));
1368                 intel_ring_emit(signaller, 0);
1369         }
1370
1371         return 0;
1372 }
1373
1374 static int gen8_xcs_signal(struct drm_i915_gem_request *signaller_req,
1375                            unsigned int num_dwords)
1376 {
1377 #define MBOX_UPDATE_DWORDS 6
1378         struct intel_engine_cs *signaller = signaller_req->engine;
1379         struct drm_i915_private *dev_priv = signaller_req->i915;
1380         struct intel_engine_cs *waiter;
1381         enum intel_engine_id id;
1382         int ret, num_rings;
1383
1384         num_rings = hweight32(INTEL_INFO(dev_priv)->ring_mask);
1385         num_dwords += (num_rings-1) * MBOX_UPDATE_DWORDS;
1386 #undef MBOX_UPDATE_DWORDS
1387
1388         ret = intel_ring_begin(signaller_req, num_dwords);
1389         if (ret)
1390                 return ret;
1391
1392         for_each_engine_id(waiter, dev_priv, id) {
1393                 u64 gtt_offset = signaller->semaphore.signal_ggtt[id];
1394                 if (gtt_offset == MI_SEMAPHORE_SYNC_INVALID)
1395                         continue;
1396
1397                 intel_ring_emit(signaller, (MI_FLUSH_DW + 1) |
1398                                            MI_FLUSH_DW_OP_STOREDW);
1399                 intel_ring_emit(signaller, lower_32_bits(gtt_offset) |
1400                                            MI_FLUSH_DW_USE_GTT);
1401                 intel_ring_emit(signaller, upper_32_bits(gtt_offset));
1402                 intel_ring_emit(signaller, signaller_req->seqno);
1403                 intel_ring_emit(signaller, MI_SEMAPHORE_SIGNAL |
1404                                            MI_SEMAPHORE_TARGET(waiter->hw_id));
1405                 intel_ring_emit(signaller, 0);
1406         }
1407
1408         return 0;
1409 }
1410
1411 static int gen6_signal(struct drm_i915_gem_request *signaller_req,
1412                        unsigned int num_dwords)
1413 {
1414         struct intel_engine_cs *signaller = signaller_req->engine;
1415         struct drm_i915_private *dev_priv = signaller_req->i915;
1416         struct intel_engine_cs *useless;
1417         enum intel_engine_id id;
1418         int ret, num_rings;
1419
1420 #define MBOX_UPDATE_DWORDS 3
1421         num_rings = hweight32(INTEL_INFO(dev_priv)->ring_mask);
1422         num_dwords += round_up((num_rings-1) * MBOX_UPDATE_DWORDS, 2);
1423 #undef MBOX_UPDATE_DWORDS
1424
1425         ret = intel_ring_begin(signaller_req, num_dwords);
1426         if (ret)
1427                 return ret;
1428
1429         for_each_engine_id(useless, dev_priv, id) {
1430                 i915_reg_t mbox_reg = signaller->semaphore.mbox.signal[id];
1431
1432                 if (i915_mmio_reg_valid(mbox_reg)) {
1433                         intel_ring_emit(signaller, MI_LOAD_REGISTER_IMM(1));
1434                         intel_ring_emit_reg(signaller, mbox_reg);
1435                         intel_ring_emit(signaller, signaller_req->seqno);
1436                 }
1437         }
1438
1439         /* If num_dwords was rounded, make sure the tail pointer is correct */
1440         if (num_rings % 2 == 0)
1441                 intel_ring_emit(signaller, MI_NOOP);
1442
1443         return 0;
1444 }
1445
1446 /**
1447  * gen6_add_request - Update the semaphore mailbox registers
1448  *
1449  * @request - request to write to the ring
1450  *
1451  * Update the mailbox registers in the *other* rings with the current seqno.
1452  * This acts like a signal in the canonical semaphore.
1453  */
1454 static int
1455 gen6_add_request(struct drm_i915_gem_request *req)
1456 {
1457         struct intel_engine_cs *engine = req->engine;
1458         int ret;
1459
1460         if (engine->semaphore.signal)
1461                 ret = engine->semaphore.signal(req, 4);
1462         else
1463                 ret = intel_ring_begin(req, 4);
1464
1465         if (ret)
1466                 return ret;
1467
1468         intel_ring_emit(engine, MI_STORE_DWORD_INDEX);
1469         intel_ring_emit(engine,
1470                         I915_GEM_HWS_INDEX << MI_STORE_DWORD_INDEX_SHIFT);
1471         intel_ring_emit(engine, req->seqno);
1472         intel_ring_emit(engine, MI_USER_INTERRUPT);
1473         __intel_ring_advance(engine);
1474
1475         return 0;
1476 }
1477
1478 static int
1479 gen8_render_add_request(struct drm_i915_gem_request *req)
1480 {
1481         struct intel_engine_cs *engine = req->engine;
1482         int ret;
1483
1484         if (engine->semaphore.signal)
1485                 ret = engine->semaphore.signal(req, 8);
1486         else
1487                 ret = intel_ring_begin(req, 8);
1488         if (ret)
1489                 return ret;
1490
1491         intel_ring_emit(engine, GFX_OP_PIPE_CONTROL(6));
1492         intel_ring_emit(engine, (PIPE_CONTROL_GLOBAL_GTT_IVB |
1493                                  PIPE_CONTROL_CS_STALL |
1494                                  PIPE_CONTROL_QW_WRITE));
1495         intel_ring_emit(engine, intel_hws_seqno_address(req->engine));
1496         intel_ring_emit(engine, 0);
1497         intel_ring_emit(engine, i915_gem_request_get_seqno(req));
1498         /* We're thrashing one dword of HWS. */
1499         intel_ring_emit(engine, 0);
1500         intel_ring_emit(engine, MI_USER_INTERRUPT);
1501         intel_ring_emit(engine, MI_NOOP);
1502         __intel_ring_advance(engine);
1503
1504         return 0;
1505 }
1506
1507 static inline bool i915_gem_has_seqno_wrapped(struct drm_i915_private *dev_priv,
1508                                               u32 seqno)
1509 {
1510         return dev_priv->last_seqno < seqno;
1511 }
1512
1513 /**
1514  * intel_ring_sync - sync the waiter to the signaller on seqno
1515  *
1516  * @waiter - ring that is waiting
1517  * @signaller - ring which has, or will signal
1518  * @seqno - seqno which the waiter will block on
1519  */
1520
1521 static int
1522 gen8_ring_sync(struct drm_i915_gem_request *waiter_req,
1523                struct intel_engine_cs *signaller,
1524                u32 seqno)
1525 {
1526         struct intel_engine_cs *waiter = waiter_req->engine;
1527         struct drm_i915_private *dev_priv = waiter_req->i915;
1528         u64 offset = GEN8_WAIT_OFFSET(waiter, signaller->id);
1529         struct i915_hw_ppgtt *ppgtt;
1530         int ret;
1531
1532         ret = intel_ring_begin(waiter_req, 4);
1533         if (ret)
1534                 return ret;
1535
1536         intel_ring_emit(waiter, MI_SEMAPHORE_WAIT |
1537                                 MI_SEMAPHORE_GLOBAL_GTT |
1538                                 MI_SEMAPHORE_SAD_GTE_SDD);
1539         intel_ring_emit(waiter, seqno);
1540         intel_ring_emit(waiter, lower_32_bits(offset));
1541         intel_ring_emit(waiter, upper_32_bits(offset));
1542         intel_ring_advance(waiter);
1543
1544         /* When the !RCS engines idle waiting upon a semaphore, they lose their
1545          * pagetables and we must reload them before executing the batch.
1546          * We do this on the i915_switch_context() following the wait and
1547          * before the dispatch.
1548          */
1549         ppgtt = waiter_req->ctx->ppgtt;
1550         if (ppgtt && waiter_req->engine->id != RCS)
1551                 ppgtt->pd_dirty_rings |= intel_engine_flag(waiter_req->engine);
1552         return 0;
1553 }
1554
1555 static int
1556 gen6_ring_sync(struct drm_i915_gem_request *waiter_req,
1557                struct intel_engine_cs *signaller,
1558                u32 seqno)
1559 {
1560         struct intel_engine_cs *waiter = waiter_req->engine;
1561         u32 dw1 = MI_SEMAPHORE_MBOX |
1562                   MI_SEMAPHORE_COMPARE |
1563                   MI_SEMAPHORE_REGISTER;
1564         u32 wait_mbox = signaller->semaphore.mbox.wait[waiter->id];
1565         int ret;
1566
1567         /* Throughout all of the GEM code, seqno passed implies our current
1568          * seqno is >= the last seqno executed. However for hardware the
1569          * comparison is strictly greater than.
1570          */
1571         seqno -= 1;
1572
1573         WARN_ON(wait_mbox == MI_SEMAPHORE_SYNC_INVALID);
1574
1575         ret = intel_ring_begin(waiter_req, 4);
1576         if (ret)
1577                 return ret;
1578
1579         /* If seqno wrap happened, omit the wait with no-ops */
1580         if (likely(!i915_gem_has_seqno_wrapped(waiter_req->i915, seqno))) {
1581                 intel_ring_emit(waiter, dw1 | wait_mbox);
1582                 intel_ring_emit(waiter, seqno);
1583                 intel_ring_emit(waiter, 0);
1584                 intel_ring_emit(waiter, MI_NOOP);
1585         } else {
1586                 intel_ring_emit(waiter, MI_NOOP);
1587                 intel_ring_emit(waiter, MI_NOOP);
1588                 intel_ring_emit(waiter, MI_NOOP);
1589                 intel_ring_emit(waiter, MI_NOOP);
1590         }
1591         intel_ring_advance(waiter);
1592
1593         return 0;
1594 }
1595
1596 static void
1597 gen5_seqno_barrier(struct intel_engine_cs *ring)
1598 {
1599         /* MI_STORE are internally buffered by the GPU and not flushed
1600          * either by MI_FLUSH or SyncFlush or any other combination of
1601          * MI commands.
1602          *
1603          * "Only the submission of the store operation is guaranteed.
1604          * The write result will be complete (coherent) some time later
1605          * (this is practically a finite period but there is no guaranteed
1606          * latency)."
1607          *
1608          * Empirically, we observe that we need a delay of at least 75us to
1609          * be sure that the seqno write is visible by the CPU.
1610          */
1611         usleep_range(125, 250);
1612 }
1613
1614 static void
1615 gen6_seqno_barrier(struct intel_engine_cs *engine)
1616 {
1617         struct drm_i915_private *dev_priv = engine->i915;
1618
1619         /* Workaround to force correct ordering between irq and seqno writes on
1620          * ivb (and maybe also on snb) by reading from a CS register (like
1621          * ACTHD) before reading the status page.
1622          *
1623          * Note that this effectively stalls the read by the time it takes to
1624          * do a memory transaction, which more or less ensures that the write
1625          * from the GPU has sufficient time to invalidate the CPU cacheline.
1626          * Alternatively we could delay the interrupt from the CS ring to give
1627          * the write time to land, but that would incur a delay after every
1628          * batch i.e. much more frequent than a delay when waiting for the
1629          * interrupt (with the same net latency).
1630          *
1631          * Also note that to prevent whole machine hangs on gen7, we have to
1632          * take the spinlock to guard against concurrent cacheline access.
1633          */
1634         spin_lock_irq(&dev_priv->uncore.lock);
1635         POSTING_READ_FW(RING_ACTHD(engine->mmio_base));
1636         spin_unlock_irq(&dev_priv->uncore.lock);
1637 }
1638
1639 static void
1640 gen5_irq_enable(struct intel_engine_cs *engine)
1641 {
1642         gen5_enable_gt_irq(engine->i915, engine->irq_enable_mask);
1643 }
1644
1645 static void
1646 gen5_irq_disable(struct intel_engine_cs *engine)
1647 {
1648         gen5_disable_gt_irq(engine->i915, engine->irq_enable_mask);
1649 }
1650
1651 static void
1652 i9xx_irq_enable(struct intel_engine_cs *engine)
1653 {
1654         struct drm_i915_private *dev_priv = engine->i915;
1655
1656         dev_priv->irq_mask &= ~engine->irq_enable_mask;
1657         I915_WRITE(IMR, dev_priv->irq_mask);
1658         POSTING_READ_FW(RING_IMR(engine->mmio_base));
1659 }
1660
1661 static void
1662 i9xx_irq_disable(struct intel_engine_cs *engine)
1663 {
1664         struct drm_i915_private *dev_priv = engine->i915;
1665
1666         dev_priv->irq_mask |= engine->irq_enable_mask;
1667         I915_WRITE(IMR, dev_priv->irq_mask);
1668 }
1669
1670 static void
1671 i8xx_irq_enable(struct intel_engine_cs *engine)
1672 {
1673         struct drm_i915_private *dev_priv = engine->i915;
1674
1675         dev_priv->irq_mask &= ~engine->irq_enable_mask;
1676         I915_WRITE16(IMR, dev_priv->irq_mask);
1677         POSTING_READ16(RING_IMR(engine->mmio_base));
1678 }
1679
1680 static void
1681 i8xx_irq_disable(struct intel_engine_cs *engine)
1682 {
1683         struct drm_i915_private *dev_priv = engine->i915;
1684
1685         dev_priv->irq_mask |= engine->irq_enable_mask;
1686         I915_WRITE16(IMR, dev_priv->irq_mask);
1687 }
1688
1689 static int
1690 bsd_ring_flush(struct drm_i915_gem_request *req,
1691                u32     invalidate_domains,
1692                u32     flush_domains)
1693 {
1694         struct intel_engine_cs *engine = req->engine;
1695         int ret;
1696
1697         ret = intel_ring_begin(req, 2);
1698         if (ret)
1699                 return ret;
1700
1701         intel_ring_emit(engine, MI_FLUSH);
1702         intel_ring_emit(engine, MI_NOOP);
1703         intel_ring_advance(engine);
1704         return 0;
1705 }
1706
1707 static int
1708 i9xx_add_request(struct drm_i915_gem_request *req)
1709 {
1710         struct intel_engine_cs *engine = req->engine;
1711         int ret;
1712
1713         ret = intel_ring_begin(req, 4);
1714         if (ret)
1715                 return ret;
1716
1717         intel_ring_emit(engine, MI_STORE_DWORD_INDEX);
1718         intel_ring_emit(engine,
1719                         I915_GEM_HWS_INDEX << MI_STORE_DWORD_INDEX_SHIFT);
1720         intel_ring_emit(engine, req->seqno);
1721         intel_ring_emit(engine, MI_USER_INTERRUPT);
1722         __intel_ring_advance(engine);
1723
1724         return 0;
1725 }
1726
1727 static void
1728 gen6_irq_enable(struct intel_engine_cs *engine)
1729 {
1730         struct drm_i915_private *dev_priv = engine->i915;
1731
1732         if (HAS_L3_DPF(dev_priv) && engine->id == RCS)
1733                 I915_WRITE_IMR(engine,
1734                                ~(engine->irq_enable_mask |
1735                                  GT_PARITY_ERROR(dev_priv)));
1736         else
1737                 I915_WRITE_IMR(engine, ~engine->irq_enable_mask);
1738         gen5_enable_gt_irq(dev_priv, engine->irq_enable_mask);
1739 }
1740
1741 static void
1742 gen6_irq_disable(struct intel_engine_cs *engine)
1743 {
1744         struct drm_i915_private *dev_priv = engine->i915;
1745
1746         if (HAS_L3_DPF(dev_priv) && engine->id == RCS)
1747                 I915_WRITE_IMR(engine, ~GT_PARITY_ERROR(dev_priv));
1748         else
1749                 I915_WRITE_IMR(engine, ~0);
1750         gen5_disable_gt_irq(dev_priv, engine->irq_enable_mask);
1751 }
1752
1753 static void
1754 hsw_vebox_irq_enable(struct intel_engine_cs *engine)
1755 {
1756         struct drm_i915_private *dev_priv = engine->i915;
1757
1758         I915_WRITE_IMR(engine, ~engine->irq_enable_mask);
1759         gen6_enable_pm_irq(dev_priv, engine->irq_enable_mask);
1760 }
1761
1762 static void
1763 hsw_vebox_irq_disable(struct intel_engine_cs *engine)
1764 {
1765         struct drm_i915_private *dev_priv = engine->i915;
1766
1767         I915_WRITE_IMR(engine, ~0);
1768         gen6_disable_pm_irq(dev_priv, engine->irq_enable_mask);
1769 }
1770
1771 static void
1772 gen8_irq_enable(struct intel_engine_cs *engine)
1773 {
1774         struct drm_i915_private *dev_priv = engine->i915;
1775
1776         if (HAS_L3_DPF(dev_priv) && engine->id == RCS)
1777                 I915_WRITE_IMR(engine,
1778                                ~(engine->irq_enable_mask |
1779                                  GT_RENDER_L3_PARITY_ERROR_INTERRUPT));
1780         else
1781                 I915_WRITE_IMR(engine, ~engine->irq_enable_mask);
1782         POSTING_READ_FW(RING_IMR(engine->mmio_base));
1783 }
1784
1785 static void
1786 gen8_irq_disable(struct intel_engine_cs *engine)
1787 {
1788         struct drm_i915_private *dev_priv = engine->i915;
1789
1790         if (HAS_L3_DPF(dev_priv) && engine->id == RCS)
1791                 I915_WRITE_IMR(engine,
1792                                ~GT_RENDER_L3_PARITY_ERROR_INTERRUPT);
1793         else
1794                 I915_WRITE_IMR(engine, ~0);
1795 }
1796
1797 static int
1798 i965_dispatch_execbuffer(struct drm_i915_gem_request *req,
1799                          u64 offset, u32 length,
1800                          unsigned dispatch_flags)
1801 {
1802         struct intel_engine_cs *engine = req->engine;
1803         int ret;
1804
1805         ret = intel_ring_begin(req, 2);
1806         if (ret)
1807                 return ret;
1808
1809         intel_ring_emit(engine,
1810                         MI_BATCH_BUFFER_START |
1811                         MI_BATCH_GTT |
1812                         (dispatch_flags & I915_DISPATCH_SECURE ?
1813                          0 : MI_BATCH_NON_SECURE_I965));
1814         intel_ring_emit(engine, offset);
1815         intel_ring_advance(engine);
1816
1817         return 0;
1818 }
1819
1820 /* Just userspace ABI convention to limit the wa batch bo to a resonable size */
1821 #define I830_BATCH_LIMIT (256*1024)
1822 #define I830_TLB_ENTRIES (2)
1823 #define I830_WA_SIZE max(I830_TLB_ENTRIES*4096, I830_BATCH_LIMIT)
1824 static int
1825 i830_dispatch_execbuffer(struct drm_i915_gem_request *req,
1826                          u64 offset, u32 len,
1827                          unsigned dispatch_flags)
1828 {
1829         struct intel_engine_cs *engine = req->engine;
1830         u32 cs_offset = engine->scratch.gtt_offset;
1831         int ret;
1832
1833         ret = intel_ring_begin(req, 6);
1834         if (ret)
1835                 return ret;
1836
1837         /* Evict the invalid PTE TLBs */
1838         intel_ring_emit(engine, COLOR_BLT_CMD | BLT_WRITE_RGBA);
1839         intel_ring_emit(engine, BLT_DEPTH_32 | BLT_ROP_COLOR_COPY | 4096);
1840         intel_ring_emit(engine, I830_TLB_ENTRIES << 16 | 4); /* load each page */
1841         intel_ring_emit(engine, cs_offset);
1842         intel_ring_emit(engine, 0xdeadbeef);
1843         intel_ring_emit(engine, MI_NOOP);
1844         intel_ring_advance(engine);
1845
1846         if ((dispatch_flags & I915_DISPATCH_PINNED) == 0) {
1847                 if (len > I830_BATCH_LIMIT)
1848                         return -ENOSPC;
1849
1850                 ret = intel_ring_begin(req, 6 + 2);
1851                 if (ret)
1852                         return ret;
1853
1854                 /* Blit the batch (which has now all relocs applied) to the
1855                  * stable batch scratch bo area (so that the CS never
1856                  * stumbles over its tlb invalidation bug) ...
1857                  */
1858                 intel_ring_emit(engine, SRC_COPY_BLT_CMD | BLT_WRITE_RGBA);
1859                 intel_ring_emit(engine,
1860                                 BLT_DEPTH_32 | BLT_ROP_SRC_COPY | 4096);
1861                 intel_ring_emit(engine, DIV_ROUND_UP(len, 4096) << 16 | 4096);
1862                 intel_ring_emit(engine, cs_offset);
1863                 intel_ring_emit(engine, 4096);
1864                 intel_ring_emit(engine, offset);
1865
1866                 intel_ring_emit(engine, MI_FLUSH);
1867                 intel_ring_emit(engine, MI_NOOP);
1868                 intel_ring_advance(engine);
1869
1870                 /* ... and execute it. */
1871                 offset = cs_offset;
1872         }
1873
1874         ret = intel_ring_begin(req, 2);
1875         if (ret)
1876                 return ret;
1877
1878         intel_ring_emit(engine, MI_BATCH_BUFFER_START | MI_BATCH_GTT);
1879         intel_ring_emit(engine, offset | (dispatch_flags & I915_DISPATCH_SECURE ?
1880                                           0 : MI_BATCH_NON_SECURE));
1881         intel_ring_advance(engine);
1882
1883         return 0;
1884 }
1885
1886 static int
1887 i915_dispatch_execbuffer(struct drm_i915_gem_request *req,
1888                          u64 offset, u32 len,
1889                          unsigned dispatch_flags)
1890 {
1891         struct intel_engine_cs *engine = req->engine;
1892         int ret;
1893
1894         ret = intel_ring_begin(req, 2);
1895         if (ret)
1896                 return ret;
1897
1898         intel_ring_emit(engine, MI_BATCH_BUFFER_START | MI_BATCH_GTT);
1899         intel_ring_emit(engine, offset | (dispatch_flags & I915_DISPATCH_SECURE ?
1900                                           0 : MI_BATCH_NON_SECURE));
1901         intel_ring_advance(engine);
1902
1903         return 0;
1904 }
1905
1906 static void cleanup_phys_status_page(struct intel_engine_cs *engine)
1907 {
1908         struct drm_i915_private *dev_priv = engine->i915;
1909
1910         if (!dev_priv->status_page_dmah)
1911                 return;
1912
1913         drm_pci_free(dev_priv->dev, dev_priv->status_page_dmah);
1914         engine->status_page.page_addr = NULL;
1915 }
1916
1917 static void cleanup_status_page(struct intel_engine_cs *engine)
1918 {
1919         struct drm_i915_gem_object *obj;
1920
1921         obj = engine->status_page.obj;
1922         if (obj == NULL)
1923                 return;
1924
1925         kunmap(sg_page(obj->pages->sgl));
1926         i915_gem_object_ggtt_unpin(obj);
1927         drm_gem_object_unreference(&obj->base);
1928         engine->status_page.obj = NULL;
1929 }
1930
1931 static int init_status_page(struct intel_engine_cs *engine)
1932 {
1933         struct drm_i915_gem_object *obj = engine->status_page.obj;
1934
1935         if (obj == NULL) {
1936                 unsigned flags;
1937                 int ret;
1938
1939                 obj = i915_gem_object_create(engine->i915->dev, 4096);
1940                 if (IS_ERR(obj)) {
1941                         DRM_ERROR("Failed to allocate status page\n");
1942                         return PTR_ERR(obj);
1943                 }
1944
1945                 ret = i915_gem_object_set_cache_level(obj, I915_CACHE_LLC);
1946                 if (ret)
1947                         goto err_unref;
1948
1949                 flags = 0;
1950                 if (!HAS_LLC(engine->i915))
1951                         /* On g33, we cannot place HWS above 256MiB, so
1952                          * restrict its pinning to the low mappable arena.
1953                          * Though this restriction is not documented for
1954                          * gen4, gen5, or byt, they also behave similarly
1955                          * and hang if the HWS is placed at the top of the
1956                          * GTT. To generalise, it appears that all !llc
1957                          * platforms have issues with us placing the HWS
1958                          * above the mappable region (even though we never
1959                          * actualy map it).
1960                          */
1961                         flags |= PIN_MAPPABLE;
1962                 ret = i915_gem_obj_ggtt_pin(obj, 4096, flags);
1963                 if (ret) {
1964 err_unref:
1965                         drm_gem_object_unreference(&obj->base);
1966                         return ret;
1967                 }
1968
1969                 engine->status_page.obj = obj;
1970         }
1971
1972         engine->status_page.gfx_addr = i915_gem_obj_ggtt_offset(obj);
1973         engine->status_page.page_addr = kmap(sg_page(obj->pages->sgl));
1974         memset(engine->status_page.page_addr, 0, PAGE_SIZE);
1975
1976         DRM_DEBUG_DRIVER("%s hws offset: 0x%08x\n",
1977                         engine->name, engine->status_page.gfx_addr);
1978
1979         return 0;
1980 }
1981
1982 static int init_phys_status_page(struct intel_engine_cs *engine)
1983 {
1984         struct drm_i915_private *dev_priv = engine->i915;
1985
1986         if (!dev_priv->status_page_dmah) {
1987                 dev_priv->status_page_dmah =
1988                         drm_pci_alloc(dev_priv->dev, PAGE_SIZE, PAGE_SIZE);
1989                 if (!dev_priv->status_page_dmah)
1990                         return -ENOMEM;
1991         }
1992
1993         engine->status_page.page_addr = dev_priv->status_page_dmah->vaddr;
1994         memset(engine->status_page.page_addr, 0, PAGE_SIZE);
1995
1996         return 0;
1997 }
1998
1999 void intel_unpin_ringbuffer_obj(struct intel_ringbuffer *ringbuf)
2000 {
2001         GEM_BUG_ON(ringbuf->vma == NULL);
2002         GEM_BUG_ON(ringbuf->virtual_start == NULL);
2003
2004         if (HAS_LLC(ringbuf->obj->base.dev) && !ringbuf->obj->stolen)
2005                 i915_gem_object_unpin_map(ringbuf->obj);
2006         else
2007                 i915_vma_unpin_iomap(ringbuf->vma);
2008         ringbuf->virtual_start = NULL;
2009
2010         i915_gem_object_ggtt_unpin(ringbuf->obj);
2011         ringbuf->vma = NULL;
2012 }
2013
2014 int intel_pin_and_map_ringbuffer_obj(struct drm_i915_private *dev_priv,
2015                                      struct intel_ringbuffer *ringbuf)
2016 {
2017         struct drm_i915_gem_object *obj = ringbuf->obj;
2018         /* Ring wraparound at offset 0 sometimes hangs. No idea why. */
2019         unsigned flags = PIN_OFFSET_BIAS | 4096;
2020         void *addr;
2021         int ret;
2022
2023         if (HAS_LLC(dev_priv) && !obj->stolen) {
2024                 ret = i915_gem_obj_ggtt_pin(obj, PAGE_SIZE, flags);
2025                 if (ret)
2026                         return ret;
2027
2028                 ret = i915_gem_object_set_to_cpu_domain(obj, true);
2029                 if (ret)
2030                         goto err_unpin;
2031
2032                 addr = i915_gem_object_pin_map(obj);
2033                 if (IS_ERR(addr)) {
2034                         ret = PTR_ERR(addr);
2035                         goto err_unpin;
2036                 }
2037         } else {
2038                 ret = i915_gem_obj_ggtt_pin(obj, PAGE_SIZE,
2039                                             flags | PIN_MAPPABLE);
2040                 if (ret)
2041                         return ret;
2042
2043                 ret = i915_gem_object_set_to_gtt_domain(obj, true);
2044                 if (ret)
2045                         goto err_unpin;
2046
2047                 /* Access through the GTT requires the device to be awake. */
2048                 assert_rpm_wakelock_held(dev_priv);
2049
2050                 addr = i915_vma_pin_iomap(i915_gem_obj_to_ggtt(obj));
2051                 if (IS_ERR(addr)) {
2052                         ret = PTR_ERR(addr);
2053                         goto err_unpin;
2054                 }
2055         }
2056
2057         ringbuf->virtual_start = addr;
2058         ringbuf->vma = i915_gem_obj_to_ggtt(obj);
2059         return 0;
2060
2061 err_unpin:
2062         i915_gem_object_ggtt_unpin(obj);
2063         return ret;
2064 }
2065
2066 static void intel_destroy_ringbuffer_obj(struct intel_ringbuffer *ringbuf)
2067 {
2068         drm_gem_object_unreference(&ringbuf->obj->base);
2069         ringbuf->obj = NULL;
2070 }
2071
2072 static int intel_alloc_ringbuffer_obj(struct drm_device *dev,
2073                                       struct intel_ringbuffer *ringbuf)
2074 {
2075         struct drm_i915_gem_object *obj;
2076
2077         obj = NULL;
2078         if (!HAS_LLC(dev))
2079                 obj = i915_gem_object_create_stolen(dev, ringbuf->size);
2080         if (obj == NULL)
2081                 obj = i915_gem_object_create(dev, ringbuf->size);
2082         if (IS_ERR(obj))
2083                 return PTR_ERR(obj);
2084
2085         /* mark ring buffers as read-only from GPU side by default */
2086         obj->gt_ro = 1;
2087
2088         ringbuf->obj = obj;
2089
2090         return 0;
2091 }
2092
2093 struct intel_ringbuffer *
2094 intel_engine_create_ringbuffer(struct intel_engine_cs *engine, int size)
2095 {
2096         struct intel_ringbuffer *ring;
2097         int ret;
2098
2099         ring = kzalloc(sizeof(*ring), GFP_KERNEL);
2100         if (ring == NULL) {
2101                 DRM_DEBUG_DRIVER("Failed to allocate ringbuffer %s\n",
2102                                  engine->name);
2103                 return ERR_PTR(-ENOMEM);
2104         }
2105
2106         ring->engine = engine;
2107         list_add(&ring->link, &engine->buffers);
2108
2109         ring->size = size;
2110         /* Workaround an erratum on the i830 which causes a hang if
2111          * the TAIL pointer points to within the last 2 cachelines
2112          * of the buffer.
2113          */
2114         ring->effective_size = size;
2115         if (IS_I830(engine->i915) || IS_845G(engine->i915))
2116                 ring->effective_size -= 2 * CACHELINE_BYTES;
2117
2118         ring->last_retired_head = -1;
2119         intel_ring_update_space(ring);
2120
2121         ret = intel_alloc_ringbuffer_obj(engine->i915->dev, ring);
2122         if (ret) {
2123                 DRM_DEBUG_DRIVER("Failed to allocate ringbuffer %s: %d\n",
2124                                  engine->name, ret);
2125                 list_del(&ring->link);
2126                 kfree(ring);
2127                 return ERR_PTR(ret);
2128         }
2129
2130         return ring;
2131 }
2132
2133 void
2134 intel_ringbuffer_free(struct intel_ringbuffer *ring)
2135 {
2136         intel_destroy_ringbuffer_obj(ring);
2137         list_del(&ring->link);
2138         kfree(ring);
2139 }
2140
2141 static int intel_ring_context_pin(struct i915_gem_context *ctx,
2142                                   struct intel_engine_cs *engine)
2143 {
2144         struct intel_context *ce = &ctx->engine[engine->id];
2145         int ret;
2146
2147         lockdep_assert_held(&ctx->i915->dev->struct_mutex);
2148
2149         if (ce->pin_count++)
2150                 return 0;
2151
2152         if (ce->state) {
2153                 ret = i915_gem_obj_ggtt_pin(ce->state, ctx->ggtt_alignment, 0);
2154                 if (ret)
2155                         goto error;
2156         }
2157
2158         /* The kernel context is only used as a placeholder for flushing the
2159          * active context. It is never used for submitting user rendering and
2160          * as such never requires the golden render context, and so we can skip
2161          * emitting it when we switch to the kernel context. This is required
2162          * as during eviction we cannot allocate and pin the renderstate in
2163          * order to initialise the context.
2164          */
2165         if (ctx == ctx->i915->kernel_context)
2166                 ce->initialised = true;
2167
2168         i915_gem_context_reference(ctx);
2169         return 0;
2170
2171 error:
2172         ce->pin_count = 0;
2173         return ret;
2174 }
2175
2176 static void intel_ring_context_unpin(struct i915_gem_context *ctx,
2177                                      struct intel_engine_cs *engine)
2178 {
2179         struct intel_context *ce = &ctx->engine[engine->id];
2180
2181         lockdep_assert_held(&ctx->i915->dev->struct_mutex);
2182
2183         if (--ce->pin_count)
2184                 return;
2185
2186         if (ce->state)
2187                 i915_gem_object_ggtt_unpin(ce->state);
2188
2189         i915_gem_context_unreference(ctx);
2190 }
2191
2192 static int intel_init_ring_buffer(struct drm_device *dev,
2193                                   struct intel_engine_cs *engine)
2194 {
2195         struct drm_i915_private *dev_priv = to_i915(dev);
2196         struct intel_ringbuffer *ringbuf;
2197         int ret;
2198
2199         WARN_ON(engine->buffer);
2200
2201         engine->i915 = dev_priv;
2202         INIT_LIST_HEAD(&engine->active_list);
2203         INIT_LIST_HEAD(&engine->request_list);
2204         INIT_LIST_HEAD(&engine->execlist_queue);
2205         INIT_LIST_HEAD(&engine->buffers);
2206         i915_gem_batch_pool_init(dev, &engine->batch_pool);
2207         memset(engine->semaphore.sync_seqno, 0,
2208                sizeof(engine->semaphore.sync_seqno));
2209
2210         ret = intel_engine_init_breadcrumbs(engine);
2211         if (ret)
2212                 goto error;
2213
2214         /* We may need to do things with the shrinker which
2215          * require us to immediately switch back to the default
2216          * context. This can cause a problem as pinning the
2217          * default context also requires GTT space which may not
2218          * be available. To avoid this we always pin the default
2219          * context.
2220          */
2221         ret = intel_ring_context_pin(dev_priv->kernel_context, engine);
2222         if (ret)
2223                 goto error;
2224
2225         ringbuf = intel_engine_create_ringbuffer(engine, 32 * PAGE_SIZE);
2226         if (IS_ERR(ringbuf)) {
2227                 ret = PTR_ERR(ringbuf);
2228                 goto error;
2229         }
2230         engine->buffer = ringbuf;
2231
2232         if (I915_NEED_GFX_HWS(dev_priv)) {
2233                 ret = init_status_page(engine);
2234                 if (ret)
2235                         goto error;
2236         } else {
2237                 WARN_ON(engine->id != RCS);
2238                 ret = init_phys_status_page(engine);
2239                 if (ret)
2240                         goto error;
2241         }
2242
2243         ret = intel_pin_and_map_ringbuffer_obj(dev_priv, ringbuf);
2244         if (ret) {
2245                 DRM_ERROR("Failed to pin and map ringbuffer %s: %d\n",
2246                                 engine->name, ret);
2247                 intel_destroy_ringbuffer_obj(ringbuf);
2248                 goto error;
2249         }
2250
2251         ret = i915_cmd_parser_init_ring(engine);
2252         if (ret)
2253                 goto error;
2254
2255         return 0;
2256
2257 error:
2258         intel_cleanup_engine(engine);
2259         return ret;
2260 }
2261
2262 void intel_cleanup_engine(struct intel_engine_cs *engine)
2263 {
2264         struct drm_i915_private *dev_priv;
2265
2266         if (!intel_engine_initialized(engine))
2267                 return;
2268
2269         dev_priv = engine->i915;
2270
2271         if (engine->buffer) {
2272                 intel_stop_engine(engine);
2273                 WARN_ON(!IS_GEN2(dev_priv) && (I915_READ_MODE(engine) & MODE_IDLE) == 0);
2274
2275                 intel_unpin_ringbuffer_obj(engine->buffer);
2276                 intel_ringbuffer_free(engine->buffer);
2277                 engine->buffer = NULL;
2278         }
2279
2280         if (engine->cleanup)
2281                 engine->cleanup(engine);
2282
2283         if (I915_NEED_GFX_HWS(dev_priv)) {
2284                 cleanup_status_page(engine);
2285         } else {
2286                 WARN_ON(engine->id != RCS);
2287                 cleanup_phys_status_page(engine);
2288         }
2289
2290         i915_cmd_parser_fini_ring(engine);
2291         i915_gem_batch_pool_fini(&engine->batch_pool);
2292         intel_engine_fini_breadcrumbs(engine);
2293
2294         intel_ring_context_unpin(dev_priv->kernel_context, engine);
2295
2296         engine->i915 = NULL;
2297 }
2298
2299 int intel_engine_idle(struct intel_engine_cs *engine)
2300 {
2301         struct drm_i915_gem_request *req;
2302
2303         /* Wait upon the last request to be completed */
2304         if (list_empty(&engine->request_list))
2305                 return 0;
2306
2307         req = list_entry(engine->request_list.prev,
2308                          struct drm_i915_gem_request,
2309                          list);
2310
2311         /* Make sure we do not trigger any retires */
2312         return __i915_wait_request(req,
2313                                    req->i915->mm.interruptible,
2314                                    NULL, NULL);
2315 }
2316
2317 int intel_ring_alloc_request_extras(struct drm_i915_gem_request *request)
2318 {
2319         int ret;
2320
2321         /* Flush enough space to reduce the likelihood of waiting after
2322          * we start building the request - in which case we will just
2323          * have to repeat work.
2324          */
2325         request->reserved_space += LEGACY_REQUEST_SIZE;
2326
2327         request->ringbuf = request->engine->buffer;
2328
2329         ret = intel_ring_begin(request, 0);
2330         if (ret)
2331                 return ret;
2332
2333         request->reserved_space -= LEGACY_REQUEST_SIZE;
2334         return 0;
2335 }
2336
2337 static int wait_for_space(struct drm_i915_gem_request *req, int bytes)
2338 {
2339         struct intel_ringbuffer *ringbuf = req->ringbuf;
2340         struct intel_engine_cs *engine = req->engine;
2341         struct drm_i915_gem_request *target;
2342
2343         intel_ring_update_space(ringbuf);
2344         if (ringbuf->space >= bytes)
2345                 return 0;
2346
2347         /*
2348          * Space is reserved in the ringbuffer for finalising the request,
2349          * as that cannot be allowed to fail. During request finalisation,
2350          * reserved_space is set to 0 to stop the overallocation and the
2351          * assumption is that then we never need to wait (which has the
2352          * risk of failing with EINTR).
2353          *
2354          * See also i915_gem_request_alloc() and i915_add_request().
2355          */
2356         GEM_BUG_ON(!req->reserved_space);
2357
2358         list_for_each_entry(target, &engine->request_list, list) {
2359                 unsigned space;
2360
2361                 /*
2362                  * The request queue is per-engine, so can contain requests
2363                  * from multiple ringbuffers. Here, we must ignore any that
2364                  * aren't from the ringbuffer we're considering.
2365                  */
2366                 if (target->ringbuf != ringbuf)
2367                         continue;
2368
2369                 /* Would completion of this request free enough space? */
2370                 space = __intel_ring_space(target->postfix, ringbuf->tail,
2371                                            ringbuf->size);
2372                 if (space >= bytes)
2373                         break;
2374         }
2375
2376         if (WARN_ON(&target->list == &engine->request_list))
2377                 return -ENOSPC;
2378
2379         return i915_wait_request(target);
2380 }
2381
2382 int intel_ring_begin(struct drm_i915_gem_request *req, int num_dwords)
2383 {
2384         struct intel_ringbuffer *ringbuf = req->ringbuf;
2385         int remain_actual = ringbuf->size - ringbuf->tail;
2386         int remain_usable = ringbuf->effective_size - ringbuf->tail;
2387         int bytes = num_dwords * sizeof(u32);
2388         int total_bytes, wait_bytes;
2389         bool need_wrap = false;
2390
2391         total_bytes = bytes + req->reserved_space;
2392
2393         if (unlikely(bytes > remain_usable)) {
2394                 /*
2395                  * Not enough space for the basic request. So need to flush
2396                  * out the remainder and then wait for base + reserved.
2397                  */
2398                 wait_bytes = remain_actual + total_bytes;
2399                 need_wrap = true;
2400         } else if (unlikely(total_bytes > remain_usable)) {
2401                 /*
2402                  * The base request will fit but the reserved space
2403                  * falls off the end. So we don't need an immediate wrap
2404                  * and only need to effectively wait for the reserved
2405                  * size space from the start of ringbuffer.
2406                  */
2407                 wait_bytes = remain_actual + req->reserved_space;
2408         } else {
2409                 /* No wrapping required, just waiting. */
2410                 wait_bytes = total_bytes;
2411         }
2412
2413         if (wait_bytes > ringbuf->space) {
2414                 int ret = wait_for_space(req, wait_bytes);
2415                 if (unlikely(ret))
2416                         return ret;
2417
2418                 intel_ring_update_space(ringbuf);
2419                 if (unlikely(ringbuf->space < wait_bytes))
2420                         return -EAGAIN;
2421         }
2422
2423         if (unlikely(need_wrap)) {
2424                 GEM_BUG_ON(remain_actual > ringbuf->space);
2425                 GEM_BUG_ON(ringbuf->tail + remain_actual > ringbuf->size);
2426
2427                 /* Fill the tail with MI_NOOP */
2428                 memset(ringbuf->virtual_start + ringbuf->tail,
2429                        0, remain_actual);
2430                 ringbuf->tail = 0;
2431                 ringbuf->space -= remain_actual;
2432         }
2433
2434         ringbuf->space -= bytes;
2435         GEM_BUG_ON(ringbuf->space < 0);
2436         return 0;
2437 }
2438
2439 /* Align the ring tail to a cacheline boundary */
2440 int intel_ring_cacheline_align(struct drm_i915_gem_request *req)
2441 {
2442         struct intel_engine_cs *engine = req->engine;
2443         int num_dwords = (engine->buffer->tail & (CACHELINE_BYTES - 1)) / sizeof(uint32_t);
2444         int ret;
2445
2446         if (num_dwords == 0)
2447                 return 0;
2448
2449         num_dwords = CACHELINE_BYTES / sizeof(uint32_t) - num_dwords;
2450         ret = intel_ring_begin(req, num_dwords);
2451         if (ret)
2452                 return ret;
2453
2454         while (num_dwords--)
2455                 intel_ring_emit(engine, MI_NOOP);
2456
2457         intel_ring_advance(engine);
2458
2459         return 0;
2460 }
2461
2462 void intel_ring_init_seqno(struct intel_engine_cs *engine, u32 seqno)
2463 {
2464         struct drm_i915_private *dev_priv = engine->i915;
2465
2466         /* Our semaphore implementation is strictly monotonic (i.e. we proceed
2467          * so long as the semaphore value in the register/page is greater
2468          * than the sync value), so whenever we reset the seqno,
2469          * so long as we reset the tracking semaphore value to 0, it will
2470          * always be before the next request's seqno. If we don't reset
2471          * the semaphore value, then when the seqno moves backwards all
2472          * future waits will complete instantly (causing rendering corruption).
2473          */
2474         if (IS_GEN6(dev_priv) || IS_GEN7(dev_priv)) {
2475                 I915_WRITE(RING_SYNC_0(engine->mmio_base), 0);
2476                 I915_WRITE(RING_SYNC_1(engine->mmio_base), 0);
2477                 if (HAS_VEBOX(dev_priv))
2478                         I915_WRITE(RING_SYNC_2(engine->mmio_base), 0);
2479         }
2480         if (dev_priv->semaphore_obj) {
2481                 struct drm_i915_gem_object *obj = dev_priv->semaphore_obj;
2482                 struct page *page = i915_gem_object_get_dirty_page(obj, 0);
2483                 void *semaphores = kmap(page);
2484                 memset(semaphores + GEN8_SEMAPHORE_OFFSET(engine->id, 0),
2485                        0, I915_NUM_ENGINES * gen8_semaphore_seqno_size);
2486                 kunmap(page);
2487         }
2488         memset(engine->semaphore.sync_seqno, 0,
2489                sizeof(engine->semaphore.sync_seqno));
2490
2491         intel_write_status_page(engine, I915_GEM_HWS_INDEX, seqno);
2492         if (engine->irq_seqno_barrier)
2493                 engine->irq_seqno_barrier(engine);
2494         engine->last_submitted_seqno = seqno;
2495
2496         engine->hangcheck.seqno = seqno;
2497
2498         /* After manually advancing the seqno, fake the interrupt in case
2499          * there are any waiters for that seqno.
2500          */
2501         rcu_read_lock();
2502         intel_engine_wakeup(engine);
2503         rcu_read_unlock();
2504 }
2505
2506 static void gen6_bsd_ring_write_tail(struct intel_engine_cs *engine,
2507                                      u32 value)
2508 {
2509         struct drm_i915_private *dev_priv = engine->i915;
2510
2511         intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
2512
2513        /* Every tail move must follow the sequence below */
2514
2515         /* Disable notification that the ring is IDLE. The GT
2516          * will then assume that it is busy and bring it out of rc6.
2517          */
2518         I915_WRITE_FW(GEN6_BSD_SLEEP_PSMI_CONTROL,
2519                       _MASKED_BIT_ENABLE(GEN6_BSD_SLEEP_MSG_DISABLE));
2520
2521         /* Clear the context id. Here be magic! */
2522         I915_WRITE64_FW(GEN6_BSD_RNCID, 0x0);
2523
2524         /* Wait for the ring not to be idle, i.e. for it to wake up. */
2525         if (intel_wait_for_register_fw(dev_priv,
2526                                        GEN6_BSD_SLEEP_PSMI_CONTROL,
2527                                        GEN6_BSD_SLEEP_INDICATOR,
2528                                        0,
2529                                        50))
2530                 DRM_ERROR("timed out waiting for the BSD ring to wake up\n");
2531
2532         /* Now that the ring is fully powered up, update the tail */
2533         I915_WRITE_FW(RING_TAIL(engine->mmio_base), value);
2534         POSTING_READ_FW(RING_TAIL(engine->mmio_base));
2535
2536         /* Let the ring send IDLE messages to the GT again,
2537          * and so let it sleep to conserve power when idle.
2538          */
2539         I915_WRITE_FW(GEN6_BSD_SLEEP_PSMI_CONTROL,
2540                       _MASKED_BIT_DISABLE(GEN6_BSD_SLEEP_MSG_DISABLE));
2541
2542         intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
2543 }
2544
2545 static int gen6_bsd_ring_flush(struct drm_i915_gem_request *req,
2546                                u32 invalidate, u32 flush)
2547 {
2548         struct intel_engine_cs *engine = req->engine;
2549         uint32_t cmd;
2550         int ret;
2551
2552         ret = intel_ring_begin(req, 4);
2553         if (ret)
2554                 return ret;
2555
2556         cmd = MI_FLUSH_DW;
2557         if (INTEL_GEN(req->i915) >= 8)
2558                 cmd += 1;
2559
2560         /* We always require a command barrier so that subsequent
2561          * commands, such as breadcrumb interrupts, are strictly ordered
2562          * wrt the contents of the write cache being flushed to memory
2563          * (and thus being coherent from the CPU).
2564          */
2565         cmd |= MI_FLUSH_DW_STORE_INDEX | MI_FLUSH_DW_OP_STOREDW;
2566
2567         /*
2568          * Bspec vol 1c.5 - video engine command streamer:
2569          * "If ENABLED, all TLBs will be invalidated once the flush
2570          * operation is complete. This bit is only valid when the
2571          * Post-Sync Operation field is a value of 1h or 3h."
2572          */
2573         if (invalidate & I915_GEM_GPU_DOMAINS)
2574                 cmd |= MI_INVALIDATE_TLB | MI_INVALIDATE_BSD;
2575
2576         intel_ring_emit(engine, cmd);
2577         intel_ring_emit(engine,
2578                         I915_GEM_HWS_SCRATCH_ADDR | MI_FLUSH_DW_USE_GTT);
2579         if (INTEL_GEN(req->i915) >= 8) {
2580                 intel_ring_emit(engine, 0); /* upper addr */
2581                 intel_ring_emit(engine, 0); /* value */
2582         } else  {
2583                 intel_ring_emit(engine, 0);
2584                 intel_ring_emit(engine, MI_NOOP);
2585         }
2586         intel_ring_advance(engine);
2587         return 0;
2588 }
2589
2590 static int
2591 gen8_ring_dispatch_execbuffer(struct drm_i915_gem_request *req,
2592                               u64 offset, u32 len,
2593                               unsigned dispatch_flags)
2594 {
2595         struct intel_engine_cs *engine = req->engine;
2596         bool ppgtt = USES_PPGTT(engine->dev) &&
2597                         !(dispatch_flags & I915_DISPATCH_SECURE);
2598         int ret;
2599
2600         ret = intel_ring_begin(req, 4);
2601         if (ret)
2602                 return ret;
2603
2604         /* FIXME(BDW): Address space and security selectors. */
2605         intel_ring_emit(engine, MI_BATCH_BUFFER_START_GEN8 | (ppgtt<<8) |
2606                         (dispatch_flags & I915_DISPATCH_RS ?
2607                          MI_BATCH_RESOURCE_STREAMER : 0));
2608         intel_ring_emit(engine, lower_32_bits(offset));
2609         intel_ring_emit(engine, upper_32_bits(offset));
2610         intel_ring_emit(engine, MI_NOOP);
2611         intel_ring_advance(engine);
2612
2613         return 0;
2614 }
2615
2616 static int
2617 hsw_ring_dispatch_execbuffer(struct drm_i915_gem_request *req,
2618                              u64 offset, u32 len,
2619                              unsigned dispatch_flags)
2620 {
2621         struct intel_engine_cs *engine = req->engine;
2622         int ret;
2623
2624         ret = intel_ring_begin(req, 2);
2625         if (ret)
2626                 return ret;
2627
2628         intel_ring_emit(engine,
2629                         MI_BATCH_BUFFER_START |
2630                         (dispatch_flags & I915_DISPATCH_SECURE ?
2631                          0 : MI_BATCH_PPGTT_HSW | MI_BATCH_NON_SECURE_HSW) |
2632                         (dispatch_flags & I915_DISPATCH_RS ?
2633                          MI_BATCH_RESOURCE_STREAMER : 0));
2634         /* bit0-7 is the length on GEN6+ */
2635         intel_ring_emit(engine, offset);
2636         intel_ring_advance(engine);
2637
2638         return 0;
2639 }
2640
2641 static int
2642 gen6_ring_dispatch_execbuffer(struct drm_i915_gem_request *req,
2643                               u64 offset, u32 len,
2644                               unsigned dispatch_flags)
2645 {
2646         struct intel_engine_cs *engine = req->engine;
2647         int ret;
2648
2649         ret = intel_ring_begin(req, 2);
2650         if (ret)
2651                 return ret;
2652
2653         intel_ring_emit(engine,
2654                         MI_BATCH_BUFFER_START |
2655                         (dispatch_flags & I915_DISPATCH_SECURE ?
2656                          0 : MI_BATCH_NON_SECURE_I965));
2657         /* bit0-7 is the length on GEN6+ */
2658         intel_ring_emit(engine, offset);
2659         intel_ring_advance(engine);
2660
2661         return 0;
2662 }
2663
2664 /* Blitter support (SandyBridge+) */
2665
2666 static int gen6_ring_flush(struct drm_i915_gem_request *req,
2667                            u32 invalidate, u32 flush)
2668 {
2669         struct intel_engine_cs *engine = req->engine;
2670         uint32_t cmd;
2671         int ret;
2672
2673         ret = intel_ring_begin(req, 4);
2674         if (ret)
2675                 return ret;
2676
2677         cmd = MI_FLUSH_DW;
2678         if (INTEL_GEN(req->i915) >= 8)
2679                 cmd += 1;
2680
2681         /* We always require a command barrier so that subsequent
2682          * commands, such as breadcrumb interrupts, are strictly ordered
2683          * wrt the contents of the write cache being flushed to memory
2684          * (and thus being coherent from the CPU).
2685          */
2686         cmd |= MI_FLUSH_DW_STORE_INDEX | MI_FLUSH_DW_OP_STOREDW;
2687
2688         /*
2689          * Bspec vol 1c.3 - blitter engine command streamer:
2690          * "If ENABLED, all TLBs will be invalidated once the flush
2691          * operation is complete. This bit is only valid when the
2692          * Post-Sync Operation field is a value of 1h or 3h."
2693          */
2694         if (invalidate & I915_GEM_DOMAIN_RENDER)
2695                 cmd |= MI_INVALIDATE_TLB;
2696         intel_ring_emit(engine, cmd);
2697         intel_ring_emit(engine,
2698                         I915_GEM_HWS_SCRATCH_ADDR | MI_FLUSH_DW_USE_GTT);
2699         if (INTEL_GEN(req->i915) >= 8) {
2700                 intel_ring_emit(engine, 0); /* upper addr */
2701                 intel_ring_emit(engine, 0); /* value */
2702         } else  {
2703                 intel_ring_emit(engine, 0);
2704                 intel_ring_emit(engine, MI_NOOP);
2705         }
2706         intel_ring_advance(engine);
2707
2708         return 0;
2709 }
2710
2711 static void intel_ring_init_semaphores(struct drm_i915_private *dev_priv,
2712                                        struct intel_engine_cs *engine)
2713 {
2714         struct drm_i915_gem_object *obj;
2715         int ret, i;
2716
2717         if (!i915_semaphore_is_enabled(dev_priv))
2718                 return;
2719
2720         if (INTEL_GEN(dev_priv) >= 8 && !dev_priv->semaphore_obj) {
2721                 obj = i915_gem_object_create(dev_priv->dev, 4096);
2722                 if (IS_ERR(obj)) {
2723                         DRM_ERROR("Failed to allocate semaphore bo. Disabling semaphores\n");
2724                         i915.semaphores = 0;
2725                 } else {
2726                         i915_gem_object_set_cache_level(obj, I915_CACHE_LLC);
2727                         ret = i915_gem_obj_ggtt_pin(obj, 0, PIN_NONBLOCK);
2728                         if (ret != 0) {
2729                                 drm_gem_object_unreference(&obj->base);
2730                                 DRM_ERROR("Failed to pin semaphore bo. Disabling semaphores\n");
2731                                 i915.semaphores = 0;
2732                         } else {
2733                                 dev_priv->semaphore_obj = obj;
2734                         }
2735                 }
2736         }
2737
2738         if (!i915_semaphore_is_enabled(dev_priv))
2739                 return;
2740
2741         if (INTEL_GEN(dev_priv) >= 8) {
2742                 u64 offset = i915_gem_obj_ggtt_offset(dev_priv->semaphore_obj);
2743
2744                 engine->semaphore.sync_to = gen8_ring_sync;
2745                 engine->semaphore.signal = gen8_xcs_signal;
2746
2747                 for (i = 0; i < I915_NUM_ENGINES; i++) {
2748                         u64 ring_offset;
2749
2750                         if (i != engine->id)
2751                                 ring_offset = offset + GEN8_SEMAPHORE_OFFSET(engine->id, i);
2752                         else
2753                                 ring_offset = MI_SEMAPHORE_SYNC_INVALID;
2754
2755                         engine->semaphore.signal_ggtt[i] = ring_offset;
2756                 }
2757         } else if (INTEL_GEN(dev_priv) >= 6) {
2758                 engine->semaphore.sync_to = gen6_ring_sync;
2759                 engine->semaphore.signal = gen6_signal;
2760
2761                 /*
2762                  * The current semaphore is only applied on pre-gen8
2763                  * platform.  And there is no VCS2 ring on the pre-gen8
2764                  * platform. So the semaphore between RCS and VCS2 is
2765                  * initialized as INVALID.  Gen8 will initialize the
2766                  * sema between VCS2 and RCS later.
2767                  */
2768                 for (i = 0; i < I915_NUM_ENGINES; i++) {
2769                         static const struct {
2770                                 u32 wait_mbox;
2771                                 i915_reg_t mbox_reg;
2772                         } sem_data[I915_NUM_ENGINES][I915_NUM_ENGINES] = {
2773                                 [RCS] = {
2774                                         [VCS] =  { .wait_mbox = MI_SEMAPHORE_SYNC_RV,  .mbox_reg = GEN6_VRSYNC },
2775                                         [BCS] =  { .wait_mbox = MI_SEMAPHORE_SYNC_RB,  .mbox_reg = GEN6_BRSYNC },
2776                                         [VECS] = { .wait_mbox = MI_SEMAPHORE_SYNC_RVE, .mbox_reg = GEN6_VERSYNC },
2777                                 },
2778                                 [VCS] = {
2779                                         [RCS] =  { .wait_mbox = MI_SEMAPHORE_SYNC_VR,  .mbox_reg = GEN6_RVSYNC },
2780                                         [BCS] =  { .wait_mbox = MI_SEMAPHORE_SYNC_VB,  .mbox_reg = GEN6_BVSYNC },
2781                                         [VECS] = { .wait_mbox = MI_SEMAPHORE_SYNC_VVE, .mbox_reg = GEN6_VEVSYNC },
2782                                 },
2783                                 [BCS] = {
2784                                         [RCS] =  { .wait_mbox = MI_SEMAPHORE_SYNC_BR,  .mbox_reg = GEN6_RBSYNC },
2785                                         [VCS] =  { .wait_mbox = MI_SEMAPHORE_SYNC_BV,  .mbox_reg = GEN6_VBSYNC },
2786                                         [VECS] = { .wait_mbox = MI_SEMAPHORE_SYNC_BVE, .mbox_reg = GEN6_VEBSYNC },
2787                                 },
2788                                 [VECS] = {
2789                                         [RCS] =  { .wait_mbox = MI_SEMAPHORE_SYNC_VER, .mbox_reg = GEN6_RVESYNC },
2790                                         [VCS] =  { .wait_mbox = MI_SEMAPHORE_SYNC_VEV, .mbox_reg = GEN6_VVESYNC },
2791                                         [BCS] =  { .wait_mbox = MI_SEMAPHORE_SYNC_VEB, .mbox_reg = GEN6_BVESYNC },
2792                                 },
2793                         };
2794                         u32 wait_mbox;
2795                         i915_reg_t mbox_reg;
2796
2797                         if (i == engine->id || i == VCS2) {
2798                                 wait_mbox = MI_SEMAPHORE_SYNC_INVALID;
2799                                 mbox_reg = GEN6_NOSYNC;
2800                         } else {
2801                                 wait_mbox = sem_data[engine->id][i].wait_mbox;
2802                                 mbox_reg = sem_data[engine->id][i].mbox_reg;
2803                         }
2804
2805                         engine->semaphore.mbox.wait[i] = wait_mbox;
2806                         engine->semaphore.mbox.signal[i] = mbox_reg;
2807                 }
2808         }
2809 }
2810
2811 static void intel_ring_init_irq(struct drm_i915_private *dev_priv,
2812                                 struct intel_engine_cs *engine)
2813 {
2814         if (INTEL_GEN(dev_priv) >= 8) {
2815                 engine->irq_enable = gen8_irq_enable;
2816                 engine->irq_disable = gen8_irq_disable;
2817                 engine->irq_seqno_barrier = gen6_seqno_barrier;
2818         } else if (INTEL_GEN(dev_priv) >= 6) {
2819                 engine->irq_enable = gen6_irq_enable;
2820                 engine->irq_disable = gen6_irq_disable;
2821                 engine->irq_seqno_barrier = gen6_seqno_barrier;
2822         } else if (INTEL_GEN(dev_priv) >= 5) {
2823                 engine->irq_enable = gen5_irq_enable;
2824                 engine->irq_disable = gen5_irq_disable;
2825                 engine->irq_seqno_barrier = gen5_seqno_barrier;
2826         } else if (INTEL_GEN(dev_priv) >= 3) {
2827                 engine->irq_enable = i9xx_irq_enable;
2828                 engine->irq_disable = i9xx_irq_disable;
2829         } else {
2830                 engine->irq_enable = i8xx_irq_enable;
2831                 engine->irq_disable = i8xx_irq_disable;
2832         }
2833 }
2834
2835 static void intel_ring_default_vfuncs(struct drm_i915_private *dev_priv,
2836                                       struct intel_engine_cs *engine)
2837 {
2838         engine->init_hw = init_ring_common;
2839         engine->write_tail = ring_write_tail;
2840
2841         engine->add_request = i9xx_add_request;
2842         if (INTEL_GEN(dev_priv) >= 6)
2843                 engine->add_request = gen6_add_request;
2844
2845         if (INTEL_GEN(dev_priv) >= 8)
2846                 engine->dispatch_execbuffer = gen8_ring_dispatch_execbuffer;
2847         else if (INTEL_GEN(dev_priv) >= 6)
2848                 engine->dispatch_execbuffer = gen6_ring_dispatch_execbuffer;
2849         else if (INTEL_GEN(dev_priv) >= 4)
2850                 engine->dispatch_execbuffer = i965_dispatch_execbuffer;
2851         else if (IS_I830(dev_priv) || IS_845G(dev_priv))
2852                 engine->dispatch_execbuffer = i830_dispatch_execbuffer;
2853         else
2854                 engine->dispatch_execbuffer = i915_dispatch_execbuffer;
2855
2856         intel_ring_init_irq(dev_priv, engine);
2857         intel_ring_init_semaphores(dev_priv, engine);
2858 }
2859
2860 int intel_init_render_ring_buffer(struct drm_device *dev)
2861 {
2862         struct drm_i915_private *dev_priv = dev->dev_private;
2863         struct intel_engine_cs *engine = &dev_priv->engine[RCS];
2864         int ret;
2865
2866         engine->name = "render ring";
2867         engine->id = RCS;
2868         engine->exec_id = I915_EXEC_RENDER;
2869         engine->hw_id = 0;
2870         engine->mmio_base = RENDER_RING_BASE;
2871
2872         intel_ring_default_vfuncs(dev_priv, engine);
2873
2874         engine->irq_enable_mask = GT_RENDER_USER_INTERRUPT;
2875
2876         if (INTEL_GEN(dev_priv) >= 8) {
2877                 engine->init_context = intel_rcs_ctx_init;
2878                 engine->add_request = gen8_render_add_request;
2879                 engine->flush = gen8_render_ring_flush;
2880                 if (i915_semaphore_is_enabled(dev_priv))
2881                         engine->semaphore.signal = gen8_rcs_signal;
2882         } else if (INTEL_GEN(dev_priv) >= 6) {
2883                 engine->init_context = intel_rcs_ctx_init;
2884                 engine->flush = gen7_render_ring_flush;
2885                 if (IS_GEN6(dev_priv))
2886                         engine->flush = gen6_render_ring_flush;
2887         } else if (IS_GEN5(dev_priv)) {
2888                 engine->flush = gen4_render_ring_flush;
2889         } else {
2890                 if (INTEL_GEN(dev_priv) < 4)
2891                         engine->flush = gen2_render_ring_flush;
2892                 else
2893                         engine->flush = gen4_render_ring_flush;
2894                 engine->irq_enable_mask = I915_USER_INTERRUPT;
2895         }
2896
2897         if (IS_HASWELL(dev_priv))
2898                 engine->dispatch_execbuffer = hsw_ring_dispatch_execbuffer;
2899
2900         engine->init_hw = init_render_ring;
2901         engine->cleanup = render_ring_cleanup;
2902
2903         ret = intel_init_ring_buffer(dev, engine);
2904         if (ret)
2905                 return ret;
2906
2907         if (INTEL_GEN(dev_priv) >= 6) {
2908                 ret = intel_init_pipe_control(engine, 4096);
2909                 if (ret)
2910                         return ret;
2911         } else if (HAS_BROKEN_CS_TLB(dev_priv)) {
2912                 ret = intel_init_pipe_control(engine, I830_WA_SIZE);
2913                 if (ret)
2914                         return ret;
2915         }
2916
2917         return 0;
2918 }
2919
2920 int intel_init_bsd_ring_buffer(struct drm_device *dev)
2921 {
2922         struct drm_i915_private *dev_priv = dev->dev_private;
2923         struct intel_engine_cs *engine = &dev_priv->engine[VCS];
2924
2925         engine->name = "bsd ring";
2926         engine->id = VCS;
2927         engine->exec_id = I915_EXEC_BSD;
2928         engine->hw_id = 1;
2929
2930         intel_ring_default_vfuncs(dev_priv, engine);
2931
2932         if (INTEL_GEN(dev_priv) >= 6) {
2933                 engine->mmio_base = GEN6_BSD_RING_BASE;
2934                 /* gen6 bsd needs a special wa for tail updates */
2935                 if (IS_GEN6(dev_priv))
2936                         engine->write_tail = gen6_bsd_ring_write_tail;
2937                 engine->flush = gen6_bsd_ring_flush;
2938                 if (INTEL_GEN(dev_priv) >= 8)
2939                         engine->irq_enable_mask =
2940                                 GT_RENDER_USER_INTERRUPT << GEN8_VCS1_IRQ_SHIFT;
2941                 else
2942                         engine->irq_enable_mask = GT_BSD_USER_INTERRUPT;
2943         } else {
2944                 engine->mmio_base = BSD_RING_BASE;
2945                 engine->flush = bsd_ring_flush;
2946                 if (IS_GEN5(dev_priv))
2947                         engine->irq_enable_mask = ILK_BSD_USER_INTERRUPT;
2948                 else
2949                         engine->irq_enable_mask = I915_BSD_USER_INTERRUPT;
2950         }
2951
2952         return intel_init_ring_buffer(dev, engine);
2953 }
2954
2955 /**
2956  * Initialize the second BSD ring (eg. Broadwell GT3, Skylake GT3)
2957  */
2958 int intel_init_bsd2_ring_buffer(struct drm_device *dev)
2959 {
2960         struct drm_i915_private *dev_priv = dev->dev_private;
2961         struct intel_engine_cs *engine = &dev_priv->engine[VCS2];
2962
2963         engine->name = "bsd2 ring";
2964         engine->id = VCS2;
2965         engine->exec_id = I915_EXEC_BSD;
2966         engine->hw_id = 4;
2967         engine->mmio_base = GEN8_BSD2_RING_BASE;
2968
2969         intel_ring_default_vfuncs(dev_priv, engine);
2970
2971         engine->flush = gen6_bsd_ring_flush;
2972         engine->irq_enable_mask =
2973                         GT_RENDER_USER_INTERRUPT << GEN8_VCS2_IRQ_SHIFT;
2974
2975         return intel_init_ring_buffer(dev, engine);
2976 }
2977
2978 int intel_init_blt_ring_buffer(struct drm_device *dev)
2979 {
2980         struct drm_i915_private *dev_priv = dev->dev_private;
2981         struct intel_engine_cs *engine = &dev_priv->engine[BCS];
2982
2983         engine->name = "blitter ring";
2984         engine->id = BCS;
2985         engine->exec_id = I915_EXEC_BLT;
2986         engine->hw_id = 2;
2987         engine->mmio_base = BLT_RING_BASE;
2988
2989         intel_ring_default_vfuncs(dev_priv, engine);
2990
2991         engine->flush = gen6_ring_flush;
2992         if (INTEL_GEN(dev_priv) >= 8)
2993                 engine->irq_enable_mask =
2994                         GT_RENDER_USER_INTERRUPT << GEN8_BCS_IRQ_SHIFT;
2995         else
2996                 engine->irq_enable_mask = GT_BLT_USER_INTERRUPT;
2997
2998         return intel_init_ring_buffer(dev, engine);
2999 }
3000
3001 int intel_init_vebox_ring_buffer(struct drm_device *dev)
3002 {
3003         struct drm_i915_private *dev_priv = dev->dev_private;
3004         struct intel_engine_cs *engine = &dev_priv->engine[VECS];
3005
3006         engine->name = "video enhancement ring";
3007         engine->id = VECS;
3008         engine->exec_id = I915_EXEC_VEBOX;
3009         engine->hw_id = 3;
3010         engine->mmio_base = VEBOX_RING_BASE;
3011
3012         intel_ring_default_vfuncs(dev_priv, engine);
3013
3014         engine->flush = gen6_ring_flush;
3015
3016         if (INTEL_GEN(dev_priv) >= 8) {
3017                 engine->irq_enable_mask =
3018                         GT_RENDER_USER_INTERRUPT << GEN8_VECS_IRQ_SHIFT;
3019         } else {
3020                 engine->irq_enable_mask = PM_VEBOX_USER_INTERRUPT;
3021                 engine->irq_enable = hsw_vebox_irq_enable;
3022                 engine->irq_disable = hsw_vebox_irq_disable;
3023         }
3024
3025         return intel_init_ring_buffer(dev, engine);
3026 }
3027
3028 int
3029 intel_ring_flush_all_caches(struct drm_i915_gem_request *req)
3030 {
3031         struct intel_engine_cs *engine = req->engine;
3032         int ret;
3033
3034         if (!engine->gpu_caches_dirty)
3035                 return 0;
3036
3037         ret = engine->flush(req, 0, I915_GEM_GPU_DOMAINS);
3038         if (ret)
3039                 return ret;
3040
3041         trace_i915_gem_ring_flush(req, 0, I915_GEM_GPU_DOMAINS);
3042
3043         engine->gpu_caches_dirty = false;
3044         return 0;
3045 }
3046
3047 int
3048 intel_ring_invalidate_all_caches(struct drm_i915_gem_request *req)
3049 {
3050         struct intel_engine_cs *engine = req->engine;
3051         uint32_t flush_domains;
3052         int ret;
3053
3054         flush_domains = 0;
3055         if (engine->gpu_caches_dirty)
3056                 flush_domains = I915_GEM_GPU_DOMAINS;
3057
3058         ret = engine->flush(req, I915_GEM_GPU_DOMAINS, flush_domains);
3059         if (ret)
3060                 return ret;
3061
3062         trace_i915_gem_ring_flush(req, I915_GEM_GPU_DOMAINS, flush_domains);
3063
3064         engine->gpu_caches_dirty = false;
3065         return 0;
3066 }
3067
3068 void
3069 intel_stop_engine(struct intel_engine_cs *engine)
3070 {
3071         int ret;
3072
3073         if (!intel_engine_initialized(engine))
3074                 return;
3075
3076         ret = intel_engine_idle(engine);
3077         if (ret)
3078                 DRM_ERROR("failed to quiesce %s whilst cleaning up: %d\n",
3079                           engine->name, ret);
3080
3081         stop_ring(engine);
3082 }