• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2010 Jerome Glisse <glisse@freedesktop.org>
3  * Copyright 2018 Advanced Micro Devices, Inc.
4  *
5  * SPDX-License-Identifier: MIT
6  */
7 
8 #include "si_pipe.h"
9 
10 #include "driver_ddebug/dd_util.h"
11 #include "radeon_uvd.h"
12 #include "si_public.h"
13 #include "sid.h"
14 #include "ac_shadowed_regs.h"
15 #include "compiler/nir/nir.h"
16 #include "util/disk_cache.h"
17 #include "util/hex.h"
18 #include "util/u_cpu_detect.h"
19 #include "util/u_log.h"
20 #include "util/u_memory.h"
21 #include "util/u_suballoc.h"
22 #include "util/u_tests.h"
23 #include "util/u_upload_mgr.h"
24 #include "util/xmlconfig.h"
25 #include "vl/vl_decoder.h"
26 #include "si_utrace.h"
27 
28 #include "aco_interface.h"
29 
30 #if LLVM_AVAILABLE
31 #include "ac_llvm_util.h"
32 #endif
33 
34 #include <xf86drm.h>
35 
36 static struct pipe_context *si_create_context(struct pipe_screen *screen, unsigned flags);
37 
38 static const struct debug_named_value radeonsi_debug_options[] = {
39    /* Shader logging options: */
40    {"vs", DBG(VS), "Print vertex shaders"},
41    {"ps", DBG(PS), "Print pixel shaders"},
42    {"gs", DBG(GS), "Print geometry shaders"},
43    {"tcs", DBG(TCS), "Print tessellation control shaders"},
44    {"tes", DBG(TES), "Print tessellation evaluation shaders"},
45    {"cs", DBG(CS), "Print compute shaders"},
46 
47    {"initnir", DBG(INIT_NIR), "Print initial input NIR when shaders are created"},
48    {"nir", DBG(NIR), "Print final NIR after lowering when shader variants are created"},
49    {"initllvm", DBG(INIT_LLVM), "Print initial LLVM IR before optimizations"},
50    {"llvm", DBG(LLVM), "Print final LLVM IR"},
51    {"initaco", DBG(INIT_ACO), "Print initial ACO IR before optimizations"},
52    {"aco", DBG(ACO), "Print final ACO IR"},
53    {"asm", DBG(ASM), "Print final shaders in asm"},
54    {"stats", DBG(STATS), "Print shader-db stats to stderr"},
55 
56    /* Shader compiler options the shader cache should be aware of: */
57    {"w32ge", DBG(W32_GE), "Use Wave32 for vertex, tessellation, and geometry shaders."},
58    {"w32ps", DBG(W32_PS), "Use Wave32 for pixel shaders."},
59    {"w32cs", DBG(W32_CS), "Use Wave32 for computes shaders."},
60    {"w64ge", DBG(W64_GE), "Use Wave64 for vertex, tessellation, and geometry shaders."},
61    {"w64ps", DBG(W64_PS), "Use Wave64 for pixel shaders."},
62    {"w64cs", DBG(W64_CS), "Use Wave64 for computes shaders."},
63 
64    /* Shader compiler options (with no effect on the shader cache): */
65    {"checkir", DBG(CHECK_IR), "Enable additional sanity checks on shader IR"},
66    {"mono", DBG(MONOLITHIC_SHADERS), "Use old-style monolithic shaders compiled on demand"},
67    {"nooptvariant", DBG(NO_OPT_VARIANT), "Disable compiling optimized shader variants."},
68    {"useaco", DBG(USE_ACO), "Use ACO as shader compiler when possible"},
69 
70    /* Information logging options: */
71    {"info", DBG(INFO), "Print driver information"},
72    {"tex", DBG(TEX), "Print texture info"},
73    {"compute", DBG(COMPUTE), "Print compute info"},
74    {"vm", DBG(VM), "Print virtual addresses when creating resources"},
75    {"cache_stats", DBG(CACHE_STATS), "Print shader cache statistics."},
76    {"ib", DBG(IB), "Print command buffers."},
77    {"elements", DBG(VERTEX_ELEMENTS), "Print vertex elements."},
78 
79    /* Driver options: */
80    {"nowc", DBG(NO_WC), "Disable GTT write combining"},
81    {"nowcstream", DBG(NO_WC_STREAM), "Disable GTT write combining for streaming uploads"},
82    {"check_vm", DBG(CHECK_VM), "Check VM faults and dump debug info."},
83    {"reserve_vmid", DBG(RESERVE_VMID), "Force VMID reservation per context."},
84    {"shadowregs", DBG(SHADOW_REGS), "Enable CP register shadowing."},
85    {"nofastdlist", DBG(NO_FAST_DISPLAY_LIST), "Disable fast display lists"},
86    {"nodmashaders", DBG(NO_DMA_SHADERS), "Disable uploading shaders via CP DMA and map them directly."},
87 
88    /* Multimedia options: */
89    { "noefc", DBG(NO_EFC), "Disable hardware based encoder colour format conversion."},
90 
91    /* 3D engine options: */
92    {"nongg", DBG(NO_NGG), "Disable NGG and use the legacy pipeline."},
93    {"nggc", DBG(ALWAYS_NGG_CULLING_ALL), "Always use NGG culling even when it can hurt."},
94    {"nonggc", DBG(NO_NGG_CULLING), "Disable NGG culling."},
95    {"switch_on_eop", DBG(SWITCH_ON_EOP), "Program WD/IA to switch on end-of-packet."},
96    {"nooutoforder", DBG(NO_OUT_OF_ORDER), "Disable out-of-order rasterization"},
97    {"nodpbb", DBG(NO_DPBB), "Disable DPBB. Overrules the dpbb enable option."},
98    {"dpbb", DBG(DPBB), "Enable DPBB for gfx9 dGPU. Default enabled for gfx9 APU and >= gfx10."},
99    {"nohyperz", DBG(NO_HYPERZ), "Disable Hyper-Z"},
100    {"no2d", DBG(NO_2D_TILING), "Disable 2D tiling"},
101    {"notiling", DBG(NO_TILING), "Disable tiling"},
102    {"nodisplaytiling", DBG(NO_DISPLAY_TILING), "Disable display tiling"},
103    {"nodisplaydcc", DBG(NO_DISPLAY_DCC), "Disable display DCC"},
104    {"noexporteddcc", DBG(NO_EXPORTED_DCC), "Disable DCC for all exported buffers (via DMABUF, etc.)"},
105    {"nodcc", DBG(NO_DCC), "Disable DCC."},
106    {"nodccclear", DBG(NO_DCC_CLEAR), "Disable DCC fast clear."},
107    {"nodccstore", DBG(NO_DCC_STORE), "Disable DCC stores"},
108    {"dccstore", DBG(DCC_STORE), "Enable DCC stores"},
109    {"nodccmsaa", DBG(NO_DCC_MSAA), "Disable DCC for MSAA"},
110    {"nofmask", DBG(NO_FMASK), "Disable MSAA compression"},
111    {"nodma", DBG(NO_DMA), "Disable SDMA-copy for DRI_PRIME"},
112 
113    {"extra_md", DBG(EXTRA_METADATA), "Set UMD metadata for all textures and with additional fields for umr"},
114 
115    {"tmz", DBG(TMZ), "Force allocation of scanout/depth/stencil buffer as encrypted"},
116    {"sqtt", DBG(SQTT), "Enable SQTT"},
117 
118    DEBUG_NAMED_VALUE_END /* must be last */
119 };
120 
121 static const struct debug_named_value test_options[] = {
122    /* Tests: */
123    {"imagecopy", DBG(TEST_IMAGE_COPY), "Invoke resource_copy_region tests with images and exit."},
124    {"cbresolve", DBG(TEST_CB_RESOLVE), "Invoke MSAA resolve tests and exit."},
125    {"computeblit", DBG(TEST_COMPUTE_BLIT), "Invoke blits tests and exit."},
126    {"testvmfaultcp", DBG(TEST_VMFAULT_CP), "Invoke a CP VM fault test and exit."},
127    {"testvmfaultshader", DBG(TEST_VMFAULT_SHADER), "Invoke a shader VM fault test and exit."},
128    {"testdmaperf", DBG(TEST_DMA_PERF), "Test DMA performance"},
129    {"testgds", DBG(TEST_GDS), "Test GDS."},
130    {"testgdsmm", DBG(TEST_GDS_MM), "Test GDS memory management."},
131    {"testgdsoamm", DBG(TEST_GDS_OA_MM), "Test GDS OA memory management."},
132 
133    DEBUG_NAMED_VALUE_END /* must be last */
134 };
135 
si_create_llvm_compiler(struct si_screen * sscreen)136 struct ac_llvm_compiler *si_create_llvm_compiler(struct si_screen *sscreen)
137 {
138 #if LLVM_AVAILABLE
139    struct ac_llvm_compiler *compiler = CALLOC_STRUCT(ac_llvm_compiler);
140    if (!compiler)
141       return NULL;
142 
143    /* Only create the less-optimizing version of the compiler on APUs
144     * predating Ryzen (Raven). */
145    bool create_low_opt_compiler =
146       !sscreen->info.has_dedicated_vram && sscreen->info.gfx_level <= GFX8;
147 
148    enum ac_target_machine_options tm_options =
149       (sscreen->debug_flags & DBG(CHECK_IR) ? AC_TM_CHECK_IR : 0) |
150       (create_low_opt_compiler ? AC_TM_CREATE_LOW_OPT : 0);
151 
152    if (!ac_init_llvm_compiler(compiler, sscreen->info.family, tm_options))
153       return NULL;
154 
155    compiler->passes = ac_create_llvm_passes(compiler->tm);
156    if (compiler->low_opt_tm)
157       compiler->low_opt_passes = ac_create_llvm_passes(compiler->low_opt_tm);
158 
159    return compiler;
160 #else
161    return NULL;
162 #endif
163 }
164 
si_init_aux_async_compute_ctx(struct si_screen * sscreen)165 void si_init_aux_async_compute_ctx(struct si_screen *sscreen)
166 {
167    assert(!sscreen->async_compute_context);
168    sscreen->async_compute_context =
169       si_create_context(&sscreen->b,
170                         SI_CONTEXT_FLAG_AUX |
171                         PIPE_CONTEXT_LOSE_CONTEXT_ON_RESET |
172                         (sscreen->options.aux_debug ? PIPE_CONTEXT_DEBUG : 0) |
173                         PIPE_CONTEXT_COMPUTE_ONLY);
174 
175    /* Limit the numbers of waves allocated for this context. */
176    if (sscreen->async_compute_context)
177       ((struct si_context*)sscreen->async_compute_context)->cs_max_waves_per_sh = 2;
178 }
179 
si_destroy_llvm_compiler(struct ac_llvm_compiler * compiler)180 static void si_destroy_llvm_compiler(struct ac_llvm_compiler *compiler)
181 {
182 #if LLVM_AVAILABLE
183    ac_destroy_llvm_compiler(compiler);
184    FREE(compiler);
185 #endif
186 }
187 
188 
decref_implicit_resource(struct hash_entry * entry)189 static void decref_implicit_resource(struct hash_entry *entry)
190 {
191    pipe_resource_reference((struct pipe_resource**)&entry->data, NULL);
192 }
193 
194 /*
195  * pipe_context
196  */
si_destroy_context(struct pipe_context * context)197 static void si_destroy_context(struct pipe_context *context)
198 {
199    struct si_context *sctx = (struct si_context *)context;
200 
201    /* Unreference the framebuffer normally to disable related logic
202     * properly.
203     */
204    struct pipe_framebuffer_state fb = {};
205    if (context->set_framebuffer_state)
206       context->set_framebuffer_state(context, &fb);
207 
208    si_release_all_descriptors(sctx);
209 
210    if (sctx->gfx_level >= GFX10 && sctx->has_graphics)
211       si_gfx11_destroy_query(sctx);
212 
213    if (sctx->sqtt) {
214       struct si_screen *sscreen = sctx->screen;
215       if (sscreen->info.has_stable_pstate && sscreen->b.num_contexts == 1 &&
216           !(sctx->context_flags & SI_CONTEXT_FLAG_AUX))
217           sscreen->ws->cs_set_pstate(&sctx->gfx_cs, RADEON_CTX_PSTATE_NONE);
218 
219       si_destroy_sqtt(sctx);
220    }
221 
222    si_utrace_fini(sctx);
223 
224    pipe_resource_reference(&sctx->esgs_ring, NULL);
225    pipe_resource_reference(&sctx->gsvs_ring, NULL);
226    pipe_resource_reference(&sctx->tess_rings, NULL);
227    pipe_resource_reference(&sctx->tess_rings_tmz, NULL);
228    pipe_resource_reference(&sctx->null_const_buf.buffer, NULL);
229    pipe_resource_reference(&sctx->sample_pos_buffer, NULL);
230    si_resource_reference(&sctx->border_color_buffer, NULL);
231    free(sctx->border_color_table);
232    si_resource_reference(&sctx->scratch_buffer, NULL);
233    si_resource_reference(&sctx->compute_scratch_buffer, NULL);
234    si_resource_reference(&sctx->wait_mem_scratch, NULL);
235    si_resource_reference(&sctx->wait_mem_scratch_tmz, NULL);
236    si_resource_reference(&sctx->small_prim_cull_info_buf, NULL);
237    si_resource_reference(&sctx->pipeline_stats_query_buf, NULL);
238    si_resource_reference(&sctx->last_const_upload_buffer, NULL);
239 
240    if (sctx->cs_preamble_state)
241       si_pm4_free_state(sctx, sctx->cs_preamble_state, ~0);
242    if (sctx->cs_preamble_state_tmz)
243       si_pm4_free_state(sctx, sctx->cs_preamble_state_tmz, ~0);
244 
245    if (sctx->fixed_func_tcs_shader_cache) {
246       hash_table_foreach(sctx->fixed_func_tcs_shader_cache, entry) {
247          sctx->b.delete_tcs_state(&sctx->b, entry->data);
248       }
249       _mesa_hash_table_destroy(sctx->fixed_func_tcs_shader_cache, NULL);
250    }
251 
252    if (sctx->custom_dsa_flush)
253       sctx->b.delete_depth_stencil_alpha_state(&sctx->b, sctx->custom_dsa_flush);
254    if (sctx->custom_blend_resolve)
255       sctx->b.delete_blend_state(&sctx->b, sctx->custom_blend_resolve);
256    if (sctx->custom_blend_fmask_decompress)
257       sctx->b.delete_blend_state(&sctx->b, sctx->custom_blend_fmask_decompress);
258    if (sctx->custom_blend_eliminate_fastclear)
259       sctx->b.delete_blend_state(&sctx->b, sctx->custom_blend_eliminate_fastclear);
260    if (sctx->custom_blend_dcc_decompress)
261       sctx->b.delete_blend_state(&sctx->b, sctx->custom_blend_dcc_decompress);
262    if (sctx->vs_blit_pos)
263       sctx->b.delete_vs_state(&sctx->b, sctx->vs_blit_pos);
264    if (sctx->vs_blit_pos_layered)
265       sctx->b.delete_vs_state(&sctx->b, sctx->vs_blit_pos_layered);
266    if (sctx->vs_blit_color)
267       sctx->b.delete_vs_state(&sctx->b, sctx->vs_blit_color);
268    if (sctx->vs_blit_color_layered)
269       sctx->b.delete_vs_state(&sctx->b, sctx->vs_blit_color_layered);
270    if (sctx->vs_blit_texcoord)
271       sctx->b.delete_vs_state(&sctx->b, sctx->vs_blit_texcoord);
272    if (sctx->cs_clear_buffer)
273       sctx->b.delete_compute_state(&sctx->b, sctx->cs_clear_buffer);
274    if (sctx->cs_clear_buffer_rmw)
275       sctx->b.delete_compute_state(&sctx->b, sctx->cs_clear_buffer_rmw);
276    if (sctx->cs_copy_buffer)
277       sctx->b.delete_compute_state(&sctx->b, sctx->cs_copy_buffer);
278    if (sctx->cs_ubyte_to_ushort)
279       sctx->b.delete_compute_state(&sctx->b, sctx->cs_ubyte_to_ushort);
280    for (unsigned i = 0; i < ARRAY_SIZE(sctx->cs_copy_image); i++) {
281       for (unsigned j = 0; j < ARRAY_SIZE(sctx->cs_copy_image[i]); j++) {
282          for (unsigned k = 0; k < ARRAY_SIZE(sctx->cs_copy_image[i][j]); k++) {
283             if (sctx->cs_copy_image[i][j][k])
284                sctx->b.delete_compute_state(&sctx->b, sctx->cs_copy_image[i][j][k]);
285          }
286       }
287    }
288    if (sctx->cs_clear_render_target)
289       sctx->b.delete_compute_state(&sctx->b, sctx->cs_clear_render_target);
290    if (sctx->cs_clear_render_target_1d_array)
291       sctx->b.delete_compute_state(&sctx->b, sctx->cs_clear_render_target_1d_array);
292    if (sctx->cs_clear_12bytes_buffer)
293       sctx->b.delete_compute_state(&sctx->b, sctx->cs_clear_12bytes_buffer);
294    for (unsigned i = 0; i < ARRAY_SIZE(sctx->cs_dcc_retile); i++) {
295       if (sctx->cs_dcc_retile[i])
296          sctx->b.delete_compute_state(&sctx->b, sctx->cs_dcc_retile[i]);
297    }
298    if (sctx->no_velems_state)
299       sctx->b.delete_vertex_elements_state(&sctx->b, sctx->no_velems_state);
300 
301    for (unsigned i = 0; i < ARRAY_SIZE(sctx->cs_fmask_expand); i++) {
302       for (unsigned j = 0; j < ARRAY_SIZE(sctx->cs_fmask_expand[i]); j++) {
303          if (sctx->cs_fmask_expand[i][j]) {
304             sctx->b.delete_compute_state(&sctx->b, sctx->cs_fmask_expand[i][j]);
305          }
306       }
307    }
308 
309    for (unsigned i = 0; i < ARRAY_SIZE(sctx->cs_clear_dcc_msaa); i++) {
310       for (unsigned j = 0; j < ARRAY_SIZE(sctx->cs_clear_dcc_msaa[i]); j++) {
311          for (unsigned k = 0; k < ARRAY_SIZE(sctx->cs_clear_dcc_msaa[i][j]); k++) {
312             for (unsigned l = 0; l < ARRAY_SIZE(sctx->cs_clear_dcc_msaa[i][j][k]); l++) {
313                for (unsigned m = 0; m < ARRAY_SIZE(sctx->cs_clear_dcc_msaa[i][j][k][l]); m++) {
314                   if (sctx->cs_clear_dcc_msaa[i][j][k][l][m])
315                      sctx->b.delete_compute_state(&sctx->b, sctx->cs_clear_dcc_msaa[i][j][k][l][m]);
316                }
317             }
318          }
319       }
320    }
321 
322    if (sctx->blitter)
323       util_blitter_destroy(sctx->blitter);
324 
325    if (sctx->query_result_shader)
326       sctx->b.delete_compute_state(&sctx->b, sctx->query_result_shader);
327    if (sctx->sh_query_result_shader)
328       sctx->b.delete_compute_state(&sctx->b, sctx->sh_query_result_shader);
329 
330    sctx->ws->cs_destroy(&sctx->gfx_cs);
331    if (sctx->ctx)
332       sctx->ws->ctx_destroy(sctx->ctx);
333    if (sctx->sdma_cs) {
334       sctx->ws->cs_destroy(sctx->sdma_cs);
335       free(sctx->sdma_cs);
336    }
337 
338    if (sctx->dirty_implicit_resources)
339       _mesa_hash_table_destroy(sctx->dirty_implicit_resources,
340                                decref_implicit_resource);
341 
342    if (sctx->b.stream_uploader)
343       u_upload_destroy(sctx->b.stream_uploader);
344    if (sctx->b.const_uploader && sctx->b.const_uploader != sctx->b.stream_uploader)
345       u_upload_destroy(sctx->b.const_uploader);
346    if (sctx->cached_gtt_allocator)
347       u_upload_destroy(sctx->cached_gtt_allocator);
348 
349    slab_destroy_child(&sctx->pool_transfers);
350    slab_destroy_child(&sctx->pool_transfers_unsync);
351 
352    u_suballocator_destroy(&sctx->allocator_zeroed_memory);
353 
354    sctx->ws->fence_reference(sctx->ws, &sctx->last_gfx_fence, NULL);
355    si_resource_reference(&sctx->eop_bug_scratch, NULL);
356    si_resource_reference(&sctx->eop_bug_scratch_tmz, NULL);
357    si_resource_reference(&sctx->shadowing.registers, NULL);
358    si_resource_reference(&sctx->shadowing.csa, NULL);
359 
360    if (sctx->compiler)
361       si_destroy_llvm_compiler(sctx->compiler);
362 
363    si_saved_cs_reference(&sctx->current_saved_cs, NULL);
364 
365    _mesa_hash_table_destroy(sctx->tex_handles, NULL);
366    _mesa_hash_table_destroy(sctx->img_handles, NULL);
367 
368    util_dynarray_fini(&sctx->resident_tex_handles);
369    util_dynarray_fini(&sctx->resident_img_handles);
370    util_dynarray_fini(&sctx->resident_tex_needs_color_decompress);
371    util_dynarray_fini(&sctx->resident_img_needs_color_decompress);
372    util_dynarray_fini(&sctx->resident_tex_needs_depth_decompress);
373 
374    if (!(sctx->context_flags & SI_CONTEXT_FLAG_AUX))
375       p_atomic_dec(&context->screen->num_contexts);
376 
377    if (sctx->cs_blit_shaders) {
378       hash_table_foreach(sctx->cs_blit_shaders, entry) {
379          context->delete_compute_state(context, entry->data);
380       }
381       _mesa_hash_table_destroy(sctx->cs_blit_shaders, NULL);
382    }
383 
384    FREE(sctx);
385 }
386 
si_get_reset_status(struct pipe_context * ctx)387 static enum pipe_reset_status si_get_reset_status(struct pipe_context *ctx)
388 {
389    struct si_context *sctx = (struct si_context *)ctx;
390    if (sctx->context_flags & SI_CONTEXT_FLAG_AUX)
391       return PIPE_NO_RESET;
392 
393    bool needs_reset, reset_completed;
394    enum pipe_reset_status status = sctx->ws->ctx_query_reset_status(sctx->ctx, false,
395                                                                     &needs_reset, &reset_completed);
396 
397    if (status != PIPE_NO_RESET) {
398       if (sctx->has_reset_been_notified && reset_completed)
399          return PIPE_NO_RESET;
400 
401       sctx->has_reset_been_notified = true;
402 
403       if (!(sctx->context_flags & SI_CONTEXT_FLAG_AUX)) {
404          /* Call the gallium frontend to set a no-op API dispatch. */
405          if (needs_reset && sctx->device_reset_callback.reset)
406             sctx->device_reset_callback.reset(sctx->device_reset_callback.data, status);
407       }
408    }
409    return status;
410 }
411 
si_set_device_reset_callback(struct pipe_context * ctx,const struct pipe_device_reset_callback * cb)412 static void si_set_device_reset_callback(struct pipe_context *ctx,
413                                          const struct pipe_device_reset_callback *cb)
414 {
415    struct si_context *sctx = (struct si_context *)ctx;
416 
417    if (cb)
418       sctx->device_reset_callback = *cb;
419    else
420       memset(&sctx->device_reset_callback, 0, sizeof(sctx->device_reset_callback));
421 }
422 
423 /* Apitrace profiling:
424  *   1) qapitrace : Tools -> Profile: Measure CPU & GPU times
425  *   2) In the middle panel, zoom in (mouse wheel) on some bad draw call
426  *      and remember its number.
427  *   3) In Mesa, enable queries and performance counters around that draw
428  *      call and print the results.
429  *   4) glretrace --benchmark --markers ..
430  */
si_emit_string_marker(struct pipe_context * ctx,const char * string,int len)431 static void si_emit_string_marker(struct pipe_context *ctx, const char *string, int len)
432 {
433    struct si_context *sctx = (struct si_context *)ctx;
434 
435    dd_parse_apitrace_marker(string, len, &sctx->apitrace_call_number);
436 
437    if (sctx->sqtt_enabled)
438       si_write_user_event(sctx, &sctx->gfx_cs, UserEventTrigger, string, len);
439 
440    if (sctx->log)
441       u_log_printf(sctx->log, "\nString marker: %*s\n", len, string);
442 }
443 
si_set_debug_callback(struct pipe_context * ctx,const struct util_debug_callback * cb)444 static void si_set_debug_callback(struct pipe_context *ctx, const struct util_debug_callback *cb)
445 {
446    struct si_context *sctx = (struct si_context *)ctx;
447    struct si_screen *screen = sctx->screen;
448 
449    util_queue_finish(&screen->shader_compiler_queue);
450    util_queue_finish(&screen->shader_compiler_queue_opt_variants);
451 
452    if (cb)
453       sctx->debug = *cb;
454    else
455       memset(&sctx->debug, 0, sizeof(sctx->debug));
456 }
457 
si_set_log_context(struct pipe_context * ctx,struct u_log_context * log)458 static void si_set_log_context(struct pipe_context *ctx, struct u_log_context *log)
459 {
460    struct si_context *sctx = (struct si_context *)ctx;
461    sctx->log = log;
462 
463    if (log)
464       u_log_add_auto_logger(log, si_auto_log_cs, sctx);
465 }
466 
si_set_context_param(struct pipe_context * ctx,enum pipe_context_param param,unsigned value)467 static void si_set_context_param(struct pipe_context *ctx, enum pipe_context_param param,
468                                  unsigned value)
469 {
470    struct radeon_winsys *ws = ((struct si_context *)ctx)->ws;
471 
472    switch (param) {
473    case PIPE_CONTEXT_PARAM_UPDATE_THREAD_SCHEDULING:
474       ws->pin_threads_to_L3_cache(ws, value);
475       break;
476    default:;
477    }
478 }
479 
si_set_frontend_noop(struct pipe_context * ctx,bool enable)480 static void si_set_frontend_noop(struct pipe_context *ctx, bool enable)
481 {
482    struct si_context *sctx = (struct si_context *)ctx;
483 
484    ctx->flush(ctx, NULL, PIPE_FLUSH_ASYNC);
485    sctx->is_noop = enable;
486 }
487 
si_create_context(struct pipe_screen * screen,unsigned flags)488 static struct pipe_context *si_create_context(struct pipe_screen *screen, unsigned flags)
489 {
490    struct si_screen *sscreen = (struct si_screen *)screen;
491    STATIC_ASSERT(DBG_COUNT <= 64);
492 
493    /* Don't create a context if it's not compute-only and hw is compute-only. */
494    if (!sscreen->info.has_graphics && !(flags & PIPE_CONTEXT_COMPUTE_ONLY)) {
495       fprintf(stderr, "radeonsi: can't create a graphics context on a compute chip\n");
496       return NULL;
497    }
498 
499    struct si_context *sctx = CALLOC_STRUCT(si_context);
500    struct radeon_winsys *ws = sscreen->ws;
501    int shader, i;
502    enum radeon_ctx_priority priority;
503 
504    if (!sctx) {
505       fprintf(stderr, "radeonsi: can't allocate a context\n");
506       return NULL;
507    }
508 
509    sctx->has_graphics = sscreen->info.gfx_level == GFX6 || !(flags & PIPE_CONTEXT_COMPUTE_ONLY);
510 
511    if (flags & PIPE_CONTEXT_DEBUG)
512       sscreen->record_llvm_ir = true; /* racy but not critical */
513 
514    sctx->b.screen = screen; /* this must be set first */
515    sctx->b.priv = NULL;
516    sctx->b.destroy = si_destroy_context;
517    sctx->screen = sscreen; /* Easy accessing of screen/winsys. */
518    sctx->is_debug = (flags & PIPE_CONTEXT_DEBUG) != 0;
519    sctx->context_flags = flags;
520 
521    slab_create_child(&sctx->pool_transfers, &sscreen->pool_transfers);
522    slab_create_child(&sctx->pool_transfers_unsync, &sscreen->pool_transfers);
523 
524    sctx->ws = sscreen->ws;
525    sctx->family = sscreen->info.family;
526    sctx->gfx_level = sscreen->info.gfx_level;
527    sctx->vcn_ip_ver = sscreen->info.vcn_ip_version;
528 
529    if (sctx->gfx_level == GFX7 || sctx->gfx_level == GFX8 || sctx->gfx_level == GFX9) {
530       sctx->eop_bug_scratch = si_aligned_buffer_create(
531          &sscreen->b, PIPE_RESOURCE_FLAG_UNMAPPABLE | SI_RESOURCE_FLAG_DRIVER_INTERNAL,
532          PIPE_USAGE_DEFAULT, 16 * sscreen->info.max_render_backends, 256);
533       if (!sctx->eop_bug_scratch) {
534          fprintf(stderr, "radeonsi: can't create eop_bug_scratch\n");
535          goto fail;
536       }
537    }
538 
539    if (flags & PIPE_CONTEXT_HIGH_PRIORITY) {
540       priority = RADEON_CTX_PRIORITY_HIGH;
541    } else if (flags & PIPE_CONTEXT_LOW_PRIORITY) {
542       priority = RADEON_CTX_PRIORITY_LOW;
543    } else {
544       priority = RADEON_CTX_PRIORITY_MEDIUM;
545    }
546 
547    bool allow_context_lost = flags & PIPE_CONTEXT_LOSE_CONTEXT_ON_RESET;
548 
549    /* Initialize the context handle and the command stream. */
550    sctx->ctx = sctx->ws->ctx_create(sctx->ws, priority, allow_context_lost);
551    if (!sctx->ctx && priority != RADEON_CTX_PRIORITY_MEDIUM) {
552       /* Context priority should be treated as a hint. If context creation
553        * fails with the requested priority, for example because the caller
554        * lacks CAP_SYS_NICE capability or other system resource constraints,
555        * fallback to normal priority.
556        */
557       priority = RADEON_CTX_PRIORITY_MEDIUM;
558       sctx->ctx = sctx->ws->ctx_create(sctx->ws, priority, allow_context_lost);
559    }
560    if (!sctx->ctx) {
561       fprintf(stderr, "radeonsi: can't create radeon_winsys_ctx\n");
562       goto fail;
563    }
564 
565    ws->cs_create(&sctx->gfx_cs, sctx->ctx, sctx->has_graphics ? AMD_IP_GFX : AMD_IP_COMPUTE,
566                  (void *)si_flush_gfx_cs, sctx);
567 
568    /* Initialize private allocators. */
569    u_suballocator_init(&sctx->allocator_zeroed_memory, &sctx->b, 128 * 1024, 0,
570                        PIPE_USAGE_DEFAULT,
571                        SI_RESOURCE_FLAG_CLEAR | SI_RESOURCE_FLAG_32BIT, false);
572 
573    sctx->cached_gtt_allocator = u_upload_create(&sctx->b, 16 * 1024, 0, PIPE_USAGE_STAGING, 0);
574    if (!sctx->cached_gtt_allocator) {
575       fprintf(stderr, "radeonsi: can't create cached_gtt_allocator\n");
576       goto fail;
577    }
578 
579    /* Initialize public allocators. Unify uploaders as follows:
580     * - dGPUs: The const uploader writes to VRAM and the stream uploader writes to RAM.
581     * - APUs: There is only one uploader instance writing to RAM. VRAM has the same perf on APUs.
582     */
583    bool is_apu = !sscreen->info.has_dedicated_vram;
584    sctx->b.stream_uploader =
585       u_upload_create(&sctx->b, 1024 * 1024, 0,
586                       sscreen->debug_flags & DBG(NO_WC_STREAM) ? PIPE_USAGE_STAGING
587                                                                : PIPE_USAGE_STREAM,
588                       SI_RESOURCE_FLAG_32BIT); /* same flags as const_uploader */
589    if (!sctx->b.stream_uploader) {
590       fprintf(stderr, "radeonsi: can't create stream_uploader\n");
591       goto fail;
592    }
593 
594    if (is_apu) {
595       sctx->b.const_uploader = sctx->b.stream_uploader;
596    } else {
597       sctx->b.const_uploader =
598          u_upload_create(&sctx->b, 256 * 1024, 0, PIPE_USAGE_DEFAULT,
599                          SI_RESOURCE_FLAG_32BIT);
600       if (!sctx->b.const_uploader) {
601          fprintf(stderr, "radeonsi: can't create const_uploader\n");
602          goto fail;
603       }
604    }
605 
606    /* Border colors. */
607    if (sscreen->info.has_3d_cube_border_color_mipmap) {
608       sctx->border_color_table = malloc(SI_MAX_BORDER_COLORS * sizeof(*sctx->border_color_table));
609       if (!sctx->border_color_table) {
610          fprintf(stderr, "radeonsi: can't create border_color_table\n");
611          goto fail;
612       }
613 
614       sctx->border_color_buffer = si_resource(pipe_buffer_create(
615          screen, 0, PIPE_USAGE_DEFAULT, SI_MAX_BORDER_COLORS * sizeof(*sctx->border_color_table)));
616       if (!sctx->border_color_buffer) {
617          fprintf(stderr, "radeonsi: can't create border_color_buffer\n");
618          goto fail;
619       }
620 
621       sctx->border_color_map =
622          ws->buffer_map(ws, sctx->border_color_buffer->buf, NULL, PIPE_MAP_WRITE);
623       if (!sctx->border_color_map) {
624          fprintf(stderr, "radeonsi: can't map border_color_buffer\n");
625          goto fail;
626       }
627    }
628 
629    sctx->ngg = sscreen->use_ngg;
630    si_shader_change_notify(sctx);
631 
632    /* Initialize context functions used by graphics and compute. */
633    if (sctx->gfx_level >= GFX10)
634       sctx->emit_cache_flush = gfx10_emit_cache_flush;
635    else
636       sctx->emit_cache_flush = gfx6_emit_cache_flush;
637 
638    sctx->b.emit_string_marker = si_emit_string_marker;
639    sctx->b.set_debug_callback = si_set_debug_callback;
640    sctx->b.set_log_context = si_set_log_context;
641    sctx->b.set_context_param = si_set_context_param;
642    sctx->b.get_device_reset_status = si_get_reset_status;
643    sctx->b.set_device_reset_callback = si_set_device_reset_callback;
644    sctx->b.set_frontend_noop = si_set_frontend_noop;
645 
646    si_init_all_descriptors(sctx);
647    si_init_buffer_functions(sctx);
648    si_init_clear_functions(sctx);
649    si_init_blit_functions(sctx);
650    si_init_compute_functions(sctx);
651    si_init_compute_blit_functions(sctx);
652    si_init_debug_functions(sctx);
653    si_init_fence_functions(sctx);
654    si_init_query_functions(sctx);
655    si_init_state_compute_functions(sctx);
656    si_init_context_texture_functions(sctx);
657 
658    /* Initialize graphics-only context functions. */
659    if (sctx->has_graphics) {
660       if (sctx->gfx_level >= GFX10)
661          si_gfx11_init_query(sctx);
662       si_init_msaa_functions(sctx);
663       si_init_shader_functions(sctx);
664       si_init_state_functions(sctx);
665       si_init_streamout_functions(sctx);
666       si_init_viewport_functions(sctx);
667 
668       sctx->blitter = util_blitter_create(&sctx->b);
669       if (sctx->blitter == NULL) {
670          fprintf(stderr, "radeonsi: can't create blitter\n");
671          goto fail;
672       }
673       sctx->blitter->skip_viewport_restore = true;
674 
675       /* Some states are expected to be always non-NULL. */
676       sctx->noop_blend = util_blitter_get_noop_blend_state(sctx->blitter);
677       sctx->queued.named.blend = sctx->noop_blend;
678 
679       sctx->noop_dsa = util_blitter_get_noop_dsa_state(sctx->blitter);
680       sctx->queued.named.dsa = sctx->noop_dsa;
681 
682       sctx->no_velems_state = sctx->b.create_vertex_elements_state(&sctx->b, 0, NULL);
683       sctx->vertex_elements = sctx->no_velems_state;
684 
685       sctx->discard_rasterizer_state = util_blitter_get_discard_rasterizer_state(sctx->blitter);
686       sctx->queued.named.rasterizer = sctx->discard_rasterizer_state;
687 
688       switch (sctx->gfx_level) {
689       case GFX6:
690          si_init_draw_functions_GFX6(sctx);
691          break;
692       case GFX7:
693          si_init_draw_functions_GFX7(sctx);
694          break;
695       case GFX8:
696          si_init_draw_functions_GFX8(sctx);
697          break;
698       case GFX9:
699          si_init_draw_functions_GFX9(sctx);
700          break;
701       case GFX10:
702          si_init_draw_functions_GFX10(sctx);
703          break;
704       case GFX10_3:
705          si_init_draw_functions_GFX10_3(sctx);
706          break;
707       case GFX11:
708          si_init_draw_functions_GFX11(sctx);
709          break;
710       case GFX11_5:
711          si_init_draw_functions_GFX11_5(sctx);
712          break;
713       default:
714          unreachable("unhandled gfx level");
715       }
716    }
717 
718    sctx->sample_mask = 0xffff;
719 
720    /* Initialize multimedia functions. */
721    if (sscreen->info.ip[AMD_IP_UVD].num_queues ||
722        ((sscreen->info.vcn_ip_version >= VCN_4_0_0) ?
723 	 sscreen->info.ip[AMD_IP_VCN_UNIFIED].num_queues : sscreen->info.ip[AMD_IP_VCN_DEC].num_queues) ||
724        sscreen->info.ip[AMD_IP_VCN_JPEG].num_queues || sscreen->info.ip[AMD_IP_VCE].num_queues ||
725        sscreen->info.ip[AMD_IP_UVD_ENC].num_queues || sscreen->info.ip[AMD_IP_VCN_ENC].num_queues ||
726        sscreen->info.ip[AMD_IP_VPE].num_queues) {
727       sctx->b.create_video_codec = si_uvd_create_decoder;
728       sctx->b.create_video_buffer = si_video_buffer_create;
729       if (screen->resource_create_with_modifiers)
730          sctx->b.create_video_buffer_with_modifiers = si_video_buffer_create_with_modifiers;
731    } else {
732       sctx->b.create_video_codec = vl_create_decoder;
733       sctx->b.create_video_buffer = vl_video_buffer_create;
734    }
735 
736    /* GFX7 cannot unbind a constant buffer (S_BUFFER_LOAD doesn't skip loads
737     * if NUM_RECORDS == 0). We need to use a dummy buffer instead. */
738    if (sctx->gfx_level == GFX7) {
739       sctx->null_const_buf.buffer =
740          pipe_aligned_buffer_create(screen,
741                                     PIPE_RESOURCE_FLAG_UNMAPPABLE | SI_RESOURCE_FLAG_32BIT |
742                                     SI_RESOURCE_FLAG_DRIVER_INTERNAL,
743                                     PIPE_USAGE_DEFAULT, 16,
744                                     sctx->screen->info.tcc_cache_line_size);
745       if (!sctx->null_const_buf.buffer) {
746          fprintf(stderr, "radeonsi: can't create null_const_buf\n");
747          goto fail;
748       }
749       sctx->null_const_buf.buffer_size = sctx->null_const_buf.buffer->width0;
750 
751       unsigned start_shader = sctx->has_graphics ? 0 : PIPE_SHADER_COMPUTE;
752       for (shader = start_shader; shader < SI_NUM_SHADERS; shader++) {
753          for (i = 0; i < SI_NUM_CONST_BUFFERS; i++) {
754             sctx->b.set_constant_buffer(&sctx->b, shader, i, false, &sctx->null_const_buf);
755          }
756       }
757 
758       si_set_internal_const_buffer(sctx, SI_HS_CONST_DEFAULT_TESS_LEVELS, &sctx->null_const_buf);
759       si_set_internal_const_buffer(sctx, SI_VS_CONST_INSTANCE_DIVISORS, &sctx->null_const_buf);
760       si_set_internal_const_buffer(sctx, SI_VS_CONST_CLIP_PLANES, &sctx->null_const_buf);
761       si_set_internal_const_buffer(sctx, SI_PS_CONST_POLY_STIPPLE, &sctx->null_const_buf);
762       si_set_internal_const_buffer(sctx, SI_PS_CONST_SAMPLE_POSITIONS, &sctx->null_const_buf);
763    }
764 
765    /* Bindless handles. */
766    sctx->tex_handles = _mesa_hash_table_create(NULL, _mesa_hash_pointer, _mesa_key_pointer_equal);
767    sctx->img_handles = _mesa_hash_table_create(NULL, _mesa_hash_pointer, _mesa_key_pointer_equal);
768 
769    util_dynarray_init(&sctx->resident_tex_handles, NULL);
770    util_dynarray_init(&sctx->resident_img_handles, NULL);
771    util_dynarray_init(&sctx->resident_tex_needs_color_decompress, NULL);
772    util_dynarray_init(&sctx->resident_img_needs_color_decompress, NULL);
773    util_dynarray_init(&sctx->resident_tex_needs_depth_decompress, NULL);
774 
775    sctx->dirty_implicit_resources = _mesa_pointer_hash_table_create(NULL);
776    if (!sctx->dirty_implicit_resources) {
777       fprintf(stderr, "radeonsi: can't create dirty_implicit_resources\n");
778       goto fail;
779    }
780 
781    /* The remainder of this function initializes the gfx CS and must be last. */
782    assert(sctx->gfx_cs.current.cdw == 0);
783 
784    si_init_cp_reg_shadowing(sctx);
785 
786    /* Set immutable fields of shader keys. */
787    if (sctx->gfx_level >= GFX9) {
788       /* The LS output / HS input layout can be communicated
789        * directly instead of via user SGPRs for merged LS-HS.
790        * This also enables jumping over the VS for HS-only waves.
791        */
792       sctx->shader.tcs.key.ge.opt.prefer_mono = 1;
793 
794       /* This enables jumping over the VS for GS-only waves. */
795       sctx->shader.gs.key.ge.opt.prefer_mono = 1;
796    }
797 
798    si_utrace_init(sctx);
799 
800    si_begin_new_gfx_cs(sctx, true);
801    assert(sctx->gfx_cs.current.cdw == sctx->initial_gfx_cs_size);
802 
803    if (sctx->gfx_level >= GFX9 && sctx->gfx_level < GFX11) {
804       sctx->wait_mem_scratch =
805            si_aligned_buffer_create(screen,
806                                     PIPE_RESOURCE_FLAG_UNMAPPABLE |
807                                     SI_RESOURCE_FLAG_DRIVER_INTERNAL,
808                                     PIPE_USAGE_DEFAULT, 4,
809                                     sscreen->info.tcc_cache_line_size);
810       if (!sctx->wait_mem_scratch) {
811          fprintf(stderr, "radeonsi: can't create wait_mem_scratch\n");
812          goto fail;
813       }
814 
815       si_cp_write_data(sctx, sctx->wait_mem_scratch, 0, 4, V_370_MEM, V_370_ME,
816                        &sctx->wait_mem_number);
817    }
818 
819    if (sctx->gfx_level == GFX7) {
820       /* Clear the NULL constant buffer, because loads should return zeros.
821        * Note that this forces CP DMA to be used, because clover deadlocks
822        * for some reason when the compute codepath is used.
823        */
824       uint32_t clear_value = 0;
825       si_clear_buffer(sctx, sctx->null_const_buf.buffer, 0, sctx->null_const_buf.buffer->width0,
826                       &clear_value, 4, SI_OP_SYNC_AFTER, SI_COHERENCY_SHADER,
827                       SI_CP_DMA_CLEAR_METHOD);
828    }
829 
830    if (!(flags & SI_CONTEXT_FLAG_AUX)) {
831       p_atomic_inc(&screen->num_contexts);
832 
833       /* Check if the aux_context needs to be recreated */
834       for (unsigned i = 0; i < ARRAY_SIZE(sscreen->aux_contexts); i++) {
835          struct si_context *saux = si_get_aux_context(&sscreen->aux_contexts[i]);
836          enum pipe_reset_status status =
837             sctx->ws->ctx_query_reset_status(saux->ctx, true, NULL, NULL);
838 
839          if (status != PIPE_NO_RESET) {
840             /* We lost the aux_context, create a new one */
841             unsigned context_flags = saux->context_flags;
842             struct u_log_context *aux_log = saux->log;
843             saux->b.set_log_context(&saux->b, NULL);
844             saux->b.destroy(&saux->b);
845 
846             saux = (struct si_context *)si_create_context(&sscreen->b, context_flags);
847             saux->b.set_log_context(&saux->b, aux_log);
848 
849             sscreen->aux_contexts[i].ctx = &saux->b;
850          }
851          si_put_aux_context_flush(&sscreen->aux_contexts[i]);
852       }
853 
854       simple_mtx_lock(&sscreen->async_compute_context_lock);
855       if (sscreen->async_compute_context) {
856          struct si_context *compute_ctx = (struct si_context*)sscreen->async_compute_context;
857          enum pipe_reset_status status =
858             sctx->ws->ctx_query_reset_status(compute_ctx->ctx, true, NULL, NULL);
859 
860          if (status != PIPE_NO_RESET) {
861             sscreen->async_compute_context->destroy(sscreen->async_compute_context);
862             sscreen->async_compute_context = NULL;
863          }
864       }
865       simple_mtx_unlock(&sscreen->async_compute_context_lock);
866    }
867 
868    sctx->initial_gfx_cs_size = sctx->gfx_cs.current.cdw;
869    sctx->last_timestamp_cmd = NULL;
870 
871    sctx->cs_blit_shaders = _mesa_hash_table_create_u32_keys(NULL);
872    if (!sctx->cs_blit_shaders)
873       goto fail;
874 
875    return &sctx->b;
876 fail:
877    fprintf(stderr, "radeonsi: Failed to create a context.\n");
878    si_destroy_context(&sctx->b);
879    return NULL;
880 }
881 
si_is_resource_busy(struct pipe_screen * screen,struct pipe_resource * resource,unsigned usage)882 static bool si_is_resource_busy(struct pipe_screen *screen, struct pipe_resource *resource,
883                                 unsigned usage)
884 {
885    struct radeon_winsys *ws = ((struct si_screen *)screen)->ws;
886 
887    return !ws->buffer_wait(ws, si_resource(resource)->buf, 0,
888                            /* If mapping for write, we need to wait for all reads and writes.
889                             * If mapping for read, we only need to wait for writes.
890                             */
891                            usage & PIPE_MAP_WRITE ? RADEON_USAGE_READWRITE : RADEON_USAGE_WRITE);
892 }
893 
si_pipe_create_context(struct pipe_screen * screen,void * priv,unsigned flags)894 static struct pipe_context *si_pipe_create_context(struct pipe_screen *screen, void *priv,
895                                                    unsigned flags)
896 {
897    struct si_screen *sscreen = (struct si_screen *)screen;
898    struct pipe_context *ctx;
899 
900    if (sscreen->debug_flags & DBG(CHECK_VM))
901       flags |= PIPE_CONTEXT_DEBUG;
902 
903    ctx = si_create_context(screen, flags);
904 
905    if (ctx && sscreen->info.gfx_level >= GFX9 && sscreen->debug_flags & DBG(SQTT)) {
906       /* Auto-enable stable performance profile if possible. */
907       if (sscreen->info.has_stable_pstate && screen->num_contexts == 1 &&
908           sscreen->ws->cs_set_pstate(&((struct si_context *)ctx)->gfx_cs, RADEON_CTX_PSTATE_PEAK)) {
909       }
910 
911       if (ac_check_profile_state(&sscreen->info)) {
912          fprintf(stderr, "radeonsi: Canceling RGP trace request as a hang condition has been "
913                          "detected. Force the GPU into a profiling mode with e.g. "
914                          "\"echo profile_peak  > "
915                          "/sys/class/drm/card0/device/power_dpm_force_performance_level\"\n");
916       } else if (!si_init_sqtt((struct si_context *)ctx)) {
917          FREE(ctx);
918          return NULL;
919       }
920    }
921 
922    if (!(flags & PIPE_CONTEXT_PREFER_THREADED))
923       return ctx;
924 
925    /* Clover (compute-only) is unsupported. */
926    if (flags & PIPE_CONTEXT_COMPUTE_ONLY)
927       return ctx;
928 
929    /* When shaders are logged to stderr, asynchronous compilation is
930     * disabled too. */
931    if (sscreen->debug_flags & DBG_ALL_SHADERS)
932       return ctx;
933 
934    /* Use asynchronous flushes only on amdgpu, since the radeon
935     * implementation for fence_server_sync is incomplete. */
936    struct pipe_context *tc =
937       threaded_context_create(ctx, &sscreen->pool_transfers,
938                               si_replace_buffer_storage,
939                               &(struct threaded_context_options){
940                                  .create_fence = sscreen->info.is_amdgpu ?
941                                        si_create_fence : NULL,
942                                  .is_resource_busy = si_is_resource_busy,
943                                  .driver_calls_flush_notify = true,
944                                  .unsynchronized_create_fence_fd = true,
945                               },
946                               &((struct si_context *)ctx)->tc);
947 
948    if (tc && tc != ctx)
949       threaded_context_init_bytes_mapped_limit((struct threaded_context *)tc, 4);
950 
951    return tc;
952 }
953 
954 /*
955  * pipe_screen
956  */
si_destroy_screen(struct pipe_screen * pscreen)957 static void si_destroy_screen(struct pipe_screen *pscreen)
958 {
959    struct si_screen *sscreen = (struct si_screen *)pscreen;
960    struct si_shader_part *parts[] = {sscreen->tcs_epilogs, sscreen->ps_prologs,
961                                      sscreen->ps_epilogs};
962    unsigned i;
963 
964    if (!sscreen->ws->unref(sscreen->ws))
965       return;
966 
967    if (sscreen->debug_flags & DBG(CACHE_STATS)) {
968       printf("live shader cache:   hits = %u, misses = %u\n", sscreen->live_shader_cache.hits,
969              sscreen->live_shader_cache.misses);
970       printf("memory shader cache: hits = %u, misses = %u\n", sscreen->num_memory_shader_cache_hits,
971              sscreen->num_memory_shader_cache_misses);
972       printf("disk shader cache:   hits = %u, misses = %u\n", sscreen->num_disk_shader_cache_hits,
973              sscreen->num_disk_shader_cache_misses);
974    }
975 
976    si_resource_reference(&sscreen->attribute_ring, NULL);
977 
978    util_queue_destroy(&sscreen->shader_compiler_queue);
979    util_queue_destroy(&sscreen->shader_compiler_queue_opt_variants);
980 
981    for (unsigned i = 0; i < ARRAY_SIZE(sscreen->aux_contexts); i++) {
982       if (!sscreen->aux_contexts[i].ctx)
983          continue;
984 
985       struct si_context *saux = si_get_aux_context(&sscreen->aux_contexts[i]);
986       struct u_log_context *aux_log = saux->log;
987       if (aux_log) {
988          saux->b.set_log_context(&saux->b, NULL);
989          u_log_context_destroy(aux_log);
990          FREE(aux_log);
991       }
992 
993       saux->b.destroy(&saux->b);
994       mtx_unlock(&sscreen->aux_contexts[i].lock);
995       mtx_destroy(&sscreen->aux_contexts[i].lock);
996    }
997 
998    simple_mtx_destroy(&sscreen->async_compute_context_lock);
999    if (sscreen->async_compute_context) {
1000       sscreen->async_compute_context->destroy(sscreen->async_compute_context);
1001    }
1002 
1003    /* Release the reference on glsl types of the compiler threads. */
1004    glsl_type_singleton_decref();
1005 
1006    for (i = 0; i < ARRAY_SIZE(sscreen->compiler); i++) {
1007       if (sscreen->compiler[i])
1008          si_destroy_llvm_compiler(sscreen->compiler[i]);
1009    }
1010 
1011    for (i = 0; i < ARRAY_SIZE(sscreen->compiler_lowp); i++) {
1012       if (sscreen->compiler_lowp[i])
1013          si_destroy_llvm_compiler(sscreen->compiler_lowp[i]);
1014    }
1015 
1016    /* Free shader parts. */
1017    for (i = 0; i < ARRAY_SIZE(parts); i++) {
1018       while (parts[i]) {
1019          struct si_shader_part *part = parts[i];
1020 
1021          parts[i] = part->next;
1022          si_shader_binary_clean(&part->binary);
1023          FREE(part);
1024       }
1025    }
1026    simple_mtx_destroy(&sscreen->shader_parts_mutex);
1027    si_destroy_shader_cache(sscreen);
1028 
1029    si_destroy_perfcounters(sscreen);
1030    si_gpu_load_kill_thread(sscreen);
1031 
1032    simple_mtx_destroy(&sscreen->gpu_load_mutex);
1033    simple_mtx_destroy(&sscreen->gds_mutex);
1034 
1035    radeon_bo_reference(sscreen->ws, &sscreen->gds_oa, NULL);
1036 
1037    slab_destroy_parent(&sscreen->pool_transfers);
1038 
1039    disk_cache_destroy(sscreen->disk_shader_cache);
1040    util_live_shader_cache_deinit(&sscreen->live_shader_cache);
1041    util_idalloc_mt_fini(&sscreen->buffer_ids);
1042    util_vertex_state_cache_deinit(&sscreen->vertex_state_cache);
1043 
1044    sscreen->ws->destroy(sscreen->ws);
1045    FREE(sscreen->nir_options);
1046    FREE(sscreen);
1047 }
1048 
si_init_gs_info(struct si_screen * sscreen)1049 static void si_init_gs_info(struct si_screen *sscreen)
1050 {
1051    sscreen->gs_table_depth = ac_get_gs_table_depth(sscreen->info.gfx_level, sscreen->info.family);
1052 }
1053 
si_test_vmfault(struct si_screen * sscreen,uint64_t test_flags)1054 static void si_test_vmfault(struct si_screen *sscreen, uint64_t test_flags)
1055 {
1056    struct pipe_context *ctx = sscreen->aux_context.general.ctx;
1057    struct si_context *sctx = (struct si_context *)ctx;
1058    struct pipe_resource *buf = pipe_buffer_create_const0(&sscreen->b, 0, PIPE_USAGE_DEFAULT, 64);
1059 
1060    if (!buf) {
1061       puts("Buffer allocation failed.");
1062       exit(1);
1063    }
1064 
1065    si_resource(buf)->gpu_address = 0; /* cause a VM fault */
1066 
1067    if (test_flags & DBG(TEST_VMFAULT_CP)) {
1068       si_cp_dma_copy_buffer(sctx, buf, buf, 0, 4, 4, SI_OP_SYNC_BEFORE_AFTER,
1069                             SI_COHERENCY_NONE, L2_BYPASS);
1070       ctx->flush(ctx, NULL, 0);
1071       puts("VM fault test: CP - done.");
1072    }
1073    if (test_flags & DBG(TEST_VMFAULT_SHADER)) {
1074       util_test_constant_buffer(ctx, buf);
1075       puts("VM fault test: Shader - done.");
1076    }
1077    exit(0);
1078 }
1079 
si_test_gds_memory_management(struct si_context * sctx,unsigned alloc_size,unsigned alignment,enum radeon_bo_domain domain)1080 static void si_test_gds_memory_management(struct si_context *sctx, unsigned alloc_size,
1081                                           unsigned alignment, enum radeon_bo_domain domain)
1082 {
1083    struct radeon_winsys *ws = sctx->ws;
1084    struct radeon_cmdbuf cs[8];
1085    struct pb_buffer_lean *gds_bo[ARRAY_SIZE(cs)];
1086 
1087    for (unsigned i = 0; i < ARRAY_SIZE(cs); i++) {
1088       ws->cs_create(&cs[i], sctx->ctx, AMD_IP_COMPUTE, NULL, NULL);
1089       gds_bo[i] = ws->buffer_create(ws, alloc_size, alignment, domain, 0);
1090       assert(gds_bo[i]);
1091    }
1092 
1093    for (unsigned iterations = 0; iterations < 20000; iterations++) {
1094       for (unsigned i = 0; i < ARRAY_SIZE(cs); i++) {
1095          /* This clears GDS with CP DMA.
1096           *
1097           * We don't care if GDS is present. Just add some packet
1098           * to make the GPU busy for a moment.
1099           */
1100          si_cp_dma_clear_buffer(
1101             sctx, &cs[i], NULL, 0, alloc_size, 0,
1102             SI_OP_CPDMA_SKIP_CHECK_CS_SPACE, 0,
1103             0);
1104 
1105          ws->cs_add_buffer(&cs[i], gds_bo[i], RADEON_USAGE_READWRITE, domain);
1106          ws->cs_flush(&cs[i], PIPE_FLUSH_ASYNC, NULL);
1107       }
1108    }
1109    exit(0);
1110 }
1111 
si_disk_cache_create(struct si_screen * sscreen)1112 static void si_disk_cache_create(struct si_screen *sscreen)
1113 {
1114    /* Don't use the cache if shader dumping is enabled. */
1115    if (sscreen->debug_flags & DBG_ALL_SHADERS)
1116       return;
1117 
1118    struct mesa_sha1 ctx;
1119    unsigned char sha1[20];
1120    char cache_id[20 * 2 + 1];
1121 
1122    _mesa_sha1_init(&ctx);
1123 
1124    if (!disk_cache_get_function_identifier(si_disk_cache_create, &ctx))
1125       return;
1126 
1127    /* ACO and LLVM shader binary have different cache id distinguished by if adding
1128     * the LLVM function identifier. ACO is a built-in component in mesa, so no need
1129     * to add aco function here.
1130     */
1131 #if LLVM_AVAILABLE
1132    if (!sscreen->use_aco &&
1133        !disk_cache_get_function_identifier(LLVMInitializeAMDGPUTargetInfo, &ctx))
1134       return;
1135 #endif
1136 
1137    _mesa_sha1_final(&ctx, sha1);
1138    mesa_bytes_to_hex(cache_id, sha1, 20);
1139 
1140    sscreen->disk_shader_cache = disk_cache_create(sscreen->info.name, cache_id,
1141                                                   sscreen->info.address32_hi);
1142 }
1143 
si_set_max_shader_compiler_threads(struct pipe_screen * screen,unsigned max_threads)1144 static void si_set_max_shader_compiler_threads(struct pipe_screen *screen, unsigned max_threads)
1145 {
1146    struct si_screen *sscreen = (struct si_screen *)screen;
1147 
1148    /* This function doesn't allow a greater number of threads than
1149     * the queue had at its creation. */
1150    util_queue_adjust_num_threads(&sscreen->shader_compiler_queue, max_threads, false);
1151    /* Don't change the number of threads on the low priority queue. */
1152 }
1153 
si_is_parallel_shader_compilation_finished(struct pipe_screen * screen,void * shader,enum pipe_shader_type shader_type)1154 static bool si_is_parallel_shader_compilation_finished(struct pipe_screen *screen, void *shader,
1155                                                        enum pipe_shader_type shader_type)
1156 {
1157    struct si_shader_selector *sel = (struct si_shader_selector *)shader;
1158 
1159    return util_queue_fence_is_signalled(&sel->ready);
1160 }
1161 
radeonsi_screen_create_impl(struct radeon_winsys * ws,const struct pipe_screen_config * config)1162 static struct pipe_screen *radeonsi_screen_create_impl(struct radeon_winsys *ws,
1163                                                        const struct pipe_screen_config *config)
1164 {
1165    struct si_screen *sscreen = CALLOC_STRUCT(si_screen);
1166    unsigned hw_threads, num_comp_hi_threads, num_comp_lo_threads;
1167    uint64_t test_flags;
1168 
1169    if (!sscreen) {
1170       return NULL;
1171    }
1172 
1173    {
1174 #define OPT_BOOL(name, dflt, description)                                                          \
1175    sscreen->options.name = driQueryOptionb(config->options, "radeonsi_" #name);
1176 #define OPT_INT(name, dflt, description)                                                           \
1177    sscreen->options.name = driQueryOptioni(config->options, "radeonsi_" #name);
1178 #include "si_debug_options.h"
1179    }
1180 
1181    sscreen->ws = ws;
1182    ws->query_info(ws, &sscreen->info);
1183 
1184    if (sscreen->info.gfx_level >= GFX9) {
1185       sscreen->se_tile_repeat = 32 * sscreen->info.max_se;
1186    } else {
1187       ac_get_raster_config(&sscreen->info, &sscreen->pa_sc_raster_config,
1188                            &sscreen->pa_sc_raster_config_1, &sscreen->se_tile_repeat);
1189    }
1190 
1191    sscreen->context_roll_log_filename = debug_get_option("AMD_ROLLS", NULL);
1192    sscreen->debug_flags = debug_get_flags_option("R600_DEBUG", radeonsi_debug_options, 0);
1193    sscreen->debug_flags |= debug_get_flags_option("AMD_DEBUG", radeonsi_debug_options, 0);
1194    test_flags = debug_get_flags_option("AMD_TEST", test_options, 0);
1195 
1196    if (sscreen->debug_flags & DBG(NO_DISPLAY_DCC)) {
1197       sscreen->info.use_display_dcc_unaligned = false;
1198       sscreen->info.use_display_dcc_with_retile_blit = false;
1199    }
1200 
1201    /* Using the environment variable doesn't enable PAIRS packets for simplicity. */
1202    if (sscreen->debug_flags & DBG(SHADOW_REGS))
1203       sscreen->info.register_shadowing_required = true;
1204 
1205 #if LLVM_AVAILABLE
1206    sscreen->use_aco = (sscreen->debug_flags & DBG(USE_ACO));
1207 #else
1208    sscreen->use_aco = true;
1209 #endif
1210 
1211    if (sscreen->use_aco && !aco_is_gpu_supported(&sscreen->info)) {
1212       fprintf(stderr, "radeonsi: ACO does not support this chip yet\n");
1213       FREE(sscreen->nir_options);
1214       FREE(sscreen);
1215       return NULL;
1216    }
1217 
1218    if ((sscreen->debug_flags & DBG(TMZ)) &&
1219        !sscreen->info.has_tmz_support) {
1220       fprintf(stderr, "radeonsi: requesting TMZ features but TMZ is not supported\n");
1221       FREE(sscreen->nir_options);
1222       FREE(sscreen);
1223       return NULL;
1224    }
1225 
1226    if (!sscreen->use_aco) {
1227       /* Initialize just one compiler instance to check for errors. The other compiler instances
1228        * are initialized on demand.
1229        */
1230       sscreen->compiler[0] = si_create_llvm_compiler(sscreen);
1231       if (!sscreen->compiler[0]) {
1232          /* The callee prints the error message. */
1233          FREE(sscreen->nir_options);
1234          FREE(sscreen);
1235          return NULL;
1236       }
1237    }
1238 
1239    util_idalloc_mt_init_tc(&sscreen->buffer_ids);
1240 
1241    /* Set functions first. */
1242    sscreen->b.context_create = si_pipe_create_context;
1243    sscreen->b.destroy = si_destroy_screen;
1244    sscreen->b.set_max_shader_compiler_threads = si_set_max_shader_compiler_threads;
1245    sscreen->b.is_parallel_shader_compilation_finished = si_is_parallel_shader_compilation_finished;
1246    sscreen->b.finalize_nir = si_finalize_nir;
1247 
1248    sscreen->nir_options = CALLOC_STRUCT(nir_shader_compiler_options);
1249 
1250    si_init_screen_get_functions(sscreen);
1251    si_init_screen_buffer_functions(sscreen);
1252    si_init_screen_fence_functions(sscreen);
1253    si_init_screen_state_functions(sscreen);
1254    si_init_screen_texture_functions(sscreen);
1255    si_init_screen_query_functions(sscreen);
1256    si_init_screen_live_shader_cache(sscreen);
1257 
1258    sscreen->max_texel_buffer_elements = sscreen->b.get_param(
1259       &sscreen->b, PIPE_CAP_MAX_TEXEL_BUFFER_ELEMENTS_UINT);
1260 
1261    if (sscreen->debug_flags & DBG(INFO))
1262       ac_print_gpu_info(&sscreen->info, stdout);
1263 
1264    slab_create_parent(&sscreen->pool_transfers, sizeof(struct si_transfer), 64);
1265 
1266    sscreen->force_aniso = MIN2(16, debug_get_num_option("R600_TEX_ANISO", -1));
1267    if (sscreen->force_aniso == -1) {
1268       sscreen->force_aniso = MIN2(16, debug_get_num_option("AMD_TEX_ANISO", -1));
1269    }
1270 
1271    if (sscreen->force_aniso >= 0) {
1272       printf("radeonsi: Forcing anisotropy filter to %ix\n",
1273              /* round down to a power of two */
1274              1 << util_logbase2(sscreen->force_aniso));
1275    }
1276 
1277    (void)simple_mtx_init(&sscreen->async_compute_context_lock, mtx_plain);
1278    (void)simple_mtx_init(&sscreen->gpu_load_mutex, mtx_plain);
1279    (void)simple_mtx_init(&sscreen->gds_mutex, mtx_plain);
1280 
1281    si_init_gs_info(sscreen);
1282    if (!si_init_shader_cache(sscreen)) {
1283       FREE(sscreen->nir_options);
1284       FREE(sscreen);
1285       return NULL;
1286    }
1287 
1288    if (sscreen->info.gfx_level < GFX10_3)
1289       sscreen->options.vrs2x2 = false;
1290 
1291    si_disk_cache_create(sscreen);
1292 
1293    /* Determine the number of shader compiler threads. */
1294    const struct util_cpu_caps_t *caps = util_get_cpu_caps();
1295    hw_threads = caps->nr_cpus;
1296 
1297    if (hw_threads >= 12) {
1298       num_comp_hi_threads = hw_threads * 3 / 4;
1299       num_comp_lo_threads = hw_threads / 3;
1300    } else if (hw_threads >= 6) {
1301       num_comp_hi_threads = hw_threads - 2;
1302       num_comp_lo_threads = hw_threads / 2;
1303    } else if (hw_threads >= 2) {
1304       num_comp_hi_threads = hw_threads - 1;
1305       num_comp_lo_threads = hw_threads / 2;
1306    } else {
1307       num_comp_hi_threads = 1;
1308       num_comp_lo_threads = 1;
1309    }
1310 
1311 #ifndef NDEBUG
1312    nir_process_debug_variable();
1313 
1314    /* Use a single compilation thread if NIR printing is enabled to avoid
1315     * multiple shaders being printed at the same time.
1316     */
1317    if (NIR_DEBUG(PRINT)) {
1318       num_comp_hi_threads = 1;
1319       num_comp_lo_threads = 1;
1320    }
1321 #endif
1322 
1323    num_comp_hi_threads = MIN2(num_comp_hi_threads, ARRAY_SIZE(sscreen->compiler));
1324    num_comp_lo_threads = MIN2(num_comp_lo_threads, ARRAY_SIZE(sscreen->compiler_lowp));
1325 
1326    /* Take a reference on the glsl types for the compiler threads. */
1327    glsl_type_singleton_init_or_ref();
1328 
1329    /* Start with a single thread and a single slot.
1330     * Each time we'll hit the "all slots are in use" case, the number of threads and
1331     * slots will be increased.
1332     */
1333    int num_slots = num_comp_hi_threads == 1 ? 64 : 1;
1334    if (!util_queue_init(&sscreen->shader_compiler_queue, "sh", num_slots,
1335                         num_comp_hi_threads,
1336                         UTIL_QUEUE_INIT_RESIZE_IF_FULL |
1337                         UTIL_QUEUE_INIT_SET_FULL_THREAD_AFFINITY, NULL)) {
1338       si_destroy_shader_cache(sscreen);
1339       FREE(sscreen->nir_options);
1340       FREE(sscreen);
1341       glsl_type_singleton_decref();
1342       return NULL;
1343    }
1344 
1345    if (!util_queue_init(&sscreen->shader_compiler_queue_opt_variants, "sh_opt", num_slots,
1346                         num_comp_lo_threads,
1347                         UTIL_QUEUE_INIT_RESIZE_IF_FULL |
1348                         UTIL_QUEUE_INIT_SET_FULL_THREAD_AFFINITY, NULL)) {
1349       si_destroy_shader_cache(sscreen);
1350       FREE(sscreen->nir_options);
1351       FREE(sscreen);
1352       glsl_type_singleton_decref();
1353       return NULL;
1354    }
1355 
1356    if (!debug_get_bool_option("RADEON_DISABLE_PERFCOUNTERS", false))
1357       si_init_perfcounters(sscreen);
1358 
1359    ac_get_hs_info(&sscreen->info, &sscreen->hs);
1360 
1361    sscreen->has_draw_indirect_multi =
1362       (sscreen->info.family >= CHIP_POLARIS10) ||
1363       (sscreen->info.gfx_level == GFX8 && sscreen->info.pfp_fw_version >= 121 &&
1364        sscreen->info.me_fw_version >= 87) ||
1365       (sscreen->info.gfx_level == GFX7 && sscreen->info.pfp_fw_version >= 211 &&
1366        sscreen->info.me_fw_version >= 173) ||
1367       (sscreen->info.gfx_level == GFX6 && sscreen->info.pfp_fw_version >= 79 &&
1368        sscreen->info.me_fw_version >= 142);
1369 
1370    if (sscreen->debug_flags & DBG(NO_OUT_OF_ORDER))
1371       sscreen->info.has_out_of_order_rast = false;
1372 
1373    if (sscreen->info.gfx_level >= GFX11) {
1374       sscreen->use_ngg = true;
1375       sscreen->use_ngg_culling = sscreen->info.max_render_backends >= 2 &&
1376                                  !(sscreen->debug_flags & DBG(NO_NGG_CULLING));
1377    } else {
1378       sscreen->use_ngg = !(sscreen->debug_flags & DBG(NO_NGG)) &&
1379                          sscreen->info.gfx_level >= GFX10 &&
1380                          (sscreen->info.family != CHIP_NAVI14 ||
1381                           sscreen->info.is_pro_graphics);
1382       sscreen->use_ngg_culling = sscreen->use_ngg &&
1383                                  sscreen->info.max_render_backends >= 2 &&
1384                                  !(sscreen->debug_flags & DBG(NO_NGG_CULLING));
1385    }
1386 
1387    /* Only set this for the cases that are known to work, which are:
1388     * - GFX9 if bpp >= 4 (in bytes)
1389     */
1390    if (sscreen->info.gfx_level >= GFX10) {
1391       memset(sscreen->allow_dcc_msaa_clear_to_reg_for_bpp, true,
1392              sizeof(sscreen->allow_dcc_msaa_clear_to_reg_for_bpp));
1393    } else if (sscreen->info.gfx_level == GFX9) {
1394       for (unsigned bpp_log2 = util_logbase2(1); bpp_log2 <= util_logbase2(16); bpp_log2++)
1395          sscreen->allow_dcc_msaa_clear_to_reg_for_bpp[bpp_log2] = true;
1396    }
1397 
1398    /* DCC stores have 50% performance of uncompressed stores and sometimes
1399     * even less than that. It's risky to enable on dGPUs.
1400     */
1401    sscreen->always_allow_dcc_stores = !(sscreen->debug_flags & DBG(NO_DCC_STORE)) &&
1402                                       (sscreen->debug_flags & DBG(DCC_STORE) ||
1403                                        sscreen->info.gfx_level >= GFX11 || /* always enabled on gfx11 */
1404                                        (sscreen->info.gfx_level >= GFX10_3 &&
1405                                         !sscreen->info.has_dedicated_vram));
1406 
1407    sscreen->dpbb_allowed = !(sscreen->debug_flags & DBG(NO_DPBB)) &&
1408                            (sscreen->info.gfx_level >= GFX10 ||
1409                             /* Only enable primitive binning on gfx9 APUs by default. */
1410                             (sscreen->info.gfx_level == GFX9 && !sscreen->info.has_dedicated_vram) ||
1411                             sscreen->debug_flags & DBG(DPBB));
1412 
1413    if (sscreen->dpbb_allowed) {
1414       if ((sscreen->info.has_dedicated_vram && sscreen->info.max_render_backends > 4) ||
1415 	  sscreen->info.gfx_level >= GFX10) {
1416 	 /* Only bin draws that have no CONTEXT and SH register changes between
1417 	  * them because higher settings cause hangs. We've only been able to
1418 	  * reproduce hangs on smaller chips (e.g. Navi24, GFX1103), though all
1419 	  * chips might have them. What we see may be due to a driver bug.
1420 	  */
1421          sscreen->pbb_context_states_per_bin = 1;
1422          sscreen->pbb_persistent_states_per_bin = 1;
1423       } else {
1424          /* This is a workaround for:
1425           *    https://bugs.freedesktop.org/show_bug.cgi?id=110214
1426           * (an alternative is to insert manual BATCH_BREAK event when
1427           *  a context_roll is detected). */
1428          sscreen->pbb_context_states_per_bin = sscreen->info.has_gfx9_scissor_bug ? 1 : 3;
1429          sscreen->pbb_persistent_states_per_bin = 8;
1430       }
1431 
1432       if (!sscreen->info.has_gfx9_scissor_bug)
1433          sscreen->pbb_context_states_per_bin =
1434             debug_get_num_option("AMD_DEBUG_DPBB_CS", sscreen->pbb_context_states_per_bin);
1435       sscreen->pbb_persistent_states_per_bin =
1436          debug_get_num_option("AMD_DEBUG_DPBB_PS", sscreen->pbb_persistent_states_per_bin);
1437 
1438       assert(sscreen->pbb_context_states_per_bin >= 1 &&
1439              sscreen->pbb_context_states_per_bin <= 6);
1440       assert(sscreen->pbb_persistent_states_per_bin >= 1 &&
1441              sscreen->pbb_persistent_states_per_bin <= 32);
1442    }
1443 
1444    (void)simple_mtx_init(&sscreen->shader_parts_mutex, mtx_plain);
1445    sscreen->use_monolithic_shaders = (sscreen->debug_flags & DBG(MONOLITHIC_SHADERS)) != 0;
1446 
1447    sscreen->barrier_flags.cp_to_L2 = SI_CONTEXT_INV_SCACHE | SI_CONTEXT_INV_VCACHE;
1448    if (sscreen->info.gfx_level <= GFX8) {
1449       sscreen->barrier_flags.cp_to_L2 |= SI_CONTEXT_INV_L2;
1450       sscreen->barrier_flags.L2_to_cp |= SI_CONTEXT_WB_L2;
1451    }
1452 
1453    if (debug_get_bool_option("RADEON_DUMP_SHADERS", false))
1454       sscreen->debug_flags |= DBG_ALL_SHADERS;
1455 
1456    /* Syntax:
1457     *     EQAA=s,z,c
1458     * Example:
1459     *     EQAA=8,4,2
1460 
1461     * That means 8 coverage samples, 4 Z/S samples, and 2 color samples.
1462     * Constraints:
1463     *     s >= z >= c (ignoring this only wastes memory)
1464     *     s = [2..16]
1465     *     z = [2..8]
1466     *     c = [2..8]
1467     *
1468     * Only MSAA color and depth buffers are overridden.
1469     */
1470    if (sscreen->info.has_eqaa_surface_allocator) {
1471       const char *eqaa = debug_get_option("EQAA", NULL);
1472       unsigned s, z, f;
1473 
1474       if (eqaa && sscanf(eqaa, "%u,%u,%u", &s, &z, &f) == 3 && s && z && f) {
1475          sscreen->eqaa_force_coverage_samples = s;
1476          sscreen->eqaa_force_z_samples = z;
1477          sscreen->eqaa_force_color_samples = f;
1478       }
1479    }
1480 
1481    if (sscreen->info.gfx_level >= GFX11) {
1482       unsigned attr_ring_size = sscreen->info.attribute_ring_size_per_se * sscreen->info.max_se;
1483       sscreen->attribute_ring = si_aligned_buffer_create(&sscreen->b,
1484                                                          PIPE_RESOURCE_FLAG_UNMAPPABLE |
1485                                                          SI_RESOURCE_FLAG_32BIT |
1486                                                          SI_RESOURCE_FLAG_DRIVER_INTERNAL |
1487                                                          SI_RESOURCE_FLAG_DISCARDABLE,
1488                                                          PIPE_USAGE_DEFAULT,
1489                                                          attr_ring_size, 2 * 1024 * 1024);
1490    }
1491 
1492    /* Create the auxiliary context. This must be done last. */
1493    for (unsigned i = 0; i < ARRAY_SIZE(sscreen->aux_contexts); i++) {
1494       (void)mtx_init(&sscreen->aux_contexts[i].lock, mtx_plain | mtx_recursive);
1495 
1496       bool compute = !sscreen->info.has_graphics ||
1497                      &sscreen->aux_contexts[i] == &sscreen->aux_context.shader_upload;
1498       sscreen->aux_contexts[i].ctx =
1499          si_create_context(&sscreen->b,
1500                            SI_CONTEXT_FLAG_AUX | PIPE_CONTEXT_LOSE_CONTEXT_ON_RESET |
1501                            (sscreen->options.aux_debug ? PIPE_CONTEXT_DEBUG : 0) |
1502                            (compute ? PIPE_CONTEXT_COMPUTE_ONLY : 0));
1503 
1504       if (sscreen->options.aux_debug) {
1505          struct u_log_context *log = CALLOC_STRUCT(u_log_context);
1506          u_log_context_init(log);
1507 
1508          struct si_context *sctx = si_get_aux_context(&sscreen->aux_context.general);
1509          sctx->b.set_log_context(&sctx->b, log);
1510          si_put_aux_context_flush(&sscreen->aux_context.general);
1511       }
1512    }
1513 
1514    if (test_flags & DBG(TEST_IMAGE_COPY))
1515       si_test_image_copy_region(sscreen);
1516 
1517    if (test_flags & (DBG(TEST_CB_RESOLVE) | DBG(TEST_COMPUTE_BLIT)))
1518       si_test_blit(sscreen, test_flags);
1519 
1520    if (test_flags & DBG(TEST_DMA_PERF)) {
1521       si_test_dma_perf(sscreen);
1522    }
1523 
1524    if (test_flags & (DBG(TEST_VMFAULT_CP) | DBG(TEST_VMFAULT_SHADER)))
1525       si_test_vmfault(sscreen, test_flags);
1526 
1527    if (test_flags & DBG(TEST_GDS))
1528       si_test_gds((struct si_context *)sscreen->aux_context.general.ctx);
1529 
1530    if (test_flags & DBG(TEST_GDS_MM)) {
1531       si_test_gds_memory_management((struct si_context *)sscreen->aux_context.general.ctx,
1532                                     32 * 1024, 4, RADEON_DOMAIN_GDS);
1533    }
1534    if (test_flags & DBG(TEST_GDS_OA_MM)) {
1535       si_test_gds_memory_management((struct si_context *)sscreen->aux_context.general.ctx,
1536                                     4, 1, RADEON_DOMAIN_OA);
1537    }
1538 
1539    ac_print_nonshadowed_regs(sscreen->info.gfx_level, sscreen->info.family);
1540 
1541    return &sscreen->b;
1542 }
1543 
radeonsi_screen_create(int fd,const struct pipe_screen_config * config)1544 struct pipe_screen *radeonsi_screen_create(int fd, const struct pipe_screen_config *config)
1545 {
1546    struct radeon_winsys *rw = NULL;
1547    drmVersionPtr version;
1548 
1549    version = drmGetVersion(fd);
1550    if (!version)
1551      return NULL;
1552 
1553 #if LLVM_AVAILABLE
1554    /* LLVM must be initialized before util_queue because both u_queue and LLVM call atexit,
1555     * and LLVM must call it first because its atexit handler executes C++ destructors,
1556     * which must be done after our compiler threads using LLVM in u_queue are finished
1557     * by their atexit handler. Since atexit handlers are called in the reverse order,
1558     * LLVM must be initialized first, followed by u_queue.
1559     */
1560    ac_init_llvm_once();
1561 #endif
1562 
1563    driParseConfigFiles(config->options, config->options_info, 0, "radeonsi",
1564                        NULL, NULL, NULL, 0, NULL, 0);
1565 
1566    switch (version->version_major) {
1567    case 2:
1568       rw = radeon_drm_winsys_create(fd, config, radeonsi_screen_create_impl);
1569       break;
1570    case 3:
1571       rw = amdgpu_winsys_create(fd, config, radeonsi_screen_create_impl);
1572       break;
1573    }
1574 
1575    si_driver_ds_init();
1576 
1577    drmFreeVersion(version);
1578    return rw ? rw->screen : NULL;
1579 }
1580 
si_get_aux_context(struct si_aux_context * ctx)1581 struct si_context *si_get_aux_context(struct si_aux_context *ctx)
1582 {
1583    mtx_lock(&ctx->lock);
1584    return (struct si_context*)ctx->ctx;
1585 }
1586 
si_put_aux_context_flush(struct si_aux_context * ctx)1587 void si_put_aux_context_flush(struct si_aux_context *ctx)
1588 {
1589    ctx->ctx->flush(ctx->ctx, NULL, 0);
1590    mtx_unlock(&ctx->lock);
1591 }
1592