Commit Graph

168 Commits

Author SHA1 Message Date
55758ae5b2 feat: kernel W^X (per-section perms, firmware unmapped, stack guard, boot check), halt on kernel faults, region W^X across processes 2026-10-27 00:13:00 +01:00
bafc18a5f8 feat(kernel): SystemControl cap for halt, board device table + boot caps to init, RegionAddress syscall, idle loop services irqs 2026-10-26 23:59:57 +01:00
130a82f50d feat(kernel): shared ABI decoder+proofs, no-panic gate, syscall storm, kani on shrunk kernel 2026-10-26 23:44:09 +01:00
154599e3af feat(kernel): derivation-tree revocation, region caps
- caps record parent (mint/delegate/ipc), CapRef w/ pid+slot gens
- Revoke = delete subtree, keep self; drop/death re-parents children
- CreateRegion/MapRegion; mapping lives only as long as its cap
- drop Permission::Revoke + object-wide revoke
- mint any cap (badge only ep/ntfn), process caps delegable
- kani: descendants == subtree; model-based fuzz vs spec
2026-10-26 20:41:03 +01:00
76f10ff1f1 feat(kernel): seL4-style IPC, notifications, status ABI
- badges + Mint, Call/Reply/ReplyRecv w/ gen-checked reply slot
- cap transfer (1/msg, copy, needs Delegate, rechecked at delivery)
- notifications: signal/wait/poll/bind, irq -> notification routing
- WaitAny/WaitForInterrupt removed; a0=status, ErrorCode
- libkos: single ecall primitive, compat wrappers + typed new api
- fix: trap return clobbered user t0 on every trap
- fix: wait queues FIFO, delegate keeps badge, fault cap checked
- docs/ipc.md spec, ipc tests, ipc fuzz, kani ntfn + waitqueue
2026-10-26 20:27:38 +01:00
d43421e33e feat(kernel): object lifetimes via slot generations
- SlotGenerations per table, never wraps, retires exhausted slots
- caps to dead/reused process, endpoint, region rejected
- endpoints owned, die w/ owner, waiters woken w/ error
- DropCap syscall + libkos wrapper
- irq table bounds-checked, routes dropped w/ thread
- self-kill terminates caller, exit_thread full cleanup
- sched run_now: switch to named thread, not queue head
- lifetime tests, fuzz kills/recreates, kani gen proofs
2026-10-26 19:54:23 +01:00
8d2c40cb1e feat(kernel): kernel-owned memory model
- FrameTable: per-frame owner/use, replaces PagePool + ProcessMemory
- Quota per process, page tables charged to owner
- Regions for shared mem + device MMIO, torn down w/ owner
- Platform: create/destroy AS, map/unmap, zero_frame; drop translate_va
- RequestPages/ReleasePages/MapPage(move) checked vs kernel records
- user window 0x1000..32MiB, private pts by construction
- boot loader + device setup go through kernel api
- kernel built in place, boot allocator bounded
- isolation tests, randomized invariant test, FrameTable kani proofs
- fixes: inflated release, unmapped release, dst va unchecked,
  heap overflow, unbounded pt alloc, unzeroed frames, double free
2026-10-26 19:40:50 +01:00
e931485ca7 fix: sched round-robin, cap slot OOB panic, clippy, make ci
- RunList -> intrusive FIFO, no starvation, no silent drop
- cap table sized to CapSlot range (kani caught OOB panic)
- snake food color test uses const
- kani cfg lint, RUST_MIN_STACK for big kernel struct in tests
2026-10-26 19:08:30 +01:00
1c04ddf909 style: cargo fmt kernel crates 2026-10-26 19:07:54 +01:00
818eaecadd refactor: replace manual debug_putchar with libkos::println!
Init, storage server, and hello app now use println!/print! macros
instead of manual byte-by-byte UART output.
2026-10-19 01:00:33 +02:00
052d7c4a64 refactor: remove old userspace and userspace-rt crates 2026-10-19 00:58:14 +02:00
9dd400656c refactor: migrate all servers, apps, binaries to libkos 2026-10-19 00:57:27 +02:00
a4315d7665 refactor: migrate server-framework to depend on libkos 2026-10-19 00:55:54 +02:00
edc55d6f2e feat(libkos): add fs, display, input service client modules with newtypes 2026-10-19 00:55:15 +02:00
25a4c9415b feat(libkos): add print!/println! macros via debug_putchar 2026-10-19 00:53:52 +02:00
dbec3842fa feat: create libkos crate with core modules (syscall, alloc, rt) 2026-10-19 00:53:31 +02:00
2792387348 fix: VirtIO keyboard input latency and direction accuracy
- Driver now drains SYN/repeat/unknown events in a loop instead of
  returning None on the first non-key event
