• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2013 Advanced Micro Devices, Inc.
3  * All Rights Reserved.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * on the rights to use, copy, modify, merge, publish, distribute, sub
9  * license, and/or sell copies of the Software, and to permit persons to whom
10  * the Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice (including the next
13  * paragraph) shall be included in all copies or substantial portions of the
14  * Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHOR(S) AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM,
20  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
21  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
22  * USE OR OTHER DEALINGS IN THE SOFTWARE.
23  *
24  */
25 
26 #include "si_compute.h"
27 
28 #include "ac_rtld.h"
29 #include "amd_kernel_code_t.h"
30 #include "nir/tgsi_to_nir.h"
31 #include "si_build_pm4.h"
32 #include "util/u_async_debug.h"
33 #include "util/u_memory.h"
34 #include "util/u_upload_mgr.h"
35 
36 #define COMPUTE_DBG(sscreen, fmt, args...)                                                         \
37    do {                                                                                            \
38       if ((sscreen->debug_flags & DBG(COMPUTE)))                                                   \
39          fprintf(stderr, fmt, ##args);                                                             \
40    } while (0);
41 
42 struct dispatch_packet {
43    uint16_t header;
44    uint16_t setup;
45    uint16_t workgroup_size_x;
46    uint16_t workgroup_size_y;
47    uint16_t workgroup_size_z;
48    uint16_t reserved0;
49    uint32_t grid_size_x;
50    uint32_t grid_size_y;
51    uint32_t grid_size_z;
52    uint32_t private_segment_size;
53    uint32_t group_segment_size;
54    uint64_t kernel_object;
55    uint64_t kernarg_address;
56    uint64_t reserved2;
57 };
58 
si_compute_get_code_object(const struct si_compute * program,uint64_t symbol_offset)59 static const amd_kernel_code_t *si_compute_get_code_object(const struct si_compute *program,
60                                                            uint64_t symbol_offset)
61 {
62    const struct si_shader_selector *sel = &program->sel;
63 
64    if (program->ir_type != PIPE_SHADER_IR_NATIVE)
65       return NULL;
66 
67    struct ac_rtld_binary rtld;
68    if (!ac_rtld_open(&rtld,
69                      (struct ac_rtld_open_info){.info = &sel->screen->info,
70                                                 .shader_type = MESA_SHADER_COMPUTE,
71                                                 .wave_size = sel->screen->compute_wave_size,
72                                                 .num_parts = 1,
73                                                 .elf_ptrs = &program->shader.binary.elf_buffer,
74                                                 .elf_sizes = &program->shader.binary.elf_size}))
75       return NULL;
76 
77    const amd_kernel_code_t *result = NULL;
78    const char *text;
79    size_t size;
80    if (!ac_rtld_get_section_by_name(&rtld, ".text", &text, &size))
81       goto out;
82 
83    if (symbol_offset + sizeof(amd_kernel_code_t) > size)
84       goto out;
85 
86    result = (const amd_kernel_code_t *)(text + symbol_offset);
87 
88 out:
89    ac_rtld_close(&rtld);
90    return result;
91 }
92 
code_object_to_config(const amd_kernel_code_t * code_object,struct ac_shader_config * out_config)93 static void code_object_to_config(const amd_kernel_code_t *code_object,
94                                   struct ac_shader_config *out_config)
95 {
96 
97    uint32_t rsrc1 = code_object->compute_pgm_resource_registers;
98    uint32_t rsrc2 = code_object->compute_pgm_resource_registers >> 32;
99    out_config->num_sgprs = code_object->wavefront_sgpr_count;
100    out_config->num_vgprs = code_object->workitem_vgpr_count;
101    out_config->float_mode = G_00B028_FLOAT_MODE(rsrc1);
102    out_config->rsrc1 = rsrc1;
103    out_config->lds_size = MAX2(out_config->lds_size, G_00B84C_LDS_SIZE(rsrc2));
104    out_config->rsrc2 = rsrc2;
105    out_config->scratch_bytes_per_wave =
106       align(code_object->workitem_private_segment_byte_size * 64, 1024);
107 }
108 
109 /* Asynchronous compute shader compilation. */
si_create_compute_state_async(void * job,int thread_index)110 static void si_create_compute_state_async(void *job, int thread_index)
111 {
112    struct si_compute *program = (struct si_compute *)job;
113    struct si_shader_selector *sel = &program->sel;
114    struct si_shader *shader = &program->shader;
115    struct ac_llvm_compiler *compiler;
116    struct pipe_debug_callback *debug = &sel->compiler_ctx_state.debug;
117    struct si_screen *sscreen = sel->screen;
118 
119    assert(!debug->debug_message || debug->async);
120    assert(thread_index >= 0);
121    assert(thread_index < ARRAY_SIZE(sscreen->compiler));
122    compiler = &sscreen->compiler[thread_index];
123 
124    if (!compiler->passes)
125       si_init_compiler(sscreen, compiler);
126 
127    assert(program->ir_type == PIPE_SHADER_IR_NIR);
128    si_nir_scan_shader(sel->nir, &sel->info);
129 
130    si_get_active_slot_masks(&sel->info, &sel->active_const_and_shader_buffers,
131                             &sel->active_samplers_and_images);
132 
133    program->shader.is_monolithic = true;
134 
135    unsigned user_sgprs = SI_NUM_RESOURCE_SGPRS + (sel->info.uses_grid_size ? 3 : 0) +
136                          (sel->info.uses_variable_block_size ? 3 : 0) +
137                          sel->info.base.cs.user_data_components_amd;
138 
139    /* Fast path for compute shaders - some descriptors passed via user SGPRs. */
140    /* Shader buffers in user SGPRs. */
141    for (unsigned i = 0; i < MIN2(3, sel->info.base.num_ssbos) && user_sgprs <= 12; i++) {
142       user_sgprs = align(user_sgprs, 4);
143       if (i == 0)
144          sel->cs_shaderbufs_sgpr_index = user_sgprs;
145       user_sgprs += 4;
146       sel->cs_num_shaderbufs_in_user_sgprs++;
147    }
148 
149    /* Images in user SGPRs. */
150    unsigned non_msaa_images = u_bit_consecutive(0, sel->info.base.num_images) &
151                               ~sel->info.base.msaa_images;
152 
153    for (unsigned i = 0; i < 3 && non_msaa_images & (1 << i); i++) {
154       unsigned num_sgprs = sel->info.base.image_buffers & (1 << i) ? 4 : 8;
155 
156       if (align(user_sgprs, num_sgprs) + num_sgprs > 16)
157          break;
158 
159       user_sgprs = align(user_sgprs, num_sgprs);
160       if (i == 0)
161          sel->cs_images_sgpr_index = user_sgprs;
162       user_sgprs += num_sgprs;
163       sel->cs_num_images_in_user_sgprs++;
164    }
165    sel->cs_images_num_sgprs = user_sgprs - sel->cs_images_sgpr_index;
166    assert(user_sgprs <= 16);
167 
168    unsigned char ir_sha1_cache_key[20];
169    si_get_ir_cache_key(sel, false, false, ir_sha1_cache_key);
170 
171    /* Try to load the shader from the shader cache. */
172    simple_mtx_lock(&sscreen->shader_cache_mutex);
173 
174    if (si_shader_cache_load_shader(sscreen, ir_sha1_cache_key, shader)) {
175       simple_mtx_unlock(&sscreen->shader_cache_mutex);
176 
177       si_shader_dump_stats_for_shader_db(sscreen, shader, debug);
178       si_shader_dump(sscreen, shader, debug, stderr, true);
179 
180       if (!si_shader_binary_upload(sscreen, shader, 0))
181          program->shader.compilation_failed = true;
182    } else {
183       simple_mtx_unlock(&sscreen->shader_cache_mutex);
184 
185       if (!si_create_shader_variant(sscreen, compiler, &program->shader, debug)) {
186          program->shader.compilation_failed = true;
187          return;
188       }
189 
190       bool scratch_enabled = shader->config.scratch_bytes_per_wave > 0;
191 
192       shader->config.rsrc1 = S_00B848_VGPRS((shader->config.num_vgprs - 1) /
193                                             (sscreen->compute_wave_size == 32 ? 8 : 4)) |
194                              S_00B848_DX10_CLAMP(1) |
195                              S_00B848_MEM_ORDERED(sscreen->info.chip_class >= GFX10) |
196                              S_00B848_WGP_MODE(sscreen->info.chip_class >= GFX10) |
197                              S_00B848_FLOAT_MODE(shader->config.float_mode);
198 
199       if (sscreen->info.chip_class < GFX10) {
200          shader->config.rsrc1 |= S_00B848_SGPRS((shader->config.num_sgprs - 1) / 8);
201       }
202 
203       shader->config.rsrc2 = S_00B84C_USER_SGPR(user_sgprs) | S_00B84C_SCRATCH_EN(scratch_enabled) |
204                              S_00B84C_TGID_X_EN(sel->info.uses_block_id[0]) |
205                              S_00B84C_TGID_Y_EN(sel->info.uses_block_id[1]) |
206                              S_00B84C_TGID_Z_EN(sel->info.uses_block_id[2]) |
207                              S_00B84C_TG_SIZE_EN(sel->info.uses_subgroup_info) |
208                              S_00B84C_TIDIG_COMP_CNT(sel->info.uses_thread_id[2]
209                                                         ? 2
210                                                         : sel->info.uses_thread_id[1] ? 1 : 0) |
211                              S_00B84C_LDS_SIZE(shader->config.lds_size);
212 
213       simple_mtx_lock(&sscreen->shader_cache_mutex);
214       si_shader_cache_insert_shader(sscreen, ir_sha1_cache_key, shader, true);
215       simple_mtx_unlock(&sscreen->shader_cache_mutex);
216    }
217 
218    ralloc_free(sel->nir);
219    sel->nir = NULL;
220 }
221 
si_create_compute_state(struct pipe_context * ctx,const struct pipe_compute_state * cso)222 static void *si_create_compute_state(struct pipe_context *ctx, const struct pipe_compute_state *cso)
223 {
224    struct si_context *sctx = (struct si_context *)ctx;
225    struct si_screen *sscreen = (struct si_screen *)ctx->screen;
226    struct si_compute *program = CALLOC_STRUCT(si_compute);
227    struct si_shader_selector *sel = &program->sel;
228 
229    pipe_reference_init(&sel->base.reference, 1);
230    sel->info.stage = MESA_SHADER_COMPUTE;
231    sel->screen = sscreen;
232    sel->const_and_shader_buf_descriptors_index =
233       si_const_and_shader_buffer_descriptors_idx(PIPE_SHADER_COMPUTE);
234    sel->sampler_and_images_descriptors_index =
235       si_sampler_and_image_descriptors_idx(PIPE_SHADER_COMPUTE);
236    sel->info.base.cs.shared_size = cso->req_local_mem;
237    program->shader.selector = &program->sel;
238    program->ir_type = cso->ir_type;
239    program->private_size = cso->req_private_mem;
240    program->input_size = cso->req_input_mem;
241 
242    if (cso->ir_type != PIPE_SHADER_IR_NATIVE) {
243       if (cso->ir_type == PIPE_SHADER_IR_TGSI) {
244          program->ir_type = PIPE_SHADER_IR_NIR;
245          sel->nir = tgsi_to_nir(cso->prog, ctx->screen, true);
246       } else {
247          assert(cso->ir_type == PIPE_SHADER_IR_NIR);
248          sel->nir = (struct nir_shader *)cso->prog;
249       }
250 
251       sel->compiler_ctx_state.debug = sctx->debug;
252       sel->compiler_ctx_state.is_debug_context = sctx->is_debug;
253       p_atomic_inc(&sscreen->num_shaders_created);
254 
255       si_schedule_initial_compile(sctx, MESA_SHADER_COMPUTE, &sel->ready, &sel->compiler_ctx_state,
256                                   program, si_create_compute_state_async);
257    } else {
258       const struct pipe_binary_program_header *header;
259       header = cso->prog;
260 
261       program->shader.binary.elf_size = header->num_bytes;
262       program->shader.binary.elf_buffer = malloc(header->num_bytes);
263       if (!program->shader.binary.elf_buffer) {
264          FREE(program);
265          return NULL;
266       }
267       memcpy((void *)program->shader.binary.elf_buffer, header->blob, header->num_bytes);
268 
269       const amd_kernel_code_t *code_object = si_compute_get_code_object(program, 0);
270       code_object_to_config(code_object, &program->shader.config);
271 
272       si_shader_dump(sctx->screen, &program->shader, &sctx->debug, stderr, true);
273       if (!si_shader_binary_upload(sctx->screen, &program->shader, 0)) {
274          fprintf(stderr, "LLVM failed to upload shader\n");
275          free((void *)program->shader.binary.elf_buffer);
276          FREE(program);
277          return NULL;
278       }
279    }
280 
281    return program;
282 }
283 
si_bind_compute_state(struct pipe_context * ctx,void * state)284 static void si_bind_compute_state(struct pipe_context *ctx, void *state)
285 {
286    struct si_context *sctx = (struct si_context *)ctx;
287    struct si_compute *program = (struct si_compute *)state;
288    struct si_shader_selector *sel = &program->sel;
289 
290    sctx->cs_shader_state.program = program;
291    if (!program)
292       return;
293 
294    /* Wait because we need active slot usage masks. */
295    if (program->ir_type != PIPE_SHADER_IR_NATIVE)
296       util_queue_fence_wait(&sel->ready);
297 
298    si_set_active_descriptors(sctx,
299                              SI_DESCS_FIRST_COMPUTE + SI_SHADER_DESCS_CONST_AND_SHADER_BUFFERS,
300                              sel->active_const_and_shader_buffers);
301    si_set_active_descriptors(sctx, SI_DESCS_FIRST_COMPUTE + SI_SHADER_DESCS_SAMPLERS_AND_IMAGES,
302                              sel->active_samplers_and_images);
303 
304    sctx->compute_shaderbuf_sgprs_dirty = true;
305    sctx->compute_image_sgprs_dirty = true;
306 }
307 
si_set_global_binding(struct pipe_context * ctx,unsigned first,unsigned n,struct pipe_resource ** resources,uint32_t ** handles)308 static void si_set_global_binding(struct pipe_context *ctx, unsigned first, unsigned n,
309                                   struct pipe_resource **resources, uint32_t **handles)
310 {
311    unsigned i;
312    struct si_context *sctx = (struct si_context *)ctx;
313    struct si_compute *program = sctx->cs_shader_state.program;
314 
315    if (first + n > program->max_global_buffers) {
316       unsigned old_max = program->max_global_buffers;
317       program->max_global_buffers = first + n;
318       program->global_buffers = realloc(
319          program->global_buffers, program->max_global_buffers * sizeof(program->global_buffers[0]));
320       if (!program->global_buffers) {
321          fprintf(stderr, "radeonsi: failed to allocate compute global_buffers\n");
322          return;
323       }
324 
325       memset(&program->global_buffers[old_max], 0,
326              (program->max_global_buffers - old_max) * sizeof(program->global_buffers[0]));
327    }
328 
329    if (!resources) {
330       for (i = 0; i < n; i++) {
331          pipe_resource_reference(&program->global_buffers[first + i], NULL);
332       }
333       return;
334    }
335 
336    for (i = 0; i < n; i++) {
337       uint64_t va;
338       uint32_t offset;
339       pipe_resource_reference(&program->global_buffers[first + i], resources[i]);
340       va = si_resource(resources[i])->gpu_address;
341       offset = util_le32_to_cpu(*handles[i]);
342       va += offset;
343       va = util_cpu_to_le64(va);
344       memcpy(handles[i], &va, sizeof(va));
345    }
346 }
347 
si_emit_initial_compute_regs(struct si_context * sctx,struct radeon_cmdbuf * cs)348 void si_emit_initial_compute_regs(struct si_context *sctx, struct radeon_cmdbuf *cs)
349 {
350    uint64_t bc_va = sctx->border_color_buffer->gpu_address;
351 
352    radeon_set_sh_reg_seq(cs, R_00B858_COMPUTE_STATIC_THREAD_MGMT_SE0, 2);
353    /* R_00B858_COMPUTE_STATIC_THREAD_MGMT_SE0 / SE1,
354     * renamed COMPUTE_DESTINATION_EN_SEn on gfx10. */
355    radeon_emit(cs, S_00B858_SH0_CU_EN(0xffff) | S_00B858_SH1_CU_EN(0xffff));
356    radeon_emit(cs, S_00B858_SH0_CU_EN(0xffff) | S_00B858_SH1_CU_EN(0xffff));
357 
358    if (sctx->chip_class == GFX6) {
359       /* This register has been moved to R_00CD20_COMPUTE_MAX_WAVE_ID
360        * and is now per pipe, so it should be handled in the
361        * kernel if we want to use something other than the default value.
362        *
363        * TODO: This should be:
364        * (number of compute units) * 4 * (waves per simd) - 1
365        */
366       radeon_set_sh_reg(cs, R_00B82C_COMPUTE_MAX_WAVE_ID, 0x190 /* Default value */);
367 
368       if (sctx->screen->info.si_TA_CS_BC_BASE_ADDR_allowed)
369          radeon_set_config_reg(cs, R_00950C_TA_CS_BC_BASE_ADDR, bc_va >> 8);
370    }
371 
372    if (sctx->chip_class >= GFX7) {
373       /* Also set R_00B858_COMPUTE_STATIC_THREAD_MGMT_SE2 / SE3 */
374       radeon_set_sh_reg_seq(cs, R_00B864_COMPUTE_STATIC_THREAD_MGMT_SE2, 2);
375       radeon_emit(cs, S_00B858_SH0_CU_EN(0xffff) | S_00B858_SH1_CU_EN(0xffff));
376       radeon_emit(cs, S_00B858_SH0_CU_EN(0xffff) | S_00B858_SH1_CU_EN(0xffff));
377 
378       /* Disable profiling on compute queues. */
379       if (cs != sctx->gfx_cs || !sctx->screen->info.has_graphics) {
380          radeon_set_sh_reg(cs, R_00B82C_COMPUTE_PERFCOUNT_ENABLE, 0);
381          radeon_set_sh_reg(cs, R_00B878_COMPUTE_THREAD_TRACE_ENABLE, 0);
382       }
383 
384       /* Set the pointer to border colors. */
385       radeon_set_uconfig_reg_seq(cs, R_030E00_TA_CS_BC_BASE_ADDR, 2);
386       radeon_emit(cs, bc_va >> 8);                    /* R_030E00_TA_CS_BC_BASE_ADDR */
387       radeon_emit(cs, S_030E04_ADDRESS(bc_va >> 40)); /* R_030E04_TA_CS_BC_BASE_ADDR_HI */
388    }
389 
390    /* cs_preamble_state initializes this for the gfx queue, so only do this
391     * if we are on a compute queue.
392     */
393    if (sctx->chip_class >= GFX9 &&
394        (cs != sctx->gfx_cs || !sctx->screen->info.has_graphics)) {
395       radeon_set_uconfig_reg(cs, R_0301EC_CP_COHER_START_DELAY,
396                              sctx->chip_class >= GFX10 ? 0x20 : 0);
397    }
398 
399    if (sctx->chip_class >= GFX10) {
400       radeon_set_sh_reg(cs, R_00B890_COMPUTE_USER_ACCUM_0, 0);
401       radeon_set_sh_reg(cs, R_00B894_COMPUTE_USER_ACCUM_1, 0);
402       radeon_set_sh_reg(cs, R_00B898_COMPUTE_USER_ACCUM_2, 0);
403       radeon_set_sh_reg(cs, R_00B89C_COMPUTE_USER_ACCUM_3, 0);
404       radeon_set_sh_reg(cs, R_00B8A0_COMPUTE_PGM_RSRC3, 0);
405       radeon_set_sh_reg(cs, R_00B9F4_COMPUTE_DISPATCH_TUNNEL, 0);
406    }
407 }
408 
si_setup_compute_scratch_buffer(struct si_context * sctx,struct si_shader * shader,struct ac_shader_config * config)409 static bool si_setup_compute_scratch_buffer(struct si_context *sctx, struct si_shader *shader,
410                                             struct ac_shader_config *config)
411 {
412    uint64_t scratch_bo_size, scratch_needed;
413    scratch_bo_size = 0;
414    scratch_needed = config->scratch_bytes_per_wave * sctx->scratch_waves;
415    if (sctx->compute_scratch_buffer)
416       scratch_bo_size = sctx->compute_scratch_buffer->b.b.width0;
417 
418    if (scratch_bo_size < scratch_needed) {
419       si_resource_reference(&sctx->compute_scratch_buffer, NULL);
420 
421       sctx->compute_scratch_buffer =
422          si_aligned_buffer_create(&sctx->screen->b,
423                                   SI_RESOURCE_FLAG_UNMAPPABLE | SI_RESOURCE_FLAG_DRIVER_INTERNAL,
424                                   PIPE_USAGE_DEFAULT,
425                                   scratch_needed, sctx->screen->info.pte_fragment_size);
426 
427       if (!sctx->compute_scratch_buffer)
428          return false;
429    }
430 
431    if (sctx->compute_scratch_buffer != shader->scratch_bo && scratch_needed) {
432       uint64_t scratch_va = sctx->compute_scratch_buffer->gpu_address;
433 
434       if (!si_shader_binary_upload(sctx->screen, shader, scratch_va))
435          return false;
436 
437       si_resource_reference(&shader->scratch_bo, sctx->compute_scratch_buffer);
438    }
439 
440    return true;
441 }
442 
si_switch_compute_shader(struct si_context * sctx,struct si_compute * program,struct si_shader * shader,const amd_kernel_code_t * code_object,unsigned offset,bool * prefetch)443 static bool si_switch_compute_shader(struct si_context *sctx, struct si_compute *program,
444                                      struct si_shader *shader, const amd_kernel_code_t *code_object,
445                                      unsigned offset, bool *prefetch)
446 {
447    struct radeon_cmdbuf *cs = sctx->gfx_cs;
448    struct ac_shader_config inline_config = {0};
449    struct ac_shader_config *config;
450    uint64_t shader_va;
451 
452    *prefetch = false;
453 
454    if (sctx->cs_shader_state.emitted_program == program && sctx->cs_shader_state.offset == offset)
455       return true;
456 
457    if (program->ir_type != PIPE_SHADER_IR_NATIVE) {
458       config = &shader->config;
459    } else {
460       unsigned lds_blocks;
461 
462       config = &inline_config;
463       code_object_to_config(code_object, config);
464 
465       lds_blocks = config->lds_size;
466       /* XXX: We are over allocating LDS.  For GFX6, the shader reports
467        * LDS in blocks of 256 bytes, so if there are 4 bytes lds
468        * allocated in the shader and 4 bytes allocated by the state
469        * tracker, then we will set LDS_SIZE to 512 bytes rather than 256.
470        */
471       if (sctx->chip_class <= GFX6) {
472          lds_blocks += align(program->sel.info.base.cs.shared_size, 256) >> 8;
473       } else {
474          lds_blocks += align(program->sel.info.base.cs.shared_size, 512) >> 9;
475       }
476 
477       /* TODO: use si_multiwave_lds_size_workaround */
478       assert(lds_blocks <= 0xFF);
479 
480       config->rsrc2 &= C_00B84C_LDS_SIZE;
481       config->rsrc2 |= S_00B84C_LDS_SIZE(lds_blocks);
482    }
483 
484    if (!si_setup_compute_scratch_buffer(sctx, shader, config))
485       return false;
486 
487    if (shader->scratch_bo) {
488       COMPUTE_DBG(sctx->screen,
489                   "Waves: %u; Scratch per wave: %u bytes; "
490                   "Total Scratch: %u bytes\n",
491                   sctx->scratch_waves, config->scratch_bytes_per_wave,
492                   config->scratch_bytes_per_wave * sctx->scratch_waves);
493 
494       radeon_add_to_buffer_list(sctx, sctx->gfx_cs, shader->scratch_bo, RADEON_USAGE_READWRITE,
495                                 RADEON_PRIO_SCRATCH_BUFFER);
496    }
497 
498    shader_va = shader->bo->gpu_address + offset;
499    if (program->ir_type == PIPE_SHADER_IR_NATIVE) {
500       /* Shader code is placed after the amd_kernel_code_t
501        * struct. */
502       shader_va += sizeof(amd_kernel_code_t);
503    }
504 
505    radeon_add_to_buffer_list(sctx, sctx->gfx_cs, shader->bo, RADEON_USAGE_READ,
506                              RADEON_PRIO_SHADER_BINARY);
507 
508    radeon_set_sh_reg_seq(cs, R_00B830_COMPUTE_PGM_LO, 2);
509    radeon_emit(cs, shader_va >> 8);
510    radeon_emit(cs, S_00B834_DATA(shader_va >> 40));
511 
512    radeon_set_sh_reg_seq(cs, R_00B848_COMPUTE_PGM_RSRC1, 2);
513    radeon_emit(cs, config->rsrc1);
514    radeon_emit(cs, config->rsrc2);
515 
516    COMPUTE_DBG(sctx->screen,
517                "COMPUTE_PGM_RSRC1: 0x%08x "
518                "COMPUTE_PGM_RSRC2: 0x%08x\n",
519                config->rsrc1, config->rsrc2);
520 
521    sctx->max_seen_compute_scratch_bytes_per_wave =
522       MAX2(sctx->max_seen_compute_scratch_bytes_per_wave, config->scratch_bytes_per_wave);
523 
524    radeon_set_sh_reg(cs, R_00B860_COMPUTE_TMPRING_SIZE,
525                      S_00B860_WAVES(sctx->scratch_waves) |
526                         S_00B860_WAVESIZE(sctx->max_seen_compute_scratch_bytes_per_wave >> 10));
527 
528    sctx->cs_shader_state.emitted_program = program;
529    sctx->cs_shader_state.offset = offset;
530    sctx->cs_shader_state.uses_scratch = config->scratch_bytes_per_wave != 0;
531 
532    *prefetch = true;
533    return true;
534 }
535 
setup_scratch_rsrc_user_sgprs(struct si_context * sctx,const amd_kernel_code_t * code_object,unsigned user_sgpr)536 static void setup_scratch_rsrc_user_sgprs(struct si_context *sctx,
537                                           const amd_kernel_code_t *code_object, unsigned user_sgpr)
538 {
539    struct radeon_cmdbuf *cs = sctx->gfx_cs;
540    uint64_t scratch_va = sctx->compute_scratch_buffer->gpu_address;
541 
542    unsigned max_private_element_size =
543       AMD_HSA_BITS_GET(code_object->code_properties, AMD_CODE_PROPERTY_PRIVATE_ELEMENT_SIZE);
544 
545    uint32_t scratch_dword0 = scratch_va & 0xffffffff;
546    uint32_t scratch_dword1 =
547       S_008F04_BASE_ADDRESS_HI(scratch_va >> 32) | S_008F04_SWIZZLE_ENABLE(1);
548 
549    /* Disable address clamping */
550    uint32_t scratch_dword2 = 0xffffffff;
551    uint32_t scratch_dword3 = S_008F0C_INDEX_STRIDE(3) | S_008F0C_ADD_TID_ENABLE(1);
552 
553    if (sctx->chip_class >= GFX9) {
554       assert(max_private_element_size == 1); /* always 4 bytes on GFX9 */
555    } else {
556       scratch_dword3 |= S_008F0C_ELEMENT_SIZE(max_private_element_size);
557 
558       if (sctx->chip_class < GFX8) {
559          /* BUF_DATA_FORMAT is ignored, but it cannot be
560           * BUF_DATA_FORMAT_INVALID. */
561          scratch_dword3 |= S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_8);
562       }
563    }
564 
565    radeon_set_sh_reg_seq(cs, R_00B900_COMPUTE_USER_DATA_0 + (user_sgpr * 4), 4);
566    radeon_emit(cs, scratch_dword0);
567    radeon_emit(cs, scratch_dword1);
568    radeon_emit(cs, scratch_dword2);
569    radeon_emit(cs, scratch_dword3);
570 }
571 
si_setup_user_sgprs_co_v2(struct si_context * sctx,const amd_kernel_code_t * code_object,const struct pipe_grid_info * info,uint64_t kernel_args_va)572 static void si_setup_user_sgprs_co_v2(struct si_context *sctx, const amd_kernel_code_t *code_object,
573                                       const struct pipe_grid_info *info, uint64_t kernel_args_va)
574 {
575    struct si_compute *program = sctx->cs_shader_state.program;
576    struct radeon_cmdbuf *cs = sctx->gfx_cs;
577 
578    static const enum amd_code_property_mask_t workgroup_count_masks[] = {
579       AMD_CODE_PROPERTY_ENABLE_SGPR_GRID_WORKGROUP_COUNT_X,
580       AMD_CODE_PROPERTY_ENABLE_SGPR_GRID_WORKGROUP_COUNT_Y,
581       AMD_CODE_PROPERTY_ENABLE_SGPR_GRID_WORKGROUP_COUNT_Z};
582 
583    unsigned i, user_sgpr = 0;
584    if (AMD_HSA_BITS_GET(code_object->code_properties,
585                         AMD_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER)) {
586       if (code_object->workitem_private_segment_byte_size > 0) {
587          setup_scratch_rsrc_user_sgprs(sctx, code_object, user_sgpr);
588       }
589       user_sgpr += 4;
590    }
591 
592    if (AMD_HSA_BITS_GET(code_object->code_properties, AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR)) {
593       struct dispatch_packet dispatch;
594       unsigned dispatch_offset;
595       struct si_resource *dispatch_buf = NULL;
596       uint64_t dispatch_va;
597 
598       /* Upload dispatch ptr */
599       memset(&dispatch, 0, sizeof(dispatch));
600 
601       dispatch.workgroup_size_x = util_cpu_to_le16(info->block[0]);
602       dispatch.workgroup_size_y = util_cpu_to_le16(info->block[1]);
603       dispatch.workgroup_size_z = util_cpu_to_le16(info->block[2]);
604 
605       dispatch.grid_size_x = util_cpu_to_le32(info->grid[0] * info->block[0]);
606       dispatch.grid_size_y = util_cpu_to_le32(info->grid[1] * info->block[1]);
607       dispatch.grid_size_z = util_cpu_to_le32(info->grid[2] * info->block[2]);
608 
609       dispatch.private_segment_size = util_cpu_to_le32(program->private_size);
610       dispatch.group_segment_size = util_cpu_to_le32(program->sel.info.base.cs.shared_size);
611 
612       dispatch.kernarg_address = util_cpu_to_le64(kernel_args_va);
613 
614       u_upload_data(sctx->b.const_uploader, 0, sizeof(dispatch), 256, &dispatch, &dispatch_offset,
615                     (struct pipe_resource **)&dispatch_buf);
616 
617       if (!dispatch_buf) {
618          fprintf(stderr, "Error: Failed to allocate dispatch "
619                          "packet.");
620       }
621       radeon_add_to_buffer_list(sctx, sctx->gfx_cs, dispatch_buf, RADEON_USAGE_READ,
622                                 RADEON_PRIO_CONST_BUFFER);
623 
624       dispatch_va = dispatch_buf->gpu_address + dispatch_offset;
625 
626       radeon_set_sh_reg_seq(cs, R_00B900_COMPUTE_USER_DATA_0 + (user_sgpr * 4), 2);
627       radeon_emit(cs, dispatch_va);
628       radeon_emit(cs, S_008F04_BASE_ADDRESS_HI(dispatch_va >> 32) | S_008F04_STRIDE(0));
629 
630       si_resource_reference(&dispatch_buf, NULL);
631       user_sgpr += 2;
632    }
633 
634    if (AMD_HSA_BITS_GET(code_object->code_properties,
635                         AMD_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR)) {
636       radeon_set_sh_reg_seq(cs, R_00B900_COMPUTE_USER_DATA_0 + (user_sgpr * 4), 2);
637       radeon_emit(cs, kernel_args_va);
638       radeon_emit(cs, S_008F04_BASE_ADDRESS_HI(kernel_args_va >> 32) | S_008F04_STRIDE(0));
639       user_sgpr += 2;
640    }
641 
642    for (i = 0; i < 3 && user_sgpr < 16; i++) {
643       if (code_object->code_properties & workgroup_count_masks[i]) {
644          radeon_set_sh_reg_seq(cs, R_00B900_COMPUTE_USER_DATA_0 + (user_sgpr * 4), 1);
645          radeon_emit(cs, info->grid[i]);
646          user_sgpr += 1;
647       }
648    }
649 }
650 
si_upload_compute_input(struct si_context * sctx,const amd_kernel_code_t * code_object,const struct pipe_grid_info * info)651 static bool si_upload_compute_input(struct si_context *sctx, const amd_kernel_code_t *code_object,
652                                     const struct pipe_grid_info *info)
653 {
654    struct si_compute *program = sctx->cs_shader_state.program;
655    struct si_resource *input_buffer = NULL;
656    uint32_t kernel_args_offset = 0;
657    uint32_t *kernel_args;
658    void *kernel_args_ptr;
659    uint64_t kernel_args_va;
660 
661    u_upload_alloc(sctx->b.const_uploader, 0, program->input_size,
662                   sctx->screen->info.tcc_cache_line_size, &kernel_args_offset,
663                   (struct pipe_resource **)&input_buffer, &kernel_args_ptr);
664 
665    if (unlikely(!kernel_args_ptr))
666       return false;
667 
668    kernel_args = (uint32_t *)kernel_args_ptr;
669    kernel_args_va = input_buffer->gpu_address + kernel_args_offset;
670 
671    memcpy(kernel_args, info->input, program->input_size);
672 
673    for (unsigned i = 0; i < program->input_size / 4; i++) {
674       COMPUTE_DBG(sctx->screen, "input %u : %u\n", i, kernel_args[i]);
675    }
676 
677    radeon_add_to_buffer_list(sctx, sctx->gfx_cs, input_buffer, RADEON_USAGE_READ,
678                              RADEON_PRIO_CONST_BUFFER);
679 
680    si_setup_user_sgprs_co_v2(sctx, code_object, info, kernel_args_va);
681    si_resource_reference(&input_buffer, NULL);
682    return true;
683 }
684 
si_setup_nir_user_data(struct si_context * sctx,const struct pipe_grid_info * info)685 static void si_setup_nir_user_data(struct si_context *sctx, const struct pipe_grid_info *info)
686 {
687    struct si_compute *program = sctx->cs_shader_state.program;
688    struct si_shader_selector *sel = &program->sel;
689    struct radeon_cmdbuf *cs = sctx->gfx_cs;
690    unsigned grid_size_reg = R_00B900_COMPUTE_USER_DATA_0 + 4 * SI_NUM_RESOURCE_SGPRS;
691    unsigned block_size_reg = grid_size_reg +
692                              /* 12 bytes = 3 dwords. */
693                              12 * sel->info.uses_grid_size;
694    unsigned cs_user_data_reg = block_size_reg + 12 * program->sel.info.uses_variable_block_size;
695 
696    if (sel->info.uses_grid_size) {
697       if (info->indirect) {
698          for (unsigned i = 0; i < 3; ++i) {
699             si_cp_copy_data(sctx, sctx->gfx_cs, COPY_DATA_REG, NULL, (grid_size_reg >> 2) + i,
700                             COPY_DATA_SRC_MEM, si_resource(info->indirect),
701                             info->indirect_offset + 4 * i);
702          }
703       } else {
704          radeon_set_sh_reg_seq(cs, grid_size_reg, 3);
705          radeon_emit(cs, info->grid[0]);
706          radeon_emit(cs, info->grid[1]);
707          radeon_emit(cs, info->grid[2]);
708       }
709    }
710 
711    if (sel->info.uses_variable_block_size) {
712       radeon_set_sh_reg_seq(cs, block_size_reg, 3);
713       radeon_emit(cs, info->block[0]);
714       radeon_emit(cs, info->block[1]);
715       radeon_emit(cs, info->block[2]);
716    }
717 
718    if (sel->info.base.cs.user_data_components_amd) {
719       radeon_set_sh_reg_seq(cs, cs_user_data_reg, sel->info.base.cs.user_data_components_amd);
720       radeon_emit_array(cs, sctx->cs_user_data, sel->info.base.cs.user_data_components_amd);
721    }
722 }
723 
si_emit_dispatch_packets(struct si_context * sctx,const struct pipe_grid_info * info)724 static void si_emit_dispatch_packets(struct si_context *sctx, const struct pipe_grid_info *info)
725 {
726    struct si_screen *sscreen = sctx->screen;
727    struct radeon_cmdbuf *cs = sctx->gfx_cs;
728    bool render_cond_bit = sctx->render_cond && !sctx->render_cond_force_off;
729    unsigned threads_per_threadgroup = info->block[0] * info->block[1] * info->block[2];
730    unsigned waves_per_threadgroup =
731       DIV_ROUND_UP(threads_per_threadgroup, sscreen->compute_wave_size);
732    unsigned threadgroups_per_cu = 1;
733 
734    if (sctx->chip_class >= GFX10 && waves_per_threadgroup == 1)
735       threadgroups_per_cu = 2;
736 
737    radeon_set_sh_reg(
738       cs, R_00B854_COMPUTE_RESOURCE_LIMITS,
739       ac_get_compute_resource_limits(&sscreen->info, waves_per_threadgroup,
740                                      sctx->cs_max_waves_per_sh, threadgroups_per_cu));
741 
742    unsigned dispatch_initiator = S_00B800_COMPUTE_SHADER_EN(1) | S_00B800_FORCE_START_AT_000(1) |
743                                  /* If the KMD allows it (there is a KMD hw register for it),
744                                   * allow launching waves out-of-order. (same as Vulkan) */
745                                  S_00B800_ORDER_MODE(sctx->chip_class >= GFX7) |
746                                  S_00B800_CS_W32_EN(sscreen->compute_wave_size == 32);
747 
748    const uint *last_block = info->last_block;
749    bool partial_block_en = last_block[0] || last_block[1] || last_block[2];
750 
751    radeon_set_sh_reg_seq(cs, R_00B81C_COMPUTE_NUM_THREAD_X, 3);
752 
753    if (partial_block_en) {
754       unsigned partial[3];
755 
756       /* If no partial_block, these should be an entire block size, not 0. */
757       partial[0] = last_block[0] ? last_block[0] : info->block[0];
758       partial[1] = last_block[1] ? last_block[1] : info->block[1];
759       partial[2] = last_block[2] ? last_block[2] : info->block[2];
760 
761       radeon_emit(
762          cs, S_00B81C_NUM_THREAD_FULL(info->block[0]) | S_00B81C_NUM_THREAD_PARTIAL(partial[0]));
763       radeon_emit(
764          cs, S_00B820_NUM_THREAD_FULL(info->block[1]) | S_00B820_NUM_THREAD_PARTIAL(partial[1]));
765       radeon_emit(
766          cs, S_00B824_NUM_THREAD_FULL(info->block[2]) | S_00B824_NUM_THREAD_PARTIAL(partial[2]));
767 
768       dispatch_initiator |= S_00B800_PARTIAL_TG_EN(1);
769    } else {
770       radeon_emit(cs, S_00B81C_NUM_THREAD_FULL(info->block[0]));
771       radeon_emit(cs, S_00B820_NUM_THREAD_FULL(info->block[1]));
772       radeon_emit(cs, S_00B824_NUM_THREAD_FULL(info->block[2]));
773    }
774 
775    if (info->indirect) {
776       uint64_t base_va = si_resource(info->indirect)->gpu_address;
777 
778       radeon_add_to_buffer_list(sctx, sctx->gfx_cs, si_resource(info->indirect), RADEON_USAGE_READ,
779                                 RADEON_PRIO_DRAW_INDIRECT);
780 
781       radeon_emit(cs, PKT3(PKT3_SET_BASE, 2, 0) | PKT3_SHADER_TYPE_S(1));
782       radeon_emit(cs, 1);
783       radeon_emit(cs, base_va);
784       radeon_emit(cs, base_va >> 32);
785 
786       radeon_emit(cs, PKT3(PKT3_DISPATCH_INDIRECT, 1, render_cond_bit) | PKT3_SHADER_TYPE_S(1));
787       radeon_emit(cs, info->indirect_offset);
788       radeon_emit(cs, dispatch_initiator);
789    } else {
790       radeon_emit(cs, PKT3(PKT3_DISPATCH_DIRECT, 3, render_cond_bit) | PKT3_SHADER_TYPE_S(1));
791       radeon_emit(cs, info->grid[0]);
792       radeon_emit(cs, info->grid[1]);
793       radeon_emit(cs, info->grid[2]);
794       radeon_emit(cs, dispatch_initiator);
795    }
796 }
797 
si_launch_grid(struct pipe_context * ctx,const struct pipe_grid_info * info)798 static void si_launch_grid(struct pipe_context *ctx, const struct pipe_grid_info *info)
799 {
800    struct si_context *sctx = (struct si_context *)ctx;
801    struct si_compute *program = sctx->cs_shader_state.program;
802    const amd_kernel_code_t *code_object = si_compute_get_code_object(program, info->pc);
803    int i;
804    /* HW bug workaround when CS threadgroups > 256 threads and async
805     * compute isn't used, i.e. only one compute job can run at a time.
806     * If async compute is possible, the threadgroup size must be limited
807     * to 256 threads on all queues to avoid the bug.
808     * Only GFX6 and certain GFX7 chips are affected.
809     */
810    bool cs_regalloc_hang =
811       (sctx->chip_class == GFX6 || sctx->family == CHIP_BONAIRE || sctx->family == CHIP_KABINI) &&
812       info->block[0] * info->block[1] * info->block[2] > 256;
813 
814    if (cs_regalloc_hang)
815       sctx->flags |= SI_CONTEXT_PS_PARTIAL_FLUSH | SI_CONTEXT_CS_PARTIAL_FLUSH;
816 
817    if (program->ir_type != PIPE_SHADER_IR_NATIVE && program->shader.compilation_failed)
818       return;
819 
820    if (sctx->has_graphics) {
821       if (sctx->last_num_draw_calls != sctx->num_draw_calls) {
822          si_update_fb_dirtiness_after_rendering(sctx);
823          sctx->last_num_draw_calls = sctx->num_draw_calls;
824       }
825 
826       si_decompress_textures(sctx, 1 << PIPE_SHADER_COMPUTE);
827    }
828 
829    /* Add buffer sizes for memory checking in need_cs_space. */
830    si_context_add_resource_size(sctx, &program->shader.bo->b.b);
831    /* TODO: add the scratch buffer */
832 
833    if (info->indirect) {
834       si_context_add_resource_size(sctx, info->indirect);
835 
836       /* Indirect buffers use TC L2 on GFX9, but not older hw. */
837       if (sctx->chip_class <= GFX8 && si_resource(info->indirect)->TC_L2_dirty) {
838          sctx->flags |= SI_CONTEXT_WB_L2;
839          si_resource(info->indirect)->TC_L2_dirty = false;
840       }
841    }
842 
843    si_need_gfx_cs_space(sctx, 0);
844 
845    /* If we're using a secure context, determine if cs must be secure or not */
846    if (unlikely(radeon_uses_secure_bos(sctx->ws))) {
847       bool secure = si_compute_resources_check_encrypted(sctx);
848       if (secure != sctx->ws->cs_is_secure(sctx->gfx_cs)) {
849          si_flush_gfx_cs(sctx, RADEON_FLUSH_ASYNC_START_NEXT_GFX_IB_NOW |
850                                RADEON_FLUSH_TOGGLE_SECURE_SUBMISSION,
851                          NULL);
852       }
853    }
854 
855    if (sctx->bo_list_add_all_compute_resources)
856       si_compute_resources_add_all_to_bo_list(sctx);
857 
858    if (!sctx->cs_shader_state.initialized) {
859       si_emit_initial_compute_regs(sctx, sctx->gfx_cs);
860 
861       sctx->cs_shader_state.emitted_program = NULL;
862       sctx->cs_shader_state.initialized = true;
863    }
864 
865    /* First emit registers. */
866    bool prefetch;
867    if (!si_switch_compute_shader(sctx, program, &program->shader, code_object, info->pc, &prefetch))
868       return;
869 
870    si_upload_compute_shader_descriptors(sctx);
871    si_emit_compute_shader_pointers(sctx);
872 
873    if (program->ir_type == PIPE_SHADER_IR_NATIVE &&
874        unlikely(!si_upload_compute_input(sctx, code_object, info)))
875       return;
876 
877    /* Global buffers */
878    for (i = 0; i < program->max_global_buffers; i++) {
879       struct si_resource *buffer = si_resource(program->global_buffers[i]);
880       if (!buffer) {
881          continue;
882       }
883       radeon_add_to_buffer_list(sctx, sctx->gfx_cs, buffer, RADEON_USAGE_READWRITE,
884                                 RADEON_PRIO_COMPUTE_GLOBAL);
885    }
886 
887    /* Registers that are not read from memory should be set before this: */
888    if (sctx->flags)
889       sctx->emit_cache_flush(sctx);
890 
891    if (sctx->has_graphics && si_is_atom_dirty(sctx, &sctx->atoms.s.render_cond)) {
892       sctx->atoms.s.render_cond.emit(sctx);
893       si_set_atom_dirty(sctx, &sctx->atoms.s.render_cond, false);
894    }
895 
896    /* Prefetch the compute shader to L2. */
897    if (sctx->chip_class >= GFX7 && prefetch)
898       cik_prefetch_TC_L2_async(sctx, &program->shader.bo->b.b, 0, program->shader.bo->b.b.width0);
899 
900    if (program->ir_type != PIPE_SHADER_IR_NATIVE)
901       si_setup_nir_user_data(sctx, info);
902 
903    si_emit_dispatch_packets(sctx, info);
904 
905    if (unlikely(sctx->current_saved_cs)) {
906       si_trace_emit(sctx);
907       si_log_compute_state(sctx, sctx->log);
908    }
909 
910    sctx->compute_is_busy = true;
911    sctx->num_compute_calls++;
912    if (sctx->cs_shader_state.uses_scratch)
913       sctx->num_spill_compute_calls++;
914 
915    if (cs_regalloc_hang)
916       sctx->flags |= SI_CONTEXT_CS_PARTIAL_FLUSH;
917 }
918 
si_destroy_compute(struct si_compute * program)919 void si_destroy_compute(struct si_compute *program)
920 {
921    struct si_shader_selector *sel = &program->sel;
922 
923    if (program->ir_type != PIPE_SHADER_IR_NATIVE) {
924       util_queue_drop_job(&sel->screen->shader_compiler_queue, &sel->ready);
925       util_queue_fence_destroy(&sel->ready);
926    }
927 
928    for (unsigned i = 0; i < program->max_global_buffers; i++)
929       pipe_resource_reference(&program->global_buffers[i], NULL);
930    FREE(program->global_buffers);
931 
932    si_shader_destroy(&program->shader);
933    ralloc_free(program->sel.nir);
934    FREE(program);
935 }
936 
si_delete_compute_state(struct pipe_context * ctx,void * state)937 static void si_delete_compute_state(struct pipe_context *ctx, void *state)
938 {
939    struct si_compute *program = (struct si_compute *)state;
940    struct si_context *sctx = (struct si_context *)ctx;
941 
942    if (!state)
943       return;
944 
945    if (program == sctx->cs_shader_state.program)
946       sctx->cs_shader_state.program = NULL;
947 
948    if (program == sctx->cs_shader_state.emitted_program)
949       sctx->cs_shader_state.emitted_program = NULL;
950 
951    si_compute_reference(&program, NULL);
952 }
953 
si_set_compute_resources(struct pipe_context * ctx_,unsigned start,unsigned count,struct pipe_surface ** surfaces)954 static void si_set_compute_resources(struct pipe_context *ctx_, unsigned start, unsigned count,
955                                      struct pipe_surface **surfaces)
956 {
957 }
958 
si_init_compute_functions(struct si_context * sctx)959 void si_init_compute_functions(struct si_context *sctx)
960 {
961    sctx->b.create_compute_state = si_create_compute_state;
962    sctx->b.delete_compute_state = si_delete_compute_state;
963    sctx->b.bind_compute_state = si_bind_compute_state;
964    sctx->b.set_compute_resources = si_set_compute_resources;
965    sctx->b.set_global_binding = si_set_global_binding;
966    sctx->b.launch_grid = si_launch_grid;
967 }
968