Skip to content

Latest commit

 

History

History
437 lines (361 loc) · 22 KB

README.md

File metadata and controls

437 lines (361 loc) · 22 KB

Hadron

Hadron is a monolithic kernel written in Rust. It targets x86_64 first and aarch64 second.

This branch is a rewrite from scratch. The kernel boots through Limine, sets up memory management, threads and a root filesystem, then starts /init and a shell in userspace. The host and boot test suites exercise the reusable libraries and kernel mechanisms.

Layout

crates/ holds libraries that do not depend on Hadron. Another kernel could use them unchanged. kernel/ holds the kernel and the crates written for it.

Path Contents
crates/arch/x86_64 x86_64 addresses, page tables, descriptor tables and the TSS
crates/boot/uefi UEFI type bindings and protocol definitions
crates/boot/limine Limine boot protocol bindings
crates/core/linkset Access to data collected in linker sections
crates/parse/acpi ACPI table parser and static AML namespace walker
crates/parse/dwarf DWARF line-program parser
crates/parse/elf ELF64 parser and x86_64 relocations
crates/parse/fdt Flattened device tree parser
kernel/kernel The kernel
kernel/config Configuration constants generated by Quon and tracked as a Cargo dependency
kernel/ktest Kernel test registration
kernel/mm Memory map, frame allocators, page table mapper and heap

Development

The dev shell provides QEMU, prek and taplo. Rust comes from your own rustup, which installs the nightly toolchain from rust-toolchain.toml.

nix develop          # or `direnv allow` with nix-direnv
prek install         # pre-commit and commit-msg hooks
cargo test --workspace

The hooks check whitespace, final newlines, cargo fmt, taplo fmt and cargo clippy -D warnings. Commit messages must follow Conventional Commits.

Building and running

Quon builds the crates for x86_64-unknown-none and boots the kernel under QEMU with Limine and OVMF. quon.rs holds the build, and limine.conf the boot menu. Cargo compiles the kernel and userspace in separate named target domains. The kernel's build script tracks kernel.ld and applies it to the kernel binary and integration images. kernel/config includes the resolved constants file that Quon supplies through QUON_CONFIG_RS.

Use a Quon build that supports explicit build(&mut Build) graphs and Cargo integration images. With Quon checked out next to Hadron, install that checkout from Hadron's root:

cargo install --path ../quon/crates/quon --locked
quon build          # build the kernel, init and initramfs into build/
quon check          # check kernel and test targets without packaging
quon clippy         # lint their dependencies and the host tests
quon run            # boot the kernel under QEMU

The kernel target uses static relocation. The userspace target uses static relocation and the small code model. Both use the toolchain's prebuilt x86_64-unknown-none libraries; there is no custom sysroot build. Cargo owns their separate dependency closures. Each Rust rule has an independent resolution and backend cache under build/graph/rust/.

Quon runs the host mkinitramfs tool with sorted rootfs/ inputs and the built init, then assembles Limine, limine.conf, the kernel and initramfs into an explicit boot directory. The build step exports kernel, init, hbox, initramfs and esp. Quon publishes these independently of Cargo cache paths. Tools can query their paths through Project::step("build") and Project::output_path; quon explain plan shows their producing actions.

The host-test libraries mix enabled and disabled doctests. Quon keeps this test group on its direct compiler path so disabled doctests stay skipped without changing feature resolution. The host packer is a separate Rust build rule.

quon run opens a QEMU window, runs the init smoke checks, then starts /bin/sh. Type in the QEMU window and read the prompt/output in the terminal that launched Quon. The window captures PS/2 input; framebuffer output is not implemented. Closing QEMU ends the development session successfully. quon test uses a separate headless runner and expects the kernel's isa-debug-exit success status. Release runs and quon run -p test also use the headless runner. The kernel console is COM3, which QEMU sends to the terminal. The firmware and Limine write to COM1 and COM2, and QEMU discards both. The first build downloads Limine's BOOTX64.EFI and checks it against the SHA-256 in quon.rs.

Interrupt callbacks

Kernel drivers call irq::register(handler) with a fn() callback to claim a free CPU vector in 0x20..=0xef. The returned Vector::number() can be programmed into an interrupt controller. irq::register_at claims a specific vector for fixed kernel interrupts; 0xf0..=0xff stays out of automatic allocation. CPU exceptions cannot be claimed, and an occupied vector's callback cannot be replaced.

irq::register_owned also accepts a capturing callback. The registration retains its captured state until shutdown, so callbacks can target a driver instance without a global device pointer. Plain callbacks still need no heap.

Registration is permanent and shared by all CPUs. Callbacks run with interrupts masked, must not sleep, and leave APIC acknowledgement to the dispatcher. Registration does not route or unmask a hardware interrupt. The API and its restrictions are in irq.rs.

Devices and driver bindings

