Skip to content

Pin-token model: compile-time GPIO routing/driving authority from the system manifest - #724

Open
JesseMelon wants to merge 16 commits into
OpenPRoT:mainfrom
JesseMelon:pr/hw-claim-tracking
Open

JesseMelon wants to merge 16 commits into
OpenPRoT:mainfrom
JesseMelon:pr/hw-claim-tracking

Conversation

@JesseMelon

Copy link
Copy Markdown
Contributor

Summary

Replaces hand-authored, unsafe-heavy GPIO register access with a pin-token model where a pin's
driving authority is derived entirely from system.json5, checked at compile time wherever
possible, and cross-checked against the whole manifest wherever it isn't.

  • util/region: move-only Region<T>/Mmap tokens for a process's granted MMIO ranges,
    generated from the manifest's memory_mappings.
  • hal: a chip-agnostic pin-token vocabulary (pins!, Routes<C>, FieldWrite), a
    compile-time field-mux applier that coalesces multiple pins' register writes into one RMW per
    register (and const-panics on a contradictory config), and the GPIO capability
    (GpioBlock/GpioPin, typed register accessors, open-drain support).
  • target/ast10x0: the AST1060 pin universe and register maps as data, and a grant-free
    Route<C, P> handle for the kernel's routing-only SCU access.
  • target/ast10x0/pins: codegen turning a pin_claims_<process> manifest entry into real,
    driveable pin tokens for the one process that claims them, and the kernel's pin-routing list
    generated from the union of every app's claims (so it can't drift from what's hand-restated).
  • util/hw_claim: manifest_check, reading system.json5 directly to catch two apps claiming
    the same pin, or two processes granted overlapping MMIO, before anything compiles.
  • Three real test images (gpio_irq, gpio_smoke, gpioh_loopback) ported end to end onto
    this model.

Holding a pin token is the only authority into_output/into_input require — there's no
separate ownership marker to keep in sync, because the only way to get a token for a pin at all
is through the one generated, unsafe-marked mint that reads the manifest.

@JesseMelon
JesseMelon marked this pull request as draft November 16, 2026 20:03
@JesseMelon
JesseMelon marked this pull request as ready for review November 16, 2026 20:19
@JesseMelon JesseMelon assigned JesseMelon and unassigned JesseMelon Nov 16, 2026
@JesseMelon
JesseMelon force-pushed the pr/hw-claim-tracking branch 2 times, most recently from d1b2632 to 79ec087 Compare November 17, 2026 16:17
@EnmanuelParache

Copy link
Copy Markdown
Contributor