- Snake drains all pending input events per tick, applies only the
  latest direction change (prevents stale event accumulation)
2026-10-19 00:34:13 +02:00
0a47b5489a feat: VirtIO keyboard input for QEMU GUI
- Add VirtIO input device driver (device ID 18) reading from eventq
- Translate Linux keycodes (WASD, arrows) to InputEvent
- Kernel probes for VirtIO input device, falls back to UART
- Add -device virtio-keyboard-device to run-gui Makefile target
- input-qemu tries VirtIO first, falls back to UART
2026-10-19 00:30:20 +02:00
68849f698b fix: GPU display at correct resolution, clean up diagnostics
- Add GET_DISPLAY_INFO command to query QEMU's preferred resolution
  (was hardcoded 640x480, QEMU wanted 1280x800)
- Allocate framebuffer matching actual display dimensions
- Remove debug diagnostic output from display server and snake
2026-10-19 00:24:37 +02:00
f5ac7189a9 fix: VirtIO GPU driver and snake rendering through display server
- Fix swapped command IDs: attach_backing was 0x0104 (FLUSH),
  resource_flush was 0x0106 (ATTACH_BACKING). Now correct.
- Increase process stack from 4 pages (16 KB) to 16 pages (64 KB)
  to prevent stack overflow in display process.
- Restructure display-qemu to avoid MockFramebuffer's 32 KB array
  inflating the VirtIO path's stack frame.
- Wire snake app to render through display server via IPC instead
  of UART escape codes. Uses existing renderer.rs pixel renderer.
- Init now delegates display endpoint to snake process.
2026-10-19 00:01:29 +02:00
194024bc08 fix(ext4): remove old monolithic ext4.rs superseded by ext4/ directory 2026-10-18 23:30:56 +02:00
9be67e403b fix(ext4): review fixes — bounds checks, delete safety, blocks_count, multi-extent dirs 2026-10-18 23:28:34 +02:00
73661e925d test(ext4): comprehensive edge case and integration tests 2026-10-18 23:17:15 +02:00
bc4659eabd feat(ext4): mkdir and nested directory support 2026-10-18 23:16:35 +02:00
2ede01bdd2 feat(ext4): file create, write, and delete with extent management 2026-10-18 23:15:38 +02:00
bff18df349 feat(ext4): directory entry find/add/remove operations 2026-10-18 23:14:02 +02:00
fe0693b969 feat(ext4): block and inode bitmap allocation/deallocation 2026-10-18 23:12:33 +02:00
381669d9dd feat(ext4): inode read/write, init_empty_inode, multi-extent read 2026-10-18 23:09:57 +02:00
5d5714914f refactor(ext4): split into submodules, add io/superblock/bgd with write-back 2026-10-18 23:08:07 +02:00
d85cb5b55d feat(storage): add mkdir to FileSystem trait with stubs 2026-10-18 23:06:26 +02:00
25824a01fe fix: remove broken QEMU GPU swap hack, add graceful fallback
VirtIO GPU:
- Removed QEMU 11.x command type swap hack (0x0104↔0x0106).
  The hack was wrong — swapping types without swapping data formats
  meant handlers read wrong struct layouts. Commands returned OK
  but did nothing.
