[Design] Can a Monolithic Kernel Stay Modular?: Structuring mkfreeOS Around Contracts

Discussions on more advanced topics such as monolithic vs micro-kernels, transactional memory models, and paging vs segmentation should go here. Use this forum to expand and improve the wiki!
Post Reply
mkfreeOS
Posts: 4
Joined: Mon Nov 30, 2026 5:05 am

[Design] Can a Monolithic Kernel Stay Modular?: Structuring mkfreeOS Around Contracts

Post by mkfreeOS »

Subject: [Design] mkfreeOS — a hobby OS structured around contracts: how every subsystem stays isolated

After several years of on-and-off work in whatever free time I can find, I rewrote large parts of mkfreeOS and want to share the structural decisions that guided it. The goal is to show how the kernel hangs together from a design perspective — not just what it does, but how the pieces stay decoupled from each other.

Source at github.com/ramonmayedo/mkfreeOS (GPL v3). x86 / x64, C++ and NASM assembly, no external dependencies.

The system at a glance

Image

The vertical stack above is crossed by one horizontal principle: every boundary between layers is a pure virtual interface defined in a neutral header. The layer above depends only on the interface; the layer below implements it. Nothing in src/kernel/core/ ever includes a hardware-specific header.

Layer 0 — Architecture isolation

The first boundary is between the kernel core and the CPU. Everything hardware-specific lives behind eight interfaces stored in one global struct:

Code: Select all

// src/kernel/architecture/arch.h
struct Arch {
    IArchIO            *io;            // in/out port access
    IArchInterrupt     *interrupt;     // IDT, IRQ register, enable/disable
    IArchVirtualMemory *virtualMemory; // page tables, CR3, TLB
    IArchCPU           *cpu;           // context switch, idle, SMP, ring transition
    IArchEventHandler  *eventHandler;  // exceptions and syscalls (set by kernel, not arch)
    IArchDebug         *debug;         // register snapshot
    IArchAtomic        *atomic;        // CAS, fetch-add, memory barriers
    IMemoryMapProvider *memoryMap;     // E820 or equivalent physical RAM map
};
A linker-resolved function archBootstrap() fills this struct before the kernel runs:

Code: Select all

                 src/kernel/architecture/
                 ┌──────────────────────────────────────────┐
                 │  contracts/   IArchCPU.h                 │
                 │               IArchInterrupt.h           │
                 │               IArchVirtualMemory.h  …    │
                 │                                          │
                 │  x86/         X86Components              │
                 │               ├─ Io          → arch.io   │
                 │               ├─ IntHandler  → arch.interrupt
                 │               ├─ VirtualMemoryX86 → arch.virtualMemory
                 │               ├─ X86Cpu      → arch.cpu  │
                 │               ├─ X86Debug    → arch.debug│
                 │               ├─ Atomic      → arch.atomic
                 │               └─ MemoryMapProvider → arch.memoryMap
                 └──────────────────────────────────────────┘
                              ↑
                        archBootstrap()   ← called once, at kernel entry
After archBootstrap() returns, arch.* is fully populated. No code in src/kernel/core/ ever calls inb, outb, cli, sti, or touches cr3 directly. If I wanted to port to ARM64 I would implement the eight interfaces and write one new archBootstrap(). The core does not change.

Contracts live outside the implementations

The interfaces (IArch*, IDevice, IBlockDevice, ISchedulerPolicy, …) all live in src/kernel/contracts/ or src/kernel/architecture/. The implementations live elsewhere and depend on the contracts — never the reverse.

Code: Select all

src/kernel/
├── contracts/          ← pure virtual interface headers only
│   ├── IDevice.h
│   ├── IDeviceSubscriber.h
│   ├── IBlockDevice.h
│   ├── IProcessHandleObject.h
│   └── …
│
├── architecture/       ← arch contracts + x86 impls
│   ├── IArchCPU.h
│   ├── IArchVirtualMemory.h
│   └── x86/
│       ├── X86Components.h
│       └── X86Cpu.cc, VirtualMemoryX86.cc, …
│
├── core/               ← knows only the contracts above; zero hardware headers
│   ├── kernel.cc
│   ├── scheduler/
│   ├── memory/
│   ├── process/
│   ├── device/
│   ├── vfs/
│   └── syscall/
│
└── drivers/            ← implement IDeviceSubscriber; know the contracts
    ├── storage/ide/
    ├── ps2/
    └── video/bochs/

Memory — three independent layers

