Author SHA1 Message Date
Daniel Samson d4f8dc51b9 docs: the hot-plug matrix is complete — 124/124 2026-08-09 14:19:39 +01:00
Daniel Samson 36ca3f98b3 test: H4 + H5 — a moved device is a new device, and generations do not leak
The hot-plug matrix's last two cells. H4: unplug from hub port 1.1, replug
on 1.2 — per-port identity means the old child is removed and reaped while
the new port binds a fresh driver; nothing ties a driver to the old port.
H5: three unplug/replug cycles on one port — three reaps, a bind after the
last, proving slots, the bus open table, and the manager's driver entries
are all reusable across generations.
2026-08-09 14:11:05 +01:00
Daniel Samson c3604429d4 test: H3 — a nested hub tree yanked whole rebuilds whole (hot-plug matrix)
hub -> hub -> keyboard, one device_del of the outer hub: the H2 recursion
runs at depth two (the inner hub is torn down as a child, its keyboard
first), the keyboard's driver is reaped, and re-adding all three rebinds.
2026-08-09 14:09:19 +01:00
Daniel Samson 77e7001878 usb: a hub yanked from a root port takes its subtree with it (H2)
The hot-plug matrix's predicted bug, found on first contact: tearDownPort
never recursed into a departing hub's children — only tearDownHubDevice
(a hub leaving one level down) did. Yank a populated hub from a root port
and the downstream slots stayed live against vanished hardware, their class
drivers were never reaped, and the replugged hub found its port still
occupied, so nothing ever re-enumerated: the subtree was gone for the boot.

tearDownPort now recurses children-first, exactly like tearDownHubDevice.
The usb-hub-yank case is the discrimination: one device_del removes a hub
carrying a keyboard AND a mouse, both drivers must be reaped, and the
re-added hub must rebind both — it failed against the unfixed bus and
passes with the recursion.
2026-08-09 14:08:15 +01:00
Daniel Samson a6a3402d92 test: H1 — root-port unplug and replug (hot-plug matrix)
The tearDownPort path, exercised for the first time with a real removal and
return: QEMU raises no root-port change events, so the bus's 250 ms
reconcile tick notices the PORTSC change alone — and it does. Reap, re-add,
rebind, second generation binds on the same port. Discrimination: against
the pre-reap manager (4a2df58~1) the case fails at the dedupe wall.
2026-08-09 14:03:02 +01:00
Daniel Samson d565a6b845 docs: the hot-plug matrix plan — unplug anything, replug anywhere 2026-08-09 13:58:29 +01:00
Daniel Samson 4a2df587bb establishment: unplug reaps like death, so a replug rebinds
The hot-unplug path (onChildRemoved, a report from a live bus) cleared the
child but left the bound class driver: a process blocked on reports that
will never come, whose stale entry made the matcher's dedupe refuse the
respawn when the device was plugged back in — the same wall the restart
zombie hit, one path over. Unplug now reaps exactly like reporter death.

The usb-hub-unplug case grows the replug: device_del the hub keyboard, then
device_add it back (qmp_sequence); the ordered tail — child removed, reaping,
delegated, ok — can only be satisfied by the second generation, since every
boot keyboard's ok precedes the unplug. Discrimination: without the reap the
replug never rebinds and the case times out (verified by stash run). Hub
family, restart drill, and the two-controller proof all green (8/8).
2026-08-09 13:51:07 +01:00
Daniel Samson 3c9f454398 establishment: the two-controller proof, and the docs catch up
P4 of docs/establishment-planes-plan.md. The new usb-two-controllers case is
the Ryzen mouse bug pinned in the suite: a second xHCI controller with its
own keyboard while the boot controller keeps the default one — both must
come up, on different device ids, which requires each class driver to reach
ITS OWN controller. Discrimination: at 72807c2 (name-based establishment)
the case fails — one keyboard is unreachable, exactly the bench failure —
verified against a checkout of that merge; with lineage routing it passes.
The existing second-controller cases could not prove this: the boot bus
always carries a keyboard, so their expects were satisfiable by it.

Docs updated with the code: device-manager.md (hello moves the channels,
paged enumerate, delegation as built, reap-and-rebuild in the restart
sequence), device-authority.md (the fourth as-built decision: driver-layer
channels ride the hello; hello is no longer only the liveness handshake).

Full suite: 118/119, the one failure being iommu-fault's fixed 200 ms
fault window under end-of-run host load — 3/3 green standalone, deflake
flagged separately. usb-two-controllers passed inside the full run.
2026-08-09 12:48:33 +01:00
Daniel Samson 8710944a92 establishment: a reporter's death reaps its subtree, and the re-report rebuilds it
P3 of docs/establishment-planes-plan.md — the restart-zombie fix. A class
driver cannot observe its provider's death: an HID driver blocks on
interrupt reports that will simply never come, and storage answers its
callers with refusals forever. Worse, the dead generation's still-used
entries made the matcher's dedupe refuse the respawn when the restarted bus
re-reported — the subtree was a permanent zombie, which is the exact
opposite of the restart-a-driver-live goal the driver model exists for.

pruneChildrenOf now reaps: each pruned child's bound driver is killed and
its entry cleared (the exit notification finds no entry, so the death is
never double-counted; its device returns by the loan rule; its stored
endpoint handle is closed). The re-report then spawns a fresh generation
whose hellos fetch the successor's channel.

The usb-report drill now asserts the subtree WORKS after the restart: the
respawned storage opens its device on the NEW bus instance and reads block
0. Discrimination: against the pre-reap manager the drill fails — no reap
line, no post-restart respawn (the survivors were zombies), verified by a
stash run. Note the scenario boots no input service, so the HID drivers of
BOTH generations exit after their input lookup times out — storage is the
functional proof.
2026-08-09 12:34:13 +01:00
Daniel Samson 1d7850239d establishment: block stops being a name, and enumerate learns to page
P2 of docs/establishment-planes-plan.md. usb-storage serves nameless — one
process per stick cannot share an exclusive bind, and a second stick used to
die silently on -EBUSY before ever helloing. Its one hello now moves both
directions at once: the block-serving endpoint up, its controller channel
down. fat finds its volume through the manager — a new `.consumer` role asks
for the channel of the driver BOUND TO a device (distinct from the device's
reporter), found by enumerating the tree for the mass-storage identity.
fat stays single-volume; the boot-volume-by-content choice is M21.

The conversion immediately caught a live truncation of exactly the audit's
shape: ChildEntry grew to 32 bytes, one enumerate reply holds ~7, and a real
tree carries a dozen ACPI nodes before the first USB child — the storage
entry silently never fit (the protocol comment already said "paging joins
the protocol if a tree ever outgrows one packet"). enumerate is now paged:
Header.target is the start cursor, a short page is the end; device-list's
page-0 read is unchanged.

Grant rows move with the code: the block bind and fat's block open die, fat
gains open device-manager. Gate: 18 cases green including the registry
trio, device-list, and both IOMMU storage variants.
2026-08-09 12:24:25 +01:00
Daniel Samson d603d40b5c establishment: usb-transfer stops being a name
P1 of docs/establishment-planes-plan.md. The bus no longer binds
/protocol/usb-transfer — the bind race made whichever instance came second
unreachable, which on a real three-controller Ryzen meant a mouse no class
driver could reach ("could not open device 50"). Each instance hands its
serving endpoint up in the hello that already delegates its controller, and
class drivers receive their OWN controller's channel from helloForChannel —
routed by the manager's lineage, retried while a provider is mid-restart,
on one manager handle so retries never spend handle-table slots.

usb.open(bus, id) now takes the channel it used to look up; the name rows
leave protocol.csv with the code (bind 67, opens 119/120/122); the
conformance fixture's prose stops claiming the bus binds; and the stale
input-client import leaves the bus with the channel one.

Gate: 19 QEMU cases green (usb family, hubs, both IOMMU variants, fat chain,
boot-from-USB, orderly shutdown, conformance).
2026-08-09 11:48:31 +01:00
Daniel Samson 77fe4d220e establishment: the mechanics — reply capabilities, helloExchange, lineage routing
P0 of docs/establishment-planes-plan.md; no behavior changes yet, nothing
sets the new flag or sends a hello capability.

- service.run gains a reply-capability out-slot (replyWithCapability), the
  registry idiom init already uses, lifted into the harness; null stays the
  untouched common path. Subscribers gains claimArrival() so a provider
  handler can keep a turn capability through the same flag the reserved
  subscribe uses.
- Hello wire struct: the padding byte becomes wants_channel — old callers
  wire-compatibly say 0, and the manager nominates a reply capability ONLY
  when asked, because a capability sent to a caller that never reads one is
  a leaked slot in that caller's table.
- driver.helloExchange: one handshake can hand a serving endpoint up and
  receive the device's provider channel down (usb-storage will need both at
  once). No channel in the reply is retryable, never a verdict.
- The manager stores each instance's serving endpoint on its Driver entry,
  routes consumer hellos by lineage (child -> reporter -> endpoint), replaces
  on re-hello, and closes the stale handle on death - the 32-slot table is
  the bound that makes forgetting this boot-fatal.
2026-08-09 11:39:29 +01:00
Daniel Samson 0d5a7394ef docs: establishment planes — the design and the two-seam plan
The namespace holds protocols, never instances; what multiplies is provider
processes, and their establishment routes through the device manager, which
owns the topology. communication.md gets the model; the plan converts the
usb-transfer and block seams in one flag-day, closes the restart-zombie hole
the scoping found, and pins the three-controller mouse bug as a QEMU case.
2026-08-09 11:26:53 +01:00
Daniel Samson 5930c9653c docs: device-authority as built — spawn carries the device, the loan, confinement rebuilt on return 2026-08-09 10:17:46 +01:00
Daniel Samson 981ff7cd25 Merge the audit fixes: unlocked give paths, restart re-confinement, AMD-Vi store bit 2026-08-09 10:03:42 +01:00
Daniel Samson 5cca580066 kernel: AMD-Vi asked for an interrupt where it meant a store
Two command encodings checked against the specification:

- COMPLETION_WAIT set bit 1 (I, interrupt) instead of bit 0 (S, store), so the
  IOMMU was never asked to write the sentinel, the poll always exhausted its
  spins, and completeAndWait returned without any guarantee the preceding
  invalidation had executed — no invalidation barrier has ever existed, on QEMU
  or on silicon. The in-code claim that "QEMU's amd-iommu does not implement
  the store form" was a misdiagnosis of this bug: with S set, QEMU stores the
  sentinel fine, and the amd-iommu cases now run without the warn line. On real
  hardware, which fetches commands asynchronously, the missing barrier was an
  IOTLB use-after-free window: unmap returned before the invalidation was
  confirmed and the caller freed the frames.

- INVALIDATE_IOMMU_PAGES "invalidate everything" used address bits 51:12
  all-ones; the architected encoding is bits 62:12 all-ones (the spec's literal
  0x7FFF_FFFF_FFFF_F000). Real silicon is free to misread the non-architected
  form as a bounded range.
2026-08-09 09:57:55 +01:00
Daniel Samson 35f43057f4 kernel: the give paths take the lock, and a give confines afresh after a death
Three holes from the real-AMD audit, one shared root: the delegation flag-day
added paths that touch the broker table and the IOMMU records without the big
kernel lock, and a loan-return rule whose re-delegation skipped confinement.

- device_enumerate walked the table with no lock. The table stopped being a
  static array in the bounds track — reserve() regrows it through realloc on
  every boot — so an unlocked reader can be mid-copy out of a slice that
  device_register on another core has already freed and reused, or pair a fresh
  count with a stale slice. Each chunk is now snapshotted under the lock; the
  copy to the user stays outside it.

- system_spawn's give ran entirely unlocked — the comment claiming "the lock
  has not been dropped" was false (spawnProcessSupervised takes and releases it
  internally). The ownership pre-check now only spares creating a doomed child;
  the give itself re-checks, confines and moves in one lock hold, and a give
  that fails after the spawn kills the child rather than leaving it running
  without the hardware it was spawned for.

- A re-delegated device after a driver death was never re-confined. Death tears
  the domain down before the loan returns to the lender, so the next give found
  no active record, reassign no-op'd, and the respawned driver ran the device
  with a V=0 device-table entry and no domain — silently unconfined, the exact
  fail-open the fail-closed claim was built to remove. Both give paths now share
  one body (giveDeviceLocked): check first, confine afresh when no record is
  active — refusing with ECONFINE like the claim — and move last, when nothing
  can fail.

The iommu test drives the death-and-respawn sequence directly; with the old
reassign-only behaviour its two confinement checks fail, with this change the
suite is 118/118.
2026-08-09 09:57:55 +01:00
Daniel Samson 72807c20e4 Merge the bounds track: the numbers we invented are gone
An AMD Ryzen booted to a working compositor with no USB and no storage. The
cause was maximum_children_per_parent = 16 — a number nobody had justified,
in a kernel where 235 compile-time ceilings turned out to exist, 139 of them
on quantities the machine or a file decides rather than us, and 171 silent
when reached.

Both invented ceilings are deleted rather than raised. The device table
grows, because no specification bounds how many devices a machine has, and a
runaway is bounded per-registrar so it costs only the driver that caused it.

Device authority became real rather than advisory. Matching was always
policy, but claiming was first-come, so any process could take any device
nobody happened to be holding. Now every driver receives its hardware in the
spawn that creates it — it never runs without it — a grant is a loan that
returns to its lender when the borrower dies, and nothing firmware-discovered
is left unheld except the framebuffer, which the compositor owns.

Along the way: the AMD boot fix itself (STAR's SYSRET base carries the RPL,
which Intel forgives and AMD does not); one errno space with every refusal
naming the rule that refused it; the IOMMU confinement moving with its
device, and refusing rather than silently succeeding at the edge of its
table; and PCI apertures derived without copying the firmware memory map
into a fixed array, which had let a large map turn occupied RAM into a
window a driver could map.

A gate now stands behind the audit: zig build bounds refuses a new ceiling
that will not say what it counts, who decides its size, what happens when it
is reached, and how anyone finds out. The 269 that predate the rule are
allowlisted and that list can only shrink.

Suite 114 -> 118, green at every step.

Docs: fixed-bounds-audit.md, os-development/bounds.md, bounds-track-plan.md,
os-development/device-authority.md.
2026-08-08 23:24:25 +01:00
Daniel Samson 0eb2420690 device-manager: delete the delegated-set scaffolding
The name list and its predicate existed so drivers could move to delegation
one at a time with the suite green throughout. Every driver is delegated
now, so the manager simply hands over whatever device a driver was assigned.

Deleting it caught a real consequence: crash-test finally got delegated too,
and it was still claiming its device — so it got AlreadyClaimed because it
already held it, exited, and the restart drill had nothing to restart. Its
own comment named what the case was really checking: "the respawn only
reaches this line because the kernel released the previous instance's claim
at death". That property still holds, by a different mechanism — the device
reverts to the manager on death and is handed to the replacement, which is
the same guarantee without the race it used to rely on.

All four delegation paths verified: the xHCI controller, the PCI bridge, the
PS/2 two-node singleton, and virtio-gpu's restart re-attach.

Run 3 complete. Suite 118/118.
2026-08-08 23:01:29 +01:00
Daniel Samson df9c1ed827 device-manager: hold the seeded hardware so none is left lying around
A device nobody holds can be claimed by anyone, so the manager now takes
every firmware-discovered device that carries mappable resources, whether or
not a driver wants it. The real gap was the HPET: an MMIO window, an IRQ, no
user-space driver, and there for the taking. Held by the manager it is
inert; unheld it was a way into physical memory.

Two deliberate exclusions. The loader's framebuffer, which the compositor
claims and which the manager must not take because it starts first. And
anything with no resources, which grants nothing worth holding.

Scope is the boot snapshot. A device reported later and matched to no driver
stays claimable — pci-cap-test and iommu-fault-test both reach an unmatched
NIC that way, so narrowing it is a separate change with those fixtures in
scope. Recorded in the plan rather than left implied.

The attacker fixture gains the assertion deferred since D2: after the system
settles, nothing with resources may be taken.

That assertion defeated itself twice before it worked, and both failures are
worth remembering. First it swept at 0.029 while the manager did not bind
its protocol until 0.047, so it reported a hole that closed a millisecond
later. The retry loop that "fixed" that was worse: the first pass TAKES the
device, so the second finds it unavailable because this process now holds
it, and concludes all is well — it passed with the manager's claiming
removed entirely. It now settles once and sweeps once, and fails when the
claiming is removed.

Suite 118/118.
2026-08-08 22:42:42 +01:00
Daniel Samson ba195fa0a2 kernel: claim refuses delegated hardware — and E2 had already closed the hole
The rule as planned: a device that was given to someone may be handed on,
never taken. Implemented, and honest about what it is worth.

Writing the test showed the plan had the wrong step doing the work. A
delegated device is HELD, so an attempt to take it is refused as
AlreadyClaimed before the giver is ever consulted; and once a borrower's
death returns the device to its lender — or clears both when the lender is
gone — there is no state where a device is unheld and still on loan. The
window a stranger could have used stops existing at E2. This check is
unreachable.

It stays anyway: one comparison, failing closed, guarding any future path
that frees a device without clearing its giver, which is exactly the hole
this run closed. The comment says it is unreachable rather than implying a
protection it does not provide.

The attacker fixture does not gain the assertion that was deferred to this
step, and its header records why: there is no refusal for it to observe, and
on a bare boot with no device manager nothing is delegated at all, so the
assertion had nothing to bite on. It failed loudly on its first run rather
than passing quietly, which is the only reason this was noticed.

It also leaves the loader's framebuffer alone without naming it: nobody
delegates the framebuffer, so it has no giver, so the display service claims
it exactly as before.

Suite 118/118.
2026-08-08 22:31:04 +01:00
Daniel Samson 1a1d92cba9 kernel: a grant is a loan — a dead borrower returns the device to its lender
When a driver dies, a device it was *given* now goes back to whoever lent
it, rather than to nobody. The device manager gets its hardware back the
instant a driver dies and hands it to the replacement, with no window in
between.

That window was real: the kernel released the claim to no one and the
manager re-claimed first-come, so every driver restart reopened the hole
this run is closing. It also becomes load-bearing at the next step — once
claim refuses a device that has a giver, releasing to nobody would strand a
dead driver's hardware permanently, because nobody could ever take it again.

A dead lender is no lender: the claim and the giver clear together, so a
device is never owed to a ghost. A device nobody lent is released outright,
exactly as before.

The broker cannot see the task table, so liveness arrives through the same
hook idiom the scheduler already uses. Null means assume dead, so a kernel
built without the hook frees claims rather than handing them to a ghost.

A stale binary nearly passed as proof for the third time this session: the
first discrimination patch left `alive` unused, the build failed with three
errors, and the old binary reported every assertion passing. Checking the
build before reading results is what caught it.

Suite 118/118.
2026-08-08 22:21:25 +01:00
Daniel Samson 4ca57fc37e kernel: record who gave each device away
One field, and the rest of the run follows from it. A device that was given
to someone is delegated hardware: it may be handed on, never taken, and when
its holder dies it goes back to whoever lent it instead of becoming free for
anyone to grab.

It also settles the framebuffer without mentioning it. Nobody delegates the
loader's framebuffer, so it has no giver, so the display service claims it
exactly as it always has — no exemption and no reference to display anywhere
in the rule.

No behaviour changes here; the field is recorded and read by nothing yet.

The test found a real bug on its first run, before the discrimination check.
The sentinel for "nobody gave this" was 0 — and task 0 is a real task, the
kernel's own, so a device given away by task 0 read back as belonging to
nobody. Both giver and registrar are optionals now. The second was a latent
bug from D9: the per-registrar allowance would have miscounted every device
task 0 registered.

Suite 118/118.
2026-08-08 22:12:01 +01:00
Daniel Samson ca1126537d docs: Run 3 — close the claiming hole, six steps, no open questions
One field settles both outstanding questions. The kernel records who gave
each device. device_claim then refuses anything that has a giver, and on
death a device reverts to its giver rather than to nobody.

The framebuffer needs no exemption: nobody delegates it, so it has no giver,
so the display service claims it exactly as today. The rule never mentions
display.

And restart stops racing. Today a dying driver releases its claim to nobody
and the manager re-claims first-come, so every restart reopens the hole this
run closes; a loan that reverts to its lender removes the window entirely.

The zero-resource inventory question is dropped from the plan rather than
carried as a blocker. It is real but nothing depends on it.
2026-08-08 22:01:49 +01:00
Daniel Samson 337b981c07 docs: reorder the Run 2 table to the plan order and note the executed sequence 2026-08-08 21:58:53 +01:00
Daniel Samson b7d97ebb5d acpi: discovery is handed its node like every other driver
The last claimant. The kernel seeds the acpi-tables node, so it sits in the
same boot snapshot the manager already scans to find the PCI host bridge —
there was never a bootstrap problem, only a lookup nobody had written. The
manager claims it and names it in the spawn; the service stops claiming.

Every driver in the system now receives its hardware rather than taking it.

Two failures on the way, both mine. addDriver puts the device id in argv[1],
and the acpi service read argv[1] as a self-verify device-count floor — so
handed device 7 it decided it was in test mode, printed "acpi-parse: ok",
and never reported a device. The test argument is now floor:N, which a bare
id cannot be mistaken for.

And acpi-parse spawns the service directly rather than through the manager,
so nothing handed it the node. That test now claims and transfers it exactly
as the manager does, which is the right shape: the test plays the manager's
role instead of the service reaching for hardware.

device_claim now has two callers left: the manager, which is the acquirer
and should have it, and the display service's GOP path. That is recorded as
question 10 — the framebuffer is not a device, so the answer is likely that
it leaves the device table rather than being exempted from its rules.

Suite 118/118.
2026-08-08 21:54:45 +01:00
Daniel Samson 6b3a381626 ps2: one instance, every node the machine has
The 8042 is a single controller described by two ACPI nodes — PNP0303
carries the 0x60/0x64 ports, PNP0F13 is the mouse — so it cannot be split
across two processes without them fighting over the same registers. That is
why ps2-bus is a singleton, and why it used to find and claim both nodes
itself.

The manager now gives it every matching node instead. The keyboard node
rides the spawn, because it holds the ports and is needed immediately; the
mouse node is transferred to the already-running instance. Late arrival is
safe here and the ordering is natural rather than lucky: the mouse is not
touched until after the controller handshakes and identify. Measured, the
handover lands at 0.336 and the driver reaches the mouse at 0.456.

Because the count is however many matched, a machine with no PS/2 ports or
only one works without a special case — which matters, since the bus is
mostly emulated now and machines vary.

ps2-bus claims nothing. irq_bind on the mouse node is the proof it holds it:
that call is ownership-gated, so a failure means the handover did not land
rather than a hardware fault, and the log says so.

acpi-ps2 asserts both delegations with the spawned device backreferenced, so
the node that rides the spawn must be the one the driver was spawned for.
Disabling the second delegation fails it.

Two things worth recording. The first discrimination patch was not valid Zig,
so nothing ran and a stale binary reported a pass — checked the build before
believing it. And with the second delegation disabled, acpi-ps2 fails while
input still passes: the mouse works without its IRQ binding, so exactly one
case covers that path.

Suite 118/118.
2026-08-08 21:33:35 +01:00
Daniel Samson 7d8aa51234 kernel: maximum_children_per_parent is gone
The second invented ceiling. It was written to stop a driver looping
device_register and exhausting a shared table — but there is no shared table
to exhaust any more, and each registrar already has its own allowance, so a
runaway costs only itself.

It never bounded a determined caller in the first place: 16 children per
parent, and nothing stopped it claiming more parents. What it reliably did
was refuse a real PCI bus with more than 16 functions, which is how an AMD
Ryzen booted with a working display, no USB and no storage.

The constant, its check, and the now-unused childCount all go. TooManyChildren
survives with one meaning instead of two: the caller is at its per-registrar
allowance.

This was unblocked from the moment D9 landed. The plan said so — "once the
quota exists the per-parent cap is redundant whether or not D6 has landed" —
in the same edit that left the step tagged "blocked on D6". Three iterations
were then spent re-reading that tag instead of the sentence beside it.

The containment test now asserts 64 children under one parent, four times
the old ceiling; restoring the cap fails it.

Suite 118/118.
2026-08-08 21:12:20 +01:00
Daniel Samson 3ae541214f iommu: assert directly that a confinement moves with its device
reassign was added at D4 to fix a regression and has been proven only
indirectly since — three IOMMU+USB cases going green. That covered the
visible symptom (a driver's DMA rings unbound) and neither of the latent
ones: the confinement still naming the giver, so the giver's death would
tear down a domain a live driver was using, and the receiver's death would
leave one behind. Those are now asserted.

confinementOwner exposes the record's owner so the suite can see it. The
sequence is the delegation in miniature: unconfined, confine as this task,
reassign to another, confirm the new holder owns it and the old one does
not, then kill the new holder and confirm the domain goes with it.

Two attempts at this test could not have failed. The first found no PCI
function to confine — pciAddressOf needs a pci_device entry and this case
runs no pci-bus — so every assertion skipped silently while the case stayed
green. It now synthesizes a function the way pci-bus does, a 4 KiB config
window inside the bridge's ECAM, and asserts that precondition explicitly so
a skip is a failure.

Verified to discriminate: making reassign a no-op flips three assertions,
including the domain surviving its holder's death.

Suite 118/118.
2026-08-08 19:57:36 +01:00
Daniel Samson 2ebfccc8ed virtio-gpu: the scanout device arrives with the spawn
Third driver converted. It no longer claims the id from argv[1] — the
manager holds the device and names it in the call that creates the process,
so it is held before the driver's first instruction.

display-reattach is the case that matters here: it kills the driver and
watches the compositor re-attach to the fresh scanout. It passes, so the
restart path survives the fused grant — the manager re-takes the device when
the driver dies and hands it to the replacement.

ps2-bus and discovery are NOT converted, and the reason is recorded as open
question 9 rather than worked around. Both need a device nobody assigned
them. ps2-bus ignores its argv[1] entirely: it finds the controller by
walking the table for PNP0303, then claims a second device, the PNP0F13
mouse node, which it also finds itself — so it holds two devices and was
assigned at most one, while system_spawn carries one. discovery claims the
acpi-tables node it locates itself, because it is what produces the device
tree and there is nothing to assign at that point.

One thing worth checking before designing an answer: devices.csv maps both
PS/2 hardware ids to ps2-bus, so the manager may already be spawning two
instances where the driver expects one. If so the fix is smaller than it
looks.

D6 stays blocked — closing device_claim with these two still depending on it
would stop the machine booting.

Suite 118/118.
2026-08-08 19:48:00 +01:00
Daniel Samson f23f073624 kernel: the device rides system_spawn, so a driver never runs without it
Delegation moves out of onHello and into the spawn itself. The manager holds
the hardware and names it in the call that creates the driver; the kernel
checks the device is the caller's to give, then hands it over as part of
making the child.

The reason is the window. A transfer after spawning always leaves an
interval in which the child is running and does not yet hold its device. It
would close on QEMU every time and open occasionally on a machine with
different core counts and timing — the exact failure shape this track exists
to delete, and not one worth introducing while removing the others. Fused
into the spawn there is no interval: the child does not exist until it holds
the device.

Ownership is checked BEFORE the child is created, so a refusal leaves
nothing running rather than a driver without the hardware it was spawned
for. The IOMMU confinement moves with the device, as it does on the transfer
path. systemCall6 is added for the sixth argument; r9 was free, and abi
gains a no_device sentinel matching the protocol's.

No driver had to change to receive a device, which is what makes this
better than requiring every driver to hello: ps2-bus keeps its legacy
status, and discovery — which has no assignment at all, since it is what
produces the device tree — is unaffected.

The attacker fixture now tries the spawn as a back door: name someone else's
device, and both the spawn and any child must be refused. Verifying that
assertion exposed a bug in the fixture itself. The kernel case's pass marker
was "device-authority: ok", which matches the FIRST per-assertion line, so
its wait loop exited before any failure was printed — the case would have
passed with failures in it, and had been able to since D2. The verdict lines
now carry a distinct VERDICT prefix, and with the ownership check removed
the case genuinely fails. A green test that cannot go red is worse than no
test.

Suite 118/118.
2026-08-08 19:39:32 +01:00
Daniel Samson 637bf2e0b1 docs: correct a stale ordering note — D9 landed without D7 2026-08-08 19:26:48 +01:00
Daniel Samson cb8d1e2e51 docs: the grant rides system_spawn, atomically
Questions 6 and 7 both dissolved on inspection, so what was left was only
where the grant is delivered. Three candidates: transfer after spawn, every
driver hellos, or fuse the device into system_spawn.

Take the third. The manager cannot transfer before the child exists, so a
separate transfer always leaves a window in which the child is running and
does not yet hold its device. That window would close on QEMU every time and
open occasionally on a machine with different timing — the exact failure
shape this track exists to delete, and not worth introducing while removing
the others. Fusing it into the spawn removes the window by construction: the
child does not exist until it holds the device. It adds no knowledge to the
kernel, only atomicity — the same rule, you may give away what you hold,
fused with the call that creates the recipient. system_spawn uses five of
six argument registers, and no_device is already the sentinel.

Making every driver hello is a good idea on its own merits — uniform
liveness, the deadline applied to all rather than some, and the
speaks_protocol two-class split leaving the manager, since a wedged ps2-bus
is invisible to its supervisor today. Kept as its own step so grant delivery
does not force it.

Order is now D0 -> D5 -> D6 -> D8, which deletes maximum_children_per_parent.
Only D7 remains blocked, on question 8, and it is needed for neither ceiling.
2026-08-08 19:26:32 +01:00
Daniel Samson 8b628a4a7d docs: there is no virtio-gpu standalone bring-up to lose
Question 7 read the comment "Best-effort: standalone bring-up has no
manager" as a boot path that delegation would delete. It is not one.
virtio-gpu's main requires argv[1] and exits without it, and the only source
of that argument is the device manager: ACPI, then pci-bus reports the
function, then devices.csv matches 1AF4:1050, then the manager spawns the
driver with the id. Without a manager the driver prints and returns, and
never reaches the hello at all.

The comment is about resilience, not boot: the hello is best-effort so a
driver whose manager has died keeps serving, which device-manager.md states
outright.

So the question dissolves. The residual is one narrow window — the manager
spawns a driver and dies before transferring — where today the driver could
still claim because claiming is free-for-all, and after D6 it would exit for
the restarted manager to respawn. That is the better behaviour: a driver
holding hardware nobody assigned it is exactly what D6 exists to stop.

Taken with the transfer-at-spawn delivery point, D5, D6 and D8 are
unblocked. D7 remains blocked on question 8, and is not needed for either
ceiling.
2026-08-08 19:22:22 +01:00
Daniel Samson a5840789dd docs: the acpi service is discovery, not a driver awaiting an assignment
Question 6 lumped the acpi service in with ps2-bus as "a claimant that does
not hello". That was wrong about what it is. The manager starts it as
addDriver("discovery", no_device, false): the discovery service, one per
firmware, with no device assignment at all, which finds and claims the
acpi-tables node itself because it is the thing that produces the device
tree. The manager cannot hand it a device — at that point there is nothing
to match against.

So its question is not whether it should hello. It is whether the bootstrap
is exempt from D6, or whether the manager claims the acpi-tables node and
passes it on.

Recorded alongside it: a delivery point that needs no hello is already
implied by the code, since spawnSupervised returns the child's pid and the
manager could transfer immediately after spawn. If that is acceptable,
question 6 largely dissolves — ps2-bus would not need to leave "legacy"
either. The cost is ordering: the child may reach for the device before the
transfer lands, where hello guarantees it cannot because the child is the
one asking. That trade is the real decision, and it is now written down as
such.
2026-08-08 19:14:54 +01:00
Daniel Samson f7151ed577 kernel: the device table has no ceiling; a runaway is charged to whoever caused it
maximum_devices = 64 is gone. It was a guess about someone else's computer,
and because it was shared, one driver's enumeration starved every other —
which is how an AMD Ryzen booted with a working display, no USB and no
storage. The table now grows from the kernel heap. It was always built after
heap.init; nothing ever prevented this except it having been written static
first.

What replaces it is an allowance charged to the registrar, so a driver
looping device_register exhausts its own and every other driver carries on.
It is declared as what it is — a runaway detector, NOT a security boundary.
A quota generous enough never to bite a real machine is still generous
enough to be unpleasant, and it is not trying to be the defence; delegation
is. What this catches is a legitimate driver in a loop, early, attributably,
and without collateral. Reaching 4096 is a bug report, not a tuning request.

The initial block is 8, deliberately small. Sizing it for a typical machine
would mean the growth path never ran on the hardware we test on and only
woke up on someone else's larger machine — the exact failure shape this
track exists to stop. At 8 it grows several times every boot; disabling
growth now fails the suite with the HPET not fitting, which is the Ryzen
failure in miniature.

The comptime coupling assert added earlier fired, and was right to. confined
(one slot per device id) and domains (the IOMMU's own translation pool) were
sized by the same constant only because device ids happened to stop at 64
too. Two unrelated quantities: confined now grows with the device table,
while maximum_domains stays as the hardware's number — both VT-d and AMD-Vi
report how many domains they support, and reading it is phase 4. The assert
existed for exactly this and did its job.

Suite 118/118.
2026-08-08 18:40:20 +01:00
Daniel Samson 5492607a61 docs: D7 blocked, and D8 reordered after D9
D7 would remove zero-resource devices from the kernel. It cannot proceed
because nothing else mints their ids. A USB interface registers with
resource_count = 0, and the id device_register hands back is load-bearing in
three places: the child_added packet's target, the class driver's argv[1],
and the device_token of the usb-transfer WIRE protocol — so the id space is
visible on the wire, not merely internal. usb-xhci-bus records the fourth
constraint itself: the kernel's idempotency is what makes the same port and
interface map back to the same id across a bus restart, which is what stops
a respawned bus spawning duplicate class drivers.

Moving that out means answering who mints the id, how it survives a bus
restart, how it survives a manager restart, and whether device_token changes
meaning. A design step, not a mechanical one.

D8 is reordered to run after D9, correcting the original sequencing. D8's
justification was that the authorisation the per-parent cap stood in for now
exists — but D6 is blocked, so it does not, and deleting the shared cap now
would reopen the exhaustion hole it was written for. D9's per-holder quota
closes that hole independently of authorisation, and closes it better: a
rogue exhausts its own allowance instead of the table everyone shares. Once
the quota exists the per-parent cap is redundant either way.

D9 also no longer depends on D7. Its rationale was that zero-resource
children are the case that sidesteps containment — true, but a per-holder
quota bounds them as well as anything else, because it counts entries per
holder rather than per parent.
2026-08-08 18:26:37 +01:00
Daniel Samson 81dd1e9318 pci: the host bridge arrives by delegation too
pci-bus joins usb-xhci-bus in receiving its device from the manager rather
than claiming the id it found in argv[1]. Its hello moves ahead of the ECAM
mapping, since that is where the bridge now arrives, and its hello was
already mandatory so nothing about its failure behaviour changes.

isDelegated compared whole strings, which silently missed this driver: the
manager records the boot-snapshot match as the bare "pci-bus" and a
devices.csv match as the full "/system/drivers/pci-bus". pci-bus was then
neither claiming nor delegated and died on "ECAM mmio_map failed". It now
matches on the last path component. Reintroducing the whole-string compare
breaks usb-xhci-bus instead of pci-bus — the two spellings swap which driver
loses — so usb-hid is the case that catches it, not pci-scan.

pci-scan asserts the delegation on the initial bring-up AND after the
restart drill, with the device id backreferenced so both must name the same
device. That is what proves the manager re-takes a device when its driver
dies and hands it to the replacement, which is the property the whole
supervision design rests on.

The remaining three claimants are NOT converted, and the plan records why
rather than working around it. ps2-bus and the acpi service never hello at
all, which device-manager.md states deliberately ("legacy drivers ... not
yet required to hello"), so delegating to them means either promoting them
out of legacy or giving the grant a delivery point that is not hello.
virtio-gpu hellos best-effort by design — "standalone bring-up has no
manager" — and delegation would make it mandatory. Both are decisions, not
mechanical steps.

Consequence: D6 is blocked, because device_claim cannot be closed off while
three claimants still depend on it. D7-D9 are unaffected — they concern what
the kernel stores and how its table is sized.

Suite 118/118.
2026-08-08 18:25:16 +01:00
Daniel Samson a2d6056772 usb: the xHCI controller arrives by delegation, not by claiming
The first driver to stop claiming its own hardware. The device manager holds
the controller and transfers it in the hello reply, so its matching becomes
authoritative instead of advisory — until now the driver claimed the id it
found in argv[1], and any process could have claimed the same integer first.

The manager claims before it spawns, so there is no window in which anything
else could take the device, and transfers in onHello using invocation.sender
— the kernel-stamped task id, which cannot be forged by the caller. hello is
synchronous, so the transfer has completed before the reply lands: no gap
between being told yes and holding the thing.

usb-xhci-bus's hello moves from after controller bring-up to before anything
that needs the device, which is the bring-up reorder the design predicted.
It is the first member of an explicit delegated set, so every unconverted
driver keeps claiming exactly as before and the suite stays green; the set
and device_claim both go at D6. D3 and D4 could not be separated and the
plan records why: the moment the manager claims, any driver still calling
device_claim is refused, and D3 applied to nothing changes no behaviour and
cannot be tested.

This step introduced a regression and the incremental conversion is what
caught it. confineDevice runs inside systemDeviceClaim, so a device arriving
by transfer was never confined for its new owner. Three IOMMU+USB cases
failed on the driver's DMA rings going unbound, and two worse consequences
were latent: a manager death would have torn down a domain a live driver was
using, and a driver death would have leaked one. iommu.reassign now moves
the confinement with the device, keeping the domain and its attachment
intact so it never translates through nothing. Converting all five drivers
at once would have produced the same three failures with five suspects.

A log line of mine claimed "holding controller device N" before anything
verified it — it printed even in the failure case, where the driver held
nothing. Reworded to state only what is known there: where the registers
are.

usb-hid asserts the delegation with the device id backreferenced, so the id
delegated and the id the driver ends up with must match. Emptying the
delegated set fails it with "hello acknowledged" then "mmio_map failed".

usb-hub failed once in a full run and has passed six times since (four
isolated, two full) — recorded in the plan as a suspected instance of the
known intermittent AP fault, not dismissed, since this step did shift boot
timing.

Suite 118/118.
2026-08-08 17:55:59 +01:00
Daniel Samson 33376f24ab test: the attacker the device suite never had
The audit's sharpest finding was structural, not a bug: a fully green suite
had hidden six real defects because it contains no attacker. Every device
case asserts that a driver handed its own hardware can drive it. None asked
what a process handed NOTHING can do.

device-authority-test is that process. It is spawned with no device and
asserts what it therefore cannot do: it cannot give away a device another
task holds, nor a free one, because the kernel's rule is that you may give
away what you hold and the device's state is irrelevant to a process holding
nothing. Asserted across every device the machine actually has, so it cannot
pass by accident of which one happened to be free at boot — six on QEMU,
none of them its.

A positive control runs first. device_enumerate works from this process, so
the refusals below it are decisions rather than a syscall path that is
simply broken here; without it, "everything failed" would read identically
to "the assertions are meaningless". A nonexistent device is refused as
NoSuchDevice rather than NotHeld, because a refusal that cannot name its own
rule is what cost a debugging session on the Ryzen.

What it deliberately does not assert, and says so in its header:
device_claim is still first-come-first-served at this point in the run. That
is the hole D6 closes, and the claim half of the invariant joins this
fixture then. Asserting it now would be writing a test that documents the
bug.

Verified to discriminate: removing the holder check flips "every transfer by
a non-holder is refused" while the positive control keeps passing.

Suite 117 -> 118.
2026-08-08 17:23:17 +01:00
Daniel Samson 3111c7c5e6 kernel: device_transfer — you may give away what you hold
The mechanism behind delegation, which device-manager.md named as the step
after hello: the device manager claims what discovery seeded and hands each
device to the driver it matched, so assignment stops being
first-come-first-served.

It is a MOVE, not a copy. A claim is exclusive (driver-model.md, invariant
1), so the giver stops holding the device the instant the receiver starts.
That is why this is a new syscall rather than the M13 capability path, where
a passed handle is shared refcounted — exclusivity cannot be expressed that
way.

The kernel's whole rule is that you may give away what you hold. It has no
notion of which task is the device manager and deliberately gains none: a
binary name inside the kernel is not something that cannot safely live in
user space. A recipient that does not exist is refused, because a device
moved to nobody would be unreachable for the rest of the boot — nothing
un-holds a device but task death.

Three errnos, each naming its own rule: ENODEV no such device, EPERM you do
not hold it, ESRCH no such recipient.

Nothing uses it yet. The five claimants move across one at a time in D4-D5,
so the suite stays green throughout and a regression names the driver that
caused it.

Ten assertions, verified to discriminate: removing the ownership check flips
four of them, including the giveaway that an illegal transfer then blocks
the legitimate claim behind it.

Suite 116 -> 117.
2026-08-08 17:11:59 +01:00
Daniel Samson 547d0ec46b docs: device authority — the how, and the run that deletes the ceilings
device-authority.md is rewritten as an implementation design rather than a
rival to device-manager.md. The what was already settled there in 2026-07:
structure in the manager, authority in the kernel, and delegation as the
step after hello. This is the how, plus the two decisions that paragraph
leaves open.

Decision 1: the manager claims, it is not granted. device-manager.md says
"claims (or is granted)"; claiming wins because the manager runs before any
driver exists and takes the seeded devices unopposed, leaving nothing unheld
to race for. One new call, device_transfer(device_id, task_id), checks only
that the caller holds the device — no names in the kernel, no attestation.
The alternative put a binary path inside the kernel, and the kernel should
hold only what cannot safely live in user space. The residual is stated
rather than hidden: authority rests on the manager claiming first, which
init.csv makes an operator-visible ordering rather than an attacker-
controlled one, and the enforced version arrives with the spawn capability
drivers.md already names as missing.

Decision 2: the kernel stops holding inventory. It reads three things out of
a descriptor — physical ranges, interrupt numbers, one PCI BDF — and stores
the rest only so device_enumerate can hand it back. Devices with no
resources leave the kernel entirely: a USB device conveys no mapping
authority, so there is nothing to enforce. That is also the case which
sidesteps containment, and therefore the reason a shared cap existed.

Decision 3: no shared ceiling. The table becomes dynamic — it is built after
heap.init, so nothing ever prevented it — and the two invented numbers go. A
per-holder quota replaces them, because dynamic storage with no bound moves
the ceiling to the kernel heap, which is shared and fatal rather than
partial. A bound charged to whoever caused it is isolation.

Two earlier drafts of this document are gone: one gave init the root grants,
the other proposed extracting a firmware-framebuffer driver. Both were wrong
and both are recorded as wrong in the run plan's settled list — the
framebuffer is not a device, it is where pixels go until a real display
driver announces itself.

Run 2 is nine steps, ordered so the suite stays green throughout: build and
prove the transfer mechanism, move the five claimants across one at a time,
then the flag day, then the inventory, then the ceilings.
2026-08-08 17:01:25 +01:00
Daniel Samson 5ad42ceac3 docs: only drivers hold devices; services speak protocols
The design still had the display service receiving a device grant, which
keeps the wrong layering and just moves who hands it over. Drivers talk
hardware. Services talk to no hardware at all — they receive device events
and send data and commands over a protocol, which is the OS abstraction
between them.

So the answer to "which services need device grants" is none, and the design
collapses: every holder of a device is a driver, and every driver is spawned
by the device manager, which is what grants it. No exceptions to
accommodate.

display already shows both halves. Its VirtioGpu backend speaks
scanout-protocol over an IPC handle and touches no device — the driver holds
the hardware, the service speaks to it, and it works today. Its Gop backend
calls device.enumerate, device.claim and device.mmioMap: the service
reaching into hardware itself, because the firmware framebuffer has no
driver to talk to. That is the only such case in the tree; every other
claimant is a device-manager child spawned with its device id.

A firmware-framebuffer driver is therefore a prerequisite of this phase
rather than a consequence. It is small — hold the display node, map the
framebuffer, serve the same scanout-protocol virtio-gpu already serves — and
the compositor needs no new path, since not caring which backend is behind
it is what it was designed for.

Two earlier drafts are recorded as wrong in the document: display asking the
device manager for a grant, and before that init minting grants because init
starts display. Both accommodated an exception instead of removing it.
2026-08-08 16:40:37 +01:00
Daniel Samson 8e388e048a docs: one line still had init minting the root grants 2026-08-08 16:35:54 +01:00
Daniel Samson ef793d1320 docs: the device manager is the root of device authority, not init
The design had init minting device grants and handing them on, because init
is what starts display and display claims the framebuffer. That was the
wrong shape. init has nothing to do with devices: it is the first process
and it starts the rest of the system. The device manager owns hardware.

So the kernel mints the root grants to the device manager, and display asks
the manager for its framebuffer like any other driver. The exception that
drove the earlier draft disappears instead of being accommodated — one
authority for hardware, not two.

The kernel recognises the manager by the chain attestation the security
track already settled on: the binary path it stamped itself, AND a
supervisor of PID 1. Path alone is forgeable, because system_spawn is
deliberately ungated and any process may spawn any bundled binary — but a
rogue copy's supervisor is the rogue, and PID 1 is the kernel's own first
process.

Costs restated for the corrected model. display gains a boot-order
dependency on the manager, mitigated by its existing ability to attach a
backend late. The kernel gains one piece of knowledge about one binary,
which is the minimum: authority has to enter somewhere, and the
alternatives are a file parser in the kernel or first-to-ask, which is the
hole again.
2026-08-08 16:35:32 +01:00
Daniel Samson 139c4f624f docs: mechanism, policy and configuration are three things
The phase 2 design called devices.csv "policy". It is not. The CSV is
configuration — declarative data an operator edits. The policy is the
component that decides using it: the device manager matching a device to a
driver, init reading protocol.csv and granting a binding. The kernel holds
mechanism, the check that a grant exists before a mapping is made.

Corrected where the document conflated them, and the three are now tabulated
so the rest of the design can lean on the distinction.

It also sharpens the open question. It was "manifest or not"; it is really
whether the grant list should be configuration from the start, or whether
init should hand the device manager the root grants and let it match by the
devices.csv it already reads. A device-grant file adds a second place an
operator must keep correct, and earns itself only when something needs to
differ from "the manager gets the hardware" — holding a device back for a
test or a bare-metal driver, say.
2026-08-08 16:31:50 +01:00
Daniel Samson 3b24b541b0 docs: phase 2 design — you hold what you were given
device_claim checks that a device exists and is free. That is all. Any
process may claim any unclaimed device, and a claim is what gates mmio_map
and irq_bind — a licence to map physical memory and take interrupts. The
device manager's matching is real but advisory: it spawns a driver with the
device id in argv[1] and nothing binds that decision to the kernel's grant.

maximum_children_per_parent is the visible cost. It exists because a driver
that claimed one device could loop device_register under it, and it is a
poor defence — an attacker burns 16 slots, claims another device, burns 16
more — while reliably refusing a legitimate PCI bus with more than 16
functions. Closing the hole is what retires the constant.

The principles decide the split: matching is policy and stays in the device
manager; enforcing that a driver holds only what it was given is security
and stays in the kernel, and is the whole of what the kernel needs.

The mechanism is decided by an awkward fact. Five of six claimants are
device-manager children spawned with their device id. display is not — init
spawns it, and it finds its framebuffer by enumerating for a display-class
node and claiming whatever it finds. So "record the device named at spawn"
closes the hole for five and breaks the sixth, and the sixth is not an
oddity to special-case: it shows authority must be delegable rather than
welded to the moment of spawn.

So: a device grant is a capability, minted by the kernel to init for the
devices firmware discovery found, delegated by init to the device manager
and to display, and passed by the manager to each driver it spawns. The
cap-passing path already exists and already carries shared memory and DMA
regions. init is already the grantor for /protocol, and protocol.csv already
records init granting the device manager its binding.

Costs named rather than buried: five drivers must hello before claiming
(pci-bus claims first today), and init grows a device role on top of the
protocol registry. A device-grant manifest mirroring protocol.csv would be
the natural symmetry and is deliberately not proposed yet.
2026-08-08 12:58:19 +01:00
Daniel Samson 5d55217212 usb: a slot the controller granted is always handed back
Both device-setup paths issued a successful Enable Slot and then returned
null if allocateDevice failed, without disabling it. A slot the driver
forgets is one the controller never reissues, so each attempt lost one
permanently for the boot. The hub path did it with no log line at all.

Both now release the slot through a shared disableSlot, extracted from
tearDownDevice, and the hub path warns like the root-port path does.

tearDownDevice also now frees the interface list. That allocation arrived
with the previous commit, so an unplug would have leaked it — found while
reading the teardown path for this fix rather than by a test.

No regression test, and it is recorded as open question 5 rather than
implied. After the slot count became the controller's own figure, reaching
this path needs more devices than the controller has slots: QEMU offers four
against sixty-four. What was verified is that the new path RUNS correctly —
pinning tracking to 2 with four devices attached produced "port 6 setup: no
free device slot", the first two devices enumerated normally, and no Disable
Slot error or timeout appeared, which is how disableSlot reports failure.

Suite 116/116.
2026-08-08 12:16:42 +01:00
Daniel Samson 729b40ece7 usb: a device has as many interfaces as it declares
max_interfaces was 4. A composite device — a headset, a webcam with audio, a
dock, a multifunction printer — routinely has more, and the fifth did not
merely go missing. parseConfiguration's cap branch had no `else`, so when the
count was reached `current` kept pointing at interface 3 and the fifth
interface's endpoint descriptors were appended to interface 3's array. A
class driver bound to interface 3 could then be handed an endpoint belonging
to something else entirely, and subscribe or bulk-transfer on it. The
alternate-setting arm one line above cleared `current` correctly, which is
what the cap branch should have done.

Interfaces are now counted from the block in a first pass and allocated to
exactly that number, so the ceiling is bNumInterfaces' u8 — the USB
specification's. The missing `else` is added too, though after this the bug
is unreachable by construction: interface_count cannot reach interfaces.len
mid-parse when the list was sized from the same walk.

max_configured_endpoints was max_interfaces * max_endpoints_per_interface =
16, a derived guess that moved whenever either input moved. It is now 31,
which is the xHCI specification's own limit: a Device Context holds a slot
context plus at most 31 endpoint contexts, because the Context Entries field
addressing them is 5 bits.

max_endpoints_per_interface stays at 4 with its reason recorded — the
usb-transfer wire protocol reports exactly max_reported_endpoints (4) per
interface, so widening it alone would change nothing a class driver sees.
Lifting it is a protocol change.

No direct test, and that is written down as open question 5 rather than
glossed. The parser is pure and wants a host unit test, but
usb-xhci-library.zig imports memory, mmio and time so it cannot be a
standalone test root, and QEMU offers nothing that reaches the path — the
largest device available is usb-audio,multi=on at 2 interfaces and 211
bytes. The alternate-setting path that shares the same `current = null`
logic is exercised by that device.

Suite 116/116.
2026-08-08 12:05:33 +01:00
Daniel Samson 6328823ef1 usb: a configuration block is as long as the device says it is
The driver read the first 512 bytes of a configuration block into a fixed
buffer and parsed those. The block's length is the device's own choice
(wTotalLength, a u16), so anything larger was silently cut: interfaces past
the cut did not exist as far as the host was concerned, while the
SET_CONFIGURATION that follows still configured the device for all of them.
A headset is 500-900 bytes, a UVC webcam 1-3 KB, a multifunction printer
600+.

Now allocated at the declared length, so the ceiling is the field's u16 —
the specification's number rather than one of ours. A block shorter than its
own 9-byte header is refused rather than trusted.

The bring-up line reports the declared length and the bytes actually read,
so a truncation can never again be invisible, and usb-large-descriptor
asserts they match with a backreference.

That case has an honest limit, recorded in its comment: QEMU cannot produce
a block over 512 bytes. The boot keyboard, mouse and stick are 34-44, and
the largest device available is usb-audio in multi-channel mode at 211 —
which is exactly why the suite never caught this, and why it cannot now
reproduce the original trigger. What it does catch is the class: any clamp
below the attached device's block fails it, verified by pinning the buffer
to 128 and watching "config block 211 bytes, read 128" turn the case red.

Suite 115 -> 116.
2026-08-08 11:53:01 +01:00
Daniel Samson 69fbef40c0 usb: the controller says how many device slots it has
max_devices was 8, with the comment "QEMU presents a handful; a fuller
machine would grow this" — a number chosen against the test rig, waiting for
a real machine, which is the pattern docs/bounds-track-plan.md exists to
stop.

The driver already knew the true figure. It reads HCSPARAMS1.MaxSlots at
bring-up and writes it straight into op_config, so every slot the controller
offers has always been *enabled*; only the array tracking them was 8. QEMU's
xHCI reports 64, so seven eighths of the controller was live and invisible,
and the ninth device — a keyboard, mouse, webcam, headset, hub and two
sticks reach that without trying — disappeared on a hub-attached path that
logs nothing at all.

The array becomes a slice allocated from max_slots at bring-up. A controller
claiming zero slots cannot address anything, so that is now a dead
controller rather than an empty allocation failing mysteriously later. The
Device Context Base Address Array is a page, 511 usable entries, so it
already covered the 255-slot maximum.

The bring-up line reports both numbers, and usb-hid asserts they are equal
with a backreference rather than a magic number, so the test cannot drift
from the hardware. Pinning tracking back to 8 fails it: "64 slots,
tracking 8".

Suite 115/115.
2026-08-08 11:39:49 +01:00
Daniel Samson f4eb88e7d2 build: a new compile-time ceiling declares itself or does not land
The convention that tunables live in system/parameters.zig with their
reasoning attached predates this and got 2% compliance — 5 of 235. A
convention with no teeth is how a bare `const maximum_devices = 64` reached
an AMD desktop and cost it USB and storage. This is the same rule with a
gate behind it.

tools/check-bounds.py finds every bound-shaped declaration — a `maximum_*`
const with a literal value, or a type with a literal array length — and
requires the five-field block above it: what it counts, who decides its
size, what it protects, what happens at the limit, and how anyone finds out.

The at-limit vocabulary is closed: refuse, degrade, truncate, grow. There is
deliberately no way to spell "silent", no way to spell "drop", and nothing
meaning "allow", so the behaviours that did the damage cannot be written
down. Truncation is legal only carrying a marker the reader can see, which
is why klog_maximum_message qualifies and a USB descriptor cut at 512 bytes
does not.

An array length that names a declared bound is not itself a bound; only
literal lengths are flagged, which pushes ceilings toward having names.

The 273 that predate the rule are allowlisted so this lands without a
tree-wide sweep in front of it, and that list may only shrink: declaring a
bound means deleting its line, and the check fails on a stale entry too.
Nothing may be added.

Wired into `zig build test` and available alone as `zig build bounds`. Not
in the default build — it reads the whole tree, and a red bounds check
should not stop you booting a kernel.

Five are now declared rather than allowlisted. Writing them out is its own
argument: maximum_devices reads "protects: nothing — this is a sizing guess
about someone else's computer", and maximum_tasks now carries the fact that
it has been raised twice, each time by something that outgrew it.

Verified the gate refuses an undeclared bound, a declared one using
forbidden vocabulary, and an allowlist entry that has since been declared.
Suite 115/115.
2026-08-08 11:27:27 +01:00
Daniel Samson 568823a4fb docs: L1 was wrong — reclamation is not a death-sweep problem
The first step of the unattended run was "a dead task's registrations die
with its claims". Implementing it would have broken the restart path it was
meant to protect.

The broker keeps entries on purpose: they describe hardware, which did not go
away when a driver died. And device ids must stay stable across a bus
restart, because device-manager dedupes re-reports by device_id so a
restarted bus does not spawn a second driver instance — stability that comes
from the idempotency scan returning the existing id. Removing entries on
death would hand a restarted bus fresh ids and duplicate every driver.

Everything else a task holds is already reclaimed on every path out: IRQ
bindings, IOMMU domains, DMA regions, then its claims.

The leak the audit found is real but has two other sources: a device that
genuinely goes away has no retirement path, and a bus that enumerates
differently on restart strands its old entries. Both belong to the device
manager's inventory, and both need the id-stability question settled first —
tombstone-and-reuse aliases ids another process still holds, generation
tagging changes the id encoding, which is ABI. Recorded as an open question
rather than guessed at.
2026-08-08 11:15:11 +01:00
Daniel Samson 4398eb7cc4 docs: scope the bounds track's unattended run
Six steps an agent can execute: reclamation, the bounds build check, and
the four user-space USB/xHCI bounds where the hardware already reports the
number we guessed.

Deliberately excluded: the authorisation gate and moving the device
inventory to the manager. Both decide whether the OS is secure and both are
a direction rather than a specification — what a device capability is, which
syscalls change, what replaces device_claim for its seven callers. They want
a design session, not an agent.

Three open questions are written down rather than guessed: device_enumerate
most likely narrows to the firmware-discovered roots rather than retiring
(the manager cannot ask itself for the PCI host bridge); a manager restart
has no re-enumerate handshake, so it comes back blind while its buses live;
and "add adversarial tests" is not executable until the attacks are named.
2026-08-08 11:13:20 +01:00
Daniel Samson a86559648e kernel: a refusal names its rule, and two bounds stop failing open
An AMD Ryzen booted to a working compositor with no USB and no storage,
and the log said only "register refused". A tree-wide audit of every
compile-time ceiling followed: 235 of them, 139 on quantities the machine
or a file decides rather than us, 5 documented anywhere, 171 silent when
reached. docs/fixed-bounds-audit.md has the inventory.

Errno attribution. The errno space was split between the kernel and the
envelope, free to drift; it is now one list in system/abi.zig, restated on
both sides, with a comptime check in library/device/driver where the two
halves are visible. device_register's six refusals and device_claim's three
are distinct codes, so a bus driver can say which rule stopped it, and
BadParent splits into NoSuchParent and NotYourParent. pci-bus reconciles
found against registered instead of counting refused functions as found.

Idempotency ordering. The child cap was checked before the identity match,
so a restarted bus was refused its own devices — the supervision restart the
system leans on ratcheted toward a degraded machine. A re-registration
consumes no slot and is now admitted first.

IOMMU fail-closed. confineDevice returned success for a device id past the
confinement table, leaving the device outside every domain while the caller
believed it confined — unreachable only while ids stop at 64, which both the
inventory move and a hardware-reported domain count would change. It refuses
now, and the coupling to the broker's device cap is a comptime assert rather
than a sentence in a comment.

PCI apertures. The bridge's MMIO apertures are derived from the holes in the
firmware memory map, and the derivation copied sub-4 GiB entries into a
fixed [64] array and skipped the rest. A skipped region is not merely lost:
the gap finder concludes it is free, so a real machine's 60-200 entry map
yields an aperture over live RAM, and containment then admits a child BAR
covering kernel memory. Rewritten to walk the map in place, with the hole
finder extracted as a pure function and driven by a synthetic 100-entry map
in a new test case. Both new tests were verified to fail on the old code.

parameters.zig gains the rationale it was missing and loses a stale sentence
pointing at the wrong file; vdso.md documents the errno space, including
EPEER, which had no written meaning anywhere.

docs/os-development/bounds.md is how a ceiling is declared from here.
docs/bounds-track-plan.md is the plan to remove the ones we invented.

Suite 114 -> 115.
2026-08-08 11:09:54 +01:00
Daniel Samson 7db5fba884 kernel: boot on AMD — SYSRET puts the RPL in the STAR base
A Ryzen 3 3200G triple-faulted on its first timer tick after reaching init.
Three defects in a chain, each hiding the one beneath it.

STAR's SYSRET base was 0x10, so SS came back as base+8 = 0x18 with RPL 0
while CS carried RPL 3. Intel ORs RPL 3 into SS on SYSRET; AMD only does so
for CS. Ring 3 ran fine — RPL is not checked on data access — and died the
moment an interrupt tried to IRETQ back, where SS.RPL must equal CS.RPL.
The base now carries the RPL (0x13), as Linux does.

Two fixes below it, both of which made the first one unreadable:

scheduler() read IA32_GS_BASE and dereferenced it without testing for zero,
so every fault reporter faulted in turn — a panic inside a panic, and the
machine reset before printing anything. Cast after the null test, plus a
re-entrancy guard in the panic handler.

NT is now masked in SFMASK alongside the rest, and isr.s exports
isr_return_iretq at the faulting instruction so a frame dump can say which
IRETQ died and print the CS/SS it was about to load. That dump is what
identified the RPL mismatch.
2026-08-08 11:07:55 +01:00
Daniel Samson a85f29edc9 merge: security track group 4 — SMEP, the SYSRET guard, and SMAP
# Conflicts:
#	docs/security-track-plan.md
2026-08-01 12:20:54 +01:00
Daniel Samson 5a5146ec13 kernel: ring 0 reaches user memory only through the checked copy
SMAP makes the rule the copy layer has followed since it was written into a
rule the hardware keeps. A ring-0 read or write of a user page now faults,
so any code that reaches for a user pointer directly fails the first time it
runs rather than the first time someone attacks it — and the suite becomes
the enforcement test, because every case exercises the kernel with the bit
on. Nothing had to be fixed to turn it on, which is the retrospective proof
that the nine stragglers converted earlier were all of them.

The interrupt entry needed one instruction first. Hardware does not clear
the alignment-check flag on its way into a handler, and ring 3 sets that
flag freely, so a process could have taken an interrupt with SMAP suspended
for the duration. The system call path was already covered — its flag mask
clears it — but the interrupt path needed a `clac`, which cannot simply be
assembled in: it is an invalid instruction on a processor without SMAP, and
danos boots on those too. So the entry ships as a three-byte NOP and is
patched at boot, through the physmap, because the kernel maps its own text
read-only.

The ordering that makes that safe is enforced rather than described: the
patch sets a flag, and no core will set the SMAP bit until it is true. A
translation that fails, or bytes that read back wrong through the address
they will actually be fetched from, leave the machine unhardened and saying
so — which is the same posture the IOMMU takes, and better than enforcing
over an entry path that cannot comply. The patch runs before interrupts are
enabled and before any second core exists; a comment says so, because the
three bytes pass through an encoding that must never be executed and a
future change that moves this later has to deal with that first.

Suite 114/114, with a case that reads a user page from ring 0 and requires
the fault, and the multi-core case asserting every core that ran work had
the bit — the same shape SMEP got, for the same reason: CR4 is per-core, and
a hardening is only as wide as its narrowest core.
2026-08-01 12:20:44 +01:00
Daniel Samson 1365a245ba docs: security track live state — HS green at 113 2026-08-01 11:22:08 +01:00
Daniel Samson cb30faf15f kernel: a hostile return address cannot fault the kernel
SYSRETQ with a non-canonical RIP raises a general protection fault in ring
0 — on the kernel stack, an instruction after the swapgs that installed the
user's GS base. It is one of the better-known escalation primitives, and
ring 3 reaches it without any kernel bug at all: the processor saves the
address of the instruction after SYSCALL, so a program whose SYSCALL is the
last two bytes of the last canonical page returns to the first
non-canonical address. The new test does exactly that.

The exit path now sign-extends the return address from bit 47 and compares;
if the value changed, it returns through IRETQ instead, which commits the
privilege change before fetching the new address, so the fault arrives from
ring 3 and the process dies like any other. Four register-only operations
and a branch that a correct program can never take — it could not have
executed at a non-canonical address in the first place. Bit 47 is the right
pivot because danos builds four-level page tables and nothing sets the
five-level bit; a future port must move the pivot, and the comment says so.

SFMASK grows one bit while we are here. SYSCALL, unlike an interrupt gate,
does not clear the nested-task flag, so the kernel had been running every
system call with whatever ring 3 last chose — harmless while the only exit
was SYSRETQ, and a question worth not having now that one exit is IRETQ.
The kernel is never nested; ring 3 still gets its own flag back.

Suite 113/113. The new case asserts the refusal counter rather than the
dying process: the emulator we test on kills it either way, so only the
counter distinguishes a guard that ran from one that did not.
2026-08-01 11:22:07 +01:00
Daniel Samson ec154a975f docs: security track live state — H2 green at 112 2026-08-01 10:05:59 +01:00
Daniel Samson 36a7cc5fe9 kernel: ring 0 cannot execute a user page
SMEP turns the classic escalation — divert kernel control flow into a page
the attacker wrote — from a silent takeover into an immediate fault with
the offending address in the log. The bit is per-core state, so it is set
where the syscall MSRs already are: in the per-CPU bring-up both the boot
processor and every application processor run on their way in. A core that
climbed the trampoline without it would be a hole no boot log would show,
which is why the SMP case now reads CR4 on each core it lands on and
requires every one of them to be hardened, not just the one that printed
the banner.

Enabling it that early is only safe because nothing ring 0 executes is
mapped for ring 3, and that had to be established rather than assumed:
kernel text carries only its ELF flags, the physmap is no-execute, the
trampoline page is mapped supervisor and the core running it has not
enabled the bit yet, and the boot processor turns it on while still on the
loader's tables — which map nothing user-accessible at all. The one
indirect call in the kernel takes a kernel address.

The CPUID probing that was scattered across the timer code becomes a small
shared helper, since the feature question is now asked from two places and
each wanted the same maximum-leaf guard. Absence is tolerated and reported,
like the IOMMU: danos still boots on a machine without the feature, and
says which one it is.

The test harness starts asking QEMU for a CPU that has the bit at all —
its default model has neither SMEP nor SMAP, so the code would otherwise
have been unreachable in every run. No case behaved differently under the
richer model.

Suite 112/112, with a new case that maps an executable user page, calls
into it from the kernel, and requires the fault the CPU is supposed to
raise.
2026-08-01 10:05:58 +01:00
Daniel Samson b3011fbb40 merge: security track group 3 — every protocol on the envelope, ids owned
# Conflicts:
#	docs/security-track-plan.md
2026-08-01 09:05:38 +01:00
Daniel Samson 1b1c587c14 library: the harness keeps the subscribers, and an id belongs to whoever opened it
Three services had each written the same thing and got it three different
ways: input polled the process list to notice a dead subscriber, and only
when someone else subscribed; the power service never noticed at all; the
device manager noticed drivers but not subscribers. The harness owns the
table now, driven by the events a protocol declares — it registers on the
reserved verb, frames each event once, posts to everyone interested without
waiting on any of them, and reclaims a slot when the kernel says its owner
died. Interest masks moved to the envelope, so a subscriber that wants only
mice asks the same way everywhere.

Two consequences the plan had not foreseen. The device manager now hears a
supervised child's death twice, once as its supervisor and once as a
subscriber, so restart backoff counted every crash twice and gave up after
half as many; it retires the id before counting. And the kernel's published
exit table had eight slots for what is now six subscriptions in a plain
boot, so it holds sixteen.

The other half is a hole the design named early and left standing: a
backend handed out a small integer and then honoured it from anyone. A
process that guessed a file's node id read another client's file; a display
layer had no owner at all, so any client could reconfigure or destroy any
layer; a USB device token was never checked against the client that opened
it. Each is now bound to the task that opened it, and a wrong owner gets
exactly what an unknown id gets — the refusal must not become the oracle
the identical answers elsewhere were designed to remove. Closing a file
changed with it: it used to succeed unconditionally, which would have told
a caller which ids existed.

Suite 111/111, with a new case in which one process holds a file and a
layer, hands both ids to a second process, and finds them untouched after
that process has tried everything with them.
2026-08-01 09:05:26 +01:00
Daniel Samson 776b04184e docs: security track live state — P4b green at 110 2026-08-01 07:20:39 +01:00
Daniel Samson 2719b93530 library: the last three protocols speak the envelope
These were the awkward ones. Each began with an operation packed into a
single byte — two of them with a version wedged in beside it — so there was
no wrapping them: the layouts had to be rebuilt. The device manager's own
enumerate and subscribe become the reserved verbs that mean the same thing
everywhere, its replies lose three status structs the envelope already
carries, and a device id becomes the packet's target. Power drops the
version it repeated on every request, because describe is the handshake,
and stops claiming a 64-byte ceiling it never needed for calls. USB moves a
control transfer's data to the packet tail in both directions, which makes
the status length the transferred length and retires a field that had been
saying the same thing twice.

The danger in this one was not the protocols but their readers. Init
recognised a power button by two bytes at the head of a message, the ACPI
service dispatched on the first byte, the xHCI driver read its operation
with a raw integer load, and the HID drivers reinterpreted a report
wholesale — none of which would have failed to compile once the layouts
moved. They would simply have stopped: no shutdown on the power button, no
reports from the keyboard. Every one of them now reads through the
generated types, and the shutdown gate that answers only a subscriber is
the same code it was.

Two sizes were decided by measuring rather than assuming. The child-added
message is both a request and the event broadcast to subscribers, and
alignment rounds it to 48 bytes, which puts its packet exactly on the
64-byte push floor — a test pins that, because a field added carelessly
would now overflow it. The interrupt report gives up eight bytes of inline
room to make space for the header; the two drivers that produce reports
send eight and four.

Suite 110/110.
2026-08-01 07:20:37 +01:00
Daniel Samson e250d8cd79 docs: security track live state — P4a green at 110 2026-08-01 06:16:15 +01:00
Daniel Samson d2dfbcabf8 library: five protocols speak the envelope
The folded header stops being a rule in a document and becomes the layout
on the wire. Verbs number from sixteen, leaving describe, enumerate,
subscribe and unsubscribe reserved and answered the same way by every
provider — none of them writes a line to do it. What each protocol used to
carry in a field of its own now travels in the header: a vfs node and a
display layer are the packet's target, and a reply opens with a status the
envelope stamps rather than one each protocol spelled for itself.

Display gains the most. One forty-byte request had served eleven verbs, so
attach_scanout smuggled stride through x, refresh through y and format
through colour, and every coordinate crossed as a bitcast. Per-operation
structs end all three: the fields have their own names and their own signs,
and the tile payload grows to 224 bytes because the prefix shrank. Scanout
loses a message maximum of 64 it had no business declaring — it answers
calls, and the floor for a call is 256 — and virtio-gpu stops hard-coding
that number at its harness.

Two changes are semantic rather than notational. A directory now ends at an
entry with no name, because the fixed part of a reply always travels and a
zero-length reply no longer exists to mean anything. And input joins the
service harness, the last loop in the tree that answered no ping and heard
no terminate; its subscriber table, its pruning and its fan-out are the
same code, and a shutdown now asks it to stop instead of killing it.

A new conformance case reads the registry's own listing and asks every
protocol it finds for its name, its version and its verb count, then offers
a verb nobody defines and requires -ENOSYS — the envelope's promise,
checked against providers rather than against itself. What it cannot reach
in that boot it names on the serial line instead of passing quietly.

Suite 110/110.
2026-08-01 06:15:25 +01:00
Daniel Samson b004b9c3eb merge: security track group 2 — the protocol namespace replaces ServiceId
# Conflicts:
#	docs/security-track-plan.md
2026-08-01 04:45:14 +01:00
Daniel Samson 73aea4582b docs: the security track plan carries its live state on main
The plan is the only progress view from a plain main checkout, and the work
lands on a feature branch that reaches main a group at a time — so between
merges the file said less than was true. It now opens with where the work
is, which branch carries it, and what main itself holds, refreshed on main
after every phase rather than at merges alone.
2026-08-01 04:01:39 +01:00
102 changed files with 9107 additions and 2243 deletions

No files matched your search

+16
View File
@@ -326,6 +326,7 @@ pub fn build(b: *std.Build) void {
if (test_case != null) for ([_][]const u8{
"vfs-test", // the user-space VFS round-trip client
"fat-test",
"badge-scope-test", // the guessable-id probe: a second process names the first's node and layer
"shared-memory-server",
"shared-memory-client",
"crash-test", // hellos to the device manager, then faults — drives the crash-loop cap
@@ -340,6 +341,8 @@ pub fn build(b: *std.Build) void {
"user-memory-test", // aims deliberately bad user pointers at the checked copy layer
"protocol-registry-test", // drives the registrar: ungranted bind, collision, restart
"protocol-denied-test", // restriction stage one: an ungranted open answers as absence
"protocol-conformance-test", // the reserved verbs, asked of every provider the boot bound
"device-authority-test", // the attacker: a process handed no device, asserting what it cannot do
}) |fixture| {
const package = b.lazyDependency(fixture, .{}) orelse
@panic("a test fixture package is missing under test/system/services");
@@ -395,6 +398,19 @@ pub fn build(b: *std.Build) void {
// here (compiled for the host rather than inheriting a freestanding target) —
// which also compile-checks that the three-way split stays self-consistent.
const test_step = b.step("test", "Run tests");
// Every compile-time ceiling states what it counts, who decides its size, what it
// protects, what happens when it is reached, and how anyone finds out
// (docs/os-development/bounds.md). The ~273 that predate the rule are listed in
// tools/bounds-allowlist.txt so this could land without a tree-wide sweep first;
// that list may only shrink. Part of `test` rather than the default build: it reads
// the whole tree, and a red bounds check should not stop you booting a kernel.
const bounds_check = b.addSystemCommand(&.{ "python3", "tools/check-bounds.py" });
bounds_check.setCwd(b.path("."));
const bounds_step = b.step("bounds", "Check that every compile-time ceiling declares itself");
bounds_step.dependOn(&bounds_check.step);
test_step.dependOn(&bounds_check.step);
for ([_][]const u8{
"system/boot-handoff.zig",
"system/abi.zig",
+3
View File
@@ -63,6 +63,7 @@
.@"virtio-gpu" = .{ .path = "system/drivers/virtio-gpu" },
.@"vfs-test" = .{ .path = "test/system/services/vfs-test", .lazy = true },
.@"fat-test" = .{ .path = "test/system/services/fat-test", .lazy = true },
.@"badge-scope-test" = .{ .path = "test/system/services/badge-scope-test", .lazy = true },
.@"shared-memory-server" = .{ .path = "test/system/services/shared-memory-server", .lazy = true },
.@"shared-memory-client" = .{ .path = "test/system/services/shared-memory-client", .lazy = true },
.@"crash-test" = .{ .path = "test/system/services/crash-test", .lazy = true },
@@ -77,6 +78,8 @@
.@"user-memory-test" = .{ .path = "test/system/services/user-memory-test", .lazy = true },
.@"protocol-registry-test" = .{ .path = "test/system/services/protocol-registry-test", .lazy = true },
.@"protocol-denied-test" = .{ .path = "test/system/services/protocol-denied-test", .lazy = true },
.@"protocol-conformance-test" = .{ .path = "test/system/services/protocol-conformance-test", .lazy = true },
.@"device-authority-test" = .{ .path = "test/system/services/device-authority-test", .lazy = true },
// See `zig fetch --save <url>` for a command-line interface for adding dependencies.
//.example = .{
// // When updating this field to a new URL, be sure to delete the corresponding
+632
View File
@@ -0,0 +1,632 @@
# The bounds track: removing the numbers we invented
*Plan, 2026-08-08. Follows [fixed-bounds-audit.md](fixed-bounds-audit.md) (235 ceilings,
139 on quantities we do not choose) and the AMD Ryzen that found the first one.*
---
## Live state — the unattended run
*This table is the progress view. It is updated at the end of every step, before the
next one starts.*
| Step | What | State |
|---|---|---|
| L1 | Reclamation: a dead task's registrations die with its claims | **stopped — the step was wrong; see open question 4** |
| L2 | Bounds build check + allowlist; declare what we have already touched | **done** — `zig build bounds`, 273 allowlisted, 5 declared |
| L3 | xHCI: slot count from `HCSPARAMS1.MaxSlots`, not 8 | **done** — QEMU reports 64; the driver tracked 8 |
| L4 | USB: configuration descriptor sized by `wTotalLength`, not 512 | **done** — QEMU tops out at 211 bytes, so the case catches the class, not the original trigger |
| L5 | USB: interfaces from the descriptor, and the misattributed-endpoint bug | **done** — fix is by construction; no direct test, see open question 5 |
| L6 | xHCI: a failed `allocateDevice` stops leaking an enabled slot | **done** — path forced and verified; no regression test, see open question 5 |
**Run 1 complete.** L1 stopped (the step was wrong), L2–L6 landed. Suite 115 → 116.
Allowlist 278 → 269. Two steps ship without a permanent regression test, both because
QEMU's USB devices are too small to reach the paths — see open question 5, which is the
audit's own lesson recurring: the test rig is smaller than a real machine.
---
## Run 2 — device authority: delete the invented ceilings
*Design: [device-authority.md](os-development/device-authority.md), which is the **how**
for the delegation step [device-manager.md](device-driver-development/device-manager.md)
already settled. Read both before starting; the second is authoritative where they
differ.*
The goal, in the project owner's words: **remove the maximum values we set arbitrarily,
move the responsibility to the device manager, and keep in the kernel only the parts
that cannot safely run in user space.**
| Step | What | State |
|---|---|---|
| D0 | The grant rides `system_spawn` — atomic, so no driver need change to receive one | **done** |
| D1 | `device_transfer(device_id, task_id)` — the holder gives a device away | **done** — syscall 54; a move, not a copy |
| D2 | Adversarial case: a process handed nothing is refused | **done** — `device-authority-test`; the claim half joins it at D6 |
| D3 | The manager claims the seeded devices before any driver is spawned | **merged into D4** |
| D4 | `usb-xhci-bus` receives its controller | **done** — caught an IOMMU regression I introduced |
| D5 | `pci-bus`, `virtio-gpu`, `ps2-bus`, discovery receive theirs | **done** — every driver now receives its hardware |
| D6 | `device_claim` refuses a device the caller was not handed | **blocked on question 10** |
| D7 | Zero-resource devices stop being kernel objects | **blocked on question 8** |
| D8 | **`maximum_children_per_parent` deleted** | **done** |
| D9 | Dynamic table; **`maximum_devices` deleted**; per-registrar allowance | **done** |
| D10 | Every driver hellos, on its own merits | not started — optional, independent |
*Executed in the order D1, D2, D4, D5(part), D9, D0, D5(rest), D8 — the numbering is
the original plan's, not the sequence. D0 was added mid-run, D3 merged into D4, and D8
turned out to have been unblocked since D9.*
**Run 2 stops, blocked on one question.** Landed: D0, D1, D2, D4, D8, D9, and D5 for
three of five claimants (`usb-xhci-bus`, `pci-bus`, `virtio-gpu`). Suite 118/118.
**Both invented ceilings are gone.** `maximum_devices` and
`maximum_children_per_parent` no longer exist, and delegation is atomic with the spawn.
What remains is not a number: **D6 closes the claiming hole** and is blocked on
question 9, and D7 moves the inventory and is blocked on question 8.
Ordering is load-bearing. D1–D2 built and proved the mechanism with nothing depending on
it. D4–D5 move each claimant across one at a time, so the suite stays green throughout
and a regression names the driver that caused it. D6 is the flag day. (The original
"D7 must precede D9" no longer holds: the per-holder quota bounds zero-resource children
as well as anything else, so D9 landed without it.)
**D3 merged into D4** (found while implementing, recorded rather than worked around).
The two cannot be separated: the moment the manager claims a device, any driver still
calling `device_claim` on it is refused `AlreadyClaimed`, so D3 on its own turns the
suite red — and D3 applied to *nothing* changes no behaviour and cannot be tested.
They land together, with the manager claiming only for drivers in an explicit
**delegated set** so every unconverted driver keeps claiming exactly as before.
`usb-xhci-bus` is the first member, as it was the first driver to conform to `hello`
(device-manager.md, M18.1). D5 moves the rest in one at a time; the set and the
`device_claim` path both disappear at D6.
### Observations from the run
- **D4 introduced an IOMMU regression, caught by converting one driver at a time.**
`confineDevice` runs inside `systemDeviceClaim`, so a device arriving by *transfer*
was never confined for its new owner: the driver's DMA rings went unbound (three
IOMMU+USB cases failed), and two worse consequences were latent — a manager death
would have torn down a domain a live driver was using, and a driver death would have
leaked one. `iommu.reassign` moves the confinement with the device, keeping the
domain and attachment intact so it never translates through nothing. Converting all
five drivers at once would have produced the same three failures with five suspects.
- **`usb-hub` failed once in a full run, then passed six times** (four isolated, two
full). Suspected instance of the known intermittent AP ring-3 fault rather than
anything in D4 — recorded rather than dismissed, because D4 moved the `hello` earlier
and so did shift boot timing. Watch it across the remaining steps.
---
## Run 3 — close the claiming hole
*Every driver now receives its hardware. What remains is that `device_claim` still
works for anyone, so a device nobody holds can still be taken. Six steps, no open
questions.*
### The rule this run implements
The kernel records, per device, **who gave it**. From that one field everything follows:
- `device_transfer` and the spawn-fused grant set the giver.
- **`device_claim` refuses a device that has a giver.** A device that was given to
someone is delegated hardware and must be handed on, never taken.
- **On death a device reverts to its giver**, if that task is still alive; otherwise its
claim clears. A grant is a loan, not a gift.
Two things fall out rather than being special-cased:
- **The framebuffer is untouched.** Nobody delegates it, so it has no giver, so the
display service can still claim it exactly as today. No exemption in the kernel, no
mention of display anywhere in the rule.
- **Restart needs no race.** A dying driver's device returns to the manager, which
re-delegates it on respawn. Previously the kernel released it to nobody and the
manager re-claimed first-come, so every restart reopened the hole.
**Found while implementing: E2 is the step that closes the hole, not E3.** A delegated
device is *held*, so an attempt to take it is refused as `AlreadyClaimed` long before
the giver is consulted — and once a borrower's death returns the device to its lender
(or clears both when the lender is gone), there is no state where a device is unheld and
still on loan. E3's check is therefore unreachable today. It stays as one comparison
that fails closed, guarding any future path that frees a device without clearing its
giver, and its comment says so rather than implying a protection it is not providing.
| Step | What |
|---|---|
| E1 | Record a giver per device; `device_transfer` and the spawn grant set it — **done** |
| E2 | On task death a device reverts to its giver if alive, else its claim clears — **done** |
| E3 | `device_claim` refuses a device that has a giver — **done**, but unreachable: E2 already closed the window |
| E4 | The manager claims every resource-bearing device at boot, so nothing is left takeable — **done** (boot snapshot only; see below) |
| E5 | The attacker fixture gains the claim half it has been waiting for since D2 — **done with E4** |
| E6 | Delete the delegated-set scaffolding — every driver is delegated now — **done** |
Ordering: E1 alone changes no behaviour. E2 must precede E3, or a restart cannot
re-acquire. E4 must precede E5, or the attacker will find takeable devices and the
assertion will be wrong about why. E6 is cleanup.
**Run 3 complete.** Suite 118/118. Every driver receives its hardware; a grant is a
loan that returns to its lender when the borrower dies; nothing firmware-discovered is
left unheld except the framebuffer, which the compositor owns.
### E4's scope, stated
It covers the **boot snapshot**. A device *reported* later and matched to no driver
stays claimable — `pci-cap-test` and `iommu-fault-test` both rely on that to reach an
unmatched NIC. Narrowing it further is a separate change with those fixtures in scope.
The real gap it closed was the **HPET**: an MMIO window, an IRQ, no user-space driver,
and claimable by anyone. Excluded on purpose: the loader's framebuffer (the manager
starts before display, so taking it would break the boot screen) and anything with no
resources, which grants nothing.
### Not in this run, and not blocking it
**Zero-resource devices stay in the kernel.** Moving them out needs an answer to who
mints their ids, given that the id is the `device_token` on the usb-transfer wire and
the kernel's idempotency is what keeps it stable across a bus restart. Nothing depends
on it: both invented ceilings are already gone and this run does not need it. Recorded
as future work.
**Not every driver hellos.** Delivery no longer needs it, so it stands or falls on its
own merits — uniform liveness and one class of driver. Also future work.
---
### Question 9 — answered: a singleton gets every device that matched it
The 8042 is one controller described by two ACPI nodes, so it cannot be split across
processes. The manager now hands the single `ps2-bus` instance **every** matching node:
the first rides the spawn, the rest are transferred to the running instance. Late
arrival is safe because the ordering is natural rather than lucky — the controller node
carries the ports and is needed at once, the mouse node not until after identify
(measured: handed over at 0.336, first touched at 0.456). The count is whatever matched,
so a machine with no PS/2 ports or one port needs no special case.
Discovery turned out not to be special either. The kernel seeds the `acpi-tables` node,
so it is in the same boot snapshot the manager already scans for the PCI host bridge —
it is handed over at spawn like everything else.
### Open question 10 — the framebuffer is the last thing anyone claims
`device_claim` now has exactly two callers: the device manager, which is the acquirer
and should have it, and `system/services/display/backend.zig`, whose GOP path claims the
kernel-seeded display node.
Closing `device_claim` breaks the compositor's boot floor. Exempting it puts a hole in
the middle of the authority model, in the one place an exemption is most expensive.
The likely answer is neither. **The framebuffer is not a device** — it is where pixels
go, handed over by the loader, and the kernel wraps it in a `DeviceClass.display`
descriptor only so `mmio_map` can hand it over write-combining. If that is right, it
should leave the device table rather than be exempted from its rules, and the compositor
should receive the pixels some other way. That is a change to the display path, which is
out of scope for this run.
### Settled 2026-08-08: the grant rides `system_spawn` (D0)
Questions 6 and 7 both dissolved on inspection — neither `ps2-bus` nor discovery needs
to start speaking `hello`, and `virtio-gpu` has no standalone path to lose. What remains
is *where the grant is delivered*, and there are three candidates:
| | Race window | Cost |
|---|---|---|
| Transfer after spawn | **yes** | none |
| Every driver hellos | no | `ps2-bus` + discovery gain a handshake |
| **Grant rides `system_spawn`** | **no — atomic** | one more syscall argument |
**Take the third.** The manager cannot transfer before the child exists, so a separate
transfer always leaves a window in which the child is running and does not yet hold its
device. It would close on QEMU every time and open occasionally on a machine with
different timing — the exact failure shape this track exists to delete, and not worth
introducing while removing the others. Fusing the device into the spawn removes it by
construction: the child does not exist until it holds the device. No new knowledge in
the kernel — the same rule, *you may give away what you hold*, made atomic with the call
that creates the recipient. `system_spawn` uses five of six argument registers, so there
is room, and `no_device` is already the sentinel for a driver with no assignment.
**`hello` for every driver is a good idea on its own merits** — uniform liveness, the
deadline applied to all rather than some, and the `speaks_protocol` two-class split
leaving the manager (a wedged `ps2-bus` is invisible to its supervisor today). It is
D10, kept separate so grant delivery does not force it.
### Open questions raised by D5 — resolved except question 8
Delegation is delivered in `onHello`. That works for a driver that says hello, and
**two of the four do not**.
6. **`ps2-bus` does not hello**, and that is deliberate: device-manager.md records
"Legacy drivers (e.g. ps2-bus) are supervised and restarted but **not yet required
to hello**", and `Driver.speaks_protocol` exists to say so. Either it leaves
"legacy", or the grant gets a delivery point that is not `hello`.
**The `acpi` service is not this case — an earlier version of this question wrongly
lumped it in.** It is spawned as `addDriver("discovery", no_device, false)`: the
*discovery service*, one per firmware, with **no device assignment at all**, which
"finds and claims the acpi-tables (or devicetree-blob) node itself. Not a per-device
driver." The manager cannot hand it a device because discovery is what produces the
device tree — there is nothing to match against yet. Its question is not "should it
hello" but "is the bootstrap exempt from D6, or does the manager claim the
acpi-tables node and pass it on".
**A delivery point that needs no hello already exists in the shape of the code**:
`process.spawnSupervised` returns the child's pid, so the manager could transfer
immediately after spawn. If that is acceptable, this question mostly dissolves —
`ps2-bus` would not need to leave "legacy" and discovery could be handed its node
too. The cost is ordering: the child may reach for the device before the transfer
lands, where `hello` guarantees it cannot because the child is the one asking. That
trade is the actual decision.
7. **`virtio-gpu`'s "standalone bring-up" — resolved; there is no such path.** An
earlier version of this question read the comment "Best-effort: standalone bring-up
has no manager" as a boot path that delegation would delete. It is not one.
`virtio-gpu`'s `main` requires `argv[1]` and exits without it, and the only source of
that argument is the device manager — the chain is ACPI → pci-bus reports the
function → `devices.csv` matches `1AF4:1050` → the manager spawns the driver with the
id. There is no way to run it without a manager, so nothing is lost.
What the comment is really about is **resilience**: the hello is best-effort so a
driver whose manager has *died* keeps serving, which device-manager.md states
("If the manager dies, drivers keep running").
The residual is one narrow window: the manager spawns a driver and dies before
transferring. Today the driver could still claim, because claiming is free-for-all;
after D6 it exits and the restarted manager respawns it. That is the better
behaviour — a driver holding hardware nobody assigned it is what D6 exists to stop.
Until these are answered, `device_claim` cannot be closed off at D6 for those three, so
**D6 is blocked on questions 6 and 7**.
8. **Removing zero-resource devices from the kernel needs someone else to mint their
ids, and nothing says who.** A USB interface is registered with
`resource_count = 0`, and the id `device_register` returns is load-bearing in three
places: it is the `child_added` packet's target, it is the class driver's `argv[1]`,
and it is the `device_token` of the **usb-transfer wire protocol** — so the id space
is visible on the wire, not merely internal. usb-xhci-bus's own comment records the
fourth constraint: the kernel's idempotency is what makes "the same port and
interface always map back to the same device id" across a bus restart, which is what
stops a respawned bus spawning duplicate class drivers.
So the mover has to answer: who mints the id, how it stays stable across a *bus*
restart, how it stays stable across a *manager* restart (open question 3 territory),
and whether the wire protocol's `device_token` changes meaning. That is a design
step, not a mechanical one.
**D8 is reordered to run after D9**, which is a correction to the original sequencing.
D8's justification was "the authorisation it stood in for exists" — but with D6 blocked
it does not, so deleting the shared per-parent cap now would reopen the exhaustion hole
it was written for. D9's **per-holder quota** closes that hole independently of
authorisation, and does it better: a rogue exhausts its own allowance rather than the
table everyone shares. Once the quota exists, the per-parent cap is redundant whether or
not D6 has landed.
D9 also no longer depends on D7. Its original rationale was that zero-resource children
are the case that sidesteps containment — true, but a per-holder quota bounds them just
as well as anything else, because it counts entries per holder rather than per parent.
### Settled, so the run does not re-litigate them
- **The manager claims, it is not granted.** No binary names in the kernel; the rule is
"you may give away what you hold". The residual — it rests on the manager claiming
first — is stated in the design and is closed later by the spawn capability
[drivers.md](device-driver-development/drivers.md) already names as missing.
- **The framebuffer is not a device.** It is where pixels go, handed over by the loader,
and the compositor uses it as the boot floor until a real display driver announces
itself. Nothing in this run touches the display service or its GOP path.
- **`maximum_endpoints_per_interface` and the wire structs stay.** Widening them is a
protocol change, out of scope.
- **A per-holder quota is not a retreat.** Dynamic storage with no bound moves the
ceiling to the kernel heap, which is shared and fatal rather than partial. A bound
charged to the task that caused it is isolation, and it is declared through
[bounds.md](os-development/bounds.md) like anything else.
### Working rules
As Run 1, unchanged: work in `/Users/danielsamson/Gitea/daniel/danos` on
`claude/bounds-track`; every step lands with a test that fails before the fix, verified
by restoring the old behaviour; full suite green before each commit; never two suites at
once (`pgrep -f qemu_test.py`); 60 GiB free; `git commit -F` with no `Co-Authored-By`;
update this table before starting the next step. **If a step needs a decision that is
not written down, stop it, add the question below, and move on** — Run 1's first step
was wrong and stopping was the right call.
**Suite:** 115/115 at the start of the run.
**Branch:** `claude/bounds-track`.
### What this run deliberately does not touch
Phases 2 and 3 below — the authorisation gate and moving the inventory to the device
manager — are **out of scope for unattended work**. They decide whether the OS is
secure, and they are currently a direction rather than a specification: what a device
capability *is*, which syscalls change, what replaces `device_claim` for its seven
callers, how a driver spawned bare behaves. Those want a design session, the way
`/protocol` had one.
Also out of scope: anything touching `maximum_device_resources` (a wire struct, so a
trust-boundary change, not a resize), and the non-device bounds the audit found in FAT,
the VFS, logger, init, display and boot.
### Open questions this run must not answer on its own
Recorded here rather than guessed. If a step runs into one, it stops and writes the
question down instead of inventing an answer.
1. **`device_enumerate` probably narrows rather than retires.** The device manager
calls it to find `pci_host_bridge` nodes — it cannot ask itself. The likely shape is
that the kernel keeps the *firmware-discovered roots* (which by principle 5 it holds
for real reasons, since they come from ACPI rather than a driver's say-so) and
everything a driver registered lives in the manager. Not decided.
2. **A device-manager restart has no re-enumerate handshake.** If only the manager
dies, the buses are alive and never re-send `child_added`, so a restarted manager
comes back blind. The manager is restartable by design; nothing implements this.
3. **Which adversarial tests I1–I3 need.** The audit's six real defects were all found
by asking what an attacker would do, and the suite had never asked. "Add adversarial
cases" is not executable until the attacks are named.
4. **Reclamation is not a death-sweep problem, and L1 as written would have broken the
restart path.** Found on the first attempt at it. The audit is right that `count`
never decreases, but *death is the wrong trigger*:
- The broker keeps entries deliberately: "The devices stay in the table — they
describe hardware, which did not go away — only their ownership clears." A driver
dying does not unplug anything.
- Device ids must stay **stable across a bus restart**, because
`device-manager.driverForDevice` dedupes by `device_id` so that "a re-report after
a bus restart must not spawn a second instance". Stability comes from the
idempotency scan returning the existing id — removing entries on death would give
a restarted bus fresh ids and spawn duplicate driver instances.
- Everything else a task holds *is* already reclaimed on every path out:
`irq.releaseOwner`, `iommu.releaseAllOwnedBy`, `dmaRegistryReleaseOwner`, then the
broker's claims (`process.releaseTaskResourcesLocked`).
So the real leak has two sources, and neither is death: a device that genuinely
**goes away** (hot-unplug) has no retirement path, and a bus that enumerates
*differently* on restart leaves its stale entries behind forever. Both are the device
manager's inventory problem — phase 3 — and both need the id-stability question
answered first (tombstone-and-reuse aliases stale ids held by another process;
generation-tagged ids change the id encoding, which is ABI). Not an unattended
decision.
5. **Driver descriptor parsing cannot be host-tested, so L5's correctness fix ships
without a direct test.** The endpoint-misattribution bug lives in
`parseConfiguration`, a pure function over a byte blob — exactly the shape a host
unit test wants, and `usb-storage/scsi.zig` and `usb-hid/hid-report.zig` already do
this. But `usb-xhci-library.zig` imports `memory`, `mmio` and `time`, so it cannot
be a standalone host-test root, and QEMU offers no device that would exercise the
path anyway: the largest available is `usb-audio,multi=on` at 2 interfaces and 211
bytes, against a cap of 4.
Three ways out, and picking one is a judgement about house style rather than a
mechanical step: extract the parser to its own file and wire `usb-abi` into a test
module (build-support currently resolves module names only for `userBinary`);
extract it and import `usb-abi` by relative path (against the import-by-name
convention); or accept QEMU-only coverage and say so.
Mitigating, and the reason this is recorded rather than blocking: after the fix the
bug is unreachable **by construction**, not by the added `else`. Interfaces are now
allocated to exactly the count the descriptor declares, so `interface_count` can
never reach `interfaces.len` mid-parse. The `else` is belt-and-braces for the
255-interface clamp. The alternate-setting path that shares it *is* exercised —
`usb-audio` has alternate settings, and the `usb-large-descriptor` case walks them.
### Working rules for the run
- Work in `/Users/danielsamson/Gitea/daniel/danos` (not a worktree), on
`claude/bounds-track`.
- **Every step lands with a test that fails before the fix**, verified by temporarily
restoring the old behaviour and watching exactly the intended assertion flip. A test
that passes both ways is not a test.
- Full QEMU suite green before each commit. Never run two suites at once — check
`pgrep -f qemu_test.py` first; a second concurrent run produces false triple faults
because both share `zig-out`.
- Check at least 60 GiB free before starting a suite.
- Commit with `git commit -F <file>`, never `-m` (a backtick in a message is executed
by the shell and silently eats a word). No `Co-Authored-By` trailers.
- Update the Live state table **before** starting the next step.
- If a step needs a decision that is not written down here, stop, add it to the open
questions above, and move to the next step.
---
## The principles this is derived from
1. **danOS is a microkernel.** Minimise what the kernel is responsible for; move
responsibility to user space so it can be restarted, or fixed live during
development, without taking the system down.
2. **Implement the specifications correctly**, with the limits those specifications
define — not limits we decide.
3. **Move as much responsibility as possible to user space** (the device manager).
4. **What remains in the kernel is minimal.**
5. **What remains in the kernel is there for security or for a hardware limitation.**
Nothing else earns a place.
Principle 5 is the test every bound is put to. For each one: *is this here because of
security, or because of a hardware limitation?* If neither, the storage does not belong
in the kernel and the bound is not a number to be resized — it is a thing to be moved or
deleted.
Applying it to the case that started this:
- `maximum_devices = 64` bounds an inventory of hardware. An inventory is neither a
security control nor a hardware limitation. **The table is in the wrong place**; the
number is a symptom.
- `maximum_children_per_parent = 16` exists because `device_claim` is unauthenticated —
any process can claim any unclaimed device ([devices-broker.zig:164](../system/kernel/devices-broker.zig:164)
checks only that the device exists and is free). The cap is a crude proxy for an
authorisation the kernel does not perform. **Fix the authorisation and the cap has
nothing to defend.**
- `maximum_domains = 64` bounds IOMMU translation domains. Security — stays in the
kernel. But VT-d and AMD-Vi both *report* how many domains they support in a
capability register. Principle 2: read it. We chose 64 without asking.
## The security invariants
Every phase must leave all five standing. This is the "without punching a hole" half of
the brief, and each phase below states how it is checked.
- **I1 Containment.** A process may map only physical memory inside a resource it was
granted. A bus may subdivide only what it already holds.
- **I2 Confinement.** A DMA-capable device is under IOMMU translation before its driver
can program it, or it is not driven at all.
- **I3 No self-granted authority.** A process holds what it was handed. It cannot name
its way into holding more.
- **I4 Death releases everything.** Every resource a task held is reclaimed when it
dies, on every path out.
- **I5 Refusal is attributable.** Every refusal names the rule that refused it.
## Phase 0 — Done
- **Errno attribution.** One errno space in `system/abi.zig`; `device_register`'s six
refusals and `device_claim`'s three are distinct codes; call sites name the reason;
`pci-bus` reconciles found against registered. (I5)
- **Idempotency ordering.** A re-registration consumes no slot, so a full parent
re-admits an identical child. A restarted bus is no longer billed for what it
rediscovers.
Suite 114/114.
## Phase 1 — Reclamation
**Nothing may become dynamic before this.** Today `count` only ever increases and
`releaseAllOwnedBy` clears a dead driver's *claims* but not its *registrations*. With a
fixed table that is a slow march to the cap; with dynamic storage it is an unbounded
leak, and every supervisor restart makes it worse.
- Extend the existing death sweep so a task's registrations go with its claims.
- A registration whose owner is gone is removed; its children are re-parented or removed
with it (they cannot outlive the authority that published them).
- Test: register under a claimed parent, kill the owner, assert the entries are gone and
the ids are not reused while any handle to them lives.
Invariant: **I4**.
## Phase 2 — Close the authorisation hole
The device manager already decides which driver gets which device — it matches against
`devices.csv` and spawns the driver with the device id as `argv[1]`. Nothing binds that
decision to the kernel's `claim`. A driver passes an integer; the kernel checks only
that the device is free.
Per principles 3 and 5: **the decision stays in user space; the kernel enforces only
possession.** The manager hands the driver the device it matched; the kernel's job is
that a driver holds what it was handed and nothing else.
- The manager passes a device to the driver it spawned, over the existing cap-passing
path. Possession is the authority.
- `device_claim` stops being a way to *acquire* a device by naming it.
- Exclusivity stops being a broker refusing a second claimant and becomes the ordinary
property of a thing only one process was given.
**`maximum_children_per_parent` is deleted here**, because after this a bus driver's
children are the devices it actually enumerated under a bus it was actually given, and
the rogue-driver-fills-the-table threat the cap was written for no longer exists.
Invariants: **I3** (the point of the phase), **I1** (containment is unchanged and still
checked on every subdivision), **I5**.
Acceptance: a driver that names a device it was not given is refused, with its own
errno. The QEMU suite gains an adversarial case for it — the audit's lesson was that
"the suite contains no attacker".
## Phase 3 — The inventory moves to user space
The kernel reads only three things out of a device descriptor: **physical ranges** (to
check a mapping falls inside one), **interrupt numbers**, and **one PCI BDF** (to key an
IOMMU domain). Vendor and device ids, class triples, subsystem ids, human-readable
names, bus numbers and parent links are stored solely so `device_enumerate` can hand
them back. That is the kernel acting as a distribution mechanism for data it does not
use — principle 5 excludes it.
- **Zero-resource devices leave the kernel entirely.** A USB device addressed through
its controller conveys no mapping authority; there is nothing for the kernel to
enforce. It is pure inventory and belongs to the device manager. (This is also the
case that sidesteps containment, which is why the cap existed.)
- Identity and topology move to the manager, which already receives them as
`child_added` reports and already holds the authoritative picture.
- `device_enumerate` retires; callers ask the manager, whose protocol already reserves
an `enumerate` verb. Public-ABI change — `docs/os-development/vdso.md` documents it.
- What the kernel keeps: for each device that carries resources, the ranges, the GSIs,
the BDF, and the owner.
After this, the kernel's table holds only resource-bearing devices, and the remaining
count is bounded by what the machine physically has rather than by us.
Invariants: **I1**, **I2** unchanged — both operate on resources, which do not move.
**I4** must be re-checked: the manager's table now needs its own reclamation, and it is
restartable, so it must be able to rebuild from the buses.
## Phase 4 — Ask the hardware and the specification
Principle 2, applied to every remaining bound. Each of these is a number the machine or
the standard already states, which we replaced with a guess. Independent of each other;
can proceed in any order.
| Today | Ask instead |
|---|---|
| `maximum_domains = 64` (IOMMU) | the VT-d / AMD-Vi capability register reports the domains supported |
| `max_devices = 8` (xHCI slots) | `HCSPARAMS1.MaxSlots` — the controller says (1–255) |
| `max_interfaces = 4`, `max_endpoints` | the configuration descriptor says |
| `blob: [512]u8` (USB config) | the device's `wTotalLength` |
| `below: [64]Range` (memory map) | UEFI reports the descriptor count |
| AML blobs capped at 6 | the XSDT's length field gives the entry count |
| `maximum_cpus = 128` | the MADT entry count |
| `maximum_gsi = 24` | the I/O APIC's redirection-entry count; and more than one I/O APIC exists |
| MSI-X vectors | the capability's table-size field (up to 2048) |
Several of these are in user space already (xHCI, USB descriptors) and are ordinary
allocations — principle 1 means those are also the safest to do first, since a mistake
restarts a driver rather than the machine.
Two in this table are **also** correctness fixes the audit found, and should carry their
regression tests: the xHCI `max_interfaces` path misattributes a fifth interface's
endpoints to interface 3, and `below: [64]Range` silently turns occupied RAM into a PCI
aperture — which is an **I1 violation reachable on real hardware**, not merely a lost
device. That one is the highest-priority item in this phase.
## Phase 5 — What legitimately remains
After phases 1–4 the survivors should be only:
- **Pre-allocator storage**: the PMM's own frame bitmap, the memory map the loader hands
over, the bootstrap page tables. You cannot allocate the allocator. (Hardware/boot
limitation — principle 5 admits these.)
- **Interrupt-context storage**: the IST stack and anything an exception path touches
without allocating.
- **Wire structures** whose layout the other side of a trust boundary parses.
- **Facts that are not ceilings**: a page is 4096 bytes; an ACPI name segment is 4.
Each is declared per [bounds.md](os-development/bounds.md) — what it counts, who decides
its size, what it protects, what happens at the limit, how you find out. And two numbers
that must agree agree in code, not in a comment:
```zig
comptime {
if (maximum_domains != devices_broker.maximum_devices)
@compileError("iommu.confined is indexed by device id; an id past its end is " ++
"left unconfined while confineDevice still reports success");
}
```
## The one that must not wait
[`iommu.zig:107`](../system/kernel/iommu.zig:107) — `if (device_id >= confined.len) return
true;` — returns *success* without confining. It is unreachable today only because
device ids stop at 64. **Phases 3 and 4 both change the device count, and either makes
it live.** Fix it before them: out of range must refuse, never allow. (I2)
This is also the standing rule the audit argues for: at a bound, the safe direction is
refusal. A ceiling that fails open is not a limit, it is a switch that turns the
protection off.
## How this is verified
- The QEMU suite is the arbiter at every step; it is 114 cases and must stay green.
- Each fix lands with a test that **fails before it** — as the idempotency reorder did,
where exactly one assertion flipped.
- Adversarial cases for I1–I3 specifically: the audit's six real defects were all found
by asking "what would an attacker do", and the suite had never asked.
- The Ryzen is the acceptance test. It is the machine that found this, and the one that
proves it fixed.
## Sequencing
Phase 1 gates everything. Phase 2 gates phase 3 — the inventory cannot move until
authority is sound, or moving it is the hole. Phase 4 is independent and its user-space
items are the safest work in the track. Phase 5 is the record of what survived.
The IOMMU fail-open is fixed before phase 3 or 4 touches the device count.
+20
View File
@@ -182,6 +182,26 @@ test for "is this an abbreviation I must expand" is simply: *is there a longer w
is a clipped form of?* If yes, write the word. If it's an initialism standing in for a
phrase, leave it.
## Kernel code touches user memory only through `user-memory`
A syscall argument is an attacker-controlled integer. Kernel code never
dereferences one: every read of a process's memory goes through
`copyFromUser` and every write through `copyToUser`
(`system/kernel/user-memory.zig`), which walk that address space's page tables
and move the bytes through the physmap, with the permissions ring 3 itself
would face. A bad pointer then fails the call instead of faulting the kernel,
and a struct pulled in once cannot change underneath the checks that follow it.
This is not a review convention — CR4.SMAP enforces it in hardware
(`docs/os-development/smep-smap.md`), so a raw dereference of a user address is
a #PF with a kernel instruction pointer the first time the QEMU suite reaches
it. Which is also why **there is no `stac` in this tree, and never should be**:
`stac` suspends exactly that enforcement, the copy layer needs no such window
by construction, and a change that adds one has removed the guarantee rather
than worked around a limitation. The same goes for the boot-time `clac` patch
at the interrupt entry — it exists so that ring 3 cannot suspend SMAP either,
by taking an interrupt with `EFLAGS.AC` set.
## Zen of Zig
* Communicate intent precisely.
@@ -64,19 +64,61 @@ restarted instance to rebuild exactly the same ids.
## The protocol
A `device-manager-protocol` module (the vfs-protocol pattern): extern-struct
messages, a version in the handshake, reserved fields everywhere. The manager is a
well-known endpoint (`ipc.register(.device_manager)`); the badge tells it who is
A `device-manager-protocol` module, defined through the
[envelope](../os-development/protocol-namespace.md): every packet — request,
reply, and pushed event alike — begins with the folded `Header`, and **the device
id is `Header.target`**, the manager's object addressing. The contract is bound at
`/protocol/device-manager`; the kernel-stamped badge tells the manager who is
talking; the same endpoint receives its children's exit notifications — one loop,
one world.
| Direction | Message | Purpose |
| Direction | Packet | Purpose |
|---|---|---|
| driver → manager | `hello { version, role, device_id }` | confirms the argv assignment, starts the deadline clock |
| bus → manager | `child_added { parent, bus_address, identity, device_id, hid }` | one node the bus discovered |
| driver → manager | `hello { role, wants_channel, version }` @ the assigned device | confirms the assignment, starts the deadline clock — **and moves the channels** (below) |
| bus → manager | `child_added { parent, bus_address, identity, bus, vendor, device, subsystem, hid }` @ the registered device id | one node the bus discovered |
| bus → manager | `child_removed { parent, bus_address }` | unplug, or the bus lost it |
| app → manager | `enumerate` | snapshot of the tree (read-only) |
| app → manager | `subscribe` | receive published add/remove events |
| app → manager | `enumerate` (reserved verb 1) @ start index | one page of the tree, one `ChildEntry` per record in the reply's tail; a short page is the end |
| app → manager | `subscribe` (reserved verb 2) | receive published add/remove events; the subscriber's endpoint rides as the call's capability |
| manager → app | `child_added` / `child_removed` events | the same two structs, pushed rather than called |
**`hello` is also the establishment plane for driver-layer channels**
([communication.md](../os-development/communication.md) "Establishment: two
planes, one namespace"). A provider's hello carries its serving endpoint UP as
the call's capability (the xHCI bus its transfer endpoint, usb-storage its
block endpoint — several processes provide those contracts, so neither is ever
a registry name). A hello with `wants_channel` set is answered with a
capability DOWN: for a `.device`-role driver, the channel of its device's
*reporter* (a class driver reaching its own controller); for a `.consumer`
(not a spawned driver at all — fat looking for its volume), the channel of the
driver *bound to* the target device. No channel in an acked reply means the
provider is mid-restart and its re-report is on the way — retryable, never a
verdict.
The watcher table behind those last two rows is the **service harness's**
(`service.Subscribers`, shared with input and power), not the manager's: it
answers `subscribe`/`unsubscribe`, frames each event once for the fan-out, and
sweeps a watcher on its exit notification — where the manager previously had no
sweep for watchers at all. Its own supervised-driver exits are a different thing
and unchanged, except that a driver's death now arrives twice (the manager is
both its supervisor and a subscriber to published exits), so the manager retires
a dead driver's process id as it handles the first and the second finds nothing
to act on.
Two of what used to be the manager's own operations are the envelope's **reserved**
verbs, which mean the same thing at every provider in the system, so this protocol
numbers only three of its own (`hello` = 16, `child_added` = 17,
`child_removed` = 18) and its two events in their own space (`child_added` = 16,
`child_removed` = 17). No reply carries a status field: that is the `Status` every
reply begins with.
`child_added` is the one struct that travels both ways — a bus *calls* it, the
manager *pushes* it — which is why the operation and event numbering spaces are
separate: one encoding, both directions, told apart by which way the packet went.
Folding the operation byte and the device id out of it is also what makes it fit:
a pushed event is 64 bytes at most, header included, and this one lands exactly on
that floor. `child_removed` is the single message whose target stays 0, because it
is addressed by the composite (parent, bus address) and no single `u64` carries a
pair.
`hello` is the one deadline the manager enforces itself: spawned and silent past the
deadline means wrong binary, wrong protocol version, or wedged before main — apply
@@ -84,10 +126,11 @@ the stop sequence and the restart policy. Everything else lifecycle-shaped
(terminate, the common `ping` liveness call, exit reasons) arrives through
[process-lifecycle.md](../os-development/process-lifecycle.md)'s vocabulary, not this protocol.
Assignment stays argv (`usb-xhci-bus <device id>`) for now — simple, and it works.
The step after `hello` exists is delegation: the manager claims (or is granted) the
devices and passes the claim to the driver over IPC (the M13 capability-transfer
mechanism), replacing first-come-first-served `device_claim` with policy. Identity in
Delegation is BUILT (docs/os-development/device-authority.md "As built"): the
device arrives WITH the spawn — `system_spawn`'s sixth argument moves the
claim before the child's first instruction — and the id still rides argv for
the driver to name itself by. A given device is a loan that returns to the
manager on the holder's death. Identity in
`child_added` is per-bus: PCI children carry the class triple (`pci_class`, as the
xHCI match already uses); USB children carry the (class, subclass, protocol) triple
from usb-ids.zig — each bus's native language, decoded by the shared ids modules.
@@ -104,13 +147,19 @@ On a death notification:
Clean exit → it meant to; don't restart. Fault or missed `hello` deadline →
restart with **backoff**, and a crash-loop cap (three fast deaths → mark failed,
stop respawning, log loudly; a later `reload` to the manager can retry).
2. **Prune the subtree** the dead bus driver reported. Its children describe
protocol state (xHCI slot ids, transfer rings) that died with the process;
keeping the nodes would be keeping a lie. Watchers receive `child_removed` — the
input service losing, then regaining, a keyboard is the *honest* description of
what happened. The restarted instance rediscovers and re-reports.
3. **The claim is already free** because the kernel released it at death — the
restarted instance claims the same controller and comes up.
2. **Prune the subtree** the dead bus driver reported, **reaping the class
drivers bound to its children**. Its children describe protocol state (xHCI
slot ids, transfer rings) that died with the process; keeping the nodes
would be keeping a lie — and the class drivers hold channels into the dead
process they cannot observe dying (an HID driver blocks on reports that
simply never come). Each is killed and its entry cleared, so the matcher
can respawn a fresh generation when the re-report arrives; their hellos
fetch the successor's channel. Watchers receive `child_removed` — the input
service losing, then regaining, a keyboard is the *honest* description of
what happened.
3. **The device is already back** because the loan returned at death — the
manager re-delegates the same controller with the respawn, and the kernel
confines it afresh.
Who supervises the supervisor: **init** (PID 1), which already supervises the
services it starts. If the manager dies, drivers keep running (they hold their
+16 -2
View File
@@ -106,8 +106,10 @@ The bring-up sequence mirrors a hardware driver's — it is the
[`usb-xhci-bus` `initialise`](../../system/drivers/usb-xhci-bus/usb-xhci-bus.zig) shape
(claim → `mmio_map` → run loop) — and the request/reply service shell is the
[FAT](../../system/services/fat/fat.zig) / [input](../../system/services/input/input.zig) shape
([`service.run`](../../library/kernel/service.zig) with a `protocol.zig` of
`extern struct` messages and an `Operation` tag).
([`service.run`](../../library/kernel/service.zig) over the dispatch table its
protocol module generates through
[`envelope.Define`](../os-development/protocol-namespace.md) — one request and
reply type per verb, and the layer id in the packet header's `target`).
**One process, for now.** v1 is a *single* service that both owns the framebuffer and
composites — it does not split a "framebuffer driver" from a "compositor" the way input
@@ -209,6 +211,18 @@ shell, a terminal, a cursor, and a wallpaper:
| `damage` | mark a region of a layer dirty |
| `present` | request a repaint: composited at the next frame-clock tick |
**A layer belongs to the client that created it.** The id is a slot in a
sixteen-entry table — small, dense, guessable — so every verb above that names one is
answered only for the task whose `create_layer` produced it, and a layer that is
somebody else's is refused exactly as one that never existed (`-ENOENT`), so a client
cannot use the refusal to learn which ids are live
([protocol-namespace.md](../os-development/protocol-namespace.md): handles are scoped
per client, validated against the badge). The compositor's own layers — the cursor
sprite and the startup self-check's pair — are marked service-owned and are created by
direct call rather than over the protocol, so no client can move or destroy the
cursor. A dead client's layers are released on its exit notification, the same sweep
the FAT server runs for open files.
Text is intentionally *not* an operation — a client renders glyphs by blitting tiles
(the [PSF font](../../system/kernel/font.psf) path the console already uses can move into a
client). Keeping the protocol to rectangles and tiles keeps the compositor small and the
+35 -12
View File
@@ -22,12 +22,22 @@ event:
- `JoystickEvent` — `axis` moves (a signed value on a `control` index) and
`button_down`/`button_up`.
All three travel in one **`InputEvent` envelope** tagged with a `DeviceKind`, so the
fan-out is a single code path and a subscriber can take a mix of classes on one stream.
Decode an envelope with `asKeyboard()` / `asMouse()` / `asJoystick()` (each returns null
unless the tag matches). A subscriber names the classes it wants with a **`device_mask`**,
and the service routes each event only to subscribers whose mask includes its class — so a
mouse-only listener never wakes for keystrokes.
A source publishes any of the three as one **`InputEvent`** tagged with a `DeviceKind`, so
`publish` is a single verb; decode one with `asKeyboard()` / `asMouse()` / `asJoystick()`
(each returns null unless the tag matches). On the *delivery* wire the class is the
packet's own operation instead — the protocol declares one event per class
([protocol-namespace.md](../os-development/protocol-namespace.md)), so a pushed packet is
the 16-byte header plus the typed event and nothing carries a tag twice. The client
helpers re-tag what arrives back into an `InputEvent`, so a subscriber can still take a
mix of classes on one stream. A subscriber names the classes it wants with a
**`device_mask`**, and the service routes each event only to subscribers whose mask
includes its class — so a mouse-only listener never wakes for keystrokes.
**`subscribe` is not this protocol's verb.** Its shape — a synchronous call whose attached
capability is the subscriber's own endpoint — is what the envelope's *reserved* subscribe
means at every provider in the system, so the input protocol adopts it rather than
defining a second spelling of the same thing. The interest mask rides as the packet's
tail. `publish` is the one verb the protocol defines for itself.
## Why this needed a new kernel primitive
@@ -98,12 +108,25 @@ This is the async counterpart of `ipc_call`, and the input service is its first
`publishJoystickEvent`. Publishing is a short synchronous `ipc_call` the service answers at
once; the service's own fan-out is asynchronous, so publishing never blocks on a slow
subscriber.
- The **service** ([input.zig](../../system/services/input/input.zig)) keeps a small subscriber
table (endpoint handle + owning task id + `device_mask`). On `publish` it `ipc_send`s the
event to every subscriber whose mask includes the event's device class. On `subscribe` it
stores the passed capability and mask and, as housekeeping, prunes any slot whose owning
process has exited (checked against `process_enumerate`) — not for correctness (an async
send to an orphaned endpoint is harmless) but to reclaim the slot.
- The **service** ([input.zig](../../system/services/input/input.zig)) owns none of that
machinery any more: the subscriber table (endpoint handle + owning task + interest mask),
the reserved `subscribe`/`unsubscribe` verbs, the fan-out, and the dead-subscriber sweep
are the shared harness's (`service.Subscribers` in
[service.zig](../../library/kernel/service.zig)), so every event stream in the system has
identical semantics. What is left in this file is what is actually about input: which
class an event belongs to, and which classes a subscriber asked for. On `publish` it names
the event's class and the harness `ipc_send`s the packet — framed once — to every
subscriber whose mask includes it.
- **A dead subscriber goes away on its exit notification**, not on a poll. The service used
to walk `process_enumerate` on every subscribe and drop slots whose owner had gone; it now
subscribes to the kernel's published exits like the FAT server and the compositor do
([process-lifecycle.md](../os-development/process-lifecycle.md)), which reclaims the slot
*and* closes the endpoint capability in it promptly rather than at the next subscribe.
(The fan-out also drops a subscriber whose `ipc_send` fails, as a backstop for a
notification a full ring dropped.)
- The service runs on the shared harness like every other, so it answers the universal ping
and exits on `terminate`; it was the last hand-rolled receive loop in the tree, and the
last service a shutdown had to kill rather than ask.
Publisher and subscriber must be **separate processes**: a single thread that both
published and serviced its own subscription would deadlock (its `publish` call blocks until
+122
View File
@@ -0,0 +1,122 @@
# Establishment planes: the plan
*2026-08-09. The design is settled in
[communication.md](os-development/communication.md) ("Establishment: two planes, one
namespace"): driver-layer channels stop being registry names and are routed at
establishment by the device manager, which owns the topology. This converts both live
seams — `usb-transfer` and `block` — in one flag-day, and fixes the restart hole the
scoping audit found on the way. Found by a real machine: three xHCI controllers, one
name, a mouse nobody could reach.*
**Non-goals, stated up front.** fat stays single-volume (multi-volume mounting, volume
identity/content-probing, and fat's own reconnection after a storage restart are the
M21 remount track). The input service's last-writer-wins button mask across two mice
is a known quirk, not part of this change. Nothing here touches the app-facing names —
`input`, `display`, `ufs` keep their exclusive registry binds.
## What the scoping reads established
- **Capabilities already travel both directions of a synchronous call, and only
there.** Request-direction via `ipc.callCap` (r9 → `shareCapability` at server
dequeue, a refcounted copy); reply-direction via `ipc_reply_wait`'s `send_cap`
(surfaces as the client's `Reply.cap`) — init's registry is the working in-tree
precedent (`pending_capability`). Pushes structurally cannot carry one. **No kernel
change is needed.**
- **The one mechanism gap is the service harness**: `service.run` hardcodes the reply
capability to null and `Answer` has no capability slot; the device manager runs on
that harness. It needs a reply-cap out-slot following init's pattern, with null
staying the untouched default for every other service.
- **The manager already stores the routing fact**: `Child{parent, bus_address,
device_id, reporter}` — consumer's device id → `children[].reporter` →
`driverByProcess(reporter)` → the (new) stored endpoint. `Hello.role` (.bus vs
.device) already exists on the wire to distinguish provider hellos (cap up) from
consumer hellos (cap down); the manager currently never reads it.
- **The restart hole (new finding):** today, when a bus instance dies, its class
drivers are zombies — HID drivers block forever on interrupt reports that will
never come, usb-storage answers fat with errors forever; the manager respawns
neither, and the matcher's dedupe actively prevents a respawn on re-report. The
user's core goal is restart-a-driver-live; this plan closes the hole.
- **Blast radius:** every QEMU case boots from USB storage, so this seam failing
fails the whole suite, and the load-bearing serial markers (`fat: mounted
/volumes/usb`, `usb-storage: ready`, `fat-test: ok`) must not change.
## P0 — mechanics (library + manager, no behavior change yet)
1. **Harness reply-capability out-slot.** A handler nominates a capability for its
reply (init's `pending_capability` idiom moved into `service.run`'s loop); default
null; the existing Arrival take/release ownership discipline is unchanged. Every
other service compiles and behaves identically.
2. **`driver.hello` grows both directions.** Provider form: carry the caller's
serving endpoint up (`ipc.callCap`). Consumer form: return `Reply.cap`. One call
can do both (a storage driver hands its block endpoint up and receives its bus
channel down in the same hello).
3. **Manager stores and routes.** `Driver` gains an endpoint field; the cap is
claimed at `onMessage` level (the `capability_claimed` pattern usb-xhci-bus
already uses — the harness's private claim flag composes, verified). `onDriverExit`
**must** `ipc.close` the stored handle (a dead owner's endpoint survives as a
refcounted slot; repeated restarts would exhaust the manager's 32-slot table —
boot-fatal). Consumer hello with an unknown device id (bus died, not yet
re-reported) gets a *retryable* refusal, never a permanent one.
## P1 — the usb-transfer seam
- Bus: delete the `bindPatiently("usb-transfer")` block and its serve-unnamed
fallback; hello carries the endpoint up.
- `usb.open(device_id)` takes the channel from the class driver's hello instead of
the name lookup; retry patience stays ≥ today's window (the provider's hello
precedes the consumer's spawn in the normal order — the retry covers respawn races).
- usb-storage's *consumer* side uses the same lineage (its own device id).
- `protocol.csv`: delete the bind row (67) and the three open rows (119/120/122) in
the same commit as the code — grants and code move together or the old path dies
silently first.
- Fixtures: conformance table row, the usb-report kernel-side registry spawn.
## P2 — the block seam
- usb-storage: drop `.service = "block"` (the field is optional; the harness serves
nameless — pci-bus and logger already do); its `initialise` keeps the endpoint it
currently discards and hellos it up. Exit-code contract preserved: device absent =
clean exit (no restart), device-present failure = exit(1) (restart with backoff) —
establishment failure is the latter, never a silent pre-hello death like today's
second-stick `-EBUSY`.
- fat: `block.tryOpen`'s name lookup becomes manager-routed — enumerate, find the
block-class provider, hello for its channel. One volume: unambiguous. Two volumes:
fat takes the first by device-id order — deterministic within a boot, and no worse
than today's bind race; choosing *the boot volume* by content is deferred to M21
(risk noted: `/system/configuration` and `/system/logs` mounts ride this choice).
- fat gets a `protocol.csv` open grant for `device-manager`; rows 68/99 die.
- Delete `block.open` (zero callers, dead code).
## P3 — restart integrity (the zombie fix)
- **A reporter's death reaps its subtree.** When a bus/storage instance dies, the
manager already prunes its children; now it also kills the class drivers spawned
for those children and clears their entries, so the matcher's dedupe stops blocking
the respawn. On re-report (ids are stable — the `P<port>I<iface>` registration
identity), the matcher spawns fresh class drivers, which hello and receive the
successor's channel. Restart a bus driver live: the subtree rebuilds itself.
- usb-storage on `-EPEER` from its bus: exit(1) → supervisor restart with backoff →
fresh hello. (fat's own reconnection: M21.)
- Extend the existing bus-restart drill (`test-usb-restart`, the usb-report case) to
assert the subtree *works* after the restart — a post-restart keyboard event, not
just a re-report. **Discrimination: today that assertion fails (zombie).**
## P4 — the multi-instance proof
- New QEMU case: **two xHCI controllers**, keyboard on one, storage on the other;
assert both class drivers come up and function. **Discrimination: without the
conversion this case fails exactly like the Ryzen mouse** (second controller's
child unreachable). This is the machine's bug, pinned in the suite forever.
- Full suite green; the four existing second-controller cases (usb-hub and friends)
re-checked against their expectations.
- Docs updated with the code: device-manager.md, drivers.md (hello), the usb-transfer
and block protocol docblocks, device-authority.md as-built appendix.
## Order and verification discipline
P0 → P1 → P2 → P3 → P4, one commit per coherent step, suite green at every phase
boundary (P0 and P1 may share a verification run — P0 alone changes no behavior).
Every new test must be shown to fail against the old behavior before it counts
(the discrimination rule). One QEMU suite at a time. The Ryzen re-test at the end is
the acceptance run: mouse moves, and killing one bus instance from a shell one day
only blinks the devices on that controller.
+115 -72
View File
@@ -6,7 +6,10 @@
> serves it directly (the read-only /system initrd mount, via `fs_node`) or
> redirects the caller to the owning backend's endpoint plus the rewritten
> mount-relative path — after which the client speaks THIS protocol to the
> backend, unchanged. The Zig source of truth is `library/protocol/vfs/vfs-protocol.zig`
> backend, unchanged. Since P4a the contract is expressed through
> `envelope.Define` (docs/os-development/protocol-namespace.md), so every
> packet begins with the universal 16-byte prefix and the open-node id rides
> in it. The Zig source of truth is `library/protocol/vfs/vfs-protocol.zig`
> (the `vfs-protocol` module), whose unit test pins a sample of the sizes
> and values below. This page is the **language-neutral wire specification**
> of that contract — what a Rust or C client implements ([vdso.md](../os-development/vdso.md)
@@ -22,12 +25,17 @@ also hands back the path rewritten relative to the mount — not from a
registry lookup. (Service id 1, the old userspace router, is retired.)
- A message is at most **256 bytes** (`message_maximum`).
- A request is a fixed 32-byte **Request** header followed by an inline
payload of at most **224 bytes** (`maximum_payload`) — a path, or write
bytes. There is no multi-message request: paths and single reads/writes
must fit, and larger transfers loop (see *read* / *write*).
- A reply is a fixed 24-byte **Reply** header followed by an inline payload —
read bytes, a `FileStatus`, or a `DirectoryEntry`.
- Every packet begins with the 16-byte **envelope prefix**
([protocol-namespace.md](../os-development/protocol-namespace.md)): a
`Header` on a request, a `Status` on a reply. The prefix is **folded, not
stacked** — the verb and the object being addressed live in it, and no
request or reply below repeats either.
- A request is the header, then the verb's own fixed part (0–16 bytes), then
an inline tail of at most **224 bytes** (`maximum_payload`) — a path, or
write bytes. There is no multi-message request: paths and single
reads/writes must fit, and larger transfers loop (see *read* / *write*).
- A reply is the status, then the verb's own fixed part, then an inline tail
— read bytes, or a directory entry's name.
- All integers are **little-endian**; layouts are C layout for x86-64
(`extern struct`), offsets given below so nothing need be inferred.
@@ -37,91 +45,108 @@ With clients holding backend node ids directly, a backend records each open
handle's owner and sweeps a dead client's handles via the published process
exit events.
## Request header — 32 bytes
## Request header — 16 bytes
The envelope's `Header`, identical in every danos protocol:
| offset | size | field | meaning |
|-------:|-----:|-------|---------|
| 0 | 4 | `operation` | an **Operation** value (below) |
| 0 | 4 | `operation` | an **Operation** value (below); 0–15 are the reserved universal verbs |
| 4 | 4 | — | padding |
| 8 | 8 | `node` | the server-side open-node id from a prior `open`; 0 for path-based operations |
| 16 | 8 | `offset` | byte position for read/write; entry index (cursor) for readdir; else 0 |
| 24 | 4 | `len` | payload length for path/write operations; requested byte count for read |
| 28 | 4 | `flags` | open flags (below); else 0 |
| 8 | 8 | `target` | **the open-node id** from a prior `open`; 0 for `open` itself and the path-based verbs |
## Reply header — 24 bytes
## Reply header — 16 bytes
The envelope's `Status`:
| offset | size | field | meaning |
|-------:|-----:|-------|---------|
| 0 | 4 | `status` | **0 = success**, negative = failure (signed) |
| 4 | 4 | — | padding |
| 8 | 8 | `node` | the new open-node id (for `open`); else 0 |
| 16 | 4 | `len` | reply payload length in bytes |
| 20 | 4 | — | padding |
| 8 | 4 | `len` | reply bytes following this header: the verb's fixed part plus its tail |
| 12 | 4 | — | padding |
On failure the backend replies `status = -1`, and that reply reaches the
client directly — there is no party between them on the wire. (Kernel-served
paths produce no wire replies at all: `fs_resolve`/`fs_node` failures are
syscall register statuses.) A richer errno vocabulary is future work —
clients must treat *any* negative status as failure, not match on -1.
A failing backend replies with the status alone (`len` = 0) and no fixed
part, and that reply reaches the client directly — there is no party between
them on the wire. (Kernel-served paths produce no wire replies at all:
`fs_resolve`/`fs_node` failures are syscall register statuses.) The errno
vocabulary is the kernel's, continued by the envelope: `ENOENT` = 4 is what a
backend answers for anything it cannot find or cannot do, `ENOSYS` = 10 for a
verb it does not implement, `EPROTO` = 11 for a packet shorter than the verb
it names. Clients must treat *any* negative status as failure rather than
matching a particular one.
## Operations
Values are append-only and never renumbered (the same evolution rule every
danos protocol follows). Send only values from this table: the shipped server
decodes the operation into an exhaustive enum, so an out-of-range value is
not answered with a `status = -1` reply — it trips a safety check in safe
builds and is undefined otherwise. (The `-1` replies cover recognised but
refused operations, such as `mount` sent to a backend.)
Values number from 16 (`first_protocol_operation`) in declaration order, and
are frozen once shipped. Values 0–15 are the envelope's reserved universal
verbs, which mean the same thing at every provider in the system: `describe`
(0) answers the protocol's name and version and is implemented by the
envelope itself, so every backend answers it. A verb outside this table is
answered `-ENOSYS`; it is never a safety check any more, because the
dispatch compares numbers rather than decoding an enum.
| value | operation | request payload | reply |
|------:|-----------|-----------------|-------|
| 0 | `open` | the path (`len` = its length), `flags` as below | `node` = open-node id |
| 1 | `close` | — (`node` set) | status only |
| 2 | `read` | — (`node`, `offset`, `len` = wanted count) | `len` bytes read, payload = the bytes; `len` 0 at end of file |
| 3 | `write` | the bytes (`node`, `offset`, `len` = count) | `len` = bytes accepted (may be short — loop) |
| 4 | `status` | — (`node` set) | payload = **FileStatus** (24 bytes) |
| 5 | `readdir` | — (`node` = a directory, `offset` = cursor) | payload = one **DirectoryEntry** + name; `len` 0 at end |
| 6 | `mount` | the mount-point path; the backend endpoint rides as the call's **capability** | status only |
| 7 | `unmount` | the mount-point path | status only |
| 8 | `mkdir` | the path | status only |
| 9 | `unlink` | the path | status only |
| 10 | `rename` | old path, one `0x00`, new path (`len` = total) | status only |
Each row's *request* and *reply* name the bytes **after** the 16-byte prefix.
| value | operation | request | tail | reply | reply tail |
|------:|-----------|---------|------|-------|-----------|
| 16 | `open` | `flags` (4 bytes, below) | the path | `node` (8 bytes) = the open-node id | — |
| 17 | `close` | — | — | — | — |
| 18 | `read` | `offset` (8), `len` (4) = wanted count | — | — | the bytes read; `Status.len` 0 at end of file |
| 19 | `write` | `offset` (8), `len` (4) = count | the bytes | `count` (4) = bytes accepted (may be short — loop) | — |
| 20 | `status` | — | — | **FileStatus** (24 bytes) | — |
| 21 | `readdir` | `cursor` (8) | — | one **DirectoryEntry** (16 bytes) | the name |
| 22 | `mount` | — | the mount-point path; the backend endpoint rides as the call's **capability** | — | — |
| 23 | `unmount` | — | the mount-point path | — | — |
| 24 | `mkdir` | — | the path | — | — |
| 25 | `unlink` | — | the path | — | — |
| 26 | `rename` | — | old path, one `0x00`, new path | — | — |
| 27 | `bind` | — | the contract name; the provider's endpoint rides as the call's **capability** | — | — |
Notes per operation:
- **open** — the path is the mount-relative path `fs_resolve` handed back
(absolute-shaped: `/notes.txt` under fat's `/mnt/usb` mount). Bare names
(absolute-shaped: `/notes.txt` under fat's `/volumes/usb` mount). Bare names
(`greeting`) resolve nowhere — the flat ramfs is retired, and `fs_resolve`
refuses non-absolute paths. The returned `node` is the *backend's* own
open-node id: with the router in the kernel there is no forwarding table,
and clients hold backend ids directly (see *Lifetimes and trust*).
and clients hold backend ids directly (see *Lifetimes and trust*). Every
later packet carries it in `Header.target` — the path is spoken once, here,
and integers do the rest.
- **read / write** — a single exchange moves at most 224 bytes
(`maximum_payload`); the client loops, advancing `offset` by the returned
`len`, until done (read) or the slice is written (write). A `write` reply
shorter than requested is progress, not an error; a `len` of 0 means no
forward progress — stop rather than spin.
- **readdir** — `offset` is a **cursor: the entry index**, not a byte
position. Each call returns exactly one entry; the client increments the
cursor by 1. A reply with `len` 0 is end-of-directory. The directory must
have been opened with the `directory` flag.
(`maximum_payload`); the client loops, advancing its own offset by what
came back, until done (read) or the slice is written (write). A `write`
reply shorter than requested is progress, not an error; a count of 0 means
no forward progress — stop rather than spin.
- **readdir** — `cursor` is the **entry index**, not a byte position. Each
call returns exactly one entry; the client increments the cursor by 1. **A
`name_len` of 0 is end-of-directory** — the reply's own length cannot say
so, because the envelope always sends the fixed reply part. The directory
must have been opened with the `directory` flag.
- **mount / unmount** — RETIRED from the wire: mounting is the `fs_mount`
syscall now (a filesystem server passes its endpoint handle; possession is
the capability, exactly the trust of the old cap-passing op). The op
the capability, exactly the trust of the old cap-passing op). The verb
numbers stay reserved. Mount-prefix semantics are unchanged: prefixes
match at path boundaries only (`/mnt/usb` never captures `/mnt/usbextra`),
the longest matching prefix wins, and an optional backend-side rewrite
prefix maps a mount into the backend's namespace (fat serves `/mnt/usb`
from its volume root and `/var` from its `/var` subtree).
match at path boundaries only (`/volumes/usb` never captures
`/volumes/usbextra`), the longest matching prefix wins, and an optional
backend-side rewrite prefix maps a mount into the backend's namespace (fat
serves `/volumes/usb` from its volume root and `/system/logs` from its
`/system/logs` subtree).
- **rename** — same-directory rename only: the backend compares the old and
new parent paths and refuses a mismatch. The client (`file_system`) refuses
earlier when the two paths resolve to different backend endpoints, but that
check is coarser than "one mount" — one endpoint can serve several mounts
(fat serves `/mnt/usb` and `/var`), so a cross-mount rename reaches the
backend and fails on its same-directory check.
(fat serves `/volumes/usb`, `/system/configuration` and `/system/logs`), so
a cross-mount rename reaches the backend and fails on its same-directory
check.
- **bind** — the protocol registry's claim verb, implemented only by the
synthetic `/protocol` backend inside PID 1
([protocol-namespace.md](../os-development/protocol-namespace.md)). A file
backend answers `-ENOSYS`.
## Open flags
Bitwise OR in `Request.flags`, meaningful for `open` only:
Bitwise OR in `open`'s `flags`, meaningful for `open` only:
| bit | name | meaning |
|----:|------|---------|
@@ -129,7 +154,7 @@ Bitwise OR in `Request.flags`, meaningful for `open` only:
| 2 | `directory` | open a directory node for `readdir` rather than a file |
| 4 | `truncate` | truncate an existing file to zero length on open (replace, don't overwrite in place) |
## FileStatus — 24 bytes (the `status` reply payload)
## FileStatus — 24 bytes (the `status` reply's fixed part)
| offset | size | field | meaning |
|-------:|-----:|-------|---------|
@@ -138,12 +163,12 @@ Bitwise OR in `Request.flags`, meaningful for `open` only:
| 12 | 4 | — | padding |
| 16 | 8 | `mtime` | modification time, Unix epoch seconds UTC; 0 if the backend keeps none |
## DirectoryEntry — 16 bytes + name (the `readdir` reply payload)
## DirectoryEntry — 16 bytes + name (the `readdir` reply)
| offset | size | field | meaning |
|-------:|-----:|-------|---------|
| 0 | 4 | `kind` | a **NodeKind** value |
| 4 | 4 | `name_len` | length of the name that follows |
| 4 | 4 | `name_len` | length of the name that follows; **0 means end of directory** |
| 8 | 8 | `size` | the entry's size in bytes |
| 16 | `name_len` | name | the entry's name, not NUL-terminated |
@@ -174,7 +199,7 @@ volumes, reserved) remain part of the design.
## An open reply may carry a capability
`open` rides `ipc_call`, whose reply direction can hand back an endpoint
capability alongside the `Reply` header. A file backend never uses it — FAT
capability alongside the reply. A file backend never uses it — FAT
answers with a node id and nothing else — but a **synthetic** backend does:
opening a `protocol` node returns the provider's endpoint, and possession of
that endpoint *is* the channel. The convention is per-backend, not
@@ -187,10 +212,24 @@ Open-node ids live in the backend. A client that dies without closing leaks
nothing permanently: the backend (the FAT server) subscribes to the kernel's
published process-exit events (docs/process-lifecycle.md) and releases a dead
client's handles. The kernel VFS root needs no sweep at all — its node tokens
are permanent for a boot and carry no open state. Ids are plain integers, not
capabilities — a backend trusts its callers with each other's ids today, which
is acceptable while every client is part of the system image and worth
revisiting (per-client id namespaces) before third-party binaries arrive.
are permanent for a boot and carry no open state.
Ids are plain integers rather than capabilities, so the backend **scopes them
to the caller's badge**: an open node belongs to the task that opened it, and
every verb that names one — read, write, status, readdir, close — is answered
only for that task. A node id is a small number drawn from a table of
thirty-two, trivially guessable, and until this rule a backend honoured every
client's ids from every other client
(docs/os-development/protocol-namespace.md: *handles must be scoped per
client — validated against the badge, or drawn from a per-client id
namespace*).
The refusal is deliberately **identical to absence**: a node that is somebody
else's answers `-ENOENT`, exactly as one that was never opened, so a prober
learns nothing about which ids are live — the same discipline the protocol
namespace applies to a refused open. The owner is a *task*, because the badge
is: a threaded client uses a node from the thread that opened it, which is
already the granularity of the exit sweep that releases it.
## Evolution rules
@@ -198,11 +237,15 @@ What a non-Zig implementation may rely on, and what it must not:
- Operation values, flag bits, `NodeKind` values, and struct layouts are
**append-only and frozen once shipped**. The unit test in
`library/protocol/vfs/vfs-protocol.zig` pins a sample of them (the `DirectoryEntry`
size, `NodeKind` 0–1 and 6–7, `Operation` values 0, 4 and 5); this page is
the full record of the frozen values.
`library/protocol/vfs/vfs-protocol.zig` pins a sample of them (the
`DirectoryEntry` size, `NodeKind` 0–1 and 6–7, `Operation` values 16–21, 26
and 27); this page is the full record of the frozen values.
*The one renumbering this contract has had was the rebase onto the envelope
(P4a), which moved every verb above the reserved range — a deliberate
flag-day across a system with no third-party clients yet, not a precedent.*
- The 256-byte message ceiling is a property of the current IPC transport,
not a promise; clients should read `maximum_payload`-shaped limits from the
reply lengths they actually get (loop-until-done), not hard-code 224.
- Negative statuses beyond -1 will appear (an errno vocabulary); success is
exactly 0.
- Success is exactly 0, and the negative statuses come from one system-wide
errno vocabulary (the kernel's, continued by the envelope) rather than from
this protocol.
+403
View File
@@ -0,0 +1,403 @@
# Fixed-bounds audit
*2026-08-07. A tree-wide audit of every compile-time ceiling on a runtime quantity,
commissioned after an AMD Ryzen desktop booted to a working compositor with no USB
and no storage. Seven parallel sweeps, adversarial verification of each finding, and
a completeness critic. 235 bounds confirmed.*
The audit was not commissioned to fix that machine. It was commissioned to answer a
different question: **why did a machine have to find this?** The answer is in the
first table below, and it is not that anyone failed to predict an AMD desktop.
## What the audit found
| | |
|---|---|
| Bounds confirmed | **235** |
| Decided by hardware or external data, not by us | **139** (59%) |
| Recorded in `system/parameters.zig` | **5** (2%) |
| With no comment explaining the number at all | **97** (41%) |
| Silent when exceeded — no log, no counter, no error | **171** (73%) |
| Severity critical / high | **17 / 26** |
The project has a stated convention: tunables live in `system/parameters.zig` with
their reasoning attached. Two percent of them do. That is the finding — not any
individual number.
And 59% of these are not tunables at all. They are guesses about someone else's
computer: how many PCI functions a board has, how many SSDTs its firmware ships,
how many descriptors its memory map carries, how many interfaces a USB headset
declares. A fixed bound on a quantity the machine decides is not a knob. It is a
defect with a plausible-looking number in it.
## Why "raise the number" is not available
This is the part that matters most, and it was found by the completeness critic
rather than by any of the seven sweeps.
`system/kernel/iommu.zig:97` sizes the per-device confinement table by
`maximum_domains = 64` — "64 mirrors devices-broker's device cap" — and indexes it
by **device id**. Line 107:
```zig
pub fn confineDevice(device_id: u64, bdf: u16, owner: u32) bool {
if (!active) return true;
if (device_id >= confined.len) return true; // unusual id; leave it to fail-open
```
It returns `true` — success — without confining the device. The doc comment three
lines above states the opposite invariant: *"a claim that can't be confined must not
stand."*
Device ids are assigned `d.id = count` with `count < maximum_devices`, so today ids
run 0–63 and that branch is unreachable. **It becomes reachable the moment
`maximum_devices` is raised above 64.** Every device with id ≥ 64 would then be
claimed by a ring-3 driver, reported as successfully confined, and left outside every
IOMMU domain — an unconfined DMA master with a driver holding it.
So the one-line fix for the Ryzen — raise 64 to 512 — is a privilege escalation. Not
inelegant: escalating. Nothing in the type system, the tests or the comments would
have caught it, because the two constants agree only by a sentence in a comment.
## The Ryzen was three bugs, not one
Each of these independently produces "the xHCI and SATA controllers are missing."
Fixing any one of them leaves the machine broken by the next.
1. **`devices-broker.zig:33`, `maximum_children_per_parent = 16`** — `pci-bus`
registers *every* discovered function as a direct child of the one host bridge, so
16 is the ceiling on PCI functions for the whole machine. Enumeration runs in
bus/device/function order, so low-numbered chipset functions consume all 16 and the
high-numbered controllers — xHCI at 0x14, SATA at 0x17 — are refused. This is the
one that fired.
2. **`device-manager.zig:174`, `maximum_children = 64`** — the *userspace* inventory
has its own flat table. ACPI contributes ~34 nodes before PCI is scanned. Refusal
returns `-ENOSPC`, which `pci-bus.zig:246` discards and `acpi.zig:257` swallows in
an empty `catch {}`. The log line "child added" is printed *before* the status is
consulted, so the log says the device was added when it was not.
3. **`acpi.zig:651`, `gaps = [3]Range`** — only three sub-4 GiB MMIO holes become PCI
bridge apertures. A BAR landing in a fourth hole fails containment and is refused,
indistinguishably from a full table.
Three ceilings, three teams of one, one symptom. "Raise the limit" would have moved
the failure to the next one and produced a second debugging session from a second
photograph.
## Two latent security findings
**`acpi.zig:627`, `below = [64]Range`.** Firmware memory-map entries below 4 GiB, used
to derive the PCI bridge's apertures *from the gaps between described regions*. Past the
64th entry: `continue`. A dropped region is not merely missing — it vanishes from the
"described space" the gap-finder subtracts, so occupied physical memory is concluded to
be a free MMIO hole and registered as a bridge aperture. `devices-broker.contains()`
then admits a child BAR covering RAM, and its claimant can `mmio_map` it: a ring-3
read/write window onto kernel memory. Real UEFI maps carry 60–200 descriptors; OVMF
carries 15–25, which is why the suite has never approached it.
**`devices-broker.zig:217`, the PCI requester id is a `u16`** with no segment field,
propagated unbroken into both IOMMU backends. On a multi-segment machine two physically
distinct functions alias onto one translation structure.
Both are the same shape as the finding above: a bound whose failure mode is not "we run
out" but "the protection silently stops applying."
## Bugs found in passing
Not bounds, but found by looking at what happens at the bound:
- **`usb-xhci-library.zig:1331`** — `else if (device.interface_count < max_interfaces)`
has no `else`, so at the limit `current` is left pointing at interface 3 and the 5th
interface's endpoints are appended to interface 3's array. A class driver bound to
interface 3 can be handed an endpoint belonging to another interface. The
alternate-setting arm one line above does `current = null` correctly.
- **`usb-xhci-library.zig:899/1102`** — `allocateDevice()` failing returns after
`enableSlot()` already succeeded, with no Disable Slot. Every failed attempt
permanently leaks a controller slot.
- **`acpi.zig:445`** — the AML loop reserves `maximum_resources - 2` slots and the
function then adds **four** more resources. At 5 AML blocks the FADT is lost; at 6+
the broad IRQ window is lost too, so every legacy-IRQ device (PS/2 keyboard at IRQ 1)
fails containment. Real firmware ships 5–15 SSDTs; QEMU ships 2.
- **`fat.zig:252`** — a `u64` protocol offset reaches a `u32` engine parameter through a
bare `@intCast`. In ReleaseSafe — this project's build mode — that panics.
- **`boot/efi.zig:318`** — the bootstrap page tables map [0, 4 GiB) and nothing checks
that the handoff buffers UEFI allocated (BootInformation, the memory-map pool, the
initial ramdisk) landed below it. Several firmware implementations allocate top-down.
Above 4 GiB it is a triple fault with no output at all.
## Headroom actually measured
Every other bound here is hypothetical. One is a schedule:
`system/configuration/protocol.csv`, the manifest deciding which binary may bind which
protocol name, is at **50 of 64 grant rows and 12,668 of 16,384 bytes** — 78% and 77%.
To its credit, both overflow paths log (`init.zig:147` and `:238`). It will fail
loudly. It will still fail.
## The rule this suggests
The audit's own exemplar turned out to be broken, which is worth recording. Two sweeps
held up `devices_broker.dropped` as the model the others should be rewritten against.
It is not: `register()` never increments it, and `kernel.zig:203` reads it once at boot
*before* `seedDisplay` and long before any ring-3 driver exists. It can only report
firmware-discovery losses — precisely the opposite of the runtime case under audit.
`parameters.maximum_cpus` is the one bound that meets the standard: hardware-determined
and bounded, but it states what happens to the surplus (parked) and how you find out
(`platform.cpusDropped()` → a WARNING at `kernel.zig:281`). Verified.
So:
1. **A fixed bound on a quantity the hardware or an external file decides is a defect,
not a tunable.** It does not need a better number; it needs to not be fixed. This
covers 139 of the 235.
2. **A bound that must exist states three things**: what it protects against, what the
system does when it is reached, and how an operator finds out. One of 235 does.
3. **Refusal must be attributable.** `process.zig:944` collapses five distinct
`RegisterError` variants into a bare `-1`; `pci-bus` can only log "register refused"
with no reason. Half this audit's difficulty was that the machine could not say
which ceiling it hit.
4. **Two constants that must agree may not agree by comment.** `maximum_domains = 64`
and `maximum_devices = 64` are coupled by prose, and the coupling fails open.
## Appendix: the inventory
Sorted by severity, then file. `Decided by` is the audit's judgment of who chooses the
quantity — the machine, an external file or peer, or us.
| File:line | Bound | Value | Decided by | At the limit | Observable |
|---|---|---|---|---|---|
| `boot/efi.zig:318` | <inline literal> (4 * gib) | 4 GiB | hardware | No check exists. buildBootstrapTables maps [0, 4 GiB) as identity + physmap 2 MiB leaves and stops; the only carve-out is the framebuffer window at ef… | Nothing on this path. No log, no error, no panic. The last thing printed is the unconditional con_out line at … |
| `library/device/model/device-abi.zig:81` | maximum_device_resources | 8 | hardware | Silent drop, but at a different site than claimed. The live enforcement is system/kernel/device-model.zig:114 `if (self.resource_count >= maximum_reso… | None on any drop path, and the code says otherwise: device-model.zig:111-112 claims "Silently drops beyond `ma… |
| `system/drivers/pci-bus/pci-bus.zig:228` | device.register refusal path (kernel maximum_chi… | 16 children per parent / 64 … | hardware | system/kernel/devices-broker.zig:305 `if (childCount(parent_id) >= maximum_children_per_parent) return error.TooManyChildren;` and :306 `if (count >= … | One line per lost function: `std.log.info("register refused for {d}:{d}.{d}", .{ bus, dev, function })` (pci-b… |
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:227` | max_interfaces | 4 | external-data | CORRECTION to this claim's description: it is not only a silent drop. `parseConfiguration` (1326-1342) has no else on `else if (device.interface_count… | None. usb-xhci-bus.zig:368/425 log `{d} interface(s)` with the truncated count; nothing says any were dropped … |
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:333` | max_devices | 8 | hardware | Two different behaviours, exactly as claimed. Root port, `setupDevice` (899-902): `const device = self.allocateDevice() orelse { std.log.info("port {d… | Root ports: one log line. Hub-attached: nothing. I confirmed the leak is real — the only Disable Slot in the f… |
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:1304` | <inline literal> blob: [512]u8 | 512 | external-data | Silent truncation of device-supplied data. Lines 1304-1307: `var blob: [512]u8 = undefined; const length = @min(configuration.total_length, blob.len);… | None. `configuration.total_length` is read at 1299 and never compared to `blob.len`, never logged. The `{d} in… |
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:1305` | blob (inline [512]u8, declared line 1304) | 512 bytes | external-data | Silent truncation of externally-supplied data. The @min clamps the GET_DESCRIPTOR request to 512; parseConfiguration then walks it and stops dead at l… | Nothing. No log line, no counter, no comparison of configuration.total_length against blob.len. The symptom is… |
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:1331` | max_interfaces (= 4), used as `else if (device.i… | 4 | external-data | CORRUPTING, not merely dropping. When interface_count == 4, neither branch of the if/else-if runs, so `current` is NOT cleared — it still points at in… | Nothing. No log, no counter, no error. The device enumerates, `port N device: ... 4 interface(s)` is logged (a… |
| `system/kernel/acpi.zig:445` | <inline literal> device_model.maximum_resources … | 6 AML blocks, inside an 8-re… | hardware | Silent double loss. The loop stops at 6 blocks, so SSDTs 7+ are never published. Then acpi.zig:454-463 adds the io_port grant (7th), the SCI irq (8th)… | Nothing at all. No counter, no log, no error. The ring-3 acpi service simply finds an acpi-tables node without… |
| `system/kernel/acpi.zig:445` | device_model.maximum_resources - 2 (inline expre… | 6 AML blocks, out of 8 total… | hardware | Silent drop, then a silent cascade. Resources are appended in order: up to 6 AML memory resources (445-448), io_port (454), the SCI irq (459), the bro… | Nothing at the kernel. The only downstream trace is the acpi service writing "acpi: no FADT on the node — powe… |
| `system/kernel/acpi.zig:627` | below | [64]Range | hardware | Silent skip: `if (region.base >= (1 << 32) or below_count == below.len) continue;`. Every region past the 64th is treated as 'not described', i.e. as … | None directly, though kernel.zig:133 does print `" regions : {d} - entries in the firmware memory map"`, w… |
| `system/kernel/acpi.zig:627` | below (inline [64]Range) | 64 entries | hardware | Silent drop, and — worse than a drop — a corrupted result. A dropped region is not merely missing from the list; it disappears from the "described spa… | Nothing at all. No counter, no log line. The kernel prints the device tree including the bogus aperture, with … |
| `system/kernel/acpi.zig:651` | gaps | [3]Range | hardware | Silent replacement of the smallest kept gap (acpi.zig:658-664): a fourth (or fifth) MMIO hole is simply forgotten. A PCI function whose BAR lands in a… | Nothing. No log, no counter, and the resulting failure is indistinguishable at the caller from a table-full re… |
| `system/kernel/device-model.zig:66` | maximum_resources | 8 | external-data | `addResource` (line 113-118) returns false without recording. I grepped every call site: system/kernel/acpi.zig lines 448, 454, 459, 460, 463, 552, 55… | Nothing at the drop. Downstream there are two ring-3 lines that name the symptom and misattribute the cause: s… |
| `system/kernel/devices-broker.zig:33` | maximum_children_per_parent | 16 | hardware | Confirmed at devices-broker.zig:305: `if (childCount(parent_id) >= maximum_children_per_parent) return error.TooManyChildren;`, where `childCount` (28… | One reasonless line per lost device, and nothing from the kernel. Confirmed at pci-bus.zig:228-231: `const reg… |
| `system/services/acpi/acpi.zig:129` | blocks | [8][]const u8 | external-data | The `blocks: [8][]const u8` array at line 129 and its `if (block_count == blocks.len) continue;` at line 152 are dead — they can never fire, because t… | Only an indirect count that cannot reveal the loss: `std.log.info("parsed {d} AML blob(s), {d} namespace devic… |
| `system/services/device-manager/device-manager.zig:174` | maximum_children | 64 | hardware | Silent drop with a misleading log. `addChild` (180-194) returns false when no free slot exists. `onChildAdded` (442-452): `if (!addChild(...)) status … | Effectively none, and actively misleading. The -ENOSPC goes back to the bus driver, which discards it — verifi… |
| `boot/efi.zig:108` | <inline literal> (handles[0]) | 1 | hardware | Silent selection of GOP handle 0, and the two halves genuinely disagree — nativeResolution (efi.zig:167-176) iterates `for (handles) \|h\|` over every… | Nothing. No log names the handle count, the chosen adapter, or the resolved mode; the only con_out writes in t… |
| `library/device/driver/driver.zig:149` | <inline literal> | @min(total, buffer.len) | hardware | Silently searches a prefix: `const total = enumerate(buffer); const n = @min(total, buffer.len); for (@as([]DeviceDescriptor, buffer[0..n])) \|d\| { …… | Nothing. The discarded `total` is the only evidence that the buffer was too small, and it is thrown away on th… |
| `library/kernel/file-system.zig:227` | Entry.name_buffer | [64]u8 | external-data | Silent truncation on both readdir paths, exactly as claimed. Backend path, Directory.next line 264-266: `const nlen = @min(@min(@as(usize, header.name… | Nothing. No log, no flag, no short-count anywhere in library/kernel/file-system.zig. Entry.name() returns a pl… |
| `system/drivers/virtio-gpu/virtio-gpu.zig:49` | max_width / max_height (line 50) | 800 x 600 | hardware | Two distinct behaviours, and the claim conflates their visibility. (a) onSetMode, line 533-540: `if (w == 0 or h == 0 or w > max_width or h > max_heig… | Partial and misleading, as claimed. Confirmed the two adjacent lines: `std.log.info("EDID preferred mode {d}x{… |
| `system/kernel/architecture/x86_64/cpu.zig:489` | irq_vector_count | 14 | hardware | irq.zig:138 allocVector() scans base..base+count for a vector free of both an MSI binding and a GSI binding and returns null when none is; bind (irq.z… | No kernel log line. Driver-side, both messages verified: usb-xhci-bus.zig:279 `std.log.info("msi_bind unavaila… |
| `system/kernel/architecture/x86_64/idt.zig:17` | gate_count | 48 | our-design | Nothing is enforced at this line. `pub fn init()` at line 136 does `inline for (0..gate_count) \|vector\| { const stub = @extern(*const anyopaque, .{ … | None at runtime. The bound only ever becomes visible as the vector-exhaustion path in irq.zig, which each driv… |
| `system/kernel/architecture/x86_64/ioapic.zig:21` | base (module-level singleton) | 1 I/O APIC | hardware | Confirmed exactly. system/kernel/acpi.zig:547-556 adds EVERY MADT I/O APIC record to the device tree as ioapic0, ioapic1, ...; kernel.zig:545-548 then… | None. No log counts the discarded units, unlike the neighbouring drop counters that ARE logged (devices_broker… |
| `system/kernel/architecture/x86_64/iommu-amd.zig:56` | ring_entries (event log) | 256 | hardware | Confirmed. faultDrain (lines 180-198) reads EventHead/EventTail, walks the ring wrapping at `if (head >= ring_entries * 16) head = 0;`, and writes the… | None. I grepped the file: `const reg_status = 0x2020;` appears at line 32 and at NO other line — it is declare… |
| `system/kernel/architecture/x86_64/iommu-intel.zig:102` | <inline literal> 16 * 1024 | 16384 (bytes of VT-d registe… | hardware | No check. `faultDrain` computes `frcd_base = fro*16` with fro up to 0x3FF (16368 bytes) and `nfr = ((cap >> 40) & 0xFF) + 1` up to 256 registers of 16… | A kernel-mode #PF: the fault handler reports the vector/CR2 and halts the core. Loud, but reported as a page f… |
| `system/kernel/architecture/x86_64/iommu.zig:17` | Discovery.register_base (single unit) | 1 IOMMU unit | hardware | Confirmed. `pub const Discovery = struct { register_base: u64, amd: bool };` at iommu.zig:16-19 carries exactly one base. Intel (acpi.zig:826-852): th… | Asymmetric, exactly as claimed. Intel warns: system/kernel/iommu.zig:395-396 `if (info.iommu_extra_units > 0) … |
| `system/kernel/devices-broker.zig:25` | maximum_devices | 64 | hardware | Three inconsistent behaviours, all confirmed. Boot discovery: devices-broker.zig:111-114 `if (count >= maximum_devices) { dropped += 1; return device_… | Partial and aimed at the wrong path, exactly as claimed. kernel.zig:203-206 prints `"/system/kernel: WARNING {… |
| `system/kernel/iommu.zig:43` | maximum_domains | 64 | hardware | Two behaviours. Domain exhaustion is safe: `domainCreate` returns null → `confineDevice` false → process.zig:418-420 rolls the claim back and returns … | The rollback path is visible as a failed `device_claim`. The fail-open path is completely silent — no log, no … |
| `system/kernel/irq.zig:43` | maximum_gsi | 24 | hardware | Refusal at three places, all becoming a bare -1. irq.zig:158 `if (gsi >= maximum_gsi or !architecture.irqOwnsGsi(gsi)) return error.BadGsi;` -> proces… | Nothing in the kernel, but every caller logs: ps2-bus.zig:246 and :265, acpi.zig:315 "acpi: SCI irq_bind faile… |
| `system/kernel/irq.zig:139` | allocVector over architecture.irq_vector_count | 14 (vectors 33..46, from arc… | hardware | `fn allocVector() ?u8` (line 139) scans v in [irq_vector_base, irq_vector_base + irq_vector_count) = [33, 47) — 14 vectors — and returns null when all… | Better than claimed at the driver level, absent at the kernel level. The kernel logs nothing and has no counte… |
| `system/kernel/process.zig:546` | maximum_dma_regions | 256 | hardware | Confirmed, and the safety-invariant break is real. process.zig:549-556 `fn dmaRegistryAdd(object: ?*ipc.DmaRegionObject, physical: u64, len: u64, owne… | None whatsoever — confirmed. `dma_alloc` returns success, no log, no counter, no failed syscall. The symptom i… |
| `system/kernel/scheduler.zig:546` | maximum_tasks (via freeSlot in secondaryMain) | 48 (parameters.maximum_tasks… | hardware | Confirmed: `const t = freeSlot() orelse @panic("sched: task table full (AP idle task)");` at scheduler.zig:546, reached from `secondaryMain` with the … | A named panic on console/serial — loud, but the machine is dead and the message points at the task table rathe… |
| `system/kernel/vfs.zig:58` | maximum_mounts | 8 | our-design | FALSE SUCCESS plus a reference leak, confirmed end to end. installMount, vfs.zig:182: `const m = slot orelse return;` — it gives up silently when no s… | Worse than nothing: the syscall reports success, so the mounting service logs its own success — system/service… |
| `system/kernel/vfs.zig:86` | maximum_directories | 8 | external-data | Silent skip inside the boot walk: `if (directoryIndex(parent) == null and directory_count < maximum_directories)` (vfs.zig:141). An unregistered direc… | Nothing. No log, no counter, no `dropped` variable of the kind acpi.zig:542 and the device manager both mainta… |
| `system/kernel/vfs.zig:141` | maximum_directories (declared line 86) | 8 | external-data | Silent drop with a mount-level knock-on, confirmed. The ninth distinct ancestor is skipped by the guard at vfs.zig:141; it then fails to resolve (reso… | Nothing — no counter, no log line, no `dropped` variable of the sort acpi.zig:542 (cpu_information.dropped, pr… |
| `system/kernel/vfs.zig:182` | maximum_mounts (declared line 58) | 8 | our-design | False success, confirmed: installMount gives up at vfs.zig:182 (`const m = slot orelse return;`) and mountBackend returns true regardless at vfs.zig:3… | Nothing in the kernel. The mounting service logs its own success — fat.zig:173/:178/:183 all `std.log.info("mo… |
| `system/services/acpi/acpi.zig:542` | buffer (readHid) / Registered.hid / Notice.hid | [8]u8 | external-data | Both failures confirmed. (a) readHid (lines 540-566) accepts only an integer _HID it can EISA-decode: a method result must be `.integer`, and a static… | None for (a): a skipped device produces no line at all. For (b) the log at line 408, `std.log.info("power: not… |
| `system/services/acpi/acpi.zig:648` | descriptor.resources.len | 8 (maximum_device_resources,… | external-data | Silent drop of the surplus. `fn addResource(descriptor: *device.DeviceDescriptor, kind: device.ResourceKind, start: u64, len: u64) void { if (descript… | Nothing at the drop. The only echo is the per-device summary at line 241, `std.log.info("device {d} bus=acpi … |
| `system/services/device-manager/device-manager.zig:149` | maximum_drivers | 16 | hardware | `addDriver` (240-254) walks for a free slot and, finding none, falls through the loop to `std.log.info("driver table full; cannot supervise {s}", .{na… | One log line only (quoted above). No counter, no status to any caller, and it lands amid the stream of `child … |
| `system/services/device-manager/device-manager.zig:358` | <inline literal> | 64 | hardware | Silent truncation. Line 362-363: `const total = device.enumerate(buffer); const count = @min(total, buffer.len);` — the difference is computed and thr… | Nothing. No log mentions `total`. The only related line, `"/system/services/device-manager: no matchable devic… |
| `system/services/fat/fat.zig:73` | open_nodes | 32 | our-design | An error is returned, but a maximally confusing one: `const index = allocOpen() orelse return refused;` (line 242), where `refused` is `-envelope.ENOE… | Nothing on the server side — no log at all in allocOpen or onOpen. The client sees ENOENT and will report "fil… |
| `system/services/fat/fat.zig:252` | <inline literal> | u32 (via @intCast of a u64 p… | external-data | Panic. `vfs_protocol.Read.offset` is a `u64` (library/protocol/vfs/vfs-protocol.zig:82-86) and `engine.readFile` takes `offset: u32`; the bridge is a … | A process fault and whatever the supervisor logs about the death; nothing identifies the offending request or … |
| `boot/efi.zig:371` | maximum_bundled | 64 | external-data | Two different behaviours for one constant, confirmed. loadByManifest (efi.zig:507): `if (count.* == maximum_bundled) return;` — silent success with th… | Manifest path: nothing. Walk path: the unconditional con_out line at efi.zig:71-75, `log("EFI: no /system bina… |
| `boot/efi.zig:375` | maximum_tree_depth | 3 | our-design | `if (depth == maximum_tree_depth) continue;` (efi.zig:580) — the subdirectory is silently skipped and nothing beneath it is bundled. No error, no coun… | Nothing. The boot proceeds; the missing binary surfaces much later as an init spawn failure or a device-manage… |
| `boot/efi.zig:507` | maximum_bundled (declared line 371) | 64 | external-data | As described and verified: efi.zig:507 `if (count.* == maximum_bundled) return;` in loadByManifest is a silent stop keeping the first 64; efi.zig:590 … | Manifest path: nothing. Enumeration path: efi.zig:71-75 prints 'EFI: no /system binaries (TooManyBinaries) - b… |
| `boot/efi.zig:582` | <inline literal> (child_prefix bufPrint) | 64 bytes (initial_ramdisk.ma… | external-data | `const child = try std.fmt.bufPrint(&child_prefix, "{s}/{s}", .{ prefix, name });` into a [initial_ramdisk.maximum_name]u8 = [64]u8. error.NoSpaceLeft… | efi.zig:71-75 prints 'EFI: no /system binaries (NoSpaceLeft) - booting without user space' on con_out. Visible… |
| `boot/efi.zig:633` | ehdr.e_phnum / e_phoff / e_phentsize (no bound a… | unbounded — read straight fr… | external-data | Unchecked out-of-bounds read. efi.zig:632-636 forms `image.ptr + ehdr.e_phoff + i * ehdr.e_phentsize` as raw pointer arithmetic and @ptrCasts it — no … | Nothing until it faults or panics, at which point the machine is still in the firmware with no kernel. |
| `library/device/acpi/aml/interpreter.zig:158` | notify_queue | [16]NotifyEvent | external-data | Silent drop of the 17th and later Notify. `notify()` (line 571-576): `if (target) \|node\| { if (self.notify_count < self.notify_queue.len) { ...appen… | None. No log in interpreter.zig at all (grepped: zero std.log/log.print/logging.write calls in the file). `tak… |
| `library/device/acpi/aml/interpreter.zig:523` | <inline literal> | 100_000 | our-design | Silently exits the loop and continues executing the method as if the loop had terminated normally: `while (guard < 100_000) : (guard += 1) { … }` then… | Nothing. No log, no `error.Unsupported`, no distinguishable result — the caller receives a normal-looking valu… |
| `library/device/acpi/aml/parser.zig:24` | maximum_segments (and its disagreeing twin, libr… | 64 in the parser, 16 in the … | external-data | Both files silently drop the surplus segment after consuming its 4 bytes. Parser: appendSegment, parser.zig:137-143. Interpreter: `fn segment(self: *C… | None on either path. Neither file logs; acpi.zig discards ParseResult.consumed/total; interpreter errors surfa… |
| `library/device/usb/usb.zig:167` | <inline literal> | 100 attempts × 20 ms = 2 s | our-design | Gives up and returns null: `const bus = while (attempts < 100) : (attempts += 1) { if (channel.openEndpoint("usb-transfer")) \|handle\| break handle; … | Nothing here. The driver's own bail-out is what an operator sees, with no indication that it was a timeout rat… |
| `library/kernel/channel.zig:124` | <inline literal> | @min(available, into.len) | our-design | Silent truncation to the caller's buffer: `const available = @min(answer.len - envelope.prefix_size, @as(usize, status.len)); const taken = @min(avail… | Weak: `Response.status.len` holds the true length the provider sent, so a caller *could* compare it against `p… |
| `library/kernel/file-system.zig:85` | <inline literal> | [224]u8 (twice: lines 77 and… | our-design | Errors invisibly, but the enforcing code is in the KERNEL, not where the claim points. system/kernel/process.zig:1898 rejects the input outright: `if … | None. A too-long path and a nonexistent file are both `null` from open(); no log on either side — the kernel's… |
| `library/kernel/logging.zig:82` | <inline literal> | [256]u8 | our-design | Truncation, marked with a `~` — but the truncated slice is the *whole* buffer, not the written prefix: `const line = std.fmt.bufPrint(&buffer, prefix … | The trailing `~` marks the line as truncated, which is good; the garbage tail is not marked at all. |
| `library/kernel/process.zig:211` | <inline literal> | [32]ProcessDescriptor | our-design | Silent false negative: `var table: [32]ProcessDescriptor = undefined; const total = processes(&table); for (table[0..@min(total, table.len)]) \|descri… | Nothing. The function returns a plain bool; the discarded `total` is the only evidence and it is thrown away b… |
| `library/protocol/device-manager/device-manager-protocol.zig:161` | entries_per_reply | (envelope.packet_maximum - e… | hardware | Silent cut with a success status. `onEnumerate` (device-manager.zig:524-536): `for (&children) \|*child\| { if (!child.used) continue; if (written + e… | None, and structurally impossible for a client to detect: the protocol's own comment (149-152) says the count … |
| `library/protocol/envelope/envelope.zig:133` | packet_maximum | 256 | our-design | Two behaviours, exactly as claimed. Compile time: `Define` rejects an oversized fixed part with a message naming protocol, verb, size, prefix and floo… | Compile-time half is excellent. Run-time half is silent everywhere I traced it: library/device/block/block.zig… |
| `library/protocol/envelope/envelope.zig:134` | post_maximum | 64 | our-design | Compile error for an event payload that does not fit (`Define`, envelope.zig:365-370, message names the event and the push floor). At run time `encode… | Compile-time: named and precise. Run-time: nothing. The `orelse return` at service.zig:239 is the whole handli… |
| `library/protocol/usb-transfer/usb-transfer-protocol.zig:58` | max_report_data | 40 | hardware | Two stacked silent truncations. First in the engine: usb-xhci-library.zig:1569 `const n = @min(length, report.data.len);` against a `data: [64]u8` (li… | None. No log at either truncation site; the surrounding comment (usb-xhci-bus.zig:766-768) states the truncati… |
| `library/protocol/usb-transfer/usb-transfer-protocol.zig:62` | max_reported_endpoints | 4 | hardware | Silent drop, and the primary site is upstream of the one claimed. The bus driver discards surplus endpoint descriptors while parsing the configuration… | None. No log at the parse-time drop, none at the client cap; a driver's `findEndpoint` just returns null for a… |
| `system/boot-handoff.zig:143` | kernel_segments | 8 | our-design | Silent drop with a delayed fatal consequence, as described. boot/efi.zig:659-668 records only `if (n < boot_information.kernel_segments.len)` with no … | The loader says nothing. The kernel prints the count it received — kernel.zig:159 `log.print(" kernel segs: {… |
| `system/drivers/pci-bus/pci-bus.zig:81` | <inline literal> alloc(device.DeviceDescriptor, … | 64 | our-design | Not reachable today, so nothing happens. If the kernel table grew past the buffer: `device.enumerate(buffer)` returns the TOTAL, the search clamps wit… | One misleading line, `std.log.info("device {d} not in the device tree", .{bridge_id})` — it names a missing de… |
| `system/drivers/pci-bus/pci-bus.zig:81` | 64 (bare inline literal — no constant, no link t… | 64 | our-design | Same site as the earlier claim on line 81 — this is a duplicate. Unreachable today (`total` is bounded by the kernel's own maximum_devices = 64). If i… | `std.log.info("device {d} not in the device tree", .{bridge_id})` — misdescribes the cause and never prints `t… |
| `system/drivers/usb-hid/hid-report.zig:20` | KeyboardReport.keys: [6]u8, and max_transitions … | 6 concurrent keys; 14 transi… | hardware | THE CLAIM IS BACKWARDS. `max_transitions = 8 + 6` is derived from a wrong worst case, and `Transitions.add`'s guard (`if (self.count < self.items.len)… | None. `add` drops without logging and `Transitions` carries no overflow flag; `slice()` just returns the first… |
| `system/drivers/usb-storage/usb-storage.zig:61` | <inline literal> .lun = 0 in the CommandBlockWra… | 1 LUN (LUN 0 only) | hardware | There is no limit check — LUNs 1..15 simply do not exist to this driver. Every CBW is built with `.lun = 0` (usb-storage.zig:57-63), and I confirmed t… | Nothing. Nothing reads bMaxLUN, so nothing can report that a device has more than one logical unit. |
| `system/drivers/usb-storage/usb-storage.zig:121` | <inline literal> while (tries < 10) with time.sl… | 10 attempts = ~500 ms | hardware | Falls out of the loop and proceeds regardless (usb-storage.zig:120-127). INQUIRY's result is discarded (`_ = transact(...)`, line 129), then READ CAPA… | Present but misattributed, exactly as claimed: `_ = logging.write("/system/drivers/usb-storage: READ CAPACITY … |
| `system/drivers/usb-storage/usb-storage.zig:172` | <inline literal> @intCast(request.lba) -> u32, @… | LBA < 2^32, count < 2^16 (RE… | external-data | Bare, unchecked @intCast on both fields — verified there is no range check anywhere between the wire struct and the CDB. scsi.read10/write10 take (lba… | In a safe build, driver death with a fault exit reason and a device-manager restart with backoff — attributed … |
| `system/drivers/usb-storage/usb-storage.zig:172` | @intCast(request.lba) / @intCast(request.count) … | u64 -> u32 LBA, u32 -> u16 b… | external-data | Unchecked narrowing of two peer-chosen wire fields. library/protocol/block/block-protocol.zig:30-35 declares `Transfer { lba: u64, count: u32, physica… | Nothing in ReleaseFast; in a safe build a driver crash with a fault exit reason and a supervised restart, attr… |
| `system/drivers/usb-xhci-bus/usb-xhci-bus.zig:80` | opens (= [_]Open{.{}} ** 16) | 16 | our-design | Confirmed, including the success-on-failure shape. recordOpen (line 87) walks `opens` for a matching token, then for a free slot, and falls through to… | Nothing on the bus side — no log when the table fills, and the harness closes the unclaimed report endpoint si… |
| `system/drivers/usb-xhci-bus/usb-xhci-bus.zig:728` | prev_connected (declared line 326 as [64]bool), … | 64 | hardware | Confirmed off-by-one. Line 728: `while (port <= engine.max_ports and port <= prev_connected.len) : (port += 1)` with `var port: u32 = 1` — at port == … | The OOB half surfaces as a driver fault and a supervised restart into the same panic — loud but attributed to … |
| `system/drivers/usb-xhci-bus/usb-xhci-bus.zig:728` | prev_connected (inline [64]bool, declared line 3… | 64 | hardware | Same site as the earlier line-728 claim — this is a duplicate. Two failures, both confirmed. (1) Off-by-one out-of-bounds: `while (port <= engine.max_… | The panic half is loud (process fault + supervised restart loop) but misattributed. The silent-drop half has n… |
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:228` | max_endpoints_per_interface (and max_configured_… | 4 per interface, 16 configur… | hardware | Parsing: `if (interface.endpoint_count < max_endpoints_per_interface)` with no else — the 5th endpoint descriptor is silently discarded, so a class dr… | The endpoint-drop during parsing is entirely silent. The ring-exhaustion path reaches the class driver as a ge… |
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:228` | max_endpoints_per_interface | 4 | external-data | Silent drop, no else (1345-1354). An endpoint never recorded cannot be found by `endpointForAddress` (1377-1382), so a class driver's subscribe or bul… | None at the drop. The secondary consequence the claim names is real and I verified it: usb-xhci-bus.zig:612 se… |
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:328` | <inline literal> Report.data: [64]u8 (and usb_tr… | 64 in the driver, then 40 ov… | hardware | Truncated twice, silently: `const n = @min(length, report.data.len);` in enqueueReport, then `const n = @min(report.length, usb_transfer_protocol.max_… | Nothing. Both truncations are @min with no branch and no log. |
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:334` | max_subscriptions | 8 | hardware | Two paths, as claimed. Class driver: `subscribeInterrupt` (1482) `const subscription = self.allocateSubscription() orelse return false;` -> usb-xhci-b… | Class drivers log it: usb-hid/keyboard.zig:94 and mouse.zig:57 both write `interrupt subscribe failed`. The hu… |
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:335` | report_queue_capacity | 16 | hardware | `enqueueReport` (1561-1562): `if (self.report_count >= self.report_queue.len) return; // full: drop the newest` — the report is discarded and the subs… | None. The comment in the source is the only trace; no log, no counter. The symptom is dropped keystrokes or a … |
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:968` | hub_change_mask: u32 (declared line 298) and the… | 31 usable downstream ports | hardware | Ports 32..255 are never seeded and never serviced: the seed clamps to 0xFFFF_FFFE for hub_ports >= 31, and takeHubChange picks bits via @ctz on a u32,… | Nothing. No log line mentions bNbrPorts exceeding what the mask holds; the 'N downstream ports powered' line p… |
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:1456` | <inline literal> `.status = length` on the bulk … | 65535 (the xHCI TRB Transfer… | hardware | Unchecked write of a u32 into a 17-bit field. `bulkTransfer` (1452-1458) pushes `.status = length` with no mask and no split across TRBs; the status d… | Nothing on the way in — no check, no log. It surfaces later as a short/failed transfer or a lost completion at… |
| `system/drivers/virtio-gpu/virtio-gpu.zig:49` | max_width / max_height | 800 x 600 | hardware | set_mode errors visibly (line 536 refuses anything larger). But the EDID path is the silent one: readEdid (lines 413-442) parses the panel's preferred… | One std.log.info line naming the preferred mode, in the driver's log file, with nothing saying it was ignored. |
| `system/drivers/virtio-gpu/virtio-gpu.zig:208` | <inline literal> descriptors: [64]device.DeviceD… | 64 | hardware | NOT reachable today, contrary to the claim's framing. The kernel's own table is the binding wall: system/kernel/devices-broker.zig:25 `const maximum_d… | `device {d} not in the device tree` (line 213), which today only means a real absence. The kernel-side drop th… |
| `system/initial-ramdisk.zig:26` | maximum_name | 64 bytes | our-design | Four different behaviours, verified individually. (a) Capsule build: tools/pack-system-image.py:35-37 writes 'pack-system-image: path too long (>63)' … | (a) clear build error. (b)(c)(d) nothing: boot/efi.zig has exactly two output helpers (lines 773 and 795) and … |
| `system/kernel/acpi.zig:94` | overrides | [16]IsoEntry | hardware | Silent drop: `if (platform_information.override_count < platform_information.overrides.len) { ... }` with no else branch and no counter — unlike the C… | Nothing. A lost override means a legacy line is routed at the wrong GSI or the wrong polarity, which shows up … |
| `system/kernel/acpi.zig:94` | PlatformInformation.overrides | [16]IsoEntry | hardware | Silent drop, at three separate 16s that must agree by hand: system/kernel/acpi.zig:558 (no else branch), system/kernel/kernel.zig:248 (`var isos: [16]… | Nothing at any of the three clamps. No counter of the cpusDropped kind, no log line. |
| `system/kernel/acpi.zig:186` | aml_block_physical / aml_block_len | [32]u64 / [32]usize | hardware | Confirmed at acpi.zig:190-197: `fn addAmlBlock(sdt_physical: u64) void { if (aml_block_count >= aml_block_physical.len or sdt_physical == 0) return; .… | None — confirmed, no log and no dropped counter, unlike `cpu_information.dropped` (acpi.zig:539) and `rmrr_ski… |
| `system/kernel/architecture/x86_64/apic.zig:320` | <inline literal> 100_000_000 (calibratePit guard… | 100000000 | our-design | Confirmed: the loop falls out and calibration proceeds on a window that never happened. `ticks_per_ms = elapsed / calib_ms` and `tsc_hz = (tsc_end -% … | No failure line, but not quite "none": kernel.zig:322 prints `timer online ({d} Hz tick; timer clock {d} MHz, … |
| `system/kernel/architecture/x86_64/apic.zig:629` | localId (return type u8) / apic_id << 24 | 8-bit APIC id (0..255) | hardware | The claimed truncations are not reachable; the real defect is an omission. `sendInit`/`sendStartup` (lines 174-184) take a `u32` but every caller pass… | None for the dropped type-9 records. `cpu_information.dropped` (acpi.zig:542) counts only overflow past the 12… |
| `system/kernel/architecture/x86_64/iommu-amd.zig:56` | ring_entries (command buffer) | 256 | our-design | Confirmed. submitCommand (lines 221-228) writes the two qwords, advances `command_tail += 16`, wraps modulo the ring, and writes the tail register — w… | None — no head check, no full-ring detection, no log. |
| `system/kernel/architecture/x86_64/iommu-amd.zig:74` | fault_log_budget | 32 | hardware | logFault (lines 200-211) opens with `if (fault_log_budget == 0) return;` — the record's bdf and address are discarded outright, with no suppressed-fau… | One "(further faults suppressed)" line (line 210) and then permanent silence for the detail. Correcting the cl… |
| `system/kernel/architecture/x86_64/iommu-amd.zig:246` | <inline literal> 100_000 | 100000 | our-design | Confirmed verbatim at lines 243-253: the spin loop polls the completion frame for the 0xC0FFEE sentinel, and at `if (spins > 100_000)` warns once behi… | One line for the whole boot: "/system/kernel: AMD-Vi COMPLETION_WAIT store not observed — proceeding (QEMU pro… |
| `system/kernel/architecture/x86_64/iommu-intel.zig:77` | fault_log_budget | 32 | hardware | `logFault` (lines 252-270) takes the else branch and does `faults_suppressed += 1`. The budget is only ever decremented (line 255) — nothing resets it… | One line at the transition: 'DANOS-IOMMU-FAULT: (further faults suppressed)' (line 266). After that a device D… |
| `system/kernel/architecture/x86_64/iommu-intel.zig:294` | <inline literal> 10_000_000 (spin64) | 10000000 | our-design | `if (spins > 10_000_000) return;` — the function returns as if the invalidation completed. Callers (`invalidateDomain`, `globalInvalidate`, `detach`) … | Nothing at all — a bare `return` with no message, unlike `spinStatus` which prints "WARNING VT-d status bit ne… |
| `system/kernel/architecture/x86_64/paging.zig:206` | <inline literal> 0xFEE00000 | 0xFEE00000 (one 4 KiB page) | hardware | Confirmed and worse than "inconsistent": the two halves disagree with no reconciliation. paging.zig:206 maps exactly one hardcoded page `mapPage(pml4,… | A boot-time kernel fault reported as a fault address, never as "LAPIC relocated". The parsed truth is thrown a… |
| `system/kernel/architecture/x86_64/serial.zig:112` | <inline literal> 5_000 (writeByte guard) | 5000 | hardware | The loop simply falls through and `setRegister(0, c)` runs anyway (serial.zig:111-113) — the byte is written into a transmit-holding register that may… | Nothing. The corruption appears in the serial log itself, which is the channel you would use to notice it. |
| `system/kernel/heap.zig:28` | heap_maximum | 64 * 1024 * 1024 | our-design | Confirmed mixed. `grow` returns false at heap.zig:63 `if (start + bytes > heap_base + heap_maximum) return false;` -> `rawAlloc` null -> std.mem.Alloc… | For the graceful callers, a bare -1 to user space with no reason. For scheduler.zig:704, a panic naming the st… |
| `system/kernel/heap.zig:161` | <inline literal> alignment ceiling | 16 | our-design | `if (alignment.toByteUnits() > 16) return null;` confirmed at heap.zig:161 inside `allocImpl`. Returning null from the vtable alloc is how the allocat… | None. No log, no distinct error; the caller sees error.OutOfMemory and investigates memory pressure. |
| `system/kernel/ipc-synchronous.zig:40` | MESSAGE_MAXIMUM | 256 | our-design | Two different behaviours, both confirmed. The cap itself errors visibly: `if (message_len > MESSAGE_MAXIMUM or reply_cap > MESSAGE_MAXIMUM) return -E2… | -E2BIG for the cap. Nothing for the truncation — no counter, no flag bit, no errno. |
| `system/kernel/ipc-synchronous.zig:75` | post_capacity | 16 | external-data | Deliberate silent drop of the OLDEST message: sendLocked, ipc-synchronous.zig:568 `if (endpoint.post_tail -% endpoint.post_head >= post_capacity) endp… | None, and I checked the struct: PostSlot (ipc-synchronous.zig:79-83) carries only length and sender_id — no se… |
| `system/kernel/ipc-synchronous.zig:513` | @min(caller.ipc_send_len, receive_cap) (no const… | whatever the receiver's buff… | external-data | Silent truncation. replyWait, ipc-synchronous.zig:512-513: `if (dequeueSender(endpoint)) \|caller\| { const n = @min(caller.ipc_send_len, receive_cap)… | Nothing — no counter, no errno, no flag bit anywhere on this path. |
| `system/kernel/log.zig:202` | buffer (log.print) | [256]u8 | our-design | Confirmed: the entire line is discarded, not truncated. Lines 201-204 verbatim: `pub fn print(comptime fmt: []const u8, args: anytype) void { var buff… | Nothing. The message never appears and its absence is indistinguishable from the code path not having run. Not… |
| `system/kernel/pmm.zig:94` | <inline literal> (implicit: bitmap must land bel… | 4 GiB, stated only in prose | hardware | Two distinct failures. If NO usable region is large enough: `@panic("pmm: no region large enough for the frame bitmap")` — loud and fatal. If the chos… | The panic is legible. The above-4-GiB case is a triple fault or an early #PF with essentially no diagnostics. |
| `system/kernel/process.zig:98` | maximum_shared_memory_pages | 8192 (32 MiB) | hardware | Confirmed at process.zig:790: `if (pages == 0 or pages > maximum_shared_memory_pages) return fail(state);` in `systemSharedMemoryCreate`, giving a cle… | No kernel log; -1 only — confirmed. And the ambiguity the claim notes is real: `pmm.allocContiguous` failing t… |
| `system/kernel/process.zig:104` | maximum_mmap_pages | 8192 (32 MiB) | our-design | Confirmed at process.zig:2050: `if (pages == 0 or pages > maximum_mmap_pages) return fail(state);` in `systemMmap` — a clean -1. The independent secon… | -1 only, no log — confirmed. Indistinguishable from arena exhaustion and from 'not a user process' (line 2049)… |
| `system/kernel/process.zig:118` | maximum_resolve_path | 224 | external-data | Confirmed at process.zig:1898: `if (path_len == 0 or path_len > maximum_resolve_path or path_ptr >= user_half_end or path_ptr + path_len > user_half_e… | No log; -1 only — confirmed. There is no ENAMETOOLONG in this path (the function does have `failErr(state, ipc… |
| `system/kernel/process.zig:1542` | exit_subscriber_capacity | 16 | hardware | Confirmed at process.zig:1573-1581: `subscribeExits` scans `for (&exit_subscribers) \|*slot\| { if (slot.* == null) { endpoint.refcount += 1; slot.* =… | Materially worse than claimed, and this is my main correction. The kernel does return a specific -ENOSPC, but … |
| `system/kernel/process.zig:1649` | timer_capacity | 16 | our-design | Confirmed at process.zig:1684-1692: `systemTimerBind` scans `for (&one_shot_timers) \|*slot\| { if (slot.* == null) { ...; return architecture.setSyst… | Effectively none, correcting the claim. The kernel's -ENOSPC is narrowed to a bool by library/kernel/time.zig:… |
| `system/kernel/process.zig:2172` | maximum_segments | 16 | external-data | Confirmed at process.zig:2200: `if (ehdr.e_phnum > maximum_segments) return error.BadElf;`. The claim's key observation is right — the test is on `e_p… | None — confirmed. `error.BadElf` is erased at process.zig:1018 and `system_spawn` returns -1, so a developer i… |
| `system/kernel/process.zig:2173` | maximum_pages | 256 | external-data | Confirmed at process.zig:2238, inside the PT_LOAD loop: `total_pages += seg.pages(); if (total_pages > maximum_pages) return error.ProgramTooBig;`. Th… | No kernel log — confirmed. `error.ProgramTooBig` is erased at the syscall boundary and becomes the same -1 as … |
| `system/kernel/scheduler.zig:206` | maximum_space_mappings | 16 | our-design | Clean refusal, confirmed. `recordSpaceMappingLocked` (scheduler.zig:343-355) walks `entry.mappings` for a null slot and `return false` when full; proc… | A bare -1 from `shared_memory_map`/`shared_memory_create` — the same value as a bad handle, an exhausted arena… |
| `system/kernel/vfs.zig:143` | @memcpy(d.path[0..parent.len], parent) — implici… | 64 == 64, by coincidence | external-data | Safe today, and safe with slightly more margin than the claim states. parentOf (vfs.zig:119-123) returns a strict prefix ending before the last '/', s… | Nothing would warn. The coupling is invisible from either file: system/initial-ramdisk.zig:26-28 reasons about… |
| `system/kernel/vfs.zig:315` | name_out (via process.zig:1972 name_buffer) | [64]u8 | external-data | Silent truncation with a header that agrees with the truncation rather than reporting it: vfs.zig:314-317 `const n = @min(name.len, name_out.len); @me… | None. The contrast is fair — system/kernel/log-ring.zig sets abi.klog_flag_truncated for exactly this situatio… |
| `system/services/acpi/acpi.zig:81` | mmio_scratch | [4096]u8 | external-data | No overflow — the aliasing IS the failure. library/device/acpi/aml/interpreter.zig:708 (readRegionByte) and :720 (writeRegionByte) both do `const virt… | None. No log fires on a SystemMemory access in either the interpreter or the HAL, so an _STA or _CRS that cons… |
| `system/services/acpi/acpi.zig:113` | <inline literal> | 64 | hardware | Falls through silently and proceeds as though ACPI mode were enabled. `while (tries < 1000 and (halPioRead(2, pm1a_cnt) & sci_en_bit) == 0) : (tries +… | None that distinguishes the two outcomes. No log fires on give-up, and the success message "acpi: power button… |
| `system/services/acpi/acpi.zig:306` | <inline literal> | 1000 | hardware | Falls through silently and proceeds as though ACPI mode were enabled. `while (tries < 1000 and (halPioRead(2, pm1a_cnt) & sci_en_bit) == 0) : (tries +… | None that distinguishes the two outcomes. No log fires on give-up, and the success message "acpi: power button… |
| `system/services/device-manager/device-manager.zig:50` | registry_source | [8192]u8 | external-data | Silent truncation of the file. `loadRegistry` (63-68): `while (used < registry_source.len) { const n = file.read(registry_source[used..]) orelse break… | Nothing says the file was cut. Only downstream symptoms: `{d} malformed line(s) skipped` (line 70) if the frag… |
| `system/services/device-manager/device-manager.zig:51` | registry_source | 8192 bytes | external-data | Silent truncation of the file. `loadRegistry` (63-68): `while (used < registry_source.len) { const n = file.read(registry_source[used..]) orelse break… | Nothing says the file was cut. Only downstream symptoms: `{d} malformed line(s) skipped` (line 70) if the frag… |
| `system/services/device-manager/device-manager.zig:531` | <inline literal> | reply tail of a 256-byte pac… | our-design | Silent truncation with a success status: `if (written + entry_size > tail.len) break;` and the handler returns the byte count. There is no cursor and … | None. The client sees a short but well-formed list. |
| `system/services/display/backend.zig:27` | device_table | [64]device.DeviceDescriptor | hardware | Confirmed as written but NOT reachable today. findDisplay (lines 54-63) does `const total = device.enumerate(&device_table); const n = @min(total, dev… | Misleading when it does fire, as claimed: Gop.init exhausts its retries and writes `display: no framebuffer de… |
| `system/services/display/compositor.zig:288` | <inline literal> | src.len >= w*h*4, against a … | our-design | Silent no-op reported as success. blitTile does `if (src.len < @as(usize, w) * h * 4) return;`, but blitLayer (display.zig:236-242) ignores that, stil… | None whatsoever: no log, and a success status. The symptom is a blank region. |
| `system/services/display/display.zig:76` | maximum_layers | 16 | our-design | Confirmed. `createLayer` (display.zig:208-210) is `const slot = freeLayer() orelse return null;`, and `onCreateLayer` (695-700) is `const slot = creat… | Nothing server-side for a client-facing exhaustion — confirmed. The service's own cursor path does log (`_ = l… |
| `system/services/display/display.zig:395` | mode_list / list | [4]backend_mod.Mode | hardware | Silent truncation on both hops: the backend clamps with `const count = @min(@min(offered.count, scanout_protocol.max_modes), out.len);` (backend.zig:1… | None — no log names the number offered versus the number kept. The mode-set self-check only says "no alternate… |
| `system/services/fat/engine.zig:70` | sector_size | 512 | external-data | Mount is refused, confirmed. Both paths test `if (geometry.bytes_per_sector == sector_size)` — engine.zig:193 (bare FAT at LBA 0) and engine.zig:209 (… | A wrong diagnosis: `_ = logging.write("/system/services/fat: not a FAT filesystem\n")` at system/services/fat/… |
| `system/services/fat/engine.zig:193` | sector_size (declared line 70) | 512 | external-data | Refuses to mount rather than corrupting, confirmed at engine.zig:193 and the MBR-partition path at engine.zig:209; both fall through to `return null`. | system/services/fat/fat.zig:162 `_ = logging.write("/system/services/fat: not a FAT filesystem\n")` — false fo… |
| `system/services/fat/fat.zig:73` | open_nodes (inline [_]OpenNode{.{}} ** 32) | 32 | our-design | Error returned, but the WRONG error, and silently: `const index = allocOpen() orelse return refused;` where `const refused: isize = -envelope.ENOENT;`… | Nothing. No log line at exhaustion, and the client is told the file does not exist. An operator debugging this… |
| `system/services/fat/fat.zig:285` | <inline literal> | reply tail of a 256-byte pac… | our-design | Silent truncation with a success status: `const name_len = @min(listing.name_len, into.len);` then `return @intCast(name_len);` — the client receives … | None. A directory listing shows a chopped filename that then fails to open. |
| `system/services/fat/fat.zig:285` | into.len (inline; = envelope.packet_maximum - pr… | 224 bytes | external-data | Silent truncation, and the reply's name_len is set to the TRUNCATED value, so the client cannot tell there was more. The engine's own buffer holds 260… | Nothing. |
| `system/services/init/init.zig:70` | max_service_args | 4 | external-data | Silent drop of the surplus arguments: loadServices, init.zig:122-127 `while (it.next()) \|argument\| { if (argument.len == 0) continue; if (service.ar… | None, and the contrast with its immediate sibling is confirmed: the max_services cap ten lines above logs `"/s… |
| `system/services/init/init.zig:161` | maximum_bindings | 16 | our-design | An error is returned to the binder: onBind, init.zig:620-622 `const slot = for (&bindings) \|*binding\| { if (!binding.used) break binding; } else ret… | Weak, and the asymmetry is confirmed: within the same function the EPERM path logs (init.zig:602-608) and the … |
| `system/services/init/init.zig:162` | maximum_grants | 64 | external-data | Parsing stops at 64 rows: loadGrants, init.zig:237-240 `if (grant_count >= grants.len) { _ = logging.write("... protocol.csv has more rows than the ta… | The overflow itself is logged with a direct `logging.write` naming the file (init.zig:238). The consequences a… |
| `system/services/init/init.zig:220` | protocol_csv | 16384 bytes | external-data | Silent truncation mid-line, then a heuristic report. readConfiguration (init.zig:138-146) fills the buffer and stops; the tail rows vanish and the las… | One heuristic info log: init.zig:147 `if (used == into.len) std.log.info("{s} filled the read buffer — rows pa… |
| `system/services/init/init.zig:220` | protocol_csv (with maximum_grants = 64 rows alon… | 16384 bytes / 64 rows | external-data | Truncation, announced on both limits. readConfiguration reports the byte cap at init.zig:147 (`std.log.info("{s} filled the read buffer — rows past {d… | Both limits log, which is what makes this the calibration point. The byte-limit line rides std.log.info (the r… |
| `system/services/init/init.zig:274` | process_table | [64]process.ProcessDescripto… | our-design | Partly handled, partly not — confirmed exactly. refreshProcessTable (init.zig:278-282) sets `process_truncated = total > process_table.len`, and taskA… | A bind refusal outside identify does log (init.zig:602-608), but a failed identify in onBind returns -EPERM wi… |
| `boot/efi.zig:308` | pool_pages | 64 frames (256 KiB) | hardware | TablePool.alloc, efi.zig:264-265: `if (self.next >= self.cap) return error.OutOfBootstrapFrames;`. Every map2M/map4K path is `try`, so it unwinds clea… | Good, and verified: main (efi.zig:34-39) writes unconditionally to con_out — `log("\r\nEFI: boot failed: "); l… |
| `boot/efi.zig:543` | info_buffer | 1024 bytes | external-data | `const n = try directory.read(&info_buffer);` (efi.zig:545) into a [1024]u8. UEFI answers EFI_BUFFER_TOO_SMALL for an EFI_FILE_INFO that will not fit;… | efi.zig:71-75 on con_out, naming the UEFI error but not the file. |
| `boot/efi.zig:543` | info_buffer (inline [1024]u8) | 1024 bytes | external-data | `const n = try directory.read(&info_buffer);` (efi.zig:545) — EFI_BUFFER_TOO_SMALL becomes an error and the `try` propagates out of walkDirectory and … | efi.zig:71-75 on con_out; names the UEFI error, not the file. |
| `boot/efi.zig:660` | BootInformation.kernel_segments (declared system… | [8]KernelSegment | our-design | `if (n < boot_information.kernel_segments.len) { ... }` (efi.zig:659-668) with no else — the segment is copied to its physical address but never recor… | Nearly nothing, but not quite nothing: kernel.zig:159 prints `log.print(" kernel segs: {d} (mapped with W^X p… |
| `boot/efi.zig:680` | <inline literal> (attempts) and cap = info.len +… | 8 attempts; +8 spare descrip… | hardware | Correct and safe, as claimed. efi.zig:680-700: on each attempt both pool buffers are sized from the firmware's own descriptor count plus 8, a failed g… | The fatal case reaches main's handler: 'EFI: boot failed: ExitBootServicesFailed' on con_out, then hlt. No bre… |
| `boot/efi.zig:787` | buffer (logBytes) | 128 UTF-16 units | our-design | `if (i + 1 >= buffer.len) break;` (efi.zig:790) — the tail of the string is dropped, the result is NUL-terminated at the truncation point and printed.… | This IS the observability path — logBytes is the only way a runtime string (in practice an @errorName from mai… |
| `build/images.zig:152` | <inline literal> (mk_fat.addArg("64")) | 64 (MiB) | our-design | Build-time hard failure. tools/make-fat-image.py:67-68 — `if cluster >= self.cluster_count + 2: sys.exit("error: image out of clusters")` inside the c… | "error: image out of clusters" on stderr, which aborts the build. It names neither the file being added nor a … |
| `library/device/acpi/aml/interpreter.zig:55` | maximum_segments | 16 | external-data | Silent truncation in `Cursor.segment` (123-129): `const s = try self.take(4); if (name_path.count < maximum_segments) { ...store... }` — the cursor ad… | None. Line 299's comment `// unknown name -> treat as uninitialised` is by design, so a truncated name is indi… |
| `library/device/acpi/aml/parser.zig:24` | maximum_segments | 64 | external-data | appendSegment (parser.zig:137-143) always consumes the 4 name bytes via readNameSegment — so the cursor stays in sync — but silently discards the segm… | None. aml.zig:36-56 builds a ParseResult{consumed,total} precisely so a desync is detectable, but the only con… |
| `library/device/block/block.zig:95` | <inline literal> | 600 attempts × 50 ms = 30 s | our-design | Returns null; the caller (the FAT server) reports no volume. | Nothing logged at this level, but the number is justified against a measurement. |
| `library/device/driver/driver.zig:165` | lookup_attempts | 100 (× lookup_pause_ms = 20 … | our-design | `hello()` runs `while (attempts < lookup_attempts) : (attempts += 1) { if (channel.openEndpoint("device-manager")) \|handle\| break handle; time.sleep… | Good, and I confirmed it at driver.zig:181 — the else branch IS the log. Requiring callers also announce their… |
| `library/device/model/device-abi.zig:139` | DeviceDescriptor.hid | [8]u8 | hardware | No truncation is reachable today. The cited site (devices-broker.zig:121-122) cannot truncate: `node.hid()` returns `hid_buffer[0..hid_len]` from devi… | Not applicable — nothing truncates. The 8-byte-with-no-NUL width does cause a live defect elsewhere: system/se… |
| `library/device/pci/pci.zig:37` | bar_virtual | [6]usize | hardware | Errors: `pub fn mapBar(self: *Function, bar: u8) ?usize { if (bar >= 6) return null;` — a caller asking for BAR 6 gets null rather than an out-of-boun… | Null from `mapBar`, which each driver reports in its own words. |
| `library/device/pci/pci.zig:283` | CapabilityIterator.guard (and ExtendedCapability… | 48 and 480 | hardware | Iteration ends. Silent, but correctly so: the bound is derived from the size of the address space being walked, so reaching it means the device's chai… | Nothing — and it needs nothing, because the bound cannot cut a well-formed chain short. |
| `library/device/pci/pci.zig:286` | <inline literal> | 48 | hardware | The iterator silently ends: `if (self.cursor == 0 or self.guard >= 48) return null;` — indistinguishable from the end of a well-formed list. `findCapa… | Nothing. No log distinguishes 'no MSI capability' from 'capability list is a loop'. |
| `library/device/pci/pci.zig:371` | <inline literal> | 480 | hardware | Silently ends the iteration: `if (self.cursor == 0 or self.guard >= 480) return null;`. `findExtendedCapability` then reports absence. | Nothing. |
| `library/device/registry/device-registry.zig:200` | cols | [9][]const u8 | external-data | Errors and counts. parseLine: `if (count >= cols.len) return .malformed; // too many columns` and after the loop `if (count != cols.len) return .malfo… | Verified end to end, and it is genuinely good: system/services/device-manager/device-manager.zig:71 `if (resul… |
| `library/device/registry/device-registry.zig:239` | out_rules.len (caller-supplied) | caller's buffer | external-data | `if (result.count >= out_rules.len) { result.truncated = true; continue; }` inside parse — the surplus valid rules are dropped and the flag records it… | The best in the tree, and I confirmed the caller actually uses it: device-manager.zig:72 `if (result.truncated… |
| `library/kernel/channel.zig:37` | path_maximum | 224 | our-design | Refuses: `join` (285) `if (total > buffer.len) return null;`. `reach` (182-193) returns null when `file_system.fsResolve` cannot write the rewritten p… | None — null, no log, same documented three-way ambiguity. |
| `library/kernel/channel.zig:46` | name_maximum | 64 | our-design | Refuses, never truncates: `join` (282-290) `if (name.len == 0 or name.len > name_maximum) return null;`, which `openEndpoint` (238-242) turns into a n… | None (no log), and the null is deliberately three-way ambiguous per the doc at 231-237: no such contract / not… |
| `library/kernel/memory/heap.zig:199` | <inline literal> | 16 | our-design | Refuses cleanly: `fn allocImpl(_: *anyopaque, len: usize, alignment: std.mem.Alignment, _: usize) ?[*]u8 { if (alignment.toByteUnits() > 16) return nu… | An allocation failure, which std reports as OutOfMemory — a misleading name for an alignment refusal, and no l… |
| `library/kernel/process.zig:116` | <inline literal> | [8]u8 | our-design | The kernel refuses the *sender* rather than truncating (the receive capacity travels in r8 to `ipc_reply_wait`), so a client that calls into a process… | The refusal reaches the caller as an IPC failure; the stopping process logs nothing. |
| `library/kernel/process.zig:185` | <inline literal> | [256]u8 | our-design | Errors, cleanly: `if (len >= blob.len) return null;` and `if (len + argument.len > blob.len) return null;` — the spawn never happens and null is retur… | Poor. `spawn*` returning null is the same answer as 'no such binary' or 'task table full'; the caller (e.g. th… |
| `library/kernel/service.zig:94` | subscriber_capacity | 8 | our-design | onSubscribe (service.zig:264) walks `slots`, and if no slot is free returns `-envelope.ENOSPC`. The turn then closes the endpoint capability that arri… | No log in the provider. On the subscriber side the only real caller in the tree does log: system/services/disp… |
| `library/kernel/thread.zig:41` | tls_block_size | 64 | our-design | No check exists anywhere. thread.zig:88-90 carves `closure_addr` down from the stack top and then `const tls_base = (closure_addr - tls_block_size) & … | None — nothing tracks a TLS extent, so nothing could report it. The symptom would be a thread running with cor… |
| `library/protocol/display/display-protocol.zig:99` | max_modes | 4 | our-design | Silent drop of the surplus, but it can never fire. Provider side confirmed at system/services/display/display.zig:749-757: `var list: [4]backend_mod.M… | Nothing at either end — no log — but nothing is dropped either. |
| `library/protocol/scanout/scanout-protocol.zig:29` | max_modes | 4 | hardware | Silent truncation on both sides, exactly as claimed. Driver: virtio-gpu.zig:525-527 `var offered = scanout_protocol.Modes{ .count = offered_modes.len … | None. Confirmed: neither `modes()` in backend.zig nor the get_modes handler in virtio-gpu.zig emits anything a… |
| `library/xkeyboard-config/xkeyboard-config.zig:80` | map(layout, hid_usage: u8, …) | u8 (indexing Layout.keys: [2… | hardware | No overflow is possible — `keys: [256]Key` (library/xkeyboard-config/generated/layouts.zig:20) exactly covers the u8 domain, and an unmapped usage yie… | A key that maps to nothing produces no character; nothing distinguishes 'unmapped' from 'narrowed to the wrong… |
| `system/drivers/pci-bus/pci-bus.zig:36` | <inline literal> var line: [320]u8 (the per-func… | 320 bytes | our-design | `const text = std.fmt.bufPrint(&line, "...", .{...}) catch return;` at line 37 — the whole breadcrumb for that function is dropped and logFunction ret… | Nothing. The function simply does not appear in the boot log, which reads identically to "the walk did not fin… |
| `system/drivers/pci-bus/pci-bus.zig:182` | <inline literal> if (descriptor.resource_count >… | 8 | our-design | `break` out of the `while (i < 6)` BAR-sizing loop at line 181. Remaining BARs are never sized, never recorded in the descriptor and never restored-th… | Nothing. No log, no counter, and the loop's `configWrite16(bus, dev, function, 0x04, command)` decode-restore … |
| `system/drivers/ps2-bus/ps2-library.zig:464` | <inline literal> while (guard < 16) in drainOutp… | 16 bytes | hardware | Returns with the output-buffer-full bit possibly still set. No error, no retry, no signal to the caller (the function returns void). Callers are ps2-b… | None — silent void return. |
| `system/drivers/usb-hid/keyboard.zig:107` | <inline literal> receive: [64]u8 (identically at… | 64 | our-design | Currently sufficient with 4 bytes to spare: the protocol's own test asserts Protocol.event_maximum == 60 and event_maximum <= envelope.post_maximum (l… | Nothing here would report an over-long message; the driver's guard is `if (message.length < @sizeOf(hid.Keyboa… |
| `system/drivers/usb-xhci-bus/usb-xhci-bus.zig:521` | <inline literal> hid_buffer: [8]u8 (the "P<port>… | 8 bytes | our-design | Confirmed at lines 521-523: `var hid_buffer: [8]u8 = undefined; const hid_text = std.fmt.bufPrint(&hid_buffer, "P{d}I{d}", .{ port, interface.number }… | Nothing. `catch ""` swallows the bufPrint failure, register returns an existing id which looks like a normal i… |
| `system/drivers/usb-xhci-bus/usb-xhci-bus.zig:763` | <inline literal> if (serviced >= 32) break | 32 hub changes per tick | our-design | Deferral, not loss. `while (engine.takeHubChange()) \|change\| { ... serviced += 1; if (serviced >= 32) break; }` — the remaining changes stay in each… | Not needed; nothing is lost. There is no log, correctly. |
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:131` | trbs_per_ring (= page_size / @sizeOf(Trb)) | 256 | our-design | Correct wraparound. `push` (155-178) writes slot `enqueue_index`, and when the index reaches `trbs_per_ring - 1` (the Link slot) it re-installs the Li… | Not needed. |
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:456` | <inline literal> port_changes: [16]u32 | 16 | hardware | Silently dropped in `pump` (1610-1613): `if (self.port_change_count < self.port_changes.len) { self.port_changes[...] = port; self.port_change_count +… | Nothing at the drop site. Recovered in practice by the level reconcile in serviceController (usb-xhci-bus.zig:… |
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:456` | port_changes (inline [16]u32) | 16 | hardware | Silent drop, no else (pump, 1610-1613). The PORTSC change bits are already acknowledged at 1608-1609, so the edge is consumed even when the queue entr… | Nothing at the drop site; recovered by the independent per-port level reconcile at usb-xhci-bus.zig:727-741, w… |
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:496` | <inline literal> guard < 64 in the xECP capabili… | 64 extended capabilities | hardware | The `while (offset != 0 and guard < 64)` walk simply stops; a Supported Protocol capability past the 64th is not logged. Diagnostic only. | Nothing distinguishes 'chain ended' (the `if (next == 0) break;` at 509) from 'guard tripped'. |
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:603` | <inline literal> device_context_array = memory.d… | 512 entries (4096 / 8), vs M… | hardware | Safe, but only by accident of type width: slot_id is a u8 (`return @truncate(event.control >> 24)` in enableSlot), so `array[device.slot_id]` cannot e… | Not applicable today. |
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:1069` | <inline literal> while (tries < 200) with time.s… | 200 tries = ~1 s | hardware | Falls out of the loop, re-reads status at 1076, and if still not enabled: `std.log.info("hub slot {d} port {d}: reset did not enable", .{ hub.slot_id,… | Good — a specific log line naming hub slot and port, quoted above. |
| `system/drivers/virtio-gpu/virtio-gpu.zig:77` | queue_size | 16 | our-design | The only failure direction is a device offering fewer than 16, and it is checked and refused loudly — confirmed at lines 282-286: `const device_qsize … | Explicit log line carrying the device's actual value, then a clean bring-up failure. |
| `system/drivers/virtio-gpu/virtio-gpu.zig:163` | <inline literal> while (tries < 2000) in waitUse… | 2000 iterations ≈ 2 s | our-design | Returns false (line 172). submit returns false, command_nodata returns 0 (line 184), which never equals ok_nodata, so each bring-up call site logs its… | Good on the BRING-UP path only. The serving path is silent: presentFull's two failure returns (lines 461 and 4… |
| `system/drivers/virtio-gpu/virtio-gpu.zig:405` | <inline literal> .scanout_id = 0 (and resource_i… | 1 scanout, 1 resource, 1 bac… | hardware | No runtime limit exists — confirmed. Grepped the whole tree: `get_display_info`, `RespDisplayInfo` and `max_scanouts` appear ONLY in their declaration… | Nothing about head count, because it is never asked. The file header does state the scope: "this instance clai… |
| `system/drivers/virtio-gpu/virtio-gpu.zig:486` | <inline literal> while (tries < 50) with time.sl… | 50 tries = 1 s | our-design | Logs and returns, confirmed at lines 485-492: `const display = while (tries < 50) : (tries += 1) { if (channel.openEndpoint("display")) \|h\| break h;… | One clearly worded log line. The lasting consequence — the display stays on the boot framebuffer permanently —… |
| `system/drivers/virtio-gpu/virtio-gpu.zig:525` | <inline literal> .count = offered_modes.len set … | 2 offered vs 4 slots | our-design | Not reachable at current constants (offered_modes.len = 2 <= scanout_protocol.max_modes = 4), so nothing happens today. The shape is unsafe as describ… | Would be silent at the point of the bug; the downstream re-clamps mean the surplus is dropped rather than read… |
| `system/kernel/acpi.zig:130` | maximum_rmrr | 8 | hardware | Counted, not silent — confirmed at acpi.zig:873-882: `if (platform_information.rmrr_count < maximum_rmrr) { ...record... } else { platform_information… | Good, and I verified the log fires: system/kernel/iommu.zig:393-394 `if (info.rmrr_skipped > 0) log.print(" r… |
| `system/kernel/architecture/x86_64/cpu.zig:69` | systemCallArg (switch arms 0..5) | 6 arguments | our-design | `else => 0` — an argument index of 6 or more silently reads as zero rather than failing. Same shape at cpu.zig:788 (`pioRead` returns 0 for a width ot… | None; a caller asking for a seventh argument gets a plausible-looking 0. |
| `system/kernel/architecture/x86_64/gdt.zig:28` | entries | 7 | our-design | Compile-time only. `const entries = 7;` sizes the template (gdt.zig:36-44) and both gdts rows; setTssFor writes fixed indices 5 and 6, and loadOnThisC… | n/a — a build-time constraint. |
| `system/kernel/architecture/x86_64/gdt.zig:50` | gdts | [maximum_cpus][7]u64 (128 ta… | hardware | `loadOnThisCpu(cpu)` (gdt.zig:78-84) takes `@intFromPtr(&gdts[cpu])` with no guard in this file; in a safe build an out-of-range cpu is a bounds-check… | Via the ACPI/SMP path only: kernel.zig:281 prints 'cpus : WARNING {d} core(s) beyond pool cap dropped' from pl… |
| `system/kernel/architecture/x86_64/ioapic.zig:24` | overrides | [16]IsoEntry | hardware | Silent truncation at three independent layers, all verified: acpi.zig:558 `if (platform_information.override_count < platform_information.overrides.le… | None at any of the three layers — no counter, no log. |
| `system/kernel/architecture/x86_64/iommu-intel.zig:284` | <inline literal> 10_000_000 (spinStatus) | 10000000 | our-design | Logs a warning and returns; `enable()` then sets `gcmd_shadow \|= gcmd_te` and the core reports the IOMMU as online even though translation may not be… | "/system/kernel: WARNING VT-d status bit never set — translation may be incomplete" — a real log line, which i… |
| `system/kernel/architecture/x86_64/paging.zig:70` | bootstrap_physmap_limit | 4 << 30 (4 GiB) | hardware | `@panic("paging: table frame above the 4 GiB bootstrap physmap")` at paging.zig:84-85, guarded by `if (!on_own_tables and frame >= bootstrap_physmap_l… | A named panic message on the console/serial. The 9-line comment at lines 55-62 states the window, why it holds… |
| `system/kernel/architecture/x86_64/per-cpu.zig:50` | blocks | [maximum_cpus]ArchitecturePe… | hardware | `setLocal(index, …)` and `setKernelRsp(index, …)` index unguarded; bounded upstream, ReleaseSafe bounds check as backstop. A ReleaseFast build would w… | Nothing in this file. |
| `system/kernel/architecture/x86_64/serial.zig:83` | <inline literal> 10_000 (probe guard) | 10000 | hardware | The loop ends, `echo = register(0)` is read regardless, and `return echo == 0xAE` (serial.zig:83-86). A false answer sets uart_present = false, after … | Recoverable but indirect: present() is exposed (serial.zig:91-93) and the boot log reports the posture, and re… |
| `system/kernel/architecture/x86_64/smp.zig:124` | <inline literal> (1 << 32) | 4294967296 | our-design | `if (cr3 >= (1 << 32)) @panic("smp: kernel page tables above 4 GiB");` — the first statement of startAp, before arm() and before any INIT/SIPI is sent… | Named panic message that states the actual condition. |
| `system/kernel/architecture/x86_64/smp.zig:141` | <inline literal> @intCast(tramp_physical >> 12) | u8 SIPI vector (frame must b… | hardware | `const vector: u8 = @intCast(tramp_physical >> 12);` — in a safety-checked build (the default), a trampoline frame at or above 1 MiB triggers a "cast … | A safety-check panic with the generic cast message — it does not name the trampoline or the 1 MiB constraint. … |
| `system/kernel/architecture/x86_64/smp.zig:149` | <inline literal> 100 (ms AP wake window) | 100 | our-design | `const deadline = apic.millis() + 100;` then a pause-spin on ap_alive; on expiry `return false`. The caller at system/kernel/kernel.zig:437-444 retrie… | Good, and the best in this set. On give-up: `log.print("/system/kernel: cpu apic_id {d}: no response after {d… |
| `system/kernel/architecture/x86_64/tss.zig:48` | tss_table / ap_ist_top | [maximum_cpus]Tss and [maxim… | hardware | `rsp0Ptr` (62-64), `setApIstStack` (68-70) and `setupThisCpu` index `tss_table[cpu]` / `ap_ist_top[cpu]` with no guard in this file; the bound is enfo… | Reported by the layer above, and it really is reported: kernel.zig:280-281 `if (platform.cpusDropped() > 0) lo… |
| `system/kernel/device-model.zig:72` | name_buffer | [24]u8 | our-design | Silent truncation in `setName` (lines 94-98, `@min` then `@memcpy`), reached from `DeviceTree.init` (line 138) and `addChild` (line 159). In practice … | None, but nothing incorrect happens either; names are diagnostic only (the boot dump), never a matching key. |
| `system/kernel/device-model.zig:72` | Device.name_buffer | [24]u8 | our-design | Silent truncation in setName; unreachable in practice. See the kernel-core duplicate: every caller passes either a literal or the result of a bufPrint… | None needed. |
| `system/kernel/ipc-synchronous.zig:71` | POST_MAXIMUM | 64 | our-design | `if (len > POST_MAXIMUM) return -E2BIG;` — sendLocked, ipc-synchronous.zig:566, before anything is touched. A distinct errno straight back to the call… | -E2BIG, specific and actionable. |
| `system/kernel/ipc-synchronous.zig:113` | notify_buffer | [8]u64 | our-design | Silent drop of the NEWEST badge: notifyLocked, ipc-synchronous.zig:596-602 — the store happens only inside `if (endpoint.notify_tail -% endpoint.notif… | None, and the file argues at 593-595 why that is correct for a level rather than merely tolerable. |
| `system/kernel/ipc-synchronous.zig:113` | Endpoint.notify_buffer | [8]u64 | our-design | Silent drop of the newest badge — outside notifyLocked's guard nothing but the wake happens (ipc-synchronous.zig:596-602). | Nothing, by design. |
| `system/kernel/kernel.zig:246` | isos | [16]architecture.IsoEntry | hardware | Silent clamp: `var isos: [16]architecture.IsoEntry = undefined; const iso_n = @min(pinfo.override_count, isos.len);` (246-247) — a second truncation s… | None. The boot log prints the I/O APIC base and route information but never the override count. |
| `system/kernel/kernel.zig:421` | maximum_wake_attempts | 3 | our-design | The core is left parked and bring-up continues: the `while (attempt <= maximum_wake_attempts)` loop at 437 falls through to the log at 443-444; the ad… | Exemplary, and verified verbatim: `log.print("/system/kernel: cpu apic_id {d}: no response after {d} attempts… |
| `system/kernel/log.zig:41` | maximum_sinks | 8 | our-design | Silent ignore, confirmed at lines 47-52: `pub fn addSink(sink: SinkFn) void { if (sink_count < maximum_sinks) { sinks[sink_count] = sink; sink_count +… | None in code, though self-announcing in practice (output does not appear on the missing channel). |
| `system/kernel/log.zig:85` | ring_capacity | 512 * 1024 | our-design | Whole records are reclaimed from the tail, never a torn record — confirmed at log-ring.zig:48, `while (self.head + record_len - self.tail > capacity) … | Best in the tree, as claimed, and I verified each mechanism: per-boot monotonic `sequence` stamped into every … |
| `system/kernel/log.zig:244` | PanicRecord.message | [512]u8 | our-design | Silent truncation that is self-describing, confirmed at lines 251-256: `const n: u32 = @intCast(@min(message.len, panic_record.message.len)); @memcpy(… | The record carries its own length and the magic-last discipline prevents a torn read. Confirmed the caller's p… |
| `system/kernel/process.zig:109` | maximum_arguments / maximum_argument_bytes | 8 / 256 | our-design | All three checks confirmed. process.zig:976 `if (arguments_len > maximum_argument_bytes) return fail(state);`; process.zig:1012 `if (argc == maximum_a… | -1 from system_spawn with no log and the error name discarded at process.zig:1018 — confirmed. |
| `system/kernel/process.zig:148` | write_buffer | [256]u8 | our-design | Confirmed at process.zig:1801: `if (len <= write_buffer.len and ptr < user_half_end and ptr + len <= user_half_end) { ... } else { fail(state); }` — I… | -1 to the caller at the syscall, and the ring-level truncation is flagged in the record header — the only boun… |
| `system/kernel/process.zig:1460` | exit_record_capacity | 64 | our-design | Confirmed. `recordExitLocked` (1467-1470) overwrites the oldest via `exit_record_next = (exit_record_next + 1) % exit_record_capacity;` and an evicted… | -ESRCH with a documented interpretation, and the docstring (1455-1459) states the equivalence to 'an id that n… |
| `system/kernel/scheduler.zig:155` | ipc_maximum_handles | 32 | our-design | Visible and correctly unwound, confirmed. `installEntry` (ipc-synchronous.zig:618-627) scans `t.handles` and `return -ENOSPC`; the cap-passing path at… | -ENOSPC reaches the caller through the IPC status — a distinct, actionable error, unlike the -1 that most othe… |
| `system/kernel/scheduler.zig:485` | cpus (PerCpu pool) | [maximum_cpus]PerCpu = [128] | hardware | Cannot be overrun. acpi.zig:534-543 gates recording on `if (cpu_information.count < cpu_information.cpus.len)` and counts the surplus into `dropped`, … | kernel.zig:280-281 `if (platform.cpusDropped() > 0) log.print(" cpus : WARNING {d} core(s) beyond pool … |
| `system/kernel/tests.zig:410` | buffer (device enumerate staging) | [64]device_abi.DeviceDescrip… | our-design | Two coupled problems. (1) The value 64 duplicates devices-broker's `maximum_devices` in eight places (tests.zig:410, 1449, 2834, 3931, 4230, 4246, 437… | None for either. A test that silently examines a truncated table still passes. |
| `system/kernel/vfs.zig:59` | maximum_prefix / maximum_rewrite | 64 / 32 | our-design | Visible refusal on the mount path: mountBackend, vfs.zig:383-384 `if (!isAbsolute(prefix) or prefix.len < 2 or prefix.len > maximum_prefix) return fal… | A -1 return with no log and no distinct errno. The mounting service's own failure message is what an operator … |
| `system/kernel/vfs.zig:143` | Directory.path | [maximum_prefix]u8 = [64]u8 | external-data | `@memcpy(d.path[0..parent.len], parent);` (vfs.zig:143) into `path: [maximum_prefix]u8` (vfs.zig:88) with no @min and no guard — the only copy in the … | A boot-time panic in safe modes (loud but fatal, before init runs); nothing at all plus corrupted neighbours i… |
| `system/services/acpi/acpi.zig:74` | registered | [64]Registered | our-design | Unreachable — this is NOT the operative ceiling. `if (registered_count >= registered.len) return;` at line 513 is the first statement of registerDevic… | The real ceiling does log, once per lost device: `std.log.info("register refused for {s}", .{hid[0..@intCast(h… |
| `system/services/device-manager/device-manager.zig:51` | registry_rules | [64]registry.Rule | external-data | Rules past the 64th are dropped by `registry.parse` (library/device/registry/device-registry.zig:239-241): `if (result.count >= out_rules.len) { resul… | Good: device-manager.zig:72 `if (result.truncated) _ = logging.write("/system/services/device-manager: /system… |
| `system/services/device-manager/device-manager.zig:129` | Driver.name_buffer | [64]u8 | our-design | Silent truncation, not refusal: `addDriver` (242-244) `const n = @min(name.len, driver.name_buffer.len); @memcpy(driver.name_buffer[0..n], name[0..n])… | Indirect: the failure appears one step later as `failed to spawn {s}` (line 268) printing the truncated path, … |
| `system/services/device-manager/device-manager.zig:260` | id_text | [20]u8 | our-design | `arguments[0] = std.fmt.bufPrint(&id_text, "{d}", .{driver.device_id}) catch return;` (264) — on overflow `spawnDriver` returns without spawning AND w… | None — the only silent return in spawnDriver; every other failure path there logs (268 `failed to spawn`, 285/… |
| `system/services/display/backend.zig:69` | <inline literal> | 100 | our-design | Confirmed at lines 68-75: `var tries: u32 = 0; const found = while (tries < 100) : (tries += 1) { if (findDisplay()) \|f\| break f; time.sleepMillis(5… | Logged, but misleadingly — "headless?" is one of at least three possible causes (genuinely headless, discovery… |
| `system/services/display/compositor.zig:74` | DamageList.capacity | 16 | our-design | No loss: `add` (lines 79-93) ends `self.rects[capacity - 1] = self.rects[capacity - 1].unite(r);`, so the overflow rectangle is united into the last e… | Not needed — nothing is dropped and nothing becomes incorrect. |
| `system/services/display/compositor.zig:121` | TileGrid.maximum_columns / maximum_rows | 128 / 128 | hardware | Graceful, documented degradation. `reset` clamps with `@min((width + tile_size - 1) / tile_size, maximum_columns)` and the same for rows (lines 139-14… | No log, and none needed — the behaviour stays correct, only the repaint granularity changes. |
| `system/services/fat/engine.zig:24` | max_transfer_sectors | 8 | our-design | Not a failure mode, confirmed. The transfer loop clamps and issues more commands: `const run: u32 = @intCast(@min(full, max_transfer_sectors));`. The … | Not applicable — correctness is unaffected, only the number of device round-trips. |
| `system/services/fat/engine.zig:80` | block_cache_lines | 16 | our-design | Round-robin eviction, write-through — correctness preserved, only hit rate degrades. | Not needed. |
| `system/services/fat/engine.zig:871` | <inline literal> | 4096 | external-data | `if (sector_index > 4096) return null;` ends the search, so findFreeRun/addEntry return null, createFile/createDirectory return null and the VFS handl… | None in the service; no log, and the errno collapses into the same ENOENT everything else uses. |
| `system/services/fat/engine.zig:1047` | run | [21]EntryLoc | external-data | Silent partial cleanup, confirmed. `var run: [21]EntryLoc = undefined;` at engine.zig:1047 (removeFile, line 1046) and 1114 (rename, line 1110), recor… | None. |
| `system/services/init/init.zig:69` | max_services | 16 | external-data | Rows past the 16th are refused and parsing stops: init.zig:114-117 `if (service_count >= services.len) { _ = logging.write(...); break; }`. | Good: a direct `logging.write` (not just a ring entry) naming the file — `"/system/services/init: /system/conf… |
| `system/services/init/init.zig:84` | init_csv / protocol_csv | [4096]u8 / [16384]u8 | external-data | Truncation, detected and reported. readConfiguration (init.zig:138-149) fills the buffer and stops (`while (used < into.len) { const n = file.read(int… | An explicit log naming the file and the byte count. It is a heuristic (a file exactly the buffer's size gives … |
| `system/services/init/init.zig:84` | init_csv | 4096 bytes | external-data | Silent truncation mid-line via the shared readConfiguration (init.zig:141-146), after which the severed line parses as a service path that does not ex… | The same heuristic info log as protocol.csv: init.zig:147 '{s} filled the read buffer — rows past {d} bytes ar… |
| `system/services/init/init.zig:160` | maximum_name | 64 | our-design | Refused, not truncated — contractName, init.zig:498-502 `if (name.len == 0 or name.len > maximum_name) return null;`, and both callers answer with an … | None on the open path, deliberately (init.zig:652-677 explains why a refusal and an absence must be the same a… |
| `system/services/init/init.zig:173` | Binding.binary | [64]u8 | our-design | Silent truncation: onBind, init.zig:630-632 `const binary_len = @min(identity.binary.len, slot.binary.len); @memcpy(slot.binary[0..binary_len], identi… | The truncated path is what appears in the provenance line (init.zig:635) and in the EBUSY refusal message (ini… |
| `system/services/logger/logger.zig:53` | maximum_files | 24 | our-design | No loss. fileFor (line 229) looks for a matching cached name, then a free slot, then `const cached = slot orelse evictOne() orelse return null;` at li… | Nothing logged on eviction. The symptom is slow logging, not lost logging, which is the right trade. |
| `system/services/logger/logger.zig:57` | CachedFile.name | [logging.maximum_process_nam… | external-data | Panic, in a narrower window than claimed. fileFor formats the path FIRST (line 245, `std.fmt.bufPrint(&path, "{s}/{s}.log", ...) catch return null`) i… | A process fault, visible as the logger dying; init's crash-loop policy stops restarting it after three deaths,… |
| `system/services/logger/logger.zig:72` | carry_capacity | 64 + 256 + 64 | our-design | consume (line 187-191): `const rest = bytes.len - offset; if (rest > carry_capacity) { carry_len = 0; // cannot happen with sane frames; drop rather t… | Partly self-reporting, and the claim was right to credit it: deliver (lines 199-206) compares header.sequence … |
| `system/services/logger/logger.zig:82` | <inline literal> | 64 | our-design | Benign today. `service.run(64, .{ .init = initialise, .on_message = onMessage, ... })` at line 82 sizes the harness receive/reply buffer. The logger s… | None, and none needed while onMessage is a no-op. |
| `system/services/logger/logger.zig:243` | path | [base.len + 1 + 19 + 1 + log… | our-design | Silent record loss. `const full = std.fmt.bufPrint(&path, "{s}/{s}.log", .{ boot_directory[0..boot_directory_len], relative }) catch return null;` (li… | None. Records for that process never appear on disk, and the gap accounting cannot flag it: next_expected_sequ… |
| `tools/make-fat-image.py:53` | <inline literal> (65525) | 65525 clusters (~33 MiB at 5… | our-design | Loud build failure: `sys.exit(f"error: image too small for FAT32 ({self.cluster_count} clusters < 65525); use a larger size")` — and --verify repeats … | Build stops with a message naming both the actual count and the requirement, and telling the operator what to … |
| `tools/make-fat-image.py:212` | <inline literal> (LFN sequence numbering) | implicitly 20 entries / 255 … | our-design | Silent corruption (my reading; not exercised): `count = len(pairs) // 13` then `entry[0] = sequence \| (0x40 if sequence == count else 0)` — for a nam… | Nothing at build time; --verify only resolves EFI/BOOT/BOOTX64.EFI by short name, so a mangled LFN chain elsew… |
| `tools/make-fat-image.py:329` | <inline literal> (guard) | 100000 cluster hops | our-design | `return None`, which the caller turns into a misleading verdict: `sys.exit("verify: EFI/BOOT/BOOTX64.efi not found")` — a chain-too-long or cyclic FAT… | A wrong-but-visible error message. The operator is told the stub is absent when the real problem is FAT struct… |
| `tools/make-iso-image.py:151` | sector_count | 0xFFFF (32 MiB at 512 B/sect… | our-design | Deliberate silent clamp, confirmed at line 151: `sector_count = min(0xFFFF, esp_size // 512)`, packed into the El Torito default entry's 16-bit field … | Nothing at build time about the clamp itself, but the true geometry is visible: the builder prints the ESP siz… |
| `tools/make-xkeyboard-config.py:308` | <inline literal> (range(256)) / generated keys: … | 256 HID usages | hardware | No overflow inside the generator (HID_TO_NAME only maps usages below 0x100). The bound is exported into the generated `Layout.keys: [256]Key`, so any … | Nothing here; whatever the input service does with an out-of-range usage is its own concern (outside this area… |
| `tools/make-xkeyboard-config.py:314` | <inline literal> (range(4)) / generated levels: … | 4 shift levels per key | external-data | Silent truncation at generation time: `levels = [resolve_keysym(kd.levels[i], keysymdef) if i < len(kd.levels) else (0, 0) for i in range(4)]` — level… | Nothing. The generator prints no warning and the generated file looks complete; the missing characters only ap… |
+54
View File
@@ -0,0 +1,54 @@
# The hot-plug matrix: unplug anything, replug anywhere
*Status: COMPLETE, 2026-08-09, same day — H1..H5 all green, full suite 124/124.
The predicted cascade bug was real and found by H2: `tearDownPort` did not recurse
into a hub yanked from a root port, so its subtree stayed live against vanished
hardware and the replugged hub found its port occupied; fixed by mirroring
`tearDownHubDevice`'s children-first recursion (77e7001). Every other cell passed
against the establishment-track machinery unchanged.*
*2026-08-09. The requirement, verbatim: "i want to be able to unplug devices and
plug them back in, in any order and on any hub." The machinery exists end to end —
per-device driver processes, cascading teardown (`tearDownHubDevice` recurses a
departing hub's subtree, children first), reap-on-removal in the manager, idempotent
per-port registration identity, lineage rebinding — but only one cell of the matrix
is verified: a leaf keyboard behind a hub, unplugged and replugged on the same port
(`usb-hub-unplug`). This plan verifies the rest and fixes what verification flushes
out. The cascade path has never executed; expect it to carry at least one bug.*
**Out of scope, stated up front:** unplugging the BOOT stick (the drivers handle it;
fat holds a dead block channel until M21 remount gives it re-acquisition), and
real-hardware root-port timing (the Ryzen bench is the acceptance run for that, as
always — QEMU proves the logic, not the silicon).
## The discrimination lever
Every case's rebind tail (— reaping → delegated → second-generation `ok`) is
impossible without the manager's reap: stashing the reap out of
`onChildRemoved`/`pruneChildrenOf` makes every matrix case fail at the dedupe wall.
That is the standing discrimination check for the whole matrix — run it once per
case shape, not per commit.
## The matrix
| Case | Topology | Event sequence | What it proves |
|---|---|---|---|
| H1 `usb-root-replug` | keyboard on a 2nd controller's ROOT port | del @8s, add @14s (same port) | the `tearDownPort` path + reap + rebind; root-port changes arrive via the 250 ms reconcile tick (QEMU raises no root-port events) |
| H2 `usb-hub-yank` | hub on 2nd controller; keyboard AND mouse behind it | del the HUB @8s; re-add hub @14s, kbd @17s, mouse @18s | the recursive cascade: one event removes the subtree, EVERY bound driver is reaped, and the rebuilt hub re-binds both |
| H3 `usb-hub-nested-yank` | hub → hub → keyboard | del the OUTER hub @8s; re-add all three @14–18s | the cascade recursion depth ≥ 2, and a nested rebuild |
| H4 `usb-replug-moved` | keyboard behind hub port 1.1 | del @8s; add on port 1.2 @14s | a replug on a DIFFERENT port is simply a new device: new port identity, new id, fresh match — no stale state ties a driver to the old port |
| H5 `usb-replug-cycles` | keyboard behind hub | del/add three times (6 hooks) | no state leaks across generations: slots, the bus's open table, driver entries (reaped entries must be reusable) |
Ordered expects follow the `usb-hub-unplug` shape: the boot devices' `ok` lines all
precede the first unplug, so a tail of `removed → reaping → delegated → ok` can only
be satisfied by the generation the sequence created. H2/H3 require one `reaping` per
bound child; H5 requires three.
## Order and discipline
H1 → H2 → H3 → H4 → H5, one commit per case (plus its fix if it finds a bug — the
case and the fix land together, the case having failed first). The standing
discrimination run once for H1 and once for H2's shape. Full suite green at the end,
docs touched where behavior was corrected, memory updated. Fixes stay within the
settled design: teardown order (children first), reap-on-removal, identity per port
— anything design-shaped that surfaces stops the loop and asks.
+140
View File
@@ -0,0 +1,140 @@
# Bounds: how a ceiling is declared
*Design, 2026-08-08. Follows [fixed-bounds-audit.md](../fixed-bounds-audit.md), which
found 235 compile-time ceilings in this tree: 139 on quantities we do not choose, 5
recorded anywhere with their reasoning, and 171 that pass in silence when reached.*
A bound is a number chosen at compile time that decides how much of something the code
can hold. `const maximum_devices = 64`. `var below: [64]Range`. `var blob: [512]u8`.
Different units — devices, firmware memory-map entries, bytes of a USB descriptor — but
one shape, and one recurring way of going wrong.
## Where a bound lives
**Where the thing it bounds lives.** A driver's transfer-ring size belongs to that
driver; a protocol's payload cap belongs to that protocol; the kernel's task-table size
belongs to the kernel. There is no central list and this document does not propose one.
`system/parameters.zig` is not a counter-example. It is kernel-only, and it exists for a
specific historical reason: tunables had accumulated inside the loader↔kernel handoff
contract, and splitting them out kept that contract to what it actually is. It is a
tidying of one file's contents, not a registry the rest of the system reports to.
This matters for the mechanism below. An earlier draft had every bound declared through
a shared `bounds` module — which would have meant adding a dependency to roughly eight
package manifests, including `library/protocol`, which deliberately depends on nothing.
That is a coupling the problem does not require: a bound is a local fact about local
storage, and the only thing worth sharing is the *shape of the statement*, not a module.
## The declaration
A structured doc comment, immediately above the declaration, in the file that owns it:
```zig
/// bound: logical CPUs the kernel tracks
/// decided-by: hardware
/// protects: the per-CPU bookkeeping arrays, which are sized at compile time
/// at-limit: degrade — surplus cores are left parked, never brought online
/// observed-by: platform.cpusDropped() -> the WARNING at kernel.zig:281
pub const maximum_cpus = 128;
```
Five fields, all mandatory:
| Field | Answers |
|---|---|
| `bound` | what is counted, in plain words |
| `decided-by` | `hardware`, `external`, or `ours` — who chooses how large it gets |
| `protects` | what this ceiling defends against |
| `at-limit` | `refuse` / `degrade` / `truncate` / `grow`, and the detail |
| `observed-by` | how an operator finds out it was reached |
`decided-by` is the classification the audit turned on. `hardware` means the machine
chooses — PCI functions, CPUs, ACPI rows, memory-map entries. `external` means a file,
disk structure or peer chooses. `ours` means we do: a stack size, a tick rate, our own
protocol's payload. A fixed bound on the first two is a defect rather than a tunable.
## What the build step enforces
A step in `build.zig` reads the tree and fails on:
1. **A bound with no declaration.** A fixed-size array or a `maximum_*`/`max_*` constant
with no `bound:` block above it. The 235 that exist today are allowlisted by
file+line+name, so only newly written ones are gated — the rule can land without a
235-site sweep in front of it.
2. **A missing field.** All five or it fails. This alone is the 97 bounds with no
comment at all and the 171 with no observability.
3. **An unspeakable `at-limit`.** The vocabulary is closed. There is no `silent`, no
`drop`, and nothing meaning *allow*. `truncate` is legal only with a marker the
reader can see — `klog_maximum_message` qualifies because the record carries
`klog_flag_truncated`; the USB configuration descriptor cut at 512 bytes does not,
because nothing records that anything was lost.
4. **A stale allowlist entry.** If a listed bound is fixed or deleted, its entry goes
too, so the list can only shrink.
Because this is text and not a Zig type, it also covers `boot/`, which imports almost
nothing, and `tools/*.py`, where the audit found bounds as well. One mechanism, whole
tree, no new dependency edges.
## Coupled bounds
Two numbers that must agree, agreeing in code rather than in a comment — no module
needed, just a `comptime` block where one of them lives:
```zig
comptime {
if (maximum_domains != devices_broker.maximum_devices)
@compileError("iommu.confined is indexed by device id; an id past its end is " ++
"left unconfined while confineDevice still reports success");
}
```
`maximum_domains = 64` and `maximum_devices = 64` agree today only by a sentence in a
comment, and the agreement fails open. This is the clause with a live hole behind it,
and the reason raising `maximum_devices` alone would be a privilege escalation rather
than a fix.
## The worked bad case
`devices_broker.maximum_devices`, which had no comment at all:
```zig
/// bound: device nodes for the whole machine — firmware-discovered plus registered
/// decided-by: hardware
/// protects: nothing; this is a sizing guess about someone else's computer
/// at-limit: refuse — ENOSPC from device_register, dropped++ during discovery
/// observed-by: kernel.zig:203 counts discovery drops only, NOT runtime refusals
const maximum_devices = 64;
```
Writing it out is the argument. `decided-by: hardware` alongside a `protects` that
admits there is no threat describes a bound that should not be fixed at all, and
`observed-by` cannot be filled in honestly. The build step does not reject this — it
makes it impossible to write down without noticing.
## The work-list this produces
`decided-by` is machine-readable, so the sweep is a query: every `hardware` or
`external` bound whose `at-limit` is not `grow`. That is 139 of the 235, and it is the
order the fixing takes — by class, not by our guesses about which machines get run.
Reachability is exactly what a new computer changes; the Ryzen's cap was unreachable
until it wasn't.
## What this does not do
**It is a statement, not a proof.** Nothing checks that the code does what `at-limit`
claims. The enforcement is completeness and vocabulary: you cannot leave the question
unanswered, and you cannot answer it with "silently".
**It carries no occupancy.** Knowing `system/configuration/protocol.csv` sits at 50 of
64 grant rows still needs a counter and somewhere to report it. The declarations make
that cheap to add later; it is not here.
**It resizes nothing.** Declaring `maximum_devices` honestly does not make the Ryzen
work. It makes the next machine's failure legible, and it names the 139 that need real
fixes.
**Enforcement is at build time, not compile time.** A Zig type could have made a missing
field a compile error. That version needed the shared module, and the module was not
worth the coupling — so a missing field is a failed build step instead. In practice both
mean `zig build` stops; the difference is which stage prints the message.
+34 -1
View File
@@ -55,7 +55,40 @@ source/destination addressing internally at L0 — the way IP runs under TCP —
and none of it surfaces into the packet header. Protocols stay ignorant of
distance.
## The transport (L0): a buffer and a doorbell
## Establishment: two planes, one namespace
`target` routes objects *within* a provider. It cannot route *between* provider
processes, because "who am I talking to" was decided at establishment — so when a
protocol's objects live in several processes, something must resolve establishment
to the right one. A real machine forced the question: three xHCI controllers,
three `usb-xhci-bus` processes, one `usb-transfer` name, and whichever instance
bound first owned every class driver's discovery — a mouse on the second
controller was unreachable (`could not open device 50`). The registry's exclusive
bind was built for parties that are genuinely singular; per-device driver
processes are deliberately *not* singular — one process per device found is what
makes a single driver recompilable and restartable while the machine runs.
So establishment has two planes, and the namespace stays instance-free on both:
- **Applications establish by name.** `/protocol/input`, `/protocol/display`,
`/protocol/ufs` — served by *services*, the layer that aggregates
(driver-model.md: services face applications). These are genuinely singular,
the registry's exclusive bind is correct for them, and multiplicity behind
them is `target`'s job. Ten mice still merge into one `/protocol/input`.
- **Drivers establish by topology.** A driver instance *creates its channel* —
its own endpoint — and hands it up in the `hello` it already sends, as a
capability. The device manager is the establishment router for the device
tree because it already owns the routing fact: it knows which instance
reported which child. A consumer's `hello` for device N returns a capability
to N's provider. The name `usb-transfer` names the *contract*; no process
binds it.
Establishment is always a synchronous call, and always consumer-initiated: the
kernel carries one capability in each direction of a call (request and reply),
and deliberately none on a push — a provider cannot foist a channel on anyone.
Re-establishment after a provider restart is therefore also consumer-initiated:
the consumer's channel dies with the provider, and a fresh `hello` fetches the
successor's.
Strip any transport to its skeleton and the same two parts remain:
+187
View File
@@ -0,0 +1,187 @@
# Device authority: the implementation of delegation
*Implementation design, 2026-08-08. The **what** is settled in
[device-manager.md](../device-driver-development/device-manager.md) — "structure in the
manager, authority in the kernel", and delegation as the step after `hello`. This
document is the **how**, and the decisions that paragraph leaves open.*
Read first: [drivers.md](../device-driver-development/drivers.md) (the claim is the
capability), [driver-model.md](../device-driver-development/driver-model.md) (the three
invariants), [device-manager.md](../device-driver-development/device-manager.md) (the
tree, the matcher, the supervisor).
## The one thing not yet true
`device-manager.md` says assignment "stays argv for now", and names the next step:
> The step after `hello` exists is delegation: the manager claims (or is granted) the
> devices and passes the claim to the driver over IPC (the M13 capability-transfer
> mechanism), replacing first-come-first-served `device_claim` with policy.
Until that lands, the manager's matching is advisory. `device_claim` checks only that
the device exists and is unheld ([devices-broker.zig](../../system/kernel/devices-broker.zig)):
```zig
pub fn claim(id: u64, owner: u32) ClaimError!void {
if (id >= count) return error.NoSuchDevice;
if (claimed[@intCast(id)] != null) return error.AlreadyClaimed;
claimed[@intCast(id)] = owner;
}
```
A driver is spawned with its device id in `argv[1]` and claims it; any process could
pass any integer instead. Since a claim is a licence to map physical memory, that is the
gap this document closes.
## Decision 1: the manager claims, then transfers
`device-manager.md` leaves "claims (or is granted)" open. **Claims.**
The manager runs before any driver exists — `init` starts it from `init.csv`, and it is
what spawns drivers — so it takes the seeded devices unopposed and there is nothing
unheld left for anyone to race for. One new call moves ownership on:
```
device_transfer(device_id, task_id) -> 0/-errno
```
The kernel checks only that the caller currently holds the device. No names, no
attestation, no notion of "the device manager" — the rule is *you may give away what you
hold*, which is the capability discipline already in force.
The alternative was the kernel granting roots to a task it recognises by binary path
plus a PID-1 supervisor. It is more robust — it does not depend on the manager being
first — but it puts a binary name inside the kernel, and the goal is that the kernel
keeps only what cannot safely live in user space. A name is not that.
**The residual, stated plainly:** authority here rests on the manager claiming first.
That holds because `init.csv` decides what starts and in what order, so it is an
operator-visible ordering rather than an attacker-controlled one — but it is an
assumption, not an enforced invariant. The enforced version arrives with the spawn
capability [drivers.md](../device-driver-development/drivers.md) already names as
missing ("`system_spawn` is currently ungated … because there is no spawn capability
yet"). This design is compatible with it and does not block on it.
## Decision 2: the kernel stops holding inventory
The kernel reads exactly three things out of a descriptor: **physical ranges** (to check
a mapping falls inside one), **interrupt numbers**, and **one PCI BDF** (to key an IOMMU
domain). Vendor, device and subsystem ids, class triples, `_HID` strings, bus addresses
and names are stored only so `device_enumerate` can hand them back — which
`device-manager.md` already resolves: that call "fades to a manager-internal (then
deleted) seam", because the manager owns the tree as data.
So the kernel's table becomes: **parent, resources, holder, BDF.** That is what cannot
safely run in user space; the rest moves.
**Devices with no resources leave the kernel entirely.** A USB device is addressed
through its controller and carries `resource_count = 0`
([driver-model.md](../device-driver-development/driver-model.md): "that case is allowed
and is the common one"). It conveys no mapping authority, so there is nothing for the
kernel to enforce and no reason for it to know. It is inventory, and inventory is the
manager's — reported by `child_added`, which already carries everything needed.
That is also the case that made `maximum_children_per_parent` necessary: a zero-resource
child sidesteps containment, so a driver could loop `device_register` and fill the
shared table. Once such children are not kernel objects, every remaining entry is a real
contained subdivision of something the caller holds.
## Decision 3: no shared ceiling; a per-holder quota instead
`maximum_devices = 64` and `maximum_children_per_parent = 16` are numbers we invented,
and both are shared — one driver's enumeration starves every other driver, which is how
an AMD Ryzen booted with no USB and no storage.
- **The table becomes dynamic.** It is built after `heap.init` (`kernel.zig`: `pmm.init`
at 137, `heap.init` at 179, `devices_broker.init` at 202), so nothing prevents it. No
specification bounds how many devices a machine has, so nothing should bound ours.
- **`maximum_children_per_parent` is deleted**, because the authorisation it stood in
for now exists.
- **A per-holder quota replaces them.** Dynamic storage without a bound moves the
ceiling to the kernel heap, which is shared and fatal rather than partial — strictly
worse. The bound that is *not* worse is one charged to the task that caused it: a
driver that loops `device_register` exhausts its own allowance, is refused with an
attributable errno, and is restarted by its supervisor while every other driver
carries on. That is the microkernel property rather than a workaround for it, and it
is declared through [bounds.md](bounds.md) like any other.
## The shape of the change
| | Before | After |
|---|---|---|
| Manager gets its devices | claims them, unauthorised | claims them (first, unopposed) |
| Driver gets its device | `argv[1]` + `device_claim` | receives it in the `hello` reply |
| Kernel checks | is it free? | do you hold it? |
| Kernel stores | the full descriptor | parent, resources, holder, BDF |
| Zero-resource devices | kernel table entries | manager records only |
| Table size | `maximum_devices = 64` | dynamic, per-holder quota |
| Children per parent | `maximum_children_per_parent = 16` | deleted |
Bring-up order changes for the five claiming drivers: `hello` must precede the claim,
because the reply is where the device arrives. `pci-bus` today does the reverse — its
own comment reads "Claim the bridge, map the ECAM, hello the manager, then scan."
## What does not change
- The three invariants of [driver-model.md](../device-driver-development/driver-model.md):
a claim is exclusive, a descriptor is a licence to map physical memory, therefore
containment. This design strengthens the first and touches neither of the others.
- The display service's GOP path. The framebuffer is not a device — it is where pixels
go, handed over by the loader, and the compositor uses it as the boot floor until a
real display driver announces itself
([display-v2.md](../device-driver-development/display-v2.md)). The kernel wraps it in
a display-class descriptor so `mmio_map` can hand it over write-combining; that is
plumbing for a mapping, not a claim about what it is.
- Supervision, restart, pruning and re-report
([device-manager.md](../device-driver-development/device-manager.md),
[process-lifecycle.md](process-lifecycle.md)). Delegation slots into the existing
`hello` exchange and changes none of it.
- `device_register` idempotency, which is what lets a restarted bus rebuild the same
ids.
## How it is verified
The invariant is: **a process holds what it was handed and cannot name its way into
holding more.** The suite has no adversarial device case today — the audit's lesson was
that "the suite contains no attacker" — so this adds one: a process that was handed
nothing calls `device_claim` and `device_transfer` on a device another driver holds, and
on one nobody holds, and is refused each time with its own errno.
The Ryzen is the acceptance test for the ceiling half: it is the machine that found the
constants, and the one that proves them gone.
## As built (2026-08-09)
Three details settled differently, or beyond, what the sections above say:
- **The device arrives with the spawn, not in the `hello` reply.** `system_spawn` grew a
sixth argument: the manager names the device it is giving, the kernel verifies the
caller holds it before the child exists, and the child holds it before its first
instruction. A give that fails after the spawn (the device stopped being the giver's,
or its confinement was refused) kills the child — a driver running without the
hardware it was spawned for is worse than no driver. `hello` stays what it was: the
liveness handshake.
- **A given device is a loan.** When the holder dies, the device returns to the giver if
the giver is still alive — so a respawned driver is handed the same device by its
manager instead of racing anyone for a released claim. Only if the lender is also dead
does the device become unheld.
- **Confinement moves with the device, and is rebuilt when the loan comes back.** A
transfer re-points the existing IOMMU record; but a death tears the domain down
*before* the loan returns, so the next delegation of that device finds no record and
confines afresh — under the same fail-closed rule as a first claim (`ECONFINE`, the
give does not stand). Without that, one driver crash left its device silently
unconfined forever. Both give paths (`device_transfer` and spawn's give) share one
body in [process.zig](../../system/kernel/process.zig) (`giveDeviceLocked`), and the
`iommu` kernel test drives the death-and-respawn sequence against it directly.
A fourth followed on 2026-08-09, when a real three-controller machine broke the last
name-shaped assumption ([communication.md](communication.md) "Establishment: two
planes, one namespace"): **driver-layer channels ride the same hello.** A driver's
serving endpoint goes up as the hello's capability; consumers get their provider's
channel down in the reply, routed by the manager's lineage — the reporter for a
class driver, the bound driver for a `.consumer`. `usb-transfer` and `block`
stopped being registry names, and a reporter's death now reaps its class-driver
subtree so the re-report can rebuild it against the successor — the manager half of
the loan story above. One correction to the earlier bullet: `hello` is no longer
*only* the liveness handshake; it is also where establishment happens. The device
itself still arrives with the spawn.
+33 -15
View File
@@ -28,28 +28,43 @@ unchanged.
## The protocol
The `power-protocol` module ([library/protocol/power/power-protocol.zig](../../library/protocol/power/power-protocol.zig))
follows the vfs-protocol pattern — extern-struct messages, a version, reserved
fields. Three operations:
is defined through the [envelope](protocol-namespace.md), so every packet begins
with the folded `Header`. `Header.target` is unused in both directions: the
provider is the only object either side addresses.
| Direction | Operation | Purpose |
| Direction | Packet | Purpose |
|---|---|---|
| subscriber → service | `subscribe` | receive published events; the subscriber's endpoint rides as the call's **capability** (the input/device-manager pattern) |
| init → service | `shutdown` | orderly shutdown's last step: enter S5 (soft off) |
| service → subscriber | `event` | a published `EventMessage`, delivered as a buffered message (never sent *to* the service) |
| subscriber → service | `subscribe` (reserved verb 2) | receive published events; the subscriber's endpoint rides as the call's **capability** (the input/device-manager pattern) |
| init → service | `shutdown` (verb 16) | orderly shutdown's last step: enter S5 (soft off) |
| service → subscriber | one event per kind | a published `Notice`, `ipc_send`t as a buffered packet (never sent *to* the service) |
`subscribe` is not one of this protocol's own verbs: a synchronous call whose
attached capability is the subscriber's endpoint is exactly what the envelope's
reserved `subscribe` means everywhere, so power adopts it wholesale. And no
packet carries a version — the reserved `describe` verb is the version handshake,
asked once at connect time rather than out of every packet's budget.
Events are published, not polled: like the input service, the service holds
subscriber endpoints as capabilities and `ipc_send`s each event as a buffered
message, so a slow or dead subscriber can never wedge the source. The event
packet, so a slow or dead subscriber can never wedge the source. The table, the
reserved `subscribe`/`unsubscribe` verbs and the fan-out are the **service
harness's** (`service.Subscribers`), shared with input and the device manager, so
the acpi service's own code is the ACPI half only — and a subscriber that dies is
now swept on its exit notification, where before this service had no sweep at
all. **The kind is the packet's operation** — one declared event per named kind, exactly as the
input service delivers one per device class — so a subscriber reads *what
happened* out of the header rather than out of a tag inside the payload. The
vocabulary is hardware-neutral:
- `power_button` — the button was pressed (a fixed ACPI event on x86).
- `lid`, `ac`, `battery` — the named GPE-driven events.
- `notify` — a device notification that maps to none of the above; its `code`
(the ACPI `Notify` argument) and the notifying device's `hid` say which device
and what happened.
- `power_button` (event 16) — the button was pressed (a fixed ACPI event on x86).
- `lid` (17), `ac` (18), `battery` (19) — the named GPE-driven events.
- `notify` (20) — a device notification that maps to none of the above; its
`code` (the ACPI `Notify` argument) and the notifying device's `hid` say which
device and what happened.
An `EventMessage` carries the `event` tag plus `code` and an 8-byte `hid`, so a
generic `notify` is fully described without a second round trip.
The payload every one of them carries is a `Notice`: `code` plus an 8-byte `hid`,
so a generic `notify` is fully described without a second round trip, and the
four named kinds leave both fields zero because the verb already said it all.
**`shutdown` is authority, not information.** It is the only operation that
*does* something irreversible, so it is gated: the contract is that only init
@@ -58,7 +73,10 @@ sequence over everything else. The acpi service implements this as a **soft
gate** — it honors `shutdown` only from a process that is a *subscriber*, and
init is the one subscriber. That stands in for "only the system supervisor may
power off" without hard-coding a pid, so it still holds under tests where PID 1
is not init.
is not init. The question is asked of the harness's table now
(`Subscribers.has(sender)`), which is why the harness exposes it: the gate is
unchanged, including the badge being the whole of it — the badge is
kernel-stamped, so nothing inside a packet can claim to be init.
## Orderly shutdown
+13 -3
View File
@@ -188,9 +188,15 @@ zombie state or privileged snooping:
state by all along is the id the exit event carries.
Subscription, not broadcast-to-everyone: only processes that asked receive
events, the kernel keeps a bounded subscriber table, and delivery is the same
non-blocking coalescing notification as everything else — a dying process never
waits on its mourners. Subscribing is ungated, like `process_enumerate`: what is
events, the kernel keeps a bounded subscriber table (sixteen — a normal boot
already fields six, since this is what *every* provider with per-client state
releases on), and delivery is the same non-blocking coalescing notification as
everything else — a dying process never waits on its mourners.
A service does not usually write the sweep itself: the shared service harness
subscribes for it and drops a dead task's event subscriptions
(`service.Subscribers`), and a provider adds its own handler only for state the
harness knows nothing about — open files, layers, device tokens.
Subscribing is ungated, like `process_enumerate`: what is
running (and dying) is not a secret between cooperating processes. Subscribers
do not receive the exit reason — the filesystem server does not care *why*
the client died.
@@ -285,6 +291,10 @@ callbacks (`on_terminate`, `on_reload`) for programs that want defaults.
`service` owns the `replyWait` loop and folds every event source — signals,
child exits, protocol messages — into callbacks, with the vocabulary's defaults:
it also owns the **subscriber side** of any protocol that declares events
(`service.Subscribers`: the table, the reserved `subscribe`/`unsubscribe` verbs,
the fan-out, and the sweep on a subscriber's published exit), so every event
stream in the system behaves identically.
`terminate` returns from the loop (clean exit), the common `ping` is answered automatically,
`reload` is ignored unless overridden. One loop, no locking, nothing reentrant. A
service author writes domain logic; the lifecycle contract is satisfied by the
+7 -1
View File
@@ -1,6 +1,7 @@
# SMEP and SMAP — supervisor-mode hardening
*Design, 2026-07-31. Not yet implemented. Companion to
*Design, 2026-07-31. H1 (the copy layer), H2 (SMEP), HS (the SYSRET guard) and
H3 (SMAP) have all landed; the track is complete. Companion to
[protocol-namespace.md](protocol-namespace.md) on the security track — this is
the hardware half; that is the namespace half.*
@@ -136,6 +137,11 @@ Broadwell+ for SMAP; AMD Zen+ for both). The test images should run with
hardening bucket, independent fix (validate RCX before `sysretq`, fall
back to `iretq`), should ride the same branch as H2/H3 but is not
SMEP/SMAP.
**Status — landed 2026-08-01 (HS).** The syscall exit sign-extends the
return RIP from bit 47 (danos is 4-level only; nothing sets CR4.LA57) and
falls back to `iretq` when that changes it, counting each refusal for the
`sysret-canonical` case. Ring 3 could reach it: `syscall` as the last two
bytes of the last canonical page returns to `user_half_end`.
- **KPTI / Meltdown-class leaks are out of scope.** SMEP/SMAP police
architectural accesses, not speculative ones. danos runs one kernel
mapping in every address space and accepts that on affected hardware;
+51
View File
@@ -150,6 +150,57 @@ they are wire values a Rust program needs verbatim. What stays private in
`abi.zig` is exactly the thing the vDSO exists to hide: the `SystemCall`
numbers and the trap convention.
## Errors: the errno space
A failed call returns `-errno`. The runtime detects failure the way Linux
does — a return value in the top 4096 — so every code stays inside 1..4095.
These are **public**: unlike the call numbers, a caller must be able to read
them verbatim, and they are the same vocabulary whether the number came from
the kernel or from a user-space provider answering over IPC.
They are defined once in `system/abi.zig`. The kernel restates them in
`system/kernel/ipc-synchronous.zig` and the envelope restates the
provider-facing subset in `library/protocol/envelope/envelope.zig` (the
`protocol` package deliberately depends on nothing, so it cannot import
`abi`); a comptime check in `library/device/driver/driver.zig` makes drift a
compile error.
| # | Name | Meaning |
|---|------|---------|
| 1 | `EBADF` | bad handle |
| 2 | `E2BIG` | an argument exceeds its maximum (a message, a descriptor's resource count) |
| 3 | `EFAULT` | buffer unmapped, or outside the user half |
| 4 | `ENOENT` | no such name |
| 5 | `ENOSPC` | a kernel table is full (handles, devices) |
| 6 | `ENOMEM` | out of memory |
| 7 | `EPEER` | the peer died before replying — its process exited or was killed |
| 8 | `ESRCH` | no such process |
| 9 | `EPERM` | not permitted: the caller is not the owner or supervisor |
| 10 | `ENOSYS` | this protocol has no such operation |
| 11 | `EPROTO` | malformed packet: shorter than the verb it names |
| 12 | `EBUSY` | the thing asked for is held by someone still alive |
| 13 | `ENODEV` | no such device id |
| 14 | `ECHILDREN` | this parent already holds as many children as it can |
| 15 | `ERANGE` | a resource escapes the window it must fall inside |
| 16 | `ECONFINE` | the device could not be placed under IOMMU translation |
`EPEER` is the one with no POSIX counterpart and it is worth stating plainly:
synchronous IPC blocks the caller until the server replies, so the caller
needs an answer for "the server died while I was waiting." It is not a
transport error and not a refusal — the request may well have been carried
out — it says only that no reply is coming. A client that treats it as
"retry" can duplicate work; the honest response is to re-resolve the protocol
name, because the provider it held is gone.
**A refusal names the rule that refused it.** This is a rule and not a
courtesy. `device_register` alone can fail six ways, and until each got its
own code a bus driver could only report "refused" — which is how an AMD
desktop came to boot with a working display, no USB and no storage, with
three independent causes indistinguishable in the log. See
[fixed-bounds-audit.md](../fixed-bounds-audit.md). A new failure mode that
does not fit an existing code gets a new one here rather than borrowing the
nearest.
## Enforcement, and an honest threat model
Renumbering only has teeth if the kernel **refuses syscalls that don't come
+117 -14
View File
@@ -36,11 +36,11 @@ plain `main` checkout always tells the truth about where the work is.**
| | |
|---|---|
| Working on | **P4a** — protocol rebase onto `envelope.Define` (next) |
| Branch carrying it | `feat/security-group-2` (pushed to origin) |
| On `main` | Phase 0, PM, H1, P1, P2, P3 (group 2 merged) |
| Awaiting merge | nothing — group 2 is on `main` |
| Suite | 109 cases, all passing |
| Working on | nothing — the track is complete |
| Branch carrying it | — |
| On `main` | every phase — groups 1, 2, 3 and 4 merged |
| Awaiting merge | nothing |
| Suite | 114 cases, all passing |
| Last updated | 2026-08-01 |
A checkbox below means the phase met its definition of green and was
@@ -65,14 +65,57 @@ group boundary.
supervising task per contract and is deliberately **open-only**, leaving P2's
bind attestation and every refusal it makes untouched (suite 109/109)
- [x] **merge** group 2 → main, push
- [ ] **P4a** — clean protocols rebased onto `Define` (vfs, block, display, scanout, input)
- [ ] **P4b** — misfit protocols rebased (device-manager, power, usb-transfer)
- [ ] **P4c** — harness subscriber lift + badge-scoped per-client integers
- [ ] **merge** group 3 → main, push
- [ ] **H2** — SMEP on every core
- [ ] **HS** — SYSRET canonical-RIP guard
- [ ] **H3** — SMAP + boot-patched `clac`; `-cpu max` in the harness; negative tests
- [ ] **merge** group 4 → main, push
- [x] **P4a** — clean protocols rebased onto `Define` (vfs, block, display, scanout, input; display's one overloaded request split per-operation and its field abuse ended, scanout's bogus 64-byte maximum deleted, directory EOF re-spelled as a nameless entry, input moved onto the service harness; new `protocol-conformance` case asks every reachable provider for `describe` and requires `-ENOSYS` for an undefined verb; suite 110/110)
- [x] **P4b** — misfit protocols rebased (device-manager, power, usb-transfer; every leading operation byte folded into the header, and with it the `device_id`/`device_token` that followed it — `Header.target` now carries the device in all three. device-manager's own `enumerate`/`subscribe` became the reserved verbs and its three `{status, reserved}` reply structs the envelope's `Status`; `ChildAdded` is one struct under two numbers, a call and an event, landing exactly on the 64-byte push floor. power's kinds became one declared event each, the input protocol's shape, so init reads *what happened* from the header; usb-transfer's control data stage moved to the packet tail in both directions, which made `Status.len` the transferred length and `actual_length` redundant. The two silent-breakage sites — init's byte-offset power parse and acpi's `message[0]` dispatch — are gone, the shutdown badge gate unchanged; three more rows in the conformance table. Suite 110/110)
- [x] **P4c** — harness subscriber lift + badge-scoped per-client integers (the
subscriber table, the reserved subscribe/unsubscribe verbs, the fan-out and the
dead-subscriber sweep are `service.Subscribers` now; input, acpi and
device-manager deleted three hand-rolled variants and their three different
ideas of when a subscriber goes away, standardizing on published exit
notifications — acpi had no sweep at all and input polled the process list on
every subscribe. The three guessable-id namespaces are scoped to the opening
badge: FAT node ids on every verb that names one, xHCI device tokens on open,
control, bulk and interrupt_subscribe, display layers on configure, fill, blit,
damage and destroy — each refusing a wrong owner with the *same* answer as an id
nobody holds. New `badge-scope` case, two processes of one fixture, every
refusal paired with a control; suite 111/111)
- [x] **merge** group 3 → main, push
- [x] **H2** — SMEP on every core (shared CPUID helper; CR4 bit 20 set in the per-CPU bring-up both the BSP and every AP run, asserted per core by the smp case; ring-0-executes-user-pages audit clean incl. the pre-paging window on the loader's tables; fail-open with a posture line; `-cpu max` added to the harness since QEMU's default model has neither bit; new `fault-smep` case; suite 112/112)
- [x] **HS** — SYSRET canonical-RIP guard (the syscall exit sign-extends the
return RIP from bit 47 and returns through `iretq` when that changes it —
four register ALU ops and a never-taken branch on the hot path, no load; the
fallback un-pops the rip slot so `iretq` consumes the frame entry already
built, reloads R11 from the rflags slot, and keeps the `swapgs` in the same
place relative to the ring change. 4-level is not an assumption but a fact:
nothing sets CR4.LA57, and the comment says what a 5-level port must change.
Ring 3 **can** reach the hazard — `syscall` as the last two bytes of the last
canonical page returns to `user_half_end` — so the new `sysret-canonical`
case is a real ring-3 probe doing exactly that, and dies of a ring-3 #GP at
`0x0000800000000000` while the kernel runs on. Its teeth are the refusal
counter, not the outcome: measured with the guard's branch removed, TCG does
not model Intel's ring-0 #GP and every outcome check still passed. Suite
113/113)
- [x] **H3** — SMAP on every core, and the boot-patched `clac` that makes it
hold. Hardware does not clear `EFLAGS.AC` on interrupt delivery and ring 3
sets it with `popfq`, so without the patch a hostile process suspends SMAP
for the length of any handler it can provoke; `clac` is #UD without the
feature, so the image ships the 3-byte canonical NOP at the first byte of
`isr_common` — ahead of the CPL test, because a fault nested in ring 0
inherits AC just as readily — and the boot processor overwrites it through
the physmap, the same door `smp.arm` and `process.run` already use to write
a page the executing mapping holds read-only. The two halves are wired
together rather than merely ordered: `initHardening` refuses CR4 bit 21
until the patch has been written *and* read back through the text address it
will be fetched from, so no core can turn SMAP on ahead of it and a
translation that lied leaves the machine unhardened and saying so instead of
enforcing over an entry path that cannot clear AC. The `smp` case now
requires SMAP on every core it lands on, which is the ordering checked from
the far end. New `fault-smap` case reads a mapped user page from ring 0 and
requires the fault: error code `0x1` — present, and nothing else, since a
SMAP violation has no bit of its own and U/S reports the ring of the access.
The suite is now the standing enforcement test, and it found nothing left to
find: H1's conversion of the nine stragglers was complete. Suite 114/114
- [x] **merge** group 4 → main, push
---
@@ -413,6 +456,32 @@ re-layouts and raw-offset readers):
USB storage/HID all exercise these wires); the conformance case now covers
three more providers. Suite 110.
*Landed. Three judgment calls the plan left open, recorded because a reader of
the wire formats will want them:*
- *`ChildAdded` is 48 bytes, not the 44 the "60 B" estimate assumed: three `u64`s
give the struct eight-byte alignment, so 41 bytes of content round up whatever
order the fields sit in. The packet is therefore **exactly** 64 — on the push
floor, not under it — which `Define` accepts and the module pins in a test. The
fields are ordered small-tail-last deliberately, so the slack the rounding pays
for is where the small ones live.*
- *power's events are declared **per kind** (`power_button`, `lid`, `ac`,
`battery`, `notify`), not one `event` with the kind in the payload. That is the
shape P4a gave input — "the class is the header's operation, so a subscriber
reads the kind from the packet rather than from a tag inside the payload" — and
it is what makes `Header.operation` carry information here at all. It also kept
every call site's spelling: `Protocol.Event` is re-exported as the protocol's
own `Event`, with the members it always had.*
- *the conformance case still checks two providers, and the three new rows report
as unbound. All three P4b contracts arrive with the device manager — it is the
first, it spawns the discovery service that binds the second, and the xHCI
driver that binds the third — so booting one means booting the driver tree, and
the fixture takes **one snapshot** of `/protocol`: a scenario whose bound set
depends on how far that tree got would make the case's own summary line a boot
race. The rows still earn their place — a future scenario that binds one gets it
checked with no edit here, and `/test/*` already holds the `open` grant for
`device-manager`.*
## P4c — harness subscriber lift + badge scoping
- `library/kernel/service.zig` grows the subscriber table, exit-
@@ -430,6 +499,33 @@ three more providers. Suite 110.
node id and asserts refusal; kernel-side unit test for the harness sweep.
Suite 111.
*Landed. Four things the plan had not foreseen:*
- *One sweep idiom means one more kernel subscriber per provider, and the kernel's
published-exit table held **eight**. A normal boot now fields six (fat, input,
power, device-manager, display, and one per xHCI controller), so the table grew
to sixteen. It is not a table anyone notices until a service silently loses its
sweep, which is exactly the failure the old ceiling was two subscriptions away
from.*
- *The device manager hears each of its drivers die **twice** now — it is both the
supervisor its spawn named and, through the harness, a subscriber to published
exits — and the notify ring delivers the two badges separately. Untreated, one
death counted as two: the restart backoff doubled and the crash-loop cap fired
at half the deaths it names. `onDriverExit` therefore retires the dead process
id before it decides anything, and the second notification finds nothing to act
on. (The `driver-restart` and `pci-scan` drills are what would have caught it.)*
- *Refusal-equals-absence has a corollary for the verbs that **release**: FAT's
`close` used to answer 0 for an unknown node, so scoping it had to change that
too — a foreign node and a free one both answer `-ENOENT`, or the pair would
have been an oracle for which ids are live. The same applies to the harness's
`unsubscribe`.*
- *Ownership is per **task**, not per process, because the badge is: the kernel
stamps the sending thread's id, which is already the granularity of the exit
sweep that releases the state (a worker thread's death releases the handles that
worker opened). Nothing in the tree shares an id across its own threads today;
a per-process notion would need the kernel to stamp the leader, and belongs with
P5's spawner-wired namespaces if it is ever wanted.*
## H2 — SMEP
- Generalize the cpuid helper (`apic.zig:351-365`, private, subleaf-0) to
@@ -454,6 +550,8 @@ put the text in `expect`, per `qemu_test.py:189`). Suite 112.
**Test:** kernel unit case driving a thread whose return RIP is forged
non-canonical via the syscall path if constructible cheaply; otherwise the
review-level proof plus the existing fault cases regression. Suite 112.
*(Landed: it was constructible, and from ring 3 rather than by forgery — the
`sysret-canonical` case, suite 113.)*
## H3 — SMAP
@@ -468,7 +566,12 @@ review-level proof plus the existing fault cases regression. Suite 112.
**Test:** new QEMU case `fault-smap`: ring-0 deliberate read of a mapped
user page; expect vector 14 + `error code : 0x1` + kernel IP. And the
whole suite becomes the tripwire — any missed straggler now fails loudly.
Suite 113.
*(Landed: the patch site sits at the very first byte of `isr_common`, and
CR4.SMAP is refused on every core until the patch has been read back through
the text mapping it will execute from — so the ordering is enforced, not
merely documented. Error code observed: `0x1` exactly, present and nothing
else. The tripwire found no missed straggler: H1 had converted them all.)*
Suite 114 (HS added one).
---
+6
View File
@@ -17,10 +17,15 @@ pub fn build(b: *std.Build) void {
// (docs/os-development/protocol-namespace.md).
const channel = kernel.module("channel");
// A client frames its own packets, so it needs the envelope alongside the
// protocol whose verbs it speaks.
const envelope = protocol.module("envelope");
_ = b.addModule("display-client", .{
.root_source_file = b.path("display/display-client.zig"),
.imports = &.{
.{ .name = "channel", .module = channel },
.{ .name = "envelope", .module = envelope },
.{ .name = "ipc", .module = ipc },
.{ .name = "time", .module = time },
.{ .name = "display-protocol", .module = protocol.module("display-protocol") },
@@ -30,6 +35,7 @@ pub fn build(b: *std.Build) void {
.root_source_file = b.path("input/input-client.zig"),
.imports = &.{
.{ .name = "channel", .module = channel },
.{ .name = "envelope", .module = envelope },
.{ .name = "ipc", .module = ipc },
.{ .name = "time", .module = time },
.{ .name = "input-protocol", .module = protocol.module("input-protocol") },
+52 -86
View File
@@ -5,10 +5,13 @@
const std = @import("std");
const channel = @import("channel");
const envelope = @import("envelope");
const ipc = @import("ipc");
const time = @import("time");
const display_protocol = @import("display-protocol");
const Protocol = display_protocol.Protocol;
/// The display's current mode, as `info()` reports it.
pub const Info = struct {
width: u32,
@@ -35,29 +38,45 @@ fn service() ?ipc.Handle {
return null;
}
/// Send one request, receive its reply; true on a zero status. `out` receives the reply
/// so callers can read `info`/`layer` fields on success.
fn transact(request: display_protocol.Request, out: *display_protocol.Reply) bool {
const h = service() orelse return false;
var req = request;
var reply: [display_protocol.reply_size]u8 = undefined;
const len = ipc.call(h, std.mem.asBytes(&req), &reply) catch return false;
if (len < display_protocol.reply_size) return false;
out.* = std.mem.bytesToValue(display_protocol.Reply, reply[0..display_protocol.reply_size]);
return out.status == 0;
/// A reply the compositor answered with, kept whole so the caller can decode the
/// verb's own fixed part out of it.
const Answered = struct {
packet: [display_protocol.message_maximum]u8,
len: usize,
fn bytes(self: *const Answered) []const u8 {
return self.packet[0..self.len];
}
};
/// Send one request (`target` addresses a layer, or 0 for the compositor itself)
/// and keep the reply. Null when the transport failed or the compositor refused.
fn transact(
comptime operation: Protocol.Operation,
target: u64,
request: Protocol.RequestOf(operation),
tail: []const u8,
) ?Answered {
const h = service() orelse return null;
var packet: [display_protocol.message_maximum]u8 = undefined;
const framed = Protocol.encodeRequest(operation, target, request, tail, &packet) orelse return null;
var answered: Answered = .{ .packet = undefined, .len = 0 };
answered.len = ipc.call(h, framed, &answered.packet) catch return null;
const status = envelope.statusOf(answered.bytes()) orelse return null;
if (status.status != 0) return null;
return answered;
}
/// The display's current mode, or null if the service never came up.
pub fn info() ?Info {
var reply: display_protocol.Reply = undefined;
if (!transact(.{ .operation = @intFromEnum(display_protocol.Operation.info) }, &reply)) return null;
const answered = transact(.info, 0, {}, &.{}) orelse return null;
const reply = Protocol.decodeReply(.info, answered.bytes()) orelse return null;
return .{ .width = reply.width, .height = reply.height, .pitch = reply.pitch, .format = reply.format };
}
/// Composite the dirty layers and flush the frame to the screen.
pub fn present() bool {
var reply: display_protocol.Reply = undefined;
return transact(.{ .operation = @intFromEnum(display_protocol.Operation.present) }, &reply);
return transact(.present, 0, {}, &.{}) != null;
}
/// One selectable display mode.
@@ -66,23 +85,17 @@ pub const Mode = display_protocol.Mode;
/// Fill `out` with the resolutions the display can switch to; returns how many were written
/// (zero on the GOP floor, or if the service never came up).
pub fn modes(out: []Mode) usize {
const h = service() orelse return 0;
var request = display_protocol.Request{ .operation = @intFromEnum(display_protocol.Operation.get_modes) };
var reply: [display_protocol.modes_reply_size]u8 = undefined;
const len = ipc.call(h, std.mem.asBytes(&request), &reply) catch return 0;
if (len < display_protocol.modes_reply_size) return 0;
const answer = std.mem.bytesToValue(display_protocol.ModesReply, reply[0..display_protocol.modes_reply_size]);
if (answer.status != 0) return 0;
const count = @min(@min(answer.count, display_protocol.max_modes), out.len);
for (0..count) |i| out[i] = answer.modes[i];
const answered = transact(.get_modes, 0, {}, &.{}) orelse return 0;
const offered = Protocol.decodeReply(.get_modes, answered.bytes()) orelse return 0;
const count = @min(@min(offered.count, display_protocol.max_modes), out.len);
for (0..count) |i| out[i] = offered.modes[i];
return count;
}
/// Change the display resolution. Only a native backend that supports mode-setting honours it
/// (on the GOP floor it returns false); on success the display's `info()` reports the new mode.
pub fn setMode(width: u32, height: u32) bool {
var reply: display_protocol.Reply = undefined;
const changed = transact(.{ .operation = @intFromEnum(display_protocol.Operation.set_mode), .width = width, .height = height }, &reply);
const changed = transact(.set_mode, 0, .{ .width = width, .height = height }, &.{}) != null;
if (changed) mode = null; // the cached mode is stale now
return changed;
}
@@ -107,93 +120,46 @@ pub fn color(r: u8, g: u8, b: u8) u32 {
/// A handle to a server-owned layer: a positioned, z-ordered surface the client draws
/// into by command. Create with `createLayer`; drawing and moves take effect on the next
/// `present`. Coordinates are signed (a layer may sit partly off-screen).
///
/// The id is the packet header's `target` on every call below, so it is named once
/// per request rather than repeated inside one.
pub const Layer = struct {
id: u32,
/// Fill a rectangle of this layer (layer-local coordinates) with a native `colour`.
pub fn fill(self: Layer, x: i32, y: i32, w: u32, h: u32, colour: u32) bool {
var reply: display_protocol.Reply = undefined;
return transact(.{
.operation = @intFromEnum(display_protocol.Operation.fill_rect),
.layer = self.id,
.x = @bitCast(x),
.y = @bitCast(y),
.width = w,
.height = h,
.colour = colour,
}, &reply);
return transact(.fill_rect, self.id, .{ .x = x, .y = y, .width = w, .height = h, .colour = colour }, &.{}) != null;
}
/// Copy a `w`×`h` tile of native pixels (row-major, little-endian bytes) into this
/// layer at (`x`, `y`). The tile rides inline in the request, so `w*h*4` must fit
/// `display_protocol.maximum_payload`.
/// layer at (`x`, `y`). The tile rides inline as the request's tail, so `w*h*4` must
/// fit `display_protocol.maximum_payload` — the bound the protocol derives from this
/// verb's own fixed part, so the check here can never drift from what fits.
pub fn blitTile(self: Layer, x: i32, y: i32, w: u32, h: u32, pixels: []const u8) bool {
var request = display_protocol.Request{
.operation = @intFromEnum(display_protocol.Operation.blit_tile),
.layer = self.id,
.x = @bitCast(x),
.y = @bitCast(y),
.width = w,
.height = h,
};
const header = std.mem.asBytes(&request);
if (header.len + pixels.len > display_protocol.message_maximum) return false;
var buffer: [display_protocol.message_maximum]u8 = undefined;
@memcpy(buffer[0..header.len], header);
@memcpy(buffer[header.len..][0..pixels.len], pixels);
const h_svc = service() orelse return false;
var reply: [display_protocol.reply_size]u8 = undefined;
const len = ipc.call(h_svc, buffer[0 .. header.len + pixels.len], &reply) catch return false;
if (len < display_protocol.reply_size) return false;
return std.mem.bytesToValue(display_protocol.Reply, reply[0..display_protocol.reply_size]).status == 0;
if (pixels.len > display_protocol.maximum_payload) return false;
return transact(.blit_tile, self.id, .{ .x = x, .y = y, .width = w, .height = h }, pixels) != null;
}
/// Move / restack / show or hide the layer.
pub fn configure(self: Layer, x: i32, y: i32, z: u32, visible: bool) bool {
var reply: display_protocol.Reply = undefined;
return transact(.{
.operation = @intFromEnum(display_protocol.Operation.configure_layer),
.layer = self.id,
.x = @bitCast(x),
.y = @bitCast(y),
.z = z,
.visible = if (visible) 1 else 0,
}, &reply);
return transact(.configure_layer, self.id, .{ .x = x, .y = y, .z = z, .visible = if (visible) 1 else 0 }, &.{}) != null;
}
/// Mark a rectangle of this layer (layer-local) dirty for the next present — for when
/// the layer's pixels changed without a drawing call the compositor already tracked.
pub fn damage(self: Layer, x: i32, y: i32, w: u32, h: u32) bool {
var reply: display_protocol.Reply = undefined;
return transact(.{
.operation = @intFromEnum(display_protocol.Operation.damage),
.layer = self.id,
.x = @bitCast(x),
.y = @bitCast(y),
.width = w,
.height = h,
}, &reply);
return transact(.damage, self.id, .{ .x = x, .y = y, .width = w, .height = h }, &.{}) != null;
}
/// Release the layer and its surface.
pub fn destroy(self: Layer) bool {
var reply: display_protocol.Reply = undefined;
return transact(.{ .operation = @intFromEnum(display_protocol.Operation.destroy_layer), .layer = self.id }, &reply);
return transact(.destroy_layer, self.id, {}, &.{}) != null;
}
};
/// Create a server-owned layer of `w`×`h` pixels at screen (`x`, `y`) with stacking order
/// `z` (higher is nearer the front), initially visible. Returns a handle, or null.
pub fn createLayer(x: i32, y: i32, w: u32, h: u32, z: u32) ?Layer {
var reply: display_protocol.Reply = undefined;
if (!transact(.{
.operation = @intFromEnum(display_protocol.Operation.create_layer),
.x = @bitCast(x),
.y = @bitCast(y),
.width = w,
.height = h,
.z = z,
.visible = 1,
}, &reply)) return null;
return .{ .id = reply.layer };
const answered = transact(.create_layer, 0, .{ .x = x, .y = y, .width = w, .height = h, .z = z, .visible = 1 }, &.{}) orelse return null;
return .{ .id = (Protocol.decodeReply(.create_layer, answered.bytes()) orelse return null).layer };
}
+31 -15
View File
@@ -21,12 +21,14 @@
//! if (event.asKeyboard()) |k| { ... } else if (event.asMouse()) |m| { ... }
//! }
const std = @import("std");
const channel = @import("channel");
const envelope = @import("envelope");
const ipc = @import("ipc");
const time = @import("time");
const input_protocol = @import("input-protocol");
const Protocol = input_protocol.Protocol;
pub const DeviceKind = input_protocol.DeviceKind;
pub const InputEvent = input_protocol.InputEvent;
pub const KeyEvent = input_protocol.KeyEvent;
@@ -66,31 +68,44 @@ pub const Subscriber = struct {
/// The endpoint the service delivers events to (created and owned by us; its handle
/// was handed to the service as a capability at subscribe time).
endpoint: ipc.Handle,
receive: [input_protocol.event_size]u8 = undefined,
/// A pushed packet is the folded header plus one typed event, so the buffer is
/// the push floor rather than any one event's size.
receive: [envelope.post_maximum]u8 = undefined,
/// Block until the next event is pushed, and return it. Events arrive as asynchronous
/// buffered messages (`ipc_send` from the service), so nothing is owed in reply — the
/// empty reply this issues is a harmless no-op. Returns null for any non-event wake-up
/// (there should be none), so callers can loop.
///
/// The device class is the packet's operation, so it is read from the header and
/// re-tagged into an `InputEvent` here — one decoded type for a caller that took
/// several classes on one stream.
pub fn next(self: *Subscriber) ?InputEvent {
const got = ipc.replyWait(self.endpoint, &.{}, &self.receive, null);
if (!got.isMessage() or got.len < input_protocol.event_size) return null;
return std.mem.bytesToValue(InputEvent, self.receive[0..input_protocol.event_size]);
if (!got.isMessage()) return null;
const packet = self.receive[0..@min(got.len, self.receive.len)];
return switch (Protocol.eventOf(packet) orelse return null) {
.keyboard => InputEvent.fromKeyboard(Protocol.decodeEvent(.keyboard, packet) orelse return null),
.mouse => InputEvent.fromMouse(Protocol.decodeEvent(.mouse, packet) orelse return null),
.joystick => InputEvent.fromJoystick(Protocol.decodeEvent(.joystick, packet) orelse return null),
};
}
};
/// Subscribe to the input classes named in `device_mask` (an OR of `device_*`, or
/// `device_all`). Creates an endpoint for the service to push to and hands it over as a
/// capability. Returns a `Subscriber` to loop `next` on, or null on failure.
/// capability — the envelope's reserved `subscribe`, whose shape this is exactly. Returns
/// a `Subscriber` to loop `next` on, or null on failure.
pub fn subscribe(device_mask: u32) ?Subscriber {
const service = lookupService() orelse return null;
const endpoint = ipc.createIpcEndpoint() orelse return null;
var request = input_protocol.Request{ .operation = @intFromEnum(input_protocol.Operation.subscribe), .device_mask = device_mask };
var reply: [input_protocol.reply_size]u8 = undefined;
const result = ipc.callCap(service, std.mem.asBytes(&request), &reply, endpoint) catch return null;
if (result.len < input_protocol.reply_size) return null;
if (std.mem.bytesToValue(input_protocol.Reply, reply[0..input_protocol.reply_size]).status != 0) return null;
var packet: [input_protocol.message_maximum]u8 = undefined;
const framed = input_protocol.encodeSubscribe(device_mask, &packet) orelse return null;
var reply: [input_protocol.message_maximum]u8 = undefined;
const result = ipc.callCap(service, framed, &reply, endpoint) catch return null;
const status = envelope.statusOf(reply[0..result.len]) orelse return null;
if (status.status != 0) return null;
return .{ .endpoint = endpoint };
}
@@ -149,11 +164,12 @@ pub const Publisher = struct {
service: ipc.Handle,
fn publish(self: Publisher, event: InputEvent) bool {
var request = input_protocol.Request{ .operation = @intFromEnum(input_protocol.Operation.publish), .event = event };
var reply: [input_protocol.reply_size]u8 = undefined;
const len = ipc.call(self.service, std.mem.asBytes(&request), &reply) catch return false;
if (len < input_protocol.reply_size) return false;
return std.mem.bytesToValue(input_protocol.Reply, reply[0..input_protocol.reply_size]).status == 0;
var packet: [input_protocol.message_maximum]u8 = undefined;
const framed = Protocol.encodeRequest(.publish, 0, event, &.{}, &packet) orelse return false;
var reply: [input_protocol.message_maximum]u8 = undefined;
const len = ipc.call(self.service, framed, &reply) catch return false;
const status = envelope.statusOf(reply[0..len]) orelse return false;
return status.status == 0;
}
/// Broadcast a keyboard event to every subscriber that took keyboard events.
+33 -46
View File
@@ -7,12 +7,12 @@
//! `runtime.dma.alloc`), so whole sectors move without crossing the IPC size
//! limit — the same handoff usb-storage uses toward the controller.
const std = @import("std");
const channel = @import("channel");
const envelope = @import("envelope");
const ipc = @import("ipc");
const time = @import("time");
const block_protocol = @import("block-protocol");
const Protocol = block_protocol.Protocol;
pub const Geometry = struct { block_size: u32, block_count: u64 };
pub const Device = struct {
@@ -20,12 +20,9 @@ pub const Device = struct {
/// The device's block size and total block count.
pub fn geometry(self: Device) ?Geometry {
var request = block_protocol.Request{ .operation = @intFromEnum(block_protocol.Operation.geometry), .lba = 0, .count = 0, .physical = 0 };
var reply: [block_protocol.reply_size]u8 = undefined;
const n = ipc.call(self.endpoint, std.mem.asBytes(&request), &reply) catch return null;
if (n < block_protocol.reply_size) return null;
const result = std.mem.bytesToValue(block_protocol.Reply, reply[0..block_protocol.reply_size]);
if (result.status != 0) return null;
var reply: [block_protocol.message_maximum]u8 = undefined;
const answered = self.call(.geometry, {}, null, &reply) orelse return null;
const result = Protocol.decodeReply(.geometry, answered) orelse return null;
return .{ .block_size = result.block_size, .block_count = result.block_count };
}
@@ -34,59 +31,49 @@ pub const Device = struct {
/// addresses become reachable by the device. Call once per buffer before naming it
/// in `read`/`write`. Harmless success when no IOMMU is enforcing.
pub fn attach(self: Device, handle: ipc.Handle) bool {
var request = block_protocol.Request{ .operation = @intFromEnum(block_protocol.Operation.attach), .lba = 0, .count = 0, .physical = 0 };
var reply: [block_protocol.reply_size]u8 = undefined;
const result = ipc.callCap(self.endpoint, std.mem.asBytes(&request), &reply, handle) catch return false;
if (result.len < block_protocol.reply_size) return false;
return std.mem.bytesToValue(block_protocol.Reply, reply[0..block_protocol.reply_size]).status == 0;
var reply: [block_protocol.message_maximum]u8 = undefined;
return self.call(.attach, {}, handle, &reply) != null;
}
/// Read `count` blocks starting at `lba` into the DMA buffer at `physical`.
pub fn read(self: Device, lba: u64, count: u32, physical: u64) bool {
return self.transfer(.read, lba, count, physical);
var reply: [block_protocol.message_maximum]u8 = undefined;
return self.call(.read, .{ .lba = lba, .count = count, .physical = physical }, null, &reply) != null;
}
/// Write `count` blocks starting at `lba` from the DMA buffer at `physical`.
pub fn write(self: Device, lba: u64, count: u32, physical: u64) bool {
return self.transfer(.write, lba, count, physical);
var reply: [block_protocol.message_maximum]u8 = undefined;
return self.call(.write, .{ .lba = lba, .count = count, .physical = physical }, null, &reply) != null;
}
/// Commit any device write cache to stable media (SCSI SYNCHRONIZE CACHE), so
/// prior writes survive a power-off. A filesystem calls this before the machine
/// goes down; no data transfer, so the buffer arguments are unused.
pub fn flush(self: Device) bool {
return self.transfer(.flush, 0, 0, 0);
var reply: [block_protocol.message_maximum]u8 = undefined;
return self.call(.flush, {}, null, &reply) != null;
}
fn transfer(self: Device, operation: block_protocol.Operation, lba: u64, count: u32, physical: u64) bool {
var request = block_protocol.Request{ .operation = @intFromEnum(operation), .lba = lba, .count = count, .physical = physical };
var reply: [block_protocol.reply_size]u8 = undefined;
const n = ipc.call(self.endpoint, std.mem.asBytes(&request), &reply) catch return false;
if (n < block_protocol.reply_size) return false;
return std.mem.bytesToValue(block_protocol.Reply, reply[0..block_protocol.reply_size]).status == 0;
/// One request at the driver. `target` is always 0: one endpoint per device, so
/// there is no object within the peer to address.
fn call(
self: Device,
comptime operation: Protocol.Operation,
request: Protocol.RequestOf(operation),
capability: ?ipc.Handle,
reply: []u8,
) ?[]u8 {
var packet: [block_protocol.message_maximum]u8 = undefined;
const framed = Protocol.encodeRequest(operation, 0, request, &.{}, &packet) orelse return null;
const answer = ipc.callCap(self.endpoint, framed, reply, capability) catch return null;
const status = envelope.statusOf(reply[0..answer.len]) orelse return null;
if (status.status != 0) return null;
return reply[0..answer.len];
}
};
/// One open attempt, no waiting — for a server that retries on its own
/// timer (the fat service) instead of blocking its harness in here.
pub fn tryOpen() ?Device {
if (channel.openEndpoint("block")) |handle| return .{ .endpoint = handle };
return null;
}
/// Open `/protocol/block`, retrying generously while the USB storage chain
/// (controller reset, enumeration, mass-storage bring-up) comes up.
pub fn open() ?Device {
// Patient: the whole USB storage chain (firmware discovery, xHCI reset and
// enumeration, mass-storage bring-up) must complete first, which can take
// tens of seconds under emulation.
var attempts: usize = 0;
// 30 s covers the slowest observed healthy chain (a flaky QEMU enumeration
// completed at ~24 s); a machine whose stick genuinely failed setup should
// not sit a further minute pretending otherwise.
while (attempts < 600) : (attempts += 1) {
if (channel.openEndpoint("block")) |handle| return .{ .endpoint = handle };
time.sleepMillis(50);
}
return null;
}
// There is deliberately no open-by-name here: `block` is not a registry name.
// One storage process serves each volume, and a consumer receives its volume's
// channel from the device manager (establishment by lineage, communication.md
// "Establishment: two planes"), then wraps it: `block.Device{ .endpoint = c }`.
+3
View File
@@ -61,6 +61,7 @@ pub fn build(b: *std.Build) void {
.{ .name = "abi", .module = abi },
.{ .name = "channel", .module = channel },
.{ .name = "device-abi", .module = device_abi },
.{ .name = "envelope", .module = protocol.module("envelope") },
.{ .name = "system-call", .module = system_call },
.{ .name = "ipc", .module = ipc },
.{ .name = "time", .module = time },
@@ -87,6 +88,7 @@ pub fn build(b: *std.Build) void {
.root_source_file = b.path("usb/usb.zig"),
.imports = &.{
.{ .name = "channel", .module = channel },
.{ .name = "envelope", .module = protocol.module("envelope") },
.{ .name = "ipc", .module = ipc },
.{ .name = "time", .module = time },
.{ .name = "usb-transfer-protocol", .module = protocol.module("usb-transfer-protocol") },
@@ -99,6 +101,7 @@ pub fn build(b: *std.Build) void {
.root_source_file = b.path("block/block.zig"),
.imports = &.{
.{ .name = "channel", .module = channel },
.{ .name = "envelope", .module = protocol.module("envelope") },
.{ .name = "ipc", .module = ipc },
.{ .name = "time", .module = time },
.{ .name = "block-protocol", .module = protocol.module("block-protocol") },
+160 -12
View File
@@ -8,6 +8,7 @@ const abi = @import("abi");
const device_abi = @import("device-abi");
const sc = @import("system-call");
const channel = @import("channel");
const envelope = @import("envelope");
const ipc = @import("ipc");
const time = @import("time");
const device_manager_protocol = @import("device-manager-protocol");
@@ -21,14 +22,67 @@ inline fn failed(r: usize) bool {
return r > ~@as(usize, 0) - 4095;
}
/// The errno inside a failed return. Only meaningful when `failed(r)`.
inline fn errnoOf(r: usize) i64 {
return -@as(i64, @bitCast(r));
}
// The envelope restates the kernel's errno numbering by hand, because the
// `protocol` package deliberately depends on nothing (so it cannot import `abi`).
// This module is one of the few that can see both halves, so it is where they are
// held together: drift becomes a compile error here rather than a driver reporting
// the wrong reason for a refusal. Anything linking a driver compiles this.
comptime {
if (envelope.ENOENT != abi.ENOENT) @compileError("envelope.ENOENT has drifted from abi.ENOENT");
if (envelope.ENOSPC != abi.ENOSPC) @compileError("envelope.ENOSPC has drifted from abi.ENOSPC");
if (envelope.EPERM != abi.EPERM) @compileError("envelope.EPERM has drifted from abi.EPERM");
if (envelope.ENOSYS != abi.ENOSYS) @compileError("envelope.ENOSYS has drifted from abi.ENOSYS");
if (envelope.EPROTO != abi.EPROTO) @compileError("envelope.EPROTO has drifted from abi.EPROTO");
if (envelope.EBUSY != abi.EBUSY) @compileError("envelope.EBUSY has drifted from abi.EBUSY");
}
/// Copy up to `buffer.len` device descriptors into `buffer`; returns the total count.
pub fn enumerate(buffer: []DeviceDescriptor) usize {
return sc.systemCall2(.device_enumerate, @intFromPtr(buffer.ptr), buffer.len);
}
/// Take exclusive ownership of device `id`. Returns false if taken or invalid.
pub fn claim(id: u64) bool {
return !failed(sc.systemCall1(.device_claim, id));
/// Why a `transfer` failed. `NotHeld` is the interesting one — it means the caller tried
/// to give away a device it does not have, which is the whole rule.
pub const TransferError = error{ NoSuchDevice, NotHeld, NoSuchTask, Refused };
/// Give device `id` to task `to`. **A move, not a copy** — a claim is exclusive, so the
/// caller stops holding it. This is how the device manager hands a driver the device it
/// matched, replacing first-come-first-served claiming with policy
/// (docs/os-development/device-authority.md).
pub fn transfer(id: u64, to: u32) TransferError!void {
const r = sc.systemCall2(.device_transfer, id, to);
if (!failed(r)) return;
return switch (errnoOf(r)) {
abi.ENODEV => error.NoSuchDevice,
abi.EPERM => error.NotHeld,
abi.ESRCH => error.NoSuchTask,
else => error.Refused,
};
}
/// Why a `claim` failed. Worth distinguishing: `AlreadyClaimed` means back off and
/// let the owner have it, `NoSuchDevice` means this id is stale and the caller should
/// re-enumerate, and `NotConfined` means the machine could not place the device under
/// IOMMU translation — the claim was rolled back, and that one is a fault report, not
/// a retry. `Refused` is an errno this library does not know a name for.
pub const ClaimError = error{ NoSuchDevice, AlreadyClaimed, NotConfined, NotYours, Refused };
/// Take exclusive ownership of device `id`.
pub fn claim(id: u64) ClaimError!void {
const r = sc.systemCall1(.device_claim, id);
if (!failed(r)) return;
return switch (errnoOf(r)) {
abi.ENODEV => error.NoSuchDevice,
abi.EBUSY => error.AlreadyClaimed,
abi.ECONFINE => error.NotConfined,
abi.EPERM => error.NotYours, // delegated hardware: it must be handed to you
else => error.Refused,
};
}
/// Map resource `resource_index` (which must be an MMIO window) of claimed device
@@ -55,11 +109,38 @@ pub const no_pci_class = device_abi.no_pci_class;
/// a bus driver may only subdivide what it already owns. `descriptor.id` and `descriptor.parent`
/// are ignored. A device with no resources at all is fine — a USB device is reached
/// through its controller, not by MMIO.
pub fn register(parent_id: u64, descriptor: *const DeviceDescriptor) ?u64 {
pub fn register(parent_id: u64, descriptor: *const DeviceDescriptor) RegisterError!u64 {
const r = sc.systemCall2(.device_register, parent_id, @intFromPtr(descriptor));
return if (failed(r)) null else r;
if (!failed(r)) return r;
return switch (errnoOf(r)) {
abi.ENOSPC => error.TableFull,
abi.ENODEV => error.NoSuchParent,
abi.EPERM => error.NotYourParent,
abi.E2BIG => error.TooManyResources,
abi.ECHILDREN => error.ParentFull,
abi.ERANGE => error.NotContained,
abi.EFAULT => error.BadDescriptor,
else => error.Refused,
};
}
/// Why a `register` failed. These are not interchangeable and a bus driver should
/// say which one it hit: `ParentFull` and `TableFull` are different ceilings with
/// different fixes, and `NotContained` is not a ceiling at all — it means the child
/// resource escaped the window the parent actually owns. Reporting all of them as
/// one refusal is what made an AMD desktop boot with no USB and no storage, and gave
/// no way to tell which of three causes it was (docs/fixed-bounds-audit.md).
pub const RegisterError = error{
TableFull, // the kernel's device table is full, machine-wide
ParentFull, // this parent already holds as many children as it can
NoSuchParent, // no device with that id
NotYourParent, // that device exists but this process has not claimed it
TooManyResources, // the descriptor declares more resources than one device may hold
NotContained, // a resource escapes the parent's window
BadDescriptor, // the descriptor pointer did not read back
Refused, // an errno this library does not know a name for
};
/// Bind resource `resource_index` (which must be an IRQ) of claimed device `device_id` to
/// `endpoint`. From then on the interrupt arrives as an asynchronous notification:
/// `ipc.replyWait` on that endpoint returns with the high bit set in `badge` and the
@@ -168,7 +249,55 @@ const lookup_pause_ms: u64 = 20;
/// (best-effort standalone bring-up) or it refused the handshake. Bus drivers keep the handle
/// to report children through; a driver that runs fine unsupervised discards it with `_ =`,
/// and one that requires supervision bails on null. Logs the outcome itself.
///
/// The device this driver was assigned is the packet's `Header.target` — the manager's
/// object addressing, so `no_device` here is a driver that serves none.
pub fn hello(role: Role, device_id: u64) ?ipc.Handle {
const exchanged = helloExchange(role, device_id, null, false) orelse return null;
return exchanged.manager;
}
/// What one hello moved, besides the handshake itself: the manager's endpoint
/// (every hello), and — when asked — the channel to the driver that provides
/// this device, shared into our handle table by the reply.
pub const Exchange = struct {
manager: ipc.Handle,
/// The provider's channel, when `want_channel` asked and the manager's
/// lineage had one. Null with `want_channel` set means the provider is not
/// there YET (its own hello has not landed, or it is mid-restart) — a
/// retryable condition, never a verdict.
channel: ?ipc.Handle,
};
/// A consumer's whole establishment step: hello until the channel to this
/// device's provider arrives. `serving` (a provider-and-consumer like
/// usb-storage: block endpoint up, bus channel down) rides the FIRST exchange
/// only — the manager keeps it, so retries need not resend it. The manager
/// acks a hello whose provider is not there yet (mid-restart, re-report on
/// the way) with no channel — retryable by design — so this re-hellos on the
/// ONE manager handle, on the same cadence the old name lookup used, and
/// gives up on a refusal or a vanished manager. Re-hello is benign: the
/// manager just re-marks the entry running.
pub fn helloForChannel(role: Role, device_id: u64, serving: ?ipc.Handle) ?ipc.Handle {
const first = helloExchange(role, device_id, serving, true) orelse return null;
if (first.channel) |bus| return bus;
var attempts: u32 = 0;
while (attempts < lookup_attempts) : (attempts += 1) {
time.sleepMillis(lookup_pause_ms);
const again = helloOn(first.manager, role, device_id, null, true) orelse return null;
if (again.channel) |bus| return bus;
}
std.log.info("no provider channel for device {d}", .{device_id});
return null;
}
/// The full handshake (communication.md "Establishment: two planes, one
/// namespace"): a provider hands `serving` — the endpoint its consumers will
/// be routed to — up with the request; a consumer sets `want_channel` and
/// receives its device's provider channel with the reply. One call can do
/// both (usb-storage serves block and consumes usb-transfer). The kernel
/// shares capabilities as refcounted copies, so `serving` stays ours too.
pub fn helloExchange(role: Role, device_id: u64, serving: ?ipc.Handle, want_channel: bool) ?Exchange {
var attempts: u32 = 0;
const manager = while (attempts < lookup_attempts) : (attempts += 1) {
if (channel.openEndpoint("device-manager")) |handle| break handle;
@@ -177,19 +306,38 @@ pub fn hello(role: Role, device_id: u64) ?ipc.Handle {
std.log.info("no device manager to hello", .{});
return null;
};
return helloOn(manager, role, device_id, serving, want_channel);
}
const message = device_manager_protocol.Hello{ .role = @intFromEnum(role), .device_id = device_id };
var reply: [device_manager_protocol.reply_size]u8 = undefined;
const length = ipc.call(manager, std.mem.asBytes(&message), &reply) catch {
/// One hello on an already-open manager handle — the exchange without the
/// lookup, so a retry loop never spends a handle-table slot per attempt.
/// Public for parties that keep their own manager handle across a long retry
/// cadence (fat polls for its volume on a timer).
pub fn helloOn(manager: ipc.Handle, role: Role, device_id: u64, serving: ?ipc.Handle, want_channel: bool) ?Exchange {
var packet: [device_manager_protocol.message_maximum]u8 = undefined;
const framed = device_manager_protocol.Protocol.encodeRequest(
.hello,
device_id,
.{ .role = @intFromEnum(role), .wants_channel = @intFromBool(want_channel) },
&.{},
&packet,
) orelse return null;
var reply: [device_manager_protocol.message_maximum]u8 = undefined;
const answered = ipc.callCap(manager, framed, &reply, serving) catch {
std.log.info("hello call failed", .{});
return null;
};
if (length < device_manager_protocol.reply_size or
std.mem.bytesToValue(device_manager_protocol.HelloReply, reply[0..device_manager_protocol.reply_size]).status != 0)
{
const status = envelope.statusOf(reply[0..answered.len]) orelse {
if (answered.cap) |stray| _ = ipc.close(stray); // never keep what we cannot read
std.log.info("hello answered nothing readable", .{});
return null;
};
if (status.status != 0) {
if (answered.cap) |stray| _ = ipc.close(stray);
std.log.info("hello refused", .{});
return null;
}
std.log.info("hello acknowledged", .{});
return manager;
return .{ .manager = manager, .channel = answered.cap };
}
+85 -56
View File
@@ -5,22 +5,32 @@
//! service and `device.zig` over the raw device calls.
//!
//! A class driver, spawned with its interface's assigned device id as argv[1]:
//! if (device_manager.hello(.device, id) == null) return; // meet the spawn deadline
//! var device = usb.open(id) orelse return; // open + get its endpoints
//! const bus = device_manager.helloForChannel(.device, id) orelse return;
//! var device = usb.open(bus, id) orelse return; // open + get its endpoints
//! _ = device.controlOut(usb_abi.setProtocol(...));// class requests, descriptors
//! _ = device.subscribeInterrupt(address, length); // reports arrive asynchronously
//! while (true) { ... ipc.replyWait(device.endpoint, ...) ... } // its own loop
//!
//! Reports are delivered to `device.endpoint` as asynchronous `InterruptReport`
//! messages (the class driver runs a bare `replyWait` loop to read them, because
//! the service harness drops buffered-message payloads — see service.zig).
//! The bus channel arrives from the device manager's hello — routed to THIS
//! device's controller by lineage — never from a registry name; several bus
//! processes provide this contract on a multi-controller machine.
//!
//! Reports are delivered to `device.endpoint` as asynchronous `interrupt_report`
//! event packets, decoded with `reportOf` (the class driver runs a bare `replyWait`
//! loop to read them, because the service harness drops buffered-message payloads
//! — see service.zig).
//!
//! Every packet this file lays down is an envelope packet: the verb and the
//! device token in the folded `Header`, the transfer's own fields after it, and
//! a control transfer's data stage in the tail.
const std = @import("std");
const channel = @import("channel");
const envelope = @import("envelope");
const ipc = @import("ipc");
const time = @import("time");
const usb_transfer_protocol = @import("usb-transfer-protocol");
const Protocol = usb_transfer_protocol.Protocol;
/// The USB chapter-9 wire ABI and the class taxonomy, re-exported so a class driver reaches
/// the whole USB domain through its one `usb` import (`usb.abi.getDescriptor`, `usb.ids.Class`).
pub const abi = @import("usb-abi");
@@ -57,21 +67,41 @@ pub const Device = struct {
return null;
}
/// One request at the bus driver, addressing this device by its token — the
/// packet's `Header.target`, so no request body ever names the device again.
/// Null covers both a failed transport and a refusal: a class driver has the
/// same recourse either way.
fn call(
self: *Device,
comptime operation: Protocol.Operation,
request: Protocol.RequestOf(operation),
tail: []const u8,
capability: ?ipc.Handle,
reply: []u8,
) ?[]u8 {
var packet: [usb_transfer_protocol.message_maximum]u8 = undefined;
const framed = Protocol.encodeRequest(operation, self.token, request, tail, &packet) orelse return null;
const answer = ipc.callCap(self.bus, framed, reply, capability) catch return null;
const status = envelope.statusOf(reply[0..answer.len]) orelse return null;
if (status.status != 0) return null;
return reply[0..answer.len];
}
/// The data stage rides the tail in both directions, so the answer's length
/// *is* the transferred length — `Status.len`, which the envelope stamps.
fn controlTransfer(self: *Device, setup: [8]u8, direction_in: bool, data: []u8) ?usize {
var request = usb_transfer_protocol.ControlRequest{
.device_token = self.token,
if (data.len > usb_transfer_protocol.max_inline_data) return null;
const outgoing: []const u8 = if (direction_in) &.{} else data;
var reply: [usb_transfer_protocol.message_maximum]u8 = undefined;
const answered = self.call(.control, .{
.setup = setup,
.direction_in = @intFromBool(direction_in),
.data_length = @intCast(data.len),
};
if (!direction_in and data.len > 0) @memcpy(request.data[0..data.len], data);
var reply: [@sizeOf(usb_transfer_protocol.ControlReply)]u8 = undefined;
const length = ipc.call(self.bus, std.mem.asBytes(&request), &reply) catch return null;
if (length < @sizeOf(usb_transfer_protocol.ControlReply)) return null;
const control_reply = std.mem.bytesToValue(usb_transfer_protocol.ControlReply, reply[0..@sizeOf(usb_transfer_protocol.ControlReply)]);
if (control_reply.status != 0) return null;
const actual = @min(control_reply.actual_length, data.len);
if (direction_in and actual > 0) @memcpy(data[0..actual], control_reply.data[0..actual]);
}, outgoing, null, &reply) orelse return null;
const returned = Protocol.replyTail(.control, answered);
const actual = @min(returned.len, data.len);
if (direction_in and actual > 0) @memcpy(data[0..actual], returned[0..actual]);
return actual;
}
@@ -89,15 +119,11 @@ pub const Device = struct {
/// Begin periodic IN polling of an interrupt endpoint; reports flow back to
/// `self.endpoint` as asynchronous `InterruptReport` messages.
pub fn subscribeInterrupt(self: *Device, endpoint_address: u8, max_length: u16) bool {
var request = usb_transfer_protocol.InterruptSubscribeRequest{
.device_token = self.token,
var reply: [usb_transfer_protocol.message_maximum]u8 = undefined;
return self.call(.interrupt_subscribe, .{
.endpoint_address = endpoint_address,
.max_length = max_length,
};
var reply: [@sizeOf(usb_transfer_protocol.InterruptSubscribeReply)]u8 = undefined;
const length = ipc.call(self.bus, std.mem.asBytes(&request), &reply) catch return false;
if (length < @sizeOf(usb_transfer_protocol.InterruptSubscribeReply)) return false;
return std.mem.bytesToValue(usb_transfer_protocol.InterruptSubscribeReply, reply[0..@sizeOf(usb_transfer_protocol.InterruptSubscribeReply)]).status == 0;
}, &.{}, null, &reply) != null;
}
/// Hand the controller a DMA-region capability (`handle` — from a `shareable`
@@ -106,50 +132,53 @@ pub const Device = struct {
/// will name in a `bulk` transfer, before the transfer. Harmless (and a no-op
/// success) when no IOMMU is enforcing. Returns false on failure.
pub fn attachDma(self: *Device, handle: ipc.Handle) bool {
var request = usb_transfer_protocol.DmaAttachRequest{ .device_token = self.token };
var reply: [@sizeOf(usb_transfer_protocol.DmaAttachReply)]u8 = undefined;
const result = ipc.callCap(self.bus, std.mem.asBytes(&request), &reply, handle) catch return false;
if (result.len < @sizeOf(usb_transfer_protocol.DmaAttachReply)) return false;
return std.mem.bytesToValue(usb_transfer_protocol.DmaAttachReply, reply[0..@sizeOf(usb_transfer_protocol.DmaAttachReply)]).status == 0;
var reply: [usb_transfer_protocol.message_maximum]u8 = undefined;
return self.call(.dma_attach, {}, &.{}, handle, &reply) != null;
}
/// One bulk transfer (IN or OUT per `endpoint_address`'s direction bit) to or
/// from the caller's own DMA buffer at `physical`. Returns the bytes moved.
pub fn bulk(self: *Device, endpoint_address: u8, physical: u64, length: u32) ?u32 {
var request = usb_transfer_protocol.BulkRequest{
.device_token = self.token,
var reply: [usb_transfer_protocol.message_maximum]u8 = undefined;
const answered = self.call(.bulk, .{
.physical_address = physical,
.length = length,
.endpoint_address = endpoint_address,
};
var reply: [@sizeOf(usb_transfer_protocol.BulkReply)]u8 = undefined;
const replied = ipc.call(self.bus, std.mem.asBytes(&request), &reply) catch return null;
if (replied < @sizeOf(usb_transfer_protocol.BulkReply)) return null;
const bulk_reply = std.mem.bytesToValue(usb_transfer_protocol.BulkReply, reply[0..@sizeOf(usb_transfer_protocol.BulkReply)]);
if (bulk_reply.status != 0) return null;
return bulk_reply.actual_length;
}, &.{}, null, &reply) orelse return null;
return (Protocol.decodeReply(.bulk, answered) orelse return null).actual_length;
}
};
/// Open `/protocol/usb-transfer` and, on that channel, open the device with the
/// assigned id, handing over a freshly created endpoint for asynchronous interrupt
/// reports. Retries while the bus is still coming up (a class driver races the bus
/// driver at boot). Two opens, deliberately: the first names the contract, the
/// second names an object within it.
pub fn open(device_id: u64) ?Device {
var attempts: usize = 0;
const bus = while (attempts < 100) : (attempts += 1) {
if (channel.openEndpoint("usb-transfer")) |handle| break handle;
time.sleepMillis(20);
} else return null;
/// Decode one asynchronous interrupt report out of a packet that arrived on the
/// class driver's own endpoint. Null when it is not one — a stray message, or a
/// packet too short to carry the report it names. The device it came from is the
/// packet's `Header.target`, which a single-device class driver never has to read.
pub fn reportOf(packet: []const u8) ?InterruptReport {
const event = Protocol.eventOf(packet) orelse return null;
if (event != .interrupt_report) return null;
return Protocol.decodeEvent(.interrupt_report, packet);
}
/// On `bus` — the channel to this device's own controller, handed to the class
/// driver by the device manager's hello (establishment by lineage,
/// communication.md "Establishment: two planes") — open the device with the
/// assigned id, handing over a freshly created endpoint for asynchronous
/// interrupt reports. The channel is never found by name: one machine carries
/// several controllers, several processes provide this contract, and only the
/// manager knows which one reported this device.
pub fn open(bus: ipc.Handle, device_id: u64) ?Device {
const endpoint = ipc.createIpcEndpoint() orelse return null;
var request = usb_transfer_protocol.OpenRequest{ .device_id = device_id };
var reply: [@sizeOf(usb_transfer_protocol.OpenReply)]u8 = undefined;
const result = ipc.callCap(bus, std.mem.asBytes(&request), &reply, endpoint) catch return null;
if (result.len < @sizeOf(usb_transfer_protocol.OpenReply)) return null;
const open_reply = std.mem.bytesToValue(usb_transfer_protocol.OpenReply, reply[0..@sizeOf(usb_transfer_protocol.OpenReply)]);
if (open_reply.status != 0) return null;
// The assigned device id is the target: it is what the caller has before a
// token exists, and the token the reply hands back addresses every packet
// after this one.
var packet: [usb_transfer_protocol.message_maximum]u8 = undefined;
const framed = Protocol.encodeRequest(.open, device_id, {}, &.{}, &packet) orelse return null;
var reply: [usb_transfer_protocol.message_maximum]u8 = undefined;
const result = ipc.callCap(bus, framed, &reply, endpoint) catch return null;
const answered = reply[0..result.len];
const status = envelope.statusOf(answered) orelse return null;
if (status.status != 0) return null;
const open_reply = Protocol.decodeReply(.open, answered) orelse return null;
var device = Device{
.bus = bus,
+5 -1
View File
@@ -59,6 +59,7 @@ pub fn build(b: *std.Build) void {
.{ .name = "system-call", .module = system_call },
.{ .name = "ipc", .module = ipc },
.{ .name = "vfs-protocol", .module = protocol.module("vfs-protocol") },
.{ .name = "envelope", .module = protocol.module("envelope") },
},
});
// The channel is the L1 concept made concrete (docs/os-development/communication.md):
@@ -86,11 +87,14 @@ pub fn build(b: *std.Build) void {
});
// The harness binds the service's contract name at startup, which is a
// conversation with the registry — hence channel (and time, for the patience
// a provider that beat init to the mount needs).
// a provider that beat init to the mount needs). It also owns the subscriber
// table and the fan-out, which are expressed in the envelope's vocabulary
// (the reserved subscribe verb, the push floor) — hence envelope.
_ = b.addModule("service", .{
.root_source_file = b.path("service.zig"),
.imports = &.{
.{ .name = "channel", .module = channel },
.{ .name = "envelope", .module = protocol.module("envelope") },
.{ .name = "ipc", .module = ipc },
.{ .name = "process", .module = process },
},
+22 -26
View File
@@ -192,41 +192,37 @@ fn reach(path: []const u8) ?Registry {
}
}
/// One vfs-protocol round trip at a backend: fixed header, inline payload, and
/// an optional capability in each direction.
/// One vfs-protocol round trip at a backend: the folded header, the verb's own
/// fixed part, the name as the packet's tail, and an optional capability in each
/// direction. Both verbs this file sends address the backend itself (target 0) —
/// the name in the tail is what they are about.
fn transact(
comptime operation: vfs_protocol.Operation,
handle: ipc.Handle,
operation: vfs_protocol.Operation,
payload: []const u8,
request: vfs_protocol.Protocol.RequestOf(operation),
name: []const u8,
send_capability: ?ipc.Handle,
) ?struct { reply: vfs_protocol.Reply, capability: ?ipc.Handle } {
var request: [vfs_protocol.message_maximum]u8 = undefined;
if (vfs_protocol.request_size + payload.len > request.len) return null;
const header = vfs_protocol.Request{
.operation = operation,
.node = 0,
.offset = 0,
.len = @intCast(payload.len),
.flags = 0,
};
@memcpy(request[0..vfs_protocol.request_size], std.mem.asBytes(&header));
@memcpy(request[vfs_protocol.request_size..][0..payload.len], payload);
) ?struct { status: envelope.Status, capability: ?ipc.Handle } {
var packet: [vfs_protocol.message_maximum]u8 = undefined;
const framed = vfs_protocol.Protocol.encodeRequest(operation, 0, request, name, &packet) orelse return null;
var reply: [vfs_protocol.message_maximum]u8 = undefined;
const answer = ipc.callCap(handle, request[0 .. vfs_protocol.request_size + payload.len], &reply, send_capability) catch return null;
if (answer.len < vfs_protocol.reply_size) return null;
return .{
.reply = std.mem.bytesToValue(vfs_protocol.Reply, reply[0..vfs_protocol.reply_size]),
.capability = answer.cap,
};
const answer = ipc.callCap(handle, framed, &reply, send_capability) catch return null;
const status = envelope.statusOf(reply[0..answer.len]) orelse return null;
return .{ .status = status, .capability = answer.cap };
}
/// Resolve an absolute `/protocol/...` path and take the provider's endpoint out
/// of the open reply's capability.
fn openPath(path: []const u8) ?ipc.Handle {
const registry = reach(path) orelse return null;
const answered = transact(registry.handle, .open, registry.path(), null) orelse return null;
if (answered.reply.status != 0) return null;
const answered = transact(.open, registry.handle, .{ .flags = 0 }, registry.path(), null) orelse return null;
if (answered.status.status != 0) {
// A refusal carries no channel; anything that arrived anyway would be a
// handle-table slot spent for nothing.
if (answered.capability) |handle| _ = ipc.close(handle);
return null;
}
// The capability *is* the channel — an open that succeeds without one was
// answered by a file backend, which does not speak protocols.
return answered.capability;
@@ -257,8 +253,8 @@ pub fn openEndpoint(name: []const u8) ?ipc.Handle {
/// `-EBUSY` a live provider already holds it.
pub fn bind(name: []const u8, endpoint: ipc.Handle) ?i32 {
const registry = reach(root) orelse return null;
const answered = transact(registry.handle, .bind, name, endpoint) orelse return null;
return answered.reply.status;
const answered = transact(.bind, registry.handle, {}, name, endpoint) orelse return null;
return answered.status.status;
}
/// How long a provider keeps offering itself before giving up. The registry is
+54 -53
View File
@@ -14,8 +14,13 @@ const std = @import("std");
const abi = @import("abi");
const sc = @import("system-call");
const ipc = @import("ipc");
const envelope = @import("envelope");
const vfs_protocol = @import("vfs-protocol");
/// The generated vfs contract: encode/decode for every verb, with the node id
/// carried in the packet header's `target`.
const Protocol = vfs_protocol.Protocol;
/// The kind of a filesystem node — re-exported so a caller need not import the
/// wire protocol.
pub const Kind = vfs_protocol.NodeKind;
@@ -89,23 +94,24 @@ fn resolve(path: []const u8, flags: usize) ?Route {
}
}
const Result = struct { reply: vfs_protocol.Reply, payload: []u8 };
// One request/reply round trip: [Request header][send payload] -> backend ->
// [Reply header][receive payload]. The receive payload lands in `out`.
fn transact(h: ipc.Handle, request: vfs_protocol.Request, send: []const u8, out: []u8) ?Result {
var message: [vfs_protocol.message_maximum]u8 = undefined;
@memcpy(message[0..vfs_protocol.request_size], std.mem.asBytes(&request));
const slen = @min(send.len, vfs_protocol.maximum_payload);
@memcpy(message[vfs_protocol.request_size..][0..slen], send[0..slen]);
var rbuf: [vfs_protocol.message_maximum]u8 = undefined;
const n = ipc.call(h, message[0 .. vfs_protocol.request_size + slen], &rbuf) catch return null;
if (n < vfs_protocol.reply_size) return null;
const reply = std.mem.bytesToValue(vfs_protocol.Reply, rbuf[0..vfs_protocol.reply_size]);
const rpl = @min(n - vfs_protocol.reply_size, out.len);
@memcpy(out[0..rpl], rbuf[vfs_protocol.reply_size..][0..rpl]);
return .{ .reply = reply, .payload = out[0..rpl] };
// One request/reply round trip: frame `[Header][request][tail]`, send it, and
// hand back the whole reply packet for the caller to decode with the generated
// helpers. A backend that refused (a negative status) reads as null, which is
// what every caller here did with it anyway.
fn transact(
comptime operation: Protocol.Operation,
handle: ipc.Handle,
target: u64,
request: Protocol.RequestOf(operation),
tail: []const u8,
reply: []u8,
) ?[]u8 {
var packet: [vfs_protocol.message_maximum]u8 = undefined;
const framed = Protocol.encodeRequest(operation, target, request, tail, &packet) orelse return null;
const n = ipc.call(handle, framed, reply) catch return null;
const status = envelope.statusOf(reply[0..n]) orelse return null;
if (status.status != 0) return null;
return reply[0..n];
}
/// An open file: a VFS node plus a byte cursor. Read and write advance the cursor.
@@ -125,11 +131,13 @@ pub const File = struct {
return n;
};
const want: u32 = @intCast(@min(buffer.len, vfs_protocol.maximum_payload));
const request = vfs_protocol.Request{ .operation = .read, .node = self.node, .offset = self.offset, .len = want, .flags = 0 };
const r = transact(h, request, &.{}, buffer) orelse return null;
if (r.reply.status != 0) return null;
self.offset += r.reply.len;
return r.reply.len;
var reply: [vfs_protocol.message_maximum]u8 = undefined;
const answered = transact(.read, h, self.node, .{ .offset = self.offset, .len = want }, &.{}, &reply) orelse return null;
const bytes = Protocol.replyTail(.read, answered);
const n = @min(bytes.len, buffer.len);
@memcpy(buffer[0..n], bytes[0..n]);
self.offset += n;
return n;
}
/// Write `data` at the current offset; returns the count written. A single
@@ -139,11 +147,11 @@ pub const File = struct {
pub fn write(self: *File, data: []const u8) ?usize {
const h = self.backend orelse return null;
const want: u32 = @intCast(@min(data.len, vfs_protocol.maximum_payload));
const request = vfs_protocol.Request{ .operation = .write, .node = self.node, .offset = self.offset, .len = want, .flags = 0 };
const r = transact(h, request, data[0..want], &.{}) orelse return null;
if (r.reply.status != 0) return null;
self.offset += r.reply.len;
return r.reply.len;
var reply: [vfs_protocol.message_maximum]u8 = undefined;
const answered = transact(.write, h, self.node, .{ .offset = self.offset, .len = want }, data[0..want], &reply) orelse return null;
const written = Protocol.decodeReply(.write, answered) orelse return null;
self.offset += written.count;
return written.count;
}
/// Write all of `data`, looping past the per-call payload cap. Returns the
@@ -169,11 +177,9 @@ pub const File = struct {
const a = fsNodeStatus(self.node) orelse return null;
return .{ .size = a.size, .kind = if (a.kind == file_kind_directory) .directory else .regular, .mtime = a.mtime };
};
const request = vfs_protocol.Request{ .operation = .status, .node = self.node, .offset = 0, .len = 0, .flags = 0 };
var buffer: [@sizeOf(vfs_protocol.FileStatus)]u8 = undefined;
const r = transact(h, request, &.{}, &buffer) orelse return null;
if (r.reply.status != 0 or r.payload.len < @sizeOf(vfs_protocol.FileStatus)) return null;
const status = std.mem.bytesToValue(vfs_protocol.FileStatus, buffer[0..@sizeOf(vfs_protocol.FileStatus)]);
var reply: [vfs_protocol.message_maximum]u8 = undefined;
const answered = transact(.status, h, self.node, {}, &.{}, &reply) orelse return null;
const status = Protocol.decodeReply(.status, answered) orelse return null;
return .{ .size = status.size, .kind = kindFromWire(status.kind), .mtime = status.mtime };
}
@@ -181,8 +187,8 @@ pub const File = struct {
/// tokens are permanent — nothing to release.
pub fn close(self: *File) void {
const h = self.backend orelse return;
const request = vfs_protocol.Request{ .operation = .close, .node = self.node, .offset = 0, .len = 0, .flags = 0 };
_ = transact(h, request, &.{}, &.{});
var reply: [vfs_protocol.message_maximum]u8 = undefined;
_ = transact(.close, h, self.node, {}, &.{}, &reply);
}
};
@@ -193,10 +199,10 @@ pub fn open(path: []const u8, options: OpenOptions) ?File {
.kernel => |token| return .{ .node = token, .backend = null },
.backend => |b| {
const relative = route.backendPath();
const request = vfs_protocol.Request{ .operation = .open, .node = 0, .offset = 0, .len = @intCast(relative.len), .flags = options.wireFlags() };
const r = transact(b.handle, request, relative, &.{}) orelse return null;
if (r.reply.status != 0) return null;
return .{ .node = r.reply.node, .backend = b.handle };
var reply: [vfs_protocol.message_maximum]u8 = undefined;
const answered = transact(.open, b.handle, 0, .{ .flags = options.wireFlags() }, relative, &reply) orelse return null;
const opened = Protocol.decodeReply(.open, answered) orelse return null;
return .{ .node = opened.node, .backend = b.handle };
},
}
}
@@ -248,15 +254,13 @@ pub const Directory = struct {
self.cursor += 1;
return true;
};
const request = vfs_protocol.Request{ .operation = .readdir, .node = self.node, .offset = self.cursor, .len = 0, .flags = 0 };
var buffer: [vfs_protocol.message_maximum]u8 = undefined;
const r = transact(h, request, &.{}, &buffer) orelse return false;
if (r.reply.status != 0 or r.reply.len == 0) return false; // error or EOF
if (r.payload.len < vfs_protocol.directory_entry_size) return false;
const header = std.mem.bytesToValue(vfs_protocol.DirectoryEntry, r.payload[0..vfs_protocol.directory_entry_size]);
var reply: [vfs_protocol.message_maximum]u8 = undefined;
const answered = transact(.readdir, h, self.node, .{ .cursor = self.cursor }, &.{}, &reply) orelse return false;
const header = Protocol.decodeReply(.readdir, answered) orelse return false;
if (header.name_len == 0) return false; // end of directory
entry.kind = kindFromWire(header.kind);
entry.size = header.size;
const source = r.payload[vfs_protocol.directory_entry_size..];
const source = Protocol.replyTail(.readdir, answered);
const nlen = @min(@min(@as(usize, header.name_len), source.len), entry.name_buffer.len);
@memcpy(entry.name_buffer[0..nlen], source[0..nlen]);
entry.name_len = nlen;
@@ -280,13 +284,11 @@ pub fn openDirectory(path: []const u8) ?Directory {
// A path-based request that returns only a status (mkdir, unlink). Kernel-served
// paths (the read-only /system) refuse mutation by construction: the resolve
// must land on a backend.
fn pathOperation(operation: vfs_protocol.Operation, path: []const u8) bool {
fn pathOperation(comptime operation: Protocol.Operation, path: []const u8) bool {
const route = resolve(path, 0) orelse return false;
if (route != .backend) return false;
const relative = route.backendPath();
const request = vfs_protocol.Request{ .operation = operation, .node = 0, .offset = 0, .len = @intCast(relative.len), .flags = 0 };
const r = transact(route.backend.handle, request, relative, &.{}) orelse return false;
return r.reply.status == 0;
var reply: [vfs_protocol.message_maximum]u8 = undefined;
return transact(operation, route.backend.handle, 0, {}, route.backendPath(), &reply) != null;
}
/// Create a directory at `path` (its parent must already exist). Returns true on
@@ -336,9 +338,8 @@ pub fn rename(old_path: []const u8, new_path: []const u8) bool {
@memcpy(payload[0..old_relative.len], old_relative);
payload[old_relative.len] = 0;
@memcpy(payload[old_relative.len + 1 ..][0..new_relative.len], new_relative);
const request = vfs_protocol.Request{ .operation = .rename, .node = 0, .offset = 0, .len = @intCast(total), .flags = 0 };
const r = transact(old_route.backend.handle, request, payload[0..total], &.{}) orelse return false;
return r.reply.status == 0;
var reply: [vfs_protocol.message_maximum]u8 = undefined;
return transact(.rename, old_route.backend.handle, 0, {}, payload[0..total], &reply) != null;
}
/// Mount a filesystem backend (its server endpoint) at absolute path `target`;
+17 -1
View File
@@ -182,6 +182,22 @@ pub fn spawnWithArguments(name: []const u8, arguments: []const []const u8) ?u32
/// `ipc.replyWait` as a child-exit badge (`ipc.Received.isChildExit`/`childProcessId`), so
/// one endpoint can supervise many children. Returns the child's process id, or null.
pub fn spawnSupervised(name: []const u8, arguments: []const []const u8, exit_endpoint: ?usize) ?u32 {
return spawnSupervisedWithDevice(name, arguments, exit_endpoint, abi.no_device);
}
/// Spawn a supervised child **and give it a device you hold**, in one call.
///
/// The device manager's path: it holds the hardware and the driver it starts must have
/// it. Fusing the handover into the spawn is what removes the window a separate
/// transfer would leave — the child cannot run without its device, because it does not
/// exist until it holds it (docs/os-development/device-authority.md). The kernel checks
/// only that the device is the caller's to give.
pub fn spawnSupervisedWithDevice(
name: []const u8,
arguments: []const []const u8,
exit_endpoint: ?usize,
device: u64,
) ?u32 {
var blob: [256]u8 = undefined;
var len: usize = 0;
for (arguments, 0..) |argument, i| {
@@ -194,7 +210,7 @@ pub fn spawnSupervised(name: []const u8, arguments: []const []const u8, exit_end
@memcpy(blob[len..][0..argument.len], argument);
len += argument.len;
}
const r = sc.systemCall5(.system_spawn, @intFromPtr(name.ptr), name.len, if (len == 0) 0 else @intFromPtr(&blob), len, exit_endpoint orelse abi.no_cap);
const r = sc.systemCall6(.system_spawn, @intFromPtr(name.ptr), name.len, if (len == 0) 0 else @intFromPtr(&blob), len, exit_endpoint orelse abi.no_cap, device);
if (r > ~@as(usize, 0) - 4095) return null; // a wrapped -errno
return @intCast(r);
}
+268 -1
View File
@@ -12,6 +12,12 @@
//! therefore safe, and keeping is explicit; the opposite arrangement quietly
//! spends a handle-table slot per request.
//!
//! The harness also owns the **subscriber side** of a protocol that declares
//! `.events` — see `Subscribers`. The table, the reserved subscribe/unsubscribe
//! verbs, the fan-out, and the dead-subscriber sweep live here rather than in
//! each provider, so every event stream in the system has identical semantics
//! (docs/os-development/protocol-namespace.md, "Wiring").
//!
//! The liveness probe: a **zero-length request is the universal ping**, answered
//! with a zero-length reply by the harness itself. No protocol's requests start
//! at length zero, so the encoding cannot collide, and there is nothing for a
@@ -19,9 +25,23 @@
//! is the diagnosis (see docs/ipc.md).
const channel = @import("channel");
const envelope = @import("envelope");
const ipc = @import("ipc");
const process = @import("process");
/// The harness's handle on a provider's subscriber table, type-erased because
/// `run` is not generic over the protocol while `Subscribers` is. A service names
/// its table once, as `Callbacks.subscribers`, and the loop does the rest: it
/// subscribes to published process exits at startup and drops a dead task's
/// subscriptions before the service's own notification callback ever sees the
/// badge.
pub const SubscriberHooks = struct {
/// Ask the kernel for published exit events on this service's endpoint.
watch: *const fn (endpoint: ipc.Handle) void,
/// Drop everything task `dead` had subscribed.
forget: *const fn (dead: u32) void,
};
pub const Callbacks = struct {
/// Called once with the service's endpoint before the loop starts — the
/// place to subscribe to exit events, bind IRQs, or announce readiness.
@@ -60,20 +80,255 @@ pub const Callbacks = struct {
/// `init` runs, so the service is reachable the moment it serves. A refusal
/// (not granted, or a live provider already holds the name) aborts startup.
service: ?[]const u8 = null,
/// This provider's subscriber table — `Subscribers(Protocol, Context).hooks`
/// — for a protocol that declares `.events`. Naming it here is what buys the
/// exit-notification sweep: the loop subscribes to published deaths at
/// startup and releases a dead subscriber's slot (and the endpoint capability
/// in it) when one lands.
subscribers: ?SubscriberHooks = null,
};
/// How many subscribers one provider fans out to. Bounded like every table in
/// this system; a subscribe past the end is refused with `-ENOSPC` rather than
/// silently forgetting an earlier one.
pub const subscriber_capacity = 8;
/// The interest mask that means "every event of this protocol" — what a
/// subscriber which named no class gets, and what a provider passes when the
/// event it is publishing belongs to no class.
pub const every_event: u32 = 0;
/// The subscriber side of a protocol, for a provider whose contract declares
/// `.events` (docs/os-development/protocol-namespace.md: *the harness owns the
/// machinery — the subscriber table, the dead-subscriber sweep, and the fan-out
/// loop*). Three services hand-rolled this, with three different ideas of when a
/// dead subscriber goes away — a poll of the process list on subscribe, a drop on
/// a failed send, and nothing at all. This is the one idiom.
///
/// ```zig
/// const Subscriptions = service.Subscribers(power_protocol.Protocol, void);
/// ...
/// fn onMessage(message: []const u8, reply: []u8, sender: u32, arrived: *ipc.Arrival) usize {
/// return Subscriptions.dispatch({}, handlers, message, sender, arrived, reply);
/// }
/// pub fn main() void {
/// service.run(power_protocol.message_maximum, .{
/// .service = "power",
/// .on_message = onMessage,
/// .subscribers = Subscriptions.hooks,
/// });
/// }
/// ```
///
/// What the provider still writes is its own events — `publish(.power_button, 0,
/// .{})`. Everything else happens here: registering the caller's endpoint on the
/// reserved `subscribe` verb, taking that capability out of the turn, dropping it
/// on `unsubscribe` or on the subscriber's death, and framing one packet for the
/// whole fan-out.
///
/// The table is per instantiation (a container-level `var` inside the generic
/// type), so a process providing two contracts gets two tables and neither can
/// see the other's subscribers.
pub fn Subscribers(comptime Protocol: type, comptime Context: type) type {
return struct {
/// The generated dispatch this provider answers with.
pub const Provider = Protocol.Provider(Context);
pub const Handlers = Provider.Handlers;
/// One registered subscriber: the endpoint events are pushed to (the
/// capability it handed over at subscribe time, which this slot owns),
/// the task that handed it over — the kernel-stamped badge, the only
/// source identity there is — and which classes of event it asked for.
const Slot = struct {
used: bool = false,
endpoint: ipc.Handle = 0,
task: u32 = 0,
interest: u32 = every_event,
};
var slots: [subscriber_capacity]Slot = .{Slot{}} ** subscriber_capacity;
/// Set when a slot has taken the capability the turn carried, and read
/// back in `dispatch`, which is where the turn's `Arrival` lives. The
/// generated dispatch hands a handler the raw handle rather than the
/// `Arrival` — deliberately, since a handler has no business closing the
/// turn's property — so the *claim* has to travel back out this way. One
/// turn, one handler, one thread: there is nothing here to race.
var claimed = false;
/// What `Callbacks.subscribers` is given.
pub const hooks: SubscriberHooks = .{ .watch = watchExits, .forget = forget };
fn watchExits(endpoint: ipc.Handle) void {
// Published exits, not a poll of the process list: a service must
// never depend on clients cleaning up after themselves, and it must
// not have to walk the whole table on every subscribe to find out
// either (docs/process-lifecycle.md, "Who learns of a death").
_ = process.subscribeExits(endpoint);
}
/// Release everything task `dead` had subscribed. The slot owns the
/// endpoint capability, so reclaiming the slot closes it — otherwise a
/// process that subscribes and dies costs a handle-table slot that never
/// comes back.
pub fn forget(dead: u32) void {
for (&slots) |*slot| {
if (slot.used and slot.task == dead) {
_ = ipc.close(slot.endpoint);
slot.* = .{};
}
}
}
/// Whether `task` is a subscriber — the gate for an operation a provider
/// honours from its subscribers and nobody else. The power service's
/// shutdown is the one: the badge is kernel-stamped, so nothing in a
/// packet can claim to be the subscriber that already ran the stop
/// sequence.
pub fn has(task: u32) bool {
for (&slots) |*slot| {
if (slot.used and slot.task == task) return true;
}
return false;
}
/// A provider's own handler kept this turn's capability (stored it
/// somewhere with a lifetime beyond the turn) — the same claim the
/// reserved `subscribe` makes for its slot table. Composes with it:
/// one flag, one `take()`, whoever claims first wins the turn.
pub fn claimArrival() void {
claimed = true;
}
/// Answer one received packet, with the reserved `subscribe` and
/// `unsubscribe` verbs already wired — a provider that leaves those two
/// handlers null (every provider should) gets the harness's. The turn's
/// capability is peeked, never taken, unless a slot actually kept it.
pub fn dispatch(
context: Context,
handlers: Handlers,
packet: []const u8,
sender: u32,
arrived: *ipc.Arrival,
reply: []u8,
) usize {
var wired = handlers;
if (wired.subscribe == null) wired.subscribe = onSubscribe;
if (wired.unsubscribe == null) wired.unsubscribe = onUnsubscribe;
claimed = false;
const written = Provider.dispatch(context, wired, packet, sender, arrived.peek(), reply);
if (claimed) _ = arrived.take();
return written;
}
/// Push one event to every subscriber.
pub fn publish(
comptime event: Protocol.Event,
target: u64,
payload: Protocol.PayloadOf(event),
) void {
publishClass(event, target, payload, every_event);
}
/// Push one event to the subscribers whose interest mask includes
/// `class` (a subscriber that named no class takes everything). The
/// packet is framed **once**, outside the loop, so every subscriber of a
/// class receives identical bytes; and delivery is `ipc.send`, which
/// never blocks, so one slow or dead subscriber can never stall the rest
/// — the whole reason broadcast is a provider pattern and not a kernel
/// primitive.
pub fn publishClass(
comptime event: Protocol.Event,
target: u64,
payload: Protocol.PayloadOf(event),
class: u32,
) void {
var packet: [envelope.post_maximum]u8 = undefined;
const framed = Protocol.encodeEvent(event, target, payload, &packet) orelse return;
for (&slots) |*slot| {
if (!slot.used) continue;
if (!wants(slot.*, class)) continue;
// The sweep is what normally reclaims a dead subscriber, promptly
// and with its capability closed. This is the backstop for a
// notification that never arrived: an endpoint's notify ring is
// bounded, so a burst of deaths can drop one, and a send to an
// endpoint whose owner is gone fails rather than blocking.
if (!ipc.send(slot.endpoint, framed)) {
_ = ipc.close(slot.endpoint);
slot.* = .{};
}
}
}
fn wants(slot: Slot, class: u32) bool {
if (class == every_event) return true; // the event belongs to no class
if (slot.interest == every_event) return true; // the subscriber named none
return slot.interest & class != 0;
}
/// The reserved `subscribe` verb: register the caller's endpoint (the
/// call's capability) for the classes its tail names. A refusal simply
/// returns and the turn closes what arrived — the harness's ownership
/// rule (`ipc.Arrival`), which is why a subscribe storm against a full
/// table cannot spend the handle table.
fn onSubscribe(_: Context, invocation: envelope.Invocation(void), _: envelope.Answer(void)) isize {
const endpoint = invocation.capability orelse return -envelope.EPROTO; // no endpoint passed
const interest = envelope.decodeSubscribe(invocation.tail).interest;
for (&slots) |*slot| {
if (slot.used) continue;
// Appended, not replaced: one task may hold several subscriptions
// on different endpoints (a client taking keyboard and mouse as
// two streams), and each is its own conversation.
slot.* = .{ .used = true, .endpoint = endpoint, .task = invocation.sender, .interest = interest };
claimed = true; // the table holds it until that task dies
return 0;
}
return -envelope.ENOSPC; // table full
}
/// The reserved `unsubscribe` verb: every subscription the calling task
/// holds here goes, which is exactly what its death would do. It names no
/// endpoint because the badge already names the only subscriber a caller
/// can speak for — its own.
fn onUnsubscribe(_: Context, invocation: envelope.Invocation(void), _: envelope.Answer(void)) isize {
if (!has(invocation.sender)) return -envelope.ENOENT;
forget(invocation.sender);
return 0;
}
};
}
/// Run the service: create the endpoint, bind it under the service's contract
/// name (if it has one), bind signals to it, call `init`, then serve until
/// `terminate` arrives — at which point the loop returns and main's return is
/// the clean exit the supervisor reads as `ExitReason.exited`.
/// `maximum_message` sizes the receive and reply buffers (a service passes its
/// protocol's message maximum).
/// The capability the current turn's handler nominates to ride out with its
/// reply — init's registry idiom (`pending_capability`), lifted into the
/// harness so any service can answer an establishment request with a channel
/// (communication.md "Establishment: two planes"). Consumed by the loop at the
/// very next `replyWait`, which is the reply this turn owes; null is the
/// untouched common path. The kernel shares the endpoint as a refcounted copy,
/// so the nominating service keeps its own handle.
var pending_reply_capability: ?ipc.Handle = null;
/// Called from inside an `on_message` handler: send `handle` with this turn's
/// reply. One capability per turn — the last nomination wins, matching the
/// transport (a reply carries at most one).
pub fn replyWithCapability(handle: ipc.Handle) void {
pending_reply_capability = handle;
}
pub fn run(comptime maximum_message: usize, callbacks: Callbacks) void {
const endpoint = ipc.createIpcEndpoint() orelse return;
if (callbacks.service) |name| {
if (!channel.bindPatiently(name, endpoint)) return;
}
_ = process.bindSignals(endpoint);
// Before `init`, so a subscriber that arrives the instant the name is bound
// is already covered by the sweep that will release it.
if (callbacks.subscribers) |subscribers| subscribers.watch(endpoint);
if (callbacks.init) |initialise| {
if (!initialise(endpoint)) return;
}
@@ -82,7 +337,12 @@ pub fn run(comptime maximum_message: usize, callbacks: Callbacks) void {
var reply_len: usize = 0;
var receive: [maximum_message]u8 = undefined;
while (true) {
const got = ipc.replyWait(endpoint, reply_buffer[0..reply_len], &receive, null);
// The reply going out is the one the just-run handler wrote, so the
// capability it nominated (if any) rides this exact replyWait and is
// reset before the next turn can see a stale one.
const reply_capability = pending_reply_capability;
pending_reply_capability = null;
const got = ipc.replyWait(endpoint, reply_buffer[0..reply_len], &receive, reply_capability);
// Whatever capability came with this turn is the turn's, and the turn
// closes it unless a callback claims it (`ipc.Arrival`). Structural
// rather than a close per branch, because the branches are exactly what
@@ -105,6 +365,13 @@ pub fn run(comptime maximum_message: usize, callbacks: Callbacks) void {
}
continue;
}
// A death sweeps the subscriber table first, then still reaches the
// service: a provider often has its own per-client state to release
// (open file handles, device tokens, layers) and the same badge is
// the notice for both.
if (got.isChildExit()) {
if (callbacks.subscribers) |subscribers| subscribers.forget(got.childProcessId());
}
if (callbacks.on_notification) |onNotification| onNotification(got.badge);
continue;
}
+16
View File
@@ -65,3 +65,19 @@ pub inline fn systemCall5(n: SystemCall, a0: usize, a1: usize, a2: usize, a3: us
[a4] "{r8}" (a4),
: .{ .rcx = true, .r11 = true, .memory = true });
}
/// The sixth and last argument register. `syscall` clobbers rcx, so r10 stands in for
/// it and r9 is the end of the line — a call needing a seventh would have to pass a
/// struct instead.
pub inline fn systemCall6(n: SystemCall, a0: usize, a1: usize, a2: usize, a3: usize, a4: usize, a5: usize) usize {
return asm volatile ("syscall"
: [ret] "={rax}" (-> usize),
: [n] "{rax}" (@intFromEnum(n)),
[a0] "{rdi}" (a0),
[a1] "{rsi}" (a1),
[a2] "{rdx}" (a2),
[a3] "{r10}" (a3),
[a4] "{r8}" (a4),
[a5] "{r9}" (a5),
: .{ .rcx = true, .r11 = true, .memory = true });
}
+49 -39
View File
@@ -1,51 +1,61 @@
//! The block-device wire protocol — what a filesystem (the FAT server) says to a
//! block driver (usb-storage) over its well-known `.block` endpoint. A protocol
//! module like vfs-protocol / usb-transfer-protocol: extern-struct messages, an
//! `Operation` tag, everything in one IPC message.
//! block driver (usb-storage) over `/protocol/block`. Defined through the
//! envelope, so every packet begins with the folded `Header`.
//!
//! **`Header.target` is always 0 here**: a block driver instance serves exactly
//! one device over its own endpoint, so there is no object within the peer to
//! address. A driver that later fronts several volumes gives them target ids and
//! `enumerate` lists them; nothing else about the protocol changes.
//!
//! Data path: read and write move whole blocks to or from a **caller-owned DMA
//! buffer**, named by its physical address — the same physical-address handoff
//! usb-storage already uses toward the controller, one layer up. So a 512-byte
//! sector never has to cross the 256-byte IPC boundary; only the small request /
//! reply headers do. Under an enforcing IOMMU the buffer's physical addresses are
//! only reachable by the device once the filesystem has `attach`ed the buffer's
//! capability (the block server forwards it to the controller); see docs/driver-model.md.
//! sector never has to cross the packet floor; only the small request / reply
//! parts do. Under an enforcing IOMMU the buffer's physical addresses are only
//! reachable by the device once the filesystem has `attach`ed the buffer's
//! capability (the block server forwards it to the controller); see
//! docs/driver-model.md.
pub const Operation = enum(u32) {
/// geometry() -> { block_size, block_count }
geometry = 0,
/// read(lba, count, physical): read `count` blocks from `lba` into the buffer
read = 1,
/// write(lba, count, physical): write `count` blocks at `lba` from the buffer
write = 2,
/// flush(): commit any device write cache to stable media (no data transfer).
/// A filesystem calls this to make prior writes durable — e.g. before power-off,
/// so a shutdown-time write isn't lost in the USB flash controller's cache.
flush = 3,
/// attach(): the caller's DMA-region capability rides the call's cap slot; the
/// block server forwards it to the controller so the buffer's physical addresses
/// (named in later read/write) are reachable by the device under an enforcing
/// IOMMU. Call once per buffer before using it in a transfer.
attach = 4,
const envelope = @import("envelope");
/// The answer to `geometry()`.
pub const Geometry = extern struct {
block_size: u32, // bytes per block (512)
_padding: u32 = 0,
block_count: u64, // total blocks
};
pub const Request = extern struct {
operation: u32,
reserved: u32 = 0,
/// `read(lba, count, physical)` / `write(...)`: move `count` blocks between the
/// device and the caller's DMA buffer at `physical`.
pub const Transfer = extern struct {
lba: u64,
count: u32, // number of blocks (read/write)
reserved2: u32 = 0,
physical: u64, // caller's DMA buffer physical address (read/write)
count: u32,
_padding: u32 = 0,
physical: u64, // caller's DMA buffer physical address
};
pub const Reply = extern struct {
status: i32, // 0 on success, negative on failure
reserved: u32 = 0,
block_size: u32, // geometry: bytes per block (512)
reserved2: u32 = 0,
block_count: u64, // geometry: total blocks; read/write: blocks moved
};
/// How many blocks a transfer actually moved.
pub const Transferred = extern struct { count: u32 };
pub const message_maximum: usize = 256;
pub const request_size: usize = @sizeOf(Request);
pub const reply_size: usize = @sizeOf(Reply);
pub const Protocol = envelope.Define(.{
.name = "block",
.version = 1,
.operations = &.{
.{ .name = "geometry", .reply = Geometry },
.{ .name = "read", .request = Transfer, .reply = Transferred },
.{ .name = "write", .request = Transfer, .reply = Transferred },
// flush(): commit any device write cache to stable media (no data
// transfer). A filesystem calls this to make prior writes durable —
// before power-off, so a shutdown-time write isn't lost in the USB flash
// controller's cache.
.{ .name = "flush" },
// attach(): the caller's DMA-region capability rides the call's cap
// slot; the block server forwards it to the controller so the buffer's
// physical addresses (named in later read/write) are reachable by the
// device under an enforcing IOMMU. Call once per buffer before using it.
.{ .name = "attach" },
},
});
pub const Operation = Protocol.Operation;
pub const message_maximum: usize = Protocol.message_maximum;
+26 -6
View File
@@ -3,7 +3,8 @@
//! every conversation depend on the contract by name; neither reaches into the
//! other's files. Pure flat wire types: no protocol module imports anything.
//!
//! One module here is not a protocol but the shape the others are written in:
//! One module here is not a protocol but the shape the others are written in,
//! and therefore the one module every other one imports:
//!
//! envelope : the packet prefix + comptime Define (docs/os-development/protocol-namespace.md)
//!
@@ -19,10 +20,12 @@
const std = @import("std");
pub fn build(b: *std.Build) void {
// Not a protocol, hence not `-protocol`: the envelope is what a protocol is
// defined *through*, so it is built first and handed to every protocol
// below as their one import.
const envelope = b.addModule("envelope", .{ .root_source_file = b.path("envelope/envelope.zig") });
for ([_]struct { name: []const u8, root: []const u8 }{
// Not a protocol, hence not `-protocol`: the envelope is what a
// protocol is defined *through*.
.{ .name = "envelope", .root = "envelope/envelope.zig" },
.{ .name = "vfs-protocol", .root = "vfs/vfs-protocol.zig" },
.{ .name = "input-protocol", .root = "input/input-protocol.zig" },
.{ .name = "block-protocol", .root = "block/block-protocol.zig" },
@@ -32,21 +35,38 @@ pub fn build(b: *std.Build) void {
.{ .name = "scanout-protocol", .root = "scanout/scanout-protocol.zig" },
.{ .name = "power-protocol", .root = "power/power-protocol.zig" },
}) |protocol| {
_ = b.addModule(protocol.name, .{ .root_source_file = b.path(protocol.root) });
_ = b.addModule(protocol.name, .{
.root_source_file = b.path(protocol.root),
.imports = &.{.{ .name = "envelope", .module = envelope }},
});
}
// Standalone `zig build test` for this domain alone; the root build keeps
// its aggregate test step.
const test_step = b.step("test", "Run the protocol unit tests");
// The envelope tests itself with no import of its own — everything else
// imports it, so it is built separately rather than importing itself.
const envelope_tests = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("envelope/envelope.zig"), // framing round trips, verb numbering, dispatch, the floors
.target = b.resolveTargetQuery(.{}),
}),
});
test_step.dependOn(&b.addRunArtifact(envelope_tests).step);
for ([_][]const u8{
"envelope/envelope.zig", // framing round trips, verb numbering, dispatch, the floors
"vfs/vfs-protocol.zig", // NodeKind / DirectoryEntry sizes + op values
"input/input-protocol.zig", // event numbering + the push-floor budget
"display/display-protocol.zig", // pack(): native pixel encoding per format
"device-manager/device-manager-protocol.zig", // the dual-use report, exactly on the push floor
"power/power-protocol.zig", // the event kind as the packet's verb
"usb-transfer/usb-transfer-protocol.zig", // the tail-carried control stage + the trimmed report
}) |root| {
const protocol_tests = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path(root),
.target = b.resolveTargetQuery(.{}),
.imports = &.{.{ .name = "envelope", .module = envelope }},
}),
});
test_step.dependOn(&b.addRunArtifact(protocol_tests).step);
@@ -1,15 +1,48 @@
//! The device-manager protocol (docs/device-manager.md): what drivers and
//! applications say to the device manager over its well-known endpoint. The
//! vfs-protocol pattern — extern-struct messages, a version in the handshake,
//! reserved fields — so both sides depend on the contract by name. Deliberately
//! contains nothing lifecycle-shaped: stopping, liveness (the zero-length ping),
//! and exit reasons are the universal vocabulary of
//! The device-manager protocol (docs/device-driver-development/device-manager.md):
//! what drivers and applications say to the device manager over
//! `/protocol/device-manager`. Defined through the envelope
//! (docs/os-development/protocol-namespace.md), so every packet — request, reply,
//! and pushed event alike — begins with the folded `Header`.
//!
//! **`Header.target` is the device id.** It was the `device_id` field of three
//! different messages; folding it into the header is what made the packed
//! leading operation byte disappear along with it. `no_device` addresses a
//! driver that serves no enumerated device.
//!
//! Two of the manager's four old operations were the reserved verbs under
//! another name and are gone from this protocol's own numbering: `enumerate`
//! (the tree, one `ChildEntry` per record in the reply tail) and `subscribe`
//! (the watcher's endpoint rides as the call's capability). What is left is the
//! driver-facing half — the handshake and the two tree reports.
//!
//! **`ChildAdded` travels in both directions, and says so twice.** A bus driver
//! *calls* `child_added` to report a device; the manager then *pushes* the same
//! struct to every subscriber as the `child_added` event. Operations and events
//! are numbered in separate spaces, so one struct under two numbers is exactly
//! how the envelope spells "one encoding, both directions" — and the direction
//! (call vs. send) already tells them apart.
//!
//! Deliberately contains nothing lifecycle-shaped: stopping, liveness (the
//! zero-length ping), and exit reasons are the universal vocabulary of
//! docs/process-lifecycle.md, not this protocol.
/// The protocol version a driver states in its hello. A manager that cannot
/// serve a driver's version refuses the hello, and the mismatch is loud at
/// startup instead of quiet corruption later.
pub const version: u16 = 1;
const std = @import("std");
const envelope = @import("envelope");
/// The protocol version a driver states in its hello, and the version this
/// contract answers `describe` with. A manager that cannot serve a driver's
/// version refuses the hello, and the mismatch is loud at startup instead of
/// quiet corruption later.
///
/// `describe` publishes the same number, but it cannot replace this: it tells a
/// *client* what the provider is, and here it is the **provider** that has to
/// learn what the client was built against in order to refuse it.
pub const version = 1;
/// `Header.target` for a driver that serves no enumerated device (a test
/// fixture, a synthetic source), and `ChildAdded`'s answer for a leaf that was
/// never `device_register`ed.
pub const no_device: u64 = ~@as(u64, 0);
/// Which bus a `child_added` came from — stated by the reporting bus driver so
/// the manager's /system/configuration/devices.csv matcher knows how to read the report's identity
@@ -24,66 +57,64 @@ pub const BusKind = enum(u8) {
acpi = 3,
};
/// What kind of driver is talking (docs/driver-model.md's shapes).
/// What kind of driver is talking (docs/device-driver-development/driver-model.md's shapes).
pub const Role = enum(u8) {
/// Owns a controller and reports the devices behind it (`child_added`).
bus = 1,
/// Serves one device, reached through a bus's transfer protocol.
device = 2,
/// Not a spawned driver at all: a party asking for the channel of the
/// driver BOUND TO the target device (a service consuming a driver-layer
/// contract — fat asking for its volume's block provider). No deadline, no
/// state, no driver entry; just establishment by lineage.
consumer = 3,
};
/// The message kinds.
pub const Operation = enum(u8) {
hello = 1,
child_added = 2,
child_removed = 3,
enumerate = 4,
subscribe = 5,
};
/// `Hello.device_id` for a driver that serves no enumerated device (a test
/// fixture, a synthetic source).
pub const no_device: u64 = ~@as(u64, 0);
// --- the per-operation request parts ----------------------------------------
//
// Each names the bytes AFTER the prefix. Nothing here carries an operation or a
// device id: those are the packet header's, folded in once. No reply part
// carries a status either — that is the `Status` every reply already begins
// with, so the manager's old three `{status, reserved}` reply structs are gone.
/// The handshake, sent once by every driver the manager spawns — the manager's
/// one self-enforced deadline: spawned and silent past it means wrong binary,
/// wrong version, or wedged before main, and the stop sequence follows.
/// wrong version, or wedged before main, and the stop sequence follows. The
/// device this driver was assigned (its argv[1]) is `Header.target`.
pub const Hello = extern struct {
operation: u8 = @intFromEnum(Operation.hello),
/// A Role value.
/// A `Role` value.
role: u8,
/// 1 = the caller asks the reply to carry a capability to the channel of
/// the driver that provides the caller's device — the target's reporter;
/// establishment by lineage (communication.md "Establishment: two
/// planes"). 0 = a plain handshake, and the reply carries nothing — which
/// keeps every caller that never reads a reply capability from leaking
/// one. Was padding, so old callers wire-compatibly say 0.
wants_channel: u8 = 0,
/// The protocol version this driver was built against (`version`).
version: u16 = version,
reserved: u32 = 0,
/// The device this driver was assigned (its argv[1]), or `no_device`.
device_id: u64,
};
pub const hello_size = @sizeOf(Hello);
/// The manager's answer to a hello. Nonzero status = refused (version mismatch,
/// unknown sender); a refused driver should exit cleanly.
pub const HelloReply = extern struct {
status: i32,
reserved: u32 = 0,
};
pub const reply_size = @sizeOf(HelloReply);
/// A bus driver reporting one device it discovered behind its controller
/// (docs/device-manager.md "the tree"). Identity is the bus's native language —
/// for USB a port-speed class; the (class, subclass, protocol) triple joins it
/// once control transfers exist (the USB track). The manager mirrors the child
/// into its tree; when the reporting driver dies, the manager prunes everything
/// it reported (the children describe protocol state that died with it) and the
/// restarted instance rediscovers and re-reports.
/// (docs/device-driver-development/device-manager.md "the tree"), and the payload
/// the manager pushes to its subscribers for the same event. Identity is the
/// bus's native language — for USB a port-speed class, for PCI the class triple.
/// The manager mirrors the child into its tree; when the reporting driver dies,
/// the manager prunes everything it reported (the children describe protocol
/// state that died with it) and the restarted instance rediscovers and
/// re-reports.
///
/// `Header.target` is the kernel device id this child was `device_register`ed
/// as — what the manager hands a matched driver as its argv assignment — or
/// `no_device` for an unregistered leaf (a USB port before the descriptor
/// track). That is the field that used to sit at the end of this struct.
///
/// **The field order is the size budget.** An event packet is the header plus
/// this, within 64 bytes, and three `u64`s round the whole struct up to a
/// multiple of eight whatever order they sit in — so the small fields are
/// packed tail-first into the space the rounding pays for anyway. `Define`
/// checks the result; this comment is why there is no slack in it.
pub const ChildAdded = extern struct {
operation: u8 = @intFromEnum(Operation.child_added),
/// A `BusKind` value: which bus reported this child, so the manager reads the
/// identity in the right namespace and matches against the right `bus` column.
bus: u8 = @intFromEnum(BusKind.unknown),
reserved1: u16 = 0,
reserved2: u32 = 0,
/// The reporting driver's own device (the controller) — the child's parent.
parent: u64,
/// Where on the bus (for USB: the root port number, 1-based).
@@ -91,10 +122,10 @@ pub const ChildAdded = extern struct {
/// Bus-specific identity (for USB: the PORTSC port-speed class; for PCI:
/// the class triple; for ACPI devices, 0 — identity is the hid below).
identity: u64,
/// The kernel device id this child was `device_register`ed as — what the
/// manager hands a matched driver as its argv assignment — or `no_device`
/// for an unregistered leaf (a USB port before the descriptor track).
device_id: u64 = no_device,
/// The PCI subsystem id, packed `(subsystem_vendor << 16) | subsystem_device`
/// (so it reads vendor-first, matching the CSV's `ssvid:ssid`), or 0 when the
/// device has no subsystem id (a bridge, or a non-PCI bus).
subsystem: u32 = 0,
/// The vendor id (PCI vendor / USB idVendor), or 0 when the bus has no such
/// concept (ACPI). Carried so the manager's /system/configuration/devices.csv matcher can bind
/// on vendor — a level the bus-native `identity` (a class triple) cannot express.
@@ -103,73 +134,126 @@ pub const ChildAdded = extern struct {
/// level: this is what lets one virtio-gpu (1AF4:1050) be told from any other
/// virtio display function without the driver re-confirming after it is spawned.
device: u16 = 0,
/// The PCI subsystem id, packed `(subsystem_vendor << 16) | subsystem_device`
/// (so it reads vendor-first, matching the CSV's `ssvid:ssid`), or 0 when the
/// device has no subsystem id (a bridge, or a non-PCI bus).
subsystem: u32 = 0,
/// The ACPI hardware id (`_HID`), EISA-decoded (e.g. "PNP0303"), for devices
/// discovered by firmware string rather than a numeric bus identity. Empty
/// (all zero) otherwise. Widens for FDT `compatible` strings later.
hid: [8]u8 = .{0} ** 8,
/// A `BusKind` value: which bus reported this child, so the manager reads the
/// identity in the right namespace and matches against the right `bus` column.
bus: u8 = @intFromEnum(BusKind.unknown),
_padding: [7]u8 = .{0} ** 7,
};
pub const child_added_size = @sizeOf(ChildAdded);
/// A bus driver reporting a device gone (hot-unplug). Not yet sent by any
/// driver — the port scan has no unplug interrupt — but the manager handles it;
/// death-pruning covers removal until hotplug lands.
/// A bus driver reporting a device gone (hot-unplug), and the payload pushed to
/// subscribers for it.
///
/// **This is the one message whose target stays 0.** A removal is addressed by
/// the composite (parent, bus address) — the reporter knows where the device
/// *was*, not necessarily what id it had been registered under — and a single
/// `u64` cannot carry a pair. So the address stays in the payload, where it
/// always was, and the header addresses the provider itself.
pub const ChildRemoved = extern struct {
operation: u8 = @intFromEnum(Operation.child_removed),
reserved0: u8 = 0,
reserved1: u16 = 0,
reserved2: u32 = 0,
parent: u64,
bus_address: u64,
};
pub const child_removed_size = @sizeOf(ChildRemoved);
/// The manager's answer to a tree report.
pub const ReportReply = extern struct {
status: i32,
reserved: u32 = 0,
};
/// An application asking for the tree (M18.3): the reply is an EnumerateReply
/// header followed by `count` ChildEntry records.
pub const Enumerate = extern struct {
operation: u8 = @intFromEnum(Operation.enumerate),
reserved0: u8 = 0,
reserved1: u16 = 0,
reserved2: u32 = 0,
};
pub const EnumerateReply = extern struct {
status: i32,
/// ChildEntry records following this header.
count: u32,
};
/// One record of the reserved `enumerate` reply: the manager's mirror, one
/// entry per known child, packed into the reply tail. The count is
/// `Status.len / @sizeOf(ChildEntry)` — the envelope's reply length says how
/// many arrived, so no count header is spent on saying it twice.
pub const ChildEntry = extern struct {
parent: u64,
bus_address: u64,
identity: u64,
/// The kernel device id this child was registered as (`no_device` for an
/// unregistered leaf) — what a `.consumer` hello names as its target to be
/// routed to the driver bound to this child.
device_id: u64,
};
/// An application subscribing to published add/remove events (the input-service
/// pattern): the subscriber's endpoint rides as the call's **capability**, and
/// events arrive on it as buffered messages whose payload is the same
/// ChildAdded / ChildRemoved struct the bus drivers send — one encoding, both
/// directions.
pub const Subscribe = extern struct {
operation: u8 = @intFromEnum(Operation.subscribe),
reserved0: u8 = 0,
reserved1: u16 = 0,
reserved2: u32 = 0,
};
/// How many `ChildEntry` records one `enumerate` reply can carry. The verb is
/// PAGED: the request's `Header.target` is the start index (skip that many
/// known children), and a short or empty page means the tree is exhausted — a
/// real tree outgrew one packet the day ACPI reported a dozen nodes before
/// the first USB child, and an unpaged reply silently truncated exactly the
/// entries a consumer was looking for.
pub const entries_per_reply: usize = (envelope.packet_maximum - envelope.prefix_size) / @sizeOf(ChildEntry);
/// Upper bound on any message in this protocol — sizes the endpoint buffers.
/// Capped by the kernel's IPC MESSAGE_MAXIMUM (256): an EnumerateReply carries
/// up to ten ChildEntry records per call, plenty for the mirror's current
/// bounds; paging joins the protocol if a tree ever outgrows one message.
pub const message_maximum = 256;
pub const Protocol = envelope.Define(.{
.name = "device-manager",
.version = version,
.operations = &.{
// The driver-facing half. `enumerate` and `subscribe` are not here: they
// are the reserved verbs, which mean the same thing at every provider.
.{ .name = "hello", .request = Hello },
.{ .name = "child_added", .request = ChildAdded },
.{ .name = "child_removed", .request = ChildRemoved },
},
.events = &.{
// The watcher-facing half — the same two structs, pushed rather than
// called, in the events' own numbering space.
.{ .name = "child_added", .payload = ChildAdded },
.{ .name = "child_removed", .payload = ChildRemoved },
},
});
pub const Operation = Protocol.Operation;
pub const Event = Protocol.Event;
/// What the manager sizes its buffers to — the call floor, as every protocol does.
pub const message_maximum: usize = Protocol.message_maximum;
test "a tree report fits the push floor with the header folded in" {
// The dual-use struct is the tight one: `child_added` is both a call and an
// event, and the event floor is 64 bytes *including* the header. Forty-one
// bytes of content, rounded to 48 by the three u64s' alignment, plus the
// 16-byte header — exactly on the floor, which is what folding the operation
// byte and the device id out of the payload bought.
try std.testing.expectEqual(@as(usize, 48), @sizeOf(ChildAdded));
try std.testing.expectEqual(envelope.post_maximum, Protocol.event_maximum);
try std.testing.expect(Protocol.event_maximum <= envelope.post_maximum);
// Ten records per enumerate reply — what the old count-header layout carried.
try std.testing.expectEqual(@as(usize, 10), entries_per_reply);
}
test "the verb and event numbering, and the device id in the header" {
try std.testing.expectEqual(@as(u32, 16), @intFromEnum(Operation.hello));
try std.testing.expectEqual(@as(u32, 17), @intFromEnum(Operation.child_added));
try std.testing.expectEqual(@as(u32, 18), @intFromEnum(Operation.child_removed));
// Events number in their own space, so the same two reports start at 16 too.
try std.testing.expectEqual(@as(u32, 16), @intFromEnum(Event.child_added));
try std.testing.expectEqual(@as(u32, 17), @intFromEnum(Event.child_removed));
// The manager's own enumerate/subscribe became the RESERVED verbs, below the
// protocol range entirely.
try std.testing.expectEqual(@as(u32, 1), envelope.operation_enumerate);
try std.testing.expectEqual(@as(u32, 2), envelope.operation_subscribe);
var buffer: [message_maximum]u8 = undefined;
const hello = Protocol.encodeRequest(.hello, 7, .{ .role = @intFromEnum(Role.bus) }, &.{}, &buffer).?;
try std.testing.expectEqual(@as(u64, 7), envelope.headerOf(hello).?.target);
try std.testing.expectEqual(@as(u16, 1), Protocol.decodeRequest(.hello, hello).?.version);
}
test "one struct, two numbers: the report a bus calls and the event a watcher is pushed" {
const report = ChildAdded{
.parent = 3,
.bus_address = 1,
.identity = 0x030000,
.bus = @intFromEnum(BusKind.pci),
.vendor = 0x1AF4,
};
var call: [message_maximum]u8 = undefined;
const called = Protocol.encodeRequest(.child_added, 42, report, &.{}, &call).?;
try std.testing.expectEqual(Operation.child_added, Protocol.operationOf(called).?);
try std.testing.expectEqual(@as(u64, 42), envelope.headerOf(called).?.target);
var push: [envelope.post_maximum]u8 = undefined;
const pushed = Protocol.encodeEvent(.child_added, 42, report, &push).?;
try std.testing.expectEqual(envelope.post_maximum, pushed.len);
try std.testing.expectEqual(Event.child_added, Protocol.eventOf(pushed).?);
try std.testing.expectEqual(@as(u16, 0x1AF4), Protocol.decodeEvent(.child_added, pushed).?.vendor);
// Same bytes after the prefix, different verb in it — the direction is what
// tells a call from a push, and the numbering spaces never collide.
try std.testing.expectEqualSlices(u8, called[envelope.prefix_size..], pushed[envelope.prefix_size..]);
}
+132 -76
View File
@@ -1,93 +1,137 @@
//! The display wire protocol — what a client says to the display service over its
//! well-known `.display` endpoint. extern-struct messages with an `Operation` tag, the
//! same shape as block/vfs/input protocols. The compositor owns the framebuffer and an
//! ordered stack of **layers**; a client creates layers, draws into them with these
//! operations, marks damage, and asks for a `present`. v1 surfaces are server-owned (a
//! client draws by command); shared-memory surfaces are a later milestone (docs/display.md).
//! The display wire protocol — what a client says to the display service over
//! `/protocol/display`. The compositor owns the framebuffer and an ordered stack of
//! **layers**; a client creates layers, draws into them with these operations, marks damage,
//! and asks for a `present`. v1 surfaces are server-owned (a client draws by command);
//! shared-memory surfaces are a later milestone (docs/display.md).
//!
//! **`Header.target` is the layer** on every verb that names one — the field that used to be
//! `Request.layer`. `info`, `present`, `set_mode`, `get_modes` and `attach_scanout` address
//! the compositor itself, so they leave it 0.
//!
//! Every verb carries its own request type. The single overloaded 40-byte request this
//! protocol used to have is gone, and with it the field abuse it invited: `attach_scanout`
//! spent `x` on a stride, `y` on a refresh rate and `colour` on a pixel format, which no
//! reader could have guessed and no compiler could have caught.
const envelope = @import("envelope");
const std = @import("std");
pub const Operation = enum(u32) {
/// info() -> { width, height, pitch, format }: the display's current mode.
info = 0,
/// create_layer(x, y, width, height, z) -> { layer }: a new server-owned surface.
create_layer = 1,
/// configure_layer(layer, x, y, z, visible): move, restack, show, or hide a layer.
configure_layer = 2,
/// destroy_layer(layer): release a layer.
destroy_layer = 3,
/// fill_rect(layer, x, y, width, height, colour): fill a rectangle of a layer.
fill_rect = 4,
/// blit_tile(layer, x, y, width, height, <inline pixels>): copy a small pixel tile in.
blit_tile = 5,
/// damage(layer, x, y, width, height): mark a region dirty for the next present.
damage = 6,
/// present(): composite the dirty layers and flush to the screen.
present = 7,
/// attach_scanout(x=stride, y=refresh_hz, width, height, colour=format) + <surface
/// capability>: a native scanout driver announces itself, handing over the shared scanout
/// surface as an `ipc_call` send_cap. The compositor maps it, looks up the driver's
/// `.scanout` present channel, and upgrades off the GOP floor (docs/display-v2.md V4).
/// `x` is the surface's row stride in pixels, `y` the panel refresh rate from the
/// driver's EDID read (0 = unknown; paces the compositor's frame clock), `colour` the
/// DisplayFormat.
attach_scanout = 8,
/// set_mode(width, height): change the display resolution — only a native backend that
/// reports `canModeSet` honours it; on the GOP floor it fails (docs/display-v2.md V5).
set_mode = 9,
/// get_modes() -> ModesReply: the resolutions the display can switch to (empty on GOP).
get_modes = 10,
};
/// The fixed request header. A `blit_tile`'s pixel payload (width*height 32-bit pixels)
/// follows this header inline in the same message, up to `maximum_payload`.
pub const Request = extern struct {
operation: u32,
layer: u32 = 0, // create/configure/destroy/fill/blit/damage: the target layer
x: u32 = 0,
y: u32 = 0,
/// The answer to `info()`: the display's current mode.
pub const Info = extern struct {
width: u32 = 0,
height: u32 = 0,
z: u32 = 0, // create_layer / configure_layer: stacking order (higher = in front)
colour: u32 = 0, // fill_rect: the fill colour (native pixel value)
visible: u32 = 1, // configure_layer: 0 hides the layer
reserved: u32 = 0,
};
pub const Reply = extern struct {
status: i32, // 0 on success, negative on failure
reserved: u32 = 0,
// info():
width: u32 = 0,
height: u32 = 0,
pitch: u32 = 0,
pitch: u32 = 0, // bytes per row (may exceed width*4)
format: u32 = 0, // a device-abi DisplayFormat value (0 = rgbx, 1 = bgrx)
// create_layer():
layer: u32 = 0,
reserved2: u32 = 0,
};
/// `create_layer(...)`: a new server-owned surface. Coordinates are signed — a layer may sit
/// partly off-screen.
pub const CreateLayer = extern struct {
x: i32,
y: i32,
width: u32,
height: u32,
z: u32 = 0, // stacking order (higher = nearer the front)
visible: u32 = 1,
};
/// The layer a `create_layer` established — the integer later packets put in `Header.target`.
pub const Created = extern struct { layer: u32 };
/// `configure_layer(...)` on `Header.target`: move, restack, show, or hide it.
pub const ConfigureLayer = extern struct {
x: i32,
y: i32,
z: u32 = 0,
visible: u32 = 1, // 0 hides the layer
};
/// `fill_rect(...)` on `Header.target`: fill a layer-local rectangle with a native pixel value.
pub const FillRect = extern struct {
x: i32,
y: i32,
width: u32,
height: u32,
colour: u32,
};
/// `blit_tile(...)` on `Header.target`: copy a `width`×`height` tile of native pixels
/// (row-major, little-endian) into the layer. The pixels ride inline as the packet's tail,
/// up to `maximum_payload`.
pub const BlitTile = extern struct {
x: i32,
y: i32,
width: u32,
height: u32,
};
/// `damage(...)` on `Header.target`: mark a layer-local region dirty for the next present.
pub const Damage = extern struct {
x: i32,
y: i32,
width: u32,
height: u32,
};
/// `attach_scanout(...)` + the shared surface as the call's capability: a native scanout
/// driver announces itself. The compositor maps the surface, opens the driver's
/// `/protocol/scanout` present channel, and upgrades off the GOP floor (docs/display-v2.md
/// V4). Each field says what it is, which the old shared request could not.
pub const AttachScanout = extern struct {
/// The surface's row stride in pixels (it is sized to the driver's largest mode).
stride: u32,
/// The active mode within that surface.
width: u32,
height: u32,
/// A device-abi DisplayFormat value.
format: u32,
/// The panel refresh rate from the driver's EDID read (0 = unknown); it paces the
/// compositor's frame clock.
refresh_hz: u32 = 0,
};
/// `set_mode(width, height)`: change the display resolution — only a native backend that
/// reports `canModeSet` honours it; on the GOP floor it fails (docs/display-v2.md V5).
pub const SetMode = extern struct { width: u32, height: u32 };
/// One selectable display mode.
pub const Mode = extern struct { width: u32, height: u32 };
pub const max_modes = 4;
/// The reply to `get_modes`: a small fixed list of resolutions the display can switch to.
pub const ModesReply = extern struct {
status: i32,
count: u32,
modes: [max_modes]Mode,
/// The answer to `get_modes`: the resolutions the display can switch to (empty on GOP).
pub const Modes = extern struct {
count: u32 = 0,
_padding: u32 = 0,
modes: [max_modes]Mode = @splat(.{ .width = 0, .height = 0 }),
};
pub const modes_reply_size: usize = @sizeOf(ModesReply);
/// The IPC message size — the kernel caps every message at `MESSAGE_MAXIMUM` (256 bytes,
/// system/kernel/ipc-synchronous.zig), so this matches it (a larger receive/reply buffer
/// is rejected with -E2BIG). A `blit_tile` therefore carries only a *small* tile inline —
/// `maximum_payload` bytes = up to 54 pixels, enough for a cursor or small sprite; larger
/// bitmaps are the deferred shared-memory surface path (docs/display.md).
pub const message_maximum: usize = 256;
pub const request_size: usize = @sizeOf(Request);
pub const reply_size: usize = @sizeOf(Reply);
pub const maximum_payload: usize = message_maximum - request_size;
pub const Protocol = envelope.Define(.{
.name = "display",
.version = 1,
.operations = &.{
.{ .name = "info", .reply = Info },
.{ .name = "create_layer", .request = CreateLayer, .reply = Created },
.{ .name = "configure_layer", .request = ConfigureLayer },
.{ .name = "destroy_layer" },
.{ .name = "fill_rect", .request = FillRect },
.{ .name = "blit_tile", .request = BlitTile },
.{ .name = "damage", .request = Damage },
.{ .name = "present" },
.{ .name = "attach_scanout", .request = AttachScanout },
.{ .name = "set_mode", .request = SetMode },
.{ .name = "get_modes", .reply = Modes },
},
});
pub const Operation = Protocol.Operation;
pub const message_maximum: usize = Protocol.message_maximum;
/// The largest inline pixel tile a `blit_tile` may carry: the call floor less the header and
/// this verb's own fixed part — 224 bytes, up to 56 pixels, enough for a cursor or a small
/// sprite. Larger bitmaps are the deferred shared-memory surface path (docs/display.md).
/// Per-verb rather than protocol-wide, because with per-operation requests there is no
/// single "request size" to subtract any more.
pub const maximum_payload: usize = envelope.packet_maximum - envelope.prefix_size - @sizeOf(BlitTile);
/// Pack an 8-bit-per-channel colour into the display's native 32-bit pixel for `format`
/// (a device-abi `DisplayFormat`: 0 = rgbx, 1 = bgrx). Shared so a `colour` in a
@@ -113,3 +157,15 @@ test "pack encodes native byte order for rgbx and bgrx" {
try std.testing.expectEqual(@as(u32, 0x00AA_0000), pack(1, 0xAA, 0, 0));
try std.testing.expectEqual(@as(u32, 0x0000_3020), pack(0, 0x20, 0x30, 0)); // green in byte 1
}
test "the layer rides the header, and the blit tile grew with the split" {
var buffer: [message_maximum]u8 = undefined;
const pixels = [_]u8{0xFF} ** 16;
const packet = Protocol.encodeRequest(.blit_tile, 3, .{ .x = 1, .y = 2, .width = 2, .height = 2 }, &pixels, &buffer).?;
try std.testing.expectEqual(@as(u64, 3), envelope.headerOf(packet).?.target);
try std.testing.expectEqual(@as(i32, 1), Protocol.decodeRequest(.blit_tile, packet).?.x);
try std.testing.expectEqual(@as(usize, 16), Protocol.requestTail(.blit_tile, packet).len);
// 216 bytes under the old 40-byte shared request; the header plus this
// verb's own four fields is 32.
try std.testing.expectEqual(@as(usize, 224), maximum_payload);
}
+50
View File
@@ -72,6 +72,41 @@ pub const operation_subscribe: u32 = 2; // capability = the subscriber's endpoin
pub const operation_unsubscribe: u32 = 3;
pub const first_protocol_operation: u32 = 16;
/// The optional body of a reserved `subscribe`: **which** of a provider's events
/// the subscriber wants, as a bit mask whose meaning the protocol defines (the
/// input service's device classes are the model). A reserved verb carries no
/// typed request, so this rides the packet's tail — and zero, which is also what
/// a subscribe that sent no body at all reads as, means *every* event.
///
/// The mask lives here rather than in each protocol because the subscriber
/// machinery is the service harness's (library/kernel/service.zig): the harness
/// records the number, the protocol decides what its bits mean, and neither has
/// to know the other.
pub const Subscription = extern struct { interest: u32 = 0 };
/// Frame a `subscribe` request. The subscriber's own endpoint travels as the
/// call's *capability*, never in the packet — that is what makes the reverse
/// path unforgeable.
pub fn encodeSubscribe(interest: u32, buffer: []u8) ?[]u8 {
const header = Header{ .operation = operation_subscribe };
const body = Subscription{ .interest = interest };
return frame(std.mem.asBytes(&header), std.mem.asBytes(&body), &.{}, buffer);
}
/// Frame a bare `unsubscribe`: it names no event and no endpoint, because it
/// means "every subscription this task holds here" (one task, one voice).
pub fn encodeUnsubscribe(buffer: []u8) ?[]u8 {
const header = Header{ .operation = operation_unsubscribe };
return frame(std.mem.asBytes(&header), &.{}, &.{}, buffer);
}
/// The interest mask out of a `subscribe` packet's tail, on the provider's side.
/// A caller that sent no mask reads as the every-event mask.
pub fn decodeSubscribe(tail: []const u8) Subscription {
if (tail.len < @sizeOf(Subscription)) return .{};
return std.mem.bytesToValue(Subscription, tail[0..@sizeOf(Subscription)]);
}
/// The `describe` reply's fixed part, followed inline by `name_len` bytes of the
/// protocol's name. This is the version handshake: the version is asked for
/// once, at connect time, rather than re-carried by every packet out of a
@@ -876,6 +911,21 @@ test "a truncated packet answers -EPROTO" {
// operation with `.request = extern struct { bytes: [241]u8 }`, or an event with
// `.payload = extern struct { bytes: [49]u8 }`, fails to compile with the
// protocol, the verb, and the two numbers named in the message.
test "a subscribe carries its interest mask in the reserved verb's tail" {
var buffer: [packet_maximum]u8 = undefined;
const packet = encodeSubscribe(0b101, &buffer).?;
try testing.expectEqual(operation_subscribe, headerOf(packet).?.operation);
try testing.expectEqual(@as(u32, 0b101), decodeSubscribe(packet[prefix_size..]).interest);
// No body at all — and a body too short to be one — read as "every event",
// which is what a subscriber that named nothing wants.
try testing.expectEqual(@as(u32, 0), decodeSubscribe(&.{}).interest);
try testing.expectEqual(@as(u32, 0), decodeSubscribe(&.{ 1, 2 }).interest);
const bare = encodeUnsubscribe(&buffer).?;
try testing.expectEqual(operation_unsubscribe, headerOf(bare).?.operation);
try testing.expectEqual(prefix_size, bare.len);
}
test "the floor counts the header once, and the boundary is exact" {
try testing.expect(fitsPacket(extern struct { bytes: [240]u8 }));
try testing.expect(!fitsPacket(extern struct { bytes: [241]u8 }));
+106 -45
View File
@@ -4,25 +4,30 @@
//! **subscriber** (any program) that subscribes and is then pushed each event.
//!
//! The service handles several device classes over one endpoint. Each class has its own
//! typed event (`KeyEvent`, `MouseEvent`, `JoystickEvent`); they all travel in a common
//! `InputEvent` envelope tagged with a `DeviceKind`, so the fan-out path is one code path
//! and a subscriber can take a mix of devices on a single stream. A subscriber declares
//! which classes it wants with a `device_mask`, and the service routes accordingly.
//! typed event (`KeyEvent`, `MouseEvent`, `JoystickEvent`); a subscriber declares which
//! classes it wants with a `device_mask`, and the service routes accordingly.
//!
//! Two message shapes ride over the endpoint, tagged by `Operation`, like the
//! [VFS protocol](../vfs/protocol.zig):
//! Three shapes ride over the channel, and the envelope names all three
//! (docs/os-development/protocol-namespace.md):
//!
//! - **subscribe / publish**: a synchronous `ipc_call` carrying a `Request`. `subscribe`
//! hands the service the subscriber's own endpoint as a capability (`send_cap`) and a
//! `device_mask`; `publish` carries an `InputEvent`. The reply is a `Reply`.
//! - **delivery**: the service pushes each `InputEvent` to every interested subscriber with
//! the asynchronous `ipc_send` — no reply owed, and a dead subscriber can never stall the
//! broadcast. Received in the subscriber's buffer with `Received.isMessage()` set.
//! - **subscribe** is the *reserved* verb, not one of this protocol's own: its shape — a
//! synchronous call whose attached capability is the subscriber's endpoint — is exactly
//! what `envelope.operation_subscribe` means everywhere. The interest mask travels as the
//! packet's tail (`envelope.Subscription`), because a reserved verb carries no typed
//! request; what this protocol supplies is the *meaning* of its bits — the device classes.
//! - **publish** is this protocol's one verb: a source sends one `InputEvent` and the
//! service answers at once, so publishing never blocks on a slow subscriber.
//! - **delivery** is an event push: the service `ipc_send`s each event to every interested
//! subscriber — no reply owed, so a dead subscriber can never stall the broadcast. The
//! packet is the folded header plus the typed event, and **the device class is the
//! header's operation**: one event per class, so a subscriber reads the kind from the
//! packet rather than from a tag inside the payload.
//!
//! This is a danos-native contract, shared by the input service, the `runtime.input`
//! client helpers, and every source/subscriber. Everything fits one IPC message.
//! `Header.target` is unused (0) in both directions: the service is the only object either
//! side addresses.
const std = @import("std");
const envelope = @import("envelope");
/// The classes of input device the service fans out. Each names a typed event and a bit in
/// the subscription mask.
@@ -242,14 +247,17 @@ pub const JoystickEvent = extern struct {
buttons: u32, // current pressed-button bitmask
};
// --- the common envelope ----------------------------------------------------
// --- the tagged union of the three ------------------------------------------
/// The largest per-device event, so `InputEvent` can hold any of them inline.
pub const max_event_size: usize = @max(@sizeOf(KeyEvent), @max(@sizeOf(MouseEvent), @sizeOf(JoystickEvent)));
/// The tagged envelope broadcast to subscribers: a `DeviceKind` plus the raw bytes of the
/// matching per-device event. Decode it with `asKeyboard`/`asMouse`/`asJoystick` (each
/// returns null unless `device` matches), or build one with the `from*` constructors.
/// One event of any class: a `DeviceKind` plus the raw bytes of the matching per-device
/// event. This is what a source `publish`es (one verb for all three classes) and what a
/// subscriber's helper hands back after decoding a delivery — on the *delivery* wire the
/// class is the packet header's operation instead, so this tag never travels there. Decode
/// it with `asKeyboard`/`asMouse`/`asJoystick` (each returns null unless `device` matches),
/// or build one with the `from*` constructors.
pub const InputEvent = extern struct {
device: u32, // a DeviceKind
_padding: u32 = 0,
@@ -285,35 +293,88 @@ pub const InputEvent = extern struct {
}
};
// --- request / reply --------------------------------------------------------
// --- the contract -----------------------------------------------------------
/// Which side of a request this is.
pub const Operation = enum(u32) {
subscribe = 0, // register the caller's endpoint (send_cap) for the classes in device_mask
publish = 1, // a source submits `event` to broadcast to interested subscribers
};
pub const Protocol = envelope.Define(.{
.name = "input",
.version = 1,
.operations = &.{
// A source submits one event; the service broadcasts it to whoever wants that class.
.{ .name = "publish", .request = InputEvent },
},
.events = &.{
// One per device class: the class is the packet's operation, the typed event its
// payload. The push floor is 64 bytes and the header spends 16 of them, so the
// widest of these — the 28-byte mouse event — leaves the budget with room to spare.
.{ .name = "keyboard", .payload = KeyEvent },
.{ .name = "mouse", .payload = MouseEvent },
.{ .name = "joystick", .payload = JoystickEvent },
},
});
/// Request header. For `subscribe`, `device_mask` is the OR of `device_*` bits the caller
/// wants (0 means all) and the caller's receive endpoint travels as the call's capability;
/// `event` is ignored. For `publish`, `event` is the event to broadcast.
pub const Request = extern struct {
operation: u32, // an Operation
device_mask: u32 = 0, // subscribe: interested device classes (0 => all)
event: InputEvent = .{ .device = 0 },
};
/// Reply header. `status` is 0 on success or a negative errno.
pub const Reply = extern struct {
status: i32,
_padding: u32 = 0,
};
pub const request_size: usize = @sizeOf(Request);
pub const reply_size: usize = @sizeOf(Reply);
pub const Operation = Protocol.Operation;
pub const Event = Protocol.Event;
pub const message_maximum: usize = Protocol.message_maximum;
pub const event_size: usize = @sizeOf(InputEvent);
comptime {
// The delivery path posts a bare InputEvent through ipc_send, so it must fit an
// endpoint's async payload slot (POST_MAXIMUM is 64).
if (event_size > 64) @compileError("InputEvent must fit the ipc_send payload (POST_MAXIMUM)");
/// The event class a `DeviceKind` value (as it appears in `InputEvent.device`) is delivered
/// as. Null for a value no class claims, which is delivered to nobody.
pub fn eventOfDevice(device: u32) ?Event {
return switch (device) {
@intFromEnum(DeviceKind.keyboard) => .keyboard,
@intFromEnum(DeviceKind.mouse) => .mouse,
@intFromEnum(DeviceKind.joystick) => .joystick,
else => null,
};
}
/// Frame a `subscribe` request: the reserved verb's header, then the interest mask. Null if
/// the buffer is too small. The mask itself is the envelope's `Subscription` — the interest
/// a reserved subscribe carries is universal, and the *meaning* of its bits (here: the
/// device classes above) is what each protocol supplies. Kept as a named helper because
/// `device_mask` is what an input caller calls it.
pub fn encodeSubscribe(device_mask: u32, buffer: []u8) ?[]u8 {
return envelope.encodeSubscribe(device_mask, buffer);
}
test "an event of every class fits the push floor, header included" {
// What the hand-rolled comptime assert used to say about `InputEvent`, now
// said by `Define` about each typed event — and counting the header, which
// the old check did not.
try std.testing.expectEqual(envelope.prefix_size + @sizeOf(MouseEvent), Protocol.event_maximum);
try std.testing.expect(Protocol.event_maximum <= envelope.post_maximum);
}
test "the verb numbering, and the class an event carries" {
try std.testing.expectEqual(@as(u32, 16), @intFromEnum(Operation.publish));
// Events number in their own space, so the three classes start at 16 too.
try std.testing.expectEqual(@as(u32, 16), @intFromEnum(Event.keyboard));
try std.testing.expectEqual(@as(u32, 17), @intFromEnum(Event.mouse));
try std.testing.expectEqual(@as(u32, 18), @intFromEnum(Event.joystick));
// subscribe is the RESERVED verb, below the protocol range entirely.
try std.testing.expectEqual(@as(u32, 2), envelope.operation_subscribe);
var buffer: [envelope.post_maximum]u8 = undefined;
const packet = Protocol.encodeEvent(.mouse, 0, .{
.kind = @intFromEnum(MouseEventKind.motion),
.button = 0,
.dx = 3,
.dy = -4,
.scroll_x = 0,
.scroll_y = 0,
.buttons = 0,
}, &buffer).?;
try std.testing.expectEqual(Event.mouse, Protocol.eventOf(packet).?);
try std.testing.expectEqual(@as(i32, -4), Protocol.decodeEvent(.mouse, packet).?.dy);
}
test "a subscribe carries its mask in the tail of the reserved verb" {
var buffer: [envelope.packet_maximum]u8 = undefined;
const packet = encodeSubscribe(device_mouse, &buffer).?;
try std.testing.expectEqual(envelope.operation_subscribe, envelope.headerOf(packet).?.operation);
// The provider side of this is the service harness's, which reads the same
// interest mask out of the tail for every protocol.
try std.testing.expectEqual(device_mouse, envelope.decodeSubscribe(packet[envelope.prefix_size..]).interest);
// A caller that sent nothing at all reads as the every-class mask.
try std.testing.expectEqual(@as(u32, 0), envelope.decodeSubscribe(&.{}).interest);
}
+96 -62
View File
@@ -1,70 +1,104 @@
//! The power protocol (docs/power.md): system power's domain-named surface,
//! bound at `/protocol/power`. On x86 the acpi service provides it; on ARM a
//! PSCI/mailbox service will bind the same name — subscribers never learn which
//! firmware they are on (docs/discovery.md — firmware neutrality), which is the
//! whole point of naming the contract rather than the provider
//! (docs/os-development/protocol-namespace.md).
//! The vfs-protocol pattern: extern-struct messages, a version, reserved fields.
//! The power protocol (docs/os-development/power.md): system power's
//! domain-named surface, bound at `/protocol/power`. On x86 the acpi service
//! provides it; on ARM a PSCI/mailbox service will bind the same name —
//! subscribers never learn which firmware they are on (docs/discovery.md —
//! firmware neutrality), which is the whole point of naming the contract rather
//! than the provider (docs/os-development/protocol-namespace.md).
//!
//! Defined through the envelope, so every packet begins with the folded
//! `Header`. Three shapes ride the channel, and the envelope names all three:
//!
//! - **subscribe** is the *reserved* verb, not one of this protocol's own: a
//! synchronous call whose attached capability is the subscriber's endpoint is
//! exactly what `envelope.operation_subscribe` means everywhere.
//! - **shutdown** is this protocol's one verb — the only operation that *does*
//! something irreversible, and the reason the provider gates it by badge.
//! - **the events** are pushes: the service `ipc_send`s each one to every
//! subscriber, no reply owed, so a slow or dead subscriber can never wedge the
//! source. **The kind is the packet's operation** — one declared event per
//! named kind, exactly as the input protocol delivers one per device class —
//! so a subscriber reads *what happened* out of the header instead of a tag
//! inside the payload. That is what the old `EventMessage`'s two leading bytes
//! (an operation byte saying "this is an event", then the kind) fold into.
//!
//! `Header.target` is unused (0) in both directions: the provider is the only
//! object either side addresses. And no packet carries a version any more — the
//! reserved `describe` verb is the version handshake, asked once at connect time
//! rather than re-carried out of every packet's budget.
/// The protocol version a client states nowhere yet — reserved for the day a
/// handshake needs it; requests carry it so a mismatch can be refused loudly.
pub const version: u16 = 1;
const std = @import("std");
const envelope = @import("envelope");
pub const Operation = enum(u8) {
/// Subscribe to power events: the subscriber's endpoint rides as the
/// call's capability (the input/device-manager pattern); events arrive on
/// it as buffered messages carrying an `EventMessage`.
subscribe = 1,
/// Orderly shutdown's last step: enter S5. Accepted only from PID 1
/// (init) — the process that has already run the stop sequence over
/// everything else.
shutdown = 2,
/// The published event payload (never sent *to* the service).
event = 3,
};
/// What happened. The vocabulary is hardware-neutral: a lid is a lid whether
/// ACPI or a PSCI mailbox reported it.
pub const Event = enum(u8) {
power_button = 1,
lid = 2,
ac = 3,
battery = 4,
/// A device notification that maps to none of the named events — the
/// `code` and `hid` fields say which device and what code.
notify = 5,
};
pub const Subscribe = extern struct {
operation: u8 = @intFromEnum(Operation.subscribe),
reserved0: u8 = 0,
version: u16 = version,
reserved1: u32 = 0,
};
pub const Shutdown = extern struct {
operation: u8 = @intFromEnum(Operation.shutdown),
reserved0: u8 = 0,
version: u16 = version,
reserved1: u32 = 0,
};
/// A published event, as the buffered-message payload subscribers receive.
pub const EventMessage = extern struct {
operation: u8 = @intFromEnum(Operation.event),
/// An Event value.
event: u8,
reserved0: u16 = 0,
/// The device notification code (Notify's second argument), or 0.
/// What a published event carries beyond its kind. The kind is the packet's
/// operation, so nothing here repeats it; `power_button`, `lid`, `ac` and
/// `battery` leave both fields zero and are fully described by the verb alone.
pub const Notice = extern struct {
/// The device notification code (ACPI `Notify`'s second argument), or 0.
code: u32 = 0,
/// The notifying device's hardware id (EISA-decoded), or all zero.
hid: [8]u8 = .{0} ** 8,
};
pub const Reply = extern struct {
status: i32,
reserved: u32 = 0,
};
pub const Protocol = envelope.Define(.{
.name = "power",
.version = 1,
.operations = &.{
// Orderly shutdown's last step: enter S5. Honored only from a
// subscriber — init, the process that has already run the stop sequence
// over everything else (docs/os-development/power.md, "authority, not
// information"). Nothing to say and nothing to answer, so the verb and
// the reply's `Status` are the whole exchange.
.{ .name = "shutdown" },
},
.events = &.{
// The vocabulary is hardware-neutral: a lid is a lid whether ACPI or a
// PSCI mailbox reported it. One event per kind, each carrying the same
// `Notice`, because what differs between them is which thing happened —
// and that is the header's job now.
.{ .name = "power_button", .payload = Notice },
.{ .name = "lid", .payload = Notice },
.{ .name = "ac", .payload = Notice },
.{ .name = "battery", .payload = Notice },
// A device notification that maps to none of the named events — the
// `code` and `hid` say which device and what happened.
.{ .name = "notify", .payload = Notice },
},
});
/// Upper bound on any message in this protocol — sizes endpoint buffers.
pub const message_maximum = 64;
pub const Operation = Protocol.Operation;
/// What happened. The event *is* the kind: this is the generated event
/// enumeration, re-exported under the name this protocol has always called its
/// vocabulary, with the same members it has always had.
pub const Event = Protocol.Event;
/// What a provider and a subscriber size their buffers to. This module used to
/// declare 64 — the *push* floor — which was simply wrong for a protocol whose
/// requests ride `ipc_call`: a provider sizing its receive buffer to 64 refuses
/// any caller that sends up to the floor it is entitled to.
pub const message_maximum: usize = Protocol.message_maximum;
test "the kind is the verb, and an event fits the push floor" {
try std.testing.expectEqual(@as(u32, 16), @intFromEnum(Operation.shutdown));
try std.testing.expectEqual(@as(u32, 16), @intFromEnum(Event.power_button));
try std.testing.expectEqual(@as(u32, 17), @intFromEnum(Event.lid));
try std.testing.expectEqual(@as(u32, 18), @intFromEnum(Event.ac));
try std.testing.expectEqual(@as(u32, 19), @intFromEnum(Event.battery));
try std.testing.expectEqual(@as(u32, 20), @intFromEnum(Event.notify));
// subscribe is the RESERVED verb, below the protocol range entirely.
try std.testing.expectEqual(@as(u32, 2), envelope.operation_subscribe);
try std.testing.expectEqual(envelope.prefix_size + @sizeOf(Notice), Protocol.event_maximum);
try std.testing.expect(Protocol.event_maximum <= envelope.post_maximum);
// The call floor, not the push floor: `shutdown` is a synchronous call.
try std.testing.expectEqual(envelope.packet_maximum, message_maximum);
}
test "a pushed event names its kind in the header" {
var buffer: [envelope.post_maximum]u8 = undefined;
const packet = Protocol.encodeEvent(.power_button, 0, .{}, &buffer).?;
try std.testing.expectEqual(Event.power_button, Protocol.eventOf(packet).?);
const notified = Protocol.encodeEvent(.notify, 0, .{ .code = 0x80, .hid = "PNP0C0A\x00".* }, &buffer).?;
try std.testing.expectEqual(Event.notify, Protocol.eventOf(notified).?);
try std.testing.expectEqual(@as(u32, 0x80), Protocol.decodeEvent(.notify, notified).?.code);
}
+39 -33
View File
@@ -1,49 +1,55 @@
//! The scanout wire protocol — what the compositor says to a native scanout driver (e.g.
//! virtio-gpu) over its well-known `.scanout` endpoint to put a composited frame on screen.
//! The driver owns the panel and the shared scanout surface it handed the compositor (via the
//! display service's `attach_scanout`); the compositor composites into that surface, then asks
//! the driver to present a damaged rectangle. Tiny by design — one present request. Separate
//! from the display protocol because the directions differ: clients call the compositor over
//! `.display`; the compositor calls the driver over `.scanout`. See docs/display-v2.md.
//! virtio-gpu) over `/protocol/scanout` to put a composited frame on screen. The driver owns
//! the panel and the shared scanout surface it handed the compositor (via the display
//! service's `attach_scanout`); the compositor composites into that surface, then asks the
//! driver to present a damaged rectangle. Tiny by design — one present request. Separate from
//! the display protocol because the directions differ: clients call the compositor over
//! `/protocol/display`; the compositor calls the driver over `/protocol/scanout`. See
//! docs/display-v2.md.
//!
//! One scanout per driver instance, so `Header.target` is always 0.
const std = @import("std");
const envelope = @import("envelope");
pub const Operation = enum(u32) {
/// present(x, y, width, height): put the given rectangle of the shared scanout surface on
/// the panel (on virtio-gpu: transfer-to-host of the region, then a fenced resource flush).
present = 0,
/// get_modes() -> ModesReply: the display modes this scanout can switch to (V5).
get_modes = 1,
/// set_mode(width, height): change the scanout resolution — the shared surface is sized to
/// the largest mode, so this just re-points the scanout rectangle; the surface is unchanged.
set_mode = 2,
};
pub const Request = extern struct {
operation: u32,
/// `present(rect)`: put the given rectangle of the shared scanout surface on the panel (on
/// virtio-gpu: transfer-to-host of the region, then a fenced resource flush).
pub const Present = extern struct {
x: u32 = 0,
y: u32 = 0,
width: u32 = 0,
height: u32 = 0,
};
pub const Reply = extern struct {
status: i32, // 0 on success, negative on failure
reserved: u32 = 0,
};
/// `set_mode(width, height)`: change the scanout resolution — the shared surface is sized to
/// the largest mode, so this just re-points the scanout rectangle; the surface is unchanged.
pub const SetMode = extern struct { width: u32, height: u32 };
/// One offered display mode.
pub const Mode = extern struct { width: u32, height: u32 };
pub const max_modes = 4;
/// The reply to `get_modes`: a small fixed list of modes.
pub const ModesReply = extern struct {
status: i32,
count: u32,
modes: [max_modes]Mode,
/// The answer to `get_modes`: a small fixed list of modes. The success/failure verdict is
/// the reply's `Status`, so this carries only the modes.
pub const Modes = extern struct {
count: u32 = 0,
_padding: u32 = 0,
modes: [max_modes]Mode = @splat(.{ .width = 0, .height = 0 }),
};
pub const message_maximum: usize = 64;
pub const request_size: usize = @sizeOf(Request);
pub const reply_size: usize = @sizeOf(Reply);
pub const modes_reply_size: usize = @sizeOf(ModesReply);
pub const Protocol = envelope.Define(.{
.name = "scanout",
.version = 1,
.operations = &.{
.{ .name = "present", .request = Present },
.{ .name = "get_modes", .reply = Modes },
.{ .name = "set_mode", .request = SetMode },
},
});
pub const Operation = Protocol.Operation;
/// The call floor, like every synchronous protocol. This module used to declare
/// 64 — the *push* floor — which was simply wrong: nothing here is pushed, and a
/// provider sizing its receive buffer to 64 refuses (`-E2BIG`) any caller that
/// sends up to the floor it is entitled to.
pub const message_maximum: usize = Protocol.message_maximum;
@@ -1,57 +1,66 @@
//! The USB transfer protocol: what a USB class driver (a keyboard, mouse, or
//! mass-storage driver) says to the xHCI bus driver over its well-known
//! `.usb_bus` endpoint to drive its device. The class driver owns no hardware —
//! it reaches its device entirely through these messages, the way a PS/2 keyboard
//! driver reaches the 8042 through the ps2-bus. Extern-struct messages tagged by
//! `Operation`, the vfs-protocol / device-manager-protocol pattern.
//! mass-storage driver) says to the xHCI bus driver over `/protocol/usb-transfer`
//! to drive its device. The class driver owns no hardware — it reaches its device
//! entirely through these packets, the way a PS/2 keyboard driver reaches the
//! 8042 through the ps2-bus.
//!
//! Defined through the envelope (docs/os-development/protocol-namespace.md), so
//! every packet begins with the folded `Header`. **`Header.target` is the device
//! token** — the per-open handle the bus driver hands back, which every request
//! but `open` addressed through a `device_token` field of its own before the
//! rebase. `open` itself addresses the *assigned device id*, because that is what
//! the caller has before there is a token.
//!
//! The shape:
//! - **open** (a capability-passing `ipc.callCap`): the class driver hands over
//! its own endpoint (for asynchronous interrupt reports) and its assigned
//! device id, and receives a `device_token` plus its interface's endpoints.
//! - **control / bulk** (synchronous `ipc.call`): one transfer, answered when
//! it completes. Control data travels inline (descriptors, HID/MSC class
//! requests are all small); bulk data travels by **physical address** — the
//! class driver's own `dma_alloc`'d buffer — so a 512-byte sector never has
//! to cross the 256-byte IPC boundary.
//! - **open** (a capability-passing call): the class driver hands over its own
//! endpoint (for asynchronous interrupt reports); the target is its assigned
//! device id, and the reply carries a `device_token` plus its interface's
//! endpoints.
//! - **control / bulk** (synchronous calls): one transfer, answered when it
//! completes. Control data travels **in the packet's tail** in both
//! directions (descriptors, HID/MSC class requests are all small), so the
//! fixed parts stay tiny and `Status.len` is the transferred length — the
//! envelope's own field for "how many bytes follow", which is precisely what
//! the old `actual_length` said. Bulk data travels by **physical address** —
//! the class driver's own `dma_alloc`'d buffer — so a 512-byte sector never
//! has to cross the packet floor.
//! - **interrupt_subscribe** (synchronous): arm periodic IN polling of an
//! interrupt endpoint; each report the device produces is then pushed to the
//! class driver's endpoint as an asynchronous `InterruptReport` (`ipc.send`),
//! exactly how the input service delivers events.
//! class driver's endpoint as an asynchronous `interrupt_report` event.
//! It stays one of **this protocol's own verbs**, not the reserved
//! `subscribe`: the reserved verb means "push me this provider's events" and
//! carries the subscriber's endpoint, while this names one endpoint address
//! on one device and a poll length, and the endpoint it pushes to was handed
//! over at `open`. Same word, different contract.
//! - **dma_attach**: a class driver hands the controller a DMA-region
//! capability (riding the call's cap slot) so the controller binds that
//! buffer into its IOMMU domain and may then DMA to the physical addresses
//! inside it. Needed once per buffer the class driver will name in a `bulk`
//! transfer (its own, or one forwarded to it).
//!
//! Single controller assumption: one `.usb_bus` singleton serves QEMU's one xHCI.
//! A multi-controller machine would need a per-controller endpoint (the device
//! manager handing each class driver the right one); noted, not built.
//! Single controller assumption: one provider serves QEMU's one xHCI. A
//! multi-controller machine would need the controller in the target (or the
//! spawner wiring each class driver its own channel); noted, not built.
/// Fits one synchronous IPC message (kernel MESSAGE_MAXIMUM).
pub const message_maximum: usize = 256;
const std = @import("std");
const envelope = @import("envelope");
/// The largest inline control-transfer payload. Sized so a whole message
/// (header + data) stays under `message_maximum`: descriptors and HID/MSC class
/// requests are all far smaller.
pub const max_inline_data: usize = 200;
/// The largest control-transfer data stage. It rides the packet's tail, so the
/// bound is the call floor less the header and the fixed request part — derived
/// rather than declared, which is what keeps it honest when a field moves.
pub const max_inline_data: usize = envelope.packet_maximum - envelope.prefix_size - @sizeOf(Control);
/// The largest interrupt report pushed asynchronously. Sized so `InterruptReport`
/// fits an `ipc_send` payload slot (POST_MAXIMUM = 64): boot keyboard reports are
/// 8 bytes, boot mouse reports 3–4.
pub const max_report_data: usize = 48;
/// The largest interrupt report pushed asynchronously. An event packet is the
/// header plus the payload within 64 bytes, so this is what is left after the
/// report's own four bytes of framing: boot keyboard reports are 8 bytes, boot
/// mouse reports 3–4, and the whole HID boot vocabulary fits many times over.
/// A device that produces more has its report truncated, never split.
pub const max_report_data: usize = 40;
/// Endpoints per interface reported back in an open reply (a boot HID interface
/// has one interrupt endpoint, a mass-storage interface two bulk endpoints).
pub const max_reported_endpoints: usize = 4;
pub const Operation = enum(u32) {
open = 0,
control = 1,
interrupt_subscribe = 2,
bulk = 3,
/// dma_attach: a class driver hands the controller a DMA-region capability (riding
/// the call's cap slot) so the controller binds that buffer into its IOMMU domain
/// and may then DMA to the physical addresses inside it. Needed once per buffer the
/// class driver will name in a `bulk` transfer (its own, or one forwarded to it).
dma_attach = 4,
};
/// The endpoint facts a class driver needs, lifted from the endpoint descriptor
/// the bus driver already parsed during enumeration.
pub const Endpoint = extern struct {
@@ -64,114 +73,146 @@ pub const Endpoint = extern struct {
reserved: [3]u8 = .{ 0, 0, 0 },
};
/// open: the class driver's receive endpoint rides as the call's capability, and
/// `device_id` is the interface's assigned id (its argv[1]).
pub const OpenRequest = extern struct {
operation: u32 = @intFromEnum(Operation.open),
reserved: u32 = 0,
device_id: u64,
};
// --- the per-operation request and reply parts ------------------------------
//
// Each names the bytes AFTER the prefix. Nothing here carries an operation or a
// device token: those are the packet header's, folded in once. No reply carries
// a status either — that is the `Status` every reply begins with.
/// The answer to open: a token scoping every later request to this device, the
/// interface's class triple (a sanity check), and its endpoints.
pub const OpenReply = extern struct {
status: i32,
endpoint_count: u32,
/// The answer to `open`: the token every later packet puts in `Header.target`,
/// the interface's class triple (a sanity check), and its endpoints.
pub const Opened = extern struct {
device_token: u64,
endpoint_count: u32,
interface_class: u8,
interface_subclass: u8,
interface_protocol: u8,
interface_number: u8,
reserved2: u32 = 0,
endpoints: [max_reported_endpoints]Endpoint = [_]Endpoint{.{ .address = 0, .transfer_type = 0, .max_packet_size = 0, .interval = 0 }} ** max_reported_endpoints,
};
/// control: one EP0 control transfer. `setup` is a bit-cast `usb_abi.Request`.
/// For an OUT transfer `data[0..data_length]` is sent; for an IN transfer the
/// reply carries up to `data_length` bytes back.
pub const ControlRequest = extern struct {
operation: u32 = @intFromEnum(Operation.control),
reserved: u32 = 0,
device_token: u64,
/// `control`: one EP0 control transfer on `Header.target`. `setup` is a bit-cast
/// `usb_abi.Request`. For an OUT transfer the data stage is the request's tail;
/// for an IN transfer it comes back as the reply's tail, and `Status.len` is how
/// much of it arrived.
pub const Control = extern struct {
setup: [8]u8,
direction_in: u8, // 1 = device-to-host (IN), 0 = host-to-device (OUT)
reserved2: u8 = 0,
/// 1 = device-to-host (IN), 0 = host-to-device (OUT).
direction_in: u8,
_padding: u8 = 0,
/// Bytes of data stage: what an IN transfer asks for, and what an OUT
/// transfer's tail carries.
data_length: u16,
reserved3: u32 = 0,
data: [max_inline_data]u8 = [_]u8{0} ** max_inline_data,
_padding2: u32 = 0,
};
pub const ControlReply = extern struct {
status: i32, // 0 success, negative on failure/stall
actual_length: u32,
data: [max_inline_data]u8 = [_]u8{0} ** max_inline_data,
};
/// interrupt_subscribe: begin periodic IN polling of an interrupt endpoint. Each
/// report the device returns is pushed to the caller's endpoint (handed over at
/// open) as an asynchronous `InterruptReport`.
pub const InterruptSubscribeRequest = extern struct {
operation: u32 = @intFromEnum(Operation.interrupt_subscribe),
reserved: u32 = 0,
device_token: u64,
/// `interrupt_subscribe`: begin periodic IN polling of an interrupt endpoint of
/// `Header.target`. Each report the device returns is pushed to the endpoint the
/// caller handed over at `open`, as an `interrupt_report` event.
pub const InterruptSubscribe = extern struct {
endpoint_address: u8,
reserved2: u8 = 0,
max_length: u16, // bytes to request per poll (the endpoint's max packet size)
_padding: u8 = 0,
/// Bytes to request per poll (the endpoint's max packet size).
max_length: u16,
};
pub const InterruptSubscribeReply = extern struct {
status: i32,
reserved: u32 = 0,
};
/// bulk: one bulk IN or OUT transfer. `physical_address` is the class driver's own
/// `dma_alloc`'d buffer — the controller DMAs straight to/from it, so the bulk
/// data never crosses IPC. `endpoint_address`'s bit 7 selects IN vs OUT.
pub const BulkRequest = extern struct {
operation: u32 = @intFromEnum(Operation.bulk),
reserved: u32 = 0,
device_token: u64,
/// `bulk`: one bulk IN or OUT transfer on `Header.target`. `physical_address` is
/// the class driver's own `dma_alloc`'d buffer — the controller DMAs straight
/// to/from it, so the bulk data never crosses IPC. `endpoint_address`'s bit 7
/// selects IN vs OUT.
pub const Bulk = extern struct {
physical_address: u64,
length: u32,
endpoint_address: u8,
reserved2: u8 = 0,
reserved3: u16 = 0,
_padding: u8 = 0,
_padding2: u16 = 0,
};
pub const BulkReply = extern struct {
status: i32,
actual_length: u32,
};
/// How many bytes a bulk transfer actually moved. It cannot ride `Status.len`
/// the way a control transfer's does: nothing follows a bulk reply, because the
/// data went to the caller's DMA buffer rather than into the packet.
pub const Transferred = extern struct { actual_length: u32 };
/// dma_attach: the region capability rides the call's cap slot; the body only carries
/// the device token (scoping) so the controller knows which caller is attaching.
pub const DmaAttachRequest = extern struct {
operation: u32 = @intFromEnum(Operation.dma_attach),
reserved: u32 = 0,
device_token: u64,
};
pub const DmaAttachReply = extern struct {
status: i32,
reserved: u32 = 0,
};
/// An asynchronous interrupt report, pushed with `ipc.send` to a subscriber's
/// endpoint. `Received.isMessage()` is set; there is no reply owed.
/// One asynchronous interrupt report, pushed to the endpoint the class driver
/// handed over at `open`. The device it came from is `Header.target`.
pub const InterruptReport = extern struct {
device_token: u64,
endpoint_address: u8,
length: u8,
reserved: u16 = 0,
_padding: u16 = 0,
data: [max_report_data]u8 = [_]u8{0} ** max_report_data,
};
comptime {
const std = @import("std");
// Every synchronous message must fit one IPC message; the async report must
// fit an ipc_send payload slot.
std.debug.assert(@sizeOf(ControlRequest) <= message_maximum);
std.debug.assert(@sizeOf(ControlReply) <= message_maximum);
std.debug.assert(@sizeOf(OpenReply) <= message_maximum);
std.debug.assert(@sizeOf(InterruptReport) <= 64);
pub const Protocol = envelope.Define(.{
.name = "usb-transfer",
.version = 1,
.operations = &.{
// open: the target is the interface's assigned device id (its argv[1]),
// and the class driver's receive endpoint rides as the capability.
.{ .name = "open", .reply = Opened },
.{ .name = "control", .request = Control },
.{ .name = "interrupt_subscribe", .request = InterruptSubscribe },
.{ .name = "bulk", .request = Bulk, .reply = Transferred },
// dma_attach: the region capability rides the call's cap slot; the
// target says which caller's device is attaching, so there is nothing
// left for a body to carry.
.{ .name = "dma_attach" },
},
.events = &.{
.{ .name = "interrupt_report", .payload = InterruptReport },
},
});
pub const Operation = Protocol.Operation;
pub const Event = Protocol.Event;
/// What both sides size their buffers to — the call floor, as every protocol does.
pub const message_maximum: usize = Protocol.message_maximum;
test "the budgets, re-verified by Define rather than by hand" {
// What the hand-rolled comptime asserts used to say, now said by `Define`
// — and counting the header, which the old checks did not.
try std.testing.expectEqual(@as(usize, 224), max_inline_data);
try std.testing.expect(Protocol.request_maximum <= envelope.packet_maximum);
try std.testing.expect(Protocol.reply_maximum <= envelope.packet_maximum);
// The report was 48 bytes of data in a 64-byte struct that had no room left
// for a header. Folding the device token into the target and trimming the
// data to 40 leaves the whole packet at 60 of the 64-byte push floor.
try std.testing.expectEqual(@as(usize, 44), @sizeOf(InterruptReport));
try std.testing.expectEqual(@as(usize, 60), Protocol.event_maximum);
try std.testing.expect(Protocol.event_maximum <= envelope.post_maximum);
}
test "the verb numbering, and the device token in the header" {
try std.testing.expectEqual(@as(u32, 16), @intFromEnum(Operation.open));
try std.testing.expectEqual(@as(u32, 17), @intFromEnum(Operation.control));
try std.testing.expectEqual(@as(u32, 18), @intFromEnum(Operation.interrupt_subscribe));
try std.testing.expectEqual(@as(u32, 19), @intFromEnum(Operation.bulk));
try std.testing.expectEqual(@as(u32, 20), @intFromEnum(Operation.dma_attach));
try std.testing.expectEqual(@as(u32, 16), @intFromEnum(Event.interrupt_report));
var buffer: [message_maximum]u8 = undefined;
const packet = Protocol.encodeRequest(.control, 9, .{
.setup = .{ 0, 6, 0, 1, 0, 0, 18, 0 },
.direction_in = 1,
.data_length = 18,
}, &.{}, &buffer).?;
try std.testing.expectEqual(@as(u64, 9), envelope.headerOf(packet).?.target);
try std.testing.expectEqual(@as(u16, 18), Protocol.decodeRequest(.control, packet).?.data_length);
}
test "a control OUT carries its data stage as the packet's tail" {
var buffer: [message_maximum]u8 = undefined;
const payload = [_]u8{ 1, 2, 3, 4 };
const packet = Protocol.encodeRequest(.control, 5, .{
.setup = .{ 0x21, 11, 0, 0, 0, 0, 4, 0 },
.direction_in = 0,
.data_length = payload.len,
}, &payload, &buffer).?;
try std.testing.expectEqualSlices(u8, &payload, Protocol.requestTail(.control, packet));
// And the answer to an IN: the bytes follow the (empty) fixed reply part,
// with `Status.len` counting exactly them.
const answered = Protocol.encodeReply(.control, 0, {}, &payload, &buffer).?;
try std.testing.expectEqual(@as(u32, payload.len), envelope.statusOf(answered).?.len);
try std.testing.expectEqualSlices(u8, &payload, Protocol.replyTail(.control, answered));
}
+134 -85
View File
@@ -1,52 +1,27 @@
//! The VFS wire protocol — the message format spoken between a client (via the file
//! API) and the user-space VFS server over IPC. A request is a fixed `Request` header
//! followed by an inline payload (a path, or write bytes); a reply is a fixed `Reply`
//! header followed by an inline payload (read bytes, or a FileStatus). Everything fits
//! in one IPC message (<= ipc MESSAGE_MAXIMUM = 256 bytes).
//! The VFS wire protocol — what a client (through the file API,
//! library/kernel/file-system.zig) says to a filesystem backend over IPC. Defined
//! through the envelope (docs/os-development/protocol-namespace.md), so every
//! packet begins with the folded `Header`: the verb in `Header.operation`, and
//! **the open node id in `Header.target`** — the field that used to be
//! `Request.node`. A path appears in the conversation once, at `open`; every
//! packet after it addresses that integer.
//!
//! This is a danos-native contract, so it uses danos names throughout. The client
//! side is `runtime.fs` (library/runtime/fs.zig), which programs use directly.
//! This is a danos-native contract, so it uses danos names throughout. It is
//! user-space only — the kernel knows nothing of files or paths; it only routes
//! (`fs_resolve`) and moves the bytes. The backends that serve it today are the
//! FAT server (system/services/fat/) and the protocol registry inside PID 1
//! (system/services/init/), which is a *synthetic* backend: `/protocol` holds
//! contracts rather than files.
//!
//! This is user-space only — the kernel knows nothing of files or paths; it only moves the bytes.
//! Shared by library/runtime/fs.zig (the client) and the mount backends that serve it (today
//! the fat server, system/services/fat/). The standalone user-space VFS server it was first
//! written against has retired — path routing moved into the kernel (system/kernel/vfs.zig,
//! fs_resolve) — but the protocol module outlived it.
//! **An `open` reply may carry a capability.** The vfs `open` request rides
//! **An `open` reply may carry a capability.** The `open` request rides
//! `ipc_call`, and the reply direction of a call can hand back an endpoint
//! (`ipc.callCap`'s `Reply.cap`). A file backend never uses it — FAT answers
//! with a node id and nothing else — but a *synthetic* backend does: opening a
//! (`ipc.callCap`'s `Reply.cap`). A file backend never uses it — FAT answers with
//! a node id and nothing else — but the registry does: opening a
//! `NodeKind.protocol` node under `/protocol` returns the provider's endpoint,
//! which is the channel (docs/os-development/protocol-namespace.md). The
//! convention is per-backend, not per-operation: a client that did not ask a
//! synthetic backend simply gets no capability back, exactly as today.
//! which is the channel. The convention is per-backend, not per-operation: a
//! client that did not ask a synthetic backend simply gets no capability back.
pub const Operation = enum(u32) {
open, // open(path) -> node id (a synthetic backend may reply with a capability instead)
close, // close(node)
read, // read(node, offset, len) -> bytes
write, // write(node, offset, bytes) -> count
status, // status(node) -> FileStatus
// Appended for the mount router (M5). Values stay stable, so existing clients
// and the flat-ramfs tests are unaffected.
readdir, // readdir(dir_node, cursor=offset) -> one DirectoryEntry (len==0 => EOF)
mount, // mount(prefix payload, capability = backend endpoint)
unmount, // unmount(prefix payload)
// Appended for filesystem mutation (Phase 2). Path-based (the path is the
// payload); a mounted backend handles them, the flat ramfs refuses them.
mkdir, // mkdir(path payload) -> status
unlink, // unlink(path payload) -> status
// rename: the payload is the old path, a single 0x00 separator, then the new
// path. Same-directory rename only (the router requires both under one mount).
rename, // rename(old\0new payload) -> status
// Appended for the protocol namespace (P2). The registry is a synthetic
// backend mounted at /protocol: `open` establishes a channel and `readdir`
// lists the bound names like any directory, so those two verbs need nothing
// new — but *claiming* a name does. A file backend refuses it, alongside the
// router verbs it does not implement either; only the registry implements it.
bind, // bind(name payload, capability = the provider's endpoint) -> status
};
const envelope = @import("envelope");
/// The type of a filesystem node, aligned to the node-kind table
/// (docs/file-system-development/file-system-hierarchy.md). Fills `FileStatus.kind` and
@@ -67,38 +42,18 @@ pub const NodeKind = enum(u32) {
protocol = 7,
};
/// One directory entry, returned by `readdir`: a fixed header followed inline in
/// the reply payload by `name_len` bytes of name. A zero-length reply is EOF.
/// One directory entry: the fixed part of a `readdir` reply, followed inline by
/// `name_len` bytes of name. **A zero `name_len` is end of directory** — the
/// reply's own length cannot say so any more, because the envelope always sends
/// the fixed part.
pub const DirectoryEntry = extern struct {
kind: u32, // a NodeKind
name_len: u32,
size: u64,
kind: u32 = 0, // a NodeKind
name_len: u32 = 0,
size: u64 = 0,
};
pub const directory_entry_size: usize = @sizeOf(DirectoryEntry);
/// Request header. `node` is the server-side open-file id (from a prior open);
/// for `open` the path is the payload and `len` is its length. `offset`/`len`
/// carry the read/write position and count.
pub const Request = extern struct {
operation: Operation,
node: u64,
offset: u64,
len: u32,
flags: u32,
};
/// Reply header. `status` is 0 on success or a negative errno; `node` is the new
/// open-file id (for `open`); `len` is the payload length (bytes read, or the
/// FileStatus size).
pub const Reply = extern struct {
status: i32,
_padding: u32 = 0,
node: u64 = 0,
len: u32 = 0,
_padding2: u32 = 0,
};
/// A file's metadata (the danos-native answer to a `status` request). The POSIX
/// layer maps this onto `struct stat`.
pub const FileStatus = extern struct {
@@ -110,13 +65,84 @@ pub const FileStatus = extern struct {
mtime: u64 = 0,
};
pub const message_maximum: usize = 256;
pub const request_size: usize = @sizeOf(Request);
pub const reply_size: usize = @sizeOf(Reply);
/// Largest inline payload that still fits one IPC message alongside a header.
pub const maximum_payload: usize = message_maximum - request_size;
// --- the per-operation request and reply parts ------------------------------
//
// Each names the bytes AFTER the prefix. Nothing here carries an operation or a
// node id: those are the packet header's, folded in once.
/// Open flags (danos-native; `runtime.fs.OpenOptions` maps its booleans onto these).
/// `open(flags)` with the path as the packet's tail. The one verb that spends a
/// path; everything after it addresses the node id this returns.
pub const Open = extern struct { flags: u32 = 0 };
/// The node id an `open` established — the integer every later packet puts in
/// `Header.target`. Meaningful only between this client and this backend.
pub const Opened = extern struct { node: u64 };
/// `read(offset, len)` on `Header.target`; the bytes come back as the reply tail.
pub const Read = extern struct {
offset: u64,
len: u32,
_padding: u32 = 0,
};
/// `write(offset, len)` on `Header.target`, with the data as the packet's tail.
pub const Write = extern struct {
offset: u64,
len: u32,
_padding: u32 = 0,
};
/// How many bytes a `write` actually took — it may be short.
pub const Written = extern struct { count: u32 };
/// `readdir(cursor)` on `Header.target`: one entry per call, cursor-advanced.
pub const Readdir = extern struct { cursor: u64 };
/// The contract, whole. Verbs number from `envelope.first_protocol_operation`
/// (16) in this order; the reserved verbs below it mean what they mean
/// everywhere. `readdir` stays a protocol verb rather than folding into the
/// reserved `enumerate`: it enumerates the children of one *node*, where
/// `enumerate` names a provider's targets.
pub const Protocol = envelope.Define(.{
.name = "vfs",
.version = 1,
.operations = &.{
.{ .name = "open", .request = Open, .reply = Opened },
.{ .name = "close" },
.{ .name = "read", .request = Read },
.{ .name = "write", .request = Write, .reply = Written },
.{ .name = "status", .reply = FileStatus },
.{ .name = "readdir", .request = Readdir, .reply = DirectoryEntry },
// The mount router's two verbs. Path routing lives in the kernel now
// (system/kernel/vfs.zig), so no backend implements either; they keep
// their numbers so the vocabulary stays the one docs/vfs-protocol.md
// describes.
.{ .name = "mount" }, // tail = the prefix, capability = the backend's endpoint
.{ .name = "unmount" }, // tail = the prefix
// Filesystem mutation, path-based: the path is the packet's tail.
.{ .name = "mkdir" },
.{ .name = "unlink" },
// rename: the tail is the old path, a single 0x00 separator, then the
// new path. Same-directory rename only.
.{ .name = "rename" },
// The registry's claim verb (P2): the name is the tail and the
// provider's endpoint rides the call as its capability. A file backend
// refuses it; only init implements it.
.{ .name = "bind" },
},
});
pub const Operation = Protocol.Operation;
/// What a backend sizes its buffers to — the call floor, as every protocol does.
pub const message_maximum: usize = Protocol.message_maximum;
/// The most inline payload any request may carry: the floor less the header and
/// the widest fixed request part, so one bound serves every verb (a path, write
/// data, a read's answer).
pub const maximum_payload: usize = envelope.packet_maximum - Protocol.request_maximum;
/// Open flags (danos-native; `file_system.OpenOptions` maps its booleans onto these).
pub const create: u32 = 1;
/// Open a directory (for readdir) rather than a file. A mounted backend uses
/// this to open a directory node; the flat ramfs ignores it.
@@ -126,7 +152,7 @@ pub const directory: u32 = 2;
/// backend frees the old cluster chain; the flat ramfs ignores it.
pub const truncate: u32 = 4;
test "protocol struct sizes and node kinds" {
test "the stable wire values: node kinds, entry layout, and the verb numbering" {
const std = @import("std");
try std.testing.expectEqual(@as(u32, 0), @intFromEnum(NodeKind.regular));
try std.testing.expectEqual(@as(u32, 1), @intFromEnum(NodeKind.directory));
@@ -134,11 +160,34 @@ test "protocol struct sizes and node kinds" {
try std.testing.expectEqual(@as(u32, 6), @intFromEnum(NodeKind.socket));
try std.testing.expectEqual(@as(u32, 7), @intFromEnum(NodeKind.protocol));
try std.testing.expectEqual(@as(usize, 16), @sizeOf(DirectoryEntry));
// The appended operations keep the original values.
try std.testing.expectEqual(@as(u32, 0), @intFromEnum(Operation.open));
try std.testing.expectEqual(@as(u32, 4), @intFromEnum(Operation.status));
try std.testing.expectEqual(@as(u32, 5), @intFromEnum(Operation.readdir));
try std.testing.expectEqual(@as(u32, 10), @intFromEnum(Operation.rename));
// The registry's claim verb, appended last with the protocol namespace.
try std.testing.expectEqual(@as(u32, 11), @intFromEnum(Operation.bind));
// The numbering the envelope gives this protocol. These are NEW values: the
// rebase moved every verb above the reserved range, so the old 0..11 are
// gone and 16..27 are what the wire carries. Pinned because both sides of a
// flag-day have to agree on them, not because they may never change again.
try std.testing.expectEqual(@as(u32, 16), @intFromEnum(Operation.open));
try std.testing.expectEqual(@as(u32, 17), @intFromEnum(Operation.close));
try std.testing.expectEqual(@as(u32, 18), @intFromEnum(Operation.read));
try std.testing.expectEqual(@as(u32, 19), @intFromEnum(Operation.write));
try std.testing.expectEqual(@as(u32, 20), @intFromEnum(Operation.status));
try std.testing.expectEqual(@as(u32, 21), @intFromEnum(Operation.readdir));
try std.testing.expectEqual(@as(u32, 26), @intFromEnum(Operation.rename));
try std.testing.expectEqual(@as(u32, 27), @intFromEnum(Operation.bind));
// The payload bound is what it always was, arrived at the other way round:
// the header plus the widest fixed request part is 32 bytes of the floor.
try std.testing.expectEqual(@as(usize, 224), maximum_payload);
}
test "the node id rides the header, and a path rides the tail" {
const std = @import("std");
var buffer: [message_maximum]u8 = undefined;
const opening = Protocol.encodeRequest(.open, 0, .{ .flags = create }, "/a/b", &buffer).?;
try std.testing.expectEqual(@as(u32, create), Protocol.decodeRequest(.open, opening).?.flags);
try std.testing.expectEqualStrings("/a/b", Protocol.requestTail(.open, opening));
try std.testing.expectEqual(@as(u64, 0), envelope.headerOf(opening).?.target);
const reading = Protocol.encodeRequest(.read, 7, .{ .offset = 512, .len = 64 }, &.{}, &buffer).?;
try std.testing.expectEqual(@as(u64, 7), envelope.headerOf(reading).?.target);
try std.testing.expectEqual(@as(u64, 512), Protocol.decodeRequest(.read, reading).?.offset);
}
+52 -5
View File
@@ -43,12 +43,12 @@ pub const SystemCall = enum(u64) {
ipc_call = 9, // ipc_call(h, message, len, reply, cap) -> reply_len: send + block for reply
ipc_reply_wait = 10, // ipc_reply_wait(h, reply, len, receive, cap) -> receive_len (+badge in rdx)
device_enumerate = 11, // device_enumerate(buffer, maximum) -> count: snapshot the device table
device_claim = 12, // device_claim(id) -> ok: take exclusive ownership of a device
device_claim = 12, // device_claim(id) -> 0/-errno: take exclusive ownership of a device (-ENODEV no such id, -EBUSY someone owns it, -ECONFINE the IOMMU would not confine it)
mmio_map = 13, // mmio_map(id, resource_index) -> virtual_address: map a claimed device's MMIO into this address space
irq_bind = 14, // irq_bind(id, resource_index, endpoint): deliver a device IRQ as an IPC notification
irq_ack = 15, // irq_ack(id, resource_index): re-arm a bound IRQ after servicing it
device_register = 16, // device_register(parent_id, descriptor) -> id: publish a child of a device you claimed
system_spawn = 17, // system_spawn(name_ptr, name_len, arguments_ptr, arguments_len, exit_endpoint) -> child process id: start a named initial-ramdisk binary as a new ring-3 process
device_register = 16, // device_register(parent_id, descriptor) -> id/-errno: publish a child of a device you claimed (-ENOSPC table full, -ECHILDREN parent full, -ERANGE resource escapes the parent, -ENODEV/-EPERM bad parent, -E2BIG too many resources)
system_spawn = 17, // system_spawn(name_ptr, name_len, arguments_ptr, arguments_len, exit_endpoint, device) -> child process id: start a named initial-ramdisk binary as a new ring-3 process. `device` (or `no_device`) is a device the caller holds and gives to the child, atomically — the child never runs without it
dma_alloc = 18, // dma_alloc(len, flags) -> virtual_address (rax), physical_address (rdx): contiguous, pinned, uncacheable DMA memory
dma_free = 19, // dma_free(virtual_address, len) -> 0: release a prior dma_alloc
msi_bind = 20, // msi_bind(device_id, endpoint) -> address (rax), data (rdx): a per-device MSI vector for a claimed device
@@ -85,9 +85,53 @@ pub const SystemCall = enum(u64) {
dma_bind = 51, // dma_bind(device_id, region_handle) -> 0/-errno: map a DMA-region capability into the claimed device's IOMMU domain (idempotent). The caller must own the device and hold the handle
dma_unbind = 52, // dma_unbind(device_id, region_handle) -> 0/-errno: unmap a previously bound region from the device's domain and invalidate
handle_close = 53, // handle_close(handle) -> 0/-errno: drop one capability handle and free its table slot (endpoints, shared-memory, DMA regions)
device_transfer = 54, // device_transfer(device_id, task_id) -> 0/-errno: give a device you hold to another task. A MOVE, not a copy — a claim is exclusive (-ENODEV no such device, -EPERM you do not hold it, -ESRCH no such task)
_,
};
/// **The errno space** — the one vocabulary of refusal, returned as `-value` in the
/// system_call result register and echoed by user-space providers in a reply status.
/// Canonical here because it crosses the kernel↔user boundary in both directions:
/// the kernel restates these in system/kernel/ipc-synchronous.zig, and the envelope
/// restates the provider-facing subset in library/protocol/envelope/envelope.zig
/// (which cannot import this module — the `protocol` package deliberately has no
/// dependencies, so a comptime cross-check in library/device/driver/driver.zig and
/// system/kernel/tests.zig holds the two halves together).
///
/// The rule these serve: **a refusal must say which rule refused it.** A caller that
/// gets one number for five different reasons cannot report, retry or route around
/// any of them — see docs/fixed-bounds-audit.md, where a bare -1 turned "this bus is
/// at its child cap" into a machine that booted with no USB and no storage, and cost
/// a debugging session to tell apart from four other causes.
///
/// Values are stable: `failed()` in the runtime treats the top 4096 return values as
/// errors (the Linux convention), so anything here must stay well inside 1..4095.
pub const EBADF: i64 = 1; // bad handle
pub const E2BIG: i64 = 2; // argument exceeds its maximum (a message, a descriptor's resource count)
pub const EFAULT: i64 = 3; // buffer unmapped / outside the user half
pub const ENOENT: i64 = 4; // no such name
pub const ENOSPC: i64 = 5; // a kernel table is full (handles, devices)
pub const ENOMEM: i64 = 6; // out of memory
pub const EPEER: i64 = 7; // peer died before replying (its process exited or was killed)
pub const ESRCH: i64 = 8; // no such process (process_kill of an unknown/dead id)
pub const EPERM: i64 = 9; // not permitted (the caller is not the owner/supervisor)
pub const ENOSYS: i64 = 10; // this protocol has no such operation
pub const EPROTO: i64 = 11; // malformed packet: shorter than the verb it names
pub const EBUSY: i64 = 12; // the thing asked for is held by someone still alive
pub const ENODEV: i64 = 13; // no such device id
pub const ECHILDREN: i64 = 14; // this parent already holds as many children as it can
pub const ERANGE: i64 = 15; // a resource escapes the window it must fall inside
pub const ECONFINE: i64 = 16; // the device could not be placed under IOMMU translation
/// The highest errno defined above. A cheap guard for anyone switching over the
/// space, and the number to bump when adding one.
pub const errno_maximum: i64 = 16;
/// `system_spawn`'s `device` argument when the child is given no device — every
/// caller but the device manager. Matches `device-manager-protocol.no_device`, which
/// is the same sentinel one layer up.
pub const no_device: u64 = ~@as(u64, 0);
/// `futex_wait` return codes (in rax).
pub const futex_woken: u64 = 0; // woken by a futex_wake
pub const futex_mismatch: u64 = 1; // *addr != expected on entry; the caller did not block
@@ -252,8 +296,11 @@ pub const klog_maximum_message: usize = 256;
pub const fs_route_kernel: u64 = 0; // rdx = node token; serve via fs_node
pub const fs_route_backend: u64 = 1; // rdx = endpoint handle; speak vfs-protocol
/// fs_node operations — the same numbers as the vfs-protocol Operation enum, so
/// client code shares one vocabulary.
/// fs_node operations. These were once the vfs-protocol Operation numbers; the
/// rebase onto the envelope moved every protocol verb above the reserved range
/// (16 and up), and these did not follow — they are a *syscall* selector, not a
/// packet's verb, and renumbering a kernel ABI to track a wire format would be
/// coupling in the wrong direction. The two vocabularies are simply separate now.
pub const fs_node_read: u64 = 2;
pub const fs_node_status: u64 = 4;
pub const fs_node_readdir: u64 = 5;
+30 -10
View File
@@ -63,9 +63,11 @@
/system/services/discovery, /system/services/device-manager, bind, power
# --- the drivers, which the device manager spawns ---------------------------
# usb-transfer and block have NO bind rows: several processes provide each (one
# per controller, one per volume), so neither is ever a registry name —
# consumers get their provider's channel from the device manager's hello,
# routed by lineage (communication.md "Establishment: two planes").
/system/drivers/ps2-bus, /system/services/device-manager, bind, ps2-bus
/system/drivers/usb-xhci-bus, /system/services/device-manager, bind, usb-transfer
/system/drivers/usb-storage, /system/services/device-manager, bind, block
/system/drivers/virtio-gpu, /system/services/device-manager, bind, scanout
# --- the same providers when the kernel test harness starts them directly ---
@@ -92,11 +94,12 @@
# ============================================================================
# --- init's own services ----------------------------------------------------
# fat reaches the block device behind the volume it mounts; the compositor
# reaches the scanout its driver announced, its own endpoint (the mouse-listener
# thread opens /protocol/display like any other client — threads share no
# handles), and the input stream that moves the cursor.
/system/services/fat, /system/services/init, open, block
# fat reaches the device manager to be routed to its volume's block provider
# (block is not a name — see the bind section); the compositor reaches the
# scanout its driver announced, its own endpoint (the mouse-listener thread
# opens /protocol/display like any other client — threads share no handles),
# and the input stream that moves the cursor.
/system/services/fat, /system/services/init, open, device-manager
/system/services/display, /system/services/init, open, scanout
/system/services/display, /system/services/init, open, display
/system/services/display, /system/services/init, open, input
@@ -116,10 +119,7 @@
# to the compositor.
/system/drivers/*, /system/services/device-manager, open, device-manager
/system/services/discovery, /system/services/device-manager, open, device-manager
/system/drivers/usb-storage, /system/services/device-manager, open, usb-transfer
/system/drivers/usb-hid-keyboard, /system/services/device-manager, open, usb-transfer
/system/drivers/usb-hid-keyboard, /system/services/device-manager, open, input
/system/drivers/usb-hid-mouse, /system/services/device-manager, open, usb-transfer
/system/drivers/usb-hid-mouse, /system/services/device-manager, open, input
/system/drivers/virtio-gpu, /system/services/device-manager, open, display
@@ -148,6 +148,26 @@
/test/system/services/input-source, kernel, open, input
/test/system/services/input-test, kernel, open, input
# The guessable-id probe (test/system/services/badge-scope-test) runs as two
# processes of one binary: the owner, which the scenario spawns, and the intruder,
# which the owner spawns with the ids it holds. Both reach the compositor — the
# owner to create the layer, the intruder to be refused it — so the binary is
# named twice, once per supervisor. The second row needs no 'supervise'
# delegation: the owner was spawned by the KERNEL, which is a chain init can
# vouch for on its own.
/test/system/services/badge-scope-test, kernel, open, display
/test/system/services/badge-scope-test, /test/*, open, display
# The conformance probe (test/system/services/protocol-conformance-test) asks
# every provider its boot bound for the envelope's reserved verbs. It reaches
# ONLY the two contracts its own scenario boots a provider for, named one at a
# time exactly like the two rows above — no subtree, no wildcard. Everything else
# under /protocol stays absent for it, which is the point: the fixture walks the
# namespace listing and reports what it could not open rather than being handed
# the tree to make the test look broad.
/test/system/services/protocol-conformance-test, kernel, open, input
/test/system/services/protocol-conformance-test, kernel, open, display
# The laundering-deputy probe (test/system/services/protocol-registry-test) runs
# a grandchild whose supervisor is a fixture nobody authorized — that is the
# point of it, and its bind must stay refused. It still has to report the verdict
Can't render this file because it contains an unexpected character in line 12 and column 15.
+37 -16
View File
@@ -44,6 +44,10 @@ var ecam_physical: u64 = 0;
var start_bus: u64 = 0;
var bus_count: u64 = 0;
var manager_handle: ipc.Handle = 0;
/// Functions this scan discovered but could not publish. Counted so the end of the
/// scan can reconcile "found" against "registered" — a scan that silently returns a
/// subset of the machine is the failure this driver is most able to hide.
var refused: u32 = 0;
/// One aligned 32-bit read from a function's configuration space.
fn configRead(bus: u64, dev: u64, function: u64, offset: u64) u32 {
@@ -71,13 +75,22 @@ fn configWrite16(bus: u64, dev: u64, function: u64, offset: u64, value: u16) voi
configWrite(bus, dev, function, aligned, (word & ~mask) | (@as(u32, value) << shift));
}
/// Claim the bridge, map the ECAM, hello the manager, then scan.
/// Hello the manager (which is where the bridge arrives), map the ECAM, then scan.
fn initialise(endpoint: ipc.Handle) bool {
_ = endpoint;
if (!device.claim(bridge_id)) {
std.log.info("unable to claim bridge device {d}", .{bridge_id});
// **The handshake first, because it is where the device arrives.** This driver
// used to claim `bridge_id` here — first-come-first-served, so the manager's
// matching was advisory and any process could have claimed the bridge by naming
// the same id. The manager now holds it and transfers it in the hello reply
// (docs/os-development/device-authority.md). `hello` is synchronous, so the
// transfer has completed by the time this returns.
//
// Keep the manager handle to report children through; a supervised bus that
// cannot reach its manager has nothing to serve.
manager_handle = device_manager.hello(.bus, bridge_id) orelse {
std.log.info("no hello with the device manager; bridge {d} not delegated", .{bridge_id});
return false;
}
};
const buffer = memory.allocator().alloc(device.DeviceDescriptor, 64) catch {
_ = logging.write("/system/drivers/pci-bus: out of memory\n");
return false;
@@ -109,11 +122,6 @@ fn initialise(endpoint: ipc.Handle) bool {
return false;
};
// The handshake (role: bus — we enumerate PCI and report the functions we
// find), then the scan. Keep the manager handle to report children through;
// a supervised bus that cannot reach its manager has nothing to serve.
manager_handle = device_manager.hello(.bus, bridge_id) orelse return false;
scan();
return true;
}
@@ -141,7 +149,13 @@ fn scan() void {
}
}
}
std.log.info("{d} functions found", .{found});
// Reconcile: "found" alone reads as success even when most of the machine was
// refused. If the two disagree, say so at a level that survives a scrollback.
if (refused == 0) {
std.log.info("{d} functions found, all registered", .{found});
} else {
std.log.warn("{d} functions found, {d} REFUSED — {d} registered", .{ found, refused, found - refused });
}
}
/// Register one function under the bridge and report it to the manager. The
@@ -225,22 +239,29 @@ fn registerAndReport(bus: u64, dev: u64, function: u64, class_triple: u32) void
// subsystem are read. Every discovered function is logged, matched or not.
logFunction(bus, dev, function, class_triple, descriptor.vendor, descriptor.device, descriptor.subsystem);
const registered = device.register(bridge_id, &descriptor) orelse {
std.log.info("register refused for {d}:{d}.{d}", .{ bus, dev, function });
// Name the rule that refused. `ParentFull` and `TableFull` are different ceilings
// with different fixes, and `NotContained` is not a ceiling at all — it means the
// BAR escaped the bridge's own window (docs/fixed-bounds-audit.md).
const registered = device.register(bridge_id, &descriptor) catch |e| {
refused += 1;
std.log.warn("register refused for {d}:{d}.{d}: {s}", .{ bus, dev, function, @errorName(e) });
return;
};
const report = device_manager_protocol.ChildAdded{
// The registered device id is the packet's target — the manager's object
// addressing — so the report body carries only where on the bus it sits and
// what it is.
var packet: [device_manager_protocol.message_maximum]u8 = undefined;
const framed = device_manager_protocol.Protocol.encodeRequest(.child_added, registered, .{
.bus = @intFromEnum(device_manager_protocol.BusKind.pci),
.parent = bridge_id,
.bus_address = (bus << 8) | (dev << 3) | function,
.identity = class_triple,
.device_id = registered,
.vendor = descriptor.vendor,
.device = descriptor.device,
.subsystem = descriptor.subsystem,
};
}, &.{}, &packet) orelse return;
var reply: [device_manager_protocol.message_maximum]u8 = undefined;
_ = ipc.call(manager_handle, std.mem.asBytes(&report), &reply) catch {
_ = ipc.call(manager_handle, framed, &reply) catch {
std.log.info("child report for {d}:{d}.{d} failed", .{ bus, dev, function });
};
}
+12 -6
View File
@@ -114,10 +114,9 @@ pub fn main() void {
_ = logging.write("/system/drivers/ps2-bus: found PS/2 controller\n");
_ = logging.write("/system/drivers/ps2-bus: initializing controller\n");
if (!device.claim(controller_device_descriptor.id)) {
_ = logging.write("/system/drivers/ps2-bus: unable to claim controller \n");
return;
}
// The controller node arrived with the spawn — the manager holds the hardware
// and names it in the call that creates this process
// (docs/os-development/device-authority.md). Nothing to claim.
const controller = ps2.Controller.init(controller_device_descriptor) orelse {
_ = logging.write("/system/drivers/ps2-bus: controller is missing its IO ports\n");
@@ -255,14 +254,21 @@ pub fn main() void {
if (port_device_types[@intFromEnum(ps2.Port.two)] != null) {
if (ps2.findMouseDescriptor(buffer)) |descriptor| {
if (findInterruptResourceIndex(descriptor)) |auxiliary_index| {
if (device.claim(descriptor.id) and device.irqBind(descriptor.id, auxiliary_index, endpoint)) {
// The mouse node is a *second* device for this one instance — the
// 8042 is one controller with two ports, so it cannot be split across
// two processes. It is transferred to us after the spawn, which is
// safe because we only reach it here, long after the controller
// handshakes and identify. irq_bind is the proof we hold it: it is
// gated on ownership, so a failure here means the handover has not
// landed rather than a hardware problem.
if (device.irqBind(descriptor.id, auxiliary_index, endpoint)) {
maybe_auxiliary_interrupt = .{
.device_id = descriptor.id,
.interrupt_index = auxiliary_index,
.gsi = descriptor.resources[auxiliary_index].start,
};
} else {
_ = logging.write("/system/drivers/ps2-bus: auxiliary irq_bind failed\n");
_ = logging.write("/system/drivers/ps2-bus: auxiliary irq_bind failed (mouse node not delegated?)\n");
}
}
}
+8 -6
View File
@@ -75,9 +75,10 @@ pub fn main(init: process.Init) void {
};
const layout = xkb.byName(init.arguments.get(2) orelse "us") orelse xkb.us;
// Hello the manager first (meet the spawn deadline), then open the device.
if (device_manager.hello(.device, device_id) == null) return;
var device = usb.open(device_id) orelse {
// The hello both meets the spawn deadline and brings back the channel to
// THIS device's controller — routed by lineage, never found by name.
const bus = device_manager.helloForChannel(.device, device_id, null) orelse return;
var device = usb.open(bus, device_id) orelse {
std.log.info("could not open device {d}", .{device_id});
return;
};
@@ -112,9 +113,10 @@ pub fn main(init: process.Init) void {
if (signals.has(.terminate)) return;
continue;
}
if (!got.isMessage() or got.len < @sizeOf(usb.InterruptReport)) continue;
const message = std.mem.bytesToValue(usb.InterruptReport, receive[0..@sizeOf(usb.InterruptReport)]);
if (!got.isMessage()) continue;
// An `interrupt_report` event packet: the verb in its folded header, the
// report after it. Anything else on this endpoint is not ours.
const message = usb.reportOf(receive[0..got.len]) orelse continue;
if (message.length < @sizeOf(hid.KeyboardReport)) continue;
const report = std.mem.bytesToValue(hid.KeyboardReport, message.data[0..@sizeOf(hid.KeyboardReport)]);
const transitions = decoder.feed(report);
+8 -5
View File
@@ -41,8 +41,10 @@ pub fn main(init: process.Init) void {
return;
};
if (device_manager.hello(.device, device_id) == null) return;
var device = usb.open(device_id) orelse {
// The hello both meets the spawn deadline and brings back the channel to
// THIS device's controller — routed by lineage, never found by name.
const bus = device_manager.helloForChannel(.device, device_id, null) orelse return;
var device = usb.open(bus, device_id) orelse {
std.log.info("could not open device {d}", .{device_id});
return;
};
@@ -74,9 +76,10 @@ pub fn main(init: process.Init) void {
if (signals.has(.terminate)) return;
continue;
}
if (!got.isMessage() or got.len < @sizeOf(usb.InterruptReport)) continue;
const message = std.mem.bytesToValue(usb.InterruptReport, receive[0..@sizeOf(usb.InterruptReport)]);
if (!got.isMessage()) continue;
// An `interrupt_report` event packet: the verb in its folded header, the
// report after it. Anything else on this endpoint is not ours.
const message = usb.reportOf(receive[0..got.len]) orelse continue;
const length = @min(message.length, message.data.len);
const report = hid.parseMouse(message.data[0..length]) orelse continue;
const mask = buttonMask(report.buttons);
+2 -2
View File
@@ -10,8 +10,8 @@ pub fn build(b: *std.Build) void {
.name = "usb-storage",
.root_source_file = b.path("usb-storage.zig"),
.imports = &.{
"block-protocol", "driver", "ipc", "logging", "memory", "process", "service",
"time", "usb",
"block-protocol", "driver", "envelope", "ipc", "logging", "memory", "process",
"service", "time", "usb",
},
});
b.installArtifact(exe);
+76 -49
View File
@@ -22,8 +22,16 @@ const logging = @import("logging");
const usb = @import("usb");
const scsi = @import("scsi.zig");
const bot = @import("bulk-only-transport.zig");
const envelope = @import("envelope");
const block_protocol = @import("block-protocol");
/// The generated block dispatch. One device per process, so the handler context
/// is empty and the geometry stays in this file's globals.
const Serve = block_protocol.Protocol.Provider(void);
const Invocation = envelope.Invocation;
const Answer = envelope.Answer;
var device_id: u64 = 0;
var device: usb.Device = undefined;
var bulk_in: usb.Endpoint = undefined;
@@ -74,9 +82,14 @@ fn transact(cdb: []const u8, direction_in: bool, data_physical: u64, data_length
var bring_up_failed = false;
fn initialise(endpoint: ipc.Handle) bool {
_ = endpoint;
if (device_manager.hello(.device, device_id) == null) return false;
device = usb.open(device_id) orelse {
// One hello, both directions: the block-serving endpoint goes UP (the
// manager routes fat's consumer hello here — this driver serves one
// volume, one process per stick, so `block` is never a registry name),
// and the channel to THIS device's controller comes DOWN, routed by
// lineage. A second stick used to die silently on the exclusive bind;
// now every instance is reachable through its lineage.
const bus = device_manager.helloForChannel(.device, device_id, endpoint) orelse return false;
device = usb.open(bus, device_id) orelse {
std.log.info("could not open device {d}", .{device_id});
return false;
};
@@ -144,53 +157,65 @@ fn initialise(endpoint: ipc.Handle) bool {
return true;
}
/// Serve the block protocol: geometry, and whole-block read/write to/from the
/// caller's DMA buffer (named by physical address).
fn onMessage(message: []const u8, reply: []u8, sender: u32, arrived: *ipc.Arrival) usize {
_ = sender;
if (message.len < block_protocol.request_size) return 0;
const request = std.mem.bytesToValue(block_protocol.Request, message[0..block_protocol.request_size]);
switch (request.operation) {
@intFromEnum(block_protocol.Operation.attach) => {
// The filesystem's DMA buffer: forward its capability to the controller
// so the device can reach it. Never claimed — the binding holds its own
// reference, so our copy is the turn's to close, on this path and on the
// refusal above it alike.
const handle = arrived.peek() orelse return writeReply(reply, .{ .status = -1, .block_size = 0, .block_count = 0 });
const ok = device.attachDma(handle);
return writeReply(reply, .{ .status = if (ok) 0 else -1, .block_size = 0, .block_count = 0 });
},
@intFromEnum(block_protocol.Operation.geometry) => {
return writeReply(reply, .{ .status = 0, .block_size = block_size, .block_count = block_count });
},
@intFromEnum(block_protocol.Operation.read) => {
const count: u16 = @intCast(request.count);
const cdb = scsi.read10(@intCast(request.lba), count);
const ok = transact(&cdb, true, request.physical, request.count * block_size);
return writeReply(reply, .{ .status = if (ok) 0 else -1, .block_size = block_size, .block_count = if (ok) request.count else 0 });
},
@intFromEnum(block_protocol.Operation.write) => {
const count: u16 = @intCast(request.count);
const cdb = scsi.write10(@intCast(request.lba), count);
const ok = transact(&cdb, false, request.physical, request.count * block_size);
return writeReply(reply, .{ .status = if (ok) 0 else -1, .block_size = block_size, .block_count = if (ok) request.count else 0 });
},
@intFromEnum(block_protocol.Operation.flush) => {
// SYNCHRONIZE CACHE: commit the device's write cache to flash. No data
// stage. Makes prior writes durable before a caller (init at shutdown)
// cuts power. A device without a volatile cache reports success anyway.
const cdb = scsi.synchronizeCache10();
const ok = transact(&cdb, false, 0, 0);
return writeReply(reply, .{ .status = if (ok) 0 else -1, .block_size = block_size, .block_count = 0 });
},
else => return 0,
}
// --- serving the block protocol ---------------------------------------------
//
// Geometry, and whole-block read/write to and from the caller's DMA buffer
// (named by physical address). One device per process, so `Header.target` is
// always 0 and no handler reads it.
/// A transfer the device refused. Every failure here is the same one — the SCSI
/// command did not complete — so there is one errno for all of them.
const refused: isize = -envelope.ENOENT;
fn onGeometry(_: void, _: Invocation(void), answer: Answer(block_protocol.Geometry)) isize {
answer.set(.{ .block_size = block_size, .block_count = block_count });
return 0;
}
fn writeReply(reply: []u8, value: block_protocol.Reply) usize {
const bytes = std.mem.asBytes(&value);
@memcpy(reply[0..bytes.len], bytes);
return bytes.len;
fn onRead(_: void, invocation: Invocation(block_protocol.Transfer), answer: Answer(block_protocol.Transferred)) isize {
const request = invocation.request;
const cdb = scsi.read10(@intCast(request.lba), @intCast(request.count));
if (!transact(&cdb, true, request.physical, request.count * block_size)) return refused;
answer.set(.{ .count = request.count });
return 0;
}
fn onWrite(_: void, invocation: Invocation(block_protocol.Transfer), answer: Answer(block_protocol.Transferred)) isize {
const request = invocation.request;
const cdb = scsi.write10(@intCast(request.lba), @intCast(request.count));
if (!transact(&cdb, false, request.physical, request.count * block_size)) return refused;
answer.set(.{ .count = request.count });
return 0;
}
/// SYNCHRONIZE CACHE: commit the device's write cache to flash. No data stage.
/// Makes prior writes durable before a caller (init at shutdown) cuts power. A
/// device without a volatile cache reports success anyway.
fn onFlush(_: void, _: Invocation(void), _: Answer(void)) isize {
const cdb = scsi.synchronizeCache10();
return if (transact(&cdb, false, 0, 0)) 0 else refused;
}
/// The filesystem's DMA buffer: forward its capability to the controller so the
/// device can reach it. Never claimed — the binding holds its own reference, so
/// our copy is the turn's to close, on this path and on the refusal alike.
fn onAttach(_: void, invocation: Invocation(void), _: Answer(void)) isize {
const handle = invocation.capability orelse return -envelope.EPROTO;
return if (device.attachDma(handle)) 0 else refused;
}
const handlers = Serve.Handlers{
.geometry = onGeometry,
.read = onRead,
.write = onWrite,
.flush = onFlush,
.attach = onAttach,
};
fn onMessage(message: []const u8, reply: []u8, sender: u32, arrived: *ipc.Arrival) usize {
// Peeked, never taken: `attach` forwards the capability and the controller's
// binding takes its own reference, so this copy stays the turn's to close.
return Serve.dispatch({}, handlers, message, sender, arrived.peek(), reply);
}
pub fn main(init: process.Init) void {
@@ -202,8 +227,10 @@ pub fn main(init: process.Init) void {
std.log.info("malformed device id '{s}'", .{argument});
return;
};
// No `.service` name: several instances provide the block contract (one
// per stick), so consumers are routed here by the device manager's
// lineage, never by a registry bind — the endpoint goes up in the hello.
service.run(block_protocol.message_maximum, .{
.service = "block",
.init = initialise,
.on_message = onMessage,
});
+4 -4
View File
@@ -10,10 +10,10 @@ pub fn build(b: *std.Build) void {
.name = "usb-xhci-bus",
.root_source_file = b.path("usb-xhci-bus.zig"),
.imports = &.{
"channel", "device-manager-protocol", "driver", "input-client",
"ipc", "logging", "memory", "mmio",
"pci", "process", "service", "time",
"usb-abi", "usb-ids", "usb-transfer-protocol",
"device-manager-protocol", "driver", "envelope", "ipc",
"logging", "memory", "mmio", "pci",
"process", "service", "time", "usb-abi",
"usb-ids", "usb-transfer-protocol",
},
});
b.installArtifact(exe);
+236 -141
View File
@@ -15,16 +15,15 @@
const std = @import("std");
const device = @import("driver");
const channel = @import("channel");
const ipc = @import("ipc");
const process = @import("process");
const service = @import("service");
const time = @import("time");
const input = @import("input-client");
const device_manager = @import("driver");
const memory = @import("memory");
const logging = @import("logging");
const device_manager_protocol = @import("device-manager-protocol");
const envelope = @import("envelope");
const usb_ids = @import("usb-ids");
const usb_abi = @import("usb-abi");
const usb_transfer_protocol = @import("usb-transfer-protocol");
@@ -60,22 +59,33 @@ fn timerInterval() u64 {
return if (msi_vector != null) reconcile_interval_ms else poll_interval_ms;
}
/// The class driver endpoints that opened each device, so interrupt reports can
/// be pushed back to them. Keyed by the device token (the interface's device id).
/// The class driver that opened each device: the endpoint interrupt reports are
/// pushed back to, and **the task that opened it** — the kernel-stamped badge, so
/// a device token is scoped to the client that was given it. Keyed by the device
/// token (the interface's device id).
///
/// The scoping is the point (docs/os-development/protocol-namespace.md: handles
/// are validated against the badge). A token is a small registered-device id any
/// process could name, and every packet that carries one used to be honoured from
/// anyone: a stranger could run control transfers on another driver's device, arm
/// interrupt polling on it, or redirect its reports.
const Open = struct {
used: bool = false,
device_token: u64 = 0,
owner: u32 = 0,
report_endpoint: usize = 0,
};
var opens = [_]Open{.{}} ** 16;
/// Remember (or replace) the endpoint that reports for `device_token`. Returns
/// whether the table kept the handle — false means the caller still owns it and
/// must dispose of it. A re-open supersedes the previous endpoint, and the one
/// it displaced is closed here: the table holds exactly one reference per slot.
fn recordOpen(device_token: u64, report_endpoint: usize) bool {
/// Remember (or replace) the endpoint task `owner` receives reports for
/// `device_token` on. Returns whether the table kept the handle — false means the
/// caller still owns it and must dispose of it. A re-open by the **same** client
/// supersedes its previous endpoint, and the one it displaced is closed here: the
/// table holds exactly one reference per slot.
fn recordOpen(device_token: u64, owner: u32, report_endpoint: usize) bool {
for (&opens) |*open| {
if (open.used and open.device_token == device_token) {
if (open.owner != owner) return false; // someone else's device; nothing kept
if (open.report_endpoint != report_endpoint) _ = ipc.close(open.report_endpoint);
open.report_endpoint = report_endpoint;
return true;
@@ -83,13 +93,33 @@ fn recordOpen(device_token: u64, report_endpoint: usize) bool {
}
for (&opens) |*open| {
if (!open.used) {
open.* = .{ .used = true, .device_token = device_token, .report_endpoint = report_endpoint };
open.* = .{ .used = true, .device_token = device_token, .owner = owner, .report_endpoint = report_endpoint };
return true;
}
}
return false; // table full: not kept
}
/// Whether `device_token` is open to task `owner`. An open device belonging to
/// someone else answers exactly as one that was never opened, so a prober cannot
/// tell another driver's device from an absent one.
fn openedBy(device_token: u64, owner: u32) bool {
for (&opens) |*open| {
if (open.used and open.device_token == device_token) return open.owner == owner;
}
return false;
}
/// Whether `device_token` is open at all. Asked only after `openedBy` has said
/// the caller is not the holder, so an answer of true means *someone else* holds
/// it — one device, one class driver.
fn heldByAnother(device_token: u64) bool {
for (&opens) |*open| {
if (open.used and open.device_token == device_token) return true;
}
return false;
}
fn reportEndpointFor(device_token: u64) ?usize {
for (&opens) |*open| {
if (open.used and open.device_token == device_token) return open.report_endpoint;
@@ -97,6 +127,23 @@ fn reportEndpointFor(device_token: u64) ?usize {
return null;
}
/// Release every device a dead client held: its slot, and the report endpoint
/// capability in it. Driven by published process exits — the same sweep idiom the
/// FAT server uses for open files and the harness uses for subscribers — which is
/// also what lets a restarted class driver re-open the device its predecessor had.
fn releaseOpensOf(dead: u32) void {
for (&opens) |*open| {
if (open.used and open.owner == dead) {
// The engine first: it holds this endpoint's handle number per
// subscription, and the close below frees that number for reuse.
if (controller) |*engine| engine.releaseSubscriptions(open.device_token);
_ = ipc.close(open.report_endpoint);
std.log.info("released device {d} for dead client {d}", .{ open.device_token, dead });
open.* = .{};
}
}
}
var controller_id: u64 = device_manager_protocol.no_device;
/// Claim the assigned controller, find its register window, and hello the
@@ -104,26 +151,32 @@ var controller_id: u64 = device_manager_protocol.no_device;
/// manager reads as "meant to stop" — a missing assignment is not a crash loop.
fn initialise(endpoint: ipc.Handle) bool {
service_endpoint = endpoint;
// Device tokens are per-client state, so this driver needs deaths for the
// same reason the FAT server does: a class driver that crashes must not keep
// its device open, or its restarted instance could never claim it back.
_ = process.subscribeExits(endpoint);
// The transfer contract, bound by hand rather than through the harness's
// `.service`, because **losing it is not fatal here**. One machine can carry
// several xHCI controllers and the driver model spawns one process per
// controller, so several processes provide the same contract for different
// hardware — and `/protocol` holds exactly one name, deliberately (addressing
// lives inside the protocol, never in the path). Whoever binds first is the
// one clients reach by name; a later instance still owns its controller,
// enumerates its bus, and reports its children to the device manager, so it
// keeps running. **Known gap:** a class driver behind a second controller
// cannot reach it — the transfer protocol has no controller field for
// `target`, and the fix is either one process multiplexing every controller
// or the spawner wiring the child's channel (P5), not a second name.
if (!channel.bindPatiently("usb-transfer", endpoint))
_ = logging.write("/system/drivers/usb-xhci-bus: /protocol/usb-transfer is another controller's; serving mine unnamed\n");
if (!device.claim(controller_id)) {
std.log.info("unable to claim controller device {d}", .{controller_id});
// **The handshake comes first, because it is where everything moves.** The
// manager holds the controller and transfers it in `onHello`, so by the time
// this call returns the device is ours and nothing else could have taken it
// (docs/os-development/device-authority.md). And the serving endpoint rides
// up with the same call: one machine can carry several xHCI controllers, one
// process per controller, so the transfer contract is never a registry name
// — `/protocol` holds no instances, deliberately. Class drivers reach *this*
// controller because the manager answers their hellos with this endpoint,
// routed by lineage (communication.md "Establishment: two planes"). The bind
// race this replaces left every device behind a losing controller
// unreachable — a real machine's mouse, "could not open device 50".
//
// `hello` is synchronous, so the transfer has completed before the reply lands —
// there is no window between being told yes and holding the thing.
//
// Keep the handle: the tick's hot-plug dispatch reports through it.
const exchanged = device_manager.helloExchange(.bus, controller_id, endpoint, false) orelse {
std.log.warn("no hello with the device manager; controller {d} not delegated", .{controller_id});
return false;
}
};
manager_handle = exchanged.manager;
// Fetch our own descriptor back for the controller's resources.
const buffer = memory.allocator().alloc(device.DeviceDescriptor, 64) catch {
@@ -151,7 +204,7 @@ fn initialise(endpoint: ipc.Handle) bool {
std.log.info("controller device {d} has no register BAR", .{controller_id});
return false;
};
std.log.info("claimed controller device {d} (registers at 0x{x}, {d} bytes)", .{
std.log.info("controller device {d} registers at 0x{x}, {d} bytes", .{
controller_id,
register_window.start,
register_window.len,
@@ -175,8 +228,13 @@ fn initialise(endpoint: ipc.Handle) bool {
_ = logging.write("/system/drivers/usb-xhci-bus: controller reset/bring-up failed\n");
return false;
};
std.log.info("controller running ({d} slots, {d}-byte contexts)", .{
// Both numbers, because for a long time they disagreed silently: the controller
// reported its real slot count and the driver tracked a fixed 8 of them, so a
// ninth device — trivially reachable behind a hub — simply did not exist. They
// must now be equal, and the suite asserts it.
std.log.info("controller running ({d} slots, tracking {d}, {d}-byte contexts)", .{
controller.?.max_slots,
controller.?.devices.len,
controller.?.context_size,
});
// The proof of life: a No-Op command round-trips the command ring, the event
@@ -189,13 +247,7 @@ fn initialise(endpoint: ipc.Handle) bool {
return false;
}
// The handshake (role: bus — we enumerate USB ports and report the devices
// behind them), inside the manager's hello deadline. Keep the handle: the
// tick's hot-plug dispatch reports through it.
const handle = device_manager.hello(.bus, controller_id) orelse return false;
manager_handle = handle;
scanPorts(handle);
scanPorts(exchanged.manager);
// Arm the timer: in polling mode it drains the event ring; in MSI mode it is the
// slower port-reconcile/safety-net tick. Re-armed on each tick in onNotification.
@@ -386,6 +438,23 @@ fn bringUpBehindHub(manager: ipc.Handle, engine: *library.Controller, hub: *libr
if (deviceIsHub(usb_device)) _ = engine.setupHub(usb_device);
}
/// Report one interface gone. A removal is addressed by the composite (parent,
/// bus address) — a pair no single `Header.target` can carry — so that stays the
/// packet's body and the target addresses the manager itself. `where` names the
/// port and interface for the log line, or null where the caller stays quiet
/// (a hub subtree collapsing reports a great many at once).
fn reportRemoved(manager: ipc.Handle, bus_address: u64, where: ?struct { port: u32, interface: u8 }) void {
var packet: [device_manager_protocol.message_maximum]u8 = undefined;
const framed = device_manager_protocol.Protocol.encodeRequest(.child_removed, 0, .{
.parent = controller_id,
.bus_address = bus_address,
}, &.{}, &packet) orelse return;
var reply: [device_manager_protocol.message_maximum]u8 = undefined;
_ = ipc.call(manager, framed, &reply) catch {
if (where) |place| std.log.info("child-removed report for port {d} interface {d} failed", .{ place.port, place.interface });
};
}
/// Tear down a device that disconnected from a hub: recursively tear down its
/// own downstream devices first if it is a hub, report each interface removed,
/// then Disable Slot. Mirrors tearDownPort for a hub-attached device.
@@ -398,12 +467,7 @@ fn tearDownHubDevice(manager: ipc.Handle, engine: *library.Controller, dev: *lib
const key = hubPortKey(dev.parent_slot, dev.parent_port);
for (dev.interfaces[0..dev.interface_count]) |*interface| {
if (interface.registered_device_id == 0) continue;
const event = device_manager_protocol.ChildRemoved{
.parent = controller_id,
.bus_address = (@as(u64, key) << 8) | interface.number,
};
var reply: [device_manager_protocol.message_maximum]u8 = undefined;
_ = ipc.call(manager, std.mem.asBytes(&event), &reply) catch {};
reportRemoved(manager, (@as(u64, key) << 8) | interface.number, null);
interface.registered_device_id = 0;
}
engine.tearDownDevice(dev);
@@ -426,16 +490,17 @@ fn deviceIsHub(usb_device: *const library.Device) bool {
fn tearDownPort(manager: ipc.Handle, engine: *library.Controller, port: u32) void {
const usb_device = engine.deviceOnPort(port) orelse return;
std.log.info("port {d} disconnected", .{port});
// A hub yanked from a root port takes its whole subtree with it — children
// first, recursively, exactly as tearDownHubDevice does for a hub leaving
// one level down. Without this, the downstream slots stayed live against
// vanished hardware, their class drivers were never reaped, and the
// replugged hub found its port still occupied — nothing re-enumerated.
if (usb_device.is_hub) {
while (engine.nextChildOf(usb_device.slot_id, 0)) |child| tearDownHubDevice(manager, engine, child);
}
for (usb_device.interfaces[0..usb_device.interface_count]) |*interface| {
if (interface.registered_device_id == 0) continue;
const event = device_manager_protocol.ChildRemoved{
.parent = controller_id,
.bus_address = (@as(u64, port) << 8) | interface.number,
};
var reply: [device_manager_protocol.message_maximum]u8 = undefined;
_ = ipc.call(manager, std.mem.asBytes(&event), &reply) catch {
std.log.info("child-removed report for port {d} interface {d} failed", .{ port, interface.number });
};
reportRemoved(manager, (@as(u64, port) << 8) | interface.number, .{ .port = port, .interface = interface.number });
interface.registered_device_id = 0;
}
engine.tearDownDevice(usb_device);
@@ -464,20 +529,22 @@ fn reportInterface(manager: ipc.Handle, port: u32, interface: library.InterfaceI
const hid_text = std.fmt.bufPrint(&hid_buffer, "P{d}I{d}", .{ port, interface.number }) catch "";
descriptor.hid_len = hid_text.len;
@memcpy(descriptor.hid[0..hid_text.len], hid_text);
const registered = device.register(controller_id, &descriptor) orelse {
std.log.info("register refused for port {d} interface {d}", .{ port, interface.number });
const registered = device.register(controller_id, &descriptor) catch |e| {
std.log.warn("register refused for port {d} interface {d}: {s}", .{ port, interface.number, @errorName(e) });
return null;
};
const report = device_manager_protocol.ChildAdded{
// The registered device id is the packet's target — the manager's object
// addressing — so the report body carries only where on the bus it sits.
var packet: [device_manager_protocol.message_maximum]u8 = undefined;
const framed = device_manager_protocol.Protocol.encodeRequest(.child_added, registered, .{
.bus = @intFromEnum(device_manager_protocol.BusKind.usb),
.parent = controller_id,
.bus_address = (@as(u64, port) << 8) | interface.number,
.identity = identity,
.device_id = registered,
};
}, &.{}, &packet) orelse return null;
var reply: [device_manager_protocol.message_maximum]u8 = undefined;
_ = ipc.call(manager, std.mem.asBytes(&report), &reply) catch {
_ = ipc.call(manager, framed, &reply) catch {
std.log.info("child report for port {d} interface {d} failed", .{ port, interface.number });
return null;
};
@@ -496,59 +563,60 @@ fn reportInterface(manager: ipc.Handle, port: u32, interface: library.InterfaceI
return registered;
}
/// Serve the USB transfer protocol: a class driver opens its device, then issues
/// control / interrupt-subscribe / bulk requests against it.
/// The generated transfer dispatch. One controller per process, so the handler
/// context is empty and the open table stays in this file's globals.
const Serve = usb_transfer_protocol.Protocol.Provider(void);
const Invocation = envelope.Invocation;
const Answer = envelope.Answer;
/// Every refusal here is the same one — this controller does not (or no longer)
/// serve the device the packet addressed — so there is one errno for all of them.
const refused: isize = -envelope.ENOENT;
/// Set by `onOpen` when the open table has taken ownership of the endpoint the
/// call carried, and read by `onMessage`, where the turn's `Arrival` lives. The
/// generated dispatch hands a handler the raw handle rather than the `Arrival`,
/// so the *claim* travels back out this way. One turn, one handler, one thread.
var capability_claimed = false;
fn onMessage(message: []const u8, reply: []u8, sender: u32, arrived: *ipc.Arrival) usize {
_ = sender;
if (message.len < 4) return 0;
const operation = std.mem.readInt(u32, message[0..4], .little);
return switch (operation) {
@intFromEnum(usb_transfer_protocol.Operation.open) => handleOpen(message, reply, arrived),
@intFromEnum(usb_transfer_protocol.Operation.control) => handleControl(message, reply),
@intFromEnum(usb_transfer_protocol.Operation.interrupt_subscribe) => handleSubscribe(message, reply),
@intFromEnum(usb_transfer_protocol.Operation.bulk) => handleBulk(message, reply),
@intFromEnum(usb_transfer_protocol.Operation.dma_attach) => handleDmaAttach(message, reply, arrived),
else => 0,
};
capability_claimed = false;
const written = Serve.dispatch({}, handlers, message, sender, arrived.peek(), reply);
if (capability_claimed) _ = arrived.take();
return written;
}
/// dma_attach: bind the class driver's DMA-region capability into the controller's IOMMU
/// domain, so the controller may DMA to the physical addresses inside that buffer. The
/// binding holds its own kernel reference, so this never claims the arriving handle —
/// the turn's `defer` in the harness is the close, on the failure paths as well as this
/// one.
fn handleDmaAttach(message: []const u8, reply: []u8, arrived: *ipc.Arrival) usize {
if (message.len < @sizeOf(usb_transfer_protocol.DmaAttachRequest)) return writeReply(reply, usb_transfer_protocol.DmaAttachReply{ .status = -1 });
const handle = arrived.peek() orelse return writeReply(reply, usb_transfer_protocol.DmaAttachReply{ .status = -1 });
const ok = device.dmaBind(controller_id, handle);
return writeReply(reply, usb_transfer_protocol.DmaAttachReply{ .status = if (ok) 0 else -1 });
}
const handlers = Serve.Handlers{
.open = onOpen,
.control = onControl,
.interrupt_subscribe = onInterruptSubscribe,
.bulk = onBulk,
.dma_attach = onDmaAttach,
};
fn writeReply(reply: []u8, value: anytype) usize {
const bytes = std.mem.asBytes(&value);
@memcpy(reply[0..bytes.len], bytes);
return bytes.len;
}
/// open: resolve the assigned device id to an interface, remember the caller's
/// endpoint (for interrupt reports), and answer with a device token + the
/// interface's endpoints so the class driver need not re-read the config.
fn handleOpen(message: []const u8, reply: []u8, arrived: *ipc.Arrival) usize {
if (message.len < @sizeOf(usb_transfer_protocol.OpenRequest)) return writeReply(reply, usb_transfer_protocol.OpenReply{ .status = -1, .endpoint_count = 0, .device_token = 0, .interface_class = 0, .interface_subclass = 0, .interface_protocol = 0, .interface_number = 0 });
const request = std.mem.bytesToValue(usb_transfer_protocol.OpenRequest, message[0..@sizeOf(usb_transfer_protocol.OpenRequest)]);
const engine = if (controller) |*c| c else return writeReply(reply, usb_transfer_protocol.OpenReply{ .status = -1, .endpoint_count = 0, .device_token = 0, .interface_class = 0, .interface_subclass = 0, .interface_protocol = 0, .interface_number = 0 });
const found = engine.findInterface(request.device_id) orelse return writeReply(reply, usb_transfer_protocol.OpenReply{ .status = -1, .endpoint_count = 0, .device_token = 0, .interface_class = 0, .interface_subclass = 0, .interface_protocol = 0, .interface_number = 0 });
/// open: the target is the class driver's assigned device id. Resolve it to an
/// interface, remember the caller's endpoint (for interrupt reports), and answer
/// with a device token — the target of every later packet — plus the interface's
/// endpoints, so the class driver need not re-read the configuration descriptor.
fn onOpen(_: void, invocation: Invocation(void), answer: Answer(usb_transfer_protocol.Opened)) isize {
const engine = if (controller) |*c| c else return refused;
const found = engine.findInterface(invocation.target) orelse return refused;
// A device another live client holds is refused exactly as an absent one: one
// device, one class driver. The predecessor's slot is released by the exit
// sweep, and notifications are delivered ahead of requests, so a *restarted*
// driver's open always finds the device free.
if (!openedBy(invocation.target, invocation.sender) and heldByAnother(invocation.target)) return refused;
// The report endpoint is claimed only if the open table actually keeps it;
// a full table leaves it to the turn to close.
if (arrived.peek()) |endpoint| {
if (recordOpen(request.device_id, endpoint)) _ = arrived.take();
if (invocation.capability) |endpoint| {
if (recordOpen(invocation.target, invocation.sender, endpoint)) capability_claimed = true;
}
var open_reply = usb_transfer_protocol.OpenReply{
.status = 0,
var opened = usb_transfer_protocol.Opened{
.device_token = invocation.target,
.endpoint_count = found.interface.endpoint_count,
.device_token = request.device_id,
.interface_class = found.interface.class,
.interface_subclass = found.interface.subclass,
.interface_protocol = found.interface.protocol,
@@ -556,57 +624,74 @@ fn handleOpen(message: []const u8, reply: []u8, arrived: *ipc.Arrival) usize {
};
const count = @min(found.interface.endpoint_count, usb_transfer_protocol.max_reported_endpoints);
for (found.interface.endpoints[0..count], 0..) |endpoint, index| {
open_reply.endpoints[index] = .{
opened.endpoints[index] = .{
.address = endpoint.address,
.transfer_type = endpoint.transfer_type,
.max_packet_size = endpoint.max_packet_size,
.interval = endpoint.interval,
};
}
return writeReply(reply, open_reply);
answer.set(opened);
return 0;
}
/// control: one EP0 control transfer, small data inline both ways.
fn handleControl(message: []const u8, reply: []u8) usize {
if (message.len < @sizeOf(usb_transfer_protocol.ControlRequest)) return writeReply(reply, usb_transfer_protocol.ControlReply{ .status = -1, .actual_length = 0 });
const request = std.mem.bytesToValue(usb_transfer_protocol.ControlRequest, message[0..@sizeOf(usb_transfer_protocol.ControlRequest)]);
const engine = if (controller) |*c| c else return writeReply(reply, usb_transfer_protocol.ControlReply{ .status = -1, .actual_length = 0 });
const found = engine.findInterface(request.device_token) orelse return writeReply(reply, usb_transfer_protocol.ControlReply{ .status = -1, .actual_length = 0 });
/// control: one EP0 control transfer. The data stage rides the tail in both
/// directions, so an IN transfer's answer is simply however many bytes were
/// written into `answer.tail()` — which is what `Status.len` then reports.
fn onControl(_: void, invocation: Invocation(usb_transfer_protocol.Control), answer: Answer(void)) isize {
const engine = if (controller) |*c| c else return refused;
if (!openedBy(invocation.target, invocation.sender)) return refused;
const found = engine.findInterface(invocation.target) orelse return refused;
const setup = std.mem.bytesToValue(usb_abi.Request, &invocation.request.setup);
const direction_in = invocation.request.direction_in != 0;
const room = @min(usb_transfer_protocol.max_inline_data, answer.tail().len);
const data_length = @min(@as(usize, invocation.request.data_length), room);
const setup = std.mem.bytesToValue(usb_abi.Request, &request.setup);
const direction_in = request.direction_in != 0;
const data_length = @min(request.data_length, usb_transfer_protocol.max_inline_data);
var data: [usb_transfer_protocol.max_inline_data]u8 = undefined;
if (!direction_in) @memcpy(data[0..data_length], request.data[0..data_length]);
if (!direction_in) {
const supplied = @min(data_length, invocation.tail.len);
@memcpy(data[0..supplied], invocation.tail[0..supplied]);
if (supplied < data_length) @memset(data[supplied..data_length], 0);
}
const ok = engine.controlTransfer(found.device, setup, data[0..data_length], direction_in);
var control_reply = usb_transfer_protocol.ControlReply{ .status = if (ok) 0 else -1, .actual_length = if (ok) data_length else 0 };
if (ok and direction_in) @memcpy(control_reply.data[0..data_length], data[0..data_length]);
return writeReply(reply, control_reply);
if (!engine.controlTransfer(found.device, setup, data[0..data_length], direction_in)) return refused;
if (!direction_in) return 0; // nothing follows an OUT: the status is the whole answer
@memcpy(answer.tail()[0..data_length], data[0..data_length]);
return @intCast(data_length);
}
/// interrupt_subscribe: arm periodic IN polling; reports flow back asynchronously.
fn handleSubscribe(message: []const u8, reply: []u8) usize {
if (message.len < @sizeOf(usb_transfer_protocol.InterruptSubscribeRequest)) return writeReply(reply, usb_transfer_protocol.InterruptSubscribeReply{ .status = -1 });
const request = std.mem.bytesToValue(usb_transfer_protocol.InterruptSubscribeRequest, message[0..@sizeOf(usb_transfer_protocol.InterruptSubscribeRequest)]);
const engine = if (controller) |*c| c else return writeReply(reply, usb_transfer_protocol.InterruptSubscribeReply{ .status = -1 });
const found = engine.findInterface(request.device_token) orelse return writeReply(reply, usb_transfer_protocol.InterruptSubscribeReply{ .status = -1 });
const endpoint = library.Controller.endpointForAddress(found.interface, request.endpoint_address) orelse return writeReply(reply, usb_transfer_protocol.InterruptSubscribeReply{ .status = -1 });
const report_endpoint = reportEndpointFor(request.device_token) orelse return writeReply(reply, usb_transfer_protocol.InterruptSubscribeReply{ .status = -1 });
const ok = engine.subscribeInterrupt(found.device, endpoint, request.device_token, report_endpoint);
return writeReply(reply, usb_transfer_protocol.InterruptSubscribeReply{ .status = if (ok) 0 else -1 });
/// interrupt_subscribe: arm periodic IN polling; reports flow back asynchronously
/// to the endpoint this device's `open` handed over.
fn onInterruptSubscribe(_: void, invocation: Invocation(usb_transfer_protocol.InterruptSubscribe), _: Answer(void)) isize {
const engine = if (controller) |*c| c else return refused;
if (!openedBy(invocation.target, invocation.sender)) return refused;
const found = engine.findInterface(invocation.target) orelse return refused;
const endpoint = library.Controller.endpointForAddress(found.interface, invocation.request.endpoint_address) orelse return refused;
const report_endpoint = reportEndpointFor(invocation.target) orelse return refused;
return if (engine.subscribeInterrupt(found.device, endpoint, invocation.target, report_endpoint)) 0 else refused;
}
/// bulk: one bulk transfer to/from the class driver's own DMA buffer (by physical
/// address), so sector-sized data never crosses IPC.
fn handleBulk(message: []const u8, reply: []u8) usize {
if (message.len < @sizeOf(usb_transfer_protocol.BulkRequest)) return writeReply(reply, usb_transfer_protocol.BulkReply{ .status = -1, .actual_length = 0 });
const request = std.mem.bytesToValue(usb_transfer_protocol.BulkRequest, message[0..@sizeOf(usb_transfer_protocol.BulkRequest)]);
const engine = if (controller) |*c| c else return writeReply(reply, usb_transfer_protocol.BulkReply{ .status = -1, .actual_length = 0 });
const found = engine.findInterface(request.device_token) orelse return writeReply(reply, usb_transfer_protocol.BulkReply{ .status = -1, .actual_length = 0 });
const endpoint = library.Controller.endpointForAddress(found.interface, request.endpoint_address) orelse return writeReply(reply, usb_transfer_protocol.BulkReply{ .status = -1, .actual_length = 0 });
const transferred = engine.bulkTransfer(found.device, endpoint, request.physical_address, request.length);
return writeReply(reply, usb_transfer_protocol.BulkReply{ .status = if (transferred != null) 0 else -1, .actual_length = transferred orelse 0 });
fn onBulk(_: void, invocation: Invocation(usb_transfer_protocol.Bulk), answer: Answer(usb_transfer_protocol.Transferred)) isize {
const engine = if (controller) |*c| c else return refused;
if (!openedBy(invocation.target, invocation.sender)) return refused;
const found = engine.findInterface(invocation.target) orelse return refused;
const endpoint = library.Controller.endpointForAddress(found.interface, invocation.request.endpoint_address) orelse return refused;
const transferred = engine.bulkTransfer(found.device, endpoint, invocation.request.physical_address, invocation.request.length) orelse return refused;
answer.set(.{ .actual_length = transferred });
return 0;
}
/// dma_attach: bind the class driver's DMA-region capability into the controller's IOMMU
/// domain, so the controller may DMA to the physical addresses inside that buffer. The
/// binding holds its own kernel reference, so this never claims the arriving handle —
/// the turn's `defer` in the harness is the close, on the failure paths as well as this
/// one.
fn onDmaAttach(_: void, invocation: Invocation(void), _: Answer(void)) isize {
const handle = invocation.capability orelse return -envelope.EPROTO;
return if (device.dmaBind(controller_id, handle)) 0 else refused;
}
/// A timer tick or an MSI landed: drain the event ring, reconcile ports, and fan out.
@@ -615,6 +700,12 @@ fn handleBulk(message: []const u8, reply: []u8) usize {
/// arriving after the drain takes IP 0→1 and fires a fresh edge instead of being
/// swallowed until the reconcile tick.
fn onNotification(badge: u64) void {
if (badge & ipc.notify_exit_bit != 0) {
// A class driver died: release the devices it held, so its successor can
// open them and no report is aimed at an endpoint that is gone.
releaseOpensOf(@intCast(badge & ~(ipc.notify_badge_bit | ipc.notify_exit_bit)));
return;
}
if (badge & ipc.notify_timer_bit != 0) {
serviceController();
_ = time.timerOnce(service_endpoint, timerInterval());
@@ -679,14 +770,18 @@ fn serviceController() void {
if (serviced >= 32) break;
}
while (engine.takeReport()) |report| {
var message = usb_transfer_protocol.InterruptReport{
.device_token = report.device_token,
.endpoint_address = report.endpoint_address,
.length = @intCast(@min(report.length, usb_transfer_protocol.max_report_data)),
};
// One `interrupt_report` event packet: the device token in the folded
// header, the report after it. A device that produced more than the
// push floor admits has its report truncated here, never split.
const n = @min(report.length, usb_transfer_protocol.max_report_data);
@memcpy(message.data[0..n], report.data[0..n]);
_ = ipc.send(report.report_endpoint, std.mem.asBytes(&message));
var payload = usb_transfer_protocol.InterruptReport{
.endpoint_address = report.endpoint_address,
.length = @intCast(n),
};
@memcpy(payload.data[0..n], report.data[0..n]);
var packet: [envelope.post_maximum]u8 = undefined;
const framed = usb_transfer_protocol.Protocol.encodeEvent(.interrupt_report, report.device_token, payload, &packet) orelse continue;
_ = ipc.send(report.report_endpoint, framed);
}
}
}
+160 -34
View File
@@ -221,10 +221,17 @@ fn intervalFor(speed: u32, b_interval: u8) u32 {
};
}
// Upper bounds on what one device's active configuration describes. A boot
// keyboard or mouse has one interface with one interrupt endpoint; a flash drive
// has one interface with two bulk endpoints. Generous for those.
pub const max_interfaces = 4;
/// bound: endpoints recorded per interface
/// decided-by: external
/// protects: the fixed endpoint array inside InterfaceInfo
/// at-limit: refuse — the surplus endpoint is not recorded and the class driver
/// cannot bind it
/// observed-by: the class driver failing to find the endpoint it wants
///
/// Held at 4 because the usb-transfer wire protocol reports exactly
/// `max_reported_endpoints` (4) endpoints per interface, so widening this alone
/// would change nothing a class driver can see. Lifting it is a protocol change —
/// docs/bounds-track-plan.md, out of scope for the unattended run.
pub const max_endpoints_per_interface = 4;
// The endpoint-descriptor facts a class driver needs to talk to an endpoint: its
@@ -256,7 +263,19 @@ const ConfiguredEndpoint = struct {
dci: u32 = 0,
ring: ProducerRing = .{ .region = .{ .virtual = 0, .physical = 0 } },
};
const max_configured_endpoints = max_interfaces * max_endpoints_per_interface;
/// bound: transfer rings configured on one device slot
/// decided-by: hardware
/// protects: the per-device ring table, sized at compile time
/// at-limit: refuse — configureEndpoint returns null and its caller reports it
/// observed-by: the class driver's own failure to bind an endpoint
///
/// The xHCI specification's number rather than ours: a Device Context carries a slot
/// context plus at most 31 endpoint contexts, because the Context Entries field that
/// addresses them is 5 bits (DCI 1..31, DCI 1 being the default control endpoint).
/// A device physically cannot present more. This was
/// `max_interfaces * max_endpoints_per_interface` = 16, so it moved whenever either
/// of those two guesses moved.
const max_configured_endpoints = 31;
// One addressed USB device behind this controller: its hardware slot, its EP0
// (control) transfer ring, the DMA context + bounce buffer the control pipe uses,
@@ -277,7 +296,13 @@ pub const Device = struct {
device_descriptor: usb_abi.DeviceDescriptor = std.mem.zeroes(usb_abi.DeviceDescriptor),
configuration_value: u8 = 0,
interface_count: u8 = 0,
interfaces: [max_interfaces]InterfaceInfo = [_]InterfaceInfo{.{}} ** max_interfaces,
/// The interfaces of the active configuration, allocated at enumeration from the
/// count the configuration descriptor actually declares. This was a fixed 4, and
/// the fifth interface of a composite device (a headset, a webcam with audio, a
/// dock, a multifunction printer) did not merely go missing — see
/// parseConfiguration, where its endpoints were appended to interface 3's list.
interfaces: []InterfaceInfo = &.{},
// Transfer rings configured for this device's interrupt/bulk endpoints.
endpoint_ring_count: u8 = 0,
endpoint_rings: [max_configured_endpoints]ConfiguredEndpoint = [_]ConfiguredEndpoint{.{}} ** max_configured_endpoints,
@@ -296,6 +321,15 @@ pub const Device = struct {
// Downstream ports with a pending change to service (bit P = port P), set
// by the status-change endpoint (and by an initial sweep in setupHub).
hub_change_mask: u32 = 0,
/// Release the interface list. Safe to call twice, and on a device that never
/// enumerated — re-enumeration and teardown both come through here.
pub fn freeInterfaces(self: *Device) void {
if (self.interfaces.len != 0) memory.allocator().free(self.interfaces);
self.interfaces = &.{};
self.interface_count = 0;
}
};
// A standing interrupt-IN subscription: the endpoint's ring is kept armed with a
@@ -328,9 +362,6 @@ pub const Report = struct {
data: [64]u8 = [_]u8{0} ** 64,
};
// How many addressed devices this driver tracks at once. QEMU presents a handful
// (a keyboard, a mouse, a storage stick); a fuller machine would grow this.
const max_devices = 8;
const max_subscriptions = 8;
const report_queue_capacity = 16;
@@ -449,7 +480,14 @@ pub const Controller = struct {
device_context_array: memory.DmaRegion,
command_ring: ProducerRing,
event_ring: EventRing,
devices: [max_devices]Device = [_]Device{.{}} ** max_devices,
/// One entry per device slot the **controller** says it has (HCSPARAMS1.MaxSlots,
/// 1..255), allocated at bring-up. This used to be a fixed 8 with the comment "QEMU
/// presents a handful; a fuller machine would grow this" — which is the shape the
/// bounds rule exists to stop, since the controller has always reported the real
/// number and `op_config` below is already programmed with it. A desktop's keyboard,
/// mouse, webcam, headset, hub and two sticks reach 8 without trying, and everything
/// past it vanished (behind a hub, without even a log line).
devices: []Device,
subscriptions: [max_subscriptions]Subscription = [_]Subscription{.{}} ** max_subscriptions,
report_queue: [report_queue_capacity]Report = [_]Report{.{}} ** report_queue_capacity,
report_count: usize = 0,
@@ -582,8 +620,16 @@ pub const Controller = struct {
.device_context_array = undefined,
.command_ring = undefined,
.event_ring = undefined,
.devices = &.{},
};
// One tracking slot per slot the controller reports. A controller that claims
// no slots cannot address anything, so treat that as a dead controller rather
// than allocating nothing and failing mysteriously later.
if (self.max_slots == 0) return null;
self.devices = memory.allocator().alloc(Device, self.max_slots) catch return null;
for (self.devices) |*device| device.* = .{};
// Wait for the controller to report ready, then halt it if it is running.
if (!waitClear(self.operational(op_usbsts), usbsts_controller_not_ready)) return null;
if (read32(self.operational(op_usbcmd)) & usbcmd_run != 0) {
@@ -790,7 +836,7 @@ pub const Controller = struct {
}
fn allocateDevice(self: *Controller) ?*Device {
for (&self.devices) |*device| {
for (self.devices) |*device| {
if (!device.used) return device;
}
return null;
@@ -897,7 +943,8 @@ pub const Controller = struct {
return null;
};
const device = self.allocateDevice() orelse {
std.log.info("port {d} setup: no free device slot", .{port});
std.log.warn("port {d} setup: no free device slot", .{port});
self.disableSlot(slot_id); // the controller already gave it to us
return null;
};
device.* = .{
@@ -1011,7 +1058,7 @@ pub const Controller = struct {
/// The next pending (hub, downstream-port) change to service, or null. Clears
/// the returned port's bit. Called on the bus tick.
pub fn takeHubChange(self: *Controller) ?struct { hub: *Device, port: u16 } {
for (&self.devices) |*device| {
for (self.devices) |*device| {
if (!device.used or !device.is_hub or device.hub_change_mask == 0) continue;
const bit: u5 = @intCast(@ctz(device.hub_change_mask));
device.hub_change_mask &= ~(@as(u32, 1) << bit);
@@ -1084,7 +1131,7 @@ pub const Controller = struct {
}
pub fn deviceOnHubPort(self: *Controller, hub: *Device, port: u16) ?*Device {
for (&self.devices) |*device| {
for (self.devices) |*device| {
if (device.used and device.parent_slot == hub.slot_id and device.parent_port == port) return device;
}
return null;
@@ -1099,7 +1146,11 @@ pub const Controller = struct {
std.log.info("hub slot {d} port {d}: Enable Slot failed", .{ hub.slot_id, port });
return null;
};
const device = self.allocateDevice() orelse return null;
const device = self.allocateDevice() orelse {
std.log.warn("hub slot {d} port {d}: no free device slot", .{ hub.slot_id, port });
self.disableSlot(slot_id); // the controller already gave it to us
return null;
};
const child_speed = mapHubPortSpeed(speed);
device.* = .{
.used = true,
@@ -1150,6 +1201,7 @@ pub const Controller = struct {
fn abandon(self: *Controller, device: *Device) ?*Device {
_ = self;
device.freeInterfaces();
device.used = false;
return null;
}
@@ -1299,12 +1351,25 @@ pub const Controller = struct {
const configuration = std.mem.bytesToValue(usb_abi.ConfigurationDescriptor, &header);
device.configuration_value = @intFromEnum(configuration.configuration_value);
// Read the whole block into a local buffer and parse it here (in the bus
// driver) so the parse never has to cross the 256-byte IPC boundary.
var blob: [512]u8 = undefined;
const length = @min(configuration.total_length, blob.len);
if (!self.controlTransfer(device, usb_abi.getDescriptor(.configuration, 0, 0, @intCast(length)), blob[0..length], true)) return false;
parseConfiguration(device, blob[0..length]);
// Read the whole block and parse it here (in the bus driver) so the parse
// never has to cross the 256-byte IPC boundary. Sized by the device's own
// wTotalLength — the ceiling is then the field's u16, which is the USB
// specification's, not ours.
//
// This was a fixed 512 with an `@min` clamp, which silently truncated: a
// composite device routinely exceeds it (a headset is 500-900 bytes, a UVC
// webcam 1-3 KB, a multifunction printer 600+), and the interfaces past the
// cut simply did not exist — while SET_CONFIGURATION below still configured
// the device for all of them. QEMU's boot keyboard, mouse and stick are all
// under 100 bytes, which is why it survived.
if (configuration.total_length < header.len) return false; // shorter than its own header
const blob = memory.allocator().alloc(u8, configuration.total_length) catch return false;
defer memory.allocator().free(blob);
if (!self.controlTransfer(device, usb_abi.getDescriptor(.configuration, 0, 0, configuration.total_length), blob, true)) return false;
// Both numbers, so a truncation can never again be invisible: the block the
// device declared, and the bytes actually fetched and parsed. They must match.
std.log.info("config block {d} bytes, read {d}", .{ configuration.total_length, blob.len });
if (!parseConfiguration(device, blob)) return false;
// Select the configuration, moving the device to the configured state.
if (!self.controlTransfer(device, usb_abi.setConfiguration(configuration.configuration_value), &.{}, false)) return false;
@@ -1315,8 +1380,30 @@ pub const Controller = struct {
// and the endpoints that follow it. Endpoints belong to the most recent
// interface. Unknown descriptor types (HID, class-specific) are skipped by
// their length.
fn parseConfiguration(device: *Device, blob: []const u8) void {
device.interface_count = 0;
/// Two passes: count the alternate-setting-0 interfaces the block declares,
/// allocate exactly that many, then fill them. False only on an allocation
/// failure. The count cannot exceed 255 — `bNumInterfaces` is a u8, so that is
/// the USB specification's ceiling and not one of ours.
fn parseConfiguration(device: *Device, blob: []const u8) bool {
var declared: usize = 0;
var count_offset: usize = 0;
while (count_offset + 2 <= blob.len) {
const length = blob[count_offset];
if (length < 2 or count_offset + length > blob.len) break;
if (@as(usb_abi.DescriptorType, @enumFromInt(blob[count_offset + 1])) == .interface and
length >= @sizeOf(usb_abi.InterfaceDescriptor))
{
const descriptor = std.mem.bytesToValue(usb_abi.InterfaceDescriptor, blob[count_offset .. count_offset + @sizeOf(usb_abi.InterfaceDescriptor)]);
if (@intFromEnum(descriptor.alternate_setting) == 0 and declared < 255) declared += 1;
}
count_offset += length;
}
device.freeInterfaces();
if (declared == 0) return true;
device.interfaces = memory.allocator().alloc(InterfaceInfo, declared) catch return false;
for (device.interfaces) |*interface| interface.* = .{};
var current: ?*InterfaceInfo = null;
var offset: usize = 0;
while (offset + 2 <= blob.len) {
@@ -1326,9 +1413,17 @@ pub const Controller = struct {
switch (@as(usb_abi.DescriptorType, @enumFromInt(descriptor_type))) {
.interface => if (length >= @sizeOf(usb_abi.InterfaceDescriptor)) {
const descriptor = std.mem.bytesToValue(usb_abi.InterfaceDescriptor, blob[offset .. offset + @sizeOf(usb_abi.InterfaceDescriptor)]);
if (@intFromEnum(descriptor.alternate_setting) != 0) {
current = null; // ignore alternate settings for now
} else if (device.interface_count < max_interfaces) {
// An interface we do not record MUST clear `current`, or the
// endpoints that follow it attach to the previous one. The cap
// branch used to have no `else`, so a fifth interface's endpoints
// were appended to interface 3's array and a class driver bound to
// interface 3 could be handed an endpoint belonging to something
// else entirely — silently, with a truthful-looking count logged.
if (@intFromEnum(descriptor.alternate_setting) != 0 or
device.interface_count >= device.interfaces.len)
{
current = null;
} else {
const slot = &device.interfaces[device.interface_count];
slot.* = .{
.number = @intFromEnum(descriptor.interface_number),
@@ -1358,13 +1453,14 @@ pub const Controller = struct {
}
offset += length;
}
return true;
}
// --- endpoint configuration + interrupt / bulk transfers ---------------
/// Find the tracked device and interface an assigned device id belongs to.
pub fn findInterface(self: *Controller, device_id: u64) ?struct { device: *Device, interface: *InterfaceInfo } {
for (&self.devices) |*device| {
for (self.devices) |*device| {
if (!device.used) continue;
for (device.interfaces[0..device.interface_count]) |*interface| {
if (interface.registered_device_id == device_id) return .{ .device = device, .interface = interface };
@@ -1498,6 +1594,24 @@ pub const Controller = struct {
return true;
}
/// Stop reporting for `device_token`: deactivate every subscription tagged
/// with it, so no further report is queued and the slot can be reused. Called
/// when the class driver that owned the token dies — its endpoint handle is
/// closed with it, and a queued report would then be aimed at a handle number
/// the bus driver has since given to something else. In-process hub
/// subscriptions carry no token and are never touched.
///
/// One completion may already be in flight; it finds no active subscription
/// and is dropped as a foreign transfer event, which is exactly what it is.
pub fn releaseSubscriptions(self: *Controller, device_token: u64) void {
for (&self.subscriptions) |*subscription| {
if (!subscription.active or subscription.hub != null) continue;
if (subscription.device_token != device_token) continue;
subscription.active = false;
subscription.report_endpoint = 0;
}
}
// Arm (or re-arm) a subscription's endpoint with a Normal TRB pointing at its
// report buffer, and ring the endpoint's doorbell so the controller polls it.
fn armInterrupt(self: *Controller, subscription: *Subscription) void {
@@ -1615,7 +1729,7 @@ pub const Controller = struct {
/// The tracked device on `port`, or null.
pub fn deviceOnPort(self: *Controller, port: u32) ?*Device {
for (&self.devices) |*device| {
for (self.devices) |*device| {
if (device.used and device.port == port) return device;
}
return null;
@@ -1624,7 +1738,7 @@ pub const Controller = struct {
/// The next used device whose parent hub is `hub_slot` and slot id > `after`
/// (for recursive teardown when a hub itself disconnects), or null.
pub fn nextChildOf(self: *Controller, hub_slot: u8, after: u8) ?*Device {
for (&self.devices) |*device| {
for (self.devices) |*device| {
if (device.used and device.parent_slot == hub_slot and device.slot_id > after) return device;
}
return null;
@@ -1638,15 +1752,27 @@ pub const Controller = struct {
for (&self.subscriptions) |*subscription| {
if (subscription.active and subscription.slot_id == device.slot_id) subscription.active = false;
}
self.disableSlot(device.slot_id);
device.freeInterfaces();
device.used = false;
}
/// Hand a slot back to the controller and clear its context-array entry.
///
/// Every path that has issued a successful Enable Slot owes this, including the
/// ones that then fail to bring the device up. A slot the driver forgets is one
/// the controller never reissues, so the loss is permanent for the boot: the two
/// setup paths used to return null straight after a failed `allocateDevice`,
/// leaking a slot per attempt — and the hub path did it without even a log line.
fn disableSlot(self: *Controller, slot_id: u8) void {
const physical = self.submitCommand(.{
.control = trbControl(.disable_slot, @as(u32, device.slot_id) << 24),
.control = trbControl(.disable_slot, @as(u32, slot_id) << 24),
});
if (self.awaitCommand(physical)) |code| {
if (code != @intFromEnum(CompletionCode.success))
std.log.info("slot {d}: Disable Slot completion code {d}", .{ device.slot_id, code });
} else std.log.info("slot {d}: Disable Slot timed out", .{device.slot_id});
std.log.info("slot {d}: Disable Slot completion code {d}", .{ slot_id, code });
} else std.log.info("slot {d}: Disable Slot timed out", .{slot_id});
const array: [*]volatile u64 = @ptrFromInt(self.device_context_array.virtual);
array[device.slot_id] = 0;
device.used = false;
array[slot_id] = 0;
}
};
+2 -2
View File
@@ -10,8 +10,8 @@ pub fn build(b: *std.Build) void {
.name = "virtio-gpu",
.root_source_file = b.path("virtio-gpu.zig"),
.imports = &.{
"channel", "display-protocol", "driver", "ipc", "logging", "memory", "mmio", "pci",
"process", "scanout-protocol", "service", "time",
"channel", "display-protocol", "driver", "envelope", "ipc", "logging", "memory",
"mmio", "pci", "process", "scanout-protocol", "service", "time",
},
});
b.installArtifact(exe);
+55 -48
View File
@@ -25,11 +25,19 @@ const memory = @import("memory");
const logging = @import("logging");
const mmio = @import("mmio");
const pci = @import("pci");
const envelope = @import("envelope");
const display_protocol = @import("display-protocol");
const scanout_protocol = @import("scanout-protocol");
const vp = @import("virtio-pci.zig");
const vg = @import("virtio-gpu-protocol.zig");
/// The generated scanout dispatch. One scanout per driver instance, so the
/// handler context is empty and the mode stays in this file's globals.
const Serve = scanout_protocol.Protocol.Provider(void);
const Invocation = envelope.Invocation;
const Answer = envelope.Answer;
/// The DisplayFormat (device-abi) our B8G8R8X8 scanout resource presents: bgrx = 1. Handed to
/// the compositor in the announce so it packs colours in the surface's byte order.
const display_format_bgrx: u32 = 1;
@@ -192,10 +200,9 @@ fn testPixel(index: u32) u32 {
fn initialise(endpoint: ipc.Handle) bool {
_ = endpoint;
if (!device.claim(device_id)) {
std.log.info("unable to claim device {d}", .{device_id});
return false;
}
// The device arrived with the spawn — the manager holds it and names it in the call
// that creates this process, so it is ours before the first instruction here
// (docs/os-development/device-authority.md). Nothing to claim.
var descriptors: [64]device.DeviceDescriptor = undefined;
const total = device.enumerate(&descriptors);
@@ -482,60 +489,60 @@ fn announce() void {
std.log.info("no display service to announce to (scanout-only)", .{});
return;
};
var request = display_protocol.Request{
.operation = @intFromEnum(display_protocol.Operation.attach_scanout),
.x = max_width, // the shared surface's row stride in pixels (it is sized to the max mode)
.y = edid_refresh_hz, // the panel refresh from EDID (0 = unknown) — the frame-clock seed
var packet: [display_protocol.message_maximum]u8 = undefined;
const framed = display_protocol.Protocol.encodeRequest(.attach_scanout, 0, .{
.stride = max_width, // the shared surface's row stride in pixels (it is sized to the max mode)
.width = current_width,
.height = current_height,
.colour = display_format_bgrx,
};
var reply: [display_protocol.reply_size]u8 = undefined;
_ = ipc.callCap(display, std.mem.asBytes(&request), &reply, surface.handle) catch {
.format = display_format_bgrx,
.refresh_hz = edid_refresh_hz, // from EDID (0 = unknown) — the frame-clock seed
}, &.{}, &packet) orelse return;
var reply: [display_protocol.message_maximum]u8 = undefined;
_ = ipc.callCap(display, framed, &reply, surface.handle) catch {
std.log.info("announce to display failed", .{});
return;
};
std.log.info("announced scanout to display", .{});
}
/// A `scanout_protocol.Reply{status}` written into `reply`.
fn scanoutStatus(reply: []u8, ok: bool) usize {
const response = scanout_protocol.Reply{ .status = if (ok) 0 else -1 };
@memcpy(reply[0..scanout_protocol.reply_size], std.mem.asBytes(&response));
return scanout_protocol.reply_size;
// --- serving the scanout protocol -------------------------------------------
//
// The compositor drives present / mode queries here. The pixels are already in
// the shared surface, so a present is a transfer-to-host + fenced flush; a mode
// change just re-points the scanout rectangle (the surface is sized to the
// largest mode). One scanout, so `Header.target` is always 0.
/// The device did not take the frame, or the mode asked for is not one this
/// scanout offers.
const refused: isize = -envelope.ENOENT;
fn onPresent(_: void, _: Invocation(scanout_protocol.Present), _: Answer(void)) isize {
return if (presentFull()) 0 else refused;
}
/// The `.scanout` service: the compositor drives present / mode queries here. The pixels are
/// already in the shared surface, so a present is a transfer-to-host + fenced flush; a mode
/// change just re-points the scanout rectangle (the surface is sized to the largest mode).
fn onMessage(message: []const u8, reply: []u8, sender: u32, arrived: *ipc.Arrival) usize {
_ = sender;
_ = arrived; // nothing here takes a capability: the harness closes what arrives
if (message.len < scanout_protocol.request_size) return 0;
const request = std.mem.bytesToValue(scanout_protocol.Request, message[0..scanout_protocol.request_size]);
switch (request.operation) {
@intFromEnum(scanout_protocol.Operation.present) => return scanoutStatus(reply, presentFull()),
@intFromEnum(scanout_protocol.Operation.get_modes) => {
var response = scanout_protocol.ModesReply{ .status = 0, .count = offered_modes.len, .modes = undefined };
for (0..scanout_protocol.max_modes) |i| {
response.modes[i] = if (i < offered_modes.len)
.{ .width = offered_modes[i].width, .height = offered_modes[i].height }
else
.{ .width = 0, .height = 0 };
}
@memcpy(reply[0..scanout_protocol.modes_reply_size], std.mem.asBytes(&response));
return scanout_protocol.modes_reply_size;
},
@intFromEnum(scanout_protocol.Operation.set_mode) => {
const w = request.width;
const h = request.height;
if (w == 0 or h == 0 or w > max_width or h > max_height) return scanoutStatus(reply, false);
current_width = w;
current_height = h;
return scanoutStatus(reply, setScanoutRect());
},
else => return 0,
fn onGetModes(_: void, _: Invocation(void), answer: Answer(scanout_protocol.Modes)) isize {
var offered = scanout_protocol.Modes{ .count = offered_modes.len };
for (0..@min(offered_modes.len, scanout_protocol.max_modes)) |i| {
offered.modes[i] = .{ .width = offered_modes[i].width, .height = offered_modes[i].height };
}
answer.set(offered);
return 0;
}
fn onSetMode(_: void, invocation: Invocation(scanout_protocol.SetMode), _: Answer(void)) isize {
const w = invocation.request.width;
const h = invocation.request.height;
if (w == 0 or h == 0 or w > max_width or h > max_height) return refused;
current_width = w;
current_height = h;
return if (setScanoutRect()) 0 else refused;
}
const handlers = Serve.Handlers{ .present = onPresent, .get_modes = onGetModes, .set_mode = onSetMode };
fn onMessage(message: []const u8, reply: []u8, sender: u32, arrived: *ipc.Arrival) usize {
_ = arrived; // nothing here takes a capability: the harness closes what arrives
return Serve.dispatch({}, handlers, message, sender, null, reply);
}
pub fn main(init: process.Init) void {
@@ -547,7 +554,7 @@ pub fn main(init: process.Init) void {
std.log.info("malformed device id '{s}'", .{argument});
return;
};
service.run(256, .{
service.run(scanout_protocol.message_maximum, .{
.service = "scanout",
.init = initialise,
.on_message = onMessage,
+82 -40
View File
@@ -615,17 +615,78 @@ var boot_memory_regions: []const boot_handoff.MemoryRegion = &.{};
/// I/O-APIC region, the high one from 4 GiB (or the end of RAM above it) to
/// the 46-bit line. Coarse, mechanical, and AML-free — available at boot no
/// matter what later moved to user space.
pub const AddressRange = struct { base: u64, end: u64 };
/// The largest holes below 4 GiB in a firmware memory map: the ranges the firmware
/// described *nothing* in, which is where a PCI BAR may legitimately live. Fills `out`
/// (keeping the largest, replacing the smallest held so far), ignores holes shorter
/// than `minimum`, and returns how many entries are non-empty; entries the caller
/// reads may be empty and are skipped by `end > base`.
///
/// **It never copies the map, and that is the point.** The firmware chooses how many
/// descriptors its map has — commonly 60–200 on a real machine, 15–25 under OVMF. The
/// previous version copied the sub-4 GiB entries into a fixed `[64]` array and
/// `continue`d past the rest, which did not merely lose them: a region absent from the
/// walk is a region this function concludes is *free*, so a large enough map yields an
/// "aperture" lying over live RAM. `device_register` containment would then admit a
/// child BAR covering kernel memory, and its claimant could `mmio_map` it. A bound
/// whose overflow hands out authority is not a limit; the fix is not a bigger array.
///
/// Pure, allocation-free, and linear-ish in the map (each inner pass consumes at least
/// one region, and it runs once at boot).
pub fn largestHolesBelow4G(
regions: []const boot_handoff.MemoryRegion,
minimum: u64,
out: []AddressRange,
) usize {
const limit: u64 = 1 << 32;
for (out) |*hole| hole.* = .{ .base = 0, .end = 0 };
var cursor: u64 = 0;
while (cursor < limit) {
// Step over every described region covering the cursor. Regions may overlap
// and chain, so repeat until the cursor stops moving.
var moved = true;
while (moved) {
moved = false;
for (regions) |region| {
if (region.base >= limit) continue;
const end = @min(region.base + region.pages * 4096, limit);
if (region.base <= cursor and end > cursor) {
cursor = end;
moved = true;
}
}
}
if (cursor >= limit) break;
// The cursor now sits in a hole; it runs to the next described base, or to
// 4 GiB if nothing is described above it.
var next: u64 = limit;
for (regions) |region| {
if (region.base >= limit) continue;
if (region.base > cursor and region.base < next) next = region.base;
}
if (next - cursor >= minimum and out.len != 0) {
var smallest: usize = 0;
for (out, 0..) |hole, i| {
if (hole.end - hole.base < out[smallest].end - out[smallest].base) smallest = i;
}
if (next - cursor > out[smallest].end - out[smallest].base)
out[smallest] = .{ .base = cursor, .end = next };
}
cursor = next;
}
var found: usize = 0;
for (out) |hole| {
if (hole.end > hole.base) found += 1;
}
return found;
}
fn addBridgeApertures(bridge: *device_model.Device) void {
// Below 4 GiB the described regions are sparse (RAM low, firmware flash
// and tables high), so the holes are the *gaps between* them — a single
// "after the last region" rule dies on OVMF's flash at the very top.
// Sort-merge the described ranges, then keep the three largest gaps
// (resource slots are bounded at 8 per device; ECAM + bus range + 3 + the
// high aperture fits). Above 4 GiB one aperture runs from the end of the
// described space to the 46-bit line.
const Range = struct { base: u64, end: u64 };
var below: [64]Range = undefined;
var below_count: usize = 0;
var high_end: u64 = 1 << 32;
for (boot_memory_regions) |region| {
const end = region.base + region.pages * 4096;
@@ -636,37 +697,18 @@ fn addBridgeApertures(bridge: *device_model.Device) void {
// kernel image, the tables, the ramdisk all live there). Bring-up
// trust: only the bridge's claimant can register into the aperture.
if (region.kind == .usable and end > high_end) high_end = end;
if (region.base >= (1 << 32) or below_count == below.len) continue;
below[below_count] = .{ .base = region.base, .end = @min(end, 1 << 32) };
below_count += 1;
}
// Insertion sort by base (the map is small and this runs once at boot).
for (1..below_count) |i| {
const key = below[i];
var j = i;
while (j > 0 and below[j - 1].base > key.base) : (j -= 1) below[j] = below[j - 1];
below[j] = key;
}
// Walk the sorted ranges, collecting inter-region gaps of at least 1 MiB.
var gaps: [3]Range = .{Range{ .base = 0, .end = 0 }} ** 3;
var cursor: u64 = 0;
var index: usize = 0;
while (index <= below_count) : (index += 1) {
const gap_end = if (index == below_count) (1 << 32) else below[index].base;
if (gap_end > cursor and gap_end - cursor >= (1 << 20)) {
// Keep the three largest, replacing the smallest kept so far.
var smallest: usize = 0;
for (gaps, 0..) |gap, gi| {
if (gap.end - gap.base < gaps[smallest].end - gaps[smallest].base) smallest = gi;
}
if (gap_end - cursor > gaps[smallest].end - gaps[smallest].base) {
gaps[smallest] = .{ .base = cursor, .end = gap_end };
}
}
if (index < below_count and below[index].end > cursor) cursor = below[index].end;
}
for (gaps) |gap| {
if (gap.end > gap.base) _ = bridge.addResource(.memory, gap.base, gap.end - gap.base);
// Three holes below 4 GiB. This three is not a guess about hardware: a
// `DeviceDescriptor` carries `maximum_device_resources` (8) resources, and the
// bridge spends them on ECAM + bus range + these + the high aperture. That cap is
// a wire struct in the kernel↔user ABI, so widening it is a separate change —
// docs/bounds-track-plan.md, phase 4. Keeping *fewer* holes is fail-closed: it
// refuses BARs, it never admits one.
var holes: [3]AddressRange = undefined;
_ = largestHolesBelow4G(boot_memory_regions, 1 << 20, &holes);
for (holes) |hole| {
if (hole.end > hole.base) _ = bridge.addResource(.memory, hole.base, hole.end - hole.base);
}
_ = bridge.addResource(.memory, high_end, (@as(u64, 1) << 46) - high_end);
}
+5 -22
View File
@@ -11,6 +11,7 @@
const boot_handoff = @import("boot-handoff");
const io = @import("io.zig");
const cpuid = @import("cpuid.zig");
const paging = @import("paging.zig");
/// The ACPI PM timer, as a calibration reference: an I/O port or MMIO counter.
@@ -331,8 +332,8 @@ fn calibratePit() void {
/// TSC frequency from CPUID leaf 0x15 (crystal_hz * numerator / denominator), or
/// null if the CPU doesn't enumerate it (common under QEMU, and on AMD).
fn cpuidTscHz() ?u64 {
if (cpuid(0).eax < 0x15) return null;
const r = cpuid(0x15);
if (!cpuid.supports(0x15)) return null;
const r = cpuid.leaf(0x15);
if (r.eax == 0 or r.ebx == 0 or r.ecx == 0) return null; // ratio/crystal not given
return @as(u64, r.ecx) * r.ebx / r.eax;
}
@@ -342,26 +343,8 @@ fn cpuidTscHz() ?u64 {
/// at a constant rate across P/C-states and never stops. Requires the extended-leaf
/// range to reach 0x80000007 first.
fn tscIsInvariant() bool {
if (cpuid(0x80000000).eax < 0x80000007) return false;
return (cpuid(0x80000007).edx & (1 << 8)) != 0;
}
const CpuidRegs = struct { eax: u32, ebx: u32, ecx: u32, edx: u32 };
fn cpuid(leaf: u32) CpuidRegs {
var a: u32 = undefined;
var b: u32 = undefined;
var c: u32 = undefined;
var d: u32 = undefined;
asm volatile ("cpuid"
: [a] "={eax}" (a),
[b] "={ebx}" (b),
[c] "={ecx}" (c),
[d] "={edx}" (d),
: [leaf] "{eax}" (leaf),
[sub] "{ecx}" (@as(u32, 0)),
);
return .{ .eax = a, .ebx = b, .ecx = c, .edx = d };
if (!cpuid.supports(0x8000_0007)) return false;
return (cpuid.leaf(0x8000_0007).edx & (1 << 8)) != 0;
}
// HPET registers: capabilities at +0x00 (period in the high dword, in fs; bit 13 =
+44
View File
@@ -141,11 +141,41 @@ pub fn debugconWrite(bytes: []const u8) void {
/// stack for double faults), then the IDT with exception handlers. After this a
/// CPU fault is reported instead of triple-faulting. Install the fault handler
/// (setFaultHandler) first so early faults are caught.
///
/// This is the **boot processor's** half of per-core bring-up; smp.apEntry is the
/// other half and must keep the per-CPU steps in step with it (the system_call
/// MSRs and the CR4 hardening bits are per-core state, so every core sets its own).
pub fn init() void {
gdt.init();
tss.init();
idt.init();
pcpu.initSystemCall();
// The machine-wide half of SMAP, and it must precede every CR4 write: the
// interrupt entry has to be able to clear EFLAGS.AC before any core claims the
// bit. This is the boot processor and the application processors are still
// parked, so "before every core" is simply "here".
_ = pcpu.armSupervisorAccessPrevention();
// Safe this early, before the kernel is on its own page tables: the loader's
// bootstrap tables (boot/efi.zig) map with present|writable and never set the
// U/S bit, so no page the BSP executes from is user-accessible — and, for SMAP,
// no page it *reads* is either, so there is nothing for the new bit to refuse
// between here and the switch to the kernel's own tables.
pcpu.initHardening();
}
/// Whether ring 0 is barred from executing user-mapped pages on this core (CR4.SMEP
/// on x86_64; the privileged-execute-never behaviour elsewhere). False means the CPU
/// doesn't offer it and the machine is running unhardened — see per-cpu.zig.
pub fn supervisorExecutePreventionEnabled() bool {
return pcpu.supervisorExecutePreventionEnabled();
}
/// Whether ring 0 is barred from *reading or writing* user-mapped pages on this core
/// (CR4.SMAP on x86_64; the privileged-access-never behaviour elsewhere). False means
/// either the CPU doesn't offer it or the interrupt entry could not be armed to clear
/// AC — see per-cpu.zig; the machine boots either way, unhardened and saying so.
pub fn supervisorAccessPreventionEnabled() bool {
return pcpu.supervisorAccessPreventionEnabled();
}
/// Build the kernel's own page tables (with real permissions) and switch onto
@@ -300,6 +330,20 @@ pub fn userExit() noreturn {
user_exit_to_kernel();
}
/// The counter the syscall exit stub bumps when it refuses to return the fast way
/// (isr.s, `sysret_non_canonical_count`).
const non_canonical_returns = @extern(*u64, .{ .name = "sysret_non_canonical_count" });
/// How many times this boot's system_call returns took the slow, safe exit because
/// the return address was not a canonical address (the SYSRETQ canonical-RIP guard
/// in isr.s; an architecture without the hazard reports 0 forever). A correct
/// program cannot produce one — it could not have executed at a non-canonical
/// address in the first place — so a nonzero count is exactly the number of times
/// a process tried to make the kernel fault on its way out.
pub fn nonCanonicalReturnCount() u64 {
return @atomicLoad(u64, non_canonical_returns, .monotonic);
}
/// Register the handler for the user system_call gate (int 0x80, vector 128). The
/// handler may write the trap frame (see `setSystemCallResult`).
pub fn setSystemCallHandler(handler: *const fn (*CpuState) void) void {
@@ -0,0 +1,42 @@
//! CPUID — the CPU describing itself.
//!
//! One helper for the whole architecture layer (the timer's TSC leaves, the
//! supervisor-hardening feature bits), rather than a private copy per module.
//! `leaf` always executes with ECX = 0, which is what every leaf danos reads
//! wants: leaf 7's feature words live in sub-leaf 0, and leaves that ignore ECX
//! don't care. A sub-leaf-taking caller would add its own entry point here.
//!
//! **Always gate on `supports` first.** CPUID does not fault on an out-of-range
//! leaf — it returns the data of the highest supported leaf instead, which would
//! be read as a feature bit that isn't there. The maximum lives in leaf 0 (basic
//! range) and leaf 0x80000000 (extended range).
pub const Registers = struct { eax: u32, ebx: u32, ecx: u32, edx: u32 };
/// Execute CPUID for `number` at sub-leaf 0.
pub fn leaf(number: u32) Registers {
var a: u32 = undefined;
var b: u32 = undefined;
var c: u32 = undefined;
var d: u32 = undefined;
asm volatile ("cpuid"
: [a] "={eax}" (a),
[b] "={ebx}" (b),
[c] "={ecx}" (c),
[d] "={edx}" (d),
: [leaf] "{eax}" (number),
[sub] "{ecx}" (@as(u32, 0)),
);
return .{ .eax = a, .ebx = b, .ecx = c, .edx = d };
}
/// Whether `number` is inside the range this CPU actually enumerates — the basic
/// range for a leaf below 0x80000000, the extended range above it. Every read of
/// a leaf beyond 0 or 0x80000000 must pass through here first (see the module doc).
pub fn supports(number: u32) bool {
const maximum = if (number >= 0x8000_0000)
leaf(0x8000_0000).eax
else
leaf(0).eax;
return maximum >= number;
}
@@ -59,8 +59,15 @@ const command_opcode_shift = 60; // opcode in bits 63:60 of qword 0
const command_completion_wait: u64 = 0x01;
const command_invalidate_devtab: u64 = 0x02;
const command_invalidate_pages: u64 = 0x03;
const completion_wait_store: u64 = 1 << 1; // S: store `data` to the supplied address
const invalidate_pages_all: u64 = 0x000F_FFFF_FFFF_F000 | 1; // address bits 51:12 all-ones + S
// COMPLETION_WAIT qword 0: bit 0 is S (store `data` to the supplied address), bit 1 is
// I (raise an interrupt). An earlier revision set bit 1 and then blamed QEMU for the
// sentinel never landing — with I instead of S the IOMMU is never *asked* to store, on
// QEMU or on silicon, and completeAndWait was no barrier at all.
const completion_wait_store: u64 = 1 << 0;
// INVALIDATE_IOMMU_PAGES address qword, S=1: the architected invalidate-everything
// encoding is bits 62:12 all-ones (the spec's literal 0x7FFF_FFFF_FFFF_F000). The
// previous 51:12 value is a non-architected range real silicon is free to misread.
const invalidate_pages_all: u64 = 0x7FFF_FFFF_FFFF_F000 | 1;
const levels: u8 = 4; // 48-bit IOVA, matching the Intel 4-level path
@@ -228,11 +235,14 @@ fn submitCommand(qword0: u64, qword1: u64) void {
}
/// Append a COMPLETION_WAIT (store form) and spin until the IOMMU writes our sentinel to
/// the completion frame. QEMU consumes the command buffer synchronously on the tail-
/// register write, so by the time we poll the prior invalidation is already applied; the
/// store confirmation is belt-and-suspenders for real hardware. If it never lands
/// (QEMU's amd-iommu does not implement the store form), warn ONCE and proceed — the
/// invalidation itself has happened.
/// the completion frame. This is the driver's only ordering barrier: real hardware
/// fetches commands asynchronously, so a preceding invalidation has not happened until
/// this store lands — the callers that free DMA frames after an unmap depend on it.
/// (QEMU consumes the ring synchronously on the tail write and implements the store
/// form fine; the warning below once fired there only because the command carried the
/// I bit instead of S, so no store was ever requested.) If the store never lands, warn
/// ONCE and proceed rather than wedge the claim path — but on real silicon that line
/// means invalidations are unconfirmed and must be treated as a bug report.
fn completeAndWait() void {
const sentinel: u64 = 0xC0FFEE;
ram(completion_frame)[0] = 0;
@@ -246,7 +256,7 @@ fn completeAndWait() void {
if (spins > 100_000) {
if (!completion_warned) {
completion_warned = true;
iommu.environment.write("/system/kernel: AMD-Vi COMPLETION_WAIT store not observed — proceeding (QEMU processes commands synchronously)\n");
iommu.environment.write("/system/kernel: AMD-Vi COMPLETION_WAIT store not observed — proceeding WITHOUT an invalidation barrier\n");
}
return;
}
+114 -6
View File
@@ -187,11 +187,9 @@ user_exit_to_kernel:
# CS/SS from STAR, masks RFLAGS with SFMASK (so IF is already clear), and jumps
# here with RSP still the *user* stack. We swap in the kernel GS, switch to the
# task's kernel stack via the per-CPU block, build a CpuState frame identical to
# the interrupt path's, and reuse interruptDispatch (vector 128) — then SYSRET.
#
# Hazard (acceptable while init is the only, trusted, user program): SYSRETQ #GPs
# in ring 0 if the return RIP (RCX) is non-canonical. A hostile user could arrange
# that; hardening (canonical check / iretq fallback) is a later security-track item.
# the interrupt path's, and reuse interruptDispatch (vector 128) — then SYSRET,
# unless the return RIP is non-canonical, in which case the canonical-RIP guard at
# the exit below returns through IRETQ instead (docs/os-development/smep-smap.md).
.global syscall_entry
syscall_entry:
swapgs # kernel GS base
@@ -249,16 +247,79 @@ syscall_entry:
pop %rax
add $16, %rsp # drop vector + error_code -> rsp at rip
popq %rcx # rip -> RCX (SYSRETQ restores RIP from RCX)
# --- canonical-RIP guard ---
# SYSRETQ with a non-canonical RCX raises #GP *in ring 0* on Intel: on the
# kernel stack, after the swapgs below has already installed the user's GS
# base — a fault in the trusted base, on user-influenced state, which is the
# classic escalation primitive (CVE-2012-0217). Ring 3 gets to choose that RIP
# without any kernel bug: the CPU saves the address of the instruction *after*
# `syscall`, so a program executing `syscall` as the last two bytes of the last
# canonical page returns to 0x0000_8000_0000_0000. Nothing between entry and
# here rewrites the frame's rip (no signal or context-restore path exists that
# could), so this is the whole attack surface — and one compare closes it.
#
# Canonical means bits 63:47 all equal bit 47, so sign-extending from bit 47
# and comparing is the complete test. Bit 47 is the right pivot because danos
# is 4-level only: paging.zig builds a PML4 and nothing anywhere sets CR4.LA57
# (bit 12), so a linear address is 48-bit on every core, on every machine we
# boot. A future 5-level port must pivot on bit 56 instead — and should patch
# this shift pair at boot rather than branch on a feature flag, to keep the
# return path of every syscall in the system free of loads.
#
# Cost: four register-only ALU ops and one forward branch the predictor sees
# taken exactly never (a correct program cannot have a non-canonical return
# address — it could not have executed there). R11 is free scratch: SYSCALL
# already destroyed the user's copy, and the fast path overwrites it with the
# saved RFLAGS two instructions further on.
movq %rcx, %r11
shlq $16, %r11
sarq $16, %r11 # sign-extend from bit 47
cmpq %rcx, %r11 # changed by the round trip => non-canonical
jne .Lnon_canonical_return
addq $8, %rsp # skip the cs slot (SYSRETQ loads CS from STAR)
popq %r11 # rflags -> R11 (SYSRETQ restores RFLAGS from R11)
popq %rsp # user rsp (the ss slot below is abandoned)
swapgs # user GS base
sysretq # -> ring 3: RIP=RCX, RFLAGS=R11, CS/SS from STAR
# The guard's cold path: return through IRETQ, which is safe where SYSRETQ is not.
# IRETQ loads CS — committing the privilege change to ring 3 — before the new RIP
# is fetched, so the #GP arrives *from ring 3*: through the IDT, onto this task's
# kernel stack, with a user CS in the frame, where isr_common swaps GS back and the
# kernel kills the process like any other user fault. That ordering is why IRETQ is
# the standard fallback for this exact case; the sysret-canonical test asserts it
# on the machine we run on (the process dies, the kernel does not).
#
# State handed to ring 3 is identical to what the fast path would have produced.
# IRETQ consumes the same 5-word frame the CPU pushes for an interrupt — rip, cs,
# rflags, rsp, ss — which is exactly the frame syscall_entry built and the fast
# path is part-way through dismantling, so un-popping the rip slot makes it whole:
# same user RIP, same user RSP, same RFLAGS, and CS/SS = 0x23/0x1B, the very
# selectors SYSRETQ would have loaded from STAR. R11 is reloaded from the frame's
# rflags slot so even the register SYSRET synthesizes matches. The swapgs sits in
# the same place relative to the ring change as the fast path's, so the swapgs
# discipline is untouched: kernel GS while we still touch kernel data, user GS for
# the instant before ring 3.
.Lnon_canonical_return:
# Cold-path diagnostic: how many hostile return addresses this boot refused.
# `lock` because every core shares the counter, and it costs nothing here — a
# process that reaches this line is about to die.
lock incq sysret_non_canonical_count(%rip)
movq 8(%rsp), %r11 # rflags -> R11, exactly as the fast path leaves it
subq $8, %rsp # un-pop the rip slot: rsp back at the iretq frame
swapgs # user GS base
iretq # -> ring 3, where the bad RIP faults harmlessly
.section .bss
.balign 8
user_saved_rsp:
.skip 8
# Times the canonical-RIP guard above refused a SYSRETQ this boot. Read through the
# architecture layer (cpu.zig nonCanonicalReturnCount); zero on any machine no
# process has attacked.
.global sysret_non_canonical_count
sysret_non_canonical_count:
.skip 8
.text
# --- user-mode test program --------------------------------------------------
@@ -282,6 +343,24 @@ user_pf_start:
1: jmp 1b
user_pf_end:
# The SYSRET-guard program: two harmless system calls, the second placed so that
# its *return address* is not canonical. The caller (tests.zig) copies these bytes
# to the very end of the last canonical user page, so the final `syscall` occupies
# the last two bytes of address space ring 3 can execute, and the RIP the CPU saves
# into RCX for it is 0x0000_8000_0000_0000 — the first non-canonical address.
# The first call proves the ordinary SYSRETQ path still works (the program only
# reaches the second instruction pair by returning correctly from the first).
# 39 is abi.SystemCall.current_core: no arguments, no side effects, always
# succeeds; the test asserts the immediate below still matches that enum.
.global user_sysret_start
.global user_sysret_end
user_sysret_start:
mov $39, %eax # current_core
syscall # canonical return address (mid-page): the fast path
mov $39, %eax # current_core
syscall # return address = the end of the page = non-canonical
user_sysret_end:
.text
# Stub for a vector the CPU does NOT push an error code for: push a dummy 0.
@@ -363,7 +442,27 @@ STUB_NOERR 128
# If the interrupt came from ring 3 the GS base holds the user's value, so swap
# in the kernel's before anything reads per-CPU data (swapgs discipline; see
# percpu.zig). CS sits at offset 24 here (vector@0, error@8, RIP@16, CS@24).
#
# The first three bytes are the SMAP guard, and they come before everything —
# before the CPL test, before the swapgs. Interrupt delivery does not clear
# EFLAGS.AC (SYSCALL does, through SFMASK; an IDT gate does not), and ring 3 sets
# AC freely with popfq, so without this a hostile process could take an interrupt
# with AC=1 and have the whole handler run with SMAP suspended. Ahead of the CPL
# test because ring 0 inherits AC just as readily: a fault or IRQ nested inside
# kernel code carries whatever AC the interrupted context had, and that context
# may itself be an entry that has not reached its own guard yet. Clearing first,
# unconditionally, means no path into the kernel is ever a path in with AC set.
#
# `clac` is #UD on a CPU without SMAP, so the image ships the 3-byte canonical NOP
# (`nopl (%rax)`) and per-cpu.zig overwrites it with `clac` (0f 01 ca) at boot,
# on the boot processor, only when CPUID says the instruction exists — a one-time
# patch rather than a branch in the hottest path in the kernel. Neither encoding
# touches the flags the `testb` below sets, so the guard is invisible to the code
# that follows it either way.
.global isr_smap_patch
isr_common:
isr_smap_patch:
.byte 0x0f, 0x1f, 0x00 # nopl (%rax) -> patched to `clac` when the CPU has SMAP
testb $3, 24(%rsp)
jz 1f
swapgs
@@ -419,4 +518,13 @@ isr_common:
testb $3, 8(%rsp)
jz 1f
swapgs
1: iretq
# Named so a fault reporter can recognise its own return instruction. A #GP
# here is the frame's fault, not this code's — the five words below RSP are
# what the CPU rejected, and they are the only evidence of why. Note that on
# the ring-3 path the swapgs above has already run, so a fault at this exact
# address re-enters the kernel with the *user's* GS base: per-CPU reads in
# that handler are reading user-controlled state and must not be trusted.
1:
.global isr_return_iretq
isr_return_iretq:
iretq
+218 -7
View File
@@ -11,9 +11,24 @@
//! transition is always an exit (the kernel starts in ring 0), the swap pairs
//! keep the invariant without seeding KERNEL_GS_BASE. `scheduler()` is therefore
//! valid in any ring-0 context and never sees a user-controlled base.
//!
//! The file has since become the home of **per-core CPU state set at bring-up**
//! generally, not just the GS block: the fast-system_call MSRs and the CR4
//! hardening bits live here too, because each is state a core owns and must set
//! for itself. Both bring-up paths — `cpu.init` on the boot processor and
//! `smp.apEntry` on every application processor — call the same functions here.
//!
//! One deliberate exception to "per-core": `armSupervisorAccessPrevention` patches
//! a machine-wide instruction into the shared interrupt entry, once, on the boot
//! processor. It lives here anyway because it is the other half of CR4.SMAP —
//! same feature probe, same fail-open posture — and splitting a hardening measure
//! across two files is how the halves drift apart.
const std = @import("std");
const io = @import("io.zig");
const cpuid = @import("cpuid.zig");
const paging = @import("paging.zig");
const boot_handoff = @import("boot-handoff");
const parameters = @import("parameters");
const ia32_gs_base = 0xC000_0101;
@@ -42,10 +57,21 @@ pub fn setLocal(index: usize, scheduler_ptr: usize) void {
io.wrmsr(ia32_gs_base, @intFromPtr(&blocks[index]));
}
/// The scheduler pointer for the running core (via the GS base). Valid in any
/// ring-0 context under the swapgs discipline.
/// The scheduler pointer for the running core (via the GS base), or 0 before this
/// core has one. Valid in any ring-0 context under the swapgs discipline.
///
/// **Zero is an answer here, not a fault.** A core has no per-CPU block between
/// reset and its `setLocal`, and the fault reporters are documented to be callable
/// unconditionally: `currentIdSafe`, `currentNameSafe`, `currentCpuIndex` and
/// `sync.releaseIfHeldHere` all test this for 0 and mean it. Casting the base
/// before testing it put the null one instruction out of their reach — an early
/// fault reported itself by panicking on the cast, and the panic handler, calling
/// those same reporters on its next line, panicked again, so the machine reset
/// instead of halting with the message that would have said what went wrong.
pub fn scheduler() usize {
return @as(*const ArchitecturePerCpu, @ptrFromInt(io.rdmsr(ia32_gs_base))).scheduler;
const base = io.rdmsr(ia32_gs_base);
if (base == 0) return 0;
return @as(*const ArchitecturePerCpu, @ptrFromInt(base)).scheduler;
}
/// Record core `index`'s kernel stack top, used by the system_call entry stub to
@@ -61,17 +87,202 @@ const ia32_star = 0xC000_0081;
const ia32_lstar = 0xC000_0082;
const ia32_sfmask = 0xC000_0084;
/// The SYSRET half of STAR: `sysret` loads CS from base+16 and SS from base+8.
/// The base carries RPL 3 itself — 0x13, not the 0x10 the GDT layout suggests —
/// because **only CS is guaranteed to come out at ring 3**. CS must: `sysret`
/// sets CPL to 3, so the selector it loads is forced to match. SS is under no
/// such obligation, and the two vendors differ on it: Intel ORs 3 into the SS
/// selector as well, AMD hands it over exactly as the arithmetic produced it.
///
/// With base 0x10 an AMD machine therefore enters ring 3 carrying SS 0x18 — RPL
/// 0 — and nothing complains, because a data access is checked against CPL and
/// the descriptor's DPL, never the selector's RPL. It runs perfectly until the
/// first interrupt: the CPU pushes that SS, and the `iretq` returning to ring 3
/// requires SS.RPL to equal CS.RPL, refusing 0 against 3 with #GP(0x18). A
/// process that made system calls happily then dies on its first timer tick.
///
/// Putting the 3 in the base makes both selectors right by construction on
/// either vendor: 0x13 + 8 = 0x1B, 0x13 + 16 = 0x23. Intel's OR is then a no-op
/// rather than the thing holding it together.
const star_sysret_base: u64 = 0x13; // user data 0x18 / user code 0x20, with RPL 3
const star_syscall_base: u64 = 0x08; // kernel code 0x08 / kernel data 0x10
/// Enable the `system_call`/`sysret` fast path on this core (BSP and each AP). EFER.SCE
/// turns the instructions on; STAR sets the selectors system_call/sysret load; LSTAR
/// is the entry stub (isr.s); SFMASK clears RFLAGS bits on entry (notably IF —
/// the handler runs with interrupts off, like the int-gate path). The GDT is laid
/// out (kernel code 0x08, then user data 0x18 / code 0x20) precisely so these line
/// up: system_call loads CS 0x08 / SS 0x10; sysret loads CS = base+16 and SS = base+8
/// with RPL forced to 3, so base 0x10 gives CS 0x23 (user code|3) and SS 0x1B.
/// up: system_call loads CS 0x08 / SS 0x10; sysret loads CS 0x23 and SS 0x1B.
pub fn initSystemCall() void {
io.wrmsr(ia32_efer, io.rdmsr(ia32_efer) | 1); // SCE
io.wrmsr(ia32_star, (@as(u64, 0x08) << 32) | (@as(u64, 0x10) << 48));
io.wrmsr(ia32_star, (star_syscall_base << 32) | (star_sysret_base << 48));
const entry = @extern(*const anyopaque, .{ .name = "syscall_entry" });
io.wrmsr(ia32_lstar, @intFromPtr(entry));
io.wrmsr(ia32_sfmask, 0x4_0700); // clear IF, TF, DF, AC on entry
// Clear IF, TF, DF, AC and NT on entry. The first four are the usual
// hygiene; NT is here because SYSCALL, unlike an interrupt gate, does not
// clear it for us, so without this the kernel runs every system call with
// whatever nested-task bit ring 3 last chose — and the canonical-RIP guard's
// cold path (isr.s) leaves through IRETQ, whose behaviour with NT set is a
// corner of the manuals not worth depending on either way. Masking it costs
// one bit and removes the question: the kernel is never nested, and ring 3
// still gets its own NT back, from R11 on the fast path and from the frame
// on the cold one.
io.wrmsr(ia32_sfmask, 0x4_4700);
}
// --- supervisor-mode hardening (CR4) ---------------------------------------
//
// CR4 is per-core state, so these bits are set during *every* core's bring-up —
// the BSP in cpu.init, each AP in smp.apEntry — and not in the AP trampoline,
// which stays minimal and would only cover the APs anyway.
/// CR4.SMEP: an instruction fetch in ring 0 from a page whose U/S bit says *user*
/// raises #PF. This is what makes the classic ret2usr shape (a kernel bug steered
/// into attacker-prepared user code) a loud, attributable fault instead of a
/// silent compromise. danos never executes user-mapped memory in ring 0 — kernel
/// text lives in the higher half, the ring-3 entry paths are kernel code, and the
/// AP trampoline page is a supervisor mapping — so nothing legitimate is refused.
const cr4_smep: u64 = 1 << 20;
/// SMEP's feature bit: CPUID leaf 7, sub-leaf 0, EBX bit 7.
fn smepSupported() bool {
if (!cpuid.supports(7)) return false;
return cpuid.leaf(7).ebx & (1 << 7) != 0;
}
/// CR4.SMAP: a ring-0 data *read or write* to a page whose U/S bit says *user*
/// raises #PF, unless EFLAGS.AC is set. It is the standing enforcement behind
/// system/kernel/user-memory.zig: that layer never dereferences a user virtual
/// address — it walks the process's tables and moves bytes through the physmap,
/// kernel mappings throughout — so nothing legitimate in this kernel is refused,
/// and any future code that reaches for a user pointer directly faults the first
/// time it runs. danos therefore opens no `stac` window anywhere; there is no
/// correct reason to have one, and adding one is how the guarantee is lost.
const cr4_smap: u64 = 1 << 21;
/// SMAP's feature bit: CPUID leaf 7, sub-leaf 0, EBX bit 20.
fn smapSupported() bool {
if (!cpuid.supports(7)) return false;
return cpuid.leaf(7).ebx & (1 << 20) != 0;
}
/// `clac` — the three bytes that replace the NOP at `isr_smap_patch` once the
/// interrupt entry is allowed to execute them.
const clac_opcode = [_]u8{ 0x0f, 0x01, 0xca };
/// Set only once the interrupt entry really clears AC, and read by every core
/// before it turns SMAP on. Nothing turns SMAP on until this is true, so there is
/// no window — not even on the boot processor, not even before ring 3 exists —
/// in which the bit is live while an interrupt could still be taken with AC set.
var interrupt_entry_clears_ac = false;
fn readCr3() u64 {
return asm volatile ("mov %%cr3, %[out]"
: [out] "=r" (-> u64),
);
}
/// Patch the `clac` into the shared interrupt entry, and by doing so authorize
/// CR4.SMAP. **Boot processor only, once, before any core sets the bit and before
/// the application processors are woken** — `initHardening` refuses SMAP until
/// this has run, so the order is enforced rather than merely documented, and an AP
/// climbing the trampoline cannot get ahead of it.
///
/// The write goes through the physmap, not through the kernel's own view of its
/// text: once `paging.init` has run, kernel `.text` is mapped read-only under W^X,
/// and a store to it would fault (or, worse, silently need CR0.WP cleared). The
/// physmap alias of the same frame is an ordinary supervisor RW mapping — the same
/// door `smp.arm` uses to write the AP trampoline and `process.run` uses to fill a
/// read-only user code frame. Going through it also makes this correct under
/// *either* set of tables: the loader's bootstrap tables map the image writable,
/// the kernel's own do not, and this runs before the switch.
///
/// Three bytes, translated one at a time, so a patch site that straddles a page
/// boundary is not a special case. A translation that fails leaves the NOP in
/// place and returns false, and the machine then boots without SMAP rather than
/// with SMAP and an entry path that cannot clear AC.
pub fn armSupervisorAccessPrevention() bool {
if (!smapSupported()) return false;
const site = @intFromPtr(@extern([*]const u8, .{ .name = "isr_smap_patch" }));
const root = readCr3() & 0x000F_FFFF_FFFF_F000;
// MUST run with interrupts masked, and does: this is reached from cpu.init,
// long before the kernel's `sti`, and before any application processor exists.
// The reason is that the three bytes go in one at a time, and the middle state
// — 0f 01 00, once the second byte lands — is `sgdt (%rax)`, a ten-byte write
// to wherever RAX points, sitting at the first instruction of every interrupt
// entry. Nothing can take that entry here, so nothing can execute it. A future
// change that moves this after interrupts are enabled has to close that window
// first (one 16-bit store covering both changed bytes is the shape, but it
// needs the two to be physically contiguous and 2-byte aligned — a naive
// version of exactly that triple-faulted this kernel).
for (clac_opcode, 0..) |byte, i| {
const physical = paging.translateIn(root, site + i) orelse return false;
const alias: *volatile u8 = @ptrFromInt(boot_handoff.physicalToVirtual(physical));
alias.* = byte;
}
// The bytes were written through a different linear address than the one they
// will be fetched from, so serialize before anyone can execute them: CPUID is
// the architecturally sanctioned way to discard whatever the core prefetched or
// decoded of the old encoding.
_ = cpuid.leaf(0);
// Read back through the *text* address, not the alias just written: that is the
// view the CPU will fetch from, so this is what proves the two are the same
// physical page and the patch landed where it will actually execute. A mismatch
// means the translation lied, and SMAP stays off rather than being enabled over
// an entry path that cannot clear AC.
const installed: [*]const volatile u8 = @ptrFromInt(site);
for (clac_opcode, 0..) |byte, i| {
if (installed[i] != byte) return false;
}
interrupt_entry_clears_ac = true;
return true;
}
fn readCr4() u64 {
return asm volatile ("mov %%cr4, %[out]"
: [out] "=r" (-> u64),
);
}
fn writeCr4(value: u64) void {
asm volatile ("mov %[in], %%cr4"
:
: [in] "r" (value),
: .{ .memory = true });
}
/// Turn on the supervisor-mode hardening this CPU offers, on the calling core.
/// Called once per core, next to `initSystemCall`, from both bring-up paths.
///
/// **Fail-open, like the IOMMU and the clocksource:** an absent feature is a
/// machine that boots unhardened, not a machine that refuses to boot. danos has
/// to run on any VM, on real Intel and on real AMD; the boot log states the
/// posture either way (see the platform block in system/kernel/kernel.zig), so
/// an unhardened boot is visible rather than assumed.
pub fn initHardening() void {
var bits: u64 = 0;
if (smepSupported()) bits |= cr4_smep;
// SMAP only after the boot processor has armed the interrupt entry: with the
// NOP still in place an interrupt inherits ring 3's AC and suspends SMAP for
// the length of the handler, which is worse than not claiming the bit at all.
if (smapSupported() and interrupt_entry_clears_ac) bits |= cr4_smap;
if (bits == 0) return;
writeCr4(readCr4() | bits);
}
/// Whether supervisor-mode execution prevention is live on *this* core. Read
/// straight out of CR4 rather than a remembered probe result, so the answer is
/// the state the hardware is actually in — which is what both the boot log and
/// the `fault-smep` test case want to assert.
pub fn supervisorExecutePreventionEnabled() bool {
return readCr4() & cr4_smep != 0;
}
/// Whether supervisor-mode *access* prevention is live on *this* core. Read from
/// CR4 for the same reason as its neighbour: the question the boot log and the
/// `fault-smap` case are asking is what the hardware is doing, not what a probe
/// once concluded.
pub fn supervisorAccessPreventionEnabled() bool {
return readCr4() & cr4_smap != 0;
}
@@ -179,6 +179,13 @@ fn apEntry(percpu: usize) callconv(.c) noreturn {
idt.loadOnThisCpu(); // the shared IDT
pcpu.setLocal(cpu, percpu); // per-CPU block via GS base — *after* the GDT reload
pcpu.initSystemCall(); // enable system_call/sysret on this core
// CR4 is per-core: this core starts from the trampoline's CR4 (PAE + SSE only),
// so it sets its own hardening bits here rather than in the trampoline — one
// Zig code path shared with the BSP (cpu.init), and the trampoline stays minimal.
// CR4.SMEP and CR4.SMAP on this core, if the CPU has them. The `clac` the SMAP
// bit depends on was patched into the shared interrupt entry by the BSP long
// before this core was woken, so an AP only ever finds it already armed.
pcpu.initHardening();
apic.initSecondary(); // software-enable this core's LAPIC
apic.initTimer(apic.frequencyHz()); // arm its timer (still masked: interrupts off)
+298 -60
View File
@@ -19,31 +19,117 @@
//! ever subdivide what it was already given.
const std = @import("std");
const abi = @import("abi");
const platform = @import("platform");
const device_abi = @import("device-abi");
const heap = @import("heap.zig");
const maximum_devices = 64;
/// How many devices a single registrar may put in the table.
///
/// **This is a runaway detector, not a security boundary**, and the difference matters.
/// It cannot stop a malicious driver — a quota generous enough never to bite a real
/// machine is still generous enough to be unpleasant — and it is not trying to. What
/// stops malice is that only a driver the manager handed a device can register children
/// under it (docs/os-development/device-authority.md). What this catches is a
/// *legitimate* driver in a loop, early, and attributably: the driver that did it is
/// refused, named in its own log, and restarted, while every other driver is untouched.
///
/// The shared ceilings it replaces could not do that. `maximum_devices = 64` was a
/// guess about someone else's computer and one driver's enumeration starved every
/// other — which is how an AMD Ryzen came to boot with a working display, no USB and no
/// storage. A per-registrar allowance is the same protection charged to whoever caused
/// it, which is the microkernel property rather than a workaround for it.
///
/// The number: a machine's whole PCI segment tops out at 65536 functions, and the
/// biggest real registrar seen is pci-bus at a few dozen. 4096 is far above anything a
/// real machine produces and around 1.4 MiB of descriptors, well under the kernel heap.
/// **Reaching it is a bug report, not a tuning request** — no correct driver gets near.
///
/// bound: devices one task may register
/// decided-by: ours
/// protects: the kernel heap, against a driver looping device_register
/// at-limit: refuse — ECHILDREN to the registrar; every other driver is unaffected
/// observed-by: the bus driver's line naming the reason (pci-bus reconciles functions
/// found against registered)
const maximum_devices_per_registrar = 4096;
/// Cap on children a single parent may have. A zero-resource child (legal — a USB
/// device is addressed through its controller, not by MMIO) sidesteps the containment
/// check, so without a bound a process that claimed one device could loop
/// `device_register` and exhaust the whole table, permanently denying it to every other
/// driver. This bounds the blast radius of one claim; a real quota (and a
/// `device_release` to reclaim on exit) is future work — see docs/driver-model.md.
const maximum_children_per_parent = 16;
var devices: [maximum_devices]device_abi.DeviceDescriptor = undefined;
var claimed: [maximum_devices]?u32 = .{null} ** maximum_devices; // owner task id, or null
/// The table, grown on demand from the kernel heap. **There is no ceiling**: how many
/// devices a machine has is the machine's business, and no specification bounds it, so
/// nothing here should. `devices_broker.init` runs after `heap.init` (kernel.zig), so
/// there was never a reason for this to be static beyond it having been written that
/// way first.
var devices: []device_abi.DeviceDescriptor = &.{};
/// Owner task id per device, or null. Parallel to `devices` and grown with it.
var claimed: []?u32 = &.{};
/// The task that called `register` for each device, so the per-registrar allowance can
/// be charged to whoever caused the entry. Firmware-discovered nodes carry `no_registrar`
/// — they are the kernel's own, not anybody's doing.
/// Optional, not a sentinel: **task 0 is a real task** (the kernel's own), so any
/// "none" value inside the id space is a device belonging to somebody reading back as
/// belonging to nobody. Found the moment the first test asserted a giver, because the
/// task doing the giving was task 0.
var registrar: []?u32 = &.{};
/// **Who gave each device away**, or `no_giver` if nobody ever did.
///
/// One field, and the whole authority rule follows from it: a device that was *given*
/// to someone is delegated hardware, so it may only be handed on, never taken
/// (`claim` refuses it); and when its holder dies it goes back to whoever lent it,
/// rather than becoming free for anyone to grab.
///
/// It also settles the framebuffer without mentioning it. Nobody delegates the
/// loader's framebuffer, so it has no giver, so the display service claims it exactly
/// as it always has — no exemption, no special case, no `display` anywhere in the rule.
var giver: []?u32 = &.{};
var count: usize = 0;
/// Grow the three parallel arrays so at least one more device fits. False if the heap
/// cannot satisfy it, which the callers report rather than swallow.
fn reserve() bool {
if (count < devices.len) return true;
// Double from a deliberately SMALL first block. Sizing it for a typical machine
// would mean the growth path never ran on the hardware we test on, and only woke up
// on someone else's larger machine — which is the exact shape of the failure this
// whole track exists to stop. At 8, every boot grows the table several times, so
// the path is exercised constantly and the suite asserts it.
const wanted = if (devices.len == 0) 8 else devices.len * 2;
const allocator = heap.allocator();
const grown_devices = allocator.realloc(devices, wanted) catch return false;
devices = grown_devices;
const grown_claimed = allocator.realloc(claimed, wanted) catch return false;
claimed = grown_claimed;
const grown_registrar = allocator.realloc(registrar, wanted) catch return false;
registrar = grown_registrar;
const grown_giver = allocator.realloc(giver, wanted) catch return false;
giver = grown_giver;
for (claimed[count..], registrar[count..], giver[count..]) |*slot, *who, *lender| {
slot.* = null;
who.* = null;
lender.* = null;
}
return true;
}
/// How many devices `task` has registered — the allowance is charged per registrar, so
/// a driver in a loop exhausts its own and no one else's.
fn registeredBy(task: u32) usize {
var n: usize = 0;
for (registrar[0..count]) |who| {
if (who != null and who.? == task) n += 1;
}
return n;
}
/// The id of the seeded framebuffer node (`seedDisplay`), or null when the machine
/// handed over no framebuffer. Lets the process layer recognise the display claim
/// (to quiesce the bootstrap console) without threading the id through every caller.
var display_device: ?u64 = null;
/// Devices discovery found but the table had no room for. Non-zero means the machine
/// is bigger than `maximum_devices` and some hardware is simply invisible to drivers —
/// which would otherwise be an entirely silent failure. Logged at boot.
/// Devices discovery found but could not record. The table grows on demand, so this is
/// no longer "the machine is bigger than our guess" — it means the kernel heap could not
/// satisfy the growth, which would otherwise be an entirely silent failure. Logged at
/// boot.
pub var dropped: usize = 0;
/// Snapshot the device tree into the flat table. Run once, right after discovery.
@@ -51,7 +137,9 @@ pub fn init(device_tree: *const platform.DeviceTree) void {
count = 0;
dropped = 0;
display_device = null;
for (&claimed) |*c| c.* = null;
for (claimed) |*c| c.* = null;
for (registrar) |*r| r.* = null;
for (giver) |*g| g.* = null;
walk(device_tree.root, device_abi.no_parent);
}
@@ -63,7 +151,7 @@ pub fn init(device_tree: *const platform.DeviceTree) void {
/// table is full. Idempotent-ish: only ever call once per boot.
pub fn seedDisplay(base: u64, width: u32, height: u32, pitch: u32, format: u32, refresh_hz: u32) ?u64 {
if (base == 0 or width == 0 or height == 0) return null; // headless
if (count >= maximum_devices) {
if (!reserve()) {
dropped += 1;
return null;
}
@@ -108,7 +196,7 @@ fn walk(node: *platform.Device, parent_id: u64) void {
}
fn record(node: *platform.Device, parent_id: u64) u64 {
if (count >= maximum_devices) {
if (!reserve()) {
dropped += 1;
return device_abi.no_parent; // children of a dropped node become roots, not orphans
}
@@ -157,13 +245,36 @@ pub fn enumerateFrom(start: usize, out: []device_abi.DeviceDescriptor) usize {
return n;
}
/// Take exclusive ownership of device `id` for task `owner`. Fails if the id is
/// out of range or already claimed.
pub fn claim(id: u64, owner: u32) bool {
if (id >= count) return false;
if (claimed[@intCast(id)] != null) return false;
/// Take exclusive ownership of device `id` for task `owner`. The two ways this can
/// fail want different responses from a driver — a stale id means re-enumerate, a
/// live claimant means back off — so they are distinguishable (`ClaimError`).
pub fn claim(id: u64, owner: u32) ClaimError!void {
if (id >= count) return error.NoSuchDevice;
if (claimed[@intCast(id)] != null) return error.AlreadyClaimed;
// **Delegated hardware may be handed on, never taken.**
//
// Belt and braces, and worth being honest about: with the loan rule above this is
// **currently unreachable**. A device that was given to someone is held, so it is
// refused as `AlreadyClaimed` before reaching here; and when the holder dies the
// device goes back to its lender (or, if the lender is gone, has its giver cleared
// with its claim), so there is no state where a device is unheld *and* still on
// loan. The window a stranger could have used simply stops existing.
//
// It stays because it is one comparison and it fails closed: any future path that
// frees a device without clearing its giver would otherwise hand delegated
// hardware to whoever asked first, which is exactly the hole this run closed.
//
// Note it leaves the loader's framebuffer alone without naming it: nobody delegates
// the framebuffer, so it has no giver, so the display service claims it as always.
if (giver[@intCast(id)] != null) return error.NotYours;
claimed[@intCast(id)] = owner;
return true;
}
/// The task that gave device `id` away, or null if nobody ever did. A device with a
/// giver is delegated hardware: it may be handed on, never taken.
pub fn giverOf(id: u64) ?u32 {
if (id >= count) return null;
return giver[@intCast(id)];
}
/// The task that owns device `id`, or null.
@@ -177,11 +288,41 @@ pub fn ownerOf(id: u64) ?u32 {
/// hardware again (docs/process-lifecycle.md iron rule 1: cleanup is the kernel's
/// job). The devices stay in the table — they describe hardware, which did not go
/// away — only their ownership clears.
/// Whether a task is still alive, injected by the process layer (which owns the task
/// table) the same way the scheduler's other hooks are. Null means "assume not", so a
/// kernel built without it clears claims rather than handing them to a ghost.
pub var task_alive_hook: ?*const fn (u32) bool = null;
fn alive(task: u32) bool {
const hook = task_alive_hook orelse return false;
return hook(task);
}
pub fn releaseAllOwnedBy(owner: u32) void {
for (claimed[0..count]) |*slot| {
if (slot.*) |o| {
if (o == owner) slot.* = null;
for (claimed[0..count], 0..) |*slot, id| {
const holder = slot.* orelse continue;
if (holder != owner) continue;
// **A grant is a loan.** A device this task was *given* goes back to whoever
// lent it, not to nobody — so the device manager gets its hardware back the
// instant a driver dies, and hands it to the replacement.
//
// Without this the kernel released the claim to no one and the manager
// re-claimed first-come, so every driver restart reopened the window this
// rule closes. And once `claim` refuses a device that has a giver, releasing
// to nobody would strand it: no one could ever take it again.
//
// A dead lender is no lender: clear the claim and the giver together, so the
// device is genuinely free rather than owed to a ghost.
if (giver[id]) |lender| {
if (alive(lender)) {
slot.* = lender;
giver[id] = null; // returned; it is the lender's own again, not on loan
continue;
}
giver[id] = null;
}
slot.* = null;
}
}
@@ -274,51 +415,99 @@ fn contains(parent: device_abi.ResourceDescriptor, child: device_abi.ResourceDes
return child.start >= parent.start and child_end <= parent_end;
}
/// Why a `register` was refused. Each variant maps to its own errno (`errnoOf`), so
/// a bus driver's log line can name the rule that stopped it — "this parent is at
/// its child cap" and "the table is full" want different fixes, and telling them
/// apart from a bare -1 cost a debugging session (docs/fixed-bounds-audit.md).
pub const RegisterError = error{
NoSpace, // the device table is full
BadParent, // no such device, or not claimed by this task
TooManyResources,
TooManyChildren, // this parent is at maximum_children_per_parent
NoSuchParent, // no device with that id
NotYourParent, // that device exists but this task has not claimed it
TooManyResources, // the descriptor declares more resources than one device may hold
TooManyChildren, // the caller is at its per-registrar allowance
NotContained, // a child resource escapes its parent's window
};
/// Number of devices currently recorded with `parent_id` as their parent.
fn childCount(parent_id: u64) usize {
var n: usize = 0;
for (devices[0..count]) |d| {
if (d.parent == parent_id) n += 1;
}
return n;
/// The errno a refused `register` returns to ring 3.
pub fn errnoOf(e: RegisterError) i64 {
return switch (e) {
error.NoSpace => abi.ENOSPC,
error.NoSuchParent => abi.ENODEV,
error.NotYourParent => abi.EPERM,
error.TooManyResources => abi.E2BIG,
error.TooManyChildren => abi.ECHILDREN,
error.NotContained => abi.ERANGE,
};
}
/// Publish `descriptor` as a child of `parent_id`, on behalf of `owner`. Returns the new
/// device id. The child is left **unclaimed**, so another process (a class driver)
/// can claim it — that is how a bus hands a device to its driver.
/// Why a `claim` was refused.
pub const ClaimError = error{
NoSuchDevice, // no device with that id
AlreadyClaimed, // a live task already owns it
NotYours, // delegated hardware: it has a giver, so it must be handed on, not taken
};
/// Why a `transfer` was refused.
pub const TransferError = error{
NoSuchDevice, // no device with that id
NotHeld, // the caller does not hold it — you may only give away what you have
};
/// The errno a refused `transfer` returns to ring 3. (`ESRCH` — no such recipient — is
/// raised by the caller in system/kernel/process.zig, which is what can see the task
/// table.)
pub fn transferErrnoOf(e: TransferError) i64 {
return switch (e) {
error.NoSuchDevice => abi.ENODEV,
error.NotHeld => abi.EPERM,
};
}
/// Move device `id` from `from` to `to`. **A move, not a copy**: a claim is exclusive
/// (driver-model.md, invariant 1), so the giver stops holding it the moment the
/// receiver starts.
///
/// `owner` must have claimed `parent_id`, and every resource in `descriptor` must be
/// contained in a parent resource of the same kind. A device with no resources is
/// fine and common: a USB device is addressed through its controller, not by MMIO.
pub fn register(parent_id: u64, owner: u32, descriptor: *const device_abi.DeviceDescriptor) RegisterError!u64 {
const parent_owner = ownerOf(parent_id) orelse return error.BadParent;
if (parent_owner != owner) return error.BadParent;
if (descriptor.resource_count > device_abi.maximum_device_resources) return error.TooManyResources;
if (childCount(parent_id) >= maximum_children_per_parent) return error.TooManyChildren;
if (count >= maximum_devices) return error.NoSpace;
/// This is the mechanism behind delegation — the device manager claims what firmware
/// discovery seeded and passes each device to the driver it matched, which replaces
/// first-come-first-served `device_claim` with policy
/// (docs/device-driver-development/device-manager.md). The kernel checks only that the
/// caller holds the device: *you may give away what you have*. It knows nothing about
/// which task is the manager, and needs to know nothing.
///
/// Note this is deliberately NOT the M13 capability-passing path, which shares a handle
/// refcounted — a copy. Exclusivity cannot be expressed that way.
pub fn transfer(id: u64, from: u32, to: u32) TransferError!void {
try canTransfer(id, from);
claimed[@intCast(id)] = to;
giver[@intCast(id)] = from;
}
const parent = &devices[@intCast(parent_id)];
for (0..@intCast(descriptor.resource_count)) |i| {
const r = descriptor.resources[i];
var ok = false;
for (0..@intCast(parent.resource_count)) |j| {
if (contains(parent.resources[j], r)) ok = true;
}
if (!ok) return error.NotContained;
}
/// The checks `transfer` will make, without the move. The syscall layer runs them
/// first — under the same lock hold that the transfer itself will run under — so it
/// can refuse, or arrange the IOMMU confinement the move needs, while nothing has
/// mutated yet and there is nothing to roll back.
pub fn canTransfer(id: u64, from: u32) TransferError!void {
if (id >= count) return error.NoSuchDevice;
const holder = claimed[@intCast(id)] orelse return error.NotHeld;
if (holder != from) return error.NotHeld;
}
// Idempotent on exact match (docs/device-manager.md): a restarted
// registering bus re-registers what it rediscovers, and the table has no
// unregister — an identical (class, identity, resources) child under the
// same parent returns the existing id instead of appending a duplicate.
/// The errno a refused `claim` returns to ring 3. (`ECONFINE` — the claim stood but
/// the IOMMU would not confine the device — is raised by the caller in
/// system/kernel/process.zig, which is what rolls the claim back.)
pub fn claimErrnoOf(e: ClaimError) i64 {
return switch (e) {
error.NoSuchDevice => abi.ENODEV,
error.AlreadyClaimed => abi.EBUSY,
error.NotYours => abi.EPERM,
};
}
/// The id of a child of `parent_id` already identical to `descriptor`, or null.
/// Exact on class, identity and every resource — anything less would let a bus
/// silently adopt an entry that is not the device it just found. The caller must
/// have bounded `descriptor.resource_count` first.
fn existingChild(parent_id: u64, descriptor: *const device_abi.DeviceDescriptor) ?u64 {
for (devices[0..count]) |*existing| {
if (existing.parent != parent_id) continue;
if (existing.class != descriptor.class) continue;
@@ -334,6 +523,54 @@ pub fn register(parent_id: u64, owner: u32, descriptor: *const device_abi.Device
}
if (same) return existing.id;
}
return null;
}
/// Publish `descriptor` as a child of `parent_id`, on behalf of `owner`. Returns the new
/// device id. The child is left **unclaimed**, so another process (a class driver)
/// can claim it — that is how a bus hands a device to its driver.
///
/// `owner` must have claimed `parent_id`, and every resource in `descriptor` must be
/// contained in a parent resource of the same kind. A device with no resources is
/// fine and common: a USB device is addressed through its controller, not by MMIO.
pub fn register(parent_id: u64, owner: u32, descriptor: *const device_abi.DeviceDescriptor) RegisterError!u64 {
if (parent_id >= count) return error.NoSuchParent;
const parent_owner = ownerOf(parent_id) orelse return error.NotYourParent;
if (parent_owner != owner) return error.NotYourParent;
// Bounds every `descriptor.resources` read below, including the match scan's.
if (descriptor.resource_count > device_abi.maximum_device_resources) return error.TooManyResources;
// Idempotent on exact match (docs/device-manager.md): a restarted registering
// bus re-registers what it rediscovers, and the table has no unregister — an
// identical child under the same parent returns the existing id instead of
// appending a duplicate.
//
// Checked **before the caps**, because a re-registration consumes no slot.
// Charging it against the child cap refused a restarted bus its own devices the
// second time it started, which turned the supervision restart this system leans
// on into a one-way ratchet toward a degraded machine. The match is exact — class,
// identity, and every resource — so an entry returned this way was contained when
// it was first admitted, and a stored descriptor's resources never change
// afterwards (they are written only by `record`, `seedDisplay` and the append
// below).
if (existingChild(parent_id, descriptor)) |existing_id| return existing_id;
// The allowance is charged to whoever is registering, so a driver in a loop
// exhausts its own and every other driver carries on. There is no machine-wide
// ceiling any more: the table grows.
if (registeredBy(owner) >= maximum_devices_per_registrar) return error.TooManyChildren;
if (!reserve()) return error.NoSpace;
const parent = &devices[@intCast(parent_id)];
for (0..@intCast(descriptor.resource_count)) |i| {
const r = descriptor.resources[i];
var ok = false;
for (0..@intCast(parent.resource_count)) |j| {
if (contains(parent.resources[j], r)) ok = true;
}
if (!ok) return error.NotContained;
}
var d = std.mem.zeroes(device_abi.DeviceDescriptor);
d.id = count;
@@ -346,6 +583,7 @@ pub fn register(parent_id: u64, owner: u32, descriptor: *const device_abi.Device
for (0..@intCast(descriptor.resource_count)) |i| d.resources[i] = descriptor.resources[i];
devices[count] = d;
registrar[count] = owner;
count += 1;
return d.id;
}
+89 -10
View File
@@ -34,12 +34,27 @@ const platform = @import("platform");
const architecture = @import("architecture");
const devices_broker = @import("devices-broker.zig");
const log = @import("log.zig");
const heap = @import("heap.zig");
const page_size: u64 = abi.page_size;
const page_mask: u64 = page_size - 1;
const huge_page_size: u64 = 2 * 1024 * 1024;
/// One domain per claimed PCI function. 64 mirrors devices-broker's device cap.
/// The IOMMU's own translation-domain pool — one per claimed DMA-capable device.
///
/// No longer coupled to the device count. It was, by a comment and then by a comptime
/// assert, only because `confined` (one slot per device id) was sized by this same
/// constant; those are two unrelated quantities and making the device table dynamic
/// separated them. This one is genuinely the hardware's: both VT-d and AMD-Vi report
/// how many domains they support in a capability register, so the honest fix is to read
/// it rather than choose 64 — bounds-track-plan.md phase 4.
///
/// bound: IOMMU translation domains the kernel can hold at once
/// decided-by: hardware
/// protects: the statically sized domain pool
/// at-limit: refuse — ECONFINE; the claim is rolled back and the device is not driven,
/// because a claim that cannot be confined must not stand
/// observed-by: the claiming driver's own line naming ECONFINE
pub const maximum_domains = 64;
pub const invalid_domain: u16 = 0xFFFF;
@@ -94,18 +109,51 @@ pub fn init() void {
/// Per-claimed-device record: its private domain, so a driver's death tears down
/// exactly the domains it held.
const Confined = struct { active: bool = false, owner: u32 = 0, bdf: u16 = 0, domain: u16 = invalid_domain };
var confined: [maximum_domains]Confined = .{Confined{}} ** maximum_domains;
/// Indexed by **device id**, so it must cover every id the broker can mint — and the
/// broker's table has no ceiling any more, so neither can this. It grows on demand.
///
/// This used to be `[maximum_domains]`, sized by the *domain* constant purely because
/// device ids happened to stop at 64 as well. Two unrelated quantities sharing one
/// number: `domains` below is the IOMMU's own translation-domain pool, which the
/// hardware bounds and reports, while this is one slot per device the machine has.
/// A comptime assert held them together while both were fixed; making the device table
/// dynamic is what forced them apart, which is the assert having done its job.
var confined: []Confined = &.{};
/// Grow `confined` to cover `device_id`. False if the heap cannot — and the caller
/// treats that as a refusal to confine, never as permission.
fn reserveConfined(device_id: u64) bool {
if (device_id < confined.len) return true;
if (device_id >= std.math.maxInt(usize) / 2) return false; // absurd id; refuse rather than size to it
var wanted: usize = if (confined.len == 0) 64 else confined.len;
while (wanted <= device_id) wanted *= 2;
const grown = heap.allocator().realloc(confined, wanted) catch return false;
const previous = confined.len;
confined = grown;
for (confined[previous..]) |*record| record.* = .{};
return true;
}
/// Place a just-claimed PCI function under IOMMU translation on behalf of `owner`: give
/// it a private empty domain, seed it with the device's own firmware reserved region,
/// and attach. Its DMA buffers arrive afterward as explicit grants — the owner's own
/// `dma_alloc`'d regions are bound by the claim path (`mapForDevice`), and cross-process
/// buffers by `dma_bind`. false only if a domain can't be allocated — the caller rolls
/// the claim back (a claim that can't be confined must not stand). No-op success when no
/// IOMMU exists (fail-open).
/// buffers by `dma_bind`. false when the device cannot be confined — the caller rolls
/// the claim back (a claim that can't be confined must not stand).
///
/// **Fail-closed at the table's edge.** There is exactly one deliberate fail-open here:
/// a machine with no IOMMU, which is a fact about the hardware rather than the size of
/// anything. Running out of *room to record* a confinement is not that, and must refuse.
pub fn confineDevice(device_id: u64, bdf: u16, owner: u32) bool {
if (!active) return true;
if (device_id >= confined.len) return true; // unusual id; leave it to fail-open
if (!active) return true; // no IOMMU on this machine — nothing to confine with
// A device id past the end of the record table. This returned `true` — success —
// leaving the device outside every domain while telling the caller it was
// confined, and rolling nothing back. It is unreachable only while device ids stop
// at `confined.len`; moving the inventory out of the kernel and taking the domain
// count from the hardware both change that, and either would have made a silent
// unconfined DMA master out of every device past the 64th.
if (!reserveConfined(device_id)) return false;
const domain = domainCreate(owner, bdf) orelse return false;
// Firmware reserved region for this device, if any (real hardware; QEMU has none).
@@ -147,7 +195,7 @@ pub fn unmapForDevice(device_id: u64, physical: u64, len: u64) void {
/// own freshly-`dma_alloc`'d buffer into the devices it drives.
pub fn mapRegionForOwner(owner: u32, physical: u64, len: u64) void {
if (!active) return;
for (&confined) |*c| {
for (confined) |*c| {
if (c.active and c.owner == owner) _ = map(c.domain, physical, len);
}
}
@@ -158,7 +206,7 @@ pub fn mapRegionForOwner(owner: u32, physical: u64, len: u64) void {
/// domain other than its owner's.
pub fn unmapRegionEverywhere(physical: u64, len: u64) void {
if (!active) return;
for (&confined) |*c| {
for (confined) |*c| {
if (c.active) unmap(c.domain, physical, len);
}
}
@@ -166,9 +214,40 @@ pub fn unmapRegionEverywhere(physical: u64, len: u64) void {
/// A driver died or released its devices: tear down every domain it held (detach the
/// device, free the tables) so their DMA is blocked again and a restarted driver
/// re-claims cleanly. Runs BEFORE the broker claims and the DMA frames are released.
/// Re-point a device's existing confinement at a new owner, keeping its domain and
/// its attachment intact.
///
/// Delegation needs this: the device manager claims a device (which confines it, with
/// the manager as owner) and then transfers it to the driver. Without moving the
/// confinement record too, the domain stays the manager's — so the driver's DMA
/// buffers are never bound into it, its rings are invisible to the device, and every
/// transfer faults. Worse, a manager death would then tear down a domain a live driver
/// is using, and a driver death would leave one behind.
///
/// The domain is *not* rebuilt: the device stays attached throughout, so there is no
/// window in which it is translating through nothing.
pub fn reassign(device_id: u64, owner: u32) void {
if (!active) return;
if (device_id >= confined.len) return;
const record = &confined[@intCast(device_id)];
if (!record.active) return;
record.owner = owner;
}
/// The task a device's confinement is recorded against, or null if it has none. The
/// confinement's owner decides whose death tears the domain down, so a delegation that
/// moved the device but not this record would leave a live driver's domain destroyed by
/// its manager's exit — which is why `reassign` exists and why the suite asserts it.
pub fn confinementOwner(device_id: u64) ?u32 {
if (!active) return null;
if (device_id >= confined.len) return null;
const record = confined[@intCast(device_id)];
return if (record.active) record.owner else null;
}
pub fn releaseAllOwnedBy(owner: u32) void {
if (!active) return;
for (&confined) |*c| {
for (confined) |*c| {
if (c.active and c.owner == owner) {
detachDevice(c.bdf);
domainDestroy(c.domain);
+16 -9
View File
@@ -42,15 +42,22 @@ pub const MESSAGE_MAXIMUM: usize = 256;
pub const maximum_handles = scheduler.ipc_maximum_handles;
/// Errno-style failures, returned as `-value` in the system_call result register.
pub const EBADF: i64 = 1; // bad handle
pub const E2BIG: i64 = 2; // message exceeds MESSAGE_MAXIMUM
pub const EFAULT: i64 = 3; // buffer unmapped / out of the user half
pub const ENOENT: i64 = 4; // no such name
pub const ENOSPC: i64 = 5; // handle table full
pub const ENOMEM: i64 = 6; // out of memory
pub const EPEER: i64 = 7; // peer died before replying (its process exited or was killed)
pub const ESRCH: i64 = 8; // no such process (process_kill of an unknown/dead id)
pub const EPERM: i64 = 9; // not permitted (process_kill by anyone but the supervisor)
/// Restated from the shared kernel↔user ABI (system/abi.zig), because ring 3 reads
/// the same numbers — the same reason `notify_badge_bit` below is restated. New
/// codes are added *there*, which is where the space is documented.
pub const EBADF = abi.EBADF; // bad handle
pub const E2BIG = abi.E2BIG; // message exceeds MESSAGE_MAXIMUM
pub const EFAULT = abi.EFAULT; // buffer unmapped / out of the user half
pub const ENOENT = abi.ENOENT; // no such name
pub const ENOSPC = abi.ENOSPC; // a kernel table is full
pub const ENOMEM = abi.ENOMEM; // out of memory
pub const EPEER = abi.EPEER; // peer died before replying (its process exited or was killed)
pub const ESRCH = abi.ESRCH; // no such process (process_kill of an unknown/dead id)
pub const EPERM = abi.EPERM; // not permitted (process_kill by anyone but the supervisor)
pub const ENODEV = abi.ENODEV; // no such device id
pub const ECHILDREN = abi.ECHILDREN; // this parent is at its child cap
pub const ERANGE = abi.ERANGE; // a resource escapes its parent's window
pub const ECONFINE = abi.ECONFINE; // the device could not be placed under IOMMU translation
/// A badge with this bit set is an asynchronous notification (e.g. an IRQ), not a
/// message from a client — there is no reply owed. The low bits carry the source
+64 -1
View File
@@ -279,6 +279,22 @@ fn kmain(boot_information: *const BootInformation) noreturn {
log.print(" cpus : {d} usable core(s); 1 running (BSP), {d} AP(s) parked (SMP bring-up pending)\n", .{ cores.len, if (cores.len > 0) cores.len - 1 else 0 });
if (platform.cpusDropped() > 0)
log.print(" cpus : WARNING {d} core(s) beyond pool cap dropped\n", .{platform.cpusDropped()});
// The supervisor-execution posture, stated plainly at every boot. Every core
// sets the bit during its own bring-up (architecture/x86_64/per-cpu.zig); the
// BSP answers for the machine here, because the feature is a property of the
// CPU model, not of an individual core. Fail-open like the IOMMU: a CPU without
// it still boots, it just boots unhardened, and says so.
if (architecture.supervisorExecutePreventionEnabled())
log.write(" smep : enabled - ring 0 cannot execute user pages\n")
else
log.write(" smep : absent - ring-0 execution of user pages unprevented\n");
// The supervisor-access posture, the same way. Its second half is a boot-time
// patch (the `clac` at the interrupt entry), so "absent" here covers both a
// CPU without the feature and a patch that could not be applied.
if (architecture.supervisorAccessPreventionEnabled())
log.write(" smap : enabled - ring 0 reaches user memory only through the checked copy layer\n")
else
log.write(" smap : absent - ring-0 access to user pages unprevented\n");
// The DMA-isolation posture, stated plainly at every boot. When a unit exists,
// iommu.init already logged its enable block above; here we only state the
// fail-open case, so a boot without the line is a boot with translation on.
@@ -509,6 +525,40 @@ fn exitReasonForVector(vector: u64) abi.ExitReason {
};
}
/// A fault *at* the interrupt return itself has one piece of evidence worth
/// having: the five words the CPU refused to load. `iretq` reports a selector in
/// the error code but never says which of them carried it, and the frame is
/// otherwise gone the moment the machine halts — so print it while it is still
/// on the stack. Silent for every other fault, which is nearly all of them.
///
/// Two honesty notes ride along. On the ring-3 path the entry stub has already
/// swapped in the user's GS base by the time this instruction runs, so the task
/// and core named above came from user-controlled state and mean nothing; the
/// frame's own CS says which case this is, so say so rather than let the reader
/// trust a number. And the stack is only read after checking it is a kernel
/// address, because a reporter that faults tells you nothing at all.
fn reportPendingReturnFrame(state: *const architecture.CpuState) void {
const site = @intFromPtr(@extern(*const anyopaque, .{ .name = "isr_return_iretq" }));
if (architecture.instructionPointer(state) != site) return;
const sp = architecture.stackPointer(state);
if (sp < 0xFFFF_8000_0000_0000 or sp % 8 != 0) {
fatalPrint(" pending return frame: stack pointer unusable\n", .{});
return;
}
const frame: [*]const u64 = @ptrFromInt(sp);
fatalPrint(" the return this refused (rip, cs, rflags, rsp, ss):\n", .{});
fatalPrint(" rip : 0x{x:0>16}\n", .{frame[0]});
fatalPrint(" cs : 0x{x:0>4} (rpl {d})\n", .{ frame[1], frame[1] & 3 });
fatalPrint(" rflags : 0x{x:0>16}\n", .{frame[2]});
fatalPrint(" rsp : 0x{x:0>16}\n", .{frame[3]});
fatalPrint(" ss : 0x{x:0>4} (rpl {d})\n", .{ frame[4], frame[4] & 3 });
if (frame[1] & 3 == 3) {
fatalPrint(" note: returning to ring 3, so the user GS base is installed —\n", .{});
fatalPrint(" the task and core reported above are not to be believed.\n", .{});
}
}
fn onException(state: *const architecture.CpuState) noreturn {
if (architecture.fromUser(state) and scheduler.currentIsUserProcess() and recoverableFault(state.vector)) {
statusPrint("\n/system/kernel: process {d} ({s}) killed by {s} (vector {d}) on core {d}\n", .{ scheduler.currentId(), scheduler.current().name(), architecture.exceptionName(state.vector), state.vector, scheduler.currentCpuIndex() });
@@ -532,6 +582,7 @@ fn onException(state: *const architecture.CpuState) noreturn {
fatalPrint(" IP : 0x{x:0>16}\n", .{architecture.instructionPointer(state)});
fatalPrint(" SP : 0x{x:0>16}\n", .{architecture.stackPointer(state)});
if (architecture.faultAddress(state)) |address| fatalPrint(" fault addr : 0x{x:0>16}\n", .{address});
reportPendingReturnFrame(state);
var buffer: [128]u8 = undefined;
log.recordPanic(std.fmt.bufPrint(&buffer, "CPU exception {s} (vector {d}) on core {d} at IP 0x{x}", .{ architecture.exceptionName(state.vector), state.vector, core, architecture.instructionPointer(state) }) catch "cpu exception");
@@ -545,11 +596,23 @@ fn onException(state: *const architecture.CpuState) noreturn {
/// Freestanding has no OS to receive a panic. Emit it to every output sink, drop a
/// POST code + a persistent breadcrumb (so a post-mortem can recover it even with
/// no live console), then halt. Assumes no console — the sinks self-guard.
/// Set on entry to the panic handler, and never cleared: a panic is terminal, so
/// the only reason to see this true is that reporting the first one faulted.
var panicking: bool = false;
pub const panic = std.debug.FullPanic(struct {
fn panic(message: []const u8, first_trace_address: ?usize) noreturn {
_ = first_trace_address;
// A panic while reporting a panic: stop where we are. Whatever the first
// one already printed is the diagnosis, and every line after this point
// risks faulting again — which on real hardware means a reset, taking the
// message off the screen of the person who needed to read it. Halting
// with a partial report beats rebooting with none.
if (panicking) architecture.halt();
panicking = true;
log.checkpoint(cp_panic);
log.recordPanic(message);
log.recordPanic(message); // the breadcrumb first: it survives what follows
fatal("\nKERNEL PANIC: "); // a panic outranks any display service holding the screen
fatal(message);
fatal("\n");
+8
View File
@@ -26,6 +26,14 @@ pub const RegisterAccess = acpi.RegisterAccess;
pub const IsoEntry = acpi.IsoEntry;
pub const Cpu = acpi.Cpu;
/// Where a PCI BAR may legitimately live: the holes in the firmware memory map.
/// Firmware-agnostic — it takes a boot-handoff map, not an ACPI table — and pure, so
/// the kernel self-test can drive it with a synthetic map. That is the only way to
/// check the invariant that matters here: an aperture must never cover memory the
/// firmware described, because containment would then admit a BAR over live RAM.
pub const AddressRange = acpi.AddressRange;
pub const largestHolesBelow4G = acpi.largestHolesBelow4G;
/// The FADT power register map discovery extracted (PM1 control, reset register),
/// for kernel reboot and diagnostics. Sleep-state values are userspace's (S5 is
/// owned by the ring-3 acpi service), so they are not here.
+198 -35
View File
@@ -124,15 +124,26 @@ pub const maximum_mount_rewrite = 32;
const auxiliary_vector_null: u64 = 0; // AT_NULL — end of the vector
const auxiliary_vector_page_size: u64 = 6; // AT_PAGESZ
// The hand-assembled user program blob (isr.s, .rodata) — the isolation probe.
// The hand-assembled user program blobs (isr.s, .rodata) — the isolation probes.
const pf_start = @extern([*]const u8, .{ .name = "user_pf_start" });
const pf_end = @extern([*]const u8, .{ .name = "user_pf_end" });
const sysret_start = @extern([*]const u8, .{ .name = "user_sysret_start" });
const sysret_end = @extern([*]const u8, .{ .name = "user_sysret_end" });
/// The isolation-proof program: reads a kernel-only page, must #PF.
pub fn pfBlob() []const u8 {
return pf_start[0 .. @intFromPtr(pf_end) - @intFromPtr(pf_start)];
}
/// The SYSRET-guard program: two system calls, the second of which must be copied
/// so that it ends at the last executable byte of the user half — its return
/// address is then the first non-canonical address. Ends with `syscall`, so the
/// caller places it at `page_size - len` inside the page at `user_half_end -
/// page_size`; anywhere else and it proves nothing.
pub fn nonCanonicalReturnBlob() []const u8 {
return sysret_start[0 .. @intFromPtr(sysret_end) - @intFromPtr(sysret_start)];
}
/// What debug_write syscalls produced (accumulated), and the exit system_call's code.
pub var write_buffer: [256]u8 = undefined;
pub var write_len: usize = 0;
@@ -179,6 +190,15 @@ pub fn init() void {
scheduler.timer_tick_hook = timerSweepLocked;
scheduler.group_exit_hook = groupExitLocked;
scheduler.space_mapping_release_hook = dropSpaceMappingHook;
// The broker owns devices; the process layer owns the task table. It asks whether a
// lender is still alive before handing a dead driver's device back to it.
devices_broker.task_alive_hook = taskAliveLocked;
}
/// Whether `id` names a live task. The broker calls this through its hook when
/// deciding if a dead holder's device can go back to the task that lent it.
fn taskAliveLocked(id: u32) bool {
return scheduler.taskByIdLocked(id) != null;
}
/// Return -1 (as an unsigned bit pattern) in the system_call result register.
@@ -238,6 +258,7 @@ fn system_call(state: *architecture.CpuState) void {
.irq_bind => systemIrqBind(state),
.irq_ack => systemIrqAck(state),
.device_register => systemDeviceRegister(state),
.device_transfer => systemDeviceTransfer(state),
.system_spawn => systemSpawn(state),
.dma_alloc => systemDmaAlloc(state),
.dma_free => systemDmaFree(state),
@@ -380,7 +401,16 @@ fn systemDeviceEnumerate(state: *architecture.CpuState) void {
var copied: u64 = 0;
var start: usize = 0;
while (copied < cap) {
const filled = devices_broker.enumerateFrom(start, &chunk);
// Snapshot each chunk under the lock: ring-3 device_register grows the table
// with realloc on other cores, so an unlocked read walks a slice that may
// already have been freed — and pairs a fresh `count` with a stale slice.
// The user copy stays outside; the chunk is the kernel's own bytes, and the
// lock windows stay as small as one chunk.
const filled = filled: {
const flags = sync.enter();
defer sync.leave(flags);
break :filled devices_broker.enumerateFrom(start, &chunk);
};
if (filled == 0) break;
start += filled;
const take = @min(@as(u64, filled), cap - copied);
@@ -388,39 +418,109 @@ fn systemDeviceEnumerate(state: *architecture.CpuState) void {
if (!user_memory.copyToUser(t.address_space, buffer_ptr + copied * sz, bytes)) return failErr(state, ipc.EFAULT);
copied += take;
}
architecture.setSystemCallResult(state, devices_broker.deviceCount());
const total = total: {
const flags = sync.enter();
defer sync.leave(flags);
break :total devices_broker.deviceCount();
};
architecture.setSystemCallResult(state, total);
}
/// device_claim(id) -> 0/-1: take exclusive ownership of a device for this process.
/// device_claim(id) -> 0/-errno: take exclusive ownership of a device for this process.
/// `-ENODEV` no such id, `-EBUSY` a live task already owns it, `-ECONFINE` the claim
/// could not be placed under IOMMU translation and was rolled back.
fn systemDeviceClaim(state: *architecture.CpuState) void {
const device_id = architecture.systemCallArg(state, 0);
const claim_flags = sync.enter();
defer sync.leave(claim_flags);
if (devices_broker.claim(device_id, scheduler.current().id)) {
// Confine the device's DMA before the driver can program it: a PCI function
// becomes reachable to the IOMMU only once claimed (until now its DMA is
// blocked). A claim that cannot be confined must not stand — roll it back —
// since the whole point is that claiming a DMA device is no longer equivalent
// to ring 0. No-op when no IOMMU exists (fail-open).
if (devices_broker.pciAddressOf(device_id)) |bdf| {
const owner = scheduler.current().id;
if (!iommu.confineDevice(device_id, bdf, owner)) {
_ = devices_broker.unclaim(device_id, owner);
return fail(state);
}
// Bind the buffers this task allocated before claiming the device (a driver
// that dma_alloc'd its rings, then claimed the controller).
dmaBindOwnerRegionsInto(owner, device_id);
devices_broker.claim(device_id, scheduler.current().id) catch |e|
return failErr(state, devices_broker.claimErrnoOf(e));
// Confine the device's DMA before the driver can program it: a PCI function
// becomes reachable to the IOMMU only once claimed (until now its DMA is
// blocked). A claim that cannot be confined must not stand — roll it back —
// since the whole point is that claiming a DMA device is no longer equivalent
// to ring 0. No-op when no IOMMU exists (fail-open).
if (devices_broker.pciAddressOf(device_id)) |bdf| {
const owner = scheduler.current().id;
if (!iommu.confineDevice(device_id, bdf, owner)) {
_ = devices_broker.unclaim(device_id, owner);
// Its own errno: "nobody could confine this" is a different world from
// "someone else already has it", and a driver that cannot tell them apart
// cannot report the one that means the machine's DMA protection ran out.
return failErr(state, ipc.ECONFINE);
}
// A display service just took the framebuffer — quiesce the bootstrap console
// so the kernel and the service don't scribble over each other's pixels. The
// claim releases (and the console resumes) automatically if the service dies;
// see releaseTaskResourcesLocked.
if (devices_broker.displayDevice()) |display_id| {
if (device_id == display_id) console.setSuppressed(true);
}
architecture.setSystemCallResult(state, 0);
} else fail(state);
// Bind the buffers this task allocated before claiming the device (a driver
// that dma_alloc'd its rings, then claimed the controller).
dmaBindOwnerRegionsInto(owner, device_id);
}
// A display service just took the framebuffer — quiesce the bootstrap console
// so the kernel and the service don't scribble over each other's pixels. The
// claim releases (and the console resumes) automatically if the service dies;
// see releaseTaskResourcesLocked.
if (devices_broker.displayDevice()) |display_id| {
if (device_id == display_id) console.setSuppressed(true);
}
architecture.setSystemCallResult(state, 0);
}
/// device_transfer(device_id, task_id) -> 0/-errno: give a device you hold to another
/// task. The mechanism behind delegation — the device manager claims what discovery
/// seeded and hands each device to the driver it matched, so assignment stops being
/// first-come-first-served (docs/os-development/device-authority.md).
///
/// The kernel's whole rule is *you may give away what you hold*. It has no notion of
/// which task is the device manager, and deliberately gains none: a binary name in the
/// kernel is not something that cannot safely live in user space.
fn systemDeviceTransfer(state: *architecture.CpuState) void {
const device_id = architecture.systemCallArg(state, 0);
const task_id: u32 = @truncate(architecture.systemCallArg(state, 1));
const flags = sync.enter();
defer sync.leave(flags);
// The recipient must exist, or the device would be moved to nobody and become
// unreachable for the rest of the boot — no path un-holds a device but task death.
if (scheduler.taskByIdLocked(task_id) == null) return failErr(state, ipc.ESRCH);
const errno = giveDeviceLocked(device_id, scheduler.current().id, task_id);
if (errno != 0) return failErr(state, errno);
architecture.setSystemCallResult(state, 0);
}
/// Move a device from `from` to `to` **with its IOMMU confinement** — the shared body
/// of `device_transfer` and spawn's give. Returns 0 or the errno to refuse with.
/// Caller holds the big kernel lock, and has verified the recipient exists.
///
/// The confinement must move with the device. Usually the giver confined it at claim,
/// so the domain exists, the device stays attached throughout, and `reassign` re-points
/// the record. But after a driver's death the loan came back with the domain torn down
/// (`releaseAllOwnedBy` runs before the broker returns the device to its lender) — so a
/// re-delegation finds no active record, and a bare `reassign` would no-op and hand the
/// device over silently unconfined: V=0 device-table entry, no domain, every later
/// `dma_alloc` bound into nothing. That is the exact fail-open the fail-closed claim
/// exists to remove, so the same rule applies here: confine afresh, and a give that
/// cannot be confined must not stand.
///
/// Order matters: the checks run first (nothing has mutated, nothing to roll back),
/// the confinement second (its failure refuses cleanly), the move last (it cannot fail
/// once `canTransfer` passed — same lock hold). Public for the in-kernel iommu test,
/// which drives the death-and-respawn sequence against it directly.
pub fn giveDeviceLocked(device_id: u64, from: u32, to: u32) i64 {
devices_broker.canTransfer(device_id, from) catch |e|
return devices_broker.transferErrnoOf(e);
if (devices_broker.pciAddressOf(device_id)) |bdf| {
if (iommu.confinementOwner(device_id) == null and !iommu.confineDevice(device_id, bdf, to))
return ipc.ECONFINE;
}
devices_broker.transfer(device_id, from, to) catch |e|
return devices_broker.transferErrnoOf(e); // unreachable: checked above under this lock
if (devices_broker.pciAddressOf(device_id)) |_| {
iommu.reassign(device_id, to);
// Bind whatever the receiver has already allocated — the same courtesy the
// claim path does for a driver that dma_alloc'd its rings before claiming.
dmaBindOwnerRegionsInto(to, device_id);
}
return 0;
}
/// mmio_map(device_id, resource_index) -> virtual_address: map a claimed device's MMIO window into
@@ -920,17 +1020,21 @@ fn systemDeviceRegister(state: *architecture.CpuState) void {
const parent_id = architecture.systemCallArg(state, 0);
const descriptor_ptr = architecture.systemCallArg(state, 1);
const t = scheduler.current();
if (t.address_space == 0) return fail(state);
if (t.address_space == 0) return failErr(state, ipc.EPERM);
var descriptor: device_abi.DeviceDescriptor = undefined;
if (!ipc.copyFromUser(t.address_space, descriptor_ptr, std.mem.asBytes(&descriptor))) return fail(state);
if (!ipc.copyFromUser(t.address_space, descriptor_ptr, std.mem.asBytes(&descriptor))) return failErr(state, ipc.EFAULT);
// Under the big kernel lock: the broker's table is also mutated by the
// death sweep (releaseAllOwnedBy) and read by enumerate on other cores —
// ring-3 registration (M19) made those genuinely concurrent.
const flags = sync.enter();
defer sync.leave(flags);
const id = devices_broker.register(parent_id, t.id, &descriptor) catch return fail(state);
// Each refusal carries its own errno (devices-broker.errnoOf) — the bus driver
// logs which rule stopped it, so "this parent is full" is never again mistaken
// for "the table is full" or "that resource escapes your window".
const id = devices_broker.register(parent_id, t.id, &descriptor) catch |e|
return failErr(state, devices_broker.errnoOf(e));
architecture.setSystemCallResult(state, id);
}
@@ -960,6 +1064,13 @@ fn systemSpawn(state: *architecture.CpuState) void {
const arguments_ptr = architecture.systemCallArg(state, 2);
const arguments_len = architecture.systemCallArg(state, 3);
const exit_handle = architecture.systemCallArg(state, 4);
// A device the caller holds and gives to the child. Fused into the spawn rather
// than transferred after it, because a separate transfer leaves a window in which
// the child is running and does not yet hold its device — a race that would close
// on one machine and open on another, which is the failure shape this whole track
// exists to remove (docs/bounds-track-plan.md, "the grant rides system_spawn").
// Here the child cannot observe the gap: it does not exist until it holds it.
const device_to_give = architecture.systemCallArg(state, 5);
const t = scheduler.current();
if (len == 0 or len > scheduler.maximum_task_name or ptr >= user_half_end or ptr + len > user_half_end) return fail(state);
if (arguments_len > maximum_argument_bytes) return fail(state);
@@ -1004,7 +1115,40 @@ fn systemSpawn(state: *architecture.CpuState) void {
}
}
// Refuse before creating anything if the device is not the caller's to give — a
// spawn that half-succeeds would leave a child running without the hardware it was
// spawned for, which is worse than not spawning it. Read under the lock; it drops
// across the spawn, so the give below re-checks under its own hold — this one only
// spares creating a child that was always going to be killed.
if (device_to_give != abi.no_device) {
const flags = sync.enter();
defer sync.leave(flags);
devices_broker.canTransfer(device_to_give, t.id) catch |e|
return failErr(state, devices_broker.transferErrnoOf(e));
}
const child = spawnProcessSupervised(item.blob, 4, argv[0..argc], t.id, exit_endpoint) catch return fail(state);
if (device_to_give != abi.no_device) {
// The give runs in one lock hold: check, confine, move (giveDeviceLocked).
// spawnProcessSupervised took and released the lock internally, so the
// pre-check above holds no authority here. The child cannot outrun the
// hand-over — its first device syscall serializes behind this same lock.
const errno = give: {
const flags = sync.enter();
defer sync.leave(flags);
break :give giveDeviceLocked(device_to_give, t.id, child);
};
if (errno != 0) {
// The device stopped being the caller's between the pre-check and here, or
// its confinement was refused. A child running without the hardware it was
// spawned for is worse than no child — undo the spawn. The kill's ownership
// sweep also releases anything the give half-did (a fresh confinement dies
// with the child).
_ = killProcess(t.id, child);
return failErr(state, errno);
}
}
architecture.setSystemCallResult(state, child);
}
@@ -1520,7 +1664,15 @@ pub fn exitReasonOf(caller_id: u32, target_id: u32) i64 {
/// subscriptions — that must release what a dead client held and cannot learn it
/// any other way (a client that simply never calls again looks like silence).
/// Bounded like every kernel table; each entry holds its own endpoint reference.
const exit_subscriber_capacity = 8;
///
/// Sixteen, not eight: a subscription is now what *every* provider with
/// per-client state uses to release it — the FAT server's open files, the input,
/// power and device-manager subscriber tables (the service harness subscribes for
/// them), the compositor's layers, and each USB controller driver's device tokens.
/// A single boot already fields six, and a machine with several xHCI controllers
/// fields one per controller, so the old ceiling was within two of a service
/// silently losing its sweep.
const exit_subscriber_capacity = 16;
const ExitSubscriber = struct { endpoint: *ipc.Endpoint, owner: u32 };
var exit_subscribers: [exit_subscriber_capacity]?ExitSubscriber = .{null} ** exit_subscriber_capacity;
@@ -1538,16 +1690,27 @@ fn systemProcessSubscribe(state: *architecture.CpuState) void {
if (t.address_space == 0) return fail(state);
const endpoint = ipc.resolveHandle(t, architecture.systemCallArg(state, 0)) orelse return failErr(state, ipc.EBADF);
if (!ipc.ownedBy(endpoint, t)) return failErr(state, ipc.EPERM);
const result = subscribeExits(endpoint, t.id);
if (result < 0) return failErr(state, @intCast(-result));
architecture.setSystemCallResult(state, 0);
}
/// Take a slot in the published-exit table for `endpoint`, owned by task `owner`.
/// The body of `process_subscribe` minus the authorization, so a kernel test can
/// exercise the fan-out (several subscribers, one death, every one notified) that
/// every provider's release-what-the-dead-client-held sweep is built on. Returns
/// 0, or -ENOSPC.
pub fn subscribeExits(endpoint: *ipc.Endpoint, owner: u32) i64 {
const flags = sync.enter();
defer sync.leave(flags);
for (&exit_subscribers) |*slot| {
if (slot.* == null) {
endpoint.refcount += 1; // the slot's own reference, dropped on unsubscribe-by-death
slot.* = .{ .endpoint = endpoint, .owner = t.id };
return architecture.setSystemCallResult(state, 0);
slot.* = .{ .endpoint = endpoint, .owner = owner };
return 0;
}
}
failErr(state, ipc.ENOSPC);
return -ipc.ENOSPC;
}
/// signal_bind(endpoint): nominate where this process's signals arrive — the
+703 -11
View File
@@ -51,6 +51,15 @@ fn check(name: []const u8, ok: bool) void {
}
}
/// `devices_broker.claim` reduced to a bool, for the `check` assertions below. The
/// broker returns `ClaimError` so ring 3 can tell "stale id" from "someone already
/// owns it" (the errno space in system/abi.zig); a test that only asserts the claim
/// succeeded does not care which, and the ones that do match the error directly.
fn claimOk(id: u64, owner: u32) bool {
devices_broker.claim(id, owner) catch return false;
return true;
}
/// Emit the overall result line the harness matches, then the done sentinel.
fn result() void {
log("DANOS-TEST-RESULT: {s} ({d} passed, {d} failed)\n", .{
@@ -140,6 +149,12 @@ pub fn run(case: []const u8, boot_information: *const BootInformation) void {
faultNoExecute();
} else if (eql(case, "fault-null")) {
faultNull();
} else if (eql(case, "fault-smep")) {
faultSmep();
} else if (eql(case, "fault-smap")) {
faultSmap();
} else if (eql(case, "sysret-canonical")) {
sysretCanonicalTest();
} else if (eql(case, "usermem")) {
userMemTest();
} else if (eql(case, "user-memory")) {
@@ -244,12 +259,20 @@ pub fn run(case: []const u8, boot_information: *const BootInformation) void {
irqFreeTest();
} else if (eql(case, "containment")) {
containmentTest();
} else if (eql(case, "apertures")) {
apertureTest();
} else if (eql(case, "device-transfer")) {
deviceTransferTest(boot_information);
} else if (eql(case, "device-authority")) {
deviceAuthorityTest(boot_information);
} else if (eql(case, "device-manager")) {
deviceManagerTest(boot_information);
} else if (eql(case, "protocol-registry")) {
protocolRegistryTest(boot_information);
} else if (eql(case, "protocol-denied")) {
protocolDeniedTest(boot_information);
} else if (eql(case, "protocol-conformance")) {
protocolConformanceTest(boot_information);
} else if (eql(case, "reboot")) {
rebootTest();
} else {
@@ -763,6 +786,15 @@ fn sleepTest() void {
// --- SMP parallelism ------------------------------------------------------
var seen_core = [_]bool{false} ** 8;
/// Whether the core this worker ran on had SMEP on in its own CR4. Recorded per
/// core because CR4 is per-core state: the boot processor enabling it says
/// nothing about the ones the trampoline brought up, and the whole hardening is
/// only as wide as its narrowest core.
var seen_core_smep = [_]bool{false} ** 8;
/// The same, for SMAP. A core that came up without it would still be able to read
/// and write user pages from ring 0 while every other core could not — a hole
/// whose only symptom is that the tripwire never trips there.
var seen_core_smap = [_]bool{false} ** 8;
var smp_running: bool = true;
/// A worker that, while running, records which core it's executing on. Spread across
@@ -771,7 +803,11 @@ fn smpWorker() void {
const p: *volatile bool = &smp_running;
while (p.*) {
const c = scheduler.currentCpuIndex();
if (c < seen_core.len) seen_core[c] = true;
if (c < seen_core.len) {
seen_core[c] = true;
seen_core_smep[c] = architecture.supervisorExecutePreventionEnabled();
seen_core_smap[c] = architecture.supervisorAccessPreventionEnabled();
}
}
scheduler.exit();
}
@@ -801,6 +837,36 @@ fn smpTest() void {
log("DANOS-SMP: workers ran on {d} distinct core(s)\n", .{cores_seen});
check("tasks ran on multiple cores in parallel", cores_seen >= 2);
// Every core that ran work must have had SMEP on, not just the one that
// booted: an application processor climbs through the trampoline with CR4
// bare and sets the bit itself on the way in, so a hardening that reached
// only the boot processor would leave every other core able to execute a
// user page in ring 0 — and would look identical from the boot log. Only
// asserted where the platform has SMEP at all, so a machine without it
// still passes rather than failing for the one reason that is not a bug.
if (architecture.supervisorExecutePreventionEnabled()) {
var hardened: u32 = 0;
for (seen_core, seen_core_smep) |ran, smep| {
if (ran and smep) hardened += 1;
}
log("DANOS-SMP: {d} of {d} core(s) had supervisor execute prevention\n", .{ hardened, cores_seen });
check("every core that ran work had SMEP enabled", hardened == cores_seen);
}
// And the same for SMAP, for the same reason and with one more of its own: the
// bit is refused until the boot processor has patched the `clac` into the shared
// interrupt entry, so a core reporting SMAP on is also a core confirming it came
// up after that patch — the ordering the whole scheme rests on, checked from the
// far end. Gated on the running core the same way, so a CPU without SMAP passes.
if (architecture.supervisorAccessPreventionEnabled()) {
var hardened: u32 = 0;
for (seen_core, seen_core_smap) |ran, smap| {
if (ran and smap) hardened += 1;
}
log("DANOS-SMP: {d} of {d} core(s) had supervisor access prevention\n", .{ hardened, cores_seen });
check("every core that ran work had SMAP enabled", hardened == cores_seen);
}
// Bring-up is done, so the trampoline frame must be inert: zeroed (no stale code)
// and non-executable (W^X restored). It's armed only while a core is climbing.
const tramp = architecture.trampolinePage();
@@ -1381,6 +1447,79 @@ fn iommuTest() void {
} else {
check("scratch domain allocated", false);
}
// Delegation moves a device between tasks, and the IOMMU confinement must move
// with it. When it did not, the driver's DMA rings were never bound into the
// device's domain and every transfer faulted — but two worse consequences were
// latent and invisible to those tests: the domain still named the *giver*, so the
// giver's death would tear down a domain a live driver was using, and the
// receiver's death would leave one behind. Asserted directly here rather than
// inferred from the USB cases going green.
// This case runs no pci-bus, so there are no PCI functions to confine — and a
// silently skipped assertion is worse than none. Register one the way pci-bus does:
// a child of the host bridge whose resource 0 is a 4 KiB config window inside the
// bridge's ECAM, which is what `pciAddressOf` derives a requester id from.
var iommu_table: [64]device_abi.DeviceDescriptor = undefined;
const iommu_total = devices_broker.enumerate(&iommu_table);
const bridge: ?device_abi.DeviceDescriptor = for (iommu_table[0..@min(iommu_total, iommu_table.len)]) |d| {
if (d.class == @intFromEnum(device_abi.DeviceClass.pci_host_bridge) and d.resource_count >= 2) break d;
} else null;
check("the kernel seeded a PCI host bridge to parent a function under", bridge != null);
const subject: ?u64 = if (bridge) |b| blk: {
const me_bridge = scheduler.currentId();
if (!claimOk(b.id, me_bridge)) break :blk null;
var function = std.mem.zeroes(device_abi.DeviceDescriptor);
function.class = @intFromEnum(device_abi.DeviceClass.pci_device);
function.pci_class = device_abi.no_pci_class;
function.resource_count = 1;
function.resources[0] = .{
.kind = @intFromEnum(device_abi.ResourceKind.memory),
.start = b.resources[0].start, // the first config slot in the ECAM window
.len = 4096,
};
break :blk devices_broker.register(b.id, me_bridge, &function) catch null;
} else null;
check("a PCI function exists to confine", subject != null);
if (subject) |device_id| {
check("a device starts unconfined", iommu.confinementOwner(device_id) == null);
const me = scheduler.currentId();
check("confining records the owner", iommu.confineDevice(device_id, devices_broker.pciAddressOf(device_id).?, me));
check("the confinement names the confiner", iommu.confinementOwner(device_id) == me);
iommu.reassign(device_id, me + 1000);
check("reassign moves the confinement to the new holder", iommu.confinementOwner(device_id) == me + 1000);
check("and the previous holder no longer owns it", iommu.confinementOwner(device_id) != me);
iommu.releaseAllOwnedBy(me + 1000);
check("the new holder's death tears the domain down", iommu.confinementOwner(device_id) == null);
// The restart hole. A driver's death returns its device to the lender with the
// domain torn down (asserted just above) — so the NEXT delegation of the same
// device finds no active confinement record, and the transfer path's bare
// `reassign` no-ops: the respawned driver would run the device with a V=0
// device-table entry and no domain, silently unconfined. The give path must
// confine afresh in that case, exactly as a first claim would.
check("the lender holds the returned device", claimOk(device_id, me));
const driver: u32 = me + 2000;
check("delegating it confines it to the receiver", process.giveDeviceLocked(device_id, me, driver) == 0);
check("the give's confinement names the receiver", iommu.confinementOwner(device_id) == driver);
// The receiver dies: confinement torn down first, then the broker loans the
// device back to the lender — the same order releaseTaskResourcesLocked runs.
iommu.releaseAllOwnedBy(driver);
devices_broker.releaseAllOwnedBy(driver);
check("death returns the loan to the lender", devices_broker.ownerOf(device_id) == me);
check("and leaves the device unconfined", iommu.confinementOwner(device_id) == null);
// The regression this guards: re-delegation after that death.
const respawned: u32 = me + 3000;
check("re-delegation after the death succeeds", process.giveDeviceLocked(device_id, me, respawned) == 0);
check(
"and the respawned driver's device is confined, not silently naked",
iommu.confinementOwner(device_id) == respawned,
);
iommu.releaseAllOwnedBy(respawned);
devices_broker.releaseAllOwnedBy(respawned);
_ = devices_broker.unclaim(device_id, me);
}
log("DANOS-IOMMU: enabled base=0x{x} domains active\n", .{pinfo.iommu_base});
result();
}
@@ -1424,7 +1563,7 @@ fn ioPortTest() void {
check("discovered the acpi-tables I/O window", true);
const me = scheduler.current();
check("claimed the io_port device", devices_broker.claim(id, me.id));
check("claimed the io_port device", claimOk(id, me.id));
check("an in-range access resolves to port 0x64", process.resolveIoPort(me, id, found_res, 0x64, 1) == 0x64);
check("a 4-byte access at the last port is refused", process.resolveIoPort(me, id, found_res, 0xFFFF, 4) == null);
check("an out-of-range offset is refused", process.resolveIoPort(me, id, found_res, 0x10000, 1) == null);
@@ -1639,6 +1778,99 @@ fn faultRecoveryTest(boot_information: *const BootInformation) void {
result();
}
/// Spawn a ring-3 process whose second system call has to return to a NON-canonical
/// address — the SYSRET hazard, staged the way a hostile program would stage it.
/// The blob is copied to the *end* of the last canonical page of the user half, so
/// its final `syscall` occupies the last two bytes ring 3 can execute and the return
/// RIP the CPU hands the kernel is `user_half_end` itself, the first non-canonical
/// address. Hand-built (address space, code page RO+X, stack RW+NX) like
/// `spawnFaultingProcess` — a raw blob is not an ELF `spawnProcess` could load.
/// Returns the process id, or null if any allocation failed.
fn spawnNonCanonicalReturnProcess() ?u32 {
const blob = process.nonCanonicalReturnBlob();
const code_virtual = process.user_half_end - abi.page_size; // the last canonical page
const entry = code_virtual + abi.page_size - blob.len; // ends flush with the page
const flags = sync.enter();
defer sync.leave(flags);
const address_space = architecture.createAddressSpace() orelse return null;
const code_frame = pmm.alloc() orelse {
architecture.destroyAddressSpace(address_space);
return null;
};
// Fill through the physmap (the user mapping is read-only); int3 everywhere the
// blob doesn't cover, so a stray entry traps instead of sliding into it.
const code: [*]u8 = @ptrFromInt(boot_handoff.physicalToVirtual(code_frame));
@memset(code[0..abi.page_size], 0xCC);
@memcpy(code[abi.page_size - blob.len .. abi.page_size], blob);
architecture.mapUserPageInto(address_space, code_virtual, code_frame, false, true); // RO + X
const stack_frame = pmm.alloc() orelse {
architecture.destroyAddressSpace(address_space); // frees code_frame too — it's mapped
return null;
};
architecture.mapUserPageInto(address_space, process.stack_base_virtual, stack_frame, true, false); // RW + NX
// Supervised by the calling test task, so exitReasonOf can read the verdict.
return scheduler.spawnUserLocked(address_space, entry, process.stack_base_virtual + abi.page_size, 0, 4, "sysret-probe", scheduler.currentId(), null, 0) orelse {
architecture.destroyAddressSpace(address_space);
return null;
};
}
/// The SYSRET canonical-RIP guard (docs/os-development/smep-smap.md, "Adjacent,
/// deliberately separate"): a process must not be able to make the kernel fault on
/// its own way out of a system call. `sysretq` with a non-canonical RIP in RCX #GPs
/// *in ring 0* on Intel — on the kernel stack, with the user's GS base already
/// installed — so the exit path checks the return address first and returns through
/// `iretq` instead, which faults in ring 3 where a bad address is just a dead
/// process.
///
/// The probe reaches the hazard the way an attacker would: its `syscall` is the last
/// two bytes of executable address space, so the return address the CPU saves is the
/// first non-canonical one. Three things then have to be true — the guard fired, the
/// *process* died of a protection fault (so the fault landed in ring 3, not in the
/// kernel), and this task is still here to say so.
///
/// The counter is what makes this a regression test rather than a decoration.
/// Measured with the guard's branch commented out (2026-08-01): QEMU's TCG does not
/// model Intel's ring-0 #GP — `sysretq` simply returns to the bad address and the
/// process dies in ring 3 anyway, so every *outcome* check still passed and only the
/// counter noticed. On real Intel silicon the same run takes the kernel down. Assert
/// the mechanism, not just the outcome, whenever the emulator is the softer machine.
/// The probe's first system call is deliberately ordinary: it only reaches the second
/// one by returning correctly from the first, so the fast path is exercised too.
fn sysretCanonicalTest() void {
log("DANOS-TEST-BEGIN: sysret-canonical\n", .{});
const blob = process.nonCanonicalReturnBlob();
check(
"the probe's system call number still matches the ABI",
blob.len > 1 and blob[0] == 0xB8 and blob[1] == @intFromEnum(abi.SystemCall.current_core),
);
const before = architecture.nonCanonicalReturnCount();
check("no return has been refused yet this boot", before == 0);
process.fault_kill_count = 0;
const probe = spawnNonCanonicalReturnProcess() orelse 0;
check("the probe process spawned", probe != 0);
// Drop below the probe so it gets the core, and wait for the kill.
scheduler.setPriority(1);
const deadline = architecture.millis() + 5000;
while (process.fault_kill_count < 1 and architecture.millis() < deadline) scheduler.yield();
scheduler.setPriority(4);
const refused = architecture.nonCanonicalReturnCount() - before;
check("the guard refused exactly one sysretq", refused == 1);
check("the probe was killed (not the machine)", process.fault_kill_count == 1);
check(
"the probe died of a protection fault — the iretq fallback faulted it in ring 3",
process.exitReasonOf(scheduler.currentId(), probe) == @intFromEnum(abi.ExitReason.protection_fault),
);
log("sysret-canonical: {d} non-canonical return(s) refused; core {d} still running\n", .{ refused, scheduler.currentCpuIndex() });
result();
}
/// Address-space refcount (docs/threading-plan.md M1): every process holds exactly one
/// reference to its address space, released when it dies, so `destroyAddressSpace` runs
/// exactly once per space — no leak, no double-free. Spawn and kill several ring-3
@@ -2246,9 +2478,67 @@ fn processKillTest(boot_information: *const BootInformation) void {
}
check("neither victim is listed after its kill", !still_listed);
check("a killed id stays dead (-ESRCH on a second kill)", process.killProcess(me, sleeper) == -ipcsync.ESRCH);
publishedExitChecks(rd, me);
result();
}
/// The mechanism every provider's release-what-a-dead-client-held sweep is built
/// on (docs/process-lifecycle.md, "Who learns of a death"): a **published** exit,
/// fanned out to every subscriber rather than only to the supervisor. The service
/// harness's subscriber sweep, the FAT server's open files, the compositor's
/// layers and the xHCI driver's device tokens all release on exactly this, and
/// several of them are subscribed at once in a normal boot — so what is checked
/// here is the fan-out: three independent subscribers, one death, three
/// notifications carrying the same badge, none of them the supervisor's.
///
/// Run at the end of the process-kill case, because a subscription is for every
/// death from then on and the checks above spawn victims of their own.
fn publishedExitChecks(rd: initial_ramdisk.Reader, me: u32) void {
var subscribers: [3]*ipcsync.Endpoint = undefined;
var subscribed: usize = 0;
while (subscribed < subscribers.len) : (subscribed += 1) {
subscribers[subscribed] = ipcsync.createIpcEndpoint() orelse break;
if (process.subscribeExits(subscribers[subscribed], me) != 0) break;
}
check("three endpoints subscribed to published exits", subscribed == subscribers.len);
if (subscribed != subscribers.len) return;
// A supervised child so the supervisor notification remains distinguishable:
// it lands on `endpoint`, the published ones on the three above.
const supervisor_endpoint = ipcsync.createIpcEndpoint() orelse {
check("supervisor endpoint allocated", false);
return;
};
var child: u32 = 0;
var i: u32 = 0;
while (i < rd.count) : (i += 1) {
const item = rd.entry(i) orelse continue;
if (!eql(initial_ramdisk.basename(item.name), "args-echo")) continue;
child = process.spawnProcessSupervised(item.blob, 4, &.{ "args-echo", "published-exit" }, me, supervisor_endpoint) catch 0;
break;
}
check("a clean-exit child spawned for the published exit", child != 0);
if (child == 0) return;
var badge: u64 = 0;
var received_cap: u64 = 0;
_ = ipcsync.replyWait(supervisor_endpoint, 0, 0, 0, 0, abi.no_cap, &badge, &received_cap);
check("the supervisor heard the child end", badge == abi.notify_badge_bit | abi.notify_exit_bit | child);
// The publication happens in the same locked section as the supervisor's
// notification and before it, so all three are already queued: a subscriber
// that had not heard would block here and time the harness out rather than
// pass vacuously.
var heard: usize = 0;
for (subscribers) |subscriber| {
badge = 0;
_ = ipcsync.replyWait(subscriber, 0, 0, 0, 0, abi.no_cap, &badge, &received_cap);
if (badge == abi.notify_badge_bit | abi.notify_exit_bit | child) heard += 1;
}
check("every subscriber heard the same death, not just the supervisor", heard == subscribers.len);
}
/// M17.1: a dead process's device claims are released by the reap, so a restarted
/// driver can claim its hardware again (docs/process-lifecycle.md iron rule 1).
/// First the broker release in isolation — two owners, one released, the other's
@@ -2268,8 +2558,8 @@ fn claimReleaseTest(boot_information: *const BootInformation) void {
}
// The broker release in isolation.
check("device 0 claimed by owner 111", devices_broker.claim(0, 111));
check("device 1 claimed by owner 222", devices_broker.claim(1, 222));
check("device 0 claimed by owner 111", claimOk(0, 111));
check("device 1 claimed by owner 222", claimOk(1, 222));
devices_broker.releaseAllOwnedBy(111);
check("owner 111's claim is released", devices_broker.ownerOf(0) == null);
check("owner 222's claim survives", (devices_broker.ownerOf(1) orelse 0) == 222);
@@ -2291,7 +2581,7 @@ fn claimReleaseTest(boot_information: *const BootInformation) void {
};
const child = process.spawnProcessSupervised(image, 4, &.{"/system/services/init"}, me, endpoint) catch 0;
check("supervised child spawned", child != 0);
check("device 0 claimed on the child's behalf", devices_broker.claim(0, child));
check("device 0 claimed on the child's behalf", claimOk(0, child));
check("the kill is accepted", process.killProcess(me, child) == 0);
var badge: u64 = 0;
@@ -2299,7 +2589,7 @@ fn claimReleaseTest(boot_information: *const BootInformation) void {
_ = ipcsync.replyWait(endpoint, 0, 0, 0, 0, abi.no_cap, &badge, &received_cap);
check("the exit notification arrived", badge == abi.notify_badge_bit | abi.notify_exit_bit | child);
check("death released the child's claim", devices_broker.ownerOf(0) == null);
check("the device is claimable again", devices_broker.claim(0, me));
check("the device is claimable again", claimOk(0, me));
devices_broker.releaseAllOwnedBy(me);
result();
}
@@ -2488,7 +2778,7 @@ fn usbReportTest(boot_information: *const BootInformation) void {
};
process.setInitialRamdisk(image);
_ = spawnRegistry(rd); // the xhci driver binds /protocol/usb-transfer
_ = spawnRegistry(rd); // drivers reach /protocol/device-manager through it
var manager: u32 = 0;
var i: u32 = 0;
while (i < rd.count) : (i += 1) {
@@ -2737,6 +3027,10 @@ fn fatMountTest(boot_information: *const BootInformation) void {
const init_ok = if (process.spawnBundled("/system/services/init")) true else |_| false;
check("init spawned (boots the tree, incl. the fat server)", init_ok);
check("fat-test client spawned", spawnNamed(rd, "fat-test"));
// The badge-scoping probe rides the same boot: it needs the fat server for a
// node id and the compositor for a layer id, and init starts both. It spawns
// its own second process — the intruder — with the ids it holds (P4c).
check("badge-scope-test owner spawned", spawnNamed(rd, "badge-scope-test"));
result();
}
@@ -2831,7 +3125,17 @@ fn acpiParseTest(boot_information: *const BootInformation) void {
while (i < rd.count) : (i += 1) {
const item = rd.entry(i) orelse continue;
if (!eql(initial_ramdisk.basename(item.name), "discovery")) continue;
_ = process.spawnProcessSupervised(item.blob, 4, &.{ item.name, "1" }, scheduler.currentId(), null) catch 0;
// Hand it the acpi-tables node the way the manager would: claim it here, then
// move it to the child. Discovery no longer claims for itself.
var scratch: [64]device_abi.DeviceDescriptor = undefined;
const seen_devices = devices_broker.enumerate(&scratch);
const tables: ?u64 = for (scratch[0..@min(seen_devices, scratch.len)]) |d| {
if (d.class == @intFromEnum(device_abi.DeviceClass.acpi_tables)) break d.id;
} else null;
const me_parse = scheduler.currentId();
if (tables) |node| _ = claimOk(node, me_parse);
const child = process.spawnProcessSupervised(item.blob, 4, &.{ item.name, "floor:1" }, me_parse, null) catch 0;
if (tables) |node| devices_broker.transfer(node, me_parse, child) catch {};
spawned = true;
break;
}
@@ -3559,8 +3863,8 @@ fn killThreadedGroupTest(boot_information: *const BootInformation) void {
// Claims for BOTH members: group death must release every member's claims
// before the supervisor hears anything — the worker's by the deferred
// (condemned) path.
check("device 0 claimed for the leader", devices_broker.claim(0, child));
check("device 1 claimed for the worker", devices_broker.claim(1, worker));
check("device 0 claimed for the leader", claimOk(0, child));
check("device 1 claimed for the worker", claimOk(1, worker));
scheduler.sleep(100); // let the worker really be running on another core
check("the supervisor's kill is accepted", process.killProcess(me, child) == 0);
const badge = awaitExitBadge(endpoint);
@@ -3748,7 +4052,7 @@ fn containmentTest() void {
result();
return;
}
check("claimed the parent device", devices_broker.claim(parent_id, me));
check("claimed the parent device", claimOk(parent_id, me));
defer devices_broker.releaseAllOwnedBy(me);
// A child whose window lies inside the parent's is accepted.
@@ -3770,10 +4074,185 @@ fn containmentTest() void {
check("re-registering an identical child returns the same id", again != 0 and again == good);
check("re-registering grew nothing", devices_broker.enumerate(&buffer) == before + 1);
// **There is no per-parent cap.** `maximum_children_per_parent = 16` is gone: it
// was written to stop a driver looping `device_register` and exhausting a shared
// table, and there is no shared table to exhaust — the table grows, and each
// registrar has its own allowance, so a runaway costs only itself. The cap never
// bounded a determined caller anyway (16 per parent, but nothing stopped it
// claiming more parents); what it reliably did was refuse a real PCI bus with more
// than 16 functions, which is how an AMD Ryzen booted with no USB and no storage.
//
// 64 children under one parent — four times the old ceiling.
var filled: u32 = 0;
var registered_children: u32 = 0;
while (filled < 64) : (filled += 1) {
var name: [4]u8 = .{ 'k', 0, 0, 0 };
name[1] = '0' + @as(u8, @intCast(filled / 10));
name[2] = '0' + @as(u8, @intCast(filled % 10));
var extra = childDescriptor(name[0..3], parent_window.start, 0x20);
if (devices_broker.register(parent_id, me, &extra)) |_| {
registered_children += 1;
} else |_| break;
}
check("one parent takes far more children than the old cap allowed", registered_children == 64);
// Idempotency still holds, and still matters: a crashed bus driver is restarted and
// re-registers everything it rediscovers, which must return the ids it had before
// rather than duplicate them.
const readmitted = devices_broker.register(parent_id, me, &fits) catch 0;
check("re-registering an identical child still returns its id", readmitted != 0 and readmitted == good);
// The table itself has no ceiling: it grows. The old `maximum_devices = 64` was a
// guess about someone else's computer, and one driver's enumeration starved every
// other — which is how a Ryzen booted with no USB and no storage. What bounds a
// runaway now is an allowance charged to the registrar, so the damage stays with
// whoever caused it (docs/os-development/device-authority.md).
// The table grows: it starts at 8 entries and this boot holds well past that, so
// the growth path runs every time rather than lying dormant until someone else's
// larger machine finds it — which is how the old ceiling stayed invisible.
const held = devices_broker.enumerate(&buffer);
check("the table grew beyond its initial block", held > 8);
result();
}
/// A minimal child descriptor with one memory resource, for the containment test.
/// Delegation's mechanism. A claim is exclusive (driver-model.md, invariant 1), so
/// handing a device on is a **move**: the giver stops holding it the instant the
/// receiver starts. That is why this is not the M13 capability path, which shares a
/// handle refcounted.
///
/// The rule the kernel enforces is the whole of it: *you may give away what you hold*.
/// It has no idea which task is the device manager and needs none
/// (docs/os-development/device-authority.md).
fn deviceTransferTest(boot_information: *const boot_handoff.BootInformation) void {
var buffer: [8]device_abi.DeviceDescriptor = undefined;
check("the device tree is seeded", devices_broker.enumerate(&buffer) >= 2);
const image = bundledInit(boot_information) orelse {
check("initial_ramdisk carries /system/services/init", false);
result();
return;
};
const me = scheduler.currentId();
const endpoint = ipcsync.createIpcEndpoint() orelse {
check("exit endpoint allocated", false);
result();
return;
};
const child = process.spawnProcessSupervised(image, 4, &.{"/system/services/init"}, me, endpoint) catch 0;
check("supervised child spawned", child != 0);
// You may only give away what you hold — so an unheld device cannot be moved at all,
// which is what stops a transfer being a back door around claiming.
const unheld = if (devices_broker.transfer(0, me, child)) |_| false else |e| e == error.NotHeld;
check("an unheld device cannot be transferred", unheld);
// A second device this test never hands over, so the "no giver" half below is a
// real observation rather than a restatement of the first.
const parentless: u64 = 1;
check("claimed device 0", claimOk(0, me));
// The move itself.
const moved = if (devices_broker.transfer(0, me, child)) |_| true else |_| false;
check("the holder may transfer", moved);
const holder = devices_broker.ownerOf(0) orelse 0;
check("the receiver holds it", holder == child);
check("the giver does not", holder != me);
// Having given it away, the giver cannot give it again. This is the assertion that
// makes it a move rather than a copy.
const again = if (devices_broker.transfer(0, me, child)) |_| false else |e| e == error.NotHeld;
check("a former holder cannot transfer again", again);
// Nor may a stranger move a device it never held.
const stranger = if (devices_broker.transfer(0, 9999, me)) |_| false else |e| e == error.NotHeld;
check("a stranger cannot transfer another task's device", stranger);
// The giver is recorded. One field, and the authority rule follows from it: a
// device that was *given* to someone is delegated hardware, so it may be handed on
// but never taken, and when its holder dies it returns to whoever lent it instead
// of becoming free for anyone. Nothing has a giver until it is handed over —
// which is why the loader's framebuffer needs no exemption from either rule.
check("the giver is recorded on a transfer", devices_broker.giverOf(0) == me);
check("a device nobody handed over has no giver", devices_broker.giverOf(parentless) == null);
const absent = if (devices_broker.transfer(9999, me, child)) |_| false else |e| e == error.NoSuchDevice;
check("a device that does not exist is refused", absent);
// **A grant is a loan.** The child holds device 0 and `me` lent it, so the child's
// death must hand it back rather than release it to nobody. That is what lets the
// device manager re-delegate to a restarted driver — and, once `claim` refuses a
// device that has a giver, it is the only thing that stops a dead driver's hardware
// being stranded forever.
check("the child still holds the lent device", devices_broker.ownerOf(0) == child);
devices_broker.releaseAllOwnedBy(child);
check("the borrower's death returns the device to its lender", devices_broker.ownerOf(0) == me);
check("and it is no longer on loan", devices_broker.giverOf(0) == null);
// A device with no lender still simply frees on death, as it always did.
check("claimed a second device with no lender", claimOk(parentless, me));
devices_broker.releaseAllOwnedBy(me);
check("a device nobody lent is released outright", devices_broker.ownerOf(parentless) == null);
result();
}
/// PCI host-bridge apertures are derived from the *holes* in the firmware memory map,
/// and a registered BAR must fall inside one. So the invariant is not "we find the
/// holes" but "an aperture never covers memory the firmware described" — an aperture
/// over RAM means `device_register` containment admits a child BAR over kernel memory,
/// and its claimant can `mmio_map` it.
///
/// The map's length is the firmware's choice: 60–200 descriptors on a real machine,
/// 15–25 under OVMF, which is why the suite never saw this. The derivation used to
/// copy sub-4 GiB entries into a fixed `[64]` array and skip the rest — and a skipped
/// region is not merely lost, it is one the gap finder concludes is *free*.
fn apertureTest() void {
// 100 described one-page regions, 2 MiB apart: 99 small holes between them, then
// one large hole from the last region up to 4 GiB. Under the old fixed array the
// 36 regions past the 64th vanished, so the "largest hole" ran from ~128 MiB to
// 4 GiB — straight across 36 regions the firmware had described.
const spacing: u64 = 2 << 20;
var regions: [100]boot_handoff.MemoryRegion = undefined;
for (&regions, 0..) |*region, i| {
region.* = .{ .base = @as(u64, i) * spacing, .pages = 1, .kind = .usable };
}
var holes: [3]platform.AddressRange = undefined;
const found = platform.largestHolesBelow4G(&regions, 1 << 20, &holes);
check("apertures were derived from a 100-entry map", found > 0);
var overlaps: usize = 0;
var largest: platform.AddressRange = .{ .base = 0, .end = 0 };
for (holes) |hole| {
if (hole.end <= hole.base) continue;
if (hole.end - hole.base > largest.end - largest.base) largest = hole;
for (regions) |region| {
const region_end = region.base + region.pages * 4096;
if (region.base < hole.end and region_end > hole.base) overlaps += 1;
}
}
check("no aperture overlaps described memory", overlaps == 0);
// The big hole is above the last described region, not across it.
const last_end = (regions.len - 1) * spacing + 4096;
check("the largest aperture starts after the last described region", largest.base == last_end);
check("the largest aperture runs to 4 GiB", largest.end == (1 << 32));
// A map the firmware describes nothing in is one whole hole; a map that describes
// everything has none. Neither may invent an aperture over something described.
var empty: [3]platform.AddressRange = undefined;
check("an empty map yields one hole", platform.largestHolesBelow4G(&.{}, 1 << 20, &empty) == 1);
check("that hole is the whole low space", empty[0].base == 0 and empty[0].end == (1 << 32));
const whole = [_]boot_handoff.MemoryRegion{.{ .base = 0, .pages = (1 << 32) / 4096, .kind = .usable }};
var none: [3]platform.AddressRange = undefined;
check("a fully described map yields no aperture", platform.largestHolesBelow4G(&whole, 1 << 20, &none) == 0);
result();
}
fn childDescriptor(hid: []const u8, start: u64, len: u64) device_abi.DeviceDescriptor {
var child = std.mem.zeroes(device_abi.DeviceDescriptor);
child.class = @intFromEnum(device_abi.DeviceClass.unknown);
@@ -3859,6 +4338,58 @@ fn protocolRegistryTest(boot_information: *const BootInformation) void {
///
/// The fixture's `protocol-denied: ok` is the marker; each step prints its own
/// line, which the harness's ordered regex reads.
/// The attacker the device suite never had. The audit's finding was that a fully
/// green suite had missed six real defects because it *contains no attacker* — every
/// device case asserts a driver handed its hardware can drive it, and none asks what a
/// process handed **nothing** can do.
///
/// The fixture is spawned with no device and asserts what it therefore cannot do. It
/// runs without the device manager on purpose: nothing here needs a driver, and a boot
/// with fewer moving parts makes the refusals unambiguous.
fn deviceAuthorityTest(boot_information: *const BootInformation) void {
log("DANOS-TEST-BEGIN: device-authority\n", .{});
if (boot_information.initial_ramdisk_len == 0) {
check("bootloader handed over an initial_ramdisk", false);
result();
return;
}
const image = @as([*]const u8, @ptrFromInt(boot_handoff.physicalToVirtual(boot_information.initial_ramdisk_base)))[0..boot_information.initial_ramdisk_len];
const rd = initial_ramdisk.Reader.init(image) orelse {
check("initial_ramdisk image is valid", false);
result();
return;
};
process.setInitialRamdisk(image);
// The manager must be up: it is what holds the seeded hardware, and without it
// every device would be lying around unheld and the last assertion would have
// nothing to observe — a test that cannot fail.
check("registry (init) spawned", spawnRegistry(rd));
check("device-manager spawned", spawnNamed(rd, "device-manager"));
check("device-authority-test spawned", spawnNamedWithArg(rd, "device-authority-test", "run"));
// The VERDICT prefix matters: the fixture prints one "device-authority: ok <name>"
// line per assertion, so a marker of "device-authority: ok" matches the FIRST
// passing assertion and this loop exits before any later failure is printed — the
// case then passes with failures in it, which it did until this was caught.
const pass_marker = "device-authority: VERDICT ok";
const fail_marker = "device-authority: VERDICT FAILED";
scheduler.setPriority(1);
const deadline = architecture.millis() + 20000;
var saw_pass = false;
var saw_fail = false;
while (architecture.millis() < deadline and !saw_pass and !saw_fail) {
if (bufferHas(pass_marker)) saw_pass = true;
if (bufferHas(fail_marker)) saw_fail = true;
scheduler.yield();
}
scheduler.setPriority(4);
check("no authority assertion failed", !saw_fail);
check("the attacker completed every assertion", saw_pass);
result();
}
fn protocolDeniedTest(boot_information: *const BootInformation) void {
log("DANOS-TEST-BEGIN: protocol-denied\n", .{});
if (boot_information.initial_ramdisk_len == 0) {
@@ -3898,6 +4429,68 @@ fn protocolDeniedTest(boot_information: *const BootInformation) void {
result();
}
/// P4a — the reserved verbs, asked of live providers
/// (docs/security-track-plan.md P4a; docs/os-development/protocol-namespace.md).
/// Every protocol rebased onto `envelope.Define` gets `describe` answered from its
/// specification and `-ENOSYS` for a verb it does not define, without its provider
/// implementing either — this case is where that stops being a host unit test of
/// the generated dispatch and becomes an observation of real providers over real
/// IPC.
///
/// The scenario is the assertion's scaffolding, the same shape `protocol-denied`
/// uses: `/protocol` (init in its registry role) plus the providers the fixture is
/// granted to reach — the **input service** and the **compositor**, two protocols
/// of different sizes and different verb counts, so "uniform" means something. The
/// fixture reads `/protocol`'s own listing rather than a list compiled into it, so
/// what it checks is what this boot actually bound; the three other P4a protocols
/// (vfs, block, scanout) sit behind hardware chains this scenario deliberately does
/// not boot, and the fixture names them on serial as unchecked rather than passing
/// over them.
///
/// The fixture's `protocol-conformance: ok` is the marker; each contract it checks
/// prints its own line, which the harness's ordered regex reads.
fn protocolConformanceTest(boot_information: *const BootInformation) void {
log("DANOS-TEST-BEGIN: protocol-conformance\n", .{});
if (boot_information.initial_ramdisk_len == 0) {
check("bootloader handed over an initial_ramdisk", false);
result();
return;
}
const image = @as([*]const u8, @ptrFromInt(boot_handoff.physicalToVirtual(boot_information.initial_ramdisk_base)))[0..boot_information.initial_ramdisk_len];
const rd = initial_ramdisk.Reader.init(image) orelse {
check("initial_ramdisk image is valid", false);
result();
return;
};
process.setInitialRamdisk(image);
check("registry (init) spawned", spawnRegistry(rd));
// The two providers under test. Neither needs hardware beyond the framebuffer
// the kernel already seeded: input binds /protocol/input and waits for
// subscribers, and the compositor binds /protocol/display and composes into
// that framebuffer (the display-service scenario boots it exactly this way).
check("input service spawned", spawnNamed(rd, "input"));
check("display service spawned", spawnNamed(rd, "display"));
check("protocol-conformance-test spawned", spawnNamedWithArg(rd, "protocol-conformance-test", "run"));
const pass_marker = "protocol-conformance: ok";
const fail_marker = "protocol-conformance: FAIL";
scheduler.setPriority(1);
const deadline = architecture.millis() + 20000;
var saw_pass = false;
var saw_fail = false;
while (architecture.millis() < deadline and !saw_pass and !saw_fail) {
if (bufferHas(pass_marker)) saw_pass = true;
if (bufferHas(fail_marker)) saw_fail = true;
scheduler.yield();
}
scheduler.setPriority(4);
check("no provider failed the reserved-verb contract", !saw_fail);
check("the fixture conformance-checked every provider its scenario boots", saw_pass);
result();
}
fn deviceManagerTest(boot_information: *const BootInformation) void {
log("DANOS-TEST-BEGIN: device-manager\n", .{});
if (boot_information.initial_ramdisk_len == 0) {
@@ -4170,6 +4763,105 @@ fn faultNoExecute() void {
log("DANOS-TEST-RESULT: FAIL (NX not enforced)\n", .{});
}
/// Verify SMEP: a ring-0 instruction fetch from a *user*-mapped page must fault.
///
/// The ret2usr shape, staged deliberately — a user code page (present, executable,
/// U/S set) mapped into the address space the kernel itself is running on, then
/// called from ring 0. CR4.SMEP makes the fetch a #PF; without it the `ret` simply
/// returns and the FAIL line below is reached.
///
/// The CPU reports it as: present (bit 0) + instruction fetch (bit 4) = error code
/// 0x11, taken in ring 0, at the user address it tried to fetch from — a #PF on an
/// instruction fetch is raised *at* the instruction that could not be fetched, so
/// the reported IP is the probe page, not the kernel-half `call` that jumped there.
/// The enabled-check up front stops the case passing vacuously on a CPU that has no
/// SMEP (where nothing would fault and nothing would be proved).
fn faultSmep() void {
log("DANOS-TEST-BEGIN: fault-smep\n", .{});
if (!architecture.supervisorExecutePreventionEnabled()) {
log("DANOS-TEST-RESULT: FAIL (SMEP not enabled in this boot)\n", .{});
return;
}
const frame = pmm.alloc() orelse {
log("DANOS-TEST-RESULT: FAIL (no frame for the probe page)\n", .{});
return;
};
// Fill through the physmap — the user mapping is read-only. A lone `ret` so an
// unenforced fetch lands harmlessly back here (and reports FAIL), int3 padding
// so a stray slide traps instead of running into whatever the frame held.
const code: [*]u8 = @ptrFromInt(boot_handoff.physicalToVirtual(frame));
@memset(code[0..abi.page_size], 0xCC);
code[0] = 0xC3; // ret
// RO + X *and user-accessible*, in the kernel's own tables: this task is a kernel
// task, so it runs on them (a process would have its own address space).
architecture.mapUserPage(process.code_virtual, frame, false, true);
// Launder the address through empty asm so the backend really forms an indirect
// call rather than folding anything about a known constant target.
var target: u64 = process.code_virtual;
target = asm (""
: [ret] "=r" (-> u64),
: [in] "0" (target),
);
const f: *const fn () void = @ptrFromInt(target);
f(); // ring-0 instruction fetch from a user page -> #PF
log("DANOS-TEST-RESULT: FAIL (SMEP not enforced)\n", .{});
}
/// Verify SMAP: a ring-0 data read from a *user*-mapped page must fault.
///
/// The bug shape this case stands in for is the ordinary one — a syscall that takes
/// the pointer ring 3 handed it and dereferences it. So the probe does exactly that
/// and nothing more: an ordinary user data page (present, user-accessible, read-only,
/// no-execute) mapped into the address space this kernel task is already running on,
/// then read directly rather than through system/kernel/user-memory.zig. With SMAP on
/// and EFLAGS.AC clear the load is a #PF; without it the byte comes back and the FAIL
/// line below reports the value it should never have seen.
///
/// The CPU reports it as error code **0x1**: present (bit 0) alone. A SMAP violation
/// has no error-code bit of its own — bit 1 stays clear because this is a read, and
/// bit 2 (U/S) describes the *access*, which was made in ring 0, not the page. So the
/// report is indistinguishable in its bits from any other supervisor read of a present
/// page; what identifies it is the pairing with `ring 0 (kernel)` and a user CR2.
///
/// The seed write goes through the physmap, which is the point in miniature: that is
/// the route the checked copy layer takes for every legitimate access to this same
/// frame, and SMAP has no objection to it. Only the second access — the one through
/// the *user* virtual address — is refused.
///
/// The enabled-check up front stops the case passing vacuously on a CPU without SMAP,
/// and fails rather than skips: a suite that quietly stops testing the tripwire is
/// exactly the outcome the tripwire exists to prevent.
fn faultSmap() void {
log("DANOS-TEST-BEGIN: fault-smap\n", .{});
if (!architecture.supervisorAccessPreventionEnabled()) {
log("DANOS-TEST-RESULT: FAIL (SMAP not enabled in this boot)\n", .{});
return;
}
const frame = pmm.alloc() orelse {
log("DANOS-TEST-RESULT: FAIL (no frame for the probe page)\n", .{});
return;
};
const seed: [*]u8 = @ptrFromInt(boot_handoff.physicalToVirtual(frame));
@memset(seed[0..abi.page_size], 0);
seed[0] = 0x5A; // a sentinel, so an unenforced read is reported as a value, not a guess
// RO + NX *and user-accessible*, in the kernel's own tables: this task is a kernel
// task, so it runs on them (a process would have its own address space).
architecture.mapUserPage(process.code_virtual, frame, false, false);
// Launder the address through empty asm for the same reason `fault-null` does:
// the backend must form a real load from a runtime address rather than reasoning
// about a constant it can see the provenance of.
var target: u64 = process.code_virtual;
target = asm (""
: [ret] "=r" (-> u64),
: [in] "0" (target),
);
const p: *const volatile u8 = @ptrFromInt(target);
const value = p.*; // ring-0 data read from a user page -> #PF
log("DANOS-TEST-RESULT: FAIL (SMAP not enforced; read 0x{x})\n", .{value});
}
/// Verify the null guard: dereferencing address 0 (page 0 left unmapped) faults.
fn faultNull() void {
log("DANOS-TEST-BEGIN: fault-null\n", .{});
+26 -4
View File
@@ -4,15 +4,26 @@
//! hiding the trade-offs. Keeping them here makes them visible at a glance and gives
//! one spot to change them. They're plain `comptime` constants (zero runtime cost);
//! any one can later be promoted to a `-D` build option if a target needs to vary it
//! (see build.zig's `-Dtest-case` for the pattern). This keeps ps2-library.zig to what it
//! actually is — the bootloader↔kernel handoff *contract* — with tunables living here.
//! (see build.zig's `-Dtest-case` for the pattern). This keeps [[boot-handoff]] to what
//! it actually is — the loader↔kernel handoff *contract* — with tunables living here.
//!
//! **Kernel only, and deliberately so.** This file exists because tunables were
//! crowding the loader↔kernel contract they were split out of; it is not a registry for
//! the whole system. A driver's ring size belongs to that driver, a protocol's payload
//! cap to that protocol. How a ceiling is *declared*, wherever it lives, is
//! docs/os-development/bounds.md — a shape, not a shared list.
/// Ceiling on logical CPUs the kernel tracks — the size of the per-CPU bookkeeping
/// arrays (discovery pool, scheduler state, per-core GDT/TSS). Generous headroom:
/// those structs are small, and the *large* per-core resources (kernel and IST
/// stacks) are allocated at bring-up for cores that actually come online, so this
/// ceiling is cheap. A machine with more logical CPUs has its surplus reported and
/// left parked (see acpi `cpusDropped`).
/// ceiling is cheap.
///
/// bound: logical CPUs the kernel tracks
/// decided-by: hardware
/// protects: the per-CPU bookkeeping arrays, which are sized at compile time
/// at-limit: degrade — the surplus cores are left parked, never brought online
/// observed-by: platform.cpusDropped() -> the WARNING at kernel.zig:281
pub const maximum_cpus = 128;
/// Maximum tasks (kernel threads) alive at once — the static task-table size. Each
@@ -23,6 +34,17 @@ pub const maximum_cpus = 128;
/// for the USB stack: the xHCI bus driver spawns a supervised class-driver instance
/// per matched interface (keyboard, mouse, mass storage), on top of the FAT and
/// block servers and the growing ramdisk bundle.
///
/// The history above is the argument against this number: it has been raised twice,
/// each time by a machine or a bundle that outgrew it, which is the pattern the
/// bounds rule exists to stop. It is `ours` only because the task table is static;
/// how many drivers a machine needs is decided by how much hardware it has.
///
/// bound: kernel threads alive at once — the static task-table size
/// decided-by: hardware
/// protects: the statically allocated task table
/// at-limit: refuse — spawn fails; a supervised driver is never started
/// observed-by: the spawning supervisor's own log line; see docs/bounds-track-plan.md
pub const maximum_tasks = 48;
/// Each task's kernel stack (also each AP's bring-up stack), in bytes.
+87 -82
View File
@@ -22,6 +22,7 @@ const logging = @import("logging");
const aml = @import("aml");
const acpi_ids = @import("acpi-ids");
const device_manager_protocol = @import("device-manager-protocol");
const envelope = @import("envelope");
const power_protocol = @import("power-protocol");
/// AML opcode/prefix bytes by name (`zero_opcode`, `byte_prefix`, …) — so the `_HID`
/// integer decode names the opcodes instead of bare 0x0A/0x0B/… (docs/coding-standards.md).
@@ -59,15 +60,14 @@ const pwrbtn_bit: u16 = 1 << 8;
const sci_en_bit: u32 = 1 << 0;
const slp_en: u32 = 1 << 13;
// The `.power` subscribers: endpoints handed over as capabilities, each
// receiving events as buffered messages. Dropped on a failed send. The
// subscriber's task id is kept too — a shutdown request is honored only from a
// subscriber (init subscribes; a stray process does not), the soft gate that
// stands in for "only the system supervisor may power off" without hardcoding
// a pid the kernel's idle tasks would have taken.
const maximum_subscribers = 8;
var subscribers: [maximum_subscribers]?ipc.Handle = .{null} ** maximum_subscribers;
var subscriber_tasks: [maximum_subscribers]u32 = .{0} ** maximum_subscribers;
/// The `.power` subscribers, kept by the service harness (P4c): endpoints handed
/// over as capabilities, each receiving events as buffered messages, each swept
/// when its task dies. The table remembers which task subscribed, which is what
/// the shutdown gate below asks — a shutdown request is honored only from a
/// subscriber (init subscribes; a stray process does not), the soft gate that
/// stands in for "only the system supervisor may power off" without hardcoding a
/// pid the kernel's idle tasks would have taken.
const Subscriptions = service.Subscribers(power_protocol.Protocol, void);
// Pass-1 registration record (see main): what pass 2 reports.
const Registered = struct { hid: [8]u8 = .{0} ** 8, hid_len: usize = 0, device_id: u64 = 0, resource_count: u64 = 0 };
@@ -104,11 +104,19 @@ fn findTablesNode(buffer: []device.DeviceDescriptor) ?device.DeviceDescriptor {
}
pub fn main(init: process.Init) void {
// When the acpi-parse scenario spawns this directly, argv[1] is a device-count
// *floor* to self-verify against. The kernel no longer parses AML, so there is
// no exact count to match — proving the ring-3 parse found at least a floor of
// devices is the check. Deterministic, no log-scraping.
const floor: ?usize = if (init.arguments.get(1)) |a| (std.fmt.parseInt(usize, a, 10) catch null) else null;
// When the acpi-parse scenario spawns this directly, it passes `floor:N` — a
// device-count floor to self-verify against. The kernel no longer parses AML, so
// there is no exact count to match; proving the ring-3 parse found at least N
// Device objects is the check. Deterministic, no log-scraping.
//
// The `floor:` prefix matters. argv[1] is the assigned device id for every driver
// the manager spawns, so a bare number here would be read as a floor — which is
// exactly what happened when discovery started being given its node: it saw
// argv[1] = "7", decided it was in self-verify mode, and never reported a device.
const floor: ?usize = if (init.arguments.get(1)) |a| blk: {
if (!std.mem.startsWith(u8, a, "floor:")) break :blk null;
break :blk std.fmt.parseInt(usize, a["floor:".len..], 10) catch null;
} else null;
const buffer = memory.allocator().alloc(device.DeviceDescriptor, 64) catch {
_ = logging.write("/system/services/acpi: out of memory\n");
@@ -118,11 +126,11 @@ pub fn main(init: process.Init) void {
_ = logging.write("/system/services/acpi: no acpi-tables node to claim\n");
return;
};
// The node arrived with the spawn: the manager holds it and names it in the call
// that creates this process. Discovery was the last thing in the system that
// acquired hardware by naming it rather than being given it
// (docs/os-development/device-authority.md).
node_id = node.id;
if (!device.claim(node_id)) {
_ = logging.write("/system/services/acpi: unable to claim acpi-tables\n");
return;
}
// Map the node's resources: the AML blobs (bytecode), the FADT (intact
// "FACP" header — decision 3), the io_port grant, and the SCI irq.
@@ -200,6 +208,7 @@ pub fn main(init: process.Init) void {
.init = onInit,
.on_message = onMessage,
.on_notification = onNotification,
.subscribers = Subscriptions.hooks,
});
}
@@ -241,10 +250,20 @@ fn onInit(endpoint: ipc.Handle) bool {
else
std.log.info("device {d} bus=acpi hid={s} ({d} resources)", .{ entry.device_id, hid, entry.resource_count });
if (manager) |h| {
var report = device_manager_protocol.ChildAdded{ .bus = @intFromEnum(device_manager_protocol.BusKind.acpi), .parent = node_id, .bus_address = entry.device_id, .identity = 0, .device_id = entry.device_id };
// The registered device id is the packet's target, so the body only
// says where on the firmware tree the node sits and what it is.
var report = device_manager_protocol.ChildAdded{
.bus = @intFromEnum(device_manager_protocol.BusKind.acpi),
.parent = node_id,
.bus_address = entry.device_id,
.identity = 0,
};
@memcpy(report.hid[0..entry.hid_len], entry.hid[0..entry.hid_len]);
var reply: [device_manager_protocol.message_maximum]u8 = undefined;
_ = ipc.call(h, std.mem.asBytes(&report), &reply) catch {};
var packet: [device_manager_protocol.message_maximum]u8 = undefined;
if (device_manager_protocol.Protocol.encodeRequest(.child_added, entry.device_id, report, &.{}, &packet)) |framed| {
var reply: [device_manager_protocol.message_maximum]u8 = undefined;
_ = ipc.call(h, framed, &reply) catch {};
}
}
}
std.log.info("reported {d} device(s) to the manager", .{registered_count});
@@ -389,13 +408,21 @@ fn dispatchGpe(n: u32) void {
fn publishNotify(node: *aml.Node, code: u64) void {
// Map the notified device's _HID to a domain event where we recognize it.
// The kind IS the packet's verb, so the mapping picks which event to frame
// rather than which tag to put in a payload.
var hid: [8]u8 = .{0} ** 8;
if (readHid(node, &global_interpreter)) |h| hid = h;
const which: power_protocol.Event = if (std.mem.eql(u8, hid[0..7], "PNP0C0A")) .battery else if (std.mem.eql(u8, hid[0..7], "ACPI0003")) .ac else if (std.mem.eql(u8, hid[0..7], "PNP0C0D")) .lid else .notify;
var event = power_protocol.EventMessage{ .event = @intFromEnum(which), .code = @truncate(code) };
event.hid = hid;
const notice = power_protocol.Notice{ .code = @truncate(code), .hid = hid };
std.log.info("power: notify {s} code {d}", .{ hid[0..7], code });
publishEvent(std.mem.asBytes(&event));
if (std.mem.eql(u8, hid[0..7], "PNP0C0A")) {
Subscriptions.publish(.battery, 0, notice);
} else if (std.mem.eql(u8, hid[0..7], "ACPI0003")) {
Subscriptions.publish(.ac, 0, notice);
} else if (std.mem.eql(u8, hid[0..7], "PNP0C0D")) {
Subscriptions.publish(.lid, 0, notice);
} else {
Subscriptions.publish(.notify, 0, notice);
}
}
/// Two lowercase hex digits of `n` into `out[0..2]`.
@@ -406,23 +433,10 @@ fn writeHex2(out: []u8, n: u32) void {
}
fn publishButton() void {
const event = power_protocol.EventMessage{ .event = @intFromEnum(power_protocol.Event.power_button) };
publishEvent(std.mem.asBytes(&event));
}
fn publishEvent(bytes: []const u8) void {
for (&subscribers) |*slot| {
if (slot.*) |handle| {
if (!ipc.send(handle, bytes)) slot.* = null;
}
}
}
fn isSubscriber(task: u32) bool {
for (&subscribers, 0..) |*slot, si| {
if (slot.* != null and subscriber_tasks[si] == task) return true;
}
return false;
// The kind is the packet's operation, so the harness frames it once and pushes
// the same bytes to every subscriber. There is no class here: a power event
// goes to everyone who asked for power events.
Subscriptions.publish(.power_button, 0, .{});
}
/// Enter S5 (soft off): write SLP_TYP|SLP_EN to the PM1 control register(s).
@@ -444,48 +458,39 @@ fn enterS5() void {
// --- harness callbacks --------------------------------------------------------
fn onNotification(badge: u64) void {
// The only notification the service binds is the SCI (an IRQ badge).
_ = badge;
// Two kinds of notification reach this loop now. The SCI is the one this
// service binds; the published process exits are the harness's, which it has
// already used to sweep the subscriber table before calling here. Everything
// that is not a bare IRQ badge must therefore be ignored — treating a death
// as an interrupt would clear PM1 status the firmware never set.
if (badge & (ipc.notify_exit_bit | ipc.notify_timer_bit | ipc.notify_message_bit | ipc.notify_signal_bit) != 0) return;
onSci();
}
/// The `.power` protocol: subscribe (endpoint as the call's capability),
/// shutdown (PID 1 only). Device discovery uses a different endpoint (the
/// device manager's), so nothing here handles ChildAdded.
const Invocation = envelope.Invocation;
const Answer = envelope.Answer;
/// The power contract: the reserved `subscribe` (the subscriber's endpoint as
/// the call's capability, answered by the harness) and `shutdown` (subscribers
/// only). Device discovery uses a different endpoint — the device manager's — so
/// nothing here handles a tree report.
fn onMessage(message: []const u8, reply: []u8, sender: u32, arrived: *ipc.Arrival) usize {
if (message.len < 1) return 0;
switch (message[0]) {
@intFromEnum(power_protocol.Operation.subscribe) => {
// The subscriber's endpoint is claimed only when a slot takes it;
// a full table refuses and the turn closes what arrived.
var status: i32 = -1;
if (arrived.peek() != null) {
for (&subscribers, 0..) |*slot, si| {
if (slot.* == null) {
slot.* = arrived.take();
subscriber_tasks[si] = sender;
status = 0;
break;
}
}
}
const r = power_protocol.Reply{ .status = status };
@memcpy(reply[0..@sizeOf(power_protocol.Reply)], std.mem.asBytes(&r));
return @sizeOf(power_protocol.Reply);
},
@intFromEnum(power_protocol.Operation.shutdown) => {
// Honored only from a power subscriber — init, which has already run
// the stop sequence over everything else. The power service is
// mechanism (write S5); deciding *when* to shut down and stopping
// the rest of the system first is init's policy.
const allowed = isSubscriber(sender);
const r = power_protocol.Reply{ .status = if (allowed) 0 else -1 };
@memcpy(reply[0..@sizeOf(power_protocol.Reply)], std.mem.asBytes(&r));
if (allowed) enterS5();
return @sizeOf(power_protocol.Reply);
},
else => return 0,
}
return Subscriptions.dispatch({}, handlers, message, sender, arrived, reply);
}
/// `subscribe` and `unsubscribe` are absent on purpose: the harness answers both.
const handlers = Subscriptions.Handlers{ .shutdown = onShutdown };
/// Honored only from a power subscriber — init, which has already run the stop
/// sequence over everything else. The power service is mechanism (write S5);
/// deciding *when* to shut down and stopping the rest of the system first is
/// init's policy. The badge is the whole gate: it is kernel-stamped, so nothing
/// in the packet can claim to be init. The subscriber table moved into the
/// harness; the question it answers has not changed.
fn onShutdown(_: void, invocation: Invocation(void), _: Answer(void)) isize {
if (!Subscriptions.has(invocation.sender)) return -envelope.EPERM;
enterS5();
return 0;
}
/// Depth-first walk: register + report each present device with a _HID, then
@@ -522,8 +527,8 @@ fn registerDevice(node: *aml.Node, hid: [8]u8, interpreter: *aml.Interpreter) vo
@memcpy(descriptor.hid[0..@intCast(hid_len)], hid[0..@intCast(hid_len)]);
applyCrs(&descriptor, node, interpreter);
const id = device.register(node_id, &descriptor) orelse {
std.log.info("register refused for {s}", .{hid[0..@intCast(hid_len)]});
const id = device.register(node_id, &descriptor) catch |e| {
std.log.warn("register refused for {s}: {s}", .{ hid[0..@intCast(hid_len)], @errorName(e) });
return;
};
registered[registered_count] = .{ .hid = hid, .hid_len = @intCast(hid_len), .device_id = id, .resource_count = descriptor.resource_count };
+2 -2
View File
@@ -14,8 +14,8 @@ pub fn build(b: *std.Build) void {
.name = "discovery",
.root_source_file = b.path("acpi.zig"),
.imports = &.{
"acpi-ids", "aml", "channel", "device-manager-protocol", "driver", "ipc", "logging",
"memory", "power-protocol", "process", "service", "time",
"acpi-ids", "aml", "channel", "device-manager-protocol", "driver", "envelope",
"ipc", "logging", "memory", "power-protocol", "process", "service", "time",
},
});
b.installArtifact(exe);
+2 -2
View File
@@ -10,8 +10,8 @@ pub fn build(b: *std.Build) void {
.name = "device-manager",
.root_source_file = b.path("device-manager.zig"),
.imports = &.{
"device-manager-protocol", "device-registry", "driver", "file-system", "ipc",
"logging", "memory", "process", "service", "time",
"device-manager-protocol", "device-registry", "driver", "envelope", "file-system",
"ipc", "logging", "memory", "process", "service", "time",
},
});
b.installArtifact(exe);
+314 -116
View File
@@ -24,7 +24,17 @@ const time = @import("time");
const memory = @import("memory");
const logging = @import("logging");
const device_manager_protocol = @import("device-manager-protocol");
const envelope = @import("envelope");
const registry = @import("device-registry");
/// The generated device-manager dispatch, plus the subscriber machinery the
/// harness owns (P4c): the watcher table, the reserved `subscribe` verb, the
/// exit sweep, and the fan-out. One manager per system, so the handler context is
/// empty and the tables stay in this file's globals.
const Serve = service.Subscribers(device_manager_protocol.Protocol, void);
const Invocation = envelope.Invocation;
const Answer = envelope.Answer;
const fs = @import("file-system");
// --- the device registry ------------------------------------------------------
@@ -89,10 +99,19 @@ fn identityFromReport(report: device_manager_protocol.ChildAdded) registry.Ident
/// Whether some driver entry already serves registered device `device_id` —
/// a re-report after a bus restart must not spawn a second instance.
fn driverForDevice(device_id: u64) bool {
return driverEntryForDevice(device_id) != null;
}
/// The driver entry BOUND TO a device — matched and spawned for it. Distinct
/// from the device's reporter: a mouse's provider is the bus that reported it
/// (lineage via `children[].reporter`), while a volume's provider is the
/// storage driver spawned FOR it — which is what a `.consumer` hello asks for.
fn driverEntryForDevice(device_id: u64) ?*Driver {
if (device_id == device_manager_protocol.no_device) return null;
for (&drivers) |*driver| {
if (driver.used and driver.device_id == device_id) return true;
if (driver.used and driver.device_id == device_id) return driver;
}
return false;
return null;
}
// --- supervision -------------------------------------------------------------
@@ -130,6 +149,12 @@ const Driver = struct {
spawn_ns: u64 = 0,
hello_deadline_ns: u64 = 0,
restart_due_ns: u64 = 0,
// The serving endpoint this instance handed up in its hello — what consumer
// hellos for its reported children are answered with (establishment by
// lineage, communication.md "Establishment: two planes"). A refcounted
// handle in OUR table: onDriverExit must close it, or every restart leaks a
// slot of the manager's 32 until no capability can arrive at all.
endpoint: ?ipc.Handle = null,
fn name(driver: *const Driver) []const u8 {
return driver.name_buffer[0..driver.name_len];
@@ -148,23 +173,6 @@ var test_scanout_killed = false;
var test_kill_pid: u32 = 0;
var test_kill_due_ns: u64 = 0;
/// The application subscribers (M18.3, the input-service pattern): endpoints
/// handed over as capabilities, each receiving every child add/remove as a
/// buffered message. A subscriber whose endpoint stops accepting (it died) is
/// dropped on the failed send.
const maximum_subscribers = 8;
var subscribers: [maximum_subscribers]?ipc.Handle = .{null} ** maximum_subscribers;
/// Publish one event (a ChildAdded or ChildRemoved struct, the same encoding
/// the bus drivers send) to every subscriber.
fn publishEvent(event: []const u8) void {
for (&subscribers) |*slot| {
if (slot.*) |handle| {
if (!ipc.send(handle, event)) slot.* = null; // dead subscriber
}
}
}
/// The manager's mirror of what bus drivers report (docs/device-manager.md "the
/// tree"): the children, keyed by (parent, bus address), each remembering which
/// driver instance reported it — that is what death-pruning sweeps by.
@@ -204,17 +212,41 @@ fn addChild(parent: u64, bus_address: u64, identity: u64, device_id: u64, report
/// protocol state (slots, rings) that died with the process — keeping the nodes
/// would be keeping a lie. The restarted instance rediscovers and re-reports.
/// Watchers hear the honest story: removed now, added again on rediscovery.
///
/// **A reporter's death reaps its subtree.** The class drivers spawned for the
/// pruned children hold channels into the dead process; they cannot observe
/// the death themselves (an HID driver blocks on interrupt reports that will
/// simply never come — a silent zombie), and their still-`used` entries would
/// make the matcher's dedupe refuse the respawn when the re-report arrives.
/// So each is killed and its entry cleared: the re-report spawns a fresh
/// instance, whose hello fetches the successor's channel. That is the restart
/// story working — kill a bus driver and only its subtree blinks
/// (docs/establishment-planes-plan.md P3).
fn pruneChildrenOf(reporter: u32) void {
for (&children) |*child| {
if (child.used and child.reporter == reporter) {
std.log.info("child removed (device {d} port {d})", .{ child.parent, child.bus_address });
reapDriverBoundTo(child.device_id);
child.used = false;
const event = device_manager_protocol.ChildRemoved{ .parent = child.parent, .bus_address = child.bus_address };
publishEvent(std.mem.asBytes(&event));
Serve.publish(.child_removed, 0, .{ .parent = child.parent, .bus_address = child.bus_address });
}
}
}
/// Kill the driver bound to a pruned child and clear its entry — the exit
/// notification that follows finds no entry and is ignored, so the death is
/// never double-counted, and the freed entry is what lets the re-report
/// respawn. The device it was given returns to us by the kernel's loan rule.
fn reapDriverBoundTo(device_id: u64) void {
const driver = driverEntryForDevice(device_id) orelse return;
if (driver.process_id != 0) {
std.log.info("reaping {s} (its provider died)", .{driver.name()});
_ = process.kill(driver.process_id);
}
if (driver.endpoint) |endpoint| _ = ipc.close(endpoint);
driver.* = .{};
}
/// How many children a driver instance has reported (the test-usb-restart
/// trigger counts these).
fn childCountOf(reporter: u32) u32 {
@@ -225,7 +257,31 @@ fn childCountOf(reporter: u32) u32 {
return n;
}
/// The child a kernel device id belongs to — the lineage lookup: its
/// `.reporter` names the driver instance that provides it, which is how a
/// consumer's hello is routed to the right provider (communication.md
/// "Establishment: two planes"). Null when nothing reported it, or its
/// reporter died and pruned it — a retryable gap, not a verdict.
fn childByDevice(device_id: u64) ?*Child {
if (device_id == device_manager_protocol.no_device) return null;
for (&children) |*child| {
if (child.used and child.device_id == device_id) return child;
}
return null;
}
/// The driver entry a live process id belongs to. Zero is not a process id here:
/// it is what `onDriverExit` writes back to retire an id it has already acted on,
/// so a second notification for the same death matches nothing.
fn driverByName(name: []const u8) ?*Driver {
for (&drivers) |*driver| {
if (driver.used and std.mem.eql(u8, driver.name(), name)) return driver;
}
return null;
}
fn driverByProcess(process_id: u32) ?*Driver {
if (process_id == 0) return null;
for (&drivers) |*driver| {
if (driver.used and driver.process_id == process_id) return driver;
}
@@ -261,6 +317,22 @@ fn addDriver(name: []const u8, device_id: u64, speaks_protocol: bool) void {
/// device id as argv[1] when it has one, the hello deadline armed when it
/// speaks the protocol.
fn spawnDriver(driver: *Driver) void {
// Take the device before the driver exists, so there is no window in which anyone
// else could claim it — which is the whole of what makes the handover authoritative
// rather than advisory. Re-claiming across a restart is expected to say
// AlreadyClaimed once the manager already holds it, and that is fine: it means the
// device never left our hands while the driver was dead.
if (driver.device_id != device_manager_protocol.no_device) {
device.claim(driver.device_id) catch |e| switch (e) {
error.AlreadyClaimed => {}, // ours already, from a previous spawn of this driver
else => {
std.log.warn("cannot hold device {d} for {s}: {s}", .{ driver.device_id, driver.name(), @errorName(e) });
driver.state = .failed;
return;
},
};
}
var id_text: [20]u8 = undefined;
var arguments: [1][]const u8 = undefined;
var argument_count: usize = 0;
@@ -268,7 +340,14 @@ fn spawnDriver(driver: *Driver) void {
arguments[0] = std.fmt.bufPrint(&id_text, "{d}", .{driver.device_id}) catch return;
argument_count = 1;
}
const child = process.spawnSupervised(driver.name(), arguments[0..argument_count], manager_endpoint) orelse {
// The device rides the spawn, so the driver holds it before its first instruction.
// A transfer *after* spawning would leave a window in which the child is running
// without its hardware — closed on one machine, open on another
// (docs/bounds-track-plan.md, "the grant rides system_spawn").
const give = driver.device_id;
if (give != device_manager_protocol.no_device)
std.log.info("delegated device {d} to {s}", .{ give, driver.name() });
const child = process.spawnSupervisedWithDevice(driver.name(), arguments[0..argument_count], manager_endpoint, give) orelse {
std.log.info("failed to spawn {s}", .{driver.name()});
driver.state = .failed;
return;
@@ -293,8 +372,24 @@ fn spawnDriver(driver: *Driver) void {
/// is the whole restart decision: a clean exit meant to stop; anything else
/// restarts with backoff until the crash-loop cap.
fn onDriverExit(driver: *Driver) void {
pruneChildrenOf(driver.process_id);
const reason = process.exitReason(driver.process_id) orelse .fault;
const dead = driver.process_id;
// One death, two notifications: the manager is this driver's supervisor (its
// spawn named this endpoint) *and*, since P4c put the watcher table in the
// harness, a subscriber to published exits. Both badges carry the same id, and
// the ring delivers them separately — so the id is retired here, before any
// decision is taken, and the second notification finds no driver to act on.
// Without this the backoff would count one death twice and the crash-loop cap
// would fire at half the deaths it names.
driver.process_id = 0;
// The dead instance's serving endpoint is stale the moment it died — the
// kernel marked the endpoint dead, but our refcounted handle would sit in
// the 32-slot table forever. The successor's hello stores a fresh one.
if (driver.endpoint) |stale| {
_ = ipc.close(stale);
driver.endpoint = null;
}
pruneChildrenOf(dead);
const reason = process.exitReason(dead) orelse .fault;
if (reason == .exited) {
driver.state = .stopped;
std.log.info("{s} exited cleanly; not restarting", .{driver.name()});
@@ -357,6 +452,40 @@ fn initialise(endpoint: ipc.Handle) bool {
const total = device.enumerate(buffer);
const count = @min(total, buffer.len);
// The node discovery needs: the kernel seeds it, so it is in this same snapshot
// and can be handed over like any other assignment. Discovery used to find and
// claim it itself — the last driver that acquired hardware by naming it rather
// than being given it (docs/os-development/device-authority.md).
var tables_node: u64 = device_manager_protocol.no_device;
for (buffer[0..count]) |descriptor| {
if (descriptor.class == @intFromEnum(device.DeviceClass.acpi_tables)) {
tables_node = descriptor.id;
break;
}
}
// **Hold the firmware-discovered hardware, so none of it is left lying around.**
// A device nobody holds can be claimed by anyone, so every seeded device that
// carries mappable resources is taken here whether or not a driver wants it — the
// HPET most of all, which has an MMIO window and an IRQ and no user-space driver.
// Held by the manager it is inert; unheld it was there for the taking.
//
// Two deliberate exclusions:
// - the loader's framebuffer, which the compositor claims and which is not
// hardware anyone is delegated (the manager starts before display, so taking
// it here would break the boot screen);
// - anything with no resources, which grants nothing and so is not worth holding.
//
// This covers the boot snapshot only. A device *reported* later and matched to no
// driver stays claimable — the pci-cap and iommu-fault fixtures rely on exactly
// that to reach an unmatched NIC. Narrowing it further is a separate change with
// those fixtures in scope.
for (buffer[0..count]) |descriptor| {
if (descriptor.resource_count == 0) continue;
if (descriptor.class == @intFromEnum(device.DeviceClass.display)) continue;
device.claim(descriptor.id) catch continue; // already held, or not ours to take
}
var matched: usize = 0;
for (buffer[0..count]) |descriptor| {
if (descriptor.class == @intFromEnum(device.DeviceClass.pci_host_bridge)) {
@@ -378,7 +507,7 @@ fn initialise(endpoint: ipc.Handle) bool {
// under the neutral name "discovery", spawned once at startup. It finds and
// claims the acpi-tables (or devicetree-blob) node itself. Not a per-device
// match — it is the discoverer, not a driver bound to one device.
addDriver("discovery", device_manager_protocol.no_device, false);
addDriver("discovery", tables_node, false);
if (test_restart_mode) {
// The driver-restart scenario's fixture: claims device 0 (the tree
@@ -396,77 +525,148 @@ fn initialise(endpoint: ipc.Handle) bool {
}
fn onMessage(message: []const u8, reply: []u8, sender: u32, arrived: *ipc.Arrival) usize {
if (message.len < 1) return 0;
switch (message[0]) {
@intFromEnum(device_manager_protocol.Operation.child_added) => return onChildAdded(message, reply, sender),
@intFromEnum(device_manager_protocol.Operation.child_removed) => return onChildRemoved(message, reply, sender),
@intFromEnum(device_manager_protocol.Operation.enumerate) => return onEnumerate(reply),
@intFromEnum(device_manager_protocol.Operation.subscribe) => return onSubscribe(reply, arrived),
@intFromEnum(device_manager_protocol.Operation.hello) => {},
else => return 0,
}
if (message.len < device_manager_protocol.hello_size) return 0;
const hello = std.mem.bytesToValue(device_manager_protocol.Hello, message[0..device_manager_protocol.hello_size]);
var status: i32 = 0;
if (hello.version != device_manager_protocol.version) {
status = -1;
std.log.info("refused hello (version {d}) from process {d}", .{ hello.version, sender });
} else if (driverByProcess(sender)) |driver| {
driver.state = .running;
std.log.info("hello from {s} (device {d})", .{ driver.name(), hello.device_id });
// Resilience drill (V6): once, kill the virtio-gpu driver a moment after it hellos, so
// the normal restart policy respawns it — the compositor must survive and re-attach.
if (test_scanout_restart_mode and !test_scanout_killed and std.mem.eql(u8, driver.name(), "/system/drivers/virtio-gpu")) {
test_scanout_killed = true;
test_kill_pid = sender;
test_kill_due_ns = time.clock() + 1_500_000_000;
_ = time.timerOnce(manager_endpoint, 1600);
}
} else {
status = -1;
std.log.info("hello from unknown process {d}", .{sender});
}
const hello_reply = device_manager_protocol.HelloReply{ .status = status };
@memcpy(reply[0..device_manager_protocol.reply_size], std.mem.asBytes(&hello_reply));
return device_manager_protocol.reply_size;
return Serve.dispatch({}, handlers, message, sender, arrived, reply);
}
/// A bus driver reported a discovered device: mirror it, and in
/// test-usb-restart mode kill the reporter once after its second child — the
/// `subscribe` and `unsubscribe` are absent on purpose: the harness answers both,
/// and its table is what `publish` fans out over.
const handlers = Serve.Handlers{
.hello = onHello,
.child_added = onChildAdded,
.child_removed = onChildRemoved,
.enumerate = onEnumerate,
};
/// The handshake. The device this driver was assigned is the packet's target.
fn onHello(_: void, invocation: Invocation(device_manager_protocol.Hello), _: Answer(void)) isize {
if (invocation.request.version != device_manager_protocol.version) {
std.log.info("refused hello (version {d}) from process {d}", .{ invocation.request.version, invocation.sender });
return -envelope.EPROTO;
}
// A consumer is not a spawned driver: no entry, no deadline, no state —
// just establishment. It asks for the channel of the driver BOUND TO its
// target (fat asking for its volume's block provider). No channel is a
// retryable ack, exactly as for a device-role consumer.
//
// The residual, stated plainly: any process granted `open device-manager`
// can ask. The grant rows are the gate today, as they were when the block
// name was open-granted; a finer per-channel policy belongs to the same
// future as the spawn capability (device-authority.md).
if (invocation.request.role == @intFromEnum(device_manager_protocol.Role.consumer)) {
if (invocation.request.wants_channel != 0) {
if (driverEntryForDevice(invocation.target)) |provider| {
if (provider.endpoint) |serving| service.replyWithCapability(serving);
}
}
return 0;
}
const driver = driverByProcess(invocation.sender) orelse {
std.log.info("hello from unknown process {d}", .{invocation.sender});
return -envelope.EPERM;
};
driver.state = .running;
// A provider's hello carries its serving endpoint — the channel consumer
// hellos for its reported children are answered with. Stored on the entry
// (claimed from the turn, so the harness's defer leaves it alone); a
// re-hello replaces, closing the old handle rather than leaking the slot.
if (invocation.capability) |serving| {
if (driver.endpoint) |previous| _ = ipc.close(previous);
driver.endpoint = serving;
Serve.claimArrival();
}
// A consumer's hello asks for its device's provider: the child's reporter
// is the routing fact (establishment by lineage). No channel is not a
// refusal — the provider may be mid-restart and its re-report on the way —
// so the hello still acks and the consumer retries. Nothing is nominated
// unless asked: a capability sent to a caller that never reads one is a
// leaked slot in ITS table.
if (invocation.request.wants_channel != 0) {
if (childByDevice(invocation.target)) |child| {
if (driverByProcess(child.reporter)) |provider| {
if (provider.endpoint) |serving| service.replyWithCapability(serving);
}
}
}
std.log.info("hello from {s} (device {d})", .{ driver.name(), invocation.target });
// Resilience drill (V6): once, kill the virtio-gpu driver a moment after it hellos, so
// the normal restart policy respawns it — the compositor must survive and re-attach.
if (test_scanout_restart_mode and !test_scanout_killed and std.mem.eql(u8, driver.name(), "/system/drivers/virtio-gpu")) {
test_scanout_killed = true;
test_kill_pid = invocation.sender;
test_kill_due_ns = time.clock() + 1_500_000_000;
_ = time.timerOnce(manager_endpoint, 1600);
}
return 0;
}
/// A bus driver reported a discovered device: mirror it, publish it, match a
/// driver for it — and in the restart drills kill the reporter once, the
/// deterministic trigger for prune -> backoff -> respawn -> re-report.
fn onChildAdded(message: []const u8, reply: []u8, sender: u32) usize {
if (message.len < device_manager_protocol.child_added_size) return 0;
const report = std.mem.bytesToValue(device_manager_protocol.ChildAdded, message[0..device_manager_protocol.child_added_size]);
var status: i32 = 0;
fn onChildAdded(_: void, invocation: Invocation(device_manager_protocol.ChildAdded), _: Answer(void)) isize {
const report = invocation.request;
const sender = invocation.sender;
// The registered kernel device id is the packet's target, not a field: what
// the manager hands a matched driver as its argv assignment.
const device_id = invocation.target;
var status: isize = 0;
if (driverByProcess(sender)) |driver| {
if (!addChild(report.parent, report.bus_address, report.identity, report.device_id, sender)) status = -1;
if (!addChild(report.parent, report.bus_address, report.identity, device_id, sender)) status = -envelope.ENOSPC;
std.log.info("child added (device {d} port {d}, identity {d}) by {s}", .{ report.parent, report.bus_address, report.identity, driver.name() });
if (status == 0) publishEvent(message[0..device_manager_protocol.child_added_size]);
if (status == 0) Serve.publish(.child_added, device_id, report);
// Matching from reports (M19.3), now data-driven via the /system/configuration/devices.csv
// registry: a registered child gets the most-specific driver its identity
// matches, once — re-reports after a bus restart dedupe on the registered
// id, exactly like the registrations do.
if (status == 0 and report.device_id != device_manager_protocol.no_device) {
if (status == 0 and device_id != device_manager_protocol.no_device) {
const id = identityFromReport(report);
if (registry.matchDriver(registry_rules[0..registry_count], id)) |match| {
if (match.ambiguous)
std.log.info("/system/configuration/devices.csv: multiple equally-specific rules match the device {s} reported; binding {s}", .{ driver.name(), match.driver });
if (id.bus == .acpi) {
// An hid-matched driver (ps2-bus) is a singleton that finds its
// own devices once spawned — spawn it once, no device assignment.
if (!alreadySupervised(match.driver)) addDriver(match.driver, device_manager_protocol.no_device, false);
// An hid-matched driver is a singleton over one piece of hardware
// described by several nodes: the 8042 is a single controller whose
// I/O ports live under the keyboard node (PNP0303) while the mouse
// is a second node (PNP0F13). Two processes would fight over the
// same 0x60/0x64 registers, so there is exactly one instance — and
// it needs *every* matching device, however many the machine has
// (some have none, some one port, some two).
//
// The first rides the spawn; the rest are transferred to the
// running instance. Late arrival is fine here because the order is
// natural: the instance needs the controller node immediately and
// reaches the mouse only after the 8042 handshakes and identify.
if (!alreadySupervised(match.driver)) {
addDriver(match.driver, device_id, false);
} else if (driverByName(match.driver)) |running| {
if (running.process_id != 0) {
device.claim(device_id) catch |e| switch (e) {
error.AlreadyClaimed => {},
else => {
std.log.warn("cannot hold device {d} for {s}: {s}", .{ device_id, match.driver, @errorName(e) });
return status;
},
};
device.transfer(device_id, running.process_id) catch |e| {
std.log.warn("could not give device {d} to {s}: {s}", .{ device_id, match.driver, @errorName(e) });
return status;
};
std.log.info("delegated device {d} to {s} (already running)", .{ device_id, match.driver });
}
}
} else {
// A per-device driver: one instance, the registered id as argv[1].
if (!driverForDevice(report.device_id)) addDriver(match.driver, report.device_id, true);
if (!driverForDevice(device_id)) addDriver(match.driver, device_id, true);
}
}
}
} else {
status = -1;
status = -envelope.EPERM;
}
const report_reply = device_manager_protocol.ReportReply{ .status = status };
@memcpy(reply[0..@sizeOf(device_manager_protocol.ReportReply)], std.mem.asBytes(&report_reply));
if (test_pci_restart_mode and !test_usb_killed) {
if (driverByProcess(sender)) |driver| {
if (std.mem.eql(u8, driver.name(), "pci-bus") and childCountOf(sender) >= 3) {
@@ -494,66 +694,63 @@ fn onChildAdded(message: []const u8, reply: []u8, sender: u32) usize {
}
}
}
return @sizeOf(device_manager_protocol.ReportReply);
return status;
}
/// A bus driver reported a device gone (hot-unplug; no sender exists yet, but
/// the handler is protocol-complete — death-pruning covers removal until then).
fn onChildRemoved(message: []const u8, reply: []u8, sender: u32) usize {
if (message.len < device_manager_protocol.child_removed_size) return 0;
const report = std.mem.bytesToValue(device_manager_protocol.ChildRemoved, message[0..device_manager_protocol.child_removed_size]);
var status: i32 = -1;
/// A bus driver reported a device gone (hot-unplug). Addressed by the composite
/// (parent, bus address) the reporter knows, which is why that pair is the
/// packet's body rather than its target.
fn onChildRemoved(_: void, invocation: Invocation(device_manager_protocol.ChildRemoved), _: Answer(void)) isize {
const report = invocation.request;
var status: isize = -envelope.ENOENT;
for (&children) |*child| {
if (child.used and child.parent == report.parent and child.bus_address == report.bus_address and child.reporter == sender) {
if (child.used and child.parent == report.parent and child.bus_address == report.bus_address and child.reporter == invocation.sender) {
std.log.info("child removed (device {d} port {d})", .{ child.parent, child.bus_address });
// Unplug reaps exactly like reporter death (pruneChildrenOf): the
// bound driver's device is gone and it cannot observe that — it
// blocks on reports that will never come — and its stale entry
// would make the dedupe refuse the respawn when the device is
// PLUGGED BACK IN. Reap now, and a replug's re-report rebinds.
reapDriverBoundTo(child.device_id);
child.used = false;
status = 0;
}
}
const report_reply = device_manager_protocol.ReportReply{ .status = status };
@memcpy(reply[0..@sizeOf(device_manager_protocol.ReportReply)], std.mem.asBytes(&report_reply));
return @sizeOf(device_manager_protocol.ReportReply);
return status;
}
/// An application asked for the tree: the mirror, as a header plus entries.
fn onEnumerate(reply: []u8) usize {
var count: u32 = 0;
var offset: usize = @sizeOf(device_manager_protocol.EnumerateReply);
/// The reserved `enumerate` verb: the mirror, one `ChildEntry` per known child,
/// packed into the reply's tail. How many arrived is the reply's own length —
/// `Status.len` — so no count header is spent saying it twice.
fn onEnumerate(_: void, invocation: Invocation(void), answer: Answer(void)) isize {
const entry_size = @sizeOf(device_manager_protocol.ChildEntry);
const tail = answer.tail();
// `target` is the page cursor: skip that many known children first. One
// reply holds only a handful of entries, and a real tree (a dozen ACPI
// nodes before the first USB child) outgrew one packet — the storage
// child silently never fit, which is precisely the truncation shape the
// bounds audit exists to forbid. A caller pages until a short page.
var skip = invocation.target;
var written: usize = 0;
for (&children) |*child| {
if (!child.used) continue;
if (offset + @sizeOf(device_manager_protocol.ChildEntry) > reply.len) break;
const entry = device_manager_protocol.ChildEntry{ .parent = child.parent, .bus_address = child.bus_address, .identity = child.identity };
@memcpy(reply[offset..][0..@sizeOf(device_manager_protocol.ChildEntry)], std.mem.asBytes(&entry));
offset += @sizeOf(device_manager_protocol.ChildEntry);
count += 1;
}
const header = device_manager_protocol.EnumerateReply{ .status = 0, .count = count };
@memcpy(reply[0..@sizeOf(device_manager_protocol.EnumerateReply)], std.mem.asBytes(&header));
return offset;
}
/// An application subscribed: its endpoint arrived as the call's capability. The
/// table taking a slot is what claims it (`take`); a full table refuses and lets
/// the turn close it, so a subscribe storm cannot spend the handle table too.
fn onSubscribe(reply: []u8, arrived: *ipc.Arrival) usize {
var status: i32 = -1;
if (arrived.peek() != null) {
for (&subscribers) |*slot| {
if (slot.* == null) {
slot.* = arrived.take(); // claimed: the table holds it from here
status = 0;
break;
}
if (skip > 0) {
skip -= 1;
continue;
}
if (written + entry_size > tail.len) break;
const entry = device_manager_protocol.ChildEntry{ .parent = child.parent, .bus_address = child.bus_address, .identity = child.identity, .device_id = child.device_id };
@memcpy(tail[written..][0..entry_size], std.mem.asBytes(&entry));
written += entry_size;
}
const report_reply = device_manager_protocol.ReportReply{ .status = status };
@memcpy(reply[0..@sizeOf(device_manager_protocol.ReportReply)], std.mem.asBytes(&report_reply));
return @sizeOf(device_manager_protocol.ReportReply);
return @intCast(written);
}
fn onNotification(badge: u64) void {
if (badge & ipc.notify_exit_bit != 0) {
const dead: u32 = @intCast(badge & ~(ipc.notify_badge_bit | ipc.notify_exit_bit));
// The harness has already swept the watcher table for this death; what is
// left is the manager's own concern, its supervised drivers.
if (driverByProcess(dead)) |driver| onDriverExit(driver);
return;
}
@@ -572,5 +769,6 @@ pub fn main(init: process.Init) void {
.init = initialise,
.on_message = onMessage,
.on_notification = onNotification,
.subscribers = Serve.hooks,
});
}
+38 -27
View File
@@ -13,6 +13,7 @@ const memory = @import("memory");
const logging = @import("logging");
const compositor = @import("compositor.zig");
const envelope = @import("envelope");
const scanout_protocol = @import("scanout-protocol");
const Rect = compositor.Rect;
const Surface = compositor.Surface;
@@ -73,10 +74,12 @@ pub const Gop = struct {
return null;
};
if (!device.claim(found.id)) {
_ = logging.write("display: could not claim the framebuffer\n");
device.claim(found.id) catch |e| {
var line: [96]u8 = undefined;
_ = logging.write(std.fmt.bufPrint(&line, "display: could not claim the framebuffer: {s}\n", .{@errorName(e)}) catch
"display: could not claim the framebuffer\n");
return null;
}
};
// Resource 0 is the framebuffer memory window; the kernel maps it write-combining
// because the resource carries that flag (docs/display-plan.md D1).
const front_base = device.mmioMap(found.id, 0) orelse {
@@ -188,45 +191,53 @@ pub const VirtioGpu = struct {
/// accumulated; the driver transfers + fenced-flushes the whole frame.
pub fn present(self: *const VirtioGpu, damage: []const Rect) void {
_ = damage;
var request = scanout_protocol.Request{
.operation = @intFromEnum(scanout_protocol.Operation.present),
.width = self.width,
.height = self.height,
};
var reply: [scanout_protocol.reply_size]u8 = undefined;
_ = ipc.call(self.scanout, std.mem.asBytes(&request), &reply) catch {};
_ = call(self.scanout, .present, .{ .width = self.width, .height = self.height });
}
/// Fill `out` with the driver's offered modes; returns how many were written.
pub fn modes(self: *const VirtioGpu, out: []Mode) usize {
var request = scanout_protocol.Request{ .operation = @intFromEnum(scanout_protocol.Operation.get_modes) };
var reply: [scanout_protocol.modes_reply_size]u8 = undefined;
const n = ipc.call(self.scanout, std.mem.asBytes(&request), &reply) catch return 0;
if (n < scanout_protocol.modes_reply_size) return 0;
const answer = std.mem.bytesToValue(scanout_protocol.ModesReply, reply[0..scanout_protocol.modes_reply_size]);
if (answer.status != 0) return 0;
const count = @min(@min(answer.count, scanout_protocol.max_modes), out.len);
for (0..count) |i| out[i] = answer.modes[i];
const answered = call(self.scanout, .get_modes, {}) orelse return 0;
const offered = Scanout.decodeReply(.get_modes, answered.packet[0..answered.len]) orelse return 0;
const count = @min(@min(offered.count, scanout_protocol.max_modes), out.len);
for (0..count) |i| out[i] = offered.modes[i];
return count;
}
/// Change the scanout resolution. On success the active `width`/`height` update (the shared
/// surface — sized to the max mode — is unchanged, so `stride` stays put).
pub fn setMode(self: *VirtioGpu, w: u32, h: u32) bool {
if (w == 0 or h == 0 or w > self.stride) return false;
var request = scanout_protocol.Request{
.operation = @intFromEnum(scanout_protocol.Operation.set_mode),
.width = w,
.height = h,
};
var reply: [scanout_protocol.reply_size]u8 = undefined;
const n = ipc.call(self.scanout, std.mem.asBytes(&request), &reply) catch return false;
if (n < scanout_protocol.reply_size) return false;
if (std.mem.bytesToValue(scanout_protocol.Reply, reply[0..scanout_protocol.reply_size]).status != 0) return false;
_ = call(self.scanout, .set_mode, .{ .width = w, .height = h }) orelse return false;
self.width = w;
self.height = h;
return true;
}
};
const Scanout = scanout_protocol.Protocol;
/// A reply the driver answered with, kept whole so the caller can decode the
/// verb's own fixed part out of it.
const Answered = struct {
packet: [scanout_protocol.message_maximum]u8,
len: usize,
};
/// One request at the scanout driver. Null covers both a transport failure and a
/// driver that refused — a present that did not happen is a present that did not
/// happen, and this backend has nothing to do about either but skip the frame.
fn call(
scanout: ipc.Handle,
comptime operation: Scanout.Operation,
request: Scanout.RequestOf(operation),
) ?Answered {
var packet: [scanout_protocol.message_maximum]u8 = undefined;
const framed = Scanout.encodeRequest(operation, 0, request, &.{}, &packet) orelse return null;
var answered: Answered = .{ .packet = undefined, .len = 0 };
answered.len = ipc.call(scanout, framed, &answered.packet) catch return null;
const status = envelope.statusOf(answered.packet[0..answered.len]) orelse return null;
if (status.status != 0) return null;
return answered;
}
/// The pluggable scanout backend. A tagged union so the compositor holds one value and
/// dispatches without caring which is active; the `virtio` native backend joins `gop` at V4.
pub const Backend = union(enum) {
+3 -2
View File
@@ -10,8 +10,9 @@ pub fn build(b: *std.Build) void {
.name = "display",
.root_source_file = b.path("display.zig"),
.imports = &.{
"channel", "display-client", "display-protocol", "driver", "input-client", "ipc",
"logging", "memory", "scanout-protocol", "service", "thread", "time",
"channel", "display-client", "display-protocol", "driver", "envelope", "input-client",
"ipc", "logging", "memory", "process", "scanout-protocol",
"service", "thread", "time",
},
.threaded = true, // real atomics/TLS (docs/threading.md)
});
+186 -95
View File
@@ -19,6 +19,7 @@ const std = @import("std");
const channel = @import("channel");
const ipc = @import("ipc");
const input = @import("input-client");
const process = @import("process");
const Thread = @import("thread").Thread;
const service = @import("service");
const time = @import("time");
@@ -28,10 +29,22 @@ const logging = @import("logging");
const compositor = @import("compositor.zig");
const backend_mod = @import("backend.zig");
const envelope = @import("envelope");
const display_protocol = @import("display-protocol");
const Rect = compositor.Rect;
const Surface = compositor.Surface;
/// The generated display dispatch. One compositor per process, so the handler
/// context is empty and the layer stack stays in this file's globals.
const Serve = display_protocol.Protocol.Provider(void);
const Invocation = envelope.Invocation;
const Answer = envelope.Answer;
/// What a handler returns when the layer named in `Header.target` is not one of
/// ours, or a mode was refused.
const refused: isize = -envelope.ENOENT;
/// The active scanout backend — the GOP framebuffer at boot, upgraded to a native driver
/// (virtio-gpu) when one announces itself (V4).
var backend: backend_mod.Backend = undefined;
@@ -62,8 +75,22 @@ var background: u32 = 0;
/// small copies rather than one huge bounding box (see compositor.DamageList).
const maximum_layers = 16;
/// A layer belongs to the client that created it. `owner` is the kernel-stamped
/// badge of that task, and `service_owned` (0, an id no task wears) marks the
/// compositor's own layers — the cursor sprite and the self-check pair — which
/// this file creates by direct call rather than over the protocol.
///
/// Layer ids are slots in a sixteen-entry table: small, dense, and guessable, so
/// before this field any client could configure, draw into, or destroy any
/// other's layer — including the cursor. The check lives in the protocol handlers
/// (docs/os-development/protocol-namespace.md: handles validated against the
/// badge); the internal helpers stay unscoped precisely so the compositor can
/// still drive its own.
const service_owned: u32 = 0;
const Layer = struct {
used: bool = false,
owner: u32 = service_owned,
x: i32 = 0,
y: i32 = 0,
z: u32 = 0,
@@ -177,7 +204,8 @@ fn layerAt(id: u32) ?*Layer {
return &layers[id];
}
fn createLayer(x: i32, y: i32, w: u32, h: u32, z: u32, visible: bool) ?u32 {
/// Create a layer for `owner` — `service_owned` for the compositor's own.
fn createLayer(owner: u32, x: i32, y: i32, w: u32, h: u32, z: u32, visible: bool) ?u32 {
if (w == 0 or h == 0) return null;
const slot = freeLayer() orelse return null;
const len = @as(usize, w) * h * 4;
@@ -185,6 +213,7 @@ fn createLayer(x: i32, y: i32, w: u32, h: u32, z: u32, visible: bool) ?u32 {
if (memory.mmapFailed(base)) return null;
layers[slot] = .{
.used = true,
.owner = owner,
.x = x,
.y = y,
.z = z,
@@ -314,11 +343,18 @@ fn verifyNativePresent() void {
/// `systemSharedMemoryMap`) — the pixels stay ours after the handle naming them
/// goes, and a driver that dies and re-announces no longer costs a handle slot
/// per restart.
fn attachScanout(stride: u32, width: u32, height: u32, format: u32, refresh_hz: u32, arrived: *ipc.Arrival, reply: []u8) usize {
const cap = arrived.peek() orelse return fail(reply);
if (width == 0 or height == 0 or stride < width) return fail(reply);
const mapped = memory.sharedMap(cap) orelse return fail(reply);
const scanout = channel.openEndpoint("scanout") orelse return fail(reply);
fn onAttachScanout(_: void, invocation: Invocation(display_protocol.AttachScanout), _: Answer(void)) isize {
const announce = invocation.request;
const stride = announce.stride;
const width = announce.width;
const height = announce.height;
const format = announce.format;
const refresh_hz = announce.refresh_hz;
const cap = invocation.capability orelse return refused;
if (width == 0 or height == 0 or stride < width) return refused;
const mapped = memory.sharedMap(cap) orelse return refused;
const scanout = channel.openEndpoint("scanout") orelse return refused;
// A second announce means the driver died and was restarted (V6): re-attach to its fresh
// scanout. (The previous shared mapping leaks — there is no shared_memory_unmap syscall yet — but the
// frames are the dead driver's, reclaimed on its exit; a handful across a crash is benign.)
@@ -346,7 +382,7 @@ fn attachScanout(stride: u32, width: u32, height: u32, format: u32, refresh_hz:
"display: scanout re-attached\n"
else
"display: scanout upgraded to virtio-gpu\n");
return ok(reply);
return 0;
}
/// After the native upgrade is verified, prove the runtime-resolution-change and fenced-present
@@ -401,8 +437,8 @@ fn selfCheck() void {
const format = backend.info().format;
const red = display_protocol.pack(format, 0xC0, 0x20, 0x20);
const green = display_protocol.pack(format, 0x20, 0xC0, 0x20);
const bottom = createLayer(100, 100, 80, 80, 0, true) orelse return fail_check("create");
const top = createLayer(140, 140, 80, 80, 1, true) orelse return fail_check("create");
const bottom = createLayer(service_owned, 100, 100, 80, 80, 0, true) orelse return fail_check("create");
const top = createLayer(service_owned, 140, 140, 80, 80, 1, true) orelse return fail_check("create");
_ = fillLayer(bottom, Rect.init(0, 0, 80, 80), red);
_ = fillLayer(top, Rect.init(0, 0, 80, 80), green);
present();
@@ -567,7 +603,7 @@ fn startCursorTracking() void {
const mode = backend.info();
cursor_origin_x = @divTrunc(@as(i32, @intCast(mode.width)), 2);
cursor_origin_y = @divTrunc(@as(i32, @intCast(mode.height)), 2);
const id = createLayer(cursor_origin_x, cursor_origin_y, cursor_size, cursor_size, cursor_z, true) orelse {
const id = createLayer(service_owned, cursor_origin_x, cursor_origin_y, cursor_size, cursor_size, cursor_z, true) orelse {
_ = logging.write("display: could not create cursor layer\n");
return;
};
@@ -584,6 +620,9 @@ fn startCursorTracking() void {
fn initialise(endpoint: ipc.Handle) bool {
service_endpoint = endpoint;
// Layers are per-client state, so the compositor needs deaths: a client that
// crashes leaves its surfaces on screen and its slots spent otherwise.
_ = process.subscribeExits(endpoint);
// Pick the scanout backend (GOP today). It logs the reason on failure.
backend = backend_mod.select() orelse return false;
@@ -609,97 +648,149 @@ fn initialise(endpoint: ipc.Handle) bool {
return true;
}
fn writeReply(reply: []u8, value: display_protocol.Reply) usize {
const bytes = std.mem.asBytes(&value);
@memcpy(reply[0..bytes.len], bytes);
return bytes.len;
// --- the protocol handlers --------------------------------------------------
//
// A layer id is `Header.target` on every verb that names one, so no handler
// reads a layer out of its own request any more. `target` is a u64 and a layer
// id a u32: a value that does not fit is not a layer of ours, and `layerAt`
// refuses it the same way an out-of-range one is refused.
/// The layer a packet addresses, **for the task that sent it**: null unless the
/// target names a used slot this sender created. A layer that is somebody else's
/// is refused exactly as one that never existed, so a client cannot use the
/// refusal to learn which ids are live (P3's refusal-equals-absence, applied to
/// ids rather than names).
fn targetLayer(target: u64, sender: u32) ?u32 {
if (target > std.math.maxInt(u32)) return null; // a layer id is a u32
const id: u32 = @intCast(target);
const layer = layerAt(id) orelse return null;
if (layer.owner != sender) return null;
return id;
}
fn ok(reply: []u8) usize {
return writeReply(reply, .{ .status = 0 });
}
fn fail(reply: []u8) usize {
return writeReply(reply, .{ .status = -1 });
}
fn onMessage(message: []const u8, reply: []u8, sender: u32, arrived: *ipc.Arrival) usize {
_ = sender;
if (message.len < display_protocol.request_size) return fail(reply);
const request = std.mem.bytesToValue(display_protocol.Request, message[0..display_protocol.request_size]);
const payload = message[display_protocol.request_size..];
// Switch on the raw operation value — an out-of-range one must fail cleanly, not
// panic an `@enumFromInt`.
switch (request.operation) {
@intFromEnum(display_protocol.Operation.info) => {
const m = backend.info();
return writeReply(reply, .{ .status = 0, .width = m.width, .height = m.height, .pitch = m.pitch, .format = m.format });
},
@intFromEnum(display_protocol.Operation.create_layer) => {
// x/y are signed coordinates carried in the u32 wire fields — reinterpret the
// bits (@bitCast), don't range-check (@intCast) which a negative would fail.
const slot = createLayer(@bitCast(request.x), @bitCast(request.y), request.width, request.height, request.z, request.visible != 0) orelse return fail(reply);
return writeReply(reply, .{ .status = 0, .layer = slot });
},
@intFromEnum(display_protocol.Operation.configure_layer) => {
return if (configureLayer(request.layer, @bitCast(request.x), @bitCast(request.y), request.z, request.visible != 0)) ok(reply) else fail(reply);
},
@intFromEnum(display_protocol.Operation.destroy_layer) => {
return if (destroyLayer(request.layer)) ok(reply) else fail(reply);
},
@intFromEnum(display_protocol.Operation.fill_rect) => {
const local = Rect.init(@bitCast(request.x), @bitCast(request.y), @intCast(request.width), @intCast(request.height));
return if (fillLayer(request.layer, local, request.colour)) ok(reply) else fail(reply);
},
@intFromEnum(display_protocol.Operation.blit_tile) => {
return if (blitLayer(request.layer, @bitCast(request.x), @bitCast(request.y), request.width, request.height, payload)) ok(reply) else fail(reply);
},
@intFromEnum(display_protocol.Operation.damage) => {
const l = layerAt(request.layer) orelse return fail(reply);
const screen = Rect{ .x = l.x + @as(i32, @bitCast(request.x)), .y = l.y + @as(i32, @bitCast(request.y)), .w = @intCast(request.width), .h = @intCast(request.height) };
addDamage(screen.intersect(layerScreenRect(l)));
return ok(reply);
},
@intFromEnum(display_protocol.Operation.present) => {
// Scheduled, not immediate: the frame clock composites the accumulated damage
// at the next tick, so back-to-back client presents coalesce into one frame.
schedulePresent();
return ok(reply);
},
@intFromEnum(display_protocol.Operation.attach_scanout) => {
return attachScanout(request.x, request.width, request.height, request.colour, request.y, arrived, reply);
},
@intFromEnum(display_protocol.Operation.set_mode) => {
if (!backend.setMode(request.width, request.height)) return fail(reply);
addDamage(screenRect()); // repaint the whole screen at the new resolution
present();
return ok(reply);
},
@intFromEnum(display_protocol.Operation.get_modes) => {
var list: [4]backend_mod.Mode = undefined;
const count = backend.modes(&list);
var response = display_protocol.ModesReply{ .status = 0, .count = @intCast(count), .modes = undefined };
for (0..display_protocol.max_modes) |i| {
response.modes[i] = if (i < count)
.{ .width = list[i].width, .height = list[i].height }
else
.{ .width = 0, .height = 0 };
}
const bytes = std.mem.asBytes(&response);
@memcpy(reply[0..bytes.len], bytes);
return bytes.len;
},
else => return fail(reply),
/// Destroy every layer a dead client left behind — its surface is pages nobody
/// will ever draw into again, and its slot is one of sixteen. The published
/// exit events are the notice, the same sweep idiom the FAT server uses for open
/// files and the harness uses for subscribers.
fn releaseLayersOf(dead: u32) void {
var released: u32 = 0;
for (&layers, 0..) |*layer, id| {
if (layer.used and layer.owner == dead) {
_ = destroyLayer(@intCast(id));
released += 1;
}
}
if (released != 0) {
std.log.info("released {d} layer(s) for dead client {d}", .{ released, dead });
schedulePresent(); // the screen still shows what they painted
}
}
/// Two notification sources reach the compositor, and one coalesced badge can carry
/// both, so each bit is handled independently. A **message-notification** is a poke from
/// the mouse-listener thread (a buffered self-`ipc.send`, `notify_message_bit`): fold the
/// newest cursor position into the scene. A **timer** (`notify_timer_bit`) is the frame
/// clock — or the deferred first native present after `attach_scanout` — either way,
/// present the accumulated damage.
fn onInfo(_: void, _: Invocation(void), answer: Answer(display_protocol.Info)) isize {
const mode = backend.info();
answer.set(.{ .width = mode.width, .height = mode.height, .pitch = mode.pitch, .format = mode.format });
return 0;
}
fn onCreateLayer(_: void, invocation: Invocation(display_protocol.CreateLayer), answer: Answer(display_protocol.Created)) isize {
const request = invocation.request;
const slot = createLayer(invocation.sender, request.x, request.y, request.width, request.height, request.z, request.visible != 0) orelse return refused;
answer.set(.{ .layer = slot });
return 0;
}
fn onConfigureLayer(_: void, invocation: Invocation(display_protocol.ConfigureLayer), _: Answer(void)) isize {
const id = targetLayer(invocation.target, invocation.sender) orelse return refused;
const request = invocation.request;
return if (configureLayer(id, request.x, request.y, request.z, request.visible != 0)) 0 else refused;
}
fn onDestroyLayer(_: void, invocation: Invocation(void), _: Answer(void)) isize {
const id = targetLayer(invocation.target, invocation.sender) orelse return refused;
return if (destroyLayer(id)) 0 else refused;
}
fn onFillRect(_: void, invocation: Invocation(display_protocol.FillRect), _: Answer(void)) isize {
const id = targetLayer(invocation.target, invocation.sender) orelse return refused;
const request = invocation.request;
const local = Rect.init(request.x, request.y, @intCast(request.width), @intCast(request.height));
return if (fillLayer(id, local, request.colour)) 0 else refused;
}
fn onBlitTile(_: void, invocation: Invocation(display_protocol.BlitTile), _: Answer(void)) isize {
const id = targetLayer(invocation.target, invocation.sender) orelse return refused;
const request = invocation.request;
return if (blitLayer(id, request.x, request.y, request.width, request.height, invocation.tail)) 0 else refused;
}
fn onDamage(_: void, invocation: Invocation(display_protocol.Damage), _: Answer(void)) isize {
const id = targetLayer(invocation.target, invocation.sender) orelse return refused;
const l = layerAt(id) orelse return refused;
const request = invocation.request;
const screen = Rect{ .x = l.x + request.x, .y = l.y + request.y, .w = @intCast(request.width), .h = @intCast(request.height) };
addDamage(screen.intersect(layerScreenRect(l)));
return 0;
}
fn onPresent(_: void, _: Invocation(void), _: Answer(void)) isize {
// Scheduled, not immediate: the frame clock composites the accumulated damage
// at the next tick, so back-to-back client presents coalesce into one frame.
schedulePresent();
return 0;
}
fn onSetMode(_: void, invocation: Invocation(display_protocol.SetMode), _: Answer(void)) isize {
if (!backend.setMode(invocation.request.width, invocation.request.height)) return refused;
addDamage(screenRect()); // repaint the whole screen at the new resolution
present();
return 0;
}
fn onGetModes(_: void, _: Invocation(void), answer: Answer(display_protocol.Modes)) isize {
var list: [4]backend_mod.Mode = undefined;
const count = backend.modes(&list);
var modes = display_protocol.Modes{ .count = @intCast(count) };
for (0..@min(count, display_protocol.max_modes)) |i| {
modes.modes[i] = .{ .width = list[i].width, .height = list[i].height };
}
answer.set(modes);
return 0;
}
const handlers = Serve.Handlers{
.info = onInfo,
.create_layer = onCreateLayer,
.configure_layer = onConfigureLayer,
.destroy_layer = onDestroyLayer,
.fill_rect = onFillRect,
.blit_tile = onBlitTile,
.damage = onDamage,
.present = onPresent,
.attach_scanout = onAttachScanout,
.set_mode = onSetMode,
.get_modes = onGetModes,
};
fn onMessage(message: []const u8, reply: []u8, sender: u32, arrived: *ipc.Arrival) usize {
// The one capability this service is ever handed is the scanout driver's
// shared surface, and `attachScanout` deliberately does not claim it (the
// mapping holds its own reference) — so the capability is peeked, never
// taken, and the turn closes it.
return Serve.dispatch({}, handlers, message, sender, arrived.peek(), reply);
}
/// Three notification sources reach the compositor, and one coalesced badge can carry
/// more than one, so each bit is handled independently. A **message-notification** is a
/// poke from the mouse-listener thread (a buffered self-`ipc.send`, `notify_message_bit`):
/// fold the newest cursor position into the scene. A **timer** (`notify_timer_bit`) is the
/// frame clock — or the deferred first native present after `attach_scanout` — either way,
/// present the accumulated damage. A **published exit** (`notify_exit_bit`) is a client
/// gone: release the layers it left.
fn onNotification(badge: u64) void {
if (badge & ipc.notify_exit_bit != 0) {
releaseLayersOf(@intCast(badge & ~(ipc.notify_badge_bit | ipc.notify_exit_bit)));
return;
}
if (badge & ipc.notify_message_bit != 0) renderCursor();
if (badge & ipc.notify_timer_bit != 0) frameTick();
}
+3 -1
View File
@@ -10,7 +10,9 @@ pub fn build(b: *std.Build) void {
.name = "fat",
.root_source_file = b.path("fat.zig"),
.imports = &.{
"block", "file-system", "ipc", "logging", "memory", "process", "service", "time",
"block", "channel", "device-manager-protocol", "driver",
"envelope", "file-system", "ipc", "logging",
"memory", "process", "service", "time",
"vfs-protocol",
},
});
+210 -104
View File
@@ -10,6 +10,9 @@
//! it.
const std = @import("std");
const channel = @import("channel");
const device_manager_protocol = @import("device-manager-protocol");
const driver = @import("driver");
const ipc = @import("ipc");
const process = @import("process");
const service = @import("service");
@@ -20,8 +23,17 @@ const memory = @import("memory");
const logging = @import("logging");
const engine = @import("engine.zig");
const on_disk = @import("on-disk.zig");
const envelope = @import("envelope");
const vfs_protocol = @import("vfs-protocol");
/// The generated vfs dispatch, bound to this server. There is one FAT volume per
/// process, so the handler context is empty and the state stays where it was: in
/// this file's globals.
const Serve = vfs_protocol.Protocol.Provider(void);
const Invocation = envelope.Invocation;
const Answer = envelope.Answer;
const mount_point = "/volumes/usb";
// The engine's BlockDevice, backed by the `.block` driver plus a DMA bounce
@@ -57,8 +69,9 @@ var ipc_block: IpcBlock = undefined;
var device_dirty: bool = false;
var filesystem: engine.FileSystem = undefined;
// Open handles the VFS holds against this backend: each maps a node id to a
// resolved engine node.
// Open handles clients hold against this backend: each maps a node id to a
// resolved engine node, and to the client that opened it. `owner` is the
// kernel-stamped badge of the opening task — the only source identity there is.
const OpenNode = struct { used: bool = false, node: engine.Node = undefined, owner: u32 = 0 };
var open_nodes = [_]OpenNode{.{}} ** 32;
@@ -69,22 +82,32 @@ fn allocOpen() ?usize {
return null;
}
fn openAt(id: u64) ?*OpenNode {
/// The open node `id` names **for `owner`** — null unless the id is in range, in
/// use, and this client's own. Node ids are small integers drawn from a table of
/// thirty-two, so they are trivially guessable; before this check every client
/// honoured every other client's ids, which is the hole
/// docs/os-development/protocol-namespace.md names ("handles must be scoped per
/// client — validated against the badge"). Nothing else about them changed: they
/// are still per-session, still swept when their owner dies.
///
/// The owner is a *task*, not a process, because the badge is: a threaded client
/// reads and writes a node from the thread that opened it, exactly as the exit
/// sweep already released a worker thread's handles when that thread died.
fn openFor(id: u64, owner: u32) ?*OpenNode {
if (id >= open_nodes.len) return null;
const o = &open_nodes[@intCast(id)];
return if (o.used) o else null;
if (!o.used or o.owner != owner) return null;
return o;
}
fn writeReply(out: []u8, reply: vfs_protocol.Reply, payload: []const u8) usize {
@memcpy(out[0..vfs_protocol.reply_size], std.mem.asBytes(&reply));
const n = @min(payload.len, out.len - vfs_protocol.reply_size);
@memcpy(out[vfs_protocol.reply_size..][0..n], payload[0..n]);
return vfs_protocol.reply_size + n;
}
fn fail(out: []u8) usize {
return writeReply(out, .{ .status = -1 }, &.{});
}
/// What a handler returns when the thing asked for is not there — a bad node id,
/// a node that is someone else's, a path that does not resolve, a mutation the
/// volume refused. One errno for all of them, because a filesystem's failures are
/// all "no such thing" as far as the file API can act on them — and because
/// *someone else's* must be indistinguishable from *nobody's*, or the refusal
/// would itself tell a prober which ids are live (the same discipline the
/// protocol namespace's refused open follows).
const refused: isize = -envelope.ENOENT;
/// How often to look for a block device while none is mounted. Storage arriving
/// is EVENT-shaped (the usb chain registering, possibly after a driver restart),
@@ -96,6 +119,56 @@ const mount_retry_ms = 500;
var mounted = false;
var service_endpoint: ipc.Handle = 0;
/// The one channel to the device manager, opened on first need and kept — the
/// poll retries on it, never spending a handle-table slot per attempt.
var manager_handle: ?ipc.Handle = null;
/// Find the volume's provider through the device manager (establishment by
/// lineage, communication.md "Establishment: two planes" — `block` is not a
/// registry name; one storage process serves each stick): enumerate the
/// manager's tree, take the FIRST usb mass-storage child by enumeration order
/// (deterministic within a boot; single-volume by construction, and choosing
/// the BOOT volume by content when two sticks are present is the M21 remount
/// track), and consumer-hello for the channel of the driver bound to it.
/// Null until the chain is up — the caller's poll retries.
fn acquireVolume() ?block.Device {
const manager = manager_handle orelse opened: {
const handle = channel.openEndpoint("device-manager") orelse return null;
manager_handle = handle;
break :opened handle;
};
// The envelope's reserved `enumerate` verb, PAGED: one reply carries only
// a handful of entries and a real tree (a dozen ACPI nodes before the
// first USB child) is bigger, so `Header.target` is the start cursor and
// a short page is the end. Identity is the bus's native triple, for USB
// (base << 16) | (class << 8) | protocol — mass storage is base 0x08,
// subclass 0x06 (SCSI transparent), the same key devices.csv matches on.
const Entry = device_manager_protocol.ChildEntry;
var start: u64 = 0;
while (true) {
const enumerate = envelope.Header{ .operation = envelope.operation_enumerate, .target = start };
var reply: [device_manager_protocol.message_maximum]u8 = undefined;
const length = ipc.call(manager, std.mem.asBytes(&enumerate), &reply) catch return null;
const status = envelope.statusOf(reply[0..length]) orelse return null;
if (status.status != 0) return null;
const carried = @min(@as(usize, status.len), length -| envelope.prefix_size);
const tail = reply[envelope.prefix_size..][0..carried];
const count = tail.len / @sizeOf(Entry);
if (count == 0) return null; // the tree is exhausted; no volume yet
var index: usize = 0;
while (index < count) : (index += 1) {
const entry = std.mem.bytesToValue(Entry, tail[index * @sizeOf(Entry) ..][0..@sizeOf(Entry)]);
if (entry.device_id == device_manager_protocol.no_device) continue;
if ((entry.identity >> 16) & 0xff != 0x08 or (entry.identity >> 8) & 0xff != 0x06) continue;
const exchanged = driver.helloOn(manager, .consumer, entry.device_id, null, true) orelse return null;
const provider = exchanged.channel orelse continue; // its driver not up yet — next tick
return .{ .endpoint = provider };
}
start += count;
}
}
fn initialise(endpoint: ipc.Handle) bool {
service_endpoint = endpoint;
@@ -113,7 +186,7 @@ fn initialise(endpoint: ipc.Handle) bool {
/// `mounted` on success; a failure leaves everything untouched for the next tick.
fn tryBringUp() void {
if (mounted) return;
const device = block.tryOpen() orelse return;
const device = acquireVolume() orelse return;
const geometry = device.geometry() orelse {
_ = logging.write("/system/services/fat: block geometry unavailable\n");
return;
@@ -204,24 +277,133 @@ fn splitParent(path: []const u8) ParentLeaf {
};
}
fn handleOpen(out: []u8, path: []const u8, flags: u32, sender: u32) usize {
fn onOpen(_: void, invocation: Invocation(vfs_protocol.Open), answer: Answer(vfs_protocol.Opened)) isize {
const path = invocation.tail;
const flags = invocation.request.flags;
var node = filesystem.resolve(path);
if (node == null and flags & vfs_protocol.create != 0) {
const split = splitParent(path);
const parent = filesystem.resolve(split.parent) orelse return fail(out);
const parent = filesystem.resolve(split.parent) orelse return refused;
node = filesystem.createFile(parent, split.leaf);
}
var resolved = node orelse return fail(out);
var resolved = node orelse return refused;
// O_TRUNC: replace an existing file's contents rather than overwriting in place
// (frees the old chain, so a shorter rewrite leaves no stale tail).
if (flags & vfs_protocol.truncate != 0 and !resolved.is_directory) {
filesystem.truncate(&resolved);
}
const index = allocOpen() orelse return fail(out);
open_nodes[index] = .{ .used = true, .node = resolved, .owner = sender };
return writeReply(out, .{ .status = 0, .node = index }, &.{});
const index = allocOpen() orelse return refused;
open_nodes[index] = .{ .used = true, .node = resolved, .owner = invocation.sender };
answer.set(.{ .node = index });
return 0;
}
fn onRead(_: void, invocation: Invocation(vfs_protocol.Read), answer: Answer(void)) isize {
const o = openFor(invocation.target, invocation.sender) orelse return refused;
const into = answer.tail();
const want = @min(@as(usize, invocation.request.len), into.len);
return @intCast(filesystem.readFile(o.node, @intCast(invocation.request.offset), into[0..want]));
}
fn onWrite(_: void, invocation: Invocation(vfs_protocol.Write), answer: Answer(vfs_protocol.Written)) isize {
const o = openFor(invocation.target, invocation.sender) orelse return refused;
const data = invocation.tail[0..@min(invocation.tail.len, invocation.request.len)];
const n = filesystem.writeFile(&o.node, @intCast(invocation.request.offset), data);
answer.set(.{ .count = @intCast(n) });
return 0;
}
fn onStatus(_: void, invocation: Invocation(void), answer: Answer(vfs_protocol.FileStatus)) isize {
const o = openFor(invocation.target, invocation.sender) orelse return refused;
const kind: vfs_protocol.NodeKind = if (o.node.is_directory) .directory else .regular;
answer.set(.{ .size = o.node.size, .kind = @intFromEnum(kind), .mtime = o.node.mtime });
return 0;
}
/// One entry per call. End of directory — a node that is not a directory, or a
/// cursor past the last child — is an entry with no name, which is how the
/// protocol spells it now that the reply's length always counts the fixed part.
fn onReaddir(_: void, invocation: Invocation(vfs_protocol.Readdir), answer: Answer(vfs_protocol.DirectoryEntry)) isize {
const o = openFor(invocation.target, invocation.sender) orelse return refused;
if (!o.node.is_directory) {
answer.set(.{});
return 0;
}
const listing = filesystem.listEntry(o.node, @intCast(invocation.request.cursor)) orelse {
answer.set(.{});
return 0;
};
const kind: vfs_protocol.NodeKind = if (listing.is_directory) .directory else .regular;
const into = answer.tail();
const name_len = @min(listing.name_len, into.len);
@memcpy(into[0..name_len], listing.name_buffer[0..name_len]);
answer.set(.{ .kind = @intFromEnum(kind), .name_len = @intCast(name_len), .size = listing.size });
return @intCast(name_len);
}
/// Closing is an operation on a node like any other, so it is scoped like any
/// other: a client may release its own handles and nobody else's. An id that is
/// not the caller's — free, out of range, or another client's — is refused
/// identically, so a close cannot be used to ask which ids are live either.
fn onClose(_: void, invocation: Invocation(void), _: Answer(void)) isize {
const o = openFor(invocation.target, invocation.sender) orelse return refused;
o.used = false;
// Durable-on-close: if any block reached the device since the last flush,
// commit its cache to stable media now (best-effort). This is what makes
// init's shutdown log flush survive a real power-off, and is the right
// default for removable media the user may unplug.
if (device_dirty) {
_ = ipc_block.device.flush();
device_dirty = false;
}
return 0;
}
fn onMakeDirectory(_: void, invocation: Invocation(void), _: Answer(void)) isize {
const path = invocation.tail;
if (filesystem.resolve(path) != null) return refused; // already exists — no duplicate entries
const split = splitParent(path);
const parent = filesystem.resolve(split.parent) orelse return refused;
if (filesystem.createDirectory(parent, split.leaf) == null) return refused;
return 0;
}
fn onUnlink(_: void, invocation: Invocation(void), _: Answer(void)) isize {
const split = splitParent(invocation.tail);
const parent = filesystem.resolve(split.parent) orelse return refused;
if (!filesystem.removeFile(parent, split.leaf)) return refused;
return 0;
}
fn onRename(_: void, invocation: Invocation(void), _: Answer(void)) isize {
const both = invocation.tail;
const separator = std.mem.indexOfScalar(u8, both, 0) orelse return refused;
const old_split = splitParent(both[0..separator]);
const new_split = splitParent(both[separator + 1 ..]);
// Same-directory rename only.
if (!std.mem.eql(u8, old_split.parent, new_split.parent)) return refused;
const parent = filesystem.resolve(old_split.parent) orelse return refused;
if (!filesystem.rename(parent, old_split.leaf, new_split.leaf)) return refused;
return 0;
}
/// The verbs this backend implements. The three it leaves out — `mount`,
/// `unmount`, `bind` — answer `-ENOSYS` from the generated dispatch, which is
/// exactly right: path routing is the kernel's now, and only init implements
/// `bind` (docs/os-development/protocol-namespace.md). `describe` is the
/// envelope's own.
const handlers = Serve.Handlers{
.open = onOpen,
.close = onClose,
.read = onRead,
.write = onWrite,
.status = onStatus,
.readdir = onReaddir,
.mkdir = onMakeDirectory,
.unlink = onUnlink,
.rename = onRename,
};
/// The vfs protocol has no operation that takes a capability, so `arrived` is
/// never claimed here — which, under the harness's ownership rule, means the
/// loop closes whatever a caller attached. That is the point of the rule: this
@@ -230,92 +412,16 @@ fn handleOpen(out: []u8, path: []const u8, flags: u32, sender: u32) usize {
/// thirty-two until it could accept no capability at all.
fn onMessage(message: []const u8, out: []u8, sender: u32, arrived: *ipc.Arrival) usize {
_ = arrived;
if (!mounted) return fail(out); // storage not up (yet): fail politely, clients retry
if (message.len < vfs_protocol.request_size) return fail(out);
const request = std.mem.bytesToValue(vfs_protocol.Request, message[0..vfs_protocol.request_size]);
const payload = message[vfs_protocol.request_size..];
// Storage not up (yet): fail politely, whatever was asked — clients retry.
if (!mounted) {
const status = envelope.Status{ .status = refused, .len = 0 };
@memcpy(out[0..envelope.prefix_size], std.mem.asBytes(&status));
return envelope.prefix_size;
}
// Stamp create/write with the current wall-clock time (mtime). Cheap, and it
// keeps the engine pure (it takes the time as data, not a syscall).
filesystem.current_time_epoch = time.wallClock();
switch (request.operation) {
.open => return handleOpen(out, payload[0..@min(payload.len, request.len)], request.flags, sender),
.read => {
const o = openAt(request.node) orelse return fail(out);
var buffer: [vfs_protocol.maximum_payload]u8 = undefined;
const want = @min(@as(usize, request.len), buffer.len);
const n = filesystem.readFile(o.node, @intCast(request.offset), buffer[0..want]);
return writeReply(out, .{ .status = 0, .len = @intCast(n) }, buffer[0..n]);
},
.write => {
const o = openAt(request.node) orelse return fail(out);
const data = payload[0..@min(payload.len, request.len)];
const n = filesystem.writeFile(&o.node, @intCast(request.offset), data);
return writeReply(out, .{ .status = 0, .len = @intCast(n) }, &.{});
},
.status => {
const o = openAt(request.node) orelse return fail(out);
const kind: vfs_protocol.NodeKind = if (o.node.is_directory) .directory else .regular;
const status = vfs_protocol.FileStatus{ .size = o.node.size, .kind = @intFromEnum(kind), .mtime = o.node.mtime };
return writeReply(out, .{ .status = 0, .len = @sizeOf(vfs_protocol.FileStatus) }, std.mem.asBytes(&status));
},
.readdir => {
const o = openAt(request.node) orelse return fail(out);
if (!o.node.is_directory) return writeReply(out, .{ .status = 0, .len = 0 }, &.{});
const listing = filesystem.listEntry(o.node, @intCast(request.offset)) orelse return writeReply(out, .{ .status = 0, .len = 0 }, &.{});
const kind: vfs_protocol.NodeKind = if (listing.is_directory) .directory else .regular;
const header = vfs_protocol.DirectoryEntry{ .kind = @intFromEnum(kind), .name_len = @intCast(listing.name_len), .size = listing.size };
var buffer: [vfs_protocol.maximum_payload]u8 = undefined;
@memcpy(buffer[0..vfs_protocol.directory_entry_size], std.mem.asBytes(&header));
const nlen = @min(listing.name_len, buffer.len - vfs_protocol.directory_entry_size);
@memcpy(buffer[vfs_protocol.directory_entry_size..][0..nlen], listing.name_buffer[0..nlen]);
const total = vfs_protocol.directory_entry_size + nlen;
return writeReply(out, .{ .status = 0, .len = @intCast(total) }, buffer[0..total]);
},
.close => {
if (openAt(request.node)) |o| o.used = false;
// Durable-on-close: if any block reached the device since the last
// flush, commit its cache to stable media now (best-effort). This is
// what makes init's shutdown log flush survive a real power-off, and is
// the right default for removable media the user may unplug.
if (device_dirty) {
_ = ipc_block.device.flush();
device_dirty = false;
}
return writeReply(out, .{ .status = 0 }, &.{});
},
.mkdir => {
const path = payload[0..@min(payload.len, request.len)];
if (filesystem.resolve(path) != null) return fail(out); // already exists — no duplicate entries
const split = splitParent(path);
const parent = filesystem.resolve(split.parent) orelse return fail(out);
if (filesystem.createDirectory(parent, split.leaf) == null) return fail(out);
return writeReply(out, .{ .status = 0 }, &.{});
},
.unlink => {
const split = splitParent(payload[0..@min(payload.len, request.len)]);
const parent = filesystem.resolve(split.parent) orelse return fail(out);
if (!filesystem.removeFile(parent, split.leaf)) return fail(out);
return writeReply(out, .{ .status = 0 }, &.{});
},
.rename => {
const both = payload[0..@min(payload.len, request.len)];
const sep = std.mem.indexOfScalar(u8, both, 0) orelse return fail(out);
const old_split = splitParent(both[0..sep]);
const new_split = splitParent(both[sep + 1 ..]);
// Same-directory rename only.
if (!std.mem.eql(u8, old_split.parent, new_split.parent)) return fail(out);
const parent = filesystem.resolve(old_split.parent) orelse return fail(out);
if (!filesystem.rename(parent, old_split.leaf, new_split.leaf)) return fail(out);
return writeReply(out, .{ .status = 0 }, &.{});
},
// A backend is never itself a mount target.
// Router verbs, and the registry's claim verb: a file backend answers
// none of them (docs/os-development/protocol-namespace.md — only init
// implements `bind`).
.mount, .unmount, .bind => return fail(out),
}
return Serve.dispatch({}, handlers, message, sender, null, out);
}
pub fn main() void {
+65 -38
View File
@@ -548,34 +548,43 @@ var heartbeat_running = false;
/// `pending_capability`. `arrived` is the capability the *request* carried, owned
/// by the turn — nothing here has to close it, only `bind` has to claim it.
fn serveRegistry(request_bytes: []const u8, reply: []u8, sender: u32, arrived: *Arrival) usize {
if (request_bytes.len < vfs_protocol.request_size)
return answer(reply, -envelope.EPROTO, 0, 0);
// The header is read field by field rather than reinterpreted whole: the
// operation is an enum on the wire and the bytes come from anyone at all, so
// a value outside it must be a refusal, never a decoded enum.
if (request_bytes.len < envelope.prefix_size)
return answer(reply, -envelope.EPROTO, 0);
// The header is read field by field rather than reinterpreted whole, and the
// verb is compared as a number rather than decoded into the generated
// `Operation`: the bytes come from anyone at all, so a value outside the enum
// must be a refusal, never an `@enumFromInt`. This is deliberately NOT
// `Protocol.Provider.dispatch` for the same reason — PID 1 reads a stranger's
// packet, and it reads it by hand.
const operation = std.mem.readInt(u32, request_bytes[0..4], .little);
const cursor = std.mem.readInt(u64, request_bytes[16..24], .little);
const declared = std.mem.readInt(u32, request_bytes[24..28], .little);
const payload_len = @min(@as(usize, declared), request_bytes.len - vfs_protocol.request_size);
const payload = request_bytes[vfs_protocol.request_size..][0..payload_len];
const body = request_bytes[envelope.prefix_size..];
if (operation == @intFromEnum(vfs_protocol.Operation.bind))
return answer(reply, onBind(sender, payload, arrived), 0, 0);
return answer(reply, onBind(sender, body, arrived), 0);
// Only `bind` claims a capability; one attached to anything else is closed by
// the turn's `defer` in the loop, along with the ones sent to a request that
// was too short to name a verb at all.
if (operation == @intFromEnum(vfs_protocol.Operation.open)) return onOpen(reply, sender, payload);
if (operation == @intFromEnum(vfs_protocol.Operation.readdir)) return onReaddir(reply, cursor);
if (operation == @intFromEnum(vfs_protocol.Operation.open)) {
// `open`'s fixed part is the flags word, which means nothing to a
// namespace; the name follows it as the packet's tail.
if (body.len < @sizeOf(vfs_protocol.Open)) return answer(reply, -envelope.EPROTO, 0);
return onOpen(reply, sender, body[@sizeOf(vfs_protocol.Open)..]);
}
if (operation == @intFromEnum(vfs_protocol.Operation.readdir)) {
if (body.len < @sizeOf(vfs_protocol.Readdir)) return answer(reply, -envelope.EPROTO, 0);
return onReaddir(reply, std.mem.readInt(u64, body[0..8], .little));
}
// Everything else a filesystem answers is meaningless here: `/protocol` holds
// contracts, not bytes.
return answer(reply, -envelope.ENOSYS, 0, 0);
return answer(reply, -envelope.ENOSYS, 0);
}
/// Lay down a vfs reply header (and say how many payload bytes follow it).
fn answer(reply: []u8, status: i32, node: u64, payload_len: usize) usize {
const header = vfs_protocol.Reply{ .status = status, .node = node, .len = @intCast(payload_len) };
@memcpy(reply[0..vfs_protocol.reply_size], std.mem.asBytes(&header));
return vfs_protocol.reply_size + payload_len;
/// Lay down the envelope's reply prefix (and say how many payload bytes the
/// caller has already written after it).
fn answer(reply: []u8, status: i32, payload_len: usize) usize {
const header = envelope.Status{ .status = status, .len = @intCast(payload_len) };
@memcpy(reply[0..envelope.prefix_size], std.mem.asBytes(&header));
return envelope.prefix_size + payload_len;
}
/// `bind(name, capability = the provider's endpoint)`. The capability is the
@@ -667,15 +676,19 @@ fn onBind(sender: u32, raw_name: []const u8, arrived: *Arrival) i32 {
/// other, a line in a world-readable log ring, or a serial write costing
/// milliseconds.)
fn onOpen(reply: []u8, sender: u32, raw_name: []const u8) usize {
const name = contractName(raw_name) orelse return answer(reply, -envelope.ENOENT, 0, 0);
const name = contractName(raw_name) orelse return answer(reply, -envelope.ENOENT, 0);
refreshProcessTable();
const identity = identify(sender);
const permitted = if (identity) |who| mayOpen(who, name) else false;
const binding = findBinding(name);
if (!permitted) return answer(reply, -envelope.ENOENT, 0, 0);
const found = binding orelse return answer(reply, -envelope.ENOENT, 0, 0);
if (!permitted) return answer(reply, -envelope.ENOENT, 0);
const found = binding orelse return answer(reply, -envelope.ENOENT, 0);
pending_capability = found.endpoint;
return answer(reply, 0, 0, 0);
// A contract node has no node id — the capability is the whole answer — but
// the protocol says an `open` reply carries one, so it carries a zero.
const opened = vfs_protocol.Opened{ .node = 0 };
@memcpy(reply[envelope.prefix_size..][0..@sizeOf(vfs_protocol.Opened)], std.mem.asBytes(&opened));
return answer(reply, 0, @sizeOf(vfs_protocol.Opened));
}
/// `readdir(cursor)` — the namespace, browsable. One entry per turn, as the vfs
@@ -690,18 +703,25 @@ fn onReaddir(reply: []u8, cursor: u64) usize {
continue;
}
const name = binding.nameSlice();
const entry = vfs_protocol.DirectoryEntry{
return writeEntry(reply, .{
.kind = @intFromEnum(vfs_protocol.NodeKind.protocol),
.name_len = @intCast(name.len),
.size = binding.task,
};
const total = vfs_protocol.directory_entry_size + name.len;
if (vfs_protocol.reply_size + total > reply.len) return answer(reply, -envelope.EPROTO, 0, 0);
@memcpy(reply[vfs_protocol.reply_size..][0..vfs_protocol.directory_entry_size], std.mem.asBytes(&entry));
@memcpy(reply[vfs_protocol.reply_size + vfs_protocol.directory_entry_size ..][0..name.len], name);
return answer(reply, 0, 0, total);
}, name);
}
return answer(reply, 0, 0, 0); // end of directory
// End of directory, which the envelope spells as an entry with no name: the
// reply's own length cannot say it any more, because the fixed reply part
// always travels.
return writeEntry(reply, .{}, &.{});
}
/// One `readdir` reply: the entry, then its name inline.
fn writeEntry(reply: []u8, entry: vfs_protocol.DirectoryEntry, name: []const u8) usize {
const total = vfs_protocol.directory_entry_size + name.len;
if (envelope.prefix_size + total > reply.len) return answer(reply, -envelope.EPROTO, 0);
@memcpy(reply[envelope.prefix_size..][0..vfs_protocol.directory_entry_size], std.mem.asBytes(&entry));
@memcpy(reply[envelope.prefix_size + vfs_protocol.directory_entry_size ..][0..name.len], name);
return answer(reply, 0, total);
}
pub fn main(startup: process.Init) void {
@@ -882,9 +902,12 @@ fn onPowerEvent(sender: u32, payload: []const u8) void {
std.log.info("ignored a power event from pid {d}: /protocol/power is pid {d}", .{ sender, authorized });
return;
}
if (payload.len < 2) return;
if (payload[0] != @intFromEnum(power_protocol.Operation.event)) return;
if (payload[1] == @intFromEnum(power_protocol.Event.power_button)) shutDown();
// Read as an envelope packet, never by byte offset: the kind IS the packet's
// verb, so a power event is decoded exactly the way every other event in the
// system is. A packet whose operation is not one of this protocol's events —
// anything else that lands in this mailbox — decodes to null and is dropped.
const kind = power_protocol.Protocol.eventOf(payload) orelse return;
if (kind == .power_button) shutDown();
}
/// A supervised boot service died. Find which one and restart it — unless it exited
@@ -935,9 +958,11 @@ fn restartChild(id: u32) void {
/// init calls owes the same discipline.
fn subscribePower() void {
const handle = power_endpoint orelse return;
const request = power_protocol.Subscribe{};
// The reserved `subscribe` verb: nothing but the header, with our own
// endpoint riding as the call's capability.
const header = envelope.Header{ .operation = envelope.operation_subscribe };
var reply: [power_protocol.message_maximum]u8 = undefined;
_ = ipc.callCap(handle, std.mem.asBytes(&request), &reply, supervision_endpoint) catch {};
_ = ipc.callCap(handle, std.mem.asBytes(&header), &reply, supervision_endpoint) catch {};
}
/// The stop sequence: persist the log while storage is still up, then terminate
@@ -956,9 +981,11 @@ fn shutDown() void {
if (child_ids[i] != 0) process.stop(child_ids[i], 2000, supervision_endpoint);
}
if (power_endpoint) |h| {
const request = power_protocol.Shutdown{};
var reply: [power_protocol.message_maximum]u8 = undefined;
_ = ipc.call(h, std.mem.asBytes(&request), &reply) catch {};
var packet: [power_protocol.message_maximum]u8 = undefined;
if (power_protocol.Protocol.encodeRequest(.shutdown, 0, {}, &.{}, &packet)) |framed| {
var reply: [power_protocol.message_maximum]u8 = undefined;
_ = ipc.call(h, framed, &reply) catch {};
}
}
// If S5 did not take, init has nothing left to do but idle.
while (true) time.sleepMillis(1000);
+1 -1
View File
@@ -9,7 +9,7 @@ pub fn build(b: *std.Build) void {
const exe = build_support.userBinary(b, .{
.name = "input",
.root_source_file = b.path("input.zig"),
.imports = &.{ "channel", "input-client", "input-protocol", "ipc", "logging", "process", "service" },
.imports = &.{ "envelope", "input-protocol", "ipc", "logging", "service" },
});
b.installArtifact(exe);
}
+49 -125
View File
@@ -17,146 +17,70 @@
//!
//! A subscriber registers by handing the service its own endpoint as a capability (M13
//! capability passing — this service is its first real consumer). The service keeps that
//! handle and `ipc.send`s each event to it.
//! handle and `ipc.send`s each event to it. That is the envelope's reserved `subscribe`
//! verb, which this protocol adopts rather than defining its own.
//!
//! P4a moved this service onto the shared harness (library/kernel/service.zig) — it was the
//! last hand-rolled receive loop in the tree, and the one service that answered neither the
//! universal ping nor a `terminate` signal. P4c finished the job: the subscriber table, the
//! fan-out, and the dead-subscriber sweep are the harness's now
//! (`service.Subscribers`), so what is left here is what is actually about input — which
//! device class an event belongs to, and which classes a subscriber asked for. The sweep
//! that replaced the old prune is the one idiom the system uses everywhere: published
//! process-exit notifications, not a poll of the process list on every subscribe.
const std = @import("std");
const channel = @import("channel");
const ipc = @import("ipc");
const process = @import("process");
const service = @import("service");
const input = @import("input-client");
const logging = @import("logging");
const input_protocol = @import("input-protocol");
const envelope = @import("envelope");
/// One registered subscriber: the endpoint we push events to (a capability it handed us at
/// subscribe time) and the task id that owns it (the subscribe call's badge), so a slot
/// left behind by a subscriber that exited can be reclaimed.
const Subscriber = struct {
used: bool = false,
endpoint: ipc.Handle = 0,
task_id: u32 = 0,
/// Which device classes this subscriber wants (an OR of input_protocol.device_*). An event
/// is delivered only if its device's bit is set here.
device_mask: u32 = 0,
};
/// The subscriber side of the input contract: the table, the reserved `subscribe`
/// verb, the exit sweep, and the fan-out. One fan-out point per process, so the
/// handler context is empty.
const Subscriptions = service.Subscribers(input_protocol.Protocol, void);
var subscribers = [_]Subscriber{.{}} ** 8;
const Invocation = envelope.Invocation;
const Answer = envelope.Answer;
/// Drop any subscriber whose owning process is no longer alive, so its slot (and the
/// endpoint reference it holds) can be reused. Cheap and only run on subscribe — the async
/// `send` to a dead subscriber's orphaned endpoint is harmless (it just fills a queue no
/// one drains), so this is housekeeping, not correctness.
fn pruneDeadSubscribers() void {
var table: [32]process.ProcessDescriptor = undefined;
const total = process.processes(&table);
const count = @min(total, table.len);
for (&subscribers) |*sub| {
if (!sub.used) continue;
var alive = false;
for (table[0..count]) |descriptor| {
if (descriptor.id == sub.task_id) {
alive = true;
break;
}
}
// The slot owns the endpoint capability it was handed, so reclaiming the
// slot closes it — otherwise a process that subscribes and dies costs a
// handle-table slot that never comes back.
if (!alive) {
_ = ipc.close(sub.endpoint);
sub.* = .{};
}
}
}
/// Register `endpoint` (owned by task `task_id`) to receive the device classes in
/// `device_mask`. Returns false if the subscriber table is full.
fn addSubscriber(endpoint: ipc.Handle, task_id: u32, device_mask: u32) bool {
for (&subscribers) |*sub| {
if (!sub.used) {
sub.* = .{ .used = true, .endpoint = endpoint, .task_id = task_id, .device_mask = device_mask };
return true;
}
}
return false;
}
/// Push `event` to every subscriber whose interest mask includes its device class.
/// `ipc.send` never blocks, so a slow or dead subscriber cannot stall delivery to others.
/// Push `event` to every subscriber whose interest mask includes its device class. The
/// class is the packet's operation, so this picks *which event* to publish and the harness
/// frames it once for the whole fan-out — the mapping from device to class is the only part
/// of a broadcast that is this service's own.
fn broadcast(event: input_protocol.InputEvent) void {
const bytes = std.mem.asBytes(&event);
const bit = input_protocol.deviceBit(event.device);
for (&subscribers) |*sub| {
if (sub.used and sub.device_mask & bit != 0) _ = ipc.send(sub.endpoint, bytes);
const class = input_protocol.deviceBit(event.device);
switch (input_protocol.eventOfDevice(event.device) orelse return) { // no class wants it
.keyboard => Subscriptions.publishClass(.keyboard, 0, event.asKeyboard() orelse return, class),
.mouse => Subscriptions.publishClass(.mouse, 0, event.asMouse() orelse return, class),
.joystick => Subscriptions.publishClass(.joystick, 0, event.asJoystick() orelse return, class),
}
}
/// Handle one request. `got` carries the sender badge (a task id); `arrived` carries the
/// capability the request came with, under the same ownership rule the service harness
/// states (`ipc.Arrival`): **it belongs to the turn, and only a handler that means to keep
/// it says `take`.** Everything else here — a short message, a `publish`, a subscribe that
/// finds the table full — simply returns, and the loop closes what arrived. Writes a
/// `Reply` into `out` and returns its length.
fn handle(message: []const u8, got: ipc.Received, out: []u8, arrived: *ipc.Arrival) usize {
const reply = struct {
fn write(buffer: []u8, status: i32) usize {
const header = input_protocol.Reply{ .status = status };
@memcpy(buffer[0..input_protocol.reply_size], std.mem.asBytes(&header));
return input_protocol.reply_size;
}
};
fn onPublish(_: void, invocation: Invocation(input_protocol.InputEvent), _: Answer(void)) isize {
broadcast(invocation.request);
return 0;
}
if (message.len < input_protocol.request_size) return reply.write(out, -1);
const request = std.mem.bytesToValue(input_protocol.Request, message[0..input_protocol.request_size]);
/// `subscribe` and `unsubscribe` are absent on purpose: the harness answers both.
const handlers = Subscriptions.Handlers{ .publish = onPublish };
switch (@as(input_protocol.Operation, @enumFromInt(request.operation))) {
.subscribe => {
const endpoint = arrived.peek() orelse return reply.write(out, -1); // no endpoint passed
// A zero mask means "everything" (a subscriber that named no class still wants input).
const mask = if (request.device_mask == 0) input_protocol.device_all else request.device_mask;
pruneDeadSubscribers();
if (!addSubscriber(endpoint, @intCast(got.badge), mask)) return reply.write(out, -1); // table full
_ = arrived.take(); // claimed: the subscriber table holds it until that task dies
return reply.write(out, 0);
},
.publish => {
broadcast(request.event);
return reply.write(out, 0);
},
}
fn onMessage(message: []const u8, out: []u8, sender: u32, arrived: *ipc.Arrival) usize {
return Subscriptions.dispatch({}, handlers, message, sender, arrived, out);
}
fn initialise(_: ipc.Handle) bool {
// The harness has already bound `/protocol/input` by the time this runs, so
// "ready" still means what it always meant: the name is claimed and the loop
// is about to serve it.
_ = logging.write("/system/services/input: ready\n");
return true;
}
pub fn main() void {
const endpoint = ipc.createIpcEndpoint() orelse {
_ = logging.write("/system/services/input: no endpoint\n");
return;
};
if (!channel.bindPatiently("input", endpoint)) {
_ = logging.write("/system/services/input: could not bind /protocol/input\n");
return;
}
_ = logging.write("/system/services/input: ready\n");
var reply_buffer: [input_protocol.reply_size]u8 = undefined;
var reply_len: usize = 0;
var receive: [input_protocol.request_size]u8 = undefined;
while (true) {
const got = ipc.replyWait(endpoint, reply_buffer[0..reply_len], &receive, null);
// Whatever capability came with this turn is the turn's, and the turn closes it
// unless `handle` claims it (`ipc.Arrival`). The kernel installs a sent capability
// whatever the message's length or kind, so this covers the notification
// `continue` and every refusal inside `handle` — otherwise about thirty-two
// capability-carrying calls, which need no authorization at all, exhaust this
// service's handle table and no further subscribe can ever land.
var arrived: ipc.Arrival = .{ .handle = got.cap };
defer arrived.release();
// Only synchronous client requests (subscribe/publish) arrive here; nothing sends
// this service asynchronous messages, so a notification wake would be spurious.
if (got.isNotification()) {
reply_len = 0;
continue;
}
reply_len = handle(receive[0..got.len], got, &reply_buffer, &arrived);
}
service.run(input_protocol.message_maximum, .{
.service = "input",
.init = initialise,
.on_message = onMessage,
.subscribers = Subscriptions.hooks,
});
}
+347 -14
View File
@@ -65,6 +65,11 @@ ARCHES = {
# Built as a function so we can splice in per-run paths.
"qemu_args": lambda a, boot_volume, vars_fd, serial: [
"-machine", "q35", "-m", "128M",
# The default TCG model (qemu64) predates the supervisor-hardening bits:
# no SMEP, no SMAP, so the kernel's probes would find nothing and the
# enabled paths would never run in CI. `max` is "everything this
# accelerator can emulate", which under TCG includes both.
"-cpu", "max",
"-drive", f"if=pflash,format=raw,readonly=on,file={a['ovmf_code']}",
"-drive", f"if=pflash,format=raw,file={vars_fd}",
# Boot off a FAT USB device: the boot volume is a mass-storage device on
@@ -338,6 +343,46 @@ CASES = [
"expect": r"page fault \(vector 14\)",
"fail": r"NX not enforced"},
{"name": "fault-null", "expect": r"page fault \(vector 14\)"},
# SMEP: ring 0 calls into a page that is present, executable and *user*-accessible
# — the ret2usr shape. CR4.SMEP must refuse the instruction fetch: #PF with error
# code 0x11 (present | instruction-fetch; the U/S bit reports the *access* ring, so
# it is 0 for a ring-0 fetch), taken in ring 0, reported at the page it tried to
# fetch from (a fetch #PF is raised at the un-fetchable instruction, so the IP is
# the user address, not the kernel-half call site). The boot line is asserted too:
# on a CPU without SMEP nothing would fault and the case would prove nothing.
{"name": "fault-smep",
"expect": r"(?s)(?=.*smep\s+: enabled)(?=.*page fault \(vector 14\))"
r"(?=.*ring 0 \(kernel\))(?=.*error code : 0x11)"
r"(?=.*fault addr : 0x0000700000000000)",
"fail": r"SMEP not enforced|SMEP not enabled|no frame for the probe page"},
# SMAP: ring 0 reads a page that is present and *user*-accessible, the way a syscall
# that dereferenced its caller's pointer would. CR4.SMAP (plus the `clac` patched
# into the interrupt entry, which keeps ring 3 from suspending it by taking an
# interrupt with AC set) must refuse the load: #PF with error code 0x1 — present,
# and nothing else. A SMAP violation has no bit of its own; bit 1 is clear because
# it is a read and bit 2 (U/S) reports the ring of the *access*, which was 0. Taken
# in ring 0, at the user address it read. The boot line is asserted too: without
# SMAP nothing would fault and the case would prove nothing.
{"name": "fault-smap",
"expect": r"(?s)(?=.*smap\s+: enabled)(?=.*page fault \(vector 14\))"
r"(?=.*ring 0 \(kernel\))(?=.*error code : 0x1(?![0-9a-f]))"
r"(?=.*fault addr : 0x0000700000000000)",
"fail": r"SMAP not enforced|SMAP not enabled|no frame for the probe page"},
# SYSRET canonical-RIP guard: a ring-3 probe whose `syscall` sits on the last two
# bytes of executable address space, so the return RIP the kernel must hand back
# is 0x0000800000000000 — non-canonical, and a ring-0 #GP if it reached SYSRETQ.
# The kernel must return through IRETQ instead, which faults the *process* in
# ring 3: the kill line names a general protection fault at exactly that address,
# and the probe's own result line reports the guard counter. Any "ring 0 (kernel)"
# report, panic or reset here is the hazard itself, so they are failures.
# TCG does not model the ring-0 #GP (measured: with the guard removed these two
# lines are unchanged), so the case's teeth are the counter assertion inside
# DANOS-TEST-RESULT, not the kill line.
{"name": "sysret-canonical",
"expect": r"(?s)(?=.*killed by general protection fault \(vector 13\))"
r"(?=.*IP\s+: 0x0000800000000000)"
r"(?=.*DANOS-TEST-RESULT: PASS)",
"fail": r"DANOS-TEST-RESULT: FAIL|CPU EXCEPTION|KERNEL PANIC"},
# Memory grants: the mmap/munmap path hands out user pages into a process's
# arena, translate resolves them, munmap frees them, and no frames leak.
{"name": "usermem",
@@ -561,9 +606,17 @@ CASES = [
"smp": 4,
"expect": r"DANOS-TEST-RESULT: PASS",
"fail": r"DANOS-TEST-RESULT: FAIL"},
# M18.2: bus tree reports — the xHCI driver scans its root-hub ports and
# reports both QEMU devices; the manager mirrors, prunes on the reporter's
# death, and the respawned driver re-reports (docs/device-manager.md).
# M18.2 + establishment P3: bus tree reports, and the restart REBUILDING
# the subtree. The manager prunes on the reporter's death — reaping the
# class drivers bound to the pruned children, which hold channels into the
# dead process and cannot observe the death themselves — and when the
# respawned instance re-reports, the matcher spawns fresh class drivers
# whose hellos fetch the successor's channel. The tail asserts the subtree
# WORKS again: the respawned usb-storage opens its device on the NEW bus
# instance and reads block 0. (The HID "ok" lines never appear in this
# scenario — it boots no input service — so storage is the functional
# proof.) Before the reap existed, the stale entries blocked the respawn
# and the survivors were silent zombies, so this tail could not match.
{"name": "usb-report",
"smp": 4,
"timeout": 150,
@@ -572,19 +625,36 @@ CASES = [
"expect": r"device-manager: child added[\s\S]*"
r"device-manager: child added[\s\S]*"
r"device-manager: test mode: killing the reporter[\s\S]*"
r"device-manager: reaping \S*usb-storage[\s\S]*"
r"device-manager: child removed[\s\S]*"
r"device-manager: restarting \S*usb-xhci-bus[\s\S]*"
r"device-manager: child added",
r"device-manager: child added[\s\S]*"
r"device-manager: delegated device \d+ to /system/drivers/usb-storage[\s\S]*"
r"usb-storage: ready[\s\S]*"
r"usb-storage: block 0 signature 0x55aa",
"fail": r"DANOS-TEST-RESULT: FAIL"},
# USB HID end to end: boot the full tree, enumerate the xHCI, and let the
# manager spawn the USB keyboard driver, which opens its device over the
# transfer protocol, asks for boot protocol, subscribes to its interrupt
# endpoint, and comes up — proof the class-driver <-> controller path works.
#
# It also pins the slot count to the hardware's answer. The backreference is the
# assertion: the driver must track exactly as many device slots as the controller
# reports in HCSPARAMS1.MaxSlots. It tracked a fixed 8 while QEMU's xHCI reports
# 64, so seven eighths of the controller was invisible and a device behind a hub
# past the eighth vanished without a log line. \1 fails the moment they diverge.
{"name": "usb-hid",
"smp": 4,
"timeout": 150,
# usb-kbd/usb-mouse ride the default boot xHCI bus (see qemu_args).
"expect": r"(?=[\s\S]*usb-hid-keyboard: ok)(?=[\s\S]*usb-hid-mouse: ok)",
# The controller must arrive by DELEGATION, not by claiming: the manager holds it
# and transfers it in the hello reply, so the match is authoritative rather than
# advisory (docs/os-development/device-authority.md). The delegation line must
# precede the hello, because the transfer completes before the reply lands.
"expect": r"(?=[\s\S]*device-manager: delegated device (\d+) to /system/drivers/usb-xhci-bus"
r"[\s\S]*usb-xhci-bus: controller device \1 registers at)"
r"(?=[\s\S]*usb-xhci-bus: controller running \((\d+) slots, tracking \2,)"
r"(?=[\s\S]*usb-hid-keyboard: ok)(?=[\s\S]*usb-hid-mouse: ok)",
"fail": r"DANOS-TEST-RESULT: FAIL"},
# Keyboard echo: inject a known phrase via QMP send-key; the usb-hid-keyboard
# driver decodes it and echoes each character to the log (the simple
@@ -622,6 +692,50 @@ CASES = [
r"(?=.*hub slot \d+ port \d+ device:.*0x0627)"
r"(?=.*usb-hid-keyboard: ok \(device 3)",
"fail": r"DANOS-TEST-RESULT: FAIL"},
# Establishment P4 — the Ryzen mouse bug, pinned (docs/establishment-planes-plan.md).
# A real machine carried THREE xHCI controllers; the transfer contract was one
# exclusive registry name, so every class driver reached whichever bus instance
# bound first, and a device behind any other controller was unreachable
# ("could not open device 50"). This case is the minimal reproduction: a second
# controller with its own keyboard, while the boot controller keeps the default
# keyboard — BOTH must come up, on different device ids, which requires each
# driver to reach ITS OWN controller. Under name-based establishment exactly one
# can; under lineage routing (the manager answers each hello with the reporter's
# channel) both do.
{"name": "usb-two-controllers",
"build_case": "usb-hid",
"smp": 4,
"timeout": 150,
"qemu_extra": ["-device", "qemu-xhci,id=xhci2",
"-device", "usb-kbd,bus=xhci2.0,port=1"],
# Two bus delegations, then two keyboards alive with distinct ids: the
# second `ok` must name a different device than the first, so one keyboard
# answering twice can never satisfy it.
"expect": r"(?s)(?=(?:[\s\S]*delegated device \d+ to /system/drivers/usb-xhci-bus){2})"
r"(?=[\s\S]*usb-hid-keyboard: ok \(device (\d+)\b[\s\S]*usb-hid-keyboard: ok \(device (?!\1\b)\d+)",
"fail": r"DANOS-TEST-RESULT: FAIL"},
# The driver must never truncate a configuration block. Its size is the DEVICE's
# choice (wTotalLength, a u16); the driver used to read the first 512 bytes into a
# fixed buffer and parse those, so interfaces past the cut did not exist while
# SET_CONFIGURATION still configured the device for all of them.
#
# The backreference is the assertion: declared length and bytes read must match.
#
# Honest limit: QEMU cannot produce a block over 512 bytes. Its boot keyboard,
# mouse and stick are 34-44, and the largest device on offer is usb-audio in
# multi-channel mode at 211 — which is why the suite never saw the original bug,
# and why it cannot now reproduce that exact trigger. What this case does catch is
# the class: any clamp below the attached device's block size fails it, verified
# by pinning the buffer to 128 and watching it go red. A real headset (500-900
# bytes), UVC webcam (1-3 KB) or multifunction printer trips the 512 itself.
{"name": "usb-large-descriptor",
"build_case": "usb-hid",
"smp": 4,
"timeout": 150,
"qemu_extra": ["-device", "qemu-xhci,id=xhci2",
"-device", "usb-audio,bus=xhci2.0,port=1,multi=on"],
"expect": r"(?s)(?=.*usb-xhci-bus: config block (\d\d\d+) bytes, read \1)",
"fail": r"DANOS-TEST-RESULT: FAIL"},
# USB mass storage end to end: the boot usb-storage device (the FAT32 image,
# which has a real 0x55AA boot sector) is enough — the manager spawns
# usb-storage, which opens the device, runs the Bulk-Only / SCSI bring-up,
@@ -658,6 +772,18 @@ CASES = [
"timeout": 150,
"expect": r"fat-test: rename ok",
"fail": r"fat-test: mutations FAILED|DANOS-TEST-RESULT: FAIL"},
# P4c: badge-scoped per-client ids. Two processes of one fixture, on the same
# boot: the owner holds a FAT node id and a compositor layer id, the intruder
# names both and must be refused — while its own node and layer, and the
# owner's after the attempt, keep working. Every refusal is paired with a
# control, so a provider that refused everything (or honoured everything)
# fails this case rather than passing it. Reuses the fat-mount build.
{"name": "badge-scope",
"build_case": "fat-mount",
"smp": 4,
"timeout": 150,
"expect": r"(?s)(?=.*badge-scope-test: ok)(?=.*badge-scope-test: owner intact)",
"fail": r"badge-scope-test: FAILED|DANOS-TEST-RESULT: FAIL"},
# Phase 2d: filesystem timestamps — a freshly-created file's mtime is a real
# current wall-clock time (stamped from the RTC), read back through stat.
{"name": "fat-mtime",
@@ -688,8 +814,16 @@ CASES = [
{"name": "acpi-ps2",
"smp": 4,
"timeout": 150,
# The 8042 is ONE controller described by two ACPI nodes, so the single ps2-bus
# instance must receive BOTH. The keyboard node rides the spawn — it carries the
# 0x60/0x64 ports and is needed immediately — and the mouse node is transferred to
# the already-running instance, which is safe because it is not touched until after
# the controller handshakes and identify. Two processes cannot split this: they
# would fight over the same registers.
"expect": r"discovery: device \d+\s+bus=acpi hid=PNP0303[\s\S]*"
r"device-manager: spawned \S*ps2-bus[\s\S]*"
r"device-manager: delegated device (\d+) to \S*ps2-bus[\s\S]*"
r"device-manager: spawned \S*ps2-bus for device \1[\s\S]*"
r"device-manager: delegated device \d+ to \S*ps2-bus \(already running\)[\s\S]*"
r"ps2-bus: keyboard driver attached",
"fail": r"DANOS-TEST-RESULT: FAIL"},
# M21.1: the SCI + power button. Boot the manager (which spawns the acpi
@@ -762,10 +896,15 @@ CASES = [
{"name": "pci-scan",
"smp": 4,
"timeout": 60,
"expect": r"pci-bus: (\d+) functions found[\s\S]*"
# The bridge must arrive by DELEGATION, not by claiming — and again after the
# restart, which is what proves the manager re-takes the device when its driver
# dies and hands it to the replacement. \1 pins it to the same device both times.
"expect": r"device-manager: delegated device (\d+) to \S*pci-bus[\s\S]*"
r"pci-bus: (\d+) functions found[\s\S]*"
r"device-manager: test mode: killing the reporter[\s\S]*"
r"device-manager: restarting \S*pci-bus[\s\S]*"
r"pci-bus: \1 functions found[\s\S]*"
r"device-manager: delegated device \1 to \S*pci-bus[\s\S]*"
r"pci-bus: \2 functions found[\s\S]*"
r"DANOS-TEST-RESULT: PASS",
"fail": r"DANOS-TEST-RESULT: FAIL"},
# M18.3: the application surface — device-list enumerates the tree over IPC,
@@ -816,10 +955,16 @@ CASES = [
"expect": r"(?s)(?=.*hub slot \d+ port \d+ device:.*0x0409)"
r"(?=.*usb-hid-keyboard: ok \(device 3)",
"fail": r"DANOS-TEST-RESULT: FAIL"},
# Hub-downstream disconnect (B4c): device_del the keyboard behind the hub;
# the hub's status-change endpoint reports it, the device is torn down
# (ChildRemoved + Disable Slot). QEMU's hub DOES raise downstream changes
# (unlike root-port hot-plug).
# Hub-downstream disconnect AND replug (B4c + establishment): device_del the
# keyboard behind the hub — the hub's status-change endpoint reports it, the
# device is torn down (ChildRemoved + Disable Slot), and the manager REAPS
# the bound class driver (it blocks on reports that will never come, and its
# stale entry would make the dedupe refuse the respawn). Then device_add
# plugs it back: the re-report re-registers the same identity and the
# matcher spawns a fresh driver, which binds — the ordered tail (reaping →
# child removed → delegated → ok) can only be satisfied by the SECOND
# generation, since the boot keyboards' ok lines all precede the unplug.
# QEMU's hub DOES raise downstream changes (unlike root-port hot-plug).
{"name": "usb-hub-unplug",
"build_case": "usb-hid",
"smp": 4,
@@ -827,9 +972,146 @@ CASES = [
"qemu_extra": ["-device", "qemu-xhci,id=xhci2",
"-device", "usb-hub,bus=xhci2.0,port=1",
"-device", "usb-kbd,bus=xhci2.0,port=1.1,id=dkbd"],
"qmp_after": {"delay": 8, "command": "device_del", "arguments": {"id": "dkbd"}},
"qmp_sequence": [
{"delay": 8, "command": "device_del", "arguments": {"id": "dkbd"}},
{"delay": 14, "command": "device_add",
"arguments": {"driver": "usb-kbd", "bus": "xhci2.0", "port": "1.1", "id": "dkbd2"}},
],
"expect": r"(?s)(?=.*usb-hid-keyboard: ok \(device 3)"
r"(?=.*slot \d+ disconnected)",
r"(?=.*slot \d+ disconnected"
r"[\s\S]*device-manager: child removed"
r"[\s\S]*device-manager: reaping \S*usb-hid-keyboard"
r"[\s\S]*device-manager: delegated device \d+ to /system/drivers/usb-hid-keyboard"
r"[\s\S]*usb-hid-keyboard: ok)",
"fail": r"DANOS-TEST-RESULT: FAIL"},
# Hot-plug matrix H1 (docs/hot-plug-matrix-plan.md): ROOT-port unplug and
# replug on the same port. Different teardown path than the hub case
# (tearDownPort, not tearDownHubDevice), and QEMU raises no port-change
# events for root ports — the bus's 250 ms reconcile tick must notice the
# PORTSC change on its own. The ordered tail (removed → reaping → delegated
# → ok) can only be the second generation: every boot device's ok precedes
# the unplug.
{"name": "usb-root-replug",
"build_case": "usb-hid",
"smp": 4,
"timeout": 150,
"qemu_extra": ["-device", "qemu-xhci,id=xhci2",
"-device", "usb-kbd,bus=xhci2.0,port=2,id=rkbd"],
"qmp_sequence": [
{"delay": 8, "command": "device_del", "arguments": {"id": "rkbd"}},
{"delay": 14, "command": "device_add",
"arguments": {"driver": "usb-kbd", "bus": "xhci2.0", "port": "2", "id": "rkbd2"}},
],
"expect": r"(?s)(?=.*usb-hid-keyboard: ok \(device (\d+)\b"
r"[\s\S]*port \d+ disconnected"
r"[\s\S]*device-manager: child removed"
r"[\s\S]*device-manager: reaping \S*usb-hid-keyboard"
r"[\s\S]*device-manager: delegated device \d+ to /system/drivers/usb-hid-keyboard"
r"[\s\S]*usb-hid-keyboard: ok)",
"fail": r"DANOS-TEST-RESULT: FAIL"},
# Hot-plug matrix H2 (docs/hot-plug-matrix-plan.md): yank a POPULATED hub.
# One device_del removes the hub with a keyboard and a mouse behind it — the
# bus's recursive teardown (tearDownHubDevice, children first) must report
# every downstream interface removed, the manager must reap BOTH bound
# drivers, and re-adding the hub and both devices must rebuild the subtree.
# The reaping lines only exist post-yank, so `reaping X ... X: ok` chains
# are unambiguously second-generation.
{"name": "usb-hub-yank",
"build_case": "usb-hid",
"smp": 4,
"timeout": 150,
"qemu_extra": ["-device", "qemu-xhci,id=xhci2",
"-device", "usb-hub,bus=xhci2.0,port=1,id=yhub",
"-device", "usb-kbd,bus=xhci2.0,port=1.1,id=ykbd",
"-device", "usb-mouse,bus=xhci2.0,port=1.2,id=ymouse"],
"qmp_sequence": [
{"delay": 8, "command": "device_del", "arguments": {"id": "yhub"}},
{"delay": 14, "command": "device_add",
"arguments": {"driver": "usb-hub", "bus": "xhci2.0", "port": "1", "id": "yhub2"}},
{"delay": 17, "command": "device_add",
"arguments": {"driver": "usb-kbd", "bus": "xhci2.0", "port": "1.1", "id": "ykbd2"}},
{"delay": 18, "command": "device_add",
"arguments": {"driver": "usb-mouse", "bus": "xhci2.0", "port": "1.2", "id": "ymouse2"}},
],
"expect": r"(?s)(?=.*hub device slot \d+ disconnected)"
r"(?=.*device-manager: reaping \S*usb-hid-keyboard[\s\S]*usb-hid-keyboard: ok)"
r"(?=.*device-manager: reaping \S*usb-hid-mouse[\s\S]*usb-hid-mouse: ok)",
"fail": r"DANOS-TEST-RESULT: FAIL"},
# Hot-plug matrix H3 (docs/hot-plug-matrix-plan.md): yank a NESTED hub tree.
# hub → hub → keyboard, one device_del of the outer hub — the recursion must
# go two levels (inner hub torn down as a child, ITS keyboard first), the
# keyboard's driver reaped, and re-adding all three rebuilds and rebinds.
{"name": "usb-hub-nested-yank",
"build_case": "usb-hid",
"smp": 4,
"timeout": 150,
"qemu_extra": ["-device", "qemu-xhci,id=xhci2",
"-device", "usb-hub,bus=xhci2.0,port=1,id=ohub",
"-device", "usb-hub,bus=xhci2.0,port=1.1,id=ihub",
"-device", "usb-kbd,bus=xhci2.0,port=1.1.1,id=nkbd"],
"qmp_sequence": [
{"delay": 8, "command": "device_del", "arguments": {"id": "ohub"}},
{"delay": 14, "command": "device_add",
"arguments": {"driver": "usb-hub", "bus": "xhci2.0", "port": "1", "id": "ohub2"}},
{"delay": 17, "command": "device_add",
"arguments": {"driver": "usb-hub", "bus": "xhci2.0", "port": "1.1", "id": "ihub2"}},
{"delay": 20, "command": "device_add",
"arguments": {"driver": "usb-kbd", "bus": "xhci2.0", "port": "1.1.1", "id": "nkbd2"}},
],
"expect": r"(?s)(?=.*hub device slot \d+ disconnected)"
r"(?=.*device-manager: reaping \S*usb-hid-keyboard[\s\S]*usb-hid-keyboard: ok)",
"fail": r"DANOS-TEST-RESULT: FAIL"},
# Hot-plug matrix H4 (docs/hot-plug-matrix-plan.md): replug on a DIFFERENT
# port. Registration identity is per-port, so a moved device is simply a new
# device: the old child is removed and its driver reaped; the new port's
# child gets a fresh id and a fresh driver. Nothing may tie a driver to the
# old port. The tail (reaping → hub slot N port 2 device → delegated → ok)
# is unambiguous: port 2 of the hub had nothing before the move.
{"name": "usb-replug-moved",
"build_case": "usb-hid",
"smp": 4,
"timeout": 150,
"qemu_extra": ["-device", "qemu-xhci,id=xhci2",
"-device", "usb-hub,bus=xhci2.0,port=1,id=mhub",
"-device", "usb-kbd,bus=xhci2.0,port=1.1,id=mkbd"],
"qmp_sequence": [
{"delay": 8, "command": "device_del", "arguments": {"id": "mkbd"}},
{"delay": 14, "command": "device_add",
"arguments": {"driver": "usb-kbd", "bus": "xhci2.0", "port": "1.2", "id": "mkbd2"}},
],
"expect": r"(?s)(?=.*device-manager: reaping \S*usb-hid-keyboard"
r"[\s\S]*hub slot \d+ port 2 device:"
r"[\s\S]*device-manager: delegated device \d+ to /system/drivers/usb-hid-keyboard"
r"[\s\S]*usb-hid-keyboard: ok)",
"fail": r"DANOS-TEST-RESULT: FAIL"},
# Hot-plug matrix H5 (docs/hot-plug-matrix-plan.md): three unplug/replug
# cycles of the same keyboard on the same hub port. Each cycle must reap the
# old generation and bind a new one — three reaping lines, and a bind after
# the last — proving no state leaks across generations: xHCI slots, the
# bus's open table, and the manager's driver entries must all be reusable.
{"name": "usb-replug-cycles",
"build_case": "usb-hid",
"smp": 4,
"timeout": 150,
"qemu_extra": ["-device", "qemu-xhci,id=xhci2",
"-device", "usb-hub,bus=xhci2.0,port=1,id=chub",
"-device", "usb-kbd,bus=xhci2.0,port=1.1,id=ckbd0"],
"qmp_sequence": [
{"delay": 8, "command": "device_del", "arguments": {"id": "ckbd0"}},
{"delay": 12, "command": "device_add",
"arguments": {"driver": "usb-kbd", "bus": "xhci2.0", "port": "1.1", "id": "ckbd1"}},
{"delay": 18, "command": "device_del", "arguments": {"id": "ckbd1"}},
{"delay": 22, "command": "device_add",
"arguments": {"driver": "usb-kbd", "bus": "xhci2.0", "port": "1.1", "id": "ckbd2"}},
{"delay": 28, "command": "device_del", "arguments": {"id": "ckbd2"}},
{"delay": 32, "command": "device_add",
"arguments": {"driver": "usb-kbd", "bus": "xhci2.0", "port": "1.1", "id": "ckbd3"}},
],
"expect": r"(?s)(?=.*device-manager: reaping \S*usb-hid-keyboard"
r"[\s\S]*device-manager: reaping \S*usb-hid-keyboard"
r"[\s\S]*device-manager: reaping \S*usb-hid-keyboard"
r"[\s\S]*device-manager: delegated device \d+ to /system/drivers/usb-hid-keyboard"
r"[\s\S]*usb-hid-keyboard: ok)",
"fail": r"DANOS-TEST-RESULT: FAIL"},
# The kernel VFS root (M-F): the mount table serves the initrd at /system —
# path resolution, node status/read (an ELF magic), and directory listing,
@@ -889,6 +1171,29 @@ CASES = [
r"(?=.*protocol-denied: ok)"
r"(?=.*DANOS-TEST-RESULT: PASS)",
"fail": r"DANOS-TEST-RESULT: FAIL|protocol-denied: FAIL"},
# The reserved verbs, asked of live providers (P4a). Every protocol built on
# envelope.Define answers `describe` out of its specification and `-ENOSYS`
# for a verb it does not define, without its provider implementing either —
# so a fixture that walks /protocol's own listing and asks both of whatever
# it finds is the proof that `Define` hands those verbs to everyone alike.
# The scenario boots the registry, the input service and the compositor: two
# protocols of different sizes and verb counts, both reached through the real
# registry under the manifest's own grants. The other six the fixture knows —
# vfs, block, scanout, device-manager, power and usb-transfer — need provider
# chains this case does not boot (the last three all arrive with the device
# manager, i.e. with the whole driver tree, whose timing would make this
# fixture's one namespace snapshot a boot race). It names them as unchecked
# rather than skipping them quietly, and the fat-mount / usb-storage /
# virtio-gpu / device-list / driver-restart / pci-scan / usb-* /
# orderly-shutdown scenarios are their proof.
{"name": "protocol-conformance",
"expect": r"(?s)(?=.*protocol-conformance: input v\d+ describes itself)"
r"(?=.*protocol-conformance: display v\d+ describes itself)"
r"(?=.*-> -ENOSYS)"
r"(?=.*protocol-conformance: 2 provider\(s\) answered the reserved verbs identically)"
r"(?=.*protocol-conformance: ok)"
r"(?=.*DANOS-TEST-RESULT: PASS)",
"fail": r"DANOS-TEST-RESULT: FAIL|protocol-conformance: FAIL"},
# Device manager: a ring-3 service enumerates /system/devices, matches the PCI host
# bridge to pci-bus, and spawns it — end-to-end proof of discover -> match -> spawn
# -> driver-up (the spawned pci-bus logs "<N> functions found").
@@ -898,9 +1203,37 @@ CASES = [
# device_register containment (in-kernel): registering a child whose MMIO window
# escapes its parent's grant is refused (NotContained) — else dev_register would map
# arbitrary physical memory — while an identical re-register stays idempotent.
# Also pins the cap ordering: a parent already at maximum_children_per_parent must
# still re-admit an identical child (a restarted bus consumes no slot re-reporting
# what it rediscovers) while still refusing a genuinely new one.
{"name": "containment",
"expect": r"DANOS-TEST-RESULT: PASS",
"fail": r"DANOS-TEST-RESULT: FAIL"},
# PCI host-bridge apertures come from the holes in the firmware memory map, and a
# registered BAR must fall inside one. The invariant is that an aperture never
# covers memory the firmware described - otherwise device_register containment
# admits a child BAR over live RAM. Driven with a synthetic 100-entry map, since
# OVMF only ever produces 15-25 and real firmware 60-200.
{"name": "apertures",
"expect": r"DANOS-TEST-RESULT: PASS",
"fail": r"DANOS-TEST-RESULT: FAIL"},
# Delegation's mechanism (docs/os-development/device-authority.md). A claim is
# exclusive, so handing a device on is a MOVE: the giver stops holding it the
# instant the receiver starts - which is why this is not the M13 capability path,
# where a handle is shared refcounted. The kernel's whole rule is "you may give
# away what you hold"; it has no notion of which task is the device manager.
{"name": "device-transfer",
"expect": r"DANOS-TEST-RESULT: PASS",
"fail": r"DANOS-TEST-RESULT: FAIL"},
# The attacker the device suite never had. The audit's finding was that a fully
# green suite missed six real defects because it contains no attacker: every device
# case asserts a driver handed its hardware can drive it, and none asks what a
# process handed NOTHING can do. This fixture is that process - it holds no device
# and asserts it can give none away, with a positive control first so the refusals
# are decisions rather than a broken syscall path.
{"name": "device-authority",
"expect": r"DANOS-TEST-RESULT: PASS",
"fail": r"DANOS-TEST-RESULT: FAIL"},
# IRQ teardown: an exiting driver's line is masked and its slot cleared (so no
# ISR notifies a freed endpoint), and a sibling owner sharing that endpoint
# keeps its own binding. A long-running driver never reaches this teardown path.
@@ -0,0 +1,216 @@
//! test/system/services/badge-scope-test — the guessable-id probe. Two providers
//! hand small integers to a client and then take them back from anyone who says
//! the number: the FAT server's node ids (a table of thirty-two) and the
//! compositor's layer ids (a table of sixteen). P4c scoped both to the badge that
//! opened them (docs/os-development/protocol-namespace.md — *handles must be
//! scoped per client, validated against the badge*), and this fixture is the
//! proof.
//!
//! It runs as two processes of the same binary, because the hole is a
//! *cross-client* one and a single process cannot demonstrate it:
//!
//! - the **owner** (no arguments — the scenario spawns this one) opens a file
//! on the volume and creates a layer, keeps both, and spawns
//! - the **intruder** (the two ids as argv), which opens a file and a layer of
//! its own and then names the owner's.
//!
//! Every refusal is paired with the same operation on the intruder's own id, so
//! the case cannot pass against a provider that refuses everything; and the owner
//! re-uses both ids after the intruder has finished — including after its attempt
//! to *close* the file node — so the case cannot pass against a provider that
//! honoured the intruder and merely reported failure. The pass marker is
//! `badge-scope-test: ok` from the intruder plus `badge-scope-test: owner intact`
//! from the owner.
//!
//! What it cannot check: which id the intruder was refused *for*. A refusal is
//! deliberately identical to "no such id" — that is the discipline being tested —
//! so the fixture proves the boundary by construction (an id it was told about by
//! its parent, which is holding it) rather than by reading anything back.
const std = @import("std");
const display = @import("display-client");
const fs = @import("file-system");
const ipc = @import("ipc");
const logging = @import("logging");
const process = @import("process");
const time = @import("time");
/// A scratch file on the volume, so the node the intruder tries to write through
/// is one nothing else reads. (A foreign write that *succeeded* would prove the
/// bug — it must not also damage the boot volume proving it.)
const held_path = "/volumes/usb/BADGE.TXT";
const held_contents = "held";
fn line(comptime format: []const u8, arguments: anytype) void {
var buffer: [192]u8 = undefined;
_ = logging.write(std.fmt.bufPrint(&buffer, format, arguments) catch return);
}
/// The fat server mounts /volumes/usb only after the whole USB storage chain is
/// up, and both instances race it.
fn waitForVolume() bool {
var tries: u32 = 0;
while (tries < 1400) : (tries += 1) {
if (fs.openDirectory("/volumes/usb")) |opened| {
var directory = opened;
directory.close();
return true;
}
time.sleepMillis(50);
}
return false;
}
pub fn main(init: process.Init) void {
if (init.arguments.get(1)) |node_text| {
const layer_text = init.arguments.get(2) orelse {
_ = logging.write("badge-scope-test: FAILED (intruder without a layer id)\n");
return;
};
const node = std.fmt.parseInt(u64, node_text, 10) catch return;
const layer = std.fmt.parseInt(u32, layer_text, 10) catch return;
intrude(node, layer);
return;
}
own();
}
// --- the owner ---------------------------------------------------------------
fn own() void {
if (!waitForVolume()) {
_ = logging.write("badge-scope-test: FAILED (/volumes/usb never became available)\n");
return;
}
var held = fs.open(held_path, .{ .create = true, .truncate = true }) orelse {
_ = logging.write("badge-scope-test: FAILED (owner could not create its file)\n");
return;
};
if ((held.writeAll(held_contents) orelse 0) != held_contents.len) {
_ = logging.write("badge-scope-test: FAILED (owner could not write its file)\n");
return;
}
const layer = display.createLayer(240, 40, 32, 32, 3) orelse {
_ = logging.write("badge-scope-test: FAILED (owner could not create a layer)\n");
return;
};
_ = layer.fill(0, 0, 32, 32, display.color(0x20, 0x80, 0xC0));
line("badge-scope-test: owner holds node {d} and layer {d}\n", .{ held.node, layer.id });
// The intruder is told both ids outright: guessing them is not what is being
// tested (they are small integers — a prober would simply enumerate), and a
// fixture that had to search would be asserting on a race instead of on the
// rule.
var node_text: [24]u8 = undefined;
var layer_text: [12]u8 = undefined;
const arguments = [_][]const u8{
std.fmt.bufPrint(&node_text, "{d}", .{held.node}) catch return,
std.fmt.bufPrint(&layer_text, "{d}", .{layer.id}) catch return,
};
const endpoint = ipc.createIpcEndpoint() orelse {
_ = logging.write("badge-scope-test: FAILED (owner has no exit endpoint)\n");
return;
};
const intruder = process.spawnSupervised("badge-scope-test", &arguments, endpoint) orelse {
_ = logging.write("badge-scope-test: FAILED (could not spawn the intruder)\n");
return;
};
var receive: [8]u8 = undefined;
while (true) {
const got = ipc.replyWait(endpoint, &.{}, &receive, null);
if (got.isChildExit() and got.childProcessId() == intruder) break;
}
// Both ids must still be the owner's, and still work — the half of the proof
// the intruder cannot give, because a provider that had honoured its close or
// its destroy would have answered it exactly as one that refused.
held.seekTo(0);
var buffer: [16]u8 = undefined;
const read = held.read(&buffer) orelse 0;
const node_intact = read == held_contents.len and std.mem.eql(u8, buffer[0..read], held_contents);
const layer_intact = layer.fill(0, 0, 32, 32, display.color(0x20, 0xC0, 0x80));
if (node_intact and layer_intact) {
_ = logging.write("badge-scope-test: owner intact\n");
} else {
line("badge-scope-test: FAILED (owner lost its ids: node={} layer={})\n", .{ node_intact, layer_intact });
}
_ = layer.destroy();
held.close();
}
// --- the intruder -------------------------------------------------------------
fn intrude(foreign_node: u64, foreign_layer: u32) void {
if (!waitForVolume()) {
_ = logging.write("badge-scope-test: FAILED (/volumes/usb never became available)\n");
return;
}
const node_verdict = probeNode(foreign_node);
const layer_verdict = probeLayer(foreign_layer);
if (node_verdict and layer_verdict) {
_ = logging.write("badge-scope-test: ok\n");
} else {
_ = logging.write("badge-scope-test: FAILED\n");
}
}
/// The FAT half: the intruder's own node works, the owner's does not.
fn probeNode(foreign: u64) bool {
var mine = fs.open(held_path, .{}) orelse {
_ = logging.write("badge-scope-test: FAILED (intruder could not open its own file)\n");
return false;
};
defer mine.close();
if (mine.backend == null or mine.node == foreign) {
line("badge-scope-test: FAILED (intruder's node {d} is not distinct from {d})\n", .{ mine.node, foreign });
return false;
}
var buffer: [16]u8 = undefined;
const own_read = (mine.read(&buffer) orelse 0) == held_contents.len;
// The same backend channel, the same verbs, one different integer. Every one
// of these worked before the owner check went in.
var forged = fs.File{ .node = foreign, .backend = mine.backend };
const read_refused = forged.read(&buffer) == null;
const status_refused = forged.attributes() == null;
const write_refused = forged.write("intruded") == null;
forged.close(); // must not release the owner's node — the owner proves that after we exit
mine.seekTo(0);
const own_read_again = (mine.read(&buffer) orelse 0) == held_contents.len;
const ok = own_read and own_read_again and read_refused and status_refused and write_refused;
line("badge-scope-test: node own={} read_refused={} status_refused={} write_refused={} own_again={}\n", .{
own_read, read_refused, status_refused, write_refused, own_read_again,
});
return ok;
}
/// The display half: the intruder's own layer obeys it, the owner's ignores it.
fn probeLayer(foreign: u32) bool {
const mine = display.createLayer(200, 40, 32, 32, 4) orelse {
_ = logging.write("badge-scope-test: FAILED (intruder could not create a layer)\n");
return false;
};
if (mine.id == foreign) {
line("badge-scope-test: FAILED (intruder's layer {d} is not distinct)\n", .{mine.id});
return false;
}
const own_fill = mine.fill(0, 0, 32, 32, display.color(0xC0, 0x40, 0x40));
const own_configure = mine.configure(200, 80, 4, true);
const forged = display.Layer{ .id = foreign };
const fill_refused = !forged.fill(0, 0, 32, 32, display.color(0xFF, 0, 0));
const configure_refused = !forged.configure(0, 0, 9, false);
const destroy_refused = !forged.destroy();
const own_still = mine.fill(0, 0, 32, 32, display.color(0x40, 0xC0, 0x40));
_ = mine.destroy();
const ok = own_fill and own_configure and own_still and fill_refused and configure_refused and destroy_refused;
line("badge-scope-test: layer own={} fill_refused={} configure_refused={} destroy_refused={} own_again={}\n", .{
own_fill, fill_refused, configure_refused, destroy_refused, own_still,
});
return ok;
}
@@ -0,0 +1,15 @@
//! The badge-scope-test fixture as a binary package (docs/build-packages-plan.md):
//! this file names the binary and EXACTLY the modules its source imports —
//! build-support resolves each name from the domains this zon declares.
const std = @import("std");
const build_support = @import("build-support");
pub fn build(b: *std.Build) void {
const exe = build_support.userBinary(b, .{
.name = "badge-scope-test",
.root_source_file = b.path("badge-scope-test.zig"),
.imports = &.{ "display-client", "file-system", "ipc", "logging", "process", "time" },
});
b.installArtifact(exe);
}
@@ -0,0 +1,17 @@
.{
.name = .badge_scope_test,
.version = "0.0.0",
.fingerprint = 0x92ab15512c4e5b49, // Changing this has security and trust implications.
.minimum_zig_version = "0.16.0",
.dependencies = .{
// build-support supplies the shared recipe; kernel is implicit in
// every binary (the root shim + link script live there). The rest
// are exactly the homes of this binary's declared imports.
.@"build-support" = .{ .path = "../../../../build-support" },
.kernel = .{ .path = "../../../../library/kernel" },
// client: the compositor half of the probe talks to /protocol/display
// through the same client library every other display client uses.
.client = .{ .path = "../../../../library/client" },
},
.paths = .{""},
}
+19 -9
View File
@@ -19,13 +19,15 @@ pub fn main(init: process.Init) void {
const argument = init.arguments.get(1) orelse return; // bare: stay silent
const assigned = std.fmt.parseInt(u64, argument, 10) catch return;
// The respawn only reaches this line because the kernel released the
// previous instance's claim at death. A failed claim exits cleanly — the
// manager reads "meant to stop" and the scenario fails loudly by silence.
if (!device.claim(assigned)) {
_ = logging.write("crash-test: claim failed\n");
return;
}
// The device arrived with the spawn — this fixture is delegated its hardware like
// any other driver, so it holds `assigned` before its first instruction and has
// nothing to claim (docs/os-development/device-authority.md).
//
// The property this scenario checks is unchanged, only its mechanism: a respawned
// instance still gets the device its predecessor held. It used to arrive because
// the kernel released the dead instance's claim and this one re-took it, racing
// anyone else who wanted it; now the device reverts to the manager on death and is
// handed to the replacement, which is the same guarantee without the race.
var manager: ?ipc.Handle = null;
var tries: u32 = 0;
@@ -34,9 +36,17 @@ pub fn main(init: process.Init) void {
if (manager == null) time.sleepMillis(20);
}
const h = manager orelse return;
const hello = device_manager_protocol.Hello{ .role = @intFromEnum(device_manager_protocol.Role.device), .device_id = assigned };
// The assigned device is the packet's target, the manager's object addressing.
var packet: [device_manager_protocol.message_maximum]u8 = undefined;
const framed = device_manager_protocol.Protocol.encodeRequest(
.hello,
assigned,
.{ .role = @intFromEnum(device_manager_protocol.Role.device) },
&.{},
&packet,
) orelse return;
var reply: [device_manager_protocol.message_maximum]u8 = undefined;
_ = ipc.call(h, std.mem.asBytes(&hello), &reply) catch return;
_ = ipc.call(h, framed, &reply) catch return;
_ = logging.write("crash-test: faulting now\n");
const poison: *volatile u32 = @ptrFromInt(0xdead0000);
@@ -0,0 +1,15 @@
//! The device-authority-test fixture as a binary package (docs/build-packages-plan.md):
//! this file names the binary and EXACTLY the modules its source imports —
//! build-support resolves each name from the domains this zon declares.
const std = @import("std");
const build_support = @import("build-support");
pub fn build(b: *std.Build) void {
const exe = build_support.userBinary(b, .{
.name = "device-authority-test",
.root_source_file = b.path("device-authority-test.zig"),
.imports = &.{ "driver", "logging", "process", "time" },
});
b.installArtifact(exe);
}
@@ -0,0 +1,15 @@
.{
.name = .device_authority_test,
.version = "0.0.0",
.fingerprint = 0x4acbba0c105a1462, // Changing this has security and trust implications.
.minimum_zig_version = "0.16.0",
.dependencies = .{
// build-support supplies the shared recipe; kernel is implicit in
// every binary (the root shim + link script live there). The rest
// are exactly the homes of this binary's declared imports.
.@"build-support" = .{ .path = "../../../../build-support" },
.kernel = .{ .path = "../../../../library/kernel" },
.device = .{ .path = "../../../../library/device" },
},
.paths = .{""},
}
@@ -0,0 +1,124 @@
//! device-authority-test — the attacker the device suite never had.
//!
//! The audit behind [docs/fixed-bounds-audit.md] found six real defects that a
//! fully green suite had missed, and the reason was structural: *the suite
//! contains no attacker*. Every device case asserts that a driver handed its
//! own hardware can drive it. None asks what a process that was handed
//! **nothing** can do.
//!
//! This binary is that process. It is spawned with no device, holds no device,
//! and asserts what it therefore cannot do
//! ([docs/os-development/device-authority.md]):
//!
//! 1. **A positive control first.** `device_enumerate` works from here, so
//! the refusals below are decisions rather than a syscall path that is
//! simply broken for this process. Without this, "everything failed" would
//! read identically to "the assertions are meaningless".
//! 2. **It cannot give away a device it does not hold** — not one another
//! task holds, and not a free one either. The kernel's whole rule is *you
//! may give away what you hold*, so the state of the device is irrelevant:
//! a process holding nothing can transfer nothing. That is asserted across
//! several ids precisely so it cannot pass by accident of which device
//! happened to be free at boot.
//! 3. **A device that does not exist is refused differently** — `NoSuchDevice`
//! rather than `NotHeld`. A refusal that cannot say which rule refused it
//! is what cost a debugging session on the Ryzen, so the distinction is
//! part of the contract and is tested as such.
//!
//! **Why there is no "cannot take a delegated device" assertion here.** The
//! hole this fixture was written for is closed, but not by a refusal it could
//! observe. A device that was given to someone is *held*, so an attempt to
//! take it is refused as `AlreadyClaimed` — the same answer as before. What
//! changed is what happens when the holder dies: the device returns to
//! whoever lent it instead of becoming free, so the window in which a
//! stranger could take it no longer exists. There is no moment to catch.
const std = @import("std");
const device = @import("driver");
const logging = @import("logging");
const process = @import("process");
const time = @import("time");
fn line(comptime format: []const u8, arguments: anytype) void {
var buffer: [160]u8 = undefined;
_ = logging.write(std.fmt.bufPrint(&buffer, format, arguments) catch return);
}
var failures: usize = 0;
var process_table: [64]process.ProcessDescriptor = undefined;
fn check(name: []const u8, ok: bool) void {
if (!ok) failures += 1;
line("device-authority: {s} {s}\n", .{ if (ok) "ok" else "FAIL", name });
}
fn run() void {
// 1. The positive control: this process can reach the device syscalls at all.
var table: [64]device.DeviceDescriptor = undefined;
const total = device.enumerate(&table);
check("enumerate works from an unprivileged process", total > 0);
const seen = @min(total, table.len);
// 2. Holding nothing, it can give nothing away — whatever the device's state.
// Every id the machine actually has, so this cannot pass by luck.
var refused: usize = 0;
var wrong_reason: usize = 0;
for (table[0..seen]) |descriptor| {
device.transfer(descriptor.id, process.taskId()) catch |e| {
refused += 1;
if (e != error.NotHeld) wrong_reason += 1;
continue;
};
}
check("every transfer by a non-holder is refused", refused == seen);
check("each refusal says NotHeld, not something vaguer", wrong_reason == 0);
// 3. A device that does not exist is a different refusal, and says so.
const absent = if (device.transfer(0xFFFF_FFFF, process.taskId())) |_| false else |e| e == error.NoSuchDevice;
check("a device that does not exist is refused as absent", absent);
// 4. **The spawn is not a second way in.** A device now rides system_spawn, which
// would be a fine back door if the kernel checked ownership any less carefully
// there than it does in transfer: spawn a child, name someone else's device, and
// the child holds hardware nobody gave it. The refusal must happen before the
// child exists, so nothing is left running either.
if (seen != 0) {
const before = process.processes(&process_table);
const spawned = process.spawnSupervisedWithDevice("/test/system/services/device-authority-test", &.{}, null, table[0].id);
check("spawning with a device the caller does not hold is refused", spawned == null);
check("and no child was left behind by the refusal", process.processes(&process_table) == before);
}
// 5. **Nothing with mappable resources is left lying around.** A device nobody
// holds can be claimed by anyone, so the manager takes every seeded device that
// carries resources — the HPET above all, which has an MMIO window and an IRQ
// and no user-space driver. The one exception is the loader's framebuffer,
// which the compositor claims. So from here, a resource-bearing device should
// refuse to be taken, and the reason should be that someone already has it.
// Settle first, then sweep **once**. The manager is still starting when this
// fixture is spawned, so an immediate sweep finds hardware unheld and reports a
// hole that closes a millisecond later. Retrying until the sweep comes back
// empty is worse than useless: the first pass *takes* the device, so the second
// finds it unavailable — because this process now holds it — and concludes all
// is well. One sweep, after a wait long enough for the manager to have claimed.
time.sleepMillis(1500);
var takeable: usize = 0;
for (table[0..seen]) |descriptor| {
if (descriptor.resource_count == 0) continue;
if (descriptor.class == @intFromEnum(device.DeviceClass.display)) continue;
device.claim(descriptor.id) catch continue; // refused, as it should be
takeable += 1;
}
check("no resource-bearing device is left for the taking", takeable == 0);
if (failures == 0) {
line("device-authority: VERDICT ok ({d} devices, none of them mine)\n", .{seen});
} else {
line("device-authority: VERDICT FAILED {d} assertion(s)\n", .{failures});
}
}
pub fn main(startup: process.Init) void {
const role = startup.arguments.get(1) orelse return; // bare (ramdisk sweep): stay silent
if (std.mem.eql(u8, role, "run")) run();
}
+1 -1
View File
@@ -9,7 +9,7 @@ pub fn build(b: *std.Build) void {
const exe = build_support.userBinary(b, .{
.name = "device-list",
.root_source_file = b.path("device-list.zig"),
.imports = &.{ "channel", "device-manager-protocol", "ipc", "logging", "time" },
.imports = &.{ "channel", "device-manager-protocol", "envelope", "ipc", "logging", "time" },
});
b.installArtifact(exe);
}
@@ -6,6 +6,7 @@
const std = @import("std");
const channel = @import("channel");
const envelope = @import("envelope");
const ipc = @import("ipc");
const time = @import("time");
const logging = @import("logging");
@@ -29,36 +30,41 @@ pub fn main() void {
};
// The snapshot — polled briefly, because at boot the bus drivers may still
// be scanning: an empty first answer usually just means "too early".
// be scanning: an empty first answer usually just means "too early". This is
// the envelope's reserved `enumerate` verb, so the request is nothing but a
// header and the answer is one `ChildEntry` per record in the reply's tail —
// how many arrived is the reply's own length, which is why no count header
// says it a second time.
const Entry = device_manager_protocol.ChildEntry;
const enumerate = envelope.Header{ .operation = envelope.operation_enumerate };
var reply: [device_manager_protocol.message_maximum]u8 = undefined;
var count: u32 = 0;
var length: usize = 0;
var count: usize = 0;
tries = 0;
while (tries < 20) : (tries += 1) {
const request = device_manager_protocol.Enumerate{};
length = ipc.call(h, std.mem.asBytes(&request), &reply) catch 0;
if (length >= @sizeOf(device_manager_protocol.EnumerateReply)) {
count = std.mem.bytesToValue(device_manager_protocol.EnumerateReply, reply[0..@sizeOf(device_manager_protocol.EnumerateReply)]).count;
if (count != 0) break;
const length = ipc.call(h, std.mem.asBytes(&enumerate), &reply) catch 0;
if (envelope.statusOf(reply[0..length])) |status| {
if (status.status == 0) {
const carried = @min(@as(usize, status.len), length - envelope.prefix_size);
count = carried / @sizeOf(Entry);
if (count != 0) break;
}
}
time.sleepMillis(100);
}
writeLine("device-list: {d} devices\n", .{count});
var offset: usize = @sizeOf(device_manager_protocol.EnumerateReply);
var index: u32 = 0;
while (index < count and offset + @sizeOf(device_manager_protocol.ChildEntry) <= length) : (index += 1) {
const entry = std.mem.bytesToValue(device_manager_protocol.ChildEntry, reply[offset..][0..@sizeOf(device_manager_protocol.ChildEntry)]);
for (0..count) |index| {
const entry = std.mem.bytesToValue(Entry, reply[envelope.prefix_size + index * @sizeOf(Entry) ..][0..@sizeOf(Entry)]);
writeLine("device-list: device {d} port {d} identity {d}\n", .{ entry.parent, entry.bus_address, entry.identity });
offset += @sizeOf(device_manager_protocol.ChildEntry);
}
// The subscription: our endpoint rides as the call's capability; events
// arrive as buffered messages carrying the same structs the bus sends.
// The subscription — the reserved `subscribe` verb: our endpoint rides as
// the call's capability, and events arrive as buffered packets carrying the
// same structs the bus drivers send, under the events' own numbering.
const endpoint = ipc.createIpcEndpoint() orelse {
_ = logging.write("device-list: no endpoint\n");
return;
};
const subscribe = device_manager_protocol.Subscribe{};
const subscribe = envelope.Header{ .operation = envelope.operation_subscribe };
_ = ipc.callCap(h, std.mem.asBytes(&subscribe), &reply, endpoint) catch {
_ = logging.write("device-list: subscribe failed\n");
return;
@@ -68,19 +74,18 @@ pub fn main() void {
var receive: [device_manager_protocol.message_maximum]u8 = undefined;
while (true) {
const got = ipc.replyWait(endpoint, &.{}, &receive, null);
if (!got.isMessage() or got.len < 1) continue;
switch (receive[0]) {
@intFromEnum(device_manager_protocol.Operation.child_added) => {
if (got.len < device_manager_protocol.child_added_size) continue;
const event = std.mem.bytesToValue(device_manager_protocol.ChildAdded, receive[0..device_manager_protocol.child_added_size]);
writeLine("device-list: added (device {d} port {d})\n", .{ event.parent, event.bus_address });
if (!got.isMessage()) continue;
const packet = receive[0..got.len];
const event = device_manager_protocol.Protocol.eventOf(packet) orelse continue;
switch (event) {
.child_added => {
const added = device_manager_protocol.Protocol.decodeEvent(.child_added, packet) orelse continue;
writeLine("device-list: added (device {d} port {d})\n", .{ added.parent, added.bus_address });
},
@intFromEnum(device_manager_protocol.Operation.child_removed) => {
if (got.len < device_manager_protocol.child_removed_size) continue;
const event = std.mem.bytesToValue(device_manager_protocol.ChildRemoved, receive[0..device_manager_protocol.child_removed_size]);
writeLine("device-list: removed (device {d} port {d})\n", .{ event.parent, event.bus_address });
.child_removed => {
const removed = device_manager_protocol.Protocol.decodeEvent(.child_removed, packet) orelse continue;
writeLine("device-list: removed (device {d} port {d})\n", .{ removed.parent, removed.bus_address });
},
else => {},
}
}
}
@@ -71,10 +71,10 @@ pub fn main() void {
return;
};
if (!device.claim(nic_id)) {
device.claim(nic_id) catch {
_ = logging.write("iommu-fault-test: FAIL claim\n");
return;
}
};
var function = pci.Function.map(nic_id, &descriptor) orelse {
_ = logging.write("iommu-fault-test: FAIL config-space map\n");
return;
@@ -64,7 +64,7 @@ pub fn main() void {
return;
};
writeLine("pci-cap-test: claiming ethernet function (device {d})\n", .{nic_id});
if (!check("claim", device.claim(nic_id))) return;
if (!check("claim", if (device.claim(nic_id)) |_| true else |_| false)) return;
var function = pci.Function.map(nic_id, &descriptor) orelse {
_ = logging.write("pci-cap-test: FAIL config-space map\n");
return;
@@ -0,0 +1,31 @@
//! The protocol-conformance-test fixture as a binary package (docs/build-packages-plan.md):
//! this file names the binary and EXACTLY the modules its source imports —
//! build-support resolves each name from the domains this zon declares.
const std = @import("std");
const build_support = @import("build-support");
pub fn build(b: *std.Build) void {
const exe = build_support.userBinary(b, .{
.name = "protocol-conformance-test",
.root_source_file = b.path("protocol-conformance-test.zig"),
.imports = &.{
"block-protocol",
"channel",
"device-manager-protocol",
"display-protocol",
"envelope",
"file-system",
"input-protocol",
"ipc",
"logging",
"power-protocol",
"process",
"scanout-protocol",
"time",
"usb-transfer-protocol",
"vfs-protocol",
},
});
b.installArtifact(exe);
}
@@ -0,0 +1,20 @@
.{
.name = .protocol_conformance_test,
.version = "0.0.0",
.fingerprint = 0xea942427118ba350, // Changing this has security and trust implications.
.minimum_zig_version = "0.16.0",
.dependencies = .{
// build-support supplies the shared recipe; kernel is implicit in
// every binary (the root shim + link script live there). The rest
// are exactly the homes of this binary's declared imports.
.@"build-support" = .{ .path = "../../../../build-support" },
.kernel = .{ .path = "../../../../library/kernel" },
// envelope: the reserved verbs and the errno a refused one answers;
// vfs-protocol: the registry's own readdir, which is where the set
// under test comes from; the four -protocol modules: the name, the
// version and the verb count each contract's `describe` must report,
// read off the contract itself rather than copied beside it.
.protocol = .{ .path = "../../../../library/protocol" },
},
.paths = .{""},
}
@@ -0,0 +1,350 @@
//! protocol-conformance-test — P4a's evidence that `envelope.Define` gives every
//! provider the reserved verbs, uniformly and without the provider writing a line
//! for them (docs/security-track-plan.md P4a;
//! docs/os-development/protocol-namespace.md). One binary, one role, driven by
//! the `protocol-conformance` kernel case:
//!
//! - `protocol-conformance-test run` — for each contract it can reach:
//! 1. `describe` — the reserved verb 0 — is answered, and the answer names
//! *that* protocol: the name it was opened under, the version its module
//! declares, and the number of verbs its module declares. No provider in
//! the system implements `describe`; the generated dispatch answers it out
//! of the specification, which is exactly the claim being checked;
//! 2. a verb number no protocol in the system defines answers `-ENOSYS`, and
//! carries no capability. That is the other half of the same generated
//! dispatch: a provider does not have to reject strangers, it gets the
//! rejection for free and every provider gives the same one;
//! 3. `describe` again, after the refusal — a refused verb is an *answer*,
//! not a wedged service, so the channel is still good afterwards.
//!
//! **The set it checks is read, never hardcoded.** The fixture asks `/protocol`
//! for its own listing (`readdir`, which the namespace publishes on purpose) and
//! walks what it finds, so the case cannot drift from what this boot actually
//! bound. What it opens is bounded by P3: the manifest names this binary against
//! exactly the two contracts its scenario boots, and an ungranted name is absent
//! for it like any other client's.
//!
//! **What it covers, and what it cannot — the honest list.** The scenario boots
//! the registry, the input service, and the compositor, so `input` and `display`
//! are checked end to end over real IPC. The other six contracts in the table
//! are not asked here, and the reason is the provider, not the protocol:
//!
//! - `vfs` — the FAT server, which needs a mounted volume behind the whole USB
//! storage chain (the `fat-mount` scenario);
//! - `block` — the usb-storage driver, which the device manager spawns after
//! enumerating an xHCI bus (the `usb-storage` scenario);
//! - `scanout` — the virtio-gpu driver, which needs an emulated virtio-gpu the
//! default harness does not attach (the `virtio-gpu` scenario);
//! - `device-manager` and `power` — both come with the device manager: it *is*
//! the first and spawns the discovery service that binds the second, so
//! booting a provider for either means booting the whole driver tree here.
//! - `usb-transfer` — never a registry name at all: several bus processes
//! provide it (one per controller) and consumers get their controller's
//! channel from the device manager's hello, routed by lineage
//! (communication.md "Establishment: two planes"). Its row below checks the
//! contract's shape only.
//!
//! That is the reason this scenario stays at two providers rather than five or
//! eight. It is not only the cost of booting half the system to send two
//! packets: this fixture takes **one snapshot** of `/protocol` and checks what
//! is in it, so a scenario whose bound set depends on how far a driver tree got
//! by that instant would make the case's own summary a boot race. What proves
//! the six instead is the scenarios that already drive them end to end —
//! `fat-mount`, `usb-storage`, `virtio-gpu`, and for the P4b three the
//! `device-list`, `driver-restart`, `pci-scan`, `usb-*`, `power-button` and
//! `orderly-shutdown` cases, every one of which is a live conversation over
//! these wires.
//!
//! All six sit in the table below regardless, so a scenario that binds one gets
//! it conformance-checked without this file being edited — and every run prints,
//! by name, the ones it found no provider for.
//!
//! The registry itself — PID 1 serving `/protocol` — is the one vfs backend
//! deliberately NOT dispatched through the generated table (it reads a
//! stranger's packet by hand, `system/services/init/init.zig`), so `describe` is
//! not asked of it and nothing here claims it.
//!
//! Prints `protocol-conformance: ok` on success, or a `protocol-conformance:
//! FAIL` line naming the step. Spawned bare (the initial-ramdisk sweep starts
//! every bundled binary), it exits silently so it cannot derange other tests.
const std = @import("std");
const channel = @import("channel");
const envelope = @import("envelope");
const file_system = @import("file-system");
const ipc = @import("ipc");
const logging = @import("logging");
const process = @import("process");
const time = @import("time");
const block_protocol = @import("block-protocol");
const device_manager_protocol = @import("device-manager-protocol");
const display_protocol = @import("display-protocol");
const input_protocol = @import("input-protocol");
const power_protocol = @import("power-protocol");
const scanout_protocol = @import("scanout-protocol");
const usb_transfer_protocol = @import("usb-transfer-protocol");
const vfs_protocol = @import("vfs-protocol");
// --- what conformance means, per contract -----------------------------------
/// One contract this fixture knows how to check, and what the answer must say.
/// Every field is read off the protocol module itself, so the expectation is the
/// contract's own definition rather than a number copied beside it — a version
/// bump or a new verb updates this table by recompiling.
const Contract = struct {
name: []const u8,
version: u32,
/// How many verbs the module declares — `describe` reports it, so it is
/// checked. The reserved verbs are not counted: they are the envelope's.
operations: u32,
/// Whether this scenario boots a provider for it. A required contract that
/// is missing, unreachable or non-conforming fails the case; the rest are
/// checked when some other scenario happens to bind them.
required: bool,
};
fn contractOf(comptime Protocol: type, required: bool) Contract {
return .{
.name = Protocol.protocol_name,
.version = Protocol.version,
.operations = @typeInfo(Protocol.Operation).@"enum".fields.len,
.required = required,
};
}
/// The protocols built on `envelope.Define`. A name listed by `/protocol` that
/// is absent from here is reported and left alone rather than probed: a
/// hand-numbered provider would read operation 0 as one of its own verbs, so
/// asking it for `describe` would *do* something. Only `ps2-bus` is still in
/// that state today.
const contracts = [_]Contract{
contractOf(input_protocol.Protocol, true), // the input fan-out service
contractOf(display_protocol.Protocol, true), // the compositor
contractOf(vfs_protocol.Protocol, false), // the FAT server — needs a volume
contractOf(block_protocol.Protocol, false), // usb-storage — needs the xHCI chain
contractOf(scanout_protocol.Protocol, false), // virtio-gpu — needs the device
// device-manager and power need the device manager (and what it starts),
// which is more than this scenario boots — see the header.
contractOf(device_manager_protocol.Protocol, false),
contractOf(power_protocol.Protocol, false), // the discovery service
contractOf(usb_transfer_protocol.Protocol, false), // never bound: per-controller, routed by hello
};
/// A verb number no protocol in the system defines, and none plausibly will: far
/// above the reserved range, so it is unambiguously a protocol verb, and far
/// above any protocol's verb count, so the generated dispatch has nothing to
/// match it against. The answer must be `-ENOSYS` at every provider.
const stranger_operation: u32 = envelope.first_protocol_operation + 4096;
fn fail(step: []const u8) noreturn {
_ = logging.write("protocol-conformance: FAIL ");
_ = logging.write(step);
_ = logging.write("\n");
process.exit(1);
}
fn report(comptime format: []const u8, arguments: anytype) void {
var line: [192]u8 = undefined;
_ = logging.write(std.fmt.bufPrint(&line, format, arguments) catch return);
}
// --- reading the namespace ---------------------------------------------------
/// The cadence every client in the tree spends finding a service.
const resolve_attempts: u32 = 200;
const resolve_retry_ms: u64 = 20;
/// The registry's endpoint, obtained the way every process obtains it: resolve
/// `/protocol`. The handle is the kernel's, shared with every other user of the
/// mount, so it is never ours to close. Patient, because the harness starts the
/// registrar and this fixture together and a first resolve can land before init
/// has mounted `/protocol` at all.
fn registryEndpoint() ?ipc.Handle {
var attempt: u32 = 0;
while (attempt < resolve_attempts) : (attempt += 1) {
var relative: [channel.path_maximum]u8 = undefined;
if (file_system.fsResolve(channel.root, 0, &relative)) |route| switch (route) {
.kernel => return null, // a kernel route means something other than the registry owns the name
.backend => |backend| return backend.handle,
};
time.sleepMillis(resolve_retry_ms);
}
return null;
}
/// One `readdir(cursor)` at the registry, into `into`. Null at end of directory
/// or on any failure — the caller is walking a listing, and both mean "stop".
///
/// The listing is what makes this test un-driftable: `/protocol` publishes what
/// is bound (protocol-namespace.md — the tree stays diagnosable), so the set
/// under test is the set this boot actually produced.
fn entryAt(registry: ipc.Handle, cursor: u64, into: []u8) ?[]u8 {
var packet: [vfs_protocol.message_maximum]u8 = undefined;
const framed = vfs_protocol.Protocol.encodeRequest(.readdir, 0, .{ .cursor = cursor }, &.{}, &packet) orelse return null;
var reply: [vfs_protocol.message_maximum]u8 = undefined;
const got = ipc.callCap(registry, framed, &reply, null) catch return null;
// A readdir owes no capability; one that arrived anyway is a handle slot.
if (got.cap) |handle| _ = ipc.close(handle);
const answer = reply[0..got.len];
const status = envelope.statusOf(answer) orelse return null;
if (status.status != 0) return null;
const entry = vfs_protocol.Protocol.decodeReply(.readdir, answer) orelse return null;
if (entry.name_len == 0) return null; // end of directory
const text = vfs_protocol.Protocol.replyTail(.readdir, answer);
const length = @min(@as(usize, entry.name_len), @min(text.len, into.len));
@memcpy(into[0..length], text[0..length]);
return into[0..length];
}
/// The listing, taken once so every later question is asked of one observation
/// rather than of a namespace that may have moved underneath it.
const maximum_listed: usize = 32;
var listed_names: [maximum_listed][channel.name_maximum]u8 = undefined;
var listed_lengths: [maximum_listed]usize = undefined;
var listed_count: usize = 0;
fn listedName(index: usize) []const u8 {
return listed_names[index][0..listed_lengths[index]];
}
fn takeListing(registry: ipc.Handle) void {
listed_count = 0;
var cursor: u64 = 0;
while (cursor < maximum_listed) : (cursor += 1) {
const name = entryAt(registry, cursor, &listed_names[listed_count]) orelse return;
listed_lengths[listed_count] = name.len;
listed_count += 1;
}
}
/// Whether `/protocol` currently lists `name`.
fn listed(registry: ipc.Handle, name: []const u8) bool {
var cursor: u64 = 0;
while (cursor < maximum_listed) : (cursor += 1) {
var scratch: [channel.name_maximum]u8 = undefined;
const entry = entryAt(registry, cursor, &scratch) orelse return false;
if (std.mem.eql(u8, entry, name)) return true;
}
return false;
}
/// Wait until `/protocol` lists `name` — the providers this case needs come up
/// alongside the fixture, and racing them would make the listing a boot race
/// rather than an observation.
fn awaitListed(registry: ipc.Handle, name: []const u8) void {
var attempts: u32 = 0;
while (attempts < 400) : (attempts += 1) {
if (listed(registry, name)) return;
time.sleepMillis(20);
}
report("protocol-conformance: FAIL /protocol never listed {s}\n", .{name});
process.exit(1);
}
// --- the assertions ----------------------------------------------------------
/// The three checks, against one open channel. Every failure is fatal: the point
/// of the case is that these hold at *every* provider, so one that does not is
/// not a degraded result, it is the regression.
fn conform(link: channel.Channel, contract: Contract) void {
var buffer: [envelope.packet_maximum]u8 = undefined;
// 1. The reserved verb no provider implements. `describe` is answered from
// the specification by the generated dispatch, so what comes back is the
// contract's own identity — checked field by field against the module
// this fixture compiled against.
const described = link.describe(&buffer) orelse fail("describe was not answered");
if (!std.mem.eql(u8, described.name, contract.name)) fail("describe named a different protocol");
if (described.description.version != contract.version) fail("describe answered the wrong version");
if (described.description.operation_count != contract.operations) fail("describe counted the wrong number of verbs");
// 2. A number no protocol wears. Nothing in the provider looks at it; the
// dispatch table finds no handler and refuses, identically everywhere.
var into: [envelope.packet_maximum]u8 = undefined;
const answered = link.call(.{ .operation = stranger_operation }, &.{}, &into) orelse
fail("a stranger verb was not answered at all");
if (answered.status.status != -envelope.ENOSYS) fail("a stranger verb did not answer -ENOSYS");
if (answered.status.len != 0) fail("a refused verb promised a payload");
if (answered.capability) |handle| {
_ = ipc.close(handle);
fail("a refused verb handed back a capability");
}
// 3. A refusal is an answer, not a wedge — so the same channel still works.
const again = link.describe(&buffer) orelse fail("the provider stopped answering after a refused verb");
if (!std.mem.eql(u8, again.name, contract.name)) fail("describe changed its answer after a refused verb");
report("protocol-conformance: {s} v{d} describes itself ({d} verbs), verb {d} -> -ENOSYS\n", .{
contract.name,
contract.version,
contract.operations,
stranger_operation,
});
}
fn contractIndex(name: []const u8) ?usize {
for (contracts, 0..) |contract, index| {
if (std.mem.eql(u8, contract.name, name)) return index;
}
return null;
}
fn run() void {
const registry = registryEndpoint() orelse fail("resolve /protocol");
// Every contract this scenario is supposed to be able to check must be bound
// before the listing is taken, or the case would assert nothing on a slow
// boot instead of failing on a broken one.
for (contracts) |contract| {
if (contract.required) awaitListed(registry, contract.name);
}
takeListing(registry);
if (listed_count == 0) fail("/protocol listed nothing at all");
report("protocol-conformance: /protocol lists {d} contract(s)\n", .{listed_count});
var checked = [_]bool{false} ** contracts.len;
for (0..listed_count) |index| {
const name = listedName(index);
const found = contractIndex(name) orelse {
// Not a lie of omission: named on serial, with the reason.
report("protocol-conformance: {s} skipped — not built on envelope.Define yet\n", .{name});
continue;
};
const contract = contracts[found];
const link = channel.Channel.connect(name) orelse {
// P3 is in force: an ungranted name is absent for this binary, and
// that is a manifest fact, not a failure — unless the scenario is
// supposed to have granted it.
if (contract.required) fail("a contract this fixture is granted would not open");
report("protocol-conformance: {s} skipped — not granted to this fixture\n", .{name});
continue;
};
conform(link, contract);
link.close();
checked[found] = true;
}
// The vacuity guard, and the honest tail: a required contract that went
// unchecked fails the case, and every other one this fixture knows how to
// check but found no provider for is named, so the coverage is legible on
// serial rather than inferred from what is absent.
var count: usize = 0;
for (contracts, 0..) |contract, index| {
if (checked[index]) {
count += 1;
continue;
}
if (contract.required) fail("a contract this scenario boots was never conformance-checked");
report("protocol-conformance: {s} not bound in this scenario — no provider to ask\n", .{contract.name});
}
report("protocol-conformance: {d} provider(s) answered the reserved verbs identically\n", .{count});
_ = logging.write("protocol-conformance: ok\n");
}
pub fn main(startup: process.Init) void {
const role = startup.arguments.get(1) orelse return; // bare (ramdisk sweep): stay silent
if (std.mem.eql(u8, role, "run")) run();
}
@@ -95,9 +95,13 @@ const Answer = struct {
/// Whether a capability rode the reply. The one field that actually matters
/// to a client: the capability IS the channel.
capability: bool = false,
/// The reply header, decoded — compared field by field as well as byte for
/// byte, so a failure says *which* field diverged.
reply: vfs_protocol.Reply = .{ .status = 0, .node = 0, .len = 0 },
/// The reply's envelope `Status`, decoded — compared field by field as well
/// as byte for byte, so a failure says *which* field diverged.
status: envelope.Status = .{ .status = 0, .len = 0 },
/// The node id the reply carried, or null when it carried no reply body at
/// all. A refusal has none; the open of a contract carries a zero, because
/// the capability is the whole answer.
node: ?u64 = null,
fn bytes(self: *const Answer) []const u8 {
return self.packet[0..self.length];
@@ -129,33 +133,30 @@ fn registryEndpoint() ?ipc.Handle {
const resolve_attempts: u32 = 200;
const resolve_retry_ms: u64 = 20;
/// One vfs-protocol request at the registry: the fixed header, then the contract
/// name inline. Names go bare (`input`, not `/input`) — the registrar normalises
/// both, and bare is what `bind` sends.
fn transact(registry: ipc.Handle, operation: vfs_protocol.Operation, name: []const u8, cursor: u64) ?Answer {
var request: [vfs_protocol.message_maximum]u8 = undefined;
if (vfs_protocol.request_size + name.len > request.len) return null;
const header = vfs_protocol.Request{
.operation = operation,
.node = 0,
.offset = cursor,
.len = @intCast(name.len),
.flags = 0,
};
@memcpy(request[0..vfs_protocol.request_size], std.mem.asBytes(&header));
@memcpy(request[vfs_protocol.request_size..][0..name.len], name);
/// One vfs-protocol request at the registry: the folded header, the verb's own
/// fixed part, then the contract name as the packet's tail. Names go bare
/// (`input`, not `/input`) — the registrar normalises both, and bare is what
/// `bind` sends.
fn transact(
registry: ipc.Handle,
comptime operation: vfs_protocol.Operation,
request: vfs_protocol.Protocol.RequestOf(operation),
name: []const u8,
) ?Answer {
var packet: [vfs_protocol.message_maximum]u8 = undefined;
const framed = vfs_protocol.Protocol.encodeRequest(operation, 0, request, name, &packet) orelse return null;
var answer: Answer = .{};
const got = ipc.callCap(
registry,
request[0 .. vfs_protocol.request_size + name.len],
&answer.packet,
null,
) catch return null;
if (got.len < vfs_protocol.reply_size) return null;
const got = ipc.callCap(registry, framed, &answer.packet, null) catch return null;
answer.length = got.len;
answer.capability = got.cap != null;
answer.reply = std.mem.bytesToValue(vfs_protocol.Reply, answer.packet[0..vfs_protocol.reply_size]);
answer.status = envelope.statusOf(answer.bytes()) orelse return null;
answer.node = if (operation == .open) blk: {
const opened = vfs_protocol.Protocol.decodeReply(.open, answer.bytes()) orelse break :blk null;
// A short reply decodes as garbage rather than absence, so the promised
// length is what says whether a body is there at all.
break :blk if (answer.status.len < @sizeOf(vfs_protocol.Opened)) null else opened.node;
} else null;
// A capability we did not ask to keep is a handle slot spent; the assertions
// below only care that one arrived.
if (got.cap) |handle| _ = ipc.close(handle);
@@ -165,7 +166,7 @@ fn transact(registry: ipc.Handle, operation: vfs_protocol.Operation, name: []con
/// `open(name)`, kept whole. Null only if the registry could not be reached at
/// all — a registrar that answered has decided, and its decision is the subject.
fn openContract(registry: ipc.Handle, name: []const u8) Answer {
return transact(registry, .open, name, 0) orelse fail("the registry stopped answering");
return transact(registry, .open, .{ .flags = 0 }, name) orelse fail("the registry stopped answering");
}
/// Whether `/protocol` currently lists `name`. The namespace is browsable on
@@ -177,12 +178,11 @@ fn openContract(registry: ipc.Handle, name: []const u8) Answer {
fn listed(registry: ipc.Handle, name: []const u8) bool {
var cursor: u64 = 0;
while (cursor < 64) : (cursor += 1) {
const answer = transact(registry, .readdir, "", cursor) orelse return false;
if (answer.reply.status != 0 or answer.reply.len == 0) return false; // end of directory
const payload = answer.packet[vfs_protocol.reply_size..answer.length];
if (payload.len < vfs_protocol.directory_entry_size) return false;
const entry = std.mem.bytesToValue(vfs_protocol.DirectoryEntry, payload[0..vfs_protocol.directory_entry_size]);
const text = payload[vfs_protocol.directory_entry_size..];
const answer = transact(registry, .readdir, .{ .cursor = cursor }, "") orelse return false;
if (answer.status.status != 0) return false;
const entry = vfs_protocol.Protocol.decodeReply(.readdir, answer.bytes()) orelse return false;
if (entry.name_len == 0) return false; // end of directory
const text = vfs_protocol.Protocol.replyTail(.readdir, answer.bytes());
const length = @min(@as(usize, entry.name_len), text.len);
if (std.mem.eql(u8, text[0..length], name)) return true;
}
@@ -207,14 +207,24 @@ fn awaitListed(registry: ipc.Handle, name: []const u8) void {
/// Every caller-visible field of two answers, compared. `step` names the pair so
/// a failure says which comparison broke and in which field.
fn expectIdentical(step: []const u8, refused: Answer, absent: Answer) void {
if (refused.reply.status != absent.reply.status) fail(step); // the errno
if (refused.reply.node != absent.reply.node) fail(step); // the node id an open would return
if (refused.reply.len != absent.reply.len) fail(step); // payload bytes promised
if (refused.status.status != absent.status.status) fail(step); // the errno
if (!nodesMatch(refused.node, absent.node)) fail(step); // the node id an open would return
if (refused.status.len != absent.status.len) fail(step); // payload bytes promised
if (refused.length != absent.length) fail(step); // reply packet length
if (refused.capability != absent.capability) fail(step); // the channel itself
if (!std.mem.eql(u8, refused.bytes(), absent.bytes())) fail(step); // and every byte of it
}
/// Two node ids agree when both are absent or both are the same value. A refusal
/// carries none at all now — the envelope sends a bare `Status` — so "no node"
/// is itself one of the observations that has to match.
fn nodesMatch(one: ?u64, other: ?u64) bool {
if (one) |a| {
return if (other) |b| a == b else false;
}
return other == null;
}
fn run() void {
const registry = registryEndpoint() orelse fail("resolve /protocol");
@@ -232,14 +242,14 @@ fn run() void {
// 1. The control. A granted, bound contract opens: success, and the
// capability that IS the channel.
const allowed = openContract(registry, granted_contract);
if (allowed.reply.status != 0) fail("a granted open was refused");
if (allowed.status.status != 0) fail("a granted open was refused");
if (!allowed.capability) fail("a granted open carried no channel");
_ = logging.write("protocol-denied: granted open succeeded\n");
// 2. The refusal. `input` is bound — the listing above proved it — and no
// manifest row names this binary against it.
const refused = openContract(registry, forbidden_contract);
if (refused.reply.status != -envelope.ENOENT) fail("an ungranted open did not answer -ENOENT");
if (refused.status.status != -envelope.ENOENT) fail("an ungranted open did not answer -ENOENT");
if (refused.capability) fail("an ungranted open carried a channel");
_ = logging.write("protocol-denied: ungranted open refused as absent\n");
@@ -259,7 +269,7 @@ fn run() void {
// what it should, so what steps 2-4 saw was policy and not a registry
// that had wedged.
const again = openContract(registry, granted_contract);
if (again.reply.status != 0 or !again.capability) fail("the granted contract stopped opening");
if (again.status.status != 0 or !again.capability) fail("the granted contract stopped opening");
_ = logging.write("protocol-denied: ok\n");
}
@@ -288,8 +288,10 @@ fn run() void {
// — the strongest one available, because a regression does not fail this
// line, it takes the entire boot down with it.
const registry = registryEndpoint() orelse fail("resolve /protocol");
const forged = power_protocol.EventMessage{ .event = @intFromEnum(power_protocol.Event.power_button) };
if (!ipc.send(registry, std.mem.asBytes(&forged))) fail("post a forged power event");
var forged: [envelope.post_maximum]u8 = undefined;
const packet = power_protocol.Protocol.encodeEvent(.power_button, 0, .{}, &forged) orelse
fail("frame a forged power event");
if (!ipc.send(registry, packet)) fail("post a forged power event");
const still_serving = verdictWithin(forbidden, spare) orelse
fail("the registrar went silent after a forged power event — it acted on it");
if (still_serving != -envelope.EPERM) fail("the registry misanswered after a forged power event");
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff. Show more