Repository navigation
Console and display
What puts text on a NetBSD screen, from a write(2) on /dev/ttyE0
or a kernel printf down to pixels, and how aiBSD puts Linux DRM
drivers underneath without changing what users see.
tty (ttyE0..) kernel printf (cnputc)
\ /
wsdisplay -- screens, switching, ioctls (wsconsctl)
|
emulation (wsemul_vt100) -- escape sequences -> drawing calls
|
vcons -- virtual screens: a text buffer per screen
|
rasops -- draws characters into a framebuffer (fonts, colours)
|
genfb / drmfb / a hardware driver -- the framebuffer
-
wsdisplay (
sys/dev/wscons/wsdisplay.c) owns the screens (struct wsscreen), each with a tty, an emulation and a screen type (struct wsscreen_descr:nrows,ncols, capabilities). It switches screens, routes keyboard input, and implements the ioctlswsconsctl(8)uses. -
The emulation (
wsemul_vt100.c) turns a byte stream into calls of the display'swsdisplay_emulops:putchar,copyrows,eraserows,cursor... -
vcons (
wsdisplay_vcons.c) implements those operations for drivers with a framebuffer. Eachstruct vcons_screenkeeps a character buffer and an attribute buffer (scr_chars,scr_attrs) next to itsrasops_info(scr_ri), so a screen that isn't visible still has its contents and can be redrawn when switched to. The driver suppliesinit_screen(struct vcons_data), which sets up a screen's rasops for the framebuffer's geometry. -
rasops (
sys/dev/rasops) draws glyphs and fills into memory of a given depth and stride. -
genfb (
sys/dev/wsfb/genfb.c) is the generic framebuffer driver: it needs only device properties (width,height,depth,linebytes,address, ...), usually a framebuffer the firmware set up (EFI GOP, VESA). Withenable_shadowfb, rasops draws into system memory and genfb copies to the framebuffer, which matters when the framebuffer is slow to read (VRAM over PCI). A damage hook tells the owner what changed, for framebuffers that must be flushed.
A terminal's size lives in its tty (struct tty, t_winsize), read
with TIOCGWINSZ (stty size). When it changes, the foreground
process group gets SIGWINCH and full-screen programs redraw. A
terminal emulator does this with TIOCSWINSZ; for a ttyE screen,
wsdisplay does it itself whenever a screen's rows or columns change:
wsdisplay_screen_resized() calls the emulation's resize, sets
t_winsize and sends SIGWINCH (ttysig(tp, TTYSIG_PG1, SIGWINCH)).
Loading a different font changes rows and columns the same way.
When the framebuffer itself changes (a new mode, a resized VM window), every screen must re-lay out on it. The difficulty is concurrency: output reaches the screens from two directions that don't sleep and don't wait for each other.
-
tty output runs from
wsdisplaystart(), which marks the ttyTS_BUSYwhile it draws. -
Kernel console output (
cnputc→wsdisplay_cnputc) can come from any context, interrupts included, and must never block.
wsdisplay_resize(dev, fn, arg) makes a window in which neither draws:
- For each screen's tty, wait until it isn't
TS_BUSYand takeTS_BUSYitself, so the tty layer queues output instead of starting it. - Hold the console: set
wsdisplay_cn_held, then wait untilwsdisplay_cn_inflight(a countercnputcincrements around its drawing) drops to zero. Console characters arriving meanwhile are dropped from the screen; they are still in the message buffer (dmesg). - Run
fn(arg): the driver switches to the new framebuffer, andvcons_resize()re-initializes each screen withinit_screen, updates the screen type's rows and columns, and moves the text that still fits into new buffers. - For each screen,
wsdisplay_screen_resized(): emulation, winsize,SIGWINCH. - Release the console and the ttys and restart output.
genfb_retarget(sc, address, width, height, stride) is the genfb
entry point: it allocates a new shadow if one is used, runs
wsdisplay_resize with the swap, and frees the old shadow. Requires
a damage hook (the owner must learn about the new contents).
A DRM driver owns the display hardware; the console must draw through
it. drmfb (drm2/drm/drmfb.c) is a genfb attached under the DRM
driver's device, fed through attach arguments (struct drmfb_attach_args): framebuffer address, size, stride, depth, whether
it is I/O memory, and callbacks (struct drmfb_ops: damage, blank,
restore). Two sources can feed it, chosen with the drmkms property
console=:
console= |
Source | Mode | Follows output changes |
|---|---|---|---|
fbdev (default) |
Linux's fbdev emulation (DRM's "fbdev" client); its shadow buffer | the connector's preferred | no (as Linux's fbcon) |
wscons |
aiBSD's console client (drm2/drm/drm_console.c), a DRM client in DRM's "log" slot |
video=, else the firmware's (efiboot gop), else preferred |
with hw.drm2.console_follow=1; hw.drm2.video writes always |
none |
no in-kernel client | -- | -- |
The console client. DRM calls a client's hotplug function when
it registers and on every output change. The client probes
(drm_client_modeset_probe), sizes a dumb buffer for the largest
chosen mode and the console for the smallest, commits it to the
outputs, and attaches drmfb to it, or, on a later size change,
retargets drmfb to a new buffer (drmfb_retarget → genfb_retarget).
What the console draws reaches the display from a work item that
flushes the damaged rectangle (drm_client_buffer_flush): the console
draws in contexts that can't sleep, flushing can.
Masters. A program that becomes DRM master (X, a compositor, a
test tool) owns the display; the client's commits fail with -EBUSY
meanwhile, and it keeps drawing into its buffer. When the master
closes, DRM calls the client's restore function, which commits again.
A resize while a master holds the display happens in the background
and shows on restore.
The firmware's mode. On x86 the console PCI function carries the
firmware framebuffer's width and height as device properties, and
the takeover from genfb keeps them with is_console. The client asks
for that mode by writing it into the connector's cmdline_mode, the
field DRM fills from video=, when no video= names the connector and
the connector offers the mode.
The console must work long before any driver for the display hardware can, and it must keep working while a GPU driver takes the hardware over. On x86 that happens in four stages.
1. The early console. The boot loader passes the firmware's
framebuffer (EFI GOP, or a VESA mode) to the kernel in its bootinfo
(BTINFO_FRAMEBUFFER: address, size, stride, depth). consinit()
(sys/arch/x86/x86/consinit.c) calls x86_genfb_cnattach()
(genfb_machdep.c), which maps that memory, sets up rasops on it and
registers a wsdisplay console screen (wsdisplay_preattach), with no
device attached yet: kernel messages appear from here on. Mapping
needs UVM, so the first calls return "defer" and consinit() is
retried later in boot. genfb_cnattach() then records that genfb
owns the console.
2. Which driver attaches to the display's PCI function. During
autoconfiguration, x86's device_pci_register() gives the PCI display
function behind the console framebuffer device properties: the
framebuffer's geometry and is_console. Several drivers can match
that function, and the highest match value wins:
| Driver | Match value |
|---|---|
| vga(4) | 1 |
genfb(4) (genfb_pci.c) |
1, or 5 when genfb holds the console (to beat vga) |
| a DRM driver (amdgpu, radeon, nouveau, ...) | 7, if its Linux driver's ID table has the device |
In a kernel with the DRM driver built in, the DRM driver attaches and
genfb never does: the early console keeps drawing into the firmware's
framebuffer until the driver stops it. A DRM driver loaded later as a
module finds genfb attached and the function taken;
linux_pci_evict_firmware_fb() detaches those genfbs first (forcibly,
so a genfb carrying the console lets it go), and the driver attaches in
the rescan. Drivers that take functions genfb would otherwise claim
can also exclude them from genfb by vendor and product
(pci_genfb_exclude()).
3. Probing after the root file system. The DRM driver's attach
(linux_pci_driver_attach()) only builds the Linux pci_dev; the
Linux driver's probe runs from config_mountroot(), once the root
file system is mounted, because probe loads firmware from
/libdata/firmware (Firmware). Until then the early
console still shows the boot messages.
4. The takeover. Early in probe the Linux driver calls
aperture_remove_conflicting_pci_devices() (Linux: remove efifb or
simpledrm, which use the same memory). Here
(drm2/linux/linux_aperture.c) it quiesces the early console if the
device has is_console (wsdisplay_cnquiesce(): nothing draws into
the firmware framebuffer any more) and detaches any genfb whose
framebuffer lies in the device's memory BARs. The driver then
programs the display; its fbdev or console client registers a
framebuffer, and the drmfb attached to it, seeing is_console,
becomes the console (above). Messages printed in between are kept in
the message buffer and are not lost, only not shown.
When probe fails. Once the driver has reprogrammed the display
engine, the firmware's framebuffer may no longer be scanned out, or
its memory may have been reused. The glue records the failed function
so that it no longer matches (linux_pci_driver_match()), detaches the
driver and rescans: genfb attaches again with is_console and takes
the console back (linux_pci_give_back). That restores the console
only as far as the firmware framebuffer survived; if the driver changed
the mode or the scan-out address, the screen stays dark although the
console is "back". Hence the rule before trying a GPU driver on real
hardware: have a way in that does not depend on the screen (SSH, a
serial console, a second GPU). The sysctl hw.linux_pci.fail_next_probe
makes the next probe fail, to test this path.
init(8) starts getty(8) on each terminal listed in /etc/ttys, with a
gettytab(5) entry describing the line. getty prints the banner and
the login: prompt, reads the name and runs login(1).
The if= capability names an issue file that getty prints before
the first prompt (only the first: not again after a failed login), the
place for a site message or the system's name. Two rules for writing
one:
- getty passes each line through
putf(), which expands%escapes as in theim=banner (%hhost name,%tterminal,%ddate,%s,%m,%r,%vthe uname fields), so a literal%must be written%%. - Before the name is read, getty sets the terminal modes itself
(
setflags(0)), and unless the entry has thenlcapability, output processing does not turn a newline into carriage return and newline (ONLCR); getty sets that only once the name shows how the terminal ends lines. getty's own messages write\r\nexplicitly. So lines in an issue file must end in CR LF, or each line starts where the previous one ended.
When a machine hangs hard or resets itself, the useful text is the last
few lines the kernel printed, and the usual ways of keeping them fail
exactly then. A screen is gone if the failing driver owned it. Copying
dmesg to a file server from user space needs the scheduler, the
network stack, NFS and a running process: it stops at the first hang,
and whatever was printed after the last copy is lost. A serial port
works but needs a cable and a port the machine may not have.
netcons (sys/net/netcons.c, options NETCONS or NETCONS_NOAUTH)
sends console output over Ethernet as it is printed, from the
printing context, without the network stack:
-
The tap.
cnputc(sys/dev/cons.c) hands every console character tocn_tapas well as to the console device. netcons appends it to a 64 KiB ring under a spin lock at high IPL; a newline triggers a flush. -
The frame. The flush builds a complete Ethernet + IPv4 + UDP
frame itself and gives it straight to the driver's
nco_sendhook: no mbufs, no routing, no ARP table, no soft interrupts. Lines go from port 6665 to port 6666, by default as broadcasts with source0.0.0.0and destination255.255.255.255(as DHCP sends before it has an address), so the kernel needs no IP address of its own. Configured with one host, the IP header stays the same and only the Ethernet destination becomes that host's address, given (mac=) or learned with an ARP request netcons sends itself; a receiver would drop unicast IP from source 0.0.0.0. -
The datagram. Each one starts with a line
netcons <mac> <seq> <nonce>: the sender's address, a sequence number counting datagrams (a gap means lost datagrams) and a nonce new each boot (a change means a reboot). The text after it is whole lines where possible. Any program receiving UDP on port 6666 reads it. -
The start of the boot. When the driver registers
(
netcons_register), the ring is seeded with the kernel message buffer, so the receiver sees the boot from its first line. Text waits in the ring until the interface is running and has a link, and a callout retries every half second; on a machine that boots over the network the kernel brings the interface up to mount its root, so output starts before init does. If the ring overruns, the oldest text is lost, not the newest. -
In ddb and panic.
netcons_forcing()is true in ddb and after a panic, when the other CPUs are stopped: the driver then sends even if its lock is held, and if the transmit ring is full netcons polls it (nco_poll) until there is room.
What a driver provides (struct netcons_ops in
net/netcons.h): nco_send, which queues one frame from buffers of
its own (rge(4) keeps eight preallocated, DMA-loaded 2 KiB buffers
beside its mbuf transmit path), and nco_poll, which processes the
receive and transmit rings without interrupts. Both may be called in
any context, at any IPL, possibly from inside the driver's own locked
code on the same CPU, so they must never sleep or spin on a lock:
they mutex_tryenter and return EBUSY when the driver is busy, and
netcons tries again later. The ring indices they share with the
normal transmit path are therefore taken under the driver's lock on
both paths. The driver also offers every received frame to
netcons_input before the stack sees it and calls netcons_intr at
the end of its interrupt handler, with no locks held.
Commands. netcons accepts commands in UDP datagrams to port 6666,
handled in the driver's interrupt handler, so they work while soft
interrupts, the network stack or the scheduler are stuck: ping,
reset (reset at once, no shutdown), ddb (enter the kernel
debugger) and input <text> (console input, which ddb reads through
cn_tapgetc). A command datagram is
netcons-cmd <nonce> <seq> <signature>
<command>
and is accepted only if the nonce is this boot's (taken from the
output), the sequence number is larger than any accepted before
(no replay), and the signature is an Ed25519 signature of
<nonce> <seq> <command> by the configured key, checked with
libsodium's verifier built into the kernel (libsodium_sign).
Anything that does not check out is dropped without a reply. Without
a key, commands are refused. NETCONS_NOAUTH builds netcons without
the crypto and accepts unsigned commands, and so does the noauth
word: then anyone on the segment can reset the machine, and the kernel
says so when it starts. reset and ddb are only noted in
netcons_input (called with the driver's locks held) and acted on in
netcons_intr.
Configuration comes from the boot loader on x86: a netcons
command or boot.cfg(5) line whose words go to the kernel unchanged in
a BTINFO_NETCONS bootinfo record: off, broadcast, a host address,
mac=xx:xx:xx:xx:xx:xx, key= (64 hex digits, or the base64 part of
an OpenSSH ssh-ed25519 public key) and noauth. The first
interface whose driver registers carries the console.
Everything above draws with the CPU into a buffer the display scans out. The display engine itself does more, in hardware, every frame, and KMS exposes it through objects and properties.
Planes. A CRTC composes the image it sends from planes, each a
framebuffer placed on the screen. Every plane has a type property:
primary (the main image), overlay, or cursor. A client sees
overlay and cursor planes only after setting the client capability
DRM_CLIENT_CAP_UNIVERSAL_PLANES; GETPLANE lists which CRTCs a plane
can serve (possible_crtcs, a bit per CRTC index) and which pixel
formats it takes. SETPLANE places a framebuffer: a destination
rectangle in screen pixels and a source rectangle in 16.16 fixed
point. When the two differ in size the plane scales; a plane that
cannot scale refuses the call, so a client tries and falls back. The
cursor has its own old ioctl (MODE_CURSOR, with the size limits in
DRM_CAP_CURSOR_WIDTH/HEIGHT); drivers implement it on their cursor
plane. A cursor may hang over the screen's edges; other planes are
clipped or refused.
Blending. Planes are stacked (zpos, where the driver exposes
it) and blended per pixel. A plane with an alpha channel (ARGB8888)
blends by it, by default as premultiplied alpha (pixel blend mode):
the colour channels must already be multiplied by alpha, so a half
transparent white is 0x80808080, not 0x80ffffff. The plane's
alpha property (0 to 0xffff) scales the whole plane on top of that.
Colour. After blending, each CRTC passes pixels through a fixed
pipeline: DEGAMMA_LUT (to linear light), CTM (a 3x3 colour matrix),
GAMMA_LUT (back to the display's encoding). Each stage is a
property whose value is a blob ID: a client creates the blob
(CREATEPROPBLOB) with the table, sets the property, and 0 means the
stage is bypassed. LUT entries are 16 bits per channel
(struct drm_color_lut), as many as GAMMA_LUT_SIZE says. The matrix
entries are S31.32 sign-magnitude, not two's complement: bit 63 is
the sign and the rest the magnitude, so −0.5 is
0x8000000080000000. Drivers without the atomic properties still
offer the legacy ramp (GETGAMMA/SETGAMMA, sized by the CRTC's
gamma_size).
Pacing. WAIT_VBLANK blocks until a CRTC's next vertical blank.
It predates CRTC IDs: it names the CRTC by index, encoded in the
request type's high bits (_DRM_VBLANK_HIGH_CRTC_SHIFT). Moving a
plane or the cursor once per blank gives one change per frame.
Writing the buffer. A dumb buffer in VRAM is mapped write-combined (see memory types): writes are gathered into bursts, so copying whole rows is fast, while scattered small writes and any read run at uncached speed. Drawing text or blending directly in such a buffer is slow enough to miss frames; compose in ordinary memory and copy rows out, and keep a copy of the image instead of reading the buffer back.
What none of this does is draw: lines, fills and copies by the GPU's own engines are programmed by a userland driver (Mesa) through vendor-specific ioctls.
-
stty sizeon a ttyE screen;sysctl -w hw.drm2.video=1280x800withconsole=wscons, thenstty sizeagain;lessredraws. -
drmctl list -vshows the planes, CRTCs and their properties;drmctl -t 5 color gamma=2.2,drmctl -t 10 overlayanddrmctl -t 10 cursorexercise the colour pipeline, an overlay plane and the cursor (seedrmctl(8)). -
wsconsctl -dfor the display's state;wsfontloadandwsconsctl -dw font=...change rows and columns through the same resize path.
sys/dev/wscons/wsdisplay.c (wsdisplay_resize,
wsdisplay_screen_resized, wsdisplay_cnputc, wsdisplaystart),
sys/dev/wscons/wsdisplay_vcons.c (vcons_resize, vcons_load_font),
sys/dev/wsfb/genfb.c (genfb_retarget), sys/dev/rasops/,
drm2/drm/drmfb.c, drm2/drm/drm_console.c,
drm2/drm/drm_fb_netbsd.c, usr.sbin/drmctl/ (planes.c,
color.c); drm_mode.h and drm.h in drm2/dist/include/uapi/drm; wscons(4), wsdisplay(4), genfb(4),
wsconsctl(8), tty(4).
aiBSD system development guide
Tutorial
II — Building
III — The kernel
- Kernel basics
- Booting and kernel modules
- The boot loader
- 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