Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3e6e21bf0a | ||
|
|
0fbd2c8f12 | ||
|
|
1379b699f3 | ||
|
|
1ff0991452 | ||
|
|
ac01f627d1 | ||
|
|
f3bc23cb81 | ||
|
|
8d4a7cf240 | ||
|
|
c4f16a5448 |
No files matched your search
@@ -115,7 +115,8 @@ fn driverArtifact(comptime package: []const u8, comptime artifact: []const u8) S
|
||||
|
||||
/// The production ship table — what a plain `zig build` image contains,
|
||||
/// beyond the specials the build fn adds around it (init, discovery, the
|
||||
/// /etc data files; the /test fixtures join only under -Dtest-case).
|
||||
/// /system/configuration data files; the /test fixtures join only under
|
||||
/// -Dtest-case).
|
||||
/// Selecting what goes into a build = selecting rows: a package in no row is
|
||||
/// not just unshipped, its build file is never even loaded
|
||||
/// (docs/build-packages-plan.md).
|
||||
@@ -265,9 +266,9 @@ pub fn build(b: *std.Build) void {
|
||||
// (receives the root's -Dserial as a dependency option — its liveness
|
||||
// heartbeat is a serial/test-build diagnostic the QEMU harness asserts
|
||||
// on; a flashable image leaves it out), discovery (the -Ddiscovery pick),
|
||||
// and the /etc data files. Each binary builds itself against the domain
|
||||
// packages via build-support's shared recipe; the root just takes
|
||||
// artifacts (docs/build-packages-plan.md).
|
||||
// and the /system/configuration data files. Each binary builds itself
|
||||
// against the domain packages via build-support's shared recipe; the root
|
||||
// just takes artifacts (docs/build-packages-plan.md).
|
||||
var bundled_list: std.ArrayListUnmanaged(images.BundledBinary) = .empty;
|
||||
bundled_list.append(b.allocator, .{
|
||||
.path = "system/services/init",
|
||||
@@ -300,15 +301,21 @@ pub fn build(b: *std.Build) void {
|
||||
.binary = b.dependency(row.package, .{}).artifact(row.artifact).getEmittedBin(),
|
||||
}) catch @panic("OOM");
|
||||
}
|
||||
// Data files, not binaries: packing them under /etc makes the kernel
|
||||
// auto-mount /etc as a read-only initrd tree (system/kernel/vfs.zig
|
||||
// Data files, not binaries: packing them under /system/configuration rides
|
||||
// the kernel's read-only initrd mount of /system (system/kernel/vfs.zig
|
||||
// setInitialRamdisk) — the device manager reads its registry and init its
|
||||
// service list with no filesystem service running. -Ddiagnose selects the
|
||||
// init.csv variant that omits the display stack (so the kernel's boot
|
||||
// transcript stays on screen); both bundle at the same /etc/init.csv path.
|
||||
const init_csv_source = if (diagnose) "etc/init-diagnose.csv" else "etc/init.csv";
|
||||
bundled_list.append(b.allocator, .{ .path = "etc/devices.csv", .binary = b.path("etc/devices.csv") }) catch @panic("OOM");
|
||||
bundled_list.append(b.allocator, .{ .path = "etc/init.csv", .binary = b.path(init_csv_source) }) catch @panic("OOM");
|
||||
// transcript stays on screen); both bundle at the same
|
||||
// /system/configuration/init.csv path.
|
||||
const init_csv_source = if (diagnose) "system/configuration/init-diagnose.csv" else "system/configuration/init.csv";
|
||||
bundled_list.append(b.allocator, .{ .path = "system/configuration/devices.csv", .binary = b.path("system/configuration/devices.csv") }) catch @panic("OOM");
|
||||
bundled_list.append(b.allocator, .{ .path = "system/configuration/init.csv", .binary = b.path(init_csv_source) }) catch @panic("OOM");
|
||||
// The protocol grants: who may claim which name under /protocol
|
||||
// (docs/os-development/protocol-namespace.md). init reads it beside init.csv,
|
||||
// out of the same read-only initrd, before it spawns anything — the registrar
|
||||
// has to know its policy before the first provider asks.
|
||||
bundled_list.append(b.allocator, .{ .path = "system/configuration/protocol.csv", .binary = b.path("system/configuration/protocol.csv") }) catch @panic("OOM");
|
||||
// A no-option build assumes neither -Dtest-case nor -Ddiagnose: it ships the
|
||||
// production set only. The userspace test fixtures under /test join in only
|
||||
// for a test build — which the QEMU harness signals by passing
|
||||
@@ -330,6 +337,9 @@ pub fn build(b: *std.Build) void {
|
||||
"args-echo",
|
||||
"process-test",
|
||||
"thread-test", // the multi-threaded fixture (its package sets .threaded)
|
||||
"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
|
||||
}) |fixture| {
|
||||
const package = b.lazyDependency(fixture, .{}) orelse
|
||||
@panic("a test fixture package is missing under test/system/services");
|
||||
|
||||
@@ -74,6 +74,9 @@
|
||||
.@"args-echo" = .{ .path = "test/system/services/args-echo", .lazy = true },
|
||||
.@"process-test" = .{ .path = "test/system/services/process-test", .lazy = true },
|
||||
.@"thread-test" = .{ .path = "test/system/services/thread-test", .lazy = true },
|
||||
.@"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 },
|
||||
// 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
|
||||
|
||||
+1
-1
@@ -83,7 +83,7 @@ pub fn addImageSteps(b: *std.Build, options: Options) std.Build.LazyPath {
|
||||
// holding the EFI stub, the kernel, and the whole /system tree of user
|
||||
// binaries at their FHS paths. QEMU presents this image as a USB mass-storage
|
||||
// device the guest boots from (see run-x86-64 and the test harness), and the
|
||||
// danos fat driver mounts the same image at /mnt/usb.
|
||||
// danos fat driver mounts the same image at /volumes/usb.
|
||||
const fat_image = addBootImage(b, options.kernel.getEmittedBin(), options.efi.getEmittedBin(), manifest_file, capsule_img, options.bundled);
|
||||
const fat_image_install = b.addInstallFile(fat_image, "danos-usb.img");
|
||||
b.getInstallStep().dependOn(&fat_image_install.step);
|
||||
|
||||
+2
-2
@@ -42,8 +42,8 @@ pub fn addRunSteps(b: *std.Build, fat_image_serial: std.Build.LazyPath) void {
|
||||
const vars_out = vars_copy.addOutputFileArg("OVMF_VARS.4m.fd");
|
||||
|
||||
// Capture the guest's serial0 (danos's machine-readable log) to the qemu-test
|
||||
// scratch area — a dev/host artifact, kept out of the FHS boot volume we mount.
|
||||
// (/var/log/system is reserved for the kernel's own logging system later.) One
|
||||
// scratch area — a dev/host artifact, kept out of the boot volume we mount.
|
||||
// (/system/logs on the volume belongs to the guest's own logger.) One
|
||||
// timestamped file per run.
|
||||
const log_dir = b.fmt("{s}/qemu-test", .{b.install_path});
|
||||
const make_log_dir = b.addSystemCommand(&.{ "mkdir", "-p", log_dir });
|
||||
|
||||
@@ -87,13 +87,13 @@ rest of the system hasn't had to face:
|
||||
│ (ResourceKind.memory = [base, height*pitch], write-combining hint,
|
||||
│ plus DisplayInfo{width, height, pitch, format, refresh_hz})
|
||||
▼
|
||||
display service (system/services/display/, ServiceId.display) ← the compositor
|
||||
display service (system/services/display/, /protocol/display) ← the compositor
|
||||
│ device.claim(display node) → mmio_map(WRITE-COMBINING) = FRONT buffer (the LFB)
|
||||
│ mmap(cacheable) a BACK buffer of the same geometry
|
||||
│ owns: an ordered LAYER STACK + a per-frame DAMAGE tracker (rect list or tile grid)
|
||||
│ loop: composite dirty layers → back buffer → present dirty rects → front
|
||||
│ backend is an INTERNAL interface: {gop-fb} at boot; {virtio-gpu} on hot-attach (v2)
|
||||
▼ reached by name (ipc_lookup); clients drive it over the display protocol
|
||||
▼ reached by name (open /protocol/display); clients drive it over the display protocol
|
||||
┌────────────────────────────────────┬──────────────────────────────────────┐
|
||||
drawing clients (v1) surface clients (deferred)
|
||||
display commands: display surfaces:
|
||||
|
||||
@@ -114,9 +114,10 @@ unforgeable source addressing, a property a network's source field lacks.
|
||||
|
||||
The bootstrap problem — how a channel is first established — is the subject of
|
||||
[protocol-namespace.md](../os-development/protocol-namespace.md): a protocol is
|
||||
resolved by name and the channel arrives as a capability. (The mechanism this
|
||||
replaces, `ipc_register`/`ipc_lookup` under compile-time `ServiceId` integers,
|
||||
is retired by that design.)
|
||||
resolved by name and the channel arrives as a capability. (The mechanism it
|
||||
replaced — `ipc_register`/`ipc_lookup` under compile-time `ServiceId` integers —
|
||||
is gone: both syscalls and the enum were deleted when the registry landed, and
|
||||
their syscall numbers are left vacant.)
|
||||
|
||||
### Interrupts are signals
|
||||
|
||||
@@ -169,6 +170,27 @@ signal mechanism:
|
||||
- **One-shot timers** (`timer_bind`, `time.timerOnce`) land as a
|
||||
timer-bit signal — the timed wait: a service arms a deadline and keeps
|
||||
serving, instead of blocking in sleep.
|
||||
- **Kernel notifications go only to your own endpoint.** `signal_bind`,
|
||||
`timer_bind`, `process_subscribe`, `irq_bind`, `msi_bind`, and spawn's exit
|
||||
endpoint all *nominate where the kernel will speak*, and all of them refuse an
|
||||
endpoint the caller did not create (`-EPERM`; the check is `ipc.ownedBy`,
|
||||
normalized to the process, so any thread may nominate an endpoint a sibling
|
||||
created). Holding a handle is not enough, because holding a handle is cheap:
|
||||
`fs_resolve` installs a mounted backend's capability in *any* caller's table,
|
||||
so every process holds a handle to PID 1's mailbox. Without the rule, "bind
|
||||
init's endpoint, then signal yourself" is a genuine, kernel-stamped `terminate`
|
||||
badge in PID 1's queue — a shutdown a receiver has no way to disbelieve — and
|
||||
timers, which carry no identity at all, multiply any loop that re-arms on its
|
||||
own landing.
|
||||
- **A capability that arrives belongs to the turn.** The kernel installs a sent
|
||||
capability in the receiver's table whatever the message's length or kind, so a
|
||||
receive loop must dispose of one on *every* path — the ping, the notification,
|
||||
the malformed request. The service harness (`service.run`) and PID 1 both hold
|
||||
it in an `ipc.Arrival`, released by a `defer`, and a handler that means to keep
|
||||
it says `take()`: forgetting closes, keeping is explicit. The reverse
|
||||
arrangement leaks a handle-table slot per request, and thirty-two unauthorized
|
||||
zero-length pings then end a service's ability to accept any capability —
|
||||
no subscribe, no shared-memory handover — for the rest of the boot.
|
||||
- **The universal ping**: a **zero-length request is the liveness probe**,
|
||||
answered with a zero-length reply by the service harness itself
|
||||
(`service.run`). No protocol's requests start at length zero, so the
|
||||
|
||||
@@ -161,15 +161,26 @@ Aligned to the node-kind table in the file-system hierarchy
|
||||
| 4 | symbolic link |
|
||||
| 5 | fifo |
|
||||
| 6 | socket |
|
||||
| 7 | protocol |
|
||||
|
||||
Clients should map unknown values to *regular* rather than reject — the
|
||||
table can grow. Kind 6 (`socket`) keeps its wire value but is retired from
|
||||
the design — a named rendezvous point is exactly what a `protocol` node is,
|
||||
planned as value 7 with the protocol namespace
|
||||
landed as value 7 with the protocol namespace
|
||||
(docs/os-development/protocol-namespace.md). `character_device` (stream
|
||||
semantics — the tty/console shape) and `block_device` (raw sector-addressed
|
||||
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
|
||||
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
|
||||
per-operation, so a client that opens an ordinary file simply receives no
|
||||
capability, exactly as before.
|
||||
|
||||
## Lifetimes and trust
|
||||
|
||||
Open-node ids live in the backend. A client that dies without closing leaks
|
||||
@@ -188,8 +199,8 @@ 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, `Operation` values 0, 4 and 5); this page is the
|
||||
full record of the frozen values.
|
||||
size, `NodeKind` 0–1 and 6–7, `Operation` values 0, 4 and 5); this page is
|
||||
the full record of the frozen values.
|
||||
- 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.
|
||||
|
||||
@@ -231,8 +231,8 @@ Two consequences of neutrality bind on later work:
|
||||
|
||||
- **Cross-firmware surfaces are named by domain, not firmware.** System power is
|
||||
a [`power`](power.md) protocol, not an "ACPI events" protocol: on x86 the acpi
|
||||
service registers it, on ARM a PSCI/mailbox service registers the same
|
||||
`ServiceId.power`, and subscribers never learn the difference.
|
||||
service binds it, on ARM a PSCI/mailbox service binds the same
|
||||
`/protocol/power`, and subscribers never learn the difference.
|
||||
- **Identity must widen before the fdt service exists.** `DeviceDescriptor`'s
|
||||
8-byte `hid` holds an EISA id but cannot hold an FDT `compatible` string
|
||||
(`"brcm,bcm2835-aux-uart"`); the identity field grows before the ARM path can
|
||||
|
||||
@@ -15,9 +15,9 @@ Where the events come from is firmware-specific — on x86 they ride the ACPI SC
|
||||
([acpi.md](acpi.md)); on a Raspberry Pi they would come from PSCI or a mailbox.
|
||||
What subscribers want is not: *the lid closed* means the same thing regardless of
|
||||
who noticed. So the surface is **domain-named**. There is a `power-protocol`
|
||||
module and a well-known `ServiceId.power = 5`; on x86 the **acpi service**
|
||||
registers it, and on ARM a PSCI/mailbox service will register the *same* id.
|
||||
Subscribers call `ipc.lookup(.power)` and never learn which firmware they
|
||||
module and a contract named `/protocol/power`; on x86 the **acpi service**
|
||||
binds it, and on ARM a PSCI/mailbox service will bind the *same* name.
|
||||
Subscribers open `/protocol/power` and never learn which firmware they
|
||||
are on — the neutrality the whole [discovery](discovery.md) migration exists to
|
||||
preserve, carried one layer up into a running-system surface.
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
# The protocol namespace
|
||||
|
||||
*Design, agreed 2026-07-31. Supersedes the `ServiceId` registry. Not yet implemented —
|
||||
the migration plan at the end is the work list.*
|
||||
*Design, agreed 2026-07-31. Supersedes the `ServiceId` registry. P1–P3 of the
|
||||
migration plan at the end have landed (the envelope, the registry and the
|
||||
`ServiceId` flag-day, and restriction stage one); P4 and P5 are the remaining
|
||||
work list.*
|
||||
|
||||
How a program finds, connects to, and is restricted from the things it talks to.
|
||||
Three ideas, kept deliberately separate:
|
||||
|
||||
@@ -27,7 +27,7 @@ packages whose build.zig calls `build_support.userBinary` (with `.threaded =
|
||||
true` where a binary spawns threads) and get packed into the initial-ramdisk;
|
||||
new syscalls extend [abi.zig](../../system/abi.zig) `SystemCall` + a
|
||||
`library/kernel` wrapper; test services live beside the code they exercise and
|
||||
register a `ServiceId` if they must be looked up.
|
||||
bind a `/protocol/test/...` name if they must be reachable.
|
||||
|
||||
## How to verify along the way
|
||||
|
||||
|
||||
@@ -270,13 +270,15 @@ stays single-threaded and lean.
|
||||
- *Handles do not cross threads.* The handle table lives on the `Task`
|
||||
([scheduler.zig](../../system/kernel/scheduler.zig)), so a handle number is meaningful
|
||||
only to the thread that created it — thread A's endpoint handle `3` is not thread B's.
|
||||
A thread that needs to reach an endpoint another thread owns looks it up
|
||||
(`ipc.lookup(service)`) to install its **own** handle to the same underlying endpoint.
|
||||
This is how the display's mouse-listener thread reaches the compositor loop's endpoint
|
||||
to poke it awake (docs/display.md).
|
||||
A thread that needs to reach an endpoint another thread owns opens the name
|
||||
(`channel.openEndpoint("display")`) to install its **own** handle to the same
|
||||
underlying endpoint — an ordinary client open, with no special mechanism for the
|
||||
fact that the provider happens to be this process. This is how the display's
|
||||
mouse-listener thread reaches the compositor loop's endpoint to poke it awake
|
||||
(docs/display.md).
|
||||
- *IPC syscalls that touch shared kernel state now serialize under the big kernel lock.*
|
||||
`create_ipc_endpoint`/`ipc_register`/`ipc_lookup` allocate from the kernel heap and
|
||||
mutate the global service registry, endpoint refcounts, and handle tables. Those paths
|
||||
`create_ipc_endpoint` allocates from the kernel heap and
|
||||
mutates endpoint refcounts and handle tables. Those paths
|
||||
were unlocked because a single-threaded process could not race itself; a multi-threaded
|
||||
one can, from two cores at once. They now take `sync.enter()` like `call`/`reply_wait`/
|
||||
`send` already did — the kernel heap has no lock of its own (heap.zig: "every kernel
|
||||
|
||||
@@ -137,15 +137,15 @@ Grouped as `abi.zig` groups them:
|
||||
| process | `danos_exit`, `danos_yield`, `danos_sleep`, `danos_spawn`, `danos_process_enumerate`, `danos_process_kill`, `danos_process_exit_reason`, `danos_process_subscribe`, `danos_process_signal`, `danos_signal_bind` |
|
||||
| threads | `danos_thread_spawn`, `danos_thread_exit`, `danos_current_core`, `danos_futex_wait`, `danos_futex_wake`, `danos_thread_self`, `danos_thread_join`, `danos_set_thread_pointer` |
|
||||
| memory | `danos_mmap`, `danos_munmap`, `danos_dma_alloc`, `danos_dma_free`, `danos_shared_memory_create`, `danos_shared_memory_map`, `danos_shared_memory_physical` |
|
||||
| ipc | `danos_endpoint_create`, `danos_ipc_register`, `danos_ipc_lookup`, `danos_ipc_call`, `danos_ipc_reply_wait`, `danos_ipc_send` |
|
||||
| ipc | `danos_endpoint_create`, `danos_ipc_call`, `danos_ipc_reply_wait`, `danos_ipc_send` (naming is not a syscall: a provider binds its contract at the registry and a client resolves `/protocol/<name>` — see [protocol-namespace.md](protocol-namespace.md)) |
|
||||
| devices | `danos_device_enumerate`, `danos_device_claim`, `danos_device_register`, `danos_mmio_map`, `danos_irq_bind`, `danos_irq_ack`, `danos_msi_bind`, `danos_io_read`, `danos_io_write` |
|
||||
| time | `danos_clock`, `danos_wall_clock`, `danos_timer_bind` |
|
||||
| diagnostics | `danos_debug_write` (leveled, kernel-stamped records), `danos_klog_read`, `danos_klog_status` |
|
||||
| filesystem naming | `danos_fs_resolve`, `danos_fs_node`, `danos_fs_mount`, `danos_fs_unmount` (naming only — file DATA still crosses the vfs-protocol IPC, see below) |
|
||||
|
||||
The constants that ride alongside the calls — mmap protection bits, DMA
|
||||
flags, notification badge bits, `ExitReason`, `Signal`, well-known service
|
||||
ids, `page_size`, the IPC message maximum — move to the public header too:
|
||||
flags, notification badge bits, `ExitReason`, `Signal`, `page_size`, the IPC
|
||||
message maximum — move to the public header too:
|
||||
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.
|
||||
|
||||
@@ -31,14 +31,40 @@ the logging/USB-lifecycle track).
|
||||
|
||||
## Status
|
||||
|
||||
**Live state — updated on `main` after every phase, so this file read from a
|
||||
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 |
|
||||
| Last updated | 2026-08-01 |
|
||||
|
||||
A checkbox below means the phase met its definition of green and was
|
||||
committed — on the branch named above, which reaches `main` at the next
|
||||
group boundary.
|
||||
|
||||
- [x] **Phase 0** — baseline: suite green on `main` (106/106, 2026-07-31; `zig build` + `zig build test` clean at 9a32380), plan committed
|
||||
- [ ] **PM** — path-migration flag-day (`/etc`→`/system/configuration`, `/var/log`→`/system/logs`, `/mnt/usb`→`/volumes/usb`)
|
||||
- [ ] **H1** — the `user-memory` module; nine stragglers converted; leaf U/S+W checks
|
||||
- [ ] **merge** group 1 → main, push
|
||||
- [ ] **P1** — envelope module + `Define`; vfs `NodeKind.protocol` + open-reply-capability; client `Channel`
|
||||
- [ ] **P2** — registry in init; `/protocol` reserved; ServiceId flag-day (11 binds, 17 lookups)
|
||||
- [ ] **P3** — open grants: `protocol.csv` enforcement, denial test
|
||||
- [ ] **merge** group 2 → main, push
|
||||
- [x] **PM** — path-migration flag-day (`/etc`→`/system/configuration`, `/var/log`→`/system/logs`, `/mnt/usb`→`/volumes/usb`; vfs carve-out for the two writable `/system` subtrees, FAT's `/var` mount split in two; suite 106/106)
|
||||
- [x] **H1** — the `user-memory` module; nine stragglers converted; leaf U/S+W checks (plus physmap-coverage confirmation, so an `mmio_map`'d buffer cannot fault ring 0 — this also closes the same hazard on the IPC path; `fs_resolve`'s out-capacity bound made overflow-safe; suite 107/107)
|
||||
- [x] **merge** group 1 → main, push (f3bc23c, 2026-07-31)
|
||||
- [x] **P1** — envelope module + `Define`; vfs `NodeKind.protocol` + open-reply-capability; client `Channel` (mechanics only, nothing converted; suite unchanged at 107)
|
||||
- [x] **P2** — registry in init; `/protocol` reserved; ServiceId flag-day (11 binds, 17 lookups; `protocol.csv` grants, chain-attested identity, dead-owner rebind; the kernel's endpoint-death sweep generalized off the retired registry; suite 108/108). Three adversarial review rounds closed six defects a green suite had missed: a forged power event could shut the machine down; the ping path leaked a capability per call, first in init and then in the shared harness; supervisor attestation by name was defeated by a laundering deputy; and the kernel let any handle-holder bind signals, timers, exits and IRQs to an endpoint it did not own.
|
||||
- [x] **P3** — open grants: `protocol.csv` enforcement, denial test. `onOpen`
|
||||
consults the manifest with the same chain-attested identity a bind uses, and a
|
||||
refused caller gets the *same* answer as one naming a contract nobody bound —
|
||||
`-ENOENT`, no capability, the same reply bytes, no log line, and both questions
|
||||
asked on every open so there is nothing to time. Twenty-seven `open` rows cover
|
||||
the whole live client set. One wrinkle the plan had not foreseen: the driver
|
||||
tree is three deep (device manager → PS/2 bus → keyboard/mouse) and attestation
|
||||
is one hop, so a legitimate grandchild read exactly like a laundering deputy;
|
||||
the manifest gained a third permission, `supervise`, which names an authorized
|
||||
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
|
||||
@@ -87,6 +113,35 @@ that implements it.
|
||||
`init` for init's own children, `kernel` for harness-spawned fixtures),
|
||||
not in extra init.csv columns — today every post-path init.csv field is
|
||||
argv, and overloading that is ambiguous. init parses both files.
|
||||
*(P2 spelling: the supervisor column carries the binary exactly as the
|
||||
kernel stamped it, so init's own children say `/system/services/init` and
|
||||
the drivers say `/system/services/device-manager`; `kernel` stays a bare
|
||||
word because a kernel task has no binary. A trailing `*` on any field
|
||||
matches a subtree, which is how decision 4's `/test/` rule is expressed.)*
|
||||
*(Clarification, 2026-08-01: the supervisor column names **the authorized
|
||||
supervising task, matched by identity** — the binary is how the row spells
|
||||
it, but init checks the task id. `kernel` is satisfied only by supervisor
|
||||
id 0 (which only the kernel confers — user `system_spawn` always stamps the
|
||||
caller); init's own path only by this init's task id; any other path only by
|
||||
a task init spawned itself or one the kernel spawned. Matching the supervisor
|
||||
by *name* alone is defeated by a laundering deputy — an attacker runs its own
|
||||
instance of `/system/services/init`, has that spawn `/system/services/input`,
|
||||
and both stamped names satisfy the row while the chain is entirely the
|
||||
attacker's. Walking to the root of the chain does not fix it either, since
|
||||
the laundered chain still roots at the real PID 1.)*
|
||||
*(P3 amendment: a third permission, `supervise`, joins `bind|open`. One-hop
|
||||
attestation cannot express the one three-deep chain in the tree — the device
|
||||
manager starts the PS/2 bus, and the bus starts the keyboard and mouse
|
||||
drivers — and nothing structural tells that chain apart from the laundering
|
||||
deputy, since both are a granted binary spawned by a granted binary. Only
|
||||
policy can: a `supervise` row names the authorized supervising task the way
|
||||
every other row names a claimant (binary, its own supervisor, the contract it
|
||||
concerns), and an `open` row may then name that task in its supervisor
|
||||
column. The delegate is itself attested the ordinary strict way, so the chain
|
||||
still anchors in init or the kernel one hop above it and the recursion stops
|
||||
there. It is **open-only** on purpose — a delegate may vouch for what its
|
||||
children *reach*, never for what they *claim* — so the bind path is
|
||||
byte-for-byte P2's and the laundering-deputy refusal is untouched.)*
|
||||
4. **Test fixtures bind under `/protocol/test/...`**, granted to any
|
||||
binary whose path starts `/test/` — the subtree-scoping rule from the
|
||||
design doc, dogfooded. `shared_memory_test` (the borrowed-ServiceId
|
||||
@@ -115,6 +170,10 @@ that implements it.
|
||||
process-test) either spawn init first or move to init.csv-driven
|
||||
scenario boots — resolved per-case in P2 with the suite as the
|
||||
arbiter.
|
||||
*(P2 resolution: init gained a `registry` argv role — it mounts
|
||||
`/protocol`, reads the grants, and starts no services — and each affected
|
||||
case calls `spawnRegistry(rd)` before its own providers. Every case keeps
|
||||
its own spawn set, so no scenario had to be re-shaped.)*
|
||||
10. **The capsule-staleness caveat is documented, not fixed.** On-volume
|
||||
edits to `/system/configuration/*.csv` do not reach the initrd copy
|
||||
the loader boots (capsule shadows tree). Same drift exists today with
|
||||
@@ -277,6 +336,34 @@ Every existing scenario doubles as conversion proof. Suite 108.
|
||||
the first succeeds and the second fails identically to not-found. Suite
|
||||
109.
|
||||
|
||||
*Landed. Four things the plan did not foresee, recorded because P4 and P5
|
||||
inherit them:*
|
||||
|
||||
- *`supervise` — decision 3's amendment. The PS/2 keyboard and mouse drivers
|
||||
are started by the PS/2 bus driver, which the device manager started: the
|
||||
tree's one three-deep chain, and one hop deeper than attestation reaches.
|
||||
Nothing structural separates it from the laundering deputy, so the manifest
|
||||
says which delegate is authorized, per contract. Open-only, so P2's bind
|
||||
attestation is unchanged.*
|
||||
- *Indistinguishability is a claim about work, not only about bytes. `onOpen`
|
||||
refreshes the process table, identifies the caller, scans the grants and
|
||||
scans the bindings on **every** open and forms one verdict at the end; and
|
||||
it logs nothing on any branch, because `klog_read` is ungated (a line
|
||||
written on one branch is a line the refused caller can read) and a serial
|
||||
line is milliseconds it could time. The operator's diagnosis is the pair the
|
||||
namespace publishes anyway: `readdir /protocol` for what is bound, the
|
||||
manifest for who may reach it.*
|
||||
- *The fixture is `protocol-denied-test`, and its scenario boots the **input
|
||||
service** so the forbidden name is genuinely bound — the fixture reads the
|
||||
namespace listing to prove it before asking for it. Without a live provider
|
||||
the case would be comparing two boot races and asserting nothing.*
|
||||
- *Two channels stay open by design, named rather than papered over: `readdir`
|
||||
over `/protocol` lists every bound name to anyone (deliberate — the tree is
|
||||
diagnosable), and `/system/configuration/protocol.csv` is world-readable on
|
||||
the `/system` mount. Stage one hides neither the set of contracts nor the
|
||||
policy; what it removes is the **oracle in the reply**, which is what stage
|
||||
two's parked and faked opens depend on.*
|
||||
|
||||
## P4a — clean protocols onto Define
|
||||
|
||||
vfs, block, display, scanout, input — the modules whose shapes map
|
||||
|
||||
@@ -12,10 +12,15 @@ pub fn build(b: *std.Build) void {
|
||||
|
||||
const ipc = kernel.module("ipc");
|
||||
const time = kernel.module("time");
|
||||
// Every client reaches its service by name now: resolve `/protocol/<name>`,
|
||||
// open it, and take the provider's endpoint out of the reply
|
||||
// (docs/os-development/protocol-namespace.md).
|
||||
const channel = kernel.module("channel");
|
||||
|
||||
_ = b.addModule("display-client", .{
|
||||
.root_source_file = b.path("display/display-client.zig"),
|
||||
.imports = &.{
|
||||
.{ .name = "channel", .module = channel },
|
||||
.{ .name = "ipc", .module = ipc },
|
||||
.{ .name = "time", .module = time },
|
||||
.{ .name = "display-protocol", .module = protocol.module("display-protocol") },
|
||||
@@ -24,6 +29,7 @@ pub fn build(b: *std.Build) void {
|
||||
_ = b.addModule("input-client", .{
|
||||
.root_source_file = b.path("input/input-client.zig"),
|
||||
.imports = &.{
|
||||
.{ .name = "channel", .module = channel },
|
||||
.{ .name = "ipc", .module = ipc },
|
||||
.{ .name = "time", .module = time },
|
||||
.{ .name = "input-protocol", .module = protocol.module("input-protocol") },
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
//! User-space display client: talk to the display service (query the mode, and — from D3
|
||||
//! — create layers, draw, and present) without hand-rolling the IPC. The `runtime.block`
|
||||
//! shape: a cached `.display` lookup with a boot-race retry, then extern-struct request/
|
||||
//! shape: a cached `/protocol/display` open with a boot-race retry, then extern-struct request/
|
||||
//! reply marshalling. See system/services/display/ and docs/display.md.
|
||||
|
||||
const std = @import("std");
|
||||
const channel = @import("channel");
|
||||
const ipc = @import("ipc");
|
||||
const time = @import("time");
|
||||
const display_protocol = @import("display-protocol");
|
||||
@@ -19,13 +20,13 @@ pub const Info = struct {
|
||||
/// The service endpoint, looked up once and cached.
|
||||
var handle: ?ipc.Handle = null;
|
||||
|
||||
/// Look up the display service, retrying while it comes up (a client races its
|
||||
/// registration at boot). Returns the endpoint, or null if it never appears.
|
||||
/// Open `/protocol/display`, retrying while it comes up (a client races the
|
||||
/// service's bind at boot). Returns the endpoint, or null if it never appears.
|
||||
fn service() ?ipc.Handle {
|
||||
if (handle) |h| return h;
|
||||
var attempts: usize = 0;
|
||||
while (attempts < 100) : (attempts += 1) {
|
||||
if (ipc.lookup(.display)) |h| {
|
||||
if (channel.openEndpoint("display")) |h| {
|
||||
handle = h;
|
||||
return h;
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
//! }
|
||||
|
||||
const std = @import("std");
|
||||
const abi = @import("abi");
|
||||
const channel = @import("channel");
|
||||
const ipc = @import("ipc");
|
||||
const time = @import("time");
|
||||
const input_protocol = @import("input-protocol");
|
||||
@@ -44,13 +44,13 @@ pub const device_mouse = input_protocol.device_mouse;
|
||||
pub const device_joystick = input_protocol.device_joystick;
|
||||
pub const device_all = input_protocol.device_all;
|
||||
|
||||
/// Look up the input service, retrying while it is still coming up. Both a subscriber and
|
||||
/// a source race the service's registration at boot, so both wait for it here rather than
|
||||
/// failing. Returns the service endpoint handle, or null if it never appears.
|
||||
/// Open `/protocol/input`, retrying while it is still coming up. Both a subscriber and
|
||||
/// a source race the service's bind at boot, so both wait for it here rather than
|
||||
/// failing. Returns the provider's endpoint handle, or null if it never appears.
|
||||
fn lookupService() ?ipc.Handle {
|
||||
var attempts: usize = 0;
|
||||
while (attempts < 100) : (attempts += 1) {
|
||||
if (ipc.lookup(.input)) |handle| return handle;
|
||||
if (channel.openEndpoint("input")) |handle| return handle;
|
||||
time.sleepMillis(50);
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! The "csv" library domain: shared CSV helpers (comment stripping, field
|
||||
//! iteration) for the /etc/*.csv config files — the device registry and the
|
||||
//! iteration) for the /system/configuration/*.csv config files — the device registry and the
|
||||
//! init service list both parse them.
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
//! Minimal CSV helpers shared by the `/etc/*.csv` config files — the device
|
||||
//! registry (`/etc/devices.csv`) and the init service list (`/etc/init.csv`).
|
||||
//! Minimal CSV helpers shared by the `/system/configuration/*.csv` config files — the device
|
||||
//! registry (`/system/configuration/devices.csv`) and the init service list (`/system/configuration/init.csv`).
|
||||
//! Freestanding, no allocator: returned fields are slices into the source line,
|
||||
//! so the source must outlive them. `#` starts a comment (whole-line or trailing);
|
||||
//! whitespace around a field is trimmed, so columns may be padded for alignment.
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
//! limit — the same handoff usb-storage uses toward the controller.
|
||||
|
||||
const std = @import("std");
|
||||
const channel = @import("channel");
|
||||
const ipc = @import("ipc");
|
||||
const time = @import("time");
|
||||
const block_protocol = @import("block-protocol");
|
||||
@@ -66,14 +67,14 @@ pub const Device = struct {
|
||||
}
|
||||
};
|
||||
|
||||
/// One lookup attempt, no waiting — for a server that retries on its own
|
||||
/// 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 (ipc.lookup(.block)) |handle| return .{ .endpoint = handle };
|
||||
if (channel.openEndpoint("block")) |handle| return .{ .endpoint = handle };
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Look up the block device, retrying generously while the USB storage chain
|
||||
/// 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
|
||||
@@ -84,7 +85,7 @@ pub fn open() ?Device {
|
||||
// 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 (ipc.lookup(.block)) |handle| return .{ .endpoint = handle };
|
||||
if (channel.openEndpoint("block")) |handle| return .{ .endpoint = handle };
|
||||
time.sleepMillis(50);
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -14,6 +14,10 @@ pub fn build(b: *std.Build) void {
|
||||
const system_call = kernel.module("system-call");
|
||||
const ipc = kernel.module("ipc");
|
||||
const time = kernel.module("time");
|
||||
// A driver finds the bus it attaches to by name — `/protocol/device-manager`,
|
||||
// `/protocol/usb-transfer`, `/protocol/block`
|
||||
// (docs/os-development/protocol-namespace.md).
|
||||
const channel = kernel.module("channel");
|
||||
|
||||
// The devices sub-project's public interface (the flat wire types),
|
||||
// importable by user space, unlike the kernel-internal device model it
|
||||
@@ -55,6 +59,7 @@ pub fn build(b: *std.Build) void {
|
||||
.root_source_file = b.path("driver/driver.zig"),
|
||||
.imports = &.{
|
||||
.{ .name = "abi", .module = abi },
|
||||
.{ .name = "channel", .module = channel },
|
||||
.{ .name = "device-abi", .module = device_abi },
|
||||
.{ .name = "system-call", .module = system_call },
|
||||
.{ .name = "ipc", .module = ipc },
|
||||
@@ -81,6 +86,7 @@ pub fn build(b: *std.Build) void {
|
||||
_ = b.addModule("usb", .{
|
||||
.root_source_file = b.path("usb/usb.zig"),
|
||||
.imports = &.{
|
||||
.{ .name = "channel", .module = channel },
|
||||
.{ .name = "ipc", .module = ipc },
|
||||
.{ .name = "time", .module = time },
|
||||
.{ .name = "usb-transfer-protocol", .module = protocol.module("usb-transfer-protocol") },
|
||||
@@ -92,12 +98,13 @@ pub fn build(b: *std.Build) void {
|
||||
_ = b.addModule("block", .{
|
||||
.root_source_file = b.path("block/block.zig"),
|
||||
.imports = &.{
|
||||
.{ .name = "channel", .module = channel },
|
||||
.{ .name = "ipc", .module = ipc },
|
||||
.{ .name = "time", .module = time },
|
||||
.{ .name = "block-protocol", .module = protocol.module("block-protocol") },
|
||||
},
|
||||
});
|
||||
// The device registry: parse /etc/devices.csv into match rules and bind a
|
||||
// The device registry: parse /system/configuration/devices.csv into match rules and bind a
|
||||
// reported device to a driver. Pure logic (no hardware, no syscalls), so it
|
||||
// unit-tests on the host; the device manager imports it.
|
||||
_ = b.addModule("device-registry", .{
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
.kernel = .{ .path = "../kernel" },
|
||||
// driver speaks device-manager-protocol; block/usb their transfer protocols.
|
||||
.protocol = .{ .path = "../protocol" },
|
||||
// device-registry parses /etc/devices.csv with the shared csv helpers.
|
||||
// device-registry parses /system/configuration/devices.csv with the shared csv helpers.
|
||||
.csv = .{ .path = "../csv" },
|
||||
},
|
||||
.paths = .{""},
|
||||
|
||||
@@ -7,6 +7,7 @@ const std = @import("std");
|
||||
const abi = @import("abi");
|
||||
const device_abi = @import("device-abi");
|
||||
const sc = @import("system-call");
|
||||
const channel = @import("channel");
|
||||
const ipc = @import("ipc");
|
||||
const time = @import("time");
|
||||
const device_manager_protocol = @import("device-manager-protocol");
|
||||
@@ -170,7 +171,7 @@ const lookup_pause_ms: u64 = 20;
|
||||
pub fn hello(role: Role, device_id: u64) ?ipc.Handle {
|
||||
var attempts: u32 = 0;
|
||||
const manager = while (attempts < lookup_attempts) : (attempts += 1) {
|
||||
if (ipc.lookup(.device_manager)) |handle| break handle;
|
||||
if (channel.openEndpoint("device-manager")) |handle| break handle;
|
||||
time.sleepMillis(lookup_pause_ms);
|
||||
} else {
|
||||
std.log.info("no device manager to hello", .{});
|
||||
|
||||
@@ -126,7 +126,7 @@ pub const DeviceDescriptor = extern struct {
|
||||
// names with the pci-class module.
|
||||
pci_class: u64,
|
||||
// Numeric identity beyond the class triple, mirrored in the bus report's
|
||||
// ChildAdded so /etc/devices.csv can bind on it: `vendor`/`device` are the PCI
|
||||
// ChildAdded so /system/configuration/devices.csv can bind on it: `vendor`/`device` are the PCI
|
||||
// vendor/device (or USB idVendor/idProduct), `subsystem` is the PCI subsystem id
|
||||
// packed `(subsystem_vendor << 16) | subsystem_device`. Zero where the bus has no
|
||||
// such concept. Defaulted so existing descriptor literals keep compiling and lay
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! The device registry: parse `/etc/devices.csv` into match rules and bind a
|
||||
//! The device registry: parse `/system/configuration/devices.csv` into match rules and bind a
|
||||
//! reported device to a driver. This is the data-driven replacement for the
|
||||
//! device manager's three hand-written `switch` tables (`pciDriverForIdentity`,
|
||||
//! `hidDriverFor`, `usbDriverForIdentity`); the registry is now **authoritative**
|
||||
@@ -11,7 +11,7 @@
|
||||
//! That keeps this module freestanding and unit-testable with plain `zig test`.
|
||||
//!
|
||||
//! The file format (docs/device-driver-development/device-manager.md, and the
|
||||
//! `/etc/devices.csv` header itself): one rule per line, nine comma-separated
|
||||
//! `/system/configuration/devices.csv` header itself): one rule per line, nine comma-separated
|
||||
//! fields, `#` starts a comment (whole-line or trailing), blank lines ignored.
|
||||
//!
|
||||
//! bus, base, class, prog_if, vendor, device, subsystem, hid, driver
|
||||
@@ -226,7 +226,7 @@ fn parseLine(line: []const u8) Line {
|
||||
} };
|
||||
}
|
||||
|
||||
/// Parse a whole `/etc/devices.csv` into `out_rules`. The string fields of the
|
||||
/// Parse a whole `/system/configuration/devices.csv` into `out_rules`. The string fields of the
|
||||
/// returned rules point into `source`, which must outlive them.
|
||||
pub fn parse(source: []const u8, out_rules: []Rule) ParseResult {
|
||||
var result: ParseResult = .{ .count = 0, .malformed = 0, .truncated = false };
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
//! the service harness drops buffered-message payloads — see service.zig).
|
||||
|
||||
const std = @import("std");
|
||||
const channel = @import("channel");
|
||||
const ipc = @import("ipc");
|
||||
const time = @import("time");
|
||||
const usb_transfer_protocol = @import("usb-transfer-protocol");
|
||||
@@ -130,13 +131,15 @@ pub const Device = struct {
|
||||
}
|
||||
};
|
||||
|
||||
/// Look up the USB bus and 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).
|
||||
/// 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 (ipc.lookup(.usb_bus)) |handle| break handle;
|
||||
if (channel.openEndpoint("usb-transfer")) |handle| break handle;
|
||||
time.sleepMillis(20);
|
||||
} else return null;
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ pub fn build(b: *std.Build) void {
|
||||
.{ .name = "time", .module = time },
|
||||
},
|
||||
});
|
||||
_ = b.addModule("file-system", .{
|
||||
const file_system = b.addModule("file-system", .{
|
||||
.root_source_file = b.path("file-system.zig"),
|
||||
.imports = &.{
|
||||
.{ .name = "abi", .module = abi },
|
||||
@@ -61,6 +61,20 @@ pub fn build(b: *std.Build) void {
|
||||
.{ .name = "vfs-protocol", .module = protocol.module("vfs-protocol") },
|
||||
},
|
||||
});
|
||||
// The channel is the L1 concept made concrete (docs/os-development/communication.md):
|
||||
// it needs the namespace (file-system, to resolve a /protocol name) and the
|
||||
// transport (ipc) both, which is why it lives here rather than in a protocol
|
||||
// module — those import nothing.
|
||||
const channel = b.addModule("channel", .{
|
||||
.root_source_file = b.path("channel.zig"),
|
||||
.imports = &.{
|
||||
.{ .name = "ipc", .module = ipc },
|
||||
.{ .name = "time", .module = time },
|
||||
.{ .name = "file-system", .module = file_system },
|
||||
.{ .name = "vfs-protocol", .module = protocol.module("vfs-protocol") },
|
||||
.{ .name = "envelope", .module = protocol.module("envelope") },
|
||||
},
|
||||
});
|
||||
_ = b.addModule("memory", .{
|
||||
.root_source_file = b.path("memory/memory.zig"),
|
||||
.imports = &.{
|
||||
@@ -70,10 +84,13 @@ pub fn build(b: *std.Build) void {
|
||||
.{ .name = "thread", .module = thread },
|
||||
},
|
||||
});
|
||||
// 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).
|
||||
_ = b.addModule("service", .{
|
||||
.root_source_file = b.path("service.zig"),
|
||||
.imports = &.{
|
||||
.{ .name = "abi", .module = abi },
|
||||
.{ .name = "channel", .module = channel },
|
||||
.{ .name = "ipc", .module = ipc },
|
||||
.{ .name = "process", .module = process },
|
||||
},
|
||||
@@ -101,4 +118,22 @@ pub fn build(b: *std.Build) void {
|
||||
});
|
||||
test_step.dependOn(&b.addRunArtifact(kernel_tests).step);
|
||||
}
|
||||
|
||||
// channel needs its whole import set to compile at all; only its framing is
|
||||
// host-runnable (the syscall seams are x86_64-only, and unreferenced from
|
||||
// the tests), so that is what it tests.
|
||||
const channel_tests = b.addTest(.{
|
||||
.root_module = b.createModule(.{
|
||||
.root_source_file = b.path("channel.zig"),
|
||||
.target = b.resolveTargetQuery(.{}),
|
||||
.imports = &.{
|
||||
.{ .name = "ipc", .module = ipc },
|
||||
.{ .name = "time", .module = time },
|
||||
.{ .name = "file-system", .module = file_system },
|
||||
.{ .name = "vfs-protocol", .module = protocol.module("vfs-protocol") },
|
||||
.{ .name = "envelope", .module = protocol.module("envelope") },
|
||||
},
|
||||
}),
|
||||
});
|
||||
test_step.dependOn(&b.addRunArtifact(channel_tests).step);
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
//! `Channel` — layer L1 of the communication stack
|
||||
//! (docs/os-development/communication.md) made concrete. A program holds a
|
||||
//! channel that speaks a protocol; it does not hold a raw handle and marshal
|
||||
//! bytes at one. The channel is the answer to "who am I talking to", decided
|
||||
//! once at establishment, so nothing after that ever routes a party again:
|
||||
//! every packet's `target` addresses an *object* within the peer already chosen.
|
||||
//!
|
||||
//! **Possession of the Channel is the connection.** There is no connect step, no
|
||||
//! session id, no reconnect handshake — the endpoint capability inside is the
|
||||
//! whole of the relationship, and it cannot be forged, only handed over. Which
|
||||
//! also means a channel is a resource: `close` it, or it occupies a handle-table
|
||||
//! slot for the life of the process.
|
||||
//!
|
||||
//! **A dead provider surfaces as `-EPEER`, and the recovery is to re-open.**
|
||||
//! When the process on the other end exits, the kernel fails calls on its
|
||||
//! endpoint rather than blocking forever; `call` returns null. The client does
|
||||
//! not repair the channel — it discards it and opens the name again, which
|
||||
//! reaches whatever instance the registry now points at. The restart story
|
||||
//! falls out of the naming layer for free; no protocol needs a reconnect verb.
|
||||
//!
|
||||
//! `open` resolves a `/protocol/<name>` path through the kernel VFS router and
|
||||
//! takes the provider's endpoint from the open reply's capability. The registry
|
||||
//! answering it is init, PID 1, which mounts `/protocol` before it spawns anyone
|
||||
//! (docs/os-development/protocol-namespace.md); `bind` below is the other half —
|
||||
//! how a provider claims the name in the first place.
|
||||
|
||||
const std = @import("std");
|
||||
const ipc = @import("ipc");
|
||||
const time = @import("time");
|
||||
const file_system = @import("file-system");
|
||||
const vfs_protocol = @import("vfs-protocol");
|
||||
const envelope = @import("envelope");
|
||||
|
||||
/// Longest `/protocol/...` path this client marshals. The registry's names are
|
||||
/// short by construction (a contract leaf, not a file path), and the buffer is
|
||||
/// on the stack of whoever opens.
|
||||
pub const path_maximum: usize = 224;
|
||||
|
||||
/// Where the protocol namespace is rooted — the one path prefix in the system
|
||||
/// that names contracts rather than files. Spelled once, here, so no caller
|
||||
/// builds it by hand (docs/file-system-development/file-system-hierarchy.md).
|
||||
pub const root: []const u8 = "/protocol";
|
||||
|
||||
/// Longest contract name — the part after `/protocol/`. Short by construction:
|
||||
/// a leaf like `display`, or a subtree leaf like `test/shared-memory`.
|
||||
pub const name_maximum: usize = 64;
|
||||
|
||||
/// What a `call` came back with: the provider's status, the reply payload (the
|
||||
/// bytes after the `Status`, in the caller's own buffer), and any capability the
|
||||
/// reply carried.
|
||||
pub const Response = struct {
|
||||
status: envelope.Status,
|
||||
payload: []u8,
|
||||
capability: ?ipc.Handle,
|
||||
|
||||
/// Whether the provider answered success. A negative status is its refusal
|
||||
/// (`-ENOSYS` for a verb it does not implement, and so on).
|
||||
pub fn succeeded(self: Response) bool {
|
||||
return self.status.status == 0;
|
||||
}
|
||||
};
|
||||
|
||||
/// An open conversation with one provider, speaking one protocol.
|
||||
pub const Channel = struct {
|
||||
/// The provider's endpoint. Sending into it is the only thing this handle
|
||||
/// can do — an endpoint is a mailbox owned by its creator, and that
|
||||
/// direction never reverses.
|
||||
endpoint: ipc.Handle,
|
||||
|
||||
/// Adopt an endpoint that arrived some other way — a capability delivered
|
||||
/// in a reply, or one a supervisor wired in at spawn time (P5). The channel
|
||||
/// takes ownership of the handle.
|
||||
pub fn adopt(endpoint: ipc.Handle) Channel {
|
||||
return .{ .endpoint = endpoint };
|
||||
}
|
||||
|
||||
/// Establish a channel by name: resolve `/protocol/<name>` to the registry
|
||||
/// backend, `open` the contract there, and take the provider's endpoint from
|
||||
/// the reply's capability. Null if the path does not resolve, the registry
|
||||
/// refuses (an ungranted name is refused *as* not-found), or the reply
|
||||
/// carries no capability.
|
||||
///
|
||||
/// The path is spoken exactly once, here. Everything afterwards is integers
|
||||
/// in the packet header.
|
||||
pub fn open(path: []const u8) ?Channel {
|
||||
return .{ .endpoint = openPath(path) orelse return null };
|
||||
}
|
||||
|
||||
/// Establish a channel by contract name — `open` with `/protocol/` supplied,
|
||||
/// which is how every caller in the system spells it.
|
||||
pub fn connect(name: []const u8) ?Channel {
|
||||
return .{ .endpoint = openEndpoint(name) orelse return null };
|
||||
}
|
||||
|
||||
/// Send one request packet and block for the reply: `[Header][request]` out,
|
||||
/// `[Status][reply]` back. `request` is the bytes *after* the header — the
|
||||
/// protocol's fixed part plus any tail — because the header is this call's
|
||||
/// to lay down. The reply's payload lands in `into`.
|
||||
///
|
||||
/// Null means the transport failed, which today means one of: a dead
|
||||
/// provider (`-EPEER` — discard this channel and `open` the name again), an
|
||||
/// oversized packet, or a bad handle. A provider that answered *and refused*
|
||||
/// is not a failure here: it comes back with a negative `Response.status`.
|
||||
pub fn call(self: Channel, header: envelope.Header, request: []const u8, into: []u8) ?Response {
|
||||
return self.callCapability(header, request, into, null);
|
||||
}
|
||||
|
||||
/// As `call`, handing the provider a capability with the request — the only
|
||||
/// direction-crossing move kernel-ipc offers, and how `subscribe` delivers
|
||||
/// the subscriber's own endpoint.
|
||||
pub fn callCapability(
|
||||
self: Channel,
|
||||
header: envelope.Header,
|
||||
request: []const u8,
|
||||
into: []u8,
|
||||
capability: ?ipc.Handle,
|
||||
) ?Response {
|
||||
var packet: [envelope.packet_maximum]u8 = undefined;
|
||||
const framed = frame(header, request, &packet) orelse return null;
|
||||
|
||||
var reply: [envelope.packet_maximum]u8 = undefined;
|
||||
const answer = ipc.callCap(self.endpoint, framed, &reply, capability) catch return null;
|
||||
const status = envelope.statusOf(reply[0..answer.len]) orelse return null;
|
||||
const available = @min(answer.len - envelope.prefix_size, @as(usize, status.len));
|
||||
const taken = @min(available, into.len);
|
||||
@memcpy(into[0..taken], reply[envelope.prefix_size..][0..taken]);
|
||||
return .{ .status = status, .payload = into[0..taken], .capability = answer.cap };
|
||||
}
|
||||
|
||||
/// Push one event packet and return immediately — no reply owed, and a slow
|
||||
/// or dead peer can never stall the sender. Bounded by `post_maximum`: an
|
||||
/// event that does not fit is refused here rather than split, because a
|
||||
/// packet is never fragmented.
|
||||
pub fn send(self: Channel, header: envelope.Header, payload: []const u8) bool {
|
||||
var packet: [envelope.post_maximum]u8 = undefined;
|
||||
const framed = frame(header, payload, &packet) orelse return false;
|
||||
return ipc.send(self.endpoint, framed);
|
||||
}
|
||||
|
||||
/// Ask the provider what it is: the reserved `describe` verb, answered by
|
||||
/// every protocol built through `envelope.Define`. The name and version come
|
||||
/// back in `into`, which the returned `Described` borrows.
|
||||
pub fn describe(self: Channel, into: []u8) ?envelope.Described {
|
||||
var request: [envelope.packet_maximum]u8 = undefined;
|
||||
const packet = envelope.encodeDescribe(&request) orelse return null;
|
||||
|
||||
var reply: [envelope.packet_maximum]u8 = undefined;
|
||||
const answer = ipc.callCap(self.endpoint, packet, &reply, null) catch return null;
|
||||
const taken = @min(answer.len, into.len);
|
||||
@memcpy(into[0..taken], reply[0..taken]);
|
||||
return envelope.decodeDescribe(into[0..taken]);
|
||||
}
|
||||
|
||||
/// Drop the provider's endpoint and free the handle-table slot. The
|
||||
/// conversation is over the moment the capability is gone — there is nothing
|
||||
/// else holding it open.
|
||||
pub fn close(self: Channel) void {
|
||||
_ = ipc.close(self.endpoint);
|
||||
}
|
||||
};
|
||||
|
||||
// --- the namespace: resolving, opening, and claiming a contract name ---------
|
||||
|
||||
/// Where a `/protocol/...` path routed: the registry's endpoint, plus the path
|
||||
/// rewritten mount-relative (`/display` for `/protocol/display`). The handle is
|
||||
/// deduplicated by the kernel across resolves and shared with every other user
|
||||
/// of that mount, so it is never ours to close.
|
||||
const Registry = struct {
|
||||
handle: ipc.Handle,
|
||||
relative: [path_maximum]u8,
|
||||
relative_len: usize,
|
||||
|
||||
fn path(self: *const Registry) []const u8 {
|
||||
return self.relative[0..self.relative_len];
|
||||
}
|
||||
};
|
||||
|
||||
/// Route `path` to whatever backend serves it. Null when nothing is mounted
|
||||
/// there — under `/protocol` that means the registry is not up yet, which is a
|
||||
/// *retry*, not a refusal. A kernel-served route (the read-only `/system` tree)
|
||||
/// is the wrong path, not a channel, and is refused here.
|
||||
fn reach(path: []const u8) ?Registry {
|
||||
var out: Registry = .{ .handle = 0, .relative = undefined, .relative_len = 0 };
|
||||
const route = file_system.fsResolve(path, 0, &out.relative) orelse return null;
|
||||
switch (route) {
|
||||
.kernel => return null,
|
||||
.backend => |b| {
|
||||
out.handle = b.handle;
|
||||
out.relative_len = b.path_len;
|
||||
return out;
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// One vfs-protocol round trip at a backend: fixed header, inline payload, and
|
||||
/// an optional capability in each direction.
|
||||
fn transact(
|
||||
handle: ipc.Handle,
|
||||
operation: vfs_protocol.Operation,
|
||||
payload: []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);
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
/// 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;
|
||||
// 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;
|
||||
}
|
||||
|
||||
/// The provider's raw endpoint behind `/protocol/<name>`. The transitional form,
|
||||
/// for the clients that still marshal their protocol's bytes by hand; P4 moves
|
||||
/// them onto `Channel` proper and this shrinks back to `connect`.
|
||||
///
|
||||
/// Null covers both "no such contract" and "you may not have it" — deliberately
|
||||
/// the same answer (protocol-namespace.md: enforcement is absence), and also
|
||||
/// "the registry is not mounted yet", which is why every caller retries.
|
||||
pub fn openEndpoint(name: []const u8) ?ipc.Handle {
|
||||
var path: [path_maximum]u8 = undefined;
|
||||
const full = join(name, &path) orelse return null;
|
||||
return openPath(full);
|
||||
}
|
||||
|
||||
/// Claim `/protocol/<name>` for `endpoint`: the registry records the name
|
||||
/// against this process and hands the endpoint to whoever opens it afterwards.
|
||||
/// The endpoint rides the call as its capability, the one direction-crossing
|
||||
/// move kernel-ipc offers.
|
||||
///
|
||||
/// Three-valued on purpose. **Null** is "the registry could not be reached" —
|
||||
/// it is not mounted yet, which happens when a provider starts before init has
|
||||
/// finished coming up, and the answer is to retry. A **value** is the registry's
|
||||
/// verdict and is final: 0 bound, `-EPERM` this binary is not granted that name,
|
||||
/// `-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;
|
||||
}
|
||||
|
||||
/// How long a provider keeps offering itself before giving up. The registry is
|
||||
/// init, which mounts `/protocol` before it spawns anyone, so in a normal boot
|
||||
/// the first try lands; a provider the kernel test harness starts may well beat
|
||||
/// init to the mount, which is what the patience is for. Four seconds of 20 ms
|
||||
/// tries — the same cadence every client in the tree spends finding a service.
|
||||
const bind_attempts: u32 = 200;
|
||||
const bind_retry_ms: u64 = 20;
|
||||
|
||||
/// `bind`, waiting out a registry that is not mounted yet. Only unreachability
|
||||
/// is retried: a registry that *answered* has decided, and asking again cannot
|
||||
/// change its mind. True when the name is ours.
|
||||
pub fn bindPatiently(name: []const u8, endpoint: ipc.Handle) bool {
|
||||
var attempt: u32 = 0;
|
||||
while (attempt < bind_attempts) : (attempt += 1) {
|
||||
if (bind(name, endpoint)) |status| return status == 0;
|
||||
time.sleepMillis(bind_retry_ms);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// `/protocol/` + `name`, in the caller's buffer. Null if the name is empty or
|
||||
/// longer than the namespace admits.
|
||||
fn join(name: []const u8, buffer: []u8) ?[]u8 {
|
||||
if (name.len == 0 or name.len > name_maximum) return null;
|
||||
const total = root.len + 1 + name.len;
|
||||
if (total > buffer.len) return null;
|
||||
@memcpy(buffer[0..root.len], root);
|
||||
buffer[root.len] = '/';
|
||||
@memcpy(buffer[root.len + 1 ..][0..name.len], name);
|
||||
return buffer[0..total];
|
||||
}
|
||||
|
||||
/// Lay a packet down: the folded header first, then the protocol's bytes. Null
|
||||
/// when it would not fit the buffer — the same rule as `envelope`'s framing,
|
||||
/// applied where the buffer is the transport's, not the protocol's.
|
||||
fn frame(header: envelope.Header, body: []const u8, buffer: []u8) ?[]u8 {
|
||||
const total = envelope.prefix_size + body.len;
|
||||
if (total > buffer.len) return null;
|
||||
@memcpy(buffer[0..envelope.prefix_size], std.mem.asBytes(&header));
|
||||
@memcpy(buffer[envelope.prefix_size..][0..body.len], body);
|
||||
return buffer[0..total];
|
||||
}
|
||||
|
||||
// --- tests ------------------------------------------------------------------
|
||||
//
|
||||
// The syscall half cannot run on the host, and there is no registry to reach
|
||||
// until P2 — so what is testable here is the framing, which is the part with
|
||||
// arithmetic in it.
|
||||
|
||||
const testing = std.testing;
|
||||
|
||||
test "a framed packet is the header followed by the protocol's bytes" {
|
||||
var buffer: [envelope.packet_maximum]u8 = undefined;
|
||||
const header = envelope.Header{ .operation = envelope.first_protocol_operation, .target = 9 };
|
||||
const packet = frame(header, "body", &buffer).?;
|
||||
|
||||
try testing.expectEqual(envelope.prefix_size + "body".len, packet.len);
|
||||
const decoded = envelope.headerOf(packet).?;
|
||||
try testing.expectEqual(envelope.first_protocol_operation, decoded.operation);
|
||||
try testing.expectEqual(@as(u64, 9), decoded.target);
|
||||
try testing.expectEqualStrings("body", packet[envelope.prefix_size..]);
|
||||
}
|
||||
|
||||
test "a contract name joins the namespace root exactly once" {
|
||||
var buffer: [path_maximum]u8 = undefined;
|
||||
try testing.expectEqualStrings("/protocol/display", join("display", &buffer).?);
|
||||
try testing.expectEqualStrings("/protocol/test/shared-memory", join("test/shared-memory", &buffer).?);
|
||||
try testing.expect(join("", &buffer) == null);
|
||||
try testing.expect(join("x" ** (name_maximum + 1), &buffer) == null);
|
||||
}
|
||||
|
||||
test "framing refuses a packet that would not fit rather than truncating it" {
|
||||
var post: [envelope.post_maximum]u8 = undefined;
|
||||
const header = envelope.Header{ .operation = envelope.first_protocol_operation };
|
||||
const body = [_]u8{0} ** (envelope.post_maximum - envelope.prefix_size);
|
||||
const one_too_many = body ++ [_]u8{0};
|
||||
|
||||
try testing.expect(frame(header, &body, &post) != null);
|
||||
try testing.expect(frame(header, &one_too_many, &post) == null);
|
||||
}
|
||||
@@ -39,6 +39,7 @@ fn kindFromWire(value: u32) Kind {
|
||||
@intFromEnum(Kind.symbolic_link) => .symbolic_link,
|
||||
@intFromEnum(Kind.fifo) => .fifo,
|
||||
@intFromEnum(Kind.socket) => .socket,
|
||||
@intFromEnum(Kind.protocol) => .protocol,
|
||||
else => .regular,
|
||||
};
|
||||
}
|
||||
@@ -305,7 +306,7 @@ pub fn makePath(path: []const u8) bool {
|
||||
while (end < path.len and path[end] != '/') end += 1;
|
||||
const prefix = path[0..end];
|
||||
if (prefix.len == 0 or (prefix.len == 1 and prefix[0] == '/')) continue;
|
||||
// Best-effort per prefix: components at or above a mount point ("/mnt")
|
||||
// Best-effort per prefix: components at or above a mount point ("/volumes")
|
||||
// are router names, not filesystem nodes — they neither exist as nodes
|
||||
// nor accept mkdir, and that is fine. Only the final verdict counts.
|
||||
if (!exists(prefix)) _ = makeDirectory(prefix);
|
||||
@@ -348,8 +349,9 @@ pub fn mount(target: []const u8, backend: ipc.Handle) bool {
|
||||
}
|
||||
|
||||
/// As `mount`, with a backend-side rewrite prefix: a path under `target` reaches
|
||||
/// the backend as `rewrite` + the mount-relative tail. How one volume serves two
|
||||
/// mounts ("/mnt/usb" from its root, "/var" from its /var subtree).
|
||||
/// the backend as `rewrite` + the mount-relative tail. How one volume serves
|
||||
/// several mounts ("/volumes/usb" from its root, "/system/logs" from its
|
||||
/// /system/logs subtree).
|
||||
pub fn mountRewritten(target: []const u8, backend: ipc.Handle, rewrite: []const u8) bool {
|
||||
return fsMount(target, backend, rewrite);
|
||||
}
|
||||
|
||||
+54
-11
@@ -29,10 +29,10 @@ pub fn createIpcEndpoint() ?Handle {
|
||||
return if (failed(r)) null else r;
|
||||
}
|
||||
|
||||
/// Publish endpoint `h` under a well-known service id so other processes find it.
|
||||
pub fn register(id: abi.ServiceId, h: Handle) bool {
|
||||
return !failed(sc.systemCall2(.ipc_register, @intFromEnum(id), h));
|
||||
}
|
||||
// `register`/`lookup` lived here — the two wrappers over the flat ServiceId
|
||||
// registry. Naming is not a system call any more: a provider binds its contract
|
||||
// name at the registry and a client resolves and opens `/protocol/<name>`, both
|
||||
// through `channel` (docs/os-development/protocol-namespace.md).
|
||||
|
||||
/// Drop a capability handle (endpoint, shared-memory, or DMA-region) and free its table
|
||||
/// slot. A forwarding hop closes a cap it passed on; a binder closes a DMA-region cap
|
||||
@@ -42,13 +42,6 @@ pub fn close(h: Handle) bool {
|
||||
return !failed(sc.systemCall1(.handle_close, h));
|
||||
}
|
||||
|
||||
/// Find the endpoint published under `id`, installing a handle to it in this
|
||||
/// process.
|
||||
pub fn lookup(id: abi.ServiceId) ?Handle {
|
||||
const r = sc.systemCall1(.ipc_lookup, @intFromEnum(id));
|
||||
return if (failed(r)) null else r;
|
||||
}
|
||||
|
||||
pub const CallError = error{Failed};
|
||||
|
||||
/// The result of a capability-passing `callCap`: the reply length, and the handle of
|
||||
@@ -178,6 +171,56 @@ pub const Received = struct {
|
||||
}
|
||||
};
|
||||
|
||||
/// A capability that arrived with one turn of a receive loop, and the ownership
|
||||
/// rule for it: **the turn owns it until a handler takes it, and closes whatever
|
||||
/// is left.**
|
||||
///
|
||||
/// The kernel installs a sent capability in the receiver's handle table whenever
|
||||
/// the caller attached one, *independent of the message's length or kind*
|
||||
/// (system/kernel/ipc-synchronous.zig `replyWait`), so every path out of a loop
|
||||
/// has to dispose of one — including the paths that never look at the message.
|
||||
/// The table is thirty-two slots, and `ipc_call` does not dedupe, so a client
|
||||
/// looping on `callCap(server, &.{}, endpoint)` spends one slot per call: about
|
||||
/// thirty-two zero-length pings and the service can never accept another
|
||||
/// capability, which means no subscribe and no shared-memory handover, for the
|
||||
/// rest of the boot. It is unauthenticated and it is two lines to write.
|
||||
///
|
||||
/// So ownership is structural rather than a close per branch — the per-branch
|
||||
/// version has already failed twice in this tree, in PID 1's ping path and in
|
||||
/// every `service.run` callback that simply ignored its capability argument.
|
||||
/// Written this way, forgetting **closes**, and *keeping* a capability is the
|
||||
/// thing a handler has to say out loud:
|
||||
///
|
||||
/// ```zig
|
||||
/// var arrived: ipc.Arrival = .{ .handle = got.cap };
|
||||
/// defer arrived.release(); // every exit path, including `continue`
|
||||
/// ...
|
||||
/// const kept = arrived.take().?; // claimed: mine to hold or close
|
||||
/// ```
|
||||
pub const Arrival = struct {
|
||||
handle: ?Handle = null,
|
||||
|
||||
/// Look without claiming — a handler that may still refuse wants no close of
|
||||
/// its own on the refusal paths.
|
||||
pub fn peek(self: *const Arrival) ?Handle {
|
||||
return self.handle;
|
||||
}
|
||||
|
||||
/// Claim ownership: from here the capability is the taker's to keep or close,
|
||||
/// and the turn will not touch it.
|
||||
pub fn take(self: *Arrival) ?Handle {
|
||||
defer self.handle = null;
|
||||
return self.handle;
|
||||
}
|
||||
|
||||
/// Close whatever nobody claimed. Idempotent, so it is safe as a `defer` next
|
||||
/// to any number of `take`s.
|
||||
pub fn release(self: *Arrival) void {
|
||||
if (self.handle) |handle| _ = close(handle);
|
||||
self.handle = null;
|
||||
}
|
||||
};
|
||||
|
||||
/// Server side of IPC_ReplyWait: deliver `reply` to the client last received (if any,
|
||||
/// optionally handing it `send_cap`), then block until the next request arrives in
|
||||
/// `receive`. Returns its length, the sender badge, and any capability the request
|
||||
|
||||
@@ -142,6 +142,18 @@ pub fn subscribeExits(endpoint: usize) bool {
|
||||
/// snapshot buffer without importing `abi` itself.
|
||||
pub const ProcessDescriptor = abi.ProcessDescriptor;
|
||||
|
||||
/// The calling task's own kernel id — its row in the process table, and the value
|
||||
/// every other process sees as this one's `supervisor` after it spawns them. For a
|
||||
/// single-threaded program that is its process id; in a threaded one it is the
|
||||
/// calling thread's id (`Thread.getCurrentId` is the same system call, named for
|
||||
/// the threading vocabulary). Ids are monotonic and never reused
|
||||
/// (system/kernel/process.zig), which is what makes comparing one an identity
|
||||
/// test where comparing a *name* is only a resemblance test — the registrar in
|
||||
/// init leans on exactly that.
|
||||
pub fn taskId() u32 {
|
||||
return @intCast(sc.systemCall0(.thread_self));
|
||||
}
|
||||
|
||||
/// Give up the rest of this quantum.
|
||||
pub fn yield() void {
|
||||
_ = sc.systemCall0(.yield);
|
||||
|
||||
+50
-16
@@ -6,13 +6,19 @@
|
||||
//! loop chose, never on a hijacked stack — the whole reason signals are
|
||||
//! messages.
|
||||
//!
|
||||
//! One rule a service author does have to know, and it is stated on
|
||||
//! `Callbacks.on_message`: **a capability that arrives belongs to the turn** —
|
||||
//! the loop closes it unless the callback claims it with `take()`. Forgetting is
|
||||
//! therefore safe, and keeping is explicit; the opposite arrangement quietly
|
||||
//! spends a handle-table slot per request.
|
||||
//!
|
||||
//! 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
|
||||
//! service author to implement — a wedged service simply fails to answer, which
|
||||
//! is the diagnosis (see docs/ipc.md).
|
||||
|
||||
const abi = @import("abi");
|
||||
const channel = @import("channel");
|
||||
const ipc = @import("ipc");
|
||||
const process = @import("process");
|
||||
|
||||
@@ -22,10 +28,22 @@ pub const Callbacks = struct {
|
||||
/// Return false to abort startup (the process exits).
|
||||
init: ?*const fn (endpoint: ipc.Handle) bool = null,
|
||||
/// One protocol request from `sender` (a task id): write the reply into
|
||||
/// `reply`, return its length. `capability` is the handle the request
|
||||
/// carried, if any (M13 cap passing — how a subscriber hands over its
|
||||
/// endpoint). The zero-length ping never reaches this.
|
||||
on_message: *const fn (message: []const u8, reply: []u8, sender: u32, capability: ?ipc.Handle) usize,
|
||||
/// `reply`, return its length. The zero-length ping never reaches this.
|
||||
///
|
||||
/// `arrived` is the capability the request carried (M13 cap passing — how a
|
||||
/// subscriber hands over its endpoint), and it comes with **an ownership
|
||||
/// rule: the turn owns it, and a handler that wants to keep it must say so
|
||||
/// with `take()`.** Whatever is left when this returns, the loop closes.
|
||||
/// `peek()` reads it without claiming, which is what a handler that may
|
||||
/// still refuse wants — no close of its own on the refusal paths.
|
||||
///
|
||||
/// The rule is stated here, in the contract, because the alternative has
|
||||
/// failed in practice: an implementation that simply ignored a `?ipc.Handle`
|
||||
/// argument leaked a handle table slot per request, and every operation
|
||||
/// except a subscribe ignores it. Thirty-two such requests — zero-length
|
||||
/// pings will do, and they need no authorization — and the service can never
|
||||
/// accept another capability for the rest of the boot. See `ipc.Arrival`.
|
||||
on_message: *const fn (message: []const u8, reply: []u8, sender: u32, arrived: *ipc.Arrival) usize,
|
||||
/// A notification that is not a signal — a subscribed exit event, a bound
|
||||
/// IRQ, a timer landing. The raw badge; decode with the ipc helpers.
|
||||
on_notification: ?*const fn (badge: u64) void = null,
|
||||
@@ -35,19 +53,25 @@ pub const Callbacks = struct {
|
||||
/// the return itself — never put *necessary* work here (iron rule 1: a kill
|
||||
/// arrives with no warning; this is for graceful extras only).
|
||||
on_terminate: ?*const fn () void = null,
|
||||
/// Publish the endpoint under a well-known service id at startup.
|
||||
service: ?abi.ServiceId = null,
|
||||
/// The contract this service provides: a name under `/protocol`, mirroring
|
||||
/// the `library/protocol/` module that defines the wire format — a program
|
||||
/// imports `display-protocol` and the provider binds `"display"`
|
||||
/// (docs/os-development/protocol-namespace.md). Bound at startup, before
|
||||
/// `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,
|
||||
};
|
||||
|
||||
/// Run the service: create and (optionally) register the endpoint, 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).
|
||||
/// 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).
|
||||
pub fn run(comptime maximum_message: usize, callbacks: Callbacks) void {
|
||||
const endpoint = ipc.createIpcEndpoint() orelse return;
|
||||
if (callbacks.service) |id| {
|
||||
if (!ipc.register(id, endpoint)) return;
|
||||
if (callbacks.service) |name| {
|
||||
if (!channel.bindPatiently(name, endpoint)) return;
|
||||
}
|
||||
_ = process.bindSignals(endpoint);
|
||||
if (callbacks.init) |initialise| {
|
||||
@@ -59,6 +83,16 @@ pub fn run(comptime maximum_message: usize, callbacks: Callbacks) void {
|
||||
var receive: [maximum_message]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 a callback claims it (`ipc.Arrival`). Structural
|
||||
// rather than a close per branch, because the branches are exactly what
|
||||
// gets forgotten: the ping's `continue` below, and every `on_message`
|
||||
// that has no use for a capability — which is every operation but a
|
||||
// subscribe. A `defer` in a loop body runs on `continue` and on the
|
||||
// `return` that ends the loop, so this covers all four exits.
|
||||
var arrived: ipc.Arrival = .{ .handle = got.cap };
|
||||
defer arrived.release();
|
||||
|
||||
if (got.isNotification()) {
|
||||
reply_len = 0; // nothing owed for a notification
|
||||
if (process.signalsFrom(got.badge)) |signals| {
|
||||
@@ -76,8 +110,8 @@ pub fn run(comptime maximum_message: usize, callbacks: Callbacks) void {
|
||||
}
|
||||
if (got.len == 0) {
|
||||
reply_len = 0; // the universal ping: a zero-length reply, from the harness
|
||||
continue;
|
||||
continue; // any capability it carried goes out through the turn's `defer`
|
||||
}
|
||||
reply_len = callbacks.on_message(receive[0..got.len], &reply_buffer, got.senderTaskId(), got.cap);
|
||||
reply_len = callbacks.on_message(receive[0..got.len], &reply_buffer, got.senderTaskId(), &arrived);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,10 @@
|
||||
//! 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:
|
||||
//!
|
||||
//! envelope : the packet prefix + comptime Define (docs/os-development/protocol-namespace.md)
|
||||
//!
|
||||
//! vfs-protocol : the VFS server <-> the file layer (unistd/stdio)
|
||||
//! input-protocol : the input fan-out service <-> sources + subscribers
|
||||
//! block-protocol : a filesystem <-> a block driver (usb-storage)
|
||||
@@ -16,6 +20,9 @@ const std = @import("std");
|
||||
|
||||
pub fn build(b: *std.Build) void {
|
||||
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,6 +39,7 @@ pub fn build(b: *std.Build) void {
|
||||
// its aggregate test step.
|
||||
const test_step = b.step("test", "Run the protocol unit tests");
|
||||
for ([_][]const u8{
|
||||
"envelope/envelope.zig", // framing round trips, verb numbering, dispatch, the floors
|
||||
"vfs/vfs-protocol.zig", // NodeKind / DirectoryEntry sizes + op values
|
||||
"display/display-protocol.zig", // pack(): native pixel encoding per format
|
||||
}) |root| {
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
pub const version: u16 = 1;
|
||||
|
||||
/// Which bus a `child_added` came from — stated by the reporting bus driver so
|
||||
/// the manager's /etc/devices.csv matcher knows how to read the report's identity
|
||||
/// the manager's /system/configuration/devices.csv matcher knows how to read the report's identity
|
||||
/// (a PCI class triple vs a USB class triple are the same 24 bits but different
|
||||
/// namespaces) and which `bus` column a rule must name to bind it. `unknown` is
|
||||
/// the zero default, so an un-upgraded reporter fails to match rather than
|
||||
@@ -96,7 +96,7 @@ pub const ChildAdded = extern struct {
|
||||
/// for an unregistered leaf (a USB port before the descriptor track).
|
||||
device_id: u64 = no_device,
|
||||
/// The vendor id (PCI vendor / USB idVendor), or 0 when the bus has no such
|
||||
/// concept (ACPI). Carried so the manager's /etc/devices.csv matcher can bind
|
||||
/// 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.
|
||||
vendor: u16 = 0,
|
||||
/// The device id (PCI device / USB idProduct), or 0. The most specific numeric
|
||||
|
||||
@@ -0,0 +1,924 @@
|
||||
//! The envelope — the fixed prefix every danos packet begins with, and the
|
||||
//! comptime `Define` that builds a protocol out of it. Layer L2 of
|
||||
//! [communication.md](../../../docs/os-development/communication.md); the
|
||||
//! authoritative description is
|
||||
//! [protocol-namespace.md](../../../docs/os-development/protocol-namespace.md).
|
||||
//!
|
||||
//! This is the one module in the protocol domain that is not itself a protocol:
|
||||
//! it is the shape every protocol is expressed in. A protocol module hands
|
||||
//! `Define` its verbs and events and gets back numbered operations (never
|
||||
//! colliding with the reserved range), typed encode/decode helpers, a
|
||||
//! provider-side dispatch table that answers `describe` on its own — and, the
|
||||
//! point of the exercise, compile-time proof that none of its packets can
|
||||
//! exceed the transport floor. Errors that used to surface as runtime
|
||||
//! truncation are compile errors, and "packets never fragment" is enforced at
|
||||
//! the source rather than by review.
|
||||
//!
|
||||
//! **The prefix is folded, never stacked.** A `request`, `reply`, or `payload`
|
||||
//! type names the bytes that follow the prefix — never the whole packet. The
|
||||
//! verb and the object being addressed live in the prefix, so a protocol type
|
||||
//! carries neither an `operation` field of its own nor a nested `Header`;
|
||||
//! `rejectStacking` refuses one at compile time, and every size check adds
|
||||
//! `prefix_size` exactly once.
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
// --- the prefix -------------------------------------------------------------
|
||||
|
||||
/// Every packet a danos protocol transmits begins with this header — requests
|
||||
/// on the synchronous call path, event packets on the asynchronous push path.
|
||||
/// A reply spends the same 16 bytes on `Status` instead.
|
||||
pub const Header = extern struct {
|
||||
/// The verb. Values below `first_protocol_operation` are the reserved
|
||||
/// universal verbs, which mean the same thing in every protocol.
|
||||
operation: u32,
|
||||
_padding: u32 = 0,
|
||||
/// **Object** addressing within the peer, never party addressing: which of
|
||||
/// the peer's objects this packet operates on — a volume, a layer, a node,
|
||||
/// a device. `0` addresses the provider itself, and a protocol with no
|
||||
/// objects never uses the field. *Which* party is at the other end was
|
||||
/// decided once, when the channel was opened, and *who sent this* is the
|
||||
/// kernel-stamped badge; neither is ever written here, which is what keeps
|
||||
/// the source unforgeable.
|
||||
target: u64 = 0,
|
||||
};
|
||||
|
||||
/// Every reply begins with this. `len` counts the bytes that follow: the
|
||||
/// reply's fixed part plus whatever variable tail the operation defines.
|
||||
pub const Status = extern struct {
|
||||
status: i32, // 0, or a negative errno
|
||||
_padding: u32 = 0,
|
||||
len: u32 = 0,
|
||||
_padding2: u32 = 0,
|
||||
};
|
||||
|
||||
/// The fixed prefix every packet spends — `Header` on a request or an event,
|
||||
/// `Status` on a reply. One constant, because the two are deliberately the same
|
||||
/// width: the packet budget does not depend on the direction.
|
||||
pub const prefix_size: usize = @sizeOf(Header);
|
||||
|
||||
comptime {
|
||||
if (@sizeOf(Header) != 16 or @sizeOf(Status) != 16)
|
||||
@compileError("the envelope prefix is 16 bytes in both directions");
|
||||
}
|
||||
|
||||
// --- the reserved verbs -----------------------------------------------------
|
||||
|
||||
/// Reserved verbs, answered by every provider. `Define` numbers a protocol's
|
||||
/// own verbs from `first_protocol_operation`, so no protocol can reach in here.
|
||||
pub const operation_describe: u32 = 0; // -> protocol name, version, target kinds
|
||||
pub const operation_enumerate: u32 = 1; // -> the current targets, one per reply page
|
||||
pub const operation_subscribe: u32 = 2; // capability = the subscriber's endpoint
|
||||
pub const operation_unsubscribe: u32 = 3;
|
||||
pub const first_protocol_operation: u32 = 16;
|
||||
|
||||
/// 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
|
||||
/// 256-byte budget.
|
||||
pub const Description = extern struct {
|
||||
version: u32,
|
||||
operation_count: u32,
|
||||
event_count: u32,
|
||||
name_len: u32,
|
||||
};
|
||||
|
||||
/// Longest protocol name a `describe` reply can carry.
|
||||
pub const name_maximum: usize = packet_maximum - prefix_size - @sizeOf(Description);
|
||||
|
||||
// --- the transport floor ----------------------------------------------------
|
||||
|
||||
/// The packet budget every protocol may assume on *any* transport. These are
|
||||
/// the kernel-ipc transport's limits — `MESSAGE_MAXIMUM` and `POST_MAXIMUM` in
|
||||
/// system/kernel/ipc-synchronous.zig — restated here because the kernel keeps
|
||||
/// them private and a protocol has to compile against something. A fatter
|
||||
/// transport raises its own ceiling; the floor does not move, so a protocol
|
||||
/// that fits here fits everywhere (communication.md: ceilings are transport
|
||||
/// properties, the floor is the protocol's contract).
|
||||
pub const packet_maximum: usize = 256; // one request or one reply (ipc_call)
|
||||
pub const post_maximum: usize = 64; // one event packet (ipc_send)
|
||||
|
||||
/// Whether a request or reply whose fixed part is `T` fits the call floor once
|
||||
/// the prefix is counted. The folded rule in one line: `prefix_size` is added
|
||||
/// exactly once, because `T` describes only what follows it. Exported so the
|
||||
/// rule itself is testable — `Define` enforces it as a compile error.
|
||||
pub fn fitsPacket(comptime T: type) bool {
|
||||
return prefix_size + @sizeOf(T) <= packet_maximum;
|
||||
}
|
||||
|
||||
/// The same, against the much smaller push floor an event packet lives within.
|
||||
pub fn fitsPost(comptime T: type) bool {
|
||||
return prefix_size + @sizeOf(T) <= post_maximum;
|
||||
}
|
||||
|
||||
// --- reply statuses the envelope itself produces -----------------------------
|
||||
|
||||
/// Continued from the kernel's danos-native errno numbering
|
||||
/// (system/kernel/ipc-synchronous.zig, which ends at `EPERM` = 9), so a client
|
||||
/// reads one vocabulary whether the number came from the kernel or a provider.
|
||||
/// Positive here, sent negated in `Status.status`, as the kernel spells it.
|
||||
pub const ENOSYS: i32 = 10; // this protocol has no such operation
|
||||
pub const EPROTO: i32 = 11; // malformed packet: shorter than the verb it names
|
||||
pub const EBUSY: i32 = 12; // the thing asked for is held by someone still alive
|
||||
|
||||
/// Restated from the kernel's half of the numbering, because a provider refuses
|
||||
/// too and userspace has no other place to read these from: `ENOENT` is "no such
|
||||
/// name", `EPERM` "not permitted". The protocol registry answers an ungranted
|
||||
/// bind with the second and a name a live provider already holds with `EBUSY`.
|
||||
pub const ENOENT: i32 = 4;
|
||||
pub const ENOSPC: i32 = 5;
|
||||
pub const EPERM: i32 = 9;
|
||||
|
||||
// --- framing ----------------------------------------------------------------
|
||||
|
||||
/// The header of a received packet, or null when it is too short to have one.
|
||||
pub fn headerOf(packet: []const u8) ?Header {
|
||||
if (packet.len < prefix_size) return null;
|
||||
return std.mem.bytesToValue(Header, packet[0..prefix_size]);
|
||||
}
|
||||
|
||||
/// The status of a received reply, or null when it is too short to have one.
|
||||
pub fn statusOf(packet: []const u8) ?Status {
|
||||
if (packet.len < prefix_size) return null;
|
||||
return std.mem.bytesToValue(Status, packet[0..prefix_size]);
|
||||
}
|
||||
|
||||
/// Frame a bare `describe` request. Protocol-independent: the reserved verbs
|
||||
/// are asked the same way of every provider.
|
||||
pub fn encodeDescribe(buffer: []u8) ?[]u8 {
|
||||
const header = Header{ .operation = operation_describe };
|
||||
return frame(std.mem.asBytes(&header), &.{}, &.{}, buffer);
|
||||
}
|
||||
|
||||
/// A decoded `describe` reply: the fixed part, plus the name that follows it.
|
||||
pub const Described = struct {
|
||||
description: Description,
|
||||
name: []const u8,
|
||||
};
|
||||
|
||||
/// Decode a `describe` reply packet. Null if it failed, was truncated, or is
|
||||
/// not a description at all.
|
||||
pub fn decodeDescribe(packet: []const u8) ?Described {
|
||||
const status = statusOf(packet) orelse return null;
|
||||
if (status.status != 0) return null;
|
||||
const body = packet[prefix_size..];
|
||||
if (body.len < @sizeOf(Description)) return null;
|
||||
const description = std.mem.bytesToValue(Description, body[0..@sizeOf(Description)]);
|
||||
const name = body[@sizeOf(Description)..];
|
||||
if (name.len < description.name_len) return null;
|
||||
return .{ .description = description, .name = name[0..description.name_len] };
|
||||
}
|
||||
|
||||
/// The single framing point: prefix, then the fixed part, then the variable
|
||||
/// tail, contiguous in one buffer. Null when the packet would not fit — a
|
||||
/// packet is never split, so not fitting is a failure, not a continuation.
|
||||
fn frame(prefix: []const u8, fixed: []const u8, tail: []const u8, buffer: []u8) ?[]u8 {
|
||||
const total = prefix.len + fixed.len + tail.len;
|
||||
if (total > buffer.len) return null;
|
||||
@memcpy(buffer[0..prefix.len], prefix);
|
||||
@memcpy(buffer[prefix.len..][0..fixed.len], fixed);
|
||||
@memcpy(buffer[prefix.len + fixed.len ..][0..tail.len], tail);
|
||||
return buffer[0..total];
|
||||
}
|
||||
|
||||
/// The bytes of a fixed part — empty for `void`, which is how an operation says
|
||||
/// "nothing but the verb".
|
||||
fn bytesOf(comptime T: type, value: *const T) []const u8 {
|
||||
if (@sizeOf(T) == 0) return &.{};
|
||||
return @as([*]const u8, @ptrCast(value))[0..@sizeOf(T)];
|
||||
}
|
||||
|
||||
/// Read a fixed part out of a packet body. A zero-sized part always succeeds
|
||||
/// (there is nothing to be short of); anything else needs its full width.
|
||||
fn valueOf(comptime T: type, body: []const u8) ?T {
|
||||
if (@sizeOf(T) == 0) return @as(T, undefined);
|
||||
if (body.len < @sizeOf(T)) return null;
|
||||
return std.mem.bytesToValue(T, body[0..@sizeOf(T)]);
|
||||
}
|
||||
|
||||
// --- the specification ------------------------------------------------------
|
||||
|
||||
/// One verb of a protocol. `request` and `reply` describe the bytes *after* the
|
||||
/// prefix; either may be `void`, meaning the verb (and its target) says it all.
|
||||
pub const OperationSpecification = struct {
|
||||
name: []const u8,
|
||||
request: type = void,
|
||||
reply: type = void,
|
||||
};
|
||||
|
||||
/// One event a provider pushes to its subscribers. `payload` is the bytes after
|
||||
/// the `Header`, and the whole packet must fit the push floor.
|
||||
pub const EventSpecification = struct {
|
||||
name: []const u8,
|
||||
payload: type = void,
|
||||
};
|
||||
|
||||
/// What `Define` is given: the contract, whole.
|
||||
pub const Specification = struct {
|
||||
/// The contract's name — the same word as its `/protocol/<name>` leaf and
|
||||
/// its `library/protocol/` module.
|
||||
name: []const u8,
|
||||
version: u32,
|
||||
operations: []const OperationSpecification = &.{},
|
||||
events: []const EventSpecification = &.{},
|
||||
};
|
||||
|
||||
const reserved_names = [_][]const u8{ "describe", "enumerate", "subscribe", "unsubscribe" };
|
||||
|
||||
fn isReservedName(comptime name: []const u8) bool {
|
||||
for (reserved_names) |reserved| {
|
||||
if (std.mem.eql(u8, reserved, name)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Refuse a protocol type that carries the prefix inside itself. The header is
|
||||
/// folded into every packet, so a type that also holds one would send it twice
|
||||
/// and re-invent per-protocol addressing — the mistake the envelope exists to
|
||||
/// prevent.
|
||||
fn rejectStacking(comptime protocol: []const u8, comptime verb: []const u8, comptime T: type) void {
|
||||
switch (@typeInfo(T)) {
|
||||
.@"struct" => |info| for (info.fields) |field| {
|
||||
if (field.type == Header or field.type == Status) @compileError(std.fmt.comptimePrint(
|
||||
"protocol '{s}', verb '{s}': the envelope prefix is folded, not stacked — " ++
|
||||
"drop the {s} field '{s}' and use the packet's own Header.operation / Header.target",
|
||||
.{ protocol, verb, @typeName(field.type), field.name },
|
||||
));
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
}
|
||||
|
||||
fn nullDefault(comptime T: type) *const anyopaque {
|
||||
const empty: ?T = null;
|
||||
return @ptrCast(&empty);
|
||||
}
|
||||
|
||||
// --- Define -----------------------------------------------------------------
|
||||
|
||||
/// Build a protocol from its specification. Everything below happens at compile
|
||||
/// time; the generated type is what both sides of the conversation import.
|
||||
///
|
||||
/// ```zig
|
||||
/// pub const Protocol = envelope.Define(.{
|
||||
/// .name = "display",
|
||||
/// .version = 1,
|
||||
/// .operations = &.{
|
||||
/// .{ .name = "configure_layer", .request = ConfigureLayer, .reply = void },
|
||||
/// .{ .name = "blit", .request = Blit, .reply = void },
|
||||
/// },
|
||||
/// .events = &.{
|
||||
/// .{ .name = "layer_lost", .payload = LayerLost },
|
||||
/// },
|
||||
/// });
|
||||
/// ```
|
||||
///
|
||||
/// Refused at compile time, each with the protocol, the verb, and the numbers
|
||||
/// named in the message:
|
||||
///
|
||||
/// - a request or reply that does not fit `packet_maximum` once `prefix_size`
|
||||
/// is added (`.request = extern struct { bytes: [241]u8 }` — 241 + 16 = 257);
|
||||
/// - an event payload that does not fit `post_maximum` the same way
|
||||
/// (`.payload = extern struct { bytes: [49]u8 }` — 49 + 16 = 65);
|
||||
/// - a type that stacks the prefix instead of folding it (a `Header` field);
|
||||
/// - a verb named after a reserved one, or named twice.
|
||||
///
|
||||
/// A variable tail is bounded at *run* time instead, by `encodeRequest` and its
|
||||
/// siblings, because only the caller knows how long it is.
|
||||
pub fn Define(comptime specification: Specification) type {
|
||||
comptime {
|
||||
if (specification.name.len == 0) @compileError("a protocol needs a name");
|
||||
if (specification.name.len > name_maximum) @compileError(std.fmt.comptimePrint(
|
||||
"protocol '{s}': the name is {d} bytes, and a describe reply carries at most {d}",
|
||||
.{ specification.name, specification.name.len, name_maximum },
|
||||
));
|
||||
|
||||
for (specification.operations, 0..) |operation, index| {
|
||||
if (isReservedName(operation.name)) @compileError(std.fmt.comptimePrint(
|
||||
"protocol '{s}': '{s}' is a reserved universal verb — the envelope already answers it",
|
||||
.{ specification.name, operation.name },
|
||||
));
|
||||
for (specification.operations[0..index]) |earlier| {
|
||||
if (std.mem.eql(u8, earlier.name, operation.name)) @compileError(std.fmt.comptimePrint(
|
||||
"protocol '{s}': operation '{s}' is declared twice",
|
||||
.{ specification.name, operation.name },
|
||||
));
|
||||
}
|
||||
rejectStacking(specification.name, operation.name, operation.request);
|
||||
rejectStacking(specification.name, operation.name, operation.reply);
|
||||
if (!fitsPacket(operation.request)) @compileError(std.fmt.comptimePrint(
|
||||
"protocol '{s}', operation '{s}': the request is {d} bytes and the header {d}, " ++
|
||||
"over the {d}-byte call floor — packets never fragment, so this has to shrink " ++
|
||||
"or move its bulk to shared memory",
|
||||
.{ specification.name, operation.name, @sizeOf(operation.request), prefix_size, packet_maximum },
|
||||
));
|
||||
if (!fitsPacket(operation.reply)) @compileError(std.fmt.comptimePrint(
|
||||
"protocol '{s}', operation '{s}': the reply is {d} bytes and the status header {d}, " ++
|
||||
"over the {d}-byte call floor",
|
||||
.{ specification.name, operation.name, @sizeOf(operation.reply), prefix_size, packet_maximum },
|
||||
));
|
||||
}
|
||||
|
||||
for (specification.events, 0..) |event, index| {
|
||||
for (specification.events[0..index]) |earlier| {
|
||||
if (std.mem.eql(u8, earlier.name, event.name)) @compileError(std.fmt.comptimePrint(
|
||||
"protocol '{s}': event '{s}' is declared twice",
|
||||
.{ specification.name, event.name },
|
||||
));
|
||||
}
|
||||
rejectStacking(specification.name, event.name, event.payload);
|
||||
if (!fitsPost(event.payload)) @compileError(std.fmt.comptimePrint(
|
||||
"protocol '{s}', event '{s}': the payload is {d} bytes and the header {d}, " ++
|
||||
"over the {d}-byte push floor — an event carries the header too, so it is the " ++
|
||||
"payload that has to give",
|
||||
.{ specification.name, event.name, @sizeOf(event.payload), prefix_size, post_maximum },
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
return struct {
|
||||
pub const protocol_name: []const u8 = specification.name;
|
||||
pub const version: u32 = specification.version;
|
||||
|
||||
/// What a provider sizes its receive and reply buffers to. A packet's
|
||||
/// fixed part may be far smaller, but any caller may send up to the
|
||||
/// floor and a short buffer truncates rather than refuses.
|
||||
pub const message_maximum: usize = packet_maximum;
|
||||
|
||||
/// The widest packet this protocol's fixed parts can actually produce,
|
||||
/// prefix included — a diagnostic, and what a test pins.
|
||||
pub const request_maximum: usize = widest(specification.operations, .request);
|
||||
pub const reply_maximum: usize = widest(specification.operations, .reply);
|
||||
pub const event_maximum: usize = blk: {
|
||||
var widest_event: usize = prefix_size;
|
||||
for (specification.events) |event| widest_event = @max(widest_event, prefix_size + @sizeOf(event.payload));
|
||||
break :blk widest_event;
|
||||
};
|
||||
|
||||
/// This protocol's verbs, numbered from `first_protocol_operation` in
|
||||
/// declaration order.
|
||||
pub const Operation = numbered(specification.operations, "name");
|
||||
|
||||
/// This protocol's events, numbered from `first_protocol_operation` in
|
||||
/// their **own** space. Events travel only provider → subscriber over
|
||||
/// `ipc_send` and operations only client → provider over `ipc_call`, so
|
||||
/// the direction already tells the two apart; separate spaces mean
|
||||
/// appending an operation can never renumber a shipped event.
|
||||
pub const Event = numbered(specification.events, "name");
|
||||
|
||||
/// The bytes after the `Header` on a request for `operation`.
|
||||
pub fn RequestOf(comptime operation: Operation) type {
|
||||
return specification.operations[indexOf(@intFromEnum(operation))].request;
|
||||
}
|
||||
|
||||
/// The bytes after the `Status` on the reply to `operation`.
|
||||
pub fn ReplyOf(comptime operation: Operation) type {
|
||||
return specification.operations[indexOf(@intFromEnum(operation))].reply;
|
||||
}
|
||||
|
||||
/// The bytes after the `Header` on an `event` packet.
|
||||
pub fn PayloadOf(comptime event: Event) type {
|
||||
return specification.events[indexOf(@intFromEnum(event))].payload;
|
||||
}
|
||||
|
||||
// --- client side ----------------------------------------------------
|
||||
|
||||
/// Frame `[Header][request][tail]`. `tail` is the variable part (a path,
|
||||
/// write bytes); pass `&.{}` when the verb has none. Null if the packet
|
||||
/// would exceed the buffer or the call floor.
|
||||
pub fn encodeRequest(
|
||||
comptime operation: Operation,
|
||||
target: u64,
|
||||
request: RequestOf(operation),
|
||||
tail: []const u8,
|
||||
buffer: []u8,
|
||||
) ?[]u8 {
|
||||
const header = Header{ .operation = @intFromEnum(operation), .target = target };
|
||||
const packet = frame(std.mem.asBytes(&header), bytesOf(RequestOf(operation), &request), tail, buffer) orelse return null;
|
||||
return if (packet.len > packet_maximum) null else packet;
|
||||
}
|
||||
|
||||
/// Frame `[Status][reply][tail]` — the provider's answer, for a provider
|
||||
/// that composes its own reply rather than using `Provider.dispatch`.
|
||||
pub fn encodeReply(
|
||||
comptime operation: Operation,
|
||||
status: i32,
|
||||
reply: ReplyOf(operation),
|
||||
tail: []const u8,
|
||||
buffer: []u8,
|
||||
) ?[]u8 {
|
||||
const fixed = bytesOf(ReplyOf(operation), &reply);
|
||||
const head = Status{ .status = status, .len = @intCast(fixed.len + tail.len) };
|
||||
const packet = frame(std.mem.asBytes(&head), fixed, tail, buffer) orelse return null;
|
||||
return if (packet.len > packet_maximum) null else packet;
|
||||
}
|
||||
|
||||
/// Frame `[Header][payload]` for an asynchronous push. Null if it would
|
||||
/// exceed the buffer or the push floor — an event that does not fit is
|
||||
/// dropped at the source, never split.
|
||||
pub fn encodeEvent(
|
||||
comptime event: Event,
|
||||
target: u64,
|
||||
payload: PayloadOf(event),
|
||||
buffer: []u8,
|
||||
) ?[]u8 {
|
||||
const header = Header{ .operation = @intFromEnum(event), .target = target };
|
||||
const packet = frame(std.mem.asBytes(&header), bytesOf(PayloadOf(event), &payload), &.{}, buffer) orelse return null;
|
||||
return if (packet.len > post_maximum) null else packet;
|
||||
}
|
||||
|
||||
/// Which of this protocol's verbs a packet names — null for a reserved
|
||||
/// verb, or for a number this protocol does not define.
|
||||
pub fn operationOf(packet: []const u8) ?Operation {
|
||||
const header = headerOf(packet) orelse return null;
|
||||
const index = header.operation -% first_protocol_operation;
|
||||
if (header.operation < first_protocol_operation or index >= specification.operations.len) return null;
|
||||
return @enumFromInt(header.operation);
|
||||
}
|
||||
|
||||
/// Which of this protocol's events a pushed packet carries.
|
||||
pub fn eventOf(packet: []const u8) ?Event {
|
||||
const header = headerOf(packet) orelse return null;
|
||||
const index = header.operation -% first_protocol_operation;
|
||||
if (header.operation < first_protocol_operation or index >= specification.events.len) return null;
|
||||
return @enumFromInt(header.operation);
|
||||
}
|
||||
|
||||
/// The fixed request part of a packet already known to name `operation`.
|
||||
pub fn decodeRequest(comptime operation: Operation, packet: []const u8) ?RequestOf(operation) {
|
||||
if (packet.len < prefix_size) return null;
|
||||
return valueOf(RequestOf(operation), packet[prefix_size..]);
|
||||
}
|
||||
|
||||
/// The bytes after the fixed request part — empty when there are none.
|
||||
pub fn requestTail(comptime operation: Operation, packet: []const u8) []const u8 {
|
||||
const start = prefix_size + @sizeOf(RequestOf(operation));
|
||||
return if (packet.len <= start) &.{} else packet[start..];
|
||||
}
|
||||
|
||||
/// The fixed reply part of a reply packet. Null on a short packet; the
|
||||
/// caller checks `statusOf(packet).status` for the provider's verdict.
|
||||
pub fn decodeReply(comptime operation: Operation, packet: []const u8) ?ReplyOf(operation) {
|
||||
if (packet.len < prefix_size) return null;
|
||||
return valueOf(ReplyOf(operation), packet[prefix_size..]);
|
||||
}
|
||||
|
||||
/// The bytes after the fixed reply part, clipped to what `Status.len`
|
||||
/// says actually arrived.
|
||||
pub fn replyTail(comptime operation: Operation, packet: []const u8) []const u8 {
|
||||
const status = statusOf(packet) orelse return &.{};
|
||||
const start = prefix_size + @sizeOf(ReplyOf(operation));
|
||||
const end = @min(packet.len, prefix_size + @as(usize, status.len));
|
||||
return if (end <= start) &.{} else packet[start..end];
|
||||
}
|
||||
|
||||
/// The payload of a pushed packet already known to carry `event`.
|
||||
pub fn decodeEvent(comptime event: Event, packet: []const u8) ?PayloadOf(event) {
|
||||
if (packet.len < prefix_size) return null;
|
||||
return valueOf(PayloadOf(event), packet[prefix_size..]);
|
||||
}
|
||||
|
||||
// --- provider side --------------------------------------------------
|
||||
|
||||
/// This protocol's dispatch table, bound to the provider's own state
|
||||
/// type. `describe` is answered here, from the specification; every verb
|
||||
/// this provider left null answers `-ENOSYS`, which is what makes the
|
||||
/// reserved verbs mean the same thing at every provider in the system.
|
||||
///
|
||||
/// ```zig
|
||||
/// const Serve = Protocol.Provider(*Server);
|
||||
/// const handlers = Serve.Handlers{ .blit = onBlit, .configure_layer = onConfigureLayer };
|
||||
/// const reply_len = Serve.dispatch(server, handlers, message, sender, capability, reply);
|
||||
/// ```
|
||||
///
|
||||
/// A handler returns the number of `answer.tail()` bytes it wrote, or a
|
||||
/// negative errno.
|
||||
pub fn Provider(comptime Context: type) type {
|
||||
return struct {
|
||||
/// A reserved verb a provider chooses to implement itself.
|
||||
/// `enumerate` writes its targets into the tail; `subscribe`
|
||||
/// takes the subscriber's endpoint from `invocation.capability`.
|
||||
pub const ReservedHandler = *const fn (Context, Invocation(void), Answer(void)) isize;
|
||||
|
||||
/// One optional handler per verb, named exactly as the verb,
|
||||
/// plus the reserved verbs the envelope cannot answer alone.
|
||||
pub const Handlers = handlerTable(Context);
|
||||
|
||||
/// Answer one received packet: writes `[Status][reply][tail]`
|
||||
/// into `reply` and returns its length. Zero means the reply
|
||||
/// buffer could not even hold a status, so nothing was written.
|
||||
pub fn dispatch(
|
||||
context: Context,
|
||||
handlers: Handlers,
|
||||
packet: []const u8,
|
||||
sender: u32,
|
||||
capability: ?usize,
|
||||
reply: []u8,
|
||||
) usize {
|
||||
if (reply.len < prefix_size) return 0;
|
||||
const header = headerOf(packet) orelse return refuse(reply, -EPROTO);
|
||||
const body = packet[prefix_size..];
|
||||
|
||||
if (header.operation == operation_describe) return describeInto(reply);
|
||||
|
||||
inline for (specification.operations, 0..) |operation, index| {
|
||||
if (header.operation == first_protocol_operation + index) {
|
||||
return invoke(
|
||||
Context,
|
||||
operation.request,
|
||||
operation.reply,
|
||||
@field(handlers, operation.name),
|
||||
context,
|
||||
header.target,
|
||||
body,
|
||||
sender,
|
||||
capability,
|
||||
reply,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const reserved: ?ReservedHandler = switch (header.operation) {
|
||||
operation_enumerate => handlers.enumerate,
|
||||
operation_subscribe => handlers.subscribe,
|
||||
operation_unsubscribe => handlers.unsubscribe,
|
||||
else => null,
|
||||
};
|
||||
return invoke(Context, void, void, reserved, context, header.target, body, sender, capability, reply);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Shared by the protocol verbs and the reserved ones: decode, hand the
|
||||
// handler a typed invocation, stamp the status. One place, so a reserved
|
||||
// verb and a protocol verb behave identically.
|
||||
fn invoke(
|
||||
comptime Context: type,
|
||||
comptime RequestType: type,
|
||||
comptime ReplyType: type,
|
||||
handler: ?*const fn (Context, Invocation(RequestType), Answer(ReplyType)) isize,
|
||||
context: Context,
|
||||
target: u64,
|
||||
body: []const u8,
|
||||
sender: u32,
|
||||
capability: ?usize,
|
||||
reply: []u8,
|
||||
) usize {
|
||||
const call = handler orelse return refuse(reply, -ENOSYS);
|
||||
const request = valueOf(RequestType, body) orelse return refuse(reply, -EPROTO);
|
||||
if (reply.len < prefix_size + @sizeOf(ReplyType)) return refuse(reply, -EPROTO);
|
||||
const produced = call(context, .{
|
||||
.target = target,
|
||||
.request = request,
|
||||
.tail = body[@min(@sizeOf(RequestType), body.len)..],
|
||||
.sender = sender,
|
||||
.capability = capability,
|
||||
}, .{ .buffer = reply[prefix_size..] });
|
||||
if (produced < 0) return refuse(reply, @intCast(produced));
|
||||
return succeed(reply, @sizeOf(ReplyType) + @as(usize, @intCast(produced)));
|
||||
}
|
||||
|
||||
fn describeInto(reply: []u8) usize {
|
||||
const description = Description{
|
||||
.version = specification.version,
|
||||
.operation_count = specification.operations.len,
|
||||
.event_count = specification.events.len,
|
||||
.name_len = specification.name.len,
|
||||
};
|
||||
const total = @sizeOf(Description) + specification.name.len;
|
||||
if (reply.len < prefix_size + total) return refuse(reply, -EPROTO);
|
||||
@memcpy(reply[prefix_size..][0..@sizeOf(Description)], std.mem.asBytes(&description));
|
||||
@memcpy(reply[prefix_size + @sizeOf(Description) ..][0..specification.name.len], specification.name);
|
||||
return succeed(reply, total);
|
||||
}
|
||||
|
||||
// "describe" is answered by the envelope, so it is the one reserved verb
|
||||
// with no slot in the table.
|
||||
const implementable_reserved = [_][]const u8{ "enumerate", "subscribe", "unsubscribe" };
|
||||
|
||||
fn handlerTable(comptime Context: type) type {
|
||||
const count = specification.operations.len + implementable_reserved.len;
|
||||
var names: [count][]const u8 = undefined;
|
||||
var types: [count]type = undefined;
|
||||
var attributes: [count]std.builtin.Type.StructField.Attributes = undefined;
|
||||
for (specification.operations, 0..) |operation, index| {
|
||||
const Handler = *const fn (Context, Invocation(operation.request), Answer(operation.reply)) isize;
|
||||
names[index] = operation.name;
|
||||
types[index] = ?Handler;
|
||||
attributes[index] = .{ .default_value_ptr = nullDefault(Handler) };
|
||||
}
|
||||
const Reserved = *const fn (Context, Invocation(void), Answer(void)) isize;
|
||||
for (implementable_reserved, 0..) |name, offset| {
|
||||
const slot = specification.operations.len + offset;
|
||||
names[slot] = name;
|
||||
types[slot] = ?Reserved;
|
||||
attributes[slot] = .{ .default_value_ptr = nullDefault(Reserved) };
|
||||
}
|
||||
const frozen_names = names;
|
||||
const frozen_types = types;
|
||||
const frozen_attributes = attributes;
|
||||
return @Struct(.auto, null, &frozen_names, &frozen_types, &frozen_attributes);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// --- the provider's view of one packet --------------------------------------
|
||||
|
||||
/// What a provider's handler is given.
|
||||
pub fn Invocation(comptime RequestType: type) type {
|
||||
return struct {
|
||||
/// Object addressing within this provider — the packet's `Header.target`.
|
||||
target: u64,
|
||||
/// The fixed request part, already decoded.
|
||||
request: RequestType,
|
||||
/// The bytes after it: a path, write data, a name.
|
||||
tail: []const u8,
|
||||
/// The kernel-stamped badge of the caller. The only source identity
|
||||
/// there is — no protocol defines a sender field — so per-client state
|
||||
/// is keyed on this.
|
||||
sender: u32,
|
||||
/// A capability the call carried: a subscriber's endpoint, a DMA
|
||||
/// region. Only the synchronous call path can move one.
|
||||
capability: ?usize,
|
||||
};
|
||||
}
|
||||
|
||||
/// Where a provider's handler writes its answer. The `Status` in front of it is
|
||||
/// the dispatcher's to stamp — a handler never writes its own.
|
||||
pub fn Answer(comptime ReplyType: type) type {
|
||||
return struct {
|
||||
buffer: []u8,
|
||||
|
||||
const fixed_size = @sizeOf(ReplyType);
|
||||
|
||||
/// Write the fixed reply part. A `void` reply writes nothing.
|
||||
pub fn set(self: @This(), reply: ReplyType) void {
|
||||
if (fixed_size == 0) return;
|
||||
@memcpy(self.buffer[0..fixed_size], bytesOf(ReplyType, &reply));
|
||||
}
|
||||
|
||||
/// Room for the variable tail; the handler returns how much of it it used.
|
||||
pub fn tail(self: @This()) []u8 {
|
||||
return self.buffer[fixed_size..];
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
fn refuse(reply: []u8, status: i32) usize {
|
||||
const head = Status{ .status = status, .len = 0 };
|
||||
@memcpy(reply[0..prefix_size], std.mem.asBytes(&head));
|
||||
return prefix_size;
|
||||
}
|
||||
|
||||
fn succeed(reply: []u8, len: usize) usize {
|
||||
const head = Status{ .status = 0, .len = @intCast(len) };
|
||||
@memcpy(reply[0..prefix_size], std.mem.asBytes(&head));
|
||||
return prefix_size + len;
|
||||
}
|
||||
|
||||
/// The widest `[prefix][fixed]` over a set of operations, on one side.
|
||||
fn widest(comptime operations: []const OperationSpecification, comptime side: enum { request, reply }) usize {
|
||||
var found: usize = prefix_size;
|
||||
for (operations) |operation| {
|
||||
const size = switch (side) {
|
||||
.request => @sizeOf(operation.request),
|
||||
.reply => @sizeOf(operation.reply),
|
||||
};
|
||||
found = @max(found, prefix_size + size);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/// An enum over `specifications`, tagged by their `name` field, numbered from
|
||||
/// `first_protocol_operation` in declaration order.
|
||||
fn numbered(comptime specifications: anytype, comptime field: []const u8) type {
|
||||
var names: [specifications.len][]const u8 = undefined;
|
||||
var values: [specifications.len]u32 = undefined;
|
||||
for (specifications, 0..) |specification, index| {
|
||||
names[index] = @field(specification, field);
|
||||
values[index] = first_protocol_operation + index;
|
||||
}
|
||||
const frozen_names = names;
|
||||
const frozen_values = values;
|
||||
return @Enum(u32, .exhaustive, &frozen_names, &frozen_values);
|
||||
}
|
||||
|
||||
/// A verb's position in its declaration list, from its wire number.
|
||||
fn indexOf(comptime operation: u32) usize {
|
||||
return operation - first_protocol_operation;
|
||||
}
|
||||
|
||||
// --- tests ------------------------------------------------------------------
|
||||
|
||||
const testing = std.testing;
|
||||
|
||||
const Produce = extern struct { count: u32, flags: u32 = 0 };
|
||||
const Produced = extern struct { total: u64 };
|
||||
const Changed = extern struct { kind: u32, value: u32 };
|
||||
|
||||
const Sample = Define(.{
|
||||
.name = "sample",
|
||||
.version = 3,
|
||||
.operations = &.{
|
||||
.{ .name = "produce", .request = Produce, .reply = Produced },
|
||||
.{ .name = "reset" },
|
||||
},
|
||||
.events = &.{
|
||||
.{ .name = "changed", .payload = Changed },
|
||||
},
|
||||
});
|
||||
|
||||
test "the prefix is 16 bytes in both directions" {
|
||||
try testing.expectEqual(@as(usize, 16), @sizeOf(Header));
|
||||
try testing.expectEqual(@as(usize, 16), @sizeOf(Status));
|
||||
try testing.expectEqual(@as(usize, 16), prefix_size);
|
||||
try testing.expectEqual(@as(usize, 256), packet_maximum);
|
||||
try testing.expectEqual(@as(usize, 64), post_maximum);
|
||||
}
|
||||
|
||||
test "verb numbering skips the reserved range" {
|
||||
try testing.expectEqual(@as(u32, 16), first_protocol_operation);
|
||||
try testing.expectEqual(@as(u32, 16), @intFromEnum(Sample.Operation.produce));
|
||||
try testing.expectEqual(@as(u32, 17), @intFromEnum(Sample.Operation.reset));
|
||||
// Events are numbered in their own space, so appending an operation can
|
||||
// never renumber a shipped event.
|
||||
try testing.expectEqual(@as(u32, 16), @intFromEnum(Sample.Event.changed));
|
||||
for ([_]u32{ operation_describe, operation_enumerate, operation_subscribe, operation_unsubscribe }) |reserved| {
|
||||
try testing.expect(reserved < first_protocol_operation);
|
||||
}
|
||||
}
|
||||
|
||||
test "request round trip, header folded and tail carried" {
|
||||
var buffer: [packet_maximum]u8 = undefined;
|
||||
const packet = Sample.encodeRequest(.produce, 42, .{ .count = 7 }, "tail bytes", &buffer).?;
|
||||
try testing.expectEqual(prefix_size + @sizeOf(Produce) + "tail bytes".len, packet.len);
|
||||
|
||||
const header = headerOf(packet).?;
|
||||
try testing.expectEqual(@as(u32, 16), header.operation);
|
||||
try testing.expectEqual(@as(u64, 42), header.target);
|
||||
try testing.expectEqual(Sample.Operation.produce, Sample.operationOf(packet).?);
|
||||
|
||||
const request = Sample.decodeRequest(.produce, packet).?;
|
||||
try testing.expectEqual(@as(u32, 7), request.count);
|
||||
try testing.expectEqualStrings("tail bytes", Sample.requestTail(.produce, packet));
|
||||
}
|
||||
|
||||
test "reply round trip" {
|
||||
var buffer: [packet_maximum]u8 = undefined;
|
||||
const packet = Sample.encodeReply(.produce, 0, .{ .total = 99 }, "more", &buffer).?;
|
||||
const status = statusOf(packet).?;
|
||||
try testing.expectEqual(@as(i32, 0), status.status);
|
||||
try testing.expectEqual(@as(u32, @sizeOf(Produced) + "more".len), status.len);
|
||||
try testing.expectEqual(@as(u64, 99), Sample.decodeReply(.produce, packet).?.total);
|
||||
try testing.expectEqualStrings("more", Sample.replyTail(.produce, packet));
|
||||
}
|
||||
|
||||
test "a void request and reply carry nothing but the verb" {
|
||||
var buffer: [packet_maximum]u8 = undefined;
|
||||
const packet = Sample.encodeRequest(.reset, 0, {}, &.{}, &buffer).?;
|
||||
try testing.expectEqual(prefix_size, packet.len);
|
||||
try testing.expectEqual(Sample.Operation.reset, Sample.operationOf(packet).?);
|
||||
try testing.expectEqual(@as(usize, 0), Sample.requestTail(.reset, packet).len);
|
||||
}
|
||||
|
||||
test "event round trip within the push floor" {
|
||||
var buffer: [post_maximum]u8 = undefined;
|
||||
const packet = Sample.encodeEvent(.changed, 0, .{ .kind = 1, .value = 2 }, &buffer).?;
|
||||
try testing.expectEqual(prefix_size + @sizeOf(Changed), packet.len);
|
||||
try testing.expect(packet.len <= post_maximum);
|
||||
try testing.expectEqual(Sample.Event.changed, Sample.eventOf(packet).?);
|
||||
try testing.expectEqual(@as(u32, 2), Sample.decodeEvent(.changed, packet).?.value);
|
||||
}
|
||||
|
||||
// A provider over a trivial context, to drive the generated dispatch table.
|
||||
const Counter = struct {
|
||||
total: u64 = 0,
|
||||
|
||||
fn onProduce(self: *Counter, invocation: Invocation(Produce), answer: Answer(Produced)) isize {
|
||||
self.total += invocation.request.count;
|
||||
answer.set(.{ .total = self.total });
|
||||
const note = "counted";
|
||||
@memcpy(answer.tail()[0..note.len], note);
|
||||
return note.len;
|
||||
}
|
||||
};
|
||||
|
||||
const CounterProvider = Sample.Provider(*Counter);
|
||||
|
||||
test "dispatch reaches a handler and stamps the status" {
|
||||
var counter = Counter{};
|
||||
const handlers = CounterProvider.Handlers{ .produce = Counter.onProduce };
|
||||
|
||||
var request: [packet_maximum]u8 = undefined;
|
||||
const packet = Sample.encodeRequest(.produce, 0, .{ .count = 5 }, &.{}, &request).?;
|
||||
var reply: [packet_maximum]u8 = undefined;
|
||||
const len = CounterProvider.dispatch(&counter, handlers, packet, 3, null, &reply);
|
||||
|
||||
const answered = reply[0..len];
|
||||
try testing.expectEqual(@as(i32, 0), statusOf(answered).?.status);
|
||||
try testing.expectEqual(@as(u64, 5), Sample.decodeReply(.produce, answered).?.total);
|
||||
try testing.expectEqualStrings("counted", Sample.replyTail(.produce, answered));
|
||||
}
|
||||
|
||||
test "describe is answered by the envelope, not the provider" {
|
||||
var counter = Counter{};
|
||||
const handlers = CounterProvider.Handlers{ .produce = Counter.onProduce };
|
||||
|
||||
var request: [packet_maximum]u8 = undefined;
|
||||
const packet = encodeDescribe(&request).?;
|
||||
var reply: [packet_maximum]u8 = undefined;
|
||||
const len = CounterProvider.dispatch(&counter, handlers, packet, 3, null, &reply);
|
||||
|
||||
const described = decodeDescribe(reply[0..len]).?;
|
||||
try testing.expectEqualStrings("sample", described.name);
|
||||
try testing.expectEqual(@as(u32, 3), described.description.version);
|
||||
try testing.expectEqual(@as(u32, 2), described.description.operation_count);
|
||||
try testing.expectEqual(@as(u32, 1), described.description.event_count);
|
||||
}
|
||||
|
||||
test "an unimplemented or unknown verb answers -ENOSYS" {
|
||||
var counter = Counter{};
|
||||
const handlers = CounterProvider.Handlers{ .produce = Counter.onProduce };
|
||||
var reply: [packet_maximum]u8 = undefined;
|
||||
|
||||
// A verb this protocol declares but this provider left null.
|
||||
var request: [packet_maximum]u8 = undefined;
|
||||
const declared = Sample.encodeRequest(.reset, 0, {}, &.{}, &request).?;
|
||||
var len = CounterProvider.dispatch(&counter, handlers, declared, 3, null, &reply);
|
||||
try testing.expectEqual(@as(i32, -ENOSYS), statusOf(reply[0..len]).?.status);
|
||||
|
||||
// A number no verb of this protocol wears.
|
||||
const stranger = Header{ .operation = first_protocol_operation + 900 };
|
||||
len = CounterProvider.dispatch(&counter, handlers, std.mem.asBytes(&stranger), 3, null, &reply);
|
||||
try testing.expectEqual(@as(i32, -ENOSYS), statusOf(reply[0..len]).?.status);
|
||||
|
||||
// A reserved verb the provider does not implement answers the same way.
|
||||
const enumerate = Header{ .operation = operation_enumerate };
|
||||
len = CounterProvider.dispatch(&counter, handlers, std.mem.asBytes(&enumerate), 3, null, &reply);
|
||||
try testing.expectEqual(@as(i32, -ENOSYS), statusOf(reply[0..len]).?.status);
|
||||
}
|
||||
|
||||
test "a truncated packet answers -EPROTO" {
|
||||
var counter = Counter{};
|
||||
const handlers = CounterProvider.Handlers{ .produce = Counter.onProduce };
|
||||
var reply: [packet_maximum]u8 = undefined;
|
||||
|
||||
// Names `produce`, but stops before the request it promises.
|
||||
const header = Header{ .operation = @intFromEnum(Sample.Operation.produce) };
|
||||
const len = CounterProvider.dispatch(&counter, handlers, std.mem.asBytes(&header), 3, null, &reply);
|
||||
try testing.expectEqual(@as(i32, -EPROTO), statusOf(reply[0..len]).?.status);
|
||||
}
|
||||
|
||||
// The size rule, exercised directly. `Define` turns exactly these predicates
|
||||
// into compile errors, which a test cannot catch — so the predicate is what the
|
||||
// test pins, and the boundary protocol below proves the compile-time half from
|
||||
// the other side. The negative example, spelled out: giving `Define` an
|
||||
// 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 "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 }));
|
||||
try testing.expect(fitsPost(extern struct { bytes: [48]u8 }));
|
||||
try testing.expect(!fitsPost(extern struct { bytes: [49]u8 }));
|
||||
try testing.expect(fitsPacket(void));
|
||||
try testing.expect(fitsPost(void));
|
||||
}
|
||||
|
||||
const WidestRequest = extern struct { bytes: [packet_maximum - prefix_size]u8 };
|
||||
const WidestEvent = extern struct { bytes: [post_maximum - prefix_size]u8 };
|
||||
|
||||
// A protocol sitting exactly on both floors. That this compiles at all is the
|
||||
// positive half of the compile-time check.
|
||||
const Boundary = Define(.{
|
||||
.name = "boundary",
|
||||
.version = 1,
|
||||
.operations = &.{.{ .name = "fill", .request = WidestRequest, .reply = WidestRequest }},
|
||||
.events = &.{.{ .name = "filled", .payload = WidestEvent }},
|
||||
});
|
||||
|
||||
test "a protocol may sit exactly on the floor" {
|
||||
try testing.expectEqual(packet_maximum, Boundary.request_maximum);
|
||||
try testing.expectEqual(packet_maximum, Boundary.reply_maximum);
|
||||
try testing.expectEqual(post_maximum, Boundary.event_maximum);
|
||||
|
||||
var buffer: [packet_maximum]u8 = undefined;
|
||||
const packet = Boundary.encodeRequest(.fill, 0, .{ .bytes = @splat(0xAB) }, &.{}, &buffer).?;
|
||||
try testing.expectEqual(packet_maximum, packet.len);
|
||||
try testing.expectEqual(@as(u8, 0xAB), Boundary.decodeRequest(.fill, packet).?.bytes[239]);
|
||||
|
||||
// One byte of tail past the floor is refused at run time, not truncated.
|
||||
try testing.expect(Boundary.encodeRequest(.fill, 0, .{ .bytes = @splat(0) }, "x", &buffer) == null);
|
||||
|
||||
var post: [post_maximum]u8 = undefined;
|
||||
const event = Boundary.encodeEvent(.filled, 0, .{ .bytes = @splat(1) }, &post).?;
|
||||
try testing.expectEqual(post_maximum, event.len);
|
||||
}
|
||||
|
||||
test "a protocol's own sizes are reported prefix-included" {
|
||||
try testing.expectEqual(prefix_size + @sizeOf(Produce), Sample.request_maximum);
|
||||
try testing.expectEqual(prefix_size + @sizeOf(Produced), Sample.reply_maximum);
|
||||
try testing.expectEqual(prefix_size + @sizeOf(Changed), Sample.event_maximum);
|
||||
try testing.expectEqual(packet_maximum, Sample.message_maximum);
|
||||
try testing.expectEqualStrings("sample", Sample.protocol_name);
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
//! The power protocol (docs/power.md): system power's domain-named surface,
|
||||
//! registered under `ServiceId.power`. On x86 the acpi service serves it; on
|
||||
//! ARM a PSCI/mailbox service will register the same id — subscribers never
|
||||
//! learn which firmware they are on (docs/discovery.md — firmware neutrality).
|
||||
//! 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 protocol version a client states nowhere yet — reserved for the day a
|
||||
|
||||
@@ -13,8 +13,17 @@
|
||||
//! 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
|
||||
//! `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
|
||||
//! `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.
|
||||
|
||||
pub const Operation = enum(u32) {
|
||||
open, // open(path) -> node id
|
||||
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
|
||||
@@ -31,6 +40,12 @@ pub const Operation = enum(u32) {
|
||||
// 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
|
||||
};
|
||||
|
||||
/// The type of a filesystem node, aligned to the node-kind table
|
||||
@@ -44,6 +59,12 @@ pub const NodeKind = enum(u32) {
|
||||
symbolic_link = 4,
|
||||
fifo = 5,
|
||||
socket = 6,
|
||||
/// A node that names a *contract*, not a file: opening it establishes a
|
||||
/// channel to whatever process currently provides that protocol, delivered
|
||||
/// as an endpoint capability in the reply rather than a node id. This is
|
||||
/// what lives under `/protocol`; `readdir` lists these like any other node,
|
||||
/// so the tree stays browsable for diagnosis.
|
||||
protocol = 7,
|
||||
};
|
||||
|
||||
/// One directory entry, returned by `readdir`: a fixed header followed inline in
|
||||
@@ -109,9 +130,15 @@ test "protocol struct sizes and node kinds" {
|
||||
const std = @import("std");
|
||||
try std.testing.expectEqual(@as(u32, 0), @intFromEnum(NodeKind.regular));
|
||||
try std.testing.expectEqual(@as(u32, 1), @intFromEnum(NodeKind.directory));
|
||||
// Appended with the protocol namespace; every earlier value keeps its own.
|
||||
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));
|
||||
}
|
||||
+13
-20
@@ -1,6 +1,6 @@
|
||||
//! The **private kernel ↔ runtime** ABI: the raw system_call contract — the call
|
||||
//! numbers, `mmap` protection flags, the page size those calls work in, and the IPC
|
||||
//! name-registry ids and notification bit. Shared by the kernel dispatcher
|
||||
//! notification bits. Shared by the kernel dispatcher
|
||||
//! (system/kernel/process.zig) and the user-space runtime library (library/runtime/),
|
||||
//! so the two can never drift.
|
||||
//!
|
||||
@@ -33,8 +33,13 @@ pub const SystemCall = enum(u64) {
|
||||
mmap = 4, // mmap(len, prot) -> base: grant zeroed, page-aligned user pages
|
||||
munmap = 5, // munmap(base, len): release pages from a prior mmap
|
||||
create_ipc_endpoint = 6, // create_ipc_endpoint() -> handle: a new IPC endpoint
|
||||
ipc_register = 7, // ipc_register(service_id, handle): publish an endpoint by well-known id
|
||||
ipc_lookup = 8, // ipc_lookup(service_id) -> handle: find a published endpoint
|
||||
// 7 and 8 were ipc_register/ipc_lookup — the flat ServiceId name registry,
|
||||
// retired with the protocol namespace (docs/os-development/protocol-namespace.md).
|
||||
// A service now binds its name at the registry (init, over /protocol) and a
|
||||
// client resolves and opens that path; neither is a system call any more. The
|
||||
// numbers stay vacant rather than being reused: every other entry is
|
||||
// position-fixed by an explicit value, so a hole costs nothing and a reused
|
||||
// number would silently mean two things across a rebuild boundary.
|
||||
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
|
||||
@@ -284,23 +289,11 @@ pub const KlogStatus = extern struct {
|
||||
boot_unix_seconds: u64, // wall-clock time of boot (RTC anchor)
|
||||
};
|
||||
|
||||
/// Well-known IPC service ids for the bootstrap name registry (create_ipc_endpoint +
|
||||
/// ipc_register/ipc_lookup). Small integers, so no string interning is needed
|
||||
/// during bring-up. The VFS server registers under `vfs`; clients look it up.
|
||||
pub const ServiceId = enum(u32) {
|
||||
vfs = 1, // RETIRED: the router moved into the kernel (fs_resolve); the slot stays reserved
|
||||
input = 2,
|
||||
ps2_bus = 3, // the 8042 owner; child device drivers attach here for raw bytes
|
||||
device_manager = 4, // the tree, the matcher, the supervisor (docs/device-manager.md)
|
||||
power = 5, // system power: events (button, lid, battery) + shutdown (docs/power.md; domain-named per docs/discovery.md — the acpi service registers it on x86, a PSCI service will on ARM)
|
||||
usb_bus = 6, // the xHCI host-controller driver's transfer endpoint; USB class drivers look it up and `callCap`-open their device to get a private per-device transfer channel (docs/driver-model.md)
|
||||
block = 7, // a block-device driver (USB mass storage today): read/write of fixed-size blocks, the storage a filesystem sits on
|
||||
fat = 8, // the FAT filesystem server; the VFS mounts it and forwards paths under its mount point (/mnt/usb) to it
|
||||
display = 9, // the display service: owns the framebuffer, composites a layer stack, presents frames (docs/display.md)
|
||||
shared_memory_test = 10, // the shared-memory test server (V2): a client passes it a shared-memory capability, it maps + verifies (docs/display-v2.md)
|
||||
scanout = 11, // a native scanout driver (virtio-gpu): the compositor finds it here to upgrade off the GOP framebuffer (docs/display-v2.md)
|
||||
_,
|
||||
};
|
||||
// The `ServiceId` enum lived here: a flat, compile-time list of well-known
|
||||
// service ids backed by a 16-slot kernel table. It is gone with the protocol
|
||||
// namespace — names are strings resolved under `/protocol` at run time, so a
|
||||
// third-party program can introduce a contract the ABI never heard of, and the
|
||||
// registrar (init) decides who may claim one.
|
||||
|
||||
/// Protection flags for `mmap` (matching the usual C bit values).
|
||||
pub const prot_read: u64 = 1;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# /etc/devices.csv — the device→driver registry.
|
||||
# /system/configuration/devices.csv — the device→driver registry.
|
||||
#
|
||||
# The device manager reads this at boot and binds each device a bus driver
|
||||
# reports to the driver named here. It is AUTHORITATIVE: a device that no row
|
||||
|
500 Internal Server Error
An error occurred: An error occurred Gitea Version: 28.1.0 |