device::DEVICE retains discovered devices and their parent IDs. Platform code registers a platform root and an i8042 child when the FADT advertises an 8042 controller. The i8042 driver creates a PS/2 child named keyboard. The keyboard binds through its parent port, not through platform I/O ports. Boot prints the tree, binding status, and per-device resource usage.

PCI discovery registers one pci-SEGMENT-START-END root per non-overlapping MCFG configuration region and a device per PCI function. Function names use segment:bus:device.function. Valid firmware-configured bridges establish parent relationships; unvisited buses are scanned as region roots. Discovery handles multifunction devices, bounds bridge traversal, and rejects duplicate bus visits. MCFG roots describe configuration regions, not full ACPI host bridges.

PCI records retain vendor/device IDs, class codes, revision, header type, type-0 subsystem IDs, bridge bus numbers, and firmware BAR addresses and types. A 64-bit BAR consumes two slots. Zero BARs cannot distinguish unimplemented registers from unassigned resources. BAR sizes and translations to CPU physical addresses remain unknown. Discovery only reads configuration space and preserves firmware bus numbering and resource assignments.

Each region owns an uncached ECAM mapping shared by its function handles. Checked dword reads remain available during driver probes. PCI drivers use the existing matches/probe API; pci::Match supports optional IDs, subsystem IDs, and masked class codes. Normal boot registers no PCI drivers, so PCI functions remain unbound. The device tree prints their identities and decoded BARs.

This version requires MCFG/ECAM and firmware-configured bridges. It does not assign bus numbers or BARs, size or map BAR resources, enable bus mastering, route INTx/MSI/MSI-X, or support hotplug. ACPI namespace host-bridge discovery, resource windows, legacy configuration ports, and PCI capability traversal are not implemented. ECAM mappings belong to the bus infrastructure; future driver BAR mappings and DMA buffers belong to the function's driver instance.

Drivers implement matches and probe. Each successful probe returns a separate typed instance. The registry owns it and can return typed shared handles without keeping its lock held during driver work. Unmatched devices remain unbound. Failed devices retain their error; neither successful nor failed probes are retried. Driver-created children are registered after their parent's instance is installed. Bus enumerators may register unbound trees. Registration order determines the first matching driver.

Each device has a DriverResources context. Its alloc and shared methods attribute heap payloads to that device. Counts exclude allocator metadata, reference counters, registry storage, and allocations made through ordinary Box or Vec. The context uses the kernel heap, not a private arena. Handles keep accounting alive until their payloads are released. Port claims check the platform descriptor and reject overlapping claims made through this API. Early architecture devices and the COM3 console still use their existing paths. MMIO and DMA acquisition have not moved into this context yet.

The i8042 instance owns the controller's port claims, byte queue, interrupt vector and route. Its keyboard child owns a decoder and consumes the port. Interrupt callbacks retain controller state. There is no runtime detach or interrupt-vector reuse; dropping a route does not release it. A failed probe releases ordinary owned resources, but published interrupt state stays alive. Device operations and resource cleanup run in thread context.

Device filesystem

/dev is a dynamic directory of character-device interfaces. Boot registers console, null, and zero. Console writes use COM3 and console reads return EOF. The shell reads physical events from the separate keyboard endpoint. Null reads return EOF and its writes discard the input. Zero reads fill the requested buffer with zeroes and its writes discard input. /init checks null and zero through the userspace syscall interface.

vfs::devfs::get() returns the mounted namespace. Register an endpoint with a NodeSpec containing its name, permission metadata, and optional device owner ID. Keep the returned Registration in the publishing binding. Dropping the handle removes the name; existing open files retain their endpoint and stream state. A retained inode cannot open the removed endpoint again. An open racing removal may succeed if it observed the node before removal. Removing a name alone does not stop hardware or wake blocked readers; the endpoint must define its own disconnect behavior before runtime driver detach can be supported.

CharDevice::open creates a CharFile for each open. Duplicated descriptors share that stream. Reads and writes have no file offset and use the stream's own synchronization, so a blocked read does not hold a file-position lock against writes. Empty stream reads and writes return zero without invoking the endpoint. Regular files and directories keep their existing offset behavior.

Registration, lookup, and name-sorted directory listing use a namespace lock. Endpoint callbacks and endpoint destruction happen outside that lock. Inode numbers are not reused within a namespace. Names are single path components; subdirectories, userspace node creation, permission enforcement, and Linux major/minor device numbering are not implemented. Directory indices refer to the current entries when registrations change between reads.

Userspace shell

user/hbox is a freestanding Rust multicall program installed as /bin/hbox, /bin/sh, and each utility name. The shell starts utility processes with arguments and waits for foreground commands, inheriting their exit status. A trailing & starts a background command and prints its PID. cd, exit, help, jobs, and status are shell built-ins. Utilities run in userspace using syscalls. The initramfs contains copies of the executable under its applet names until filesystem links are supported. Debug sections are stripped from hbox so the loader can read it within the kernel's fixed heap.

hadron:/ $ ls /
hadron:/ $ ls /dev
hadron:/ $ cat /etc/hostname
hadron:/ $ cd /etc
hadron:/etc $ head -n 3 motd
hadron:/etc $ wc hostname
hadron:/etc $ hexdump hostname
hadron:/etc $ echo "hello world"

Commands: echo [-n], pwd, ls [DIR...], cat [FILE...], head [-n LINES | -c BYTES] [FILE], wc [-l] [FILE], hexdump [FILE], clear, true, false, pid, and kill. hbox COMMAND ... dispatches an applet explicitly. sh -c 'COMMAND' runs one command without keyboard input. Relative paths use the process working directory and children inherit it.

The shell supports single/double quotes, backslash escapes, and comments. Backspace erases a character; Ctrl-U clears a line; Ctrl-C cancels prompt input or interrupts the foreground command. Ctrl-D at an empty prompt exits. status prints the last command status. exit [STATUS] ends the shell and leaves the kernel idle until QEMU is closed. Limits are 512 input bytes, 32 arguments, and 16 tracked background tasks. This shell has no pipelines, redirection, variable expansion, or fg/bg commands. Files are read-only. The shell and its commands inherit /dev/tty0 as stdin, stdout, and stderr. Tools without a filename read terminal characters. Reading an endless device such as /dev/zero requires a bound, such as head -c 32 /dev/zero, or Ctrl-C to interrupt it.

kill [-s SIGNAL | -SIGNAL] PID... sends a signal to known positive PIDs. The default is TERM (15); INT (2), KILL (9), and 0 are also supported. Names may have a SIG prefix. For example, kill -9 42 sends SIGKILL to PID 42, and kill -0 42 checks whether it is running. Missing targets report errno 3. The utility attempts all valid PID operands even if one is missing.

For example, launch a quiet background reader, use the printed PID with kill, and check completion with jobs:

hadron:/ $ wc /dev/keyboard0 &
[42] wc
hadron:/ $ jobs
[42] running
hadron:/ $ kill 42
[42] done 143
hadron:/ $ jobs

jobs lists tracked background PIDs. Completion notices use [PID] done STATUS, with 128 + signal for signal termination. The shell reaps completed children when processing a line and before displaying a prompt. A task that finishes while the shell waits for keyboard input is reported after the next submitted line. Completion notices do not change status; successful background launch sets it to zero. Failed launches do not occupy a task slot.

Quoted or escaped ampersands remain arguments. Only one command per line is supported: command & works, while a & b and a && b are rejected. Shell built-ins reject &. Background tasks inherit the terminal, so their output may interleave with the prompt. Each open of the keyboard device gets its own event cursor. Background tasks keep running after the shell exits; sh -c 'command &' also leaves its child running. There are no process groups, fg/bg commands, or system-wide process listing yet.

For an automated headless session that types through QMP and checks output:

python3 scripts/smoke-shell.py

Set QUON=/absolute/path/to/quon to test with a specific Quon binary.

Terminal

/dev/tty0 is a kernel terminal backed by the primary PS/2 keyboard and COM3 output. /dev/console remains the diagnostic stream, with EOF on reads. The TTY applies the US keyboard layout, including Shift, Caps Lock, and Ctrl. It buffers up to 512 editable ASCII characters and commits a line on Enter. Reads return at most one committed line and support short buffers. Backspace erases a character, Ctrl-U erases the editable line, and Tab inserts a space. Ctrl-D with pending text makes that text readable without a newline; Ctrl-D on an empty line produces one zero-byte read. Later input still works. Committed input is bounded to 4096 bytes and 32 records; overflow rings the terminal bell and keeps the current edit buffer available for correction.

The terminal tracks a stack of foreground PIDs, with a maximum nesting depth of 32. Foreground spawn hands access to the child before it becomes runnable. Exit restores the nearest surviving ancestor, including across nested shells. Ownership changes discard queued and partially edited input. Background TTY reads fail with EIO rather than consuming foreground input; writes are allowed. The raw /dev/keyboard0 event stream remains available independently.

Ctrl-C clears pending terminal input and sends SIGINT to the foreground PID, including when the task is not reading stdin. It does not signal background tasks. The shell selects Hadron's prompt mode through ioctl 0x80007400: Ctrl-C then interrupts its read with EINTR instead of terminating the shell. This is a temporary prompt policy until userspace signal handlers exist.

This is one local terminal, with fixed canonical input and echo settings. There are no process groups, sessions, termios controls, raw mode, pseudoterminals, serial input, or terminal escape-sequence interpretation yet. Output still appears in the host terminal; the QEMU window supplies keyboard input.

