1 /*
2  * Copyright © 2008 Jérôme Glisse
3  * Copyright © 2010 Marek Olšák <maraeo@gmail.com>
4  * Copyright © 2015 Advanced Micro Devices, Inc.
5  * All Rights Reserved.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining
8  * a copy of this software and associated documentation files (the
9  * "Software"), to deal in the Software without restriction, including
10  * without limitation the rights to use, copy, modify, merge, publish,
11  * distribute, sub license, and/or sell copies of the Software, and to
12  * permit persons to whom the Software is furnished to do so, subject to
13  * the following conditions:
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
17  * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18  * NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS, AUTHORS
19  * AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
22  * USE OR OTHER DEALINGS IN THE SOFTWARE.
23  *
24  * The above copyright notice and this permission notice (including the
25  * next paragraph) shall be included in all copies or substantial portions
26  * of the Software.
27  */
28 
29 #include "amdgpu_cs.h"
30 #include "util/os_time.h"
31 #include <inttypes.h>
32 #include <stdio.h>
33 
34 #include "amd/common/sid.h"
35 
36 /* FENCES */
37 
38 static struct pipe_fence_handle *
amdgpu_fence_create(struct amdgpu_ctx * ctx,unsigned ip_type,unsigned ip_instance,unsigned ring)39 amdgpu_fence_create(struct amdgpu_ctx *ctx, unsigned ip_type,
40                     unsigned ip_instance, unsigned ring)
41 {
42    struct amdgpu_fence *fence = CALLOC_STRUCT(amdgpu_fence);
43 
44    fence->reference.count = 1;
45    fence->ws = ctx->ws;
46    fence->ctx = ctx;
47    fence->fence.context = ctx->ctx;
48    fence->fence.ip_type = ip_type;
49    fence->fence.ip_instance = ip_instance;
50    fence->fence.ring = ring;
51    util_queue_fence_init(&fence->submitted);
52    util_queue_fence_reset(&fence->submitted);
53    p_atomic_inc(&ctx->refcount);
54    return (struct pipe_fence_handle *)fence;
55 }
56 
57 static struct pipe_fence_handle *
amdgpu_fence_import_syncobj(struct radeon_winsys * rws,int fd)58 amdgpu_fence_import_syncobj(struct radeon_winsys *rws, int fd)
59 {
60    struct amdgpu_winsys *ws = amdgpu_winsys(rws);
61    struct amdgpu_fence *fence = CALLOC_STRUCT(amdgpu_fence);
62    int r;
63 
64    if (!fence)
65       return NULL;
66 
67    pipe_reference_init(&fence->reference, 1);
68    fence->ws = ws;
69 
70    r = amdgpu_cs_import_syncobj(ws->dev, fd, &fence->syncobj);
71    if (r) {
72       FREE(fence);
73       return NULL;
74    }
75 
76    util_queue_fence_init(&fence->submitted);
77 
78    assert(amdgpu_fence_is_syncobj(fence));
79    return (struct pipe_fence_handle*)fence;
80 }
81 
82 static struct pipe_fence_handle *
amdgpu_fence_import_sync_file(struct radeon_winsys * rws,int fd)83 amdgpu_fence_import_sync_file(struct radeon_winsys *rws, int fd)
84 {
85    struct amdgpu_winsys *ws = amdgpu_winsys(rws);
86    struct amdgpu_fence *fence = CALLOC_STRUCT(amdgpu_fence);
87 
88    if (!fence)
89       return NULL;
90 
91    pipe_reference_init(&fence->reference, 1);
92    fence->ws = ws;
93    /* fence->ctx == NULL means that the fence is syncobj-based. */
94 
95    /* Convert sync_file into syncobj. */
96    int r = amdgpu_cs_create_syncobj(ws->dev, &fence->syncobj);
97    if (r) {
98       FREE(fence);
99       return NULL;
100    }
101 
102    r = amdgpu_cs_syncobj_import_sync_file(ws->dev, fence->syncobj, fd);
103    if (r) {
104       amdgpu_cs_destroy_syncobj(ws->dev, fence->syncobj);
105       FREE(fence);
106       return NULL;
107    }
108 
109    util_queue_fence_init(&fence->submitted);
110 
111    return (struct pipe_fence_handle*)fence;
112 }
113 
amdgpu_fence_export_sync_file(struct radeon_winsys * rws,struct pipe_fence_handle * pfence)114 static int amdgpu_fence_export_sync_file(struct radeon_winsys *rws,
115 					 struct pipe_fence_handle *pfence)
116 {
117    struct amdgpu_winsys *ws = amdgpu_winsys(rws);
118    struct amdgpu_fence *fence = (struct amdgpu_fence*)pfence;
119 
120    if (amdgpu_fence_is_syncobj(fence)) {
121       int fd, r;
122 
123       /* Convert syncobj into sync_file. */
124       r = amdgpu_cs_syncobj_export_sync_file(ws->dev, fence->syncobj, &fd);
125       return r ? -1 : fd;
126    }
127 
128    util_queue_fence_wait(&fence->submitted);
129 
130    /* Convert the amdgpu fence into a fence FD. */
131    int fd;
132    if (amdgpu_cs_fence_to_handle(ws->dev, &fence->fence,
133                                  AMDGPU_FENCE_TO_HANDLE_GET_SYNC_FILE_FD,
134                                  (uint32_t*)&fd))
135       return -1;
136 
137    return fd;
138 }
139 
amdgpu_export_signalled_sync_file(struct radeon_winsys * rws)140 static int amdgpu_export_signalled_sync_file(struct radeon_winsys *rws)
141 {
142    struct amdgpu_winsys *ws = amdgpu_winsys(rws);
143    uint32_t syncobj;
144    int fd = -1;
145 
146    int r = amdgpu_cs_create_syncobj2(ws->dev, DRM_SYNCOBJ_CREATE_SIGNALED,
147                                      &syncobj);
148    if (r) {
149       return -1;
150    }
151 
152    r = amdgpu_cs_syncobj_export_sync_file(ws->dev, syncobj, &fd);
153    if (r) {
154       fd = -1;
155    }
156 
157    amdgpu_cs_destroy_syncobj(ws->dev, syncobj);
158    return fd;
159 }
160 
amdgpu_fence_submitted(struct pipe_fence_handle * fence,uint64_t seq_no,uint64_t * user_fence_cpu_address)161 static void amdgpu_fence_submitted(struct pipe_fence_handle *fence,
162                                    uint64_t seq_no,
163                                    uint64_t *user_fence_cpu_address)
164 {
165    struct amdgpu_fence *afence = (struct amdgpu_fence*)fence;
166 
167    afence->fence.fence = seq_no;
168    afence->user_fence_cpu_address = user_fence_cpu_address;
169    util_queue_fence_signal(&afence->submitted);
170 }
171 
amdgpu_fence_signalled(struct pipe_fence_handle * fence)172 static void amdgpu_fence_signalled(struct pipe_fence_handle *fence)
173 {
174    struct amdgpu_fence *afence = (struct amdgpu_fence*)fence;
175 
176    afence->signalled = true;
177    util_queue_fence_signal(&afence->submitted);
178 }
179 
amdgpu_fence_wait(struct pipe_fence_handle * fence,uint64_t timeout,bool absolute)180 bool amdgpu_fence_wait(struct pipe_fence_handle *fence, uint64_t timeout,
181                        bool absolute)
182 {
183    struct amdgpu_fence *afence = (struct amdgpu_fence*)fence;
184    uint32_t expired;
185    int64_t abs_timeout;
186    uint64_t *user_fence_cpu;
187    int r;
188 
189    if (afence->signalled)
190       return true;
191 
192    if (absolute)
193       abs_timeout = timeout;
194    else
195       abs_timeout = os_time_get_absolute_timeout(timeout);
196 
197    /* Handle syncobjs. */
198    if (amdgpu_fence_is_syncobj(afence)) {
199       if (abs_timeout == OS_TIMEOUT_INFINITE)
200          abs_timeout = INT64_MAX;
201 
202       if (amdgpu_cs_syncobj_wait(afence->ws->dev, &afence->syncobj, 1,
203                                  abs_timeout, 0, NULL))
204          return false;
205 
206       afence->signalled = true;
207       return true;
208    }
209 
210    /* The fence might not have a number assigned if its IB is being
211     * submitted in the other thread right now. Wait until the submission
212     * is done. */
213    if (!util_queue_fence_wait_timeout(&afence->submitted, abs_timeout))
214       return false;
215 
216    user_fence_cpu = afence->user_fence_cpu_address;
217    if (user_fence_cpu) {
218       if (*user_fence_cpu >= afence->fence.fence) {
219          afence->signalled = true;
220          return true;
221       }
222 
223       /* No timeout, just query: no need for the ioctl. */
224       if (!absolute && !timeout)
225          return false;
226    }
227 
228    /* Now use the libdrm query. */
229    r = amdgpu_cs_query_fence_status(&afence->fence,
230 				    abs_timeout,
231 				    AMDGPU_QUERY_FENCE_TIMEOUT_IS_ABSOLUTE,
232 				    &expired);
233    if (r) {
234       fprintf(stderr, "amdgpu: amdgpu_cs_query_fence_status failed.\n");
235       return false;
236    }
237 
238    if (expired) {
239       /* This variable can only transition from false to true, so it doesn't
240        * matter if threads race for it. */
241       afence->signalled = true;
242       return true;
243    }
244    return false;
245 }
246 
amdgpu_fence_wait_rel_timeout(struct radeon_winsys * rws,struct pipe_fence_handle * fence,uint64_t timeout)247 static bool amdgpu_fence_wait_rel_timeout(struct radeon_winsys *rws,
248                                           struct pipe_fence_handle *fence,
249                                           uint64_t timeout)
250 {
251    return amdgpu_fence_wait(fence, timeout, false);
252 }
253 
254 static struct pipe_fence_handle *
amdgpu_cs_get_next_fence(struct radeon_cmdbuf * rcs)255 amdgpu_cs_get_next_fence(struct radeon_cmdbuf *rcs)
256 {
257    struct amdgpu_cs *cs = amdgpu_cs(rcs);
258    struct pipe_fence_handle *fence = NULL;
259 
260    if (cs->noop)
261       return NULL;
262 
263    if (cs->next_fence) {
264       amdgpu_fence_reference(&fence, cs->next_fence);
265       return fence;
266    }
267 
268    fence = amdgpu_fence_create(cs->ctx,
269                                cs->csc->ib[IB_MAIN].ip_type,
270                                cs->csc->ib[IB_MAIN].ip_instance,
271                                cs->csc->ib[IB_MAIN].ring);
272    if (!fence)
273       return NULL;
274 
275    amdgpu_fence_reference(&cs->next_fence, fence);
276    return fence;
277 }
278 
279 /* CONTEXTS */
280 
amdgpu_ctx_create(struct radeon_winsys * ws)281 static struct radeon_winsys_ctx *amdgpu_ctx_create(struct radeon_winsys *ws)
282 {
283    struct amdgpu_ctx *ctx = CALLOC_STRUCT(amdgpu_ctx);
284    int r;
285    struct amdgpu_bo_alloc_request alloc_buffer = {};
286    amdgpu_bo_handle buf_handle;
287 
288    if (!ctx)
289       return NULL;
290 
291    ctx->ws = amdgpu_winsys(ws);
292    ctx->refcount = 1;
293    ctx->initial_num_total_rejected_cs = ctx->ws->num_total_rejected_cs;
294 
295    r = amdgpu_cs_ctx_create(ctx->ws->dev, &ctx->ctx);
296    if (r) {
297       fprintf(stderr, "amdgpu: amdgpu_cs_ctx_create failed. (%i)\n", r);
298       goto error_create;
299    }
300 
301    alloc_buffer.alloc_size = ctx->ws->info.gart_page_size;
302    alloc_buffer.phys_alignment = ctx->ws->info.gart_page_size;
303    alloc_buffer.preferred_heap = AMDGPU_GEM_DOMAIN_GTT;
304 
305    r = amdgpu_bo_alloc(ctx->ws->dev, &alloc_buffer, &buf_handle);
306    if (r) {
307       fprintf(stderr, "amdgpu: amdgpu_bo_alloc failed. (%i)\n", r);
308       goto error_user_fence_alloc;
309    }
310 
311    r = amdgpu_bo_cpu_map(buf_handle, (void**)&ctx->user_fence_cpu_address_base);
312    if (r) {
313       fprintf(stderr, "amdgpu: amdgpu_bo_cpu_map failed. (%i)\n", r);
314       goto error_user_fence_map;
315    }
316 
317    memset(ctx->user_fence_cpu_address_base, 0, alloc_buffer.alloc_size);
318    ctx->user_fence_bo = buf_handle;
319 
320    return (struct radeon_winsys_ctx*)ctx;
321 
322 error_user_fence_map:
323    amdgpu_bo_free(buf_handle);
324 error_user_fence_alloc:
325    amdgpu_cs_ctx_free(ctx->ctx);
326 error_create:
327    FREE(ctx);
328    return NULL;
329 }
330 
amdgpu_ctx_destroy(struct radeon_winsys_ctx * rwctx)331 static void amdgpu_ctx_destroy(struct radeon_winsys_ctx *rwctx)
332 {
333    amdgpu_ctx_unref((struct amdgpu_ctx*)rwctx);
334 }
335 
336 static enum pipe_reset_status
amdgpu_ctx_query_reset_status(struct radeon_winsys_ctx * rwctx,bool full_reset_only,bool * needs_reset)337 amdgpu_ctx_query_reset_status(struct radeon_winsys_ctx *rwctx, bool full_reset_only,
338                               bool *needs_reset)
339 {
340    struct amdgpu_ctx *ctx = (struct amdgpu_ctx*)rwctx;
341    int r;
342 
343    if (needs_reset)
344       *needs_reset = false;
345 
346    /* Return a failure due to a GPU hang. */
347    if (ctx->ws->info.drm_minor >= 24) {
348       uint64_t flags;
349 
350       if (full_reset_only &&
351           ctx->initial_num_total_rejected_cs == ctx->ws->num_total_rejected_cs) {
352          /* If the caller is only interested in full reset (= wants to ignore soft
353           * recoveries), we can use the rejected cs count as a quick first check.
354           */
355          return PIPE_NO_RESET;
356       }
357 
358       r = amdgpu_cs_query_reset_state2(ctx->ctx, &flags);
359       if (r) {
360          fprintf(stderr, "amdgpu: amdgpu_cs_query_reset_state failed. (%i)\n", r);
361          return PIPE_NO_RESET;
362       }
363 
364       if (flags & AMDGPU_CTX_QUERY2_FLAGS_RESET) {
365          if (needs_reset)
366                *needs_reset = flags & AMDGPU_CTX_QUERY2_FLAGS_VRAMLOST;
367          if (flags & AMDGPU_CTX_QUERY2_FLAGS_GUILTY)
368             return PIPE_GUILTY_CONTEXT_RESET;
369          else
370             return PIPE_INNOCENT_CONTEXT_RESET;
371       }
372    } else {
373       uint32_t result, hangs;
374 
375       r = amdgpu_cs_query_reset_state(ctx->ctx, &result, &hangs);
376       if (r) {
377          fprintf(stderr, "amdgpu: amdgpu_cs_query_reset_state failed. (%i)\n", r);
378          return PIPE_NO_RESET;
379       }
380 
381       if (needs_reset)
382          *needs_reset = true;
383       switch (result) {
384       case AMDGPU_CTX_GUILTY_RESET:
385          return PIPE_GUILTY_CONTEXT_RESET;
386       case AMDGPU_CTX_INNOCENT_RESET:
387          return PIPE_INNOCENT_CONTEXT_RESET;
388       case AMDGPU_CTX_UNKNOWN_RESET:
389          return PIPE_UNKNOWN_CONTEXT_RESET;
390       }
391    }
392 
393    /* Return a failure due to a rejected command submission. */
394    if (ctx->ws->num_total_rejected_cs > ctx->initial_num_total_rejected_cs) {
395       if (needs_reset)
396          *needs_reset = true;
397       return ctx->num_rejected_cs ? PIPE_GUILTY_CONTEXT_RESET :
398                                     PIPE_INNOCENT_CONTEXT_RESET;
399    }
400    if (needs_reset)
401       *needs_reset = false;
402    return PIPE_NO_RESET;
403 }
404 
405 /* COMMAND SUBMISSION */
406 
amdgpu_cs_has_user_fence(struct amdgpu_cs_context * cs)407 static bool amdgpu_cs_has_user_fence(struct amdgpu_cs_context *cs)
408 {
409    return cs->ib[IB_MAIN].ip_type != AMDGPU_HW_IP_UVD &&
410           cs->ib[IB_MAIN].ip_type != AMDGPU_HW_IP_VCE &&
411           cs->ib[IB_MAIN].ip_type != AMDGPU_HW_IP_UVD_ENC &&
412           cs->ib[IB_MAIN].ip_type != AMDGPU_HW_IP_VCN_DEC &&
413           cs->ib[IB_MAIN].ip_type != AMDGPU_HW_IP_VCN_ENC &&
414           cs->ib[IB_MAIN].ip_type != AMDGPU_HW_IP_VCN_JPEG;
415 }
416 
amdgpu_cs_epilog_dws(struct amdgpu_cs * cs)417 static inline unsigned amdgpu_cs_epilog_dws(struct amdgpu_cs *cs)
418 {
419    if (cs->has_chaining)
420       return 4; /* for chaining */
421 
422    return 0;
423 }
424 
amdgpu_lookup_buffer(struct amdgpu_cs_context * cs,struct amdgpu_winsys_bo * bo,struct amdgpu_cs_buffer * buffers,unsigned num_buffers)425 static int amdgpu_lookup_buffer(struct amdgpu_cs_context *cs, struct amdgpu_winsys_bo *bo,
426                                 struct amdgpu_cs_buffer *buffers, unsigned num_buffers)
427 {
428    unsigned hash = bo->unique_id & (BUFFER_HASHLIST_SIZE-1);
429    int i = cs->buffer_indices_hashlist[hash];
430 
431    /* not found or found */
432    if (i < 0 || (i < num_buffers && buffers[i].bo == bo))
433       return i;
434 
435    /* Hash collision, look for the BO in the list of buffers linearly. */
436    for (int i = num_buffers - 1; i >= 0; i--) {
437       if (buffers[i].bo == bo) {
438          /* Put this buffer in the hash list.
439           * This will prevent additional hash collisions if there are
440           * several consecutive lookup_buffer calls for the same buffer.
441           *
442           * Example: Assuming buffers A,B,C collide in the hash list,
443           * the following sequence of buffers:
444           *         AAAAAAAAAAABBBBBBBBBBBBBBCCCCCCCC
445           * will collide here: ^ and here:   ^,
446           * meaning that we should get very few collisions in the end. */
447          cs->buffer_indices_hashlist[hash] = i & 0x7fff;
448          return i;
449       }
450    }
451    return -1;
452 }
453 
amdgpu_lookup_buffer_any_type(struct amdgpu_cs_context * cs,struct amdgpu_winsys_bo * bo)454 int amdgpu_lookup_buffer_any_type(struct amdgpu_cs_context *cs, struct amdgpu_winsys_bo *bo)
455 {
456    struct amdgpu_cs_buffer *buffers;
457    int num_buffers;
458 
459    if (bo->bo) {
460       buffers = cs->real_buffers;
461       num_buffers = cs->num_real_buffers;
462    } else if (!(bo->base.usage & RADEON_FLAG_SPARSE)) {
463       buffers = cs->slab_buffers;
464       num_buffers = cs->num_slab_buffers;
465    } else {
466       buffers = cs->sparse_buffers;
467       num_buffers = cs->num_sparse_buffers;
468    }
469 
470    return amdgpu_lookup_buffer(cs, bo, buffers, num_buffers);
471 }
472 
473 static int
amdgpu_do_add_real_buffer(struct amdgpu_winsys * ws,struct amdgpu_cs_context * cs,struct amdgpu_winsys_bo * bo)474 amdgpu_do_add_real_buffer(struct amdgpu_winsys *ws, struct amdgpu_cs_context *cs,
475                           struct amdgpu_winsys_bo *bo)
476 {
477    struct amdgpu_cs_buffer *buffer;
478    int idx;
479 
480    /* New buffer, check if the backing array is large enough. */
481    if (cs->num_real_buffers >= cs->max_real_buffers) {
482       unsigned new_max =
483          MAX2(cs->max_real_buffers + 16, (unsigned)(cs->max_real_buffers * 1.3));
484       struct amdgpu_cs_buffer *new_buffers;
485 
486       new_buffers = MALLOC(new_max * sizeof(*new_buffers));
487 
488       if (!new_buffers) {
489          fprintf(stderr, "amdgpu_do_add_buffer: allocation failed\n");
490          FREE(new_buffers);
491          return -1;
492       }
493 
494       memcpy(new_buffers, cs->real_buffers, cs->num_real_buffers * sizeof(*new_buffers));
495 
496       FREE(cs->real_buffers);
497 
498       cs->max_real_buffers = new_max;
499       cs->real_buffers = new_buffers;
500    }
501 
502    idx = cs->num_real_buffers;
503    buffer = &cs->real_buffers[idx];
504 
505    memset(buffer, 0, sizeof(*buffer));
506    amdgpu_winsys_bo_reference(ws, &buffer->bo, bo);
507    cs->num_real_buffers++;
508 
509    return idx;
510 }
511 
512 static int
amdgpu_lookup_or_add_real_buffer(struct radeon_cmdbuf * rcs,struct amdgpu_cs * acs,struct amdgpu_winsys_bo * bo)513 amdgpu_lookup_or_add_real_buffer(struct radeon_cmdbuf *rcs, struct amdgpu_cs *acs,
514                                  struct amdgpu_winsys_bo *bo)
515 {
516    struct amdgpu_cs_context *cs = acs->csc;
517    unsigned hash;
518    int idx = amdgpu_lookup_buffer(cs, bo, cs->real_buffers, cs->num_real_buffers);
519 
520    if (idx >= 0)
521       return idx;
522 
523    idx = amdgpu_do_add_real_buffer(acs->ws, cs, bo);
524 
525    hash = bo->unique_id & (BUFFER_HASHLIST_SIZE-1);
526    cs->buffer_indices_hashlist[hash] = idx & 0x7fff;
527 
528    if (bo->base.placement & RADEON_DOMAIN_VRAM)
529       rcs->used_vram_kb += bo->base.size / 1024;
530    else if (bo->base.placement & RADEON_DOMAIN_GTT)
531       rcs->used_gart_kb += bo->base.size / 1024;
532 
533    return idx;
534 }
535 
amdgpu_lookup_or_add_slab_buffer(struct amdgpu_winsys * ws,struct radeon_cmdbuf * rcs,struct amdgpu_cs * acs,struct amdgpu_winsys_bo * bo)536 static int amdgpu_lookup_or_add_slab_buffer(struct amdgpu_winsys *ws,
537                                             struct radeon_cmdbuf *rcs,
538                                             struct amdgpu_cs *acs,
539                                             struct amdgpu_winsys_bo *bo)
540 {
541    struct amdgpu_cs_context *cs = acs->csc;
542    struct amdgpu_cs_buffer *buffer;
543    unsigned hash;
544    int idx = amdgpu_lookup_buffer(cs, bo, cs->slab_buffers, cs->num_slab_buffers);
545    int real_idx;
546 
547    if (idx >= 0)
548       return idx;
549 
550    real_idx = amdgpu_lookup_or_add_real_buffer(rcs, acs, bo->u.slab.real);
551    if (real_idx < 0)
552       return -1;
553 
554    /* New buffer, check if the backing array is large enough. */
555    if (cs->num_slab_buffers >= cs->max_slab_buffers) {
556       unsigned new_max =
557          MAX2(cs->max_slab_buffers + 16, (unsigned)(cs->max_slab_buffers * 1.3));
558       struct amdgpu_cs_buffer *new_buffers;
559 
560       new_buffers = REALLOC(cs->slab_buffers,
561                             cs->max_slab_buffers * sizeof(*new_buffers),
562                             new_max * sizeof(*new_buffers));
563       if (!new_buffers) {
564          fprintf(stderr, "amdgpu_lookup_or_add_slab_buffer: allocation failed\n");
565          return -1;
566       }
567 
568       cs->max_slab_buffers = new_max;
569       cs->slab_buffers = new_buffers;
570    }
571 
572    idx = cs->num_slab_buffers;
573    buffer = &cs->slab_buffers[idx];
574 
575    memset(buffer, 0, sizeof(*buffer));
576    amdgpu_winsys_bo_reference(ws, &buffer->bo, bo);
577    buffer->u.slab.real_idx = real_idx;
578    cs->num_slab_buffers++;
579 
580    hash = bo->unique_id & (BUFFER_HASHLIST_SIZE-1);
581    cs->buffer_indices_hashlist[hash] = idx & 0x7fff;
582 
583    return idx;
584 }
585 
amdgpu_lookup_or_add_sparse_buffer(struct amdgpu_winsys * ws,struct radeon_cmdbuf * rcs,struct amdgpu_cs * acs,struct amdgpu_winsys_bo * bo)586 static int amdgpu_lookup_or_add_sparse_buffer(struct amdgpu_winsys *ws,
587                                               struct radeon_cmdbuf *rcs,
588                                               struct amdgpu_cs *acs,
589                                               struct amdgpu_winsys_bo *bo)
590 {
591    struct amdgpu_cs_context *cs = acs->csc;
592    struct amdgpu_cs_buffer *buffer;
593    unsigned hash;
594    int idx = amdgpu_lookup_buffer(cs, bo, cs->sparse_buffers, cs->num_sparse_buffers);
595 
596    if (idx >= 0)
597       return idx;
598 
599    /* New buffer, check if the backing array is large enough. */
600    if (cs->num_sparse_buffers >= cs->max_sparse_buffers) {
601       unsigned new_max =
602          MAX2(cs->max_sparse_buffers + 16, (unsigned)(cs->max_sparse_buffers * 1.3));
603       struct amdgpu_cs_buffer *new_buffers;
604 
605       new_buffers = REALLOC(cs->sparse_buffers,
606                             cs->max_sparse_buffers * sizeof(*new_buffers),
607                             new_max * sizeof(*new_buffers));
608       if (!new_buffers) {
609          fprintf(stderr, "amdgpu_lookup_or_add_sparse_buffer: allocation failed\n");
610          return -1;
611       }
612 
613       cs->max_sparse_buffers = new_max;
614       cs->sparse_buffers = new_buffers;
615    }
616 
617    idx = cs->num_sparse_buffers;
618    buffer = &cs->sparse_buffers[idx];
619 
620    memset(buffer, 0, sizeof(*buffer));
621    amdgpu_winsys_bo_reference(ws, &buffer->bo, bo);
622    cs->num_sparse_buffers++;
623 
624    hash = bo->unique_id & (BUFFER_HASHLIST_SIZE-1);
625    cs->buffer_indices_hashlist[hash] = idx & 0x7fff;
626 
627    /* We delay adding the backing buffers until we really have to. However,
628     * we cannot delay accounting for memory use.
629     */
630    simple_mtx_lock(&bo->lock);
631 
632    list_for_each_entry(struct amdgpu_sparse_backing, backing, &bo->u.sparse.backing, list) {
633       if (bo->base.placement & RADEON_DOMAIN_VRAM)
634          rcs->used_vram_kb += backing->bo->base.size / 1024;
635       else if (bo->base.placement & RADEON_DOMAIN_GTT)
636          rcs->used_gart_kb += backing->bo->base.size / 1024;
637    }
638 
639    simple_mtx_unlock(&bo->lock);
640 
641    return idx;
642 }
643 
amdgpu_cs_add_buffer(struct radeon_cmdbuf * rcs,struct pb_buffer * buf,enum radeon_bo_usage usage,enum radeon_bo_domain domains,enum radeon_bo_priority priority)644 static unsigned amdgpu_cs_add_buffer(struct radeon_cmdbuf *rcs,
645                                     struct pb_buffer *buf,
646                                     enum radeon_bo_usage usage,
647                                     enum radeon_bo_domain domains,
648                                     enum radeon_bo_priority priority)
649 {
650    /* Don't use the "domains" parameter. Amdgpu doesn't support changing
651     * the buffer placement during command submission.
652     */
653    struct amdgpu_cs *acs = amdgpu_cs(rcs);
654    struct amdgpu_cs_context *cs = acs->csc;
655    struct amdgpu_winsys_bo *bo = (struct amdgpu_winsys_bo*)buf;
656    struct amdgpu_cs_buffer *buffer;
657    int index;
658 
659    /* Fast exit for no-op calls.
660     * This is very effective with suballocators and linear uploaders that
661     * are outside of the winsys.
662     */
663    if (bo == cs->last_added_bo &&
664        (usage & cs->last_added_bo_usage) == usage &&
665        (1u << priority) & cs->last_added_bo_priority_usage)
666       return cs->last_added_bo_index;
667 
668    if (!(bo->base.usage & RADEON_FLAG_SPARSE)) {
669       if (!bo->bo) {
670          index = amdgpu_lookup_or_add_slab_buffer(acs->ws, rcs, acs, bo);
671          if (index < 0)
672             return 0;
673 
674          buffer = &cs->slab_buffers[index];
675          buffer->usage |= usage;
676 
677          usage &= ~RADEON_USAGE_SYNCHRONIZED;
678          index = buffer->u.slab.real_idx;
679       } else {
680          index = amdgpu_lookup_or_add_real_buffer(rcs, acs, bo);
681          if (index < 0)
682             return 0;
683       }
684 
685       buffer = &cs->real_buffers[index];
686    } else {
687       index = amdgpu_lookup_or_add_sparse_buffer(acs->ws, rcs, acs, bo);
688       if (index < 0)
689          return 0;
690 
691       buffer = &cs->sparse_buffers[index];
692    }
693 
694    buffer->u.real.priority_usage |= 1u << priority;
695    buffer->usage |= usage;
696 
697    cs->last_added_bo = bo;
698    cs->last_added_bo_index = index;
699    cs->last_added_bo_usage = buffer->usage;
700    cs->last_added_bo_priority_usage = buffer->u.real.priority_usage;
701    return index;
702 }
703 
amdgpu_ib_new_buffer(struct amdgpu_winsys * ws,struct amdgpu_ib * ib,struct amdgpu_cs * cs)704 static bool amdgpu_ib_new_buffer(struct amdgpu_winsys *ws,
705                                  struct amdgpu_ib *ib,
706                                  struct amdgpu_cs *cs)
707 {
708    struct pb_buffer *pb;
709    uint8_t *mapped;
710    unsigned buffer_size;
711 
712    /* Always create a buffer that is at least as large as the maximum seen IB
713     * size, aligned to a power of two (and multiplied by 4 to reduce internal
714     * fragmentation if chaining is not available). Limit to 512k dwords, which
715     * is the largest power of two that fits into the size field of the
716     * INDIRECT_BUFFER packet.
717     */
718    if (cs->has_chaining)
719       buffer_size = 4 * util_next_power_of_two(ib->max_ib_size);
720    else
721       buffer_size = 4 * util_next_power_of_two(4 * ib->max_ib_size);
722 
723    const unsigned min_size = MAX2(ib->max_check_space_size, 8 * 1024 * 4);
724    const unsigned max_size = 512 * 1024 * 4;
725 
726    buffer_size = MIN2(buffer_size, max_size);
727    buffer_size = MAX2(buffer_size, min_size); /* min_size is more important */
728 
729    enum radeon_bo_domain domain;
730    unsigned flags = RADEON_FLAG_NO_INTERPROCESS_SHARING;
731 
732    if (cs->ring_type == RING_GFX ||
733        cs->ring_type == RING_COMPUTE ||
734        cs->ring_type == RING_DMA) {
735       domain = ws->info.smart_access_memory ? RADEON_DOMAIN_VRAM : RADEON_DOMAIN_GTT;
736       flags |= RADEON_FLAG_32BIT | RADEON_FLAG_GTT_WC;
737    } else {
738       /* UVD/VCE */
739       /* TODO: validate that UVD/VCE don't read from IBs and enable WC or even VRAM. */
740       domain = RADEON_DOMAIN_GTT;
741    }
742 
743    pb = amdgpu_bo_create(ws, buffer_size,
744                          ws->info.gart_page_size,
745                          domain, flags);
746    if (!pb)
747       return false;
748 
749    mapped = amdgpu_bo_map(&ws->dummy_ws.base, pb, NULL, PIPE_MAP_WRITE);
750    if (!mapped) {
751       radeon_bo_reference(&ws->dummy_ws.base, &pb, NULL);
752       return false;
753    }
754 
755    radeon_bo_reference(&ws->dummy_ws.base, &ib->big_ib_buffer, pb);
756    radeon_bo_reference(&ws->dummy_ws.base, &pb, NULL);
757 
758    ib->ib_mapped = mapped;
759    ib->used_ib_space = 0;
760 
761    return true;
762 }
763 
amdgpu_get_new_ib(struct amdgpu_winsys * ws,struct radeon_cmdbuf * rcs,struct amdgpu_ib * ib,struct amdgpu_cs * cs)764 static bool amdgpu_get_new_ib(struct amdgpu_winsys *ws,
765                               struct radeon_cmdbuf *rcs,
766                               struct amdgpu_ib *ib,
767                               struct amdgpu_cs *cs)
768 {
769    /* Small IBs are better than big IBs, because the GPU goes idle quicker
770     * and there is less waiting for buffers and fences. Proof:
771     *   http://www.phoronix.com/scan.php?page=article&item=mesa-111-si&num=1
772     */
773    struct drm_amdgpu_cs_chunk_ib *info = &cs->csc->ib[ib->ib_type];
774    /* This is the minimum size of a contiguous IB. */
775    unsigned ib_size = 4 * 1024 * 4;
776 
777    /* Always allocate at least the size of the biggest cs_check_space call,
778     * because precisely the last call might have requested this size.
779     */
780    ib_size = MAX2(ib_size, ib->max_check_space_size);
781 
782    if (!cs->has_chaining) {
783       ib_size = MAX2(ib_size,
784                      4 * MIN2(util_next_power_of_two(ib->max_ib_size),
785                               IB_MAX_SUBMIT_DWORDS));
786    }
787 
788    ib->max_ib_size = ib->max_ib_size - ib->max_ib_size / 32;
789 
790    rcs->prev_dw = 0;
791    rcs->num_prev = 0;
792    rcs->current.cdw = 0;
793    rcs->current.buf = NULL;
794 
795    /* Allocate a new buffer for IBs if the current buffer is all used. */
796    if (!ib->big_ib_buffer ||
797        ib->used_ib_space + ib_size > ib->big_ib_buffer->size) {
798       if (!amdgpu_ib_new_buffer(ws, ib, cs))
799          return false;
800    }
801 
802    info->va_start = amdgpu_winsys_bo(ib->big_ib_buffer)->va + ib->used_ib_space;
803    info->ib_bytes = 0;
804    /* ib_bytes is in dwords and the conversion to bytes will be done before
805     * the CS ioctl. */
806    ib->ptr_ib_size = &info->ib_bytes;
807    ib->ptr_ib_size_inside_ib = false;
808 
809    amdgpu_cs_add_buffer(cs->main.rcs, ib->big_ib_buffer,
810                         RADEON_USAGE_READ, 0, RADEON_PRIO_IB1);
811 
812    rcs->current.buf = (uint32_t*)(ib->ib_mapped + ib->used_ib_space);
813 
814    if (ib->ib_type == IB_MAIN)
815       cs->csc->ib_main_addr = rcs->current.buf;
816 
817    ib_size = ib->big_ib_buffer->size - ib->used_ib_space;
818    rcs->current.max_dw = ib_size / 4 - amdgpu_cs_epilog_dws(cs);
819    rcs->gpu_address = info->va_start;
820    return true;
821 }
822 
amdgpu_set_ib_size(struct radeon_cmdbuf * rcs,struct amdgpu_ib * ib)823 static void amdgpu_set_ib_size(struct radeon_cmdbuf *rcs, struct amdgpu_ib *ib)
824 {
825    if (ib->ptr_ib_size_inside_ib) {
826       *ib->ptr_ib_size = rcs->current.cdw |
827                          S_3F2_CHAIN(1) | S_3F2_VALID(1);
828    } else {
829       *ib->ptr_ib_size = rcs->current.cdw;
830    }
831 }
832 
amdgpu_ib_finalize(struct amdgpu_winsys * ws,struct radeon_cmdbuf * rcs,struct amdgpu_ib * ib)833 static void amdgpu_ib_finalize(struct amdgpu_winsys *ws, struct radeon_cmdbuf *rcs,
834                                struct amdgpu_ib *ib)
835 {
836    amdgpu_set_ib_size(rcs, ib);
837    ib->used_ib_space += rcs->current.cdw * 4;
838    ib->used_ib_space = align(ib->used_ib_space, ws->info.ib_alignment);
839    ib->max_ib_size = MAX2(ib->max_ib_size, rcs->prev_dw + rcs->current.cdw);
840 }
841 
amdgpu_init_cs_context(struct amdgpu_winsys * ws,struct amdgpu_cs_context * cs,enum ring_type ring_type)842 static bool amdgpu_init_cs_context(struct amdgpu_winsys *ws,
843                                    struct amdgpu_cs_context *cs,
844                                    enum ring_type ring_type)
845 {
846    switch (ring_type) {
847    case RING_DMA:
848       cs->ib[IB_MAIN].ip_type = AMDGPU_HW_IP_DMA;
849       break;
850 
851    case RING_UVD:
852       cs->ib[IB_MAIN].ip_type = AMDGPU_HW_IP_UVD;
853       break;
854 
855    case RING_UVD_ENC:
856       cs->ib[IB_MAIN].ip_type = AMDGPU_HW_IP_UVD_ENC;
857       break;
858 
859    case RING_VCE:
860       cs->ib[IB_MAIN].ip_type = AMDGPU_HW_IP_VCE;
861       break;
862 
863    case RING_VCN_DEC:
864       cs->ib[IB_MAIN].ip_type = AMDGPU_HW_IP_VCN_DEC;
865       break;
866 
867    case RING_VCN_ENC:
868       cs->ib[IB_MAIN].ip_type = AMDGPU_HW_IP_VCN_ENC;
869       break;
870 
871    case RING_VCN_JPEG:
872       cs->ib[IB_MAIN].ip_type = AMDGPU_HW_IP_VCN_JPEG;
873       break;
874 
875    case RING_COMPUTE:
876    case RING_GFX:
877       cs->ib[IB_MAIN].ip_type = ring_type == RING_GFX ? AMDGPU_HW_IP_GFX :
878                                                         AMDGPU_HW_IP_COMPUTE;
879 
880       /* The kernel shouldn't invalidate L2 and vL1. The proper place for cache
881        * invalidation is the beginning of IBs (the previous commit does that),
882        * because completion of an IB doesn't care about the state of GPU caches,
883        * but the beginning of an IB does. Draw calls from multiple IBs can be
884        * executed in parallel, so draw calls from the current IB can finish after
885        * the next IB starts drawing, and so the cache flush at the end of IB
886        * is always late.
887        */
888       if (ws->info.drm_minor >= 26)
889          cs->ib[IB_MAIN].flags = AMDGPU_IB_FLAG_TC_WB_NOT_INVALIDATE;
890       break;
891 
892    default:
893       assert(0);
894    }
895 
896    cs->last_added_bo = NULL;
897    return true;
898 }
899 
cleanup_fence_list(struct amdgpu_fence_list * fences)900 static void cleanup_fence_list(struct amdgpu_fence_list *fences)
901 {
902    for (unsigned i = 0; i < fences->num; i++)
903       amdgpu_fence_reference(&fences->list[i], NULL);
904    fences->num = 0;
905 }
906 
amdgpu_cs_context_cleanup(struct amdgpu_winsys * ws,struct amdgpu_cs_context * cs)907 static void amdgpu_cs_context_cleanup(struct amdgpu_winsys *ws, struct amdgpu_cs_context *cs)
908 {
909    unsigned i;
910 
911    for (i = 0; i < cs->num_real_buffers; i++) {
912       amdgpu_winsys_bo_reference(ws, &cs->real_buffers[i].bo, NULL);
913    }
914    for (i = 0; i < cs->num_slab_buffers; i++) {
915       amdgpu_winsys_bo_reference(ws, &cs->slab_buffers[i].bo, NULL);
916    }
917    for (i = 0; i < cs->num_sparse_buffers; i++) {
918       amdgpu_winsys_bo_reference(ws, &cs->sparse_buffers[i].bo, NULL);
919    }
920    cleanup_fence_list(&cs->fence_dependencies);
921    cleanup_fence_list(&cs->syncobj_dependencies);
922    cleanup_fence_list(&cs->syncobj_to_signal);
923 
924    cs->num_real_buffers = 0;
925    cs->num_slab_buffers = 0;
926    cs->num_sparse_buffers = 0;
927    amdgpu_fence_reference(&cs->fence, NULL);
928    cs->last_added_bo = NULL;
929 }
930 
amdgpu_destroy_cs_context(struct amdgpu_winsys * ws,struct amdgpu_cs_context * cs)931 static void amdgpu_destroy_cs_context(struct amdgpu_winsys *ws, struct amdgpu_cs_context *cs)
932 {
933    amdgpu_cs_context_cleanup(ws, cs);
934    FREE(cs->real_buffers);
935    FREE(cs->slab_buffers);
936    FREE(cs->sparse_buffers);
937    FREE(cs->fence_dependencies.list);
938    FREE(cs->syncobj_dependencies.list);
939    FREE(cs->syncobj_to_signal.list);
940 }
941 
942 
943 static bool
amdgpu_cs_create(struct radeon_cmdbuf * rcs,struct radeon_winsys_ctx * rwctx,enum ring_type ring_type,void (* flush)(void * ctx,unsigned flags,struct pipe_fence_handle ** fence),void * flush_ctx,bool stop_exec_on_failure)944 amdgpu_cs_create(struct radeon_cmdbuf *rcs,
945                  struct radeon_winsys_ctx *rwctx,
946                  enum ring_type ring_type,
947                  void (*flush)(void *ctx, unsigned flags,
948                                struct pipe_fence_handle **fence),
949                  void *flush_ctx,
950                  bool stop_exec_on_failure)
951 {
952    struct amdgpu_ctx *ctx = (struct amdgpu_ctx*)rwctx;
953    struct amdgpu_cs *cs;
954 
955    cs = CALLOC_STRUCT(amdgpu_cs);
956    if (!cs) {
957       return false;
958    }
959 
960    util_queue_fence_init(&cs->flush_completed);
961 
962    cs->ws = ctx->ws;
963    cs->ctx = ctx;
964    cs->flush_cs = flush;
965    cs->flush_data = flush_ctx;
966    cs->ring_type = ring_type;
967    cs->stop_exec_on_failure = stop_exec_on_failure;
968    cs->noop = ctx->ws->noop_cs;
969    cs->has_chaining = ctx->ws->info.chip_class >= GFX7 &&
970                       (ring_type == RING_GFX || ring_type == RING_COMPUTE);
971 
972    struct amdgpu_cs_fence_info fence_info;
973    fence_info.handle = cs->ctx->user_fence_bo;
974    fence_info.offset = cs->ring_type * 4;
975    amdgpu_cs_chunk_fence_info_to_data(&fence_info, (void*)&cs->fence_chunk);
976 
977    cs->main.ib_type = IB_MAIN;
978 
979    if (!amdgpu_init_cs_context(ctx->ws, &cs->csc1, ring_type)) {
980       FREE(cs);
981       return false;
982    }
983 
984    if (!amdgpu_init_cs_context(ctx->ws, &cs->csc2, ring_type)) {
985       amdgpu_destroy_cs_context(ctx->ws, &cs->csc1);
986       FREE(cs);
987       return false;
988    }
989 
990    memset(cs->buffer_indices_hashlist, -1, sizeof(cs->buffer_indices_hashlist));
991 
992    /* Set the first submission context as current. */
993    cs->csc = &cs->csc1;
994    cs->cst = &cs->csc2;
995 
996    /* Assign to both amdgpu_cs_context; only csc will use it. */
997    cs->csc1.buffer_indices_hashlist = cs->buffer_indices_hashlist;
998    cs->csc2.buffer_indices_hashlist = cs->buffer_indices_hashlist;
999 
1000    cs->main.rcs = rcs;
1001    rcs->priv = cs;
1002 
1003    if (!amdgpu_get_new_ib(ctx->ws, rcs, &cs->main, cs)) {
1004       amdgpu_destroy_cs_context(ctx->ws, &cs->csc2);
1005       amdgpu_destroy_cs_context(ctx->ws, &cs->csc1);
1006       FREE(cs);
1007       rcs->priv = NULL;
1008       return false;
1009    }
1010 
1011    p_atomic_inc(&ctx->ws->num_cs);
1012    return true;
1013 }
1014 
1015 static bool
amdgpu_cs_setup_preemption(struct radeon_cmdbuf * rcs,const uint32_t * preamble_ib,unsigned preamble_num_dw)1016 amdgpu_cs_setup_preemption(struct radeon_cmdbuf *rcs, const uint32_t *preamble_ib,
1017                            unsigned preamble_num_dw)
1018 {
1019    struct amdgpu_cs *cs = amdgpu_cs(rcs);
1020    struct amdgpu_winsys *ws = cs->ws;
1021    struct amdgpu_cs_context *csc[2] = {&cs->csc1, &cs->csc2};
1022    unsigned size = align(preamble_num_dw * 4, ws->info.ib_alignment);
1023    struct pb_buffer *preamble_bo;
1024    uint32_t *map;
1025 
1026    /* Create the preamble IB buffer. */
1027    preamble_bo = amdgpu_bo_create(ws, size, ws->info.ib_alignment,
1028                                   RADEON_DOMAIN_VRAM,
1029                                   RADEON_FLAG_NO_INTERPROCESS_SHARING |
1030                                   RADEON_FLAG_GTT_WC |
1031                                   RADEON_FLAG_READ_ONLY);
1032    if (!preamble_bo)
1033       return false;
1034 
1035    map = (uint32_t*)amdgpu_bo_map(&ws->dummy_ws.base, preamble_bo, NULL,
1036                                   PIPE_MAP_WRITE | RADEON_MAP_TEMPORARY);
1037    if (!map) {
1038       radeon_bo_reference(&ws->dummy_ws.base, &preamble_bo, NULL);
1039       return false;
1040    }
1041 
1042    /* Upload the preamble IB. */
1043    memcpy(map, preamble_ib, preamble_num_dw * 4);
1044 
1045    /* Pad the IB. */
1046    uint32_t ib_pad_dw_mask = ws->info.ib_pad_dw_mask[cs->ring_type];
1047    while (preamble_num_dw & ib_pad_dw_mask)
1048       map[preamble_num_dw++] = PKT3_NOP_PAD;
1049    amdgpu_bo_unmap(&ws->dummy_ws.base, preamble_bo);
1050 
1051    for (unsigned i = 0; i < 2; i++) {
1052       csc[i]->ib[IB_PREAMBLE] = csc[i]->ib[IB_MAIN];
1053       csc[i]->ib[IB_PREAMBLE].flags |= AMDGPU_IB_FLAG_PREAMBLE;
1054       csc[i]->ib[IB_PREAMBLE].va_start = amdgpu_winsys_bo(preamble_bo)->va;
1055       csc[i]->ib[IB_PREAMBLE].ib_bytes = preamble_num_dw * 4;
1056 
1057       csc[i]->ib[IB_MAIN].flags |= AMDGPU_IB_FLAG_PREEMPT;
1058    }
1059 
1060    assert(!cs->preamble_ib_bo);
1061    cs->preamble_ib_bo = preamble_bo;
1062 
1063    amdgpu_cs_add_buffer(rcs, cs->preamble_ib_bo, RADEON_USAGE_READ, 0,
1064                         RADEON_PRIO_IB1);
1065    return true;
1066 }
1067 
amdgpu_cs_validate(struct radeon_cmdbuf * rcs)1068 static bool amdgpu_cs_validate(struct radeon_cmdbuf *rcs)
1069 {
1070    return true;
1071 }
1072 
amdgpu_cs_check_space(struct radeon_cmdbuf * rcs,unsigned dw,bool force_chaining)1073 static bool amdgpu_cs_check_space(struct radeon_cmdbuf *rcs, unsigned dw,
1074                                   bool force_chaining)
1075 {
1076    struct amdgpu_cs *cs = amdgpu_cs(rcs);
1077    struct amdgpu_ib *ib = &cs->main;
1078    unsigned cs_epilog_dw = amdgpu_cs_epilog_dws(cs);
1079    unsigned need_byte_size = (dw + cs_epilog_dw) * 4;
1080 
1081    assert(rcs->current.cdw <= rcs->current.max_dw);
1082 
1083    /* 125% of the size for IB epilog. */
1084    unsigned safe_byte_size = need_byte_size + need_byte_size / 4;
1085    ib->max_check_space_size = MAX2(ib->max_check_space_size,
1086                                    safe_byte_size);
1087 
1088    /* If force_chaining is true, we can't return. We have to chain. */
1089    if (!force_chaining) {
1090       unsigned requested_size = rcs->prev_dw + rcs->current.cdw + dw;
1091 
1092       if (requested_size > IB_MAX_SUBMIT_DWORDS)
1093          return false;
1094 
1095       ib->max_ib_size = MAX2(ib->max_ib_size, requested_size);
1096 
1097       if (rcs->current.max_dw - rcs->current.cdw >= dw)
1098          return true;
1099    }
1100 
1101    if (!cs->has_chaining) {
1102       assert(!force_chaining);
1103       return false;
1104    }
1105 
1106    /* Allocate a new chunk */
1107    if (rcs->num_prev >= rcs->max_prev) {
1108       unsigned new_max_prev = MAX2(1, 2 * rcs->max_prev);
1109       struct radeon_cmdbuf_chunk *new_prev;
1110 
1111       new_prev = REALLOC(rcs->prev,
1112                          sizeof(*new_prev) * rcs->max_prev,
1113                          sizeof(*new_prev) * new_max_prev);
1114       if (!new_prev)
1115          return false;
1116 
1117       rcs->prev = new_prev;
1118       rcs->max_prev = new_max_prev;
1119    }
1120 
1121    if (!amdgpu_ib_new_buffer(cs->ws, ib, cs))
1122       return false;
1123 
1124    assert(ib->used_ib_space == 0);
1125    uint64_t va = amdgpu_winsys_bo(ib->big_ib_buffer)->va;
1126 
1127    /* This space was originally reserved. */
1128    rcs->current.max_dw += cs_epilog_dw;
1129 
1130    /* Pad with NOPs but leave 4 dwords for INDIRECT_BUFFER. */
1131    uint32_t ib_pad_dw_mask = cs->ws->info.ib_pad_dw_mask[cs->ring_type];
1132    while ((rcs->current.cdw & ib_pad_dw_mask) != ib_pad_dw_mask - 3)
1133       radeon_emit(rcs, PKT3_NOP_PAD);
1134 
1135    radeon_emit(rcs, PKT3(PKT3_INDIRECT_BUFFER_CIK, 2, 0));
1136    radeon_emit(rcs, va);
1137    radeon_emit(rcs, va >> 32);
1138    uint32_t *new_ptr_ib_size = &rcs->current.buf[rcs->current.cdw++];
1139    assert((rcs->current.cdw & ib_pad_dw_mask) == 0);
1140 
1141    assert((rcs->current.cdw & 7) == 0);
1142    assert(rcs->current.cdw <= rcs->current.max_dw);
1143 
1144    amdgpu_set_ib_size(rcs, ib);
1145    ib->ptr_ib_size = new_ptr_ib_size;
1146    ib->ptr_ib_size_inside_ib = true;
1147 
1148    /* Hook up the new chunk */
1149    rcs->prev[rcs->num_prev].buf = rcs->current.buf;
1150    rcs->prev[rcs->num_prev].cdw = rcs->current.cdw;
1151    rcs->prev[rcs->num_prev].max_dw = rcs->current.cdw; /* no modifications */
1152    rcs->num_prev++;
1153 
1154    rcs->prev_dw += rcs->current.cdw;
1155    rcs->current.cdw = 0;
1156 
1157    rcs->current.buf = (uint32_t*)(ib->ib_mapped + ib->used_ib_space);
1158    rcs->current.max_dw = ib->big_ib_buffer->size / 4 - cs_epilog_dw;
1159    rcs->gpu_address = va;
1160 
1161    amdgpu_cs_add_buffer(cs->main.rcs, ib->big_ib_buffer,
1162                         RADEON_USAGE_READ, 0, RADEON_PRIO_IB1);
1163 
1164    return true;
1165 }
1166 
amdgpu_cs_get_buffer_list(struct radeon_cmdbuf * rcs,struct radeon_bo_list_item * list)1167 static unsigned amdgpu_cs_get_buffer_list(struct radeon_cmdbuf *rcs,
1168                                           struct radeon_bo_list_item *list)
1169 {
1170     struct amdgpu_cs_context *cs = amdgpu_cs(rcs)->csc;
1171     int i;
1172 
1173     if (list) {
1174         for (i = 0; i < cs->num_real_buffers; i++) {
1175             list[i].bo_size = cs->real_buffers[i].bo->base.size;
1176             list[i].vm_address = cs->real_buffers[i].bo->va;
1177             list[i].priority_usage = cs->real_buffers[i].u.real.priority_usage;
1178         }
1179     }
1180     return cs->num_real_buffers;
1181 }
1182 
add_fence_to_list(struct amdgpu_fence_list * fences,struct amdgpu_fence * fence)1183 static void add_fence_to_list(struct amdgpu_fence_list *fences,
1184                               struct amdgpu_fence *fence)
1185 {
1186    unsigned idx = fences->num++;
1187 
1188    if (idx >= fences->max) {
1189       unsigned size;
1190       const unsigned increment = 8;
1191 
1192       fences->max = idx + increment;
1193       size = fences->max * sizeof(fences->list[0]);
1194       fences->list = realloc(fences->list, size);
1195       /* Clear the newly-allocated elements. */
1196       memset(fences->list + idx, 0,
1197              increment * sizeof(fences->list[0]));
1198    }
1199    amdgpu_fence_reference(&fences->list[idx], (struct pipe_fence_handle*)fence);
1200 }
1201 
is_noop_fence_dependency(struct amdgpu_cs * acs,struct amdgpu_fence * fence)1202 static bool is_noop_fence_dependency(struct amdgpu_cs *acs,
1203                                      struct amdgpu_fence *fence)
1204 {
1205    struct amdgpu_cs_context *cs = acs->csc;
1206 
1207    /* Detect no-op dependencies only when there is only 1 ring,
1208     * because IBs on one ring are always executed one at a time.
1209     *
1210     * We always want no dependency between back-to-back gfx IBs, because
1211     * we need the parallelism between IBs for good performance.
1212     */
1213    if ((acs->ring_type == RING_GFX ||
1214         acs->ws->info.num_rings[acs->ring_type] == 1) &&
1215        !amdgpu_fence_is_syncobj(fence) &&
1216        fence->ctx == acs->ctx &&
1217        fence->fence.ip_type == cs->ib[IB_MAIN].ip_type &&
1218        fence->fence.ip_instance == cs->ib[IB_MAIN].ip_instance &&
1219        fence->fence.ring == cs->ib[IB_MAIN].ring)
1220       return true;
1221 
1222    return amdgpu_fence_wait((void *)fence, 0, false);
1223 }
1224 
amdgpu_cs_add_fence_dependency(struct radeon_cmdbuf * rws,struct pipe_fence_handle * pfence,unsigned dependency_flags)1225 static void amdgpu_cs_add_fence_dependency(struct radeon_cmdbuf *rws,
1226                                            struct pipe_fence_handle *pfence,
1227                                            unsigned dependency_flags)
1228 {
1229    struct amdgpu_cs *acs = amdgpu_cs(rws);
1230    struct amdgpu_cs_context *cs = acs->csc;
1231    struct amdgpu_fence *fence = (struct amdgpu_fence*)pfence;
1232 
1233    util_queue_fence_wait(&fence->submitted);
1234 
1235    /* Start fences are not needed here. */
1236    assert(!(dependency_flags & RADEON_DEPENDENCY_START_FENCE));
1237 
1238    if (is_noop_fence_dependency(acs, fence))
1239       return;
1240 
1241    if (amdgpu_fence_is_syncobj(fence))
1242       add_fence_to_list(&cs->syncobj_dependencies, fence);
1243    else
1244       add_fence_to_list(&cs->fence_dependencies, fence);
1245 }
1246 
amdgpu_add_bo_fence_dependencies(struct amdgpu_cs * acs,struct amdgpu_cs_buffer * buffer)1247 static void amdgpu_add_bo_fence_dependencies(struct amdgpu_cs *acs,
1248                                              struct amdgpu_cs_buffer *buffer)
1249 {
1250    struct amdgpu_cs_context *cs = acs->csc;
1251    struct amdgpu_winsys_bo *bo = buffer->bo;
1252    unsigned new_num_fences = 0;
1253 
1254    for (unsigned j = 0; j < bo->num_fences; ++j) {
1255       struct amdgpu_fence *bo_fence = (void *)bo->fences[j];
1256 
1257       if (is_noop_fence_dependency(acs, bo_fence))
1258          continue;
1259 
1260       amdgpu_fence_reference(&bo->fences[new_num_fences], bo->fences[j]);
1261       new_num_fences++;
1262 
1263       if (!(buffer->usage & RADEON_USAGE_SYNCHRONIZED))
1264          continue;
1265 
1266       add_fence_to_list(&cs->fence_dependencies, bo_fence);
1267    }
1268 
1269    for (unsigned j = new_num_fences; j < bo->num_fences; ++j)
1270       amdgpu_fence_reference(&bo->fences[j], NULL);
1271 
1272    bo->num_fences = new_num_fences;
1273 }
1274 
1275 /* Add the given list of fences to the buffer's fence list.
1276  *
1277  * Must be called with the winsys bo_fence_lock held.
1278  */
amdgpu_add_fences(struct amdgpu_winsys_bo * bo,unsigned num_fences,struct pipe_fence_handle ** fences)1279 void amdgpu_add_fences(struct amdgpu_winsys_bo *bo,
1280                        unsigned num_fences,
1281                        struct pipe_fence_handle **fences)
1282 {
1283    if (bo->num_fences + num_fences > bo->max_fences) {
1284       unsigned new_max_fences = MAX2(bo->num_fences + num_fences, bo->max_fences * 2);
1285       struct pipe_fence_handle **new_fences =
1286          REALLOC(bo->fences,
1287                  bo->num_fences * sizeof(*new_fences),
1288                  new_max_fences * sizeof(*new_fences));
1289       if (likely(new_fences && new_max_fences < UINT16_MAX)) {
1290          bo->fences = new_fences;
1291          bo->max_fences = new_max_fences;
1292       } else {
1293          unsigned drop;
1294 
1295          fprintf(stderr, new_fences ? "amdgpu_add_fences: too many fences, dropping some\n"
1296                                     : "amdgpu_add_fences: allocation failure, dropping fence(s)\n");
1297          free(new_fences);
1298 
1299          if (!bo->num_fences)
1300             return;
1301 
1302          bo->num_fences--; /* prefer to keep the most recent fence if possible */
1303          amdgpu_fence_reference(&bo->fences[bo->num_fences], NULL);
1304 
1305          drop = bo->num_fences + num_fences - bo->max_fences;
1306          num_fences -= drop;
1307          fences += drop;
1308       }
1309    }
1310 
1311    for (unsigned i = 0; i < num_fences; ++i) {
1312       bo->fences[bo->num_fences] = NULL;
1313       amdgpu_fence_reference(&bo->fences[bo->num_fences], fences[i]);
1314       bo->num_fences++;
1315    }
1316 }
1317 
amdgpu_add_fence_dependencies_bo_list(struct amdgpu_cs * acs,struct pipe_fence_handle * fence,unsigned num_buffers,struct amdgpu_cs_buffer * buffers)1318 static void amdgpu_add_fence_dependencies_bo_list(struct amdgpu_cs *acs,
1319                                                   struct pipe_fence_handle *fence,
1320                                                   unsigned num_buffers,
1321                                                   struct amdgpu_cs_buffer *buffers)
1322 {
1323    for (unsigned i = 0; i < num_buffers; i++) {
1324       struct amdgpu_cs_buffer *buffer = &buffers[i];
1325       struct amdgpu_winsys_bo *bo = buffer->bo;
1326 
1327       amdgpu_add_bo_fence_dependencies(acs, buffer);
1328       p_atomic_inc(&bo->num_active_ioctls);
1329       amdgpu_add_fences(bo, 1, &fence);
1330    }
1331 }
1332 
1333 /* Since the kernel driver doesn't synchronize execution between different
1334  * rings automatically, we have to add fence dependencies manually.
1335  */
amdgpu_add_fence_dependencies_bo_lists(struct amdgpu_cs * acs)1336 static void amdgpu_add_fence_dependencies_bo_lists(struct amdgpu_cs *acs)
1337 {
1338    struct amdgpu_cs_context *cs = acs->csc;
1339 
1340    amdgpu_add_fence_dependencies_bo_list(acs, cs->fence, cs->num_real_buffers, cs->real_buffers);
1341    amdgpu_add_fence_dependencies_bo_list(acs, cs->fence, cs->num_slab_buffers, cs->slab_buffers);
1342    amdgpu_add_fence_dependencies_bo_list(acs, cs->fence, cs->num_sparse_buffers, cs->sparse_buffers);
1343 }
1344 
amdgpu_cs_add_syncobj_signal(struct radeon_cmdbuf * rws,struct pipe_fence_handle * fence)1345 static void amdgpu_cs_add_syncobj_signal(struct radeon_cmdbuf *rws,
1346                                          struct pipe_fence_handle *fence)
1347 {
1348    struct amdgpu_cs *acs = amdgpu_cs(rws);
1349    struct amdgpu_cs_context *cs = acs->csc;
1350 
1351    assert(amdgpu_fence_is_syncobj((struct amdgpu_fence *)fence));
1352 
1353    add_fence_to_list(&cs->syncobj_to_signal, (struct amdgpu_fence*)fence);
1354 }
1355 
1356 /* Add backing of sparse buffers to the buffer list.
1357  *
1358  * This is done late, during submission, to keep the buffer list short before
1359  * submit, and to avoid managing fences for the backing buffers.
1360  */
amdgpu_add_sparse_backing_buffers(struct amdgpu_winsys * ws,struct amdgpu_cs_context * cs)1361 static bool amdgpu_add_sparse_backing_buffers(struct amdgpu_winsys *ws,
1362                                               struct amdgpu_cs_context *cs)
1363 {
1364    for (unsigned i = 0; i < cs->num_sparse_buffers; ++i) {
1365       struct amdgpu_cs_buffer *buffer = &cs->sparse_buffers[i];
1366       struct amdgpu_winsys_bo *bo = buffer->bo;
1367 
1368       simple_mtx_lock(&bo->lock);
1369 
1370       list_for_each_entry(struct amdgpu_sparse_backing, backing, &bo->u.sparse.backing, list) {
1371          /* We can directly add the buffer here, because we know that each
1372           * backing buffer occurs only once.
1373           */
1374          int idx = amdgpu_do_add_real_buffer(ws, cs, backing->bo);
1375          if (idx < 0) {
1376             fprintf(stderr, "%s: failed to add buffer\n", __FUNCTION__);
1377             simple_mtx_unlock(&bo->lock);
1378             return false;
1379          }
1380 
1381          cs->real_buffers[idx].u.real.priority_usage = buffer->u.real.priority_usage;
1382       }
1383 
1384       simple_mtx_unlock(&bo->lock);
1385    }
1386 
1387    return true;
1388 }
1389 
amdgpu_cs_submit_ib(void * job,void * gdata,int thread_index)1390 static void amdgpu_cs_submit_ib(void *job, void *gdata, int thread_index)
1391 {
1392    struct amdgpu_cs *acs = (struct amdgpu_cs*)job;
1393    struct amdgpu_winsys *ws = acs->ws;
1394    struct amdgpu_cs_context *cs = acs->cst;
1395    int i, r;
1396    uint32_t bo_list = 0;
1397    uint64_t seq_no = 0;
1398    bool has_user_fence = amdgpu_cs_has_user_fence(cs);
1399    bool use_bo_list_create = ws->info.drm_minor < 27;
1400    struct drm_amdgpu_bo_list_in bo_list_in;
1401    unsigned initial_num_real_buffers = cs->num_real_buffers;
1402 
1403 #if DEBUG
1404    /* Prepare the buffer list. */
1405    if (ws->debug_all_bos) {
1406       /* The buffer list contains all buffers. This is a slow path that
1407        * ensures that no buffer is missing in the BO list.
1408        */
1409       unsigned num_handles = 0;
1410       struct drm_amdgpu_bo_list_entry *list =
1411          alloca(ws->num_buffers * sizeof(struct drm_amdgpu_bo_list_entry));
1412       struct amdgpu_winsys_bo *bo;
1413 
1414       simple_mtx_lock(&ws->global_bo_list_lock);
1415       LIST_FOR_EACH_ENTRY(bo, &ws->global_bo_list, u.real.global_list_item) {
1416          list[num_handles].bo_handle = bo->u.real.kms_handle;
1417          list[num_handles].bo_priority = 0;
1418          ++num_handles;
1419       }
1420 
1421       r = amdgpu_bo_list_create_raw(ws->dev, ws->num_buffers, list, &bo_list);
1422       simple_mtx_unlock(&ws->global_bo_list_lock);
1423       if (r) {
1424          fprintf(stderr, "amdgpu: buffer list creation failed (%d)\n", r);
1425          goto cleanup;
1426       }
1427    } else
1428 #endif
1429    {
1430       if (!amdgpu_add_sparse_backing_buffers(ws, cs)) {
1431          fprintf(stderr, "amdgpu: amdgpu_add_sparse_backing_buffers failed\n");
1432          r = -ENOMEM;
1433          goto cleanup;
1434       }
1435 
1436       struct drm_amdgpu_bo_list_entry *list =
1437          alloca((cs->num_real_buffers + 2) * sizeof(struct drm_amdgpu_bo_list_entry));
1438 
1439       unsigned num_handles = 0;
1440       for (i = 0; i < cs->num_real_buffers; ++i) {
1441          struct amdgpu_cs_buffer *buffer = &cs->real_buffers[i];
1442          assert(buffer->u.real.priority_usage != 0);
1443 
1444          list[num_handles].bo_handle = buffer->bo->u.real.kms_handle;
1445          list[num_handles].bo_priority = (util_last_bit(buffer->u.real.priority_usage) - 1) / 2;
1446          ++num_handles;
1447       }
1448 
1449       if (use_bo_list_create) {
1450          /* Legacy path creating the buffer list handle and passing it to the CS ioctl. */
1451          r = amdgpu_bo_list_create_raw(ws->dev, num_handles, list, &bo_list);
1452          if (r) {
1453             fprintf(stderr, "amdgpu: buffer list creation failed (%d)\n", r);
1454             goto cleanup;
1455          }
1456       } else {
1457          /* Standard path passing the buffer list via the CS ioctl. */
1458          bo_list_in.operation = ~0;
1459          bo_list_in.list_handle = ~0;
1460          bo_list_in.bo_number = num_handles;
1461          bo_list_in.bo_info_size = sizeof(struct drm_amdgpu_bo_list_entry);
1462          bo_list_in.bo_info_ptr = (uint64_t)(uintptr_t)list;
1463       }
1464    }
1465 
1466    if (acs->ring_type == RING_GFX)
1467       ws->gfx_bo_list_counter += cs->num_real_buffers;
1468 
1469    bool noop = false;
1470 
1471    if (acs->stop_exec_on_failure && acs->ctx->num_rejected_cs) {
1472       r = -ECANCELED;
1473    } else {
1474       struct drm_amdgpu_cs_chunk chunks[7];
1475       unsigned num_chunks = 0;
1476 
1477       /* BO list */
1478       if (!use_bo_list_create) {
1479          chunks[num_chunks].chunk_id = AMDGPU_CHUNK_ID_BO_HANDLES;
1480          chunks[num_chunks].length_dw = sizeof(struct drm_amdgpu_bo_list_in) / 4;
1481          chunks[num_chunks].chunk_data = (uintptr_t)&bo_list_in;
1482          num_chunks++;
1483       }
1484 
1485       /* Fence dependencies. */
1486       unsigned num_dependencies = cs->fence_dependencies.num;
1487       if (num_dependencies) {
1488          struct drm_amdgpu_cs_chunk_dep *dep_chunk =
1489             alloca(num_dependencies * sizeof(*dep_chunk));
1490 
1491          for (unsigned i = 0; i < num_dependencies; i++) {
1492             struct amdgpu_fence *fence =
1493                (struct amdgpu_fence*)cs->fence_dependencies.list[i];
1494 
1495             assert(util_queue_fence_is_signalled(&fence->submitted));
1496             amdgpu_cs_chunk_fence_to_dep(&fence->fence, &dep_chunk[i]);
1497          }
1498 
1499          chunks[num_chunks].chunk_id = AMDGPU_CHUNK_ID_DEPENDENCIES;
1500          chunks[num_chunks].length_dw = sizeof(dep_chunk[0]) / 4 * num_dependencies;
1501          chunks[num_chunks].chunk_data = (uintptr_t)dep_chunk;
1502          num_chunks++;
1503       }
1504 
1505       /* Syncobj dependencies. */
1506       unsigned num_syncobj_dependencies = cs->syncobj_dependencies.num;
1507       if (num_syncobj_dependencies) {
1508          struct drm_amdgpu_cs_chunk_sem *sem_chunk =
1509             alloca(num_syncobj_dependencies * sizeof(sem_chunk[0]));
1510 
1511          for (unsigned i = 0; i < num_syncobj_dependencies; i++) {
1512             struct amdgpu_fence *fence =
1513                (struct amdgpu_fence*)cs->syncobj_dependencies.list[i];
1514 
1515             if (!amdgpu_fence_is_syncobj(fence))
1516                continue;
1517 
1518             assert(util_queue_fence_is_signalled(&fence->submitted));
1519             sem_chunk[i].handle = fence->syncobj;
1520          }
1521 
1522          chunks[num_chunks].chunk_id = AMDGPU_CHUNK_ID_SYNCOBJ_IN;
1523          chunks[num_chunks].length_dw = sizeof(sem_chunk[0]) / 4 * num_syncobj_dependencies;
1524          chunks[num_chunks].chunk_data = (uintptr_t)sem_chunk;
1525          num_chunks++;
1526       }
1527 
1528       /* Syncobj signals. */
1529       unsigned num_syncobj_to_signal = cs->syncobj_to_signal.num;
1530       if (num_syncobj_to_signal) {
1531          struct drm_amdgpu_cs_chunk_sem *sem_chunk =
1532             alloca(num_syncobj_to_signal * sizeof(sem_chunk[0]));
1533 
1534          for (unsigned i = 0; i < num_syncobj_to_signal; i++) {
1535             struct amdgpu_fence *fence =
1536                (struct amdgpu_fence*)cs->syncobj_to_signal.list[i];
1537 
1538             assert(amdgpu_fence_is_syncobj(fence));
1539             sem_chunk[i].handle = fence->syncobj;
1540          }
1541 
1542          chunks[num_chunks].chunk_id = AMDGPU_CHUNK_ID_SYNCOBJ_OUT;
1543          chunks[num_chunks].length_dw = sizeof(sem_chunk[0]) / 4
1544                                         * num_syncobj_to_signal;
1545          chunks[num_chunks].chunk_data = (uintptr_t)sem_chunk;
1546          num_chunks++;
1547       }
1548 
1549       /* Fence */
1550       if (has_user_fence) {
1551          chunks[num_chunks].chunk_id = AMDGPU_CHUNK_ID_FENCE;
1552          chunks[num_chunks].length_dw = sizeof(struct drm_amdgpu_cs_chunk_fence) / 4;
1553          chunks[num_chunks].chunk_data = (uintptr_t)&acs->fence_chunk;
1554          num_chunks++;
1555       }
1556 
1557       /* IB */
1558       if (cs->ib[IB_PREAMBLE].ib_bytes) {
1559          chunks[num_chunks].chunk_id = AMDGPU_CHUNK_ID_IB;
1560          chunks[num_chunks].length_dw = sizeof(struct drm_amdgpu_cs_chunk_ib) / 4;
1561          chunks[num_chunks].chunk_data = (uintptr_t)&cs->ib[IB_PREAMBLE];
1562          num_chunks++;
1563       }
1564 
1565       /* IB */
1566       cs->ib[IB_MAIN].ib_bytes *= 4; /* Convert from dwords to bytes. */
1567       chunks[num_chunks].chunk_id = AMDGPU_CHUNK_ID_IB;
1568       chunks[num_chunks].length_dw = sizeof(struct drm_amdgpu_cs_chunk_ib) / 4;
1569       chunks[num_chunks].chunk_data = (uintptr_t)&cs->ib[IB_MAIN];
1570       num_chunks++;
1571 
1572       if (cs->secure) {
1573          cs->ib[IB_PREAMBLE].flags |= AMDGPU_IB_FLAGS_SECURE;
1574          cs->ib[IB_MAIN].flags |= AMDGPU_IB_FLAGS_SECURE;
1575       } else {
1576          cs->ib[IB_PREAMBLE].flags &= ~AMDGPU_IB_FLAGS_SECURE;
1577          cs->ib[IB_MAIN].flags &= ~AMDGPU_IB_FLAGS_SECURE;
1578       }
1579 
1580       /* Apply RADEON_NOOP. */
1581       if (acs->noop) {
1582          if (acs->ring_type == RING_GFX) {
1583             /* Reduce the IB size and fill it with NOP to make it like an empty IB. */
1584             unsigned noop_size = MIN2(cs->ib[IB_MAIN].ib_bytes, ws->info.ib_alignment);
1585 
1586             cs->ib_main_addr[0] = PKT3(PKT3_NOP, noop_size / 4 - 2, 0);
1587             cs->ib[IB_MAIN].ib_bytes = noop_size;
1588          } else {
1589             noop = true;
1590          }
1591       }
1592 
1593       assert(num_chunks <= ARRAY_SIZE(chunks));
1594 
1595       r = noop ? 0 : amdgpu_cs_submit_raw2(ws->dev, acs->ctx->ctx, bo_list,
1596                                            num_chunks, chunks, &seq_no);
1597    }
1598 
1599    if (r) {
1600       if (r == -ENOMEM)
1601          fprintf(stderr, "amdgpu: Not enough memory for command submission.\n");
1602       else if (r == -ECANCELED)
1603          fprintf(stderr, "amdgpu: The CS has been cancelled because the context is lost.\n");
1604       else
1605          fprintf(stderr, "amdgpu: The CS has been rejected, "
1606                  "see dmesg for more information (%i).\n", r);
1607 
1608       acs->ctx->num_rejected_cs++;
1609       ws->num_total_rejected_cs++;
1610    } else if (!noop) {
1611       /* Success. */
1612       uint64_t *user_fence = NULL;
1613 
1614       /* Need to reserve 4 QWORD for user fence:
1615        *   QWORD[0]: completed fence
1616        *   QWORD[1]: preempted fence
1617        *   QWORD[2]: reset fence
1618        *   QWORD[3]: preempted then reset
1619        **/
1620       if (has_user_fence)
1621          user_fence = acs->ctx->user_fence_cpu_address_base + acs->ring_type * 4;
1622       amdgpu_fence_submitted(cs->fence, seq_no, user_fence);
1623    }
1624 
1625    /* Cleanup. */
1626    if (bo_list)
1627       amdgpu_bo_list_destroy_raw(ws->dev, bo_list);
1628 
1629 cleanup:
1630    /* If there was an error, signal the fence, because it won't be signalled
1631     * by the hardware. */
1632    if (r || noop)
1633       amdgpu_fence_signalled(cs->fence);
1634 
1635    cs->error_code = r;
1636 
1637    /* Only decrement num_active_ioctls for those buffers where we incremented it. */
1638    for (i = 0; i < initial_num_real_buffers; i++)
1639       p_atomic_dec(&cs->real_buffers[i].bo->num_active_ioctls);
1640    for (i = 0; i < cs->num_slab_buffers; i++)
1641       p_atomic_dec(&cs->slab_buffers[i].bo->num_active_ioctls);
1642    for (i = 0; i < cs->num_sparse_buffers; i++)
1643       p_atomic_dec(&cs->sparse_buffers[i].bo->num_active_ioctls);
1644 
1645    amdgpu_cs_context_cleanup(ws, cs);
1646 }
1647 
1648 /* Make sure the previous submission is completed. */
amdgpu_cs_sync_flush(struct radeon_cmdbuf * rcs)1649 void amdgpu_cs_sync_flush(struct radeon_cmdbuf *rcs)
1650 {
1651    struct amdgpu_cs *cs = amdgpu_cs(rcs);
1652 
1653    /* Wait for any pending ioctl of this CS to complete. */
1654    util_queue_fence_wait(&cs->flush_completed);
1655 }
1656 
amdgpu_cs_flush(struct radeon_cmdbuf * rcs,unsigned flags,struct pipe_fence_handle ** fence)1657 static int amdgpu_cs_flush(struct radeon_cmdbuf *rcs,
1658                            unsigned flags,
1659                            struct pipe_fence_handle **fence)
1660 {
1661    struct amdgpu_cs *cs = amdgpu_cs(rcs);
1662    struct amdgpu_winsys *ws = cs->ws;
1663    int error_code = 0;
1664    uint32_t ib_pad_dw_mask = ws->info.ib_pad_dw_mask[cs->ring_type];
1665 
1666    rcs->current.max_dw += amdgpu_cs_epilog_dws(cs);
1667 
1668    /* Pad the IB according to the mask. */
1669    switch (cs->ring_type) {
1670    case RING_DMA:
1671       if (ws->info.chip_class <= GFX6) {
1672          while (rcs->current.cdw & ib_pad_dw_mask)
1673             radeon_emit(rcs, 0xf0000000); /* NOP packet */
1674       } else {
1675          while (rcs->current.cdw & ib_pad_dw_mask)
1676             radeon_emit(rcs, 0x00000000); /* NOP packet */
1677       }
1678       break;
1679    case RING_GFX:
1680    case RING_COMPUTE:
1681       if (ws->info.gfx_ib_pad_with_type2) {
1682          while (rcs->current.cdw & ib_pad_dw_mask)
1683             radeon_emit(rcs, PKT2_NOP_PAD);
1684       } else {
1685          while (rcs->current.cdw & ib_pad_dw_mask)
1686             radeon_emit(rcs, PKT3_NOP_PAD);
1687       }
1688       if (cs->ring_type == RING_GFX)
1689          ws->gfx_ib_size_counter += (rcs->prev_dw + rcs->current.cdw) * 4;
1690       break;
1691    case RING_UVD:
1692    case RING_UVD_ENC:
1693       while (rcs->current.cdw & ib_pad_dw_mask)
1694          radeon_emit(rcs, 0x80000000); /* type2 nop packet */
1695       break;
1696    case RING_VCN_JPEG:
1697       if (rcs->current.cdw % 2)
1698          assert(0);
1699       while (rcs->current.cdw & ib_pad_dw_mask) {
1700          radeon_emit(rcs, 0x60000000); /* nop packet */
1701          radeon_emit(rcs, 0x00000000);
1702       }
1703       break;
1704    case RING_VCN_DEC:
1705       while (rcs->current.cdw & ib_pad_dw_mask)
1706          radeon_emit(rcs, 0x81ff); /* nop packet */
1707       break;
1708    default:
1709       break;
1710    }
1711 
1712    if (rcs->current.cdw > rcs->current.max_dw) {
1713       fprintf(stderr, "amdgpu: command stream overflowed\n");
1714    }
1715 
1716    /* If the CS is not empty or overflowed.... */
1717    if (likely(radeon_emitted(rcs, 0) &&
1718        rcs->current.cdw <= rcs->current.max_dw &&
1719        !(flags & RADEON_FLUSH_NOOP))) {
1720       struct amdgpu_cs_context *cur = cs->csc;
1721 
1722       /* Set IB sizes. */
1723       amdgpu_ib_finalize(ws, rcs, &cs->main);
1724 
1725       /* Create a fence. */
1726       amdgpu_fence_reference(&cur->fence, NULL);
1727       if (cs->next_fence) {
1728          /* just move the reference */
1729          cur->fence = cs->next_fence;
1730          cs->next_fence = NULL;
1731       } else {
1732          cur->fence = amdgpu_fence_create(cs->ctx,
1733                                           cur->ib[IB_MAIN].ip_type,
1734                                           cur->ib[IB_MAIN].ip_instance,
1735                                           cur->ib[IB_MAIN].ring);
1736       }
1737       if (fence)
1738          amdgpu_fence_reference(fence, cur->fence);
1739 
1740       amdgpu_cs_sync_flush(rcs);
1741 
1742       /* Prepare buffers.
1743        *
1744        * This fence must be held until the submission is queued to ensure
1745        * that the order of fence dependency updates matches the order of
1746        * submissions.
1747        */
1748       simple_mtx_lock(&ws->bo_fence_lock);
1749       amdgpu_add_fence_dependencies_bo_lists(cs);
1750 
1751       /* Swap command streams. "cst" is going to be submitted. */
1752       cs->csc = cs->cst;
1753       cs->cst = cur;
1754 
1755       /* Submit. */
1756       util_queue_add_job(&ws->cs_queue, cs, &cs->flush_completed,
1757                          amdgpu_cs_submit_ib, NULL, 0);
1758 
1759       if (flags & RADEON_FLUSH_TOGGLE_SECURE_SUBMISSION)
1760          cs->csc->secure = !cs->cst->secure;
1761       else
1762          cs->csc->secure = cs->cst->secure;
1763 
1764       /* The submission has been queued, unlock the fence now. */
1765       simple_mtx_unlock(&ws->bo_fence_lock);
1766 
1767       if (!(flags & PIPE_FLUSH_ASYNC)) {
1768          amdgpu_cs_sync_flush(rcs);
1769          error_code = cur->error_code;
1770       }
1771    } else {
1772       if (flags & RADEON_FLUSH_TOGGLE_SECURE_SUBMISSION)
1773          cs->csc->secure = !cs->csc->secure;
1774       amdgpu_cs_context_cleanup(ws, cs->csc);
1775    }
1776 
1777    memset(cs->csc->buffer_indices_hashlist, -1, sizeof(cs->buffer_indices_hashlist));
1778 
1779    amdgpu_get_new_ib(ws, rcs, &cs->main, cs);
1780 
1781    if (cs->preamble_ib_bo) {
1782       amdgpu_cs_add_buffer(rcs, cs->preamble_ib_bo, RADEON_USAGE_READ, 0,
1783                            RADEON_PRIO_IB1);
1784    }
1785 
1786    rcs->used_gart_kb = 0;
1787    rcs->used_vram_kb = 0;
1788 
1789    if (cs->ring_type == RING_GFX)
1790       ws->num_gfx_IBs++;
1791    else if (cs->ring_type == RING_DMA)
1792       ws->num_sdma_IBs++;
1793 
1794    return error_code;
1795 }
1796 
amdgpu_cs_destroy(struct radeon_cmdbuf * rcs)1797 static void amdgpu_cs_destroy(struct radeon_cmdbuf *rcs)
1798 {
1799    struct amdgpu_cs *cs = amdgpu_cs(rcs);
1800 
1801    if (!cs)
1802       return;
1803 
1804    amdgpu_cs_sync_flush(rcs);
1805    util_queue_fence_destroy(&cs->flush_completed);
1806    p_atomic_dec(&cs->ws->num_cs);
1807    radeon_bo_reference(&cs->ws->dummy_ws.base, &cs->preamble_ib_bo, NULL);
1808    radeon_bo_reference(&cs->ws->dummy_ws.base, &cs->main.big_ib_buffer, NULL);
1809    FREE(rcs->prev);
1810    amdgpu_destroy_cs_context(cs->ws, &cs->csc1);
1811    amdgpu_destroy_cs_context(cs->ws, &cs->csc2);
1812    amdgpu_fence_reference(&cs->next_fence, NULL);
1813    FREE(cs);
1814 }
1815 
amdgpu_bo_is_referenced(struct radeon_cmdbuf * rcs,struct pb_buffer * _buf,enum radeon_bo_usage usage)1816 static bool amdgpu_bo_is_referenced(struct radeon_cmdbuf *rcs,
1817                                     struct pb_buffer *_buf,
1818                                     enum radeon_bo_usage usage)
1819 {
1820    struct amdgpu_cs *cs = amdgpu_cs(rcs);
1821    struct amdgpu_winsys_bo *bo = (struct amdgpu_winsys_bo*)_buf;
1822 
1823    return amdgpu_bo_is_referenced_by_cs_with_usage(cs, bo, usage);
1824 }
1825 
amdgpu_cs_init_functions(struct amdgpu_screen_winsys * ws)1826 void amdgpu_cs_init_functions(struct amdgpu_screen_winsys *ws)
1827 {
1828    ws->base.ctx_create = amdgpu_ctx_create;
1829    ws->base.ctx_destroy = amdgpu_ctx_destroy;
1830    ws->base.ctx_query_reset_status = amdgpu_ctx_query_reset_status;
1831    ws->base.cs_create = amdgpu_cs_create;
1832    ws->base.cs_setup_preemption = amdgpu_cs_setup_preemption;
1833    ws->base.cs_destroy = amdgpu_cs_destroy;
1834    ws->base.cs_add_buffer = amdgpu_cs_add_buffer;
1835    ws->base.cs_validate = amdgpu_cs_validate;
1836    ws->base.cs_check_space = amdgpu_cs_check_space;
1837    ws->base.cs_get_buffer_list = amdgpu_cs_get_buffer_list;
1838    ws->base.cs_flush = amdgpu_cs_flush;
1839    ws->base.cs_get_next_fence = amdgpu_cs_get_next_fence;
1840    ws->base.cs_is_buffer_referenced = amdgpu_bo_is_referenced;
1841    ws->base.cs_sync_flush = amdgpu_cs_sync_flush;
1842    ws->base.cs_add_fence_dependency = amdgpu_cs_add_fence_dependency;
1843    ws->base.cs_add_syncobj_signal = amdgpu_cs_add_syncobj_signal;
1844    ws->base.fence_wait = amdgpu_fence_wait_rel_timeout;
1845    ws->base.fence_reference = amdgpu_fence_reference;
1846    ws->base.fence_import_syncobj = amdgpu_fence_import_syncobj;
1847    ws->base.fence_import_sync_file = amdgpu_fence_import_sync_file;
1848    ws->base.fence_export_sync_file = amdgpu_fence_export_sync_file;
1849    ws->base.export_signalled_sync_file = amdgpu_export_signalled_sync_file;
1850 }
1851