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