• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2012 Advanced Micro Devices, Inc.
3  *
4  * SPDX-License-Identifier: MIT
5  */
6 
7 #include "si_build_pm4.h"
8 
9 #include "util/hash_table.h"
10 #define XXH_INLINE_ALL
11 #include "util/xxhash.h"
12 #include "util/u_cpu_detect.h"
13 #include "util/u_index_modify.h"
14 #include "util/u_prim.h"
15 #include "util/u_upload_mgr.h"
16 #include "ac_rtld.h"
17 #include "si_build_pm4.h"
18 #include "si_tracepoints.h"
19 
20 #if (GFX_VER == 6)
21 #define GFX(name) name##GFX6
22 #elif (GFX_VER == 7)
23 #define GFX(name) name##GFX7
24 #elif (GFX_VER == 8)
25 #define GFX(name) name##GFX8
26 #elif (GFX_VER == 9)
27 #define GFX(name) name##GFX9
28 #elif (GFX_VER == 10)
29 #define GFX(name) name##GFX10
30 #elif (GFX_VER == 103)
31 #define GFX(name) name##GFX10_3
32 #elif (GFX_VER == 11)
33 #define GFX(name) name##GFX11
34 #elif (GFX_VER == 115)
35 #define GFX(name) name##GFX11_5
36 #elif (GFX_VER == 12)
37 #define GFX(name) name##GFX12
38 #else
39 #error "Unknown gfx level"
40 #endif
41 
42 template <amd_gfx_level GFX_VERSION, si_has_tess HAS_TESS, si_has_gs HAS_GS, si_has_ngg NGG>
si_update_shaders(struct si_context * sctx)43 static bool si_update_shaders(struct si_context *sctx)
44 {
45    struct pipe_context *ctx = (struct pipe_context *)sctx;
46    struct si_shader *old_vs = si_get_vs_inline(sctx, HAS_TESS, HAS_GS)->current;
47    unsigned old_pa_cl_vs_out_cntl = old_vs ? old_vs->pa_cl_vs_out_cntl : 0;
48    bool old_uses_vs_state_provoking_vertex = old_vs ? old_vs->uses_vs_state_provoking_vertex : false;
49    bool old_uses_gs_state_outprim = old_vs ? old_vs->uses_gs_state_outprim : false;
50    struct si_shader *old_ps = sctx->shader.ps.current;
51    unsigned old_spi_shader_col_format =
52       old_ps ? old_ps->key.ps.part.epilog.spi_shader_col_format : 0;
53    int r;
54 
55    /* Update TCS and TES. */
56    if (HAS_TESS) {
57       if (!sctx->has_tessellation) {
58          si_init_tess_factor_ring(sctx);
59          if (!sctx->has_tessellation)
60             return false;
61       }
62 
63       if (!sctx->is_user_tcs) {
64          if (!si_set_tcs_to_fixed_func_shader(sctx))
65             return false;
66       }
67 
68       r = si_shader_select(ctx, &sctx->shader.tcs);
69       if (r)
70          return false;
71       si_pm4_bind_state(sctx, hs, sctx->shader.tcs.current);
72 
73       if (!HAS_GS || GFX_VERSION <= GFX8) {
74          r = si_shader_select(ctx, &sctx->shader.tes);
75          if (r)
76             return false;
77 
78          if (HAS_GS) {
79             /* TES as ES */
80             assert(GFX_VERSION <= GFX8);
81             si_pm4_bind_state(sctx, es, sctx->shader.tes.current);
82          } else if (NGG) {
83             si_pm4_bind_state(sctx, gs, sctx->shader.tes.current);
84          } else {
85             si_pm4_bind_state(sctx, vs, sctx->shader.tes.current);
86          }
87       }
88    } else {
89       /* Reset TCS to clear fixed function shader. */
90       if (!sctx->is_user_tcs && sctx->shader.tcs.cso) {
91          sctx->shader.tcs.cso = NULL;
92          sctx->shader.tcs.current = NULL;
93       }
94 
95       if (GFX_VERSION <= GFX8) {
96          si_pm4_bind_state(sctx, ls, NULL);
97          sctx->prefetch_L2_mask &= ~SI_PREFETCH_LS;
98       }
99       si_pm4_bind_state(sctx, hs, NULL);
100       sctx->prefetch_L2_mask &= ~SI_PREFETCH_HS;
101    }
102 
103    /* Update GS. */
104    if (HAS_GS) {
105       r = si_shader_select(ctx, &sctx->shader.gs);
106       if (r)
107          return false;
108       si_pm4_bind_state(sctx, gs, sctx->shader.gs.current);
109       if (!NGG) {
110          si_pm4_bind_state(sctx, vs, sctx->shader.gs.current->gs_copy_shader);
111 
112          if (!si_update_gs_ring_buffers(sctx))
113             return false;
114       } else if (GFX_VERSION < GFX11) {
115          si_pm4_bind_state(sctx, vs, NULL);
116          sctx->prefetch_L2_mask &= ~SI_PREFETCH_VS;
117       }
118    } else {
119       if (!NGG) {
120          si_pm4_bind_state(sctx, gs, NULL);
121          sctx->prefetch_L2_mask &= ~SI_PREFETCH_GS;
122          if (GFX_VERSION <= GFX8) {
123             si_pm4_bind_state(sctx, es, NULL);
124             sctx->prefetch_L2_mask &= ~SI_PREFETCH_ES;
125          }
126       }
127    }
128 
129    /* Update VS. */
130    if ((!HAS_TESS && !HAS_GS) || GFX_VERSION <= GFX8) {
131       r = si_shader_select(ctx, &sctx->shader.vs);
132       if (r)
133          return false;
134 
135       if (!HAS_TESS && !HAS_GS) {
136          if (NGG) {
137             si_pm4_bind_state(sctx, gs, sctx->shader.vs.current);
138             if (GFX_VERSION < GFX11) {
139                si_pm4_bind_state(sctx, vs, NULL);
140                sctx->prefetch_L2_mask &= ~SI_PREFETCH_VS;
141             }
142          } else {
143             si_pm4_bind_state(sctx, vs, sctx->shader.vs.current);
144          }
145       } else if (HAS_TESS) {
146          si_pm4_bind_state(sctx, ls, sctx->shader.vs.current);
147       } else {
148          assert(HAS_GS);
149          si_pm4_bind_state(sctx, es, sctx->shader.vs.current);
150       }
151    }
152 
153    if (GFX_VERSION >= GFX9 && HAS_TESS)
154       sctx->vs_uses_base_instance = sctx->queued.named.hs->uses_base_instance;
155    else if (GFX_VERSION >= GFX9 && HAS_GS)
156       sctx->vs_uses_base_instance = sctx->shader.gs.current->uses_base_instance;
157    else
158       sctx->vs_uses_base_instance = sctx->shader.vs.current->uses_base_instance;
159 
160    /* Update VGT_SHADER_STAGES_EN. */
161    uint32_t vgt_stages = 0;
162 
163    if (HAS_TESS) {
164       if (GFX_VERSION >= GFX12) {
165          vgt_stages |= S_028A98_HS_EN(1) |
166                        S_028A98_HS_W32_EN(sctx->queued.named.hs->wave_size == 32);
167       } else {
168          vgt_stages |= S_028B54_LS_EN(V_028B54_LS_STAGE_ON) |
169                        S_028B54_HS_EN(1) |
170                        S_028B54_DYNAMIC_HS(1) |
171                        S_028B54_HS_W32_EN(GFX_VERSION >= GFX10 &&
172                                           sctx->queued.named.hs->wave_size == 32);
173       }
174    }
175 
176    if (NGG) {
177       vgt_stages |= si_get_vs_inline(sctx, HAS_TESS, HAS_GS)->current->ngg.vgt_shader_stages_en;
178    } else {
179       if (HAS_GS) {
180          /* Legacy GS only supports Wave64. */
181          assert(sctx->shader.gs.current->wave_size == 64);
182 
183          vgt_stages |= S_028B54_ES_EN(HAS_TESS ? V_028B54_ES_STAGE_DS : V_028B54_ES_STAGE_REAL) |
184                        S_028B54_GS_EN(1) |
185                        S_028B54_VS_EN(V_028B54_VS_STAGE_COPY_SHADER) |
186                        S_028B54_VS_W32_EN(GFX_VERSION >= GFX10 &&
187                                           sctx->shader.gs.current->gs_copy_shader->wave_size == 32);
188       } else if (HAS_TESS) {
189          vgt_stages |= S_028B54_VS_EN(V_028B54_VS_STAGE_DS);
190       }
191 
192       vgt_stages |= S_028B54_MAX_PRIMGRP_IN_WAVE(GFX_VERSION >= GFX9 ? 2 : 0) |
193                     S_028B54_VS_W32_EN(!HAS_GS && GFX_VERSION >= GFX10 &&
194                                        si_get_vs_inline(sctx, HAS_TESS, HAS_GS)->current->wave_size == 32);
195    }
196 
197    /* Update GE_CNTL. */
198    uint32_t ge_cntl = 0;
199 
200    if (GFX_VERSION >= GFX10) {
201       union si_vgt_param_key key = sctx->ia_multi_vgt_param_key;
202 
203       if (NGG) {
204          if (HAS_TESS) {
205             if (GFX_VERSION >= GFX11) {
206                ge_cntl = si_get_vs_inline(sctx, HAS_TESS, HAS_GS)->current->ge_cntl |
207                          S_03096C_BREAK_PRIMGRP_AT_EOI(key.u.tess_uses_prim_id);
208             } else {
209                /* PRIM_GRP_SIZE_GFX10 is set by si_emit_vgt_pipeline_state. */
210                ge_cntl = S_03096C_VERT_GRP_SIZE(0) |
211                          S_03096C_BREAK_WAVE_AT_EOI(key.u.tess_uses_prim_id);
212             }
213          } else {
214             ge_cntl = si_get_vs_inline(sctx, HAS_TESS, HAS_GS)->current->ge_cntl;
215          }
216       } else {
217          unsigned primgroup_size;
218          unsigned vertgroup_size;
219          assert(GFX_VERSION < GFX11);
220 
221          if (HAS_TESS) {
222             primgroup_size = 0; /* this is set by si_emit_vgt_pipeline_state */
223             vertgroup_size = 0;
224          } else if (HAS_GS) {
225             unsigned vgt_gs_onchip_cntl = sctx->shader.gs.current->gs.vgt_gs_onchip_cntl;
226             primgroup_size = G_028A44_GS_PRIMS_PER_SUBGRP(vgt_gs_onchip_cntl);
227             vertgroup_size = G_028A44_ES_VERTS_PER_SUBGRP(vgt_gs_onchip_cntl);
228          } else {
229             primgroup_size = 128; /* recommended without a GS and tess */
230             vertgroup_size = 0;
231          }
232 
233          ge_cntl = S_03096C_PRIM_GRP_SIZE_GFX10(primgroup_size) |
234                    S_03096C_VERT_GRP_SIZE(vertgroup_size) |
235                    S_03096C_BREAK_WAVE_AT_EOI(key.u.uses_tess && key.u.tess_uses_prim_id);
236       }
237 
238       /* Note: GE_CNTL.PACKET_TO_ONE_PA should only be set if LINE_STIPPLE_TEX_ENA == 1.
239        * Since we don't use that, we don't have to do anything.
240        */
241    }
242 
243    if (vgt_stages != sctx->vgt_shader_stages_en ||
244        (GFX_VERSION >= GFX10 && ge_cntl != sctx->ge_cntl)) {
245       sctx->vgt_shader_stages_en = vgt_stages;
246       sctx->ge_cntl = ge_cntl;
247       si_mark_atom_dirty(sctx, &sctx->atoms.s.vgt_pipeline_state);
248    }
249 
250    struct si_shader *hw_vs = si_get_vs_inline(sctx, HAS_TESS, HAS_GS)->current;
251 
252    if (old_pa_cl_vs_out_cntl != hw_vs->pa_cl_vs_out_cntl)
253       si_mark_atom_dirty(sctx, &sctx->atoms.s.clip_regs);
254 
255    /* If we start to use any of these, we need to update the SGPR. */
256    if ((hw_vs->uses_vs_state_provoking_vertex && !old_uses_vs_state_provoking_vertex) ||
257        (hw_vs->uses_gs_state_outprim && !old_uses_gs_state_outprim)) {
258       si_update_ngg_sgpr_state_out_prim(sctx, hw_vs, NGG);
259       si_update_ngg_sgpr_state_provoking_vtx(sctx, hw_vs, NGG);
260    }
261 
262    r = si_shader_select(ctx, &sctx->shader.ps);
263    if (r)
264       return false;
265    si_pm4_bind_state(sctx, ps, sctx->shader.ps.current);
266 
267    unsigned db_shader_control = sctx->shader.ps.current->ps.db_shader_control;
268    if (sctx->ps_db_shader_control != db_shader_control) {
269       sctx->ps_db_shader_control = db_shader_control;
270       si_mark_atom_dirty(sctx, &sctx->atoms.s.db_render_state);
271       if (sctx->screen->dpbb_allowed)
272          si_mark_atom_dirty(sctx, &sctx->atoms.s.dpbb_state);
273    }
274 
275    unsigned pa_sc_hisz_control = sctx->shader.ps.current->ps.pa_sc_hisz_control;
276    if (GFX_VERSION >= GFX12 && sctx->screen->dpbb_allowed &&
277        sctx->ps_pa_sc_hisz_control != pa_sc_hisz_control) {
278       sctx->ps_pa_sc_hisz_control = pa_sc_hisz_control;
279       si_mark_atom_dirty(sctx, &sctx->atoms.s.dpbb_state);
280    }
281 
282    if (si_pm4_state_changed(sctx, ps) ||
283        (!NGG && si_pm4_state_changed(sctx, vs)) ||
284        (NGG && si_pm4_state_changed(sctx, gs))) {
285       sctx->atoms.s.spi_map.emit = sctx->emit_spi_map[sctx->shader.ps.current->ps.num_interp];
286       si_mark_atom_dirty(sctx, &sctx->atoms.s.spi_map);
287    }
288 
289    if ((GFX_VERSION >= GFX10_3 || (GFX_VERSION >= GFX9 && sctx->screen->info.rbplus_allowed)) &&
290        si_pm4_state_changed(sctx, ps) &&
291        (!old_ps || old_spi_shader_col_format !=
292                       sctx->shader.ps.current->key.ps.part.epilog.spi_shader_col_format))
293       si_mark_atom_dirty(sctx, &sctx->atoms.s.cb_render_state);
294 
295    if (sctx->smoothing_enabled !=
296        sctx->shader.ps.current->key.ps.mono.poly_line_smoothing) {
297       sctx->smoothing_enabled = sctx->shader.ps.current->key.ps.mono.poly_line_smoothing;
298       si_mark_atom_dirty(sctx, &sctx->atoms.s.msaa_config);
299 
300       /* NGG cull state uses smoothing_enabled. */
301       if (GFX_VERSION >= GFX10 && sctx->screen->use_ngg_culling)
302          si_mark_atom_dirty(sctx, &sctx->atoms.s.ngg_cull_state);
303 
304       if (GFX_VERSION == GFX11 && sctx->screen->info.has_export_conflict_bug)
305          si_mark_atom_dirty(sctx, &sctx->atoms.s.db_render_state);
306 
307       if (sctx->framebuffer.nr_samples <= 1)
308          si_mark_atom_dirty(sctx, &sctx->atoms.s.sample_locations);
309    }
310 
311    if (HAS_TESS)
312       si_update_tess_io_layout_state(sctx);
313 
314    if (GFX_VERSION >= GFX9 && unlikely(sctx->sqtt)) {
315       /* Pretend the bound shaders form a vk pipeline. Include the scratch size in
316        * the hash calculation to force re-emitting the pipeline if the scratch bo
317        * changes.
318        */
319       uint64_t scratch_bo_size = sctx->scratch_buffer ? sctx->scratch_buffer->bo_size : 0;
320       uint32_t total_size = 0;
321 
322       /* Compute pipeline code hash. */
323       XXH64_state_t* xh = XXH64_createState();
324       XXH64_reset(xh, scratch_bo_size);
325 
326       for (int i = 0; i < SI_NUM_GRAPHICS_SHADERS; i++) {
327          struct si_shader *shader = sctx->shaders[i].current;
328          if (sctx->shaders[i].cso && shader) {
329             /* Hash the key. */
330             XXH64_update(xh, &shader->key, sizeof(shader->key));
331             /* Hash the main part binary. */
332             XXH64_update(xh, shader->binary.code_buffer, shader->binary.code_size);
333 
334             total_size += (uint32_t)align_uintptr(shader->binary.uploaded_code_size, 256);
335          }
336       }
337 
338       XXH64_hash_t pipeline_code_hash = XXH64_digest(xh);
339       XXH64_freeState(xh);
340 
341       struct si_sqtt_fake_pipeline *pipeline = NULL;
342       if (!si_sqtt_pipeline_is_registered(sctx->sqtt, pipeline_code_hash)) {
343          /* This is a new pipeline. Allocate a new bo to hold all the shaders. Without
344           * this, shader code export process creates huge rgp files because RGP assumes
345           * the shaders live sequentially in memory (shader N address = shader 0 + offset N)
346           */
347          struct si_resource *bo = si_aligned_buffer_create(
348             &sctx->screen->b,
349             SI_RESOURCE_FLAG_DRIVER_INTERNAL | SI_RESOURCE_FLAG_32BIT,
350             PIPE_USAGE_IMMUTABLE, align(total_size, SI_CPDMA_ALIGNMENT), 256);
351 
352          char *ptr = (char *) (bo ? sctx->screen->ws->buffer_map(sctx->screen->ws,
353                bo->buf, NULL,
354                (enum pipe_map_flags)(PIPE_MAP_READ_WRITE | PIPE_MAP_UNSYNCHRONIZED | RADEON_MAP_TEMPORARY)) :
355              NULL);
356 
357          uint32_t offset = 0;
358          uint64_t scratch_va = sctx->scratch_buffer ? sctx->scratch_buffer->gpu_address : 0;
359 
360          if (ptr) {
361             pipeline = (struct si_sqtt_fake_pipeline *)
362                CALLOC(1, sizeof(struct si_sqtt_fake_pipeline));
363 
364             pipeline->code_hash = pipeline_code_hash;
365             pipeline->bo = bo;
366 
367             /* Re-upload all gfx shaders and init PM4. */
368             si_pm4_clear_state(&pipeline->pm4, sctx->screen, false);
369 
370             uint32_t gfx_sh_offsets[SI_NUM_GRAPHICS_SHADERS] = { 0 };
371             for (int i = 0; i < SI_NUM_GRAPHICS_SHADERS; i++) {
372                struct si_shader *shader = sctx->shaders[i].current;
373                if (sctx->shaders[i].cso && shader) {
374                   struct si_resource *original_bo = shader->bo;
375 
376                   /* Temp override for si_shader_binary_upload_at to work. */
377                   shader->bo = pipeline->bo;
378 
379                   int size = si_shader_binary_upload_at(sctx->screen, shader, scratch_va, offset);
380 
381                   shader->bo = original_bo;
382 
383                   assert(size == (int)shader->binary.uploaded_code_size);
384 
385                   gfx_sh_offsets[i] = offset;
386                   offset += align(size, 256);
387 
388                   struct si_pm4_state *pm4 = &shader->pm4;
389 
390                   /* Patch the SPI_SHADER_PGM_LO_* register to point to the new bo address,
391                    * with the proper offset.
392                    */
393                   uint64_t va_low = shader->gpu_address >> 8;
394                   uint32_t reg = pm4->base.spi_shader_pgm_lo_reg;
395                   ac_pm4_set_reg(&pipeline->pm4.base, reg, va_low);
396                }
397             }
398             ac_pm4_finalize(&pipeline->pm4.base);
399             sctx->screen->ws->buffer_unmap(sctx->screen->ws, bo->buf);
400 
401             _mesa_hash_table_u64_insert(sctx->sqtt->pipeline_bos,
402                                         pipeline_code_hash, pipeline);
403 
404             si_sqtt_register_pipeline(sctx, pipeline, gfx_sh_offsets);
405          } else {
406             if (bo)
407                si_resource_reference(&bo, NULL);
408          }
409       } else {
410          pipeline = (struct si_sqtt_fake_pipeline *)_mesa_hash_table_u64_search(
411              sctx->sqtt->pipeline_bos, pipeline_code_hash);
412       }
413       assert(pipeline);
414 
415       si_sqtt_describe_pipeline_bind(sctx, pipeline_code_hash, 0);
416       si_pm4_bind_state(sctx, sqtt_pipeline, pipeline);
417    }
418 
419    if ((GFX_VERSION <= GFX8 &&
420         (si_pm4_state_enabled_and_changed(sctx, ls) || si_pm4_state_enabled_and_changed(sctx, es))) ||
421        si_pm4_state_enabled_and_changed(sctx, hs) || si_pm4_state_enabled_and_changed(sctx, gs) ||
422        (!NGG && si_pm4_state_enabled_and_changed(sctx, vs)) || si_pm4_state_enabled_and_changed(sctx, ps)) {
423       unsigned scratch_size = 0;
424 
425       if (HAS_TESS) {
426          if (GFX_VERSION <= GFX8) /* LS */
427             scratch_size = MAX2(scratch_size, sctx->shader.vs.current->config.scratch_bytes_per_wave);
428 
429          scratch_size = MAX2(scratch_size, sctx->queued.named.hs->config.scratch_bytes_per_wave);
430 
431          if (HAS_GS) {
432             if (GFX_VERSION <= GFX8) /* ES */
433                scratch_size = MAX2(scratch_size, sctx->shader.tes.current->config.scratch_bytes_per_wave);
434 
435             scratch_size = MAX2(scratch_size, sctx->shader.gs.current->config.scratch_bytes_per_wave);
436          } else {
437             scratch_size = MAX2(scratch_size, sctx->shader.tes.current->config.scratch_bytes_per_wave);
438          }
439       } else if (HAS_GS) {
440          if (GFX_VERSION <= GFX8) /* ES */
441             scratch_size = MAX2(scratch_size, sctx->shader.vs.current->config.scratch_bytes_per_wave);
442 
443          scratch_size = MAX2(scratch_size, sctx->shader.gs.current->config.scratch_bytes_per_wave);
444       } else {
445          scratch_size = MAX2(scratch_size, sctx->shader.vs.current->config.scratch_bytes_per_wave);
446       }
447 
448       scratch_size = MAX2(scratch_size, sctx->shader.ps.current->config.scratch_bytes_per_wave);
449 
450       if (scratch_size && !si_update_spi_tmpring_size(sctx, scratch_size))
451          return false;
452 
453       if (GFX_VERSION >= GFX7) {
454          if (GFX_VERSION <= GFX8 && HAS_TESS && si_pm4_state_enabled_and_changed(sctx, ls))
455             sctx->prefetch_L2_mask |= SI_PREFETCH_LS;
456 
457          if (HAS_TESS && si_pm4_state_enabled_and_changed(sctx, hs))
458             sctx->prefetch_L2_mask |= SI_PREFETCH_HS;
459 
460          if (GFX_VERSION <= GFX8 && HAS_GS && si_pm4_state_enabled_and_changed(sctx, es))
461             sctx->prefetch_L2_mask |= SI_PREFETCH_ES;
462 
463          if ((HAS_GS || NGG) && si_pm4_state_enabled_and_changed(sctx, gs))
464             sctx->prefetch_L2_mask |= SI_PREFETCH_GS;
465 
466          if (!NGG && si_pm4_state_enabled_and_changed(sctx, vs))
467             sctx->prefetch_L2_mask |= SI_PREFETCH_VS;
468 
469          if (si_pm4_state_enabled_and_changed(sctx, ps))
470             sctx->prefetch_L2_mask |= SI_PREFETCH_PS;
471       }
472    }
473 
474    /* si_shader_select_with_key can clear the ngg_culling in the shader key if the shader
475     * compilation hasn't finished. Set it to the same value in si_context.
476     */
477    if (GFX_VERSION >= GFX10 && NGG)
478       sctx->ngg_culling = si_get_vs_inline(sctx, HAS_TESS, HAS_GS)->current->key.ge.opt.ngg_culling;
479 
480    sctx->do_update_shaders = false;
481    return true;
482 }
483 
484 ALWAYS_INLINE
si_conv_pipe_prim(unsigned mode)485 static unsigned si_conv_pipe_prim(unsigned mode)
486 {
487    static const unsigned prim_conv[] = {
488       [MESA_PRIM_POINTS] = V_008958_DI_PT_POINTLIST,
489       [MESA_PRIM_LINES] = V_008958_DI_PT_LINELIST,
490       [MESA_PRIM_LINE_LOOP] = V_008958_DI_PT_LINELOOP,
491       [MESA_PRIM_LINE_STRIP] = V_008958_DI_PT_LINESTRIP,
492       [MESA_PRIM_TRIANGLES] = V_008958_DI_PT_TRILIST,
493       [MESA_PRIM_TRIANGLE_STRIP] = V_008958_DI_PT_TRISTRIP,
494       [MESA_PRIM_TRIANGLE_FAN] = V_008958_DI_PT_TRIFAN,
495       [MESA_PRIM_QUADS] = V_008958_DI_PT_QUADLIST,
496       [MESA_PRIM_QUAD_STRIP] = V_008958_DI_PT_QUADSTRIP,
497       [MESA_PRIM_POLYGON] = V_008958_DI_PT_POLYGON,
498       [MESA_PRIM_LINES_ADJACENCY] = V_008958_DI_PT_LINELIST_ADJ,
499       [MESA_PRIM_LINE_STRIP_ADJACENCY] = V_008958_DI_PT_LINESTRIP_ADJ,
500       [MESA_PRIM_TRIANGLES_ADJACENCY] = V_008958_DI_PT_TRILIST_ADJ,
501       [MESA_PRIM_TRIANGLE_STRIP_ADJACENCY] = V_008958_DI_PT_TRISTRIP_ADJ,
502       [MESA_PRIM_PATCHES] = V_008958_DI_PT_PATCH,
503       [SI_PRIM_RECTANGLE_LIST] = V_008958_DI_PT_RECTLIST};
504    assert(mode < ARRAY_SIZE(prim_conv));
505    return prim_conv[mode];
506 }
507 
508 template<amd_gfx_level GFX_VERSION>
si_cp_dma_prefetch_inline(struct si_context * sctx,uint64_t address,unsigned size)509 static void si_cp_dma_prefetch_inline(struct si_context *sctx, uint64_t address, unsigned size)
510 {
511    assert(GFX_VERSION >= GFX7);
512    assert(sctx->screen->info.has_cp_dma);
513 
514    if (GFX_VERSION >= GFX11)
515       size = MIN2(size, 32768 - SI_CPDMA_ALIGNMENT);
516 
517    /* The prefetch address and size must be aligned, so that we don't have to apply
518     * the complicated hw bug workaround.
519     *
520     * The size should also be less than 2 MB, so that we don't have to use a loop.
521     * Callers shouldn't need to prefetch more than 2 MB.
522     */
523    assert(size % SI_CPDMA_ALIGNMENT == 0);
524    assert(address % SI_CPDMA_ALIGNMENT == 0);
525    assert(size < S_415_BYTE_COUNT_GFX6(~0u));
526 
527    uint32_t header = S_411_SRC_SEL(V_411_SRC_ADDR_TC_L2);
528    uint32_t command = S_415_BYTE_COUNT_GFX6(size);
529 
530    if (GFX_VERSION >= GFX9) {
531       command |= S_415_DISABLE_WR_CONFIRM_GFX9(1);
532       header |= S_411_DST_SEL(V_411_NOWHERE);
533    } else {
534       command |= S_415_DISABLE_WR_CONFIRM_GFX6(1);
535       header |= S_411_DST_SEL(V_411_DST_ADDR_TC_L2);
536    }
537 
538    struct radeon_cmdbuf *cs = &sctx->gfx_cs;
539    radeon_begin(cs);
540    radeon_emit(PKT3(PKT3_DMA_DATA, 5, 0));
541    radeon_emit(header);
542    radeon_emit(address);       /* SRC_ADDR_LO [31:0] */
543    radeon_emit(address >> 32); /* SRC_ADDR_HI [31:0] */
544    radeon_emit(address);       /* DST_ADDR_LO [31:0] */
545    radeon_emit(address >> 32); /* DST_ADDR_HI [31:0] */
546    radeon_emit(command);
547    radeon_end();
548 }
549 
550 #if GFX_VER == 6 /* declare this function only once because it handles all chips. */
551 
si_cp_dma_prefetch(struct si_context * sctx,struct pipe_resource * buf,unsigned offset,unsigned size)552 void si_cp_dma_prefetch(struct si_context *sctx, struct pipe_resource *buf,
553                         unsigned offset, unsigned size)
554 {
555    uint64_t address = si_resource(buf)->gpu_address + offset;
556    switch (sctx->gfx_level) {
557    case GFX7:
558       si_cp_dma_prefetch_inline<GFX7>(sctx, address, size);
559       break;
560    case GFX8:
561       si_cp_dma_prefetch_inline<GFX8>(sctx, address, size);
562       break;
563    case GFX9:
564       si_cp_dma_prefetch_inline<GFX9>(sctx, address, size);
565       break;
566    case GFX10:
567       si_cp_dma_prefetch_inline<GFX10>(sctx, address, size);
568       break;
569    case GFX10_3:
570       si_cp_dma_prefetch_inline<GFX10_3>(sctx, address, size);
571       break;
572    case GFX11:
573       si_cp_dma_prefetch_inline<GFX11>(sctx, address, size);
574       break;
575    case GFX11_5:
576       si_cp_dma_prefetch_inline<GFX11_5>(sctx, address, size);
577       break;
578    case GFX12:
579       si_cp_dma_prefetch_inline<GFX12>(sctx, address, size);
580       break;
581    default:
582       break;
583    }
584 }
585 
586 #endif
587 
588 template<amd_gfx_level GFX_VERSION>
si_prefetch_shader_async(struct si_context * sctx,struct si_shader * shader)589 static void si_prefetch_shader_async(struct si_context *sctx, struct si_shader *shader)
590 {
591    struct pipe_resource *bo = &shader->bo->b.b;
592    si_cp_dma_prefetch_inline<GFX_VERSION>(sctx, shader->gpu_address, bo->width0);
593 }
594 
595 /**
596  * Prefetch shaders.
597  */
598 template<amd_gfx_level GFX_VERSION, si_has_tess HAS_TESS, si_has_gs HAS_GS, si_has_ngg NGG>
599 ALWAYS_INLINE
si_prefetch_shaders(struct si_context * sctx)600 static void si_prefetch_shaders(struct si_context *sctx)
601 {
602    unsigned mask = sctx->prefetch_L2_mask;
603 
604    /* GFX6 doesn't support the L2 prefetch. */
605    if (GFX_VERSION < GFX7 || !mask)
606       return;
607 
608    /* Prefetch shaders and VBO descriptors into L2. */
609    if (GFX_VERSION >= GFX11) {
610       if (HAS_TESS && mask & SI_PREFETCH_HS)
611          si_prefetch_shader_async<GFX_VERSION>(sctx, sctx->queued.named.hs);
612 
613       if (mask & SI_PREFETCH_GS)
614          si_prefetch_shader_async<GFX_VERSION>(sctx, sctx->queued.named.gs);
615    } else if (GFX_VERSION >= GFX9) {
616       if (HAS_TESS) {
617          if (mask & SI_PREFETCH_HS)
618             si_prefetch_shader_async<GFX_VERSION>(sctx, sctx->queued.named.hs);
619       }
620       if ((HAS_GS || NGG) && mask & SI_PREFETCH_GS)
621          si_prefetch_shader_async<GFX_VERSION>(sctx, sctx->queued.named.gs);
622       if (!NGG && mask & SI_PREFETCH_VS)
623             si_prefetch_shader_async<GFX_VERSION>(sctx, sctx->queued.named.vs);
624    } else {
625       /* GFX6-GFX8 */
626       /* Choose the right spot for the VBO prefetch. */
627       if (HAS_TESS) {
628          if (mask & SI_PREFETCH_LS)
629             si_prefetch_shader_async<GFX_VERSION>(sctx, sctx->queued.named.ls);
630          if (mask & SI_PREFETCH_HS)
631             si_prefetch_shader_async<GFX_VERSION>(sctx, sctx->queued.named.hs);
632          if (mask & SI_PREFETCH_ES)
633             si_prefetch_shader_async<GFX_VERSION>(sctx, sctx->queued.named.es);
634          if (mask & SI_PREFETCH_GS)
635             si_prefetch_shader_async<GFX_VERSION>(sctx, sctx->queued.named.gs);
636       } else if (HAS_GS) {
637          if (mask & SI_PREFETCH_ES)
638             si_prefetch_shader_async<GFX_VERSION>(sctx, sctx->queued.named.es);
639          if (mask & SI_PREFETCH_GS)
640             si_prefetch_shader_async<GFX_VERSION>(sctx, sctx->queued.named.gs);
641       }
642       if (mask & SI_PREFETCH_VS)
643          si_prefetch_shader_async<GFX_VERSION>(sctx, sctx->queued.named.vs);
644    }
645 
646    if (mask & SI_PREFETCH_PS)
647       si_prefetch_shader_async<GFX_VERSION>(sctx, sctx->queued.named.ps);
648 
649    /* This must be cleared only when AFTER_DRAW is true. */
650    sctx->prefetch_L2_mask = 0;
651 }
652 
si_num_prims_for_vertices(enum mesa_prim prim,unsigned count,unsigned vertices_per_patch)653 static unsigned si_num_prims_for_vertices(enum mesa_prim prim,
654                                           unsigned count, unsigned vertices_per_patch)
655 {
656    switch (prim) {
657    case MESA_PRIM_PATCHES:
658       return count / vertices_per_patch;
659    case MESA_PRIM_POLYGON:
660       /* It's a triangle fan with different edge flags. */
661       return count >= 3 ? count - 2 : 0;
662    case SI_PRIM_RECTANGLE_LIST:
663       return count / 3;
664    default:
665       return u_decomposed_prims_for_vertices(prim, count);
666    }
667 }
668 
si_get_init_multi_vgt_param(struct si_screen * sscreen,union si_vgt_param_key * key)669 static unsigned si_get_init_multi_vgt_param(struct si_screen *sscreen, union si_vgt_param_key *key)
670 {
671    STATIC_ASSERT(sizeof(union si_vgt_param_key) == 2);
672    unsigned max_primgroup_in_wave = 2;
673 
674    /* SWITCH_ON_EOP(0) is always preferable. */
675    bool wd_switch_on_eop = false;
676    bool ia_switch_on_eop = false;
677    bool ia_switch_on_eoi = false;
678    bool partial_vs_wave = false;
679    bool partial_es_wave = false;
680 
681    if (key->u.uses_tess) {
682       /* SWITCH_ON_EOI must be set if PrimID is used. */
683       if (key->u.tess_uses_prim_id)
684          ia_switch_on_eoi = true;
685 
686       /* Bug with tessellation and GS on Bonaire and older 2 SE chips. */
687       if ((sscreen->info.family == CHIP_TAHITI || sscreen->info.family == CHIP_PITCAIRN ||
688            sscreen->info.family == CHIP_BONAIRE) &&
689           key->u.uses_gs)
690          partial_vs_wave = true;
691 
692       /* Needed for 028B6C_DISTRIBUTION_MODE != 0. (implies >= GFX8) */
693       if (sscreen->info.has_distributed_tess) {
694          if (key->u.uses_gs) {
695             if (sscreen->info.gfx_level == GFX8)
696                partial_es_wave = true;
697          } else {
698             partial_vs_wave = true;
699          }
700       }
701    }
702 
703    /* This is a hardware requirement. */
704    if (key->u.line_stipple_enabled || (sscreen->debug_flags & DBG(SWITCH_ON_EOP))) {
705       ia_switch_on_eop = true;
706       wd_switch_on_eop = true;
707    }
708 
709    if (sscreen->info.gfx_level >= GFX7) {
710       /* WD_SWITCH_ON_EOP has no effect on GPUs with less than
711        * 4 shader engines. Set 1 to pass the assertion below.
712        * The other cases are hardware requirements.
713        *
714        * Polaris supports primitive restart with WD_SWITCH_ON_EOP=0
715        * for points, line strips, and tri strips.
716        */
717       if (sscreen->info.max_se <= 2 || key->u.prim == MESA_PRIM_POLYGON ||
718           key->u.prim == MESA_PRIM_LINE_LOOP || key->u.prim == MESA_PRIM_TRIANGLE_FAN ||
719           key->u.prim == MESA_PRIM_TRIANGLE_STRIP_ADJACENCY ||
720           (key->u.primitive_restart &&
721            (sscreen->info.family < CHIP_POLARIS10 ||
722             (key->u.prim != MESA_PRIM_POINTS && key->u.prim != MESA_PRIM_LINE_STRIP &&
723              key->u.prim != MESA_PRIM_TRIANGLE_STRIP))) ||
724           key->u.count_from_stream_output)
725          wd_switch_on_eop = true;
726 
727       /* Hawaii hangs if instancing is enabled and WD_SWITCH_ON_EOP is 0.
728        * We don't know that for indirect drawing, so treat it as
729        * always problematic. */
730       if (sscreen->info.family == CHIP_HAWAII && key->u.uses_instancing)
731          wd_switch_on_eop = true;
732 
733       /* Performance recommendation for 4 SE Gfx7-8 parts if
734        * instances are smaller than a primgroup.
735        * Assume indirect draws always use small instances.
736        * This is needed for good VS wave utilization.
737        */
738       if (sscreen->info.gfx_level <= GFX8 && sscreen->info.max_se == 4 &&
739           key->u.multi_instances_smaller_than_primgroup)
740          wd_switch_on_eop = true;
741 
742       /* Required on GFX7 and later. */
743       if (sscreen->info.max_se == 4 && !wd_switch_on_eop)
744          ia_switch_on_eoi = true;
745 
746       /* HW engineers suggested that PARTIAL_VS_WAVE_ON should be set
747        * to work around a GS hang.
748        */
749       if (key->u.uses_gs &&
750           (sscreen->info.family == CHIP_TONGA || sscreen->info.family == CHIP_FIJI ||
751            sscreen->info.family == CHIP_POLARIS10 || sscreen->info.family == CHIP_POLARIS11 ||
752            sscreen->info.family == CHIP_POLARIS12 || sscreen->info.family == CHIP_VEGAM))
753          partial_vs_wave = true;
754 
755       /* Required by Hawaii and, for some special cases, by GFX8. */
756       if (ia_switch_on_eoi &&
757           (sscreen->info.family == CHIP_HAWAII ||
758            (sscreen->info.gfx_level == GFX8 && (key->u.uses_gs || max_primgroup_in_wave != 2))))
759          partial_vs_wave = true;
760 
761       /* Instancing bug on Bonaire. */
762       if (sscreen->info.family == CHIP_BONAIRE && ia_switch_on_eoi && key->u.uses_instancing)
763          partial_vs_wave = true;
764 
765       /* This only applies to Polaris10 and later 4 SE chips.
766        * wd_switch_on_eop is already true on all other chips.
767        */
768       if (!wd_switch_on_eop && key->u.primitive_restart)
769          partial_vs_wave = true;
770 
771       /* If the WD switch is false, the IA switch must be false too. */
772       assert(wd_switch_on_eop || !ia_switch_on_eop);
773    }
774 
775    /* If SWITCH_ON_EOI is set, PARTIAL_ES_WAVE must be set too. */
776    if (sscreen->info.gfx_level <= GFX8 && ia_switch_on_eoi)
777       partial_es_wave = true;
778 
779    return S_028AA8_SWITCH_ON_EOP(ia_switch_on_eop) | S_028AA8_SWITCH_ON_EOI(ia_switch_on_eoi) |
780           S_028AA8_PARTIAL_VS_WAVE_ON(partial_vs_wave) |
781           S_028AA8_PARTIAL_ES_WAVE_ON(partial_es_wave) |
782           S_028AA8_WD_SWITCH_ON_EOP(sscreen->info.gfx_level >= GFX7 ? wd_switch_on_eop : 0) |
783           /* The following field was moved to VGT_SHADER_STAGES_EN in GFX9. */
784           S_028AA8_MAX_PRIMGRP_IN_WAVE(sscreen->info.gfx_level == GFX8 ? max_primgroup_in_wave
785                                                                         : 0) |
786           S_030960_EN_INST_OPT_BASIC(sscreen->info.gfx_level >= GFX9) |
787           S_030960_EN_INST_OPT_ADV(sscreen->info.gfx_level >= GFX9);
788 }
789 
si_init_ia_multi_vgt_param_table(struct si_context * sctx)790 static void si_init_ia_multi_vgt_param_table(struct si_context *sctx)
791 {
792    for (int prim = 0; prim <= SI_PRIM_RECTANGLE_LIST; prim++)
793       for (int uses_instancing = 0; uses_instancing < 2; uses_instancing++)
794          for (int multi_instances = 0; multi_instances < 2; multi_instances++)
795             for (int primitive_restart = 0; primitive_restart < 2; primitive_restart++)
796                for (int count_from_so = 0; count_from_so < 2; count_from_so++)
797                   for (int line_stipple = 0; line_stipple < 2; line_stipple++)
798                      for (int uses_tess = 0; uses_tess < 2; uses_tess++)
799                         for (int tess_uses_primid = 0; tess_uses_primid < 2; tess_uses_primid++)
800                            for (int uses_gs = 0; uses_gs < 2; uses_gs++) {
801                               union si_vgt_param_key key;
802 
803                               key.index = 0;
804                               key.u.prim = prim;
805                               key.u.uses_instancing = uses_instancing;
806                               key.u.multi_instances_smaller_than_primgroup = multi_instances;
807                               key.u.primitive_restart = primitive_restart;
808                               key.u.count_from_stream_output = count_from_so;
809                               key.u.line_stipple_enabled = line_stipple;
810                               key.u.uses_tess = uses_tess;
811                               key.u.tess_uses_prim_id = tess_uses_primid;
812                               key.u.uses_gs = uses_gs;
813 
814                               sctx->ia_multi_vgt_param[key.index] =
815                                  si_get_init_multi_vgt_param(sctx->screen, &key);
816                            }
817 }
818 
si_is_line_stipple_enabled(struct si_context * sctx)819 static bool si_is_line_stipple_enabled(struct si_context *sctx)
820 {
821    struct si_state_rasterizer *rs = sctx->queued.named.rasterizer;
822 
823    return rs->line_stipple_enable && sctx->current_rast_prim != MESA_PRIM_POINTS &&
824           (rs->polygon_mode_is_lines || util_prim_is_lines(sctx->current_rast_prim));
825 }
826 
827 enum si_is_draw_vertex_state {
828    DRAW_VERTEX_STATE_OFF,
829    DRAW_VERTEX_STATE_ON,
830 };
831 
832 enum si_has_sh_pairs_packed {
833    HAS_SH_PAIRS_PACKED_OFF,
834    HAS_SH_PAIRS_PACKED_ON,
835 };
836 
837 enum si_alt_hiz_logic {
838    ALT_HIZ_LOGIC_OFF,
839    ALT_HIZ_LOGIC_ON,
840 };
841 
842 template <si_is_draw_vertex_state IS_DRAW_VERTEX_STATE> ALWAYS_INLINE
num_instanced_prims_less_than(const struct pipe_draw_indirect_info * indirect,enum mesa_prim prim,unsigned min_vertex_count,unsigned instance_count,unsigned num_prims,uint8_t vertices_per_patch)843 static bool num_instanced_prims_less_than(const struct pipe_draw_indirect_info *indirect,
844                                           enum mesa_prim prim,
845                                           unsigned min_vertex_count,
846                                           unsigned instance_count,
847                                           unsigned num_prims,
848                                           uint8_t vertices_per_patch)
849 {
850    if (IS_DRAW_VERTEX_STATE)
851       return 0;
852 
853    if (indirect) {
854       return indirect->buffer ||
855              (instance_count > 1 && indirect->count_from_stream_output);
856    } else {
857       return instance_count > 1 &&
858              si_num_prims_for_vertices(prim, min_vertex_count, vertices_per_patch) < num_prims;
859    }
860 }
861 
862 template <amd_gfx_level GFX_VERSION, si_has_tess HAS_TESS, si_has_gs HAS_GS,
863           si_is_draw_vertex_state IS_DRAW_VERTEX_STATE> ALWAYS_INLINE
si_get_ia_multi_vgt_param(struct si_context * sctx,const struct pipe_draw_indirect_info * indirect,enum mesa_prim prim,unsigned instance_count,bool primitive_restart,unsigned min_vertex_count)864 static unsigned si_get_ia_multi_vgt_param(struct si_context *sctx,
865                                           const struct pipe_draw_indirect_info *indirect,
866                                           enum mesa_prim prim, unsigned instance_count,
867                                           bool primitive_restart, unsigned min_vertex_count)
868 {
869    union si_vgt_param_key key = sctx->ia_multi_vgt_param_key;
870    unsigned primgroup_size;
871    unsigned ia_multi_vgt_param;
872 
873    if (HAS_TESS) {
874       primgroup_size = sctx->num_patches_per_workgroup;
875    } else if (HAS_GS) {
876       primgroup_size = 64; /* recommended with a GS */
877    } else {
878       primgroup_size = 128; /* recommended without a GS and tess */
879    }
880 
881    key.u.prim = prim;
882    key.u.uses_instancing = !IS_DRAW_VERTEX_STATE &&
883                            ((indirect && indirect->buffer) || instance_count > 1);
884    if (GFX_VERSION == GFX7 || GFX_VERSION == GFX8) {
885       key.u.multi_instances_smaller_than_primgroup =
886          num_instanced_prims_less_than<IS_DRAW_VERTEX_STATE>(indirect, prim, min_vertex_count,
887                                                              instance_count, primgroup_size,
888                                                              sctx->patch_vertices);
889    } else {
890       key.u.multi_instances_smaller_than_primgroup = 0;
891    }
892    key.u.primitive_restart = !IS_DRAW_VERTEX_STATE && primitive_restart;
893    key.u.count_from_stream_output = !IS_DRAW_VERTEX_STATE && indirect &&
894                                     indirect->count_from_stream_output;
895    key.u.line_stipple_enabled = si_is_line_stipple_enabled(sctx);
896 
897    ia_multi_vgt_param =
898       sctx->ia_multi_vgt_param[key.index] | S_028AA8_PRIMGROUP_SIZE(primgroup_size - 1);
899 
900    if (HAS_GS) {
901       /* GS requirement. */
902       if (GFX_VERSION <= GFX8 &&
903           SI_GS_PER_ES / primgroup_size >= sctx->screen->gs_table_depth - 3)
904          ia_multi_vgt_param |= S_028AA8_PARTIAL_ES_WAVE_ON(1);
905 
906       /* GS hw bug with single-primitive instances and SWITCH_ON_EOI.
907        * The hw doc says all multi-SE chips are affected, but Vulkan
908        * only applies it to Hawaii. Do what Vulkan does.
909        */
910       if (GFX_VERSION == GFX7 &&
911           sctx->family == CHIP_HAWAII && G_028AA8_SWITCH_ON_EOI(ia_multi_vgt_param) &&
912           num_instanced_prims_less_than<IS_DRAW_VERTEX_STATE>(indirect, prim, min_vertex_count,
913                                                               instance_count, 2, sctx->patch_vertices)) {
914          /* The cache flushes should have been emitted already. */
915          assert(sctx->barrier_flags == 0);
916          sctx->barrier_flags = SI_BARRIER_EVENT_VGT_FLUSH;
917          si_emit_barrier_direct(sctx);
918       }
919    }
920 
921    return ia_multi_vgt_param;
922 }
923 
924 /* rast_prim is the primitive type after GS. */
925 template<amd_gfx_level GFX_VERSION, si_has_gs HAS_GS, si_has_ngg NGG> ALWAYS_INLINE
si_emit_rasterizer_prim_state(struct si_context * sctx)926 static void si_emit_rasterizer_prim_state(struct si_context *sctx)
927 {
928    struct radeon_cmdbuf *cs = &sctx->gfx_cs;
929 
930    radeon_begin(cs);
931 
932    if (unlikely(si_is_line_stipple_enabled(sctx))) {
933       /* For lines, reset the stipple pattern at each primitive. Otherwise,
934        * reset the stipple pattern at each packet (line strips, line loops).
935        */
936       enum mesa_prim rast_prim = sctx->current_rast_prim;
937       bool reset_per_prim = rast_prim == MESA_PRIM_LINES ||
938                             rast_prim == MESA_PRIM_LINES_ADJACENCY;
939       /* 0 = no reset, 1 = reset per prim, 2 = reset per packet */
940       if (GFX_VERSION >= GFX12) {
941          radeon_opt_set_context_reg(R_028A44_PA_SC_LINE_STIPPLE_RESET,
942                                     SI_TRACKED_PA_SC_LINE_STIPPLE_RESET,
943                                     S_028A44_AUTO_RESET_CNTL(reset_per_prim ? 1 : 2));
944       } else {
945          struct si_state_rasterizer *rs = sctx->queued.named.rasterizer;
946 
947          radeon_opt_set_context_reg(R_028A0C_PA_SC_LINE_STIPPLE,
948                                     SI_TRACKED_PA_SC_LINE_STIPPLE,
949                                     rs->pa_sc_line_stipple |
950                                     S_028A0C_AUTO_RESET_CNTL(reset_per_prim ? 1 : 2));
951       }
952    }
953 
954    if (NGG || HAS_GS) {
955       if (GFX_VERSION >= GFX11) {
956          radeon_opt_set_uconfig_reg(R_030998_VGT_GS_OUT_PRIM_TYPE,
957                                     SI_TRACKED_VGT_GS_OUT_PRIM_TYPE_UCONFIG, sctx->gs_out_prim);
958       } else {
959          radeon_opt_set_context_reg(R_028A6C_VGT_GS_OUT_PRIM_TYPE,
960                                     SI_TRACKED_VGT_GS_OUT_PRIM_TYPE, sctx->gs_out_prim);
961       }
962    }
963 
964    if (GFX_VERSION == GFX9)
965       radeon_end_update_context_roll();
966    else
967       radeon_end();
968 }
969 
970 template <amd_gfx_level GFX_VERSION, si_has_tess HAS_TESS, si_has_gs HAS_GS, si_has_ngg NGG,
971           si_is_draw_vertex_state IS_DRAW_VERTEX_STATE, si_has_sh_pairs_packed HAS_SH_PAIRS_PACKED> ALWAYS_INLINE
si_emit_vs_state(struct si_context * sctx,unsigned index_size)972 static void si_emit_vs_state(struct si_context *sctx, unsigned index_size)
973 {
974    if (!IS_DRAW_VERTEX_STATE && sctx->num_vs_blit_sgprs) {
975       /* Re-emit the state after we leave u_blitter. */
976       sctx->last_vs_state = ~0;
977       sctx->last_gs_state = ~0;
978       return;
979    }
980 
981    unsigned vs_state = sctx->current_vs_state; /* all VS bits */
982    unsigned gs_state = sctx->current_gs_state; /* only GS and NGG bits; VS bits will be copied here */
983 
984    if (sctx->shader.vs.cso->info.uses_base_vertex && index_size)
985       vs_state |= ENCODE_FIELD(VS_STATE_INDEXED, 1);
986 
987    /* Copy all state bits from vs_state to gs_state. */
988    gs_state |= vs_state;
989 
990    if (vs_state != sctx->last_vs_state ||
991        ((HAS_GS || NGG) && gs_state != sctx->last_gs_state)) {
992       struct radeon_cmdbuf *cs = &sctx->gfx_cs;
993 
994       /* These are all constant expressions. */
995       unsigned vs_base = si_get_user_data_base(GFX_VERSION, HAS_TESS, HAS_GS, NGG,
996                                                PIPE_SHADER_VERTEX);
997       unsigned tes_base = si_get_user_data_base(GFX_VERSION, HAS_TESS, HAS_GS, NGG,
998                                                 PIPE_SHADER_TESS_EVAL);
999       unsigned gs_base = si_get_user_data_base(GFX_VERSION, HAS_TESS, HAS_GS, NGG,
1000                                                PIPE_SHADER_GEOMETRY);
1001       unsigned gs_copy_base = R_00B130_SPI_SHADER_USER_DATA_VS_0;
1002 
1003       radeon_begin(cs);
1004       if (HAS_GS) {
1005          radeon_set_or_push_gfx_sh_reg(vs_base + SI_SGPR_VS_STATE_BITS * 4, vs_state);
1006 
1007          /* GS always uses the state bits for emulating VGT_ESGS_RING_ITEMSIZE on Gfx9
1008           * (via nir_load_esgs_vertex_stride_amd) and for emulating GS pipeline statistics
1009           * on gfx10.x. NGG GS also has lots of states in there.
1010           */
1011          if (GFX_VERSION >= GFX9)
1012             radeon_set_or_push_gfx_sh_reg(gs_base + SI_SGPR_VS_STATE_BITS * 4, gs_state);
1013 
1014          /* The GS copy shader (for legacy GS) always uses the state bits. */
1015          if (!NGG)
1016             radeon_set_or_push_gfx_sh_reg(gs_copy_base + SI_SGPR_VS_STATE_BITS * 4, gs_state);
1017       } else if (HAS_TESS) {
1018          radeon_set_or_push_gfx_sh_reg(vs_base + SI_SGPR_VS_STATE_BITS * 4, vs_state);
1019          radeon_set_or_push_gfx_sh_reg(tes_base + SI_SGPR_VS_STATE_BITS * 4, NGG ? gs_state : vs_state);
1020       } else {
1021          radeon_set_or_push_gfx_sh_reg(vs_base + SI_SGPR_VS_STATE_BITS * 4, NGG ? gs_state : vs_state);
1022       }
1023       radeon_end();
1024 
1025       sctx->last_vs_state = vs_state;
1026       if (HAS_GS || NGG)
1027          sctx->last_gs_state = gs_state;
1028    }
1029 }
1030 
1031 template <amd_gfx_level GFX_VERSION> ALWAYS_INLINE
si_prim_restart_index_changed(struct si_context * sctx,unsigned index_size,bool primitive_restart,unsigned restart_index)1032 static bool si_prim_restart_index_changed(struct si_context *sctx, unsigned index_size,
1033                                           bool primitive_restart, unsigned restart_index)
1034 {
1035    if (!primitive_restart)
1036       return false;
1037 
1038    if (sctx->last_restart_index == SI_RESTART_INDEX_UNKNOWN)
1039       return true;
1040 
1041    /* GFX8+ only compares the index type number of bits of the restart index, so the unused bits
1042     * are "don't care".
1043     *
1044     * Summary of restart index comparator behavior:
1045     * - GFX6-7: Compare all bits.
1046     * - GFX8: Only compare index type bits.
1047     * - GFX9+: If MATCH_ALL_BITS, compare all bits, else only compare index type bits.
1048     */
1049    if (GFX_VERSION >= GFX8) {
1050       /* This masking eliminates no-op 0xffffffff -> 0xffff restart index changes that cause
1051        * unnecessary context rolls when switching the index type.
1052        */
1053       unsigned index_mask = BITFIELD_MASK(index_size * 8);
1054       return (restart_index & index_mask) != (sctx->last_restart_index & index_mask);
1055    } else {
1056       return restart_index != sctx->last_restart_index;
1057    }
1058 }
1059 
1060 template <amd_gfx_level GFX_VERSION, si_has_tess HAS_TESS, si_has_gs HAS_GS,
1061           si_is_draw_vertex_state IS_DRAW_VERTEX_STATE> ALWAYS_INLINE
si_emit_ia_multi_vgt_param(struct si_context * sctx,const struct pipe_draw_indirect_info * indirect,enum mesa_prim prim,unsigned instance_count,bool primitive_restart,unsigned min_vertex_count)1062 static void si_emit_ia_multi_vgt_param(struct si_context *sctx,
1063                                        const struct pipe_draw_indirect_info *indirect,
1064                                        enum mesa_prim prim, unsigned instance_count,
1065                                        bool primitive_restart, unsigned min_vertex_count)
1066 {
1067    struct radeon_cmdbuf *cs = &sctx->gfx_cs;
1068    unsigned ia_multi_vgt_param;
1069 
1070    ia_multi_vgt_param =
1071       si_get_ia_multi_vgt_param<GFX_VERSION, HAS_TESS, HAS_GS, IS_DRAW_VERTEX_STATE>
1072          (sctx, indirect, prim, instance_count, primitive_restart, min_vertex_count);
1073 
1074    radeon_begin(cs);
1075    if (GFX_VERSION == GFX9) {
1076       /* Workaround for SpecviewPerf13 Catia hang on GFX9. */
1077       if (prim != sctx->last_prim)
1078          BITSET_CLEAR(sctx->tracked_regs.reg_saved_mask, SI_TRACKED_IA_MULTI_VGT_PARAM_UCONFIG);
1079 
1080       radeon_opt_set_uconfig_reg_idx(R_030960_IA_MULTI_VGT_PARAM,
1081                                      SI_TRACKED_IA_MULTI_VGT_PARAM_UCONFIG,
1082                                      4, ia_multi_vgt_param);
1083    } else if (GFX_VERSION >= GFX7) {
1084       radeon_opt_set_context_reg_idx(R_028AA8_IA_MULTI_VGT_PARAM,
1085                                      SI_TRACKED_IA_MULTI_VGT_PARAM, 1, ia_multi_vgt_param);
1086    } else {
1087       radeon_opt_set_context_reg(R_028AA8_IA_MULTI_VGT_PARAM,
1088                                  SI_TRACKED_IA_MULTI_VGT_PARAM, ia_multi_vgt_param);
1089    }
1090    radeon_end();
1091 }
1092 
1093 template <amd_gfx_level GFX_VERSION, si_has_tess HAS_TESS, si_has_gs HAS_GS, si_has_ngg NGG,
1094           si_is_draw_vertex_state IS_DRAW_VERTEX_STATE> ALWAYS_INLINE
si_emit_draw_registers(struct si_context * sctx,const struct pipe_draw_indirect_info * indirect,enum mesa_prim prim,unsigned index_size,unsigned instance_count,bool primitive_restart,unsigned restart_index,unsigned min_vertex_count)1095 static void si_emit_draw_registers(struct si_context *sctx,
1096                                    const struct pipe_draw_indirect_info *indirect,
1097                                    enum mesa_prim prim, unsigned index_size,
1098                                    unsigned instance_count, bool primitive_restart,
1099                                    unsigned restart_index, unsigned min_vertex_count)
1100 {
1101    struct radeon_cmdbuf *cs = &sctx->gfx_cs;
1102 
1103    if (GFX_VERSION <= GFX9) {
1104       si_emit_ia_multi_vgt_param<GFX_VERSION, HAS_TESS, HAS_GS, IS_DRAW_VERTEX_STATE>
1105          (sctx, indirect, prim, instance_count, primitive_restart, min_vertex_count);
1106    }
1107 
1108    radeon_begin(cs);
1109 
1110    if (prim != sctx->last_prim) {
1111       unsigned vgt_prim = HAS_TESS ? V_008958_DI_PT_PATCH : si_conv_pipe_prim(prim);
1112 
1113       if (GFX_VERSION >= GFX12 && HAS_TESS)
1114          vgt_prim |= S_030908_NUM_INPUT_CP(sctx->patch_vertices);
1115 
1116       if (GFX_VERSION >= GFX10)
1117          radeon_set_uconfig_reg(R_030908_VGT_PRIMITIVE_TYPE, vgt_prim);
1118       else if (GFX_VERSION >= GFX7)
1119          radeon_set_uconfig_reg_idx(R_030908_VGT_PRIMITIVE_TYPE, 1, vgt_prim);
1120       else
1121          radeon_set_config_reg(R_008958_VGT_PRIMITIVE_TYPE, vgt_prim);
1122 
1123       sctx->last_prim = prim;
1124    }
1125 
1126    /* Primitive restart. */
1127    if (GFX_VERSION >= GFX11) {
1128       /* GFX11+ can ignore primitive restart for non-indexed draws because it has no effect.
1129        * (it's disabled for non-indexed draws by setting DISABLE_FOR_AUTO_INDEX in the preamble)
1130        */
1131       if (index_size) {
1132          if (primitive_restart != sctx->last_primitive_restart_en) {
1133             radeon_set_uconfig_reg(R_03092C_GE_MULTI_PRIM_IB_RESET_EN,
1134                                    S_03092C_RESET_EN(primitive_restart) |
1135                                    /* This disables primitive restart for non-indexed draws.
1136                                     * By keeping this set, we don't have to unset RESET_EN
1137                                     * for non-indexed draws. */
1138                                    S_03092C_DISABLE_FOR_AUTO_INDEX(1));
1139             sctx->last_primitive_restart_en = primitive_restart;
1140          }
1141          if (si_prim_restart_index_changed<GFX_VERSION>(sctx, index_size, primitive_restart,
1142                                                         restart_index)) {
1143             radeon_set_context_reg(R_02840C_VGT_MULTI_PRIM_IB_RESET_INDX, restart_index);
1144             sctx->last_restart_index = restart_index;
1145          }
1146       }
1147    } else {
1148       if (primitive_restart != sctx->last_primitive_restart_en) {
1149          if (GFX_VERSION >= GFX9)
1150             radeon_set_uconfig_reg(R_03092C_VGT_MULTI_PRIM_IB_RESET_EN, primitive_restart);
1151          else
1152             radeon_set_context_reg(R_028A94_VGT_MULTI_PRIM_IB_RESET_EN, primitive_restart);
1153          sctx->last_primitive_restart_en = primitive_restart;
1154       }
1155       if (si_prim_restart_index_changed<GFX_VERSION>(sctx, index_size, primitive_restart,
1156                                                      restart_index)) {
1157          radeon_set_context_reg(R_02840C_VGT_MULTI_PRIM_IB_RESET_INDX, restart_index);
1158          sctx->last_restart_index = restart_index;
1159          if (GFX_VERSION == GFX9)
1160             sctx->context_roll = true;
1161       }
1162    }
1163    radeon_end();
1164 }
1165 
1166 static ALWAYS_INLINE void
gfx11_emit_buffered_sh_regs_inline(struct si_context * sctx,unsigned * num_regs,struct gfx11_reg_pair * reg_pairs)1167 gfx11_emit_buffered_sh_regs_inline(struct si_context *sctx, unsigned *num_regs,
1168                                    struct gfx11_reg_pair *reg_pairs)
1169 {
1170    unsigned reg_count = *num_regs;
1171 
1172    if (!reg_count)
1173       return;
1174 
1175    *num_regs = 0;
1176 
1177    /* If there is only one register, we can't use the packed SET packet. */
1178    if (reg_count == 1) {
1179       radeon_begin(&sctx->gfx_cs);
1180       radeon_emit(PKT3(PKT3_SET_SH_REG, 1, 0));
1181       radeon_emit(reg_pairs[0].reg_offset[0]);
1182       radeon_emit(reg_pairs[0].reg_value[0]);
1183       radeon_end();
1184       return;
1185    }
1186 
1187    unsigned packet = reg_count <= 14 ? PKT3_SET_SH_REG_PAIRS_PACKED_N :
1188                                        PKT3_SET_SH_REG_PAIRS_PACKED;
1189    unsigned padded_reg_count = align(reg_count, 2);
1190 
1191    radeon_begin(&sctx->gfx_cs);
1192    radeon_emit(PKT3(packet, (padded_reg_count / 2) * 3, 0) | PKT3_RESET_FILTER_CAM_S(1));
1193    radeon_emit(padded_reg_count);
1194    radeon_emit_array(reg_pairs, (reg_count / 2) * 3);
1195 
1196    if (reg_count % 2 == 1) {
1197       unsigned i = reg_count / 2;
1198 
1199       /* Pad the packet by setting the first register again at the end because the register
1200        * count must be even and 2 consecutive offsets must not be equal.
1201        */
1202       radeon_emit(reg_pairs[i].reg_offset[0] | ((uint32_t)reg_pairs[0].reg_offset[0] << 16));
1203       radeon_emit(reg_pairs[i].reg_value[0]);
1204       radeon_emit(reg_pairs[0].reg_value[0]);
1205    }
1206    radeon_end();
1207 }
1208 
1209 #define gfx12_emit_buffered_sh_regs_inline(num_regs, regs) do { \
1210    unsigned __reg_count = *(num_regs); \
1211    if (__reg_count) { \
1212       radeon_emit(PKT3(PKT3_SET_SH_REG_PAIRS, __reg_count * 2 - 1, 0) | PKT3_RESET_FILTER_CAM_S(1)); \
1213       radeon_emit_array(regs, __reg_count * 2); \
1214       *(num_regs) = 0; \
1215    } \
1216 } while (0)
1217 
1218 #if GFX_VER == 6 /* declare this function only once because there is only one variant. */
1219 
si_emit_buffered_compute_sh_regs(struct si_context * sctx)1220 void si_emit_buffered_compute_sh_regs(struct si_context *sctx)
1221 {
1222    if (sctx->gfx_level >= GFX12) {
1223       radeon_begin(&sctx->gfx_cs);
1224       gfx12_emit_buffered_sh_regs_inline(&sctx->num_buffered_compute_sh_regs,
1225                                          sctx->gfx12.buffered_compute_sh_regs);
1226       radeon_end();
1227    } else {
1228       gfx11_emit_buffered_sh_regs_inline(sctx, &sctx->num_buffered_compute_sh_regs,
1229                                          sctx->gfx11.buffered_compute_sh_regs);
1230    }
1231 }
1232 
1233 #endif
1234 
1235 template <amd_gfx_level GFX_VERSION, si_has_tess HAS_TESS, si_has_gs HAS_GS, si_has_ngg NGG,
1236           si_is_draw_vertex_state IS_DRAW_VERTEX_STATE, si_has_sh_pairs_packed HAS_SH_PAIRS_PACKED,
1237           si_alt_hiz_logic ALT_HIZ_LOGIC> ALWAYS_INLINE
si_emit_draw_packets(struct si_context * sctx,const struct pipe_draw_info * info,unsigned drawid_base,const struct pipe_draw_indirect_info * indirect,const struct pipe_draw_start_count_bias * draws,unsigned num_draws,struct pipe_resource * indexbuf,unsigned index_size,unsigned index_offset,unsigned instance_count)1238 static void si_emit_draw_packets(struct si_context *sctx, const struct pipe_draw_info *info,
1239                                  unsigned drawid_base,
1240                                  const struct pipe_draw_indirect_info *indirect,
1241                                  const struct pipe_draw_start_count_bias *draws,
1242                                  unsigned num_draws,
1243                                  struct pipe_resource *indexbuf, unsigned index_size,
1244                                  unsigned index_offset, unsigned instance_count)
1245 {
1246    struct radeon_cmdbuf *cs = &sctx->gfx_cs;
1247 
1248    if (unlikely(sctx->sqtt_enabled)) {
1249       si_sqtt_write_event_marker(sctx, &sctx->gfx_cs, sctx->sqtt_next_event,
1250                                  UINT_MAX, UINT_MAX, UINT_MAX);
1251    }
1252 
1253    uint32_t use_opaque = 0;
1254 
1255    if (!IS_DRAW_VERTEX_STATE && indirect && indirect->count_from_stream_output) {
1256       struct si_streamout_target *t = (struct si_streamout_target *)indirect->count_from_stream_output;
1257 
1258       radeon_begin(cs);
1259       radeon_set_context_reg(R_028B30_VGT_STRMOUT_DRAW_OPAQUE_VERTEX_STRIDE, t->stride);
1260       radeon_end();
1261 
1262       if (GFX_VERSION >= GFX9) {
1263          /* Use PKT3_LOAD_CONTEXT_REG_INDEX instead of si_cp_copy_data to support state shadowing. */
1264          uint64_t va = t->buf_filled_size->gpu_address + t->buf_filled_size_draw_count_offset;
1265 
1266          radeon_begin(cs);
1267 
1268          // TODO: GFX12: This may be discarded by PFP if the shadow base address is provided by the MQD.
1269          radeon_emit(PKT3(PKT3_LOAD_CONTEXT_REG_INDEX, 3, 0));
1270          radeon_emit(va);
1271          radeon_emit(va >> 32);
1272          radeon_emit((R_028B2C_VGT_STRMOUT_DRAW_OPAQUE_BUFFER_FILLED_SIZE - SI_CONTEXT_REG_OFFSET) >> 2);
1273          radeon_emit(1);
1274 
1275          radeon_end();
1276       } else {
1277          si_cp_copy_data(sctx, &sctx->gfx_cs, COPY_DATA_REG, NULL,
1278                          R_028B2C_VGT_STRMOUT_DRAW_OPAQUE_BUFFER_FILLED_SIZE >> 2, COPY_DATA_SRC_MEM,
1279                          t->buf_filled_size, t->buf_filled_size_draw_count_offset);
1280       }
1281       use_opaque = S_0287F0_USE_OPAQUE(1);
1282       indirect = NULL;
1283    }
1284 
1285    uint32_t index_max_size = 0;
1286    uint64_t index_va = 0;
1287    bool disable_instance_packing = false;
1288 
1289    radeon_begin(cs);
1290 
1291    if (GFX_VERSION == GFX10_3) {
1292       /* Workaround for incorrect stats with adjacent primitive types
1293        * (see PAL's waDisableInstancePacking).
1294        */
1295       if (sctx->num_pipeline_stat_queries &&
1296           sctx->shader.gs.cso == NULL &&
1297           (instance_count > 1 || indirect) &&
1298           (1 << info->mode) & (1 << MESA_PRIM_LINES_ADJACENCY |
1299                                1 << MESA_PRIM_LINE_STRIP_ADJACENCY |
1300                                1 << MESA_PRIM_TRIANGLES_ADJACENCY |
1301                                1 << MESA_PRIM_TRIANGLE_STRIP_ADJACENCY)) {
1302          disable_instance_packing = true;
1303       }
1304    }
1305 
1306    /* draw packet */
1307    if (index_size) {
1308       /* Register shadowing doesn't shadow INDEX_TYPE. */
1309       if (index_size != sctx->last_index_size ||
1310           (GFX_VERSION == GFX10_3 && disable_instance_packing != sctx->disable_instance_packing)) {
1311          unsigned index_type;
1312 
1313          /* Index type computation. When we look at how we need to translate index_size,
1314           * we can see that we just need 2 shifts to get the hw value.
1315           *
1316           * 1 = 001b --> 10b = 2
1317           * 2 = 010b --> 00b = 0
1318           * 4 = 100b --> 01b = 1
1319           */
1320          index_type = (((index_size >> 2) | (index_size << 1)) & 0x3) |
1321                       S_028A7C_DISABLE_INSTANCE_PACKING(disable_instance_packing);
1322 
1323          if (GFX_VERSION <= GFX7 && UTIL_ARCH_BIG_ENDIAN) {
1324             /* GFX7 doesn't support ubyte indices. */
1325             index_type |= index_size == 2 ? V_028A7C_VGT_DMA_SWAP_16_BIT
1326                                           : V_028A7C_VGT_DMA_SWAP_32_BIT;
1327          }
1328 
1329          if (GFX_VERSION >= GFX9) {
1330             radeon_set_uconfig_reg_idx(R_03090C_VGT_INDEX_TYPE, 2, index_type);
1331          } else {
1332             radeon_emit(PKT3(PKT3_INDEX_TYPE, 0, 0));
1333             radeon_emit(index_type);
1334          }
1335 
1336          sctx->last_index_size = index_size;
1337          if (GFX_VERSION == GFX10_3)
1338             sctx->disable_instance_packing = disable_instance_packing;
1339       }
1340 
1341       index_max_size = (indexbuf->width0 - index_offset) >> util_logbase2(index_size);
1342       /* Skip draw calls with 0-sized index buffers.
1343        * They cause a hang on some chips, like Navi10-14.
1344        */
1345       if (!index_max_size) {
1346          radeon_end();
1347          return;
1348       }
1349 
1350       index_va = si_resource(indexbuf)->gpu_address + index_offset;
1351 
1352       radeon_add_to_buffer_list(sctx, &sctx->gfx_cs, si_resource(indexbuf),
1353                                 RADEON_USAGE_READ | RADEON_PRIO_INDEX_BUFFER);
1354    } else {
1355       /* On GFX7 and later, non-indexed draws overwrite VGT_INDEX_TYPE,
1356        * so the state must be re-emitted before the next indexed draw.
1357        */
1358       if (GFX_VERSION >= GFX7)
1359          sctx->last_index_size = -1;
1360       if (GFX_VERSION == GFX10_3 && disable_instance_packing != sctx->disable_instance_packing) {
1361          radeon_set_uconfig_reg_idx(R_03090C_VGT_INDEX_TYPE, 2,
1362                                     S_028A7C_DISABLE_INSTANCE_PACKING(disable_instance_packing));
1363          sctx->disable_instance_packing = disable_instance_packing;
1364       }
1365    }
1366 
1367    unsigned sh_base_reg = si_get_user_data_base(GFX_VERSION, HAS_TESS, HAS_GS, NGG,
1368                                                 PIPE_SHADER_VERTEX);
1369    bool render_cond_bit = sctx->render_cond_enabled;
1370    const unsigned tracked_base_vertex_reg =
1371       HAS_TESS ? SI_TRACKED_SPI_SHADER_USER_DATA_LS__BASE_VERTEX :
1372       HAS_GS || NGG ? SI_TRACKED_SPI_SHADER_USER_DATA_ES__BASE_VERTEX :
1373       SI_TRACKED_SPI_SHADER_USER_DATA_VS__BASE_VERTEX;
1374 
1375    if (!IS_DRAW_VERTEX_STATE && indirect) {
1376       assert(num_draws == 1);
1377       uint64_t indirect_va = si_resource(indirect->buffer)->gpu_address;
1378 
1379       assert(indirect_va % 8 == 0);
1380 
1381       if (GFX_VERSION >= GFX12) {
1382          gfx12_emit_buffered_sh_regs_inline(&sctx->num_buffered_gfx_sh_regs,
1383                                             sctx->gfx12.buffered_gfx_sh_regs);
1384       } else if (HAS_SH_PAIRS_PACKED) {
1385          radeon_end();
1386          gfx11_emit_buffered_sh_regs_inline(sctx, &sctx->num_buffered_gfx_sh_regs,
1387                                             sctx->gfx11.buffered_gfx_sh_regs);
1388          radeon_begin_again(cs);
1389       }
1390 
1391       /* Invalidate tracked draw constants because DrawIndirect overwrites them. */
1392       BITSET_CLEAR(sctx->tracked_regs.reg_saved_mask, tracked_base_vertex_reg); /* BaseVertex */
1393       BITSET_CLEAR(sctx->tracked_regs.reg_saved_mask, tracked_base_vertex_reg + 1); /* DrawID */
1394       BITSET_CLEAR(sctx->tracked_regs.reg_saved_mask, tracked_base_vertex_reg + 2); /* StartInstance */
1395       sctx->last_instance_count = SI_INSTANCE_COUNT_UNKNOWN;
1396 
1397       radeon_emit(PKT3(PKT3_SET_BASE, 2, 0));
1398       radeon_emit(1);
1399       radeon_emit(indirect_va);
1400       radeon_emit(indirect_va >> 32);
1401 
1402       radeon_add_to_buffer_list(sctx, &sctx->gfx_cs, si_resource(indirect->buffer),
1403                                 RADEON_USAGE_READ | RADEON_PRIO_DRAW_INDIRECT);
1404 
1405       unsigned di_src_sel = index_size ? V_0287F0_DI_SRC_SEL_DMA : V_0287F0_DI_SRC_SEL_AUTO_INDEX;
1406 
1407       assert(indirect->offset % 4 == 0);
1408 
1409       if (index_size) {
1410          radeon_emit(PKT3(PKT3_INDEX_BASE, 1, 0));
1411          radeon_emit(index_va);
1412          radeon_emit(index_va >> 32);
1413 
1414          radeon_emit(PKT3(PKT3_INDEX_BUFFER_SIZE, 0, 0));
1415          radeon_emit(index_max_size);
1416       }
1417 
1418       if (!sctx->screen->has_draw_indirect_multi) {
1419          radeon_emit(PKT3(index_size ? PKT3_DRAW_INDEX_INDIRECT : PKT3_DRAW_INDIRECT, 3,
1420                           render_cond_bit));
1421          radeon_emit(indirect->offset);
1422          radeon_emit((sh_base_reg + SI_SGPR_BASE_VERTEX * 4 - SI_SH_REG_OFFSET) >> 2);
1423          radeon_emit((sh_base_reg + SI_SGPR_START_INSTANCE * 4 - SI_SH_REG_OFFSET) >> 2);
1424          radeon_emit(di_src_sel);
1425 
1426          radeon_emit_alt_hiz_logic();
1427       } else {
1428          uint64_t count_va = 0;
1429 
1430          if (indirect->indirect_draw_count) {
1431             struct si_resource *params_buf = si_resource(indirect->indirect_draw_count);
1432 
1433             radeon_add_to_buffer_list(sctx, &sctx->gfx_cs, params_buf,
1434                                       RADEON_USAGE_READ | RADEON_PRIO_DRAW_INDIRECT);
1435 
1436             count_va = params_buf->gpu_address + indirect->indirect_draw_count_offset;
1437          }
1438 
1439          radeon_emit(PKT3(index_size ? PKT3_DRAW_INDEX_INDIRECT_MULTI : PKT3_DRAW_INDIRECT_MULTI, 8,
1440                           render_cond_bit));
1441          radeon_emit(indirect->offset);
1442          radeon_emit((sh_base_reg + SI_SGPR_BASE_VERTEX * 4 - SI_SH_REG_OFFSET) >> 2);
1443          radeon_emit((sh_base_reg + SI_SGPR_START_INSTANCE * 4 - SI_SH_REG_OFFSET) >> 2);
1444          radeon_emit(((sh_base_reg + SI_SGPR_DRAWID * 4 - SI_SH_REG_OFFSET) >> 2) |
1445                      S_2C3_DRAW_INDEX_ENABLE(sctx->shader.vs.cso->info.uses_drawid) |
1446                      S_2C3_COUNT_INDIRECT_ENABLE(!!indirect->indirect_draw_count));
1447          radeon_emit(indirect->draw_count);
1448          radeon_emit(count_va);
1449          radeon_emit(count_va >> 32);
1450          radeon_emit(indirect->stride);
1451          radeon_emit(di_src_sel);
1452 
1453          radeon_emit_alt_hiz_logic();
1454       }
1455    } else {
1456       if (sctx->last_instance_count == SI_INSTANCE_COUNT_UNKNOWN ||
1457           sctx->last_instance_count != instance_count) {
1458          radeon_emit(PKT3(PKT3_NUM_INSTANCES, 0, 0));
1459          radeon_emit(instance_count);
1460          sctx->last_instance_count = instance_count;
1461       }
1462 
1463       /* Base vertex and start instance. */
1464       int base_vertex = index_size ? draws[0].index_bias : draws[0].start;
1465 
1466       bool set_draw_id = !IS_DRAW_VERTEX_STATE && sctx->vs_uses_draw_id;
1467       bool set_base_instance = sctx->vs_uses_base_instance;
1468       bool is_blit = !IS_DRAW_VERTEX_STATE && sctx->num_vs_blit_sgprs;
1469 
1470       if (!is_blit) {
1471          /* Prefer SET_SH_REG_PAIRS_PACKED* on Gfx11+. */
1472          if (GFX_VERSION >= GFX12) {
1473             gfx12_opt_push_gfx_sh_reg(sh_base_reg + SI_SGPR_BASE_VERTEX * 4,
1474                                       tracked_base_vertex_reg, base_vertex);
1475             if (set_draw_id) {
1476                gfx12_opt_push_gfx_sh_reg(sh_base_reg + SI_SGPR_DRAWID * 4,
1477                                          tracked_base_vertex_reg + 1, drawid_base);
1478             }
1479             if (set_base_instance) {
1480                gfx12_opt_push_gfx_sh_reg(sh_base_reg + SI_SGPR_START_INSTANCE * 4,
1481                                          tracked_base_vertex_reg + 2, info->start_instance);
1482             }
1483          } else if (HAS_SH_PAIRS_PACKED) {
1484             gfx11_opt_push_gfx_sh_reg(sh_base_reg + SI_SGPR_BASE_VERTEX * 4,
1485                                       tracked_base_vertex_reg, base_vertex);
1486             if (set_draw_id) {
1487                gfx11_opt_push_gfx_sh_reg(sh_base_reg + SI_SGPR_DRAWID * 4,
1488                                          tracked_base_vertex_reg + 1, drawid_base);
1489             }
1490             if (set_base_instance) {
1491                gfx11_opt_push_gfx_sh_reg(sh_base_reg + SI_SGPR_START_INSTANCE * 4,
1492                                          tracked_base_vertex_reg + 2, info->start_instance);
1493             }
1494          } else {
1495             if (set_base_instance) {
1496                radeon_opt_set_sh_reg3(sh_base_reg + SI_SGPR_BASE_VERTEX * 4,
1497                                       tracked_base_vertex_reg, base_vertex, drawid_base,
1498                                       info->start_instance);
1499             } else if (set_draw_id) {
1500                radeon_opt_set_sh_reg2(sh_base_reg + SI_SGPR_BASE_VERTEX * 4,
1501                                       tracked_base_vertex_reg, base_vertex, drawid_base);
1502             } else {
1503                radeon_opt_set_sh_reg(sh_base_reg + SI_SGPR_BASE_VERTEX * 4,
1504                                      tracked_base_vertex_reg, base_vertex);
1505             }
1506          }
1507       }
1508 
1509       if (GFX_VERSION >= GFX12) {
1510          gfx12_emit_buffered_sh_regs_inline(&sctx->num_buffered_gfx_sh_regs,
1511                                             sctx->gfx12.buffered_gfx_sh_regs);
1512       } else if (HAS_SH_PAIRS_PACKED) {
1513          radeon_end();
1514          gfx11_emit_buffered_sh_regs_inline(sctx, &sctx->num_buffered_gfx_sh_regs,
1515                                             sctx->gfx11.buffered_gfx_sh_regs);
1516          radeon_begin_again(cs);
1517       }
1518 
1519       /* Blit SGPRs must be set after gfx1X_emit_buffered_sh_regs_inline because they can
1520        * overwrite them.
1521        */
1522       if (is_blit) {
1523          /* Re-emit draw constants after we leave u_blitter. */
1524          BITSET_CLEAR(sctx->tracked_regs.reg_saved_mask, tracked_base_vertex_reg); /* BaseVertex */
1525          BITSET_CLEAR(sctx->tracked_regs.reg_saved_mask, tracked_base_vertex_reg + 1); /* DrawID */
1526          BITSET_CLEAR(sctx->tracked_regs.reg_saved_mask, tracked_base_vertex_reg + 2); /* StartInstance */
1527 
1528          /* Blit VS doesn't use BASE_VERTEX, START_INSTANCE, and DRAWID. */
1529          radeon_set_sh_reg_seq(sh_base_reg + SI_SGPR_VS_BLIT_DATA * 4, sctx->num_vs_blit_sgprs);
1530          radeon_emit_array(sctx->vs_blit_sh_data, sctx->num_vs_blit_sgprs);
1531       }
1532 
1533       /* Don't update draw_id in the following code if it doesn't increment. */
1534       bool increment_draw_id = !IS_DRAW_VERTEX_STATE && num_draws > 1 &&
1535                                set_draw_id && info->increment_draw_id;
1536 
1537       if (index_size) {
1538          /* NOT_EOP allows merging multiple draws into 1 wave, but only user VGPRs
1539           * can be changed between draws, and GS fast launch must be disabled.
1540           * NOT_EOP doesn't work on gfx9 and older.
1541           *
1542           * Instead of doing this, which evaluates the case conditions repeatedly:
1543           *  for (all draws) {
1544           *    if (case1);
1545           *    else;
1546           *  }
1547           *
1548           * Use this structuring to evaluate the case conditions once:
1549           *  if (case1) for (all draws);
1550           *  else for (all draws);
1551           *
1552           */
1553          bool index_bias_varies = !IS_DRAW_VERTEX_STATE && num_draws > 1 &&
1554                                   info->index_bias_varies;
1555 
1556          if (increment_draw_id) {
1557             if (index_bias_varies) {
1558                for (unsigned i = 0; i < num_draws; i++) {
1559                   uint64_t va = index_va + draws[i].start * index_size;
1560 
1561                   if (i > 0) {
1562                      radeon_set_sh_reg_seq(sh_base_reg + SI_SGPR_BASE_VERTEX * 4, 2);
1563                      radeon_emit(draws[i].index_bias);
1564                      radeon_emit(drawid_base + i);
1565                   }
1566 
1567                   radeon_emit(PKT3(PKT3_DRAW_INDEX_2, 4, render_cond_bit));
1568                   radeon_emit(index_max_size);
1569                   radeon_emit(va);
1570                   radeon_emit(va >> 32);
1571                   radeon_emit(draws[i].count);
1572                   radeon_emit(V_0287F0_DI_SRC_SEL_DMA); /* NOT_EOP disabled */
1573 
1574                   radeon_emit_alt_hiz_logic();
1575                }
1576                if (num_draws > 1) {
1577                   BITSET_CLEAR(sctx->tracked_regs.reg_saved_mask, tracked_base_vertex_reg); /* BaseVertex */
1578                   BITSET_CLEAR(sctx->tracked_regs.reg_saved_mask, tracked_base_vertex_reg + 1); /* DrawID */
1579                }
1580             } else {
1581                /* Only DrawID varies. */
1582                for (unsigned i = 0; i < num_draws; i++) {
1583                   uint64_t va = index_va + draws[i].start * index_size;
1584 
1585                   if (i > 0)
1586                      radeon_set_sh_reg(sh_base_reg + SI_SGPR_DRAWID * 4, drawid_base + i);
1587 
1588                   radeon_emit(PKT3(PKT3_DRAW_INDEX_2, 4, render_cond_bit));
1589                   radeon_emit(index_max_size);
1590                   radeon_emit(va);
1591                   radeon_emit(va >> 32);
1592                   radeon_emit(draws[i].count);
1593                   radeon_emit(V_0287F0_DI_SRC_SEL_DMA); /* NOT_EOP disabled */
1594 
1595                   radeon_emit_alt_hiz_logic();
1596                }
1597                if (num_draws > 1) {
1598                   BITSET_CLEAR(sctx->tracked_regs.reg_saved_mask, tracked_base_vertex_reg + 1); /* DrawID */
1599                }
1600             }
1601          } else {
1602             if (index_bias_varies) {
1603                /* Only BaseVertex varies. */
1604                for (unsigned i = 0; i < num_draws; i++) {
1605                   uint64_t va = index_va + draws[i].start * index_size;
1606 
1607                   if (i > 0)
1608                      radeon_set_sh_reg(sh_base_reg + SI_SGPR_BASE_VERTEX * 4, draws[i].index_bias);
1609 
1610                   radeon_emit(PKT3(PKT3_DRAW_INDEX_2, 4, render_cond_bit));
1611                   radeon_emit(index_max_size);
1612                   radeon_emit(va);
1613                   radeon_emit(va >> 32);
1614                   radeon_emit(draws[i].count);
1615                   radeon_emit(V_0287F0_DI_SRC_SEL_DMA); /* NOT_EOP disabled */
1616 
1617                   radeon_emit_alt_hiz_logic();
1618                }
1619                if (num_draws > 1) {
1620                   BITSET_CLEAR(sctx->tracked_regs.reg_saved_mask, tracked_base_vertex_reg); /* BaseVertex */
1621                }
1622             } else {
1623                /* DrawID and BaseVertex are constant. */
1624                if (GFX_VERSION == GFX10) {
1625                   /* GFX10 has a bug that consecutive draw packets with NOT_EOP must not have
1626                    * count == 0 in the last draw (which doesn't set NOT_EOP).
1627                    *
1628                    * So remove all trailing draws with count == 0.
1629                    */
1630                   while (num_draws > 1 && !draws[num_draws - 1].count)
1631                      num_draws--;
1632                }
1633 
1634                for (unsigned i = 0; i < num_draws; i++) {
1635                   uint64_t va = index_va + draws[i].start * index_size;
1636 
1637                   radeon_emit(PKT3(PKT3_DRAW_INDEX_2, 4, render_cond_bit));
1638                   radeon_emit(index_max_size);
1639                   radeon_emit(va);
1640                   radeon_emit(va >> 32);
1641                   radeon_emit(draws[i].count);
1642                   radeon_emit(V_0287F0_DI_SRC_SEL_DMA |
1643                               S_0287F0_NOT_EOP(GFX_VERSION >= GFX10 && GFX_VERSION < GFX12 &&
1644                                                i < num_draws - 1));
1645 
1646                   radeon_emit_alt_hiz_logic();
1647                }
1648             }
1649          }
1650       } else {
1651          if (GFX_VERSION == GFX12 && !IS_DRAW_VERTEX_STATE &&
1652              indirect && indirect->count_from_stream_output) {
1653             /* DrawTransformFeedback requires 3 SQ_NON_EVENTs after the packet. */
1654             assert(num_draws == 1);
1655 
1656             radeon_emit(PKT3(PKT3_DRAW_INDEX_AUTO, 1, render_cond_bit));
1657             radeon_emit(0);
1658             radeon_emit(V_0287F0_DI_SRC_SEL_AUTO_INDEX | use_opaque);
1659 
1660             radeon_emit_alt_hiz_logic();
1661             for (unsigned i = 0; i < 3; i++)
1662                radeon_event_write(V_028A90_SQ_NON_EVENT);
1663          } else if (increment_draw_id) {
1664             for (unsigned i = 0; i < num_draws; i++) {
1665                if (i > 0) {
1666                   unsigned draw_id = drawid_base + i;
1667 
1668                   radeon_set_sh_reg_seq(sh_base_reg + SI_SGPR_BASE_VERTEX * 4, 2);
1669                   radeon_emit(draws[i].start);
1670                   radeon_emit(draw_id);
1671                }
1672 
1673                radeon_emit(PKT3(PKT3_DRAW_INDEX_AUTO, 1, render_cond_bit));
1674                radeon_emit(draws[i].count);
1675                radeon_emit(V_0287F0_DI_SRC_SEL_AUTO_INDEX | use_opaque);
1676 
1677                radeon_emit_alt_hiz_logic();
1678             }
1679             if (num_draws > 1 && (IS_DRAW_VERTEX_STATE || !sctx->num_vs_blit_sgprs)) {
1680                BITSET_CLEAR(sctx->tracked_regs.reg_saved_mask, tracked_base_vertex_reg); /* BaseVertex */
1681                BITSET_CLEAR(sctx->tracked_regs.reg_saved_mask, tracked_base_vertex_reg + 1); /* DrawID */
1682             }
1683          } else {
1684             for (unsigned i = 0; i < num_draws; i++) {
1685                if (i > 0)
1686                   radeon_set_sh_reg(sh_base_reg + SI_SGPR_BASE_VERTEX * 4, draws[i].start);
1687 
1688                radeon_emit(PKT3(PKT3_DRAW_INDEX_AUTO, 1, render_cond_bit));
1689                radeon_emit(draws[i].count);
1690                radeon_emit(V_0287F0_DI_SRC_SEL_AUTO_INDEX | use_opaque);
1691 
1692                radeon_emit_alt_hiz_logic();
1693             }
1694             if (num_draws > 1 && (IS_DRAW_VERTEX_STATE || !sctx->num_vs_blit_sgprs)) {
1695                BITSET_CLEAR(sctx->tracked_regs.reg_saved_mask, tracked_base_vertex_reg); /* BaseVertex */
1696             }
1697          }
1698       }
1699    }
1700 
1701    if (GFX_VERSION >= GFX9 && unlikely(sctx->sqtt_enabled))
1702      radeon_event_write(V_028A90_THREAD_TRACE_MARKER);
1703    radeon_end();
1704 }
1705 
1706 /* Return false if not bound. */
1707 template<amd_gfx_level GFX_VERSION>
si_set_vb_descriptor(struct si_vertex_elements * velems,const struct pipe_vertex_buffer * vb,unsigned index,uint32_t * desc)1708 static void ALWAYS_INLINE si_set_vb_descriptor(struct si_vertex_elements *velems,
1709                                                const struct pipe_vertex_buffer *vb,
1710                                                unsigned index, /* vertex element index */
1711                                                uint32_t *desc) /* where to upload descriptors */
1712 {
1713    struct si_resource *buf = si_resource(vb->buffer.resource);
1714    int64_t offset = (int64_t)((int)vb->buffer_offset) + velems->elem[index].src_offset;
1715 
1716    if (!buf || offset >= buf->b.b.width0) {
1717       memset(desc, 0, 16);
1718       return;
1719    }
1720 
1721    uint64_t va = buf->gpu_address + offset;
1722    unsigned stride = velems->elem[index].stride;
1723 
1724    int64_t num_records = (int64_t)buf->b.b.width0 - offset;
1725    if (GFX_VERSION != GFX8 && stride) {
1726       /* Round up by rounding down and adding 1 */
1727       num_records = (num_records - velems->elem[index].format_size) / stride + 1;
1728    }
1729    assert(num_records >= 0 && num_records <= UINT_MAX);
1730 
1731    desc[0] = va;
1732    desc[1] = S_008F04_BASE_ADDRESS_HI(va >> 32) | S_008F04_STRIDE(stride);
1733    desc[2] = num_records;
1734    desc[3] = velems->elem[index].rsrc_word3;
1735 }
1736 
1737 #if GFX_VER == 6 /* declare this function only once because it supports all chips. */
1738 
si_set_vertex_buffer_descriptor(struct si_screen * sscreen,struct si_vertex_elements * velems,const struct pipe_vertex_buffer * vb,unsigned element_index,uint32_t * out)1739 void si_set_vertex_buffer_descriptor(struct si_screen *sscreen, struct si_vertex_elements *velems,
1740                                      const struct pipe_vertex_buffer *vb, unsigned element_index,
1741                                      uint32_t *out)
1742 {
1743    switch (sscreen->info.gfx_level) {
1744    case GFX6:
1745       si_set_vb_descriptor<GFX6>(velems, vb, element_index, out);
1746       break;
1747    case GFX7:
1748       si_set_vb_descriptor<GFX7>(velems, vb, element_index, out);
1749       break;
1750    case GFX8:
1751       si_set_vb_descriptor<GFX8>(velems, vb, element_index, out);
1752       break;
1753    case GFX9:
1754       si_set_vb_descriptor<GFX9>(velems, vb, element_index, out);
1755       break;
1756    case GFX10:
1757       si_set_vb_descriptor<GFX10>(velems, vb, element_index, out);
1758       break;
1759    case GFX10_3:
1760       si_set_vb_descriptor<GFX10_3>(velems, vb, element_index, out);
1761       break;
1762    case GFX11:
1763       si_set_vb_descriptor<GFX11>(velems, vb, element_index, out);
1764       break;
1765    case GFX11_5:
1766       si_set_vb_descriptor<GFX11_5>(velems, vb, element_index, out);
1767       break;
1768    case GFX12:
1769       si_set_vb_descriptor<GFX12>(velems, vb, element_index, out);
1770       break;
1771    default:
1772       unreachable("unhandled gfx level");
1773    }
1774 }
1775 
1776 #endif
1777 
1778 template<util_popcnt POPCNT>
get_next_vertex_state_elem(struct pipe_vertex_state * state,uint32_t * partial_velem_mask)1779 static ALWAYS_INLINE unsigned get_next_vertex_state_elem(struct pipe_vertex_state *state,
1780                                                          uint32_t *partial_velem_mask)
1781 {
1782    unsigned semantic_index = u_bit_scan(partial_velem_mask);
1783    assert(state->input.full_velem_mask & BITFIELD_BIT(semantic_index));
1784    /* A prefix mask of the full mask gives us the index in pipe_vertex_state. */
1785    return util_bitcount_fast<POPCNT>(state->input.full_velem_mask & BITFIELD_MASK(semantic_index));
1786 }
1787 
1788 template<amd_gfx_level GFX_VERSION, si_has_tess HAS_TESS, si_has_gs HAS_GS, si_has_ngg NGG>
get_vb_descriptor_sgpr_ptr_offset(void)1789 static unsigned get_vb_descriptor_sgpr_ptr_offset(void)
1790 {
1791    /* Find the location of the VB descriptor pointer. */
1792    unsigned dw_offset = SI_VS_NUM_USER_SGPR;
1793    if (GFX_VERSION >= GFX9) {
1794       if (HAS_TESS)
1795          dw_offset = GFX9_TCS_NUM_USER_SGPR;
1796       else if (HAS_GS || NGG)
1797          dw_offset = GFX9_GS_NUM_USER_SGPR;
1798    }
1799    return dw_offset * 4;
1800 }
1801 
1802 template <amd_gfx_level GFX_VERSION, si_has_tess HAS_TESS, si_has_gs HAS_GS, si_has_ngg NGG,
1803           si_is_draw_vertex_state IS_DRAW_VERTEX_STATE, si_has_sh_pairs_packed HAS_SH_PAIRS_PACKED,
1804           util_popcnt POPCNT> ALWAYS_INLINE
si_upload_and_prefetch_VB_descriptors(struct si_context * sctx,struct pipe_vertex_state * state,uint32_t partial_velem_mask)1805 static bool si_upload_and_prefetch_VB_descriptors(struct si_context *sctx,
1806                                                   struct pipe_vertex_state *state,
1807                                                   uint32_t partial_velem_mask)
1808 {
1809    struct si_vertex_state *vstate = (struct si_vertex_state *)state;
1810    unsigned count = IS_DRAW_VERTEX_STATE ? util_bitcount_fast<POPCNT>(partial_velem_mask) :
1811                                            sctx->num_vertex_elements;
1812    unsigned sh_base = si_get_user_data_base(GFX_VERSION, HAS_TESS, HAS_GS, NGG,
1813                                             PIPE_SHADER_VERTEX);
1814    unsigned num_vbos_in_user_sgprs = si_num_vbos_in_user_sgprs_inline(GFX_VERSION);
1815 
1816    assert(count <= SI_MAX_ATTRIBS);
1817 
1818    if (sctx->vertex_buffers_dirty || IS_DRAW_VERTEX_STATE) {
1819       assert(count || IS_DRAW_VERTEX_STATE);
1820 
1821       struct si_vertex_elements *velems = sctx->vertex_elements;
1822       unsigned alloc_size = IS_DRAW_VERTEX_STATE ?
1823                                vstate->velems.vb_desc_list_alloc_size :
1824                                velems->vb_desc_list_alloc_size;
1825       uint64_t vb_descriptors_address = 0;
1826       uint32_t *ptr;
1827 
1828       if (alloc_size) {
1829          unsigned offset;
1830 
1831          /* Vertex buffer descriptors are the only ones which are uploaded directly
1832           * and don't go through si_upload_graphics_shader_descriptors.
1833           */
1834          u_upload_alloc(sctx->b.const_uploader, 0, alloc_size,
1835                         si_optimal_tcc_alignment(sctx, alloc_size), &offset,
1836                         (struct pipe_resource **)&sctx->last_const_upload_buffer, (void **)&ptr);
1837          if (!sctx->last_const_upload_buffer)
1838             return false;
1839 
1840          radeon_add_to_buffer_list(sctx, &sctx->gfx_cs, sctx->last_const_upload_buffer,
1841                                    RADEON_USAGE_READ | RADEON_PRIO_DESCRIPTORS);
1842          vb_descriptors_address = sctx->last_const_upload_buffer->gpu_address + offset;
1843 
1844          /* GFX6 doesn't support the L2 prefetch. */
1845          if (GFX_VERSION >= GFX7) {
1846             uint64_t address = sctx->last_const_upload_buffer->gpu_address + offset;
1847             si_cp_dma_prefetch_inline<GFX_VERSION>(sctx, address, alloc_size);
1848          }
1849       }
1850 
1851       unsigned count_in_user_sgprs = MIN2(count, num_vbos_in_user_sgprs);
1852       unsigned i = 0;
1853 
1854       if (IS_DRAW_VERTEX_STATE) {
1855          radeon_begin(&sctx->gfx_cs);
1856 
1857          if (count_in_user_sgprs) {
1858             radeon_set_sh_reg_seq(sh_base + SI_SGPR_VS_VB_DESCRIPTOR_FIRST * 4, count_in_user_sgprs * 4);
1859 
1860             /* the first iteration always executes */
1861             do {
1862                unsigned velem_index = get_next_vertex_state_elem<POPCNT>(state, &partial_velem_mask);
1863 
1864                radeon_emit_array(&vstate->descriptors[velem_index * 4], 4);
1865             } while (++i < count_in_user_sgprs);
1866          }
1867 
1868          if (partial_velem_mask) {
1869             assert(alloc_size);
1870 
1871             unsigned vb_desc_offset =
1872                sh_base + get_vb_descriptor_sgpr_ptr_offset<GFX_VERSION, HAS_TESS, HAS_GS, NGG>();
1873 
1874             radeon_set_or_push_gfx_sh_reg(vb_desc_offset, vb_descriptors_address);
1875 
1876             /* the first iteration always executes */
1877             do {
1878                unsigned velem_index = get_next_vertex_state_elem<POPCNT>(state, &partial_velem_mask);
1879                uint32_t *desc = &ptr[(i - num_vbos_in_user_sgprs) * 4];
1880 
1881                memcpy(desc, &vstate->descriptors[velem_index * 4], 16);
1882                i++;
1883             } while (partial_velem_mask);
1884          }
1885          radeon_end();
1886 
1887          if (vstate->b.input.vbuffer.buffer.resource != vstate->b.input.indexbuf) {
1888             radeon_add_to_buffer_list(sctx, &sctx->gfx_cs,
1889                                       si_resource(vstate->b.input.vbuffer.buffer.resource),
1890                                       RADEON_USAGE_READ | RADEON_PRIO_VERTEX_BUFFER);
1891          }
1892 
1893          /* The next draw_vbo should recompute and rebind vertex buffer descriptors. */
1894          sctx->vertex_buffers_dirty = sctx->num_vertex_elements > 0;
1895       } else {
1896          if (count_in_user_sgprs) {
1897             radeon_begin(&sctx->gfx_cs);
1898             radeon_set_sh_reg_seq(sh_base + SI_SGPR_VS_VB_DESCRIPTOR_FIRST * 4,
1899                                   count_in_user_sgprs * 4);
1900 
1901             /* the first iteration always executes */
1902             do {
1903                unsigned vbo_index = velems->vertex_buffer_index[i];
1904                const struct pipe_vertex_buffer *vb = &sctx->vertex_buffer[vbo_index];
1905                uint32_t *desc;
1906 
1907                radeon_emit_array_get_ptr(4, &desc);
1908 
1909                si_set_vb_descriptor<GFX_VERSION>(velems, vb, i, desc);
1910             } while (++i < count_in_user_sgprs);
1911 
1912             radeon_end();
1913          }
1914 
1915          if (alloc_size) {
1916             /* the first iteration always executes */
1917             do {
1918                unsigned vbo_index = velems->vertex_buffer_index[i];
1919                const struct pipe_vertex_buffer *vb = &sctx->vertex_buffer[vbo_index];
1920                uint32_t *desc = &ptr[(i - num_vbos_in_user_sgprs) * 4];
1921 
1922                si_set_vb_descriptor<GFX_VERSION>(velems, vb, i, desc);
1923             } while (++i < count);
1924 
1925             unsigned vb_desc_ptr_offset =
1926                sh_base + get_vb_descriptor_sgpr_ptr_offset<GFX_VERSION, HAS_TESS, HAS_GS, NGG>();
1927             radeon_begin(&sctx->gfx_cs);
1928             radeon_set_or_push_gfx_sh_reg(vb_desc_ptr_offset, vb_descriptors_address);
1929             radeon_end();
1930          }
1931 
1932          sctx->vertex_buffers_dirty = false;
1933       }
1934    }
1935 
1936    return true;
1937 }
1938 
si_get_draw_start_count(struct si_context * sctx,const struct pipe_draw_info * info,const struct pipe_draw_indirect_info * indirect,const struct pipe_draw_start_count_bias * draws,unsigned num_draws,unsigned * start,unsigned * count)1939 static void si_get_draw_start_count(struct si_context *sctx, const struct pipe_draw_info *info,
1940                                     const struct pipe_draw_indirect_info *indirect,
1941                                     const struct pipe_draw_start_count_bias *draws,
1942                                     unsigned num_draws, unsigned *start, unsigned *count)
1943 {
1944    if (indirect && !indirect->count_from_stream_output) {
1945       unsigned indirect_count;
1946       struct pipe_transfer *transfer;
1947       unsigned begin, end;
1948       unsigned map_size;
1949       unsigned *data;
1950 
1951       if (indirect->indirect_draw_count) {
1952          data = (unsigned*)
1953                 pipe_buffer_map_range(&sctx->b, indirect->indirect_draw_count,
1954                                       indirect->indirect_draw_count_offset, sizeof(unsigned),
1955                                       PIPE_MAP_READ, &transfer);
1956 
1957          indirect_count = *data;
1958 
1959          pipe_buffer_unmap(&sctx->b, transfer);
1960       } else {
1961          indirect_count = indirect->draw_count;
1962       }
1963 
1964       if (!indirect_count) {
1965          *start = *count = 0;
1966          return;
1967       }
1968 
1969       map_size = (indirect_count - 1) * indirect->stride + 3 * sizeof(unsigned);
1970       data = (unsigned*)
1971              pipe_buffer_map_range(&sctx->b, indirect->buffer, indirect->offset, map_size,
1972                                    PIPE_MAP_READ, &transfer);
1973 
1974       begin = UINT_MAX;
1975       end = 0;
1976 
1977       for (unsigned i = 0; i < indirect_count; ++i) {
1978          unsigned count = data[0];
1979          unsigned start = data[2];
1980 
1981          if (count > 0) {
1982             begin = MIN2(begin, start);
1983             end = MAX2(end, start + count);
1984          }
1985 
1986          data += indirect->stride / sizeof(unsigned);
1987       }
1988 
1989       pipe_buffer_unmap(&sctx->b, transfer);
1990 
1991       if (begin < end) {
1992          *start = begin;
1993          *count = end - begin;
1994       } else {
1995          *start = *count = 0;
1996       }
1997    } else {
1998       unsigned min_element = UINT_MAX;
1999       unsigned max_element = 0;
2000 
2001       for (unsigned i = 0; i < num_draws; i++) {
2002          min_element = MIN2(min_element, draws[i].start);
2003          max_element = MAX2(max_element, draws[i].start + draws[i].count);
2004       }
2005 
2006       *start = min_element;
2007       *count = max_element - min_element;
2008    }
2009 }
2010 
2011 ALWAYS_INLINE
si_emit_all_states(struct si_context * sctx,uint64_t skip_atom_mask)2012 static void si_emit_all_states(struct si_context *sctx, uint64_t skip_atom_mask)
2013 {
2014    /* Emit states by calling their emit functions. */
2015    uint64_t dirty = sctx->dirty_atoms & ~skip_atom_mask;
2016 
2017    if (dirty) {
2018       sctx->dirty_atoms &= skip_atom_mask;
2019 
2020       /* u_bit_scan64 is too slow on i386. */
2021       if (sizeof(void*) == 8) {
2022          do {
2023             unsigned i = u_bit_scan64(&dirty);
2024             sctx->atoms.array[i].emit(sctx, i);
2025          } while (dirty);
2026       } else {
2027          unsigned dirty_lo = dirty;
2028          unsigned dirty_hi = dirty >> 32;
2029 
2030          while (dirty_lo) {
2031             unsigned i = u_bit_scan(&dirty_lo);
2032             sctx->atoms.array[i].emit(sctx, i);
2033          }
2034          while (dirty_hi) {
2035             unsigned i = 32 + u_bit_scan(&dirty_hi);
2036             sctx->atoms.array[i].emit(sctx, i);
2037          }
2038       }
2039    }
2040 }
2041 
2042 #define DRAW_CLEANUP do {                                 \
2043       if (index_size && indexbuf != info->index.resource) \
2044          pipe_resource_reference(&indexbuf, NULL);        \
2045    } while (0)
2046 
2047 template <amd_gfx_level GFX_VERSION, si_has_tess HAS_TESS, si_has_gs HAS_GS, si_has_ngg NGG,
2048           si_is_draw_vertex_state IS_DRAW_VERTEX_STATE, si_has_sh_pairs_packed HAS_SH_PAIRS_PACKED,
2049           util_popcnt POPCNT, si_alt_hiz_logic ALT_HIZ_LOGIC> ALWAYS_INLINE
si_draw(struct pipe_context * ctx,const struct pipe_draw_info * info,unsigned drawid_offset,const struct pipe_draw_indirect_info * indirect,const struct pipe_draw_start_count_bias * draws,unsigned num_draws,struct pipe_vertex_state * state,uint32_t partial_velem_mask)2050 static void si_draw(struct pipe_context *ctx,
2051                     const struct pipe_draw_info *info,
2052                     unsigned drawid_offset,
2053                     const struct pipe_draw_indirect_info *indirect,
2054                     const struct pipe_draw_start_count_bias *draws,
2055                     unsigned num_draws,
2056                     struct pipe_vertex_state *state,
2057                     uint32_t partial_velem_mask)
2058 {
2059    /* Keep code that uses the least number of local variables as close to the beginning
2060     * of this function as possible to minimize register pressure.
2061     *
2062     * It doesn't matter where we return due to invalid parameters because such cases
2063     * shouldn't occur in practice.
2064     */
2065    struct si_context *sctx = (struct si_context *)ctx;
2066 
2067    si_check_dirty_buffers_textures(sctx);
2068 
2069    if (GFX_VERSION < GFX11)
2070       gfx6_decompress_textures(sctx, u_bit_consecutive(0, SI_NUM_GRAPHICS_SHADERS));
2071    else if (GFX_VERSION < GFX12)
2072       gfx11_decompress_textures(sctx, u_bit_consecutive(0, SI_NUM_GRAPHICS_SHADERS));
2073 
2074    si_need_gfx_cs_space(sctx, num_draws, ALT_HIZ_LOGIC ? 8 : 0);
2075 
2076    if (u_trace_perfetto_active(&sctx->ds.trace_context))
2077       trace_si_begin_draw(&sctx->trace);
2078 
2079    unsigned instance_count = info->instance_count;
2080 
2081    /* GFX6-GFX7 treat instance_count==0 as instance_count==1. There is
2082     * no workaround for indirect draws, but we can at least skip
2083     * direct draws.
2084     * 'instance_count == 0' seems to be problematic on Renoir chips (#4866),
2085     * so simplify the condition and drop these draws for all <= GFX9 chips.
2086     */
2087    if (GFX_VERSION <= GFX9 && unlikely(!IS_DRAW_VERTEX_STATE && !indirect && !instance_count))
2088       return;
2089 
2090    struct si_shader_selector *vs = sctx->shader.vs.cso;
2091    struct si_vertex_state *vstate = (struct si_vertex_state *)state;
2092    if (unlikely(!vs ||
2093                 (!IS_DRAW_VERTEX_STATE && sctx->num_vertex_elements < vs->info.num_vs_inputs) ||
2094                 (IS_DRAW_VERTEX_STATE && vstate->velems.count < vs->info.num_vs_inputs) ||
2095                 !sctx->shader.ps.cso || (HAS_TESS != (info->mode == MESA_PRIM_PATCHES)))) {
2096       assert(0);
2097       return;
2098    }
2099 
2100    enum mesa_prim prim = HAS_TESS ? MESA_PRIM_PATCHES : (enum mesa_prim)info->mode;
2101 
2102    if (GFX_VERSION <= GFX9 && HAS_GS) {
2103       /* Determine whether the GS triangle strip adjacency fix should
2104        * be applied. Rotate every other triangle if triangle strips with
2105        * adjacency are fed to the GS. This doesn't work if primitive
2106        * restart occurs after an odd number of triangles.
2107        */
2108       bool gs_tri_strip_adj_fix =
2109          !HAS_TESS && prim == MESA_PRIM_TRIANGLE_STRIP_ADJACENCY;
2110 
2111       if (gs_tri_strip_adj_fix != sctx->shader.gs.key.ge.mono.u.gs_tri_strip_adj_fix) {
2112          sctx->shader.gs.key.ge.mono.u.gs_tri_strip_adj_fix = gs_tri_strip_adj_fix;
2113          sctx->do_update_shaders = true;
2114       }
2115    }
2116 
2117    struct pipe_resource *indexbuf = info->index.resource;
2118    unsigned index_size = info->index_size;
2119    unsigned index_offset = indirect && indirect->buffer ? draws[0].start * index_size : 0;
2120 
2121    if (index_size) {
2122       /* Translate or upload, if needed. */
2123       /* 8-bit indices are supported on GFX8. */
2124       if (!IS_DRAW_VERTEX_STATE && GFX_VERSION <= GFX7 && index_size == 1) {
2125          unsigned start, count, start_offset, size;
2126 
2127          si_get_draw_start_count(sctx, info, indirect, draws, num_draws, &start, &count);
2128          start_offset = start * 2;
2129          size = count * 2;
2130 
2131          /* Don't use u_upload_alloc because we don't need to map the buffer for CPU access. */
2132          indexbuf = pipe_buffer_create(&sctx->screen->b, 0, PIPE_USAGE_IMMUTABLE, start_offset + size);
2133          if (unlikely(!indexbuf))
2134             return;
2135 
2136          si_compute_shorten_ubyte_buffer(sctx, indexbuf, info->index.resource, start_offset,
2137                                          index_offset + start, count, sctx->render_cond_enabled);
2138          si_barrier_after_simple_buffer_op(sctx, 0, indexbuf, info->index.resource);
2139 
2140          index_offset = 0;
2141          index_size = 2;
2142 
2143          /* GFX6-7 don't read index buffers through L2. */
2144          sctx->barrier_flags |= SI_BARRIER_WB_L2 | SI_BARRIER_PFP_SYNC_ME;
2145          si_mark_atom_dirty(sctx, &sctx->atoms.s.barrier);
2146          si_resource(indexbuf)->L2_cache_dirty = false;
2147       } else if (!IS_DRAW_VERTEX_STATE && info->has_user_indices) {
2148          unsigned start_offset;
2149 
2150          assert(!indirect);
2151          assert(num_draws == 1);
2152          start_offset = draws[0].start * index_size;
2153 
2154          indexbuf = NULL;
2155          u_upload_data(ctx->stream_uploader, start_offset, draws[0].count * index_size,
2156                        sctx->screen->info.tcc_cache_line_size,
2157                        (char *)info->index.user + start_offset, &index_offset, &indexbuf);
2158          if (unlikely(!indexbuf))
2159             return;
2160 
2161          /* info->start will be added by the drawing code */
2162          index_offset -= start_offset;
2163       } else if ((GFX_VERSION <= GFX7 || GFX_VERSION == GFX12) &&
2164                  si_resource(indexbuf)->L2_cache_dirty) {
2165          /* GFX8-GFX11 reads index buffers through L2, so it doesn't
2166           * need this. */
2167          sctx->barrier_flags |= SI_BARRIER_WB_L2 | SI_BARRIER_PFP_SYNC_ME;
2168          si_mark_atom_dirty(sctx, &sctx->atoms.s.barrier);
2169          si_resource(indexbuf)->L2_cache_dirty = false;
2170       }
2171    }
2172 
2173 #define NEED_MIN_DIRECT_COUNT (GFX_VERSION == GFX7 || GFX_VERSION == GFX8)
2174 #define NEED_TOTAL_DIRECT_COUNT (NGG && !HAS_TESS && !HAS_GS)
2175    unsigned min_direct_count = 0;
2176    unsigned total_direct_count = 0;
2177 
2178    if (!IS_DRAW_VERTEX_STATE && indirect) {
2179       /* Indirect buffers use L2 on GFX9-GFX11, but not other hw. */
2180       if (GFX_VERSION <= GFX8 || GFX_VERSION == GFX12) {
2181          if (indirect->buffer && si_resource(indirect->buffer)->L2_cache_dirty) {
2182             sctx->barrier_flags |= SI_BARRIER_WB_L2 | SI_BARRIER_PFP_SYNC_ME;
2183             si_mark_atom_dirty(sctx, &sctx->atoms.s.barrier);
2184             si_resource(indirect->buffer)->L2_cache_dirty = false;
2185          }
2186 
2187          if (indirect->indirect_draw_count &&
2188              si_resource(indirect->indirect_draw_count)->L2_cache_dirty) {
2189             sctx->barrier_flags |= SI_BARRIER_WB_L2 | SI_BARRIER_PFP_SYNC_ME;
2190             si_mark_atom_dirty(sctx, &sctx->atoms.s.barrier);
2191             si_resource(indirect->indirect_draw_count)->L2_cache_dirty = false;
2192          }
2193       }
2194 
2195       if (NEED_TOTAL_DIRECT_COUNT)
2196          total_direct_count = INT_MAX; /* just set something other than 0 to enable shader culling */
2197    } else if (NEED_MIN_DIRECT_COUNT || NEED_TOTAL_DIRECT_COUNT) {
2198       if (NEED_TOTAL_DIRECT_COUNT)
2199          total_direct_count = draws[0].count;
2200       if (NEED_MIN_DIRECT_COUNT)
2201          min_direct_count = draws[0].count;
2202 
2203       for (unsigned i = 1; i < num_draws; i++) {
2204          unsigned count = draws[i].count;
2205 
2206          if (NEED_TOTAL_DIRECT_COUNT)
2207             total_direct_count += count;
2208          if (NEED_MIN_DIRECT_COUNT)
2209             min_direct_count = MIN2(min_direct_count, count);
2210       }
2211    }
2212 
2213    /* Set the rasterization primitive type.
2214     *
2215     * This must be done after si_decompress_textures, which can call
2216     * draw_vbo recursively, and before si_update_shaders, which uses
2217     * current_rast_prim for this draw_vbo call.
2218     */
2219    if (!HAS_GS && !HAS_TESS) {
2220       enum mesa_prim rast_prim;
2221 
2222       if (util_rast_prim_is_triangles(prim)) {
2223          rast_prim = MESA_PRIM_TRIANGLES;
2224       } else {
2225          /* Only possibilities, POINTS, LINE*, RECTANGLES */
2226          rast_prim = prim;
2227       }
2228 
2229       si_set_rasterized_prim(sctx, rast_prim, si_get_vs_inline(sctx, HAS_TESS, HAS_GS)->current,
2230                              NGG);
2231    }
2232 
2233    if (IS_DRAW_VERTEX_STATE) {
2234       /* draw_vertex_state doesn't use the current vertex buffers and vertex elements,
2235        * so disable all VS input lowering.
2236        */
2237       if (!sctx->force_trivial_vs_inputs) {
2238          sctx->force_trivial_vs_inputs = true;
2239 
2240          /* Update shaders to disable VS input lowering. */
2241          if (sctx->uses_nontrivial_vs_inputs) {
2242             si_vs_key_update_inputs(sctx);
2243             sctx->do_update_shaders = true;
2244          }
2245       }
2246    } else {
2247       if (sctx->force_trivial_vs_inputs) {
2248          sctx->force_trivial_vs_inputs = false;
2249 
2250          /* Update shaders to possibly enable VS input lowering. */
2251          if (sctx->uses_nontrivial_vs_inputs) {
2252             si_vs_key_update_inputs(sctx);
2253             sctx->do_update_shaders = true;
2254          }
2255       }
2256    }
2257 
2258    /* Update NGG culling settings. */
2259    uint16_t old_ngg_culling = sctx->ngg_culling;
2260    if (GFX_VERSION >= GFX10) {
2261       struct si_shader_selector *hw_vs = si_get_vs_inline(sctx, HAS_TESS, HAS_GS)->cso;
2262 
2263       if (NGG &&
2264           /* Tessellation and GS set ngg_cull_vert_threshold to UINT_MAX if the prim type
2265            * is not points, so this check is only needed for VS. */
2266           (HAS_TESS || HAS_GS || sctx->current_rast_prim != MESA_PRIM_POINTS) &&
2267           /* Only the first draw for a shader starts with culling disabled and it's disabled
2268            * until we pass the total_direct_count check and then it stays enabled until
2269            * the shader is changed. This eliminates most culling on/off state changes. */
2270           (old_ngg_culling ||
2271            /* If tess or GS is enabled, the shader just has to allow culling. */
2272            /* If tess and GS are disabled, the draw has to pass the total_direct_count check. */
2273            (HAS_TESS || HAS_GS ? hw_vs->ngg_cull_vert_threshold == 0
2274                                : total_direct_count > hw_vs->ngg_cull_vert_threshold))) {
2275          struct si_state_rasterizer *rs = sctx->queued.named.rasterizer;
2276 
2277          /* Check that the current shader allows culling. */
2278          assert(hw_vs->ngg_cull_vert_threshold != UINT_MAX);
2279 
2280          uint16_t ngg_culling;
2281 
2282          if (util_prim_is_lines(sctx->current_rast_prim)) {
2283             /* Overwrite it to mask out face cull flags. */
2284             ngg_culling = rs->ngg_cull_flags_lines |
2285                           (!HAS_TESS && !HAS_GS ? SI_NGG_CULL_VS_LINES : 0);
2286          } else {
2287             ngg_culling = rs->ngg_cull_flags_tris |
2288                           (!HAS_TESS && !HAS_GS ? SI_NGG_CULL_VS_TRIANGLES : 0);
2289          }
2290 
2291          if (ngg_culling != old_ngg_culling) {
2292             /* If shader compilation is not ready, this setting will be rejected. */
2293             sctx->ngg_culling = ngg_culling;
2294             sctx->do_update_shaders = true;
2295          }
2296       } else if (old_ngg_culling) {
2297          sctx->ngg_culling = 0;
2298          sctx->do_update_shaders = true;
2299       }
2300    }
2301 
2302    if (unlikely(sctx->do_update_shaders)) {
2303       if (unlikely(!(si_update_shaders<GFX_VERSION, HAS_TESS, HAS_GS, NGG>(sctx)))) {
2304          DRAW_CLEANUP;
2305          return;
2306       }
2307    }
2308 
2309    /* This is the optimal packet order:
2310     * Set all states first, so that all SET packets are processed in parallel with previous
2311     * draw calls. Then flush caches and wait if needed. Then draw and prefetch at the end.
2312     * It's better to draw before prefetches because we want to start fetching indices before
2313     * shaders. The idea is to minimize the time when the CUs are idle.
2314     */
2315 
2316    /* Vega10/Raven scissor bug workaround. When any context register is
2317     * written (i.e. the GPU rolls the context), PA_SC_VPORT_SCISSOR
2318     * registers must be written too.
2319     */
2320    bool gfx9_scissor_bug = false;
2321    uint64_t masked_atoms = 0;
2322 
2323    if (GFX_VERSION == GFX9 && sctx->screen->info.has_gfx9_scissor_bug) {
2324       masked_atoms |= si_get_atom_bit(sctx, &sctx->atoms.s.scissors);
2325       gfx9_scissor_bug = true;
2326 
2327       if ((!IS_DRAW_VERTEX_STATE && indirect && indirect->count_from_stream_output) ||
2328           sctx->dirty_atoms & si_atoms_that_always_roll_context())
2329          sctx->context_roll = true;
2330    }
2331 
2332    bool primitive_restart = !IS_DRAW_VERTEX_STATE && info->primitive_restart;
2333 
2334    /* Emit states. */
2335    si_emit_rasterizer_prim_state<GFX_VERSION, HAS_GS, NGG>(sctx);
2336    /* This emits states and flushes caches. */
2337    si_emit_all_states(sctx, masked_atoms);
2338    /* This can be done after si_emit_all_states because it doesn't set barrier flags. */
2339    si_emit_draw_registers<GFX_VERSION, HAS_TESS, HAS_GS, NGG, IS_DRAW_VERTEX_STATE>
2340          (sctx, indirect, prim, index_size, instance_count, primitive_restart,
2341           info->restart_index, min_direct_count);
2342 
2343    /* <-- CUs are idle here if the barrier atom waited. */
2344 
2345    /* This must be done after si_emit_all_states, which can affect this. */
2346    si_emit_vs_state<GFX_VERSION, HAS_TESS, HAS_GS, NGG, IS_DRAW_VERTEX_STATE, HAS_SH_PAIRS_PACKED>
2347          (sctx, index_size);
2348 
2349    /* This needs to be done after cache flushes because ACQUIRE_MEM rolls the context. */
2350    if (GFX_VERSION == GFX9 && gfx9_scissor_bug &&
2351        (sctx->context_roll || si_is_atom_dirty(sctx, &sctx->atoms.s.scissors))) {
2352       sctx->atoms.s.scissors.emit(sctx, -1);
2353       sctx->dirty_atoms &= ~si_get_atom_bit(sctx, &sctx->atoms.s.scissors);
2354    }
2355    assert(sctx->dirty_atoms == 0);
2356 
2357    /* This uploads VBO descriptors, sets user SGPRs, and executes the L2 prefetch.
2358     * It should done after cache flushing.
2359     */
2360    if (unlikely((!si_upload_and_prefetch_VB_descriptors
2361                      <GFX_VERSION, HAS_TESS, HAS_GS, NGG, IS_DRAW_VERTEX_STATE, HAS_SH_PAIRS_PACKED, POPCNT>
2362                      (sctx, state, partial_velem_mask)))) {
2363       DRAW_CLEANUP;
2364       return;
2365    }
2366 
2367    si_emit_draw_packets<GFX_VERSION, HAS_TESS, HAS_GS, NGG, IS_DRAW_VERTEX_STATE,
2368                         HAS_SH_PAIRS_PACKED, ALT_HIZ_LOGIC>
2369          (sctx, info, drawid_offset, indirect, draws, num_draws, indexbuf,
2370           index_size, index_offset, instance_count);
2371    /* <-- CUs start to get busy here if we waited. */
2372 
2373    /* Start prefetches after the draw has been started. Both will run
2374     * in parallel, but starting the draw first is more important.
2375     */
2376    si_prefetch_shaders<GFX_VERSION, HAS_TESS, HAS_GS, NGG>(sctx);
2377 
2378    /* Clear the context roll flag after the draw call.
2379     * Only used by the gfx9 scissor bug.
2380     */
2381    if (GFX_VERSION == GFX9)
2382       sctx->context_roll = false;
2383 
2384    if (unlikely(sctx->current_saved_cs)) {
2385       si_trace_emit(sctx);
2386       si_log_draw_state(sctx, sctx->log);
2387    }
2388 
2389    /* Workaround for a VGT hang when streamout is enabled.
2390     * It must be done after drawing. */
2391    if (((GFX_VERSION == GFX7 && sctx->family == CHIP_HAWAII) ||
2392         (GFX_VERSION == GFX8 && (sctx->family == CHIP_TONGA || sctx->family == CHIP_FIJI))) &&
2393        si_get_strmout_en(sctx)) {
2394       radeon_begin(&sctx->gfx_cs);
2395       radeon_event_write(V_028A90_VGT_STREAMOUT_SYNC);
2396       radeon_end();
2397    }
2398 
2399    if (unlikely(GFX_VERSION < GFX12 && sctx->decompression_enabled)) {
2400       sctx->num_decompress_calls++;
2401    } else {
2402       sctx->num_draw_calls += num_draws;
2403    }
2404 
2405    /* On Gfx12, this is only used to detect whether a depth texture is in the cleared state. */
2406    if (sctx->framebuffer.state.zsbuf) {
2407       struct si_texture *zstex = (struct si_texture *)sctx->framebuffer.state.zsbuf->texture;
2408       zstex->depth_cleared_level_mask &= ~BITFIELD_BIT(sctx->framebuffer.state.zsbuf->u.tex.level);
2409    }
2410 
2411    if (u_trace_perfetto_active(&sctx->ds.trace_context)) {
2412       /* Just use the draw[0] vertex count for perfetto. */
2413       trace_si_end_draw(&sctx->trace, draws[0].count);
2414    }
2415 
2416    DRAW_CLEANUP;
2417 }
2418 
2419 template <amd_gfx_level GFX_VERSION, si_has_tess HAS_TESS, si_has_gs HAS_GS, si_has_ngg NGG,
2420           si_has_sh_pairs_packed HAS_SH_PAIRS_PACKED, si_alt_hiz_logic ALT_HIZ_LOGIC>
si_draw_vbo(struct pipe_context * ctx,const struct pipe_draw_info * info,unsigned drawid_offset,const struct pipe_draw_indirect_info * indirect,const struct pipe_draw_start_count_bias * draws,unsigned num_draws)2421 static void si_draw_vbo(struct pipe_context *ctx,
2422                         const struct pipe_draw_info *info,
2423                         unsigned drawid_offset,
2424                         const struct pipe_draw_indirect_info *indirect,
2425                         const struct pipe_draw_start_count_bias *draws,
2426                         unsigned num_draws)
2427 {
2428    si_draw<GFX_VERSION, HAS_TESS, HAS_GS, NGG, DRAW_VERTEX_STATE_OFF, HAS_SH_PAIRS_PACKED,
2429          POPCNT_NO, ALT_HIZ_LOGIC>
2430       (ctx, info, drawid_offset, indirect, draws, num_draws, NULL, 0);
2431 }
2432 
2433 template <amd_gfx_level GFX_VERSION, si_has_tess HAS_TESS, si_has_gs HAS_GS, si_has_ngg NGG,
2434           si_has_sh_pairs_packed HAS_SH_PAIRS_PACKED, util_popcnt POPCNT,
2435           si_alt_hiz_logic ALT_HIZ_LOGIC>
si_draw_vertex_state(struct pipe_context * ctx,struct pipe_vertex_state * vstate,uint32_t partial_velem_mask,struct pipe_draw_vertex_state_info info,const struct pipe_draw_start_count_bias * draws,unsigned num_draws)2436 static void si_draw_vertex_state(struct pipe_context *ctx,
2437                                  struct pipe_vertex_state *vstate,
2438                                  uint32_t partial_velem_mask,
2439                                  struct pipe_draw_vertex_state_info info,
2440                                  const struct pipe_draw_start_count_bias *draws,
2441                                  unsigned num_draws)
2442 {
2443    struct si_vertex_state *state = (struct si_vertex_state *)vstate;
2444    struct pipe_draw_info dinfo = {};
2445 
2446    dinfo.mode = info.mode;
2447    dinfo.index_size = 4;
2448    dinfo.instance_count = 1;
2449    dinfo.index.resource = state->b.input.indexbuf;
2450 
2451    si_draw<GFX_VERSION, HAS_TESS, HAS_GS, NGG, DRAW_VERTEX_STATE_ON, HAS_SH_PAIRS_PACKED, POPCNT,
2452            ALT_HIZ_LOGIC>
2453       (ctx, &dinfo, 0, NULL, draws, num_draws, vstate, partial_velem_mask);
2454 
2455    if (info.take_vertex_state_ownership)
2456       pipe_vertex_state_reference(&vstate, NULL);
2457 }
2458 
si_draw_rectangle(struct blitter_context * blitter,void * vertex_elements_cso,blitter_get_vs_func get_vs,int x1,int y1,int x2,int y2,float depth,unsigned num_instances,enum blitter_attrib_type type,const union blitter_attrib * attrib)2459 static void si_draw_rectangle(struct blitter_context *blitter, void *vertex_elements_cso,
2460                               blitter_get_vs_func get_vs, int x1, int y1, int x2, int y2,
2461                               float depth, unsigned num_instances, enum blitter_attrib_type type,
2462                               const union blitter_attrib *attrib)
2463 {
2464    struct pipe_context *pipe = util_blitter_get_pipe(blitter);
2465    struct si_context *sctx = (struct si_context *)pipe;
2466    uint32_t attribute_ring_address_lo =
2467       sctx->gfx_level >= GFX11 ? sctx->screen->attribute_pos_prim_ring->gpu_address : 0;
2468 
2469    if (MAX2(abs(x1), abs(x2)) > INT16_MAX || MAX2(abs(y1), abs(y2)) > INT16_MAX) {
2470       /* Fallback when coordinates can't fit in int16. */
2471       util_blitter_save_vertex_elements(sctx->blitter, sctx->vertex_elements);
2472       util_blitter_draw_rectangle(blitter, vertex_elements_cso, get_vs, x1, y1, x2, y2,
2473                                   depth, num_instances, type, attrib);
2474       return;
2475    }
2476 
2477    /* Pack position coordinates as signed int16. */
2478    sctx->vs_blit_sh_data[0] = (uint32_t)(x1 & 0xffff) | ((uint32_t)(y1 & 0xffff) << 16);
2479    sctx->vs_blit_sh_data[1] = (uint32_t)(x2 & 0xffff) | ((uint32_t)(y2 & 0xffff) << 16);
2480    sctx->vs_blit_sh_data[2] = fui(depth);
2481 
2482    switch (type) {
2483    case UTIL_BLITTER_ATTRIB_COLOR:
2484       memcpy(&sctx->vs_blit_sh_data[3], attrib->color, sizeof(float) * 4);
2485       sctx->vs_blit_sh_data[7] = attribute_ring_address_lo;
2486       break;
2487    case UTIL_BLITTER_ATTRIB_TEXCOORD_XY:
2488    case UTIL_BLITTER_ATTRIB_TEXCOORD_XYZW:
2489       memcpy(&sctx->vs_blit_sh_data[3], &attrib->texcoord, sizeof(attrib->texcoord));
2490       sctx->vs_blit_sh_data[9] = attribute_ring_address_lo;
2491       break;
2492    case UTIL_BLITTER_ATTRIB_NONE:;
2493    }
2494 
2495    pipe->bind_vs_state(pipe, si_get_blitter_vs(sctx, type, num_instances));
2496 
2497    struct pipe_draw_info info = {};
2498    struct pipe_draw_start_count_bias draw;
2499 
2500    info.mode = SI_PRIM_RECTANGLE_LIST;
2501    info.instance_count = num_instances;
2502 
2503    draw.start = 0;
2504    draw.count = 3;
2505 
2506    /* Blits don't use vertex buffers. */
2507    sctx->vertex_buffers_dirty = false;
2508 
2509    pipe->draw_vbo(pipe, &info, 0, NULL, &draw, 1);
2510 }
2511 
2512 template <amd_gfx_level GFX_VERSION, si_has_tess HAS_TESS, si_has_gs HAS_GS, si_has_ngg NGG,
2513           util_popcnt POPCNT>
si_init_draw_vbo(struct si_context * sctx)2514 static void si_init_draw_vbo(struct si_context *sctx)
2515 {
2516    if (NGG && GFX_VERSION < GFX10)
2517       return;
2518 
2519    if (!NGG && GFX_VERSION >= GFX11)
2520       return;
2521 
2522    if (GFX_VERSION == GFX12 && sctx->screen->options.alt_hiz_logic) {
2523       sctx->draw_vbo[HAS_TESS][HAS_GS][NGG] =
2524          si_draw_vbo<GFX12, HAS_TESS, HAS_GS, NGG, HAS_SH_PAIRS_PACKED_OFF, ALT_HIZ_LOGIC_ON>;
2525 
2526       sctx->draw_vertex_state[HAS_TESS][HAS_GS][NGG] =
2527          si_draw_vertex_state<GFX12, HAS_TESS, HAS_GS, NGG, HAS_SH_PAIRS_PACKED_OFF, POPCNT,
2528                               ALT_HIZ_LOGIC_ON>;
2529    } else if (GFX_VERSION >= GFX11 && GFX_VERSION < GFX12 &&
2530               sctx->screen->info.has_set_sh_pairs_packed) {
2531       sctx->draw_vbo[HAS_TESS][HAS_GS][NGG] =
2532          si_draw_vbo<GFX_VERSION, HAS_TESS, HAS_GS, NGG, HAS_SH_PAIRS_PACKED_ON, ALT_HIZ_LOGIC_OFF>;
2533 
2534       sctx->draw_vertex_state[HAS_TESS][HAS_GS][NGG] =
2535          si_draw_vertex_state<GFX_VERSION, HAS_TESS, HAS_GS, NGG, HAS_SH_PAIRS_PACKED_ON, POPCNT,
2536                               ALT_HIZ_LOGIC_OFF>;
2537    } else {
2538       sctx->draw_vbo[HAS_TESS][HAS_GS][NGG] =
2539          si_draw_vbo<GFX_VERSION, HAS_TESS, HAS_GS, NGG, HAS_SH_PAIRS_PACKED_OFF, ALT_HIZ_LOGIC_OFF>;
2540 
2541       sctx->draw_vertex_state[HAS_TESS][HAS_GS][NGG] =
2542          si_draw_vertex_state<GFX_VERSION, HAS_TESS, HAS_GS, NGG, HAS_SH_PAIRS_PACKED_OFF, POPCNT,
2543                               ALT_HIZ_LOGIC_OFF>;
2544    }
2545 }
2546 
2547 template <amd_gfx_level GFX_VERSION>
si_init_draw_vbo_all_pipeline_options(struct si_context * sctx)2548 static void si_init_draw_vbo_all_pipeline_options(struct si_context *sctx)
2549 {
2550    if (util_get_cpu_caps()->has_popcnt) {
2551       si_init_draw_vbo<GFX_VERSION, TESS_OFF, GS_OFF, NGG_OFF, POPCNT_YES>(sctx);
2552       si_init_draw_vbo<GFX_VERSION, TESS_OFF, GS_ON,  NGG_OFF, POPCNT_YES>(sctx);
2553       si_init_draw_vbo<GFX_VERSION, TESS_ON,  GS_OFF, NGG_OFF, POPCNT_YES>(sctx);
2554       si_init_draw_vbo<GFX_VERSION, TESS_ON,  GS_ON,  NGG_OFF, POPCNT_YES>(sctx);
2555       si_init_draw_vbo<GFX_VERSION, TESS_OFF, GS_OFF, NGG_ON, POPCNT_YES>(sctx);
2556       si_init_draw_vbo<GFX_VERSION, TESS_OFF, GS_ON,  NGG_ON, POPCNT_YES>(sctx);
2557       si_init_draw_vbo<GFX_VERSION, TESS_ON,  GS_OFF, NGG_ON, POPCNT_YES>(sctx);
2558       si_init_draw_vbo<GFX_VERSION, TESS_ON,  GS_ON,  NGG_ON, POPCNT_YES>(sctx);
2559    } else {
2560       si_init_draw_vbo<GFX_VERSION, TESS_OFF, GS_OFF, NGG_OFF, POPCNT_NO>(sctx);
2561       si_init_draw_vbo<GFX_VERSION, TESS_OFF, GS_ON,  NGG_OFF, POPCNT_NO>(sctx);
2562       si_init_draw_vbo<GFX_VERSION, TESS_ON,  GS_OFF, NGG_OFF, POPCNT_NO>(sctx);
2563       si_init_draw_vbo<GFX_VERSION, TESS_ON,  GS_ON,  NGG_OFF, POPCNT_NO>(sctx);
2564       si_init_draw_vbo<GFX_VERSION, TESS_OFF, GS_OFF, NGG_ON, POPCNT_NO>(sctx);
2565       si_init_draw_vbo<GFX_VERSION, TESS_OFF, GS_ON,  NGG_ON, POPCNT_NO>(sctx);
2566       si_init_draw_vbo<GFX_VERSION, TESS_ON,  GS_OFF, NGG_ON, POPCNT_NO>(sctx);
2567       si_init_draw_vbo<GFX_VERSION, TESS_ON,  GS_ON,  NGG_ON, POPCNT_NO>(sctx);
2568    }
2569 }
2570 
si_invalid_draw_vbo(struct pipe_context * pipe,const struct pipe_draw_info * info,unsigned drawid_offset,const struct pipe_draw_indirect_info * indirect,const struct pipe_draw_start_count_bias * draws,unsigned num_draws)2571 static void si_invalid_draw_vbo(struct pipe_context *pipe,
2572                                 const struct pipe_draw_info *info,
2573                                 unsigned drawid_offset,
2574                                 const struct pipe_draw_indirect_info *indirect,
2575                                 const struct pipe_draw_start_count_bias *draws,
2576                                 unsigned num_draws)
2577 {
2578    unreachable("vertex shader not bound");
2579 }
2580 
si_invalid_draw_vertex_state(struct pipe_context * ctx,struct pipe_vertex_state * vstate,uint32_t partial_velem_mask,struct pipe_draw_vertex_state_info info,const struct pipe_draw_start_count_bias * draws,unsigned num_draws)2581 static void si_invalid_draw_vertex_state(struct pipe_context *ctx,
2582                                          struct pipe_vertex_state *vstate,
2583                                          uint32_t partial_velem_mask,
2584                                          struct pipe_draw_vertex_state_info info,
2585                                          const struct pipe_draw_start_count_bias *draws,
2586                                          unsigned num_draws)
2587 {
2588    unreachable("vertex shader not bound");
2589 }
2590 
2591 extern "C"
GFX(si_init_draw_functions_)2592 void GFX(si_init_draw_functions_)(struct si_context *sctx)
2593 {
2594    assert(sctx->gfx_level == GFX());
2595 
2596    si_init_draw_vbo_all_pipeline_options<GFX()>(sctx);
2597 
2598    /* Bind a fake draw_vbo, so that draw_vbo isn't NULL, which would skip
2599     * initialization of callbacks in upper layers (such as u_threaded_context).
2600     */
2601    sctx->b.draw_vbo = si_invalid_draw_vbo;
2602    sctx->b.draw_vertex_state = si_invalid_draw_vertex_state;
2603    sctx->blitter->draw_rectangle = si_draw_rectangle;
2604 
2605    si_init_ia_multi_vgt_param_table(sctx);
2606 }
2607