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