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