Code: Select all

 Layer 3   ProcessAddressSpace      KernelMemoryManager    SharedMemoryManager
           (per-process VA + heap)  (MMIO, DMA buffers)    (shmget / shmat)
                    │                       │                      │
 Layer 2   ─────────────────── VirtualMemory ────────────────────────────
           (pool registry · cloneKernelMappings · switchAddressSpace)
                    │
           IArchVirtualMemory ← mapPage · unmapPage · invalidatePage · …
                    │
 Layer 1   ── BitmapPageAllocator ───────────────────────────────────────
           (physical frame tracking — packed bitmap, next-fit + byte-skip)
The bitmap allocator maintains a cursor (hintBit) for next-fit and skips fully-occupied bytes in one comparison — O(byte count) instead of O(page count) in the common case. No locks at boot; after enableConcurrency() a function-pointer swap activates SpinlockIrq on every allocation. The same two-mode pattern applies to all allocators and the device manager.

Virtual address layout (32-bit):

Code: Select all

0x00000000  User code / data / BSS
0x00400000  Kernel page directory + initial page tables      (4 MB)
0x00800000  Kernel page pool (PDEs, PTEs, internal buffers) (128 MB)
0x08000000  Kernel heap (malloc — first-fit + coalescing)   (960 MB)
0x40000000  User process pages                              (  1 GB)
0x80000000  User stack (grows down)                         (512 MB)
0xA0000000  Shared memory regions (System V IPC)            (512 MB)
0xC0000000  DMA buffers (physically contiguous)             ( 16 MB)
0xF0000000  MMIO (PCI BARs, LAPIC, framebuffer)             (240 MB)
Kernel malloc uses a 5-byte packed header (free/used flag + block size), walks from heap base first-fit, coalesces adjacent free blocks on free(), and extends the heap by calling the kernel page pool if the arena is exhausted.

Device discovery — publish-subscribe with queryInterface

Every driver is a subscriber. The device manager notifies all subscribers on every addDevice(). Each subscriber inspects the device with a COM-style interface query:

Code: Select all

class IDeviceSubscriber {
    virtual bool onDevice(IDevice* device, IDeviceManagerPublic* dm) = 0;
};

// IDevice — the one method every hardware object answers
class IDevice {
    virtual void* queryInterface(u32 iid) = 0;
};
A driver returns true if it claimed the device, false if it did not. The subscriber that accepted the device may publish new devices of its own — triggering another round. The chain is depth-first with no central coordinator.

IDE disk example:

Code: Select all

bool IdeDiskDriver::onDevice(IDevice* dev, IDeviceManagerPublic* dm) {
    IIdeDevice* ide = (IIdeDevice*) dev->queryInterface(IID_IDE_DEVICE);
    if (!ide || ide->type() != IdeDeviceType::Ata) return false;
    dm->addDevice(new IdeDiskDevice(ide, protocol));  // ← triggers next round
    return true;
}
PCI Bochs VGA example — matching on vendor/device IDs:

Code: Select all

bool BxVgaDriver::onDevice(IDevice* dev, IDeviceManagerPublic* dm) {
    IPciDevice* pci = (IPciDevice*) dev->queryInterface(IID_BUS_DEVICE);
    if (!pci || pci->getVendorId() != BOCHS_VBE_VENDOR) return false;
    BochsVgaDevice* d = new BochsVgaDevice(pci, mem);
    if (!d->isPresent()) { delete d; return false; }
    dm->addDevice(d);
    return true;
}
All drivers are registered in installDrivers() before busManager.scanBuses() is called, so the subscription list is complete before any device is published.

The full storage chain — from IDE slot to a/file.txt

This entire chain fires automatically within a single busManager.scanBuses() call. No central coordinator orchestrates it; each step publishes a device and the next subscriber picks it up.

Code: Select all

busManager.scanBuses()
  │
  └─ PciBus::scan()
       └─ for each PCI function → dm->addDevice(PciDevice)
            └─ [no subscriber matches display — VGA driver picks it separately]
  │
  └─ IdeBus::scan()
       └─ for each IDE slot → dm->addDevice(IdeRawDevice)
            │
            └─► IdeDiskDriver::onDevice()           [IID_IDE_DEVICE + Ata type]
                 └─ dm->addDevice(IdeDiskDevice)
                      │
                      └─► BlockManager::onDevice()  [IID_BLOCK]
                           └─ wraps in BlockCacheDevice (read cache)
                                └─ dm->addDevice(BlockCacheDevice)
                                     │
                                     └─► PartitionManager::onDevice()
                                          └─ reads MBR → 1..4 partitions
                                               └─ dm->addDevice(PartitionDevice)
                                                    │
                                                    └─► FsManager::onDevice()
                                                         └─ probes FAT32 (reads BPB)
                                                              └─ VolumeManager::mount()
                                                                   └─ assigns letter "a"
                                                                        └─ VFS::addMount("a")
