Skip to content

[ISSUE] Separate driver implementations into a modular structure for out-of-tree builds #72

Done
5 of 5 issues completed

Description

@marcobuschini

Context

Following the C++ encapsulation of core kernel subsystems (kernel/uapi/, Sync::IrqGuard, Process, MM::PageFrameAllocator, and MM::KernelHeap), hardware drivers are still coupled directly to internal kernel headers and globals (for example, kernel/drivers/virtio/virtio_blk.cpp reaches directly into mm/pfa.hpp, mm/AddressSpace.hpp, process/Process.hpp, process/scheduler.hpp, and sync/IrqGuard.hpp).

To enforce strict kernel/driver boundaries and allow drivers to be developed, unit-tested, and compiled independently of the core kernel, upcoming and migrated drivers must build against a self-contained Driver Development Kit (DDK) interface (include/ddk/). In-tree and out-of-tree drivers must follow the exact same directory structure, header surface, and Make build workflow.

Proposed Directory Structure

├── include/
│   └── ddk/                     # Public Driver SDK headers (stable freestanding C++20 interfaces)
│       ├── Status.hpp           # Exception-free Status enum & Result<T> helper
│       ├── Resources.hpp        # Move-only RAII handles: MmioRegion, IrqHandle, DmaBuffer, IrqLock
│       ├── Bus.hpp              # FDT/MMIO DeviceDescriptor (extensible to PCI later)
│       ├── Services.hpp         # Abstract PlatformServices & device-class registration contracts
│       └── Driver.hpp           # Base Driver lifecycle class & static DriverMetadata entry point
├── kernel/
│   ├── uapi/                    # Linux AArch64 syscall ABI headers (private to kernel personality)
│   ├── ddk/                     # Kernel-side PlatformServices bridge (maps DDK -> PFA, HAL, IrqGuard, WaitQueue)
│   └── ...                      # Private core kernel headers; inaccessible to drivers/
├── drivers/                     # In-tree modular drivers (identical layout to external driver repos)
│   ├── ddk.mk                   # Reusable Make rules & compiler flags (exportable via MILO_DDK_DIR)
│   ├── dummy/                   # Minimal reference driver verifying in-tree & out-of-tree builds
│   ├── serial/                  # Future: decoupled PL011/serial drivers
│   └── block/                   # Future: migration target for kernel/drivers/virtio/virtio_blk.cpp
└── tests/
    └── host/                    # Host unit tests with mock Kernel::DDK::PlatformServices

