redbluegreen wiki

Ownership

Every kernel resource is a type with a Drop, so the teardown order comes from the tree and not from the caller.

Kfd two fds, plus the gpu_id 4 closes both fds, last owns owns Queue 1 DESTROY_QUEUE doorbell mapping 2 munmap the doorbell Buffer ring Buffer write_ptr Buffer read_ptr Buffer cwsr Buffer eop borrow, cannot outlive a slice 3 each Buffer: munmap, UNMAP, FREE Event the event page Drop: munmap, then DESTROY Kernel one Buffer descriptor plus code, step 3 Signal one Buffer a 64 byte struct, step 3 our code driver call 1 drop order, 1 to 4
Each type owns the resources under it, so Drop runs DESTROY_QUEUE, then the doorbell munmap, then munmap, UNMAP and FREE for every Buffer, and closes the two fds last.

Drop is the method Rust runs when a value goes out of scope. Every kernel resource is a type with a Drop, so the types carry the teardown order. The caller does not have to remember it.

The tree, outermost first:

  1. Kfd holds the two fds and the gpu_id. Its Drop closes both.
  2. Buffer holds a va, a size, a handle, flags and a view_mapped bit. Its Drop does munmap, UNMAP and FREE.
  3. Queue owns the ring, write_ptr, read_ptr, cwsr and eop Buffers and the doorbell mapping. Its Drop sends DESTROY_QUEUE, munmaps the doorbell, and then lets the Buffers drop in declaration order.
  4. Event owns an event id and the event page.
  5. Kernel and Signal each hold one Buffer.

A Drop cannot fail. An error inside it prints to stderr and the work goes on.

as_slice_mut borrows through the Buffer, so a slice cannot outlive the memory behind it.

Every syscall returns Result<T, Error>. The Error carries the call name and the errno, and prints as "call: message". main prints it and exits 1.

Why this matters: a training run keeps a corpus of gigabytes resident, and a GPU hang on this APU takes the desktop with it. Ownership is the cheapest guard. It is the reason we chose Rust over C.

Nesting gives the order for free. A Queue drops its own fields first and then its Buffers, so DESTROY_QUEUE always runs before the ring memory is freed.

Sources