- Restored correct VirtIO spec command types.
- Removed broken test pattern (fill + flush that never displayed).
- GPU setup now reports success/failure without crashing.

Display server resilience:
- VirtioFramebuffer::new() → try_new() -> Option<Self>.
  Returns None if phys-info page is unmapped or has zero dimensions.
- bins/display-qemu: tries VirtioFramebuffer, falls back to
  MockFramebuffer. Display server runs headless instead of crashing.
- No more page faults when GPU is absent.

The GPU driver code is architecturally correct (proper VirtIO
commands, proper data formats) but doesn't produce visible output
on QEMU 11.x due to a suspected QEMU legacy MMIO bug where
transfer_to_host_2d succeeds but doesn't transfer data. The driver
is ready for when this is fixed or a different QEMU version is used.
2026-10-18 22:49:55 +02:00
cbabe2abfe cleanup: replace magic 1024 page limit with ProcessMemory::DEFAULT_PAGE_LIMIT 2026-10-18 22:43:18 +02:00
73eed4e5b7 cleanup: replace magic TimeSlice::new(100) and Priority::new(16) with DEFAULT
TimeSlice::DEFAULT and Priority::DEFAULT already exist with the
same values. Using them makes the intent clear and centralizes
the default values.

TimeSlice::new(2) in tick test is intentional — tests preemption
after 2 ticks specifically.
2026-10-18 22:41:29 +02:00
06863c84fa fix: critical privilege escalation + resource leak hardening
CRITICAL — MapPage privilege escalation:
  handle_map_page allowed mapping kernel memory (VA >= 0x80000000)
  into userspace. Any process with a Process capability could read/
  write kernel data structures. Fixed: reject src_va >= USER_VA_LIMIT.

HIGH — resource leaks:
  handle_kill: leaked pages (used cleanup_threads directly instead
    of destroy_process). Now uses destroy_process for full cleanup.
  handle_create_process: orphaned process on cap grant failure.
    Now destroys process on rollback.
  handle_create_endpoint: orphaned endpoint on cap grant failure.
    Now destroys endpoint on rollback.
  Thread ID array: hardcoded [None; 4] replaced with
    [None; MAX_THREADS_PER_PROCESS] slice. cleanup_threads now
    takes &[Option<ThreadId>] slice.

MEDIUM — quality fixes:
  handle_request_pages: replaced unreachable!() with proper error
    return + page pool rollback.
2026-10-18 22:39:16 +02:00
d009818caf fix: kernel hardening pass 2 — page tracking, queue overflow, region tracking
Page lifecycle:
- ProcessMemory now tracks (PhysicalAddress, count) pairs for each
  allocation (up to 16). destroy_process iterates and frees all
  pages back to the pool. No more permanent page leaks on exit/fault.
- RequestPages re-adds MemoryRegion entries so ReleasePages works.
  Release test un-ignored, passes.
- RequestPages: VA allocation moved after pool allocation succeeds,
  preventing VA leak on OOM.

IPC hardening:
- WaitQueue overflow (>16 waiters): returns WouldBlock error instead
  of silently dropping the thread. Thread is not blocked if enqueue
  fails.
- debug_assert on pending_messages[sender].take() — invariant that
  a sender in wait queue must have a pending message.

Scheduler:
- remove() now clears current thread if the removed thread was
  current on its core.
- add() asserts push succeeded; bitmap bit only set if thread was
  actually added to RunList.

Cleanup:
- Priority::DEFAULT replaces Priority::new(16).unwrap() in
  spawn_thread and spawn_thread_in.

36 kernel tests pass, 0 ignored.
2026-10-18 22:31:16 +02:00
ea2ac5d1d9 fix: harden kernel — eliminate UB, proper process cleanup
Critical: kernel_ref() UB eliminated
- kernel_ref() returned &'static mut, creating aliasing mutable
  references across trap handler + boot code (13+ call sites)
- Replaced with kernel_ptr() -> *mut Kernel, each use site does
  explicit unsafe { &mut *kernel_ptr() }
- KernelCell: removed get_mut(), added as_ptr() -> *mut T
- UB is gone: raw pointer access makes the single-core invariant
  explicit at every use site

Important: process cleanup on exit/fault
- New destroy_process() method consolidates cleanup:
  - Removes all threads from scheduler and endpoints
  - Clears pending messages and results
  - Destroys process and frees ProcessMemory
- handle_exit and handle_fault both use destroy_process()
- handle_exit_thread uses destroy_process when last thread exits

IPC hardening:
- Added invariant comment on pending_messages[sender].take()
  (sender in wait queue must have a pending message)

handle_release_pages:
- Now uses translate_va to convert VA→PA (was treating VA as PA)
2026-10-18 22:22:48 +02:00
61e28f0af5 fix: sync kernel tests with current API, add CapSlot::const_new
Tests:
- IPC tests: spawn thread B explicitly (CreateProcess no longer
  spawns threads since the boot logic fix)
- Memory tests: RequestPages now returns Value(va) not Slot(cap)
- MockPlatform: tracks VA→PA mappings for translate_va
- ReleasePages test: ignored (RequestPages no longer creates
  regions — ReleasePages needs redesign)

CapSlot::const_new(value):
- const fn that panics at compile time for invalid values
- Replaces CapSlot::new(N).unwrap() in init, echo, snake
- Cap slot constants are now compile-time verified

Also fixes handle_release_pages to use translate_va instead of
treating VA as PA directly.

