The bytes and the order of writes that make the
hardware run one kernel.
One dispatch is four objects and an order of writes, and
the doorbell is the last write and the only one that starts the
hardware.
A dispatch is four objects and an order of writes.
The four objects:
The kernel object is one 4 KiB buffer, COHERENT and EXECUTABLE. Bytes 0 to 64 hold the kernel descriptor.
The code starts at byte 256.
The kernarg buffer is 4 KiB and COHERENT. It
holds the address the kernel writes to.
The signal is 64 bytes and
zero-filled. The kind, 1 for user, is at offset 0. The value is at
offset 8.
The packet sits in the ring and points at the other
three.
We set the signal value to 1. The CP
decrements it to 0 when the packet retires. Our code polls it.
The descriptor is the dangerous one.
Its register fields tell the hardware how many registers each
wave gets and how the wave starts. A wrong bit there
resets the GPU.
So the assembler builds the descriptor from the .amdhsa_ directives in the source. We patch one field
at load: the i64 at
offset 16, kernel_code_entry_byte_offset, set to 256.
The assembler leaves it as a relocation.
The descriptor asks for the kernarg pointer in s[0:1].
The packet is 64 bytes. It holds a header and setup, the
workgroup and grid sizes, the private and group segment sizes, and
three addresses: kernel_object, kernarg_address and
completion_signal.
The header is 0x1502: KERNEL_DISPATCH, barrier, acquire system and release system. Setup 1 means one
dimension.
The order of writes is the mechanism. ROCr does exactly
this:
Write the packet body.
Write the header last, as one u32 store after a release
fence. The CP never reads a half-built packet behind a
valid header.
Set the write pointer to the packet index
plus one.
Write the packet's own index to the doorbell. It is not the index plus one and not
the ring slot.
The doorbell write is the one place in our code that starts
hardware. A comment in the code says so.
With coherent memory, the CP finds the packet from the write
pointer alone, so a packet can run with no doorbell. Ring it
anyway.
The first kernel is store42. It is nine instructions
and 36 bytes of code. Its steps:
Load the target address from the kernarg pointer.
Store 42.
Wait for the store.
End.
tools/asm assembles it with llvm-mc. Then llvm-objcopy
extracts the .text code and the 64-byte .rodata descriptor.
The bytes are committed, so a clone without LLVM still
builds.
On the first run, target[0] became 42. The signal did not reach
0.