• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2017 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 shall be included
12  * in all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
17  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20  * DEALINGS IN THE SOFTWARE.
21  */
22 
23 /**
24  * @file crocus_batch.c
25  *
26  * Batchbuffer and command submission module.
27  *
28  * Every API draw call results in a number of GPU commands, which we
29  * collect into a "batch buffer".  Typically, many draw calls are grouped
30  * into a single batch to amortize command submission overhead.
31  *
32  * We submit batches to the kernel using the I915_GEM_EXECBUFFER2 ioctl.
33  * One critical piece of data is the "validation list", which contains a
34  * list of the buffer objects (BOs) which the commands in the GPU need.
35  * The kernel will make sure these are resident and pinned at the correct
36  * virtual memory address before executing our batch.  If a BO is not in
37  * the validation list, it effectively does not exist, so take care.
38  */
39 
40 #include "crocus_batch.h"
41 #include "crocus_bufmgr.h"
42 #include "crocus_context.h"
43 #include "crocus_fence.h"
44 
45 #include "drm-uapi/i915_drm.h"
46 
47 #include "intel/common/intel_gem.h"
48 #include "main/macros.h"
49 #include "util/hash_table.h"
50 #include "util/set.h"
51 #include "util/u_upload_mgr.h"
52 
53 #include <errno.h>
54 #include <xf86drm.h>
55 
56 #if HAVE_VALGRIND
57 #include <memcheck.h>
58 #include <valgrind.h>
59 #define VG(x) x
60 #else
61 #define VG(x)
62 #endif
63 
64 #define FILE_DEBUG_FLAG DEBUG_BUFMGR
65 
66 /* Terminating the batch takes either 4 bytes for MI_BATCH_BUFFER_END
67  * or 12 bytes for MI_BATCH_BUFFER_START (when chaining).  Plus, we may
68  * need an extra 4 bytes to pad out to the nearest QWord.  So reserve 16.
69  */
70 #define BATCH_RESERVED(devinfo) ((devinfo)->is_haswell ? 32 : 16)
71 
72 static void crocus_batch_reset(struct crocus_batch *batch);
73 
74 static unsigned
num_fences(struct crocus_batch * batch)75 num_fences(struct crocus_batch *batch)
76 {
77    return util_dynarray_num_elements(&batch->exec_fences,
78                                      struct drm_i915_gem_exec_fence);
79 }
80 
81 /**
82  * Debugging code to dump the fence list, used by INTEL_DEBUG=submit.
83  */
84 static void
dump_fence_list(struct crocus_batch * batch)85 dump_fence_list(struct crocus_batch *batch)
86 {
87    fprintf(stderr, "Fence list (length %u):      ", num_fences(batch));
88 
89    util_dynarray_foreach(&batch->exec_fences,
90                          struct drm_i915_gem_exec_fence, f) {
91       fprintf(stderr, "%s%u%s ",
92               (f->flags & I915_EXEC_FENCE_WAIT) ? "..." : "",
93               f->handle,
94               (f->flags & I915_EXEC_FENCE_SIGNAL) ? "!" : "");
95    }
96 
97    fprintf(stderr, "\n");
98 }
99 
100 /**
101  * Debugging code to dump the validation list, used by INTEL_DEBUG=submit.
102  */
103 static void
dump_validation_list(struct crocus_batch * batch)104 dump_validation_list(struct crocus_batch *batch)
105 {
106    fprintf(stderr, "Validation list (length %d):\n", batch->exec_count);
107 
108    for (int i = 0; i < batch->exec_count; i++) {
109       uint64_t flags = batch->validation_list[i].flags;
110       assert(batch->validation_list[i].handle ==
111              batch->exec_bos[i]->gem_handle);
112       fprintf(stderr,
113               "[%2d]: %2d %-14s @ 0x%"PRIx64" (%" PRIu64 "B)\t %2d refs %s\n", i,
114               batch->validation_list[i].handle, batch->exec_bos[i]->name,
115               (uint64_t)batch->validation_list[i].offset, batch->exec_bos[i]->size,
116               batch->exec_bos[i]->refcount,
117               (flags & EXEC_OBJECT_WRITE) ? " (write)" : "");
118    }
119 }
120 
121 /**
122  * Return BO information to the batch decoder (for debugging).
123  */
124 static struct intel_batch_decode_bo
decode_get_bo(void * v_batch,bool ppgtt,uint64_t address)125 decode_get_bo(void *v_batch, bool ppgtt, uint64_t address)
126 {
127    struct crocus_batch *batch = v_batch;
128 
129    for (int i = 0; i < batch->exec_count; i++) {
130       struct crocus_bo *bo = batch->exec_bos[i];
131       /* The decoder zeroes out the top 16 bits, so we need to as well */
132       uint64_t bo_address = bo->gtt_offset & (~0ull >> 16);
133 
134       if (address >= bo_address && address < bo_address + bo->size) {
135          return (struct intel_batch_decode_bo){
136             .addr = address,
137             .size = bo->size,
138             .map = crocus_bo_map(batch->dbg, bo, MAP_READ) +
139                    (address - bo_address),
140          };
141       }
142    }
143 
144    return (struct intel_batch_decode_bo) { };
145 }
146 
147 static unsigned
decode_get_state_size(void * v_batch,uint64_t address,uint64_t base_address)148 decode_get_state_size(void *v_batch, uint64_t address,
149                       uint64_t base_address)
150 {
151    struct crocus_batch *batch = v_batch;
152 
153    /* The decoder gives us offsets from a base address, which is not great.
154     * Binding tables are relative to surface state base address, and other
155     * state is relative to dynamic state base address.  These could alias,
156     * but in practice it's unlikely because surface offsets are always in
157     * the [0, 64K) range, and we assign dynamic state addresses starting at
158     * the top of the 4GB range.  We should fix this but it's likely good
159     * enough for now.
160     */
161    unsigned size = (uintptr_t)
162       _mesa_hash_table_u64_search(batch->state_sizes, address - base_address);
163 
164    return size;
165 }
166 
167 /**
168  * Decode the current batch.
169  */
170 static void
decode_batch(struct crocus_batch * batch)171 decode_batch(struct crocus_batch *batch)
172 {
173    void *map = crocus_bo_map(batch->dbg, batch->exec_bos[0], MAP_READ);
174    intel_print_batch(&batch->decoder, map, batch->primary_batch_size,
175                      batch->exec_bos[0]->gtt_offset, false);
176 }
177 
178 static void
init_reloc_list(struct crocus_reloc_list * rlist,int count)179 init_reloc_list(struct crocus_reloc_list *rlist, int count)
180 {
181    rlist->reloc_count = 0;
182    rlist->reloc_array_size = count;
183    rlist->relocs = malloc(rlist->reloc_array_size *
184                           sizeof(struct drm_i915_gem_relocation_entry));
185 }
186 
187 void
crocus_init_batch(struct crocus_context * ice,enum crocus_batch_name name,int priority)188 crocus_init_batch(struct crocus_context *ice,
189                   enum crocus_batch_name name,
190                   int priority)
191 {
192    struct crocus_batch *batch = &ice->batches[name];
193    struct crocus_screen *screen = (struct crocus_screen *)ice->ctx.screen;
194    struct intel_device_info *devinfo = &screen->devinfo;
195 
196    batch->ice = ice;
197    batch->screen = screen;
198    batch->dbg = &ice->dbg;
199    batch->reset = &ice->reset;
200    batch->name = name;
201    batch->contains_fence_signal = false;
202 
203    if (devinfo->ver >= 7) {
204       batch->fine_fences.uploader =
205          u_upload_create(&ice->ctx, 4096, PIPE_BIND_CUSTOM,
206                          PIPE_USAGE_STAGING, 0);
207    }
208    crocus_fine_fence_init(batch);
209 
210    batch->hw_ctx_id = crocus_create_hw_context(screen->bufmgr);
211    assert(batch->hw_ctx_id);
212 
213    crocus_hw_context_set_priority(screen->bufmgr, batch->hw_ctx_id, priority);
214 
215    batch->valid_reloc_flags = EXEC_OBJECT_WRITE;
216    if (devinfo->ver == 6)
217       batch->valid_reloc_flags |= EXEC_OBJECT_NEEDS_GTT;
218 
219    if (INTEL_DEBUG(DEBUG_BATCH)) {
220       /* The shadow doesn't get relocs written so state decode fails. */
221       batch->use_shadow_copy = false;
222    } else
223       batch->use_shadow_copy = !devinfo->has_llc;
224 
225    util_dynarray_init(&batch->exec_fences, ralloc_context(NULL));
226    util_dynarray_init(&batch->syncobjs, ralloc_context(NULL));
227 
228    init_reloc_list(&batch->command.relocs, 250);
229    init_reloc_list(&batch->state.relocs, 250);
230 
231    batch->exec_count = 0;
232    batch->exec_array_size = 100;
233    batch->exec_bos =
234       malloc(batch->exec_array_size * sizeof(batch->exec_bos[0]));
235    batch->validation_list =
236       malloc(batch->exec_array_size * sizeof(batch->validation_list[0]));
237 
238    batch->cache.render = _mesa_hash_table_create(NULL, NULL,
239                                                  _mesa_key_pointer_equal);
240    batch->cache.depth = _mesa_set_create(NULL, NULL,
241                                          _mesa_key_pointer_equal);
242 
243    memset(batch->other_batches, 0, sizeof(batch->other_batches));
244 
245    for (int i = 0, j = 0; i < ice->batch_count; i++) {
246       if (i != name)
247          batch->other_batches[j++] = &ice->batches[i];
248    }
249 
250    if (INTEL_DEBUG(DEBUG_BATCH)) {
251 
252       batch->state_sizes = _mesa_hash_table_u64_create(NULL);
253       const unsigned decode_flags =
254          INTEL_BATCH_DECODE_FULL |
255          (INTEL_DEBUG(DEBUG_COLOR) ? INTEL_BATCH_DECODE_IN_COLOR : 0) |
256          INTEL_BATCH_DECODE_OFFSETS | INTEL_BATCH_DECODE_FLOATS;
257 
258       intel_batch_decode_ctx_init(&batch->decoder, &screen->devinfo, stderr,
259                                   decode_flags, NULL, decode_get_bo,
260                                   decode_get_state_size, batch);
261       batch->decoder.max_vbo_decoded_lines = 32;
262    }
263 
264    crocus_batch_reset(batch);
265 }
266 
267 static struct drm_i915_gem_exec_object2 *
find_validation_entry(struct crocus_batch * batch,struct crocus_bo * bo)268 find_validation_entry(struct crocus_batch *batch, struct crocus_bo *bo)
269 {
270    unsigned index = READ_ONCE(bo->index);
271 
272    if (index < batch->exec_count && batch->exec_bos[index] == bo)
273       return &batch->validation_list[index];
274 
275    /* May have been shared between multiple active batches */
276    for (index = 0; index < batch->exec_count; index++) {
277       if (batch->exec_bos[index] == bo)
278          return &batch->validation_list[index];
279    }
280 
281    return NULL;
282 }
283 
284 static void
ensure_exec_obj_space(struct crocus_batch * batch,uint32_t count)285 ensure_exec_obj_space(struct crocus_batch *batch, uint32_t count)
286 {
287    while (batch->exec_count + count > batch->exec_array_size) {
288       batch->exec_array_size *= 2;
289       batch->exec_bos = realloc(
290          batch->exec_bos, batch->exec_array_size * sizeof(batch->exec_bos[0]));
291       batch->validation_list =
292          realloc(batch->validation_list,
293                  batch->exec_array_size * sizeof(batch->validation_list[0]));
294    }
295 }
296 
297 static struct drm_i915_gem_exec_object2 *
crocus_use_bo(struct crocus_batch * batch,struct crocus_bo * bo,bool writable)298 crocus_use_bo(struct crocus_batch *batch, struct crocus_bo *bo, bool writable)
299 {
300    assert(bo->bufmgr == batch->command.bo->bufmgr);
301 
302    struct drm_i915_gem_exec_object2 *existing_entry =
303       find_validation_entry(batch, bo);
304 
305    if (existing_entry) {
306       /* The BO is already in the validation list; mark it writable */
307       if (writable)
308          existing_entry->flags |= EXEC_OBJECT_WRITE;
309       return existing_entry;
310    }
311 
312    if (bo != batch->command.bo && bo != batch->state.bo) {
313       /* This is the first time our batch has seen this BO.  Before we use it,
314        * we may need to flush and synchronize with other batches.
315        */
316       for (int b = 0; b < ARRAY_SIZE(batch->other_batches); b++) {
317 
318          if (!batch->other_batches[b])
319             continue;
320          struct drm_i915_gem_exec_object2 *other_entry =
321             find_validation_entry(batch->other_batches[b], bo);
322 
323          /* If the buffer is referenced by another batch, and either batch
324           * intends to write it, then flush the other batch and synchronize.
325           *
326           * Consider these cases:
327           *
328           * 1. They read, we read   =>  No synchronization required.
329           * 2. They read, we write  =>  Synchronize (they need the old value)
330           * 3. They write, we read  =>  Synchronize (we need their new value)
331           * 4. They write, we write =>  Synchronize (order writes)
332           *
333           * The read/read case is very common, as multiple batches usually
334           * share a streaming state buffer or shader assembly buffer, and
335           * we want to avoid synchronizing in this case.
336           */
337          if (other_entry &&
338              ((other_entry->flags & EXEC_OBJECT_WRITE) || writable)) {
339             crocus_batch_flush(batch->other_batches[b]);
340             crocus_batch_add_syncobj(batch,
341                                      batch->other_batches[b]->last_fence->syncobj,
342                                      I915_EXEC_FENCE_WAIT);
343          }
344       }
345    }
346 
347    /* Bump the ref count since the batch is now using this bo. */
348    crocus_bo_reference(bo);
349 
350    ensure_exec_obj_space(batch, 1);
351 
352    batch->validation_list[batch->exec_count] =
353       (struct drm_i915_gem_exec_object2) {
354          .handle = bo->gem_handle,
355          .offset = bo->gtt_offset,
356          .flags = bo->kflags | (writable ? EXEC_OBJECT_WRITE : 0),
357       };
358 
359    bo->index = batch->exec_count;
360    batch->exec_bos[batch->exec_count] = bo;
361    batch->aperture_space += bo->size;
362 
363    batch->exec_count++;
364 
365    return &batch->validation_list[batch->exec_count - 1];
366 }
367 
368 static uint64_t
emit_reloc(struct crocus_batch * batch,struct crocus_reloc_list * rlist,uint32_t offset,struct crocus_bo * target,int32_t target_offset,unsigned int reloc_flags)369 emit_reloc(struct crocus_batch *batch,
370            struct crocus_reloc_list *rlist, uint32_t offset,
371            struct crocus_bo *target, int32_t target_offset,
372            unsigned int reloc_flags)
373 {
374    assert(target != NULL);
375 
376    if (target == batch->ice->workaround_bo)
377       reloc_flags &= ~RELOC_WRITE;
378 
379    bool writable = reloc_flags & RELOC_WRITE;
380 
381    struct drm_i915_gem_exec_object2 *entry =
382       crocus_use_bo(batch, target, writable);
383 
384    if (rlist->reloc_count == rlist->reloc_array_size) {
385       rlist->reloc_array_size *= 2;
386       rlist->relocs = realloc(rlist->relocs,
387                               rlist->reloc_array_size *
388                               sizeof(struct drm_i915_gem_relocation_entry));
389    }
390 
391    if (reloc_flags & RELOC_32BIT) {
392       /* Restrict this buffer to the low 32 bits of the address space.
393        *
394        * Altering the validation list flags restricts it for this batch,
395        * but we also alter the BO's kflags to restrict it permanently
396        * (until the BO is destroyed and put back in the cache).  Buffers
397        * may stay bound across batches, and we want keep it constrained.
398        */
399       target->kflags &= ~EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
400       entry->flags &= ~EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
401 
402       /* RELOC_32BIT is not an EXEC_OBJECT_* flag, so get rid of it. */
403       reloc_flags &= ~RELOC_32BIT;
404    }
405 
406    if (reloc_flags)
407       entry->flags |= reloc_flags & batch->valid_reloc_flags;
408 
409    rlist->relocs[rlist->reloc_count++] =
410       (struct drm_i915_gem_relocation_entry) {
411          .offset = offset,
412          .delta = target_offset,
413          .target_handle = target->index,
414          .presumed_offset = entry->offset,
415       };
416 
417    /* Using the old buffer offset, write in what the right data would be, in
418     * case the buffer doesn't move and we can short-circuit the relocation
419     * processing in the kernel
420     */
421    return entry->offset + target_offset;
422 }
423 
424 uint64_t
crocus_command_reloc(struct crocus_batch * batch,uint32_t batch_offset,struct crocus_bo * target,uint32_t target_offset,unsigned int reloc_flags)425 crocus_command_reloc(struct crocus_batch *batch, uint32_t batch_offset,
426                      struct crocus_bo *target, uint32_t target_offset,
427                      unsigned int reloc_flags)
428 {
429    assert(batch_offset <= batch->command.bo->size - sizeof(uint32_t));
430 
431    return emit_reloc(batch, &batch->command.relocs, batch_offset,
432                      target, target_offset, reloc_flags);
433 }
434 
435 uint64_t
crocus_state_reloc(struct crocus_batch * batch,uint32_t state_offset,struct crocus_bo * target,uint32_t target_offset,unsigned int reloc_flags)436 crocus_state_reloc(struct crocus_batch *batch, uint32_t state_offset,
437                    struct crocus_bo *target, uint32_t target_offset,
438                    unsigned int reloc_flags)
439 {
440    assert(state_offset <= batch->state.bo->size - sizeof(uint32_t));
441 
442    return emit_reloc(batch, &batch->state.relocs, state_offset,
443                      target, target_offset, reloc_flags);
444 }
445 
446 static void
recreate_growing_buffer(struct crocus_batch * batch,struct crocus_growing_bo * grow,const char * name,unsigned size)447 recreate_growing_buffer(struct crocus_batch *batch,
448                         struct crocus_growing_bo *grow,
449                         const char *name, unsigned size)
450 {
451    struct crocus_screen *screen = batch->screen;
452    struct crocus_bufmgr *bufmgr = screen->bufmgr;
453    grow->bo = crocus_bo_alloc(bufmgr, name, size);
454    grow->bo->kflags |= EXEC_OBJECT_CAPTURE;
455    grow->partial_bo = NULL;
456    grow->partial_bo_map = NULL;
457    grow->partial_bytes = 0;
458    if (batch->use_shadow_copy)
459       grow->map = realloc(grow->map, grow->bo->size);
460    else
461       grow->map = crocus_bo_map(NULL, grow->bo, MAP_READ | MAP_WRITE);
462    grow->map_next = grow->map;
463 }
464 
465 static void
create_batch(struct crocus_batch * batch)466 create_batch(struct crocus_batch *batch)
467 {
468    struct crocus_screen *screen = batch->screen;
469 
470    recreate_growing_buffer(batch, &batch->command,
471                            "command buffer",
472                            BATCH_SZ + BATCH_RESERVED(&screen->devinfo));
473 
474    crocus_use_bo(batch, batch->command.bo, false);
475 
476    /* Always add workaround_bo which contains a driver identifier to be
477     * recorded in error states.
478     */
479    crocus_use_bo(batch, batch->ice->workaround_bo, false);
480 
481    recreate_growing_buffer(batch, &batch->state,
482                            "state buffer",
483                            STATE_SZ);
484 
485    batch->state.used = 1;
486    crocus_use_bo(batch, batch->state.bo, false);
487 }
488 
489 static void
crocus_batch_maybe_noop(struct crocus_batch * batch)490 crocus_batch_maybe_noop(struct crocus_batch *batch)
491 {
492    /* We only insert the NOOP at the beginning of the batch. */
493    assert(crocus_batch_bytes_used(batch) == 0);
494 
495    if (batch->noop_enabled) {
496       /* Emit MI_BATCH_BUFFER_END to prevent any further command to be
497        * executed.
498        */
499       uint32_t *map = batch->command.map_next;
500 
501       map[0] = (0xA << 23);
502 
503       batch->command.map_next += 4;
504    }
505 }
506 
507 static void
crocus_batch_reset(struct crocus_batch * batch)508 crocus_batch_reset(struct crocus_batch *batch)
509 {
510    struct crocus_screen *screen = batch->screen;
511 
512    crocus_bo_unreference(batch->command.bo);
513    crocus_bo_unreference(batch->state.bo);
514    batch->primary_batch_size = 0;
515    batch->contains_draw = false;
516    batch->contains_fence_signal = false;
517    batch->state_base_address_emitted = false;
518    batch->screen->vtbl.batch_reset_dirty(batch);
519 
520    create_batch(batch);
521    assert(batch->command.bo->index == 0);
522 
523    if (batch->state_sizes)
524       _mesa_hash_table_u64_clear(batch->state_sizes);
525    struct crocus_syncobj *syncobj = crocus_create_syncobj(screen);
526    crocus_batch_add_syncobj(batch, syncobj, I915_EXEC_FENCE_SIGNAL);
527    crocus_syncobj_reference(screen, &syncobj, NULL);
528 
529    crocus_cache_sets_clear(batch);
530 }
531 
532 void
crocus_batch_free(struct crocus_batch * batch)533 crocus_batch_free(struct crocus_batch *batch)
534 {
535    struct crocus_screen *screen = batch->screen;
536    struct crocus_bufmgr *bufmgr = screen->bufmgr;
537 
538    if (batch->use_shadow_copy) {
539       free(batch->command.map);
540       free(batch->state.map);
541    }
542 
543    for (int i = 0; i < batch->exec_count; i++) {
544       crocus_bo_unreference(batch->exec_bos[i]);
545    }
546 
547    pipe_resource_reference(&batch->fine_fences.ref.res, NULL);
548 
549    free(batch->command.relocs.relocs);
550    free(batch->state.relocs.relocs);
551    free(batch->exec_bos);
552    free(batch->validation_list);
553 
554    ralloc_free(batch->exec_fences.mem_ctx);
555 
556    util_dynarray_foreach(&batch->syncobjs, struct crocus_syncobj *, s)
557       crocus_syncobj_reference(screen, s, NULL);
558    ralloc_free(batch->syncobjs.mem_ctx);
559 
560    crocus_fine_fence_reference(batch->screen, &batch->last_fence, NULL);
561    if (batch_has_fine_fence(batch))
562       u_upload_destroy(batch->fine_fences.uploader);
563 
564    crocus_bo_unreference(batch->command.bo);
565    crocus_bo_unreference(batch->state.bo);
566    batch->command.bo = NULL;
567    batch->command.map = NULL;
568    batch->command.map_next = NULL;
569 
570    crocus_destroy_hw_context(bufmgr, batch->hw_ctx_id);
571 
572    _mesa_hash_table_destroy(batch->cache.render, NULL);
573    _mesa_set_destroy(batch->cache.depth, NULL);
574 
575    if (batch->state_sizes) {
576       _mesa_hash_table_u64_destroy(batch->state_sizes);
577       intel_batch_decode_ctx_finish(&batch->decoder);
578    }
579 }
580 
581 /**
582  * If we've chained to a secondary batch, or are getting near to the end,
583  * then flush.  This should only be called between draws.
584  */
585 void
crocus_batch_maybe_flush(struct crocus_batch * batch,unsigned estimate)586 crocus_batch_maybe_flush(struct crocus_batch *batch, unsigned estimate)
587 {
588    if (batch->command.bo != batch->exec_bos[0] ||
589        crocus_batch_bytes_used(batch) + estimate >= BATCH_SZ) {
590       crocus_batch_flush(batch);
591    }
592 }
593 
594 /**
595  * Finish copying the old batch/state buffer's contents to the new one
596  * after we tried to "grow" the buffer in an earlier operation.
597  */
598 static void
finish_growing_bos(struct crocus_growing_bo * grow)599 finish_growing_bos(struct crocus_growing_bo *grow)
600 {
601    struct crocus_bo *old_bo = grow->partial_bo;
602    if (!old_bo)
603       return;
604 
605    memcpy(grow->map, grow->partial_bo_map, grow->partial_bytes);
606 
607    grow->partial_bo = NULL;
608    grow->partial_bo_map = NULL;
609    grow->partial_bytes = 0;
610 
611    crocus_bo_unreference(old_bo);
612 }
613 
614 void
crocus_grow_buffer(struct crocus_batch * batch,bool grow_state,unsigned used,unsigned new_size)615 crocus_grow_buffer(struct crocus_batch *batch, bool grow_state,
616                    unsigned used,
617                    unsigned new_size)
618 {
619    struct crocus_screen *screen = batch->screen;
620    struct crocus_bufmgr *bufmgr = screen->bufmgr;
621    struct crocus_growing_bo *grow = grow_state ? &batch->state : &batch->command;
622    struct crocus_bo *bo = grow->bo;
623 
624    if (grow->partial_bo) {
625       /* We've already grown once, and now we need to do it again.
626        * Finish our last grow operation so we can start a new one.
627        * This should basically never happen.
628        */
629       finish_growing_bos(grow);
630    }
631 
632    struct crocus_bo *new_bo = crocus_bo_alloc(bufmgr, bo->name, new_size);
633 
634    /* Copy existing data to the new larger buffer */
635    grow->partial_bo_map = grow->map;
636 
637    if (batch->use_shadow_copy) {
638       /* We can't safely use realloc, as it may move the existing buffer,
639        * breaking existing pointers the caller may still be using.  Just
640        * malloc a new copy and memcpy it like the normal BO path.
641        *
642        * Use bo->size rather than new_size because the bufmgr may have
643        * rounded up the size, and we want the shadow size to match.
644        */
645       grow->map = malloc(new_bo->size);
646    } else {
647       grow->map = crocus_bo_map(NULL, new_bo, MAP_READ | MAP_WRITE);
648    }
649    /* Try to put the new BO at the same GTT offset as the old BO (which
650     * we're throwing away, so it doesn't need to be there).
651     *
652     * This guarantees that our relocations continue to work: values we've
653     * already written into the buffer, values we're going to write into the
654     * buffer, and the validation/relocation lists all will match.
655     *
656     * Also preserve kflags for EXEC_OBJECT_CAPTURE.
657     */
658    new_bo->gtt_offset = bo->gtt_offset;
659    new_bo->index = bo->index;
660    new_bo->kflags = bo->kflags;
661 
662    /* Batch/state buffers are per-context, and if we've run out of space,
663     * we must have actually used them before, so...they will be in the list.
664     */
665    assert(bo->index < batch->exec_count);
666    assert(batch->exec_bos[bo->index] == bo);
667 
668    /* Update the validation list to use the new BO. */
669    batch->validation_list[bo->index].handle = new_bo->gem_handle;
670    /* Exchange the two BOs...without breaking pointers to the old BO.
671     *
672     * Consider this scenario:
673     *
674     * 1. Somebody calls brw_state_batch() to get a region of memory, and
675     *    and then creates a brw_address pointing to brw->batch.state.bo.
676     * 2. They then call brw_state_batch() a second time, which happens to
677     *    grow and replace the state buffer.  They then try to emit a
678     *    relocation to their first section of memory.
679     *
680     * If we replace the brw->batch.state.bo pointer at step 2, we would
681     * break the address created in step 1.  They'd have a pointer to the
682     * old destroyed BO.  Emitting a relocation would add this dead BO to
683     * the validation list...causing /both/ statebuffers to be in the list,
684     * and all kinds of disasters.
685     *
686     * This is not a contrived case - BLORP vertex data upload hits this.
687     *
688     * There are worse scenarios too.  Fences for GL sync objects reference
689     * brw->batch.batch.bo.  If we replaced the batch pointer when growing,
690     * we'd need to chase down every fence and update it to point to the
691     * new BO.  Otherwise, it would refer to a "batch" that never actually
692     * gets submitted, and would fail to trigger.
693     *
694     * To work around both of these issues, we transmutate the buffers in
695     * place, making the existing struct brw_bo represent the new buffer,
696     * and "new_bo" represent the old BO.  This is highly unusual, but it
697     * seems like a necessary evil.
698     *
699     * We also defer the memcpy of the existing batch's contents.  Callers
700     * may make multiple brw_state_batch calls, and retain pointers to the
701     * old BO's map.  We'll perform the memcpy in finish_growing_bo() when
702     * we finally submit the batch, at which point we've finished uploading
703     * state, and nobody should have any old references anymore.
704     *
705     * To do that, we keep a reference to the old BO in grow->partial_bo,
706     * and store the number of bytes to copy in grow->partial_bytes.  We
707     * can monkey with the refcounts directly without atomics because these
708     * are per-context BOs and they can only be touched by this thread.
709     */
710    assert(new_bo->refcount == 1);
711    new_bo->refcount = bo->refcount;
712    bo->refcount = 1;
713 
714    struct crocus_bo tmp;
715    memcpy(&tmp, bo, sizeof(struct crocus_bo));
716    memcpy(bo, new_bo, sizeof(struct crocus_bo));
717    memcpy(new_bo, &tmp, sizeof(struct crocus_bo));
718 
719    grow->partial_bo = new_bo; /* the one reference of the OLD bo */
720    grow->partial_bytes = used;
721 }
722 
723 static void
finish_seqno(struct crocus_batch * batch)724 finish_seqno(struct crocus_batch *batch)
725 {
726    struct crocus_fine_fence *sq = crocus_fine_fence_new(batch, CROCUS_FENCE_END);
727    if (!sq)
728       return;
729 
730    crocus_fine_fence_reference(batch->screen, &batch->last_fence, sq);
731    crocus_fine_fence_reference(batch->screen, &sq, NULL);
732 }
733 
734 /**
735  * Terminate a batch with MI_BATCH_BUFFER_END.
736  */
737 static void
crocus_finish_batch(struct crocus_batch * batch)738 crocus_finish_batch(struct crocus_batch *batch)
739 {
740 
741    batch->no_wrap = true;
742    if (batch->screen->vtbl.finish_batch)
743       batch->screen->vtbl.finish_batch(batch);
744 
745    finish_seqno(batch);
746 
747    /* Emit MI_BATCH_BUFFER_END to finish our batch. */
748    uint32_t *map = batch->command.map_next;
749 
750    map[0] = (0xA << 23);
751 
752    batch->command.map_next += 4;
753    VG(VALGRIND_CHECK_MEM_IS_DEFINED(batch->command.map, crocus_batch_bytes_used(batch)));
754 
755    if (batch->command.bo == batch->exec_bos[0])
756       batch->primary_batch_size = crocus_batch_bytes_used(batch);
757    batch->no_wrap = false;
758 }
759 
760 /**
761  * Replace our current GEM context with a new one (in case it got banned).
762  */
763 static bool
replace_hw_ctx(struct crocus_batch * batch)764 replace_hw_ctx(struct crocus_batch *batch)
765 {
766    struct crocus_screen *screen = batch->screen;
767    struct crocus_bufmgr *bufmgr = screen->bufmgr;
768 
769    uint32_t new_ctx = crocus_clone_hw_context(bufmgr, batch->hw_ctx_id);
770    if (!new_ctx)
771       return false;
772 
773    crocus_destroy_hw_context(bufmgr, batch->hw_ctx_id);
774    batch->hw_ctx_id = new_ctx;
775 
776    /* Notify the context that state must be re-initialized. */
777    crocus_lost_context_state(batch);
778 
779    return true;
780 }
781 
782 enum pipe_reset_status
crocus_batch_check_for_reset(struct crocus_batch * batch)783 crocus_batch_check_for_reset(struct crocus_batch *batch)
784 {
785    struct crocus_screen *screen = batch->screen;
786    enum pipe_reset_status status = PIPE_NO_RESET;
787    struct drm_i915_reset_stats stats = { .ctx_id = batch->hw_ctx_id };
788 
789    if (drmIoctl(screen->fd, DRM_IOCTL_I915_GET_RESET_STATS, &stats))
790       DBG("DRM_IOCTL_I915_GET_RESET_STATS failed: %s\n", strerror(errno));
791 
792    if (stats.batch_active != 0) {
793       /* A reset was observed while a batch from this hardware context was
794        * executing.  Assume that this context was at fault.
795        */
796       status = PIPE_GUILTY_CONTEXT_RESET;
797    } else if (stats.batch_pending != 0) {
798       /* A reset was observed while a batch from this context was in progress,
799        * but the batch was not executing.  In this case, assume that the
800        * context was not at fault.
801        */
802       status = PIPE_INNOCENT_CONTEXT_RESET;
803    }
804 
805    if (status != PIPE_NO_RESET) {
806       /* Our context is likely banned, or at least in an unknown state.
807        * Throw it away and start with a fresh context.  Ideally this may
808        * catch the problem before our next execbuf fails with -EIO.
809        */
810       replace_hw_ctx(batch);
811    }
812 
813    return status;
814 }
815 
816 /**
817  * Submit the batch to the GPU via execbuffer2.
818  */
819 static int
submit_batch(struct crocus_batch * batch)820 submit_batch(struct crocus_batch *batch)
821 {
822 
823    if (batch->use_shadow_copy) {
824       void *bo_map = crocus_bo_map(batch->dbg, batch->command.bo, MAP_WRITE);
825       memcpy(bo_map, batch->command.map, crocus_batch_bytes_used(batch));
826 
827       bo_map = crocus_bo_map(batch->dbg, batch->state.bo, MAP_WRITE);
828       memcpy(bo_map, batch->state.map, batch->state.used);
829    }
830 
831    crocus_bo_unmap(batch->command.bo);
832    crocus_bo_unmap(batch->state.bo);
833 
834    /* The requirement for using I915_EXEC_NO_RELOC are:
835     *
836     *   The addresses written in the objects must match the corresponding
837     *   reloc.gtt_offset which in turn must match the corresponding
838     *   execobject.offset.
839     *
840     *   Any render targets written to in the batch must be flagged with
841     *   EXEC_OBJECT_WRITE.
842     *
843     *   To avoid stalling, execobject.offset should match the current
844     *   address of that object within the active context.
845     */
846    /* Set statebuffer relocations */
847    const unsigned state_index = batch->state.bo->index;
848    if (state_index < batch->exec_count &&
849        batch->exec_bos[state_index] == batch->state.bo) {
850       struct drm_i915_gem_exec_object2 *entry =
851          &batch->validation_list[state_index];
852       assert(entry->handle == batch->state.bo->gem_handle);
853       entry->relocation_count = batch->state.relocs.reloc_count;
854       entry->relocs_ptr = (uintptr_t)batch->state.relocs.relocs;
855    }
856 
857    /* Set batchbuffer relocations */
858    struct drm_i915_gem_exec_object2 *entry = &batch->validation_list[0];
859    assert(entry->handle == batch->command.bo->gem_handle);
860    entry->relocation_count = batch->command.relocs.reloc_count;
861    entry->relocs_ptr = (uintptr_t)batch->command.relocs.relocs;
862 
863    struct drm_i915_gem_execbuffer2 execbuf = {
864       .buffers_ptr = (uintptr_t)batch->validation_list,
865       .buffer_count = batch->exec_count,
866       .batch_start_offset = 0,
867       /* This must be QWord aligned. */
868       .batch_len = ALIGN(batch->primary_batch_size, 8),
869       .flags = I915_EXEC_RENDER |
870                I915_EXEC_NO_RELOC |
871                I915_EXEC_BATCH_FIRST |
872                I915_EXEC_HANDLE_LUT,
873       .rsvd1 = batch->hw_ctx_id, /* rsvd1 is actually the context ID */
874    };
875 
876    if (num_fences(batch)) {
877       execbuf.flags |= I915_EXEC_FENCE_ARRAY;
878       execbuf.num_cliprects = num_fences(batch);
879       execbuf.cliprects_ptr =
880          (uintptr_t)util_dynarray_begin(&batch->exec_fences);
881    }
882 
883    int ret = 0;
884    if (!batch->screen->devinfo.no_hw &&
885        intel_ioctl(batch->screen->fd, DRM_IOCTL_I915_GEM_EXECBUFFER2, &execbuf))
886       ret = -errno;
887 
888    for (int i = 0; i < batch->exec_count; i++) {
889       struct crocus_bo *bo = batch->exec_bos[i];
890 
891       bo->idle = false;
892       bo->index = -1;
893 
894       /* Update brw_bo::gtt_offset */
895       if (batch->validation_list[i].offset != bo->gtt_offset) {
896          DBG("BO %d migrated: 0x%" PRIx64 " -> 0x%" PRIx64 "\n",
897              bo->gem_handle, bo->gtt_offset,
898              (uint64_t)batch->validation_list[i].offset);
899          assert(!(bo->kflags & EXEC_OBJECT_PINNED));
900          bo->gtt_offset = batch->validation_list[i].offset;
901       }
902    }
903 
904    return ret;
905 }
906 
907 static const char *
batch_name_to_string(enum crocus_batch_name name)908 batch_name_to_string(enum crocus_batch_name name)
909 {
910    const char *names[CROCUS_BATCH_COUNT] = {
911       [CROCUS_BATCH_RENDER] = "render",
912       [CROCUS_BATCH_COMPUTE] = "compute",
913    };
914    return names[name];
915 }
916 
917 /**
918  * Flush the batch buffer, submitting it to the GPU and resetting it so
919  * we're ready to emit the next batch.
920  *
921  * \param in_fence_fd is ignored if -1.  Otherwise, this function takes
922  * ownership of the fd.
923  *
924  * \param out_fence_fd is ignored if NULL.  Otherwise, the caller must
925  * take ownership of the returned fd.
926  */
927 void
_crocus_batch_flush(struct crocus_batch * batch,const char * file,int line)928 _crocus_batch_flush(struct crocus_batch *batch, const char *file, int line)
929 {
930    struct crocus_screen *screen = batch->screen;
931 
932    /* If a fence signals we need to flush it. */
933    if (crocus_batch_bytes_used(batch) == 0 && !batch->contains_fence_signal)
934       return;
935 
936    assert(!batch->no_wrap);
937    crocus_finish_batch(batch);
938 
939    finish_growing_bos(&batch->command);
940    finish_growing_bos(&batch->state);
941    int ret = submit_batch(batch);
942 
943    if (INTEL_DEBUG(DEBUG_BATCH | DEBUG_SUBMIT | DEBUG_PIPE_CONTROL)) {
944       int bytes_for_commands = crocus_batch_bytes_used(batch);
945       int second_bytes = 0;
946       if (batch->command.bo != batch->exec_bos[0]) {
947          second_bytes = bytes_for_commands;
948          bytes_for_commands += batch->primary_batch_size;
949       }
950       fprintf(stderr, "%19s:%-3d: %s batch [%u] flush with %5d+%5db (%0.1f%%) "
951               "(cmds), %4d BOs (%0.1fMb aperture),"
952               " %4d command relocs, %4d state relocs\n",
953               file, line, batch_name_to_string(batch->name), batch->hw_ctx_id,
954               batch->primary_batch_size, second_bytes,
955               100.0f * bytes_for_commands / BATCH_SZ,
956               batch->exec_count,
957               (float) batch->aperture_space / (1024 * 1024),
958               batch->command.relocs.reloc_count,
959               batch->state.relocs.reloc_count);
960 
961       if (INTEL_DEBUG(DEBUG_BATCH | DEBUG_SUBMIT)) {
962          dump_fence_list(batch);
963          dump_validation_list(batch);
964       }
965 
966       if (INTEL_DEBUG(DEBUG_BATCH)) {
967          decode_batch(batch);
968       }
969    }
970 
971    for (int i = 0; i < batch->exec_count; i++) {
972       struct crocus_bo *bo = batch->exec_bos[i];
973       crocus_bo_unreference(bo);
974    }
975 
976    batch->command.relocs.reloc_count = 0;
977    batch->state.relocs.reloc_count = 0;
978    batch->exec_count = 0;
979    batch->aperture_space = 0;
980 
981    util_dynarray_foreach(&batch->syncobjs, struct crocus_syncobj *, s)
982       crocus_syncobj_reference(screen, s, NULL);
983    util_dynarray_clear(&batch->syncobjs);
984 
985    util_dynarray_clear(&batch->exec_fences);
986 
987    if (INTEL_DEBUG(DEBUG_SYNC)) {
988       dbg_printf("waiting for idle\n");
989       crocus_bo_wait_rendering(batch->command.bo); /* if execbuf failed; this is a nop */
990    }
991 
992    /* Start a new batch buffer. */
993    crocus_batch_reset(batch);
994 
995    /* EIO means our context is banned.  In this case, try and replace it
996     * with a new logical context, and inform crocus_context that all state
997     * has been lost and needs to be re-initialized.  If this succeeds,
998     * dubiously claim success...
999     */
1000    if (ret == -EIO && replace_hw_ctx(batch)) {
1001       if (batch->reset->reset) {
1002          /* Tell the state tracker the device is lost and it was our fault. */
1003          batch->reset->reset(batch->reset->data, PIPE_GUILTY_CONTEXT_RESET);
1004       }
1005 
1006       ret = 0;
1007    }
1008 
1009    if (ret < 0) {
1010 #ifdef DEBUG
1011       const bool color = INTEL_DEBUG(DEBUG_COLOR);
1012       fprintf(stderr, "%scrocus: Failed to submit batchbuffer: %-80s%s\n",
1013               color ? "\e[1;41m" : "", strerror(-ret), color ? "\e[0m" : "");
1014 #endif
1015       abort();
1016    }
1017 }
1018 
1019 /**
1020  * Does the current batch refer to the given BO?
1021  *
1022  * (In other words, is the BO in the current batch's validation list?)
1023  */
1024 bool
crocus_batch_references(struct crocus_batch * batch,struct crocus_bo * bo)1025 crocus_batch_references(struct crocus_batch *batch, struct crocus_bo *bo)
1026 {
1027    return find_validation_entry(batch, bo) != NULL;
1028 }
1029 
1030 /**
1031  * Updates the state of the noop feature.  Returns true if there was a noop
1032  * transition that led to state invalidation.
1033  */
1034 bool
crocus_batch_prepare_noop(struct crocus_batch * batch,bool noop_enable)1035 crocus_batch_prepare_noop(struct crocus_batch *batch, bool noop_enable)
1036 {
1037    if (batch->noop_enabled == noop_enable)
1038       return 0;
1039 
1040    batch->noop_enabled = noop_enable;
1041 
1042    crocus_batch_flush(batch);
1043 
1044    /* If the batch was empty, flush had no effect, so insert our noop. */
1045    if (crocus_batch_bytes_used(batch) == 0)
1046       crocus_batch_maybe_noop(batch);
1047 
1048    /* We only need to update the entire state if we transition from noop ->
1049     * not-noop.
1050     */
1051    return !batch->noop_enabled;
1052 }
1053