Sysfs Device Model, MMIO Safety & /sys/class/leds Control
Bridge VFS descriptors, mmap mappings, and poll loops from GL-C01..GL-C03 into embedded Linux hardware control by inspecting the /sys kobject tree, understanding why /dev/mem MMIO pokes race kernel drivers, and driving /sys/class/leds attributes deterministically in ISO C11.
What you'll learn
- Differentiate
/sys/classASCII kobject attributes from/devcharacter-deviceioctlandmmapUAPIs. - Configure manual
/sys/class/ledscontrol by writingnonetotriggerbefore updatingbrightness. - Validate requested LED brightness against
max_brightnesswhile avoiding user-space/dev/memMMIO races.
Why User-Space Hardware Control Never Pokes Raw Registers
Welcome to Course 4 (GL-C04: Embedded Linux Peripherals, Display, Video & Audio in C), the hardware-interfacing capstone of our four-course Linux Systems Programming series. Across GL-C01 through GL-C03, you built Virtual Filesystem (VFS) descriptor pipelines, multi-threaded signal-safe daemons, mmap() shared mappings, poll()/epoll reactors, and POSIX sockets. In GL-C04, those exact user-space mechanisms drive physical embedded peripherals: status Light-Emitting Diodes (LEDs), General-Purpose Input/Output (GPIO) banks, evdev touch panels, Pulse-Width Modulation (PWM) timers, framebuffers, Universal Asynchronous Receiver/Transmitter (UART) buses, hardware watchdogs, Controller Area Network (SocketCAN) links, Advanced Linux Sound Architecture (ALSA) rings, and Video4Linux2 (V4L2) cameras.
Consider a real field failure seen when bare-metal firmware engineers port status-indicator code onto an embedded Linux gateway. Seeking direct register speed, an engineer opens /dev/mem, maps the 32-bit GPIO bank at physical address 0x0209C000, qualifies the pointer as volatile uint32_t *dr, and toggles bit 3 (*dr |= (1U << 3);) from a user-space daemon. Hours later under cellular modem load, the Ethernet PHY reset line on bit 9 of that same 32-bit GPIO port drops unexpectedly and severs network connectivity.
Why did that bare-metal idiom fail under Linux? In C11, *dr |= (1U << 3) compiles into three separate instructions: a 32-bit load (LDR), a bitwise OR (ORR), and a 32-bit store (STR). If the kernel's fec Ethernet driver updates bit 9 inside an interrupt or kernel thread between user space's LDR and STR, user space's stale STR overwrites bit 9 with its old value. Worse, qualifying a pointer volatile only forbids the C compiler from caching or eliding loads and stores; volatile emits zero CPU memory barriers (DMB/DSB), performs zero cache invalidation, and provides zero atomicity across cores or privilege rings. On Write-1-to-Clear (W1C) interrupt status registers, *status |= (1U << 3) actively clears every other pending 1 bit in the word!
For that reason, production Linux 6.12 LTS kernels enable CONFIG_STRICT_DEVMEM to block raw /dev/mem peripheral mappings and mediate hardware exclusively through two race-free User-Space API (UAPI) surfaces: ASCII sysfs attributes under /sys for low-rate configuration and state switches, and binary /dev character or network descriptors (ioctl(), mmap(), poll()) for high-rate or multi-line data streams.
note: Think of /sys as an aircraft cockpit switch panel wired into live actuator controllers: flipping a labeled switch does not store passive text on disk; closing the contact immediately runs a validation circuit and drives physical hardware state.
Where it stops working: Unlike passive copper switches, every write() to a sysfs file traps from Ring 3 into a Ring 0 kernfs store() callback that parses ASCII bytes from offset 0, checks range limits, acquires driver spinlocks, and updates memory-mapped SoC registers.
definition: Sysfs (kernfs) vs /dev UAPI Split & LED Trigger Contract: Mounted at /sys, sysfs is an in-RAM virtual filesystem backed by kernfs that projects kernel struct kobject instances as directories, struct kobj_attribute callbacks (show() and store()) as one-value-per-file ASCII attributes, and subsystem memberships as /sys/class/ symlinks. Under /sys/class/leds/<led>/, the kernel leds-gpio or leds-pwm class driver serializes indicator hardware through max_brightness (read-only integer ceiling), trigger (space-delimited kernel event sources with the active source in [brackets], detached by writing "none"), and brightness (0 .. max_brightness), eliminating /dev/mem Memory-Mapped I/O (MMIO) read-modify-write races.
- Step 1. Step 1: Kernel kobjects map to /sys directories, kobj_attributes to show()/store() files, and relationships to symlinks.
- Step 2. Step 2: /sys/class/leds/<name> symlinks point into the physical /sys/devices/platform/leds hierarchy.
- Step 3. Step 3: Each LED exposes brightness (rw), max_brightness (ro), and trigger (rw, active mode enclosed in brackets).
- Step 4. Step 4: User-space C writes 'none' to trigger first so heartbeat or mmc0 timers stop overriding brightness.
Figure 1.1a. Detach active kernel LED triggers by writing 'none' to trigger before driving brightness within 0..max_brightness.
Figure 1.1. Hardware-to-UAPI architecture of Linux kernel kernfs (/sys/class/leds), trigger detachment, and serialized GPIO/PWM access versus unsafe /dev/mem MMIO.
One Layer Down: kernfs Buffers, Trigger Timers & Access Trade-Offs
When user space calls open("/sys/class/leds/status:green/brightness", O_WRONLY | O_CLOEXEC) and write(fd, "128", 3), VFS routes the buffer into kernfs_fop_write_iter() rather than a block-device page cache. Inside Ring 0, kernfs allocates a temporary kernel buffer (up to PAGE_SIZE, 4096 B on 32-bit ARMv7 and x86_64), copies the user slice via copy_from_user(), NUL-terminates it, and invokes brightness_store() in drivers/leds/led-class.c. That callback parses the unsigned integer via kstrtoul(), clamps values exceeding led_cdev->max_brightness, acquires led_cdev->led_access mutex, and dispatches either atomic GPIO bit-set/clear registers or PWM duty updates.
Notice the exact byte-framing and timing consequences of kernfs_fop_write_iter():
- One token per
write()syscall: Everywrite()call invokesstore()independently as a complete transaction. Formatting"255"into a stack buffer withsnprintf()costs1syscall (~0.8 .. 2.5 uson Cortex-A7 / x86_64), whereas callingfputc()unbuffered3times issues"2","5", and"5", setting hardware brightness to5instead of255! - Trigger detachment rule: Reading
triggerreturns a list such asnone timer [heartbeat] mmc0. While[heartbeat]is active, a kerneltimer_listcallback overwritesbrightnessevery70 .. 1000 ms. Furthermore, indrivers/leds/led-class.c, writing"0"(LED_OFF) tobrightnessimplicitly callsled_trigger_remove(), whereas writing"128"leaves[heartbeat]armed! Always write"none"(4bytes) totriggerfirst so manual ownership is explicit.
sysfs_leds(5) GL-C04 Quick Reference sysfs_leds(5) NAME sysfs, /sys/class/leds - kernel kobject ASCII attributes for LED class devices SYNOPSIS int fd = open("/sys/class/leds/<label>/trigger", O_WRONLY | O_CLOEXEC); ssize_t write(int fd, const void *buf, size_t count); DESCRIPTION Exports struct led_classdev controls as RAM-backed kernfs files: max_brightness (0444): read-only integer ceiling (1 for GPIO, 255 for PWM). trigger (0644): space-separated triggers; [active] shown in brackets. brightness (0644): integer 0..max_brightness parsed per write() syscall. RETURN VALUE write() returns count on valid token commit, or -1 setting errno. ERRORS EINVAL Token in trigger is unregistered or brightness text is non-numeric. EBUSY Underlying hardware pin is locked or owned byleds-gpio against raw GPIO. EACCES Caller lacks write permission (configure udev group rules in production). Kernel Systems Academy Lesson 1.1 sysfs_leds(5) GL-C04 quick reference · full manual page: man 5 sysfs_leds | Hardware Access Mechanism | Typical Update Latency | Crash & Concurrency Safety | Appropriate Linux 6.12 Engineering Scope |
|---|---|---|---|
Raw /dev/mem mmap (volatile *) | ~10 .. 30 ns (user load/store) | Unsafe: RMW bank races, W1C clobber, blocked by CONFIG_STRICT_DEVMEM | Never in production daemons; debug bring-up only |
/sys/class/* (leds, pwm, backlight) | ~1.5 .. 6.0 us (open/write ASCII) | Safe: kernel driver mutex/spinlock serializes shared SoC banks | Low-rate (<= 100 Hz) human indicators, triggers, and policy attributes |
/dev/* UAPI (gpiochipN, evdev, V4L2) | ~0.4 .. 1.5 us (ioctl) or 0 copies (mmap) | Safe: descriptor-scoped ownership with automatic release on close() | Multi-pin atomic I/O, IRQ poll() streams, audio/video DMA rings |
Worked Example: Safe Trigger Detachment & Ceiling-Clamped LED Driver
Save sysfs_led_driver.c below. To verify the exact /sys/class/leds/ attribute protocol deterministically on an unprivileged build host without requiring physical board LEDs, main() provisions a replica /tmp/ksa_c04_leds/status:green/ attribute directory (max_brightness = 255, trigger = "none timer [heartbeat] mmc0\n"). On a physical target board, passing "/sys/class/leds/status:green" into parse_active_trigger(), write_attr(), and led_set_clamped() runs the identical VFS system calls with zero code changes.
learner@ksa:~/gl-c04/m01-l01$ bat -H 15 -H 45 -H 78 sysfs_led_driver.c File: sysfs_led_driver.c #define _GNU_SOURCE #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> static int write_attr(const char *dir, const char *attr, const char *val) { char path[256]; snprintf(path, sizeof(path), "%s/%s", dir, attr); int fd = open(path, O_WRONLY | O_TRUNC | O_CLOEXEC); if (fd == -1) return -1; size_t len = strlen(val); ssize_t rc = write(fd, val, len); (void)close(fd); return (rc == (ssize_t)len) ? 0 : -1; } static int read_attr(const char *dir, const char *attr, char *buf, size_t cap) { char path[256]; snprintf(path, sizeof(path), "%s/%s", dir, attr); int fd = open(path, O_RDONLY | O_CLOEXEC); if (fd == -1) return -1; ssize_t n = read(fd, buf, cap - 1U); (void)close(fd); if (n < 0) return -1; buf[n] = '\0'; while (n > 0 && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) { buf[--n] = '\0'; } return 0; } static void parse_active_trigger(const char *raw, char *out, size_t cap) { const char *l = strchr(raw, '['); const char *r = l ? strchr(l + 1, ']') : NULL; if (l && r && (size_t)(r - l - 1) < cap) { memcpy(out, l + 1, (size_t)(r - l - 1)); out[r - l - 1] = '\0'; } else { snprintf(out, cap, "%s", raw); } } static int led_set_clamped(const char *led_dir, int req_level, int max_b) { int clamped = req_level < 0 ? 0 : (req_level > max_b ? max_b : req_level); char num[16]; snprintf(num, sizeof(num), "%d", clamped); return (write_attr(led_dir, "brightness", num) == 0) ? clamped : -1; } int main(void) { const char *root = "/tmp/ksa_c04_leds"; const char *led = "/tmp/ksa_c04_leds/status:green"; (void)mkdir(root, 0700); (void)mkdir(led, 0700); char p[256]; const char *init_files[][2] = { {"max_brightness", "255\n"}, {"brightness", "0\n"}, {"trigger", "none timer [heartbeat] mmc0\n"}, }; for (size_t i = 0; i < 3U; ++i) { snprintf(p, sizeof(p), "%s/%s", led, init_files[i][0]); int fd = open(p, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); if (fd == -1) return EXIT_FAILURE; size_t n = strlen(init_files[i][1]); if (write(fd, init_files[i][1], n) != (ssize_t)n) return EXIT_FAILURE; (void)close(fd); } char trig_raw[128] = {0}, active_before[32] = {0}; char max_str[32] = {0}, cur_str[32] = {0}; if (read_attr(led, "trigger", trig_raw, sizeof(trig_raw)) != 0 || read_attr(led, "max_brightness", max_str, sizeof(max_str)) != 0) { return EXIT_FAILURE; } parse_active_trigger(trig_raw, active_before, sizeof(active_before)); int max_b = (int)strtol(max_str, NULL, 10); if (write_attr(led, "trigger", "none") != 0) return EXIT_FAILURE; int half = led_set_clamped(led, 128, max_b); if (led_set_clamped(led, 400, max_b) < 0) return EXIT_FAILURE; (void)read_attr(led, "brightness", cur_str, sizeof(cur_str)); int off = led_set_clamped(led, 0, max_b); for (size_t i = 0; i < 3U; ++i) { snprintf(p, sizeof(p), "%s/%s", led, init_files[i][0]); (void)unlink(p); } (void)rmdir(led); (void)rmdir(root); printf("prev_trigger=%s detached=none max=%d\n", active_before, max_b); printf("set_half=%d clamp_400=%s final_off=%d\n", half, cur_str, off); return EXIT_SUCCESS; }- Dispatch the full formatted ASCII token in one
write()syscall sokernfsinvokesstore()once. - Clamp requested brightness against
0 .. max_bbefore formatting so callers cannot exceed hardware limits. - Write
nonetotriggerfirst to detach[heartbeat]timers before commanding manual brightness.
Guided Practice: Keeping brightness Open with pwrite()
In write_attr() above, each brightness update calls open(), write(), and close() (3 syscalls). If a fault-blink loop updates brightness at 20 Hz, keeping a persistent int bfd = open(..., O_WRONLY | O_CLOEXEC) open cuts overhead to 1 syscall per transition, provided you write at file offset 0. Complete the faded helper below in your scratch copy:
- Cue 1 (Formatting): Format
clampedintochar num[16]withsnprintf()and capture its exact byte lengthlen. - Cue 2 (Offset-zero syscall): Call
pwrite(bfd, num, len, 0)(notwrite(), which advances the file offset on regular files and somekernfswrappers) and verifyrc == (ssize_t)len.
Independent Practice: timer Trigger Blink Offload
Extend sysfs_led_driver.c with a function int led_arm_kernel_blink(const char *led_dir, unsigned int on_ms, unsigned int off_ms) that writes "timer" to trigger, verifies that delay_on and delay_off attribute files exist (creating mock files in the host harness when "timer" is selected), and writes on_ms and off_ms as single-syscall ASCII strings so the kernel blinks the LED at 0% user-space CPU cost. Confirm clean compilation under -std=c11 -Wall -Wextra -Werror.
Compiling, Running & Tracing VFS Attribute Transactions
Compile sysfs_led_driver.c on the Linux host and inspect both stdout and the strace syscall sequence. Notice the host-versus-target distinction: on this host harness, O_TRUNC truncates regular /tmp files, whereas on target /sys/class/leds/<label>/ kernfs nodes, O_WRONLY | O_CLOEXEC (without O_CREAT) invokes led_trigger_write() and brightness_store() directly in RAM.
learner@ksa:~/gl-c04/m01-l01gcc -std=c11 -Wall -Wextra -Werror -fdiagnostics-color=always sysfs_led_driver.c -o sysfs_led_driverlearner@ksa:~/gl-c04/m01-l01./sysfs_led_driverprev_trigger=heartbeat detached=none max=255set_half=128 clamp_400=255 final_off=0learner@ksa:~/gl-c04/m01-l01echo $?0learner@ksa:~/gl-c04/m01-l01ls -A --color=alwayssysfs_led_driversysfs_led_driver.clearner@ksa:~/gl-c04/m01-l01learner@ksa:~/gl-c04/m01-l01strace -s 32 -e trace=openat,read,write,close \./sysfs_led_driveropenat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3close(3) = 0openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\220\243\2\0\0\0\0\0"..., 832) = 832close(3) = 0openat(AT_FDCWD, "/tmp/ksa_c04_leds/status:green/max_brightness", O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0600) = 3write(3, "255\n", 4) = 4close(3) = 0openat(AT_FDCWD, "/tmp/ksa_c04_leds/status:green/brightness", O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0600) = 3write(3, "0\n", 2) = 2close(3) = 0openat(AT_FDCWD, "/tmp/ksa_c04_leds/status:green/trigger", O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0600) = 3write(3, "none timer [heartbeat] mmc0\n", 28) = 28close(3) = 0openat(AT_FDCWD, "/tmp/ksa_c04_leds/status:green/trigger", O_RDONLY|O_CLOEXEC) = 3read(3, "none timer [heartbeat] mmc0\n", 127) = 28close(3) = 0openat(AT_FDCWD, "/tmp/ksa_c04_leds/status:green/max_brightness", O_RDONLY|O_CLOEXEC) = 3read(3, "255\n", 31) = 4close(3) = 0openat(AT_FDCWD, "/tmp/ksa_c04_leds/status:green/trigger", O_WRONLY|O_TRUNC|O_CLOEXEC) = 3write(3, "none", 4) = 4close(3) = 0openat(AT_FDCWD, "/tmp/ksa_c04_leds/status:green/brightness", O_WRONLY|O_TRUNC|O_CLOEXEC) = 3write(3, "128", 3) = 3close(3) = 0openat(AT_FDCWD, "/tmp/ksa_c04_leds/status:green/brightness", O_WRONLY|O_TRUNC|O_CLOEXEC) = 3write(3, "255", 3) = 3close(3) = 0openat(AT_FDCWD, "/tmp/ksa_c04_leds/status:green/brightness", O_RDONLY|O_CLOEXEC) = 3read(3, "255", 31) = 3close(3) = 0openat(AT_FDCWD, "/tmp/ksa_c04_leds/status:green/brightness", O_WRONLY|O_TRUNC|O_CLOEXEC) = 3write(3, "0", 1) = 1close(3) = 0write(1, "prev_trigger=heartbeat detached="..., 84) = 84+++ exited with 0 +++Tracing Exclusive Pin Ownership & Single-Syscall Atomicity
Examine the strace log line by line: read(3, "none timer [heartbeat] mmc0\n", 127) retrieved the active trigger in one read, write(3, "none", 4) detached the kernel timer in a single 4-byte syscall, and write(3, "255", 3) committed the clamped ceiling (400 -> 255) without splitting digits across multiple store() invocations. Every openat() also carried O_CLOEXEC, guaranteeing that if a sibling worker thread calls fork() and execve(), child processes never inherit write handles to hardware indicators.
Equally important on target hardware, while leds-gpio is bound to an LED node in Device Tree, the kernel GPIO subsystem marks that pin claimed ([status:green] in gpioinfo). Any attempt to request that same pin through /dev/gpiochip0 returns -EBUSY so two subsystems cannot fight over one physical pad.
Production Pitfalls & Diagnostic Verification
Sysfs works cleanly for low-frequency human indicators, yet its open/write ASCII path incurs ~2..6 us per update and cannot toggle two pins in one instruction cycle. Before moving to multi-line GPIO character descriptors, guard against two classic sysfs failures.
warning: Symptom: Writing "1" to /sys/class/leds/status/brightness illuminates the LED briefly before it resumes double-blinking on its own. Root Cause: An autonomous kernel trigger ([heartbeat] or [mmc0]) remains attached and keeps invoking led_set_brightness() from a Ring 0 timer. Fix: Always write "none" (write(tfd, "none", 4)) to trigger before driving brightness from user space.
warning: Symptom: An engineer maps a GPIO bank through /dev/mem using volatile uint32_t *reg and runs *reg |= (1U << 3), intermittently dropping sibling output pins controlled by kernel drivers. Root Cause: C volatile only prevents compiler load/store elision without providing CPU memory barriers or atomic read-modify-write safety across cores and interrupt handlers. Fix: Keep CONFIG_STRICT_DEVMEM enabled and control hardware exclusively through kernel-serialized /sys/class attributes or /dev character UAPIs.
Diagnostic Checks & Spaced Retrieval
Verify your command of these UAPI invariants, bitmask contracts, and failure modes below.
Key takeaways
GL-C04applies POSIX descriptors,ioctl(),mmap(), andpoll()fromGL-C01..GL-C03to embedded Linux LEDs, GPIOs, input devices, displays, buses, audio, and cameras.- The
/sys(sysfs) virtual filesystem maps kernelstruct kobjectdirectories,show()/store()ASCII attributes, and class-to-device symlinks in RAM. /sys/class/leds/<led>/controls indicator hardware viamax_brightness(ceiling),trigger(bracketed active kernel source), andbrightness(0..max_brightness); always detach autonomous triggers with a singlewrite(tfd, "none", 4)before issuing single-syscall ASCII writes tobrightness.- C
volatileonly prevents compiler load/store elision on MMIO or signal flags without providing CPU memory barriers or atomic read-modify-write safety; LinuxCONFIG_STRICT_DEVMEMblocks/dev/memraces in favor of kernelreadl/writeldrivers and sysfs//devUAPIs. - What happens when your hardware pin is an unclaimed relay bank, modem reset line, or parallel strobe that has no
/sys/class/ledsdriver and requires atomic multi-pin updates? Next, we move from ASCII sysfs files into the Linux 6.12/dev/gpiochipNv2 character-device ioctl ABI.