Skip to content
ebenali edited this page Dec 3, 2026 · 14 revisions

aiBSD system development guide

How the aiBSD (NetBSD-derived) source tree and build work, how to hack on the kernel, and what we learned bringing Linux DRM v7.3 to it. The kernel API reference stays in the section 9 man pages (share/man/man9); this guide explains and links to them rather than repeating them.

Status markers: [written] = a full chapter; [stub] or abridged = verified facts, names and source pointers, enough to be written out later without re-research; [notes] = material gathered and partly written up; [todo] = not yet learned.

Start here:

This wiki is a git repository (<repository>.wiki.git); pages are Markdown files, and images or other files can be committed next to them and linked relatively.


Part I — The source tree

  1. Orientation [notes]
    • aiBSD vs NetBSD: what the fork is, what changes, what stays compatible
    • Top-level layout: sys/, lib/, bin/, usr.*, external/, distrib/, etc/, share/, tests/, tools/
    • external/ and sys/external/: third-party code by license (bsd, mit, gpl2, gpl3, cddl, ...), vendor imports and local glue
  2. Source control [notes]
    • git, not CVS: branches, the trunk branch, topic branches
    • Vendor branches in git (vendor/linux-drm, tags linux-drm-vX.Y.Z), merging imports into a working branch
    • $NetBSD$ RCS ids: kept in existing files, not added to new ones
    • Local-only aids via .git/info/exclude
  3. Licensing [notes]
    • NetBSD's no-GPL-in-the-kernel rule and how aiBSD differs
    • Reading SPDX expressions (GPL-2.0 OR MIT vs GPL-2.0 AND MIT)
    • GPL-only DRM files: build switch, allowlist, tools/license-check
    • CDDL (ZFS, DTrace) next to GPL code
    • Clean-room rule for compat code: write from documented behaviour, never translate GPL sources

