OSDN Git Service

i965: Allocate shadow batches to explicitly be the BO size.
[android-x86/external-mesa.git] / src / mesa / drivers / dri / i965 / intel_batchbuffer.c
1 /*
2  * Copyright 2006 VMware, Inc.
3  * All Rights Reserved.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the
7  * "Software"), to deal in the Software without restriction, including
8  * without limitation the rights to use, copy, modify, merge, publish,
9  * distribute, sublicense, and/or sell copies of the Software, and to
10  * permit persons to whom the Software is furnished to do so, subject to
11  * the following conditions:
12  *
13  * The above copyright notice and this permission notice (including the
14  * next paragraph) shall be included in all copies or substantial portions
15  * of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
20  * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR
21  * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
22  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
23  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24  */
25
26 #include "intel_batchbuffer.h"
27 #include "intel_buffer_objects.h"
28 #include "brw_bufmgr.h"
29 #include "intel_buffers.h"
30 #include "intel_fbo.h"
31 #include "brw_context.h"
32 #include "brw_defines.h"
33 #include "brw_state.h"
34 #include "common/gen_decoder.h"
35
36 #include "util/hash_table.h"
37
38 #include <xf86drm.h>
39 #include <i915_drm.h>
40
41 #define FILE_DEBUG_FLAG DEBUG_BUFMGR
42
43 /**
44  * Target sizes of the batch and state buffers.  We create the initial
45  * buffers at these sizes, and flush when they're nearly full.  If we
46  * underestimate how close we are to the end, and suddenly need more space
47  * in the middle of a draw, we can grow the buffers, and finish the draw.
48  * At that point, we'll be over our target size, so the next operation
49  * should flush.  Each time we flush the batch, we recreate both buffers
50  * at the original target size, so it doesn't grow without bound.
51  */
52 #define BATCH_SZ (20 * 1024)
53 #define STATE_SZ (16 * 1024)
54
55 static void
56 intel_batchbuffer_reset(struct brw_context *brw);
57
58 UNUSED static void
59 dump_validation_list(struct intel_batchbuffer *batch)
60 {
61    fprintf(stderr, "Validation list (length %d):\n", batch->exec_count);
62
63    for (int i = 0; i < batch->exec_count; i++) {
64       uint64_t flags = batch->validation_list[i].flags;
65       assert(batch->validation_list[i].handle ==
66              batch->exec_bos[i]->gem_handle);
67       fprintf(stderr, "[%2d]: %2d %-14s %p %s%-7s @ 0x%016llx%s (%"PRIu64"B)\n",
68               i,
69               batch->validation_list[i].handle,
70               batch->exec_bos[i]->name,
71               batch->exec_bos[i],
72               (flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS) ? "(48b" : "(32b",
73               (flags & EXEC_OBJECT_WRITE) ? " write)" : ")",
74               batch->validation_list[i].offset,
75               (flags & EXEC_OBJECT_PINNED) ? " (pinned)" : "",
76               batch->exec_bos[i]->size);
77    }
78 }
79
80 static bool
81 uint_key_compare(const void *a, const void *b)
82 {
83    return a == b;
84 }
85
86 static uint32_t
87 uint_key_hash(const void *key)
88 {
89    return (uintptr_t) key;
90 }
91
92 static void
93 init_reloc_list(struct brw_reloc_list *rlist, int count)
94 {
95    rlist->reloc_count = 0;
96    rlist->reloc_array_size = count;
97    rlist->relocs = malloc(rlist->reloc_array_size *
98                           sizeof(struct drm_i915_gem_relocation_entry));
99 }
100
101 void
102 intel_batchbuffer_init(struct brw_context *brw)
103 {
104    struct intel_screen *screen = brw->screen;
105    struct intel_batchbuffer *batch = &brw->batch;
106    const struct gen_device_info *devinfo = &screen->devinfo;
107
108    batch->use_shadow_copy = !devinfo->has_llc;
109
110    init_reloc_list(&batch->batch_relocs, 250);
111    init_reloc_list(&batch->state_relocs, 250);
112
113    batch->batch.map = NULL;
114    batch->state.map = NULL;
115    batch->exec_count = 0;
116    batch->exec_array_size = 100;
117    batch->exec_bos =
118       malloc(batch->exec_array_size * sizeof(batch->exec_bos[0]));
119    batch->validation_list =
120       malloc(batch->exec_array_size * sizeof(batch->validation_list[0]));
121
122    if (INTEL_DEBUG & DEBUG_BATCH) {
123       batch->state_batch_sizes =
124          _mesa_hash_table_create(NULL, uint_key_hash, uint_key_compare);
125    }
126
127    batch->use_batch_first =
128       screen->kernel_features & KERNEL_ALLOWS_EXEC_BATCH_FIRST;
129
130    /* PIPE_CONTROL needs a w/a but only on gen6 */
131    batch->valid_reloc_flags = EXEC_OBJECT_WRITE;
132    if (devinfo->gen == 6)
133       batch->valid_reloc_flags |= EXEC_OBJECT_NEEDS_GTT;
134
135    intel_batchbuffer_reset(brw);
136 }
137
138 #define READ_ONCE(x) (*(volatile __typeof__(x) *)&(x))
139
140 static unsigned
141 add_exec_bo(struct intel_batchbuffer *batch, struct brw_bo *bo)
142 {
143    unsigned index = READ_ONCE(bo->index);
144
145    if (index < batch->exec_count && batch->exec_bos[index] == bo)
146       return index;
147
148    /* May have been shared between multiple active batches */
149    for (index = 0; index < batch->exec_count; index++) {
150       if (batch->exec_bos[index] == bo)
151          return index;
152    }
153
154    brw_bo_reference(bo);
155
156    if (batch->exec_count == batch->exec_array_size) {
157       batch->exec_array_size *= 2;
158       batch->exec_bos =
159          realloc(batch->exec_bos,
160                  batch->exec_array_size * sizeof(batch->exec_bos[0]));
161       batch->validation_list =
162          realloc(batch->validation_list,
163                  batch->exec_array_size * sizeof(batch->validation_list[0]));
164    }
165
166    batch->validation_list[batch->exec_count] =
167       (struct drm_i915_gem_exec_object2) {
168          .handle = bo->gem_handle,
169          .offset = bo->gtt_offset,
170          .flags = bo->kflags,
171       };
172
173    bo->index = batch->exec_count;
174    batch->exec_bos[batch->exec_count] = bo;
175    batch->aperture_space += bo->size;
176
177    return batch->exec_count++;
178 }
179
180 static void
181 recreate_growing_buffer(struct brw_context *brw,
182                         struct brw_growing_bo *grow,
183                         const char *name, unsigned size)
184 {
185    struct intel_screen *screen = brw->screen;
186    struct intel_batchbuffer *batch = &brw->batch;
187    struct brw_bufmgr *bufmgr = screen->bufmgr;
188
189    grow->bo = brw_bo_alloc(bufmgr, name, size);
190    grow->bo->kflags |= can_do_exec_capture(screen) ? EXEC_OBJECT_CAPTURE : 0;
191    grow->partial_bo = NULL;
192    grow->partial_bo_map = NULL;
193    grow->partial_bytes = 0;
194
195    if (batch->use_shadow_copy)
196       grow->map = realloc(grow->map, grow->bo->size);
197    else
198       grow->map = brw_bo_map(brw, grow->bo, MAP_READ | MAP_WRITE);
199 }
200
201 static void
202 intel_batchbuffer_reset(struct brw_context *brw)
203 {
204    struct intel_batchbuffer *batch = &brw->batch;
205
206    if (batch->last_bo != NULL) {
207       brw_bo_unreference(batch->last_bo);
208       batch->last_bo = NULL;
209    }
210    batch->last_bo = batch->batch.bo;
211
212    recreate_growing_buffer(brw, &batch->batch, "batchbuffer", BATCH_SZ);
213    batch->map_next = batch->batch.map;
214
215    recreate_growing_buffer(brw, &batch->state, "statebuffer", STATE_SZ);
216
217    /* Avoid making 0 a valid state offset - otherwise the decoder will try
218     * and decode data when we use offset 0 as a null pointer.
219     */
220    batch->state_used = 1;
221
222    add_exec_bo(batch, batch->batch.bo);
223    assert(batch->batch.bo->index == 0);
224
225    batch->needs_sol_reset = false;
226    batch->state_base_address_emitted = false;
227
228    /* We don't know what ring the new batch will be sent to until we see the
229     * first BEGIN_BATCH or BEGIN_BATCH_BLT.  Mark it as unknown.
230     */
231    batch->ring = UNKNOWN_RING;
232
233    if (batch->state_batch_sizes)
234       _mesa_hash_table_clear(batch->state_batch_sizes, NULL);
235 }
236
237 static void
238 intel_batchbuffer_reset_and_clear_render_cache(struct brw_context *brw)
239 {
240    intel_batchbuffer_reset(brw);
241    brw_cache_sets_clear(brw);
242 }
243
244 void
245 intel_batchbuffer_save_state(struct brw_context *brw)
246 {
247    brw->batch.saved.map_next = brw->batch.map_next;
248    brw->batch.saved.batch_reloc_count = brw->batch.batch_relocs.reloc_count;
249    brw->batch.saved.state_reloc_count = brw->batch.state_relocs.reloc_count;
250    brw->batch.saved.exec_count = brw->batch.exec_count;
251 }
252
253 void
254 intel_batchbuffer_reset_to_saved(struct brw_context *brw)
255 {
256    for (int i = brw->batch.saved.exec_count;
257         i < brw->batch.exec_count; i++) {
258       brw_bo_unreference(brw->batch.exec_bos[i]);
259    }
260    brw->batch.batch_relocs.reloc_count = brw->batch.saved.batch_reloc_count;
261    brw->batch.state_relocs.reloc_count = brw->batch.saved.state_reloc_count;
262    brw->batch.exec_count = brw->batch.saved.exec_count;
263
264    brw->batch.map_next = brw->batch.saved.map_next;
265    if (USED_BATCH(brw->batch) == 0)
266       brw->batch.ring = UNKNOWN_RING;
267 }
268
269 void
270 intel_batchbuffer_free(struct intel_batchbuffer *batch)
271 {
272    if (batch->use_shadow_copy) {
273       free(batch->batch.map);
274       free(batch->state.map);
275    }
276
277    for (int i = 0; i < batch->exec_count; i++) {
278       brw_bo_unreference(batch->exec_bos[i]);
279    }
280    free(batch->batch_relocs.relocs);
281    free(batch->state_relocs.relocs);
282    free(batch->exec_bos);
283    free(batch->validation_list);
284
285    brw_bo_unreference(batch->last_bo);
286    brw_bo_unreference(batch->batch.bo);
287    brw_bo_unreference(batch->state.bo);
288    if (batch->state_batch_sizes)
289       _mesa_hash_table_destroy(batch->state_batch_sizes, NULL);
290 }
291
292 /**
293  * Finish copying the old batch/state buffer's contents to the new one
294  * after we tried to "grow" the buffer in an earlier operation.
295  */
296 static void
297 finish_growing_bos(struct brw_growing_bo *grow)
298 {
299    struct brw_bo *old_bo = grow->partial_bo;
300    if (!old_bo)
301       return;
302
303    memcpy(grow->map, grow->partial_bo_map, grow->partial_bytes);
304
305    grow->partial_bo = NULL;
306    grow->partial_bo_map = NULL;
307    grow->partial_bytes = 0;
308
309    brw_bo_unreference(old_bo);
310 }
311
312 static void
313 replace_bo_in_reloc_list(struct brw_reloc_list *rlist,
314                          uint32_t old_handle, uint32_t new_handle)
315 {
316    for (int i = 0; i < rlist->reloc_count; i++) {
317       if (rlist->relocs[i].target_handle == old_handle)
318          rlist->relocs[i].target_handle = new_handle;
319    }
320 }
321
322 /**
323  * Grow either the batch or state buffer to a new larger size.
324  *
325  * We can't actually grow buffers, so we allocate a new one, copy over
326  * the existing contents, and update our lists to refer to the new one.
327  *
328  * Note that this is only temporary - each new batch recreates the buffers
329  * at their original target size (BATCH_SZ or STATE_SZ).
330  */
331 static void
332 grow_buffer(struct brw_context *brw,
333             struct brw_growing_bo *grow,
334             unsigned existing_bytes,
335             unsigned new_size)
336 {
337    struct intel_batchbuffer *batch = &brw->batch;
338    struct brw_bufmgr *bufmgr = brw->bufmgr;
339    struct brw_bo *bo = grow->bo;
340
341    perf_debug("Growing %s - ran out of space\n", bo->name);
342
343    if (grow->partial_bo) {
344       /* We've already grown once, and now we need to do it again.
345        * Finish our last grow operation so we can start a new one.
346        * This should basically never happen.
347        */
348       perf_debug("Had to grow multiple times");
349       finish_growing_bos(grow);
350    }
351
352    struct brw_bo *new_bo = brw_bo_alloc(bufmgr, bo->name, new_size);
353
354    /* Copy existing data to the new larger buffer */
355    grow->partial_bo_map = grow->map;
356
357    if (batch->use_shadow_copy) {
358       /* We can't safely use realloc, as it may move the existing buffer,
359        * breaking existing pointers the caller may still be using.  Just
360        * malloc a new copy and memcpy it like the normal BO path.
361        *
362        * Use bo->size rather than new_size because the bufmgr may have
363        * rounded up the size, and we want the shadow size to match.
364        */
365       grow->map = malloc(new_bo->size);
366    } else {
367       grow->map = brw_bo_map(brw, new_bo, MAP_READ | MAP_WRITE);
368    }
369
370    /* Try to put the new BO at the same GTT offset as the old BO (which
371     * we're throwing away, so it doesn't need to be there).
372     *
373     * This guarantees that our relocations continue to work: values we've
374     * already written into the buffer, values we're going to write into the
375     * buffer, and the validation/relocation lists all will match.
376     *
377     * Also preserve kflags for EXEC_OBJECT_CAPTURE.
378     */
379    new_bo->gtt_offset = bo->gtt_offset;
380    new_bo->index = bo->index;
381    new_bo->kflags = bo->kflags;
382
383    /* Batch/state buffers are per-context, and if we've run out of space,
384     * we must have actually used them before, so...they will be in the list.
385     */
386    assert(bo->index < batch->exec_count);
387    assert(batch->exec_bos[bo->index] == bo);
388
389    /* Update the validation list to use the new BO. */
390    batch->validation_list[bo->index].handle = new_bo->gem_handle;
391
392    if (!batch->use_batch_first) {
393       /* We're not using I915_EXEC_HANDLE_LUT, which means we need to go
394        * update the relocation list entries to point at the new BO as well.
395        * (With newer kernels, the "handle" is an offset into the validation
396        * list, which remains unchanged, so we can skip this.)
397        */
398       replace_bo_in_reloc_list(&batch->batch_relocs,
399                                bo->gem_handle, new_bo->gem_handle);
400       replace_bo_in_reloc_list(&batch->state_relocs,
401                                bo->gem_handle, new_bo->gem_handle);
402    }
403
404    /* Exchange the two BOs...without breaking pointers to the old BO.
405     *
406     * Consider this scenario:
407     *
408     * 1. Somebody calls brw_state_batch() to get a region of memory, and
409     *    and then creates a brw_address pointing to brw->batch.state.bo.
410     * 2. They then call brw_state_batch() a second time, which happens to
411     *    grow and replace the state buffer.  They then try to emit a
412     *    relocation to their first section of memory.
413     *
414     * If we replace the brw->batch.state.bo pointer at step 2, we would
415     * break the address created in step 1.  They'd have a pointer to the
416     * old destroyed BO.  Emitting a relocation would add this dead BO to
417     * the validation list...causing /both/ statebuffers to be in the list,
418     * and all kinds of disasters.
419     *
420     * This is not a contrived case - BLORP vertex data upload hits this.
421     *
422     * There are worse scenarios too.  Fences for GL sync objects reference
423     * brw->batch.batch.bo.  If we replaced the batch pointer when growing,
424     * we'd need to chase down every fence and update it to point to the
425     * new BO.  Otherwise, it would refer to a "batch" that never actually
426     * gets submitted, and would fail to trigger.
427     *
428     * To work around both of these issues, we transmutate the buffers in
429     * place, making the existing struct brw_bo represent the new buffer,
430     * and "new_bo" represent the old BO.  This is highly unusual, but it
431     * seems like a necessary evil.
432     *
433     * We also defer the memcpy of the existing batch's contents.  Callers
434     * may make multiple brw_state_batch calls, and retain pointers to the
435     * old BO's map.  We'll perform the memcpy in finish_growing_bo() when
436     * we finally submit the batch, at which point we've finished uploading
437     * state, and nobody should have any old references anymore.
438     *
439     * To do that, we keep a reference to the old BO in grow->partial_bo,
440     * and store the number of bytes to copy in grow->partial_bytes.  We
441     * can monkey with the refcounts directly without atomics because these
442     * are per-context BOs and they can only be touched by this thread.
443     */
444    assert(new_bo->refcount == 1);
445    new_bo->refcount = bo->refcount;
446    bo->refcount = 1;
447
448    struct brw_bo tmp;
449    memcpy(&tmp, bo, sizeof(struct brw_bo));
450    memcpy(bo, new_bo, sizeof(struct brw_bo));
451    memcpy(new_bo, &tmp, sizeof(struct brw_bo));
452
453    grow->partial_bo = new_bo; /* the one reference of the OLD bo */
454    grow->partial_bytes = existing_bytes;
455 }
456
457 void
458 intel_batchbuffer_require_space(struct brw_context *brw, GLuint sz,
459                                 enum brw_gpu_ring ring)
460 {
461    const struct gen_device_info *devinfo = &brw->screen->devinfo;
462    struct intel_batchbuffer *batch = &brw->batch;
463
464    /* If we're switching rings, implicitly flush the batch. */
465    if (unlikely(ring != brw->batch.ring) && brw->batch.ring != UNKNOWN_RING &&
466        devinfo->gen >= 6) {
467       intel_batchbuffer_flush(brw);
468    }
469
470    const unsigned batch_used = USED_BATCH(*batch) * 4;
471    if (batch_used + sz >= BATCH_SZ && !batch->no_wrap) {
472       intel_batchbuffer_flush(brw);
473    } else if (batch_used + sz >= batch->batch.bo->size) {
474       const unsigned new_size =
475          MIN2(batch->batch.bo->size + batch->batch.bo->size / 2,
476               MAX_BATCH_SIZE);
477       grow_buffer(brw, &batch->batch, batch_used, new_size);
478       batch->map_next = (void *) batch->batch.map + batch_used;
479       assert(batch_used + sz < batch->batch.bo->size);
480    }
481
482    /* The intel_batchbuffer_flush() calls above might have changed
483     * brw->batch.ring to UNKNOWN_RING, so we need to set it here at the end.
484     */
485    brw->batch.ring = ring;
486 }
487
488 #ifdef DEBUG
489 #define CSI "\e["
490 #define BLUE_HEADER  CSI "0;44m"
491 #define NORMAL       CSI "0m"
492
493
494 static void
495 decode_struct(struct brw_context *brw, struct gen_spec *spec,
496               const char *struct_name, uint32_t *data,
497               uint32_t gtt_offset, uint32_t offset, bool color)
498 {
499    struct gen_group *group = gen_spec_find_struct(spec, struct_name);
500    if (!group)
501       return;
502
503    fprintf(stderr, "%s\n", struct_name);
504    gen_print_group(stderr, group, gtt_offset + offset,
505                    &data[offset / 4], 0, color);
506 }
507
508 static void
509 decode_structs(struct brw_context *brw, struct gen_spec *spec,
510                const char *struct_name,
511                uint32_t *data, uint32_t gtt_offset, uint32_t offset,
512                int struct_size, bool color)
513 {
514    struct gen_group *group = gen_spec_find_struct(spec, struct_name);
515    if (!group)
516       return;
517
518    int entries = brw_state_batch_size(brw, offset) / struct_size;
519    for (int i = 0; i < entries; i++) {
520       fprintf(stderr, "%s %d\n", struct_name, i);
521       gen_print_group(stderr, group, gtt_offset + offset,
522                       &data[(offset + i * struct_size) / 4], 0, color);
523    }
524 }
525
526 static void
527 do_batch_dump(struct brw_context *brw)
528 {
529    const struct gen_device_info *devinfo = &brw->screen->devinfo;
530    struct intel_batchbuffer *batch = &brw->batch;
531    struct gen_spec *spec = gen_spec_load(&brw->screen->devinfo);
532
533    if (batch->ring != RENDER_RING)
534       return;
535
536    uint32_t *batch_data = brw_bo_map(brw, batch->batch.bo, MAP_READ);
537    uint32_t *state = brw_bo_map(brw, batch->state.bo, MAP_READ);
538    if (batch_data == NULL || state == NULL) {
539       fprintf(stderr, "WARNING: failed to map batchbuffer/statebuffer\n");
540       return;
541    }
542
543    uint32_t *end = batch_data + USED_BATCH(*batch);
544    uint32_t batch_gtt_offset = batch->batch.bo->gtt_offset;
545    uint32_t state_gtt_offset = batch->state.bo->gtt_offset;
546    int length;
547
548    bool color = INTEL_DEBUG & DEBUG_COLOR;
549    const char *header_color = color ? BLUE_HEADER : "";
550    const char *reset_color  = color ? NORMAL : "";
551
552    for (uint32_t *p = batch_data; p < end; p += length) {
553       struct gen_group *inst = gen_spec_find_instruction(spec, p);
554       length = gen_group_get_length(inst, p);
555       assert(inst == NULL || length > 0);
556       length = MAX2(1, length);
557       if (inst == NULL) {
558          fprintf(stderr, "unknown instruction %08x\n", p[0]);
559          continue;
560       }
561
562       uint64_t offset = batch_gtt_offset + 4 * (p - batch_data);
563
564       fprintf(stderr, "%s0x%08"PRIx64":  0x%08x:  %-80s%s\n", header_color,
565               offset, p[0], gen_group_get_name(inst), reset_color);
566
567       gen_print_group(stderr, inst, offset, p, 0, color);
568
569       switch (gen_group_get_opcode(inst) >> 16) {
570       case _3DSTATE_PIPELINED_POINTERS:
571          /* Note: these Gen4-5 pointers are full relocations rather than
572           * offsets from the start of the statebuffer.  So we need to subtract
573           * gtt_offset (the start of the statebuffer) to obtain an offset we
574           * can add to the map and get at the data.
575           */
576          decode_struct(brw, spec, "VS_STATE", state, state_gtt_offset,
577                        (p[1] & ~0x1fu) - state_gtt_offset, color);
578          if (p[2] & 1) {
579             decode_struct(brw, spec, "GS_STATE", state, state_gtt_offset,
580                           (p[2] & ~0x1fu) - state_gtt_offset, color);
581          }
582          if (p[3] & 1) {
583             decode_struct(brw, spec, "CLIP_STATE", state, state_gtt_offset,
584                           (p[3] & ~0x1fu) - state_gtt_offset, color);
585          }
586          decode_struct(brw, spec, "SF_STATE", state, state_gtt_offset,
587                        (p[4] & ~0x1fu) - state_gtt_offset, color);
588          decode_struct(brw, spec, "WM_STATE", state, state_gtt_offset,
589                        (p[5] & ~0x1fu) - state_gtt_offset, color);
590          decode_struct(brw, spec, "COLOR_CALC_STATE", state, state_gtt_offset,
591                        (p[6] & ~0x3fu) - state_gtt_offset, color);
592          break;
593       case _3DSTATE_BINDING_TABLE_POINTERS_VS:
594       case _3DSTATE_BINDING_TABLE_POINTERS_HS:
595       case _3DSTATE_BINDING_TABLE_POINTERS_DS:
596       case _3DSTATE_BINDING_TABLE_POINTERS_GS:
597       case _3DSTATE_BINDING_TABLE_POINTERS_PS: {
598          struct gen_group *group =
599             gen_spec_find_struct(spec, "RENDER_SURFACE_STATE");
600          if (!group)
601             break;
602
603          uint32_t bt_offset = p[1] & ~0x1fu;
604          int bt_entries = brw_state_batch_size(brw, bt_offset) / 4;
605          uint32_t *bt_pointers = &state[bt_offset / 4];
606          for (int i = 0; i < bt_entries; i++) {
607             fprintf(stderr, "SURFACE_STATE - BTI = %d\n", i);
608             gen_print_group(stderr, group, state_gtt_offset + bt_pointers[i],
609                             &state[bt_pointers[i] / 4], 0, color);
610          }
611          break;
612       }
613       case _3DSTATE_SAMPLER_STATE_POINTERS_VS:
614       case _3DSTATE_SAMPLER_STATE_POINTERS_HS:
615       case _3DSTATE_SAMPLER_STATE_POINTERS_DS:
616       case _3DSTATE_SAMPLER_STATE_POINTERS_GS:
617       case _3DSTATE_SAMPLER_STATE_POINTERS_PS:
618          decode_structs(brw, spec, "SAMPLER_STATE", state,
619                         state_gtt_offset, p[1] & ~0x1fu, 4 * 4, color);
620          break;
621       case _3DSTATE_VIEWPORT_STATE_POINTERS:
622          decode_structs(brw, spec, "CLIP_VIEWPORT", state,
623                         state_gtt_offset, p[1] & ~0x3fu, 4 * 4, color);
624          decode_structs(brw, spec, "SF_VIEWPORT", state,
625                         state_gtt_offset, p[1] & ~0x3fu, 8 * 4, color);
626          decode_structs(brw, spec, "CC_VIEWPORT", state,
627                         state_gtt_offset, p[3] & ~0x3fu, 2 * 4, color);
628          break;
629       case _3DSTATE_VIEWPORT_STATE_POINTERS_CC:
630          decode_structs(brw, spec, "CC_VIEWPORT", state,
631                         state_gtt_offset, p[1] & ~0x3fu, 2 * 4, color);
632          break;
633       case _3DSTATE_VIEWPORT_STATE_POINTERS_SF_CL:
634          decode_structs(brw, spec, "SF_CLIP_VIEWPORT", state,
635                         state_gtt_offset, p[1] & ~0x3fu, 16 * 4, color);
636          break;
637       case _3DSTATE_SCISSOR_STATE_POINTERS:
638          decode_structs(brw, spec, "SCISSOR_RECT", state,
639                         state_gtt_offset, p[1] & ~0x1fu, 2 * 4, color);
640          break;
641       case _3DSTATE_BLEND_STATE_POINTERS:
642          /* TODO: handle Gen8+ extra dword at the beginning */
643          decode_structs(brw, spec, "BLEND_STATE", state,
644                         state_gtt_offset, p[1] & ~0x3fu, 8 * 4, color);
645          break;
646       case _3DSTATE_CC_STATE_POINTERS:
647          if (devinfo->gen >= 7) {
648             decode_struct(brw, spec, "COLOR_CALC_STATE", state,
649                           state_gtt_offset, p[1] & ~0x3fu, color);
650          } else if (devinfo->gen == 6) {
651             decode_structs(brw, spec, "BLEND_STATE", state,
652                            state_gtt_offset, p[1] & ~0x3fu, 2 * 4, color);
653             decode_struct(brw, spec, "DEPTH_STENCIL_STATE", state,
654                           state_gtt_offset, p[2] & ~0x3fu, color);
655             decode_struct(brw, spec, "COLOR_CALC_STATE", state,
656                           state_gtt_offset, p[3] & ~0x3fu, color);
657          }
658          break;
659       case _3DSTATE_DEPTH_STENCIL_STATE_POINTERS:
660          decode_struct(brw, spec, "DEPTH_STENCIL_STATE", state,
661                        state_gtt_offset, p[1] & ~0x3fu, color);
662          break;
663       case MEDIA_INTERFACE_DESCRIPTOR_LOAD: {
664          struct gen_group *group =
665             gen_spec_find_struct(spec, "RENDER_SURFACE_STATE");
666          if (!group)
667             break;
668
669          uint32_t idd_offset = p[3] & ~0x1fu;
670          decode_struct(brw, spec, "INTERFACE_DESCRIPTOR_DATA", state,
671                        state_gtt_offset, idd_offset, color);
672
673          uint32_t ss_offset = state[idd_offset / 4 + 3] & ~0x1fu;
674          decode_structs(brw, spec, "SAMPLER_STATE", state,
675                         state_gtt_offset, ss_offset, 4 * 4, color);
676
677          uint32_t bt_offset = state[idd_offset / 4 + 4] & ~0x1fu;
678          int bt_entries = brw_state_batch_size(brw, bt_offset) / 4;
679          uint32_t *bt_pointers = &state[bt_offset / 4];
680          for (int i = 0; i < bt_entries; i++) {
681             fprintf(stderr, "SURFACE_STATE - BTI = %d\n", i);
682             gen_print_group(stderr, group, state_gtt_offset + bt_pointers[i],
683                             &state[bt_pointers[i] / 4], 0, color);
684          }
685          break;
686       }
687       }
688    }
689
690    brw_bo_unmap(batch->batch.bo);
691    brw_bo_unmap(batch->state.bo);
692 }
693 #else
694 static void do_batch_dump(struct brw_context *brw) { }
695 #endif
696
697 /**
698  * Called when starting a new batch buffer.
699  */
700 static void
701 brw_new_batch(struct brw_context *brw)
702 {
703    /* Unreference any BOs held by the previous batch, and reset counts. */
704    for (int i = 0; i < brw->batch.exec_count; i++) {
705       brw_bo_unreference(brw->batch.exec_bos[i]);
706       brw->batch.exec_bos[i] = NULL;
707    }
708    brw->batch.batch_relocs.reloc_count = 0;
709    brw->batch.state_relocs.reloc_count = 0;
710    brw->batch.exec_count = 0;
711    brw->batch.aperture_space = 0;
712
713    brw_bo_unreference(brw->batch.state.bo);
714
715    /* Create a new batchbuffer and reset the associated state: */
716    intel_batchbuffer_reset_and_clear_render_cache(brw);
717
718    /* If the kernel supports hardware contexts, then most hardware state is
719     * preserved between batches; we only need to re-emit state that is required
720     * to be in every batch.  Otherwise we need to re-emit all the state that
721     * would otherwise be stored in the context (which for all intents and
722     * purposes means everything).
723     */
724    if (brw->hw_ctx == 0) {
725       brw->ctx.NewDriverState |= BRW_NEW_CONTEXT;
726       brw_upload_invariant_state(brw);
727    }
728
729    brw->ctx.NewDriverState |= BRW_NEW_BATCH;
730
731    brw->ib.index_size = -1;
732
733    /* We need to periodically reap the shader time results, because rollover
734     * happens every few seconds.  We also want to see results every once in a
735     * while, because many programs won't cleanly destroy our context, so the
736     * end-of-run printout may not happen.
737     */
738    if (INTEL_DEBUG & DEBUG_SHADER_TIME)
739       brw_collect_and_report_shader_time(brw);
740 }
741
742 /**
743  * Called from intel_batchbuffer_flush before emitting MI_BATCHBUFFER_END and
744  * sending it off.
745  *
746  * This function can emit state (say, to preserve registers that aren't saved
747  * between batches).
748  */
749 static void
750 brw_finish_batch(struct brw_context *brw)
751 {
752    const struct gen_device_info *devinfo = &brw->screen->devinfo;
753
754    brw->batch.no_wrap = true;
755
756    /* Capture the closing pipeline statistics register values necessary to
757     * support query objects (in the non-hardware context world).
758     */
759    brw_emit_query_end(brw);
760
761    if (brw->batch.ring == RENDER_RING) {
762       /* Work around L3 state leaks into contexts set MI_RESTORE_INHIBIT which
763        * assume that the L3 cache is configured according to the hardware
764        * defaults.  On Kernel 4.16+, we no longer need to do this.
765        */
766       if (devinfo->gen >= 7 &&
767           !(brw->screen->kernel_features & KERNEL_ALLOWS_CONTEXT_ISOLATION))
768          gen7_restore_default_l3_config(brw);
769
770       if (devinfo->is_haswell) {
771          /* From the Haswell PRM, Volume 2b, Command Reference: Instructions,
772           * 3DSTATE_CC_STATE_POINTERS > "Note":
773           *
774           * "SW must program 3DSTATE_CC_STATE_POINTERS command at the end of every
775           *  3D batch buffer followed by a PIPE_CONTROL with RC flush and CS stall."
776           *
777           * From the example in the docs, it seems to expect a regular pipe control
778           * flush here as well. We may have done it already, but meh.
779           *
780           * See also WaAvoidRCZCounterRollover.
781           */
782          brw_emit_mi_flush(brw);
783          BEGIN_BATCH(2);
784          OUT_BATCH(_3DSTATE_CC_STATE_POINTERS << 16 | (2 - 2));
785          OUT_BATCH(brw->cc.state_offset | 1);
786          ADVANCE_BATCH();
787          brw_emit_pipe_control_flush(brw, PIPE_CONTROL_RENDER_TARGET_FLUSH |
788                                           PIPE_CONTROL_CS_STALL);
789       }
790
791       /* Do not restore push constant packets during context restore. */
792       if (devinfo->gen >= 7)
793          gen10_emit_isp_disable(brw);
794    }
795
796    /* Emit MI_BATCH_BUFFER_END to finish our batch.  Note that execbuf2
797     * requires our batch size to be QWord aligned, so we pad it out if
798     * necessary by emitting an extra MI_NOOP after the end.
799     */
800    intel_batchbuffer_require_space(brw, 8, brw->batch.ring);
801    *brw->batch.map_next++ = MI_BATCH_BUFFER_END;
802    if (USED_BATCH(brw->batch) & 1) {
803       *brw->batch.map_next++ = MI_NOOP;
804    }
805
806    brw->batch.no_wrap = false;
807 }
808
809 static void
810 throttle(struct brw_context *brw)
811 {
812    /* Wait for the swapbuffers before the one we just emitted, so we
813     * don't get too many swaps outstanding for apps that are GPU-heavy
814     * but not CPU-heavy.
815     *
816     * We're using intelDRI2Flush (called from the loader before
817     * swapbuffer) and glFlush (for front buffer rendering) as the
818     * indicator that a frame is done and then throttle when we get
819     * here as we prepare to render the next frame.  At this point for
820     * round trips for swap/copy and getting new buffers are done and
821     * we'll spend less time waiting on the GPU.
822     *
823     * Unfortunately, we don't have a handle to the batch containing
824     * the swap, and getting our hands on that doesn't seem worth it,
825     * so we just use the first batch we emitted after the last swap.
826     */
827    if (brw->need_swap_throttle && brw->throttle_batch[0]) {
828       if (brw->throttle_batch[1]) {
829          if (!brw->disable_throttling) {
830             brw_bo_wait_rendering(brw->throttle_batch[1]);
831          }
832          brw_bo_unreference(brw->throttle_batch[1]);
833       }
834       brw->throttle_batch[1] = brw->throttle_batch[0];
835       brw->throttle_batch[0] = NULL;
836       brw->need_swap_throttle = false;
837       /* Throttling here is more precise than the throttle ioctl, so skip it */
838       brw->need_flush_throttle = false;
839    }
840
841    if (brw->need_flush_throttle) {
842       __DRIscreen *dri_screen = brw->screen->driScrnPriv;
843       drmCommandNone(dri_screen->fd, DRM_I915_GEM_THROTTLE);
844       brw->need_flush_throttle = false;
845    }
846 }
847
848 static int
849 execbuffer(int fd,
850            struct intel_batchbuffer *batch,
851            uint32_t ctx_id,
852            int used,
853            int in_fence,
854            int *out_fence,
855            int flags)
856 {
857    struct drm_i915_gem_execbuffer2 execbuf = {
858       .buffers_ptr = (uintptr_t) batch->validation_list,
859       .buffer_count = batch->exec_count,
860       .batch_start_offset = 0,
861       .batch_len = used,
862       .flags = flags,
863       .rsvd1 = ctx_id, /* rsvd1 is actually the context ID */
864    };
865
866    unsigned long cmd = DRM_IOCTL_I915_GEM_EXECBUFFER2;
867
868    if (in_fence != -1) {
869       execbuf.rsvd2 = in_fence;
870       execbuf.flags |= I915_EXEC_FENCE_IN;
871    }
872
873    if (out_fence != NULL) {
874       cmd = DRM_IOCTL_I915_GEM_EXECBUFFER2_WR;
875       *out_fence = -1;
876       execbuf.flags |= I915_EXEC_FENCE_OUT;
877    }
878
879    int ret = drmIoctl(fd, cmd, &execbuf);
880    if (ret != 0)
881       ret = -errno;
882
883    for (int i = 0; i < batch->exec_count; i++) {
884       struct brw_bo *bo = batch->exec_bos[i];
885
886       bo->idle = false;
887       bo->index = -1;
888
889       /* Update brw_bo::gtt_offset */
890       if (batch->validation_list[i].offset != bo->gtt_offset) {
891          DBG("BO %d migrated: 0x%" PRIx64 " -> 0x%llx\n",
892              bo->gem_handle, bo->gtt_offset,
893              batch->validation_list[i].offset);
894          bo->gtt_offset = batch->validation_list[i].offset;
895       }
896    }
897
898    if (ret == 0 && out_fence != NULL)
899       *out_fence = execbuf.rsvd2 >> 32;
900
901    return ret;
902 }
903
904 static int
905 submit_batch(struct brw_context *brw, int in_fence_fd, int *out_fence_fd)
906 {
907    const struct gen_device_info *devinfo = &brw->screen->devinfo;
908    __DRIscreen *dri_screen = brw->screen->driScrnPriv;
909    struct intel_batchbuffer *batch = &brw->batch;
910    int ret = 0;
911
912    if (batch->use_shadow_copy) {
913       void *bo_map = brw_bo_map(brw, batch->batch.bo, MAP_WRITE);
914       memcpy(bo_map, batch->batch.map, 4 * USED_BATCH(*batch));
915
916       bo_map = brw_bo_map(brw, batch->state.bo, MAP_WRITE);
917       memcpy(bo_map, batch->state.map, batch->state_used);
918    }
919
920    brw_bo_unmap(batch->batch.bo);
921    brw_bo_unmap(batch->state.bo);
922
923    if (!brw->screen->no_hw) {
924       /* The requirement for using I915_EXEC_NO_RELOC are:
925        *
926        *   The addresses written in the objects must match the corresponding
927        *   reloc.gtt_offset which in turn must match the corresponding
928        *   execobject.offset.
929        *
930        *   Any render targets written to in the batch must be flagged with
931        *   EXEC_OBJECT_WRITE.
932        *
933        *   To avoid stalling, execobject.offset should match the current
934        *   address of that object within the active context.
935        */
936       int flags = I915_EXEC_NO_RELOC;
937
938       if (devinfo->gen >= 6 && batch->ring == BLT_RING) {
939          flags |= I915_EXEC_BLT;
940       } else {
941          flags |= I915_EXEC_RENDER;
942       }
943       if (batch->needs_sol_reset)
944          flags |= I915_EXEC_GEN7_SOL_RESET;
945
946       uint32_t hw_ctx = batch->ring == RENDER_RING ? brw->hw_ctx : 0;
947
948       /* Set statebuffer relocations */
949       const unsigned state_index = batch->state.bo->index;
950       if (state_index < batch->exec_count &&
951           batch->exec_bos[state_index] == batch->state.bo) {
952          struct drm_i915_gem_exec_object2 *entry =
953             &batch->validation_list[state_index];
954          assert(entry->handle == batch->state.bo->gem_handle);
955          entry->relocation_count = batch->state_relocs.reloc_count;
956          entry->relocs_ptr = (uintptr_t) batch->state_relocs.relocs;
957       }
958
959       /* Set batchbuffer relocations */
960       struct drm_i915_gem_exec_object2 *entry = &batch->validation_list[0];
961       assert(entry->handle == batch->batch.bo->gem_handle);
962       entry->relocation_count = batch->batch_relocs.reloc_count;
963       entry->relocs_ptr = (uintptr_t) batch->batch_relocs.relocs;
964
965       if (batch->use_batch_first) {
966          flags |= I915_EXEC_BATCH_FIRST | I915_EXEC_HANDLE_LUT;
967       } else {
968          /* Move the batch to the end of the validation list */
969          struct drm_i915_gem_exec_object2 tmp;
970          const unsigned index = batch->exec_count - 1;
971
972          tmp = *entry;
973          *entry = batch->validation_list[index];
974          batch->validation_list[index] = tmp;
975       }
976
977       ret = execbuffer(dri_screen->fd, batch, hw_ctx,
978                        4 * USED_BATCH(*batch),
979                        in_fence_fd, out_fence_fd, flags);
980
981       throttle(brw);
982    }
983
984    if (unlikely(INTEL_DEBUG & DEBUG_BATCH))
985       do_batch_dump(brw);
986
987    if (brw->ctx.Const.ResetStrategy == GL_LOSE_CONTEXT_ON_RESET_ARB)
988       brw_check_for_reset(brw);
989
990    if (ret != 0) {
991       fprintf(stderr, "i965: Failed to submit batchbuffer: %s\n",
992               strerror(-ret));
993       exit(1);
994    }
995
996    return ret;
997 }
998
999 /**
1000  * The in_fence_fd is ignored if -1.  Otherwise this function takes ownership
1001  * of the fd.
1002  *
1003  * The out_fence_fd is ignored if NULL. Otherwise, the caller takes ownership
1004  * of the returned fd.
1005  */
1006 int
1007 _intel_batchbuffer_flush_fence(struct brw_context *brw,
1008                                int in_fence_fd, int *out_fence_fd,
1009                                const char *file, int line)
1010 {
1011    int ret;
1012
1013    if (USED_BATCH(brw->batch) == 0)
1014       return 0;
1015
1016    /* Check that we didn't just wrap our batchbuffer at a bad time. */
1017    assert(!brw->batch.no_wrap);
1018
1019    brw_finish_batch(brw);
1020    brw_upload_finish(&brw->upload);
1021
1022    finish_growing_bos(&brw->batch.batch);
1023    finish_growing_bos(&brw->batch.state);
1024
1025    if (brw->throttle_batch[0] == NULL) {
1026       brw->throttle_batch[0] = brw->batch.batch.bo;
1027       brw_bo_reference(brw->throttle_batch[0]);
1028    }
1029
1030    if (unlikely(INTEL_DEBUG & (DEBUG_BATCH | DEBUG_SUBMIT))) {
1031       int bytes_for_commands = 4 * USED_BATCH(brw->batch);
1032       int bytes_for_state = brw->batch.state_used;
1033       fprintf(stderr, "%19s:%-3d: Batchbuffer flush with %5db (%0.1f%%) (pkt),"
1034               " %5db (%0.1f%%) (state), %4d BOs (%0.1fMb aperture),"
1035               " %4d batch relocs, %4d state relocs\n", file, line,
1036               bytes_for_commands, 100.0f * bytes_for_commands / BATCH_SZ,
1037               bytes_for_state, 100.0f * bytes_for_state / STATE_SZ,
1038               brw->batch.exec_count,
1039               (float) brw->batch.aperture_space / (1024 * 1024),
1040               brw->batch.batch_relocs.reloc_count,
1041               brw->batch.state_relocs.reloc_count);
1042    }
1043
1044    ret = submit_batch(brw, in_fence_fd, out_fence_fd);
1045
1046    if (unlikely(INTEL_DEBUG & DEBUG_SYNC)) {
1047       fprintf(stderr, "waiting for idle\n");
1048       brw_bo_wait_rendering(brw->batch.batch.bo);
1049    }
1050
1051    /* Start a new batch buffer. */
1052    brw_new_batch(brw);
1053
1054    return ret;
1055 }
1056
1057 bool
1058 brw_batch_has_aperture_space(struct brw_context *brw, unsigned extra_space)
1059 {
1060    return brw->batch.aperture_space + extra_space <=
1061           brw->screen->aperture_threshold;
1062 }
1063
1064 bool
1065 brw_batch_references(struct intel_batchbuffer *batch, struct brw_bo *bo)
1066 {
1067    unsigned index = READ_ONCE(bo->index);
1068    if (index < batch->exec_count && batch->exec_bos[index] == bo)
1069       return true;
1070
1071    for (int i = 0; i < batch->exec_count; i++) {
1072       if (batch->exec_bos[i] == bo)
1073          return true;
1074    }
1075    return false;
1076 }
1077
1078 /*  This is the only way buffers get added to the validate list.
1079  */
1080 static uint64_t
1081 emit_reloc(struct intel_batchbuffer *batch,
1082            struct brw_reloc_list *rlist, uint32_t offset,
1083            struct brw_bo *target, int32_t target_offset,
1084            unsigned int reloc_flags)
1085 {
1086    assert(target != NULL);
1087
1088    if (rlist->reloc_count == rlist->reloc_array_size) {
1089       rlist->reloc_array_size *= 2;
1090       rlist->relocs = realloc(rlist->relocs,
1091                               rlist->reloc_array_size *
1092                               sizeof(struct drm_i915_gem_relocation_entry));
1093    }
1094
1095    unsigned int index = add_exec_bo(batch, target);
1096    struct drm_i915_gem_exec_object2 *entry = &batch->validation_list[index];
1097
1098    if (reloc_flags & RELOC_32BIT) {
1099       /* Restrict this buffer to the low 32 bits of the address space.
1100        *
1101        * Altering the validation list flags restricts it for this batch,
1102        * but we also alter the BO's kflags to restrict it permanently
1103        * (until the BO is destroyed and put back in the cache).  Buffers
1104        * may stay bound across batches, and we want keep it constrained.
1105        */
1106       target->kflags &= ~EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
1107       entry->flags &= ~EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
1108
1109       /* RELOC_32BIT is not an EXEC_OBJECT_* flag, so get rid of it. */
1110       reloc_flags &= ~RELOC_32BIT;
1111    }
1112
1113    if (reloc_flags)
1114       entry->flags |= reloc_flags & batch->valid_reloc_flags;
1115
1116    rlist->relocs[rlist->reloc_count++] =
1117       (struct drm_i915_gem_relocation_entry) {
1118          .offset = offset,
1119          .delta = target_offset,
1120          .target_handle = batch->use_batch_first ? index : target->gem_handle,
1121          .presumed_offset = entry->offset,
1122       };
1123
1124    /* Using the old buffer offset, write in what the right data would be, in
1125     * case the buffer doesn't move and we can short-circuit the relocation
1126     * processing in the kernel
1127     */
1128    return entry->offset + target_offset;
1129 }
1130
1131 uint64_t
1132 brw_batch_reloc(struct intel_batchbuffer *batch, uint32_t batch_offset,
1133                 struct brw_bo *target, uint32_t target_offset,
1134                 unsigned int reloc_flags)
1135 {
1136    assert(batch_offset <= batch->batch.bo->size - sizeof(uint32_t));
1137
1138    return emit_reloc(batch, &batch->batch_relocs, batch_offset,
1139                      target, target_offset, reloc_flags);
1140 }
1141
1142 uint64_t
1143 brw_state_reloc(struct intel_batchbuffer *batch, uint32_t state_offset,
1144                 struct brw_bo *target, uint32_t target_offset,
1145                 unsigned int reloc_flags)
1146 {
1147    assert(state_offset <= batch->state.bo->size - sizeof(uint32_t));
1148
1149    return emit_reloc(batch, &batch->state_relocs, state_offset,
1150                      target, target_offset, reloc_flags);
1151 }
1152
1153
1154 uint32_t
1155 brw_state_batch_size(struct brw_context *brw, uint32_t offset)
1156 {
1157    struct hash_entry *entry =
1158       _mesa_hash_table_search(brw->batch.state_batch_sizes,
1159                               (void *) (uintptr_t) offset);
1160    return entry ? (uintptr_t) entry->data : 0;
1161 }
1162
1163 /**
1164  * Reserve some space in the statebuffer, or flush.
1165  *
1166  * This is used to estimate when we're near the end of the batch,
1167  * so we can flush early.
1168  */
1169 void
1170 brw_require_statebuffer_space(struct brw_context *brw, int size)
1171 {
1172    if (brw->batch.state_used + size >= STATE_SZ)
1173       intel_batchbuffer_flush(brw);
1174 }
1175
1176 /**
1177  * Allocates a block of space in the batchbuffer for indirect state.
1178  */
1179 void *
1180 brw_state_batch(struct brw_context *brw,
1181                 int size,
1182                 int alignment,
1183                 uint32_t *out_offset)
1184 {
1185    struct intel_batchbuffer *batch = &brw->batch;
1186
1187    assert(size < batch->state.bo->size);
1188
1189    uint32_t offset = ALIGN(batch->state_used, alignment);
1190
1191    if (offset + size >= STATE_SZ && !batch->no_wrap) {
1192       intel_batchbuffer_flush(brw);
1193       offset = ALIGN(batch->state_used, alignment);
1194    } else if (offset + size >= batch->state.bo->size) {
1195       const unsigned new_size =
1196          MIN2(batch->state.bo->size + batch->state.bo->size / 2,
1197               MAX_STATE_SIZE);
1198       grow_buffer(brw, &batch->state, batch->state_used, new_size);
1199       assert(offset + size < batch->state.bo->size);
1200    }
1201
1202    if (unlikely(INTEL_DEBUG & DEBUG_BATCH)) {
1203       _mesa_hash_table_insert(batch->state_batch_sizes,
1204                               (void *) (uintptr_t) offset,
1205                               (void *) (uintptr_t) size);
1206    }
1207
1208    batch->state_used = offset + size;
1209
1210    *out_offset = offset;
1211    return batch->state.map + (offset >> 2);
1212 }
1213
1214 void
1215 intel_batchbuffer_data(struct brw_context *brw,
1216                        const void *data, GLuint bytes, enum brw_gpu_ring ring)
1217 {
1218    assert((bytes & 3) == 0);
1219    intel_batchbuffer_require_space(brw, bytes, ring);
1220    memcpy(brw->batch.map_next, data, bytes);
1221    brw->batch.map_next += bytes >> 2;
1222 }
1223
1224 static void
1225 load_sized_register_mem(struct brw_context *brw,
1226                         uint32_t reg,
1227                         struct brw_bo *bo,
1228                         uint32_t offset,
1229                         int size)
1230 {
1231    const struct gen_device_info *devinfo = &brw->screen->devinfo;
1232    int i;
1233
1234    /* MI_LOAD_REGISTER_MEM only exists on Gen7+. */
1235    assert(devinfo->gen >= 7);
1236
1237    if (devinfo->gen >= 8) {
1238       BEGIN_BATCH(4 * size);
1239       for (i = 0; i < size; i++) {
1240          OUT_BATCH(GEN7_MI_LOAD_REGISTER_MEM | (4 - 2));
1241          OUT_BATCH(reg + i * 4);
1242          OUT_RELOC64(bo, 0, offset + i * 4);
1243       }
1244       ADVANCE_BATCH();
1245    } else {
1246       BEGIN_BATCH(3 * size);
1247       for (i = 0; i < size; i++) {
1248          OUT_BATCH(GEN7_MI_LOAD_REGISTER_MEM | (3 - 2));
1249          OUT_BATCH(reg + i * 4);
1250          OUT_RELOC(bo, 0, offset + i * 4);
1251       }
1252       ADVANCE_BATCH();
1253    }
1254 }
1255
1256 void
1257 brw_load_register_mem(struct brw_context *brw,
1258                       uint32_t reg,
1259                       struct brw_bo *bo,
1260                       uint32_t offset)
1261 {
1262    load_sized_register_mem(brw, reg, bo, offset, 1);
1263 }
1264
1265 void
1266 brw_load_register_mem64(struct brw_context *brw,
1267                         uint32_t reg,
1268                         struct brw_bo *bo,
1269                         uint32_t offset)
1270 {
1271    load_sized_register_mem(brw, reg, bo, offset, 2);
1272 }
1273
1274 /*
1275  * Write an arbitrary 32-bit register to a buffer via MI_STORE_REGISTER_MEM.
1276  */
1277 void
1278 brw_store_register_mem32(struct brw_context *brw,
1279                          struct brw_bo *bo, uint32_t reg, uint32_t offset)
1280 {
1281    const struct gen_device_info *devinfo = &brw->screen->devinfo;
1282
1283    assert(devinfo->gen >= 6);
1284
1285    if (devinfo->gen >= 8) {
1286       BEGIN_BATCH(4);
1287       OUT_BATCH(MI_STORE_REGISTER_MEM | (4 - 2));
1288       OUT_BATCH(reg);
1289       OUT_RELOC64(bo, RELOC_WRITE, offset);
1290       ADVANCE_BATCH();
1291    } else {
1292       BEGIN_BATCH(3);
1293       OUT_BATCH(MI_STORE_REGISTER_MEM | (3 - 2));
1294       OUT_BATCH(reg);
1295       OUT_RELOC(bo, RELOC_WRITE | RELOC_NEEDS_GGTT, offset);
1296       ADVANCE_BATCH();
1297    }
1298 }
1299
1300 /*
1301  * Write an arbitrary 64-bit register to a buffer via MI_STORE_REGISTER_MEM.
1302  */
1303 void
1304 brw_store_register_mem64(struct brw_context *brw,
1305                          struct brw_bo *bo, uint32_t reg, uint32_t offset)
1306 {
1307    const struct gen_device_info *devinfo = &brw->screen->devinfo;
1308
1309    assert(devinfo->gen >= 6);
1310
1311    /* MI_STORE_REGISTER_MEM only stores a single 32-bit value, so to
1312     * read a full 64-bit register, we need to do two of them.
1313     */
1314    if (devinfo->gen >= 8) {
1315       BEGIN_BATCH(8);
1316       OUT_BATCH(MI_STORE_REGISTER_MEM | (4 - 2));
1317       OUT_BATCH(reg);
1318       OUT_RELOC64(bo, RELOC_WRITE, offset);
1319       OUT_BATCH(MI_STORE_REGISTER_MEM | (4 - 2));
1320       OUT_BATCH(reg + sizeof(uint32_t));
1321       OUT_RELOC64(bo, RELOC_WRITE, offset + sizeof(uint32_t));
1322       ADVANCE_BATCH();
1323    } else {
1324       BEGIN_BATCH(6);
1325       OUT_BATCH(MI_STORE_REGISTER_MEM | (3 - 2));
1326       OUT_BATCH(reg);
1327       OUT_RELOC(bo, RELOC_WRITE | RELOC_NEEDS_GGTT, offset);
1328       OUT_BATCH(MI_STORE_REGISTER_MEM | (3 - 2));
1329       OUT_BATCH(reg + sizeof(uint32_t));
1330       OUT_RELOC(bo, RELOC_WRITE | RELOC_NEEDS_GGTT, offset + sizeof(uint32_t));
1331       ADVANCE_BATCH();
1332    }
1333 }
1334
1335 /*
1336  * Write a 32-bit register using immediate data.
1337  */
1338 void
1339 brw_load_register_imm32(struct brw_context *brw, uint32_t reg, uint32_t imm)
1340 {
1341    assert(brw->screen->devinfo.gen >= 6);
1342
1343    BEGIN_BATCH(3);
1344    OUT_BATCH(MI_LOAD_REGISTER_IMM | (3 - 2));
1345    OUT_BATCH(reg);
1346    OUT_BATCH(imm);
1347    ADVANCE_BATCH();
1348 }
1349
1350 /*
1351  * Write a 64-bit register using immediate data.
1352  */
1353 void
1354 brw_load_register_imm64(struct brw_context *brw, uint32_t reg, uint64_t imm)
1355 {
1356    assert(brw->screen->devinfo.gen >= 6);
1357
1358    BEGIN_BATCH(5);
1359    OUT_BATCH(MI_LOAD_REGISTER_IMM | (5 - 2));
1360    OUT_BATCH(reg);
1361    OUT_BATCH(imm & 0xffffffff);
1362    OUT_BATCH(reg + 4);
1363    OUT_BATCH(imm >> 32);
1364    ADVANCE_BATCH();
1365 }
1366
1367 /*
1368  * Copies a 32-bit register.
1369  */
1370 void
1371 brw_load_register_reg(struct brw_context *brw, uint32_t src, uint32_t dest)
1372 {
1373    assert(brw->screen->devinfo.gen >= 8 || brw->screen->devinfo.is_haswell);
1374
1375    BEGIN_BATCH(3);
1376    OUT_BATCH(MI_LOAD_REGISTER_REG | (3 - 2));
1377    OUT_BATCH(src);
1378    OUT_BATCH(dest);
1379    ADVANCE_BATCH();
1380 }
1381
1382 /*
1383  * Copies a 64-bit register.
1384  */
1385 void
1386 brw_load_register_reg64(struct brw_context *brw, uint32_t src, uint32_t dest)
1387 {
1388    assert(brw->screen->devinfo.gen >= 8 || brw->screen->devinfo.is_haswell);
1389
1390    BEGIN_BATCH(6);
1391    OUT_BATCH(MI_LOAD_REGISTER_REG | (3 - 2));
1392    OUT_BATCH(src);
1393    OUT_BATCH(dest);
1394    OUT_BATCH(MI_LOAD_REGISTER_REG | (3 - 2));
1395    OUT_BATCH(src + sizeof(uint32_t));
1396    OUT_BATCH(dest + sizeof(uint32_t));
1397    ADVANCE_BATCH();
1398 }
1399
1400 /*
1401  * Write 32-bits of immediate data to a GPU memory buffer.
1402  */
1403 void
1404 brw_store_data_imm32(struct brw_context *brw, struct brw_bo *bo,
1405                      uint32_t offset, uint32_t imm)
1406 {
1407    const struct gen_device_info *devinfo = &brw->screen->devinfo;
1408
1409    assert(devinfo->gen >= 6);
1410
1411    BEGIN_BATCH(4);
1412    OUT_BATCH(MI_STORE_DATA_IMM | (4 - 2));
1413    if (devinfo->gen >= 8)
1414       OUT_RELOC64(bo, RELOC_WRITE, offset);
1415    else {
1416       OUT_BATCH(0); /* MBZ */
1417       OUT_RELOC(bo, RELOC_WRITE, offset);
1418    }
1419    OUT_BATCH(imm);
1420    ADVANCE_BATCH();
1421 }
1422
1423 /*
1424  * Write 64-bits of immediate data to a GPU memory buffer.
1425  */
1426 void
1427 brw_store_data_imm64(struct brw_context *brw, struct brw_bo *bo,
1428                      uint32_t offset, uint64_t imm)
1429 {
1430    const struct gen_device_info *devinfo = &brw->screen->devinfo;
1431
1432    assert(devinfo->gen >= 6);
1433
1434    BEGIN_BATCH(5);
1435    OUT_BATCH(MI_STORE_DATA_IMM | (5 - 2));
1436    if (devinfo->gen >= 8)
1437       OUT_RELOC64(bo, RELOC_WRITE, offset);
1438    else {
1439       OUT_BATCH(0); /* MBZ */
1440       OUT_RELOC(bo, RELOC_WRITE, offset);
1441    }
1442    OUT_BATCH(imm & 0xffffffffu);
1443    OUT_BATCH(imm >> 32);
1444    ADVANCE_BATCH();
1445 }