After this chain, open("a/system/bin/init.elf") works for any process.

VFS — a prefix namespace of mounts

Code: Select all

VirtualFileSystem
  └─ RootNamespace
       ├─ VolumeMount  "a"    → FAT32 on disk0 partition 0
       ├─ VolumeMount  "b"    → FAT32 on disk0 partition 1
       ├─ DeviceNamespace "dev"
       │    ├─ block/disk0, disk1, …
       │    ├─ input/keyboard0, mouse0
       │    └─ video/pci-bxvga0
       ├─ ProcessNamespace "proc"
       └─ SysNamespace "sys"
Every mount implements IVirtualMount (open / create / mkdir / remove / rename). RootNamespace splits the first path segment and delegates. Cross-mount rename returns false — not supported.

Opening a path:

Code: Select all

open("dev/block/disk0", FILE_R)
  → RootNamespace splits "dev" → DeviceNamespace
      → DeviceManager::getDevice("block", "disk0")
          → queryInterface(IID_HANDLE_PROVIDER)
              → IProcessHandleProvider::createHandle()
                  → DiskHandle* (IProcessHandleObject)
  → ProcessHandleTable::add(DiskHandle*) → fd = 3

Object model — everything is a handle

The kernel has two root contracts:

Code: Select all

IDevice                                IProcessHandleObject
(kernel side)                          (userspace side)
─────────────────                      ───────────────────────────
getName()                              read(buf, len)
getClass()                             write(buf, len)
queryInterface(iid)                    seek(offset, whence)
                                       ioctl(cmd, arg)
Hierarchy:                             close()
 IDevice
  ├─ IBusDevice                        Hierarchy:
  │   ├─ IPciDevice                     IProcessHandleObject
  │   └─ IIdeDevice                      ├─ File          (FAT32 file)
  ├─ IBlockDevice                         ├─ DirectoryObject
  ├─ IVideoDevice                         ├─ SocketHandle
  ├─ IInputDevice                         ├─ DeviceHandle
  └─ IFileSystem                          └─ ConsoleObject
A process's handle table maps integer fds to IProcessHandleObject*. The syscall dispatcher for read(fd, buf, len) does one thing: handleTable.get(fd)->read(buf, len). It never inspects the type. File, socket, keyboard device — the same call path.


Processes — no fork(), spawn only

There is no fork(). The only process-creation syscall is cmpExecV: open an ELF file, build a fresh address space, map segments, build a user stack with argv, create a first thread and enqueue it. No parent state is copied.

Code: Select all

cmpExecV("a/system/bin/shell", argv, ExecOptions{fdIn=5, fdOut=6})
  │
  └─ open ELF as handle
       └─ ElfImageBuilder::build()
            ├─ new ProcessAddressSpace (new page directory, clone kernel mappings)
            ├─ map ELF PT_LOAD segments
            ├─ map BSS (zero-fill via rep stosl)
            ├─ build user stack (argv strings + pointer array)
            └─ return ElfProcessImage{entryPoint, stackTop}
       └─ createProcess() → new Thread → Scheduler::enqueue()
Stdio redirection is explicit: the caller passes two fd numbers via ExecOptions. The child's fd table is populated only with what the parent explicitly gives it. No implicit inheritance, no copy-on-write, no fork-safety concerns.

The libc wrapper execv_io() is the common call site:

Code: Select all

execv_io("a/system/bin/cat", argv, fdIn, fdOut);

IProcessImageBuilder — pluggable process loader

Process loading goes through a pure interface. The kernel's createProcess() never mentions ELF — it only knows IProcessImageBuilder:

Code: Select all

class IProcessImageBuilder {
public:
    virtual IProcessImage* build() = 0;
    virtual ~IProcessImageBuilder() {}
};
// IProcessImage carries the entry point and initial stack pointer
// returned to the scheduler when the first thread is created.
The current implementation is ElfImageBuilder, constructed in the cmpExecV syscall handler:

Code: Select all

// inside the cmpExecV handler:
ElfImageBuilder builder(fd, 0, &opts);
createProcess(&builder, priority);
ElfImageBuilder reads the ELF header, maps PT_LOAD segments into a fresh address space, zeroes BSS with rep stosl, and lays out the argv array on the user stack. createProcess() never sees any of that — it calls build() and gets back an entry point and a stack pointer.

Because the interface is the only boundary, other builders can be added without touching the process manager or the scheduler:
  • FlatBinaryBuilder — load a raw binary at a fixed address, useful for tiny bootloader-style payloads
  • Custom bytecode VM — build a sandboxed interpreter process without a native code segment
  • Memory-preloaded module — build a process image from an already-mapped region, skipping the file read entirely
Scheduler — policy as a contract

The scheduler owns per-CPU ready queues and the context-switch mechanism. It knows nothing about which algorithm decides thread order — that is fully delegated to ISchedulerPolicy:

Code: Select all

class ISchedulerPolicy {
    virtual void onCreate    (Thread* t)               = 0;  // thread just created
    virtual void onActivate  (Thread* t)               = 0;  // about to run
    virtual void onDeactivate(Thread* t, u32 consumed) = 0;  // was preempted
    virtual void onTick      (Thread* t, u32 elapsed)  = 0;  // timer tick
};
The current implementation RoundRobinPolicy uses an EMA to adapt each thread's quantum to its recent CPU usage:

Code: Select all

plannedTime = (filter × recentConsumed + (100 − filter) × standardTime) / 100
A CPU-bound thread gradually receives a longer slice (up to its priority ceiling); a thread that consistently yields early sees a shorter planned time. The scheduler itself does not know this formula.

Because the policy is a pure interface, it can be swapped at initialization. The longer-term goal is to let a privileged userspace process implement ISchedulerPolicy over a shared memory channel — observing thread behavior and making preemption decisions without touching the kernel.

IPC — sockets as the universal channel

All inter-process communication goes through AF_LOCAL sockets. There is no pipe() syscall; a bidirectional channel is a socketpair().

How the terminal works without TTY:

Code: Select all

terminal_w creates socketpair(termFd, shellFd)
  → execv_io("shell", argv, shellFd, shellFd)

  terminal_w                         shell process
  ──────────────────────────────     ──────────────────
  keyboard event → write(termFd)  ←→  stdin = read(0)
  read(termFd) → render chars     ←→  stdout = write(1)
The kernel sees two connected sockets. There is no line discipline, no controlling terminal, no SIGWINCH, no session group. The terminal is a window that happens to pipe bytes to a shell.

Window server as a named service:

Code: Select all

Server: bind("/svc/windowserver") → listen() → accept()

Client (any process wanting a window):
  connect("/svc/windowserver")
  → handshake → receives eventHandle + SHM key for canvas

Canvas in shared memory:
  ┌──────────────────────────────┐  ← SHM base
  │  ShmWindowHeader             │
  │   volatile int front;        │  active slot (0 or 1)
  │   int slotBytes;             │  width × height × 4
  ├──────────────────────────────┤
  │  Slot 0  (ARGB pixel data)   │
  ├──────────────────────────────┤
  │  Slot 1  (back buffer)       │
  └──────────────────────────────┘
Client writes pixels into slot[front]; the server composites from the same slot. On resize, client writes into the inactive slot, sends WINDOW_SWAP_BUFFER, server flips front. No pixel data crosses the socket — only commands and events.

What this structure gives you in practice

Each of the patterns above — dependency injection via struct, pub/sub for discovery, COM-style queryInterface, policy interfaces for algorithms — is not new. What mattered was applying them consistently from the beginning.

The practical result:
  • Adding a driver is a self-contained IDeviceSubscriber subclass. No changes to DeviceManager, no changes to any other driver, no central dispatch table to update.
  • Adding a syscall group is a new handler file and one case in the main switch. The handler unpacks its own subcommands; nothing else changes.
  • Adding a VFS mount is a new IVirtualMount subclass registered in one line.
  • Adding a new executable format is a new IProcessImageBuilder implementation. The process manager and scheduler are untouched.
  • Porting to a new CPU is implementing eight interfaces and writing archBootstrap(). The entire kernel core is untouched.
  • Replacing the scheduler algorithm is implementing ISchedulerPolicy and passing a different pointer at startup.
Happy to discuss any of it — particularly curious whether others have experimented with externalizing kernel policy decisions (scheduling, reclaim, I/O priority) to userspace via interfaces.
Post Reply