(Note: kernel/uapi/ remains private to kernel/ because Linux syscall ABI layouts belong to the kernel's POSIX personality, not to hardware drivers.)

Design & Architectural Rules

1. Strict Header & Build Isolation

  • No private kernel or arch includes: Code under drivers/ may only include freestanding C++20 standard headers (<cstdint>, <cstddef>, <type_traits>, <span>, etc.) and public headers from include/ddk/. Including anything from kernel/ or arch/ is forbidden.
  • Compiler-enforced boundary: Driver compilation rules in drivers/ddk.mk pass -I$(MILO_DDK_DIR)/include and omit -Ikernel and -Iarch/..., so any internal header leakage fails immediately at compile time.
  • Freestanding C++20 & quality gate parity: All DDK headers and drivers must compile cleanly with Milo's strict flags (-std=c++20 -ffreestanding -fno-exceptions -fno-rtti -Wall -Wextra -Werror -Wpedantic -Wshadow -Wconversion -Wsign-conversion -Wnull-dereference), support -DHOST_TEST, and pass make format (clang-format) and make quality (clang-tidy).

2. Namespace, Ownership & Dependency Injection (Kernel::DDK)

  • Naming consistency: Use namespace Kernel::DDK and PascalCase class/header names matching the rest of the kernel (Kernel::MM, Kernel::Sync, Kernel::Process, Kernel::UAPI).
  • Abstract capability injection: Drivers never reference global kernel symbols (alloc_frames, Process::current(), HAL::get_cpu(), Sync::IrqGuard). Instead, the kernel passes a PlatformServices& reference providing:
    • MMIO: map_mmio(uintptr_t paddr, size_t size) returning a move-only MmioRegion with typed volatile reads/writes and memory barriers.
    • DMA: alloc_dma(size_t size, size_t align) returning a move-only DmaBuffer exposing both virt_ptr() and phys_addr() (backed by MM::PageFrameAllocator + MM::phys_to_virt inside kernel/ddk/).
    • Interrupts & synchronization: register_irq(uint32_t irq, IrqHandler fn, void* ctx) returning IrqHandle, and an opaque IRQ-masking lock primitive (acquire_irq_lock() -> IrqLock, backed by Sync::IrqGuard).
    • Blocking I/O: An opaque wait/wake primitive (EventHandle / wait() / wake_all()) backed by Process::WaitQueue so drivers never inspect Process or Scheduler.
    • Logging: log(LogLevel, const char* msg).
  • RAII resource ownership (Rule of Five): MmioRegion, IrqHandle, DmaBuffer, and IrqLock are non-copyable, movable, noexcept, and deterministically release their backing kernel resources through their PlatformServices* pointer on destruction.
  • No direct kernel heap coupling: Out-of-tree drivers must not assume kernel kmalloc/kfree. DriverMetadata pairs create_instance() with destroy_instance(Driver*) (or uses static/placement storage managed by the driver module).

3. Out-of-Tree Build & Dual-Target Testing

  • Exportable SDK via Make: Add a make export-ddk target that packages include/ddk/ and drivers/ddk.mk into a standalone directory (e.g., build/ddk/).
  • Identical in-tree and external consumption: In-tree drivers under drivers/ include drivers/ddk.mk using MILO_DDK_DIR, the exact same variable an external driver repository sets to build a static driver archive (.a) or object against build/ddk/.
  • Host-testable by default: Because drivers depend only on PlatformServices&, tests/host/ can instantiate any driver directly against a mock PlatformServices without booting QEMU or linking core kernel globals.

Example DDK Interface Pattern

// include/ddk/Driver.hpp
#pragma once

#include "ddk/Bus.hpp"
#include "ddk/Services.hpp"
#include "ddk/Status.hpp"

#include <cstdint>

namespace Kernel::DDK {

inline constexpr uint32_t DDK_ABI_VERSION = 1U;

class Driver {
  public:
    virtual ~Driver() noexcept = default;

    Driver(const Driver&) = delete;
    Driver& operator=(const Driver&) = delete;
    Driver(Driver&&) = delete;
    Driver& operator=(Driver&&) = delete;

    [[nodiscard]] virtual bool probe(const DeviceDescriptor& dev) noexcept = 0;
    [[nodiscard]] virtual Status init(PlatformServices& services,
                                      const DeviceDescriptor& dev) noexcept = 0;
    virtual void shutdown() noexcept = 0;

  protected:
    constexpr Driver() noexcept = default;
};

struct DriverMetadata {
    uint32_t ddk_abi_version{DDK_ABI_VERSION};
    const char* name{nullptr};
    Driver* (*create_instance)() noexcept {nullptr};
    void (*destroy_instance)(Driver*) noexcept {nullptr};
};

} // namespace Kernel::DDK

Technical Scope & Action Items

  • Create include/ddk/ with freestanding C++20 headers (Status.hpp, Resources.hpp, Bus.hpp, Services.hpp, Driver.hpp) in namespace Kernel::DDK.
  • Create kernel/ddk/ implementing the kernel-side PlatformServices bridge over MM::PageFrameAllocator, HAL, Sync::IrqGuard, and Process::WaitQueue.
  • Create drivers/ddk.mk and integrate it into Makefile / kernel/kernel.mk without -Ikernel or -Iarch/... on driver translation units.
  • Add a make export-ddk target producing a self-contained SDK bundle (include/ddk/ + ddk.mk) consumable via MILO_DDK_DIR.
  • Implement a minimal reference driver under drivers/dummy/ and verify:
    • It builds cleanly in-tree and links into the kernel image.
    • It builds cleanly from an external directory pointing only at MILO_DDK_DIR=build/ddk.
    • A Catch2 unit test in tests/host/ exercises its probe() / init() / shutdown() lifecycle and RAII resource cleanup using a mock PlatformServices.
  • Verify make format && make all && make quality passes with zero warnings.

Out of Scope (Follow-Up Issues)

  • Migrating kernel/drivers/virtio/virtio_blk.cpp to drivers/block/virtio_blk/ and retiring kernel/drivers/ (will be tracked as a dedicated follow-up once the DDK foundation and BlockDevice contract land).
  • Dynamic module loading / userspace driver servers (this issue establishes static linking via DriverMetadata first).

Sub-issues

Sub-issues

5 of 5 Issues completed
Loading 5 sub-issues

Activity

  1. changed the title [-][Architecture / Build] Separate driver implementations into a modular structure for out-of-tree builds[/-] [+][ISSUE] Separate driver implementations into a modular structure for out-of-tree builds[/+] on Dec 2, 2026
  2. moved this from Backlog to Todo in kernelite/miloon Dec 3, 2026
  3. moved this from Todo to In progress in kernelite/miloon Dec 3, 2026
  4. moved this from In progress to In review in kernelite/miloon Dec 3, 2026
  5. moved this from In review to Done in kernelite/miloon Dec 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions