Skip to content

Files descriptors and device nodes

ebenali edited this page Dec 1, 2026 · 2 revisions

Files, descriptors and device nodes

How a process talks to a driver: it opens a device node, gets a file descriptor, and reads, writes, ioctls, mmaps, polls and closes through it. This chapter follows that path through NetBSD and Linux, and shows how the compat layer lets Linux's DRM own the /dev/dri nodes on NetBSD. It ends with the three ways a process waits for a descriptor to become ready — select/poll, kqueue and Linux's epoll — because a graphics stack spends its life waiting on DRM events.

Prerequisites: Devices and drivers.

Three layers

Both kernels have the same three layers, with different names:

NetBSD Linux
per-process number file descriptor (index into filedesc_t) file descriptor (index into struct fdtable)
open file struct file (file_t) struct file
what it is open on a vnode, a socket, a pipe, or a cloned object an inode (and its address_space)
operations struct fileops (f_ops), per kind of file struct file_operations (f_op), per driver
device operations struct cdevsw / struct bdevsw, per major file_operations registered per major (register_chrdev, cdev_add)

A descriptor is just a small integer naming an entry in the process's table. Several descriptors (after dup, or in parent and child after fork) can refer to one open file, which holds the offset, the open mode and a reference count; the open file refers to the object — for a device, the device node's vnode on NetBSD, an inode on Linux.

NetBSD

The open file

