1/*
2 * Copyright 2006 VMware, Inc.
3 * All Rights Reserved.
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a
6 * copy of this software and associated documentation files (the
7 * "Software"), to deal in the Software without restriction, including
8 * without limitation the rights to use, copy, modify, merge, publish,
9 * distribute, sublicense, and/or sell copies of the Software, and to
10 * permit persons to whom the Software is furnished to do so, subject to
11 * the following conditions:
12 *
13 * The above copyright notice and this permission notice (including the
14 * next paragraph) shall be included in all copies or substantial portions
15 * of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
20 * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR
21 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
22 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
23 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 */
25
26#include <GL/gl.h>
27#include <GL/internal/dri_interface.h>
28#include "drm-uapi/drm_fourcc.h"
29
30#include "brw_batch.h"
31#include "brw_image.h"
32#include "brw_mipmap_tree.h"
33#include "brw_tex.h"
34#include "brw_blit.h"
35#include "brw_fbo.h"
36
37#include "brw_blorp.h"
38#include "brw_context.h"
39#include "brw_state.h"
40
41#include "main/enums.h"
42#include "main/fbobject.h"
43#include "main/formats.h"
44#include "main/glformats.h"
45#include "main/texcompress_etc.h"
46#include "main/teximage.h"
47#include "main/streaming-load-memcpy.h"
48
49#include "util/format_srgb.h"
50#include "util/u_memory.h"
51
52#include "x86/common_x86_asm.h"
53
54#define FILE_DEBUG_FLAG DEBUG_MIPTREE
55
56static void *brw_miptree_map_raw(struct brw_context *brw,
57                                 struct brw_mipmap_tree *mt,
58                                 GLbitfield mode);
59
60static void brw_miptree_unmap_raw(struct brw_mipmap_tree *mt);
61
62/**
63 * Return true if the format that will be used to access the miptree is
64 * CCS_E-compatible with the miptree's linear/non-sRGB format.
65 *
66 * Why use the linear format? Well, although the miptree may be specified with
67 * an sRGB format, the usage of that color space/format can be toggled. Since
68 * our HW tends to support more linear formats than sRGB ones, we use this
69 * format variant for check for CCS_E compatibility.
70 */
71static bool
72format_ccs_e_compat_with_miptree(const struct intel_device_info *devinfo,
73                                 const struct brw_mipmap_tree *mt,
74                                 enum isl_format access_format)
75{
76   assert(mt->aux_usage == ISL_AUX_USAGE_CCS_E);
77
78   mesa_format linear_format = _mesa_get_srgb_format_linear(mt->format);
79   enum isl_format isl_format = brw_isl_format_for_mesa_format(linear_format);
80   return isl_formats_are_ccs_e_compatible(devinfo, isl_format, access_format);
81}
82
83/* Determine if CCS_E is supported for a given platform and mesa format. */
84static bool
85format_supports_ccs_e(const struct brw_context *brw, mesa_format format)
86{
87   /* For now compression is only enabled for integer formats even though
88    * there exist supported floating point formats also. This is a heuristic
89    * decision based on current public benchmarks. In none of the cases these
90    * formats provided any improvement but a few cases were seen to regress.
91    * Hence these are left to to be enabled in the future when they are known
92    * to improve things.
93    */
94   if (_mesa_get_format_datatype(format) == GL_FLOAT)
95      return false;
96
97   /* Many window system buffers are sRGB even if they are never rendered as
98    * sRGB.  For those, we want CCS_E for when sRGBEncode is false.  When the
99    * surface is used as sRGB, we fall back to CCS_D.
100    */
101   mesa_format linear_format = _mesa_get_srgb_format_linear(format);
102   enum isl_format isl_format = brw_isl_format_for_mesa_format(linear_format);
103   return isl_format_supports_ccs_e(&brw->screen->devinfo, isl_format);
104}
105
106/**
107 * Determine depth format corresponding to a depth+stencil format,
108 * for separate stencil.
109 */
110mesa_format
111brw_depth_format_for_depthstencil_format(mesa_format format) {
112   switch (format) {
113   case MESA_FORMAT_Z24_UNORM_S8_UINT:
114      return MESA_FORMAT_Z24_UNORM_X8_UINT;
115   case MESA_FORMAT_Z32_FLOAT_S8X24_UINT:
116      return MESA_FORMAT_Z_FLOAT32;
117   default:
118      return format;
119   }
120}
121
122static bool
123create_mapping_table(GLenum target, unsigned first_level, unsigned last_level,
124                     unsigned depth0, struct brw_mipmap_level *table)
125{
126   for (unsigned level = first_level; level <= last_level; level++) {
127      const unsigned d =
128         target == GL_TEXTURE_3D ? minify(depth0, level) : depth0;
129
130      table[level].slice = calloc(d, sizeof(*table[0].slice));
131      if (!table[level].slice)
132         goto unwind;
133   }
134
135   return true;
136
137unwind:
138   for (unsigned level = first_level; level <= last_level; level++)
139      free(table[level].slice);
140
141   return false;
142}
143
144static bool
145needs_separate_stencil(const struct brw_context *brw,
146                       struct brw_mipmap_tree *mt,
147                       mesa_format format)
148{
149   const struct intel_device_info *devinfo = &brw->screen->devinfo;
150
151   if (_mesa_get_format_base_format(format) != GL_DEPTH_STENCIL)
152      return false;
153
154   if (devinfo->must_use_separate_stencil)
155      return true;
156
157   return brw->has_separate_stencil && brw->has_hiz;
158}
159
160/**
161 * Choose the aux usage for this miptree.  This function must be called fairly
162 * late in the miptree create process after we have a tiling.
163 */
164static void
165brw_miptree_choose_aux_usage(struct brw_context *brw,
166                             struct brw_mipmap_tree *mt)
167{
168   assert(mt->aux_usage == ISL_AUX_USAGE_NONE);
169
170   if (_mesa_is_format_color_format(mt->format)) {
171      if (mt->surf.samples > 1) {
172         mt->aux_usage = ISL_AUX_USAGE_MCS;
173      } else if (!INTEL_DEBUG(DEBUG_NO_RBC) &&
174                 format_supports_ccs_e(brw, mt->format)) {
175         mt->aux_usage = ISL_AUX_USAGE_CCS_E;
176      } else if (brw->mesa_format_supports_render[mt->format]) {
177         mt->aux_usage = ISL_AUX_USAGE_CCS_D;
178      }
179   } else if (isl_surf_usage_is_depth(mt->surf.usage) && brw->has_hiz) {
180      mt->aux_usage = ISL_AUX_USAGE_HIZ;
181   }
182
183   /* We can do fast-clear on all auxiliary surface types that are
184    * allocated through the normal texture creation paths.
185    */
186   if (mt->aux_usage != ISL_AUX_USAGE_NONE)
187      mt->supports_fast_clear = true;
188}
189
190
191/**
192 * Choose an appropriate uncompressed format for a requested
193 * compressed format, if unsupported.
194 */
195mesa_format
196brw_lower_compressed_format(struct brw_context *brw, mesa_format format)
197{
198   const struct intel_device_info *devinfo = &brw->screen->devinfo;
199
200   /* No need to lower ETC formats on these platforms,
201    * they are supported natively.
202    */
203   if (devinfo->ver >= 8 || devinfo->is_baytrail)
204      return format;
205
206   switch (format) {
207   case MESA_FORMAT_ETC1_RGB8:
208      return MESA_FORMAT_R8G8B8X8_UNORM;
209   case MESA_FORMAT_ETC2_RGB8:
210      return MESA_FORMAT_R8G8B8X8_UNORM;
211   case MESA_FORMAT_ETC2_SRGB8:
212   case MESA_FORMAT_ETC2_SRGB8_ALPHA8_EAC:
213   case MESA_FORMAT_ETC2_SRGB8_PUNCHTHROUGH_ALPHA1:
214      return MESA_FORMAT_B8G8R8A8_SRGB;
215   case MESA_FORMAT_ETC2_RGBA8_EAC:
216   case MESA_FORMAT_ETC2_RGB8_PUNCHTHROUGH_ALPHA1:
217      return MESA_FORMAT_R8G8B8A8_UNORM;
218   case MESA_FORMAT_ETC2_R11_EAC:
219      return MESA_FORMAT_R_UNORM16;
220   case MESA_FORMAT_ETC2_SIGNED_R11_EAC:
221      return MESA_FORMAT_R_SNORM16;
222   case MESA_FORMAT_ETC2_RG11_EAC:
223      return MESA_FORMAT_RG_UNORM16;
224   case MESA_FORMAT_ETC2_SIGNED_RG11_EAC:
225      return MESA_FORMAT_RG_SNORM16;
226   default:
227      /* Non ETC1 / ETC2 format */
228      return format;
229   }
230}
231
232unsigned
233brw_get_num_logical_layers(const struct brw_mipmap_tree *mt, unsigned level)
234{
235   if (mt->surf.dim == ISL_SURF_DIM_3D)
236      return minify(mt->surf.logical_level0_px.depth, level);
237   else
238      return mt->surf.logical_level0_px.array_len;
239}
240
241UNUSED static unsigned
242get_num_phys_layers(const struct isl_surf *surf, unsigned level)
243{
244   /* In case of physical dimensions one needs to consider also the layout.
245    * See isl_calc_phys_level0_extent_sa().
246    */
247   if (surf->dim != ISL_SURF_DIM_3D)
248      return surf->phys_level0_sa.array_len;
249
250   if (surf->dim_layout == ISL_DIM_LAYOUT_GFX4_2D)
251      return minify(surf->phys_level0_sa.array_len, level);
252
253   return minify(surf->phys_level0_sa.depth, level);
254}
255
256/** \brief Assert that the level and layer are valid for the miptree. */
257void
258brw_miptree_check_level_layer(const struct brw_mipmap_tree *mt,
259                              uint32_t level,
260                              uint32_t layer)
261{
262   (void) mt;
263   (void) level;
264   (void) layer;
265
266   assert(level >= mt->first_level);
267   assert(level <= mt->last_level);
268   assert(layer < get_num_phys_layers(&mt->surf, level));
269}
270
271static enum isl_aux_state **
272create_aux_state_map(struct brw_mipmap_tree *mt,
273                     enum isl_aux_state initial)
274{
275   const uint32_t levels = mt->last_level + 1;
276
277   uint32_t total_slices = 0;
278   for (uint32_t level = 0; level < levels; level++)
279      total_slices += brw_get_num_logical_layers(mt, level);
280
281   const size_t per_level_array_size = levels * sizeof(enum isl_aux_state *);
282
283   /* We're going to allocate a single chunk of data for both the per-level
284    * reference array and the arrays of aux_state.  This makes cleanup
285    * significantly easier.
286    */
287   const size_t total_size = per_level_array_size +
288                             total_slices * sizeof(enum isl_aux_state);
289   void *data = malloc(total_size);
290   if (data == NULL)
291      return NULL;
292
293   enum isl_aux_state **per_level_arr = data;
294   enum isl_aux_state *s = data + per_level_array_size;
295   for (uint32_t level = 0; level < levels; level++) {
296      per_level_arr[level] = s;
297      const unsigned level_layers = brw_get_num_logical_layers(mt, level);
298      for (uint32_t a = 0; a < level_layers; a++)
299         *(s++) = initial;
300   }
301   assert((void *)s == data + total_size);
302
303   return per_level_arr;
304}
305
306static void
307free_aux_state_map(enum isl_aux_state **state)
308{
309   free(state);
310}
311
312static bool
313need_to_retile_as_linear(struct brw_context *brw, unsigned blt_pitch,
314                         enum isl_tiling tiling, unsigned samples)
315{
316   if (samples > 1)
317      return false;
318
319   if (tiling == ISL_TILING_LINEAR)
320      return false;
321
322   if (blt_pitch >= 32768) {
323      perf_debug("blt pitch %u too large to blit, falling back to untiled",
324                 blt_pitch);
325      return true;
326   }
327
328   return false;
329}
330
331static bool
332need_to_retile_as_x(const struct brw_context *brw, uint64_t size,
333                    enum isl_tiling tiling)
334{
335   const struct intel_device_info *devinfo = &brw->screen->devinfo;
336
337   /* If the BO is too large to fit in the aperture, we need to use the
338    * BLT engine to support it.  Prior to Sandybridge, the BLT paths can't
339    * handle Y-tiling, so we need to fall back to X.
340    */
341   if (devinfo->ver < 6 && size >= brw->max_gtt_map_object_size &&
342       tiling == ISL_TILING_Y0)
343      return true;
344
345   return false;
346}
347
348static struct brw_mipmap_tree *
349make_surface(struct brw_context *brw, GLenum target, mesa_format format,
350             unsigned first_level, unsigned last_level,
351             unsigned width0, unsigned height0, unsigned depth0,
352             unsigned num_samples, isl_tiling_flags_t tiling_flags,
353             isl_surf_usage_flags_t isl_usage_flags, uint32_t alloc_flags,
354             unsigned row_pitch_B, struct brw_bo *bo)
355{
356   struct brw_mipmap_tree *mt = calloc(sizeof(*mt), 1);
357   if (!mt)
358      return NULL;
359
360   if (!create_mapping_table(target, first_level, last_level, depth0,
361                             mt->level)) {
362      free(mt);
363      return NULL;
364   }
365
366   mt->refcount = 1;
367
368   if (target == GL_TEXTURE_CUBE_MAP ||
369       target == GL_TEXTURE_CUBE_MAP_ARRAY)
370      isl_usage_flags |= ISL_SURF_USAGE_CUBE_BIT;
371
372   DBG("%s: %s %s %ux %u:%u:%u %d..%d <-- %p\n",
373        __func__,
374       _mesa_enum_to_string(target),
375       _mesa_get_format_name(format),
376       num_samples, width0, height0, depth0,
377       first_level, last_level, mt);
378
379   struct isl_surf_init_info init_info = {
380      .dim = get_isl_surf_dim(target),
381      .format = translate_tex_format(brw, format, false),
382      .width = width0,
383      .height = height0,
384      .depth = target == GL_TEXTURE_3D ? depth0 : 1,
385      .levels = last_level - first_level + 1,
386      .array_len = target == GL_TEXTURE_3D ? 1 : depth0,
387      .samples = num_samples,
388      .row_pitch_B = row_pitch_B,
389      .usage = isl_usage_flags,
390      .tiling_flags = tiling_flags,
391   };
392
393   if (!isl_surf_init_s(&brw->isl_dev, &mt->surf, &init_info))
394      goto fail;
395
396   /* Depth surfaces are always Y-tiled and stencil is always W-tiled, although
397    * on gfx7 platforms we also need to create Y-tiled copies of stencil for
398    * texturing since the hardware can't sample from W-tiled surfaces. For
399    * everything else, check for corner cases needing special treatment.
400    */
401   bool is_depth_stencil =
402      mt->surf.usage & (ISL_SURF_USAGE_STENCIL_BIT | ISL_SURF_USAGE_DEPTH_BIT);
403   if (!is_depth_stencil) {
404      if (need_to_retile_as_linear(brw, brw_miptree_blt_pitch(mt),
405                                   mt->surf.tiling, mt->surf.samples)) {
406         init_info.tiling_flags = 1u << ISL_TILING_LINEAR;
407         if (!isl_surf_init_s(&brw->isl_dev, &mt->surf, &init_info))
408            goto fail;
409      } else if (need_to_retile_as_x(brw, mt->surf.size_B, mt->surf.tiling)) {
410         init_info.tiling_flags = 1u << ISL_TILING_X;
411         if (!isl_surf_init_s(&brw->isl_dev, &mt->surf, &init_info))
412            goto fail;
413      }
414   }
415
416   /* In case of linear the buffer gets padded by fixed 64 bytes and therefore
417    * the size may not be multiple of row_pitch.
418    * See isl_apply_surface_padding().
419    */
420   if (mt->surf.tiling != ISL_TILING_LINEAR)
421      assert(mt->surf.size_B % mt->surf.row_pitch_B == 0);
422
423   if (!bo) {
424      mt->bo = brw_bo_alloc_tiled(brw->bufmgr, "isl-miptree",
425                                  mt->surf.size_B,
426                                  BRW_MEMZONE_OTHER,
427                                  isl_tiling_to_i915_tiling(
428                                     mt->surf.tiling),
429                                  mt->surf.row_pitch_B, alloc_flags);
430      if (!mt->bo)
431         goto fail;
432   } else {
433      mt->bo = bo;
434   }
435
436   mt->first_level = first_level;
437   mt->last_level = last_level;
438   mt->target = target;
439   mt->format = format;
440   mt->aux_state = NULL;
441   mt->cpp = isl_format_get_layout(mt->surf.format)->bpb / 8;
442   mt->compressed = _mesa_is_format_compressed(format);
443   mt->drm_modifier = DRM_FORMAT_MOD_INVALID;
444
445   return mt;
446
447fail:
448   brw_miptree_release(&mt);
449   return NULL;
450}
451
452/* Return the usual surface usage flags for the given format. */
453static isl_surf_usage_flags_t
454mt_surf_usage(mesa_format format)
455{
456   switch(_mesa_get_format_base_format(format)) {
457   case GL_DEPTH_COMPONENT:
458      return ISL_SURF_USAGE_DEPTH_BIT | ISL_SURF_USAGE_TEXTURE_BIT;
459   case GL_DEPTH_STENCIL:
460      return ISL_SURF_USAGE_DEPTH_BIT | ISL_SURF_USAGE_STENCIL_BIT |
461             ISL_SURF_USAGE_TEXTURE_BIT;
462   case GL_STENCIL_INDEX:
463      return ISL_SURF_USAGE_STENCIL_BIT | ISL_SURF_USAGE_TEXTURE_BIT;
464   default:
465      return ISL_SURF_USAGE_RENDER_TARGET_BIT | ISL_SURF_USAGE_TEXTURE_BIT;
466   }
467}
468
469static struct brw_mipmap_tree *
470miptree_create(struct brw_context *brw,
471               GLenum target,
472               mesa_format format,
473               GLuint first_level,
474               GLuint last_level,
475               GLuint width0,
476               GLuint height0,
477               GLuint depth0,
478               GLuint num_samples,
479               enum brw_miptree_create_flags flags)
480{
481   const struct intel_device_info *devinfo = &brw->screen->devinfo;
482   const uint32_t alloc_flags =
483      (flags & MIPTREE_CREATE_BUSY || num_samples > 1) ? BO_ALLOC_BUSY : 0;
484   isl_tiling_flags_t tiling_flags = ISL_TILING_ANY_MASK;
485
486   /* TODO: This used to be because there wasn't BLORP to handle Y-tiling. */
487   if (devinfo->ver < 6 && _mesa_is_format_color_format(format))
488      tiling_flags &= ~ISL_TILING_Y0_BIT;
489
490   mesa_format mt_fmt = format;
491   if (!_mesa_is_format_color_format(format) && devinfo->ver >= 6) {
492      /* Fix up the Z miptree format for how we're splitting out separate
493       * stencil. Gfx7 expects there to be no stencil bits in its depth buffer.
494       */
495      mt_fmt = brw_depth_format_for_depthstencil_format(format);
496   }
497
498   struct brw_mipmap_tree *mt =
499      make_surface(brw, target, mt_fmt, first_level, last_level,
500                   width0, height0, depth0, num_samples,
501                   tiling_flags, mt_surf_usage(mt_fmt),
502                   alloc_flags, 0, NULL);
503
504   if (mt == NULL)
505      return NULL;
506
507   if (brw_miptree_needs_fake_etc(brw, mt)) {
508      mesa_format decomp_format = brw_lower_compressed_format(brw, format);
509      mt->shadow_mt = make_surface(brw, target, decomp_format, first_level,
510                                   last_level, width0, height0, depth0,
511                                   num_samples, tiling_flags,
512                                   mt_surf_usage(decomp_format),
513                                   alloc_flags, 0, NULL);
514
515      if (mt->shadow_mt == NULL) {
516         brw_miptree_release(&mt);
517         return NULL;
518      }
519   }
520
521   if (needs_separate_stencil(brw, mt, format)) {
522      mt->stencil_mt =
523         make_surface(brw, target, MESA_FORMAT_S_UINT8, first_level, last_level,
524                      width0, height0, depth0, num_samples,
525                      ISL_TILING_W_BIT, mt_surf_usage(MESA_FORMAT_S_UINT8),
526                      alloc_flags, 0, NULL);
527      if (mt->stencil_mt == NULL) {
528         brw_miptree_release(&mt);
529         return NULL;
530      }
531   }
532
533   if (!(flags & MIPTREE_CREATE_NO_AUX))
534      brw_miptree_choose_aux_usage(brw, mt);
535
536   return mt;
537}
538
539struct brw_mipmap_tree *
540brw_miptree_create(struct brw_context *brw,
541                   GLenum target,
542                   mesa_format format,
543                   GLuint first_level,
544                   GLuint last_level,
545                   GLuint width0,
546                   GLuint height0,
547                   GLuint depth0,
548                   GLuint num_samples,
549                   enum brw_miptree_create_flags flags)
550{
551   assert(num_samples > 0);
552
553   struct brw_mipmap_tree *mt = miptree_create(
554                                     brw, target, format,
555                                     first_level, last_level,
556                                     width0, height0, depth0, num_samples,
557                                     flags);
558   if (!mt)
559      return NULL;
560
561   mt->offset = 0;
562
563   /* Create the auxiliary surface up-front. CCS_D, on the other hand, can only
564    * compress clear color so we wait until an actual fast-clear to allocate
565    * it.
566    */
567   if (mt->aux_usage != ISL_AUX_USAGE_CCS_D &&
568       !brw_miptree_alloc_aux(brw, mt)) {
569      mt->aux_usage = ISL_AUX_USAGE_NONE;
570      mt->supports_fast_clear = false;
571   }
572
573   return mt;
574}
575
576struct brw_mipmap_tree *
577brw_miptree_create_for_bo(struct brw_context *brw,
578                          struct brw_bo *bo,
579                          mesa_format format,
580                          uint32_t offset,
581                          uint32_t width,
582                          uint32_t height,
583                          uint32_t depth,
584                          int pitch,
585                          enum isl_tiling tiling,
586                          enum brw_miptree_create_flags flags)
587{
588   const struct intel_device_info *devinfo = &brw->screen->devinfo;
589   struct brw_mipmap_tree *mt;
590   const GLenum target = depth > 1 ? GL_TEXTURE_2D_ARRAY : GL_TEXTURE_2D;
591   const GLenum base_format = _mesa_get_format_base_format(format);
592
593   if ((base_format == GL_DEPTH_COMPONENT ||
594        base_format == GL_DEPTH_STENCIL)) {
595      const mesa_format mt_fmt = (devinfo->ver < 6) ? format :
596         brw_depth_format_for_depthstencil_format(format);
597      mt = make_surface(brw, target, mt_fmt,
598                        0, 0, width, height, depth, 1, ISL_TILING_Y0_BIT,
599                        mt_surf_usage(mt_fmt),
600                        0, pitch, bo);
601      if (!mt)
602         return NULL;
603
604      brw_bo_reference(bo);
605
606      if (!(flags & MIPTREE_CREATE_NO_AUX))
607         brw_miptree_choose_aux_usage(brw, mt);
608
609      return mt;
610   } else if (format == MESA_FORMAT_S_UINT8) {
611      mt = make_surface(brw, target, MESA_FORMAT_S_UINT8,
612                        0, 0, width, height, depth, 1,
613                        ISL_TILING_W_BIT,
614                        mt_surf_usage(MESA_FORMAT_S_UINT8),
615                        0, pitch, bo);
616      if (!mt)
617         return NULL;
618
619      assert(bo->size >= mt->surf.size_B);
620
621      brw_bo_reference(bo);
622      return mt;
623   }
624
625   /* Nothing will be able to use this miptree with the BO if the offset isn't
626    * aligned.
627    */
628   if (tiling != ISL_TILING_LINEAR)
629      assert(offset % 4096 == 0);
630
631   /* miptrees can't handle negative pitch.  If you need flipping of images,
632    * that's outside of the scope of the mt.
633    */
634   assert(pitch >= 0);
635
636   mt = make_surface(brw, target, format,
637                     0, 0, width, height, depth, 1,
638                     1lu << tiling,
639                     mt_surf_usage(format),
640                     0, pitch, bo);
641   if (!mt)
642      return NULL;
643
644   brw_bo_reference(bo);
645   mt->bo = bo;
646   mt->offset = offset;
647
648   if (!(flags & MIPTREE_CREATE_NO_AUX)) {
649      brw_miptree_choose_aux_usage(brw, mt);
650
651      /* Create the auxiliary surface up-front. CCS_D, on the other hand, can
652       * only compress clear color so we wait until an actual fast-clear to
653       * allocate it.
654       */
655      if (mt->aux_usage != ISL_AUX_USAGE_CCS_D &&
656          !brw_miptree_alloc_aux(brw, mt)) {
657         mt->aux_usage = ISL_AUX_USAGE_NONE;
658         mt->supports_fast_clear = false;
659      }
660   }
661
662   return mt;
663}
664
665static struct brw_mipmap_tree *
666miptree_create_for_planar_image(struct brw_context *brw,
667                                __DRIimage *image, GLenum target,
668                                enum isl_tiling tiling)
669{
670   const struct brw_image_format *f = image->planar_format;
671   struct brw_mipmap_tree *planar_mt = NULL;
672
673   for (int i = 0; i < f->nplanes; i++) {
674      const int index = f->planes[i].buffer_index;
675      const uint32_t dri_format = f->planes[i].dri_format;
676      const mesa_format format = driImageFormatToGLFormat(dri_format);
677      const uint32_t width = image->width >> f->planes[i].width_shift;
678      const uint32_t height = image->height >> f->planes[i].height_shift;
679
680      /* Disable creation of the texture's aux buffers because the driver
681       * exposes no EGL API to manage them. That is, there is no API for
682       * resolving the aux buffer's content to the main buffer nor for
683       * invalidating the aux buffer's content.
684       */
685      struct brw_mipmap_tree *mt =
686         brw_miptree_create_for_bo(brw, image->bo, format,
687                                   image->offsets[index],
688                                   width, height, 1,
689                                   image->strides[index],
690                                   tiling,
691                                   MIPTREE_CREATE_NO_AUX);
692      if (mt == NULL) {
693         brw_miptree_release(&planar_mt);
694         return NULL;
695      }
696
697      mt->target = target;
698
699      if (i == 0)
700         planar_mt = mt;
701      else
702         planar_mt->plane[i - 1] = mt;
703   }
704
705   planar_mt->drm_modifier = image->modifier;
706
707   return planar_mt;
708}
709
710static bool
711create_ccs_buf_for_image(struct brw_context *brw,
712                         __DRIimage *image,
713                         struct brw_mipmap_tree *mt,
714                         enum isl_aux_state initial_state)
715{
716   struct isl_surf temp_ccs_surf = {0,};
717
718   /* CCS is only supported for very simple miptrees */
719   assert(image->aux_offset != 0 && image->aux_pitch != 0);
720   assert(image->tile_x == 0 && image->tile_y == 0);
721   assert(mt->surf.samples == 1);
722   assert(mt->surf.levels == 1);
723   assert(mt->surf.logical_level0_px.depth == 1);
724   assert(mt->surf.logical_level0_px.array_len == 1);
725   assert(mt->first_level == 0);
726   assert(mt->last_level == 0);
727
728   /* We shouldn't already have a CCS */
729   assert(!mt->aux_buf);
730
731   if (!isl_surf_get_ccs_surf(&brw->isl_dev, &mt->surf, NULL,
732                              &temp_ccs_surf, image->aux_pitch))
733      return false;
734
735   assert(image->aux_offset < image->bo->size);
736   assert(temp_ccs_surf.size_B <= image->bo->size - image->aux_offset);
737
738   mt->aux_buf = calloc(sizeof(*mt->aux_buf), 1);
739   if (mt->aux_buf == NULL)
740      return false;
741
742   mt->aux_state = create_aux_state_map(mt, initial_state);
743   if (!mt->aux_state) {
744      free(mt->aux_buf);
745      mt->aux_buf = NULL;
746      return false;
747   }
748
749   /* On gfx10+ we start using an extra space in the aux buffer to store the
750    * indirect clear color. However, if we imported an image from the window
751    * system with CCS, we don't have the extra space at the end of the aux
752    * buffer. So create a new bo here that will store that clear color.
753    */
754   if (brw->isl_dev.ss.clear_color_state_size > 0) {
755      mt->aux_buf->clear_color_bo =
756         brw_bo_alloc_tiled(brw->bufmgr, "clear_color_bo",
757                            brw->isl_dev.ss.clear_color_state_size,
758                            BRW_MEMZONE_OTHER, I915_TILING_NONE, 0,
759                            BO_ALLOC_ZEROED);
760      if (!mt->aux_buf->clear_color_bo) {
761         free(mt->aux_buf);
762         mt->aux_buf = NULL;
763         return false;
764      }
765   }
766
767   mt->aux_buf->bo = image->bo;
768   brw_bo_reference(image->bo);
769
770   mt->aux_buf->offset = image->aux_offset;
771   mt->aux_buf->surf = temp_ccs_surf;
772
773   return true;
774}
775
776struct brw_mipmap_tree *
777brw_miptree_create_for_dri_image(struct brw_context *brw,
778                                 __DRIimage *image, GLenum target,
779                                 mesa_format format,
780                                 bool allow_internal_aux)
781{
782   uint32_t bo_tiling, bo_swizzle;
783   brw_bo_get_tiling(image->bo, &bo_tiling, &bo_swizzle);
784
785   const struct isl_drm_modifier_info *mod_info =
786      isl_drm_modifier_get_info(image->modifier);
787
788   const enum isl_tiling tiling =
789      mod_info ? mod_info->tiling : isl_tiling_from_i915_tiling(bo_tiling);
790
791   if (image->planar_format && image->planar_format->nplanes > 1)
792      return miptree_create_for_planar_image(brw, image, target, tiling);
793
794   if (image->planar_format)
795      assert(image->planar_format->planes[0].dri_format == image->dri_format);
796
797   if (!brw->ctx.TextureFormatSupported[format]) {
798      /* The texture storage paths in core Mesa detect if the driver does not
799       * support the user-requested format, and then searches for a
800       * fallback format. The DRIimage code bypasses core Mesa, though. So we
801       * do the fallbacks here for important formats.
802       *
803       * We must support DRM_FOURCC_XBGR8888 textures because the Android
804       * framework produces HAL_PIXEL_FORMAT_RGBX8888 winsys surfaces, which
805       * the Chrome OS compositor consumes as dma_buf EGLImages.
806       */
807      format = _mesa_format_fallback_rgbx_to_rgba(format);
808   }
809
810   if (!brw->ctx.TextureFormatSupported[format])
811      return NULL;
812
813   enum brw_miptree_create_flags mt_create_flags = 0;
814
815   /* If this image comes in from a window system, we have different
816    * requirements than if it comes in via an EGL import operation.  Window
817    * system images can use any form of auxiliary compression we wish because
818    * they get "flushed" before being handed off to the window system and we
819    * have the opportunity to do resolves.  Non window-system images, on the
820    * other hand, have no resolve point so we can't have aux without a
821    * modifier.
822    */
823   if (!allow_internal_aux)
824      mt_create_flags |= MIPTREE_CREATE_NO_AUX;
825
826   /* If we have a modifier which specifies aux, don't create one yet */
827   if (mod_info && mod_info->aux_usage != ISL_AUX_USAGE_NONE)
828      mt_create_flags |= MIPTREE_CREATE_NO_AUX;
829
830   /* Disable creation of the texture's aux buffers because the driver exposes
831    * no EGL API to manage them. That is, there is no API for resolving the aux
832    * buffer's content to the main buffer nor for invalidating the aux buffer's
833    * content.
834    */
835   struct brw_mipmap_tree *mt =
836      brw_miptree_create_for_bo(brw, image->bo, format,
837                                image->offset, image->width, image->height, 1,
838                                image->pitch, tiling, mt_create_flags);
839   if (mt == NULL)
840      return NULL;
841
842   mt->target = target;
843   mt->level[0].level_x = image->tile_x;
844   mt->level[0].level_y = image->tile_y;
845   mt->drm_modifier = image->modifier;
846
847   /* From "OES_EGL_image" error reporting. We report GL_INVALID_OPERATION
848    * for EGL images from non-tile aligned sufaces in gfx4 hw and earlier which has
849    * trouble resolving back to destination image due to alignment issues.
850    */
851   const struct intel_device_info *devinfo = &brw->screen->devinfo;
852   if (!devinfo->has_surface_tile_offset) {
853      uint32_t draw_x, draw_y;
854      brw_miptree_get_tile_offsets(mt, 0, 0, &draw_x, &draw_y);
855
856      if (draw_x != 0 || draw_y != 0) {
857         _mesa_error(&brw->ctx, GL_INVALID_OPERATION, __func__);
858         brw_miptree_release(&mt);
859         return NULL;
860      }
861   }
862
863   if (mod_info && mod_info->aux_usage != ISL_AUX_USAGE_NONE) {
864      assert(mod_info->aux_usage == ISL_AUX_USAGE_CCS_E);
865
866      mt->aux_usage = mod_info->aux_usage;
867      /* If we are a window system buffer, then we can support fast-clears
868       * even if the modifier doesn't support them by doing a partial resolve
869       * as part of the flush operation.
870       */
871      mt->supports_fast_clear =
872         allow_internal_aux || mod_info->supports_clear_color;
873
874      /* We don't know the actual state of the surface when we get it but we
875       * can make a pretty good guess based on the modifier.  What we do know
876       * for sure is that it isn't in the AUX_INVALID state, so we just assume
877       * a worst case of compression.
878       */
879      enum isl_aux_state initial_state =
880         isl_drm_modifier_get_default_aux_state(image->modifier);
881
882      if (!create_ccs_buf_for_image(brw, image, mt, initial_state)) {
883         brw_miptree_release(&mt);
884         return NULL;
885      }
886   }
887
888   /* Don't assume coherency for imported EGLimages.  We don't know what
889    * external clients are going to do with it.  They may scan it out.
890    */
891   image->bo->cache_coherent = false;
892
893   return mt;
894}
895
896/**
897 * For a singlesample renderbuffer, this simply wraps the given BO with a
898 * miptree.
899 *
900 * For a multisample renderbuffer, this wraps the window system's
901 * (singlesample) BO with a singlesample miptree attached to the
902 * brw_renderbuffer, then creates a multisample miptree attached to irb->mt
903 * that will contain the actual rendering (which is lazily resolved to
904 * irb->singlesample_mt).
905 */
906bool
907brw_update_winsys_renderbuffer_miptree(struct brw_context *intel,
908                                         struct brw_renderbuffer *irb,
909                                         struct brw_mipmap_tree *singlesample_mt,
910                                         uint32_t width, uint32_t height,
911                                         uint32_t pitch)
912{
913   struct brw_mipmap_tree *multisample_mt = NULL;
914   struct gl_renderbuffer *rb = &irb->Base.Base;
915   mesa_format format = rb->Format;
916   const unsigned num_samples = MAX2(rb->NumSamples, 1);
917
918   /* Only the front and back buffers, which are color buffers, are allocated
919    * through the image loader.
920    */
921   assert(_mesa_get_format_base_format(format) == GL_RGB ||
922          _mesa_get_format_base_format(format) == GL_RGBA);
923
924   assert(singlesample_mt);
925
926   if (num_samples == 1) {
927      brw_miptree_release(&irb->mt);
928      irb->mt = singlesample_mt;
929
930      assert(!irb->singlesample_mt);
931   } else {
932      brw_miptree_release(&irb->singlesample_mt);
933      irb->singlesample_mt = singlesample_mt;
934
935      if (!irb->mt ||
936          irb->mt->surf.logical_level0_px.width != width ||
937          irb->mt->surf.logical_level0_px.height != height) {
938         multisample_mt = brw_miptree_create_for_renderbuffer(intel,
939                                                              format,
940                                                              width,
941                                                              height,
942                                                              num_samples);
943         if (!multisample_mt)
944            goto fail;
945
946         irb->need_downsample = false;
947         brw_miptree_release(&irb->mt);
948         irb->mt = multisample_mt;
949      }
950   }
951   return true;
952
953fail:
954   brw_miptree_release(&irb->mt);
955   return false;
956}
957
958struct brw_mipmap_tree*
959brw_miptree_create_for_renderbuffer(struct brw_context *brw,
960                                    mesa_format format,
961                                    uint32_t width,
962                                    uint32_t height,
963                                    uint32_t num_samples)
964{
965   struct brw_mipmap_tree *mt;
966   uint32_t depth = 1;
967   GLenum target = num_samples > 1 ? GL_TEXTURE_2D_MULTISAMPLE : GL_TEXTURE_2D;
968
969   mt = brw_miptree_create(brw, target, format, 0, 0,
970                           width, height, depth, num_samples,
971                           MIPTREE_CREATE_BUSY);
972   if (!mt)
973      goto fail;
974
975   return mt;
976
977fail:
978   brw_miptree_release(&mt);
979   return NULL;
980}
981
982void
983brw_miptree_reference(struct brw_mipmap_tree **dst,
984                      struct brw_mipmap_tree *src)
985{
986   if (*dst == src)
987      return;
988
989   brw_miptree_release(dst);
990
991   if (src) {
992      src->refcount++;
993      DBG("%s %p refcount now %d\n", __func__, src, src->refcount);
994   }
995
996   *dst = src;
997}
998
999static void
1000brw_miptree_aux_buffer_free(struct brw_miptree_aux_buffer *aux_buf)
1001{
1002   if (aux_buf == NULL)
1003      return;
1004
1005   brw_bo_unreference(aux_buf->bo);
1006   brw_bo_unreference(aux_buf->clear_color_bo);
1007
1008   free(aux_buf);
1009}
1010
1011void
1012brw_miptree_release(struct brw_mipmap_tree **mt)
1013{
1014   if (!*mt)
1015      return;
1016
1017   DBG("%s %p refcount will be %d\n", __func__, *mt, (*mt)->refcount - 1);
1018   if (--(*mt)->refcount <= 0) {
1019      GLuint i;
1020
1021      DBG("%s deleting %p\n", __func__, *mt);
1022
1023      brw_bo_unreference((*mt)->bo);
1024      brw_miptree_release(&(*mt)->stencil_mt);
1025      brw_miptree_release(&(*mt)->shadow_mt);
1026      brw_miptree_aux_buffer_free((*mt)->aux_buf);
1027      free_aux_state_map((*mt)->aux_state);
1028
1029      brw_miptree_release(&(*mt)->plane[0]);
1030      brw_miptree_release(&(*mt)->plane[1]);
1031
1032      for (i = 0; i < MAX_TEXTURE_LEVELS; i++) {
1033         free((*mt)->level[i].slice);
1034      }
1035
1036      free(*mt);
1037   }
1038   *mt = NULL;
1039}
1040
1041
1042void
1043brw_get_image_dims(struct gl_texture_image *image,
1044                     int *width, int *height, int *depth)
1045{
1046   switch (image->TexObject->Target) {
1047   case GL_TEXTURE_1D_ARRAY:
1048      /* For a 1D Array texture the OpenGL API will treat the image height as
1049       * the number of array slices. For Intel hardware, we treat the 1D array
1050       * as a 2D Array with a height of 1. So, here we want to swap image
1051       * height and depth.
1052       */
1053      assert(image->Depth == 1);
1054      *width = image->Width;
1055      *height = 1;
1056      *depth = image->Height;
1057      break;
1058   case GL_TEXTURE_CUBE_MAP:
1059      /* For Cube maps, the mesa/main api layer gives us a depth of 1 even
1060       * though we really have 6 slices.
1061       */
1062      assert(image->Depth == 1);
1063      *width = image->Width;
1064      *height = image->Height;
1065      *depth = 6;
1066      break;
1067   default:
1068      *width = image->Width;
1069      *height = image->Height;
1070      *depth = image->Depth;
1071      break;
1072   }
1073}
1074
1075/**
1076 * Can the image be pulled into a unified mipmap tree?  This mirrors
1077 * the completeness test in a lot of ways.
1078 *
1079 * Not sure whether I want to pass gl_texture_image here.
1080 */
1081bool
1082brw_miptree_match_image(struct brw_mipmap_tree *mt,
1083                        struct gl_texture_image *image)
1084{
1085   struct brw_texture_image *brw_image = brw_texture_image(image);
1086   GLuint level = brw_image->base.Base.Level;
1087   int width, height, depth;
1088
1089   /* glTexImage* choose the texture object based on the target passed in, and
1090    * objects can't change targets over their lifetimes, so this should be
1091    * true.
1092    */
1093   assert(image->TexObject->Target == mt->target);
1094
1095   mesa_format mt_format = mt->format;
1096   if (mt->format == MESA_FORMAT_Z24_UNORM_X8_UINT && mt->stencil_mt)
1097      mt_format = MESA_FORMAT_Z24_UNORM_S8_UINT;
1098   if (mt->format == MESA_FORMAT_Z_FLOAT32 && mt->stencil_mt)
1099      mt_format = MESA_FORMAT_Z32_FLOAT_S8X24_UINT;
1100
1101   if (_mesa_get_srgb_format_linear(image->TexFormat) !=
1102       _mesa_get_srgb_format_linear(mt_format))
1103      return false;
1104
1105   brw_get_image_dims(image, &width, &height, &depth);
1106
1107   if (mt->target == GL_TEXTURE_CUBE_MAP)
1108      depth = 6;
1109
1110   if (level >= mt->surf.levels)
1111      return false;
1112
1113   const unsigned level_depth =
1114      mt->surf.dim == ISL_SURF_DIM_3D ?
1115         minify(mt->surf.logical_level0_px.depth, level) :
1116         mt->surf.logical_level0_px.array_len;
1117
1118   return width == minify(mt->surf.logical_level0_px.width, level) &&
1119          height == minify(mt->surf.logical_level0_px.height, level) &&
1120          depth == level_depth &&
1121          MAX2(image->NumSamples, 1) == mt->surf.samples;
1122}
1123
1124void
1125brw_miptree_get_image_offset(const struct brw_mipmap_tree *mt,
1126                             GLuint level, GLuint slice,
1127                             GLuint *x, GLuint *y)
1128{
1129   if (level == 0 && slice == 0) {
1130      *x = mt->level[0].level_x;
1131      *y = mt->level[0].level_y;
1132      return;
1133   }
1134
1135   uint32_t x_offset_sa, y_offset_sa, z_offset_sa, array_offset;
1136
1137   /* Miptree itself can have an offset only if it represents a single
1138    * slice in an imported buffer object.
1139    * See brw_miptree_create_for_dri_image().
1140    */
1141   assert(mt->level[0].level_x == 0);
1142   assert(mt->level[0].level_y == 0);
1143
1144   /* Given level is relative to level zero while the miptree may be
1145    * represent just a subset of all levels starting from 'first_level'.
1146    */
1147   assert(level >= mt->first_level);
1148   level -= mt->first_level;
1149
1150   const unsigned z = mt->surf.dim == ISL_SURF_DIM_3D ? slice : 0;
1151   slice = mt->surf.dim == ISL_SURF_DIM_3D ? 0 : slice;
1152   isl_surf_get_image_offset_el(&mt->surf, level, slice, z,
1153                                &x_offset_sa, &y_offset_sa,
1154                                &z_offset_sa, &array_offset);
1155
1156   *x = x_offset_sa;
1157   *y = y_offset_sa;
1158   assert(z_offset_sa == 0);
1159   assert(array_offset == 0);
1160}
1161
1162/**
1163 * Compute the offset (in bytes) from the start of the BO to the given x
1164 * and y coordinate.  For tiled BOs, caller must ensure that x and y are
1165 * multiples of the tile size.
1166 */
1167uint32_t
1168brw_miptree_get_aligned_offset(const struct brw_mipmap_tree *mt,
1169                               uint32_t x, uint32_t y)
1170{
1171   int cpp = mt->cpp;
1172   uint32_t pitch = mt->surf.row_pitch_B;
1173
1174   switch (mt->surf.tiling) {
1175   default:
1176      unreachable("not reached");
1177   case ISL_TILING_LINEAR:
1178      return y * pitch + x * cpp;
1179   case ISL_TILING_X:
1180      assert((x % (512 / cpp)) == 0);
1181      assert((y % 8) == 0);
1182      return y * pitch + x / (512 / cpp) * 4096;
1183   case ISL_TILING_Y0:
1184      assert((x % (128 / cpp)) == 0);
1185      assert((y % 32) == 0);
1186      return y * pitch + x / (128 / cpp) * 4096;
1187   }
1188}
1189
1190/**
1191 * Rendering with tiled buffers requires that the base address of the buffer
1192 * be aligned to a page boundary.  For renderbuffers, and sometimes with
1193 * textures, we may want the surface to point at a texture image level that
1194 * isn't at a page boundary.
1195 *
1196 * This function returns an appropriately-aligned base offset
1197 * according to the tiling restrictions, plus any required x/y offset
1198 * from there.
1199 */
1200uint32_t
1201brw_miptree_get_tile_offsets(const struct brw_mipmap_tree *mt,
1202                             GLuint level, GLuint slice,
1203                             uint32_t *tile_x,
1204                             uint32_t *tile_y)
1205{
1206   uint32_t x, y;
1207   uint32_t mask_x, mask_y;
1208
1209   isl_get_tile_masks(mt->surf.tiling, mt->cpp, &mask_x, &mask_y);
1210   brw_miptree_get_image_offset(mt, level, slice, &x, &y);
1211
1212   *tile_x = x & mask_x;
1213   *tile_y = y & mask_y;
1214
1215   return brw_miptree_get_aligned_offset(mt, x & ~mask_x, y & ~mask_y);
1216}
1217
1218static void
1219brw_miptree_copy_slice_sw(struct brw_context *brw,
1220                          struct brw_mipmap_tree *src_mt,
1221                          unsigned src_level, unsigned src_layer,
1222                          struct brw_mipmap_tree *dst_mt,
1223                          unsigned dst_level, unsigned dst_layer,
1224                          unsigned width, unsigned height)
1225{
1226   void *src, *dst;
1227   ptrdiff_t src_stride, dst_stride;
1228   const unsigned cpp = (isl_format_get_layout(dst_mt->surf.format)->bpb / 8);
1229
1230   brw_miptree_map(brw, src_mt,
1231                   src_level, src_layer,
1232                   0, 0,
1233                   width, height,
1234                   GL_MAP_READ_BIT | BRW_MAP_DIRECT_BIT,
1235                   &src, &src_stride);
1236
1237   brw_miptree_map(brw, dst_mt,
1238                   dst_level, dst_layer,
1239                   0, 0,
1240                   width, height,
1241                   GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_RANGE_BIT |
1242                   BRW_MAP_DIRECT_BIT,
1243                   &dst, &dst_stride);
1244
1245   DBG("sw blit %s mt %p %p/%"PRIdPTR" -> %s mt %p %p/%"PRIdPTR" (%dx%d)\n",
1246       _mesa_get_format_name(src_mt->format),
1247       src_mt, src, src_stride,
1248       _mesa_get_format_name(dst_mt->format),
1249       dst_mt, dst, dst_stride,
1250       width, height);
1251
1252   int row_size = cpp * width;
1253   if (src_stride == row_size &&
1254       dst_stride == row_size) {
1255      memcpy(dst, src, row_size * height);
1256   } else {
1257      for (int i = 0; i < height; i++) {
1258         memcpy(dst, src, row_size);
1259         dst += dst_stride;
1260         src += src_stride;
1261      }
1262   }
1263
1264   brw_miptree_unmap(brw, dst_mt, dst_level, dst_layer);
1265   brw_miptree_unmap(brw, src_mt, src_level, src_layer);
1266
1267   /* Don't forget to copy the stencil data over, too.  We could have skipped
1268    * passing BRW_MAP_DIRECT_BIT, but that would have meant brw_miptree_map
1269    * shuffling the two data sources in/out of temporary storage instead of
1270    * the direct mapping we get this way.
1271    */
1272   if (dst_mt->stencil_mt) {
1273      assert(src_mt->stencil_mt);
1274      brw_miptree_copy_slice_sw(brw,
1275                                src_mt->stencil_mt, src_level, src_layer,
1276                                dst_mt->stencil_mt, dst_level, dst_layer,
1277                                width, height);
1278   }
1279}
1280
1281void
1282brw_miptree_copy_slice(struct brw_context *brw,
1283                       struct brw_mipmap_tree *src_mt,
1284                       unsigned src_level, unsigned src_layer,
1285                       struct brw_mipmap_tree *dst_mt,
1286                       unsigned dst_level, unsigned dst_layer)
1287{
1288   const struct intel_device_info *devinfo = &brw->screen->devinfo;
1289   mesa_format format = src_mt->format;
1290   unsigned width = minify(src_mt->surf.phys_level0_sa.width,
1291                           src_level - src_mt->first_level);
1292   unsigned height = minify(src_mt->surf.phys_level0_sa.height,
1293                            src_level - src_mt->first_level);
1294
1295   assert(src_layer < get_num_phys_layers(&src_mt->surf,
1296                                          src_level - src_mt->first_level));
1297
1298   assert(_mesa_get_srgb_format_linear(src_mt->format) ==
1299          _mesa_get_srgb_format_linear(dst_mt->format));
1300
1301   DBG("validate blit mt %s %p %d,%d -> mt %s %p %d,%d (%dx%d)\n",
1302       _mesa_get_format_name(src_mt->format),
1303       src_mt, src_level, src_layer,
1304       _mesa_get_format_name(dst_mt->format),
1305       dst_mt, dst_level, dst_layer,
1306       width, height);
1307
1308   if (devinfo->ver >= 6) {
1309      /* On gfx6 and above, we just use blorp.  It's faster than the blitter
1310       * and can handle everything without software fallbacks.
1311       */
1312      brw_blorp_copy_miptrees(brw,
1313                              src_mt, src_level, src_layer,
1314                              dst_mt, dst_level, dst_layer,
1315                              0, 0, 0, 0, width, height);
1316
1317      if (src_mt->stencil_mt) {
1318         assert(dst_mt->stencil_mt);
1319         brw_blorp_copy_miptrees(brw,
1320                                 src_mt->stencil_mt, src_level, src_layer,
1321                                 dst_mt->stencil_mt, dst_level, dst_layer,
1322                                 0, 0, 0, 0, width, height);
1323      }
1324      return;
1325   }
1326
1327   if (dst_mt->compressed) {
1328      unsigned int i, j;
1329      _mesa_get_format_block_size(dst_mt->format, &i, &j);
1330      height = ALIGN_NPOT(height, j) / j;
1331      width = ALIGN_NPOT(width, i) / i;
1332   }
1333
1334   /* Gfx4-5 doesn't support separate stencil */
1335   assert(!src_mt->stencil_mt);
1336
1337   uint32_t dst_x, dst_y, src_x, src_y;
1338   brw_miptree_get_image_offset(dst_mt, dst_level, dst_layer, &dst_x, &dst_y);
1339   brw_miptree_get_image_offset(src_mt, src_level, src_layer, &src_x, &src_y);
1340
1341   DBG("validate blit mt %s %p %d,%d/%d -> mt %s %p %d,%d/%d (%dx%d)\n",
1342       _mesa_get_format_name(src_mt->format),
1343       src_mt, src_x, src_y, src_mt->surf.row_pitch_B,
1344       _mesa_get_format_name(dst_mt->format),
1345       dst_mt, dst_x, dst_y, dst_mt->surf.row_pitch_B,
1346       width, height);
1347
1348   if (!brw_miptree_blit(brw,
1349                           src_mt, src_level, src_layer, 0, 0, false,
1350                           dst_mt, dst_level, dst_layer, 0, 0, false,
1351                           width, height, COLOR_LOGICOP_COPY)) {
1352      perf_debug("miptree validate blit for %s failed\n",
1353                 _mesa_get_format_name(format));
1354
1355      brw_miptree_copy_slice_sw(brw,
1356                                src_mt, src_level, src_layer,
1357                                dst_mt, dst_level, dst_layer,
1358                                width, height);
1359   }
1360}
1361
1362/**
1363 * Copies the image's current data to the given miptree, and associates that
1364 * miptree with the image.
1365 */
1366void
1367brw_miptree_copy_teximage(struct brw_context *brw,
1368                          struct brw_texture_image *brw_image,
1369                          struct brw_mipmap_tree *dst_mt)
1370{
1371   struct brw_mipmap_tree *src_mt = brw_image->mt;
1372   struct brw_texture_object *intel_obj =
1373      brw_texture_object(brw_image->base.Base.TexObject);
1374   int level = brw_image->base.Base.Level;
1375   const unsigned face = brw_image->base.Base.Face;
1376   unsigned start_layer, end_layer;
1377
1378   if (intel_obj->base.Target == GL_TEXTURE_1D_ARRAY) {
1379      assert(face == 0);
1380      assert(brw_image->base.Base.Height);
1381      start_layer = 0;
1382      end_layer = brw_image->base.Base.Height - 1;
1383   } else if (face > 0) {
1384      start_layer = face;
1385      end_layer = face;
1386   } else {
1387      assert(brw_image->base.Base.Depth);
1388      start_layer = 0;
1389      end_layer = brw_image->base.Base.Depth - 1;
1390   }
1391
1392   for (unsigned i = start_layer; i <= end_layer; i++) {
1393      brw_miptree_copy_slice(brw, src_mt, level, i, dst_mt, level, i);
1394   }
1395
1396   brw_miptree_reference(&brw_image->mt, dst_mt);
1397   intel_obj->needs_validate = true;
1398}
1399
1400static struct brw_miptree_aux_buffer *
1401brw_alloc_aux_buffer(struct brw_context *brw,
1402                       const struct isl_surf *aux_surf,
1403                       bool wants_memset,
1404                       uint8_t memset_value)
1405{
1406   struct brw_miptree_aux_buffer *buf = calloc(sizeof(*buf), 1);
1407   if (!buf)
1408      return false;
1409
1410   uint64_t size = aux_surf->size_B;
1411
1412   const bool has_indirect_clear = brw->isl_dev.ss.clear_color_state_size > 0;
1413   if (has_indirect_clear) {
1414      /* On CNL+, instead of setting the clear color in the SURFACE_STATE, we
1415       * will set a pointer to a dword somewhere that contains the color. So,
1416       * allocate the space for the clear color value here on the aux buffer.
1417       */
1418      buf->clear_color_offset = size;
1419      size += brw->isl_dev.ss.clear_color_state_size;
1420   }
1421
1422   /* If the buffer needs to be initialised (requiring the buffer to be
1423    * immediately mapped to cpu space for writing), do not use the gpu access
1424    * flag which can cause an unnecessary delay if the backing pages happened
1425    * to be just used by the GPU.
1426    */
1427   const bool alloc_zeroed = wants_memset && memset_value == 0;
1428   const bool needs_memset =
1429      !alloc_zeroed && (wants_memset || has_indirect_clear);
1430   const uint32_t alloc_flags =
1431      alloc_zeroed ? BO_ALLOC_ZEROED : (needs_memset ? 0 : BO_ALLOC_BUSY);
1432
1433   /* ISL has stricter set of alignment rules then the drm allocator.
1434    * Therefore one can pass the ISL dimensions in terms of bytes instead of
1435    * trying to recalculate based on different format block sizes.
1436    */
1437   buf->bo = brw_bo_alloc_tiled(brw->bufmgr, "aux-miptree", size,
1438                                BRW_MEMZONE_OTHER, I915_TILING_Y,
1439                                aux_surf->row_pitch_B, alloc_flags);
1440   if (!buf->bo) {
1441      free(buf);
1442      return NULL;
1443   }
1444
1445   /* Initialize the bo to the desired value */
1446   if (needs_memset) {
1447      assert(!(alloc_flags & BO_ALLOC_BUSY));
1448
1449      void *map = brw_bo_map(brw, buf->bo, MAP_WRITE | MAP_RAW);
1450      if (map == NULL) {
1451         brw_miptree_aux_buffer_free(buf);
1452         return NULL;
1453      }
1454
1455      /* Memset the aux_surf portion of the BO. */
1456      if (wants_memset)
1457         memset(map, memset_value, aux_surf->size_B);
1458
1459      /* Zero the indirect clear color to match ::fast_clear_color. */
1460      if (has_indirect_clear) {
1461         memset((char *)map + buf->clear_color_offset, 0,
1462                brw->isl_dev.ss.clear_color_state_size);
1463      }
1464
1465      brw_bo_unmap(buf->bo);
1466   }
1467
1468   if (has_indirect_clear) {
1469      buf->clear_color_bo = buf->bo;
1470      brw_bo_reference(buf->clear_color_bo);
1471   }
1472
1473   buf->surf = *aux_surf;
1474
1475   return buf;
1476}
1477
1478
1479/**
1480 * Helper for brw_miptree_alloc_aux() that sets
1481 * \c mt->level[level].has_hiz. Return true if and only if
1482 * \c has_hiz was set.
1483 */
1484static bool
1485brw_miptree_level_enable_hiz(struct brw_context *brw,
1486                             struct brw_mipmap_tree *mt,
1487                             uint32_t level)
1488{
1489   const struct intel_device_info *devinfo = &brw->screen->devinfo;
1490
1491   assert(mt->aux_buf);
1492   assert(mt->surf.size_B > 0);
1493
1494   if (devinfo->verx10 >= 75) {
1495      uint32_t width = minify(mt->surf.phys_level0_sa.width, level);
1496      uint32_t height = minify(mt->surf.phys_level0_sa.height, level);
1497
1498      /* Disable HiZ for LOD > 0 unless the width is 8 aligned
1499       * and the height is 4 aligned. This allows our HiZ support
1500       * to fulfill Haswell restrictions for HiZ ops. For LOD == 0,
1501       * we can grow the width & height to allow the HiZ op to
1502       * force the proper size alignments.
1503       */
1504      if (level > 0 && ((width & 7) || (height & 3))) {
1505         DBG("mt %p level %d: HiZ DISABLED\n", mt, level);
1506         return false;
1507      }
1508   }
1509
1510   DBG("mt %p level %d: HiZ enabled\n", mt, level);
1511   mt->level[level].has_hiz = true;
1512   return true;
1513}
1514
1515
1516/**
1517 * Allocate the initial aux surface for a miptree based on mt->aux_usage
1518 *
1519 * Since MCS, HiZ, and CCS_E can compress more than just clear color, we
1520 * create the auxiliary surfaces up-front.  CCS_D, on the other hand, can only
1521 * compress clear color so we wait until an actual fast-clear to allocate it.
1522 */
1523bool
1524brw_miptree_alloc_aux(struct brw_context *brw, struct brw_mipmap_tree *mt)
1525{
1526   assert(mt->aux_buf == NULL);
1527
1528   /* Get the aux buf allocation parameters for this miptree. */
1529   enum isl_aux_state initial_state;
1530   uint8_t memset_value;
1531   struct isl_surf aux_surf = {0,};
1532   bool aux_surf_ok = false;
1533
1534   switch (mt->aux_usage) {
1535   case ISL_AUX_USAGE_NONE:
1536      aux_surf.size_B = 0;
1537      aux_surf_ok = true;
1538      break;
1539   case ISL_AUX_USAGE_HIZ:
1540      initial_state = ISL_AUX_STATE_AUX_INVALID;
1541      memset_value = 0;
1542      aux_surf_ok = isl_surf_get_hiz_surf(&brw->isl_dev, &mt->surf, &aux_surf);
1543      break;
1544   case ISL_AUX_USAGE_MCS:
1545      /* From the Ivy Bridge PRM, Vol 2 Part 1 p326:
1546       *
1547       *     When MCS buffer is enabled and bound to MSRT, it is required that
1548       *     it is cleared prior to any rendering.
1549       *
1550       * Since we don't use the MCS buffer for any purpose other than
1551       * rendering, it makes sense to just clear it immediately upon
1552       * allocation.
1553       *
1554       * Note: the clear value for MCS buffers is all 1's, so we memset to
1555       * 0xff.
1556       */
1557      initial_state = ISL_AUX_STATE_CLEAR;
1558      memset_value = 0xFF;
1559      aux_surf_ok = isl_surf_get_mcs_surf(&brw->isl_dev, &mt->surf, &aux_surf);
1560      break;
1561   case ISL_AUX_USAGE_CCS_D:
1562   case ISL_AUX_USAGE_CCS_E:
1563      /* When CCS_E is used, we need to ensure that the CCS starts off in a
1564       * valid state.  From the Sky Lake PRM, "MCS Buffer for Render
1565       * Target(s)":
1566       *
1567       *    "If Software wants to enable Color Compression without Fast
1568       *    clear, Software needs to initialize MCS with zeros."
1569       *
1570       * A CCS value of 0 indicates that the corresponding block is in the
1571       * pass-through state which is what we want.
1572       *
1573       * For CCS_D, do the same thing. On gfx9+, this avoids having any
1574       * undefined bits in the aux buffer.
1575       */
1576      initial_state = ISL_AUX_STATE_PASS_THROUGH;
1577      memset_value = 0;
1578      aux_surf_ok =
1579         isl_surf_get_ccs_surf(&brw->isl_dev, &mt->surf, NULL, &aux_surf, 0);
1580      break;
1581
1582   default:
1583      unreachable("Invalid aux usage");
1584   }
1585
1586   /* We should have a valid aux_surf. */
1587   if (!aux_surf_ok)
1588      return false;
1589
1590   /* No work is needed for a zero-sized auxiliary buffer. */
1591   if (aux_surf.size_B == 0)
1592      return true;
1593
1594   /* Create the aux_state for the auxiliary buffer. */
1595   mt->aux_state = create_aux_state_map(mt, initial_state);
1596   if (mt->aux_state == NULL)
1597      return false;
1598
1599   /* Allocate the auxiliary buffer. */
1600   const bool needs_memset = initial_state != ISL_AUX_STATE_AUX_INVALID;
1601   mt->aux_buf = brw_alloc_aux_buffer(brw, &aux_surf, needs_memset,
1602                                        memset_value);
1603   if (mt->aux_buf == NULL) {
1604      free_aux_state_map(mt->aux_state);
1605      mt->aux_state = NULL;
1606      return false;
1607   }
1608
1609   /* Perform aux_usage-specific initialization. */
1610   if (mt->aux_usage == ISL_AUX_USAGE_HIZ) {
1611      for (unsigned level = mt->first_level; level <= mt->last_level; ++level)
1612         brw_miptree_level_enable_hiz(brw, mt, level);
1613   }
1614
1615   return true;
1616}
1617
1618
1619/**
1620 * Can the miptree sample using the hiz buffer?
1621 */
1622bool
1623brw_miptree_sample_with_hiz(struct brw_context *brw,
1624                            struct brw_mipmap_tree *mt)
1625{
1626   const struct intel_device_info *devinfo = &brw->screen->devinfo;
1627
1628   if (!devinfo->has_sample_with_hiz) {
1629      return false;
1630   }
1631
1632   if (!mt->aux_buf) {
1633      return false;
1634   }
1635
1636   for (unsigned level = 0; level < mt->surf.levels; ++level) {
1637      if (!brw_miptree_level_has_hiz(mt, level))
1638         return false;
1639   }
1640
1641   /* From the BDW PRM (Volume 2d: Command Reference: Structures
1642    *                   RENDER_SURFACE_STATE.AuxiliarySurfaceMode):
1643    *
1644    *  "If this field is set to AUX_HIZ, Number of Multisamples must be
1645    *   MULTISAMPLECOUNT_1, and Surface Type cannot be SURFTYPE_3D.
1646    *
1647    * There is no such blurb for 1D textures, but there is sufficient evidence
1648    * that this is broken on SKL+.
1649    */
1650   return (mt->surf.samples == 1 &&
1651           mt->target != GL_TEXTURE_3D &&
1652           mt->target != GL_TEXTURE_1D /* gfx9+ restriction */);
1653}
1654
1655static bool
1656level_has_aux(const struct brw_mipmap_tree *mt, uint32_t level)
1657{
1658   return isl_aux_usage_has_hiz(mt->aux_usage) ?
1659          brw_miptree_level_has_hiz(mt, level) :
1660          mt->aux_usage != ISL_AUX_USAGE_NONE && mt->aux_buf;
1661}
1662
1663/**
1664 * Does the miptree slice have hiz enabled?
1665 */
1666bool
1667brw_miptree_level_has_hiz(const struct brw_mipmap_tree *mt, uint32_t level)
1668{
1669   brw_miptree_check_level_layer(mt, level, 0);
1670   return mt->level[level].has_hiz;
1671}
1672
1673static inline uint32_t
1674miptree_level_range_length(const struct brw_mipmap_tree *mt,
1675                           uint32_t start_level, uint32_t num_levels)
1676{
1677   assert(start_level >= mt->first_level);
1678   assert(start_level <= mt->last_level);
1679
1680   if (num_levels == INTEL_REMAINING_LAYERS)
1681      num_levels = mt->last_level - start_level + 1;
1682   /* Check for overflow */
1683   assert(start_level + num_levels >= start_level);
1684   assert(start_level + num_levels <= mt->last_level + 1);
1685
1686   return num_levels;
1687}
1688
1689static inline uint32_t
1690miptree_layer_range_length(const struct brw_mipmap_tree *mt, uint32_t level,
1691                           uint32_t start_layer, uint32_t num_layers)
1692{
1693   assert(level <= mt->last_level);
1694
1695   const uint32_t total_num_layers = brw_get_num_logical_layers(mt, level);
1696   assert(start_layer < total_num_layers);
1697   if (num_layers == INTEL_REMAINING_LAYERS)
1698      num_layers = total_num_layers - start_layer;
1699   /* Check for overflow */
1700   assert(start_layer + num_layers >= start_layer);
1701   assert(start_layer + num_layers <= total_num_layers);
1702
1703   return num_layers;
1704}
1705
1706bool
1707brw_miptree_has_color_unresolved(const struct brw_mipmap_tree *mt,
1708                                 unsigned start_level, unsigned num_levels,
1709                                 unsigned start_layer, unsigned num_layers)
1710{
1711   assert(_mesa_is_format_color_format(mt->format));
1712
1713   if (!mt->aux_buf)
1714      return false;
1715
1716   /* Clamp the level range to fit the miptree */
1717   num_levels = miptree_level_range_length(mt, start_level, num_levels);
1718
1719   for (uint32_t l = 0; l < num_levels; l++) {
1720      const uint32_t level = start_level + l;
1721      const uint32_t level_layers =
1722         miptree_layer_range_length(mt, level, start_layer, num_layers);
1723      for (unsigned a = 0; a < level_layers; a++) {
1724         enum isl_aux_state aux_state =
1725            brw_miptree_get_aux_state(mt, level, start_layer + a);
1726         assert(aux_state != ISL_AUX_STATE_AUX_INVALID);
1727         if (aux_state != ISL_AUX_STATE_PASS_THROUGH)
1728            return true;
1729      }
1730   }
1731
1732   return false;
1733}
1734
1735static void
1736brw_miptree_check_color_resolve(const struct brw_context *brw,
1737                                const struct brw_mipmap_tree *mt,
1738                                unsigned level, unsigned layer)
1739{
1740   if (!mt->aux_buf)
1741      return;
1742
1743   /* Fast color clear is supported for mipmapped surfaces only on Gfx8+. */
1744   assert(brw->screen->devinfo.ver >= 8 ||
1745          (level == 0 && mt->first_level == 0 && mt->last_level == 0));
1746
1747   /* Compression of arrayed msaa surfaces is supported. */
1748   if (mt->surf.samples > 1)
1749      return;
1750
1751   /* Fast color clear is supported for non-msaa arrays only on Gfx8+. */
1752   assert(brw->screen->devinfo.ver >= 8 ||
1753          (layer == 0 &&
1754           mt->surf.logical_level0_px.depth == 1 &&
1755           mt->surf.logical_level0_px.array_len == 1));
1756
1757   (void)level;
1758   (void)layer;
1759}
1760
1761void
1762brw_miptree_prepare_access(struct brw_context *brw,
1763                           struct brw_mipmap_tree *mt,
1764                           uint32_t start_level, uint32_t num_levels,
1765                           uint32_t start_layer, uint32_t num_layers,
1766                           enum isl_aux_usage aux_usage,
1767                           bool fast_clear_supported)
1768{
1769   const uint32_t clamped_levels =
1770      miptree_level_range_length(mt, start_level, num_levels);
1771   for (uint32_t l = 0; l < clamped_levels; l++) {
1772      const uint32_t level = start_level + l;
1773      if (!level_has_aux(mt, level))
1774         continue;
1775
1776      const uint32_t level_layers =
1777         miptree_layer_range_length(mt, level, start_layer, num_layers);
1778      for (uint32_t a = 0; a < level_layers; a++) {
1779         const uint32_t layer = start_layer + a;
1780         const enum isl_aux_state aux_state =
1781            brw_miptree_get_aux_state(mt, level, layer);
1782         const enum isl_aux_op aux_op =
1783            isl_aux_prepare_access(aux_state, aux_usage, fast_clear_supported);
1784
1785         if (aux_op == ISL_AUX_OP_NONE) {
1786            /* Nothing to do here. */
1787         } else if (isl_aux_usage_has_mcs(mt->aux_usage)) {
1788            assert(aux_op == ISL_AUX_OP_PARTIAL_RESOLVE);
1789            brw_blorp_mcs_partial_resolve(brw, mt, layer, 1);
1790         } else if (isl_aux_usage_has_hiz(mt->aux_usage)) {
1791            brw_hiz_exec(brw, mt, level, layer, 1, aux_op);
1792         } else {
1793            assert(isl_aux_usage_has_ccs(mt->aux_usage));
1794            brw_miptree_check_color_resolve(brw, mt, level, layer);
1795            brw_blorp_resolve_color(brw, mt, level, layer, aux_op);
1796         }
1797
1798         const enum isl_aux_state new_state =
1799            isl_aux_state_transition_aux_op(aux_state, mt->aux_usage, aux_op);
1800         brw_miptree_set_aux_state(brw, mt, level, layer, 1, new_state);
1801      }
1802   }
1803}
1804
1805void
1806brw_miptree_finish_write(struct brw_context *brw,
1807                         struct brw_mipmap_tree *mt, uint32_t level,
1808                         uint32_t start_layer, uint32_t num_layers,
1809                         enum isl_aux_usage aux_usage)
1810{
1811   const struct intel_device_info *devinfo = &brw->screen->devinfo;
1812
1813   if (mt->format == MESA_FORMAT_S_UINT8 && devinfo->ver <= 7) {
1814      mt->shadow_needs_update = true;
1815   } else if (brw_miptree_has_etc_shadow(brw, mt)) {
1816      mt->shadow_needs_update = true;
1817   }
1818
1819   if (!level_has_aux(mt, level))
1820      return;
1821
1822   const uint32_t level_layers =
1823      miptree_layer_range_length(mt, level, start_layer, num_layers);
1824
1825   for (uint32_t a = 0; a < level_layers; a++) {
1826      const uint32_t layer = start_layer + a;
1827      const enum isl_aux_state aux_state =
1828         brw_miptree_get_aux_state(mt, level, layer);
1829      const enum isl_aux_state new_aux_state =
1830         isl_aux_state_transition_write(aux_state, aux_usage, false);
1831      brw_miptree_set_aux_state(brw, mt, level, layer, 1, new_aux_state);
1832   }
1833}
1834
1835enum isl_aux_state
1836brw_miptree_get_aux_state(const struct brw_mipmap_tree *mt,
1837                          uint32_t level, uint32_t layer)
1838{
1839   brw_miptree_check_level_layer(mt, level, layer);
1840
1841   if (_mesa_is_format_color_format(mt->format)) {
1842      assert(mt->aux_buf != NULL);
1843      assert(mt->surf.samples == 1 ||
1844             mt->surf.msaa_layout == ISL_MSAA_LAYOUT_ARRAY);
1845   } else if (mt->format == MESA_FORMAT_S_UINT8) {
1846      unreachable("Cannot get aux state for stencil");
1847   } else {
1848      assert(brw_miptree_level_has_hiz(mt, level));
1849   }
1850
1851   return mt->aux_state[level][layer];
1852}
1853
1854void
1855brw_miptree_set_aux_state(struct brw_context *brw,
1856                          struct brw_mipmap_tree *mt, uint32_t level,
1857                          uint32_t start_layer, uint32_t num_layers,
1858                          enum isl_aux_state aux_state)
1859{
1860   num_layers = miptree_layer_range_length(mt, level, start_layer, num_layers);
1861
1862   if (_mesa_is_format_color_format(mt->format)) {
1863      assert(mt->aux_buf != NULL);
1864      assert(mt->surf.samples == 1 ||
1865             mt->surf.msaa_layout == ISL_MSAA_LAYOUT_ARRAY);
1866   } else if (mt->format == MESA_FORMAT_S_UINT8) {
1867      unreachable("Cannot get aux state for stencil");
1868   } else {
1869      assert(brw_miptree_level_has_hiz(mt, level));
1870   }
1871
1872   for (unsigned a = 0; a < num_layers; a++) {
1873      if (mt->aux_state[level][start_layer + a] != aux_state) {
1874         mt->aux_state[level][start_layer + a] = aux_state;
1875         brw->ctx.NewDriverState |= BRW_NEW_AUX_STATE;
1876      }
1877   }
1878}
1879
1880/* On Gfx9 color buffers may be compressed by the hardware (lossless
1881 * compression). There are, however, format restrictions and care needs to be
1882 * taken that the sampler engine is capable for re-interpreting a buffer with
1883 * format different the buffer was originally written with.
1884 *
1885 * For example, SRGB formats are not compressible and the sampler engine isn't
1886 * capable of treating RGBA_UNORM as SRGB_ALPHA. In such a case the underlying
1887 * color buffer needs to be resolved so that the sampling surface can be
1888 * sampled as non-compressed (i.e., without the auxiliary MCS buffer being
1889 * set).
1890 */
1891static bool
1892can_texture_with_ccs(struct brw_context *brw,
1893                     struct brw_mipmap_tree *mt,
1894                     enum isl_format view_format)
1895{
1896   if (mt->aux_usage != ISL_AUX_USAGE_CCS_E)
1897      return false;
1898
1899   if (!format_ccs_e_compat_with_miptree(&brw->screen->devinfo,
1900                                         mt, view_format)) {
1901      perf_debug("Incompatible sampling format (%s) for rbc (%s)\n",
1902                 isl_format_get_name(view_format),
1903                 _mesa_get_format_name(mt->format));
1904      return false;
1905   }
1906
1907   return true;
1908}
1909
1910enum isl_aux_usage
1911brw_miptree_texture_aux_usage(struct brw_context *brw,
1912                              struct brw_mipmap_tree *mt,
1913                              enum isl_format view_format,
1914                              enum gfx9_astc5x5_wa_tex_type astc5x5_wa_bits)
1915{
1916   assert(brw->screen->devinfo.ver == 9 || astc5x5_wa_bits == 0);
1917
1918   /* On gfx9, ASTC 5x5 textures cannot live in the sampler cache along side
1919    * CCS or HiZ compressed textures.  See gfx9_apply_astc5x5_wa_flush() for
1920    * details.
1921    */
1922   if ((astc5x5_wa_bits & GFX9_ASTC5X5_WA_TEX_TYPE_ASTC5x5) &&
1923       mt->aux_usage != ISL_AUX_USAGE_MCS)
1924      return ISL_AUX_USAGE_NONE;
1925
1926   switch (mt->aux_usage) {
1927   case ISL_AUX_USAGE_HIZ:
1928      if (brw_miptree_sample_with_hiz(brw, mt))
1929         return ISL_AUX_USAGE_HIZ;
1930      break;
1931
1932   case ISL_AUX_USAGE_MCS:
1933      return ISL_AUX_USAGE_MCS;
1934
1935   case ISL_AUX_USAGE_CCS_D:
1936   case ISL_AUX_USAGE_CCS_E:
1937      if (!mt->aux_buf) {
1938         assert(mt->aux_usage == ISL_AUX_USAGE_CCS_D);
1939         return ISL_AUX_USAGE_NONE;
1940      }
1941
1942      /* If we don't have any unresolved color, report an aux usage of
1943       * ISL_AUX_USAGE_NONE.  This way, texturing won't even look at the
1944       * aux surface and we can save some bandwidth.
1945       */
1946      if (!brw_miptree_has_color_unresolved(mt, 0, INTEL_REMAINING_LEVELS,
1947                                              0, INTEL_REMAINING_LAYERS))
1948         return ISL_AUX_USAGE_NONE;
1949
1950      if (can_texture_with_ccs(brw, mt, view_format))
1951         return ISL_AUX_USAGE_CCS_E;
1952      break;
1953
1954   default:
1955      break;
1956   }
1957
1958   return ISL_AUX_USAGE_NONE;
1959}
1960
1961static bool
1962isl_formats_are_fast_clear_compatible(enum isl_format a, enum isl_format b)
1963{
1964   /* On gfx8 and earlier, the hardware was only capable of handling 0/1 clear
1965    * values so sRGB curve application was a no-op for all fast-clearable
1966    * formats.
1967    *
1968    * On gfx9+, the hardware supports arbitrary clear values.  For sRGB clear
1969    * values, the hardware interprets the floats, not as what would be
1970    * returned from the sampler (or written by the shader), but as being
1971    * between format conversion and sRGB curve application.  This means that
1972    * we can switch between sRGB and UNORM without having to whack the clear
1973    * color.
1974    */
1975   return isl_format_srgb_to_linear(a) == isl_format_srgb_to_linear(b);
1976}
1977
1978void
1979brw_miptree_prepare_texture(struct brw_context *brw,
1980                            struct brw_mipmap_tree *mt,
1981                            enum isl_format view_format,
1982                            uint32_t start_level, uint32_t num_levels,
1983                            uint32_t start_layer, uint32_t num_layers,
1984                            enum gfx9_astc5x5_wa_tex_type astc5x5_wa_bits)
1985{
1986   enum isl_aux_usage aux_usage =
1987      brw_miptree_texture_aux_usage(brw, mt, view_format, astc5x5_wa_bits);
1988
1989   bool clear_supported = aux_usage != ISL_AUX_USAGE_NONE;
1990
1991   /* Clear color is specified as ints or floats and the conversion is done by
1992    * the sampler.  If we have a texture view, we would have to perform the
1993    * clear color conversion manually.  Just disable clear color.
1994    */
1995   if (!isl_formats_are_fast_clear_compatible(mt->surf.format, view_format))
1996      clear_supported = false;
1997
1998   brw_miptree_prepare_access(brw, mt, start_level, num_levels,
1999                              start_layer, num_layers,
2000                              aux_usage, clear_supported);
2001}
2002
2003void
2004brw_miptree_prepare_image(struct brw_context *brw, struct brw_mipmap_tree *mt)
2005{
2006   /* The data port doesn't understand any compression */
2007   brw_miptree_prepare_access(brw, mt, 0, INTEL_REMAINING_LEVELS,
2008                              0, INTEL_REMAINING_LAYERS,
2009                              ISL_AUX_USAGE_NONE, false);
2010}
2011
2012enum isl_aux_usage
2013brw_miptree_render_aux_usage(struct brw_context *brw,
2014                             struct brw_mipmap_tree *mt,
2015                             enum isl_format render_format,
2016                             bool blend_enabled,
2017                             bool draw_aux_disabled)
2018{
2019   struct intel_device_info *devinfo = &brw->screen->devinfo;
2020
2021   if (draw_aux_disabled)
2022      return ISL_AUX_USAGE_NONE;
2023
2024   switch (mt->aux_usage) {
2025   case ISL_AUX_USAGE_MCS:
2026      assert(mt->aux_buf);
2027      return ISL_AUX_USAGE_MCS;
2028
2029   case ISL_AUX_USAGE_CCS_D:
2030   case ISL_AUX_USAGE_CCS_E:
2031      if (!mt->aux_buf) {
2032         assert(mt->aux_usage == ISL_AUX_USAGE_CCS_D);
2033         return ISL_AUX_USAGE_NONE;
2034      }
2035
2036      /* gfx9+ hardware technically supports non-0/1 clear colors with sRGB
2037       * formats.  However, there are issues with blending where it doesn't
2038       * properly apply the sRGB curve to the clear color when blending.
2039       */
2040      if (devinfo->ver >= 9 && blend_enabled &&
2041          isl_format_is_srgb(render_format) &&
2042          !isl_color_value_is_zero_one(mt->fast_clear_color, render_format))
2043         return ISL_AUX_USAGE_NONE;
2044
2045      if (mt->aux_usage == ISL_AUX_USAGE_CCS_E &&
2046          format_ccs_e_compat_with_miptree(&brw->screen->devinfo,
2047                                           mt, render_format))
2048         return ISL_AUX_USAGE_CCS_E;
2049
2050      /* Otherwise, we have to fall back to CCS_D */
2051      return ISL_AUX_USAGE_CCS_D;
2052
2053   default:
2054      return ISL_AUX_USAGE_NONE;
2055   }
2056}
2057
2058void
2059brw_miptree_prepare_render(struct brw_context *brw,
2060                           struct brw_mipmap_tree *mt, uint32_t level,
2061                           uint32_t start_layer, uint32_t layer_count,
2062                           enum isl_aux_usage aux_usage)
2063{
2064   brw_miptree_prepare_access(brw, mt, level, 1, start_layer, layer_count,
2065                              aux_usage, aux_usage != ISL_AUX_USAGE_NONE);
2066}
2067
2068void
2069brw_miptree_finish_render(struct brw_context *brw,
2070                          struct brw_mipmap_tree *mt, uint32_t level,
2071                          uint32_t start_layer, uint32_t layer_count,
2072                          enum isl_aux_usage aux_usage)
2073{
2074   assert(_mesa_is_format_color_format(mt->format));
2075
2076   brw_miptree_finish_write(brw, mt, level, start_layer, layer_count,
2077                              aux_usage);
2078}
2079
2080void
2081brw_miptree_prepare_depth(struct brw_context *brw,
2082                          struct brw_mipmap_tree *mt, uint32_t level,
2083                          uint32_t start_layer, uint32_t layer_count)
2084{
2085   brw_miptree_prepare_access(brw, mt, level, 1, start_layer, layer_count,
2086                              mt->aux_usage, mt->aux_buf != NULL);
2087}
2088
2089void
2090brw_miptree_finish_depth(struct brw_context *brw,
2091                         struct brw_mipmap_tree *mt, uint32_t level,
2092                         uint32_t start_layer, uint32_t layer_count,
2093                         bool depth_written)
2094{
2095   if (depth_written) {
2096      brw_miptree_finish_write(brw, mt, level, start_layer, layer_count,
2097                               mt->aux_usage);
2098   }
2099}
2100
2101void
2102brw_miptree_prepare_external(struct brw_context *brw,
2103                             struct brw_mipmap_tree *mt)
2104{
2105   enum isl_aux_usage aux_usage = ISL_AUX_USAGE_NONE;
2106   bool supports_fast_clear = false;
2107
2108   const struct isl_drm_modifier_info *mod_info =
2109      isl_drm_modifier_get_info(mt->drm_modifier);
2110
2111   if (mod_info && mod_info->aux_usage != ISL_AUX_USAGE_NONE) {
2112      /* CCS_E is the only supported aux for external images and it's only
2113       * supported on very simple images.
2114       */
2115      assert(mod_info->aux_usage == ISL_AUX_USAGE_CCS_E);
2116      assert(_mesa_is_format_color_format(mt->format));
2117      assert(mt->first_level == 0 && mt->last_level == 0);
2118      assert(mt->surf.logical_level0_px.depth == 1);
2119      assert(mt->surf.logical_level0_px.array_len == 1);
2120      assert(mt->surf.samples == 1);
2121      assert(mt->aux_buf != NULL);
2122
2123      aux_usage = mod_info->aux_usage;
2124      supports_fast_clear = mod_info->supports_clear_color;
2125   }
2126
2127   brw_miptree_prepare_access(brw, mt, 0, INTEL_REMAINING_LEVELS,
2128                              0, INTEL_REMAINING_LAYERS,
2129                              aux_usage, supports_fast_clear);
2130}
2131
2132void
2133brw_miptree_finish_external(struct brw_context *brw,
2134                            struct brw_mipmap_tree *mt)
2135{
2136   if (!mt->aux_buf)
2137      return;
2138
2139   /* We don't know the actual aux state of the aux surface.  The previous
2140    * owner could have given it to us in a number of different states.
2141    * Because we don't know the aux state, we reset the aux state to the
2142    * least common denominator of possible valid states.
2143    */
2144   enum isl_aux_state default_aux_state =
2145      isl_drm_modifier_get_default_aux_state(mt->drm_modifier);
2146   assert(mt->last_level == mt->first_level);
2147   brw_miptree_set_aux_state(brw, mt, 0, 0, INTEL_REMAINING_LAYERS,
2148                               default_aux_state);
2149}
2150
2151/**
2152 * Make it possible to share the BO backing the given miptree with another
2153 * process or another miptree.
2154 *
2155 * Fast color clears are unsafe with shared buffers, so we need to resolve and
2156 * then discard the MCS buffer, if present.  We also set the no_ccs flag to
2157 * ensure that no MCS buffer gets allocated in the future.
2158 *
2159 * HiZ is similarly unsafe with shared buffers.
2160 */
2161void
2162brw_miptree_make_shareable(struct brw_context *brw,
2163                           struct brw_mipmap_tree *mt)
2164{
2165   /* MCS buffers are also used for multisample buffers, but we can't resolve
2166    * away a multisample MCS buffer because it's an integral part of how the
2167    * pixel data is stored.  Fortunately this code path should never be
2168    * reached for multisample buffers.
2169    */
2170   assert(mt->surf.msaa_layout == ISL_MSAA_LAYOUT_NONE ||
2171          mt->surf.samples == 1);
2172
2173   brw_miptree_prepare_access(brw, mt, 0, INTEL_REMAINING_LEVELS,
2174                              0, INTEL_REMAINING_LAYERS,
2175                              ISL_AUX_USAGE_NONE, false);
2176
2177   if (mt->aux_buf) {
2178      brw_miptree_aux_buffer_free(mt->aux_buf);
2179      mt->aux_buf = NULL;
2180
2181      /* Make future calls of brw_miptree_level_has_hiz() return false. */
2182      for (uint32_t l = mt->first_level; l <= mt->last_level; ++l) {
2183         mt->level[l].has_hiz = false;
2184      }
2185
2186      free(mt->aux_state);
2187      mt->aux_state = NULL;
2188      brw->ctx.NewDriverState |= BRW_NEW_AUX_STATE;
2189   }
2190
2191   mt->aux_usage = ISL_AUX_USAGE_NONE;
2192   mt->supports_fast_clear = false;
2193}
2194
2195
2196/**
2197 * \brief Get pointer offset into stencil buffer.
2198 *
2199 * The stencil buffer is W tiled. Since the GTT is incapable of W fencing, we
2200 * must decode the tile's layout in software.
2201 *
2202 * See
2203 *   - PRM, 2011 Sandy Bridge, Volume 1, Part 2, Section 4.5.2.1 W-Major Tile
2204 *     Format.
2205 *   - PRM, 2011 Sandy Bridge, Volume 1, Part 2, Section 4.5.3 Tiling Algorithm
2206 *
2207 * Even though the returned offset is always positive, the return type is
2208 * signed due to
2209 *    commit e8b1c6d6f55f5be3bef25084fdd8b6127517e137
2210 *    mesa: Fix return type of  _mesa_get_format_bytes() (#37351)
2211 */
2212static intptr_t
2213brw_offset_S8(uint32_t stride, uint32_t x, uint32_t y, bool swizzled)
2214{
2215   uint32_t tile_size = 4096;
2216   uint32_t tile_width = 64;
2217   uint32_t tile_height = 64;
2218   uint32_t row_size = 64 * stride / 2; /* Two rows are interleaved. */
2219
2220   uint32_t tile_x = x / tile_width;
2221   uint32_t tile_y = y / tile_height;
2222
2223   /* The byte's address relative to the tile's base addres. */
2224   uint32_t byte_x = x % tile_width;
2225   uint32_t byte_y = y % tile_height;
2226
2227   uintptr_t u = tile_y * row_size
2228               + tile_x * tile_size
2229               + 512 * (byte_x / 8)
2230               +  64 * (byte_y / 8)
2231               +  32 * ((byte_y / 4) % 2)
2232               +  16 * ((byte_x / 4) % 2)
2233               +   8 * ((byte_y / 2) % 2)
2234               +   4 * ((byte_x / 2) % 2)
2235               +   2 * (byte_y % 2)
2236               +   1 * (byte_x % 2);
2237
2238   if (swizzled) {
2239      /* adjust for bit6 swizzling */
2240      if (((byte_x / 8) % 2) == 1) {
2241         if (((byte_y / 8) % 2) == 0) {
2242            u += 64;
2243         } else {
2244            u -= 64;
2245         }
2246      }
2247   }
2248
2249   return u;
2250}
2251
2252void
2253brw_miptree_updownsample(struct brw_context *brw,
2254                         struct brw_mipmap_tree *src,
2255                         struct brw_mipmap_tree *dst)
2256{
2257   unsigned src_w = src->surf.logical_level0_px.width;
2258   unsigned src_h = src->surf.logical_level0_px.height;
2259   unsigned dst_w = dst->surf.logical_level0_px.width;
2260   unsigned dst_h = dst->surf.logical_level0_px.height;
2261
2262   brw_blorp_blit_miptrees(brw,
2263                           src, 0 /* level */, 0 /* layer */,
2264                           src->format, SWIZZLE_XYZW,
2265                           dst, 0 /* level */, 0 /* layer */, dst->format,
2266                           0, 0, src_w, src_h,
2267                           0, 0, dst_w, dst_h,
2268                           GL_NEAREST, false, false /*mirror x, y*/,
2269                           false, false);
2270
2271   if (src->stencil_mt) {
2272      src_w = src->stencil_mt->surf.logical_level0_px.width;
2273      src_h = src->stencil_mt->surf.logical_level0_px.height;
2274      dst_w = dst->stencil_mt->surf.logical_level0_px.width;
2275      dst_h = dst->stencil_mt->surf.logical_level0_px.height;
2276
2277      brw_blorp_blit_miptrees(brw,
2278                              src->stencil_mt, 0 /* level */, 0 /* layer */,
2279                              src->stencil_mt->format, SWIZZLE_XYZW,
2280                              dst->stencil_mt, 0 /* level */, 0 /* layer */,
2281                              dst->stencil_mt->format,
2282                              0, 0, src_w, src_h,
2283                              0, 0, dst_w, dst_h,
2284                              GL_NEAREST, false, false /*mirror x, y*/,
2285                              false, false /* decode/encode srgb */);
2286   }
2287}
2288
2289void
2290brw_update_r8stencil(struct brw_context *brw,
2291                       struct brw_mipmap_tree *mt)
2292{
2293   const struct intel_device_info *devinfo = &brw->screen->devinfo;
2294
2295   assert(devinfo->ver >= 7);
2296   struct brw_mipmap_tree *src =
2297      mt->format == MESA_FORMAT_S_UINT8 ? mt : mt->stencil_mt;
2298   if (!src || devinfo->ver >= 8)
2299      return;
2300
2301   assert(src->surf.size_B > 0);
2302
2303   if (!mt->shadow_mt) {
2304      assert(devinfo->ver > 6); /* Handle MIPTREE_LAYOUT_GFX6_HIZ_STENCIL */
2305      mt->shadow_mt = make_surface(
2306                            brw,
2307                            src->target,
2308                            MESA_FORMAT_R_UINT8,
2309                            src->first_level, src->last_level,
2310                            src->surf.logical_level0_px.width,
2311                            src->surf.logical_level0_px.height,
2312                            src->surf.dim == ISL_SURF_DIM_3D ?
2313                               src->surf.logical_level0_px.depth :
2314                               src->surf.logical_level0_px.array_len,
2315                            src->surf.samples,
2316                            ISL_TILING_Y0_BIT,
2317                            ISL_SURF_USAGE_TEXTURE_BIT,
2318                            BO_ALLOC_BUSY, 0, NULL);
2319      assert(mt->shadow_mt);
2320   }
2321
2322   if (src->shadow_needs_update == false)
2323      return;
2324
2325   struct brw_mipmap_tree *dst = mt->shadow_mt;
2326
2327   for (int level = src->first_level; level <= src->last_level; level++) {
2328      const unsigned depth = src->surf.dim == ISL_SURF_DIM_3D ?
2329         minify(src->surf.phys_level0_sa.depth, level) :
2330         src->surf.phys_level0_sa.array_len;
2331
2332      for (unsigned layer = 0; layer < depth; layer++) {
2333         brw_blorp_copy_miptrees(brw,
2334                                 src, level, layer,
2335                                 dst, level, layer,
2336                                 0, 0, 0, 0,
2337                                 minify(src->surf.logical_level0_px.width,
2338                                        level),
2339                                 minify(src->surf.logical_level0_px.height,
2340                                        level));
2341      }
2342   }
2343
2344   brw_cache_flush_for_read(brw, dst->bo);
2345   src->shadow_needs_update = false;
2346}
2347
2348static void *
2349brw_miptree_map_raw(struct brw_context *brw,
2350                    struct brw_mipmap_tree *mt,
2351                    GLbitfield mode)
2352{
2353   struct brw_bo *bo = mt->bo;
2354
2355   if (brw_batch_references(&brw->batch, bo))
2356      brw_batch_flush(brw);
2357
2358   return brw_bo_map(brw, bo, mode);
2359}
2360
2361static void
2362brw_miptree_unmap_raw(struct brw_mipmap_tree *mt)
2363{
2364   brw_bo_unmap(mt->bo);
2365}
2366
2367static void
2368brw_miptree_unmap_map(struct brw_context *brw,
2369                      struct brw_mipmap_tree *mt,
2370                      struct brw_miptree_map *map,
2371                      unsigned int level, unsigned int slice)
2372{
2373   brw_miptree_unmap_raw(mt);
2374}
2375
2376static void
2377brw_miptree_map_map(struct brw_context *brw,
2378                    struct brw_mipmap_tree *mt,
2379                    struct brw_miptree_map *map,
2380                    unsigned int level, unsigned int slice)
2381{
2382   unsigned int bw, bh;
2383   void *base;
2384   unsigned int image_x, image_y;
2385   intptr_t x = map->x;
2386   intptr_t y = map->y;
2387
2388   /* For compressed formats, the stride is the number of bytes per
2389    * row of blocks.  brw_miptree_get_image_offset() already does
2390    * the divide.
2391    */
2392   _mesa_get_format_block_size(mt->format, &bw, &bh);
2393   assert(y % bh == 0);
2394   assert(x % bw == 0);
2395   y /= bh;
2396   x /= bw;
2397
2398   brw_miptree_access_raw(brw, mt, level, slice,
2399                          map->mode & GL_MAP_WRITE_BIT);
2400
2401   base = brw_miptree_map_raw(brw, mt, map->mode);
2402
2403   if (base == NULL)
2404      map->ptr = NULL;
2405   else {
2406      base += mt->offset;
2407
2408      /* Note that in the case of cube maps, the caller must have passed the
2409       * slice number referencing the face.
2410      */
2411      brw_miptree_get_image_offset(mt, level, slice, &image_x, &image_y);
2412      x += image_x;
2413      y += image_y;
2414
2415      map->stride = mt->surf.row_pitch_B;
2416      map->ptr = base + y * map->stride + x * mt->cpp;
2417   }
2418
2419   DBG("%s: %d,%d %dx%d from mt %p (%s) "
2420       "%"PRIiPTR",%"PRIiPTR" = %p/%d\n", __func__,
2421       map->x, map->y, map->w, map->h,
2422       mt, _mesa_get_format_name(mt->format),
2423       x, y, map->ptr, map->stride);
2424
2425   map->unmap = brw_miptree_unmap_map;
2426}
2427
2428static void
2429brw_miptree_unmap_blit(struct brw_context *brw,
2430                       struct brw_mipmap_tree *mt,
2431                       struct brw_miptree_map *map,
2432                       unsigned int level,
2433                       unsigned int slice)
2434{
2435   const struct intel_device_info *devinfo = &brw->screen->devinfo;
2436   struct gl_context *ctx = &brw->ctx;
2437
2438   brw_miptree_unmap_raw(map->linear_mt);
2439
2440   if (map->mode & GL_MAP_WRITE_BIT) {
2441      if (devinfo->ver >= 6) {
2442         brw_blorp_copy_miptrees(brw, map->linear_mt, 0, 0,
2443                                 mt, level, slice,
2444                                 0, 0, map->x, map->y, map->w, map->h);
2445      } else {
2446         bool ok = brw_miptree_copy(brw,
2447                                    map->linear_mt, 0, 0, 0, 0,
2448                                    mt, level, slice, map->x, map->y,
2449                                    map->w, map->h);
2450         WARN_ONCE(!ok, "Failed to blit from linear temporary mapping");
2451      }
2452   }
2453
2454   brw_miptree_release(&map->linear_mt);
2455}
2456
2457/* Compute extent parameters for use with tiled_memcpy functions.
2458 * xs are in units of bytes and ys are in units of strides.
2459 */
2460static inline void
2461tile_extents(struct brw_mipmap_tree *mt, struct brw_miptree_map *map,
2462             unsigned int level, unsigned int slice, unsigned int *x1_B,
2463             unsigned int *x2_B, unsigned int *y1_el, unsigned int *y2_el)
2464{
2465   unsigned int block_width, block_height;
2466   unsigned int x0_el, y0_el;
2467
2468   _mesa_get_format_block_size(mt->format, &block_width, &block_height);
2469
2470   assert(map->x % block_width == 0);
2471   assert(map->y % block_height == 0);
2472
2473   brw_miptree_get_image_offset(mt, level, slice, &x0_el, &y0_el);
2474   *x1_B = (map->x / block_width + x0_el) * mt->cpp;
2475   *y1_el = map->y / block_height + y0_el;
2476   *x2_B = (DIV_ROUND_UP(map->x + map->w, block_width) + x0_el) * mt->cpp;
2477   *y2_el = DIV_ROUND_UP(map->y + map->h, block_height) + y0_el;
2478}
2479
2480static void
2481brw_miptree_unmap_tiled_memcpy(struct brw_context *brw,
2482                               struct brw_mipmap_tree *mt,
2483                               struct brw_miptree_map *map,
2484                               unsigned int level,
2485                               unsigned int slice)
2486{
2487   if (map->mode & GL_MAP_WRITE_BIT) {
2488      unsigned int x1, x2, y1, y2;
2489      tile_extents(mt, map, level, slice, &x1, &x2, &y1, &y2);
2490
2491      char *dst = brw_miptree_map_raw(brw, mt, map->mode | MAP_RAW);
2492      dst += mt->offset;
2493
2494      isl_memcpy_linear_to_tiled(
2495         x1, x2, y1, y2, dst, map->ptr, mt->surf.row_pitch_B, map->stride,
2496         brw->has_swizzling, mt->surf.tiling, ISL_MEMCPY);
2497
2498      brw_miptree_unmap_raw(mt);
2499   }
2500   align_free(map->buffer);
2501   map->buffer = map->ptr = NULL;
2502}
2503
2504/**
2505 * Determine which copy function to use for the given format combination
2506 *
2507 * The only two possible copy functions which are ever returned are a
2508 * direct memcpy and a RGBA <-> BGRA copy function.  Since RGBA -> BGRA and
2509 * BGRA -> RGBA are exactly the same operation (and memcpy is obviously
2510 * symmetric), it doesn't matter whether the copy is from the tiled image
2511 * to the untiled or vice versa.  The copy function required is the same in
2512 * either case so this function can be used.
2513 *
2514 * \param[in]  tiledFormat The format of the tiled image
2515 * \param[in]  format      The GL format of the client data
2516 * \param[in]  type        The GL type of the client data
2517 * \param[out] mem_copy    Will be set to one of either the standard
2518 *                         library's memcpy or a different copy function
2519 *                         that performs an RGBA to BGRA conversion
2520 * \param[out] cpp         Number of bytes per channel
2521 *
2522 * \return true if the format and type combination are valid
2523 */
2524isl_memcpy_type
2525brw_miptree_get_memcpy_type(mesa_format tiledFormat, GLenum format, GLenum type,
2526                            uint32_t *cpp)
2527{
2528   if (type == GL_UNSIGNED_INT_8_8_8_8_REV &&
2529       !(format == GL_RGBA || format == GL_BGRA))
2530      return ISL_MEMCPY_INVALID; /* Invalid type/format combination */
2531
2532   if ((tiledFormat == MESA_FORMAT_L_UNORM8 && format == GL_LUMINANCE) ||
2533       (tiledFormat == MESA_FORMAT_A_UNORM8 && format == GL_ALPHA)) {
2534      *cpp = 1;
2535      return ISL_MEMCPY;
2536   } else if ((tiledFormat == MESA_FORMAT_B8G8R8A8_UNORM) ||
2537              (tiledFormat == MESA_FORMAT_B8G8R8X8_UNORM) ||
2538              (tiledFormat == MESA_FORMAT_B8G8R8A8_SRGB) ||
2539              (tiledFormat == MESA_FORMAT_B8G8R8X8_SRGB)) {
2540      *cpp = 4;
2541      if (format == GL_BGRA) {
2542         return ISL_MEMCPY;
2543      } else if (format == GL_RGBA) {
2544         return ISL_MEMCPY_BGRA8;
2545      }
2546   } else if ((tiledFormat == MESA_FORMAT_R8G8B8A8_UNORM) ||
2547              (tiledFormat == MESA_FORMAT_R8G8B8X8_UNORM) ||
2548              (tiledFormat == MESA_FORMAT_R8G8B8A8_SRGB) ||
2549              (tiledFormat == MESA_FORMAT_R8G8B8X8_SRGB)) {
2550      *cpp = 4;
2551      if (format == GL_BGRA) {
2552         /* Copying from RGBA to BGRA is the same as BGRA to RGBA so we can
2553          * use the same function.
2554          */
2555         return ISL_MEMCPY_BGRA8;
2556      } else if (format == GL_RGBA) {
2557         return ISL_MEMCPY;
2558      }
2559   }
2560
2561   return ISL_MEMCPY_INVALID;
2562}
2563
2564static void
2565brw_miptree_map_tiled_memcpy(struct brw_context *brw,
2566                             struct brw_mipmap_tree *mt,
2567                             struct brw_miptree_map *map,
2568                             unsigned int level, unsigned int slice)
2569{
2570   brw_miptree_access_raw(brw, mt, level, slice,
2571                          map->mode & GL_MAP_WRITE_BIT);
2572
2573   unsigned int x1, x2, y1, y2;
2574   tile_extents(mt, map, level, slice, &x1, &x2, &y1, &y2);
2575   map->stride = ALIGN(_mesa_format_row_stride(mt->format, map->w), 16);
2576
2577   /* The tiling and detiling functions require that the linear buffer
2578    * has proper 16-byte alignment (that is, its `x0` is 16-byte
2579    * aligned). Here we over-allocate the linear buffer by enough
2580    * bytes to get the proper alignment.
2581    */
2582   map->buffer = align_malloc(map->stride * (y2 - y1) + (x1 & 0xf), 16);
2583   map->ptr = (char *)map->buffer + (x1 & 0xf);
2584   assert(map->buffer);
2585
2586   if (!(map->mode & GL_MAP_INVALIDATE_RANGE_BIT)) {
2587      char *src = brw_miptree_map_raw(brw, mt, map->mode | MAP_RAW);
2588      src += mt->offset;
2589
2590      const isl_memcpy_type copy_type =
2591#if defined(USE_SSE41)
2592         cpu_has_sse4_1 ? ISL_MEMCPY_STREAMING_LOAD :
2593#endif
2594         ISL_MEMCPY;
2595
2596      isl_memcpy_tiled_to_linear(
2597         x1, x2, y1, y2, map->ptr, src, map->stride,
2598         mt->surf.row_pitch_B, brw->has_swizzling, mt->surf.tiling,
2599         copy_type);
2600
2601      brw_miptree_unmap_raw(mt);
2602   }
2603
2604   map->unmap = brw_miptree_unmap_tiled_memcpy;
2605}
2606
2607static void
2608brw_miptree_map_blit(struct brw_context *brw,
2609                     struct brw_mipmap_tree *mt,
2610                     struct brw_miptree_map *map,
2611                     unsigned int level, unsigned int slice)
2612{
2613   const struct intel_device_info *devinfo = &brw->screen->devinfo;
2614   map->linear_mt = make_surface(brw, GL_TEXTURE_2D, mt->format,
2615                                 0, 0, map->w, map->h, 1, 1,
2616                                 ISL_TILING_LINEAR_BIT,
2617                                 ISL_SURF_USAGE_RENDER_TARGET_BIT |
2618                                 ISL_SURF_USAGE_TEXTURE_BIT,
2619                                 0, 0, NULL);
2620
2621   if (!map->linear_mt) {
2622      fprintf(stderr, "Failed to allocate blit temporary\n");
2623      goto fail;
2624   }
2625   map->stride = map->linear_mt->surf.row_pitch_B;
2626
2627   /* One of either READ_BIT or WRITE_BIT or both is set.  READ_BIT implies no
2628    * INVALIDATE_RANGE_BIT.  WRITE_BIT needs the original values read in unless
2629    * invalidate is set, since we'll be writing the whole rectangle from our
2630    * temporary buffer back out.
2631    */
2632   if (!(map->mode & GL_MAP_INVALIDATE_RANGE_BIT)) {
2633      if (devinfo->ver >= 6) {
2634         brw_blorp_copy_miptrees(brw, mt, level, slice,
2635                                 map->linear_mt, 0, 0,
2636                                 map->x, map->y, 0, 0, map->w, map->h);
2637      } else {
2638         if (!brw_miptree_copy(brw,
2639                                 mt, level, slice, map->x, map->y,
2640                                 map->linear_mt, 0, 0, 0, 0,
2641                                 map->w, map->h)) {
2642            fprintf(stderr, "Failed to blit\n");
2643            goto fail;
2644         }
2645      }
2646   }
2647
2648   map->ptr = brw_miptree_map_raw(brw, map->linear_mt, map->mode);
2649
2650   DBG("%s: %d,%d %dx%d from mt %p (%s) %d,%d = %p/%d\n", __func__,
2651       map->x, map->y, map->w, map->h,
2652       mt, _mesa_get_format_name(mt->format),
2653       level, slice, map->ptr, map->stride);
2654
2655   map->unmap = brw_miptree_unmap_blit;
2656   return;
2657
2658fail:
2659   brw_miptree_release(&map->linear_mt);
2660   map->ptr = NULL;
2661   map->stride = 0;
2662}
2663
2664/**
2665 * "Map" a buffer by copying it to an untiled temporary using MOVNTDQA.
2666 */
2667#if defined(USE_SSE41)
2668static void
2669brw_miptree_unmap_movntdqa(struct brw_context *brw,
2670                           struct brw_mipmap_tree *mt,
2671                           struct brw_miptree_map *map,
2672                           unsigned int level,
2673                           unsigned int slice)
2674{
2675   align_free(map->buffer);
2676   map->buffer = NULL;
2677   map->ptr = NULL;
2678}
2679
2680static void
2681brw_miptree_map_movntdqa(struct brw_context *brw,
2682                         struct brw_mipmap_tree *mt,
2683                         struct brw_miptree_map *map,
2684                         unsigned int level, unsigned int slice)
2685{
2686   assert(map->mode & GL_MAP_READ_BIT);
2687   assert(!(map->mode & GL_MAP_WRITE_BIT));
2688
2689   brw_miptree_access_raw(brw, mt, level, slice, false);
2690
2691   DBG("%s: %d,%d %dx%d from mt %p (%s) %d,%d = %p/%d\n", __func__,
2692       map->x, map->y, map->w, map->h,
2693       mt, _mesa_get_format_name(mt->format),
2694       level, slice, map->ptr, map->stride);
2695
2696   /* Map the original image */
2697   uint32_t image_x;
2698   uint32_t image_y;
2699   brw_miptree_get_image_offset(mt, level, slice, &image_x, &image_y);
2700   image_x += map->x;
2701   image_y += map->y;
2702
2703   void *src = brw_miptree_map_raw(brw, mt, map->mode);
2704   if (!src)
2705      return;
2706
2707   src += mt->offset;
2708
2709   src += image_y * mt->surf.row_pitch_B;
2710   src += image_x * mt->cpp;
2711
2712   /* Due to the pixel offsets for the particular image being mapped, our
2713    * src pointer may not be 16-byte aligned.  However, if the pitch is
2714    * divisible by 16, then the amount by which it's misaligned will remain
2715    * consistent from row to row.
2716    */
2717   assert((mt->surf.row_pitch_B % 16) == 0);
2718   const int misalignment = ((uintptr_t) src) & 15;
2719
2720   /* Create an untiled temporary buffer for the mapping. */
2721   const unsigned width_bytes = _mesa_format_row_stride(mt->format, map->w);
2722
2723   map->stride = ALIGN(misalignment + width_bytes, 16);
2724
2725   map->buffer = align_malloc(map->stride * map->h, 16);
2726   /* Offset the destination so it has the same misalignment as src. */
2727   map->ptr = map->buffer + misalignment;
2728
2729   assert((((uintptr_t) map->ptr) & 15) == misalignment);
2730
2731   for (uint32_t y = 0; y < map->h; y++) {
2732      void *dst_ptr = map->ptr + y * map->stride;
2733      void *src_ptr = src + y * mt->surf.row_pitch_B;
2734
2735      _mesa_streaming_load_memcpy(dst_ptr, src_ptr, width_bytes);
2736   }
2737
2738   brw_miptree_unmap_raw(mt);
2739
2740   map->unmap = brw_miptree_unmap_movntdqa;
2741}
2742#endif
2743
2744static void
2745brw_miptree_unmap_s8(struct brw_context *brw,
2746                     struct brw_mipmap_tree *mt,
2747                     struct brw_miptree_map *map,
2748                     unsigned int level,
2749                     unsigned int slice)
2750{
2751   if (map->mode & GL_MAP_WRITE_BIT) {
2752      unsigned int image_x, image_y;
2753      uint8_t *untiled_s8_map = map->ptr;
2754      uint8_t *tiled_s8_map = brw_miptree_map_raw(brw, mt, GL_MAP_WRITE_BIT);
2755
2756      brw_miptree_get_image_offset(mt, level, slice, &image_x, &image_y);
2757
2758      for (uint32_t y = 0; y < map->h; y++) {
2759         for (uint32_t x = 0; x < map->w; x++) {
2760            ptrdiff_t offset = brw_offset_S8(mt->surf.row_pitch_B,
2761                                             image_x + x + map->x,
2762                                             image_y + y + map->y,
2763                                             brw->has_swizzling);
2764            tiled_s8_map[offset] = untiled_s8_map[y * map->w + x];
2765         }
2766      }
2767
2768      brw_miptree_unmap_raw(mt);
2769   }
2770
2771   free(map->buffer);
2772}
2773
2774static void
2775brw_miptree_map_s8(struct brw_context *brw,
2776                   struct brw_mipmap_tree *mt,
2777                   struct brw_miptree_map *map,
2778                   unsigned int level, unsigned int slice)
2779{
2780   map->stride = map->w;
2781   map->buffer = map->ptr = malloc(map->stride * map->h);
2782   if (!map->buffer)
2783      return;
2784
2785   brw_miptree_access_raw(brw, mt, level, slice,
2786                          map->mode & GL_MAP_WRITE_BIT);
2787
2788   /* One of either READ_BIT or WRITE_BIT or both is set.  READ_BIT implies no
2789    * INVALIDATE_RANGE_BIT.  WRITE_BIT needs the original values read in unless
2790    * invalidate is set, since we'll be writing the whole rectangle from our
2791    * temporary buffer back out.
2792    */
2793   if (!(map->mode & GL_MAP_INVALIDATE_RANGE_BIT)) {
2794      uint8_t *untiled_s8_map = map->ptr;
2795      uint8_t *tiled_s8_map = brw_miptree_map_raw(brw, mt, GL_MAP_READ_BIT);
2796      unsigned int image_x, image_y;
2797
2798      brw_miptree_get_image_offset(mt, level, slice, &image_x, &image_y);
2799
2800      for (uint32_t y = 0; y < map->h; y++) {
2801         for (uint32_t x = 0; x < map->w; x++) {
2802            ptrdiff_t offset = brw_offset_S8(mt->surf.row_pitch_B,
2803                                             x + image_x + map->x,
2804                                             y + image_y + map->y,
2805                                             brw->has_swizzling);
2806            untiled_s8_map[y * map->w + x] = tiled_s8_map[offset];
2807         }
2808      }
2809
2810      brw_miptree_unmap_raw(mt);
2811
2812      DBG("%s: %d,%d %dx%d from mt %p %d,%d = %p/%d\n", __func__,
2813          map->x, map->y, map->w, map->h,
2814          mt, map->x + image_x, map->y + image_y, map->ptr, map->stride);
2815   } else {
2816      DBG("%s: %d,%d %dx%d from mt %p = %p/%d\n", __func__,
2817          map->x, map->y, map->w, map->h,
2818          mt, map->ptr, map->stride);
2819   }
2820
2821   map->unmap = brw_miptree_unmap_s8;
2822}
2823
2824/**
2825 * Mapping functions for packed depth/stencil miptrees backed by real separate
2826 * miptrees for depth and stencil.
2827 *
2828 * On gfx7, and to support HiZ pre-gfx7, we have to have the stencil buffer
2829 * separate from the depth buffer.  Yet at the GL API level, we have to expose
2830 * packed depth/stencil textures and FBO attachments, and Mesa core expects to
2831 * be able to map that memory for texture storage and glReadPixels-type
2832 * operations.  We give Mesa core that access by mallocing a temporary and
2833 * copying the data between the actual backing store and the temporary.
2834 */
2835static void
2836brw_miptree_unmap_depthstencil(struct brw_context *brw,
2837                               struct brw_mipmap_tree *mt,
2838                               struct brw_miptree_map *map,
2839                               unsigned int level,
2840                               unsigned int slice)
2841{
2842   struct brw_mipmap_tree *z_mt = mt;
2843   struct brw_mipmap_tree *s_mt = mt->stencil_mt;
2844   bool map_z32f_x24s8 = mt->format == MESA_FORMAT_Z_FLOAT32;
2845
2846   if (map->mode & GL_MAP_WRITE_BIT) {
2847      uint32_t *packed_map = map->ptr;
2848      uint8_t *s_map = brw_miptree_map_raw(brw, s_mt, GL_MAP_WRITE_BIT);
2849      uint32_t *z_map = brw_miptree_map_raw(brw, z_mt, GL_MAP_WRITE_BIT);
2850      unsigned int s_image_x, s_image_y;
2851      unsigned int z_image_x, z_image_y;
2852
2853      brw_miptree_get_image_offset(s_mt, level, slice,
2854                                   &s_image_x, &s_image_y);
2855      brw_miptree_get_image_offset(z_mt, level, slice,
2856                                   &z_image_x, &z_image_y);
2857
2858      for (uint32_t y = 0; y < map->h; y++) {
2859         for (uint32_t x = 0; x < map->w; x++) {
2860            ptrdiff_t s_offset = brw_offset_S8(s_mt->surf.row_pitch_B,
2861                                               x + s_image_x + map->x,
2862                                               y + s_image_y + map->y,
2863                                               brw->has_swizzling);
2864            ptrdiff_t z_offset = ((y + z_image_y + map->y) *
2865                                  (z_mt->surf.row_pitch_B / 4) +
2866                                  (x + z_image_x + map->x));
2867
2868            if (map_z32f_x24s8) {
2869               z_map[z_offset] = packed_map[(y * map->w + x) * 2 + 0];
2870               s_map[s_offset] = packed_map[(y * map->w + x) * 2 + 1];
2871            } else {
2872               uint32_t packed = packed_map[y * map->w + x];
2873               s_map[s_offset] = packed >> 24;
2874               z_map[z_offset] = packed;
2875            }
2876         }
2877      }
2878
2879      brw_miptree_unmap_raw(s_mt);
2880      brw_miptree_unmap_raw(z_mt);
2881
2882      DBG("%s: %d,%d %dx%d from z mt %p (%s) %d,%d, s mt %p %d,%d = %p/%d\n",
2883          __func__,
2884          map->x, map->y, map->w, map->h,
2885          z_mt, _mesa_get_format_name(z_mt->format),
2886          map->x + z_image_x, map->y + z_image_y,
2887          s_mt, map->x + s_image_x, map->y + s_image_y,
2888          map->ptr, map->stride);
2889   }
2890
2891   free(map->buffer);
2892}
2893
2894static void
2895brw_miptree_map_depthstencil(struct brw_context *brw,
2896                             struct brw_mipmap_tree *mt,
2897                             struct brw_miptree_map *map,
2898                             unsigned int level, unsigned int slice)
2899{
2900   struct brw_mipmap_tree *z_mt = mt;
2901   struct brw_mipmap_tree *s_mt = mt->stencil_mt;
2902   bool map_z32f_x24s8 = mt->format == MESA_FORMAT_Z_FLOAT32;
2903   int packed_bpp = map_z32f_x24s8 ? 8 : 4;
2904
2905   map->stride = map->w * packed_bpp;
2906   map->buffer = map->ptr = malloc(map->stride * map->h);
2907   if (!map->buffer)
2908      return;
2909
2910   brw_miptree_access_raw(brw, z_mt, level, slice,
2911                          map->mode & GL_MAP_WRITE_BIT);
2912   brw_miptree_access_raw(brw, s_mt, level, slice,
2913                          map->mode & GL_MAP_WRITE_BIT);
2914
2915   /* One of either READ_BIT or WRITE_BIT or both is set.  READ_BIT implies no
2916    * INVALIDATE_RANGE_BIT.  WRITE_BIT needs the original values read in unless
2917    * invalidate is set, since we'll be writing the whole rectangle from our
2918    * temporary buffer back out.
2919    */
2920   if (!(map->mode & GL_MAP_INVALIDATE_RANGE_BIT)) {
2921      uint32_t *packed_map = map->ptr;
2922      uint8_t *s_map = brw_miptree_map_raw(brw, s_mt, GL_MAP_READ_BIT);
2923      uint32_t *z_map = brw_miptree_map_raw(brw, z_mt, GL_MAP_READ_BIT);
2924      unsigned int s_image_x, s_image_y;
2925      unsigned int z_image_x, z_image_y;
2926
2927      brw_miptree_get_image_offset(s_mt, level, slice,
2928                                   &s_image_x, &s_image_y);
2929      brw_miptree_get_image_offset(z_mt, level, slice,
2930                                   &z_image_x, &z_image_y);
2931
2932      for (uint32_t y = 0; y < map->h; y++) {
2933         for (uint32_t x = 0; x < map->w; x++) {
2934            int map_x = map->x + x, map_y = map->y + y;
2935            ptrdiff_t s_offset = brw_offset_S8(s_mt->surf.row_pitch_B,
2936                                                 map_x + s_image_x,
2937                                                 map_y + s_image_y,
2938                                                 brw->has_swizzling);
2939            ptrdiff_t z_offset = ((map_y + z_image_y) *
2940                                  (z_mt->surf.row_pitch_B / 4) +
2941                                  (map_x + z_image_x));
2942            uint8_t s = s_map[s_offset];
2943            uint32_t z = z_map[z_offset];
2944
2945            if (map_z32f_x24s8) {
2946               packed_map[(y * map->w + x) * 2 + 0] = z;
2947               packed_map[(y * map->w + x) * 2 + 1] = s;
2948            } else {
2949               packed_map[y * map->w + x] = (s << 24) | (z & 0x00ffffff);
2950            }
2951         }
2952      }
2953
2954      brw_miptree_unmap_raw(s_mt);
2955      brw_miptree_unmap_raw(z_mt);
2956
2957      DBG("%s: %d,%d %dx%d from z mt %p %d,%d, s mt %p %d,%d = %p/%d\n",
2958          __func__,
2959          map->x, map->y, map->w, map->h,
2960          z_mt, map->x + z_image_x, map->y + z_image_y,
2961          s_mt, map->x + s_image_x, map->y + s_image_y,
2962          map->ptr, map->stride);
2963   } else {
2964      DBG("%s: %d,%d %dx%d from mt %p = %p/%d\n", __func__,
2965          map->x, map->y, map->w, map->h,
2966          mt, map->ptr, map->stride);
2967   }
2968
2969   map->unmap = brw_miptree_unmap_depthstencil;
2970}
2971
2972/**
2973 * Create and attach a map to the miptree at (level, slice). Return the
2974 * attached map.
2975 */
2976static struct brw_miptree_map*
2977brw_miptree_attach_map(struct brw_mipmap_tree *mt,
2978                       unsigned int level,
2979                       unsigned int slice,
2980                       unsigned int x,
2981                       unsigned int y,
2982                       unsigned int w,
2983                       unsigned int h,
2984                       GLbitfield mode)
2985{
2986   struct brw_miptree_map *map = calloc(1, sizeof(*map));
2987
2988   if (!map)
2989      return NULL;
2990
2991   assert(mt->level[level].slice[slice].map == NULL);
2992   mt->level[level].slice[slice].map = map;
2993
2994   map->mode = mode;
2995   map->x = x;
2996   map->y = y;
2997   map->w = w;
2998   map->h = h;
2999
3000   return map;
3001}
3002
3003/**
3004 * Release the map at (level, slice).
3005 */
3006static void
3007brw_miptree_release_map(struct brw_mipmap_tree *mt,
3008                         unsigned int level,
3009                         unsigned int slice)
3010{
3011   struct brw_miptree_map **map;
3012
3013   map = &mt->level[level].slice[slice].map;
3014   free(*map);
3015   *map = NULL;
3016}
3017
3018static bool
3019can_blit_slice(struct brw_mipmap_tree *mt,
3020               const struct brw_miptree_map *map)
3021{
3022   /* See brw_miptree_blit() for details on the 32k pitch limit. */
3023   const unsigned src_blt_pitch = brw_miptree_blt_pitch(mt);
3024   const unsigned dst_blt_pitch = ALIGN(map->w * mt->cpp, 64);
3025   return src_blt_pitch < 32768 && dst_blt_pitch < 32768;
3026}
3027
3028static bool
3029use_blitter_to_map(struct brw_context *brw,
3030                   struct brw_mipmap_tree *mt,
3031                   const struct brw_miptree_map *map)
3032{
3033   const struct intel_device_info *devinfo = &brw->screen->devinfo;
3034
3035   if (devinfo->has_llc &&
3036      /* It's probably not worth swapping to the blit ring because of
3037       * all the overhead involved.
3038       */
3039       !(map->mode & GL_MAP_WRITE_BIT) &&
3040       !mt->compressed &&
3041       (mt->surf.tiling == ISL_TILING_X ||
3042        /* Prior to Sandybridge, the blitter can't handle Y tiling */
3043        (devinfo->ver >= 6 && mt->surf.tiling == ISL_TILING_Y0) ||
3044        /* Fast copy blit on skl+ supports all tiling formats. */
3045        devinfo->ver >= 9) &&
3046       can_blit_slice(mt, map))
3047      return true;
3048
3049   if (mt->surf.tiling != ISL_TILING_LINEAR &&
3050       mt->bo->size >= brw->max_gtt_map_object_size) {
3051      assert(can_blit_slice(mt, map));
3052      return true;
3053   }
3054
3055   return false;
3056}
3057
3058/**
3059 * Parameter \a out_stride has type ptrdiff_t not because the buffer stride may
3060 * exceed 32 bits but to diminish the likelihood subtle bugs in pointer
3061 * arithmetic overflow.
3062 *
3063 * If you call this function and use \a out_stride, then you're doing pointer
3064 * arithmetic on \a out_ptr. The type of \a out_stride doesn't prevent all
3065 * bugs.  The caller must still take care to avoid 32-bit overflow errors in
3066 * all arithmetic expressions that contain buffer offsets and pixel sizes,
3067 * which usually have type uint32_t or GLuint.
3068 */
3069void
3070brw_miptree_map(struct brw_context *brw,
3071                struct brw_mipmap_tree *mt,
3072                unsigned int level,
3073                unsigned int slice,
3074                unsigned int x,
3075                unsigned int y,
3076                unsigned int w,
3077                unsigned int h,
3078                GLbitfield mode,
3079                void **out_ptr,
3080                ptrdiff_t *out_stride)
3081{
3082   const struct intel_device_info *devinfo = &brw->screen->devinfo;
3083   struct brw_miptree_map *map;
3084
3085   assert(mt->surf.samples == 1);
3086
3087   map = brw_miptree_attach_map(mt, level, slice, x, y, w, h, mode);
3088   if (!map){
3089      *out_ptr = NULL;
3090      *out_stride = 0;
3091      return;
3092   }
3093
3094   if (mt->format == MESA_FORMAT_S_UINT8) {
3095      brw_miptree_map_s8(brw, mt, map, level, slice);
3096   } else if (mt->stencil_mt && !(mode & BRW_MAP_DIRECT_BIT)) {
3097      brw_miptree_map_depthstencil(brw, mt, map, level, slice);
3098   } else if (use_blitter_to_map(brw, mt, map)) {
3099      brw_miptree_map_blit(brw, mt, map, level, slice);
3100   } else if (mt->surf.tiling != ISL_TILING_LINEAR && devinfo->ver > 4) {
3101      brw_miptree_map_tiled_memcpy(brw, mt, map, level, slice);
3102#if defined(USE_SSE41)
3103   } else if (!(mode & GL_MAP_WRITE_BIT) &&
3104              !mt->compressed && cpu_has_sse4_1 &&
3105              (mt->surf.row_pitch_B % 16 == 0)) {
3106      brw_miptree_map_movntdqa(brw, mt, map, level, slice);
3107#endif
3108   } else {
3109      if (mt->surf.tiling != ISL_TILING_LINEAR)
3110         perf_debug("brw_miptree_map: mapping via gtt");
3111      brw_miptree_map_map(brw, mt, map, level, slice);
3112   }
3113
3114   *out_ptr = map->ptr;
3115   *out_stride = map->stride;
3116
3117   if (map->ptr == NULL)
3118      brw_miptree_release_map(mt, level, slice);
3119}
3120
3121void
3122brw_miptree_unmap(struct brw_context *brw,
3123                  struct brw_mipmap_tree *mt,
3124                  unsigned int level,
3125                  unsigned int slice)
3126{
3127   struct brw_miptree_map *map = mt->level[level].slice[slice].map;
3128
3129   assert(mt->surf.samples == 1);
3130
3131   if (!map)
3132      return;
3133
3134   DBG("%s: mt %p (%s) level %d slice %d\n", __func__,
3135       mt, _mesa_get_format_name(mt->format), level, slice);
3136
3137   if (map->unmap)
3138      map->unmap(brw, mt, map, level, slice);
3139
3140   brw_miptree_release_map(mt, level, slice);
3141}
3142
3143enum isl_surf_dim
3144get_isl_surf_dim(GLenum target)
3145{
3146   switch (target) {
3147   case GL_TEXTURE_1D:
3148   case GL_TEXTURE_1D_ARRAY:
3149      return ISL_SURF_DIM_1D;
3150
3151   case GL_TEXTURE_2D:
3152   case GL_TEXTURE_2D_ARRAY:
3153   case GL_TEXTURE_RECTANGLE:
3154   case GL_TEXTURE_CUBE_MAP:
3155   case GL_TEXTURE_CUBE_MAP_ARRAY:
3156   case GL_TEXTURE_2D_MULTISAMPLE:
3157   case GL_TEXTURE_2D_MULTISAMPLE_ARRAY:
3158   case GL_TEXTURE_EXTERNAL_OES:
3159      return ISL_SURF_DIM_2D;
3160
3161   case GL_TEXTURE_3D:
3162      return ISL_SURF_DIM_3D;
3163   }
3164
3165   unreachable("Invalid texture target");
3166}
3167
3168enum isl_dim_layout
3169get_isl_dim_layout(const struct intel_device_info *devinfo,
3170                   enum isl_tiling tiling, GLenum target)
3171{
3172   switch (target) {
3173   case GL_TEXTURE_1D:
3174   case GL_TEXTURE_1D_ARRAY:
3175      return (devinfo->ver >= 9 && tiling == ISL_TILING_LINEAR ?
3176              ISL_DIM_LAYOUT_GFX9_1D : ISL_DIM_LAYOUT_GFX4_2D);
3177
3178   case GL_TEXTURE_2D:
3179   case GL_TEXTURE_2D_ARRAY:
3180   case GL_TEXTURE_RECTANGLE:
3181   case GL_TEXTURE_2D_MULTISAMPLE:
3182   case GL_TEXTURE_2D_MULTISAMPLE_ARRAY:
3183   case GL_TEXTURE_EXTERNAL_OES:
3184      return ISL_DIM_LAYOUT_GFX4_2D;
3185
3186   case GL_TEXTURE_CUBE_MAP:
3187   case GL_TEXTURE_CUBE_MAP_ARRAY:
3188      return (devinfo->ver == 4 ? ISL_DIM_LAYOUT_GFX4_3D :
3189              ISL_DIM_LAYOUT_GFX4_2D);
3190
3191   case GL_TEXTURE_3D:
3192      return (devinfo->ver >= 9 ?
3193              ISL_DIM_LAYOUT_GFX4_2D : ISL_DIM_LAYOUT_GFX4_3D);
3194   }
3195
3196   unreachable("Invalid texture target");
3197}
3198
3199bool
3200brw_miptree_set_clear_color(struct brw_context *brw,
3201                            struct brw_mipmap_tree *mt,
3202                            union isl_color_value clear_color)
3203{
3204   if (memcmp(&mt->fast_clear_color, &clear_color, sizeof(clear_color)) != 0) {
3205      mt->fast_clear_color = clear_color;
3206      if (mt->aux_buf->clear_color_bo) {
3207         /* We can't update the clear color while the hardware is still using
3208          * the previous one for a resolve or sampling from it. Make sure that
3209          * there are no pending commands at this point.
3210          */
3211         brw_emit_pipe_control_flush(brw, PIPE_CONTROL_CS_STALL);
3212         for (int i = 0; i < 4; i++) {
3213            brw_store_data_imm32(brw, mt->aux_buf->clear_color_bo,
3214                                 mt->aux_buf->clear_color_offset + i * 4,
3215                                 mt->fast_clear_color.u32[i]);
3216         }
3217         brw_emit_pipe_control_flush(brw, PIPE_CONTROL_STATE_CACHE_INVALIDATE);
3218      }
3219      brw->ctx.NewDriverState |= BRW_NEW_AUX_STATE;
3220      return true;
3221   }
3222   return false;
3223}
3224
3225union isl_color_value
3226brw_miptree_get_clear_color(const struct brw_mipmap_tree *mt,
3227                            struct brw_bo **clear_color_bo,
3228                            uint64_t *clear_color_offset)
3229{
3230   assert(mt->aux_buf);
3231
3232   *clear_color_bo = mt->aux_buf->clear_color_bo;
3233   *clear_color_offset = mt->aux_buf->clear_color_offset;
3234   return mt->fast_clear_color;
3235}
3236
3237static void
3238brw_miptree_update_etc_shadow(struct brw_context *brw,
3239                              struct brw_mipmap_tree *mt,
3240                              unsigned int level,
3241                              unsigned int slice,
3242                              int level_w,
3243                              int level_h)
3244{
3245   ptrdiff_t etc_stride, shadow_stride;
3246   void *mptr, *sptr;
3247   struct brw_mipmap_tree *smt = mt->shadow_mt;
3248
3249   assert(brw_miptree_has_etc_shadow(brw, mt));
3250
3251   brw_miptree_map(brw, mt, level, slice, 0, 0, level_w, level_h,
3252                   GL_MAP_READ_BIT, &mptr, &etc_stride);
3253   brw_miptree_map(brw, smt, level, slice, 0, 0, level_w, level_h,
3254                   GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_RANGE_BIT,
3255                   &sptr, &shadow_stride);
3256
3257   if (mt->format == MESA_FORMAT_ETC1_RGB8) {
3258      _mesa_etc1_unpack_rgba8888(sptr, shadow_stride, mptr, etc_stride,
3259                                 level_w, level_h);
3260   } else {
3261      /* destination and source images must have the same swizzle */
3262      bool is_bgra = (smt->format == MESA_FORMAT_B8G8R8A8_SRGB);
3263      _mesa_unpack_etc2_format(sptr, shadow_stride, mptr, etc_stride,
3264                               level_w, level_h, mt->format, is_bgra);
3265   }
3266
3267   brw_miptree_unmap(brw, mt, level, slice);
3268   brw_miptree_unmap(brw, smt, level, slice);
3269}
3270
3271void
3272brw_miptree_update_etc_shadow_levels(struct brw_context *brw,
3273                                     struct brw_mipmap_tree *mt)
3274{
3275   struct brw_mipmap_tree *smt;
3276   int num_slices;
3277
3278   assert(mt);
3279   assert(mt->surf.size_B > 0);
3280   assert(brw_miptree_has_etc_shadow(brw, mt));
3281
3282   smt = mt->shadow_mt;
3283   num_slices = smt->surf.logical_level0_px.array_len;
3284
3285   for (int level = smt->first_level; level <= smt->last_level; level++) {
3286      int level_w = minify(smt->surf.logical_level0_px.width,
3287                           level - smt->first_level);
3288      int level_h = minify(smt->surf.logical_level0_px.height,
3289                           level - smt->first_level);
3290
3291      for (unsigned int slice = 0; slice < num_slices; slice++) {
3292         brw_miptree_update_etc_shadow(brw, mt, level, slice, level_w,
3293                                       level_h);
3294      }
3295   }
3296
3297   mt->shadow_needs_update = false;
3298}
3299