Part II — Building

  1. build.sh [notes]
    • Tools, distribution, release, kernel, live-image targets
    • -O/-T object and tool dirs, -u updates, -j
    • Host compilers: building tools with clang vs gcc; the MPFR _Float128 failure and --disable-float128; never mixing compilers in one tools dir
    • -V overrides (MKKMOD=no, KERNEL_SETS, KERN_SET, ...)
    • CTF: type data for DTrace [written]: ctfconvert/ctfmerge from illumos, the BTF-based merge, strict and lenient conversion, how the kernel, fbt and libdtrace read CTF; section renumbering when rewriting ELF files
  2. Kernel configuration [notes]
    • Config files, include/no, options, attachments
    • config(8)/nbconfig: files.*, define, file, makeoptions, defflag; per-file CWARNFLAGS/COPTS
    • Why basenames must be unique across a kernel
    • Kernel modules (sys/modules) vs built-in drivers
  3. Set lists and mtree [notes]
    • distrib/sets/lists/*, marking removed files obsolete
    • etc/mtree/NetBSD.dist.*
    • Debug sets
  4. Images and VMs [notes]
    • The amd64 live image (GPT, EFI, resize_gpt/resize_root)
    • The test VMs: q35, UEFI without secure boot, NVMe, TPM 2.0 over TIS (why not CRB), virtio-gpu, no vIOMMU
    • Growing disks; GPU passthrough candidates [todo]

Part III — Hacking on the kernel

Each chapter: what NetBSD has (structures, handles, lifetimes), what Linux has for the same job, and how the compat layer makes the Linux one appear on NetBSD. [stub] chapters hold verified facts and source pointers, to be written out.

  1. Kernel programming basics [written]
    • Execution contexts and "may I sleep here?"; KNF, KASSERT, DIAGNOSTIC; NetBSD positive vs Linux negative errnos
  2. Synchronization (in kernel basics) [written]
    • mutex(9) adaptive vs spin, IPLs, MUTEX_NODEBUG and LOCKDEBUG; condvar(9); pserialize(9), psref(9), localcount(9), RCU emulation; atomics and memory ordering, with worked examples
  3. Threads, processes and tasks [written]
    • proc/lwp, specificdata, kthreads and joining, exit order; Linux tasks, pids, kthreads; per-LWP tasks in the compat layer
  4. Devices and drivers [written]
    • why devices form a tree, enumerated vs described hardware, matching and binding, why detaching is the hard part; autoconf (cfdriver, cfattach, device_t, softc, deferred attach, references); Linux's driver model (kobject, device, driver, bus, class, devres); the two struct devices
  5. Files, descriptors and device nodes [written]
    • struct file, fileops, descriptors, the cdevsw and cloning devices (fd_clone, EMOVEFD); Linux's file/inode/ file_operations, replace_fops; Linux files on NetBSD and /dev/dri; select/poll, kqueue, epoll, and kqueue on Linux poll methods
  6. PCI [written]
    • how PCI Express works: topology, config space (mechanism #1, ECAM), enumeration, BAR sizing and windows, posted writes and read flushes, MSI/MSI-X as memory writes, resizable BAR, links; attach args, bus_space(9), interrupts, struct pci_dev built on NetBSD
  7. Virtual memory, from the ground up [written]
    • address spaces, map entries, UVM's two layers (objects, amaps of anons), copy-on-write, the fault path and its locking, the life of a page, the page daemon (clock, intents), swap and where slots are recorded; Linux's mm side by side; how the compat layer sits on UVM
    • Reading: Cranor's UVM thesis; Gorman's Linux VM book
  8. Memory and DMA [written]
    • kmem(9), pools, UVM pages and objects, bus_dma(9); Linux allocators, pages and folios, shmem, the DMA API; mapping memory into processes (pgo_fault vs VMAs and fault handlers), taking mappings back (pv lists), caching attributes, shrinkers
    • Reading: Cranor's UVM thesis; Thorpe's bus_dma paper
  9. Page tables, TLBs and memory types [written]
    • x86-64 paging and entry bits, large pages, TLBs and shootdowns, PAT/MTRR memory types and the aliasing rule; NetBSD's pmap, the recursive mapping and the direct map; per-page cache attributes (M0) as worked example; pitfall: stale translations of page tables
    • Reading: Intel SDM vol. 3 ch. 4 and 11; FreeBSD's amd64 pmap
  10. Firmware [written]
    • firmload(9) vs request_firmware(); xz-compressed images (XZ Embedded, single-call); GPU firmware from linux-firmware per what drivers declare (MODULE_FIRMWARE), sets, builds without it
  11. Exporting state and events [written]
    • sysctl, drvctl/devpubd, sysmon vs sysfs, uevents, udev
  12. Power management [written; Linux side abridged]
    • pmf(9) vs dev_pm_ops and runtime PM
    • Reading: Kunz, Writing Drivers for NetBSD

Also in Part III (unnumbered so the numbering below stays stable):

  • Booting and kernel modules [written]
    • boot loader to kernel (bootinfo, priming), module sources and classes, init order around autoconf, _MODULE pitfalls, module properties from boot.cfg, Linux module parameters as sysctl
  • The console: wscons, vcons, genfb and DRM [written]
    • the layers, tty window size and SIGWINCH, resizing in place, drmfb and the DRM console client; at boot, from the firmware's framebuffer to DRM (early console, match priorities, probe after root, takeover and give-back)

Part IV — Linux compatibility layer (sys/external/bsd/{common,drm2}/include/linux)

  1. How the layer works [notes]
    • Header overrides first, then upstream; linux_* symbol renaming
    • Matching Linux's transitive includes (pm.h, device.h, kernel.h)
    • Namespace clashes: ALIGN, struct rb_node/rb_left, RB_ROOT, free
    • IS_ENABLED with Linux semantics (undefined = off)
  2. Design notes per API [notes]
    • Wait queues: generation counter, conditions evaluated unlocked, no lost wakeups, no destroy, selinfo hook for poll
    • cleanup.h: guard, scoped_guard, __free, CLASS
    • Red-black trees: textbook algorithm on NetBSD's struct rb_node, augmented callbacks, interval trees
    • dma_resv: usage model, packed entries, lockless iteration, poll
    • Fences (inline locks, 64-bit seqnos, detaching ops) and fence arrays
    • Tasks: per-thread task_struct, process pids, atomic context, exit order
    • kthread_worker on ordered workqueues
    • ww_mutex with acquire contexts; iosys_map; allocation helpers
    • Stubs and why: device tree, debugfs/sysfs, dynamic debug, cgroups, kunit, eventfd
  3. Open problems [notes]
    • GEM backing store: Linux shmem/folios over UVM
    • Task state for sleeping (set_current_state, wake_up_process)
    • File-descriptor layer

Part V — The DRM integration

  1. History and the cost of the old approach [notes]
    • NetBSD's 5.6 import: edits in place, 1,725 #ifdefs, unmarked edits
    • Measuring the delta against pristine Linux; classifying hunks
    • What happened to those files upstream by 7.x (rewritten/removed)
  2. The pristine-dist/ model [notes]
    • Rules: never edit dist/; compat first, glue second, replacement files last; generated renames; generated files outside dist/
    • tools/import, tools/verify-dist, tools/paths
    • Importing a new Linux release step by step
    • Shadowing headers: finding them, MIT → upstream, GPL → BSD replacement with the same API, deriving an API cleanly
    • Stub policy: fail cleanly, do nothing, or panic — chosen by what breaks
  3. Build lists [notes]
    • drm2netbsd: evaluating Kbuild, composite objects, NetBSD replacements, skipped objects and why
  4. What was removed and why [notes]
    • Legacy DRM (drmums), VIA, AGP ioctls; AGP still works for radeon/nouveau
  5. Drivers [todo]
    • i915, amdgpu, radeon, nouveau, vmwgfx; firmware; Rust drivers (nova, tyr) and what supporting them would take
  6. Backlog: from working to fully capable
    • Every stand-in, what replacing it takes; core changes; gates before real hardware
  7. GPU drivers: lessons from amdgpu
    • A GPU as many processors; rings, doorbells and fences
    • Memory domains, memory types and the GPU's own MMU
    • Failure handling; code shared across operating systems; what porting it teaches; a reading order

Part VI — Testing

  1. Compile testing [notes]
    • The syntax probe (tools/probe, temporary) and reading its output
    • Cross-port kernel builds [todo]
  2. Unit tests [notes]
    • ATF; rump kernels; private rump libraries and rumpns_ symbols (tests/dev/usb/t_hid, tests/dev/drm)
    • A rump kernel on the build host (Linux), AddressSanitizer
    • Rump pitfalls: 2 vCPUs, no preemption, cached curlwp, implicit lwps
    • Writing stress tests that catch things
    • Host-side randomized harnesses
  3. System tests [notes]
    • Booting a built image in the VM; running tests unattended; collecting results over the serial console
    • The dev VM: install once, copy and run tests over ssh
  4. What each kind of test finds [written]
    • Contracts, locking, randomized models, postconditions, stress loops, a second kernel, pmap stress, module loading

Part VII — Working with upstreams

  1. Reporting upstream [notes]
    • Verify against current upstream first; describe fixes in words; disclose AI assistance; say whether reproduced
    • Where: NetBSD send-pr/gnats, Linux dri-devel / freedesktop GitLab
    • Drafts are kept outside the tree
  2. Tracking upstream NetBSD [notes]
    • trunk mirrors NetBSD; sync, review rewritten areas, merge
    • Local changes to imported code: written as upstream code, no labels; found with git log -- dist and README.aibsd

Tutorials

  • Porting a Linux API to the compat layer: the task API end to end — find the gap, learn the semantics cleanly, map onto NetBSD, implement, test in three loops, commit; plus a GPL-shadowed header [written]

Appendices

  • A. Glossary [notes]
  • B. Further reading [notes]: section 9 man pages; Thorpe (bus_dma); Cranor (UVM); Kantee (rump/anykernel); Kunz (drivers); McKusick et al. (4.4BSD, FreeBSD); NetBSD Guide and Internals (in NetBSD's htdocs repository, not this one); tech-kern archives
  • C. Source map: what is where in NetBSD's sources, and what we verified there (gotchas marked) [notes]

Clone this wiki locally