Compare commits
211
Commits
cacbacd76b
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4037e746aa | ||
|
|
4dfb5012c0 | ||
|
|
061eb7c004 | ||
|
|
5dc966838a | ||
|
|
700452dc4e | ||
|
|
0faa0fd21b | ||
|
|
c47215821c | ||
|
|
6ddb08091d | ||
|
|
77b64229c2 | ||
|
|
90906bcefe | ||
|
|
2c2745e9e5 | ||
|
|
2a6d604577 | ||
|
|
e81a4e6f1d | ||
|
|
e240341bfb | ||
|
|
62eb2a748a | ||
|
|
56bd2e7678 | ||
|
|
0b25cd2c94 | ||
|
|
d59279422e | ||
|
|
bf9f8560c6 | ||
|
|
da7dcce64e | ||
|
|
9750db14da | ||
|
|
b2a5a0a3c6 | ||
|
|
7efe7b72d8 | ||
|
|
d4b544d66b | ||
|
|
6d4992ae02 | ||
|
|
df61693065 | ||
|
|
f1e79d0eeb | ||
|
|
167e9c7a9e | ||
|
|
5bfdb75e12 | ||
|
|
3fb8a9b96f | ||
|
|
ea8ccf65d0 | ||
|
|
aca3d5855a | ||
|
|
5637d0e5fc | ||
|
|
48ab12e262 | ||
|
|
020e31bc8f | ||
|
|
c81120ef0f | ||
|
|
4f9196c03e | ||
|
|
eff95416d0 | ||
|
|
addd264880 | ||
|
|
fca41b351e | ||
|
|
bf0595763e | ||
|
|
8216be991d | ||
|
|
68e65803eb | ||
|
|
af47d41989 | ||
|
|
5e89b111cf | ||
|
|
e3ec9fa668 | ||
|
|
9e67a74232 | ||
|
|
b9058fe020 | ||
|
|
7c6ed2ca09 | ||
|
|
a67a7015bf | ||
|
|
301bdcaf5b | ||
|
|
d56b1b81c0 | ||
|
|
bc67771bfd | ||
|
|
89d4592777 | ||
|
|
7af65697cc | ||
|
|
73fbbd3922 | ||
|
|
c37402891a | ||
|
|
f1bdce25e0 | ||
|
|
7ea54a84e5 | ||
|
|
d63a008148 | ||
|
|
b59f981c58 | ||
|
|
60b41c0e82 | ||
|
|
451abba000 | ||
|
|
9da63e81e2 | ||
|
|
ada251150a | ||
|
|
728b436d0f | ||
|
|
092817ba2e | ||
|
|
a44b397bed | ||
|
|
fa54ef6915 | ||
|
|
fae616fa5a | ||
|
|
5a8a2a4d7e | ||
|
|
d4f8dc51b9 | ||
|
|
36ca3f98b3 | ||
|
|
c3604429d4 | ||
|
|
77e7001878 | ||
|
|
a6a3402d92 | ||
|
|
d565a6b845 | ||
|
|
4a2df587bb | ||
|
|
3c9f454398 | ||
|
|
8710944a92 | ||
|
|
1d7850239d | ||
|
|
d603d40b5c | ||
|
|
77fe4d220e | ||
|
|
0d5a7394ef | ||
|
|
5930c9653c | ||
|
|
981ff7cd25 | ||
|
|
5cca580066 | ||
|
|
35f43057f4 | ||
|
|
72807c20e4 | ||
|
|
0eb2420690 | ||
|
|
df9c1ed827 | ||
|
|
ba195fa0a2 | ||
|
|
1a1d92cba9 | ||
|
|
4ca57fc37e | ||
|
|
ca1126537d | ||
|
|
337b981c07 | ||
|
|
b7d97ebb5d | ||
|
|
6b3a381626 | ||
|
|
7d8aa51234 | ||
|
|
3ae541214f | ||
|
|
2ebfccc8ed | ||
|
|
f23f073624 | ||
|
|
637bf2e0b1 | ||
|
|
cb8d1e2e51 | ||
|
|
8b628a4a7d | ||
|
|
a5840789dd | ||
|
|
f7151ed577 | ||
|
|
5492607a61 | ||
|
|
81dd1e9318 | ||
|
|
a2d6056772 | ||
|
|
33376f24ab | ||
|
|
3111c7c5e6 | ||
|
|
547d0ec46b | ||
|
|
5ad42ceac3 | ||
|
|
8e388e048a | ||
|
|
ef793d1320 | ||
|
|
139c4f624f | ||
|
|
3b24b541b0 | ||
|
|
5d55217212 | ||
|
|
729b40ece7 | ||
|
|
6328823ef1 | ||
|
|
69fbef40c0 | ||
|
|
f4eb88e7d2 | ||
|
|
568823a4fb | ||
|
|
4398eb7cc4 | ||
|
|
a86559648e | ||
|
|
7db5fba884 | ||
|
|
a85f29edc9 | ||
|
|
5a5146ec13 | ||
|
|
1365a245ba | ||
|
|
cb30faf15f | ||
|
|
ec154a975f | ||
|
|
36a7cc5fe9 | ||
|
|
b3011fbb40 | ||
|
|
1b1c587c14 | ||
|
|
776b04184e | ||
|
|
2719b93530 | ||
|
|
e250d8cd79 | ||
|
|
d2dfbcabf8 | ||
|
|
b004b9c3eb | ||
|
|
3e6e21bf0a | ||
|
|
0fbd2c8f12 | ||
|
|
73aea4582b | ||
|
|
1379b699f3 | ||
|
|
1ff0991452 | ||
|
|
ac01f627d1 | ||
|
|
f3bc23cb81 | ||
|
|
8d4a7cf240 | ||
|
|
c4f16a5448 | ||
|
|
e4da4e0610 | ||
|
|
9a3238025d | ||
|
|
c96ef87714 | ||
|
|
de9870175f | ||
|
|
be04ebe954 | ||
|
|
62d6a7a150 | ||
|
|
fa8203cdba | ||
|
|
e53d6ebafb | ||
|
|
4476208361 | ||
|
|
c621b649f6 | ||
|
|
d27670ec39 | ||
|
|
ab7594df6e | ||
|
|
d03942b543 | ||
|
|
3f9b6813f7 | ||
|
|
bc2eb67581 | ||
|
|
cb98a9844e | ||
|
|
4701fbd123 | ||
|
|
3b23b11b0e | ||
|
|
902e4a0a9e | ||
|
|
15575960bd | ||
|
|
6f4fdc2789 | ||
|
|
721288c516 | ||
|
|
4194bb6e32 | ||
|
|
fc0b934b7f | ||
|
|
6a687fbc2b | ||
|
|
4e7cbc9792 | ||
|
|
e94adcfc02 | ||
|
|
f477ef7d9f | ||
|
|
9e649178bf | ||
|
|
e376c9e908 | ||
|
|
48b9ed4001 | ||
|
|
081ba1d74e | ||
|
|
203528c8a7 | ||
|
|
bf0c3fd3e0 | ||
|
|
3af0110483 | ||
|
|
757c6f14c3 | ||
|
|
52d6e372fd | ||
|
|
f023f1cfd6 | ||
|
|
b9cec7d1be | ||
|
|
6271278d4d | ||
|
|
37326c7664 | ||
|
|
23bcd77c58 | ||
|
|
dded46726b | ||
|
|
60f32ee9ff | ||
|
|
3e69712b97 | ||
|
|
11f567ee20 | ||
|
|
3a155cdc7d | ||
|
|
5b874fc756 | ||
|
|
7d540c4b2f | ||
|
|
ac2d102878 | ||
|
|
3c9475e33a | ||
|
|
44122bd44d | ||
|
|
9ef22d6e55 | ||
|
|
07c901c18c | ||
|
|
25cc4d610e | ||
|
|
f90dc6c121 | ||
|
|
1d1234c963 | ||
|
|
a7f0c1a450 | ||
|
|
f86f2987d5 | ||
|
|
794a8b5782 | ||
|
|
ea470afe84 | ||
|
|
d27377ab1e |
No files matched your search
@@ -52,7 +52,8 @@ zig build
|
|||||||
Produces a FHS-shaped `zig-out/` that *is* the danos filesystem and the boot volume:
|
Produces a FHS-shaped `zig-out/` that *is* the danos filesystem and the boot volume:
|
||||||
the UEFI bootloader at `zig-out/EFI/BOOT/BOOTX64.efi`, the kernel at
|
the UEFI bootloader at `zig-out/EFI/BOOT/BOOTX64.efi`, the kernel at
|
||||||
`zig-out/system/kernel`, init at `zig-out/system/services/init`, drivers under
|
`zig-out/system/kernel`, init at `zig-out/system/services/init`, drivers under
|
||||||
`zig-out/system/drivers/`, and the initial-ramdisk at `zig-out/boot/`.
|
`zig-out/system/drivers/`, the test fixtures under `zig-out/test/system/services/`,
|
||||||
|
and the initial-ramdisk at `zig-out/boot/`.
|
||||||
|
|
||||||
## Release media
|
## Release media
|
||||||
|
|
||||||
@@ -62,7 +63,7 @@ zig build release-x86-64
|
|||||||
|
|
||||||
Produces `zig-out/danos-x86-64.iso`, a hybrid ISO that boots flashed raw to a
|
Produces `zig-out/danos-x86-64.iso`, a hybrid ISO that boots flashed raw to a
|
||||||
USB stick (balenaEtcher, dd) or burned to optical media — see
|
USB stick (balenaEtcher, dd) or burned to optical media — see
|
||||||
[docs/release-iso.md](docs/release-iso.md). `zig build check-iso-image`
|
[docs/release-iso.md](docs/os-development/release-iso.md). `zig build check-iso-image`
|
||||||
validates it without booting.
|
validates it without booting.
|
||||||
|
|
||||||
## Run
|
## Run
|
||||||
|
|||||||
+22
-14
@@ -16,11 +16,12 @@ const MemoryMapSlice = uefi.tables.MemoryMapSlice;
|
|||||||
/// The kernel image: /system/kernel.
|
/// The kernel image: /system/kernel.
|
||||||
const kernel_file_name = std.unicode.utf8ToUtf16LeStringLiteral("system\\kernel");
|
const kernel_file_name = std.unicode.utf8ToUtf16LeStringLiteral("system\\kernel");
|
||||||
|
|
||||||
/// The user binaries: everything under /system except the kernel itself. The
|
/// The user binaries: everything under /system except the kernel itself, plus
|
||||||
/// loader walks this tree and packs it into the in-RAM initial_ramdisk image —
|
/// the test fixtures under /test. The loader walks both trees and packs them
|
||||||
/// the volume's file structure is the single source of truth (no packed image
|
/// into the in-RAM initial_ramdisk image — the volume's file structure is the
|
||||||
/// artifact on disk).
|
/// single source of truth (no packed image artifact on disk).
|
||||||
const system_directory_name = std.unicode.utf8ToUtf16LeStringLiteral("system");
|
const system_directory_name = std.unicode.utf8ToUtf16LeStringLiteral("system");
|
||||||
|
const test_directory_name = std.unicode.utf8ToUtf16LeStringLiteral("test");
|
||||||
|
|
||||||
/// Physical page size, and the sentinel UEFI uses to seek to end-of-file.
|
/// Physical page size, and the sentinel UEFI uses to seek to end-of-file.
|
||||||
const page_size = 4096;
|
const page_size = 4096;
|
||||||
@@ -364,16 +365,17 @@ fn handoff(cr3: u64, entry: usize, boot_information: *const BootInformation) nor
|
|||||||
unreachable;
|
unreachable;
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- the /system tree -> initial_ramdisk ------------------------------------
|
// --- the /system and /test trees -> initial_ramdisk --------------------------
|
||||||
|
|
||||||
/// Cap on bundled binaries. Generous: the tree carries ~30 today.
|
/// Cap on bundled binaries. Generous: the tree carries ~30 today.
|
||||||
const maximum_bundled = 64;
|
const maximum_bundled = 64;
|
||||||
|
|
||||||
/// How deep the walk goes below /system ("/system/services/x" is depth 1).
|
/// How deep the walk goes below a tree root ("/system/services/x" is depth 1,
|
||||||
|
/// "/test/system/services/x" is depth 2).
|
||||||
const maximum_tree_depth = 3;
|
const maximum_tree_depth = 3;
|
||||||
|
|
||||||
/// One binary discovered under /system: its FHS path (UTF-8, '/'-separated,
|
/// One binary discovered under a walked tree: its FHS path (UTF-8,
|
||||||
/// NUL-free) and its contents in a transient pool buffer.
|
/// '/'-separated, NUL-free) and its contents in a transient pool buffer.
|
||||||
const Bundled = struct {
|
const Bundled = struct {
|
||||||
path: [initial_ramdisk.maximum_name]u8,
|
path: [initial_ramdisk.maximum_name]u8,
|
||||||
path_len: usize,
|
path_len: usize,
|
||||||
@@ -389,10 +391,10 @@ const Bundled = struct {
|
|||||||
/// 1. /system/manifest (written by the build): each listed path is opened BY
|
/// 1. /system/manifest (written by the build): each listed path is opened BY
|
||||||
/// NAME — the case-insensitive lookup every firmware FAT driver gets
|
/// NAME — the case-insensitive lookup every firmware FAT driver gets
|
||||||
/// right, and the only file access the pre-tree loader ever used.
|
/// right, and the only file access the pre-tree loader ever used.
|
||||||
/// 2. No manifest: ENUMERATE the /system tree. Portable in principle, but
|
/// 2. No manifest: ENUMERATE the /system and /test trees. Portable in
|
||||||
/// firmware differs in what names enumeration returns (bare 8.3 entries
|
/// principle, but firmware differs in what names enumeration returns
|
||||||
/// come back uppercase on some drivers), so this is the fallback for
|
/// (bare 8.3 entries come back uppercase on some drivers), so this is
|
||||||
/// hand-assembled sticks, not the primary path.
|
/// the fallback for hand-assembled sticks, not the primary path.
|
||||||
fn loadSystemTree(bs: *uefi.tables.BootServices, boot_information: *BootInformation) !void {
|
fn loadSystemTree(bs: *uefi.tables.BootServices, boot_information: *BootInformation) !void {
|
||||||
const loaded = (try bs.handleProtocol(uefi.protocol.LoadedImage, uefi.handle)) orelse
|
const loaded = (try bs.handleProtocol(uefi.protocol.LoadedImage, uefi.handle)) orelse
|
||||||
return error.NoLoadedImage;
|
return error.NoLoadedImage;
|
||||||
@@ -426,6 +428,11 @@ fn loadSystemTree(bs: *uefi.tables.BootServices, boot_information: *BootInformat
|
|||||||
const system_directory = try root.open(system_directory_name, .read, .{});
|
const system_directory = try root.open(system_directory_name, .read, .{});
|
||||||
defer _ = system_directory.close() catch {};
|
defer _ = system_directory.close() catch {};
|
||||||
try walkDirectory(bs, system_directory, "/system", 0, &list, &count);
|
try walkDirectory(bs, system_directory, "/system", 0, &list, &count);
|
||||||
|
// The /test tree is optional: a stick without fixtures still boots.
|
||||||
|
if (root.open(test_directory_name, .read, .{})) |test_directory| {
|
||||||
|
defer _ = test_directory.close() catch {};
|
||||||
|
try walkDirectory(bs, test_directory, "/test", 0, &list, &count);
|
||||||
|
} else |_| {}
|
||||||
}
|
}
|
||||||
if (count == 0) return error.NoBinaries;
|
if (count == 0) return error.NoBinaries;
|
||||||
|
|
||||||
@@ -452,7 +459,7 @@ fn loadSystemTree(bs: *uefi.tables.BootServices, boot_information: *BootInformat
|
|||||||
|
|
||||||
boot_information.initial_ramdisk_base = @intFromPtr(image.ptr);
|
boot_information.initial_ramdisk_base = @intFromPtr(image.ptr);
|
||||||
boot_information.initial_ramdisk_len = total;
|
boot_information.initial_ramdisk_len = total;
|
||||||
log("EFI: /system tree loaded, starting the kernel\r\n");
|
log("EFI: boot tree loaded, starting the kernel\r\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The boot capsule: the bundled binaries as one v2 initial_ramdisk image.
|
/// The boot capsule: the bundled binaries as one v2 initial_ramdisk image.
|
||||||
@@ -522,7 +529,8 @@ fn loadByManifest(bs: *uefi.tables.BootServices, root: *uefi.protocol.File, list
|
|||||||
|
|
||||||
/// Recursively collect the regular files below `directory` into `list`. Top-level
|
/// Recursively collect the regular files below `directory` into `list`. Top-level
|
||||||
/// files (depth 0) are skipped: the only one is /system/kernel, which loadKernel
|
/// files (depth 0) are skipped: the only one is /system/kernel, which loadKernel
|
||||||
/// has already consumed and which is not a spawnable user binary.
|
/// has already consumed and which is not a spawnable user binary (/test has no
|
||||||
|
/// top-level files, so the skip is a no-op there).
|
||||||
fn walkDirectory(
|
fn walkDirectory(
|
||||||
bs: *uefi.tables.BootServices,
|
bs: *uefi.tables.BootServices,
|
||||||
directory: *uefi.protocol.File,
|
directory: *uefi.protocol.File,
|
||||||
|
|||||||
@@ -0,0 +1,131 @@
|
|||||||
|
//! The danos build API (docs/build-packages-plan.md): the one shared recipe
|
||||||
|
//! for building a user-space binary. A binary package's build.zig names its
|
||||||
|
//! binary and EXACTLY the modules its source imports — the moral equivalent
|
||||||
|
//! of a C file's include list — and `userBinary` resolves each name from the
|
||||||
|
//! library domain package that exports it. Nothing is pre-wired: an @import
|
||||||
|
//! the package did not declare is a compile error, and a domain none of the
|
||||||
|
//! imports come from never appears in the package's manifest. The only
|
||||||
|
//! implicit dependency is the kernel package, because the shared root shim
|
||||||
|
//! (root.zig, user.ld) lives there and itself reaches start + logging.
|
||||||
|
//!
|
||||||
|
//! Consumers declare this package in their build.zig.zon (as "build-support")
|
||||||
|
//! and @import its build.zig from their own build.zig; nothing is compiled
|
||||||
|
//! from this package itself — it exports build-time functions only.
|
||||||
|
|
||||||
|
const std = @import("std");
|
||||||
|
|
||||||
|
pub fn build(b: *std.Build) void {
|
||||||
|
_ = b; // nothing to build: this package exports build-time functions only
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The freestanding x86-64 target every danos binary (kernel and user) is
|
||||||
|
/// built for. SSE2 is part of the x86_64 baseline and UEFI leaves it enabled
|
||||||
|
/// at handoff, so we keep it: disabling it forces soft-float and makes the
|
||||||
|
/// compiler unable to encode the vector ops that std's formatting/runtime
|
||||||
|
/// still emit.
|
||||||
|
pub fn freestandingTarget(b: *std.Build) std.Build.ResolvedTarget {
|
||||||
|
return b.resolveTargetQuery(.{
|
||||||
|
.cpu_arch = .x86_64,
|
||||||
|
.os_tag = .freestanding,
|
||||||
|
.abi = .none,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolve one imported module by searching the packages this binary DECLARED
|
||||||
|
/// in its own build.zig.zon — the C include path made literal: an import can
|
||||||
|
/// only be satisfied by a domain the binary claims, and each domain's own
|
||||||
|
/// build.zig (its addModule exports) is the single statement of who owns
|
||||||
|
/// what. There is no name table here to drift.
|
||||||
|
fn moduleFromDeclaredDependencies(b: *std.Build, name: []const u8) *std.Build.Module {
|
||||||
|
for (b.available_deps) |declared| {
|
||||||
|
const dependency = b.dependency(declared[0], .{});
|
||||||
|
if (dependency.builder.modules.get(name)) |module| return module;
|
||||||
|
}
|
||||||
|
@panic(b.fmt(
|
||||||
|
"no declared dependency exports a module named '{s}' — declare the domain that owns it in this package's build.zig.zon",
|
||||||
|
.{name},
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What `userBinary` needs to know about one user binary.
|
||||||
|
pub const UserBinaryOptions = struct {
|
||||||
|
name: []const u8,
|
||||||
|
/// The program's own source file — it becomes the `program` module the
|
||||||
|
/// root shim imports; a program only defines `pub fn main`.
|
||||||
|
root_source_file: std.Build.LazyPath,
|
||||||
|
/// Exactly the modules the program's source @imports (directly or through
|
||||||
|
/// its same-directory files) — no more, no less. Order is free; sorted
|
||||||
|
/// reads best. An undeclared @import fails the compile; a name no
|
||||||
|
/// declared domain exports fails the build graph, naming the miss.
|
||||||
|
imports: []const []const u8,
|
||||||
|
/// Built multi-threaded (`single_threaded = false`) so real atomics/TLS
|
||||||
|
/// work — required before a binary may call `Thread.spawn`
|
||||||
|
/// (docs/threading.md). Threads are a deliberate per-binary opt-in.
|
||||||
|
threaded: bool = false,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Build one user-space binary the same way for every program (init, the
|
||||||
|
/// services, the drivers): freestanding, ReleaseSmall, `.large` code model
|
||||||
|
/// (the image base is above 4 GiB — smaller models emit 32-bit relocations
|
||||||
|
/// that can't reach), linked with the shared user link script. Pinned to
|
||||||
|
/// LLVM + LLD so the script's PHDRS (segment permissions) are authoritative —
|
||||||
|
/// the kernel's W^X user-ELF loader requires exact perms.
|
||||||
|
///
|
||||||
|
/// The compilation root is not the program's own file but the shared shim
|
||||||
|
/// (the kernel package's root.zig), which supplies the root declarations
|
||||||
|
/// (`main` re-export, panic handler, `_start` pull) so a program only defines
|
||||||
|
/// `pub fn main`. The program's file becomes the `program` module the shim
|
||||||
|
/// imports; reach it through `programModule` to add per-binary non-library
|
||||||
|
/// modules (compile-time options).
|
||||||
|
pub fn userBinary(b: *std.Build, options: UserBinaryOptions) *std.Build.Step.Compile {
|
||||||
|
const kernel = b.dependency("kernel", .{});
|
||||||
|
var imports: std.ArrayListUnmanaged(std.Build.Module.Import) = .empty;
|
||||||
|
for (options.imports) |name| {
|
||||||
|
imports.append(b.allocator, .{
|
||||||
|
.name = name,
|
||||||
|
.module = moduleFromDeclaredDependencies(b, name),
|
||||||
|
}) catch @panic("OOM");
|
||||||
|
}
|
||||||
|
// Settings (target, optimize, code model, ...) live on the root module
|
||||||
|
// only; the program module inherits them.
|
||||||
|
const program_module = b.createModule(.{
|
||||||
|
.root_source_file = options.root_source_file,
|
||||||
|
.imports = imports.items,
|
||||||
|
});
|
||||||
|
const exe = b.addExecutable(.{
|
||||||
|
.name = options.name,
|
||||||
|
.root_module = b.createModule(.{
|
||||||
|
.root_source_file = kernel.path("root.zig"),
|
||||||
|
.target = freestandingTarget(b),
|
||||||
|
.optimize = .ReleaseSmall,
|
||||||
|
.code_model = .large,
|
||||||
|
.single_threaded = !options.threaded, // a threaded binary needs real atomics/TLS
|
||||||
|
.sanitize_c = .off,
|
||||||
|
.stack_check = false,
|
||||||
|
.stack_protector = false,
|
||||||
|
// The root shim itself imports only start (_start + panic) and
|
||||||
|
// logging (std_options) — straight from the kernel package, so a
|
||||||
|
// program's own import list stays exactly its own.
|
||||||
|
.imports = &.{
|
||||||
|
.{ .name = "start", .module = kernel.module("start") },
|
||||||
|
.{ .name = "logging", .module = kernel.module("logging") },
|
||||||
|
.{ .name = "program", .module = program_module },
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
exe.setLinkerScript(kernel.path("user.ld"));
|
||||||
|
exe.entry = .{ .symbol_name = "_start" };
|
||||||
|
exe.image_base = 0x7000_0000_0000;
|
||||||
|
exe.use_llvm = true;
|
||||||
|
exe.use_lld = true;
|
||||||
|
return exe;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `program` module of a binary built by `userBinary` — the module rooted
|
||||||
|
/// at the program's own source file. Per-binary non-library modules (an
|
||||||
|
/// addOptions build_options) go here, not on the root shim: module imports
|
||||||
|
/// are not transitive, so an import added to the root would be invisible to
|
||||||
|
/// the program's code.
|
||||||
|
pub fn programModule(exe: *std.Build.Step.Compile) *std.Build.Module {
|
||||||
|
return exe.root_module.import_table.get("program").?;
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
.{
|
||||||
|
.name = .build_support,
|
||||||
|
.version = "0.0.0",
|
||||||
|
.fingerprint = 0xad91962994f4be41, // Changing this has security and trust implications.
|
||||||
|
.minimum_zig_version = "0.16.0",
|
||||||
|
.dependencies = .{},
|
||||||
|
.paths = .{""},
|
||||||
|
}
|
||||||
+53
-8
@@ -32,6 +32,58 @@
|
|||||||
// Once all dependencies are fetched, `zig build` no longer requires
|
// Once all dependencies are fetched, `zig build` no longer requires
|
||||||
// internet connectivity.
|
// internet connectivity.
|
||||||
.dependencies = .{
|
.dependencies = .{
|
||||||
|
// The danos build API — the shared user-binary recipe every build file
|
||||||
|
// (root and per-binary packages) consumes (docs/build-packages-plan.md).
|
||||||
|
.@"build-support" = .{ .path = "build-support" },
|
||||||
|
// The library domains, each a package exporting its modules.
|
||||||
|
.kernel = .{ .path = "library/kernel" },
|
||||||
|
.device = .{ .path = "library/device" },
|
||||||
|
.client = .{ .path = "library/client" },
|
||||||
|
.protocol = .{ .path = "library/protocol" },
|
||||||
|
.csv = .{ .path = "library/csv" },
|
||||||
|
.@"xkeyboard-config" = .{ .path = "library/xkeyboard-config" },
|
||||||
|
// Binary packages (phase 2), consumed as artifacts for the boot image.
|
||||||
|
.@"pci-bus" = .{ .path = "system/drivers/pci-bus" },
|
||||||
|
.init = .{ .path = "system/services/init" },
|
||||||
|
.fat = .{ .path = "system/services/fat" },
|
||||||
|
.exfat = .{ .path = "system/services/exfat" },
|
||||||
|
.display = .{ .path = "system/services/display" },
|
||||||
|
.@"display-demo" = .{ .path = "system/services/display-demo" },
|
||||||
|
.@"device-manager" = .{ .path = "system/services/device-manager" },
|
||||||
|
.@"volume-manager" = .{ .path = "system/services/volume-manager" },
|
||||||
|
.input = .{ .path = "system/services/input" },
|
||||||
|
.logger = .{ .path = "system/services/logger" },
|
||||||
|
// The discovery pair and the /test fixtures are lazy: only what a
|
||||||
|
// given build actually ships gets its build file loaded and compiled
|
||||||
|
// (-Ddiscovery picks one of the pair; -Dtest-case pulls the fixtures).
|
||||||
|
.acpi = .{ .path = "system/services/acpi", .lazy = true },
|
||||||
|
.fdt = .{ .path = "system/services/fdt", .lazy = true },
|
||||||
|
.@"ps2-bus" = .{ .path = "system/drivers/ps2-bus" },
|
||||||
|
.@"usb-xhci-bus" = .{ .path = "system/drivers/usb-xhci-bus" },
|
||||||
|
.@"usb-hid" = .{ .path = "system/drivers/usb-hid" },
|
||||||
|
.@"usb-storage" = .{ .path = "system/drivers/usb-storage" },
|
||||||
|
.@"virtio-gpu" = .{ .path = "system/drivers/virtio-gpu" },
|
||||||
|
.@"vfs-test" = .{ .path = "test/system/services/vfs-test", .lazy = true },
|
||||||
|
.@"fat-test" = .{ .path = "test/system/services/fat-test", .lazy = true },
|
||||||
|
.@"exfat-test" = .{ .path = "test/system/services/exfat-test", .lazy = true },
|
||||||
|
.@"badge-scope-test" = .{ .path = "test/system/services/badge-scope-test", .lazy = true },
|
||||||
|
.@"shared-memory-server" = .{ .path = "test/system/services/shared-memory-server", .lazy = true },
|
||||||
|
.@"shared-memory-client" = .{ .path = "test/system/services/shared-memory-client", .lazy = true },
|
||||||
|
.@"crash-test" = .{ .path = "test/system/services/crash-test", .lazy = true },
|
||||||
|
.@"device-list" = .{ .path = "test/system/services/device-list", .lazy = true },
|
||||||
|
.@"pci-cap-test" = .{ .path = "test/system/services/pci-cap-test", .lazy = true },
|
||||||
|
.@"iommu-fault-test" = .{ .path = "test/system/services/iommu-fault-test", .lazy = true },
|
||||||
|
.@"input-source" = .{ .path = "test/system/services/input-source", .lazy = true },
|
||||||
|
.@"input-test" = .{ .path = "test/system/services/input-test", .lazy = true },
|
||||||
|
.@"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 },
|
||||||
|
.@"protocol-conformance-test" = .{ .path = "test/system/services/protocol-conformance-test", .lazy = true },
|
||||||
|
.@"device-authority-test" = .{ .path = "test/system/services/device-authority-test", .lazy = true },
|
||||||
|
.@"block-range-test" = .{ .path = "test/system/services/block-range-test", .lazy = true },
|
||||||
// See `zig fetch --save <url>` for a command-line interface for adding dependencies.
|
// See `zig fetch --save <url>` for a command-line interface for adding dependencies.
|
||||||
//.example = .{
|
//.example = .{
|
||||||
// // When updating this field to a new URL, be sure to delete the corresponding
|
// // When updating this field to a new URL, be sure to delete the corresponding
|
||||||
@@ -70,12 +122,5 @@
|
|||||||
// Paths are relative to the build root. Use the empty string (`""`) to refer to
|
// Paths are relative to the build root. Use the empty string (`""`) to refer to
|
||||||
// the build root itself.
|
// the build root itself.
|
||||||
// A directory listed here means that all files within, recursively, are included.
|
// A directory listed here means that all files within, recursively, are included.
|
||||||
.paths = .{
|
.paths = .{""},
|
||||||
"build.zig",
|
|
||||||
"build.zig.zon",
|
|
||||||
"src",
|
|
||||||
// For example...
|
|
||||||
//"LICENSE",
|
|
||||||
//"README.md",
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
//! Boot-image assembly (docs/build-packages-plan.md, phase 3): everything
|
||||||
|
//! between "here are the built binaries" and "here is a bootable volume".
|
||||||
|
//! The FHS-shaped zig-out install tree, the boot manifest, the boot capsule,
|
||||||
|
//! the FAT32 USB image (+ its serial-enabled twin for the QEMU run steps),
|
||||||
|
//! and the release ISO — with their check steps. The root build.zig decides
|
||||||
|
//! WHAT ships (the bundled list); this file owns HOW it becomes an image.
|
||||||
|
|
||||||
|
const std = @import("std");
|
||||||
|
|
||||||
|
/// One user binary and its FHS home on the boot volume (and in zig-out).
|
||||||
|
pub const BundledBinary = struct { path: []const u8, binary: std.Build.LazyPath };
|
||||||
|
|
||||||
|
pub const Options = struct {
|
||||||
|
/// The installed/flashable kernel (serial follows the root -Dserial).
|
||||||
|
kernel: *std.Build.Step.Compile,
|
||||||
|
/// The serial-enabled kernel variant the `run-x86-64` image boots.
|
||||||
|
kernel_serial: *std.Build.Step.Compile,
|
||||||
|
/// The UEFI loader (BOOTX64).
|
||||||
|
efi: *std.Build.Step.Compile,
|
||||||
|
/// Every user binary and data file at its FHS path.
|
||||||
|
bundled: []const BundledBinary,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Wire up the install tree, both FAT32 boot images, the release ISO, and the
|
||||||
|
/// check steps. Returns the serial-enabled FAT image for the QEMU run steps.
|
||||||
|
pub fn addImageSteps(b: *std.Build, options: Options) std.Build.LazyPath {
|
||||||
|
// Everything installs into a FHS-shaped zig-out: it IS the danos filesystem *and*
|
||||||
|
// the boot volume. Each binary lands at its addressed, leaf-collapsed path — the
|
||||||
|
// kernel at zig-out/system/kernel (from system/kernel/kernel.zig), init at
|
||||||
|
// zig-out/system/services/init, and so on (see docs/README.md). The bootloader
|
||||||
|
// then loads these FHS paths off the volume.
|
||||||
|
const kernel_install = b.addInstallArtifact(options.kernel, .{ .dest_dir = .{ .override = .{ .custom = "system" } } });
|
||||||
|
b.getInstallStep().dependOn(&kernel_install.step);
|
||||||
|
|
||||||
|
// UEFI firmware requires the removable-media loader at exactly \EFI\BOOT\BOOTX64.efi,
|
||||||
|
// so that path is fixed by the firmware (it is /boot's EFI stub, conceptually).
|
||||||
|
const efi_install = b.addInstallArtifact(options.efi, .{ .dest_dir = .{ .override = .{ .custom = "EFI/BOOT" } } });
|
||||||
|
b.getInstallStep().dependOn(&efi_install.step);
|
||||||
|
|
||||||
|
// The boot manifest: the FHS path of every bundled binary, one per line. The
|
||||||
|
// EFI loader reads THIS by name and opens each listed path by name — FAT
|
||||||
|
// name lookup is case-insensitive and firmware-portable, unlike directory
|
||||||
|
// ENUMERATION, whose returned names vary by firmware (bare 8.3 entries come
|
||||||
|
// back uppercase on some FAT drivers). The tree walk remains only as the
|
||||||
|
// loader's fallback for hand-assembled sticks without a manifest.
|
||||||
|
var manifest_text: std.ArrayListUnmanaged(u8) = .empty;
|
||||||
|
for (options.bundled) |item| {
|
||||||
|
manifest_text.append(b.allocator, '/') catch @panic("OOM");
|
||||||
|
manifest_text.appendSlice(b.allocator, item.path) catch @panic("OOM");
|
||||||
|
manifest_text.append(b.allocator, '\n') catch @panic("OOM");
|
||||||
|
}
|
||||||
|
const manifest_files = b.addWriteFiles();
|
||||||
|
const manifest_file = manifest_files.add("manifest", manifest_text.items);
|
||||||
|
const manifest_install = b.addInstallFileWithDir(manifest_file, .prefix, "system/manifest");
|
||||||
|
b.getInstallStep().dependOn(&manifest_install.step);
|
||||||
|
|
||||||
|
// The boot capsule: the same bundled list packed into ONE file (v2
|
||||||
|
// initial_ramdisk format), because a single open + sequential read is the
|
||||||
|
// only firmware file I/O shape that is fast everywhere — a per-file tree
|
||||||
|
// walk measured MINUTES on real firmware. The loader tries this first,
|
||||||
|
// then the manifest, then the walk; the running system cannot tell the
|
||||||
|
// difference (it always receives the same in-RAM table). Derived from the
|
||||||
|
// tree in the same build graph, so the two cannot drift.
|
||||||
|
const mk_capsule = b.addSystemCommand(&.{"python3"});
|
||||||
|
mk_capsule.addFileArg(b.path("tools/pack-system-image.py"));
|
||||||
|
const capsule_img = mk_capsule.addOutputFileArg("system.img");
|
||||||
|
for (options.bundled) |item| {
|
||||||
|
mk_capsule.addArg(item.path);
|
||||||
|
mk_capsule.addFileArg(item.binary);
|
||||||
|
}
|
||||||
|
const capsule_install = b.addInstallFile(capsule_img, "boot/system.img");
|
||||||
|
b.getInstallStep().dependOn(&capsule_install.step);
|
||||||
|
|
||||||
|
// Install every bundled binary to its FHS home, so zig-out is a true image of
|
||||||
|
// the filesystem — the same tree make-fat-image.py lays out on the boot volume.
|
||||||
|
for (options.bundled) |item| {
|
||||||
|
const install = b.addInstallFileWithDir(item.binary, .prefix, item.path);
|
||||||
|
b.getInstallStep().dependOn(&install.step);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- danos-usb.img: the bootable FAT32 USB image ---
|
||||||
|
// Format a real FAT32 image (the in-repo Python builder, no external tools)
|
||||||
|
// 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 /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);
|
||||||
|
|
||||||
|
// The image `run-x86-64` boots: identical to the flashable one but with the
|
||||||
|
// serial log sink compiled in, so a developer always gets the machine-readable
|
||||||
|
// log captured to serial0 — without baking serial into the image users flash.
|
||||||
|
// Built lazily (only when `run-x86-64` is requested), and never installed.
|
||||||
|
const fat_image_serial = addBootImage(b, options.kernel_serial.getEmittedBin(), options.efi.getEmittedBin(), manifest_file, capsule_img, options.bundled);
|
||||||
|
|
||||||
|
// `zig build check-fat-image` — validate the produced image is a real FAT32
|
||||||
|
// with the EFI stub present (the builder's own --verify, no external tools).
|
||||||
|
const check_fat = b.addSystemCommand(&.{"python3"});
|
||||||
|
check_fat.addFileArg(b.path("tools/make-fat-image.py"));
|
||||||
|
check_fat.addArg("--verify");
|
||||||
|
check_fat.addFileArg(fat_image);
|
||||||
|
const check_fat_step = b.step("check-fat-image", "Verify the FAT32 USB image is valid and bootable");
|
||||||
|
check_fat_step.dependOn(&check_fat.step);
|
||||||
|
|
||||||
|
// --- release-x86-64: danos-x86-64.iso, the flashable release image ---
|
||||||
|
// Wrap the FAT32 boot volume in a hybrid ISO (the in-repo Python builder
|
||||||
|
// again, no xorriso/isohybrid): an ISO9660 whose El Torito EFI boot entry
|
||||||
|
// and MBR ESP partition entry both point at the embedded FAT image. One
|
||||||
|
// file then boots every way release media is consumed — flashed raw to a
|
||||||
|
// USB stick with Etcher or dd, or burned to optical media — while
|
||||||
|
// danos-usb.img stays the raw superfloppy QEMU and the test harness boot.
|
||||||
|
const mk_iso = b.addSystemCommand(&.{"python3"});
|
||||||
|
mk_iso.addFileArg(b.path("tools/make-iso-image.py"));
|
||||||
|
const iso_image = mk_iso.addOutputFileArg("danos-x86-64.iso");
|
||||||
|
mk_iso.addFileArg(fat_image);
|
||||||
|
const iso_install = b.addInstallFile(iso_image, "danos-x86-64.iso");
|
||||||
|
const release_step = b.step("release-x86-64", "Build the flashable x86-64 release ISO (zig-out/danos-x86-64.iso; flash with Etcher or dd)");
|
||||||
|
release_step.dependOn(&iso_install.step);
|
||||||
|
|
||||||
|
// `zig build check-iso-image` — the ISO builder's own --verify (mirroring
|
||||||
|
// check-fat-image): the MBR partition, the El Torito catalog, and the
|
||||||
|
// embedded FAT32 image must all agree.
|
||||||
|
const check_iso = b.addSystemCommand(&.{"python3"});
|
||||||
|
check_iso.addFileArg(b.path("tools/make-iso-image.py"));
|
||||||
|
check_iso.addArg("--verify");
|
||||||
|
check_iso.addFileArg(iso_image);
|
||||||
|
const check_iso_step = b.step("check-iso-image", "Verify the release ISO is a valid hybrid (MBR ESP partition + El Torito EFI entry)");
|
||||||
|
check_iso_step.dependOn(&check_iso.step);
|
||||||
|
|
||||||
|
return fat_image_serial;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Assemble the bootable FAT32 image (the in-repo Python builder) holding the
|
||||||
|
/// EFI stub, the kernel, and every user binary at its FHS path — the volume's
|
||||||
|
/// /system tree IS the system image; the EFI loader walks it at boot and builds
|
||||||
|
/// the in-RAM initial_ramdisk from it. Factored so the serial-enabled
|
||||||
|
/// `run-x86-64` variant can bundle its own serial kernel while sharing the
|
||||||
|
/// loader and user tree (the loader's boot breadcrumbs and init's heartbeat both
|
||||||
|
/// follow the top-level -Dserial). Returns the image's LazyPath.
|
||||||
|
fn addBootImage(
|
||||||
|
b: *std.Build,
|
||||||
|
kernel_bin: std.Build.LazyPath,
|
||||||
|
efi_bin: std.Build.LazyPath,
|
||||||
|
manifest: std.Build.LazyPath,
|
||||||
|
capsule: std.Build.LazyPath,
|
||||||
|
bundled: []const BundledBinary,
|
||||||
|
) std.Build.LazyPath {
|
||||||
|
const mk_fat = b.addSystemCommand(&.{"python3"});
|
||||||
|
mk_fat.addFileArg(b.path("tools/make-fat-image.py"));
|
||||||
|
const fat_image = mk_fat.addOutputFileArg("danos-usb.img");
|
||||||
|
mk_fat.addArg("64"); // MiB
|
||||||
|
mk_fat.addArg("EFI/BOOT/BOOTX64.efi");
|
||||||
|
mk_fat.addFileArg(efi_bin);
|
||||||
|
mk_fat.addArg("system/kernel");
|
||||||
|
mk_fat.addFileArg(kernel_bin);
|
||||||
|
mk_fat.addArg("system/manifest");
|
||||||
|
mk_fat.addFileArg(manifest);
|
||||||
|
mk_fat.addArg("boot/system.img");
|
||||||
|
mk_fat.addFileArg(capsule);
|
||||||
|
for (bundled) |item| {
|
||||||
|
mk_fat.addArg(item.path);
|
||||||
|
mk_fat.addFileArg(item.binary);
|
||||||
|
}
|
||||||
|
return fat_image;
|
||||||
|
}
|
||||||
+176
@@ -0,0 +1,176 @@
|
|||||||
|
//! The QEMU run steps (docs/build-packages-plan.md, phase 3): `run-x86-64`
|
||||||
|
//! boots the serial-enabled FAT image via UEFI/OVMF; `run-x86-64-gpu` adds a
|
||||||
|
//! virtio-gpu adapter for the native-present display path. OVMF firmware is
|
||||||
|
//! probed across distro/OS layouts (-Dovmf-code / -Dovmf-vars override).
|
||||||
|
|
||||||
|
const std = @import("std");
|
||||||
|
|
||||||
|
/// Wire up the `run-x86-64` and `run-x86-64-gpu` steps around the given
|
||||||
|
/// serial-enabled boot image (the guest boots that self-contained image
|
||||||
|
/// attached as USB storage, not the installed FHS zig-out).
|
||||||
|
pub fn addRunSteps(b: *std.Build, fat_image_serial: std.Build.LazyPath) void {
|
||||||
|
// Firmware lives in different places per OS/distro, so probe the known
|
||||||
|
// layouts (Architecture, Debian/Ubuntu, Fedora, macOS Homebrew) and use the first
|
||||||
|
// that exists. Override with -Dovmf-code / -Dovmf-vars if yours is elsewhere.
|
||||||
|
const ovmf_code = b.option(
|
||||||
|
[]const u8,
|
||||||
|
"ovmf-code",
|
||||||
|
"Path to the OVMF_CODE firmware image",
|
||||||
|
) orelse firstExisting(b.graph.io, &.{
|
||||||
|
"/usr/share/edk2/x64/OVMF_CODE.4m.fd", // Architecture
|
||||||
|
"/usr/share/OVMF/OVMF_CODE_4M.fd", // Debian/Ubuntu
|
||||||
|
"/usr/share/OVMF/OVMF_CODE.fd", // older Debian/Ubuntu
|
||||||
|
"/usr/share/edk2-ovmf/x64/OVMF_CODE.fd", // Fedora
|
||||||
|
"/opt/homebrew/share/qemu/edk2-x86_64-code.fd", // macOS Homebrew (Apple Silicon)
|
||||||
|
"/usr/local/share/qemu/edk2-x86_64-code.fd", // macOS Homebrew (Intel)
|
||||||
|
});
|
||||||
|
const ovmf_vars = b.option(
|
||||||
|
[]const u8,
|
||||||
|
"ovmf-vars",
|
||||||
|
"Path to the OVMF_VARS firmware image (a writable copy is made)",
|
||||||
|
) orelse firstExisting(b.graph.io, &.{
|
||||||
|
"/usr/share/edk2/x64/OVMF_VARS.4m.fd", // Architecture
|
||||||
|
"/usr/share/OVMF/OVMF_VARS_4M.fd", // Debian/Ubuntu
|
||||||
|
"/usr/share/OVMF/OVMF_VARS.fd", // older Debian/Ubuntu
|
||||||
|
"/usr/share/edk2-ovmf/x64/OVMF_VARS.fd", // Fedora
|
||||||
|
"/opt/homebrew/share/qemu/edk2-i386-vars.fd", // macOS Homebrew (Apple Silicon)
|
||||||
|
"/usr/local/share/qemu/edk2-i386-vars.fd", // macOS Homebrew (Intel)
|
||||||
|
});
|
||||||
|
|
||||||
|
// The firmware needs to write NVRAM, so give it a writable copy of the vars.
|
||||||
|
const vars_copy = b.addSystemCommand(&.{ "cp", "-f", ovmf_vars });
|
||||||
|
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 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 });
|
||||||
|
|
||||||
|
// --- run-x86-64: boot the x86-64 kernel in QEMU via UEFI/OVMF ---
|
||||||
|
const run_efi = b.addSystemCommand(&.{
|
||||||
|
"qemu-system-x86_64",
|
||||||
|
"-device",
|
||||||
|
"qemu-xhci,id=xhci",
|
||||||
|
"-device",
|
||||||
|
"usb-mouse,bus=xhci.0",
|
||||||
|
"-device",
|
||||||
|
"usb-kbd,bus=xhci.0",
|
||||||
|
"-machine",
|
||||||
|
"q35",
|
||||||
|
"-m",
|
||||||
|
"128M",
|
||||||
|
"-drive",
|
||||||
|
b.fmt("if=pflash,format=raw,readonly=on,file={s}", .{ovmf_code}),
|
||||||
|
});
|
||||||
|
run_efi.addArg("-drive");
|
||||||
|
run_efi.addPrefixedFileArg("if=pflash,format=raw,file=", vars_out);
|
||||||
|
// Boot off the FAT32 USB image: a mass-storage device on the same xHCI bus as
|
||||||
|
// the keyboard and mouse. OVMF finds \EFI\BOOT\BOOTX64.efi on it and boots.
|
||||||
|
// The serial-enabled variant, so serial0 carries the log for this dev boot.
|
||||||
|
run_efi.addArg("-drive");
|
||||||
|
run_efi.addPrefixedFileArg("if=none,id=bootusb,format=raw,file=", fat_image_serial);
|
||||||
|
run_efi.addArgs(&.{
|
||||||
|
"-device",
|
||||||
|
"usb-storage,bus=xhci.0,drive=bootusb,removable=on,bootindex=0",
|
||||||
|
"-net",
|
||||||
|
"none",
|
||||||
|
// Emulated display advertising 1280x720 as its native (EDID preferred)
|
||||||
|
// resolution, so the kernel's native-resolution switch has something to
|
||||||
|
// find. `-vga none` avoids a second, default adapter.
|
||||||
|
"-vga",
|
||||||
|
"none",
|
||||||
|
"-device",
|
||||||
|
"VGA,edid=on,xres=1280,yres=720",
|
||||||
|
});
|
||||||
|
const serial_log = b.fmt("{s}/run-x86-64-serial0-{s}.log", .{ log_dir, timestamp(b) });
|
||||||
|
run_efi.addArgs(&.{ "-serial", b.fmt("file:{s}", .{serial_log}) });
|
||||||
|
// We boot the self-contained `fat_image_serial` (added as a file arg above, so
|
||||||
|
// it's already a dependency) — not the installed FHS zig-out — so `run-x86-64`
|
||||||
|
// builds only the serial kernel, never the flashable one. Just make the serial
|
||||||
|
// scratch dir first.
|
||||||
|
run_efi.step.dependOn(&make_log_dir.step);
|
||||||
|
|
||||||
|
const run_efi_step = b.step("run-x86-64", "Boot the x86-64 kernel in QEMU (UEFI/OVMF); serial0 is logged to zig-out/qemu-test/run-x86-64-serial0-<timestamp>.log");
|
||||||
|
run_efi_step.dependOn(&run_efi.step);
|
||||||
|
|
||||||
|
// --- run-x86-64-gpu: the same boot plus a virtio-gpu adapter ---
|
||||||
|
// The VGA device still supplies the boot (GOP) framebuffer the compositor starts
|
||||||
|
// on; the virtio-gpu function is discovered by the device-manager stack, its
|
||||||
|
// driver announces a shared scanout, and the compositor upgrades off the GOP
|
||||||
|
// floor to fenced, tear-free native presents (docs/display-v2.md).
|
||||||
|
// This is the interactive twin of the `display-native` test case, and 512M
|
||||||
|
// matches it (the whole driver stack + the compositor's surfaces at once).
|
||||||
|
// QEMU shows one head per adapter: pick the virtio-gpu head in the View menu
|
||||||
|
// to watch the native output.
|
||||||
|
const run_gpu = b.addSystemCommand(&.{
|
||||||
|
"qemu-system-x86_64",
|
||||||
|
"-device",
|
||||||
|
"qemu-xhci,id=xhci",
|
||||||
|
"-device",
|
||||||
|
"usb-mouse,bus=xhci.0",
|
||||||
|
"-device",
|
||||||
|
"usb-kbd,bus=xhci.0",
|
||||||
|
"-machine",
|
||||||
|
"q35",
|
||||||
|
"-m",
|
||||||
|
"512M",
|
||||||
|
"-drive",
|
||||||
|
b.fmt("if=pflash,format=raw,readonly=on,file={s}", .{ovmf_code}),
|
||||||
|
});
|
||||||
|
run_gpu.addArg("-drive");
|
||||||
|
run_gpu.addPrefixedFileArg("if=pflash,format=raw,file=", vars_out);
|
||||||
|
run_gpu.addArg("-drive");
|
||||||
|
run_gpu.addPrefixedFileArg("if=none,id=bootusb,format=raw,file=", fat_image_serial);
|
||||||
|
run_gpu.addArgs(&.{
|
||||||
|
"-device",
|
||||||
|
"usb-storage,bus=xhci.0,drive=bootusb,removable=on,bootindex=0",
|
||||||
|
"-net",
|
||||||
|
"none",
|
||||||
|
"-vga",
|
||||||
|
"none",
|
||||||
|
"-device",
|
||||||
|
"VGA,edid=on,xres=1280,yres=720",
|
||||||
|
"-device",
|
||||||
|
"virtio-gpu-pci",
|
||||||
|
});
|
||||||
|
const gpu_serial_log = b.fmt("{s}/run-x86-64-gpu-serial0-{s}.log", .{ log_dir, timestamp(b) });
|
||||||
|
run_gpu.addArgs(&.{ "-serial", b.fmt("file:{s}", .{gpu_serial_log}) });
|
||||||
|
run_gpu.step.dependOn(&make_log_dir.step);
|
||||||
|
|
||||||
|
const run_gpu_step = b.step("run-x86-64-gpu", "Boot in QEMU with a virtio-gpu adapter: the compositor upgrades to fenced (tear-free) native presents; watch the virtio-gpu head in QEMU's View menu");
|
||||||
|
run_gpu_step.dependOn(&run_gpu.step);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Return the first path in `candidates` that exists on the build host, else the
|
||||||
|
/// first candidate as a fallback so a missing-firmware error still names a
|
||||||
|
/// concrete (and, by convention, the primary) path. Used to locate OVMF firmware
|
||||||
|
/// across distro/OS layouts without configuration.
|
||||||
|
fn firstExisting(io: std.Io, candidates: []const []const u8) []const u8 {
|
||||||
|
for (candidates) |path| {
|
||||||
|
std.Io.Dir.accessAbsolute(io, path, .{}) catch continue;
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
return candidates[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A UTC timestamp like "20260708-153045", for naming a per-run artifact so
|
||||||
|
/// repeated runs don't clobber each other's logs. Resolved when `zig build`
|
||||||
|
/// runs, which is moments before QEMU launches.
|
||||||
|
fn timestamp(b: *std.Build) []const u8 {
|
||||||
|
const ns = std.Io.Clock.now(.real, b.graph.io).nanoseconds;
|
||||||
|
const secs: u64 = @intCast(@divFloor(ns, std.time.ns_per_s));
|
||||||
|
const es = std.time.epoch.EpochSeconds{ .secs = secs };
|
||||||
|
const yd = es.getEpochDay().calculateYearDay();
|
||||||
|
const md = yd.calculateMonthDay();
|
||||||
|
const ds = es.getDaySeconds();
|
||||||
|
return b.fmt("{d:0>4}{d:0>2}{d:0>2}-{d:0>2}{d:0>2}{d:0>2}", .{
|
||||||
|
yd.year,
|
||||||
|
md.month.numeric(),
|
||||||
|
@as(u32, md.day_index) + 1,
|
||||||
|
ds.getHoursIntoDay(),
|
||||||
|
ds.getMinutesIntoHour(),
|
||||||
|
ds.getSecondsIntoMinute(),
|
||||||
|
});
|
||||||
|
}
|
||||||
+140
-94
@@ -3,102 +3,106 @@
|
|||||||
Notes on how danos boots and draws, written to explain the *why* behind the code
|
Notes on how danos boots and draws, written to explain the *why* behind the code
|
||||||
rather than restate it. Roughly in the order things happen at runtime:
|
rather than restate it. Roughly in the order things happen at runtime:
|
||||||
|
|
||||||
1. **[efi.md](efi.md) — EFI / the boot process.** How UEFI firmware finds and
|
1. **[efi.md](os-development/efi.md) — EFI / the boot process.** How UEFI firmware finds and
|
||||||
runs the bootloader, what the loader gathers before `ExitBootServices`, how it
|
runs the bootloader, what the loader gathers before `ExitBootServices`, how it
|
||||||
loads the kernel ELF, and the ABI contract for the jump into the kernel. Start
|
loads the kernel ELF, and the ABI contract for the jump into the kernel. Start
|
||||||
here.
|
here.
|
||||||
2. **[system-image.md](system-image.md) — system.img, the boot capsule.** The
|
2. **[system-image.md](os-development/system-image.md) — system.img, the boot capsule.** The
|
||||||
bundled user binaries packed into one file in the initial-ramdisk wire
|
bundled user binaries packed into one file in the initial-ramdisk wire
|
||||||
format, because one open + one sequential read is the only file I/O shape
|
format, because one open + one sequential read is the only file I/O shape
|
||||||
firmware is fast at. The trivial container format, the three artifacts one
|
firmware is fast at. The trivial container format, the three artifacts one
|
||||||
build list derives (tree, manifest, capsule), the loader's three-strategy
|
build list derives (tree, manifest, capsule), the loader's three-strategy
|
||||||
fallback chain, and the capsule's kernel-side life as both the spawn table
|
fallback chain, and the capsule's kernel-side life as both the spawn table
|
||||||
and the read-only `/system` mount.
|
and the read-only `/system` mount.
|
||||||
3. **[gop.md](gop.md) — the Graphics Output Protocol.** How UEFI exposes graphics
|
3. **[gop.md](os-development/gop.md) — the Graphics Output Protocol.** How UEFI exposes graphics
|
||||||
modes (unlike fixed VGA modes), how we detect the monitor's native resolution
|
modes (unlike fixed VGA modes), how we detect the monitor's native resolution
|
||||||
from EDID and switch to it, and the pixel formats we accept or reject.
|
from EDID and switch to it, and the pixel formats we accept or reject.
|
||||||
4. **[framebuffer.md](framebuffer.md) — the framebuffer.** What the linear
|
4. **[framebuffer.md](os-development/framebuffer.md) — the framebuffer.** What the linear
|
||||||
framebuffer the loader hands over actually is, and what **pitch** (stride)
|
framebuffer the loader hands over actually is, and what **pitch** (stride)
|
||||||
means versus width — the detail you have to get right to avoid a skewed image.
|
means versus width — the detail you have to get right to avoid a skewed image.
|
||||||
5. **[memory-map.md](memory-map.md) — the memory map.** How the loader learns what
|
5. **[memory-map.md](os-development/memory-map.md) — the memory map.** How the loader learns what
|
||||||
physical RAM exists and hands it to the kernel in danos's own neutral format,
|
physical RAM exists and hands it to the kernel in danos's own neutral format,
|
||||||
rather than leaking UEFI's memory descriptors across the boundary.
|
rather than leaking UEFI's memory descriptors across the boundary.
|
||||||
6. **[frame-allocator.md](frame-allocator.md) — the physical frame allocator.** The
|
6. **[frame-allocator.md](os-development/frame-allocator.md) — the physical frame allocator.** The
|
||||||
bitmap allocator that hands out and reclaims 4 KiB physical frames from that
|
bitmap allocator that hands out and reclaims 4 KiB physical frames from that
|
||||||
map — the primitive page tables and the heap are built on.
|
map — the primitive page tables and the heap are built on.
|
||||||
7. **[interrupts.md](interrupts.md) — interrupts and exceptions.** The GDT, IDT and
|
7. **[interrupts.md](os-development/interrupts.md) — interrupts and exceptions.** The GDT, IDT and
|
||||||
TSS, the exception stubs, and the handler that reports a CPU fault in red instead
|
TSS, the exception stubs, and the handler that reports a CPU fault in red instead
|
||||||
of letting it triple-fault into a silent reset.
|
of letting it triple-fault into a silent reset.
|
||||||
8. **[paging.md](paging.md) — the kernel's page tables.** Building our own 4-level
|
8. **[paging.md](os-development/paging.md) — the kernel's page tables.** Building our own 4-level
|
||||||
page tables, identity-mapping the low 4 GiB, and switching CR3 off the firmware's
|
page tables, identity-mapping the low 4 GiB, and switching CR3 off the firmware's
|
||||||
tables onto ours.
|
tables onto ours.
|
||||||
9. **[device-interrupts.md](device-interrupts.md) — device interrupts.** The Local
|
9. **[device-interrupts.md](device-driver-development/device-interrupts.md) — device interrupts.** The Local
|
||||||
APIC and its timer — the kernel's first interrupt that is *handled and returned
|
APIC and its timer — the kernel's first interrupt that is *handled and returned
|
||||||
from*, giving it a heartbeat.
|
from*, giving it a heartbeat.
|
||||||
10. **[heap.md](heap.md) — the kernel heap.** A growable free-list allocator built on
|
10. **[heap.md](os-development/heap.md) — the kernel heap.** A growable free-list allocator built on
|
||||||
the VMM, exposed as a `std.mem.Allocator` so std containers work — dynamic
|
the VMM, exposed as a `std.mem.Allocator` so std containers work — dynamic
|
||||||
allocation for the kernel.
|
allocation for the kernel.
|
||||||
11. **[scheduling.md](scheduling.md) — the scheduler.** Fixed-priority preemptive
|
11. **[scheduling.md](os-development/scheduling.md) — the scheduler.** Fixed-priority preemptive
|
||||||
multitasking: kernel threads, the context switch, O(1) priority selection, and
|
multitasking: kernel threads, the context switch, O(1) priority selection, and
|
||||||
blocking (sleep, wait queues) — the leap to a running system.
|
blocking (sleep, wait queues) — the leap to a running system.
|
||||||
12. **[ipc.md](ipc.md) — inter-process communication.** Bounded blocking
|
12. **[ipc.md](device-driver-development/ipc.md) — inter-process communication.** Bounded blocking
|
||||||
message-passing channels, then synchronous call/reply between *processes* over
|
message-passing channels, then synchronous call/reply between *processes* over
|
||||||
endpoints — the backbone the microkernel's isolated servers talk over.
|
endpoints — the backbone the microkernel's isolated servers talk over.
|
||||||
13. **[syscall.md](syscall.md) — system calls.** How ring 3 asks the kernel for
|
13. **[syscall.md](os-development/syscall.md) — system calls.** How ring 3 asks the kernel for
|
||||||
something: the `syscall`/`sysret` fast path, the trap frame, and why the table is
|
something: the `syscall`/`sysret` fast path, the trap frame, and why the table is
|
||||||
deliberately tiny. The numbers are a **private** ABI — [vdso.md](vdso.md) designs
|
deliberately tiny. The numbers are a **private** ABI — [vdso.md](os-development/vdso.md) designs
|
||||||
the public boundary that will hide them.
|
the public boundary that will hide them.
|
||||||
14. **[vfs-protocol.md](vfs-protocol.md) — the VFS wire protocol.** The language-neutral
|
14. **[vfs-protocol.md](file-system-development/vfs-protocol.md) — the VFS wire protocol.** The language-neutral
|
||||||
byte-level spec of the file protocol spoken over IPC: request/reply headers,
|
byte-level spec of the file protocol spoken over IPC: request/reply headers,
|
||||||
the operation table, mount routing, and the append-only evolution rules — the
|
the operation table, mount routing, and the append-only evolution rules — the
|
||||||
first IPC protocol documented as public ABI.
|
first IPC protocol documented as public ABI. Its architectural frame is
|
||||||
15. **[drivers.md](drivers.md) — writing a driver.** The payoff: a driver is an
|
**[storage-architecture.md](file-system-development/storage-architecture.md) — the storage stack**:
|
||||||
|
the layers from application to hardware, the three kinds of boundary
|
||||||
|
(protocol, library, control-plane), how to add a filesystem, and the
|
||||||
|
per-layer responsibilities when removable media is yanked and returned.
|
||||||
|
15. **[drivers.md](device-driver-development/drivers.md) — writing a driver.** The payoff: a driver is an
|
||||||
ordinary ring-3 process that claims a device, maps its registers, and **sleeps
|
ordinary ring-3 process that claims a device, maps its registers, and **sleeps
|
||||||
until its hardware interrupts it**. The claim is the capability; `irq_ack` is the
|
until its hardware interrupts it**. The claim is the capability; `irq_ack` is the
|
||||||
unmask.
|
unmask.
|
||||||
16. **[driver-model.md](driver-model.md) — buses, classes and host controllers.** How
|
16. **[driver-model.md](device-driver-development/driver-model.md) — buses, classes and host controllers.** How
|
||||||
real driver stacks factor into three shapes and how families share code. The
|
real driver stacks factor into three shapes and how families share code. The
|
||||||
three primitives it proposed are long since built (M13 capability passing,
|
three primitives it proposed are long since built (M13 capability passing,
|
||||||
M14 DMA + barriers, M15 MSI), and the driver *contract* on top of them —
|
M14 DMA + barriers, M15 MSI), and the driver *contract* on top of them —
|
||||||
hello, supervision, restart — is built too (device-manager.md, M18).
|
hello, supervision, restart — is built too (device-manager.md, M18).
|
||||||
17. **[usb-hub.md](usb-hub.md) — USB hubs.** Built (M22): why hub topology is handled
|
17. **[usb-hub.md](device-driver-development/usb-hub.md) — USB hubs.** Built (M22): why hub topology is handled
|
||||||
*inside* the `usb-xhci-bus` driver rather than a separate hub class driver — a
|
*inside* the `usb-xhci-bus` driver rather than a separate hub class driver — a
|
||||||
device behind a hub is reached by the **controller**, programmed with a route
|
device behind a hub is reached by the **controller**, programmed with a route
|
||||||
string in its slot context — plus the compound-hub reality (a USB 3.0 hub is
|
string in its slot context — plus the compound-hub reality (a USB 3.0 hub is
|
||||||
physically two hubs) and detection via the hub's status-change interrupt endpoint.
|
physically two hubs) and detection via the hub's status-change interrupt endpoint.
|
||||||
18. **[process-management.md](process-management.md) — process management.** The
|
18. **[process-management.md](os-development/process-management.md) — process management.** The
|
||||||
microkernel's `ps`/`kill`/SIGCHLD: enumerate as a table snapshot, the
|
microkernel's `ps`/`kill`/SIGCHLD: enumerate as a table snapshot, the
|
||||||
supervision link as the kill authority, and child-exit notifications over the
|
supervision link as the kill authority, and child-exit notifications over the
|
||||||
same endpoints IRQs arrive on.
|
same endpoints IRQs arrive on.
|
||||||
19. **[process-lifecycle.md](process-lifecycle.md) — the process lifecycle.** Built
|
19. **[process-lifecycle.md](os-development/process-lifecycle.md) — the process lifecycle.** Built
|
||||||
(M17): signals over IPC as the one lifecycle vocabulary every process speaks — the
|
(M17): signals over IPC as the one lifecycle vocabulary every process speaks — the
|
||||||
POSIX.1-1990 words with message delivery instead of stack hijack, the stable
|
POSIX.1-1990 words with message delivery instead of stack hijack, the stable
|
||||||
`runtime.process` interface, exit reasons, published exit events any stateful
|
`process` module interface, exit reasons, published exit events any stateful
|
||||||
service can subscribe to (the VFS releasing dead clients' handles), and the two
|
service can subscribe to (the VFS releasing dead clients' handles), and the two
|
||||||
iron rules (cleanup is the kernel's job; kill is not a signal).
|
iron rules (cleanup is the kernel's job; kill is not a signal).
|
||||||
20. **[device-manager.md](device-manager.md) — the device manager.** Built (M18,
|
20. **[device-manager.md](device-driver-development/device-manager.md) — the device manager.** Built (M18,
|
||||||
through the app surface): the
|
through the app surface): the
|
||||||
tree, the matcher, and the supervisor. Tree structure lives in the manager,
|
tree, the matcher, and the supervisor. Tree structure lives in the manager,
|
||||||
authority stays in the kernel; bus drivers report what they see; drivers are
|
authority stays in the kernel; bus drivers report what they see; drivers are
|
||||||
restarted through the lifecycle vocabulary — the plan that turns
|
restarted through the lifecycle vocabulary — the plan that turns
|
||||||
[resilience.md](resilience.md)'s restart goal into increments.
|
[resilience.md](os-development/resilience.md)'s restart goal into increments.
|
||||||
21. **[input.md](input.md) — the input module.** Broadcasting input events (keyboard,
|
21. **[input.md](device-driver-development/input.md) — the input module.** Broadcasting input events (keyboard,
|
||||||
mouse, joystick): why a synchronous rendezvous can't fan out to many listeners, the
|
mouse, joystick): why a synchronous rendezvous can't fan out to many listeners, the
|
||||||
asynchronous `ipc_send` primitive built to fix it, and the per-device subscribe/publish
|
asynchronous `ipc_send` primitive built to fix it, and the per-device subscribe/publish
|
||||||
service layered on top.
|
service layered on top.
|
||||||
22. **[display.md](display.md) — the display service.** The display half of the GUI
|
22. **[display.md](device-driver-development/display.md) — the display service.** The display half of the GUI
|
||||||
track: a user-space compositor that owns the framebuffer, composes a layer stack into
|
track: a user-space compositor that owns the framebuffer, composes a layer stack into
|
||||||
a double buffer, and presents it. Why GOP and the PCI display device are two views of
|
a double buffer, and presents it. Why GOP and the PCI display device are two views of
|
||||||
one controller, the device-node + write-combining handoff, and what flicker-free buys
|
one controller, the device-node + write-combining handoff, and what flicker-free buys
|
||||||
that tear-free doesn't. Plan: [display-plan.md](display-plan.md). **v2** (complete) makes
|
that tear-free doesn't. Plan: [display-plan.md](device-driver-development/display-plan.md). **v2** (complete) makes
|
||||||
scanout a pluggable backend — GOP floor + a native virtio-gpu driver, hot-attached, with
|
scanout a pluggable backend — GOP floor + a native virtio-gpu driver, hot-attached, with
|
||||||
runtime mode-set, EDID, fenced vsync presents, and restart re-attach:
|
runtime mode-set, EDID, fenced vsync presents, and restart re-attach:
|
||||||
[display-v2.md](display-v2.md), plan [display-v2-plan.md](display-v2-plan.md). Looking
|
[display-v2.md](device-driver-development/display-v2.md), plan [display-v2-plan.md](device-driver-development/display-v2-plan.md). Looking
|
||||||
further out, three research snapshots survey what a *native* driver for real GPU silicon
|
further out, three research snapshots survey what a *native* driver for real GPU silicon
|
||||||
would take as another `.scanout` backend: [nvidia-gpus.md](nvidia-gpus.md) (RTX 3060 /
|
would take as another `.scanout` backend: [nvidia-gpus.md](device-driver-development/nvidia-gpus.md) (RTX 3060 /
|
||||||
Ampere), [amd-gpus.md](amd-gpus.md) (RX 6600 / RDNA2), and [intel-igpu.md](intel-igpu.md)
|
Ampere), [amd-gpus.md](device-driver-development/amd-gpus.md) (RX 6600 / RDNA2), and [intel-igpu.md](device-driver-development/intel-igpu.md)
|
||||||
(Intel iGPU).
|
(Intel iGPU).
|
||||||
23. **[halting.md](halting.md) — halting.** Why a kernel can't just "exit", and
|
23. **[halting.md](os-development/halting.md) — halting.** Why a kernel can't just "exit", and
|
||||||
how `while (true) hlt` parks the CPU safely once there's nothing left to do.
|
how `while (true) hlt` parks the CPU safely once there's nothing left to do.
|
||||||
|
|
||||||
Start with the north star:
|
Start with the north star:
|
||||||
@@ -108,28 +112,28 @@ Start with the north star:
|
|||||||
**resilience** (restartable components). Win condition: runs on the author's PC and
|
**resilience** (restartable components). Win condition: runs on the author's PC and
|
||||||
both Raspberry Pis, ideally with a GUI. Real-time is an option to explore, not a
|
both Raspberry Pis, ideally with a GUI. Real-time is an option to explore, not a
|
||||||
requirement. The *why* that shapes everything below.
|
requirement. The *why* that shapes everything below.
|
||||||
- **[resilience.md](resilience.md) — resilience.** A design note (not built yet) on
|
- **[resilience.md](os-development/resilience.md) — resilience.** A design note (not built yet) on
|
||||||
fault isolation + live restart — the reincarnation-server + capability model that
|
fault isolation + live restart — the reincarnation-server + capability model that
|
||||||
makes "if I break it, I can restart it" real. danos's core motivation.
|
makes "if I break it, I can restart it" real. danos's core motivation.
|
||||||
- **[zig-self-hosting.md](zig-self-hosting.md) — running Zig on danos.** A design note
|
- **[zig-self-hosting.md](zig-self-hosting.md) — running Zig on danos.** A design note
|
||||||
(not built yet) on making danos a real Zig target (`-target x86_64-danos`) and
|
(not built yet) on making danos a real Zig target (`-target x86_64-danos`) and
|
||||||
eventually running the compiler on it. The key realisation: Zig 0.16 reduces an OS
|
eventually running the compiler on it. The key realisation: Zig 0.16 reduces an OS
|
||||||
port to **one seam** (`std.os.danos`), so we build `runtime.os` (→ that seam) plus a
|
port to **one seam** (`std.os.danos`), so we build an `os` seam module (→ that seam) plus
|
||||||
thin `runtime.fs`, retire the `posix` shim, and follow a phased path to
|
the thin `file-system` module, retire the `posix` shim, and follow a phased path to
|
||||||
`zig build-exe hello.zig` running on danos — **not** Linux-ABI emulation.
|
`zig build-exe hello.zig` running on danos — **not** Linux-ABI emulation.
|
||||||
- **[threading.md](threading.md) — threads, the std-shaped way.** **Built** (M1–M6):
|
- **[threading.md](os-development/threading.md) — threads, the std-shaped way.** **Built** (M1–M6):
|
||||||
`runtime.Thread` mirrors `std.Thread`'s API (spawn/join/detach, Mutex/Condition/
|
the `thread` module's `Thread` mirrors `std.Thread`'s API (spawn/join/detach, Mutex/Condition/
|
||||||
Semaphore) over a **private** thread ABI — several tasks sharing one address space via
|
Semaphore) over a **private** thread ABI — several tasks sharing one address space via
|
||||||
a `thread_spawn` syscall, futex-backed blocking, address-space refcounting. Why it's the
|
a `thread_spawn` syscall, futex-backed blocking, address-space refcounting. Why it's the
|
||||||
native type and not literal `std.Thread` (the [private ABI](syscall.md)), and why
|
native type and not literal `std.Thread` (the [private ABI](os-development/syscall.md)), and why
|
||||||
threads stay a narrow opt-in against the [resilience](resilience.md) default. Build
|
threads stay a narrow opt-in against the [resilience](os-development/resilience.md) default. Build
|
||||||
plan + gates: [threading-plan.md](threading-plan.md).
|
plan + gates: [threading-plan.md](os-development/threading-plan.md).
|
||||||
- **[vdso.md](vdso.md) — the vDSO, the public system-call boundary.** A design note
|
- **[vdso.md](os-development/vdso.md) — the vDSO, the public system-call boundary.** A design note
|
||||||
(not built yet) on keeping `abi.zig` genuinely private: a kernel-supplied, C-ABI
|
(not built yet) on keeping `abi.zig` genuinely private: a kernel-supplied, C-ABI
|
||||||
entry blob mapped into every process as the *only* way into the kernel — so the
|
entry blob mapped into every process as the *only* way into the kernel — so the
|
||||||
syscall numbers can be renumbered or randomised at will, and Rust/C binaries get a
|
syscall numbers can be renumbered or randomised at will, and Rust/C binaries get a
|
||||||
stable boundary without danos growing a dynamic linker. danos's public ABI = the
|
stable boundary without danos growing a dynamic linker. danos's public ABI = the
|
||||||
vDSO + the documented IPC wire protocols ([vfs-protocol.md](vfs-protocol.md) first).
|
vDSO + the documented IPC wire protocols ([vfs-protocol.md](file-system-development/vfs-protocol.md) first).
|
||||||
|
|
||||||
Cutting across all of these:
|
Cutting across all of these:
|
||||||
|
|
||||||
@@ -137,69 +141,69 @@ Cutting across all of these:
|
|||||||
hardware needed to run danos: minimum specs (UEFI x86-64, ACPI, PCIe ECAM,
|
hardware needed to run danos: minimum specs (UEFI x86-64, ACPI, PCIe ECAM,
|
||||||
xHCI, ~128 MiB RAM) grounded in what the boot path actually assumes, plus a
|
xHCI, ~128 MiB RAM) grounded in what the boot path actually assumes, plus a
|
||||||
plain-language guide matching Intel/AMD CPU generations by name.
|
plain-language guide matching Intel/AMD CPU generations by name.
|
||||||
- **[release-iso.md](release-iso.md) — the release ISO.** The flashable boot
|
- **[release-iso.md](os-development/release-iso.md) — the release ISO.** The flashable boot
|
||||||
media: `zig build release-x86-64` wraps the FAT32 boot volume in a hybrid ISO
|
media: `zig build release-x86-64` wraps the FAT32 boot volume in a hybrid ISO
|
||||||
(MBR ESP partition + El Torito EFI entry, one embedded image) that Etcher/dd
|
(MBR ESP partition + El Torito EFI entry, one embedded image) that Etcher/dd
|
||||||
flash to USB or a burner writes to disc — built by an in-repo pure-Python
|
flash to USB or a burner writes to disc — built by an in-repo pure-Python
|
||||||
tool, like the FAT image itself.
|
tool, like the FAT image itself.
|
||||||
- **[architecture.md](architecture.md) — the architecture split.** How CPU-specific code is kept
|
- **[architecture.md](os-development/architecture.md) — the architecture split.** How CPU-specific code is kept
|
||||||
behind a build-time `arch` module so the generic kernel never names x86_64,
|
behind a build-time `arch` module so the generic kernel never names x86_64,
|
||||||
leaving room for other systems (e.g. an AArch64 Raspberry Pi) later.
|
leaving room for other systems (e.g. an AArch64 Raspberry Pi) later.
|
||||||
- **[arm.md](arm.md) — ARM targets.** The Raspberry Pi landscape the arch split is
|
- **[arm.md](os-development/arm.md) — ARM targets.** The Raspberry Pi landscape the arch split is
|
||||||
aiming at: `arm` (32-bit, Pi Zero W) vs `aarch64` (64-bit, Pi 3-5), UEFI vs
|
aiming at: `arm` (32-bit, Pi Zero W) vs `aarch64` (64-bit, Pi 3-5), UEFI vs
|
||||||
device-tree boot, and what each layer needs.
|
device-tree boot, and what each layer needs.
|
||||||
- **[discovery.md](discovery.md) — device discovery.** A design note on learning what
|
- **[discovery.md](os-development/discovery.md) — device discovery.** A design note on learning what
|
||||||
hardware exists via ACPI (x86) or device tree (ARM) behind one neutral device model —
|
hardware exists via ACPI (x86) or device tree (ARM) behind one neutral device model —
|
||||||
when to build it, and how to keep it architecture-agnostic.
|
when to build it, and how to keep it architecture-agnostic.
|
||||||
- **[acpi.md](acpi.md) — finding the ACPI tables.** The concrete x86 locator chain:
|
- **[acpi.md](os-development/acpi.md) — finding the ACPI tables.** The concrete x86 locator chain:
|
||||||
how the loader captures the **RSDP**, hands its physical address across in `BootInformation`,
|
how the loader captures the **RSDP**, hands its physical address across in `BootInformation`,
|
||||||
and how the platform derives the **RSDT/XSDT** from it and walks the SDTs — plus the
|
and how the platform derives the **RSDT/XSDT** from it and walks the SDTs — plus the
|
||||||
live event side (the SCI, the power button, GPE/Notify) the ring-3 acpi service runs.
|
live event side (the SCI, the power button, GPE/Notify) the ring-3 acpi service runs.
|
||||||
- **[power.md](power.md) — the power service.** System power as a domain-named
|
- **[power.md](os-development/power.md) — the power service.** System power as a domain-named
|
||||||
service: button/lid/battery events published to subscribers, and init's orderly
|
service: button/lid/battery events published to subscribers, and init's orderly
|
||||||
shutdown composing the [lifecycle](process-lifecycle.md) stop sequence with an ACPI
|
shutdown composing the [lifecycle](os-development/process-lifecycle.md) stop sequence with an ACPI
|
||||||
S5 write. Firmware-neutral — a PSCI backend drops in on ARM.
|
S5 write. Firmware-neutral — a PSCI backend drops in on ARM.
|
||||||
- **[timers.md](timers.md) — timers and time.** The ring-3 surface for reading the
|
- **[timers.md](os-development/timers.md) — timers and time.** The ring-3 surface for reading the
|
||||||
clock and waiting: why `now()` is a syscall rather than a service, and the one-shot
|
clock and waiting: why `now()` is a syscall rather than a service, and the one-shot
|
||||||
timer notification (`timer_bind`) that gives supervisors a timed wait — built on the
|
timer notification (`timer_bind`) that gives supervisors a timed wait — built on the
|
||||||
LAPIC heartbeat and calibrated TSC of [device-interrupts.md](device-interrupts.md).
|
LAPIC heartbeat and calibrated TSC of [device-interrupts.md](device-driver-development/device-interrupts.md).
|
||||||
- **[smp.md](smp.md) — multiple cores.** A design/research note on how microkernels
|
- **[smp.md](os-development/smp.md) — multiple cores.** A design/research note on how microkernels
|
||||||
(L4, seL4) handle SMP — big kernel lock vs per-CPU vs multikernel — and how the
|
(L4, seL4) handle SMP — big kernel lock vs per-CPU vs multikernel — and how the
|
||||||
right choice depends on whether danos is chasing real-time or resilience.
|
right choice depends on whether danos is chasing real-time or resilience.
|
||||||
- **[coding-standards.md](coding-standards.md) — coding standards.** The naming rule the
|
- **[coding-standards.md](coding-standards.md) — coding standards.** The naming rule the
|
||||||
tree follows: non-acronyms are spelled out in full (`message`, not `msg`), files are
|
tree follows: non-acronyms are spelled out in full (`message`, not `msg`), files are
|
||||||
`kebab-case`, code follows Zig's case conventions, and the handful of exceptions
|
`kebab-case`, code follows Zig's case conventions, and the handful of exceptions
|
||||||
(POSIX/C ABI names, `init`/`len`/`ptr`, acronyms).
|
(POSIX/C ABI names, `init`/`len`/`ptr`, acronyms).
|
||||||
- **[sysv.md](sysv.md) — the calling convention.** What "the kernel is SysV" means,
|
- **[sysv.md](os-development/sysv.md) — the calling convention.** What "the kernel is SysV" means,
|
||||||
and why the loader→kernel boundary has to pin it (the RDI-vs-RCX handoff).
|
and why the loader→kernel boundary has to pin it (the RDI-vs-RCX handoff).
|
||||||
- **[testing.md](testing.md) — testing.** How the kernel is tested by booting it in
|
- **[testing.md](testing.md) — testing.** How the kernel is tested by booting it in
|
||||||
QEMU and asserting on its serial output — reproducibly, and structured so the
|
QEMU and asserting on its serial output — reproducibly, and structured so the
|
||||||
same tests run across architectures.
|
same tests run across architectures.
|
||||||
- **[logging.md](logging.md) — logging.** The multi-sink diagnostic log (serial,
|
- **[logging.md](os-development/logging.md) — logging.** The multi-sink diagnostic log (serial,
|
||||||
0xE9 debugcon, file later) kept separate from the framebuffer display, plus the
|
0xE9 debugcon, file later) kept separate from the framebuffer display, plus the
|
||||||
robustness path: optional framebuffer, POST-code checkpoints, and a persistent
|
robustness path: optional framebuffer, POST-code checkpoints, and a persistent
|
||||||
panic breadcrumb so the kernel survives — and can be diagnosed — with no output.
|
panic breadcrumb so the kernel survives — and can be diagnosed — with no output.
|
||||||
|
|
||||||
## How the pieces relate
|
## How the pieces relate
|
||||||
|
|
||||||
The boot flow ties them together: UEFI runs the loader ([efi.md](efi.md)), which
|
The boot flow ties them together: UEFI runs the loader ([efi.md](os-development/efi.md)), which
|
||||||
queries the **GOP** to pick a graphics mode ([gop.md](gop.md)), hands the kernel a
|
queries the **GOP** to pick a graphics mode ([gop.md](os-development/gop.md)), hands the kernel a
|
||||||
**framebuffer** to draw into ([framebuffer.md](framebuffer.md)) and a **memory
|
**framebuffer** to draw into ([framebuffer.md](os-development/framebuffer.md)) and a **memory
|
||||||
map** of physical RAM ([memory-map.md](memory-map.md)); the kernel turns that map
|
map** of physical RAM ([memory-map.md](os-development/memory-map.md)); the kernel turns that map
|
||||||
into a **frame allocator** ([frame-allocator.md](frame-allocator.md)), installs
|
into a **frame allocator** ([frame-allocator.md](os-development/frame-allocator.md)), installs
|
||||||
its **descriptor tables** so CPU faults are caught ([interrupts.md](interrupts.md)),
|
its **descriptor tables** so CPU faults are caught ([interrupts.md](os-development/interrupts.md)),
|
||||||
builds its own **page tables** and switches onto them ([paging.md](paging.md)),
|
builds its own **page tables** and switches onto them ([paging.md](os-development/paging.md)),
|
||||||
brings up the **heap** for dynamic allocation ([heap.md](heap.md)), starts the
|
brings up the **heap** for dynamic allocation ([heap.md](os-development/heap.md)), starts the
|
||||||
**scheduler** ([scheduling.md](scheduling.md)) and the **timer** that preempts it
|
**scheduler** ([scheduling.md](os-development/scheduling.md)) and the **timer** that preempts it
|
||||||
([device-interrupts.md](device-interrupts.md)) — with tasks blocking, sleeping and
|
([device-interrupts.md](device-driver-development/device-interrupts.md)) — with tasks blocking, sleeping and
|
||||||
passing messages over **[IPC](ipc.md)** channels — runs, its CPU-specific bits
|
passing messages over **[IPC](device-driver-development/ipc.md)** channels — runs, its CPU-specific bits
|
||||||
behind the [architecture](architecture.md) boundary, and when idle, or on a panic, it **halts**
|
behind the [architecture](os-development/architecture.md) boundary, and when idle, or on a panic, it **halts**
|
||||||
([halting.md](halting.md)).
|
([halting.md](os-development/halting.md)).
|
||||||
|
|
||||||
Above that line the microkernel proper begins: **discovery** ([discovery.md](discovery.md),
|
Above that line the microkernel proper begins: **discovery** ([discovery.md](os-development/discovery.md),
|
||||||
[acpi.md](acpi.md)) learns what hardware exists, ring-3 processes ask the kernel for
|
[acpi.md](os-development/acpi.md)) learns what hardware exists, ring-3 processes ask the kernel for
|
||||||
things through the small **[syscall](syscall.md)** table, isolated servers reach each
|
things through the small **[syscall](os-development/syscall.md)** table, isolated servers reach each
|
||||||
other over IPC **endpoints** ([ipc.md](ipc.md)), and a **[driver](drivers.md)** claims
|
other over IPC **endpoints** ([ipc.md](device-driver-development/ipc.md)), and a **[driver](device-driver-development/drivers.md)** claims
|
||||||
a device, maps its registers, and sleeps until the hardware interrupts it — which is
|
a device, maps its registers, and sleeps until the hardware interrupts it — which is
|
||||||
the whole reason for the arrangement ([vision.md](vision.md)).
|
the whole reason for the arrangement ([vision.md](vision.md)).
|
||||||
|
|
||||||
@@ -208,7 +212,7 @@ the whole reason for the arrangement ([vision.md](vision.md)).
|
|||||||
danos is a **monorepo of sub-projects**. Each service or driver is a directory that is
|
danos is a **monorepo of sub-projects**. Each service or driver is a directory that is
|
||||||
its own Zig module — it can hold as many files as it needs, and other sub-projects
|
its own Zig module — it can hold as many files as it needs, and other sub-projects
|
||||||
reach it *by module name*, never by a path into its files. The source tree deliberately
|
reach it *by module name*, never by a path into its files. The source tree deliberately
|
||||||
**mirrors the runtime FHS** ([danos-file-system-hierarchy-FSH.md](danos-file-system-hierarchy-FSH.md)):
|
**mirrors the runtime file-system hierarchy** ([file-system-hierarchy.md](file-system-development/file-system-hierarchy.md)):
|
||||||
what you see under `system/` in the source is what a running danos represents under
|
what you see under `system/` in the source is what a running danos represents under
|
||||||
`/system`.
|
`/system`.
|
||||||
|
|
||||||
@@ -216,11 +220,12 @@ what you see under `system/` in the source is what a running danos represents un
|
|||||||
name.** `system/services/init/` contains `init.zig` (its root), and produces a binary
|
name.** `system/services/init/` contains `init.zig` (its root), and produces a binary
|
||||||
addressed as **`system/services/init`** — the repeated leaf resolves away:
|
addressed as **`system/services/init`** — the repeated leaf resolves away:
|
||||||
|
|
||||||
| Source (root file) | Addressed as (module / binary / FHS path) |
|
| Source (root file) | Addressed as (module / binary / hierarchy path) |
|
||||||
|----------------------------------------|--------------------------------------------|
|
|----------------------------------------|--------------------------------------------|
|
||||||
| `system/services/init/init.zig` | `system/services/init` → `/system/services/init` |
|
| `system/services/init/init.zig` | `system/services/init` → `/system/services/init` |
|
||||||
| `system/drivers/ps2-bus/ps2-bus.zig` | `system/drivers/ps2-bus` → `/system/drivers/ps2-bus` |
|
| `system/drivers/ps2-bus/ps2-bus.zig` | `system/drivers/ps2-bus` → `/system/drivers/ps2-bus` |
|
||||||
| `library/runtime/runtime.zig` | `library/runtime` (the `runtime` module) |
|
| `test/system/services/vfs-test/vfs-test.zig` | `test/system/services/vfs-test` → `/test/system/services/vfs-test` |
|
||||||
|
| `library/device/pci/pci.zig` | `library/device/pci` (the `pci` module) |
|
||||||
|
|
||||||
In **source**, a sub-project is a directory so it can hold many files — the entry is
|
In **source**, a sub-project is a directory so it can hold many files — the entry is
|
||||||
`fat/fat.zig`, beside it `fat/engine.zig`, `fat/on-disk.zig`, and so on. When
|
`fat/fat.zig`, beside it `fat/engine.zig`, `fat/on-disk.zig`, and so on. When
|
||||||
@@ -234,32 +239,69 @@ A sub-project's extra files are reached through the module, never as separate pa
|
|||||||
```
|
```
|
||||||
system/ → /system danos's own internals (the self-representation)
|
system/ → /system danos's own internals (the self-representation)
|
||||||
boot-handoff.zig the loader↔kernel contract (the `boot-handoff` module)
|
boot-handoff.zig the loader↔kernel contract (the `boot-handoff` module)
|
||||||
abi.zig the private kernel↔runtime syscall ABI (the `abi` module)
|
abi.zig the private kernel↔userspace syscall ABI (the `abi` module)
|
||||||
parameters.zig initial-ramdisk.zig vfs-protocol.zig shared contracts
|
parameters.zig initial-ramdisk.zig shared contracts
|
||||||
kernel/ IPC, memory, scheduling, the VFS root, the private syscall dispatch
|
kernel/ IPC, memory, scheduling, the VFS root, the private syscall dispatch
|
||||||
architecture/x86_64/ the `architecture` module (never named by generic code)
|
architecture/x86_64/ the `architecture` module (never named by generic code)
|
||||||
devices/ the device model /system/devices reflects (+ aml/)
|
devices-broker.zig the syscall-facing device table
|
||||||
device-abi.zig the device wire types (the `device-abi` module)
|
platform.zig acpi.zig fdt.zig device-model.zig firmware discovery + the kernel's
|
||||||
|
device model — the implementation of what /system/devices reflects
|
||||||
drivers/ pci-bus/ ps2-bus/ usb-xhci-bus/ one sub-project per driver → /system/drivers
|
drivers/ pci-bus/ ps2-bus/ usb-xhci-bus/ one sub-project per driver → /system/drivers
|
||||||
services/ init/ fat/ device-manager/ system servers → /system/services (fat/ holds
|
services/ init/ fat/ device-manager/ system servers → /system/services (fat/ holds
|
||||||
fat.zig, engine.zig, on-disk.zig)
|
fat.zig, engine.zig, on-disk.zig)
|
||||||
library/ → /lib libraries, one sub-directory each
|
library/ → /lib libraries, one sub-directory each
|
||||||
runtime/ the danos-native runtime + file API (fs) — the stable application ABI
|
kernel/ the danos-native system library (kernel32-style): the syscall
|
||||||
|
surface split by concern — ipc, memory (heap/dma/shared-memory),
|
||||||
|
process, time, logging, file-system, thread, service, plus the
|
||||||
|
system-call stubs and the start/root entry shim
|
||||||
|
device/ device code by domain — mmio/ model/ pci/ usb/ acpi/ driver/
|
||||||
|
block/ — each a shareable data module (device-abi, pci-class,
|
||||||
|
usb-abi/ids, acpi-ids) plus a logic module (mmio, pci, usb, aml,
|
||||||
|
driver — the device-access + device-manager-hello client)
|
||||||
|
client/ userspace service clients (display, input) — a program's view of
|
||||||
|
a service, layered over that service's protocol
|
||||||
|
protocol/ driver↔service wire contracts (vfs block display scanout input
|
||||||
|
power device-manager usb-transfer), one module per directory
|
||||||
boot/ → /boot the loaders
|
boot/ → /boot the loaders
|
||||||
tools/ test/ host-side build + QEMU test harness
|
test/ → /test the test tree: the QEMU harness (qemu_test.py, host-side)
|
||||||
|
system/services/ beside the on-image test fixtures — vfs-test/ thread-test/
|
||||||
|
crash-test/ … — whose repo path IS their boot-volume path
|
||||||
|
(/test/system/services/<name>)
|
||||||
|
build-support/ the danos build API (build-time only, nothing on the image):
|
||||||
|
the shared user-binary recipe + default-import wiring every
|
||||||
|
build file consumes (docs/build-packages-plan.md)
|
||||||
|
build/ root-build helpers: image assembly (images.zig) + the QEMU
|
||||||
|
run steps (qemu.zig)
|
||||||
|
tools/ host-side build scripts
|
||||||
```
|
```
|
||||||
|
|
||||||
A sub-project exposes its **public interface as a module**: the `usb-xhci-bus` driver
|
**Builds are packages** (docs/build-packages-plan.md): each `library/` domain owns a
|
||||||
owns the USB transfer protocol (`usb-transfer-protocol.zig`, the `usb-transfer-protocol`
|
`build.zig`/`build.zig.zon` exporting its modules (with a standalone `zig build test`),
|
||||||
module), which `runtime.usb` imports by name — the USB class drivers reach the
|
every binary directory is a ~15-line package build, and the root `build.zig`
|
||||||
protocol through that wrapper; `block` exposes its protocol (`block-protocol`) the
|
orchestrates — the kernel + loader, what ships, and the aggregate test step — with
|
||||||
same way. The VFS wire protocol is the one that outgrew its
|
image assembly in `build/images.zig` and the QEMU run steps in `build/qemu.zig`.
|
||||||
sub-project: the VFS root moved into the kernel (`system/kernel/vfs.zig`), so the
|
|
||||||
protocol lives as a shared contract at `system/vfs-protocol.zig` (the `vfs-protocol`
|
**Wire protocols live in `library/protocol/`**, one module per directory
|
||||||
module), which the runtime's file API (`runtime.fs`) imports by name.
|
(`library/protocol/vfs/vfs-protocol.zig` is the `vfs-protocol` module), imported by module
|
||||||
|
name. A protocol is the seam between a low-level driver and the higher-level service it
|
||||||
|
serves — block ↔ the filesystem, a scanout driver ↔ the compositor — so both sides depend
|
||||||
|
on the contract, not on each other, and the contract belongs to neither sub-project. A
|
||||||
|
client module may *wrap* one for application convenience (the `file-system` module over
|
||||||
|
`vfs-protocol`, and the `block`, `display`, `input` clients over theirs), but the protocol
|
||||||
|
module is the boundary — a client re-exports no protocol, it imports it by name. A driver's
|
||||||
|
private wire to its *hardware* (virtio-gpu's command set) is not a service seam and stays a
|
||||||
|
driver-private file, beside the transport that reaches the same device.
|
||||||
|
|
||||||
|
**Device code lives in `library/device/<domain>/`**, grouped by what it is about (pci, usb,
|
||||||
|
acpi, and the cross-cutting device model) and split by dependency weight: a data module of
|
||||||
|
enums and wire types that is `std`-only and cheap for anyone to import, and a logic module
|
||||||
|
that needs `mmio` or IPC. This is what keeps the microkernel out of device business — it
|
||||||
|
imports exactly one `library/` module, `device-abi` (the descriptor types its broker
|
||||||
|
marshals across the syscall boundary), and nothing with logic or a taxonomy in it. That
|
||||||
|
lone pure-data import is the only edge from `system/kernel/` into `library/`.
|
||||||
|
|
||||||
There is **no POSIX/C compatibility layer today**: danos programs do file I/O through the
|
There is **no POSIX/C compatibility layer today**: danos programs do file I/O through the
|
||||||
danos-native `runtime.fs` (open/read/write/list over the VFS). A hand-rolled POSIX shim
|
danos-native `file-system` module (open/read/write/list over the VFS). A hand-rolled POSIX shim
|
||||||
(`library/posix/`) was retired as premature — the real POSIX/C surface will come later
|
(`library/posix/`) was retired as premature — the real POSIX/C surface will come later
|
||||||
from the `std.os.danos` seam (and, eventually, musl) when danos becomes a Zig target (see
|
from the `std.os.danos` seam (and, eventually, musl) when danos becomes a Zig target (see
|
||||||
[zig-self-hosting.md](zig-self-hosting.md)). When it does, the foreign-ABI naming
|
[zig-self-hosting.md](zig-self-hosting.md)). When it does, the foreign-ABI naming
|
||||||
@@ -272,8 +314,8 @@ exception in [coding-standards.md](coding-standards.md) applies to that seam.
|
|||||||
| Boot methods (one per way of booting the kernel) | `boot/` — `efi.zig` (UEFI) → `BOOTX64.efi` |
|
| Boot methods (one per way of booting the kernel) | `boot/` — `efi.zig` (UEFI) → `BOOTX64.efi` |
|
||||||
| Kernel entry, panic, bring-up | `system/kernel/kernel.zig` |
|
| Kernel entry, panic, bring-up | `system/kernel/kernel.zig` |
|
||||||
| Loader↔kernel handoff (`BootInformation`, `Framebuffer`, `MemoryMap`, VM layout) | `system/boot-handoff.zig` |
|
| Loader↔kernel handoff (`BootInformation`, `Framebuffer`, `MemoryMap`, VM layout) | `system/boot-handoff.zig` |
|
||||||
| Private kernel↔runtime syscall ABI (`SystemCall`, mmap prot flags, `page_size`) — the runtime speaks it, not apps | `system/abi.zig` |
|
| Private kernel↔userspace syscall ABI (`SystemCall`, mmap prot flags, `page_size`) — the system library speaks it, not apps | `system/abi.zig` |
|
||||||
| Device wire types (`DeviceDescriptor`, `DeviceClass`, …) | `system/devices/device-abi.zig` |
|
| Device wire types (`DeviceDescriptor`, `DeviceClass`, …) | `library/device/model/device-abi.zig` |
|
||||||
| Physical frame allocator | `system/kernel/pmm.zig` |
|
| Physical frame allocator | `system/kernel/pmm.zig` |
|
||||||
| Kernel heap (`std.mem.Allocator`) | `system/kernel/heap.zig` |
|
| Kernel heap (`std.mem.Allocator`) | `system/kernel/heap.zig` |
|
||||||
| Scheduler (fixed-priority preemptive; blocking, wait queues) | `system/kernel/scheduler.zig` |
|
| Scheduler (fixed-priority preemptive; blocking, wait queues) | `system/kernel/scheduler.zig` |
|
||||||
@@ -281,15 +323,19 @@ exception in [coding-standards.md](coding-standards.md) applies to that seam.
|
|||||||
| IPC channels between kernel threads (message passing) | `system/kernel/ipc.zig` |
|
| IPC channels between kernel threads (message passing) | `system/kernel/ipc.zig` |
|
||||||
| IPC endpoints: cross-address-space call/reply, handles, notifications | `system/kernel/ipc-synchronous.zig` |
|
| IPC endpoints: cross-address-space call/reply, handles, notifications | `system/kernel/ipc-synchronous.zig` |
|
||||||
| User processes: ELF loading, address spaces, the syscall table | `system/kernel/process.zig` |
|
| User processes: ELF loading, address spaces, the syscall table | `system/kernel/process.zig` |
|
||||||
| VFS root: mount table + kernel-served nodes (`fs_resolve`/`fs_node`); wire protocol in `system/vfs-protocol.zig` | `system/kernel/vfs.zig` |
|
| VFS root: mount table + kernel-served nodes (`fs_resolve`/`fs_node`); wire protocol in `library/protocol/vfs/vfs-protocol.zig` | `system/kernel/vfs.zig` |
|
||||||
| Device tree + claim capability + `device_register` containment | `system/kernel/devices-broker.zig` |
|
| Device tree + claim capability + `device_register` containment | `system/kernel/devices-broker.zig` |
|
||||||
| IRQ-as-IPC: routing a device interrupt to a driver's endpoint | `system/kernel/irq.zig` |
|
| IRQ-as-IPC: routing a device interrupt to a driver's endpoint | `system/kernel/irq.zig` |
|
||||||
| Hardware discovery (ACPI/device tree) behind one neutral device model | `system/devices/` |
|
| Hardware discovery (ACPI/device tree) behind one neutral device model | `system/kernel/platform.zig` |
|
||||||
| Framebuffer text console (mirrors to serial) | `system/kernel/console.zig` |
|
| Framebuffer text console (mirrors to serial) | `system/kernel/console.zig` |
|
||||||
| In-kernel test cases | `system/kernel/tests.zig` |
|
| In-kernel test cases | `system/kernel/tests.zig` |
|
||||||
| Arch-specific kernel code (`halt`, GDT/IDT/TSS, exception + interrupt stubs, page tables, APIC/IO-APIC/timer, serial, linker script) | `system/kernel/architecture/x86_64/` |
|
| Arch-specific kernel code (`halt`, GDT/IDT/TSS, exception + interrupt stubs, page tables, APIC/IO-APIC/timer, serial, linker script) | `system/kernel/architecture/x86_64/` |
|
||||||
| danos-native runtime (`runtime`): syscall wrappers, heap, IPC, device access, the file API (`fs`) — the stable application ABI | `library/runtime/` |
|
| danos-native system library (kernel32-style): the syscall surface by concern — `ipc`, `memory`, `process`, `time`, `logging`, `file-system`, `thread`, `service` — the stable application ABI | `library/kernel/` |
|
||||||
|
| Service clients (a program's view of a service) and device clients | `library/client/` (display, input), `library/device/driver` |
|
||||||
| System services (init, the `fat` filesystem, the device-manager) | `system/services/` |
|
| System services (init, the `fat` filesystem, the device-manager) | `system/services/` |
|
||||||
| Device drivers, one sub-project each (`pci-bus`, `ps2-bus`, `usb-xhci-bus` bus drivers) | `system/drivers/` |
|
| Device drivers, one sub-project each (`pci-bus`, `ps2-bus`, `usb-xhci-bus` bus drivers) | `system/drivers/` |
|
||||||
| Build + `run-x86-64` (QEMU/OVMF) + `release-x86-64` (the flashable ISO) | `build.zig` |
|
| On-image test fixtures for the QEMU cases (`vfs-test`, `crash-test`, `thread-test`, …) → `/test/system/services` | `test/system/services/` |
|
||||||
|
| Build orchestration (kernel + loader, what ships, the aggregate test step) | `build.zig` (root; the shared user-binary recipe is `build-support/`, and each `library/` domain + binary package carries its own `build.zig`) |
|
||||||
|
| Image assembly + `release-x86-64` (the flashable ISO) | `build/images.zig` |
|
||||||
|
| `run-x86-64` / `run-x86-64-gpu` (QEMU/OVMF) | `build/qemu.zig` |
|
||||||
| QEMU integration test harness | `test/qemu_test.py` |
|
| QEMU integration test harness | `test/qemu_test.py` |
|
||||||
@@ -0,0 +1,632 @@
|
|||||||
|
# The bounds track: removing the numbers we invented
|
||||||
|
|
||||||
|
*Plan, 2026-08-08. Follows [fixed-bounds-audit.md](fixed-bounds-audit.md) (235 ceilings,
|
||||||
|
139 on quantities we do not choose) and the AMD Ryzen that found the first one.*
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Live state — the unattended run
|
||||||
|
|
||||||
|
*This table is the progress view. It is updated at the end of every step, before the
|
||||||
|
next one starts.*
|
||||||
|
|
||||||
|
| Step | What | State |
|
||||||
|
|---|---|---|
|
||||||
|
| L1 | Reclamation: a dead task's registrations die with its claims | **stopped — the step was wrong; see open question 4** |
|
||||||
|
| L2 | Bounds build check + allowlist; declare what we have already touched | **done** — `zig build bounds`, 273 allowlisted, 5 declared |
|
||||||
|
| L3 | xHCI: slot count from `HCSPARAMS1.MaxSlots`, not 8 | **done** — QEMU reports 64; the driver tracked 8 |
|
||||||
|
| L4 | USB: configuration descriptor sized by `wTotalLength`, not 512 | **done** — QEMU tops out at 211 bytes, so the case catches the class, not the original trigger |
|
||||||
|
| L5 | USB: interfaces from the descriptor, and the misattributed-endpoint bug | **done** — fix is by construction; no direct test, see open question 5 |
|
||||||
|
| L6 | xHCI: a failed `allocateDevice` stops leaking an enabled slot | **done** — path forced and verified; no regression test, see open question 5 |
|
||||||
|
|
||||||
|
**Run 1 complete.** L1 stopped (the step was wrong), L2–L6 landed. Suite 115 → 116.
|
||||||
|
Allowlist 278 → 269. Two steps ship without a permanent regression test, both because
|
||||||
|
QEMU's USB devices are too small to reach the paths — see open question 5, which is the
|
||||||
|
audit's own lesson recurring: the test rig is smaller than a real machine.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Run 2 — device authority: delete the invented ceilings
|
||||||
|
|
||||||
|
*Design: [device-authority.md](os-development/device-authority.md), which is the **how**
|
||||||
|
for the delegation step [device-manager.md](device-driver-development/device-manager.md)
|
||||||
|
already settled. Read both before starting; the second is authoritative where they
|
||||||
|
differ.*
|
||||||
|
|
||||||
|
The goal, in the project owner's words: **remove the maximum values we set arbitrarily,
|
||||||
|
move the responsibility to the device manager, and keep in the kernel only the parts
|
||||||
|
that cannot safely run in user space.**
|
||||||
|
|
||||||
|
| Step | What | State |
|
||||||
|
|---|---|---|
|
||||||
|
| D0 | The grant rides `system_spawn` — atomic, so no driver need change to receive one | **done** |
|
||||||
|
| D1 | `device_transfer(device_id, task_id)` — the holder gives a device away | **done** — syscall 54; a move, not a copy |
|
||||||
|
| D2 | Adversarial case: a process handed nothing is refused | **done** — `device-authority-test`; the claim half joins it at D6 |
|
||||||
|
| D3 | The manager claims the seeded devices before any driver is spawned | **merged into D4** |
|
||||||
|
| D4 | `usb-xhci-bus` receives its controller | **done** — caught an IOMMU regression I introduced |
|
||||||
|
| D5 | `pci-bus`, `virtio-gpu`, `ps2-bus`, discovery receive theirs | **done** — every driver now receives its hardware |
|
||||||
|
| D6 | `device_claim` refuses a device the caller was not handed | **blocked on question 10** |
|
||||||
|
| D7 | Zero-resource devices stop being kernel objects | **blocked on question 8** |
|
||||||
|
| D8 | **`maximum_children_per_parent` deleted** | **done** |
|
||||||
|
| D9 | Dynamic table; **`maximum_devices` deleted**; per-registrar allowance | **done** |
|
||||||
|
| D10 | Every driver hellos, on its own merits | not started — optional, independent |
|
||||||
|
|
||||||
|
*Executed in the order D1, D2, D4, D5(part), D9, D0, D5(rest), D8 — the numbering is
|
||||||
|
the original plan's, not the sequence. D0 was added mid-run, D3 merged into D4, and D8
|
||||||
|
turned out to have been unblocked since D9.*
|
||||||
|
|
||||||
|
**Run 2 stops, blocked on one question.** Landed: D0, D1, D2, D4, D8, D9, and D5 for
|
||||||
|
three of five claimants (`usb-xhci-bus`, `pci-bus`, `virtio-gpu`). Suite 118/118.
|
||||||
|
|
||||||
|
**Both invented ceilings are gone.** `maximum_devices` and
|
||||||
|
`maximum_children_per_parent` no longer exist, and delegation is atomic with the spawn.
|
||||||
|
|
||||||
|
What remains is not a number: **D6 closes the claiming hole** and is blocked on
|
||||||
|
question 9, and D7 moves the inventory and is blocked on question 8.
|
||||||
|
|
||||||
|
Ordering is load-bearing. D1–D2 built and proved the mechanism with nothing depending on
|
||||||
|
it. D4–D5 move each claimant across one at a time, so the suite stays green throughout
|
||||||
|
and a regression names the driver that caused it. D6 is the flag day. (The original
|
||||||
|
"D7 must precede D9" no longer holds: the per-holder quota bounds zero-resource children
|
||||||
|
as well as anything else, so D9 landed without it.)
|
||||||
|
|
||||||
|
**D3 merged into D4** (found while implementing, recorded rather than worked around).
|
||||||
|
The two cannot be separated: the moment the manager claims a device, any driver still
|
||||||
|
calling `device_claim` on it is refused `AlreadyClaimed`, so D3 on its own turns the
|
||||||
|
suite red — and D3 applied to *nothing* changes no behaviour and cannot be tested.
|
||||||
|
They land together, with the manager claiming only for drivers in an explicit
|
||||||
|
**delegated set** so every unconverted driver keeps claiming exactly as before.
|
||||||
|
`usb-xhci-bus` is the first member, as it was the first driver to conform to `hello`
|
||||||
|
(device-manager.md, M18.1). D5 moves the rest in one at a time; the set and the
|
||||||
|
`device_claim` path both disappear at D6.
|
||||||
|
|
||||||
|
### Observations from the run
|
||||||
|
|
||||||
|
- **D4 introduced an IOMMU regression, caught by converting one driver at a time.**
|
||||||
|
`confineDevice` runs inside `systemDeviceClaim`, so a device arriving by *transfer*
|
||||||
|
was never confined for its new owner: the driver's DMA rings went unbound (three
|
||||||
|
IOMMU+USB cases failed), and two worse consequences were latent — a manager death
|
||||||
|
would have torn down a domain a live driver was using, and a driver death would have
|
||||||
|
leaked one. `iommu.reassign` moves the confinement with the device, keeping the
|
||||||
|
domain and attachment intact so it never translates through nothing. Converting all
|
||||||
|
five drivers at once would have produced the same three failures with five suspects.
|
||||||
|
- **`usb-hub` failed once in a full run, then passed six times** (four isolated, two
|
||||||
|
full). Suspected instance of the known intermittent AP ring-3 fault rather than
|
||||||
|
anything in D4 — recorded rather than dismissed, because D4 moved the `hello` earlier
|
||||||
|
and so did shift boot timing. Watch it across the remaining steps.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Run 3 — close the claiming hole
|
||||||
|
|
||||||
|
*Every driver now receives its hardware. What remains is that `device_claim` still
|
||||||
|
works for anyone, so a device nobody holds can still be taken. Six steps, no open
|
||||||
|
questions.*
|
||||||
|
|
||||||
|
### The rule this run implements
|
||||||
|
|
||||||
|
The kernel records, per device, **who gave it**. From that one field everything follows:
|
||||||
|
|
||||||
|
- `device_transfer` and the spawn-fused grant set the giver.
|
||||||
|
- **`device_claim` refuses a device that has a giver.** A device that was given to
|
||||||
|
someone is delegated hardware and must be handed on, never taken.
|
||||||
|
- **On death a device reverts to its giver**, if that task is still alive; otherwise its
|
||||||
|
claim clears. A grant is a loan, not a gift.
|
||||||
|
|
||||||
|
Two things fall out rather than being special-cased:
|
||||||
|
|
||||||
|
- **The framebuffer is untouched.** Nobody delegates it, so it has no giver, so the
|
||||||
|
display service can still claim it exactly as today. No exemption in the kernel, no
|
||||||
|
mention of display anywhere in the rule.
|
||||||
|
- **Restart needs no race.** A dying driver's device returns to the manager, which
|
||||||
|
re-delegates it on respawn. Previously the kernel released it to nobody and the
|
||||||
|
manager re-claimed first-come, so every restart reopened the hole.
|
||||||
|
|
||||||
|
**Found while implementing: E2 is the step that closes the hole, not E3.** A delegated
|
||||||
|
device is *held*, so an attempt to take it is refused as `AlreadyClaimed` long before
|
||||||
|
the giver is consulted — and once a borrower's death returns the device to its lender
|
||||||
|
(or clears both when the lender is gone), there is no state where a device is unheld and
|
||||||
|
still on loan. E3's check is therefore unreachable today. It stays as one comparison
|
||||||
|
that fails closed, guarding any future path that frees a device without clearing its
|
||||||
|
giver, and its comment says so rather than implying a protection it is not providing.
|
||||||
|
|
||||||
|
| Step | What |
|
||||||
|
|---|---|
|
||||||
|
| E1 | Record a giver per device; `device_transfer` and the spawn grant set it — **done** |
|
||||||
|
| E2 | On task death a device reverts to its giver if alive, else its claim clears — **done** |
|
||||||
|
| E3 | `device_claim` refuses a device that has a giver — **done**, but unreachable: E2 already closed the window |
|
||||||
|
| E4 | The manager claims every resource-bearing device at boot, so nothing is left takeable — **done** (boot snapshot only; see below) |
|
||||||
|
| E5 | The attacker fixture gains the claim half it has been waiting for since D2 — **done with E4** |
|
||||||
|
| E6 | Delete the delegated-set scaffolding — every driver is delegated now — **done** |
|
||||||
|
|
||||||
|
Ordering: E1 alone changes no behaviour. E2 must precede E3, or a restart cannot
|
||||||
|
re-acquire. E4 must precede E5, or the attacker will find takeable devices and the
|
||||||
|
assertion will be wrong about why. E6 is cleanup.
|
||||||
|
|
||||||
|
**Run 3 complete.** Suite 118/118. Every driver receives its hardware; a grant is a
|
||||||
|
loan that returns to its lender when the borrower dies; nothing firmware-discovered is
|
||||||
|
left unheld except the framebuffer, which the compositor owns.
|
||||||
|
|
||||||
|
### E4's scope, stated
|
||||||
|
|
||||||
|
It covers the **boot snapshot**. A device *reported* later and matched to no driver
|
||||||
|
stays claimable — `pci-cap-test` and `iommu-fault-test` both rely on that to reach an
|
||||||
|
unmatched NIC. Narrowing it further is a separate change with those fixtures in scope.
|
||||||
|
|
||||||
|
The real gap it closed was the **HPET**: an MMIO window, an IRQ, no user-space driver,
|
||||||
|
and claimable by anyone. Excluded on purpose: the loader's framebuffer (the manager
|
||||||
|
starts before display, so taking it would break the boot screen) and anything with no
|
||||||
|
resources, which grants nothing.
|
||||||
|
|
||||||
|
### Not in this run, and not blocking it
|
||||||
|
|
||||||
|
**Zero-resource devices stay in the kernel.** Moving them out needs an answer to who
|
||||||
|
mints their ids, given that the id is the `device_token` on the usb-transfer wire and
|
||||||
|
the kernel's idempotency is what keeps it stable across a bus restart. Nothing depends
|
||||||
|
on it: both invented ceilings are already gone and this run does not need it. Recorded
|
||||||
|
as future work.
|
||||||
|
|
||||||
|
**Not every driver hellos.** Delivery no longer needs it, so it stands or falls on its
|
||||||
|
own merits — uniform liveness and one class of driver. Also future work.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Question 9 — answered: a singleton gets every device that matched it
|
||||||
|
|
||||||
|
The 8042 is one controller described by two ACPI nodes, so it cannot be split across
|
||||||
|
processes. The manager now hands the single `ps2-bus` instance **every** matching node:
|
||||||
|
the first rides the spawn, the rest are transferred to the running instance. Late
|
||||||
|
arrival is safe because the ordering is natural rather than lucky — the controller node
|
||||||
|
carries the ports and is needed at once, the mouse node not until after identify
|
||||||
|
(measured: handed over at 0.336, first touched at 0.456). The count is whatever matched,
|
||||||
|
so a machine with no PS/2 ports or one port needs no special case.
|
||||||
|
|
||||||
|
Discovery turned out not to be special either. The kernel seeds the `acpi-tables` node,
|
||||||
|
so it is in the same boot snapshot the manager already scans for the PCI host bridge —
|
||||||
|
it is handed over at spawn like everything else.
|
||||||
|
|
||||||
|
### Open question 10 — the framebuffer is the last thing anyone claims
|
||||||
|
|
||||||
|
`device_claim` now has exactly two callers: the device manager, which is the acquirer
|
||||||
|
and should have it, and `system/services/display/backend.zig`, whose GOP path claims the
|
||||||
|
kernel-seeded display node.
|
||||||
|
|
||||||
|
Closing `device_claim` breaks the compositor's boot floor. Exempting it puts a hole in
|
||||||
|
the middle of the authority model, in the one place an exemption is most expensive.
|
||||||
|
|
||||||
|
The likely answer is neither. **The framebuffer is not a device** — it is where pixels
|
||||||
|
go, handed over by the loader, and the kernel wraps it in a `DeviceClass.display`
|
||||||
|
descriptor only so `mmio_map` can hand it over write-combining. If that is right, it
|
||||||
|
should leave the device table rather than be exempted from its rules, and the compositor
|
||||||
|
should receive the pixels some other way. That is a change to the display path, which is
|
||||||
|
out of scope for this run.
|
||||||
|
|
||||||
|
### Settled 2026-08-08: the grant rides `system_spawn` (D0)
|
||||||
|
|
||||||
|
Questions 6 and 7 both dissolved on inspection — neither `ps2-bus` nor discovery needs
|
||||||
|
to start speaking `hello`, and `virtio-gpu` has no standalone path to lose. What remains
|
||||||
|
is *where the grant is delivered*, and there are three candidates:
|
||||||
|
|
||||||
|
| | Race window | Cost |
|
||||||
|
|---|---|---|
|
||||||
|
| Transfer after spawn | **yes** | none |
|
||||||
|
| Every driver hellos | no | `ps2-bus` + discovery gain a handshake |
|
||||||
|
| **Grant rides `system_spawn`** | **no — atomic** | one more syscall argument |
|
||||||
|
|
||||||
|
**Take the third.** The manager cannot transfer before the child exists, so a separate
|
||||||
|
transfer always leaves a window in which the child is running and does not yet hold its
|
||||||
|
device. It would close on QEMU every time and open occasionally on a machine with
|
||||||
|
different timing — the exact failure shape this track exists to delete, and not worth
|
||||||
|
introducing while removing the others. Fusing the device into the spawn removes it by
|
||||||
|
construction: the child does not exist until it holds the device. No new knowledge in
|
||||||
|
the kernel — the same rule, *you may give away what you hold*, made atomic with the call
|
||||||
|
that creates the recipient. `system_spawn` uses five of six argument registers, so there
|
||||||
|
is room, and `no_device` is already the sentinel for a driver with no assignment.
|
||||||
|
|
||||||
|
**`hello` for every driver is a good idea on its own merits** — uniform liveness, the
|
||||||
|
deadline applied to all rather than some, and the `speaks_protocol` two-class split
|
||||||
|
leaving the manager (a wedged `ps2-bus` is invisible to its supervisor today). It is
|
||||||
|
D10, kept separate so grant delivery does not force it.
|
||||||
|
|
||||||
|
### Open questions raised by D5 — resolved except question 8
|
||||||
|
|
||||||
|
Delegation is delivered in `onHello`. That works for a driver that says hello, and
|
||||||
|
**two of the four do not**.
|
||||||
|
|
||||||
|
6. **`ps2-bus` does not hello**, and that is deliberate: device-manager.md records
|
||||||
|
"Legacy drivers (e.g. ps2-bus) are supervised and restarted but **not yet required
|
||||||
|
to hello**", and `Driver.speaks_protocol` exists to say so. Either it leaves
|
||||||
|
"legacy", or the grant gets a delivery point that is not `hello`.
|
||||||
|
|
||||||
|
**The `acpi` service is not this case — an earlier version of this question wrongly
|
||||||
|
lumped it in.** It is spawned as `addDriver("discovery", no_device, false)`: the
|
||||||
|
*discovery service*, one per firmware, with **no device assignment at all**, which
|
||||||
|
"finds and claims the acpi-tables (or devicetree-blob) node itself. Not a per-device
|
||||||
|
driver." The manager cannot hand it a device because discovery is what produces the
|
||||||
|
device tree — there is nothing to match against yet. Its question is not "should it
|
||||||
|
hello" but "is the bootstrap exempt from D6, or does the manager claim the
|
||||||
|
acpi-tables node and pass it on".
|
||||||
|
|
||||||
|
**A delivery point that needs no hello already exists in the shape of the code**:
|
||||||
|
`process.spawnSupervised` returns the child's pid, so the manager could transfer
|
||||||
|
immediately after spawn. If that is acceptable, this question mostly dissolves —
|
||||||
|
`ps2-bus` would not need to leave "legacy" and discovery could be handed its node
|
||||||
|
too. The cost is ordering: the child may reach for the device before the transfer
|
||||||
|
lands, where `hello` guarantees it cannot because the child is the one asking. That
|
||||||
|
trade is the actual decision.
|
||||||
|
|
||||||
|
7. **`virtio-gpu`'s "standalone bring-up" — resolved; there is no such path.** An
|
||||||
|
earlier version of this question read the comment "Best-effort: standalone bring-up
|
||||||
|
has no manager" as a boot path that delegation would delete. It is not one.
|
||||||
|
`virtio-gpu`'s `main` requires `argv[1]` and exits without it, and the only source of
|
||||||
|
that argument is the device manager — the chain is ACPI → pci-bus reports the
|
||||||
|
function → `devices.csv` matches `1AF4:1050` → the manager spawns the driver with the
|
||||||
|
id. There is no way to run it without a manager, so nothing is lost.
|
||||||
|
|
||||||
|
What the comment is really about is **resilience**: the hello is best-effort so a
|
||||||
|
driver whose manager has *died* keeps serving, which device-manager.md states
|
||||||
|
("If the manager dies, drivers keep running").
|
||||||
|
|
||||||
|
The residual is one narrow window: the manager spawns a driver and dies before
|
||||||
|
transferring. Today the driver could still claim, because claiming is free-for-all;
|
||||||
|
after D6 it exits and the restarted manager respawns it. That is the better
|
||||||
|
behaviour — a driver holding hardware nobody assigned it is what D6 exists to stop.
|
||||||
|
|
||||||
|
Until these are answered, `device_claim` cannot be closed off at D6 for those three, so
|
||||||
|
**D6 is blocked on questions 6 and 7**.
|
||||||
|
|
||||||
|
8. **Removing zero-resource devices from the kernel needs someone else to mint their
|
||||||
|
ids, and nothing says who.** A USB interface is registered with
|
||||||
|
`resource_count = 0`, and the id `device_register` returns is load-bearing in three
|
||||||
|
places: it is the `child_added` packet's target, it is the class driver's `argv[1]`,
|
||||||
|
and it is the `device_token` of the **usb-transfer wire protocol** — so the id space
|
||||||
|
is visible on the wire, not merely internal. usb-xhci-bus's own comment records the
|
||||||
|
fourth constraint: the kernel's idempotency is what makes "the same port and
|
||||||
|
interface always map back to the same device id" across a bus restart, which is what
|
||||||
|
stops a respawned bus spawning duplicate class drivers.
|
||||||
|
|
||||||
|
So the mover has to answer: who mints the id, how it stays stable across a *bus*
|
||||||
|
restart, how it stays stable across a *manager* restart (open question 3 territory),
|
||||||
|
and whether the wire protocol's `device_token` changes meaning. That is a design
|
||||||
|
step, not a mechanical one.
|
||||||
|
|
||||||
|
**D8 is reordered to run after D9**, which is a correction to the original sequencing.
|
||||||
|
D8's justification was "the authorisation it stood in for exists" — but with D6 blocked
|
||||||
|
it does not, so deleting the shared per-parent cap now would reopen the exhaustion hole
|
||||||
|
it was written for. D9's **per-holder quota** closes that hole independently of
|
||||||
|
authorisation, and does it better: a rogue exhausts its own allowance rather than the
|
||||||
|
table everyone shares. Once the quota exists, the per-parent cap is redundant whether or
|
||||||
|
not D6 has landed.
|
||||||
|
|
||||||
|
D9 also no longer depends on D7. Its original rationale was that zero-resource children
|
||||||
|
are the case that sidesteps containment — true, but a per-holder quota bounds them just
|
||||||
|
as well as anything else, because it counts entries per holder rather than per parent.
|
||||||
|
|
||||||
|
### Settled, so the run does not re-litigate them
|
||||||
|
|
||||||
|
- **The manager claims, it is not granted.** No binary names in the kernel; the rule is
|
||||||
|
"you may give away what you hold". The residual — it rests on the manager claiming
|
||||||
|
first — is stated in the design and is closed later by the spawn capability
|
||||||
|
[drivers.md](device-driver-development/drivers.md) already names as missing.
|
||||||
|
- **The framebuffer is not a device.** It is where pixels go, handed over by the loader,
|
||||||
|
and the compositor uses it as the boot floor until a real display driver announces
|
||||||
|
itself. Nothing in this run touches the display service or its GOP path.
|
||||||
|
- **`maximum_endpoints_per_interface` and the wire structs stay.** Widening them is a
|
||||||
|
protocol change, out of scope.
|
||||||
|
- **A per-holder quota is not a retreat.** Dynamic storage with no bound moves the
|
||||||
|
ceiling to the kernel heap, which is shared and fatal rather than partial. A bound
|
||||||
|
charged to the task that caused it is isolation, and it is declared through
|
||||||
|
[bounds.md](os-development/bounds.md) like anything else.
|
||||||
|
|
||||||
|
### Working rules
|
||||||
|
|
||||||
|
As Run 1, unchanged: work in `/Users/danielsamson/Gitea/daniel/danos` on
|
||||||
|
`claude/bounds-track`; every step lands with a test that fails before the fix, verified
|
||||||
|
by restoring the old behaviour; full suite green before each commit; never two suites at
|
||||||
|
once (`pgrep -f qemu_test.py`); 60 GiB free; `git commit -F` with no `Co-Authored-By`;
|
||||||
|
update this table before starting the next step. **If a step needs a decision that is
|
||||||
|
not written down, stop it, add the question below, and move on** — Run 1's first step
|
||||||
|
was wrong and stopping was the right call.
|
||||||
|
|
||||||
|
**Suite:** 115/115 at the start of the run.
|
||||||
|
**Branch:** `claude/bounds-track`.
|
||||||
|
|
||||||
|
### What this run deliberately does not touch
|
||||||
|
|
||||||
|
Phases 2 and 3 below — the authorisation gate and moving the inventory to the device
|
||||||
|
manager — are **out of scope for unattended work**. They decide whether the OS is
|
||||||
|
secure, and they are currently a direction rather than a specification: what a device
|
||||||
|
capability *is*, which syscalls change, what replaces `device_claim` for its seven
|
||||||
|
callers, how a driver spawned bare behaves. Those want a design session, the way
|
||||||
|
`/protocol` had one.
|
||||||
|
|
||||||
|
Also out of scope: anything touching `maximum_device_resources` (a wire struct, so a
|
||||||
|
trust-boundary change, not a resize), and the non-device bounds the audit found in FAT,
|
||||||
|
the VFS, logger, init, display and boot.
|
||||||
|
|
||||||
|
### Open questions this run must not answer on its own
|
||||||
|
|
||||||
|
Recorded here rather than guessed. If a step runs into one, it stops and writes the
|
||||||
|
question down instead of inventing an answer.
|
||||||
|
|
||||||
|
1. **`device_enumerate` probably narrows rather than retires.** The device manager
|
||||||
|
calls it to find `pci_host_bridge` nodes — it cannot ask itself. The likely shape is
|
||||||
|
that the kernel keeps the *firmware-discovered roots* (which by principle 5 it holds
|
||||||
|
for real reasons, since they come from ACPI rather than a driver's say-so) and
|
||||||
|
everything a driver registered lives in the manager. Not decided.
|
||||||
|
2. **A device-manager restart has no re-enumerate handshake.** If only the manager
|
||||||
|
dies, the buses are alive and never re-send `child_added`, so a restarted manager
|
||||||
|
comes back blind. The manager is restartable by design; nothing implements this.
|
||||||
|
3. **Which adversarial tests I1–I3 need.** The audit's six real defects were all found
|
||||||
|
by asking what an attacker would do, and the suite had never asked. "Add adversarial
|
||||||
|
cases" is not executable until the attacks are named.
|
||||||
|
4. **Reclamation is not a death-sweep problem, and L1 as written would have broken the
|
||||||
|
restart path.** Found on the first attempt at it. The audit is right that `count`
|
||||||
|
never decreases, but *death is the wrong trigger*:
|
||||||
|
- The broker keeps entries deliberately: "The devices stay in the table — they
|
||||||
|
describe hardware, which did not go away — only their ownership clears." A driver
|
||||||
|
dying does not unplug anything.
|
||||||
|
- Device ids must stay **stable across a bus restart**, because
|
||||||
|
`device-manager.driverForDevice` dedupes by `device_id` so that "a re-report after
|
||||||
|
a bus restart must not spawn a second instance". Stability comes from the
|
||||||
|
idempotency scan returning the existing id — removing entries on death would give
|
||||||
|
a restarted bus fresh ids and spawn duplicate driver instances.
|
||||||
|
- Everything else a task holds *is* already reclaimed on every path out:
|
||||||
|
`irq.releaseOwner`, `iommu.releaseAllOwnedBy`, `dmaRegistryReleaseOwner`, then the
|
||||||
|
broker's claims (`process.releaseTaskResourcesLocked`).
|
||||||
|
|
||||||
|
So the real leak has two sources, and neither is death: a device that genuinely
|
||||||
|
**goes away** (hot-unplug) has no retirement path, and a bus that enumerates
|
||||||
|
*differently* on restart leaves its stale entries behind forever. Both are the device
|
||||||
|
manager's inventory problem — phase 3 — and both need the id-stability question
|
||||||
|
answered first (tombstone-and-reuse aliases stale ids held by another process;
|
||||||
|
generation-tagged ids change the id encoding, which is ABI). Not an unattended
|
||||||
|
decision.
|
||||||
|
5. **Driver descriptor parsing cannot be host-tested, so L5's correctness fix ships
|
||||||
|
without a direct test.** The endpoint-misattribution bug lives in
|
||||||
|
`parseConfiguration`, a pure function over a byte blob — exactly the shape a host
|
||||||
|
unit test wants, and `usb-storage/scsi.zig` and `usb-hid/hid-report.zig` already do
|
||||||
|
this. But `usb-xhci-library.zig` imports `memory`, `mmio` and `time`, so it cannot
|
||||||
|
be a standalone host-test root, and QEMU offers no device that would exercise the
|
||||||
|
path anyway: the largest available is `usb-audio,multi=on` at 2 interfaces and 211
|
||||||
|
bytes, against a cap of 4.
|
||||||
|
|
||||||
|
Three ways out, and picking one is a judgement about house style rather than a
|
||||||
|
mechanical step: extract the parser to its own file and wire `usb-abi` into a test
|
||||||
|
module (build-support currently resolves module names only for `userBinary`);
|
||||||
|
extract it and import `usb-abi` by relative path (against the import-by-name
|
||||||
|
convention); or accept QEMU-only coverage and say so.
|
||||||
|
|
||||||
|
Mitigating, and the reason this is recorded rather than blocking: after the fix the
|
||||||
|
bug is unreachable **by construction**, not by the added `else`. Interfaces are now
|
||||||
|
allocated to exactly the count the descriptor declares, so `interface_count` can
|
||||||
|
never reach `interfaces.len` mid-parse. The `else` is belt-and-braces for the
|
||||||
|
255-interface clamp. The alternate-setting path that shares it *is* exercised —
|
||||||
|
`usb-audio` has alternate settings, and the `usb-large-descriptor` case walks them.
|
||||||
|
|
||||||
|
### Working rules for the run
|
||||||
|
|
||||||
|
- Work in `/Users/danielsamson/Gitea/daniel/danos` (not a worktree), on
|
||||||
|
`claude/bounds-track`.
|
||||||
|
- **Every step lands with a test that fails before the fix**, verified by temporarily
|
||||||
|
restoring the old behaviour and watching exactly the intended assertion flip. A test
|
||||||
|
that passes both ways is not a test.
|
||||||
|
- Full QEMU suite green before each commit. Never run two suites at once — check
|
||||||
|
`pgrep -f qemu_test.py` first; a second concurrent run produces false triple faults
|
||||||
|
because both share `zig-out`.
|
||||||
|
- Check at least 60 GiB free before starting a suite.
|
||||||
|
- Commit with `git commit -F <file>`, never `-m` (a backtick in a message is executed
|
||||||
|
by the shell and silently eats a word). No `Co-Authored-By` trailers.
|
||||||
|
- Update the Live state table **before** starting the next step.
|
||||||
|
- If a step needs a decision that is not written down here, stop, add it to the open
|
||||||
|
questions above, and move to the next step.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## The principles this is derived from
|
||||||
|
|
||||||
|
1. **danOS is a microkernel.** Minimise what the kernel is responsible for; move
|
||||||
|
responsibility to user space so it can be restarted, or fixed live during
|
||||||
|
development, without taking the system down.
|
||||||
|
2. **Implement the specifications correctly**, with the limits those specifications
|
||||||
|
define — not limits we decide.
|
||||||
|
3. **Move as much responsibility as possible to user space** (the device manager).
|
||||||
|
4. **What remains in the kernel is minimal.**
|
||||||
|
5. **What remains in the kernel is there for security or for a hardware limitation.**
|
||||||
|
Nothing else earns a place.
|
||||||
|
|
||||||
|
Principle 5 is the test every bound is put to. For each one: *is this here because of
|
||||||
|
security, or because of a hardware limitation?* If neither, the storage does not belong
|
||||||
|
in the kernel and the bound is not a number to be resized — it is a thing to be moved or
|
||||||
|
deleted.
|
||||||
|
|
||||||
|
Applying it to the case that started this:
|
||||||
|
|
||||||
|
- `maximum_devices = 64` bounds an inventory of hardware. An inventory is neither a
|
||||||
|
security control nor a hardware limitation. **The table is in the wrong place**; the
|
||||||
|
number is a symptom.
|
||||||
|
- `maximum_children_per_parent = 16` exists because `device_claim` is unauthenticated —
|
||||||
|
any process can claim any unclaimed device ([devices-broker.zig:164](../system/kernel/devices-broker.zig:164)
|
||||||
|
checks only that the device exists and is free). The cap is a crude proxy for an
|
||||||
|
authorisation the kernel does not perform. **Fix the authorisation and the cap has
|
||||||
|
nothing to defend.**
|
||||||
|
- `maximum_domains = 64` bounds IOMMU translation domains. Security — stays in the
|
||||||
|
kernel. But VT-d and AMD-Vi both *report* how many domains they support in a
|
||||||
|
capability register. Principle 2: read it. We chose 64 without asking.
|
||||||
|
|
||||||
|
## The security invariants
|
||||||
|
|
||||||
|
Every phase must leave all five standing. This is the "without punching a hole" half of
|
||||||
|
the brief, and each phase below states how it is checked.
|
||||||
|
|
||||||
|
- **I1 Containment.** A process may map only physical memory inside a resource it was
|
||||||
|
granted. A bus may subdivide only what it already holds.
|
||||||
|
- **I2 Confinement.** A DMA-capable device is under IOMMU translation before its driver
|
||||||
|
can program it, or it is not driven at all.
|
||||||
|
- **I3 No self-granted authority.** A process holds what it was handed. It cannot name
|
||||||
|
its way into holding more.
|
||||||
|
- **I4 Death releases everything.** Every resource a task held is reclaimed when it
|
||||||
|
dies, on every path out.
|
||||||
|
- **I5 Refusal is attributable.** Every refusal names the rule that refused it.
|
||||||
|
|
||||||
|
## Phase 0 — Done
|
||||||
|
|
||||||
|
- **Errno attribution.** One errno space in `system/abi.zig`; `device_register`'s six
|
||||||
|
refusals and `device_claim`'s three are distinct codes; call sites name the reason;
|
||||||
|
`pci-bus` reconciles found against registered. (I5)
|
||||||
|
- **Idempotency ordering.** A re-registration consumes no slot, so a full parent
|
||||||
|
re-admits an identical child. A restarted bus is no longer billed for what it
|
||||||
|
rediscovers.
|
||||||
|
|
||||||
|
Suite 114/114.
|
||||||
|
|
||||||
|
## Phase 1 — Reclamation
|
||||||
|
|
||||||
|
**Nothing may become dynamic before this.** Today `count` only ever increases and
|
||||||
|
`releaseAllOwnedBy` clears a dead driver's *claims* but not its *registrations*. With a
|
||||||
|
fixed table that is a slow march to the cap; with dynamic storage it is an unbounded
|
||||||
|
leak, and every supervisor restart makes it worse.
|
||||||
|
|
||||||
|
- Extend the existing death sweep so a task's registrations go with its claims.
|
||||||
|
- A registration whose owner is gone is removed; its children are re-parented or removed
|
||||||
|
with it (they cannot outlive the authority that published them).
|
||||||
|
- Test: register under a claimed parent, kill the owner, assert the entries are gone and
|
||||||
|
the ids are not reused while any handle to them lives.
|
||||||
|
|
||||||
|
Invariant: **I4**.
|
||||||
|
|
||||||
|
## Phase 2 — Close the authorisation hole
|
||||||
|
|
||||||
|
The device manager already decides which driver gets which device — it matches against
|
||||||
|
`devices.csv` and spawns the driver with the device id as `argv[1]`. Nothing binds that
|
||||||
|
decision to the kernel's `claim`. A driver passes an integer; the kernel checks only
|
||||||
|
that the device is free.
|
||||||
|
|
||||||
|
Per principles 3 and 5: **the decision stays in user space; the kernel enforces only
|
||||||
|
possession.** The manager hands the driver the device it matched; the kernel's job is
|
||||||
|
that a driver holds what it was handed and nothing else.
|
||||||
|
|
||||||
|
- The manager passes a device to the driver it spawned, over the existing cap-passing
|
||||||
|
path. Possession is the authority.
|
||||||
|
- `device_claim` stops being a way to *acquire* a device by naming it.
|
||||||
|
- Exclusivity stops being a broker refusing a second claimant and becomes the ordinary
|
||||||
|
property of a thing only one process was given.
|
||||||
|
|
||||||
|
**`maximum_children_per_parent` is deleted here**, because after this a bus driver's
|
||||||
|
children are the devices it actually enumerated under a bus it was actually given, and
|
||||||
|
the rogue-driver-fills-the-table threat the cap was written for no longer exists.
|
||||||
|
|
||||||
|
Invariants: **I3** (the point of the phase), **I1** (containment is unchanged and still
|
||||||
|
checked on every subdivision), **I5**.
|
||||||
|
|
||||||
|
Acceptance: a driver that names a device it was not given is refused, with its own
|
||||||
|
errno. The QEMU suite gains an adversarial case for it — the audit's lesson was that
|
||||||
|
"the suite contains no attacker".
|
||||||
|
|
||||||
|
## Phase 3 — The inventory moves to user space
|
||||||
|
|
||||||
|
The kernel reads only three things out of a device descriptor: **physical ranges** (to
|
||||||
|
check a mapping falls inside one), **interrupt numbers**, and **one PCI BDF** (to key an
|
||||||
|
IOMMU domain). Vendor and device ids, class triples, subsystem ids, human-readable
|
||||||
|
names, bus numbers and parent links are stored solely so `device_enumerate` can hand
|
||||||
|
them back. That is the kernel acting as a distribution mechanism for data it does not
|
||||||
|
use — principle 5 excludes it.
|
||||||
|
|
||||||
|
- **Zero-resource devices leave the kernel entirely.** A USB device addressed through
|
||||||
|
its controller conveys no mapping authority; there is nothing for the kernel to
|
||||||
|
enforce. It is pure inventory and belongs to the device manager. (This is also the
|
||||||
|
case that sidesteps containment, which is why the cap existed.)
|
||||||
|
- Identity and topology move to the manager, which already receives them as
|
||||||
|
`child_added` reports and already holds the authoritative picture.
|
||||||
|
- `device_enumerate` retires; callers ask the manager, whose protocol already reserves
|
||||||
|
an `enumerate` verb. Public-ABI change — `docs/os-development/vdso.md` documents it.
|
||||||
|
- What the kernel keeps: for each device that carries resources, the ranges, the GSIs,
|
||||||
|
the BDF, and the owner.
|
||||||
|
|
||||||
|
After this, the kernel's table holds only resource-bearing devices, and the remaining
|
||||||
|
count is bounded by what the machine physically has rather than by us.
|
||||||
|
|
||||||
|
Invariants: **I1**, **I2** unchanged — both operate on resources, which do not move.
|
||||||
|
**I4** must be re-checked: the manager's table now needs its own reclamation, and it is
|
||||||
|
restartable, so it must be able to rebuild from the buses.
|
||||||
|
|
||||||
|
## Phase 4 — Ask the hardware and the specification
|
||||||
|
|
||||||
|
Principle 2, applied to every remaining bound. Each of these is a number the machine or
|
||||||
|
the standard already states, which we replaced with a guess. Independent of each other;
|
||||||
|
can proceed in any order.
|
||||||
|
|
||||||
|
| Today | Ask instead |
|
||||||
|
|---|---|
|
||||||
|
| `maximum_domains = 64` (IOMMU) | the VT-d / AMD-Vi capability register reports the domains supported |
|
||||||
|
| `max_devices = 8` (xHCI slots) | `HCSPARAMS1.MaxSlots` — the controller says (1–255) |
|
||||||
|
| `max_interfaces = 4`, `max_endpoints` | the configuration descriptor says |
|
||||||
|
| `blob: [512]u8` (USB config) | the device's `wTotalLength` |
|
||||||
|
| `below: [64]Range` (memory map) | UEFI reports the descriptor count |
|
||||||
|
| AML blobs capped at 6 | the XSDT's length field gives the entry count |
|
||||||
|
| `maximum_cpus = 128` | the MADT entry count |
|
||||||
|
| `maximum_gsi = 24` | the I/O APIC's redirection-entry count; and more than one I/O APIC exists |
|
||||||
|
| MSI-X vectors | the capability's table-size field (up to 2048) |
|
||||||
|
|
||||||
|
Several of these are in user space already (xHCI, USB descriptors) and are ordinary
|
||||||
|
allocations — principle 1 means those are also the safest to do first, since a mistake
|
||||||
|
restarts a driver rather than the machine.
|
||||||
|
|
||||||
|
Two in this table are **also** correctness fixes the audit found, and should carry their
|
||||||
|
regression tests: the xHCI `max_interfaces` path misattributes a fifth interface's
|
||||||
|
endpoints to interface 3, and `below: [64]Range` silently turns occupied RAM into a PCI
|
||||||
|
aperture — which is an **I1 violation reachable on real hardware**, not merely a lost
|
||||||
|
device. That one is the highest-priority item in this phase.
|
||||||
|
|
||||||
|
## Phase 5 — What legitimately remains
|
||||||
|
|
||||||
|
After phases 1–4 the survivors should be only:
|
||||||
|
|
||||||
|
- **Pre-allocator storage**: the PMM's own frame bitmap, the memory map the loader hands
|
||||||
|
over, the bootstrap page tables. You cannot allocate the allocator. (Hardware/boot
|
||||||
|
limitation — principle 5 admits these.)
|
||||||
|
- **Interrupt-context storage**: the IST stack and anything an exception path touches
|
||||||
|
without allocating.
|
||||||
|
- **Wire structures** whose layout the other side of a trust boundary parses.
|
||||||
|
- **Facts that are not ceilings**: a page is 4096 bytes; an ACPI name segment is 4.
|
||||||
|
|
||||||
|
Each is declared per [bounds.md](os-development/bounds.md) — what it counts, who decides
|
||||||
|
its size, what it protects, what happens at the limit, how you find out. And two numbers
|
||||||
|
that must agree agree in code, not in a comment:
|
||||||
|
|
||||||
|
```zig
|
||||||
|
comptime {
|
||||||
|
if (maximum_domains != devices_broker.maximum_devices)
|
||||||
|
@compileError("iommu.confined is indexed by device id; an id past its end is " ++
|
||||||
|
"left unconfined while confineDevice still reports success");
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## The one that must not wait
|
||||||
|
|
||||||
|
[`iommu.zig:107`](../system/kernel/iommu.zig:107) — `if (device_id >= confined.len) return
|
||||||
|
true;` — returns *success* without confining. It is unreachable today only because
|
||||||
|
device ids stop at 64. **Phases 3 and 4 both change the device count, and either makes
|
||||||
|
it live.** Fix it before them: out of range must refuse, never allow. (I2)
|
||||||
|
|
||||||
|
This is also the standing rule the audit argues for: at a bound, the safe direction is
|
||||||
|
refusal. A ceiling that fails open is not a limit, it is a switch that turns the
|
||||||
|
protection off.
|
||||||
|
|
||||||
|
## How this is verified
|
||||||
|
|
||||||
|
- The QEMU suite is the arbiter at every step; it is 114 cases and must stay green.
|
||||||
|
- Each fix lands with a test that **fails before it** — as the idempotency reorder did,
|
||||||
|
where exactly one assertion flipped.
|
||||||
|
- Adversarial cases for I1–I3 specifically: the audit's six real defects were all found
|
||||||
|
by asking "what would an attacker do", and the suite had never asked.
|
||||||
|
- The Ryzen is the acceptance test. It is the machine that found this, and the one that
|
||||||
|
proves it fixed.
|
||||||
|
|
||||||
|
## Sequencing
|
||||||
|
|
||||||
|
Phase 1 gates everything. Phase 2 gates phase 3 — the inventory cannot move until
|
||||||
|
authority is sound, or moving it is the hole. Phase 4 is independent and its user-space
|
||||||
|
items are the safest work in the track. Phase 5 is the record of what survived.
|
||||||
|
|
||||||
|
The IOMMU fail-open is fixed before phase 3 or 4 touches the device count.
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
# Plan: packages — hierarchical builds for libraries and binaries
|
||||||
|
|
||||||
|
**Status: complete** (branch `claude/build-packages-plan-174144`). Phase 0
|
||||||
|
(`build-support`), phase 1 (all six library domains), phase 2 (every binary —
|
||||||
|
the pci-bus pilot first, then services, drivers, and test fixtures in waves;
|
||||||
|
multi-binary directories like ps2-bus and usb-hid are one package exporting
|
||||||
|
several artifacts, and the acpi/fdt discovery pair each export an artifact
|
||||||
|
named "discovery" that the root's -Ddiscovery picks between), and phase 3 (the
|
||||||
|
root split into `build/images.zig` + `build/qemu.zig`; the root `build.zig` is
|
||||||
|
~460 lines of orchestration, down from ~1,250). Every phase landed green: unit
|
||||||
|
tests, the QEMU suite at parity with main, boot-image file list unchanged.
|
||||||
|
The `lazyDependency` payoff (What-this-buys #4) is in too: the /test fixtures
|
||||||
|
and the unselected discovery package are lazy — a build loads and compiles
|
||||||
|
only what it ships. And imports are exact: the pre-wired default set is gone;
|
||||||
|
every binary names precisely the modules its source imports and carries only
|
||||||
|
those domains in its manifest (rule 1 below).
|
||||||
|
|
||||||
|
## Why
|
||||||
|
|
||||||
|
`build.zig` was ~1,250 lines, growing by three hand-written stanzas per binary;
|
||||||
|
at a driver per device family that does not scale. More fundamentally: in one
|
||||||
|
monolithic build every binary compiles against library *source*, so a library
|
||||||
|
interface break is silently absorbed by whoever edits everything in one commit —
|
||||||
|
the interface never has to be honest. danos is about isolation; the build should
|
||||||
|
mirror it.
|
||||||
|
|
||||||
|
A **package** here is a build-time unit only — a directory owning a `build.zig`
|
||||||
|
(recipe: what it exports, how to test it) and a `build.zig.zon` (manifest: name
|
||||||
|
+ dependencies). Binaries remain fully static freestanding ELFs; packages change
|
||||||
|
who declares what, not what links to what. Source code is untouched: `@import`
|
||||||
|
uses module names (`"pci"`, `"service"`) exactly as today — only build files
|
||||||
|
know where anything lives.
|
||||||
|
|
||||||
|
## Target shape
|
||||||
|
|
||||||
|
```
|
||||||
|
build-support/ package: the danos build API (userBinary(), defaultImports(), targets)
|
||||||
|
library/kernel/ package "kernel": modules abi, ipc, service, memory, process, logging, time, ... (depends on protocol)
|
||||||
|
library/device/ package "device": modules driver, pci, usb-abi, model, ... (depends on kernel, protocol, csv)
|
||||||
|
library/protocol/ package "protocol": the wire protocols
|
||||||
|
library/client/ package "client" (depends on kernel, protocol)
|
||||||
|
library/csv/ package "csv"
|
||||||
|
library/xkeyboard-config/ package "xkeyboard-config"
|
||||||
|
system/services/<name>/ one package per binary: ~15-line build.zig + zon
|
||||||
|
system/drivers/<name>/ one package per binary
|
||||||
|
build.zig (root) orchestrator: dependency() per binary, image assembly, QEMU, test steps
|
||||||
|
```
|
||||||
|
|
||||||
|
The three shared contracts: `boot-handoff` stays a root module (only the
|
||||||
|
loader↔kernel pair speaks it); `abi` is exported by the kernel package from
|
||||||
|
`../../system/abi.zig` (the source stays with the kernel; userspace's one view
|
||||||
|
of it lives in the package, so every consumer names the same module instance);
|
||||||
|
`device-abi` is exported by device. Reaching outside the package root means the
|
||||||
|
kernel package is valid only as an in-repo path dependency — it could never be
|
||||||
|
fetched by hash — which is fine: path dependencies are the only way any of
|
||||||
|
these packages is consumed.
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
- **Imports are exact and per binary.** A binary's build.zig names precisely
|
||||||
|
the modules its source `@import`s — the moral equivalent of a C file's
|
||||||
|
include list — and its zon names only the domains those modules come from
|
||||||
|
(plus `build-support` and `kernel`, which is implicit in every binary: the
|
||||||
|
root shim and user link script live there). Nothing is pre-wired: an
|
||||||
|
undeclared `@import` is a compile error, and build-support resolves each
|
||||||
|
name by searching the packages the zon declares — the domains' own
|
||||||
|
addModule exports are the single statement of who owns what, with no name
|
||||||
|
table anywhere to drift. Availability
|
||||||
|
never meant bloat — Zig only compiles what a program actually imports — but
|
||||||
|
exactness makes the declared interface honest and machine-checked.
|
||||||
|
- **Modules export source, not artifacts** — each consumer compiles libraries
|
||||||
|
with its own flags, so per-binary optimization choices keep working; Zig's
|
||||||
|
cache deduplicates.
|
||||||
|
- **Zon paths are relative and that is accepted.** Binaries sit exactly three
|
||||||
|
levels deep, so the `../../../` prefix is a constant idiom; a library-domain
|
||||||
|
move is a rare, already-breaking event fixed by one sed across manifests, and
|
||||||
|
a stale path fails loudly before anything compiles.
|
||||||
|
- **Cross-cutting build changes live in `build-support` only** — that is the
|
||||||
|
contract that keeps per-binary build files declarative.
|
||||||
|
|
||||||
|
## What this buys
|
||||||
|
|
||||||
|
1. Library interfaces become machine-checked: a consumer can only import what
|
||||||
|
it declared — per binary, down to the single module — and each domain's zon
|
||||||
|
declares what it needs (claim-before-touch, applied to source). A keyboard
|
||||||
|
driver carries `xkeyboard-config` in its manifest; nothing else does.
|
||||||
|
2. Each library domain gets a standalone `zig build test` — runtime-library
|
||||||
|
stability testing in isolation.
|
||||||
|
3. Adding a binary = adding a directory (source + two small files), not editing
|
||||||
|
three places in a 1,250-line file.
|
||||||
|
4. `lazyDependency` lets an image target build only what it ships: the /test
|
||||||
|
fixtures resolve only under -Dtest-case, and only the -Ddiscovery-selected
|
||||||
|
discovery package ever loads.
|
||||||
|
|
||||||
|
## Phases
|
||||||
|
|
||||||
|
Each phase ends green: `zig build test` passes (88/88 QEMU) and the boot
|
||||||
|
image's file list is unchanged. Byte-identical binaries are expected but not
|
||||||
|
required (module reorganization can perturb symbol order); file list is the
|
||||||
|
hard gate.
|
||||||
|
|
||||||
|
**Phase 0 — `build-support`.** Extract `addUserBinary`/`addThreadedUserBinary`,
|
||||||
|
the freestanding target setup, and the default-import wiring into the
|
||||||
|
`build-support` package. Root build consumes it; nothing else moves. This is
|
||||||
|
the cross-cutting-change home, so it lands first.
|
||||||
|
|
||||||
|
**Phase 1 — library domains become packages.** In dependency order: `protocol`
|
||||||
|
and `csv` (the roots) → `kernel` (depends on protocol: file-system speaks
|
||||||
|
vfs-protocol) → `device`, `client`; `xkeyboard-config` stands alone. Each gets
|
||||||
|
build.zig + zon + a standalone test step (client's is empty until its modules
|
||||||
|
grow host tests — kept for uniformity, since the root aggregate depends on
|
||||||
|
every domain's test step). The root build swaps its `createModule` calls for
|
||||||
|
`b.dependency("<domain>").module("<name>")`. **No binary moves in this phase**
|
||||||
|
— the root build is the pilot consumer, which proves the packages without
|
||||||
|
touching 30 binaries.
|
||||||
|
|
||||||
|
**Phase 2 — binaries become packages, in waves.** The template was shaken out
|
||||||
|
by the pci-bus pilot (see Status). Wave A: services (done). Wave B: the
|
||||||
|
remaining drivers (done). Wave C: test fixtures (done). Root build shrank to
|
||||||
|
orchestration per wave. init's `-Dserial` heartbeat flag rides a dependency
|
||||||
|
option; a directory with several binaries (ps2-bus, usb-hid) is one package
|
||||||
|
exporting several artifacts.
|
||||||
|
|
||||||
|
**Phase 3 — root cleanup (done).** What remained of the root build split into
|
||||||
|
`build/images.zig` (the FHS install tree, boot manifest + capsule, FAT32
|
||||||
|
images, release ISO, check steps) and `build/qemu.zig` (the run steps + OVMF
|
||||||
|
probing), imported by a short root `build.zig`.
|
||||||
|
|
||||||
|
**Afterwards** (outside this plan): the intel-uhd-graphics-750 driver is
|
||||||
|
(re)created as a greenfield package. The new-driver checklist's build step
|
||||||
|
(docs/device-driver-development/new-driver-checklist.md, step 2) is already
|
||||||
|
rewritten against the package template.
|
||||||
|
|
||||||
|
## Execution notes (the finished shape)
|
||||||
|
|
||||||
|
- The shared recipe lives in `build-support/build.zig`: `userBinary` (what
|
||||||
|
every binary package calls; each named import resolves by searching the
|
||||||
|
packages the binary's zon declares) and `programModule` (for per-binary
|
||||||
|
addOptions modules). The `start` root shim and `user.ld` are named through the kernel
|
||||||
|
package (Dependency.path).
|
||||||
|
- Adding a binary = adding a directory with source + a ~15-line build.zig +
|
||||||
|
zon (copy any existing binary package, e.g.
|
||||||
|
`system/drivers/pci-bus/build.zig`) listing exactly the modules the source
|
||||||
|
imports and the domains they come from, then one dependency + one bundled
|
||||||
|
entry in the root build.zig and one zon line.
|
||||||
|
- The boot-tree array in the root (search `"etc/init.csv"` or
|
||||||
|
`.getEmittedBin()`) is the image file list — the authoritative comparison
|
||||||
|
target for any future build change.
|
||||||
|
- Package unit tests live in each package's own `test` step; the root
|
||||||
|
aggregate depends on every test-bearing package's step, so `zig build test`
|
||||||
|
at the root still runs everything.
|
||||||
|
|
||||||
|
Verification per phase:
|
||||||
|
|
||||||
|
- Unit tests: `zig build test`.
|
||||||
|
- QEMU integration suite: `python3 test/qemu_test.py` (docs/testing.md; the
|
||||||
|
full suite, all cases must pass).
|
||||||
|
- Image file list: the boot-tree array is the source of truth — snapshot it
|
||||||
|
(paths only) before phase 0 and diff after each phase; `zig build
|
||||||
|
check-fat-image` must also stay green.
|
||||||
|
|
||||||
|
Context a fresh session should read first: this doc, docs/testing.md,
|
||||||
|
docs/coding-standards.md (kebab-case names, no abbreviations), and the
|
||||||
|
`userBinary`/`userBinaryFromImports` bodies in build-support/build.zig. Commit
|
||||||
|
style: no Co-Authored-By trailers.
|
||||||
|
|
||||||
|
## Risks / notes
|
||||||
|
|
||||||
|
- Zig version churn: the package API (`b.dependency`, zon schema) has moved
|
||||||
|
between releases; the work pins against the repo's current Zig and any
|
||||||
|
upgrade lands separately, never mid-phase.
|
||||||
|
- The QEMU size-check tests hardcode source paths (e.g. virtio-gpu protocol
|
||||||
|
struct sizes) — they moved into their binaries' packages with their waves,
|
||||||
|
discharging the carry-along obligation.
|
||||||
|
- Doc updates ride each phase: docs/README.md (repo layout + source map),
|
||||||
|
docs/device-driver-development/new-driver-checklist.md (step 2) and
|
||||||
|
devices-csv.md ("Adding a driver"), and the docs that cite the build recipe
|
||||||
|
(driver-model.md, threading.md, system-requirements.md) reference build
|
||||||
|
shapes that keep changing.
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
# The C library compatibility layer
|
||||||
|
|
||||||
|
A design note and milestone plan for **libdanos-c** — the mini C library that lets
|
||||||
|
`zig cc` cross-compile C programs for danos. It is milestone **P0** of
|
||||||
|
[python-on-danos-milestones.md](python-on-danos-milestones.md), expanded here the
|
||||||
|
way [character-devices-and-tty.md](character-devices-and-tty.md) expands P1.
|
||||||
|
CPython is the driving consumer, but the layer is general: any portable C program
|
||||||
|
within its surface should build.
|
||||||
|
|
||||||
|
## What it is — and the three things it is not
|
||||||
|
|
||||||
|
The deliverable is a **sysroot**: a set of C headers plus a static `libdanos-c.a`,
|
||||||
|
handed to `zig cc -target x86_64-freestanding-none` via `-isystem` and linked into
|
||||||
|
every C binary. Three explicit non-goals keep it small:
|
||||||
|
|
||||||
|
- **Not a musl port.** Whole-musl assumes Linux syscall semantics at its bottom
|
||||||
|
(the door the Zig roadmap deferred, twice now). We *lift* musl's pure-computation
|
||||||
|
source files and *write* a danos-native bottom — see the layer split below.
|
||||||
|
- **Not full POSIX — *yet*.** Stage 1's surface is "what CPython's minimal
|
||||||
|
configuration and ordinary portable C need" — roughly 100–150 functions — and
|
||||||
|
at that stage absence is a *feature*: configure scripts probe and adapt, and a
|
||||||
|
linker error is honest. But the end state is a **full C compatibility layer**
|
||||||
|
(see "The road to full coverage" below); the absence table is a schedule of
|
||||||
|
arrivals, not a wall.
|
||||||
|
- **Not a second runtime.** The library is a thin C-ABI re-spelling of the same
|
||||||
|
danos-native surface `runtime` already provides. It contains no policy of its
|
||||||
|
own; when the Zig track's `runtime.os` seam is authored, the libc bottom
|
||||||
|
re-targets it near-mechanically — the fourth appearance of the roadmap's "same
|
||||||
|
surface" symmetry.
|
||||||
|
|
||||||
|
One scoping rule sits above all three — the **size doctrine**: this layer serves
|
||||||
|
**applications only**. The kernel and the system services never link libdanos-c;
|
||||||
|
they stay danos-native Zig over `runtime`, small and static, because leanness is
|
||||||
|
an operating-system property. Applications have their own budget and may be as
|
||||||
|
big as they need to be. The libc is how big software *lands on* danos, never how
|
||||||
|
danos itself is built.
|
||||||
|
|
||||||
|
## The layer split: lift the mathematics, write the plumbing
|
||||||
|
|
||||||
|
The realization that makes 100–150 functions tractable: a libc is two very
|
||||||
|
different kinds of code, and the hard kind is portable.
|
||||||
|
|
||||||
|
| Layer | Contents | Source |
|
||||||
|
|-------|----------|--------|
|
||||||
|
| **Pure computation** | `string.h`/`memcpy` family, all of libm, `strtod`/`dtoa`, `strtol`, `qsort`, `ctype` tables, `gmtime` calendar math, the `printf`/`scanf` engines, `setjmp` (a dozen instructions of x86-64 asm) | **Lift from musl**, vendored under `library/c/third-party/musl/` (MIT; files compile standalone) |
|
||||||
|
| **OS plumbing** | fds (`open`/`read`/`write`/`close`/`lseek`/`stat`/`getcwd`/`chdir`/`isatty`), `mmap`/`munmap`, clocks, `exit`, `getenv`, `getentropy` | **Write in Zig**, exporting C ABI over the `runtime` syscall + VFS client surface |
|
||||||
|
| **The middle** | `malloc` over danos `mmap` (simple free-list; CPython's arenas sit above), `FILE*` buffering, `errno` | **Write in Zig** (small, danos-shaped) |
|
||||||
|
| **Entry** | `crt0`: the existing danos entry shim ([sysv.md](os-development/sysv.md)) bridged to C `main(argc, argv, envp)`, `environ` initialised, `exit` flushing stdio | **Write** |
|
||||||
|
|
||||||
|
Two liftings deserve their own line because getting them wrong is silent
|
||||||
|
corruption rather than a linker error:
|
||||||
|
|
||||||
|
- **`strtod`/float formatting.** Python's float `repr` guarantees shortest
|
||||||
|
round-trip; that property lives entirely in these routines. musl's are correct;
|
||||||
|
an improvised one would be subtly wrong for years. Lift, never write.
|
||||||
|
- **The stdio engines.** musl's `vfprintf`/`vfscanf` are self-contained around
|
||||||
|
its `FILE` abstraction (function-pointer read/write slots), so the whole
|
||||||
|
formatted-I/O engine lifts too — we implement only the fd-backed slots
|
||||||
|
(`__stdio_write`-shaped) and the buffering glue.
|
||||||
|
|
||||||
|
## Header policy
|
||||||
|
|
||||||
|
Hand-write the headers as danos's own minimal set rather than importing musl's
|
||||||
|
(musl's are entangled with Linux ABI details), borrowing declarations freely.
|
||||||
|
Freestanding compiler headers (`stdint.h`, `stddef.h`, `stdarg.h`, `stdbool.h`,
|
||||||
|
`float.h`, `limits.h`) come from clang via `zig cc` — do not duplicate them.
|
||||||
|
`errno.h` values are the danos errno enum re-spelled with POSIX names; there is no
|
||||||
|
Linux numbering to be compatible with, so the enum is the truth.
|
||||||
|
|
||||||
|
Deliberate absences, and their planned arrivals — this table is the
|
||||||
|
compatibility matrix, and "the road to full coverage" below is the schedule
|
||||||
|
that empties it:
|
||||||
|
|
||||||
|
| Absent | Arrives with |
|
||||||
|
|--------|--------------|
|
||||||
|
| `pthread.h` | the post-P5 pthread subset over `thread_spawn`/futex — but see the risk below |
|
||||||
|
| real `signal.h` (beyond no-op `signal()`/`raise` stubs) | M17 signals-over-IPC in the libc |
|
||||||
|
| `dlfcn.h` | [dynamic-libraries.md](dynamic-libraries.md) D1 |
|
||||||
|
| `fork`/`exec*`/`wait*` | P5 exposes danos spawn as `posix_spawn`; `fork` itself never (see below) |
|
||||||
|
| `socket.h` | a future networking track |
|
||||||
|
| locale beyond `"C"` | stage 3 evaluation (CPython is UTF-8-mode happy without it) |
|
||||||
|
| pipes (`pipe()`) | P5 process-control cluster |
|
||||||
|
|
||||||
|
## The road to full coverage
|
||||||
|
|
||||||
|
The layer grows in three stages; only stage 1 is a current milestone (P0), but
|
||||||
|
the stages exist so stage-1 decisions never have to be unmade:
|
||||||
|
|
||||||
|
- **Stage 1 — CPython-minimal** (P0, the slicing below): ~100–150 functions,
|
||||||
|
static-only, absences honest.
|
||||||
|
- **Stage 2 — the danos-complete layer**: the full hosted C11 standard library,
|
||||||
|
plus every POSIX facility danos semantics support, landing as its enabling
|
||||||
|
milestone lands — pipes and `posix_spawn` at P5, real signals at M17, the
|
||||||
|
pthread subset after P5, `dlfcn.h` at
|
||||||
|
[dynamic-libraries](dynamic-libraries.md) D1, sockets with networking. Stage 2
|
||||||
|
is not one milestone but the standing rule that **every system capability
|
||||||
|
gets its C spelling when it ships**, so the matrix above drains as the OS
|
||||||
|
grows.
|
||||||
|
- **Stage 3 — ecosystem grade**: the point where "portable C program" generally
|
||||||
|
means "builds on danos" (autotools-style probing included). Reaching it is
|
||||||
|
mostly stage 2 compounding, plus the long tail (locale, wide-char,
|
||||||
|
`fnmatch`/`glob`/`regex` — the last three lift from musl like the rest). At
|
||||||
|
this stage, re-evaluate hand-grown-vs-musl-port once with real data; the
|
||||||
|
standing recommendation remains danos-native — musl's bottom assumes Linux
|
||||||
|
syscall semantics, and by stage 3 the danos bottom exists and is tested —
|
||||||
|
with musl continuing as the quarry for computation code.
|
||||||
|
|
||||||
|
Two boundaries are permanent and worth stating at every stage: **`fork` never
|
||||||
|
comes** — danos is a spawn-shaped OS, and `fork`'s address-space-duplication
|
||||||
|
semantics are hostile to everything from capabilities to threads; software that
|
||||||
|
hard-requires `fork` (not `posix_spawn`) stays off the platform. And the
|
||||||
|
**public ABI stays the vDSO + IPC protocols** — a full libc is a compatibility
|
||||||
|
*layer*, not a second stable system ABI.
|
||||||
|
|
||||||
|
## Milestone slicing
|
||||||
|
|
||||||
|
1. **sysroot-skeleton** — layout under `library/c/` (a build package:
|
||||||
|
`include/`, Zig sources, vendored musl subtree); `crt0`; string/mem +
|
||||||
|
`ctype` lifted; a `build.zig` step making C binaries first-class targets.
|
||||||
|
*Test:* a C program using only computation links and runs in QEMU
|
||||||
|
(`c-hello` printing via a raw `write` extern to `debug_write`).
|
||||||
|
2. **fd-plumbing** — `errno`; open/read/write/close/lseek/stat/unlink/mkdir/
|
||||||
|
rename over the `runtime` VFS client; `getcwd`/`chdir`/`getenv`/
|
||||||
|
`getentropy` arriving as P1 lands them (stubbed truthfully until then:
|
||||||
|
`getenv` empty, `getentropy` `ENOSYS`). *Test:* QEMU `c-file-io` — create,
|
||||||
|
write, reopen, read back, stat size + mtime through FAT.
|
||||||
|
3. **malloc** — free-list allocator over danos `mmap`; `calloc`/`realloc`/
|
||||||
|
`free`; alignment guarantees documented. *Test:* host + QEMU allocator
|
||||||
|
torture (interleaved sizes, realloc growth, alignment asserts).
|
||||||
|
4. **stdio** — `FILE*`, buffering modes, the lifted printf/scanf engines wired
|
||||||
|
to the fd slots; `snprintf` family; stdin/stdout/stderr over fd 0/1/2.
|
||||||
|
*Test:* host round-trip suite for format engines (especially `%.17g`
|
||||||
|
float round-trip); QEMU `c-stdio` cooked-line echo once P1's console exists.
|
||||||
|
5. **mathematics-and-time** — libm lifted wholesale; `strtod`/`strtol`;
|
||||||
|
`clock_gettime` (monotonic + realtime over `clock`/`wall_clock`);
|
||||||
|
`gmtime`/`mktime`/`strftime` (UTC only — no timezone database);
|
||||||
|
`setjmp`/`longjmp`; `qsort`/`bsearch`; `abort`/`assert`. *Test:* host
|
||||||
|
`strtod`/`dtoa` vectors against known-hard cases; QEMU `c-time` sanity
|
||||||
|
against the wall clock.
|
||||||
|
|
||||||
|
Slices 1, 3, 4-host, and 5-host have **no dependency on P1** and can start
|
||||||
|
immediately; slice 2 and the QEMU halves interleave with P1 as it lands.
|
||||||
|
|
||||||
|
**Exit for the layer as a whole** (= P0's exit): `c-hello` and `c-file-io` green
|
||||||
|
in the QEMU suite, and the host-side computation tests green — at which point P2
|
||||||
|
(CPython configure) becomes the layer's real integration test.
|
||||||
|
|
||||||
|
## Testing strategy: two targets, on purpose
|
||||||
|
|
||||||
|
The computation layer is target-independent, so it is unit-tested **on the host**
|
||||||
|
(built for the host triple, compared against the host libc's answers —
|
||||||
|
thousands of cheap oracle checks for `strtod`, `printf`, libm edge cases). The
|
||||||
|
plumbing layer only means anything **on danos**, so it is tested in the QEMU
|
||||||
|
suite like every other subsystem. Keeping the split explicit stops the slow-QEMU
|
||||||
|
suite from absorbing tests that a host `zig test` runs in milliseconds.
|
||||||
|
|
||||||
|
## Risks and gotchas
|
||||||
|
|
||||||
|
- **CPython's configure may insist on pthreads.** WASI-class targets build
|
||||||
|
threadless, but verify this *first* in P2 bring-up; the fallback is a
|
||||||
|
truthfully-single-threaded `pthread.h` stub set (create returns `EAGAIN`,
|
||||||
|
mutexes are no-ops — valid when only one thread can exist). Decide from
|
||||||
|
evidence, not assumption.
|
||||||
|
- **`long double` is x87 80-bit on x86-64.** musl's libm handles it, but keep
|
||||||
|
CPython away from it (`configure` uses `double` throughout by default);
|
||||||
|
don't hand-write anything touching x87.
|
||||||
|
- **errno is a contract, not a convention.** The Zig plumbing must map every
|
||||||
|
`runtime` error to a POSIX name consistently — CPython turns errno into
|
||||||
|
exception types (`FileNotFoundError` is `ENOENT`). One table, tested.
|
||||||
|
- **`malloc` alignment**: 16-byte minimum on x86-64 (SSE spills in
|
||||||
|
compiled C). The free-list must guarantee it from day one; retrofitting
|
||||||
|
alignment bugs out of an allocator is misery.
|
||||||
|
- **Vendoring discipline.** The musl subtree is lift-only — never edited in
|
||||||
|
place (patches live beside it if ever needed), pinned to one musl release,
|
||||||
|
with the file list documented so a version bump is a re-copy, not an
|
||||||
|
archaeology dig.
|
||||||
|
- **stdio buffering vs. crashes.** Buffered stdout + a crashing program eats
|
||||||
|
output — the classic debugging trap. `stderr` stays unbuffered (per C
|
||||||
|
standard) and `exit`/`abort` flush; document that `_exit` does not.
|
||||||
|
|
||||||
|
## Decisions needing sign-off
|
||||||
|
|
||||||
|
- **Lift-from-musl for all pure computation** (vendored, pinned, unedited) rather
|
||||||
|
than writing or porting whole-musl.
|
||||||
|
- **Hand-written danos-native headers**; danos errno values are the numbering.
|
||||||
|
- **`library/c/` as a build package** producing both the sysroot and the
|
||||||
|
first-class C-binary build step.
|
||||||
|
- The **deliberate-absence table** as the living compatibility matrix, drained
|
||||||
|
by the three-stage road above — with exactly one permanent "never": `fork`.
|
||||||
|
- **Full coverage as the end state** (stage 3), reached by the standing rule
|
||||||
|
that every system capability ships with its C spelling — not by a musl port.
|
||||||
|
|
||||||
|
## Related
|
||||||
|
|
||||||
|
- [python-on-danos-milestones.md](python-on-danos-milestones.md) — this is P0.
|
||||||
|
- [dynamic-libraries.md](dynamic-libraries.md) — ships in this sysroot
|
||||||
|
(`dlfcn.h` + the loader) once its D1 lands.
|
||||||
|
- [python-on-danos.md](python-on-danos.md) — the design note that scoped the
|
||||||
|
layer.
|
||||||
|
- [character-devices-and-tty.md](character-devices-and-tty.md) — P1; supplies
|
||||||
|
the console that makes stdio interactive.
|
||||||
|
- [zig-self-hosting.md](zig-self-hosting.md) — the `runtime.os` seam the
|
||||||
|
plumbing layer will re-target when it exists.
|
||||||
|
- [os-development/sysv.md](os-development/sysv.md) — the entry stack `crt0`
|
||||||
|
bridges.
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
# Character devices, the console, and the tty question
|
||||||
|
|
||||||
|
A design note for the **stream** half of the device world. danos has block devices
|
||||||
|
(the USB storage service behind the FAT mount) but no character devices — and three
|
||||||
|
tracks now need them at once: the terminal application, Zig self-hosting Phase 1
|
||||||
|
("wire fd 0/1/2 to a console byte stream"), and [Python on danos](python-on-danos.md)
|
||||||
|
Phase 1. This note settles what a character device *is* on danos before any of those
|
||||||
|
tracks build one.
|
||||||
|
|
||||||
|
## The Unix picture, briefly
|
||||||
|
|
||||||
|
Unix splits devices in two: **block devices** are seekable arrays of fixed-size
|
||||||
|
sectors (disks); **character devices** are unseekable byte streams (keyboards,
|
||||||
|
serial ports, terminals, `/dev/null`, entropy). A **tty** is the canonical
|
||||||
|
character device — a byte stream plus a *line discipline* (echo, line buffering,
|
||||||
|
erase handling, Ctrl-C-to-signal) that lives in the kernel. A **pty** is a pair of
|
||||||
|
character devices (master/slave) that exists so a *userspace* program — a terminal
|
||||||
|
emulator — can impersonate terminal hardware to the kernel's in-kernel line
|
||||||
|
discipline.
|
||||||
|
|
||||||
|
The identification asked for and confirmed: yes, tty and pty are character
|
||||||
|
devices in this taxonomy.
|
||||||
|
|
||||||
|
## The realization that shapes everything: danos already has the mechanism
|
||||||
|
|
||||||
|
A Unix character device is an in-kernel dispatch table: major/minor numbers route
|
||||||
|
`read()`/`write()` to a driver. danos already has exactly that dispatch — the VFS:
|
||||||
|
`fs_resolve` routes a path to a mounted backend service, and `Operation.mount`
|
||||||
|
attaches a backend *endpoint* at a prefix. What is missing is not a device model;
|
||||||
|
it is **one node kind with stream semantics**. And the protocol already reserved
|
||||||
|
it: `NodeKind.character_device = 2` sits unimplemented in
|
||||||
|
[vfs-protocol.zig](../library/protocol/vfs/vfs-protocol.zig), exactly like
|
||||||
|
`symbolic_link`.
|
||||||
|
|
||||||
|
So the design is small:
|
||||||
|
|
||||||
|
**A character device on danos is a VFS node, served by an ordinary service over
|
||||||
|
the existing VFS wire protocol, whose read/write have stream semantics.**
|
||||||
|
|
||||||
|
No device numbers, no `/dev` special casing, no new syscalls, no new protocol —
|
||||||
|
a service is reachable at a path, clients open it with `runtime.fs` like any
|
||||||
|
file, and the node kind says what it is. (Since the protocol namespace landed
|
||||||
|
in design, that path is `/protocol/console` — a protocol node, see
|
||||||
|
[os-development/protocol-namespace.md](os-development/protocol-namespace.md) —
|
||||||
|
rather than a mounted device file; the stream semantics below are unchanged.)
|
||||||
|
|
||||||
|
### Stream semantics (the actual contract change)
|
||||||
|
|
||||||
|
For a node whose kind is `character_device`:
|
||||||
|
|
||||||
|
- **`offset` is ignored** on read and write; there is no seek position. (`lseek`,
|
||||||
|
when the C layer exists, returns `ESPIPE`.)
|
||||||
|
- **Reads block** until at least one byte is available, then return what is there —
|
||||||
|
**short reads are normal**, not EOF. A zero-length read reply means the stream
|
||||||
|
is closed (hangup), not end-of-file-at-size.
|
||||||
|
- **`FileStatus.size` is 0** and means nothing; `mtime` may be 0.
|
||||||
|
- Writes may be short if the service's buffer is full; the client loops as it
|
||||||
|
already must for the 256-byte message cap.
|
||||||
|
|
||||||
|
This is a semantics note on existing operations, not a wire change — the `Request`
|
||||||
|
and `Reply` structs are untouched. The one true protocol addition is a **`control`
|
||||||
|
operation** (appended to `Operation`, values stable): a typed request the stream's
|
||||||
|
service interprets. Deliberately *not* an `ioctl` grab-bag — the control payloads
|
||||||
|
are enumerated per protocol, starting with the terminal set below.
|
||||||
|
|
||||||
|
## The first character device is a pseudo-device
|
||||||
|
|
||||||
|
The first device is deliberately **not hardware**: an in-memory **loopback** — a
|
||||||
|
byte queue served over the stream contract, where bytes written to one end are
|
||||||
|
read from the other. It is the reference implementation of the semantics above
|
||||||
|
(blocking reads, short reads, hangup on close, the `control` round-trip), it
|
||||||
|
tests deterministically with no QEMU serial scripting, and it keeps hardware off
|
||||||
|
the critical path entirely. `null` and `zero` come along nearly for free as
|
||||||
|
degenerate cases. This is a decision, not a convenience: the dead-COM1 boot bug
|
||||||
|
on real hardware already proved serial cannot be assumed present or alive, so
|
||||||
|
**nothing in this milestone writes to COM1**. (A serial-backed stream node can
|
||||||
|
exist *later* as one more optional backend for headless debugging; it is on
|
||||||
|
nobody's critical path.)
|
||||||
|
|
||||||
|
The loopback is also not throwaway — it is the seed of P5's `pipe()`, which is
|
||||||
|
the same object with two fds.
|
||||||
|
|
||||||
|
## The console service
|
||||||
|
|
||||||
|
A `console` service owns the line discipline — **in userspace**, where a
|
||||||
|
microkernel wants it, not in the kernel as Unix has it:
|
||||||
|
|
||||||
|
- **The discipline is a pure library first**: bytes and key events in, bytes
|
||||||
|
out, no I/O of its own — developed and host-tested against in-memory buffers,
|
||||||
|
then shared verbatim between the console and the future terminal application.
|
||||||
|
- **Input**: subscribes to keyboard `InputEvent` IPC (the structured events that
|
||||||
|
exist today) and cooks them into bytes. Cooked mode is the default: echo, line
|
||||||
|
buffering, backspace/erase, so a line is delivered on Enter. Raw mode delivers
|
||||||
|
bytes as they come (the REPL's line editor and any full-screen program need it).
|
||||||
|
- **Output is a pluggable sink**, and the stream contract is independent of it:
|
||||||
|
the bring-up sink is in-memory (readable back by tests, mirrored to the boot
|
||||||
|
log), and the real one is the framebuffer text renderer when the display
|
||||||
|
track's font work lands.
|
||||||
|
- **Control set** (the `control` payloads): mode raw/cooked, echo on/off, and
|
||||||
|
window-size query — the minimal termios. Ctrl-C-to-signal joins when M17
|
||||||
|
signals-over-IPC lands; until then Ctrl-C is just a byte.
|
||||||
|
- Mounts itself at `/device/console` as a `character_device` node.
|
||||||
|
|
||||||
|
**fd 0/1/2** then stop being special: spawn hands the child three open handles
|
||||||
|
(console by default; anything else if the parent chooses), and `runtime`'s fd
|
||||||
|
table maps 0/1/2 to them. `isatty` is simply "does `status` say
|
||||||
|
`character_device`" — no side channel needed.
|
||||||
|
|
||||||
|
## The pty answer: there is no pty
|
||||||
|
|
||||||
|
The pty exists in Unix *because the line discipline is in the kernel* — userspace
|
||||||
|
terminal emulators need a kernel gadget to impersonate hardware. On danos the
|
||||||
|
terminal emulator is already a userspace server, so the pair collapses:
|
||||||
|
|
||||||
|
**The graphical terminal application serves the VFS stream protocol itself and
|
||||||
|
hands its own endpoints to the children it spawns as their fd 0/1/2.**
|
||||||
|
|
||||||
|
The terminal *is* the console service for its children — same protocol, same
|
||||||
|
control set, same line discipline code (shared as a library with the boot
|
||||||
|
console). No master/slave device pair, no `/dev/pts`, no new kernel object. When
|
||||||
|
CPython arrives, the libc's `isatty`/read/write see a character device and are
|
||||||
|
none the wiser; when xonsh eventually wants job control, that lands as control
|
||||||
|
messages + M17 signals, still with no pty object.
|
||||||
|
|
||||||
|
What this costs: programs that *specifically* manipulate Unix ptys
|
||||||
|
(`os.openpty()`, `pexpect`-style tools) have no direct equivalent — the danos
|
||||||
|
answer is "spawn the child yourself with your own stream endpoints," which is the
|
||||||
|
same capability with less machinery. Accepted.
|
||||||
|
|
||||||
|
## Milestone slicing
|
||||||
|
|
||||||
|
1. **pseudo-devices** — VFS honors `character_device` semantics end to end;
|
||||||
|
`Operation.control` added; the in-memory **loopback** (plus `null`/`zero`)
|
||||||
|
as the first device. QEMU test: one client writes, another reads — open,
|
||||||
|
offsetless read/write, blocking read, short read, hangup on close, control
|
||||||
|
round-trip. No hardware anywhere.
|
||||||
|
2. **console-service** — the line-discipline library (host-tested, pure) plus
|
||||||
|
the console composing keyboard `InputEvent`s with an in-memory output sink;
|
||||||
|
mounted at `/device/console`. QEMU test injects key events and reads cooked
|
||||||
|
lines and raw bytes back through the sink.
|
||||||
|
3. **fd-inheritance** — spawn passes 0/1/2 handles; `runtime` fd table; `isatty`
|
||||||
|
via `status`; existing binaries' stdout migrates from `debug_write` to fd 1
|
||||||
|
(the logger keeps its own path).
|
||||||
|
4. **terminal-as-server** — deferred to the terminal application milestone
|
||||||
|
(Python track P3): the terminal reuses the discipline library and serves its
|
||||||
|
children directly.
|
||||||
|
|
||||||
|
Steps 1–3 are exactly the shared seam that Zig self-hosting Phase 1 and Python
|
||||||
|
Phase 1 both list; neither track repeats them.
|
||||||
|
|
||||||
|
## Decisions needing sign-off
|
||||||
|
|
||||||
|
- **No pty object; the terminal serves its children directly** (the section
|
||||||
|
above) — the load-bearing simplification.
|
||||||
|
- **`control` as an enumerated, typed operation** rather than an ioctl-style
|
||||||
|
opaque pass-through.
|
||||||
|
- **Line discipline in userspace services** (console + terminal, shared library),
|
||||||
|
never in the kernel.
|
||||||
|
|
||||||
|
## Related
|
||||||
|
|
||||||
|
- [python-on-danos.md](python-on-danos.md) — consumes this as its Phase 1.
|
||||||
|
- [zig-self-hosting.md](zig-self-hosting.md) — ditto ("stdio as fds").
|
||||||
|
- [file-system-development/vfs-protocol.md](file-system-development/vfs-protocol.md) —
|
||||||
|
the wire protocol this note extends.
|
||||||
|
- [file-system-development/file-system-hierarchy.md](file-system-development/file-system-hierarchy.md)
|
||||||
|
— the tree the console surfaces in.
|
||||||
|
- [os-development/protocol-namespace.md](os-development/protocol-namespace.md) —
|
||||||
|
supersedes this note's device-node naming: the console lands as a protocol
|
||||||
|
(`/protocol/console`, a protocol node), not a `/dev`-style device file. The
|
||||||
|
stream semantics designed here (line discipline, cooked/raw modes) carry over
|
||||||
|
unchanged.
|
||||||
|
- [device-driver-development/input.md](device-driver-development/input.md) — the
|
||||||
|
`InputEvent` stream the console cooks.
|
||||||
@@ -67,7 +67,7 @@ Three, and only three.
|
|||||||
|
|
||||||
**This exception is scoped to a file that *is* a foreign ABI, and nothing else.**
|
**This exception is scoped to a file that *is* a foreign ABI, and nothing else.**
|
||||||
danos has no such file today: the old `library/posix/` compatibility shim was retired
|
danos has no such file today: the old `library/posix/` compatibility shim was retired
|
||||||
once its callers moved to the danos-native `runtime.fs`, since a hand-rolled POSIX
|
once its callers moved to the danos-native `file_system`, since a hand-rolled POSIX
|
||||||
layer is premature until danos actually needs it (see
|
layer is premature until danos actually needs it (see
|
||||||
[zig-self-hosting.md](zig-self-hosting.md)). The exception will apply again to the
|
[zig-self-hosting.md](zig-self-hosting.md)). The exception will apply again to the
|
||||||
`std.os.danos` seam when danos becomes a real Zig target — that module *is* the C-ABI
|
`std.os.danos` seam when danos becomes a real Zig target — that module *is* the C-ABI
|
||||||
@@ -97,8 +97,9 @@ Three, and only three.
|
|||||||
|
|
||||||
That's all — no Unix-abbreviation exception. The source directories are full words
|
That's all — no Unix-abbreviation exception. The source directories are full words
|
||||||
(`system`, `library`, not `src`/`lib`), and there is no daemon `d` suffix: a driver
|
(`system`, `library`, not `src`/`lib`), and there is no daemon `d` suffix: a driver
|
||||||
lives in `system/drivers/` and a service in `system/services/`, so the *location*
|
lives in `system/drivers/`, a service in `system/services/`, and a test fixture in
|
||||||
already says what it is. Encoding the role in the name too (`busd`, `fatd`) is
|
`test/system/services/` (the repo path *is* its path on the boot volume), so the
|
||||||
|
*location* already says what it is. Encoding the role in the name too (`busd`, `fatd`) is
|
||||||
redundant — the program is just `ps2-bus`, `fat`. Don't put in a name what its directory
|
redundant — the program is just `ps2-bus`, `fat`. Don't put in a name what its directory
|
||||||
already tells you.
|
already tells you.
|
||||||
|
|
||||||
@@ -135,15 +136,16 @@ Within those spelling rules, follow Zig's own conventions:
|
|||||||
`notify_badge_bit`.
|
`notify_badge_bit`.
|
||||||
|
|
||||||
**File names are `kebab-case`.** A file named for a multi-word thing hyphenates it:
|
**File names are `kebab-case`.** A file named for a multi-word thing hyphenates it:
|
||||||
`device-tree.zig`, `ipc-synchronous.zig`, `vfs-protocol.zig`, `devices-broker.zig`. A
|
`device-model.zig`, `ipc-synchronous.zig`, `vfs-protocol.zig`, `devices-broker.zig`. A
|
||||||
single word or acronym needs no hyphen: `scheduler.zig`, `paging.zig`, `apic.zig`,
|
single word or acronym needs no hyphen: `scheduler.zig`, `paging.zig`, `apic.zig`,
|
||||||
`idt.zig`. (The module *alias* a file is imported under still follows the code
|
`idt.zig`. (The module *alias* a file is imported under still follows the code
|
||||||
conventions above — `snake_case` — because it's an identifier, not a filename.)
|
conventions above — `snake_case` — because it's an identifier, not a filename.)
|
||||||
|
|
||||||
**A sub-project's entry point repeats its directory's name** — `init/init.zig`,
|
**A sub-project's entry point repeats its directory's name** — `init/init.zig`,
|
||||||
`runtime/runtime.zig`, `ps2-bus/ps2-bus.zig` — and the sub-project is addressed by the
|
`pci/pci.zig`, `ps2-bus/ps2-bus.zig` — and the sub-project is addressed by the
|
||||||
*directory* (`system/services/init`, `library/runtime`), with the repeated leaf
|
*directory* (`system/services/init`, `library/device/pci`,
|
||||||
resolving away. See the repository-layout section of [README.md](README.md).
|
`test/system/services/vfs-test`), with the repeated leaf resolving away. See the
|
||||||
|
repository-layout section of [README.md](README.md).
|
||||||
|
|
||||||
## Named values, not magic numbers
|
## Named values, not magic numbers
|
||||||
|
|
||||||
@@ -180,6 +182,26 @@ test for "is this an abbreviation I must expand" is simply: *is there a longer w
|
|||||||
is a clipped form of?* If yes, write the word. If it's an initialism standing in for a
|
is a clipped form of?* If yes, write the word. If it's an initialism standing in for a
|
||||||
phrase, leave it.
|
phrase, leave it.
|
||||||
|
|
||||||
|
## Kernel code touches user memory only through `user-memory`
|
||||||
|
|
||||||
|
A syscall argument is an attacker-controlled integer. Kernel code never
|
||||||
|
dereferences one: every read of a process's memory goes through
|
||||||
|
`copyFromUser` and every write through `copyToUser`
|
||||||
|
(`system/kernel/user-memory.zig`), which walk that address space's page tables
|
||||||
|
and move the bytes through the physmap, with the permissions ring 3 itself
|
||||||
|
would face. A bad pointer then fails the call instead of faulting the kernel,
|
||||||
|
and a struct pulled in once cannot change underneath the checks that follow it.
|
||||||
|
|
||||||
|
This is not a review convention — CR4.SMAP enforces it in hardware
|
||||||
|
(`docs/os-development/smep-smap.md`), so a raw dereference of a user address is
|
||||||
|
a #PF with a kernel instruction pointer the first time the QEMU suite reaches
|
||||||
|
it. Which is also why **there is no `stac` in this tree, and never should be**:
|
||||||
|
`stac` suspends exactly that enforcement, the copy layer needs no such window
|
||||||
|
by construction, and a change that adds one has removed the guarantee rather
|
||||||
|
than worked around a limitation. The same goes for the boot-time `clac` patch
|
||||||
|
at the interrupt entry — it exists so that ring 3 cannot suspend SMAP either,
|
||||||
|
by taking an interrupt with `EFLAGS.AC` set.
|
||||||
|
|
||||||
## Zen of Zig
|
## Zen of Zig
|
||||||
|
|
||||||
* Communicate intent precisely.
|
* Communicate intent precisely.
|
||||||
|
|||||||
@@ -1,125 +0,0 @@
|
|||||||
# DanOS Filesystem Hierarchy Standard (DFHS)
|
|
||||||
|
|
||||||
Most modern Unix and Unix-like operating systems follow the FHS. DanOS has its own FHS structure which extends the unix FHS. Root path resolution is provided by the kernel-resident VFS root (`fs_resolve`, `system/kernel/vfs.zig`); mounted filesystem servers serve the subtrees they own.
|
|
||||||
|
|
||||||
## Directory structure
|
|
||||||
|
|
||||||
| Path | Description |
|
|
||||||
|------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
|
||||||
| / | Primary hierarchy root and root directory of the entire file system hierarchy. |
|
|
||||||
| /bin | Essential command binaries that need to be available in single-user mode, including to bring up the system or repair it, for all users (e.g., cat, ls, cp). |
|
|
||||||
| /boot | Boot loader files (e.g., EFI, initial-ramdisk.img ). |
|
|
||||||
| /dev | POSIX Device files (e.g., /dev/null, /dev/disk0, /dev/tty, /dev/random). |
|
|
||||||
| /etc | Host-specific system-wide configuration files. |
|
|
||||||
| /home | Users' home directories, containing saved files, personal settings, etc. |
|
|
||||||
| /lib | Libraries essential for the binaries in /bin and /sbin. eg realtime, system, ipc etc. |
|
|
||||||
| /sbin | Essential system binaries (e.g init) |
|
|
||||||
| /srv | Site-specific data served by this system, such as data and scripts for web servers, data offered by FTP servers, and repositories for version control systems |
|
|
||||||
| /system | DanOS operating system files (similar idea to C:\Windows). A true representation of danos — its layout mirrors the source tree, so `/system` is what danos *is*. |
|
|
||||||
| /system/devices | danos virtual device tree e.g. similar to /sys on linux but with danos device tree conventions (the structures in the devices module) |
|
|
||||||
| /system/drivers | driver binaries, one sub-project each (e.g. /system/drivers/pci-bus, /system/drivers/ps2-bus) |
|
|
||||||
| /system/services | system-service binaries — init, the FAT server, and other user-mode servers (e.g. /system/services/init, /system/services/fat) |
|
|
||||||
| /system/kernel | the kernel image |
|
|
||||||
| /tmp | Directory for temporary files (see also /var/tmp). Often not preserved between system reboots and may be severely size-restricted. |
|
|
||||||
| /usr | Secondary hierarchy for read-only user data; contains the majority of (multi-)user utilities and applications. Should be shareable and read-only. |
|
|
||||||
| /var | Variable files: files whose content is expected to continually change during normal operation of the system, such as logs, spool files, and temporary e-mail files. |
|
|
||||||
|
|
||||||
## File types
|
|
||||||
|
|
||||||
POSIX specifies the long format of the ls command to represent the Unix file type as the first letter for an entry.
|
|
||||||
|
|
||||||
| type | symbol | Description |
|
|
||||||
|-------------------|--------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
|
||||||
| regular | - | An ordinary file holding an uninterpreted byte stream. Reads and writes are positional, and the file grows on demand (e.g., a binary in /bin, a config file in /etc). |
|
|
||||||
| directory | d | A container mapping names to other files. It may only be modified through directory operations, never written to directly. |
|
|
||||||
| symbolic link | l | A file whose contents are a path that is resolved in its place. The target need not exist, and may cross mount points. |
|
|
||||||
| FIFO special | p | A named pipe: an in-order byte stream between processes, where writers block until a reader opens the other end. |
|
|
||||||
| block special | b | A device node addressed in fixed-size blocks with the kernel free to buffer and reorder access (e.g., /dev/disk0). |
|
|
||||||
| character special | c | A device node addressed as an unbuffered byte stream, delivered to the driver in order (e.g., /dev/tty, /dev/null). |
|
|
||||||
| socket | s | A named endpoint for bidirectional message-passing between processes, bound to a path rather than an address. |
|
|
||||||
|
|
||||||
## /dev
|
|
||||||
|
|
||||||
`/dev` holds the names through which processes reach devices. It is deliberately not
|
|
||||||
the device tree: the tree — every node discovered by ACPI or PCI enumeration, with its
|
|
||||||
resources and its parent — lives under [/system/devices](#directory-structure) and is
|
|
||||||
addressed by device id. `/dev` is the much smaller set of devices that have a driver
|
|
||||||
willing to serve them, addressed by name.
|
|
||||||
|
|
||||||
A device node is not a file the VFS can read. The bytes live in a driver process
|
|
||||||
([drivers.md](drivers.md)), so opening a `/dev` name has to resolve to that driver's
|
|
||||||
IPC endpoint, and subsequent reads and writes are calls against it. Resolve-to-endpoint
|
|
||||||
is exactly what the kernel's `fs_resolve` already does for any mounted backend, and
|
|
||||||
`FileStatus.kind` is the field that marks a device node; **what is not implemented today
|
|
||||||
is `/dev` itself** — no service mounts it. (The flat eight-node ramfs this section once
|
|
||||||
described is retired: the kernel-resident VFS root in `system/kernel/vfs.zig` serves the
|
|
||||||
read-only `/system` initrd mount with real directories and node kinds, and filesystem
|
|
||||||
backends such as the FAT server mount the rest.) The three sections below describe the
|
|
||||||
intended shape, and are honest about which parts the kernel can already support.
|
|
||||||
|
|
||||||
### Character devices
|
|
||||||
|
|
||||||
A character device is a byte stream with no addressable position: bytes are delivered
|
|
||||||
to the driver in the order written, and a read consumes what is there. Terminals,
|
|
||||||
serial lines, keyboards and mice are all of this shape. These are the natural first
|
|
||||||
device nodes in danos, because a character driver needs nothing the kernel doesn't
|
|
||||||
already provide — it claims its device, maps its registers with `mmio_map`, and blocks
|
|
||||||
on `replyWait` for either an interrupt or a client request. `system/drivers/ps2-bus/ps2-bus.zig`
|
|
||||||
is already that program, minus the file-node client half.
|
|
||||||
|
|
||||||
The obstacle was never the file type; it is which hardware a ring-3 driver can reach.
|
|
||||||
Direct `in`/`out` from user space is still a #GP (no TSS I/O bitmap, IOPL never raised),
|
|
||||||
but a driver no longer needs it: **`io_read`/`io_write`** grant port access the same way
|
|
||||||
`mmio_map` grants memory — gated by `device_claim` and the device's discovered `io_port`
|
|
||||||
resource. So the 16550 UART at `0x3F8` and the PS/2 controller at `0x60`/`0x64` (and thus
|
|
||||||
`/dev/ttyS0` and a keyboard node) are now writable as ordinary ring-3 drivers; the
|
|
||||||
low-rate legacy hardware that needs port I/O is fine with a syscall per access. A
|
|
||||||
memory-mapped device such as the framebuffer, needing no port I/O at all, remains the
|
|
||||||
easiest first entry.
|
|
||||||
|
|
||||||
### Block devices
|
|
||||||
|
|
||||||
A block device is addressed in fixed-size blocks and, unlike a character device, the
|
|
||||||
layer above is free to buffer, reorder, coalesce and retry requests against it. Disks
|
|
||||||
and other persistent storage are the whole population of this class.
|
|
||||||
|
|
||||||
A block driver is now **writable, but not yet memory-safe.** Every storage controller
|
|
||||||
worth naming is a bus master: it is programmed by handing it the physical address of a
|
|
||||||
descriptor ring and left to read and write memory on its own. That ring is exactly what
|
|
||||||
**`dma_alloc`** now provides — physically contiguous, pinned, uncacheable, with its
|
|
||||||
physical address disclosed — and **`/lib/mmio`**'s barriers order the descriptor writes
|
|
||||||
against the doorbell, and **`msi_bind`** delivers completions. So an AHCI or NVMe driver
|
|
||||||
can be written today (the M14/M15 work in [driver-model.md](driver-model.md); the earlier
|
|
||||||
"cannot host a block driver at all" is no longer true).
|
|
||||||
|
|
||||||
What is *not* yet true is that it is safe. A device programmed with an arbitrary physical
|
|
||||||
address writes to arbitrary physical memory, and page tables do not sit between a device
|
|
||||||
and RAM — an IOMMU does. The IOMMU is now *detected* (M16), but no translation domains
|
|
||||||
are programmed, so granting a DMA-capable device to a driver process is still equivalent
|
|
||||||
to granting ring 0. Until per-device domains confine a driver's DMA to the buffers it
|
|
||||||
`dma_alloc`'d, a block driver works but forfeits the isolation that motivates user-space
|
|
||||||
drivers — enforcement is the next step, and lands with that first driver. A ramdisk over
|
|
||||||
the initial ramdisk remains the one block-shaped thing that needs no driver process at all.
|
|
||||||
|
|
||||||
### Pseudo-devices
|
|
||||||
|
|
||||||
A pseudo-device has the interface of a device and no hardware behind it: `/dev/null`
|
|
||||||
discarding writes and reading as end-of-file, `/dev/zero` reading as an endless run of
|
|
||||||
zero bytes, `/dev/full` failing writes with `ENOSPC`, `/dev/random` and `/dev/urandom`
|
|
||||||
yielding unpredictable bytes.
|
|
||||||
|
|
||||||
These are the only `/dev` entries danos can implement immediately, and they are the
|
|
||||||
sensible place to start, because they are exactly the entries that need no driver
|
|
||||||
process, no `device_claim`, no MMIO grant and no interrupt. A future pseudo-device
|
|
||||||
service would answer them out of its own address space — `null` and `zero` are a few
|
|
||||||
lines each in its `read` and `write` handlers — and mount itself at `/dev` the way the
|
|
||||||
FAT server mounts `/mnt/usb`. The two pieces of structure every later device node
|
|
||||||
depends on (and that the flat ramfs of the time lacked) exist now: directories, so that
|
|
||||||
`/dev/null` is a path rather than a name; and a populated `FileStatus.kind`, so that a
|
|
||||||
caller can tell a character device from a regular file.
|
|
||||||
|
|
||||||
`/dev/random` is the one that is not free. It needs an entropy source, and the honest
|
|
||||||
options on this kernel are `RDRAND`/`RDSEED` where CPUID advertises them, and the HPET
|
|
||||||
counter's low bits as a poor fallback. Neither is a seeded CSPRNG, and a `/dev/random`
|
|
||||||
that is merely unpredictable-looking is worse than none — nothing should be keyed from
|
|
||||||
it until it is a real one.
|
|
||||||
File renamed without changes.
@@ -1,6 +1,6 @@
|
|||||||
# Device interrupts
|
# Device interrupts
|
||||||
|
|
||||||
CPU exceptions ([interrupts.md](interrupts.md)) are the kernel reacting to its own
|
CPU exceptions ([interrupts.md](../os-development/interrupts.md)) are the kernel reacting to its own
|
||||||
mistakes. **Device interrupts** are the opposite: hardware asking for attention —
|
mistakes. **Device interrupts** are the opposite: hardware asking for attention —
|
||||||
a timer firing, a key pressed, a packet arriving. They share the IDT, but differ
|
a timer firing, a key pressed, a packet arriving. They share the IDT, but differ
|
||||||
in one fundamental way: an exception here is terminal (we report and halt), while a
|
in one fundamental way: an exception here is terminal (we report and halt), while a
|
||||||
@@ -10,7 +10,7 @@ back — the same mechanism a scheduler will later use to preempt tasks.
|
|||||||
|
|
||||||
The first device we bring up is the **timer**, because it's the simplest: it lives
|
The first device we bring up is the **timer**, because it's the simplest: it lives
|
||||||
entirely on the CPU's local interrupt controller, needing no external routing.
|
entirely on the CPU's local interrupt controller, needing no external routing.
|
||||||
It's all x86_64-specific, behind the [architecture](architecture.md) boundary.
|
It's all x86_64-specific, behind the [architecture](../os-development/architecture.md) boundary.
|
||||||
|
|
||||||
## The APIC, not the PIC
|
## The APIC, not the PIC
|
||||||
|
|
||||||
@@ -40,7 +40,7 @@ count that becomes the reload value. From then on it fires vector 32 repeatedly,
|
|||||||
its own, forever.
|
its own, forever.
|
||||||
|
|
||||||
The reload count isn't picked arbitrarily — it's **calibrated to real time**,
|
The reload count isn't picked arbitrarily — it's **calibrated to real time**,
|
||||||
which the [real-time](vision.md) scheduling guarantees depend on. Since the LAPIC
|
which the [real-time](../vision.md) scheduling guarantees depend on. Since the LAPIC
|
||||||
timer's raw rate is bus-clock dependent and unknown up front, `calibrate` runs the
|
timer's raw rate is bus-clock dependent and unknown up front, `calibrate` runs the
|
||||||
LAPIC timer one-shot from its maximum count while a **reference clock** counts out a
|
LAPIC timer one-shot from its maximum count while a **reference clock** counts out a
|
||||||
known 10 ms, then sees how far the LAPIC got — its counts-per-millisecond, from which
|
known 10 ms, then sees how far the LAPIC got — its counts-per-millisecond, from which
|
||||||
@@ -53,7 +53,7 @@ a missing PIT would hang the boot):
|
|||||||
|
|
||||||
1. **CPUID leaf 0x15** — the CPU's TSC frequency directly, needing no external timer
|
1. **CPUID leaf 0x15** — the CPU's TSC frequency directly, needing no external timer
|
||||||
at all (the LAPIC is then measured against the TSC).
|
at all (the LAPIC is then measured against the TSC).
|
||||||
2. The **HPET**, discovered via ACPI (see [discovery](discovery.md) / [acpi](acpi.md)).
|
2. The **HPET**, discovered via ACPI (see [discovery](../os-development/discovery.md) / [acpi](../os-development/acpi.md)).
|
||||||
3. The **ACPI PM timer** (a fixed 3.579545 MHz counter from the FADT).
|
3. The **ACPI PM timer** (a fixed 3.579545 MHz counter from the FADT).
|
||||||
4. The **PIT** (legacy 8254, 1.193182 MHz) — last resort, and bounded so it can't hang.
|
4. The **PIT** (legacy 8254, 1.193182 MHz) — last resort, and bounded so it can't hang.
|
||||||
|
|
||||||
@@ -100,7 +100,7 @@ values (a second socket, some firmware), so a thread migrating from a core readi
|
|||||||
check** as each application processor comes online (`checkWarpSource`, adapted from
|
check** as each application processor comes online (`checkWarpSource`, adapted from
|
||||||
Linux's): the waking core and the BSP hammer a shared "highest seen" TSC under a lock,
|
Linux's): the waking core and the BSP hammer a shared "highest seen" TSC under a lock,
|
||||||
and if either ever reads below it, the cores' TSCs are skewed. It's pairwise because APs
|
and if either ever reads below it, the cores' TSCs are skewed. It's pairwise because APs
|
||||||
come up one at a time ([smp.md](smp.md)).
|
come up one at a time ([smp.md](../os-development/smp.md)).
|
||||||
|
|
||||||
**The fallback.** When the TSC fails either test — non-invariant (a bare VM such as the
|
**The fallback.** When the TSC fails either test — non-invariant (a bare VM such as the
|
||||||
default qemu64), or warped between cores — danos moves the monotonic clock onto the
|
default qemu64), or warped between cores — danos moves the monotonic clock onto the
|
||||||
@@ -160,7 +160,7 @@ A device handler is a plain `fn () void` — a timer or keyboard handler doesn't
|
|||||||
the interrupted registers. (The stubs originally didn't save the SSE/vector
|
the interrupted registers. (The stubs originally didn't save the SSE/vector
|
||||||
registers, so a handler couldn't use them; `isr_common` now does an
|
registers, so a handler couldn't use them; `isr_common` now does an
|
||||||
`fxsave`/`fxrstor` of the full SSE/x87 state around dispatch — see
|
`fxsave`/`fxrstor` of the full SSE/x87 state around dispatch — see
|
||||||
[interrupts.md](interrupts.md).)
|
[interrupts.md](../os-development/interrupts.md).)
|
||||||
|
|
||||||
## Turning them on
|
## Turning them on
|
||||||
|
|
||||||
@@ -168,11 +168,11 @@ Exceptions can't be masked, which is why they worked all along. Maskable device
|
|||||||
interrupts don't fire until the CPU's interrupt flag is set — so the final step is
|
interrupts don't fire until the CPU's interrupt flag is set — so the final step is
|
||||||
`sti` (`arch.enableInterrupts()`), after the APIC and timer are configured. From
|
`sti` (`arch.enableInterrupts()`), after the APIC and timer are configured. From
|
||||||
that instant the kernel has a heartbeat, and its idle `hlt` loop
|
that instant the kernel has a heartbeat, and its idle `hlt` loop
|
||||||
([halting.md](halting.md)) wakes on every tick and dozes off again.
|
([halting.md](../os-development/halting.md)) wakes on every tick and dozes off again.
|
||||||
|
|
||||||
## Verifying it
|
## Verifying it
|
||||||
|
|
||||||
The `timer` test (see [testing.md](testing.md)) is the proof that an interrupt both
|
The `timer` test (see [testing.md](../testing.md)) is the proof that an interrupt both
|
||||||
*fires* and *returns*: it records the tick count, busy-waits, and checks the count
|
*fires* and *returns*: it records the tick count, busy-waits, and checks the count
|
||||||
advanced on its own.
|
advanced on its own.
|
||||||
|
|
||||||
@@ -188,13 +188,13 @@ spinning in unrelated code — is the whole mechanism working end to end.
|
|||||||
## Since (done elsewhere)
|
## Since (done elsewhere)
|
||||||
|
|
||||||
- **Preemption**: the timer handler is where the scheduler decides to switch — the
|
- **Preemption**: the timer handler is where the scheduler decides to switch — the
|
||||||
reason a *returning* interrupt matters. See [scheduling.md](scheduling.md).
|
reason a *returning* interrupt matters. See [scheduling.md](../os-development/scheduling.md).
|
||||||
- **`sleep()` / timeouts** built on the calibrated clock.
|
- **`sleep()` / timeouts** built on the calibrated clock.
|
||||||
- **The I/O APIC, routed**: external device lines now reach a vector, and the
|
- **The I/O APIC, routed**: external device lines now reach a vector, and the
|
||||||
interrupt is delivered onward to a *user-space* driver as an IPC message. See
|
interrupt is delivered onward to a *user-space* driver as an IPC message. See
|
||||||
[drivers.md](drivers.md).
|
[drivers.md](drivers.md).
|
||||||
- **Uncacheable MMIO**: device grants are mapped `PCD|PWT` (strong-uncacheable) for
|
- **Uncacheable MMIO**: device grants are mapped `PCD|PWT` (strong-uncacheable) for
|
||||||
user drivers — see [paging.md](paging.md).
|
user drivers — see [paging.md](../os-development/paging.md).
|
||||||
|
|
||||||
## What's next (partly done since)
|
## What's next (partly done since)
|
||||||
|
|
||||||
@@ -10,19 +10,19 @@ mirrors them and prunes a dead reporter's children, and the `usb-report`
|
|||||||
scenario proves report → prune → respawn → re-report. The application surface is built (M18.3, 2026-07-13):
|
scenario proves report → prune → respawn → re-report. The application surface is built (M18.3, 2026-07-13):
|
||||||
`enumerate` and `subscribe` over IPC, with `device-list` as the first client —
|
`enumerate` and `subscribe` over IPC, with `device-list` as the first client —
|
||||||
the manager is now the one answer to "what devices exist" for applications.
|
the manager is now the one answer to "what devices exist" for applications.
|
||||||
The primitives underneath are real ([process-management.md](process-management.md):
|
The primitives underneath are real ([process-management.md](../os-development/process-management.md):
|
||||||
spawn/supervise/kill/exit-notification; [driver-model.md](driver-model.md): the device
|
spawn/supervise/kill/exit-notification; [driver-model.md](driver-model.md): the device
|
||||||
table as a capability system; [drivers.md](drivers.md): claim/map/IRQ), and the first
|
table as a capability system; [drivers.md](drivers.md): claim/map/IRQ), and the first
|
||||||
per-device driver spawn works (the device manager matches the xHCI controller by PCI
|
per-device driver spawn works (the device manager matches the xHCI controller by PCI
|
||||||
class and spawns `usb-xhci-bus` with the device id as argv[1]). This document designs
|
class and spawns `usb-xhci-bus` with the device id as argv[1]). This document designs
|
||||||
the rest: the device manager as **the tree, the matcher, and the supervisor** — the
|
the rest: the device manager as **the tree, the matcher, and the supervisor** — the
|
||||||
policy process that turns [resilience.md](resilience.md)'s restart goal into practice
|
policy process that turns [resilience.md](../os-development/resilience.md)'s restart goal into practice
|
||||||
for drivers.
|
for drivers.
|
||||||
|
|
||||||
How processes stop, reload, and report their deaths is deliberately **not** in this
|
How processes stop, reload, and report their deaths is deliberately **not** in this
|
||||||
document: that is the universal lifecycle every danos process speaks —
|
document: that is the universal lifecycle every danos process speaks —
|
||||||
[process-lifecycle.md](process-lifecycle.md), signals over IPC and the stable
|
[process-lifecycle.md](../os-development/process-lifecycle.md), signals over IPC and the stable
|
||||||
`runtime.process` interface. The device manager is that design's first serious
|
`process` interface. The device manager is that design's first serious
|
||||||
customer, not its owner. Its own protocol contains nothing lifecycle-shaped; a
|
customer, not its owner. Its own protocol contains nothing lifecycle-shaped; a
|
||||||
driver is stopped, health-checked, and buried exactly like any other process.
|
driver is stopped, health-checked, and buried exactly like any other process.
|
||||||
|
|
||||||
@@ -35,7 +35,7 @@ The device tree is two things fused: *information* (what exists, how it nests) a
|
|||||||
claims, resource containment on `device_register`, the
|
claims, resource containment on `device_register`, the
|
||||||
`mmio_map`/`irq_bind`/`msi_bind` gates — and **cleans all of it up when a process
|
`mmio_map`/`irq_bind`/`msi_bind` gates — and **cleans all of it up when a process
|
||||||
dies** (settled; it is increment 1 of
|
dies** (settled; it is increment 1 of
|
||||||
[process-lifecycle.md](process-lifecycle.md)). The three invariants in
|
[process-lifecycle.md](../os-development/process-lifecycle.md)). The three invariants in
|
||||||
[driver-model.md](driver-model.md) stay exactly where they are. A device manager
|
[driver-model.md](driver-model.md) stay exactly where they are. A device manager
|
||||||
that could mint MMIO mappings by its own say-so would be a second kernel, and a
|
that could mint MMIO mappings by its own say-so would be a second kernel, and a
|
||||||
buggy one would un-earn everything the microkernel bought.
|
buggy one would un-earn everything the microkernel bought.
|
||||||
@@ -51,7 +51,7 @@ enumeration is a **pci-bus driver**: the manager spawns it against the host brid
|
|||||||
like any bus reports children. ACPI becomes an **acpi service** that interprets the
|
like any bus reports children. ACPI becomes an **acpi service** that interprets the
|
||||||
tables and reports the namespace. The manager only orchestrates and merges. Moving
|
tables and reports the namespace. The manager only orchestrates and merges. Moving
|
||||||
AML interpretation out of ring 0 is its own project on its own track; nothing here
|
AML interpretation out of ring 0 is its own project on its own track; nothing here
|
||||||
depends on when it lands. (It landed: [discovery.md](discovery.md), M19–M20.)
|
depends on when it lands. (It landed: [discovery.md](../os-development/discovery.md), M19–M20.)
|
||||||
|
|
||||||
`device_register` is **idempotent on exact match**: a re-registration with an
|
`device_register` is **idempotent on exact match**: a re-registration with an
|
||||||
identical (parent, class, identity, resources) tuple returns the existing id
|
identical (parent, class, identity, resources) tuple returns the existing id
|
||||||
@@ -64,50 +64,102 @@ restarted instance to rebuild exactly the same ids.
|
|||||||
|
|
||||||
## The protocol
|
## The protocol
|
||||||
|
|
||||||
A `device-manager-protocol` module (the vfs-protocol pattern): extern-struct
|
A `device-manager-protocol` module, defined through the
|
||||||
messages, a version in the handshake, reserved fields everywhere. The manager is a
|
[envelope](../os-development/protocol-namespace.md): every packet — request,
|
||||||
well-known endpoint (`ipc.register(.device_manager)`); the badge tells it who is
|
reply, and pushed event alike — begins with the folded `Header`, and **the device
|
||||||
|
id is `Header.target`**, the manager's object addressing. The contract is bound at
|
||||||
|
`/protocol/device-manager`; the kernel-stamped badge tells the manager who is
|
||||||
talking; the same endpoint receives its children's exit notifications — one loop,
|
talking; the same endpoint receives its children's exit notifications — one loop,
|
||||||
one world.
|
one world.
|
||||||
|
|
||||||
| Direction | Message | Purpose |
|
| Direction | Packet | Purpose |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| driver → manager | `hello { version, role, device_id }` | confirms the argv assignment, starts the deadline clock |
|
| driver → manager | `hello { role, wants_channel, version }` @ the assigned device | confirms the assignment, starts the deadline clock — **and moves the channels** (below) |
|
||||||
| bus → manager | `child_added { parent, bus_address, identity, device_id, hid }` | one node the bus discovered |
|
| bus → manager | `child_added { parent, bus_address, identity, bus, vendor, device, subsystem, hid }` @ the registered device id | one node the bus discovered |
|
||||||
| bus → manager | `child_removed { parent, bus_address }` | unplug, or the bus lost it |
|
| bus → manager | `child_removed { parent, bus_address }` | unplug, or the bus lost it |
|
||||||
| app → manager | `enumerate` | snapshot of the tree (read-only) |
|
| app → manager | `enumerate` (reserved verb 1) @ start index | one page of the tree, one `ChildEntry` per record in the reply's tail; a short page is the end |
|
||||||
| app → manager | `subscribe` | receive published add/remove events |
|
| app → manager | `subscribe` (reserved verb 2) | receive published add/remove events; the subscriber's endpoint rides as the call's capability |
|
||||||
|
| manager → app | `child_added` / `child_removed` events | the same two structs, pushed rather than called |
|
||||||
|
|
||||||
|
**`hello` is also the establishment plane for driver-layer channels**
|
||||||
|
([communication.md](../os-development/communication.md) "Establishment: two
|
||||||
|
planes, one namespace"). A provider's hello carries its serving endpoint UP as
|
||||||
|
the call's capability (the xHCI bus its transfer endpoint, usb-storage its
|
||||||
|
block endpoint — several processes provide those contracts, so neither is ever
|
||||||
|
a registry name). A hello with `wants_channel` set is answered with a
|
||||||
|
capability DOWN: for a `.device`-role driver, the channel of its device's
|
||||||
|
*reporter* (a class driver reaching its own controller); for a `.consumer`
|
||||||
|
(not a spawned driver at all — fat looking for its volume), the channel of the
|
||||||
|
driver *bound to* the target device. No channel in an acked reply means the
|
||||||
|
provider is mid-restart and its re-report is on the way — retryable, never a
|
||||||
|
verdict.
|
||||||
|
|
||||||
|
The watcher table behind those last two rows is the **service harness's**
|
||||||
|
(`service.Subscribers`, shared with input and power), not the manager's: it
|
||||||
|
answers `subscribe`/`unsubscribe`, frames each event once for the fan-out, and
|
||||||
|
sweeps a watcher on its exit notification — where the manager previously had no
|
||||||
|
sweep for watchers at all. Its own supervised-driver exits are a different thing
|
||||||
|
and unchanged, except that a driver's death now arrives twice (the manager is
|
||||||
|
both its supervisor and a subscriber to published exits), so the manager retires
|
||||||
|
a dead driver's process id as it handles the first and the second finds nothing
|
||||||
|
to act on.
|
||||||
|
|
||||||
|
Two of what used to be the manager's own operations are the envelope's **reserved**
|
||||||
|
verbs, which mean the same thing at every provider in the system, so this protocol
|
||||||
|
numbers only three of its own (`hello` = 16, `child_added` = 17,
|
||||||
|
`child_removed` = 18) and its two events in their own space (`child_added` = 16,
|
||||||
|
`child_removed` = 17). No reply carries a status field: that is the `Status` every
|
||||||
|
reply begins with.
|
||||||
|
|
||||||
|
`child_added` is the one struct that travels both ways — a bus *calls* it, the
|
||||||
|
manager *pushes* it — which is why the operation and event numbering spaces are
|
||||||
|
separate: one encoding, both directions, told apart by which way the packet went.
|
||||||
|
Folding the operation byte and the device id out of it is also what makes it fit:
|
||||||
|
a pushed event is 64 bytes at most, header included, and this one lands exactly on
|
||||||
|
that floor. `child_removed` is the single message whose target stays 0, because it
|
||||||
|
is addressed by the composite (parent, bus address) and no single `u64` carries a
|
||||||
|
pair.
|
||||||
|
|
||||||
`hello` is the one deadline the manager enforces itself: spawned and silent past the
|
`hello` is the one deadline the manager enforces itself: spawned and silent past the
|
||||||
deadline means wrong binary, wrong protocol version, or wedged before main — apply
|
deadline means wrong binary, wrong protocol version, or wedged before main — apply
|
||||||
the stop sequence and the restart policy. Everything else lifecycle-shaped
|
the stop sequence and the restart policy. Everything else lifecycle-shaped
|
||||||
(terminate, the common `ping` liveness call, exit reasons) arrives through
|
(terminate, the common `ping` liveness call, exit reasons) arrives through
|
||||||
[process-lifecycle.md](process-lifecycle.md)'s vocabulary, not this protocol.
|
[process-lifecycle.md](../os-development/process-lifecycle.md)'s vocabulary, not this protocol.
|
||||||
|
|
||||||
Assignment stays argv (`usb-xhci-bus <device id>`) for now — simple, and it works.
|
Delegation is BUILT (docs/os-development/device-authority.md "As built"): the
|
||||||
The step after `hello` exists is delegation: the manager claims (or is granted) the
|
device arrives WITH the spawn — `system_spawn`'s sixth argument moves the
|
||||||
devices and passes the claim to the driver over IPC (the M13 capability-transfer
|
claim before the child's first instruction — and the id still rides argv for
|
||||||
mechanism), replacing first-come-first-served `device_claim` with policy. Identity in
|
the driver to name itself by. A given device is a loan that returns to the
|
||||||
|
manager on the holder's death. Identity in
|
||||||
`child_added` is per-bus: PCI children carry the class triple (`pci_class`, as the
|
`child_added` is per-bus: PCI children carry the class triple (`pci_class`, as the
|
||||||
xHCI match already uses); USB children carry the (class, subclass, protocol) triple
|
xHCI match already uses); USB children carry the (class, subclass, protocol) triple
|
||||||
from usb-ids.zig — each bus's native language, decoded by the shared ids modules.
|
from usb-ids.zig — each bus's native language, decoded by the shared ids modules.
|
||||||
|
(Since the registry landed, `child_added` also carries a `bus` discriminator and
|
||||||
|
the numeric `vendor`/`device`/`subsystem` ids the finer match levels need —
|
||||||
|
see [/system/configuration/devices.csv](devices-csv.md).)
|
||||||
|
|
||||||
## Supervision and restart
|
## Supervision and restart
|
||||||
|
|
||||||
Every driver is spawned with the manager's exit endpoint (`spawnSupervised` — built).
|
Every driver is spawned with the manager's exit endpoint (`spawnSupervised` — built).
|
||||||
On a death notification:
|
On a death notification:
|
||||||
|
|
||||||
1. **Read the reason** ([process-lifecycle.md](process-lifecycle.md) increment 2).
|
1. **Read the reason** ([process-lifecycle.md](../os-development/process-lifecycle.md) increment 2).
|
||||||
Clean exit → it meant to; don't restart. Fault or missed `hello` deadline →
|
Clean exit → it meant to; don't restart. Fault or missed `hello` deadline →
|
||||||
restart with **backoff**, and a crash-loop cap (three fast deaths → mark failed,
|
restart with **backoff**, and a crash-loop cap (three fast deaths → mark failed,
|
||||||
stop respawning, log loudly; a later `reload` to the manager can retry).
|
stop respawning, log loudly; a later `reload` to the manager can retry).
|
||||||
2. **Prune the subtree** the dead bus driver reported. Its children describe
|
2. **Prune the subtree** the dead bus driver reported, **reaping the class
|
||||||
protocol state (xHCI slot ids, transfer rings) that died with the process;
|
drivers bound to its children**. Its children describe protocol state (xHCI
|
||||||
keeping the nodes would be keeping a lie. Watchers receive `child_removed` — the
|
slot ids, transfer rings) that died with the process; keeping the nodes
|
||||||
input service losing, then regaining, a keyboard is the *honest* description of
|
would be keeping a lie — and the class drivers hold channels into the dead
|
||||||
what happened. The restarted instance rediscovers and re-reports.
|
process they cannot observe dying (an HID driver blocks on reports that
|
||||||
3. **The claim is already free** because the kernel released it at death — the
|
simply never come). Each is killed and its entry cleared, so the matcher
|
||||||
restarted instance claims the same controller and comes up.
|
can respawn a fresh generation when the re-report arrives; their hellos
|
||||||
|
fetch the successor's channel. Watchers receive `child_removed` — the input
|
||||||
|
service losing, then regaining, a keyboard is the *honest* description of
|
||||||
|
what happened.
|
||||||
|
3. **The device is already back** because the loan returned at death — the
|
||||||
|
manager re-delegates the same controller with the respawn, and the kernel
|
||||||
|
confines it afresh.
|
||||||
|
|
||||||
Who supervises the supervisor: **init** (PID 1), which already supervises the
|
Who supervises the supervisor: **init** (PID 1), which already supervises the
|
||||||
services it starts. If the manager dies, drivers keep running (they hold their
|
services it starts. If the manager dies, drivers keep running (they hold their
|
||||||
@@ -136,8 +188,8 @@ way.
|
|||||||
## Increments
|
## Increments
|
||||||
|
|
||||||
Increments 1–4 are the lifecycle prerequisites and live in
|
Increments 1–4 are the lifecycle prerequisites and live in
|
||||||
[process-lifecycle.md](process-lifecycle.md) (claim cleanup on death, exit reasons,
|
[process-lifecycle.md](../os-development/process-lifecycle.md) (claim cleanup on death, exit reasons,
|
||||||
published exit events, signals + `runtime.process`). On top of those:
|
published exit events, signals + `process`). On top of those:
|
||||||
|
|
||||||
5. **device-manager-protocol**: `hello`, supervised spawn with restart policy;
|
5. **device-manager-protocol**: `hello`, supervised spawn with restart policy;
|
||||||
usb-xhci-bus becomes the first conforming driver.
|
usb-xhci-bus becomes the first conforming driver.
|
||||||
@@ -147,7 +199,7 @@ published exit events, signals + `runtime.process`). On top of those:
|
|||||||
to a manager-internal seam.
|
to a manager-internal seam.
|
||||||
8. **Discovery migration** — DONE (M19–M20, 2026-07-13): enumeration moved to
|
8. **Discovery migration** — DONE (M19–M20, 2026-07-13): enumeration moved to
|
||||||
ring 3 as swappable per-firmware discoverers — the pci-bus driver (M19) then
|
ring 3 as swappable per-firmware discoverers — the pci-bus driver (M19) then
|
||||||
the acpi service (M20), see [discovery.md](discovery.md); of the enumerable
|
the acpi service (M20), see [discovery.md](../os-development/discovery.md); of the enumerable
|
||||||
devices, the kernel seeds only the host bridge and the acpi-tables node (the
|
devices, the kernel seeds only the host bridge and the acpi-tables node (the
|
||||||
non-enumerable platform nodes — processors, interrupt controllers, the HPET,
|
non-enumerable platform nodes — processors, interrupt controllers, the HPET,
|
||||||
the loader's framebuffer — stay kernel-seeded too). Matching moved with it:
|
the loader's framebuffer — stay kernel-seeded too). Matching moved with it:
|
||||||
@@ -169,9 +221,15 @@ published exit events, signals + `runtime.process`). On top of those:
|
|||||||
- **Manager death**: drivers survive the manager; the restarted manager re-learns
|
- **Manager death**: drivers survive the manager; the restarted manager re-learns
|
||||||
the world (above). Checkpointing driver state with the manager is deferred until
|
the world (above). Checkpointing driver state with the manager is deferred until
|
||||||
something demonstrates the need.
|
something demonstrates the need.
|
||||||
- **Matching stays code until the third bus.** `driverFor`/`pciDriverFor` were
|
- **Matching is a registry, not code (resolved 2026-07-26).** `driverFor`/
|
||||||
honest at two bus types; the third was expected to trigger the manifest (a driver
|
`pciDriverFor` were honest at two bus types; the third (USB) was matched in code
|
||||||
declares what it binds: a PCI class triple, a USB class triple, an ACPI `_HID`).
|
too, and then the switch tables started to hurt — they keyed PCI matches on the
|
||||||
(Since then: the third bus — USB — arrived and is matched in code too. Today's
|
class triple alone, so a virtio-gpu could only be matched as a generic display
|
||||||
matchers are `pciDriverForIdentity`, `hidDriverFor`, and `usbDriverForIdentity`;
|
function and the driver had to re-confirm its `1AF4:1050` identity from config
|
||||||
the manifest waits until code matching actually hurts.)
|
space after being spawned. The manifest the earlier note anticipated landed as a
|
||||||
|
human-readable registry: **[/system/configuration/devices.csv](devices-csv.md)**, parsed by the
|
||||||
|
pure `device-registry` module and read by the manager at boot. A row binds a
|
||||||
|
driver to a device by any of base / subclass / prog-IF / vendor / device /
|
||||||
|
subsystem / `_HID`, most-specific match winning; it is authoritative (no
|
||||||
|
compiled-in fallback — an unmatched device is logged, never guessed).
|
||||||
|
`pciDriverForIdentity`, `hidDriverFor`, and `usbDriverForIdentity` are gone.
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
# /system/configuration/devices.csv — the device registry
|
||||||
|
|
||||||
|
**Status: built (2026-07-26).** The device manager reads `/system/configuration/devices.csv` at
|
||||||
|
boot and binds every device a bus driver reports to the driver the registry
|
||||||
|
names. It replaces the three hand-written `switch` tables that used to live in
|
||||||
|
the manager (`pciDriverForIdentity`, `hidDriverFor`, `usbDriverForIdentity`) —
|
||||||
|
the "manifest" [device-manager.md](device-manager.md) anticipated once code
|
||||||
|
matching started to hurt. The parser and matcher are the pure, unit-tested
|
||||||
|
`device-registry` module (`library/device/registry/device-registry.zig`).
|
||||||
|
|
||||||
|
## Why a registry
|
||||||
|
|
||||||
|
The switch tables keyed PCI matches on the 24-bit class/subclass/prog-IF triple
|
||||||
|
alone. That is too coarse: a virtio-gpu is just "display / other" by class, so it
|
||||||
|
could only be *class-matched* and the driver had to re-confirm its real
|
||||||
|
`1AF4:1050` identity from config space **after** the manager had already spawned
|
||||||
|
it. The registry lets a rule bind on the full identity — down to vendor, device,
|
||||||
|
and subsystem — so the manager makes the precise decision itself, and the driver
|
||||||
|
comes up already knowing it is the right one.
|
||||||
|
|
||||||
|
It is also **data, not code**: teaching the system new hardware is a line in a
|
||||||
|
file, not an edit-and-recompile of the manager. And it is **greppable** — one
|
||||||
|
place to read "what binds what," the same idea as Linux's `modules.alias`.
|
||||||
|
|
||||||
|
## The file
|
||||||
|
|
||||||
|
One rule per line, nine comma-separated fields; `#` starts a comment (whole-line
|
||||||
|
or trailing); blank lines are ignored. Whitespace around a field is trimmed, so
|
||||||
|
columns may be padded for readability.
|
||||||
|
|
||||||
|
```
|
||||||
|
# bus base class prog_if vendor device subsystem hid driver
|
||||||
|
pci, 0C, 03, 30, *, *, *, *, /system/drivers/usb-xhci-bus
|
||||||
|
pci, 03, 00, 00, *, *, *, *, /system/drivers/display
|
||||||
|
pci, 03, 80, *, 1AF4, 1050, *, *, /system/drivers/virtio-gpu
|
||||||
|
usb, 03, 01, 01, *, *, *, *, /system/drivers/usb-hid-keyboard
|
||||||
|
acpi, *, *, *, *, *, *, PNP0303, /system/drivers/ps2-bus
|
||||||
|
```
|
||||||
|
|
||||||
|
| Field | Meaning | Notes |
|
||||||
|
|---|---|---|
|
||||||
|
| `bus` | `pci` \| `usb` \| `acpi` | which bus reported the device; picks the namespace for the id columns |
|
||||||
|
| `base` | PCI base class / USB class | hex |
|
||||||
|
| `class` | PCI subclass / USB subclass | hex |
|
||||||
|
| `prog_if` | PCI prog-IF / USB protocol | hex |
|
||||||
|
| `vendor` | PCI vendor / USB idVendor | hex |
|
||||||
|
| `device` | PCI device / USB idProduct | hex |
|
||||||
|
| `subsystem` | PCI subsystem, `(ssvid<<16)\|ssid` | hex; blank for usb/acpi |
|
||||||
|
| `hid` | ACPI `_HID` (e.g. `PNP0303`) | blank for pci/usb |
|
||||||
|
| `driver` | full ramdisk path to spawn | e.g. `/system/drivers/virtio-gpu` |
|
||||||
|
|
||||||
|
`*` or an empty field is a **wildcard** — it matches anything and adds nothing to
|
||||||
|
a rule's specificity.
|
||||||
|
|
||||||
|
## Levels of detection: most-specific-wins
|
||||||
|
|
||||||
|
Several rows may match one device. The manager picks the **most specific** — the
|
||||||
|
one that pins the finest-grained fields. Specificity weights double from the
|
||||||
|
coarsest level so each outweighs all coarser levels combined:
|
||||||
|
|
||||||
|
```
|
||||||
|
base(1) < class(2) < prog_if(4) < vendor(8) < subsystem(16) < device(32) ≈ hid(32)
|
||||||
|
```
|
||||||
|
|
||||||
|
So the generic `pci, 03, 00, 00, …/display` rule and the precise
|
||||||
|
`pci, 03, 80, *, 1AF4, 1050, …/virtio-gpu` rule coexist: the virtio card
|
||||||
|
(vendor 1AF4, device 1050) takes the specific rule; a plain VGA adapter still
|
||||||
|
falls to the generic one. Two rules that match a device with the *same*
|
||||||
|
specificity are a registry authoring error — the manager logs it loudly and binds
|
||||||
|
the first, so the shadowed rule is visible rather than silently dropped.
|
||||||
|
|
||||||
|
## Authoritative — no code fallback
|
||||||
|
|
||||||
|
There is no compiled-in default table behind the registry. A device that no row
|
||||||
|
matches goes **unbound** and is logged; the manager never guesses. A missing or
|
||||||
|
empty `/system/configuration/devices.csv` therefore means nothing matches — which is loud at boot,
|
||||||
|
not a silent half-working system.
|
||||||
|
|
||||||
|
## How the manager reads it
|
||||||
|
|
||||||
|
`/system/configuration/devices.csv` is bundled into the initial ramdisk (`build.zig`'s `bundled`
|
||||||
|
list). The kernel serves the initrd's `/system/configuration` tree directly — the `fat` service is
|
||||||
|
spawned *after* the device manager and is irrelevant to `/system/configuration` — so the manager
|
||||||
|
reads the file with a plain `fs.open("/system/configuration/devices.csv")` + `read`, with no
|
||||||
|
filesystem service running and no boot-ordering dependency. It parses the bytes
|
||||||
|
once in `initialise`, before any bus driver can report a device to match.
|
||||||
|
|
||||||
|
## Feeding the matcher: the widened report
|
||||||
|
|
||||||
|
Finer-grained matching needs identity the old ABI threw away. Two things carry it
|
||||||
|
now: `child_added` (and `DeviceDescriptor`) grew `vendor` / `device` /
|
||||||
|
`subsystem` fields, filled by the PCI bus driver from config space (offsets
|
||||||
|
0x00 and 0x2C); and each bus driver states its `bus` in the report (a `BusKind`),
|
||||||
|
so the manager reads a PCI class triple and a USB class triple — the same 24 bits
|
||||||
|
in different namespaces — against the right `bus` column.
|
||||||
|
|
||||||
|
## Adding a driver
|
||||||
|
|
||||||
|
(The step-by-step walkthrough with a worked example is
|
||||||
|
[new-driver-checklist.md](new-driver-checklist.md).)
|
||||||
|
|
||||||
|
1. Create `system/drivers/<name>/` with the driver source plus a ~15-line
|
||||||
|
package `build.zig` + `build.zig.zon` (copy an existing driver package,
|
||||||
|
e.g. `system/drivers/pci-bus/`; per-driver extras go through
|
||||||
|
`build_support.programModule`). Then bundle it at `/system/drivers/<name>`:
|
||||||
|
one dependency + one bundled entry in the root `build.zig`, one line in the
|
||||||
|
root `build.zig.zon`.
|
||||||
|
2. Add a row to `system/configuration/devices.csv` naming the identity it binds and its full path.
|
||||||
|
|
||||||
|
No device-manager change is required — the registry is the seam.
|
||||||
@@ -18,18 +18,19 @@ Read [display.md](display.md) first for the *why*; this is the *what* and the *o
|
|||||||
|
|
||||||
## Conventions
|
## Conventions
|
||||||
|
|
||||||
Follow [coding-standards.md](coding-standards.md): spell out non-acronym abbreviations in
|
Follow [coding-standards.md](../coding-standards.md): spell out non-acronym abbreviations in
|
||||||
full, kebab-case file names, no `Co-Authored-By` trailers on commits. New user binaries
|
full, kebab-case file names, no `Co-Authored-By` trailers on commits. New user binaries
|
||||||
go through `addUserBinary` in [build.zig](../build.zig) and get packed into the
|
go through build-support's shared user-binary recipe and get packed into the
|
||||||
initial-ramdisk; protocols are `b.addModule("…-protocol", …)` and imported into the
|
initial-ramdisk; protocols are modules exported by the `library/protocol` package.
|
||||||
`runtime` module.
|
(This section predates the build-packages split; see
|
||||||
|
[build-packages-plan.md](../build-packages-plan.md) for the current build shape.)
|
||||||
|
|
||||||
## How to verify along the way
|
## How to verify along the way
|
||||||
|
|
||||||
- `zig build test` — host unit tests (compositor math: layer clipping, damage merge,
|
- `zig build test` — host unit tests (compositor math: layer clipping, damage merge,
|
||||||
pitch/format blits are all host-testable with a fake framebuffer).
|
pitch/format blits are all host-testable with a fake framebuffer).
|
||||||
- `python3 test/qemu_test.py <case>` — boots the real kernel in QEMU; assert on the
|
- `python3 test/qemu_test.py <case>` — boots the real kernel in QEMU; assert on the
|
||||||
serial log ([tests.zig](../system/kernel/tests.zig) is the registry).
|
serial log ([tests.zig](../../system/kernel/tests.zig) is the registry).
|
||||||
- The `run-efi` target renders to QEMU's display (`-device VGA,edid=on,xres=1280,yres=720`)
|
- The `run-efi` target renders to QEMU's display (`-device VGA,edid=on,xres=1280,yres=720`)
|
||||||
— a screenshot confirms pixels for the milestones whose gate is visual.
|
— a screenshot confirms pixels for the milestones whose gate is visual.
|
||||||
|
|
||||||
@@ -39,22 +40,22 @@ initial-ramdisk; protocols are `b.addModule("…-protocol", …)` and imported i
|
|||||||
|
|
||||||
Make the boot framebuffer reachable and mappable **write-combining** from user space.
|
Make the boot framebuffer reachable and mappable **write-combining** from user space.
|
||||||
|
|
||||||
- [x] [device-abi.zig](../system/devices/device-abi.zig): added `DeviceClass.display`; a
|
- [x] [device-abi.zig](../../library/device/model/device-abi.zig): added `DeviceClass.display`; a
|
||||||
`DisplayInfo{ width, height, pitch, format }` carried on the descriptor; a
|
`DisplayInfo{ width, height, pitch, format }` carried on the descriptor; a
|
||||||
`flags` field on `ResourceDescriptor` + `resource_flag_write_combining`.
|
`flags` field on `ResourceDescriptor` + `resource_flag_write_combining`.
|
||||||
- [x] [devices-broker.zig](../system/kernel/devices-broker.zig): `seedDisplay(base, w, h,
|
- [x] [devices-broker.zig](../../system/kernel/devices-broker.zig): `seedDisplay(base, w, h,
|
||||||
pitch, format)` publishes a root-level `display` node with one WC-flagged `memory`
|
pitch, format)` publishes a root-level `display` node with one WC-flagged `memory`
|
||||||
resource `[base, height*pitch]` + the `DisplayInfo`; `displayDevice()` /
|
resource `[base, height*pitch]` + the `DisplayInfo`; `displayDevice()` /
|
||||||
`displayClaimed()`. Seeded from `kmain` after `devices_broker.init`.
|
`displayClaimed()`. Seeded from `kmain` after `devices_broker.init`.
|
||||||
- [x] [process.zig](../system/kernel/process.zig) `systemMmioMap` + paging
|
- [x] [process.zig](../../system/kernel/process.zig) `systemMmioMap` + paging
|
||||||
(`mapUserDeviceInto` gains a `write_combining` bool): a resource's WC flag maps it
|
(`mapUserDeviceInto` gains a `write_combining` bool): a resource's WC flag maps it
|
||||||
through the WC PAT slot (`setupPat`) instead of strong-uncacheable.
|
through the WC PAT slot (`setupPat`) instead of strong-uncacheable.
|
||||||
- [x] [console.zig](../system/kernel/console.zig): `setSuppressed` quiesces `write` while
|
- [x] [console.zig](../../system/kernel/console.zig): `setSuppressed` quiesces `write` while
|
||||||
the display device is claimed (driven from `systemDeviceClaim` / release); the
|
the display device is claimed (driven from `systemDeviceClaim` / release); the
|
||||||
terminal panic + exception paths clear it first so a dying machine still draws.
|
terminal panic + exception paths clear it first so a dying machine still draws.
|
||||||
|
|
||||||
**Gate (met, automated):** the `display` kernel test (`python3 test/qemu_test.py display`,
|
**Gate (met, automated):** the `display` kernel test (`python3 test/qemu_test.py display`,
|
||||||
`displayTest` in [tests.zig](../system/kernel/tests.zig)) asserts the seeded node's shape
|
`displayTest` in [tests.zig](../../system/kernel/tests.zig)) asserts the seeded node's shape
|
||||||
and geometry, then walks the real claim + `mmio_map` path into a throwaway address space
|
and geometry, then walks the real claim + `mmio_map` path into a throwaway address space
|
||||||
and verifies the leaf is **write-combining** (PAT entry 4: PAT bit set, PCD/PWT clear) —
|
and verifies the leaf is **write-combining** (PAT entry 4: PAT bit set, PCD/PWT clear) —
|
||||||
with an uncacheable-still-uncacheable regression guard. Chosen over the original
|
with an uncacheable-still-uncacheable regression guard. Chosen over the original
|
||||||
@@ -67,10 +68,10 @@ Regression-checked: `discovery`, `ioport`, `claim-release`, `supervision`, `devi
|
|||||||
|
|
||||||
Stand up the named service and the double-buffer, no layers yet.
|
Stand up the named service and the double-buffer, no layers yet.
|
||||||
|
|
||||||
- [x] `system/services/display/protocol.zig`: `Operation{ info, create_layer,
|
- [x] `library/protocol/display/display-protocol.zig`: `Operation{ info, create_layer,
|
||||||
configure_layer, destroy_layer, fill_rect, blit_tile, damage, present }`; `extern`
|
configure_layer, destroy_layer, fill_rect, blit_tile, damage, present }`; `extern`
|
||||||
`Request`/`Reply`; size + `maximum_payload` consts. (Model: block/protocol.zig.)
|
`Request`/`Reply`; size + `maximum_payload` consts. (Model: block/protocol.zig.)
|
||||||
- [x] [abi.zig](../system/abi.zig): `ServiceId.display = 9`.
|
- [x] [abi.zig](../../system/abi.zig): `ServiceId.display = 9`.
|
||||||
- [x] `system/services/display/display.zig`: `main` → enumerate + claim + WC-map the LFB
|
- [x] `system/services/display/display.zig`: `main` → enumerate + claim + WC-map the LFB
|
||||||
(front) → `mmap` a cacheable back buffer of `height*pitch` → `runtime.service.run`.
|
(front) → `mmap` a cacheable back buffer of `height*pitch` → `runtime.service.run`.
|
||||||
`info` and a whole-screen `present` (back → front) are live; layer ops fail-stub
|
`info` and a whole-screen `present` (back → front) are live; layer ops fail-stub
|
||||||
@@ -78,8 +79,8 @@ Stand up the named service and the double-buffer, no layers yet.
|
|||||||
- [x] [library/runtime/display.zig](../library/runtime/runtime.zig) (+ barrel export of
|
- [x] [library/runtime/display.zig](../library/runtime/runtime.zig) (+ barrel export of
|
||||||
`display` and `display_protocol`): `info()` and `present()`, cached `.display`
|
`display` and `display_protocol`): `info()` and `present()`, cached `.display`
|
||||||
lookup with retry (model: block.zig).
|
lookup with retry (model: block.zig).
|
||||||
- [x] [init.zig](../system/services/init/init.zig): `"display"` added to `boot_services`.
|
- [x] [init.zig](../../system/services/init/init.zig): `"display"` added to `boot_services`.
|
||||||
- [x] [build.zig](../build.zig): `display-protocol` module on the runtime; `display` exe
|
- [x] [build.zig](../../build.zig): `display-protocol` module on the runtime; `display` exe
|
||||||
via `addUserBinary`; packed into the initial-ramdisk; installed to
|
via `addUserBinary`; packed into the initial-ramdisk; installed to
|
||||||
`/system/services/display`.
|
`/system/services/display`.
|
||||||
- [x] **Kernel fix the back buffer surfaced:** `mmap` was capped at 256 pages (1 MiB) by
|
- [x] **Kernel fix the back buffer surfaced:** `mmap` was capped at 256 pages (1 MiB) by
|
||||||
@@ -105,7 +106,7 @@ The heart: composite an ordered layer stack, present only what changed.
|
|||||||
- [x] `create_layer` / `configure_layer` (damages old + new footprints) / `destroy_layer`,
|
- [x] `create_layer` / `configure_layer` (damages old + new footprints) / `destroy_layer`,
|
||||||
`fill_rect`, `blit_tile` (reads the inline tile from the IPC payload, unaligned-safe),
|
`fill_rect`, `blit_tile` (reads the inline tile from the IPC payload, unaligned-safe),
|
||||||
`damage`, `present`.
|
`damage`, `present`.
|
||||||
- [x] Pure, host-tested [compositor.zig](../system/services/display/compositor.zig): `Rect`
|
- [x] Pure, host-tested [compositor.zig](../../system/services/display/compositor.zig): `Rect`
|
||||||
(intersect/unite), `Surface`, `fillRect`, `composite` (opaque, clipped to a damage
|
(intersect/unite), `Surface`, `fillRect`, `composite` (opaque, clipped to a damage
|
||||||
rect), `blitTile`. `present` clears the damaged region to the wallpaper, paints the
|
rect), `blitTile`. `present` clears the damaged region to the wallpaper, paints the
|
||||||
visible layers bottom-to-top (z-sorted), and flushes just that rect back → front (WC).
|
visible layers bottom-to-top (z-sorted), and flushes just that rect back → front (WC).
|
||||||
@@ -148,10 +149,10 @@ still pass, and the default `zig build` is clean.
|
|||||||
- [x] The three integration cases exist and pass: `display` (D1 handoff, kernel),
|
- [x] The three integration cases exist and pass: `display` (D1 handoff, kernel),
|
||||||
`display-service` (D2/D3 compositor + self-check), and `display-demo` (D4 full
|
`display-service` (D2/D3 compositor + self-check), and `display-demo` (D4 full
|
||||||
pipeline: spawn `display` + `display-demo`, match `display-demo: ok`) —
|
pipeline: spawn `display` + `display-demo`, match `display-demo: ok`) —
|
||||||
[tests.zig](../system/kernel/tests.zig) + [qemu_test.py](../test/qemu_test.py). Plus
|
[tests.zig](../../system/kernel/tests.zig) + [qemu_test.py](../../test/qemu_test.py). Plus
|
||||||
the pure host tests (`zig build test`).
|
the pure host tests (`zig build test`).
|
||||||
- [x] [display.md](display.md) updated to the built state (the "Verifying it" section names
|
- [x] [display.md](display.md) updated to the built state (the "Verifying it" section names
|
||||||
the real cases); [README index](README.md) entry present (#19); the `display-track`
|
the real cases); [README index](../README.md) entry present (#19); the `display-track`
|
||||||
memory marked DONE with the commits.
|
memory marked DONE with the commits.
|
||||||
|
|
||||||
**Gate (met):** `python3 test/qemu_test.py display display-service display-demo` all pass,
|
**Gate (met):** `python3 test/qemu_test.py display display-service display-demo` all pass,
|
||||||
@@ -16,11 +16,13 @@ lands on its own and ends in a **verifiable gate** — shaped for a `/loop` run,
|
|||||||
|
|
||||||
## Conventions
|
## Conventions
|
||||||
|
|
||||||
Follow [coding-standards.md](coding-standards.md): spell out non-acronym abbreviations,
|
Follow [coding-standards.md](../coding-standards.md): spell out non-acronym abbreviations,
|
||||||
kebab-case file names, no `Co-Authored-By` trailers. New user binaries go through
|
kebab-case file names, no `Co-Authored-By` trailers. New user binaries go through
|
||||||
`addUserBinary` and get packed into the initial-ramdisk; protocols are
|
build-support's shared user-binary recipe and get packed into the initial-ramdisk;
|
||||||
`b.addModule("…-protocol", …)` imported into `runtime`; new syscalls extend
|
protocols are modules exported by the `library/protocol` package; new syscalls extend
|
||||||
[abi.zig](../system/abi.zig) `SystemCall` + a `library/runtime` wrapper.
|
[abi.zig](../../system/abi.zig) `SystemCall` + a `library/kernel` wrapper.
|
||||||
|
(This section predates the build-packages split; see
|
||||||
|
[build-packages-plan.md](../build-packages-plan.md) for the current build shape.)
|
||||||
|
|
||||||
## How to verify along the way
|
## How to verify along the way
|
||||||
|
|
||||||
@@ -59,7 +61,7 @@ is the only backend), and `zig build test` stays green.
|
|||||||
|
|
||||||
## V2 — The shared-memory cross-process capability (kernel) ✅
|
## V2 — The shared-memory cross-process capability (kernel) ✅
|
||||||
|
|
||||||
- [x] [abi.zig](../system/abi.zig): `shared_memory_create` (34) / `shared_memory_map` (35) syscalls + a
|
- [x] [abi.zig](../../system/abi.zig): `shared_memory_create` (34) / `shared_memory_map` (35) syscalls + a
|
||||||
`shared_memory_test` service id. Handlers in process.zig: `shared_memory_create(len)` allocates contiguous,
|
`shared_memory_test` service id. Handlers in process.zig: `shared_memory_create(len)` allocates contiguous,
|
||||||
zeroed, **cacheable** frames, wraps them in a refcounted object, installs a capability
|
zeroed, **cacheable** frames, wraps them in a refcounted object, installs a capability
|
||||||
handle, maps them into the caller's shared-memory arena → returns virtual_address + handle; `shared_memory_map(cap)`
|
handle, maps them into the caller's shared-memory arena → returns virtual_address + handle; `shared_memory_map(cap)`
|
||||||
@@ -144,4 +144,4 @@ path in VMs**, where danos development happens. The framebuffer floor never goes
|
|||||||
- [display.md](display.md) — v1: the compositor, the GOP-vs-device split, the WC discipline.
|
- [display.md](display.md) — v1: the compositor, the GOP-vs-device split, the WC discipline.
|
||||||
- [display-v2-plan.md](display-v2-plan.md) — the ordered build-out.
|
- [display-v2-plan.md](display-v2-plan.md) — the ordered build-out.
|
||||||
- [driver-model.md](driver-model.md) — claim / `mmio_map` / MSI / capability passing (M13).
|
- [driver-model.md](driver-model.md) — claim / `mmio_map` / MSI / capability passing (M13).
|
||||||
- [resilience.md](resilience.md) — the restart machinery the hot-attach leans on.
|
- [resilience.md](../os-development/resilience.md) — the restart machinery the hot-attach leans on.
|
||||||
@@ -1,12 +1,12 @@
|
|||||||
# The display service: a framebuffer compositor
|
# The display service: a framebuffer compositor
|
||||||
|
|
||||||
The [framebuffer](framebuffer.md) the loader hands over is a flat block of pixel
|
The [framebuffer](../os-development/framebuffer.md) the loader hands over is a flat block of pixel
|
||||||
memory, and the kernel's [bootstrap console](../system/kernel/console.zig) draws text
|
memory, and the kernel's [bootstrap console](../../system/kernel/console.zig) draws text
|
||||||
into it directly. That console is a stop-gap. The **display service**
|
into it directly. That console is a stop-gap. The **display service**
|
||||||
(`system/services/display/`) is the real thing: an ordinary ring-3 process that *owns*
|
(`system/services/display/`) is the real thing: an ordinary ring-3 process that *owns*
|
||||||
the framebuffer, composes a stack of **layers** into an off-screen back buffer, and
|
the framebuffer, composes a stack of **layers** into an off-screen back buffer, and
|
||||||
**presents** finished frames to the screen — the display half of the GUI track
|
**presents** finished frames to the screen — the display half of the GUI track
|
||||||
([vision.md](vision.md)), the sibling of the [input service](input.md).
|
([vision.md](../vision.md)), the sibling of the [input service](input.md).
|
||||||
|
|
||||||
This note is the architecture and the reasoning behind it. The concrete build order
|
This note is the architecture and the reasoning behind it. The concrete build order
|
||||||
lives in [display-plan.md](display-plan.md).
|
lives in [display-plan.md](display-plan.md).
|
||||||
@@ -20,20 +20,20 @@ which one you're holding decides what you can do.
|
|||||||
|
|
||||||
- **GOP is firmware's *temporary* driver** for the display controller. It gives you a
|
- **GOP is firmware's *temporary* driver** for the display controller. It gives you a
|
||||||
linear framebuffer pointer and can set video modes — but only until
|
linear framebuffer pointer and can set video modes — but only until
|
||||||
`ExitBootServices`. The loader already leans on this: [`queryFramebuffer`](../boot/efi.zig)
|
`ExitBootServices`. The loader already leans on this: [`queryFramebuffer`](../../boot/efi.zig)
|
||||||
reads the monitor's EDID, picks the native mode, and calls `set_mode` **before**
|
reads the monitor's EDID, picks the native mode, and calls `set_mode` **before**
|
||||||
exiting ([gop.md](gop.md)). Once the kernel runs, GOP is **gone** — no `set_mode`, no
|
exiting ([gop.md](../os-development/gop.md)). Once the kernel runs, GOP is **gone** — no `set_mode`, no
|
||||||
mode list, no EDID. What survives is the frozen snapshot in
|
mode list, no EDID. What survives is the frozen snapshot in
|
||||||
[`BootInformation.framebuffer`](../system/boot-handoff.zig): `{base, width, height,
|
[`BootInformation.framebuffer`](../../system/boot-handoff.zig): `{base, width, height,
|
||||||
pitch, format, refresh_hz}`, and nothing more.
|
pitch, format, refresh_hz}`, and nothing more.
|
||||||
|
|
||||||
- **The PCI class-0x03 device is the raw controller** — BARs, config space, registers,
|
- **The PCI class-0x03 device is the raw controller** — BARs, config space, registers,
|
||||||
IO ports. It is what you actually *own* after boot. On QEMU's emulated adapter
|
IO ports. It is what you actually *own* after boot. On QEMU's emulated adapter
|
||||||
([`-device VGA,edid=on`](../build.zig), the Bochs VBE/DISPI model) the `base` GOP handed
|
([`-device VGA,edid=on`](../../build/qemu.zig), the Bochs VBE/DISPI model) the `base` GOP handed
|
||||||
you *is* that device's linear-framebuffer BAR — the same physical memory, seen through
|
you *is* that device's linear-framebuffer BAR — the same physical memory, seen through
|
||||||
a different door. On a real discrete GPU, GOP's `base` is an aperture inside the GPU's
|
a different door. On a real discrete GPU, GOP's `base` is an aperture inside the GPU's
|
||||||
VRAM BAR. danos already decodes this device
|
VRAM BAR. danos already decodes this device
|
||||||
([pci-class.zig](../system/devices/pci-class.zig) has the full `display` namespace, and
|
([pci-class.zig](../../library/device/pci/pci-class.zig) has the full `display` namespace, and
|
||||||
`pci-bus` already reports it to the [device manager](device-manager.md) with its class
|
`pci-bus` already reports it to the [device manager](device-manager.md) with its class
|
||||||
triple) — but nothing binds it yet.
|
triple) — but nothing binds it yet.
|
||||||
|
|
||||||
@@ -63,16 +63,16 @@ rest of the system hasn't had to face:
|
|||||||
|
|
||||||
1. **The framebuffer is kernel-only today.** It arrives through the boot handoff, is
|
1. **The framebuffer is kernel-only today.** It arrives through the boot handoff, is
|
||||||
mapped into the kernel's physmap, and is touched only by
|
mapped into the kernel's physmap, and is touched only by
|
||||||
[`console.zig`](../system/kernel/console.zig). It is *not* a
|
[`console.zig`](../../system/kernel/console.zig). It is *not* a
|
||||||
[devices-broker](../system/kernel/devices-broker.zig) node, so
|
[devices-broker](../../system/kernel/devices-broker.zig) node, so
|
||||||
`device.claim`/`mmio_map` cannot reach it, and there is no framebuffer
|
`device.claim`/`mmio_map` cannot reach it, and there is no framebuffer
|
||||||
[syscall](syscall.md). A user-space display service needs a **new mechanism just to
|
[syscall](../os-development/syscall.md). A user-space display service needs a **new mechanism just to
|
||||||
touch the pixels**. (See "The handoff" below — this is built.)
|
touch the pixels**. (See "The handoff" below — this is built.)
|
||||||
|
|
||||||
2. **danos had no cross-process shared memory.** At v1 the memory syscalls were `mmap`
|
2. **danos had no cross-process shared memory.** At v1 the memory syscalls were `mmap`
|
||||||
(private, zeroed), `mmio_map` (a *claimed device's* MMIO), and `dma_alloc` (new
|
(private, zeroed), `mmio_map` (a *claimed device's* MMIO), and `dma_alloc` (new
|
||||||
pinned physical). The block driver's "pass a buffer by physical address" trick
|
pinned physical). The block driver's "pass a buffer by physical address" trick
|
||||||
([block/protocol.zig](../system/services/block/protocol.zig)) works *only because its
|
([block/protocol.zig](../../library/protocol/block/block-protocol.zig)) works *only because its
|
||||||
consumer is DMA hardware*. A compositor that CPU-reads and blends client layers can't
|
consumer is DMA hardware*. A compositor that CPU-reads and blends client layers can't
|
||||||
use it — it would have to *map* another process's memory, which nothing allowed. v1
|
use it — it would have to *map* another process's memory, which nothing allowed. v1
|
||||||
sidesteps it entirely (see "What v1 does not do"); v2 has since built the primitive
|
sidesteps it entirely (see "What v1 does not do"); v2 has since built the primitive
|
||||||
@@ -87,27 +87,29 @@ rest of the system hasn't had to face:
|
|||||||
│ (ResourceKind.memory = [base, height*pitch], write-combining hint,
|
│ (ResourceKind.memory = [base, height*pitch], write-combining hint,
|
||||||
│ plus DisplayInfo{width, height, pitch, format, refresh_hz})
|
│ 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)
|
│ device.claim(display node) → mmio_map(WRITE-COMBINING) = FRONT buffer (the LFB)
|
||||||
│ mmap(cacheable) a BACK buffer of the same geometry
|
│ mmap(cacheable) a BACK buffer of the same geometry
|
||||||
│ owns: an ordered LAYER STACK + a per-frame DAMAGE tracker (rect list or tile grid)
|
│ 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
|
│ 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)
|
│ 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)
|
drawing clients (v1) surface clients (deferred)
|
||||||
runtime.display commands: runtime.display surfaces:
|
display commands: display surfaces:
|
||||||
create_layer / configure_layer shared_memory_create → pass as a capability →
|
create_layer / configure_layer shared_memory_create → pass as a capability →
|
||||||
fill_rect / blit_tile / damage the compositor maps & composites the
|
fill_rect / blit_tile / damage the compositor maps & composites the
|
||||||
present client-rendered bitmap directly
|
present client-rendered bitmap directly
|
||||||
```
|
```
|
||||||
|
|
||||||
The bring-up sequence mirrors a hardware driver's — it is the
|
The bring-up sequence mirrors a hardware driver's — it is the
|
||||||
[`usb-xhci-bus` `initialise`](../system/drivers/usb-xhci-bus/usb-xhci-bus.zig) shape
|
[`usb-xhci-bus` `initialise`](../../system/drivers/usb-xhci-bus/usb-xhci-bus.zig) shape
|
||||||
(claim → `mmio_map` → run loop) — and the request/reply service shell is the
|
(claim → `mmio_map` → run loop) — and the request/reply service shell is the
|
||||||
[FAT](../system/services/fat/fat.zig) / [input](../system/services/input/input.zig) shape
|
[FAT](../../system/services/fat/fat.zig) / [input](../../system/services/input/input.zig) shape
|
||||||
([`runtime.service.run`](../library/runtime/service.zig) with a `protocol.zig` of
|
([`service.run`](../../library/kernel/service.zig) over the dispatch table its
|
||||||
`extern struct` messages and an `Operation` tag).
|
protocol module generates through
|
||||||
|
[`envelope.Define`](../os-development/protocol-namespace.md) — one request and
|
||||||
|
reply type per verb, and the layer id in the packet header's `target`).
|
||||||
|
|
||||||
**One process, for now.** v1 is a *single* service that both owns the framebuffer and
|
**One process, for now.** v1 is a *single* service that both owns the framebuffer and
|
||||||
composites — it does not split a "framebuffer driver" from a "compositor" the way input
|
composites — it does not split a "framebuffer driver" from a "compositor" the way input
|
||||||
@@ -119,12 +121,12 @@ second backend or a second monitor appears; until then it is complexity with no
|
|||||||
|
|
||||||
The framebuffer crosses into user space through the machinery that already exists for
|
The framebuffer crosses into user space through the machinery that already exists for
|
||||||
every other device, rather than a bespoke syscall — so it inherits ownership,
|
every other device, rather than a bespoke syscall — so it inherits ownership,
|
||||||
release-on-death, and re-claim-on-restart for free (the [resilience](resilience.md)
|
release-on-death, and re-claim-on-restart for free (the [resilience](../os-development/resilience.md)
|
||||||
story: a crashed display service returns the LFB to the kernel, and its restart
|
story: a crashed display service returns the LFB to the kernel, and its restart
|
||||||
re-claims it).
|
re-claims it).
|
||||||
|
|
||||||
- The kernel seeds a synthetic **display-class** node into the
|
- The kernel seeds a synthetic **display-class** node into the
|
||||||
[devices-broker](../system/kernel/devices-broker.zig) at init (`seedDisplay`), from
|
[devices-broker](../../system/kernel/devices-broker.zig) at init (`seedDisplay`), from
|
||||||
`BootInformation.framebuffer`: one `ResourceKind.memory` resource spanning
|
`BootInformation.framebuffer`: one `ResourceKind.memory` resource spanning
|
||||||
`[base, height*pitch]`, tagged **write-combining**, plus a small
|
`[base, height*pitch]`, tagged **write-combining**, plus a small
|
||||||
`DisplayInfo{width, height, pitch, format, refresh_hz}` (the memory resource says *where*
|
`DisplayInfo{width, height, pitch, format, refresh_hz}` (the memory resource says *where*
|
||||||
@@ -135,7 +137,7 @@ re-claims it).
|
|||||||
- The service `device.claim`s it and `mmio_map`s the resource. The map is
|
- The service `device.claim`s it and `mmio_map`s the resource. The map is
|
||||||
**write-combining**, not the strong-uncacheable that `mmio_map` uses for register
|
**write-combining**, not the strong-uncacheable that `mmio_map` uses for register
|
||||||
MMIO. The kernel already programs a WC PAT slot for its own console
|
MMIO. The kernel already programs a WC PAT slot for its own console
|
||||||
([`setupPat`](../system/kernel/architecture/x86_64/paging.zig)); this reaches it from
|
([`setupPat`](../../system/kernel/architecture/x86_64/paging.zig)); this reaches it from
|
||||||
the user mapping path. **This matters:** an uncacheable framebuffer makes the
|
the user mapping path. **This matters:** an uncacheable framebuffer makes the
|
||||||
back→front blit unusably slow.
|
back→front blit unusably slow.
|
||||||
- On `claim`, the kernel's bootstrap console goes quiet, so the two never fight over the
|
- On `claim`, the kernel's bootstrap console goes quiet, so the two never fight over the
|
||||||
@@ -143,7 +145,7 @@ re-claims it).
|
|||||||
panic on screen wins.
|
panic on screen wins.
|
||||||
|
|
||||||
The display service is a **named boot service**: `init` spawns it by name alongside
|
The display service is a **named boot service**: `init` spawns it by name alongside
|
||||||
`input`/`device-manager`/`fat` ([init.zig](../system/services/init/init.zig)), and it
|
`input`/`device-manager`/`fat` ([init.zig](../../system/services/init/init.zig)), and it
|
||||||
self-discovers the display node with `device.enumerate` (matching on `DeviceClass.display`). The [device manager](device-manager.md)
|
self-discovers the display node with `device.enumerate` (matching on `DeviceClass.display`). The [device manager](device-manager.md)
|
||||||
matching path (PCI class 0x03 → a driver) is reserved for the future *native* backend, not
|
matching path (PCI class 0x03 → a driver) is reserved for the future *native* backend, not
|
||||||
this singleton synthetic node.
|
this singleton synthetic node.
|
||||||
@@ -160,8 +162,8 @@ Two buffers, with deliberately different memory types:
|
|||||||
|
|
||||||
So a frame is: compose every dirty layer into the cacheable back buffer, then **present**
|
So a frame is: compose every dirty layer into the cacheable back buffer, then **present**
|
||||||
— copy the changed regions back→front in sequential, WC-friendly writes. Two details the
|
— copy the changed regions back→front in sequential, WC-friendly writes. Two details the
|
||||||
[framebuffer](framebuffer.md) note already establishes carry over: step rows by `pitch`,
|
[framebuffer](../os-development/framebuffer.md) note already establishes carry over: step rows by `pitch`,
|
||||||
not `width*4`; and handle both `rgbx` and `bgrx` [pixel formats](gop.md).
|
not `width*4`; and handle both `rgbx` and `bgrx` [pixel formats](../os-development/gop.md).
|
||||||
|
|
||||||
## Flicker vs. tearing — what double buffering does and doesn't buy
|
## Flicker vs. tearing — what double buffering does and doesn't buy
|
||||||
|
|
||||||
@@ -188,10 +190,10 @@ The compositor holds an **ordered stack of layers**. Each layer has a rectangle,
|
|||||||
z-order, a visibility flag, and a surface. Presenting walks the stack bottom-to-top,
|
z-order, a visibility flag, and a surface. Presenting walks the stack bottom-to-top,
|
||||||
painting each dirty layer into the back buffer, then flushes the damage to the front.
|
painting each dirty layer into the back buffer, then flushes the damage to the front.
|
||||||
Damage is tracked by one of two interchangeable trackers behind a compile-time
|
Damage is tracked by one of two interchangeable trackers behind a compile-time
|
||||||
`damage_mode` A/B switch ([display.zig](../system/services/display/display.zig)): a
|
`damage_mode` A/B switch ([display.zig](../../system/services/display/display.zig)): a
|
||||||
free-form dirty-rectangle **list** (tight bounds, heuristic merging) or a fixed 64-px
|
free-form dirty-rectangle **list** (tight bounds, heuristic merging) or a fixed 64-px
|
||||||
**tile grid** (exact O(1) merging, tile-quantized repaints) — the grid is the default;
|
**tile grid** (exact O(1) merging, tile-quantized repaints) — the grid is the default;
|
||||||
[compositor.zig](../system/services/display/compositor.zig) has both, with the trade-off
|
[compositor.zig](../../system/services/display/compositor.zig) has both, with the trade-off
|
||||||
discussion.
|
discussion.
|
||||||
|
|
||||||
In v1 the surfaces are **server-owned**, and clients draw into them with a small
|
In v1 the surfaces are **server-owned**, and clients draw into them with a small
|
||||||
@@ -209,8 +211,20 @@ shell, a terminal, a cursor, and a wallpaper:
|
|||||||
| `damage` | mark a region of a layer dirty |
|
| `damage` | mark a region of a layer dirty |
|
||||||
| `present` | request a repaint: composited at the next frame-clock tick |
|
| `present` | request a repaint: composited at the next frame-clock tick |
|
||||||
|
|
||||||
|
**A layer belongs to the client that created it.** The id is a slot in a
|
||||||
|
sixteen-entry table — small, dense, guessable — so every verb above that names one is
|
||||||
|
answered only for the task whose `create_layer` produced it, and a layer that is
|
||||||
|
somebody else's is refused exactly as one that never existed (`-ENOENT`), so a client
|
||||||
|
cannot use the refusal to learn which ids are live
|
||||||
|
([protocol-namespace.md](../os-development/protocol-namespace.md): handles are scoped
|
||||||
|
per client, validated against the badge). The compositor's own layers — the cursor
|
||||||
|
sprite and the startup self-check's pair — are marked service-owned and are created by
|
||||||
|
direct call rather than over the protocol, so no client can move or destroy the
|
||||||
|
cursor. A dead client's layers are released on its exit notification, the same sweep
|
||||||
|
the FAT server runs for open files.
|
||||||
|
|
||||||
Text is intentionally *not* an operation — a client renders glyphs by blitting tiles
|
Text is intentionally *not* an operation — a client renders glyphs by blitting tiles
|
||||||
(the [PSF font](../system/kernel/font.psf) path the console already uses can move into a
|
(the [PSF font](../../system/kernel/font.psf) path the console already uses can move into a
|
||||||
client). Keeping the protocol to rectangles and tiles keeps the compositor small and the
|
client). Keeping the protocol to rectangles and tiles keeps the compositor small and the
|
||||||
policy in the client.
|
policy in the client.
|
||||||
|
|
||||||
@@ -222,19 +236,19 @@ pacing on backends that have none (all of them today; see
|
|||||||
[display-v2.md](display-v2.md), "Fenced is not vsync"). Bring-up paths that must put
|
[display-v2.md](display-v2.md), "Fenced is not vsync"). Bring-up paths that must put
|
||||||
pixels on screen synchronously (initialisation, the self-checks) bypass the clock.
|
pixels on screen synchronously (initialisation, the self-checks) bypass the clock.
|
||||||
|
|
||||||
## `runtime.display`
|
## `display`
|
||||||
|
|
||||||
Clients speak the protocol through a new [`library/runtime/display.zig`](../library/runtime/runtime.zig),
|
Clients speak the protocol through a new [`library/client/display/display.zig`](../../library/client/display/display.zig),
|
||||||
the [`runtime.block`](../library/runtime/block.zig) shape (a cached `.display` lookup
|
the [`block`](../../library/device/block/block.zig) shape (a cached `.display` lookup
|
||||||
with a boot-race retry): `display.info()`, a `Layer` handle with `fill` / `blitTile` /
|
with a boot-race retry): `display.info()`, a `Layer` handle with `fill` / `blitTile` /
|
||||||
`damage`, and `present()`. Application code never issues the raw syscalls — it calls the
|
`damage`, and `present()`. Application code never issues the raw syscalls — it calls the
|
||||||
runtime, as with every other danos service.
|
client module, as with every other danos service.
|
||||||
|
|
||||||
## The cursor: a mouse-listener thread feeding the compositor
|
## The cursor: a mouse-listener thread feeding the compositor
|
||||||
|
|
||||||
The compositor is the single owner of the framebuffer — only the main `service.run` loop
|
The compositor is the single owner of the framebuffer — only the main `service.run` loop
|
||||||
touches the backend and the layer stack. Tracking the mouse without breaking that
|
touches the backend and the layer stack. Tracking the mouse without breaking that
|
||||||
ownership is the display's first use of [threads](threading.md): the service is built
|
ownership is the display's first use of [threads](../os-development/threading.md): the service is built
|
||||||
multi-threaded (`addThreadedUserBinary`) and, at startup, spawns a **mouse-listener
|
multi-threaded (`addThreadedUserBinary`) and, at startup, spawns a **mouse-listener
|
||||||
thread** beside the compositor loop.
|
thread** beside the compositor loop.
|
||||||
|
|
||||||
@@ -242,9 +256,9 @@ thread** beside the compositor loop.
|
|||||||
(`input.subscribeMouse()`), accumulates the relative `dx`/`dy` motion into an absolute
|
(`input.subscribeMouse()`), accumulates the relative `dx`/`dy` motion into an absolute
|
||||||
cursor position clamped to the screen, and hands it to the compositor. It never touches
|
cursor position clamped to the screen, and hands it to the compositor. It never touches
|
||||||
the compositor — so no lock guards the framebuffer. A parked `next()` leaves its core
|
the compositor — so no lock guards the framebuffer. A parked `next()` leaves its core
|
||||||
free to halt ([halting.md](halting.md)).
|
free to halt ([halting.md](../os-development/halting.md)).
|
||||||
- **The channel.** A single-slot *latest-value* cell (`CursorChannel`) guarded by a
|
- **The channel.** A single-slot *latest-value* cell (`CursorChannel`) guarded by a
|
||||||
`runtime.Thread.Mutex`: the renderer wants where the cursor *is now*, not a replay of
|
`Thread.Mutex`: the renderer wants where the cursor *is now*, not a replay of
|
||||||
every delta, so a new position overwrites the old. The listener also **pokes** the
|
every delta, so a new position overwrites the old. The listener also **pokes** the
|
||||||
compositor awake — the main loop is parked in `replyWait`, so the listener posts a
|
compositor awake — the main loop is parked in `replyWait`, so the listener posts a
|
||||||
zero-payload `ipc.send` to the compositor's endpoint, which arrives as a
|
zero-payload `ipc.send` to the compositor's endpoint, which arrives as a
|
||||||
@@ -254,13 +268,13 @@ thread** beside the compositor loop.
|
|||||||
which is just a top-z compositor layer — with the existing `configure` + `present` path
|
which is just a top-z compositor layer — with the existing `configure` + `present` path
|
||||||
(it damages the old and new footprints, so only those two rectangles repaint).
|
(it damages the old and new footprints, so only those two rectangles repaint).
|
||||||
|
|
||||||
Two threading facts shape this (both in [threading.md](threading.md)). IPC **handles do
|
Two threading facts shape this (both in [threading.md](../os-development/threading.md)). IPC **handles do
|
||||||
not cross threads**, so the listener can't reuse the main loop's endpoint handle — it
|
not cross threads**, so the listener can't reuse the main loop's endpoint handle — it
|
||||||
`ipc.lookup(.display)`s its *own* handle to the same endpoint to poke through. And a
|
`ipc.lookup(.display)`s its *own* handle to the same endpoint to poke through. And a
|
||||||
multi-threaded service doing concurrent IPC is why the kernel's endpoint-create / register
|
multi-threaded service doing concurrent IPC is why the kernel's endpoint-create / register
|
||||||
/ lookup syscalls now serialize under the big kernel lock. Shared fate applies: a fault in
|
/ lookup syscalls now serialize under the big kernel lock. Shared fate applies: a fault in
|
||||||
the listener takes the whole display down, and the supervisor restarts the process
|
the listener takes the whole display down, and the supervisor restarts the process
|
||||||
([resilience.md](resilience.md)).
|
([resilience.md](../os-development/resilience.md)).
|
||||||
|
|
||||||
## What v1 does not do (and why that's fine)
|
## What v1 does not do (and why that's fine)
|
||||||
|
|
||||||
@@ -284,7 +298,7 @@ both are clean additions behind the interfaces v1 establishes.
|
|||||||
|
|
||||||
## Verifying it
|
## Verifying it
|
||||||
|
|
||||||
Four QEMU test cases ([tests.zig](../system/kernel/tests.zig), `python3
|
Four QEMU test cases ([tests.zig](../../system/kernel/tests.zig), `python3
|
||||||
test/qemu_test.py <case>`), each layering on the last:
|
test/qemu_test.py <case>`), each layering on the last:
|
||||||
|
|
||||||
- **`display`** — the kernel handoff: the seeded `display` device is shaped correctly and
|
- **`display`** — the kernel handoff: the seeded `display` device is shaped correctly and
|
||||||
@@ -297,7 +311,7 @@ test/qemu_test.py <case>`), each layering on the last:
|
|||||||
layer — logging `display: compositor self-check ok`.
|
layer — logging `display: compositor self-check ok`.
|
||||||
- **`display-demo`** — the full pipeline from a separate process: the hardware-free
|
- **`display-demo`** — the full pipeline from a separate process: the hardware-free
|
||||||
[`display-demo`](../system/services/display-demo/) client (the
|
[`display-demo`](../system/services/display-demo/) client (the
|
||||||
[`input-source`](../system/services/input-source/) analog) drives layers — a wallpaper and
|
[`input-source`](../test/system/services/input-source/) analog) drives layers — a wallpaper and
|
||||||
a sliding rectangle — through the layer client API and heartbeats
|
a sliding rectangle — through the layer client API and heartbeats
|
||||||
`display-demo: ok`, proving a frame travelled client → compositor → screen, exactly as
|
`display-demo: ok`, proving a frame travelled client → compositor → screen, exactly as
|
||||||
the [input test](input.md) proves an event travels source → service → subscriber. It draws
|
the [input test](input.md) proves an event travels source → service → subscriber. It draws
|
||||||
@@ -317,8 +331,8 @@ packing are additionally covered by pure host unit tests under `zig build test`.
|
|||||||
|
|
||||||
## See also
|
## See also
|
||||||
|
|
||||||
- [framebuffer.md](framebuffer.md) — the linear framebuffer, pitch vs. width, `volatile`.
|
- [framebuffer.md](../os-development/framebuffer.md) — the linear framebuffer, pitch vs. width, `volatile`.
|
||||||
- [gop.md](gop.md) — GOP, and why only linear RGBX/BGRX modes are paintable.
|
- [gop.md](../os-development/gop.md) — GOP, and why only linear RGBX/BGRX modes are paintable.
|
||||||
- [input.md](input.md) — the sibling service; the async `ipc_send` fan-out.
|
- [input.md](input.md) — the sibling service; the async `ipc_send` fan-out.
|
||||||
- [driver-model.md](driver-model.md) — claim / `mmio_map`, capability passing, the trust model.
|
- [driver-model.md](driver-model.md) — claim / `mmio_map`, capability passing, the trust model.
|
||||||
- [device-manager.md](device-manager.md) — matching and supervision (the native backend's route).
|
- [device-manager.md](device-manager.md) — matching and supervision (the native backend's route).
|
||||||
@@ -34,7 +34,7 @@ plain bus driver with no controller — a USB hub — is also a real thing.
|
|||||||
|
|
||||||
danos already has the right central structure. `system/kernel/devices-broker.zig` holds a table of
|
danos already has the right central structure. `system/kernel/devices-broker.zig` holds a table of
|
||||||
`DeviceDescriptor`, each with a parent, a class, and a set of resources. Firmware discovery
|
`DeviceDescriptor`, each with a parent, a class, and a set of resources. Firmware discovery
|
||||||
seeds it ([discovery.md](discovery.md)); `device_register` grows it.
|
seeds it ([discovery.md](../os-development/discovery.md)); `device_register` grows it.
|
||||||
|
|
||||||
Three invariants make it a capability system rather than a directory:
|
Three invariants make it a capability system rather than a directory:
|
||||||
|
|
||||||
@@ -95,40 +95,66 @@ A "family" is two modules, not one:
|
|||||||
- **A protocol module** — the IPC message types that let a class driver talk to
|
- **A protocol module** — the IPC message types that let a class driver talk to
|
||||||
*whatever* published its device. This is the part that makes class drivers portable.
|
*whatever* published its device. This is the part that makes class drivers portable.
|
||||||
|
|
||||||
danos already has one of each: `library/runtime/device.zig` is a logic module,
|
danos already has one of each: `library/device/pci/pci.zig` is a logic module (the
|
||||||
[`system/vfs-protocol.zig`](system/vfs-protocol.zig) is a protocol module shared by the
|
`Function` view of a claimed PCI function),
|
||||||
mount backends (today the fat server) and their clients. (The user-space VFS server it
|
[`library/protocol/vfs/vfs-protocol.zig`](../../library/protocol/vfs/vfs-protocol.zig) is a
|
||||||
was originally written against has since retired — path routing moved into the kernel,
|
protocol module shared by the mount backends (today the fat server) and their clients.
|
||||||
`system/kernel/vfs.zig`'s `fs_resolve` — but the protocol module outlived it, which is
|
(The user-space VFS server it was originally written against has since retired — path
|
||||||
rather the point.) The pattern generalises directly:
|
routing moved into the kernel, `system/kernel/vfs.zig`'s `fs_resolve` — but the protocol
|
||||||
|
module outlived it, which is rather the point.) The pattern generalises directly:
|
||||||
|
|
||||||
```
|
```
|
||||||
library/
|
library/
|
||||||
runtime/ module "runtime" — syscalls, heap, ipc, device, stdio
|
kernel/ the system library (kernel32-style): the syscall surface split by concern
|
||||||
mmio/ module "mmio" — volatile register access + barriers [M14]
|
— ipc, memory (heap/dma/shared-memory), process, time, logging,
|
||||||
bus/
|
file-system, thread, service, plus system-call stubs + start/root
|
||||||
pci/ module "pci" — ECAM, BAR decode, capability walk
|
device/ device code grouped by domain; each domain splits into a shareable
|
||||||
usb/ module "usb" — descriptors, control transfers, hubs
|
data module (enums/wire types, std-only) and a logic module (mmio/IPC)
|
||||||
proto/
|
mmio/ module "mmio" — typed volatile register access + barriers [M14]
|
||||||
vfs/ module "vfs-protocol" (today: system/vfs-protocol.zig)
|
model/ module "device-abi" — DeviceDescriptor, DeviceClass, ResourceKind
|
||||||
block/ module "block-protocol"
|
pci/ "pci-class" (data) + "pci" — config/BAR/capability walk (Function)
|
||||||
hid/ module "hid-protocol"
|
usb/ "usb-abi" + "usb-ids" (data) + "usb" — descriptors, control/interrupt/bulk client
|
||||||
|
acpi/ "acpi-ids" (data) + "aml" — _HID names, the AML interpreter
|
||||||
|
driver/ module "driver" — device-access syscalls + device-manager hello
|
||||||
|
block/ module "block" — the block-device client (a device type)
|
||||||
|
client/ userspace service clients — display, input (a program's view of a service)
|
||||||
|
protocol/ driver <-> service wire contracts, one module per directory
|
||||||
|
vfs/ block/ display/ scanout/ input/ power/ device-manager/ usb-transfer/
|
||||||
|
|
||||||
system/drivers/ one sub-project each → /system/drivers (no `d` suffix)
|
system/drivers/ one sub-project each → /system/drivers (no `d` suffix)
|
||||||
xhci/ HCD + bus driver imports runtime, pci, usb, mmio
|
usb-xhci-bus/ HCD + bus driver imports usb, mmio, usb-transfer-protocol (+ kernel modules)
|
||||||
usb-hid/ class driver imports runtime, usb, hid-protocol
|
usb-hid/ class driver imports usb, input-protocol (+ kernel modules)
|
||||||
block/ class driver imports runtime, block-protocol
|
virtio-gpu/ scanout driver imports pci, mmio, display-/scanout-protocol (+ kernel modules)
|
||||||
```
|
```
|
||||||
|
|
||||||
The build side of this has since landed: [`addUserBinary`](build.zig) injects the
|
The split by *dependency weight* is what lets the microkernel stay out of device
|
||||||
default modules (`runtime`, `mmio`, `xkeyboard-config`, `acpi-ids`) into every user
|
business: it imports only the `device-abi` data module (the descriptor types its broker
|
||||||
binary, and per-binary extras — protocol modules, bus logic — are added with
|
marshals across the syscall boundary) — never a logic module, never a taxonomy. That one
|
||||||
`programModule(exe).addImport(...)`. That's the *entire* mechanism — Zig modules
|
pure-data import is the only edge from `system/kernel/` into `library/`; decoding a class
|
||||||
already give you everything else.
|
code or `_HID` to a name is user space's job (the device manager owns those taxonomies).
|
||||||
|
|
||||||
The discipline that makes this work: **a class driver must not import a bus's logic
|
A protocol lives in `library/protocol/` when it is the seam between a low-level driver and
|
||||||
module.** `usbhid` imports `proto.hid` and `usb` (for descriptor types), never `pci`.
|
a higher-level service (block ↔ filesystem, a scanout driver ↔ the compositor). A driver's
|
||||||
If a class driver needs `mmio`, it has become an HCD and should be one.
|
private wire to its *hardware* — virtio-gpu's command set — is not that; it stays a
|
||||||
|
driver-private file, like the virtio-pci transport beside it.
|
||||||
|
|
||||||
|
The build side of this has since landed: every binary owns a package whose
|
||||||
|
~15-line `build.zig` names EXACTLY the modules its source imports — the moral
|
||||||
|
equivalent of a C file's include list — and the shared recipe in
|
||||||
|
[`build-support/build.zig`](../../build-support/build.zig) (`userBinary`)
|
||||||
|
resolves each name from the library domain that exports it (kernel's concern
|
||||||
|
modules, the device driver libraries, the service clients, the protocols). An
|
||||||
|
undeclared `@import` is a compile error, and a domain none of the imports come
|
||||||
|
from never appears in the binary's manifest — a keyboard driver declares
|
||||||
|
`xkeyboard-config`; nothing else does (see
|
||||||
|
[build-packages-plan.md](../build-packages-plan.md)). That's the *entire*
|
||||||
|
mechanism — Zig modules already give you everything else.
|
||||||
|
|
||||||
|
The discipline that makes this work: **a class driver must not import a bus's *hardware*
|
||||||
|
logic module.** `usb-hid` imports `usb` (the transfer client) and `input-protocol`, never
|
||||||
|
`pci` and never `mmio`. If a class driver needs `mmio`, it has become an HCD and should be
|
||||||
|
one. The domain data modules (`usb-abi`, `usb-ids`, `pci-class`) carry no such weight — a
|
||||||
|
class driver, the device manager, or the kernel may share them freely.
|
||||||
|
|
||||||
## What exists today
|
## What exists today
|
||||||
|
|
||||||
@@ -141,16 +167,16 @@ If a class driver needs `mmio`, it has become an HCD and should be one.
|
|||||||
and a `received_cap` return (r8): an endpoint travels with a message, installed into
|
and a `received_cap` return (r8): an endpoint travels with a message, installed into
|
||||||
the receiver's handle table (shared, refcount-bumped — a copy, not a move). A full
|
the receiver's handle table (shared, refcount-bumped — a copy, not a move). A full
|
||||||
table fails `-ENOSPC` and does not half-deliver. This is the "open" primitive — a bus
|
table fails `-ENOSPC` and does not half-deliver. This is the "open" primitive — a bus
|
||||||
driver mints a per-device endpoint and hands it to a class driver. The runtime exposes
|
driver mints a per-device endpoint and hands it to a class driver. The `ipc` module
|
||||||
`callCap` and `replyWait(..., send_cap)`, and class drivers consume them now: the
|
exposes `callCap` and `replyWait(..., send_cap)`, and class drivers consume them now: the
|
||||||
PS/2 keyboard and mouse drivers attach to ps2-bus this way, and `runtime.usb` /
|
PS/2 keyboard and mouse drivers attach to ps2-bus this way, and the `usb` / `input`
|
||||||
`runtime.input` open their per-device and subscription channels with `callCap`.
|
client modules open their per-device and subscription channels with `callCap`.
|
||||||
- **M14** — DMA memory + the memory-ordering layer. `/lib/mmio` gives drivers typed
|
- **M14** — DMA memory + the memory-ordering layer. `/lib/device/mmio` gives drivers typed
|
||||||
volatile access and `mb`/`rmb`/`wmb` (per-arch); `dma_alloc`/`dma_free` grant
|
volatile access and `memoryBarrier`/`readMemoryBarrier`/`writeMemoryBarrier` (per-arch); `dma_alloc`/`dma_free` grant
|
||||||
physically-contiguous, pinned, uncacheable, reclaim-on-teardown buffers with the
|
physically-contiguous, pinned, uncacheable, reclaim-on-teardown buffers with the
|
||||||
physical address exposed (`pmm.allocContiguous`, a DMA arena, `mapUserDmaInto`).
|
physical address exposed (`pmm.allocContiguous`, a DMA arena, `mapUserDmaInto`).
|
||||||
`dma_below_4g` caps the address for legacy engines; `dma_write_combining` is accepted
|
`dma_below_4g` caps the address for legacy engines; `dma_write_combining` is accepted
|
||||||
but falls back to coherent until PAT is programmed. The bus drivers use `/lib/mmio`,
|
but falls back to coherent until PAT is programmed. The bus drivers use `/lib/device/mmio`,
|
||||||
and `dma_alloc` has real consumers now: the xHCI driver's rings and contexts,
|
and `dma_alloc` has real consumers now: the xHCI driver's rings and contexts,
|
||||||
usb-storage's command/status wrappers, virtio-gpu's virtqueue, and the fat
|
usb-storage's command/status wrappers, virtio-gpu's virtqueue, and the fat
|
||||||
service's bounce buffer.
|
service's bounce buffer.
|
||||||
@@ -167,17 +193,19 @@ If a class driver needs `mmio`, it has become an HCD and should be one.
|
|||||||
a PS/2 or 16550 driver possible; the low-rate legacy hardware that needs it is fine with
|
a PS/2 or 16550 driver possible; the low-rate legacy hardware that needs it is fine with
|
||||||
a syscall per access. `io_port` resources were recorded by discovery and ignored — now
|
a syscall per access. `io_port` resources were recorded by discovery and ignored — now
|
||||||
they're used.
|
they're used.
|
||||||
- **M16 (detection)** — the IOMMU is now *found*: discovery parses the ACPI DMAR table,
|
- **M16 (enforcement)** — the IOMMU is now *found and used*: discovery parses the ACPI
|
||||||
maps the first VT-d unit, and reads its version + capabilities (`iommu_present` in the
|
DMAR table, maps the first VT-d unit, and reads its version + capabilities
|
||||||
platform info). This is detection only — **no translation domains are programmed, so
|
(`iommu_present` in the platform info), and **`device_claim` programs a private
|
||||||
DMA is still unprotected** (the caveat below). Enforcement lands with the first DMA
|
per-device translation domain** for the claimed function — rolling the claim back with
|
||||||
driver, which is what there is to protect and test against. Proven in the `iommu` test,
|
`-ECONFINE` if it cannot confine it — so `dma_alloc` buffers are bound into that domain
|
||||||
booted with an emulated `intel-iommu`.
|
and torn down at process death. DMA is protected on any IOMMU-equipped machine; the
|
||||||
|
system fails open only when there is no IOMMU at all. Proven in the `iommu` test, booted
|
||||||
|
with an emulated `intel-iommu`.
|
||||||
- **`system_spawn`** — a user-space supervisor starts a driver:
|
- **`system_spawn`** — a user-space supervisor starts a driver:
|
||||||
`system_spawn(name, arguments)` loads a binary bundled in the initial-ramdisk as a
|
`system_spawn(name, arguments)` loads a binary bundled in the initial-ramdisk as a
|
||||||
fresh ring-3 process; `name` becomes the child's argv[0] and the optional
|
fresh ring-3 process; `name` becomes the child's argv[0] and the optional
|
||||||
NUL-separated `arguments` blob its argv[1..], delivered on a SysV entry stack
|
NUL-separated `arguments` blob its argv[1..], delivered on a SysV entry stack
|
||||||
([sysv.md](sysv.md)). This is what
|
([sysv.md](../os-development/sysv.md)). This is what
|
||||||
turned the device manager from "log the match" into "run the driver": the kernel now
|
turned the device manager from "log the match" into "run the driver": the kernel now
|
||||||
spawns only `init`, `init` spawns the services, and the **device-manager** discovers
|
spawns only `init`, `init` spawns the services, and the **device-manager** discovers
|
||||||
the hardware and spawns each driver ([drivers.md](drivers.md)). Ungated for now — a
|
the hardware and spawns each driver ([drivers.md](drivers.md)). Ungated for now — a
|
||||||
@@ -237,7 +265,7 @@ const dev_ep = ipc.callCap(h, // ... mint a per-device endpoint,
|
|||||||
|
|
||||||
## M14 — DMA memory and the memory-ordering contract, for HCDs ✅ done
|
## M14 — DMA memory and the memory-ordering contract, for HCDs ✅ done
|
||||||
|
|
||||||
*Implemented: `/lib/mmio` (typed volatile access + `mb`/`rmb`/`wmb`, per-arch) and
|
*Implemented: `/lib/device/mmio` (typed volatile access + `memoryBarrier`/`readMemoryBarrier`/`writeMemoryBarrier`, per-arch) and
|
||||||
`dma_alloc`/`dma_free` (contiguous, pinned, uncacheable, reclaim-on-teardown, physical
|
`dma_alloc`/`dma_free` (contiguous, pinned, uncacheable, reclaim-on-teardown, physical
|
||||||
address exposed). `dma_write_combining` still falls back to coherent — real WC needs
|
address exposed). `dma_write_combining` still falls back to coherent — real WC needs
|
||||||
PAT, a small follow-up. The rest of this section is the original design note.*
|
PAT, a small follow-up. The rest of this section is the original design note.*
|
||||||
@@ -279,31 +307,31 @@ doorbell.* = i; // volatile store to UC MMIO
|
|||||||
// nothing stops the compiler reordering these; the device reads a stale descriptor
|
// nothing stops the compiler reordering these; the device reads a stale descriptor
|
||||||
```
|
```
|
||||||
|
|
||||||
So the rules, which belong in `library/mmio.zig` and behind `arch`:
|
So the rules, which belong in `library/device/mmio/mmio.zig` and behind `arch`:
|
||||||
|
|
||||||
| Situation | Required |
|
| Situation | Required |
|
||||||
|---|---|
|
|---|---|
|
||||||
| MMIO register read/write | `mmio.read` / `mmio.write` (volatile) |
|
| MMIO register read/write | `mmio.read` / `mmio.write` (volatile) |
|
||||||
| Fill DMA descriptor, then ring doorbell | `wmb()` between them |
|
| Fill DMA descriptor, then ring doorbell | `writeMemoryBarrier()` between them |
|
||||||
| Woken by IRQ, then read what the device wrote | `rmb()` before the read |
|
| Woken by IRQ, then read what the device wrote | `readMemoryBarrier()` before the read |
|
||||||
| MMIO write that must complete before the next read | `mb()` |
|
| MMIO write that must complete before the next read | `memoryBarrier()` |
|
||||||
|
|
||||||
And the per-arch lowering — the reason this must be an `arch` primitive and not a
|
And the per-arch lowering — the reason this must be an `arch` primitive and not a
|
||||||
sprinkling of `asm volatile`:
|
sprinkling of `asm volatile`:
|
||||||
|
|
||||||
| | x86_64 | aarch64 |
|
| | x86_64 | aarch64 |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `mb()` | `mfence` | `dsb sy` |
|
| `memoryBarrier()` | `mfence` | `dsb sy` |
|
||||||
| `rmb()` | `lfence` | `dsb ld` |
|
| `readMemoryBarrier()` | `lfence` | `dsb ld` |
|
||||||
| `wmb()` | `sfence` | `dsb st` |
|
| `writeMemoryBarrier()` | `sfence` | `dsb st` |
|
||||||
| DMA cache coherency | coherent; nothing to do | **not guaranteed**; needs non-cacheable buffers or cache maintenance |
|
| DMA cache coherency | coherent; nothing to do | **not guaranteed**; needs non-cacheable buffers or cache maintenance |
|
||||||
|
|
||||||
x86 is forgiving here — TSO plus strong-uncacheable MMIO means you usually get away
|
x86 is forgiving here — TSO plus strong-uncacheable MMIO means you usually get away
|
||||||
with a compiler barrier alone. ARM is not, and [vision.md](vision.md) makes ARM the win
|
with a compiler barrier alone. ARM is not, and [vision.md](../vision.md) makes ARM the win
|
||||||
condition. Build the abstraction while there is one caller to fix.
|
condition. Build the abstraction while there is one caller to fix.
|
||||||
|
|
||||||
(Zig note: `@fence` was **removed in 0.16**. Use `@atomicRmw(..., .seq_cst)` for a full
|
(Zig note: `@fence` was **removed in 0.16**. Use `@atomicRmw(..., .seq_cst)` for a full
|
||||||
barrier, or per-arch inline asm — which is what `library/mmio.zig` should hide.)
|
barrier, or per-arch inline asm — which is what `library/device/mmio/mmio.zig` should hide.)
|
||||||
|
|
||||||
## M15 — interrupts for PCI devices ✅ done (MSI)
|
## M15 — interrupts for PCI devices ✅ done (MSI)
|
||||||
|
|
||||||
@@ -343,25 +371,29 @@ capability walk (MSI, MSI-X, PCIe extended caps) without any new syscall.
|
|||||||
Note QEMU's HPET reports `Tn_FSB_INT_DEL_CAP = 0` — no MSI — so an HPET timer could never
|
Note QEMU's HPET reports `Tn_FSB_INT_DEL_CAP = 0` — no MSI — so an HPET timer could never
|
||||||
exercise this path. The first MSI driver will be the first PCI driver.
|
exercise this path. The first MSI driver will be the first PCI driver.
|
||||||
|
|
||||||
## M16 — the IOMMU, and the honest caveat ◑ detection done, enforcement pending
|
## M16 — the IOMMU, and the honest caveat ✅ done
|
||||||
|
|
||||||
*The IOMMU is now detected (DMAR parsed, VT-d unit mapped and read — see the `iommu`
|
*The IOMMU is now detected (DMAR parsed, VT-d unit mapped and read — see the `iommu`
|
||||||
test), but **enforcement is not built**: no translation domains are programmed, so the
|
test) **and enforced**: `device_claim` programs a private per-device VT-d/AMD-Vi
|
||||||
caveat below still holds in full. Detection can't be taken further usefully until there
|
translation domain for the claimed function and rolls the claim back with `-ECONFINE` if
|
||||||
is a DMA driver to protect and QEMU's `intel-iommu` to test the protection against —
|
it cannot confine it, `dma_alloc` buffers are bound into that domain and torn down at
|
||||||
building the per-device domains alongside that first driver is both the natural order
|
process death, and the machine fails open only when it has no IOMMU at all. So the caveat
|
||||||
and the only way to verify them. The rest of this section is the original caveat.*
|
below no longer holds except on IOMMU-less hardware. The rest of this section is the
|
||||||
|
original caveat, kept for the reasoning.*
|
||||||
|
|
||||||
Everything above is capability-gated at the *CPU*. None of it is gated at the *device*.
|
Everything above is capability-gated at the *CPU*. CPU page tables alone do not gate the
|
||||||
A driver that can program a bus-mastering engine can make that device write to any
|
*device*: a driver that can program a bus-mastering engine could make that device write to
|
||||||
physical address, because page tables sit between the CPU and RAM, not between a device
|
any physical address, because those page tables sit between the CPU and RAM, not between a
|
||||||
and RAM. Until VT-d/DMAR (or SMMU on ARM) is programmed from the DMAR table, **`device_claim`
|
device and RAM. That is exactly what the IOMMU closes. Now that VT-d/DMAR (and AMD-Vi; SMMU
|
||||||
on any DMA-capable device is equivalent to granting ring 0.**
|
on ARM) is programmed, **`device_claim` confines the function into a private translation
|
||||||
|
domain** and rolls the claim back with `-ECONFINE` if it cannot — so a claimed DMA-capable
|
||||||
|
device is no longer equivalent to granting ring 0.
|
||||||
|
|
||||||
This does not make the model useless — it's the same position Linux is in with the
|
This puts the model ahead of Linux-with-the-IOMMU-off: with an IOMMU present,
|
||||||
IOMMU off, and every other guarantee (crash isolation, restart, no shared address
|
"user-space drivers are memory-safe" now holds, alongside every other guarantee (crash
|
||||||
space) still holds. But "user-space drivers are memory-safe" is not true yet, and the
|
isolation, restart, no shared address space). The one remaining gap — a machine with no
|
||||||
gap should be named rather than implied.
|
IOMMU at all, where the system deliberately fails open — should be named rather than
|
||||||
|
implied.
|
||||||
|
|
||||||
## Ordering
|
## Ordering
|
||||||
|
|
||||||
@@ -376,6 +408,6 @@ from hand-rolling `*volatile` and getting ARM wrong.
|
|||||||
## See also
|
## See also
|
||||||
|
|
||||||
- [drivers.md](drivers.md) — how to write one, concretely.
|
- [drivers.md](drivers.md) — how to write one, concretely.
|
||||||
- [discovery.md](discovery.md) / [acpi.md](acpi.md) — where the device table comes from.
|
- [discovery.md](../os-development/discovery.md) / [acpi.md](../os-development/acpi.md) — where the device table comes from.
|
||||||
- [ipc.md](ipc.md) — endpoints, badges, and the notification path an IRQ arrives on.
|
- [ipc.md](ipc.md) — endpoints, badges, and the notification path an IRQ arrives on.
|
||||||
- [resilience.md](resilience.md) — restart, the reason any of this is worth the trouble.
|
- [resilience.md](../os-development/resilience.md) — restart, the reason any of this is worth the trouble.
|
||||||
@@ -4,13 +4,13 @@ In a monolithic kernel a driver is a function call away from everything: it runs
|
|||||||
ring 0, dereferences any physical address, and its interrupt handler *is* the ISR. In
|
ring 0, dereferences any physical address, and its interrupt handler *is* the ISR. In
|
||||||
danos a driver is **an ordinary ring-3 process**. It has its own address space, it
|
danos a driver is **an ordinary ring-3 process**. It has its own address space, it
|
||||||
can crash without taking the kernel with it, and — the point of this document — it
|
can crash without taking the kernel with it, and — the point of this document — it
|
||||||
can be restarted ([resilience](resilience.md)).
|
can be restarted ([resilience](../os-development/resilience.md)).
|
||||||
|
|
||||||
That leaves three questions the kernel has to answer, because a process can't answer
|
That leaves three questions the kernel has to answer, because a process can't answer
|
||||||
them for itself:
|
them for itself:
|
||||||
|
|
||||||
1. **What hardware exists?** → `device_enumerate`, over the device table discovery built
|
1. **What hardware exists?** → `device_enumerate`, over the device table discovery built
|
||||||
([discovery](discovery.md), [acpi](acpi.md)).
|
([discovery](../os-development/discovery.md), [acpi](../os-development/acpi.md)).
|
||||||
2. **How do I touch its registers?** → `device_claim` + `mmio_map`: the kernel maps the
|
2. **How do I touch its registers?** → `device_claim` + `mmio_map`: the kernel maps the
|
||||||
device's physical MMIO window into your address space, and from then on it's plain
|
device's physical MMIO window into your address space, and from then on it's plain
|
||||||
memory. No syscall per register access.
|
memory. No syscall per register access.
|
||||||
@@ -32,7 +32,7 @@ kernel ──spawns──► init (PID 1) ──spawns──► device-manag
|
|||||||
spawns only init, the service supervisor: the driver supervisor: enumerates
|
spawns only init, the service supervisor: the driver supervisor: enumerates
|
||||||
publishes the starts the system /system/devices, matches each device
|
publishes the starts the system /system/devices, matches each device
|
||||||
initial-ramdisk services (device-manager, to a driver, and system_spawn's it
|
initial-ramdisk services (device-manager, to a driver, and system_spawn's it
|
||||||
so user space can fat, logger, ...). Its
|
so user space can volume-manager, logger, ...). Its
|
||||||
system_spawn from it list is init policy.
|
system_spawn from it list is init policy.
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -43,7 +43,7 @@ the optional arguments its argv[1..], on a SysV entry stack, see sysv.md). Every
|
|||||||
|
|
||||||
- **init** ([system/services/init](system/services/init/init.zig)) is the **service
|
- **init** ([system/services/init](system/services/init/init.zig)) is the **service
|
||||||
supervisor**. It spawns the system services danos brings up at boot — today `input`,
|
supervisor**. It spawns the system services danos brings up at boot — today `input`,
|
||||||
the `device-manager`, `fat`, `display`, `display-demo`, and the `logger` — from a
|
the `device-manager`, `volume-manager`, `display`, `display-demo`, and the `logger` — from a
|
||||||
small list. Drivers are deliberately *not* its job. (An earlier draft listed a `vfs`
|
small list. Drivers are deliberately *not* its job. (An earlier draft listed a `vfs`
|
||||||
service here; that service is retired — the router moved into the kernel as
|
service here; that service is retired — the router moved into the kernel as
|
||||||
`fs_resolve`.)
|
`fs_resolve`.)
|
||||||
@@ -51,7 +51,7 @@ the optional arguments its argv[1..], on a SysV entry stack, see sysv.md). Every
|
|||||||
is the **driver supervisor**. It does the three steps a monolithic kernel would do in
|
is the **driver supervisor**. It does the three steps a monolithic kernel would do in
|
||||||
its probe path, entirely from ring 3:
|
its probe path, entirely from ring 3:
|
||||||
1. **Discover** — `device_enumerate` snapshots the device table the kernel built from
|
1. **Discover** — `device_enumerate` snapshots the device table the kernel built from
|
||||||
ACPI/PCI ([discovery](discovery.md)).
|
ACPI/PCI ([discovery](../os-development/discovery.md)).
|
||||||
2. **Match** — for each device it looks up a driver. The match policy is code, a few
|
2. **Match** — for each device it looks up a driver. The match policy is code, a few
|
||||||
small per-bus tables: from the boot snapshot only the PCI host bridge matches
|
small per-bus tables: from the boot snapshot only the PCI host bridge matches
|
||||||
(→ `pci-bus`); everything else arrives later as bus reports and matches on
|
(→ `pci-bus`); everything else arrives later as bus reports and matches on
|
||||||
@@ -66,16 +66,17 @@ the optional arguments its argv[1..], on a SysV entry stack, see sysv.md). Every
|
|||||||
|
|
||||||
So "how is a driver discovered and configured" has two halves: **discovery** is the
|
So "how is a driver discovered and configured" has two halves: **discovery** is the
|
||||||
kernel's device table, read by anyone; **configuration** is two user-space policies —
|
kernel's device table, read by anyone; **configuration** is two user-space policies —
|
||||||
init's service list and the device-manager's match table. Both are hardcoded in their
|
init's service list and the device-manager's match table. Both are now data, not code —
|
||||||
respective programs today; the natural next step is to move them into `/etc` (see the
|
init reads `/system/configuration/init.csv` and the device manager reads
|
||||||
milestone notes in [driver-model.md](driver-model.md)). `system_spawn` is currently
|
`/system/configuration/devices.csv`, each parsed at startup (the compiled-in switch
|
||||||
|
tables are gone). `system_spawn` is currently
|
||||||
ungated — any process may spawn any bundled binary — because there is no spawn
|
ungated — any process may spawn any bundled binary — because there is no spawn
|
||||||
capability yet.
|
capability yet.
|
||||||
|
|
||||||
## The capability: claim before touch
|
## The capability: claim before touch
|
||||||
|
|
||||||
The driver syscall numbers (`system/abi.zig`) with the device types they carry
|
The driver syscall numbers (`system/abi.zig`) with the device types they carry
|
||||||
(`system/devices/device-abi.zig`), dispatched in `system/kernel/process.zig`:
|
(`library/device/model/device-abi.zig`), dispatched in `system/kernel/process.zig`:
|
||||||
|
|
||||||
| # | Call | Meaning |
|
| # | Call | Meaning |
|
||||||
|---|------|---------|
|
|---|------|---------|
|
||||||
@@ -269,7 +270,7 @@ already owns.
|
|||||||
A device with **no resources** is legal and common. A USB device is reached through its
|
A device with **no resources** is legal and common. A USB device is reached through its
|
||||||
controller, not by MMIO, so it gets `resource_count = 0`.
|
controller, not by MMIO, so it gets `resource_count = 0`.
|
||||||
|
|
||||||
See [`system/drivers/pci-bus/pci-bus.zig`](../system/drivers/pci-bus/pci-bus.zig) for a
|
See [`system/drivers/pci-bus/pci-bus.zig`](../../system/drivers/pci-bus/pci-bus.zig) for a
|
||||||
real one — it claims a PCI host bridge, maps its ECAM window, and publishes each function
|
real one — it claims a PCI host bridge, maps its ECAM window, and publishes each function
|
||||||
it finds as a child — and [driver-model.md](driver-model.md) for how bus drivers, class
|
it finds as a child — and [driver-model.md](driver-model.md) for how bus drivers, class
|
||||||
drivers and host controller drivers fit together.
|
drivers and host controller drivers fit together.
|
||||||
@@ -290,10 +291,10 @@ Several things this list used to warn about are now available (see
|
|||||||
[driver-model.md](driver-model.md)): **port I/O** (`io_read`/`io_write`, claim-gated by
|
[driver-model.md](driver-model.md)): **port I/O** (`io_read`/`io_write`, claim-gated by
|
||||||
the device's `io_port` resource — direct ring-3 `in`/`out` is still a #GP, so a PS/2 or
|
the device's `io_port` resource — direct ring-3 `in`/`out` is still a #GP, so a PS/2 or
|
||||||
16550 driver goes through these), **DMA memory** (`dma_alloc`: contiguous, pinned,
|
16550 driver goes through these), **DMA memory** (`dma_alloc`: contiguous, pinned,
|
||||||
uncacheable, physical address exposed), **memory barriers** (`library/mmio`'s
|
uncacheable, physical address exposed), **memory barriers** (`library/device/mmio`'s
|
||||||
`mb`/`rmb`/`wmb`, imported as the `mmio` module), **fault isolation** (a ring-3 fault kills only the faulting
|
`memoryBarrier`/`readMemoryBarrier`/`writeMemoryBarrier`, imported as the `mmio` module), **fault isolation** (a ring-3 fault kills only the faulting
|
||||||
process — `killCurrentProcess` — and the machine keeps running,
|
process — `killCurrentProcess` — and the machine keeps running,
|
||||||
[resilience](resilience.md)), and **reclaim + restart on death** (every path out of a
|
[resilience](../os-development/resilience.md)), and **reclaim + restart on death** (every path out of a
|
||||||
process releases its claims and IRQ/MSI bindings — `releaseAllOwnedBy`,
|
process releases its claims and IRQ/MSI bindings — `releaseAllOwnedBy`,
|
||||||
`irq.releaseOwner` — and the device manager respawns the driver with backoff,
|
`irq.releaseOwner` — and the device manager respawns the driver with backoff,
|
||||||
[device-manager.md](device-manager.md)). What remains:
|
[device-manager.md](device-manager.md)). What remains:
|
||||||
@@ -301,12 +302,13 @@ process releases its claims and IRQ/MSI bindings — `releaseAllOwnedBy`,
|
|||||||
- **Page granularity.** `mmio_map` rounds to 4 KiB. Two devices sharing a page means
|
- **Page granularity.** `mmio_map` rounds to 4 KiB. Two devices sharing a page means
|
||||||
granting one grants the other. A `device_register`ed child's *resource* can be narrower
|
granting one grants the other. A `device_register`ed child's *resource* can be narrower
|
||||||
than a page, but its *mapping* can't.
|
than a page, but its *mapping* can't.
|
||||||
- **DMA is not contained.** A driver that can program a bus-mastering device can make
|
- **DMA is contained — except on a machine with no IOMMU.** A driver that can program a
|
||||||
that device write to *any* physical address — page tables don't sit between a device
|
bus-mastering device could make that device write to *any* physical address — page
|
||||||
and RAM; an IOMMU does. The IOMMU is now *detected* (M16), but no translation domains
|
tables don't sit between a device and RAM; an IOMMU does. `device_claim` now confines
|
||||||
are programmed, so `device_claim` on a DMA-capable device is still effectively
|
each claimed PCI function into its own VT-d/AMD-Vi translation domain and rolls the
|
||||||
equivalent to granting ring 0. This is the largest gap between the design's promise and
|
claim back with `-ECONFINE` if it can't (`system/kernel/process.zig`); DMA buffers are
|
||||||
what it delivers; enforcement lands with the first DMA driver.
|
bound into that domain and torn down at process death. The residual gap is fail-open:
|
||||||
|
where the machine exposes **no IOMMU at all**, a DMA-capable claim still reaches RAM.
|
||||||
- **No voluntary `dev_release`.** A *live* driver can't drop a claim — only exit
|
- **No voluntary `dev_release`.** A *live* driver can't drop a claim — only exit
|
||||||
releases it (any path out of a process runs `releaseAllOwnedBy`) — so handing a
|
releases it (any path out of a process runs `releaseAllOwnedBy`) — so handing a
|
||||||
device between running drivers still means exiting.
|
device between running drivers still means exiting.
|
||||||
@@ -365,10 +367,9 @@ $ python3 test/qemu_test.py device-manager acpi-ps2 pci-scan containment irqfree
|
|||||||
## What's next (not done here)
|
## What's next (not done here)
|
||||||
|
|
||||||
The big driver-model pieces — capability passing (class drivers), DMA + barriers, MSI,
|
The big driver-model pieces — capability passing (class drivers), DMA + barriers, MSI,
|
||||||
and IOMMU detection — are **now done** ([driver-model.md](driver-model.md), M13–M16), as
|
and per-device IOMMU confinement — are **now done** ([driver-model.md](driver-model.md),
|
||||||
is **port I/O** (`io_read`/`io_write`, the claim-gated syscalls that make a PS/2 or 16550
|
M13–M16), as is **port I/O** (`io_read`/`io_write`, the claim-gated syscalls that make a
|
||||||
driver possible). What's left is IOMMU *enforcement* (per-device domains — it waits on
|
PS/2 or 16550 driver possible). What's left is a handful of smaller items:
|
||||||
the first DMA driver to protect and test against) and these smaller items:
|
|
||||||
|
|
||||||
- **Releasing a claim** — half done. The kernel now drops *all* of a dead driver's
|
- **Releasing a claim** — half done. The kernel now drops *all* of a dead driver's
|
||||||
claims on every path out of a process (`releaseAllOwnedBy`, called from process
|
claims on every path out of a process (`releaseAllOwnedBy`, called from process
|
||||||
@@ -391,10 +392,10 @@ the first DMA driver to protect and test against) and these smaller items:
|
|||||||
Claiming and mapping is half of being a danos driver; the other half is the
|
Claiming and mapping is half of being a danos driver; the other half is the
|
||||||
**lifecycle and protocol contract**, and the runtime makes it nearly free:
|
**lifecycle and protocol contract**, and the runtime makes it nearly free:
|
||||||
|
|
||||||
- Build on `runtime.service.run` — one replyWait loop folding protocol
|
- Build on `service.run` — one replyWait loop folding protocol
|
||||||
requests, signals, and notifications into callbacks. The harness answers the
|
requests, signals, and notifications into callbacks. The harness answers the
|
||||||
universal zero-length ping and turns `terminate` into a clean exit for you
|
universal zero-length ping and turns `terminate` into a clean exit for you
|
||||||
([process-lifecycle.md](process-lifecycle.md)).
|
([process-lifecycle.md](../os-development/process-lifecycle.md)).
|
||||||
- A driver spawned with an assignment (its device id as argv[1]) sends the
|
- A driver spawned with an assignment (its device id as argv[1]) sends the
|
||||||
versioned `hello` to the device manager inside the deadline, and a **bus**
|
versioned `hello` to the device manager inside the deadline, and a **bus**
|
||||||
driver reports what it discovers with `child_added`
|
driver reports what it discovers with `child_added`
|
||||||
@@ -5,14 +5,14 @@ window server, a logger. None of them owns the hardware, and the driver should n
|
|||||||
who is listening. So between the drivers and the listeners sits the **input service**
|
who is listening. So between the drivers and the listeners sits the **input service**
|
||||||
(`system/services/input/`): drivers **publish** events to it, programs **subscribe**, and
|
(`system/services/input/`): drivers **publish** events to it, programs **subscribe**, and
|
||||||
it fans each event out to every interested subscriber. It is an ordinary ring-3 process
|
it fans each event out to every interested subscriber. It is an ordinary ring-3 process
|
||||||
reached over IPC, like the [FAT server](../system/services/fat/fat.zig) — no kernel knows
|
reached over IPC, like the [FAT server](../../system/services/fat/fat.zig) — no kernel knows
|
||||||
what a key is.
|
what a key is.
|
||||||
|
|
||||||
## One service, several device classes
|
## One service, several device classes
|
||||||
|
|
||||||
The service carries three device classes today — **keyboard**, **mouse**, and
|
The service carries three device classes today — **keyboard**, **mouse**, and
|
||||||
**joystick/gamepad** — and is built to take more
|
**joystick/gamepad** — and is built to take more
|
||||||
([protocol.zig](../system/services/input/protocol.zig)). Each class has its own typed
|
([protocol.zig](../../library/protocol/input/input-protocol.zig)). Each class has its own typed
|
||||||
event:
|
event:
|
||||||
|
|
||||||
- `KeyEvent` — `key_down`/`key_up` (physical make/break) and `key_press` (a character was
|
- `KeyEvent` — `key_down`/`key_up` (physical make/break) and `key_press` (a character was
|
||||||
@@ -22,12 +22,22 @@ event:
|
|||||||
- `JoystickEvent` — `axis` moves (a signed value on a `control` index) and
|
- `JoystickEvent` — `axis` moves (a signed value on a `control` index) and
|
||||||
`button_down`/`button_up`.
|
`button_down`/`button_up`.
|
||||||
|
|
||||||
All three travel in one **`InputEvent` envelope** tagged with a `DeviceKind`, so the
|
A source publishes any of the three as one **`InputEvent`** tagged with a `DeviceKind`, so
|
||||||
fan-out is a single code path and a subscriber can take a mix of classes on one stream.
|
`publish` is a single verb; decode one with `asKeyboard()` / `asMouse()` / `asJoystick()`
|
||||||
Decode an envelope with `asKeyboard()` / `asMouse()` / `asJoystick()` (each returns null
|
(each returns null unless the tag matches). On the *delivery* wire the class is the
|
||||||
unless the tag matches). A subscriber names the classes it wants with a **`device_mask`**,
|
packet's own operation instead — the protocol declares one event per class
|
||||||
and the service routes each event only to subscribers whose mask includes its class — so a
|
([protocol-namespace.md](../os-development/protocol-namespace.md)), so a pushed packet is
|
||||||
mouse-only listener never wakes for keystrokes.
|
the 16-byte header plus the typed event and nothing carries a tag twice. The client
|
||||||
|
helpers re-tag what arrives back into an `InputEvent`, so a subscriber can still take a
|
||||||
|
mix of classes on one stream. A subscriber names the classes it wants with a
|
||||||
|
**`device_mask`**, and the service routes each event only to subscribers whose mask
|
||||||
|
includes its class — so a mouse-only listener never wakes for keystrokes.
|
||||||
|
|
||||||
|
**`subscribe` is not this protocol's verb.** Its shape — a synchronous call whose attached
|
||||||
|
capability is the subscriber's own endpoint — is what the envelope's *reserved* subscribe
|
||||||
|
means at every provider in the system, so the input protocol adopts it rather than
|
||||||
|
defining a second spelling of the same thing. The interest mask rides as the packet's
|
||||||
|
tail. `publish` is the one verb the protocol defines for itself.
|
||||||
|
|
||||||
## Why this needed a new kernel primitive
|
## Why this needed a new kernel primitive
|
||||||
|
|
||||||
@@ -45,7 +55,7 @@ consequences decide the whole design:
|
|||||||
`ipc_call`, it would block until each subscriber replied. `ipc_call` has no timeout, and
|
`ipc_call`, it would block until each subscriber replied. `ipc_call` has no timeout, and
|
||||||
a subscriber's endpoint is an *unregistered* capability the kernel's death path cannot
|
a subscriber's endpoint is an *unregistered* capability the kernel's death path cannot
|
||||||
reach (since display v2's V6, `killOwnedEndpointsLocked` in
|
reach (since display v2's V6, `killOwnedEndpointsLocked` in
|
||||||
[ipc-synchronous.zig](../system/kernel/ipc-synchronous.zig) marks a dead owner's
|
[ipc-synchronous.zig](../../system/kernel/ipc-synchronous.zig) marks a dead owner's
|
||||||
*registered* endpoints dead and wakes parked callers with `-EPEER` — but unregistered
|
*registered* endpoints dead and wakes parked callers with `-EPEER` — but unregistered
|
||||||
ones just drop with the task's handle table). One subscriber that exits mid-delivery
|
ones just drop with the task's handle table). One subscriber that exits mid-delivery
|
||||||
would wedge input for everyone. That is the opposite of the resilience the microkernel
|
would wedge input for everyone. That is the opposite of the resilience the microkernel
|
||||||
@@ -66,7 +76,7 @@ the badge (distinguishing it from a bare IRQ/child-exit notification), the sende
|
|||||||
in the low bits, and the payload in the receive buffer, with no reply owed. The queue holds
|
in the low bits, and the payload in the receive buffer, with no reply owed. The queue holds
|
||||||
16 messages per endpoint; a full queue **drops the oldest**, because a buffered message is
|
16 messages per endpoint; a full queue **drops the oldest**, because a buffered message is
|
||||||
discrete data, not a coalescing "level" like an interrupt. See
|
discrete data, not a coalescing "level" like an interrupt. See
|
||||||
[ipc-synchronous.zig](../system/kernel/ipc-synchronous.zig) (`sendLocked`, `popPost`, and
|
[ipc-synchronous.zig](../../system/kernel/ipc-synchronous.zig) (`sendLocked`, `popPost`, and
|
||||||
the `replyWait` receive loop).
|
the `replyWait` receive loop).
|
||||||
|
|
||||||
This is the async counterpart of `ipc_call`, and the input service is its first consumer.
|
This is the async counterpart of `ipc_call`, and the input service is its first consumer.
|
||||||
@@ -89,7 +99,7 @@ This is the async counterpart of `ipc_call`, and the input service is its first
|
|||||||
- A **subscriber** calls `input.subscribe(mask)` — or a typed helper: `subscribeKeyboard()`,
|
- A **subscriber** calls `input.subscribe(mask)` — or a typed helper: `subscribeKeyboard()`,
|
||||||
`subscribeMouse()`, `subscribeJoystick()` (one class, `next()` returns the decoded event),
|
`subscribeMouse()`, `subscribeJoystick()` (one class, `next()` returns the decoded event),
|
||||||
or `subscribeAll()` (every class, `next()` returns a tagged `InputEvent`)
|
or `subscribeAll()` (every class, `next()` returns a tagged `InputEvent`)
|
||||||
([library/runtime/input.zig](../library/runtime/input.zig)). It creates its own endpoint
|
([library/client/input/input.zig](../../library/client/input/input.zig)). It creates its own endpoint
|
||||||
and hands it to the service as a **capability** (M13 capability passing — the input
|
and hands it to the service as a **capability** (M13 capability passing — the input
|
||||||
service is that feature's first real user), along with its `device_mask`. Then it loops on
|
service is that feature's first real user), along with its `device_mask`. Then it loops on
|
||||||
`next()`, a `replyWait` on that endpoint returning each pushed event.
|
`next()`, a `replyWait` on that endpoint returning each pushed event.
|
||||||
@@ -98,12 +108,25 @@ This is the async counterpart of `ipc_call`, and the input service is its first
|
|||||||
`publishJoystickEvent`. Publishing is a short synchronous `ipc_call` the service answers at
|
`publishJoystickEvent`. Publishing is a short synchronous `ipc_call` the service answers at
|
||||||
once; the service's own fan-out is asynchronous, so publishing never blocks on a slow
|
once; the service's own fan-out is asynchronous, so publishing never blocks on a slow
|
||||||
subscriber.
|
subscriber.
|
||||||
- The **service** ([input.zig](../system/services/input/input.zig)) keeps a small subscriber
|
- The **service** ([input.zig](../../system/services/input/input.zig)) owns none of that
|
||||||
table (endpoint handle + owning task id + `device_mask`). On `publish` it `ipc_send`s the
|
machinery any more: the subscriber table (endpoint handle + owning task + interest mask),
|
||||||
event to every subscriber whose mask includes the event's device class. On `subscribe` it
|
the reserved `subscribe`/`unsubscribe` verbs, the fan-out, and the dead-subscriber sweep
|
||||||
stores the passed capability and mask and, as housekeeping, prunes any slot whose owning
|
are the shared harness's (`service.Subscribers` in
|
||||||
process has exited (checked against `process_enumerate`) — not for correctness (an async
|
[service.zig](../../library/kernel/service.zig)), so every event stream in the system has
|
||||||
send to an orphaned endpoint is harmless) but to reclaim the slot.
|
identical semantics. What is left in this file is what is actually about input: which
|
||||||
|
class an event belongs to, and which classes a subscriber asked for. On `publish` it names
|
||||||
|
the event's class and the harness `ipc_send`s the packet — framed once — to every
|
||||||
|
subscriber whose mask includes it.
|
||||||
|
- **A dead subscriber goes away on its exit notification**, not on a poll. The service used
|
||||||
|
to walk `process_enumerate` on every subscribe and drop slots whose owner had gone; it now
|
||||||
|
subscribes to the kernel's published exits like the FAT server and the compositor do
|
||||||
|
([process-lifecycle.md](../os-development/process-lifecycle.md)), which reclaims the slot
|
||||||
|
*and* closes the endpoint capability in it promptly rather than at the next subscribe.
|
||||||
|
(The fan-out also drops a subscriber whose `ipc_send` fails, as a backstop for a
|
||||||
|
notification a full ring dropped.)
|
||||||
|
- The service runs on the shared harness like every other, so it answers the universal ping
|
||||||
|
and exits on `terminate`; it was the last hand-rolled receive loop in the tree, and the
|
||||||
|
last service a shutdown had to kill rather than ask.
|
||||||
|
|
||||||
Publisher and subscriber must be **separate processes**: a single thread that both
|
Publisher and subscriber must be **separate processes**: a single thread that both
|
||||||
published and serviced its own subscription would deadlock (its `publish` call blocks until
|
published and serviced its own subscription would deadlock (its `publish` call blocks until
|
||||||
@@ -113,18 +136,18 @@ the service delivers to its endpoint, which only the same thread could receive).
|
|||||||
|
|
||||||
- **The keyboard is real.** The `ps2-bus` driver owns PNP0303, which carries *both* the
|
- **The keyboard is real.** The `ps2-bus` driver owns PNP0303, which carries *both* the
|
||||||
0x60/0x64 ports and IRQ1, so reading the hardware lives in the bus, not in
|
0x60/0x64 ports and IRQ1, so reading the hardware lives in the bus, not in
|
||||||
[keyboard.zig](../system/drivers/ps2-bus/keyboard.zig): the bus binds IRQ1 and, on each
|
[keyboard.zig](../../system/drivers/ps2-bus/keyboard.zig): the bus binds IRQ1 and, on each
|
||||||
interrupt, drains port 0x60, routing every byte by the status register's
|
interrupt, drains port 0x60, routing every byte by the status register's
|
||||||
auxiliary-output bit to whichever child driver **attached** for that device (an
|
auxiliary-output bit to whichever child driver **attached** for that device (an
|
||||||
`AttachRequest` to the well-known `ps2_bus` service, carrying the child's endpoint as a
|
`AttachRequest` to the well-known `ps2_bus` service, carrying the child's endpoint as a
|
||||||
capability; the bytes then arrive as asynchronous `ForwardedByte` messages, so the IRQ
|
capability; the bytes then arrive as asynchronous `ForwardedByte` messages, so the IRQ
|
||||||
path never blocks on a child). The keyboard driver decodes the stream — scancode **set 2**,
|
path never blocks on a child). The keyboard driver decodes the stream — scancode **set 2**,
|
||||||
what the keyboard sends with the 8042's legacy translation off, decoded by
|
what the keyboard sends with the 8042's legacy translation off, decoded by
|
||||||
[scancode.zig](../system/drivers/ps2-bus/scancode.zig) into USB HID usage keycodes with
|
[scancode.zig](../../system/drivers/ps2-bus/scancode.zig) into USB HID usage keycodes with
|
||||||
make/break, typematic-repeat, and modifier tracking (host-tested under `zig build test`) —
|
make/break, typematic-repeat, and modifier tracking (host-tested under `zig build test`) —
|
||||||
and publishes real `key_down`/`key_press`/`key_up` events.
|
and publishes real `key_down`/`key_press`/`key_up` events.
|
||||||
- **Keycode → character** is wired in: the keyboard driver fills a `key_press` event's
|
- **Keycode → character** is wired in: the keyboard driver fills a `key_press` event's
|
||||||
`character` through [`library/xkeyboard-config`](../library/xkeyboard-config/README.md)
|
`character` through [`library/xkeyboard-config`](../../library/xkeyboard-config/README.md)
|
||||||
(`xkb.map(layout, keycode, mods)` → keysym + Unicode character), synthesizing the ASCII
|
(`xkb.map(layout, keycode, mods)` → keysym + Unicode character), synthesizing the ASCII
|
||||||
control characters for Enter/Tab/Backspace/Escape, whose keysyms map to no Unicode. The
|
control characters for Enter/Tab/Backspace/Escape, whose keysyms map to no Unicode. The
|
||||||
layout defaults to `us`; the bus can pass another as the driver's argv[2] — the seam for
|
layout defaults to `us`; the bus can pass another as the driver's argv[2] — the seam for
|
||||||
@@ -132,9 +155,9 @@ the service delivers to its endpoint, which only the same thread could receive).
|
|||||||
- **The mouse is real too.** IRQ12 is enumerated on the auxiliary device's own ACPI node
|
- **The mouse is real too.** IRQ12 is enumerated on the auxiliary device's own ACPI node
|
||||||
(PNP0F13), so the bus claims that node alongside the controller and routes both IRQs to
|
(PNP0F13), so the bus claims that node alongside the controller and routes both IRQs to
|
||||||
its one endpoint, acking whichever line the notification's badge names.
|
its one endpoint, acking whichever line the notification's badge names.
|
||||||
[mouse.zig](../system/drivers/ps2-bus/mouse.zig) attaches the way the keyboard does and
|
[mouse.zig](../../system/drivers/ps2-bus/mouse.zig) attaches the way the keyboard does and
|
||||||
assembles the forwarded bytes with
|
assembles the forwarded bytes with
|
||||||
[mouse-packet.zig](../system/drivers/ps2-bus/mouse-packet.zig) (three-byte stream-mode
|
[mouse-packet.zig](../../system/drivers/ps2-bus/mouse-packet.zig) (three-byte stream-mode
|
||||||
packets: sync/overflow handling, nine-bit movement, screen-convention `dy` — host-tested
|
packets: sync/overflow handling, nine-bit movement, screen-convention `dy` — host-tested
|
||||||
under `zig build test`) into `button_down`/`button_up` transitions and `motion` events.
|
under `zig build test`) into `button_down`/`button_up` transitions and `motion` events.
|
||||||
**Follow-up:** the IntelliMouse magic-knock for a scroll wheel (four-byte packets) and
|
**Follow-up:** the IntelliMouse magic-knock for a scroll wheel (four-byte packets) and
|
||||||
@@ -150,7 +173,7 @@ the service delivers to its endpoint, which only the same thread could receive).
|
|||||||
## Verifying it
|
## Verifying it
|
||||||
|
|
||||||
The `input` case (`python3 test/qemu_test.py input`, in
|
The `input` case (`python3 test/qemu_test.py input`, in
|
||||||
[tests.zig](../system/kernel/tests.zig) `inputTest`) boots the real kernel and spawns the
|
[tests.zig](../../system/kernel/tests.zig) `inputTest`) boots the real kernel and spawns the
|
||||||
service, the synthetic source (which cycles keyboard, mouse, and joystick events), and a
|
service, the synthetic source (which cycles keyboard, mouse, and joystick events), and a
|
||||||
subscriber that took all three classes. It passes only when the subscriber heartbeats
|
subscriber that took all three classes. It passes only when the subscriber heartbeats
|
||||||
`input-test: ok` — proof that an event travelled source → service → subscriber over IPC,
|
`input-test: ok` — proof that an event travelled source → service → subscriber over IPC,
|
||||||
@@ -160,5 +183,5 @@ serial line names the class received, so the log shows all three arriving on one
|
|||||||
## See also
|
## See also
|
||||||
|
|
||||||
- [ipc.md](ipc.md) — the synchronous rendezvous and the notification path `ipc_send` extends.
|
- [ipc.md](ipc.md) — the synchronous rendezvous and the notification path `ipc_send` extends.
|
||||||
- [syscall.md](syscall.md) — the system-call surface, including `ipc_send`.
|
- [syscall.md](../os-development/syscall.md) — the system-call surface, including `ipc_send`.
|
||||||
- [driver-model.md](driver-model.md) — class drivers, capability passing (M13), the trust model.
|
- [driver-model.md](driver-model.md) — class drivers, capability passing (M13), the trust model.
|
||||||
File renamed without changes.
@@ -0,0 +1,199 @@
|
|||||||
|
# IPC: the kernel-ipc transport
|
||||||
|
|
||||||
|
Inter-process communication is the **backbone of a microkernel**. Once drivers and
|
||||||
|
services run isolated in their own address spaces ([vision](../vision.md)), they can't
|
||||||
|
just call each other — a request becomes bytes on a wire. In a microkernel, whatever
|
||||||
|
was a function call across a monolithic kernel is IPC, so it's a first-class
|
||||||
|
concern, not an afterthought.
|
||||||
|
|
||||||
|
This document describes **one transport** — the bottom layer (L0) of the
|
||||||
|
communication stack defined in
|
||||||
|
[communication.md](../os-development/communication.md), which owns the model
|
||||||
|
and the vocabulary (*protocol*, *channel*, *packet*, *signal*, *endpoint*).
|
||||||
|
kernel-ipc is the **first** transport, not the only possible one: in
|
||||||
|
buffer-plus-doorbell terms it is a kernel-owned mailbox with the scheduler as
|
||||||
|
the doorbell. Its distinguishing properties, which the layers above may rely
|
||||||
|
on where they say so:
|
||||||
|
|
||||||
|
- **Rendezvous.** A call is a synchronous meeting, copied sender-page to
|
||||||
|
receiver-page — natural backpressure, no queue to size.
|
||||||
|
- **Capability carriage.** The *only* transport that can move a handle
|
||||||
|
between processes. Channels are therefore always established over
|
||||||
|
kernel-ipc, and it remains every channel's control path even when bulk
|
||||||
|
data is negotiated onto a fatter transport (a shared-memory ring).
|
||||||
|
- **Verified source.** Every delivery carries the kernel-stamped badge — the
|
||||||
|
identity the channel layer attaches to received packets.
|
||||||
|
- **Bounded packets.** 256 bytes call/reply, 64 pushed — the floor every
|
||||||
|
protocol may assume on any transport.
|
||||||
|
|
||||||
|
Three properties keep the networking analogy honest — kernel-ipc is
|
||||||
|
networking-*shaped*, not TCP:
|
||||||
|
|
||||||
|
- **Channels over it are RPC-shaped, not streams.** Packets, call/reply,
|
||||||
|
datagram pushes — closer to UDP plus RPC than to a byte stream. Ordering
|
||||||
|
exists per exchange (a reply answers its call), not across a channel.
|
||||||
|
- **Possession is the connection.** There is no handshake state in the
|
||||||
|
kernel: holding the capability *is* having the channel. A provider's one
|
||||||
|
endpoint terminates every client's channel at once, demultiplexed by badge
|
||||||
|
— like every client sharing the server's listening socket, with
|
||||||
|
per-connection state living in the provider, keyed by badge. A *private*
|
||||||
|
channel (a dedicated endpoint pair) is built when wanted: that is exactly
|
||||||
|
what `subscribe` does.
|
||||||
|
- **Packets never fragment.** If it doesn't fit in a packet, it isn't a
|
||||||
|
packet: bulk data lives in shared memory and a packet (or signal) is the
|
||||||
|
doorbell. The display path already works this way.
|
||||||
|
|
||||||
|
The rest of this document is the implementation, bottom-up: the kernel-thread
|
||||||
|
queue the blocking discipline was worked out on, then endpoints — this
|
||||||
|
transport's termination points.
|
||||||
|
|
||||||
|
## The kernel-thread queue
|
||||||
|
|
||||||
|
The first form is a **bounded blocking queue** (`system/kernel/ipc.zig`): a
|
||||||
|
fixed-size ring buffer of messages with a producer/consumer rendezvous, built
|
||||||
|
on the scheduler's [wait queues](../os-development/scheduling.md). (Its type
|
||||||
|
is still named `Channel(T, capacity)` — it predates the vocabulary above, and
|
||||||
|
is a *queue between kernel threads in one address space*, not a channel in
|
||||||
|
the model's sense; a rename can ride a later flag-day.)
|
||||||
|
|
||||||
|
`Channel(T, capacity)` is generic over the message type and buffer size. It holds a
|
||||||
|
ring buffer, a count, and two wait queues:
|
||||||
|
|
||||||
|
- **`send(msg)`** — if the queue is full, block on the *not-full* queue; otherwise
|
||||||
|
write the message, bump the count, and wake a waiting receiver.
|
||||||
|
- **`receive()`** — if the queue is empty, block on the *not-empty* queue; otherwise
|
||||||
|
take a message, drop the count, and wake a waiting sender.
|
||||||
|
|
||||||
|
Neither side busy-waits: a full queue parks the sender, an empty one parks the
|
||||||
|
receiver, and each operation wakes the other side when it makes progress possible.
|
||||||
|
|
||||||
|
Two details make it correct:
|
||||||
|
|
||||||
|
- **Recheck in a loop.** A woken task re-tests the condition (`while (full) wait`)
|
||||||
|
rather than assuming the slot is still available — another waiter may have taken
|
||||||
|
it first. This is the standard guard against spurious or racing wakeups.
|
||||||
|
- **One critical section.** `send`/`receive` run under the [big kernel
|
||||||
|
lock](../os-development/smp.md) (`sync.enter` / `sync.leave`), which disables interrupts on this
|
||||||
|
core *and* takes the kernel's one spinlock — since SMP, the interrupt flag alone
|
||||||
|
is not atomicity, because `cli` on one core does nothing to another. So checking
|
||||||
|
the condition and committing the block/enqueue happen atomically both with respect
|
||||||
|
to the timer preempting mid-operation and to the other side running on another
|
||||||
|
CPU. `waitLocked` / `wakeLocked` are the variants that assume the caller already
|
||||||
|
holds that critical section.
|
||||||
|
|
||||||
|
### Verifying it
|
||||||
|
|
||||||
|
The `ipc` test (see [testing.md](../testing.md)) runs a producer and a consumer passing
|
||||||
|
**100 messages through a 4-slot queue**. The small buffer means the queue goes
|
||||||
|
full and empty over and over, so both the blocking-send and blocking-receive paths are
|
||||||
|
exercised heavily. The messages arrive intact and in order (their sum is the
|
||||||
|
expected `5050`), and neither task busy-waits — they block and wake each other.
|
||||||
|
|
||||||
|
## Endpoints: the termination points
|
||||||
|
|
||||||
|
A queue connects two kernel threads sharing one address space. Real providers are
|
||||||
|
*processes*, so a packet has to cross an address-space boundary. That's
|
||||||
|
`system/kernel/ipc-synchronous.zig`, and its shape is L4's: a synchronous **rendezvous** at an
|
||||||
|
`Endpoint`, with the packet copied directly from the sender's pages to the receiver's
|
||||||
|
(`copyAcross` walks both sets of page tables through the physmap — no CR3 switch, no
|
||||||
|
bounce buffer).
|
||||||
|
|
||||||
|
Two syscalls carry the request/reply exchange:
|
||||||
|
|
||||||
|
- **`ipc_call(h, msg, reply)`** — copy the request packet to the provider, block
|
||||||
|
until the reply packet comes back.
|
||||||
|
- **`ipc_reply_wait(h, reply, recv)`** — reply to the client you're still holding (if
|
||||||
|
any), then block for the next request. One syscall, because a provider's steady state
|
||||||
|
is *always* "finish the last one, wait for the next".
|
||||||
|
|
||||||
|
An endpoint is reached by **handle** — a small integer index into the process's handle
|
||||||
|
table (`Task.handles`), exactly like a file descriptor, and just as unforgeable.
|
||||||
|
The provider never learns the client's identity beyond the **badge** delivered
|
||||||
|
alongside each packet: the caller's task id, stamped by the kernel —
|
||||||
|
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 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
|
||||||
|
|
||||||
|
`notifyFromIsr` posts an *asynchronous* signal to an endpoint — no payload, no
|
||||||
|
reply owed — and wakes whoever is blocked in `reply_wait`. Its badge has the top bit
|
||||||
|
set (`notify_badge_bit`), which is how a driver's single event loop distinguishes "a
|
||||||
|
client wants something" from "the hardware wants something". Signals sit in a
|
||||||
|
small coalescing ring on the endpoint, so an interrupt taken while the driver was busy
|
||||||
|
elsewhere is not lost — coalesced, never dropped, which is exactly a signal's
|
||||||
|
contract (the *count* may collapse; the *fact* may not).
|
||||||
|
|
||||||
|
This is what makes a user-space driver possible at all, and it's the subject of
|
||||||
|
[drivers.md](drivers.md).
|
||||||
|
|
||||||
|
## What's next (partly done since)
|
||||||
|
|
||||||
|
- **Priority inheritance** through IPC — still open: a high-priority client
|
||||||
|
blocked on a low-priority provider suffers unbounded priority inversion.
|
||||||
|
- **Handle transfer.** *Landed as cap-passing (M13)*: `ipc_call` and
|
||||||
|
`ipc_reply_wait` carry an optional capability alongside the bytes (`send_cap`),
|
||||||
|
copying an endpoint or shared-memory handle into the peer's table — the
|
||||||
|
mechanism by which channels are established and private channels built. First
|
||||||
|
user: [input](input.md) subscribers register by handing over their own
|
||||||
|
endpoint, and class drivers get a private channel to one device.
|
||||||
|
- **Asynchronous / buffered send** for the cases where a rendezvous is the wrong
|
||||||
|
shape (logging, event fan-out). *Landed as `ipc_send`* — a
|
||||||
|
non-blocking post of an event packet (≤ 64 bytes) to an endpoint's bounded
|
||||||
|
queue, delivered through `reply_wait` (badge bit `notify_message_bit`). Built
|
||||||
|
for, and first used by, the [input service](input.md)'s keyboard-event
|
||||||
|
broadcast, where a synchronous push would let one dead subscriber hang the
|
||||||
|
fan-out. A full queue drops the oldest — event packets are droppable by
|
||||||
|
design ([protocol-namespace.md](../os-development/protocol-namespace.md)'s
|
||||||
|
wiring section states the rule).
|
||||||
|
- **A bounded reply** — half landed. The copy is still one packet
|
||||||
|
(256 bytes) under the big kernel lock, but bulk transfer got its shared
|
||||||
|
pages: `shared_memory_create`/`map`/`physical`, the region handle delegated as
|
||||||
|
a capability (above) — the packets-never-fragment rule in practice.
|
||||||
|
virtio-gpu's scanout surface is the first user
|
||||||
|
([display-v2.md](display-v2.md)).
|
||||||
|
|
||||||
|
## Lifecycle conventions over IPC (M17)
|
||||||
|
|
||||||
|
Three conventions from [process-lifecycle.md](../os-development/process-lifecycle.md) ride the
|
||||||
|
signal mechanism:
|
||||||
|
|
||||||
|
- **Process signals** arrive as endpoint signals on the endpoint a process
|
||||||
|
nominated with `signal_bind` (`process.bindSignals`): badge = the signal bit
|
||||||
|
plus the coalesced pending mask (`process.signalsFrom` decodes). Statements,
|
||||||
|
never questions; no payload, no reply.
|
||||||
|
- **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
|
||||||
|
encoding cannot collide, and a wedged service simply fails to answer — which
|
||||||
|
is the diagnosis. Deep health ("can I reach my hardware?") stays a per-service
|
||||||
|
protocol packet.
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
# New driver: the minimum steps
|
||||||
|
|
||||||
|
The shortest path from "a device shows up in the boot log" to "my process is
|
||||||
|
running with its registers mapped". This is the checklist; the reasoning behind
|
||||||
|
every step lives in [Writing a driver](drivers.md), the matching rules in
|
||||||
|
[devices.csv](devices-csv.md), and interrupts in
|
||||||
|
[device interrupts](device-interrupts.md).
|
||||||
|
|
||||||
|
Worked example throughout: the Intel UHD 750 iGPU, which the boot log reports as
|
||||||
|
|
||||||
|
```
|
||||||
|
pci-bus: 0:2.0 bus=pci base=03 class=00 prog_if=00 vendor=8086 device=4C8A ...
|
||||||
|
```
|
||||||
|
|
||||||
|
## 1. Create the source file
|
||||||
|
|
||||||
|
`system/drivers/<name>/<name>.zig` — kebab-case, abbreviations spelled out
|
||||||
|
([coding standards](../coding-standards.md)). The directory name, the binary
|
||||||
|
name, and the `devices.csv` driver path must all agree; a mismatch fails
|
||||||
|
silently (the device-manager logs the spawn failure, nothing else happens).
|
||||||
|
|
||||||
|
The complete minimal driver — claims its device, logs every resource, maps the
|
||||||
|
register window, then sleeps in the harness loop:
|
||||||
|
|
||||||
|
```zig
|
||||||
|
//! /system/drivers/intel-uhd-graphics-750 — spawned by the device manager with
|
||||||
|
//! the device-tree id as argv[1]; claims that device and no other.
|
||||||
|
|
||||||
|
const std = @import("std");
|
||||||
|
const device = @import("driver");
|
||||||
|
const ipc = @import("ipc");
|
||||||
|
const memory = @import("memory");
|
||||||
|
const process = @import("process");
|
||||||
|
const service = @import("service");
|
||||||
|
|
||||||
|
/// No protocol yet: the kernel's IPC ceiling (MESSAGE_MAXIMUM) sizes the buffers.
|
||||||
|
const message_maximum = 256;
|
||||||
|
|
||||||
|
var controller_id: u64 = 0;
|
||||||
|
var register_base: usize = 0;
|
||||||
|
|
||||||
|
fn initialise(endpoint: ipc.Handle) bool {
|
||||||
|
_ = endpoint; // needed later, for irq binding and timers
|
||||||
|
|
||||||
|
if (!device.claim(controller_id)) {
|
||||||
|
std.log.err("unable to claim device {d}", .{controller_id});
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch our own descriptor back for the device's resources.
|
||||||
|
const buffer = memory.allocator().alloc(device.DeviceDescriptor, 64) catch return false;
|
||||||
|
defer memory.allocator().free(buffer);
|
||||||
|
const total = device.enumerate(buffer);
|
||||||
|
const descriptor = for (buffer[0..@min(total, buffer.len)]) |d| {
|
||||||
|
if (d.id == controller_id) break d;
|
||||||
|
} else {
|
||||||
|
std.log.err("device {d} not in the device tree", .{controller_id});
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Log every resource BEFORE choosing one (see step 5).
|
||||||
|
var register_index: u64 = 0;
|
||||||
|
for (descriptor.resources[0..@intCast(descriptor.resource_count)], 0..) |resource, index| {
|
||||||
|
std.log.info("resource {d}: kind={d} start=0x{x} len=0x{x}", .{
|
||||||
|
index, resource.kind, resource.start, resource.len,
|
||||||
|
});
|
||||||
|
// The 16 MiB window is GTTMMADR, the register BAR (this device also has
|
||||||
|
// a 256 MiB memory BAR, GMADR — "first memory resource" would be wrong).
|
||||||
|
if (resource.kind == @intFromEnum(device.ResourceKind.memory) and
|
||||||
|
resource.len == 16 * 1024 * 1024) register_index = index;
|
||||||
|
}
|
||||||
|
if (register_index == 0) {
|
||||||
|
std.log.err("register BAR not found", .{});
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
register_base = device.mmioMap(controller_id, register_index) orelse {
|
||||||
|
std.log.err("mmio_map failed", .{});
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
std.log.info("registers mapped at 0x{x}", .{register_base});
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn onMessage(message: []const u8, reply: []u8, sender: u32, capability: ?ipc.Handle) usize {
|
||||||
|
_ = message;
|
||||||
|
_ = reply;
|
||||||
|
_ = sender;
|
||||||
|
_ = capability;
|
||||||
|
return 0; // no protocol yet; the zero-length ping is answered by the harness
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn main(init: process.Init) void {
|
||||||
|
const argument = init.arguments.get(1) orelse {
|
||||||
|
std.log.err("missing device id (argv[1])", .{});
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
controller_id = std.fmt.parseInt(u64, argument, 10) catch {
|
||||||
|
std.log.err("malformed device id '{s}'", .{argument});
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
service.run(message_maximum, .{
|
||||||
|
.init = initialise,
|
||||||
|
.on_message = onMessage,
|
||||||
|
// .on_notification only once an IRQ or timer is bound
|
||||||
|
});
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`claim` is the capability gate: MMIO mapping, DMA grants, and IRQ binding all
|
||||||
|
require it, and it pins the IOMMU domain to this process
|
||||||
|
([drivers.md — claim before touch](drivers.md#the-capability-claim-before-touch)).
|
||||||
|
|
||||||
|
## 2. Create the build package and register it in the root build
|
||||||
|
|
||||||
|
The driver directory is its own build package
|
||||||
|
([build-packages-plan.md](../build-packages-plan.md)): a ~15-line `build.zig`
|
||||||
|
plus a `build.zig.zon` beside the source. Copy both from an existing driver —
|
||||||
|
`system/drivers/pci-bus/` is the template — and adjust the name, root source
|
||||||
|
file, and the import list. The list names EXACTLY the modules the driver's
|
||||||
|
source `@import`s (the moral equivalent of its include list; an undeclared
|
||||||
|
import is a compile error):
|
||||||
|
|
||||||
|
```zig
|
||||||
|
pub fn build(b: *std.Build) void {
|
||||||
|
const exe = build_support.userBinary(b, .{
|
||||||
|
.name = "intel-uhd-graphics-750",
|
||||||
|
.root_source_file = b.path("intel-uhd-graphics-750.zig"),
|
||||||
|
.imports = &.{ "driver", "ipc", "memory", "process", "service" },
|
||||||
|
});
|
||||||
|
b.installArtifact(exe);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The zon declares `build-support`, `kernel` (implicit in every binary: the root
|
||||||
|
shim lives there), and the homes of the listed imports — for the minimal
|
||||||
|
driver above that is kernel alone plus `device` (for `driver`); add
|
||||||
|
`protocol`, `client`, ... only when an import comes from them (again, copy
|
||||||
|
pci-bus's zon and adjust). For the `.fingerprint` field, leave the copied
|
||||||
|
value in place and `zig build` will reject it and suggest the fresh one to
|
||||||
|
paste.
|
||||||
|
|
||||||
|
Then three one-liners in the root build register the package: the dependency
|
||||||
|
and a row in the boot-tree array in `build.zig` (search for
|
||||||
|
`virtio_gpu_package` to land in the right places),
|
||||||
|
|
||||||
|
```zig
|
||||||
|
const intel_uhd_graphics_750_exe = b.dependency("intel-uhd-graphics-750", .{}).artifact("intel-uhd-graphics-750");
|
||||||
|
```
|
||||||
|
|
||||||
|
```zig
|
||||||
|
.{ .path = "system/drivers/intel-uhd-graphics-750", .binary = intel_uhd_graphics_750_exe.getEmittedBin() },
|
||||||
|
```
|
||||||
|
|
||||||
|
and the path entry in the root `build.zig.zon`:
|
||||||
|
|
||||||
|
```zig
|
||||||
|
.@"intel-uhd-graphics-750" = .{ .path = "system/drivers/intel-uhd-graphics-750" },
|
||||||
|
```
|
||||||
|
|
||||||
|
Without the boot-tree row the binary never reaches the image and the
|
||||||
|
device-manager has nothing to spawn. (The package also builds standalone:
|
||||||
|
`cd system/drivers/intel-uhd-graphics-750 && zig build`.)
|
||||||
|
|
||||||
|
## 3. Add the match rule to `system/configuration/devices.csv`
|
||||||
|
|
||||||
|
One row: bus, class triplet, vendor/device, driver path. **Copy the class
|
||||||
|
triplet from the pci-bus boot log line, not from another row** — for the iGPU
|
||||||
|
above the correct rule is
|
||||||
|
|
||||||
|
```
|
||||||
|
pci, 03, 00, 00, 8086, 4C8A, *, *, /system/drivers/intel-uhd-graphics-750
|
||||||
|
```
|
||||||
|
|
||||||
|
Field-by-field rules and the most-specific-wins policy: [devices.csv](devices-csv.md).
|
||||||
|
The registry is authoritative: an unmatched device is logged unbound, never
|
||||||
|
guessed — so a wrong nibble here means the driver simply never starts.
|
||||||
|
|
||||||
|
## 4. First contact: read, predict, verify
|
||||||
|
|
||||||
|
Before writing any register, read one whose value you can predict from state
|
||||||
|
the firmware already programmed (for a display controller: the pipe source
|
||||||
|
size of the live mode). Registers are volatile loads at `register_base +
|
||||||
|
offset`, where `offset` is what the device's manual lists:
|
||||||
|
|
||||||
|
```zig
|
||||||
|
fn read32(offset: usize) u32 {
|
||||||
|
return @as(*volatile u32, @ptrFromInt(register_base + offset)).*;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
A matching read proves the whole chain — CSV match, spawn, claim, BAR choice,
|
||||||
|
mapping — with zero risk to the hardware.
|
||||||
|
|
||||||
|
## 5. Verify the plumbing
|
||||||
|
|
||||||
|
- `zig build test` still passes.
|
||||||
|
- On the image: `/system/logs/<boot-stamp>/system/services/device-manager.log`
|
||||||
|
shows `spawned <name> for device <N>`, and
|
||||||
|
`/system/logs/<boot-stamp>/system/drivers/<name>.log` holds the resource list and
|
||||||
|
your first read.
|
||||||
|
- If the driver did not spawn, diagnose in this order: binary on the image
|
||||||
|
(step 2) → CSV row matches the log line exactly (step 3) → path identical in
|
||||||
|
both (step 1).
|
||||||
|
|
||||||
|
## Later, when the device needs them
|
||||||
|
|
||||||
|
- **Interrupts**: MSI/MSI-X via the `pci` module, delivered as notifications to
|
||||||
|
`on_notification` — see [device interrupts](device-interrupts.md) and the
|
||||||
|
xHCI driver's `setupMsi` (QEMU trap documented there: enable MSI-X before
|
||||||
|
unmasking the device's own interrupt-enable bit).
|
||||||
|
- **DMA**: grant-backed buffers, bounded by the IOMMU domain established at
|
||||||
|
claim time ([driver model](driver-model.md)).
|
||||||
|
- **Children**: a bus driver publishes what it finds via `device_register`
|
||||||
|
([drivers.md — publishing children](drivers.md#publishing-children-device_register)).
|
||||||
|
- **A protocol**: replace `message_maximum` with the protocol's own maximum and
|
||||||
|
dispatch on the operation word in `onMessage` — every service under
|
||||||
|
`system/services/` is an example.
|
||||||
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,124 @@
|
|||||||
|
# Dynamic libraries on danos
|
||||||
|
|
||||||
|
A design note and milestone plan for shared objects: building them, loading them
|
||||||
|
with `dlopen`, and — the part that needs kernel work — actually *sharing* them
|
||||||
|
between processes. Directional, post-P5 of
|
||||||
|
[python-on-danos-milestones.md](python-on-danos-milestones.md); nothing on the
|
||||||
|
CPython bring-up path depends on it.
|
||||||
|
|
||||||
|
## Reconciling the earlier "rejected"
|
||||||
|
|
||||||
|
Dynamic libraries were evaluated once before and rejected — but as an answer to a
|
||||||
|
*different question*: whether they could claw back ReleaseSafe's measured ~2×
|
||||||
|
code size. They cannot (the safety checks inline at every call site; no library
|
||||||
|
scheme dedups them), and that verdict stands for that question. The reasons to
|
||||||
|
build them now are the ones that investigation never weighed:
|
||||||
|
|
||||||
|
- **`ctypes` and runtime FFI** — Python calling into a danos library without
|
||||||
|
rebuilding the interpreter. This is the piece that makes Python prototyping
|
||||||
|
self-serve: drop a `.so` on the image, `ctypes.CDLL` it, iterate.
|
||||||
|
- **Loadable CPython extension modules** — today every C extension means
|
||||||
|
relinking the interpreter (`Modules/Setup`); with `dlopen`, an extension is a
|
||||||
|
file.
|
||||||
|
- **One interpreter image, many Python services** — a statically-linked CPython
|
||||||
|
is tens of megabytes *per process*. A shared `libpython` mapped read-only once
|
||||||
|
(milestone D3 below) makes Python services cheap enough to be the default way
|
||||||
|
to prototype one.
|
||||||
|
- **Plugin-shaped applications** — the UI toolkit and the terminal will want
|
||||||
|
them eventually.
|
||||||
|
|
||||||
|
The scoping that dissolves the apparent contradiction is the **size doctrine**:
|
||||||
|
leanness is an *operating-system* property — the kernel and system services stay
|
||||||
|
small and statically linked, and none of them ever link the loader — while
|
||||||
|
*applications* have their own budget and may be big. Dynamic libraries are an
|
||||||
|
**application-layer facility**, full stop.
|
||||||
|
|
||||||
|
What also does **not** change: the public ABI stays the vDSO + the IPC
|
||||||
|
protocols. Shared objects are artifacts *within* one system image, versioned by
|
||||||
|
the build — not a new stable ABI surface for the OS.
|
||||||
|
|
||||||
|
## Design
|
||||||
|
|
||||||
|
- **Format and codegen are free.** ELF shared objects with position-independent
|
||||||
|
code; `zig cc -fPIC -shared` against the [libdanos-c](c-library-compatibility.md)
|
||||||
|
sysroot already emits them. The work is entirely on the loading side.
|
||||||
|
- **The loader lives in userspace, inside the libc.** `dlopen` reads the `.so`
|
||||||
|
through the VFS, maps its segments, applies relocations, resolves symbols
|
||||||
|
against the process and the `DT_NEEDED` dependency graph, runs constructors,
|
||||||
|
returns a handle. No kernel loader changes in v1 — segments land in anonymous
|
||||||
|
`mmap` as private copies.
|
||||||
|
- **Bind-now, always.** All relocations resolved at `dlopen` time
|
||||||
|
(`RTLD_NOW` semantics only). Lazy PLT binding buys startup latency danos does
|
||||||
|
not care about, at the price of a writable GOT dance and a much subtler
|
||||||
|
loader. Not worth it; keep it out permanently.
|
||||||
|
- **W^X from day one.** Map, relocate, then flip text pages read-execute —
|
||||||
|
which requires memory-protection change (`mprotect`-shaped) in the danos
|
||||||
|
`mmap` surface if it is not already there. No page is ever writable and
|
||||||
|
executable at once.
|
||||||
|
- **TLS in shared objects is deferred.** Thread-local storage models
|
||||||
|
(initial-exec vs. general-dynamic) are the deep end of every dynamic linker.
|
||||||
|
v1 refuses a `.so` with a TLS segment; revisit alongside the post-P5 pthread
|
||||||
|
subset, which is when it could matter.
|
||||||
|
- **Executables stay static until D4.** v1 is "a static binary that can
|
||||||
|
`dlopen`" — no `PT_INTERP`, no program interpreter, no dynamically-linked
|
||||||
|
`main` binaries. That keeps process startup untouched.
|
||||||
|
|
||||||
|
## Milestones
|
||||||
|
|
||||||
|
1. **D1 — dlopen in-process.** The `.so` build target; the loader in libdanos-c:
|
||||||
|
map, relocate (`RELATIVE`/`GLOB_DAT`/`JUMP_SLOT`), resolve, constructors;
|
||||||
|
`dlopen`/`dlsym`/`dlerror`/`dlclose`; private anonymous mappings; no TLS.
|
||||||
|
*Test:* QEMU `dlopen-hello` — load a `.so`, call a symbol, unload, reload.
|
||||||
|
2. **D2 — the FFI payoff.** `DT_NEEDED` dependency graphs; a **libffi port**
|
||||||
|
(x86-64 SysV assembly is upstream; the port is its closure-allocation paths,
|
||||||
|
which must respect W^X); CPython's `ctypes` enabled; extension modules
|
||||||
|
loadable from file. *Test:* QEMU — a Python script `ctypes.CDLL`s a danos
|
||||||
|
`.so` and round-trips a call; a `.so` extension module imports.
|
||||||
|
3. **D3 — actual sharing (the kernel milestone).** Shared read-only file-backed
|
||||||
|
mappings — a page-cache-shaped facility so N processes mapping `libpython`
|
||||||
|
hold one physical copy. This is the memory-win milestone and the only one
|
||||||
|
touching the kernel; design it with the existing shm machinery in view
|
||||||
|
(the shared-fate walks already locked the relevant paths). *Test:* N Python
|
||||||
|
services up; measure physical pages against N× the static baseline.
|
||||||
|
4. **D4 — dynamically-linked executables** (optional, evaluate after D3):
|
||||||
|
`PT_INTERP`, a danos program interpreter, and the spawn path teaching the
|
||||||
|
loader about it. Only worth it if the image-size or update story demands it.
|
||||||
|
|
||||||
|
## Risks and gotchas
|
||||||
|
|
||||||
|
- **Scope creep is the failure mode.** Every dynamic linker grows toward glibc.
|
||||||
|
The fences: bind-now only, no lazy binding ever, no TLS until pthreads demand
|
||||||
|
it, no dlopen-from-memory, no versioned symbols. Each fence removed is a
|
||||||
|
design discussion, not a patch.
|
||||||
|
- **Code loading is a security event.** `dlopen` turns file bytes into executable
|
||||||
|
code, so W^X discipline is table stakes and *what may be dlopened* is a
|
||||||
|
capability question — the natural danos answer is that loadability follows VFS
|
||||||
|
readability of the `.so`, and services' images are supervised like any other
|
||||||
|
artifact. Revisit explicitly at D3 when mappings become shared.
|
||||||
|
- **`dlclose` is where loaders go to die.** Constructors/destructors,
|
||||||
|
dangling function pointers, re-open identity. Keep v1 semantics honest and
|
||||||
|
simple: `dlclose` runs destructors and unmaps; holding pointers past it is
|
||||||
|
undefined; no reference-counted deferral cleverness.
|
||||||
|
- **The ReleaseSafe fact still applies to `.so`s** — a ReleaseSafe shared object
|
||||||
|
carries its inlined checks like any static code; D3's sharing saves *copies*,
|
||||||
|
not check overhead. Size expectations should be set accordingly.
|
||||||
|
|
||||||
|
## Decisions needing sign-off
|
||||||
|
|
||||||
|
- Dynamic libraries join the roadmap at all (this note exists because the
|
||||||
|
earlier size-motivated rejection was re-opened for ABI/sharing reasons).
|
||||||
|
- **Bind-now only; no lazy binding, permanently.**
|
||||||
|
- **Loader in userspace libc; kernel involvement only at D3** (shared read-only
|
||||||
|
mappings).
|
||||||
|
- **Static executables until D4**, and D4 only on demonstrated need.
|
||||||
|
|
||||||
|
## Related
|
||||||
|
|
||||||
|
- [c-library-compatibility.md](c-library-compatibility.md) — the sysroot the
|
||||||
|
loader ships in; its absence table gains `dlfcn.h` at D1.
|
||||||
|
- [python-on-danos.md](python-on-danos.md) — the `ctypes` story this unlocks.
|
||||||
|
- [python-on-danos-milestones.md](python-on-danos-milestones.md) — sequencing;
|
||||||
|
this work is post-P5.
|
||||||
|
- [os-development/memory-map.md](os-development/memory-map.md) /
|
||||||
|
[os-development/paging.md](os-development/paging.md) — where W^X and shared
|
||||||
|
mappings land.
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
# Establishment planes: the plan
|
||||||
|
|
||||||
|
*2026-08-09. The design is settled in
|
||||||
|
[communication.md](os-development/communication.md) ("Establishment: two planes, one
|
||||||
|
namespace"): driver-layer channels stop being registry names and are routed at
|
||||||
|
establishment by the device manager, which owns the topology. This converts both live
|
||||||
|
seams — `usb-transfer` and `block` — in one flag-day, and fixes the restart hole the
|
||||||
|
scoping audit found on the way. Found by a real machine: three xHCI controllers, one
|
||||||
|
name, a mouse nobody could reach.*
|
||||||
|
|
||||||
|
**Non-goals, stated up front.** fat stays single-volume (multi-volume mounting, volume
|
||||||
|
identity/content-probing, and fat's own reconnection after a storage restart are the
|
||||||
|
M21 remount track). The input service's last-writer-wins button mask across two mice
|
||||||
|
is a known quirk, not part of this change. Nothing here touches the app-facing names —
|
||||||
|
`input`, `display`, `ufs` keep their exclusive registry binds.
|
||||||
|
|
||||||
|
## What the scoping reads established
|
||||||
|
|
||||||
|
- **Capabilities already travel both directions of a synchronous call, and only
|
||||||
|
there.** Request-direction via `ipc.callCap` (r9 → `shareCapability` at server
|
||||||
|
dequeue, a refcounted copy); reply-direction via `ipc_reply_wait`'s `send_cap`
|
||||||
|
(surfaces as the client's `Reply.cap`) — init's registry is the working in-tree
|
||||||
|
precedent (`pending_capability`). Pushes structurally cannot carry one. **No kernel
|
||||||
|
change is needed.**
|
||||||
|
- **The one mechanism gap is the service harness**: `service.run` hardcodes the reply
|
||||||
|
capability to null and `Answer` has no capability slot; the device manager runs on
|
||||||
|
that harness. It needs a reply-cap out-slot following init's pattern, with null
|
||||||
|
staying the untouched default for every other service.
|
||||||
|
- **The manager already stores the routing fact**: `Child{parent, bus_address,
|
||||||
|
device_id, reporter}` — consumer's device id → `children[].reporter` →
|
||||||
|
`driverByProcess(reporter)` → the (new) stored endpoint. `Hello.role` (.bus vs
|
||||||
|
.device) already exists on the wire to distinguish provider hellos (cap up) from
|
||||||
|
consumer hellos (cap down); the manager currently never reads it.
|
||||||
|
- **The restart hole (new finding):** today, when a bus instance dies, its class
|
||||||
|
drivers are zombies — HID drivers block forever on interrupt reports that will
|
||||||
|
never come, usb-storage answers fat with errors forever; the manager respawns
|
||||||
|
neither, and the matcher's dedupe actively prevents a respawn on re-report. The
|
||||||
|
user's core goal is restart-a-driver-live; this plan closes the hole.
|
||||||
|
- **Blast radius:** every QEMU case boots from USB storage, so this seam failing
|
||||||
|
fails the whole suite, and the load-bearing serial markers (`fat: mounted
|
||||||
|
/volumes/usb`, `usb-storage: ready`, `fat-test: ok`) must not change.
|
||||||
|
|
||||||
|
## P0 — mechanics (library + manager, no behavior change yet)
|
||||||
|
|
||||||
|
1. **Harness reply-capability out-slot.** A handler nominates a capability for its
|
||||||
|
reply (init's `pending_capability` idiom moved into `service.run`'s loop); default
|
||||||
|
null; the existing Arrival take/release ownership discipline is unchanged. Every
|
||||||
|
other service compiles and behaves identically.
|
||||||
|
2. **`driver.hello` grows both directions.** Provider form: carry the caller's
|
||||||
|
serving endpoint up (`ipc.callCap`). Consumer form: return `Reply.cap`. One call
|
||||||
|
can do both (a storage driver hands its block endpoint up and receives its bus
|
||||||
|
channel down in the same hello).
|
||||||
|
3. **Manager stores and routes.** `Driver` gains an endpoint field; the cap is
|
||||||
|
claimed at `onMessage` level (the `capability_claimed` pattern usb-xhci-bus
|
||||||
|
already uses — the harness's private claim flag composes, verified). `onDriverExit`
|
||||||
|
**must** `ipc.close` the stored handle (a dead owner's endpoint survives as a
|
||||||
|
refcounted slot; repeated restarts would exhaust the manager's 32-slot table —
|
||||||
|
boot-fatal). Consumer hello with an unknown device id (bus died, not yet
|
||||||
|
re-reported) gets a *retryable* refusal, never a permanent one.
|
||||||
|
|
||||||
|
## P1 — the usb-transfer seam
|
||||||
|
|
||||||
|
- Bus: delete the `bindPatiently("usb-transfer")` block and its serve-unnamed
|
||||||
|
fallback; hello carries the endpoint up.
|
||||||
|
- `usb.open(device_id)` takes the channel from the class driver's hello instead of
|
||||||
|
the name lookup; retry patience stays ≥ today's window (the provider's hello
|
||||||
|
precedes the consumer's spawn in the normal order — the retry covers respawn races).
|
||||||
|
- usb-storage's *consumer* side uses the same lineage (its own device id).
|
||||||
|
- `protocol.csv`: delete the bind row (67) and the three open rows (119/120/122) in
|
||||||
|
the same commit as the code — grants and code move together or the old path dies
|
||||||
|
silently first.
|
||||||
|
- Fixtures: conformance table row, the usb-report kernel-side registry spawn.
|
||||||
|
|
||||||
|
## P2 — the block seam
|
||||||
|
|
||||||
|
- usb-storage: drop `.service = "block"` (the field is optional; the harness serves
|
||||||
|
nameless — pci-bus and logger already do); its `initialise` keeps the endpoint it
|
||||||
|
currently discards and hellos it up. Exit-code contract preserved: device absent =
|
||||||
|
clean exit (no restart), device-present failure = exit(1) (restart with backoff) —
|
||||||
|
establishment failure is the latter, never a silent pre-hello death like today's
|
||||||
|
second-stick `-EBUSY`.
|
||||||
|
- fat: `block.tryOpen`'s name lookup becomes manager-routed — enumerate, find the
|
||||||
|
block-class provider, hello for its channel. One volume: unambiguous. Two volumes:
|
||||||
|
fat takes the first by device-id order — deterministic within a boot, and no worse
|
||||||
|
than today's bind race; choosing *the boot volume* by content is deferred to M21
|
||||||
|
(risk noted: `/system/configuration` and `/system/logs` mounts ride this choice).
|
||||||
|
- fat gets a `protocol.csv` open grant for `device-manager`; rows 68/99 die.
|
||||||
|
- Delete `block.open` (zero callers, dead code).
|
||||||
|
|
||||||
|
## P3 — restart integrity (the zombie fix)
|
||||||
|
|
||||||
|
- **A reporter's death reaps its subtree.** When a bus/storage instance dies, the
|
||||||
|
manager already prunes its children; now it also kills the class drivers spawned
|
||||||
|
for those children and clears their entries, so the matcher's dedupe stops blocking
|
||||||
|
the respawn. On re-report (ids are stable — the `P<port>I<iface>` registration
|
||||||
|
identity), the matcher spawns fresh class drivers, which hello and receive the
|
||||||
|
successor's channel. Restart a bus driver live: the subtree rebuilds itself.
|
||||||
|
- usb-storage on `-EPEER` from its bus: exit(1) → supervisor restart with backoff →
|
||||||
|
fresh hello. (fat's own reconnection: M21.)
|
||||||
|
- Extend the existing bus-restart drill (`test-usb-restart`, the usb-report case) to
|
||||||
|
assert the subtree *works* after the restart — a post-restart keyboard event, not
|
||||||
|
just a re-report. **Discrimination: today that assertion fails (zombie).**
|
||||||
|
|
||||||
|
## P4 — the multi-instance proof
|
||||||
|
|
||||||
|
- New QEMU case: **two xHCI controllers**, keyboard on one, storage on the other;
|
||||||
|
assert both class drivers come up and function. **Discrimination: without the
|
||||||
|
conversion this case fails exactly like the Ryzen mouse** (second controller's
|
||||||
|
child unreachable). This is the machine's bug, pinned in the suite forever.
|
||||||
|
- Full suite green; the four existing second-controller cases (usb-hub and friends)
|
||||||
|
re-checked against their expectations.
|
||||||
|
- Docs updated with the code: device-manager.md, drivers.md (hello), the usb-transfer
|
||||||
|
and block protocol docblocks, device-authority.md as-built appendix.
|
||||||
|
|
||||||
|
## Order and verification discipline
|
||||||
|
|
||||||
|
P0 → P1 → P2 → P3 → P4, one commit per coherent step, suite green at every phase
|
||||||
|
boundary (P0 and P1 may share a verification run — P0 alone changes no behavior).
|
||||||
|
Every new test must be shown to fail against the old behavior before it counts
|
||||||
|
(the discrimination rule). One QEMU suite at a time. The Ryzen re-test at the end is
|
||||||
|
the acceptance run: mouse moves, and killing one bus instance from a shell one day
|
||||||
|
only blinks the devices on that controller.
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
# The danos file-system hierarchy
|
||||||
|
|
||||||
|
danos is not unix, and its tree does not follow the unix FHS. Paths are the
|
||||||
|
system's universal namespace — files, the device inventory, and protocol
|
||||||
|
endpoints all live in one tree — but what a path *yields* differs by subtree:
|
||||||
|
bytes, facts, or a connection. Root path resolution is provided by the
|
||||||
|
kernel-resident VFS root (`fs_resolve`, `system/kernel/vfs.zig`); mounted
|
||||||
|
backends serve the subtrees they own.
|
||||||
|
|
||||||
|
Naming follows the codebase conventions: kebab-case, full words, no
|
||||||
|
abbreviations. Every top-level name says what its subtree *is*.
|
||||||
|
|
||||||
|
## The tree
|
||||||
|
|
||||||
|
| Path | What it is |
|
||||||
|
|-------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||||
|
| `/` | The root of the one namespace. |
|
||||||
|
| `/applications` | Installed applications, one directory per application — the directory is the identity, the same rule as source sub-projects. *(Planned; empty today.)* |
|
||||||
|
| `/protocol` | The contract namespace: one protocol node per contract, grouped into directories by domain (`/protocol/display`, `/protocol/networking/ip`). Synthetic — no bytes; opening a name yields a connection to the current provider. See [protocol-namespace.md](../os-development/protocol-namespace.md). |
|
||||||
|
| `/system` | The operating system — what danos *is*. Its program subtrees mirror the source tree exactly. |
|
||||||
|
| `/system/kernel` | The kernel image. |
|
||||||
|
| `/system/drivers` | Driver binaries, one per sub-project (`/system/drivers/pci-bus`, `/system/drivers/ps2-bus`). |
|
||||||
|
| `/system/services` | System-service binaries (`/system/services/init`, `/system/services/fat`). |
|
||||||
|
| `/system/devices` | The device inventory: every node hardware discovery found, with its resources and parent — the structures of the devices module, as a browsable virtual tree. Informational only; you *read about* hardware here and *talk to* it through `/protocol`. *(Planned; served by device-manager.)* |
|
||||||
|
| `/system/configuration` | Machine configuration (`init.csv`, `devices.csv`). Writable, served from the boot volume. |
|
||||||
|
| `/system/logs` | Per-boot logs: `/system/logs/<boot-stamp>/<binary-path>.log`. Writable, served from the boot volume. |
|
||||||
|
| `/test` | Test fixtures for the QEMU integration suite. Read-only and initrd-backed like the program subtrees of `/system`, mirroring the repo's `test/` directory. Present on development and test images; a volume without it still boots. |
|
||||||
|
| `/volumes` | Attached storage volumes, one directory per volume (`/volumes/usb`). A volume's own tree appears beneath its name. |
|
||||||
|
|
||||||
|
Read-only and writable halves of `/system`: the program subtrees (`kernel`,
|
||||||
|
`drivers`, `services`) and the future `devices` are immutable at runtime —
|
||||||
|
initrd-backed or synthetic — while `configuration` and `logs` are mutable
|
||||||
|
machine state served by the boot-volume FAT backend. The kernel's
|
||||||
|
reserved-prefix rule (no mount may shadow `/system`, `/test`, or `/protocol`)
|
||||||
|
carves out exactly these two writable subtrees (`initrd_carve_outs` in
|
||||||
|
`system/kernel/vfs.zig`), so the boot volume mounts them while every other
|
||||||
|
`/system` path stays initrd-served.
|
||||||
|
|
||||||
|
Deliberately not defined yet: a temporary-files location and per-application
|
||||||
|
mutable storage. Both belong to the `/applications` design and will be
|
||||||
|
specified there, not guessed at here.
|
||||||
|
|
||||||
|
## Node kinds
|
||||||
|
|
||||||
|
What a path resolves to. These fill `FileStatus.kind` and
|
||||||
|
`DirectoryEntry.kind` in the [vfs protocol](vfs-protocol.md)
|
||||||
|
(`library/protocol/vfs/vfs-protocol.zig`); enum values are append-only.
|
||||||
|
|
||||||
|
| Kind | Meaning |
|
||||||
|
|--------------------|-------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||||
|
| `regular` | An ordinary file: an uninterpreted byte stream, positional reads and writes, grows on demand. |
|
||||||
|
| `directory` | A container mapping names to nodes; modified only through directory operations. |
|
||||||
|
| `character_device` | A node whose read/write have **stream semantics**: unseekable, reads block until bytes exist, size is meaningless. The console and every tty-shaped node ([character-devices-and-tty.md](../character-devices-and-tty.md)); what a POSIX layer's `isatty` detects. |
|
||||||
|
| `block_device` | A node addressed in fixed-size sectors — a raw volume. Reserved: recognized, nothing serves one yet. |
|
||||||
|
| `symbolic_link` | Reserved: a recognized value, not implemented by any backend. |
|
||||||
|
| `fifo` | Reserved for the future pipe object (wanted by the POSIX compatibility layer); not implemented. |
|
||||||
|
| `protocol` | A node naming a contract: `open` yields an IPC connection (an endpoint capability) instead of a file id — the kind of every leaf under `/protocol`. *(Being added; see protocol-namespace.md.)* |
|
||||||
|
|
||||||
|
Note the layering: `protocol` says what *opening the name* does (you get a
|
||||||
|
conversation); `character_device`/`block_device` say what *read and write
|
||||||
|
mean* on a node a provider serves you. The two compose — `/protocol/console`
|
||||||
|
is a protocol node in the registry, and the node opened over that connection
|
||||||
|
reports `character_device`, which is what gives it stream semantics. Only
|
||||||
|
`socket` is retired (its value stays reserved for wire stability): a named
|
||||||
|
rendezvous point is exactly what a protocol node is.
|
||||||
|
|
||||||
|
## What is deliberately absent
|
||||||
|
|
||||||
|
There is no `/bin`, `/boot`, `/dev`, `/etc`, `/home`, `/lib`, `/mnt`, `/sbin`,
|
||||||
|
`/srv`, `/tmp`, `/usr`, or `/var`. These encode unix history — the
|
||||||
|
binary/library split of small disks, configuration-as-scattered-text, devices
|
||||||
|
as magic files — that danos does not carry. A POSIX compatibility layer (the
|
||||||
|
Python track's mini-libc) may *present* whichever of these its programs
|
||||||
|
expect, mapped onto the real tree; the tree itself stays danos-native.
|
||||||
|
|
||||||
|
## Migration
|
||||||
|
|
||||||
|
The tree above is the specification, and the code writes it. A flag-day already
|
||||||
|
converted the unix paths it replaced:
|
||||||
|
|
||||||
|
| Was | Now | Where |
|
||||||
|
|------------------------------------------|-------------------------------------------|-----------------------------------------------------------------|
|
||||||
|
| `/etc/init.csv` | `/system/configuration/init.csv` | `system/services/init/init.zig` |
|
||||||
|
| `/etc/devices.csv` | `/system/configuration/devices.csv` | `system/services/device-manager/device-manager.zig` |
|
||||||
|
| `/var/log/...` | `/system/logs/...` | `system/services/logger/logger.zig`, the FAT server's `/var` mount |
|
||||||
|
| `/mnt/usb` | `/volumes/usb` | `system/services/fat/fat.zig`, the fat/vfs tests |
|
||||||
|
| `ServiceId` lookup | resolve + open under `/protocol` | every service and client; [protocol-namespace.md](../os-development/protocol-namespace.md) |
|
||||||
|
|
||||||
|
The boot-image builder and the on-volume directory layout moved in the same
|
||||||
|
change, so a freshly written image and the paths the services expect never
|
||||||
|
disagree.
|
||||||
@@ -0,0 +1,300 @@
|
|||||||
|
# The storage architecture: layers, boundaries, responsibilities
|
||||||
|
|
||||||
|
> **Status:** the layered model below is the settled design
|
||||||
|
> ([storage-design-rationale.md](storage-design-rationale.md) records how it was
|
||||||
|
> reached, and [volume-manager-plan.md](../volume-manager-plan.md) how it was
|
||||||
|
> built). **Built** (V0–V4 + the storage-stack S1/S2): the data path, the driver
|
||||||
|
> range confinement (per-sender clamp + the confinement gate), the `medium_changed`
|
||||||
|
> presence event, the volume manager itself — it probes the partition table,
|
||||||
|
> confines each filesystem to its partition, spawns one filesystem per volume, and
|
||||||
|
> supervises it — the removal half of the lifecycle (a pulled stick unmounts), the
|
||||||
|
> identity ladder (GPT GUID + name, FAT serial + label, MBR), and the mount map:
|
||||||
|
> `filesystems.csv` (signature → binary) + `volumes.csv` (identity → optional
|
||||||
|
> override), a volume's mount path IS its content id (`/volumes/<id>`), with the
|
||||||
|
> label as display metadata a `volumes` query returns. Multi-volume is **built**:
|
||||||
|
> the manager adopts every storage device, probes each device's whole partition
|
||||||
|
> table, and spawns one range-confined FAT per volume — several volumes across
|
||||||
|
> several devices, or several partitions sharing one device's channel — each at
|
||||||
|
> its own `/volumes/<id>` path with its own supervision. The boot volume is
|
||||||
|
> identified by **content** (a volume backs `/system/configuration` + `/system/logs`
|
||||||
|
> only when it resolves `/system/configuration` on its own media), so it works as
|
||||||
|
> any partition of any device. exFAT is **built** as a second engine
|
||||||
|
> (`system/services/exfat`): full read + write, directories, rename, and on-disk
|
||||||
|
> up-case folding, reusing `library/kernel/file-system-harness` wholesale — the
|
||||||
|
> reuse claim, proven — and a volume routes to fat or exfat by its VBR, at an
|
||||||
|
> `exfat-<serial>` id-path. Removal is robust to all three triggers now: a
|
||||||
|
> pulled device (presence polling), a medium that leaves while its device stays
|
||||||
|
> (the volume manager CONSUMES `medium_changed`), and a storage driver that
|
||||||
|
> crashes while its device stays present (a channel-liveness `geometry()` probe
|
||||||
|
> reaps the volume and rebuilds it on the restarted driver's fresh channel). The
|
||||||
|
> re-adopt-and-remount path is QEMU-proven by the driver-crash rebuild; a physical
|
||||||
|
> unplug/replug exercises the same path but is bench-pending (QEMU cannot
|
||||||
|
> re-present a usb-storage `device_add`). **Still pending**: the `filesystem UUID`
|
||||||
|
> rung (ext-family superblocks, which need such an engine); and arbitration when
|
||||||
|
> two volumes both resolve the boot markers (S3 mounts both and logs each claim;
|
||||||
|
> picking one is deferred). A few
|
||||||
|
> markers below are left where a duty is still pending.
|
||||||
|
|
||||||
|
## The model
|
||||||
|
|
||||||
|
One pattern, applied twice: an application is a client of a service over a
|
||||||
|
protocol; a service is a client of a driver over a protocol.
|
||||||
|
|
||||||
|
```
|
||||||
|
application
|
||||||
|
│ vfs protocol (routed by the kernel mount table)
|
||||||
|
▼
|
||||||
|
filesystem service ── one process per volume
|
||||||
|
│ inside: [file-protocol shell] ── Zig API ── [fs engine]
|
||||||
|
│ block protocol (channel received at spawn)
|
||||||
|
▼
|
||||||
|
storage driver ── one process per device (usb-storage per stick)
|
||||||
|
│ usb-transfer protocol (channel received via hello, by lineage)
|
||||||
|
▼
|
||||||
|
bus driver ── one process per controller (usb-xhci-bus)
|
||||||
|
│ hardware
|
||||||
|
```
|
||||||
|
|
||||||
|
Three kinds of boundary, deliberately different:
|
||||||
|
|
||||||
|
- **Protocol boundaries** sit where processes meet (vfs, block, usb-transfer).
|
||||||
|
Each side is independently restartable; channels are established by
|
||||||
|
capability handoff, never by registry names (communication.md
|
||||||
|
"Establishment: two planes"). Steady-state file I/O crosses exactly two —
|
||||||
|
vfs and block.
|
||||||
|
- **Library boundaries** sit where concerns meet inside one process. The
|
||||||
|
filesystem service's engine (on-disk format logic, host-testable, behind
|
||||||
|
the four-function `BlockDevice` vtable) and shell (IPC serving, open-node
|
||||||
|
table, mount registration) talk through a Zig API. No protocol between
|
||||||
|
them: they share fate regardless — a corrupt engine corrupts the answers
|
||||||
|
either way — so a channel there would add a hop per file operation and buy
|
||||||
|
nothing. The seam exists for compile-time testability and reuse; the
|
||||||
|
*process* is the restart unit.
|
||||||
|
- **Control-plane relationships** sit beside the data path, never on it. Two
|
||||||
|
supervisors, one per layer: the **device manager** wires and revives the
|
||||||
|
device layers (bus and storage drivers — devices only); the **volume
|
||||||
|
manager** *(built)* wires and revives the volume layer (filesystem
|
||||||
|
services). Neither touches steady-state I/O.
|
||||||
|
|
||||||
|
## Who does what
|
||||||
|
|
||||||
|
**Bus driver** (usb-xhci-bus, per controller): hardware only. Enumerates,
|
||||||
|
reports children to the device manager, serves the transfer contract to its
|
||||||
|
own children's class drivers, routed by lineage.
|
||||||
|
|
||||||
|
**Storage driver** (usb-storage, per device; later nvme, ahci): hardware →
|
||||||
|
blocks. Speaks its transport upward from its device; serves the block
|
||||||
|
protocol (geometry, read, write, flush, attach, detach — and the pushed
|
||||||
|
`medium_changed` presence event, published today from a slow TEST UNIT READY
|
||||||
|
poll; *planned*: translating it from the transport's native signal instead of
|
||||||
|
polling). **Content-blind, permanently**:
|
||||||
|
it reads block 0 only as a bring-up self-check and parses nothing — no MBR, no
|
||||||
|
GPT, no filesystem magic, ever. It has one content-blind mechanism *(built)*:
|
||||||
|
**named sub-ranges** — "serve blocks [a, b) as a channel of the
|
||||||
|
same block contract". It clamps and offsets; it never knows the numbers came
|
||||||
|
from a partition table. The clamp lives here and nowhere else because a
|
||||||
|
channel must carry exactly the authority it grants: handing a filesystem the
|
||||||
|
whole disk plus a polite base offset would let a buggy or compromised
|
||||||
|
filesystem scribble the neighboring partition — the same authority-overshoot
|
||||||
|
the device-authority track eliminated for MMIO and DMA.
|
||||||
|
|
||||||
|
**Volume manager** *(built; `system/services/volume-manager`)*: the policy home
|
||||||
|
of the volume layer, one service, supervised by init. It watches the device
|
||||||
|
manager's tree for a storage provider; when one appears it consumer-hellos for
|
||||||
|
the block channel, reads the partition table and the first blocks itself
|
||||||
|
(**it** is the prober), defines the volume's sub-range on the driver, spawns the
|
||||||
|
matching filesystem service confined to that range, and supervises it (backoff,
|
||||||
|
crash-loop cap). *(Built)*: it picks the filesystem binary from
|
||||||
|
`filesystems.csv` by the volume's content signature, and mounts the volume at its
|
||||||
|
content id (`/volumes/<id>`) — or a `volumes.csv` override. The label is display
|
||||||
|
metadata the `volumes` query returns, never the path. Those tables are CSV
|
||||||
|
configuration, read by it (the policy), enforced by nobody else:
|
||||||
|
|
||||||
|
- `filesystems.csv` *(built)* — content signature → filesystem binary. Adding
|
||||||
|
a filesystem adds a row.
|
||||||
|
- `volumes.csv` *(built)* — the mount map, danos's fstab: an OPTIONAL **volume
|
||||||
|
identity → mount prefix** override (a volume with no row mounts at its default
|
||||||
|
`/volumes/<id>`), keyed on content identity and never on port, path, or arrival
|
||||||
|
order (the lesson of Linux's `/dev/sda1`-era fstab, which broke on every
|
||||||
|
port move until `UUID=` replaced it). Identity is read off the medium by
|
||||||
|
the prober, strongest first: GPT partition GUID → filesystem UUID → FAT
|
||||||
|
serial + label → MBR signature + partition index → anonymous (generated
|
||||||
|
name, no persistence). Same identity, same mount point: a drive moved to
|
||||||
|
another port — USB to another hub, SATA to another bay, even a stick
|
||||||
|
returning in a different dock — lands exactly where it was. Duplicate
|
||||||
|
identity (cloned sticks, together) is policy: first keeps the name, the
|
||||||
|
second mounts suffixed and is logged loudly. The boot volume is the
|
||||||
|
recorded identity of the volume carrying `/system/configuration` and
|
||||||
|
`/system/logs`, findable on any port. Every volume's default mount is
|
||||||
|
`/volumes/<id>` — its rendered content identity.
|
||||||
|
|
||||||
|
**Filesystem service** (the FAT service today; one process per volume): the
|
||||||
|
proven unit — block-client + engine + file-protocol provider in one binary. It
|
||||||
|
receives its block channel at spawn; it never discovers devices. It registers
|
||||||
|
its own mounts with the kernel; its write cache lives inside the process, so a
|
||||||
|
write error is observed by the code that owns the volume and surfaces on the
|
||||||
|
owning channel (the anti-fsyncgate rule — never a system-wide dirty pool).
|
||||||
|
*(Built:)* fat receives its mount path as `argv[2]` from the volume manager (the
|
||||||
|
volume's id-path, e.g. `/volumes/fat-12345678`) and mounts its root there. It
|
||||||
|
installs the two `/system` hierarchy rewrites (`/system/configuration`,
|
||||||
|
`/system/logs`) only when it is the boot volume — decided by **content**: it
|
||||||
|
resolves `/system/configuration` on its own media at mount, so a data volume
|
||||||
|
mounts at its id-path alone and never shadows the running system. It no longer
|
||||||
|
self-acquires a volume — the V3b flip made it receive its volume id and block
|
||||||
|
channel from the volume manager, consistent with "it never discovers devices"
|
||||||
|
above. Because several volumes now serve at once, no filesystem binds a shared
|
||||||
|
service name; clients reach each through the kernel mount table (`fs_resolve`
|
||||||
|
routes by prefix to the backing endpoint).
|
||||||
|
|
||||||
|
**Kernel** (mechanism only): the mount table routes paths to backend
|
||||||
|
endpoints — resolve and redirect, never data. Remount-replace is the restart
|
||||||
|
story; a dead backend's slot is swept lazily on the next resolution.
|
||||||
|
`fs_unmount` is ownership-gated *(built, V0)* — only the mounting task may
|
||||||
|
unmount its own prefix; anyone else is refused (`EPERM`). No dead-owner
|
||||||
|
exception: a dead owner's slot is swept lazily by resolution, and restart goes
|
||||||
|
through remount-replace, never through a stranger's unmount.
|
||||||
|
|
||||||
|
## Adding a filesystem
|
||||||
|
|
||||||
|
1. **Write the engine**: pure Zig, no IPC, behind the `BlockDevice` vtable
|
||||||
|
(four functions). On-disk layout in `align(1)` extern structs. Host-test it
|
||||||
|
with `zig build test` fixtures — the FAT engine
|
||||||
|
([engine.zig](../../system/services/fat/engine.zig),
|
||||||
|
[on-disk.zig](../../system/services/fat/on-disk.zig)) is the template, and
|
||||||
|
its ~500 lines of host tests the standard.
|
||||||
|
2. **Reuse the shell**: the filesystem harness — establishment, the
|
||||||
|
badge-scoped open-node table, the nine vfs-protocol handlers, mount
|
||||||
|
registration, the removal path — is shared code, not per-filesystem code.
|
||||||
|
*(Done: extracted from fat's original 434-line shell into
|
||||||
|
`library/kernel/file-system-harness.zig`; fat imports it and instantiates
|
||||||
|
`harness.Server(engine.FileSystem)`.)* An engine plus a `main` wiring it into the
|
||||||
|
harness is a complete filesystem service.
|
||||||
|
3. **Add the configuration row**: one line in `filesystems.csv` mapping the
|
||||||
|
on-disk signature to the binary. No other component changes: the volume
|
||||||
|
manager probes, matches, spawns; the vfs protocol is already
|
||||||
|
backend-neutral (a second provider serves it in production today — init's
|
||||||
|
synthetic registry backend).
|
||||||
|
4. **Prove removal**: extend the removable-media suite (below) for the new
|
||||||
|
filesystem — surprise-yank during writes must lose only what was
|
||||||
|
unflushed, said honestly, with the volume consistent enough to remount.
|
||||||
|
|
||||||
|
The engine never sees: partitions (it receives a volume-shaped block channel;
|
||||||
|
base offsets are the driver's clamp), device discovery (the channel arrives at
|
||||||
|
spawn), mount policy (prefixes are handed to it), or other volumes (one
|
||||||
|
process, one volume).
|
||||||
|
|
||||||
|
## Removable media: responsibilities on removal, per layer
|
||||||
|
|
||||||
|
The design rule, learned from what Linux cannot do: there is exactly **one**
|
||||||
|
surprise-removal path — kill the filesystem process, retire its mounts,
|
||||||
|
respawn on return. No half-alive states, no `remount-ro`, no mounts that
|
||||||
|
error forever (Plan 9's dead-server wart).
|
||||||
|
|
||||||
|
The path folds **three triggers into one lifecycle**: the *device* leaving (a
|
||||||
|
pulled stick — presence polling); the *medium* leaving while the device stays
|
||||||
|
(an SD card pulled from its reader, an ATAPI tray opened, a USB card reader);
|
||||||
|
and a storage *driver crashing* while its device stays in the tree. The second
|
||||||
|
trigger is the pushed `medium_changed` event on the block protocol, published
|
||||||
|
from a TEST UNIT READY poll — the volume manager now **consumes** it (subscribed
|
||||||
|
per device), running the same kill-retire path and re-probing on medium return,
|
||||||
|
so a swapped card is never served with the previous card's filesystem state. The
|
||||||
|
third is caught by a channel-liveness `geometry()` probe: presence polling alone
|
||||||
|
sees the device still present, but the channel is dead, so the manager reaps the
|
||||||
|
volume and rebuilds it on the restarted driver's fresh channel. Still *planned*
|
||||||
|
is translating the transport's native signal (SCSI UNIT ATTENTION, AHCI PxSSTS,
|
||||||
|
NVMe namespace-change AER) in place of the presence poll.
|
||||||
|
|
||||||
|
| Layer | Observes | Must do | Guarantees |
|
||||||
|
|---|---|---|---|
|
||||||
|
| Bus driver | port/hub status change | tear down the device's slots (children first, recursively — built, hot-plug matrix), report `child_removed` per interface | the device tree is honest within one reconcile tick |
|
||||||
|
| Device manager | `child_removed` / reporter death | prune the child; **reap the bound driver** (built) — the storage driver for that stick dies now, not never | no zombie storage processes; re-report rebinds |
|
||||||
|
| Storage driver | its own death (it IS the removed device's driver) | nothing — dying is its removal handling; DMA/IOMMU/claims release mechanically at death | in-flight transfers fail visibly to callers, never hang |
|
||||||
|
| Volume manager *(built)* | a device leaving the tree (poll), a `medium_changed` event, or a dead channel under a still-present device (a crashed driver — `geometry()` liveness probe) | kill that volume's filesystem service (its mounts retire), then re-adopt + remount on return or on the restarted driver's fresh channel | one removal path for all three triggers; mounts never dangle; the manager never serves from behind a dead channel |
|
||||||
|
| Filesystem service | its block channel dies (`EPEER`) mid-operation, or it is killed by the volume manager | if it observes the death first: flush nothing (the medium is gone), answer in-flight requests with errors, exit; dirty write-back data is **lost and said to be lost** | the unflushed write-back window is dropped on a surprise yank — danos writes no on-disk dirty/clean-shutdown marker today; the process never serves from behind a dead channel |
|
||||||
|
| Kernel | backend endpoint death | lazy mount-slot sweep on next resolve (built); ownership-gated `fs_unmount` (built, V0) | resolution under a dead mount is `not_found`, not a hang |
|
||||||
|
| Application | `not_found` / error on paths under the vanished mount | its own error handling — the contract is honest absence, identical to the path never existing | no operation blocks forever on removed media |
|
||||||
|
|
||||||
|
**On return** the same table runs upward in reverse: the bus re-enumerates and
|
||||||
|
re-reports; the device manager respawns the storage driver (built); the volume
|
||||||
|
manager re-probes — same content, same volume identity — respawns the
|
||||||
|
filesystem service, and remounts at the same prefix; applications see the
|
||||||
|
subtree reappear. A different stick in the same port is a *different volume*
|
||||||
|
(identity is content, not port) and mounts wherever its identity says —
|
||||||
|
possibly nowhere but `/volumes/…`.
|
||||||
|
|
||||||
|
### The boot volume: identity is what makes yanking it survivable
|
||||||
|
|
||||||
|
The boot volume is the sharpest instance of the return story, because the
|
||||||
|
system's own log persistence rides it (`/system/logs`), and because nothing
|
||||||
|
else about the running system depends on it at all — every binary and the
|
||||||
|
boot-time configuration live in the initial ramdisk. Its lifecycle,
|
||||||
|
end to end:
|
||||||
|
|
||||||
|
- **At first mount** the volume manager records the identity of the volume
|
||||||
|
carrying `/system/configuration` and `/system/logs` — THE boot volume,
|
||||||
|
from then on a fact about content, not about a port.
|
||||||
|
- **While it is absent**, the system runs on. The kernel log ring keeps
|
||||||
|
accumulating — it is the buffer that makes the absence survivable — and
|
||||||
|
the logger keeps draining it; only *persistence* pauses. File operations
|
||||||
|
under the retired mounts fail honestly (`not_found`). The ring is bounded,
|
||||||
|
so a long absence overwrites its oldest entries: that window is the data
|
||||||
|
loss, and it must be *said* — the logger marks the gap in the file when
|
||||||
|
persistence resumes, never splicing the stream silently.
|
||||||
|
- **On return — any port, any hub, even a different transport** — the
|
||||||
|
prober reads the same identity, the mount map answers with the same
|
||||||
|
prefixes, the filesystem service is respawned, and `/system/logs` is the
|
||||||
|
same tree it was: the logger resumes appending into the SAME
|
||||||
|
`<boot-stamp>` directory, per-binary files continuing where they left
|
||||||
|
off (plus the gap marker if the ring wrapped).
|
||||||
|
- **What never comes back** is the write-back window lost at the yank —
|
||||||
|
the dirty-honesty rule, unchanged; the boot volume gets no exemption.
|
||||||
|
|
||||||
|
This is also the requirement that shapes the logger: it treats the log tree
|
||||||
|
as a volume that comes and goes — failed flushes are retried on the same
|
||||||
|
patient cadence the fat service already uses for storage that arrives late,
|
||||||
|
never abandoned after the first `not_found`.
|
||||||
|
|
||||||
|
What is lost on a surprise yank is exactly the write-back window of the
|
||||||
|
filesystem service, no more: the engine owns its cache, so the blast radius of
|
||||||
|
a yank is one volume's unflushed writes, which are simply lost — danos records
|
||||||
|
no on-disk dirty/clean-shutdown bit yet. A
|
||||||
|
filesystem format with better crash honesty (journaling, copy-on-write — the
|
||||||
|
lesson of QNX's Power-Safe) narrows that window further and slots in as
|
||||||
|
implementation N+1 through the table above, changing nothing else.
|
||||||
|
|
||||||
|
## How the lifecycle is enforced
|
||||||
|
|
||||||
|
Responsibility tables are convention; convention is worthless (the bounds
|
||||||
|
audit's lesson). The volume lifecycle is enforced with the same three levers
|
||||||
|
the device lifecycle already uses, mapped one-to-one:
|
||||||
|
|
||||||
|
1. **A filesystem cannot acquire — it can only be given.** Filesystem
|
||||||
|
binaries hold NO establishment grants: no `open device-manager`, no
|
||||||
|
registry name to look up. The only block channel a filesystem process ever
|
||||||
|
has is the one handed to it at spawn by the volume manager. Serving the
|
||||||
|
wrong volume, a second volume, or a self-discovered volume is not
|
||||||
|
forbidden but *impossible* — the same way a driver cannot claim hardware
|
||||||
|
it was not delegated (device-authority.md).
|
||||||
|
2. **The volume manager supervises with teeth.** Mount-within-deadline or be
|
||||||
|
stopped (a filesystem wedged on a corrupt volume is killed and crash-loop
|
||||||
|
capped; the volume is marked bad, not retried forever). On removal the
|
||||||
|
manager KILLS the filesystem process and retires its mounts — the polite
|
||||||
|
observe-`EPEER`-and-exit path is an optimization; the kill is the
|
||||||
|
guarantee, because a process cannot be trusted to observe its own
|
||||||
|
obsolescence (the reap argument, proven on the device tree).
|
||||||
|
3. **The shared harness is how every filesystem inherits the lifecycle by
|
||||||
|
construction.** The harness — not the engine — owns the state machine:
|
||||||
|
establishment at spawn, mount registration, the flush-on-close hook (an
|
||||||
|
in-memory device-dirty check that commits the device write cache on close),
|
||||||
|
error-out-and-exit on channel death. The engine sits behind the
|
||||||
|
four-function vtable and never sees a channel; it cannot opt out of the
|
||||||
|
lifecycle for the same reason it cannot find a device. This is why the
|
||||||
|
harness is extracted BEFORE the second engine is written.
|
||||||
|
|
||||||
|
Beneath all three, two kernel mechanisms: ownership-gated `fs_unmount` (only
|
||||||
|
the mounting endpoint's holder may unmount), and the lazy dead-endpoint mount
|
||||||
|
sweep as the backstop nothing can disable. And above them, the check: a
|
||||||
|
**lifecycle conformance drill** — mount, serve, yank mid-write, verify honest
|
||||||
|
loss, replug, remount — parameterized over filesystem implementations, so
|
||||||
|
"danos supports filesystem X" MEANS "X passes the drill through the harness",
|
||||||
|
exactly as provider conformance means passing the reserved-verb suite.
|
||||||
@@ -0,0 +1,267 @@
|
|||||||
|
# The storage design rationale: why the stack is shaped this way
|
||||||
|
|
||||||
|
*2026-08-09. The design record behind
|
||||||
|
[storage-architecture.md](storage-architecture.md): the survey, the
|
||||||
|
trade-offs, and the decisions with their reasons — kept so future changes
|
||||||
|
argue against the evidence rather than rediscovering it. The questions that
|
||||||
|
drove it, verbatim: should the block protocol be separate from the VFS? how
|
||||||
|
do channels work with these block devices? how should we wire up different
|
||||||
|
filesystems? Grounded in how Minix 3, QNX Neutrino, Fuchsia, Redox, Plan 9,
|
||||||
|
and Linux each answered the same questions, and in exactly where our own
|
||||||
|
seams sat. The layering rule it serves: drivers are the lowest level
|
||||||
|
(hardware only); VFS and the filesystems are higher layers; the protocol
|
||||||
|
layer routes between them.*
|
||||||
|
|
||||||
|
## What the survey says, compressed
|
||||||
|
|
||||||
|
**Everyone separates block from VFS.** Even Plan 9, which unifies the *protocol*
|
||||||
|
(a disk is a file tree), keeps the layers: kernel `sd` serves raw ranges,
|
||||||
|
user-space filesystem servers consume them and serve files. The two poles are
|
||||||
|
Minix 3 (every layer a process: one VFS server, one filesystem server *per
|
||||||
|
mounted volume*, driver processes below — driver crashes proven survivable by
|
||||||
|
fault-injection, tens of thousands of injected faults) and QNX (filesystems as
|
||||||
|
DLLs inside the disk-driver process — fastest path, but one corrupt volume takes
|
||||||
|
every volume behind that controller down). Fuchsia is the modern capability-
|
||||||
|
native reference: a tiny block contract that every layer speaks, control channel
|
||||||
|
separate from a data fast-path with pre-registered buffers, filesystems as
|
||||||
|
separate processes launched by a storage-policy component (`fshost`) that probes
|
||||||
|
content and hands each filesystem its block channel at startup. The filesystem
|
||||||
|
never discovers devices.
|
||||||
|
|
||||||
|
**Partition tables are parsed in user space, below the filesystem, above the
|
||||||
|
raw device — never in the kernel, never in the filesystem engine.** Fuchsia
|
||||||
|
tried partitions-as-drivers and formally reversed it (RFC-0257). Plan 9 has the
|
||||||
|
cleanest split of all: the kernel offers only a *mechanism* — "create a named
|
||||||
|
sub-range of this disk" — and a user-space prober parses the table and issues
|
||||||
|
those commands. QNX (`io-blk`) and Minix (driver-side shared library) agree on
|
||||||
|
placement: the block layer multiplexes one physical block object into several
|
||||||
|
logical block objects **of the same contract**.
|
||||||
|
|
||||||
|
**The failure lessons are unanimous.** Linux's shared page cache across the
|
||||||
|
filesystem boundary produced fsyncgate (write errors observed by the wrong
|
||||||
|
process, dirty pages marked clean); the lesson is to keep write caching *inside*
|
||||||
|
the filesystem process, so an error surfaces on the channel that owns the
|
||||||
|
volume. Linux's `errors=remount-ro`/lazy-unmount half-alive states exist because
|
||||||
|
a monolith cannot kill and respawn a filesystem; Plan 9 leaves dead servers'
|
||||||
|
mounts in the namespace erroring forever. A restartable-parts system should have
|
||||||
|
exactly one surprise-removal path: kill the filesystem process, retire its
|
||||||
|
mounts, respawn on return. QNX's deepest lesson: after years of removable-media
|
||||||
|
pain they concluded detection isn't enough and built a copy-on-write filesystem
|
||||||
|
(Power-Safe) — *format-level* crash honesty. And QNX's `mcd` (a standalone
|
||||||
|
policy daemon with declarative insertion/removal rules) plus Fuchsia's `fshost`
|
||||||
|
agree that media policy is one dedicated component, not code scattered through
|
||||||
|
filesystems.
|
||||||
|
|
||||||
|
## Where we already stand
|
||||||
|
|
||||||
|
Closer than expected. The block protocol is 61 lines, five verbs, and its
|
||||||
|
docblock already reserves `Header.target` for volumes ("targets = volumes,
|
||||||
|
`enumerate` lists them; nothing else about the protocol changes"). usb-storage
|
||||||
|
is content-blind — it reads block 0 only as a bring-up self-check and parses
|
||||||
|
nothing. The vfs protocol is already served by a second provider in production
|
||||||
|
(init's registry serves it synthetically), so a second filesystem is *not* a
|
||||||
|
protocol problem. The FAT service is already internally split: a host-testable
|
||||||
|
engine (1659 + 310 lines) behind a four-function BlockDevice vtable, and a
|
||||||
|
434-line IPC shell. The kernel mount table already has the right restart
|
||||||
|
semantics (remount-replace; lazy dead-endpoint sweep on resolve).
|
||||||
|
|
||||||
|
The misplacements, all small: the MBR walk lives *inside the FAT engine*
|
||||||
|
(`engine.zig:196-212`) — every future engine would duplicate it; fat hardcodes
|
||||||
|
its acquisition policy ("first mass-storage child, mount at /volumes/usb") —
|
||||||
|
that is policy in a filesystem binary; `fs_unmount` is gated by nothing (any
|
||||||
|
process may unmount any prefix — latent now, an obvious cross-tenant hole once
|
||||||
|
mounts multiply); and fat's `mounted` flag is one-way — no path back after its
|
||||||
|
block channel dies.
|
||||||
|
|
||||||
|
## The proposed shape
|
||||||
|
|
||||||
|
Three layers, matching the stated rule, every boundary a channel:
|
||||||
|
|
||||||
|
**Block (driver layer, mechanism).** usb-storage stays hardware→blocks and
|
||||||
|
content-blind. It gains one mechanism, Plan 9's: *named sub-ranges*. A
|
||||||
|
`define_range`-style op creates a logical block object (a partition) clamped
|
||||||
|
and offset onto the disk; sub-ranges are `target` ids on the same endpoint, or
|
||||||
|
separate endpoints handed out per range — either way they speak the **same
|
||||||
|
block contract** (Fuchsia's closed-under-layering rule), so a filesystem cannot
|
||||||
|
tell whole-disk from partition. The driver never parses a table; it clamps
|
||||||
|
ranges it is told about. Offsets translate at definition time, so the data path
|
||||||
|
stays one hop (Fuchsia's session-mapping trick, for free).
|
||||||
|
|
||||||
|
**Volumes (service layer, policy).** One new service — the *volume manager*
|
||||||
|
(fshost/mcd-shaped, init-supervised; the device manager stays devices-only). It
|
||||||
|
subscribes to the device manager's `child_added`/`child_removed`, consumer-
|
||||||
|
hellos for each new mass-storage provider's block channel, reads the partition
|
||||||
|
table and the first blocks itself (the prober is policy), consults
|
||||||
|
configuration — `filesystems.csv`: content signature → filesystem binary;
|
||||||
|
`mounts.csv` or similar: volume identity → mount prefix — defines sub-ranges on
|
||||||
|
the driver, spawns **one filesystem process per volume**, hands it its block
|
||||||
|
channel at startup, and supervises it with the reap-and-rebuild idiom the
|
||||||
|
device manager proved: provider dies or medium leaves → kill the filesystem
|
||||||
|
process, retire its mounts; medium returns → re-probe, respawn, remount. The
|
||||||
|
boot volume is chosen by *content* (which volume carries /system/configuration
|
||||||
|
and /system/logs), closing the two-sticks question honestly.
|
||||||
|
|
||||||
|
**Filesystems (per volume, one process).** The proven unit everywhere from
|
||||||
|
Plan 9's `dossrv` to Minix to Fuchsia: block-client + engine + file-protocol
|
||||||
|
provider in one binary, one process per volume (9front practice; per-volume
|
||||||
|
fault isolation is what our supervision makes cheap). fat's shell became a
|
||||||
|
shared *filesystem harness* library (`library/kernel/file-system-harness`), and
|
||||||
|
the second engine — **exFAT**, `system/services/exfat` — now reuses it wholesale:
|
||||||
|
the reuse this design promised, proven. exfat is nothing but the exFAT engine +
|
||||||
|
a near-clone of fat's thin service, full read + write + directories + rename +
|
||||||
|
on-disk up-case folding, differing only in the format it wraps. A partition walk
|
||||||
|
lives in the volume manager (`partition.zig`), which recognizes fat vs exFAT by
|
||||||
|
VBR and routes each to its engine; write caching stays inside the process (the
|
||||||
|
anti-fsyncgate rule). Each mounts its prefixes into the kernel mount table
|
||||||
|
itself. Two surface limits are shared across both engines and are the vfs
|
||||||
|
layer's, not an exFAT shortcut: file offsets are u32 (a 4 GiB addressable cap),
|
||||||
|
and file names are ASCII bytes (a non-ASCII unit becomes `?`) — teaching the vfs
|
||||||
|
name layer UTF-8 is a separate cross-cutting change.
|
||||||
|
|
||||||
|
**Kernel: two small changes only.** `fs_unmount` gains ownership (only the
|
||||||
|
mounting endpoint's holder may unmount — possession-is-capability, consistent
|
||||||
|
with everything else), and the 8-slot mount table gets a declared bound or
|
||||||
|
growth once volumes multiply. The mount table stays the router; per-process
|
||||||
|
namespaces (Plan 9's extra) remain separable future work.
|
||||||
|
|
||||||
|
## Transport generality: NVMe and SATA against this design
|
||||||
|
|
||||||
|
The layering was chosen transport-agnostic on purpose (the 9front lesson:
|
||||||
|
filesystem services cannot tell a USB stick from an ATA disk); NVMe and AHCI
|
||||||
|
are the test of that claim, and they fit — with three named pressure points.
|
||||||
|
|
||||||
|
**What transfers untouched:** the block protocol (nothing USB in it), the
|
||||||
|
volume manager, partitions/ranges, filesystems, mounts, and the whole
|
||||||
|
enforcement stack — delegation, IOMMU confinement (these are first-party PCI
|
||||||
|
DMA masters, so confinement applies even more directly than USB),
|
||||||
|
reap-and-rebuild, the hot-plug lifecycle. Integration cost per transport is
|
||||||
|
what the architecture promises: one driver binary plus one `devices.csv` row.
|
||||||
|
|
||||||
|
**NVMe** shortens the stack — no bus/class split; the driver IS the
|
||||||
|
controller driver, one hop fewer than USB. Its structural novelty,
|
||||||
|
**namespaces** (hardware-native multiple volumes behind one controller), is
|
||||||
|
exactly the case the block protocol reserved on day one — still reserved, not
|
||||||
|
implemented (pressure point 1 below): decision 4 settles per-volume addressing
|
||||||
|
as per-sender confinement on a single endpoint, and names endpoint-per-volume
|
||||||
|
only as an unbuilt future refactor. **AHCI** is a shape choice, not a problem: an
|
||||||
|
HBA fronts up to 32 ports plus port multipliers — structurally a bus — so
|
||||||
|
either mirror USB (ahci-bus + a per-port disk driver: maximum restart
|
||||||
|
granularity, the proven shape) or mirror NVMe (one driver per controller, one
|
||||||
|
block channel per port). Leaning per-port processes for consistency with the
|
||||||
|
matrix-proven shape; genuinely open.
|
||||||
|
|
||||||
|
**The pressure points, honestly:**
|
||||||
|
|
||||||
|
1. **Multi-volume is built; multi-namespace-per-provider is untried.** The
|
||||||
|
volume manager adopts every device and spawns one range-confined FAT per
|
||||||
|
partition — several volumes across several devices, or several partitions
|
||||||
|
sharing one device's channel, both proven on USB. What is untried is a single
|
||||||
|
provider exposing several volumes as *namespaces* (NVMe): the endpoint and
|
||||||
|
per-badge range machinery generalizes, but no such driver exists yet to
|
||||||
|
exercise it.
|
||||||
|
2. **The current transport will bottleneck NVMe.** Synchronous call/reply,
|
||||||
|
one operation in flight, one bounce buffer — fine for a USB2 stick,
|
||||||
|
forfeits an NVMe drive's queue depth and per-queue MSI-X. Correctness
|
||||||
|
needs nothing; performance is gated on the shm-ring data plane
|
||||||
|
communication.md already names (Fuchsia's FIFO+VMO is the precedent).
|
||||||
|
NVMe is not worth building before that milestone.
|
||||||
|
3. **Media lifecycle ≠ device lifecycle.** ATAPI trays and SD card readers
|
||||||
|
(USB ones too, today) keep the DEVICE present while the MEDIUM comes and
|
||||||
|
goes — a removal trigger our channel-death lifecycle does not carry. The
|
||||||
|
fix is decision 7 below. (Related small item: fat's bounce sizing
|
||||||
|
hardcodes 512-byte sectors; 4Kn drives need the geometry honored
|
||||||
|
throughout.)
|
||||||
|
|
||||||
|
## The decisions on the table
|
||||||
|
|
||||||
|
1. **Partitions as driver-side sub-ranges** (mechanism in usb-storage, parsing
|
||||||
|
in the volume manager) — versus a separate partition *process* re-serving
|
||||||
|
block (Fuchsia's storage-host). Sub-ranges are ~20 lines of clamp in the
|
||||||
|
driver and keep the data path one hop; a separate process is purer layering
|
||||||
|
at the cost of a hop or session plumbing. Recommendation: sub-ranges.
|
||||||
|
2. **The volume manager as a new service** owning probe, spawn, supervision,
|
||||||
|
and mount policy — with `filesystems.csv` and the mount map as
|
||||||
|
configuration. Recommendation: yes; it is the missing policy home that fat
|
||||||
|
is currently squatting in.
|
||||||
|
3. **One filesystem process per volume** (fat's binary becomes "the FAT
|
||||||
|
implementation", spawned per FAT volume). Recommendation: yes — it extends
|
||||||
|
recompile-and-restart-live to filesystems and isolates corrupt media.
|
||||||
|
4. **Sub-range addressing — SETTLED as per-sender confinement at the
|
||||||
|
provider, one serving endpoint.** The deciding argument is precedent: the
|
||||||
|
xHCI bus already serves every class driver on one endpoint with authority
|
||||||
|
scoped by the kernel-stamped badge (the per-client device-token table) —
|
||||||
|
that IS danos's provider pattern, and per-badge range confinement is the
|
||||||
|
same pattern applied to blocks. The volume manager sets each filesystem
|
||||||
|
process's range on the driver; the driver clamps AND translates every
|
||||||
|
transfer by the sender's range, so filesystems address volume-relative
|
||||||
|
LBAs from 0. On the confined path the FAT engine's `base_lba` therefore
|
||||||
|
resolves to 0 on every access; the field and the engine's own MBR walk
|
||||||
|
remain in `engine.zig` as now-inert legacy code (the authoritative partition
|
||||||
|
walk lives in the volume manager's `partition.zig`), not yet deleted.
|
||||||
|
The enforcement point (the clamp at the provider, never in the consumer)
|
||||||
|
is what carries the security property; endpoint-per-volume would deliver
|
||||||
|
the same property only by inventing a multi-endpoint harness the pattern
|
||||||
|
does not need. It stays available as a future refactor if a multi-endpoint
|
||||||
|
harness ever exists for other reasons; the wire contract is identical
|
||||||
|
either way.
|
||||||
|
5. **`fs_unmount` ownership** — a defect fix more than a decision.
|
||||||
|
6. **Later, kept open**: the shm-ring data plane (communication.md already
|
||||||
|
names it as the 256-byte ceiling's unlock — Fuchsia's FIFO+VMO is the
|
||||||
|
precedent); format-level crash honesty (a Power-Safe-style journaling or COW
|
||||||
|
filesystem) once danos outgrows FAT; per-process namespaces.
|
||||||
|
7. **The media-presence event** (the consuming half is BUILT; the
|
||||||
|
transport-native signal stays future): the block protocol carries a pushed
|
||||||
|
event — `medium_changed`, with present/absent and a change counter —
|
||||||
|
produced today by the storage driver from a TEST UNIT READY poll (the
|
||||||
|
transport's native signal — SCSI UNIT ATTENTION, PxSSTS for AHCI,
|
||||||
|
namespace-change AER for NVMe — is the future refinement in place of the
|
||||||
|
poll) and now **consumed** by the volume manager, which subscribes per
|
||||||
|
device and runs the SAME kill-retire-remount path it runs on channel death.
|
||||||
|
The driver reports presence, never content; a pushed event carries no
|
||||||
|
capability, which the kernel already guarantees. The device staying while
|
||||||
|
its medium leaves is the one removable-media case the channel-death trigger
|
||||||
|
cannot see; without this event a swapped SD card would be served with the
|
||||||
|
old card's filesystem state. A THIRD trigger closes the last gap — a
|
||||||
|
storage driver that *crashes* while its device stays present: channel death
|
||||||
|
there is invisible to presence polling, so the volume manager probes channel
|
||||||
|
liveness (`geometry()`) each tick and reaps-then-rebuilds the volume on the
|
||||||
|
restarted driver's fresh channel. One lifecycle, three triggers.
|
||||||
|
8. **Volume identity, and the mount map as danos's fstab** (settled). The
|
||||||
|
lesson is Linux's own history: fstab keyed on `/dev/sda1` for years and
|
||||||
|
broke whenever a drive changed ports or enumeration order; `UUID=` entries
|
||||||
|
exist because device-path identity failed. danos skips that era: the mount
|
||||||
|
map (`volumes.csv` — configuration, read by the volume manager) keys on
|
||||||
|
**content identity, never port or discovery order**. Build status: rungs 1,
|
||||||
|
3, and 4 (GPT partition GUID, FAT serial + label, MBR signature + index) are
|
||||||
|
implemented (S1); rung 2 waits on a non-FAT engine. The `volumes.csv` map and
|
||||||
|
the id-derived mount path are built (S2): a volume's mount path IS its content
|
||||||
|
id (`/volumes/<id>`, e.g. `/volumes/fat-12345678`), or a `volumes.csv`
|
||||||
|
override; the label is display metadata a `volumes` query returns, never the
|
||||||
|
path. The ladder the prober reads off the medium, strongest first:
|
||||||
|
1. GPT partition GUID — 128-bit, unique, stable for the volume's life — **built (S1)**;
|
||||||
|
2. filesystem UUID (ext-family and most modern formats, in the superblock) *(planned)*;
|
||||||
|
3. FAT volume serial + label — 32 bits, weak (dd-cloned sticks share it)
|
||||||
|
but what real sticks carry — **built (S1)**;
|
||||||
|
4. MBR disk signature + partition index — **built**; a bare FAT with no
|
||||||
|
table takes index 0 over the whole device;
|
||||||
|
5. nothing — an anonymous volume: generated mount name, no persistence *(planned)*.
|
||||||
|
|
||||||
|
Consequences, each mechanical once identity keys the map: **moving a drive
|
||||||
|
to a different port changes nothing** — same identity, same mount point,
|
||||||
|
whether USB port, hub depth, SATA port, or a stick that left as USB and
|
||||||
|
returned in a SATA dock; **replug remounts at the same path** (the id-path is
|
||||||
|
content-derived, so a volume returns to `/volumes/<id>` wherever it reappears;
|
||||||
|
the re-adopt+remount code path is QEMU-proven by the driver-crash rebuild, but
|
||||||
|
remount on a *physical* replug end-to-end is bench-pending, not QEMU-testable,
|
||||||
|
because QEMU can't re-present the boot-controller device); **the boot volume** is the volume
|
||||||
|
that resolves `/system/configuration` on its own media, findable on any port or
|
||||||
|
partition; and **duplicate identity is a known S4 gap** — two cloned sticks
|
||||||
|
share one content id, so today they collide on `/volumes/<id>` (the kernel
|
||||||
|
remount-replaces; the last wins) and each boot-volume claim is logged loudly.
|
||||||
|
Distinguishing them with a suffix is arbitration, deferred to S4. Unknown identities
|
||||||
|
mount under a derived name (sanitized label, else generated) at
|
||||||
|
`/volumes/<name>` — the hierarchy's documented home for attached media,
|
||||||
|
which stands: `/system` is what danos IS; attached media is what it isn't.
|
||||||
|
danos never needs to MINT identifiers to detect volumes — detection only
|
||||||
|
reads — until it grows formatting, which brings the entropy question and
|
||||||
|
is deliberately out of scope here.
|
||||||
@@ -0,0 +1,251 @@
|
|||||||
|
# The VFS wire protocol
|
||||||
|
|
||||||
|
> **Status:** built and spoken today between `file_system` (the client) and the
|
||||||
|
> filesystem BACKENDS (the FAT server). The mount router lives in the
|
||||||
|
> **kernel** (`system/kernel/vfs.zig`): `fs_resolve` routes a path and either
|
||||||
|
> serves it directly (the read-only /system initrd mount, via `fs_node`) or
|
||||||
|
> redirects the caller to the owning backend's endpoint plus the rewritten
|
||||||
|
> mount-relative path — after which the client speaks THIS protocol to the
|
||||||
|
> backend, unchanged. Since P4a the contract is expressed through
|
||||||
|
> `envelope.Define` (docs/os-development/protocol-namespace.md), so every
|
||||||
|
> packet begins with the universal 16-byte prefix and the open-node id rides
|
||||||
|
> in it. The Zig source of truth is `library/protocol/vfs/vfs-protocol.zig`
|
||||||
|
> (the `vfs-protocol` module), whose unit test pins a sample of the sizes
|
||||||
|
> and values below. This page is the **language-neutral wire specification**
|
||||||
|
> of that contract — what a Rust or C client implements ([vdso.md](../os-development/vdso.md)
|
||||||
|
> explains why the IPC protocols, not the syscall numbers, are danos's
|
||||||
|
> public ABI).
|
||||||
|
|
||||||
|
## Transport
|
||||||
|
|
||||||
|
A VFS exchange is one synchronous IPC rendezvous (`ipc_call`,
|
||||||
|
docs/ipc.md): the client sends one message and blocks; the server replies
|
||||||
|
with one message. The endpoint comes from the kernel's `fs_resolve` — which
|
||||||
|
also hands back the path rewritten relative to the mount — not from a
|
||||||
|
registry lookup. (Service id 1, the old userspace router, is retired.)
|
||||||
|
|
||||||
|
- A message is at most **256 bytes** (`message_maximum`).
|
||||||
|
- Every packet begins with the 16-byte **envelope prefix**
|
||||||
|
([protocol-namespace.md](../os-development/protocol-namespace.md)): a
|
||||||
|
`Header` on a request, a `Status` on a reply. The prefix is **folded, not
|
||||||
|
stacked** — the verb and the object being addressed live in it, and no
|
||||||
|
request or reply below repeats either.
|
||||||
|
- A request is the header, then the verb's own fixed part (0–16 bytes), then
|
||||||
|
an inline tail of at most **224 bytes** (`maximum_payload`) — a path, or
|
||||||
|
write bytes. There is no multi-message request: paths and single
|
||||||
|
reads/writes must fit, and larger transfers loop (see *read* / *write*).
|
||||||
|
- A reply is the status, then the verb's own fixed part, then an inline tail
|
||||||
|
— read bytes, or a directory entry's name.
|
||||||
|
- All integers are **little-endian**; layouts are C layout for x86-64
|
||||||
|
(`extern struct`), offsets given below so nothing need be inferred.
|
||||||
|
|
||||||
|
The kernel resolves NAMES (the mount table) but never parses these
|
||||||
|
messages — it moves the bytes; file state is entirely the backend's affair.
|
||||||
|
With clients holding backend node ids directly, a backend records each open
|
||||||
|
handle's owner and sweeps a dead client's handles via the published process
|
||||||
|
exit events.
|
||||||
|
|
||||||
|
## Request header — 16 bytes
|
||||||
|
|
||||||
|
The envelope's `Header`, identical in every danos protocol:
|
||||||
|
|
||||||
|
| offset | size | field | meaning |
|
||||||
|
|-------:|-----:|-------|---------|
|
||||||
|
| 0 | 4 | `operation` | an **Operation** value (below); 0–15 are the reserved universal verbs |
|
||||||
|
| 4 | 4 | — | padding |
|
||||||
|
| 8 | 8 | `target` | **the open-node id** from a prior `open`; 0 for `open` itself and the path-based verbs |
|
||||||
|
|
||||||
|
## Reply header — 16 bytes
|
||||||
|
|
||||||
|
The envelope's `Status`:
|
||||||
|
|
||||||
|
| offset | size | field | meaning |
|
||||||
|
|-------:|-----:|-------|---------|
|
||||||
|
| 0 | 4 | `status` | **0 = success**, negative = failure (signed) |
|
||||||
|
| 4 | 4 | — | padding |
|
||||||
|
| 8 | 4 | `len` | reply bytes following this header: the verb's fixed part plus its tail |
|
||||||
|
| 12 | 4 | — | padding |
|
||||||
|
|
||||||
|
A failing backend replies with the status alone (`len` = 0) and no fixed
|
||||||
|
part, and that reply reaches the client directly — there is no party between
|
||||||
|
them on the wire. (Kernel-served paths produce no wire replies at all:
|
||||||
|
`fs_resolve`/`fs_node` failures are syscall register statuses.) The errno
|
||||||
|
vocabulary is the kernel's, continued by the envelope: `ENOENT` = 4 is what a
|
||||||
|
backend answers for anything it cannot find or cannot do, `ENOSYS` = 10 for a
|
||||||
|
verb it does not implement, `EPROTO` = 11 for a packet shorter than the verb
|
||||||
|
it names. Clients must treat *any* negative status as failure rather than
|
||||||
|
matching a particular one.
|
||||||
|
|
||||||
|
## Operations
|
||||||
|
|
||||||
|
Values number from 16 (`first_protocol_operation`) in declaration order, and
|
||||||
|
are frozen once shipped. Values 0–15 are the envelope's reserved universal
|
||||||
|
verbs, which mean the same thing at every provider in the system: `describe`
|
||||||
|
(0) answers the protocol's name and version and is implemented by the
|
||||||
|
envelope itself, so every backend answers it. A verb outside this table is
|
||||||
|
answered `-ENOSYS`; it is never a safety check any more, because the
|
||||||
|
dispatch compares numbers rather than decoding an enum.
|
||||||
|
|
||||||
|
Each row's *request* and *reply* name the bytes **after** the 16-byte prefix.
|
||||||
|
|
||||||
|
| value | operation | request | tail | reply | reply tail |
|
||||||
|
|------:|-----------|---------|------|-------|-----------|
|
||||||
|
| 16 | `open` | `flags` (4 bytes, below) | the path | `node` (8 bytes) = the open-node id | — |
|
||||||
|
| 17 | `close` | — | — | — | — |
|
||||||
|
| 18 | `read` | `offset` (8), `len` (4) = wanted count | — | — | the bytes read; `Status.len` 0 at end of file |
|
||||||
|
| 19 | `write` | `offset` (8), `len` (4) = count | the bytes | `count` (4) = bytes accepted (may be short — loop) | — |
|
||||||
|
| 20 | `status` | — | — | **FileStatus** (24 bytes) | — |
|
||||||
|
| 21 | `readdir` | `cursor` (8) | — | one **DirectoryEntry** (16 bytes) | the name |
|
||||||
|
| 22 | `mount` | — | the mount-point path; the backend endpoint rides as the call's **capability** | — | — |
|
||||||
|
| 23 | `unmount` | — | the mount-point path | — | — |
|
||||||
|
| 24 | `mkdir` | — | the path | — | — |
|
||||||
|
| 25 | `unlink` | — | the path | — | — |
|
||||||
|
| 26 | `rename` | — | old path, one `0x00`, new path | — | — |
|
||||||
|
| 27 | `bind` | — | the contract name; the provider's endpoint rides as the call's **capability** | — | — |
|
||||||
|
|
||||||
|
Notes per operation:
|
||||||
|
|
||||||
|
- **open** — the path is the mount-relative path `fs_resolve` handed back
|
||||||
|
(absolute-shaped: `/notes.txt` under fat's `/volumes/usb` mount). Bare names
|
||||||
|
(`greeting`) resolve nowhere — the flat ramfs is retired, and `fs_resolve`
|
||||||
|
refuses non-absolute paths. The returned `node` is the *backend's* own
|
||||||
|
open-node id: with the router in the kernel there is no forwarding table,
|
||||||
|
and clients hold backend ids directly (see *Lifetimes and trust*). Every
|
||||||
|
later packet carries it in `Header.target` — the path is spoken once, here,
|
||||||
|
and integers do the rest.
|
||||||
|
- **read / write** — a single exchange moves at most 224 bytes
|
||||||
|
(`maximum_payload`); the client loops, advancing its own offset by what
|
||||||
|
came back, until done (read) or the slice is written (write). A `write`
|
||||||
|
reply shorter than requested is progress, not an error; a count of 0 means
|
||||||
|
no forward progress — stop rather than spin.
|
||||||
|
- **readdir** — `cursor` is the **entry index**, not a byte position. Each
|
||||||
|
call returns exactly one entry; the client increments the cursor by 1. **A
|
||||||
|
`name_len` of 0 is end-of-directory** — the reply's own length cannot say
|
||||||
|
so, because the envelope always sends the fixed reply part. The directory
|
||||||
|
must have been opened with the `directory` flag.
|
||||||
|
- **mount / unmount** — RETIRED from the wire: mounting is the `fs_mount`
|
||||||
|
syscall now (a filesystem server passes its endpoint handle; possession is
|
||||||
|
the capability, exactly the trust of the old cap-passing op). The verb
|
||||||
|
numbers stay reserved. Mount-prefix semantics are unchanged: prefixes
|
||||||
|
match at path boundaries only (`/volumes/usb` never captures
|
||||||
|
`/volumes/usbextra`), the longest matching prefix wins, and an optional
|
||||||
|
backend-side rewrite prefix maps a mount into the backend's namespace (fat
|
||||||
|
serves `/volumes/usb` from its volume root and `/system/logs` from its
|
||||||
|
`/system/logs` subtree).
|
||||||
|
- **rename** — same-directory rename only: the backend compares the old and
|
||||||
|
new parent paths and refuses a mismatch. The client (`file_system`) refuses
|
||||||
|
earlier when the two paths resolve to different backend endpoints, but that
|
||||||
|
check is coarser than "one mount" — one endpoint can serve several mounts
|
||||||
|
(fat serves `/volumes/usb`, `/system/configuration` and `/system/logs`), so
|
||||||
|
a cross-mount rename reaches the backend and fails on its same-directory
|
||||||
|
check.
|
||||||
|
- **bind** — the protocol registry's claim verb, implemented only by the
|
||||||
|
synthetic `/protocol` backend inside PID 1
|
||||||
|
([protocol-namespace.md](../os-development/protocol-namespace.md)). A file
|
||||||
|
backend answers `-ENOSYS`.
|
||||||
|
|
||||||
|
## Open flags
|
||||||
|
|
||||||
|
Bitwise OR in `open`'s `flags`, meaningful for `open` only:
|
||||||
|
|
||||||
|
| bit | name | meaning |
|
||||||
|
|----:|------|---------|
|
||||||
|
| 1 | `create` | create the file if it does not exist |
|
||||||
|
| 2 | `directory` | open a directory node for `readdir` rather than a file |
|
||||||
|
| 4 | `truncate` | truncate an existing file to zero length on open (replace, don't overwrite in place) |
|
||||||
|
|
||||||
|
## FileStatus — 24 bytes (the `status` reply's fixed part)
|
||||||
|
|
||||||
|
| offset | size | field | meaning |
|
||||||
|
|-------:|-----:|-------|---------|
|
||||||
|
| 0 | 8 | `size` | file size in bytes |
|
||||||
|
| 8 | 4 | `kind` | a **NodeKind** value |
|
||||||
|
| 12 | 4 | — | padding |
|
||||||
|
| 16 | 8 | `mtime` | modification time, Unix epoch seconds UTC; 0 if the backend keeps none |
|
||||||
|
|
||||||
|
## DirectoryEntry — 16 bytes + name (the `readdir` reply)
|
||||||
|
|
||||||
|
| offset | size | field | meaning |
|
||||||
|
|-------:|-----:|-------|---------|
|
||||||
|
| 0 | 4 | `kind` | a **NodeKind** value |
|
||||||
|
| 4 | 4 | `name_len` | length of the name that follows; **0 means end of directory** |
|
||||||
|
| 8 | 8 | `size` | the entry's size in bytes |
|
||||||
|
| 16 | `name_len` | name | the entry's name, not NUL-terminated |
|
||||||
|
|
||||||
|
## NodeKind
|
||||||
|
|
||||||
|
Aligned to the node-kind table in the file-system hierarchy
|
||||||
|
(docs/file-system-development/file-system-hierarchy.md):
|
||||||
|
|
||||||
|
| value | kind |
|
||||||
|
|------:|------|
|
||||||
|
| 0 | regular file |
|
||||||
|
| 1 | directory |
|
||||||
|
| 2 | character device |
|
||||||
|
| 3 | block device |
|
||||||
|
| 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,
|
||||||
|
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. 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
|
||||||
|
nothing permanently: the backend (the FAT server) subscribes to the kernel's
|
||||||
|
published process-exit events (docs/process-lifecycle.md) and releases a dead
|
||||||
|
client's handles. The kernel VFS root needs no sweep at all — its node tokens
|
||||||
|
are permanent for a boot and carry no open state.
|
||||||
|
|
||||||
|
Ids are plain integers rather than capabilities, so the backend **scopes them
|
||||||
|
to the caller's badge**: an open node belongs to the task that opened it, and
|
||||||
|
every verb that names one — read, write, status, readdir, close — is answered
|
||||||
|
only for that task. A node id is a small number drawn from a table of
|
||||||
|
thirty-two, trivially guessable, and until this rule a backend honoured every
|
||||||
|
client's ids from every other client
|
||||||
|
(docs/os-development/protocol-namespace.md: *handles must be scoped per
|
||||||
|
client — validated against the badge, or drawn from a per-client id
|
||||||
|
namespace*).
|
||||||
|
|
||||||
|
The refusal is deliberately **identical to absence**: a node that is somebody
|
||||||
|
else's answers `-ENOENT`, exactly as one that was never opened, so a prober
|
||||||
|
learns nothing about which ids are live — the same discipline the protocol
|
||||||
|
namespace applies to a refused open. The owner is a *task*, because the badge
|
||||||
|
is: a threaded client uses a node from the thread that opened it, which is
|
||||||
|
already the granularity of the exit sweep that releases it.
|
||||||
|
|
||||||
|
## Evolution rules
|
||||||
|
|
||||||
|
What a non-Zig implementation may rely on, and what it must not:
|
||||||
|
|
||||||
|
- Operation values, flag bits, `NodeKind` values, and struct layouts are
|
||||||
|
**append-only and frozen once shipped**. The unit test in
|
||||||
|
`library/protocol/vfs/vfs-protocol.zig` pins a sample of them (the
|
||||||
|
`DirectoryEntry` size, `NodeKind` 0–1 and 6–7, `Operation` values 16–21, 26
|
||||||
|
and 27); this page is the full record of the frozen values.
|
||||||
|
*The one renumbering this contract has had was the rebase onto the envelope
|
||||||
|
(P4a), which moved every verb above the reserved range — a deliberate
|
||||||
|
flag-day across a system with no third-party clients yet, not a precedent.*
|
||||||
|
- The 256-byte message ceiling is a property of the current IPC transport,
|
||||||
|
not a promise; clients should read `maximum_payload`-shaped limits from the
|
||||||
|
reply lengths they actually get (loop-until-done), not hard-code 224.
|
||||||
|
- Success is exactly 0, and the negative statuses come from one system-wide
|
||||||
|
errno vocabulary (the kernel's, continued by the envelope) rather than from
|
||||||
|
this protocol.
|
||||||
@@ -0,0 +1,403 @@
|
|||||||
|
# Fixed-bounds audit
|
||||||
|
|
||||||
|
*2026-08-07. A tree-wide audit of every compile-time ceiling on a runtime quantity,
|
||||||
|
commissioned after an AMD Ryzen desktop booted to a working compositor with no USB
|
||||||
|
and no storage. Seven parallel sweeps, adversarial verification of each finding, and
|
||||||
|
a completeness critic. 235 bounds confirmed.*
|
||||||
|
|
||||||
|
The audit was not commissioned to fix that machine. It was commissioned to answer a
|
||||||
|
different question: **why did a machine have to find this?** The answer is in the
|
||||||
|
first table below, and it is not that anyone failed to predict an AMD desktop.
|
||||||
|
|
||||||
|
## What the audit found
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Bounds confirmed | **235** |
|
||||||
|
| Decided by hardware or external data, not by us | **139** (59%) |
|
||||||
|
| Recorded in `system/parameters.zig` | **5** (2%) |
|
||||||
|
| With no comment explaining the number at all | **97** (41%) |
|
||||||
|
| Silent when exceeded — no log, no counter, no error | **171** (73%) |
|
||||||
|
| Severity critical / high | **17 / 26** |
|
||||||
|
|
||||||
|
The project has a stated convention: tunables live in `system/parameters.zig` with
|
||||||
|
their reasoning attached. Two percent of them do. That is the finding — not any
|
||||||
|
individual number.
|
||||||
|
|
||||||
|
And 59% of these are not tunables at all. They are guesses about someone else's
|
||||||
|
computer: how many PCI functions a board has, how many SSDTs its firmware ships,
|
||||||
|
how many descriptors its memory map carries, how many interfaces a USB headset
|
||||||
|
declares. A fixed bound on a quantity the machine decides is not a knob. It is a
|
||||||
|
defect with a plausible-looking number in it.
|
||||||
|
|
||||||
|
## Why "raise the number" is not available
|
||||||
|
|
||||||
|
This is the part that matters most, and it was found by the completeness critic
|
||||||
|
rather than by any of the seven sweeps.
|
||||||
|
|
||||||
|
`system/kernel/iommu.zig:97` sizes the per-device confinement table by
|
||||||
|
`maximum_domains = 64` — "64 mirrors devices-broker's device cap" — and indexes it
|
||||||
|
by **device id**. Line 107:
|
||||||
|
|
||||||
|
```zig
|
||||||
|
pub fn confineDevice(device_id: u64, bdf: u16, owner: u32) bool {
|
||||||
|
if (!active) return true;
|
||||||
|
if (device_id >= confined.len) return true; // unusual id; leave it to fail-open
|
||||||
|
```
|
||||||
|
|
||||||
|
It returns `true` — success — without confining the device. The doc comment three
|
||||||
|
lines above states the opposite invariant: *"a claim that can't be confined must not
|
||||||
|
stand."*
|
||||||
|
|
||||||
|
Device ids are assigned `d.id = count` with `count < maximum_devices`, so today ids
|
||||||
|
run 0–63 and that branch is unreachable. **It becomes reachable the moment
|
||||||
|
`maximum_devices` is raised above 64.** Every device with id ≥ 64 would then be
|
||||||
|
claimed by a ring-3 driver, reported as successfully confined, and left outside every
|
||||||
|
IOMMU domain — an unconfined DMA master with a driver holding it.
|
||||||
|
|
||||||
|
So the one-line fix for the Ryzen — raise 64 to 512 — is a privilege escalation. Not
|
||||||
|
inelegant: escalating. Nothing in the type system, the tests or the comments would
|
||||||
|
have caught it, because the two constants agree only by a sentence in a comment.
|
||||||
|
|
||||||
|
## The Ryzen was three bugs, not one
|
||||||
|
|
||||||
|
Each of these independently produces "the xHCI and SATA controllers are missing."
|
||||||
|
Fixing any one of them leaves the machine broken by the next.
|
||||||
|
|
||||||
|
1. **`devices-broker.zig:33`, `maximum_children_per_parent = 16`** — `pci-bus`
|
||||||
|
registers *every* discovered function as a direct child of the one host bridge, so
|
||||||
|
16 is the ceiling on PCI functions for the whole machine. Enumeration runs in
|
||||||
|
bus/device/function order, so low-numbered chipset functions consume all 16 and the
|
||||||
|
high-numbered controllers — xHCI at 0x14, SATA at 0x17 — are refused. This is the
|
||||||
|
one that fired.
|
||||||
|
2. **`device-manager.zig:174`, `maximum_children = 64`** — the *userspace* inventory
|
||||||
|
has its own flat table. ACPI contributes ~34 nodes before PCI is scanned. Refusal
|
||||||
|
returns `-ENOSPC`, which `pci-bus.zig:246` discards and `acpi.zig:257` swallows in
|
||||||
|
an empty `catch {}`. The log line "child added" is printed *before* the status is
|
||||||
|
consulted, so the log says the device was added when it was not.
|
||||||
|
3. **`acpi.zig:651`, `gaps = [3]Range`** — only three sub-4 GiB MMIO holes become PCI
|
||||||
|
bridge apertures. A BAR landing in a fourth hole fails containment and is refused,
|
||||||
|
indistinguishably from a full table.
|
||||||
|
|
||||||
|
Three ceilings, three teams of one, one symptom. "Raise the limit" would have moved
|
||||||
|
the failure to the next one and produced a second debugging session from a second
|
||||||
|
photograph.
|
||||||
|
|
||||||
|
## Two latent security findings
|
||||||
|
|
||||||
|
**`acpi.zig:627`, `below = [64]Range`.** Firmware memory-map entries below 4 GiB, used
|
||||||
|
to derive the PCI bridge's apertures *from the gaps between described regions*. Past the
|
||||||
|
64th entry: `continue`. A dropped region is not merely missing — it vanishes from the
|
||||||
|
"described space" the gap-finder subtracts, so occupied physical memory is concluded to
|
||||||
|
be a free MMIO hole and registered as a bridge aperture. `devices-broker.contains()`
|
||||||
|
then admits a child BAR covering RAM, and its claimant can `mmio_map` it: a ring-3
|
||||||
|
read/write window onto kernel memory. Real UEFI maps carry 60–200 descriptors; OVMF
|
||||||
|
carries 15–25, which is why the suite has never approached it.
|
||||||
|
|
||||||
|
**`devices-broker.zig:217`, the PCI requester id is a `u16`** with no segment field,
|
||||||
|
propagated unbroken into both IOMMU backends. On a multi-segment machine two physically
|
||||||
|
distinct functions alias onto one translation structure.
|
||||||
|
|
||||||
|
Both are the same shape as the finding above: a bound whose failure mode is not "we run
|
||||||
|
out" but "the protection silently stops applying."
|
||||||
|
|
||||||
|
## Bugs found in passing
|
||||||
|
|
||||||
|
Not bounds, but found by looking at what happens at the bound:
|
||||||
|
|
||||||
|
- **`usb-xhci-library.zig:1331`** — `else if (device.interface_count < max_interfaces)`
|
||||||
|
has no `else`, so at the limit `current` is left pointing at interface 3 and the 5th
|
||||||
|
interface's endpoints are appended to interface 3's array. A class driver bound to
|
||||||
|
interface 3 can be handed an endpoint belonging to another interface. The
|
||||||
|
alternate-setting arm one line above does `current = null` correctly.
|
||||||
|
- **`usb-xhci-library.zig:899/1102`** — `allocateDevice()` failing returns after
|
||||||
|
`enableSlot()` already succeeded, with no Disable Slot. Every failed attempt
|
||||||
|
permanently leaks a controller slot.
|
||||||
|
- **`acpi.zig:445`** — the AML loop reserves `maximum_resources - 2` slots and the
|
||||||
|
function then adds **four** more resources. At 5 AML blocks the FADT is lost; at 6+
|
||||||
|
the broad IRQ window is lost too, so every legacy-IRQ device (PS/2 keyboard at IRQ 1)
|
||||||
|
fails containment. Real firmware ships 5–15 SSDTs; QEMU ships 2.
|
||||||
|
- **`fat.zig:252`** — a `u64` protocol offset reaches a `u32` engine parameter through a
|
||||||
|
bare `@intCast`. In ReleaseSafe — this project's build mode — that panics.
|
||||||
|
- **`boot/efi.zig:318`** — the bootstrap page tables map [0, 4 GiB) and nothing checks
|
||||||
|
that the handoff buffers UEFI allocated (BootInformation, the memory-map pool, the
|
||||||
|
initial ramdisk) landed below it. Several firmware implementations allocate top-down.
|
||||||
|
Above 4 GiB it is a triple fault with no output at all.
|
||||||
|
|
||||||
|
## Headroom actually measured
|
||||||
|
|
||||||
|
Every other bound here is hypothetical. One is a schedule:
|
||||||
|
`system/configuration/protocol.csv`, the manifest deciding which binary may bind which
|
||||||
|
protocol name, is at **50 of 64 grant rows and 12,668 of 16,384 bytes** — 78% and 77%.
|
||||||
|
|
||||||
|
To its credit, both overflow paths log (`init.zig:147` and `:238`). It will fail
|
||||||
|
loudly. It will still fail.
|
||||||
|
|
||||||
|
## The rule this suggests
|
||||||
|
|
||||||
|
The audit's own exemplar turned out to be broken, which is worth recording. Two sweeps
|
||||||
|
held up `devices_broker.dropped` as the model the others should be rewritten against.
|
||||||
|
It is not: `register()` never increments it, and `kernel.zig:203` reads it once at boot
|
||||||
|
*before* `seedDisplay` and long before any ring-3 driver exists. It can only report
|
||||||
|
firmware-discovery losses — precisely the opposite of the runtime case under audit.
|
||||||
|
|
||||||
|
`parameters.maximum_cpus` is the one bound that meets the standard: hardware-determined
|
||||||
|
and bounded, but it states what happens to the surplus (parked) and how you find out
|
||||||
|
(`platform.cpusDropped()` → a WARNING at `kernel.zig:281`). Verified.
|
||||||
|
|
||||||
|
So:
|
||||||
|
|
||||||
|
1. **A fixed bound on a quantity the hardware or an external file decides is a defect,
|
||||||
|
not a tunable.** It does not need a better number; it needs to not be fixed. This
|
||||||
|
covers 139 of the 235.
|
||||||
|
2. **A bound that must exist states three things**: what it protects against, what the
|
||||||
|
system does when it is reached, and how an operator finds out. One of 235 does.
|
||||||
|
3. **Refusal must be attributable.** `process.zig:944` collapses five distinct
|
||||||
|
`RegisterError` variants into a bare `-1`; `pci-bus` can only log "register refused"
|
||||||
|
with no reason. Half this audit's difficulty was that the machine could not say
|
||||||
|
which ceiling it hit.
|
||||||
|
4. **Two constants that must agree may not agree by comment.** `maximum_domains = 64`
|
||||||
|
and `maximum_devices = 64` are coupled by prose, and the coupling fails open.
|
||||||
|
|
||||||
|
## Appendix: the inventory
|
||||||
|
|
||||||
|
Sorted by severity, then file. `Decided by` is the audit's judgment of who chooses the
|
||||||
|
quantity — the machine, an external file or peer, or us.
|
||||||
|
| File:line | Bound | Value | Decided by | At the limit | Observable |
|
||||||
|
|---|---|---|---|---|---|
|
||||||
|
| `boot/efi.zig:318` | <inline literal> (4 * gib) | 4 GiB | hardware | No check exists. buildBootstrapTables maps [0, 4 GiB) as identity + physmap 2 MiB leaves and stops; the only carve-out is the framebuffer window at ef… | Nothing on this path. No log, no error, no panic. The last thing printed is the unconditional con_out line at … |
|
||||||
|
| `library/device/model/device-abi.zig:81` | maximum_device_resources | 8 | hardware | Silent drop, but at a different site than claimed. The live enforcement is system/kernel/device-model.zig:114 `if (self.resource_count >= maximum_reso… | None on any drop path, and the code says otherwise: device-model.zig:111-112 claims "Silently drops beyond `ma… |
|
||||||
|
| `system/drivers/pci-bus/pci-bus.zig:228` | device.register refusal path (kernel maximum_chi… | 16 children per parent / 64 … | hardware | system/kernel/devices-broker.zig:305 `if (childCount(parent_id) >= maximum_children_per_parent) return error.TooManyChildren;` and :306 `if (count >= … | One line per lost function: `std.log.info("register refused for {d}:{d}.{d}", .{ bus, dev, function })` (pci-b… |
|
||||||
|
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:227` | max_interfaces | 4 | external-data | CORRECTION to this claim's description: it is not only a silent drop. `parseConfiguration` (1326-1342) has no else on `else if (device.interface_count… | None. usb-xhci-bus.zig:368/425 log `{d} interface(s)` with the truncated count; nothing says any were dropped … |
|
||||||
|
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:333` | max_devices | 8 | hardware | Two different behaviours, exactly as claimed. Root port, `setupDevice` (899-902): `const device = self.allocateDevice() orelse { std.log.info("port {d… | Root ports: one log line. Hub-attached: nothing. I confirmed the leak is real — the only Disable Slot in the f… |
|
||||||
|
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:1304` | <inline literal> blob: [512]u8 | 512 | external-data | Silent truncation of device-supplied data. Lines 1304-1307: `var blob: [512]u8 = undefined; const length = @min(configuration.total_length, blob.len);… | None. `configuration.total_length` is read at 1299 and never compared to `blob.len`, never logged. The `{d} in… |
|
||||||
|
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:1305` | blob (inline [512]u8, declared line 1304) | 512 bytes | external-data | Silent truncation of externally-supplied data. The @min clamps the GET_DESCRIPTOR request to 512; parseConfiguration then walks it and stops dead at l… | Nothing. No log line, no counter, no comparison of configuration.total_length against blob.len. The symptom is… |
|
||||||
|
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:1331` | max_interfaces (= 4), used as `else if (device.i… | 4 | external-data | CORRUPTING, not merely dropping. When interface_count == 4, neither branch of the if/else-if runs, so `current` is NOT cleared — it still points at in… | Nothing. No log, no counter, no error. The device enumerates, `port N device: ... 4 interface(s)` is logged (a… |
|
||||||
|
| `system/kernel/acpi.zig:445` | <inline literal> device_model.maximum_resources … | 6 AML blocks, inside an 8-re… | hardware | Silent double loss. The loop stops at 6 blocks, so SSDTs 7+ are never published. Then acpi.zig:454-463 adds the io_port grant (7th), the SCI irq (8th)… | Nothing at all. No counter, no log, no error. The ring-3 acpi service simply finds an acpi-tables node without… |
|
||||||
|
| `system/kernel/acpi.zig:445` | device_model.maximum_resources - 2 (inline expre… | 6 AML blocks, out of 8 total… | hardware | Silent drop, then a silent cascade. Resources are appended in order: up to 6 AML memory resources (445-448), io_port (454), the SCI irq (459), the bro… | Nothing at the kernel. The only downstream trace is the acpi service writing "acpi: no FADT on the node — powe… |
|
||||||
|
| `system/kernel/acpi.zig:627` | below | [64]Range | hardware | Silent skip: `if (region.base >= (1 << 32) or below_count == below.len) continue;`. Every region past the 64th is treated as 'not described', i.e. as … | None directly, though kernel.zig:133 does print `" regions : {d} - entries in the firmware memory map"`, w… |
|
||||||
|
| `system/kernel/acpi.zig:627` | below (inline [64]Range) | 64 entries | hardware | Silent drop, and — worse than a drop — a corrupted result. A dropped region is not merely missing from the list; it disappears from the "described spa… | Nothing at all. No counter, no log line. The kernel prints the device tree including the bogus aperture, with … |
|
||||||
|
| `system/kernel/acpi.zig:651` | gaps | [3]Range | hardware | Silent replacement of the smallest kept gap (acpi.zig:658-664): a fourth (or fifth) MMIO hole is simply forgotten. A PCI function whose BAR lands in a… | Nothing. No log, no counter, and the resulting failure is indistinguishable at the caller from a table-full re… |
|
||||||
|
| `system/kernel/device-model.zig:66` | maximum_resources | 8 | external-data | `addResource` (line 113-118) returns false without recording. I grepped every call site: system/kernel/acpi.zig lines 448, 454, 459, 460, 463, 552, 55… | Nothing at the drop. Downstream there are two ring-3 lines that name the symptom and misattribute the cause: s… |
|
||||||
|
| `system/kernel/devices-broker.zig:33` | maximum_children_per_parent | 16 | hardware | Confirmed at devices-broker.zig:305: `if (childCount(parent_id) >= maximum_children_per_parent) return error.TooManyChildren;`, where `childCount` (28… | One reasonless line per lost device, and nothing from the kernel. Confirmed at pci-bus.zig:228-231: `const reg… |
|
||||||
|
| `system/services/acpi/acpi.zig:129` | blocks | [8][]const u8 | external-data | The `blocks: [8][]const u8` array at line 129 and its `if (block_count == blocks.len) continue;` at line 152 are dead — they can never fire, because t… | Only an indirect count that cannot reveal the loss: `std.log.info("parsed {d} AML blob(s), {d} namespace devic… |
|
||||||
|
| `system/services/device-manager/device-manager.zig:174` | maximum_children | 64 | hardware | Silent drop with a misleading log. `addChild` (180-194) returns false when no free slot exists. `onChildAdded` (442-452): `if (!addChild(...)) status … | Effectively none, and actively misleading. The -ENOSPC goes back to the bus driver, which discards it — verifi… |
|
||||||
|
| `boot/efi.zig:108` | <inline literal> (handles[0]) | 1 | hardware | Silent selection of GOP handle 0, and the two halves genuinely disagree — nativeResolution (efi.zig:167-176) iterates `for (handles) \|h\|` over every… | Nothing. No log names the handle count, the chosen adapter, or the resolved mode; the only con_out writes in t… |
|
||||||
|
| `library/device/driver/driver.zig:149` | <inline literal> | @min(total, buffer.len) | hardware | Silently searches a prefix: `const total = enumerate(buffer); const n = @min(total, buffer.len); for (@as([]DeviceDescriptor, buffer[0..n])) \|d\| { …… | Nothing. The discarded `total` is the only evidence that the buffer was too small, and it is thrown away on th… |
|
||||||
|
| `library/kernel/file-system.zig:227` | Entry.name_buffer | [64]u8 | external-data | Silent truncation on both readdir paths, exactly as claimed. Backend path, Directory.next line 264-266: `const nlen = @min(@min(@as(usize, header.name… | Nothing. No log, no flag, no short-count anywhere in library/kernel/file-system.zig. Entry.name() returns a pl… |
|
||||||
|
| `system/drivers/virtio-gpu/virtio-gpu.zig:49` | max_width / max_height (line 50) | 800 x 600 | hardware | Two distinct behaviours, and the claim conflates their visibility. (a) onSetMode, line 533-540: `if (w == 0 or h == 0 or w > max_width or h > max_heig… | Partial and misleading, as claimed. Confirmed the two adjacent lines: `std.log.info("EDID preferred mode {d}x{… |
|
||||||
|
| `system/kernel/architecture/x86_64/cpu.zig:489` | irq_vector_count | 14 | hardware | irq.zig:138 allocVector() scans base..base+count for a vector free of both an MSI binding and a GSI binding and returns null when none is; bind (irq.z… | No kernel log line. Driver-side, both messages verified: usb-xhci-bus.zig:279 `std.log.info("msi_bind unavaila… |
|
||||||
|
| `system/kernel/architecture/x86_64/idt.zig:17` | gate_count | 48 | our-design | Nothing is enforced at this line. `pub fn init()` at line 136 does `inline for (0..gate_count) \|vector\| { const stub = @extern(*const anyopaque, .{ … | None at runtime. The bound only ever becomes visible as the vector-exhaustion path in irq.zig, which each driv… |
|
||||||
|
| `system/kernel/architecture/x86_64/ioapic.zig:21` | base (module-level singleton) | 1 I/O APIC | hardware | Confirmed exactly. system/kernel/acpi.zig:547-556 adds EVERY MADT I/O APIC record to the device tree as ioapic0, ioapic1, ...; kernel.zig:545-548 then… | None. No log counts the discarded units, unlike the neighbouring drop counters that ARE logged (devices_broker… |
|
||||||
|
| `system/kernel/architecture/x86_64/iommu-amd.zig:56` | ring_entries (event log) | 256 | hardware | Confirmed. faultDrain (lines 180-198) reads EventHead/EventTail, walks the ring wrapping at `if (head >= ring_entries * 16) head = 0;`, and writes the… | None. I grepped the file: `const reg_status = 0x2020;` appears at line 32 and at NO other line — it is declare… |
|
||||||
|
| `system/kernel/architecture/x86_64/iommu-intel.zig:102` | <inline literal> 16 * 1024 | 16384 (bytes of VT-d registe… | hardware | No check. `faultDrain` computes `frcd_base = fro*16` with fro up to 0x3FF (16368 bytes) and `nfr = ((cap >> 40) & 0xFF) + 1` up to 256 registers of 16… | A kernel-mode #PF: the fault handler reports the vector/CR2 and halts the core. Loud, but reported as a page f… |
|
||||||
|
| `system/kernel/architecture/x86_64/iommu.zig:17` | Discovery.register_base (single unit) | 1 IOMMU unit | hardware | Confirmed. `pub const Discovery = struct { register_base: u64, amd: bool };` at iommu.zig:16-19 carries exactly one base. Intel (acpi.zig:826-852): th… | Asymmetric, exactly as claimed. Intel warns: system/kernel/iommu.zig:395-396 `if (info.iommu_extra_units > 0) … |
|
||||||
|
| `system/kernel/devices-broker.zig:25` | maximum_devices | 64 | hardware | Three inconsistent behaviours, all confirmed. Boot discovery: devices-broker.zig:111-114 `if (count >= maximum_devices) { dropped += 1; return device_… | Partial and aimed at the wrong path, exactly as claimed. kernel.zig:203-206 prints `"/system/kernel: WARNING {… |
|
||||||
|
| `system/kernel/iommu.zig:43` | maximum_domains | 64 | hardware | Two behaviours. Domain exhaustion is safe: `domainCreate` returns null → `confineDevice` false → process.zig:418-420 rolls the claim back and returns … | The rollback path is visible as a failed `device_claim`. The fail-open path is completely silent — no log, no … |
|
||||||
|
| `system/kernel/irq.zig:43` | maximum_gsi | 24 | hardware | Refusal at three places, all becoming a bare -1. irq.zig:158 `if (gsi >= maximum_gsi or !architecture.irqOwnsGsi(gsi)) return error.BadGsi;` -> proces… | Nothing in the kernel, but every caller logs: ps2-bus.zig:246 and :265, acpi.zig:315 "acpi: SCI irq_bind faile… |
|
||||||
|
| `system/kernel/irq.zig:139` | allocVector over architecture.irq_vector_count | 14 (vectors 33..46, from arc… | hardware | `fn allocVector() ?u8` (line 139) scans v in [irq_vector_base, irq_vector_base + irq_vector_count) = [33, 47) — 14 vectors — and returns null when all… | Better than claimed at the driver level, absent at the kernel level. The kernel logs nothing and has no counte… |
|
||||||
|
| `system/kernel/process.zig:546` | maximum_dma_regions | 256 | hardware | Confirmed, and the safety-invariant break is real. process.zig:549-556 `fn dmaRegistryAdd(object: ?*ipc.DmaRegionObject, physical: u64, len: u64, owne… | None whatsoever — confirmed. `dma_alloc` returns success, no log, no counter, no failed syscall. The symptom i… |
|
||||||
|
| `system/kernel/scheduler.zig:546` | maximum_tasks (via freeSlot in secondaryMain) | 48 (parameters.maximum_tasks… | hardware | Confirmed: `const t = freeSlot() orelse @panic("sched: task table full (AP idle task)");` at scheduler.zig:546, reached from `secondaryMain` with the … | A named panic on console/serial — loud, but the machine is dead and the message points at the task table rathe… |
|
||||||
|
| `system/kernel/vfs.zig:58` | maximum_mounts | 8 | our-design | FALSE SUCCESS plus a reference leak, confirmed end to end. installMount, vfs.zig:182: `const m = slot orelse return;` — it gives up silently when no s… | Worse than nothing: the syscall reports success, so the mounting service logs its own success — system/service… |
|
||||||
|
| `system/kernel/vfs.zig:86` | maximum_directories | 8 | external-data | Silent skip inside the boot walk: `if (directoryIndex(parent) == null and directory_count < maximum_directories)` (vfs.zig:141). An unregistered direc… | Nothing. No log, no counter, no `dropped` variable of the kind acpi.zig:542 and the device manager both mainta… |
|
||||||
|
| `system/kernel/vfs.zig:141` | maximum_directories (declared line 86) | 8 | external-data | Silent drop with a mount-level knock-on, confirmed. The ninth distinct ancestor is skipped by the guard at vfs.zig:141; it then fails to resolve (reso… | Nothing — no counter, no log line, no `dropped` variable of the sort acpi.zig:542 (cpu_information.dropped, pr… |
|
||||||
|
| `system/kernel/vfs.zig:182` | maximum_mounts (declared line 58) | 8 | our-design | False success, confirmed: installMount gives up at vfs.zig:182 (`const m = slot orelse return;`) and mountBackend returns true regardless at vfs.zig:3… | Nothing in the kernel. The mounting service logs its own success — fat.zig:173/:178/:183 all `std.log.info("mo… |
|
||||||
|
| `system/services/acpi/acpi.zig:542` | buffer (readHid) / Registered.hid / Notice.hid | [8]u8 | external-data | Both failures confirmed. (a) readHid (lines 540-566) accepts only an integer _HID it can EISA-decode: a method result must be `.integer`, and a static… | None for (a): a skipped device produces no line at all. For (b) the log at line 408, `std.log.info("power: not… |
|
||||||
|
| `system/services/acpi/acpi.zig:648` | descriptor.resources.len | 8 (maximum_device_resources,… | external-data | Silent drop of the surplus. `fn addResource(descriptor: *device.DeviceDescriptor, kind: device.ResourceKind, start: u64, len: u64) void { if (descript… | Nothing at the drop. The only echo is the per-device summary at line 241, `std.log.info("device {d} bus=acpi … |
|
||||||
|
| `system/services/device-manager/device-manager.zig:149` | maximum_drivers | 16 | hardware | `addDriver` (240-254) walks for a free slot and, finding none, falls through the loop to `std.log.info("driver table full; cannot supervise {s}", .{na… | One log line only (quoted above). No counter, no status to any caller, and it lands amid the stream of `child … |
|
||||||
|
| `system/services/device-manager/device-manager.zig:358` | <inline literal> | 64 | hardware | Silent truncation. Line 362-363: `const total = device.enumerate(buffer); const count = @min(total, buffer.len);` — the difference is computed and thr… | Nothing. No log mentions `total`. The only related line, `"/system/services/device-manager: no matchable devic… |
|
||||||
|
| `system/services/fat/fat.zig:73` | open_nodes | 32 | our-design | An error is returned, but a maximally confusing one: `const index = allocOpen() orelse return refused;` (line 242), where `refused` is `-envelope.ENOE… | Nothing on the server side — no log at all in allocOpen or onOpen. The client sees ENOENT and will report "fil… |
|
||||||
|
| `system/services/fat/fat.zig:252` | <inline literal> | u32 (via @intCast of a u64 p… | external-data | Panic. `vfs_protocol.Read.offset` is a `u64` (library/protocol/vfs/vfs-protocol.zig:82-86) and `engine.readFile` takes `offset: u32`; the bridge is a … | A process fault and whatever the supervisor logs about the death; nothing identifies the offending request or … |
|
||||||
|
| `boot/efi.zig:371` | maximum_bundled | 64 | external-data | Two different behaviours for one constant, confirmed. loadByManifest (efi.zig:507): `if (count.* == maximum_bundled) return;` — silent success with th… | Manifest path: nothing. Walk path: the unconditional con_out line at efi.zig:71-75, `log("EFI: no /system bina… |
|
||||||
|
| `boot/efi.zig:375` | maximum_tree_depth | 3 | our-design | `if (depth == maximum_tree_depth) continue;` (efi.zig:580) — the subdirectory is silently skipped and nothing beneath it is bundled. No error, no coun… | Nothing. The boot proceeds; the missing binary surfaces much later as an init spawn failure or a device-manage… |
|
||||||
|
| `boot/efi.zig:507` | maximum_bundled (declared line 371) | 64 | external-data | As described and verified: efi.zig:507 `if (count.* == maximum_bundled) return;` in loadByManifest is a silent stop keeping the first 64; efi.zig:590 … | Manifest path: nothing. Enumeration path: efi.zig:71-75 prints 'EFI: no /system binaries (TooManyBinaries) - b… |
|
||||||
|
| `boot/efi.zig:582` | <inline literal> (child_prefix bufPrint) | 64 bytes (initial_ramdisk.ma… | external-data | `const child = try std.fmt.bufPrint(&child_prefix, "{s}/{s}", .{ prefix, name });` into a [initial_ramdisk.maximum_name]u8 = [64]u8. error.NoSpaceLeft… | efi.zig:71-75 prints 'EFI: no /system binaries (NoSpaceLeft) - booting without user space' on con_out. Visible… |
|
||||||
|
| `boot/efi.zig:633` | ehdr.e_phnum / e_phoff / e_phentsize (no bound a… | unbounded — read straight fr… | external-data | Unchecked out-of-bounds read. efi.zig:632-636 forms `image.ptr + ehdr.e_phoff + i * ehdr.e_phentsize` as raw pointer arithmetic and @ptrCasts it — no … | Nothing until it faults or panics, at which point the machine is still in the firmware with no kernel. |
|
||||||
|
| `library/device/acpi/aml/interpreter.zig:158` | notify_queue | [16]NotifyEvent | external-data | Silent drop of the 17th and later Notify. `notify()` (line 571-576): `if (target) \|node\| { if (self.notify_count < self.notify_queue.len) { ...appen… | None. No log in interpreter.zig at all (grepped: zero std.log/log.print/logging.write calls in the file). `tak… |
|
||||||
|
| `library/device/acpi/aml/interpreter.zig:523` | <inline literal> | 100_000 | our-design | Silently exits the loop and continues executing the method as if the loop had terminated normally: `while (guard < 100_000) : (guard += 1) { … }` then… | Nothing. No log, no `error.Unsupported`, no distinguishable result — the caller receives a normal-looking valu… |
|
||||||
|
| `library/device/acpi/aml/parser.zig:24` | maximum_segments (and its disagreeing twin, libr… | 64 in the parser, 16 in the … | external-data | Both files silently drop the surplus segment after consuming its 4 bytes. Parser: appendSegment, parser.zig:137-143. Interpreter: `fn segment(self: *C… | None on either path. Neither file logs; acpi.zig discards ParseResult.consumed/total; interpreter errors surfa… |
|
||||||
|
| `library/device/usb/usb.zig:167` | <inline literal> | 100 attempts × 20 ms = 2 s | our-design | Gives up and returns null: `const bus = while (attempts < 100) : (attempts += 1) { if (channel.openEndpoint("usb-transfer")) \|handle\| break handle; … | Nothing here. The driver's own bail-out is what an operator sees, with no indication that it was a timeout rat… |
|
||||||
|
| `library/kernel/channel.zig:124` | <inline literal> | @min(available, into.len) | our-design | Silent truncation to the caller's buffer: `const available = @min(answer.len - envelope.prefix_size, @as(usize, status.len)); const taken = @min(avail… | Weak: `Response.status.len` holds the true length the provider sent, so a caller *could* compare it against `p… |
|
||||||
|
| `library/kernel/file-system.zig:85` | <inline literal> | [224]u8 (twice: lines 77 and… | our-design | Errors invisibly, but the enforcing code is in the KERNEL, not where the claim points. system/kernel/process.zig:1898 rejects the input outright: `if … | None. A too-long path and a nonexistent file are both `null` from open(); no log on either side — the kernel's… |
|
||||||
|
| `library/kernel/logging.zig:82` | <inline literal> | [256]u8 | our-design | Truncation, marked with a `~` — but the truncated slice is the *whole* buffer, not the written prefix: `const line = std.fmt.bufPrint(&buffer, prefix … | The trailing `~` marks the line as truncated, which is good; the garbage tail is not marked at all. |
|
||||||
|
| `library/kernel/process.zig:211` | <inline literal> | [32]ProcessDescriptor | our-design | Silent false negative: `var table: [32]ProcessDescriptor = undefined; const total = processes(&table); for (table[0..@min(total, table.len)]) \|descri… | Nothing. The function returns a plain bool; the discarded `total` is the only evidence and it is thrown away b… |
|
||||||
|
| `library/protocol/device-manager/device-manager-protocol.zig:161` | entries_per_reply | (envelope.packet_maximum - e… | hardware | Silent cut with a success status. `onEnumerate` (device-manager.zig:524-536): `for (&children) \|*child\| { if (!child.used) continue; if (written + e… | None, and structurally impossible for a client to detect: the protocol's own comment (149-152) says the count … |
|
||||||
|
| `library/protocol/envelope/envelope.zig:133` | packet_maximum | 256 | our-design | Two behaviours, exactly as claimed. Compile time: `Define` rejects an oversized fixed part with a message naming protocol, verb, size, prefix and floo… | Compile-time half is excellent. Run-time half is silent everywhere I traced it: library/device/block/block.zig… |
|
||||||
|
| `library/protocol/envelope/envelope.zig:134` | post_maximum | 64 | our-design | Compile error for an event payload that does not fit (`Define`, envelope.zig:365-370, message names the event and the push floor). At run time `encode… | Compile-time: named and precise. Run-time: nothing. The `orelse return` at service.zig:239 is the whole handli… |
|
||||||
|
| `library/protocol/usb-transfer/usb-transfer-protocol.zig:58` | max_report_data | 40 | hardware | Two stacked silent truncations. First in the engine: usb-xhci-library.zig:1569 `const n = @min(length, report.data.len);` against a `data: [64]u8` (li… | None. No log at either truncation site; the surrounding comment (usb-xhci-bus.zig:766-768) states the truncati… |
|
||||||
|
| `library/protocol/usb-transfer/usb-transfer-protocol.zig:62` | max_reported_endpoints | 4 | hardware | Silent drop, and the primary site is upstream of the one claimed. The bus driver discards surplus endpoint descriptors while parsing the configuration… | None. No log at the parse-time drop, none at the client cap; a driver's `findEndpoint` just returns null for a… |
|
||||||
|
| `system/boot-handoff.zig:143` | kernel_segments | 8 | our-design | Silent drop with a delayed fatal consequence, as described. boot/efi.zig:659-668 records only `if (n < boot_information.kernel_segments.len)` with no … | The loader says nothing. The kernel prints the count it received — kernel.zig:159 `log.print(" kernel segs: {… |
|
||||||
|
| `system/drivers/pci-bus/pci-bus.zig:81` | <inline literal> alloc(device.DeviceDescriptor, … | 64 | our-design | Not reachable today, so nothing happens. If the kernel table grew past the buffer: `device.enumerate(buffer)` returns the TOTAL, the search clamps wit… | One misleading line, `std.log.info("device {d} not in the device tree", .{bridge_id})` — it names a missing de… |
|
||||||
|
| `system/drivers/pci-bus/pci-bus.zig:81` | 64 (bare inline literal — no constant, no link t… | 64 | our-design | Same site as the earlier claim on line 81 — this is a duplicate. Unreachable today (`total` is bounded by the kernel's own maximum_devices = 64). If i… | `std.log.info("device {d} not in the device tree", .{bridge_id})` — misdescribes the cause and never prints `t… |
|
||||||
|
| `system/drivers/usb-hid/hid-report.zig:20` | KeyboardReport.keys: [6]u8, and max_transitions … | 6 concurrent keys; 14 transi… | hardware | THE CLAIM IS BACKWARDS. `max_transitions = 8 + 6` is derived from a wrong worst case, and `Transitions.add`'s guard (`if (self.count < self.items.len)… | None. `add` drops without logging and `Transitions` carries no overflow flag; `slice()` just returns the first… |
|
||||||
|
| `system/drivers/usb-storage/usb-storage.zig:61` | <inline literal> .lun = 0 in the CommandBlockWra… | 1 LUN (LUN 0 only) | hardware | There is no limit check — LUNs 1..15 simply do not exist to this driver. Every CBW is built with `.lun = 0` (usb-storage.zig:57-63), and I confirmed t… | Nothing. Nothing reads bMaxLUN, so nothing can report that a device has more than one logical unit. |
|
||||||
|
| `system/drivers/usb-storage/usb-storage.zig:121` | <inline literal> while (tries < 10) with time.sl… | 10 attempts = ~500 ms | hardware | Falls out of the loop and proceeds regardless (usb-storage.zig:120-127). INQUIRY's result is discarded (`_ = transact(...)`, line 129), then READ CAPA… | Present but misattributed, exactly as claimed: `_ = logging.write("/system/drivers/usb-storage: READ CAPACITY … |
|
||||||
|
| `system/drivers/usb-storage/usb-storage.zig:172` | <inline literal> @intCast(request.lba) -> u32, @… | LBA < 2^32, count < 2^16 (RE… | external-data | Bare, unchecked @intCast on both fields — verified there is no range check anywhere between the wire struct and the CDB. scsi.read10/write10 take (lba… | In a safe build, driver death with a fault exit reason and a device-manager restart with backoff — attributed … |
|
||||||
|
| `system/drivers/usb-storage/usb-storage.zig:172` | @intCast(request.lba) / @intCast(request.count) … | u64 -> u32 LBA, u32 -> u16 b… | external-data | Unchecked narrowing of two peer-chosen wire fields. library/protocol/block/block-protocol.zig:30-35 declares `Transfer { lba: u64, count: u32, physica… | Nothing in ReleaseFast; in a safe build a driver crash with a fault exit reason and a supervised restart, attr… |
|
||||||
|
| `system/drivers/usb-xhci-bus/usb-xhci-bus.zig:80` | opens (= [_]Open{.{}} ** 16) | 16 | our-design | Confirmed, including the success-on-failure shape. recordOpen (line 87) walks `opens` for a matching token, then for a free slot, and falls through to… | Nothing on the bus side — no log when the table fills, and the harness closes the unclaimed report endpoint si… |
|
||||||
|
| `system/drivers/usb-xhci-bus/usb-xhci-bus.zig:728` | prev_connected (declared line 326 as [64]bool), … | 64 | hardware | Confirmed off-by-one. Line 728: `while (port <= engine.max_ports and port <= prev_connected.len) : (port += 1)` with `var port: u32 = 1` — at port == … | The OOB half surfaces as a driver fault and a supervised restart into the same panic — loud but attributed to … |
|
||||||
|
| `system/drivers/usb-xhci-bus/usb-xhci-bus.zig:728` | prev_connected (inline [64]bool, declared line 3… | 64 | hardware | Same site as the earlier line-728 claim — this is a duplicate. Two failures, both confirmed. (1) Off-by-one out-of-bounds: `while (port <= engine.max_… | The panic half is loud (process fault + supervised restart loop) but misattributed. The silent-drop half has n… |
|
||||||
|
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:228` | max_endpoints_per_interface (and max_configured_… | 4 per interface, 16 configur… | hardware | Parsing: `if (interface.endpoint_count < max_endpoints_per_interface)` with no else — the 5th endpoint descriptor is silently discarded, so a class dr… | The endpoint-drop during parsing is entirely silent. The ring-exhaustion path reaches the class driver as a ge… |
|
||||||
|
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:228` | max_endpoints_per_interface | 4 | external-data | Silent drop, no else (1345-1354). An endpoint never recorded cannot be found by `endpointForAddress` (1377-1382), so a class driver's subscribe or bul… | None at the drop. The secondary consequence the claim names is real and I verified it: usb-xhci-bus.zig:612 se… |
|
||||||
|
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:328` | <inline literal> Report.data: [64]u8 (and usb_tr… | 64 in the driver, then 40 ov… | hardware | Truncated twice, silently: `const n = @min(length, report.data.len);` in enqueueReport, then `const n = @min(report.length, usb_transfer_protocol.max_… | Nothing. Both truncations are @min with no branch and no log. |
|
||||||
|
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:334` | max_subscriptions | 8 | hardware | Two paths, as claimed. Class driver: `subscribeInterrupt` (1482) `const subscription = self.allocateSubscription() orelse return false;` -> usb-xhci-b… | Class drivers log it: usb-hid/keyboard.zig:94 and mouse.zig:57 both write `interrupt subscribe failed`. The hu… |
|
||||||
|
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:335` | report_queue_capacity | 16 | hardware | `enqueueReport` (1561-1562): `if (self.report_count >= self.report_queue.len) return; // full: drop the newest` — the report is discarded and the subs… | None. The comment in the source is the only trace; no log, no counter. The symptom is dropped keystrokes or a … |
|
||||||
|
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:968` | hub_change_mask: u32 (declared line 298) and the… | 31 usable downstream ports | hardware | Ports 32..255 are never seeded and never serviced: the seed clamps to 0xFFFF_FFFE for hub_ports >= 31, and takeHubChange picks bits via @ctz on a u32,… | Nothing. No log line mentions bNbrPorts exceeding what the mask holds; the 'N downstream ports powered' line p… |
|
||||||
|
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:1456` | <inline literal> `.status = length` on the bulk … | 65535 (the xHCI TRB Transfer… | hardware | Unchecked write of a u32 into a 17-bit field. `bulkTransfer` (1452-1458) pushes `.status = length` with no mask and no split across TRBs; the status d… | Nothing on the way in — no check, no log. It surfaces later as a short/failed transfer or a lost completion at… |
|
||||||
|
| `system/drivers/virtio-gpu/virtio-gpu.zig:49` | max_width / max_height | 800 x 600 | hardware | set_mode errors visibly (line 536 refuses anything larger). But the EDID path is the silent one: readEdid (lines 413-442) parses the panel's preferred… | One std.log.info line naming the preferred mode, in the driver's log file, with nothing saying it was ignored. |
|
||||||
|
| `system/drivers/virtio-gpu/virtio-gpu.zig:208` | <inline literal> descriptors: [64]device.DeviceD… | 64 | hardware | NOT reachable today, contrary to the claim's framing. The kernel's own table is the binding wall: system/kernel/devices-broker.zig:25 `const maximum_d… | `device {d} not in the device tree` (line 213), which today only means a real absence. The kernel-side drop th… |
|
||||||
|
| `system/initial-ramdisk.zig:26` | maximum_name | 64 bytes | our-design | Four different behaviours, verified individually. (a) Capsule build: tools/pack-system-image.py:35-37 writes 'pack-system-image: path too long (>63)' … | (a) clear build error. (b)(c)(d) nothing: boot/efi.zig has exactly two output helpers (lines 773 and 795) and … |
|
||||||
|
| `system/kernel/acpi.zig:94` | overrides | [16]IsoEntry | hardware | Silent drop: `if (platform_information.override_count < platform_information.overrides.len) { ... }` with no else branch and no counter — unlike the C… | Nothing. A lost override means a legacy line is routed at the wrong GSI or the wrong polarity, which shows up … |
|
||||||
|
| `system/kernel/acpi.zig:94` | PlatformInformation.overrides | [16]IsoEntry | hardware | Silent drop, at three separate 16s that must agree by hand: system/kernel/acpi.zig:558 (no else branch), system/kernel/kernel.zig:248 (`var isos: [16]… | Nothing at any of the three clamps. No counter of the cpusDropped kind, no log line. |
|
||||||
|
| `system/kernel/acpi.zig:186` | aml_block_physical / aml_block_len | [32]u64 / [32]usize | hardware | Confirmed at acpi.zig:190-197: `fn addAmlBlock(sdt_physical: u64) void { if (aml_block_count >= aml_block_physical.len or sdt_physical == 0) return; .… | None — confirmed, no log and no dropped counter, unlike `cpu_information.dropped` (acpi.zig:539) and `rmrr_ski… |
|
||||||
|
| `system/kernel/architecture/x86_64/apic.zig:320` | <inline literal> 100_000_000 (calibratePit guard… | 100000000 | our-design | Confirmed: the loop falls out and calibration proceeds on a window that never happened. `ticks_per_ms = elapsed / calib_ms` and `tsc_hz = (tsc_end -% … | No failure line, but not quite "none": kernel.zig:322 prints `timer online ({d} Hz tick; timer clock {d} MHz, … |
|
||||||
|
| `system/kernel/architecture/x86_64/apic.zig:629` | localId (return type u8) / apic_id << 24 | 8-bit APIC id (0..255) | hardware | The claimed truncations are not reachable; the real defect is an omission. `sendInit`/`sendStartup` (lines 174-184) take a `u32` but every caller pass… | None for the dropped type-9 records. `cpu_information.dropped` (acpi.zig:542) counts only overflow past the 12… |
|
||||||
|
| `system/kernel/architecture/x86_64/iommu-amd.zig:56` | ring_entries (command buffer) | 256 | our-design | Confirmed. submitCommand (lines 221-228) writes the two qwords, advances `command_tail += 16`, wraps modulo the ring, and writes the tail register — w… | None — no head check, no full-ring detection, no log. |
|
||||||
|
| `system/kernel/architecture/x86_64/iommu-amd.zig:74` | fault_log_budget | 32 | hardware | logFault (lines 200-211) opens with `if (fault_log_budget == 0) return;` — the record's bdf and address are discarded outright, with no suppressed-fau… | One "(further faults suppressed)" line (line 210) and then permanent silence for the detail. Correcting the cl… |
|
||||||
|
| `system/kernel/architecture/x86_64/iommu-amd.zig:246` | <inline literal> 100_000 | 100000 | our-design | Confirmed verbatim at lines 243-253: the spin loop polls the completion frame for the 0xC0FFEE sentinel, and at `if (spins > 100_000)` warns once behi… | One line for the whole boot: "/system/kernel: AMD-Vi COMPLETION_WAIT store not observed — proceeding (QEMU pro… |
|
||||||
|
| `system/kernel/architecture/x86_64/iommu-intel.zig:77` | fault_log_budget | 32 | hardware | `logFault` (lines 252-270) takes the else branch and does `faults_suppressed += 1`. The budget is only ever decremented (line 255) — nothing resets it… | One line at the transition: 'DANOS-IOMMU-FAULT: (further faults suppressed)' (line 266). After that a device D… |
|
||||||
|
| `system/kernel/architecture/x86_64/iommu-intel.zig:294` | <inline literal> 10_000_000 (spin64) | 10000000 | our-design | `if (spins > 10_000_000) return;` — the function returns as if the invalidation completed. Callers (`invalidateDomain`, `globalInvalidate`, `detach`) … | Nothing at all — a bare `return` with no message, unlike `spinStatus` which prints "WARNING VT-d status bit ne… |
|
||||||
|
| `system/kernel/architecture/x86_64/paging.zig:206` | <inline literal> 0xFEE00000 | 0xFEE00000 (one 4 KiB page) | hardware | Confirmed and worse than "inconsistent": the two halves disagree with no reconciliation. paging.zig:206 maps exactly one hardcoded page `mapPage(pml4,… | A boot-time kernel fault reported as a fault address, never as "LAPIC relocated". The parsed truth is thrown a… |
|
||||||
|
| `system/kernel/architecture/x86_64/serial.zig:112` | <inline literal> 5_000 (writeByte guard) | 5000 | hardware | The loop simply falls through and `setRegister(0, c)` runs anyway (serial.zig:111-113) — the byte is written into a transmit-holding register that may… | Nothing. The corruption appears in the serial log itself, which is the channel you would use to notice it. |
|
||||||
|
| `system/kernel/heap.zig:28` | heap_maximum | 64 * 1024 * 1024 | our-design | Confirmed mixed. `grow` returns false at heap.zig:63 `if (start + bytes > heap_base + heap_maximum) return false;` -> `rawAlloc` null -> std.mem.Alloc… | For the graceful callers, a bare -1 to user space with no reason. For scheduler.zig:704, a panic naming the st… |
|
||||||
|
| `system/kernel/heap.zig:161` | <inline literal> alignment ceiling | 16 | our-design | `if (alignment.toByteUnits() > 16) return null;` confirmed at heap.zig:161 inside `allocImpl`. Returning null from the vtable alloc is how the allocat… | None. No log, no distinct error; the caller sees error.OutOfMemory and investigates memory pressure. |
|
||||||
|
| `system/kernel/ipc-synchronous.zig:40` | MESSAGE_MAXIMUM | 256 | our-design | Two different behaviours, both confirmed. The cap itself errors visibly: `if (message_len > MESSAGE_MAXIMUM or reply_cap > MESSAGE_MAXIMUM) return -E2… | -E2BIG for the cap. Nothing for the truncation — no counter, no flag bit, no errno. |
|
||||||
|
| `system/kernel/ipc-synchronous.zig:75` | post_capacity | 16 | external-data | Deliberate silent drop of the OLDEST message: sendLocked, ipc-synchronous.zig:568 `if (endpoint.post_tail -% endpoint.post_head >= post_capacity) endp… | None, and I checked the struct: PostSlot (ipc-synchronous.zig:79-83) carries only length and sender_id — no se… |
|
||||||
|
| `system/kernel/ipc-synchronous.zig:513` | @min(caller.ipc_send_len, receive_cap) (no const… | whatever the receiver's buff… | external-data | Silent truncation. replyWait, ipc-synchronous.zig:512-513: `if (dequeueSender(endpoint)) \|caller\| { const n = @min(caller.ipc_send_len, receive_cap)… | Nothing — no counter, no errno, no flag bit anywhere on this path. |
|
||||||
|
| `system/kernel/log.zig:202` | buffer (log.print) | [256]u8 | our-design | Confirmed: the entire line is discarded, not truncated. Lines 201-204 verbatim: `pub fn print(comptime fmt: []const u8, args: anytype) void { var buff… | Nothing. The message never appears and its absence is indistinguishable from the code path not having run. Not… |
|
||||||
|
| `system/kernel/pmm.zig:94` | <inline literal> (implicit: bitmap must land bel… | 4 GiB, stated only in prose | hardware | Two distinct failures. If NO usable region is large enough: `@panic("pmm: no region large enough for the frame bitmap")` — loud and fatal. If the chos… | The panic is legible. The above-4-GiB case is a triple fault or an early #PF with essentially no diagnostics. |
|
||||||
|
| `system/kernel/process.zig:98` | maximum_shared_memory_pages | 8192 (32 MiB) | hardware | Confirmed at process.zig:790: `if (pages == 0 or pages > maximum_shared_memory_pages) return fail(state);` in `systemSharedMemoryCreate`, giving a cle… | No kernel log; -1 only — confirmed. And the ambiguity the claim notes is real: `pmm.allocContiguous` failing t… |
|
||||||
|
| `system/kernel/process.zig:104` | maximum_mmap_pages | 8192 (32 MiB) | our-design | Confirmed at process.zig:2050: `if (pages == 0 or pages > maximum_mmap_pages) return fail(state);` in `systemMmap` — a clean -1. The independent secon… | -1 only, no log — confirmed. Indistinguishable from arena exhaustion and from 'not a user process' (line 2049)… |
|
||||||
|
| `system/kernel/process.zig:118` | maximum_resolve_path | 224 | external-data | Confirmed at process.zig:1898: `if (path_len == 0 or path_len > maximum_resolve_path or path_ptr >= user_half_end or path_ptr + path_len > user_half_e… | No log; -1 only — confirmed. There is no ENAMETOOLONG in this path (the function does have `failErr(state, ipc… |
|
||||||
|
| `system/kernel/process.zig:1542` | exit_subscriber_capacity | 16 | hardware | Confirmed at process.zig:1573-1581: `subscribeExits` scans `for (&exit_subscribers) \|*slot\| { if (slot.* == null) { endpoint.refcount += 1; slot.* =… | Materially worse than claimed, and this is my main correction. The kernel does return a specific -ENOSPC, but … |
|
||||||
|
| `system/kernel/process.zig:1649` | timer_capacity | 16 | our-design | Confirmed at process.zig:1684-1692: `systemTimerBind` scans `for (&one_shot_timers) \|*slot\| { if (slot.* == null) { ...; return architecture.setSyst… | Effectively none, correcting the claim. The kernel's -ENOSPC is narrowed to a bool by library/kernel/time.zig:… |
|
||||||
|
| `system/kernel/process.zig:2172` | maximum_segments | 16 | external-data | Confirmed at process.zig:2200: `if (ehdr.e_phnum > maximum_segments) return error.BadElf;`. The claim's key observation is right — the test is on `e_p… | None — confirmed. `error.BadElf` is erased at process.zig:1018 and `system_spawn` returns -1, so a developer i… |
|
||||||
|
| `system/kernel/process.zig:2173` | maximum_pages | 256 | external-data | Confirmed at process.zig:2238, inside the PT_LOAD loop: `total_pages += seg.pages(); if (total_pages > maximum_pages) return error.ProgramTooBig;`. Th… | No kernel log — confirmed. `error.ProgramTooBig` is erased at the syscall boundary and becomes the same -1 as … |
|
||||||
|
| `system/kernel/scheduler.zig:206` | maximum_space_mappings | 16 | our-design | Clean refusal, confirmed. `recordSpaceMappingLocked` (scheduler.zig:343-355) walks `entry.mappings` for a null slot and `return false` when full; proc… | A bare -1 from `shared_memory_map`/`shared_memory_create` — the same value as a bad handle, an exhausted arena… |
|
||||||
|
| `system/kernel/vfs.zig:143` | @memcpy(d.path[0..parent.len], parent) — implici… | 64 == 64, by coincidence | external-data | Safe today, and safe with slightly more margin than the claim states. parentOf (vfs.zig:119-123) returns a strict prefix ending before the last '/', s… | Nothing would warn. The coupling is invisible from either file: system/initial-ramdisk.zig:26-28 reasons about… |
|
||||||
|
| `system/kernel/vfs.zig:315` | name_out (via process.zig:1972 name_buffer) | [64]u8 | external-data | Silent truncation with a header that agrees with the truncation rather than reporting it: vfs.zig:314-317 `const n = @min(name.len, name_out.len); @me… | None. The contrast is fair — system/kernel/log-ring.zig sets abi.klog_flag_truncated for exactly this situatio… |
|
||||||
|
| `system/services/acpi/acpi.zig:81` | mmio_scratch | [4096]u8 | external-data | No overflow — the aliasing IS the failure. library/device/acpi/aml/interpreter.zig:708 (readRegionByte) and :720 (writeRegionByte) both do `const virt… | None. No log fires on a SystemMemory access in either the interpreter or the HAL, so an _STA or _CRS that cons… |
|
||||||
|
| `system/services/acpi/acpi.zig:113` | <inline literal> | 64 | hardware | Falls through silently and proceeds as though ACPI mode were enabled. `while (tries < 1000 and (halPioRead(2, pm1a_cnt) & sci_en_bit) == 0) : (tries +… | None that distinguishes the two outcomes. No log fires on give-up, and the success message "acpi: power button… |
|
||||||
|
| `system/services/acpi/acpi.zig:306` | <inline literal> | 1000 | hardware | Falls through silently and proceeds as though ACPI mode were enabled. `while (tries < 1000 and (halPioRead(2, pm1a_cnt) & sci_en_bit) == 0) : (tries +… | None that distinguishes the two outcomes. No log fires on give-up, and the success message "acpi: power button… |
|
||||||
|
| `system/services/device-manager/device-manager.zig:50` | registry_source | [8192]u8 | external-data | Silent truncation of the file. `loadRegistry` (63-68): `while (used < registry_source.len) { const n = file.read(registry_source[used..]) orelse break… | Nothing says the file was cut. Only downstream symptoms: `{d} malformed line(s) skipped` (line 70) if the frag… |
|
||||||
|
| `system/services/device-manager/device-manager.zig:51` | registry_source | 8192 bytes | external-data | Silent truncation of the file. `loadRegistry` (63-68): `while (used < registry_source.len) { const n = file.read(registry_source[used..]) orelse break… | Nothing says the file was cut. Only downstream symptoms: `{d} malformed line(s) skipped` (line 70) if the frag… |
|
||||||
|
| `system/services/device-manager/device-manager.zig:531` | <inline literal> | reply tail of a 256-byte pac… | our-design | Silent truncation with a success status: `if (written + entry_size > tail.len) break;` and the handler returns the byte count. There is no cursor and … | None. The client sees a short but well-formed list. |
|
||||||
|
| `system/services/display/backend.zig:27` | device_table | [64]device.DeviceDescriptor | hardware | Confirmed as written but NOT reachable today. findDisplay (lines 54-63) does `const total = device.enumerate(&device_table); const n = @min(total, dev… | Misleading when it does fire, as claimed: Gop.init exhausts its retries and writes `display: no framebuffer de… |
|
||||||
|
| `system/services/display/compositor.zig:288` | <inline literal> | src.len >= w*h*4, against a … | our-design | Silent no-op reported as success. blitTile does `if (src.len < @as(usize, w) * h * 4) return;`, but blitLayer (display.zig:236-242) ignores that, stil… | None whatsoever: no log, and a success status. The symptom is a blank region. |
|
||||||
|
| `system/services/display/display.zig:76` | maximum_layers | 16 | our-design | Confirmed. `createLayer` (display.zig:208-210) is `const slot = freeLayer() orelse return null;`, and `onCreateLayer` (695-700) is `const slot = creat… | Nothing server-side for a client-facing exhaustion — confirmed. The service's own cursor path does log (`_ = l… |
|
||||||
|
| `system/services/display/display.zig:395` | mode_list / list | [4]backend_mod.Mode | hardware | Silent truncation on both hops: the backend clamps with `const count = @min(@min(offered.count, scanout_protocol.max_modes), out.len);` (backend.zig:1… | None — no log names the number offered versus the number kept. The mode-set self-check only says "no alternate… |
|
||||||
|
| `system/services/fat/engine.zig:70` | sector_size | 512 | external-data | Mount is refused, confirmed. Both paths test `if (geometry.bytes_per_sector == sector_size)` — engine.zig:193 (bare FAT at LBA 0) and engine.zig:209 (… | A wrong diagnosis: `_ = logging.write("/system/services/fat: not a FAT filesystem\n")` at system/services/fat/… |
|
||||||
|
| `system/services/fat/engine.zig:193` | sector_size (declared line 70) | 512 | external-data | Refuses to mount rather than corrupting, confirmed at engine.zig:193 and the MBR-partition path at engine.zig:209; both fall through to `return null`. | system/services/fat/fat.zig:162 `_ = logging.write("/system/services/fat: not a FAT filesystem\n")` — false fo… |
|
||||||
|
| `system/services/fat/fat.zig:73` | open_nodes (inline [_]OpenNode{.{}} ** 32) | 32 | our-design | Error returned, but the WRONG error, and silently: `const index = allocOpen() orelse return refused;` where `const refused: isize = -envelope.ENOENT;`… | Nothing. No log line at exhaustion, and the client is told the file does not exist. An operator debugging this… |
|
||||||
|
| `system/services/fat/fat.zig:285` | <inline literal> | reply tail of a 256-byte pac… | our-design | Silent truncation with a success status: `const name_len = @min(listing.name_len, into.len);` then `return @intCast(name_len);` — the client receives … | None. A directory listing shows a chopped filename that then fails to open. |
|
||||||
|
| `system/services/fat/fat.zig:285` | into.len (inline; = envelope.packet_maximum - pr… | 224 bytes | external-data | Silent truncation, and the reply's name_len is set to the TRUNCATED value, so the client cannot tell there was more. The engine's own buffer holds 260… | Nothing. |
|
||||||
|
| `system/services/init/init.zig:70` | max_service_args | 4 | external-data | Silent drop of the surplus arguments: loadServices, init.zig:122-127 `while (it.next()) \|argument\| { if (argument.len == 0) continue; if (service.ar… | None, and the contrast with its immediate sibling is confirmed: the max_services cap ten lines above logs `"/s… |
|
||||||
|
| `system/services/init/init.zig:161` | maximum_bindings | 16 | our-design | An error is returned to the binder: onBind, init.zig:620-622 `const slot = for (&bindings) \|*binding\| { if (!binding.used) break binding; } else ret… | Weak, and the asymmetry is confirmed: within the same function the EPERM path logs (init.zig:602-608) and the … |
|
||||||
|
| `system/services/init/init.zig:162` | maximum_grants | 64 | external-data | Parsing stops at 64 rows: loadGrants, init.zig:237-240 `if (grant_count >= grants.len) { _ = logging.write("... protocol.csv has more rows than the ta… | The overflow itself is logged with a direct `logging.write` naming the file (init.zig:238). The consequences a… |
|
||||||
|
| `system/services/init/init.zig:220` | protocol_csv | 16384 bytes | external-data | Silent truncation mid-line, then a heuristic report. readConfiguration (init.zig:138-146) fills the buffer and stops; the tail rows vanish and the las… | One heuristic info log: init.zig:147 `if (used == into.len) std.log.info("{s} filled the read buffer — rows pa… |
|
||||||
|
| `system/services/init/init.zig:220` | protocol_csv (with maximum_grants = 64 rows alon… | 16384 bytes / 64 rows | external-data | Truncation, announced on both limits. readConfiguration reports the byte cap at init.zig:147 (`std.log.info("{s} filled the read buffer — rows past {d… | Both limits log, which is what makes this the calibration point. The byte-limit line rides std.log.info (the r… |
|
||||||
|
| `system/services/init/init.zig:274` | process_table | [64]process.ProcessDescripto… | our-design | Partly handled, partly not — confirmed exactly. refreshProcessTable (init.zig:278-282) sets `process_truncated = total > process_table.len`, and taskA… | A bind refusal outside identify does log (init.zig:602-608), but a failed identify in onBind returns -EPERM wi… |
|
||||||
|
| `boot/efi.zig:308` | pool_pages | 64 frames (256 KiB) | hardware | TablePool.alloc, efi.zig:264-265: `if (self.next >= self.cap) return error.OutOfBootstrapFrames;`. Every map2M/map4K path is `try`, so it unwinds clea… | Good, and verified: main (efi.zig:34-39) writes unconditionally to con_out — `log("\r\nEFI: boot failed: "); l… |
|
||||||
|
| `boot/efi.zig:543` | info_buffer | 1024 bytes | external-data | `const n = try directory.read(&info_buffer);` (efi.zig:545) into a [1024]u8. UEFI answers EFI_BUFFER_TOO_SMALL for an EFI_FILE_INFO that will not fit;… | efi.zig:71-75 on con_out, naming the UEFI error but not the file. |
|
||||||
|
| `boot/efi.zig:543` | info_buffer (inline [1024]u8) | 1024 bytes | external-data | `const n = try directory.read(&info_buffer);` (efi.zig:545) — EFI_BUFFER_TOO_SMALL becomes an error and the `try` propagates out of walkDirectory and … | efi.zig:71-75 on con_out; names the UEFI error, not the file. |
|
||||||
|
| `boot/efi.zig:660` | BootInformation.kernel_segments (declared system… | [8]KernelSegment | our-design | `if (n < boot_information.kernel_segments.len) { ... }` (efi.zig:659-668) with no else — the segment is copied to its physical address but never recor… | Nearly nothing, but not quite nothing: kernel.zig:159 prints `log.print(" kernel segs: {d} (mapped with W^X p… |
|
||||||
|
| `boot/efi.zig:680` | <inline literal> (attempts) and cap = info.len +… | 8 attempts; +8 spare descrip… | hardware | Correct and safe, as claimed. efi.zig:680-700: on each attempt both pool buffers are sized from the firmware's own descriptor count plus 8, a failed g… | The fatal case reaches main's handler: 'EFI: boot failed: ExitBootServicesFailed' on con_out, then hlt. No bre… |
|
||||||
|
| `boot/efi.zig:787` | buffer (logBytes) | 128 UTF-16 units | our-design | `if (i + 1 >= buffer.len) break;` (efi.zig:790) — the tail of the string is dropped, the result is NUL-terminated at the truncation point and printed.… | This IS the observability path — logBytes is the only way a runtime string (in practice an @errorName from mai… |
|
||||||
|
| `build/images.zig:152` | <inline literal> (mk_fat.addArg("64")) | 64 (MiB) | our-design | Build-time hard failure. tools/make-fat-image.py:67-68 — `if cluster >= self.cluster_count + 2: sys.exit("error: image out of clusters")` inside the c… | "error: image out of clusters" on stderr, which aborts the build. It names neither the file being added nor a … |
|
||||||
|
| `library/device/acpi/aml/interpreter.zig:55` | maximum_segments | 16 | external-data | Silent truncation in `Cursor.segment` (123-129): `const s = try self.take(4); if (name_path.count < maximum_segments) { ...store... }` — the cursor ad… | None. Line 299's comment `// unknown name -> treat as uninitialised` is by design, so a truncated name is indi… |
|
||||||
|
| `library/device/acpi/aml/parser.zig:24` | maximum_segments | 64 | external-data | appendSegment (parser.zig:137-143) always consumes the 4 name bytes via readNameSegment — so the cursor stays in sync — but silently discards the segm… | None. aml.zig:36-56 builds a ParseResult{consumed,total} precisely so a desync is detectable, but the only con… |
|
||||||
|
| `library/device/block/block.zig:95` | <inline literal> | 600 attempts × 50 ms = 30 s | our-design | Returns null; the caller (the FAT server) reports no volume. | Nothing logged at this level, but the number is justified against a measurement. |
|
||||||
|
| `library/device/driver/driver.zig:165` | lookup_attempts | 100 (× lookup_pause_ms = 20 … | our-design | `hello()` runs `while (attempts < lookup_attempts) : (attempts += 1) { if (channel.openEndpoint("device-manager")) \|handle\| break handle; time.sleep… | Good, and I confirmed it at driver.zig:181 — the else branch IS the log. Requiring callers also announce their… |
|
||||||
|
| `library/device/model/device-abi.zig:139` | DeviceDescriptor.hid | [8]u8 | hardware | No truncation is reachable today. The cited site (devices-broker.zig:121-122) cannot truncate: `node.hid()` returns `hid_buffer[0..hid_len]` from devi… | Not applicable — nothing truncates. The 8-byte-with-no-NUL width does cause a live defect elsewhere: system/se… |
|
||||||
|
| `library/device/pci/pci.zig:37` | bar_virtual | [6]usize | hardware | Errors: `pub fn mapBar(self: *Function, bar: u8) ?usize { if (bar >= 6) return null;` — a caller asking for BAR 6 gets null rather than an out-of-boun… | Null from `mapBar`, which each driver reports in its own words. |
|
||||||
|
| `library/device/pci/pci.zig:283` | CapabilityIterator.guard (and ExtendedCapability… | 48 and 480 | hardware | Iteration ends. Silent, but correctly so: the bound is derived from the size of the address space being walked, so reaching it means the device's chai… | Nothing — and it needs nothing, because the bound cannot cut a well-formed chain short. |
|
||||||
|
| `library/device/pci/pci.zig:286` | <inline literal> | 48 | hardware | The iterator silently ends: `if (self.cursor == 0 or self.guard >= 48) return null;` — indistinguishable from the end of a well-formed list. `findCapa… | Nothing. No log distinguishes 'no MSI capability' from 'capability list is a loop'. |
|
||||||
|
| `library/device/pci/pci.zig:371` | <inline literal> | 480 | hardware | Silently ends the iteration: `if (self.cursor == 0 or self.guard >= 480) return null;`. `findExtendedCapability` then reports absence. | Nothing. |
|
||||||
|
| `library/device/registry/device-registry.zig:200` | cols | [9][]const u8 | external-data | Errors and counts. parseLine: `if (count >= cols.len) return .malformed; // too many columns` and after the loop `if (count != cols.len) return .malfo… | Verified end to end, and it is genuinely good: system/services/device-manager/device-manager.zig:71 `if (resul… |
|
||||||
|
| `library/device/registry/device-registry.zig:239` | out_rules.len (caller-supplied) | caller's buffer | external-data | `if (result.count >= out_rules.len) { result.truncated = true; continue; }` inside parse — the surplus valid rules are dropped and the flag records it… | The best in the tree, and I confirmed the caller actually uses it: device-manager.zig:72 `if (result.truncated… |
|
||||||
|
| `library/kernel/channel.zig:37` | path_maximum | 224 | our-design | Refuses: `join` (285) `if (total > buffer.len) return null;`. `reach` (182-193) returns null when `file_system.fsResolve` cannot write the rewritten p… | None — null, no log, same documented three-way ambiguity. |
|
||||||
|
| `library/kernel/channel.zig:46` | name_maximum | 64 | our-design | Refuses, never truncates: `join` (282-290) `if (name.len == 0 or name.len > name_maximum) return null;`, which `openEndpoint` (238-242) turns into a n… | None (no log), and the null is deliberately three-way ambiguous per the doc at 231-237: no such contract / not… |
|
||||||
|
| `library/kernel/memory/heap.zig:199` | <inline literal> | 16 | our-design | Refuses cleanly: `fn allocImpl(_: *anyopaque, len: usize, alignment: std.mem.Alignment, _: usize) ?[*]u8 { if (alignment.toByteUnits() > 16) return nu… | An allocation failure, which std reports as OutOfMemory — a misleading name for an alignment refusal, and no l… |
|
||||||
|
| `library/kernel/process.zig:116` | <inline literal> | [8]u8 | our-design | The kernel refuses the *sender* rather than truncating (the receive capacity travels in r8 to `ipc_reply_wait`), so a client that calls into a process… | The refusal reaches the caller as an IPC failure; the stopping process logs nothing. |
|
||||||
|
| `library/kernel/process.zig:185` | <inline literal> | [256]u8 | our-design | Errors, cleanly: `if (len >= blob.len) return null;` and `if (len + argument.len > blob.len) return null;` — the spawn never happens and null is retur… | Poor. `spawn*` returning null is the same answer as 'no such binary' or 'task table full'; the caller (e.g. th… |
|
||||||
|
| `library/kernel/service.zig:94` | subscriber_capacity | 8 | our-design | onSubscribe (service.zig:264) walks `slots`, and if no slot is free returns `-envelope.ENOSPC`. The turn then closes the endpoint capability that arri… | No log in the provider. On the subscriber side the only real caller in the tree does log: system/services/disp… |
|
||||||
|
| `library/kernel/thread.zig:41` | tls_block_size | 64 | our-design | No check exists anywhere. thread.zig:88-90 carves `closure_addr` down from the stack top and then `const tls_base = (closure_addr - tls_block_size) & … | None — nothing tracks a TLS extent, so nothing could report it. The symptom would be a thread running with cor… |
|
||||||
|
| `library/protocol/display/display-protocol.zig:99` | max_modes | 4 | our-design | Silent drop of the surplus, but it can never fire. Provider side confirmed at system/services/display/display.zig:749-757: `var list: [4]backend_mod.M… | Nothing at either end — no log — but nothing is dropped either. |
|
||||||
|
| `library/protocol/scanout/scanout-protocol.zig:29` | max_modes | 4 | hardware | Silent truncation on both sides, exactly as claimed. Driver: virtio-gpu.zig:525-527 `var offered = scanout_protocol.Modes{ .count = offered_modes.len … | None. Confirmed: neither `modes()` in backend.zig nor the get_modes handler in virtio-gpu.zig emits anything a… |
|
||||||
|
| `library/xkeyboard-config/xkeyboard-config.zig:80` | map(layout, hid_usage: u8, …) | u8 (indexing Layout.keys: [2… | hardware | No overflow is possible — `keys: [256]Key` (library/xkeyboard-config/generated/layouts.zig:20) exactly covers the u8 domain, and an unmapped usage yie… | A key that maps to nothing produces no character; nothing distinguishes 'unmapped' from 'narrowed to the wrong… |
|
||||||
|
| `system/drivers/pci-bus/pci-bus.zig:36` | <inline literal> var line: [320]u8 (the per-func… | 320 bytes | our-design | `const text = std.fmt.bufPrint(&line, "...", .{...}) catch return;` at line 37 — the whole breadcrumb for that function is dropped and logFunction ret… | Nothing. The function simply does not appear in the boot log, which reads identically to "the walk did not fin… |
|
||||||
|
| `system/drivers/pci-bus/pci-bus.zig:182` | <inline literal> if (descriptor.resource_count >… | 8 | our-design | `break` out of the `while (i < 6)` BAR-sizing loop at line 181. Remaining BARs are never sized, never recorded in the descriptor and never restored-th… | Nothing. No log, no counter, and the loop's `configWrite16(bus, dev, function, 0x04, command)` decode-restore … |
|
||||||
|
| `system/drivers/ps2-bus/ps2-library.zig:464` | <inline literal> while (guard < 16) in drainOutp… | 16 bytes | hardware | Returns with the output-buffer-full bit possibly still set. No error, no retry, no signal to the caller (the function returns void). Callers are ps2-b… | None — silent void return. |
|
||||||
|
| `system/drivers/usb-hid/keyboard.zig:107` | <inline literal> receive: [64]u8 (identically at… | 64 | our-design | Currently sufficient with 4 bytes to spare: the protocol's own test asserts Protocol.event_maximum == 60 and event_maximum <= envelope.post_maximum (l… | Nothing here would report an over-long message; the driver's guard is `if (message.length < @sizeOf(hid.Keyboa… |
|
||||||
|
| `system/drivers/usb-xhci-bus/usb-xhci-bus.zig:521` | <inline literal> hid_buffer: [8]u8 (the "P<port>… | 8 bytes | our-design | Confirmed at lines 521-523: `var hid_buffer: [8]u8 = undefined; const hid_text = std.fmt.bufPrint(&hid_buffer, "P{d}I{d}", .{ port, interface.number }… | Nothing. `catch ""` swallows the bufPrint failure, register returns an existing id which looks like a normal i… |
|
||||||
|
| `system/drivers/usb-xhci-bus/usb-xhci-bus.zig:763` | <inline literal> if (serviced >= 32) break | 32 hub changes per tick | our-design | Deferral, not loss. `while (engine.takeHubChange()) \|change\| { ... serviced += 1; if (serviced >= 32) break; }` — the remaining changes stay in each… | Not needed; nothing is lost. There is no log, correctly. |
|
||||||
|
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:131` | trbs_per_ring (= page_size / @sizeOf(Trb)) | 256 | our-design | Correct wraparound. `push` (155-178) writes slot `enqueue_index`, and when the index reaches `trbs_per_ring - 1` (the Link slot) it re-installs the Li… | Not needed. |
|
||||||
|
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:456` | <inline literal> port_changes: [16]u32 | 16 | hardware | Silently dropped in `pump` (1610-1613): `if (self.port_change_count < self.port_changes.len) { self.port_changes[...] = port; self.port_change_count +… | Nothing at the drop site. Recovered in practice by the level reconcile in serviceController (usb-xhci-bus.zig:… |
|
||||||
|
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:456` | port_changes (inline [16]u32) | 16 | hardware | Silent drop, no else (pump, 1610-1613). The PORTSC change bits are already acknowledged at 1608-1609, so the edge is consumed even when the queue entr… | Nothing at the drop site; recovered by the independent per-port level reconcile at usb-xhci-bus.zig:727-741, w… |
|
||||||
|
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:496` | <inline literal> guard < 64 in the xECP capabili… | 64 extended capabilities | hardware | The `while (offset != 0 and guard < 64)` walk simply stops; a Supported Protocol capability past the 64th is not logged. Diagnostic only. | Nothing distinguishes 'chain ended' (the `if (next == 0) break;` at 509) from 'guard tripped'. |
|
||||||
|
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:603` | <inline literal> device_context_array = memory.d… | 512 entries (4096 / 8), vs M… | hardware | Safe, but only by accident of type width: slot_id is a u8 (`return @truncate(event.control >> 24)` in enableSlot), so `array[device.slot_id]` cannot e… | Not applicable today. |
|
||||||
|
| `system/drivers/usb-xhci-bus/usb-xhci-library.zig:1069` | <inline literal> while (tries < 200) with time.s… | 200 tries = ~1 s | hardware | Falls out of the loop, re-reads status at 1076, and if still not enabled: `std.log.info("hub slot {d} port {d}: reset did not enable", .{ hub.slot_id,… | Good — a specific log line naming hub slot and port, quoted above. |
|
||||||
|
| `system/drivers/virtio-gpu/virtio-gpu.zig:77` | queue_size | 16 | our-design | The only failure direction is a device offering fewer than 16, and it is checked and refused loudly — confirmed at lines 282-286: `const device_qsize … | Explicit log line carrying the device's actual value, then a clean bring-up failure. |
|
||||||
|
| `system/drivers/virtio-gpu/virtio-gpu.zig:163` | <inline literal> while (tries < 2000) in waitUse… | 2000 iterations ≈ 2 s | our-design | Returns false (line 172). submit returns false, command_nodata returns 0 (line 184), which never equals ok_nodata, so each bring-up call site logs its… | Good on the BRING-UP path only. The serving path is silent: presentFull's two failure returns (lines 461 and 4… |
|
||||||
|
| `system/drivers/virtio-gpu/virtio-gpu.zig:405` | <inline literal> .scanout_id = 0 (and resource_i… | 1 scanout, 1 resource, 1 bac… | hardware | No runtime limit exists — confirmed. Grepped the whole tree: `get_display_info`, `RespDisplayInfo` and `max_scanouts` appear ONLY in their declaration… | Nothing about head count, because it is never asked. The file header does state the scope: "this instance clai… |
|
||||||
|
| `system/drivers/virtio-gpu/virtio-gpu.zig:486` | <inline literal> while (tries < 50) with time.sl… | 50 tries = 1 s | our-design | Logs and returns, confirmed at lines 485-492: `const display = while (tries < 50) : (tries += 1) { if (channel.openEndpoint("display")) \|h\| break h;… | One clearly worded log line. The lasting consequence — the display stays on the boot framebuffer permanently —… |
|
||||||
|
| `system/drivers/virtio-gpu/virtio-gpu.zig:525` | <inline literal> .count = offered_modes.len set … | 2 offered vs 4 slots | our-design | Not reachable at current constants (offered_modes.len = 2 <= scanout_protocol.max_modes = 4), so nothing happens today. The shape is unsafe as describ… | Would be silent at the point of the bug; the downstream re-clamps mean the surplus is dropped rather than read… |
|
||||||
|
| `system/kernel/acpi.zig:130` | maximum_rmrr | 8 | hardware | Counted, not silent — confirmed at acpi.zig:873-882: `if (platform_information.rmrr_count < maximum_rmrr) { ...record... } else { platform_information… | Good, and I verified the log fires: system/kernel/iommu.zig:393-394 `if (info.rmrr_skipped > 0) log.print(" r… |
|
||||||
|
| `system/kernel/architecture/x86_64/cpu.zig:69` | systemCallArg (switch arms 0..5) | 6 arguments | our-design | `else => 0` — an argument index of 6 or more silently reads as zero rather than failing. Same shape at cpu.zig:788 (`pioRead` returns 0 for a width ot… | None; a caller asking for a seventh argument gets a plausible-looking 0. |
|
||||||
|
| `system/kernel/architecture/x86_64/gdt.zig:28` | entries | 7 | our-design | Compile-time only. `const entries = 7;` sizes the template (gdt.zig:36-44) and both gdts rows; setTssFor writes fixed indices 5 and 6, and loadOnThisC… | n/a — a build-time constraint. |
|
||||||
|
| `system/kernel/architecture/x86_64/gdt.zig:50` | gdts | [maximum_cpus][7]u64 (128 ta… | hardware | `loadOnThisCpu(cpu)` (gdt.zig:78-84) takes `@intFromPtr(&gdts[cpu])` with no guard in this file; in a safe build an out-of-range cpu is a bounds-check… | Via the ACPI/SMP path only: kernel.zig:281 prints 'cpus : WARNING {d} core(s) beyond pool cap dropped' from pl… |
|
||||||
|
| `system/kernel/architecture/x86_64/ioapic.zig:24` | overrides | [16]IsoEntry | hardware | Silent truncation at three independent layers, all verified: acpi.zig:558 `if (platform_information.override_count < platform_information.overrides.le… | None at any of the three layers — no counter, no log. |
|
||||||
|
| `system/kernel/architecture/x86_64/iommu-intel.zig:284` | <inline literal> 10_000_000 (spinStatus) | 10000000 | our-design | Logs a warning and returns; `enable()` then sets `gcmd_shadow \|= gcmd_te` and the core reports the IOMMU as online even though translation may not be… | "/system/kernel: WARNING VT-d status bit never set — translation may be incomplete" — a real log line, which i… |
|
||||||
|
| `system/kernel/architecture/x86_64/paging.zig:70` | bootstrap_physmap_limit | 4 << 30 (4 GiB) | hardware | `@panic("paging: table frame above the 4 GiB bootstrap physmap")` at paging.zig:84-85, guarded by `if (!on_own_tables and frame >= bootstrap_physmap_l… | A named panic message on the console/serial. The 9-line comment at lines 55-62 states the window, why it holds… |
|
||||||
|
| `system/kernel/architecture/x86_64/per-cpu.zig:50` | blocks | [maximum_cpus]ArchitecturePe… | hardware | `setLocal(index, …)` and `setKernelRsp(index, …)` index unguarded; bounded upstream, ReleaseSafe bounds check as backstop. A ReleaseFast build would w… | Nothing in this file. |
|
||||||
|
| `system/kernel/architecture/x86_64/serial.zig:83` | <inline literal> 10_000 (probe guard) | 10000 | hardware | The loop ends, `echo = register(0)` is read regardless, and `return echo == 0xAE` (serial.zig:83-86). A false answer sets uart_present = false, after … | Recoverable but indirect: present() is exposed (serial.zig:91-93) and the boot log reports the posture, and re… |
|
||||||
|
| `system/kernel/architecture/x86_64/smp.zig:124` | <inline literal> (1 << 32) | 4294967296 | our-design | `if (cr3 >= (1 << 32)) @panic("smp: kernel page tables above 4 GiB");` — the first statement of startAp, before arm() and before any INIT/SIPI is sent… | Named panic message that states the actual condition. |
|
||||||
|
| `system/kernel/architecture/x86_64/smp.zig:141` | <inline literal> @intCast(tramp_physical >> 12) | u8 SIPI vector (frame must b… | hardware | `const vector: u8 = @intCast(tramp_physical >> 12);` — in a safety-checked build (the default), a trampoline frame at or above 1 MiB triggers a "cast … | A safety-check panic with the generic cast message — it does not name the trampoline or the 1 MiB constraint. … |
|
||||||
|
| `system/kernel/architecture/x86_64/smp.zig:149` | <inline literal> 100 (ms AP wake window) | 100 | our-design | `const deadline = apic.millis() + 100;` then a pause-spin on ap_alive; on expiry `return false`. The caller at system/kernel/kernel.zig:437-444 retrie… | Good, and the best in this set. On give-up: `log.print("/system/kernel: cpu apic_id {d}: no response after {d… |
|
||||||
|
| `system/kernel/architecture/x86_64/tss.zig:48` | tss_table / ap_ist_top | [maximum_cpus]Tss and [maxim… | hardware | `rsp0Ptr` (62-64), `setApIstStack` (68-70) and `setupThisCpu` index `tss_table[cpu]` / `ap_ist_top[cpu]` with no guard in this file; the bound is enfo… | Reported by the layer above, and it really is reported: kernel.zig:280-281 `if (platform.cpusDropped() > 0) lo… |
|
||||||
|
| `system/kernel/device-model.zig:72` | name_buffer | [24]u8 | our-design | Silent truncation in `setName` (lines 94-98, `@min` then `@memcpy`), reached from `DeviceTree.init` (line 138) and `addChild` (line 159). In practice … | None, but nothing incorrect happens either; names are diagnostic only (the boot dump), never a matching key. |
|
||||||
|
| `system/kernel/device-model.zig:72` | Device.name_buffer | [24]u8 | our-design | Silent truncation in setName; unreachable in practice. See the kernel-core duplicate: every caller passes either a literal or the result of a bufPrint… | None needed. |
|
||||||
|
| `system/kernel/ipc-synchronous.zig:71` | POST_MAXIMUM | 64 | our-design | `if (len > POST_MAXIMUM) return -E2BIG;` — sendLocked, ipc-synchronous.zig:566, before anything is touched. A distinct errno straight back to the call… | -E2BIG, specific and actionable. |
|
||||||
|
| `system/kernel/ipc-synchronous.zig:113` | notify_buffer | [8]u64 | our-design | Silent drop of the NEWEST badge: notifyLocked, ipc-synchronous.zig:596-602 — the store happens only inside `if (endpoint.notify_tail -% endpoint.notif… | None, and the file argues at 593-595 why that is correct for a level rather than merely tolerable. |
|
||||||
|
| `system/kernel/ipc-synchronous.zig:113` | Endpoint.notify_buffer | [8]u64 | our-design | Silent drop of the newest badge — outside notifyLocked's guard nothing but the wake happens (ipc-synchronous.zig:596-602). | Nothing, by design. |
|
||||||
|
| `system/kernel/kernel.zig:246` | isos | [16]architecture.IsoEntry | hardware | Silent clamp: `var isos: [16]architecture.IsoEntry = undefined; const iso_n = @min(pinfo.override_count, isos.len);` (246-247) — a second truncation s… | None. The boot log prints the I/O APIC base and route information but never the override count. |
|
||||||
|
| `system/kernel/kernel.zig:421` | maximum_wake_attempts | 3 | our-design | The core is left parked and bring-up continues: the `while (attempt <= maximum_wake_attempts)` loop at 437 falls through to the log at 443-444; the ad… | Exemplary, and verified verbatim: `log.print("/system/kernel: cpu apic_id {d}: no response after {d} attempts… |
|
||||||
|
| `system/kernel/log.zig:41` | maximum_sinks | 8 | our-design | Silent ignore, confirmed at lines 47-52: `pub fn addSink(sink: SinkFn) void { if (sink_count < maximum_sinks) { sinks[sink_count] = sink; sink_count +… | None in code, though self-announcing in practice (output does not appear on the missing channel). |
|
||||||
|
| `system/kernel/log.zig:85` | ring_capacity | 512 * 1024 | our-design | Whole records are reclaimed from the tail, never a torn record — confirmed at log-ring.zig:48, `while (self.head + record_len - self.tail > capacity) … | Best in the tree, as claimed, and I verified each mechanism: per-boot monotonic `sequence` stamped into every … |
|
||||||
|
| `system/kernel/log.zig:244` | PanicRecord.message | [512]u8 | our-design | Silent truncation that is self-describing, confirmed at lines 251-256: `const n: u32 = @intCast(@min(message.len, panic_record.message.len)); @memcpy(… | The record carries its own length and the magic-last discipline prevents a torn read. Confirmed the caller's p… |
|
||||||
|
| `system/kernel/process.zig:109` | maximum_arguments / maximum_argument_bytes | 8 / 256 | our-design | All three checks confirmed. process.zig:976 `if (arguments_len > maximum_argument_bytes) return fail(state);`; process.zig:1012 `if (argc == maximum_a… | -1 from system_spawn with no log and the error name discarded at process.zig:1018 — confirmed. |
|
||||||
|
| `system/kernel/process.zig:148` | write_buffer | [256]u8 | our-design | Confirmed at process.zig:1801: `if (len <= write_buffer.len and ptr < user_half_end and ptr + len <= user_half_end) { ... } else { fail(state); }` — I… | -1 to the caller at the syscall, and the ring-level truncation is flagged in the record header — the only boun… |
|
||||||
|
| `system/kernel/process.zig:1460` | exit_record_capacity | 64 | our-design | Confirmed. `recordExitLocked` (1467-1470) overwrites the oldest via `exit_record_next = (exit_record_next + 1) % exit_record_capacity;` and an evicted… | -ESRCH with a documented interpretation, and the docstring (1455-1459) states the equivalence to 'an id that n… |
|
||||||
|
| `system/kernel/scheduler.zig:155` | ipc_maximum_handles | 32 | our-design | Visible and correctly unwound, confirmed. `installEntry` (ipc-synchronous.zig:618-627) scans `t.handles` and `return -ENOSPC`; the cap-passing path at… | -ENOSPC reaches the caller through the IPC status — a distinct, actionable error, unlike the -1 that most othe… |
|
||||||
|
| `system/kernel/scheduler.zig:485` | cpus (PerCpu pool) | [maximum_cpus]PerCpu = [128] | hardware | Cannot be overrun. acpi.zig:534-543 gates recording on `if (cpu_information.count < cpu_information.cpus.len)` and counts the surplus into `dropped`, … | kernel.zig:280-281 `if (platform.cpusDropped() > 0) log.print(" cpus : WARNING {d} core(s) beyond pool … |
|
||||||
|
| `system/kernel/tests.zig:410` | buffer (device enumerate staging) | [64]device_abi.DeviceDescrip… | our-design | Two coupled problems. (1) The value 64 duplicates devices-broker's `maximum_devices` in eight places (tests.zig:410, 1449, 2834, 3931, 4230, 4246, 437… | None for either. A test that silently examines a truncated table still passes. |
|
||||||
|
| `system/kernel/vfs.zig:59` | maximum_prefix / maximum_rewrite | 64 / 32 | our-design | Visible refusal on the mount path: mountBackend, vfs.zig:383-384 `if (!isAbsolute(prefix) or prefix.len < 2 or prefix.len > maximum_prefix) return fal… | A -1 return with no log and no distinct errno. The mounting service's own failure message is what an operator … |
|
||||||
|
| `system/kernel/vfs.zig:143` | Directory.path | [maximum_prefix]u8 = [64]u8 | external-data | `@memcpy(d.path[0..parent.len], parent);` (vfs.zig:143) into `path: [maximum_prefix]u8` (vfs.zig:88) with no @min and no guard — the only copy in the … | A boot-time panic in safe modes (loud but fatal, before init runs); nothing at all plus corrupted neighbours i… |
|
||||||
|
| `system/services/acpi/acpi.zig:74` | registered | [64]Registered | our-design | Unreachable — this is NOT the operative ceiling. `if (registered_count >= registered.len) return;` at line 513 is the first statement of registerDevic… | The real ceiling does log, once per lost device: `std.log.info("register refused for {s}", .{hid[0..@intCast(h… |
|
||||||
|
| `system/services/device-manager/device-manager.zig:51` | registry_rules | [64]registry.Rule | external-data | Rules past the 64th are dropped by `registry.parse` (library/device/registry/device-registry.zig:239-241): `if (result.count >= out_rules.len) { resul… | Good: device-manager.zig:72 `if (result.truncated) _ = logging.write("/system/services/device-manager: /system… |
|
||||||
|
| `system/services/device-manager/device-manager.zig:129` | Driver.name_buffer | [64]u8 | our-design | Silent truncation, not refusal: `addDriver` (242-244) `const n = @min(name.len, driver.name_buffer.len); @memcpy(driver.name_buffer[0..n], name[0..n])… | Indirect: the failure appears one step later as `failed to spawn {s}` (line 268) printing the truncated path, … |
|
||||||
|
| `system/services/device-manager/device-manager.zig:260` | id_text | [20]u8 | our-design | `arguments[0] = std.fmt.bufPrint(&id_text, "{d}", .{driver.device_id}) catch return;` (264) — on overflow `spawnDriver` returns without spawning AND w… | None — the only silent return in spawnDriver; every other failure path there logs (268 `failed to spawn`, 285/… |
|
||||||
|
| `system/services/display/backend.zig:69` | <inline literal> | 100 | our-design | Confirmed at lines 68-75: `var tries: u32 = 0; const found = while (tries < 100) : (tries += 1) { if (findDisplay()) \|f\| break f; time.sleepMillis(5… | Logged, but misleadingly — "headless?" is one of at least three possible causes (genuinely headless, discovery… |
|
||||||
|
| `system/services/display/compositor.zig:74` | DamageList.capacity | 16 | our-design | No loss: `add` (lines 79-93) ends `self.rects[capacity - 1] = self.rects[capacity - 1].unite(r);`, so the overflow rectangle is united into the last e… | Not needed — nothing is dropped and nothing becomes incorrect. |
|
||||||
|
| `system/services/display/compositor.zig:121` | TileGrid.maximum_columns / maximum_rows | 128 / 128 | hardware | Graceful, documented degradation. `reset` clamps with `@min((width + tile_size - 1) / tile_size, maximum_columns)` and the same for rows (lines 139-14… | No log, and none needed — the behaviour stays correct, only the repaint granularity changes. |
|
||||||
|
| `system/services/fat/engine.zig:24` | max_transfer_sectors | 8 | our-design | Not a failure mode, confirmed. The transfer loop clamps and issues more commands: `const run: u32 = @intCast(@min(full, max_transfer_sectors));`. The … | Not applicable — correctness is unaffected, only the number of device round-trips. |
|
||||||
|
| `system/services/fat/engine.zig:80` | block_cache_lines | 16 | our-design | Round-robin eviction, write-through — correctness preserved, only hit rate degrades. | Not needed. |
|
||||||
|
| `system/services/fat/engine.zig:871` | <inline literal> | 4096 | external-data | `if (sector_index > 4096) return null;` ends the search, so findFreeRun/addEntry return null, createFile/createDirectory return null and the VFS handl… | None in the service; no log, and the errno collapses into the same ENOENT everything else uses. |
|
||||||
|
| `system/services/fat/engine.zig:1047` | run | [21]EntryLoc | external-data | Silent partial cleanup, confirmed. `var run: [21]EntryLoc = undefined;` at engine.zig:1047 (removeFile, line 1046) and 1114 (rename, line 1110), recor… | None. |
|
||||||
|
| `system/services/init/init.zig:69` | max_services | 16 | external-data | Rows past the 16th are refused and parsing stops: init.zig:114-117 `if (service_count >= services.len) { _ = logging.write(...); break; }`. | Good: a direct `logging.write` (not just a ring entry) naming the file — `"/system/services/init: /system/conf… |
|
||||||
|
| `system/services/init/init.zig:84` | init_csv / protocol_csv | [4096]u8 / [16384]u8 | external-data | Truncation, detected and reported. readConfiguration (init.zig:138-149) fills the buffer and stops (`while (used < into.len) { const n = file.read(int… | An explicit log naming the file and the byte count. It is a heuristic (a file exactly the buffer's size gives … |
|
||||||
|
| `system/services/init/init.zig:84` | init_csv | 4096 bytes | external-data | Silent truncation mid-line via the shared readConfiguration (init.zig:141-146), after which the severed line parses as a service path that does not ex… | The same heuristic info log as protocol.csv: init.zig:147 '{s} filled the read buffer — rows past {d} bytes ar… |
|
||||||
|
| `system/services/init/init.zig:160` | maximum_name | 64 | our-design | Refused, not truncated — contractName, init.zig:498-502 `if (name.len == 0 or name.len > maximum_name) return null;`, and both callers answer with an … | None on the open path, deliberately (init.zig:652-677 explains why a refusal and an absence must be the same a… |
|
||||||
|
| `system/services/init/init.zig:173` | Binding.binary | [64]u8 | our-design | Silent truncation: onBind, init.zig:630-632 `const binary_len = @min(identity.binary.len, slot.binary.len); @memcpy(slot.binary[0..binary_len], identi… | The truncated path is what appears in the provenance line (init.zig:635) and in the EBUSY refusal message (ini… |
|
||||||
|
| `system/services/logger/logger.zig:53` | maximum_files | 24 | our-design | No loss. fileFor (line 229) looks for a matching cached name, then a free slot, then `const cached = slot orelse evictOne() orelse return null;` at li… | Nothing logged on eviction. The symptom is slow logging, not lost logging, which is the right trade. |
|
||||||
|
| `system/services/logger/logger.zig:57` | CachedFile.name | [logging.maximum_process_nam… | external-data | Panic, in a narrower window than claimed. fileFor formats the path FIRST (line 245, `std.fmt.bufPrint(&path, "{s}/{s}.log", ...) catch return null`) i… | A process fault, visible as the logger dying; init's crash-loop policy stops restarting it after three deaths,… |
|
||||||
|
| `system/services/logger/logger.zig:72` | carry_capacity | 64 + 256 + 64 | our-design | consume (line 187-191): `const rest = bytes.len - offset; if (rest > carry_capacity) { carry_len = 0; // cannot happen with sane frames; drop rather t… | Partly self-reporting, and the claim was right to credit it: deliver (lines 199-206) compares header.sequence … |
|
||||||
|
| `system/services/logger/logger.zig:82` | <inline literal> | 64 | our-design | Benign today. `service.run(64, .{ .init = initialise, .on_message = onMessage, ... })` at line 82 sizes the harness receive/reply buffer. The logger s… | None, and none needed while onMessage is a no-op. |
|
||||||
|
| `system/services/logger/logger.zig:243` | path | [base.len + 1 + 19 + 1 + log… | our-design | Silent record loss. `const full = std.fmt.bufPrint(&path, "{s}/{s}.log", .{ boot_directory[0..boot_directory_len], relative }) catch return null;` (li… | None. Records for that process never appear on disk, and the gap accounting cannot flag it: next_expected_sequ… |
|
||||||
|
| `tools/make-fat-image.py:53` | <inline literal> (65525) | 65525 clusters (~33 MiB at 5… | our-design | Loud build failure: `sys.exit(f"error: image too small for FAT32 ({self.cluster_count} clusters < 65525); use a larger size")` — and --verify repeats … | Build stops with a message naming both the actual count and the requirement, and telling the operator what to … |
|
||||||
|
| `tools/make-fat-image.py:212` | <inline literal> (LFN sequence numbering) | implicitly 20 entries / 255 … | our-design | Silent corruption (my reading; not exercised): `count = len(pairs) // 13` then `entry[0] = sequence \| (0x40 if sequence == count else 0)` — for a nam… | Nothing at build time; --verify only resolves EFI/BOOT/BOOTX64.EFI by short name, so a mangled LFN chain elsew… |
|
||||||
|
| `tools/make-fat-image.py:329` | <inline literal> (guard) | 100000 cluster hops | our-design | `return None`, which the caller turns into a misleading verdict: `sys.exit("verify: EFI/BOOT/BOOTX64.efi not found")` — a chain-too-long or cyclic FAT… | A wrong-but-visible error message. The operator is told the stub is absent when the real problem is FAT struct… |
|
||||||
|
| `tools/make-iso-image.py:151` | sector_count | 0xFFFF (32 MiB at 512 B/sect… | our-design | Deliberate silent clamp, confirmed at line 151: `sector_count = min(0xFFFF, esp_size // 512)`, packed into the El Torito default entry's 16-bit field … | Nothing at build time about the clamp itself, but the true geometry is visible: the builder prints the ESP siz… |
|
||||||
|
| `tools/make-xkeyboard-config.py:308` | <inline literal> (range(256)) / generated keys: … | 256 HID usages | hardware | No overflow inside the generator (HID_TO_NAME only maps usages below 0x100). The bound is exported into the generated `Layout.keys: [256]Key`, so any … | Nothing here; whatever the input service does with an out-of-range usage is its own concern (outside this area… |
|
||||||
|
| `tools/make-xkeyboard-config.py:314` | <inline literal> (range(4)) / generated levels: … | 4 shift levels per key | external-data | Silent truncation at generation time: `levels = [resolve_keysym(kd.levels[i], keysymdef) if i < len(kd.levels) else (0, 0) for i in range(4)]` — level… | Nothing. The generator prints no warning and the generated file looks complete; the missing characters only ap… |
|
||||||
|
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
# The hot-plug matrix: unplug anything, replug anywhere
|
||||||
|
|
||||||
|
*Status: COMPLETE, 2026-08-09, same day — H1..H5 all green, full suite 124/124.
|
||||||
|
The predicted cascade bug was real and found by H2: `tearDownPort` did not recurse
|
||||||
|
into a hub yanked from a root port, so its subtree stayed live against vanished
|
||||||
|
hardware and the replugged hub found its port occupied; fixed by mirroring
|
||||||
|
`tearDownHubDevice`'s children-first recursion (77e7001). Every other cell passed
|
||||||
|
against the establishment-track machinery unchanged.*
|
||||||
|
|
||||||
|
*2026-08-09. The requirement, verbatim: "i want to be able to unplug devices and
|
||||||
|
plug them back in, in any order and on any hub." The machinery exists end to end —
|
||||||
|
per-device driver processes, cascading teardown (`tearDownHubDevice` recurses a
|
||||||
|
departing hub's subtree, children first), reap-on-removal in the manager, idempotent
|
||||||
|
per-port registration identity, lineage rebinding — but only one cell of the matrix
|
||||||
|
is verified: a leaf keyboard behind a hub, unplugged and replugged on the same port
|
||||||
|
(`usb-hub-unplug`). This plan verifies the rest and fixes what verification flushes
|
||||||
|
out. The cascade path has never executed; expect it to carry at least one bug.*
|
||||||
|
|
||||||
|
**Out of scope, stated up front:** unplugging the BOOT stick (the drivers handle it;
|
||||||
|
fat holds a dead block channel until M21 remount gives it re-acquisition), and
|
||||||
|
real-hardware root-port timing (the Ryzen bench is the acceptance run for that, as
|
||||||
|
always — QEMU proves the logic, not the silicon).
|
||||||
|
|
||||||
|
## The discrimination lever
|
||||||
|
|
||||||
|
Every case's rebind tail (— reaping → delegated → second-generation `ok`) is
|
||||||
|
impossible without the manager's reap: stashing the reap out of
|
||||||
|
`onChildRemoved`/`pruneChildrenOf` makes every matrix case fail at the dedupe wall.
|
||||||
|
That is the standing discrimination check for the whole matrix — run it once per
|
||||||
|
case shape, not per commit.
|
||||||
|
|
||||||
|
## The matrix
|
||||||
|
|
||||||
|
| Case | Topology | Event sequence | What it proves |
|
||||||
|
|---|---|---|---|
|
||||||
|
| H1 `usb-root-replug` | keyboard on a 2nd controller's ROOT port | del @8s, add @14s (same port) | the `tearDownPort` path + reap + rebind; root-port changes arrive via the 250 ms reconcile tick (QEMU raises no root-port events) |
|
||||||
|
| H2 `usb-hub-yank` | hub on 2nd controller; keyboard AND mouse behind it | del the HUB @8s; re-add hub @14s, kbd @17s, mouse @18s | the recursive cascade: one event removes the subtree, EVERY bound driver is reaped, and the rebuilt hub re-binds both |
|
||||||
|
| H3 `usb-hub-nested-yank` | hub → hub → keyboard | del the OUTER hub @8s; re-add all three @14–18s | the cascade recursion depth ≥ 2, and a nested rebuild |
|
||||||
|
| H4 `usb-replug-moved` | keyboard behind hub port 1.1 | del @8s; add on port 1.2 @14s | a replug on a DIFFERENT port is simply a new device: new port identity, new id, fresh match — no stale state ties a driver to the old port |
|
||||||
|
| H5 `usb-replug-cycles` | keyboard behind hub | del/add three times (6 hooks) | no state leaks across generations: slots, the bus's open table, driver entries (reaped entries must be reusable) |
|
||||||
|
|
||||||
|
Ordered expects follow the `usb-hub-unplug` shape: the boot devices' `ok` lines all
|
||||||
|
precede the first unplug, so a tail of `removed → reaping → delegated → ok` can only
|
||||||
|
be satisfied by the generation the sequence created. H2/H3 require one `reaping` per
|
||||||
|
bound child; H5 requires three.
|
||||||
|
|
||||||
|
## Order and discipline
|
||||||
|
|
||||||
|
H1 → H2 → H3 → H4 → H5, one commit per case (plus its fix if it finds a bug — the
|
||||||
|
case and the fix land together, the case having failed first). The standing
|
||||||
|
discrimination run once for H1 and once for H2's shape. Full suite green at the end,
|
||||||
|
docs touched where behavior was corrected, memory updated. Fixes stay within the
|
||||||
|
settled design: teardown order (children first), reap-on-removal, identity per port
|
||||||
|
— anything design-shaped that surfaces stops the loop and asks.
|
||||||
-132
@@ -1,132 +0,0 @@
|
|||||||
# IPC: message-passing channels
|
|
||||||
|
|
||||||
Inter-process communication is the **backbone of a microkernel**. Once drivers and
|
|
||||||
services run isolated in their own address spaces ([vision](vision.md)), they can't
|
|
||||||
just call each other — a request becomes a **message**. In a microkernel, whatever
|
|
||||||
was a function call across a monolithic kernel is IPC, so it's a first-class
|
|
||||||
concern, not an afterthought.
|
|
||||||
|
|
||||||
There are two layers, built a milestone apart:
|
|
||||||
|
|
||||||
- **`system/kernel/ipc.zig`** — a bounded blocking channel between *kernel threads*,
|
|
||||||
described below. The primitive, and where the blocking discipline was worked out.
|
|
||||||
- **`system/kernel/ipc-synchronous.zig`** — synchronous call/reply between *processes*, across
|
|
||||||
address spaces. What user-space servers and drivers actually talk over. It's the
|
|
||||||
second half of this document.
|
|
||||||
|
|
||||||
## The channel
|
|
||||||
|
|
||||||
The first form is a **bounded blocking channel** (`system/kernel/ipc.zig`): a fixed-size
|
|
||||||
ring buffer of messages with a producer/consumer rendezvous, built on the
|
|
||||||
scheduler's [wait queues](scheduling.md).
|
|
||||||
|
|
||||||
`Channel(T, capacity)` is generic over the message type and buffer size. It holds a
|
|
||||||
ring buffer, a count, and two wait queues:
|
|
||||||
|
|
||||||
- **`send(msg)`** — if the channel is full, block on the *not-full* queue; otherwise
|
|
||||||
write the message, bump the count, and wake a waiting receiver.
|
|
||||||
- **`receive()`** — if the channel is empty, block on the *not-empty* queue; otherwise
|
|
||||||
take a message, drop the count, and wake a waiting sender.
|
|
||||||
|
|
||||||
Neither side busy-waits: a full channel parks the sender, an empty one parks the
|
|
||||||
receiver, and each operation wakes the other side when it makes progress possible.
|
|
||||||
|
|
||||||
Two details make it correct:
|
|
||||||
|
|
||||||
- **Recheck in a loop.** A woken task re-tests the condition (`while (full) wait`)
|
|
||||||
rather than assuming the slot is still available — another waiter may have taken
|
|
||||||
it first. This is the standard guard against spurious or racing wakeups.
|
|
||||||
- **One critical section.** `send`/`receive` run under the [big kernel
|
|
||||||
lock](smp.md) (`sync.enter` / `sync.leave`), which disables interrupts on this
|
|
||||||
core *and* takes the kernel's one spinlock — since SMP, the interrupt flag alone
|
|
||||||
is not atomicity, because `cli` on one core does nothing to another. So checking
|
|
||||||
the condition and committing the block/enqueue happen atomically both with respect
|
|
||||||
to the timer preempting mid-operation and to the other side running on another
|
|
||||||
CPU. `waitLocked` / `wakeLocked` are the variants that assume the caller already
|
|
||||||
holds that critical section.
|
|
||||||
|
|
||||||
## Verifying it
|
|
||||||
|
|
||||||
The `ipc` test (see [testing.md](testing.md)) runs a producer and a consumer passing
|
|
||||||
**100 messages through a 4-slot channel**. The small buffer means the channel goes
|
|
||||||
full and empty over and over, so both the blocking-send and blocking-receive paths are
|
|
||||||
exercised heavily. The messages arrive intact and in order (their sum is the
|
|
||||||
expected `5050`), and neither task busy-waits — they block and wake each other.
|
|
||||||
|
|
||||||
## Endpoints: call/reply across address spaces
|
|
||||||
|
|
||||||
A channel connects two kernel threads sharing one address space. Real servers are
|
|
||||||
*processes*, so the payload has to cross an address-space boundary. That's
|
|
||||||
`system/kernel/ipc-synchronous.zig`, and its shape is L4's: a synchronous **rendezvous** at an
|
|
||||||
`Endpoint`, with the message copied directly from the sender's pages to the receiver's
|
|
||||||
(`copyAcross` walks both sets of page tables through the physmap — no CR3 switch, no
|
|
||||||
bounce buffer).
|
|
||||||
|
|
||||||
Two syscalls carry it:
|
|
||||||
|
|
||||||
- **`ipc_call(h, msg, reply)`** — copy `msg` to the server, block until it replies.
|
|
||||||
- **`ipc_reply_wait(h, reply, recv)`** — reply to the client you're still holding (if
|
|
||||||
any), then block for the next request. One syscall, because a server's steady state
|
|
||||||
is *always* "finish the last one, wait for the next".
|
|
||||||
|
|
||||||
An endpoint is reached by **handle** — a small integer index into the process's handle
|
|
||||||
table (`Task.handles`), exactly like a file descriptor, and just as unforgeable. The
|
|
||||||
bootstrap problem (how do you get the first handle?) is solved by a tiny name registry:
|
|
||||||
a server calls `ipc_register(service_id, h)` under a well-known small integer, and a
|
|
||||||
client calls `ipc_lookup(service_id)`.
|
|
||||||
|
|
||||||
The server never learns the client's identity beyond a **badge**, delivered alongside
|
|
||||||
the message: the caller's task id.
|
|
||||||
|
|
||||||
### Interrupts are messages too
|
|
||||||
|
|
||||||
`notifyFromIsr` posts an *asynchronous* notification to an endpoint — no payload, no
|
|
||||||
reply owed — and wakes whoever is blocked in `reply_wait`. Its badge has the top bit
|
|
||||||
set (`notify_badge_bit`), which is how a driver's single event loop distinguishes "a
|
|
||||||
client wants something" from "the hardware wants something". Notifications sit in a
|
|
||||||
small coalescing ring on the endpoint, so an interrupt taken while the driver was busy
|
|
||||||
elsewhere is not lost.
|
|
||||||
|
|
||||||
This is what makes a user-space driver possible at all, and it's the subject of
|
|
||||||
[drivers.md](drivers.md).
|
|
||||||
|
|
||||||
## What's next (partly done since)
|
|
||||||
|
|
||||||
- **Priority inheritance** through IPC — still open: a high-priority client
|
|
||||||
blocked on a low-priority server suffers unbounded priority inversion.
|
|
||||||
- **Handle transfer.** *Landed as cap-passing (M13)*: `ipc_call` and
|
|
||||||
`ipc_reply_wait` carry an optional capability alongside the bytes (`send_cap`),
|
|
||||||
copying an endpoint or shared-memory handle into the peer's table. First user:
|
|
||||||
[input](input.md) subscribers register by handing over their own endpoint, and
|
|
||||||
class drivers get a private channel to one device.
|
|
||||||
- **Asynchronous / buffered send** for the cases where a rendezvous is the wrong
|
|
||||||
shape (logging, notifications between servers). *Landed as `ipc_send`* — a
|
|
||||||
non-blocking post to an endpoint's bounded payload queue, delivered through
|
|
||||||
`reply_wait` as a buffered message (badge bit `notify_message_bit`). Built for, and
|
|
||||||
first used by, the [input service](input.md)'s keyboard-event broadcast, where a
|
|
||||||
synchronous push would let one dead subscriber hang the fan-out. A full queue drops
|
|
||||||
the oldest (discrete messages, not a coalescing level like the notification ring).
|
|
||||||
- **A bounded reply** — half landed. The copy is still 256 bytes
|
|
||||||
(`MESSAGE_MAXIMUM`) under the big kernel lock, but bulk transfer got its shared
|
|
||||||
pages: `shared_memory_create`/`map`/`physical`, the region handle delegated as
|
|
||||||
a capability (above). virtio-gpu's scanout surface is the first user
|
|
||||||
([display-v2.md](display-v2.md)).
|
|
||||||
|
|
||||||
## Lifecycle conventions over IPC (M17)
|
|
||||||
|
|
||||||
Three conventions from [process-lifecycle.md](process-lifecycle.md) ride the
|
|
||||||
notification mechanism:
|
|
||||||
|
|
||||||
- **Signals** arrive as notifications on the endpoint a process nominated with
|
|
||||||
`signal_bind` (`runtime.process.bindSignals`): badge = the signal bit plus the
|
|
||||||
coalesced pending mask (`runtime.process.signalsFrom` decodes). Statements,
|
|
||||||
never questions; no payload, no reply.
|
|
||||||
- **One-shot timers** (`timer_bind`, `runtime.system.timerOnce`) land as a
|
|
||||||
timer-bit notification — the timed wait: a service arms a deadline and keeps
|
|
||||||
serving, instead of blocking in sleep.
|
|
||||||
- **The universal ping**: a **zero-length request is the liveness probe**,
|
|
||||||
answered with a zero-length reply by the service harness itself
|
|
||||||
(`runtime.service.run`). No protocol's requests start at length zero, so the
|
|
||||||
encoding cannot collide, and a wedged service simply fails to answer — which
|
|
||||||
is the diagnosis. Deep health ("can I reach my hardware?") stays a per-service
|
|
||||||
protocol message.
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
# OS Developer Guide
|
|
||||||
|
|
||||||
This document is for those who need to understand the architectural decisions behind the OS.
|
|
||||||
|
|
||||||
## Written in Zig?
|
|
||||||
|
|
||||||
The os was initially written in zig because it has excellent support for EFI. With zig, we could forgo using a third party bootloader, reducing the time to boot up the kernel. Following the "Zen of Zig", helped to produce the most readable codebase for an operating system ever created. So those, new to OS development could quickly get up to speed.
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
# OS Development
|
||||||
|
|
||||||
|
This document explains the architectural decisions behind the operating system.
|
||||||
|
|
||||||
|
## Written in Zig?
|
||||||
|
|
||||||
|
The OS is written in Zig because it has excellent EFI support, so the OS boots quickly without a third-party bootloader.
|
||||||
|
|
||||||
|
Zig comes batteries included for systems work — cross-compilation, a build system, and a test runner are all part of the toolchain. Building with `-Doptimize=ReleaseSafe` keeps runtime safety checks on in the shipped kernel, which removes entire classes of bugs. The built-in test suite, combined with a QEMU integration harness, means every feature is proven to work, before it is shipped.
|
||||||
|
|
||||||
|
The codebase of the OS prioritizes readability. The aim is a codebase where someone new to OS development can find their way around without a guide.
|
||||||
|
|
||||||
|
## A microkernel?
|
||||||
|
|
||||||
|
The kernel is a thin layer: it schedules processes and manages memory. Everything else — drivers, file systems, the display — runs in user space as separate, isolated processes.
|
||||||
|
|
||||||
|
The payoff is resilience. When a driver crashes, it doesn't take the OS down with it; it gets restarted. That makes this an ideal environment for *developing* an operating system, because a buggy driver is an ordinary bug: patch it, restart the service, and keep going.
|
||||||
|
|
||||||
|
There is a security benefit too. Processes are isolated and talk over Inter-Process Communication (IPC) channels, so compromising one service doesn't hand an attacker the whole machine. Vulnerabilities tend to stay contained in the process they started in.
|
||||||
|
|
||||||
|
Other operating systems choose to pack all of these duties into one binary as a Monolithic kernel, mostly for performance: a function call inside the kernel is faster than passing a message between isolated processes. That cost is real — an IPC round-trip is a few microseconds where a function call is nanoseconds — but it is also workload-shaped. Compute-bound programs don't notice it at all. For bulk data like file contents and pixels, the design moves data through shared memory and DMA so it is copied once, the same as a monolithic kernel; only small control messages cross the IPC boundary. What remains is the per-message cost on chatty paths, and the scheduler and memory management are designed to keep that small.
|
||||||
|
|
||||||
|
## Private ABI
|
||||||
|
|
||||||
|
The syscall layer is private. The numbers and structures in `abi.zig` are an internal detail shared between the kernel and the system's own libraries, and they are free to change between builds.
|
||||||
|
|
||||||
|
The public boundary sits one level up: the [vDSO](vdso.md) that programs call into, and the documented IPC protocols such as the [VFS protocol](../file-system-development/vfs-protocol.md). Programs that stick to those interfaces keep working while the kernel rearranges itself underneath. This is the opposite of the Linux approach, where raw syscall numbers are frozen forever; here, stability is promised at the library and protocol level, and nowhere below it.
|
||||||
|
|
||||||
|
## Steal the best bits and dump the legacy
|
||||||
|
|
||||||
|
The OS is Unix-like, but selectively. It borrows the ideas that have aged well — everything is a file, small services composed over clean interfaces — and skips the parts of POSIX that have caused decades of headaches.
|
||||||
|
|
||||||
|
Some concrete choices:
|
||||||
|
|
||||||
|
- **`spawn`, not `fork`.** Creating a process starts a fresh program and returns the child's id. There is no clone-the-whole-address-space-then-immediately-throw-it-away dance, and none of the subtle state-inheritance bugs that come with it.
|
||||||
|
- **Time is a syscall.** The kernel owns the clock and timers directly. There is no time daemon to keep alive and no ambiguity about where the truth lives.
|
||||||
|
- **Lifecycle events arrive as messages.** A supervisor learns that a child exited through an IPC message on an endpoint it already owns — delivered like any other message, not as an interrupt that can fire between any two instructions.
|
||||||
|
|
||||||
|
The test for keeping an idea is simple: does it still pull its weight, or is it only there because it was there in 1979?
|
||||||
@@ -19,10 +19,10 @@ UEFI configuration table
|
|||||||
BootInformation.acpi_rsdp (u64, in the loader↔kernel handoff) system/boot-handoff.zig
|
BootInformation.acpi_rsdp (u64, in the loader↔kernel handoff) system/boot-handoff.zig
|
||||||
│ the kernel forwards the whole BootInformation
|
│ the kernel forwards the whole BootInformation
|
||||||
▼
|
▼
|
||||||
platform.discover(boot_information, …) system/devices/platform.zig
|
platform.discover(boot_information, …) system/kernel/platform.zig
|
||||||
│ reads boot_information.acpi_rsdp, hands it to the ACPI backend
|
│ reads boot_information.acpi_rsdp, hands it to the ACPI backend
|
||||||
▼
|
▼
|
||||||
acpi.discover(rsdp_phys, …) system/devices/acpi.zig
|
acpi.discover(rsdp_phys, …) system/kernel/acpi.zig
|
||||||
│ dereferences the RSDP, reads the pointer it contains
|
│ dereferences the RSDP, reads the pointer it contains
|
||||||
▼
|
▼
|
||||||
RSDP ──(a field in the struct)──► RSDT / XSDT ──► SDTs (MADT, MCFG, FADT, HPET, DSDT…)
|
RSDP ──(a field in the struct)──► RSDT / XSDT ──► SDTs (MADT, MCFG, FADT, HPET, DSDT…)
|
||||||
@@ -75,9 +75,9 @@ There are really two independent questions, and it's worth not conflating them:
|
|||||||
- **`system/kernel/architecture/x86_64/paging.zig`** — the kernel's page tables and address-space
|
- **`system/kernel/architecture/x86_64/paging.zig`** — the kernel's page tables and address-space
|
||||||
management (see [paging.md](paging.md)).
|
management (see [paging.md](paging.md)).
|
||||||
- **`system/kernel/architecture/x86_64/apic.zig`** / **`ioapic.zig`** — the Local APIC, its timer,
|
- **`system/kernel/architecture/x86_64/apic.zig`** / **`ioapic.zig`** — the Local APIC, its timer,
|
||||||
and the I/O APIC for device interrupts (see [device-interrupts.md](device-interrupts.md)).
|
and the I/O APIC for device interrupts (see [device-interrupts.md](../device-driver-development/device-interrupts.md)).
|
||||||
- **`system/kernel/architecture/x86_64/serial.zig`** / **`io.zig`** — the COM1 UART (the kernel's
|
- **`system/kernel/architecture/x86_64/serial.zig`** / **`io.zig`** — the COM1 UART (the kernel's
|
||||||
machine-readable log channel, see [testing.md](testing.md)) and the shared port-I/O + MSR primitives.
|
machine-readable log channel, see [testing.md](../testing.md)) and the shared port-I/O + MSR primitives.
|
||||||
- **`system/kernel/architecture/x86_64/smp.zig`** / **`per-cpu.zig`** — application-processor bring-up
|
- **`system/kernel/architecture/x86_64/smp.zig`** / **`per-cpu.zig`** — application-processor bring-up
|
||||||
and per-CPU state (GS base, system-call entry point, see [scheduling.md](scheduling.md)).
|
and per-CPU state (GS base, system-call entry point, see [scheduling.md](scheduling.md)).
|
||||||
- **`system/kernel/architecture/x86_64/isr.s`** — the exception stubs, the `lgdt`/`lidt`/`ltr` load
|
- **`system/kernel/architecture/x86_64/isr.s`** — the exception stubs, the `lgdt`/`lidt`/`ltr` load
|
||||||
@@ -87,7 +87,7 @@ The Pi is not a "standard" ARM platform — expect Broadcom-specific peripherals
|
|||||||
Pi 5. Everything below is an offset from it.
|
Pi 5. Everything below is an offset from it.
|
||||||
- **UART**: a **PL011** (at base + `0x20_1000`) plus a mini-UART; on some boards the
|
- **UART**: a **PL011** (at base + `0x20_1000`) plus a mini-UART; on some boards the
|
||||||
PL011 is wired to Bluetooth, so which one is the console varies. This is the
|
PL011 is wired to Bluetooth, so which one is the console varies. This is the
|
||||||
`aarch64`/`arm` equivalent of our x86 [COM1 serial](testing.md).
|
`aarch64`/`arm` equivalent of our x86 [COM1 serial](../testing.md).
|
||||||
- **Interrupt controller**: *not* a standard ARM GIC on the older parts — the Zero W
|
- **Interrupt controller**: *not* a standard ARM GIC on the older parts — the Zero W
|
||||||
and Pi 3 use Broadcom's own ARMCTRL controller (Pi 3 adds a per-core "local"
|
and Pi 3 use Broadcom's own ARMCTRL controller (Pi 3 adds a per-core "local"
|
||||||
controller for timers/mailboxes). The **Pi 4 and 5 do have a GIC-400**. So the
|
controller for timers/mailboxes). The **Pi 4 and 5 do have a GIC-400**. So the
|
||||||
@@ -122,4 +122,4 @@ Two routes, mirroring how we test x86-64 with OVMF:
|
|||||||
- [architecture.md](architecture.md) — the arch-module boundary these targets plug into, and the
|
- [architecture.md](architecture.md) — the arch-module boundary these targets plug into, and the
|
||||||
CPU-arch vs boot-protocol "two axes".
|
CPU-arch vs boot-protocol "two axes".
|
||||||
- [efi.md](efi.md) — the UEFI loader that carries over to aarch64-UEFI.
|
- [efi.md](efi.md) — the UEFI loader that carries over to aarch64-UEFI.
|
||||||
- [vision.md](vision.md) — why isolated, portable-across-architectures is the goal.
|
- [vision.md](../vision.md) — why isolated, portable-across-architectures is the goal.
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
# Bounds: how a ceiling is declared
|
||||||
|
|
||||||
|
*Design, 2026-08-08. Follows [fixed-bounds-audit.md](../fixed-bounds-audit.md), which
|
||||||
|
found 235 compile-time ceilings in this tree: 139 on quantities we do not choose, 5
|
||||||
|
recorded anywhere with their reasoning, and 171 that pass in silence when reached.*
|
||||||
|
|
||||||
|
A bound is a number chosen at compile time that decides how much of something the code
|
||||||
|
can hold. `const maximum_devices = 64`. `var below: [64]Range`. `var blob: [512]u8`.
|
||||||
|
Different units — devices, firmware memory-map entries, bytes of a USB descriptor — but
|
||||||
|
one shape, and one recurring way of going wrong.
|
||||||
|
|
||||||
|
## Where a bound lives
|
||||||
|
|
||||||
|
**Where the thing it bounds lives.** A driver's transfer-ring size belongs to that
|
||||||
|
driver; a protocol's payload cap belongs to that protocol; the kernel's task-table size
|
||||||
|
belongs to the kernel. There is no central list and this document does not propose one.
|
||||||
|
|
||||||
|
`system/parameters.zig` is not a counter-example. It is kernel-only, and it exists for a
|
||||||
|
specific historical reason: tunables had accumulated inside the loader↔kernel handoff
|
||||||
|
contract, and splitting them out kept that contract to what it actually is. It is a
|
||||||
|
tidying of one file's contents, not a registry the rest of the system reports to.
|
||||||
|
|
||||||
|
This matters for the mechanism below. An earlier draft had every bound declared through
|
||||||
|
a shared `bounds` module — which would have meant adding a dependency to roughly eight
|
||||||
|
package manifests, including `library/protocol`, which deliberately depends on nothing.
|
||||||
|
That is a coupling the problem does not require: a bound is a local fact about local
|
||||||
|
storage, and the only thing worth sharing is the *shape of the statement*, not a module.
|
||||||
|
|
||||||
|
## The declaration
|
||||||
|
|
||||||
|
A structured doc comment, immediately above the declaration, in the file that owns it:
|
||||||
|
|
||||||
|
```zig
|
||||||
|
/// bound: logical CPUs the kernel tracks
|
||||||
|
/// decided-by: hardware
|
||||||
|
/// protects: the per-CPU bookkeeping arrays, which are sized at compile time
|
||||||
|
/// at-limit: degrade — surplus cores are left parked, never brought online
|
||||||
|
/// observed-by: platform.cpusDropped() -> the WARNING at kernel.zig:281
|
||||||
|
pub const maximum_cpus = 128;
|
||||||
|
```
|
||||||
|
|
||||||
|
Five fields, all mandatory:
|
||||||
|
|
||||||
|
| Field | Answers |
|
||||||
|
|---|---|
|
||||||
|
| `bound` | what is counted, in plain words |
|
||||||
|
| `decided-by` | `hardware`, `external`, or `ours` — who chooses how large it gets |
|
||||||
|
| `protects` | what this ceiling defends against |
|
||||||
|
| `at-limit` | `refuse` / `degrade` / `truncate` / `grow`, and the detail |
|
||||||
|
| `observed-by` | how an operator finds out it was reached |
|
||||||
|
|
||||||
|
`decided-by` is the classification the audit turned on. `hardware` means the machine
|
||||||
|
chooses — PCI functions, CPUs, ACPI rows, memory-map entries. `external` means a file,
|
||||||
|
disk structure or peer chooses. `ours` means we do: a stack size, a tick rate, our own
|
||||||
|
protocol's payload. A fixed bound on the first two is a defect rather than a tunable.
|
||||||
|
|
||||||
|
## What the build step enforces
|
||||||
|
|
||||||
|
A step in `build.zig` reads the tree and fails on:
|
||||||
|
|
||||||
|
1. **A bound with no declaration.** A fixed-size array or a `maximum_*`/`max_*` constant
|
||||||
|
with no `bound:` block above it. The 235 that exist today are allowlisted by
|
||||||
|
file+line+name, so only newly written ones are gated — the rule can land without a
|
||||||
|
235-site sweep in front of it.
|
||||||
|
2. **A missing field.** All five or it fails. This alone is the 97 bounds with no
|
||||||
|
comment at all and the 171 with no observability.
|
||||||
|
3. **An unspeakable `at-limit`.** The vocabulary is closed. There is no `silent`, no
|
||||||
|
`drop`, and nothing meaning *allow*. `truncate` is legal only with a marker the
|
||||||
|
reader can see — `klog_maximum_message` qualifies because the record carries
|
||||||
|
`klog_flag_truncated`; the USB configuration descriptor cut at 512 bytes does not,
|
||||||
|
because nothing records that anything was lost.
|
||||||
|
4. **A stale allowlist entry.** If a listed bound is fixed or deleted, its entry goes
|
||||||
|
too, so the list can only shrink.
|
||||||
|
|
||||||
|
Because this is text and not a Zig type, it also covers `boot/`, which imports almost
|
||||||
|
nothing, and `tools/*.py`, where the audit found bounds as well. One mechanism, whole
|
||||||
|
tree, no new dependency edges.
|
||||||
|
|
||||||
|
## Coupled bounds
|
||||||
|
|
||||||
|
Two numbers that must agree, agreeing in code rather than in a comment — no module
|
||||||
|
needed, just a `comptime` block where one of them lives:
|
||||||
|
|
||||||
|
```zig
|
||||||
|
comptime {
|
||||||
|
if (maximum_domains != devices_broker.maximum_devices)
|
||||||
|
@compileError("iommu.confined is indexed by device id; an id past its end is " ++
|
||||||
|
"left unconfined while confineDevice still reports success");
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`maximum_domains = 64` and `maximum_devices = 64` once agreed only by a sentence in a
|
||||||
|
comment, and that agreement failed open — the clause with the live hole behind it, where
|
||||||
|
raising `maximum_devices` alone left every device id past the end of `iommu.confined`
|
||||||
|
unconfined while `confineDevice` still reported success, a privilege escalation rather
|
||||||
|
than a fix. The assert closed that: it held the two together while both stayed fixed, and
|
||||||
|
when the device table was later made dynamic — no `maximum_devices` any more, only a
|
||||||
|
per-registrar quota — that forced them apart, the assert having done its job. `confined`
|
||||||
|
now grows to cover every id the broker mints, and `confineDevice` refuses when it cannot
|
||||||
|
record a confinement rather than failing open.
|
||||||
|
|
||||||
|
## The worked bad case
|
||||||
|
|
||||||
|
`devices_broker.maximum_devices`, which had no comment at all, before it was made dynamic:
|
||||||
|
|
||||||
|
```zig
|
||||||
|
/// bound: device nodes for the whole machine — firmware-discovered plus registered
|
||||||
|
/// decided-by: hardware
|
||||||
|
/// protects: nothing; this is a sizing guess about someone else's computer
|
||||||
|
/// at-limit: refuse — ENOSPC from device_register, dropped++ during discovery
|
||||||
|
/// observed-by: kernel.zig:203 counts discovery drops only, NOT runtime refusals
|
||||||
|
const maximum_devices = 64;
|
||||||
|
```
|
||||||
|
|
||||||
|
Writing it out is the argument. `decided-by: hardware` alongside a `protects` that
|
||||||
|
admits there is no threat describes a bound that should not be fixed at all, and
|
||||||
|
`observed-by` cannot be filled in honestly. The build step does not reject this — it
|
||||||
|
makes it impossible to write down without noticing.
|
||||||
|
|
||||||
|
## The work-list this produces
|
||||||
|
|
||||||
|
`decided-by` is machine-readable, so the sweep is a query: every `hardware` or
|
||||||
|
`external` bound whose `at-limit` is not `grow`. That is 139 of the 235, and it is the
|
||||||
|
order the fixing takes — by class, not by our guesses about which machines get run.
|
||||||
|
Reachability is exactly what a new computer changes; the Ryzen's cap was unreachable
|
||||||
|
until it wasn't.
|
||||||
|
|
||||||
|
## What this does not do
|
||||||
|
|
||||||
|
**It is a statement, not a proof.** Nothing checks that the code does what `at-limit`
|
||||||
|
claims. The enforcement is completeness and vocabulary: you cannot leave the question
|
||||||
|
unanswered, and you cannot answer it with "silently".
|
||||||
|
|
||||||
|
**It carries no occupancy.** Knowing `system/configuration/protocol.csv` sits at 50 of
|
||||||
|
64 grant rows still needs a counter and somewhere to report it. The declarations make
|
||||||
|
that cheap to add later; it is not here.
|
||||||
|
|
||||||
|
**It resizes nothing.** Declaring `maximum_devices` honestly does not make the Ryzen
|
||||||
|
work. It makes the next machine's failure legible, and it names the 139 that need real
|
||||||
|
fixes.
|
||||||
|
|
||||||
|
**Enforcement is at build time, not compile time.** A Zig type could have made a missing
|
||||||
|
field a compile error. That version needed the shared module, and the module was not
|
||||||
|
worth the coupling — so a missing field is a failed build step instead. In practice both
|
||||||
|
mean `zig build` stops; the difference is which stage prints the message.
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
# Communication: the four layers
|
||||||
|
|
||||||
|
*Design, agreed 2026-07-31. The model document — the vocabulary and layering
|
||||||
|
every other communication document speaks.*
|
||||||
|
|
||||||
|
danos separates **what is said** from **how the bytes move**, so that the
|
||||||
|
mechanism is replaceable. The shape is a network stack's, cut into four
|
||||||
|
layers; a program only ever touches the top two.
|
||||||
|
|
||||||
|
```
|
||||||
|
L3 namespace /protocol/... names establishment points protocol-namespace.md
|
||||||
|
L2 protocol the language: packet schemas, verbs, targets the envelope, library/protocol/*
|
||||||
|
L1 channel two ends exchanging packets and signals the client library's Channel
|
||||||
|
L0 transport a buffer + a doorbell: moves the bytes ipc.md (kernel-ipc), later shm-ring, …
|
||||||
|
```
|
||||||
|
|
||||||
|
## Vocabulary
|
||||||
|
|
||||||
|
| Term | Meaning |
|
||||||
|
|---|---|
|
||||||
|
| **protocol** | The language: which packets exist, what their fields mean, which verbs a provider answers. Defined transport-independently in a `library/protocol/*` module. |
|
||||||
|
| **channel** | An open conversation between two processes, speaking one protocol. Established by opening a `/protocol/...` name; both ends can send and receive. |
|
||||||
|
| **packet** | The unit a protocol transmits: a bounded, atomic header+payload. Never fragmented — if it doesn't fit, it isn't a packet; bulk data rides shared memory with a packet as the doorbell. |
|
||||||
|
| **signal** | A payload-less poke below the packet layer: "something happened, come look." Coalescing — the count may collapse, the fact may not. |
|
||||||
|
| **transport** | What moves the bytes of one channel: a buffer plus a doorbell. Chosen (and upgradable) at establishment, invisible above L1. |
|
||||||
|
| **endpoint** | A termination point where a transport delivers. The kernel-ipc transport's endpoint is its kernel mailbox object. |
|
||||||
|
|
||||||
|
## Addressing: parties by channel, objects by target
|
||||||
|
|
||||||
|
There are no network-style addresses in a packet. The two questions addresses
|
||||||
|
answer are answered at different layers:
|
||||||
|
|
||||||
|
- **Who am I talking to?** The **channel**, decided once at establishment.
|
||||||
|
Opening `/protocol/input` yields a channel; every packet sent on it goes to
|
||||||
|
the peer. Nothing to route per-packet — like TCP, where no HTTP request
|
||||||
|
carries the server's IP.
|
||||||
|
- **Who sent this?** Attached to every received packet **by the channel
|
||||||
|
layer**, from identity the transport can verify — under kernel-ipc, the
|
||||||
|
kernel-stamped badge. The sender never writes a source field, which is what
|
||||||
|
makes source unforgeable (the property a network's spoofable source header
|
||||||
|
lacks).
|
||||||
|
- **Which of your things?** The packet's **`target`** field: *object*
|
||||||
|
addressing within the already-chosen peer — the vfs protocol's node id, the
|
||||||
|
display protocol's layer id, a block volume. `target = 0` addresses the
|
||||||
|
provider itself; a protocol without objects never uses it.
|
||||||
|
|
||||||
|
`target` is how instance multiplicity stays out of the namespace. Ten USB
|
||||||
|
sticks and the namespace still holds exactly one name, `/protocol/block`: a
|
||||||
|
channel to the provider, `enumerate` lists the current volumes as targets, a
|
||||||
|
`targets_changed` signal announces hotplug, and a read names its volume in
|
||||||
|
`target`. The unix `/dev/sda`,`/dev/sdb` problem is dissolved, not renamed.
|
||||||
|
|
||||||
|
If a future transport genuinely routes between machines, *it* carries real
|
||||||
|
source/destination addressing internally at L0 — the way IP runs under TCP —
|
||||||
|
and none of it surfaces into the packet header. Protocols stay ignorant of
|
||||||
|
distance.
|
||||||
|
|
||||||
|
## Establishment: two planes, one namespace
|
||||||
|
|
||||||
|
`target` routes objects *within* a provider. It cannot route *between* provider
|
||||||
|
processes, because "who am I talking to" was decided at establishment — so when a
|
||||||
|
protocol's objects live in several processes, something must resolve establishment
|
||||||
|
to the right one. A real machine forced the question: three xHCI controllers,
|
||||||
|
three `usb-xhci-bus` processes, one `usb-transfer` name, and whichever instance
|
||||||
|
bound first owned every class driver's discovery — a mouse on the second
|
||||||
|
controller was unreachable (`could not open device 50`). The registry's exclusive
|
||||||
|
bind was built for parties that are genuinely singular; per-device driver
|
||||||
|
processes are deliberately *not* singular — one process per device found is what
|
||||||
|
makes a single driver recompilable and restartable while the machine runs.
|
||||||
|
|
||||||
|
So establishment has two planes, and the namespace stays instance-free on both:
|
||||||
|
|
||||||
|
- **Applications establish by name.** `/protocol/input`, `/protocol/display`,
|
||||||
|
`/protocol/ufs` — served by *services*, the layer that aggregates
|
||||||
|
(driver-model.md: services face applications). These are genuinely singular,
|
||||||
|
the registry's exclusive bind is correct for them, and multiplicity behind
|
||||||
|
them is `target`'s job. Ten mice still merge into one `/protocol/input`.
|
||||||
|
- **Drivers establish by topology.** A driver instance *creates its channel* —
|
||||||
|
its own endpoint — and hands it up in the `hello` it already sends, as a
|
||||||
|
capability. The device manager is the establishment router for the device
|
||||||
|
tree because it already owns the routing fact: it knows which instance
|
||||||
|
reported which child. A consumer's `hello` for device N returns a capability
|
||||||
|
to N's provider. The name `usb-transfer` names the *contract*; no process
|
||||||
|
binds it.
|
||||||
|
|
||||||
|
Establishment is always a synchronous call, and always consumer-initiated: the
|
||||||
|
kernel carries one capability in each direction of a call (request and reply),
|
||||||
|
and deliberately none on a push — a provider cannot foist a channel on anyone.
|
||||||
|
Re-establishment after a provider restart is therefore also consumer-initiated:
|
||||||
|
the consumer's channel dies with the provider, and a fresh `hello` fetches the
|
||||||
|
successor's.
|
||||||
|
|
||||||
|
Strip any transport to its skeleton and the same two parts remain:
|
||||||
|
|
||||||
|
| Transport | Buffer | Doorbell | Status |
|
||||||
|
|---|---|---|---|
|
||||||
|
| **kernel-ipc** | kernel-owned mailbox (the `Endpoint`) | the scheduler (rendezvous wake) | the first transport — [ipc.md](../device-driver-development/ipc.md) |
|
||||||
|
| **shm-ring** | user-owned shared-memory ring | a signal | exists ad hoc (display bulk); to be formalized — the unlock for the 256-byte ceiling |
|
||||||
|
| network | NIC queue | an interrupt | someday, when danos networks |
|
||||||
|
|
||||||
|
Transports differ in their **properties**, which the channel layer exposes and
|
||||||
|
the protocol layer may depend on:
|
||||||
|
|
||||||
|
- **packet ceiling** — kernel-ipc: 256 bytes request/reply, 64 pushed. An
|
||||||
|
shm-ring's ceiling is its slot size. Kernel-ipc's 256 is the *floor* every
|
||||||
|
protocol may assume everywhere.
|
||||||
|
- **synchrony** — kernel-ipc's call is a rendezvous: natural backpressure, no
|
||||||
|
queue to size. An asynchronous transport buffers, so a channel over one
|
||||||
|
needs explicit flow control. Backpressure is a *transport property*, not a
|
||||||
|
channel guarantee — protocols that rely on it say so.
|
||||||
|
- **droppability** — pushed event packets may drop when a ring fills;
|
||||||
|
request/reply may not.
|
||||||
|
- **capability carriage** — **only kernel-ipc can move a capability.**
|
||||||
|
Handles are kernel objects; a user-space ring cannot transfer one. So
|
||||||
|
kernel-ipc is always the *establishment and control* transport — channels
|
||||||
|
are born on it, capabilities ride it — even when a channel's data is
|
||||||
|
negotiated onto something fatter.
|
||||||
|
|
||||||
|
That negotiation is the upgrade path: a channel starts on kernel-ipc; the
|
||||||
|
protocol's handshake may then delegate a shared-memory region (as a
|
||||||
|
capability, over kernel-ipc) and move its bulk traffic there. The display
|
||||||
|
path already does exactly this by hand; formalizing it in the channel layer
|
||||||
|
makes it every protocol's option.
|
||||||
|
|
||||||
|
## The channel (L1)
|
||||||
|
|
||||||
|
A channel has two ends, and **the ends are peers**: each may send packets,
|
||||||
|
each may receive, each may signal. Request/reply is a *pattern* over the
|
||||||
|
channel — a send with a correlated receive, which the kernel-ipc transport
|
||||||
|
happens to accelerate as a single rendezvous — not the definition of it. The
|
||||||
|
event stream (subscribe, then pushes) and the change signal (poke, then
|
||||||
|
re-read) are the other two patterns; all three are catalogued in
|
||||||
|
[protocol-namespace.md](protocol-namespace.md)'s wiring section.
|
||||||
|
|
||||||
|
The channel layer's obligations: deliver packets whole, attach the verified
|
||||||
|
source to every receive, expose the transport's properties, and hide the
|
||||||
|
transport's mechanics. The client library's `Channel` type is this layer made
|
||||||
|
concrete — a program holds channels that speak protocols and never touches a
|
||||||
|
raw handle.
|
||||||
|
|
||||||
|
## The protocol (L2) and the namespace (L3)
|
||||||
|
|
||||||
|
A protocol defines its packets through the envelope — every packet begins
|
||||||
|
`{operation, target}`, reserved verbs (`describe`, `enumerate`, `subscribe`,
|
||||||
|
`unsubscribe`) mean the same thing in every protocol, and `Define` checks
|
||||||
|
every packet against the transport floor at compile time. The full treatment,
|
||||||
|
including how names are granted, resolved, and restricted per process, is
|
||||||
|
[protocol-namespace.md](protocol-namespace.md).
|
||||||
|
|
||||||
|
Establishment points are named by contract — `/protocol/display`, never
|
||||||
|
`/protocol/ipc-1` — because the name must outlive the mechanism: a
|
||||||
|
transport named in the namespace could never be swapped, which would defeat
|
||||||
|
this document's premise.
|
||||||
@@ -0,0 +1,187 @@
|
|||||||
|
# Device authority: the implementation of delegation
|
||||||
|
|
||||||
|
*Implementation design, 2026-08-08. The **what** is settled in
|
||||||
|
[device-manager.md](../device-driver-development/device-manager.md) — "structure in the
|
||||||
|
manager, authority in the kernel", and delegation as the step after `hello`. This
|
||||||
|
document is the **how**, and the decisions that paragraph leaves open.*
|
||||||
|
|
||||||
|
Read first: [drivers.md](../device-driver-development/drivers.md) (the claim is the
|
||||||
|
capability), [driver-model.md](../device-driver-development/driver-model.md) (the three
|
||||||
|
invariants), [device-manager.md](../device-driver-development/device-manager.md) (the
|
||||||
|
tree, the matcher, the supervisor).
|
||||||
|
|
||||||
|
## The one thing not yet true
|
||||||
|
|
||||||
|
`device-manager.md` says assignment "stays argv for now", and names the next step:
|
||||||
|
|
||||||
|
> The step after `hello` exists is delegation: the manager claims (or is granted) the
|
||||||
|
> devices and passes the claim to the driver over IPC (the M13 capability-transfer
|
||||||
|
> mechanism), replacing first-come-first-served `device_claim` with policy.
|
||||||
|
|
||||||
|
Until that lands, the manager's matching is advisory. `device_claim` checks only that
|
||||||
|
the device exists and is unheld ([devices-broker.zig](../../system/kernel/devices-broker.zig)):
|
||||||
|
|
||||||
|
```zig
|
||||||
|
pub fn claim(id: u64, owner: u32) ClaimError!void {
|
||||||
|
if (id >= count) return error.NoSuchDevice;
|
||||||
|
if (claimed[@intCast(id)] != null) return error.AlreadyClaimed;
|
||||||
|
claimed[@intCast(id)] = owner;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
A driver is spawned with its device id in `argv[1]` and claims it; any process could
|
||||||
|
pass any integer instead. Since a claim is a licence to map physical memory, that is the
|
||||||
|
gap this document closes.
|
||||||
|
|
||||||
|
## Decision 1: the manager claims, then transfers
|
||||||
|
|
||||||
|
`device-manager.md` leaves "claims (or is granted)" open. **Claims.**
|
||||||
|
|
||||||
|
The manager runs before any driver exists — `init` starts it from `init.csv`, and it is
|
||||||
|
what spawns drivers — so it takes the seeded devices unopposed and there is nothing
|
||||||
|
unheld left for anyone to race for. One new call moves ownership on:
|
||||||
|
|
||||||
|
```
|
||||||
|
device_transfer(device_id, task_id) -> 0/-errno
|
||||||
|
```
|
||||||
|
|
||||||
|
The kernel checks only that the caller currently holds the device. No names, no
|
||||||
|
attestation, no notion of "the device manager" — the rule is *you may give away what you
|
||||||
|
hold*, which is the capability discipline already in force.
|
||||||
|
|
||||||
|
The alternative was the kernel granting roots to a task it recognises by binary path
|
||||||
|
plus a PID-1 supervisor. It is more robust — it does not depend on the manager being
|
||||||
|
first — but it puts a binary name inside the kernel, and the goal is that the kernel
|
||||||
|
keeps only what cannot safely live in user space. A name is not that.
|
||||||
|
|
||||||
|
**The residual, stated plainly:** authority here rests on the manager claiming first.
|
||||||
|
That holds because `init.csv` decides what starts and in what order, so it is an
|
||||||
|
operator-visible ordering rather than an attacker-controlled one — but it is an
|
||||||
|
assumption, not an enforced invariant. The enforced version arrives with the spawn
|
||||||
|
capability [drivers.md](../device-driver-development/drivers.md) already names as
|
||||||
|
missing ("`system_spawn` is currently ungated … because there is no spawn capability
|
||||||
|
yet"). This design is compatible with it and does not block on it.
|
||||||
|
|
||||||
|
## Decision 2: the kernel stops holding inventory
|
||||||
|
|
||||||
|
The kernel reads exactly three things out of a descriptor: **physical ranges** (to check
|
||||||
|
a mapping falls inside one), **interrupt numbers**, and **one PCI BDF** (to key an IOMMU
|
||||||
|
domain). Vendor, device and subsystem ids, class triples, `_HID` strings, bus addresses
|
||||||
|
and names are stored only so `device_enumerate` can hand them back — which
|
||||||
|
`device-manager.md` already resolves: that call "fades to a manager-internal (then
|
||||||
|
deleted) seam", because the manager owns the tree as data.
|
||||||
|
|
||||||
|
So the kernel's table becomes: **parent, resources, holder, BDF.** That is what cannot
|
||||||
|
safely run in user space; the rest moves.
|
||||||
|
|
||||||
|
**Devices with no resources leave the kernel entirely.** A USB device is addressed
|
||||||
|
through its controller and carries `resource_count = 0`
|
||||||
|
([driver-model.md](../device-driver-development/driver-model.md): "that case is allowed
|
||||||
|
and is the common one"). It conveys no mapping authority, so there is nothing for the
|
||||||
|
kernel to enforce and no reason for it to know. It is inventory, and inventory is the
|
||||||
|
manager's — reported by `child_added`, which already carries everything needed.
|
||||||
|
|
||||||
|
That is also the case that made `maximum_children_per_parent` necessary: a zero-resource
|
||||||
|
child sidesteps containment, so a driver could loop `device_register` and fill the
|
||||||
|
shared table. Once such children are not kernel objects, every remaining entry is a real
|
||||||
|
contained subdivision of something the caller holds.
|
||||||
|
|
||||||
|
## Decision 3: no shared ceiling; a per-holder quota instead
|
||||||
|
|
||||||
|
`maximum_devices = 64` and `maximum_children_per_parent = 16` are numbers we invented,
|
||||||
|
and both are shared — one driver's enumeration starves every other driver, which is how
|
||||||
|
an AMD Ryzen booted with no USB and no storage.
|
||||||
|
|
||||||
|
- **The table becomes dynamic.** It is built after `heap.init` (`kernel.zig`: `pmm.init`
|
||||||
|
at 137, `heap.init` at 179, `devices_broker.init` at 202), so nothing prevents it. No
|
||||||
|
specification bounds how many devices a machine has, so nothing should bound ours.
|
||||||
|
- **`maximum_children_per_parent` is deleted**, because the authorisation it stood in
|
||||||
|
for now exists.
|
||||||
|
- **A per-holder quota replaces them.** Dynamic storage without a bound moves the
|
||||||
|
ceiling to the kernel heap, which is shared and fatal rather than partial — strictly
|
||||||
|
worse. The bound that is *not* worse is one charged to the task that caused it: a
|
||||||
|
driver that loops `device_register` exhausts its own allowance, is refused with an
|
||||||
|
attributable errno, and is restarted by its supervisor while every other driver
|
||||||
|
carries on. That is the microkernel property rather than a workaround for it, and it
|
||||||
|
is declared through [bounds.md](bounds.md) like any other.
|
||||||
|
|
||||||
|
## The shape of the change
|
||||||
|
|
||||||
|
| | Before | After |
|
||||||
|
|---|---|---|
|
||||||
|
| Manager gets its devices | claims them, unauthorised | claims them (first, unopposed) |
|
||||||
|
| Driver gets its device | `argv[1]` + `device_claim` | receives it in the `hello` reply |
|
||||||
|
| Kernel checks | is it free? | do you hold it? |
|
||||||
|
| Kernel stores | the full descriptor | parent, resources, holder, BDF |
|
||||||
|
| Zero-resource devices | kernel table entries | manager records only |
|
||||||
|
| Table size | `maximum_devices = 64` | dynamic, per-holder quota |
|
||||||
|
| Children per parent | `maximum_children_per_parent = 16` | deleted |
|
||||||
|
|
||||||
|
Bring-up order changes for the five claiming drivers: `hello` must precede the claim,
|
||||||
|
because the reply is where the device arrives. `pci-bus` today does the reverse — its
|
||||||
|
own comment reads "Claim the bridge, map the ECAM, hello the manager, then scan."
|
||||||
|
|
||||||
|
## What does not change
|
||||||
|
|
||||||
|
- The three invariants of [driver-model.md](../device-driver-development/driver-model.md):
|
||||||
|
a claim is exclusive, a descriptor is a licence to map physical memory, therefore
|
||||||
|
containment. This design strengthens the first and touches neither of the others.
|
||||||
|
- The display service's GOP path. The framebuffer is not a device — it is where pixels
|
||||||
|
go, handed over by the loader, and the compositor uses it as the boot floor until a
|
||||||
|
real display driver announces itself
|
||||||
|
([display-v2.md](../device-driver-development/display-v2.md)). The kernel wraps it in
|
||||||
|
a display-class descriptor so `mmio_map` can hand it over write-combining; that is
|
||||||
|
plumbing for a mapping, not a claim about what it is.
|
||||||
|
- Supervision, restart, pruning and re-report
|
||||||
|
([device-manager.md](../device-driver-development/device-manager.md),
|
||||||
|
[process-lifecycle.md](process-lifecycle.md)). Delegation slots into the existing
|
||||||
|
`hello` exchange and changes none of it.
|
||||||
|
- `device_register` idempotency, which is what lets a restarted bus rebuild the same
|
||||||
|
ids.
|
||||||
|
|
||||||
|
## How it is verified
|
||||||
|
|
||||||
|
The invariant is: **a process holds what it was handed and cannot name its way into
|
||||||
|
holding more.** The suite has no adversarial device case today — the audit's lesson was
|
||||||
|
that "the suite contains no attacker" — so this adds one: a process that was handed
|
||||||
|
nothing calls `device_claim` and `device_transfer` on a device another driver holds, and
|
||||||
|
on one nobody holds, and is refused each time with its own errno.
|
||||||
|
|
||||||
|
The Ryzen is the acceptance test for the ceiling half: it is the machine that found the
|
||||||
|
constants, and the one that proves them gone.
|
||||||
|
|
||||||
|
## As built (2026-08-09)
|
||||||
|
|
||||||
|
Three details settled differently, or beyond, what the sections above say:
|
||||||
|
|
||||||
|
- **The device arrives with the spawn, not in the `hello` reply.** `system_spawn` grew a
|
||||||
|
sixth argument: the manager names the device it is giving, the kernel verifies the
|
||||||
|
caller holds it before the child exists, and the child holds it before its first
|
||||||
|
instruction. A give that fails after the spawn (the device stopped being the giver's,
|
||||||
|
or its confinement was refused) kills the child — a driver running without the
|
||||||
|
hardware it was spawned for is worse than no driver. `hello` stays what it was: the
|
||||||
|
liveness handshake.
|
||||||
|
- **A given device is a loan.** When the holder dies, the device returns to the giver if
|
||||||
|
the giver is still alive — so a respawned driver is handed the same device by its
|
||||||
|
manager instead of racing anyone for a released claim. Only if the lender is also dead
|
||||||
|
does the device become unheld.
|
||||||
|
- **Confinement moves with the device, and is rebuilt when the loan comes back.** A
|
||||||
|
transfer re-points the existing IOMMU record; but a death tears the domain down
|
||||||
|
*before* the loan returns, so the next delegation of that device finds no record and
|
||||||
|
confines afresh — under the same fail-closed rule as a first claim (`ECONFINE`, the
|
||||||
|
give does not stand). Without that, one driver crash left its device silently
|
||||||
|
unconfined forever. Both give paths (`device_transfer` and spawn's give) share one
|
||||||
|
body in [process.zig](../../system/kernel/process.zig) (`giveDeviceLocked`), and the
|
||||||
|
`iommu` kernel test drives the death-and-respawn sequence against it directly.
|
||||||
|
|
||||||
|
A fourth followed on 2026-08-09, when a real three-controller machine broke the last
|
||||||
|
name-shaped assumption ([communication.md](communication.md) "Establishment: two
|
||||||
|
planes, one namespace"): **driver-layer channels ride the same hello.** A driver's
|
||||||
|
serving endpoint goes up as the hello's capability; consumers get their provider's
|
||||||
|
channel down in the reply, routed by the manager's lineage — the reporter for a
|
||||||
|
class driver, the bound driver for a `.consumer`. `usb-transfer` and `block`
|
||||||
|
stopped being registry names, and a reporter's death now reaps its class-driver
|
||||||
|
subtree so the re-report can rebuild it against the successor — the manager half of
|
||||||
|
the loan story above. One correction to the earlier bullet: `hello` is no longer
|
||||||
|
*only* the liveness handshake; it is also where establishment happens. The device
|
||||||
|
itself still arrives with the spawn.
|
||||||
@@ -36,7 +36,7 @@ Two things drive the need, and they set the timing:
|
|||||||
**aarch64 it's required to boot at all**. The [aarch64 port](arm.md) is what
|
**aarch64 it's required to boot at all**. The [aarch64 port](arm.md) is what
|
||||||
forces the issue.
|
forces the issue.
|
||||||
|
|
||||||
2. **Isolated user-space drivers need it.** In the [microkernel vision](vision.md),
|
2. **Isolated user-space drivers need it.** In the [microkernel vision](../vision.md),
|
||||||
drivers live in user space — but something has to enumerate the hardware and hand
|
drivers live in user space — but something has to enumerate the hardware and hand
|
||||||
each driver its MMIO regions and IRQs. That enumeration *is* device discovery. So
|
each driver its MMIO regions and IRQs. That enumeration *is* device discovery. So
|
||||||
discovery is a prerequisite for real drivers, **not** for user mode itself.
|
discovery is a prerequisite for real drivers, **not** for user mode itself.
|
||||||
@@ -132,7 +132,7 @@ when*:
|
|||||||
- **User-space enumeration: a device-manager server.** Everything else — PCI devices,
|
- **User-space enumeration: a device-manager server.** Everything else — PCI devices,
|
||||||
peripherals — is parsed (or queried from the kernel's parse) by a privileged
|
peripherals — is parsed (or queried from the kernel's parse) by a privileged
|
||||||
user-space server that hands each driver process its MMIO regions and IRQ rights
|
user-space server that hands each driver process its MMIO regions and IRQ rights
|
||||||
over [IPC](ipc.md). Combined with **interrupts-as-messages** (an IRQ delivered to a
|
over [IPC](../device-driver-development/ipc.md). Combined with **interrupts-as-messages** (an IRQ delivered to a
|
||||||
driver as a message on a channel — a natural extension of the wait queues and
|
driver as a message on a channel — a natural extension of the wait queues and
|
||||||
channels already built), that's what makes drivers genuinely isolated.
|
channels already built), that's what makes drivers genuinely isolated.
|
||||||
|
|
||||||
@@ -144,7 +144,7 @@ slice is unavoidably in-kernel.
|
|||||||
On ARMv8 the generic timer exposes its frequency directly via the `CNTFRQ` register —
|
On ARMv8 the generic timer exposes its frequency directly via the `CNTFRQ` register —
|
||||||
no calibration needed. That's cleaner than the x86 side, where we measure the LAPIC
|
no calibration needed. That's cleaner than the x86 side, where we measure the LAPIC
|
||||||
and TSC against the PIT because nothing tells us their frequency (see
|
and TSC against the PIT because nothing tells us their frequency (see
|
||||||
[device-interrupts.md](device-interrupts.md)). Discovery on ARM hands you more for
|
[device-interrupts.md](../device-driver-development/device-interrupts.md)). Discovery on ARM hands you more for
|
||||||
free; discovery on x86 is partly about *finding* what ARM just tells you.
|
free; discovery on x86 is partly about *finding* what ARM just tells you.
|
||||||
|
|
||||||
## Suggested ordering
|
## Suggested ordering
|
||||||
@@ -166,18 +166,18 @@ free; discovery on x86 is partly about *finding* what ARM just tells you.
|
|||||||
- [arm.md](arm.md) — the aarch64 target that forces genuine discovery (DTB, GIC).
|
- [arm.md](arm.md) — the aarch64 target that forces genuine discovery (DTB, GIC).
|
||||||
- [memory-map.md](memory-map.md) — the same loader-captures / kernel-consumes seam,
|
- [memory-map.md](memory-map.md) — the same loader-captures / kernel-consumes seam,
|
||||||
and the note about grabbing the RSDP before `ExitBootServices`.
|
and the note about grabbing the RSDP before `ExitBootServices`.
|
||||||
- [device-interrupts.md](device-interrupts.md) — the LAPIC/timer bring-up that
|
- [device-interrupts.md](../device-driver-development/device-interrupts.md) — the LAPIC/timer bring-up that
|
||||||
discovery will eventually feed (IOAPIC, real IRQ routing).
|
discovery will eventually feed (IOAPIC, real IRQ routing).
|
||||||
- [ipc.md](ipc.md) — the channels that interrupts-as-messages and the device manager
|
- [ipc.md](../device-driver-development/ipc.md) — the channels that interrupts-as-messages and the device manager
|
||||||
will ride on.
|
will ride on.
|
||||||
- [vision.md](vision.md) — why drivers belong in isolated user space at all.
|
- [vision.md](../vision.md) — why drivers belong in isolated user space at all.
|
||||||
|
|
||||||
## Update (M19.3, 2026-07-13): PCI enumeration left the kernel
|
## Update (M19.3, 2026-07-13): PCI enumeration left the kernel
|
||||||
|
|
||||||
The kernel now seeds only the `pci_host_bridge` node (ECAM window, MMIO
|
The kernel now seeds only the `pci_host_bridge` node (ECAM window, MMIO
|
||||||
apertures derived from the memory map's holes, bus range, and the 16-bit I/O
|
apertures derived from the memory map's holes, bus range, and the 16-bit I/O
|
||||||
window). The per-function walk moved to the ring-3 `pci-bus` driver
|
window). The per-function walk moved to the ring-3 `pci-bus` driver
|
||||||
([device-manager.md](device-manager.md)): it claims the bridge, repeats the
|
([device-manager.md](../device-driver-development/device-manager.md)): it claims the bridge, repeats the
|
||||||
ECAM scan through its mmio grant, and `device_register`s what it finds, which
|
ECAM scan through its mmio grant, and `device_register`s what it finds, which
|
||||||
the device manager mirrors and matches. The ACPI namespace walk follows in M20;
|
the device manager mirrors and matches. The ACPI namespace walk follows in M20;
|
||||||
the static tables (MADT, HPET, MCFG, FADT + `\\_S5`) stay kernel-side.
|
the static tables (MADT, HPET, MCFG, FADT + `\\_S5`) stay kernel-side.
|
||||||
@@ -190,7 +190,7 @@ for the host bridge, FADT); at this point it also still built the AML namespace
|
|||||||
but only to read the `\\_S5` sleep type for poweroff. (That remnant is gone too:
|
but only to read the `\\_S5` sleep type for poweroff. (That remnant is gone too:
|
||||||
the kernel now runs no AML at all — soft-off belongs to the acpi service, and the
|
the kernel now runs no AML at all — soft-off belongs to the acpi service, and the
|
||||||
kernel keeps only the AML-free reboot path.) Device discovery is the ring-3 **acpi
|
kernel keeps only the AML-free reboot path.) Device discovery is the ring-3 **acpi
|
||||||
service** ([device-manager.md](device-manager.md)): it claims the `acpi-tables`
|
service** ([device-manager.md](../device-driver-development/device-manager.md)): it claims the `acpi-tables`
|
||||||
node the kernel publishes (the AML blobs, a broad io_port grant, the SCI),
|
node the kernel publishes (the AML blobs, a broad io_port grant, the SCI),
|
||||||
re-parses the same blobs with the shared AML module, evaluates `_STA`/`_CRS`,
|
re-parses the same blobs with the shared AML module, evaluates `_STA`/`_CRS`,
|
||||||
and registers + reports each `_HID` device — the device manager matches drivers
|
and registers + reports each `_HID` device — the device manager matches drivers
|
||||||
@@ -206,7 +206,7 @@ ring 0.)
|
|||||||
Moving PCI and ACPI enumeration out of ring 0 was not just a relocation — it
|
Moving PCI and ACPI enumeration out of ring 0 was not just a relocation — it
|
||||||
made discovery **firmware-neutral by construction**, which is the whole reason
|
made discovery **firmware-neutral by construction**, which is the whole reason
|
||||||
to do it before the second architecture rather than after. Everything at and
|
to do it before the second architecture rather than after. Everything at and
|
||||||
above the [device-manager](device-manager.md) protocol — descriptors,
|
above the [device-manager](../device-driver-development/device-manager.md) protocol — descriptors,
|
||||||
containment, reports, matching, supervision — is generic and may never become
|
containment, reports, matching, supervision — is generic and may never become
|
||||||
x86-specific. Discovery is the single firmware-specific piece, and it is
|
x86-specific. Discovery is the single firmware-specific piece, and it is
|
||||||
isolated as **one swappable process per firmware**:
|
isolated as **one swappable process per firmware**:
|
||||||
@@ -231,8 +231,8 @@ Two consequences of neutrality bind on later work:
|
|||||||
|
|
||||||
- **Cross-firmware surfaces are named by domain, not firmware.** System power is
|
- **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
|
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
|
service binds it, on ARM a PSCI/mailbox service binds the same
|
||||||
`ServiceId.power`, and subscribers never learn the difference.
|
`/protocol/power`, and subscribers never learn the difference.
|
||||||
- **Identity must widen before the fdt service exists.** `DeviceDescriptor`'s
|
- **Identity must widen before the fdt service exists.** `DeviceDescriptor`'s
|
||||||
8-byte `hid` holds an EISA id but cannot hold an FDT `compatible` string
|
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
|
(`"brcm,bcm2835-aux-uart"`); the identity field grows before the ARM path can
|
||||||
@@ -241,7 +241,7 @@ Two consequences of neutrality bind on later work:
|
|||||||
Two supporting decisions keep the kernel's remaining slice honest:
|
Two supporting decisions keep the kernel's remaining slice honest:
|
||||||
|
|
||||||
- **The AML interpreter is a single build module**
|
- **The AML interpreter is a single build module**
|
||||||
(`system/devices/aml/aml.zig`) — one source, no fork. During the ring-3 move
|
(`library/device/acpi/aml/aml.zig`) — one source, no fork. During the ring-3 move
|
||||||
it was compiled into both the kernel (which linked it just for the `\_S5`
|
it was compiled into both the kernel (which linked it just for the `\_S5`
|
||||||
poweroff evaluation) and the acpi service, with the `acpi-parse` test
|
poweroff evaluation) and the acpi service, with the `acpi-parse` test
|
||||||
asserting the two produce the same device count. Since soft-off followed
|
asserting the two produce the same device count. Since soft-off followed
|
||||||
@@ -24,8 +24,9 @@ EFI/BOOT/BOOTX64.efi <- the "removable media" default for x86-64
|
|||||||
```
|
```
|
||||||
|
|
||||||
The boot volume is **FHS-shaped** (see the repository-layout note in
|
The boot volume is **FHS-shaped** (see the repository-layout note in
|
||||||
[README.md](README.md)): `build.zig` installs `boot/efi.zig` (built for the `uefi`
|
[README.md](../README.md)): the root `build.zig` compiles `boot/efi.zig` (built
|
||||||
target) at `EFI/BOOT/BOOTX64.efi` — the one path UEFI firmware fixes — and lays
|
for the `uefi` target) and `build/images.zig` places it at
|
||||||
|
`EFI/BOOT/BOOTX64.efi` — the one path UEFI firmware fixes — and lays
|
||||||
the rest out by FHS path: the kernel at `system/kernel`, init at
|
the rest out by FHS path: the kernel at `system/kernel`, init at
|
||||||
`system/services/init`, the pre-packed boot capsule at `boot/system.img`
|
`system/services/init`, the pre-packed boot capsule at `boot/system.img`
|
||||||
([system-image.md](system-image.md)).
|
([system-image.md](system-image.md)).
|
||||||
@@ -67,8 +68,8 @@ captures the **ACPI RSDP** from the UEFI configuration table (while boot
|
|||||||
services are still up), loads the system binaries into an in-RAM
|
services are still up), loads the system binaries into an in-RAM
|
||||||
**initial ramdisk** (`loadSystemTree` — normally a single read of the pre-packed
|
**initial ramdisk** (`loadSystemTree` — normally a single read of the pre-packed
|
||||||
`boot\system.img` capsule, which already *is* the ramdisk wire format; it falls
|
`boot\system.img` capsule, which already *is* the ramdisk wire format; it falls
|
||||||
back to opening each manifest-listed path, and walks the `/system` tree only as
|
back to opening each manifest-listed path, and walks the `/system` and `/test`
|
||||||
a last resort for hand-assembled sticks — the capsule's format, builder, and
|
trees only as a last resort for hand-assembled sticks — the capsule's format, builder, and
|
||||||
fallback chain are documented in [system-image.md](system-image.md). Best-effort either way — a kernel-only
|
fallback chain are documented in [system-image.md](system-image.md). Best-effort either way — a kernel-only
|
||||||
volume still boots), and builds the **bootstrap page tables** the kernel starts
|
volume still boots), and builds the **bootstrap page tables** the kernel starts
|
||||||
life on (`buildBootstrapTables`), all before the jump:
|
life on (`buildBootstrapTables`), all before the jump:
|
||||||
@@ -173,7 +174,7 @@ The loader and kernel are two *separate* binaries built for two different target
|
|||||||
so everything they exchange must have an identically-defined memory layout. That's
|
so everything they exchange must have an identically-defined memory layout. That's
|
||||||
what `system/boot-handoff.zig` provides — imported by both as the `boot-handoff` module.
|
what `system/boot-handoff.zig` provides — imported by both as the `boot-handoff` module.
|
||||||
It is *only* the handoff: the kernel↔user ABI (`system/abi.zig`) and the device types
|
It is *only* the handoff: the kernel↔user ABI (`system/abi.zig`) and the device types
|
||||||
(`system/devices/device-abi.zig`) are separate contracts the bootloader never sees.
|
(`library/device/model/device-abi.zig`) are separate contracts the bootloader never sees.
|
||||||
|
|
||||||
- `BootInformation` — the top-level struct passed to the kernel: the
|
- `BootInformation` — the top-level struct passed to the kernel: the
|
||||||
framebuffer, the memory map, the kernel's own `PT_LOAD` segments
|
framebuffer, the memory map, the kernel's own `PT_LOAD` segments
|
||||||
@@ -196,7 +197,7 @@ power on
|
|||||||
-> queryFramebuffer (via GOP: EDID native res, setMode, describe fb)
|
-> queryFramebuffer (via GOP: EDID native res, setMode, describe fb)
|
||||||
-> loadKernel (read system/kernel ELF, load PT_LOAD segments low, .text at 0x100000)
|
-> loadKernel (read system/kernel ELF, load PT_LOAD segments low, .text at 0x100000)
|
||||||
-> loadSystemTree (read the boot\system.img capsule as the in-RAM initial ramdisk;
|
-> loadSystemTree (read the boot\system.img capsule as the in-RAM initial ramdisk;
|
||||||
fallbacks: manifest-listed paths, then a /system tree walk)
|
fallbacks: manifest-listed paths, then a /system + /test tree walk)
|
||||||
-> buildBootstrapTables (identity + physmap + higher-half kernel mappings)
|
-> buildBootstrapTables (identity + physmap + higher-half kernel mappings)
|
||||||
-> exitBootServices (retry until the memory-map key holds)
|
-> exitBootServices (retry until the memory-map key holds)
|
||||||
-> handoff: load bootstrap CR3, jump to e_entry, boot_information pointer in RDI
|
-> handoff: load bootstrap CR3, jump to e_entry, boot_information pointer in RDI
|
||||||
@@ -118,17 +118,22 @@ regions `init` frees. Keeping that boot-protocol knowledge on the loader side is
|
|||||||
deliberate — the kernel has no notion of "reclaimable" or of UEFI at all.
|
deliberate — the kernel has no notion of "reclaimable" or of UEFI at all.
|
||||||
|
|
||||||
The one live piece in that memory is the boot stack the kernel starts on; the loader
|
The one live piece in that memory is the boot stack the kernel starts on; the loader
|
||||||
leaves the single region containing it `reserved`, so `init` won't hand it out. A
|
leaves the single region containing it `reserved`, so `init` won't hand it out. The
|
||||||
later step will move task 0 onto a kernel-owned stack, freeing that last ~1 MiB
|
kernel is only on it for an instant, though — `_start`'s first instruction switches
|
||||||
region too (and giving user mode the clean stack it wants).
|
to a kernel-owned 64 KiB stack in `.bss` (that context becomes task 0). The region
|
||||||
|
stays `reserved` because the loader's own `convertMemoryMap` was executing on that
|
||||||
|
stack when it reclassified the RAM, and, like the map buffers below, nothing frees it
|
||||||
|
yet.
|
||||||
|
|
||||||
## What's next (partly done since)
|
## What's next (partly done since)
|
||||||
|
|
||||||
- **Contiguous allocation** — done: `allocContiguous` scans for a run of clear
|
- **Contiguous allocation** — done: `allocContiguous` scans for a run of clear
|
||||||
bits, with an optional physical ceiling for DMA (`dma_alloc` is its user), and
|
bits, with an optional physical ceiling for DMA (`dma_alloc` is its user), and
|
||||||
`allocBelow` serves the SMP trampoline.
|
`allocBelow` serves the SMP trampoline.
|
||||||
- **A kernel stack for task 0** — still open: the boot processor's idle task runs
|
- **A kernel stack for task 0** — done: `_start`'s first instruction switches `rsp`
|
||||||
on the boot stack to this day, so that region can't be freed.
|
to a kernel-owned 64 KiB stack in `.bss` (`bootstrap_stack`), and `scheduler.init`
|
||||||
|
registers that running context as task 0 — the kernel is on the loader's boot
|
||||||
|
stack for that one instruction and never again.
|
||||||
- **Freeing the `reserved` `loader_data`** (the boot-time map buffers) — still
|
- **Freeing the `reserved` `loader_data`** (the boot-time map buffers) — still
|
||||||
open: the bitmap deliberately tracks those frames so they *can* be freed, but
|
open: the bitmap deliberately tracks those frames so they *can* be freed, but
|
||||||
nothing frees them yet.
|
nothing frees them yet.
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -51,7 +51,7 @@ rest — works directly on the kernel heap, no bespoke containers required.
|
|||||||
|
|
||||||
## Verifying it
|
## Verifying it
|
||||||
|
|
||||||
The `heap` test (see [testing.md](testing.md)) exercises the allocator end to end:
|
The `heap` test (see [testing.md](../testing.md)) exercises the allocator end to end:
|
||||||
|
|
||||||
```
|
```
|
||||||
[PASS] alloc 4096 bytes
|
[PASS] alloc 4096 bytes
|
||||||
@@ -133,10 +133,10 @@ TSS/IST is wired up: the handler survived a completely broken stack.
|
|||||||
|
|
||||||
Both items originally deferred here have landed:
|
Both items originally deferred here have landed:
|
||||||
|
|
||||||
- **The IO-APIC**: [ioapic.zig](../system/kernel/architecture/x86_64/ioapic.zig)
|
- **The IO-APIC**: [ioapic.zig](../../system/kernel/architecture/x86_64/ioapic.zig)
|
||||||
routes external device lines onto vectors — discovered via ACPI's MADT, every
|
routes external device lines onto vectors — discovered via ACPI's MADT, every
|
||||||
input masked at init, lines unmasked one at a time as user-space drivers bind
|
input masked at init, lines unmasked one at a time as user-space drivers bind
|
||||||
them (see [device-interrupts.md](device-interrupts.md)). The keyboard followed
|
them (see [device-interrupts.md](../device-driver-development/device-interrupts.md)). The keyboard followed
|
||||||
exactly as predicted: the PS/2 bus driver (`system/drivers/ps2-bus/`) claims
|
exactly as predicted: the PS/2 bus driver (`system/drivers/ps2-bus/`) claims
|
||||||
the 8042 controller and binds its IRQ 1 (and the aux mouse's IRQ 12) through
|
the 8042 controller and binds its IRQ 1 (and the aux mouse's IRQ 12) through
|
||||||
this routing. USB HID keyboards arrive over xHCI instead, which interrupts via
|
this routing. USB HID keyboards arrive over xHCI instead, which interrupts via
|
||||||
@@ -14,16 +14,16 @@ are mirrored to it explicitly (`system/kernel/kernel.zig`).
|
|||||||
## The pipeline
|
## The pipeline
|
||||||
|
|
||||||
```
|
```
|
||||||
process std.log ──▶ debug_write(level) ──▶ tagged kernel ring ──▶ logger service ──▶ /var/log/<boot-stamp>/<binary-path>.log
|
process std.log ──▶ debug_write(level) ──▶ tagged kernel ring ──▶ logger service ──▶ /system/logs/<boot-stamp>/<binary-path>.log
|
||||||
kernel log.print ─┘ │
|
kernel log.print ─┘ │
|
||||||
└▶ serial / 0xE9 sinks (QEMU, -Dserial)
|
└▶ serial / 0xE9 sinks (QEMU, -Dserial)
|
||||||
```
|
```
|
||||||
|
|
||||||
1. **Emit.** A program calls `std.log.info("mounted {s}", .{path})` — the
|
1. **Emit.** A program calls `std.log.info("mounted {s}", .{path})` — the
|
||||||
runtime's `logFn` (installed for every binary by the root shim,
|
runtime's `logFn` (installed for every binary by the root shim,
|
||||||
`library/runtime/log.zig`) formats one line and issues one `debug_write`
|
`library/kernel/logging.zig`) formats one line and issues one `debug_write`
|
||||||
carrying the level. The payload does NOT contain the process's name.
|
carrying the level. The payload does NOT contain the process's name.
|
||||||
`runtime.system.write` remains as the raw/bring-up path (panics, test
|
`logging.write` remains as the raw/bring-up path (panics, test
|
||||||
fixtures); raw bytes ride the same ring, attributed all the same.
|
fixtures); raw bytes ride the same ring, attributed all the same.
|
||||||
|
|
||||||
2. **Stamp.** The kernel wraps every payload LINE in a record stamped with the
|
2. **Stamp.** The kernel wraps every payload LINE in a record stamped with the
|
||||||
@@ -49,12 +49,12 @@ kernel log.print ─┘ │
|
|||||||
|
|
||||||
5. **Persist.** The **logger service** (`system/services/logger`) drains the
|
5. **Persist.** The **logger service** (`system/services/logger`) drains the
|
||||||
ring every 250 ms and demultiplexes records into one file per source under
|
ring every 250 ms and demultiplexes records into one file per source under
|
||||||
`/var/log/<boot-stamp>/`, e.g.
|
`/system/logs/<boot-stamp>/`, e.g.
|
||||||
|
|
||||||
```
|
```
|
||||||
/var/log/2026-07-21T150434Z/kernel.log
|
/system/logs/2026-07-21T150434Z/kernel.log
|
||||||
/var/log/2026-07-21T150434Z/system/services/fat.log
|
/system/logs/2026-07-21T150434Z/system/services/fat.log
|
||||||
/var/log/2026-07-21T150434Z/system/drivers/usb-storage.log
|
/system/logs/2026-07-21T150434Z/system/drivers/usb-storage.log
|
||||||
```
|
```
|
||||||
|
|
||||||
The boot stamp is the RTC anchor from `klog_status` (FAT-safe: no colons; a
|
The boot stamp is the RTC anchor from `klog_status` (FAT-safe: no colons; a
|
||||||
@@ -95,6 +95,6 @@ written last so a reader only trusts a complete record).
|
|||||||
- A write-spamming process can evict other processes' unread records from the
|
- A write-spamming process can evict other processes' unread records from the
|
||||||
ring (a per-process quota is future work); the loss is at least visible via
|
ring (a per-process quota is future work); the loss is at least visible via
|
||||||
sequence gaps in every affected file.
|
sequence gaps in every affected file.
|
||||||
- `/var/log` files have no privacy until the VFS grows permissions.
|
- `/system/logs` files have no privacy until the VFS grows permissions.
|
||||||
- Records emitted after the logger's final shutdown drain reach serial and the
|
- Records emitted after the logger's final shutdown drain reach serial and the
|
||||||
ring but not the files.
|
ring but not the files.
|
||||||
File renamed without changes.
@@ -112,7 +112,7 @@ kernel heap will build on to map pages on demand.
|
|||||||
|
|
||||||
## Verifying it
|
## Verifying it
|
||||||
|
|
||||||
Four tests (see [testing.md](testing.md)) pin down the guarantees:
|
Four tests (see [testing.md](../testing.md)) pin down the guarantees:
|
||||||
|
|
||||||
- **`vmm`** — map a fresh frame at an unused virtual address, write and read it
|
- **`vmm`** — map a fresh frame at an unused virtual address, write and read it
|
||||||
back. Proves `map` works end to end.
|
back. Proves `map` works end to end.
|
||||||
@@ -138,8 +138,8 @@ Four tests (see [testing.md](testing.md)) pin down the guarantees:
|
|||||||
processes own the low half.
|
processes own the low half.
|
||||||
- **Per-address-space tables** — done: each user process gets its own root with
|
- **Per-address-space tables** — done: each user process gets its own root with
|
||||||
the kernel half shared, and refcounted shared-memory mappings exist
|
the kernel half shared, and refcounted shared-memory mappings exist
|
||||||
([ipc.md](ipc.md)). Copy-on-write remains unbuilt — nothing has needed it yet.
|
([ipc.md](../device-driver-development/ipc.md)). Copy-on-write remains unbuilt — nothing has needed it yet.
|
||||||
- **Uncacheable MMIO** — half done: user-space device and DMA mappings are
|
- **Uncacheable MMIO** — half done: user-space device and DMA mappings are
|
||||||
strong-uncacheable and the framebuffer is write-combining via the PAT, but the
|
strong-uncacheable and the framebuffer is write-combining via the PAT, but the
|
||||||
kernel's own `mapMmio` path is still writeback — the LAPIC included (see
|
kernel's own `mapMmio` path is still writeback — the LAPIC included (see
|
||||||
[device-interrupts.md](device-interrupts.md)).
|
[device-interrupts.md](../device-driver-development/device-interrupts.md)).
|
||||||
@@ -7,7 +7,7 @@ them owns the hardware that reported the event, and the reporter should not know
|
|||||||
who is listening. So system power is a **service**: an event source **publishes**
|
who is listening. So system power is a **service**: an event source **publishes**
|
||||||
button/lid/battery/AC events, interested processes **subscribe**, and one
|
button/lid/battery/AC events, interested processes **subscribe**, and one
|
||||||
privileged caller — init — can ask it to power the machine off. It is the same
|
privileged caller — init — can ask it to power the machine off. It is the same
|
||||||
publish/subscribe shape as the [input service](input.md), applied to power.
|
publish/subscribe shape as the [input service](../device-driver-development/input.md), applied to power.
|
||||||
|
|
||||||
## Why a service, and why it is named for the domain, not the firmware
|
## Why a service, and why it is named for the domain, not the firmware
|
||||||
|
|
||||||
@@ -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.
|
([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
|
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`
|
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**
|
module and a contract named `/protocol/power`; on x86 the **acpi service**
|
||||||
registers it, and on ARM a PSCI/mailbox service will register the *same* id.
|
binds it, and on ARM a PSCI/mailbox service will bind the *same* name.
|
||||||
Subscribers call `runtime.ipc.lookup(.power)` and never learn which firmware they
|
Subscribers open `/protocol/power` and never learn which firmware they
|
||||||
are on — the neutrality the whole [discovery](discovery.md) migration exists to
|
are on — the neutrality the whole [discovery](discovery.md) migration exists to
|
||||||
preserve, carried one layer up into a running-system surface.
|
preserve, carried one layer up into a running-system surface.
|
||||||
|
|
||||||
@@ -27,29 +27,44 @@ unchanged.
|
|||||||
|
|
||||||
## The protocol
|
## The protocol
|
||||||
|
|
||||||
The `power-protocol` module ([system/services/power/protocol.zig](../system/services/power/protocol.zig))
|
The `power-protocol` module ([library/protocol/power/power-protocol.zig](../../library/protocol/power/power-protocol.zig))
|
||||||
follows the vfs-protocol pattern — extern-struct messages, a version, reserved
|
is defined through the [envelope](protocol-namespace.md), so every packet begins
|
||||||
fields. Three operations:
|
with the folded `Header`. `Header.target` is unused in both directions: the
|
||||||
|
provider is the only object either side addresses.
|
||||||
|
|
||||||
| Direction | Operation | Purpose |
|
| Direction | Packet | Purpose |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| subscriber → service | `subscribe` | receive published events; the subscriber's endpoint rides as the call's **capability** (the input/device-manager pattern) |
|
| subscriber → service | `subscribe` (reserved verb 2) | receive published events; the subscriber's endpoint rides as the call's **capability** (the input/device-manager pattern) |
|
||||||
| init → service | `shutdown` | orderly shutdown's last step: enter S5 (soft off) |
|
| init → service | `shutdown` (verb 16) | orderly shutdown's last step: enter S5 (soft off) |
|
||||||
| service → subscriber | `event` | a published `EventMessage`, delivered as a buffered message (never sent *to* the service) |
|
| service → subscriber | one event per kind | a published `Notice`, `ipc_send`t as a buffered packet (never sent *to* the service) |
|
||||||
|
|
||||||
|
`subscribe` is not one of this protocol's own verbs: a synchronous call whose
|
||||||
|
attached capability is the subscriber's endpoint is exactly what the envelope's
|
||||||
|
reserved `subscribe` means everywhere, so power adopts it wholesale. And no
|
||||||
|
packet carries a version — the reserved `describe` verb is the version handshake,
|
||||||
|
asked once at connect time rather than out of every packet's budget.
|
||||||
|
|
||||||
Events are published, not polled: like the input service, the service holds
|
Events are published, not polled: like the input service, the service holds
|
||||||
subscriber endpoints as capabilities and `ipc_send`s each event as a buffered
|
subscriber endpoints as capabilities and `ipc_send`s each event as a buffered
|
||||||
message, so a slow or dead subscriber can never wedge the source. The event
|
packet, so a slow or dead subscriber can never wedge the source. The table, the
|
||||||
|
reserved `subscribe`/`unsubscribe` verbs and the fan-out are the **service
|
||||||
|
harness's** (`service.Subscribers`), shared with input and the device manager, so
|
||||||
|
the acpi service's own code is the ACPI half only — and a subscriber that dies is
|
||||||
|
now swept on its exit notification, where before this service had no sweep at
|
||||||
|
all. **The kind is the packet's operation** — one declared event per named kind, exactly as the
|
||||||
|
input service delivers one per device class — so a subscriber reads *what
|
||||||
|
happened* out of the header rather than out of a tag inside the payload. The
|
||||||
vocabulary is hardware-neutral:
|
vocabulary is hardware-neutral:
|
||||||
|
|
||||||
- `power_button` — the button was pressed (a fixed ACPI event on x86).
|
- `power_button` (event 16) — the button was pressed (a fixed ACPI event on x86).
|
||||||
- `lid`, `ac`, `battery` — the named GPE-driven events.
|
- `lid` (17), `ac` (18), `battery` (19) — the named GPE-driven events.
|
||||||
- `notify` — a device notification that maps to none of the above; its `code`
|
- `notify` (20) — a device notification that maps to none of the above; its
|
||||||
(the ACPI `Notify` argument) and the notifying device's `hid` say which device
|
`code` (the ACPI `Notify` argument) and the notifying device's `hid` say which
|
||||||
and what happened.
|
device and what happened.
|
||||||
|
|
||||||
An `EventMessage` carries the `event` tag plus `code` and an 8-byte `hid`, so a
|
The payload every one of them carries is a `Notice`: `code` plus an 8-byte `hid`,
|
||||||
generic `notify` is fully described without a second round trip.
|
so a generic `notify` is fully described without a second round trip, and the
|
||||||
|
four named kinds leave both fields zero because the verb already said it all.
|
||||||
|
|
||||||
**`shutdown` is authority, not information.** It is the only operation that
|
**`shutdown` is authority, not information.** It is the only operation that
|
||||||
*does* something irreversible, so it is gated: the contract is that only init
|
*does* something irreversible, so it is gated: the contract is that only init
|
||||||
@@ -58,7 +73,10 @@ sequence over everything else. The acpi service implements this as a **soft
|
|||||||
gate** — it honors `shutdown` only from a process that is a *subscriber*, and
|
gate** — it honors `shutdown` only from a process that is a *subscriber*, and
|
||||||
init is the one subscriber. That stands in for "only the system supervisor may
|
init is the one subscriber. That stands in for "only the system supervisor may
|
||||||
power off" without hard-coding a pid, so it still holds under tests where PID 1
|
power off" without hard-coding a pid, so it still holds under tests where PID 1
|
||||||
is not init.
|
is not init. The question is asked of the harness's table now
|
||||||
|
(`Subscribers.has(sender)`), which is why the harness exposes it: the gate is
|
||||||
|
unchanged, including the badge being the whole of it — the badge is
|
||||||
|
kernel-stamped, so nothing inside a packet can claim to be init.
|
||||||
|
|
||||||
## Orderly shutdown
|
## Orderly shutdown
|
||||||
|
|
||||||
@@ -75,7 +93,7 @@ notifications, the lifecycle **signals** it can receive (`terminate`), and the
|
|||||||
On a `power_button` event or a `terminate` signal, init:
|
On a `power_button` event or a `terminate` signal, init:
|
||||||
|
|
||||||
1. logs that it is shutting down,
|
1. logs that it is shutting down,
|
||||||
2. runs the standard stop sequence — `runtime.process.stop(child, deadline,
|
2. runs the standard stop sequence — `process.stop(child, deadline,
|
||||||
endpoint)` — over its children **in reverse spawn order**, so the VFS stops
|
endpoint)` — over its children **in reverse spawn order**, so the VFS stops
|
||||||
last (other services may flush through it), each child getting the
|
last (other services may flush through it), each child getting the
|
||||||
*terminate → deadline → kill* escalation from
|
*terminate → deadline → kill* escalation from
|
||||||
@@ -92,9 +110,9 @@ fails rather than hangs.
|
|||||||
`acpi-tables` node ([discovery.md](discovery.md)) already put the PM1 control
|
`acpi-tables` node ([discovery.md](discovery.md)) already put the PM1 control
|
||||||
ports in the acpi service's hands, so writing S5 from ring 3 is something it
|
ports in the acpi service's hands, so writing S5 from ring 3 is something it
|
||||||
could physically already do; formalizing it as a protocol operation added a
|
could physically already do; formalizing it as a protocol operation added a
|
||||||
contract, not authority. The kernel's `system/devices/power.zig` keeps only
|
contract, not authority. The kernel keeps only **reboot** (`acpi.reboot` in
|
||||||
**reboot** (the FADT reset register plus the legacy fallbacks, which need no AML);
|
`system/kernel/acpi.zig` — the FADT reset register plus the legacy fallbacks, which
|
||||||
it has no poweroff path at all — S5 is not a kernel operation.
|
need no AML); it has no poweroff path at all — S5 is not a kernel operation.
|
||||||
|
|
||||||
## Verifying it
|
## Verifying it
|
||||||
|
|
||||||
@@ -126,5 +144,5 @@ until laptop sleep), and thermal zones.
|
|||||||
firmware neutrality that makes a PSCI backend drop-in on ARM.
|
firmware neutrality that makes a PSCI backend drop-in on ARM.
|
||||||
- [process-lifecycle.md](process-lifecycle.md) — the stop sequence
|
- [process-lifecycle.md](process-lifecycle.md) — the stop sequence
|
||||||
(`terminate → deadline → kill`) and signals init composes into shutdown.
|
(`terminate → deadline → kill`) and signals init composes into shutdown.
|
||||||
- [device-manager.md](device-manager.md) — the supervision model init mirrors for
|
- [device-manager.md](../device-driver-development/device-manager.md) — the supervision model init mirrors for
|
||||||
its own children.
|
its own children.
|
||||||
@@ -6,10 +6,10 @@ harness are all in — the interface below is as-built. The primitives underneat
|
|||||||
predate this design ([process-management.md](process-management.md):
|
predate this design ([process-management.md](process-management.md):
|
||||||
spawn, the supervision link, kill, child-exit notifications); this document designs
|
spawn, the supervision link, kill, child-exit notifications); this document designs
|
||||||
the layer above them — the standard vocabulary a danos process speaks about its own
|
the layer above them — the standard vocabulary a danos process speaks about its own
|
||||||
life, and the stable `runtime.process` interface that carries it. Nothing here is
|
life, and the stable `process` interface that carries it. Nothing here is
|
||||||
device- or driver-specific: a driver, the VFS, and a user application all stop,
|
device- or driver-specific: a driver, the VFS, and a user application all stop,
|
||||||
reload, and die the same way. The device manager is simply this design's first
|
reload, and die the same way. The device manager is simply this design's first
|
||||||
serious customer ([device-manager.md](device-manager.md)).
|
serious customer ([device-manager.md](../device-driver-development/device-manager.md)).
|
||||||
|
|
||||||
**"POSIX" in this document means the concepts, never the letter of the standard.**
|
**"POSIX" in this document means the concepts, never the letter of the standard.**
|
||||||
danos borrows the ideas and the hard-won lessons (what SIGTERM *means*, why SIGPIPE
|
danos borrows the ideas and the hard-won lessons (what SIGTERM *means*, why SIGPIPE
|
||||||
@@ -19,7 +19,7 @@ rule is danos's own and it is strict: plain words that communicate intent
|
|||||||
(`bind`, `subscribe`, `publish`, `endpoint`) — never `SIG*`, never a second word for
|
(`bind`, `subscribe`, `publish`, `endpoint`) — never `SIG*`, never a second word for
|
||||||
a concept that already has one. Literal POSIX arrives later and lives elsewhere: the
|
a concept that already has one. Literal POSIX arrives later and lives elsewhere: the
|
||||||
`std.os.danos` seam that makes danos a Zig target, and eventually a **musl-based C
|
`std.os.danos` seam that makes danos a Zig target, and eventually a **musl-based C
|
||||||
layer** on the same native surface (see [zig-self-hosting.md](zig-self-hosting.md)) —
|
layer** on the same native surface (see [zig-self-hosting.md](../zig-self-hosting.md)) —
|
||||||
musl's syscall surface retargeted at danos system calls and IPC protocols (files onto
|
musl's syscall surface retargeted at danos system calls and IPC protocols (files onto
|
||||||
the VFS protocol, `sigaction`/`wait` onto this lifecycle, sockets onto whatever
|
the VFS protocol, `sigaction`/`wait` onto this lifecycle, sockets onto whatever
|
||||||
networking becomes). Ported programs see POSIX; the system underneath never does.
|
networking becomes). Ported programs see POSIX; the system underneath never does.
|
||||||
@@ -172,7 +172,7 @@ zombie state or privileged snooping:
|
|||||||
the server's reply with `-EPEER`; a server that dies fails its waiting clients
|
the server's reply with `-EPEER`; a server that dies fails its waiting clients
|
||||||
the same way. This covers the *synchronous* case only.
|
the same way. This covers the *synchronous* case only.
|
||||||
3. **The subscribers** — the new piece, and it is the input service's
|
3. **The subscribers** — the new piece, and it is the input service's
|
||||||
publish/subscribe shape ([input.md](input.md)) applied to exits. A stateful
|
publish/subscribe shape ([input.md](../device-driver-development/input.md)) applied to exits. A stateful
|
||||||
service accumulates per-client state across many requests: a filesystem server
|
service accumulates per-client state across many requests: a filesystem server
|
||||||
(FAT today) holds a dead client's open file handles, the input service holds
|
(FAT today) holds a dead client's open file handles, the input service holds
|
||||||
its subscriptions, a future network stack holds its sockets. None of these
|
its subscriptions, a future network stack holds its sockets. None of these
|
||||||
@@ -184,13 +184,19 @@ zombie state or privileged snooping:
|
|||||||
same encoding supervisors already decode, the IRQ-as-IPC pattern once more). The
|
same encoding supervisors already decode, the IRQ-as-IPC pattern once more). The
|
||||||
subscriber filters for ids it holds state for and releases what the dead client
|
subscriber filters for ids it holds state for and releases what the dead client
|
||||||
held. Correlating is free of bookkeeping: an IPC sender's badge already *is* its
|
held. Correlating is free of bookkeeping: an IPC sender's badge already *is* its
|
||||||
task id (`runtime.ipc.Received`), so the id a service has been keying client
|
task id (`ipc.Received`), so the id a service has been keying client
|
||||||
state by all along is the id the exit event carries.
|
state by all along is the id the exit event carries.
|
||||||
|
|
||||||
Subscription, not broadcast-to-everyone: only processes that asked receive
|
Subscription, not broadcast-to-everyone: only processes that asked receive
|
||||||
events, the kernel keeps a bounded subscriber table, and delivery is the same
|
events, the kernel keeps a bounded subscriber table (sixteen — a normal boot
|
||||||
non-blocking coalescing notification as everything else — a dying process never
|
already fields six, since this is what *every* provider with per-client state
|
||||||
waits on its mourners. Subscribing is ungated, like `process_enumerate`: what is
|
releases on), and delivery is the same non-blocking coalescing notification as
|
||||||
|
everything else — a dying process never waits on its mourners.
|
||||||
|
A service does not usually write the sweep itself: the shared service harness
|
||||||
|
subscribes for it and drops a dead task's event subscriptions
|
||||||
|
(`service.Subscribers`), and a provider adds its own handler only for state the
|
||||||
|
harness knows nothing about — open files, layers, device tokens.
|
||||||
|
Subscribing is ungated, like `process_enumerate`: what is
|
||||||
running (and dying) is not a secret between cooperating processes. Subscribers
|
running (and dying) is not a secret between cooperating processes. Subscribers
|
||||||
do not receive the exit reason — the filesystem server does not care *why*
|
do not receive the exit reason — the filesystem server does not care *why*
|
||||||
the client died.
|
the client died.
|
||||||
@@ -200,9 +206,9 @@ its clients cleaning up after themselves.** Handle release on client death is th
|
|||||||
service's job, triggered by the published exit event — never by a courtesy
|
service's job, triggered by the published exit event — never by a courtesy
|
||||||
"closing now" message that a crashed client will never send.
|
"closing now" message that a crashed client will never send.
|
||||||
|
|
||||||
## The stable interface: `runtime.process`
|
## The stable interface: `process`
|
||||||
|
|
||||||
`runtime.process` already owns what a process receives at birth (`Init`, the
|
`process` already owns what a process receives at birth (`Init`, the
|
||||||
argv contract). It grows to own the other end of life.
|
argv contract). It grows to own the other end of life.
|
||||||
|
|
||||||
**The runtime is the stable interface; the numbers are not.** danos applications do
|
**The runtime is the stable interface; the numbers are not.** danos applications do
|
||||||
@@ -283,8 +289,12 @@ callbacks (`on_terminate`, `on_reload`) for programs that want defaults.
|
|||||||
|
|
||||||
### The service harness
|
### The service harness
|
||||||
|
|
||||||
`runtime.service` owns the `replyWait` loop and folds every event source — signals,
|
`service` owns the `replyWait` loop and folds every event source — signals,
|
||||||
child exits, protocol messages — into callbacks, with the vocabulary's defaults:
|
child exits, protocol messages — into callbacks, with the vocabulary's defaults:
|
||||||
|
it also owns the **subscriber side** of any protocol that declares events
|
||||||
|
(`service.Subscribers`: the table, the reserved `subscribe`/`unsubscribe` verbs,
|
||||||
|
the fan-out, and the sweep on a subscriber's published exit), so every event
|
||||||
|
stream in the system behaves identically.
|
||||||
`terminate` returns from the loop (clean exit), the common `ping` is answered automatically,
|
`terminate` returns from the loop (clean exit), the common `ping` is answered automatically,
|
||||||
`reload` is ignored unless overridden. One loop, no locking, nothing reentrant. A
|
`reload` is ignored unless overridden. One loop, no locking, nothing reentrant. A
|
||||||
service author writes domain logic; the lifecycle contract is satisfied by the
|
service author writes domain logic; the lifecycle contract is satisfied by the
|
||||||
@@ -312,15 +322,15 @@ get POSIX; danos-native programs never pay for it.
|
|||||||
kill a claiming driver, spawn it again, the claim succeeds.
|
kill a claiming driver, spawn it again, the claim succeeds.
|
||||||
2. **Exit reason in the death notification** (`ExitReason` above).
|
2. **Exit reason in the death notification** (`ExitReason` above).
|
||||||
3. **Exit events**: `process_subscribe` in the kernel (bounded subscriber table,
|
3. **Exit events**: `process_subscribe` in the kernel (bounded subscriber table,
|
||||||
publishes on every death), `runtime.process.subscribeExits`; the userspace VFS
|
publishes on every death), `process.subscribeExits`; the userspace VFS
|
||||||
router was the first subscriber — releasing a dead client's handles was its
|
router was the first subscriber — releasing a dead client's handles was its
|
||||||
proof test — and the FAT server inherited the role when the router moved into
|
proof test — and the FAT server inherited the role when the router moved into
|
||||||
the kernel (clients now hold the filesystem server's node ids directly).
|
the kernel (clients now hold the filesystem server's node ids directly).
|
||||||
4. **Signals**: `signal_bind` + `process_signal` + the pending mask in the kernel;
|
4. **Signals**: `signal_bind` + `process_signal` + the pending mask in the kernel;
|
||||||
`runtime.process` grows the interface above; the service harness handles
|
`process` grows the interface above; the service harness handles
|
||||||
`terminate` and answers the common `ping`; `stop()` for supervisors.
|
`terminate` and answers the common `ping`; `stop()` for supervisors.
|
||||||
|
|
||||||
[device-manager.md](device-manager.md) builds directly on all four.
|
[device-manager.md](../device-driver-development/device-manager.md) builds directly on all four.
|
||||||
|
|
||||||
## Settled questions (2026-07-12)
|
## Settled questions (2026-07-12)
|
||||||
|
|
||||||
@@ -14,7 +14,7 @@ process-manager server, and Fuchsia/seL4 control processes only through handles.
|
|||||||
|
|
||||||
danos rules out `/proc` **as the primitive**: the path router lives in the
|
danos rules out `/proc` **as the primitive**: the path router lives in the
|
||||||
kernel (`fs_resolve`), but what is mounted under a path is served by a
|
kernel (`fs_resolve`), but what is mounted under a path is served by a
|
||||||
user-process filesystem server (the way FAT serves `/mnt/usb`) — a `/proc`
|
user-process filesystem server (the way FAT serves `/volumes/usb`) — a `/proc`
|
||||||
would be one more such server, which would put a user process in the path of
|
would be one more such server, which would put a user process in the path of
|
||||||
process control. If that server (or anything under it) hangs, nothing could be
|
process control. If that server (or anything under it) hangs, nothing could be
|
||||||
listed or killed, *including the hung server*. The control plane for processes
|
listed or killed, *including the hung server*. The control plane for processes
|
||||||
@@ -114,12 +114,14 @@ the architecture layer calls up into `tick`.
|
|||||||
- ~~There is no exit status in the notification~~ Closed (M17.2): the kernel
|
- ~~There is no exit status in the notification~~ Closed (M17.2): the kernel
|
||||||
records how every process ends — exited, a fault class, or killed — before it
|
records how every process ends — exited, a fault class, or killed — before it
|
||||||
posts the exit notification, and the supervisor reads it with
|
posts the exit notification, and the supervisor reads it with
|
||||||
`process_exit_reason` (`runtime.process.exitReason`). This is the input to
|
`process_exit_reason` (`process.exitReason`). This is the input to
|
||||||
restart policy ([process-lifecycle.md](process-lifecycle.md)); an exit *code*
|
restart policy ([process-lifecycle.md](process-lifecycle.md)); an exit *code*
|
||||||
for the clean case can still ride alongside later.
|
for the clean case can still ride alongside later.
|
||||||
- Enumerate writes through the caller's raw pointer under the bring-up trust
|
- ~~Enumerate writes through the caller's raw pointer under the bring-up trust
|
||||||
model, like `device_enumerate` (an unmapped page is a self-DoS, not an
|
model, like `device_enumerate`~~ Closed (8d4a7cf): both `process_enumerate`
|
||||||
isolation break).
|
and `device_enumerate` describe a chunk into a kernel buffer and place it with
|
||||||
|
`copyToUser`, which validates the range and resolves each page — an unmapped
|
||||||
|
page returns `-EFAULT`, and the kernel never stores through the user pointer.
|
||||||
|
|
||||||
## Tests
|
## Tests
|
||||||
|
|
||||||
@@ -0,0 +1,474 @@
|
|||||||
|
# The protocol namespace
|
||||||
|
|
||||||
|
*Design, agreed 2026-07-31. Supersedes the `ServiceId` registry. P1–P4 of the
|
||||||
|
migration plan at the end have landed (the envelope, the registry and the
|
||||||
|
`ServiceId` flag-day, restriction stage one, and the protocol rebase); P5
|
||||||
|
(restriction stage two) is the remaining work.*
|
||||||
|
|
||||||
|
How a program finds, connects to, and is restricted from the things it talks to.
|
||||||
|
Three ideas, kept deliberately separate:
|
||||||
|
|
||||||
|
1. **Naming** — a path under `/protocol` names a *contract*, not a service.
|
||||||
|
2. **Access** — resolving that path yields an endpoint *capability*; what a process
|
||||||
|
cannot resolve, it cannot reach.
|
||||||
|
3. **Transport** — unchanged: packets over channels, moved by whichever
|
||||||
|
transport the channel rides (kernel-ipc first).
|
||||||
|
This document is layers **L3** (the namespace) and **L2** (the protocol
|
||||||
|
and its envelope) of the communication stack;
|
||||||
|
[communication.md](communication.md) owns the model and the vocabulary
|
||||||
|
(*protocol* the language, *channel* the conversation, *packet* the
|
||||||
|
transmitted unit, *signal* the payload-less poke, *transport* the
|
||||||
|
replaceable mechanism), and
|
||||||
|
[ipc.md](../device-driver-development/ipc.md) is the first transport.
|
||||||
|
|
||||||
|
## Why ServiceId has to go
|
||||||
|
|
||||||
|
Today a service calls `ipc_register(service_id, endpoint)` and a client calls
|
||||||
|
`ipc_lookup(service_id)`, where `ServiceId` is a compile-time enum in `abi.zig`
|
||||||
|
backed by a flat 16-slot table in the kernel. Three defects, in rising order:
|
||||||
|
|
||||||
|
- **Static.** The id space is baked into the ABI at compile time. A third-party
|
||||||
|
program can never introduce a service; the one place danos is *less* dynamic
|
||||||
|
than its own design.
|
||||||
|
- **Ungated.** `ipc_register` is callable by any process and *replaces* an
|
||||||
|
existing registration. Any process can hijack `.fat` or `.display` and
|
||||||
|
impersonate it. `ipc_lookup` is equally ambient.
|
||||||
|
- **Unrestrictable.** Because lookup is a syscall available to everyone, there is
|
||||||
|
no point at which "this process may not talk to the display" can be enforced.
|
||||||
|
Any future file-access restriction would be bypassable by speaking to the FAT
|
||||||
|
server directly.
|
||||||
|
|
||||||
|
## Naming: contracts, not services
|
||||||
|
|
||||||
|
`/protocol/<name>` names a protocol — the contract a conversation follows — and
|
||||||
|
resolving it connects you to whatever process currently provides that contract.
|
||||||
|
The client never cared *which* binary answers; it cares that its messages are
|
||||||
|
understood. Naming the contract makes that explicit, and buys:
|
||||||
|
|
||||||
|
- **Swappable providers.** Replace the display server; `/protocol/display`
|
||||||
|
routes to the new one; clients notice nothing.
|
||||||
|
- **Test fakes.** Spawn a program whose namespace wires `/protocol/display` to a
|
||||||
|
mock. The name promises the protocol; the mock speaks it.
|
||||||
|
- **One vocabulary.** The names mirror `library/protocol/`: a program imports
|
||||||
|
the `display-protocol` module, then opens `/protocol/display`. What you
|
||||||
|
compiled against and what you ask the namespace for are the same word.
|
||||||
|
|
||||||
|
A leaf names one contract — kebab-case, full words, matching the
|
||||||
|
`library/protocol/` module that defines its wire format — and related
|
||||||
|
contracts group into directories: `/protocol/networking/ip`,
|
||||||
|
`/protocol/networking/bluetooth`. Directories organize *contracts only*;
|
||||||
|
they never encode addressing (see below), so a directory appears because a
|
||||||
|
domain has several contracts, never because hardware multiplied. The module
|
||||||
|
tree mirrors the namespace (`library/protocol/networking/ip` ↔
|
||||||
|
`/protocol/networking/ip`), and registrar grants scope naturally to subtrees
|
||||||
|
— an application installed at `/applications/foo` can be granted
|
||||||
|
`/protocol/applications/foo/...` and nothing above it. `/protocol` is
|
||||||
|
top level, beside `/system` and `/applications`, because the boundary it names
|
||||||
|
is spoken on both sides: applications talk to protocols as much as the OS does
|
||||||
|
(see [file-system-hierarchy.md](../file-system-development/file-system-hierarchy.md)).
|
||||||
|
|
||||||
|
**Addressing lives inside the protocol, never in the path.** Which volume, which
|
||||||
|
layer, which input device — that is a destination field in the messages, the way
|
||||||
|
TCP carries a destination address, and the way danos protocols already work (the
|
||||||
|
display protocol multiplexes layer ids; the vfs protocol addresses node ids).
|
||||||
|
The namespace answers exactly one question — *may this process speak this
|
||||||
|
protocol at all* — so `/protocol/block` is one name no matter how many disks are
|
||||||
|
attached. The source address is never in the message either: it is the IPC
|
||||||
|
badge, stamped by the kernel per message, unforgeable — a property TCP's source
|
||||||
|
address does not have.
|
||||||
|
|
||||||
|
`/system/devices` (the device inventory) stays purely informational: facts for
|
||||||
|
diagnosis, never a routing mechanism. Unix conflated the two in `/dev`; danos
|
||||||
|
does not. You *read about* hardware in `/system/devices`; you *talk to* it
|
||||||
|
through `/protocol`.
|
||||||
|
|
||||||
|
## Resolution: a protocol node in the VFS
|
||||||
|
|
||||||
|
The kernel VFS router already does the hard part: `fs_resolve` matches a mount
|
||||||
|
prefix and installs the backend's endpoint capability in the caller's handle
|
||||||
|
table. The registry is just a backend mounted at `/protocol` — ring 3, like FAT.
|
||||||
|
Connecting is a normal vfs-protocol `open` with one twist in the reply:
|
||||||
|
|
||||||
|
```
|
||||||
|
client kernel router registry backend
|
||||||
|
│ fs_resolve("/protocol/display") │
|
||||||
|
│──────────────────────────▶│ prefix match: /protocol │
|
||||||
|
│◀── registry endpoint ─────│ (capability installed) │
|
||||||
|
│ vfs open("display") ──────────────────────────────────────▶│
|
||||||
|
│◀───────────────── Reply + capability = provider endpoint ──│
|
||||||
|
│ ipc_call(provider, display-protocol messages...) │
|
||||||
|
```
|
||||||
|
|
||||||
|
Both capability moves use machinery the kernel already has: request-direction
|
||||||
|
and reply-direction `send_cap` on `call`/`replyWait`. The vfs protocol needs two
|
||||||
|
additions, both append-only:
|
||||||
|
|
||||||
|
- `NodeKind.protocol` — a node that names a contract; its `open` establishes
|
||||||
|
a **channel** (delivered as an endpoint capability) instead of returning a
|
||||||
|
file id. The node is the protocol, the channel is the conversation, and the
|
||||||
|
addressing inside the packets decides where within the provider each one
|
||||||
|
lands. `readdir` over `/protocol` lists protocol nodes like any others, so
|
||||||
|
the tree stays browsable for diagnosis.
|
||||||
|
- The convention that an `open` reply may carry a capability. File backends
|
||||||
|
(FAT) never use it; synthetic backends (the registry, later the device
|
||||||
|
inventory) do.
|
||||||
|
|
||||||
|
The path lookup happens once, at connect time. The hot path — `ipc_call` on the
|
||||||
|
cached endpoint — is untouched. A provider crash turns the cached endpoint dead
|
||||||
|
(`-EPEER`), and the client's recovery is to re-resolve: the restart story falls
|
||||||
|
out of the naming layer for free.
|
||||||
|
|
||||||
|
## Registration: the registrar, held by init
|
||||||
|
|
||||||
|
The registry backend is **init**. It is already PID 1, already spawns every
|
||||||
|
service from its manifest, and already holds the supervision link to each — it
|
||||||
|
is the process that *knows* which binary is which. (If init grows
|
||||||
|
uncomfortable, the same design lifts into a dedicated registry service that
|
||||||
|
init spawns first and delegates to; nothing below changes.)
|
||||||
|
|
||||||
|
- **Binding.** A service creates its endpoint and sends the registry a `bind`
|
||||||
|
request with the protocol name as payload and the endpoint attached as the
|
||||||
|
call's capability.
|
||||||
|
- **Authorization.** Init's manifest gains a column: the protocols each spawned
|
||||||
|
binary may bind. A `bind` from any process not granted that name is refused
|
||||||
|
(`-EPERM`) — the badge identifies the caller, the supervision records map
|
||||||
|
badge to binary. This is the registrar authority; it never leaves init.
|
||||||
|
- **Collision is an error.** A name already bound refuses a second bind — never
|
||||||
|
last-writer-wins. When a provider dies, init (its supervisor) unbinds its
|
||||||
|
names; the restarted instance binds again.
|
||||||
|
- **Provenance.** The registry records name → task id → binary path, so a
|
||||||
|
diagnostic listing answers "who serves this?" at a glance:
|
||||||
|
|
||||||
|
```
|
||||||
|
/protocol/display pid 12 /system/services/display
|
||||||
|
/protocol/input pid 7 /system/services/input
|
||||||
|
```
|
||||||
|
|
||||||
|
`ipc_register` and `ipc_lookup` retire; the `ServiceId` enum leaves `abi.zig`.
|
||||||
|
The kernel keeps one residual rule: `/protocol` becomes a reserved prefix like
|
||||||
|
`/system` — `fs_mount` refuses to shadow it, and init's boot-time mount is the
|
||||||
|
only one it will ever hold. (Full gating of `fs_mount` is a separate item on
|
||||||
|
the security track; the reserved prefix closes the hole for this namespace
|
||||||
|
without waiting for it.)
|
||||||
|
|
||||||
|
## Restriction: per-process namespaces, not ACLs
|
||||||
|
|
||||||
|
danos has no users and no principals, deliberately. Restriction is therefore
|
||||||
|
**delegation**: what a process may open is decided by whoever spawned it, and
|
||||||
|
enforcement is absence — a protocol you cannot resolve does not exist for you.
|
||||||
|
"Permission denied" and "not found" are the same answer, which is the same
|
||||||
|
discipline the device layer already follows: the claim is the capability; here,
|
||||||
|
the resolvable name is the capability.
|
||||||
|
|
||||||
|
Two stages, deliberately ordered so the useful half lands first:
|
||||||
|
|
||||||
|
**Stage one — the registry filters by badge.** Init is both the spawner and the
|
||||||
|
registry, so its manifest already knows which binary may *open* which protocols
|
||||||
|
(a second manifest column, beside the bind grants). An `open` from a process
|
||||||
|
whose binary is not granted that protocol is refused. No new kernel mechanism
|
||||||
|
at all; the display driver's view can be narrowed to nothing, a future
|
||||||
|
downloaded application's to `display` and `input`, today.
|
||||||
|
|
||||||
|
**Stage two — spawn passes the namespace.** `spawn` gains an initial
|
||||||
|
capability: the child's connection to *its* registry view, chosen by the
|
||||||
|
spawner. A newly spawned process starts with an empty handle table and this one
|
||||||
|
handle — its world is whatever its parent wired in. This removes the last
|
||||||
|
ambient reach (`fs_resolve` finding `/protocol` globally), lets any supervisor
|
||||||
|
— not just init — narrow or fake a child's view (an application launcher
|
||||||
|
granting an app only what its manifest declares; a test harness substituting
|
||||||
|
every provider), and composes down the supervision tree. Stage one's manifest
|
||||||
|
column becomes the *content* of the view init builds, so nothing is thrown
|
||||||
|
away.
|
||||||
|
|
||||||
|
### A worked example: the microphone prompt
|
||||||
|
|
||||||
|
The scenario stage two exists for: an application opens
|
||||||
|
`/protocol/audio-input`, and the user should be asked. The supervisor is an
|
||||||
|
ordinary user process — an application launcher — and the flow needs no new
|
||||||
|
security concepts:
|
||||||
|
|
||||||
|
1. The launcher spawned the app with a namespace channel that terminates at
|
||||||
|
**the launcher itself**. The app's whole world is a conversation with its
|
||||||
|
supervisor.
|
||||||
|
2. The app's `open("audio-input")` packet lands in the launcher,
|
||||||
|
badge-stamped. The launcher spawned the app, so badge → binary path
|
||||||
|
(`/applications/foo`) is its own supervision record — "remember my choice"
|
||||||
|
needs no identity system.
|
||||||
|
3. Grant unknown → the launcher parks the request and shows a prompt (it is a
|
||||||
|
user process with display access; init never does UI). Blocking an open on
|
||||||
|
a human is architecturally fine: opens are connect-time, never hot-path.
|
||||||
|
4. **Yes** → the launcher opens `/protocol/audio-input` in *its own*
|
||||||
|
namespace and attaches the resulting channel to the parked reply. The app
|
||||||
|
cannot tell a prompt happened — a consented open is indistinguishable from
|
||||||
|
a direct one, merely slower.
|
||||||
|
5. **No** → refuse the open, indistinguishable from "no such protocol" — or
|
||||||
|
hand the app a **fake**: a silence-generating provider. The test-fake
|
||||||
|
mechanism doubles as a privacy feature.
|
||||||
|
|
||||||
|
The capability discipline holds throughout: the launcher can only grant what
|
||||||
|
it holds — if init never gave the launcher `audio-input`, no prompt can
|
||||||
|
conjure it. Consent is delegation flowing down the supervision tree, never a
|
||||||
|
global ACL edit. And the provider still sees the app's badge on every packet,
|
||||||
|
so a coarser second check at the audio service remains possible.
|
||||||
|
|
||||||
|
Two mechanical requirements this scenario pins on stage two:
|
||||||
|
|
||||||
|
- **Parked replies.** A prompt takes seconds, and the service loop holds one
|
||||||
|
outstanding reply today — the launcher must park request A, keep serving B
|
||||||
|
and C, and reply to A later (by badge). The kernel already tracks owed
|
||||||
|
replies (that is how death delivers `-EPEER`); multiple parked replies is
|
||||||
|
the extension, in the harness and, if needed, the kernel.
|
||||||
|
- **Granted channels are dedicated, hence revocable.** Once the app holds a
|
||||||
|
channel capability, nobody reaches into its handle table — so a
|
||||||
|
prompt-granted channel must be one that can be *killed*: a dedicated
|
||||||
|
endpoint pair (or per-client session at the provider) whose death turns
|
||||||
|
the app's capability into `-EPEER`. Revoking microphone access is then
|
||||||
|
killing that channel, using machinery that already exists.
|
||||||
|
|
||||||
|
One adjacent problem, named and deferred: **trusted UI**. The prompt is only
|
||||||
|
meaningful if the app cannot draw a convincing fake or overlay the real one —
|
||||||
|
a display-layer question (a reserved surface for the supervisor chain), owned
|
||||||
|
by the display track, not this one.
|
||||||
|
|
||||||
|
Fine-grained restriction *within* a protocol (this process may use volume A but
|
||||||
|
not volume B) is not the namespace's job. The capability-shaped answer, when it
|
||||||
|
is needed: the supervisor pre-opens a connection scoped to one target and passes
|
||||||
|
that connection to the child, which never opens `/protocol/block` at all.
|
||||||
|
Delegation again, not ACLs.
|
||||||
|
|
||||||
|
## The envelope: one addressing scheme for every protocol
|
||||||
|
|
||||||
|
Every protocol module today hand-rolls its `Request`/`Reply` with an
|
||||||
|
`operation` first field. That convention becomes a library, so addressing is
|
||||||
|
uniform and the rules are enforced by construction rather than by review. New
|
||||||
|
module: **`library/protocol/envelope`** (the one protocol-layer module that is
|
||||||
|
not itself a protocol).
|
||||||
|
|
||||||
|
```zig
|
||||||
|
/// Every packet a danos protocol transmits begins with this header.
|
||||||
|
pub const Header = extern struct {
|
||||||
|
operation: u32, // the verb; values 0..15 are reserved universal verbs
|
||||||
|
_padding: u32 = 0,
|
||||||
|
/// Object addressing, never party addressing: which of the peer's
|
||||||
|
/// objects this packet operates on — a volume, layer, node, device.
|
||||||
|
/// 0 addresses the provider itself. Parties are addressed by the
|
||||||
|
/// channel; the protocol defines target's meaning; the field's place
|
||||||
|
/// and width are universal.
|
||||||
|
target: u64 = 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Reserved verbs, answered by every provider.
|
||||||
|
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;
|
||||||
|
|
||||||
|
/// Every reply begins with this.
|
||||||
|
pub const Status = extern struct {
|
||||||
|
status: i32, // 0 or a negative errno
|
||||||
|
_padding: u32 = 0,
|
||||||
|
len: u32 = 0, // payload bytes following the header
|
||||||
|
_padding2: u32 = 0,
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
A protocol is then *defined through* the envelope, not beside it:
|
||||||
|
|
||||||
|
```zig
|
||||||
|
pub const Protocol = envelope.Define(.{
|
||||||
|
.name = "display",
|
||||||
|
.version = 1,
|
||||||
|
.operations = &.{
|
||||||
|
.{ .name = "configure_layer", .request = ConfigureLayer, .reply = void },
|
||||||
|
.{ .name = "blit", .request = Blit, .reply = void },
|
||||||
|
...
|
||||||
|
},
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
`Define` is comptime and is where the enforcement lives:
|
||||||
|
|
||||||
|
- verbs are numbered automatically from `first_protocol_operation`, so no
|
||||||
|
protocol can collide with the reserved range;
|
||||||
|
- every packet is size-checked at compile time against the kernel-ipc floor
|
||||||
|
— `packet_maximum` (256) for request/reply, `post_maximum` (64) for event
|
||||||
|
packets. Ceilings are transport properties
|
||||||
|
([communication.md](communication.md)); the floor is what every protocol
|
||||||
|
may assume on any transport. The errors that today surface as runtime
|
||||||
|
truncation become compile errors, and packets-never-fragment is enforced
|
||||||
|
at the source;
|
||||||
|
- the generated type carries encode/decode helpers and a provider-side dispatch
|
||||||
|
table, so a provider answers `describe` automatically and unknown operations
|
||||||
|
with `-ENOSYS` uniformly;
|
||||||
|
- the service harness (`library/kernel/service.zig`) accepts the generated
|
||||||
|
dispatch type, which is what makes the envelope *enforced*: a protocol that
|
||||||
|
bypasses `Define` does not plug into the harness.
|
||||||
|
|
||||||
|
Universal conventions that ride on the reserved verbs:
|
||||||
|
|
||||||
|
- **`describe`** is the version handshake. Version lives in the handshake, not
|
||||||
|
in every message — the 256-byte budget is too small to spend per call.
|
||||||
|
- **`enumerate`** is how multi-target protocols expose their targets, and the
|
||||||
|
standard `targets_changed` notification (a notify bit) tells subscribers to
|
||||||
|
re-enumerate — arrival and removal of volumes, layers, devices all take the
|
||||||
|
same shape. Hotplug fits the notification ring far better than a filesystem
|
||||||
|
tree ever did.
|
||||||
|
- **Source is the badge.** No protocol defines a "sender" field; the kernel's
|
||||||
|
per-message badge is the only source identity, and providers key per-client
|
||||||
|
state on it.
|
||||||
|
|
||||||
|
### Paths resolve once; integers do the work
|
||||||
|
|
||||||
|
A rule the envelope makes official: **a path appears in a conversation at most
|
||||||
|
once — at resolve or open — and everything after it addresses integers.** The
|
||||||
|
namespace resolves `/protocol/display` to an endpoint; a backend's `open`
|
||||||
|
resolves a path payload to a node id; from then on every packet carries the
|
||||||
|
integer in `target`. Integers compare in one instruction and fit the fixed
|
||||||
|
header, and the 256-byte message budget never re-carries path strings on the
|
||||||
|
hot path. This is already the system's shape — vfs node ids, display layer ids
|
||||||
|
— and the envelope pins it as the required shape for every protocol.
|
||||||
|
|
||||||
|
Two integer identities, not to be confused:
|
||||||
|
|
||||||
|
- **An open handle** — what vfs `open` returns today: transient, meaningful
|
||||||
|
only within one client's session with one provider, swept when the client
|
||||||
|
exits. Cheap, and all a protocol usually needs. Handles must be **scoped per
|
||||||
|
client** — validated against the badge, or drawn from a per-client id
|
||||||
|
namespace. (Today the FAT server's node ids are guessable small integers
|
||||||
|
honoured across clients; that hole closes with this rule.)
|
||||||
|
- **A persistent node identity** — a unix inode number, stable across opens
|
||||||
|
and renames. danos deliberately does not promise this, because FAT cannot
|
||||||
|
deliver it: a FAT file's identity is its directory entry, and rename or
|
||||||
|
truncation moves every candidate anchor. If a future filesystem or a cache
|
||||||
|
layer needs stable identity, that is the backend's promise to make, never
|
||||||
|
the protocol's assumption.
|
||||||
|
|
||||||
|
The five existing protocol modules (`vfs`, `display`, `input`, `power`,
|
||||||
|
`block`, plus `scanout`, `usb-transfer`, `device-manager`) rebase onto the
|
||||||
|
envelope during the migration flag-day. `input-protocol`'s subscribe/publish
|
||||||
|
split and `vfs-protocol`'s node addressing both map cleanly (`node` and layer
|
||||||
|
ids become `target`).
|
||||||
|
|
||||||
|
## Wiring: how conversations flow
|
||||||
|
|
||||||
|
The patterns below are channel-layer (L1) shapes; the delivery mechanics are
|
||||||
|
the kernel-ipc transport's, described here because it is the transport every
|
||||||
|
channel starts on. Kernel-ipc provides exactly three delivery shapes, and
|
||||||
|
every one is unicast. An endpoint is a mailbox owned by one process — its
|
||||||
|
creator receives; anyone holding its capability sends into it. That direction
|
||||||
|
never reverses:
|
||||||
|
|
||||||
|
1. **Synchronous call** — request/reply. The kernel parks the caller and
|
||||||
|
`replyWait` delivers the reply straight back, so the provider answers
|
||||||
|
without holding any capability to the client. Badge-stamped, blocking, and
|
||||||
|
the *only* shape that carries capabilities (in the request, and in the
|
||||||
|
reply — which is how a reverse path is bootstrapped).
|
||||||
|
2. **Asynchronous send** — an event packet pushed into the receiver's post
|
||||||
|
ring, at most `post_maximum` (64) bytes, no reply owed, never blocks the
|
||||||
|
sender. Strictly one-way: to be pushed to, you must first hand the pusher
|
||||||
|
your endpoint.
|
||||||
|
3. **Signals** — payload-less notification bits, below the packet layer,
|
||||||
|
coalescing: "something changed, come look."
|
||||||
|
|
||||||
|
A bidirectional link is therefore always **a pair of endpoints**, one per
|
||||||
|
direction, each delivered by cap-passing. Three conversation patterns are
|
||||||
|
built from these, and the envelope names all three:
|
||||||
|
|
||||||
|
- **Request/response** — the synchronous call. The default, and the only
|
||||||
|
place capabilities move.
|
||||||
|
- **Event stream** — `subscribe` (a synchronous call whose attached
|
||||||
|
capability is the subscriber's own endpoint), after which the provider
|
||||||
|
pushes events asynchronously; `unsubscribe` or subscriber exit ends it.
|
||||||
|
Listened-to, not blocked-on.
|
||||||
|
- **Change signal** — a signal plus re-read: `targets_changed` →
|
||||||
|
`enumerate`. For state whose truth lives with the provider.
|
||||||
|
|
||||||
|
**Broadcast is a provider pattern, never a kernel primitive.** The kernel
|
||||||
|
does not know subscriber sets — a service does. The input service is the
|
||||||
|
model: sources *publish* (a unicast call to the service), the service
|
||||||
|
*broadcasts* (a fan-out loop of asynchronous sends over its subscriber list,
|
||||||
|
so one dead subscriber can never stall the rest). One fan-out point per event
|
||||||
|
domain, owned by the service that defines the event.
|
||||||
|
|
||||||
|
The harness owns the machinery: the subscriber table, the dead-subscriber
|
||||||
|
sweep (via process-exit notifications), and the fan-out loop — all written by
|
||||||
|
hand in `input.zig` today, lifted into the service harness so every protocol
|
||||||
|
gets identical semantics. `Define` declares a protocol's events (`.events`),
|
||||||
|
and each event type is checked against `post_maximum` at compile time,
|
||||||
|
generalizing the assert `input-protocol` already carries.
|
||||||
|
|
||||||
|
**Event packets are droppable.** A slow subscriber's ring fills, and the
|
||||||
|
provider must not block on it — so an event stream is a hint or a coalescing
|
||||||
|
signal, never a ledger. Anything that must not be lost is either re-readable
|
||||||
|
state (the change-signal pattern) or bulk data in shared memory with a
|
||||||
|
packet as the doorbell, which is how the display path already works — the
|
||||||
|
packets-never-fragment rule and this one are the same rule seen from two
|
||||||
|
sides.
|
||||||
|
|
||||||
|
**Source direction (open point).** Today event sources are *clients*: an
|
||||||
|
input driver resolves `/protocol/input` and delivers each event as a
|
||||||
|
synchronous `publish` call — one capability, obtained by resolution, covers
|
||||||
|
everything, and the badge tells the service exactly who each event came from.
|
||||||
|
The inversion — the service subscribing to each driver — would require every
|
||||||
|
driver to be individually discoverable and its endpoint ferried to the
|
||||||
|
service, machinery whose payoff (the service choosing its sources) the
|
||||||
|
namespace already provides more cheaply: only a process granted open on
|
||||||
|
`/protocol/input` can publish into it. Sources stay clients for now;
|
||||||
|
revisited at restriction stage two, when a supervisor can wire capabilities
|
||||||
|
at spawn time.
|
||||||
|
|
||||||
|
## What this deliberately does not solve
|
||||||
|
|
||||||
|
The wider security track, for which this namespace is the foundation, not the
|
||||||
|
whole:
|
||||||
|
|
||||||
|
- **File access restriction** — the point of the exercise. The same stage-two
|
||||||
|
namespace mechanism extends from protocol names to file paths: the spawner
|
||||||
|
decides which subtrees resolve. Designed separately once this lands.
|
||||||
|
- `fs_mount` gating beyond the reserved prefixes; `system_spawn` gating;
|
||||||
|
`klog_read` being world-readable; backends checking the badge on per-node
|
||||||
|
operations (the FAT server honours node ids across clients today).
|
||||||
|
- Kernel hardening items already noted in-tree: SMEP/SMAP and SYSRET
|
||||||
|
canonical-RIP, now designed in [smep-smap.md](smep-smap.md).
|
||||||
|
- Pipes/FIFOs for the POSIX layer — a byte-stream object *beside* message IPC,
|
||||||
|
wanted by the Python track, unrelated to naming.
|
||||||
|
- **Trusted UI** — a permission prompt an application cannot fake or overlay
|
||||||
|
(see the microphone example). A display-track concern: the supervisor chain
|
||||||
|
needs a reserved surface.
|
||||||
|
|
||||||
|
## Migration plan
|
||||||
|
|
||||||
|
Flag-day per phase, in the style of the DMA-capability conversion — no
|
||||||
|
dual-stack periods, the QEMU suite green at each phase boundary.
|
||||||
|
|
||||||
|
**P1 — mechanics, no behavior change.** The `envelope` module with its comptime
|
||||||
|
`Define`, unit tests; `NodeKind.protocol` and the open-reply-capability
|
||||||
|
convention in `vfs-protocol`; existing protocols untouched.
|
||||||
|
|
||||||
|
**P2 — the registry.** Init serves `/protocol` (bind with manifest
|
||||||
|
authorization, collision refusal, unbind on provider death, provenance);
|
||||||
|
kernel reserves the `/protocol` prefix; every service converts from
|
||||||
|
`ipc_register` to `bind`, every client from `ipc_lookup` to resolve-and-open;
|
||||||
|
`ServiceId`, `ipc_register`, `ipc_lookup` deleted. Tests: unauthorized bind
|
||||||
|
refused, collision refused, provider restart re-binds and a client re-resolves.
|
||||||
|
|
||||||
|
**P3 — restriction, stage one.** The open-grant column in init's manifest;
|
||||||
|
registry refuses ungranted opens. Test: a fixture process denied a protocol its
|
||||||
|
neighbour is granted.
|
||||||
|
|
||||||
|
**P4 — protocol rebase.** Existing protocol modules re-expressed through
|
||||||
|
`Define`; providers move onto the generated dispatch; `describe`/`enumerate`
|
||||||
|
answered everywhere; the conformance test fixture exercises the reserved verbs
|
||||||
|
against every registered provider.
|
||||||
|
|
||||||
|
**P5 — restriction, stage two.** Spawn's initial capability; namespace views
|
||||||
|
built by the spawner; ambient resolution of `/protocol` retired. Includes the
|
||||||
|
two requirements the microphone example pins: **parked replies** (a
|
||||||
|
supervisor parks an open, keeps serving, replies later by badge) and
|
||||||
|
**dedicated, killable granted channels** (revocation = channel death →
|
||||||
|
`-EPEER`). Scoped separately — it touches `spawn`, the loader contract, and
|
||||||
|
every supervisor — and lands together with the file-path half of namespacing.
|
||||||
|
|
||||||
|
The unix-path migration ([file-system-hierarchy.md](../file-system-development/file-system-hierarchy.md#migration))
|
||||||
|
is independent of P1–P5 and can land before or after.
|
||||||
@@ -44,7 +44,7 @@ tables of contents, both pointing at the same embedded FAT image:
|
|||||||
same `BOOTX64.efi` off it.
|
same `BOOTX64.efi` off it.
|
||||||
|
|
||||||
Neither path involves the legacy BIOS boot-sector machinery: danos is
|
Neither path involves the legacy BIOS boot-sector machinery: danos is
|
||||||
UEFI-only ([system-requirements.md](system-requirements.md)), so the MBR holds
|
UEFI-only ([system-requirements.md](../system-requirements.md)), so the MBR holds
|
||||||
no boot code, just the partition entry, and the El Torito entry is EFI-class,
|
no boot code, just the partition entry, and the El Torito entry is EFI-class,
|
||||||
not floppy emulation.
|
not floppy emulation.
|
||||||
|
|
||||||
@@ -57,7 +57,7 @@ allocated from the front) either way. The USB path has no such cap.
|
|||||||
## The builder
|
## The builder
|
||||||
|
|
||||||
`tools/make-iso-image.py` follows the house rule of
|
`tools/make-iso-image.py` follows the house rule of
|
||||||
[make-fat-image.py](../tools/make-fat-image.py): pure Python 3 standard
|
[make-fat-image.py](../../tools/make-fat-image.py): pure Python 3 standard
|
||||||
library, no external tools (no xorriso, mkisofs, or isohybrid), with a
|
library, no external tools (no xorriso, mkisofs, or isohybrid), with a
|
||||||
`--verify` mode the `check-iso-image` step runs — it checks that the MBR
|
`--verify` mode the `check-iso-image` step runs — it checks that the MBR
|
||||||
partition and the El Torito catalog agree on where the FAT image lives and
|
partition and the El Torito catalog agree on where the FAT image lives and
|
||||||
@@ -5,7 +5,7 @@ isolation; fault → kill the process → keep the core (`onException`; the
|
|||||||
`fault-recovery` test); the supervisor notification **with exit reasons**
|
`fault-recovery` test); the supervisor notification **with exit reasons**
|
||||||
([process-lifecycle.md](process-lifecycle.md) — clean exit, fault class, or
|
([process-lifecycle.md](process-lifecycle.md) — clean exit, fault class, or
|
||||||
killed, recorded before the notice posts); and the **restart policy itself**
|
killed, recorded before the notice posts); and the **restart policy itself**
|
||||||
([device-manager.md](device-manager.md)): the device manager supervises every
|
([device-manager.md](../device-driver-development/device-manager.md)): the device manager supervises every
|
||||||
driver, restarts crashes with backoff, caps crash loops, and re-claims work
|
driver, restarts crashes with backoff, caps crash loops, and re-claims work
|
||||||
because the kernel releases a dead process's claims. The `driver-restart` and
|
because the kernel releases a dead process's claims. The `driver-restart` and
|
||||||
`usb-report` scenarios prove kill → release → respawn → re-claim → re-report
|
`usb-report` scenarios prove kill → release → respawn → re-claim → re-report
|
||||||
@@ -14,9 +14,9 @@ more of the system moved into restartable processes (the discovery migration,
|
|||||||
[discovery.md](discovery.md), is the next rung). This is the property danos is really chasing:
|
[discovery.md](discovery.md), is the next rung). This is the property danos is really chasing:
|
||||||
**if a part of the OS breaks, isolate it, and re-initialise it — without rebooting.**
|
**if a part of the OS breaks, isolate it, and re-initialise it — without rebooting.**
|
||||||
A crashed driver gets restarted; a wedged service gets killed and brought back. It's
|
A crashed driver gets restarted; a wedged service gets killed and brought back. It's
|
||||||
the reason the [microkernel](vision.md) shape was chosen, and it's a *separate* goal
|
the reason the [microkernel](../vision.md) shape was chosen, and it's a *separate* goal
|
||||||
from [real-time](smp.md#does-the-right-choice-depend-on-real-time-vs-resilience) —
|
from [real-time](smp.md#does-the-right-choice-depend-on-real-time-vs-resilience) —
|
||||||
one that's less pervasive to build (see [vision.md](vision.md)).
|
one that's less pervasive to build (see [vision.md](../vision.md)).
|
||||||
|
|
||||||
## The idea: "let it crash" + supervision
|
## The idea: "let it crash" + supervision
|
||||||
|
|
||||||
@@ -44,7 +44,7 @@ down. **Keeping the kernel minimal is a resilience strategy, not just an aesthet
|
|||||||
## The building blocks
|
## The building blocks
|
||||||
|
|
||||||
1. **Address-space isolation.** A fault in one component can't corrupt another or the
|
1. **Address-space isolation.** A fault in one component can't corrupt another or the
|
||||||
kernel. This is the [user-mode milestone](vision.md) (ring 3, per-process page
|
kernel. This is the [user-mode milestone](../vision.md) (ring 3, per-process page
|
||||||
tables) — the shared prerequisite for *any* of this, and it's needed regardless.
|
tables) — the shared prerequisite for *any* of this, and it's needed regardless.
|
||||||
2. **Fault detection** — how the system notices a component is dead or sick:
|
2. **Fault detection** — how the system notices a component is dead or sick:
|
||||||
- **Crash**: a CPU fault in a user process (page fault, illegal instruction) traps
|
- **Crash**: a CPU fault in a user process (page fault, illegal instruction) traps
|
||||||
@@ -81,7 +81,7 @@ Detecting and killing is the easy half. The genuinely tricky questions are about
|
|||||||
- **In-flight IPC**: messages sent to the dead component, or replies its clients are
|
- **In-flight IPC**: messages sent to the dead component, or replies its clients are
|
||||||
blocked waiting for. The channel has to break cleanly and unblock the waiters with
|
blocked waiting for. The channel has to break cleanly and unblock the waiters with
|
||||||
an error rather than hang them forever (a design constraint that reaches back into
|
an error rather than hang them forever (a design constraint that reaches back into
|
||||||
[ipc.md](ipc.md) — channels need a "peer died" outcome).
|
[ipc.md](../device-driver-development/ipc.md) — channels need a "peer died" outcome).
|
||||||
- **Clients**: how does a client discover the service it was talking to is gone and
|
- **Clients**: how does a client discover the service it was talking to is gone and
|
||||||
has been replaced? Options: capability revocation makes stale handles fail; or a
|
has been replaced? Options: capability revocation makes stale handles fail; or a
|
||||||
**name server** re-binds clients to the new instance; or clients retry through a
|
**name server** re-binds clients to the new instance; or clients retry through a
|
||||||
@@ -137,7 +137,7 @@ Honest boundaries:
|
|||||||
|
|
||||||
Resilience needs **structural** features (isolation + supervision + a resource
|
Resilience needs **structural** features (isolation + supervision + a resource
|
||||||
model); real-time needs a **pervasive** timing invariant. They're separable, and
|
model); real-time needs a **pervasive** timing invariant. They're separable, and
|
||||||
resilience is the lighter commitment (see [smp.md](smp.md) and [vision.md](vision.md)).
|
resilience is the lighter commitment (see [smp.md](smp.md) and [vision.md](../vision.md)).
|
||||||
Note the overlap, though: **preemptive scheduling** and **priorities** — already
|
Note the overlap, though: **preemptive scheduling** and **priorities** — already
|
||||||
built — serve resilience too (you can preempt and kill a misbehaving component, and
|
built — serve resilience too (you can preempt and kill a misbehaving component, and
|
||||||
run the supervisor at high priority). So danos keeps the useful *mechanisms* of the
|
run the supervisor at high priority). So danos keeps the useful *mechanisms* of the
|
||||||
@@ -156,10 +156,10 @@ real-time work without owing anyone a timing *guarantee*.
|
|||||||
|
|
||||||
## Related
|
## Related
|
||||||
|
|
||||||
- [vision.md](vision.md) — the goals this serves (learning by doing; resilience over
|
- [vision.md](../vision.md) — the goals this serves (learning by doing; resilience over
|
||||||
hard real-time).
|
hard real-time).
|
||||||
- [scheduling.md](scheduling.md) — preemption, which makes runaway components killable.
|
- [scheduling.md](scheduling.md) — preemption, which makes runaway components killable.
|
||||||
- [ipc.md](ipc.md) — channels that need a "peer died" outcome for clean restart.
|
- [ipc.md](../device-driver-development/ipc.md) — channels that need a "peer died" outcome for clean restart.
|
||||||
- [interrupts.md](interrupts.md) — fault reporting that user mode turns into "kill and
|
- [interrupts.md](interrupts.md) — fault reporting that user mode turns into "kill and
|
||||||
restart" instead of "halt".
|
restart" instead of "halt".
|
||||||
- [smp.md](smp.md) — the real-time-vs-resilience fork, in the SMP context.
|
- [smp.md](smp.md) — the real-time-vs-resilience fork, in the SMP context.
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
The scheduler turns danos from a linear "boot then halt" kernel into a **running
|
The scheduler turns danos from a linear "boot then halt" kernel into a **running
|
||||||
multitasking system**. It's **fixed-priority preemptive**: the highest-priority
|
multitasking system**. It's **fixed-priority preemptive**: the highest-priority
|
||||||
ready task always runs, and tasks at the same priority take turns. That model is
|
ready task always runs, and tasks at the same priority take turns. That model is
|
||||||
chosen for [real-time](vision.md) — it's predictable (you can reason about which
|
chosen for [real-time](../vision.md) — it's predictable (you can reason about which
|
||||||
task runs when) and its decisions are O(1), unlike a fair-share scheduler.
|
task runs when) and its decisions are O(1), unlike a fair-share scheduler.
|
||||||
|
|
||||||
The scheduler proper (`system/kernel/scheduler.zig`) is generic; the context switch and new-task
|
The scheduler proper (`system/kernel/scheduler.zig`) is generic; the context switch and new-task
|
||||||
@@ -37,7 +37,7 @@ down a return address pointing at `task_trampoline` and zeroed callee-saved slot
|
|||||||
`schedule()` — pick the best task and switch — runs from two places:
|
`schedule()` — pick the best task and switch — runs from two places:
|
||||||
|
|
||||||
- **`yield()`** — a task voluntarily gives up the CPU.
|
- **`yield()`** — a task voluntarily gives up the CPU.
|
||||||
- **`tick()`** — the 1000 Hz [timer](device-interrupts.md) preempts the running
|
- **`tick()`** — the 1000 Hz [timer](../device-driver-development/device-interrupts.md) preempts the running
|
||||||
task. This is what lets a task that never yields still share the CPU.
|
task. This is what lets a task that never yields still share the CPU.
|
||||||
|
|
||||||
The subtlety in mixing them is the **interrupt flag (IF)**. The rule: `switch_context`
|
The subtlety in mixing them is the **interrupt flag (IF)**. The rule: `switch_context`
|
||||||
@@ -97,7 +97,7 @@ marks the task blocked with a wake deadline and switches away. On every tick the
|
|||||||
timer wakes any task whose deadline has passed (a bounded scan, so it stays
|
timer wakes any task whose deadline has passed (a bounded scan, so it stays
|
||||||
deterministic), which makes it ready again; the scheduler then runs it when its
|
deterministic), which makes it ready again; the scheduler then runs it when its
|
||||||
priority comes up. `sleep` measures its deadline on the [calibrated
|
priority comes up. `sleep` measures its deadline on the [calibrated
|
||||||
clock](device-interrupts.md), so it's real time.
|
clock](../device-driver-development/device-interrupts.md), so it's real time.
|
||||||
|
|
||||||
When *every* task is blocked, something still has to run — so there's an **idle
|
When *every* task is blocked, something still has to run — so there's an **idle
|
||||||
task** at the lowest priority that just `hlt`s until the next interrupt (see
|
task** at the lowest priority that just `hlt`s until the next interrupt (see
|
||||||
@@ -111,7 +111,7 @@ The other form of blocking is waiting for an **event** rather than a duration. A
|
|||||||
the caller on it, `wake(wq)` moves the highest-priority waiter back to ready
|
the caller on it, `wake(wq)` moves the highest-priority waiter back to ready
|
||||||
(preempting if it now outranks the running task). A task links into a wait queue
|
(preempting if it now outranks the running task). A task links into a wait queue
|
||||||
through the same field the ready queues use — it's in exactly one queue at a time.
|
through the same field the ready queues use — it's in exactly one queue at a time.
|
||||||
These are the primitives locks, semaphores and [IPC](ipc.md) are built on.
|
These are the primitives locks, semaphores and [IPC](../device-driver-development/ipc.md) are built on.
|
||||||
|
|
||||||
Blocking safely needs **composable critical sections**. A blanket `cli`/`sti` pair
|
Blocking safely needs **composable critical sections**. A blanket `cli`/`sti` pair
|
||||||
doesn't nest: an IPC channel that `cli`s and then calls `wait` would have `wait`'s
|
doesn't nest: an IPC channel that `cli`s and then calls `wait` would have `wait`'s
|
||||||
@@ -124,7 +124,7 @@ caller's state.
|
|||||||
|
|
||||||
## Verifying it
|
## Verifying it
|
||||||
|
|
||||||
Three tests (see [testing.md](testing.md)) prove the guarantees:
|
Three tests (see [testing.md](../testing.md)) prove the guarantees:
|
||||||
|
|
||||||
- **`sched`** spawns three tasks that busy-loop *without ever yielding*. They all
|
- **`sched`** spawns three tasks that busy-loop *without ever yielding*. They all
|
||||||
make progress — which can only happen if the timer is **preempting** between them
|
make progress — which can only happen if the timer is **preempting** between them
|
||||||
@@ -140,7 +140,7 @@ Three tests (see [testing.md](testing.md)) prove the guarantees:
|
|||||||
|
|
||||||
- **Priority inheritance** — still open. Tasks now do block on shared resources
|
- **Priority inheritance** — still open. Tasks now do block on shared resources
|
||||||
(IPC rendezvous, the big kernel lock), and nothing yet bounds priority
|
(IPC rendezvous, the big kernel lock), and nothing yet bounds priority
|
||||||
inversion — a [real-time](vision.md) requirement.
|
inversion — a [real-time](../vision.md) requirement.
|
||||||
- **Task exit / a reaper** — done. A dying task goes on its core's reap list in a
|
- **Task exit / a reaper** — done. A dying task goes on its core's reap list in a
|
||||||
`.reaping` state; the timer tick drains the list, frees the stack back to the
|
`.reaping` state; the timer tick drains the list, frees the stack back to the
|
||||||
heap, and recycles the task-table slot.
|
heap, and recycles the task-table slot.
|
||||||
@@ -307,4 +307,4 @@ refcount, and no group-kill special case is needed at all.
|
|||||||
Then update [threading.md](threading.md) (the shared-fate gap note),
|
Then update [threading.md](threading.md) (the shared-fate gap note),
|
||||||
[process-lifecycle.md](process-lifecycle.md),
|
[process-lifecycle.md](process-lifecycle.md),
|
||||||
[process-management.md](process-management.md), and
|
[process-management.md](process-management.md), and
|
||||||
[ipc.md](ipc.md)/[drivers.md](drivers.md) mentions.
|
[ipc.md](../device-driver-development/ipc.md)/[drivers.md](../device-driver-development/drivers.md) mentions.
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
# SMEP and SMAP — supervisor-mode hardening
|
||||||
|
|
||||||
|
*Design, 2026-07-31. H1 (the copy layer), H2 (SMEP), HS (the SYSRET guard) and
|
||||||
|
H3 (SMAP) have all landed; the track is complete. Companion to
|
||||||
|
[protocol-namespace.md](protocol-namespace.md) on the security track — this is
|
||||||
|
the hardware half; that is the namespace half.*
|
||||||
|
|
||||||
|
Two CR4 bits that make the CPU refuse the two things a kernel should never do
|
||||||
|
with user memory:
|
||||||
|
|
||||||
|
- **SMEP** (Supervisor Mode Execution Prevention, CR4 bit 20): instruction
|
||||||
|
fetch in ring 0 from a page whose U/S bit says *user* → #PF. Kills the
|
||||||
|
classic ret2usr exploit shape — a kernel bug that redirects control flow
|
||||||
|
can no longer land in attacker-prepared user code.
|
||||||
|
- **SMAP** (Supervisor Mode Access Prevention, CR4 bit 21): data read/write
|
||||||
|
in ring 0 to a user page → #PF, unless `EFLAGS.AC` is set. `stac`/`clac`
|
||||||
|
open and close deliberate access windows; danos's design needs no windows
|
||||||
|
at all (below).
|
||||||
|
|
||||||
|
Detection is CPUID leaf 7, subleaf 0, EBX bit 7 (SMEP) and bit 20 (SMAP).
|
||||||
|
Both bits are per-core state: the BSP and every AP must set them.
|
||||||
|
|
||||||
|
## Why, in danos terms
|
||||||
|
|
||||||
|
Every syscall argument is an attacker-controlled integer, and several take
|
||||||
|
pointers. A kernel bug that dereferences a crafted pointer reads, writes, or
|
||||||
|
executes memory of the attacker's choosing — the exact bug class the
|
||||||
|
isolation tracks exist to prevent. SMEP/SMAP turn that class from "silent
|
||||||
|
compromise" into "immediate, attributable #PF with a kernel RIP in the log."
|
||||||
|
|
||||||
|
The second benefit matters as much as the first: **SMAP is a permanent
|
||||||
|
tripwire.** Once it is on, any *future* syscall that touches user memory
|
||||||
|
directly — instead of going through the checked copy layer — faults the
|
||||||
|
first time the QEMU suite runs it. The discipline stops depending on review.
|
||||||
|
|
||||||
|
## Where danos already stands
|
||||||
|
|
||||||
|
The design is closer than it looks, because the IPC layer was built right:
|
||||||
|
|
||||||
|
- **The copy layer is already SMAP-proof.** `copyAcross` and `copyFromUser`
|
||||||
|
(`system/kernel/ipc-synchronous.zig:305,333`) never dereference a user
|
||||||
|
virtual address: they walk the page tables and move bytes through the
|
||||||
|
physmap — kernel mappings throughout. SMAP cannot object.
|
||||||
|
- **Syscall entry already clears AC.** `SFMASK = 0x4_0700` clears IF, TF,
|
||||||
|
DF, **AC** on every `syscall`
|
||||||
|
(`system/kernel/architecture/x86_64/per-cpu.zig:76`). The syscall path is
|
||||||
|
SMAP-clean from day one.
|
||||||
|
- **The interrupt path is not.** Hardware does *not* clear AC on IDT
|
||||||
|
delivery, and ring 3 can set AC with `popfq` — so a hostile process could
|
||||||
|
take an interrupt with AC=1 and have the handler run with SMAP suspended.
|
||||||
|
`isr_common` (`system/kernel/architecture/x86_64/isr.s:366`) needs a
|
||||||
|
`clac` beside its `swapgs`.
|
||||||
|
- **CR4 today:** the BSP inherits firmware CR4 (no kernel write anywhere);
|
||||||
|
APs set PAE/OSFXSR/OSXMMEXCPT in `trampoline.s:62-68`. Neither path sets
|
||||||
|
SMEP/SMAP yet, and both must.
|
||||||
|
- **The stragglers.** Nine syscalls still dereference user pointers raw
|
||||||
|
after a bounds check — every one is a SMAP #PF waiting to happen, and
|
||||||
|
every one is *already* a latent kernel fault today (an unmapped-but-in-
|
||||||
|
range user page oopses the kernel instead of failing the call). The
|
||||||
|
verified sweep of `system/kernel/process.zig` (2026-07-31; a
|
||||||
|
whole-kernel `@ptrFromInt` audit found no user-address dereference
|
||||||
|
outside this file):
|
||||||
|
|
||||||
|
| Syscall | Raw access | Direction |
|
||||||
|
|---|---|---|
|
||||||
|
| `system_spawn` | name + argument blob (`:972`, `:980`) | read |
|
||||||
|
| `fs_resolve` | path in (`:1780`), result out (`:1797`) | read + write |
|
||||||
|
| `fs_mount` | prefix + rewrite strings (`:1864`, `:1865`) | read |
|
||||||
|
| `fs_unmount` | prefix string (`:1883`) | read |
|
||||||
|
| `fs_node` | read buffer out (`:1820`) | write |
|
||||||
|
| `debug_write` | message bytes (`:1700`; read twice — memcpy `:1710` and `log.append` `:1717`) | read |
|
||||||
|
| `klog_read` | log bytes out (`:1741`) | write |
|
||||||
|
| `klog_status` | status struct out (`:1758`) | write |
|
||||||
|
| `process_enumerate` | descriptor array out (`:1132`) | write |
|
||||||
|
| `device_enumerate` | descriptor array out (`:388`) | write |
|
||||||
|
|
||||||
|
For the write-direction rows the `@ptrFromInt` is in process.zig but the
|
||||||
|
stores happen in callees (`scheduler.enumerate`
|
||||||
|
`system/kernel/scheduler.zig:1209`, `devices_broker.enumerate`
|
||||||
|
`devices-broker.zig:136`, `log.readAt` `log.zig:209`, the vfs node calls
|
||||||
|
`vfs.zig:257/269/289`) — converting them means bounce buffers plus
|
||||||
|
`copyToUser` around those calls, not just editing the process.zig lines.
|
||||||
|
(Some paths already do it right — the futex word and the device-register
|
||||||
|
descriptor go through `copyFromUser` (`:1087`, `:924`). The write
|
||||||
|
direction has no public helper yet, but the mechanism exists:
|
||||||
|
`copyAcross` with a kernel source is exactly how IPC replies reach user
|
||||||
|
buffers, so `copyToUser` is a mechanical mirror.)
|
||||||
|
|
||||||
|
- **One known gap inside the copy layer itself:** the walk checks presence,
|
||||||
|
not the leaf U/S and writable bits (`ipc-synchronous.zig:20-22` flags
|
||||||
|
this). Today that is nearly moot — the user half contains only mappings
|
||||||
|
the kernel itself created for that process — but it must close before
|
||||||
|
shared or copy-on-write mappings exist, and closing it is part of making
|
||||||
|
the copy layer the single trusted door.
|
||||||
|
|
||||||
|
## The plan
|
||||||
|
|
||||||
|
**H1 — copy discipline (the real work).** A `user-memory` kernel module:
|
||||||
|
`copyFromUser` / `copyToUser` (the missing write direction) via the physmap
|
||||||
|
walk, with U/S and writable leaf checks closing the in-tree TODO. Convert
|
||||||
|
the nine stragglers. This fixes the latent unmapped-page kernel fault on
|
||||||
|
its own — it is worth doing even if SMEP/SMAP never shipped. QEMU suite
|
||||||
|
green; no behavior change visible to correct programs.
|
||||||
|
|
||||||
|
**H2 — SMEP.** A leaf-7 feature probe (the kernel has per-leaf `cpuid`
|
||||||
|
helpers in `apic.zig` to generalize); set CR4.SMEP during per-CPU bring-up
|
||||||
|
on BSP and APs — prefer the Zig-side per-CPU init over the trampoline
|
||||||
|
assembly, so one code path covers every core and the trampoline stays
|
||||||
|
minimal. Audit first that ring 0 never executes user-mapped pages: kernel
|
||||||
|
text lives in the kernel half, `jump_to_user` is kernel code, and the AP
|
||||||
|
trampoline page is kernel-mapped — expected clean, verify before flipping.
|
||||||
|
|
||||||
|
**H3 — SMAP.** Add `clac` at `isr_common` entry. `clac` is #UD on CPUs
|
||||||
|
without SMAP, so the instruction is a 3-byte NOP in the image, patched to
|
||||||
|
`clac` at boot when CPUID advertises SMAP (one-time patch beats a
|
||||||
|
conditional branch in the hottest path in the kernel). Then set CR4.SMAP in
|
||||||
|
the same per-CPU init. From this point the whole QEMU suite doubles as the
|
||||||
|
enforcement test: any missed raw dereference is a vector-14 with a kernel
|
||||||
|
RIP and a user CR2 — loud and attributable.
|
||||||
|
|
||||||
|
**H4 — keep it honest.** A line in the coding standards: kernel code
|
||||||
|
touches user memory only through `user-memory`; there is no `stac` anywhere
|
||||||
|
in the tree, and a PR that adds one is wrong by definition. SMAP enforces
|
||||||
|
the rule mechanically at test time.
|
||||||
|
|
||||||
|
Feature-gating follows the timekeeping rule (work on any VM, real Intel,
|
||||||
|
real AMD): both bits are probed, absence is logged and tolerated — like the
|
||||||
|
IOMMU's fail-open, the machine still boots, just unhardened. QEMU: TCG
|
||||||
|
implements both; KVM inherits the host (Intel Ivy Bridge+ for SMEP,
|
||||||
|
Broadwell+ for SMAP; AMD Zen+ for both). The test images should run with
|
||||||
|
`-cpu max` so the suite always exercises the enabled paths.
|
||||||
|
|
||||||
|
## Adjacent, deliberately separate
|
||||||
|
|
||||||
|
- **SYSRET canonical-RIP hardening** (`isr.s:192-194` documents it): a
|
||||||
|
non-canonical return RIP makes `sysretq` #GP *in ring 0* on Intel. Same
|
||||||
|
hardening bucket, independent fix (validate RCX before `sysretq`, fall
|
||||||
|
back to `iretq`), should ride the same branch as H2/H3 but is not
|
||||||
|
SMEP/SMAP.
|
||||||
|
**Status — landed 2026-08-01 (HS).** The syscall exit sign-extends the
|
||||||
|
return RIP from bit 47 (danos is 4-level only; nothing sets CR4.LA57) and
|
||||||
|
falls back to `iretq` when that changes it, counting each refusal for the
|
||||||
|
`sysret-canonical` case. Ring 3 could reach it: `syscall` as the last two
|
||||||
|
bytes of the last canonical page returns to `user_half_end`.
|
||||||
|
- **KPTI / Meltdown-class leaks are out of scope.** SMEP/SMAP police
|
||||||
|
architectural accesses, not speculative ones. danos runs one kernel
|
||||||
|
mapping in every address space and accepts that on affected hardware;
|
||||||
|
revisit only if the threat model ever includes hostile native code on
|
||||||
|
shared machines.
|
||||||
@@ -23,8 +23,8 @@ INIT–SIPI–SIPI, brings each up into 64-bit long mode with its own descriptor
|
|||||||
LAPIC and timer, and drops it into the scheduler. Tasks run **genuinely in parallel** —
|
LAPIC and timer, and drops it into the scheduler. Tasks run **genuinely in parallel** —
|
||||||
the `smp` self-test confirms worker tasks executing on all four cores at once under
|
the `smp` self-test confirms worker tasks executing on all four cores at once under
|
||||||
QEMU `-smp 4`. Shared kernel state (scheduler queues, IPC) is serialised behind a big
|
QEMU `-smp 4`. Shared kernel state (scheduler queues, IPC) is serialised behind a big
|
||||||
kernel lock. What's left is refinement, not first-light: per-core run queues, IPIs,
|
kernel lock. What's left is refinement, not first-light: per-core run queues and IPIs
|
||||||
and thread-to-core affinity (see [Implementation status](#implementation-status)).
|
(see [Implementation status](#implementation-status)).
|
||||||
|
|
||||||
## The common microkernel instinct: don't share kernel state
|
## The common microkernel instinct: don't share kernel state
|
||||||
|
|
||||||
@@ -112,7 +112,7 @@ Yes — and this is the branch that matters for danos right now.
|
|||||||
|
|
||||||
These pull in different directions, so **picking the primary goal comes before
|
These pull in different directions, so **picking the primary goal comes before
|
||||||
picking the SMP design.** (danos's founding assumption was real-time; that's under
|
picking the SMP design.** (danos's founding assumption was real-time; that's under
|
||||||
active reconsideration in favour of resilience — see [vision.md](vision.md).)
|
active reconsideration in favour of resilience — see [vision.md](../vision.md).)
|
||||||
|
|
||||||
## What this would mean for danos
|
## What this would mean for danos
|
||||||
|
|
||||||
@@ -169,7 +169,7 @@ next lands.
|
|||||||
the highest-priority ready task; per-core queues are a later optimisation.
|
the highest-priority ready task; per-core queues are a later optimisation.
|
||||||
- **AP wake to long mode** — `architecture.startSecondary` drives INIT–SIPI–SIPI (via the
|
- **AP wake to long mode** — `architecture.startSecondary` drives INIT–SIPI–SIPI (via the
|
||||||
LAPIC ICR) to wake each parked core one at a time. A woken core starts in 16-bit
|
LAPIC ICR) to wake each parked core one at a time. A woken core starts in 16-bit
|
||||||
real mode at a low page and runs the [trampoline](../system/kernel/architecture/x86_64/trampoline.s)
|
real mode at a low page and runs the [trampoline](../../system/kernel/architecture/x86_64/trampoline.s)
|
||||||
up through protected mode into 64-bit long mode, then lands in `smp.zig:apEntry`,
|
up through protected mode into 64-bit long mode, then lands in `smp.zig:apEntry`,
|
||||||
publishes its per-CPU pointer, and reports in. Verified in QEMU with `-smp 4`:
|
publishes its per-CPU pointer, and reports in. Verified in QEMU with `-smp 4`:
|
||||||
all four cores report `online`.
|
all four cores report `online`.
|
||||||
@@ -238,10 +238,12 @@ next lands.
|
|||||||
- **Per-core run queues** — the Fiasco.OC direction, if the single global queue's lock
|
- **Per-core run queues** — the Fiasco.OC direction, if the single global queue's lock
|
||||||
contention ever bites. (Thread *affinity* already exists — see above; this is the
|
contention ever bites. (Thread *affinity* already exists — see above; this is the
|
||||||
further step of giving each core its own primary run queue for load distribution.)
|
further step of giving each core its own primary run queue for load distribution.)
|
||||||
- **Fault recovery** — today a fault halts (only) the faulting core. Turning that into
|
- **Fault recovery** — a ring-3 fault already **kills the faulting process and keeps the
|
||||||
"kill the task, keep the core running" is the [resilience](resilience.md) track (it
|
core (and the rest of the system) running**: the kernel trapped it on the task's own
|
||||||
needs the task's lock/resource state handled), and for taking a core fully offline,
|
kernel stack, reclaims what the process held, and reschedules
|
||||||
its tasks migrated first.
|
(`process.killCurrentProcess`; the `fault-recovery` test proves init keeps heartbeating
|
||||||
|
through the kill) — the [resilience](resilience.md) track. What's still open here is
|
||||||
|
taking a core fully **offline**, which additionally needs its tasks migrated off first.
|
||||||
|
|
||||||
## Further reading
|
## Further reading
|
||||||
|
|
||||||
@@ -270,6 +272,6 @@ next lands.
|
|||||||
|
|
||||||
- [scheduling.md](scheduling.md) — the single-core scheduler SMP would extend.
|
- [scheduling.md](scheduling.md) — the single-core scheduler SMP would extend.
|
||||||
- [discovery.md](discovery.md) — enumerating cores is a device-discovery problem.
|
- [discovery.md](discovery.md) — enumerating cores is a device-discovery problem.
|
||||||
- [ipc.md](ipc.md) — the message passing cross-core coordination rides on.
|
- [ipc.md](../device-driver-development/ipc.md) — the message passing cross-core coordination rides on.
|
||||||
- [vision.md](vision.md) — the goals question (real-time vs resilience) this note
|
- [vision.md](../vision.md) — the goals question (real-time vs resilience) this note
|
||||||
keeps bumping into.
|
keeps bumping into.
|
||||||
@@ -51,7 +51,7 @@ Everything else---including`read()`,`write()`,`malloc()`, and`fork()`---will run
|
|||||||
3. **`Yield()`/`Thread_Ctrl()`**
|
3. **`Yield()`/`Thread_Ctrl()`**
|
||||||
- **What it does:**Allows a thread to voluntarily give up its CPU time slice, or allows a root task to spawn/kill threads.
|
- **What it does:**Allows a thread to voluntarily give up its CPU time slice, or allows a root task to spawn/kill threads.
|
||||||
4. **`ipc_send(endpoint, message_buffer)`(Asynchronous Send)**
|
4. **`ipc_send(endpoint, message_buffer)`(Asynchronous Send)**
|
||||||
- **What it does:**Posts a small payload to an endpoint's bounded queue and returns *without* blocking — no rendezvous, no reply. The receiver picks it up through the same `IPC_ReplyWait`, as a buffered message. It is the async counterpart of `IPC_Call`, for one-to-many broadcasts where a synchronous rendezvous would let one dead or slow receiver hang the sender. The [input service](input.md) — keyboard-event fan-out — is its first user. A full queue drops the oldest message (a buffered message is discrete data, unlike a coalescing interrupt notification).
|
- **What it does:**Posts a small payload to an endpoint's bounded queue and returns *without* blocking — no rendezvous, no reply. The receiver picks it up through the same `IPC_ReplyWait`, as a buffered message. It is the async counterpart of `IPC_Call`, for one-to-many broadcasts where a synchronous rendezvous would let one dead or slow receiver hang the sender. The [input service](../device-driver-development/input.md) — keyboard-event fan-out — is its first user. A full queue drops the oldest message (a buffered message is discrete data, unlike a coalescing interrupt notification).
|
||||||
|
|
||||||
* * * * *
|
* * * * *
|
||||||
|
|
||||||
@@ -92,4 +92,4 @@ Managing the Payload Challenge
|
|||||||
Because it is a microkernel, performance lives or dies by how fast your`IPC_Call`can move data from Client to Server. You have two minimal choices for handling the`message_buffer`pointer:[[1](https://anazimzada2020.medium.com/microkernel-architectural-pattern-5e4e9184170e)]
|
Because it is a microkernel, performance lives or dies by how fast your`IPC_Call`can move data from Client to Server. You have two minimal choices for handling the`message_buffer`pointer:[[1](https://anazimzada2020.medium.com/microkernel-architectural-pattern-5e4e9184170e)]
|
||||||
|
|
||||||
- **The Copy Method (Simplest to start):**Your kernel pauses the client, reads the data from the client's memory space, switches page tables to the server, and copies the data into the server's buffer.
|
- **The Copy Method (Simplest to start):**Your kernel pauses the client, reads the data from the client's memory space, switches page tables to the server, and copies the data into the server's buffer.
|
||||||
- **The Shared Memory Method (Fastest):**The kernel sets up a temporary, shared virtual memory page between the client and server. The client writes to it, calls`syscall`/`svc`, and the server reads it instantly without the kernel copying any bytes
|
- **The Shared Memory Method (Fastest):**The kernel sets up a temporary, shared virtual memory page between the client and server. The client writes to it, calls`syscall`/`svc`, and the server reads it instantly without the kernel copying any bytes
|
||||||
@@ -10,8 +10,8 @@ v2), written to disk ahead of time. The EFI loader reads it in a single
|
|||||||
sequential pass and hands the bytes to the kernel unmodified.
|
sequential pass and hands the bytes to the kernel unmodified.
|
||||||
|
|
||||||
The capsule is a *performance artifact*, not a source of truth. The boot
|
The capsule is a *performance artifact*, not a source of truth. The boot
|
||||||
volume's `/system` file tree remains the canonical layout (see
|
volume's `/system` and `/test` file trees remain the canonical layout (see
|
||||||
[danos-file-system-hierarchy-FSH.md](danos-file-system-hierarchy-FSH.md));
|
[file-system-hierarchy.md](../file-system-development/file-system-hierarchy.md));
|
||||||
the capsule is a pre-baked snapshot of the same binaries, derived from the same
|
the capsule is a pre-baked snapshot of the same binaries, derived from the same
|
||||||
build graph, so the running system is identical whether the loader read the
|
build graph, so the running system is identical whether the loader read the
|
||||||
capsule or walked the tree.
|
capsule or walked the tree.
|
||||||
@@ -36,11 +36,11 @@ so it need be no fancier. Little-endian throughout:
|
|||||||
|
|
||||||
```
|
```
|
||||||
Header magic: u32 = "DNR2" (0x32524E44), count: u32
|
Header magic: u32 = "DNR2" (0x32524E44), count: u32
|
||||||
Entry × count name: [64]u8 (NUL-padded FHS path), offset: u64, len: u64
|
Entry × count name: [64]u8 (NUL-padded hierarchy path), offset: u64, len: u64
|
||||||
blobs... each entry's file bytes, at its offset within the image
|
blobs... each entry's file bytes, at its offset within the image
|
||||||
```
|
```
|
||||||
|
|
||||||
- **Names are full FHS paths** (`/system/services/init`), not basenames — that
|
- **Names are full hierarchy paths** (`/system/services/init`), not basenames — that
|
||||||
is what "v2" means. The 64-byte capacity matches `abi.maximum_process_name`,
|
is what "v2" means. The 64-byte capacity matches `abi.maximum_process_name`,
|
||||||
so a task named after its binary path is never truncated. Paths longer than
|
so a task named after its binary path is never truncated. Paths longer than
|
||||||
63 bytes are a build error (`pack-system-image.py` rejects them).
|
63 bytes are a build error (`pack-system-image.py` rejects them).
|
||||||
@@ -54,13 +54,14 @@ blobs... each entry's file bytes, at its offset within the image
|
|||||||
|
|
||||||
## How it is built
|
## How it is built
|
||||||
|
|
||||||
`build.zig` maintains one `bundled` list — every user binary and its FHS home.
|
`build.zig` maintains one `bundled` list — every user binary and its hierarchy home.
|
||||||
Three artifacts are derived from that same list, in the same build graph, so
|
Three artifacts are derived from that same list, in the same build graph, so
|
||||||
they cannot drift apart:
|
they cannot drift apart:
|
||||||
|
|
||||||
1. **The tree**: each binary installed at its FHS path (`zig-out/system/...`,
|
1. **The tree**: each binary installed at its hierarchy path (`zig-out/system/...`
|
||||||
mirrored onto the FAT boot volume by `tools/make-fat-image.py`).
|
and `zig-out/test/...`, mirrored onto the FAT boot volume by
|
||||||
2. **The manifest** (`system/manifest`): the FHS path of every bundled binary,
|
`tools/make-fat-image.py`).
|
||||||
|
2. **The manifest** (`system/manifest`): the hierarchy path of every bundled binary,
|
||||||
one per line — the loader's per-file fallback input.
|
one per line — the loader's per-file fallback input.
|
||||||
3. **The capsule**: `tools/pack-system-image.py` packs the same binaries into
|
3. **The capsule**: `tools/pack-system-image.py` packs the same binaries into
|
||||||
the v2 container, installed at `zig-out/boot/system.img` and placed on the
|
the v2 container, installed at `zig-out/boot/system.img` and placed on the
|
||||||
@@ -81,7 +82,8 @@ same in-RAM ramdisk image:
|
|||||||
2. **The manifest** — read `system\manifest` and open each listed path *by
|
2. **The manifest** — read `system\manifest` and open each listed path *by
|
||||||
name*. FAT name lookup is case-insensitive and firmware-portable, unlike
|
name*. FAT name lookup is case-insensitive and firmware-portable, unlike
|
||||||
directory enumeration. The loader assembles the v2 image in RAM itself.
|
directory enumeration. The loader assembles the v2 image in RAM itself.
|
||||||
3. **The tree walk** — enumerate `/system` recursively. Last resort for
|
3. **The tree walk** — enumerate `/system` and `/test` recursively (`/test`
|
||||||
|
is optional: a stick without fixtures still boots). Last resort for
|
||||||
hand-assembled sticks with neither file: some firmware FAT drivers return
|
hand-assembled sticks with neither file: some firmware FAT drivers return
|
||||||
bare 8.3 names uppercase from enumeration, which is why this is the
|
bare 8.3 names uppercase from enumeration, which is why this is the
|
||||||
fallback and not the primary path.
|
fallback and not the primary path.
|
||||||
@@ -101,14 +103,15 @@ the kernel (`kernel.zig`) then publishes the same bytes twice, to two
|
|||||||
consumers:
|
consumers:
|
||||||
|
|
||||||
- **The process layer** (`process.zig`): `system_spawn` looks binaries up in
|
- **The process layer** (`process.zig`): `system_spawn` looks binaries up in
|
||||||
the ramdisk via `Reader.find` — exact FHS path, or unique basename for
|
the ramdisk via `Reader.find` — exact hierarchy path, or unique basename for
|
||||||
pre-path callers — and loads them as fresh ring-3 processes. The stored path
|
pre-path callers — and loads them as fresh ring-3 processes. The stored path
|
||||||
becomes the task's name.
|
becomes the task's name.
|
||||||
- **The VFS root** (`vfs.zig`, `setInitialRamdisk`): the image is mounted as
|
- **The VFS root** (`vfs.zig`, `setInitialRamdisk`): the image is mounted as
|
||||||
the kernel-backed, read-only `/system` mount. Directory nodes are derived
|
kernel-backed, read-only mounts — one per top-level tree named by the entry
|
||||||
from the entry paths (the unique parents), so `/system` is listable and its
|
paths, so `/system` and, when the fixtures are bundled, `/test`. Directory
|
||||||
files readable over the normal VFS protocol — the FHS boot tree every
|
nodes are derived from the entry paths (the unique parents), so the trees
|
||||||
process sees comes straight out of the capsule bytes.
|
are listable and their files readable over the normal VFS protocol — the
|
||||||
|
boot tree every process sees comes straight out of the capsule bytes.
|
||||||
|
|
||||||
The image is never copied after the handoff and never mutated: the initrd is
|
The image is never copied after the handoff and never mutated: the initrd is
|
||||||
immutable, which is what makes the VFS's node serving lock-free.
|
immutable, which is what makes the VFS's node serving lock-free.
|
||||||
@@ -59,9 +59,9 @@ danos's two binaries default to different conventions:
|
|||||||
When the loader jumps to the kernel passing the `BootInformation` pointer, both sides have
|
When the loader jumps to the kernel passing the `BootInformation` pointer, both sides have
|
||||||
to agree *which register that pointer lands in*. Left to their defaults, the loader
|
to agree *which register that pointer lands in*. Left to their defaults, the loader
|
||||||
would place it in RCX while the kernel looked in RDI — and the kernel would read
|
would place it in RCX while the kernel looked in RDI — and the kernel would read
|
||||||
garbage. So both sides reference the same `system.kernel_abi` (SysV): the loader's
|
garbage. So both sides reference the same `boot_handoff.kernel_abi` (SysV): the loader's
|
||||||
function-pointer type and the kernel's `_start` both carry
|
function-pointer type and the kernel's `_start` both carry
|
||||||
`callconv(system.kernel_abi)`, and the pointer reliably arrives in RDI. That is the
|
`callconv(boot_handoff.kernel_abi)`, and the pointer reliably arrives in RDI. That is the
|
||||||
whole reason `kernel_abi` lives in the shared contract — see [efi.md](efi.md) for
|
whole reason `kernel_abi` lives in the shared contract — see [efi.md](efi.md) for
|
||||||
the handoff it governs.
|
the handoff it governs.
|
||||||
|
|
||||||
@@ -90,9 +90,9 @@ process) instead of silently corrupting the image
|
|||||||
(`buildEntryStack` in `system/kernel/process.zig`); `argv[0]` is always the path
|
(`buildEntryStack` in `system/kernel/process.zig`); `argv[0]` is always the path
|
||||||
or initial-ramdisk name the process was spawned as, and `system_spawn`'s optional
|
or initial-ramdisk name the process was spawned as, and `system_spawn`'s optional
|
||||||
argument blob becomes `argv[1..]`. The runtime's `_start`
|
argument blob becomes `argv[1..]`. The runtime's `_start`
|
||||||
(`library/runtime/start.zig`) hands the block to `rt_start`, which builds a
|
(`library/kernel/start.zig`) hands the block to `rt_start`, which builds a
|
||||||
`runtime.process.Init` from it and passes that to the program's `main`
|
`process.Init` from it and passes that to the program's `main`
|
||||||
(`pub fn main(init: runtime.process.Init)`; a parameterless `main()` is also
|
(`pub fn main(init: process.Init)`; a parameterless `main()` is also
|
||||||
accepted). A C runtime's `crt0` would walk
|
accepted). A C runtime's `crt0` would walk
|
||||||
the identical layout unmodified — that's the compatibility being bought. The
|
the identical layout unmodified — that's the compatibility being bought. The
|
||||||
`args` test proves the round trip.
|
`args` test proves the round trip.
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
The ordered, checkpointable build-out for [threading.md](threading.md). Each milestone
|
The ordered, checkpointable build-out for [threading.md](threading.md). Each milestone
|
||||||
lands on its own and ends in a **verifiable gate** — shaped for a `/loop` run, like
|
lands on its own and ends in a **verifiable gate** — shaped for a `/loop` run, like
|
||||||
[display-v2-plan.md](display-v2-plan.md). Read threading.md first for the *why*.
|
[display-v2-plan.md](../device-driver-development/display-v2-plan.md). Read threading.md first for the *why*.
|
||||||
|
|
||||||
## Locked decisions (do not relitigate)
|
## Locked decisions (do not relitigate)
|
||||||
|
|
||||||
@@ -13,7 +13,7 @@ lands on its own and ends in a **verifiable gate** — shaped for a `/loop` run,
|
|||||||
`single_threaded = false`.
|
`single_threaded = false`.
|
||||||
- **Blocking is futex-backed, never spin-backed** — waiters park in the kernel so an
|
- **Blocking is futex-backed, never spin-backed** — waiters park in the kernel so an
|
||||||
idle core still halts ([halting.md](halting.md)).
|
idle core still halts ([halting.md](halting.md)).
|
||||||
- **New syscalls are private**: extend [abi.zig](../system/abi.zig) `SystemCall` after
|
- **New syscalls are private**: extend [abi.zig](../../system/abi.zig) `SystemCall` after
|
||||||
`shared_memory_physical = 36` (`thread_spawn = 37`, `thread_exit = 38`, `current_core = 39`,
|
`shared_memory_physical = 36` (`thread_spawn = 37`, `thread_exit = 38`, `current_core = 39`,
|
||||||
`futex_wait = 40`, `futex_wake = 41`) + a `library/runtime` wrapper; user code never names a number.
|
`futex_wait = 40`, `futex_wake = 41`) + a `library/runtime` wrapper; user code never names a number.
|
||||||
- **Restart granularity stays the process** — a faulting thread kills its process; the
|
- **Restart granularity stays the process** — a faulting thread kills its process; the
|
||||||
@@ -21,12 +21,13 @@ lands on its own and ends in a **verifiable gate** — shaped for a `/loop` run,
|
|||||||
|
|
||||||
## Conventions
|
## Conventions
|
||||||
|
|
||||||
Follow [coding-standards.md](coding-standards.md): spell out non-acronym abbreviations,
|
Follow [coding-standards.md](../coding-standards.md): spell out non-acronym abbreviations,
|
||||||
kebab-case file names, no `Co-Authored-By` trailers. New user binaries go through
|
kebab-case file names, no `Co-Authored-By` trailers. New user binaries are
|
||||||
`addUserBinary` (with the new `threaded` flag where a binary spawns threads) and get
|
packages whose build.zig calls `build_support.userBinary` (with `.threaded =
|
||||||
packed into the initial-ramdisk; new syscalls extend [abi.zig](../system/abi.zig)
|
true` where a binary spawns threads) and get packed into the initial-ramdisk;
|
||||||
`SystemCall` + a `library/runtime` wrapper; test services live beside the code they
|
new syscalls extend [abi.zig](../../system/abi.zig) `SystemCall` + a
|
||||||
exercise and register a `ServiceId` if they must be looked up.
|
`library/kernel` wrapper; test services live beside the code they exercise and
|
||||||
|
bind a `/protocol/test/...` name if they must be reachable.
|
||||||
|
|
||||||
## How to verify along the way
|
## How to verify along the way
|
||||||
|
|
||||||
@@ -58,7 +59,7 @@ fixed in *Locked decisions*; the checkboxes are the only state. A loop iteration
|
|||||||
5) so progress is backed up remotely; **do not push `main`** — merging Phase 2 into
|
5) so progress is backed up remotely; **do not push `main`** — merging Phase 2 into
|
||||||
`main` stays a human step.
|
`main` stays a human step.
|
||||||
3. **Implement** every unchecked item in that milestone, including adding its
|
3. **Implement** every unchecked item in that milestone, including adding its
|
||||||
`-Dtest-case` to `CASES` in [test/qemu_test.py](../test/qemu_test.py) (with
|
`-Dtest-case` to `CASES` in [test/qemu_test.py](../../test/qemu_test.py) (with
|
||||||
`smp: true` / a `mem` bump where noted) so the gate is runnable.
|
`smp: true` / a `mem` bump where noted) so the gate is runnable.
|
||||||
4. **Run the gate**: `python3 test/qemu_test.py <case>`, then the full **guardrail
|
4. **Run the gate**: `python3 test/qemu_test.py <case>`, then the full **guardrail
|
||||||
set**, then `zig build` (clean) and `zig build test` (green).
|
set**, then `zig build` (clean) and `zig build test` (green).
|
||||||
@@ -67,7 +68,7 @@ fixed in *Locked decisions*; the checkboxes are the only state. A loop iteration
|
|||||||
the whole guardrail set passes, `zig build` is clean, and host tests are green.
|
the whole guardrail set passes, `zig build` is clean, and host tests are green.
|
||||||
→ tick this milestone's boxes **and** its `**Gate:**`-referenced case, `git commit`
|
→ tick this milestone's boxes **and** its `**Gate:**`-referenced case, `git commit`
|
||||||
(`threads(M<n>): <summary>`, no `Co-Authored-By` trailer per
|
(`threads(M<n>): <summary>`, no `Co-Authored-By` trailer per
|
||||||
[coding-standards.md](coding-standards.md)), then **`git push` the working branch to
|
[coding-standards.md](../coding-standards.md)), then **`git push` the working branch to
|
||||||
`origin`** (use `-u` on the first push to set upstream). Continue to the next
|
`origin`** (use `-u` on the first push to set upstream). Continue to the next
|
||||||
milestone in the same iteration if budget remains; otherwise let the loop re-fire.
|
milestone in the same iteration if budget remains; otherwise let the loop re-fire.
|
||||||
- **Red** = anything above fails. Diagnose from the captured serial log
|
- **Red** = anything above fails. Diagnose from the captured serial log
|
||||||
@@ -111,7 +112,7 @@ task's exit; make destruction happen on the **last** exit.
|
|||||||
- [x] A refcount keyed by the address-space root, held in `scheduler.zig`
|
- [x] A refcount keyed by the address-space root, held in `scheduler.zig`
|
||||||
(`address_space_refs`): `retainAddressSpace` takes a reference in `spawnUserLocked` (on the
|
(`address_space_refs`): `retainAddressSpace` takes a reference in `spawnUserLocked` (on the
|
||||||
success path, after the slot + stack are secured), all under the big kernel lock.
|
success path, after the slot + stack are secured), all under the big kernel lock.
|
||||||
- [x] Both task-teardown paths ([scheduler.zig](../system/kernel/scheduler.zig):
|
- [x] Both task-teardown paths ([scheduler.zig](../../system/kernel/scheduler.zig):
|
||||||
`exitUserLocked` and `destroyTaskLocked`) call `releaseAddressSpace`, which decrements
|
`exitUserLocked` and `destroyTaskLocked`) call `releaseAddressSpace`, which decrements
|
||||||
and only `destroyAddressSpace`s at **zero**; an unretained space (hand-built test
|
and only `destroyAddressSpace`s at **zero**; an unretained space (hand-built test
|
||||||
spaces) is destroyed directly, preserving prior behaviour.
|
spaces) is destroyed directly, preserving prior behaviour.
|
||||||
@@ -133,7 +134,7 @@ full guardrail set passes unchanged — 13/13 (`smoke`, `sched`, `priority`, `sm
|
|||||||
Spawn only — no join yet. Prove a second task executes in the **caller's** address
|
Spawn only — no join yet. Prove a second task executes in the **caller's** address
|
||||||
space and exits cleanly.
|
space and exits cleanly.
|
||||||
|
|
||||||
- [x] [abi.zig](../system/abi.zig): `thread_spawn = 37`, `thread_exit = 38`. Handlers in
|
- [x] [abi.zig](../../system/abi.zig): `thread_spawn = 37`, `thread_exit = 38`. Handlers in
|
||||||
process.zig; `thread_spawn` calls `scheduler.spawnThread` (today, after M3, the
|
process.zig; `thread_spawn` calls `scheduler.spawnThread` (today, after M3, the
|
||||||
handler goes `spawnThreadSupervised` → `scheduler.spawnUserLocked`; shares the caller's
|
handler goes `spawnThreadSupervised` → `scheduler.spawnUserLocked`; shares the caller's
|
||||||
address space, `retainAddressSpace`); `thread_exit` ends the task like a process `exit(0)`
|
address space, `retainAddressSpace`); `thread_exit` ends the task like a process `exit(0)`
|
||||||
@@ -195,7 +196,7 @@ plus `address-space-refcount`/`thread-spawn`; `zig build` clean, `zig build test
|
|||||||
|
|
||||||
## M4 — Futex: the one blocking primitive ✅
|
## M4 — Futex: the one blocking primitive ✅
|
||||||
|
|
||||||
- [x] [abi.zig](../system/abi.zig): `futex_wait = 40`, `futex_wake = 41`. A waiter is a
|
- [x] [abi.zig](../../system/abi.zig): `futex_wait = 40`, `futex_wake = 41`. A waiter is a
|
||||||
`.blocked` task tagged with `Task.futex_addr` (no queue linkage);
|
`.blocked` task tagged with `Task.futex_addr` (no queue linkage);
|
||||||
`futex_wait(addr, expected, timeout_ns)` reads the user word under the big lock,
|
`futex_wait(addr, expected, timeout_ns)` reads the user word under the big lock,
|
||||||
parks iff `*addr == expected`, and returns on wake or timeout; `futex_wake(addr,
|
parks iff `*addr == expected`, and returns on wake or timeout; `futex_wake(addr,
|
||||||
@@ -261,7 +262,7 @@ green.
|
|||||||
restores it.
|
restores it.
|
||||||
- [x] `RwLock` / `WaitGroup` deferred (no consumer yet); they slot onto the same
|
- [x] `RwLock` / `WaitGroup` deferred (no consumer yet); they slot onto the same
|
||||||
`Futex`/`Mutex`/`Condition` when wanted.
|
`Futex`/`Mutex`/`Condition` when wanted.
|
||||||
- [x] All `thread-*` cases wired into [test/qemu_test.py](../test/qemu_test.py)
|
- [x] All `thread-*` cases wired into [test/qemu_test.py](../../test/qemu_test.py)
|
||||||
(`thread-spawn`/`-join`/`-futex`/`-mutex`/`-id`); threading.md + docs/README.md
|
(`thread-spawn`/`-join`/`-futex`/`-mutex`/`-id`); threading.md + docs/README.md
|
||||||
status updated to **built**; the worked example is threading.md's win-condition.
|
status updated to **built**; the worked example is threading.md's win-condition.
|
||||||
- [x] `-Dtest-case=thread-id` (`smp: 4`): two workers read `getCurrentId`; the main
|
- [x] `-Dtest-case=thread-id` (`smp: 4`): two workers read `getCurrentId`; the main
|
||||||
@@ -405,7 +406,7 @@ guardrail 26/26 (incl. `process-kill`, `supervision`, `fault-recovery`, `task-re
|
|||||||
### M10 — Per-thread TLS: the thread-pointer mechanism ✅
|
### M10 — Per-thread TLS: the thread-pointer mechanism ✅
|
||||||
|
|
||||||
Give each thread its own thread pointer and private TLS storage — the foundation
|
Give each thread its own thread pointer and private TLS storage — the foundation
|
||||||
self-hosting Zig ([zig-self-hosting.md](zig-self-hosting.md)) will build `threadlocal` on.
|
self-hosting Zig ([zig-self-hosting.md](../zig-self-hosting.md)) will build `threadlocal` on.
|
||||||
|
|
||||||
- [x] **Kernel** stores `thread_pointer` on `Task` and restores it on every context switch
|
- [x] **Kernel** stores `thread_pointer` on `Task` and restores it on every context switch
|
||||||
**only when it changes** (the same conditional-load discipline as CR3;
|
**only when it changes** (the same conditional-load discipline as CR3;
|
||||||
@@ -459,7 +460,7 @@ clean.
|
|||||||
## Deferred (explicitly not in this plan)
|
## Deferred (explicitly not in this plan)
|
||||||
|
|
||||||
- **Cross-process shared-memory futex** — the `(address_space, virtual_address)` key can become a
|
- **Cross-process shared-memory futex** — the `(address_space, virtual_address)` key can become a
|
||||||
physical-address key so two processes share a futex through a [shared-memory](display-v2.md)
|
physical-address key so two processes share a futex through a [shared-memory](../device-driver-development/display-v2.md)
|
||||||
region. Not needed for intra-process threads.
|
region. Not needed for intra-process threads.
|
||||||
- **Per-thread priorities / affinity distinct from the process** — threads inherit the
|
- **Per-thread priorities / affinity distinct from the process** — threads inherit the
|
||||||
process priority ([scheduling.md](scheduling.md)); revisit only if it earns its keep.
|
process priority ([scheduling.md](scheduling.md)); revisit only if it earns its keep.
|
||||||
@@ -467,5 +468,5 @@ clean.
|
|||||||
([process-lifecycle.md](process-lifecycle.md)).
|
([process-lifecycle.md](process-lifecycle.md)).
|
||||||
- **A `pthread`/POSIX surface** — the API is `std.Thread`-shaped Zig, nothing more.
|
- **A `pthread`/POSIX surface** — the API is `std.Thread`-shaped Zig, nothing more.
|
||||||
- **A real `std.Thread` backend** — arrives with self-hosting
|
- **A real `std.Thread` backend** — arrives with self-hosting
|
||||||
([zig-self-hosting.md](zig-self-hosting.md)); it sits on these same primitives, so it
|
([zig-self-hosting.md](../zig-self-hosting.md)); it sits on these same primitives, so it
|
||||||
swaps the impl under `runtime.Thread`, not the call sites.
|
swaps the impl under `runtime.Thread`, not the call sites.
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
# Threading: `runtime.Thread`, a std-shaped API over a private thread ABI
|
# Threading: `Thread`, a std-shaped API over a private thread ABI
|
||||||
|
|
||||||
A note on danos **threads** — several tasks sharing one address space — provided by a
|
A note on danos **threads** — several tasks sharing one address space — provided by a
|
||||||
`runtime.Thread` type that mirrors the shape of Zig's `std.Thread` while keeping every
|
`Thread` type that mirrors the shape of Zig's `std.Thread` while keeping every
|
||||||
kernel entry behind the [runtime](../library/runtime). **Built** (M1–M11, see
|
kernel entry behind the [runtime](../../library/kernel). **Built** (M1–M11, see
|
||||||
[threading-plan.md](threading-plan.md)): `spawn`/`join`/`detach`, cross-core parallelism,
|
[threading-plan.md](threading-plan.md)): `spawn`/`join`/`detach`, cross-core parallelism,
|
||||||
a futex, `Mutex`/`Condition`/`Semaphore`/`RwLock`/`WaitGroup`, `getCurrentId`/`currentCore`,
|
a futex, `Mutex`/`Condition`/`Semaphore`/`RwLock`/`WaitGroup`, `getCurrentId`/`currentCore`,
|
||||||
per-thread thread-pointer TLS, thread-safe allocation, and a task reaper that reclaims dead
|
per-thread thread-pointer TLS, thread-safe allocation, and a task reaper that reclaims dead
|
||||||
@@ -17,13 +17,13 @@ treat upstream shapes as "0.16.x."
|
|||||||
A danos service can write
|
A danos service can write
|
||||||
|
|
||||||
```zig
|
```zig
|
||||||
const t = try runtime.Thread.spawn(.{}, worker, .{ctx});
|
const t = try Thread.spawn(.{}, worker, .{ctx});
|
||||||
// ... do other work concurrently ...
|
// ... do other work concurrently ...
|
||||||
t.join();
|
t.join();
|
||||||
```
|
```
|
||||||
|
|
||||||
and get real parallelism across cores — with `runtime.Thread.Mutex`,
|
and get real parallelism across cores — with `Thread.Mutex`,
|
||||||
`runtime.Thread.Condition`, and `runtime.Thread.Semaphore` available for
|
`Thread.Condition`, and `Thread.Semaphore` available for
|
||||||
coordination — **without any code path reaching the kernel except through the
|
coordination — **without any code path reaching the kernel except through the
|
||||||
runtime**. The call sites read exactly like `std.Thread`, so the day danos becomes a
|
runtime**. The call sites read exactly like `std.Thread`, so the day danos becomes a
|
||||||
real Zig target (see [self-hosting](#the-self-hosting-endgame)) we swap the
|
real Zig target (see [self-hosting](#the-self-hosting-endgame)) we swap the
|
||||||
@@ -31,18 +31,18 @@ implementation underneath, not the API above.
|
|||||||
|
|
||||||
## Locked decisions (do not relitigate)
|
## Locked decisions (do not relitigate)
|
||||||
|
|
||||||
- **We build `runtime.Thread`, not literal `std.Thread`.** It mirrors std's *API and
|
- **We build `Thread`, not literal `std.Thread`.** It mirrors std's *API and
|
||||||
features*; the implementation underneath is danos-native. See
|
features*; the implementation underneath is danos-native. See
|
||||||
[Why not literal std.Thread](#why-not-literal-stdthread).
|
[Why not literal std.Thread](#why-not-literal-stdthread).
|
||||||
- **Threads are a narrow, opt-in capability — not the default concurrency tool.** The
|
- **Threads are a narrow, opt-in capability — not the default concurrency tool.** The
|
||||||
default for resilience stays **process + IPC** ([resilience.md](resilience.md),
|
default for resilience stays **process + IPC** ([resilience.md](resilience.md),
|
||||||
[ipc.md](ipc.md)). See [Where threads fit](#where-threads-fit-the-resilience-tension).
|
[ipc.md](../device-driver-development/ipc.md)). See [Where threads fit](#where-threads-fit-the-resilience-tension).
|
||||||
- **Blocking synchronization is futex-backed, never spin-backed.** Waiters sleep in
|
- **Blocking synchronization is futex-backed, never spin-backed.** Waiters sleep in
|
||||||
the kernel so an idle core still halts ([halting.md](halting.md)).
|
the kernel so an idle core still halts ([halting.md](halting.md)).
|
||||||
- **Per-binary opt-in to multi-threaded codegen.** Only a service that asks for
|
- **Per-binary opt-in to multi-threaded codegen.** Only a service that asks for
|
||||||
threads is built `single_threaded = false`; the rest stay lean and single-threaded.
|
threads is built `single_threaded = false`; the rest stay lean and single-threaded.
|
||||||
- **The thread ABI is private.** New syscalls extend [abi.zig](../system/abi.zig)
|
- **The thread ABI is private.** New syscalls extend [abi.zig](../../system/abi.zig)
|
||||||
`SystemCall` and are reached only through `library/runtime` wrappers, exactly like
|
`SystemCall` and are reached only through `library/kernel` wrappers, exactly like
|
||||||
every other danos syscall ([syscall.md](syscall.md)) — numbers stay renumberable.
|
every other danos syscall ([syscall.md](syscall.md)) — numbers stay renumberable.
|
||||||
|
|
||||||
## Why not literal `std.Thread`
|
## Why not literal `std.Thread`
|
||||||
@@ -56,14 +56,15 @@ runtime — rebuilt in lockstep — knows the mapping.
|
|||||||
`std.Thread` is incompatible with that invariant on two counts:
|
`std.Thread` is incompatible with that invariant on two counts:
|
||||||
|
|
||||||
1. **It selects its backend from `builtin.os.tag`, and issues syscalls directly.**
|
1. **It selects its backend from `builtin.os.tag`, and issues syscalls directly.**
|
||||||
danos targets `.os_tag = .freestanding` ([build.zig](../build.zig)), for which
|
danos targets `.os_tag = .freestanding` ([build.zig](../../build.zig)), for which
|
||||||
`std.Thread` resolves to an unsupported stub that `@compileError`s. Adding a real
|
`std.Thread` resolves to an unsupported stub that `@compileError`s. Adding a real
|
||||||
backend would either bake danos syscall numbers into std (breaking ABI privacy and
|
backend would either bake danos syscall numbers into std (breaking ABI privacy and
|
||||||
renumbering) or fork std to route back through the runtime — a permanent rebase
|
renumbering) or fork std to route back through the runtime — a permanent rebase
|
||||||
cost that buys nothing the native type doesn't.
|
cost that buys nothing the native type doesn't.
|
||||||
2. **Our user binaries are built `single_threaded = true`** ([build.zig](../build.zig)
|
2. **Our user binaries are built `single_threaded = true`** (the shared recipe in
|
||||||
`addUserBinary`), which compiles threading out entirely and makes atomics and TLS
|
[build-support/build.zig](../../build-support/build.zig)), which compiles threading
|
||||||
single-threaded. Threads need this flipped per binary regardless.
|
out entirely and makes atomics and TLS single-threaded. Threads need this flipped
|
||||||
|
per binary regardless.
|
||||||
|
|
||||||
So we take the *shape* of `std.Thread`, not the *type*. The cost of replicating the
|
So we take the *shape* of `std.Thread`, not the *type*. The cost of replicating the
|
||||||
surface (spawn/join/Mutex/Condition) is small; the cost of the std type is the ABI
|
surface (spawn/join/Mutex/Condition) is small; the cost of the std type is the ABI
|
||||||
@@ -83,7 +84,7 @@ address space. Threads deliberately remove that boundary *within* a process:
|
|||||||
there is no isolation **between** threads.
|
there is no isolation **between** threads.
|
||||||
- Threads share fate — by contract: a fault in any thread, or a "kill the process"
|
- Threads share fate — by contract: a fault in any thread, or a "kill the process"
|
||||||
decision, takes down **all** of them, so restartability lives at the process level,
|
decision, takes down **all** of them, so restartability lives at the process level,
|
||||||
not the thread level. (The kernel does not yet enforce this fan-out — see the
|
not the thread level. (The kernel enforces this fan-out — see the
|
||||||
Lifecycle note under
|
Lifecycle note under
|
||||||
[Interaction with the rest of the kernel](#interaction-with-the-rest-of-the-kernel).)
|
[Interaction with the rest of the kernel](#interaction-with-the-rest-of-the-kernel).)
|
||||||
- Shared mutable state reintroduces data races — the failure class the
|
- Shared mutable state reintroduces data races — the failure class the
|
||||||
@@ -99,7 +100,7 @@ processes. The isolation boundary stays at process granularity.
|
|||||||
|
|
||||||
## The API surface (mirrors `std.Thread`)
|
## The API surface (mirrors `std.Thread`)
|
||||||
|
|
||||||
Lives in `library/runtime/thread.zig`, re-exported as `runtime.Thread`.
|
Lives in `library/kernel/thread.zig`, re-exported as `Thread`.
|
||||||
|
|
||||||
```zig
|
```zig
|
||||||
pub const Thread = struct {
|
pub const Thread = struct {
|
||||||
@@ -129,14 +130,14 @@ Deviations from `std.Thread`, called out honestly:
|
|||||||
`void`). Return data through shared state or a `Semaphore`/`Condition`, not the
|
`void`). Return data through shared state or a `Semaphore`/`Condition`, not the
|
||||||
return.
|
return.
|
||||||
- No `getCpuCount()` (a service rarely needs it) and no `Thread.yield()` — `yield`
|
- No `getCpuCount()` (a service rarely needs it) and no `Thread.yield()` — `yield`
|
||||||
lives in `runtime.system`. Instead `currentCore()` exposes the calling core's dense
|
lives in the `process` module. Instead `currentCore()` exposes the calling core's dense
|
||||||
index ([smp.md](smp.md)), used to observe genuine cross-core parallelism.
|
index ([smp.md](smp.md)), used to observe genuine cross-core parallelism.
|
||||||
|
|
||||||
## Kernel primitives (new private syscalls)
|
## Kernel primitives (new private syscalls)
|
||||||
|
|
||||||
Five core entries extend [abi.zig](../system/abi.zig) `SystemCall` after
|
Five core entries extend [abi.zig](../../system/abi.zig) `SystemCall` after
|
||||||
`shared_memory_physical = 36` (plus small helpers `current_core`, `thread_self`, and
|
`shared_memory_physical = 36` (plus small helpers `current_core`, `thread_self`, and
|
||||||
`set_thread_pointer`), each with a `library/runtime` wrapper:
|
`set_thread_pointer`), each with a `library/kernel` wrapper:
|
||||||
|
|
||||||
| Syscall | Signature | Purpose |
|
| Syscall | Signature | Purpose |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
@@ -155,12 +156,12 @@ Plus one invariant change with no new syscall: **address-space reference countin
|
|||||||
Before this work an address space was 1:1 with a task: `spawnUserLocked` records
|
Before this work an address space was 1:1 with a task: `spawnUserLocked` records
|
||||||
`address_space` on the Task (as it still does), and teardown did
|
`address_space` on the Task (as it still does), and teardown did
|
||||||
`destroyAddressSpace(t.address_space)` when **any** user task exited
|
`destroyAddressSpace(t.address_space)` when **any** user task exited
|
||||||
([scheduler.zig](../system/kernel/scheduler.zig)). With threads, several tasks share
|
([scheduler.zig](../../system/kernel/scheduler.zig)). With threads, several tasks share
|
||||||
one `address_space`, so the first to exit would rip the address space out from under its
|
one `address_space`, so the first to exit would rip the address space out from under its
|
||||||
siblings.
|
siblings.
|
||||||
|
|
||||||
Fix: a small refcount keyed by the address-space root, kept in
|
Fix: a small refcount keyed by the address-space root, kept in
|
||||||
[scheduler.zig](../system/kernel/scheduler.zig): `retainAddressSpace` takes a
|
[scheduler.zig](../../system/kernel/scheduler.zig): `retainAddressSpace` takes a
|
||||||
reference for every user task `spawnUserLocked` starts (count 1 on the first take, so
|
reference for every user task `spawnUserLocked` starts (count 1 on the first take, so
|
||||||
a thread sharing the caller's space increments it); task teardown calls
|
a thread sharing the caller's space increments it); task teardown calls
|
||||||
`releaseAddressSpace`, which only calls `destroyAddressSpace` at **zero**. All of
|
`releaseAddressSpace`, which only calls `destroyAddressSpace` at **zero**. All of
|
||||||
@@ -172,7 +173,7 @@ that must land and be proven before anything shares an address space.
|
|||||||
The scheduler already accepts an arbitrary `address_space` and does **not** smuggle
|
The scheduler already accepts an arbitrary `address_space` and does **not** smuggle
|
||||||
values through scratch registers — `startUserTask` reads the entry/stack (and the
|
values through scratch registers — `startUserTask` reads the entry/stack (and the
|
||||||
thread's closure arg, delivered in `rdi` via `jumpToUserArg`) from the Task
|
thread's closure arg, delivered in `rdi` via `jumpToUserArg`) from the Task
|
||||||
([scheduler.zig](../system/kernel/scheduler.zig)). That makes the thread path clean:
|
([scheduler.zig](../../system/kernel/scheduler.zig)). That makes the thread path clean:
|
||||||
|
|
||||||
1. The runtime's `spawn` `mmap`s a stack (syscall `4`) and writes the closure —
|
1. The runtime's `spawn` `mmap`s a stack (syscall `4`) and writes the closure —
|
||||||
`{ tls_base, args }`, the std "Instance" pattern — at the **top of the new stack
|
`{ tls_base, args }`, the std "Instance" pattern — at the **top of the new stack
|
||||||
@@ -214,7 +215,7 @@ Keying: threads share an address space, so a **virtual address within that addre
|
|||||||
identifies a futex uniquely; the kernel keys its wait queue by `(address_space_root, virtual_address)`.
|
identifies a futex uniquely; the kernel keys its wait queue by `(address_space_root, virtual_address)`.
|
||||||
Keying by the **physical** address instead (translate `virtual_address -> physical_address` on entry) is a
|
Keying by the **physical** address instead (translate `virtual_address -> physical_address` on entry) is a
|
||||||
deliberate forward door: it lets two *processes* share a futex through an
|
deliberate forward door: it lets two *processes* share a futex through an
|
||||||
[shared-memory](display-v2.md) region later, without changing the API. We start with the
|
[shared-memory](../device-driver-development/display-v2.md) region later, without changing the API. We start with the
|
||||||
private-per-address-space key and note the physical-key upgrade.
|
private-per-address-space key and note the physical-key upgrade.
|
||||||
|
|
||||||
No spinning: a contended lock parks the task in the kernel and the core is free to run
|
No spinning: a contended lock parks the task in the kernel and the core is free to run
|
||||||
@@ -236,10 +237,11 @@ see the intro). Two scoped pieces, as built:
|
|||||||
|
|
||||||
### Build: multi-threaded codegen, opt-in
|
### Build: multi-threaded codegen, opt-in
|
||||||
|
|
||||||
A binary opts in by being added with `addThreadedUserBinary` — as `addUserBinary`,
|
A binary opts in with `.threaded = true` in its package's
|
||||||
but the shared implementation builds it `single_threaded = false` — so atomics and
|
`build_support.userBinary` call — the shared recipe in build-support then builds it
|
||||||
(later) TLS are real. Threads and atomics are unsound in a `single_threaded` image,
|
`single_threaded = false` — so atomics
|
||||||
so a binary must opt in **before** it may call `runtime.Thread.spawn`. Everyone else
|
and (later) TLS are real. Threads and atomics are unsound in a `single_threaded` image,
|
||||||
|
so a binary must opt in **before** it may call `Thread.spawn`. Everyone else
|
||||||
stays single-threaded and lean.
|
stays single-threaded and lean.
|
||||||
|
|
||||||
## Interaction with the rest of the kernel
|
## Interaction with the rest of the kernel
|
||||||
@@ -264,17 +266,19 @@ stays single-threaded and lean.
|
|||||||
**process**, which respawns its threads from a known-good state — restart
|
**process**, which respawns its threads from a known-good state — restart
|
||||||
granularity stays the process. The leader's recorded exit reason carries the fault
|
granularity stays the process. The leader's recorded exit reason carries the fault
|
||||||
class even when a worker faulted, so restart policy is unchanged.
|
class even when a worker faulted, so restart policy is unchanged.
|
||||||
- **IPC — two consequences threads forced ([ipc.md](ipc.md)):**
|
- **IPC — two consequences threads forced ([ipc.md](../device-driver-development/ipc.md)):**
|
||||||
- *Handles do not cross threads.* The handle table lives on the `Task`
|
- *Handles do not cross threads.* The handle table lives on the `Task`
|
||||||
([scheduler.zig](../system/kernel/scheduler.zig)), so a handle number is meaningful
|
([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.
|
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
|
A thread that needs to reach an endpoint another thread owns opens the name
|
||||||
(`ipc.lookup(service)`) to install its **own** handle to the same underlying endpoint.
|
(`channel.openEndpoint("display")`) to install its **own** handle to the same
|
||||||
This is how the display's mouse-listener thread reaches the compositor loop's endpoint
|
underlying endpoint — an ordinary client open, with no special mechanism for the
|
||||||
to poke it awake (docs/display.md).
|
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.*
|
- *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
|
`create_ipc_endpoint` allocates from the kernel heap and
|
||||||
mutate the global service registry, endpoint refcounts, and handle tables. Those paths
|
mutates endpoint refcounts and handle tables. Those paths
|
||||||
were unlocked because a single-threaded process could not race itself; a multi-threaded
|
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`/
|
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
|
`send` already did — the kernel heap has no lock of its own (heap.zig: "every kernel
|
||||||
@@ -284,7 +288,7 @@ stays single-threaded and lean.
|
|||||||
|
|
||||||
The ordered, `/loop`-runnable milestones live in
|
The ordered, `/loop`-runnable milestones live in
|
||||||
**[threading-plan.md](threading-plan.md)** (shaped like
|
**[threading-plan.md](threading-plan.md)** (shaped like
|
||||||
[display-v2-plan.md](display-v2-plan.md)): every milestone lands on its own and ends in
|
[display-v2-plan.md](../device-driver-development/display-v2-plan.md)): every milestone lands on its own and ends in
|
||||||
a verifiable gate (`python3 test/qemu_test.py <case>`, asserting serial markers;
|
a verifiable gate (`python3 test/qemu_test.py <case>`, asserting serial markers;
|
||||||
`zig build test` for host unit tests). The stages below are the shape it expands.
|
`zig build test` for host unit tests). The stages below are the shape it expands.
|
||||||
|
|
||||||
@@ -307,15 +311,15 @@ a verifiable gate (`python3 test/qemu_test.py <case>`, asserting serial markers;
|
|||||||
the consumer blocked, e.g. via a low idle tick count).
|
the consumer blocked, e.g. via a low idle tick count).
|
||||||
- **Stage 3 — polish.** Per-thread TLS / thread pointer and `threadlocal` (only if a
|
- **Stage 3 — polish.** Per-thread TLS / thread pointer and `threadlocal` (only if a
|
||||||
consumer needs it), `RwLock`/`WaitGroup` as demanded, and this doc's cases wired
|
consumer needs it), `RwLock`/`WaitGroup` as demanded, and this doc's cases wired
|
||||||
into [test/qemu_test.py](../test/qemu_test.py).
|
into [test/qemu_test.py](../../test/qemu_test.py).
|
||||||
|
|
||||||
## Conventions
|
## Conventions
|
||||||
|
|
||||||
Follow [coding-standards.md](coding-standards.md): spell out non-acronym
|
Follow [coding-standards.md](../coding-standards.md): spell out non-acronym
|
||||||
abbreviations, kebab-case file names, no `Co-Authored-By` trailers. New syscalls
|
abbreviations, kebab-case file names, no `Co-Authored-By` trailers. New syscalls
|
||||||
extend [abi.zig](../system/abi.zig) `SystemCall` + a `library/runtime` wrapper
|
extend [abi.zig](../../system/abi.zig) `SystemCall` + a `library/kernel` wrapper
|
||||||
([syscall.md](syscall.md)). `runtime.Thread` is a first-class runtime module, the same
|
([syscall.md](syscall.md)). `Thread` is a first-class runtime module, the same
|
||||||
way `runtime.process` ([process-lifecycle.md](process-lifecycle.md)) and `runtime.ipc`
|
way `process` ([process-lifecycle.md](process-lifecycle.md)) and `ipc`
|
||||||
are — user code never names a syscall.
|
are — user code never names a syscall.
|
||||||
|
|
||||||
## Non-goals
|
## Non-goals
|
||||||
@@ -331,19 +335,19 @@ are — user code never names a syscall.
|
|||||||
## The self-hosting endgame
|
## The self-hosting endgame
|
||||||
|
|
||||||
When danos becomes a real Zig target and we (eventually) add a danos backend to std
|
When danos becomes a real Zig target and we (eventually) add a danos backend to std
|
||||||
([zig-self-hosting.md](zig-self-hosting.md)), `std.Thread` can sit *on top of* these
|
([zig-self-hosting.md](../zig-self-hosting.md)), `std.Thread` can sit *on top of* these
|
||||||
same kernel primitives — the danos `std.Thread.Impl` would call the very
|
same kernel primitives — the danos `std.Thread.Impl` would call the very
|
||||||
`thread_spawn`/`futex_*` wrappers `runtime.Thread` already uses. Because
|
`thread_spawn`/`futex_*` wrappers `Thread` already uses. Because
|
||||||
`runtime.Thread` was built API-compatible from day one, that transition swaps the
|
`Thread` was built API-compatible from day one, that transition swaps the
|
||||||
implementation, not a single call site. Designing to the std shape now is what makes
|
implementation, not a single call site. Designing to the std shape now is what makes
|
||||||
the later self-hosting lift cheap.
|
the later self-hosting lift cheap.
|
||||||
|
|
||||||
## Further reading
|
## Further reading
|
||||||
|
|
||||||
- [scheduling.md](scheduling.md), [smp.md](smp.md) — the task model these threads join.
|
- [scheduling.md](scheduling.md), [smp.md](smp.md) — the task model these threads join.
|
||||||
- [resilience.md](resilience.md), [vision.md](vision.md) — why isolation is the default
|
- [resilience.md](resilience.md), [vision.md](../vision.md) — why isolation is the default
|
||||||
and threads are the exception.
|
and threads are the exception.
|
||||||
- [syscall.md](syscall.md), [ipc.md](ipc.md) — the private ABI and the messaging model
|
- [syscall.md](syscall.md), [ipc.md](../device-driver-development/ipc.md) — the private ABI and the messaging model
|
||||||
threads sit beside.
|
threads sit beside.
|
||||||
- [halting.md](halting.md) — the idle/halt property futex-backed blocking preserves.
|
- [halting.md](halting.md) — the idle/halt property futex-backed blocking preserves.
|
||||||
- [zig-self-hosting.md](zig-self-hosting.md) — the target this bends toward.
|
- [zig-self-hosting.md](../zig-self-hosting.md) — the target this bends toward.
|
||||||
@@ -7,7 +7,7 @@ Two different needs hide under the word "timer", and danos keeps them apart:
|
|||||||
|
|
||||||
Both are answered by the **kernel**, because the kernel already owns a timer: it has
|
Both are answered by the **kernel**, because the kernel already owns a timer: it has
|
||||||
to, to preempt tasks. The LAPIC heartbeat and the calibrated TSC that back all of this
|
to, to preempt tasks. The LAPIC heartbeat and the calibrated TSC that back all of this
|
||||||
are built in [device-interrupts.md](device-interrupts.md); the scheduler's blocking and
|
are built in [device-interrupts.md](../device-driver-development/device-interrupts.md); the scheduler's blocking and
|
||||||
wait queues are in [scheduling.md](scheduling.md). This page is about the surface a
|
wait queues are in [scheduling.md](scheduling.md). This page is about the surface a
|
||||||
ring-3 program actually uses, and one deliberate absence: **there is no user-space time
|
ring-3 program actually uses, and one deliberate absence: **there is no user-space time
|
||||||
service.**
|
service.**
|
||||||
@@ -32,13 +32,14 @@ danos checks both — the invariant-TSC CPUID bit (`0x80000007` EDX[8], set on I
|
|||||||
AMD), and a cross-core "warp" check as the cores come up — and falls back to the HPET
|
AMD), and a cross-core "warp" check as the cores come up — and falls back to the HPET
|
||||||
counter when either fails. So `now()` stays accurate on a real Intel box, a real AMD box,
|
counter when either fails. So `now()` stays accurate on a real Intel box, a real AMD box,
|
||||||
and inside a VM alike; only the source behind it differs. The mechanism is in
|
and inside a VM alike; only the source behind it differs. The mechanism is in
|
||||||
[device-interrupts.md](device-interrupts.md).
|
[device-interrupts.md](../device-driver-development/device-interrupts.md).
|
||||||
|
|
||||||
So the timer hardware lives in the kernel, and there is **no `hpet` driver and no time
|
So the timer hardware lives in the kernel, and there is **no `hpet` driver and no time
|
||||||
server** to consume. (An earlier HPET driver existed only to *demonstrate* the driver
|
server** to consume. (An earlier HPET driver existed only to *demonstrate* the driver
|
||||||
model; that role now lives in [drivers.md](drivers.md), as documentation.) The one place
|
model; that role now lives in [drivers.md](../device-driver-development/drivers.md), as documentation.) The one part
|
||||||
a user-space time service *is* justified — **wall-clock / calendar time** — is discussed
|
left to user space — **calendar policy** over wall-clock time (time zones, formatting) —
|
||||||
at the end; it is deliberately not built yet.
|
is discussed at the end; the wall-clock *seconds* it builds on are a kernel syscall
|
||||||
|
(`wall_clock`), like the monotonic clock.
|
||||||
|
|
||||||
## The three system calls
|
## The three system calls
|
||||||
|
|
||||||
@@ -55,20 +56,20 @@ Time and waiting are three entries in the small syscall table ([syscall.md](sysc
|
|||||||
service can keep answering messages on the same endpoint while a deadline is pending.
|
service can keep answering messages on the same endpoint while a deadline is pending.
|
||||||
This is the timed wait that stop-sequence escalation, hello deadlines, and restart
|
This is the timed wait that stop-sequence escalation, hello deadlines, and restart
|
||||||
backoff are built from ([process-lifecycle.md](process-lifecycle.md),
|
backoff are built from ([process-lifecycle.md](process-lifecycle.md),
|
||||||
[device-manager.md](device-manager.md)).
|
[device-manager.md](../device-driver-development/device-manager.md)).
|
||||||
|
|
||||||
The kernel's own scheduling timer (the LAPIC, vector 32) is never exposed to user space;
|
The kernel's own scheduling timer (the LAPIC, vector 32) is never exposed to user space;
|
||||||
programs read the TSC through `clock` and get timed wakeups through `sleep`/`timer_bind`,
|
programs read the TSC through `clock` and get timed wakeups through `sleep`/`timer_bind`,
|
||||||
both riding the scheduler tick.
|
both riding the scheduler tick.
|
||||||
|
|
||||||
## `runtime.time` — the generic interface
|
## `time` — the generic interface
|
||||||
|
|
||||||
Applications don't call the syscalls directly; they use `runtime.time`
|
Applications don't call the syscalls directly; they use `time`
|
||||||
(`library/runtime/time.zig`), a thin `Instant`/`Duration` layer over them — an ergonomic
|
(`library/kernel/time.zig`), a thin `Instant`/`Duration` layer over them — an ergonomic
|
||||||
front door, not new mechanism.
|
front door, not new mechanism.
|
||||||
|
|
||||||
```zig
|
```zig
|
||||||
const time = @import("runtime").time;
|
const time = @import("time");
|
||||||
|
|
||||||
const start = time.now(); // Instant — monotonic
|
const start = time.now(); // Instant — monotonic
|
||||||
doWork();
|
doWork();
|
||||||
@@ -91,25 +92,28 @@ _ = time.after(endpoint, time.Duration.fromMillis(200));
|
|||||||
- `sleep(d)` wraps `sleep`; `spin(d)` busy-polls `now()` for the sub-millisecond delays
|
- `sleep(d)` wraps `sleep`; `spin(d)` busy-polls `now()` for the sub-millisecond delays
|
||||||
the millisecond tick can't express; `after(endpoint, d)` wraps `timer_bind`.
|
the millisecond tick can't express; `after(endpoint, d)` wraps `timer_bind`.
|
||||||
|
|
||||||
The raw wrappers (`system.clock`, `system.sleep`, `system.timerOnce`) stay in
|
The raw wrappers (`clock`, `sleepMillis`, `timerOnce`) and the ergonomic
|
||||||
`library/runtime/system.zig`; `runtime.time` is the layer meant for everyday use.
|
`Instant`/`Duration` layer both live in the `time` module
|
||||||
|
(`library/kernel/time.zig`); the latter is what everyday code uses.
|
||||||
|
|
||||||
## Wall-clock time (not built)
|
## Wall-clock time
|
||||||
|
|
||||||
Everything above is **monotonic**: elapsed time since boot, perfect for timeouts and
|
Everything above is **monotonic**: elapsed time since boot, perfect for timeouts and
|
||||||
measurement, useless for "what is the date?" Calendar time — a real-time clock, time
|
measurement, useless for "what is the date?" Calendar time needs a **real-time clock**.
|
||||||
zones, leap seconds — is genuinely a **user-space** concern, and it *is* the case a time
|
The kernel owns wall-clock *seconds* as mechanism, exactly like the monotonic clock: the
|
||||||
service is for. It would be backed by an **RTC** driver (the CMOS real-time clock), not
|
`wall_clock` syscall (#33) returns Unix epoch seconds (UTC). The CMOS **RTC** is read
|
||||||
the HPET, and exposed as a `CLOCK_REALTIME`-style service alongside the monotonic
|
once at boot and anchored to the monotonic clock (`system/kernel/wall-clock.zig`), so a
|
||||||
syscall. It is deferred until something needs it; the monotonic clock the kernel already
|
query is a cheap arithmetic offset rather than a per-call CMOS poll; `time`'s
|
||||||
owns covers every current use.
|
`wallClock()` (`library/kernel/time.zig`) wraps it. Reading the hardware's value is not
|
||||||
|
policy — time zones, leap seconds, calendars, and formatting layer on top in user space.
|
||||||
|
It exists because the filesystem needs real timestamps (mtime).
|
||||||
|
|
||||||
## Verifying it
|
## Verifying it
|
||||||
|
|
||||||
`runtime.time`'s `Instant`/`Duration` arithmetic has unit tests that run on the host:
|
`time`'s `Instant`/`Duration` arithmetic has unit tests that run on the host:
|
||||||
|
|
||||||
```
|
```
|
||||||
$ zig build test # includes library/runtime/time.zig
|
$ zig build test # includes library/kernel/time.zig
|
||||||
```
|
```
|
||||||
|
|
||||||
End to end, the proof the clock is real is that it *advances*: read `now()`, `sleep` a
|
End to end, the proof the clock is real is that it *advances*: read `now()`, `sleep` a
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
# The vDSO — the public system-call boundary
|
# The vDSO — the public system-call boundary
|
||||||
|
|
||||||
> **Status:** design note, not built. The runtime today issues raw `syscall`
|
> **Status:** design note, not built. The runtime today issues raw `syscall`
|
||||||
> instructions from `library/runtime/system-call.zig` using the numbers in
|
> instructions from `library/kernel/system-call.zig` using the numbers in
|
||||||
> `system/abi.zig`. This note designs the layer that replaces that arrangement:
|
> `system/abi.zig`. This note designs the layer that replaces that arrangement:
|
||||||
> a **kernel-supplied, C-ABI entry library** mapped into every process — the
|
> a **kernel-supplied, C-ABI entry library** mapped into every process — the
|
||||||
> only supported way into the kernel — so the raw numbers can stay private,
|
> only supported way into the kernel — so the raw numbers can stay private,
|
||||||
@@ -25,8 +25,8 @@ ourselves:
|
|||||||
this mistake: it issued XNU syscalls directly instead of going through
|
this mistake: it issued XNU syscalls directly instead of going through
|
||||||
libSystem, and macOS updates repeatedly broke every Go binary until Go
|
libSystem, and macOS updates repeatedly broke every Go binary until Go
|
||||||
switched to the library like everyone else.
|
switched to the library like everyone else.
|
||||||
2. **Not everything is Zig.** A Rust or C program can't import the `runtime`
|
2. **Not everything is Zig.** A Rust or C program can't import the danos Zig
|
||||||
module. The public boundary has to be expressible in the one calling
|
modules. The public boundary has to be expressible in the one calling
|
||||||
convention every language speaks: the C ABI.
|
convention every language speaks: the C ABI.
|
||||||
3. **Randomised syscall numbers** — a hardening option we want open — only
|
3. **Randomised syscall numbers** — a hardening option we want open — only
|
||||||
work if no user binary anywhere knows a number at build time. The binding
|
work if no user binary anywhere knows a number at build time. The binding
|
||||||
@@ -49,10 +49,10 @@ The public danos ABI then has exactly two layers, neither of which is
|
|||||||
|
|
||||||
| Layer | Contract | Spoken by |
|
| Layer | Contract | Spoken by |
|
||||||
|-------|----------|-----------|
|
|-------|----------|-----------|
|
||||||
| **vDSO** | C-ABI functions, this note | every language's thin shim (`runtime.system` for Zig, a `-sys` crate for Rust, a header for C) |
|
| **vDSO** | C-ABI functions, this note | every language's thin shim (the `system-call` module for Zig, a `-sys` crate for Rust, a header for C) |
|
||||||
| **IPC wire protocols** | byte layouts over `ipc_call` ([vfs-protocol.md](vfs-protocol.md) is the first one documented) | any client that can lay out bytes |
|
| **IPC wire protocols** | byte layouts over `ipc_call` ([vfs-protocol.md](../file-system-development/vfs-protocol.md) is the first one documented) | any client that can lay out bytes |
|
||||||
|
|
||||||
Everything above those — the heap, `runtime.fs`, the service harness — is
|
Everything above those — the heap, `file_system`, the service harness — is
|
||||||
per-language convenience, compiled into each binary from source, exactly as
|
per-language convenience, compiled into each binary from source, exactly as
|
||||||
today. Nothing about the Zig runtime's shape changes; it just stops being the
|
today. Nothing about the Zig runtime's shape changes; it just stops being the
|
||||||
*only* door.
|
*only* door.
|
||||||
@@ -107,7 +107,7 @@ convenience, not a requirement.)
|
|||||||
|
|
||||||
The kernel already builds a System V entry block — argc, argv, envp
|
The kernel already builds a System V entry block — argc, argv, envp
|
||||||
terminator, **auxiliary vector** — on every new process's stack
|
terminator, **auxiliary vector** — on every new process's stack
|
||||||
(`buildEntryStack`, read by `runtime.start`). The vDSO base rides in a new
|
(`buildEntryStack`, read by the `start` module). The vDSO base rides in a new
|
||||||
auxv entry, exactly Linux's `AT_SYSINFO_EHDR` move. No new syscall, no magic
|
auxv entry, exactly Linux's `AT_SYSINFO_EHDR` move. No new syscall, no magic
|
||||||
address, and a language shim finds it the same portable way on every
|
address, and a language shim finds it the same portable way on every
|
||||||
architecture.
|
architecture.
|
||||||
@@ -123,12 +123,15 @@ The calls that return two values in `rax:rdx` today — `dma_alloc`
|
|||||||
`fs_resolve` (route tag + node token / backend handle) —
|
`fs_resolve` (route tag + node token / backend handle) —
|
||||||
become functions returning a two-`u64` struct. The System V ABI returns a
|
become functions returning a two-`u64` struct. The System V ABI returns a
|
||||||
16-byte struct in `rax:rdx`, so the stub is a plain `syscall; ret` — the
|
16-byte struct in `rax:rdx`, so the stub is a plain `syscall; ret` — the
|
||||||
C-ABI spelling of the existing convention, at zero cost. The one call that
|
C-ABI spelling of the existing convention, at zero cost. The calls that
|
||||||
returns *three* values — `ipc_reply_wait` (receive_len in `rax`, badge in
|
return *three* values — `ipc_reply_wait` (receive_len in `rax`, badge in
|
||||||
`rdx`, received capability in `r8`) — exceeds the two-register return: its
|
`rdx`, received capability in `r8`) and `dma_alloc` when the region is
|
||||||
function returns a three-`u64` struct, which the ABI passes via a hidden
|
`shareable` (virtual in `rax`, physical in `rdx`, handle in `r8`) — exceed the
|
||||||
result pointer, so that one stub stores `rax`/`rdx`/`r8` through the pointer
|
two-register return: their functions return a three-`u64` struct, which the
|
||||||
after the `syscall` — a few instructions rather than one.
|
ABI passes via a hidden result pointer, so each stub stores `rax`/`rdx`/`r8`
|
||||||
|
through the pointer after the `syscall` — a few instructions rather than one.
|
||||||
|
(`ipc_call` likewise carries a received capability in `r8` alongside its `rax`
|
||||||
|
result.)
|
||||||
|
|
||||||
Grouped as `abi.zig` groups them:
|
Grouped as `abi.zig` groups them:
|
||||||
|
|
||||||
@@ -137,19 +140,70 @@ 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` |
|
| 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` |
|
| 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` |
|
| 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` |
|
| 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` |
|
| time | `danos_clock`, `danos_wall_clock`, `danos_timer_bind` |
|
||||||
| diagnostics | `danos_debug_write` (leveled, kernel-stamped records), `danos_klog_read`, `danos_klog_status` |
|
| 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) |
|
| 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
|
The constants that ride alongside the calls — mmap protection bits, DMA
|
||||||
flags, notification badge bits, `ExitReason`, `Signal`, well-known service
|
flags, notification badge bits, `ExitReason`, `Signal`, `page_size`, the IPC
|
||||||
ids, `page_size`, the IPC message maximum — move to the public header too:
|
message maximum — move to the public header too:
|
||||||
they are wire values a Rust program needs verbatim. What stays private in
|
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`
|
`abi.zig` is exactly the thing the vDSO exists to hide: the `SystemCall`
|
||||||
numbers and the trap convention.
|
numbers and the trap convention.
|
||||||
|
|
||||||
|
## Errors: the errno space
|
||||||
|
|
||||||
|
A failed call returns `-errno`. The runtime detects failure the way Linux
|
||||||
|
does — a return value in the top 4096 — so every code stays inside 1..4095.
|
||||||
|
These are **public**: unlike the call numbers, a caller must be able to read
|
||||||
|
them verbatim, and they are the same vocabulary whether the number came from
|
||||||
|
the kernel or from a user-space provider answering over IPC.
|
||||||
|
|
||||||
|
They are defined once in `system/abi.zig`. The kernel restates them in
|
||||||
|
`system/kernel/ipc-synchronous.zig` and the envelope restates the
|
||||||
|
provider-facing subset in `library/protocol/envelope/envelope.zig` (the
|
||||||
|
`protocol` package deliberately depends on nothing, so it cannot import
|
||||||
|
`abi`); a comptime check in `library/device/driver/driver.zig` makes drift a
|
||||||
|
compile error.
|
||||||
|
|
||||||
|
| # | Name | Meaning |
|
||||||
|
|---|------|---------|
|
||||||
|
| 1 | `EBADF` | bad handle |
|
||||||
|
| 2 | `E2BIG` | an argument exceeds its maximum (a message, a descriptor's resource count) |
|
||||||
|
| 3 | `EFAULT` | buffer unmapped, or outside the user half |
|
||||||
|
| 4 | `ENOENT` | no such name |
|
||||||
|
| 5 | `ENOSPC` | a kernel table is full (handles, devices) |
|
||||||
|
| 6 | `ENOMEM` | out of memory |
|
||||||
|
| 7 | `EPEER` | the peer died before replying — its process exited or was killed |
|
||||||
|
| 8 | `ESRCH` | no such process |
|
||||||
|
| 9 | `EPERM` | not permitted: the caller is not the owner or supervisor |
|
||||||
|
| 10 | `ENOSYS` | this protocol has no such operation |
|
||||||
|
| 11 | `EPROTO` | malformed packet: shorter than the verb it names |
|
||||||
|
| 12 | `EBUSY` | the thing asked for is held by someone still alive |
|
||||||
|
| 13 | `ENODEV` | no such device id |
|
||||||
|
| 14 | `ECHILDREN` | this parent already holds as many children as it can |
|
||||||
|
| 15 | `ERANGE` | a resource escapes the window it must fall inside |
|
||||||
|
| 16 | `ECONFINE` | the device could not be placed under IOMMU translation |
|
||||||
|
|
||||||
|
`EPEER` is the one with no POSIX counterpart and it is worth stating plainly:
|
||||||
|
synchronous IPC blocks the caller until the server replies, so the caller
|
||||||
|
needs an answer for "the server died while I was waiting." It is not a
|
||||||
|
transport error and not a refusal — the request may well have been carried
|
||||||
|
out — it says only that no reply is coming. A client that treats it as
|
||||||
|
"retry" can duplicate work; the honest response is to re-resolve the protocol
|
||||||
|
name, because the provider it held is gone.
|
||||||
|
|
||||||
|
**A refusal names the rule that refused it.** This is a rule and not a
|
||||||
|
courtesy. `device_register` alone can fail six ways, and until each got its
|
||||||
|
own code a bus driver could only report "refused" — which is how an AMD
|
||||||
|
desktop came to boot with a working display, no USB and no storage, with
|
||||||
|
three independent causes indistinguishable in the log. See
|
||||||
|
[fixed-bounds-audit.md](../fixed-bounds-audit.md). A new failure mode that
|
||||||
|
does not fit an existing code gets a new one here rather than borrowing the
|
||||||
|
nearest.
|
||||||
|
|
||||||
## Enforcement, and an honest threat model
|
## Enforcement, and an honest threat model
|
||||||
|
|
||||||
Renumbering only has teeth if the kernel **refuses syscalls that don't come
|
Renumbering only has teeth if the kernel **refuses syscalls that don't come
|
||||||
@@ -183,11 +237,11 @@ second — but the design should never be sold as more than that.
|
|||||||
Phased so every step ships alone (the M-milestone discipline):
|
Phased so every step ships alone (the M-milestone discipline):
|
||||||
|
|
||||||
1. **The blob + the table.** Build the vDSO, map it at spawn, deliver the
|
1. **The blob + the table.** Build the vDSO, map it at spawn, deliver the
|
||||||
base via auxv. `runtime.system-call.zig` binds through the table when the
|
base via auxv. `library/kernel/system-call.zig` binds through the table when the
|
||||||
auxv entry is present, falls back to raw `syscall` when absent — the whole
|
auxv entry is present, falls back to raw `syscall` when absent — the whole
|
||||||
tree keeps booting during the transition.
|
tree keeps booting during the transition.
|
||||||
2. **Cut the runtime over.** Delete the raw stubs; `runtime` no longer
|
2. **Cut the system library over.** Delete the raw stubs; the `system-call`
|
||||||
imports the `SystemCall` numbers at all (`abi.zig`'s enum becomes
|
module no longer imports the `SystemCall` numbers at all (`abi.zig`'s enum becomes
|
||||||
kernel-internal). The QEMU suite passing proves the table carries the
|
kernel-internal). The QEMU suite passing proves the table carries the
|
||||||
whole system.
|
whole system.
|
||||||
3. **Enforce + randomise.** Add the `rip`-range check, then per-boot number
|
3. **Enforce + randomise.** Add the `rip`-range check, then per-boot number
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
# Python on danos: the milestone plan
|
||||||
|
|
||||||
|
The execution plan for [python-on-danos.md](python-on-danos.md). That note holds
|
||||||
|
the *why* and the design decisions; this one slices the work into milestones with
|
||||||
|
concrete deliverables, tests, and exit criteria. Milestones are numbered **P0–P5**
|
||||||
|
(track-local — the global M-series stays with the driver/lifecycle tracks).
|
||||||
|
|
||||||
|
Dependencies at a glance:
|
||||||
|
|
||||||
|
```
|
||||||
|
P0 toolchain + mini-libc ──┐
|
||||||
|
P1 streams + console + seam ─┴─→ P2 CPython minimal ─→ P3 terminal + REPL
|
||||||
|
│ │
|
||||||
|
└─→ P4 danos module │
|
||||||
|
+ Python service│
|
||||||
|
P5 process control + shell ←─────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
P0 and P1 are independent of each other and can proceed in parallel. P1 is shared
|
||||||
|
work — it is also Zig self-hosting Phase 1 and the first three slices of
|
||||||
|
[character-devices-and-tty.md](character-devices-and-tty.md).
|
||||||
|
|
||||||
|
## P0 — Toolchain + the C library compatibility layer
|
||||||
|
|
||||||
|
**Goal:** a C hello-world, cross-compiled on the host with `zig cc`, runs on danos.
|
||||||
|
|
||||||
|
Design and slicing live in
|
||||||
|
[c-library-compatibility.md](c-library-compatibility.md): the **libdanos-c**
|
||||||
|
sysroot (hand-written danos-native headers + `libc.a`) as a `library/c/` build
|
||||||
|
package — pure computation (string, libm, `strtod`, the printf/scanf engines)
|
||||||
|
lifted from a vendored, pinned musl subtree; the OS plumbing written in Zig over
|
||||||
|
the `runtime` surface (re-targeting `runtime.os` when the Zig track authors it);
|
||||||
|
`malloc` over danos `mmap`; a `crt0` bridging the danos entry shim to C `main`.
|
||||||
|
Driven by `zig cc -target x86_64-freestanding-none -isystem` (the triple becomes
|
||||||
|
`x86_64-danos` if the Zig fork lands first; nothing else changes).
|
||||||
|
|
||||||
|
Its five slices (sysroot-skeleton, fd-plumbing, malloc, stdio,
|
||||||
|
mathematics-and-time) carry their own tests — host-side oracle suites for the
|
||||||
|
computation layer, QEMU cases (`c-hello`, `c-file-io`, `c-stdio`, `c-time`) for
|
||||||
|
the plumbing.
|
||||||
|
|
||||||
|
**Exit:** `c-hello` and `c-file-io` green in the QEMU suite; host computation
|
||||||
|
tests green.
|
||||||
|
|
||||||
|
## P1 — Stream nodes, console, and the seam pieces
|
||||||
|
|
||||||
|
**Goal:** the shared Phase-1 surface exists: byte-stream stdio, cwd, environment,
|
||||||
|
entropy. Design and slicing live in
|
||||||
|
[character-devices-and-tty.md](character-devices-and-tty.md); this milestone is
|
||||||
|
its slices 1–3 plus three small seam pieces:
|
||||||
|
|
||||||
|
- **cwd/chdir** — per-process current directory used by path resolution (the
|
||||||
|
kernel already anchors a VFS root per `fs_resolve`; the cwd is the same idea,
|
||||||
|
process-scoped, with `getcwd`/`chdir` exposed through `runtime` and the libc).
|
||||||
|
- **Environment** — spawn carries an environment block; the SysV entry stack's
|
||||||
|
`envp` slot ([sysv.md](os-development/sysv.md)) stops being empty; `getenv`
|
||||||
|
reads it. An empty block stays valid.
|
||||||
|
- **Entropy** — a kernel `entropy` syscall (RDSEED/RDRAND with a jitter fallback,
|
||||||
|
mirroring the TSC-reliability posture of not trusting one CPU feature blindly);
|
||||||
|
the libc exposes `getentropy`.
|
||||||
|
|
||||||
|
- **Tests.** QEMU: the character-device tests from the tty note (offsetless
|
||||||
|
read/write, blocking read, cooked/raw control round-trip), plus `cwd-basics`
|
||||||
|
(chdir + relative open), `env-roundtrip` (spawn with env, child reads it),
|
||||||
|
`entropy-sane` (nonzero, changing, correct length).
|
||||||
|
|
||||||
|
**Exit:** a C program reads a cooked line from fd 0 and echoes it to fd 1 —
|
||||||
|
injected key events in, bytes read back through the console's in-memory sink,
|
||||||
|
all under QEMU with no hardware involved — and `getcwd`/`getenv`/`getentropy`
|
||||||
|
return real answers.
|
||||||
|
|
||||||
|
## P2 — CPython, minimal configuration
|
||||||
|
|
||||||
|
**Goal:** `python -c 'print(2**100)'` runs on danos under QEMU.
|
||||||
|
|
||||||
|
- Pin **CPython 3.13.x**; vendor as `third-party/cpython/` or fetch via the build
|
||||||
|
(decide with the build-packages conventions).
|
||||||
|
- Host build-Python of the same version (`--with-build-python`).
|
||||||
|
- `config.site` cache for the cross answers; `config.sub` patch so
|
||||||
|
`x86_64-unknown-danos` parses; a small `configure`/`pyconfig` patch set kept as
|
||||||
|
rebasable diffs, WASI-style.
|
||||||
|
- `--disable-shared`; static `Modules/Setup`: `posix errno _io _codecs _weakref
|
||||||
|
time math _stat _collections itertools _functools _locale _sre` plus what the
|
||||||
|
interpreter core insists on; threadless build (WASI precedent).
|
||||||
|
- `Lib/` on the FAT image under the hierarchy (e.g. `/system/python/lib`);
|
||||||
|
`PYTHONHOME` set accordingly; `.pyc` written with **checked-hash
|
||||||
|
invalidation** (FAT's 2-second mtime granularity makes mtime-based validation
|
||||||
|
lie during fast edit-run cycles).
|
||||||
|
- `PYTHONHASHSEED` pinned only if P1's entropy slipped — otherwise real
|
||||||
|
hash randomization from day one.
|
||||||
|
- **Tests.** QEMU: `python-expr` (the exit criterion), `python-file` (run a
|
||||||
|
script from FAT, write a file, read it back), then a curated slice of CPython's
|
||||||
|
own suite (`test_int`, `test_float`, `test_io`, `test_dict`) as a
|
||||||
|
longer-running target — the suite is the porting harness.
|
||||||
|
|
||||||
|
**Exit:** the four QEMU cases green; the CPython test slice green or with a
|
||||||
|
short, documented skip list.
|
||||||
|
|
||||||
|
## P3 — Terminal + REPL: the first real application
|
||||||
|
|
||||||
|
**Goal:** an interactive `python` REPL in a graphical danos terminal — the
|
||||||
|
milestone demo for the OS.
|
||||||
|
|
||||||
|
- Depends on the display track's font rendering (its stated next step) — until
|
||||||
|
that lands, the REPL is exercised end-to-end through the pseudo-device
|
||||||
|
harness from P1+P2 (scripted input in, output read back), so P2's exit is
|
||||||
|
never blocked on graphics; the graphical terminal is the *interactive* debut.
|
||||||
|
- The terminal application: draws with the UI toolkit / display client, consumes
|
||||||
|
keyboard `InputEvent`s, and — per the tty note's load-bearing decision —
|
||||||
|
**serves the VFS stream protocol itself** to its children, reusing the console's
|
||||||
|
line-discipline library. Spawns `python` with its endpoints as fd 0/1/2.
|
||||||
|
- Raw mode + the control set give the REPL line editing; window-size control
|
||||||
|
gives it wrapping.
|
||||||
|
- **Tests.** QEMU: scripted terminal session (inject key events, assert rendered
|
||||||
|
or captured output). Real-hardware smoke on the Intel box joins the existing
|
||||||
|
checklist.
|
||||||
|
|
||||||
|
**Exit:** typing `2+2` into the terminal on the QEMU GPU target prints `4`.
|
||||||
|
|
||||||
|
## P4 — The `danos` extension module + a Python service
|
||||||
|
|
||||||
|
**Goal:** Python can speak danos: IPC, capabilities, spawn.
|
||||||
|
|
||||||
|
- The `danos` module, **written in Zig against `Python.h`**, statically linked
|
||||||
|
via `Modules/Setup`: endpoints (create/send/receive), capability passing,
|
||||||
|
spawn + exit-notification, and the service bootstrap (announce, supervision
|
||||||
|
handshake) — the same surface Zig services use, re-exposed.
|
||||||
|
- UI-toolkit bindings as a second module once the toolkit's API settles.
|
||||||
|
- Prototype **one real service in Python** — policy-shaped, not data-plane
|
||||||
|
(candidates: hot-plug policy, a settings service) — speaking an existing wire
|
||||||
|
protocol, supervised by the device manager like any service.
|
||||||
|
- **Tests.** QEMU: `python-ipc-echo` (Python service echoes over an endpoint, a
|
||||||
|
Zig client asserts), plus the prototype service's own protocol test.
|
||||||
|
|
||||||
|
**Exit:** a Python process runs as a supervised danos service exchanging IPC
|
||||||
|
with Zig peers.
|
||||||
|
|
||||||
|
## P5 — Process control, then the shell
|
||||||
|
|
||||||
|
**Goal:** danos can spawn arbitrary programs with arguments and pipes; a small
|
||||||
|
Python shell uses it.
|
||||||
|
|
||||||
|
The kernel/VFS cluster a shell forces (any shell, any language):
|
||||||
|
|
||||||
|
- **exec-of-path** — spawn an arbitrary VFS path, not a named ramdisk binary;
|
||||||
|
- **argv/envp** — carried through spawn onto the child's entry stack (argv
|
||||||
|
already built and tested via `spawnWithArguments`; envp new, from P1);
|
||||||
|
- **numeric exit status** — extend the exit record beyond the categorical
|
||||||
|
`ExitReason` (the gotcha the Zig roadmap flagged: `WEXITSTATUS` must be real);
|
||||||
|
- **fd inheritance + pipes** — a kernel or service pipe (a character device by
|
||||||
|
the tty note's definition) and spawn-time fd mapping.
|
||||||
|
|
||||||
|
Then, in order: `subprocess` enabled in CPython (maps onto spawn + the
|
||||||
|
exit-notification endpoint — no fork, Windows-style); a **small Python shell** (a
|
||||||
|
few hundred lines over `subprocess` + the console: prompt, argv parsing, pipes,
|
||||||
|
cwd) as the forcing function that reveals what job control actually needs.
|
||||||
|
|
||||||
|
**Explicitly deferred past P5:** the pthread subset over `thread_spawn`/futex,
|
||||||
|
signals-in-libc via M17, termios job control (Ctrl-C to foreground child), and
|
||||||
|
**xonsh** — which wants all three and is the arc's endpoint, not a milestone.
|
||||||
|
|
||||||
|
**Tests.** QEMU: `spawn-argv-exit` (child echoes argv, exits 42, parent sees
|
||||||
|
42), `pipe-through` (parent → child → parent), `python-subprocess`, and a
|
||||||
|
scripted shell session.
|
||||||
|
|
||||||
|
**Exit:** the Python shell runs `program | program` typed at the terminal and
|
||||||
|
reports the exit status.
|
||||||
|
|
||||||
|
## Post-P5 outlook
|
||||||
|
|
||||||
|
Two tracks continue past this plan, each with its own design doc rather than a
|
||||||
|
P-number here:
|
||||||
|
|
||||||
|
- **Dynamic libraries** ([dynamic-libraries.md](dynamic-libraries.md), D1–D4) —
|
||||||
|
an application-layer facility (the OS stays static and lean): `dlopen` in the
|
||||||
|
libc, then libffi + `ctypes` + loadable extension modules, then shared
|
||||||
|
read-only mappings so N Python services hold one physical `libpython`.
|
||||||
|
- **The full C compatibility layer**
|
||||||
|
([c-library-compatibility.md](c-library-compatibility.md), stages 2–3) — the
|
||||||
|
standing rule that every system capability ships with its C spelling, draining
|
||||||
|
the absence table toward "portable C builds on danos"; `fork` is the one
|
||||||
|
permanent exception.
|
||||||
|
|
||||||
|
## Related
|
||||||
|
|
||||||
|
- [python-on-danos.md](python-on-danos.md) — the design note this executes.
|
||||||
|
- [c-library-compatibility.md](c-library-compatibility.md) — P0's design.
|
||||||
|
- [character-devices-and-tty.md](character-devices-and-tty.md) — P1's design.
|
||||||
|
- [zig-self-hosting.md](zig-self-hosting.md) — shares P1; its fork makes P0's
|
||||||
|
triple prettier but gates nothing here.
|
||||||
|
- [os-development/process-management.md](os-development/process-management.md) —
|
||||||
|
the spawn/exit surface P5 extends.
|
||||||
@@ -0,0 +1,261 @@
|
|||||||
|
# Python on danos: the CPython milestone
|
||||||
|
|
||||||
|
A design note (not built yet) on bringing **CPython** to danos, compiled with the Zig
|
||||||
|
toolchain (`zig cc`). Like [zig-self-hosting.md](zig-self-hosting.md), it is
|
||||||
|
forward-looking: it sets a direction and the decisions that follow from it.
|
||||||
|
|
||||||
|
## Why Python, and why now
|
||||||
|
|
||||||
|
The Zig self-hosting road is gated on a compiler fork and a long std-library seam.
|
||||||
|
Python is the **stop-gap that removes the wait**: a working CPython gives danos a way
|
||||||
|
to write programs — services, tools, application prototypes — *without* the Zig
|
||||||
|
compiler being self-hosted, and it brings the pure-Python package ecosystem along as
|
||||||
|
a bonus. The intended division of labour:
|
||||||
|
|
||||||
|
- **Zig** — the kernel, drivers, and anything on a data plane (interrupt paths,
|
||||||
|
DMA rings, block I/O). Unchanged.
|
||||||
|
- **Python** — the control plane and the prototyping surface: services that are
|
||||||
|
event loops over IPC, policy logic that changes often, application experiments,
|
||||||
|
and eventually the shell.
|
||||||
|
|
||||||
|
Python is also the scripting language for the terminal-and-shell arc: the first
|
||||||
|
real danos application is planned as a terminal, a terminal wants a shell, a shell
|
||||||
|
wants a scripting language — and [xonsh](https://xon.sh) (a shell written in
|
||||||
|
Python) marks where that road can end.
|
||||||
|
|
||||||
|
### Non-goals
|
||||||
|
|
||||||
|
- **No drivers in Python.** Interrupt handling, ring management, and DMA stay in
|
||||||
|
Zig. Python may *supervise and configure* drivers; it does not sit in their hot
|
||||||
|
paths (interpreter overhead and garbage-collection pauses in an interrupt path
|
||||||
|
are disqualifying).
|
||||||
|
- **No dynamic loading during bring-up, no `pip`.** The whole arc here ships
|
||||||
|
statically linked. Dynamic libraries are a real *later* milestone
|
||||||
|
([dynamic-libraries.md](dynamic-libraries.md)) — an application-layer
|
||||||
|
facility that unlocks `ctypes` and loadable extension modules; the operating
|
||||||
|
system itself stays static and lean regardless (the size doctrine below).
|
||||||
|
`pip` stays out either way until a networking track exists.
|
||||||
|
- **No fork.** `os.fork` will not exist. This costs almost nothing (see "The
|
||||||
|
spawn model fits").
|
||||||
|
|
||||||
|
## The realization that shapes everything: the compiler is not the obstacle
|
||||||
|
|
||||||
|
`zig cc` is a full Clang-based C cross-compiler, and CPython is portable C with
|
||||||
|
official precedent for stranger targets than danos — the WASI port is upstream
|
||||||
|
tier-2, and it runs **without fork, without dynamic loading, and without working
|
||||||
|
threads**. Every "CPython can't possibly run there" objection has already been
|
||||||
|
answered upstream by a target *more* constrained than danos.
|
||||||
|
|
||||||
|
What CPython actually needs is a **C environment**: headers and a `libc.a`. danos
|
||||||
|
has neither — and that is the whole project. In the language of the Zig roadmap's
|
||||||
|
three doors, this is the **door-2-shaped work** (the deferred "musl door"), not the
|
||||||
|
`std.os.danos` seam: CPython never touches Zig's std.
|
||||||
|
|
||||||
|
### The same surface, a third time
|
||||||
|
|
||||||
|
The Zig roadmap observed that door 1 (`std.os.danos`) and door 2 (a libc) implement
|
||||||
|
the *same* ~30 danos-facing operations at different layers. CPython consumes that
|
||||||
|
identical surface through C spellings. So nothing here is throwaway: the
|
||||||
|
danos-native operations backing `runtime.os` are the same ones the libc bottoms out
|
||||||
|
in, and the gaps this track must close (stdio byte streams, cwd, environment,
|
||||||
|
entropy) are **exactly the Phase-1 gaps the Zig roadmap already lists**. The two
|
||||||
|
tracks share a road until Python forks off at "build the libc."
|
||||||
|
|
||||||
|
## Where danos stands: coverage vs. the gaps
|
||||||
|
|
||||||
|
Judged against the minimal CPython configuration (static, WASI-like):
|
||||||
|
|
||||||
|
| CPython need | danos today | Gap |
|
||||||
|
|--------------|-------------|-----|
|
||||||
|
| open/read/write/close/lseek, readdir | VFS + FAT via `runtime.fs` | none — wrap in C |
|
||||||
|
| mkdir / unlink / rename / truncate | done (self-hosting Phase 2) | none |
|
||||||
|
| stat with mtime | done (`wall_clock` + FAT mtime) | none |
|
||||||
|
| mmap/munmap (object allocator) | native syscalls | none |
|
||||||
|
| monotonic + wall clock | `clock` + `wall_clock` syscalls | none |
|
||||||
|
| a place for `Lib/` | FAT boot image | none — better than WASI has it |
|
||||||
|
| fork / exec | not needed (subprocess disabled at first) | — |
|
||||||
|
| dynamic loading | not needed (static extension modules) | — |
|
||||||
|
| getcwd / chdir | — | **missing** (shared with Zig Phase 1) |
|
||||||
|
| environment variables | `Init` has no env | **missing** (can start empty) |
|
||||||
|
| entropy | — | **missing** (hash seed; `PYTHONHASHSEED` pins it meanwhile) |
|
||||||
|
| byte-stream stdin/stdout (fd 0/1/2) | `debug_write` out; structured `InputEvent` in | **missing** (shared with Zig Phase 1; the REPL needs it) |
|
||||||
|
| signals | — | stubs suffice (WASI precedent); M17 signals-over-IPC maps on later |
|
||||||
|
| threads | native `thread_spawn`/futex | build threadless first; a pthread subset later (xonsh needs it) |
|
||||||
|
|
||||||
|
The clustering repeats the Zig roadmap's: **files, memory, and time are done; the
|
||||||
|
work is the C packaging plus the small seam pieces** (tty bytes, cwd, env, entropy).
|
||||||
|
|
||||||
|
## The libc decision: hand-rolled in Zig, computation lifted from musl
|
||||||
|
|
||||||
|
Two viable shapes were considered:
|
||||||
|
|
||||||
|
| Option | What it is | Verdict |
|
||||||
|
|--------|-----------|---------|
|
||||||
|
| **Mini-libc in Zig** | C-ABI-exporting Zig library over `runtime.os`/`runtime.fs`, shipped as headers + `libc.a`. | **Take this.** Reuses the danos-native surface directly; no Linux assumptions to fight. |
|
||||||
|
| **Port musl** | Full musl with a danos syscall backend. | Defer, again. musl assumes Linux syscall semantics in places; heavier than the need. |
|
||||||
|
|
||||||
|
The trick that makes the mini-libc tractable: musl's `string/`, `math/` (libm —
|
||||||
|
CPython needs essentially all of it), and number-conversion layers are **pure
|
||||||
|
computation with no syscalls**. Lift those wholesale (MIT-licensed, designed to
|
||||||
|
compile standalone) and hand-write only:
|
||||||
|
|
||||||
|
- the OS-facing bottom: fds, `mmap`, clocks, `exit`, `getcwd` — thin C-ABI wrappers
|
||||||
|
over `runtime.os`;
|
||||||
|
- a `FILE*` stdio layer (buffered, over the fd layer);
|
||||||
|
- `malloc` over danos `mmap` (a simple allocator is fine; CPython does its own
|
||||||
|
small-object arena management above it);
|
||||||
|
- the headers (`stdio.h`, `stdlib.h`, `string.h`, `math.h`, `errno.h`, …).
|
||||||
|
|
||||||
|
Estimate: **100–150 functions**, of which the hard 40% (libm, string, printf/strtod
|
||||||
|
cores) are lifted, not written. Correctness hot spots are `strtod`/`dtoa` (Python's
|
||||||
|
float repr round-trips through them) — another reason to lift musl's, not improvise.
|
||||||
|
|
||||||
|
## C interop: static extension modules, not ctypes
|
||||||
|
|
||||||
|
"Python can interface with C libraries" is true on danos with one important
|
||||||
|
correction: **`ctypes` does not work at first** — it is built on `dlopen` + libffi,
|
||||||
|
both of which arrive only with the [dynamic-libraries](dynamic-libraries.md)
|
||||||
|
milestone (D2). Until then the interop story is the other, older one:
|
||||||
|
|
||||||
|
- **Extension modules statically linked into the interpreter** via CPython's
|
||||||
|
`Modules/Setup` mechanism (the standard route for embedded/static builds).
|
||||||
|
- **Zig speaks C ABI natively**, so danos extension modules are written in Zig
|
||||||
|
against `Python.h` — no C required. Two modules are planned from the start:
|
||||||
|
- **`danos`** — the system module: endpoints, send/receive, capability passing,
|
||||||
|
spawn, exit notification. This is what makes a Python *service* possible: an
|
||||||
|
event loop over IPC, speaking the same wire protocols as Zig services.
|
||||||
|
- **UI toolkit bindings** — the in-progress danos UI toolkit exposed to Python,
|
||||||
|
so application prototypes drive real windows.
|
||||||
|
|
||||||
|
The package story follows: **pure-Python packages work** (unpack into
|
||||||
|
`Lib/site-packages` on the FAT image); packages with C extensions must be
|
||||||
|
cross-compiled and baked into the interpreter — a curated set chosen per image,
|
||||||
|
not `pip install`. That is the honest shape of the stop-gap.
|
||||||
|
|
||||||
|
## The roadmap
|
||||||
|
|
||||||
|
### Phase 0 — Toolchain + libc bring-up
|
||||||
|
|
||||||
|
`zig cc -target x86_64-freestanding-none` plus `-isystem` the danos headers and the
|
||||||
|
mini-libc archive. No compiler fork required — this track deliberately avoids the
|
||||||
|
Zig roadmap's Phase-0 gate (if the fork lands first, the triple becomes a clean
|
||||||
|
`x86_64-danos`; nothing else changes). Exit criterion: a **hello-world C program**
|
||||||
|
compiles on the host and runs on danos, printing via the libc's `write`.
|
||||||
|
|
||||||
|
### Phase 1 — The shared seam pieces
|
||||||
|
|
||||||
|
The same list as Zig self-hosting Phase 1, closed once for both tracks:
|
||||||
|
|
||||||
|
- fd 0/1/2 as console **byte** streams (output exists as `debug_write`; input is a
|
||||||
|
new small thing — cooked line input first, raw mode when the REPL wants editing);
|
||||||
|
- `getcwd`/`chdir`;
|
||||||
|
- environment variables (an empty block is a valid start);
|
||||||
|
- an entropy syscall or service (until then, builds pin `PYTHONHASHSEED`).
|
||||||
|
|
||||||
|
### Phase 2 — Cross-compile CPython, minimal configuration
|
||||||
|
|
||||||
|
Pin one CPython release (3.13 — strongest WASI-era cross-compile support). The
|
||||||
|
mechanics are well-trodden upstream since 3.11:
|
||||||
|
|
||||||
|
- a same-version **build-Python on the host** (`--with-build-python`);
|
||||||
|
- a `config.site` cache answering what configure cannot probe cross
|
||||||
|
(`ac_cv_file__dev_ptmx=no` and friends);
|
||||||
|
- a `config.sub` patch so `x86_64-unknown-danos` parses;
|
||||||
|
- `--disable-shared`, static `Modules/Setup` with a minimal module set
|
||||||
|
(`posix`, `errno`, `_io`, `_codecs`, `time`, `math`, …);
|
||||||
|
- `Lib/` shipped on the FAT image; `PYTHONHOME` pointed at it.
|
||||||
|
|
||||||
|
Exit criterion: `python -c 'print(2**100)'` runs on danos under QEMU.
|
||||||
|
|
||||||
|
### Phase 3 — Terminal + REPL: the first real application
|
||||||
|
|
||||||
|
Depends on the display track's font rendering (already its stated next step) and
|
||||||
|
Phase 1's tty. A terminal emulator drawing a `python` REPL is the milestone demo:
|
||||||
|
interactive, self-evidently real, and it needs **zero** process-control machinery.
|
||||||
|
|
||||||
|
### Phase 4 — The `danos` module and Python services
|
||||||
|
|
||||||
|
Write the `danos` extension module and the UI-toolkit bindings; prototype one real
|
||||||
|
service in Python (a policy-shaped one — e.g. hot-plug policy or a settings
|
||||||
|
service) speaking the existing IPC protocols. This is the payoff phase for
|
||||||
|
"prototyping a service or application."
|
||||||
|
|
||||||
|
### Phase 5 — Process control, then the shell
|
||||||
|
|
||||||
|
The shell — any shell, in any language — forces the surface danos has deferred so
|
||||||
|
far: **exec-of-path, argv/envp passing, numeric exit status (`WEXITSTATUS`, not the
|
||||||
|
categorical `ExitReason`), fd inheritance, and pipes.** That is a kernel/VFS
|
||||||
|
milestone cluster of its own. Then, in order:
|
||||||
|
|
||||||
|
1. `subprocess` enabled in CPython (maps onto danos spawn — see below);
|
||||||
|
2. a **small Python shell** (a few hundred lines over `subprocess` + line input, no
|
||||||
|
job control) — the forcing function that reveals which process-control pieces
|
||||||
|
actually matter;
|
||||||
|
3. **explicitly deferred:** a pthread subset over `thread_spawn`/futex
|
||||||
|
(create/join/mutex/condition/thread-locals), signals via M17 signals-over-IPC,
|
||||||
|
termios job control — and then **xonsh**, which wants all three.
|
||||||
|
|
||||||
|
### The spawn model fits
|
||||||
|
|
||||||
|
One genuinely good alignment: **CPython does not need fork.** `subprocess` maps
|
||||||
|
cleanly onto a posix_spawn-style model — exactly what danos has — and the existing
|
||||||
|
exit-notification-via-endpoint is a *better* fit for `Popen.wait` than Unix's
|
||||||
|
`wait` semantics. `os.fork` simply won't exist, as on Windows, and almost nothing
|
||||||
|
in practice cares.
|
||||||
|
|
||||||
|
## Risks and gotchas
|
||||||
|
|
||||||
|
- **Binary size — and the size doctrine that makes it acceptable.** danos's
|
||||||
|
leanness mandate applies to the **operating system**: the kernel and the system
|
||||||
|
services stay small (the kernel is measured in kilobytes, not megabytes), and
|
||||||
|
nothing in this track changes that — Python never enters the OS layer. An
|
||||||
|
**application** budget is different: a statically-linked CPython with its
|
||||||
|
module set will be tens of megabytes in ReleaseSafe (the measured ~2×
|
||||||
|
safety-check factor compounds it), and that is *allowed* — applications live
|
||||||
|
on the FAT image, not in the kernel's world. It still shapes the image, and it
|
||||||
|
means every Python service shares one interpreter binary + per-service
|
||||||
|
scripts, so the spawn model needs **argv** before "run this .py" works at all.
|
||||||
|
- **FAT mtime granularity is 2 seconds.** CPython's `.pyc` cache validation is
|
||||||
|
mtime-based by default; a rapid edit-run cycle can see stale bytecode. Use
|
||||||
|
hash-based `.pyc` invalidation (PEP 552, `--invalidation-mode checked-hash` at
|
||||||
|
freeze time) or accept the quirk during bring-up.
|
||||||
|
- **FAT name lookups are case-insensitive.** Long file names preserve case but
|
||||||
|
match insensitively — the same world Python inhabits on Windows/macOS, so
|
||||||
|
importlib copes, but two modules differing only by case cannot coexist on the
|
||||||
|
image.
|
||||||
|
- **`strtod`/float repr correctness.** Python's float round-tripping is exacting;
|
||||||
|
lift musl's conversions rather than writing them, and run CPython's float tests
|
||||||
|
early.
|
||||||
|
- **Threadless build is load-bearing, initially.** Like WASI, the first builds have
|
||||||
|
no working `threading`. The escape hatch is real (danos has native threads and
|
||||||
|
futexes; a pthread subset is Phase-5 work) but keep the configuration honestly
|
||||||
|
single-threaded until then.
|
||||||
|
- **The test suite is the porting harness.** CPython ships its own conformance
|
||||||
|
suite; getting `test_builtin`, `test_int`, `test_float`, `test_io` running on
|
||||||
|
danos early converts "it seems to work" into a checklist. Budget image space for
|
||||||
|
the test `Lib/` tree during bring-up.
|
||||||
|
- **Entropy before exposure.** `PYTHONHASHSEED=0` is fine for bring-up and wrong
|
||||||
|
forever; hash randomization exists because attacker-controlled dict keys are a
|
||||||
|
denial-of-service vector. Land the entropy source before any Python service
|
||||||
|
parses external input.
|
||||||
|
|
||||||
|
## Related
|
||||||
|
|
||||||
|
- [python-on-danos-milestones.md](python-on-danos-milestones.md) — the execution
|
||||||
|
plan (P0–P5) for this note.
|
||||||
|
- [c-library-compatibility.md](c-library-compatibility.md) — the mini-libc
|
||||||
|
(libdanos-c) design behind Phase 0.
|
||||||
|
- [character-devices-and-tty.md](character-devices-and-tty.md) — the stream-node /
|
||||||
|
console / no-pty design behind Phase 1.
|
||||||
|
- [zig-self-hosting.md](zig-self-hosting.md) — the sibling track; shares Phase 1,
|
||||||
|
diverges at the libc.
|
||||||
|
- [os-development/syscall.md](os-development/syscall.md) — the kernel ABI the
|
||||||
|
mini-libc bottoms out in.
|
||||||
|
- [os-development/vdso.md](os-development/vdso.md) — the public ABI boundary the
|
||||||
|
`danos` extension module wraps.
|
||||||
|
- [os-development/sysv.md](os-development/sysv.md) — the entry stack (argv/envp)
|
||||||
|
the spawn-argv work extends.
|
||||||
|
- [device-driver-development/ipc.md](device-driver-development/ipc.md) — the IPC
|
||||||
|
surface Python services speak.
|
||||||
|
- [file-system-development/file-system-hierarchy.md](file-system-development/file-system-hierarchy.md)
|
||||||
|
— where `Lib/` and `site-packages` land on the image.
|
||||||
@@ -0,0 +1,584 @@
|
|||||||
|
# Security track execution plan: paths, protocol namespace, SMEP/SMAP
|
||||||
|
|
||||||
|
The design is settled in
|
||||||
|
[communication.md](os-development/communication.md),
|
||||||
|
[protocol-namespace.md](os-development/protocol-namespace.md),
|
||||||
|
[file-system-hierarchy.md](file-system-development/file-system-hierarchy.md),
|
||||||
|
and [smep-smap.md](os-development/smep-smap.md). This file is the build order
|
||||||
|
— one phase at a time, each phase green before the next starts. Delete or
|
||||||
|
archive this file when the last milestone lands.
|
||||||
|
|
||||||
|
**Context a fresh session should read first:** the four design docs above,
|
||||||
|
then this plan's *Settled decisions* section — those decisions came out of a
|
||||||
|
full-code grounding pass (2026-07-31) and must not be re-derived or reopened.
|
||||||
|
|
||||||
|
**Definition of green, every phase:** `zig build` clean, `zig build test`
|
||||||
|
clean, `python3 test/qemu_test.py` passes (existing scenarios plus the
|
||||||
|
phase's new ones — record the suite count in the checkbox), and the relevant
|
||||||
|
design doc's status/known-gap lines updated in the same commit. Commit per
|
||||||
|
green phase, style `area: lower-case declarative summary`, **no co-author
|
||||||
|
trailers**. On a suite failure, read
|
||||||
|
`zig-out/qemu-test/<case>-failed-serial.log` before changing anything.
|
||||||
|
|
||||||
|
**Workflow:** work in a dedicated git worktree on feature branches cut from
|
||||||
|
`main` (one branch per milestone group as marked below); when a group's
|
||||||
|
phases are all green, merge to `main` and push. The loop marks a phase `[x]`
|
||||||
|
in the same commit that lands it.
|
||||||
|
|
||||||
|
**Numbering note:** milestones use the design docs' own names (PM, H1–H3,
|
||||||
|
HS, P1–P4) — the M-number sequence is left alone (M19–M22 are reserved by
|
||||||
|
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 | nothing — the track is complete |
|
||||||
|
| Branch carrying it | — |
|
||||||
|
| On `main` | every phase — groups 1, 2, 3 and 4 merged |
|
||||||
|
| Awaiting merge | nothing |
|
||||||
|
| Suite | 114 cases, all passing |
|
||||||
|
| Last updated | 2026-08-01 |
|
||||||
|
|
||||||
|
A checkbox below means the phase met its definition of green and was
|
||||||
|
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
|
||||||
|
- [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
|
||||||
|
- [x] **P4a** — clean protocols rebased onto `Define` (vfs, block, display, scanout, input; display's one overloaded request split per-operation and its field abuse ended, scanout's bogus 64-byte maximum deleted, directory EOF re-spelled as a nameless entry, input moved onto the service harness; new `protocol-conformance` case asks every reachable provider for `describe` and requires `-ENOSYS` for an undefined verb; suite 110/110)
|
||||||
|
- [x] **P4b** — misfit protocols rebased (device-manager, power, usb-transfer; every leading operation byte folded into the header, and with it the `device_id`/`device_token` that followed it — `Header.target` now carries the device in all three. device-manager's own `enumerate`/`subscribe` became the reserved verbs and its three `{status, reserved}` reply structs the envelope's `Status`; `ChildAdded` is one struct under two numbers, a call and an event, landing exactly on the 64-byte push floor. power's kinds became one declared event each, the input protocol's shape, so init reads *what happened* from the header; usb-transfer's control data stage moved to the packet tail in both directions, which made `Status.len` the transferred length and `actual_length` redundant. The two silent-breakage sites — init's byte-offset power parse and acpi's `message[0]` dispatch — are gone, the shutdown badge gate unchanged; three more rows in the conformance table. Suite 110/110)
|
||||||
|
- [x] **P4c** — harness subscriber lift + badge-scoped per-client integers (the
|
||||||
|
subscriber table, the reserved subscribe/unsubscribe verbs, the fan-out and the
|
||||||
|
dead-subscriber sweep are `service.Subscribers` now; input, acpi and
|
||||||
|
device-manager deleted three hand-rolled variants and their three different
|
||||||
|
ideas of when a subscriber goes away, standardizing on published exit
|
||||||
|
notifications — acpi had no sweep at all and input polled the process list on
|
||||||
|
every subscribe. The three guessable-id namespaces are scoped to the opening
|
||||||
|
badge: FAT node ids on every verb that names one, xHCI device tokens on open,
|
||||||
|
control, bulk and interrupt_subscribe, display layers on configure, fill, blit,
|
||||||
|
damage and destroy — each refusing a wrong owner with the *same* answer as an id
|
||||||
|
nobody holds. New `badge-scope` case, two processes of one fixture, every
|
||||||
|
refusal paired with a control; suite 111/111)
|
||||||
|
- [x] **merge** group 3 → main, push
|
||||||
|
- [x] **H2** — SMEP on every core (shared CPUID helper; CR4 bit 20 set in the per-CPU bring-up both the BSP and every AP run, asserted per core by the smp case; ring-0-executes-user-pages audit clean incl. the pre-paging window on the loader's tables; fail-open with a posture line; `-cpu max` added to the harness since QEMU's default model has neither bit; new `fault-smep` case; suite 112/112)
|
||||||
|
- [x] **HS** — SYSRET canonical-RIP guard (the syscall exit sign-extends the
|
||||||
|
return RIP from bit 47 and returns through `iretq` when that changes it —
|
||||||
|
four register ALU ops and a never-taken branch on the hot path, no load; the
|
||||||
|
fallback un-pops the rip slot so `iretq` consumes the frame entry already
|
||||||
|
built, reloads R11 from the rflags slot, and keeps the `swapgs` in the same
|
||||||
|
place relative to the ring change. 4-level is not an assumption but a fact:
|
||||||
|
nothing sets CR4.LA57, and the comment says what a 5-level port must change.
|
||||||
|
Ring 3 **can** reach the hazard — `syscall` as the last two bytes of the last
|
||||||
|
canonical page returns to `user_half_end` — so the new `sysret-canonical`
|
||||||
|
case is a real ring-3 probe doing exactly that, and dies of a ring-3 #GP at
|
||||||
|
`0x0000800000000000` while the kernel runs on. Its teeth are the refusal
|
||||||
|
counter, not the outcome: measured with the guard's branch removed, TCG does
|
||||||
|
not model Intel's ring-0 #GP and every outcome check still passed. Suite
|
||||||
|
113/113)
|
||||||
|
- [x] **H3** — SMAP on every core, and the boot-patched `clac` that makes it
|
||||||
|
hold. Hardware does not clear `EFLAGS.AC` on interrupt delivery and ring 3
|
||||||
|
sets it with `popfq`, so without the patch a hostile process suspends SMAP
|
||||||
|
for the length of any handler it can provoke; `clac` is #UD without the
|
||||||
|
feature, so the image ships the 3-byte canonical NOP at the first byte of
|
||||||
|
`isr_common` — ahead of the CPL test, because a fault nested in ring 0
|
||||||
|
inherits AC just as readily — and the boot processor overwrites it through
|
||||||
|
the physmap, the same door `smp.arm` and `process.run` already use to write
|
||||||
|
a page the executing mapping holds read-only. The two halves are wired
|
||||||
|
together rather than merely ordered: `initHardening` refuses CR4 bit 21
|
||||||
|
until the patch has been written *and* read back through the text address it
|
||||||
|
will be fetched from, so no core can turn SMAP on ahead of it and a
|
||||||
|
translation that lied leaves the machine unhardened and saying so instead of
|
||||||
|
enforcing over an entry path that cannot clear AC. The `smp` case now
|
||||||
|
requires SMAP on every core it lands on, which is the ordering checked from
|
||||||
|
the far end. New `fault-smap` case reads a mapped user page from ring 0 and
|
||||||
|
requires the fault: error code `0x1` — present, and nothing else, since a
|
||||||
|
SMAP violation has no bit of its own and U/S reports the ring of the access.
|
||||||
|
The suite is now the standing enforcement test, and it found nothing left to
|
||||||
|
find: H1's conversion of the nine stragglers was complete. Suite 114/114
|
||||||
|
- [x] **merge** group 4 → main, push
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Settled decisions (grounding pass, 2026-07-31 — do not reopen)
|
||||||
|
|
||||||
|
These resolve every open wrinkle the code inventory surfaced. Where one
|
||||||
|
amends a design doc, the amendment lands in the same commit as the phase
|
||||||
|
that implements it.
|
||||||
|
|
||||||
|
1. **Every packet — request, reply, and event — begins with the envelope
|
||||||
|
`Header`, exactly as the design says; the header is FOLDED, never
|
||||||
|
stacked.** It absorbs each protocol's existing operation/id fields
|
||||||
|
rather than sitting on top of them, so the two apparent 64-byte-limit
|
||||||
|
offenders fit: `ChildAdded` re-lays to 60 bytes (its packed operation
|
||||||
|
byte and `device_id` become `Header.operation`/`.target`);
|
||||||
|
`InterruptReport` puts `device_token` in `Header.target` and trims
|
||||||
|
inline data 48 → 40 bytes (largest real report today is 8). A
|
||||||
|
headerless-events variant was considered and REJECTED (2026-07-31): it
|
||||||
|
re-invents per-protocol mini-headers and breaks uniform tooling. No
|
||||||
|
design-doc amendment; `Define`'s event check stays ≤ 64 *including*
|
||||||
|
the header.
|
||||||
|
2. **Bind/open authorization is chain-attested identity: the
|
||||||
|
kernel-stamped binary name PLUS the supervision chain**, both read from
|
||||||
|
the kernel's process records (`ProcessDescriptor` carries `name` and
|
||||||
|
`supervisor`; init walks the chain with `process_enumerate` — no new
|
||||||
|
protocol). A grant row names the binary *and* the supervisor expected
|
||||||
|
in its chain, so a malicious process re-spawning a granted binary
|
||||||
|
(ungated `spawn`, hostile argv — the confused deputy) is refused: its
|
||||||
|
chain roots at the attacker, not at init or device-manager. Name alone
|
||||||
|
is NOT sufficient — that was considered and rejected (2026-07-31).
|
||||||
|
Pure delegation (device-manager forwarding driver binds as
|
||||||
|
capabilities — "option B") is deliberately deferred to P5, whose
|
||||||
|
spawner-wired namespaces subsume it. Amends protocol-namespace.md's
|
||||||
|
"Authorization" bullet in P2.
|
||||||
|
3. **Grants live in a new manifest, `/system/configuration/protocol.csv`**
|
||||||
|
(rows: `binary-path, supervisor, bind|open, protocol-name`, where
|
||||||
|
`supervisor` is the binary expected in the caller's supervision chain —
|
||||||
|
`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
|
||||||
|
hack) becomes `/protocol/test/shared-memory`; process-test's child gets
|
||||||
|
`/protocol/test/process`.
|
||||||
|
5. **Rebind after provider death:** a `bind` hitting an existing binding
|
||||||
|
succeeds only if the current owner process is dead (init checks
|
||||||
|
liveness); otherwise `-EBUSY`. Init also unbinds in `restartChild`
|
||||||
|
before respawning its own children. This preserves collision-refusal
|
||||||
|
while making restart work for providers init does not supervise.
|
||||||
|
6. **Cross-thread service access** (the display mouse-listener's
|
||||||
|
per-thread self-lookup, `display.zig:512`): threads resolve and open
|
||||||
|
`/protocol/<name>` like any client — once, at thread startup. No
|
||||||
|
special mechanism.
|
||||||
|
7. **The envelope module is `library/protocol/envelope/envelope.zig`**
|
||||||
|
(module name `envelope`) — the one protocol-package module not ending
|
||||||
|
in `-protocol`, because it is not a protocol. Wired as a new
|
||||||
|
`addModule` row in `library/protocol/build.zig` with its host tests in
|
||||||
|
that package's test step.
|
||||||
|
8. **The QEMU harness gains `-cpu max`** (in `qemu_args`,
|
||||||
|
`test/qemu_test.py:66-83`) so TCG exposes SMEP/SMAP — without it the
|
||||||
|
enabled paths never execute in CI. Landed in H2 so the flag soaks
|
||||||
|
before H3 depends on it.
|
||||||
|
9. **Scenario fixtures that need the registry are init-driven.** Kernel
|
||||||
|
test cases that today spawn providers directly (shared-memory,
|
||||||
|
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
|
||||||
|
`/etc`; PM adds the note to file-system-hierarchy.md and moves on.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## PM — path-migration flag-day
|
||||||
|
|
||||||
|
One commit, everything moves together. The authoritative site inventory is
|
||||||
|
the grounding pass; the checklist order:
|
||||||
|
|
||||||
|
1. Move repo `etc/` → `configuration/` sources; fix the three CSVs'
|
||||||
|
self-referencing headers (`etc/init.csv:1,12`, `etc/devices.csv:1`,
|
||||||
|
`etc/init-diagnose.csv:1`).
|
||||||
|
2. `build.zig:309-311`: bundled entries `etc/...` →
|
||||||
|
`system/configuration/...` (this alone re-shapes the image, manifest,
|
||||||
|
and capsule — `tools/make-fat-image.py` and the EFI loader need
|
||||||
|
nothing; the tree-walk fallback even starts picking the CSVs up, a
|
||||||
|
bonus fix).
|
||||||
|
3. `system/kernel/vfs.zig` `mountBackend` (`:332-340`): allow exactly
|
||||||
|
`/system/configuration` and `/system/logs` as backend prefixes beneath
|
||||||
|
the initrd `/system` mount; keep refusing everything else under
|
||||||
|
`/system` and `/test`.
|
||||||
|
4. `system/services/fat/fat.zig`: `mount_point` → `/volumes/usb` (`:25`);
|
||||||
|
replace the `/var` mount (`:155`) with two `mountRewritten` calls for
|
||||||
|
`/system/configuration` and `/system/logs`; update the mount log lines
|
||||||
|
(the harness matches them).
|
||||||
|
5. `system/services/init/init.zig:76` and
|
||||||
|
`system/services/device-manager/device-manager.zig:48`: open the new
|
||||||
|
CSV paths; update the message strings (`init.zig:77,92`,
|
||||||
|
`device-manager.zig:49,61-63,454`).
|
||||||
|
6. `system/services/logger/logger.zig:44`: `base = "/system/logs"`
|
||||||
|
(buffers derive from `base.len` comptime — nothing else changes).
|
||||||
|
7. `system/kernel/tests.zig:2808-2810`: exclude `/system/configuration/`
|
||||||
|
from the spawn-everything sweep (the CSVs are not programs).
|
||||||
|
8. Tests: `fat-test.zig` and `vfs-test.zig` `/mnt/usb` literals →
|
||||||
|
`/volumes/usb`; harness regexes `test/qemu_test.py:175,211,632,717`.
|
||||||
|
9. Comment sweep (init, device-manager, logger, fat, engine, vfs, abi,
|
||||||
|
file-system, csv, device, protocol/device-manager, drivers, acpi,
|
||||||
|
build.zig — full list in the grounding inventory); delete vestigial
|
||||||
|
repo `var/`.
|
||||||
|
|
||||||
|
**Test:** no new case — the existing 106 are the test, since fat/logger/
|
||||||
|
init/device-manager scenarios all assert the new paths through their
|
||||||
|
regexes. Suite stays 106.
|
||||||
|
|
||||||
|
## H1 — user-memory copy discipline
|
||||||
|
|
||||||
|
New kernel module `system/kernel/user-memory.zig`:
|
||||||
|
|
||||||
|
- `copyFromUser` moves from ipc-synchronous.zig (which re-exports or
|
||||||
|
imports it); new `copyToUser(user_as, user_va, source) bool` — the
|
||||||
|
mechanical mirror (kernel-source `copyAcross` already does this for IPC
|
||||||
|
replies at `ipc-synchronous.zig:431,460`).
|
||||||
|
- The page walk gains leaf U/S and writable checks: `paging.translateIn`
|
||||||
|
(`architecture/x86_64/paging.zig:513-525`) tests only `present` today —
|
||||||
|
add a flags-accumulating variant (2 MiB leaves included); reads require
|
||||||
|
U/S, writes require U/S+W. Closes the TODO at
|
||||||
|
`ipc-synchronous.zig:20-22`.
|
||||||
|
- Convert the nine stragglers (table in smep-smap.md). Read direction is
|
||||||
|
local to `process.zig`; the write direction restructures callees with
|
||||||
|
kernel bounce buffers: `scheduler.enumerate` (`scheduler.zig:1209`),
|
||||||
|
`devices_broker.enumerate` (`devices-broker.zig:136`), `log.readAt`
|
||||||
|
(`log.zig:209`), and the `fs_node` flows through
|
||||||
|
`vfs.nodeRead/nodeStatus/nodeReaddir` (`vfs.zig:257/269/289`).
|
||||||
|
|
||||||
|
**Test:** kernel unit coverage in `system/kernel/tests.zig` for
|
||||||
|
`copyToUser` bounds/permission refusals; one new QEMU case `user-memory` —
|
||||||
|
a fixture passes an unmapped-but-in-range buffer to `klog_read`,
|
||||||
|
`process_enumerate`, and `fs_resolve` and asserts `-EFAULT` returns with
|
||||||
|
the system still alive (today each would oops the kernel). Suite 107.
|
||||||
|
|
||||||
|
## P1 — envelope, vfs additions, Channel
|
||||||
|
|
||||||
|
- `library/protocol/envelope/envelope.zig`: `Header` {operation:u32, pad,
|
||||||
|
target:u64}, `Status`, reserved verbs (describe=0, enumerate=1,
|
||||||
|
subscribe=2, unsubscribe=3, protocol verbs from 16), `packet_maximum`
|
||||||
|
= 256 / `post_maximum` = 64 (the floor constants protocols compile
|
||||||
|
against — nothing exports them today), and comptime
|
||||||
|
`Define(.{name, version, operations, events})` generating request/reply
|
||||||
|
types, encode/decode, a provider dispatch table (automatic `describe`,
|
||||||
|
`-ENOSYS` for unknown verbs), and compile-time size checks:
|
||||||
|
request/reply ≤ 256, each `.events` entry ≤ 64 *including* its Header
|
||||||
|
(decision 1). Host unit tests in the protocol package's test step.
|
||||||
|
- `library/protocol/vfs/vfs-protocol.zig`: `NodeKind.protocol = 7`; the
|
||||||
|
open-reply-may-carry-capability convention documented in the module.
|
||||||
|
Rewrite the value-pinning unit test (`:108-117`) to pin the *new*
|
||||||
|
stable values.
|
||||||
|
- `library/kernel/file-system.zig` + a new `Channel` type in
|
||||||
|
`library/kernel` (or `library/client`): `open("/protocol/<name>")` →
|
||||||
|
resolve, vfs open, receive the reply capability → a `Channel` wrapping
|
||||||
|
the handle with `call`/typed helpers. Nothing uses it yet — P2 converts
|
||||||
|
the world.
|
||||||
|
- Docs: vfs-protocol.md's NodeKind table gains value 7 (no
|
||||||
|
protocol-namespace.md amendment — decision 1 conforms to it as written).
|
||||||
|
|
||||||
|
**Test:** host unit tests only (envelope round-trips, size-check compile
|
||||||
|
errors via `error` tests, Channel plumbing against a mock). Suite stays
|
||||||
|
107.
|
||||||
|
|
||||||
|
## P2 — the registry; ServiceId flag-day
|
||||||
|
|
||||||
|
The single biggest phase; one branch, may be several commits, green at the
|
||||||
|
end of each.
|
||||||
|
|
||||||
|
- **init as registry backend** (`system/services/init/init.zig`): a second
|
||||||
|
endpoint (the supervision endpoint's reply-empty loop is unsuitable for
|
||||||
|
a vfs backend); serve vfs `open`/`readdir` over `/protocol` plus the
|
||||||
|
`bind` operation (name payload + capability). Mount `/protocol` before
|
||||||
|
spawning children. Parse `/system/configuration/protocol.csv`
|
||||||
|
(decision 3). Authorization by chain-attested identity (decision 2):
|
||||||
|
badge → kernel process records → binary name **and** supervision chain
|
||||||
|
(walk `supervisor` links) checked against the grant row's expected
|
||||||
|
supervisor. Unbind on child death in `restartChild`; dead-owner rebind
|
||||||
|
rule (decision 5).
|
||||||
|
Provenance: readdir/diagnostics show name → pid → binary path.
|
||||||
|
- **Kernel:** reserve `/protocol` — `mountBackend` refuses mounts at or
|
||||||
|
under it once bound, `installMount`'s remount-replace path refuses it,
|
||||||
|
and `fs_unmount` refuses it (`vfs.zig:164-181,332-351`,
|
||||||
|
`process.zig:1879-1889`). First mount wins (init is PID 1).
|
||||||
|
- **Harness:** `library/kernel/service.zig` `Callbacks.service:
|
||||||
|
?abi.ServiceId` becomes a protocol name; the register call (`:49-51`)
|
||||||
|
becomes bind-with-retry via the registry.
|
||||||
|
- **Flag-day conversion** — all 11 registration sites and 17 lookup sites
|
||||||
|
from the grounding inventory: providers (input:123, ps2-bus:223,
|
||||||
|
device-manager:569, acpi:193, usb-xhci-bus:676, usb-storage:205,
|
||||||
|
fat:307, display:699, virtio-gpu:550, shared-memory-server:43,
|
||||||
|
process-test:130 → `/protocol/test/...` per decision 4); clients
|
||||||
|
(input-client:53, display-client:28, driver.zig:173, usb.zig:139,
|
||||||
|
block.zig:72+87, ps2-bus keyboard:35 + mouse:34, virtio-gpu:478,
|
||||||
|
display:314+512 (decision 6), acpi:212, init:218+245 — init
|
||||||
|
short-circuits its own registry, shared-memory-client:22,
|
||||||
|
process-test:85, device-list:22, crash-test:32). Retry loops keep their
|
||||||
|
cadence, wrapping resolve+open instead of lookup.
|
||||||
|
- **Delete:** `abi.zig:36-37` (syscall ids — leave holes),
|
||||||
|
`abi.zig:287-303` (enum), `process.zig:223-224,314-343`,
|
||||||
|
`ipc-synchronous.zig:41-43,646-664` and the registry sweep in
|
||||||
|
`:121-140`; the wrappers `library/kernel/ipc.zig:33-35,47-50`; comment
|
||||||
|
sweep (irq.zig:50, tests.zig:3744, vdso.md's syscall table, the docs
|
||||||
|
list in the inventory).
|
||||||
|
- Kernel-spawned test scenarios made init-driven where they need the
|
||||||
|
registry (decision 9).
|
||||||
|
|
||||||
|
**Test:** new QEMU case `protocol-registry`: a fixture asserts (a) bind of
|
||||||
|
an ungranted name → `-EPERM`, (b) bind collision with a live owner →
|
||||||
|
`-EBUSY`, (c) provider kill → re-resolve reaches the restarted instance.
|
||||||
|
Every existing scenario doubles as conversion proof. Suite 108.
|
||||||
|
|
||||||
|
## P3 — open grants (restriction stage one)
|
||||||
|
|
||||||
|
- `protocol.csv` `open` rows enforced in the registry's `open` handler,
|
||||||
|
same name-based identity as bind. Default rows grant what today's
|
||||||
|
clients need (from the P2 conversion table); a deliberate hole for the
|
||||||
|
test fixture.
|
||||||
|
- Docs: protocol-namespace.md stage-one section gets its "landed" line.
|
||||||
|
|
||||||
|
**Test:** new QEMU case `protocol-denied`: a fixture granted
|
||||||
|
`/protocol/test/shared-memory` but not `/protocol/display` asserts open of
|
||||||
|
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
|
||||||
|
directly (grounding inventory §1,3,4,6,8):
|
||||||
|
|
||||||
|
- vfs: `node` → `target`; `Reply.node` (open's result) moves to reply
|
||||||
|
payload — `library/kernel/file-system.zig` decoders change; readdir
|
||||||
|
stays a protocol verb.
|
||||||
|
- block: pure renumber; `attach`'s DMA cap rides the call as today.
|
||||||
|
- display: the overloaded 40-byte `Request` becomes per-operation structs
|
||||||
|
(attach_scanout's field abuse dies); `layer` → `target`; blit payload
|
||||||
|
grows to 224 bytes.
|
||||||
|
- scanout: renumber; drop its bogus `message_maximum=64` (sync floor is
|
||||||
|
256); fix virtio-gpu's hard-coded `service.run(256, …)` to the
|
||||||
|
generated constant.
|
||||||
|
- input: subscribe merges into reserved subscribe; publish renumbers;
|
||||||
|
the event re-lays onto the Header folded (operation = event kind,
|
||||||
|
target = 0; 16 + 28-byte payload = 44 ≤ 64); **input moves onto the
|
||||||
|
service harness** (it is the last hand-rolled loop, no ping/terminate
|
||||||
|
compliance today).
|
||||||
|
|
||||||
|
**Test:** new QEMU case `protocol-conformance`: a fixture opens every
|
||||||
|
registered protocol and asserts `describe` answers (name, version) and an
|
||||||
|
unknown verb returns `-ENOSYS`. Existing input/display/fat scenarios prove
|
||||||
|
the rebase. Suite 110.
|
||||||
|
|
||||||
|
## P4b — misfit protocols onto Define
|
||||||
|
|
||||||
|
device-manager, power, usb-transfer (inventory §2,5,7 — the u8-operation
|
||||||
|
re-layouts and raw-offset readers):
|
||||||
|
|
||||||
|
- device-manager: u8 operations → Header; its enumerate=4/subscribe=5
|
||||||
|
merge into the reserved verbs; `ChildAdded` splits its dual role —
|
||||||
|
request struct and event, both Header-first (folded to 60 B ≤ 64);
|
||||||
|
`ChildRemoved`'s (parent, bus_address) addressing stays payload.
|
||||||
|
- power: u8 operations → Header; subscribe merges; **init's raw
|
||||||
|
byte-offset event parsing (`init.zig:171-173`) and acpi's
|
||||||
|
`message[0]` dispatch (`acpi.zig:435-467`) are rewritten against the
|
||||||
|
generated types** — the two silent-breakage sites, called out so the
|
||||||
|
loop treats them as first-class conversions, not collateral.
|
||||||
|
- usb-transfer: `device_token` → `target` (already layout-identical);
|
||||||
|
`InterruptReport` re-lays onto the Header (`device_token` → `target`,
|
||||||
|
inline data trimmed 48 → 40 — largest real report is 8); control/bulk
|
||||||
|
budgets re-verified by `Define` (Status absorbs `actual_length`).
|
||||||
|
|
||||||
|
**Test:** existing scenarios are the proof (device hot-add, power button,
|
||||||
|
USB storage/HID all exercise these wires); the conformance case now covers
|
||||||
|
three more providers. Suite 110.
|
||||||
|
|
||||||
|
*Landed. Three judgment calls the plan left open, recorded because a reader of
|
||||||
|
the wire formats will want them:*
|
||||||
|
|
||||||
|
- *`ChildAdded` is 48 bytes, not the 44 the "60 B" estimate assumed: three `u64`s
|
||||||
|
give the struct eight-byte alignment, so 41 bytes of content round up whatever
|
||||||
|
order the fields sit in. The packet is therefore **exactly** 64 — on the push
|
||||||
|
floor, not under it — which `Define` accepts and the module pins in a test. The
|
||||||
|
fields are ordered small-tail-last deliberately, so the slack the rounding pays
|
||||||
|
for is where the small ones live.*
|
||||||
|
- *power's events are declared **per kind** (`power_button`, `lid`, `ac`,
|
||||||
|
`battery`, `notify`), not one `event` with the kind in the payload. That is the
|
||||||
|
shape P4a gave input — "the class is the header's operation, so a subscriber
|
||||||
|
reads the kind from the packet rather than from a tag inside the payload" — and
|
||||||
|
it is what makes `Header.operation` carry information here at all. It also kept
|
||||||
|
every call site's spelling: `Protocol.Event` is re-exported as the protocol's
|
||||||
|
own `Event`, with the members it always had.*
|
||||||
|
- *the conformance case still checks two providers, and the three new rows report
|
||||||
|
as unbound. All three P4b contracts arrive with the device manager — it is the
|
||||||
|
first, it spawns the discovery service that binds the second, and the xHCI
|
||||||
|
driver that binds the third — so booting one means booting the driver tree, and
|
||||||
|
the fixture takes **one snapshot** of `/protocol`: a scenario whose bound set
|
||||||
|
depends on how far that tree got would make the case's own summary line a boot
|
||||||
|
race. The rows still earn their place — a future scenario that binds one gets it
|
||||||
|
checked with no edit here, and `/test/*` already holds the `open` grant for
|
||||||
|
`device-manager`.*
|
||||||
|
|
||||||
|
## P4c — harness subscriber lift + badge scoping
|
||||||
|
|
||||||
|
- `library/kernel/service.zig` grows the subscriber table, exit-
|
||||||
|
notification sweep, and fan-out loop declared via `Define(.events)`;
|
||||||
|
input (:33-116), acpi (:67-68,393-406), and device-manager (:155-166)
|
||||||
|
delete their hand-rolled variants. One sweep idiom: exit notifications
|
||||||
|
(fat's pattern), replacing input's process-list polling and acpi's
|
||||||
|
none-at-all.
|
||||||
|
- Badge-scoped per-client integers (the guessable-id holes): fat node ids
|
||||||
|
gain owner checks on every operation (`fat.zig:72-76`), xhci device
|
||||||
|
tokens validate sender and sweep on exit (`usb-xhci-bus.zig:66-88,479`),
|
||||||
|
display layers gain an owner field.
|
||||||
|
|
||||||
|
**Test:** extend the fat scenario: a second fixture guesses the first's
|
||||||
|
node id and asserts refusal; kernel-side unit test for the harness sweep.
|
||||||
|
Suite 111.
|
||||||
|
|
||||||
|
*Landed. Four things the plan had not foreseen:*
|
||||||
|
|
||||||
|
- *One sweep idiom means one more kernel subscriber per provider, and the kernel's
|
||||||
|
published-exit table held **eight**. A normal boot now fields six (fat, input,
|
||||||
|
power, device-manager, display, and one per xHCI controller), so the table grew
|
||||||
|
to sixteen. It is not a table anyone notices until a service silently loses its
|
||||||
|
sweep, which is exactly the failure the old ceiling was two subscriptions away
|
||||||
|
from.*
|
||||||
|
- *The device manager hears each of its drivers die **twice** now — it is both the
|
||||||
|
supervisor its spawn named and, through the harness, a subscriber to published
|
||||||
|
exits — and the notify ring delivers the two badges separately. Untreated, one
|
||||||
|
death counted as two: the restart backoff doubled and the crash-loop cap fired
|
||||||
|
at half the deaths it names. `onDriverExit` therefore retires the dead process
|
||||||
|
id before it decides anything, and the second notification finds nothing to act
|
||||||
|
on. (The `driver-restart` and `pci-scan` drills are what would have caught it.)*
|
||||||
|
- *Refusal-equals-absence has a corollary for the verbs that **release**: FAT's
|
||||||
|
`close` used to answer 0 for an unknown node, so scoping it had to change that
|
||||||
|
too — a foreign node and a free one both answer `-ENOENT`, or the pair would
|
||||||
|
have been an oracle for which ids are live. The same applies to the harness's
|
||||||
|
`unsubscribe`.*
|
||||||
|
- *Ownership is per **task**, not per process, because the badge is: the kernel
|
||||||
|
stamps the sending thread's id, which is already the granularity of the exit
|
||||||
|
sweep that releases the state (a worker thread's death releases the handles that
|
||||||
|
worker opened). Nothing in the tree shares an id across its own threads today;
|
||||||
|
a per-process notion would need the kernel to stamp the leader, and belongs with
|
||||||
|
P5's spawner-wired namespaces if it is ever wanted.*
|
||||||
|
|
||||||
|
## H2 — SMEP
|
||||||
|
|
||||||
|
- Generalize the cpuid helper (`apic.zig:351-365`, private, subleaf-0) to
|
||||||
|
a shared probe; gate on `cpuid(0).eax >= 7`.
|
||||||
|
- Set CR4 bit 20 in `per-cpu.zig:initSystemCall` (or a sibling called
|
||||||
|
from both `cpu.zig:148` and `smp.zig:181` — the one path both BSP and
|
||||||
|
every AP already execute). Log enabled/absent (fail-open, IOMMU style).
|
||||||
|
- Harness: add `-cpu max` to `qemu_args` (decision 8).
|
||||||
|
|
||||||
|
**Test:** new QEMU case `fault-smep` mirroring the `fault-*` injector
|
||||||
|
pattern (`tests.zig:3906-3938`): ring-0 call through a pointer into a
|
||||||
|
user-mapped page; expect `page fault (vector 14)` + `error code : 0x11` +
|
||||||
|
kernel-half IP, machine reports the exception (deliberate-exception cases
|
||||||
|
put the text in `expect`, per `qemu_test.py:189`). Suite 112.
|
||||||
|
|
||||||
|
## HS — SYSRET canonical-RIP guard
|
||||||
|
|
||||||
|
- `isr.s` syscall exit (`:256`): validate RCX canonicality before
|
||||||
|
`sysretq`; non-canonical → `iretq` fallback (or kill), per the hazard
|
||||||
|
note at `isr.s:192-194`.
|
||||||
|
|
||||||
|
**Test:** kernel unit case driving a thread whose return RIP is forged
|
||||||
|
non-canonical via the syscall path if constructible cheaply; otherwise the
|
||||||
|
review-level proof plus the existing fault cases regression. Suite 112.
|
||||||
|
*(Landed: it was constructible, and from ring 3 rather than by forgery — the
|
||||||
|
`sysret-canonical` case, suite 113.)*
|
||||||
|
|
||||||
|
## H3 — SMAP
|
||||||
|
|
||||||
|
- `clac` patch site at `isr_common` (`isr.s:367`, before the CPL test —
|
||||||
|
ring-0 nesting inherits AC too): assemble a 3-byte NOP, patch to `clac`
|
||||||
|
at boot through the physmap (the `process.zig:1990-1995` /
|
||||||
|
`smp.zig:79-111` precedent), BSP-only before AP bring-up.
|
||||||
|
- Set CR4 bit 21 in the same per-CPU init as SMEP.
|
||||||
|
- Coding standards: kernel code touches user memory only through
|
||||||
|
`user-memory`; no `stac` anywhere, ever.
|
||||||
|
|
||||||
|
**Test:** new QEMU case `fault-smap`: ring-0 deliberate read of a mapped
|
||||||
|
user page; expect vector 14 + `error code : 0x1` + kernel IP. And the
|
||||||
|
whole suite becomes the tripwire — any missed straggler now fails loudly.
|
||||||
|
*(Landed: the patch site sits at the very first byte of `isr_common`, and
|
||||||
|
CR4.SMAP is refused on every core until the patch has been read back through
|
||||||
|
the text mapping it will execute from — so the ordering is enforced, not
|
||||||
|
merely documented. Error code observed: `0x1` exactly, present and nothing
|
||||||
|
else. The tripwire found no missed straggler: H1 had converted them all.)*
|
||||||
|
Suite 114 (HS added one).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Explicitly out of scope** (own tracks, after this plan): P5 restriction
|
||||||
|
stage two (spawn's initial capability, namespace views, parked replies,
|
||||||
|
dedicated killable channels — needs a design session on the spawn
|
||||||
|
contract), file-path namespacing, trusted UI (display track), pipes/FIFOs
|
||||||
|
(Python track), `/applications` and its storage, `fs_mount`/`spawn`/
|
||||||
|
`klog_read` gating beyond the `/protocol` reserved prefix, KPTI, IPC
|
||||||
|
priority inheritance.
|
||||||
@@ -0,0 +1,368 @@
|
|||||||
|
# Finishing the storage stack: the S1–S5 plan
|
||||||
|
|
||||||
|
*2026-08-09. Continues the volume-manager track (V0–V5, on main) from "one FAT
|
||||||
|
volume" to "any filesystem, any number of volumes, identified by content,
|
||||||
|
remounting where they belong, surviving a driver crash." Executes the settled
|
||||||
|
design in
|
||||||
|
[storage-architecture.md](file-system-development/storage-architecture.md) and
|
||||||
|
[storage-design-rationale.md](file-system-development/storage-design-rationale.md).
|
||||||
|
Track discipline as always: work on main; one commit per coherent step with
|
||||||
|
`git commit -F` (no `-m`, no co-author trailer); every new test shown to FAIL
|
||||||
|
against the old behavior; one QEMU suite at a time; CSV is configuration read by
|
||||||
|
the volume manager (the policy), never itself policy; bounds discipline
|
||||||
|
(`tools/check-bounds.py` gate); adversarial boundary review at each phase.*
|
||||||
|
|
||||||
|
## Where V0–V4 left it
|
||||||
|
|
||||||
|
The volume manager probes ONE storage device, parses its MBR (rung-4 identity =
|
||||||
|
`(diskSignature<<8)|index`), spawns ONE FAT service confined to that partition's
|
||||||
|
badge-scoped block range, supervises it, and unmounts it when the device is
|
||||||
|
pulled. `partition.firstVolume` returns the FIRST partition; `openAnyStorage`
|
||||||
|
adopts the FIRST device; `var volume: ?Volume` and `volume_id = 1` are singular;
|
||||||
|
`filesystem_binary` and fat's mount prefixes are hardcoded; `medium_changed` is
|
||||||
|
published by the driver but consumed by no one; remount-on-replug is
|
||||||
|
bench-pending.
|
||||||
|
|
||||||
|
## The five phases and how they depend
|
||||||
|
|
||||||
|
```
|
||||||
|
S1 identity ladder ──► S2 mount map ──► S3 multi-volume ──► S4 exFAT
|
||||||
|
(needs S2+S3)
|
||||||
|
S5 removal robustness ── independent; single-volume ── may land any time
|
||||||
|
```
|
||||||
|
|
||||||
|
- **S1** grows the identity read off the medium (GPT GUID, FAT serial+label). It
|
||||||
|
comes FIRST because a volume's mount name is now its identity (below), and the
|
||||||
|
friendly form of that name is the FAT label / GPT name S1 parses.
|
||||||
|
- **S2** moves the last policy out of hardcode into `volumes.csv` +
|
||||||
|
`filesystems.csv`, and names each volume by its identity **id** (a GUID/key),
|
||||||
|
keeping the label as separate, queryable display metadata — no port-name.
|
||||||
|
- **S3** generalizes to N volumes across N devices.
|
||||||
|
- **S4** adds exFAT — a COMPLETE second engine that proves the V1 harness
|
||||||
|
extraction. Needs S2 (to route by signature) and S3 (to run a second volume).
|
||||||
|
- **S5** closes the removal-lifecycle gaps. Independent of the rest; single-volume.
|
||||||
|
|
||||||
|
Recommended build order is S1 → S2 → S3 → S4 → S5. S5 may be pulled earlier.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## S1 — the identity ladder
|
||||||
|
|
||||||
|
**Goal.** Grow `system/services/volume-manager/partition.zig` from the single
|
||||||
|
rung-4 identity into a ladder that reads the richest available content identity:
|
||||||
|
GPT partition GUID (rung 1, 128-bit), FAT volume serial + label (rung 3), MBR
|
||||||
|
signature + index (rung 4, kept), bare-FAT (kept, enriched to its serial). The
|
||||||
|
`u64` identity becomes a small tagged struct `Identity{ rung, key: u128, label,
|
||||||
|
has_label }` — `key` is the **id** (the path handle), `label` is the **display
|
||||||
|
name** (the GPT 36-char partition name, or the FAT volume label), a separate
|
||||||
|
field per the id/name split S2 relies on. Because GPT metadata is at LBA 1 and
|
||||||
|
the entry array beyond it, and
|
||||||
|
the FAT serial is in each partition's VBR, `firstVolume` stops taking one
|
||||||
|
preloaded block-0 slice and takes a `SectorReader` (context + read-one-sector
|
||||||
|
fn, mirroring the engine's `BlockDevice` vtable) — host-testable against a
|
||||||
|
RAM-disk reader exactly as the four existing `partition.zig` tests are.
|
||||||
|
|
||||||
|
**Key touchpoints.** `partition.zig` (the `Rung`/`Identity`/`SectorReader` types;
|
||||||
|
`gptFirstVolume`; `fatIdentity`; `firstVolume` control flow — GPT authoritative,
|
||||||
|
else MBR walk skipping type-0xEE, else bare-FAT, each preferring the FAT serial
|
||||||
|
over the disk signature); `volume-manager.zig` (`Volume.identity` type; a
|
||||||
|
`ProbeReader` over the existing 512-byte bounce; the probe log prints
|
||||||
|
`identity.key`); `build.zig` (add `b.dependency("volume-manager", .{})` to the
|
||||||
|
package-test aggregation loop so the host fixtures run under root `zig build
|
||||||
|
test`). Declared bound `gpt_entry_scan_maximum = 128` with the full bounds block;
|
||||||
|
`sector_bytes`/`fat_label_bytes` named consts.
|
||||||
|
|
||||||
|
**Steps (commits).** (1) The SectorReader/Identity flag-day — pure refactor, no
|
||||||
|
new behavior, all existing tests green. (2) GPT parsing (rung 1) — protective-MBR
|
||||||
|
+ `EFI PART` signature + header CRC-32 + per-entry overflow-safe range
|
||||||
|
validation (the confinement-safety invariant the driver's clamp rests on,
|
||||||
|
extended to GPT). (3) FAT serial + label (rung 3), preferred over the disk
|
||||||
|
signature; `Identity.eql`. (4) Test wiring, `check-bounds.py`, full suite, docs,
|
||||||
|
memory.
|
||||||
|
|
||||||
|
**Discrimination.** Host: a GPT disk yields `rung==.gpt_guid` + the exact GUID
|
||||||
|
key (old code walks the 0xEE protective entry as an ordinary partition); a GPT
|
||||||
|
entry past the device is skipped, an out-of-device-only GPT returns null (the
|
||||||
|
security-boundary guard); an invalid GPT header is not a volume; a bare FAT
|
||||||
|
reports its real serial `0x12345678` not the rung-4 pseudo-signature; an
|
||||||
|
MBR+FAT partition prefers the serial over the disk signature. On-image: the
|
||||||
|
`volume-probe` QEMU regex tightens to `volume 0x0*12345678` — the boot image's
|
||||||
|
real FAT32 serial reaches the running log.
|
||||||
|
|
||||||
|
**Top risks.** Adversarial GPT input from untrusted media (huge entry counts,
|
||||||
|
bogus offsets, overflowing ranges) — mitigated by header CRC + size bounds +
|
||||||
|
`gpt_entry_scan_maximum` + per-entry overflow-safe validation under boundary
|
||||||
|
review. The `std.hash.crc` symbol in Zig 0.16 is unverified (fallback: a ~15-line
|
||||||
|
reflected CRC-32, poly `0xEDB88320`, used by both parser and fixtures so they
|
||||||
|
never drift onto magic constants).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## S2 — the mount map: volumes.csv + filesystems.csv
|
||||||
|
|
||||||
|
**Goal.** Move the last two pieces of storage policy out of hardcode into
|
||||||
|
configuration read by the volume manager, and split a volume's **id** from its
|
||||||
|
**label** (the database model: the id is the real, stable, unique key software
|
||||||
|
uses; the label is a mutable display name). `filesystems.csv` (content signature
|
||||||
|
→ filesystem binary) so the VM picks the binary from the probed signature;
|
||||||
|
`volumes.csv` (id → mount prefix, danos's fstab) as the explicit override for a
|
||||||
|
volume the user wants at a fixed path.
|
||||||
|
|
||||||
|
**The mount path IS the identity id, never a label or a port/role name.** A
|
||||||
|
volume mounts at `/volumes/<id>` — the GPT partition GUID for a GPT volume, a
|
||||||
|
`fat-<serial>` / `mbr-<sig>-<index>` form otherwise (exact rendering is an impl
|
||||||
|
detail; the point is a stable, unique, content-derived string). Because the path
|
||||||
|
is the id and never the label, two distinct volumes that happen to share a label
|
||||||
|
(`Backup`, `UNTITLED`, unlabeled) get distinct paths automatically and never
|
||||||
|
collide; only genuinely identical *ids* (dd-cloned media) hit the rationale's
|
||||||
|
duplicate-identity policy (first mounts, second suffixed and logged).
|
||||||
|
|
||||||
|
**The label is display metadata, exposed by a protocol query, not the path.** S1
|
||||||
|
reads it off the medium (FAT volume label, GPT partition name); a volume-manager
|
||||||
|
`volumes` verb returns `{ id, mount_path, label }` per volume so a future
|
||||||
|
shell/UI can show the friendly name — the id↔name split, like a table's primary
|
||||||
|
key vs its display column. (`volumes.csv` may optionally carry a chosen label
|
||||||
|
override alongside the path override, both keyed on id.) There is no
|
||||||
|
`/volumes/usb` and no `/volumes/boot`; the boot volume is detected by content (it
|
||||||
|
installs the `/system/configuration` + `/system/logs` rewrites) but is named by
|
||||||
|
its id like any other.
|
||||||
|
|
||||||
|
Parsed with `library/csv` exactly as `device-registry` parses `devices.csv`. The
|
||||||
|
VM hands the binary + volume-id + mount specs to fat at spawn (the argv channel
|
||||||
|
V3b already uses for the volume id); fat retires `fat_mounts` and reads mounts
|
||||||
|
from argv[2..].
|
||||||
|
|
||||||
|
**Key touchpoints.** New pure-logic modules `filesystem-map.zig` (parse +
|
||||||
|
`match(signature)`) and `volume-map.zig` (parse + `mountsFor(identity)` +
|
||||||
|
`derivedAnonymous`), mirroring `device-registry`, host-tested; `partition.zig`
|
||||||
|
`Volume` gains a `signature`; `volume-manager.zig` loads both tables in
|
||||||
|
`initialise`, resolves binary + mounts, spawns the chosen binary with the mount
|
||||||
|
argv; `fat.zig` deletes `fat_mounts`, parses argv[2..] into a bounded
|
||||||
|
`MountSpec` array; new `system/configuration/filesystems.csv` +
|
||||||
|
`volumes.csv`; `build.zig` bundles them; `make-fat-image.py` writes a real 4-byte
|
||||||
|
MBR disk signature so the boot volume's identity is a legible non-zero key.
|
||||||
|
|
||||||
|
**Steps (commits).** (1) partition emits a signature. (2) `filesystem-map`
|
||||||
|
parser + host tests. (3) `volume-map` parser (id→prefix override) + the id-path
|
||||||
|
deriver + the `volumes` label-query verb + host tests. (4) Ship the tables +
|
||||||
|
VM integration **behind fat's still-hardcoded mounts** (behavior-preserving —
|
||||||
|
parsers proven before consumption flips; full suite green). (5) fat consumes
|
||||||
|
argv mounts; the VM mounts the boot volume at its id-path (`/volumes/fat-12345678`,
|
||||||
|
from its serial); **migrate the fixtures + QEMU regexes off `/volumes/usb`**
|
||||||
|
(fat-test, badge-scope-test, vfs-test, and the four cases) in the same commit;
|
||||||
|
the `volume-identity-name` QEMU case (shown failing against HEAD~1); flip the
|
||||||
|
docs' pending markers.
|
||||||
|
|
||||||
|
**Discrimination.** QEMU `volume-identity-name`: the boot volume mounts at its
|
||||||
|
id-path (`/volumes/fat-12345678`, from its serial), a line the old hardcoded
|
||||||
|
`/volumes/usb` never emits; the `volumes` query returns that id paired with the
|
||||||
|
label `DANOS`. Host: two volumes sharing a label but not an id get distinct
|
||||||
|
id-paths (the collision the label-as-name approach could not resolve stably); a
|
||||||
|
`volumes.csv` override sends a mapped id to its chosen prefix; `match(.fat)`
|
||||||
|
returns the configured binary; fat's argv parser makes installed mounts a
|
||||||
|
function of argv.
|
||||||
|
|
||||||
|
**Top risks.** Step 5's blast radius — a parser/argv bug, OR the `/volumes/usb`→
|
||||||
|
id-path migration missing a fixture/regex, breaks every fat-dependent case at
|
||||||
|
once; mitigated by landing the VM half behind fat's hardcoded mounts first (step
|
||||||
|
4) and making the name migration one atomic, complete sweep. The
|
||||||
|
argv blob is 256 bytes (process.zig) — cap emitted mounts and refuse+log on
|
||||||
|
overflow. `/system/logs` is now a `volumes.csv` concern: dropping the boot
|
||||||
|
identity's rewrite rows silently stops log persistence — ship them by default
|
||||||
|
and document the boot-identity contract in the CSV header.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## S3 — multi-volume
|
||||||
|
|
||||||
|
**Goal.** Generalize from `var volume: ?Volume` / `volume_id = 1` / first-device
|
||||||
|
/ first-partition to a bounded table of volumes across a bounded table of
|
||||||
|
devices. `partition.allVolumes` returns ALL partitions; the VM adopts EVERY
|
||||||
|
mass-storage provider, probes each device's table, and for each partition spawns
|
||||||
|
one FAT confined to that partition's range (the per-sender clamp is already
|
||||||
|
built), with a distinct `/volumes/<name>` and its OWN backoff/crash-loop state.
|
||||||
|
Removal is per-device. The **boot volume is identified by content** — the FAT
|
||||||
|
process installs the `/system/configuration` + `/system/logs` rewrites only when
|
||||||
|
its own volume resolves `/system/configuration` — so it works as the 2nd
|
||||||
|
partition of the 2nd device just as the 1st of the 1st. (This clarifies the
|
||||||
|
initrd relationship: the kernel already serves `/system/configuration` +
|
||||||
|
binaries read-only from the initrd, which is what lets danos boot with NO volume
|
||||||
|
mounted; a mounted boot volume only adds writable, persistent
|
||||||
|
`/system/configuration` + `/system/logs` that shadow the initrd via
|
||||||
|
longest-prefix match.)
|
||||||
|
|
||||||
|
**Key touchpoints.** `partition.zig` `firstVolume` → `allVolumes(block0,
|
||||||
|
device_blocks, out) usize` (per-entry overflow-safe skip preserved);
|
||||||
|
`volume-manager.zig` the core refactor — `Volume` absorbs the file-global
|
||||||
|
supervision state as per-volume fields, a `StorageDevice` table owns each
|
||||||
|
adopted device's channel once, `volumes[maximum_volumes]` replaces the singleton,
|
||||||
|
a monotonic `next_volume_id`, `openAllStorage`/`adoptAndProbe`,
|
||||||
|
`gatherPresentStorage` + per-device reconcile in `pollTick`, `onHello`/
|
||||||
|
`onNotification` keyed across the table; `fat.zig` content-conditional boot
|
||||||
|
mounts; `system/kernel/vfs.zig` raise `maximum_mounts` (8 → 16) with a refreshed
|
||||||
|
bounds annotation; `make-fat-image.py` a partition-table mode; `build/images.zig`
|
||||||
|
the test disk artifacts.
|
||||||
|
|
||||||
|
**Steps (commits).** (1) `partition.allVolumes` + two-partition host test. (2)
|
||||||
|
Tables, behavior-preserving (still one device / one volume). (3) Multi-device +
|
||||||
|
multi-partition. (4) Per-volume mount naming via argv — each volume by its
|
||||||
|
id-path (from S2), one per volume, no port-name. (5) fat content-conditional
|
||||||
|
boot mounts. (6) Raise `maximum_mounts`. (7) Partitioned-image tool. (8)
|
||||||
|
`two-volume` QEMU case. (9) `boot-2nd-partition` case. (10) Adversarial review,
|
||||||
|
full suite, docs, memory.
|
||||||
|
|
||||||
|
**Discrimination.** Host: an MBR with two partitions yields two volumes with
|
||||||
|
distinct identities (old `firstVolume` returns one). QEMU `two-volume`: a
|
||||||
|
two-partition second device yields two mount lines at two base_lbas (old
|
||||||
|
`openAnyStorage` adopts only the first device). `boot-2nd-partition`: the boot
|
||||||
|
volume works as partition 2 (old code confines fat to partition 1, whose
|
||||||
|
`/system` rewrite backs empty space). Per-volume supervision: killing one
|
||||||
|
volume's FAT restarts only that one (old module-scope supervision can't
|
||||||
|
attribute an exit to one of two).
|
||||||
|
|
||||||
|
**Top risks.** OVMF booting an MBR ESP on partition 2 may be flaky in CI —
|
||||||
|
fallback to a content-detection-ordering assertion + bench-verified boot (the
|
||||||
|
track's existing precedent). N-client range reclamation in usb-storage
|
||||||
|
(`maximum_ranges=64`) must reclaim each of N confined pids' ranges — the V2
|
||||||
|
mechanism, previously exercised with one live client. Duplicate boot volumes:
|
||||||
|
S3 supports exactly one and must log loudly if a second also resolves the boot
|
||||||
|
markers (arbitration deferred to S4).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## S4 — exFAT: the second engine
|
||||||
|
|
||||||
|
**Goal.** A working exFAT filesystem as `system/services/exfat` that is nothing
|
||||||
|
but an engine + a `main`, reusing `library/kernel/file-system-harness.zig`'s
|
||||||
|
`Server(Engine)` wholesale — the reuse claim the architecture makes, now proven.
|
||||||
|
The harness already owns vfs serving, the badge-scoped open-node table,
|
||||||
|
create-on-open/O_TRUNC, mount registration, the exit sweep, bring-up retry,
|
||||||
|
per-turn time stamping, and durable-on-close. S4 writes only the exFAT-specific
|
||||||
|
bits — but **in full**: complete read AND write, directories, rename, and the
|
||||||
|
real on-disk up-case table for correct case-folding. Not a read-first, minimal-
|
||||||
|
write, or ASCII-only subset. The only limit that survives is the vfs protocol's
|
||||||
|
u32 file-offset surface (a 4 GiB addressable-size cap that applies to FAT too),
|
||||||
|
which is a separate vfs-protocol change, not an exFAT shortcut.
|
||||||
|
|
||||||
|
**Key touchpoints.** New `system/services/exfat/on-disk.zig` (the Main Boot
|
||||||
|
Sector VBR + the five 32-byte directory-entry types as `align(1)` extern structs;
|
||||||
|
`geometryOf` accepting only `"EXFAT "` + `0xAA55`; `setChecksum`, `nameHash`,
|
||||||
|
and case-folding driven by the volume's **on-disk up-case table**); `engine.zig` (`FileSystem` behind the identical `BlockDevice`
|
||||||
|
vtable with fat's exact method set; **allocation-bitmap** cluster authority — the
|
||||||
|
deepest departure from FAT; read honoring `no_fat_chain` contiguous vs FAT-follow;
|
||||||
|
File+Stream+FileName set assembly with recomputed set checksum); `exfat.zig` (the
|
||||||
|
thin service, a near-clone of fat.zig); build wiring + `service("exfat")`;
|
||||||
|
`tools/make-exfat-image.py` (pure stdlib, correct boot checksum, up-case table —
|
||||||
|
**no committed .img**); the `filesystems.csv` EXFAT row (S2) + the `"EXFAT "`
|
||||||
|
recognizer; a `exfat-test` fixture cloned from fat-test.
|
||||||
|
|
||||||
|
**Steps (commits).** (1) on-disk.zig byte layout. (2) engine read path. (3)
|
||||||
|
engine write path (bitmap allocate/free, real 32-bit FAT chain with
|
||||||
|
`no_fat_chain=0`, set-checksum recompute). (4) service + build wiring. (5)
|
||||||
|
`make-exfat-image.py` + image assembly. (6) Routing: `filesystems.csv` +
|
||||||
|
recognizer. (7) `exfat-test` fixture + **cross-engine discrimination** host test.
|
||||||
|
(8) In-VM lifecycle drill (second removable device; mount/mutations/removal). (9)
|
||||||
|
Bounds, docs, adversarial review, memory.
|
||||||
|
|
||||||
|
**Discrimination.** The named one: `fat.mount(exfat_img) == null` (fat reads
|
||||||
|
bytes-per-sector at VBR offset 11 = exFAT's MustBeZero = 0 → reject) AND
|
||||||
|
`exfat.mount(fat_img) == null`, each mounting its own as a control. Host: read
|
||||||
|
across a cluster boundary on both a contiguous and a fragmented file; write
|
||||||
|
across >1 cluster setting the bitmap bits (not the FAT) and a validating set
|
||||||
|
checksum. QEMU: `exfat: mounted /volumes/exfat` + `exfat-test: ok`;
|
||||||
|
`exfat-removal` yanks the exFAT stick mid-write while the FAT boot volume keeps
|
||||||
|
serving.
|
||||||
|
|
||||||
|
**Top risks.** Allocation authority is the bitmap, not the FAT — allocating
|
||||||
|
without setting the bit silently corrupts free space (highest-attention area).
|
||||||
|
A directory-entry SET can straddle sector/cluster boundaries — scanDirectory,
|
||||||
|
set-checksum, and updateStreamEntry must handle multi-sector sets. vfs offsets
|
||||||
|
are u32 while exFAT DataLength is u64 — clamp and document (as fat does). The
|
||||||
|
in-VM drill needs S3 (a non-boot exFAT volume beside the FAT boot volume); if S4
|
||||||
|
landed before S3 the discrimination would rest on host tests until multi-volume
|
||||||
|
exists.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## S5 — removal robustness
|
||||||
|
|
||||||
|
**Goal.** Close the three known gaps so every removal trigger is exercised
|
||||||
|
end-to-end. (1) **Consume `medium_changed`** — the VM subscribes to the driver's
|
||||||
|
already-published event so the "device stays, medium leaves" case (a card
|
||||||
|
reader, an ejected removable) runs the same kill-retire-remount path as a pulled
|
||||||
|
stick, closing the second of the "two triggers, one lifecycle" the architecture
|
||||||
|
specifies. (2) **Storage-driver-crash rebuild** — a driver that dies while its
|
||||||
|
device stays present is detected and the volume subtree rebuilt on the restarted
|
||||||
|
driver's fresh channel, instead of leaving fat wedged on a dead channel (the V4
|
||||||
|
review's open edge). (3) **QEMU-verified remount-on-replug** — the device-return
|
||||||
|
half is proven, not merely asserted-unmount. Single-volume; independent of S1–S4.
|
||||||
|
|
||||||
|
**Key touchpoints.** `library/kernel/service.zig` an additive, behavior-neutral
|
||||||
|
`on_buffered_message` callback so a buffered-message wake forwards its payload
|
||||||
|
(no existing service sets it); `volume-manager.zig` subscribe on `bringUpVolume`
|
||||||
|
success, `onMediumEvent` with change-count dedupe running a medium-teardown (with
|
||||||
|
`encodeUnsubscribe` before close so the driver's 8-slot table doesn't leak), plus
|
||||||
|
`channelAlive()` (a `geometry()` liveness probe) + `rebuildVolume()` used in
|
||||||
|
`pollTick` and the child-exit path; `fat.zig` re-probe geometry on I/O failure
|
||||||
|
and exit on channel death (device NAK keeps serving); `device-manager.zig` a
|
||||||
|
`test-storage-restart` mode (mirroring `test-scanout-restart`) to kill usb-storage
|
||||||
|
once, post-mount, as the discrimination trigger.
|
||||||
|
|
||||||
|
**Steps (commits).** (1) **Cheap decisive experiments first** (no commits): QMP-
|
||||||
|
eject the boot medium and confirm `usb-storage: medium absent` fires under QEMU
|
||||||
|
(the whole item-1 chain depends on it); and test whether a boot-controller
|
||||||
|
`device_add` is re-presented (settles whether item 3 extends `volume-removal` or
|
||||||
|
needs a second controller as H1 does). (2) Harness `on_buffered_message`
|
||||||
|
(behavior-neutral). (3) VM consumes `medium_changed`. (4) `volume-medium-change`
|
||||||
|
case (fails pre-step-3). (5) VM driver-crash rebuild. (6) fat observes dead
|
||||||
|
channel and exits. (7) `volume-driver-restart` trigger + case. (8) `volume-replug`
|
||||||
|
(second controller if needed). (9) Docs + the real-hardware bench protocol. (10)
|
||||||
|
Full suite + memory.
|
||||||
|
|
||||||
|
**Discrimination.** `volume-medium-change`: an eject with the device left in the
|
||||||
|
tree unmounts (old VM never subscribes → the event goes to no one → mount
|
||||||
|
persists). `volume-driver-restart`: killing usb-storage post-mount while its
|
||||||
|
child stays present triggers a rebuild and a SECOND mount + post-kill read (old
|
||||||
|
`pollTick` only checks `isDevicePresent`, still true, and restarts fat against
|
||||||
|
the stale channel → wedge/crash-loop). `volume-replug`: a device return on a
|
||||||
|
second controller drives a remount (the existing case only ever sees the unmount
|
||||||
|
half).
|
||||||
|
|
||||||
|
**Top risks.** QEMU medium-eject must make TEST UNIT READY report not-ready —
|
||||||
|
step 1(a) validates this before any code. The op-16 overlap (`medium_changed` ==
|
||||||
|
`hello` by number) is safe only because async events arrive as `isMessage`
|
||||||
|
notifications and never reach `Serve.dispatch` — the intercept must run in the
|
||||||
|
notification branch and never catch a synchronous hello. fat can't today
|
||||||
|
distinguish EPEER from a device NAK (`CallError` swallows the errno) — the plan
|
||||||
|
uses a geometry re-probe as the liveness oracle, which is correct but indirect.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Decisions (settled)
|
||||||
|
|
||||||
|
Both flagged decisions are settled:
|
||||||
|
|
||||||
|
1. **A volume's path is its id; the label is display metadata (S1/S2).** The
|
||||||
|
mount path is the identity id — the GPT GUID, else a `fat-<serial>` /
|
||||||
|
`mbr-<sig>-<index>` form — a stable, unique, content-derived handle software
|
||||||
|
uses. The label (FAT volume label / GPT partition name) is a mutable display
|
||||||
|
name, NOT in the path; a volume-manager `volumes` verb returns
|
||||||
|
`{ id, mount_path, label }` so a UI can show the friendly name (the database
|
||||||
|
id/name split). Same-label-different-id volumes therefore never collide; only
|
||||||
|
identical ids (dd-clones) hit first-wins-and-log. `volumes.csv` overrides the
|
||||||
|
path (and optionally the label) for a chosen volume, keyed on id. Makes S1
|
||||||
|
precede S2 and folds the `/volumes/usb` → id-path fixture + regex migration
|
||||||
|
into S2 step 5.
|
||||||
|
|
||||||
|
2. **exFAT is implemented in full (S4).** A complete exFAT: full read and write,
|
||||||
|
directories, rename, and the on-disk up-case table for correct case-folding —
|
||||||
|
not a read-first or ASCII-only subset. The one remaining limit is the vfs
|
||||||
|
protocol's u32 file-offset surface, which caps addressable file size at 4 GiB
|
||||||
|
for ALL filesystems (FAT included); widening it to u64 is a separate vfs-
|
||||||
|
protocol change, flagged but out of the exFAT engine's scope.
|
||||||
|
|
||||||
|
The ~26 smaller design-time questions are settled with the recommended default
|
||||||
|
in the phase text (defer GPT entry-array CRC to correctness-only; GUID key =
|
||||||
|
little-endian u128 pinned now; share the DOS date-time helper into a library
|
||||||
|
module both engines import; a second removable usb-storage device for the exFAT
|
||||||
|
drill; VM-poll `channelAlive()` as the load-bearing crash-detection guarantee).
|
||||||
@@ -95,9 +95,9 @@ hypervisor configured for UEFI firmware and an xHCI USB controller.
|
|||||||
|
|
||||||
| Requirement | Detail | Source |
|
| Requirement | Detail | Source |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| **x86-64, 64-bit only** | Kernel and loader are built exclusively for `x86_64`; the loader rejects any non-x86-64 kernel ELF (`error.WrongArchitecture`). | `build.zig:481`, `boot/efi.zig:622` |
|
| **x86-64, 64-bit only** | Kernel and loader are built exclusively for `x86_64`; the loader rejects any non-x86-64 kernel ELF (`error.WrongArchitecture`). | `build-support/build.zig` (`freestandingTarget`), `boot/efi.zig:622` |
|
||||||
| **Long mode + PAE + NX** | AP trampoline sets `CR4.PAE`, `EFER.LME`, `EFER.NXE`; NX is used in kernel page-table entries. | `system/kernel/architecture/x86_64/trampoline.s:62` |
|
| **Long mode + PAE + NX** | AP trampoline sets `CR4.PAE`, `EFER.LME`, `EFER.NXE`; NX is used in kernel page-table entries. | `system/kernel/architecture/x86_64/trampoline.s:62` |
|
||||||
| **SSE / SSE2** | Baseline: the compiler emits SSE for ordinary struct copies. Trampoline enables `CR4.OSFXSR` + `OSXMMEXCPT` and clears `CR0.EM`. | `build.zig:477`, `trampoline.s:62` |
|
| **SSE / SSE2** | Baseline: the compiler emits SSE for ordinary struct copies. Trampoline enables `CR4.OSFXSR` + `OSXMMEXCPT` and clears `CR0.EM`. | `build-support/build.zig` (`freestandingTarget`), `trampoline.s:62` |
|
||||||
| **`syscall` / `sysret`** | Primary user↔kernel entry path. `EFER.SCE` enabled; `STAR`/`LSTAR`/`SFMASK` programmed per core. (`int 0x80` exists as a parallel gate.) | `architecture/x86_64/per-cpu.zig:71`, `isr.s:196` |
|
| **`syscall` / `sysret`** | Primary user↔kernel entry path. `EFER.SCE` enabled; `STAR`/`LSTAR`/`SFMASK` programmed per core. (`int 0x80` exists as a parallel gate.) | `architecture/x86_64/per-cpu.zig:71`, `isr.s:196` |
|
||||||
| **Local APIC (xAPIC)** | LAPIC accessed via MMIO at `0xFEE00000`. LAPIC ID read as a `u8` — classic xAPIC. **x2APIC is not supported** (no MSR path). | `apic.zig:67`, `apic.zig:646` |
|
| **Local APIC (xAPIC)** | LAPIC accessed via MMIO at `0xFEE00000`. LAPIC ID read as a `u8` — classic xAPIC. **x2APIC is not supported** (no MSR path). | `apic.zig:67`, `apic.zig:646` |
|
||||||
| **CPUID + RDTSC** | CPUID leaf `0x15` for TSC frequency; RDTSC is the monotonic clock. | `apic.zig:333`, `apic.zig:113` |
|
| **CPUID + RDTSC** | CPUID leaf `0x15` for TSC frequency; RDTSC is the monotonic clock. | `apic.zig:333`, `apic.zig:113` |
|
||||||
@@ -108,19 +108,20 @@ hypervisor configured for UEFI firmware and an xHCI USB controller.
|
|||||||
- **UEFI only.** A custom UEFI application loader is installed to
|
- **UEFI only.** A custom UEFI application loader is installed to
|
||||||
`\EFI\BOOT\BOOTX64.efi`. There is **no BIOS, multiboot, or limine** path. The
|
`\EFI\BOOT\BOOTX64.efi`. There is **no BIOS, multiboot, or limine** path. The
|
||||||
loader tolerates UEFI Class-3 machines with no legacy PIC/PIT.
|
loader tolerates UEFI Class-3 machines with no legacy PIC/PIT.
|
||||||
(`build.zig:246`, `boot/efi.zig`)
|
(`build/images.zig` — the EFI/BOOT install — and `boot/efi.zig`)
|
||||||
- **ACPI is the hardware-discovery mechanism.** The RSDP is taken from the UEFI
|
- **ACPI is the hardware-discovery mechanism.** The RSDP is taken from the UEFI
|
||||||
configuration table (ACPI 2.0 GUID preferred, 1.0 fallback). Without a valid
|
configuration table (ACPI 2.0 GUID preferred, 1.0 fallback). Without a valid
|
||||||
RSDP there is **no device discovery** — no SMP, no IOAPIC routing, no PCI/USB.
|
RSDP there is **no device discovery** — no SMP, no IOAPIC routing, no PCI/USB.
|
||||||
(`efi.zig:790`, `boot-handoff.zig:149`)
|
(`efi.zig:790`, `boot-handoff.zig:149`)
|
||||||
- **Required ACPI tables:** MADT (interrupt topology), MCFG (PCIe ECAM base),
|
- **Required ACPI tables:** MADT (interrupt topology), MCFG (PCIe ECAM base),
|
||||||
FADT (power / PM timer). Optionally consumed: HPET, DMAR, SPCR.
|
FADT (power / PM timer). Optionally consumed: HPET, DMAR, SPCR.
|
||||||
(`system/devices/acpi.zig:3`)
|
(`system/kernel/acpi.zig:3`)
|
||||||
- The loader reads `/system/kernel` off the FAT boot volume, then loads user
|
- The loader reads `/system/kernel` off the FAT boot volume, then loads user
|
||||||
space: a prebuilt `boot\system.img` capsule
|
space: a prebuilt `boot\system.img` capsule
|
||||||
([system-image.md](system-image.md)) when present, otherwise it walks
|
([system-image.md](os-development/system-image.md)) when present, otherwise it walks
|
||||||
the volume's `/system` tree (init included) into the initial ramdisk. The
|
the volume's `/system` and optional `/test` trees (init included) into the
|
||||||
kernel can boot "kernel-only" without either. (`efi.zig:16`, `efi.zig:68`)
|
initial ramdisk. The kernel can boot "kernel-only" without either.
|
||||||
|
(`efi.zig:16`, `efi.zig:68`)
|
||||||
|
|
||||||
## Interrupt controller
|
## Interrupt controller
|
||||||
|
|
||||||
@@ -221,7 +222,7 @@ named for reporting only; internal SATA / NVMe / IDE disks have no driver.
|
|||||||
first VT-d DRHD unit and its capabilities are exposed via `PlatformInformation`
|
first VT-d DRHD unit and its capabilities are exposed via `PlatformInformation`
|
||||||
(`iommu_present`, `iommu_base`, `iommu_version`). No DMA-remapping tables are
|
(`iommu_present`, `iommu_base`, `iommu_version`). No DMA-remapping tables are
|
||||||
programmed and no translation is enforced. An IOMMU is therefore **not required**
|
programmed and no translation is enforced. An IOMMU is therefore **not required**
|
||||||
and does not currently constrain devices. (`system/devices/acpi.zig:96`)
|
and does not currently constrain devices. (`system/kernel/acpi.zig:96`)
|
||||||
|
|
||||||
## What is explicitly NOT supported
|
## What is explicitly NOT supported
|
||||||
|
|
||||||
|
|||||||
+6
-4
@@ -9,10 +9,12 @@ There are two layers:
|
|||||||
|
|
||||||
- **Host unit tests** (`zig build test`) — for pure, platform-independent logic.
|
- **Host unit tests** (`zig build test`) — for pure, platform-independent logic.
|
||||||
What began as the three shared contracts (`system/boot-handoff.zig`,
|
What began as the three shared contracts (`system/boot-handoff.zig`,
|
||||||
`system/abi.zig`, `system/devices/device-abi.zig`) now spans ~26 modules:
|
`system/abi.zig`, `library/device/model/device-abi.zig`) now spans ~26 modules:
|
||||||
protocol and on-wire definitions (VFS, USB, virtio-gpu), the FAT engine, the
|
protocol and on-wire definitions (VFS, USB, virtio-gpu), the FAT engine, the
|
||||||
display compositor, PS/2 and HID decoding, the kernel log ring, and the
|
display compositor, PS/2 and HID decoding, the kernel log ring, and the
|
||||||
runtime's `time`/`thread` — the full list is the test step in `build.zig`.
|
runtime's `time`/`thread` — the list is distributed across the library-domain
|
||||||
|
and binary packages' own `test` steps, which the root `zig build test`
|
||||||
|
aggregates (docs/build-packages-plan.md).
|
||||||
These compile for the host and run natively.
|
These compile for the host and run natively.
|
||||||
- **QEMU integration tests** (`python3 test/qemu_test.py`) — boot the real kernel
|
- **QEMU integration tests** (`python3 test/qemu_test.py`) — boot the real kernel
|
||||||
and check its behaviour. This is the interesting part.
|
and check its behaviour. This is the interesting part.
|
||||||
@@ -27,7 +29,7 @@ boot log, memory summary, exception reports — appears on serial as plain text.
|
|||||||
|
|
||||||
QEMU captures that with `-serial file:serial.log`, giving a machine-readable
|
QEMU captures that with `-serial file:serial.log`, giving a machine-readable
|
||||||
transcript. Serial is per-architecture (x86 uses port I/O; an ARM board uses a
|
transcript. Serial is per-architecture (x86 uses port I/O; an ARM board uses a
|
||||||
memory-mapped UART), so it lives behind the [architecture](architecture.md) boundary — and adding
|
memory-mapped UART), so it lives behind the [architecture](os-development/architecture.md) boundary — and adding
|
||||||
a new architecture's UART is what makes the same tests run there.
|
a new architecture's UART is what makes the same tests run there.
|
||||||
|
|
||||||
The serial log sink is **compiled in only under `-Dserial`** (off by default).
|
The serial log sink is **compiled in only under `-Dserial`** (off by default).
|
||||||
@@ -88,7 +90,7 @@ table in `test/qemu_test.py`):
|
|||||||
| `fault-recovery` | a ring-3 process that faults is killed and reaped while init keeps heartbeating — the OS survives | `DANOS-TEST-RESULT: PASS` |
|
| `fault-recovery` | a ring-3 process that faults is killed and reaped while init keeps heartbeating — the OS survives | `DANOS-TEST-RESULT: PASS` |
|
||||||
|
|
||||||
The faulting cases don't print a result line — they deliberately raise a CPU
|
The faulting cases don't print a result line — they deliberately raise a CPU
|
||||||
exception, and the harness asserts on the [exception report](interrupts.md) the
|
exception, and the harness asserts on the [exception report](os-development/interrupts.md) the
|
||||||
handler prints (which also reaches serial). This reuses the real fault path as the
|
handler prints (which also reaches serial). This reuses the real fault path as the
|
||||||
test oracle: if the IDT/TSS weren't wired up, `fault-df` would triple-fault and the
|
test oracle: if the IDT/TSS weren't wired up, `fault-df` would triple-fault and the
|
||||||
marker would never appear.
|
marker would never appear.
|
||||||
|
|||||||
@@ -1,192 +0,0 @@
|
|||||||
# The VFS wire protocol
|
|
||||||
|
|
||||||
> **Status:** built and spoken today between `runtime.fs` (the client) and the
|
|
||||||
> filesystem BACKENDS (the FAT server). The mount router lives in the
|
|
||||||
> **kernel** (`system/kernel/vfs.zig`): `fs_resolve` routes a path and either
|
|
||||||
> serves it directly (the read-only /system initrd mount, via `fs_node`) or
|
|
||||||
> redirects the caller to the owning backend's endpoint plus the rewritten
|
|
||||||
> mount-relative path — after which the client speaks THIS protocol to the
|
|
||||||
> backend, unchanged. The Zig source of truth is `system/vfs-protocol.zig`
|
|
||||||
> (the `vfs-protocol` module), whose unit test pins a sample of the sizes
|
|
||||||
> and values below. This page is the **language-neutral wire specification**
|
|
||||||
> of that contract — what a Rust or C client implements ([vdso.md](vdso.md)
|
|
||||||
> explains why the IPC protocols, not the syscall numbers, are danos's
|
|
||||||
> public ABI).
|
|
||||||
|
|
||||||
## Transport
|
|
||||||
|
|
||||||
A VFS exchange is one synchronous IPC rendezvous (`ipc_call`,
|
|
||||||
docs/ipc.md): the client sends one message and blocks; the server replies
|
|
||||||
with one message. The endpoint comes from the kernel's `fs_resolve` — which
|
|
||||||
also hands back the path rewritten relative to the mount — not from a
|
|
||||||
registry lookup. (Service id 1, the old userspace router, is retired.)
|
|
||||||
|
|
||||||
- A message is at most **256 bytes** (`message_maximum`).
|
|
||||||
- A request is a fixed 32-byte **Request** header followed by an inline
|
|
||||||
payload of at most **224 bytes** (`maximum_payload`) — a path, or write
|
|
||||||
bytes. There is no multi-message request: paths and single reads/writes
|
|
||||||
must fit, and larger transfers loop (see *read* / *write*).
|
|
||||||
- A reply is a fixed 24-byte **Reply** header followed by an inline payload —
|
|
||||||
read bytes, a `FileStatus`, or a `DirectoryEntry`.
|
|
||||||
- All integers are **little-endian**; layouts are C layout for x86-64
|
|
||||||
(`extern struct`), offsets given below so nothing need be inferred.
|
|
||||||
|
|
||||||
The kernel resolves NAMES (the mount table) but never parses these
|
|
||||||
messages — it moves the bytes; file state is entirely the backend's affair.
|
|
||||||
With clients holding backend node ids directly, a backend records each open
|
|
||||||
handle's owner and sweeps a dead client's handles via the published process
|
|
||||||
exit events.
|
|
||||||
|
|
||||||
## Request header — 32 bytes
|
|
||||||
|
|
||||||
| offset | size | field | meaning |
|
|
||||||
|-------:|-----:|-------|---------|
|
|
||||||
| 0 | 4 | `operation` | an **Operation** value (below) |
|
|
||||||
| 4 | 4 | — | padding |
|
|
||||||
| 8 | 8 | `node` | the server-side open-node id from a prior `open`; 0 for path-based operations |
|
|
||||||
| 16 | 8 | `offset` | byte position for read/write; entry index (cursor) for readdir; else 0 |
|
|
||||||
| 24 | 4 | `len` | payload length for path/write operations; requested byte count for read |
|
|
||||||
| 28 | 4 | `flags` | open flags (below); else 0 |
|
|
||||||
|
|
||||||
## Reply header — 24 bytes
|
|
||||||
|
|
||||||
| offset | size | field | meaning |
|
|
||||||
|-------:|-----:|-------|---------|
|
|
||||||
| 0 | 4 | `status` | **0 = success**, negative = failure (signed) |
|
|
||||||
| 4 | 4 | — | padding |
|
|
||||||
| 8 | 8 | `node` | the new open-node id (for `open`); else 0 |
|
|
||||||
| 16 | 4 | `len` | reply payload length in bytes |
|
|
||||||
| 20 | 4 | — | padding |
|
|
||||||
|
|
||||||
On failure the backend replies `status = -1`, and that reply reaches the
|
|
||||||
client directly — there is no party between them on the wire. (Kernel-served
|
|
||||||
paths produce no wire replies at all: `fs_resolve`/`fs_node` failures are
|
|
||||||
syscall register statuses.) A richer errno vocabulary is future work —
|
|
||||||
clients must treat *any* negative status as failure, not match on -1.
|
|
||||||
|
|
||||||
## Operations
|
|
||||||
|
|
||||||
Values are append-only and never renumbered (the same evolution rule every
|
|
||||||
danos protocol follows). Send only values from this table: the shipped server
|
|
||||||
decodes the operation into an exhaustive enum, so an out-of-range value is
|
|
||||||
not answered with a `status = -1` reply — it trips a safety check in safe
|
|
||||||
builds and is undefined otherwise. (The `-1` replies cover recognised but
|
|
||||||
refused operations, such as `mount` sent to a backend.)
|
|
||||||
|
|
||||||
| value | operation | request payload | reply |
|
|
||||||
|------:|-----------|-----------------|-------|
|
|
||||||
| 0 | `open` | the path (`len` = its length), `flags` as below | `node` = open-node id |
|
|
||||||
| 1 | `close` | — (`node` set) | status only |
|
|
||||||
| 2 | `read` | — (`node`, `offset`, `len` = wanted count) | `len` bytes read, payload = the bytes; `len` 0 at end of file |
|
|
||||||
| 3 | `write` | the bytes (`node`, `offset`, `len` = count) | `len` = bytes accepted (may be short — loop) |
|
|
||||||
| 4 | `status` | — (`node` set) | payload = **FileStatus** (24 bytes) |
|
|
||||||
| 5 | `readdir` | — (`node` = a directory, `offset` = cursor) | payload = one **DirectoryEntry** + name; `len` 0 at end |
|
|
||||||
| 6 | `mount` | the mount-point path; the backend endpoint rides as the call's **capability** | status only |
|
|
||||||
| 7 | `unmount` | the mount-point path | status only |
|
|
||||||
| 8 | `mkdir` | the path | status only |
|
|
||||||
| 9 | `unlink` | the path | status only |
|
|
||||||
| 10 | `rename` | old path, one `0x00`, new path (`len` = total) | status only |
|
|
||||||
|
|
||||||
Notes per operation:
|
|
||||||
|
|
||||||
- **open** — the path is the mount-relative path `fs_resolve` handed back
|
|
||||||
(absolute-shaped: `/notes.txt` under fat's `/mnt/usb` mount). Bare names
|
|
||||||
(`greeting`) resolve nowhere — the flat ramfs is retired, and `fs_resolve`
|
|
||||||
refuses non-absolute paths. The returned `node` is the *backend's* own
|
|
||||||
open-node id: with the router in the kernel there is no forwarding table,
|
|
||||||
and clients hold backend ids directly (see *Lifetimes and trust*).
|
|
||||||
- **read / write** — a single exchange moves at most 224 bytes
|
|
||||||
(`maximum_payload`); the client loops, advancing `offset` by the returned
|
|
||||||
`len`, until done (read) or the slice is written (write). A `write` reply
|
|
||||||
shorter than requested is progress, not an error; a `len` of 0 means no
|
|
||||||
forward progress — stop rather than spin.
|
|
||||||
- **readdir** — `offset` is a **cursor: the entry index**, not a byte
|
|
||||||
position. Each call returns exactly one entry; the client increments the
|
|
||||||
cursor by 1. A reply with `len` 0 is end-of-directory. The directory must
|
|
||||||
have been opened with the `directory` flag.
|
|
||||||
- **mount / unmount** — RETIRED from the wire: mounting is the `fs_mount`
|
|
||||||
syscall now (a filesystem server passes its endpoint handle; possession is
|
|
||||||
the capability, exactly the trust of the old cap-passing op). The op
|
|
||||||
numbers stay reserved. Mount-prefix semantics are unchanged: prefixes
|
|
||||||
match at path boundaries only (`/mnt/usb` never captures `/mnt/usbextra`),
|
|
||||||
the longest matching prefix wins, and an optional backend-side rewrite
|
|
||||||
prefix maps a mount into the backend's namespace (fat serves `/mnt/usb`
|
|
||||||
from its volume root and `/var` from its `/var` subtree).
|
|
||||||
- **rename** — same-directory rename only: the backend compares the old and
|
|
||||||
new parent paths and refuses a mismatch. The client (`runtime.fs`) refuses
|
|
||||||
earlier when the two paths resolve to different backend endpoints, but that
|
|
||||||
check is coarser than "one mount" — one endpoint can serve several mounts
|
|
||||||
(fat serves `/mnt/usb` and `/var`), so a cross-mount rename reaches the
|
|
||||||
backend and fails on its same-directory check.
|
|
||||||
|
|
||||||
## Open flags
|
|
||||||
|
|
||||||
Bitwise OR in `Request.flags`, meaningful for `open` only:
|
|
||||||
|
|
||||||
| bit | name | meaning |
|
|
||||||
|----:|------|---------|
|
|
||||||
| 1 | `create` | create the file if it does not exist |
|
|
||||||
| 2 | `directory` | open a directory node for `readdir` rather than a file |
|
|
||||||
| 4 | `truncate` | truncate an existing file to zero length on open (replace, don't overwrite in place) |
|
|
||||||
|
|
||||||
## FileStatus — 24 bytes (the `status` reply payload)
|
|
||||||
|
|
||||||
| offset | size | field | meaning |
|
|
||||||
|-------:|-----:|-------|---------|
|
|
||||||
| 0 | 8 | `size` | file size in bytes |
|
|
||||||
| 8 | 4 | `kind` | a **NodeKind** value |
|
|
||||||
| 12 | 4 | — | padding |
|
|
||||||
| 16 | 8 | `mtime` | modification time, Unix epoch seconds UTC; 0 if the backend keeps none |
|
|
||||||
|
|
||||||
## DirectoryEntry — 16 bytes + name (the `readdir` reply payload)
|
|
||||||
|
|
||||||
| offset | size | field | meaning |
|
|
||||||
|-------:|-----:|-------|---------|
|
|
||||||
| 0 | 4 | `kind` | a **NodeKind** value |
|
|
||||||
| 4 | 4 | `name_len` | length of the name that follows |
|
|
||||||
| 8 | 8 | `size` | the entry's size in bytes |
|
|
||||||
| 16 | `name_len` | name | the entry's name, not NUL-terminated |
|
|
||||||
|
|
||||||
## NodeKind
|
|
||||||
|
|
||||||
Aligned to the FSH file-type table
|
|
||||||
(docs/danos-file-system-hierarchy-FSH.md):
|
|
||||||
|
|
||||||
| value | kind |
|
|
||||||
|------:|------|
|
|
||||||
| 0 | regular file |
|
|
||||||
| 1 | directory |
|
|
||||||
| 2 | character device |
|
|
||||||
| 3 | block device |
|
|
||||||
| 4 | symbolic link |
|
|
||||||
| 5 | fifo |
|
|
||||||
| 6 | socket |
|
|
||||||
|
|
||||||
Clients should map unknown values to *regular* rather than reject — the
|
|
||||||
table can grow.
|
|
||||||
|
|
||||||
## Lifetimes and trust
|
|
||||||
|
|
||||||
Open-node ids live in the backend. A client that dies without closing leaks
|
|
||||||
nothing permanently: the backend (the FAT server) subscribes to the kernel's
|
|
||||||
published process-exit events (docs/process-lifecycle.md) and releases a dead
|
|
||||||
client's handles. The kernel VFS root needs no sweep at all — its node tokens
|
|
||||||
are permanent for a boot and carry no open state. Ids are plain integers, not
|
|
||||||
capabilities — a backend trusts its callers with each other's ids today, which
|
|
||||||
is acceptable while every client is part of the system image and worth
|
|
||||||
revisiting (per-client id namespaces) before third-party binaries arrive.
|
|
||||||
|
|
||||||
## Evolution rules
|
|
||||||
|
|
||||||
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
|
|
||||||
`system/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.
|
|
||||||
- The 256-byte message ceiling is a property of the current IPC transport,
|
|
||||||
not a promise; clients should read `maximum_payload`-shaped limits from the
|
|
||||||
reply lengths they actually get (loop-until-done), not hard-code 224.
|
|
||||||
- Negative statuses beyond -1 will appear (an errno vocabulary); success is
|
|
||||||
exactly 0.
|
|
||||||
-118
@@ -1,118 +0,0 @@
|
|||||||
# Vision: a microkernel, built to learn
|
|
||||||
|
|
||||||
danos exists first and foremost as a **learning-by-doing project**: the point is to
|
|
||||||
build a real operating system, bump into the hard constraints for real, and research
|
|
||||||
them from a position of having actually hit them. The docs in this folder are part of
|
|
||||||
that — they're where a constraint gets understood once it's been met.
|
|
||||||
|
|
||||||
That framing sets the priorities. danos is not chasing a spec or a product; it's
|
|
||||||
chasing understanding, with a concrete, motivating **win condition** to aim at.
|
|
||||||
|
|
||||||
## The win condition
|
|
||||||
|
|
||||||
danos is a "win" when it:
|
|
||||||
|
|
||||||
- **boots and runs on real hardware** — the author's **PC** (x86-64) and **both
|
|
||||||
Raspberry Pis**: the **Zero 2 W** and the **Pi 5** (both `aarch64`, one backend —
|
|
||||||
see [arm.md](arm.md)),
|
|
||||||
- **has a graphical user interface**, ideally — building on the framebuffer it
|
|
||||||
already draws to.
|
|
||||||
|
|
||||||
Everything below serves that, or serves the curiosity that the project runs on.
|
|
||||||
|
|
||||||
## Why a microkernel: resilience
|
|
||||||
|
|
||||||
The kernel stays **minimal** — only what genuinely must run privileged:
|
|
||||||
|
|
||||||
- scheduling,
|
|
||||||
- inter-process communication (IPC),
|
|
||||||
- memory management (address spaces, page tables),
|
|
||||||
- low-level interrupt dispatch.
|
|
||||||
|
|
||||||
Everything else — device drivers, filesystems, the GUI, the network stack — runs as
|
|
||||||
an **isolated user-space server**, each in its own address space with only the
|
|
||||||
privileges it needs.
|
|
||||||
|
|
||||||
The reason for this shape is **resilience**: the ability to **re-initialise parts of
|
|
||||||
the OS while it runs**. A driver bug can't corrupt the kernel or another driver; a
|
|
||||||
crashed or wedged component is contained, killed, and **restarted** — "if I break
|
|
||||||
something, I can just fix it," without rebooting. Keeping the kernel tiny is part of
|
|
||||||
that strategy: the one thing that *can't* be restarted is the trusted base, so the
|
|
||||||
less code in it, the less that can take the whole system down. This is the project's
|
|
||||||
real motivation, and it has its own design note: [resilience.md](resilience.md).
|
|
||||||
|
|
||||||
The cost is that **IPC becomes the backbone**: what used to be a function call inside
|
|
||||||
a monolithic kernel is now a message between address spaces. In a microkernel, IPC
|
|
||||||
performance essentially *is* system performance (the lesson of L4), so it's a
|
|
||||||
first-class concern. Hardware interrupts become IPC too: the kernel turns an IRQ into
|
|
||||||
a message to the driver that owns the device.
|
|
||||||
|
|
||||||
## On real-time: an option, not a commitment
|
|
||||||
|
|
||||||
danos was originally framed as a hard **real-time** OS. That's now held as **one
|
|
||||||
interesting constraint to explore, not a requirement** — because real-time is a
|
|
||||||
*pervasive* invariant (every operation must be provably time-bounded, everywhere)
|
|
||||||
that would slow every milestone, whereas resilience is a set of *structural* features
|
|
||||||
that's lighter to build and is what the project actually wants. The trade-off is
|
|
||||||
written up in [smp.md](smp.md#does-the-right-choice-depend-on-real-time-vs-resilience).
|
|
||||||
|
|
||||||
What danos keeps from the real-time direction, because it's cheap and useful anyway:
|
|
||||||
|
|
||||||
- **Fixed-priority preemptive scheduling** — the highest-priority ready task runs, and
|
|
||||||
preemption lets a runaway component be interrupted and killed (which *serves
|
|
||||||
resilience*). Already built ([scheduling.md](scheduling.md)).
|
|
||||||
- **A calibrated, deterministic clock** — already built ([device-interrupts.md](device-interrupts.md)).
|
|
||||||
|
|
||||||
What danos does *not* owe anyone unless it deliberately chooses real-time later:
|
|
||||||
timing *guarantees*, priority inheritance, bounded allocators, tickless timers, MCS
|
|
||||||
scheduling contexts. Concretely, the current [heap](heap.md) is a first-fit free list
|
|
||||||
with unbounded allocation time — fine here, and only a problem *if* a hard-real-time
|
|
||||||
path is ever added. Note that **QNX is both** a real-time and a restartable
|
|
||||||
microkernel, so choosing resilience now doesn't close the real-time door — it just
|
|
||||||
doesn't pay the tax yet.
|
|
||||||
|
|
||||||
## The roadmap — tracks, not a strict line
|
|
||||||
|
|
||||||
Because the driver is curiosity plus the win condition, the roadmap is a set of
|
|
||||||
**tracks** with dependencies, not a rigid sequence. Pick by interest; mind the
|
|
||||||
prerequisites.
|
|
||||||
|
|
||||||
**Done:** UEFI boot, framebuffer + [serial](testing.md), [physical frames](frame-allocator.md)
|
|
||||||
(with boot-services memory reclaimed), [paging](paging.md) with W^X, [exceptions and
|
|
||||||
interrupts](interrupts.md), a [calibrated timer + ns clock](device-interrupts.md), a
|
|
||||||
[heap](heap.md), a [fixed-priority preemptive scheduler](scheduling.md) with blocking,
|
|
||||||
in-kernel [IPC channels](ipc.md), SMP (all cores scheduling, with affinity), a
|
|
||||||
**higher-half kernel** with a physmap, and **user space**: per-process address
|
|
||||||
spaces, `syscall`/`sysret` with the `swapgs` discipline, a user-ELF loader, and
|
|
||||||
`/system/services/init` — a real user ELF built from `system/services/init/`, running at CPL 3 as PID 1 on its
|
|
||||||
own page tables — plus a [test harness](testing.md).
|
|
||||||
|
|
||||||
- **Isolation track** — **user mode + address-space isolation**. *Done: a
|
|
||||||
higher-half kernel with a physmap (the low half is user space), per-process
|
|
||||||
address spaces with CR3 switched on context switch, the `swapgs` discipline,
|
|
||||||
`syscall`/`sysret`, a user-ELF loader, an address-space/stack reaper for exited
|
|
||||||
tasks, and `/system/services/init` running as a real preemptive ring-3 process
|
|
||||||
(PID 1). Remaining polish: SMAP + fault-recovering copy-in/out, and TLB shootdown
|
|
||||||
once a process has more than one thread. (The real IPC syscalls —
|
|
||||||
`ipc_call`/`ipc_reply_wait` — have since been built and are the backbone every
|
|
||||||
driver and service speaks; see [ipc.md](ipc.md).)*
|
|
||||||
- **Resilience track** — fault → kill → notify, a supervisor/reincarnation server,
|
|
||||||
resource cleanup on death, then a restartable driver as proof. Needs isolation.
|
|
||||||
See [resilience.md](resilience.md).
|
|
||||||
- **ARM track** — the `aarch64` port so danos runs on the Zero 2 W and Pi 5. Largely
|
|
||||||
independent of the others (it's the [architecture layer](architecture.md)); directly serves the win
|
|
||||||
condition. Likely via aarch64-UEFI first (QEMU `virt` + AAVMF), then real boards.
|
|
||||||
See [arm.md](arm.md), and [discovery.md](discovery.md) for the device tree it needs.
|
|
||||||
- **GUI track** — a framebuffer-based windowing/compositor, and the input + display
|
|
||||||
drivers under it. Builds on the neutral framebuffer (so it's arch-independent), and
|
|
||||||
on the driver model from the isolation/resilience tracks. The visible payoff.
|
|
||||||
|
|
||||||
The natural spine is **isolation → (resilience + drivers) → GUI**, with the **ARM
|
|
||||||
track** pursued alongside whenever the itch to see it boot on a Pi wins out.
|
|
||||||
|
|
||||||
## How to use this page
|
|
||||||
|
|
||||||
Read it before adding anything structural. When a design decision comes up, the
|
|
||||||
question is: does it serve the **win condition** (runs on the three machines, with a
|
|
||||||
GUI), or the **learning** (a constraint worth meeting)? If it serves neither — e.g.
|
|
||||||
paying the full real-time tax with no payoff in sight — it can wait.
|
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
# The volume manager: the plan
|
||||||
|
|
||||||
|
*2026-08-09. Executes the settled design in
|
||||||
|
[storage-architecture.md](file-system-development/storage-architecture.md) and
|
||||||
|
[storage-design-rationale.md](file-system-development/storage-design-rationale.md)
|
||||||
|
(decisions 1–8). Track discipline as always: one commit per coherent step, suite
|
||||||
|
green at phase boundaries, every new test shown to fail against the old
|
||||||
|
behavior, one QEMU suite at a time, work on main.*
|
||||||
|
|
||||||
|
**No open decisions.** Decision 4 is settled in the rationale as per-sender
|
||||||
|
range confinement at the provider on one serving endpoint — the badge-scoped
|
||||||
|
provider pattern the xHCI bus already uses, applied to blocks. The volume
|
||||||
|
manager sets each filesystem process's range; the driver clamps and translates
|
||||||
|
every transfer by the sender's kernel-stamped badge; filesystems address
|
||||||
|
volume-relative LBAs from 0 (on the confined path the FAT engine's `base_lba`
|
||||||
|
resolves to 0; the field and the engine's own MBR walk remain as now-inert
|
||||||
|
legacy, the authoritative walk living in the volume manager's `partition.zig`).
|
||||||
|
Every other decision the phases below execute is recorded in the
|
||||||
|
rationale (decisions 1–8); nothing in this plan waits on a choice.
|
||||||
|
|
||||||
|
## V0 — `fs_unmount` ownership (the defect fix)
|
||||||
|
|
||||||
|
The kernel records the mounting process on each mount slot; `fs_unmount` is
|
||||||
|
refused for any caller but the owner (the `/protocol` special case stays).
|
||||||
|
Death cleanup is unaffected (the lazy sweep is not an unmount). Discrimination:
|
||||||
|
a fixture unmounting a prefix it does not own must be refused — fails against
|
||||||
|
today's kernel, which lets any process unmount anything.
|
||||||
|
|
||||||
|
## V1 — the filesystem harness (extraction, no behavior change)
|
||||||
|
|
||||||
|
fat's 434-line shell becomes `library/file-system/harness` (name per
|
||||||
|
convention): establishment, the badge-scoped open-node table, the nine
|
||||||
|
vfs-protocol handlers, mount registration, bring-up/teardown. fat becomes
|
||||||
|
engine + on-disk + a thin main wiring the harness. Suite green is the gate;
|
||||||
|
nothing observable changes. This lands FIRST so every later phase touches the
|
||||||
|
harness once, not fat and the harness both.
|
||||||
|
|
||||||
|
## V2 — the driver mechanism: ranges, confinement, presence
|
||||||
|
|
||||||
|
- Block protocol additions (appended; numbering holds): `define_range`
|
||||||
|
(volume-manager-only in practice — see grants), and the pushed
|
||||||
|
`medium_changed` event (present/absent + change counter).
|
||||||
|
- usb-storage: per-badge range table (clamp + translate per sender), range
|
||||||
|
definitions from the volume manager, and presence: a slow idle-time
|
||||||
|
TEST UNIT READY poll plus sense-key inspection on failed transfers, emitting
|
||||||
|
`medium_changed` on transitions. QEMU test lever: `eject` /
|
||||||
|
`blockdev-remove-medium` against a `removable=on` usb-storage device; if
|
||||||
|
QEMU's model refuses, the fallback drill is device_del/add of the whole
|
||||||
|
stick (the H-matrix already proves that path) and presence gets its real
|
||||||
|
test on the bench with a card reader.
|
||||||
|
- Discrimination: a fixture transferring outside its assigned range must be
|
||||||
|
refused; fails against a driver without the clamp.
|
||||||
|
|
||||||
|
**Sequencing (as executed).** V2a landed the range clamp + its discrimination
|
||||||
|
fixture (block-range) — the security mechanism is testable in isolation. V2b
|
||||||
|
adds `medium_changed` and makes usb-storage a publisher that emits it on
|
||||||
|
presence transitions, but its END-TO-END test (eject → medium_changed →
|
||||||
|
unmount/remount) lands in V4 with the real consumer, the volume manager —
|
||||||
|
rather than a throwaway subscriber fixture V3 would immediately replace. Same
|
||||||
|
work, no duplicated scaffolding.
|
||||||
|
|
||||||
|
## V3 — the volume manager service
|
||||||
|
|
||||||
|
New binary `system/services/volume-manager`, spawned by init, serving the
|
||||||
|
(genuinely singular) name `volume-manager`. Duties, all moved OUT of fat:
|
||||||
|
|
||||||
|
- subscribe to the device manager; consumer-hello each storage provider for
|
||||||
|
its block channel;
|
||||||
|
- probe: partition table walk (MBR now, GPT next — the walk LEAVES the FAT
|
||||||
|
engine) and content identity (the decision-8 ladder: GPT GUID → fs UUID →
|
||||||
|
FAT serial+label → MBR signature+index → anonymous);
|
||||||
|
- configuration: `filesystems.csv` (signature → filesystem binary) and
|
||||||
|
`volumes.csv` (identity → mount prefix; the fstab). Boot volume identity
|
||||||
|
recorded at first sight of `/system/configuration`;
|
||||||
|
- define ranges on the driver; spawn one filesystem process per volume
|
||||||
|
(argv: volume id); answer each filesystem's startup hello with its volume
|
||||||
|
channel (the reply-capability path, same as the device manager's);
|
||||||
|
- supervise: hello/mount deadline, crash-loop cap, reap on removal.
|
||||||
|
|
||||||
|
fat sheds `acquireVolume` and its device-manager grant; filesystem binaries
|
||||||
|
get `open volume-manager` only — a filesystem cannot acquire, only be given.
|
||||||
|
Grants move with the code in the same commits.
|
||||||
|
|
||||||
|
**Sequencing (as executed).** V3a (discovery+probe) and V3b (the flip: spawn +
|
||||||
|
confine + hand over the channel, single volume) landed the core. The V3c items —
|
||||||
|
the `volumes.csv` mount map, the fuller identity ladder (FAT serial, GPT GUID),
|
||||||
|
and multi-volume spawning — mainly serve the MULTI-volume drills (two-partitions,
|
||||||
|
clone-policy). The user's goal is the single-volume boot-stick removal lifecycle,
|
||||||
|
so V4's removal lifecycle runs next on the single volume, and the multi-volume
|
||||||
|
work + its drills become a documented follow-on (V3c/multi-volume). fat keeps its
|
||||||
|
hardcoded mount prefixes until the mount map lands.
|
||||||
|
|
||||||
|
## V4 — the removal lifecycle, end to end
|
||||||
|
|
||||||
|
Two triggers, one path: storage-channel death and `medium_changed(absent)`
|
||||||
|
both drive kill-the-filesystem-process + retire-its-mounts; return (device
|
||||||
|
re-report or `medium_changed(present)`) drives re-probe → respawn → remount
|
||||||
|
at the identity's prefix. The logger gains resume patience (retry flushes on
|
||||||
|
the fat cadence, never abandon) and the ring-wrap gap marker. QEMU cases:
|
||||||
|
|
||||||
|
- `volume-replug`: yank the boot stick mid-run, replug, assert remount at the
|
||||||
|
same prefixes and the logger appending to the SAME boot-stamp tree with the
|
||||||
|
gap marked. Discrimination: against pre-V4, fat wedges (`mounted` forever)
|
||||||
|
and no remount happens.
|
||||||
|
- `volume-two-partitions`: a two-partition FAT image → two volumes, two
|
||||||
|
filesystem processes, two mounts from one stick; yank once, both die; return
|
||||||
|
once, both remount. Proves multi-volume and the reap breadth. (New image
|
||||||
|
fixture beside make-fat-image.py.)
|
||||||
|
- `volume-clone-policy`: two sticks with identical FAT serials — first keeps
|
||||||
|
the mapped name, second mounts suffixed, loudly logged.
|
||||||
|
- The **lifecycle conformance drill**, parameterized by filesystem: mount,
|
||||||
|
serve, yank mid-write, verify honest loss (dirty flag set, gap said),
|
||||||
|
replug, remount. FAT is implementation #1; the drill is the definition of
|
||||||
|
"danos supports filesystem X".
|
||||||
|
|
||||||
|
## V5 — close-out
|
||||||
|
|
||||||
|
Full suite green; the architecture doc's *(planned)* markers flip to built;
|
||||||
|
`fs_unmount` ownership, ranges, presence, identity, and the volume manager
|
||||||
|
lose their future-tense; memory updated; Ryzen bench note: pull the stick,
|
||||||
|
watch the log gap get marked, plug it back anywhere.
|
||||||
|
|
||||||
|
**Not in this track** (recorded so absence is deliberate): GPT parsing beyond
|
||||||
|
the identity read (row exists in the prober's ladder; full GPT when a GPT
|
||||||
|
medium matters), AHCI/NVMe drivers (NVMe gated on the shm-ring data plane),
|
||||||
|
formatting/entropy, per-process namespaces.
|
||||||
+11
-10
@@ -108,7 +108,7 @@ localised (below).
|
|||||||
## The architecture decision: `runtime.os` + `runtime.fs`, and retire `posix`
|
## The architecture decision: `runtime.os` + `runtime.fs`, and retire `posix`
|
||||||
|
|
||||||
danos already has the right split ([the private-ABI boundary](../README.md)): the
|
danos already has the right split ([the private-ABI boundary](../README.md)): the
|
||||||
kernel exposes a minimal syscall ABI ([syscall.md](syscall.md)); the **`runtime`**
|
kernel exposes a minimal syscall ABI ([syscall.md](os-development/syscall.md)); the **`runtime`**
|
||||||
library is the stable, danos-native application ABI. What this roadmap adds:
|
library is the stable, danos-native application ABI. What this roadmap adds:
|
||||||
|
|
||||||
- **`runtime.os` — the seam.** A C-ABI-shaped module of the ~30 operations
|
- **`runtime.os` — the seam.** A C-ABI-shaped module of the ~30 operations
|
||||||
@@ -151,8 +151,9 @@ Its footprint was tiny: **five** call sites, all `unistd` file operations —
|
|||||||
(from the boot-log work) `init.zig` and `log-flush.zig`. `stdio.zig` was dead — nothing
|
(from the boot-log work) `init.zig` and `log-flush.zig`. `stdio.zig` was dead — nothing
|
||||||
imported it. The plan — build `runtime.fs`, migrate those five to it, delete
|
imported it. The plan — build `runtime.fs`, migrate those five to it, delete
|
||||||
`library/posix/`, and drop the `posix` module from `build.zig`'s `addUserBinary` — has
|
`library/posix/`, and drop the `posix` module from `build.zig`'s `addUserBinary` — has
|
||||||
since been carried out: `library/` today holds only `mmio`, `runtime`, and
|
since been carried out: `library/` today holds `client`, `csv`, `device`,
|
||||||
`xkeyboard-config`.
|
`kernel`, `protocol`, and `xkeyboard-config` (the `runtime` namespace was later
|
||||||
|
reorganized into `library/kernel`, and `mmio` moved under `library/device`).
|
||||||
|
|
||||||
## Where danos stands: coverage vs. the gaps
|
## Where danos stands: coverage vs. the gaps
|
||||||
|
|
||||||
@@ -165,7 +166,7 @@ What the seam needs, and what danos already provides:
|
|||||||
| mmap / munmap | native syscalls ([abi.zig](../system/abi.zig)) | none |
|
| mmap / munmap | native syscalls ([abi.zig](../system/abi.zig)) | none |
|
||||||
| page allocator | over `mmap`, via `root.os.heap.page_allocator` override | ~30-line hook |
|
| page allocator | over `mmap`, via `root.os.heap.page_allocator` override | ~30-line hook |
|
||||||
| monotonic clock | `clock` syscall | none |
|
| monotonic clock | `clock` syscall | none |
|
||||||
| args / argv | SysV entry stack ([sysv.md](sysv.md)), `runtime.process.Init` | none |
|
| args / argv | SysV entry stack ([sysv.md](os-development/sysv.md)), `runtime.process.Init` | none |
|
||||||
| stdout / stderr | `debug_write` today | wire fd 1/2 to a console **byte** stream |
|
| stdout / stderr | `debug_write` today | wire fd 1/2 to a console **byte** stream |
|
||||||
| mkdir / unlink / rename / truncate | done — engine + VFS + `runtime.fs` (Phase 2) | — |
|
| mkdir / unlink / rename / truncate | done — engine + VFS + `runtime.fs` (Phase 2) | — |
|
||||||
| stat fields | `{size, kind, mtime}` | **mode / inode** still missing (cache validity) |
|
| stat fields | `{size, kind, mtime}` | **mode / inode** still missing (cache validity) |
|
||||||
@@ -209,7 +210,7 @@ build); point danos's `build.zig`/CI at the resulting binary. Four localised pat
|
|||||||
plan9/serenity;
|
plan9/serenity;
|
||||||
- add `danos` to the freestanding/other **no-op `_start` list** in `std`'s `start.zig`,
|
- add `danos` to the freestanding/other **no-op `_start` list** in `std`'s `start.zig`,
|
||||||
so std does *not* emit its own System-V `_start` — danos keeps owning the entry shim
|
so std does *not* emit its own System-V `_start` — danos keeps owning the entry shim
|
||||||
and `Init`/argv construction it already builds ([sysv.md](sysv.md));
|
and `Init`/argv construction it already builds ([sysv.md](os-development/sysv.md));
|
||||||
- wire the `system` selector `.danos => std.os.danos` in `std.posix`;
|
- wire the `system` selector `.danos => std.os.danos` in `std.posix`;
|
||||||
- add `std/os/danos.zig` — **the seam itself**, promoted near-verbatim from the
|
- add `std/os/danos.zig` — **the seam itself**, promoted near-verbatim from the
|
||||||
`runtime.os` developed first in Phase 1 (against the stock toolchain, so the fork is
|
`runtime.os` developed first in Phase 1 (against the stock toolchain, so the fork is
|
||||||
@@ -243,7 +244,7 @@ readdir/isatty/args/exit) exists. Those are downstream and out of scope here.
|
|||||||
danos's biggest genuine gap, and the correctness-critical one:
|
danos's biggest genuine gap, and the correctness-critical one:
|
||||||
|
|
||||||
- Add **mkdir / unlink / rename / truncate** to *both* the VFS wire protocol
|
- Add **mkdir / unlink / rename / truncate** to *both* the VFS wire protocol
|
||||||
([vfs-protocol.zig](../system/vfs-protocol.zig)) and the FAT engine
|
([vfs-protocol.zig](../library/protocol/vfs/vfs-protocol.zig)) and the FAT engine
|
||||||
([engine.zig](../system/services/fat/engine.zig)), then expose them via `runtime.os`.
|
([engine.zig](../system/services/fat/engine.zig)), then expose them via `runtime.os`.
|
||||||
- Extend `stat` beyond `{size, kind}` to carry **mtime + inode + mode** — `std`'s file
|
- Extend `stat` beyond `{size, kind}` to carry **mtime + inode + mode** — `std`'s file
|
||||||
stat needs them for build-cache validity — which in turn needs **wall-clock** time
|
stat needs them for build-cache validity — which in turn needs **wall-clock** time
|
||||||
@@ -344,10 +345,10 @@ Two current decisions fall out of this roadmap:
|
|||||||
## Related
|
## Related
|
||||||
|
|
||||||
- [vision.md](vision.md) — the north star this serves.
|
- [vision.md](vision.md) — the north star this serves.
|
||||||
- [syscall.md](syscall.md) — the kernel↔runtime ABI `runtime.os` is built on.
|
- [syscall.md](os-development/syscall.md) — the kernel↔runtime ABI `runtime.os` is built on.
|
||||||
- [sysv.md](sysv.md) — the entry stack (`argc/argv/envp/auxv`) danos already constructs.
|
- [sysv.md](os-development/sysv.md) — the entry stack (`argc/argv/envp/auxv`) danos already constructs.
|
||||||
- [ipc.md](ipc.md) — the IPC the VFS/FAT operations travel over.
|
- [ipc.md](device-driver-development/ipc.md) — the IPC the VFS/FAT operations travel over.
|
||||||
- [danos-file-system-hierarchy-FSH.md](danos-file-system-hierarchy-FSH.md) — the
|
- [file-system-hierarchy.md](file-system-development/file-system-hierarchy.md) — the
|
||||||
filesystem layout the file surface serves.
|
filesystem layout the file surface serves.
|
||||||
- [coding-standards.md](coding-standards.md) — danos naming (why the compat spellings
|
- [coding-standards.md](coding-standards.md) — danos naming (why the compat spellings
|
||||||
are confined, and now retired).
|
are confined, and now retired).
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
//! The "client" library domain (library/client): userspace-service clients —
|
||||||
|
//! they talk to services over IPC, not to the kernel. Client modules end in
|
||||||
|
//! `-client` the way wire protocols end in `-protocol`, so a service, its
|
||||||
|
//! protocol, and its client never share a name (`display` the service,
|
||||||
|
//! `display-protocol` the wire contract, `display-client` a program's view).
|
||||||
|
|
||||||
|
const std = @import("std");
|
||||||
|
|
||||||
|
pub fn build(b: *std.Build) void {
|
||||||
|
const kernel = b.dependency("kernel", .{});
|
||||||
|
const protocol = b.dependency("protocol", .{});
|
||||||
|
|
||||||
|
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");
|
||||||
|
|
||||||
|
// A client frames its own packets, so it needs the envelope alongside the
|
||||||
|
// protocol whose verbs it speaks.
|
||||||
|
const envelope = protocol.module("envelope");
|
||||||
|
|
||||||
|
_ = b.addModule("display-client", .{
|
||||||
|
.root_source_file = b.path("display/display-client.zig"),
|
||||||
|
.imports = &.{
|
||||||
|
.{ .name = "channel", .module = channel },
|
||||||
|
.{ .name = "envelope", .module = envelope },
|
||||||
|
.{ .name = "ipc", .module = ipc },
|
||||||
|
.{ .name = "time", .module = time },
|
||||||
|
.{ .name = "display-protocol", .module = protocol.module("display-protocol") },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
_ = b.addModule("input-client", .{
|
||||||
|
.root_source_file = b.path("input/input-client.zig"),
|
||||||
|
.imports = &.{
|
||||||
|
.{ .name = "channel", .module = channel },
|
||||||
|
.{ .name = "envelope", .module = envelope },
|
||||||
|
.{ .name = "ipc", .module = ipc },
|
||||||
|
.{ .name = "time", .module = time },
|
||||||
|
.{ .name = "input-protocol", .module = protocol.module("input-protocol") },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Standalone `zig build test`, kept for uniformity across the domains (the
|
||||||
|
// root aggregate depends on every domain's test step). The clients have no
|
||||||
|
// host-runnable unit tests yet — they are thin IPC conversation wrappers —
|
||||||
|
// so the step is empty until one grows some.
|
||||||
|
_ = b.step("test", "Run the client unit tests (none yet)");
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
.{
|
||||||
|
.name = .client,
|
||||||
|
.version = "0.0.0",
|
||||||
|
.fingerprint = 0xc74404553e73d4ff, // Changing this has security and trust implications.
|
||||||
|
.minimum_zig_version = "0.16.0",
|
||||||
|
.dependencies = .{
|
||||||
|
// The clients converse over ipc with time-bounded waits.
|
||||||
|
.kernel = .{ .path = "../kernel" },
|
||||||
|
// Each client speaks its service's wire protocol.
|
||||||
|
.protocol = .{ .path = "../protocol" },
|
||||||
|
},
|
||||||
|
.paths = .{""},
|
||||||
|
}
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
//! 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 `/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 envelope = @import("envelope");
|
||||||
|
const ipc = @import("ipc");
|
||||||
|
const time = @import("time");
|
||||||
|
const display_protocol = @import("display-protocol");
|
||||||
|
|
||||||
|
const Protocol = display_protocol.Protocol;
|
||||||
|
|
||||||
|
/// The display's current mode, as `info()` reports it.
|
||||||
|
pub const Info = struct {
|
||||||
|
width: u32,
|
||||||
|
height: u32,
|
||||||
|
pitch: u32, // bytes per row (may exceed width*4; see docs/framebuffer.md)
|
||||||
|
format: u32, // a device-abi DisplayFormat value (0 = rgbx, 1 = bgrx)
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The service endpoint, looked up once and cached.
|
||||||
|
var handle: ?ipc.Handle = null;
|
||||||
|
|
||||||
|
/// 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 (channel.openEndpoint("display")) |h| {
|
||||||
|
handle = h;
|
||||||
|
return h;
|
||||||
|
}
|
||||||
|
time.sleepMillis(50);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A reply the compositor answered with, kept whole so the caller can decode the
|
||||||
|
/// verb's own fixed part out of it.
|
||||||
|
const Answered = struct {
|
||||||
|
packet: [display_protocol.message_maximum]u8,
|
||||||
|
len: usize,
|
||||||
|
|
||||||
|
fn bytes(self: *const Answered) []const u8 {
|
||||||
|
return self.packet[0..self.len];
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Send one request (`target` addresses a layer, or 0 for the compositor itself)
|
||||||
|
/// and keep the reply. Null when the transport failed or the compositor refused.
|
||||||
|
fn transact(
|
||||||
|
comptime operation: Protocol.Operation,
|
||||||
|
target: u64,
|
||||||
|
request: Protocol.RequestOf(operation),
|
||||||
|
tail: []const u8,
|
||||||
|
) ?Answered {
|
||||||
|
const h = service() orelse return null;
|
||||||
|
var packet: [display_protocol.message_maximum]u8 = undefined;
|
||||||
|
const framed = Protocol.encodeRequest(operation, target, request, tail, &packet) orelse return null;
|
||||||
|
var answered: Answered = .{ .packet = undefined, .len = 0 };
|
||||||
|
answered.len = ipc.call(h, framed, &answered.packet) catch return null;
|
||||||
|
const status = envelope.statusOf(answered.bytes()) orelse return null;
|
||||||
|
if (status.status != 0) return null;
|
||||||
|
return answered;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The display's current mode, or null if the service never came up.
|
||||||
|
pub fn info() ?Info {
|
||||||
|
const answered = transact(.info, 0, {}, &.{}) orelse return null;
|
||||||
|
const reply = Protocol.decodeReply(.info, answered.bytes()) orelse return null;
|
||||||
|
return .{ .width = reply.width, .height = reply.height, .pitch = reply.pitch, .format = reply.format };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Composite the dirty layers and flush the frame to the screen.
|
||||||
|
pub fn present() bool {
|
||||||
|
return transact(.present, 0, {}, &.{}) != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One selectable display mode.
|
||||||
|
pub const Mode = display_protocol.Mode;
|
||||||
|
|
||||||
|
/// Fill `out` with the resolutions the display can switch to; returns how many were written
|
||||||
|
/// (zero on the GOP floor, or if the service never came up).
|
||||||
|
pub fn modes(out: []Mode) usize {
|
||||||
|
const answered = transact(.get_modes, 0, {}, &.{}) orelse return 0;
|
||||||
|
const offered = Protocol.decodeReply(.get_modes, answered.bytes()) orelse return 0;
|
||||||
|
const count = @min(@min(offered.count, display_protocol.max_modes), out.len);
|
||||||
|
for (0..count) |i| out[i] = offered.modes[i];
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Change the display resolution. Only a native backend that supports mode-setting honours it
|
||||||
|
/// (on the GOP floor it returns false); on success the display's `info()` reports the new mode.
|
||||||
|
pub fn setMode(width: u32, height: u32) bool {
|
||||||
|
const changed = transact(.set_mode, 0, .{ .width = width, .height = height }, &.{}) != null;
|
||||||
|
if (changed) mode = null; // the cached mode is stale now
|
||||||
|
return changed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The mode, cached after the first `info()` so `color()` doesn't round-trip per pixel.
|
||||||
|
var mode: ?Info = null;
|
||||||
|
|
||||||
|
fn cachedInfo() ?Info {
|
||||||
|
if (mode) |m| return m;
|
||||||
|
const i = info() orelse return null;
|
||||||
|
mode = i;
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The native pixel value for an 8-bit-per-channel colour, in the display's format. A
|
||||||
|
/// client packs colours through this so it never has to know the byte order itself.
|
||||||
|
pub fn color(r: u8, g: u8, b: u8) u32 {
|
||||||
|
const format = if (cachedInfo()) |i| i.format else 0;
|
||||||
|
return display_protocol.pack(format, r, g, b);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A handle to a server-owned layer: a positioned, z-ordered surface the client draws
|
||||||
|
/// into by command. Create with `createLayer`; drawing and moves take effect on the next
|
||||||
|
/// `present`. Coordinates are signed (a layer may sit partly off-screen).
|
||||||
|
///
|
||||||
|
/// The id is the packet header's `target` on every call below, so it is named once
|
||||||
|
/// per request rather than repeated inside one.
|
||||||
|
pub const Layer = struct {
|
||||||
|
id: u32,
|
||||||
|
|
||||||
|
/// Fill a rectangle of this layer (layer-local coordinates) with a native `colour`.
|
||||||
|
pub fn fill(self: Layer, x: i32, y: i32, w: u32, h: u32, colour: u32) bool {
|
||||||
|
return transact(.fill_rect, self.id, .{ .x = x, .y = y, .width = w, .height = h, .colour = colour }, &.{}) != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Copy a `w`×`h` tile of native pixels (row-major, little-endian bytes) into this
|
||||||
|
/// layer at (`x`, `y`). The tile rides inline as the request's tail, so `w*h*4` must
|
||||||
|
/// fit `display_protocol.maximum_payload` — the bound the protocol derives from this
|
||||||
|
/// verb's own fixed part, so the check here can never drift from what fits.
|
||||||
|
pub fn blitTile(self: Layer, x: i32, y: i32, w: u32, h: u32, pixels: []const u8) bool {
|
||||||
|
if (pixels.len > display_protocol.maximum_payload) return false;
|
||||||
|
return transact(.blit_tile, self.id, .{ .x = x, .y = y, .width = w, .height = h }, pixels) != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Move / restack / show or hide the layer.
|
||||||
|
pub fn configure(self: Layer, x: i32, y: i32, z: u32, visible: bool) bool {
|
||||||
|
return transact(.configure_layer, self.id, .{ .x = x, .y = y, .z = z, .visible = if (visible) 1 else 0 }, &.{}) != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mark a rectangle of this layer (layer-local) dirty for the next present — for when
|
||||||
|
/// the layer's pixels changed without a drawing call the compositor already tracked.
|
||||||
|
pub fn damage(self: Layer, x: i32, y: i32, w: u32, h: u32) bool {
|
||||||
|
return transact(.damage, self.id, .{ .x = x, .y = y, .width = w, .height = h }, &.{}) != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Release the layer and its surface.
|
||||||
|
pub fn destroy(self: Layer) bool {
|
||||||
|
return transact(.destroy_layer, self.id, {}, &.{}) != null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Create a server-owned layer of `w`×`h` pixels at screen (`x`, `y`) with stacking order
|
||||||
|
/// `z` (higher is nearer the front), initially visible. Returns a handle, or null.
|
||||||
|
pub fn createLayer(x: i32, y: i32, w: u32, h: u32, z: u32) ?Layer {
|
||||||
|
const answered = transact(.create_layer, 0, .{ .x = x, .y = y, .width = w, .height = h, .z = z, .visible = 1 }, &.{}) orelse return null;
|
||||||
|
return .{ .id = (Protocol.decodeReply(.create_layer, answered.bytes()) orelse return null).layer };
|
||||||
|
}
|
||||||
@@ -21,37 +21,39 @@
|
|||||||
//! if (event.asKeyboard()) |k| { ... } else if (event.asMouse()) |m| { ... }
|
//! if (event.asKeyboard()) |k| { ... } else if (event.asMouse()) |m| { ... }
|
||||||
//! }
|
//! }
|
||||||
|
|
||||||
const std = @import("std");
|
const channel = @import("channel");
|
||||||
const abi = @import("abi");
|
const envelope = @import("envelope");
|
||||||
const ipc = @import("ipc.zig");
|
const ipc = @import("ipc");
|
||||||
const system = @import("system.zig");
|
const time = @import("time");
|
||||||
const protocol = @import("input-protocol");
|
const input_protocol = @import("input-protocol");
|
||||||
|
|
||||||
pub const DeviceKind = protocol.DeviceKind;
|
const Protocol = input_protocol.Protocol;
|
||||||
pub const InputEvent = protocol.InputEvent;
|
|
||||||
pub const KeyEvent = protocol.KeyEvent;
|
pub const DeviceKind = input_protocol.DeviceKind;
|
||||||
pub const MouseEvent = protocol.MouseEvent;
|
pub const InputEvent = input_protocol.InputEvent;
|
||||||
pub const JoystickEvent = protocol.JoystickEvent;
|
pub const KeyEvent = input_protocol.KeyEvent;
|
||||||
pub const EventKind = protocol.EventKind;
|
pub const MouseEvent = input_protocol.MouseEvent;
|
||||||
pub const MouseEventKind = protocol.MouseEventKind;
|
pub const JoystickEvent = input_protocol.JoystickEvent;
|
||||||
pub const JoystickEventKind = protocol.JoystickEventKind;
|
pub const EventKind = input_protocol.EventKind;
|
||||||
pub const Keycode = protocol.Keycode;
|
pub const MouseEventKind = input_protocol.MouseEventKind;
|
||||||
|
pub const JoystickEventKind = input_protocol.JoystickEventKind;
|
||||||
|
pub const Keycode = input_protocol.Keycode;
|
||||||
|
|
||||||
/// Interest masks re-exported so a caller can `subscribe(input.device_keyboard |
|
/// Interest masks re-exported so a caller can `subscribe(input.device_keyboard |
|
||||||
/// input.device_mouse)`.
|
/// input.device_mouse)`.
|
||||||
pub const device_keyboard = protocol.device_keyboard;
|
pub const device_keyboard = input_protocol.device_keyboard;
|
||||||
pub const device_mouse = protocol.device_mouse;
|
pub const device_mouse = input_protocol.device_mouse;
|
||||||
pub const device_joystick = protocol.device_joystick;
|
pub const device_joystick = input_protocol.device_joystick;
|
||||||
pub const device_all = protocol.device_all;
|
pub const device_all = input_protocol.device_all;
|
||||||
|
|
||||||
/// Look up the input service, retrying while it is still coming up. Both a subscriber and
|
/// Open `/protocol/input`, 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
|
/// a source race the service's bind at boot, so both wait for it here rather than
|
||||||
/// failing. Returns the service endpoint handle, or null if it never appears.
|
/// failing. Returns the provider's endpoint handle, or null if it never appears.
|
||||||
fn lookupService() ?ipc.Handle {
|
fn lookupService() ?ipc.Handle {
|
||||||
var attempts: usize = 0;
|
var attempts: usize = 0;
|
||||||
while (attempts < 100) : (attempts += 1) {
|
while (attempts < 100) : (attempts += 1) {
|
||||||
if (ipc.lookup(.input)) |handle| return handle;
|
if (channel.openEndpoint("input")) |handle| return handle;
|
||||||
system.sleep(50);
|
time.sleepMillis(50);
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -66,31 +68,44 @@ pub const Subscriber = struct {
|
|||||||
/// The endpoint the service delivers events to (created and owned by us; its handle
|
/// The endpoint the service delivers events to (created and owned by us; its handle
|
||||||
/// was handed to the service as a capability at subscribe time).
|
/// was handed to the service as a capability at subscribe time).
|
||||||
endpoint: ipc.Handle,
|
endpoint: ipc.Handle,
|
||||||
receive: [protocol.event_size]u8 = undefined,
|
/// A pushed packet is the folded header plus one typed event, so the buffer is
|
||||||
|
/// the push floor rather than any one event's size.
|
||||||
|
receive: [envelope.post_maximum]u8 = undefined,
|
||||||
|
|
||||||
/// Block until the next event is pushed, and return it. Events arrive as asynchronous
|
/// Block until the next event is pushed, and return it. Events arrive as asynchronous
|
||||||
/// buffered messages (`ipc_send` from the service), so nothing is owed in reply — the
|
/// buffered messages (`ipc_send` from the service), so nothing is owed in reply — the
|
||||||
/// empty reply this issues is a harmless no-op. Returns null for any non-event wake-up
|
/// empty reply this issues is a harmless no-op. Returns null for any non-event wake-up
|
||||||
/// (there should be none), so callers can loop.
|
/// (there should be none), so callers can loop.
|
||||||
|
///
|
||||||
|
/// The device class is the packet's operation, so it is read from the header and
|
||||||
|
/// re-tagged into an `InputEvent` here — one decoded type for a caller that took
|
||||||
|
/// several classes on one stream.
|
||||||
pub fn next(self: *Subscriber) ?InputEvent {
|
pub fn next(self: *Subscriber) ?InputEvent {
|
||||||
const got = ipc.replyWait(self.endpoint, &.{}, &self.receive, null);
|
const got = ipc.replyWait(self.endpoint, &.{}, &self.receive, null);
|
||||||
if (!got.isMessage() or got.len < protocol.event_size) return null;
|
if (!got.isMessage()) return null;
|
||||||
return std.mem.bytesToValue(InputEvent, self.receive[0..protocol.event_size]);
|
const packet = self.receive[0..@min(got.len, self.receive.len)];
|
||||||
|
return switch (Protocol.eventOf(packet) orelse return null) {
|
||||||
|
.keyboard => InputEvent.fromKeyboard(Protocol.decodeEvent(.keyboard, packet) orelse return null),
|
||||||
|
.mouse => InputEvent.fromMouse(Protocol.decodeEvent(.mouse, packet) orelse return null),
|
||||||
|
.joystick => InputEvent.fromJoystick(Protocol.decodeEvent(.joystick, packet) orelse return null),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Subscribe to the input classes named in `device_mask` (an OR of `device_*`, or
|
/// Subscribe to the input classes named in `device_mask` (an OR of `device_*`, or
|
||||||
/// `device_all`). Creates an endpoint for the service to push to and hands it over as a
|
/// `device_all`). Creates an endpoint for the service to push to and hands it over as a
|
||||||
/// capability. Returns a `Subscriber` to loop `next` on, or null on failure.
|
/// capability — the envelope's reserved `subscribe`, whose shape this is exactly. Returns
|
||||||
|
/// a `Subscriber` to loop `next` on, or null on failure.
|
||||||
pub fn subscribe(device_mask: u32) ?Subscriber {
|
pub fn subscribe(device_mask: u32) ?Subscriber {
|
||||||
const service = lookupService() orelse return null;
|
const service = lookupService() orelse return null;
|
||||||
const endpoint = ipc.createIpcEndpoint() orelse return null;
|
const endpoint = ipc.createIpcEndpoint() orelse return null;
|
||||||
|
|
||||||
var request = protocol.Request{ .operation = @intFromEnum(protocol.Operation.subscribe), .device_mask = device_mask };
|
var packet: [input_protocol.message_maximum]u8 = undefined;
|
||||||
var reply: [protocol.reply_size]u8 = undefined;
|
const framed = input_protocol.encodeSubscribe(device_mask, &packet) orelse return null;
|
||||||
const result = ipc.callCap(service, std.mem.asBytes(&request), &reply, endpoint) catch return null;
|
var reply: [input_protocol.message_maximum]u8 = undefined;
|
||||||
if (result.len < protocol.reply_size) return null;
|
const result = ipc.callCap(service, framed, &reply, endpoint) catch return null;
|
||||||
if (std.mem.bytesToValue(protocol.Reply, reply[0..protocol.reply_size]).status != 0) return null;
|
const status = envelope.statusOf(reply[0..result.len]) orelse return null;
|
||||||
|
if (status.status != 0) return null;
|
||||||
return .{ .endpoint = endpoint };
|
return .{ .endpoint = endpoint };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -149,11 +164,12 @@ pub const Publisher = struct {
|
|||||||
service: ipc.Handle,
|
service: ipc.Handle,
|
||||||
|
|
||||||
fn publish(self: Publisher, event: InputEvent) bool {
|
fn publish(self: Publisher, event: InputEvent) bool {
|
||||||
var request = protocol.Request{ .operation = @intFromEnum(protocol.Operation.publish), .event = event };
|
var packet: [input_protocol.message_maximum]u8 = undefined;
|
||||||
var reply: [protocol.reply_size]u8 = undefined;
|
const framed = Protocol.encodeRequest(.publish, 0, event, &.{}, &packet) orelse return false;
|
||||||
const len = ipc.call(self.service, std.mem.asBytes(&request), &reply) catch return false;
|
var reply: [input_protocol.message_maximum]u8 = undefined;
|
||||||
if (len < protocol.reply_size) return false;
|
const len = ipc.call(self.service, framed, &reply) catch return false;
|
||||||
return std.mem.bytesToValue(protocol.Reply, reply[0..protocol.reply_size]).status == 0;
|
const status = envelope.statusOf(reply[0..len]) orelse return false;
|
||||||
|
return status.status == 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Broadcast a keyboard event to every subscriber that took keyboard events.
|
/// Broadcast a keyboard event to every subscriber that took keyboard events.
|
||||||
@@ -204,8 +220,8 @@ pub fn syntheticKeyEvent(step: usize) KeyEvent {
|
|||||||
pub fn syntheticMouseEvent(step: usize) MouseEvent {
|
pub fn syntheticMouseEvent(step: usize) MouseEvent {
|
||||||
return switch (step % 3) {
|
return switch (step % 3) {
|
||||||
0 => .{ .kind = @intFromEnum(MouseEventKind.motion), .button = 0, .dx = 1, .dy = 1, .scroll_x = 0, .scroll_y = 0, .buttons = 0 },
|
0 => .{ .kind = @intFromEnum(MouseEventKind.motion), .button = 0, .dx = 1, .dy = 1, .scroll_x = 0, .scroll_y = 0, .buttons = 0 },
|
||||||
1 => .{ .kind = @intFromEnum(MouseEventKind.button_down), .button = protocol.mouse_button_left, .dx = 0, .dy = 0, .scroll_x = 0, .scroll_y = 0, .buttons = protocol.mouse_button_left },
|
1 => .{ .kind = @intFromEnum(MouseEventKind.button_down), .button = input_protocol.mouse_button_left, .dx = 0, .dy = 0, .scroll_x = 0, .scroll_y = 0, .buttons = input_protocol.mouse_button_left },
|
||||||
else => .{ .kind = @intFromEnum(MouseEventKind.button_up), .button = protocol.mouse_button_left, .dx = 0, .dy = 0, .scroll_x = 0, .scroll_y = 0, .buttons = 0 },
|
else => .{ .kind = @intFromEnum(MouseEventKind.button_up), .button = input_protocol.mouse_button_left, .dx = 0, .dy = 0, .scroll_x = 0, .scroll_y = 0, .buttons = 0 },
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
//! The "csv" library domain: shared CSV helpers (comment stripping, field
|
||||||
|
//! iteration) for the /system/configuration/*.csv config files — the device registry and the
|
||||||
|
//! init service list both parse them.
|
||||||
|
|
||||||
|
const std = @import("std");
|
||||||
|
|
||||||
|
pub fn build(b: *std.Build) void {
|
||||||
|
_ = b.addModule("csv", .{ .root_source_file = b.path("csv.zig") });
|
||||||
|
|
||||||
|
// Standalone `zig build test` for this domain alone; the root build keeps
|
||||||
|
// its aggregate test step.
|
||||||
|
const test_step = b.step("test", "Run the csv unit tests");
|
||||||
|
const csv_tests = b.addTest(.{
|
||||||
|
.root_module = b.createModule(.{
|
||||||
|
.root_source_file = b.path("csv.zig"),
|
||||||
|
.target = b.resolveTargetQuery(.{}),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
test_step.dependOn(&b.addRunArtifact(csv_tests).step);
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
.{
|
||||||
|
.name = .csv,
|
||||||
|
.version = "0.0.0",
|
||||||
|
.fingerprint = 0x8a4525791f4e5b6, // Changing this has security and trust implications.
|
||||||
|
.minimum_zig_version = "0.16.0",
|
||||||
|
.dependencies = .{},
|
||||||
|
.paths = .{""},
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
//! 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.
|
||||||
|
|
||||||
|
const std = @import("std");
|
||||||
|
|
||||||
|
/// Strip a trailing `#` comment and surrounding whitespace from one raw line.
|
||||||
|
/// A blank or comment-only line returns "" (length 0) — the caller's skip signal.
|
||||||
|
pub fn stripComment(raw: []const u8) []const u8 {
|
||||||
|
const body = if (std.mem.indexOfScalar(u8, raw, '#')) |hash| raw[0..hash] else raw;
|
||||||
|
return std.mem.trim(u8, body, " \t\r\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Iterate the comma-separated fields of a line body, each trimmed of spaces and
|
||||||
|
/// tabs. Build it from a `stripComment`ed body.
|
||||||
|
pub const Fields = struct {
|
||||||
|
inner: std.mem.SplitIterator(u8, .scalar),
|
||||||
|
|
||||||
|
/// The next field, trimmed, or null when the row is exhausted.
|
||||||
|
pub fn next(self: *Fields) ?[]const u8 {
|
||||||
|
const field = self.inner.next() orelse return null;
|
||||||
|
return std.mem.trim(u8, field, " \t");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
pub fn fields(body: []const u8) Fields {
|
||||||
|
return .{ .inner = std.mem.splitScalar(u8, body, ',') };
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- tests -------------------------------------------------------------------
|
||||||
|
|
||||||
|
const testing = std.testing;
|
||||||
|
|
||||||
|
test "stripComment trims and drops comments" {
|
||||||
|
try testing.expectEqualStrings("a, b", stripComment(" a, b # trailing\r\n"));
|
||||||
|
try testing.expectEqualStrings("", stripComment(" # whole-line comment"));
|
||||||
|
try testing.expectEqualStrings("", stripComment(" \t "));
|
||||||
|
try testing.expectEqualStrings("x", stripComment("x"));
|
||||||
|
}
|
||||||
|
|
||||||
|
test "fields splits and trims each column" {
|
||||||
|
var it = fields(stripComment("pci, 03 , 80 , /system/drivers/x # note"));
|
||||||
|
try testing.expectEqualStrings("pci", it.next().?);
|
||||||
|
try testing.expectEqualStrings("03", it.next().?);
|
||||||
|
try testing.expectEqualStrings("80", it.next().?);
|
||||||
|
try testing.expectEqualStrings("/system/drivers/x", it.next().?);
|
||||||
|
try testing.expect(it.next() == null);
|
||||||
|
}
|
||||||
|
|
||||||
|
test "a single field yields one column then null" {
|
||||||
|
var it = fields(stripComment("/system/services/input"));
|
||||||
|
try testing.expectEqualStrings("/system/services/input", it.next().?);
|
||||||
|
try testing.expect(it.next() == null);
|
||||||
|
}
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,133 @@
|
|||||||
|
//! Block-device client: the helper a filesystem uses to read and write a block
|
||||||
|
//! device (a USB stick, via usb-storage) without hand-rolling the block-protocol
|
||||||
|
//! IPC. Layered over `ipc` and the shared `block-protocol` wire format, like
|
||||||
|
//! `runtime.usb` over the transfer protocol.
|
||||||
|
//!
|
||||||
|
//! Transfers name a caller-owned DMA buffer by physical address (from
|
||||||
|
//! `runtime.dma.alloc`), so whole sectors move without crossing the IPC size
|
||||||
|
//! limit — the same handoff usb-storage uses toward the controller.
|
||||||
|
|
||||||
|
const std = @import("std");
|
||||||
|
const envelope = @import("envelope");
|
||||||
|
const ipc = @import("ipc");
|
||||||
|
const block_protocol = @import("block-protocol");
|
||||||
|
|
||||||
|
const Protocol = block_protocol.Protocol;
|
||||||
|
|
||||||
|
/// The medium_changed event payload, re-exported so a consumer decodes it without
|
||||||
|
/// reaching into the wire-format module.
|
||||||
|
pub const MediumChanged = block_protocol.MediumChanged;
|
||||||
|
|
||||||
|
/// Decode a medium_changed event from a buffered-message payload a subscriber
|
||||||
|
/// received (a `Received.isMessage` wake). Null if the bytes are too short to be
|
||||||
|
/// one — a caller ignores anything that is not a well-formed event.
|
||||||
|
pub fn decodeMediumChanged(payload: []const u8) ?MediumChanged {
|
||||||
|
if (payload.len < envelope.prefix_size + @sizeOf(MediumChanged)) return null;
|
||||||
|
return std.mem.bytesToValue(MediumChanged, payload[envelope.prefix_size..][0..@sizeOf(MediumChanged)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const Geometry = struct { block_size: u32, block_count: u64 };
|
||||||
|
|
||||||
|
pub const Device = struct {
|
||||||
|
endpoint: ipc.Handle,
|
||||||
|
|
||||||
|
/// The device's block size and total block count.
|
||||||
|
pub fn geometry(self: Device) ?Geometry {
|
||||||
|
var reply: [block_protocol.message_maximum]u8 = undefined;
|
||||||
|
const answered = self.call(.geometry, {}, null, &reply) orelse return null;
|
||||||
|
const result = Protocol.decodeReply(.geometry, answered) orelse return null;
|
||||||
|
return .{ .block_size = result.block_size, .block_count = result.block_count };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hand the block server a DMA-region capability (`handle` — from a `shareable`
|
||||||
|
/// dma_alloc) so it forwards it to the controller and the buffer's physical
|
||||||
|
/// addresses become reachable by the device. Call once per buffer before naming it
|
||||||
|
/// in `read`/`write`. Harmless success when no IOMMU is enforcing.
|
||||||
|
pub fn attach(self: Device, handle: ipc.Handle) bool {
|
||||||
|
var reply: [block_protocol.message_maximum]u8 = undefined;
|
||||||
|
return self.call(.attach, {}, handle, &reply) != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The reverse of `attach`: the buffer leaves the device's reach. The same
|
||||||
|
/// region capability rides again (the kernel matches the region). Do not name
|
||||||
|
/// the buffer's physical address in `read`/`write` after this.
|
||||||
|
pub fn detach(self: Device, handle: ipc.Handle) bool {
|
||||||
|
var reply: [block_protocol.message_maximum]u8 = undefined;
|
||||||
|
return self.call(.detach, {}, handle, &reply) != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read `count` blocks starting at `lba` into the DMA buffer at `physical`.
|
||||||
|
pub fn read(self: Device, lba: u64, count: u32, physical: u64) bool {
|
||||||
|
var reply: [block_protocol.message_maximum]u8 = undefined;
|
||||||
|
return self.call(.read, .{ .lba = lba, .count = count, .physical = physical }, null, &reply) != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write `count` blocks starting at `lba` from the DMA buffer at `physical`.
|
||||||
|
pub fn write(self: Device, lba: u64, count: u32, physical: u64) bool {
|
||||||
|
var reply: [block_protocol.message_maximum]u8 = undefined;
|
||||||
|
return self.call(.write, .{ .lba = lba, .count = count, .physical = physical }, null, &reply) != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Commit any device write cache to stable media (SCSI SYNCHRONIZE CACHE), so
|
||||||
|
/// prior writes survive a power-off. A filesystem calls this before the machine
|
||||||
|
/// goes down; no data transfer, so the buffer arguments are unused.
|
||||||
|
pub fn flush(self: Device) bool {
|
||||||
|
var reply: [block_protocol.message_maximum]u8 = undefined;
|
||||||
|
return self.call(.flush, {}, null, &reply) != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Confine the process `badge` to blocks `[base_lba, base_lba + block_count)`
|
||||||
|
/// on this device — the volume manager's per-volume grant to a filesystem.
|
||||||
|
/// The caller must itself be unconfined (whole-device); a confined caller is
|
||||||
|
/// refused, so a filesystem cannot widen its own range. See `DefineRange`.
|
||||||
|
pub fn defineRange(self: Device, badge: u32, base_lba: u64, block_count: u64) bool {
|
||||||
|
var reply: [block_protocol.message_maximum]u8 = undefined;
|
||||||
|
return self.call(.define_range, .{ .badge = badge, .base_lba = base_lba, .block_count = block_count }, null, &reply) != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One request at the driver. `target` is always 0: one endpoint per device, so
|
||||||
|
/// there is no object within the peer to address.
|
||||||
|
fn call(
|
||||||
|
self: Device,
|
||||||
|
comptime operation: Protocol.Operation,
|
||||||
|
request: Protocol.RequestOf(operation),
|
||||||
|
capability: ?ipc.Handle,
|
||||||
|
reply: []u8,
|
||||||
|
) ?[]u8 {
|
||||||
|
var packet: [block_protocol.message_maximum]u8 = undefined;
|
||||||
|
const framed = Protocol.encodeRequest(operation, 0, request, &.{}, &packet) orelse return null;
|
||||||
|
const answer = ipc.callCap(self.endpoint, framed, reply, capability) catch return null;
|
||||||
|
const status = envelope.statusOf(reply[0..answer.len]) orelse return null;
|
||||||
|
if (status.status != 0) return null;
|
||||||
|
return reply[0..answer.len];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Subscribe `subscriber` (an endpoint) to this device's medium_changed
|
||||||
|
/// events: the reserved `subscribe` verb carries the subscriber's endpoint as
|
||||||
|
/// the capability, and the driver then ipc.sends each medium transition to it.
|
||||||
|
pub fn subscribeMedium(self: Device, subscriber: ipc.Handle) bool {
|
||||||
|
var packet: [block_protocol.message_maximum]u8 = undefined;
|
||||||
|
const framed = envelope.encodeSubscribe(0, &packet) orelse return false; // interest 0: every event (block has one)
|
||||||
|
var reply: [block_protocol.message_maximum]u8 = undefined;
|
||||||
|
const answer = ipc.callCap(self.endpoint, framed, &reply, subscriber) catch return false;
|
||||||
|
const status = envelope.statusOf(reply[0..answer.len]) orelse return false;
|
||||||
|
return status.status == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Unsubscribe from this device's medium_changed events. Call before closing
|
||||||
|
/// the channel so the driver's bounded subscriber table frees the slot rather
|
||||||
|
/// than holding a dead endpoint until an exit sweep notices.
|
||||||
|
pub fn unsubscribeMedium(self: Device) bool {
|
||||||
|
var packet: [block_protocol.message_maximum]u8 = undefined;
|
||||||
|
const framed = envelope.encodeUnsubscribe(&packet) orelse return false;
|
||||||
|
var reply: [block_protocol.message_maximum]u8 = undefined;
|
||||||
|
const answer = ipc.callCap(self.endpoint, framed, &reply, null) catch return false;
|
||||||
|
const status = envelope.statusOf(reply[0..answer.len]) orelse return false;
|
||||||
|
return status.status == 0;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// There is deliberately no open-by-name here: `block` is not a registry name.
|
||||||
|
// One storage process serves each volume, and a consumer receives its volume's
|
||||||
|
// channel from the device manager (establishment by lineage, communication.md
|
||||||
|
// "Establishment: two planes"), then wraps it: `block.Device{ .endpoint = c }`.
|
||||||
Loaded 100 of 332 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user