Apple Silicon: Lina's AGX notes
apple_asahi_docs)Apple Silicon M1 / M2 / M3+ SoCs
main
Summary
Reader beware, here be dragons. Pointer-shaped dragons. Lots of them.
Syntax / Encoding
Lina's AGX notes
Reference Notes
# Lina's AGX notes
Reader beware, here be dragons. Pointer-shaped dragons. Lots of them.
This document focuses on the AGX architecture from the point of view of a kernel driver. It will not discuss aspects that are purely of userspace concern, like shaders, texture sampling, pipeline command encoders, etc.
## Overview
AGX is a *heavily* PowerVR-inspired (but largely bespoke) GPU design. The OS interface is brokered almost exclusively via an ASC (ARM64) coprocessor, which runs Apple firmware. All communication occurs via shared memory and a few mailbox doorbell messages. All memory is coherent as far as we can tell (we haven't used a single cache management instruction yet and everything still works).
The layers involved in getting a triangle on the screen are roughly:
* UAT (MMU)
* Firmware init
* GPU Channels
* GPU Contexts
* Work Queues
* Work Items
* Micro Sequences
* Tiler buffer management
* Event management
* (All the userspace stuff goes here)
### UAT (Unified Address Translator)
The UAT is the AGX's MMU. It is essentially the ARM64 MMU, and uses identical page tables. In fact, the AGX ASC literally configures UAT page table bases as its TTBR0/1 registers. There *may* be some nuance to how the GPU proper interprets page permissions and other attributes compared to how a CPU would; this is still largely unexplored.
GPU VAs are 40 bits, with the top bit sign-extended to 64 bits. As with ARM64, there is a kernel/user address space split. Pages are always 16K.
There is a global, fixed page of memory that contains GPU context page table base addresses. There are up to 16 contexts (TODO: double check this limit is real and not driver-controlled), each with two base registers for the kernel/user page tables.
macOS always uses context 0 for the kernel only (no user pages for that one) and shares the kernel half of the page tables for all contexts. User VA space is unique per context.
The kernel address space literally maps ASC firmware too, as it *is* the ASC's CPU page table. This is in a VA range that the firmware controls by itself, and sets up during initialization. The host OS is responsible for the rest of the page tables in this half of the address space, which is where all the GPU control structures go.
Note: firmware is loaded by the bootloader and write-protected. While hijacking the page tables to completely take over AGX firmware is plausible with the current design, clearly Apple's intent and direction is for ASC firmwares to be hardened against takeover, so we will not consider using our own firmware at this point. Talking to Apple's firmware to make this GPU work is considered non-negotiable.
TODO: UAT TLB invalidation. There's some shared memory involved and poking the firmware.
### Firmware init
Firmware communication uses the RTKit framework common to other ASCs, which will not be covered here. Only the memory/buffer management is different (other ASCs use either DART IOMMUs, SART address filters, or can only access dedicated SRAM).
To initialize the GPU, a single message is sent containing a pointer to an inititalization data structure. This is a complex nested data structure with more pointers, containing things such as:
* Channel ring buffer control area and ring buffer area pointers
* Power management data including DVFS states
* Shared memory regions containing various (largely unknown) data
* Colorspace conversion coefficients
* MMIO mapping list (OS is responsible for mapping MMIO regions the ASC needs to access)
* UAT layout information
* Various unknown buffers
Data structures: see [initdata.py](https://github.com/AsahiLinux/m1n1/blob/main/proxyclient/m1n1/fw/agx/initdata.py)
### Channels
Communication with the firmware happens via channel ring buffers. Channels hold small, fixed-size messages delivered in-line in the ring buffers. A control structure has the read/write buffer pointers and size, cacheline-aligned so the GPU/CPU do not bounce things all the time. There are channels in both directions.
Data structures: see [channels.py](https://github.com/AsahiLinux/m1n1/blob/main/proxyclient/m1n1/fw/agx/channels.py)
#### CPU->GPU channels
* Work Channels: four groups (0-3), each with three channels, one per GPU work type
* TA (Tile Accelerator; vertex processing)
* 3D (3D; pixel processing)
* CP (Compute)
TODO: there is probably some priority scheme for work submitted to different channels.
* DeviceControl channel, for device-wide messages (e.g. GPU init and presumably power management related stuff)
#### GPU->CPU channels
* Event: work-related event notifications
* Work completion flag events
* These have a 128-bit array indicating which event indices are firing
* Fault notifications
* GPU faults seem to be quite poorly handled as a stop-the-world process; macOS actually goes off dumping GPU MMIO registers directly, and the firmware seems to be quite clueless as to what to do.
* Statistics messages
* We ignore these. The firmware will complain once if the buffer overflows, but it's harmless.
* Firmware syslogs
* This one is weird in that there are multiple sub-channels for some reason, with control structures laid out contiguously.
* An unknown channel (tracing?)
### GPU contexts
GPU contexts map to a few small shared structures, some populated by the ASC. This is mostly still TBD.
### Work Queues
A work queue holds work items of a specific type. There are usually multiple work queues per context (e.g. at least 3D and TA for 3D rendering). Work queues are represented by a few structures, mostly a main structure initialized by the CPU and managed by the GPU, with pointers to context structures, a ring buffer, a ring buffer pointer block, and others. The ring buffer is an array of pointers to individual items (not in-line).
To process a work queue, the OS submits a message on a work channel with a pointer to the work queue management structure and the most recent ring buffer write pointer, plus an event index to signal work completion, and a flag indicating whether this is the first submission from a new work queue.
Data structures: see [cmdqueue.py](https://github.com/AsahiLinux/m1n1/blob/main/proxyclient/m1n1/fw/agx/cmdqueue.py)
### Work items
Work items represent GPU work or related operations. These are fairly large buffers containing embedded sub-structures in a particular layout (pointers to some of these sub-structures exist, but the firmware assumes the embedding in a particular way, so the layout must be respected).
Data structures: see [cmdqueue.py](https://github.com/AsahiLinux/m1n1/blob/main/proxyclient/m1n1/fw/agx/cmdqueue.py)
### Micro Sequences
The ASC firmware contains a command sequencer that can run fairly complex "scripts" as part of work commands, but it is usually used in a fairly basic manner. These sequences are packed buffers of commands that are executed as part of a work item. The typical sequence is:
* Start (3D/TA/CP)
* Write Timestamp
* Wait For Idle
* Write Timestamp
* Finish (3D/TA/CP)
Data structures: see [microsequence.py](https://github.com/AsahiLinux/m1n1/blob/main/proxyclient/m1n1/fw/agx/microsequence.py)
### Tiler buffer management
The GPU tiler needs a buffer to store vertex attribute and primitive data. This is done through a few fixed-size buffers provided by the driver, and a heap that the GPU firmware allocates stuff out of at its discretion. The heap is managed via a buffer manager object and a few buffers it points to, where the CPU provides a list of blocks (4 pages) and pages (32K each, aligned in VA space (!)).
The tiler buffer overflow / partial store / reload process is entirely managed by ASC firmware.
Data structures: see BufferManager* in [microsequence.py](https://github.com/AsahiLinux/m1n1/blob/main/proxyclient/m1n1/fw/agx/microsequence.py)
### Event Management
Work completion is signaled by writing values to stamp objects, which are 32-bit words in RAM. Typically initialized at 0 and increment by 0x100 for each work item processed. Each work item is also associated with an event ID (0-127), and an event management structure. The structure is shared between 3D/TA for a single user, and contains the base barrier value and (?) a number of events threshold. When the threshold is reached, the corresponding event ID(s) are asserted in an Event message to the CPU. How this works/counts is still unclear, since the same structure is shared between different queues using different barrier objects which increment in lockstep, but each only increments by one while the threshold needs to be 2 to get both events... TBD
## Drawing a 3D frame
To draw a frame first you need these things:
* A pair of 3D/TA channels to use
* A pair of event indexes for completion notification
* A pair of WorkQueues
* A context ID for the UAT
* A shared context structure
* Tiler static buffers
* Tiler heap manager & associated buffers/lists
* Four stamp objects
### Tiler buffers
* (U) TVB tile array (depends on tile count)
* (U) TVB list array (depends on tile count?)
* (U) TVB heap metadata block (fixed size?)
* (K) TVB heap manager & (U) heap (arbitrary size >= 3 128K blocks, CPU can dynamically adjust in response to overflows for future frames)
macOS allocates these in the kernel. Do we want to do it in the kernel or userspace? Userspace should probably be in control of sizing at least? Could let the kernel decide, or have userspace donate pages to the buffer manager. Kernel needs to handle the heap manager structure at least.
### Stamp objects & event management
There are 128 event indices. A render needs 4 stamp objects, 2 each for TA/3D. Current theory is one stamp indicates completion of the work, the other indicates the completion event was delivered to the CPU (work was reaped?)
### TA work
The TA work usually looks like this:
#### Initialize Heap Manager
Needed the first time or when the heap size changes. Tells the GPU that the CPU re-initialized the management structure.
There is an unknown context-related ID involved. This might be a heap manager ID? The (new) TA stamp value is also passed.
#### Execute TA
Note: this is all summarized and glosses over tons of unknown/fixed/magic numbers
* UAT context ID for this job
* Event management structure pointer
* Heap manager structure pointer
* Pointer to some kind of related buffer descriptor (?)
* Pointer to unknown buffer (empty)
* Timestamp 1 ptr
* Timestamp 2 ptr
* Timestamp 3 ptr
* Unknown buffer 2 (empty)
* Embedded structures:
* Tiler parameters (tile counts/etc)
* TA work struct 2
* TVB tilemap ptr
* TVB list ptr
* Three small buffers passed from userspace (alyssa calls these "deflake")
* Command encoder ptr (i.e. actual gfx pipeline to run, from userspace)
* Pipeline window base (4GiB window into VAs used for 32-bit shader pointers)
* TA work struct 3
* One of the deflake ptrs
* Encoder ID (unique ID, GPU likely does not care)
* "Unknown buffer" (the one with incrementing numbers, from userspace)
* Pointer to TA barrier 1 and 2
* Stamp value to write on completion
* Some UUID
* Micro sequence pointers
* Completion stamp value again
* Event number assigned to 3D (for TA/3D coordination on TVB overflows?)
* TVB tile array again & size
### TA Micro Sequence
The micro sequence is pointed to by the TA work and has these commands:
#### Start TA
* Tiling params ptr
* TA work struct 2 ptr
* Heap manager ptr
* Buffer descriptor thing pointer
* Some pointer into an array in the shared GPU initdata (?)
* Pointer back to the work queue control structure involved
* UAT context ID
* That other context-related ID (heap mgr id?)
* TA work struct 3 ptr
* Pointer to one of the unknown buffers in Execute TA
* UUID
#### Timestamp
* Flag=1
* Points to three timestamp pointers in Execute TA: #1, #2, #2
* UUID
#### Wait For Idle
* Args: 1, 0, 0
#### Timestamp
* Flag=0
* Points to three timestamp pointers in Execute TA: