Ferrite
- 21 Devlogs
- 114 Total hours
A custom kernel written entirely from scratch in rust.
A custom kernel written entirely from scratch in rust.
Changes so far:
gs_info struct, which saves the user stack and holds a pointer to the kernel stacksyscall::init which enables the syscall/sysret instructions and sets up the STAR, LSTAR and SFMASK registerssyscall_entry which builds a UserFrame (a snapshot of the CPU registers on syscall entry) and calls syscall_dispatch
syscall_dispatch, which currently logs the received syscall number and halts (the system call return path is not implemented YET)UserFrame which holds a CPU register snapshot which gets taken upon entering the kernelAfter a week of basically no progress, I’ve finally finished moving the ELF init sequence from main.rs into the proper methods under the sched subsystem.
I’ve also simplified and improved the build system (build.py/docs.py). They now use a shared lib.py to avoid code duplication. Also, build.py got a few changes:
The docker permissions have been fixed, as under Linux, root would own parts of the build files which is of course annoying as you can’t easily interact with those files then.
The github-hosted rustdoc was failing to build as it could not find USER-BINARY, so I just faked user-binary via touch user-binary.
After almost 30 hours of work over the last week, I’ve finally finished the big refactor.
kprint backendKSTATE
kernel_entry, which builds a BootInfo and hands to kernel_main)main.rs into the sched subsystem… and so much more.
oh boy this is taking way too long
kprint
kprint, the kernel print macro has been fully rewritten. The public macros have not changed, but internally, the macros now:
core::fmt::write on the kernel writerThe kernel writer collects the text of all calls made to it using core::fmt::write in an internal buffer, and on drop, it pushes a new entry into the kernel log ringbuffer in a format that is (currently only partially) syslog-compatible. Then, the kernel writer dispatches a log header and the full log text to all active log recievers (like UART or the basic framebuffer).
PackedU8: A type which wraps all the bitwise logic for packing multiple pieces of data which are less than one byte into a byteUncheckedCell: A datatype with interior mutability, which can be uninitialized via MaybeUninit. When the cargo feature debug-checks is enabled, this type also checks for double initialization and uninitialized accessNicheCell: A datatype with interior mutability, which can be uninitialized via Option. This datatype is designed to be used with values that can take advantage of niche optimization (where the datatype T has a value which is guaranteed to be invalid, like a NonZeroU64 being zero)refactor: redid kernel source tree, ... commit is gonna be one hell of a mess…
I’ve decided to change what the kernel aims to be and how it will work. I’ve dropped full linux drop-in compatibility in favour of creating a clean, modern and optimized kernel which tries to fix design mistakes other kernels have already made.
The kernel will be POSIX-compatible, feature a namespaced VFS to seperate virtual files or devices like /dev/sda, /sys/class/hwmon, /proc/self/ and more from actual files. It will have namespaces like fs:/ for the actual file system, dev:/ for device files (like dev:/sda), vdev:/ for virtual devices (like vdev:/urandom) and more, including hw:/ for a modern hardware info interface, log:/ for a standardized logging interface and reg:/ for a global registry-like configuration system. Internally, the kernel will also feature KSTATE, a central static struct for storing everything the kernel uses. Also, ther kernel will move from strictly limine to a dynamic bootloader format, where each architecture has its own kernel_entry, which prepares the CPU and kernel into a common state (long mode, paging, …) and builds a standardized BootInfo struct, which then gets handed to kernel_main when it is called.
I’m also currently working on massively reorganizing and cleaning up the kernel source, by for example standardizing where arch-specific code lands, categorizing and organizing the code better and more. Also, the kernel print system (kprint) is currently being rewritten to improve performance and integrate it into KSTATE.
Before I start on syscalls for the userspace binary, I’ve decided to first get most TODOs done, like updating the safety comments and rustdoc, refactoring the ELF loading stuff to properly utilize KSTATE::procs, proper error delegation and more.
I’ve finally finished refactoring the TSS, GDT and IDT properly by removing the struct wrapper for GDT and IDT, getting rid of all the Onces and more. Additionally, I refactored KSTATE::cpu to be an arch-independent container of arch-specific structs.
@everyone… WE HAVE USERSPACE!!! 🎉 :D
This is something I’ve been waiting for sooo long… a binary is actually executing in USERSPACE now (ring 3 and stuff)!!!
Currently, the code is extremely hacked together, or “gepfuscht” as we like to call it in Austria ;). Basically, what should be cleanly integrated with KSTATE::procs, should use a proper userspace and kernel stack and so on, doesn’t. All of this of course won’t stay like that, but it currently is like that to just get something in userspace running. The one thing that is actually done cleanly is the ELF validation and definitions, which live under src/elf. There is a struct representing the ELF header, an ELF PHDR and also an enum for ELF validation errors. All other logic was just thrown into main for now, like creating the processes address space, mapping its memory, copying the binary into the mapped memor, setting up its stack and actually jumping to it.
Written in good old assembly of course, the test binary currently has the job to cause some sort of CPU exception, as syscalls or any other way to interact with the kernel or output something doesn’t even exist yet.
The current program manages that via just running the hlt instruction, which, when run from userspace (Ring 3) causes a general protection fault (#GP). This is because a userspace program shouldn’t just be able to halt the CPU or disable interrupts (via the cli instruction). That would defeat the whole purpose of rings and kernel/userspace.
The userspace binary currently lies under src/user-binary.asm, next to src/kernel/. It is build via running docker exec ferrite_os /ferrite_os/build-user-binary.sh. NASM was also added to the Dockerfile to make building the assembly file possible.
I’ve added methods for mapping pages and VMA together. I’ve also improved the kernel VMA granularity and added a kernel paging remap step to mm_init() which applies the kernel VMA permissions to the kernel pages. This is only intermediate until I switch to the linux boot protocol.
Next up, I’ll be adding a (very basic) ELF loader!
Changelog for the last two days
build.py
kernel_panic outputSIMPLE_STATE out of main… and an INSANE amount of optimizations, including:
Once and similar by swapping them for UnsafeCell<MaybeUninit<T>> and others and taking advantage of things like niche optimizationNext up, I’ll be doing some more work on the VMM and finally add the full mapping methods, which map pages and VMAs together.
AddressSpace and VMA data structs done!
I’ve introduced a struct called AddressSpace which contains the virtual address of the root page table (the PML4 on x86_64) and a BTreeSet of VMAs (virtual memory areas).
A BTreeSet is basically a type of set which organizes data in a tree-like structure (in a B-Tree structure to be exact) with a time complexity of O(log n) for inserting, removing and searching for elements.
A VMA (virtual memory area) is an area in memory with specific flags, such as READ, WRITE, EXEC or USER. One of their main uses is determining what to do on a #PF (page fault): should we allocate a page here (lazy-mapping)? Or was this truly a faulty operation like trying to execute READ-only memory?
Also, I briefly attempted to switch over to the linux boot protocol, but I decided to do that sometime later, because it is slightly complicated and definitely did not break everything ;)
After needing to quickly relearn the logic of the free method because I somehow forgot it, it finally works again!
Additionally, I’ve added a little safeguard to the bootloader memory reclamation. Next, I’ll be continuing on the VMM and refactoring it to support userland page tables too.
Also, I’ve added a few core::fmt traits to PhysAddr and VirtAddr and also added a constructor which creates a new address type (PhysAddr or VirtAddr) with an address of zero. In addition, PhysAddr got a few new getters like as_ptr or as_mut_ptr.
Currently working on the PMM and VMM a little more, also cleaned up the main for better readability.
I also moved the PMM and VMM into the mm subsystem of the KState struct.
Additionally, I switched from rust 2021 to rust 2024, which also needed a little fixing to get working again. Why? Well to use let chains in if statements of course cause its like a little bit nicer to write! :)
Also, I partially upgraded scripts/x86_64/build.py to log to a log file and restore your terminal config on termination.
Currently working on getting a bug in the PMM fixed, getting bootloader memory reclaim to work and then I’ll do the VMM’s VMAs.
I’ve added remap_page aswell as translate to the VMM (virtual memory manager). Also, I’ve added alignment-checking to ensure the VMM doesn’t corrupt memory when an incorrect virt/phys address is given to one of it’s methods.
Additionally, I’ve cleaned up the code a little bit by making things like the raw pointer stuff more readable.
I’ve painstakingly (hope i spelled it right) put together a handmade logo for the kernel. It’s pretty simple but I still think it looks pretty nice.
The PMM now uses a buddy allocator which gives us many advantages, including:
Next is adding a few methods to the VMM, and then I’ll work on the heap allocator to finally be able to work on the kstate struct :)
I’ve refactored PMM and VMM into SIMPLE_STATE, updated the build and docs scripts, enhanced kernel logging via log levels and more, added and fleshed out a Claude Code Skill for writing rustdoc and let Claude re-do a lot of the rust doc to reduce the over-documentation that was done by none other than… Claude.
Currently working on improving the kernel a lot to make it robuster for its later stages.
Tooling
docs.py, refactor build.py to work on linux tooKernel
text.rs and move its logic into kprint (which has also been refactored to be concurrency-safe)I also tested the kernel on real hardware!!
To my suprise, grabbing the ISO from the build folder, flashing it onto a USB drive and plugging it into a laptop just… WORKED?!?
I attached a video of the kernel booting on real hardware and IRQ0 (the BIOS-configured 18.2 Hz hardware timer) printing “a” repeatedly. :)
CHAINED_PICS
I’ve noticed that my so far work has been kinda sloppy, so I’m currently working on improving everything (as u can see on the changelist above ive already started). I’m doing this because when I started with IRQs, stuff started breaking a lot. My goal is to get everything thread-safe and ready in a way that it’ll work in later stages of the kernel too.
Next, I’ll be working on fixing logging (add a ringbuffer to prevent interrupts creating half-printed or partially drawn logs)
Tried to implement a live web demo using a wasm implementation of qemu with UEFI and more, but couldnt get it to run.
Also, I heavily improved documentation and finished up the virtual memory manager (for now…).
Next, the heap allocator is coming then I’ll finally be able to use dynamic types!
(Well, idk if you can call it a whole OS if im only planning to do a kernel, but anyways)
My end goal is for it to be able to run systemd, GNOME and more. But thats a very, VERY distant goal. For now, im focusing on getting a statically linked C binary running in userspace.
I’ve already managed to get some basic logging via serial and a basic framebuffer going, aswell as x86_64 GDT, IDT, TSS and a physical aswell as a very slim virtual memory manager.
Next, I’ll be “finishing” up the VMM a little to be able to start work on the heap allocator, which will enable use of datatypes like Vec, Box and more.
For anyone interested in the more technical stuff:
The build toolchain works through python scripts, which use docker to build and then QEMU to run the kernel.
I’m mainly targeting x86_64, but aarch64 support is also my plan (but I’ll be focusing on x86_64 during this challenge).