Repository navigation
Linux compatibility layer
Part IV of the system development guide.
Linux DRM code is compiled unmodified against an emulation of the Linux kernel API built from NetBSD kernel facilities. The emulation lives in:
-
sys/external/bsd/common/include/linux/— generic headers shared with other Linux-derived code (kernel.h,list.h,slab.h, ...) -
sys/external/bsd/drm2/include/linux/,include/asm/, ... — the rest of the headers -
sys/external/bsd/drm2/linux/linux_*.c— out-of-line implementations, built asdrmkms_linux(files.drmkms_linux,sys/modules/drmkms_linux)
Include order. Overrides come first, then upstream:
drm2/include, drm2/include/drm, common/include, then
dist/include, dist/include/drm, dist/include/uapi. A compat
header therefore shadows any same-named upstream header.
Symbol renaming. Out-of-line functions are renamed with a macro so they cannot collide with NetBSD kernel symbols:
#define init_waitqueue_head linux_init_waitqueue_head
void init_waitqueue_head(wait_queue_head_t *);Transitive includes. Linux headers include a lot indirectly, and
upstream code silently relies on it: drm_atomic.h never includes
<linux/completion.h>; it arrives via <linux/i2c.h> →
<linux/device.h> → <linux/pm.h>. When an upstream header fails on
a type it never included, make the compat headers include what the
corresponding Linux header does (pm.h, device.h, kernel.h
have been extended this way), rather than patching upstream.
Namespace clashes with NetBSD headers:
-
ALIGN: NetBSD's<sys/param.h>has a one-argumentALIGN(p), Linux a two-argumentALIGN(x, a).<linux/kernel.h>undefines NetBSD's and defines Linux's. -
struct rb_node,rb_left,rb_right: defined by NetBSD's<sys/rbtree.h>. See the red-black tree notes below. -
RB_ROOT:<sys/tree.h>has an unrelated function-like macro. -
free,current,hzvsHZand similar: handle in the compat header that introduces the Linux meaning.
Prefer solutions that let both meanings work in the same file, since glue and compat code use the NetBSD meaning next to Linux code:
| Clash | Solution |
|---|---|
mutex_init, mutex_destroy (Linux: struct mutex *; NetBSD: kmutex_t *, type, IPL) |
C11 _Generic on the argument type; parenthesized names (mutex_init) reach the real NetBSD functions |
LIST_HEAD(name) vs <sys/queue.h>'s LIST_HEAD(name, type)
|
variadic macro selecting by argument count |
RB_ROOT (Linux: object-like) vs <sys/tree.h>'s RB_ROOT(head)
|
<linux/rbtree.h> includes <sys/tree.h> first, so its include guard prevents a later redefinition |
ALIGN(x, a) vs ALIGN(p)
|
Linux's replaces NetBSD's in Linux code |
sprintf (absent from the NetBSD kernel) |
compat version with Linux's unbounded semantics |
Config options. Linux code tests CONFIG_* with
IS_ENABLED(), IS_BUILTIN(), IS_REACHABLE(), IS_MODULE(). The
compat versions follow Linux's semantics: 1 if the option is defined
as 1, else 0 — including undefined options — usable in both #if and
C expressions. (The previous #define IS_ENABLED(x) (x) broke on
undefined options in C code, which is why NetBSD had to pass
-DCONFIG_FOO=0 for so many options.) Options defined as 0 still
mean off.
Errors. Linux functions return negative errno; NetBSD positive. Convert at the boundary (in glue), never inside upstream code.
-
Force-included headers. Kbuild passes
-includeforcompiler_types.h, so Linux sources use__must_check,__always_inlineand the like without including anything. The drmkms build force-includes a compat<linux/compiler_types.h>the same way (files.drmkms,modules/drmkms/Makefile.inc, and the probe's flag list, which must be kept in sync by hand). -
Long include chains. Linux headers include a great deal
transitively (
device.hreachesstring.h,bitmap.h,seq_file.h, ...); ours are short. When a Linux file uses something it never included, find the Linux header that would have brought it and include it from our version of that header, with a comment.
Compat code must not be derived from GPL Linux code, so its behaviour
is learned from documentation: Documentation/, header comments and
the kernel-doc comments in .c files. To keep that boundary
mechanical, suspected GPL source is never read directly but through a
filter that prints only its comments (optionally only those outside
function bodies, which tend to narrate the implementation, plus the
one declaration line each comment documents), never code. Check the
SPDX tag first: MIT and dual-licensed files (most of DRM) and
BSD-licensed code may be read normally.
FreeBSD solves the same problem in sys/compat/linuxkpi, under
BSD-2-Clause (a few files MIT or dual-licensed). Unlike Linux's own
sources, it may be reused: check it before designing any non-trivial
piece, and port it where that is simpler than writing our own, keeping
its copyright notices and adapting to NetBSD (UVM is not FreeBSD's VM).
Simple shims are written directly.
The file layer follows its model: Linux code's struct file is
renamed to a Linux-shaped struct linux_file (f_op, private_data,
...), which a native file points to through an operations table that
forwards to f_op.
While DRM does not build, tools/probe (local-only, see
Testing) compiles each DRM source file with the real
kernel flags, syntax only, and ranks the first error of each failing
file. First errors matter most: one unknown token inside a struct in
a header breaks everything after it, so raw error counts mislead.
Work from the top of that ranking.
Once the first errors are mostly big topics, switch views: collect
every "implicit declaration", "undeclared" and "No such file" across
all logs and rank those. Small names (str_yes_no, MINORBITS,
readl, ...) cluster, and a batch of them unblocks several files at
once — one such batch took the probe from 57 to 68 of 81.
Checklist for each gap:
-
Does it already exist? Grep the compat headers first: twice the
"missing" name was defined, just in a header the file does not
reach (
string_helpers.hhad thestr_*helpers;bitmap.hhadbitmap_set). -
Reach it the way Linux does. Linux headers include each other
in known chains (
fs.h→kdev_t.h,of.h→property.h,vga_switcheroo.h→fb.h,seq_file.h→string_helpers.h→string_choices.h). Copy the chain — the include lines, not the GPL code — instead of adding the include to the.cfile, which is pristine anyway. -
Is it a CONFIG question? A header that stubs a function when
CONFIG_Xis unset clashes with the.cfile that defines it. If that file is built,CONFIG_Xbelongs in the three flag lists (files.drmkms,sys/modules/drmkms/Makefile.inc, the probe). - Pick the stub kind by the stub policy above, and say in the header why it is safe.
- Test whatever has behaviour (not pure declarations).
Linux: module_init(fn) runs when a module loads (or, built in, at
the "device" initcall level); core_initcall, subsys_initcall, ...
run earlier levels; module_exit(fn) runs at unload. Drivers and the
DRM core (drm_core_init) do their setup there.
Implementation: each macro adds an entry to the link set
linux_initcalls; a NetBSD module runs the set when it loads
(LINUX_INITCALLS_RUN()), by level then link order, each entry once,
and LINUX_EXITCALLS_RUN() at unload.
-
No filtering by module name. A loadable module's link set holds
only its own entries; in a built-in kernel the first module to load
runs everyone's, as Linux does. Filtering by
KBUILD_MODNAMEwould silently skip entries compiled under another module's flags (many attributes inheritCPPFLAGS.drmkms); designs whose failure mode is "nothing happens" are best avoided. -
Exit pairing per translation unit:
module_exitruns only if its unit had no init, or all its inits succeeded. A failed init cleans up after itself (Linux's rule), so its exit does not run. -
KBUILD_MODNAMElabels messages; it is-DKBUILD_MODNAME_ID=<name>(a bare token: config(1) mangles quotes) turned into a string. -
<linux/init.h>includes<sys/module.h>first: NetBSD declares its ownmodule_init()there.
Linux: a character device is a major number with file_operations
(register_chrdev); opening a node creates a struct file and runs
fops->open(inode, file), which may switch the file to other
operations (replace_fops: DRM's stub does, to the driver's).
NetBSD: a cdevsw whose d_open clones a descriptor (fd_clone).
Implementation: register_chrdev records the operations by Linux
major; linux_chrdev_open(linux_major, dev, fflags) is what a cdevsw's
d_open calls: inode for dev (so iminor is NetBSD's minor), Linux
file, open, fd_clone. A failed open does not call release.
kqueue. Linux has none; epoll is built on the poll method. On
NetBSD, kqueue is how Wayland compositors wait (through epoll-shim), so
every Linux file with a poll method supports EVFILT_READ and
EVFILT_WRITE:
- Attaching runs
pollonce with a poll table markedpt_kqueue, so the file'sselinfois attached to the wait queues it uses (as for poll(2), but without registering the thread for select). - A wakeup of any of those queues activates the knote (
NOTE_SUBMIT), without callingpoll: wakeups can come with spin locks held or from interrupt context, and poll methods may take other locks. - When kqueue scans, it re-checks level-triggered knotes with hint 0
in thread context; then the filter asks
poll(file, NULL)for the real state. A wakeup that finds nothing ready costs one check. - Notifications and knote attach/detach are serialized by a per-file
spin lock (
f_sellock, IPL_VM), whichselnotifyrequires. - Limitation: a wait queue polled by several files notifies only the
first (it carries one
selinfo);poll_waitreports it.
Linux: wait_event*(wq, cond) sleeps until a C expression becomes
true; wakers make it true, then call wake_up*(wq). NetBSD's 5.6 port
had none of this and rewrote every call site with explicit condvar
loops; this was the largest single category of local patches.
Implementation: a wait queue is a spin lock (wq->lock, which Linux
code may take directly), a condvar and a generation counter.
-
wake_up*increments the counter and broadcasts, under the lock. - A waiter snapshots the counter, evaluates
condwithout holdingwq->lock, and if false sleeps until the counter changes. A wakeup between snapshot and sleep changes the counter, so it cannot be lost. Not holding the queue lock while evaluatingcondmeanscondmay take other locks without lock-order cycles against wakers that hold those locks while callingwake_up. - Every wake-up wakes all waiters (Linux can wake one "exclusive" waiter); waiters recheck their condition, so this costs time only.
-
*_lock_irq(wq, cond, lock)variants release a caller-held spin lock while asleep;*_lockedvariants run withwq->lockheld. - Timeouts are in ticks;
MAX_SCHEDULE_TIMEOUTmeans forever; return values follow Linux (remaining time, at least 1, on success; 0 on timeout;-ERESTARTSYSon signal). - Linux never destroys wait queues, so the lock is
MUTEX_NODEBUG: freeing memory containing one is safe even under LOCKDEBUG, and no_destroypatch is needed. -
poll: an optionalwq->selinfo, set by NetBSD glue, getsselnotifyon every wake-up — after dropping the queue lock, since kqueue filters may take other locks. This replaces NetBSD's old patches callingselnotifyfrom upstream code. -
Entries: Linux's
wait_queue_entry_ton the queue's list (__add_wait_queue,add_wait_queue,init_waitqueue_func_entry). A wake-up calls every entry's function withwq->lockheld, before waking the sleepers; a function may remove its own entry. Drivers act at wake-up time this way: radeon signals its fences from such a callback (the fence's lock is the queue lock). Sleepers inwait_event*do not use entries.
Still to do: Linux's lower-level task-state API (set_current_state,
schedule_timeout, wake_up_process, prepare_to_wait), used by i915
and drm_syncobj.
guard(mutex)(&m), scoped_guard(mutex, &m) { ... },
T *p __free(name) = ..., DEFINE_FREE, CLASS, no_free_ptr, all
on the compiler's __attribute__((cleanup)). scoped_guard is a
for loop over a guarded variable, so break leaves the block and
unlocks. Lock types provide their guard with DEFINE_GUARD (mutex in
<linux/mutex.h>).
Linux's API is intrusive and caller-driven: the caller walks the tree
to find the link, then rb_link_node() and rb_insert_color(); code
reads node->rb_left/rb_right directly; and augmented trees cache
a per-subtree value (largest hole, largest interval end) maintained by
callbacks. NetBSD's rb_tree(3) is comparator-driven and cannot
express this, so the 5.6 port patched every caller.
Implementation: the textbook algorithm (Cormen et al., ch. 13) with
NULL leaves, written from scratch (Linux's lib/rbtree.c is GPL).
Nodes reuse NetBSD's struct rb_node, which has the same shape —
rb_nodes[2], which <sys/rbtree.h> already exposes as
rb_left/rb_right, and one word, used here for parent pointer |
black bit. Linux nodes and rb_tree(3) nodes never mix.
Augmented trees follow Linux's callback contract: rotate(old, new)
on every rotation, copy(old, new) when erase moves the successor into
the deleted node's place, propagate(node, stop) to recompute
upwards, stopping early once a value is unchanged. One subtlety cost
a bug: after copy, the successor carries the deleted node's stale
value, so propagation must go up to the successor and then recompute
from it unconditionally — otherwise an early stop below it leaves the
stale value in place.
Interval trees (INTERVAL_TREE_DEFINE, struct interval_tree_node)
are augmented trees caching the largest interval end per subtree, so
an overlap query can descend into subtrees whose intervals start
before the query. The previous rb_tree(3)-based version returned
the first interval starting at or after the query start, and missed
intervals that start earlier but overlap.
Linux 5.19 replaced "one exclusive fence + a list of shared fences"
with a single list of fences, each tagged with an
enum dma_resv_usage: KERNEL < WRITE < READ < BOOKKEEP. A query for
usage U covers all fences with usage ≤ U; dma_resv_usage_rw(write)
gives READ for writers (wait for everyone) and WRITE for readers (wait
for writers).
- Entries pack fence pointer and usage into one word, so a lockless reader never sees a mismatched pair after an in-place replacement.
- Writers hold the lock. Appends fill the slot, then publish the
count with a release store.
dma_resv_reserve_fencesgrows the list by publishing a new one (dropping signalled fences) and frees the old after an RCU grace period. -
dma_resv_add_fencereplaces an existing entry when its fence has signalled, or when the new fence comes from the same context, is no older, and has a usage no broader — otherwise a query could lose a fence it must wait for. - Lockless iteration takes each fence with
dma_fence_get_rcu, skips signalled ones, and restarts (telling the caller) if the list is replaced. This relies on fences being freed after RCU. - NetBSD's
pollsupport for dma-bufs stays: POLLIN waits for WRITE fences, POLLOUT for READ fences, with one shared fence callback per poll state.
Linux defines locks and containers at file scope with no init call
(static DEFINE_MUTEX(m);); NetBSD's must be initialized at run time,
and the 5.6 port added hand-written init functions for each. Instead,
each DEFINE_* macro also registers an init/fini pair in the link set
linux_static_init. Each module containing Linux code runs its set on
load (LINUX_STATIC_INIT_RUN()), before any Linux code, and the fini
functions on unload. In a kernel with everything built in, all
modules' entries merge into one set, so each entry has a done flag and
acts once. drmkms_linux runs its set first thing at load; available
for DEFINE_MUTEX, DEFINE_SPINLOCK, DEFINE_SRCU/DEFINE_STATIC_SRCU
and the DEFINE_XARRAY family. The pattern of a module taking its own link-set bounds
and passing them to a common routine is the same as for module
parameters (drm_sysctl_init).
Link sets in loadable modules. A link set's bounds,
__start_link_set_X and __stop_link_set_X, are made by the linker
when it merges the set's sections. A kernel module gets them only if
it is linked with a generated linker script, MKLDSCRIPT=yes in its
Makefile; without one, modload fails with "symbol
__stop_link_set_X not found". Every module with Linux code sets it.
__link_set_decl() declares the end as a weak symbol, and the
kernel's module linker (kobj) rejects unresolved symbols, weak or not.
A declaration at file scope would put that reference into every object
including the header, entries or not. So LINUX_STATIC_INIT_RUN()
and LINUX_INITCALLS_RUN() declare their set inside their own braces,
and only code that runs a set refers to it.
That still leaves a module that runs a set with no entries -- TTM has
no module_init, so its set of init calls is empty. Running a set
therefore also adds an anchor entry to it, which the run loops skip.
The anchor points to a sentinel object (linux_link_set_anchor), not
to NULL, because the generated linker script (sys/conf/mkldscript.sh)
lists only sets whose entries have relocation records, and a null
pointer has none.
Callers may take xa_lock() themselves to make several operations
atomic: drm_minor_acquire holds it across xa_load and taking a
reference, so xa_erase cannot slip in between. Linux's xa_load
never takes the lock (it reads under RCU), so that is legal; the
compat version takes the lock, which would recurse. xa_lock()
therefore records the owning thread, and every operation takes the
lock only if the current thread does not already hold it — which is
also exactly the meaning of Linux's __xa_store/__xa_erase/
__xa_alloc (for callers holding the lock). Under a held spin lock,
allocations must not sleep. Storage is still an rb_tree(3), not a
radix tree.
Linux's maple tree is a B-tree of ranges, RCU-safe, used for VMAs and
by some drivers. The compat version covers what drivers use (nouveau's
VM regions): a map from disjoint [index, last] ranges to entries on
an rb_tree(3) ordered by start, with Linux's cursor (MA_STATE)
semantics. mas_walk returns the entry holding index and its range,
or NULL and the range of the gap there (callers test the gap's end);
mas_store_gfp overwrites, trimming or splitting what it overlaps
(allocating its two possible new nodes before changing anything);
mas_for_each iterates and tolerates erasing the current entry. As
in Linux the caller serializes, with its own lock under
MT_FLAGS_LOCK_EXTERN; there is no RCU reading.
Drivers reach into struct dma_fence directly (flags, seqno,
context, error, ops, refcount, rcu, and i915 even cb_list
and timestamp), so its field names and types must match Linux,
while NetBSD-only internals (the condition variable used for waiting)
stay private additions at the end. Since 5.6:
- The lock is optional: with
NULL, the fence uses its owninline_lock(DMA_FENCE_FLAG_INLINE_LOCK_BIT); code reaches either throughdma_fence_spinlock(). - Sequence numbers are 64-bit per fence (
dma_fence_init64), compared with__dma_fence_is_later(fence, a, b). -
opsis RCU-protected, and after signalling, a fence whose ops have neitherwaitnorreleasedetaches from them (opsbecomes NULL), so the module providing them can unload while fences live on. Name lookups fall back to fixed strings. -
dma_fence_signal*return nothing;check_and_signalreports whether the fence had signalled already. - The condition variable and inline lock are released in the fence's release path, so drivers no longer call a NetBSD-only destroy.
The conversion was done in place, keeping NetBSD's locking and race handling rather than rewriting from scratch.
One fence standing for several: it signals when all members have,
with the first member error. Signalling is enabled lazily: then a
callback on each member counts down a pending count, and whoever takes
it to zero signals the array (from a softint when it is a member
callback, which runs under the member's lock). The count is atomic
because member callbacks run under their own locks; the error is
passed on under the array's lock by whichever path signals first.
Until signalling is enabled, asking whether the array has signalled
asks the members, as on Linux. 7.3 API: alloc and init (no
allocation, for reclaim paths), create without signal_on_any,
first/next/for_each, match_context; to_dma_fence_array
returns NULL for other fences.
Linux and NetBSD both call their device structure struct device.
NetBSD's 5.6 port used NetBSD's as Linux's and edited DRM wherever Linux
code needed more (its own devices for DRM minors and connectors,
kobjects, managed resources) — impossible with a pristine dist/. So,
as in FreeBSD's LinuxKPI, Linux code gets its own struct device:
-
The name.
<linux/device_netbsd.h>includes NetBSD's<sys/device.h>and then definesdeviceaslinux_device. The DRM build force-includes it, so the rename holds from the first line of every file (Linux headers forward-declarestruct device;everywhere); compat headers that mention struct device include it too. NetBSD's structure stays reachable asdevice_t. Fields nameddevice(pdev->device) are renamed consistently. Expectlinux_devicein compiler errors and in the debugger. If a NetBSD header were first read after the rename, itsstruct devicewould silently become Linux's — strange type errors there are the clue; no NetBSD header DRM reaches uses it as a type today. -
The structure has the fields Linux code uses (
parent,type,driver,class,driver_data,release, an embeddedkobj, DMA masks, PM state) plusbsddev: the NetBSD device it stands for, or NULL for devices Linux code creates for itself.linux_device_bsddev()finds the nearest one up the parents (the firmware loader needs a NetBSD driver name). -
Lifetime is the kobject's: named, refcounted, a child holding its
parent while added; on the last put, managed resources are released
and then the device's, its type's or its class's release function
runs.
dev_err()and friends print through the NetBSD device when there is one, else with the Linux name. -
Managed resources (
devm_*, ported from LinuxKPI'slinux_devres.c, BSD-2) are released newest first, when the device is released or when NetBSD glue detaches the driver (devres_release_all, called bylinux_pci_dev_destroy). -
sysfs and uevents do not exist: creating attributes, groups and
links succeeds and does nothing;
sysfs_emit()works, into page-aligned show buffers only, as on Linux. -
PCI:
struct pci_devembeds a Linuxstruct device dev(itsbsddevis the NetBSD device), registered bylinux_pci_dev_init;to_pci_dev()iscontainer_of,dev_is_pci()checks the bus type, and drvdata lives in the device, sopci_get_drvdata(pdev)anddev_get_drvdata(&pdev->dev)agree.
NetBSD and Linux both have a struct file, and Linux code reaches into
fields NetBSD's lacks (private_data, f_op, f_mapping). As with
devices, Linux code gets its own: <linux/file_netbsd.h> includes
the NetBSD headers that use struct file (sys/file.h, filedesc.h,
vnode.h), then defines file as linux_file; the DRM build
force-includes it. NetBSD's stays reachable as file_t.
-
A Linux file has Linux's fields, its own reference count and an inode (all anonymous files share one).
fput()releases it throughf_op->release— at once if the caller may sleep, else from a workqueue, as Linux defers it. -
Descriptors, Linux's way. Linux reserves a number (
get_unused_fd_flags), creates the file independently, then installs it (fd_install) or gives the number back (put_unused_fd). NetBSD'sfd_allocfile()takes a number and afile_t(there is no public way to get one without the other), so the reservation keeps both on the calling task;fd_installturns thefile_tinto one whose fileops (linux_fileops) call the Linuxfile_operations, and affixes it (fd_affix);put_unused_fdaborts it (fd_abort). Thefile_tthen holds the file's reference, dropped when NetBSD closes it;dupandforkshare thefile_t. -
The ioctl window. NetBSD's
sys_ioctlcopies an ioctl's argument into a kernel buffer before calling the driver; Linux drivers expect a user pointer and copy themselves (drm_ioctldoes). So the Linux ioctl is handed the kernel buffer's own address as its "user" pointer, and while it runs the task records the buffer:copy_from_user,copy_to_user,strncpy_from_userandclear_userserve that range from it. A kernel address is never a valid user address, so there is no ambiguity, and user pointers embedded in the argument (arrays) still go tocopyin/copyout. Commands without a payload (IOC_VOID) get the user's argument, whichsys_ioctlstores in the buffer. (After FreeBSD's LinuxKPI, which uses a fake address range instead.) -
Command numbers.
_IOWand friends encode direction and size differently on Linux and NetBSD, so a uapi header compiled here gives NetBSD numbers to the kernel and to programs alike, and they agree. The size field matters more than the number: NetBSD copies that many bytes in from the argument. Linux has commands that pass a pointer as the argument itself but are numbered as if they wrote one (DMA_BUF_SET_NAME,_IOW(..., const char *)); here the kernel would copy in the string's first eight bytes in place of its address. Such commands are defined with_IO(no payload) in our headers, so the address reaches the driver unchanged. -
poll: a file's
pollmethod callspoll_wait()for each wait queue that can make it ready; that attaches the file'sselinfoto the queue, whose wakeups alreadyselnotifyit. Release detaches the file from its queues before calling the driver'srelease, which may free them. -
lseek and kqueue: the adapter's
fo_seekcalls the Linuxllseek; kqueue, which Linux lacks, goes through one NetBSD-onlyfile_operationsmember,netbsd_kqfilter, which Linux code leaves NULL. -
dma-bufs and sync files are Linux files with their own
file_operations, recognized by them (dma_buf_get,sync_file_get_fence). A dma-buf's references are its file's (get_dma_buf/dma_buf_put), its own inode carries the size (fstat;lseek(SEEK_END)too, which libdrm uses), and the file's release calls the exporter'srelease.dma_buf_fdconsumes the caller's reference, as in Linux. The dma-buf code is a BSD implementation of the 7.3 API (Linux's is GPL): attachments of a Linux device, dynamic importers, pinning, the locked/_unlockedpairs, countedvmap,mmapof the descriptor through the exporter. -
Their ioctls are what explicit-synchronization user space (Vulkan, compositors) uses to meet implicitly synchronized buffers:
- on a dma-buf,
DMA_BUF_IOCTL_SYNCbrackets CPU access to a mapping; starting it waits for the buffer's implicit fences (a writer's for reading, all for writing), as Linux documents fordma_buf_begin_cpu_access, then the exporter makes the memory coherent; -
DMA_BUF_IOCTL_EXPORT_SYNC_FILEsnapshots the fences a reader or writer would wait for into a sync file (one fence, an array if several, the signalled stub if none);IMPORT_SYNC_FILEadds a sync file's fences to the buffer as a writer's or a reader's; - on a sync file,
SYNC_IOC_MERGEmakes one for two files' fences,SYNC_IOC_FILE_INFOdescribes it (name, status, each fence's driver, timeline and signal time),SYNC_IOC_SET_DEADLINEpasses a deadline hint to the fence's driver.
The structures and numbers are in
drm2/include/uapi/linux/(dma-buf.h,sync_file.h), our own definitions of the Linux ABI (Linux's uapi headers are GPL with the syscall note). User space needs no copy installed: Mesa carries its own copies of the Linux headers, and they produce the same numbers when compiled here. - on a dma-buf,
Linux code reads current->comm, ->group_leader, ->flags,
->exit_code, and keeps a refcounted struct pid per open DRM file
(compared and dereferenced under RCU). NetBSD's curproc cannot carry
that, so, as in FreeBSD's LinuxKPI:
-
Per-thread tasks. An lwp evaluating
currentgets atask_structon first use, kept as lwp-specific data until it exits. The fields Linux reads are refreshed from the lwp and process on everycurrent(cheap: the lookup is lock-free). Kthreads arePF_KTHREADand named after the lwp. -
Per-process task and pid. Each process has one more task, its
group_leader, which owns the process'sstruct pid. When the process exits,pid_task()answers NULL but the pid lives on while referenced. Tasks are refcounted (get/put_task_struct); tasks and pids are freed after an RCU grace period. -
Atomic context. Creating a task needs
lwp_setspecific(), which may sleep; a firstcurrentin atomic context gets a shared placeholder, not cached. "Can sleep" is tested as the kernel does: not in an interrupt or softint, not in a pserialize read section, no spin mutex held (MUTEX_NO_SPIN_ACTIVE_P), preemption not disabled (l_nopreempt). -
Exit order.
exit1()setsPS_WEXIT, closes files, and only then records the exit signal and runs specificdata destructors. So close-at-exit code seesPF_EXITING, but not yetexit_code == SIGKILL; the GPU scheduler then waits out a flush timeout instead of dropping a killed process's jobs at once. -
Kthreads made with
kthread_runkeep their state in a structure hung off the thread's task, which holds a reference so thatkthread_stop(task)works after the thread has exited.
Linux and NetBSD both run Intel's ACPICA (the ACPI interpreter and
table code), but Linux runs it through acpisrc, a tool that rewrites
ACPICA into Linux style: types and members in lower case
(union acpi_object, obj->integer.value). NetBSD's copy keeps
ACPICA's own spelling (ACPI_OBJECT, obj->Integer.Value). The
compiled layouts are the same; only the names differ. Linux driver
code calling ACPICA therefore needs Linux's names on NetBSD's ACPICA.
-
Twin structures. For each ACPICA structure Linux code touches
(the object union, object list, buffer, table header), the header
defines a twin with Linux's member names and ACPICA's layout
(
union linux_acpi_object, ...), and then renames the tags (#define acpi_object linux_acpi_object), never the members. Every member pair is checked at compile time: a__CTASSERTon the sizes of the two types, and one per member on its offset and size (LINUX_ACPI_SAME). A change in ACPICA's layout breaks the build, not memory. The calls (acpi_evaluate_object,acpi_get_table, ...) take the twins and cast to ACPICA's types. FreeBSD's LinuxKPI twins the object and buffer the same way. -
ACPI_HANDLE(dev)is a function-like macro. Linux usesACPI_HANDLE(dev)for "the ACPI node of a device", while NetBSD's ACPICA has a type of that name. An object-like macro would replace the type everywhere; a function-like macro expands only where the name is followed by(, so ACPICA's own casts,(ACPI_HANDLE) x, still name the type. -
Which kernels have ACPI. A kernel build knows (
acpica.h,NACPICA). A module build cannot, so it assumes ACPI on the ports whose GENERIC kernels have it (x86, aarch64); the module then needsacpicain the kernel it loads into. The header never definesCONFIG_ACPIitself: it offers the types and calls, and each driver decides (amdgpu setsCONFIG_ACPIinkconfig_amdgpu.h; the DRM core and other drivers do not). -
A device's ACPI node.
linux_pci_dev_initlooks the function up among acpi(4)'s nodes (acpi_pcidev_find(segment, bus, device, function));ACPI_HANDLE(dev)andACPI_COMPANION(dev)of a PCI device return it.acpi_dev_get_first_match_devsearches acpi(4)'s nodes by hardware ID._DSMcalls (acpi_evaluate_dsm,acpi_check_dsm) build the method's four arguments. -
Notifier chain.
register_acpi_notifierkeeps a chain under a mutex (its callbacks evaluate ACPI methods, which may sleep). On Linux, the ACPI video and AC adapter drivers broadcast events on it; here those events go to acpivga(4) and acpiacad(4), which do not call it yet (Backlog).
What amdgpu uses it for: an APU has no PCI expansion ROM, and its
VBIOS (the GPU's table of display, clock and power data) is in the
ACPI VFCT table; a discrete GPU in a hybrid laptop returns its
VBIOS from the ATRM method. Without CONFIG_ACPI the driver finds
no VBIOS on these machines and stops at init. The ATIF and
ATCS methods (firmware requests about power, backlight and PCIe
link speed) come with it.
-
Two-argument
strscpy(dst, src)(Linux 6.8+) takes the size fromdst, which must be an array; the macro dispatches on the number of arguments and checks with__must_be_array. -
smp_store_release(p, v)/smp_load_acquire(p)take pointers. -
delayed_work.timer.expires: the GPU scheduler reads when its timeout fires; set (in ticks) wherever the callout is armed. -
hrtimer_try_to_cancelcannot tell a running callback from a finished one on NetBSD, so it answers -1 ("may be running") for any timer that had fired; callers loop onhrtimer_active. -
Workqueues: every queue runs its work in one thread, in order, which honours any
max_active(WQ_MAX_ACTIVEincluded); names are printf-formatted as in Linux.disable_work[_sync]/enable_work(Linux 6.10) keep a disable count on the item:queue_workrefuses a disabled item and returns false. -
io_mappingis Linux's API (address-onlyio_mapping_unmap,io_mapping_create_wc) overioremap_wc, one mapping per call; the "atomic" variants are the same, callers here being in thread context. -
Flexible arrays:
struct_group[_tagged],TRAILING_OVERLAP,DEFINE_FLEX/DEFINE_RAW_FLEX(on-stack objects sized bystruct_size_t, an integer constant expression for constant counts), and Linux's__struct_size(p)/__member_size(p)(the compiler's dynamic object size). -
kthread_worker: a thread running queued items one at a time, in order — implemented as an ordered Linux workqueue.sched_set_fifois a no-op for now (vblank work may see more latency than on Linux). -
dma_resv_reserve_fencespublishes the grown list before dropping the signalled fences it leaves behind, so lockless readers do not keep finding dying fences in the current list. -
ww_mutex_trylock(lock, ctx): since Linux 5.16 a successful trylock with a context joins it, asww_mutex_lockwould. -
raw_spinlock_t: NetBSD spin mutexes always spin, so it isspinlock_tunder another name. -
iosys_map: a buffer pointer that is either system memory or I/O memory, with copy, read and write helpers. -
printk_once,pr_*_onceprint once per call site, as Linux'sDO_ONCE_LITE: a static flag inside a statement expression, so each expansion has its own; they return whether they printed. A plainprintkin their place floods the message buffer from code that runs per frame or per commit. -
in_task()means "not in hard or soft interrupt context" (!(cpu_intr_p() || cpu_softintr_p())), as on Linux; preemption being disabled does not make code non-task (amdgpu's display code nests floating-point sections, which disable preemption). -
sscanf,vsscanfare real kernel functions (sys/kern/subr_scanf.c, FreeBSD's, from 4.4BSD'svfscanf; declared in<sys/systm.h>, in the kernel and rump). Drivers parse firmware version strings, device-tree compatibles and module parameters with them; a stand-in returning 0 makes every parse fail. -
CONFIG_64BITis defined on 64-bit kernels (kconfig_netbsd.h), as on every 64-bit Linux kernel: amdgpu maps the CPU-visible part of VRAM once only under it, and needs that mapping for memory training and VRAM access through the aperture. -
Allocation helpers:
k{m,z}alloc_obj{,s},kv*variants,GFP_KERNEL_ACCOUNT(no memory cgroups: same asGFP_KERNEL).
Rule: when NetBSD lacks something whose absence users would feel, change NetBSD. Stubs are fine for developer-only facilities and as a temporary step to get code compiling; a missing core feature that would cripple what end users get is fixed in the core instead — small, self-contained, tested, and offered upstream (the per-page cache attributes of M0 are the model).
| API | Why a stub | Users affected? |
|---|---|---|
Device tree (of.h, of_graph.h, video/of_*) |
x86 has none; NetBSD's ARM DRM drivers use NetBSD's own FDT code | no (x86) |
| debugfs, sysfs, seq_file users | no equivalents; struct seq_file exists and seq_puts/seq_printf/seq_write write nowhere; dma_resv_describe is a no-op |
no — developer tools |
| Dynamic debug, kmsg_dump, kunit, cgroup_dmem, nomodeset | features NetBSD does not have | no |
eventfd |
NetBSD has eventfd(2) but no in-kernel signalling API yet, so DRM_IOCTL_SYNCOBJ_EVENTFD returns EOPNOTSUPP |
yes — compositors and Vulkan can wait on syncobjs through eventfds: core change planned (an in-kernel eventfd signal API) |
-
GEM backing storage:
drm_gem.cnow gets pages through Linux's shmem/folio API; the compat layer must provide it on UVM anonymous objects. -
Big topics left in the probe (each a design of its own):
platform_device(HDMI audio/CEC sub-devices),fb_info(fbdev emulation), folios/list_lru(GEM shmem and TTM pools),dma_map_sgtable, the glue's AGP/legacy headers,drm_device.pdevin the glue. -
kthread_runsignature: still NetBSD's extra interlock/wait-queue arguments (from the 5.6 GPU scheduler); 7.3 drivers use Linux's, andkthread_stopshould now usewake_up_process. -
Device nodes for DRM minors:
drm_sysfs_minor_allocmust create a Linux device per minor (now possible), and the cdevsw glue find minors through it. - mmap for Linux files and dma-bufs (with GEM storage).
-
GPL-only helpers to replace with BSD-licensed versions, starting
with
drm_managed.
aiBSD system development guide
Tutorial
II — Building
III — The kernel
- Kernel basics
- Booting and kernel modules
- Threads, processes, tasks
- Devices and drivers
- Files, descriptors, device nodes
- PCI
- Virtual memory
- Memory and DMA
- Page tables, TLBs, memory types
- Firmware
- State and events
- The console
- Power management
IV — Linux compat layer
V — DRM
VI — Testing
VII — Upstreams
Appendices