Keyboard input

The i8042 controller requires the FADT's 8042-presence flag. Its first port uses ports 0x60 and 0x64; IRQ 1 follows MADT overrides through the I/O APIC. Initialization disables the mouse port and controller translation, checks the controller and keyboard, selects set 2 and enables scanning. Missing hardware or a failed probe is logged and boot continues.

A kernel worker consumes controller bytes and decodes physical keys once. /dev/keyboard0 publishes four-byte records: little-endian set-2 key code, action (0 release, 1 press, 2 repeat, 3 reset), and a zero reserved byte. This is a Hadron format, not Linux evdev. Each open has an independent cursor; duplicates share a cursor. Reads block until events arrive and return complete records. Input loss emits a reset so readers can clear held modifiers. The terminal applies the US layout in the kernel. The shell reads character stdin.

Key logging is off by default so it does not interleave with the shell. QUON_KEYBOARD_DEBUG=true quon run logs decoded events while input remains available to userspace. quon test stays headless.

Userspace ABI

System calls use Linux's x86-64 register convention, syscall numbers and negative errno values. The kernel implements read, write, open, close, ioctl, sched_yield, dup, dup2, getpid, exit, kill, getcwd, chdir, getdents64, gettid and exit_group. open takes a NUL-terminated UTF-8 path, absolute or relative to cwd, and supports only the three access modes. Processes have one thread, so gettid returns the process ID and exit_group acts as exit. Other Linux calls return -ENOSYS.

Hadron's existing spawn and wait interfaces remain available as extensions at 0x80000000 and 0x80000001. Spawn accepts an optional argv pointer as its third argument; passing zero keeps its original behavior. The fourth argument is spawn flags: 0 leaves terminal ownership unchanged, while 1 hands foreground access to the child if its parent currently has it. Background parents cannot acquire the terminal through this flag. Other flags return EINVAL. Wait's second argument selects blocking (0) or nonblocking (1) operation. Nonblocking wait returns -EAGAIN while the child is running and reaps it once it ends; unknown options return -EINVAL, and nonchildren or reaped children return -ECHILD. They do not implement Linux's process creation or wait interfaces. The supported calls and limits are documented in syscall.rs. This is an initial Linux ABI subset; ordinary libc-linked Linux programs need more support.

kill uses Linux x86-64 syscall 62, with a positive PID and signal number. SIGINT, SIGKILL, and SIGTERM have their default terminating action. Signal 0 only checks for a running target. Repeated pending signals coalesce, with SIGKILL taking priority. Delivery runs on the target's own kernel stack before entering or returning to userspace, including after timer interrupts. Keyboard reads and the Hadron child-wait syscall return through their Rust callers when interrupted, releasing guards before process termination. Internal mutex waits remain uninterruptible unless explicitly requested. Signal exit status uses the low seven bits; the shell reports 128 + signal.

This subset has no userspace handlers, signal masks, stop/continue actions, process groups, credential checks, or special PID 1 protection. All current userspace processes may signal each other. Nonpositive/group PIDs and unsupported signals return EINVAL. Ended processes return ESRCH even while their parent retains their exit status for wait; Linux can still find zombies.

Kernel tests

quon test                 # host tests, heap integration image, kernel boot tests
quon test --host          # no QEMU
quon test --integration   # boot each harness=false image
quon test --boot          # boot the test profile's kernel suite

The heap integration target is a separate image compiled by Cargo. Quon substitutes it for the normal kernel in its own ESP copy and boots it with the same QEMU runner.

Kernel tests run inside the kernel after boot. Define one with ktest::ktest! in the kernel crate. A test fails by panicking.

ktest::ktest! {
    fn null_page_is_unmapped() {
        assert_eq!(translate(VirtAddr::ZERO), None);
    }
}

Write #[ignore] before fn to keep a test out of the default run.

quon run -p test                       # enable KTEST through the test preset
QUON_KTEST=true quon run               # enable KTEST in the current profile
QUON_KTEST_IGNORED=true quon run -p test # also run #[ignore] tests

The test-boot step builds a separate kernel with the test configuration. quon run -p test selects that configuration for the normal run step too. Both set the KTEST config option. The kernel then prints one line per test on COM3 and exits QEMU with status 33 when every test passes. The kernel has no unwinding, so the first failing test ends the run: the panic handler prints FAILED and the panic message, and QEMU exits with status 35. quon run exits 0 or 1 to match.

Generated constants and published artifacts distinguish option values, including overrides under the same profile. A later quon run without the override uses the normal configuration and starts /init again. quon configure -p test exports the test profile and its constants for rust-analyzer.

History

  • legacy: the previous monolithic kernel, with userspace, a Wayland compositor and partial Mesa ports.
  • microkernel: an unfinished capability-based microkernel.

License

GPL-3.0-only. See LICENSE.