• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2008 VMware, Inc.
3  * Copyright (C) 2012 Rob Clark <robclark@freedesktop.org>
4  * Copyright (C) 2014-2017 Broadcom
5  * Copyright (C) 2018-2019 Alyssa Rosenzweig
6  * Copyright (C) 2019 Collabora, Ltd.
7  * Copyright (C) 2023 Amazon.com, Inc. or its affiliates
8  *
9  * Permission is hereby granted, free of charge, to any person obtaining a
10  * copy of this software and associated documentation files (the "Software"),
11  * to deal in the Software without restriction, including without limitation
12  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
13  * and/or sell copies of the Software, and to permit persons to whom the
14  * Software is furnished to do so, subject to the following conditions:
15  *
16  * The above copyright notice and this permission notice (including the next
17  * paragraph) shall be included in all copies or substantial portions of the
18  * Software.
19  *
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
23  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26  * SOFTWARE.
27  *
28  * Authors (Collabora):
29  *   Tomeu Vizoso <tomeu.vizoso@collabora.com>
30  *   Alyssa Rosenzweig <alyssa.rosenzweig@collabora.com>
31  *
32  */
33 
34 #include <fcntl.h>
35 #include <xf86drm.h>
36 #include "drm-uapi/drm_fourcc.h"
37 
38 #include "frontend/winsys_handle.h"
39 #include "util/format/u_format.h"
40 #include "util/u_debug_image.h"
41 #include "util/u_drm.h"
42 #include "util/u_gen_mipmap.h"
43 #include "util/u_memory.h"
44 #include "util/u_resource.h"
45 #include "util/u_surface.h"
46 #include "util/u_transfer.h"
47 #include "util/u_transfer_helper.h"
48 
49 #include "decode.h"
50 #include "pan_bo.h"
51 #include "pan_context.h"
52 #include "pan_resource.h"
53 #include "pan_screen.h"
54 #include "pan_tiling.h"
55 #include "pan_util.h"
56 
57 static void
panfrost_clear_depth_stencil(struct pipe_context * pipe,struct pipe_surface * dst,unsigned clear_flags,double depth,unsigned stencil,unsigned dstx,unsigned dsty,unsigned width,unsigned height,bool render_condition_enabled)58 panfrost_clear_depth_stencil(struct pipe_context *pipe,
59                              struct pipe_surface *dst, unsigned clear_flags,
60                              double depth, unsigned stencil, unsigned dstx,
61                              unsigned dsty, unsigned width, unsigned height,
62                              bool render_condition_enabled)
63 {
64    struct panfrost_context *ctx = pan_context(pipe);
65 
66    if (render_condition_enabled && !panfrost_render_condition_check(ctx))
67       return;
68 
69    panfrost_blitter_save(
70       ctx, render_condition_enabled ? PAN_RENDER_COND : PAN_RENDER_BASE);
71    util_blitter_clear_depth_stencil(ctx->blitter, dst, clear_flags, depth,
72                                     stencil, dstx, dsty, width, height);
73 }
74 
75 static void
panfrost_clear_render_target(struct pipe_context * pipe,struct pipe_surface * dst,const union pipe_color_union * color,unsigned dstx,unsigned dsty,unsigned width,unsigned height,bool render_condition_enabled)76 panfrost_clear_render_target(struct pipe_context *pipe,
77                              struct pipe_surface *dst,
78                              const union pipe_color_union *color, unsigned dstx,
79                              unsigned dsty, unsigned width, unsigned height,
80                              bool render_condition_enabled)
81 {
82    struct panfrost_context *ctx = pan_context(pipe);
83 
84    if (render_condition_enabled && !panfrost_render_condition_check(ctx))
85       return;
86 
87    panfrost_blitter_save(
88       ctx, render_condition_enabled ? PAN_RENDER_COND : PAN_RENDER_BASE);
89    util_blitter_clear_render_target(ctx->blitter, dst, color, dstx, dsty, width,
90                                     height);
91 }
92 
93 static struct pipe_resource *
panfrost_resource_from_handle(struct pipe_screen * pscreen,const struct pipe_resource * templat,struct winsys_handle * whandle,unsigned usage)94 panfrost_resource_from_handle(struct pipe_screen *pscreen,
95                               const struct pipe_resource *templat,
96                               struct winsys_handle *whandle, unsigned usage)
97 {
98    struct panfrost_device *dev = pan_device(pscreen);
99    struct panfrost_resource *rsc;
100    struct pipe_resource *prsc;
101 
102    assert(whandle->type == WINSYS_HANDLE_TYPE_FD);
103 
104    rsc = CALLOC_STRUCT(panfrost_resource);
105    if (!rsc)
106       return NULL;
107 
108    prsc = &rsc->base;
109 
110    *prsc = *templat;
111 
112    pipe_reference_init(&prsc->reference, 1);
113    prsc->screen = pscreen;
114 
115    uint64_t mod = whandle->modifier == DRM_FORMAT_MOD_INVALID
116                      ? DRM_FORMAT_MOD_LINEAR
117                      : whandle->modifier;
118    enum mali_texture_dimension dim =
119       panfrost_translate_texture_dimension(templat->target);
120    struct pan_image_explicit_layout explicit_layout = {
121       .offset = whandle->offset,
122       .row_stride =
123          panfrost_from_legacy_stride(whandle->stride, templat->format, mod),
124    };
125 
126    rsc->image.layout = (struct pan_image_layout){
127       .modifier = mod,
128       .format = templat->format,
129       .dim = dim,
130       .width = prsc->width0,
131       .height = prsc->height0,
132       .depth = prsc->depth0,
133       .array_size = prsc->array_size,
134       .nr_samples = MAX2(prsc->nr_samples, 1),
135       .nr_slices = 1,
136    };
137 
138    bool valid =
139       pan_image_layout_init(dev->arch, &rsc->image.layout, &explicit_layout);
140 
141    if (!valid) {
142       FREE(rsc);
143       return NULL;
144    }
145 
146    rsc->bo = panfrost_bo_import(dev, whandle->handle);
147    /* Sometimes an import can fail e.g. on an invalid buffer fd, out of
148     * memory space to mmap it etc.
149     */
150    if (!rsc->bo) {
151       FREE(rsc);
152       return NULL;
153    }
154 
155    rsc->image.data.base = rsc->bo->ptr.gpu;
156    rsc->modifier_constant = true;
157 
158    BITSET_SET(rsc->valid.data, 0);
159    panfrost_resource_set_damage_region(pscreen, &rsc->base, 0, NULL);
160 
161    if (dev->ro) {
162       rsc->scanout =
163          renderonly_create_gpu_import_for_resource(prsc, dev->ro, NULL);
164       /* failure is expected in some cases.. */
165    }
166 
167    return prsc;
168 }
169 
170 static bool
panfrost_resource_get_handle(struct pipe_screen * pscreen,struct pipe_context * ctx,struct pipe_resource * pt,struct winsys_handle * handle,unsigned usage)171 panfrost_resource_get_handle(struct pipe_screen *pscreen,
172                              struct pipe_context *ctx, struct pipe_resource *pt,
173                              struct winsys_handle *handle, unsigned usage)
174 {
175    struct panfrost_device *dev = pan_device(pscreen);
176    struct panfrost_resource *rsrc;
177    struct renderonly_scanout *scanout;
178    struct pipe_resource *plane_res =
179       util_resource_at_index(pt, handle->plane);
180 
181    if (!plane_res)
182       return false;
183 
184    rsrc = pan_resource(plane_res);
185    scanout = rsrc->scanout;
186 
187    handle->modifier = rsrc->image.layout.modifier;
188    rsrc->modifier_constant = true;
189 
190    if (handle->type == WINSYS_HANDLE_TYPE_KMS && dev->ro) {
191       return renderonly_get_handle(scanout, handle);
192    } else if (handle->type == WINSYS_HANDLE_TYPE_KMS) {
193       handle->handle = panfrost_bo_handle(rsrc->bo);
194    } else if (handle->type == WINSYS_HANDLE_TYPE_FD) {
195       int fd = panfrost_bo_export(rsrc->bo);
196 
197       if (fd < 0)
198          return false;
199 
200       handle->handle = fd;
201    } else {
202       /* Other handle types not supported */
203       return false;
204    }
205 
206    handle->stride = panfrost_get_legacy_stride(&rsrc->image.layout, 0);
207    handle->offset = rsrc->image.layout.slices[0].offset;
208    return true;
209 }
210 
211 static bool
panfrost_resource_get_param(struct pipe_screen * pscreen,struct pipe_context * pctx,struct pipe_resource * prsc,unsigned plane,unsigned layer,unsigned level,enum pipe_resource_param param,unsigned usage,uint64_t * value)212 panfrost_resource_get_param(struct pipe_screen *pscreen,
213                             struct pipe_context *pctx,
214                             struct pipe_resource *prsc, unsigned plane,
215                             unsigned layer, unsigned level,
216                             enum pipe_resource_param param, unsigned usage,
217                             uint64_t *value)
218 {
219    struct pipe_resource *plane_res = util_resource_at_index(prsc, plane);
220    struct panfrost_resource *rsrc = pan_resource(plane_res);
221 
222    switch (param) {
223    case PIPE_RESOURCE_PARAM_STRIDE:
224       *value = panfrost_get_legacy_stride(&rsrc->image.layout, level);
225       return true;
226    case PIPE_RESOURCE_PARAM_OFFSET:
227       *value = rsrc->image.layout.slices[level].offset;
228       return true;
229    case PIPE_RESOURCE_PARAM_MODIFIER:
230       *value = rsrc->image.layout.modifier;
231       return true;
232    case PIPE_RESOURCE_PARAM_NPLANES:
233       *value = util_resource_num(prsc);
234       return true;
235    default:
236       return false;
237    }
238 }
239 
240 static void
panfrost_flush_resource(struct pipe_context * pctx,struct pipe_resource * prsc)241 panfrost_flush_resource(struct pipe_context *pctx, struct pipe_resource *prsc)
242 {
243    /* TODO */
244 }
245 
246 static struct pipe_surface *
panfrost_create_surface(struct pipe_context * pipe,struct pipe_resource * pt,const struct pipe_surface * surf_tmpl)247 panfrost_create_surface(struct pipe_context *pipe, struct pipe_resource *pt,
248                         const struct pipe_surface *surf_tmpl)
249 {
250    struct pipe_surface *ps = NULL;
251 
252    ps = CALLOC_STRUCT(pipe_surface);
253 
254    if (ps) {
255       pipe_reference_init(&ps->reference, 1);
256       pipe_resource_reference(&ps->texture, pt);
257       ps->context = pipe;
258       ps->format = surf_tmpl->format;
259 
260       if (pt->target != PIPE_BUFFER) {
261          assert(surf_tmpl->u.tex.level <= pt->last_level);
262          ps->width = u_minify(pt->width0, surf_tmpl->u.tex.level);
263          ps->height = u_minify(pt->height0, surf_tmpl->u.tex.level);
264          ps->nr_samples = surf_tmpl->nr_samples;
265          ps->u.tex.level = surf_tmpl->u.tex.level;
266          ps->u.tex.first_layer = surf_tmpl->u.tex.first_layer;
267          ps->u.tex.last_layer = surf_tmpl->u.tex.last_layer;
268       } else {
269          /* setting width as number of elements should get us correct
270           * renderbuffer width */
271          ps->width =
272             surf_tmpl->u.buf.last_element - surf_tmpl->u.buf.first_element + 1;
273          ps->height = pt->height0;
274          ps->u.buf.first_element = surf_tmpl->u.buf.first_element;
275          ps->u.buf.last_element = surf_tmpl->u.buf.last_element;
276          assert(ps->u.buf.first_element <= ps->u.buf.last_element);
277          assert(ps->u.buf.last_element < ps->width);
278       }
279    }
280 
281    return ps;
282 }
283 
284 static void
panfrost_surface_destroy(struct pipe_context * pipe,struct pipe_surface * surf)285 panfrost_surface_destroy(struct pipe_context *pipe, struct pipe_surface *surf)
286 {
287    assert(surf->texture);
288    pipe_resource_reference(&surf->texture, NULL);
289    free(surf);
290 }
291 
292 static inline bool
panfrost_is_2d(const struct panfrost_resource * pres)293 panfrost_is_2d(const struct panfrost_resource *pres)
294 {
295    return (pres->base.target == PIPE_TEXTURE_2D) ||
296           (pres->base.target == PIPE_TEXTURE_RECT);
297 }
298 
299 /* Based on the usage, determine if it makes sense to use u-inteleaved tiling.
300  * We only have routines to tile 2D textures of sane bpps. On the hardware
301  * level, not all usages are valid for tiling. Finally, if the app is hinting
302  * that the contents frequently change, tiling will be a loss.
303  *
304  * On platforms where it is supported, AFBC is even better. */
305 
306 static bool
panfrost_should_afbc(struct panfrost_device * dev,const struct panfrost_resource * pres,enum pipe_format fmt)307 panfrost_should_afbc(struct panfrost_device *dev,
308                      const struct panfrost_resource *pres, enum pipe_format fmt)
309 {
310    /* AFBC resources may be rendered to, textured from, or shared across
311     * processes, but may not be used as e.g buffers */
312    const unsigned valid_binding =
313       PIPE_BIND_DEPTH_STENCIL | PIPE_BIND_RENDER_TARGET | PIPE_BIND_BLENDABLE |
314       PIPE_BIND_SAMPLER_VIEW | PIPE_BIND_DISPLAY_TARGET | PIPE_BIND_SCANOUT |
315       PIPE_BIND_SHARED;
316 
317    if (pres->base.bind & ~valid_binding)
318       return false;
319 
320    /* AFBC support is optional */
321    if (!dev->has_afbc)
322       return false;
323 
324    /* AFBC<-->staging is expensive */
325    if (pres->base.usage == PIPE_USAGE_STREAM)
326       return false;
327 
328    /* If constant (non-data-dependent) format is requested, don't AFBC: */
329    if (pres->base.bind & PIPE_BIND_CONST_BW)
330       return false;
331 
332    /* Only a small selection of formats are AFBC'able */
333    if (!panfrost_format_supports_afbc(dev->arch, fmt))
334       return false;
335 
336    /* AFBC does not support layered (GLES3 style) multisampling. Use
337     * EXT_multisampled_render_to_texture instead */
338    if (pres->base.nr_samples > 1)
339       return false;
340 
341    switch (pres->base.target) {
342    case PIPE_TEXTURE_2D:
343    case PIPE_TEXTURE_RECT:
344    case PIPE_TEXTURE_2D_ARRAY:
345    case PIPE_TEXTURE_CUBE:
346    case PIPE_TEXTURE_CUBE_ARRAY:
347       break;
348 
349    case PIPE_TEXTURE_3D:
350       /* 3D AFBC is only supported on Bifrost v7+. It's supposed to
351        * be supported on Midgard but it doesn't seem to work */
352       if (dev->arch != 7)
353          return false;
354 
355       break;
356 
357    default:
358       return false;
359    }
360 
361    /* For one tile, AFBC is a loss compared to u-interleaved */
362    if (pres->base.width0 <= 16 && pres->base.height0 <= 16)
363       return false;
364 
365    /* Otherwise, we'd prefer AFBC as it is dramatically more efficient
366     * than linear or usually even u-interleaved */
367    return true;
368 }
369 
370 /*
371  * For a resource we want to use AFBC with, should we use AFBC with tiled
372  * headers? On GPUs that support it, this is believed to be beneficial for
373  * images that are at least 128x128.
374  */
375 static bool
panfrost_should_tile_afbc(const struct panfrost_device * dev,const struct panfrost_resource * pres)376 panfrost_should_tile_afbc(const struct panfrost_device *dev,
377                           const struct panfrost_resource *pres)
378 {
379    return panfrost_afbc_can_tile(dev->arch) && pres->base.width0 >= 128 &&
380           pres->base.height0 >= 128 && !(dev->debug & PAN_DBG_FORCE_PACK);
381 }
382 
383 bool
panfrost_should_pack_afbc(struct panfrost_device * dev,const struct panfrost_resource * prsrc)384 panfrost_should_pack_afbc(struct panfrost_device *dev,
385                           const struct panfrost_resource *prsrc)
386 {
387    const unsigned valid_binding = PIPE_BIND_DEPTH_STENCIL |
388                                   PIPE_BIND_RENDER_TARGET |
389                                   PIPE_BIND_SAMPLER_VIEW;
390 
391    return panfrost_afbc_can_pack(prsrc->base.format) && panfrost_is_2d(prsrc) &&
392           drm_is_afbc(prsrc->image.layout.modifier) &&
393           (prsrc->image.layout.modifier & AFBC_FORMAT_MOD_SPARSE) &&
394           !(prsrc->image.layout.modifier & AFBC_FORMAT_MOD_SPLIT) &&
395           (prsrc->base.bind & ~valid_binding) == 0 &&
396           !prsrc->modifier_constant && prsrc->base.array_size == 1 &&
397           prsrc->base.width0 >= 32 && prsrc->base.height0 >= 32 ;
398 }
399 
400 static bool
panfrost_should_tile(struct panfrost_device * dev,const struct panfrost_resource * pres,enum pipe_format fmt)401 panfrost_should_tile(struct panfrost_device *dev,
402                      const struct panfrost_resource *pres, enum pipe_format fmt)
403 {
404    const unsigned valid_binding =
405       PIPE_BIND_DEPTH_STENCIL | PIPE_BIND_RENDER_TARGET | PIPE_BIND_BLENDABLE |
406       PIPE_BIND_SAMPLER_VIEW | PIPE_BIND_DISPLAY_TARGET | PIPE_BIND_SCANOUT |
407       PIPE_BIND_SHARED;
408 
409    /* The purpose of tiling is improving locality in both X- and
410     * Y-directions. If there is only a single pixel in either direction,
411     * tiling does not make sense; using a linear layout instead is optimal
412     * for both memory usage and performance.
413     */
414    if (MIN2(pres->base.width0, pres->base.height0) < 2)
415       return false;
416 
417    bool can_tile = (pres->base.target != PIPE_BUFFER) &&
418                    ((pres->base.bind & ~valid_binding) == 0);
419 
420    return can_tile && (pres->base.usage != PIPE_USAGE_STREAM);
421 }
422 
423 static bool
panfrost_should_afrc(struct panfrost_device * dev,const struct panfrost_resource * pres,enum pipe_format fmt)424 panfrost_should_afrc(struct panfrost_device *dev,
425                      const struct panfrost_resource *pres, enum pipe_format fmt)
426 {
427    const unsigned valid_binding = PIPE_BIND_RENDER_TARGET |
428                                   PIPE_BIND_BLENDABLE | PIPE_BIND_SAMPLER_VIEW |
429                                   PIPE_BIND_DISPLAY_TARGET | PIPE_BIND_SHARED;
430 
431    if (pres->base.bind & ~valid_binding)
432       return false;
433 
434    /* AFRC support is optional */
435    if (!dev->has_afrc)
436       return false;
437 
438    /* AFRC<-->staging is expensive */
439    if (pres->base.usage == PIPE_USAGE_STREAM)
440       return false;
441 
442    /* Only a small selection of formats are AFRC'able */
443    if (!panfrost_format_supports_afrc(fmt))
444       return false;
445 
446    /* AFRC does not support layered (GLES3 style) multisampling. Use
447     * EXT_multisampled_render_to_texture instead */
448    if (pres->base.nr_samples > 1)
449       return false;
450 
451    switch (pres->base.target) {
452    case PIPE_TEXTURE_2D:
453    case PIPE_TEXTURE_RECT:
454    case PIPE_TEXTURE_2D_ARRAY:
455    case PIPE_TEXTURE_CUBE:
456    case PIPE_TEXTURE_CUBE_ARRAY:
457    case PIPE_TEXTURE_3D:
458       break;
459 
460    default:
461       return false;
462    }
463 
464    return true;
465 }
466 
467 static uint64_t
panfrost_best_modifier(struct pipe_screen * pscreen,const struct panfrost_resource * pres,enum pipe_format fmt)468 panfrost_best_modifier(struct pipe_screen *pscreen,
469                        const struct panfrost_resource *pres,
470                        enum pipe_format fmt)
471 {
472    struct panfrost_screen *screen = pan_screen(pscreen);
473    struct panfrost_device *dev = pan_device(pscreen);
474 
475    /* Force linear textures when debugging tiling/compression */
476    if (unlikely(dev->debug & PAN_DBG_LINEAR))
477       return DRM_FORMAT_MOD_LINEAR;
478 
479    int afrc_rate = screen->force_afrc_rate;
480    if (afrc_rate < 0)
481       afrc_rate = pres->base.compression_rate;
482    if (afrc_rate > PIPE_COMPRESSION_FIXED_RATE_NONE &&
483        panfrost_should_afrc(dev, pres, fmt)) {
484       /* It's not really possible to decide on a global AFRC-rate,
485        * because the set of valid AFRC rates varies from format to
486        * format. So instead, treat this as a minimum rate, and search
487        * for the next valid one.
488        */
489       for (int i = afrc_rate; i < 12; ++i) {
490          if (panfrost_afrc_get_modifiers(fmt, i, 0, NULL)) {
491             afrc_rate = i;
492             break;
493          }
494       }
495    }
496 
497    if (afrc_rate != PIPE_COMPRESSION_FIXED_RATE_NONE &&
498        panfrost_should_afrc(dev, pres, fmt)) {
499       uint64_t mod;
500       unsigned num_mods = 0;
501 
502       STATIC_ASSERT(PIPE_COMPRESSION_FIXED_RATE_DEFAULT == PAN_AFRC_RATE_DEFAULT);
503       num_mods = panfrost_afrc_get_modifiers(fmt, afrc_rate, 1, &mod);
504       if (num_mods > 0) {
505          return mod;
506       }
507    }
508 
509    if (panfrost_should_afbc(dev, pres, fmt)) {
510       uint64_t afbc = AFBC_FORMAT_MOD_BLOCK_SIZE_16x16 | AFBC_FORMAT_MOD_SPARSE;
511 
512       if (panfrost_afbc_can_ytr(pres->base.format))
513          afbc |= AFBC_FORMAT_MOD_YTR;
514 
515       if (panfrost_should_tile_afbc(dev, pres))
516          afbc |= AFBC_FORMAT_MOD_TILED | AFBC_FORMAT_MOD_SC;
517 
518       return DRM_FORMAT_MOD_ARM_AFBC(afbc);
519    } else if (panfrost_should_tile(dev, pres, fmt))
520       return DRM_FORMAT_MOD_ARM_16X16_BLOCK_U_INTERLEAVED;
521    else
522       return DRM_FORMAT_MOD_LINEAR;
523 }
524 
525 static bool
panfrost_should_checksum(const struct panfrost_device * dev,const struct panfrost_resource * pres)526 panfrost_should_checksum(const struct panfrost_device *dev,
527                          const struct panfrost_resource *pres)
528 {
529    /* When checksumming is enabled, the tile data must fit in the
530     * size of the writeback buffer, so don't checksum formats
531     * that use too much space. */
532 
533    unsigned bytes_per_pixel_max = (dev->arch == 6) ? 6 : 4;
534 
535    unsigned bytes_per_pixel = MAX2(pres->base.nr_samples, 1) *
536                               util_format_get_blocksize(pres->base.format);
537 
538    return pres->base.bind & PIPE_BIND_RENDER_TARGET && panfrost_is_2d(pres) &&
539           bytes_per_pixel <= bytes_per_pixel_max &&
540           pres->base.last_level == 0 && !(dev->debug & PAN_DBG_NO_CRC);
541 }
542 
543 static void
panfrost_resource_setup(struct pipe_screen * screen,struct panfrost_resource * pres,uint64_t modifier,enum pipe_format fmt)544 panfrost_resource_setup(struct pipe_screen *screen,
545                         struct panfrost_resource *pres, uint64_t modifier,
546                         enum pipe_format fmt)
547 {
548    struct panfrost_device *dev = pan_device(screen);
549    uint64_t chosen_mod = modifier != DRM_FORMAT_MOD_INVALID
550                             ? modifier
551                             : panfrost_best_modifier(screen, pres, fmt);
552    enum mali_texture_dimension dim =
553       panfrost_translate_texture_dimension(pres->base.target);
554 
555    /* We can only switch tiled->linear if the resource isn't already
556     * linear and if we control the modifier */
557    pres->modifier_constant = !(chosen_mod != DRM_FORMAT_MOD_LINEAR &&
558                                modifier == DRM_FORMAT_MOD_INVALID);
559 
560    /* Z32_S8X24 variants are actually stored in 2 planes (one per
561     * component), we have to adjust the format on the first plane.
562     */
563    if (fmt == PIPE_FORMAT_Z32_FLOAT_S8X24_UINT)
564       fmt = PIPE_FORMAT_Z32_FLOAT;
565 
566    pres->image.layout = (struct pan_image_layout){
567       .modifier = chosen_mod,
568       .format = fmt,
569       .dim = dim,
570       .width = pres->base.width0,
571       .height = pres->base.height0,
572       .depth = pres->base.depth0,
573       .array_size = pres->base.array_size,
574       .nr_samples = MAX2(pres->base.nr_samples, 1),
575       .nr_slices = pres->base.last_level + 1,
576       .crc = panfrost_should_checksum(dev, pres),
577    };
578 
579    /* Update the compression rate with the correct value as we
580     * want the real bitrate and not DEFAULT */
581    pres->base.compression_rate = panfrost_afrc_get_rate(fmt, chosen_mod);
582 
583    ASSERTED bool valid =
584       pan_image_layout_init(dev->arch, &pres->image.layout, NULL);
585    assert(valid);
586 }
587 
588 static int
panfrost_resource_init_afbc_headers(struct panfrost_resource * pres)589 panfrost_resource_init_afbc_headers(struct panfrost_resource *pres)
590 {
591    if (panfrost_bo_mmap(pres->bo))
592       return -1;
593 
594    unsigned nr_samples = MAX2(pres->base.nr_samples, 1);
595 
596    for (unsigned i = 0; i < pres->base.array_size; ++i) {
597       for (unsigned l = 0; l <= pres->base.last_level; ++l) {
598          struct pan_image_slice_layout *slice = &pres->image.layout.slices[l];
599 
600          for (unsigned s = 0; s < nr_samples; ++s) {
601             void *ptr = pres->bo->ptr.cpu +
602                         (i * pres->image.layout.array_stride) + slice->offset +
603                         (s * slice->afbc.surface_stride);
604 
605             /* Zero-ed AFBC headers seem to encode a plain
606              * black. Let's use this pattern to keep the
607              * initialization simple.
608              */
609             memset(ptr, 0, slice->afbc.header_size);
610          }
611       }
612    }
613    return 0;
614 }
615 
616 void
panfrost_resource_set_damage_region(struct pipe_screen * screen,struct pipe_resource * res,unsigned int nrects,const struct pipe_box * rects)617 panfrost_resource_set_damage_region(struct pipe_screen *screen,
618                                     struct pipe_resource *res,
619                                     unsigned int nrects,
620                                     const struct pipe_box *rects)
621 {
622    struct panfrost_device *dev = pan_device(screen);
623    struct panfrost_resource *pres = pan_resource(res);
624    struct pipe_scissor_state *damage_extent = &pres->damage.extent;
625    unsigned int i;
626 
627    /* Partial updates are implemented with a tile enable map only on v5.
628     * Later architectures have a more efficient method of implementing
629     * partial updates (frame shaders), while earlier architectures lack
630     * tile enable maps altogether.
631     */
632    if (dev->arch == 5 && nrects > 1) {
633       if (!pres->damage.tile_map.data) {
634          pres->damage.tile_map.stride =
635             ALIGN_POT(DIV_ROUND_UP(res->width0, 32 * 8), 64);
636          pres->damage.tile_map.size =
637             pres->damage.tile_map.stride * DIV_ROUND_UP(res->height0, 32);
638          pres->damage.tile_map.data = malloc(pres->damage.tile_map.size);
639       }
640 
641       memset(pres->damage.tile_map.data, 0, pres->damage.tile_map.size);
642       pres->damage.tile_map.enable = true;
643    } else {
644       pres->damage.tile_map.enable = false;
645    }
646 
647    /* Track the damage extent: the quad including all damage regions. Will
648     * be used restrict the rendering area */
649 
650    damage_extent->minx = 0xffff;
651    damage_extent->miny = 0xffff;
652 
653    unsigned enable_count = 0;
654 
655    for (i = 0; i < nrects; i++) {
656       int x = rects[i].x, w = rects[i].width, h = rects[i].height;
657       int y = res->height0 - (rects[i].y + h);
658 
659       damage_extent->minx = MIN2(damage_extent->minx, x);
660       damage_extent->miny = MIN2(damage_extent->miny, y);
661       damage_extent->maxx = MAX2(damage_extent->maxx, MIN2(x + w, res->width0));
662       damage_extent->maxy =
663          MAX2(damage_extent->maxy, MIN2(y + h, res->height0));
664 
665       if (!pres->damage.tile_map.enable)
666          continue;
667 
668       unsigned t_x_start = x / 32;
669       unsigned t_x_end = (x + w - 1) / 32;
670       unsigned t_y_start = y / 32;
671       unsigned t_y_end = (y + h - 1) / 32;
672 
673       for (unsigned t_y = t_y_start; t_y <= t_y_end; t_y++) {
674          for (unsigned t_x = t_x_start; t_x <= t_x_end; t_x++) {
675             unsigned b = (t_y * pres->damage.tile_map.stride * 8) + t_x;
676 
677             if (BITSET_TEST(pres->damage.tile_map.data, b))
678                continue;
679 
680             BITSET_SET(pres->damage.tile_map.data, b);
681             enable_count++;
682          }
683       }
684    }
685 
686    if (nrects == 0) {
687       damage_extent->minx = 0;
688       damage_extent->miny = 0;
689       damage_extent->maxx = res->width0;
690       damage_extent->maxy = res->height0;
691    }
692 
693    if (pres->damage.tile_map.enable) {
694       unsigned t_x_start = damage_extent->minx / 32;
695       unsigned t_x_end = damage_extent->maxx / 32;
696       unsigned t_y_start = damage_extent->miny / 32;
697       unsigned t_y_end = damage_extent->maxy / 32;
698       unsigned tile_count =
699          (t_x_end - t_x_start + 1) * (t_y_end - t_y_start + 1);
700 
701       /* Don't bother passing a tile-enable-map if the amount of
702        * tiles to reload is to close to the total number of tiles.
703        */
704       if (tile_count - enable_count < 10)
705          pres->damage.tile_map.enable = false;
706    }
707 }
708 
709 static bool
panfrost_can_create_resource(struct pipe_screen * screen,const struct pipe_resource * template)710 panfrost_can_create_resource(struct pipe_screen *screen,
711                              const struct pipe_resource *template)
712 {
713    struct panfrost_resource tmp;
714    tmp.base = *template;
715 
716    panfrost_resource_setup(screen, &tmp, DRM_FORMAT_MOD_INVALID, template->format);
717 
718    uint64_t system_memory;
719    if (!os_get_total_physical_memory(&system_memory))
720       return false;
721 
722    /* Limit maximum texture size to a quarter of the system memory, to avoid
723     * allocating huge textures on systems with little memory.
724     */
725    return tmp.image.layout.data_size <= system_memory / 4;
726 }
727 
728 struct pipe_resource *
panfrost_resource_create_with_modifier(struct pipe_screen * screen,const struct pipe_resource * template,uint64_t modifier)729 panfrost_resource_create_with_modifier(struct pipe_screen *screen,
730                                        const struct pipe_resource *template,
731                                        uint64_t modifier)
732 {
733    struct panfrost_device *dev = pan_device(screen);
734 
735    struct panfrost_resource *so = CALLOC_STRUCT(panfrost_resource);
736 
737    if (!so)
738       return NULL;
739 
740    so->base = *template;
741    so->base.screen = screen;
742 
743    pipe_reference_init(&so->base.reference, 1);
744 
745    util_range_init(&so->valid_buffer_range);
746 
747    if (template->bind & PAN_BIND_SHARED_MASK) {
748       /* For compatibility with older consumers that may not be
749        * modifiers aware, treat INVALID as LINEAR for shared
750        * resources.
751        */
752       if (modifier == DRM_FORMAT_MOD_INVALID)
753          modifier = DRM_FORMAT_MOD_LINEAR;
754 
755       /* At any rate, we can't change the modifier later for shared
756        * resources, since we have no way to propagate the modifier
757        * change.
758        */
759       so->modifier_constant = true;
760    }
761 
762    panfrost_resource_setup(screen, so, modifier, template->format);
763 
764    /* Guess a label based on the bind */
765    unsigned bind = template->bind;
766    const char *label = (bind & PIPE_BIND_INDEX_BUFFER)     ? "Index buffer"
767                        : (bind & PIPE_BIND_SCANOUT)        ? "Scanout"
768                        : (bind & PIPE_BIND_DISPLAY_TARGET) ? "Display target"
769                        : (bind & PIPE_BIND_SHARED)         ? "Shared resource"
770                        : (bind & PIPE_BIND_RENDER_TARGET)  ? "Render target"
771                        : (bind & PIPE_BIND_DEPTH_STENCIL)
772                           ? "Depth/stencil buffer"
773                        : (bind & PIPE_BIND_SAMPLER_VIEW)    ? "Texture"
774                        : (bind & PIPE_BIND_VERTEX_BUFFER)   ? "Vertex buffer"
775                        : (bind & PIPE_BIND_CONSTANT_BUFFER) ? "Constant buffer"
776                        : (bind & PIPE_BIND_GLOBAL)          ? "Global memory"
777                        : (bind & PIPE_BIND_SHADER_BUFFER)   ? "Shader buffer"
778                        : (bind & PIPE_BIND_SHADER_IMAGE)    ? "Shader image"
779                                                             : "Other resource";
780 
781    if (dev->ro && (template->bind & PIPE_BIND_SCANOUT)) {
782       struct winsys_handle handle;
783       struct pan_block_size blocksize =
784          panfrost_renderblock_size(modifier, template->format);
785 
786       /* Block-based texture formats are only used for texture
787        * compression (not framebuffer compression!), which doesn't
788        * make sense to share across processes.
789        */
790       assert(util_format_get_blockwidth(template->format) == 1);
791       assert(util_format_get_blockheight(template->format) == 1);
792 
793       /* Present a resource with similar dimensions that, if allocated
794        * as a linear image, is big enough to fit the resource in the
795        * actual layout. For linear images, this is a no-op. For 16x16
796        * tiling, this aligns the dimensions to 16x16.
797        *
798        * For AFBC, this aligns the width to the superblock width (as
799        * expected) and adds extra rows to account for the header. This
800        * is a bit of a lie, but it's the best we can do with dumb
801        * buffers, which are extremely not meant for AFBC. And yet this
802        * has to work anyway...
803        *
804        * Moral of the story: if you're reading this comment, that
805        * means you're working on WSI and so it's already too late for
806        * you. I'm sorry.
807        */
808       unsigned width = ALIGN_POT(template->width0, blocksize.width);
809       unsigned stride = ALIGN_POT(template->width0, blocksize.width) *
810                         util_format_get_blocksize(template->format);
811       unsigned size = so->image.layout.data_size;
812       unsigned effective_rows = DIV_ROUND_UP(size, stride);
813 
814       struct pipe_resource scanout_tmpl = {
815          .target = so->base.target,
816          .format = template->format,
817          .width0 = width,
818          .height0 = effective_rows,
819          .depth0 = 1,
820          .array_size = 1,
821       };
822 
823       so->scanout =
824          renderonly_scanout_for_resource(&scanout_tmpl, dev->ro, &handle);
825 
826       if (!so->scanout) {
827          mesa_loge("Failed to create scanout resource\n");
828          FREE(so);
829          return NULL;
830       }
831       assert(handle.type == WINSYS_HANDLE_TYPE_FD);
832       so->bo = panfrost_bo_import(dev, handle.handle);
833       close(handle.handle);
834 
835       if (!so->bo) {
836          FREE(so);
837          return NULL;
838       }
839 
840       so->image.data.base = so->bo->ptr.gpu;
841    } else {
842       /* We create a BO immediately but don't bother mapping, since we don't
843        * care to map e.g. FBOs which the CPU probably won't touch */
844       uint32_t flags = PAN_BO_DELAY_MMAP;
845 
846       /* If the resource is never exported, we can make the BO private. */
847       if (template->bind & PIPE_BIND_SHARED)
848          flags |= PAN_BO_SHAREABLE;
849 
850       so->bo =
851          panfrost_bo_create(dev, so->image.layout.data_size, flags, label);
852 
853       if (!so->bo) {
854          FREE(so);
855          return NULL;
856       }
857 
858       so->image.data.base = so->bo->ptr.gpu;
859 
860       so->constant_stencil = true;
861    }
862 
863    if (drm_is_afbc(so->image.layout.modifier)) {
864       if (panfrost_resource_init_afbc_headers(so)) {
865          FREE(so);
866          return NULL;
867       }
868    }
869 
870    panfrost_resource_set_damage_region(screen, &so->base, 0, NULL);
871 
872    if (template->bind & PIPE_BIND_INDEX_BUFFER)
873       so->index_cache = CALLOC_STRUCT(panfrost_minmax_cache);
874 
875    return (struct pipe_resource *)so;
876 }
877 
878 /* Default is to create a resource as don't care */
879 
880 static struct pipe_resource *
panfrost_resource_create(struct pipe_screen * screen,const struct pipe_resource * template)881 panfrost_resource_create(struct pipe_screen *screen,
882                          const struct pipe_resource *template)
883 {
884    return panfrost_resource_create_with_modifier(screen, template,
885                                                  DRM_FORMAT_MOD_INVALID);
886 }
887 
888 /* If no modifier is specified, we'll choose. Otherwise, the order of
889  * preference is compressed, tiled, linear. */
890 
891 static struct pipe_resource *
panfrost_resource_create_with_modifiers(struct pipe_screen * screen,const struct pipe_resource * template,const uint64_t * modifiers,int count)892 panfrost_resource_create_with_modifiers(struct pipe_screen *screen,
893                                         const struct pipe_resource *template,
894                                         const uint64_t *modifiers, int count)
895 {
896    for (unsigned i = 0; i < PAN_MODIFIER_COUNT; ++i) {
897       if (drm_find_modifier(pan_best_modifiers[i], modifiers, count)) {
898          return panfrost_resource_create_with_modifier(screen, template,
899                                                        pan_best_modifiers[i]);
900       }
901    }
902 
903    /* If we didn't find one, app specified invalid */
904    assert(count == 1 && modifiers[0] == DRM_FORMAT_MOD_INVALID);
905    return panfrost_resource_create(screen, template);
906 }
907 
908 static void
panfrost_resource_destroy(struct pipe_screen * screen,struct pipe_resource * pt)909 panfrost_resource_destroy(struct pipe_screen *screen, struct pipe_resource *pt)
910 {
911    struct panfrost_device *dev = pan_device(screen);
912    struct panfrost_resource *rsrc = (struct panfrost_resource *)pt;
913 
914    if (rsrc->scanout)
915       renderonly_scanout_destroy(rsrc->scanout, dev->ro);
916 
917    if (rsrc->shadow_image)
918          pipe_resource_reference(
919             (struct pipe_resource **)&rsrc->shadow_image, NULL);
920 
921    if (rsrc->bo)
922       panfrost_bo_unreference(rsrc->bo);
923 
924    free(rsrc->index_cache);
925    free(rsrc->damage.tile_map.data);
926 
927    util_range_destroy(&rsrc->valid_buffer_range);
928    free(rsrc);
929 }
930 
931 /* Most of the time we can do CPU-side transfers, but sometimes we need to use
932  * the 3D pipe for this. Let's wrap u_blitter to blit to/from staging textures.
933  * Code adapted from freedreno */
934 
935 static struct panfrost_resource *
pan_alloc_staging(struct panfrost_context * ctx,struct panfrost_resource * rsc,unsigned level,const struct pipe_box * box)936 pan_alloc_staging(struct panfrost_context *ctx, struct panfrost_resource *rsc,
937                   unsigned level, const struct pipe_box *box)
938 {
939    struct pipe_context *pctx = &ctx->base;
940    struct pipe_resource tmpl = rsc->base;
941 
942    tmpl.width0 = box->width;
943    tmpl.height0 = box->height;
944    /* for array textures, box->depth is the array_size, otherwise
945     * for 3d textures, it is the depth:
946     */
947    if (tmpl.array_size > 1) {
948       if (tmpl.target == PIPE_TEXTURE_CUBE)
949          tmpl.target = PIPE_TEXTURE_2D_ARRAY;
950       tmpl.array_size = box->depth;
951       tmpl.depth0 = 1;
952    } else {
953       tmpl.array_size = 1;
954       tmpl.depth0 = box->depth;
955    }
956    tmpl.last_level = 0;
957    tmpl.bind |= PIPE_BIND_LINEAR;
958    tmpl.bind &= ~PAN_BIND_SHARED_MASK;
959    tmpl.compression_rate = PIPE_COMPRESSION_FIXED_RATE_NONE;
960 
961    struct pipe_resource *pstaging =
962       pctx->screen->resource_create(pctx->screen, &tmpl);
963    if (!pstaging)
964       return NULL;
965 
966    return pan_resource(pstaging);
967 }
968 
969 static void
pan_blit_from_staging(struct pipe_context * pctx,struct panfrost_transfer * trans)970 pan_blit_from_staging(struct pipe_context *pctx,
971                       struct panfrost_transfer *trans)
972 {
973    struct pipe_resource *dst = trans->base.resource;
974    struct pipe_blit_info blit = {0};
975 
976    blit.dst.resource = dst;
977    blit.dst.format = dst->format;
978    blit.dst.level = trans->base.level;
979    blit.dst.box = trans->base.box;
980    blit.src.resource = trans->staging.rsrc;
981    blit.src.format = trans->staging.rsrc->format;
982    blit.src.level = 0;
983    blit.src.box = trans->staging.box;
984    blit.mask = util_format_get_mask(blit.src.format);
985    blit.filter = PIPE_TEX_FILTER_NEAREST;
986 
987    panfrost_blit_no_afbc_legalization(pctx, &blit);
988 }
989 
990 static void
pan_blit_to_staging(struct pipe_context * pctx,struct panfrost_transfer * trans)991 pan_blit_to_staging(struct pipe_context *pctx, struct panfrost_transfer *trans)
992 {
993    struct pipe_resource *src = trans->base.resource;
994    struct pipe_blit_info blit = {0};
995 
996    blit.src.resource = src;
997    blit.src.format = src->format;
998    blit.src.level = trans->base.level;
999    blit.src.box = trans->base.box;
1000    blit.dst.resource = trans->staging.rsrc;
1001    blit.dst.format = trans->staging.rsrc->format;
1002    blit.dst.level = 0;
1003    blit.dst.box = trans->staging.box;
1004    blit.mask = util_format_get_mask(blit.dst.format);
1005    blit.filter = PIPE_TEX_FILTER_NEAREST;
1006 
1007    panfrost_blit_no_afbc_legalization(pctx, &blit);
1008 }
1009 
1010 static void
panfrost_load_tiled_images(struct panfrost_transfer * transfer,struct panfrost_resource * rsrc)1011 panfrost_load_tiled_images(struct panfrost_transfer *transfer,
1012                            struct panfrost_resource *rsrc)
1013 {
1014    struct pipe_transfer *ptrans = &transfer->base;
1015    unsigned level = ptrans->level;
1016 
1017    /* If the requested level of the image is uninitialized, it's not
1018     * necessary to copy it. Leave the result unintiialized too.
1019     */
1020    if (!BITSET_TEST(rsrc->valid.data, level))
1021       return;
1022 
1023    struct panfrost_bo *bo = rsrc->bo;
1024    unsigned stride = panfrost_get_layer_stride(&rsrc->image.layout, level);
1025 
1026    /* Otherwise, load each layer separately, required to load from 3D and
1027     * array textures.
1028     */
1029    for (unsigned z = 0; z < ptrans->box.depth; ++z) {
1030       void *dst = transfer->map + (ptrans->layer_stride * z);
1031       uint8_t *map = bo->ptr.cpu + rsrc->image.layout.slices[level].offset +
1032                      (z + ptrans->box.z) * stride;
1033 
1034       panfrost_load_tiled_image(dst, map, ptrans->box.x, ptrans->box.y,
1035                                 ptrans->box.width, ptrans->box.height,
1036                                 ptrans->stride,
1037                                 rsrc->image.layout.slices[level].row_stride,
1038                                 rsrc->image.layout.format);
1039    }
1040 }
1041 
1042 #if MESA_DEBUG
1043 
1044 static unsigned
get_superblock_size(uint32_t * hdr,unsigned uncompressed_size)1045 get_superblock_size(uint32_t *hdr, unsigned uncompressed_size)
1046 {
1047    /* AFBC superblock layout 0 */
1048    unsigned body_base_ptr_len = 32;
1049    unsigned nr_subblocks = 16;
1050    unsigned sz_len = 6; /* bits */
1051    unsigned mask = (1 << sz_len) - 1;
1052    unsigned size = 0;
1053 
1054    /* Sum up all of the subblock sizes */
1055    for (int i = 0; i < nr_subblocks; i++) {
1056       unsigned bitoffset = body_base_ptr_len + (i * sz_len);
1057       unsigned start = bitoffset / 32;
1058       unsigned end = (bitoffset + (sz_len - 1)) / 32;
1059       unsigned offset = bitoffset % 32;
1060       unsigned subblock_size;
1061 
1062       if (start != end)
1063          subblock_size = (hdr[start] >> offset) | (hdr[end] << (32 - offset));
1064       else
1065          subblock_size = hdr[start] >> offset;
1066       subblock_size = (subblock_size == 1) ? uncompressed_size : subblock_size;
1067       size += subblock_size & mask;
1068 
1069       if (i == 0 && size == 0)
1070          return 0;
1071    }
1072 
1073    return size;
1074 }
1075 
1076 static void
dump_block(struct panfrost_resource * rsrc,uint32_t idx)1077 dump_block(struct panfrost_resource *rsrc, uint32_t idx)
1078 {
1079    panfrost_bo_wait(rsrc->bo, INT64_MAX, false);
1080 
1081    uint8_t *ptr = rsrc->bo->ptr.cpu;
1082    uint32_t *header = (uint32_t *)(ptr + (idx * AFBC_HEADER_BYTES_PER_TILE));
1083    uint32_t body_base_ptr = header[0];
1084    uint32_t *body = (uint32_t *)(ptr + body_base_ptr);
1085    struct pan_block_size block_sz =
1086       panfrost_afbc_subblock_size(rsrc->image.layout.modifier);
1087    unsigned pixel_sz = util_format_get_blocksize(rsrc->base.format);
1088    unsigned uncompressed_size = pixel_sz * block_sz.width * block_sz.height;
1089    unsigned size = get_superblock_size(header, uncompressed_size);
1090 
1091    fprintf(stderr, "  Header: %08x %08x %08x %08x (size: %u bytes)\n",
1092            header[0], header[1], header[2], header[3], size);
1093    if (size > 0) {
1094       fprintf(stderr, "  Body:   %08x %08x %08x %08x\n", body[0], body[1],
1095               body[2], body[3]);
1096    } else {
1097       uint8_t *comp = (uint8_t *)(header + 2);
1098       fprintf(stderr, "  Color:  0x%02x%02x%02x%02x\n", comp[0], comp[1],
1099               comp[2], comp[3]);
1100    }
1101    fprintf(stderr, "\n");
1102 }
1103 
1104 void
pan_dump_resource(struct panfrost_context * ctx,struct panfrost_resource * rsc)1105 pan_dump_resource(struct panfrost_context *ctx, struct panfrost_resource *rsc)
1106 {
1107    struct pipe_context *pctx = &ctx->base;
1108    struct pipe_resource tmpl = rsc->base;
1109    struct pipe_resource *plinear = NULL;
1110    struct panfrost_resource *linear = rsc;
1111    struct pipe_blit_info blit = {0};
1112    struct pipe_box box;
1113    char buffer[1024];
1114 
1115    if (rsc->image.layout.modifier != DRM_FORMAT_MOD_LINEAR) {
1116       tmpl.bind |= PIPE_BIND_LINEAR;
1117       tmpl.bind &= ~PAN_BIND_SHARED_MASK;
1118 
1119       plinear = pctx->screen->resource_create(pctx->screen, &tmpl);
1120       u_box_2d(0, 0, rsc->base.width0, rsc->base.height0, &box);
1121 
1122       blit.src.resource = &rsc->base;
1123       blit.src.format = rsc->base.format;
1124       blit.src.level = 0;
1125       blit.src.box = box;
1126       blit.dst.resource = plinear;
1127       blit.dst.format = rsc->base.format;
1128       blit.dst.level = 0;
1129       blit.dst.box = box;
1130       blit.mask = util_format_get_mask(blit.dst.format);
1131       blit.filter = PIPE_TEX_FILTER_NEAREST;
1132 
1133       panfrost_blit(pctx, &blit);
1134 
1135       linear = pan_resource(plinear);
1136    }
1137 
1138    panfrost_flush_writer(ctx, linear, "dump image");
1139    panfrost_bo_wait(linear->bo, INT64_MAX, false);
1140 
1141    if (!panfrost_bo_mmap(linear->bo)) {
1142       static unsigned frame_count = 0;
1143       frame_count++;
1144       snprintf(buffer, sizeof(buffer), "dump_image.%04d", frame_count);
1145 
1146       debug_dump_image(buffer, rsc->base.format, 0 /* UNUSED */, rsc->base.width0,
1147                      rsc->base.height0,
1148                      linear->image.layout.slices[0].row_stride,
1149                      linear->bo->ptr.cpu);
1150    } else {
1151       mesa_loge("failed to mmap, not dumping resource");
1152    }
1153 
1154    if (plinear)
1155       pipe_resource_reference(&plinear, NULL);
1156 }
1157 
1158 #endif
1159 
1160 /* Get scan-order index from (x, y) position when blocks are
1161  * arranged in z-order in 8x8 tiles */
1162 static unsigned
get_morton_index(unsigned x,unsigned y,unsigned stride)1163 get_morton_index(unsigned x, unsigned y, unsigned stride)
1164 {
1165    unsigned i = ((x << 0) & 1) | ((y << 1) & 2) | ((x << 1) & 4) |
1166                 ((y << 2) & 8) | ((x << 2) & 16) | ((y << 3) & 32);
1167    return (((y & ~7) * stride) + ((x & ~7) << 3)) + i;
1168 }
1169 
1170 static void
panfrost_store_tiled_images(struct panfrost_transfer * transfer,struct panfrost_resource * rsrc)1171 panfrost_store_tiled_images(struct panfrost_transfer *transfer,
1172                             struct panfrost_resource *rsrc)
1173 {
1174    struct panfrost_bo *bo = rsrc->bo;
1175    struct pipe_transfer *ptrans = &transfer->base;
1176    unsigned level = ptrans->level;
1177    unsigned stride = panfrost_get_layer_stride(&rsrc->image.layout, level);
1178 
1179    /* Otherwise, store each layer separately, required to store to 3D and
1180     * array textures.
1181     */
1182    for (unsigned z = 0; z < ptrans->box.depth; ++z) {
1183       void *src = transfer->map + (ptrans->layer_stride * z);
1184       uint8_t *map = bo->ptr.cpu + rsrc->image.layout.slices[level].offset +
1185                      (z + ptrans->box.z) * stride;
1186 
1187       panfrost_store_tiled_image(map, src, ptrans->box.x, ptrans->box.y,
1188                                  ptrans->box.width, ptrans->box.height,
1189                                  rsrc->image.layout.slices[level].row_stride,
1190                                  ptrans->stride, rsrc->image.layout.format);
1191    }
1192 }
1193 
1194 static bool
panfrost_box_covers_resource(const struct pipe_resource * resource,const struct pipe_box * box)1195 panfrost_box_covers_resource(const struct pipe_resource *resource,
1196                              const struct pipe_box *box)
1197 {
1198    return resource->last_level == 0 &&
1199           util_texrange_covers_whole_level(resource, 0, box->x, box->y, box->z,
1200                                            box->width, box->height, box->depth);
1201 }
1202 
1203 static bool
panfrost_can_discard(struct pipe_resource * resource,const struct pipe_box * box,unsigned usage)1204 panfrost_can_discard(struct pipe_resource *resource, const struct pipe_box *box,
1205                      unsigned usage)
1206 {
1207    struct panfrost_resource *rsrc = pan_resource(resource);
1208 
1209    return ((usage & PIPE_MAP_DISCARD_RANGE) &&
1210            !(usage & PIPE_MAP_UNSYNCHRONIZED) &&
1211            !(resource->flags & PIPE_RESOURCE_FLAG_MAP_PERSISTENT) &&
1212            panfrost_box_covers_resource(resource, box) &&
1213            !(rsrc->bo->flags & PAN_BO_SHARED));
1214 }
1215 
1216 static void *
panfrost_ptr_map(struct pipe_context * pctx,struct pipe_resource * resource,unsigned level,unsigned usage,const struct pipe_box * box,struct pipe_transfer ** out_transfer)1217 panfrost_ptr_map(struct pipe_context *pctx, struct pipe_resource *resource,
1218                  unsigned level,
1219                  unsigned usage, /* a combination of PIPE_MAP_x */
1220                  const struct pipe_box *box,
1221                  struct pipe_transfer **out_transfer)
1222 {
1223    struct panfrost_context *ctx = pan_context(pctx);
1224    struct panfrost_device *dev = pan_device(pctx->screen);
1225    struct panfrost_resource *rsrc = pan_resource(resource);
1226    enum pipe_format format = rsrc->image.layout.format;
1227    int bytes_per_block = util_format_get_blocksize(format);
1228    struct panfrost_bo *bo = rsrc->bo;
1229 
1230    /* Can't map tiled/compressed directly */
1231    if ((usage & PIPE_MAP_DIRECTLY) &&
1232        rsrc->image.layout.modifier != DRM_FORMAT_MOD_LINEAR)
1233       return NULL;
1234 
1235    struct panfrost_transfer *transfer = rzalloc(pctx, struct panfrost_transfer);
1236    transfer->base.level = level;
1237    transfer->base.usage = usage;
1238    transfer->base.box = *box;
1239 
1240    pipe_resource_reference(&transfer->base.resource, resource);
1241    *out_transfer = &transfer->base;
1242 
1243    if (usage & PIPE_MAP_WRITE)
1244       rsrc->constant_stencil = false;
1245 
1246    /* We don't have s/w routines for AFBC/AFRC, so use a staging texture */
1247    if (drm_is_afbc(rsrc->image.layout.modifier) ||
1248        drm_is_afrc(rsrc->image.layout.modifier)) {
1249       struct panfrost_resource *staging =
1250          pan_alloc_staging(ctx, rsrc, level, box);
1251       assert(staging);
1252 
1253       /* Staging resources have one LOD: level 0. Query the strides
1254        * on this LOD.
1255        */
1256       transfer->base.stride = staging->image.layout.slices[0].row_stride;
1257       transfer->base.layer_stride =
1258          panfrost_get_layer_stride(&staging->image.layout, 0);
1259 
1260       transfer->staging.rsrc = &staging->base;
1261 
1262       transfer->staging.box = *box;
1263       transfer->staging.box.x = 0;
1264       transfer->staging.box.y = 0;
1265       transfer->staging.box.z = 0;
1266 
1267       assert(transfer->staging.rsrc != NULL);
1268 
1269       bool valid = BITSET_TEST(rsrc->valid.data, level);
1270 
1271       if ((usage & PIPE_MAP_READ) &&
1272           (valid || panfrost_any_batch_writes_rsrc(ctx, rsrc))) {
1273          pan_blit_to_staging(pctx, transfer);
1274          panfrost_flush_writer(ctx, staging, "AFBC/AFRC tex read staging blit");
1275          panfrost_bo_wait(staging->bo, INT64_MAX, false);
1276       }
1277 
1278       if (panfrost_bo_mmap(staging->bo))
1279          return NULL;
1280 
1281       return staging->bo->ptr.cpu;
1282    }
1283 
1284    bool already_mapped = bo->ptr.cpu != NULL;
1285 
1286    /* If we haven't already mmaped, now's the time */
1287    if (panfrost_bo_mmap(bo))
1288       return NULL;
1289 
1290    if (dev->debug & (PAN_DBG_TRACE | PAN_DBG_SYNC)) {
1291       pandecode_inject_mmap(dev->decode_ctx, bo->ptr.gpu, bo->ptr.cpu,
1292                             panfrost_bo_size(bo), NULL);
1293    }
1294 
1295    /* Upgrade writes to uninitialized ranges to UNSYNCHRONIZED */
1296    if ((usage & PIPE_MAP_WRITE) && resource->target == PIPE_BUFFER &&
1297        !util_ranges_intersect(&rsrc->valid_buffer_range, box->x,
1298                               box->x + box->width)) {
1299 
1300       usage |= PIPE_MAP_UNSYNCHRONIZED;
1301    }
1302 
1303    /* Upgrade DISCARD_RANGE to WHOLE_RESOURCE if the whole resource is
1304     * being mapped.
1305     */
1306    if (panfrost_can_discard(resource, box, usage)) {
1307       usage |= PIPE_MAP_DISCARD_WHOLE_RESOURCE;
1308    }
1309 
1310    bool create_new_bo = usage & PIPE_MAP_DISCARD_WHOLE_RESOURCE;
1311    bool copy_resource = false;
1312 
1313    if (!(usage & PIPE_MAP_UNSYNCHRONIZED) &&
1314        !(resource->flags & PIPE_RESOURCE_FLAG_MAP_PERSISTENT) &&
1315        (usage & PIPE_MAP_WRITE) && panfrost_any_batch_reads_rsrc(ctx, rsrc)) {
1316       /* When a resource to be modified is already being used by a
1317        * pending batch, it is often faster to copy the whole BO than
1318        * to flush and split the frame in two.
1319        */
1320 
1321       panfrost_flush_writer(ctx, rsrc, "Shadow resource creation");
1322       panfrost_bo_wait(bo, INT64_MAX, false);
1323 
1324       create_new_bo = true;
1325       copy_resource = !(usage & PIPE_MAP_DISCARD_WHOLE_RESOURCE);
1326    }
1327 
1328    /* Shadowing with separate stencil may require additional accounting.
1329     * Bail in these exotic cases.
1330     */
1331    if (rsrc->separate_stencil || rsrc->shadow_image) {
1332       create_new_bo = false;
1333       copy_resource = false;
1334    }
1335 
1336    if (create_new_bo &&
1337        (!(resource->flags & PIPE_RESOURCE_FLAG_MAP_PERSISTENT) ||
1338         !already_mapped)) {
1339       /* Make sure we re-emit any descriptors using this resource */
1340       panfrost_dirty_state_all(ctx);
1341 
1342       /* If the BO is used by one of the pending batches or if it's
1343        * not ready yet (still accessed by one of the already flushed
1344        * batches), we try to allocate a new one to avoid waiting.
1345        */
1346       if (panfrost_any_batch_reads_rsrc(ctx, rsrc) ||
1347           !panfrost_bo_wait(bo, 0, true)) {
1348          /* We want the BO to be MMAPed. */
1349          uint32_t flags = bo->flags & ~PAN_BO_DELAY_MMAP;
1350          struct panfrost_bo *newbo = NULL;
1351 
1352          /* When the BO has been imported/exported, we can't
1353           * replace it by another one, otherwise the
1354           * importer/exporter wouldn't see the change we're
1355           * doing to it.
1356           */
1357          if (!(bo->flags & PAN_BO_SHARED)) {
1358             newbo =
1359                panfrost_bo_create(dev, panfrost_bo_size(bo), flags, bo->label);
1360          }
1361 
1362          if (newbo) {
1363             if (copy_resource) {
1364                memcpy(newbo->ptr.cpu, rsrc->bo->ptr.cpu, panfrost_bo_size(bo));
1365             }
1366 
1367             /* Swap the pointers, dropping a reference to
1368              * the old BO which is no long referenced from
1369              * the resource.
1370              */
1371             panfrost_bo_unreference(rsrc->bo);
1372             rsrc->bo = newbo;
1373             rsrc->image.data.base = newbo->ptr.gpu;
1374 
1375             if (!copy_resource && drm_is_afbc(rsrc->image.layout.modifier)) {
1376                if (panfrost_resource_init_afbc_headers(rsrc))
1377                   return NULL;
1378             }
1379 
1380             bo = newbo;
1381          } else {
1382             /* Allocation failed or was impossible, let's
1383              * fall back on a flush+wait.
1384              */
1385             panfrost_flush_batches_accessing_rsrc(
1386                ctx, rsrc, "Resource access with high memory pressure");
1387             panfrost_bo_wait(bo, INT64_MAX, true);
1388          }
1389       }
1390    } else if (!(usage & PIPE_MAP_UNSYNCHRONIZED)) {
1391       if (usage & PIPE_MAP_WRITE) {
1392          panfrost_flush_batches_accessing_rsrc(ctx, rsrc, "Synchronized write");
1393          panfrost_bo_wait(bo, INT64_MAX, true);
1394       } else if (usage & PIPE_MAP_READ) {
1395          panfrost_flush_writer(ctx, rsrc, "Synchronized read");
1396          panfrost_bo_wait(bo, INT64_MAX, false);
1397       }
1398    }
1399 
1400    /* For access to compressed textures, we want the (x, y, w, h)
1401     * region-of-interest in blocks, not pixels. Then we compute the stride
1402     * between rows of blocks as the width in blocks times the width per
1403     * block, etc.
1404     */
1405    struct pipe_box box_blocks;
1406    u_box_pixels_to_blocks(&box_blocks, box, format);
1407 
1408    switch(rsrc->image.layout.modifier) {
1409    case DRM_FORMAT_MOD_ARM_16X16_BLOCK_U_INTERLEAVED:
1410    case DRM_FORMAT_MOD_MTK_16L_32S_TILE:
1411       transfer->base.stride = box_blocks.width * bytes_per_block;
1412       transfer->base.layer_stride = transfer->base.stride * box_blocks.height;
1413       transfer->map =
1414          ralloc_size(transfer, transfer->base.layer_stride * box->depth);
1415 
1416       if (usage & PIPE_MAP_READ)
1417          panfrost_load_tiled_images(transfer, rsrc);
1418 
1419       return transfer->map;
1420    default:
1421       assert(rsrc->image.layout.modifier == DRM_FORMAT_MOD_LINEAR);
1422 
1423       /* Direct, persistent writes create holes in time for
1424        * caching... I don't know if this is actually possible but we
1425        * should still get it right */
1426 
1427       unsigned dpw = PIPE_MAP_DIRECTLY | PIPE_MAP_WRITE | PIPE_MAP_PERSISTENT;
1428 
1429       if ((usage & dpw) == dpw && rsrc->index_cache)
1430          return NULL;
1431 
1432       transfer->base.stride = rsrc->image.layout.slices[level].row_stride;
1433       transfer->base.layer_stride =
1434          panfrost_get_layer_stride(&rsrc->image.layout, level);
1435 
1436       /* By mapping direct-write, we're implicitly already
1437        * initialized (maybe), so be conservative */
1438 
1439       if (usage & PIPE_MAP_WRITE) {
1440          BITSET_SET(rsrc->valid.data, level);
1441          panfrost_minmax_cache_invalidate(
1442             rsrc->index_cache, transfer->base.box.x, transfer->base.box.width);
1443       }
1444 
1445       return bo->ptr.cpu + rsrc->image.layout.slices[level].offset +
1446              box->z * transfer->base.layer_stride +
1447              box_blocks.y * rsrc->image.layout.slices[level].row_stride +
1448              box_blocks.x * bytes_per_block;
1449    }
1450 }
1451 
1452 void
pan_resource_modifier_convert(struct panfrost_context * ctx,struct panfrost_resource * rsrc,uint64_t modifier,bool copy_resource,const char * reason)1453 pan_resource_modifier_convert(struct panfrost_context *ctx,
1454                               struct panfrost_resource *rsrc, uint64_t modifier,
1455                               bool copy_resource, const char *reason)
1456 {
1457    bool need_shadow = rsrc->modifier_constant;
1458 
1459    assert(!rsrc->modifier_constant || copy_resource);
1460 
1461    struct pipe_resource template = rsrc->base;
1462    struct pipe_resource *tmp_prsrc;
1463    struct pipe_resource *next_tmp_prsrc = NULL;
1464    struct panfrost_resource *next_tmp_rsrc = NULL;
1465    if (template.next) {
1466       struct pipe_resource second_template = *template.next;
1467       bool fix_stride;
1468       assert(drm_is_mtk_tiled(rsrc->base.format, rsrc->image.layout.modifier));
1469       /* fix up the stride */
1470       switch (rsrc->base.format) {
1471       case PIPE_FORMAT_R8_G8B8_420_UNORM:
1472       case PIPE_FORMAT_R8_G8B8_422_UNORM:
1473       case PIPE_FORMAT_R10_G10B10_420_UNORM:
1474       case PIPE_FORMAT_R10_G10B10_422_UNORM:
1475          fix_stride = true;
1476          break;
1477       default:
1478          fix_stride = false;
1479          break;
1480       }
1481       template.next = NULL;
1482       if (fix_stride) {
1483          second_template.width0 *= 2; /* temporarily adjust size for subsampling */
1484       }
1485       next_tmp_prsrc = panfrost_resource_create_with_modifier(
1486          ctx->base.screen, &second_template, modifier);
1487       next_tmp_rsrc = pan_resource(next_tmp_prsrc);
1488       if (fix_stride) {
1489          next_tmp_rsrc->base.width0 /= 2;
1490          next_tmp_rsrc->image.layout.width /= 2;
1491       }
1492    }
1493    tmp_prsrc = panfrost_resource_create_with_modifier(
1494       ctx->base.screen, &template, modifier);
1495    struct panfrost_resource *tmp_rsrc = pan_resource(tmp_prsrc);
1496    if (next_tmp_prsrc) {
1497       tmp_prsrc->next = next_tmp_prsrc;
1498    }
1499 
1500    if (need_shadow && rsrc->shadow_image) {
1501       /* free the old shadow image */
1502       pipe_resource_reference(
1503          (struct pipe_resource **)&rsrc->shadow_image, NULL);
1504    }
1505    if (copy_resource) {
1506       struct pipe_blit_info blit = {
1507          .dst.resource = &tmp_rsrc->base,
1508          .dst.format = tmp_rsrc->base.format,
1509          .src.resource = &rsrc->base,
1510          .src.format = rsrc->base.format,
1511          .mask = util_format_get_mask(tmp_rsrc->base.format),
1512          .filter = PIPE_TEX_FILTER_NEAREST,
1513       };
1514 
1515       struct panfrost_screen *screen = pan_screen(ctx->base.screen);
1516       /* data_valid is not valid until flushed */
1517       panfrost_flush_writer(ctx, rsrc, "AFBC/AFRC decompressing blit");
1518 
1519       for (int i = 0; i <= rsrc->base.last_level; i++) {
1520          if (BITSET_TEST(rsrc->valid.data, i)) {
1521             blit.dst.level = blit.src.level = i;
1522 
1523             u_box_3d(0, 0, 0, u_minify(rsrc->base.width0, i),
1524                      u_minify(rsrc->base.height0, i),
1525                      util_num_layers(&rsrc->base, i), &blit.dst.box);
1526             blit.src.box = blit.dst.box;
1527 
1528             if (drm_is_mtk_tiled(rsrc->base.format,
1529                                  rsrc->image.layout.modifier))
1530                screen->vtbl.mtk_detile(ctx, &blit);
1531             else
1532                panfrost_blit_no_afbc_legalization(&ctx->base, &blit);
1533          }
1534       }
1535 
1536       /* we lose track of tmp_rsrc after this point, and the BO migration
1537        * (from tmp_rsrc to rsrc) doesn't transfer the last_writer to rsrc
1538        */
1539       panfrost_flush_writer(ctx, tmp_rsrc, "AFBC/AFRC decompressing blit");
1540    }
1541 
1542    if (need_shadow) {
1543       panfrost_resource_setup(ctx->base.screen, tmp_rsrc,
1544                               modifier, tmp_rsrc->base.format);
1545       rsrc->shadow_image = tmp_rsrc;
1546    } else {
1547       panfrost_bo_unreference(rsrc->bo);
1548 
1549       rsrc->bo = tmp_rsrc->bo;
1550       rsrc->image.data.base = rsrc->bo->ptr.gpu;
1551       panfrost_bo_reference(rsrc->bo);
1552 
1553       panfrost_resource_setup(ctx->base.screen, rsrc, modifier,
1554                               tmp_rsrc->base.format);
1555       /* panfrost_resource_setup will force the modifier to stay constant when
1556        * called with a specific modifier. We don't want that here, we want to
1557        * be able to convert back to another modifier if needed */
1558       rsrc->modifier_constant = false;
1559       pipe_resource_reference(&tmp_prsrc, NULL);
1560       perf_debug(ctx, "resource_modifier_convert required due to: %s", reason);
1561    }
1562 }
1563 
1564 /* Validate that an AFBC/AFRC resource may be used as a particular format. If it
1565  * may not, decompress it on the fly. Failure to do so can produce wrong results
1566  * or invalid data faults when sampling or rendering to AFBC */
1567 
1568 void
pan_legalize_format(struct panfrost_context * ctx,struct panfrost_resource * rsrc,enum pipe_format format,bool write,bool discard)1569 pan_legalize_format(struct panfrost_context *ctx,
1570                     struct panfrost_resource *rsrc, enum pipe_format format,
1571                     bool write, bool discard)
1572 {
1573    struct panfrost_device *dev = pan_device(ctx->base.screen);
1574    enum pipe_format old_format = rsrc->base.format;
1575    enum pipe_format new_format = format;
1576    bool compatible = true;
1577    uint64_t dest_modifier = DRM_FORMAT_MOD_ARM_16X16_BLOCK_U_INTERLEAVED;
1578 
1579    if (!drm_is_afbc(rsrc->image.layout.modifier) &&
1580        !drm_is_afrc(rsrc->image.layout.modifier) &&
1581        !drm_is_mtk_tiled(old_format, rsrc->image.layout.modifier))
1582       return;
1583 
1584    if (drm_is_afbc(rsrc->image.layout.modifier)) {
1585       compatible = (panfrost_afbc_format(dev->arch, old_format) ==
1586                     panfrost_afbc_format(dev->arch, new_format));
1587    } else if (drm_is_afrc(rsrc->image.layout.modifier)) {
1588       struct pan_afrc_format_info old_info =
1589          panfrost_afrc_get_format_info(old_format);
1590       struct pan_afrc_format_info new_info =
1591          panfrost_afrc_get_format_info(new_format);
1592       compatible = !memcmp(&old_info, &new_info, sizeof(old_info));
1593    } else if (drm_is_mtk_tiled(old_format, rsrc->image.layout.modifier)) {
1594       compatible = false;
1595       dest_modifier = DRM_FORMAT_MOD_LINEAR;
1596    }
1597 
1598    if (!compatible) {
1599       pan_resource_modifier_convert(
1600          ctx, rsrc, dest_modifier, !discard,
1601          drm_is_afbc(rsrc->image.layout.modifier)
1602             ? "Reinterpreting AFBC surface as incompatible format"
1603             : "Reinterpreting tiled surface as incompatible format");
1604       return;
1605    }
1606 
1607    /* Can't write to AFBC-P resources */
1608    if (write && drm_is_afbc(rsrc->image.layout.modifier) &&
1609       (rsrc->image.layout.modifier & AFBC_FORMAT_MOD_SPARSE) == 0) {
1610       pan_resource_modifier_convert(
1611          ctx, rsrc, rsrc->image.layout.modifier | AFBC_FORMAT_MOD_SPARSE,
1612          !discard, "Legalizing resource to allow writing");
1613    }
1614 }
1615 
1616 static bool
panfrost_should_linear_convert(struct panfrost_context * ctx,struct panfrost_resource * prsrc,struct pipe_transfer * transfer)1617 panfrost_should_linear_convert(struct panfrost_context *ctx,
1618                                struct panfrost_resource *prsrc,
1619                                struct pipe_transfer *transfer)
1620 {
1621    if (prsrc->modifier_constant)
1622       return false;
1623 
1624    /* Overwriting the entire resource indicates streaming, for which
1625     * linear layout is most efficient due to the lack of expensive
1626     * conversion.
1627     *
1628     * For now we just switch to linear after a number of complete
1629     * overwrites to keep things simple, but we could do better.
1630     *
1631     * This mechanism is only implemented for 2D resources. This suffices
1632     * for video players, its intended use case.
1633     */
1634 
1635    bool entire_overwrite = panfrost_is_2d(prsrc) &&
1636                            prsrc->base.last_level == 0 &&
1637                            transfer->box.width == prsrc->base.width0 &&
1638                            transfer->box.height == prsrc->base.height0 &&
1639                            transfer->box.x == 0 && transfer->box.y == 0;
1640 
1641    if (entire_overwrite)
1642       ++prsrc->modifier_updates;
1643 
1644    if (prsrc->modifier_updates >= LAYOUT_CONVERT_THRESHOLD) {
1645       perf_debug(ctx, "Transitioning to linear due to streaming usage");
1646       return true;
1647    } else {
1648       return false;
1649    }
1650 }
1651 
1652 static struct panfrost_bo *
panfrost_get_afbc_superblock_sizes(struct panfrost_context * ctx,struct panfrost_resource * rsrc,unsigned first_level,unsigned last_level,unsigned * out_offsets)1653 panfrost_get_afbc_superblock_sizes(struct panfrost_context *ctx,
1654                                    struct panfrost_resource *rsrc,
1655                                    unsigned first_level, unsigned last_level,
1656                                    unsigned *out_offsets)
1657 {
1658    struct panfrost_screen *screen = pan_screen(ctx->base.screen);
1659    struct panfrost_device *dev = pan_device(ctx->base.screen);
1660    struct panfrost_batch *batch;
1661    struct panfrost_bo *bo;
1662    unsigned metadata_size = 0;
1663 
1664    for (int level = first_level; level <= last_level; ++level) {
1665       struct pan_image_slice_layout *slice = &rsrc->image.layout.slices[level];
1666       unsigned sz = slice->afbc.nr_blocks * sizeof(struct pan_afbc_block_info);
1667       out_offsets[level - first_level] = metadata_size;
1668       metadata_size += sz;
1669    }
1670 
1671    bo = panfrost_bo_create(dev, metadata_size, 0, "AFBC superblock sizes");
1672    if (!bo)
1673       return NULL;
1674 
1675    panfrost_flush_batches_accessing_rsrc(ctx, rsrc, "AFBC before size flush");
1676    batch = panfrost_get_fresh_batch_for_fbo(ctx, "AFBC superblock sizes");
1677 
1678    for (int level = first_level; level <= last_level; ++level) {
1679       unsigned offset = out_offsets[level - first_level];
1680       screen->vtbl.afbc_size(batch, rsrc, bo, offset, level);
1681    }
1682 
1683    panfrost_flush_batches_accessing_rsrc(ctx, rsrc, "AFBC after size flush");
1684 
1685    return bo;
1686 }
1687 
1688 void
panfrost_pack_afbc(struct panfrost_context * ctx,struct panfrost_resource * prsrc)1689 panfrost_pack_afbc(struct panfrost_context *ctx,
1690                    struct panfrost_resource *prsrc)
1691 {
1692    struct panfrost_screen *screen = pan_screen(ctx->base.screen);
1693    struct panfrost_device *dev = pan_device(ctx->base.screen);
1694    struct panfrost_bo *metadata_bo;
1695    unsigned metadata_offsets[PIPE_MAX_TEXTURE_LEVELS];
1696 
1697    assert(prsrc->base.array_size == 1);
1698 
1699    uint64_t src_modifier = prsrc->image.layout.modifier;
1700    uint64_t dst_modifier =
1701       src_modifier & ~(AFBC_FORMAT_MOD_TILED | AFBC_FORMAT_MOD_SPARSE);
1702    bool is_tiled = src_modifier & AFBC_FORMAT_MOD_TILED;
1703    unsigned last_level = prsrc->base.last_level;
1704    struct pan_image_slice_layout slice_infos[PIPE_MAX_TEXTURE_LEVELS] = {0};
1705    unsigned total_size = 0;
1706 
1707    /* It doesn't make sense to pack everything if we need to unpack right
1708     * away to upload data to another level */
1709    for (int i = 0; i <= last_level; i++) {
1710       if (!BITSET_TEST(prsrc->valid.data, i))
1711          return;
1712    }
1713 
1714    metadata_bo = panfrost_get_afbc_superblock_sizes(ctx, prsrc, 0, last_level,
1715                                                     metadata_offsets);
1716 
1717    if (!metadata_bo) {
1718       mesa_loge("panfrost_pack_afbc: failed to get afbc superblock sizes");
1719       return;
1720    }
1721 
1722    panfrost_bo_wait(metadata_bo, INT64_MAX, false);
1723 
1724    for (unsigned level = 0; level <= last_level; ++level) {
1725       struct pan_image_slice_layout *src_slice =
1726          &prsrc->image.layout.slices[level];
1727       struct pan_image_slice_layout *dst_slice = &slice_infos[level];
1728 
1729       unsigned width = u_minify(prsrc->base.width0, level);
1730       unsigned height = u_minify(prsrc->base.height0, level);
1731       unsigned src_stride =
1732          pan_afbc_stride_blocks(src_modifier, src_slice->row_stride);
1733       unsigned dst_stride =
1734          DIV_ROUND_UP(width, panfrost_afbc_superblock_width(dst_modifier));
1735       unsigned dst_height =
1736          DIV_ROUND_UP(height, panfrost_afbc_superblock_height(dst_modifier));
1737 
1738       uint32_t offset = 0;
1739       struct pan_afbc_block_info *meta =
1740          metadata_bo->ptr.cpu + metadata_offsets[level];
1741 
1742       for (unsigned y = 0, i = 0; y < dst_height; ++y) {
1743          for (unsigned x = 0; x < dst_stride; ++x, ++i) {
1744             unsigned idx = is_tiled ? get_morton_index(x, y, src_stride) : i;
1745             uint32_t size = meta[idx].size;
1746             meta[idx].offset = offset; /* write the start offset */
1747             offset += size;
1748          }
1749       }
1750 
1751       total_size = ALIGN_POT(total_size, pan_slice_align(dst_modifier));
1752       {
1753          dst_slice->afbc.stride = dst_stride;
1754          dst_slice->afbc.nr_blocks = dst_stride * dst_height;
1755          dst_slice->afbc.header_size =
1756             ALIGN_POT(dst_stride * dst_height * AFBC_HEADER_BYTES_PER_TILE,
1757                       pan_afbc_body_align(dev->arch, dst_modifier));
1758          dst_slice->afbc.body_size = offset;
1759          dst_slice->afbc.surface_stride = dst_slice->afbc.header_size + offset;
1760 
1761          dst_slice->offset = total_size;
1762          dst_slice->row_stride = dst_stride * AFBC_HEADER_BYTES_PER_TILE;
1763          dst_slice->surface_stride = dst_slice->afbc.surface_stride;
1764          dst_slice->size = dst_slice->afbc.surface_stride;
1765 
1766          /* We can't write to AFBC-packed resource, so there is no reason to
1767           * keep CRC data around */
1768          dst_slice->crc.offset = 0;
1769          dst_slice->crc.size = 0;
1770       }
1771       total_size += dst_slice->afbc.surface_stride;
1772    }
1773 
1774    unsigned new_size = ALIGN_POT(total_size, 4096); // FIXME
1775    unsigned old_size = panfrost_bo_size(prsrc->bo);
1776    unsigned ratio = 100 * new_size / old_size;
1777 
1778    if (ratio > screen->max_afbc_packing_ratio) {
1779       panfrost_bo_unreference(metadata_bo);
1780       return;
1781    }
1782    perf_debug(ctx, "%i%%: %i KB -> %i KB\n", ratio, old_size / 1024,
1783               new_size / 1024);
1784 
1785    struct panfrost_bo *dst =
1786       panfrost_bo_create(dev, new_size, 0, "AFBC compact texture");
1787 
1788    if (!dst) {
1789       mesa_loge("panfrost_pack_afbc: failed to get afbc superblock sizes");
1790       panfrost_bo_unreference(metadata_bo);
1791       return;
1792    }
1793 
1794    struct panfrost_batch *batch =
1795       panfrost_get_fresh_batch_for_fbo(ctx, "AFBC compaction");
1796 
1797    for (unsigned level = 0; level <= last_level; ++level) {
1798       struct pan_image_slice_layout *slice = &slice_infos[level];
1799       screen->vtbl.afbc_pack(batch, prsrc, dst, slice, metadata_bo,
1800                              metadata_offsets[level], level);
1801       prsrc->image.layout.slices[level] = *slice;
1802    }
1803    prsrc->image.layout.array_stride = new_size;
1804    prsrc->image.layout.data_size = new_size;
1805 
1806    panfrost_flush_batches_accessing_rsrc(ctx, prsrc, "AFBC compaction flush");
1807 
1808    prsrc->image.layout.modifier = dst_modifier;
1809    panfrost_bo_unreference(prsrc->bo);
1810    prsrc->bo = dst;
1811    prsrc->image.data.base = dst->ptr.gpu;
1812    prsrc->image.layout.crc = false;
1813    prsrc->valid.crc = false;
1814    panfrost_bo_unreference(metadata_bo);
1815 }
1816 
1817 static void
panfrost_ptr_unmap(struct pipe_context * pctx,struct pipe_transfer * transfer)1818 panfrost_ptr_unmap(struct pipe_context *pctx, struct pipe_transfer *transfer)
1819 {
1820    /* Gallium expects writeback here, so we tile */
1821 
1822    struct panfrost_context *ctx = pan_context(pctx);
1823    struct pipe_screen *screen = ctx->base.screen;
1824    struct panfrost_transfer *trans = pan_transfer(transfer);
1825    struct panfrost_resource *prsrc =
1826       (struct panfrost_resource *)transfer->resource;
1827    struct panfrost_device *dev = pan_device(pctx->screen);
1828 
1829    if (transfer->usage & PIPE_MAP_WRITE)
1830       prsrc->valid.crc = false;
1831 
1832    /* AFBC/AFRC will use a staging resource. `initialized` will be set when
1833     * the fragment job is created; this is deferred to prevent useless surface
1834     * reloads that can cascade into DATA_INVALID_FAULTs due to reading
1835     * malformed AFBC/AFRC data if uninitialized */
1836 
1837    if (trans->staging.rsrc) {
1838       if (transfer->usage & PIPE_MAP_WRITE) {
1839          if (panfrost_should_linear_convert(ctx, prsrc, transfer)) {
1840 
1841             panfrost_bo_unreference(prsrc->bo);
1842 
1843             panfrost_resource_setup(screen, prsrc, DRM_FORMAT_MOD_LINEAR,
1844                                     prsrc->image.layout.format);
1845 
1846             prsrc->bo = pan_resource(trans->staging.rsrc)->bo;
1847             prsrc->image.data.base = prsrc->bo->ptr.gpu;
1848             panfrost_bo_reference(prsrc->bo);
1849          } else {
1850             bool discard = panfrost_can_discard(&prsrc->base, &transfer->box,
1851                                                 transfer->usage);
1852             pan_legalize_format(ctx, prsrc, prsrc->image.layout.format, true,
1853                                 discard);
1854             pan_blit_from_staging(pctx, trans);
1855             panfrost_flush_batches_accessing_rsrc(
1856                ctx, pan_resource(trans->staging.rsrc),
1857                "AFBC write staging blit");
1858 
1859             if (pan_screen(pctx->screen)->force_afbc_packing) {
1860                if (panfrost_should_pack_afbc(dev, prsrc))
1861                   panfrost_pack_afbc(ctx, prsrc);
1862             }
1863          }
1864       }
1865 
1866       pipe_resource_reference(&trans->staging.rsrc, NULL);
1867    }
1868 
1869    /* Tiling will occur in software from a staging cpu buffer */
1870    if (trans->map) {
1871       struct panfrost_bo *bo = prsrc->bo;
1872 
1873       if (transfer->usage & PIPE_MAP_WRITE) {
1874          BITSET_SET(prsrc->valid.data, transfer->level);
1875 
1876          if (prsrc->image.layout.modifier ==
1877              DRM_FORMAT_MOD_ARM_16X16_BLOCK_U_INTERLEAVED) {
1878             if (panfrost_should_linear_convert(ctx, prsrc, transfer)) {
1879                panfrost_resource_setup(screen, prsrc, DRM_FORMAT_MOD_LINEAR,
1880                                        prsrc->image.layout.format);
1881 
1882                /* converting the resource from tiled to linear and back
1883                 * shouldn't increase memory usage...
1884                 */
1885                assert(prsrc->image.layout.data_size <= panfrost_bo_size(bo));
1886 
1887                util_copy_rect(
1888                   bo->ptr.cpu + prsrc->image.layout.slices[0].offset,
1889                   prsrc->base.format, prsrc->image.layout.slices[0].row_stride,
1890                   0, 0, transfer->box.width, transfer->box.height, trans->map,
1891                   transfer->stride, 0, 0);
1892             } else {
1893                panfrost_store_tiled_images(trans, prsrc);
1894             }
1895          }
1896       }
1897    }
1898 
1899    util_range_add(&prsrc->base, &prsrc->valid_buffer_range, transfer->box.x,
1900                   transfer->box.x + transfer->box.width);
1901 
1902    if (transfer->usage & PIPE_MAP_WRITE) {
1903       panfrost_minmax_cache_invalidate(prsrc->index_cache, transfer->box.x,
1904                                        transfer->box.width);
1905    }
1906 
1907    /* Derefence the resource */
1908    pipe_resource_reference(&transfer->resource, NULL);
1909 
1910    /* Transfer itself is RALLOCed at the moment */
1911    ralloc_free(transfer);
1912 }
1913 
1914 static void
panfrost_ptr_flush_region(struct pipe_context * pctx,struct pipe_transfer * transfer,const struct pipe_box * box)1915 panfrost_ptr_flush_region(struct pipe_context *pctx,
1916                           struct pipe_transfer *transfer,
1917                           const struct pipe_box *box)
1918 {
1919    struct panfrost_resource *rsc = pan_resource(transfer->resource);
1920 
1921    if (transfer->resource->target == PIPE_BUFFER) {
1922       util_range_add(&rsc->base, &rsc->valid_buffer_range,
1923                      transfer->box.x + box->x,
1924                      transfer->box.x + box->x + box->width);
1925    } else {
1926       BITSET_SET(rsc->valid.data, transfer->level);
1927    }
1928 }
1929 
1930 static void
panfrost_invalidate_resource(struct pipe_context * pctx,struct pipe_resource * prsrc)1931 panfrost_invalidate_resource(struct pipe_context *pctx,
1932                              struct pipe_resource *prsrc)
1933 {
1934    struct panfrost_context *ctx = pan_context(pctx);
1935    struct panfrost_batch *batch = panfrost_get_batch_for_fbo(ctx);
1936    struct panfrost_resource *rsrc = pan_resource(prsrc);
1937 
1938    if (!batch) {
1939       mesa_loge("panfrost_invalidate_resource failed");
1940       return;
1941    }
1942 
1943    rsrc->constant_stencil = true;
1944 
1945    /* Handle the glInvalidateFramebuffer case */
1946    if (batch->key.zsbuf && batch->key.zsbuf->texture == prsrc)
1947       batch->resolve &= ~PIPE_CLEAR_DEPTHSTENCIL;
1948 
1949    for (unsigned i = 0; i < batch->key.nr_cbufs; ++i) {
1950       struct pipe_surface *surf = batch->key.cbufs[i];
1951 
1952       if (surf && surf->texture == prsrc)
1953          batch->resolve &= ~(PIPE_CLEAR_COLOR0 << i);
1954    }
1955 }
1956 
1957 static enum pipe_format
panfrost_resource_get_internal_format(struct pipe_resource * rsrc)1958 panfrost_resource_get_internal_format(struct pipe_resource *rsrc)
1959 {
1960    struct panfrost_resource *prsrc = (struct panfrost_resource *)rsrc;
1961    return prsrc->image.layout.format;
1962 }
1963 
1964 void
panfrost_set_image_view_planes(struct pan_image_view * iview,struct pipe_resource * texture)1965 panfrost_set_image_view_planes(struct pan_image_view *iview,
1966                                struct pipe_resource *texture)
1967 {
1968    struct panfrost_resource *prsrc_plane = (struct panfrost_resource *)texture;
1969 
1970    for (int i = 0; i < MAX_IMAGE_PLANES && prsrc_plane; i++) {
1971       iview->planes[i] = &prsrc_plane->image;
1972       prsrc_plane = (struct panfrost_resource *)prsrc_plane->base.next;
1973    }
1974 }
1975 
1976 static bool
panfrost_generate_mipmap(struct pipe_context * pctx,struct pipe_resource * prsrc,enum pipe_format format,unsigned base_level,unsigned last_level,unsigned first_layer,unsigned last_layer)1977 panfrost_generate_mipmap(struct pipe_context *pctx, struct pipe_resource *prsrc,
1978                          enum pipe_format format, unsigned base_level,
1979                          unsigned last_level, unsigned first_layer,
1980                          unsigned last_layer)
1981 {
1982    struct panfrost_resource *rsrc = pan_resource(prsrc);
1983 
1984    perf_debug(pan_context(pctx), "Unoptimized mipmap generation");
1985 
1986    /* Generating a mipmap invalidates the written levels, so make that
1987     * explicit so we don't try to wallpaper them back and end up with
1988     * u_blitter recursion */
1989 
1990    assert(rsrc->bo);
1991    for (unsigned l = base_level + 1; l <= last_level; ++l)
1992       BITSET_CLEAR(rsrc->valid.data, l);
1993 
1994    /* Beyond that, we just delegate the hard stuff. */
1995 
1996    bool blit_res =
1997       util_gen_mipmap(pctx, prsrc, format, base_level, last_level, first_layer,
1998                       last_layer, PIPE_TEX_FILTER_LINEAR);
1999 
2000    return blit_res;
2001 }
2002 
2003 static void
panfrost_resource_set_stencil(struct pipe_resource * prsrc,struct pipe_resource * stencil)2004 panfrost_resource_set_stencil(struct pipe_resource *prsrc,
2005                               struct pipe_resource *stencil)
2006 {
2007    pan_resource(prsrc)->separate_stencil = pan_resource(stencil);
2008 }
2009 
2010 static struct pipe_resource *
panfrost_resource_get_stencil(struct pipe_resource * prsrc)2011 panfrost_resource_get_stencil(struct pipe_resource *prsrc)
2012 {
2013    if (!pan_resource(prsrc)->separate_stencil)
2014       return NULL;
2015 
2016    return &pan_resource(prsrc)->separate_stencil->base;
2017 }
2018 
2019 static const struct u_transfer_vtbl transfer_vtbl = {
2020    .resource_create = panfrost_resource_create,
2021    .resource_destroy = panfrost_resource_destroy,
2022    .transfer_map = panfrost_ptr_map,
2023    .transfer_unmap = panfrost_ptr_unmap,
2024    .transfer_flush_region = panfrost_ptr_flush_region,
2025    .get_internal_format = panfrost_resource_get_internal_format,
2026    .set_stencil = panfrost_resource_set_stencil,
2027    .get_stencil = panfrost_resource_get_stencil,
2028 };
2029 
2030 void
panfrost_resource_screen_init(struct pipe_screen * pscreen)2031 panfrost_resource_screen_init(struct pipe_screen *pscreen)
2032 {
2033    pscreen->can_create_resource = panfrost_can_create_resource;
2034    pscreen->resource_create_with_modifiers =
2035       panfrost_resource_create_with_modifiers;
2036    pscreen->resource_create = u_transfer_helper_resource_create;
2037    pscreen->resource_destroy = u_transfer_helper_resource_destroy;
2038    pscreen->resource_from_handle = panfrost_resource_from_handle;
2039    pscreen->resource_get_handle = panfrost_resource_get_handle;
2040    pscreen->resource_get_param = panfrost_resource_get_param;
2041    pscreen->transfer_helper = u_transfer_helper_create(
2042       &transfer_vtbl,
2043       U_TRANSFER_HELPER_SEPARATE_Z32S8 | U_TRANSFER_HELPER_MSAA_MAP);
2044 }
2045 void
panfrost_resource_screen_destroy(struct pipe_screen * pscreen)2046 panfrost_resource_screen_destroy(struct pipe_screen *pscreen)
2047 {
2048    u_transfer_helper_destroy(pscreen->transfer_helper);
2049 }
2050 
2051 void
panfrost_resource_context_init(struct pipe_context * pctx)2052 panfrost_resource_context_init(struct pipe_context *pctx)
2053 {
2054    pctx->buffer_map = u_transfer_helper_transfer_map;
2055    pctx->buffer_unmap = u_transfer_helper_transfer_unmap;
2056    pctx->texture_map = u_transfer_helper_transfer_map;
2057    pctx->texture_unmap = u_transfer_helper_transfer_unmap;
2058    pctx->create_surface = panfrost_create_surface;
2059    pctx->surface_destroy = panfrost_surface_destroy;
2060    pctx->resource_copy_region = util_resource_copy_region;
2061    pctx->blit = panfrost_blit;
2062    pctx->generate_mipmap = panfrost_generate_mipmap;
2063    pctx->flush_resource = panfrost_flush_resource;
2064    pctx->invalidate_resource = panfrost_invalidate_resource;
2065    pctx->transfer_flush_region = u_transfer_helper_transfer_flush_region;
2066    pctx->buffer_subdata = u_default_buffer_subdata;
2067    pctx->texture_subdata = u_default_texture_subdata;
2068    pctx->clear_buffer = u_default_clear_buffer;
2069    pctx->clear_render_target = panfrost_clear_render_target;
2070    pctx->clear_depth_stencil = panfrost_clear_depth_stencil;
2071 }
2072