• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2012 Advanced Micro Devices, 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 "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * on the rights to use, copy, modify, merge, publish, distribute, sub
9  * license, and/or sell copies of the Software, and to permit persons to whom
10  * the Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice (including the next
13  * paragraph) shall be included in all copies or substantial portions of the
14  * Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHOR(S) AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM,
20  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
21  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
22  * USE OR OTHER DEALINGS IN THE SOFTWARE.
23  */
24 
25 #include "ac_exp_param.h"
26 #include "ac_shader_util.h"
27 #include "compiler/nir/nir_serialize.h"
28 #include "nir/tgsi_to_nir.h"
29 #include "si_build_pm4.h"
30 #include "sid.h"
31 #include "util/crc32.h"
32 #include "util/disk_cache.h"
33 #include "util/hash_table.h"
34 #include "util/mesa-sha1.h"
35 #include "util/u_async_debug.h"
36 #include "util/u_memory.h"
37 #include "util/u_prim.h"
38 #include "tgsi/tgsi_from_mesa.h"
39 
40 /* SHADER_CACHE */
41 
42 /**
43  * Return the IR key for the shader cache.
44  */
si_get_ir_cache_key(struct si_shader_selector * sel,bool ngg,bool es,unsigned char ir_sha1_cache_key[20])45 void si_get_ir_cache_key(struct si_shader_selector *sel, bool ngg, bool es,
46                          unsigned char ir_sha1_cache_key[20])
47 {
48    struct blob blob = {};
49    unsigned ir_size;
50    void *ir_binary;
51 
52    if (sel->nir_binary) {
53       ir_binary = sel->nir_binary;
54       ir_size = sel->nir_size;
55    } else {
56       assert(sel->nir);
57 
58       blob_init(&blob);
59       nir_serialize(&blob, sel->nir, true);
60       ir_binary = blob.data;
61       ir_size = blob.size;
62    }
63 
64    /* These settings affect the compilation, but they are not derived
65     * from the input shader IR.
66     */
67    unsigned shader_variant_flags = 0;
68 
69    if (ngg)
70       shader_variant_flags |= 1 << 0;
71    if (sel->nir)
72       shader_variant_flags |= 1 << 1;
73    if (si_get_wave_size(sel->screen, sel->info.stage, ngg, es, false, false) == 32)
74       shader_variant_flags |= 1 << 2;
75    if (sel->info.stage == MESA_SHADER_FRAGMENT &&
76        /* Derivatives imply helper invocations so check for needs_helper_invocations. */
77        sel->info.base.fs.needs_helper_invocations &&
78        sel->info.base.fs.uses_discard &&
79        sel->screen->debug_flags & DBG(FS_CORRECT_DERIVS_AFTER_KILL))
80       shader_variant_flags |= 1 << 3;
81 
82    /* This varies depending on whether compute-based culling is enabled. */
83    assert(sel->screen->num_vbos_in_user_sgprs <= 7);
84    shader_variant_flags |= MIN2(sel->screen->num_vbos_in_user_sgprs, 7) << 4;
85 
86    if (sel->screen->options.no_infinite_interp)
87       shader_variant_flags |= 1 << 7;
88    if (sel->screen->options.clamp_div_by_zero)
89       shader_variant_flags |= 1 << 8;
90    if (sel->screen->debug_flags & DBG(GISEL))
91       shader_variant_flags |= 1 << 9;
92    if (sel->screen->options.inline_uniforms)
93       shader_variant_flags |= 1 << 11;
94 
95    struct mesa_sha1 ctx;
96    _mesa_sha1_init(&ctx);
97    _mesa_sha1_update(&ctx, &shader_variant_flags, 4);
98    _mesa_sha1_update(&ctx, ir_binary, ir_size);
99    if (sel->info.stage == MESA_SHADER_VERTEX || sel->info.stage == MESA_SHADER_TESS_EVAL ||
100        sel->info.stage == MESA_SHADER_GEOMETRY)
101       _mesa_sha1_update(&ctx, &sel->so, sizeof(sel->so));
102    _mesa_sha1_final(&ctx, ir_sha1_cache_key);
103 
104    if (ir_binary == blob.data)
105       blob_finish(&blob);
106 }
107 
108 /** Copy "data" to "ptr" and return the next dword following copied data. */
write_data(uint32_t * ptr,const void * data,unsigned size)109 static uint32_t *write_data(uint32_t *ptr, const void *data, unsigned size)
110 {
111    /* data may be NULL if size == 0 */
112    if (size)
113       memcpy(ptr, data, size);
114    ptr += DIV_ROUND_UP(size, 4);
115    return ptr;
116 }
117 
118 /** Read data from "ptr". Return the next dword following the data. */
read_data(uint32_t * ptr,void * data,unsigned size)119 static uint32_t *read_data(uint32_t *ptr, void *data, unsigned size)
120 {
121    memcpy(data, ptr, size);
122    ptr += DIV_ROUND_UP(size, 4);
123    return ptr;
124 }
125 
126 /**
127  * Write the size as uint followed by the data. Return the next dword
128  * following the copied data.
129  */
write_chunk(uint32_t * ptr,const void * data,unsigned size)130 static uint32_t *write_chunk(uint32_t *ptr, const void *data, unsigned size)
131 {
132    *ptr++ = size;
133    return write_data(ptr, data, size);
134 }
135 
136 /**
137  * Read the size as uint followed by the data. Return both via parameters.
138  * Return the next dword following the data.
139  */
read_chunk(uint32_t * ptr,void ** data,unsigned * size)140 static uint32_t *read_chunk(uint32_t *ptr, void **data, unsigned *size)
141 {
142    *size = *ptr++;
143    assert(*data == NULL);
144    if (!*size)
145       return ptr;
146    *data = malloc(*size);
147    return read_data(ptr, *data, *size);
148 }
149 
150 /**
151  * Return the shader binary in a buffer. The first 4 bytes contain its size
152  * as integer.
153  */
si_get_shader_binary(struct si_shader * shader)154 static void *si_get_shader_binary(struct si_shader *shader)
155 {
156    /* There is always a size of data followed by the data itself. */
157    unsigned llvm_ir_size =
158       shader->binary.llvm_ir_string ? strlen(shader->binary.llvm_ir_string) + 1 : 0;
159 
160    /* Refuse to allocate overly large buffers and guard against integer
161     * overflow. */
162    if (shader->binary.elf_size > UINT_MAX / 4 || llvm_ir_size > UINT_MAX / 4)
163       return NULL;
164 
165    unsigned size = 4 + /* total size */
166                    4 + /* CRC32 of the data below */
167                    align(sizeof(shader->config), 4) + align(sizeof(shader->info), 4) + 4 +
168                    align(shader->binary.elf_size, 4) + 4 + align(llvm_ir_size, 4);
169    void *buffer = CALLOC(1, size);
170    uint32_t *ptr = (uint32_t *)buffer;
171 
172    if (!buffer)
173       return NULL;
174 
175    *ptr++ = size;
176    ptr++; /* CRC32 is calculated at the end. */
177 
178    ptr = write_data(ptr, &shader->config, sizeof(shader->config));
179    ptr = write_data(ptr, &shader->info, sizeof(shader->info));
180    ptr = write_chunk(ptr, shader->binary.elf_buffer, shader->binary.elf_size);
181    ptr = write_chunk(ptr, shader->binary.llvm_ir_string, llvm_ir_size);
182    assert((char *)ptr - (char *)buffer == size);
183 
184    /* Compute CRC32. */
185    ptr = (uint32_t *)buffer;
186    ptr++;
187    *ptr = util_hash_crc32(ptr + 1, size - 8);
188 
189    return buffer;
190 }
191 
si_load_shader_binary(struct si_shader * shader,void * binary)192 static bool si_load_shader_binary(struct si_shader *shader, void *binary)
193 {
194    uint32_t *ptr = (uint32_t *)binary;
195    uint32_t size = *ptr++;
196    uint32_t crc32 = *ptr++;
197    unsigned chunk_size;
198    unsigned elf_size;
199 
200    if (util_hash_crc32(ptr, size - 8) != crc32) {
201       fprintf(stderr, "radeonsi: binary shader has invalid CRC32\n");
202       return false;
203    }
204 
205    ptr = read_data(ptr, &shader->config, sizeof(shader->config));
206    ptr = read_data(ptr, &shader->info, sizeof(shader->info));
207    ptr = read_chunk(ptr, (void **)&shader->binary.elf_buffer, &elf_size);
208    shader->binary.elf_size = elf_size;
209    ptr = read_chunk(ptr, (void **)&shader->binary.llvm_ir_string, &chunk_size);
210 
211    return true;
212 }
213 
214 /**
215  * Insert a shader into the cache. It's assumed the shader is not in the cache.
216  * Use si_shader_cache_load_shader before calling this.
217  */
si_shader_cache_insert_shader(struct si_screen * sscreen,unsigned char ir_sha1_cache_key[20],struct si_shader * shader,bool insert_into_disk_cache)218 void si_shader_cache_insert_shader(struct si_screen *sscreen, unsigned char ir_sha1_cache_key[20],
219                                    struct si_shader *shader, bool insert_into_disk_cache)
220 {
221    void *hw_binary;
222    struct hash_entry *entry;
223    uint8_t key[CACHE_KEY_SIZE];
224 
225    entry = _mesa_hash_table_search(sscreen->shader_cache, ir_sha1_cache_key);
226    if (entry)
227       return; /* already added */
228 
229    hw_binary = si_get_shader_binary(shader);
230    if (!hw_binary)
231       return;
232 
233    if (_mesa_hash_table_insert(sscreen->shader_cache, mem_dup(ir_sha1_cache_key, 20), hw_binary) ==
234        NULL) {
235       FREE(hw_binary);
236       return;
237    }
238 
239    if (sscreen->disk_shader_cache && insert_into_disk_cache) {
240       disk_cache_compute_key(sscreen->disk_shader_cache, ir_sha1_cache_key, 20, key);
241       disk_cache_put(sscreen->disk_shader_cache, key, hw_binary, *((uint32_t *)hw_binary), NULL);
242    }
243 }
244 
si_shader_cache_load_shader(struct si_screen * sscreen,unsigned char ir_sha1_cache_key[20],struct si_shader * shader)245 bool si_shader_cache_load_shader(struct si_screen *sscreen, unsigned char ir_sha1_cache_key[20],
246                                  struct si_shader *shader)
247 {
248    struct hash_entry *entry = _mesa_hash_table_search(sscreen->shader_cache, ir_sha1_cache_key);
249 
250    if (entry) {
251       if (si_load_shader_binary(shader, entry->data)) {
252          p_atomic_inc(&sscreen->num_memory_shader_cache_hits);
253          return true;
254       }
255    }
256    p_atomic_inc(&sscreen->num_memory_shader_cache_misses);
257 
258    if (!sscreen->disk_shader_cache)
259       return false;
260 
261    unsigned char sha1[CACHE_KEY_SIZE];
262    disk_cache_compute_key(sscreen->disk_shader_cache, ir_sha1_cache_key, 20, sha1);
263 
264    size_t binary_size;
265    uint8_t *buffer = disk_cache_get(sscreen->disk_shader_cache, sha1, &binary_size);
266    if (buffer) {
267       if (binary_size >= sizeof(uint32_t) && *((uint32_t *)buffer) == binary_size) {
268          if (si_load_shader_binary(shader, buffer)) {
269             free(buffer);
270             si_shader_cache_insert_shader(sscreen, ir_sha1_cache_key, shader, false);
271             p_atomic_inc(&sscreen->num_disk_shader_cache_hits);
272             return true;
273          }
274       } else {
275          /* Something has gone wrong discard the item from the cache and
276           * rebuild/link from source.
277           */
278          assert(!"Invalid radeonsi shader disk cache item!");
279          disk_cache_remove(sscreen->disk_shader_cache, sha1);
280       }
281    }
282 
283    free(buffer);
284    p_atomic_inc(&sscreen->num_disk_shader_cache_misses);
285    return false;
286 }
287 
si_shader_cache_key_hash(const void * key)288 static uint32_t si_shader_cache_key_hash(const void *key)
289 {
290    /* Take the first dword of SHA1. */
291    return *(uint32_t *)key;
292 }
293 
si_shader_cache_key_equals(const void * a,const void * b)294 static bool si_shader_cache_key_equals(const void *a, const void *b)
295 {
296    /* Compare SHA1s. */
297    return memcmp(a, b, 20) == 0;
298 }
299 
si_destroy_shader_cache_entry(struct hash_entry * entry)300 static void si_destroy_shader_cache_entry(struct hash_entry *entry)
301 {
302    FREE((void *)entry->key);
303    FREE(entry->data);
304 }
305 
si_init_shader_cache(struct si_screen * sscreen)306 bool si_init_shader_cache(struct si_screen *sscreen)
307 {
308    (void)simple_mtx_init(&sscreen->shader_cache_mutex, mtx_plain);
309    sscreen->shader_cache =
310       _mesa_hash_table_create(NULL, si_shader_cache_key_hash, si_shader_cache_key_equals);
311 
312    return sscreen->shader_cache != NULL;
313 }
314 
si_destroy_shader_cache(struct si_screen * sscreen)315 void si_destroy_shader_cache(struct si_screen *sscreen)
316 {
317    if (sscreen->shader_cache)
318       _mesa_hash_table_destroy(sscreen->shader_cache, si_destroy_shader_cache_entry);
319    simple_mtx_destroy(&sscreen->shader_cache_mutex);
320 }
321 
322 /* SHADER STATES */
323 
si_set_tesseval_regs(struct si_screen * sscreen,const struct si_shader_selector * tes,struct si_pm4_state * pm4)324 static void si_set_tesseval_regs(struct si_screen *sscreen, const struct si_shader_selector *tes,
325                                  struct si_pm4_state *pm4)
326 {
327    const struct si_shader_info *info = &tes->info;
328    unsigned tes_prim_mode = info->base.tess.primitive_mode;
329    unsigned tes_spacing = info->base.tess.spacing;
330    bool tes_vertex_order_cw = !info->base.tess.ccw;
331    bool tes_point_mode = info->base.tess.point_mode;
332    unsigned type, partitioning, topology, distribution_mode;
333 
334    switch (tes_prim_mode) {
335    case GL_LINES:
336       type = V_028B6C_TESS_ISOLINE;
337       break;
338    case GL_TRIANGLES:
339       type = V_028B6C_TESS_TRIANGLE;
340       break;
341    case GL_QUADS:
342       type = V_028B6C_TESS_QUAD;
343       break;
344    default:
345       assert(0);
346       return;
347    }
348 
349    switch (tes_spacing) {
350    case TESS_SPACING_FRACTIONAL_ODD:
351       partitioning = V_028B6C_PART_FRAC_ODD;
352       break;
353    case TESS_SPACING_FRACTIONAL_EVEN:
354       partitioning = V_028B6C_PART_FRAC_EVEN;
355       break;
356    case TESS_SPACING_EQUAL:
357       partitioning = V_028B6C_PART_INTEGER;
358       break;
359    default:
360       assert(0);
361       return;
362    }
363 
364    if (tes_point_mode)
365       topology = V_028B6C_OUTPUT_POINT;
366    else if (tes_prim_mode == GL_LINES)
367       topology = V_028B6C_OUTPUT_LINE;
368    else if (tes_vertex_order_cw)
369       /* for some reason, this must be the other way around */
370       topology = V_028B6C_OUTPUT_TRIANGLE_CCW;
371    else
372       topology = V_028B6C_OUTPUT_TRIANGLE_CW;
373 
374    if (sscreen->info.has_distributed_tess) {
375       if (sscreen->info.family == CHIP_FIJI || sscreen->info.family >= CHIP_POLARIS10)
376          distribution_mode = V_028B6C_TRAPEZOIDS;
377       else
378          distribution_mode = V_028B6C_DONUTS;
379    } else
380       distribution_mode = V_028B6C_NO_DIST;
381 
382    assert(pm4->shader);
383    pm4->shader->vgt_tf_param = S_028B6C_TYPE(type) | S_028B6C_PARTITIONING(partitioning) |
384                                S_028B6C_TOPOLOGY(topology) |
385                                S_028B6C_DISTRIBUTION_MODE(distribution_mode);
386 }
387 
388 /* Polaris needs different VTX_REUSE_DEPTH settings depending on
389  * whether the "fractional odd" tessellation spacing is used.
390  *
391  * Possible VGT configurations and which state should set the register:
392  *
393  *   Reg set in | VGT shader configuration   | Value
394  * ------------------------------------------------------
395  *     VS as VS | VS                         | 30
396  *     VS as ES | ES -> GS -> VS             | 30
397  *    TES as VS | LS -> HS -> VS             | 14 or 30
398  *    TES as ES | LS -> HS -> ES -> GS -> VS | 14 or 30
399  *
400  * If "shader" is NULL, it's assumed it's not LS or GS copy shader.
401  */
polaris_set_vgt_vertex_reuse(struct si_screen * sscreen,struct si_shader_selector * sel,struct si_shader * shader,struct si_pm4_state * pm4)402 static void polaris_set_vgt_vertex_reuse(struct si_screen *sscreen, struct si_shader_selector *sel,
403                                          struct si_shader *shader, struct si_pm4_state *pm4)
404 {
405    if (sscreen->info.family < CHIP_POLARIS10 || sscreen->info.chip_class >= GFX10)
406       return;
407 
408    /* VS as VS, or VS as ES: */
409    if ((sel->info.stage == MESA_SHADER_VERTEX &&
410         (!shader || (!shader->key.as_ls && !shader->is_gs_copy_shader))) ||
411        /* TES as VS, or TES as ES: */
412        sel->info.stage == MESA_SHADER_TESS_EVAL) {
413       unsigned vtx_reuse_depth = 30;
414 
415       if (sel->info.stage == MESA_SHADER_TESS_EVAL &&
416           sel->info.base.tess.spacing == TESS_SPACING_FRACTIONAL_ODD)
417          vtx_reuse_depth = 14;
418 
419       assert(pm4->shader);
420       pm4->shader->vgt_vertex_reuse_block_cntl = vtx_reuse_depth;
421    }
422 }
423 
si_get_shader_pm4_state(struct si_shader * shader)424 static struct si_pm4_state *si_get_shader_pm4_state(struct si_shader *shader)
425 {
426    if (shader->pm4)
427       si_pm4_clear_state(shader->pm4);
428    else
429       shader->pm4 = CALLOC_STRUCT(si_pm4_state);
430 
431    if (shader->pm4) {
432       shader->pm4->shader = shader;
433       return shader->pm4;
434    } else {
435       fprintf(stderr, "radeonsi: Failed to create pm4 state.\n");
436       return NULL;
437    }
438 }
439 
si_get_num_vs_user_sgprs(struct si_shader * shader,unsigned num_always_on_user_sgprs)440 static unsigned si_get_num_vs_user_sgprs(struct si_shader *shader,
441                                          unsigned num_always_on_user_sgprs)
442 {
443    struct si_shader_selector *vs =
444       shader->previous_stage_sel ? shader->previous_stage_sel : shader->selector;
445    unsigned num_vbos_in_user_sgprs = vs->num_vbos_in_user_sgprs;
446 
447    /* 1 SGPR is reserved for the vertex buffer pointer. */
448    assert(num_always_on_user_sgprs <= SI_SGPR_VS_VB_DESCRIPTOR_FIRST - 1);
449 
450    if (num_vbos_in_user_sgprs)
451       return SI_SGPR_VS_VB_DESCRIPTOR_FIRST + num_vbos_in_user_sgprs * 4;
452 
453    /* Add the pointer to VBO descriptors. */
454    return num_always_on_user_sgprs + 1;
455 }
456 
457 /* Return VGPR_COMP_CNT for the API vertex shader. This can be hw LS, LSHS, ES, ESGS, VS. */
si_get_vs_vgpr_comp_cnt(struct si_screen * sscreen,struct si_shader * shader,bool legacy_vs_prim_id)458 static unsigned si_get_vs_vgpr_comp_cnt(struct si_screen *sscreen, struct si_shader *shader,
459                                         bool legacy_vs_prim_id)
460 {
461    assert(shader->selector->info.stage == MESA_SHADER_VERTEX ||
462           (shader->previous_stage_sel && shader->previous_stage_sel->info.stage == MESA_SHADER_VERTEX));
463 
464    /* GFX6-9 LS    (VertexID, RelAutoindex,                InstanceID / StepRate0(==1), ...).
465     * GFX6-9 ES,VS (VertexID, InstanceID / StepRate0(==1), VSPrimID,                    ...)
466     * GFX10  LS    (VertexID, RelAutoindex,                UserVGPR1,                   InstanceID).
467     * GFX10  ES,VS (VertexID, UserVGPR0,                   UserVGPR1 or VSPrimID,       UserVGPR2 or
468     * InstanceID)
469     */
470    bool is_ls = shader->selector->info.stage == MESA_SHADER_TESS_CTRL || shader->key.as_ls;
471 
472    if (sscreen->info.chip_class >= GFX10 && shader->info.uses_instanceid)
473       return 3;
474    else if ((is_ls && shader->info.uses_instanceid) || legacy_vs_prim_id)
475       return 2;
476    else if (is_ls || shader->info.uses_instanceid)
477       return 1;
478    else
479       return 0;
480 }
481 
si_shader_ls(struct si_screen * sscreen,struct si_shader * shader)482 static void si_shader_ls(struct si_screen *sscreen, struct si_shader *shader)
483 {
484    struct si_pm4_state *pm4;
485    uint64_t va;
486 
487    assert(sscreen->info.chip_class <= GFX8);
488 
489    pm4 = si_get_shader_pm4_state(shader);
490    if (!pm4)
491       return;
492 
493    va = shader->bo->gpu_address;
494    si_pm4_set_reg(pm4, R_00B520_SPI_SHADER_PGM_LO_LS, va >> 8);
495    si_pm4_set_reg(pm4, R_00B524_SPI_SHADER_PGM_HI_LS, S_00B524_MEM_BASE(va >> 40));
496 
497    shader->config.rsrc1 = S_00B528_VGPRS((shader->config.num_vgprs - 1) / 4) |
498                           S_00B528_SGPRS((shader->config.num_sgprs - 1) / 8) |
499                           S_00B528_VGPR_COMP_CNT(si_get_vs_vgpr_comp_cnt(sscreen, shader, false)) |
500                           S_00B528_DX10_CLAMP(1) | S_00B528_FLOAT_MODE(shader->config.float_mode);
501    shader->config.rsrc2 =
502       S_00B52C_USER_SGPR(si_get_num_vs_user_sgprs(shader, SI_VS_NUM_USER_SGPR)) |
503       S_00B52C_SCRATCH_EN(shader->config.scratch_bytes_per_wave > 0);
504 }
505 
si_shader_hs(struct si_screen * sscreen,struct si_shader * shader)506 static void si_shader_hs(struct si_screen *sscreen, struct si_shader *shader)
507 {
508    struct si_pm4_state *pm4;
509    uint64_t va;
510 
511    pm4 = si_get_shader_pm4_state(shader);
512    if (!pm4)
513       return;
514 
515    va = shader->bo->gpu_address;
516 
517    if (sscreen->info.chip_class >= GFX9) {
518       if (sscreen->info.chip_class >= GFX10) {
519          si_pm4_set_reg(pm4, R_00B520_SPI_SHADER_PGM_LO_LS, va >> 8);
520          si_pm4_set_reg(pm4, R_00B524_SPI_SHADER_PGM_HI_LS, S_00B524_MEM_BASE(va >> 40));
521       } else {
522          si_pm4_set_reg(pm4, R_00B410_SPI_SHADER_PGM_LO_LS, va >> 8);
523          si_pm4_set_reg(pm4, R_00B414_SPI_SHADER_PGM_HI_LS, S_00B414_MEM_BASE(va >> 40));
524       }
525 
526       unsigned num_user_sgprs = si_get_num_vs_user_sgprs(shader, GFX9_TCS_NUM_USER_SGPR);
527 
528       shader->config.rsrc2 = S_00B42C_USER_SGPR(num_user_sgprs) |
529                              S_00B42C_SCRATCH_EN(shader->config.scratch_bytes_per_wave > 0);
530 
531       if (sscreen->info.chip_class >= GFX10)
532          shader->config.rsrc2 |= S_00B42C_USER_SGPR_MSB_GFX10(num_user_sgprs >> 5);
533       else
534          shader->config.rsrc2 |= S_00B42C_USER_SGPR_MSB_GFX9(num_user_sgprs >> 5);
535    } else {
536       si_pm4_set_reg(pm4, R_00B420_SPI_SHADER_PGM_LO_HS, va >> 8);
537       si_pm4_set_reg(pm4, R_00B424_SPI_SHADER_PGM_HI_HS, S_00B424_MEM_BASE(va >> 40));
538 
539       shader->config.rsrc2 = S_00B42C_USER_SGPR(GFX6_TCS_NUM_USER_SGPR) | S_00B42C_OC_LDS_EN(1) |
540                              S_00B42C_SCRATCH_EN(shader->config.scratch_bytes_per_wave > 0);
541    }
542 
543    si_pm4_set_reg(
544       pm4, R_00B428_SPI_SHADER_PGM_RSRC1_HS,
545       S_00B428_VGPRS((shader->config.num_vgprs - 1) / (sscreen->ge_wave_size == 32 ? 8 : 4)) |
546          (sscreen->info.chip_class <= GFX9 ? S_00B428_SGPRS((shader->config.num_sgprs - 1) / 8)
547                                            : 0) |
548          S_00B428_DX10_CLAMP(1) | S_00B428_MEM_ORDERED(sscreen->info.chip_class >= GFX10) |
549          S_00B428_WGP_MODE(sscreen->info.chip_class >= GFX10) |
550          S_00B428_FLOAT_MODE(shader->config.float_mode) |
551          S_00B428_LS_VGPR_COMP_CNT(sscreen->info.chip_class >= GFX9
552                                       ? si_get_vs_vgpr_comp_cnt(sscreen, shader, false)
553                                       : 0));
554 
555    if (sscreen->info.chip_class <= GFX8) {
556       si_pm4_set_reg(pm4, R_00B42C_SPI_SHADER_PGM_RSRC2_HS, shader->config.rsrc2);
557    }
558 }
559 
si_emit_shader_es(struct si_context * sctx)560 static void si_emit_shader_es(struct si_context *sctx)
561 {
562    struct si_shader *shader = sctx->queued.named.es->shader;
563    unsigned initial_cdw = sctx->gfx_cs->current.cdw;
564 
565    if (!shader)
566       return;
567 
568    radeon_opt_set_context_reg(sctx, R_028AAC_VGT_ESGS_RING_ITEMSIZE,
569                               SI_TRACKED_VGT_ESGS_RING_ITEMSIZE,
570                               shader->selector->esgs_itemsize / 4);
571 
572    if (shader->selector->info.stage == MESA_SHADER_TESS_EVAL)
573       radeon_opt_set_context_reg(sctx, R_028B6C_VGT_TF_PARAM, SI_TRACKED_VGT_TF_PARAM,
574                                  shader->vgt_tf_param);
575 
576    if (shader->vgt_vertex_reuse_block_cntl)
577       radeon_opt_set_context_reg(sctx, R_028C58_VGT_VERTEX_REUSE_BLOCK_CNTL,
578                                  SI_TRACKED_VGT_VERTEX_REUSE_BLOCK_CNTL,
579                                  shader->vgt_vertex_reuse_block_cntl);
580 
581    if (initial_cdw != sctx->gfx_cs->current.cdw)
582       sctx->context_roll = true;
583 }
584 
si_shader_es(struct si_screen * sscreen,struct si_shader * shader)585 static void si_shader_es(struct si_screen *sscreen, struct si_shader *shader)
586 {
587    struct si_pm4_state *pm4;
588    unsigned num_user_sgprs;
589    unsigned vgpr_comp_cnt;
590    uint64_t va;
591    unsigned oc_lds_en;
592 
593    assert(sscreen->info.chip_class <= GFX8);
594 
595    pm4 = si_get_shader_pm4_state(shader);
596    if (!pm4)
597       return;
598 
599    pm4->atom.emit = si_emit_shader_es;
600    va = shader->bo->gpu_address;
601 
602    if (shader->selector->info.stage == MESA_SHADER_VERTEX) {
603       vgpr_comp_cnt = si_get_vs_vgpr_comp_cnt(sscreen, shader, false);
604       num_user_sgprs = si_get_num_vs_user_sgprs(shader, SI_VS_NUM_USER_SGPR);
605    } else if (shader->selector->info.stage == MESA_SHADER_TESS_EVAL) {
606       vgpr_comp_cnt = shader->selector->info.uses_primid ? 3 : 2;
607       num_user_sgprs = SI_TES_NUM_USER_SGPR;
608    } else
609       unreachable("invalid shader selector type");
610 
611    oc_lds_en = shader->selector->info.stage == MESA_SHADER_TESS_EVAL ? 1 : 0;
612 
613    si_pm4_set_reg(pm4, R_00B320_SPI_SHADER_PGM_LO_ES, va >> 8);
614    si_pm4_set_reg(pm4, R_00B324_SPI_SHADER_PGM_HI_ES, S_00B324_MEM_BASE(va >> 40));
615    si_pm4_set_reg(pm4, R_00B328_SPI_SHADER_PGM_RSRC1_ES,
616                   S_00B328_VGPRS((shader->config.num_vgprs - 1) / 4) |
617                      S_00B328_SGPRS((shader->config.num_sgprs - 1) / 8) |
618                      S_00B328_VGPR_COMP_CNT(vgpr_comp_cnt) | S_00B328_DX10_CLAMP(1) |
619                      S_00B328_FLOAT_MODE(shader->config.float_mode));
620    si_pm4_set_reg(pm4, R_00B32C_SPI_SHADER_PGM_RSRC2_ES,
621                   S_00B32C_USER_SGPR(num_user_sgprs) | S_00B32C_OC_LDS_EN(oc_lds_en) |
622                      S_00B32C_SCRATCH_EN(shader->config.scratch_bytes_per_wave > 0));
623 
624    if (shader->selector->info.stage == MESA_SHADER_TESS_EVAL)
625       si_set_tesseval_regs(sscreen, shader->selector, pm4);
626 
627    polaris_set_vgt_vertex_reuse(sscreen, shader->selector, shader, pm4);
628 }
629 
gfx9_get_gs_info(struct si_shader_selector * es,struct si_shader_selector * gs,struct gfx9_gs_info * out)630 void gfx9_get_gs_info(struct si_shader_selector *es, struct si_shader_selector *gs,
631                       struct gfx9_gs_info *out)
632 {
633    unsigned gs_num_invocations = MAX2(gs->info.base.gs.invocations, 1);
634    unsigned input_prim = gs->info.base.gs.input_primitive;
635    bool uses_adjacency =
636       input_prim >= PIPE_PRIM_LINES_ADJACENCY && input_prim <= PIPE_PRIM_TRIANGLE_STRIP_ADJACENCY;
637 
638    /* All these are in dwords: */
639    /* We can't allow using the whole LDS, because GS waves compete with
640     * other shader stages for LDS space. */
641    const unsigned max_lds_size = 8 * 1024;
642    const unsigned esgs_itemsize = es->esgs_itemsize / 4;
643    unsigned esgs_lds_size;
644 
645    /* All these are per subgroup: */
646    const unsigned max_out_prims = 32 * 1024;
647    const unsigned max_es_verts = 255;
648    const unsigned ideal_gs_prims = 64;
649    unsigned max_gs_prims, gs_prims;
650    unsigned min_es_verts, es_verts, worst_case_es_verts;
651 
652    if (uses_adjacency || gs_num_invocations > 1)
653       max_gs_prims = 127 / gs_num_invocations;
654    else
655       max_gs_prims = 255;
656 
657    /* MAX_PRIMS_PER_SUBGROUP = gs_prims * max_vert_out * gs_invocations.
658     * Make sure we don't go over the maximum value.
659     */
660    if (gs->info.base.gs.vertices_out > 0) {
661       max_gs_prims =
662          MIN2(max_gs_prims, max_out_prims / (gs->info.base.gs.vertices_out * gs_num_invocations));
663    }
664    assert(max_gs_prims > 0);
665 
666    /* If the primitive has adjacency, halve the number of vertices
667     * that will be reused in multiple primitives.
668     */
669    min_es_verts = gs->gs_input_verts_per_prim / (uses_adjacency ? 2 : 1);
670 
671    gs_prims = MIN2(ideal_gs_prims, max_gs_prims);
672    worst_case_es_verts = MIN2(min_es_verts * gs_prims, max_es_verts);
673 
674    /* Compute ESGS LDS size based on the worst case number of ES vertices
675     * needed to create the target number of GS prims per subgroup.
676     */
677    esgs_lds_size = esgs_itemsize * worst_case_es_verts;
678 
679    /* If total LDS usage is too big, refactor partitions based on ratio
680     * of ESGS item sizes.
681     */
682    if (esgs_lds_size > max_lds_size) {
683       /* Our target GS Prims Per Subgroup was too large. Calculate
684        * the maximum number of GS Prims Per Subgroup that will fit
685        * into LDS, capped by the maximum that the hardware can support.
686        */
687       gs_prims = MIN2((max_lds_size / (esgs_itemsize * min_es_verts)), max_gs_prims);
688       assert(gs_prims > 0);
689       worst_case_es_verts = MIN2(min_es_verts * gs_prims, max_es_verts);
690 
691       esgs_lds_size = esgs_itemsize * worst_case_es_verts;
692       assert(esgs_lds_size <= max_lds_size);
693    }
694 
695    /* Now calculate remaining ESGS information. */
696    if (esgs_lds_size)
697       es_verts = MIN2(esgs_lds_size / esgs_itemsize, max_es_verts);
698    else
699       es_verts = max_es_verts;
700 
701    /* Vertices for adjacency primitives are not always reused, so restore
702     * it for ES_VERTS_PER_SUBGRP.
703     */
704    min_es_verts = gs->gs_input_verts_per_prim;
705 
706    /* For normal primitives, the VGT only checks if they are past the ES
707     * verts per subgroup after allocating a full GS primitive and if they
708     * are, kick off a new subgroup.  But if those additional ES verts are
709     * unique (e.g. not reused) we need to make sure there is enough LDS
710     * space to account for those ES verts beyond ES_VERTS_PER_SUBGRP.
711     */
712    es_verts -= min_es_verts - 1;
713 
714    out->es_verts_per_subgroup = es_verts;
715    out->gs_prims_per_subgroup = gs_prims;
716    out->gs_inst_prims_in_subgroup = gs_prims * gs_num_invocations;
717    out->max_prims_per_subgroup = out->gs_inst_prims_in_subgroup * gs->info.base.gs.vertices_out;
718    out->esgs_ring_size = esgs_lds_size;
719 
720    assert(out->max_prims_per_subgroup <= max_out_prims);
721 }
722 
si_emit_shader_gs(struct si_context * sctx)723 static void si_emit_shader_gs(struct si_context *sctx)
724 {
725    struct si_shader *shader = sctx->queued.named.gs->shader;
726    unsigned initial_cdw = sctx->gfx_cs->current.cdw;
727 
728    if (!shader)
729       return;
730 
731    /* R_028A60_VGT_GSVS_RING_OFFSET_1, R_028A64_VGT_GSVS_RING_OFFSET_2
732     * R_028A68_VGT_GSVS_RING_OFFSET_3 */
733    radeon_opt_set_context_reg3(
734       sctx, R_028A60_VGT_GSVS_RING_OFFSET_1, SI_TRACKED_VGT_GSVS_RING_OFFSET_1,
735       shader->ctx_reg.gs.vgt_gsvs_ring_offset_1, shader->ctx_reg.gs.vgt_gsvs_ring_offset_2,
736       shader->ctx_reg.gs.vgt_gsvs_ring_offset_3);
737 
738    /* R_028AB0_VGT_GSVS_RING_ITEMSIZE */
739    radeon_opt_set_context_reg(sctx, R_028AB0_VGT_GSVS_RING_ITEMSIZE,
740                               SI_TRACKED_VGT_GSVS_RING_ITEMSIZE,
741                               shader->ctx_reg.gs.vgt_gsvs_ring_itemsize);
742 
743    /* R_028B38_VGT_GS_MAX_VERT_OUT */
744    radeon_opt_set_context_reg(sctx, R_028B38_VGT_GS_MAX_VERT_OUT, SI_TRACKED_VGT_GS_MAX_VERT_OUT,
745                               shader->ctx_reg.gs.vgt_gs_max_vert_out);
746 
747    /* R_028B5C_VGT_GS_VERT_ITEMSIZE, R_028B60_VGT_GS_VERT_ITEMSIZE_1
748     * R_028B64_VGT_GS_VERT_ITEMSIZE_2, R_028B68_VGT_GS_VERT_ITEMSIZE_3 */
749    radeon_opt_set_context_reg4(
750       sctx, R_028B5C_VGT_GS_VERT_ITEMSIZE, SI_TRACKED_VGT_GS_VERT_ITEMSIZE,
751       shader->ctx_reg.gs.vgt_gs_vert_itemsize, shader->ctx_reg.gs.vgt_gs_vert_itemsize_1,
752       shader->ctx_reg.gs.vgt_gs_vert_itemsize_2, shader->ctx_reg.gs.vgt_gs_vert_itemsize_3);
753 
754    /* R_028B90_VGT_GS_INSTANCE_CNT */
755    radeon_opt_set_context_reg(sctx, R_028B90_VGT_GS_INSTANCE_CNT, SI_TRACKED_VGT_GS_INSTANCE_CNT,
756                               shader->ctx_reg.gs.vgt_gs_instance_cnt);
757 
758    if (sctx->chip_class >= GFX9) {
759       /* R_028A44_VGT_GS_ONCHIP_CNTL */
760       radeon_opt_set_context_reg(sctx, R_028A44_VGT_GS_ONCHIP_CNTL, SI_TRACKED_VGT_GS_ONCHIP_CNTL,
761                                  shader->ctx_reg.gs.vgt_gs_onchip_cntl);
762       /* R_028A94_VGT_GS_MAX_PRIMS_PER_SUBGROUP */
763       radeon_opt_set_context_reg(sctx, R_028A94_VGT_GS_MAX_PRIMS_PER_SUBGROUP,
764                                  SI_TRACKED_VGT_GS_MAX_PRIMS_PER_SUBGROUP,
765                                  shader->ctx_reg.gs.vgt_gs_max_prims_per_subgroup);
766       /* R_028AAC_VGT_ESGS_RING_ITEMSIZE */
767       radeon_opt_set_context_reg(sctx, R_028AAC_VGT_ESGS_RING_ITEMSIZE,
768                                  SI_TRACKED_VGT_ESGS_RING_ITEMSIZE,
769                                  shader->ctx_reg.gs.vgt_esgs_ring_itemsize);
770 
771       if (shader->key.part.gs.es->info.stage == MESA_SHADER_TESS_EVAL)
772          radeon_opt_set_context_reg(sctx, R_028B6C_VGT_TF_PARAM, SI_TRACKED_VGT_TF_PARAM,
773                                     shader->vgt_tf_param);
774       if (shader->vgt_vertex_reuse_block_cntl)
775          radeon_opt_set_context_reg(sctx, R_028C58_VGT_VERTEX_REUSE_BLOCK_CNTL,
776                                     SI_TRACKED_VGT_VERTEX_REUSE_BLOCK_CNTL,
777                                     shader->vgt_vertex_reuse_block_cntl);
778    }
779 
780    if (initial_cdw != sctx->gfx_cs->current.cdw)
781       sctx->context_roll = true;
782 }
783 
si_shader_gs(struct si_screen * sscreen,struct si_shader * shader)784 static void si_shader_gs(struct si_screen *sscreen, struct si_shader *shader)
785 {
786    struct si_shader_selector *sel = shader->selector;
787    const ubyte *num_components = sel->info.num_stream_output_components;
788    unsigned gs_num_invocations = sel->info.base.gs.invocations;
789    struct si_pm4_state *pm4;
790    uint64_t va;
791    unsigned max_stream = util_last_bit(sel->info.base.gs.active_stream_mask);
792    unsigned offset;
793 
794    pm4 = si_get_shader_pm4_state(shader);
795    if (!pm4)
796       return;
797 
798    pm4->atom.emit = si_emit_shader_gs;
799 
800    offset = num_components[0] * sel->info.base.gs.vertices_out;
801    shader->ctx_reg.gs.vgt_gsvs_ring_offset_1 = offset;
802 
803    if (max_stream >= 2)
804       offset += num_components[1] * sel->info.base.gs.vertices_out;
805    shader->ctx_reg.gs.vgt_gsvs_ring_offset_2 = offset;
806 
807    if (max_stream >= 3)
808       offset += num_components[2] * sel->info.base.gs.vertices_out;
809    shader->ctx_reg.gs.vgt_gsvs_ring_offset_3 = offset;
810 
811    if (max_stream >= 4)
812       offset += num_components[3] * sel->info.base.gs.vertices_out;
813    shader->ctx_reg.gs.vgt_gsvs_ring_itemsize = offset;
814 
815    /* The GSVS_RING_ITEMSIZE register takes 15 bits */
816    assert(offset < (1 << 15));
817 
818    shader->ctx_reg.gs.vgt_gs_max_vert_out = sel->info.base.gs.vertices_out;
819 
820    shader->ctx_reg.gs.vgt_gs_vert_itemsize = num_components[0];
821    shader->ctx_reg.gs.vgt_gs_vert_itemsize_1 = (max_stream >= 2) ? num_components[1] : 0;
822    shader->ctx_reg.gs.vgt_gs_vert_itemsize_2 = (max_stream >= 3) ? num_components[2] : 0;
823    shader->ctx_reg.gs.vgt_gs_vert_itemsize_3 = (max_stream >= 4) ? num_components[3] : 0;
824 
825    shader->ctx_reg.gs.vgt_gs_instance_cnt =
826       S_028B90_CNT(MIN2(gs_num_invocations, 127)) | S_028B90_ENABLE(gs_num_invocations > 0);
827 
828    va = shader->bo->gpu_address;
829 
830    if (sscreen->info.chip_class >= GFX9) {
831       unsigned input_prim = sel->info.base.gs.input_primitive;
832       gl_shader_stage es_stage = shader->key.part.gs.es->info.stage;
833       unsigned es_vgpr_comp_cnt, gs_vgpr_comp_cnt;
834 
835       if (es_stage == MESA_SHADER_VERTEX) {
836          es_vgpr_comp_cnt = si_get_vs_vgpr_comp_cnt(sscreen, shader, false);
837       } else if (es_stage == MESA_SHADER_TESS_EVAL)
838          es_vgpr_comp_cnt = shader->key.part.gs.es->info.uses_primid ? 3 : 2;
839       else
840          unreachable("invalid shader selector type");
841 
842       /* If offsets 4, 5 are used, GS_VGPR_COMP_CNT is ignored and
843        * VGPR[0:4] are always loaded.
844        */
845       if (sel->info.uses_invocationid)
846          gs_vgpr_comp_cnt = 3; /* VGPR3 contains InvocationID. */
847       else if (sel->info.uses_primid)
848          gs_vgpr_comp_cnt = 2; /* VGPR2 contains PrimitiveID. */
849       else if (input_prim >= PIPE_PRIM_TRIANGLES)
850          gs_vgpr_comp_cnt = 1; /* VGPR1 contains offsets 2, 3 */
851       else
852          gs_vgpr_comp_cnt = 0; /* VGPR0 contains offsets 0, 1 */
853 
854       unsigned num_user_sgprs;
855       if (es_stage == MESA_SHADER_VERTEX)
856          num_user_sgprs = si_get_num_vs_user_sgprs(shader, GFX9_VSGS_NUM_USER_SGPR);
857       else
858          num_user_sgprs = GFX9_TESGS_NUM_USER_SGPR;
859 
860       if (sscreen->info.chip_class >= GFX10) {
861          si_pm4_set_reg(pm4, R_00B320_SPI_SHADER_PGM_LO_ES, va >> 8);
862          si_pm4_set_reg(pm4, R_00B324_SPI_SHADER_PGM_HI_ES, S_00B324_MEM_BASE(va >> 40));
863       } else {
864          si_pm4_set_reg(pm4, R_00B210_SPI_SHADER_PGM_LO_ES, va >> 8);
865          si_pm4_set_reg(pm4, R_00B214_SPI_SHADER_PGM_HI_ES, S_00B214_MEM_BASE(va >> 40));
866       }
867 
868       uint32_t rsrc1 = S_00B228_VGPRS((shader->config.num_vgprs - 1) / 4) | S_00B228_DX10_CLAMP(1) |
869                        S_00B228_MEM_ORDERED(sscreen->info.chip_class >= GFX10) |
870                        S_00B228_WGP_MODE(sscreen->info.chip_class >= GFX10) |
871                        S_00B228_FLOAT_MODE(shader->config.float_mode) |
872                        S_00B228_GS_VGPR_COMP_CNT(gs_vgpr_comp_cnt);
873       uint32_t rsrc2 = S_00B22C_USER_SGPR(num_user_sgprs) |
874                        S_00B22C_ES_VGPR_COMP_CNT(es_vgpr_comp_cnt) |
875                        S_00B22C_OC_LDS_EN(es_stage == MESA_SHADER_TESS_EVAL) |
876                        S_00B22C_LDS_SIZE(shader->config.lds_size) |
877                        S_00B22C_SCRATCH_EN(shader->config.scratch_bytes_per_wave > 0);
878 
879       if (sscreen->info.chip_class >= GFX10) {
880          rsrc2 |= S_00B22C_USER_SGPR_MSB_GFX10(num_user_sgprs >> 5);
881       } else {
882          rsrc1 |= S_00B228_SGPRS((shader->config.num_sgprs - 1) / 8);
883          rsrc2 |= S_00B22C_USER_SGPR_MSB_GFX9(num_user_sgprs >> 5);
884       }
885 
886       si_pm4_set_reg(pm4, R_00B228_SPI_SHADER_PGM_RSRC1_GS, rsrc1);
887       si_pm4_set_reg(pm4, R_00B22C_SPI_SHADER_PGM_RSRC2_GS, rsrc2);
888 
889       if (sscreen->info.chip_class >= GFX10) {
890          si_pm4_set_reg(pm4, R_00B204_SPI_SHADER_PGM_RSRC4_GS,
891                         S_00B204_CU_EN(0xffff) | S_00B204_SPI_SHADER_LATE_ALLOC_GS_GFX10(0));
892       }
893 
894       shader->ctx_reg.gs.vgt_gs_onchip_cntl =
895          S_028A44_ES_VERTS_PER_SUBGRP(shader->gs_info.es_verts_per_subgroup) |
896          S_028A44_GS_PRIMS_PER_SUBGRP(shader->gs_info.gs_prims_per_subgroup) |
897          S_028A44_GS_INST_PRIMS_IN_SUBGRP(shader->gs_info.gs_inst_prims_in_subgroup);
898       shader->ctx_reg.gs.vgt_gs_max_prims_per_subgroup =
899          S_028A94_MAX_PRIMS_PER_SUBGROUP(shader->gs_info.max_prims_per_subgroup);
900       shader->ctx_reg.gs.vgt_esgs_ring_itemsize = shader->key.part.gs.es->esgs_itemsize / 4;
901 
902       if (es_stage == MESA_SHADER_TESS_EVAL)
903          si_set_tesseval_regs(sscreen, shader->key.part.gs.es, pm4);
904 
905       polaris_set_vgt_vertex_reuse(sscreen, shader->key.part.gs.es, NULL, pm4);
906    } else {
907       si_pm4_set_reg(pm4, R_00B220_SPI_SHADER_PGM_LO_GS, va >> 8);
908       si_pm4_set_reg(pm4, R_00B224_SPI_SHADER_PGM_HI_GS, S_00B224_MEM_BASE(va >> 40));
909 
910       si_pm4_set_reg(pm4, R_00B228_SPI_SHADER_PGM_RSRC1_GS,
911                      S_00B228_VGPRS((shader->config.num_vgprs - 1) / 4) |
912                         S_00B228_SGPRS((shader->config.num_sgprs - 1) / 8) |
913                         S_00B228_DX10_CLAMP(1) | S_00B228_FLOAT_MODE(shader->config.float_mode));
914       si_pm4_set_reg(pm4, R_00B22C_SPI_SHADER_PGM_RSRC2_GS,
915                      S_00B22C_USER_SGPR(GFX6_GS_NUM_USER_SGPR) |
916                         S_00B22C_SCRATCH_EN(shader->config.scratch_bytes_per_wave > 0));
917    }
918 }
919 
gfx10_emit_ge_pc_alloc(struct si_context * sctx,unsigned value)920 static void gfx10_emit_ge_pc_alloc(struct si_context *sctx, unsigned value)
921 {
922    enum si_tracked_reg reg = SI_TRACKED_GE_PC_ALLOC;
923 
924    if (((sctx->tracked_regs.reg_saved >> reg) & 0x1) != 0x1 ||
925        sctx->tracked_regs.reg_value[reg] != value) {
926       struct radeon_cmdbuf *cs = sctx->gfx_cs;
927 
928       if (sctx->chip_class == GFX10) {
929          /* SQ_NON_EVENT must be emitted before GE_PC_ALLOC is written. */
930          radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
931          radeon_emit(cs, EVENT_TYPE(V_028A90_SQ_NON_EVENT) | EVENT_INDEX(0));
932       }
933 
934       radeon_set_uconfig_reg(cs, R_030980_GE_PC_ALLOC, value);
935 
936       sctx->tracked_regs.reg_saved |= 0x1ull << reg;
937       sctx->tracked_regs.reg_value[reg] = value;
938    }
939 }
940 
941 /* Common tail code for NGG primitive shaders. */
gfx10_emit_shader_ngg_tail(struct si_context * sctx,struct si_shader * shader,unsigned initial_cdw)942 static void gfx10_emit_shader_ngg_tail(struct si_context *sctx, struct si_shader *shader,
943                                        unsigned initial_cdw)
944 {
945    radeon_opt_set_context_reg(sctx, R_0287FC_GE_MAX_OUTPUT_PER_SUBGROUP,
946                               SI_TRACKED_GE_MAX_OUTPUT_PER_SUBGROUP,
947                               shader->ctx_reg.ngg.ge_max_output_per_subgroup);
948    radeon_opt_set_context_reg(sctx, R_028B4C_GE_NGG_SUBGRP_CNTL, SI_TRACKED_GE_NGG_SUBGRP_CNTL,
949                               shader->ctx_reg.ngg.ge_ngg_subgrp_cntl);
950    radeon_opt_set_context_reg(sctx, R_028A84_VGT_PRIMITIVEID_EN, SI_TRACKED_VGT_PRIMITIVEID_EN,
951                               shader->ctx_reg.ngg.vgt_primitiveid_en);
952    radeon_opt_set_context_reg(sctx, R_028A44_VGT_GS_ONCHIP_CNTL, SI_TRACKED_VGT_GS_ONCHIP_CNTL,
953                               shader->ctx_reg.ngg.vgt_gs_onchip_cntl);
954    radeon_opt_set_context_reg(sctx, R_028B90_VGT_GS_INSTANCE_CNT, SI_TRACKED_VGT_GS_INSTANCE_CNT,
955                               shader->ctx_reg.ngg.vgt_gs_instance_cnt);
956    radeon_opt_set_context_reg(sctx, R_028AAC_VGT_ESGS_RING_ITEMSIZE,
957                               SI_TRACKED_VGT_ESGS_RING_ITEMSIZE,
958                               shader->ctx_reg.ngg.vgt_esgs_ring_itemsize);
959    radeon_opt_set_context_reg(sctx, R_0286C4_SPI_VS_OUT_CONFIG, SI_TRACKED_SPI_VS_OUT_CONFIG,
960                               shader->ctx_reg.ngg.spi_vs_out_config);
961    radeon_opt_set_context_reg2(
962       sctx, R_028708_SPI_SHADER_IDX_FORMAT, SI_TRACKED_SPI_SHADER_IDX_FORMAT,
963       shader->ctx_reg.ngg.spi_shader_idx_format, shader->ctx_reg.ngg.spi_shader_pos_format);
964    radeon_opt_set_context_reg(sctx, R_028818_PA_CL_VTE_CNTL, SI_TRACKED_PA_CL_VTE_CNTL,
965                               shader->ctx_reg.ngg.pa_cl_vte_cntl);
966    radeon_opt_set_context_reg(sctx, R_028838_PA_CL_NGG_CNTL, SI_TRACKED_PA_CL_NGG_CNTL,
967                               shader->ctx_reg.ngg.pa_cl_ngg_cntl);
968 
969    radeon_opt_set_context_reg_rmw(sctx, R_02881C_PA_CL_VS_OUT_CNTL,
970                                   SI_TRACKED_PA_CL_VS_OUT_CNTL__VS, shader->pa_cl_vs_out_cntl,
971                                   SI_TRACKED_PA_CL_VS_OUT_CNTL__VS_MASK);
972 
973    if (initial_cdw != sctx->gfx_cs->current.cdw)
974       sctx->context_roll = true;
975 
976    /* GE_PC_ALLOC is not a context register, so it doesn't cause a context roll. */
977    gfx10_emit_ge_pc_alloc(sctx, shader->ctx_reg.ngg.ge_pc_alloc);
978 }
979 
gfx10_emit_shader_ngg_notess_nogs(struct si_context * sctx)980 static void gfx10_emit_shader_ngg_notess_nogs(struct si_context *sctx)
981 {
982    struct si_shader *shader = sctx->queued.named.gs->shader;
983    unsigned initial_cdw = sctx->gfx_cs->current.cdw;
984 
985    if (!shader)
986       return;
987 
988    gfx10_emit_shader_ngg_tail(sctx, shader, initial_cdw);
989 }
990 
gfx10_emit_shader_ngg_tess_nogs(struct si_context * sctx)991 static void gfx10_emit_shader_ngg_tess_nogs(struct si_context *sctx)
992 {
993    struct si_shader *shader = sctx->queued.named.gs->shader;
994    unsigned initial_cdw = sctx->gfx_cs->current.cdw;
995 
996    if (!shader)
997       return;
998 
999    radeon_opt_set_context_reg(sctx, R_028B6C_VGT_TF_PARAM, SI_TRACKED_VGT_TF_PARAM,
1000                               shader->vgt_tf_param);
1001 
1002    gfx10_emit_shader_ngg_tail(sctx, shader, initial_cdw);
1003 }
1004 
gfx10_emit_shader_ngg_notess_gs(struct si_context * sctx)1005 static void gfx10_emit_shader_ngg_notess_gs(struct si_context *sctx)
1006 {
1007    struct si_shader *shader = sctx->queued.named.gs->shader;
1008    unsigned initial_cdw = sctx->gfx_cs->current.cdw;
1009 
1010    if (!shader)
1011       return;
1012 
1013    radeon_opt_set_context_reg(sctx, R_028B38_VGT_GS_MAX_VERT_OUT, SI_TRACKED_VGT_GS_MAX_VERT_OUT,
1014                               shader->ctx_reg.ngg.vgt_gs_max_vert_out);
1015 
1016    gfx10_emit_shader_ngg_tail(sctx, shader, initial_cdw);
1017 }
1018 
gfx10_emit_shader_ngg_tess_gs(struct si_context * sctx)1019 static void gfx10_emit_shader_ngg_tess_gs(struct si_context *sctx)
1020 {
1021    struct si_shader *shader = sctx->queued.named.gs->shader;
1022    unsigned initial_cdw = sctx->gfx_cs->current.cdw;
1023 
1024    if (!shader)
1025       return;
1026 
1027    radeon_opt_set_context_reg(sctx, R_028B38_VGT_GS_MAX_VERT_OUT, SI_TRACKED_VGT_GS_MAX_VERT_OUT,
1028                               shader->ctx_reg.ngg.vgt_gs_max_vert_out);
1029    radeon_opt_set_context_reg(sctx, R_028B6C_VGT_TF_PARAM, SI_TRACKED_VGT_TF_PARAM,
1030                               shader->vgt_tf_param);
1031 
1032    gfx10_emit_shader_ngg_tail(sctx, shader, initial_cdw);
1033 }
1034 
si_get_input_prim(const struct si_shader_selector * gs)1035 unsigned si_get_input_prim(const struct si_shader_selector *gs)
1036 {
1037    if (gs->info.stage == MESA_SHADER_GEOMETRY)
1038       return gs->info.base.gs.input_primitive;
1039 
1040    if (gs->info.stage == MESA_SHADER_TESS_EVAL) {
1041       if (gs->info.base.tess.point_mode)
1042          return PIPE_PRIM_POINTS;
1043       if (gs->info.base.tess.primitive_mode == GL_LINES)
1044          return PIPE_PRIM_LINES;
1045       return PIPE_PRIM_TRIANGLES;
1046    }
1047 
1048    /* TODO: Set this correctly if the primitive type is set in the shader key. */
1049    return PIPE_PRIM_TRIANGLES; /* worst case for all callers */
1050 }
1051 
si_get_vs_out_cntl(const struct si_shader_selector * sel,const struct si_shader * shader,bool ngg)1052 static unsigned si_get_vs_out_cntl(const struct si_shader_selector *sel,
1053                                    const struct si_shader *shader, bool ngg)
1054 {
1055    bool writes_psize = sel->info.writes_psize;
1056 
1057    if (shader)
1058       writes_psize &= !shader->key.opt.kill_pointsize;
1059 
1060    bool misc_vec_ena = writes_psize || (sel->info.writes_edgeflag && !ngg) ||
1061                        sel->info.writes_layer || sel->info.writes_viewport_index;
1062    return S_02881C_USE_VTX_POINT_SIZE(writes_psize) |
1063           S_02881C_USE_VTX_EDGE_FLAG(sel->info.writes_edgeflag && !ngg) |
1064           S_02881C_USE_VTX_RENDER_TARGET_INDX(sel->info.writes_layer) |
1065           S_02881C_USE_VTX_VIEWPORT_INDX(sel->info.writes_viewport_index) |
1066           S_02881C_VS_OUT_MISC_VEC_ENA(misc_vec_ena) |
1067           S_02881C_VS_OUT_MISC_SIDE_BUS_ENA(misc_vec_ena);
1068 }
1069 
1070 /**
1071  * Prepare the PM4 image for \p shader, which will run as a merged ESGS shader
1072  * in NGG mode.
1073  */
gfx10_shader_ngg(struct si_screen * sscreen,struct si_shader * shader)1074 static void gfx10_shader_ngg(struct si_screen *sscreen, struct si_shader *shader)
1075 {
1076    const struct si_shader_selector *gs_sel = shader->selector;
1077    const struct si_shader_info *gs_info = &gs_sel->info;
1078    const gl_shader_stage gs_stage = shader->selector->info.stage;
1079    const struct si_shader_selector *es_sel =
1080       shader->previous_stage_sel ? shader->previous_stage_sel : shader->selector;
1081    const struct si_shader_info *es_info = &es_sel->info;
1082    const gl_shader_stage es_stage = es_sel->info.stage;
1083    unsigned num_user_sgprs;
1084    unsigned nparams, es_vgpr_comp_cnt, gs_vgpr_comp_cnt;
1085    uint64_t va;
1086    bool window_space = gs_info->stage == MESA_SHADER_VERTEX ?
1087                           gs_info->base.vs.window_space_position : 0;
1088    bool es_enable_prim_id = shader->key.mono.u.vs_export_prim_id || es_info->uses_primid;
1089    unsigned gs_num_invocations = MAX2(gs_sel->info.base.gs.invocations, 1);
1090    unsigned input_prim = si_get_input_prim(gs_sel);
1091    bool break_wave_at_eoi = false;
1092    struct si_pm4_state *pm4 = si_get_shader_pm4_state(shader);
1093    if (!pm4)
1094       return;
1095 
1096    if (es_stage == MESA_SHADER_TESS_EVAL) {
1097       pm4->atom.emit = gs_stage == MESA_SHADER_GEOMETRY ? gfx10_emit_shader_ngg_tess_gs
1098                                                        : gfx10_emit_shader_ngg_tess_nogs;
1099    } else {
1100       pm4->atom.emit = gs_stage == MESA_SHADER_GEOMETRY ? gfx10_emit_shader_ngg_notess_gs
1101                                                        : gfx10_emit_shader_ngg_notess_nogs;
1102    }
1103 
1104    va = shader->bo->gpu_address;
1105 
1106    if (es_stage == MESA_SHADER_VERTEX) {
1107       es_vgpr_comp_cnt = si_get_vs_vgpr_comp_cnt(sscreen, shader, false);
1108 
1109       if (es_info->base.vs.blit_sgprs_amd) {
1110          num_user_sgprs =
1111             SI_SGPR_VS_BLIT_DATA + es_info->base.vs.blit_sgprs_amd;
1112       } else {
1113          num_user_sgprs = si_get_num_vs_user_sgprs(shader, GFX9_VSGS_NUM_USER_SGPR);
1114       }
1115    } else {
1116       assert(es_stage == MESA_SHADER_TESS_EVAL);
1117       es_vgpr_comp_cnt = es_enable_prim_id ? 3 : 2;
1118       num_user_sgprs = GFX9_TESGS_NUM_USER_SGPR;
1119 
1120       if (es_enable_prim_id || gs_info->uses_primid)
1121          break_wave_at_eoi = true;
1122    }
1123 
1124    /* If offsets 4, 5 are used, GS_VGPR_COMP_CNT is ignored and
1125     * VGPR[0:4] are always loaded.
1126     *
1127     * Vertex shaders always need to load VGPR3, because they need to
1128     * pass edge flags for decomposed primitives (such as quads) to the PA
1129     * for the GL_LINE polygon mode to skip rendering lines on inner edges.
1130     */
1131    if (gs_info->uses_invocationid ||
1132        (gs_stage == MESA_SHADER_VERTEX && !gfx10_is_ngg_passthrough(shader)))
1133       gs_vgpr_comp_cnt = 3; /* VGPR3 contains InvocationID, edge flags. */
1134    else if ((gs_stage == MESA_SHADER_GEOMETRY && gs_info->uses_primid) ||
1135             (gs_stage == MESA_SHADER_VERTEX && shader->key.mono.u.vs_export_prim_id))
1136       gs_vgpr_comp_cnt = 2; /* VGPR2 contains PrimitiveID. */
1137    else if (input_prim >= PIPE_PRIM_TRIANGLES && !gfx10_is_ngg_passthrough(shader))
1138       gs_vgpr_comp_cnt = 1; /* VGPR1 contains offsets 2, 3 */
1139    else
1140       gs_vgpr_comp_cnt = 0; /* VGPR0 contains offsets 0, 1 */
1141 
1142    unsigned wave_size = si_get_shader_wave_size(shader);
1143 
1144    si_pm4_set_reg(pm4, R_00B320_SPI_SHADER_PGM_LO_ES, va >> 8);
1145    si_pm4_set_reg(pm4, R_00B324_SPI_SHADER_PGM_HI_ES, va >> 40);
1146    si_pm4_set_reg(
1147       pm4, R_00B228_SPI_SHADER_PGM_RSRC1_GS,
1148       S_00B228_VGPRS((shader->config.num_vgprs - 1) / (wave_size == 32 ? 8 : 4)) |
1149          S_00B228_FLOAT_MODE(shader->config.float_mode) | S_00B228_DX10_CLAMP(1) |
1150          S_00B228_MEM_ORDERED(1) |
1151          /* Disable the WGP mode on gfx10.3 because it can hang. (it happened on VanGogh)
1152           * Let's disable it on all chips that disable exactly 1 CU per SA for GS. */
1153          S_00B228_WGP_MODE(sscreen->info.chip_class == GFX10) |
1154          S_00B228_GS_VGPR_COMP_CNT(gs_vgpr_comp_cnt));
1155    si_pm4_set_reg(pm4, R_00B22C_SPI_SHADER_PGM_RSRC2_GS,
1156                   S_00B22C_SCRATCH_EN(shader->config.scratch_bytes_per_wave > 0) |
1157                      S_00B22C_USER_SGPR(num_user_sgprs) |
1158                      S_00B22C_ES_VGPR_COMP_CNT(es_vgpr_comp_cnt) |
1159                      S_00B22C_USER_SGPR_MSB_GFX10(num_user_sgprs >> 5) |
1160                      S_00B22C_OC_LDS_EN(es_stage == MESA_SHADER_TESS_EVAL) |
1161                      S_00B22C_LDS_SIZE(shader->config.lds_size));
1162 
1163    /* Determine LATE_ALLOC_GS. */
1164    unsigned num_cu_per_sh = sscreen->info.min_good_cu_per_sa;
1165    unsigned late_alloc_wave64; /* The limit is per SA. */
1166 
1167    /* For Wave32, the hw will launch twice the number of late
1168     * alloc waves, so 1 == 2x wave32.
1169     *
1170     * Don't use late alloc for NGG on Navi14 due to a hw bug.
1171     */
1172    if (sscreen->info.family == CHIP_NAVI14 || !sscreen->info.use_late_alloc)
1173       late_alloc_wave64 = 0;
1174    else if (num_cu_per_sh <= 6)
1175       late_alloc_wave64 = num_cu_per_sh - 2; /* All CUs enabled */
1176    else if (shader->key.opt.ngg_culling)
1177       late_alloc_wave64 = num_cu_per_sh * 10;
1178    else
1179       late_alloc_wave64 = num_cu_per_sh * 4;
1180 
1181    /* Limit LATE_ALLOC_GS for prevent a hang (hw bug). */
1182    if (sscreen->info.chip_class == GFX10)
1183       late_alloc_wave64 = MIN2(late_alloc_wave64, 64);
1184 
1185    /* Max number that fits into the register field. */
1186    late_alloc_wave64 = MIN2(late_alloc_wave64, 127);
1187 
1188    si_pm4_set_reg(
1189       pm4, R_00B204_SPI_SHADER_PGM_RSRC4_GS,
1190       S_00B204_CU_EN(0xffff) | S_00B204_SPI_SHADER_LATE_ALLOC_GS_GFX10(late_alloc_wave64));
1191 
1192    nparams = MAX2(shader->info.nr_param_exports, 1);
1193    shader->ctx_reg.ngg.spi_vs_out_config =
1194       S_0286C4_VS_EXPORT_COUNT(nparams - 1) |
1195       S_0286C4_NO_PC_EXPORT(shader->info.nr_param_exports == 0);
1196 
1197    shader->ctx_reg.ngg.spi_shader_idx_format =
1198       S_028708_IDX0_EXPORT_FORMAT(V_028708_SPI_SHADER_1COMP);
1199    shader->ctx_reg.ngg.spi_shader_pos_format =
1200       S_02870C_POS0_EXPORT_FORMAT(V_02870C_SPI_SHADER_4COMP) |
1201       S_02870C_POS1_EXPORT_FORMAT(shader->info.nr_pos_exports > 1 ? V_02870C_SPI_SHADER_4COMP
1202                                                                   : V_02870C_SPI_SHADER_NONE) |
1203       S_02870C_POS2_EXPORT_FORMAT(shader->info.nr_pos_exports > 2 ? V_02870C_SPI_SHADER_4COMP
1204                                                                   : V_02870C_SPI_SHADER_NONE) |
1205       S_02870C_POS3_EXPORT_FORMAT(shader->info.nr_pos_exports > 3 ? V_02870C_SPI_SHADER_4COMP
1206                                                                   : V_02870C_SPI_SHADER_NONE);
1207 
1208    shader->ctx_reg.ngg.vgt_primitiveid_en =
1209       S_028A84_PRIMITIVEID_EN(es_enable_prim_id) |
1210       S_028A84_NGG_DISABLE_PROVOK_REUSE(shader->key.mono.u.vs_export_prim_id ||
1211                                         gs_sel->info.writes_primid);
1212 
1213    if (gs_stage == MESA_SHADER_GEOMETRY) {
1214       shader->ctx_reg.ngg.vgt_esgs_ring_itemsize = es_sel->esgs_itemsize / 4;
1215       shader->ctx_reg.ngg.vgt_gs_max_vert_out = gs_sel->info.base.gs.vertices_out;
1216    } else {
1217       shader->ctx_reg.ngg.vgt_esgs_ring_itemsize = 1;
1218    }
1219 
1220    if (es_stage == MESA_SHADER_TESS_EVAL)
1221       si_set_tesseval_regs(sscreen, es_sel, pm4);
1222 
1223    shader->ctx_reg.ngg.vgt_gs_onchip_cntl =
1224       S_028A44_ES_VERTS_PER_SUBGRP(shader->ngg.hw_max_esverts) |
1225       S_028A44_GS_PRIMS_PER_SUBGRP(shader->ngg.max_gsprims) |
1226       S_028A44_GS_INST_PRIMS_IN_SUBGRP(shader->ngg.max_gsprims * gs_num_invocations);
1227    shader->ctx_reg.ngg.ge_max_output_per_subgroup =
1228       S_0287FC_MAX_VERTS_PER_SUBGROUP(shader->ngg.max_out_verts);
1229    shader->ctx_reg.ngg.ge_ngg_subgrp_cntl = S_028B4C_PRIM_AMP_FACTOR(shader->ngg.prim_amp_factor) |
1230                                             S_028B4C_THDS_PER_SUBGRP(0); /* for fast launch */
1231    shader->ctx_reg.ngg.vgt_gs_instance_cnt =
1232       S_028B90_CNT(gs_num_invocations) | S_028B90_ENABLE(gs_num_invocations > 1) |
1233       S_028B90_EN_MAX_VERT_OUT_PER_GS_INSTANCE(shader->ngg.max_vert_out_per_gs_instance);
1234 
1235    /* Always output hw-generated edge flags and pass them via the prim
1236     * export to prevent drawing lines on internal edges of decomposed
1237     * primitives (such as quads) with polygon mode = lines. Only VS needs
1238     * this.
1239     */
1240    shader->ctx_reg.ngg.pa_cl_ngg_cntl =
1241       S_028838_INDEX_BUF_EDGE_FLAG_ENA(gs_stage == MESA_SHADER_VERTEX) |
1242       /* Reuse for NGG. */
1243       S_028838_VERTEX_REUSE_DEPTH(sscreen->info.chip_class >= GFX10_3 ? 30 : 0);
1244    shader->pa_cl_vs_out_cntl = si_get_vs_out_cntl(shader->selector, shader, true);
1245 
1246    /* Oversubscribe PC. This improves performance when there are too many varyings. */
1247    float oversub_pc_factor = 0.25;
1248 
1249    if (shader->key.opt.ngg_culling) {
1250       /* Be more aggressive with NGG culling. */
1251       if (shader->info.nr_param_exports > 4)
1252          oversub_pc_factor = 1;
1253       else if (shader->info.nr_param_exports > 2)
1254          oversub_pc_factor = 0.75;
1255       else
1256          oversub_pc_factor = 0.5;
1257    }
1258 
1259    unsigned oversub_pc_lines = sscreen->info.pc_lines * oversub_pc_factor;
1260    shader->ctx_reg.ngg.ge_pc_alloc = S_030980_OVERSUB_EN(sscreen->info.use_late_alloc) |
1261                                      S_030980_NUM_PC_LINES(oversub_pc_lines - 1);
1262 
1263    if (shader->key.opt.ngg_culling & SI_NGG_CULL_GS_FAST_LAUNCH_TRI_LIST) {
1264       shader->ge_cntl = S_03096C_PRIM_GRP_SIZE(shader->ngg.max_gsprims) |
1265                         S_03096C_VERT_GRP_SIZE(shader->ngg.max_gsprims * 3);
1266    } else if (shader->key.opt.ngg_culling & SI_NGG_CULL_GS_FAST_LAUNCH_TRI_STRIP) {
1267       shader->ge_cntl = S_03096C_PRIM_GRP_SIZE(shader->ngg.max_gsprims) |
1268                         S_03096C_VERT_GRP_SIZE(shader->ngg.max_gsprims + 2);
1269    } else {
1270       shader->ge_cntl = S_03096C_PRIM_GRP_SIZE(shader->ngg.max_gsprims) |
1271                         S_03096C_VERT_GRP_SIZE(shader->ngg.hw_max_esverts) |
1272                         S_03096C_BREAK_WAVE_AT_EOI(break_wave_at_eoi);
1273 
1274       /* Bug workaround for a possible hang with non-tessellation cases.
1275        * Tessellation always sets GE_CNTL.VERT_GRP_SIZE = 0
1276        *
1277        * Requirement: GE_CNTL.VERT_GRP_SIZE = VGT_GS_ONCHIP_CNTL.ES_VERTS_PER_SUBGRP - 5
1278        */
1279       if ((sscreen->info.chip_class == GFX10) &&
1280           (es_stage == MESA_SHADER_VERTEX || gs_stage == MESA_SHADER_VERTEX) && /* = no tess */
1281           shader->ngg.hw_max_esverts != 256) {
1282          shader->ge_cntl &= C_03096C_VERT_GRP_SIZE;
1283 
1284          if (shader->ngg.hw_max_esverts > 5) {
1285             shader->ge_cntl |= S_03096C_VERT_GRP_SIZE(shader->ngg.hw_max_esverts - 5);
1286          }
1287       }
1288    }
1289 
1290    if (window_space) {
1291       shader->ctx_reg.ngg.pa_cl_vte_cntl = S_028818_VTX_XY_FMT(1) | S_028818_VTX_Z_FMT(1);
1292    } else {
1293       shader->ctx_reg.ngg.pa_cl_vte_cntl =
1294          S_028818_VTX_W0_FMT(1) | S_028818_VPORT_X_SCALE_ENA(1) | S_028818_VPORT_X_OFFSET_ENA(1) |
1295          S_028818_VPORT_Y_SCALE_ENA(1) | S_028818_VPORT_Y_OFFSET_ENA(1) |
1296          S_028818_VPORT_Z_SCALE_ENA(1) | S_028818_VPORT_Z_OFFSET_ENA(1);
1297    }
1298 }
1299 
si_emit_shader_vs(struct si_context * sctx)1300 static void si_emit_shader_vs(struct si_context *sctx)
1301 {
1302    struct si_shader *shader = sctx->queued.named.vs->shader;
1303    unsigned initial_cdw = sctx->gfx_cs->current.cdw;
1304 
1305    if (!shader)
1306       return;
1307 
1308    radeon_opt_set_context_reg(sctx, R_028A40_VGT_GS_MODE, SI_TRACKED_VGT_GS_MODE,
1309                               shader->ctx_reg.vs.vgt_gs_mode);
1310    radeon_opt_set_context_reg(sctx, R_028A84_VGT_PRIMITIVEID_EN, SI_TRACKED_VGT_PRIMITIVEID_EN,
1311                               shader->ctx_reg.vs.vgt_primitiveid_en);
1312 
1313    if (sctx->chip_class <= GFX8) {
1314       radeon_opt_set_context_reg(sctx, R_028AB4_VGT_REUSE_OFF, SI_TRACKED_VGT_REUSE_OFF,
1315                                  shader->ctx_reg.vs.vgt_reuse_off);
1316    }
1317 
1318    radeon_opt_set_context_reg(sctx, R_0286C4_SPI_VS_OUT_CONFIG, SI_TRACKED_SPI_VS_OUT_CONFIG,
1319                               shader->ctx_reg.vs.spi_vs_out_config);
1320 
1321    radeon_opt_set_context_reg(sctx, R_02870C_SPI_SHADER_POS_FORMAT,
1322                               SI_TRACKED_SPI_SHADER_POS_FORMAT,
1323                               shader->ctx_reg.vs.spi_shader_pos_format);
1324 
1325    radeon_opt_set_context_reg(sctx, R_028818_PA_CL_VTE_CNTL, SI_TRACKED_PA_CL_VTE_CNTL,
1326                               shader->ctx_reg.vs.pa_cl_vte_cntl);
1327 
1328    if (shader->selector->info.stage == MESA_SHADER_TESS_EVAL)
1329       radeon_opt_set_context_reg(sctx, R_028B6C_VGT_TF_PARAM, SI_TRACKED_VGT_TF_PARAM,
1330                                  shader->vgt_tf_param);
1331 
1332    if (shader->vgt_vertex_reuse_block_cntl)
1333       radeon_opt_set_context_reg(sctx, R_028C58_VGT_VERTEX_REUSE_BLOCK_CNTL,
1334                                  SI_TRACKED_VGT_VERTEX_REUSE_BLOCK_CNTL,
1335                                  shader->vgt_vertex_reuse_block_cntl);
1336 
1337    /* Required programming for tessellation. (legacy pipeline only) */
1338    if (sctx->chip_class >= GFX10 && shader->selector->info.stage == MESA_SHADER_TESS_EVAL) {
1339       radeon_opt_set_context_reg(sctx, R_028A44_VGT_GS_ONCHIP_CNTL,
1340                                  SI_TRACKED_VGT_GS_ONCHIP_CNTL,
1341                                  S_028A44_ES_VERTS_PER_SUBGRP(250) |
1342                                  S_028A44_GS_PRIMS_PER_SUBGRP(126) |
1343                                  S_028A44_GS_INST_PRIMS_IN_SUBGRP(126));
1344    }
1345 
1346    if (sctx->chip_class >= GFX10) {
1347       radeon_opt_set_context_reg_rmw(sctx, R_02881C_PA_CL_VS_OUT_CNTL,
1348                                      SI_TRACKED_PA_CL_VS_OUT_CNTL__VS, shader->pa_cl_vs_out_cntl,
1349                                      SI_TRACKED_PA_CL_VS_OUT_CNTL__VS_MASK);
1350    }
1351 
1352    if (initial_cdw != sctx->gfx_cs->current.cdw)
1353       sctx->context_roll = true;
1354 
1355    /* GE_PC_ALLOC is not a context register, so it doesn't cause a context roll. */
1356    if (sctx->chip_class >= GFX10)
1357       gfx10_emit_ge_pc_alloc(sctx, shader->ctx_reg.vs.ge_pc_alloc);
1358 }
1359 
1360 /**
1361  * Compute the state for \p shader, which will run as a vertex shader on the
1362  * hardware.
1363  *
1364  * If \p gs is non-NULL, it points to the geometry shader for which this shader
1365  * is the copy shader.
1366  */
si_shader_vs(struct si_screen * sscreen,struct si_shader * shader,struct si_shader_selector * gs)1367 static void si_shader_vs(struct si_screen *sscreen, struct si_shader *shader,
1368                          struct si_shader_selector *gs)
1369 {
1370    const struct si_shader_info *info = &shader->selector->info;
1371    struct si_pm4_state *pm4;
1372    unsigned num_user_sgprs, vgpr_comp_cnt;
1373    uint64_t va;
1374    unsigned nparams, oc_lds_en;
1375    bool window_space = info->stage == MESA_SHADER_VERTEX ?
1376                           info->base.vs.window_space_position : 0;
1377    bool enable_prim_id = shader->key.mono.u.vs_export_prim_id || info->uses_primid;
1378 
1379    pm4 = si_get_shader_pm4_state(shader);
1380    if (!pm4)
1381       return;
1382 
1383    pm4->atom.emit = si_emit_shader_vs;
1384 
1385    /* We always write VGT_GS_MODE in the VS state, because every switch
1386     * between different shader pipelines involving a different GS or no
1387     * GS at all involves a switch of the VS (different GS use different
1388     * copy shaders). On the other hand, when the API switches from a GS to
1389     * no GS and then back to the same GS used originally, the GS state is
1390     * not sent again.
1391     */
1392    if (!gs) {
1393       unsigned mode = V_028A40_GS_OFF;
1394 
1395       /* PrimID needs GS scenario A. */
1396       if (enable_prim_id)
1397          mode = V_028A40_GS_SCENARIO_A;
1398 
1399       shader->ctx_reg.vs.vgt_gs_mode = S_028A40_MODE(mode);
1400       shader->ctx_reg.vs.vgt_primitiveid_en = enable_prim_id;
1401    } else {
1402       shader->ctx_reg.vs.vgt_gs_mode =
1403          ac_vgt_gs_mode(gs->info.base.gs.vertices_out, sscreen->info.chip_class);
1404       shader->ctx_reg.vs.vgt_primitiveid_en = 0;
1405    }
1406 
1407    if (sscreen->info.chip_class <= GFX8) {
1408       /* Reuse needs to be set off if we write oViewport. */
1409       shader->ctx_reg.vs.vgt_reuse_off = S_028AB4_REUSE_OFF(info->writes_viewport_index);
1410    }
1411 
1412    va = shader->bo->gpu_address;
1413 
1414    if (gs) {
1415       vgpr_comp_cnt = 0; /* only VertexID is needed for GS-COPY. */
1416       num_user_sgprs = SI_GSCOPY_NUM_USER_SGPR;
1417    } else if (shader->selector->info.stage == MESA_SHADER_VERTEX) {
1418       vgpr_comp_cnt = si_get_vs_vgpr_comp_cnt(sscreen, shader, enable_prim_id);
1419 
1420       if (info->base.vs.blit_sgprs_amd) {
1421          num_user_sgprs = SI_SGPR_VS_BLIT_DATA + info->base.vs.blit_sgprs_amd;
1422       } else {
1423          num_user_sgprs = si_get_num_vs_user_sgprs(shader, SI_VS_NUM_USER_SGPR);
1424       }
1425    } else if (shader->selector->info.stage == MESA_SHADER_TESS_EVAL) {
1426       vgpr_comp_cnt = enable_prim_id ? 3 : 2;
1427       num_user_sgprs = SI_TES_NUM_USER_SGPR;
1428    } else
1429       unreachable("invalid shader selector type");
1430 
1431    /* VS is required to export at least one param. */
1432    nparams = MAX2(shader->info.nr_param_exports, 1);
1433    shader->ctx_reg.vs.spi_vs_out_config = S_0286C4_VS_EXPORT_COUNT(nparams - 1);
1434 
1435    if (sscreen->info.chip_class >= GFX10) {
1436       shader->ctx_reg.vs.spi_vs_out_config |=
1437          S_0286C4_NO_PC_EXPORT(shader->info.nr_param_exports == 0);
1438    }
1439 
1440    shader->ctx_reg.vs.spi_shader_pos_format =
1441       S_02870C_POS0_EXPORT_FORMAT(V_02870C_SPI_SHADER_4COMP) |
1442       S_02870C_POS1_EXPORT_FORMAT(shader->info.nr_pos_exports > 1 ? V_02870C_SPI_SHADER_4COMP
1443                                                                   : V_02870C_SPI_SHADER_NONE) |
1444       S_02870C_POS2_EXPORT_FORMAT(shader->info.nr_pos_exports > 2 ? V_02870C_SPI_SHADER_4COMP
1445                                                                   : V_02870C_SPI_SHADER_NONE) |
1446       S_02870C_POS3_EXPORT_FORMAT(shader->info.nr_pos_exports > 3 ? V_02870C_SPI_SHADER_4COMP
1447                                                                   : V_02870C_SPI_SHADER_NONE);
1448    shader->ctx_reg.vs.ge_pc_alloc = S_030980_OVERSUB_EN(sscreen->info.use_late_alloc) |
1449                                     S_030980_NUM_PC_LINES(sscreen->info.pc_lines / 4 - 1);
1450    shader->pa_cl_vs_out_cntl = si_get_vs_out_cntl(shader->selector, shader, false);
1451 
1452    oc_lds_en = shader->selector->info.stage == MESA_SHADER_TESS_EVAL ? 1 : 0;
1453 
1454    si_pm4_set_reg(pm4, R_00B120_SPI_SHADER_PGM_LO_VS, va >> 8);
1455    si_pm4_set_reg(pm4, R_00B124_SPI_SHADER_PGM_HI_VS, S_00B124_MEM_BASE(va >> 40));
1456 
1457    uint32_t rsrc1 =
1458       S_00B128_VGPRS((shader->config.num_vgprs - 1) / (sscreen->ge_wave_size == 32 ? 8 : 4)) |
1459       S_00B128_VGPR_COMP_CNT(vgpr_comp_cnt) | S_00B128_DX10_CLAMP(1) |
1460       S_00B128_MEM_ORDERED(sscreen->info.chip_class >= GFX10) |
1461       S_00B128_FLOAT_MODE(shader->config.float_mode);
1462    uint32_t rsrc2 = S_00B12C_USER_SGPR(num_user_sgprs) | S_00B12C_OC_LDS_EN(oc_lds_en) |
1463                     S_00B12C_SCRATCH_EN(shader->config.scratch_bytes_per_wave > 0);
1464 
1465    if (sscreen->info.chip_class >= GFX10)
1466       rsrc2 |= S_00B12C_USER_SGPR_MSB_GFX10(num_user_sgprs >> 5);
1467    else if (sscreen->info.chip_class == GFX9)
1468       rsrc2 |= S_00B12C_USER_SGPR_MSB_GFX9(num_user_sgprs >> 5);
1469 
1470    if (sscreen->info.chip_class <= GFX9)
1471       rsrc1 |= S_00B128_SGPRS((shader->config.num_sgprs - 1) / 8);
1472 
1473    if (!sscreen->use_ngg_streamout) {
1474       rsrc2 |= S_00B12C_SO_BASE0_EN(!!shader->selector->so.stride[0]) |
1475                S_00B12C_SO_BASE1_EN(!!shader->selector->so.stride[1]) |
1476                S_00B12C_SO_BASE2_EN(!!shader->selector->so.stride[2]) |
1477                S_00B12C_SO_BASE3_EN(!!shader->selector->so.stride[3]) |
1478                S_00B12C_SO_EN(!!shader->selector->so.num_outputs);
1479    }
1480 
1481    si_pm4_set_reg(pm4, R_00B128_SPI_SHADER_PGM_RSRC1_VS, rsrc1);
1482    si_pm4_set_reg(pm4, R_00B12C_SPI_SHADER_PGM_RSRC2_VS, rsrc2);
1483 
1484    if (window_space)
1485       shader->ctx_reg.vs.pa_cl_vte_cntl = S_028818_VTX_XY_FMT(1) | S_028818_VTX_Z_FMT(1);
1486    else
1487       shader->ctx_reg.vs.pa_cl_vte_cntl =
1488          S_028818_VTX_W0_FMT(1) | S_028818_VPORT_X_SCALE_ENA(1) | S_028818_VPORT_X_OFFSET_ENA(1) |
1489          S_028818_VPORT_Y_SCALE_ENA(1) | S_028818_VPORT_Y_OFFSET_ENA(1) |
1490          S_028818_VPORT_Z_SCALE_ENA(1) | S_028818_VPORT_Z_OFFSET_ENA(1);
1491 
1492    if (shader->selector->info.stage == MESA_SHADER_TESS_EVAL)
1493       si_set_tesseval_regs(sscreen, shader->selector, pm4);
1494 
1495    polaris_set_vgt_vertex_reuse(sscreen, shader->selector, shader, pm4);
1496 }
1497 
si_get_ps_num_interp(struct si_shader * ps)1498 static unsigned si_get_ps_num_interp(struct si_shader *ps)
1499 {
1500    struct si_shader_info *info = &ps->selector->info;
1501    unsigned num_colors = !!(info->colors_read & 0x0f) + !!(info->colors_read & 0xf0);
1502    unsigned num_interp =
1503       ps->selector->info.num_inputs + (ps->key.part.ps.prolog.color_two_side ? num_colors : 0);
1504 
1505    assert(num_interp <= 32);
1506    return MIN2(num_interp, 32);
1507 }
1508 
si_get_spi_shader_col_format(struct si_shader * shader)1509 static unsigned si_get_spi_shader_col_format(struct si_shader *shader)
1510 {
1511    unsigned spi_shader_col_format = shader->key.part.ps.epilog.spi_shader_col_format;
1512    unsigned value = 0, num_mrts = 0;
1513    unsigned i, num_targets = (util_last_bit(spi_shader_col_format) + 3) / 4;
1514 
1515    /* Remove holes in spi_shader_col_format. */
1516    for (i = 0; i < num_targets; i++) {
1517       unsigned spi_format = (spi_shader_col_format >> (i * 4)) & 0xf;
1518 
1519       if (spi_format) {
1520          value |= spi_format << (num_mrts * 4);
1521          num_mrts++;
1522       }
1523    }
1524 
1525    return value;
1526 }
1527 
si_emit_shader_ps(struct si_context * sctx)1528 static void si_emit_shader_ps(struct si_context *sctx)
1529 {
1530    struct si_shader *shader = sctx->queued.named.ps->shader;
1531    unsigned initial_cdw = sctx->gfx_cs->current.cdw;
1532 
1533    if (!shader)
1534       return;
1535 
1536    /* R_0286CC_SPI_PS_INPUT_ENA, R_0286D0_SPI_PS_INPUT_ADDR*/
1537    radeon_opt_set_context_reg2(sctx, R_0286CC_SPI_PS_INPUT_ENA, SI_TRACKED_SPI_PS_INPUT_ENA,
1538                                shader->ctx_reg.ps.spi_ps_input_ena,
1539                                shader->ctx_reg.ps.spi_ps_input_addr);
1540 
1541    radeon_opt_set_context_reg(sctx, R_0286E0_SPI_BARYC_CNTL, SI_TRACKED_SPI_BARYC_CNTL,
1542                               shader->ctx_reg.ps.spi_baryc_cntl);
1543    radeon_opt_set_context_reg(sctx, R_0286D8_SPI_PS_IN_CONTROL, SI_TRACKED_SPI_PS_IN_CONTROL,
1544                               shader->ctx_reg.ps.spi_ps_in_control);
1545 
1546    /* R_028710_SPI_SHADER_Z_FORMAT, R_028714_SPI_SHADER_COL_FORMAT */
1547    radeon_opt_set_context_reg2(sctx, R_028710_SPI_SHADER_Z_FORMAT, SI_TRACKED_SPI_SHADER_Z_FORMAT,
1548                                shader->ctx_reg.ps.spi_shader_z_format,
1549                                shader->ctx_reg.ps.spi_shader_col_format);
1550 
1551    radeon_opt_set_context_reg(sctx, R_02823C_CB_SHADER_MASK, SI_TRACKED_CB_SHADER_MASK,
1552                               shader->ctx_reg.ps.cb_shader_mask);
1553 
1554    if (initial_cdw != sctx->gfx_cs->current.cdw)
1555       sctx->context_roll = true;
1556 }
1557 
si_shader_ps(struct si_screen * sscreen,struct si_shader * shader)1558 static void si_shader_ps(struct si_screen *sscreen, struct si_shader *shader)
1559 {
1560    struct si_shader_info *info = &shader->selector->info;
1561    struct si_pm4_state *pm4;
1562    unsigned spi_ps_in_control, spi_shader_col_format, cb_shader_mask;
1563    unsigned spi_baryc_cntl = S_0286E0_FRONT_FACE_ALL_BITS(1);
1564    uint64_t va;
1565    unsigned input_ena = shader->config.spi_ps_input_ena;
1566 
1567    /* we need to enable at least one of them, otherwise we hang the GPU */
1568    assert(G_0286CC_PERSP_SAMPLE_ENA(input_ena) || G_0286CC_PERSP_CENTER_ENA(input_ena) ||
1569           G_0286CC_PERSP_CENTROID_ENA(input_ena) || G_0286CC_PERSP_PULL_MODEL_ENA(input_ena) ||
1570           G_0286CC_LINEAR_SAMPLE_ENA(input_ena) || G_0286CC_LINEAR_CENTER_ENA(input_ena) ||
1571           G_0286CC_LINEAR_CENTROID_ENA(input_ena) || G_0286CC_LINE_STIPPLE_TEX_ENA(input_ena));
1572    /* POS_W_FLOAT_ENA requires one of the perspective weights. */
1573    assert(!G_0286CC_POS_W_FLOAT_ENA(input_ena) || G_0286CC_PERSP_SAMPLE_ENA(input_ena) ||
1574           G_0286CC_PERSP_CENTER_ENA(input_ena) || G_0286CC_PERSP_CENTROID_ENA(input_ena) ||
1575           G_0286CC_PERSP_PULL_MODEL_ENA(input_ena));
1576 
1577    /* Validate interpolation optimization flags (read as implications). */
1578    assert(!shader->key.part.ps.prolog.bc_optimize_for_persp ||
1579           (G_0286CC_PERSP_CENTER_ENA(input_ena) && G_0286CC_PERSP_CENTROID_ENA(input_ena)));
1580    assert(!shader->key.part.ps.prolog.bc_optimize_for_linear ||
1581           (G_0286CC_LINEAR_CENTER_ENA(input_ena) && G_0286CC_LINEAR_CENTROID_ENA(input_ena)));
1582    assert(!shader->key.part.ps.prolog.force_persp_center_interp ||
1583           (!G_0286CC_PERSP_SAMPLE_ENA(input_ena) && !G_0286CC_PERSP_CENTROID_ENA(input_ena)));
1584    assert(!shader->key.part.ps.prolog.force_linear_center_interp ||
1585           (!G_0286CC_LINEAR_SAMPLE_ENA(input_ena) && !G_0286CC_LINEAR_CENTROID_ENA(input_ena)));
1586    assert(!shader->key.part.ps.prolog.force_persp_sample_interp ||
1587           (!G_0286CC_PERSP_CENTER_ENA(input_ena) && !G_0286CC_PERSP_CENTROID_ENA(input_ena)));
1588    assert(!shader->key.part.ps.prolog.force_linear_sample_interp ||
1589           (!G_0286CC_LINEAR_CENTER_ENA(input_ena) && !G_0286CC_LINEAR_CENTROID_ENA(input_ena)));
1590 
1591    /* Validate cases when the optimizations are off (read as implications). */
1592    assert(shader->key.part.ps.prolog.bc_optimize_for_persp ||
1593           !G_0286CC_PERSP_CENTER_ENA(input_ena) || !G_0286CC_PERSP_CENTROID_ENA(input_ena));
1594    assert(shader->key.part.ps.prolog.bc_optimize_for_linear ||
1595           !G_0286CC_LINEAR_CENTER_ENA(input_ena) || !G_0286CC_LINEAR_CENTROID_ENA(input_ena));
1596 
1597    pm4 = si_get_shader_pm4_state(shader);
1598    if (!pm4)
1599       return;
1600 
1601    /* If multiple state sets are allowed to be in a bin, break the batch on a new PS. */
1602    if (sscreen->dpbb_allowed &&
1603        (sscreen->pbb_context_states_per_bin > 1 ||
1604         sscreen->pbb_persistent_states_per_bin > 1)) {
1605       si_pm4_cmd_add(pm4, PKT3(PKT3_EVENT_WRITE, 0, 0));
1606       si_pm4_cmd_add(pm4, EVENT_TYPE(V_028A90_BREAK_BATCH) | EVENT_INDEX(0));
1607    }
1608 
1609    pm4->atom.emit = si_emit_shader_ps;
1610 
1611    /* SPI_BARYC_CNTL.POS_FLOAT_LOCATION
1612     * Possible vaules:
1613     * 0 -> Position = pixel center
1614     * 1 -> Position = pixel centroid
1615     * 2 -> Position = at sample position
1616     *
1617     * From GLSL 4.5 specification, section 7.1:
1618     *   "The variable gl_FragCoord is available as an input variable from
1619     *    within fragment shaders and it holds the window relative coordinates
1620     *    (x, y, z, 1/w) values for the fragment. If multi-sampling, this
1621     *    value can be for any location within the pixel, or one of the
1622     *    fragment samples. The use of centroid does not further restrict
1623     *    this value to be inside the current primitive."
1624     *
1625     * Meaning that centroid has no effect and we can return anything within
1626     * the pixel. Thus, return the value at sample position, because that's
1627     * the most accurate one shaders can get.
1628     */
1629    spi_baryc_cntl |= S_0286E0_POS_FLOAT_LOCATION(2);
1630 
1631    if (info->base.fs.pixel_center_integer)
1632       spi_baryc_cntl |= S_0286E0_POS_FLOAT_ULC(1);
1633 
1634    spi_shader_col_format = si_get_spi_shader_col_format(shader);
1635    cb_shader_mask = ac_get_cb_shader_mask(shader->key.part.ps.epilog.spi_shader_col_format);
1636 
1637    /* Ensure that some export memory is always allocated, for two reasons:
1638     *
1639     * 1) Correctness: The hardware ignores the EXEC mask if no export
1640     *    memory is allocated, so KILL and alpha test do not work correctly
1641     *    without this.
1642     * 2) Performance: Every shader needs at least a NULL export, even when
1643     *    it writes no color/depth output. The NULL export instruction
1644     *    stalls without this setting.
1645     *
1646     * Don't add this to CB_SHADER_MASK.
1647     *
1648     * GFX10 supports pixel shaders without exports by setting both
1649     * the color and Z formats to SPI_SHADER_ZERO. The hw will skip export
1650     * instructions if any are present.
1651     */
1652    if ((sscreen->info.chip_class <= GFX9 || info->base.fs.uses_discard ||
1653         shader->key.part.ps.epilog.alpha_func != PIPE_FUNC_ALWAYS) &&
1654        !spi_shader_col_format && !info->writes_z && !info->writes_stencil &&
1655        !info->writes_samplemask)
1656       spi_shader_col_format = V_028714_SPI_SHADER_32_R;
1657 
1658    shader->ctx_reg.ps.spi_ps_input_ena = input_ena;
1659    shader->ctx_reg.ps.spi_ps_input_addr = shader->config.spi_ps_input_addr;
1660 
1661    /* Set interpolation controls. */
1662    spi_ps_in_control = S_0286D8_NUM_INTERP(si_get_ps_num_interp(shader)) |
1663                        S_0286D8_PS_W32_EN(sscreen->ps_wave_size == 32);
1664 
1665    shader->ctx_reg.ps.spi_baryc_cntl = spi_baryc_cntl;
1666    shader->ctx_reg.ps.spi_ps_in_control = spi_ps_in_control;
1667    shader->ctx_reg.ps.spi_shader_z_format =
1668       ac_get_spi_shader_z_format(info->writes_z, info->writes_stencil, info->writes_samplemask);
1669    shader->ctx_reg.ps.spi_shader_col_format = spi_shader_col_format;
1670    shader->ctx_reg.ps.cb_shader_mask = cb_shader_mask;
1671 
1672    va = shader->bo->gpu_address;
1673    si_pm4_set_reg(pm4, R_00B020_SPI_SHADER_PGM_LO_PS, va >> 8);
1674    si_pm4_set_reg(pm4, R_00B024_SPI_SHADER_PGM_HI_PS, S_00B024_MEM_BASE(va >> 40));
1675 
1676    uint32_t rsrc1 =
1677       S_00B028_VGPRS((shader->config.num_vgprs - 1) / (sscreen->ps_wave_size == 32 ? 8 : 4)) |
1678       S_00B028_DX10_CLAMP(1) | S_00B028_MEM_ORDERED(sscreen->info.chip_class >= GFX10) |
1679       S_00B028_FLOAT_MODE(shader->config.float_mode);
1680 
1681    if (sscreen->info.chip_class < GFX10) {
1682       rsrc1 |= S_00B028_SGPRS((shader->config.num_sgprs - 1) / 8);
1683    }
1684 
1685    si_pm4_set_reg(pm4, R_00B028_SPI_SHADER_PGM_RSRC1_PS, rsrc1);
1686    si_pm4_set_reg(pm4, R_00B02C_SPI_SHADER_PGM_RSRC2_PS,
1687                   S_00B02C_EXTRA_LDS_SIZE(shader->config.lds_size) |
1688                      S_00B02C_USER_SGPR(SI_PS_NUM_USER_SGPR) |
1689                      S_00B32C_SCRATCH_EN(shader->config.scratch_bytes_per_wave > 0));
1690 }
1691 
si_shader_init_pm4_state(struct si_screen * sscreen,struct si_shader * shader)1692 static void si_shader_init_pm4_state(struct si_screen *sscreen, struct si_shader *shader)
1693 {
1694    switch (shader->selector->info.stage) {
1695    case MESA_SHADER_VERTEX:
1696       if (shader->key.as_ls)
1697          si_shader_ls(sscreen, shader);
1698       else if (shader->key.as_es)
1699          si_shader_es(sscreen, shader);
1700       else if (shader->key.as_ngg)
1701          gfx10_shader_ngg(sscreen, shader);
1702       else
1703          si_shader_vs(sscreen, shader, NULL);
1704       break;
1705    case MESA_SHADER_TESS_CTRL:
1706       si_shader_hs(sscreen, shader);
1707       break;
1708    case MESA_SHADER_TESS_EVAL:
1709       if (shader->key.as_es)
1710          si_shader_es(sscreen, shader);
1711       else if (shader->key.as_ngg)
1712          gfx10_shader_ngg(sscreen, shader);
1713       else
1714          si_shader_vs(sscreen, shader, NULL);
1715       break;
1716    case MESA_SHADER_GEOMETRY:
1717       if (shader->key.as_ngg)
1718          gfx10_shader_ngg(sscreen, shader);
1719       else
1720          si_shader_gs(sscreen, shader);
1721       break;
1722    case MESA_SHADER_FRAGMENT:
1723       si_shader_ps(sscreen, shader);
1724       break;
1725    default:
1726       assert(0);
1727    }
1728 }
1729 
si_get_alpha_test_func(struct si_context * sctx)1730 static unsigned si_get_alpha_test_func(struct si_context *sctx)
1731 {
1732    /* Alpha-test should be disabled if colorbuffer 0 is integer. */
1733    return sctx->queued.named.dsa->alpha_func;
1734 }
1735 
si_shader_selector_key_vs(struct si_context * sctx,struct si_shader_selector * vs,struct si_shader_key * key,struct si_vs_prolog_bits * prolog_key)1736 void si_shader_selector_key_vs(struct si_context *sctx, struct si_shader_selector *vs,
1737                                struct si_shader_key *key, struct si_vs_prolog_bits *prolog_key)
1738 {
1739    if (!sctx->vertex_elements || vs->info.base.vs.blit_sgprs_amd)
1740       return;
1741 
1742    struct si_vertex_elements *elts = sctx->vertex_elements;
1743 
1744    prolog_key->instance_divisor_is_one = elts->instance_divisor_is_one;
1745    prolog_key->instance_divisor_is_fetched = elts->instance_divisor_is_fetched;
1746    prolog_key->unpack_instance_id_from_vertex_id = sctx->prim_discard_cs_instancing;
1747 
1748    /* Prefer a monolithic shader to allow scheduling divisions around
1749     * VBO loads. */
1750    if (prolog_key->instance_divisor_is_fetched)
1751       key->opt.prefer_mono = 1;
1752 
1753    unsigned count = MIN2(vs->info.num_inputs, elts->count);
1754    unsigned count_mask = (1 << count) - 1;
1755    unsigned fix = elts->fix_fetch_always & count_mask;
1756    unsigned opencode = elts->fix_fetch_opencode & count_mask;
1757 
1758    if (sctx->vertex_buffer_unaligned & elts->vb_alignment_check_mask) {
1759       uint32_t mask = elts->fix_fetch_unaligned & count_mask;
1760       while (mask) {
1761          unsigned i = u_bit_scan(&mask);
1762          unsigned log_hw_load_size = 1 + ((elts->hw_load_is_dword >> i) & 1);
1763          unsigned vbidx = elts->vertex_buffer_index[i];
1764          struct pipe_vertex_buffer *vb = &sctx->vertex_buffer[vbidx];
1765          unsigned align_mask = (1 << log_hw_load_size) - 1;
1766          if (vb->buffer_offset & align_mask || vb->stride & align_mask) {
1767             fix |= 1 << i;
1768             opencode |= 1 << i;
1769          }
1770       }
1771    }
1772 
1773    while (fix) {
1774       unsigned i = u_bit_scan(&fix);
1775       key->mono.vs_fix_fetch[i].bits = elts->fix_fetch[i];
1776    }
1777    key->mono.vs_fetch_opencode = opencode;
1778 }
1779 
si_shader_selector_key_hw_vs(struct si_context * sctx,struct si_shader_selector * vs,struct si_shader_key * key)1780 static void si_shader_selector_key_hw_vs(struct si_context *sctx, struct si_shader_selector *vs,
1781                                          struct si_shader_key *key)
1782 {
1783    struct si_shader_selector *ps = sctx->ps_shader.cso;
1784 
1785    key->opt.kill_clip_distances = vs->clipdist_mask & ~sctx->queued.named.rasterizer->clip_plane_enable;
1786 
1787    /* Find out if PS is disabled. */
1788    bool ps_disabled = true;
1789    if (ps) {
1790       bool ps_modifies_zs = ps->info.base.fs.uses_discard || ps->info.writes_z || ps->info.writes_stencil ||
1791                             ps->info.writes_samplemask ||
1792                             sctx->queued.named.blend->alpha_to_coverage ||
1793                             si_get_alpha_test_func(sctx) != PIPE_FUNC_ALWAYS;
1794       unsigned ps_colormask = si_get_total_colormask(sctx);
1795 
1796       ps_disabled = sctx->queued.named.rasterizer->rasterizer_discard ||
1797                     (!ps_colormask && !ps_modifies_zs && !ps->info.base.writes_memory);
1798    }
1799 
1800    /* Find out which VS outputs aren't used by the PS. */
1801    uint64_t outputs_written = vs->outputs_written_before_ps;
1802    uint64_t inputs_read = 0;
1803 
1804    /* Ignore outputs that are not passed from VS to PS. */
1805    outputs_written &= ~((1ull << si_shader_io_get_unique_index(VARYING_SLOT_POS, true)) |
1806                         (1ull << si_shader_io_get_unique_index(VARYING_SLOT_PSIZ, true)) |
1807                         (1ull << si_shader_io_get_unique_index(VARYING_SLOT_CLIP_VERTEX, true)));
1808 
1809    if (!ps_disabled) {
1810       inputs_read = ps->inputs_read;
1811    }
1812 
1813    uint64_t linked = outputs_written & inputs_read;
1814 
1815    key->opt.kill_outputs = ~linked & outputs_written;
1816 
1817    if (vs->info.stage != MESA_SHADER_GEOMETRY) {
1818       key->opt.ngg_culling = sctx->ngg_culling;
1819 
1820       if (sctx->ps_shader.cso && sctx->ps_shader.cso->info.uses_primid)
1821          key->mono.u.vs_export_prim_id = 1;
1822    }
1823 
1824    /* We need PKT3_CONTEXT_REG_RMW, which we currently only use on GFX10+. */
1825    if (sctx->chip_class >= GFX10 &&
1826        vs->info.writes_psize &&
1827        sctx->current_rast_prim != PIPE_PRIM_POINTS &&
1828        !sctx->queued.named.rasterizer->polygon_mode_is_points)
1829       key->opt.kill_pointsize = 1;
1830 }
1831 
1832 /* Compute the key for the hw shader variant */
si_shader_selector_key(struct pipe_context * ctx,struct si_shader_selector * sel,union si_vgt_stages_key stages_key,struct si_shader_key * key)1833 static inline void si_shader_selector_key(struct pipe_context *ctx, struct si_shader_selector *sel,
1834                                           union si_vgt_stages_key stages_key,
1835                                           struct si_shader_key *key)
1836 {
1837    struct si_context *sctx = (struct si_context *)ctx;
1838 
1839    memset(key, 0, sizeof(*key));
1840 
1841    unsigned num_inlinable_uniforms = sel->info.base.num_inlinable_uniforms;
1842    if (num_inlinable_uniforms &&
1843        sctx->inlinable_uniforms_valid_mask & (1 << sel->pipe_shader_type)) {
1844       key->opt.inline_uniforms = true;
1845       memcpy(key->opt.inlined_uniform_values,
1846              sctx->inlinable_uniforms[sel->pipe_shader_type],
1847              num_inlinable_uniforms * 4);
1848    }
1849 
1850    switch (sel->info.stage) {
1851    case MESA_SHADER_VERTEX:
1852       si_shader_selector_key_vs(sctx, sel, key, &key->part.vs.prolog);
1853 
1854       if (sctx->tes_shader.cso)
1855          key->as_ls = 1;
1856       else if (sctx->gs_shader.cso) {
1857          key->as_es = 1;
1858          key->as_ngg = stages_key.u.ngg;
1859       } else {
1860          key->as_ngg = stages_key.u.ngg;
1861          si_shader_selector_key_hw_vs(sctx, sel, key);
1862       }
1863       break;
1864    case MESA_SHADER_TESS_CTRL:
1865       if (sctx->chip_class >= GFX9) {
1866          si_shader_selector_key_vs(sctx, sctx->vs_shader.cso, key, &key->part.tcs.ls_prolog);
1867          key->part.tcs.ls = sctx->vs_shader.cso;
1868 
1869          /* When the LS VGPR fix is needed, monolithic shaders
1870           * can:
1871           *  - avoid initializing EXEC in both the LS prolog
1872           *    and the LS main part when !vs_needs_prolog
1873           *  - remove the fixup for unused input VGPRs
1874           */
1875          key->part.tcs.ls_prolog.ls_vgpr_fix = sctx->ls_vgpr_fix;
1876 
1877          /* The LS output / HS input layout can be communicated
1878           * directly instead of via user SGPRs for merged LS-HS.
1879           * The LS VGPR fix prefers this too.
1880           */
1881          key->opt.prefer_mono = 1;
1882       }
1883 
1884       key->part.tcs.epilog.prim_mode =
1885          sctx->tes_shader.cso->info.base.tess.primitive_mode;
1886       key->part.tcs.epilog.invoc0_tess_factors_are_def =
1887          sel->info.tessfactors_are_def_in_all_invocs;
1888       key->part.tcs.epilog.tes_reads_tess_factors = sctx->tes_shader.cso->info.reads_tess_factors;
1889 
1890       if (sel == sctx->fixed_func_tcs_shader.cso)
1891          key->mono.u.ff_tcs_inputs_to_copy = sctx->vs_shader.cso->outputs_written;
1892       break;
1893    case MESA_SHADER_TESS_EVAL:
1894       key->as_ngg = stages_key.u.ngg;
1895 
1896       if (sctx->gs_shader.cso)
1897          key->as_es = 1;
1898       else {
1899          si_shader_selector_key_hw_vs(sctx, sel, key);
1900       }
1901       break;
1902    case MESA_SHADER_GEOMETRY:
1903       if (sctx->chip_class >= GFX9) {
1904          if (sctx->tes_shader.cso) {
1905             key->part.gs.es = sctx->tes_shader.cso;
1906          } else {
1907             si_shader_selector_key_vs(sctx, sctx->vs_shader.cso, key, &key->part.gs.vs_prolog);
1908             key->part.gs.es = sctx->vs_shader.cso;
1909             key->part.gs.prolog.gfx9_prev_is_vs = 1;
1910          }
1911 
1912          key->as_ngg = stages_key.u.ngg;
1913 
1914          /* Only NGG can eliminate GS outputs, because the code is shared with VS. */
1915          if (stages_key.u.ngg)
1916             si_shader_selector_key_hw_vs(sctx, sel, key);
1917 
1918          /* Merged ES-GS can have unbalanced wave usage.
1919           *
1920           * ES threads are per-vertex, while GS threads are
1921           * per-primitive. So without any amplification, there
1922           * are fewer GS threads than ES threads, which can result
1923           * in empty (no-op) GS waves. With too much amplification,
1924           * there are more GS threads than ES threads, which
1925           * can result in empty (no-op) ES waves.
1926           *
1927           * Non-monolithic shaders are implemented by setting EXEC
1928           * at the beginning of shader parts, and don't jump to
1929           * the end if EXEC is 0.
1930           *
1931           * Monolithic shaders use conditional blocks, so they can
1932           * jump and skip empty waves of ES or GS. So set this to
1933           * always use optimized variants, which are monolithic.
1934           */
1935          key->opt.prefer_mono = 1;
1936       }
1937       key->part.gs.prolog.tri_strip_adj_fix = sctx->gs_tri_strip_adj_fix;
1938       break;
1939    case MESA_SHADER_FRAGMENT: {
1940       struct si_state_rasterizer *rs = sctx->queued.named.rasterizer;
1941       struct si_state_blend *blend = sctx->queued.named.blend;
1942 
1943       if (sel->info.color0_writes_all_cbufs &&
1944           sel->info.colors_written == 0x1)
1945          key->part.ps.epilog.last_cbuf = MAX2(sctx->framebuffer.state.nr_cbufs, 1) - 1;
1946 
1947       /* Select the shader color format based on whether
1948        * blending or alpha are needed.
1949        */
1950       key->part.ps.epilog.spi_shader_col_format =
1951          (blend->blend_enable_4bit & blend->need_src_alpha_4bit &
1952           sctx->framebuffer.spi_shader_col_format_blend_alpha) |
1953          (blend->blend_enable_4bit & ~blend->need_src_alpha_4bit &
1954           sctx->framebuffer.spi_shader_col_format_blend) |
1955          (~blend->blend_enable_4bit & blend->need_src_alpha_4bit &
1956           sctx->framebuffer.spi_shader_col_format_alpha) |
1957          (~blend->blend_enable_4bit & ~blend->need_src_alpha_4bit &
1958           sctx->framebuffer.spi_shader_col_format);
1959       key->part.ps.epilog.spi_shader_col_format &= blend->cb_target_enabled_4bit;
1960 
1961       /* The output for dual source blending should have
1962        * the same format as the first output.
1963        */
1964       if (blend->dual_src_blend) {
1965          key->part.ps.epilog.spi_shader_col_format |=
1966             (key->part.ps.epilog.spi_shader_col_format & 0xf) << 4;
1967       }
1968 
1969       /* If alpha-to-coverage is enabled, we have to export alpha
1970        * even if there is no color buffer.
1971        */
1972       if (!(key->part.ps.epilog.spi_shader_col_format & 0xf) && blend->alpha_to_coverage)
1973          key->part.ps.epilog.spi_shader_col_format |= V_028710_SPI_SHADER_32_AR;
1974 
1975       /* On GFX6 and GFX7 except Hawaii, the CB doesn't clamp outputs
1976        * to the range supported by the type if a channel has less
1977        * than 16 bits and the export format is 16_ABGR.
1978        */
1979       if (sctx->chip_class <= GFX7 && sctx->family != CHIP_HAWAII) {
1980          key->part.ps.epilog.color_is_int8 = sctx->framebuffer.color_is_int8;
1981          key->part.ps.epilog.color_is_int10 = sctx->framebuffer.color_is_int10;
1982       }
1983 
1984       /* Disable unwritten outputs (if WRITE_ALL_CBUFS isn't enabled). */
1985       if (!key->part.ps.epilog.last_cbuf) {
1986          key->part.ps.epilog.spi_shader_col_format &= sel->colors_written_4bit;
1987          key->part.ps.epilog.color_is_int8 &= sel->info.colors_written;
1988          key->part.ps.epilog.color_is_int10 &= sel->info.colors_written;
1989       }
1990 
1991       bool is_poly = !util_prim_is_points_or_lines(sctx->current_rast_prim);
1992       bool is_line = util_prim_is_lines(sctx->current_rast_prim);
1993 
1994       key->part.ps.prolog.color_two_side = rs->two_side && sel->info.colors_read;
1995       key->part.ps.prolog.flatshade_colors = rs->flatshade && sel->info.colors_read;
1996 
1997       key->part.ps.epilog.alpha_to_one = blend->alpha_to_one && rs->multisample_enable;
1998 
1999       key->part.ps.prolog.poly_stipple = rs->poly_stipple_enable && is_poly;
2000       key->part.ps.epilog.poly_line_smoothing =
2001          ((is_poly && rs->poly_smooth) || (is_line && rs->line_smooth)) &&
2002          sctx->framebuffer.nr_samples <= 1;
2003       key->part.ps.epilog.clamp_color = rs->clamp_fragment_color;
2004 
2005       if (sctx->ps_iter_samples > 1 && sel->info.reads_samplemask) {
2006          key->part.ps.prolog.samplemask_log_ps_iter = util_logbase2(sctx->ps_iter_samples);
2007       }
2008 
2009       if (rs->force_persample_interp && rs->multisample_enable &&
2010           sctx->framebuffer.nr_samples > 1 && sctx->ps_iter_samples > 1) {
2011          key->part.ps.prolog.force_persp_sample_interp =
2012             sel->info.uses_persp_center || sel->info.uses_persp_centroid;
2013 
2014          key->part.ps.prolog.force_linear_sample_interp =
2015             sel->info.uses_linear_center || sel->info.uses_linear_centroid;
2016       } else if (rs->multisample_enable && sctx->framebuffer.nr_samples > 1) {
2017          key->part.ps.prolog.bc_optimize_for_persp =
2018             sel->info.uses_persp_center && sel->info.uses_persp_centroid;
2019          key->part.ps.prolog.bc_optimize_for_linear =
2020             sel->info.uses_linear_center && sel->info.uses_linear_centroid;
2021       } else {
2022          /* Make sure SPI doesn't compute more than 1 pair
2023           * of (i,j), which is the optimization here. */
2024          key->part.ps.prolog.force_persp_center_interp = sel->info.uses_persp_center +
2025                                                             sel->info.uses_persp_centroid +
2026                                                             sel->info.uses_persp_sample >
2027                                                          1;
2028 
2029          key->part.ps.prolog.force_linear_center_interp = sel->info.uses_linear_center +
2030                                                              sel->info.uses_linear_centroid +
2031                                                              sel->info.uses_linear_sample >
2032                                                           1;
2033 
2034          if (sel->info.uses_interp_at_sample)
2035             key->mono.u.ps.interpolate_at_sample_force_center = 1;
2036       }
2037 
2038       key->part.ps.epilog.alpha_func = si_get_alpha_test_func(sctx);
2039 
2040       /* ps_uses_fbfetch is true only if the color buffer is bound. */
2041       if (sctx->ps_uses_fbfetch && !sctx->blitter->running) {
2042          struct pipe_surface *cb0 = sctx->framebuffer.state.cbufs[0];
2043          struct pipe_resource *tex = cb0->texture;
2044 
2045          /* 1D textures are allocated and used as 2D on GFX9. */
2046          key->mono.u.ps.fbfetch_msaa = sctx->framebuffer.nr_samples > 1;
2047          key->mono.u.ps.fbfetch_is_1D =
2048             sctx->chip_class != GFX9 &&
2049             (tex->target == PIPE_TEXTURE_1D || tex->target == PIPE_TEXTURE_1D_ARRAY);
2050          key->mono.u.ps.fbfetch_layered =
2051             tex->target == PIPE_TEXTURE_1D_ARRAY || tex->target == PIPE_TEXTURE_2D_ARRAY ||
2052             tex->target == PIPE_TEXTURE_CUBE || tex->target == PIPE_TEXTURE_CUBE_ARRAY ||
2053             tex->target == PIPE_TEXTURE_3D;
2054       }
2055       break;
2056    }
2057    default:
2058       assert(0);
2059    }
2060 
2061    if (unlikely(sctx->screen->debug_flags & DBG(NO_OPT_VARIANT)))
2062       memset(&key->opt, 0, sizeof(key->opt));
2063 }
2064 
si_build_shader_variant(struct si_shader * shader,int thread_index,bool low_priority)2065 static void si_build_shader_variant(struct si_shader *shader, int thread_index, bool low_priority)
2066 {
2067    struct si_shader_selector *sel = shader->selector;
2068    struct si_screen *sscreen = sel->screen;
2069    struct ac_llvm_compiler *compiler;
2070    struct pipe_debug_callback *debug = &shader->compiler_ctx_state.debug;
2071 
2072    if (thread_index >= 0) {
2073       if (low_priority) {
2074          assert(thread_index < ARRAY_SIZE(sscreen->compiler_lowp));
2075          compiler = &sscreen->compiler_lowp[thread_index];
2076       } else {
2077          assert(thread_index < ARRAY_SIZE(sscreen->compiler));
2078          compiler = &sscreen->compiler[thread_index];
2079       }
2080       if (!debug->async)
2081          debug = NULL;
2082    } else {
2083       assert(!low_priority);
2084       compiler = shader->compiler_ctx_state.compiler;
2085    }
2086 
2087    if (!compiler->passes)
2088       si_init_compiler(sscreen, compiler);
2089 
2090    if (unlikely(!si_create_shader_variant(sscreen, compiler, shader, debug))) {
2091       PRINT_ERR("Failed to build shader variant (type=%u)\n", sel->info.stage);
2092       shader->compilation_failed = true;
2093       return;
2094    }
2095 
2096    if (shader->compiler_ctx_state.is_debug_context) {
2097       FILE *f = open_memstream(&shader->shader_log, &shader->shader_log_size);
2098       if (f) {
2099          si_shader_dump(sscreen, shader, NULL, f, false);
2100          fclose(f);
2101       }
2102    }
2103 
2104    si_shader_init_pm4_state(sscreen, shader);
2105 }
2106 
si_build_shader_variant_low_priority(void * job,int thread_index)2107 static void si_build_shader_variant_low_priority(void *job, int thread_index)
2108 {
2109    struct si_shader *shader = (struct si_shader *)job;
2110 
2111    assert(thread_index >= 0);
2112 
2113    si_build_shader_variant(shader, thread_index, true);
2114 }
2115 
2116 static const struct si_shader_key zeroed;
2117 
si_check_missing_main_part(struct si_screen * sscreen,struct si_shader_selector * sel,struct si_compiler_ctx_state * compiler_state,struct si_shader_key * key)2118 static bool si_check_missing_main_part(struct si_screen *sscreen, struct si_shader_selector *sel,
2119                                        struct si_compiler_ctx_state *compiler_state,
2120                                        struct si_shader_key *key)
2121 {
2122    struct si_shader **mainp = si_get_main_shader_part(sel, key);
2123 
2124    if (!*mainp) {
2125       struct si_shader *main_part = CALLOC_STRUCT(si_shader);
2126 
2127       if (!main_part)
2128          return false;
2129 
2130       /* We can leave the fence as permanently signaled because the
2131        * main part becomes visible globally only after it has been
2132        * compiled. */
2133       util_queue_fence_init(&main_part->ready);
2134 
2135       main_part->selector = sel;
2136       main_part->key.as_es = key->as_es;
2137       main_part->key.as_ls = key->as_ls;
2138       main_part->key.as_ngg = key->as_ngg;
2139       main_part->is_monolithic = false;
2140 
2141       if (!si_compile_shader(sscreen, compiler_state->compiler, main_part,
2142                              &compiler_state->debug)) {
2143          FREE(main_part);
2144          return false;
2145       }
2146       *mainp = main_part;
2147    }
2148    return true;
2149 }
2150 
2151 /**
2152  * Select a shader variant according to the shader key.
2153  *
2154  * \param optimized_or_none  If the key describes an optimized shader variant and
2155  *                           the compilation isn't finished, don't select any
2156  *                           shader and return an error.
2157  */
si_shader_select_with_key(struct si_screen * sscreen,struct si_shader_ctx_state * state,struct si_compiler_ctx_state * compiler_state,struct si_shader_key * key,int thread_index,bool optimized_or_none)2158 int si_shader_select_with_key(struct si_screen *sscreen, struct si_shader_ctx_state *state,
2159                               struct si_compiler_ctx_state *compiler_state,
2160                               struct si_shader_key *key, int thread_index, bool optimized_or_none)
2161 {
2162    struct si_shader_selector *sel = state->cso;
2163    struct si_shader_selector *previous_stage_sel = NULL;
2164    struct si_shader *current = state->current;
2165    struct si_shader *iter, *shader = NULL;
2166 
2167 again:
2168    /* Check if we don't need to change anything.
2169     * This path is also used for most shaders that don't need multiple
2170     * variants, it will cost just a computation of the key and this
2171     * test. */
2172    if (likely(current && memcmp(&current->key, key, sizeof(*key)) == 0)) {
2173       if (unlikely(!util_queue_fence_is_signalled(&current->ready))) {
2174          if (current->is_optimized) {
2175             if (optimized_or_none)
2176                return -1;
2177 
2178             memset(&key->opt, 0, sizeof(key->opt));
2179             goto current_not_ready;
2180          }
2181 
2182          util_queue_fence_wait(&current->ready);
2183       }
2184 
2185       return current->compilation_failed ? -1 : 0;
2186    }
2187 current_not_ready:
2188 
2189    /* This must be done before the mutex is locked, because async GS
2190     * compilation calls this function too, and therefore must enter
2191     * the mutex first.
2192     *
2193     * Only wait if we are in a draw call. Don't wait if we are
2194     * in a compiler thread.
2195     */
2196    if (thread_index < 0)
2197       util_queue_fence_wait(&sel->ready);
2198 
2199    simple_mtx_lock(&sel->mutex);
2200 
2201    /* Find the shader variant. */
2202    for (iter = sel->first_variant; iter; iter = iter->next_variant) {
2203       /* Don't check the "current" shader. We checked it above. */
2204       if (current != iter && memcmp(&iter->key, key, sizeof(*key)) == 0) {
2205          simple_mtx_unlock(&sel->mutex);
2206 
2207          if (unlikely(!util_queue_fence_is_signalled(&iter->ready))) {
2208             /* If it's an optimized shader and its compilation has
2209              * been started but isn't done, use the unoptimized
2210              * shader so as not to cause a stall due to compilation.
2211              */
2212             if (iter->is_optimized) {
2213                if (optimized_or_none)
2214                   return -1;
2215                memset(&key->opt, 0, sizeof(key->opt));
2216                goto again;
2217             }
2218 
2219             util_queue_fence_wait(&iter->ready);
2220          }
2221 
2222          if (iter->compilation_failed) {
2223             return -1; /* skip the draw call */
2224          }
2225 
2226          state->current = iter;
2227          return 0;
2228       }
2229    }
2230 
2231    /* Build a new shader. */
2232    shader = CALLOC_STRUCT(si_shader);
2233    if (!shader) {
2234       simple_mtx_unlock(&sel->mutex);
2235       return -ENOMEM;
2236    }
2237 
2238    util_queue_fence_init(&shader->ready);
2239 
2240    shader->selector = sel;
2241    shader->key = *key;
2242    shader->compiler_ctx_state = *compiler_state;
2243 
2244    /* If this is a merged shader, get the first shader's selector. */
2245    if (sscreen->info.chip_class >= GFX9) {
2246       if (sel->info.stage == MESA_SHADER_TESS_CTRL)
2247          previous_stage_sel = key->part.tcs.ls;
2248       else if (sel->info.stage == MESA_SHADER_GEOMETRY)
2249          previous_stage_sel = key->part.gs.es;
2250 
2251       /* We need to wait for the previous shader. */
2252       if (previous_stage_sel && thread_index < 0)
2253          util_queue_fence_wait(&previous_stage_sel->ready);
2254    }
2255 
2256    bool is_pure_monolithic =
2257       sscreen->use_monolithic_shaders || memcmp(&key->mono, &zeroed.mono, sizeof(key->mono)) != 0;
2258 
2259    /* Compile the main shader part if it doesn't exist. This can happen
2260     * if the initial guess was wrong.
2261     *
2262     * The prim discard CS doesn't need the main shader part.
2263     */
2264    if (!is_pure_monolithic && !key->opt.vs_as_prim_discard_cs) {
2265       bool ok = true;
2266 
2267       /* Make sure the main shader part is present. This is needed
2268        * for shaders that can be compiled as VS, LS, or ES, and only
2269        * one of them is compiled at creation.
2270        *
2271        * It is also needed for GS, which can be compiled as non-NGG
2272        * and NGG.
2273        *
2274        * For merged shaders, check that the starting shader's main
2275        * part is present.
2276        */
2277       if (previous_stage_sel) {
2278          struct si_shader_key shader1_key = zeroed;
2279 
2280          if (sel->info.stage == MESA_SHADER_TESS_CTRL) {
2281             shader1_key.as_ls = 1;
2282          } else if (sel->info.stage == MESA_SHADER_GEOMETRY) {
2283             shader1_key.as_es = 1;
2284             shader1_key.as_ngg = key->as_ngg; /* for Wave32 vs Wave64 */
2285          } else {
2286             assert(0);
2287          }
2288 
2289          simple_mtx_lock(&previous_stage_sel->mutex);
2290          ok = si_check_missing_main_part(sscreen, previous_stage_sel, compiler_state, &shader1_key);
2291          simple_mtx_unlock(&previous_stage_sel->mutex);
2292       }
2293 
2294       if (ok) {
2295          ok = si_check_missing_main_part(sscreen, sel, compiler_state, key);
2296       }
2297 
2298       if (!ok) {
2299          FREE(shader);
2300          simple_mtx_unlock(&sel->mutex);
2301          return -ENOMEM; /* skip the draw call */
2302       }
2303    }
2304 
2305    /* Keep the reference to the 1st shader of merged shaders, so that
2306     * Gallium can't destroy it before we destroy the 2nd shader.
2307     *
2308     * Set sctx = NULL, because it's unused if we're not releasing
2309     * the shader, and we don't have any sctx here.
2310     */
2311    si_shader_selector_reference(NULL, &shader->previous_stage_sel, previous_stage_sel);
2312 
2313    /* Monolithic-only shaders don't make a distinction between optimized
2314     * and unoptimized. */
2315    shader->is_monolithic =
2316       is_pure_monolithic || memcmp(&key->opt, &zeroed.opt, sizeof(key->opt)) != 0;
2317 
2318    /* The prim discard CS is always optimized. */
2319    shader->is_optimized = (!is_pure_monolithic || key->opt.vs_as_prim_discard_cs) &&
2320                           memcmp(&key->opt, &zeroed.opt, sizeof(key->opt)) != 0;
2321 
2322    /* If it's an optimized shader, compile it asynchronously. */
2323    if (shader->is_optimized && thread_index < 0) {
2324       /* Compile it asynchronously. */
2325       util_queue_add_job(&sscreen->shader_compiler_queue_low_priority, shader, &shader->ready,
2326                          si_build_shader_variant_low_priority, NULL, 0);
2327 
2328       /* Add only after the ready fence was reset, to guard against a
2329        * race with si_bind_XX_shader. */
2330       if (!sel->last_variant) {
2331          sel->first_variant = shader;
2332          sel->last_variant = shader;
2333       } else {
2334          sel->last_variant->next_variant = shader;
2335          sel->last_variant = shader;
2336       }
2337 
2338       /* Use the default (unoptimized) shader for now. */
2339       memset(&key->opt, 0, sizeof(key->opt));
2340       simple_mtx_unlock(&sel->mutex);
2341 
2342       if (sscreen->options.sync_compile)
2343          util_queue_fence_wait(&shader->ready);
2344 
2345       if (optimized_or_none)
2346          return -1;
2347       goto again;
2348    }
2349 
2350    /* Reset the fence before adding to the variant list. */
2351    util_queue_fence_reset(&shader->ready);
2352 
2353    if (!sel->last_variant) {
2354       sel->first_variant = shader;
2355       sel->last_variant = shader;
2356    } else {
2357       sel->last_variant->next_variant = shader;
2358       sel->last_variant = shader;
2359    }
2360 
2361    simple_mtx_unlock(&sel->mutex);
2362 
2363    assert(!shader->is_optimized);
2364    si_build_shader_variant(shader, thread_index, false);
2365 
2366    util_queue_fence_signal(&shader->ready);
2367 
2368    if (!shader->compilation_failed)
2369       state->current = shader;
2370 
2371    return shader->compilation_failed ? -1 : 0;
2372 }
2373 
si_shader_select(struct pipe_context * ctx,struct si_shader_ctx_state * state,union si_vgt_stages_key stages_key,struct si_compiler_ctx_state * compiler_state)2374 static int si_shader_select(struct pipe_context *ctx, struct si_shader_ctx_state *state,
2375                             union si_vgt_stages_key stages_key,
2376                             struct si_compiler_ctx_state *compiler_state)
2377 {
2378    struct si_context *sctx = (struct si_context *)ctx;
2379    struct si_shader_key key;
2380 
2381    si_shader_selector_key(ctx, state->cso, stages_key, &key);
2382    return si_shader_select_with_key(sctx->screen, state, compiler_state, &key, -1, false);
2383 }
2384 
si_parse_next_shader_property(const struct si_shader_info * info,bool streamout,struct si_shader_key * key)2385 static void si_parse_next_shader_property(const struct si_shader_info *info, bool streamout,
2386                                           struct si_shader_key *key)
2387 {
2388    gl_shader_stage next_shader = info->base.next_stage;
2389 
2390    switch (info->stage) {
2391    case MESA_SHADER_VERTEX:
2392       switch (next_shader) {
2393       case MESA_SHADER_GEOMETRY:
2394          key->as_es = 1;
2395          break;
2396       case MESA_SHADER_TESS_CTRL:
2397       case MESA_SHADER_TESS_EVAL:
2398          key->as_ls = 1;
2399          break;
2400       default:
2401          /* If POSITION isn't written, it can only be a HW VS
2402           * if streamout is used. If streamout isn't used,
2403           * assume that it's a HW LS. (the next shader is TCS)
2404           * This heuristic is needed for separate shader objects.
2405           */
2406          if (!info->writes_position && !streamout)
2407             key->as_ls = 1;
2408       }
2409       break;
2410 
2411    case MESA_SHADER_TESS_EVAL:
2412       if (next_shader == MESA_SHADER_GEOMETRY || !info->writes_position)
2413          key->as_es = 1;
2414       break;
2415 
2416    default:;
2417    }
2418 }
2419 
2420 /**
2421  * Compile the main shader part or the monolithic shader as part of
2422  * si_shader_selector initialization. Since it can be done asynchronously,
2423  * there is no way to report compile failures to applications.
2424  */
si_init_shader_selector_async(void * job,int thread_index)2425 static void si_init_shader_selector_async(void *job, int thread_index)
2426 {
2427    struct si_shader_selector *sel = (struct si_shader_selector *)job;
2428    struct si_screen *sscreen = sel->screen;
2429    struct ac_llvm_compiler *compiler;
2430    struct pipe_debug_callback *debug = &sel->compiler_ctx_state.debug;
2431 
2432    assert(!debug->debug_message || debug->async);
2433    assert(thread_index >= 0);
2434    assert(thread_index < ARRAY_SIZE(sscreen->compiler));
2435    compiler = &sscreen->compiler[thread_index];
2436 
2437    if (!compiler->passes)
2438       si_init_compiler(sscreen, compiler);
2439 
2440    /* Serialize NIR to save memory. Monolithic shader variants
2441     * have to deserialize NIR before compilation.
2442     */
2443    if (sel->nir) {
2444       struct blob blob;
2445       size_t size;
2446 
2447       blob_init(&blob);
2448       /* true = remove optional debugging data to increase
2449        * the likehood of getting more shader cache hits.
2450        * It also drops variable names, so we'll save more memory.
2451        */
2452       nir_serialize(&blob, sel->nir, true);
2453       blob_finish_get_buffer(&blob, &sel->nir_binary, &size);
2454       sel->nir_size = size;
2455    }
2456 
2457    /* Compile the main shader part for use with a prolog and/or epilog.
2458     * If this fails, the driver will try to compile a monolithic shader
2459     * on demand.
2460     */
2461    if (!sscreen->use_monolithic_shaders) {
2462       struct si_shader *shader = CALLOC_STRUCT(si_shader);
2463       unsigned char ir_sha1_cache_key[20];
2464 
2465       if (!shader) {
2466          fprintf(stderr, "radeonsi: can't allocate a main shader part\n");
2467          return;
2468       }
2469 
2470       /* We can leave the fence signaled because use of the default
2471        * main part is guarded by the selector's ready fence. */
2472       util_queue_fence_init(&shader->ready);
2473 
2474       shader->selector = sel;
2475       shader->is_monolithic = false;
2476       si_parse_next_shader_property(&sel->info, sel->so.num_outputs != 0, &shader->key);
2477 
2478       if (sscreen->use_ngg && (!sel->so.num_outputs || sscreen->use_ngg_streamout) &&
2479           ((sel->info.stage == MESA_SHADER_VERTEX && !shader->key.as_ls) ||
2480            sel->info.stage == MESA_SHADER_TESS_EVAL || sel->info.stage == MESA_SHADER_GEOMETRY))
2481          shader->key.as_ngg = 1;
2482 
2483       if (sel->nir) {
2484          si_get_ir_cache_key(sel, shader->key.as_ngg, shader->key.as_es, ir_sha1_cache_key);
2485       }
2486 
2487       /* Try to load the shader from the shader cache. */
2488       simple_mtx_lock(&sscreen->shader_cache_mutex);
2489 
2490       if (si_shader_cache_load_shader(sscreen, ir_sha1_cache_key, shader)) {
2491          simple_mtx_unlock(&sscreen->shader_cache_mutex);
2492          si_shader_dump_stats_for_shader_db(sscreen, shader, debug);
2493       } else {
2494          simple_mtx_unlock(&sscreen->shader_cache_mutex);
2495 
2496          /* Compile the shader if it hasn't been loaded from the cache. */
2497          if (!si_compile_shader(sscreen, compiler, shader, debug)) {
2498             FREE(shader);
2499             fprintf(stderr, "radeonsi: can't compile a main shader part\n");
2500             return;
2501          }
2502 
2503          simple_mtx_lock(&sscreen->shader_cache_mutex);
2504          si_shader_cache_insert_shader(sscreen, ir_sha1_cache_key, shader, true);
2505          simple_mtx_unlock(&sscreen->shader_cache_mutex);
2506       }
2507 
2508       *si_get_main_shader_part(sel, &shader->key) = shader;
2509 
2510       /* Unset "outputs_written" flags for outputs converted to
2511        * DEFAULT_VAL, so that later inter-shader optimizations don't
2512        * try to eliminate outputs that don't exist in the final
2513        * shader.
2514        *
2515        * This is only done if non-monolithic shaders are enabled.
2516        */
2517       if ((sel->info.stage == MESA_SHADER_VERTEX ||
2518            sel->info.stage == MESA_SHADER_TESS_EVAL ||
2519            sel->info.stage == MESA_SHADER_GEOMETRY) &&
2520           !shader->key.as_ls && !shader->key.as_es) {
2521          unsigned i;
2522 
2523          for (i = 0; i < sel->info.num_outputs; i++) {
2524             unsigned offset = shader->info.vs_output_param_offset[i];
2525 
2526             if (offset <= AC_EXP_PARAM_OFFSET_31)
2527                continue;
2528 
2529             unsigned semantic = sel->info.output_semantic[i];
2530             unsigned id;
2531 
2532             if (semantic < VARYING_SLOT_MAX &&
2533                 semantic != VARYING_SLOT_POS &&
2534                 semantic != VARYING_SLOT_PSIZ &&
2535                 semantic != VARYING_SLOT_CLIP_VERTEX &&
2536                 semantic != VARYING_SLOT_EDGE) {
2537                id = si_shader_io_get_unique_index(semantic, true);
2538                sel->outputs_written_before_ps &= ~(1ull << id);
2539             }
2540          }
2541       }
2542    }
2543 
2544    /* The GS copy shader is always pre-compiled. */
2545    if (sel->info.stage == MESA_SHADER_GEOMETRY &&
2546        (!sscreen->use_ngg || !sscreen->use_ngg_streamout || /* also for PRIMITIVES_GENERATED */
2547         sel->tess_turns_off_ngg)) {
2548       sel->gs_copy_shader = si_generate_gs_copy_shader(sscreen, compiler, sel, debug);
2549       if (!sel->gs_copy_shader) {
2550          fprintf(stderr, "radeonsi: can't create GS copy shader\n");
2551          return;
2552       }
2553 
2554       si_shader_vs(sscreen, sel->gs_copy_shader, sel);
2555    }
2556 
2557    /* Free NIR. We only keep serialized NIR after this point. */
2558    if (sel->nir) {
2559       ralloc_free(sel->nir);
2560       sel->nir = NULL;
2561    }
2562 }
2563 
si_schedule_initial_compile(struct si_context * sctx,gl_shader_stage stage,struct util_queue_fence * ready_fence,struct si_compiler_ctx_state * compiler_ctx_state,void * job,util_queue_execute_func execute)2564 void si_schedule_initial_compile(struct si_context *sctx, gl_shader_stage stage,
2565                                  struct util_queue_fence *ready_fence,
2566                                  struct si_compiler_ctx_state *compiler_ctx_state, void *job,
2567                                  util_queue_execute_func execute)
2568 {
2569    util_queue_fence_init(ready_fence);
2570 
2571    struct util_async_debug_callback async_debug;
2572    bool debug = (sctx->debug.debug_message && !sctx->debug.async) || sctx->is_debug ||
2573                 si_can_dump_shader(sctx->screen, stage);
2574 
2575    if (debug) {
2576       u_async_debug_init(&async_debug);
2577       compiler_ctx_state->debug = async_debug.base;
2578    }
2579 
2580    util_queue_add_job(&sctx->screen->shader_compiler_queue, job, ready_fence, execute, NULL, 0);
2581 
2582    if (debug) {
2583       util_queue_fence_wait(ready_fence);
2584       u_async_debug_drain(&async_debug, &sctx->debug);
2585       u_async_debug_cleanup(&async_debug);
2586    }
2587 
2588    if (sctx->screen->options.sync_compile)
2589       util_queue_fence_wait(ready_fence);
2590 }
2591 
2592 /* Return descriptor slot usage masks from the given shader info. */
si_get_active_slot_masks(const struct si_shader_info * info,uint64_t * const_and_shader_buffers,uint64_t * samplers_and_images)2593 void si_get_active_slot_masks(const struct si_shader_info *info, uint64_t *const_and_shader_buffers,
2594                               uint64_t *samplers_and_images)
2595 {
2596    unsigned start, num_shaderbufs, num_constbufs, num_images, num_msaa_images, num_samplers;
2597 
2598    num_shaderbufs = info->base.num_ssbos;
2599    num_constbufs = info->base.num_ubos;
2600    /* two 8-byte images share one 16-byte slot */
2601    num_images = align(info->base.num_images, 2);
2602    num_msaa_images = align(util_last_bit(info->base.msaa_images), 2);
2603    num_samplers = util_last_bit(info->base.textures_used);
2604 
2605    /* The layout is: sb[last] ... sb[0], cb[0] ... cb[last] */
2606    start = si_get_shaderbuf_slot(num_shaderbufs - 1);
2607    *const_and_shader_buffers = u_bit_consecutive64(start, num_shaderbufs + num_constbufs);
2608 
2609    /* The layout is:
2610     *   - fmask[last] ... fmask[0]     go to [15-last .. 15]
2611     *   - image[last] ... image[0]     go to [31-last .. 31]
2612     *   - sampler[0] ... sampler[last] go to [32 .. 32+last*2]
2613     *
2614     * FMASKs for images are placed separately, because MSAA images are rare,
2615     * and so we can benefit from a better cache hit rate if we keep image
2616     * descriptors together.
2617     */
2618    if (num_msaa_images)
2619       num_images = SI_NUM_IMAGES + num_msaa_images; /* add FMASK descriptors */
2620 
2621    start = si_get_image_slot(num_images - 1) / 2;
2622    *samplers_and_images = u_bit_consecutive64(start, num_images / 2 + num_samplers);
2623 }
2624 
si_create_shader_selector(struct pipe_context * ctx,const struct pipe_shader_state * state)2625 static void *si_create_shader_selector(struct pipe_context *ctx,
2626                                        const struct pipe_shader_state *state)
2627 {
2628    struct si_screen *sscreen = (struct si_screen *)ctx->screen;
2629    struct si_context *sctx = (struct si_context *)ctx;
2630    struct si_shader_selector *sel = CALLOC_STRUCT(si_shader_selector);
2631    int i;
2632 
2633    if (!sel)
2634       return NULL;
2635 
2636    sel->screen = sscreen;
2637    sel->compiler_ctx_state.debug = sctx->debug;
2638    sel->compiler_ctx_state.is_debug_context = sctx->is_debug;
2639 
2640    sel->so = state->stream_output;
2641 
2642    if (state->type == PIPE_SHADER_IR_TGSI) {
2643       sel->nir = tgsi_to_nir(state->tokens, ctx->screen, true);
2644    } else {
2645       assert(state->type == PIPE_SHADER_IR_NIR);
2646       sel->nir = state->ir.nir;
2647    }
2648 
2649    si_nir_scan_shader(sel->nir, &sel->info);
2650 
2651    const enum pipe_shader_type type = pipe_shader_type_from_mesa(sel->info.stage);
2652    sel->pipe_shader_type = type;
2653    sel->const_and_shader_buf_descriptors_index =
2654       si_const_and_shader_buffer_descriptors_idx(type);
2655    sel->sampler_and_images_descriptors_index =
2656       si_sampler_and_image_descriptors_idx(type);
2657 
2658    p_atomic_inc(&sscreen->num_shaders_created);
2659    si_get_active_slot_masks(&sel->info, &sel->active_const_and_shader_buffers,
2660                             &sel->active_samplers_and_images);
2661 
2662    /* Record which streamout buffers are enabled. */
2663    for (i = 0; i < sel->so.num_outputs; i++) {
2664       sel->enabled_streamout_buffer_mask |= (1 << sel->so.output[i].output_buffer)
2665                                             << (sel->so.output[i].stream * 4);
2666    }
2667 
2668    sel->num_vs_inputs =
2669       sel->info.stage == MESA_SHADER_VERTEX && !sel->info.base.vs.blit_sgprs_amd
2670          ? sel->info.num_inputs
2671          : 0;
2672    sel->num_vbos_in_user_sgprs = MIN2(sel->num_vs_inputs, sscreen->num_vbos_in_user_sgprs);
2673 
2674    /* The prolog is a no-op if there are no inputs. */
2675    sel->vs_needs_prolog = sel->info.stage == MESA_SHADER_VERTEX && sel->info.num_inputs &&
2676                           !sel->info.base.vs.blit_sgprs_amd;
2677 
2678    sel->prim_discard_cs_allowed =
2679       sel->info.stage == MESA_SHADER_VERTEX && !sel->info.uses_bindless_images &&
2680       !sel->info.uses_bindless_samplers && !sel->info.base.writes_memory &&
2681       !sel->info.writes_viewport_index &&
2682       !sel->info.base.vs.window_space_position && !sel->so.num_outputs;
2683 
2684    if (sel->info.stage == MESA_SHADER_VERTEX ||
2685        sel->info.stage == MESA_SHADER_TESS_CTRL ||
2686        sel->info.stage == MESA_SHADER_TESS_EVAL ||
2687        sel->info.stage == MESA_SHADER_GEOMETRY) {
2688       if (sel->info.stage == MESA_SHADER_TESS_CTRL) {
2689          /* Always reserve space for these. */
2690          sel->patch_outputs_written |=
2691             (1ull << si_shader_io_get_unique_index_patch(VARYING_SLOT_TESS_LEVEL_INNER)) |
2692             (1ull << si_shader_io_get_unique_index_patch(VARYING_SLOT_TESS_LEVEL_OUTER));
2693       }
2694       for (i = 0; i < sel->info.num_outputs; i++) {
2695          unsigned semantic = sel->info.output_semantic[i];
2696 
2697          if (semantic == VARYING_SLOT_TESS_LEVEL_INNER ||
2698              semantic == VARYING_SLOT_TESS_LEVEL_OUTER ||
2699              (semantic >= VARYING_SLOT_PATCH0 && semantic < VARYING_SLOT_TESS_MAX)) {
2700             sel->patch_outputs_written |= 1ull << si_shader_io_get_unique_index_patch(semantic);
2701          } else if (semantic < VARYING_SLOT_MAX &&
2702                     semantic != VARYING_SLOT_EDGE) {
2703             sel->outputs_written |= 1ull << si_shader_io_get_unique_index(semantic, false);
2704             sel->outputs_written_before_ps |= 1ull
2705                                               << si_shader_io_get_unique_index(semantic, true);
2706          }
2707       }
2708    }
2709 
2710    switch (sel->info.stage) {
2711    case MESA_SHADER_GEOMETRY:
2712       /* Only possibilities: POINTS, LINE_STRIP, TRIANGLES */
2713       sel->rast_prim = sel->info.base.gs.output_primitive;
2714       if (util_rast_prim_is_triangles(sel->rast_prim))
2715          sel->rast_prim = PIPE_PRIM_TRIANGLES;
2716 
2717       sel->gsvs_vertex_size = sel->info.num_outputs * 16;
2718       sel->max_gsvs_emit_size = sel->gsvs_vertex_size * sel->info.base.gs.vertices_out;
2719       sel->gs_input_verts_per_prim =
2720          u_vertices_per_prim(sel->info.base.gs.input_primitive);
2721 
2722       /* EN_MAX_VERT_OUT_PER_GS_INSTANCE does not work with tesselation so
2723        * we can't split workgroups. Disable ngg if any of the following conditions is true:
2724        * - num_invocations * gs.vertices_out > 256
2725        * - LDS usage is too high
2726        */
2727       sel->tess_turns_off_ngg = sscreen->info.chip_class >= GFX10 &&
2728                                 (sel->info.base.gs.invocations * sel->info.base.gs.vertices_out > 256 ||
2729                                  sel->info.base.gs.invocations * sel->info.base.gs.vertices_out *
2730                                  (sel->info.num_outputs * 4 + 1) > 6500 /* max dw per GS primitive */);
2731       break;
2732 
2733    case MESA_SHADER_VERTEX:
2734    case MESA_SHADER_TESS_CTRL:
2735    case MESA_SHADER_TESS_EVAL:
2736       sel->esgs_itemsize = util_last_bit64(sel->outputs_written) * 16;
2737       sel->lshs_vertex_stride = sel->esgs_itemsize;
2738 
2739       /* Add 1 dword to reduce LDS bank conflicts, so that each vertex
2740        * will start on a different bank. (except for the maximum 32*16).
2741        */
2742       if (sel->lshs_vertex_stride < 32 * 16)
2743          sel->lshs_vertex_stride += 4;
2744 
2745       /* For the ESGS ring in LDS, add 1 dword to reduce LDS bank
2746        * conflicts, i.e. each vertex will start at a different bank.
2747        */
2748       if (sctx->chip_class >= GFX9)
2749          sel->esgs_itemsize += 4;
2750 
2751       assert(((sel->esgs_itemsize / 4) & C_028AAC_ITEMSIZE) == 0);
2752 
2753       /* Only for TES: */
2754       if (sel->info.stage == MESA_SHADER_TESS_EVAL) {
2755          if (sel->info.base.tess.point_mode)
2756             sel->rast_prim = PIPE_PRIM_POINTS;
2757          else if (sel->info.base.tess.primitive_mode == GL_LINES)
2758             sel->rast_prim = PIPE_PRIM_LINE_STRIP;
2759          else
2760             sel->rast_prim = PIPE_PRIM_TRIANGLES;
2761       } else {
2762          sel->rast_prim = PIPE_PRIM_TRIANGLES;
2763       }
2764       break;
2765 
2766    case MESA_SHADER_FRAGMENT:
2767       for (i = 0; i < sel->info.num_inputs; i++) {
2768          unsigned semantic = sel->info.input_semantic[i];
2769 
2770          if (semantic < VARYING_SLOT_MAX &&
2771              semantic != VARYING_SLOT_PNTC) {
2772             sel->inputs_read |= 1ull << si_shader_io_get_unique_index(semantic, true);
2773          }
2774       }
2775 
2776       for (i = 0; i < 8; i++)
2777          if (sel->info.colors_written & (1 << i))
2778             sel->colors_written_4bit |= 0xf << (4 * i);
2779 
2780       for (i = 0; i < sel->info.num_inputs; i++) {
2781          if (sel->info.input_semantic[i] == VARYING_SLOT_COL0)
2782             sel->color_attr_index[0] = i;
2783          else if (sel->info.input_semantic[i] == VARYING_SLOT_COL1)
2784             sel->color_attr_index[1] = i;
2785       }
2786       break;
2787    default:;
2788    }
2789 
2790    bool ngg_culling_allowed =
2791       sscreen->info.chip_class >= GFX10 &&
2792       sscreen->info.has_dedicated_vram &&
2793       sscreen->use_ngg_culling &&
2794       (sel->info.stage == MESA_SHADER_VERTEX ||
2795        sel->info.stage == MESA_SHADER_TESS_EVAL) &&
2796       sel->info.writes_position &&
2797       !sel->info.writes_viewport_index && /* cull only against viewport 0 */
2798       !sel->info.base.writes_memory && !sel->so.num_outputs &&
2799       (sel->info.stage != MESA_SHADER_VERTEX ||
2800        (!sel->info.base.vs.blit_sgprs_amd &&
2801         !sel->info.base.vs.window_space_position));
2802 
2803    sel->ngg_cull_vert_threshold = UINT_MAX; /* disabled (changed below) */
2804    sel->ngg_cull_nonindexed_fast_launch_vert_threshold = UINT_MAX;
2805 
2806    if (ngg_culling_allowed) {
2807       if (sel->info.stage == MESA_SHADER_VERTEX) {
2808          /* 1000 non-indexed vertices (roughly 8 primgroups) are needed
2809           * per draw call (no TES/GS) to enable NGG culling by default.
2810           */
2811          sel->ngg_cull_nonindexed_fast_launch_vert_threshold = 1000;
2812 
2813          if (sscreen->debug_flags & DBG(ALWAYS_NGG_CULLING_ALL))
2814             sel->ngg_cull_vert_threshold = 0; /* always enabled */
2815          else if (sscreen->options.shader_culling ||
2816                   (sscreen->info.chip_class == GFX10_3 &&
2817                    sscreen->info.has_dedicated_vram) ||
2818                   (sscreen->info.chip_class == GFX10 &&
2819                    sscreen->info.is_pro_graphics))
2820             sel->ngg_cull_vert_threshold = 1500; /* vertex count must be more than this */
2821       } else if (sel->info.stage == MESA_SHADER_TESS_EVAL) {
2822          if (sscreen->debug_flags & DBG(ALWAYS_NGG_CULLING_ALL) ||
2823              sscreen->debug_flags & DBG(ALWAYS_NGG_CULLING_TESS) ||
2824              (sscreen->info.chip_class == GFX10_3 &&
2825               sscreen->info.has_dedicated_vram))
2826             sel->ngg_cull_vert_threshold = 0; /* always enabled */
2827       }
2828    }
2829 
2830    /* PA_CL_VS_OUT_CNTL */
2831    if (sctx->chip_class <= GFX9)
2832       sel->pa_cl_vs_out_cntl = si_get_vs_out_cntl(sel, NULL, false);
2833 
2834    sel->clipdist_mask = sel->info.writes_clipvertex ? SIX_BITS :
2835                            u_bit_consecutive(0, sel->info.base.clip_distance_array_size);
2836    sel->culldist_mask = u_bit_consecutive(0, sel->info.base.cull_distance_array_size) <<
2837                         sel->info.base.clip_distance_array_size;
2838 
2839    /* DB_SHADER_CONTROL */
2840    sel->db_shader_control = S_02880C_Z_EXPORT_ENABLE(sel->info.writes_z) |
2841                             S_02880C_STENCIL_TEST_VAL_EXPORT_ENABLE(sel->info.writes_stencil) |
2842                             S_02880C_MASK_EXPORT_ENABLE(sel->info.writes_samplemask) |
2843                             S_02880C_KILL_ENABLE(sel->info.base.fs.uses_discard);
2844 
2845    if (sel->info.stage == MESA_SHADER_FRAGMENT) {
2846       switch (sel->info.base.fs.depth_layout) {
2847       case FRAG_DEPTH_LAYOUT_GREATER:
2848          sel->db_shader_control |= S_02880C_CONSERVATIVE_Z_EXPORT(V_02880C_EXPORT_GREATER_THAN_Z);
2849          break;
2850       case FRAG_DEPTH_LAYOUT_LESS:
2851          sel->db_shader_control |= S_02880C_CONSERVATIVE_Z_EXPORT(V_02880C_EXPORT_LESS_THAN_Z);
2852          break;
2853       default:;
2854       }
2855 
2856       /* Z_ORDER, EXEC_ON_HIER_FAIL and EXEC_ON_NOOP should be set as following:
2857        *
2858        *   | early Z/S | writes_mem | allow_ReZ? |      Z_ORDER       | EXEC_ON_HIER_FAIL | EXEC_ON_NOOP
2859        * --|-----------|------------|------------|--------------------|-------------------|-------------
2860        * 1a|   false   |   false    |   true     | EarlyZ_Then_ReZ    |         0         |     0
2861        * 1b|   false   |   false    |   false    | EarlyZ_Then_LateZ  |         0         |     0
2862        * 2 |   false   |   true     |   n/a      |       LateZ        |         1         |     0
2863        * 3 |   true    |   false    |   n/a      | EarlyZ_Then_LateZ  |         0         |     0
2864        * 4 |   true    |   true     |   n/a      | EarlyZ_Then_LateZ  |         0         |     1
2865        *
2866        * In cases 3 and 4, HW will force Z_ORDER to EarlyZ regardless of what's set in the register.
2867        * In case 2, NOOP_CULL is a don't care field. In case 2, 3 and 4, ReZ doesn't make sense.
2868        *
2869        * Don't use ReZ without profiling !!!
2870        *
2871        * ReZ decreases performance by 15% in DiRT: Showdown on Ultra settings, which has pretty complex
2872        * shaders.
2873        */
2874       if (sel->info.base.fs.early_fragment_tests) {
2875          /* Cases 3, 4. */
2876          sel->db_shader_control |= S_02880C_DEPTH_BEFORE_SHADER(1) |
2877                                    S_02880C_Z_ORDER(V_02880C_EARLY_Z_THEN_LATE_Z) |
2878                                    S_02880C_EXEC_ON_NOOP(sel->info.base.writes_memory);
2879       } else if (sel->info.base.writes_memory) {
2880          /* Case 2. */
2881          sel->db_shader_control |= S_02880C_Z_ORDER(V_02880C_LATE_Z) | S_02880C_EXEC_ON_HIER_FAIL(1);
2882       } else {
2883          /* Case 1. */
2884          sel->db_shader_control |= S_02880C_Z_ORDER(V_02880C_EARLY_Z_THEN_LATE_Z);
2885       }
2886 
2887       if (sel->info.base.fs.post_depth_coverage)
2888          sel->db_shader_control |= S_02880C_PRE_SHADER_DEPTH_COVERAGE_ENABLE(1);
2889    }
2890 
2891    (void)simple_mtx_init(&sel->mutex, mtx_plain);
2892 
2893    si_schedule_initial_compile(sctx, sel->info.stage, &sel->ready, &sel->compiler_ctx_state,
2894                                sel, si_init_shader_selector_async);
2895    return sel;
2896 }
2897 
si_create_shader(struct pipe_context * ctx,const struct pipe_shader_state * state)2898 static void *si_create_shader(struct pipe_context *ctx, const struct pipe_shader_state *state)
2899 {
2900    struct si_context *sctx = (struct si_context *)ctx;
2901    struct si_screen *sscreen = (struct si_screen *)ctx->screen;
2902    bool cache_hit;
2903    struct si_shader_selector *sel = (struct si_shader_selector *)util_live_shader_cache_get(
2904       ctx, &sscreen->live_shader_cache, state, &cache_hit);
2905 
2906    if (sel && cache_hit && sctx->debug.debug_message) {
2907       if (sel->main_shader_part)
2908          si_shader_dump_stats_for_shader_db(sscreen, sel->main_shader_part, &sctx->debug);
2909       if (sel->main_shader_part_ls)
2910          si_shader_dump_stats_for_shader_db(sscreen, sel->main_shader_part_ls, &sctx->debug);
2911       if (sel->main_shader_part_es)
2912          si_shader_dump_stats_for_shader_db(sscreen, sel->main_shader_part_es, &sctx->debug);
2913       if (sel->main_shader_part_ngg)
2914          si_shader_dump_stats_for_shader_db(sscreen, sel->main_shader_part_ngg, &sctx->debug);
2915       if (sel->main_shader_part_ngg_es)
2916          si_shader_dump_stats_for_shader_db(sscreen, sel->main_shader_part_ngg_es, &sctx->debug);
2917    }
2918    return sel;
2919 }
2920 
si_update_streamout_state(struct si_context * sctx)2921 static void si_update_streamout_state(struct si_context *sctx)
2922 {
2923    struct si_shader_selector *shader_with_so = si_get_vs(sctx)->cso;
2924 
2925    if (!shader_with_so)
2926       return;
2927 
2928    sctx->streamout.enabled_stream_buffers_mask = shader_with_so->enabled_streamout_buffer_mask;
2929    sctx->streamout.stride_in_dw = shader_with_so->so.stride;
2930 }
2931 
si_update_clip_regs(struct si_context * sctx,struct si_shader_selector * old_hw_vs,struct si_shader * old_hw_vs_variant,struct si_shader_selector * next_hw_vs,struct si_shader * next_hw_vs_variant)2932 static void si_update_clip_regs(struct si_context *sctx, struct si_shader_selector *old_hw_vs,
2933                                 struct si_shader *old_hw_vs_variant,
2934                                 struct si_shader_selector *next_hw_vs,
2935                                 struct si_shader *next_hw_vs_variant)
2936 {
2937    if (next_hw_vs &&
2938        (!old_hw_vs ||
2939         (old_hw_vs->info.stage == MESA_SHADER_VERTEX && old_hw_vs->info.base.vs.window_space_position) !=
2940         (next_hw_vs->info.stage == MESA_SHADER_VERTEX && next_hw_vs->info.base.vs.window_space_position) ||
2941         old_hw_vs->pa_cl_vs_out_cntl != next_hw_vs->pa_cl_vs_out_cntl ||
2942         old_hw_vs->clipdist_mask != next_hw_vs->clipdist_mask ||
2943         old_hw_vs->culldist_mask != next_hw_vs->culldist_mask || !old_hw_vs_variant ||
2944         !next_hw_vs_variant ||
2945         old_hw_vs_variant->key.opt.kill_clip_distances != next_hw_vs_variant->key.opt.kill_clip_distances))
2946       si_mark_atom_dirty(sctx, &sctx->atoms.s.clip_regs);
2947 }
2948 
si_update_common_shader_state(struct si_context * sctx,struct si_shader_selector * sel,enum pipe_shader_type type)2949 static void si_update_common_shader_state(struct si_context *sctx, struct si_shader_selector *sel,
2950                                           enum pipe_shader_type type)
2951 {
2952    si_set_active_descriptors_for_shader(sctx, sel);
2953 
2954    sctx->uses_bindless_samplers = si_shader_uses_bindless_samplers(sctx->vs_shader.cso) ||
2955                                   si_shader_uses_bindless_samplers(sctx->gs_shader.cso) ||
2956                                   si_shader_uses_bindless_samplers(sctx->ps_shader.cso) ||
2957                                   si_shader_uses_bindless_samplers(sctx->tcs_shader.cso) ||
2958                                   si_shader_uses_bindless_samplers(sctx->tes_shader.cso);
2959    sctx->uses_bindless_images = si_shader_uses_bindless_images(sctx->vs_shader.cso) ||
2960                                 si_shader_uses_bindless_images(sctx->gs_shader.cso) ||
2961                                 si_shader_uses_bindless_images(sctx->ps_shader.cso) ||
2962                                 si_shader_uses_bindless_images(sctx->tcs_shader.cso) ||
2963                                 si_shader_uses_bindless_images(sctx->tes_shader.cso);
2964 
2965    if (sel && sel->info.base.num_inlinable_uniforms)
2966       sctx->shader_has_inlinable_uniforms_mask |= 1 << type;
2967    else
2968       sctx->shader_has_inlinable_uniforms_mask &= ~(1 << type);
2969 
2970    /* Invalidate inlinable uniforms. */
2971    sctx->inlinable_uniforms_valid_mask &= ~(1 << type);
2972 
2973    sctx->do_update_shaders = true;
2974 }
2975 
si_bind_vs_shader(struct pipe_context * ctx,void * state)2976 static void si_bind_vs_shader(struct pipe_context *ctx, void *state)
2977 {
2978    struct si_context *sctx = (struct si_context *)ctx;
2979    struct si_shader_selector *old_hw_vs = si_get_vs(sctx)->cso;
2980    struct si_shader *old_hw_vs_variant = si_get_vs_state(sctx);
2981    struct si_shader_selector *sel = state;
2982 
2983    if (sctx->vs_shader.cso == sel)
2984       return;
2985 
2986    sctx->vs_shader.cso = sel;
2987    sctx->vs_shader.current = sel ? sel->first_variant : NULL;
2988    sctx->num_vs_blit_sgprs = sel ? sel->info.base.vs.blit_sgprs_amd : 0;
2989 
2990    if (si_update_ngg(sctx))
2991       si_shader_change_notify(sctx);
2992 
2993    si_update_common_shader_state(sctx, sel, PIPE_SHADER_VERTEX);
2994    si_update_vs_viewport_state(sctx);
2995    si_update_streamout_state(sctx);
2996    si_update_clip_regs(sctx, old_hw_vs, old_hw_vs_variant, si_get_vs(sctx)->cso,
2997                        si_get_vs_state(sctx));
2998 }
2999 
si_update_tess_uses_prim_id(struct si_context * sctx)3000 static void si_update_tess_uses_prim_id(struct si_context *sctx)
3001 {
3002    sctx->ia_multi_vgt_param_key.u.tess_uses_prim_id =
3003       (sctx->tes_shader.cso && sctx->tes_shader.cso->info.uses_primid) ||
3004       (sctx->tcs_shader.cso && sctx->tcs_shader.cso->info.uses_primid) ||
3005       (sctx->gs_shader.cso && sctx->gs_shader.cso->info.uses_primid) ||
3006       (sctx->ps_shader.cso && !sctx->gs_shader.cso && sctx->ps_shader.cso->info.uses_primid);
3007 }
3008 
si_update_ngg(struct si_context * sctx)3009 bool si_update_ngg(struct si_context *sctx)
3010 {
3011    if (!sctx->screen->use_ngg) {
3012       assert(!sctx->ngg);
3013       return false;
3014    }
3015 
3016    bool new_ngg = true;
3017 
3018    if (sctx->gs_shader.cso && sctx->tes_shader.cso && sctx->gs_shader.cso->tess_turns_off_ngg) {
3019       new_ngg = false;
3020    } else if (!sctx->screen->use_ngg_streamout) {
3021       struct si_shader_selector *last = si_get_vs(sctx)->cso;
3022 
3023       if ((last && last->so.num_outputs) || sctx->streamout.prims_gen_query_enabled)
3024          new_ngg = false;
3025    }
3026 
3027    if (new_ngg != sctx->ngg) {
3028       /* Transitioning from NGG to legacy GS requires VGT_FLUSH on Navi10-14.
3029        * VGT_FLUSH is also emitted at the beginning of IBs when legacy GS ring
3030        * pointers are set.
3031        */
3032       if ((sctx->chip_class == GFX10 || sctx->family == CHIP_SIENNA_CICHLID) && !new_ngg) {
3033          sctx->flags |= SI_CONTEXT_VGT_FLUSH;
3034          if (sctx->chip_class == GFX10) {
3035             /* Workaround for https://gitlab.freedesktop.org/mesa/mesa/-/issues/2941 */
3036             si_flush_gfx_cs(sctx, RADEON_FLUSH_ASYNC_START_NEXT_GFX_IB_NOW, NULL);
3037          }
3038       }
3039 
3040       sctx->ngg = new_ngg;
3041       sctx->last_gs_out_prim = -1; /* reset this so that it gets updated */
3042       return true;
3043    }
3044    return false;
3045 }
3046 
si_bind_gs_shader(struct pipe_context * ctx,void * state)3047 static void si_bind_gs_shader(struct pipe_context *ctx, void *state)
3048 {
3049    struct si_context *sctx = (struct si_context *)ctx;
3050    struct si_shader_selector *old_hw_vs = si_get_vs(sctx)->cso;
3051    struct si_shader *old_hw_vs_variant = si_get_vs_state(sctx);
3052    struct si_shader_selector *sel = state;
3053    bool enable_changed = !!sctx->gs_shader.cso != !!sel;
3054    bool ngg_changed;
3055 
3056    if (sctx->gs_shader.cso == sel)
3057       return;
3058 
3059    sctx->gs_shader.cso = sel;
3060    sctx->gs_shader.current = sel ? sel->first_variant : NULL;
3061    sctx->ia_multi_vgt_param_key.u.uses_gs = sel != NULL;
3062 
3063    si_update_common_shader_state(sctx, sel, PIPE_SHADER_GEOMETRY);
3064    sctx->last_gs_out_prim = -1; /* reset this so that it gets updated */
3065 
3066    ngg_changed = si_update_ngg(sctx);
3067    if (ngg_changed || enable_changed)
3068       si_shader_change_notify(sctx);
3069    if (enable_changed) {
3070       if (sctx->ia_multi_vgt_param_key.u.uses_tess)
3071          si_update_tess_uses_prim_id(sctx);
3072    }
3073    si_update_vs_viewport_state(sctx);
3074    si_update_streamout_state(sctx);
3075    si_update_clip_regs(sctx, old_hw_vs, old_hw_vs_variant, si_get_vs(sctx)->cso,
3076                        si_get_vs_state(sctx));
3077 }
3078 
si_bind_tcs_shader(struct pipe_context * ctx,void * state)3079 static void si_bind_tcs_shader(struct pipe_context *ctx, void *state)
3080 {
3081    struct si_context *sctx = (struct si_context *)ctx;
3082    struct si_shader_selector *sel = state;
3083    bool enable_changed = !!sctx->tcs_shader.cso != !!sel;
3084 
3085    if (sctx->tcs_shader.cso == sel)
3086       return;
3087 
3088    sctx->tcs_shader.cso = sel;
3089    sctx->tcs_shader.current = sel ? sel->first_variant : NULL;
3090    si_update_tess_uses_prim_id(sctx);
3091 
3092    si_update_common_shader_state(sctx, sel, PIPE_SHADER_TESS_CTRL);
3093 
3094    if (enable_changed)
3095       sctx->last_tcs = NULL; /* invalidate derived tess state */
3096 }
3097 
si_bind_tes_shader(struct pipe_context * ctx,void * state)3098 static void si_bind_tes_shader(struct pipe_context *ctx, void *state)
3099 {
3100    struct si_context *sctx = (struct si_context *)ctx;
3101    struct si_shader_selector *old_hw_vs = si_get_vs(sctx)->cso;
3102    struct si_shader *old_hw_vs_variant = si_get_vs_state(sctx);
3103    struct si_shader_selector *sel = state;
3104    bool enable_changed = !!sctx->tes_shader.cso != !!sel;
3105 
3106    if (sctx->tes_shader.cso == sel)
3107       return;
3108 
3109    sctx->tes_shader.cso = sel;
3110    sctx->tes_shader.current = sel ? sel->first_variant : NULL;
3111    sctx->ia_multi_vgt_param_key.u.uses_tess = sel != NULL;
3112    si_update_tess_uses_prim_id(sctx);
3113 
3114    si_update_common_shader_state(sctx, sel, PIPE_SHADER_TESS_EVAL);
3115    sctx->last_gs_out_prim = -1; /* reset this so that it gets updated */
3116 
3117    bool ngg_changed = si_update_ngg(sctx);
3118    if (ngg_changed || enable_changed)
3119       si_shader_change_notify(sctx);
3120    if (enable_changed)
3121       sctx->last_tes_sh_base = -1; /* invalidate derived tess state */
3122    si_update_vs_viewport_state(sctx);
3123    si_update_streamout_state(sctx);
3124    si_update_clip_regs(sctx, old_hw_vs, old_hw_vs_variant, si_get_vs(sctx)->cso,
3125                        si_get_vs_state(sctx));
3126 }
3127 
si_bind_ps_shader(struct pipe_context * ctx,void * state)3128 static void si_bind_ps_shader(struct pipe_context *ctx, void *state)
3129 {
3130    struct si_context *sctx = (struct si_context *)ctx;
3131    struct si_shader_selector *old_sel = sctx->ps_shader.cso;
3132    struct si_shader_selector *sel = state;
3133 
3134    /* skip if supplied shader is one already in use */
3135    if (old_sel == sel)
3136       return;
3137 
3138    sctx->ps_shader.cso = sel;
3139    sctx->ps_shader.current = sel ? sel->first_variant : NULL;
3140 
3141    si_update_common_shader_state(sctx, sel, PIPE_SHADER_FRAGMENT);
3142    if (sel) {
3143       if (sctx->ia_multi_vgt_param_key.u.uses_tess)
3144          si_update_tess_uses_prim_id(sctx);
3145 
3146       if (!old_sel || old_sel->info.colors_written != sel->info.colors_written)
3147          si_mark_atom_dirty(sctx, &sctx->atoms.s.cb_render_state);
3148 
3149       if (sctx->screen->has_out_of_order_rast &&
3150           (!old_sel || old_sel->info.base.writes_memory != sel->info.base.writes_memory ||
3151            old_sel->info.base.fs.early_fragment_tests !=
3152               sel->info.base.fs.early_fragment_tests))
3153          si_mark_atom_dirty(sctx, &sctx->atoms.s.msaa_config);
3154    }
3155    si_update_ps_colorbuf0_slot(sctx);
3156 }
3157 
si_delete_shader(struct si_context * sctx,struct si_shader * shader)3158 static void si_delete_shader(struct si_context *sctx, struct si_shader *shader)
3159 {
3160    if (shader->is_optimized) {
3161       util_queue_drop_job(&sctx->screen->shader_compiler_queue_low_priority, &shader->ready);
3162    }
3163 
3164    util_queue_fence_destroy(&shader->ready);
3165 
3166    if (shader->pm4) {
3167       /* If destroyed shaders were not unbound, the next compiled
3168        * shader variant could get the same pointer address and so
3169        * binding it to the same shader stage would be considered
3170        * a no-op, causing random behavior.
3171        */
3172       switch (shader->selector->info.stage) {
3173       case MESA_SHADER_VERTEX:
3174          if (shader->key.as_ls) {
3175             assert(sctx->chip_class <= GFX8);
3176             si_pm4_delete_state(sctx, ls, shader->pm4);
3177          } else if (shader->key.as_es) {
3178             assert(sctx->chip_class <= GFX8);
3179             si_pm4_delete_state(sctx, es, shader->pm4);
3180          } else if (shader->key.as_ngg) {
3181             si_pm4_delete_state(sctx, gs, shader->pm4);
3182          } else {
3183             si_pm4_delete_state(sctx, vs, shader->pm4);
3184          }
3185          break;
3186       case MESA_SHADER_TESS_CTRL:
3187          si_pm4_delete_state(sctx, hs, shader->pm4);
3188          break;
3189       case MESA_SHADER_TESS_EVAL:
3190          if (shader->key.as_es) {
3191             assert(sctx->chip_class <= GFX8);
3192             si_pm4_delete_state(sctx, es, shader->pm4);
3193          } else if (shader->key.as_ngg) {
3194             si_pm4_delete_state(sctx, gs, shader->pm4);
3195          } else {
3196             si_pm4_delete_state(sctx, vs, shader->pm4);
3197          }
3198          break;
3199       case MESA_SHADER_GEOMETRY:
3200          if (shader->is_gs_copy_shader)
3201             si_pm4_delete_state(sctx, vs, shader->pm4);
3202          else
3203             si_pm4_delete_state(sctx, gs, shader->pm4);
3204          break;
3205       case MESA_SHADER_FRAGMENT:
3206          si_pm4_delete_state(sctx, ps, shader->pm4);
3207          break;
3208       default:;
3209       }
3210    }
3211 
3212    si_shader_selector_reference(sctx, &shader->previous_stage_sel, NULL);
3213    si_shader_destroy(shader);
3214    free(shader);
3215 }
3216 
si_destroy_shader_selector(struct pipe_context * ctx,void * cso)3217 static void si_destroy_shader_selector(struct pipe_context *ctx, void *cso)
3218 {
3219    struct si_context *sctx = (struct si_context *)ctx;
3220    struct si_shader_selector *sel = (struct si_shader_selector *)cso;
3221    struct si_shader *p = sel->first_variant, *c;
3222    struct si_shader_ctx_state *current_shader[SI_NUM_SHADERS] = {
3223       [MESA_SHADER_VERTEX] = &sctx->vs_shader,
3224       [MESA_SHADER_TESS_CTRL] = &sctx->tcs_shader,
3225       [MESA_SHADER_TESS_EVAL] = &sctx->tes_shader,
3226       [MESA_SHADER_GEOMETRY] = &sctx->gs_shader,
3227       [MESA_SHADER_FRAGMENT] = &sctx->ps_shader,
3228    };
3229 
3230    util_queue_drop_job(&sctx->screen->shader_compiler_queue, &sel->ready);
3231 
3232    if (current_shader[sel->info.stage]->cso == sel) {
3233       current_shader[sel->info.stage]->cso = NULL;
3234       current_shader[sel->info.stage]->current = NULL;
3235    }
3236 
3237    while (p) {
3238       c = p->next_variant;
3239       si_delete_shader(sctx, p);
3240       p = c;
3241    }
3242 
3243    if (sel->main_shader_part)
3244       si_delete_shader(sctx, sel->main_shader_part);
3245    if (sel->main_shader_part_ls)
3246       si_delete_shader(sctx, sel->main_shader_part_ls);
3247    if (sel->main_shader_part_es)
3248       si_delete_shader(sctx, sel->main_shader_part_es);
3249    if (sel->main_shader_part_ngg)
3250       si_delete_shader(sctx, sel->main_shader_part_ngg);
3251    if (sel->gs_copy_shader)
3252       si_delete_shader(sctx, sel->gs_copy_shader);
3253 
3254    util_queue_fence_destroy(&sel->ready);
3255    simple_mtx_destroy(&sel->mutex);
3256    ralloc_free(sel->nir);
3257    free(sel->nir_binary);
3258    free(sel);
3259 }
3260 
si_delete_shader_selector(struct pipe_context * ctx,void * state)3261 static void si_delete_shader_selector(struct pipe_context *ctx, void *state)
3262 {
3263    struct si_context *sctx = (struct si_context *)ctx;
3264    struct si_shader_selector *sel = (struct si_shader_selector *)state;
3265 
3266    si_shader_selector_reference(sctx, &sel, NULL);
3267 }
3268 
si_get_ps_input_cntl(struct si_context * sctx,struct si_shader * vs,unsigned semantic,enum glsl_interp_mode interpolate)3269 static unsigned si_get_ps_input_cntl(struct si_context *sctx, struct si_shader *vs,
3270                                      unsigned semantic, enum glsl_interp_mode interpolate)
3271 {
3272    struct si_shader_info *vsinfo = &vs->selector->info;
3273    unsigned offset, ps_input_cntl = 0;
3274 
3275    if (interpolate == INTERP_MODE_FLAT ||
3276        (interpolate == INTERP_MODE_COLOR && sctx->flatshade) ||
3277        semantic == VARYING_SLOT_PRIMITIVE_ID)
3278       ps_input_cntl |= S_028644_FLAT_SHADE(1);
3279 
3280    if (semantic == VARYING_SLOT_PNTC ||
3281        (semantic >= VARYING_SLOT_TEX0 && semantic <= VARYING_SLOT_TEX7 &&
3282         sctx->sprite_coord_enable & (1 << (semantic - VARYING_SLOT_TEX0)))) {
3283       ps_input_cntl |= S_028644_PT_SPRITE_TEX(1);
3284    }
3285 
3286    int vs_slot = vsinfo->output_semantic_to_slot[semantic];
3287    if (vs_slot >= 0) {
3288       offset = vs->info.vs_output_param_offset[vs_slot];
3289 
3290       if (offset <= AC_EXP_PARAM_OFFSET_31) {
3291          /* The input is loaded from parameter memory. */
3292          ps_input_cntl |= S_028644_OFFSET(offset);
3293       } else if (!G_028644_PT_SPRITE_TEX(ps_input_cntl)) {
3294          if (offset == AC_EXP_PARAM_UNDEFINED) {
3295             /* This can happen with depth-only rendering. */
3296             offset = 0;
3297          } else {
3298             /* The input is a DEFAULT_VAL constant. */
3299             assert(offset >= AC_EXP_PARAM_DEFAULT_VAL_0000 &&
3300                    offset <= AC_EXP_PARAM_DEFAULT_VAL_1111);
3301             offset -= AC_EXP_PARAM_DEFAULT_VAL_0000;
3302          }
3303 
3304          ps_input_cntl = S_028644_OFFSET(0x20) | S_028644_DEFAULT_VAL(offset);
3305       }
3306    } else {
3307       /* VS output not found. */
3308       if (semantic == VARYING_SLOT_PRIMITIVE_ID) {
3309          /* PrimID is written after the last output when HW VS is used. */
3310          ps_input_cntl |= S_028644_OFFSET(vs->info.vs_output_param_offset[vsinfo->num_outputs]);
3311       } else if (!G_028644_PT_SPRITE_TEX(ps_input_cntl)) {
3312          /* No corresponding output found, load defaults into input.
3313           * Don't set any other bits.
3314           * (FLAT_SHADE=1 completely changes behavior) */
3315          ps_input_cntl = S_028644_OFFSET(0x20);
3316          /* D3D 9 behaviour. GL is undefined */
3317          if (semantic == VARYING_SLOT_COL0)
3318             ps_input_cntl |= S_028644_DEFAULT_VAL(3);
3319       }
3320    }
3321 
3322    return ps_input_cntl;
3323 }
3324 
si_emit_spi_map(struct si_context * sctx)3325 static void si_emit_spi_map(struct si_context *sctx)
3326 {
3327    struct si_shader *ps = sctx->ps_shader.current;
3328    struct si_shader *vs = si_get_vs_state(sctx);
3329    struct si_shader_info *psinfo = ps ? &ps->selector->info : NULL;
3330    unsigned i, num_interp, num_written = 0;
3331    unsigned spi_ps_input_cntl[32];
3332 
3333    if (!ps || !ps->selector->info.num_inputs)
3334       return;
3335 
3336    num_interp = si_get_ps_num_interp(ps);
3337    assert(num_interp > 0);
3338 
3339    for (i = 0; i < psinfo->num_inputs; i++) {
3340       unsigned semantic = psinfo->input_semantic[i];
3341       unsigned interpolate = psinfo->input_interpolate[i];
3342 
3343       spi_ps_input_cntl[num_written++] = si_get_ps_input_cntl(sctx, vs, semantic, interpolate);
3344    }
3345 
3346    if (ps->key.part.ps.prolog.color_two_side) {
3347       for (i = 0; i < 2; i++) {
3348          if (!(psinfo->colors_read & (0xf << (i * 4))))
3349             continue;
3350 
3351          unsigned semantic = VARYING_SLOT_BFC0 + i;
3352          spi_ps_input_cntl[num_written++] = si_get_ps_input_cntl(sctx, vs, semantic,
3353                                                                  psinfo->color_interpolate[i]);
3354       }
3355    }
3356    assert(num_interp == num_written);
3357 
3358    /* R_028644_SPI_PS_INPUT_CNTL_0 */
3359    /* Dota 2: Only ~16% of SPI map updates set different values. */
3360    /* Talos: Only ~9% of SPI map updates set different values. */
3361    unsigned initial_cdw = sctx->gfx_cs->current.cdw;
3362    radeon_opt_set_context_regn(sctx, R_028644_SPI_PS_INPUT_CNTL_0, spi_ps_input_cntl,
3363                                sctx->tracked_regs.spi_ps_input_cntl, num_interp);
3364 
3365    if (initial_cdw != sctx->gfx_cs->current.cdw)
3366       sctx->context_roll = true;
3367 }
3368 
3369 /**
3370  * Writing CONFIG or UCONFIG VGT registers requires VGT_FLUSH before that.
3371  */
si_cs_preamble_add_vgt_flush(struct si_context * sctx)3372 static void si_cs_preamble_add_vgt_flush(struct si_context *sctx)
3373 {
3374    /* We shouldn't get here if registers are shadowed. */
3375    assert(!sctx->shadowed_regs);
3376 
3377    if (sctx->cs_preamble_has_vgt_flush)
3378       return;
3379 
3380    /* Done by Vulkan before VGT_FLUSH. */
3381    si_pm4_cmd_add(sctx->cs_preamble_state, PKT3(PKT3_EVENT_WRITE, 0, 0));
3382    si_pm4_cmd_add(sctx->cs_preamble_state, EVENT_TYPE(V_028A90_VS_PARTIAL_FLUSH) | EVENT_INDEX(4));
3383 
3384    /* VGT_FLUSH is required even if VGT is idle. It resets VGT pointers. */
3385    si_pm4_cmd_add(sctx->cs_preamble_state, PKT3(PKT3_EVENT_WRITE, 0, 0));
3386    si_pm4_cmd_add(sctx->cs_preamble_state, EVENT_TYPE(V_028A90_VGT_FLUSH) | EVENT_INDEX(0));
3387    sctx->cs_preamble_has_vgt_flush = true;
3388 }
3389 
3390 /**
3391  * Writing CONFIG or UCONFIG VGT registers requires VGT_FLUSH before that.
3392  */
si_emit_vgt_flush(struct radeon_cmdbuf * cs)3393 static void si_emit_vgt_flush(struct radeon_cmdbuf *cs)
3394 {
3395    /* This is required before VGT_FLUSH. */
3396    radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
3397    radeon_emit(cs, EVENT_TYPE(V_028A90_VS_PARTIAL_FLUSH) | EVENT_INDEX(4));
3398 
3399    /* VGT_FLUSH is required even if VGT is idle. It resets VGT pointers. */
3400    radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
3401    radeon_emit(cs, EVENT_TYPE(V_028A90_VGT_FLUSH) | EVENT_INDEX(0));
3402 }
3403 
3404 /* Initialize state related to ESGS / GSVS ring buffers */
si_update_gs_ring_buffers(struct si_context * sctx)3405 static bool si_update_gs_ring_buffers(struct si_context *sctx)
3406 {
3407    struct si_shader_selector *es =
3408       sctx->tes_shader.cso ? sctx->tes_shader.cso : sctx->vs_shader.cso;
3409    struct si_shader_selector *gs = sctx->gs_shader.cso;
3410    struct si_pm4_state *pm4;
3411 
3412    /* Chip constants. */
3413    unsigned num_se = sctx->screen->info.max_se;
3414    unsigned wave_size = 64;
3415    unsigned max_gs_waves = 32 * num_se; /* max 32 per SE on GCN */
3416    /* On GFX6-GFX7, the value comes from VGT_GS_VERTEX_REUSE = 16.
3417     * On GFX8+, the value comes from VGT_VERTEX_REUSE_BLOCK_CNTL = 30 (+2).
3418     */
3419    unsigned gs_vertex_reuse = (sctx->chip_class >= GFX8 ? 32 : 16) * num_se;
3420    unsigned alignment = 256 * num_se;
3421    /* The maximum size is 63.999 MB per SE. */
3422    unsigned max_size = ((unsigned)(63.999 * 1024 * 1024) & ~255) * num_se;
3423 
3424    /* Calculate the minimum size. */
3425    unsigned min_esgs_ring_size = align(es->esgs_itemsize * gs_vertex_reuse * wave_size, alignment);
3426 
3427    /* These are recommended sizes, not minimum sizes. */
3428    unsigned esgs_ring_size =
3429       max_gs_waves * 2 * wave_size * es->esgs_itemsize * gs->gs_input_verts_per_prim;
3430    unsigned gsvs_ring_size = max_gs_waves * 2 * wave_size * gs->max_gsvs_emit_size;
3431 
3432    min_esgs_ring_size = align(min_esgs_ring_size, alignment);
3433    esgs_ring_size = align(esgs_ring_size, alignment);
3434    gsvs_ring_size = align(gsvs_ring_size, alignment);
3435 
3436    esgs_ring_size = CLAMP(esgs_ring_size, min_esgs_ring_size, max_size);
3437    gsvs_ring_size = MIN2(gsvs_ring_size, max_size);
3438 
3439    /* Some rings don't have to be allocated if shaders don't use them.
3440     * (e.g. no varyings between ES and GS or GS and VS)
3441     *
3442     * GFX9 doesn't have the ESGS ring.
3443     */
3444    bool update_esgs = sctx->chip_class <= GFX8 && esgs_ring_size &&
3445                       (!sctx->esgs_ring || sctx->esgs_ring->width0 < esgs_ring_size);
3446    bool update_gsvs =
3447       gsvs_ring_size && (!sctx->gsvs_ring || sctx->gsvs_ring->width0 < gsvs_ring_size);
3448 
3449    if (!update_esgs && !update_gsvs)
3450       return true;
3451 
3452    if (update_esgs) {
3453       pipe_resource_reference(&sctx->esgs_ring, NULL);
3454       sctx->esgs_ring =
3455          pipe_aligned_buffer_create(sctx->b.screen,
3456                                     SI_RESOURCE_FLAG_UNMAPPABLE | SI_RESOURCE_FLAG_DRIVER_INTERNAL,
3457                                     PIPE_USAGE_DEFAULT,
3458                                     esgs_ring_size, sctx->screen->info.pte_fragment_size);
3459       if (!sctx->esgs_ring)
3460          return false;
3461    }
3462 
3463    if (update_gsvs) {
3464       pipe_resource_reference(&sctx->gsvs_ring, NULL);
3465       sctx->gsvs_ring =
3466          pipe_aligned_buffer_create(sctx->b.screen,
3467                                     SI_RESOURCE_FLAG_UNMAPPABLE | SI_RESOURCE_FLAG_DRIVER_INTERNAL,
3468                                     PIPE_USAGE_DEFAULT,
3469                                     gsvs_ring_size, sctx->screen->info.pte_fragment_size);
3470       if (!sctx->gsvs_ring)
3471          return false;
3472    }
3473 
3474    /* Set ring bindings. */
3475    if (sctx->esgs_ring) {
3476       assert(sctx->chip_class <= GFX8);
3477       si_set_ring_buffer(sctx, SI_ES_RING_ESGS, sctx->esgs_ring, 0, sctx->esgs_ring->width0, true,
3478                          true, 4, 64, 0);
3479       si_set_ring_buffer(sctx, SI_GS_RING_ESGS, sctx->esgs_ring, 0, sctx->esgs_ring->width0, false,
3480                          false, 0, 0, 0);
3481    }
3482    if (sctx->gsvs_ring) {
3483       si_set_ring_buffer(sctx, SI_RING_GSVS, sctx->gsvs_ring, 0, sctx->gsvs_ring->width0, false,
3484                          false, 0, 0, 0);
3485    }
3486 
3487    if (sctx->shadowed_regs) {
3488       /* These registers will be shadowed, so set them only once. */
3489       struct radeon_cmdbuf *cs = sctx->gfx_cs;
3490 
3491       assert(sctx->chip_class >= GFX7);
3492 
3493       si_emit_vgt_flush(cs);
3494 
3495       /* Set the GS registers. */
3496       if (sctx->esgs_ring) {
3497          assert(sctx->chip_class <= GFX8);
3498          radeon_set_uconfig_reg(cs, R_030900_VGT_ESGS_RING_SIZE,
3499                                 sctx->esgs_ring->width0 / 256);
3500       }
3501       if (sctx->gsvs_ring) {
3502          radeon_set_uconfig_reg(cs, R_030904_VGT_GSVS_RING_SIZE,
3503                                 sctx->gsvs_ring->width0 / 256);
3504       }
3505       return true;
3506    }
3507 
3508    /* The codepath without register shadowing. */
3509    /* Create the "cs_preamble_gs_rings" state. */
3510    pm4 = CALLOC_STRUCT(si_pm4_state);
3511    if (!pm4)
3512       return false;
3513 
3514    if (sctx->chip_class >= GFX7) {
3515       if (sctx->esgs_ring) {
3516          assert(sctx->chip_class <= GFX8);
3517          si_pm4_set_reg(pm4, R_030900_VGT_ESGS_RING_SIZE, sctx->esgs_ring->width0 / 256);
3518       }
3519       if (sctx->gsvs_ring)
3520          si_pm4_set_reg(pm4, R_030904_VGT_GSVS_RING_SIZE, sctx->gsvs_ring->width0 / 256);
3521    } else {
3522       if (sctx->esgs_ring)
3523          si_pm4_set_reg(pm4, R_0088C8_VGT_ESGS_RING_SIZE, sctx->esgs_ring->width0 / 256);
3524       if (sctx->gsvs_ring)
3525          si_pm4_set_reg(pm4, R_0088CC_VGT_GSVS_RING_SIZE, sctx->gsvs_ring->width0 / 256);
3526    }
3527 
3528    /* Set the state. */
3529    if (sctx->cs_preamble_gs_rings)
3530       si_pm4_free_state(sctx, sctx->cs_preamble_gs_rings, ~0);
3531    sctx->cs_preamble_gs_rings = pm4;
3532 
3533    si_cs_preamble_add_vgt_flush(sctx);
3534 
3535    /* Flush the context to re-emit both cs_preamble states. */
3536    sctx->initial_gfx_cs_size = 0; /* force flush */
3537    si_flush_gfx_cs(sctx, RADEON_FLUSH_ASYNC_START_NEXT_GFX_IB_NOW, NULL);
3538 
3539    return true;
3540 }
3541 
si_shader_lock(struct si_shader * shader)3542 static void si_shader_lock(struct si_shader *shader)
3543 {
3544    simple_mtx_lock(&shader->selector->mutex);
3545    if (shader->previous_stage_sel) {
3546       assert(shader->previous_stage_sel != shader->selector);
3547       simple_mtx_lock(&shader->previous_stage_sel->mutex);
3548    }
3549 }
3550 
si_shader_unlock(struct si_shader * shader)3551 static void si_shader_unlock(struct si_shader *shader)
3552 {
3553    if (shader->previous_stage_sel)
3554       simple_mtx_unlock(&shader->previous_stage_sel->mutex);
3555    simple_mtx_unlock(&shader->selector->mutex);
3556 }
3557 
3558 /**
3559  * @returns 1 if \p sel has been updated to use a new scratch buffer
3560  *          0 if not
3561  *          < 0 if there was a failure
3562  */
si_update_scratch_buffer(struct si_context * sctx,struct si_shader * shader)3563 static int si_update_scratch_buffer(struct si_context *sctx, struct si_shader *shader)
3564 {
3565    uint64_t scratch_va = sctx->scratch_buffer->gpu_address;
3566 
3567    if (!shader)
3568       return 0;
3569 
3570    /* This shader doesn't need a scratch buffer */
3571    if (shader->config.scratch_bytes_per_wave == 0)
3572       return 0;
3573 
3574    /* Prevent race conditions when updating:
3575     * - si_shader::scratch_bo
3576     * - si_shader::binary::code
3577     * - si_shader::previous_stage::binary::code.
3578     */
3579    si_shader_lock(shader);
3580 
3581    /* This shader is already configured to use the current
3582     * scratch buffer. */
3583    if (shader->scratch_bo == sctx->scratch_buffer) {
3584       si_shader_unlock(shader);
3585       return 0;
3586    }
3587 
3588    assert(sctx->scratch_buffer);
3589 
3590    /* Replace the shader bo with a new bo that has the relocs applied. */
3591    if (!si_shader_binary_upload(sctx->screen, shader, scratch_va)) {
3592       si_shader_unlock(shader);
3593       return -1;
3594    }
3595 
3596    /* Update the shader state to use the new shader bo. */
3597    si_shader_init_pm4_state(sctx->screen, shader);
3598 
3599    si_resource_reference(&shader->scratch_bo, sctx->scratch_buffer);
3600 
3601    si_shader_unlock(shader);
3602    return 1;
3603 }
3604 
si_get_scratch_buffer_bytes_per_wave(struct si_shader * shader)3605 static unsigned si_get_scratch_buffer_bytes_per_wave(struct si_shader *shader)
3606 {
3607    return shader ? shader->config.scratch_bytes_per_wave : 0;
3608 }
3609 
si_get_tcs_current(struct si_context * sctx)3610 static struct si_shader *si_get_tcs_current(struct si_context *sctx)
3611 {
3612    if (!sctx->tes_shader.cso)
3613       return NULL; /* tessellation disabled */
3614 
3615    return sctx->tcs_shader.cso ? sctx->tcs_shader.current : sctx->fixed_func_tcs_shader.current;
3616 }
3617 
si_update_scratch_relocs(struct si_context * sctx)3618 static bool si_update_scratch_relocs(struct si_context *sctx)
3619 {
3620    struct si_shader *tcs = si_get_tcs_current(sctx);
3621    int r;
3622 
3623    /* Update the shaders, so that they are using the latest scratch.
3624     * The scratch buffer may have been changed since these shaders were
3625     * last used, so we still need to try to update them, even if they
3626     * require scratch buffers smaller than the current size.
3627     */
3628    r = si_update_scratch_buffer(sctx, sctx->ps_shader.current);
3629    if (r < 0)
3630       return false;
3631    if (r == 1)
3632       si_pm4_bind_state(sctx, ps, sctx->ps_shader.current->pm4);
3633 
3634    r = si_update_scratch_buffer(sctx, sctx->gs_shader.current);
3635    if (r < 0)
3636       return false;
3637    if (r == 1)
3638       si_pm4_bind_state(sctx, gs, sctx->gs_shader.current->pm4);
3639 
3640    r = si_update_scratch_buffer(sctx, tcs);
3641    if (r < 0)
3642       return false;
3643    if (r == 1)
3644       si_pm4_bind_state(sctx, hs, tcs->pm4);
3645 
3646    /* VS can be bound as LS, ES, or VS. */
3647    r = si_update_scratch_buffer(sctx, sctx->vs_shader.current);
3648    if (r < 0)
3649       return false;
3650    if (r == 1) {
3651       if (sctx->vs_shader.current->key.as_ls)
3652          si_pm4_bind_state(sctx, ls, sctx->vs_shader.current->pm4);
3653       else if (sctx->vs_shader.current->key.as_es)
3654          si_pm4_bind_state(sctx, es, sctx->vs_shader.current->pm4);
3655       else if (sctx->vs_shader.current->key.as_ngg)
3656          si_pm4_bind_state(sctx, gs, sctx->vs_shader.current->pm4);
3657       else
3658          si_pm4_bind_state(sctx, vs, sctx->vs_shader.current->pm4);
3659    }
3660 
3661    /* TES can be bound as ES or VS. */
3662    r = si_update_scratch_buffer(sctx, sctx->tes_shader.current);
3663    if (r < 0)
3664       return false;
3665    if (r == 1) {
3666       if (sctx->tes_shader.current->key.as_es)
3667          si_pm4_bind_state(sctx, es, sctx->tes_shader.current->pm4);
3668       else if (sctx->tes_shader.current->key.as_ngg)
3669          si_pm4_bind_state(sctx, gs, sctx->tes_shader.current->pm4);
3670       else
3671          si_pm4_bind_state(sctx, vs, sctx->tes_shader.current->pm4);
3672    }
3673 
3674    return true;
3675 }
3676 
si_update_spi_tmpring_size(struct si_context * sctx)3677 static bool si_update_spi_tmpring_size(struct si_context *sctx)
3678 {
3679    /* SPI_TMPRING_SIZE.WAVESIZE must be constant for each scratch buffer.
3680     * There are 2 cases to handle:
3681     *
3682     * - If the current needed size is less than the maximum seen size,
3683     *   use the maximum seen size, so that WAVESIZE remains the same.
3684     *
3685     * - If the current needed size is greater than the maximum seen size,
3686     *   the scratch buffer is reallocated, so we can increase WAVESIZE.
3687     *
3688     * Shaders that set SCRATCH_EN=0 don't allocate scratch space.
3689     * Otherwise, the number of waves that can use scratch is
3690     * SPI_TMPRING_SIZE.WAVES.
3691     */
3692    unsigned bytes = 0;
3693 
3694    bytes = MAX2(bytes, si_get_scratch_buffer_bytes_per_wave(sctx->ps_shader.current));
3695    bytes = MAX2(bytes, si_get_scratch_buffer_bytes_per_wave(sctx->gs_shader.current));
3696    bytes = MAX2(bytes, si_get_scratch_buffer_bytes_per_wave(sctx->vs_shader.current));
3697 
3698    if (sctx->tes_shader.cso) {
3699       bytes = MAX2(bytes, si_get_scratch_buffer_bytes_per_wave(sctx->tes_shader.current));
3700       bytes = MAX2(bytes, si_get_scratch_buffer_bytes_per_wave(si_get_tcs_current(sctx)));
3701    }
3702 
3703    sctx->max_seen_scratch_bytes_per_wave = MAX2(sctx->max_seen_scratch_bytes_per_wave, bytes);
3704 
3705    unsigned scratch_needed_size = sctx->max_seen_scratch_bytes_per_wave * sctx->scratch_waves;
3706    unsigned spi_tmpring_size;
3707 
3708    if (scratch_needed_size > 0) {
3709       if (!sctx->scratch_buffer || scratch_needed_size > sctx->scratch_buffer->b.b.width0) {
3710          /* Create a bigger scratch buffer */
3711          si_resource_reference(&sctx->scratch_buffer, NULL);
3712 
3713          sctx->scratch_buffer = si_aligned_buffer_create(
3714             &sctx->screen->b,
3715             SI_RESOURCE_FLAG_UNMAPPABLE | SI_RESOURCE_FLAG_DRIVER_INTERNAL,
3716             PIPE_USAGE_DEFAULT, scratch_needed_size,
3717             sctx->screen->info.pte_fragment_size);
3718          if (!sctx->scratch_buffer)
3719             return false;
3720 
3721          si_mark_atom_dirty(sctx, &sctx->atoms.s.scratch_state);
3722          si_context_add_resource_size(sctx, &sctx->scratch_buffer->b.b);
3723       }
3724 
3725       if (!si_update_scratch_relocs(sctx))
3726          return false;
3727    }
3728 
3729    /* The LLVM shader backend should be reporting aligned scratch_sizes. */
3730    assert((scratch_needed_size & ~0x3FF) == scratch_needed_size &&
3731           "scratch size should already be aligned correctly.");
3732 
3733    spi_tmpring_size = S_0286E8_WAVES(sctx->scratch_waves) |
3734                       S_0286E8_WAVESIZE(sctx->max_seen_scratch_bytes_per_wave >> 10);
3735    if (spi_tmpring_size != sctx->spi_tmpring_size) {
3736       sctx->spi_tmpring_size = spi_tmpring_size;
3737       si_mark_atom_dirty(sctx, &sctx->atoms.s.scratch_state);
3738    }
3739    return true;
3740 }
3741 
si_init_tess_factor_ring(struct si_context * sctx)3742 static void si_init_tess_factor_ring(struct si_context *sctx)
3743 {
3744    assert(!sctx->tess_rings);
3745    assert(((sctx->screen->tess_factor_ring_size / 4) & C_030938_SIZE) == 0);
3746 
3747    /* The address must be aligned to 2^19, because the shader only
3748     * receives the high 13 bits.
3749     */
3750    sctx->tess_rings = pipe_aligned_buffer_create(
3751       sctx->b.screen, SI_RESOURCE_FLAG_32BIT | SI_RESOURCE_FLAG_DRIVER_INTERNAL, PIPE_USAGE_DEFAULT,
3752       sctx->screen->tess_offchip_ring_size + sctx->screen->tess_factor_ring_size, 1 << 19);
3753    if (!sctx->tess_rings)
3754       return;
3755 
3756    if (sctx->screen->info.has_tmz_support) {
3757       sctx->tess_rings_tmz = pipe_aligned_buffer_create(
3758          sctx->b.screen,
3759          PIPE_RESOURCE_FLAG_ENCRYPTED | SI_RESOURCE_FLAG_32BIT | SI_RESOURCE_FLAG_DRIVER_INTERNAL,
3760          PIPE_USAGE_DEFAULT,
3761          sctx->screen->tess_offchip_ring_size + sctx->screen->tess_factor_ring_size, 1 << 19);
3762    }
3763 
3764    uint64_t factor_va =
3765       si_resource(sctx->tess_rings)->gpu_address + sctx->screen->tess_offchip_ring_size;
3766 
3767    if (sctx->shadowed_regs) {
3768       /* These registers will be shadowed, so set them only once. */
3769       /* TODO: tmz + shadowed_regs support */
3770       struct radeon_cmdbuf *cs = sctx->gfx_cs;
3771 
3772       assert(sctx->chip_class >= GFX7);
3773 
3774       radeon_add_to_buffer_list(sctx, sctx->gfx_cs, si_resource(sctx->tess_rings),
3775                                 RADEON_USAGE_READWRITE, RADEON_PRIO_SHADER_RINGS);
3776       si_emit_vgt_flush(cs);
3777 
3778       /* Set tessellation registers. */
3779       radeon_set_uconfig_reg(cs, R_030938_VGT_TF_RING_SIZE,
3780                              S_030938_SIZE(sctx->screen->tess_factor_ring_size / 4));
3781       radeon_set_uconfig_reg(cs, R_030940_VGT_TF_MEMORY_BASE, factor_va >> 8);
3782       if (sctx->chip_class >= GFX10) {
3783          radeon_set_uconfig_reg(cs, R_030984_VGT_TF_MEMORY_BASE_HI_UMD,
3784                                 S_030984_BASE_HI(factor_va >> 40));
3785       } else if (sctx->chip_class == GFX9) {
3786          radeon_set_uconfig_reg(cs, R_030944_VGT_TF_MEMORY_BASE_HI,
3787                                 S_030944_BASE_HI(factor_va >> 40));
3788       }
3789       radeon_set_uconfig_reg(cs, R_03093C_VGT_HS_OFFCHIP_PARAM,
3790                              sctx->screen->vgt_hs_offchip_param);
3791       return;
3792    }
3793 
3794    /* The codepath without register shadowing. */
3795    si_cs_preamble_add_vgt_flush(sctx);
3796 
3797    /* Append these registers to the init config state. */
3798    if (sctx->chip_class >= GFX7) {
3799       si_pm4_set_reg(sctx->cs_preamble_state, R_030938_VGT_TF_RING_SIZE,
3800                      S_030938_SIZE(sctx->screen->tess_factor_ring_size / 4));
3801       si_pm4_set_reg(sctx->cs_preamble_state, R_030940_VGT_TF_MEMORY_BASE, factor_va >> 8);
3802       if (sctx->chip_class >= GFX10)
3803          si_pm4_set_reg(sctx->cs_preamble_state, R_030984_VGT_TF_MEMORY_BASE_HI_UMD,
3804                         S_030984_BASE_HI(factor_va >> 40));
3805       else if (sctx->chip_class == GFX9)
3806          si_pm4_set_reg(sctx->cs_preamble_state, R_030944_VGT_TF_MEMORY_BASE_HI,
3807                         S_030944_BASE_HI(factor_va >> 40));
3808       si_pm4_set_reg(sctx->cs_preamble_state, R_03093C_VGT_HS_OFFCHIP_PARAM,
3809                      sctx->screen->vgt_hs_offchip_param);
3810    } else {
3811       struct si_pm4_state *pm4 = CALLOC_STRUCT(si_pm4_state);
3812 
3813       si_pm4_set_reg(pm4, R_008988_VGT_TF_RING_SIZE,
3814                      S_008988_SIZE(sctx->screen->tess_factor_ring_size / 4));
3815       si_pm4_set_reg(pm4, R_0089B8_VGT_TF_MEMORY_BASE, factor_va >> 8);
3816       si_pm4_set_reg(pm4, R_0089B0_VGT_HS_OFFCHIP_PARAM,
3817                      sctx->screen->vgt_hs_offchip_param);
3818       sctx->cs_preamble_tess_rings = pm4;
3819 
3820       if (sctx->screen->info.has_tmz_support) {
3821          pm4 = CALLOC_STRUCT(si_pm4_state);
3822          uint64_t factor_va_tmz =
3823             si_resource(sctx->tess_rings_tmz)->gpu_address + sctx->screen->tess_offchip_ring_size;
3824          si_pm4_set_reg(pm4, R_008988_VGT_TF_RING_SIZE,
3825                      S_008988_SIZE(sctx->screen->tess_factor_ring_size / 4));
3826          si_pm4_set_reg(pm4, R_0089B8_VGT_TF_MEMORY_BASE, factor_va_tmz >> 8);
3827          si_pm4_set_reg(pm4, R_0089B0_VGT_HS_OFFCHIP_PARAM,
3828                         sctx->screen->vgt_hs_offchip_param);
3829          sctx->cs_preamble_tess_rings_tmz = pm4;
3830       }
3831    }
3832 
3833    /* Flush the context to re-emit the cs_preamble state.
3834     * This is done only once in a lifetime of a context.
3835     */
3836    sctx->initial_gfx_cs_size = 0; /* force flush */
3837    si_flush_gfx_cs(sctx, RADEON_FLUSH_ASYNC_START_NEXT_GFX_IB_NOW, NULL);
3838 }
3839 
si_build_vgt_shader_config(struct si_screen * screen,union si_vgt_stages_key key)3840 static struct si_pm4_state *si_build_vgt_shader_config(struct si_screen *screen,
3841                                                        union si_vgt_stages_key key)
3842 {
3843    struct si_pm4_state *pm4 = CALLOC_STRUCT(si_pm4_state);
3844    uint32_t stages = 0;
3845 
3846    if (key.u.tess) {
3847       stages |= S_028B54_LS_EN(V_028B54_LS_STAGE_ON) | S_028B54_HS_EN(1) | S_028B54_DYNAMIC_HS(1);
3848 
3849       if (key.u.gs)
3850          stages |= S_028B54_ES_EN(V_028B54_ES_STAGE_DS) | S_028B54_GS_EN(1);
3851       else if (key.u.ngg)
3852          stages |= S_028B54_ES_EN(V_028B54_ES_STAGE_DS);
3853       else
3854          stages |= S_028B54_VS_EN(V_028B54_VS_STAGE_DS);
3855    } else if (key.u.gs) {
3856       stages |= S_028B54_ES_EN(V_028B54_ES_STAGE_REAL) | S_028B54_GS_EN(1);
3857    } else if (key.u.ngg) {
3858       stages |= S_028B54_ES_EN(V_028B54_ES_STAGE_REAL);
3859    }
3860 
3861    if (key.u.ngg) {
3862       stages |= S_028B54_PRIMGEN_EN(1) | S_028B54_GS_FAST_LAUNCH(key.u.ngg_gs_fast_launch) |
3863                 S_028B54_NGG_WAVE_ID_EN(key.u.streamout) |
3864                 S_028B54_PRIMGEN_PASSTHRU_EN(key.u.ngg_passthrough);
3865    } else if (key.u.gs)
3866       stages |= S_028B54_VS_EN(V_028B54_VS_STAGE_COPY_SHADER);
3867 
3868    if (screen->info.chip_class >= GFX9)
3869       stages |= S_028B54_MAX_PRIMGRP_IN_WAVE(2);
3870 
3871    if (screen->info.chip_class >= GFX10 &&
3872        /* GS fast launch hangs with Wave64, so always use Wave32. */
3873        (screen->ge_wave_size == 32 || (key.u.ngg && key.u.ngg_gs_fast_launch))) {
3874       stages |= S_028B54_HS_W32_EN(1) |
3875                 S_028B54_GS_W32_EN(key.u.ngg) | /* legacy GS only supports Wave64 */
3876                 S_028B54_VS_W32_EN(1);
3877    }
3878 
3879    si_pm4_set_reg(pm4, R_028B54_VGT_SHADER_STAGES_EN, stages);
3880    return pm4;
3881 }
3882 
si_update_vgt_shader_config(struct si_context * sctx,union si_vgt_stages_key key)3883 static void si_update_vgt_shader_config(struct si_context *sctx, union si_vgt_stages_key key)
3884 {
3885    struct si_pm4_state **pm4 = &sctx->vgt_shader_config[key.index];
3886 
3887    if (unlikely(!*pm4))
3888       *pm4 = si_build_vgt_shader_config(sctx->screen, key);
3889    si_pm4_bind_state(sctx, vgt_shader_config, *pm4);
3890 }
3891 
si_update_shaders(struct si_context * sctx)3892 bool si_update_shaders(struct si_context *sctx)
3893 {
3894    struct pipe_context *ctx = (struct pipe_context *)sctx;
3895    struct si_compiler_ctx_state compiler_state;
3896    struct si_state_rasterizer *rs = sctx->queued.named.rasterizer;
3897    struct si_shader *old_vs = si_get_vs_state(sctx);
3898    unsigned old_kill_clip_distances = old_vs ? old_vs->key.opt.kill_clip_distances : 0;
3899    struct si_shader *old_ps = sctx->ps_shader.current;
3900    union si_vgt_stages_key key;
3901    unsigned old_spi_shader_col_format =
3902       old_ps ? old_ps->key.part.ps.epilog.spi_shader_col_format : 0;
3903    int r;
3904 
3905    if (!sctx->compiler.passes)
3906       si_init_compiler(sctx->screen, &sctx->compiler);
3907 
3908    compiler_state.compiler = &sctx->compiler;
3909    compiler_state.debug = sctx->debug;
3910    compiler_state.is_debug_context = sctx->is_debug;
3911 
3912    key.index = 0;
3913 
3914    if (sctx->tes_shader.cso)
3915       key.u.tess = 1;
3916    if (sctx->gs_shader.cso)
3917       key.u.gs = 1;
3918 
3919    if (sctx->ngg) {
3920       key.u.ngg = 1;
3921       key.u.streamout = !!si_get_vs(sctx)->cso->so.num_outputs;
3922    }
3923 
3924    /* Update TCS and TES. */
3925    if (sctx->tes_shader.cso) {
3926       if (!sctx->tess_rings) {
3927          si_init_tess_factor_ring(sctx);
3928          if (!sctx->tess_rings)
3929             return false;
3930       }
3931 
3932       if (sctx->tcs_shader.cso) {
3933          r = si_shader_select(ctx, &sctx->tcs_shader, key, &compiler_state);
3934          if (r)
3935             return false;
3936          si_pm4_bind_state(sctx, hs, sctx->tcs_shader.current->pm4);
3937       } else {
3938          if (!sctx->fixed_func_tcs_shader.cso) {
3939             sctx->fixed_func_tcs_shader.cso = si_create_fixed_func_tcs(sctx);
3940             if (!sctx->fixed_func_tcs_shader.cso)
3941                return false;
3942          }
3943 
3944          r = si_shader_select(ctx, &sctx->fixed_func_tcs_shader, key, &compiler_state);
3945          if (r)
3946             return false;
3947          si_pm4_bind_state(sctx, hs, sctx->fixed_func_tcs_shader.current->pm4);
3948       }
3949 
3950       if (!sctx->gs_shader.cso || sctx->chip_class <= GFX8) {
3951          r = si_shader_select(ctx, &sctx->tes_shader, key, &compiler_state);
3952          if (r)
3953             return false;
3954 
3955          if (sctx->gs_shader.cso) {
3956             /* TES as ES */
3957             assert(sctx->chip_class <= GFX8);
3958             si_pm4_bind_state(sctx, es, sctx->tes_shader.current->pm4);
3959          } else if (key.u.ngg) {
3960             si_pm4_bind_state(sctx, gs, sctx->tes_shader.current->pm4);
3961          } else {
3962             si_pm4_bind_state(sctx, vs, sctx->tes_shader.current->pm4);
3963          }
3964       }
3965    } else {
3966       if (sctx->chip_class <= GFX8)
3967          si_pm4_bind_state(sctx, ls, NULL);
3968       si_pm4_bind_state(sctx, hs, NULL);
3969    }
3970 
3971    /* Update GS. */
3972    if (sctx->gs_shader.cso) {
3973       r = si_shader_select(ctx, &sctx->gs_shader, key, &compiler_state);
3974       if (r)
3975          return false;
3976       si_pm4_bind_state(sctx, gs, sctx->gs_shader.current->pm4);
3977       if (!key.u.ngg) {
3978          si_pm4_bind_state(sctx, vs, sctx->gs_shader.cso->gs_copy_shader->pm4);
3979 
3980          if (!si_update_gs_ring_buffers(sctx))
3981             return false;
3982       } else {
3983          si_pm4_bind_state(sctx, vs, NULL);
3984       }
3985    } else {
3986       if (!key.u.ngg) {
3987          si_pm4_bind_state(sctx, gs, NULL);
3988          if (sctx->chip_class <= GFX8)
3989             si_pm4_bind_state(sctx, es, NULL);
3990       }
3991    }
3992 
3993    /* Update VS. */
3994    if ((!key.u.tess && !key.u.gs) || sctx->chip_class <= GFX8) {
3995       r = si_shader_select(ctx, &sctx->vs_shader, key, &compiler_state);
3996       if (r)
3997          return false;
3998 
3999       if (!key.u.tess && !key.u.gs) {
4000          if (key.u.ngg) {
4001             si_pm4_bind_state(sctx, gs, sctx->vs_shader.current->pm4);
4002             si_pm4_bind_state(sctx, vs, NULL);
4003          } else {
4004             si_pm4_bind_state(sctx, vs, sctx->vs_shader.current->pm4);
4005          }
4006       } else if (sctx->tes_shader.cso) {
4007          si_pm4_bind_state(sctx, ls, sctx->vs_shader.current->pm4);
4008       } else {
4009          assert(sctx->gs_shader.cso);
4010          si_pm4_bind_state(sctx, es, sctx->vs_shader.current->pm4);
4011       }
4012    }
4013 
4014    /* This must be done after the shader variant is selected. */
4015    if (sctx->ngg) {
4016       struct si_shader *vs = si_get_vs(sctx)->current;
4017 
4018       key.u.ngg_passthrough = gfx10_is_ngg_passthrough(vs);
4019       key.u.ngg_gs_fast_launch = !!(vs->key.opt.ngg_culling & SI_NGG_CULL_GS_FAST_LAUNCH_ALL);
4020    }
4021 
4022    si_update_vgt_shader_config(sctx, key);
4023 
4024    if (old_kill_clip_distances != si_get_vs_state(sctx)->key.opt.kill_clip_distances)
4025       si_mark_atom_dirty(sctx, &sctx->atoms.s.clip_regs);
4026 
4027    if (sctx->ps_shader.cso) {
4028       unsigned db_shader_control;
4029 
4030       r = si_shader_select(ctx, &sctx->ps_shader, key, &compiler_state);
4031       if (r)
4032          return false;
4033       si_pm4_bind_state(sctx, ps, sctx->ps_shader.current->pm4);
4034 
4035       db_shader_control = sctx->ps_shader.cso->db_shader_control |
4036                           S_02880C_KILL_ENABLE(si_get_alpha_test_func(sctx) != PIPE_FUNC_ALWAYS);
4037 
4038       if (si_pm4_state_changed(sctx, ps) || si_pm4_state_changed(sctx, vs) ||
4039           (key.u.ngg && si_pm4_state_changed(sctx, gs)) ||
4040           sctx->sprite_coord_enable != rs->sprite_coord_enable ||
4041           sctx->flatshade != rs->flatshade) {
4042          sctx->sprite_coord_enable = rs->sprite_coord_enable;
4043          sctx->flatshade = rs->flatshade;
4044          si_mark_atom_dirty(sctx, &sctx->atoms.s.spi_map);
4045       }
4046 
4047       if (sctx->screen->info.rbplus_allowed && si_pm4_state_changed(sctx, ps) &&
4048           (!old_ps || old_spi_shader_col_format !=
4049                          sctx->ps_shader.current->key.part.ps.epilog.spi_shader_col_format))
4050          si_mark_atom_dirty(sctx, &sctx->atoms.s.cb_render_state);
4051 
4052       if (sctx->ps_db_shader_control != db_shader_control) {
4053          sctx->ps_db_shader_control = db_shader_control;
4054          si_mark_atom_dirty(sctx, &sctx->atoms.s.db_render_state);
4055          if (sctx->screen->dpbb_allowed)
4056             si_mark_atom_dirty(sctx, &sctx->atoms.s.dpbb_state);
4057       }
4058 
4059       if (sctx->smoothing_enabled !=
4060           sctx->ps_shader.current->key.part.ps.epilog.poly_line_smoothing) {
4061          sctx->smoothing_enabled = sctx->ps_shader.current->key.part.ps.epilog.poly_line_smoothing;
4062          si_mark_atom_dirty(sctx, &sctx->atoms.s.msaa_config);
4063 
4064          /* NGG cull state uses smoothing_enabled. */
4065          if (sctx->screen->use_ngg_culling)
4066             si_mark_atom_dirty(sctx, &sctx->atoms.s.ngg_cull_state);
4067 
4068          if (sctx->chip_class == GFX6)
4069             si_mark_atom_dirty(sctx, &sctx->atoms.s.db_render_state);
4070 
4071          if (sctx->framebuffer.nr_samples <= 1)
4072             si_mark_atom_dirty(sctx, &sctx->atoms.s.msaa_sample_locs);
4073       }
4074    }
4075 
4076    if (si_pm4_state_enabled_and_changed(sctx, ls) || si_pm4_state_enabled_and_changed(sctx, hs) ||
4077        si_pm4_state_enabled_and_changed(sctx, es) || si_pm4_state_enabled_and_changed(sctx, gs) ||
4078        si_pm4_state_enabled_and_changed(sctx, vs) || si_pm4_state_enabled_and_changed(sctx, ps)) {
4079       if (!si_update_spi_tmpring_size(sctx))
4080          return false;
4081    }
4082 
4083    if (sctx->chip_class >= GFX7) {
4084       if (si_pm4_state_enabled_and_changed(sctx, ls))
4085          sctx->prefetch_L2_mask |= SI_PREFETCH_LS;
4086       else if (!sctx->queued.named.ls)
4087          sctx->prefetch_L2_mask &= ~SI_PREFETCH_LS;
4088 
4089       if (si_pm4_state_enabled_and_changed(sctx, hs))
4090          sctx->prefetch_L2_mask |= SI_PREFETCH_HS;
4091       else if (!sctx->queued.named.hs)
4092          sctx->prefetch_L2_mask &= ~SI_PREFETCH_HS;
4093 
4094       if (si_pm4_state_enabled_and_changed(sctx, es))
4095          sctx->prefetch_L2_mask |= SI_PREFETCH_ES;
4096       else if (!sctx->queued.named.es)
4097          sctx->prefetch_L2_mask &= ~SI_PREFETCH_ES;
4098 
4099       if (si_pm4_state_enabled_and_changed(sctx, gs))
4100          sctx->prefetch_L2_mask |= SI_PREFETCH_GS;
4101       else if (!sctx->queued.named.gs)
4102          sctx->prefetch_L2_mask &= ~SI_PREFETCH_GS;
4103 
4104       if (si_pm4_state_enabled_and_changed(sctx, vs))
4105          sctx->prefetch_L2_mask |= SI_PREFETCH_VS;
4106       else if (!sctx->queued.named.vs)
4107          sctx->prefetch_L2_mask &= ~SI_PREFETCH_VS;
4108 
4109       if (si_pm4_state_enabled_and_changed(sctx, ps))
4110          sctx->prefetch_L2_mask |= SI_PREFETCH_PS;
4111       else if (!sctx->queued.named.ps)
4112          sctx->prefetch_L2_mask &= ~SI_PREFETCH_PS;
4113    }
4114 
4115    sctx->do_update_shaders = false;
4116    return true;
4117 }
4118 
si_emit_scratch_state(struct si_context * sctx)4119 static void si_emit_scratch_state(struct si_context *sctx)
4120 {
4121    struct radeon_cmdbuf *cs = sctx->gfx_cs;
4122 
4123    radeon_set_context_reg(cs, R_0286E8_SPI_TMPRING_SIZE, sctx->spi_tmpring_size);
4124 
4125    if (sctx->scratch_buffer) {
4126       radeon_add_to_buffer_list(sctx, sctx->gfx_cs, sctx->scratch_buffer, RADEON_USAGE_READWRITE,
4127                                 RADEON_PRIO_SCRATCH_BUFFER);
4128    }
4129 }
4130 
si_init_screen_live_shader_cache(struct si_screen * sscreen)4131 void si_init_screen_live_shader_cache(struct si_screen *sscreen)
4132 {
4133    util_live_shader_cache_init(&sscreen->live_shader_cache, si_create_shader_selector,
4134                                si_destroy_shader_selector);
4135 }
4136 
si_init_shader_functions(struct si_context * sctx)4137 void si_init_shader_functions(struct si_context *sctx)
4138 {
4139    sctx->atoms.s.spi_map.emit = si_emit_spi_map;
4140    sctx->atoms.s.scratch_state.emit = si_emit_scratch_state;
4141 
4142    sctx->b.create_vs_state = si_create_shader;
4143    sctx->b.create_tcs_state = si_create_shader;
4144    sctx->b.create_tes_state = si_create_shader;
4145    sctx->b.create_gs_state = si_create_shader;
4146    sctx->b.create_fs_state = si_create_shader;
4147 
4148    sctx->b.bind_vs_state = si_bind_vs_shader;
4149    sctx->b.bind_tcs_state = si_bind_tcs_shader;
4150    sctx->b.bind_tes_state = si_bind_tes_shader;
4151    sctx->b.bind_gs_state = si_bind_gs_shader;
4152    sctx->b.bind_fs_state = si_bind_ps_shader;
4153 
4154    sctx->b.delete_vs_state = si_delete_shader_selector;
4155    sctx->b.delete_tcs_state = si_delete_shader_selector;
4156    sctx->b.delete_tes_state = si_delete_shader_selector;
4157    sctx->b.delete_gs_state = si_delete_shader_selector;
4158    sctx->b.delete_fs_state = si_delete_shader_selector;
4159 }
4160