struct file (sys/sys/file.h): f_ops (the operations), f_data (the object they act on), f_type (DTYPE_VNODE, DTYPE_SOCKET, DTYPE_MISC...), f_flag (FREAD, FWRITE, FNONBLOCK...), f_offset, f_cred (the opener's credentials), f_count (references).

struct fileops is one table per kind of file: fo_read, fo_write, fo_ioctl, fo_fcntl, fo_poll, fo_stat, fo_close, fo_kqfilter, fo_mmap, fo_seek, ... Vnodes have vnops, sockets socketops, and a driver can supply its own.

Descriptor functions (kern/kern_descrip.c):

  • fd_allocfile(&fp, &fd) — reserve a descriptor and a fresh struct file, not yet visible to the process;
  • fd_affix(p, fp, fd) — make it visible;
  • fd_abort(p, fp, fd) — give both back (an open that failed);
  • fd_getfile(fd) / fd_putfile(fd) — look a descriptor up and hold it while using it; fd_close(fd) closes (after fd_getfile).

Device nodes and the cdevsw

A device node (/dev/dri/card0) is a file whose vnode carries a device number: major and minor (major(dev), minor(dev), makedev). The major picks a driver's struct cdevsw (sys/sys/conf.h) — d_open, d_close, d_read, d_write, d_ioctl, d_poll, d_mmap, d_kqfilter, ... and d_flag (e.g. D_MPSAFE: the methods run without the kernel lock). The minor picks the instance within the driver; its meaning is the driver's.

Majors are assigned in sys/conf/majors (device-major drm char 180 drmbase | drmkms); nodes are created by MAKEDEV (etc/MAKEDEV.tmpl) or the driver's module attaches its cdevsw at load (devsw_attach("drm", NULL, &bmajor, &drm_cdevsw, &cmajor)).

open("/dev/dri/card0") goes namei → the special-file vnode → spec_open → d_open(dev, flags, fmt, l). After that, read and ioctl on the descriptor go vnode → specfs → d_read, d_ioctl: the file is a vnode file, and every open of the node shares the driver's per-device state unless the driver keeps per-open state itself — which d_* methods have no place for.

Cloning devices

Drivers that need per-open state (DRM keeps a drm_file per open — its authentication, its GEM handles, its event queue) use the cloning pattern instead:

static int
foo_open(dev_t dev, int flags, int fmt, struct lwp *l)
{
	struct file *fp;
	int fd, error;

	if ((error = fd_allocfile(&fp, &fd)) != 0)
		return error;
	/* ... make the per-open object `priv' ... */
	return fd_clone(fp, fd, flags, &foo_fileops, priv);
}

fd_clone fills in the new file (DTYPE_MISC, foo_fileops, f_data = priv), affixes it, records the descriptor in curlwp->l_dupfd, and returns the magic error EMOVEFD. vn_open passes that up as "move descriptor l_dupfd", and open(2) (do_open) moves the file to the descriptor it returns (fd_dupopen). From then on the descriptor is not a vnode file at all: read, ioctl, poll, mmap and close go to foo_fileops with fp->f_data — the per-open object. The cdevsw only opens.

Linux

file, inode, file_operations

struct file has f_op (the file_operations), private_data (the driver's per-open object), f_inode, f_mapping (the address_space — see Memory and DMA), f_pos, f_flags (O_*), f_mode (FMODE_READ, FMODE_WRITE...). struct inode is the object — for a device node, i_rdev holds the device number and iminor(inode) its minor.

file_operations is per driver: open(inode, file), release(inode, file) (when the last reference to the open file goes), read(file, char __user *, size_t, loff_t *), write, unlocked_ioctl(file, cmd, arg) (the argument is a user pointer — the driver copies in and out itself), poll(file, poll_table *), mmap(file, vma), llseek, fop_flags (e.g. FOP_UNSIGNED_OFFSET, which DRM requires for its large fake mmap offsets).

So every Linux file is, in NetBSD terms, a cloned file: per-open state in private_data is the norm. An open method may even switch the file to other operations — replace_fops(file, new_fops) — which is how DRM routes all its minors through one stub to each driver's own operations:

open("/dev/dri/card0")
  -> chrdev DRM_MAJOR: drm_stub_open(inode, file)
       minor = drm_minor_acquire(iminor(inode))
       replace_fops(file, minor->dev->driver->fops)
       file->f_op->open(inode, file)        /* drm_open: drm_file */

Descriptors: get_unused_fd_flags(flags) reserves a number, fd_install(fd, file) publishes the file there (and is final: there is no un-install), put_unused_fd(fd) gives a reservation back; fget(fd)/fdget(fd) look one up. anon_inode_getfile() makes a file not backed by any node — dma-bufs and sync files are such files.

The compat layer: Linux files on NetBSD

struct file in Linux code is renamed struct linux_file (<linux/file_netbsd.h>), shaped as Linux's, with NetBSD fields at the end (f_bsdfile, a selinfo, locks). It is attached to a NetBSD file_t as a cloned file: f_ops = linux_fileops, f_data = the Linux file, and linux_fileops forwards — fo_read to f_op->read, fo_ioctl to f_op->unlocked_ioctl (through the ioctl window, because NetBSD has already copied the argument in), fo_poll to f_op->poll, fo_close to dropping the reference, and the last reference runs release.

Two ways in (drm2/linux/linux_file.c):

  • Linux code creating files (anon_inode_getfd, or get_unused_fd_flags + fd_install): reservation by fd_allocfile, publication by fd_affix.
  • Device nodes: register_chrdev(major, name, fops) records a Linux character device; a NetBSD cdevsw whose d_open is linux_chrdev_open(linux_major, dev, flags) makes an inode for dev (so iminor is NetBSD's minor), a Linux file with the registered operations, runs their open — which may replace_fops — and installs the file with fd_clone. A failed open does not run release, as in Linux.

DRM's whole cdevsw is now that (drm2/drm/drm_cdevsw.c): open is linux_chrdev_open(DRM_MAJOR, ...) and every other d_ method is unused, because the descriptor is a cloned Linux file. NetBSD minors already match DRM's minor indices: dri/cardN is minor N, dri/renderD(N+128) minor N+128 (MAKEDEV).

32-bit processes

A 64-bit kernel can run 32-bit programs (NetBSD's COMPAT_NETBSD32: i386 binaries on amd64, 32-bit ARM on aarch64). Their system calls mean the same, but their data does not look the same:

  • Sizes. 32-bit programs use the ILP32 model (int, long and pointers are 32 bits); 64-bit kernels use LP64 (long and pointers are 64 bits). A structure with a pointer or a long in it has a different size and layout on each side.
  • Alignment. i386 aligns 64-bit integers to 4 bytes inside structures, amd64 to 8, so even a structure of plain integers can differ (drm_ioc32.c marks such structures __packed on x86).

So every interface that passes structures must translate. NetBSD does it in sys/compat/netbsd32/: 32-bit system call entry points copy the 32-bit structures in, widen them and call the native code. For ioctl, netbsd32_ioctl() converts the commands it knows and hands the rest to the file unchanged, with the argument copied in by the size the command encodes -- which, for a 32-bit program, is the 32-bit size.

Linux puts the knowledge with the driver instead: a 32-bit process's ioctl goes to the file's compat_ioctl, which reads the 32-bit layout and widens user pointers with compat_ptr(). DRM's is drm_compat_ioctl (drm_ioc32.c): it translates the core ioctls whose layout differs and passes the rest to drm_ioctl.

The compat layer joins the two: the Linux file's fo_ioctl checks whether the calling process is 32-bit (PK_32) and calls compat_ioctl instead of unlocked_ioctl, through the same argument window as native ioctls. 32-bit graphics programs -- Wine, older games -- then work as on Linux.

Waiting for a descriptor

A compositor waits on many descriptors at once: DRM (vblank and page-flip events), input devices, client sockets, fences.

select and poll (NetBSD)

select(2)/poll(2) call each file's fo_poll(fp, events). A file that is not ready calls selrecord(curlwp, &sc->sc_selinfo) on a struct selinfo it owns, and later, when it becomes ready, selnotify(&sc->sc_selinfo, events, hint) wakes the recorded waiters, who poll again. The pattern is level-triggered and stateless: every call re-asks every file.

kqueue (NetBSD)

A kqueue keeps knotes — registrations "tell me when descriptor 7 is readable" (EVFILT_READ), "writable" (EVFILT_WRITE), or other filters (process exit, timers, file changes). The file's fo_kqfilter(fp, kn) sets kn->kn_fop to a struct filterops: f_attach, f_detach (take the knote off the object's list), f_event(kn, hint) (is the condition true?). The object keeps a list of knotes — usually its selinfo's sel_klist (selrecord_knote/selremove_knote) — and KNOTE(list, hint) (which selnotify does first) calls every knote's f_event; true activates the knote. Two rules matter:

  • KNOTE / selnotify must run under the lock that guards the knote list; filters run from there, with that lock held.
  • When the process collects events (kevent), kqueue re-checks every level-triggered knote by calling f_event(kn, 0) again, in thread context. A notification can therefore be an over-approximation — "something may have changed" — as long as the re-check is exact.

epoll (Linux)

An epoll instance registers a callback on each wait queue the file's poll method passes to poll_wait; a wakeup of that queue runs the callback, which queues the file as possibly ready; epoll_wait calls poll again to confirm. Drivers only implement poll and wake their wait queues; they know nothing of epoll.

Linux poll methods on NetBSD

That last fact is what the compat layer builds on: everything needed is in the poll method and the wait queues.

  • poll(2): fo_poll calls f_op->poll(file, &pt); its poll_wait attaches the file's selinfo to the wait queue and records the thread; a wakeup of the queue (wake_up_all) selnotifys it.
  • kqueue: attaching a knote runs poll once with a poll table marked "for kqueue", which attaches the selinfo without recording a thread; a wakeup activates the knote without calling poll — wakeups can come from interrupt context or with spin locks held (DRM sends events under its event_lock), and poll methods may take locks; kevent's re-check calls poll(file, NULL) in thread context. A per-file spin lock serializes notifications with knote attach and detach.

So Wayland compositors, which reach kqueue through epoll-shim, can wait on /dev/dri descriptors although Linux's DRM was never written for kqueue.

Try it

ls -l /dev/dri          # majors and minors
fstat -p $(pgrep Xorg)  # descriptors of a process

Read fd_clone and fd_dupopen (sys/kern/kern_descrip.c), the EMOVEFD case in vn_open (sys/kern/vfs_vnops.c) and do_open (sys/kern/vfs_syscalls.c); then linux_chrdev_open and the kqueue filter in drm2/linux/linux_file.c; then 7.3's drm_stub_open (drivers/gpu/drm/drm_drv.c) and drm_open_helper (drm_file.c).

Further reading

open(2), select(2), poll(2), kqueue(2), file(9), devsw_attach(9), select(9) (selrecord, selnotify), kfilter_register(9); sys/kern/kern_descrip.c, sys/kern/kern_event.c, sys/kern/sys_select.c, sys/miscfs/specfs/spec_vnops.c; Linux Documentation/filesystems/vfs.rst (the file_operations reference); Marshall Kirk McKusick et al., The Design and Implementation of the FreeBSD Operating System (descriptors and kqueue — NetBSD's kqueue shares the design).

Clone this wiki locally