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