//! /system/services/init — the first user-space program, PID 1. Built as its own //! freestanding binary (see build.zig), shipped on the boot volume at /system/services/init, //! loaded by the bootloader, and started in ring 3 as a scheduled process by the //! kernel (system/kernel/process.zig). It links against the shared user runtime //! library `runtime` and talks to the kernel only through `runtime`'s system_call wrappers. //! //! It proves the C-convention heap works, then — as PID 1 — acts as the system's //! **service supervisor**: it spawns the user-space services danos brings up at boot //! (the VFS server, the device manager), and settles into an event loop as the root //! of user space. Drivers are *not* its job: the device manager discovers the //! hardware and spawns those. This is the service half of the service/driver spawn //! split (docs/driver-model.md). //! //! M21: init also owns **orderly shutdown**. It supervises its children (keeping //! their ids and an exit endpoint), subscribes to the power service, and on a //! power-button event runs the stop sequence over its children in reverse order //! before asking the power service to enter S5 — lifecycle (M17) and events (M21) //! composing into a clean poweroff. const std = @import("std"); const runtime = @import("runtime"); const power = runtime.power_protocol; /// Where the kernel boot log is persisted on the USB FAT volume — an 8.3 name at /// the mount root (see system/services/log-flush). init writes it at shutdown; /// the log-flush one-shot writes it once at boot. const log_path = "/mnt/usb/DANOS.LOG"; /// The system services init brings up at boot, in order. This is init's policy — the /// microkernel keeps such choices in user space, not the kernel. Drivers are absent /// on purpose: the device manager owns those. (A future init reads this from a /// manifest under /system/services instead of a hardcoded list.) const boot_services = [_][]const u8{ "vfs", "input", "device-manager", "fat" }; var children: [boot_services.len]u32 = .{0} ** boot_services.len; var child_count: usize = 0; var supervision_endpoint: runtime.ipc.Handle = 0; pub fn main() void { // Prove the heap end to end: allocate through the runtime allocator (which // mmaps pages from the kernel and carves them with the free list), write into // that heap buffer (exercising the widened debug_write bounds check), and // free it. A fault here would kill init before it heartbeats — so the init // test doubles as the heap regression test. (C code links the same heap via // the extern malloc/free symbols; Zig code uses this allocator.) const gpa = runtime.allocator(); if (gpa.alloc(u8, 64)) |buffer| { const message = "/system/services/init: heap ok\n"; @memcpy(buffer[0..message.len], message); _ = runtime.system.write(buffer[0..message.len]); gpa.free(buffer); } else |_| {} // One endpoint carries everything init waits on: children's exit // notifications (they are spawned supervised against it), init's own // signals, and power events it subscribes to. All arrive in the loop below. supervision_endpoint = runtime.ipc.createIpcEndpoint() orelse { _ = runtime.system.write("/system/services/init: no endpoint\n"); return; }; _ = runtime.process.bindSignals(supervision_endpoint); // Bring up the boot services, supervised so init can stop them cleanly. // Best-effort and silent: each service announces its own readiness, and in // an isolation test with no initial-ramdisk the spawns simply no-op. for (boot_services) |service| { if (runtime.system.spawnSupervised(service, &.{}, supervision_endpoint)) |id| { children[child_count] = id; child_count += 1; } } // Once the storage stack is up, a one-shot copies the boot log to the USB // volume (/mnt/usb/DANOS.LOG) so it can be read on another machine — the only // way to see it on a headless/real board with no host capturing serial. Fire // and forget: it polls for the mount itself, and is deliberately NOT one of // init's supervised children (a transient one-shot must not be stopped-and- // waited-for during shutdown). _ = runtime.system.spawn("log-flush"); // Subscribe to power events (retry: the power service registers well after // init starts). Best-effort — without it, a `terminate` signal still // triggers the same shutdown path. subscribePower(); // A re-arming timer drives the liveness heartbeat: proof PID 1 is alive // (the init test's marker) while the loop stays free to receive signals, // power events, and children's exit notifications. _ = runtime.system.timerOnce(supervision_endpoint, 1000); var receive: [power.message_maximum]u8 = undefined; while (true) { const got = runtime.ipc.replyWait(supervision_endpoint, &.{}, &receive, null); if (runtime.process.signalsFrom(got.badge)) |signals| { if (signals.has(.terminate)) shutDown(); continue; } if (got.isTimer()) { _ = runtime.system.write("/system/services/init: heartbeat\n"); _ = runtime.system.timerOnce(supervision_endpoint, 1000); continue; } if (got.isMessage() and got.len >= 2 and receive[0] == @intFromEnum(power.Operation.event)) { // A power event (the only buffered messages init receives). if (receive[1] == @intFromEnum(power.Event.power_button)) shutDown(); continue; } // Child-exit notifications and anything else: keep waiting. if (got.isNotification()) continue; } } /// Look up the power service and subscribe our endpoint (handed over as the /// call's capability) so events arrive as buffered messages here. fn subscribePower() void { var handle: ?runtime.ipc.Handle = null; var tries: u32 = 0; while (handle == null and tries < 200) : (tries += 1) { handle = runtime.ipc.lookup(.power); if (handle == null) runtime.system.sleep(20); } // A missing power service is not fatal — init proceeds to its heartbeat and // a `terminate` signal still drives shutdown. Silent so the no-ramdisk init // test's heartbeat marker is the next line written. const h = handle orelse return; const request = power.Subscribe{}; var reply: [power.message_maximum]u8 = undefined; _ = runtime.ipc.callCap(h, std.mem.asBytes(&request), &reply, supervision_endpoint) catch {}; } /// Copy the whole kernel log to /mnt/usb/DANOS.LOG (the same file log-flush /// writes at boot), so a poweroff captures the fullest log. Best-effort: if the /// USB volume is not mounted, the open fails and it does nothing. Must run while /// the storage services are still alive (see shutDown). fn flushKernelLog() void { // Truncate on open so this fuller flush replaces the boot-time one cleanly. var file = runtime.fs.open(log_path, .{ .create = true, .truncate = true }) orelse return; // no USB volume defer file.close(); var chunk: [4096]u8 = undefined; var offset: usize = 0; while (true) { const got = runtime.system.klogRead(offset, &chunk); if (got == 0) break; // reached the end of the accumulated log if (file.writeAll(chunk[0..got]) == null) break; // storage went away offset += got; } var line: [96]u8 = undefined; _ = runtime.system.write(std.fmt.bufPrint(&line, "/system/services/init: flushed log to {s} ({d} bytes)\n", .{ log_path, offset }) catch ""); } /// The stop sequence: persist the log while storage is still up, then terminate /// each child in reverse spawn order (vfs last — other services may flush through /// it), waiting up to a deadline for each to exit before killing it, then ask the /// power service to enter S5. fn shutDown() void { _ = runtime.system.write("/system/services/init: shutting down\n"); // Persist the fullest log to the USB volume BEFORE tearing anything down: the // reverse-order stop loop below kills the fat server (children[3]) first, so // /mnt/usb must be written while it is still mounted. flushKernelLog(); var i = child_count; while (i > 0) { i -= 1; if (children[i] != 0) runtime.process.stop(children[i], 2000, supervision_endpoint); } if (runtime.ipc.lookup(.power)) |h| { const request = power.Shutdown{}; var reply: [power.message_maximum]u8 = undefined; _ = runtime.ipc.call(h, std.mem.asBytes(&request), &reply) catch {}; } // If S5 did not take, init has nothing left to do but idle. while (true) runtime.system.sleep(1000); } pub const panic = runtime.panic; comptime { _ = &runtime.start._start; // pull the runtime entry shim into the image }