35 kernel tests pass, 1 ignored.
2026-10-18 22:17:42 +02:00
a3b15e5264 feat: playable snake game via UART terminal rendering
Snake renders using ANSI escape codes via debug_putchar syscall,
bypassing the VirtIO GPU (which has a QEMU 11.x legacy MMIO bug
where transfer_to_host_2d succeeds but doesn't transfer data).

Full microkernel stack running end-to-end:
  adapter → init → storage-server IPC → load snake from disk →
  input-server IPC (UART keyboard) → snake game logic →
  debug_putchar syscall → UART → terminal display

Controls: WASD to steer, runs at 0.2s tick rate.
Green O=head, o=body, red @=food, #=border.
2026-10-18 22:08:52 +02:00
27be73f42d feat: wire display + input servers to snake, fix QEMU 11.x GPU bug
VirtIO GPU: QEMU 11.x has RESOURCE_ATTACH_BACKING (0x0104) and
RESOURCE_FLUSH (0x0106) command types swapped in its legacy MMIO
VirtIO GPU implementation. Workaround: send swapped type values.
Confirmed via QEMU monitor (xp shows correct bytes in memory)
and QEMU trace events (device dispatches to wrong handler).

Display pipeline now works end-to-end:
  adapter → GPU init → create_2d → attach_backing → set_scanout
  display-server → clear(blue) → flush → transfer + resource_flush
  snake → draw commands via IPC → display renders → flush to GPU

Input server:
  - New driver-input-uart crate (reads UART at mapped VA 0x20000)
  - New bins/input-qemu composition root
  - Adapter loads input-server, maps UART MMIO into its address space
  - Init delegates both display_ep (slot 0) and input_ep (slot 1) to snake
  - WASD keys → UART → input-server → IPC → snake direction change

Snake game runs with display and input, exits on wall collision.
2026-10-18 21:10:42 +02:00
7c7e3b8748 refactor: apply newtypes throughout userspace API and display types
Every syscall stub now uses proper types from types/ — CapSlot,
EntryPoint, StackPointer, VirtualAddress, PageCount, ProcessId,
PermissionSet, Ticks. The compiler prevents swapping entry/stack,
passing a ProcessId where a CapSlot is expected, or using an
address as a page count.

New display types in types/display.rs:
  - Color(u32) with rgb() constructor
  - ScreenCoord(u16) for x/y positions
  - Dimension(u16) for width/height

Updated throughout:
  - userspace/syscall.rs: all params typed, returns Option instead
    of sentinel usize::MAX
  - server-framework: endpoint param is CapSlot
  - port-framebuffer: trait uses Color, ScreenCoord, Dimension
  - hw-virtio: DmaAddrs uses PhysicalAddress/VirtualAddress,
    GPU commands use Dimension
  - All servers, drivers, bins, apps updated for new signatures
  - permission-manager: process field uses ProcessId
  - PermissionSet: added bits() accessor

89 tests pass, full QEMU boot verified.
2026-10-18 13:45:40 +02:00
3a0395453b refactor: extract shared hw-virtio crate, eliminate VirtIO protocol duplication
Two VirtIO block and two VirtIO GPU implementations (adapter + driver)
shared 90% of their protocol logic. Extracted the common code into
hw-virtio, parameterized by MmioAccess trait.

New crate: hw-virtio (no_std, zero deps)
  - mmio.rs: MmioAccess trait, DirectMmio, init_legacy_device(), scan
  - queue.rs: VirtioQueue with descriptor chain submit + poll
  - block.rs: block read protocol (3-descriptor chain)
  - gpu.rs: GPU commands (create_2d, attach_backing, set_scanout,
            transfer_to_host, resource_flush)

Adapter thin wrappers (identity-mapped, statics for DMA):
  - virtio_blk.rs: 220 → 53 lines
  - virtio_gpu.rs: 165 → 37 lines

Driver thin wrappers (mapped VAs, phys-info for DMA):
  - drivers/block/virtio: 139 → 70 lines
  - drivers/framebuffer/virtio: 146 → 95 lines

Also deleted input-server/input_device.rs (1-line re-export,
superseded by port-input-device).
2026-10-18 13:29:28 +02:00
8d53fa9ac5 refactor(adapter-riscv): split kmain into boot/, devices/ modules
kmain is now 20 lines — six function calls:

  hardware::init        → BSS, MMU, traps, timer, PLIC, kernel
  loader::load_init     → read init.elf, create process, map ELF
  loader::load_server   → read server ELF, create process, map ELF
  storage_setup         → VirtIO block re-init, shared buffer, phys-info
  gpu_setup             → VirtIO GPU init, framebuffer alloc, phys-info
  caps::grant_all       → endpoints, capability grants

New modules:
  boot/hardware.rs   — hardware init (BSS, MMU, traps, kernel)
  boot/loader.rs     — ELF loading, thread setup, enter_userspace
  boot/caps.rs       — endpoint creation, capability grants
  devices/storage_setup.rs — VirtIO block for storage server
  devices/gpu_setup.rs     — VirtIO GPU for display server

All unsafe contained in hw/, mmu/, trap/. Boot and device
modules call safe wrappers.
2026-10-18 13:19:16 +02:00
5766c6f7f7 refactor: extract ports/drivers/bins layers — clean dependency inversion
Separate abstractions from implementations following DIP:

  servers/              drivers/
      │                     │
      ▼                     ▼
    ports/  (trait-only crates, zero deps)

New crates:

ports/ (abstractions):
  - port-framebuffer: Framebuffer trait
  - port-block-device: BlockDevice trait + SectorId
  - port-input-device: InputDevice trait + InputEvent types

drivers/ (implementations depend on ports/):
  - driver-framebuffer-virtio: VirtIO GPU framebuffer
  - driver-framebuffer-mock: test double
  - driver-block-virtio: VirtIO block device

bins/ (composition roots wire server + driver):
  - display-qemu: DisplayServer<VirtioFramebuffer>
  - storage-qemu: storage server with VirtIO block

Servers no longer own their hardware traits or driver code.
Neither server nor driver depends on the other — both point
inward to the port abstraction.
2026-10-18 13:13:53 +02:00
38f20cc3c4 feat: proper IPC-based boot — init loads servers from storage via IPC, VirtIO GPU driver
Complete microkernel boot pipeline: adapter loads only init + storage + display
from disk. Init bootstraps all other servers by reading binaries from the
storage server via IPC, parsing ELF, creating processes, mapping pages, and
spawning threads.

New syscalls:
- CreateEndpoint: userspace endpoint creation with full capability grant
- DebugPutchar: debug output to UART from userspace
- MapPage: cross-process page mapping (init loads binaries into children)
- SpawnThreadIn: spawn thread in another process via capability

Key fixes:
- Per-process L1 page tables for VPN[2]=0 (prevents cross-process corruption)
- Separate kernel_pt from page_tables[0] (init pid=0 overwrote kernel PT ref)
- Thread Running state set in switch_to_next (syscalls rejected without it)
- Pending IPC results applied during context switch
- SIE disabled during boot (timer can't preempt into unready processes)
- User heap VA starts at 0x40000 (avoids shared buffer at 0x30000)
- RequestPages maps at user VAs via per-process heap allocator

VirtIO GPU:
- Adapter probes for GPU device, initializes resource/scanout/backing
- Display server writes to mapped framebuffer, flushes via GPU virtqueue
- 640x480 BGRA framebuffer with transfer-to-host and resource-flush

Storage server:
- Userspace VirtIO block driver using pre-mapped MMIO and DMA pages
- FAT16 filesystem reader serving file-read requests via IPC
- Shared buffer protocol: init writes filename, storage writes file data

Echo app for IPC testing (adapter-loaded echo proved the pipeline end-to-end).
2026-10-18 13:02:30 +02:00
ffde4065ba fix: full init boot logic works — CreateProcess no longer spawns threads, boot uses out-param to avoid sret bug
- CreateProcess only creates process + grants cap, no thread spawning
- boot::boot takes &mut BootResult instead of returning it (fixes -> ! sret convention issue)
- Init creates 6 server processes, sets up supervisor, enters receive loop
- No faults on QEMU with full boot sequence
2026-10-18 04:57:20 +02:00
29cd0e7dfe feat: userspace linker script at 0x10000, proper ELF segment loading, full disk boot pipeline working
- Userspace linker script: apps/servers link at 0x10000 (user VA)
- Adapter linker script: kernel links at 0x80200000 (S-mode)
- Each uses build.rs to emit its own -T flag, global config only sets panic=abort
- ELF loader: page-aligns segment mappings, handles non-aligned vaddrs
- Stack: 4 pages (16K) mapped below program
- SP set to top of stack (0x10000), not bottom
- FAT16 disk image forced (mformat was creating FAT32)
- End-to-end verified: VirtIO → FAT16 → ELF → userspace → ecall → exit
2026-10-18 04:51:07 +02:00
924baede9e fix(adapter-riscv): fix VirtIO block driver — scan all MMIO slots, handle legacy mode, fix virtqueue layout
VirtIO now properly scans 8 MMIO slots, detects legacy vs modern mode,
uses correct virtqueue page alignment for legacy, and reads sectors.
Fixed disk image script to force FAT16 (mformat was creating FAT32).
init.elf successfully loaded from FAT16 disk via VirtIO on QEMU.
2026-10-18 04:42:13 +02:00
7649cb0b18 feat: add run() and binary entry points for all servers and init
Every server now has lib.rs (testable) + main.rs (deployable binary).
Binary is 3 lines: extern crate userspace_rt + call run().
Hardware servers use feature flags for adapter selection.
9 RISC-V binaries ready for the disk image.
2026-10-18 04:26:42 +02:00
d43c6a7e74 feat(adapter-riscv): load init from VirtIO block device with FAT16 filesystem
Adapter probes for VirtIO block device, reads init.elf from FAT16 disk,
parses ELF, maps into userspace, and launches. Falls back to embedded
minimal init if no disk is present.

Also: VirtIO MMIO driver, boot FAT16 reader, disk image build script,
Makefile targets for build/run/run-disk.
2026-10-18 04:19:19 +02:00
a910c06cf7 refactor(adapter-riscv): replace hardcoded demo with proper init launch via ELF parsing
Adapter now: parses init binary (ELF or raw), allocates pages, creates
user page table, sets thread entry point in SavedContext, enters U-mode.
Init takes over from there — no more IPC demo hardcoded in the adapter.
2026-10-18 04:13:13 +02:00