si_pipe.h revision 7ec681f3
1/*
2 * Copyright 2010 Jerome Glisse <glisse@freedesktop.org>
3 * Copyright 2018 Advanced Micro Devices, Inc.
4 * All Rights Reserved.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * on the rights to use, copy, modify, merge, publish, distribute, sub
10 * license, and/or sell copies of the Software, and to permit persons to whom
11 * the Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice (including the next
14 * paragraph) shall be included in all copies or substantial portions of the
15 * Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHOR(S) AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM,
21 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
22 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
23 * USE OR OTHER DEALINGS IN THE SOFTWARE.
24 */
25#ifndef SI_PIPE_H
26#define SI_PIPE_H
27
28#include "si_shader.h"
29#include "si_state.h"
30#include "util/u_dynarray.h"
31#include "util/u_idalloc.h"
32#include "util/u_suballoc.h"
33#include "util/u_threaded_context.h"
34#include "util/u_vertex_state_cache.h"
35#include "ac_sqtt.h"
36
37#ifdef __cplusplus
38extern "C" {
39#endif
40
41#if UTIL_ARCH_BIG_ENDIAN
42#define SI_BIG_ENDIAN 1
43#else
44#define SI_BIG_ENDIAN 0
45#endif
46
47#define ATI_VENDOR_ID         0x1002
48#define SI_NOT_QUERY          0xffffffff
49
50/* The base vertex and primitive restart can be any number, but we must pick
51 * one which will mean "unknown" for the purpose of state tracking and
52 * the number shouldn't be a commonly-used one. */
53#define SI_BASE_VERTEX_UNKNOWN    INT_MIN
54#define SI_START_INSTANCE_UNKNOWN ((unsigned)INT_MIN)
55#define SI_DRAW_ID_UNKNOWN        ((unsigned)INT_MIN)
56#define SI_RESTART_INDEX_UNKNOWN  ((unsigned)INT_MIN)
57#define SI_INSTANCE_COUNT_UNKNOWN ((unsigned)INT_MIN)
58#define SI_NUM_SMOOTH_AA_SAMPLES  4
59#define SI_MAX_POINT_SIZE         2048
60#define SI_GS_PER_ES              128
61/* Alignment for optimal CP DMA performance. */
62#define SI_CPDMA_ALIGNMENT 32
63
64/* Tunables for compute-based clear_buffer and copy_buffer: */
65#define SI_COMPUTE_CLEAR_DW_PER_THREAD 4
66#define SI_COMPUTE_COPY_DW_PER_THREAD  4
67/* L2 LRU is recommended because the compute shader can finish sooner due to fewer L2 evictions. */
68#define SI_COMPUTE_DST_CACHE_POLICY    L2_LRU
69
70/* Pipeline & streamout query controls. */
71#define SI_CONTEXT_START_PIPELINE_STATS  (1 << 0)
72#define SI_CONTEXT_STOP_PIPELINE_STATS   (1 << 1)
73#define SI_CONTEXT_FLUSH_FOR_RENDER_COND (1 << 2)
74/* Instruction cache. */
75#define SI_CONTEXT_INV_ICACHE (1 << 3)
76/* Scalar cache. (GFX6-9: scalar L1; GFX10: scalar L0)
77 * GFX10: This also invalidates the L1 shader array cache. */
78#define SI_CONTEXT_INV_SCACHE (1 << 4)
79/* Vector cache. (GFX6-9: vector L1; GFX10: vector L0)
80 * GFX10: This also invalidates the L1 shader array cache. */
81#define SI_CONTEXT_INV_VCACHE (1 << 5)
82/* L2 cache + L2 metadata cache writeback & invalidate.
83 * GFX6-8: Used by shaders only. GFX9-10: Used by everything. */
84#define SI_CONTEXT_INV_L2 (1 << 6)
85/* L2 writeback (write dirty L2 lines to memory for non-L2 clients).
86 * Only used for coherency with non-L2 clients like CB, DB, CP on GFX6-8.
87 * GFX6-7 will do complete invalidation, because the writeback is unsupported. */
88#define SI_CONTEXT_WB_L2 (1 << 7)
89/* Writeback & invalidate the L2 metadata cache only. It can only be coupled with
90 * a CB or DB flush. */
91#define SI_CONTEXT_INV_L2_METADATA (1 << 8)
92/* Framebuffer caches. */
93#define SI_CONTEXT_FLUSH_AND_INV_DB      (1 << 9)
94#define SI_CONTEXT_FLUSH_AND_INV_DB_META (1 << 10)
95#define SI_CONTEXT_FLUSH_AND_INV_CB      (1 << 11)
96/* Engine synchronization. */
97#define SI_CONTEXT_VS_PARTIAL_FLUSH   (1 << 12)
98#define SI_CONTEXT_PS_PARTIAL_FLUSH   (1 << 13)
99#define SI_CONTEXT_CS_PARTIAL_FLUSH   (1 << 14)
100#define SI_CONTEXT_VGT_FLUSH          (1 << 15)
101#define SI_CONTEXT_VGT_STREAMOUT_SYNC (1 << 16)
102/* PFP waits for ME to finish. Used to sync for index and indirect buffers and render
103 * condition. It's typically set when doing a VS/PS/CS partial flush for buffers. */
104#define SI_CONTEXT_PFP_SYNC_ME        (1 << 17)
105
106#define SI_PREFETCH_LS              (1 << 1)
107#define SI_PREFETCH_HS              (1 << 2)
108#define SI_PREFETCH_ES              (1 << 3)
109#define SI_PREFETCH_GS              (1 << 4)
110#define SI_PREFETCH_VS              (1 << 5)
111#define SI_PREFETCH_PS              (1 << 6)
112
113#define SI_MAX_BORDER_COLORS              4096
114#define SI_MAX_VIEWPORTS                  16
115#define SIX_BITS                          0x3F
116#define SI_MAP_BUFFER_ALIGNMENT           64
117/* We only support the minimum allowed value (512), so that we can pack a 3D block size
118 * in 1 SGPR. */
119#define SI_MAX_VARIABLE_THREADS_PER_BLOCK 512
120
121#define SI_CONTEXT_FLAG_AUX               (1u << 31)
122
123#define SI_RESOURCE_FLAG_FORCE_LINEAR      (PIPE_RESOURCE_FLAG_DRV_PRIV << 0)
124#define SI_RESOURCE_FLAG_FLUSHED_DEPTH     (PIPE_RESOURCE_FLAG_DRV_PRIV << 1)
125#define SI_RESOURCE_FLAG_FORCE_MSAA_TILING (PIPE_RESOURCE_FLAG_DRV_PRIV << 2)
126#define SI_RESOURCE_FLAG_DISABLE_DCC       (PIPE_RESOURCE_FLAG_DRV_PRIV << 3)
127#define SI_RESOURCE_FLAG_UNMAPPABLE        (PIPE_RESOURCE_FLAG_DRV_PRIV << 4)
128#define SI_RESOURCE_FLAG_READ_ONLY         (PIPE_RESOURCE_FLAG_DRV_PRIV << 5)
129#define SI_RESOURCE_FLAG_32BIT             (PIPE_RESOURCE_FLAG_DRV_PRIV << 6)
130#define SI_RESOURCE_FLAG_CLEAR             (PIPE_RESOURCE_FLAG_DRV_PRIV << 7)
131/* gap */
132/* Set a micro tile mode: */
133#define SI_RESOURCE_FLAG_FORCE_MICRO_TILE_MODE (PIPE_RESOURCE_FLAG_DRV_PRIV << 9)
134#define SI_RESOURCE_FLAG_MICRO_TILE_MODE_SHIFT (util_logbase2(PIPE_RESOURCE_FLAG_DRV_PRIV) + 10)
135#define SI_RESOURCE_FLAG_MICRO_TILE_MODE_SET(x)                                                    \
136   (((x)&0x3) << SI_RESOURCE_FLAG_MICRO_TILE_MODE_SHIFT)
137#define SI_RESOURCE_FLAG_MICRO_TILE_MODE_GET(x)                                                    \
138   (((x) >> SI_RESOURCE_FLAG_MICRO_TILE_MODE_SHIFT) & 0x3)
139#define SI_RESOURCE_FLAG_UNCACHED          (PIPE_RESOURCE_FLAG_DRV_PRIV << 12)
140#define SI_RESOURCE_FLAG_DRIVER_INTERNAL   (PIPE_RESOURCE_FLAG_DRV_PRIV << 13)
141#define SI_RESOURCE_AUX_PLANE              (PIPE_RESOURCE_FLAG_DRV_PRIV << 14)
142
143enum si_has_gs {
144   GS_OFF,
145   GS_ON,
146};
147
148enum si_has_tess {
149   TESS_OFF,
150   TESS_ON,
151};
152
153enum si_has_ngg {
154   NGG_OFF,
155   NGG_ON,
156};
157
158enum si_clear_code
159{
160   DCC_CLEAR_COLOR_0000 = 0x00000000,
161   DCC_CLEAR_COLOR_0001 = 0x40404040,
162   DCC_CLEAR_COLOR_1110 = 0x80808080,
163   DCC_CLEAR_COLOR_1111 = 0xC0C0C0C0,
164   DCC_CLEAR_COLOR_REG = 0x20202020,
165   DCC_UNCOMPRESSED = 0xFFFFFFFF,
166};
167
168#define SI_IMAGE_ACCESS_DCC_OFF           (1 << 8)
169#define SI_IMAGE_ACCESS_ALLOW_DCC_STORE   (1 << 9)
170
171/* Debug flags. */
172enum
173{
174   /* Shader logging options: */
175   DBG_VS = MESA_SHADER_VERTEX,
176   DBG_TCS = MESA_SHADER_TESS_CTRL,
177   DBG_TES = MESA_SHADER_TESS_EVAL,
178   DBG_GS = MESA_SHADER_GEOMETRY,
179   DBG_PS = MESA_SHADER_FRAGMENT,
180   DBG_CS = MESA_SHADER_COMPUTE,
181   DBG_NO_IR,
182   DBG_NO_NIR,
183   DBG_NO_ASM,
184   DBG_PREOPT_IR,
185
186   /* Shader compiler options the shader cache should be aware of: */
187   DBG_FS_CORRECT_DERIVS_AFTER_KILL,
188   DBG_GISEL,
189   DBG_W32_GE,
190   DBG_W32_PS,
191   DBG_W32_CS,
192   DBG_W64_GE,
193   DBG_W64_PS,
194   DBG_W64_CS,
195
196   /* Shader compiler options (with no effect on the shader cache): */
197   DBG_CHECK_IR,
198   DBG_MONOLITHIC_SHADERS,
199   DBG_NO_OPT_VARIANT,
200
201   /* Information logging options: */
202   DBG_INFO,
203   DBG_TEX,
204   DBG_COMPUTE,
205   DBG_VM,
206   DBG_CACHE_STATS,
207   DBG_IB,
208
209   /* Driver options: */
210   DBG_NO_WC,
211   DBG_CHECK_VM,
212   DBG_RESERVE_VMID,
213   DBG_SHADOW_REGS,
214   DBG_NO_FAST_DISPLAY_LIST,
215
216   /* 3D engine options: */
217   DBG_NO_GFX,
218   DBG_NO_NGG,
219   DBG_ALWAYS_NGG_CULLING_ALL,
220   DBG_ALWAYS_NGG_CULLING_TESS,
221   DBG_NO_NGG_CULLING,
222   DBG_SWITCH_ON_EOP,
223   DBG_NO_OUT_OF_ORDER,
224   DBG_NO_DPBB,
225   DBG_DPBB,
226   DBG_NO_HYPERZ,
227   DBG_NO_2D_TILING,
228   DBG_NO_TILING,
229   DBG_NO_DISPLAY_TILING,
230   DBG_NO_DISPLAY_DCC,
231   DBG_NO_DCC,
232   DBG_NO_DCC_CLEAR,
233   DBG_NO_DCC_STORE,
234   DBG_DCC_STORE,
235   DBG_NO_DCC_MSAA,
236   DBG_NO_FMASK,
237   DBG_NO_DMA,
238
239   DBG_TMZ,
240   DBG_SQTT,
241
242   DBG_COUNT
243};
244
245enum
246{
247   /* Tests: */
248   DBG_TEST_BLIT,
249   DBG_TEST_VMFAULT_CP,
250   DBG_TEST_VMFAULT_SHADER,
251   DBG_TEST_DMA_PERF,
252   DBG_TEST_GDS,
253   DBG_TEST_GDS_MM,
254   DBG_TEST_GDS_OA_MM,
255};
256
257#define DBG_ALL_SHADERS (((1 << (DBG_CS + 1)) - 1))
258#define DBG(name)       (1ull << DBG_##name)
259
260enum si_cache_policy
261{
262   L2_BYPASS,
263   L2_STREAM, /* same as SLC=1 */
264   L2_LRU,    /* same as SLC=0 */
265};
266
267enum si_coherency
268{
269   SI_COHERENCY_NONE, /* no cache flushes needed */
270   SI_COHERENCY_SHADER,
271   SI_COHERENCY_CB_META,
272   SI_COHERENCY_DB_META,
273   SI_COHERENCY_CP,
274};
275
276struct si_compute;
277struct si_shader_context;
278struct hash_table;
279
280/* Only 32-bit buffer allocations are supported, gallium doesn't support more
281 * at the moment.
282 */
283struct si_resource {
284   struct threaded_resource b;
285
286   /* Winsys objects. */
287   struct pb_buffer *buf;
288   uint64_t gpu_address;
289   /* Memory usage if the buffer placement is optimal. */
290   uint32_t memory_usage_kb;
291
292   /* Resource properties. */
293   uint64_t bo_size;
294   uint8_t bo_alignment_log2;
295   enum radeon_bo_domain domains:8;
296   enum radeon_bo_flag flags:16;
297   unsigned bind_history;
298
299   /* The buffer range which is initialized (with a write transfer,
300    * streamout, DMA, or as a random access target). The rest of
301    * the buffer is considered invalid and can be mapped unsynchronized.
302    *
303    * This allows unsynchronized mapping of a buffer range which hasn't
304    * been used yet. It's for applications which forget to use
305    * the unsynchronized map flag and expect the driver to figure it out.
306    */
307   struct util_range valid_buffer_range;
308
309   /* For buffers only. This indicates that a write operation has been
310    * performed by TC L2, but the cache hasn't been flushed.
311    * Any hw block which doesn't use or bypasses TC L2 should check this
312    * flag and flush the cache before using the buffer.
313    *
314    * For example, TC L2 must be flushed if a buffer which has been
315    * modified by a shader store instruction is about to be used as
316    * an index buffer. The reason is that VGT DMA index fetching doesn't
317    * use TC L2.
318    */
319   bool TC_L2_dirty;
320
321   /* Whether this resource is referenced by bindless handles. */
322   bool texture_handle_allocated;
323   bool image_handle_allocated;
324
325   /* Whether the resource has been exported via resource_get_handle. */
326   uint8_t external_usage; /* PIPE_HANDLE_USAGE_* */
327};
328
329struct si_transfer {
330   struct threaded_transfer b;
331   struct si_resource *staging;
332};
333
334struct si_texture {
335   struct si_resource buffer;
336
337   struct radeon_surf surface;
338   struct si_texture *flushed_depth_texture;
339
340   /* One texture allocation can contain these buffers:
341    * - image (pixel data)
342    * - FMASK buffer (MSAA compression)
343    * - CMASK buffer (MSAA compression and/or legacy fast color clear)
344    * - HTILE buffer (Z/S compression and fast Z/S clear)
345    * - DCC buffer (color compression and new fast color clear)
346    * - displayable DCC buffer (if the DCC buffer is not displayable)
347    */
348   uint64_t cmask_base_address_reg;
349   struct si_resource *cmask_buffer;
350   unsigned cb_color_info; /* fast clear enable bit */
351   unsigned color_clear_value[2];
352   unsigned last_msaa_resolve_target_micro_mode;
353   bool swap_rgb_to_bgr_on_next_clear;
354   bool swap_rgb_to_bgr;
355   unsigned num_level0_transfers;
356   unsigned plane_index; /* other planes are different pipe_resources */
357   unsigned num_planes;
358
359   /* Depth buffer compression and fast clear. */
360   float depth_clear_value[RADEON_SURF_MAX_LEVELS];
361   uint8_t stencil_clear_value[RADEON_SURF_MAX_LEVELS];
362   uint16_t depth_cleared_level_mask_once; /* if it was cleared at least once */
363   uint16_t depth_cleared_level_mask;     /* track if it's cleared (can be false negative) */
364   uint16_t stencil_cleared_level_mask; /* if it was cleared at least once */
365   uint16_t dirty_level_mask;         /* each bit says if that mipmap is compressed */
366   uint16_t stencil_dirty_level_mask; /* each bit says if that mipmap is compressed */
367   enum pipe_format db_render_format : 16;
368   bool fmask_is_identity : 1;
369   bool tc_compatible_htile : 1;
370   bool enable_tc_compatible_htile_next_clear : 1;
371   bool htile_stencil_disabled : 1;
372   bool upgraded_depth : 1;  /* upgraded from unorm to Z32_FLOAT */
373   bool is_depth : 1;
374   bool db_compatible : 1;
375   bool can_sample_z : 1;
376   bool can_sample_s : 1;
377   bool need_flush_after_depth_decompression: 1;
378
379   /* We need to track DCC dirtiness, because st/dri usually calls
380    * flush_resource twice per frame (not a bug) and we don't wanna
381    * decompress DCC twice.
382    */
383   bool displayable_dcc_dirty : 1;
384
385   /* Counter that should be non-zero if the texture is bound to a
386    * framebuffer.
387    */
388   unsigned framebuffers_bound;
389};
390
391/* State trackers create separate textures in a next-chain for extra planes
392 * even if those are planes created purely for modifiers. Because the linking
393 * of the chain happens outside of the driver, and NULL is interpreted as
394 * failure, let's create some dummy texture structs. We could use these
395 * later to use the offsets for linking if we really wanted to.
396 *
397 * For now just create a dummy struct and completely ignore it.
398 *
399 * Potentially in the future we could store stride/offset and use it during
400 * creation, though we might want to change how linking is done first.
401 */
402struct si_auxiliary_texture {
403   struct threaded_resource b;
404   struct pb_buffer *buffer;
405   uint32_t offset;
406   uint32_t stride;
407};
408
409struct si_surface {
410   struct pipe_surface base;
411
412   /* These can vary with block-compressed textures. */
413   uint16_t width0;
414   uint16_t height0;
415
416   bool color_initialized : 1;
417   bool depth_initialized : 1;
418
419   /* Misc. color flags. */
420   bool color_is_int8 : 1;
421   bool color_is_int10 : 1;
422   bool dcc_incompatible : 1;
423
424   /* Color registers. */
425   unsigned cb_color_info;
426   unsigned cb_color_view;
427   unsigned cb_color_attrib;
428   unsigned cb_color_attrib2;                      /* GFX9 and later */
429   unsigned cb_color_attrib3;                      /* GFX10 and later */
430   unsigned cb_dcc_control;                        /* GFX8 and later */
431   unsigned spi_shader_col_format : 8;             /* no blending, no alpha-to-coverage. */
432   unsigned spi_shader_col_format_alpha : 8;       /* alpha-to-coverage */
433   unsigned spi_shader_col_format_blend : 8;       /* blending without alpha. */
434   unsigned spi_shader_col_format_blend_alpha : 8; /* blending with alpha. */
435
436   /* DB registers. */
437   uint64_t db_depth_base; /* DB_Z_READ/WRITE_BASE */
438   uint64_t db_stencil_base;
439   uint64_t db_htile_data_base;
440   unsigned db_depth_info;
441   unsigned db_z_info;
442   unsigned db_z_info2; /* GFX9 only */
443   unsigned db_depth_view;
444   unsigned db_depth_size;
445   unsigned db_depth_slice;
446   unsigned db_stencil_info;
447   unsigned db_stencil_info2; /* GFX9 only */
448   unsigned db_htile_surface;
449};
450
451struct si_mmio_counter {
452   unsigned busy;
453   unsigned idle;
454};
455
456union si_mmio_counters {
457   struct si_mmio_counters_named {
458      /* For global GPU load including SDMA. */
459      struct si_mmio_counter gpu;
460
461      /* GRBM_STATUS */
462      struct si_mmio_counter spi;
463      struct si_mmio_counter gui;
464      struct si_mmio_counter ta;
465      struct si_mmio_counter gds;
466      struct si_mmio_counter vgt;
467      struct si_mmio_counter ia;
468      struct si_mmio_counter sx;
469      struct si_mmio_counter wd;
470      struct si_mmio_counter bci;
471      struct si_mmio_counter sc;
472      struct si_mmio_counter pa;
473      struct si_mmio_counter db;
474      struct si_mmio_counter cp;
475      struct si_mmio_counter cb;
476
477      /* SRBM_STATUS2 */
478      struct si_mmio_counter sdma;
479
480      /* CP_STAT */
481      struct si_mmio_counter pfp;
482      struct si_mmio_counter meq;
483      struct si_mmio_counter me;
484      struct si_mmio_counter surf_sync;
485      struct si_mmio_counter cp_dma;
486      struct si_mmio_counter scratch_ram;
487   } named;
488
489   unsigned array[sizeof(struct si_mmio_counters_named) / sizeof(unsigned)];
490};
491
492struct si_memory_object {
493   struct pipe_memory_object b;
494   struct pb_buffer *buf;
495   uint32_t stride;
496};
497
498/* Saved CS data for debugging features. */
499struct radeon_saved_cs {
500   uint32_t *ib;
501   unsigned num_dw;
502
503   struct radeon_bo_list_item *bo_list;
504   unsigned bo_count;
505};
506
507struct si_screen {
508   struct pipe_screen b;
509   struct radeon_winsys *ws;
510   struct disk_cache *disk_shader_cache;
511
512   struct radeon_info info;
513   struct nir_shader_compiler_options nir_options;
514   uint64_t debug_flags;
515   char renderer_string[183];
516
517   void (*make_texture_descriptor)(struct si_screen *screen, struct si_texture *tex, bool sampler,
518                                   enum pipe_texture_target target, enum pipe_format pipe_format,
519                                   const unsigned char state_swizzle[4], unsigned first_level,
520                                   unsigned last_level, unsigned first_layer, unsigned last_layer,
521                                   unsigned width, unsigned height, unsigned depth, uint32_t *state,
522                                   uint32_t *fmask_state);
523
524   unsigned max_memory_usage_kb;
525   unsigned pa_sc_raster_config;
526   unsigned pa_sc_raster_config_1;
527   unsigned se_tile_repeat;
528   unsigned gs_table_depth;
529   unsigned tess_offchip_block_dw_size;
530   unsigned tess_offchip_ring_size;
531   unsigned tess_factor_ring_size;
532   unsigned vgt_hs_offchip_param;
533   unsigned eqaa_force_coverage_samples;
534   unsigned eqaa_force_z_samples;
535   unsigned eqaa_force_color_samples;
536   unsigned pbb_context_states_per_bin;
537   unsigned pbb_persistent_states_per_bin;
538   bool has_draw_indirect_multi;
539   bool has_out_of_order_rast;
540   bool assume_no_z_fights;
541   bool commutative_blend_add;
542   bool allow_draw_out_of_order;
543   bool dpbb_allowed;
544   bool use_ngg;
545   bool use_ngg_culling;
546   bool use_ngg_streamout;
547   bool allow_dcc_msaa_clear_to_reg_for_bpp[5]; /* indexed by log2(Bpp) */
548   bool always_allow_dcc_stores;
549
550   struct {
551#define OPT_BOOL(name, dflt, description) bool name : 1;
552#include "si_debug_options.h"
553   } options;
554
555   /* Whether shaders are monolithic (1-part) or separate (3-part). */
556   bool use_monolithic_shaders;
557   bool record_llvm_ir;
558
559   struct slab_parent_pool pool_transfers;
560
561   /* Texture filter settings. */
562   int force_aniso; /* -1 = disabled */
563
564   /* Auxiliary context. Mainly used to initialize resources.
565    * It must be locked prior to using and flushed before unlocking. */
566   struct pipe_context *aux_context;
567   simple_mtx_t aux_context_lock;
568
569   /* Async compute context for DRI_PRIME copies. */
570   struct pipe_context *async_compute_context;
571   simple_mtx_t async_compute_context_lock;
572
573   /* This must be in the screen, because UE4 uses one context for
574    * compilation and another one for rendering.
575    */
576   unsigned num_compilations;
577   /* Along with ST_DEBUG=precompile, this should show if applications
578    * are loading shaders on demand. This is a monotonic counter.
579    */
580   unsigned num_shaders_created;
581   unsigned num_memory_shader_cache_hits;
582   unsigned num_memory_shader_cache_misses;
583   unsigned num_disk_shader_cache_hits;
584   unsigned num_disk_shader_cache_misses;
585
586   /* GPU load thread. */
587   simple_mtx_t gpu_load_mutex;
588   thrd_t gpu_load_thread;
589   union si_mmio_counters mmio_counters;
590   volatile unsigned gpu_load_stop_thread; /* bool */
591
592   /* Performance counters. */
593   struct si_perfcounters *perfcounters;
594
595   /* If pipe_screen wants to recompute and re-emit the framebuffer,
596    * sampler, and image states of all contexts, it should atomically
597    * increment this.
598    *
599    * Each context will compare this with its own last known value of
600    * the counter before drawing and re-emit the states accordingly.
601    */
602   unsigned dirty_tex_counter;
603   unsigned dirty_buf_counter;
604
605   /* Atomically increment this counter when an existing texture's
606    * metadata is enabled or disabled in a way that requires changing
607    * contexts' compressed texture binding masks.
608    */
609   unsigned compressed_colortex_counter;
610
611   struct {
612      /* Context flags to set so that all writes from earlier jobs
613       * in the CP are seen by L2 clients.
614       */
615      unsigned cp_to_L2;
616
617      /* Context flags to set so that all writes from earlier jobs
618       * that end in L2 are seen by CP.
619       */
620      unsigned L2_to_cp;
621   } barrier_flags;
622
623   simple_mtx_t shader_parts_mutex;
624   struct si_shader_part *vs_prologs;
625   struct si_shader_part *tcs_epilogs;
626   struct si_shader_part *gs_prologs;
627   struct si_shader_part *ps_prologs;
628   struct si_shader_part *ps_epilogs;
629
630   /* Shader cache in memory.
631    *
632    * Design & limitations:
633    * - The shader cache is per screen (= per process), never saved to
634    *   disk, and skips redundant shader compilations from NIR to bytecode.
635    * - It can only be used with one-variant-per-shader support, in which
636    *   case only the main (typically middle) part of shaders is cached.
637    * - Only VS, TCS, TES, PS are cached, out of which only the hw VS
638    *   variants of VS and TES are cached, so LS and ES aren't.
639    * - GS and CS aren't cached, but it's certainly possible to cache
640    *   those as well.
641    */
642   simple_mtx_t shader_cache_mutex;
643   struct hash_table *shader_cache;
644   /* Maximum and current size */
645   uint32_t shader_cache_size;
646   uint32_t shader_cache_max_size;
647
648   /* Shader cache of live shaders. */
649   struct util_live_shader_cache live_shader_cache;
650
651   /* Shader compiler queue for multithreaded compilation. */
652   struct util_queue shader_compiler_queue;
653   /* Use at most 3 normal compiler threads on quadcore and better.
654    * Hyperthreaded CPUs report the number of threads, but we want
655    * the number of cores. We only need this many threads for shader-db. */
656   struct ac_llvm_compiler compiler[24]; /* used by the queue only */
657
658   struct util_queue shader_compiler_queue_low_priority;
659   /* Use at most 2 low priority threads on quadcore and better.
660    * We want to minimize the impact on multithreaded Mesa. */
661   struct ac_llvm_compiler compiler_lowp[10];
662
663   unsigned compute_wave_size;
664   unsigned ps_wave_size;
665   unsigned ge_wave_size;
666   unsigned ngg_subgroup_size;
667
668   struct util_idalloc_mt buffer_ids;
669   struct util_vertex_state_cache vertex_state_cache;
670};
671
672struct si_sampler_view {
673   struct pipe_sampler_view base;
674   /* [0..7] = image descriptor
675    * [4..7] = buffer descriptor */
676   uint32_t state[8];
677   uint32_t fmask_state[8];
678   const struct legacy_surf_level *base_level_info;
679   ubyte base_level;
680   ubyte block_width;
681   bool is_stencil_sampler;
682   bool dcc_incompatible;
683};
684
685#define SI_SAMPLER_STATE_MAGIC 0x34f1c35a
686
687struct si_sampler_state {
688#ifndef NDEBUG
689   unsigned magic;
690#endif
691   uint32_t val[4];
692   uint32_t upgraded_depth_val[4];
693};
694
695struct si_cs_shader_state {
696   struct si_compute *program;
697   struct si_compute *emitted_program;
698   unsigned offset;
699   bool initialized;
700   bool uses_scratch;
701};
702
703struct si_samplers {
704   struct pipe_sampler_view *views[SI_NUM_SAMPLERS];
705   struct si_sampler_state *sampler_states[SI_NUM_SAMPLERS];
706
707   /* The i-th bit is set if that element is enabled (non-NULL resource). */
708   unsigned enabled_mask;
709   uint32_t needs_depth_decompress_mask;
710   uint32_t needs_color_decompress_mask;
711};
712
713struct si_images {
714   struct pipe_image_view views[SI_NUM_IMAGES];
715   uint32_t needs_color_decompress_mask;
716   unsigned enabled_mask;
717   unsigned display_dcc_store_mask;
718};
719
720struct si_framebuffer {
721   struct pipe_framebuffer_state state;
722   unsigned colorbuf_enabled_4bit;
723   unsigned spi_shader_col_format;
724   unsigned spi_shader_col_format_alpha;
725   unsigned spi_shader_col_format_blend;
726   unsigned spi_shader_col_format_blend_alpha;
727   ubyte nr_samples : 5;   /* at most 16xAA */
728   ubyte log_samples : 3;  /* at most 4 = 16xAA */
729   ubyte nr_color_samples; /* at most 8xAA */
730   ubyte compressed_cb_mask;
731   ubyte uncompressed_cb_mask;
732   ubyte color_is_int8;
733   ubyte color_is_int10;
734   ubyte dirty_cbufs;
735   ubyte dcc_overwrite_combiner_watermark;
736   ubyte min_bytes_per_pixel;
737   bool dirty_zsbuf;
738   bool any_dst_linear;
739   bool CB_has_shader_readable_metadata;
740   bool DB_has_shader_readable_metadata;
741   bool all_DCC_pipe_aligned;
742   bool has_dcc_msaa;
743};
744
745enum si_quant_mode
746{
747   /* This is the list we want to support. */
748   SI_QUANT_MODE_16_8_FIXED_POINT_1_256TH,
749   SI_QUANT_MODE_14_10_FIXED_POINT_1_1024TH,
750   SI_QUANT_MODE_12_12_FIXED_POINT_1_4096TH,
751};
752
753struct si_signed_scissor {
754   int minx;
755   int miny;
756   int maxx;
757   int maxy;
758   enum si_quant_mode quant_mode;
759};
760
761struct si_viewports {
762   struct pipe_viewport_state states[SI_MAX_VIEWPORTS];
763   struct si_signed_scissor as_scissor[SI_MAX_VIEWPORTS];
764};
765
766struct si_streamout_target {
767   struct pipe_stream_output_target b;
768
769   /* The buffer where BUFFER_FILLED_SIZE is stored. */
770   struct si_resource *buf_filled_size;
771   unsigned buf_filled_size_offset;
772   bool buf_filled_size_valid;
773
774   unsigned stride_in_dw;
775};
776
777struct si_streamout {
778   bool begin_emitted;
779
780   unsigned enabled_mask;
781   unsigned num_targets;
782   struct si_streamout_target *targets[PIPE_MAX_SO_BUFFERS];
783
784   unsigned append_bitmask;
785   bool suspended;
786
787   /* External state which comes from the vertex shader,
788    * it must be set explicitly when binding a shader. */
789   uint16_t *stride_in_dw;
790   unsigned enabled_stream_buffers_mask; /* stream0 buffers0-3 in 4 LSB */
791
792   /* The state of VGT_STRMOUT_BUFFER_(CONFIG|EN). */
793   unsigned hw_enabled_mask;
794
795   /* The state of VGT_STRMOUT_(CONFIG|EN). */
796   bool streamout_enabled;
797   bool prims_gen_query_enabled;
798   int num_prims_gen_queries;
799};
800
801/* A shader state consists of the shader selector, which is a constant state
802 * object shared by multiple contexts and shouldn't be modified, and
803 * the current shader variant selected for this context.
804 */
805struct si_shader_ctx_state {
806   struct si_shader_selector *cso;
807   struct si_shader *current;
808   /* The shader variant key representing the current state. */
809   struct si_shader_key key;
810};
811
812#define SI_NUM_VGT_PARAM_KEY_BITS 12
813#define SI_NUM_VGT_PARAM_STATES   (1 << SI_NUM_VGT_PARAM_KEY_BITS)
814
815/* The IA_MULTI_VGT_PARAM key used to index the table of precomputed values.
816 * Some fields are set by state-change calls, most are set by draw_vbo.
817 */
818union si_vgt_param_key {
819   struct {
820#if UTIL_ARCH_LITTLE_ENDIAN
821      uint16_t prim : 4;
822      uint16_t uses_instancing : 1;
823      uint16_t multi_instances_smaller_than_primgroup : 1;
824      uint16_t primitive_restart : 1;
825      uint16_t count_from_stream_output : 1;
826      uint16_t line_stipple_enabled : 1;
827      uint16_t uses_tess : 1;
828      uint16_t tess_uses_prim_id : 1;
829      uint16_t uses_gs : 1;
830      uint16_t _pad : 16 - SI_NUM_VGT_PARAM_KEY_BITS;
831#else /* UTIL_ARCH_BIG_ENDIAN */
832      uint16_t _pad : 16 - SI_NUM_VGT_PARAM_KEY_BITS;
833      uint16_t uses_gs : 1;
834      uint16_t tess_uses_prim_id : 1;
835      uint16_t uses_tess : 1;
836      uint16_t line_stipple_enabled : 1;
837      uint16_t count_from_stream_output : 1;
838      uint16_t primitive_restart : 1;
839      uint16_t multi_instances_smaller_than_primgroup : 1;
840      uint16_t uses_instancing : 1;
841      uint16_t prim : 4;
842#endif
843   } u;
844   uint16_t index;
845};
846
847struct si_texture_handle {
848   unsigned desc_slot;
849   bool desc_dirty;
850   struct pipe_sampler_view *view;
851   struct si_sampler_state sstate;
852};
853
854struct si_image_handle {
855   unsigned desc_slot;
856   bool desc_dirty;
857   struct pipe_image_view view;
858};
859
860struct si_saved_cs {
861   struct pipe_reference reference;
862   struct si_context *ctx;
863   struct radeon_saved_cs gfx;
864   struct radeon_saved_cs compute;
865   struct si_resource *trace_buf;
866   unsigned trace_id;
867
868   unsigned gfx_last_dw;
869   bool flushed;
870   int64_t time_flush;
871};
872
873struct si_small_prim_cull_info {
874   float scale[2], translate[2];
875   float small_prim_precision;
876};
877
878struct si_vertex_state {
879   struct pipe_vertex_state b;
880   struct si_vertex_elements velems;
881   uint32_t descriptors[4 * SI_MAX_ATTRIBS];
882};
883
884typedef void (*pipe_draw_vbo_func)(struct pipe_context *pipe,
885                                   const struct pipe_draw_info *info,
886                                   unsigned drawid_offset,
887                                   const struct pipe_draw_indirect_info *indirect,
888                                   const struct pipe_draw_start_count_bias *draws,
889                                   unsigned num_draws);
890typedef void (*pipe_draw_vertex_state_func)(struct pipe_context *ctx,
891                                            struct pipe_vertex_state *vstate,
892                                            uint32_t partial_velem_mask,
893                                            struct pipe_draw_vertex_state_info info,
894                                            const struct pipe_draw_start_count_bias *draws,
895                                            unsigned num_draws);
896
897struct si_context {
898   struct pipe_context b; /* base class */
899
900   enum radeon_family family;
901   enum chip_class chip_class;
902
903   struct radeon_winsys *ws;
904   struct radeon_winsys_ctx *ctx;
905   struct radeon_cmdbuf gfx_cs; /* compute IB if graphics is disabled */
906   struct radeon_cmdbuf *sdma_cs;
907   struct pipe_fence_handle *last_gfx_fence;
908   struct si_resource *eop_bug_scratch;
909   struct si_resource *eop_bug_scratch_tmz;
910   struct u_upload_mgr *cached_gtt_allocator;
911   struct threaded_context *tc;
912   struct u_suballocator allocator_zeroed_memory;
913   struct slab_child_pool pool_transfers;
914   struct slab_child_pool pool_transfers_unsync; /* for threaded_context */
915   struct pipe_device_reset_callback device_reset_callback;
916   struct u_log_context *log;
917   void *query_result_shader;
918   void *sh_query_result_shader;
919   struct si_resource *shadowed_regs;
920
921   void (*emit_cache_flush)(struct si_context *ctx, struct radeon_cmdbuf *cs);
922
923   struct blitter_context *blitter;
924   void *noop_blend;
925   void *noop_dsa;
926   void *no_velems_state;
927   void *discard_rasterizer_state;
928   void *custom_dsa_flush;
929   void *custom_blend_resolve;
930   void *custom_blend_fmask_decompress;
931   void *custom_blend_eliminate_fastclear;
932   void *custom_blend_dcc_decompress;
933   void *vs_blit_pos;
934   void *vs_blit_pos_layered;
935   void *vs_blit_color;
936   void *vs_blit_color_layered;
937   void *vs_blit_texcoord;
938   void *cs_clear_buffer;
939   void *cs_clear_buffer_rmw;
940   void *cs_copy_buffer;
941   void *cs_copy_image;
942   void *cs_copy_image_1d_array;
943   void *cs_clear_render_target;
944   void *cs_clear_render_target_1d_array;
945   void *cs_clear_12bytes_buffer;
946   void *cs_dcc_decompress;
947   void *cs_dcc_retile[32];
948   void *cs_fmask_expand[3][2]; /* [log2(samples)-1][is_array] */
949   struct si_screen *screen;
950   struct pipe_debug_callback debug;
951   struct ac_llvm_compiler compiler; /* only non-threaded compilation */
952   struct si_shader_ctx_state fixed_func_tcs_shader;
953   /* Offset 0: EOP flush number; Offset 4: GDS prim restart counter */
954   struct si_resource *wait_mem_scratch;
955   struct si_resource *wait_mem_scratch_tmz;
956   unsigned wait_mem_number;
957   uint16_t prefetch_L2_mask;
958
959   bool blitter_running;
960   bool is_noop:1;
961   bool has_graphics:1;
962   bool gfx_flush_in_progress : 1;
963   bool gfx_last_ib_is_busy : 1;
964   bool compute_is_busy : 1;
965   int8_t pipeline_stats_enabled; /* -1 = unknown, 0 = disabled, 1 = enabled */
966
967   unsigned num_gfx_cs_flushes;
968   unsigned initial_gfx_cs_size;
969   unsigned last_dirty_tex_counter;
970   unsigned last_dirty_buf_counter;
971   unsigned last_compressed_colortex_counter;
972   unsigned last_num_draw_calls;
973   unsigned flags; /* flush flags */
974   /* Current unaccounted memory usage. */
975   uint32_t memory_usage_kb;
976
977   /* NGG streamout. */
978   struct pb_buffer *gds;
979   struct pb_buffer *gds_oa;
980
981   /* Atoms (direct states). */
982   union si_state_atoms atoms;
983   unsigned dirty_atoms; /* mask */
984   /* PM4 states (precomputed immutable states) */
985   unsigned dirty_states;
986   union si_state queued;
987   union si_state emitted;
988
989   /* Atom declarations. */
990   struct si_framebuffer framebuffer;
991   unsigned sample_locs_num_samples;
992   uint16_t sample_mask;
993   unsigned last_cb_target_mask;
994   struct pipe_blend_color blend_color;
995   struct pipe_clip_state clip_state;
996   struct si_shader_data shader_pointers;
997   struct si_stencil_ref stencil_ref;
998   bool blend_color_any_nonzeros:1;
999   bool clip_state_any_nonzeros:1;
1000   bool viewport0_y_inverted;
1001   struct pipe_scissor_state scissors[SI_MAX_VIEWPORTS];
1002   struct si_streamout streamout;
1003   struct si_viewports viewports;
1004   unsigned num_window_rectangles;
1005   bool window_rectangles_include;
1006   struct pipe_scissor_state window_rectangles[4];
1007
1008   /* Precomputed states. */
1009   struct si_pm4_state *cs_preamble_state;
1010   struct si_pm4_state *cs_preamble_tess_rings;
1011   struct si_pm4_state *cs_preamble_tess_rings_tmz;
1012   struct si_pm4_state *cs_preamble_gs_rings;
1013   bool cs_preamble_has_vgt_flush;
1014   struct si_pm4_state *vgt_shader_config[SI_NUM_VGT_STAGES_STATES];
1015
1016   /* shaders */
1017   union {
1018      struct {
1019         struct si_shader_ctx_state vs;
1020         struct si_shader_ctx_state ps;
1021         struct si_shader_ctx_state gs;
1022         struct si_shader_ctx_state tcs;
1023         struct si_shader_ctx_state tes;
1024      } shader;
1025      /* indexed access using pipe_shader_type (not by MESA_SHADER_*) */
1026      struct si_shader_ctx_state shaders[SI_NUM_GRAPHICS_SHADERS];
1027   };
1028   struct si_cs_shader_state cs_shader_state;
1029
1030   /* shader information */
1031   uint64_t ps_inputs_read_or_disabled;
1032   struct si_vertex_elements *vertex_elements;
1033   unsigned num_vertex_elements;
1034   unsigned cs_max_waves_per_sh;
1035   bool uses_nontrivial_vs_prolog;
1036   bool force_trivial_vs_prolog;
1037   bool do_update_shaders;
1038   bool compute_shaderbuf_sgprs_dirty;
1039   bool compute_image_sgprs_dirty;
1040   bool vs_uses_base_instance;
1041   bool vs_uses_draw_id;
1042   uint8_t patch_vertices;
1043
1044   /* shader descriptors */
1045   struct si_descriptors descriptors[SI_NUM_DESCS];
1046   unsigned descriptors_dirty;
1047   unsigned shader_pointers_dirty;
1048   unsigned shader_needs_decompress_mask;
1049   struct si_buffer_resources internal_bindings;
1050   struct si_buffer_resources const_and_shader_buffers[SI_NUM_SHADERS];
1051   struct si_samplers samplers[SI_NUM_SHADERS];
1052   struct si_images images[SI_NUM_SHADERS];
1053   bool bo_list_add_all_resident_resources;
1054   bool bo_list_add_all_gfx_resources;
1055   bool bo_list_add_all_compute_resources;
1056
1057   /* other shader resources */
1058   struct pipe_constant_buffer null_const_buf; /* used for set_constant_buffer(NULL) on GFX7 */
1059   struct pipe_resource *esgs_ring;
1060   struct pipe_resource *gsvs_ring;
1061   struct pipe_resource *tess_rings;
1062   struct pipe_resource *tess_rings_tmz;
1063   union pipe_color_union *border_color_table; /* in CPU memory, any endian */
1064   struct si_resource *border_color_buffer;
1065   union pipe_color_union *border_color_map; /* in VRAM (slow access), little endian */
1066   unsigned border_color_count;
1067   unsigned num_vs_blit_sgprs;
1068   uint32_t vs_blit_sh_data[SI_VS_BLIT_SGPRS_POS_TEXCOORD];
1069   uint32_t cs_user_data[4];
1070
1071   /* Vertex buffers. */
1072   bool vertex_buffers_dirty;
1073   bool vertex_buffer_pointer_dirty;
1074   bool vertex_buffer_user_sgprs_dirty;
1075   struct pipe_vertex_buffer vertex_buffer[SI_NUM_VERTEX_BUFFERS];
1076   uint16_t vertex_buffer_unaligned; /* bitmask of not dword-aligned buffers */
1077   uint32_t *vb_descriptors_gpu_list;
1078   struct si_resource *vb_descriptors_buffer;
1079   unsigned vb_descriptors_offset;
1080   unsigned vb_descriptor_user_sgprs[5 * 4];
1081
1082   /* MSAA config state. */
1083   int ps_iter_samples;
1084   bool ps_uses_fbfetch;
1085   bool smoothing_enabled;
1086
1087   /* DB render state. */
1088   unsigned ps_db_shader_control;
1089   unsigned dbcb_copy_sample;
1090   bool dbcb_depth_copy_enabled : 1;
1091   bool dbcb_stencil_copy_enabled : 1;
1092   bool db_flush_depth_inplace : 1;
1093   bool db_flush_stencil_inplace : 1;
1094   bool db_depth_clear : 1;
1095   bool db_depth_disable_expclear : 1;
1096   bool db_stencil_clear : 1;
1097   bool db_stencil_disable_expclear : 1;
1098   bool occlusion_queries_disabled : 1;
1099   bool generate_mipmap_for_depth : 1;
1100   bool allow_flat_shading : 1;
1101
1102   /* Emitted draw state. */
1103   bool ngg : 1;
1104   uint8_t ngg_culling;
1105   unsigned last_index_size;
1106   int last_base_vertex;
1107   unsigned last_start_instance;
1108   unsigned last_instance_count;
1109   unsigned last_drawid;
1110   unsigned last_sh_base_reg;
1111   int last_primitive_restart_en;
1112   unsigned last_restart_index;
1113   unsigned last_prim;
1114   unsigned last_multi_vgt_param;
1115   unsigned last_gs_out_prim;
1116   int last_binning_enabled;
1117   unsigned current_vs_state;
1118   unsigned last_vs_state;
1119   enum pipe_prim_type current_rast_prim; /* primitive type after TES, GS */
1120
1121   struct si_small_prim_cull_info last_small_prim_cull_info;
1122   struct si_resource *small_prim_cull_info_buf;
1123   uint64_t small_prim_cull_info_address;
1124
1125   /* Scratch buffer */
1126   struct si_resource *scratch_buffer;
1127   unsigned scratch_waves;
1128   unsigned spi_tmpring_size;
1129   unsigned max_seen_scratch_bytes_per_wave;
1130   unsigned max_seen_compute_scratch_bytes_per_wave;
1131
1132   struct si_resource *compute_scratch_buffer;
1133
1134   /* Emitted derived tessellation state. */
1135   /* Local shader (VS), or HS if LS-HS are merged. */
1136   struct si_shader *last_ls;
1137   struct si_shader_selector *last_tcs;
1138   unsigned last_num_tcs_input_cp;
1139   unsigned last_tes_sh_base;
1140   bool last_tess_uses_primid;
1141   unsigned last_num_patches;
1142   unsigned last_ls_hs_config;
1143
1144   /* Debug state. */
1145   bool is_debug;
1146   struct si_saved_cs *current_saved_cs;
1147   uint64_t dmesg_timestamp;
1148   unsigned apitrace_call_number;
1149
1150   /* Other state */
1151   bool need_check_render_feedback;
1152   bool decompression_enabled;
1153   bool dpbb_force_off;
1154   bool vs_writes_viewport_index;
1155   bool vs_disables_clipping_viewport;
1156
1157   /* Precomputed IA_MULTI_VGT_PARAM */
1158   union si_vgt_param_key ia_multi_vgt_param_key;
1159   unsigned ia_multi_vgt_param[SI_NUM_VGT_PARAM_STATES];
1160
1161   /* Bindless descriptors. */
1162   struct si_descriptors bindless_descriptors;
1163   struct util_idalloc bindless_used_slots;
1164   unsigned num_bindless_descriptors;
1165   bool bindless_descriptors_dirty;
1166   bool graphics_bindless_pointer_dirty;
1167   bool compute_bindless_pointer_dirty;
1168
1169   /* Allocated bindless handles */
1170   struct hash_table *tex_handles;
1171   struct hash_table *img_handles;
1172
1173   /* Resident bindless handles */
1174   struct util_dynarray resident_tex_handles;
1175   struct util_dynarray resident_img_handles;
1176
1177   /* Resident bindless handles which need decompression */
1178   struct util_dynarray resident_tex_needs_color_decompress;
1179   struct util_dynarray resident_img_needs_color_decompress;
1180   struct util_dynarray resident_tex_needs_depth_decompress;
1181
1182   /* Bindless state */
1183   bool uses_bindless_samplers;
1184   bool uses_bindless_images;
1185
1186   /* MSAA sample locations.
1187    * The first index is the sample index.
1188    * The second index is the coordinate: X, Y. */
1189   struct {
1190      float x1[1][2];
1191      float x2[2][2];
1192      float x4[4][2];
1193      float x8[8][2];
1194      float x16[16][2];
1195   } sample_positions;
1196   struct pipe_resource *sample_pos_buffer;
1197
1198   /* Misc stats. */
1199   unsigned num_draw_calls;
1200   unsigned num_decompress_calls;
1201   unsigned num_prim_restart_calls;
1202   unsigned num_compute_calls;
1203   unsigned num_cp_dma_calls;
1204   unsigned num_vs_flushes;
1205   unsigned num_ps_flushes;
1206   unsigned num_cs_flushes;
1207   unsigned num_cb_cache_flushes;
1208   unsigned num_db_cache_flushes;
1209   unsigned num_L2_invalidates;
1210   unsigned num_L2_writebacks;
1211   unsigned num_resident_handles;
1212   uint64_t num_alloc_tex_transfer_bytes;
1213   unsigned last_tex_ps_draw_ratio; /* for query */
1214   unsigned context_roll;
1215
1216   /* Queries. */
1217   /* Maintain the list of active queries for pausing between IBs. */
1218   int num_occlusion_queries;
1219   int num_perfect_occlusion_queries;
1220   int num_pipeline_stat_queries;
1221   struct list_head active_queries;
1222   unsigned num_cs_dw_queries_suspend;
1223
1224   /* Render condition. */
1225   struct pipe_query *render_cond;
1226   unsigned render_cond_mode;
1227   bool render_cond_invert;
1228   bool render_cond_enabled; /* for u_blitter */
1229
1230   /* Shader-based queries. */
1231   struct list_head shader_query_buffers;
1232   unsigned num_active_shader_queries;
1233
1234   bool force_cb_shader_coherent;
1235
1236   struct si_tracked_regs tracked_regs;
1237
1238   /* Resources that need to be flushed, but will not get an explicit
1239    * flush_resource from the frontend and that will need to get flushed during
1240    * a context flush.
1241    */
1242   struct hash_table *dirty_implicit_resources;
1243
1244   pipe_draw_vbo_func draw_vbo[2][2][2];
1245   pipe_draw_vertex_state_func draw_vertex_state[2][2][2];
1246   /* When b.draw_vbo is a wrapper, real_draw_vbo is the real draw_vbo function */
1247   pipe_draw_vbo_func real_draw_vbo;
1248   pipe_draw_vertex_state_func real_draw_vertex_state;
1249   void (*emit_spi_map[33])(struct si_context *sctx);
1250
1251   /* SQTT */
1252   struct ac_thread_trace_data *thread_trace;
1253   struct pipe_fence_handle *last_sqtt_fence;
1254   enum rgp_sqtt_marker_event_type sqtt_next_event;
1255   bool thread_trace_enabled;
1256
1257   unsigned context_flags;
1258
1259   /* Shaders. */
1260   /* TODO: move other shaders here too */
1261   /* Only used for DCC MSAA clears with 4-8 fragments and 4-16 samples. */
1262   void *cs_clear_dcc_msaa[32][5][2][3][2]; /* [swizzle_mode][log2(bpe)][fragments == 8][log2(samples)-2][is_array] */
1263};
1264
1265/* si_blit.c */
1266enum si_blitter_op /* bitmask */
1267{
1268   SI_SAVE_TEXTURES = 1,
1269   SI_SAVE_FRAMEBUFFER = 2,
1270   SI_SAVE_FRAGMENT_STATE = 4,
1271   SI_DISABLE_RENDER_COND = 8,
1272};
1273
1274void si_blitter_begin(struct si_context *sctx, enum si_blitter_op op);
1275void si_blitter_end(struct si_context *sctx);
1276void si_init_blit_functions(struct si_context *sctx);
1277void si_decompress_textures(struct si_context *sctx, unsigned shader_mask);
1278void si_decompress_subresource(struct pipe_context *ctx, struct pipe_resource *tex, unsigned planes,
1279                               unsigned level, unsigned first_layer, unsigned last_layer);
1280void si_resource_copy_region(struct pipe_context *ctx, struct pipe_resource *dst,
1281                             unsigned dst_level, unsigned dstx, unsigned dsty, unsigned dstz,
1282                             struct pipe_resource *src, unsigned src_level,
1283                             const struct pipe_box *src_box);
1284void si_decompress_dcc(struct si_context *sctx, struct si_texture *tex);
1285void si_flush_implicit_resources(struct si_context *sctx);
1286
1287/* si_nir_optim.c */
1288bool si_nir_is_output_const_if_tex_is_const(nir_shader *shader, float *in, float *out, int *texunit);
1289
1290/* si_buffer.c */
1291bool si_cs_is_buffer_referenced(struct si_context *sctx, struct pb_buffer *buf,
1292                                enum radeon_bo_usage usage);
1293void *si_buffer_map(struct si_context *sctx, struct si_resource *resource,
1294                    unsigned usage);
1295void si_init_resource_fields(struct si_screen *sscreen, struct si_resource *res, uint64_t size,
1296                             unsigned alignment);
1297bool si_alloc_resource(struct si_screen *sscreen, struct si_resource *res);
1298struct pipe_resource *pipe_aligned_buffer_create(struct pipe_screen *screen, unsigned flags,
1299                                                 unsigned usage, unsigned size, unsigned alignment);
1300struct si_resource *si_aligned_buffer_create(struct pipe_screen *screen, unsigned flags,
1301                                             unsigned usage, unsigned size, unsigned alignment);
1302void si_replace_buffer_storage(struct pipe_context *ctx, struct pipe_resource *dst,
1303                               struct pipe_resource *src, unsigned num_rebinds,
1304                               uint32_t rebind_mask, uint32_t delete_buffer_id);
1305void si_init_screen_buffer_functions(struct si_screen *sscreen);
1306void si_init_buffer_functions(struct si_context *sctx);
1307
1308/* si_clear.c */
1309#define SI_CLEAR_TYPE_CMASK  (1 << 0)
1310#define SI_CLEAR_TYPE_DCC    (1 << 1)
1311#define SI_CLEAR_TYPE_HTILE  (1 << 2)
1312
1313struct si_clear_info {
1314   struct pipe_resource *resource;
1315   uint64_t offset;
1316   uint32_t size;
1317   uint32_t clear_value;
1318   uint32_t writemask;
1319   bool is_dcc_msaa; /* Clear it as a DCC MSAA image. */
1320};
1321
1322enum pipe_format si_simplify_cb_format(enum pipe_format format);
1323bool vi_alpha_is_on_msb(struct si_screen *sscreen, enum pipe_format format);
1324bool vi_dcc_get_clear_info(struct si_context *sctx, struct si_texture *tex, unsigned level,
1325                           unsigned clear_value, struct si_clear_info *out);
1326void si_init_buffer_clear(struct si_clear_info *info,
1327                          struct pipe_resource *resource, uint64_t offset,
1328                          uint32_t size, uint32_t clear_value);
1329void si_execute_clears(struct si_context *sctx, struct si_clear_info *info,
1330                       unsigned num_clears, unsigned types);
1331void si_init_clear_functions(struct si_context *sctx);
1332
1333/* si_compute_blit.c */
1334#define SI_OP_SYNC_CS_BEFORE              (1 << 0)
1335#define SI_OP_SYNC_PS_BEFORE              (1 << 1)
1336#define SI_OP_SYNC_CPDMA_BEFORE           (1 << 2) /* only affects CP DMA calls */
1337#define SI_OP_SYNC_BEFORE                 (SI_OP_SYNC_CS_BEFORE | SI_OP_SYNC_PS_BEFORE | SI_OP_SYNC_CPDMA_BEFORE)
1338#define SI_OP_SYNC_AFTER                  (1 << 3)
1339#define SI_OP_SYNC_BEFORE_AFTER           (SI_OP_SYNC_BEFORE | SI_OP_SYNC_AFTER)
1340#define SI_OP_SKIP_CACHE_INV_BEFORE       (1 << 4) /* don't invalidate caches */
1341#define SI_OP_CS_IMAGE                    (1 << 5)
1342#define SI_OP_CS_RENDER_COND_ENABLE       (1 << 6)
1343#define SI_OP_CPDMA_SKIP_CHECK_CS_SPACE   (1 << 7) /* don't call need_cs_space */
1344
1345unsigned si_get_flush_flags(struct si_context *sctx, enum si_coherency coher,
1346                            enum si_cache_policy cache_policy);
1347void si_launch_grid_internal(struct si_context *sctx, struct pipe_grid_info *info,
1348                             void *shader, unsigned flags);
1349void si_launch_grid_internal_ssbos(struct si_context *sctx, struct pipe_grid_info *info,
1350                                   void *shader, unsigned flags, enum si_coherency coher,
1351                                   unsigned num_buffers, const struct pipe_shader_buffer *buffers,
1352                                   unsigned writeable_bitmask);
1353enum si_clear_method {
1354  SI_CP_DMA_CLEAR_METHOD,
1355  SI_COMPUTE_CLEAR_METHOD,
1356  SI_AUTO_SELECT_CLEAR_METHOD
1357};
1358void si_clear_buffer(struct si_context *sctx, struct pipe_resource *dst,
1359                     uint64_t offset, uint64_t size, uint32_t *clear_value,
1360                     uint32_t clear_value_size, unsigned flags,
1361                     enum si_coherency coher, enum si_clear_method method);
1362void si_compute_clear_buffer_rmw(struct si_context *sctx, struct pipe_resource *dst,
1363                                 unsigned dst_offset, unsigned size,
1364                                 uint32_t clear_value, uint32_t writebitmask,
1365                                 unsigned flags, enum si_coherency coher);
1366void si_screen_clear_buffer(struct si_screen *sscreen, struct pipe_resource *dst, uint64_t offset,
1367                            uint64_t size, unsigned value, unsigned flags);
1368void si_copy_buffer(struct si_context *sctx, struct pipe_resource *dst, struct pipe_resource *src,
1369                    uint64_t dst_offset, uint64_t src_offset, unsigned size, unsigned flags);
1370void si_compute_copy_image(struct si_context *sctx, struct pipe_resource *dst, unsigned dst_level,
1371                           struct pipe_resource *src, unsigned src_level, unsigned dstx,
1372                           unsigned dsty, unsigned dstz, const struct pipe_box *src_box,
1373                           bool is_dcc_decompress, unsigned flags);
1374void si_compute_clear_render_target(struct pipe_context *ctx, struct pipe_surface *dstsurf,
1375                                    const union pipe_color_union *color, unsigned dstx,
1376                                    unsigned dsty, unsigned width, unsigned height,
1377                                    bool render_condition_enabled);
1378void si_retile_dcc(struct si_context *sctx, struct si_texture *tex);
1379void gfx9_clear_dcc_msaa(struct si_context *sctx, struct pipe_resource *res, uint32_t clear_value,
1380                         unsigned flags, enum si_coherency coher);
1381void si_compute_expand_fmask(struct pipe_context *ctx, struct pipe_resource *tex);
1382void si_init_compute_blit_functions(struct si_context *sctx);
1383
1384/* si_cp_dma.c */
1385void si_cp_dma_wait_for_idle(struct si_context *sctx, struct radeon_cmdbuf *cs);
1386void si_cp_dma_clear_buffer(struct si_context *sctx, struct radeon_cmdbuf *cs,
1387                            struct pipe_resource *dst, uint64_t offset, uint64_t size,
1388                            unsigned value, unsigned user_flags, enum si_coherency coher,
1389                            enum si_cache_policy cache_policy);
1390void si_cp_dma_copy_buffer(struct si_context *sctx, struct pipe_resource *dst,
1391                           struct pipe_resource *src, uint64_t dst_offset, uint64_t src_offset,
1392                           unsigned size, unsigned user_flags, enum si_coherency coher,
1393                           enum si_cache_policy cache_policy);
1394void si_cp_dma_prefetch(struct si_context *sctx, struct pipe_resource *buf,
1395                        unsigned offset, unsigned size);
1396void si_test_gds(struct si_context *sctx);
1397void si_cp_write_data(struct si_context *sctx, struct si_resource *buf, unsigned offset,
1398                      unsigned size, unsigned dst_sel, unsigned engine, const void *data);
1399void si_cp_copy_data(struct si_context *sctx, struct radeon_cmdbuf *cs, unsigned dst_sel,
1400                     struct si_resource *dst, unsigned dst_offset, unsigned src_sel,
1401                     struct si_resource *src, unsigned src_offset);
1402
1403/* si_cp_reg_shadowing.c */
1404void si_init_cp_reg_shadowing(struct si_context *sctx);
1405
1406/* si_debug.c */
1407void si_save_cs(struct radeon_winsys *ws, struct radeon_cmdbuf *cs, struct radeon_saved_cs *saved,
1408                bool get_buffer_list);
1409void si_clear_saved_cs(struct radeon_saved_cs *saved);
1410void si_destroy_saved_cs(struct si_saved_cs *scs);
1411void si_auto_log_cs(void *data, struct u_log_context *log);
1412void si_log_hw_flush(struct si_context *sctx);
1413void si_log_draw_state(struct si_context *sctx, struct u_log_context *log);
1414void si_log_compute_state(struct si_context *sctx, struct u_log_context *log);
1415void si_init_debug_functions(struct si_context *sctx);
1416void si_check_vm_faults(struct si_context *sctx, struct radeon_saved_cs *saved,
1417                        enum ring_type ring);
1418bool si_replace_shader(unsigned num, struct si_shader_binary *binary);
1419void si_print_current_ib(struct si_context *sctx, FILE *f);
1420
1421/* si_fence.c */
1422void si_cp_release_mem(struct si_context *ctx, struct radeon_cmdbuf *cs, unsigned event,
1423                       unsigned event_flags, unsigned dst_sel, unsigned int_sel, unsigned data_sel,
1424                       struct si_resource *buf, uint64_t va, uint32_t new_fence,
1425                       unsigned query_type);
1426unsigned si_cp_write_fence_dwords(struct si_screen *screen);
1427void si_cp_wait_mem(struct si_context *ctx, struct radeon_cmdbuf *cs, uint64_t va, uint32_t ref,
1428                    uint32_t mask, unsigned flags);
1429void si_init_fence_functions(struct si_context *ctx);
1430void si_init_screen_fence_functions(struct si_screen *screen);
1431struct pipe_fence_handle *si_create_fence(struct pipe_context *ctx,
1432                                          struct tc_unflushed_batch_token *tc_token);
1433
1434/* si_get.c */
1435void si_init_screen_get_functions(struct si_screen *sscreen);
1436
1437bool si_sdma_copy_image(struct si_context *ctx, struct si_texture *dst, struct si_texture *src);
1438
1439/* si_gfx_cs.c */
1440void si_flush_gfx_cs(struct si_context *ctx, unsigned flags, struct pipe_fence_handle **fence);
1441void si_allocate_gds(struct si_context *ctx);
1442void si_set_tracked_regs_to_clear_state(struct si_context *ctx);
1443void si_begin_new_gfx_cs(struct si_context *ctx, bool first_cs);
1444void si_trace_emit(struct si_context *sctx);
1445void si_emit_surface_sync(struct si_context *sctx, struct radeon_cmdbuf *cs,
1446                          unsigned cp_coher_cntl);
1447void gfx10_emit_cache_flush(struct si_context *sctx, struct radeon_cmdbuf *cs);
1448void si_emit_cache_flush(struct si_context *sctx, struct radeon_cmdbuf *cs);
1449/* Replace the sctx->b.draw_vbo function with a wrapper. This can be use to implement
1450 * optimizations without affecting the normal draw_vbo functions perf.
1451 */
1452void si_install_draw_wrapper(struct si_context *sctx, pipe_draw_vbo_func wrapper,
1453                             pipe_draw_vertex_state_func vstate_wrapper);
1454
1455/* si_gpu_load.c */
1456void si_gpu_load_kill_thread(struct si_screen *sscreen);
1457uint64_t si_begin_counter(struct si_screen *sscreen, unsigned type);
1458unsigned si_end_counter(struct si_screen *sscreen, unsigned type, uint64_t begin);
1459
1460/* si_compute.c */
1461void si_emit_initial_compute_regs(struct si_context *sctx, struct radeon_cmdbuf *cs);
1462void si_init_compute_functions(struct si_context *sctx);
1463
1464/* si_pipe.c */
1465void si_init_compiler(struct si_screen *sscreen, struct ac_llvm_compiler *compiler);
1466void si_init_aux_async_compute_ctx(struct si_screen *sscreen);
1467
1468/* si_perfcounters.c */
1469void si_init_perfcounters(struct si_screen *screen);
1470void si_destroy_perfcounters(struct si_screen *screen);
1471void si_inhibit_clockgating(struct si_context *sctx, struct radeon_cmdbuf *cs, bool inhibit);
1472
1473/* si_query.c */
1474void si_init_screen_query_functions(struct si_screen *sscreen);
1475void si_init_query_functions(struct si_context *sctx);
1476void si_suspend_queries(struct si_context *sctx);
1477void si_resume_queries(struct si_context *sctx);
1478
1479/* si_shaderlib_nir.c */
1480void *si_create_dcc_retile_cs(struct si_context *sctx, struct radeon_surf *surf);
1481void *gfx9_create_clear_dcc_msaa_cs(struct si_context *sctx, struct si_texture *tex);
1482
1483/* si_shaderlib_tgsi.c */
1484void *si_get_blitter_vs(struct si_context *sctx, enum blitter_attrib_type type,
1485                        unsigned num_layers);
1486void *si_create_fixed_func_tcs(struct si_context *sctx);
1487void *si_create_dma_compute_shader(struct pipe_context *ctx, unsigned num_dwords_per_thread,
1488                                   bool dst_stream_cache_policy, bool is_copy);
1489void *si_create_clear_buffer_rmw_cs(struct pipe_context *ctx);
1490void *si_create_copy_image_compute_shader(struct pipe_context *ctx);
1491void *si_create_copy_image_compute_shader_1d_array(struct pipe_context *ctx);
1492void *si_create_dcc_decompress_cs(struct pipe_context *ctx);
1493void *si_clear_render_target_shader(struct pipe_context *ctx);
1494void *si_clear_render_target_shader_1d_array(struct pipe_context *ctx);
1495void *si_clear_12bytes_buffer_shader(struct pipe_context *ctx);
1496void *si_create_fmask_expand_cs(struct pipe_context *ctx, unsigned num_samples, bool is_array);
1497void *si_create_query_result_cs(struct si_context *sctx);
1498void *gfx10_create_sh_query_result_cs(struct si_context *sctx);
1499
1500/* gfx10_query.c */
1501void gfx10_init_query(struct si_context *sctx);
1502void gfx10_destroy_query(struct si_context *sctx);
1503
1504/* si_test_blit.c */
1505void si_test_blit(struct si_screen *sscreen);
1506
1507/* si_test_clearbuffer.c */
1508void si_test_dma_perf(struct si_screen *sscreen);
1509
1510/* si_uvd.c */
1511struct pipe_video_codec *si_uvd_create_decoder(struct pipe_context *context,
1512                                               const struct pipe_video_codec *templ);
1513
1514struct pipe_video_buffer *si_video_buffer_create(struct pipe_context *pipe,
1515                                                 const struct pipe_video_buffer *tmpl);
1516struct pipe_video_buffer *si_video_buffer_create_with_modifiers(struct pipe_context *pipe,
1517                                                                const struct pipe_video_buffer *tmpl,
1518                                                                const uint64_t *modifiers,
1519                                                                unsigned int modifiers_count);
1520
1521/* si_viewport.c */
1522void si_get_small_prim_cull_info(struct si_context *sctx, struct si_small_prim_cull_info *out);
1523void si_update_vs_viewport_state(struct si_context *ctx);
1524void si_init_viewport_functions(struct si_context *ctx);
1525
1526/* si_texture.c */
1527void si_eliminate_fast_color_clear(struct si_context *sctx, struct si_texture *tex,
1528                                   bool *ctx_flushed);
1529void si_texture_discard_cmask(struct si_screen *sscreen, struct si_texture *tex);
1530bool si_init_flushed_depth_texture(struct pipe_context *ctx, struct pipe_resource *texture);
1531void si_print_texture_info(struct si_screen *sscreen, struct si_texture *tex,
1532                           struct u_log_context *log);
1533struct pipe_resource *si_texture_create(struct pipe_screen *screen,
1534                                        const struct pipe_resource *templ);
1535bool vi_dcc_formats_compatible(struct si_screen *sscreen, enum pipe_format format1,
1536                               enum pipe_format format2);
1537bool vi_dcc_formats_are_incompatible(struct pipe_resource *tex, unsigned level,
1538                                     enum pipe_format view_format);
1539void vi_disable_dcc_if_incompatible_format(struct si_context *sctx, struct pipe_resource *tex,
1540                                           unsigned level, enum pipe_format view_format);
1541struct pipe_surface *si_create_surface_custom(struct pipe_context *pipe,
1542                                              struct pipe_resource *texture,
1543                                              const struct pipe_surface *templ, unsigned width0,
1544                                              unsigned height0, unsigned width, unsigned height);
1545unsigned si_translate_colorswap(enum pipe_format format, bool do_endian_swap);
1546bool si_texture_disable_dcc(struct si_context *sctx, struct si_texture *tex);
1547void si_init_screen_texture_functions(struct si_screen *sscreen);
1548void si_init_context_texture_functions(struct si_context *sctx);
1549
1550/* si_sqtt.c */
1551void si_sqtt_write_event_marker(struct si_context* sctx, struct radeon_cmdbuf *rcs,
1552                                enum rgp_sqtt_marker_event_type api_type,
1553                                uint32_t vertex_offset_user_data,
1554                                uint32_t instance_offset_user_data,
1555                                uint32_t draw_index_user_data);
1556bool si_sqtt_register_pipeline(struct si_context* sctx, uint64_t pipeline_hash, uint64_t base_address, bool is_compute);
1557bool si_sqtt_pipeline_is_registered(struct ac_thread_trace_data *thread_trace_data,
1558                                    uint64_t pipeline_hash);
1559void si_sqtt_describe_pipeline_bind(struct si_context* sctx, uint64_t pipeline_hash, int bind_point);
1560void
1561si_write_event_with_dims_marker(struct si_context* sctx, struct radeon_cmdbuf *rcs,
1562                                enum rgp_sqtt_marker_event_type api_type,
1563                                uint32_t x, uint32_t y, uint32_t z);
1564void
1565si_write_user_event(struct si_context* sctx, struct radeon_cmdbuf *rcs,
1566                    enum rgp_sqtt_marker_user_event_type type,
1567                    const char *str, int len);
1568void
1569si_sqtt_describe_barrier_start(struct si_context* sctx, struct radeon_cmdbuf *rcs);
1570void
1571si_sqtt_describe_barrier_end(struct si_context* sctx, struct radeon_cmdbuf *rcs, unsigned flags);
1572bool si_init_thread_trace(struct si_context *sctx);
1573void si_destroy_thread_trace(struct si_context *sctx);
1574void si_handle_thread_trace(struct si_context *sctx, struct radeon_cmdbuf *rcs);
1575
1576/* si_state_shaders.c */
1577struct si_pm4_state *si_build_vgt_shader_config(struct si_screen *screen, union si_vgt_stages_key key);
1578
1579/*
1580 * common helpers
1581 */
1582
1583static inline struct si_resource *si_resource(struct pipe_resource *r)
1584{
1585   return (struct si_resource *)r;
1586}
1587
1588static inline void si_resource_reference(struct si_resource **ptr, struct si_resource *res)
1589{
1590   pipe_resource_reference((struct pipe_resource **)ptr, (struct pipe_resource *)res);
1591}
1592
1593static inline void si_texture_reference(struct si_texture **ptr, struct si_texture *res)
1594{
1595   pipe_resource_reference((struct pipe_resource **)ptr, &res->buffer.b.b);
1596}
1597
1598static inline void
1599si_shader_selector_reference(struct si_context *sctx, /* sctx can optionally be NULL */
1600                             struct si_shader_selector **dst, struct si_shader_selector *src)
1601{
1602   if (*dst == src)
1603      return;
1604
1605   struct si_screen *sscreen = src ? src->screen : (*dst)->screen;
1606   util_shader_reference(&sctx->b, &sscreen->live_shader_cache, (void **)dst, src);
1607}
1608
1609static inline bool vi_dcc_enabled(struct si_texture *tex, unsigned level)
1610{
1611   return !tex->is_depth && tex->surface.meta_offset && level < tex->surface.num_meta_levels;
1612}
1613
1614static inline unsigned si_tile_mode_index(struct si_texture *tex, unsigned level, bool stencil)
1615{
1616   if (stencil)
1617      return tex->surface.u.legacy.zs.stencil_tiling_index[level];
1618   else
1619      return tex->surface.u.legacy.tiling_index[level];
1620}
1621
1622static inline unsigned si_get_minimum_num_gfx_cs_dwords(struct si_context *sctx,
1623                                                        unsigned num_draws)
1624{
1625   /* Don't count the needed CS space exactly and just use an upper bound.
1626    *
1627    * Also reserve space for stopping queries at the end of IB, because
1628    * the number of active queries is unlimited in theory.
1629    */
1630   return 2048 + sctx->num_cs_dw_queries_suspend + num_draws * 10;
1631}
1632
1633static inline void si_context_add_resource_size(struct si_context *sctx, struct pipe_resource *r)
1634{
1635   if (r) {
1636      /* Add memory usage for need_gfx_cs_space */
1637      sctx->memory_usage_kb += si_resource(r)->memory_usage_kb;
1638   }
1639}
1640
1641static inline void si_invalidate_draw_sh_constants(struct si_context *sctx)
1642{
1643   sctx->last_base_vertex = SI_BASE_VERTEX_UNKNOWN;
1644   sctx->last_start_instance = SI_START_INSTANCE_UNKNOWN;
1645   sctx->last_drawid = SI_DRAW_ID_UNKNOWN;
1646}
1647
1648static inline void si_invalidate_draw_constants(struct si_context *sctx)
1649{
1650   si_invalidate_draw_sh_constants(sctx);
1651   sctx->last_instance_count = SI_INSTANCE_COUNT_UNKNOWN;
1652}
1653
1654static inline unsigned si_get_atom_bit(struct si_context *sctx, struct si_atom *atom)
1655{
1656   return 1 << (atom - sctx->atoms.array);
1657}
1658
1659static inline void si_set_atom_dirty(struct si_context *sctx, struct si_atom *atom, bool dirty)
1660{
1661   unsigned bit = si_get_atom_bit(sctx, atom);
1662
1663   if (dirty)
1664      sctx->dirty_atoms |= bit;
1665   else
1666      sctx->dirty_atoms &= ~bit;
1667}
1668
1669static inline bool si_is_atom_dirty(struct si_context *sctx, struct si_atom *atom)
1670{
1671   return (sctx->dirty_atoms & si_get_atom_bit(sctx, atom)) != 0;
1672}
1673
1674static inline void si_mark_atom_dirty(struct si_context *sctx, struct si_atom *atom)
1675{
1676   si_set_atom_dirty(sctx, atom, true);
1677}
1678
1679/* This should be evaluated at compile time if all parameters except sctx are constants. */
1680static ALWAYS_INLINE struct si_shader_ctx_state *
1681si_get_vs_inline(struct si_context *sctx, enum si_has_tess has_tess, enum si_has_gs has_gs)
1682{
1683   if (has_gs)
1684      return &sctx->shader.gs;
1685   if (has_tess)
1686      return &sctx->shader.tes;
1687
1688   return &sctx->shader.vs;
1689}
1690
1691static inline struct si_shader_ctx_state *si_get_vs(struct si_context *sctx)
1692{
1693   return si_get_vs_inline(sctx, sctx->shader.tes.cso ? TESS_ON : TESS_OFF,
1694                           sctx->shader.gs.cso ? GS_ON : GS_OFF);
1695}
1696
1697static inline struct si_shader_info *si_get_vs_info(struct si_context *sctx)
1698{
1699   struct si_shader_ctx_state *vs = si_get_vs(sctx);
1700
1701   return vs->cso ? &vs->cso->info : NULL;
1702}
1703
1704static inline bool si_can_dump_shader(struct si_screen *sscreen, gl_shader_stage stage)
1705{
1706   return sscreen->debug_flags & (1 << stage);
1707}
1708
1709static inline bool si_get_strmout_en(struct si_context *sctx)
1710{
1711   return sctx->streamout.streamout_enabled || sctx->streamout.prims_gen_query_enabled;
1712}
1713
1714static inline unsigned si_optimal_tcc_alignment(struct si_context *sctx, unsigned upload_size)
1715{
1716   unsigned alignment, tcc_cache_line_size;
1717
1718   /* If the upload size is less than the cache line size (e.g. 16, 32),
1719    * the whole thing will fit into a cache line if we align it to its size.
1720    * The idea is that multiple small uploads can share a cache line.
1721    * If the upload size is greater, align it to the cache line size.
1722    */
1723   alignment = util_next_power_of_two(upload_size);
1724   tcc_cache_line_size = sctx->screen->info.tcc_cache_line_size;
1725   return MIN2(alignment, tcc_cache_line_size);
1726}
1727
1728static inline void si_saved_cs_reference(struct si_saved_cs **dst, struct si_saved_cs *src)
1729{
1730   if (pipe_reference(&(*dst)->reference, &src->reference))
1731      si_destroy_saved_cs(*dst);
1732
1733   *dst = src;
1734}
1735
1736static inline void si_make_CB_shader_coherent(struct si_context *sctx, unsigned num_samples,
1737                                              bool shaders_read_metadata, bool dcc_pipe_aligned)
1738{
1739   sctx->flags |= SI_CONTEXT_FLUSH_AND_INV_CB | SI_CONTEXT_INV_VCACHE;
1740   sctx->force_cb_shader_coherent = false;
1741
1742   if (sctx->chip_class >= GFX10) {
1743      if (sctx->screen->info.tcc_rb_non_coherent)
1744         sctx->flags |= SI_CONTEXT_INV_L2;
1745      else if (shaders_read_metadata)
1746         sctx->flags |= SI_CONTEXT_INV_L2_METADATA;
1747   } else if (sctx->chip_class == GFX9) {
1748      /* Single-sample color is coherent with shaders on GFX9, but
1749       * L2 metadata must be flushed if shaders read metadata.
1750       * (DCC, CMASK).
1751       */
1752      if (num_samples >= 2 || (shaders_read_metadata && !dcc_pipe_aligned))
1753         sctx->flags |= SI_CONTEXT_INV_L2;
1754      else if (shaders_read_metadata)
1755         sctx->flags |= SI_CONTEXT_INV_L2_METADATA;
1756   } else {
1757      /* GFX6-GFX8 */
1758      sctx->flags |= SI_CONTEXT_INV_L2;
1759   }
1760}
1761
1762static inline void si_make_DB_shader_coherent(struct si_context *sctx, unsigned num_samples,
1763                                              bool include_stencil, bool shaders_read_metadata)
1764{
1765   sctx->flags |= SI_CONTEXT_FLUSH_AND_INV_DB | SI_CONTEXT_INV_VCACHE;
1766
1767   if (sctx->chip_class >= GFX10) {
1768      if (sctx->screen->info.tcc_rb_non_coherent)
1769         sctx->flags |= SI_CONTEXT_INV_L2;
1770      else if (shaders_read_metadata)
1771         sctx->flags |= SI_CONTEXT_INV_L2_METADATA;
1772   } else if (sctx->chip_class == GFX9) {
1773      /* Single-sample depth (not stencil) is coherent with shaders
1774       * on GFX9, but L2 metadata must be flushed if shaders read
1775       * metadata.
1776       */
1777      if (num_samples >= 2 || include_stencil)
1778         sctx->flags |= SI_CONTEXT_INV_L2;
1779      else if (shaders_read_metadata)
1780         sctx->flags |= SI_CONTEXT_INV_L2_METADATA;
1781   } else {
1782      /* GFX6-GFX8 */
1783      sctx->flags |= SI_CONTEXT_INV_L2;
1784   }
1785}
1786
1787static inline bool si_can_sample_zs(struct si_texture *tex, bool stencil_sampler)
1788{
1789   return (stencil_sampler && tex->can_sample_s) || (!stencil_sampler && tex->can_sample_z);
1790}
1791
1792static inline bool si_htile_enabled(struct si_texture *tex, unsigned level, unsigned zs_mask)
1793{
1794   if (zs_mask == PIPE_MASK_S && (tex->htile_stencil_disabled || !tex->surface.has_stencil))
1795      return false;
1796
1797   if (!tex->is_depth || !tex->surface.meta_offset)
1798      return false;
1799
1800   struct si_screen *sscreen = (struct si_screen *)tex->buffer.b.b.screen;
1801   if (sscreen->info.chip_class >= GFX8) {
1802      return level < tex->surface.num_meta_levels;
1803   } else {
1804      /* GFX6-7 don't have TC-compatible HTILE, which means they have to run
1805       * a decompression pass for every mipmap level before texturing, so compress
1806       * only one level to reduce the number of decompression passes to a minimum.
1807       */
1808      return level == 0;
1809   }
1810}
1811
1812static inline bool vi_tc_compat_htile_enabled(struct si_texture *tex, unsigned level,
1813                                              unsigned zs_mask)
1814{
1815   assert(!tex->tc_compatible_htile || tex->surface.meta_offset);
1816   return tex->tc_compatible_htile && si_htile_enabled(tex, level, zs_mask);
1817}
1818
1819static inline unsigned si_get_ps_iter_samples(struct si_context *sctx)
1820{
1821   if (sctx->ps_uses_fbfetch)
1822      return sctx->framebuffer.nr_color_samples;
1823
1824   return MIN2(sctx->ps_iter_samples, sctx->framebuffer.nr_color_samples);
1825}
1826
1827static inline unsigned si_get_total_colormask(struct si_context *sctx)
1828{
1829   if (sctx->queued.named.rasterizer->rasterizer_discard)
1830      return 0;
1831
1832   struct si_shader_selector *ps = sctx->shader.ps.cso;
1833   if (!ps)
1834      return 0;
1835
1836   unsigned colormask =
1837      sctx->framebuffer.colorbuf_enabled_4bit & sctx->queued.named.blend->cb_target_mask;
1838
1839   if (!ps->info.color0_writes_all_cbufs)
1840      colormask &= ps->colors_written_4bit;
1841   else if (!ps->colors_written_4bit)
1842      colormask = 0; /* color0 writes all cbufs, but it's not written */
1843
1844   return colormask;
1845}
1846
1847#define UTIL_ALL_PRIM_LINE_MODES                                                                   \
1848   ((1 << PIPE_PRIM_LINES) | (1 << PIPE_PRIM_LINE_LOOP) | (1 << PIPE_PRIM_LINE_STRIP) |            \
1849    (1 << PIPE_PRIM_LINES_ADJACENCY) | (1 << PIPE_PRIM_LINE_STRIP_ADJACENCY))
1850
1851#define UTIL_ALL_PRIM_TRIANGLE_MODES \
1852   ((1 << PIPE_PRIM_TRIANGLES) | (1 << PIPE_PRIM_TRIANGLE_STRIP) | \
1853    (1 << PIPE_PRIM_TRIANGLE_FAN) | (1 << PIPE_PRIM_QUADS) | (1 << PIPE_PRIM_QUAD_STRIP) | \
1854    (1 << PIPE_PRIM_POLYGON) | (1 << PIPE_PRIM_TRIANGLES_ADJACENCY) | \
1855    (1 << PIPE_PRIM_TRIANGLE_STRIP_ADJACENCY))
1856
1857static inline bool util_prim_is_lines(unsigned prim)
1858{
1859   return ((1 << prim) & UTIL_ALL_PRIM_LINE_MODES) != 0;
1860}
1861
1862static inline bool util_prim_is_points_or_lines(unsigned prim)
1863{
1864   return ((1 << prim) & (UTIL_ALL_PRIM_LINE_MODES | (1 << PIPE_PRIM_POINTS))) != 0;
1865}
1866
1867static inline bool util_rast_prim_is_triangles(unsigned prim)
1868{
1869   return ((1 << prim) & UTIL_ALL_PRIM_TRIANGLE_MODES) != 0;
1870}
1871
1872static inline bool util_rast_prim_is_lines_or_triangles(unsigned prim)
1873{
1874   return ((1 << prim) & (UTIL_ALL_PRIM_LINE_MODES | UTIL_ALL_PRIM_TRIANGLE_MODES)) != 0;
1875}
1876
1877/**
1878 * Return true if there is enough memory in VRAM and GTT for the buffers
1879 * added so far.
1880 *
1881 * \param vram      VRAM memory size not added to the buffer list yet
1882 * \param gtt       GTT memory size not added to the buffer list yet
1883 */
1884static inline bool radeon_cs_memory_below_limit(struct si_screen *screen, struct radeon_cmdbuf *cs,
1885                                                uint32_t kb)
1886{
1887   return kb + cs->used_vram_kb + cs->used_gart_kb < screen->max_memory_usage_kb;
1888}
1889
1890static inline void si_need_gfx_cs_space(struct si_context *ctx, unsigned num_draws)
1891{
1892   struct radeon_cmdbuf *cs = &ctx->gfx_cs;
1893
1894   /* There are two memory usage counters in the winsys for all buffers
1895    * that have been added (cs_add_buffer) and one counter in the pipe
1896    * driver for those that haven't been added yet.
1897    */
1898   uint32_t kb = ctx->memory_usage_kb;
1899   ctx->memory_usage_kb = 0;
1900
1901   if (radeon_cs_memory_below_limit(ctx->screen, &ctx->gfx_cs, kb) &&
1902       ctx->ws->cs_check_space(cs, si_get_minimum_num_gfx_cs_dwords(ctx, num_draws), false))
1903      return;
1904
1905   si_flush_gfx_cs(ctx, RADEON_FLUSH_ASYNC_START_NEXT_GFX_IB_NOW, NULL);
1906}
1907
1908/**
1909 * Add a buffer to the buffer list for the given command stream (CS).
1910 *
1911 * All buffers used by a CS must be added to the list. This tells the kernel
1912 * driver which buffers are used by GPU commands. Other buffers can
1913 * be swapped out (not accessible) during execution.
1914 *
1915 * The buffer list becomes empty after every context flush and must be
1916 * rebuilt.
1917 */
1918static inline void radeon_add_to_buffer_list(struct si_context *sctx, struct radeon_cmdbuf *cs,
1919                                             struct si_resource *bo, enum radeon_bo_usage usage,
1920                                             enum radeon_bo_priority priority)
1921{
1922   assert(usage);
1923   sctx->ws->cs_add_buffer(cs, bo->buf, (enum radeon_bo_usage)(usage | RADEON_USAGE_SYNCHRONIZED),
1924                           bo->domains, priority);
1925}
1926
1927/**
1928 * Same as above, but also checks memory usage and flushes the context
1929 * accordingly.
1930 *
1931 * When this SHOULD NOT be used:
1932 *
1933 * - if si_context_add_resource_size has been called for the buffer
1934 *   followed by *_need_cs_space for checking the memory usage
1935 *
1936 * - when emitting state packets and draw packets (because preceding packets
1937 *   can't be re-emitted at that point)
1938 *
1939 * - if shader resource "enabled_mask" is not up-to-date or there is
1940 *   a different constraint disallowing a context flush
1941 */
1942static inline void radeon_add_to_gfx_buffer_list_check_mem(struct si_context *sctx,
1943                                                           struct si_resource *bo,
1944                                                           enum radeon_bo_usage usage,
1945                                                           enum radeon_bo_priority priority,
1946                                                           bool check_mem)
1947{
1948   if (check_mem &&
1949       !radeon_cs_memory_below_limit(sctx->screen, &sctx->gfx_cs, sctx->memory_usage_kb + bo->memory_usage_kb))
1950      si_flush_gfx_cs(sctx, RADEON_FLUSH_ASYNC_START_NEXT_GFX_IB_NOW, NULL);
1951
1952   radeon_add_to_buffer_list(sctx, &sctx->gfx_cs, bo, usage, priority);
1953}
1954
1955static inline unsigned si_get_wave_size(struct si_screen *sscreen,
1956                                        gl_shader_stage stage, bool ngg, bool es)
1957{
1958   if (stage == MESA_SHADER_COMPUTE)
1959      return sscreen->compute_wave_size;
1960   else if (stage == MESA_SHADER_FRAGMENT)
1961      return sscreen->ps_wave_size;
1962   else if ((stage == MESA_SHADER_VERTEX && es && !ngg) ||
1963            (stage == MESA_SHADER_TESS_EVAL && es && !ngg) ||
1964            (stage == MESA_SHADER_GEOMETRY && !ngg)) /* legacy GS only supports Wave64 */
1965      return 64;
1966   else
1967      return sscreen->ge_wave_size;
1968}
1969
1970static inline unsigned si_get_shader_wave_size(struct si_shader *shader)
1971{
1972   return si_get_wave_size(shader->selector->screen, shader->selector->info.stage,
1973                           shader->key.as_ngg,
1974                           shader->key.as_es);
1975}
1976
1977static inline void si_select_draw_vbo(struct si_context *sctx)
1978{
1979   pipe_draw_vbo_func draw_vbo = sctx->draw_vbo[!!sctx->shader.tes.cso]
1980                                               [!!sctx->shader.gs.cso]
1981                                               [sctx->ngg];
1982   pipe_draw_vertex_state_func draw_vertex_state =
1983      sctx->draw_vertex_state[!!sctx->shader.tes.cso]
1984                             [!!sctx->shader.gs.cso]
1985                             [sctx->ngg];
1986   assert(draw_vbo);
1987   assert(draw_vertex_state);
1988
1989   if (unlikely(sctx->real_draw_vbo)) {
1990      assert(sctx->real_draw_vertex_state);
1991      sctx->real_draw_vbo = draw_vbo;
1992      sctx->real_draw_vertex_state = draw_vertex_state;
1993   } else {
1994      assert(!sctx->real_draw_vertex_state);
1995      sctx->b.draw_vbo = draw_vbo;
1996      sctx->b.draw_vertex_state = draw_vertex_state;
1997   }
1998}
1999
2000/* Return the number of samples that the rasterizer uses. */
2001static inline unsigned si_get_num_coverage_samples(struct si_context *sctx)
2002{
2003   if (sctx->framebuffer.nr_samples > 1 &&
2004       sctx->queued.named.rasterizer->multisample_enable)
2005      return sctx->framebuffer.nr_samples;
2006
2007   /* Note that smoothing_enabled is set by si_update_shaders. */
2008   if (sctx->smoothing_enabled)
2009      return SI_NUM_SMOOTH_AA_SAMPLES;
2010
2011   return 1;
2012}
2013
2014static unsigned ALWAYS_INLINE
2015si_num_vbos_in_user_sgprs_inline(enum chip_class chip_class)
2016{
2017   /* This decreases CPU overhead if all descriptors are in user SGPRs because we don't
2018    * have to allocate and count references for the upload buffer.
2019    */
2020   return chip_class >= GFX9 ? 5 : 1;
2021}
2022
2023static inline unsigned si_num_vbos_in_user_sgprs(struct si_screen *sscreen)
2024{
2025   return si_num_vbos_in_user_sgprs_inline(sscreen->info.chip_class);
2026}
2027
2028#define PRINT_ERR(fmt, args...)                                                                    \
2029   fprintf(stderr, "EE %s:%d %s - " fmt, __FILE__, __LINE__, __func__, ##args)
2030
2031struct pipe_resource *si_buffer_from_winsys_buffer(struct pipe_screen *screen,
2032                                                   const struct pipe_resource *templ,
2033                                                   struct pb_buffer *imported_buf,
2034                                                   bool dedicated);
2035
2036#ifdef __cplusplus
2037}
2038#endif
2039
2040#endif
2041