• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2010 Jerome Glisse <glisse@freedesktop.org>
3  * Copyright 2018 Advanced Micro Devices, Inc.
4  *
5  * SPDX-License-Identifier: MIT
6  */
7 
8 #include "drm-uapi/drm_fourcc.h"
9 #include "si_pipe.h"
10 #include "si_query.h"
11 #include "sid.h"
12 #include "frontend/drm_driver.h"
13 #include "util/format/u_format.h"
14 #include "util/os_time.h"
15 #include "util/u_log.h"
16 #include "util/u_memory.h"
17 #include "util/u_pack_color.h"
18 #include "util/u_resource.h"
19 #include "util/u_surface.h"
20 #include "util/u_transfer.h"
21 
22 #include <errno.h>
23 #include <inttypes.h>
24 
25 #include "amd/addrlib/inc/addrinterface.h"
26 
27 static enum radeon_surf_mode si_choose_tiling(struct si_screen *sscreen,
28                                               const struct pipe_resource *templ,
29                                               bool tc_compatible_htile);
30 
31 static bool si_texture_is_aux_plane(const struct pipe_resource *resource);
32 
33 /* Same as resource_copy_region, except that both upsampling and downsampling are allowed. */
si_copy_region_with_blit(struct pipe_context * pipe,struct pipe_resource * dst,unsigned dst_level,unsigned dst_sample,unsigned dstx,unsigned dsty,unsigned dstz,struct pipe_resource * src,unsigned src_level,const struct pipe_box * src_box)34 static void si_copy_region_with_blit(struct pipe_context *pipe, struct pipe_resource *dst,
35                                      unsigned dst_level, unsigned dst_sample, unsigned dstx, unsigned dsty,
36                                      unsigned dstz, struct pipe_resource *src, unsigned src_level,
37                                      const struct pipe_box *src_box)
38 {
39    struct pipe_blit_info blit;
40 
41    memset(&blit, 0, sizeof(blit));
42    blit.src.resource = src;
43    blit.src.format = src->format;
44    blit.src.level = src_level;
45    blit.src.box = *src_box;
46    blit.dst.resource = dst;
47    blit.dst.format = dst->format;
48    blit.dst.level = dst_level;
49    blit.dst.box.x = dstx;
50    blit.dst.box.y = dsty;
51    blit.dst.box.z = dstz;
52    blit.dst.box.width = src_box->width;
53    blit.dst.box.height = src_box->height;
54    blit.dst.box.depth = src_box->depth;
55    blit.mask = util_format_get_mask(dst->format);
56    blit.filter = PIPE_TEX_FILTER_NEAREST;
57    blit.dst_sample = dst_sample;
58 
59    if (blit.mask) {
60       /* Only the gfx blit handles dst_sample. */
61       if (dst_sample)
62          si_gfx_blit(pipe, &blit);
63       else
64          pipe->blit(pipe, &blit);
65    }
66 }
67 
68 /* Copy all planes of multi-plane texture */
si_copy_multi_plane_texture(struct pipe_context * ctx,struct pipe_resource * dst,unsigned dst_level,unsigned dstx,unsigned dsty,unsigned dstz,struct pipe_resource * src,unsigned src_level,const struct pipe_box * src_box)69 static bool si_copy_multi_plane_texture(struct pipe_context *ctx, struct pipe_resource *dst,
70                                         unsigned dst_level, unsigned dstx, unsigned dsty, unsigned dstz,
71                                         struct pipe_resource *src, unsigned src_level,
72                                         const struct pipe_box *src_box)
73 {
74    unsigned i, dx, dy;
75    struct si_texture *src_tex = (struct si_texture *)src;
76    struct si_texture *dst_tex = (struct si_texture *)dst;
77    struct pipe_box sbox;
78 
79    if (src_tex->multi_plane_format == PIPE_FORMAT_NONE || src_tex->plane_index != 0)
80       return false;
81 
82    assert(src_tex->multi_plane_format == dst_tex->multi_plane_format);
83    assert(dst_tex->plane_index == 0 && src_tex->num_planes == dst_tex->num_planes);
84 
85    sbox = *src_box;
86 
87    for (i = 0; i < src_tex->num_planes && src && dst; ++i) {
88       dx = util_format_get_plane_width(src_tex->multi_plane_format, i, dstx);
89       dy = util_format_get_plane_height(src_tex->multi_plane_format, i, dsty);
90       sbox.x = util_format_get_plane_width(src_tex->multi_plane_format, i, src_box->x);
91       sbox.y = util_format_get_plane_height(src_tex->multi_plane_format, i, src_box->y);
92       sbox.width = util_format_get_plane_width(src_tex->multi_plane_format, i, src_box->width);
93       sbox.height = util_format_get_plane_height(src_tex->multi_plane_format, i, src_box->height);
94 
95       si_resource_copy_region(ctx, dst, dst_level, dx, dy, dstz, src, src_level, &sbox);
96 
97       src = src->next;
98       dst = dst->next;
99    }
100 
101    return true;
102 }
103 
104 /* Copy from a full GPU texture to a transfer's staging one. */
si_copy_to_staging_texture(struct pipe_context * ctx,struct si_transfer * stransfer)105 static void si_copy_to_staging_texture(struct pipe_context *ctx, struct si_transfer *stransfer)
106 {
107    struct pipe_transfer *transfer = (struct pipe_transfer *)stransfer;
108    struct pipe_resource *dst = &stransfer->staging->b.b;
109    struct pipe_resource *src = transfer->resource;
110    /* level means sample_index - 1 with MSAA. Used by texture uploads. */
111    unsigned src_level = src->nr_samples > 1 ? 0 : transfer->level;
112 
113    if (src->nr_samples > 1 || ((struct si_texture *)src)->is_depth) {
114       si_copy_region_with_blit(ctx, dst, 0, 0, 0, 0, 0, src, src_level, &transfer->box);
115       return;
116    }
117 
118    if (si_copy_multi_plane_texture(ctx, dst, 0, 0, 0, 0, src, src_level, &transfer->box))
119       return;
120 
121    si_resource_copy_region(ctx, dst, 0, 0, 0, 0, src, src_level, &transfer->box);
122 }
123 
124 /* Copy from a transfer's staging texture to a full GPU one. */
si_copy_from_staging_texture(struct pipe_context * ctx,struct si_transfer * stransfer)125 static void si_copy_from_staging_texture(struct pipe_context *ctx, struct si_transfer *stransfer)
126 {
127    struct pipe_transfer *transfer = (struct pipe_transfer *)stransfer;
128    struct pipe_resource *dst = transfer->resource;
129    struct pipe_resource *src = &stransfer->staging->b.b;
130    struct pipe_box sbox;
131 
132    u_box_3d(0, 0, 0, transfer->box.width, transfer->box.height, transfer->box.depth, &sbox);
133 
134    if (dst->nr_samples > 1 || ((struct si_texture *)dst)->is_depth) {
135       unsigned dst_level = dst->nr_samples > 1 ? 0 : transfer->level;
136       unsigned dst_sample = dst->nr_samples > 1 ? transfer->level : 0;
137 
138       si_copy_region_with_blit(ctx, dst, dst_level, dst_sample, transfer->box.x, transfer->box.y,
139                                transfer->box.z, src, 0, &sbox);
140       return;
141    }
142 
143    if (si_copy_multi_plane_texture(ctx, dst, transfer->level, transfer->box.x, transfer->box.y,
144                                    transfer->box.z, src, 0, &sbox))
145       return;
146 
147    if (util_format_is_compressed(dst->format)) {
148       sbox.width = util_format_get_nblocksx(dst->format, sbox.width);
149       sbox.height = util_format_get_nblocksx(dst->format, sbox.height);
150    }
151 
152    si_resource_copy_region(ctx, dst, transfer->level, transfer->box.x, transfer->box.y,
153                            transfer->box.z, src, 0, &sbox);
154 }
155 
si_texture_get_offset(struct si_screen * sscreen,struct si_texture * tex,unsigned level,const struct pipe_box * box,unsigned * stride,uintptr_t * layer_stride)156 static uint64_t si_texture_get_offset(struct si_screen *sscreen, struct si_texture *tex,
157                                       unsigned level, const struct pipe_box *box, unsigned *stride,
158                                       uintptr_t *layer_stride)
159 {
160    if (sscreen->info.gfx_level >= GFX9) {
161       unsigned pitch;
162       if (tex->surface.is_linear) {
163          pitch = tex->surface.u.gfx9.pitch[level];
164       } else {
165          pitch = tex->surface.u.gfx9.surf_pitch;
166       }
167 
168       *stride = pitch * tex->surface.bpe;
169       *layer_stride = tex->surface.u.gfx9.surf_slice_size;
170 
171       if (!box)
172          return 0;
173 
174       /* Each texture is an array of slices. Each slice is an array
175        * of mipmap levels. */
176       return tex->surface.u.gfx9.surf_offset + box->z * tex->surface.u.gfx9.surf_slice_size +
177              tex->surface.u.gfx9.offset[level] +
178              (box->y / tex->surface.blk_h * (uint64_t)pitch + box->x / tex->surface.blk_w) *
179              tex->surface.bpe;
180    } else {
181       *stride = tex->surface.u.legacy.level[level].nblk_x * tex->surface.bpe;
182       assert((uint64_t)tex->surface.u.legacy.level[level].slice_size_dw * 4 <= UINT_MAX);
183       *layer_stride = (uint64_t)tex->surface.u.legacy.level[level].slice_size_dw * 4;
184 
185       if (!box)
186          return (uint64_t)tex->surface.u.legacy.level[level].offset_256B * 256;
187 
188       /* Each texture is an array of mipmap levels. Each level is
189        * an array of slices. */
190       return (uint64_t)tex->surface.u.legacy.level[level].offset_256B * 256 +
191              box->z * (uint64_t)tex->surface.u.legacy.level[level].slice_size_dw * 4 +
192              (box->y / tex->surface.blk_h * tex->surface.u.legacy.level[level].nblk_x +
193               box->x / tex->surface.blk_w) *
194                 tex->surface.bpe;
195    }
196 }
197 
si_init_surface(struct si_screen * sscreen,struct radeon_surf * surface,const struct pipe_resource * ptex,enum radeon_surf_mode array_mode,uint64_t modifier,bool is_imported,bool is_scanout,bool is_flushed_depth,bool tc_compatible_htile)198 static int si_init_surface(struct si_screen *sscreen, struct radeon_surf *surface,
199                            const struct pipe_resource *ptex, enum radeon_surf_mode array_mode,
200                            uint64_t modifier, bool is_imported, bool is_scanout,
201                            bool is_flushed_depth, bool tc_compatible_htile)
202 {
203    const struct util_format_description *desc = util_format_description(ptex->format);
204    bool is_depth = util_format_has_depth(desc);
205    bool is_stencil = util_format_has_stencil(desc);
206    int r;
207    unsigned bpe;
208    uint64_t flags = 0;
209 
210    if (!is_flushed_depth && ptex->format == PIPE_FORMAT_Z32_FLOAT_S8X24_UINT) {
211       bpe = 4; /* stencil is allocated separately */
212    } else {
213       bpe = util_format_get_blocksize(ptex->format);
214       assert(util_is_power_of_two_or_zero(bpe));
215    }
216 
217    if (!is_flushed_depth && is_depth) {
218       flags |= RADEON_SURF_ZBUFFER;
219 
220       if ((sscreen->debug_flags & DBG(NO_HYPERZ)) ||
221           (ptex->bind & PIPE_BIND_SHARED) || is_imported) {
222          flags |= RADEON_SURF_NO_HTILE;
223       } else if (tc_compatible_htile &&
224                  (sscreen->info.gfx_level >= GFX9 || array_mode == RADEON_SURF_MODE_2D)) {
225          /* TC-compatible HTILE only supports Z32_FLOAT.
226           * GFX9 also supports Z16_UNORM.
227           * On GFX8, promote Z16 to Z32. DB->CB copies will convert
228           * the format for transfers.
229           */
230          if (sscreen->info.gfx_level == GFX8)
231             bpe = 4;
232 
233          flags |= RADEON_SURF_TC_COMPATIBLE_HTILE;
234       }
235 
236       if (is_stencil)
237          flags |= RADEON_SURF_SBUFFER;
238    }
239 
240    /* Disable DCC? (it can't be disabled if modifiers are used) */
241    if (sscreen->info.gfx_level >= GFX8 && modifier == DRM_FORMAT_MOD_INVALID && !is_imported) {
242       /* Global options that disable DCC. */
243       if (ptex->flags & SI_RESOURCE_FLAG_DISABLE_DCC)
244          flags |= RADEON_SURF_DISABLE_DCC;
245 
246       if (ptex->nr_samples >= 2 && sscreen->debug_flags & DBG(NO_DCC_MSAA))
247          flags |= RADEON_SURF_DISABLE_DCC;
248 
249       /* Shared textures must always set up DCC. If it's not present, it will be disabled by
250        * si_get_opaque_metadata later.
251        */
252       if (!is_imported && sscreen->debug_flags & DBG(NO_DCC))
253          flags |= RADEON_SURF_DISABLE_DCC;
254 
255       /* R9G9B9E5 isn't supported for rendering by older generations. */
256       if (sscreen->info.gfx_level < GFX10_3 &&
257           ptex->format == PIPE_FORMAT_R9G9B9E5_FLOAT)
258          flags |= RADEON_SURF_DISABLE_DCC;
259 
260       /* If constant (non-data-dependent) format is requested, disable DCC: */
261       if (ptex->bind & PIPE_BIND_CONST_BW)
262          flags |= RADEON_SURF_DISABLE_DCC;
263 
264       switch (sscreen->info.gfx_level) {
265       case GFX8:
266          /* Stoney: 128bpp MSAA textures randomly fail piglit tests with DCC. */
267          if (sscreen->info.family == CHIP_STONEY && bpe == 16 && ptex->nr_samples >= 2)
268             flags |= RADEON_SURF_DISABLE_DCC;
269 
270          /* DCC clear for 4x and 8x MSAA array textures unimplemented. */
271          if (ptex->nr_storage_samples >= 4 && ptex->array_size > 1)
272             flags |= RADEON_SURF_DISABLE_DCC;
273          break;
274 
275       case GFX9:
276          /* DCC MSAA fails this on Raven:
277           *    https://www.khronos.org/registry/webgl/sdk/tests/deqp/functional/gles3/fbomultisample.2_samples.html
278           * and this on Picasso:
279           *    https://www.khronos.org/registry/webgl/sdk/tests/deqp/functional/gles3/fbomultisample.4_samples.html
280           */
281          if (sscreen->info.family == CHIP_RAVEN && ptex->nr_storage_samples >= 2 && bpe < 4)
282             flags |= RADEON_SURF_DISABLE_DCC;
283          break;
284 
285       case GFX10:
286       case GFX10_3:
287          if (ptex->nr_storage_samples >= 2 && !sscreen->options.dcc_msaa)
288             flags |= RADEON_SURF_DISABLE_DCC;
289          break;
290 
291       case GFX11:
292       case GFX11_5:
293          break;
294 
295       default:
296          assert(0);
297       }
298    }
299 
300    if (is_scanout) {
301       /* This should catch bugs in gallium users setting incorrect flags. */
302       assert(ptex->nr_samples <= 1 && ptex->depth0 == 1 &&
303              ptex->last_level == 0 && !(flags & RADEON_SURF_Z_OR_SBUFFER));
304 
305       flags |= RADEON_SURF_SCANOUT;
306    }
307 
308    if (ptex->bind & PIPE_BIND_SHARED)
309       flags |= RADEON_SURF_SHAREABLE;
310    if (is_imported)
311       flags |= RADEON_SURF_IMPORTED | RADEON_SURF_SHAREABLE;
312    if (sscreen->debug_flags & DBG(NO_FMASK))
313       flags |= RADEON_SURF_NO_FMASK;
314 
315    if (sscreen->info.gfx_level == GFX9 && (ptex->flags & SI_RESOURCE_FLAG_FORCE_MICRO_TILE_MODE)) {
316       flags |= RADEON_SURF_FORCE_MICRO_TILE_MODE;
317       surface->micro_tile_mode = SI_RESOURCE_FLAG_MICRO_TILE_MODE_GET(ptex->flags);
318    }
319 
320    if (ptex->flags & SI_RESOURCE_FLAG_FORCE_MSAA_TILING) {
321       /* GFX11 shouldn't get here because the flag is only used by the CB MSAA resolving
322        * that GFX11 doesn't have.
323        */
324       assert(sscreen->info.gfx_level <= GFX10_3);
325 
326       flags |= RADEON_SURF_FORCE_SWIZZLE_MODE;
327 
328       if (sscreen->info.gfx_level >= GFX10)
329          surface->u.gfx9.swizzle_mode = ADDR_SW_64KB_R_X;
330    }
331 
332    if (ptex->flags & PIPE_RESOURCE_FLAG_SPARSE) {
333       flags |=
334          RADEON_SURF_PRT |
335          RADEON_SURF_NO_FMASK |
336          RADEON_SURF_NO_HTILE |
337          RADEON_SURF_DISABLE_DCC;
338    }
339 
340    surface->modifier = modifier;
341 
342    r = sscreen->ws->surface_init(sscreen->ws, &sscreen->info, ptex, flags, bpe, array_mode,
343                                  surface);
344    if (r) {
345       return r;
346    }
347 
348    return 0;
349 }
350 
si_eliminate_fast_color_clear(struct si_context * sctx,struct si_texture * tex,bool * ctx_flushed)351 void si_eliminate_fast_color_clear(struct si_context *sctx, struct si_texture *tex,
352                                    bool *ctx_flushed)
353 {
354    struct pipe_context *ctx = &sctx->b;
355 
356    unsigned n = sctx->num_decompress_calls;
357    ctx->flush_resource(ctx, &tex->buffer.b.b);
358 
359    /* Flush only if any fast clear elimination took place. */
360    bool flushed = false;
361    if (n != sctx->num_decompress_calls)
362    {
363       ctx->flush(ctx, NULL, 0);
364       flushed = true;
365    }
366    if (ctx_flushed)
367       *ctx_flushed = flushed;
368 }
369 
si_texture_discard_cmask(struct si_screen * sscreen,struct si_texture * tex)370 void si_texture_discard_cmask(struct si_screen *sscreen, struct si_texture *tex)
371 {
372    if (!tex->cmask_buffer)
373       return;
374 
375    assert(tex->buffer.b.b.nr_samples <= 1);
376 
377    /* Disable CMASK. */
378    tex->cmask_base_address_reg = tex->buffer.gpu_address >> 8;
379    tex->dirty_level_mask = 0;
380 
381    tex->cb_color_info &= ~S_028C70_FAST_CLEAR(1);
382 
383    if (tex->cmask_buffer != &tex->buffer)
384       si_resource_reference(&tex->cmask_buffer, NULL);
385 
386    tex->cmask_buffer = NULL;
387 
388    /* Notify all contexts about the change. */
389    p_atomic_inc(&sscreen->dirty_tex_counter);
390    p_atomic_inc(&sscreen->compressed_colortex_counter);
391 }
392 
si_can_disable_dcc(struct si_texture * tex)393 static bool si_can_disable_dcc(struct si_texture *tex)
394 {
395    /* We can't disable DCC if it can be written by another process. */
396    return !tex->is_depth &&
397           tex->surface.meta_offset &&
398           (!tex->buffer.b.is_shared ||
399            !(tex->buffer.external_usage & PIPE_HANDLE_USAGE_FRAMEBUFFER_WRITE)) &&
400           !ac_modifier_has_dcc(tex->surface.modifier);
401 }
402 
si_texture_discard_dcc(struct si_screen * sscreen,struct si_texture * tex)403 static bool si_texture_discard_dcc(struct si_screen *sscreen, struct si_texture *tex)
404 {
405    if (!si_can_disable_dcc(tex))
406       return false;
407 
408    /* Disable DCC. */
409    ac_surface_zero_dcc_fields(&tex->surface);
410 
411    /* Notify all contexts about the change. */
412    p_atomic_inc(&sscreen->dirty_tex_counter);
413    return true;
414 }
415 
416 /**
417  * Disable DCC for the texture. (first decompress, then discard metadata).
418  *
419  * There is unresolved multi-context synchronization issue between
420  * screen::aux_context and the current context. If applications do this with
421  * multiple contexts, it's already undefined behavior for them and we don't
422  * have to worry about that. The scenario is:
423  *
424  * If context 1 disables DCC and context 2 has queued commands that write
425  * to the texture via CB with DCC enabled, and the order of operations is
426  * as follows:
427  *   context 2 queues draw calls rendering to the texture, but doesn't flush
428  *   context 1 disables DCC and flushes
429  *   context 1 & 2 reset descriptors and FB state
430  *   context 2 flushes (new compressed tiles written by the draw calls)
431  *   context 1 & 2 read garbage, because DCC is disabled, yet there are
432  *   compressed tiled
433  *
434  * \param sctx  the current context if you have one, or sscreen->aux_context
435  *              if you don't.
436  */
si_texture_disable_dcc(struct si_context * sctx,struct si_texture * tex)437 bool si_texture_disable_dcc(struct si_context *sctx, struct si_texture *tex)
438 {
439    struct si_screen *sscreen = sctx->screen;
440 
441    if (!sctx->has_graphics)
442       return si_texture_discard_dcc(sscreen, tex);
443 
444    if (!si_can_disable_dcc(tex))
445       return false;
446 
447    /* Decompress DCC. */
448    si_decompress_dcc(sctx, tex);
449    sctx->b.flush(&sctx->b, NULL, 0);
450 
451    return si_texture_discard_dcc(sscreen, tex);
452 }
453 
si_reallocate_texture_inplace(struct si_context * sctx,struct si_texture * tex,unsigned new_bind_flag,bool invalidate_storage)454 static void si_reallocate_texture_inplace(struct si_context *sctx, struct si_texture *tex,
455                                           unsigned new_bind_flag, bool invalidate_storage)
456 {
457    struct pipe_screen *screen = sctx->b.screen;
458    struct si_texture *new_tex;
459    struct pipe_resource templ = tex->buffer.b.b;
460    unsigned i;
461 
462    templ.bind |= new_bind_flag;
463 
464    if (tex->buffer.b.is_shared || tex->num_planes > 1)
465       return;
466 
467    if (new_bind_flag == PIPE_BIND_LINEAR) {
468       if (tex->surface.is_linear)
469          return;
470 
471       /* This fails with MSAA, depth, and compressed textures. */
472       if (si_choose_tiling(sctx->screen, &templ, false) != RADEON_SURF_MODE_LINEAR_ALIGNED)
473          return;
474    }
475 
476    /* Inherit the modifier from the old texture. */
477    if (tex->surface.modifier != DRM_FORMAT_MOD_INVALID && screen->resource_create_with_modifiers)
478       new_tex = (struct si_texture *)screen->resource_create_with_modifiers(screen, &templ,
479                                                                             &tex->surface.modifier, 1);
480    else
481       new_tex = (struct si_texture *)screen->resource_create(screen, &templ);
482 
483    if (!new_tex)
484       return;
485 
486    /* Copy the pixels to the new texture. */
487    if (!invalidate_storage) {
488       for (i = 0; i <= templ.last_level; i++) {
489          struct pipe_box box;
490 
491          u_box_3d(0, 0, 0, u_minify(templ.width0, i), u_minify(templ.height0, i),
492                   util_num_layers(&templ, i), &box);
493 
494          si_resource_copy_region(&sctx->b, &new_tex->buffer.b.b,
495                                  i, 0, 0, 0, &tex->buffer.b.b, i, &box);
496       }
497    }
498 
499    if (new_bind_flag == PIPE_BIND_LINEAR) {
500       si_texture_discard_cmask(sctx->screen, tex);
501       si_texture_discard_dcc(sctx->screen, tex);
502    }
503 
504    /* Replace the structure fields of tex. */
505    tex->buffer.b.b.bind = templ.bind;
506    radeon_bo_reference(sctx->screen->ws, &tex->buffer.buf, new_tex->buffer.buf);
507    tex->buffer.gpu_address = new_tex->buffer.gpu_address;
508    tex->buffer.bo_size = new_tex->buffer.bo_size;
509    tex->buffer.bo_alignment_log2 = new_tex->buffer.bo_alignment_log2;
510    tex->buffer.domains = new_tex->buffer.domains;
511    tex->buffer.flags = new_tex->buffer.flags;
512 
513    tex->surface = new_tex->surface;
514    si_texture_reference(&tex->flushed_depth_texture, new_tex->flushed_depth_texture);
515 
516    tex->surface.fmask_offset = new_tex->surface.fmask_offset;
517    tex->surface.cmask_offset = new_tex->surface.cmask_offset;
518    tex->cmask_base_address_reg = new_tex->cmask_base_address_reg;
519 
520    if (tex->cmask_buffer == &tex->buffer)
521       tex->cmask_buffer = NULL;
522    else
523       si_resource_reference(&tex->cmask_buffer, NULL);
524 
525    if (new_tex->cmask_buffer == &new_tex->buffer)
526       tex->cmask_buffer = &tex->buffer;
527    else
528       si_resource_reference(&tex->cmask_buffer, new_tex->cmask_buffer);
529 
530    tex->surface.meta_offset = new_tex->surface.meta_offset;
531    tex->cb_color_info = new_tex->cb_color_info;
532    memcpy(tex->color_clear_value, new_tex->color_clear_value, sizeof(tex->color_clear_value));
533    tex->last_msaa_resolve_target_micro_mode = new_tex->last_msaa_resolve_target_micro_mode;
534 
535    memcpy(tex->depth_clear_value, new_tex->depth_clear_value, sizeof(tex->depth_clear_value));
536    tex->dirty_level_mask = new_tex->dirty_level_mask;
537    tex->stencil_dirty_level_mask = new_tex->stencil_dirty_level_mask;
538    tex->db_render_format = new_tex->db_render_format;
539    memcpy(tex->stencil_clear_value, new_tex->stencil_clear_value, sizeof(tex->stencil_clear_value));
540    tex->tc_compatible_htile = new_tex->tc_compatible_htile;
541    tex->depth_cleared_level_mask_once = new_tex->depth_cleared_level_mask_once;
542    tex->stencil_cleared_level_mask_once = new_tex->stencil_cleared_level_mask_once;
543    tex->upgraded_depth = new_tex->upgraded_depth;
544    tex->db_compatible = new_tex->db_compatible;
545    tex->can_sample_z = new_tex->can_sample_z;
546    tex->can_sample_s = new_tex->can_sample_s;
547 
548    tex->displayable_dcc_dirty = new_tex->displayable_dcc_dirty;
549 
550    if (new_bind_flag == PIPE_BIND_LINEAR) {
551       assert(!tex->surface.meta_offset);
552       assert(!tex->cmask_buffer);
553       assert(!tex->surface.fmask_size);
554       assert(!tex->is_depth);
555    }
556 
557    si_texture_reference(&new_tex, NULL);
558 
559    p_atomic_inc(&sctx->screen->dirty_tex_counter);
560 }
561 
si_set_tex_bo_metadata(struct si_screen * sscreen,struct si_texture * tex)562 static void si_set_tex_bo_metadata(struct si_screen *sscreen, struct si_texture *tex)
563 {
564    struct pipe_resource *res = &tex->buffer.b.b;
565    struct radeon_bo_metadata md;
566 
567    memset(&md, 0, sizeof(md));
568 
569    assert(tex->surface.fmask_size == 0);
570 
571    static const unsigned char swizzle[] = {PIPE_SWIZZLE_X, PIPE_SWIZZLE_Y, PIPE_SWIZZLE_Z,
572                                            PIPE_SWIZZLE_W};
573    bool is_array = util_texture_is_array(res->target);
574    uint32_t desc[8];
575 
576    sscreen->make_texture_descriptor(sscreen, tex, true, res->target, res->format, swizzle, 0,
577                                     res->last_level, 0, is_array ? res->array_size - 1 : 0,
578                                     res->width0, res->height0, res->depth0, true, desc, NULL);
579    si_set_mutable_tex_desc_fields(sscreen, tex, &tex->surface.u.legacy.level[0], 0, 0,
580                                   tex->surface.blk_w, false, 0, desc);
581 
582    ac_surface_compute_umd_metadata(&sscreen->info, &tex->surface,
583                                    tex->buffer.b.b.last_level + 1,
584                                    desc, &md.size_metadata, md.metadata,
585                                    sscreen->debug_flags & DBG(EXTRA_METADATA));
586    sscreen->ws->buffer_set_metadata(sscreen->ws, tex->buffer.buf, &md, &tex->surface);
587 }
588 
si_displayable_dcc_needs_explicit_flush(struct si_texture * tex)589 static bool si_displayable_dcc_needs_explicit_flush(struct si_texture *tex)
590 {
591    struct si_screen *sscreen = (struct si_screen *)tex->buffer.b.b.screen;
592 
593    if (sscreen->info.gfx_level <= GFX8)
594       return false;
595 
596    /* With modifiers and > 1 planes any applications will know that they
597     * cannot do frontbuffer rendering with the texture. */
598    if (ac_surface_get_nplanes(&tex->surface) > 1)
599       return false;
600 
601    return tex->surface.is_displayable && tex->surface.meta_offset;
602 }
603 
si_resource_get_param(struct pipe_screen * screen,struct pipe_context * context,struct pipe_resource * resource,unsigned plane,unsigned layer,unsigned level,enum pipe_resource_param param,unsigned handle_usage,uint64_t * value)604 static bool si_resource_get_param(struct pipe_screen *screen, struct pipe_context *context,
605                                   struct pipe_resource *resource, unsigned plane, unsigned layer,
606                                   unsigned level,
607                                   enum pipe_resource_param param, unsigned handle_usage,
608                                   uint64_t *value)
609 {
610    while (plane && resource->next && !si_texture_is_aux_plane(resource->next)) {
611       --plane;
612       resource = resource->next;
613    }
614 
615    struct si_screen *sscreen = (struct si_screen *)screen;
616    struct si_texture *tex = (struct si_texture *)resource;
617    struct winsys_handle whandle;
618 
619    switch (param) {
620    case PIPE_RESOURCE_PARAM_NPLANES:
621       if (resource->target == PIPE_BUFFER)
622          *value = 1;
623       else if (tex->num_planes > 1)
624          *value = tex->num_planes;
625       else
626          *value = ac_surface_get_nplanes(&tex->surface);
627       return true;
628 
629    case PIPE_RESOURCE_PARAM_STRIDE:
630       if (resource->target == PIPE_BUFFER)
631          *value = 0;
632       else
633          *value = ac_surface_get_plane_stride(sscreen->info.gfx_level,
634                                               &tex->surface, plane, level);
635       return true;
636 
637    case PIPE_RESOURCE_PARAM_OFFSET:
638       if (resource->target == PIPE_BUFFER) {
639          *value = 0;
640       } else {
641          uint64_t level_offset = 0;
642          if (sscreen->info.gfx_level >= GFX9 && tex->surface.is_linear)
643             level_offset = tex->surface.u.gfx9.offset[level];
644          *value = ac_surface_get_plane_offset(sscreen->info.gfx_level,
645                                               &tex->surface, plane, layer)  + level_offset;
646       }
647       return true;
648 
649    case PIPE_RESOURCE_PARAM_MODIFIER:
650       *value = tex->surface.modifier;
651       return true;
652 
653    case PIPE_RESOURCE_PARAM_HANDLE_TYPE_SHARED:
654    case PIPE_RESOURCE_PARAM_HANDLE_TYPE_KMS:
655    case PIPE_RESOURCE_PARAM_HANDLE_TYPE_FD:
656       memset(&whandle, 0, sizeof(whandle));
657 
658       if (param == PIPE_RESOURCE_PARAM_HANDLE_TYPE_SHARED)
659          whandle.type = WINSYS_HANDLE_TYPE_SHARED;
660       else if (param == PIPE_RESOURCE_PARAM_HANDLE_TYPE_KMS)
661          whandle.type = WINSYS_HANDLE_TYPE_KMS;
662       else if (param == PIPE_RESOURCE_PARAM_HANDLE_TYPE_FD)
663          whandle.type = WINSYS_HANDLE_TYPE_FD;
664 
665       if (!screen->resource_get_handle(screen, context, resource, &whandle, handle_usage))
666          return false;
667 
668       *value = whandle.handle;
669       return true;
670    case PIPE_RESOURCE_PARAM_LAYER_STRIDE:
671       break;
672    }
673    return false;
674 }
675 
si_texture_get_info(struct pipe_screen * screen,struct pipe_resource * resource,unsigned * pstride,unsigned * poffset)676 static void si_texture_get_info(struct pipe_screen *screen, struct pipe_resource *resource,
677                                 unsigned *pstride, unsigned *poffset)
678 {
679    uint64_t value;
680 
681    if (pstride) {
682       si_resource_get_param(screen, NULL, resource, 0, 0, 0, PIPE_RESOURCE_PARAM_STRIDE, 0, &value);
683       *pstride = value;
684    }
685 
686    if (poffset) {
687       si_resource_get_param(screen, NULL, resource, 0, 0, 0, PIPE_RESOURCE_PARAM_OFFSET, 0, &value);
688       *poffset = value;
689    }
690 }
691 
si_texture_get_handle(struct pipe_screen * screen,struct pipe_context * ctx,struct pipe_resource * resource,struct winsys_handle * whandle,unsigned usage)692 static bool si_texture_get_handle(struct pipe_screen *screen, struct pipe_context *ctx,
693                                   struct pipe_resource *resource, struct winsys_handle *whandle,
694                                   unsigned usage)
695 {
696    struct si_screen *sscreen = (struct si_screen *)screen;
697    struct si_context *sctx;
698    struct si_resource *res = si_resource(resource);
699    struct si_texture *tex = (struct si_texture *)resource;
700    bool update_metadata = false;
701    unsigned stride, offset, slice_size;
702    uint64_t modifier = DRM_FORMAT_MOD_INVALID;
703    bool flush = false;
704 
705    ctx = threaded_context_unwrap_sync(ctx);
706    sctx = ctx ? (struct si_context *)ctx : si_get_aux_context(&sscreen->aux_context.general);
707 
708    if (resource->target != PIPE_BUFFER) {
709       unsigned plane = whandle->plane;
710 
711       /* Individual planes are chained pipe_resource instances. */
712       while (plane && resource->next && !si_texture_is_aux_plane(resource->next)) {
713          resource = resource->next;
714          --plane;
715       }
716 
717       res = si_resource(resource);
718       tex = (struct si_texture *)resource;
719 
720       /* This is not supported now, but it might be required for OpenCL
721        * interop in the future.
722        */
723       if (resource->nr_samples > 1 || tex->is_depth) {
724          if (!ctx)
725             si_put_aux_context_flush(&sscreen->aux_context.general);
726          return false;
727       }
728 
729       whandle->size = tex->buffer.bo_size;
730 
731       if (plane) {
732          if (!ctx)
733             si_put_aux_context_flush(&sscreen->aux_context.general);
734          whandle->offset = ac_surface_get_plane_offset(sscreen->info.gfx_level,
735                                                        &tex->surface, plane, 0);
736          whandle->stride = ac_surface_get_plane_stride(sscreen->info.gfx_level,
737                                                        &tex->surface, plane, 0);
738          whandle->modifier = tex->surface.modifier;
739          return sscreen->ws->buffer_get_handle(sscreen->ws, res->buf, whandle);
740       }
741 
742       /* Move a suballocated texture into a non-suballocated allocation. */
743       if (sscreen->ws->buffer_is_suballocated(res->buf) || tex->surface.tile_swizzle ||
744           (tex->buffer.flags & RADEON_FLAG_NO_INTERPROCESS_SHARING &&
745            sscreen->info.has_local_buffers)) {
746          assert(!res->b.is_shared);
747          si_reallocate_texture_inplace(sctx, tex, PIPE_BIND_SHARED, false);
748          flush = true;
749          assert(res->b.b.bind & PIPE_BIND_SHARED);
750          assert(res->flags & RADEON_FLAG_NO_SUBALLOC);
751          assert(!(res->flags & RADEON_FLAG_NO_INTERPROCESS_SHARING));
752          assert(tex->surface.tile_swizzle == 0);
753       }
754 
755       /* Since shader image stores don't support DCC on GFX8,
756        * disable it for external clients that want write
757        * access.
758        */
759       if (sscreen->debug_flags & DBG(NO_EXPORTED_DCC) ||
760           (usage & PIPE_HANDLE_USAGE_SHADER_WRITE && !tex->is_depth && tex->surface.meta_offset) ||
761           /* Displayable DCC requires an explicit flush. */
762           (!(usage & PIPE_HANDLE_USAGE_EXPLICIT_FLUSH) &&
763            si_displayable_dcc_needs_explicit_flush(tex))) {
764          if (si_texture_disable_dcc(sctx, tex)) {
765             update_metadata = true;
766             /* si_texture_disable_dcc flushes the context */
767             flush = false;
768          }
769       }
770 
771       if (!(usage & PIPE_HANDLE_USAGE_EXPLICIT_FLUSH) &&
772           (tex->cmask_buffer || (!tex->is_depth && tex->surface.meta_offset))) {
773          /* Eliminate fast clear (both CMASK and DCC) */
774          bool flushed;
775          si_eliminate_fast_color_clear(sctx, tex, &flushed);
776          /* eliminate_fast_color_clear sometimes flushes the context */
777          flush = !flushed;
778 
779          /* Disable CMASK if flush_resource isn't going
780           * to be called.
781           */
782          if (tex->cmask_buffer)
783             si_texture_discard_cmask(sscreen, tex);
784       }
785 
786       /* Set metadata. */
787       if ((!res->b.is_shared || update_metadata) && whandle->offset == 0)
788          si_set_tex_bo_metadata(sscreen, tex);
789 
790       if (sscreen->info.gfx_level >= GFX9) {
791          slice_size = tex->surface.u.gfx9.surf_slice_size;
792       } else {
793          slice_size = (uint64_t)tex->surface.u.legacy.level[0].slice_size_dw * 4;
794       }
795 
796       modifier = tex->surface.modifier;
797    } else {
798       tc_buffer_disable_cpu_storage(&res->b.b);
799 
800       /* Buffer exports are for the OpenCL interop. */
801       /* Move a suballocated buffer into a non-suballocated allocation. */
802       if (sscreen->ws->buffer_is_suballocated(res->buf) ||
803           /* A DMABUF export always fails if the BO is local. */
804           (tex->buffer.flags & RADEON_FLAG_NO_INTERPROCESS_SHARING &&
805            sscreen->info.has_local_buffers)) {
806          assert(!res->b.is_shared);
807 
808          /* Allocate a new buffer with PIPE_BIND_SHARED. */
809          struct pipe_resource templ = res->b.b;
810          templ.bind |= PIPE_BIND_SHARED;
811 
812          struct pipe_resource *newb = screen->resource_create(screen, &templ);
813          if (!newb) {
814             if (!ctx)
815                si_put_aux_context_flush(&sscreen->aux_context.general);
816             return false;
817          }
818 
819          /* Copy the old buffer contents to the new one. */
820          struct pipe_box box;
821          u_box_1d(0, newb->width0, &box);
822          sctx->b.resource_copy_region(&sctx->b, newb, 0, 0, 0, 0, &res->b.b, 0, &box);
823          flush = true;
824          /* Move the new buffer storage to the old pipe_resource. */
825          si_replace_buffer_storage(&sctx->b, &res->b.b, newb, 0, 0, 0);
826          pipe_resource_reference(&newb, NULL);
827 
828          assert(res->b.b.bind & PIPE_BIND_SHARED);
829          assert(res->flags & RADEON_FLAG_NO_SUBALLOC);
830       }
831 
832       /* Buffers */
833       slice_size = 0;
834    }
835 
836    si_texture_get_info(screen, resource, &stride, &offset);
837 
838    if (res->b.is_shared) {
839       /* USAGE_EXPLICIT_FLUSH must be cleared if at least one user
840        * doesn't set it.
841        */
842       res->external_usage |= usage & ~PIPE_HANDLE_USAGE_EXPLICIT_FLUSH;
843       if (!(usage & PIPE_HANDLE_USAGE_EXPLICIT_FLUSH))
844          res->external_usage &= ~PIPE_HANDLE_USAGE_EXPLICIT_FLUSH;
845    } else {
846       res->b.is_shared = true;
847       res->external_usage = usage;
848    }
849 
850    if (flush && ctx)
851       sctx->b.flush(&sctx->b, NULL, 0);
852    if (!ctx)
853       si_put_aux_context_flush(&sscreen->aux_context.general);
854 
855    whandle->stride = stride;
856    whandle->offset = offset + slice_size * whandle->layer;
857    whandle->modifier = modifier;
858 
859    return sscreen->ws->buffer_get_handle(sscreen->ws, res->buf, whandle);
860 }
861 
si_print_texture_info(struct si_screen * sscreen,struct si_texture * tex,struct u_log_context * log)862 void si_print_texture_info(struct si_screen *sscreen, struct si_texture *tex,
863                            struct u_log_context *log)
864 {
865    int i;
866    FILE *f;
867    char *surf_info = NULL;
868    size_t surf_info_size;
869 
870    /* Common parameters. */
871    u_log_printf(log,
872                 "  Info: npix_x=%u, npix_y=%u, npix_z=%u, "
873                 "array_size=%u, last_level=%u, nsamples=%u",
874                 tex->buffer.b.b.width0, tex->buffer.b.b.height0,
875                 tex->buffer.b.b.depth0, tex->buffer.b.b.array_size,
876                 tex->buffer.b.b.last_level, tex->buffer.b.b.nr_samples);
877 
878    if (tex->is_depth && tex->surface.meta_offset)
879       u_log_printf(log, ", tc_compatible_htile=%u", tex->tc_compatible_htile);
880 
881    u_log_printf(log, ", %s\n",
882                 util_format_short_name(tex->buffer.b.b.format));
883 
884    f = open_memstream(&surf_info, &surf_info_size);
885    if (!f)
886       return;
887    ac_surface_print_info(f, &sscreen->info, &tex->surface);
888    fclose(f);
889    u_log_printf(log, "%s", surf_info);
890    free(surf_info);
891 
892    if (sscreen->info.gfx_level >= GFX9) {
893       return;
894    }
895 
896    if (!tex->is_depth && tex->surface.meta_offset) {
897       for (i = 0; i <= tex->buffer.b.b.last_level; i++)
898          u_log_printf(log,
899                       "    DCCLevel[%i]: enabled=%u, offset=%u, "
900                       "fast_clear_size=%u\n",
901                       i, i < tex->surface.num_meta_levels, tex->surface.u.legacy.color.dcc_level[i].dcc_offset,
902                       tex->surface.u.legacy.color.dcc_level[i].dcc_fast_clear_size);
903    }
904 
905    for (i = 0; i <= tex->buffer.b.b.last_level; i++)
906       u_log_printf(log,
907                    "    Level[%i]: offset=%" PRIu64 ", slice_size=%" PRIu64 ", "
908                    "npix_x=%u, npix_y=%u, npix_z=%u, nblk_x=%u, nblk_y=%u, "
909                    "mode=%u, tiling_index = %u\n",
910                    i, (uint64_t)tex->surface.u.legacy.level[i].offset_256B * 256,
911                    (uint64_t)tex->surface.u.legacy.level[i].slice_size_dw * 4,
912                    u_minify(tex->buffer.b.b.width0, i), u_minify(tex->buffer.b.b.height0, i),
913                    u_minify(tex->buffer.b.b.depth0, i), tex->surface.u.legacy.level[i].nblk_x,
914                    tex->surface.u.legacy.level[i].nblk_y, tex->surface.u.legacy.level[i].mode,
915                    tex->surface.u.legacy.tiling_index[i]);
916 
917    if (tex->surface.has_stencil) {
918       for (i = 0; i <= tex->buffer.b.b.last_level; i++) {
919          u_log_printf(log,
920                       "    StencilLevel[%i]: offset=%" PRIu64 ", "
921                       "slice_size=%" PRIu64 ", npix_x=%u, "
922                       "npix_y=%u, npix_z=%u, nblk_x=%u, nblk_y=%u, "
923                       "mode=%u, tiling_index = %u\n",
924                       i, (uint64_t)tex->surface.u.legacy.zs.stencil_level[i].offset_256B * 256,
925                       (uint64_t)tex->surface.u.legacy.zs.stencil_level[i].slice_size_dw * 4,
926                       u_minify(tex->buffer.b.b.width0, i), u_minify(tex->buffer.b.b.height0, i),
927                       u_minify(tex->buffer.b.b.depth0, i),
928                       tex->surface.u.legacy.zs.stencil_level[i].nblk_x,
929                       tex->surface.u.legacy.zs.stencil_level[i].nblk_y,
930                       tex->surface.u.legacy.zs.stencil_level[i].mode,
931                       tex->surface.u.legacy.zs.stencil_tiling_index[i]);
932       }
933    }
934 }
935 
936 /**
937  * Common function for si_texture_create and si_texture_from_handle.
938  *
939  * \param screen       screen
940  * \param base         resource template
941  * \param surface      radeon_surf
942  * \param plane0       if a non-zero plane is being created, this is the first plane
943  * \param imported_buf from si_texture_from_handle
944  * \param offset       offset for non-zero planes or imported buffers
945  * \param alloc_size   the size to allocate if plane0 != NULL
946  * \param alignment    alignment for the allocation
947  */
si_texture_create_object(struct pipe_screen * screen,const struct pipe_resource * base,const struct radeon_surf * surface,const struct si_texture * plane0,struct pb_buffer_lean * imported_buf,uint64_t offset,unsigned pitch_in_bytes,uint64_t alloc_size,unsigned alignment)948 static struct si_texture *si_texture_create_object(struct pipe_screen *screen,
949                                                    const struct pipe_resource *base,
950                                                    const struct radeon_surf *surface,
951                                                    const struct si_texture *plane0,
952                                                    struct pb_buffer_lean *imported_buf,
953                                                    uint64_t offset, unsigned pitch_in_bytes,
954                                                    uint64_t alloc_size, unsigned alignment)
955 {
956    struct si_texture *tex;
957    struct si_resource *resource;
958    struct si_screen *sscreen = (struct si_screen *)screen;
959 
960    if (!sscreen->info.has_3d_cube_border_color_mipmap &&
961        (base->last_level > 0 ||
962         base->target == PIPE_TEXTURE_3D ||
963         base->target == PIPE_TEXTURE_CUBE)) {
964       assert(0);
965       return NULL;
966    }
967 
968    tex = CALLOC_STRUCT_CL(si_texture);
969    if (!tex)
970       goto error;
971 
972    resource = &tex->buffer;
973    resource->b.b = *base;
974    pipe_reference_init(&resource->b.b.reference, 1);
975    resource->b.b.screen = screen;
976 
977    /* don't include stencil-only formats which we don't support for rendering */
978    tex->is_depth = util_format_has_depth(util_format_description(tex->buffer.b.b.format));
979    tex->surface = *surface;
980 
981    if (!ac_surface_override_offset_stride(&sscreen->info, &tex->surface,
982                                           tex->buffer.b.b.array_size,
983                                           tex->buffer.b.b.last_level + 1,
984                                           offset, pitch_in_bytes / tex->surface.bpe))
985       goto error;
986 
987    if (plane0) {
988       /* The buffer is shared with the first plane. */
989       resource->bo_size = plane0->buffer.bo_size;
990       resource->bo_alignment_log2 = plane0->buffer.bo_alignment_log2;
991       resource->flags = plane0->buffer.flags;
992       resource->domains = plane0->buffer.domains;
993 
994       radeon_bo_reference(sscreen->ws, &resource->buf, plane0->buffer.buf);
995       resource->gpu_address = plane0->buffer.gpu_address;
996    } else if (!(surface->flags & RADEON_SURF_IMPORTED)) {
997       if (base->flags & PIPE_RESOURCE_FLAG_SPARSE)
998          resource->b.b.flags |= PIPE_RESOURCE_FLAG_UNMAPPABLE;
999       if (base->bind & PIPE_BIND_PRIME_BLIT_DST)
1000          resource->b.b.flags |= SI_RESOURCE_FLAG_GL2_BYPASS;
1001 
1002       /* Create the backing buffer. */
1003       si_init_resource_fields(sscreen, resource, alloc_size, alignment);
1004 
1005       if (!si_alloc_resource(sscreen, resource))
1006          goto error;
1007    } else {
1008       resource->buf = imported_buf;
1009       resource->gpu_address = sscreen->ws->buffer_get_virtual_address(resource->buf);
1010       resource->bo_size = imported_buf->size;
1011       resource->bo_alignment_log2 = imported_buf->alignment_log2;
1012       resource->domains = sscreen->ws->buffer_get_initial_domain(resource->buf);
1013       if (sscreen->ws->buffer_get_flags)
1014          resource->flags = sscreen->ws->buffer_get_flags(resource->buf);
1015    }
1016 
1017    if (sscreen->debug_flags & DBG(VM)) {
1018       fprintf(stderr,
1019               "VM start=0x%" PRIX64 "  end=0x%" PRIX64
1020               " | Texture %ix%ix%i, %i levels, %i samples, %s | Flags: ",
1021               tex->buffer.gpu_address, tex->buffer.gpu_address + tex->buffer.buf->size,
1022               base->width0, base->height0, util_num_layers(base, 0), base->last_level + 1,
1023               base->nr_samples ? base->nr_samples : 1, util_format_short_name(base->format));
1024       si_res_print_flags(tex->buffer.flags);
1025       fprintf(stderr, "\n");
1026    }
1027 
1028    if (sscreen->debug_flags & DBG(TEX)) {
1029       puts("Texture:");
1030       struct u_log_context log;
1031       u_log_context_init(&log);
1032       si_print_texture_info(sscreen, tex, &log);
1033       u_log_new_page_print(&log, stdout);
1034       fflush(stdout);
1035       u_log_context_destroy(&log);
1036    }
1037 
1038    /* Use 1.0 as the default clear value to get optimal ZRANGE_PRECISION if we don't
1039     * get a fast clear.
1040     */
1041    for (unsigned i = 0; i < ARRAY_SIZE(tex->depth_clear_value); i++)
1042       tex->depth_clear_value[i] = 1.0;
1043 
1044    /* On GFX8, HTILE uses different tiling depending on the TC_COMPATIBLE_HTILE
1045     * setting, so we have to enable it if we enabled it at allocation.
1046     *
1047     * GFX9 and later use the same tiling for both, so TC-compatible HTILE can be
1048     * enabled on demand.
1049     */
1050    tex->tc_compatible_htile = (sscreen->info.gfx_level == GFX8 &&
1051                                tex->surface.flags & RADEON_SURF_TC_COMPATIBLE_HTILE) ||
1052                               /* Mipmapping always starts TC-compatible. */
1053                               (sscreen->info.gfx_level >= GFX8 &&
1054                                tex->surface.flags & RADEON_SURF_TC_COMPATIBLE_HTILE &&
1055                                tex->buffer.b.b.last_level > 0);
1056 
1057    /* TC-compatible HTILE:
1058     * - GFX8 only supports Z32_FLOAT.
1059     * - GFX9 only supports Z32_FLOAT and Z16_UNORM. */
1060    if (tex->surface.flags & RADEON_SURF_TC_COMPATIBLE_HTILE) {
1061       if (sscreen->info.gfx_level >= GFX9 && base->format == PIPE_FORMAT_Z16_UNORM)
1062          tex->db_render_format = base->format;
1063       else {
1064          tex->db_render_format = PIPE_FORMAT_Z32_FLOAT;
1065          tex->upgraded_depth = base->format != PIPE_FORMAT_Z32_FLOAT &&
1066                                base->format != PIPE_FORMAT_Z32_FLOAT_S8X24_UINT;
1067       }
1068    } else {
1069       tex->db_render_format = base->format;
1070    }
1071 
1072    /* Applies to GCN. */
1073    tex->last_msaa_resolve_target_micro_mode = tex->surface.micro_tile_mode;
1074 
1075    if (tex->is_depth) {
1076       tex->htile_stencil_disabled = !tex->surface.has_stencil;
1077 
1078       if (sscreen->info.gfx_level >= GFX9) {
1079          tex->can_sample_z = true;
1080          tex->can_sample_s = true;
1081 
1082          /* Stencil texturing with HTILE doesn't work
1083           * with mipmapping on Navi10-14. */
1084          if (sscreen->info.gfx_level == GFX10 && base->last_level > 0)
1085             tex->htile_stencil_disabled = true;
1086       } else {
1087          tex->can_sample_z = !tex->surface.u.legacy.depth_adjusted;
1088          tex->can_sample_s = !tex->surface.u.legacy.stencil_adjusted;
1089 
1090          /* GFX8 must keep stencil enabled because it can't use Z-only TC-compatible
1091           * HTILE because of a hw bug. This has only a small effect on performance
1092           * because we lose a little bit of Z precision in order to make space for
1093           * stencil in HTILE.
1094           */
1095          if (sscreen->info.gfx_level == GFX8 &&
1096              tex->surface.flags & RADEON_SURF_TC_COMPATIBLE_HTILE)
1097             tex->htile_stencil_disabled = false;
1098       }
1099 
1100       tex->db_compatible = surface->flags & RADEON_SURF_ZBUFFER;
1101    } else {
1102       if (tex->surface.cmask_offset) {
1103          assert(sscreen->info.gfx_level < GFX11);
1104          tex->cb_color_info |= S_028C70_FAST_CLEAR(1);
1105          tex->cmask_buffer = &tex->buffer;
1106       }
1107    }
1108 
1109    /* Prepare metadata clears.  */
1110    struct si_clear_info clears[4];
1111    unsigned num_clears = 0;
1112 
1113    if (tex->cmask_buffer) {
1114       /* Initialize the cmask to 0xCC (= compressed state). */
1115       assert(num_clears < ARRAY_SIZE(clears));
1116       si_init_buffer_clear(&clears[num_clears++], &tex->cmask_buffer->b.b,
1117                            tex->surface.cmask_offset, tex->surface.cmask_size,
1118                            0xCCCCCCCC);
1119    }
1120    if (tex->is_depth && tex->surface.meta_offset) {
1121       uint32_t clear_value = 0;
1122 
1123       if (sscreen->info.gfx_level >= GFX9 || tex->tc_compatible_htile)
1124          clear_value = 0x0000030F;
1125 
1126       assert(num_clears < ARRAY_SIZE(clears));
1127       si_init_buffer_clear(&clears[num_clears++], &tex->buffer.b.b, tex->surface.meta_offset,
1128                            tex->surface.meta_size, clear_value);
1129    }
1130 
1131    /* Initialize DCC only if the texture is not being imported. */
1132    if (!(surface->flags & RADEON_SURF_IMPORTED) && !tex->is_depth && tex->surface.meta_offset) {
1133       /* Clear DCC to black for all tiles with DCC enabled.
1134        *
1135        * This fixes corruption in 3DMark Slingshot Extreme, which
1136        * uses uninitialized textures, causing corruption.
1137        */
1138       if (tex->surface.num_meta_levels == tex->buffer.b.b.last_level + 1 &&
1139           tex->buffer.b.b.nr_samples <= 2) {
1140          /* Simple case - all tiles have DCC enabled. */
1141          assert(num_clears < ARRAY_SIZE(clears));
1142          si_init_buffer_clear(&clears[num_clears++], &tex->buffer.b.b, tex->surface.meta_offset,
1143                               tex->surface.meta_size, DCC_CLEAR_0000);
1144       } else if (sscreen->info.gfx_level >= GFX9) {
1145          /* Clear to uncompressed. Clearing this to black is complicated. */
1146          assert(num_clears < ARRAY_SIZE(clears));
1147          si_init_buffer_clear(&clears[num_clears++], &tex->buffer.b.b, tex->surface.meta_offset,
1148                               tex->surface.meta_size, DCC_UNCOMPRESSED);
1149       } else {
1150          /* GFX8: Initialize mipmap levels and multisamples separately. */
1151          if (tex->buffer.b.b.nr_samples >= 2) {
1152             /* Clearing this to black is complicated. */
1153             assert(num_clears < ARRAY_SIZE(clears));
1154             si_init_buffer_clear(&clears[num_clears++], &tex->buffer.b.b, tex->surface.meta_offset,
1155                                  tex->surface.meta_size, DCC_UNCOMPRESSED);
1156          } else {
1157             /* Clear the enabled mipmap levels to black. */
1158             unsigned size = 0;
1159 
1160             for (unsigned i = 0; i < tex->surface.num_meta_levels; i++) {
1161                if (!tex->surface.u.legacy.color.dcc_level[i].dcc_fast_clear_size)
1162                   break;
1163 
1164                size = tex->surface.u.legacy.color.dcc_level[i].dcc_offset +
1165                       tex->surface.u.legacy.color.dcc_level[i].dcc_fast_clear_size;
1166             }
1167 
1168             /* Mipmap levels with DCC. */
1169             if (size) {
1170                assert(num_clears < ARRAY_SIZE(clears));
1171                si_init_buffer_clear(&clears[num_clears++], &tex->buffer.b.b, tex->surface.meta_offset, size,
1172                                     DCC_CLEAR_0000);
1173             }
1174             /* Mipmap levels without DCC. */
1175             if (size != tex->surface.meta_size) {
1176                assert(num_clears < ARRAY_SIZE(clears));
1177                si_init_buffer_clear(&clears[num_clears++], &tex->buffer.b.b, tex->surface.meta_offset + size,
1178                                     tex->surface.meta_size - size, DCC_UNCOMPRESSED);
1179             }
1180          }
1181       }
1182    }
1183 
1184    /* Initialize displayable DCC that requires the retile blit. */
1185    if (tex->surface.display_dcc_offset && !(surface->flags & RADEON_SURF_IMPORTED)) {
1186       /* Uninitialized DCC can hang the display hw.
1187        * Clear to white to indicate that. */
1188       assert(num_clears < ARRAY_SIZE(clears));
1189       si_init_buffer_clear(&clears[num_clears++], &tex->buffer.b.b, tex->surface.display_dcc_offset,
1190                            tex->surface.u.gfx9.color.display_dcc_size,
1191                            sscreen->info.gfx_level >= GFX11 ? GFX11_DCC_CLEAR_1111_UNORM
1192                                                              : GFX8_DCC_CLEAR_1111);
1193    }
1194 
1195    /* Execute the clears. */
1196    if (num_clears) {
1197       si_execute_clears(si_get_aux_context(&sscreen->aux_context.general), clears, num_clears, 0);
1198       si_put_aux_context_flush(&sscreen->aux_context.general);
1199    }
1200 
1201    /* Initialize the CMASK base register value. */
1202    tex->cmask_base_address_reg = (tex->buffer.gpu_address + tex->surface.cmask_offset) >> 8;
1203 
1204    return tex;
1205 
1206 error:
1207    FREE_CL(tex);
1208    return NULL;
1209 }
1210 
si_choose_tiling(struct si_screen * sscreen,const struct pipe_resource * templ,bool tc_compatible_htile)1211 static enum radeon_surf_mode si_choose_tiling(struct si_screen *sscreen,
1212                                               const struct pipe_resource *templ,
1213                                               bool tc_compatible_htile)
1214 {
1215    const struct util_format_description *desc = util_format_description(templ->format);
1216    bool force_tiling = templ->flags & SI_RESOURCE_FLAG_FORCE_MSAA_TILING;
1217    bool is_depth_stencil = util_format_is_depth_or_stencil(templ->format) &&
1218                            !(templ->flags & SI_RESOURCE_FLAG_FLUSHED_DEPTH);
1219 
1220    /* MSAA resources must be 2D tiled. */
1221    if (templ->nr_samples > 1)
1222       return RADEON_SURF_MODE_2D;
1223 
1224    /* Transfer resources should be linear. */
1225    if (templ->flags & SI_RESOURCE_FLAG_FORCE_LINEAR)
1226       return RADEON_SURF_MODE_LINEAR_ALIGNED;
1227 
1228    /* Avoid Z/S decompress blits by forcing TC-compatible HTILE on GFX8,
1229     * which requires 2D tiling.
1230     */
1231    if (sscreen->info.gfx_level == GFX8 && tc_compatible_htile)
1232       return RADEON_SURF_MODE_2D;
1233 
1234    /* Handle common candidates for the linear mode.
1235     * Compressed textures and DB surfaces must always be tiled.
1236     */
1237    if (!force_tiling && !is_depth_stencil && !util_format_is_compressed(templ->format)) {
1238       if (sscreen->debug_flags & DBG(NO_TILING) ||
1239           (templ->bind & PIPE_BIND_SCANOUT && sscreen->debug_flags & DBG(NO_DISPLAY_TILING)))
1240          return RADEON_SURF_MODE_LINEAR_ALIGNED;
1241 
1242       /* Tiling doesn't work with the 422 (SUBSAMPLED) formats. */
1243       if (desc->layout == UTIL_FORMAT_LAYOUT_SUBSAMPLED)
1244          return RADEON_SURF_MODE_LINEAR_ALIGNED;
1245 
1246       /* Cursors are linear on AMD GCN.
1247        * (XXX double-check, maybe also use RADEON_SURF_SCANOUT) */
1248       if (templ->bind & PIPE_BIND_CURSOR)
1249          return RADEON_SURF_MODE_LINEAR_ALIGNED;
1250 
1251       if (templ->bind & PIPE_BIND_LINEAR)
1252          return RADEON_SURF_MODE_LINEAR_ALIGNED;
1253 
1254       /* Textures with a very small height are recommended to be linear. */
1255       if (templ->target == PIPE_TEXTURE_1D || templ->target == PIPE_TEXTURE_1D_ARRAY ||
1256           /* Only very thin and long 2D textures should benefit from
1257            * linear_aligned. */
1258           templ->height0 <= 2)
1259          return RADEON_SURF_MODE_LINEAR_ALIGNED;
1260 
1261       /* Textures likely to be mapped often. */
1262       if (templ->usage == PIPE_USAGE_STAGING || templ->usage == PIPE_USAGE_STREAM)
1263          return RADEON_SURF_MODE_LINEAR_ALIGNED;
1264    }
1265 
1266    /* Make small textures 1D tiled. */
1267    if (templ->width0 <= 16 || templ->height0 <= 16 || (sscreen->debug_flags & DBG(NO_2D_TILING)))
1268       return RADEON_SURF_MODE_1D;
1269 
1270    /* The allocator will switch to 1D if needed. */
1271    return RADEON_SURF_MODE_2D;
1272 }
1273 
1274 static struct pipe_resource *
si_texture_create_with_modifier(struct pipe_screen * screen,const struct pipe_resource * templ,uint64_t modifier)1275 si_texture_create_with_modifier(struct pipe_screen *screen,
1276                                 const struct pipe_resource *templ,
1277                                 uint64_t modifier)
1278 {
1279    struct si_screen *sscreen = (struct si_screen *)screen;
1280    bool is_zs = util_format_is_depth_or_stencil(templ->format);
1281 
1282    if (templ->nr_samples >= 2) {
1283       /* This is hackish (overwriting the const pipe_resource template),
1284        * but should be harmless and gallium frontends can also see
1285        * the overridden number of samples in the created pipe_resource.
1286        */
1287       if (is_zs && sscreen->eqaa_force_z_samples) {
1288          ((struct pipe_resource *)templ)->nr_samples =
1289             ((struct pipe_resource *)templ)->nr_storage_samples = sscreen->eqaa_force_z_samples;
1290       } else if (!is_zs && sscreen->eqaa_force_color_samples) {
1291          ((struct pipe_resource *)templ)->nr_samples = sscreen->eqaa_force_coverage_samples;
1292          ((struct pipe_resource *)templ)->nr_storage_samples = sscreen->eqaa_force_color_samples;
1293       }
1294    }
1295 
1296    bool is_flushed_depth = templ->flags & SI_RESOURCE_FLAG_FLUSHED_DEPTH ||
1297                            templ->flags & SI_RESOURCE_FLAG_FORCE_LINEAR;
1298    bool tc_compatible_htile =
1299       sscreen->info.gfx_level >= GFX8 &&
1300       /* There are issues with TC-compatible HTILE on Tonga (and
1301        * Iceland is the same design), and documented bug workarounds
1302        * don't help. For example, this fails:
1303        *   piglit/bin/tex-miplevel-selection 'texture()' 2DShadow -auto
1304        */
1305       sscreen->info.family != CHIP_TONGA && sscreen->info.family != CHIP_ICELAND &&
1306       (templ->flags & PIPE_RESOURCE_FLAG_TEXTURING_MORE_LIKELY) &&
1307       !(sscreen->debug_flags & DBG(NO_HYPERZ)) && !is_flushed_depth &&
1308       is_zs;
1309    enum radeon_surf_mode tile_mode = si_choose_tiling(sscreen, templ, tc_compatible_htile);
1310 
1311    /* This allocates textures with multiple planes like NV12 in 1 buffer. */
1312    enum
1313    {
1314       SI_TEXTURE_MAX_PLANES = 3
1315    };
1316    struct radeon_surf surface[SI_TEXTURE_MAX_PLANES] = {};
1317    struct pipe_resource plane_templ[SI_TEXTURE_MAX_PLANES];
1318    uint64_t plane_offset[SI_TEXTURE_MAX_PLANES] = {};
1319    uint64_t total_size = 0;
1320    unsigned max_alignment = 0;
1321    unsigned num_planes = util_format_get_num_planes(templ->format);
1322    assert(num_planes <= SI_TEXTURE_MAX_PLANES);
1323 
1324    /* Compute texture or plane layouts and offsets. */
1325    for (unsigned i = 0; i < num_planes; i++) {
1326       plane_templ[i] = *templ;
1327       plane_templ[i].format = util_format_get_plane_format(templ->format, i);
1328       plane_templ[i].width0 = util_format_get_plane_width(templ->format, i, templ->width0);
1329       plane_templ[i].height0 = util_format_get_plane_height(templ->format, i, templ->height0);
1330 
1331       /* Multi-plane allocations need PIPE_BIND_SHARED, because we can't
1332        * reallocate the storage to add PIPE_BIND_SHARED, because it's
1333        * shared by 3 pipe_resources.
1334        */
1335       if (num_planes > 1)
1336          plane_templ[i].bind |= PIPE_BIND_SHARED;
1337       /* Setting metadata on suballocated buffers is impossible. So use PIPE_BIND_CUSTOM to
1338        * request a non-suballocated buffer.
1339        */
1340       if (!is_zs && sscreen->debug_flags & DBG(EXTRA_METADATA))
1341          plane_templ[i].bind |= PIPE_BIND_CUSTOM;
1342 
1343       if (si_init_surface(sscreen, &surface[i], &plane_templ[i], tile_mode, modifier,
1344                           false, plane_templ[i].bind & PIPE_BIND_SCANOUT,
1345                           is_flushed_depth, tc_compatible_htile))
1346          return NULL;
1347 
1348       plane_templ[i].nr_sparse_levels = surface[i].first_mip_tail_level;
1349 
1350       plane_offset[i] = align64(total_size, 1 << surface[i].surf_alignment_log2);
1351       total_size = plane_offset[i] + surface[i].total_size;
1352       max_alignment = MAX2(max_alignment, 1 << surface[i].surf_alignment_log2);
1353    }
1354 
1355    struct si_texture *plane0 = NULL, *last_plane = NULL;
1356 
1357    for (unsigned i = 0; i < num_planes; i++) {
1358       struct si_texture *tex =
1359          si_texture_create_object(screen, &plane_templ[i], &surface[i], plane0, NULL,
1360                                   plane_offset[i], 0, total_size, max_alignment);
1361       if (!tex) {
1362          si_texture_reference(&plane0, NULL);
1363          return NULL;
1364       }
1365 
1366       tex->plane_index = i;
1367       tex->num_planes = num_planes;
1368 
1369       if (!plane0) {
1370          plane0 = last_plane = tex;
1371       } else {
1372          last_plane->buffer.b.b.next = &tex->buffer.b.b;
1373          last_plane = tex;
1374       }
1375       if (i == 0 && !is_zs && tex->surface.fmask_size == 0 &&
1376           sscreen->debug_flags & DBG(EXTRA_METADATA))
1377          si_set_tex_bo_metadata(sscreen, tex);
1378    }
1379 
1380    if (num_planes >= 2)
1381       plane0->multi_plane_format = templ->format;
1382 
1383    return (struct pipe_resource *)plane0;
1384 }
1385 
si_texture_create(struct pipe_screen * screen,const struct pipe_resource * templ)1386 struct pipe_resource *si_texture_create(struct pipe_screen *screen,
1387                                         const struct pipe_resource *templ)
1388 {
1389    return si_texture_create_with_modifier(screen, templ, DRM_FORMAT_MOD_INVALID);
1390 }
1391 
si_texture_commit(struct si_context * ctx,struct si_resource * res,unsigned level,struct pipe_box * box,bool commit)1392 bool si_texture_commit(struct si_context *ctx, struct si_resource *res, unsigned level,
1393                        struct pipe_box *box, bool commit)
1394 {
1395    struct si_texture *tex = (struct si_texture *)res;
1396    struct radeon_surf *surface = &tex->surface;
1397    enum pipe_format format = res->b.b.format;
1398    unsigned blks = util_format_get_blocksize(format);
1399    unsigned samples = MAX2(1, res->b.b.nr_samples);
1400 
1401    assert(ctx->gfx_level >= GFX9);
1402 
1403    unsigned row_pitch = surface->u.gfx9.prt_level_pitch[level] *
1404       surface->prt_tile_height * surface->prt_tile_depth * blks * samples;
1405    uint64_t depth_pitch = surface->u.gfx9.surf_slice_size * surface->prt_tile_depth;
1406 
1407    unsigned x = box->x / surface->prt_tile_width;
1408    unsigned y = box->y / surface->prt_tile_height;
1409    unsigned z = box->z / surface->prt_tile_depth;
1410 
1411    unsigned w = DIV_ROUND_UP(box->width, surface->prt_tile_width);
1412    unsigned h = DIV_ROUND_UP(box->height, surface->prt_tile_height);
1413    unsigned d = DIV_ROUND_UP(box->depth, surface->prt_tile_depth);
1414 
1415    /* Align to tile block base, for levels in mip tail whose offset is inside
1416     * a tile block.
1417     */
1418    uint64_t level_base = ROUND_DOWN_TO(surface->u.gfx9.prt_level_offset[level],
1419                                        RADEON_SPARSE_PAGE_SIZE);
1420    uint64_t commit_base = level_base +
1421       x * RADEON_SPARSE_PAGE_SIZE + y * (uint64_t)row_pitch + z * depth_pitch;
1422 
1423    uint64_t size = (uint64_t)w * RADEON_SPARSE_PAGE_SIZE;
1424    for (int i = 0; i < d; i++) {
1425       uint64_t base = commit_base + i * depth_pitch;
1426       for (int j = 0; j < h; j++) {
1427          uint64_t offset = base + j * row_pitch;
1428          if (!ctx->ws->buffer_commit(ctx->ws, res->buf, offset, size, commit))
1429             return false;
1430       }
1431    }
1432 
1433    return true;
1434 }
1435 
si_query_dmabuf_modifiers(struct pipe_screen * screen,enum pipe_format format,int max,uint64_t * modifiers,unsigned int * external_only,int * count)1436 static void si_query_dmabuf_modifiers(struct pipe_screen *screen,
1437                                       enum pipe_format format,
1438                                       int max,
1439                                       uint64_t *modifiers,
1440                                       unsigned int *external_only,
1441                                       int *count)
1442 {
1443    struct si_screen *sscreen = (struct si_screen *)screen;
1444 
1445    unsigned ac_mod_count = max;
1446    ac_get_supported_modifiers(&sscreen->info, &(struct ac_modifier_options) {
1447          .dcc = !(sscreen->debug_flags & DBG(NO_DCC)),
1448          /* Do not support DCC with retiling yet. This needs explicit
1449           * resource flushes, but the app has no way to promise doing
1450           * flushes with modifiers. */
1451          .dcc_retile = !(sscreen->debug_flags & DBG(NO_DCC)),
1452       }, format, &ac_mod_count,  max ? modifiers : NULL);
1453    if (max && external_only) {
1454       for (unsigned i = 0; i < ac_mod_count; ++i)
1455          external_only[i] = util_format_is_yuv(format);
1456    }
1457    *count = ac_mod_count;
1458 }
1459 
1460 static bool
si_is_dmabuf_modifier_supported(struct pipe_screen * screen,uint64_t modifier,enum pipe_format format,bool * external_only)1461 si_is_dmabuf_modifier_supported(struct pipe_screen *screen,
1462                                uint64_t modifier,
1463                                enum pipe_format format,
1464                                bool *external_only)
1465 {
1466    int allowed_mod_count;
1467    si_query_dmabuf_modifiers(screen, format, 0, NULL, NULL, &allowed_mod_count);
1468 
1469    uint64_t *allowed_modifiers = (uint64_t *)calloc(allowed_mod_count, sizeof(uint64_t));
1470    if (!allowed_modifiers)
1471       return false;
1472 
1473    unsigned *external_array = NULL;
1474    if (external_only) {
1475       external_array = (unsigned *)calloc(allowed_mod_count, sizeof(unsigned));
1476       if (!external_array) {
1477          free(allowed_modifiers);
1478          return false;
1479       }
1480    }
1481 
1482    si_query_dmabuf_modifiers(screen, format, allowed_mod_count, allowed_modifiers,
1483                             external_array, &allowed_mod_count);
1484 
1485    bool supported = false;
1486    for (int i = 0; i < allowed_mod_count && !supported; ++i) {
1487       if (allowed_modifiers[i] != modifier)
1488          continue;
1489 
1490       supported = true;
1491       if (external_only)
1492          *external_only = external_array[i];
1493    }
1494 
1495    free(allowed_modifiers);
1496    free(external_array);
1497    return supported;
1498 }
1499 
1500 static unsigned
si_get_dmabuf_modifier_planes(struct pipe_screen * pscreen,uint64_t modifier,enum pipe_format format)1501 si_get_dmabuf_modifier_planes(struct pipe_screen *pscreen, uint64_t modifier,
1502                              enum pipe_format format)
1503 {
1504    unsigned planes = util_format_get_num_planes(format);
1505 
1506    if (IS_AMD_FMT_MOD(modifier) && planes == 1) {
1507       if (AMD_FMT_MOD_GET(DCC_RETILE, modifier))
1508          return 3;
1509       else if (AMD_FMT_MOD_GET(DCC, modifier))
1510          return 2;
1511       else
1512          return 1;
1513    }
1514 
1515    return planes;
1516 }
1517 
1518 static bool
si_modifier_supports_resource(struct pipe_screen * screen,uint64_t modifier,const struct pipe_resource * templ)1519 si_modifier_supports_resource(struct pipe_screen *screen,
1520                               uint64_t modifier,
1521                               const struct pipe_resource *templ)
1522 {
1523    struct si_screen *sscreen = (struct si_screen *)screen;
1524    uint32_t max_width, max_height;
1525 
1526    ac_modifier_max_extent(&sscreen->info, modifier, &max_width, &max_height);
1527    return templ->width0 <= max_width && templ->height0 <= max_height;
1528 }
1529 
1530 static struct pipe_resource *
si_texture_create_with_modifiers(struct pipe_screen * screen,const struct pipe_resource * templ,const uint64_t * modifiers,int modifier_count)1531 si_texture_create_with_modifiers(struct pipe_screen *screen,
1532                                  const struct pipe_resource *templ,
1533                                  const uint64_t *modifiers,
1534                                  int modifier_count)
1535 {
1536    /* Buffers with modifiers make zero sense. */
1537    assert(templ->target != PIPE_BUFFER);
1538 
1539    /* Select modifier. */
1540    int allowed_mod_count;
1541    si_query_dmabuf_modifiers(screen, templ->format, 0, NULL, NULL, &allowed_mod_count);
1542 
1543    uint64_t *allowed_modifiers = (uint64_t *)calloc(allowed_mod_count, sizeof(uint64_t));
1544    if (!allowed_modifiers) {
1545       return NULL;
1546    }
1547 
1548    /* This does not take external_only into account. We assume it is the same for all modifiers. */
1549    si_query_dmabuf_modifiers(screen, templ->format, allowed_mod_count, allowed_modifiers, NULL, &allowed_mod_count);
1550 
1551    uint64_t modifier = DRM_FORMAT_MOD_INVALID;
1552 
1553    /* Try to find the first allowed modifier that is in the application provided
1554     * list. We assume that the allowed modifiers are ordered in descending
1555     * preference in the list provided by si_query_dmabuf_modifiers. */
1556    for (int i = 0; i < allowed_mod_count; ++i) {
1557       bool found = false;
1558       for (int j = 0; j < modifier_count && !found; ++j)
1559          if (modifiers[j] == allowed_modifiers[i] && si_modifier_supports_resource(screen, modifiers[j], templ))
1560             found = true;
1561 
1562       if (found) {
1563          modifier = allowed_modifiers[i];
1564          break;
1565       }
1566    }
1567 
1568    free(allowed_modifiers);
1569 
1570    if (modifier == DRM_FORMAT_MOD_INVALID) {
1571       return NULL;
1572    }
1573    return si_texture_create_with_modifier(screen, templ, modifier);
1574 }
1575 
si_texture_is_aux_plane(const struct pipe_resource * resource)1576 static bool si_texture_is_aux_plane(const struct pipe_resource *resource)
1577 {
1578    return resource->flags & SI_RESOURCE_AUX_PLANE;
1579 }
1580 
si_texture_from_winsys_buffer(struct si_screen * sscreen,const struct pipe_resource * templ,struct pb_buffer_lean * buf,unsigned stride,uint64_t offset,uint64_t modifier,unsigned usage,bool dedicated)1581 static struct pipe_resource *si_texture_from_winsys_buffer(struct si_screen *sscreen,
1582                                                            const struct pipe_resource *templ,
1583                                                            struct pb_buffer_lean *buf, unsigned stride,
1584                                                            uint64_t offset, uint64_t modifier,
1585                                                            unsigned usage, bool dedicated)
1586 {
1587    struct radeon_surf surface = {};
1588    struct radeon_bo_metadata metadata = {};
1589    struct si_texture *tex;
1590    int r;
1591 
1592    /* Ignore metadata for non-zero planes. */
1593    if (offset != 0)
1594       dedicated = false;
1595 
1596    if (dedicated) {
1597       sscreen->ws->buffer_get_metadata(sscreen->ws, buf, &metadata, &surface);
1598    } else {
1599       /**
1600        * The bo metadata is unset for un-dedicated images. So we fall
1601        * back to linear. See answer to question 5 of the
1602        * VK_KHX_external_memory spec for some details.
1603        *
1604        * It is possible that this case isn't going to work if the
1605        * surface pitch isn't correctly aligned by default.
1606        *
1607        * In order to support it correctly we require multi-image
1608        * metadata to be synchronized between radv and radeonsi. The
1609        * semantics of associating multiple image metadata to a memory
1610        * object on the vulkan export side are not concretely defined
1611        * either.
1612        *
1613        * All the use cases we are aware of at the moment for memory
1614        * objects use dedicated allocations. So lets keep the initial
1615        * implementation simple.
1616        *
1617        * A possible alternative is to attempt to reconstruct the
1618        * tiling information when the TexParameter TEXTURE_TILING_EXT
1619        * is set.
1620        */
1621       metadata.mode = RADEON_SURF_MODE_LINEAR_ALIGNED;
1622    }
1623 
1624    r = si_init_surface(sscreen, &surface, templ, metadata.mode, modifier, true,
1625                        surface.flags & RADEON_SURF_SCANOUT, false, false);
1626    if (r)
1627       return NULL;
1628 
1629    /* This is a hack to skip alignment checking for 3D textures */
1630    if (templ->target == PIPE_TEXTURE_3D)
1631       stride = 0;
1632 
1633    tex = si_texture_create_object(&sscreen->b, templ, &surface, NULL, buf,
1634                                   offset, stride, 0, 0);
1635    if (!tex)
1636       return NULL;
1637 
1638    tex->buffer.b.is_shared = true;
1639    tex->buffer.external_usage = usage;
1640    tex->num_planes = 1;
1641    if (tex->buffer.flags & RADEON_FLAG_ENCRYPTED)
1642       tex->buffer.b.b.bind |= PIPE_BIND_PROTECTED;
1643 
1644    /* Account for multiple planes with lowered yuv import. */
1645    struct pipe_resource *next_plane = tex->buffer.b.b.next;
1646    while (next_plane && !si_texture_is_aux_plane(next_plane)) {
1647       struct si_texture *next_tex = (struct si_texture *)next_plane;
1648       ++next_tex->num_planes;
1649       ++tex->num_planes;
1650       next_plane = next_plane->next;
1651    }
1652 
1653    unsigned nplanes = ac_surface_get_nplanes(&tex->surface);
1654    unsigned plane = 1;
1655    while (next_plane) {
1656       struct si_auxiliary_texture *ptex = (struct si_auxiliary_texture *)next_plane;
1657       if (plane >= nplanes || ptex->buffer != tex->buffer.buf ||
1658           ptex->offset != ac_surface_get_plane_offset(sscreen->info.gfx_level,
1659                                                       &tex->surface, plane, 0) ||
1660           ptex->stride != ac_surface_get_plane_stride(sscreen->info.gfx_level,
1661                                                       &tex->surface, plane, 0)) {
1662          si_texture_reference(&tex, NULL);
1663          return NULL;
1664       }
1665       ++plane;
1666       next_plane = next_plane->next;
1667    }
1668 
1669    if (plane != nplanes && tex->num_planes == 1) {
1670       si_texture_reference(&tex, NULL);
1671       return NULL;
1672    }
1673 
1674    if (!ac_surface_apply_umd_metadata(&sscreen->info, &tex->surface,
1675                                       tex->buffer.b.b.nr_storage_samples,
1676                                       tex->buffer.b.b.last_level + 1,
1677                                       metadata.size_metadata,
1678                                       metadata.metadata)) {
1679       si_texture_reference(&tex, NULL);
1680       return NULL;
1681    }
1682 
1683    if (ac_surface_get_plane_offset(sscreen->info.gfx_level, &tex->surface, 0, 0) +
1684         tex->surface.total_size > buf->size) {
1685       si_texture_reference(&tex, NULL);
1686       return NULL;
1687    }
1688 
1689    /* Displayable DCC requires an explicit flush. */
1690    if (dedicated && offset == 0 && !(usage & PIPE_HANDLE_USAGE_EXPLICIT_FLUSH) &&
1691        si_displayable_dcc_needs_explicit_flush(tex)) {
1692       /* TODO: do we need to decompress DCC? */
1693       if (si_texture_discard_dcc(sscreen, tex)) {
1694          /* Update BO metadata after disabling DCC. */
1695          si_set_tex_bo_metadata(sscreen, tex);
1696       }
1697    }
1698 
1699    assert(tex->surface.tile_swizzle == 0);
1700    return &tex->buffer.b.b;
1701 }
1702 
si_texture_from_handle(struct pipe_screen * screen,const struct pipe_resource * templ,struct winsys_handle * whandle,unsigned usage)1703 static struct pipe_resource *si_texture_from_handle(struct pipe_screen *screen,
1704                                                     const struct pipe_resource *templ,
1705                                                     struct winsys_handle *whandle, unsigned usage)
1706 {
1707    struct si_screen *sscreen = (struct si_screen *)screen;
1708    struct pb_buffer_lean *buf = NULL;
1709 
1710    buf = sscreen->ws->buffer_from_handle(sscreen->ws, whandle,
1711                                          sscreen->info.max_alignment,
1712                                          templ->bind & PIPE_BIND_PRIME_BLIT_DST);
1713    if (!buf)
1714       return NULL;
1715 
1716    if (templ->target == PIPE_BUFFER)
1717       return si_buffer_from_winsys_buffer(screen, templ, buf, 0);
1718 
1719    if (whandle->plane >= util_format_get_num_planes(whandle->format)) {
1720       struct si_auxiliary_texture *tex = CALLOC_STRUCT_CL(si_auxiliary_texture);
1721       if (!tex)
1722          return NULL;
1723       tex->b.b = *templ;
1724       tex->b.b.flags |= SI_RESOURCE_AUX_PLANE;
1725       tex->stride = whandle->stride;
1726       tex->offset = whandle->offset;
1727       tex->buffer = buf;
1728       pipe_reference_init(&tex->b.b.reference, 1);
1729       tex->b.b.screen = screen;
1730 
1731       return &tex->b.b;
1732    }
1733 
1734    return si_texture_from_winsys_buffer(sscreen, templ, buf, whandle->stride, whandle->offset,
1735                                         whandle->modifier, usage, true);
1736 }
1737 
si_init_flushed_depth_texture(struct pipe_context * ctx,struct pipe_resource * texture)1738 bool si_init_flushed_depth_texture(struct pipe_context *ctx, struct pipe_resource *texture)
1739 {
1740    struct si_texture *tex = (struct si_texture *)texture;
1741    struct pipe_resource resource;
1742    enum pipe_format pipe_format = texture->format;
1743 
1744    assert(!tex->flushed_depth_texture);
1745 
1746    if (!tex->can_sample_z && tex->can_sample_s) {
1747       switch (pipe_format) {
1748       case PIPE_FORMAT_Z32_FLOAT_S8X24_UINT:
1749          /* Save memory by not allocating the S plane. */
1750          pipe_format = PIPE_FORMAT_Z32_FLOAT;
1751          break;
1752       case PIPE_FORMAT_Z24_UNORM_S8_UINT:
1753       case PIPE_FORMAT_S8_UINT_Z24_UNORM:
1754          /* Save memory bandwidth by not copying the
1755           * stencil part during flush.
1756           *
1757           * This potentially increases memory bandwidth
1758           * if an application uses both Z and S texturing
1759           * simultaneously (a flushed Z24S8 texture
1760           * would be stored compactly), but how often
1761           * does that really happen?
1762           */
1763          pipe_format = PIPE_FORMAT_Z24X8_UNORM;
1764          break;
1765       default:;
1766       }
1767    } else if (!tex->can_sample_s && tex->can_sample_z) {
1768       assert(util_format_has_stencil(util_format_description(pipe_format)));
1769 
1770       /* DB->CB copies to an 8bpp surface don't work. */
1771       pipe_format = PIPE_FORMAT_X24S8_UINT;
1772    }
1773 
1774    memset(&resource, 0, sizeof(resource));
1775    resource.target = texture->target;
1776    resource.format = pipe_format;
1777    resource.width0 = texture->width0;
1778    resource.height0 = texture->height0;
1779    resource.depth0 = texture->depth0;
1780    resource.array_size = texture->array_size;
1781    resource.last_level = texture->last_level;
1782    resource.nr_samples = texture->nr_samples;
1783    resource.nr_storage_samples = texture->nr_storage_samples;
1784    resource.usage = PIPE_USAGE_DEFAULT;
1785    resource.bind = texture->bind & ~PIPE_BIND_DEPTH_STENCIL;
1786    resource.flags = texture->flags | SI_RESOURCE_FLAG_FLUSHED_DEPTH;
1787 
1788    tex->flushed_depth_texture =
1789       (struct si_texture *)ctx->screen->resource_create(ctx->screen, &resource);
1790    if (!tex->flushed_depth_texture) {
1791       PRINT_ERR("failed to create temporary texture to hold flushed depth\n");
1792       return false;
1793    }
1794    return true;
1795 }
1796 
1797 /**
1798  * Initialize the pipe_resource descriptor to be of the same size as the box,
1799  * which is supposed to hold a subregion of the texture "orig" at the given
1800  * mipmap level.
1801  */
si_init_temp_resource_from_box(struct pipe_resource * res,struct pipe_resource * orig,const struct pipe_box * box,unsigned level,unsigned usage,unsigned flags)1802 static void si_init_temp_resource_from_box(struct pipe_resource *res, struct pipe_resource *orig,
1803                                            const struct pipe_box *box, unsigned level,
1804                                            unsigned usage, unsigned flags)
1805 {
1806    struct si_texture *tex = (struct si_texture *)orig;
1807    enum pipe_format orig_format = tex->multi_plane_format != PIPE_FORMAT_NONE ?
1808       tex->multi_plane_format : orig->format;
1809 
1810    memset(res, 0, sizeof(*res));
1811    res->format = orig_format;
1812    res->width0 = box->width;
1813    res->height0 = box->height;
1814    res->depth0 = 1;
1815    res->array_size = 1;
1816    res->usage = usage;
1817    res->flags = flags;
1818 
1819    if (flags & SI_RESOURCE_FLAG_FORCE_LINEAR && util_format_is_compressed(orig_format)) {
1820       /* Transfer resources are allocated with linear tiling, which is
1821        * not supported for compressed formats.
1822        */
1823       unsigned blocksize = util_format_get_blocksize(orig_format);
1824 
1825       if (blocksize == 8) {
1826          res->format = PIPE_FORMAT_R16G16B16A16_UINT;
1827       } else {
1828          assert(blocksize == 16);
1829          res->format = PIPE_FORMAT_R32G32B32A32_UINT;
1830       }
1831 
1832       res->width0 = util_format_get_nblocksx(orig_format, box->width);
1833       res->height0 = util_format_get_nblocksy(orig_format, box->height);
1834    }
1835 
1836    /* We must set the correct texture target and dimensions for a 3D box. */
1837    if (box->depth > 1 && util_max_layer(orig, level) > 0) {
1838       res->target = PIPE_TEXTURE_2D_ARRAY;
1839       res->array_size = box->depth;
1840    } else {
1841       res->target = PIPE_TEXTURE_2D;
1842    }
1843 }
1844 
si_can_invalidate_texture(struct si_screen * sscreen,struct si_texture * tex,unsigned transfer_usage,const struct pipe_box * box)1845 static bool si_can_invalidate_texture(struct si_screen *sscreen, struct si_texture *tex,
1846                                       unsigned transfer_usage, const struct pipe_box *box)
1847 {
1848    return !tex->buffer.b.is_shared && !(tex->surface.flags & RADEON_SURF_IMPORTED) &&
1849           !(transfer_usage & PIPE_MAP_READ) && tex->buffer.b.b.last_level == 0 &&
1850           util_texrange_covers_whole_level(&tex->buffer.b.b, 0, box->x, box->y, box->z, box->width,
1851                                            box->height, box->depth);
1852 }
1853 
si_texture_invalidate_storage(struct si_context * sctx,struct si_texture * tex)1854 static void si_texture_invalidate_storage(struct si_context *sctx, struct si_texture *tex)
1855 {
1856    struct si_screen *sscreen = sctx->screen;
1857 
1858    /* There is no point in discarding depth and tiled buffers. */
1859    assert(!tex->is_depth);
1860    assert(tex->surface.is_linear);
1861 
1862    /* Reallocate the buffer in the same pipe_resource. */
1863    si_alloc_resource(sscreen, &tex->buffer);
1864 
1865    /* Initialize the CMASK base address (needed even without CMASK). */
1866    tex->cmask_base_address_reg = (tex->buffer.gpu_address + tex->surface.cmask_offset) >> 8;
1867 
1868    p_atomic_inc(&sscreen->dirty_tex_counter);
1869 
1870    sctx->num_alloc_tex_transfer_bytes += tex->surface.total_size;
1871 }
1872 
si_texture_transfer_map(struct pipe_context * ctx,struct pipe_resource * texture,unsigned level,unsigned usage,const struct pipe_box * box,struct pipe_transfer ** ptransfer)1873 static void *si_texture_transfer_map(struct pipe_context *ctx, struct pipe_resource *texture,
1874                                      unsigned level, unsigned usage, const struct pipe_box *box,
1875                                      struct pipe_transfer **ptransfer)
1876 {
1877    struct si_context *sctx = (struct si_context *)ctx;
1878    struct si_texture *tex = (struct si_texture *)texture;
1879    struct si_transfer *trans;
1880    struct si_resource *buf;
1881    uint64_t offset = 0;
1882    char *map;
1883    bool use_staging_texture = tex->buffer.flags & RADEON_FLAG_ENCRYPTED;
1884    unsigned real_level = texture->nr_samples > 1 ? 0 : level;
1885 
1886    assert(texture->target != PIPE_BUFFER);
1887    assert(!(texture->flags & SI_RESOURCE_FLAG_FORCE_LINEAR));
1888    assert(box->width && box->height && box->depth);
1889 
1890    if (tex->buffer.b.b.flags & SI_RESOURCE_AUX_PLANE)
1891       return NULL;
1892 
1893    if ((tex->buffer.flags & RADEON_FLAG_ENCRYPTED) && usage & PIPE_MAP_READ)
1894       return NULL;
1895 
1896    if (tex->is_depth || tex->buffer.flags & RADEON_FLAG_SPARSE) {
1897       /* Depth and sparse textures use staging unconditionally. */
1898       use_staging_texture = true;
1899    } else {
1900       /* Degrade the tile mode if we get too many transfers on APUs.
1901        * On dGPUs, the staging texture is always faster.
1902        * Only count uploads that are at least 4x4 pixels large.
1903        */
1904       if (!sctx->screen->info.has_dedicated_vram && real_level == 0 && box->width >= 4 &&
1905           box->height >= 4 && p_atomic_inc_return(&tex->num_level0_transfers) == 10) {
1906          bool can_invalidate = si_can_invalidate_texture(sctx->screen, tex, usage, box);
1907 
1908          si_reallocate_texture_inplace(sctx, tex, PIPE_BIND_LINEAR, can_invalidate);
1909       }
1910 
1911       /* Tiled textures need to be converted into a linear texture for CPU
1912        * access. The staging texture is always linear and is placed in GART.
1913        *
1914        * dGPU use a staging texture for VRAM, so that we don't map it and
1915        * don't relocate it to GTT.
1916        *
1917        * Reading from VRAM or GTT WC is slow, always use the staging
1918        * texture in this case.
1919        *
1920        * Use the staging texture for uploads if the underlying BO
1921        * is busy.
1922        */
1923       if (!tex->surface.is_linear || (tex->buffer.flags & RADEON_FLAG_ENCRYPTED) ||
1924           (tex->buffer.domains & RADEON_DOMAIN_VRAM && sctx->screen->info.has_dedicated_vram))
1925          use_staging_texture = true;
1926       else if (usage & PIPE_MAP_READ)
1927          use_staging_texture =
1928             tex->buffer.domains & RADEON_DOMAIN_VRAM || tex->buffer.flags & RADEON_FLAG_GTT_WC;
1929       /* Write & linear only: */
1930       else if (si_cs_is_buffer_referenced(sctx, tex->buffer.buf, RADEON_USAGE_READWRITE) ||
1931                !sctx->ws->buffer_wait(sctx->ws, tex->buffer.buf, 0, RADEON_USAGE_READWRITE)) {
1932          /* It's busy. */
1933          if (si_can_invalidate_texture(sctx->screen, tex, usage, box))
1934             si_texture_invalidate_storage(sctx, tex);
1935          else
1936             use_staging_texture = true;
1937       }
1938    }
1939 
1940    trans = CALLOC_STRUCT(si_transfer);
1941    if (!trans)
1942       return NULL;
1943    pipe_resource_reference(&trans->b.b.resource, texture);
1944    trans->b.b.level = level;
1945    trans->b.b.usage = usage;
1946    trans->b.b.box = *box;
1947 
1948    if (use_staging_texture) {
1949       struct pipe_resource resource;
1950       struct si_texture *staging;
1951       unsigned bo_usage = usage & PIPE_MAP_READ ? PIPE_USAGE_STAGING : PIPE_USAGE_STREAM;
1952       unsigned bo_flags = SI_RESOURCE_FLAG_FORCE_LINEAR | SI_RESOURCE_FLAG_DRIVER_INTERNAL;
1953 
1954       si_init_temp_resource_from_box(&resource, texture, box, real_level, bo_usage,
1955                                      bo_flags);
1956 
1957       /* Since depth-stencil textures don't support linear tiling,
1958        * blit from ZS to color and vice versa. u_blitter will do
1959        * the packing for these formats.
1960        */
1961       if (tex->is_depth)
1962          resource.format = util_blitter_get_color_format_for_zs(resource.format);
1963 
1964       /* Create the temporary texture. */
1965       staging = (struct si_texture *)ctx->screen->resource_create(ctx->screen, &resource);
1966       if (!staging) {
1967          PRINT_ERR("failed to create temporary texture to hold untiled copy\n");
1968          goto fail_trans;
1969       }
1970       trans->staging = &staging->buffer;
1971 
1972       /* Just get the strides. */
1973       si_texture_get_offset(sctx->screen, staging, 0, NULL, &trans->b.b.stride,
1974                             &trans->b.b.layer_stride);
1975 
1976       if (usage & PIPE_MAP_READ)
1977          si_copy_to_staging_texture(ctx, trans);
1978       else
1979          usage |= PIPE_MAP_UNSYNCHRONIZED;
1980 
1981       buf = trans->staging;
1982    } else {
1983       /* the resource is mapped directly */
1984       offset = si_texture_get_offset(sctx->screen, tex, real_level, box, &trans->b.b.stride,
1985                                      &trans->b.b.layer_stride);
1986       buf = &tex->buffer;
1987    }
1988 
1989    /* Always unmap texture CPU mappings on 32-bit architectures, so that
1990     * we don't run out of the CPU address space.
1991     */
1992    if (sizeof(void *) == 4)
1993       usage |= RADEON_MAP_TEMPORARY;
1994 
1995    if (!(map = si_buffer_map(sctx, buf, usage)))
1996       goto fail_trans;
1997 
1998    *ptransfer = &trans->b.b;
1999    return map + offset;
2000 
2001 fail_trans:
2002    si_resource_reference(&trans->staging, NULL);
2003    pipe_resource_reference(&trans->b.b.resource, NULL);
2004    FREE(trans);
2005    return NULL;
2006 }
2007 
si_texture_transfer_unmap(struct pipe_context * ctx,struct pipe_transfer * transfer)2008 static void si_texture_transfer_unmap(struct pipe_context *ctx, struct pipe_transfer *transfer)
2009 {
2010    struct si_context *sctx = (struct si_context *)ctx;
2011    struct si_transfer *stransfer = (struct si_transfer *)transfer;
2012    struct pipe_resource *texture = transfer->resource;
2013    struct si_texture *tex = (struct si_texture *)texture;
2014 
2015    /* Always unmap texture CPU mappings on 32-bit architectures, so that
2016     * we don't run out of the CPU address space.
2017     */
2018    if (sizeof(void *) == 4) {
2019       struct si_resource *buf = stransfer->staging ? stransfer->staging : &tex->buffer;
2020 
2021       sctx->ws->buffer_unmap(sctx->ws, buf->buf);
2022    }
2023 
2024    if ((transfer->usage & PIPE_MAP_WRITE) && stransfer->staging)
2025       si_copy_from_staging_texture(ctx, stransfer);
2026 
2027    if (stransfer->staging) {
2028       sctx->num_alloc_tex_transfer_bytes += stransfer->staging->buf->size;
2029       si_resource_reference(&stransfer->staging, NULL);
2030    }
2031 
2032    /* Heuristic for {upload, draw, upload, draw, ..}:
2033     *
2034     * Flush the gfx IB if we've allocated too much texture storage.
2035     *
2036     * The idea is that we don't want to build IBs that use too much
2037     * memory and put pressure on the kernel memory manager and we also
2038     * want to make temporary and invalidated buffers go idle ASAP to
2039     * decrease the total memory usage or make them reusable. The memory
2040     * usage will be slightly higher than given here because of the buffer
2041     * cache in the winsys.
2042     *
2043     * The result is that the kernel memory manager is never a bottleneck.
2044     */
2045    if (sctx->num_alloc_tex_transfer_bytes > (uint64_t)sctx->screen->info.gart_size_kb * 1024 / 4) {
2046       si_flush_gfx_cs(sctx, RADEON_FLUSH_ASYNC_START_NEXT_GFX_IB_NOW, NULL);
2047       sctx->num_alloc_tex_transfer_bytes = 0;
2048    }
2049 
2050    pipe_resource_reference(&transfer->resource, NULL);
2051    FREE(transfer);
2052 }
2053 
2054 /* Return if it's allowed to reinterpret one format as another with DCC enabled.
2055  */
vi_dcc_formats_compatible(struct si_screen * sscreen,enum pipe_format format1,enum pipe_format format2)2056 bool vi_dcc_formats_compatible(struct si_screen *sscreen, enum pipe_format format1,
2057                                enum pipe_format format2)
2058 {
2059    const struct util_format_description *desc1, *desc2;
2060 
2061    /* All formats are compatible on GFX11. */
2062    if (sscreen->info.gfx_level >= GFX11)
2063       return true;
2064 
2065    /* No format change - exit early. */
2066    if (format1 == format2)
2067       return true;
2068 
2069    format1 = si_simplify_cb_format(format1);
2070    format2 = si_simplify_cb_format(format2);
2071 
2072    /* Check again after format adjustments. */
2073    if (format1 == format2)
2074       return true;
2075 
2076    desc1 = util_format_description(format1);
2077    desc2 = util_format_description(format2);
2078 
2079    if (desc1->layout != UTIL_FORMAT_LAYOUT_PLAIN || desc2->layout != UTIL_FORMAT_LAYOUT_PLAIN)
2080       return false;
2081 
2082    /* Float and non-float are totally incompatible. */
2083    if ((desc1->channel[0].type == UTIL_FORMAT_TYPE_FLOAT) !=
2084        (desc2->channel[0].type == UTIL_FORMAT_TYPE_FLOAT))
2085       return false;
2086 
2087    /* Channel sizes must match across DCC formats.
2088     * Comparing just the first 2 channels should be enough.
2089     */
2090    if (desc1->channel[0].size != desc2->channel[0].size ||
2091        (desc1->nr_channels >= 2 && desc1->channel[1].size != desc2->channel[1].size))
2092       return false;
2093 
2094    /* Everything below is not needed if the driver never uses the DCC
2095     * clear code with the value of 1.
2096     */
2097 
2098    /* If the clear values are all 1 or all 0, this constraint can be
2099     * ignored. */
2100    if (vi_alpha_is_on_msb(sscreen, format1) != vi_alpha_is_on_msb(sscreen, format2))
2101       return false;
2102 
2103    /* Channel types must match if the clear value of 1 is used.
2104     * The type categories are only float, signed, unsigned.
2105     * NORM and INT are always compatible.
2106     */
2107    if (desc1->channel[0].type != desc2->channel[0].type ||
2108        (desc1->nr_channels >= 2 && desc1->channel[1].type != desc2->channel[1].type))
2109       return false;
2110 
2111    return true;
2112 }
2113 
vi_dcc_formats_are_incompatible(struct pipe_resource * tex,unsigned level,enum pipe_format view_format)2114 bool vi_dcc_formats_are_incompatible(struct pipe_resource *tex, unsigned level,
2115                                      enum pipe_format view_format)
2116 {
2117    struct si_texture *stex = (struct si_texture *)tex;
2118 
2119    return vi_dcc_enabled(stex, level) &&
2120           !vi_dcc_formats_compatible((struct si_screen *)tex->screen, tex->format, view_format);
2121 }
2122 
2123 /* This can't be merged with the above function, because
2124  * vi_dcc_formats_compatible should be called only when DCC is enabled. */
vi_disable_dcc_if_incompatible_format(struct si_context * sctx,struct pipe_resource * tex,unsigned level,enum pipe_format view_format)2125 void vi_disable_dcc_if_incompatible_format(struct si_context *sctx, struct pipe_resource *tex,
2126                                            unsigned level, enum pipe_format view_format)
2127 {
2128    struct si_texture *stex = (struct si_texture *)tex;
2129 
2130    if (vi_dcc_formats_are_incompatible(tex, level, view_format))
2131       if (!si_texture_disable_dcc(sctx, stex))
2132          si_decompress_dcc(sctx, stex);
2133 }
2134 
si_create_surface(struct pipe_context * pipe,struct pipe_resource * tex,const struct pipe_surface * templ)2135 static struct pipe_surface *si_create_surface(struct pipe_context *pipe, struct pipe_resource *tex,
2136                                               const struct pipe_surface *templ)
2137 {
2138    unsigned level = templ->u.tex.level;
2139    unsigned width = u_minify(tex->width0, level);
2140    unsigned height = u_minify(tex->height0, level);
2141    unsigned width0 = tex->width0;
2142    unsigned height0 = tex->height0;
2143 
2144    if (tex->target != PIPE_BUFFER && templ->format != tex->format) {
2145       const struct util_format_description *tex_desc = util_format_description(tex->format);
2146       const struct util_format_description *templ_desc = util_format_description(templ->format);
2147 
2148       assert(tex_desc->block.bits == templ_desc->block.bits);
2149 
2150       /* Adjust size of surface if and only if the block width or
2151        * height is changed. */
2152       if (tex_desc->block.width != templ_desc->block.width ||
2153           tex_desc->block.height != templ_desc->block.height) {
2154          unsigned nblks_x = util_format_get_nblocksx(tex->format, width);
2155          unsigned nblks_y = util_format_get_nblocksy(tex->format, height);
2156 
2157          width = nblks_x * templ_desc->block.width;
2158          height = nblks_y * templ_desc->block.height;
2159 
2160          width0 = util_format_get_nblocksx(tex->format, width0);
2161          height0 = util_format_get_nblocksy(tex->format, height0);
2162       }
2163    }
2164 
2165    struct si_surface *surface = CALLOC_STRUCT(si_surface);
2166 
2167    if (!surface)
2168       return NULL;
2169 
2170    assert(templ->u.tex.first_layer <= util_max_layer(tex, templ->u.tex.level));
2171    assert(templ->u.tex.last_layer <= util_max_layer(tex, templ->u.tex.level));
2172 
2173    pipe_reference_init(&surface->base.reference, 1);
2174    pipe_resource_reference(&surface->base.texture, tex);
2175    surface->base.context = pipe;
2176    surface->base.format = templ->format;
2177    surface->base.width = width;
2178    surface->base.height = height;
2179    surface->base.u = templ->u;
2180 
2181    surface->width0 = width0;
2182    surface->height0 = height0;
2183 
2184    surface->dcc_incompatible =
2185       tex->target != PIPE_BUFFER &&
2186       vi_dcc_formats_are_incompatible(tex, templ->u.tex.level, templ->format);
2187    return &surface->base;
2188 }
2189 
si_surface_destroy(struct pipe_context * pipe,struct pipe_surface * surface)2190 static void si_surface_destroy(struct pipe_context *pipe, struct pipe_surface *surface)
2191 {
2192    pipe_resource_reference(&surface->texture, NULL);
2193    FREE(surface);
2194 }
2195 
si_translate_colorswap(enum amd_gfx_level gfx_level,enum pipe_format format,bool do_endian_swap)2196 unsigned si_translate_colorswap(enum amd_gfx_level gfx_level, enum pipe_format format,
2197                                 bool do_endian_swap)
2198 {
2199    const struct util_format_description *desc = util_format_description(format);
2200 
2201 #define HAS_SWIZZLE(chan, swz) (desc->swizzle[chan] == PIPE_SWIZZLE_##swz)
2202 
2203    if (format == PIPE_FORMAT_R11G11B10_FLOAT) /* isn't plain */
2204       return V_028C70_SWAP_STD;
2205 
2206    if (gfx_level >= GFX10_3 &&
2207        format == PIPE_FORMAT_R9G9B9E5_FLOAT) /* isn't plain */
2208       return V_028C70_SWAP_STD;
2209 
2210    if (desc->layout != UTIL_FORMAT_LAYOUT_PLAIN)
2211       return ~0U;
2212 
2213    switch (desc->nr_channels) {
2214    case 1:
2215       if (HAS_SWIZZLE(0, X))
2216          return V_028C70_SWAP_STD; /* X___ */
2217       else if (HAS_SWIZZLE(3, X))
2218          return V_028C70_SWAP_ALT_REV; /* ___X */
2219       break;
2220    case 2:
2221       if ((HAS_SWIZZLE(0, X) && HAS_SWIZZLE(1, Y)) || (HAS_SWIZZLE(0, X) && HAS_SWIZZLE(1, NONE)) ||
2222           (HAS_SWIZZLE(0, NONE) && HAS_SWIZZLE(1, Y)))
2223          return V_028C70_SWAP_STD; /* XY__ */
2224       else if ((HAS_SWIZZLE(0, Y) && HAS_SWIZZLE(1, X)) ||
2225                (HAS_SWIZZLE(0, Y) && HAS_SWIZZLE(1, NONE)) ||
2226                (HAS_SWIZZLE(0, NONE) && HAS_SWIZZLE(1, X)))
2227          /* YX__ */
2228          return (do_endian_swap ? V_028C70_SWAP_STD : V_028C70_SWAP_STD_REV);
2229       else if (HAS_SWIZZLE(0, X) && HAS_SWIZZLE(3, Y))
2230          return V_028C70_SWAP_ALT; /* X__Y */
2231       else if (HAS_SWIZZLE(0, Y) && HAS_SWIZZLE(3, X))
2232          return V_028C70_SWAP_ALT_REV; /* Y__X */
2233       break;
2234    case 3:
2235       if (HAS_SWIZZLE(0, X))
2236          return (do_endian_swap ? V_028C70_SWAP_STD_REV : V_028C70_SWAP_STD);
2237       else if (HAS_SWIZZLE(0, Z))
2238          return V_028C70_SWAP_STD_REV; /* ZYX */
2239       break;
2240    case 4:
2241       /* check the middle channels, the 1st and 4th channel can be NONE */
2242       if (HAS_SWIZZLE(1, Y) && HAS_SWIZZLE(2, Z)) {
2243          return V_028C70_SWAP_STD; /* XYZW */
2244       } else if (HAS_SWIZZLE(1, Z) && HAS_SWIZZLE(2, Y)) {
2245          return V_028C70_SWAP_STD_REV; /* WZYX */
2246       } else if (HAS_SWIZZLE(1, Y) && HAS_SWIZZLE(2, X)) {
2247          return V_028C70_SWAP_ALT; /* ZYXW */
2248       } else if (HAS_SWIZZLE(1, Z) && HAS_SWIZZLE(2, W)) {
2249          /* YZWX */
2250          if (desc->is_array)
2251             return V_028C70_SWAP_ALT_REV;
2252          else
2253             return (do_endian_swap ? V_028C70_SWAP_ALT : V_028C70_SWAP_ALT_REV);
2254       }
2255       break;
2256    }
2257    return ~0U;
2258 }
2259 
2260 static struct pipe_memory_object *
si_memobj_from_handle(struct pipe_screen * screen,struct winsys_handle * whandle,bool dedicated)2261 si_memobj_from_handle(struct pipe_screen *screen, struct winsys_handle *whandle, bool dedicated)
2262 {
2263    struct si_screen *sscreen = (struct si_screen *)screen;
2264    struct si_memory_object *memobj = CALLOC_STRUCT(si_memory_object);
2265    struct pb_buffer_lean *buf = NULL;
2266 
2267    if (!memobj)
2268       return NULL;
2269 
2270    buf = sscreen->ws->buffer_from_handle(sscreen->ws, whandle, sscreen->info.max_alignment, false);
2271    if (!buf) {
2272       free(memobj);
2273       return NULL;
2274    }
2275 
2276    memobj->b.dedicated = dedicated;
2277    memobj->buf = buf;
2278    memobj->stride = whandle->stride;
2279 
2280    return (struct pipe_memory_object *)memobj;
2281 }
2282 
si_memobj_destroy(struct pipe_screen * screen,struct pipe_memory_object * _memobj)2283 static void si_memobj_destroy(struct pipe_screen *screen, struct pipe_memory_object *_memobj)
2284 {
2285    struct si_memory_object *memobj = (struct si_memory_object *)_memobj;
2286 
2287    radeon_bo_reference(((struct si_screen*)screen)->ws, &memobj->buf, NULL);
2288    free(memobj);
2289 }
2290 
si_resource_from_memobj(struct pipe_screen * screen,const struct pipe_resource * templ,struct pipe_memory_object * _memobj,uint64_t offset)2291 static struct pipe_resource *si_resource_from_memobj(struct pipe_screen *screen,
2292                                                     const struct pipe_resource *templ,
2293                                                     struct pipe_memory_object *_memobj,
2294                                                     uint64_t offset)
2295 {
2296    struct si_screen *sscreen = (struct si_screen *)screen;
2297    struct si_memory_object *memobj = (struct si_memory_object *)_memobj;
2298    struct pipe_resource *res;
2299 
2300    if (templ->target == PIPE_BUFFER)
2301       res = si_buffer_from_winsys_buffer(screen, templ, memobj->buf, offset);
2302    else
2303       res = si_texture_from_winsys_buffer(sscreen, templ, memobj->buf,
2304                                           memobj->stride,
2305                                           offset, DRM_FORMAT_MOD_INVALID,
2306                                           PIPE_HANDLE_USAGE_FRAMEBUFFER_WRITE | PIPE_HANDLE_USAGE_SHADER_WRITE,
2307                                           memobj->b.dedicated);
2308 
2309    if (!res)
2310       return NULL;
2311 
2312    /* si_texture_from_winsys_buffer doesn't increment refcount of
2313     * memobj->buf, so increment it here.
2314     */
2315    struct pb_buffer_lean *buf = NULL;
2316    radeon_bo_reference(sscreen->ws, &buf, memobj->buf);
2317    return res;
2318 }
2319 
si_check_resource_capability(struct pipe_screen * screen,struct pipe_resource * resource,unsigned bind)2320 static bool si_check_resource_capability(struct pipe_screen *screen, struct pipe_resource *resource,
2321                                          unsigned bind)
2322 {
2323    struct si_texture *tex = (struct si_texture *)resource;
2324 
2325    /* Buffers only support the linear flag. */
2326    if (resource->target == PIPE_BUFFER)
2327       return (bind & ~PIPE_BIND_LINEAR) == 0;
2328 
2329    if (bind & PIPE_BIND_LINEAR && !tex->surface.is_linear)
2330       return false;
2331 
2332    if (bind & PIPE_BIND_SCANOUT && !tex->surface.is_displayable)
2333       return false;
2334 
2335    /* TODO: PIPE_BIND_CURSOR - do we care? */
2336    return true;
2337 }
2338 
si_get_sparse_texture_virtual_page_size(struct pipe_screen * screen,enum pipe_texture_target target,bool multi_sample,enum pipe_format format,unsigned offset,unsigned size,int * x,int * y,int * z)2339 static int si_get_sparse_texture_virtual_page_size(struct pipe_screen *screen,
2340                                                    enum pipe_texture_target target,
2341                                                    bool multi_sample,
2342                                                    enum pipe_format format,
2343                                                    unsigned offset, unsigned size,
2344                                                    int *x, int *y, int *z)
2345 {
2346    struct si_screen *sscreen = (struct si_screen *)screen;
2347 
2348    /* Only support one type of page size. */
2349    if (offset != 0)
2350       return 0;
2351 
2352    static const int page_size_2d[][3] = {
2353       { 256, 256, 1 }, /* 8bpp   */
2354       { 256, 128, 1 }, /* 16bpp  */
2355       { 128, 128, 1 }, /* 32bpp  */
2356       { 128, 64,  1 }, /* 64bpp  */
2357       { 64,  64,  1 }, /* 128bpp */
2358    };
2359    static const int page_size_3d[][3] = {
2360       { 64,  32,  32 }, /* 8bpp   */
2361       { 32,  32,  32 }, /* 16bpp  */
2362       { 32,  32,  16 }, /* 32bpp  */
2363       { 32,  16,  16 }, /* 64bpp  */
2364       { 16,  16,  16 }, /* 128bpp */
2365    };
2366 
2367    const int (*page_sizes)[3];
2368 
2369    /* Supported targets. */
2370    switch (target) {
2371    case PIPE_TEXTURE_2D:
2372    case PIPE_TEXTURE_CUBE:
2373    case PIPE_TEXTURE_RECT:
2374    case PIPE_TEXTURE_2D_ARRAY:
2375    case PIPE_TEXTURE_CUBE_ARRAY:
2376       page_sizes = page_size_2d;
2377       break;
2378    case PIPE_TEXTURE_3D:
2379       page_sizes = page_size_3d;
2380       break;
2381    default:
2382       return 0;
2383    }
2384 
2385    /* ARB_sparse_texture2 need to query supported virtual page x/y/z without
2386     * knowing the actual sample count. So we need to return a fixed virtual page
2387     * x/y/z for all sample count which means the virtual page size can not be fixed
2388     * to 64KB.
2389     *
2390     * Only enabled for GFX9. GFX10+ removed MS texture support. By specification
2391     * ARB_sparse_texture2 need MS texture support, but we relax it by just return
2392     * no page size for GFX10+ to keep shader query capbility.
2393     */
2394    if (multi_sample && sscreen->info.gfx_level != GFX9)
2395       return 0;
2396 
2397    /* Unsupported formats. */
2398    /* TODO: support these formats. */
2399    if (util_format_is_depth_or_stencil(format) ||
2400        util_format_get_num_planes(format) > 1 ||
2401        util_format_is_compressed(format))
2402       return 0;
2403 
2404    int blk_size = util_format_get_blocksize(format);
2405    /* We don't support any non-power-of-two bpp formats, so
2406     * pipe_screen->is_format_supported() should already filter out these formats.
2407     */
2408    assert(util_is_power_of_two_nonzero(blk_size));
2409 
2410    if (size) {
2411       unsigned index = util_logbase2(blk_size);
2412       if (x) *x = page_sizes[index][0];
2413       if (y) *y = page_sizes[index][1];
2414       if (z) *z = page_sizes[index][2];
2415    }
2416 
2417    return 1;
2418 }
2419 
si_init_screen_texture_functions(struct si_screen * sscreen)2420 void si_init_screen_texture_functions(struct si_screen *sscreen)
2421 {
2422    sscreen->b.resource_from_handle = si_texture_from_handle;
2423    sscreen->b.resource_get_handle = si_texture_get_handle;
2424    sscreen->b.resource_get_param = si_resource_get_param;
2425    sscreen->b.resource_get_info = si_texture_get_info;
2426    sscreen->b.resource_from_memobj = si_resource_from_memobj;
2427    sscreen->b.memobj_create_from_handle = si_memobj_from_handle;
2428    sscreen->b.memobj_destroy = si_memobj_destroy;
2429    sscreen->b.check_resource_capability = si_check_resource_capability;
2430    sscreen->b.get_sparse_texture_virtual_page_size =
2431       si_get_sparse_texture_virtual_page_size;
2432 
2433    /* By not setting it the frontend will fall back to non-modifier create,
2434     * which works around some applications using modifiers that are not
2435     * allowed in combination with lack of error reporting in
2436     * gbm_dri_surface_create */
2437    if (sscreen->info.gfx_level >= GFX9 && sscreen->info.kernel_has_modifiers) {
2438       sscreen->b.resource_create_with_modifiers = si_texture_create_with_modifiers;
2439       sscreen->b.query_dmabuf_modifiers = si_query_dmabuf_modifiers;
2440       sscreen->b.is_dmabuf_modifier_supported = si_is_dmabuf_modifier_supported;
2441       sscreen->b.get_dmabuf_modifier_planes = si_get_dmabuf_modifier_planes;
2442    }
2443 }
2444 
si_init_context_texture_functions(struct si_context * sctx)2445 void si_init_context_texture_functions(struct si_context *sctx)
2446 {
2447    sctx->b.texture_map = si_texture_transfer_map;
2448    sctx->b.texture_unmap = si_texture_transfer_unmap;
2449    sctx->b.create_surface = si_create_surface;
2450    sctx->b.surface_destroy = si_surface_destroy;
2451 }
2452