• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2012 Rob Clark <robclark@freedesktop.org>
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 (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21  * SOFTWARE.
22  *
23  * Authors:
24  *    Rob Clark <robclark@freedesktop.org>
25  */
26 
27 #include "util/format/u_format.h"
28 #include "util/format/u_format_rgtc.h"
29 #include "util/format/u_format_zs.h"
30 #include "util/set.h"
31 #include "util/u_drm.h"
32 #include "util/u_inlines.h"
33 #include "util/u_string.h"
34 #include "util/u_surface.h"
35 #include "util/u_transfer.h"
36 
37 #include "decode/util.h"
38 
39 #include "freedreno_batch_cache.h"
40 #include "freedreno_blitter.h"
41 #include "freedreno_context.h"
42 #include "freedreno_fence.h"
43 #include "freedreno_query_hw.h"
44 #include "freedreno_resource.h"
45 #include "freedreno_screen.h"
46 #include "freedreno_surface.h"
47 #include "freedreno_util.h"
48 
49 #include <errno.h>
50 #include "drm-uapi/drm_fourcc.h"
51 
52 /* XXX this should go away, needed for 'struct winsys_handle' */
53 #include "frontend/drm_driver.h"
54 
55 /* A private modifier for now, so we have a way to request tiled but not
56  * compressed.  It would perhaps be good to get real modifiers for the
57  * tiled formats, but would probably need to do some work to figure out
58  * the layout(s) of the tiled modes, and whether they are the same
59  * across generations.
60  */
61 #define FD_FORMAT_MOD_QCOM_TILED fourcc_mod_code(QCOM, 0xffffffff)
62 
63 /**
64  * Go through the entire state and see if the resource is bound
65  * anywhere. If it is, mark the relevant state as dirty. This is
66  * called on realloc_bo to ensure the necessary state is re-
67  * emitted so the GPU looks at the new backing bo.
68  */
69 static void
rebind_resource_in_ctx(struct fd_context * ctx,struct fd_resource * rsc)70 rebind_resource_in_ctx(struct fd_context *ctx,
71                        struct fd_resource *rsc) assert_dt
72 {
73    struct pipe_resource *prsc = &rsc->b.b;
74 
75    if (ctx->rebind_resource)
76       ctx->rebind_resource(ctx, rsc);
77 
78    /* VBOs */
79    if (rsc->dirty & FD_DIRTY_VTXBUF) {
80       struct fd_vertexbuf_stateobj *vb = &ctx->vtx.vertexbuf;
81       for (unsigned i = 0; i < vb->count && !(ctx->dirty & FD_DIRTY_VTXBUF);
82            i++) {
83          if (vb->vb[i].buffer.resource == prsc)
84             fd_context_dirty(ctx, FD_DIRTY_VTXBUF);
85       }
86    }
87 
88    const enum fd_dirty_3d_state per_stage_dirty =
89       FD_DIRTY_CONST | FD_DIRTY_TEX | FD_DIRTY_IMAGE | FD_DIRTY_SSBO;
90 
91    if (!(rsc->dirty & per_stage_dirty))
92       return;
93 
94    /* per-shader-stage resources: */
95    for (unsigned stage = 0; stage < PIPE_SHADER_TYPES; stage++) {
96       /* Constbufs.. note that constbuf[0] is normal uniforms emitted in
97        * cmdstream rather than by pointer..
98        */
99       if ((rsc->dirty & FD_DIRTY_CONST) &&
100           !(ctx->dirty_shader[stage] & FD_DIRTY_CONST)) {
101          struct fd_constbuf_stateobj *cb = &ctx->constbuf[stage];
102          const unsigned num_ubos = util_last_bit(cb->enabled_mask);
103          for (unsigned i = 1; i < num_ubos; i++) {
104             if (cb->cb[i].buffer == prsc) {
105                fd_context_dirty_shader(ctx, stage, FD_DIRTY_SHADER_CONST);
106                break;
107             }
108          }
109       }
110 
111       /* Textures */
112       if ((rsc->dirty & FD_DIRTY_TEX) &&
113           !(ctx->dirty_shader[stage] & FD_DIRTY_TEX)) {
114          struct fd_texture_stateobj *tex = &ctx->tex[stage];
115          for (unsigned i = 0; i < tex->num_textures; i++) {
116             if (tex->textures[i] && (tex->textures[i]->texture == prsc)) {
117                fd_context_dirty_shader(ctx, stage, FD_DIRTY_SHADER_TEX);
118                break;
119             }
120          }
121       }
122 
123       /* Images */
124       if ((rsc->dirty & FD_DIRTY_IMAGE) &&
125           !(ctx->dirty_shader[stage] & FD_DIRTY_IMAGE)) {
126          struct fd_shaderimg_stateobj *si = &ctx->shaderimg[stage];
127          const unsigned num_images = util_last_bit(si->enabled_mask);
128          for (unsigned i = 0; i < num_images; i++) {
129             if (si->si[i].resource == prsc) {
130                fd_context_dirty_shader(ctx, stage, FD_DIRTY_SHADER_IMAGE);
131                break;
132             }
133          }
134       }
135 
136       /* SSBOs */
137       if ((rsc->dirty & FD_DIRTY_SSBO) &&
138           !(ctx->dirty_shader[stage] & FD_DIRTY_SSBO)) {
139          struct fd_shaderbuf_stateobj *sb = &ctx->shaderbuf[stage];
140          const unsigned num_ssbos = util_last_bit(sb->enabled_mask);
141          for (unsigned i = 0; i < num_ssbos; i++) {
142             if (sb->sb[i].buffer == prsc) {
143                fd_context_dirty_shader(ctx, stage, FD_DIRTY_SHADER_SSBO);
144                break;
145             }
146          }
147       }
148    }
149 }
150 
151 static void
rebind_resource(struct fd_resource * rsc)152 rebind_resource(struct fd_resource *rsc) assert_dt
153 {
154    struct fd_screen *screen = fd_screen(rsc->b.b.screen);
155 
156    fd_screen_lock(screen);
157    fd_resource_lock(rsc);
158 
159    if (rsc->dirty)
160       list_for_each_entry (struct fd_context, ctx, &screen->context_list, node)
161          rebind_resource_in_ctx(ctx, rsc);
162 
163    fd_resource_unlock(rsc);
164    fd_screen_unlock(screen);
165 }
166 
167 static inline void
fd_resource_set_bo(struct fd_resource * rsc,struct fd_bo * bo)168 fd_resource_set_bo(struct fd_resource *rsc, struct fd_bo *bo)
169 {
170    struct fd_screen *screen = fd_screen(rsc->b.b.screen);
171 
172    rsc->bo = bo;
173    rsc->seqno = p_atomic_inc_return(&screen->rsc_seqno);
174 }
175 
176 int
__fd_resource_wait(struct fd_context * ctx,struct fd_resource * rsc,unsigned op,const char * func)177 __fd_resource_wait(struct fd_context *ctx, struct fd_resource *rsc, unsigned op,
178                    const char *func)
179 {
180    if (op & FD_BO_PREP_NOSYNC)
181       return fd_bo_cpu_prep(rsc->bo, ctx->pipe, op);
182 
183    int ret;
184 
185    perf_time_ctx (ctx, 10000, "%s: a busy \"%" PRSC_FMT "\" BO stalled", func,
186                   PRSC_ARGS(&rsc->b.b)) {
187       ret = fd_bo_cpu_prep(rsc->bo, ctx->pipe, op);
188    }
189 
190    return ret;
191 }
192 
193 static void
realloc_bo(struct fd_resource * rsc,uint32_t size)194 realloc_bo(struct fd_resource *rsc, uint32_t size)
195 {
196    struct pipe_resource *prsc = &rsc->b.b;
197    struct fd_screen *screen = fd_screen(rsc->b.b.screen);
198    uint32_t flags =
199       COND(rsc->layout.tile_mode, FD_BO_NOMAP) |
200       COND(prsc->usage & PIPE_USAGE_STAGING, FD_BO_CACHED_COHERENT) |
201       COND(prsc->bind & PIPE_BIND_SHARED, FD_BO_SHARED) |
202       COND(prsc->bind & PIPE_BIND_SCANOUT, FD_BO_SCANOUT);
203    /* TODO other flags? */
204 
205    /* if we start using things other than write-combine,
206     * be sure to check for PIPE_RESOURCE_FLAG_MAP_COHERENT
207     */
208 
209    if (rsc->bo)
210       fd_bo_del(rsc->bo);
211 
212    struct fd_bo *bo =
213       fd_bo_new(screen->dev, size, flags, "%ux%ux%u@%u:%x", prsc->width0,
214                 prsc->height0, prsc->depth0, rsc->layout.cpp, prsc->bind);
215    fd_resource_set_bo(rsc, bo);
216 
217    /* Zero out the UBWC area on allocation.  This fixes intermittent failures
218     * with UBWC, which I suspect are due to the HW having a hard time
219     * interpreting arbitrary values populating the flags buffer when the BO
220     * was recycled through the bo cache (instead of fresh allocations from
221     * the kernel, which are zeroed).  sleep(1) in this spot didn't work
222     * around the issue, but any memset value seems to.
223     */
224    if (rsc->layout.ubwc) {
225       rsc->needs_ubwc_clear = true;
226    }
227 
228    util_range_set_empty(&rsc->valid_buffer_range);
229    fd_bc_invalidate_resource(rsc, true);
230 }
231 
232 static void
do_blit(struct fd_context * ctx,const struct pipe_blit_info * blit,bool fallback)233 do_blit(struct fd_context *ctx, const struct pipe_blit_info *blit,
234         bool fallback) assert_dt
235 {
236    struct pipe_context *pctx = &ctx->base;
237 
238    assert(!ctx->in_blit);
239    ctx->in_blit = true;
240 
241    /* TODO size threshold too?? */
242    if (fallback || !fd_blit(pctx, blit)) {
243       /* do blit on cpu: */
244       util_resource_copy_region(pctx, blit->dst.resource, blit->dst.level,
245                                 blit->dst.box.x, blit->dst.box.y,
246                                 blit->dst.box.z, blit->src.resource,
247                                 blit->src.level, &blit->src.box);
248    }
249 
250    ctx->in_blit = false;
251 }
252 
253 /**
254  * Replace the storage of dst with src.  This is only used by TC in the
255  * DISCARD_WHOLE_RESOURCE path, and src is a freshly allocated buffer.
256  */
257 void
fd_replace_buffer_storage(struct pipe_context * pctx,struct pipe_resource * pdst,struct pipe_resource * psrc,unsigned num_rebinds,uint32_t rebind_mask,uint32_t delete_buffer_id)258 fd_replace_buffer_storage(struct pipe_context *pctx, struct pipe_resource *pdst,
259                           struct pipe_resource *psrc, unsigned num_rebinds, uint32_t rebind_mask,
260                           uint32_t delete_buffer_id)
261 {
262    struct fd_context *ctx = fd_context(pctx);
263    struct fd_resource *dst = fd_resource(pdst);
264    struct fd_resource *src = fd_resource(psrc);
265 
266    DBG("pdst=%p, psrc=%p", pdst, psrc);
267 
268    /* This should only be called with buffers.. which side-steps some tricker
269     * cases, like a rsc that is in a batch-cache key...
270     */
271    assert(pdst->target == PIPE_BUFFER);
272    assert(psrc->target == PIPE_BUFFER);
273    assert(dst->track->bc_batch_mask == 0);
274    assert(src->track->bc_batch_mask == 0);
275    assert(src->track->batch_mask == 0);
276    assert(src->track->write_batch == NULL);
277    assert(memcmp(&dst->layout, &src->layout, sizeof(dst->layout)) == 0);
278 
279    /* get rid of any references that batch-cache might have to us (which
280     * should empty/destroy rsc->batches hashset)
281     *
282     * Note that we aren't actually destroying dst, but we are replacing
283     * it's storage so we want to go thru the same motions of decoupling
284     * it's batch connections.
285     */
286    fd_bc_invalidate_resource(dst, true);
287    rebind_resource(dst);
288 
289    util_idalloc_mt_free(&ctx->screen->buffer_ids, delete_buffer_id);
290 
291    fd_screen_lock(ctx->screen);
292 
293    fd_bo_del(dst->bo);
294    dst->bo = fd_bo_ref(src->bo);
295 
296    fd_resource_tracking_reference(&dst->track, src->track);
297    src->is_replacement = true;
298 
299    dst->seqno = p_atomic_inc_return(&ctx->screen->rsc_seqno);
300 
301    fd_screen_unlock(ctx->screen);
302 }
303 
304 static unsigned
translate_usage(unsigned usage)305 translate_usage(unsigned usage)
306 {
307    uint32_t op = 0;
308 
309    if (usage & PIPE_MAP_READ)
310       op |= FD_BO_PREP_READ;
311 
312    if (usage & PIPE_MAP_WRITE)
313       op |= FD_BO_PREP_WRITE;
314 
315    return op;
316 }
317 
318 bool
fd_resource_busy(struct pipe_screen * pscreen,struct pipe_resource * prsc,unsigned usage)319 fd_resource_busy(struct pipe_screen *pscreen, struct pipe_resource *prsc,
320                  unsigned usage)
321 {
322    struct fd_resource *rsc = fd_resource(prsc);
323 
324    if (pending(rsc, !!(usage & PIPE_MAP_WRITE)))
325       return true;
326 
327    if (resource_busy(rsc, translate_usage(usage)))
328       return true;
329 
330    return false;
331 }
332 
333 static void flush_resource(struct fd_context *ctx, struct fd_resource *rsc,
334                            unsigned usage);
335 
336 /**
337  * Helper to check if the format is something that we can blit/render
338  * to.. if the format is not renderable, there is no point in trying
339  * to do a staging blit (as it will still end up being a cpu copy)
340  */
341 static bool
is_renderable(struct pipe_resource * prsc)342 is_renderable(struct pipe_resource *prsc)
343 {
344    struct pipe_screen *pscreen = prsc->screen;
345    return pscreen->is_format_supported(
346          pscreen, prsc->format, prsc->target, prsc->nr_samples,
347          prsc->nr_storage_samples, PIPE_BIND_RENDER_TARGET);
348 }
349 
350 /**
351  * @rsc: the resource to shadow
352  * @level: the level to discard (if box != NULL, otherwise ignored)
353  * @box: the box to discard (or NULL if none)
354  * @modifier: the modifier for the new buffer state
355  */
356 static bool
fd_try_shadow_resource(struct fd_context * ctx,struct fd_resource * rsc,unsigned level,const struct pipe_box * box,uint64_t modifier)357 fd_try_shadow_resource(struct fd_context *ctx, struct fd_resource *rsc,
358                        unsigned level, const struct pipe_box *box,
359                        uint64_t modifier) assert_dt
360 {
361    struct pipe_context *pctx = &ctx->base;
362    struct pipe_resource *prsc = &rsc->b.b;
363    struct fd_screen *screen = fd_screen(pctx->screen);
364    struct fd_batch *batch;
365    bool fallback = false;
366 
367    if (prsc->next)
368       return false;
369 
370    /* Flush any pending batches writing the resource before we go mucking around
371     * in its insides.  The blit would immediately cause the batch to be flushed,
372     * anyway.
373     */
374    fd_bc_flush_writer(ctx, rsc);
375 
376    /* Because IB1 ("gmem") cmdstream is built only when we flush the
377     * batch, we need to flush any batches that reference this rsc as
378     * a render target.  Otherwise the framebuffer state emitted in
379     * IB1 will reference the resources new state, and not the state
380     * at the point in time that the earlier draws referenced it.
381     *
382     * Note that being in the gmem key doesn't necessarily mean the
383     * batch was considered a writer!
384     */
385    foreach_batch (batch, &screen->batch_cache, rsc->track->bc_batch_mask) {
386       fd_batch_flush(batch);
387    }
388 
389    /* TODO: somehow munge dimensions and format to copy unsupported
390     * render target format to something that is supported?
391     */
392    if (!is_renderable(prsc))
393       fallback = true;
394 
395    /* do shadowing back-blits on the cpu for buffers -- requires about a page of
396     * DMA to make GPU copies worth it according to robclark.  Note, if you
397     * decide to do it on the GPU then you'll need to update valid_buffer_range
398     * in the swap()s below.
399     */
400    if (prsc->target == PIPE_BUFFER)
401       fallback = true;
402 
403    bool discard_whole_level = box && util_texrange_covers_whole_level(
404                                         prsc, level, box->x, box->y, box->z,
405                                         box->width, box->height, box->depth);
406 
407    /* TODO need to be more clever about current level */
408    if ((prsc->target >= PIPE_TEXTURE_2D) && box && !discard_whole_level)
409       return false;
410 
411    struct pipe_resource *pshadow = pctx->screen->resource_create_with_modifiers(
412       pctx->screen, prsc, &modifier, 1);
413 
414    if (!pshadow)
415       return false;
416 
417    assert(!ctx->in_shadow);
418    ctx->in_shadow = true;
419 
420    /* get rid of any references that batch-cache might have to us (which
421     * should empty/destroy rsc->batches hashset)
422     */
423    fd_bc_invalidate_resource(rsc, false);
424    rebind_resource(rsc);
425 
426    fd_screen_lock(ctx->screen);
427 
428    /* Swap the backing bo's, so shadow becomes the old buffer,
429     * blit from shadow to new buffer.  From here on out, we
430     * cannot fail.
431     *
432     * Note that we need to do it in this order, otherwise if
433     * we go down cpu blit path, the recursive transfer_map()
434     * sees the wrong status..
435     */
436    struct fd_resource *shadow = fd_resource(pshadow);
437 
438    DBG("shadow: %p (%d, %p) -> %p (%d, %p)", rsc, rsc->b.b.reference.count,
439        rsc->track, shadow, shadow->b.b.reference.count, shadow->track);
440 
441    swap(rsc->bo, shadow->bo);
442    swap(rsc->valid, shadow->valid);
443 
444    /* swap() doesn't work because you can't typeof() the bitfield. */
445    bool temp = shadow->needs_ubwc_clear;
446    shadow->needs_ubwc_clear = rsc->needs_ubwc_clear;
447    rsc->needs_ubwc_clear = temp;
448 
449    swap(rsc->layout, shadow->layout);
450    rsc->seqno = p_atomic_inc_return(&ctx->screen->rsc_seqno);
451 
452    /* at this point, the newly created shadow buffer is not referenced
453     * by any batches, but the existing rsc (probably) is.  We need to
454     * transfer those references over:
455     */
456    assert(shadow->track->batch_mask == 0);
457    foreach_batch (batch, &ctx->screen->batch_cache, rsc->track->batch_mask) {
458       struct set_entry *entry = _mesa_set_search_pre_hashed(batch->resources, rsc->hash, rsc);
459       _mesa_set_remove(batch->resources, entry);
460       _mesa_set_add_pre_hashed(batch->resources, shadow->hash, shadow);
461    }
462    swap(rsc->track, shadow->track);
463 
464    fd_screen_unlock(ctx->screen);
465 
466    struct pipe_blit_info blit = {};
467    blit.dst.resource = prsc;
468    blit.dst.format = prsc->format;
469    blit.src.resource = pshadow;
470    blit.src.format = pshadow->format;
471    blit.mask = util_format_get_mask(prsc->format);
472    blit.filter = PIPE_TEX_FILTER_NEAREST;
473 
474 #define set_box(field, val)                                                    \
475    do {                                                                        \
476       blit.dst.field = (val);                                                  \
477       blit.src.field = (val);                                                  \
478    } while (0)
479 
480    /* Disable occlusion queries during shadow blits. */
481    bool saved_active_queries = ctx->active_queries;
482    pctx->set_active_query_state(pctx, false);
483 
484    /* blit the other levels in their entirety: */
485    for (unsigned l = 0; l <= prsc->last_level; l++) {
486       if (box && l == level)
487          continue;
488 
489       /* just blit whole level: */
490       set_box(level, l);
491       set_box(box.width, u_minify(prsc->width0, l));
492       set_box(box.height, u_minify(prsc->height0, l));
493       set_box(box.depth, u_minify(prsc->depth0, l));
494 
495       for (int i = 0; i < prsc->array_size; i++) {
496          set_box(box.z, i);
497          do_blit(ctx, &blit, fallback);
498       }
499    }
500 
501    /* deal w/ current level specially, since we might need to split
502     * it up into a couple blits:
503     */
504    if (box && !discard_whole_level) {
505       set_box(level, level);
506 
507       switch (prsc->target) {
508       case PIPE_BUFFER:
509       case PIPE_TEXTURE_1D:
510          set_box(box.y, 0);
511          set_box(box.z, 0);
512          set_box(box.height, 1);
513          set_box(box.depth, 1);
514 
515          if (box->x > 0) {
516             set_box(box.x, 0);
517             set_box(box.width, box->x);
518 
519             do_blit(ctx, &blit, fallback);
520          }
521          if ((box->x + box->width) < u_minify(prsc->width0, level)) {
522             set_box(box.x, box->x + box->width);
523             set_box(box.width,
524                     u_minify(prsc->width0, level) - (box->x + box->width));
525 
526             do_blit(ctx, &blit, fallback);
527          }
528          break;
529       case PIPE_TEXTURE_2D:
530          /* TODO */
531       default:
532          unreachable("TODO");
533       }
534    }
535 
536    pctx->set_active_query_state(pctx, saved_active_queries);
537 
538    ctx->in_shadow = false;
539 
540    pipe_resource_reference(&pshadow, NULL);
541 
542    return true;
543 }
544 
545 /**
546  * Uncompress an UBWC compressed buffer "in place".  This works basically
547  * like resource shadowing, creating a new resource, and doing an uncompress
548  * blit, and swapping the state between shadow and original resource so it
549  * appears to the gallium frontends as if nothing changed.
550  */
551 void
fd_resource_uncompress(struct fd_context * ctx,struct fd_resource * rsc,bool linear)552 fd_resource_uncompress(struct fd_context *ctx, struct fd_resource *rsc, bool linear)
553 {
554    tc_assert_driver_thread(ctx->tc);
555 
556    uint64_t modifier = linear ? DRM_FORMAT_MOD_LINEAR : FD_FORMAT_MOD_QCOM_TILED;
557 
558    bool success = fd_try_shadow_resource(ctx, rsc, 0, NULL, modifier);
559 
560    /* shadow should not fail in any cases where we need to uncompress: */
561    assert(success);
562 }
563 
564 /**
565  * Debug helper to hexdump a resource.
566  */
567 void
fd_resource_dump(struct fd_resource * rsc,const char * name)568 fd_resource_dump(struct fd_resource *rsc, const char *name)
569 {
570    fd_bo_cpu_prep(rsc->bo, NULL, FD_BO_PREP_READ);
571    printf("%s: \n", name);
572    dump_hex(fd_bo_map(rsc->bo), fd_bo_size(rsc->bo));
573 }
574 
575 static struct fd_resource *
fd_alloc_staging(struct fd_context * ctx,struct fd_resource * rsc,unsigned level,const struct pipe_box * box)576 fd_alloc_staging(struct fd_context *ctx, struct fd_resource *rsc,
577                  unsigned level, const struct pipe_box *box)
578    assert_dt
579 {
580    struct pipe_context *pctx = &ctx->base;
581    struct pipe_resource tmpl = rsc->b.b;
582 
583    /* We cannot currently do stencil export on earlier gens, and
584     * u_blitter cannot do blits involving stencil otherwise:
585     */
586    if ((ctx->screen->gen < 6) && !ctx->blit &&
587        (util_format_get_mask(tmpl.format) & PIPE_MASK_S))
588       return NULL;
589 
590    tmpl.width0 = box->width;
591    tmpl.height0 = box->height;
592    /* for array textures, box->depth is the array_size, otherwise
593     * for 3d textures, it is the depth:
594     */
595    if (tmpl.array_size > 1) {
596       if (tmpl.target == PIPE_TEXTURE_CUBE)
597          tmpl.target = PIPE_TEXTURE_2D_ARRAY;
598       tmpl.array_size = box->depth;
599       tmpl.depth0 = 1;
600    } else {
601       tmpl.array_size = 1;
602       tmpl.depth0 = box->depth;
603    }
604    tmpl.last_level = 0;
605    tmpl.bind |= PIPE_BIND_LINEAR;
606    tmpl.usage = PIPE_USAGE_STAGING;
607 
608    struct pipe_resource *pstaging =
609       pctx->screen->resource_create(pctx->screen, &tmpl);
610    if (!pstaging)
611       return NULL;
612 
613    return fd_resource(pstaging);
614 }
615 
616 static void
fd_blit_from_staging(struct fd_context * ctx,struct fd_transfer * trans)617 fd_blit_from_staging(struct fd_context *ctx,
618                      struct fd_transfer *trans) assert_dt
619 {
620    DBG("");
621    struct pipe_resource *dst = trans->b.b.resource;
622    struct pipe_blit_info blit = {};
623 
624    blit.dst.resource = dst;
625    blit.dst.format = dst->format;
626    blit.dst.level = trans->b.b.level;
627    blit.dst.box = trans->b.b.box;
628    blit.src.resource = trans->staging_prsc;
629    blit.src.format = trans->staging_prsc->format;
630    blit.src.level = 0;
631    blit.src.box = trans->staging_box;
632    blit.mask = util_format_get_mask(trans->staging_prsc->format);
633    blit.filter = PIPE_TEX_FILTER_NEAREST;
634 
635    do_blit(ctx, &blit, false);
636 }
637 
638 static void
fd_blit_to_staging(struct fd_context * ctx,struct fd_transfer * trans)639 fd_blit_to_staging(struct fd_context *ctx, struct fd_transfer *trans) assert_dt
640 {
641    DBG("");
642    struct pipe_resource *src = trans->b.b.resource;
643    struct pipe_blit_info blit = {};
644 
645    blit.src.resource = src;
646    blit.src.format = src->format;
647    blit.src.level = trans->b.b.level;
648    blit.src.box = trans->b.b.box;
649    blit.dst.resource = trans->staging_prsc;
650    blit.dst.format = trans->staging_prsc->format;
651    blit.dst.level = 0;
652    blit.dst.box = trans->staging_box;
653    blit.mask = util_format_get_mask(trans->staging_prsc->format);
654    blit.filter = PIPE_TEX_FILTER_NEAREST;
655 
656    do_blit(ctx, &blit, false);
657 }
658 
659 static void
fd_resource_transfer_flush_region(struct pipe_context * pctx,struct pipe_transfer * ptrans,const struct pipe_box * box)660 fd_resource_transfer_flush_region(struct pipe_context *pctx,
661                                   struct pipe_transfer *ptrans,
662                                   const struct pipe_box *box)
663 {
664    struct fd_resource *rsc = fd_resource(ptrans->resource);
665 
666    if (ptrans->resource->target == PIPE_BUFFER)
667       util_range_add(&rsc->b.b, &rsc->valid_buffer_range,
668                      ptrans->box.x + box->x,
669                      ptrans->box.x + box->x + box->width);
670 }
671 
672 static void
flush_resource(struct fd_context * ctx,struct fd_resource * rsc,unsigned usage)673 flush_resource(struct fd_context *ctx, struct fd_resource *rsc,
674                unsigned usage) assert_dt
675 {
676    if (usage & PIPE_MAP_WRITE) {
677       fd_bc_flush_readers(ctx, rsc);
678    } else {
679       fd_bc_flush_writer(ctx, rsc);
680    }
681 }
682 
683 static void
fd_flush_resource(struct pipe_context * pctx,struct pipe_resource * prsc)684 fd_flush_resource(struct pipe_context *pctx, struct pipe_resource *prsc)
685    in_dt
686 {
687    struct fd_context *ctx = fd_context(pctx);
688    struct fd_resource *rsc = fd_resource(prsc);
689 
690    flush_resource(ctx, rsc, PIPE_MAP_READ);
691 
692    /* If we had to flush a batch, make sure it makes it's way all the
693     * way to the kernel:
694     */
695    fd_resource_wait(ctx, rsc, FD_BO_PREP_FLUSH);
696 }
697 
698 static void
fd_resource_transfer_unmap(struct pipe_context * pctx,struct pipe_transfer * ptrans)699 fd_resource_transfer_unmap(struct pipe_context *pctx,
700                            struct pipe_transfer *ptrans)
701    in_dt /* TODO for threaded-ctx we'll need to split out unsynchronized path */
702 {
703    struct fd_context *ctx = fd_context(pctx);
704    struct fd_resource *rsc = fd_resource(ptrans->resource);
705    struct fd_transfer *trans = fd_transfer(ptrans);
706 
707    if (trans->staging_prsc) {
708       if (ptrans->usage & PIPE_MAP_WRITE)
709          fd_blit_from_staging(ctx, trans);
710       pipe_resource_reference(&trans->staging_prsc, NULL);
711    }
712 
713    if (!(ptrans->usage & PIPE_MAP_UNSYNCHRONIZED)) {
714       fd_bo_cpu_fini(rsc->bo);
715    }
716 
717    util_range_add(&rsc->b.b, &rsc->valid_buffer_range, ptrans->box.x,
718                   ptrans->box.x + ptrans->box.width);
719 
720    pipe_resource_reference(&ptrans->resource, NULL);
721 
722    assert(trans->b.staging == NULL); /* for threaded context only */
723 
724    /* Don't use pool_transfers_unsync. We are always in the driver
725     * thread. Freeing an object into a different pool is allowed.
726     */
727    slab_free(&ctx->transfer_pool, ptrans);
728 }
729 
730 static void
invalidate_resource(struct fd_resource * rsc,unsigned usage)731 invalidate_resource(struct fd_resource *rsc, unsigned usage) assert_dt
732 {
733    bool needs_flush = pending(rsc, !!(usage & PIPE_MAP_WRITE));
734    unsigned op = translate_usage(usage);
735 
736    if (needs_flush || resource_busy(rsc, op)) {
737       rebind_resource(rsc);
738       realloc_bo(rsc, fd_bo_size(rsc->bo));
739    } else {
740       util_range_set_empty(&rsc->valid_buffer_range);
741    }
742 }
743 
744 static void *
resource_transfer_map_staging(struct pipe_context * pctx,struct pipe_resource * prsc,unsigned level,unsigned usage,const struct pipe_box * box,struct fd_transfer * trans)745 resource_transfer_map_staging(struct pipe_context *pctx,
746                               struct pipe_resource *prsc,
747                               unsigned level, unsigned usage,
748                               const struct pipe_box *box,
749                               struct fd_transfer *trans)
750    in_dt
751 {
752    struct fd_context *ctx = fd_context(pctx);
753    struct fd_resource *rsc = fd_resource(prsc);
754    struct fd_resource *staging_rsc;
755 
756    assert(prsc->target != PIPE_BUFFER);
757 
758    staging_rsc = fd_alloc_staging(ctx, rsc, level, box);
759    if (!staging_rsc)
760       return NULL;
761 
762    trans->staging_prsc = &staging_rsc->b.b;
763    trans->b.b.stride = fd_resource_pitch(staging_rsc, 0);
764    trans->b.b.layer_stride = fd_resource_layer_stride(staging_rsc, 0);
765    trans->staging_box = *box;
766    trans->staging_box.x = 0;
767    trans->staging_box.y = 0;
768    trans->staging_box.z = 0;
769 
770    if (usage & PIPE_MAP_READ) {
771       fd_blit_to_staging(ctx, trans);
772 
773       fd_resource_wait(ctx, staging_rsc, FD_BO_PREP_READ);
774    }
775 
776    ctx->stats.staging_uploads++;
777 
778    return fd_bo_map(staging_rsc->bo);
779 }
780 
781 static void *
resource_transfer_map_unsync(struct pipe_context * pctx,struct pipe_resource * prsc,unsigned level,unsigned usage,const struct pipe_box * box,struct fd_transfer * trans)782 resource_transfer_map_unsync(struct pipe_context *pctx,
783                              struct pipe_resource *prsc, unsigned level,
784                              unsigned usage, const struct pipe_box *box,
785                              struct fd_transfer *trans)
786 {
787    struct fd_resource *rsc = fd_resource(prsc);
788    enum pipe_format format = prsc->format;
789    uint32_t offset;
790    char *buf;
791 
792    buf = fd_bo_map(rsc->bo);
793 
794    /* With imported bo's allocated by something outside of mesa, when
795     * running in a VM (using virtio_gpu kernel driver) we could end up in
796     * a situation where we have a linear bo, but are unable to mmap it
797     * because it was allocated without the VIRTGPU_BLOB_FLAG_USE_MAPPABLE
798     * flag.  So we need end up needing to do a staging blit instead:
799     */
800    if (!buf)
801       return resource_transfer_map_staging(pctx, prsc, level, usage, box, trans);
802 
803    offset = box->y / util_format_get_blockheight(format) * trans->b.b.stride +
804             box->x / util_format_get_blockwidth(format) * rsc->layout.cpp +
805             fd_resource_offset(rsc, level, box->z);
806 
807    if (usage & PIPE_MAP_WRITE)
808       rsc->valid = true;
809 
810    return buf + offset;
811 }
812 
813 /**
814  * Note, with threaded_context, resource_transfer_map() is only called
815  * in driver thread, but resource_transfer_map_unsync() can be called in
816  * either driver or frontend thread.
817  */
818 static void *
resource_transfer_map(struct pipe_context * pctx,struct pipe_resource * prsc,unsigned level,unsigned usage,const struct pipe_box * box,struct fd_transfer * trans)819 resource_transfer_map(struct pipe_context *pctx, struct pipe_resource *prsc,
820                       unsigned level, unsigned usage,
821                       const struct pipe_box *box,
822                       struct fd_transfer *trans) in_dt
823 {
824    struct fd_context *ctx = fd_context(pctx);
825    struct fd_resource *rsc = fd_resource(prsc);
826    char *buf;
827    int ret = 0;
828 
829    tc_assert_driver_thread(ctx->tc);
830 
831    /* Strip the read flag if the buffer has been invalidated (or is freshly
832     * created). Avoids extra staging blits of undefined data on glTexSubImage of
833     * a fresh DEPTH_COMPONENT or STENCIL_INDEX texture being stored as z24s8.
834     */
835    if (!rsc->valid)
836       usage &= ~PIPE_MAP_READ;
837 
838    /* we always need a staging texture for tiled buffers:
839     *
840     * TODO we might sometimes want to *also* shadow the resource to avoid
841     * splitting a batch.. for ex, mid-frame texture uploads to a tiled
842     * texture.
843     */
844    if (rsc->layout.tile_mode) {
845       return resource_transfer_map_staging(pctx, prsc, level, usage, box, trans);
846    } else if ((usage & PIPE_MAP_READ) && !fd_bo_is_cached(rsc->bo)) {
847       perf_debug_ctx(ctx, "wc readback: prsc=%p, level=%u, usage=%x, box=%dx%d+%d,%d",
848                      prsc, level, usage, box->width, box->height, box->x, box->y);
849    }
850 
851    if (usage & PIPE_MAP_DISCARD_WHOLE_RESOURCE) {
852       invalidate_resource(rsc, usage);
853    } else {
854       unsigned op = translate_usage(usage);
855       bool needs_flush = pending(rsc, !!(usage & PIPE_MAP_WRITE));
856 
857       /* If the GPU is writing to the resource, or if it is reading from the
858        * resource and we're trying to write to it, flush the renders.
859        */
860       bool busy = needs_flush || resource_busy(rsc, op);
861 
862       /* if we need to flush/stall, see if we can make a shadow buffer
863        * to avoid this:
864        *
865        * TODO we could go down this path !reorder && !busy_for_read
866        * ie. we only *don't* want to go down this path if the blit
867        * will trigger a flush!
868        */
869       if (ctx->screen->reorder && busy && !(usage & PIPE_MAP_READ) &&
870           (usage & PIPE_MAP_DISCARD_RANGE)) {
871 
872          /* try shadowing only if it avoids a flush, otherwise staging would
873           * be better:
874           */
875          if (needs_flush && fd_try_shadow_resource(ctx, rsc, level, box,
876                                                    DRM_FORMAT_MOD_LINEAR)) {
877             needs_flush = busy = false;
878             ctx->stats.shadow_uploads++;
879          } else {
880             struct fd_resource *staging_rsc = NULL;
881 
882             if (needs_flush) {
883                flush_resource(ctx, rsc, usage);
884                needs_flush = false;
885             }
886 
887             /* in this case, we don't need to shadow the whole resource,
888              * since any draw that references the previous contents has
889              * already had rendering flushed for all tiles.  So we can
890              * use a staging buffer to do the upload.
891              */
892             if (is_renderable(prsc))
893                staging_rsc = fd_alloc_staging(ctx, rsc, level, box);
894             if (staging_rsc) {
895                trans->staging_prsc = &staging_rsc->b.b;
896                trans->b.b.stride = fd_resource_pitch(staging_rsc, 0);
897                trans->b.b.layer_stride =
898                   fd_resource_layer_stride(staging_rsc, 0);
899                trans->staging_box = *box;
900                trans->staging_box.x = 0;
901                trans->staging_box.y = 0;
902                trans->staging_box.z = 0;
903                buf = fd_bo_map(staging_rsc->bo);
904 
905                ctx->stats.staging_uploads++;
906 
907                return buf;
908             }
909          }
910       }
911 
912       if (needs_flush) {
913          flush_resource(ctx, rsc, usage);
914          needs_flush = false;
915       }
916 
917       /* The GPU keeps track of how the various bo's are being used, and
918        * will wait if necessary for the proper operation to have
919        * completed.
920        */
921       if (busy) {
922          ret = fd_resource_wait(ctx, rsc, op);
923          if (ret)
924             return NULL;
925       }
926    }
927 
928    return resource_transfer_map_unsync(pctx, prsc, level, usage, box, trans);
929 }
930 
931 static unsigned
improve_transfer_map_usage(struct fd_context * ctx,struct fd_resource * rsc,unsigned usage,const struct pipe_box * box)932 improve_transfer_map_usage(struct fd_context *ctx, struct fd_resource *rsc,
933                            unsigned usage, const struct pipe_box *box)
934    /* Not *strictly* true, but the access to things that must only be in driver-
935     * thread are protected by !(usage & TC_TRANSFER_MAP_THREADED_UNSYNC):
936     */
937    in_dt
938 {
939    if (usage & TC_TRANSFER_MAP_NO_INVALIDATE) {
940       usage &= ~PIPE_MAP_DISCARD_WHOLE_RESOURCE;
941    }
942 
943    if (usage & TC_TRANSFER_MAP_THREADED_UNSYNC)
944       usage |= PIPE_MAP_UNSYNCHRONIZED;
945 
946    if (!(usage &
947          (TC_TRANSFER_MAP_NO_INFER_UNSYNCHRONIZED | PIPE_MAP_UNSYNCHRONIZED))) {
948       if (ctx->in_shadow && !(usage & PIPE_MAP_READ)) {
949          usage |= PIPE_MAP_UNSYNCHRONIZED;
950       } else if ((usage & PIPE_MAP_WRITE) && (rsc->b.b.target == PIPE_BUFFER) &&
951                  !util_ranges_intersect(&rsc->valid_buffer_range, box->x,
952                                         box->x + box->width)) {
953          /* We are trying to write to a previously uninitialized range. No need
954           * to synchronize.
955           */
956          usage |= PIPE_MAP_UNSYNCHRONIZED;
957       }
958    }
959 
960    return usage;
961 }
962 
963 static void *
fd_resource_transfer_map(struct pipe_context * pctx,struct pipe_resource * prsc,unsigned level,unsigned usage,const struct pipe_box * box,struct pipe_transfer ** pptrans)964 fd_resource_transfer_map(struct pipe_context *pctx, struct pipe_resource *prsc,
965                          unsigned level, unsigned usage,
966                          const struct pipe_box *box,
967                          struct pipe_transfer **pptrans)
968 {
969    struct fd_context *ctx = fd_context(pctx);
970    struct fd_resource *rsc = fd_resource(prsc);
971    struct fd_transfer *trans;
972    struct pipe_transfer *ptrans;
973 
974    DBG("prsc=%p, level=%u, usage=%x, box=%dx%d+%d,%d", prsc, level, usage,
975        box->width, box->height, box->x, box->y);
976 
977    if ((usage & PIPE_MAP_DIRECTLY) && rsc->layout.tile_mode) {
978       DBG("CANNOT MAP DIRECTLY!\n");
979       return NULL;
980    }
981 
982    if (usage & TC_TRANSFER_MAP_THREADED_UNSYNC) {
983       ptrans = slab_zalloc(&ctx->transfer_pool_unsync);
984    } else {
985       ptrans = slab_zalloc(&ctx->transfer_pool);
986    }
987 
988    if (!ptrans)
989       return NULL;
990 
991    trans = fd_transfer(ptrans);
992 
993    usage = improve_transfer_map_usage(ctx, rsc, usage, box);
994 
995    pipe_resource_reference(&ptrans->resource, prsc);
996    ptrans->level = level;
997    ptrans->usage = usage;
998    ptrans->box = *box;
999    ptrans->stride = fd_resource_pitch(rsc, level);
1000    ptrans->layer_stride = fd_resource_layer_stride(rsc, level);
1001 
1002    void *ret;
1003    if (usage & PIPE_MAP_UNSYNCHRONIZED) {
1004       ret = resource_transfer_map_unsync(pctx, prsc, level, usage, box, trans);
1005    } else {
1006       ret = resource_transfer_map(pctx, prsc, level, usage, box, trans);
1007    }
1008 
1009    if (ret) {
1010       *pptrans = ptrans;
1011    } else {
1012       fd_resource_transfer_unmap(pctx, ptrans);
1013    }
1014 
1015    return ret;
1016 }
1017 
1018 static void
fd_resource_destroy(struct pipe_screen * pscreen,struct pipe_resource * prsc)1019 fd_resource_destroy(struct pipe_screen *pscreen, struct pipe_resource *prsc)
1020 {
1021    struct fd_screen *screen = fd_screen(prsc->screen);
1022    struct fd_resource *rsc = fd_resource(prsc);
1023 
1024    if (!rsc->is_replacement)
1025       fd_bc_invalidate_resource(rsc, true);
1026    if (rsc->bo)
1027       fd_bo_del(rsc->bo);
1028    if (rsc->lrz)
1029       fd_bo_del(rsc->lrz);
1030    if (rsc->scanout)
1031       renderonly_scanout_destroy(rsc->scanout, fd_screen(pscreen)->ro);
1032 
1033    if (prsc->target == PIPE_BUFFER)
1034       util_idalloc_mt_free(&screen->buffer_ids, rsc->b.buffer_id_unique);
1035 
1036    threaded_resource_deinit(prsc);
1037 
1038    util_range_destroy(&rsc->valid_buffer_range);
1039    simple_mtx_destroy(&rsc->lock);
1040    fd_resource_tracking_reference(&rsc->track, NULL);
1041 
1042    FREE(rsc);
1043 }
1044 
1045 static uint64_t
fd_resource_modifier(struct fd_resource * rsc)1046 fd_resource_modifier(struct fd_resource *rsc)
1047 {
1048    if (!rsc->layout.tile_mode)
1049       return DRM_FORMAT_MOD_LINEAR;
1050 
1051    if (rsc->layout.ubwc_layer_size)
1052       return DRM_FORMAT_MOD_QCOM_COMPRESSED;
1053 
1054    /* TODO invent a modifier for tiled but not UBWC buffers: */
1055    return DRM_FORMAT_MOD_INVALID;
1056 }
1057 
1058 static bool
fd_resource_get_handle(struct pipe_screen * pscreen,struct pipe_context * pctx,struct pipe_resource * prsc,struct winsys_handle * handle,unsigned usage)1059 fd_resource_get_handle(struct pipe_screen *pscreen, struct pipe_context *pctx,
1060                        struct pipe_resource *prsc, struct winsys_handle *handle,
1061                        unsigned usage)
1062 {
1063    struct fd_resource *rsc = fd_resource(prsc);
1064 
1065    rsc->b.is_shared = true;
1066 
1067    handle->modifier = fd_resource_modifier(rsc);
1068 
1069    DBG("%" PRSC_FMT ", modifier=%" PRIx64, PRSC_ARGS(prsc), handle->modifier);
1070 
1071    return fd_screen_bo_get_handle(pscreen, rsc->bo, rsc->scanout,
1072                                   fd_resource_pitch(rsc, 0), handle);
1073 }
1074 
1075 /* special case to resize query buf after allocated.. */
1076 void
fd_resource_resize(struct pipe_resource * prsc,uint32_t sz)1077 fd_resource_resize(struct pipe_resource *prsc, uint32_t sz)
1078 {
1079    struct fd_resource *rsc = fd_resource(prsc);
1080 
1081    assert(prsc->width0 == 0);
1082    assert(prsc->target == PIPE_BUFFER);
1083    assert(prsc->bind == PIPE_BIND_QUERY_BUFFER);
1084 
1085    prsc->width0 = sz;
1086    realloc_bo(rsc, fd_screen(prsc->screen)->setup_slices(rsc));
1087 }
1088 
1089 static void
fd_resource_layout_init(struct pipe_resource * prsc)1090 fd_resource_layout_init(struct pipe_resource *prsc)
1091 {
1092    struct fd_resource *rsc = fd_resource(prsc);
1093    struct fdl_layout *layout = &rsc->layout;
1094 
1095    layout->format = prsc->format;
1096 
1097    layout->width0 = prsc->width0;
1098    layout->height0 = prsc->height0;
1099    layout->depth0 = prsc->depth0;
1100 
1101    layout->cpp = util_format_get_blocksize(prsc->format);
1102    layout->cpp *= fd_resource_nr_samples(prsc);
1103    layout->cpp_shift = ffs(layout->cpp) - 1;
1104 }
1105 
1106 static struct fd_resource *
alloc_resource_struct(struct pipe_screen * pscreen,const struct pipe_resource * tmpl)1107 alloc_resource_struct(struct pipe_screen *pscreen,
1108                       const struct pipe_resource *tmpl)
1109 {
1110    struct fd_screen *screen = fd_screen(pscreen);
1111    struct fd_resource *rsc = CALLOC_STRUCT(fd_resource);
1112 
1113    if (!rsc)
1114       return NULL;
1115 
1116    struct pipe_resource *prsc = &rsc->b.b;
1117    *prsc = *tmpl;
1118 
1119    pipe_reference_init(&prsc->reference, 1);
1120    prsc->screen = pscreen;
1121    rsc->hash = _mesa_hash_pointer(rsc);
1122 
1123    util_range_init(&rsc->valid_buffer_range);
1124    simple_mtx_init(&rsc->lock, mtx_plain);
1125 
1126    rsc->track = CALLOC_STRUCT(fd_resource_tracking);
1127    if (!rsc->track) {
1128       free(rsc);
1129       return NULL;
1130    }
1131 
1132    pipe_reference_init(&rsc->track->reference, 1);
1133 
1134    threaded_resource_init(prsc, false);
1135 
1136    if (tmpl->target == PIPE_BUFFER)
1137       rsc->b.buffer_id_unique = util_idalloc_mt_alloc(&screen->buffer_ids);
1138 
1139    return rsc;
1140 }
1141 
1142 enum fd_layout_type {
1143    ERROR,
1144    LINEAR,
1145    TILED,
1146    UBWC,
1147 };
1148 
1149 static enum fd_layout_type
get_best_layout(struct fd_screen * screen,struct pipe_resource * prsc,const struct pipe_resource * tmpl,const uint64_t * modifiers,int count)1150 get_best_layout(struct fd_screen *screen, struct pipe_resource *prsc,
1151                 const struct pipe_resource *tmpl, const uint64_t *modifiers,
1152                 int count)
1153 {
1154    bool implicit_modifiers =
1155       (count == 0 ||
1156        drm_find_modifier(DRM_FORMAT_MOD_INVALID, modifiers, count));
1157 
1158    /* First, find all the conditions which would force us to linear */
1159    if (!screen->tile_mode)
1160       return LINEAR;
1161 
1162    if (!screen->tile_mode(prsc))
1163       return LINEAR;
1164 
1165    if (tmpl->target == PIPE_BUFFER)
1166       return LINEAR;
1167 
1168    if (tmpl->bind & PIPE_BIND_LINEAR) {
1169       if (tmpl->usage != PIPE_USAGE_STAGING)
1170          perf_debug("%" PRSC_FMT ": forcing linear: bind flags",
1171                     PRSC_ARGS(prsc));
1172       return LINEAR;
1173    }
1174 
1175    if (FD_DBG(NOTILE))
1176        return LINEAR;
1177 
1178    /* Shared resources with implicit modifiers must always be linear */
1179    if (implicit_modifiers && (tmpl->bind & PIPE_BIND_SHARED)) {
1180       perf_debug("%" PRSC_FMT
1181                  ": forcing linear: shared resource + implicit modifiers",
1182                  PRSC_ARGS(prsc));
1183       return LINEAR;
1184    }
1185 
1186    bool ubwc_ok = is_a6xx(screen);
1187    if (FD_DBG(NOUBWC))
1188       ubwc_ok = false;
1189 
1190    if (ubwc_ok && !implicit_modifiers &&
1191        !drm_find_modifier(DRM_FORMAT_MOD_QCOM_COMPRESSED, modifiers, count)) {
1192       perf_debug("%" PRSC_FMT
1193                  ": not using UBWC: not in acceptable modifier set",
1194                  PRSC_ARGS(prsc));
1195       ubwc_ok = false;
1196    }
1197 
1198    if (ubwc_ok)
1199       return UBWC;
1200 
1201    /* We can't use tiled with explicit modifiers, as there is no modifier token
1202     * defined for it. But we might internally force tiled allocation using a
1203     * private modifier token.
1204     *
1205     * TODO we should probably also limit TILED in a similar way to UBWC above,
1206     * once we have a public modifier token defined.
1207     */
1208    if (implicit_modifiers ||
1209        drm_find_modifier(FD_FORMAT_MOD_QCOM_TILED, modifiers, count))
1210       return TILED;
1211 
1212    if (!drm_find_modifier(DRM_FORMAT_MOD_LINEAR, modifiers, count)) {
1213       perf_debug("%" PRSC_FMT ": need linear but not in modifier set",
1214                  PRSC_ARGS(prsc));
1215       return ERROR;
1216    }
1217 
1218    perf_debug("%" PRSC_FMT ": not using tiling: explicit modifiers and no UBWC",
1219               PRSC_ARGS(prsc));
1220    return LINEAR;
1221 }
1222 
1223 /**
1224  * Helper that allocates a resource and resolves its layout (but doesn't
1225  * allocate its bo).
1226  *
1227  * It returns a pipe_resource (as fd_resource_create_with_modifiers()
1228  * would do), and also bo's minimum required size as an output argument.
1229  */
1230 static struct pipe_resource *
fd_resource_allocate_and_resolve(struct pipe_screen * pscreen,const struct pipe_resource * tmpl,const uint64_t * modifiers,int count,uint32_t * psize)1231 fd_resource_allocate_and_resolve(struct pipe_screen *pscreen,
1232                                  const struct pipe_resource *tmpl,
1233                                  const uint64_t *modifiers, int count,
1234                                  uint32_t *psize)
1235 {
1236    struct fd_screen *screen = fd_screen(pscreen);
1237    struct fd_resource *rsc;
1238    struct pipe_resource *prsc;
1239    enum pipe_format format = tmpl->format;
1240    uint32_t size;
1241 
1242    rsc = alloc_resource_struct(pscreen, tmpl);
1243    if (!rsc)
1244       return NULL;
1245 
1246    prsc = &rsc->b.b;
1247 
1248    /* Clover creates buffers with PIPE_FORMAT_NONE: */
1249    if ((prsc->target == PIPE_BUFFER) && (format == PIPE_FORMAT_NONE))
1250       format = prsc->format = PIPE_FORMAT_R8_UNORM;
1251 
1252    DBG("%" PRSC_FMT, PRSC_ARGS(prsc));
1253 
1254    if (tmpl->bind & PIPE_BIND_SHARED)
1255       rsc->b.is_shared = true;
1256 
1257    fd_resource_layout_init(prsc);
1258 
1259    enum fd_layout_type layout =
1260       get_best_layout(screen, prsc, tmpl, modifiers, count);
1261    if (layout == ERROR) {
1262       free(prsc);
1263       return NULL;
1264    }
1265 
1266    if (layout >= TILED)
1267       rsc->layout.tile_mode = screen->tile_mode(prsc);
1268    if (layout == UBWC)
1269       rsc->layout.ubwc = true;
1270 
1271    rsc->internal_format = format;
1272 
1273    if (prsc->target == PIPE_BUFFER) {
1274       assert(prsc->format == PIPE_FORMAT_R8_UNORM);
1275       size = prsc->width0;
1276       fdl_layout_buffer(&rsc->layout, size);
1277    } else {
1278       size = screen->setup_slices(rsc);
1279    }
1280 
1281    /* special case for hw-query buffer, which we need to allocate before we
1282     * know the size:
1283     */
1284    if (size == 0) {
1285       /* note, semi-intention == instead of & */
1286       assert(prsc->bind == PIPE_BIND_QUERY_BUFFER);
1287       *psize = 0;
1288       return prsc;
1289    }
1290 
1291    /* Set the layer size if the (non-a6xx) backend hasn't done so. */
1292    if (rsc->layout.layer_first && !rsc->layout.layer_size) {
1293       rsc->layout.layer_size = align(size, 4096);
1294       size = rsc->layout.layer_size * prsc->array_size;
1295    }
1296 
1297    if (FD_DBG(LAYOUT))
1298       fdl_dump_layout(&rsc->layout);
1299 
1300    /* Hand out the resolved size. */
1301    if (psize)
1302       *psize = size;
1303 
1304    return prsc;
1305 }
1306 
1307 /**
1308  * Create a new texture object, using the given template info.
1309  */
1310 static struct pipe_resource *
fd_resource_create_with_modifiers(struct pipe_screen * pscreen,const struct pipe_resource * tmpl,const uint64_t * modifiers,int count)1311 fd_resource_create_with_modifiers(struct pipe_screen *pscreen,
1312                                   const struct pipe_resource *tmpl,
1313                                   const uint64_t *modifiers, int count)
1314 {
1315    struct fd_screen *screen = fd_screen(pscreen);
1316    struct fd_resource *rsc;
1317    struct pipe_resource *prsc;
1318    uint32_t size;
1319 
1320    /* when using kmsro, scanout buffers are allocated on the display device
1321     * create_with_modifiers() doesn't give us usage flags, so we have to
1322     * assume that all calls with modifiers are scanout-possible
1323     */
1324    if (screen->ro &&
1325        ((tmpl->bind & PIPE_BIND_SCANOUT) ||
1326         !(count == 1 && modifiers[0] == DRM_FORMAT_MOD_INVALID))) {
1327       struct pipe_resource scanout_templat = *tmpl;
1328       struct renderonly_scanout *scanout;
1329       struct winsys_handle handle;
1330 
1331       /* note: alignment is wrong for a6xx */
1332       scanout_templat.width0 = align(tmpl->width0, screen->info->gmem_align_w);
1333 
1334       scanout =
1335          renderonly_scanout_for_resource(&scanout_templat, screen->ro, &handle);
1336       if (!scanout)
1337          return NULL;
1338 
1339       renderonly_scanout_destroy(scanout, screen->ro);
1340 
1341       assert(handle.type == WINSYS_HANDLE_TYPE_FD);
1342       rsc = fd_resource(pscreen->resource_from_handle(
1343          pscreen, tmpl, &handle, PIPE_HANDLE_USAGE_FRAMEBUFFER_WRITE));
1344       close(handle.handle);
1345       if (!rsc)
1346          return NULL;
1347 
1348       return &rsc->b.b;
1349    }
1350 
1351    prsc =
1352       fd_resource_allocate_and_resolve(pscreen, tmpl, modifiers, count, &size);
1353    if (!prsc)
1354       return NULL;
1355    rsc = fd_resource(prsc);
1356 
1357    realloc_bo(rsc, size);
1358    if (!rsc->bo)
1359       goto fail;
1360 
1361    return prsc;
1362 fail:
1363    fd_resource_destroy(pscreen, prsc);
1364    return NULL;
1365 }
1366 
1367 static struct pipe_resource *
fd_resource_create(struct pipe_screen * pscreen,const struct pipe_resource * tmpl)1368 fd_resource_create(struct pipe_screen *pscreen,
1369                    const struct pipe_resource *tmpl)
1370 {
1371    const uint64_t mod = DRM_FORMAT_MOD_INVALID;
1372    return fd_resource_create_with_modifiers(pscreen, tmpl, &mod, 1);
1373 }
1374 
1375 /**
1376  * Create a texture from a winsys_handle. The handle is often created in
1377  * another process by first creating a pipe texture and then calling
1378  * resource_get_handle.
1379  */
1380 static struct pipe_resource *
fd_resource_from_handle(struct pipe_screen * pscreen,const struct pipe_resource * tmpl,struct winsys_handle * handle,unsigned usage)1381 fd_resource_from_handle(struct pipe_screen *pscreen,
1382                         const struct pipe_resource *tmpl,
1383                         struct winsys_handle *handle, unsigned usage)
1384 {
1385    struct fd_screen *screen = fd_screen(pscreen);
1386    struct fd_resource *rsc = alloc_resource_struct(pscreen, tmpl);
1387 
1388    if (!rsc)
1389       return NULL;
1390 
1391    struct fdl_slice *slice = fd_resource_slice(rsc, 0);
1392    struct pipe_resource *prsc = &rsc->b.b;
1393 
1394    DBG("%" PRSC_FMT ", modifier=%" PRIx64, PRSC_ARGS(prsc), handle->modifier);
1395 
1396    rsc->b.is_shared = true;
1397 
1398    fd_resource_layout_init(prsc);
1399 
1400    struct fd_bo *bo = fd_screen_bo_from_handle(pscreen, handle);
1401    if (!bo)
1402       goto fail;
1403 
1404    fd_resource_set_bo(rsc, bo);
1405 
1406    rsc->internal_format = tmpl->format;
1407    rsc->layout.layer_first = true;
1408    rsc->layout.pitch0 = handle->stride;
1409    slice->offset = handle->offset;
1410    slice->size0 = handle->stride * prsc->height0;
1411 
1412    /* use a pitchalign of gmem_align_w pixels, because GMEM resolve for
1413     * lower alignments is not implemented (but possible for a6xx at least)
1414     *
1415     * for UBWC-enabled resources, layout_resource_for_modifier will further
1416     * validate the pitch and set the right pitchalign
1417     */
1418    rsc->layout.pitchalign =
1419       fdl_cpp_shift(&rsc->layout) + util_logbase2(screen->info->gmem_align_w);
1420 
1421    /* apply the minimum pitchalign (note: actually 4 for a3xx but doesn't
1422     * matter) */
1423    if (is_a6xx(screen) || is_a5xx(screen))
1424       rsc->layout.pitchalign = MAX2(rsc->layout.pitchalign, 6);
1425    else
1426       rsc->layout.pitchalign = MAX2(rsc->layout.pitchalign, 5);
1427 
1428    if (rsc->layout.pitch0 < (prsc->width0 * rsc->layout.cpp) ||
1429        fd_resource_pitch(rsc, 0) != rsc->layout.pitch0)
1430       goto fail;
1431 
1432    assert(rsc->layout.cpp);
1433 
1434    if (screen->layout_resource_for_modifier(rsc, handle->modifier) < 0)
1435       goto fail;
1436 
1437    if (screen->ro) {
1438       rsc->scanout =
1439          renderonly_create_gpu_import_for_resource(prsc, screen->ro, NULL);
1440       /* failure is expected in some cases.. */
1441    }
1442 
1443    rsc->valid = true;
1444 
1445    return prsc;
1446 
1447 fail:
1448    fd_resource_destroy(pscreen, prsc);
1449    return NULL;
1450 }
1451 
1452 bool
fd_render_condition_check(struct pipe_context * pctx)1453 fd_render_condition_check(struct pipe_context *pctx)
1454 {
1455    struct fd_context *ctx = fd_context(pctx);
1456 
1457    if (!ctx->cond_query)
1458       return true;
1459 
1460    perf_debug("Implementing conditional rendering using a CPU read instaed of HW conditional rendering.");
1461 
1462    union pipe_query_result res = {0};
1463    bool wait = ctx->cond_mode != PIPE_RENDER_COND_NO_WAIT &&
1464                ctx->cond_mode != PIPE_RENDER_COND_BY_REGION_NO_WAIT;
1465 
1466    if (pctx->get_query_result(pctx, ctx->cond_query, wait, &res))
1467       return (bool)res.u64 != ctx->cond_cond;
1468 
1469    return true;
1470 }
1471 
1472 static void
fd_invalidate_resource(struct pipe_context * pctx,struct pipe_resource * prsc)1473 fd_invalidate_resource(struct pipe_context *pctx,
1474                        struct pipe_resource *prsc) in_dt
1475 {
1476    struct fd_context *ctx = fd_context(pctx);
1477    struct fd_resource *rsc = fd_resource(prsc);
1478 
1479    if (prsc->target == PIPE_BUFFER) {
1480       /* Handle the glInvalidateBufferData() case:
1481        */
1482       invalidate_resource(rsc, PIPE_MAP_READ | PIPE_MAP_WRITE);
1483    } else if (rsc->track->write_batch) {
1484       /* Handle the glInvalidateFramebuffer() case, telling us that
1485        * we can skip resolve.
1486        */
1487 
1488       struct fd_batch *batch = rsc->track->write_batch;
1489       struct pipe_framebuffer_state *pfb = &batch->framebuffer;
1490 
1491       if (pfb->zsbuf && pfb->zsbuf->texture == prsc) {
1492          batch->resolve &= ~(FD_BUFFER_DEPTH | FD_BUFFER_STENCIL);
1493          fd_context_dirty(ctx, FD_DIRTY_ZSA);
1494       }
1495 
1496       for (unsigned i = 0; i < pfb->nr_cbufs; i++) {
1497          if (pfb->cbufs[i] && pfb->cbufs[i]->texture == prsc) {
1498             batch->resolve &= ~(PIPE_CLEAR_COLOR0 << i);
1499             fd_context_dirty(ctx, FD_DIRTY_FRAMEBUFFER);
1500          }
1501       }
1502    }
1503 
1504    rsc->valid = false;
1505 }
1506 
1507 static enum pipe_format
fd_resource_get_internal_format(struct pipe_resource * prsc)1508 fd_resource_get_internal_format(struct pipe_resource *prsc)
1509 {
1510    return fd_resource(prsc)->internal_format;
1511 }
1512 
1513 static void
fd_resource_set_stencil(struct pipe_resource * prsc,struct pipe_resource * stencil)1514 fd_resource_set_stencil(struct pipe_resource *prsc,
1515                         struct pipe_resource *stencil)
1516 {
1517    fd_resource(prsc)->stencil = fd_resource(stencil);
1518 }
1519 
1520 static struct pipe_resource *
fd_resource_get_stencil(struct pipe_resource * prsc)1521 fd_resource_get_stencil(struct pipe_resource *prsc)
1522 {
1523    struct fd_resource *rsc = fd_resource(prsc);
1524    if (rsc->stencil)
1525       return &rsc->stencil->b.b;
1526    return NULL;
1527 }
1528 
1529 static const struct u_transfer_vtbl transfer_vtbl = {
1530    .resource_create = fd_resource_create,
1531    .resource_destroy = fd_resource_destroy,
1532    .transfer_map = fd_resource_transfer_map,
1533    .transfer_flush_region = fd_resource_transfer_flush_region,
1534    .transfer_unmap = fd_resource_transfer_unmap,
1535    .get_internal_format = fd_resource_get_internal_format,
1536    .set_stencil = fd_resource_set_stencil,
1537    .get_stencil = fd_resource_get_stencil,
1538 };
1539 
1540 static const uint64_t supported_modifiers[] = {
1541    DRM_FORMAT_MOD_LINEAR,
1542 };
1543 
1544 static int
fd_layout_resource_for_modifier(struct fd_resource * rsc,uint64_t modifier)1545 fd_layout_resource_for_modifier(struct fd_resource *rsc, uint64_t modifier)
1546 {
1547    switch (modifier) {
1548    case DRM_FORMAT_MOD_LINEAR:
1549       /* The dri gallium frontend will pass DRM_FORMAT_MOD_INVALID to us
1550        * when it's called through any of the non-modifier BO create entry
1551        * points.  Other drivers will determine tiling from the kernel or
1552        * other legacy backchannels, but for freedreno it just means
1553        * LINEAR. */
1554    case DRM_FORMAT_MOD_INVALID:
1555       return 0;
1556    default:
1557       return -1;
1558    }
1559 }
1560 
1561 static struct pipe_resource *
fd_resource_from_memobj(struct pipe_screen * pscreen,const struct pipe_resource * tmpl,struct pipe_memory_object * pmemobj,uint64_t offset)1562 fd_resource_from_memobj(struct pipe_screen *pscreen,
1563                         const struct pipe_resource *tmpl,
1564                         struct pipe_memory_object *pmemobj, uint64_t offset)
1565 {
1566    struct fd_screen *screen = fd_screen(pscreen);
1567    struct fd_memory_object *memobj = fd_memory_object(pmemobj);
1568    struct pipe_resource *prsc;
1569    struct fd_resource *rsc;
1570    uint32_t size;
1571    assert(memobj->bo);
1572 
1573    /* We shouldn't get a scanout buffer here. */
1574    assert(!(tmpl->bind & PIPE_BIND_SCANOUT));
1575 
1576    uint64_t modifiers = DRM_FORMAT_MOD_INVALID;
1577    if (tmpl->bind & PIPE_BIND_LINEAR) {
1578       modifiers = DRM_FORMAT_MOD_LINEAR;
1579    } else if (is_a6xx(screen) && tmpl->width0 >= FDL_MIN_UBWC_WIDTH) {
1580       modifiers = DRM_FORMAT_MOD_QCOM_COMPRESSED;
1581    }
1582 
1583    /* Allocate new pipe resource. */
1584    prsc = fd_resource_allocate_and_resolve(pscreen, tmpl, &modifiers, 1, &size);
1585    if (!prsc)
1586       return NULL;
1587    rsc = fd_resource(prsc);
1588    rsc->b.is_shared = true;
1589 
1590    /* bo's size has to be large enough, otherwise cleanup resource and fail
1591     * gracefully.
1592     */
1593    if (fd_bo_size(memobj->bo) < size) {
1594       fd_resource_destroy(pscreen, prsc);
1595       return NULL;
1596    }
1597 
1598    /* Share the bo with the memory object. */
1599    fd_resource_set_bo(rsc, fd_bo_ref(memobj->bo));
1600 
1601    return prsc;
1602 }
1603 
1604 static struct pipe_memory_object *
fd_memobj_create_from_handle(struct pipe_screen * pscreen,struct winsys_handle * whandle,bool dedicated)1605 fd_memobj_create_from_handle(struct pipe_screen *pscreen,
1606                              struct winsys_handle *whandle, bool dedicated)
1607 {
1608    struct fd_memory_object *memobj = CALLOC_STRUCT(fd_memory_object);
1609    if (!memobj)
1610       return NULL;
1611 
1612    struct fd_bo *bo = fd_screen_bo_from_handle(pscreen, whandle);
1613    if (!bo) {
1614       free(memobj);
1615       return NULL;
1616    }
1617 
1618    memobj->b.dedicated = dedicated;
1619    memobj->bo = bo;
1620 
1621    return &memobj->b;
1622 }
1623 
1624 static void
fd_memobj_destroy(struct pipe_screen * pscreen,struct pipe_memory_object * pmemobj)1625 fd_memobj_destroy(struct pipe_screen *pscreen,
1626                   struct pipe_memory_object *pmemobj)
1627 {
1628    struct fd_memory_object *memobj = fd_memory_object(pmemobj);
1629 
1630    assert(memobj->bo);
1631    fd_bo_del(memobj->bo);
1632 
1633    free(pmemobj);
1634 }
1635 
1636 void
fd_resource_screen_init(struct pipe_screen * pscreen)1637 fd_resource_screen_init(struct pipe_screen *pscreen)
1638 {
1639    struct fd_screen *screen = fd_screen(pscreen);
1640    bool fake_rgtc = screen->gen < 4;
1641 
1642    pscreen->resource_create = u_transfer_helper_resource_create;
1643    /* NOTE: u_transfer_helper does not yet support the _with_modifiers()
1644     * variant:
1645     */
1646    pscreen->resource_create_with_modifiers = fd_resource_create_with_modifiers;
1647    pscreen->resource_from_handle = fd_resource_from_handle;
1648    pscreen->resource_get_handle = fd_resource_get_handle;
1649    pscreen->resource_destroy = u_transfer_helper_resource_destroy;
1650 
1651    pscreen->transfer_helper =
1652       u_transfer_helper_create(&transfer_vtbl, true, false, fake_rgtc, true, false);
1653 
1654    if (!screen->layout_resource_for_modifier)
1655       screen->layout_resource_for_modifier = fd_layout_resource_for_modifier;
1656    if (!screen->supported_modifiers) {
1657       screen->supported_modifiers = supported_modifiers;
1658       screen->num_supported_modifiers = ARRAY_SIZE(supported_modifiers);
1659    }
1660 
1661    /* GL_EXT_memory_object */
1662    pscreen->memobj_create_from_handle = fd_memobj_create_from_handle;
1663    pscreen->memobj_destroy = fd_memobj_destroy;
1664    pscreen->resource_from_memobj = fd_resource_from_memobj;
1665 }
1666 
1667 static void
fd_get_sample_position(struct pipe_context * context,unsigned sample_count,unsigned sample_index,float * pos_out)1668 fd_get_sample_position(struct pipe_context *context, unsigned sample_count,
1669                        unsigned sample_index, float *pos_out)
1670 {
1671    /* The following is copied from nouveau/nv50 except for position
1672     * values, which are taken from blob driver */
1673    static const uint8_t pos1[1][2] = {{0x8, 0x8}};
1674    static const uint8_t pos2[2][2] = {{0xc, 0xc}, {0x4, 0x4}};
1675    static const uint8_t pos4[4][2] = {{0x6, 0x2},
1676                                       {0xe, 0x6},
1677                                       {0x2, 0xa},
1678                                       {0xa, 0xe}};
1679    /* TODO needs to be verified on supported hw */
1680    static const uint8_t pos8[8][2] = {{0x9, 0x5}, {0x7, 0xb}, {0xd, 0x9},
1681                                       {0x5, 0x3}, {0x3, 0xd}, {0x1, 0x7},
1682                                       {0xb, 0xf}, {0xf, 0x1}};
1683 
1684    const uint8_t(*ptr)[2];
1685 
1686    switch (sample_count) {
1687    case 1:
1688       ptr = pos1;
1689       break;
1690    case 2:
1691       ptr = pos2;
1692       break;
1693    case 4:
1694       ptr = pos4;
1695       break;
1696    case 8:
1697       ptr = pos8;
1698       break;
1699    default:
1700       assert(0);
1701       return;
1702    }
1703 
1704    pos_out[0] = ptr[sample_index][0] / 16.0f;
1705    pos_out[1] = ptr[sample_index][1] / 16.0f;
1706 }
1707 
1708 static void
fd_blit_pipe(struct pipe_context * pctx,const struct pipe_blit_info * blit_info)1709 fd_blit_pipe(struct pipe_context *pctx,
1710              const struct pipe_blit_info *blit_info) in_dt
1711 {
1712    /* wrap fd_blit to return void */
1713    fd_blit(pctx, blit_info);
1714 }
1715 
1716 void
fd_resource_context_init(struct pipe_context * pctx)1717 fd_resource_context_init(struct pipe_context *pctx)
1718 {
1719    pctx->buffer_map = u_transfer_helper_transfer_map;
1720    pctx->texture_map = u_transfer_helper_transfer_map;
1721    pctx->transfer_flush_region = u_transfer_helper_transfer_flush_region;
1722    pctx->buffer_unmap = u_transfer_helper_transfer_unmap;
1723    pctx->texture_unmap = u_transfer_helper_transfer_unmap;
1724    pctx->buffer_subdata = u_default_buffer_subdata;
1725    pctx->texture_subdata = u_default_texture_subdata;
1726    pctx->create_surface = fd_create_surface;
1727    pctx->surface_destroy = fd_surface_destroy;
1728    pctx->resource_copy_region = fd_resource_copy_region;
1729    pctx->blit = fd_blit_pipe;
1730    pctx->flush_resource = fd_flush_resource;
1731    pctx->invalidate_resource = fd_invalidate_resource;
1732    pctx->get_sample_position = fd_get_sample_position;
1733 }
1734