# Transfer provider contract

A module whose plan schedules `dma` units copies them through a **transfer
provider**: three functions and a `self` pointer that the application sets in
the context before `<prefix>_model_init`. `cpu` units need no provider; the
module copies them itself. For when to stream and how to write a schedule, see
[Streaming constants](https://ambiqai.github.io/helia-aot/guide/streaming/).

The examples use the default prefix, `aot`. The declarations are in
`<prefix>_context.h`, and their stability is `advanced` (see
[the generated C API](https://ambiqai.github.io/helia-aot/reference/compatibility/#the-generated-c-api)).

## The interface

From heliaAOT 1.5.0 (C API 2.0.0):

```c
typedef int32_t (*aot_transfer_issue_fn)(void *self, uint32_t ticket, void *destination,
                                        const void *source, size_t bytes);
typedef int32_t (*aot_transfer_wait_fn)(void *self, uint32_t ticket);
typedef int32_t (*aot_transfer_abort_fn)(void *self);
typedef struct {
    aot_transfer_issue_fn issue;
    aot_transfer_wait_fn wait;
    aot_transfer_abort_fn abort;
    void *self;
} aot_transfer_provider_t;
```

| Call | When the module calls it | What it must do | Returns |
| --- | --- | --- | --- |
| `issue` | After the operator a `dma` unit is issued after, once per piece, in piece order | Queue one piece and return without waiting. `ticket` is the unit id. `source` is the CPU address of the piece's bytes: route the piece by it. | 0, or a code of the provider's own |
| `wait` | Before the first operator that reads the unit | Return 0 once every piece issued with `ticket` in this run has landed and the destination bytes are visible to the CPU. | 0, or a code of the provider's own |
| `abort` | After any failure once a run has started | Cancel or drain every piece issued with this `self` and not waited for, never another `self`'s. | 0 when no piece remains |

- The three function types are the same in every module, so one set of
  functions serves every module. Each module's struct points at them.
- A piece never crosses the pool memory's DMA boundary (4096 bytes in DTCM on
  the Apollo510 family), counted from the pool base. The report lists every
  piece under `pieces`.
- The struct only grows, by members appended after `self`. A source the CPU
  cannot address, which no target has today, would arrive that way: a member
  that locates bytes by the module's region and an offset.

Before 1.5.0 (C API 1), `issue` also took `source_memory` and `source_offset`,
and the module declared `<prefix>_memory_t`. A provider written for C API 1
drops those two arguments.

## What a provider owes the module

| Obligation | What it means |
| --- | --- |
| Destination | The stream pool is uncached DTCM, the only pool memory the configuration accepts, so a provider does no cache maintenance of the destination. A cacheable pool memory, when one is added, comes with its own rule. |
| Source | The provider does no maintenance of the source. The application keeps the source coherent for a DMA reader; see [Target rules](https://ambiqai.github.io/helia-aot/reference/transfer-provider/#target-rules). |
| Reads during DMA | While pieces are in flight, the module keeps reading the same source through its memory-mapped window (a `cpu` unit's copy, constants read in place). The provider and its driver keep those reads correct. |
| One `self` per overlapping run | Tickets are one module's unit ids. Modules whose runs can overlap (a task preempting a run) each use their own `self`, or the application serializes their runs. |
| Power | From each piece's issue until it is waited for or aborted, hold a power-management lock, or expose a predicate the idle path checks. `wait` may block, but never lets the core enter a power state in which the transfer cannot complete. |
| Queue depth | Hold at least `<prefix>_transfer_pieces_in_flight` pieces. See [Queue depth](https://ambiqai.github.io/helia-aot/reference/transfer-provider/#queue-depth). |
| Errors | Keep the last failure code where the application can read it. Under `module.schedule: static` no callback carries it. |
| Recovery | After a non-zero `abort`, stay unusable until the application resets the provider. |
| Calls | Every call comes from the thread that calls `<prefix>_model_run`, never from an interrupt handler. Completion may be signalled from one. |

## Queue depth

`<prefix>_transfer_pieces_in_flight` is the most `dma` pieces a run has issued
and not yet waited for. The report states the same number as the stable field
`stream_pool.pieces_in_flight`, from heliaAOT 1.5.0; build the driver's queue
from it.

- One module: a queue of at least that many pieces.
- Several modules on one queue whose runs overlap: at least the sum of their
  numbers. No plan field can state that; it is the application's fact.
- No `dma` units: 0, and no provider is needed.

## Runtime statuses

| Status | From | Meaning | Recovery |
| --- | --- | --- | --- |
| 10 | `<prefix>_model_init`, from `<prefix>_context_init` | An arena region is not bound: the stream pool, which the application binds in both arena modes, or, with caller-bound arenas (`memory.allocate_arenas: false`), any region, scratch, persistent or constant. | `<prefix>_bind_arena(region, buffer, size)` for every unbound region before `<prefix>_model_init`. |
| 300 | `<prefix>_model_init`, `<prefix>_model_run` | The module has a `dma` unit and `ctx.transfer`, or one of its functions, is NULL. | Set `ctx.transfer` before `<prefix>_model_init`. |
| 301 | `<prefix>_model_run` | An `issue` or `wait` returned non-zero, and `abort` then drained every piece. | Read the provider's own code; the next run can follow. |
| 302 | `<prefix>_model_run` | `abort` returned non-zero too: a piece may still land. The module clears its lifecycle latch. | Reset the provider, then call `<prefix>_model_init` before running this module or any module bound to the same pool or provider. |
| 14 | `<prefix>_model_run` | Returned after 302 until the next successful `<prefix>_model_init`. | As for 302. |

When `<prefix>_model_run` returns 0, 301 or an operator's status, no piece is
in flight. The pool's contents are unspecified between runs.

The generated test case of a module with `dma` units binds a synchronous
provider of its own, which copies each piece when it is issued, so the test
runs without an application provider. That holds with module-owned arenas.
With caller-bound arenas (`memory.allocate_arenas: false`) the test loads no
sidecar: it returns -1 when a constant arena is read in place from a memory it
cannot write, such as MRAM, and binds a zero-filled buffer for one in a
writable memory, such as PSRAM. Check such a module with a harness of your own
that loads and binds the sidecars, then calls `<prefix>_model_init` and
`<prefix>_model_run`.

## Target rules

The module README's "Transfer provider rules" section prints the rules of the
module's target when the module has `dma` units, in every module type.

| Rule | Where it comes from | Today |
| --- | --- | --- |
| The core's D-cache line | The target's core | 32 bytes on Cortex-M55 (the Apollo510 and Apollo330 families and atomiq110); none recorded for other cores |
| Power states in which DMA cannot complete | The SoC | Apollo510 family: DMA to DTCM is forbidden in deep sleep (DS-A510 p22). On Apollo330P, catalog 0.3.x records the DTCM deep-sleep restriction. Catalog 0.2.x has no recorded restriction for that SoC. |

The cache rule for a constant arena in a cacheable external memory, such as
PSRAM:

1. From heliaAOT 1.5.0 the module aligns such an arena to the core's D-cache
   line and pads its size to it. It does the same for a constant arena staged
   from or into external memory. `alignas`, `<prefix>_arena_alignments[]`,
   the `_size` and `_alignment` macros and the residency report agree, and
   `<prefix>_bind_arena` refuses a misaligned buffer for an arena the
   application binds. No tensor inside the arena moves. A conversion refuses
   a memory planner backend whose arena record breaks the rule.
2. After loading the constants, clean and invalidate the D-cache over the
   arena before the first run, and again after any reload.
3. If the arena was ever written through the cached window (a clear, a copy,
   a test), clean and invalidate it before the load as well, or a dirty line
   evicted later overwrites the constants that `dma` pieces read.
4. Never invalidate the whole D-cache without a clean: that discards
   unrelated dirty lines.

## The emitted nsx provider

An `nsx` module with `dma` units ships its own provider under
`module.transfer_provider: auto`, the default. It is experimental with that
setting, and its declarations are `internal`.

| What | Value |
| --- | --- |
| Files | `includes-api/<prefix>_nsx_transfer.h` and `src/<prefix>_nsx_transfer.c` |
| CMake target | `nsx::<module>_nsx_transfer`, compiled only when the application links it |
| Driver | The nsx-psram module's asynchronous read, API 1.1.0 or newer, which `nsx-module.yaml` lists as a dependency |
| Configure | The module's CMake fails at configure time without `nsx::psram`, even when the application binds its own provider; convert with `module.transfer_provider: none` to drop the target |
| Bind | `<prefix>_nsx_transfer_bind(&ctx, NULL)` after `nsx_psram_init` (with XIP enabled) and before `<prefix>_model_init` |
| Sources | PSRAM only: a conversion under `auto` refuses a `dma` unit stored in another memory |
| Queue | nsx-psram's `NSX_PSRAM_ASYNC_DEPTH`, 8 by default and at most 32. The conversion warns when a module needs more than 8 and refuses one that needs more than 32. |
| Sleep | `<prefix>_nsx_transfer_can_sleep()`: no piece in flight, no failed abort, and `nsx_psram_can_sleep()`. A snapshot: evaluate it with interrupts masked and enter sleep inside that section. |
| Cache | None of the source and none of the destination. The application follows [Target rules](https://ambiqai.github.io/helia-aot/reference/transfer-provider/#target-rules). |
| Observer | Optional, for profiling: see [The completion observer](https://ambiqai.github.io/helia-aot/reference/transfer-provider/#the-completion-observer). |

`module.transfer_provider: none` emits nothing, for an application that binds
its own provider. `cmake`, `cmsis_pack` and `zephyr` modules leave the
provider to the application under either value.

Its codes are 310 to 329. `<prefix>_nsx_transfer_bind` and
`<prefix>_nsx_transfer_reset` return them. In a run they reach the
application on three channels, which can disagree:

| Channel | What it carries |
| --- | --- |
| `<prefix>_model_run`'s status | 301 when an issue or wait failed and abort drained every piece; 302 when abort failed too. |
| The callback, under `module.schedule: table` | `transfer_issue_finished` and `transfer_wait_finished` carry that issue's or wait's own code. No state reports abort: its failure shows only as 302 and in `last()`. |
| `<prefix>_nsx_transfer_last()` | A diagnostic record of the latest failure: code, driver status and ticket. Each later failure of issue, wait, abort, reset or bind overwrites it, and a bind that returns 0 clears it. |

A wait that times out and an abort that then fails give 321 in the
`transfer_wait_finished` callback, 323 in `last()->error` and 302 from
`<prefix>_model_run`.

| Code | Name | Returned by | Cause |
| --- | --- | --- | --- |
| 310 | `null_context` | bind | `ctx` is NULL. |
| 311 | `psram_api` | bind | nsx-psram's supported range excludes API 1.1.0. |
| 312 | `psram_not_ready` | bind | nsx-psram's info failed, it is not READY, or XIP is off. |
| 313 | `psram_no_async` | bind | `NSX_PSRAM_CAP_ASYNC_READ` is clear (Apollo3, Apollo4). |
| 314 | `psram_depth` | bind | nsx-psram's queue is shorter than `<prefix>_transfer_pieces_in_flight`. |
| 315 | `failed` | issue, wait | A previous abort failed; call reset until it returns 0. |
| 316 | | | Retired from C API 1; never reused. |
| 317 | `window` | issue | The piece lies outside the PSRAM XIP window, or has 0 bytes. On every run, it means the PSRAM constant arena is not in PSRAM; see [Put the PSRAM constants in PSRAM](https://ambiqai.github.io/helia-aot/guide/streaming/#put-the-psram-constants-in-psram). |
| 318 | `slots` | issue | More pieces in flight than `<prefix>_transfer_pieces_in_flight`. |
| 319 | `queue` | issue | nsx-psram refused the read. With `driver_status` BUSY, another client held the queue: retry the run. |
| 320 | `ticket` | wait | No piece in flight has the ticket. |
| 321 | `timeout` | wait | The wait's check budget ran out; abort drains the pieces. |
| 322 | `landed` | wait | A piece completed with a transfer failure. |
| 323 | `drain` | abort, reset, bind | The drain timed out; a piece may still land. |

After 302, call `<prefix>_nsx_transfer_reset()` until it returns 0, then
`<prefix>_model_init`. A reset that keeps failing means a read never
completes, and only a system reset recovers.

### The completion observer

`<prefix>_nsx_transfer_options_t` takes an optional observer, which the
provider calls once for each read nsx-psram accepted, when it completes. The
observer reads its own clock; the provider records no time. What it gets is
when each completion was notified, not when the bus moved the bytes.

| What | Value |
| --- | --- |
| Bind | `observe` and `observer_ctx` in the options given to `<prefix>_nsx_transfer_bind`. A NULL `observe` binds none; a NULL `observer_ctx` is passed as NULL. Zero-initialize the options: `= {0}` in C, `{}` in C++. An initializer that names fewer members, such as `{4096u, 200000u}`, still zeroes the observer but warns under `-Wextra` (`-Wmissing-field-initializers`). |
| Called | Only from nsx-psram's completion callback, in the MSPI interrupt, at that interrupt's priority with interrupts enabled. A refused read is never observed: issue's code and `last()` report it. |
| Piece | `sequence`: the binding's accepted reads, numbered 0, 1, 2, ... with no gaps, modulo 2^32. `ticket`: the unit's, as issue received it. `bytes`. `status`: 0 or `NSX_PSRAM_STATUS_TRANSFER_FAILED`. The pointer is valid only during the call. |
| Matching | A unit's pieces are issued one after another, so they carry consecutive sequences: match pieces by sequence and units by ticket. |
| Kept | Until the next bind that returns 0, which replaces the observer and its ctx and restarts the sequence at 0; one with NULL options or a NULL `observe` unbinds it. The pieces a successful bind drains go to the previous observer and ctx, with the old sequence, before the replacement takes effect, so the old ctx must stay valid through that call. A bind that fails, `reset` and `abort` keep both, so late completions and the runs after a recovery still reach them. Keep the ctx valid for as long as the observer is bound: a successful drain only means that no late completion is still to come. |
| Rules | The observer must not block, print, allocate, mask interrupts or call any nsx-psram API, queries included: nsx-psram's callback rule. Nor may it call the provider (issue, wait, abort, `<prefix>_nsx_transfer_bind` or `_reset`) or `<prefix>_model_run`. |
| Cost | With none bound: per completion, one load and one branch, in a completion handler that now sets up a stack frame; per read `issue` submits, two stores, and per accepted read, one increment. RAM: 12 bytes of state plus 8 per slot, so 28 bytes for a module with two pieces in flight. |
