iris: Hook up device reset callbacks
[mesa.git] / src / gallium / drivers / iris / iris_batch.c
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 iris_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 "iris_batch.h"
41 #include "iris_bufmgr.h"
42 #include "iris_context.h"
43 #include "iris_fence.h"
44
45 #include "drm-uapi/i915_drm.h"
46
47 #include "util/hash_table.h"
48 #include "util/set.h"
49 #include "main/macros.h"
50
51 #include <errno.h>
52 #include <xf86drm.h>
53
54 #if HAVE_VALGRIND
55 #include <valgrind.h>
56 #include <memcheck.h>
57 #define VG(x) x
58 #else
59 #define VG(x)
60 #endif
61
62 #define FILE_DEBUG_FLAG DEBUG_BUFMGR
63
64 /* Terminating the batch takes either 4 bytes for MI_BATCH_BUFFER_END
65 * or 12 bytes for MI_BATCH_BUFFER_START (when chaining). Plus, we may
66 * need an extra 4 bytes to pad out to the nearest QWord. So reserve 16.
67 */
68 #define BATCH_RESERVED 16
69
70 static void
71 iris_batch_reset(struct iris_batch *batch);
72
73 static unsigned
74 num_fences(struct iris_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
84 dump_fence_list(struct iris_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
103 dump_validation_list(struct iris_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, "[%2d]: %2d %-14s @ 0x%016llx (%"PRIu64"B)\t %2d refs %s\n",
112 i,
113 batch->validation_list[i].handle,
114 batch->exec_bos[i]->name,
115 batch->validation_list[i].offset,
116 batch->exec_bos[i]->size,
117 batch->exec_bos[i]->refcount,
118 (flags & EXEC_OBJECT_WRITE) ? " (write)" : "");
119 }
120 }
121
122 /**
123 * Return BO information to the batch decoder (for debugging).
124 */
125 static struct gen_batch_decode_bo
126 decode_get_bo(void *v_batch, bool ppgtt, uint64_t address)
127 {
128 struct iris_batch *batch = v_batch;
129
130 assert(ppgtt);
131
132 for (int i = 0; i < batch->exec_count; i++) {
133 struct iris_bo *bo = batch->exec_bos[i];
134 /* The decoder zeroes out the top 16 bits, so we need to as well */
135 uint64_t bo_address = bo->gtt_offset & (~0ull >> 16);
136
137 if (address >= bo_address && address < bo_address + bo->size) {
138 return (struct gen_batch_decode_bo) {
139 .addr = address,
140 .size = bo->size,
141 .map = iris_bo_map(batch->dbg, bo, MAP_READ) +
142 (address - bo_address),
143 };
144 }
145 }
146
147 return (struct gen_batch_decode_bo) { };
148 }
149
150 /**
151 * Decode the current batch.
152 */
153 static void
154 decode_batch(struct iris_batch *batch)
155 {
156 void *map = iris_bo_map(batch->dbg, batch->exec_bos[0], MAP_READ);
157 gen_print_batch(&batch->decoder, map, batch->primary_batch_size,
158 batch->exec_bos[0]->gtt_offset, false);
159 }
160
161 void
162 iris_init_batch(struct iris_batch *batch,
163 struct iris_screen *screen,
164 struct iris_vtable *vtbl,
165 struct pipe_debug_callback *dbg,
166 struct pipe_device_reset_callback *reset,
167 struct iris_batch *all_batches,
168 enum iris_batch_name name,
169 uint8_t engine,
170 int priority)
171 {
172 batch->screen = screen;
173 batch->vtbl = vtbl;
174 batch->dbg = dbg;
175 batch->reset = reset;
176 batch->name = name;
177
178 /* engine should be one of I915_EXEC_RENDER, I915_EXEC_BLT, etc. */
179 assert((engine & ~I915_EXEC_RING_MASK) == 0);
180 assert(util_bitcount(engine) == 1);
181 batch->engine = engine;
182
183 batch->hw_ctx_id = iris_create_hw_context(screen->bufmgr);
184 assert(batch->hw_ctx_id);
185
186 iris_hw_context_set_priority(screen->bufmgr, batch->hw_ctx_id, priority);
187
188 util_dynarray_init(&batch->exec_fences, ralloc_context(NULL));
189 util_dynarray_init(&batch->syncpts, ralloc_context(NULL));
190
191 batch->exec_count = 0;
192 batch->exec_array_size = 100;
193 batch->exec_bos =
194 malloc(batch->exec_array_size * sizeof(batch->exec_bos[0]));
195 batch->validation_list =
196 malloc(batch->exec_array_size * sizeof(batch->validation_list[0]));
197
198 batch->cache.render = _mesa_hash_table_create(NULL, _mesa_hash_pointer,
199 _mesa_key_pointer_equal);
200 batch->cache.depth = _mesa_set_create(NULL, _mesa_hash_pointer,
201 _mesa_key_pointer_equal);
202
203 memset(batch->other_batches, 0, sizeof(batch->other_batches));
204
205 for (int i = 0, j = 0; i < IRIS_BATCH_COUNT; i++) {
206 if (&all_batches[i] != batch)
207 batch->other_batches[j++] = &all_batches[i];
208 }
209
210 if (unlikely(INTEL_DEBUG)) {
211 const unsigned decode_flags =
212 GEN_BATCH_DECODE_FULL |
213 ((INTEL_DEBUG & DEBUG_COLOR) ? GEN_BATCH_DECODE_IN_COLOR : 0) |
214 GEN_BATCH_DECODE_OFFSETS |
215 GEN_BATCH_DECODE_FLOATS;
216
217 /* TODO: track state size so we can print the right # of entries */
218 gen_batch_decode_ctx_init(&batch->decoder, &screen->devinfo,
219 stderr, decode_flags, NULL,
220 decode_get_bo, NULL, batch);
221 batch->decoder.max_vbo_decoded_lines = 32;
222 }
223
224 iris_batch_reset(batch);
225 }
226
227 static struct drm_i915_gem_exec_object2 *
228 find_validation_entry(struct iris_batch *batch, struct iris_bo *bo)
229 {
230 unsigned index = READ_ONCE(bo->index);
231
232 if (index < batch->exec_count && batch->exec_bos[index] == bo)
233 return &batch->validation_list[index];
234
235 /* May have been shared between multiple active batches */
236 for (index = 0; index < batch->exec_count; index++) {
237 if (batch->exec_bos[index] == bo)
238 return &batch->validation_list[index];
239 }
240
241 return NULL;
242 }
243
244 /**
245 * Add a buffer to the current batch's validation list.
246 *
247 * You must call this on any BO you wish to use in this batch, to ensure
248 * that it's resident when the GPU commands execute.
249 */
250 void
251 iris_use_pinned_bo(struct iris_batch *batch,
252 struct iris_bo *bo,
253 bool writable)
254 {
255 assert(bo->kflags & EXEC_OBJECT_PINNED);
256
257 /* Never mark the workaround BO with EXEC_OBJECT_WRITE. We don't care
258 * about the order of any writes to that buffer, and marking it writable
259 * would introduce data dependencies between multiple batches which share
260 * the buffer.
261 */
262 if (bo == batch->screen->workaround_bo)
263 writable = false;
264
265 struct drm_i915_gem_exec_object2 *existing_entry =
266 find_validation_entry(batch, bo);
267
268 if (existing_entry) {
269 /* The BO is already in the validation list; mark it writable */
270 if (writable)
271 existing_entry->flags |= EXEC_OBJECT_WRITE;
272
273 return;
274 }
275
276 if (bo != batch->bo) {
277 /* This is the first time our batch has seen this BO. Before we use it,
278 * we may need to flush and synchronize with other batches.
279 */
280 for (int b = 0; b < ARRAY_SIZE(batch->other_batches); b++) {
281 struct drm_i915_gem_exec_object2 *other_entry =
282 find_validation_entry(batch->other_batches[b], bo);
283
284 /* If the buffer is referenced by another batch, and either batch
285 * intends to write it, then flush the other batch and synchronize.
286 *
287 * Consider these cases:
288 *
289 * 1. They read, we read => No synchronization required.
290 * 2. They read, we write => Synchronize (they need the old value)
291 * 3. They write, we read => Synchronize (we need their new value)
292 * 4. They write, we write => Synchronize (order writes)
293 *
294 * The read/read case is very common, as multiple batches usually
295 * share a streaming state buffer or shader assembly buffer, and
296 * we want to avoid synchronizing in this case.
297 */
298 if (other_entry &&
299 ((other_entry->flags & EXEC_OBJECT_WRITE) || writable)) {
300 iris_batch_flush(batch->other_batches[b]);
301 iris_batch_add_syncpt(batch, batch->other_batches[b]->last_syncpt,
302 I915_EXEC_FENCE_WAIT);
303 }
304 }
305 }
306
307 /* Now, take a reference and add it to the validation list. */
308 iris_bo_reference(bo);
309
310 if (batch->exec_count == batch->exec_array_size) {
311 batch->exec_array_size *= 2;
312 batch->exec_bos =
313 realloc(batch->exec_bos,
314 batch->exec_array_size * sizeof(batch->exec_bos[0]));
315 batch->validation_list =
316 realloc(batch->validation_list,
317 batch->exec_array_size * sizeof(batch->validation_list[0]));
318 }
319
320 batch->validation_list[batch->exec_count] =
321 (struct drm_i915_gem_exec_object2) {
322 .handle = bo->gem_handle,
323 .offset = bo->gtt_offset,
324 .flags = bo->kflags | (writable ? EXEC_OBJECT_WRITE : 0),
325 };
326
327 bo->index = batch->exec_count;
328 batch->exec_bos[batch->exec_count] = bo;
329 batch->aperture_space += bo->size;
330
331 batch->exec_count++;
332 }
333
334 static void
335 create_batch(struct iris_batch *batch)
336 {
337 struct iris_screen *screen = batch->screen;
338 struct iris_bufmgr *bufmgr = screen->bufmgr;
339
340 batch->bo = iris_bo_alloc(bufmgr, "command buffer",
341 BATCH_SZ + BATCH_RESERVED, IRIS_MEMZONE_OTHER);
342 batch->bo->kflags |= EXEC_OBJECT_CAPTURE;
343 batch->map = iris_bo_map(NULL, batch->bo, MAP_READ | MAP_WRITE);
344 batch->map_next = batch->map;
345
346 iris_use_pinned_bo(batch, batch->bo, false);
347 }
348
349 static void
350 iris_batch_reset(struct iris_batch *batch)
351 {
352 struct iris_screen *screen = batch->screen;
353
354 iris_bo_unreference(batch->bo);
355 batch->primary_batch_size = 0;
356 batch->contains_draw = false;
357
358 create_batch(batch);
359 assert(batch->bo->index == 0);
360
361 struct iris_syncpt *syncpt = iris_create_syncpt(screen);
362 iris_batch_add_syncpt(batch, syncpt, I915_EXEC_FENCE_SIGNAL);
363 iris_syncpt_reference(screen, &syncpt, NULL);
364
365 iris_cache_sets_clear(batch);
366 }
367
368 void
369 iris_batch_free(struct iris_batch *batch)
370 {
371 struct iris_screen *screen = batch->screen;
372 struct iris_bufmgr *bufmgr = screen->bufmgr;
373
374 for (int i = 0; i < batch->exec_count; i++) {
375 iris_bo_unreference(batch->exec_bos[i]);
376 }
377 free(batch->exec_bos);
378 free(batch->validation_list);
379
380 ralloc_free(batch->exec_fences.mem_ctx);
381
382 util_dynarray_foreach(&batch->syncpts, struct iris_syncpt *, s)
383 iris_syncpt_reference(screen, s, NULL);
384 ralloc_free(batch->syncpts.mem_ctx);
385
386 iris_syncpt_reference(screen, &batch->last_syncpt, NULL);
387
388 iris_bo_unreference(batch->bo);
389 batch->bo = NULL;
390 batch->map = NULL;
391 batch->map_next = NULL;
392
393 iris_destroy_hw_context(bufmgr, batch->hw_ctx_id);
394
395 _mesa_hash_table_destroy(batch->cache.render, NULL);
396 _mesa_set_destroy(batch->cache.depth, NULL);
397
398 if (unlikely(INTEL_DEBUG))
399 gen_batch_decode_ctx_finish(&batch->decoder);
400 }
401
402 /**
403 * If we've chained to a secondary batch, or are getting near to the end,
404 * then flush. This should only be called between draws.
405 */
406 void
407 iris_batch_maybe_flush(struct iris_batch *batch, unsigned estimate)
408 {
409 if (batch->bo != batch->exec_bos[0] ||
410 iris_batch_bytes_used(batch) + estimate >= BATCH_SZ) {
411 iris_batch_flush(batch);
412 }
413 }
414
415 void
416 iris_chain_to_new_batch(struct iris_batch *batch)
417 {
418 /* We only support chaining a single time. */
419 assert(batch->bo == batch->exec_bos[0]);
420
421 VG(void *map = batch->map);
422 uint32_t *cmd = batch->map_next;
423 uint64_t *addr = batch->map_next + 4;
424 batch->map_next += 12;
425
426 /* No longer held by batch->bo, still held by validation list */
427 iris_bo_unreference(batch->bo);
428 batch->primary_batch_size = iris_batch_bytes_used(batch);
429 create_batch(batch);
430
431 /* Emit MI_BATCH_BUFFER_START to chain to another batch. */
432 *cmd = (0x31 << 23) | (1 << 8) | (3 - 2);
433 *addr = batch->bo->gtt_offset;
434
435 VG(VALGRIND_CHECK_MEM_IS_DEFINED(map, batch->primary_batch_size));
436 }
437
438 /**
439 * Terminate a batch with MI_BATCH_BUFFER_END.
440 */
441 static void
442 iris_finish_batch(struct iris_batch *batch)
443 {
444 /* Emit MI_BATCH_BUFFER_END to finish our batch. */
445 uint32_t *map = batch->map_next;
446
447 map[0] = (0xA << 23);
448
449 batch->map_next += 4;
450 VG(VALGRIND_CHECK_MEM_IS_DEFINED(batch->map, iris_batch_bytes_used(batch)));
451
452 if (batch->bo == batch->exec_bos[0])
453 batch->primary_batch_size = iris_batch_bytes_used(batch);
454 }
455
456 /**
457 * Replace our current GEM context with a new one (in case it got banned).
458 */
459 static bool
460 replace_hw_ctx(struct iris_batch *batch)
461 {
462 struct iris_screen *screen = batch->screen;
463 struct iris_bufmgr *bufmgr = screen->bufmgr;
464
465 uint32_t new_ctx = iris_clone_hw_context(bufmgr, batch->hw_ctx_id);
466 if (!new_ctx)
467 return false;
468
469 iris_destroy_hw_context(bufmgr, batch->hw_ctx_id);
470 batch->hw_ctx_id = new_ctx;
471
472 /* Notify the context that state must be re-initialized. */
473 iris_lost_context_state(batch);
474
475 return true;
476 }
477
478 /**
479 * Submit the batch to the GPU via execbuffer2.
480 */
481 static int
482 submit_batch(struct iris_batch *batch)
483 {
484 iris_bo_unmap(batch->bo);
485
486 /* The requirement for using I915_EXEC_NO_RELOC are:
487 *
488 * The addresses written in the objects must match the corresponding
489 * reloc.gtt_offset which in turn must match the corresponding
490 * execobject.offset.
491 *
492 * Any render targets written to in the batch must be flagged with
493 * EXEC_OBJECT_WRITE.
494 *
495 * To avoid stalling, execobject.offset should match the current
496 * address of that object within the active context.
497 */
498 struct drm_i915_gem_execbuffer2 execbuf = {
499 .buffers_ptr = (uintptr_t) batch->validation_list,
500 .buffer_count = batch->exec_count,
501 .batch_start_offset = 0,
502 /* This must be QWord aligned. */
503 .batch_len = ALIGN(batch->primary_batch_size, 8),
504 .flags = batch->engine |
505 I915_EXEC_NO_RELOC |
506 I915_EXEC_BATCH_FIRST |
507 I915_EXEC_HANDLE_LUT,
508 .rsvd1 = batch->hw_ctx_id, /* rsvd1 is actually the context ID */
509 };
510
511 if (num_fences(batch)) {
512 execbuf.flags |= I915_EXEC_FENCE_ARRAY;
513 execbuf.num_cliprects = num_fences(batch);
514 execbuf.cliprects_ptr =
515 (uintptr_t)util_dynarray_begin(&batch->exec_fences);
516 }
517
518 int ret = 0;
519 if (!batch->screen->no_hw &&
520 drm_ioctl(batch->screen->fd, DRM_IOCTL_I915_GEM_EXECBUFFER2, &execbuf))
521 ret = -errno;
522
523 for (int i = 0; i < batch->exec_count; i++) {
524 struct iris_bo *bo = batch->exec_bos[i];
525
526 bo->idle = false;
527 bo->index = -1;
528
529 iris_bo_unreference(bo);
530 }
531
532 return ret;
533 }
534
535 static const char *
536 batch_name_to_string(enum iris_batch_name name)
537 {
538 const char *names[IRIS_BATCH_COUNT] = {
539 [IRIS_BATCH_RENDER] = "render",
540 [IRIS_BATCH_COMPUTE] = "compute",
541 };
542 return names[name];
543 }
544
545 /**
546 * Flush the batch buffer, submitting it to the GPU and resetting it so
547 * we're ready to emit the next batch.
548 *
549 * \param in_fence_fd is ignored if -1. Otherwise, this function takes
550 * ownership of the fd.
551 *
552 * \param out_fence_fd is ignored if NULL. Otherwise, the caller must
553 * take ownership of the returned fd.
554 */
555 void
556 _iris_batch_flush(struct iris_batch *batch, const char *file, int line)
557 {
558 struct iris_screen *screen = batch->screen;
559
560 if (iris_batch_bytes_used(batch) == 0)
561 return;
562
563 iris_finish_batch(batch);
564
565 if (unlikely(INTEL_DEBUG & (DEBUG_BATCH | DEBUG_SUBMIT))) {
566 int bytes_for_commands = iris_batch_bytes_used(batch);
567 int second_bytes = 0;
568 if (batch->bo != batch->exec_bos[0]) {
569 second_bytes = bytes_for_commands;
570 bytes_for_commands += batch->primary_batch_size;
571 }
572 fprintf(stderr, "%19s:%-3d: %s batch [%u] flush with %5d+%5db (%0.1f%%) "
573 "(cmds), %4d BOs (%0.1fMb aperture)\n",
574 file, line, batch_name_to_string(batch->name), batch->hw_ctx_id,
575 batch->primary_batch_size, second_bytes,
576 100.0f * bytes_for_commands / BATCH_SZ,
577 batch->exec_count,
578 (float) batch->aperture_space / (1024 * 1024));
579 dump_fence_list(batch);
580 dump_validation_list(batch);
581 }
582
583 if (unlikely(INTEL_DEBUG & DEBUG_BATCH)) {
584 decode_batch(batch);
585 }
586
587 int ret = submit_batch(batch);
588
589 batch->exec_count = 0;
590 batch->aperture_space = 0;
591
592 struct iris_syncpt *syncpt =
593 ((struct iris_syncpt **) util_dynarray_begin(&batch->syncpts))[0];
594 iris_syncpt_reference(screen, &batch->last_syncpt, syncpt);
595
596 util_dynarray_foreach(&batch->syncpts, struct iris_syncpt *, s)
597 iris_syncpt_reference(screen, s, NULL);
598 util_dynarray_clear(&batch->syncpts);
599
600 util_dynarray_clear(&batch->exec_fences);
601
602 if (unlikely(INTEL_DEBUG & DEBUG_SYNC)) {
603 dbg_printf("waiting for idle\n");
604 iris_bo_wait_rendering(batch->bo); /* if execbuf failed; this is a nop */
605 }
606
607 /* Start a new batch buffer. */
608 iris_batch_reset(batch);
609
610 /* EIO means our context is banned. In this case, try and replace it
611 * with a new logical context, and inform iris_context that all state
612 * has been lost and needs to be re-initialized. If this succeeds,
613 * dubiously claim success...
614 */
615 if (ret == -EIO && replace_hw_ctx(batch)) {
616 if (batch->reset->reset) {
617 /* Tell the state tracker the device is lost and it was our fault. */
618 batch->reset->reset(batch->reset->data, PIPE_GUILTY_CONTEXT_RESET);
619 }
620
621 ret = 0;
622 }
623
624 if (ret >= 0) {
625 //if (iris->ctx.Const.ResetStrategy == GL_LOSE_CONTEXT_ON_RESET_ARB)
626 //iris_check_for_reset(ice);
627 } else {
628 #ifdef DEBUG
629 const bool color = INTEL_DEBUG & DEBUG_COLOR;
630 fprintf(stderr, "%siris: Failed to submit batchbuffer: %-80s%s\n",
631 color ? "\e[1;41m" : "", strerror(-ret), color ? "\e[0m" : "");
632 #endif
633 abort();
634 }
635 }
636
637 /**
638 * Does the current batch refer to the given BO?
639 *
640 * (In other words, is the BO in the current batch's validation list?)
641 */
642 bool
643 iris_batch_references(struct iris_batch *batch, struct iris_bo *bo)
644 {
645 return find_validation_entry(batch, bo) != NULL;
646 }