Thanks for this — the move to manifest-derived pin authority is a clear improvement. I reviewed it locally and built/tested the touched targets (//hal, //util/region, //util/hw_claim, //target/ast10x0/{pins,peripherals,tests/hw_claim,tests/peripherals/gpio}). Hardware tests were not run. Notes below, most important first.

Blocking

  1. Rustdoc lint fails the build. hal/src/gpio.rs (the doc on Reg::offset, ~line 84) links to GpioPin::read and GpioPin::ack, which are private; with -D warnings this trips rustdoc::private_intra_doc_links, so 1 of 64 top-level targets fails. Drop the link brackets or make the links resolvable. Because of this, the three no_panics_test targets were SKIPPED in my run; they need a re-run after the fix. Everything else passed (14/14 executed tests, including the new hw_claim positive and negative fixtures).

Documentation
2. No .md or docs/ changes, and no README for the new hal/, util/hw_claim, util/region or target/ast10x0/pins code. A design page (threat model: kernel routes, app drives), a short "how to claim a pin / add a capability" recipe, and an AGENTS.md pointer would make this discoverable for developers and agents. In-code docs are good.
3. Check that comment names match the code (e.g. MuxRoutes::COALESCED is referenced in kernel_pin_routes.rs.jinja).

Robustness
4. pin_claims_<process> is a comma-separated string. A typo or unknown pin only fails inside Jinja-generated code, with a hard-to-trace error. Consider validating names in manifest_check against the pin universe, or a structured manifest field.
5. Pin::take() is unsafe with a "once per protection domain" rule that nothing enforces. A generated one-shot guard would close that gap.
6. Make sure manifest_hw_claim_test is attached to every image, so a new target cannot skip it.

Smaller items
7. RegBatch: the TODO notes dead slots reach fastbuild binaries (196 bytes at opt-level=0).
8. gpio_smoke moves from kernel to userspace and gpioj_loopback is replaced by gpioh_loopback. Please confirm the coverage change is intended, and run the EVB tests before merge.
9. The PR is 50 files / ~3.1k added lines; splitting along the existing commit boundaries (region, hal vocabulary, ast10x0 pins, hw_claim, test ports) would ease review.

@JesseMelon

Copy link
Copy Markdown
Contributor Author

Thanks for this — the move to manifest-derived pin authority is a clear improvement. I reviewed it locally and built/tested the touched targets (//hal, //util/region, //util/hw_claim,

point 1 is fixed,

point 2 is a valid todo

point 3, they do match

point 4: I could expand the pins! macro in pins.rs to generate the valid keys as strings for comparison to the json via a script, but I feel this would add complexity to something already quite complex. too complex also would be a generated schema.json, I'm open to suggestions with this.

point 5: open to suggestions with this also

point 6: This pattern is only ported on gpio in this PR but there is also use of it with i2c on the demo branch. I hope this pattern will get adopted across ast1060 implementation, and serve as an example to future targets too. But it cannot be a firm replacement immediately, we will have to phase out old APIs after some time or risk breaking other peoples work. This would be a follow up

point 7: no comment. Open todo.

point 8: I might revert this to gpioJ for simplicity but technically it was moved to bank H.

…l's pin routing from the manifest

A pin_claims_<process_name> string constant in the manifest's apps[].constants names the pins
that process may drive. app_pin_claims turns that one list into a PinClaims struct and a
take_pin_claims() mint, handing back exactly those pins as real, driveable
ast10x0_peripherals::scu::pins tokens — holding one is the only authority into_output/into_input
require. kernel_pin_routes renders the whole manifest (every app, not one process) to route the
union of every app's claimed pins through one coalesced scu::route call, so the kernel's routing
list can never drift from what apps actually claim to drive.

Both share util/manifest_codegen's rule with app_regions, which now delegates to it too instead
of carrying its own near-identical copy of the same Bazel plumbing.
… check

Fails the build when one system manifest has a hardware conflict: two apps both claim the same
pin (read from their pin_claims_<process> constants), or two processes are both granted an
overlapping device register range (read straight from memory_mappings — a granted device range
is the claim for MMIO, unlike a pin, where holding a register-block grant doesn't say which bit
within it is actually driven). Reads system.json5 directly, before anything compiles.
@EnmanuelParache

EnmanuelParache commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for this — the move to manifest-derived pin authority is a clear improvement. I reviewed it locally and built/tested the touched targets (//hal, //util/region, //util/hw_claim,

point 1 is fixed,

point 2 is a valid todo

point 3, they do match

point 4: I could expand the pins! macro in pins.rs to generate the valid keys as strings for comparison to the json via a script, but I feel this would add complexity to something already quite complex. too complex also would be a generated schema.json, I'm open to suggestions with this.

point 5: open to suggestions with this also

point 6: This pattern is only ported on gpio in this PR but there is also use of it with i2c on the demo branch. I hope this pattern will get adopted across ast1060 implementation, and serve as an example to future targets too. But it cannot be a firm replacement immediately, we will have to phase out old APIs after some time or risk breaking other peoples work. This would be a follow up

point 7: no comment. Open todo.

point 8: I might revert this to gpioJ for simplicity but technically it was moved to bank H.

Feel free to leave gpioh_loopback as it is. I think point 2 would be nice to have in this PR we can create issues to follow up on others like 4,5 and 6.

@rusty1968
rusty1968 requested a review from swenson November 17, 2026 19:06
@rusty1968

Copy link
Copy Markdown
Collaborator

@swenson

swenson commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Are the pin claims enforced at runtime at all? As far as I can tell, take() is a public unsafe constructor for a zero-sized type, and the only runtime check is the MPU grant for the whole 4 KiB GPIO block, which covers every pin. So malicious code (or a glitch in the process that holds the GPIO grant) could drive any pin muxed to GPIO. Is the plan to put GPIO behind a server process that checks each client’s pins at runtime?

Also, scu::route() unlocks the SCU and never relocks it. Should it relock after applying the mux?

…e pin-token model

Each image's kernel side routes the pins it needs (the only code with SCU access) via the
kernel_pin_routes codegen, and hands them off to its userspace app to drive — kernel-mode pin
driving isn't a pattern any of these need. gpio_smoke's GPIOA3 is bound open-drain
(into_open_drain_output::<ActiveLow>()) to match its real electrical behavior; GPIOH4/H5's
loopback test (renamed from GPIOJ, which this rig doesn't expose) is named for the pins it
actually drives.
…arsing

rust.lang.security.args.args flags std::env::args() generically as unsafe
for security decisions (argv[0] isn't trustworthy). This use only reads
argv[1..] to pick a manifest path and a --expect-conflict flag — not a
security decision resting on argv[0].
… mux

unlock_scu_writes was never paired with a relock: the SCU's protected
registers stayed writable for the rest of the system's life after every
boot. route() is documented to run exactly once, from privileged boot
code, before any process starts, and dynamic re-muxing after boot isn't
implemented anywhere in this codebase — nothing has a legitimate reason
to need the SCU open past that point. Relock immediately after applying
the coalesced mux writes.
…ility it routes

A pin can carry more than one capability (e.g. GPIO or an I2C role on the
same pad), and the kernel's boot-time routing performs a different register
write per capability — not just a label change, the opposite RMW on the
same mux-select bit. kernel_pin_routes.rs.jinja had no way to know which
Routes<C> impl a claimed pin meant, so it hardcoded Gpio for every pin.

pin_claims_<process> entries are now `pin:capability` pairs (e.g.
scu410_0:gpio); the kernel template picks the route from the tag, the
app-side template drops it (capability-agnostic there), and
manifest_check validates the tag against a known list before either
template ever runs.
take() minted any pin in the chip's universe for anyone willing to write
an unsafe block, regardless of whether that process's own system.json5
entry actually listed it — driving a pin already required holding its
token (GpioPin's register-touching methods are private, no raw escape
hatch exists around them), but minting the token itself was unrestricted.

take() now requires A: AuthorizesPin<Self> — a marker trait whose only
intended implementations are generated from the manifest: pin_claims.rs
emits one zero-sized Authority type per process with an impl per pin that
process's own pin_claims_<process> entry lists; kernel_pin_routes.rs emits
one for the union of every claimed pin, for the kernel's own routing. A
pin outside that set has no matching impl anywhere in the program, so
minting it fails to compile — verified with a deliberate negative case
(an out-of-grant take() call) that produced exactly the expected E0277.

This does not make take() single-use within a domain — that's a separate,
harder problem (enforcing "call at most once" structurally needs either a
runtime flag or trusting the single generated call site, same as today).
@JesseMelon

Copy link
Copy Markdown
Contributor Author

Are the pin claims enforced at runtime at all? As far as I can tell, take() is a public unsafe constructor for a zero-sized type, and the only runtime check is the MPU grant for the whole 4 KiB GPIO block, which covers every pin. So malicious code (or a glitch in the process that holds the GPIO grant) could drive any pin muxed to GPIO. Is the plan to put GPIO behind a server process that checks each client’s pins at runtime?

Also, scu::route() unlocks the SCU and never relocks it. Should it relock after applying the mux?

Thanks for your input, I appreciate it. I went ahead and addressed the scu lock. Good catch.

On the driver question The GPIO controller cannot arbitrarily drive any pin just because it holds the whole 4 KiB MPU grant, unlike on main currently where every pin method dereferences the raw global PAC pointer directly (unsafe { &*device::Gpio::ptr() }), and split() hands back every pin in a bank unconditionally, with no grant check at all.

  • GpioPin's only register-touching methods: mmio(), apply(), read(), ack(); are all private. Nothing outside hal::gpio can call them.
  • The only way to reach them is through GpioPin's public API (into_output, set_high, etc.), and every one of those requires an actual GpioPin<P, R, D> instance.
  • The only constructor for that is GpioPin::new(pin: P, block: &GpioBlock), which consumes a real P: Routes token.
  • There's no raw escape hatch around any of this either: GpioBlockMarker (the phantom type tagging the whole GPIO block's MMIO accessor) has no impl Block anywhere only ScuBlock does. So there's no public way to mint a raw Mmio and poke arbitrary bits directly; the one private mmio() method inside GpioPin is the only thing that ever constructs one, always with that specific pin's own base/bit baked in.

Your questions also made me notice that take() did not check against the system.json5 grant like it should, so that has just been addressed too.

If server/runtime checks are still required, is open to discussion I think.

@swenson

swenson commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

All of the protections mentioned are only protections in that they prevent us from writing legitimate firmware that violates these rules -- private methods and compile-time checks don't protect us against a process that has been compromised, overwritten, or glitched. The only thing that protects you there is having those runtime accesses checked against capabilities, e.g., by the kernel or privileged service/driver.

So, this might be a more general question about how we approach our threat model and what kinds of attacks are in-scope.

It's definitely always good to add additional compile-time checks, but we can't assume attackers honor compile-time checks.

Comment thread hal/src/field_mux.rs Resolved
Comment thread hal/src/field_mux.rs Resolved
Comment thread hal/src/field_mux.rs Resolved
Comment thread hal/src/gpio.rs Resolved
…-bounds at RegBatch construction

RegBatch<B> is block-typed, and apply<B, H: MuxRoutes<B>>() is safe (no unsafe
keyword) because it forces a reference to ProvenInBounds::PROVEN before
touching hardware. PROVEN is an associated const, not a function call -- the
compiler evaluates an associated const's initializer unconditionally at
compile time, regardless of where or how it's referenced, so the bounds check
inside it (every offset in H::COALESCED fits B::SIZE) has no runtime-reachable
path, ever. This is deliberately not an assert inside a plain const fn (e.g.
RegBatch::push): a const fn's evaluation timing is inherited from its call
site, so the same assert can run at compile time from one caller and at
genuine runtime from another -- which is exactly the gap this closes. Verified
the rejecting case is a compile error, not a runtime panic, by hand: a
temporary out-of-range route offset on a test pin failed the build with
"evaluation panicked: ... erroneous constant encountered", not a test harness
panic.

This replaces a documented, trusted invariant with one the compiler enforces,
closing a review concern that an arbitrary/unchecked register offset was only
checked by convention.
… the trait

Without this, any code could hand-write a MuxRoutes impl whose COALESCED
comes from coalesce_routes() called on arbitrary, hand-picked offsets --
still in-bounds (that part's proven separately), but never derived from any
pin's own Routes impl, bypassing the pin-token authority model that Route
and GpioPin exist to enforce. Rather than sealing the trait (a new marker
trait plus an impl for every implementor), coalesce_routes and RegBatch::new
drop from pub to pub(crate): they're the only way to put anything into a
RegBatch, so with them crate-private, no implementor outside this crate can
give COALESCED a real op at all, regardless of whether MuxRoutes itself is
sealed. Verified by hand: the same probe impl now fails with "function
coalesce_routes is private" instead of a missing sealed-trait bound.
Narrows read_reg/write_reg to pub(crate) -- their only callers (apply, via
ProvenInBounds, and gpio's accessors, via AssertGpioGrant/map_extent) already
discharge the bounds obligation before calling in, so nothing outside this
crate could ever reach them anyway. In their place, read_reg_at/write_reg_at
take the offset as a const generic instead of a runtime u32: the bounds check
runs in an inline const block referencing the generic directly, which the
language evaluates at compile time regardless of call context, same proof
shape as ProvenInBounds. There is no way to call these with an offset that
wasn't just checked against B::SIZE, because there's no way to name the
offset except as that literal. Verified both directions by hand: an external
crate can no longer reach the raw primitive at all (E0624, private method),
and an out-of-range literal through the checked path fails the build (E0080,
not a runtime panic). registers.rs's two SCU lock/unlock calls move to the
checked form and drop their unsafe blocks entirely.
@JesseMelon
JesseMelon requested a review from yvettewu1 November 18, 2026 19:54

@swenson swenson left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM; I think we should still investigate having a runtime check, as compile-time checks only get us so far with security.

@lxuxx

lxuxx commented Nov 18, 2026

Copy link
Copy Markdown
Collaborator

The previous GPIO implementation supported GPIO banks A through U, but the new gpio/map.rs only defines ABCD, EFGH, and IJKL. Also, scu/pins.rs currently defines only a subset of GPIO pins within these groups. Is this intentional? If so, how will GPIO M–U and the remaining pins be supported after the old implementation is removed?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants