GPIO Character UAPI: Migrating from Sysfs to /dev/gpiochipN v2

Replace deprecated /sys/class/gpio global pin files with the Linux 6.12 /dev/gpiochipN v2 character-device ABI (<linux/gpio.h>), configuring glitch-free active-low outputs, atomic 64-line bitmask updates, and crash-safe descriptor lifetimes in ISO C11.

20 minfree previewLinux 6.12C11glibc 2.39→ module 1 lab
What you'll learn
  • Contrast deprecated global /sys/class/gpio exports against descriptor-scoped /dev/gpiochipN v2 line requests.
  • Configure glitch-free multi-line outputs and ACTIVE_LOW semantics via GPIO_V2_GET_LINE_IOCTL.
  • Implement atomic multi-pin updates via struct gpio_v2_line_values mask/bits shifts instead of C bit-fields.

Why Global /sys/class/gpio Numbers Break Production Systems

Suppose an industrial controller toggles a cellular modem's PWRKEY and active-low RESET_N pins on GPIO bank 4 while reading two hardware revision straps. Using legacy shell-era code (echo 112 > /sys/class/gpio/export), the daemon computes global = chip_base + offset, exports gpio112 and gpio116, writes "out" to direction, and writes "1" to value. Six months later, a Linux 6.12 LTS kernel upgrade switches dynamic gpiochip probe registration order: chip_base shifts from 96 to 512, gpio112 now maps to an unrelated stepper-enable pin, writing "out" briefly glitches RESET_N low for 18 us before "1" arrives, and a SIGKILL crash leaves the pins permanently locked (EBUSY) on restart!

Legacy /sys/class/gpio (CONFIG_GPIO_SYSFS, deprecated upstream and scheduled for removal) suffers four structural flaws: unstable global integer numbering (base + offset), leaked exports on process termination, non-atomic multi-file direction/value transitions (direction then value), and inability to toggle multiple pins in one atomic transaction.

On Linux 6.12 LTS, user space drives unclaimed General-Purpose Input/Output (GPIO) lines through the /dev/gpiochipN character-device v2 UAPI defined in <linux/gpio.h>. Instead of global numbers, you open /dev/gpiochip0, populate struct gpio_v2_line_request with 1 to 64 bank-local offsets[], a diagnostic consumer string, direction/polarity flags, and initial output values, and issue ioctl(cfd, GPIO_V2_GET_LINE_IOCTL, &req). The kernel claims all requested pins atomically and returns an isolated anonymous descriptor req.fd that releases every claimed line automatically when closed or when the owning process crashes.

note: Legacy /sys/class/gpio is like signing out lab instruments on a wall whiteboard where a sudden fire-drill exit leaves gear marked busy indefinitely; /dev/gpiochipN v2 issues a spring-loaded tether tied to a file descriptor that snaps cleanly free the instant your process exits.

Where it stops working: Unlike a single-user tether, GPIO_V2_GET_LINE_IOCTL creates an anonymous kernel struct file whose claim persists across fork() duplicates unless opened or duplicated with close-on-exec semantics until the final descriptor reference closes.

definition: & Explicit Bitmask ABI: Introduced in <linux/gpio.h> (GPIO_V2_GET_LINE_IOCTL, GPIO_V2_LINE_SET_VALUES_IOCTL, GPIO_V2_LINE_GET_VALUES_IOCTL), the v2 UAPI binds 1 .. GPIO_V2_LINES_MAX (64) bank-local line offsets to a VFS descriptor req.fd. It encodes line selection and logic states in fixed-width __aligned_u64 .mask and .bits words indexed by 0 .. req.num_lines - 1 (with kernel polarity inversion via GPIO_V2_LINE_FLAG_ACTIVE_LOW), avoiding implementation-defined C11 struct bit-fields and non-atomic multi-file sysfs races.

ast_m01_l02.svg — Use /dev/gpiochipN GPIO_V2_GET_LINE_IOCTL for all new…step 1/4
  1. Step 1. Step 1: Legacy /sys/class/gpio exports global pin IDs across multiple ASCII files with no crash cleanup.
  2. Step 2. Step 2: Hardware GPIO banks expose 0..31 local offsets whose pad muxing is governed by Device Tree pinctrl.
  3. Step 3. Step 3: GPIO_V2_GET_LINE_IOCTL claims 1..64 offsets atomically with consumer tag and direction flags, returning req.fd.
  4. Step 4. Step 4: GPIO_V2_LINE_SET_VALUES_IOCTL updates selected mask bits atomically while close(req.fd) frees the lines.

Figure 1.2a. Use /dev/gpiochipN GPIO_V2_GET_LINE_IOCTL for all new Linux 6.12 C code, and understand legacy /sys/class/gpio only to maintain or migrate older BSP scripts.

fig_m01_l02_arch.svg — Linux 6.12 /dev/gpiochipN v2 line-descriptor…

Figure 1.2. Linux 6.12 /dev/gpiochipN v2 line-descriptor architecture, slot-indexed bitmask mapping, and glitch-free atomic bank writes.

One Layer Down: gpiolib Descriptors, Request-Slot Indexing & Bitmask Math

Inside drivers/gpio/gpiolib-cdev.c, GPIO_V2_GET_LINE_IOCTL translates each requested bank offset req.offsets[i] into a kernel struct gpio_desc *, checks that no Device Tree consumer or other req.fd holds FLAG_REQUESTED (returning -EBUSY otherwise), records req.consumer (32-byte ASCII tag visible in /sys/kernel/debug/gpio and gpioinfo), and calls anon_inode_getfd("gpio-line", &line_fileops, line, O_RDONLY | O_CLOEXEC). Once ioctl() returns 0, you can close(cfd) immediately because req.fd owns the struct line allocation until line_release() runs on final descriptor close.

Pay close attention to two bit-level rules in <linux/gpio.h>:

  1. Slot index vs bank offset (0 .. req.num_lines - 1): In struct gpio_v2_line_values { __aligned_u64 bits; __aligned_u64 mask; };, bit position i (1ULL << i) addresses req.offsets[i], NOT the raw hardware offset! If req.offsets[0] = 3 and req.offsets[1] = 7 (num_lines = 2), setting mask = (1ULL << 1) and bits = (1ULL << 1) updates pin 7 while leaving pin 3 untouched in a single gpio_chip->set_multiple() call.
  2. Glitch-free startup & explicit shifts vs C struct bit-fields: Attaching GPIO_V2_LINE_ATTR_ID_OUTPUT_VALUES inside req.config.attrs[] latches the output register before switching pad direction to output, eliminating 10 .. 50 us reset glitches. Notice why <linux/gpio.h> uses __aligned_u64 masks and shifts (1ULL << n, (val & ~mask) | ((field << shift) & mask)) rather than C struct bit-fields (unsigned pin0:1;): under ISO C11 section 6.7.2.1, bit-field bit ordering (MSB-first vs LSB-first), straddling, and container width are implementation-defined, and bit-field assignments compile into non-atomic read-modify-writes. Always shift unsigned 1ULL (1 << 31 on 32-bit signed int is C11 Undefined Behavior!).
gpio_v2_ioctl(2) at a glance — GL-C04
gpio_v2_ioctl(2)            GL-C04 Quick Reference            gpio_v2_ioctl(2) NAME       GPIO_V2_GET_LINE_IOCTL, GPIO_V2_LINE_SET_VALUES_IOCTL - Linux 6.12 GPIO       v2 UAPI SYNOPSIS       #include <linux/gpio.h>       #include <sys/ioctl.h>       int ioctl(int chip_fd, GPIO_V2_GET_LINE_IOCTL, struct gpio_v2_line_request *req);       int ioctl(int line_fd, GPIO_V2_LINE_SET_VALUES_IOCTL, struct gpio_v2_line_values *v); DESCRIPTION       Claims 1..64 bank-local offsets[] on /dev/gpiochipN with consumer tag,       direction (GPIO_V2_LINE_FLAG_OUTPUT / INPUT), polarity       (GPIO_V2_LINE_FLAG_ACTIVE_LOW), and initial       GPIO_V2_LINE_ATTR_ID_OUTPUT_VALUES, returning isolated descriptor       req->fd. SET_VALUES updates only slot indices where v->mask & (1ULL <<       idx) is nonzero. RETURN VALUE       Returns 0 on success (populating req->fd >= 0 on GET_LINE), or -1       setting errno. ERRORS       EBUSY  One or more requested offsets[] are already owned by kernel or              user space.        EINVAL num_lines is 0 or > 64, duplicate offsets[], or invalid flag              combination.        ENOTTY SET_VALUES_IOCTL was mistakenly called on chip_fd instead of              req->fd. Kernel Systems Academy               Lesson 1.2               gpio_v2_ioctl(2) GL-C04 quick reference · full manual page: man 2 gpio_v2_ioctl 
DimensionDeprecated /sys/class/gpioLinux 6.12 /dev/gpiochipN v2 (<linux/gpio.h>)
Addressing unitUnstable global integer chip_base + offsetStable (gpiochipN, bank_offset 0 .. lines-1)
Syscalls for 2-pin update2 separate write() calls (~4 .. 10 us inter-pin skew)1 GPIO_V2_LINE_SET_VALUES_IOCTL (0 ns bank-register skew)
Output startup glitchdirection="out" before value="1" glitches 0V (unless "high")Glitch-free atomic GPIO_V2_LINE_ATTR_ID_OUTPUT_VALUES
Process crash (SIGKILL)Leaks exported /sys/class/gpio/gpioN foreverVFS closes req.fd -> line_release() frees pins automatically
AuditabilityAnonymous; cannot see owning PID/daemonreq.consumer string reported by gpioinfo and debugfs

Worked Example: Atomic Multi-Line & Active-Low GPIO v2 Controller

Save gpio_v2_controller.c below. Compiled directly against the kernel's <linux/gpio.h> UAPI structs, it builds a 2-line request (offsets[0] = 3 active-high PWR_EN, offsets[1] = 7 GPIO_V2_LINE_FLAG_ACTIVE_LOW RESET_N) with glitch-free GPIO_V2_LINE_ATTR_ID_OUTPUT_VALUES (0x3ULL, asserting both logically at request time), then executes selective bitmask updates (mask = 1ULL << 0) against a deterministic in-process GPIO bank verifier.

learner@ksa: ~/gl-c04/m01-l02
learner@ksa:~/gl-c04/m01-l02$ bat -H 20 -H 56 -H 70 gpio_v2_controller.c File: gpio_v2_controller.c    #define _GNU_SOURCE    #include <linux/gpio.h>    #include <stdint.h>    #include <stdio.h>    #include <stdlib.h>    #include <string.h>        struct sim_gpio_bank {        uint32_t phys_levels;        uint32_t claimed_mask;        struct gpio_v2_line_request active_req;    };        static uint32_t apply_v2_values(struct sim_gpio_bank *bank,                                    const struct gpio_v2_line_values *v) {        const struct gpio_v2_line_request *r = &bank->active_req;        uint64_t active_low_idx = 0ULL;        for (uint32_t a = 0; a < r->config.num_attrs; ++a) {            if (r->config.attrs[a].attr.id == GPIO_V2_LINE_ATTR_ID_FLAGS &&              (r->config.attrs[a].attr.flags & GPIO_V2_LINE_FLAG_ACTIVE_LOW)) {                active_low_idx |= r->config.attrs[a].mask;            }        }        for (uint32_t i = 0; i < r->num_lines; ++i) {            if (!(v->mask & (1ULL << i))) continue;            uint32_t pin = r->offsets[i];            int logical = (v->bits & (1ULL << i)) ? 1 : 0;            int phys = (active_low_idx & (1ULL << i)) ? !logical : logical;            if (phys) bank->phys_levels |= (1U << pin);            else bank->phys_levels &= ~(1U << pin);        }        return bank->phys_levels;    }        int main(void) {        int legacy_base = 96, legacy_offset = 16;        int legacy_global = legacy_base + legacy_offset;            struct sim_gpio_bank bank;        memset(&bank, 0, sizeof(bank));        bank.phys_levels = (1U << 7);            struct gpio_v2_line_request req;        memset(&req, 0, sizeof(req));        req.offsets[0] = 3U;        req.offsets[1] = 7U;        req.num_lines = 2U;        snprintf(req.consumer, sizeof(req.consumer), "ksa-modem-ctl");        req.config.flags = GPIO_V2_LINE_FLAG_OUTPUT;            req.config.num_attrs = 2U;        req.config.attrs[0].mask = (1ULL << 1);        req.config.attrs[0].attr.id = GPIO_V2_LINE_ATTR_ID_FLAGS;        req.config.attrs[0].attr.flags =            GPIO_V2_LINE_FLAG_OUTPUT | GPIO_V2_LINE_FLAG_ACTIVE_LOW;          req.config.attrs[1].mask = 0x3ULL;        req.config.attrs[1].attr.id = GPIO_V2_LINE_ATTR_ID_OUTPUT_VALUES;        req.config.attrs[1].attr.values = 0x3ULL;            bank.active_req = req;        bank.claimed_mask = (1U << 3) | (1U << 7);        struct gpio_v2_line_values init_v = {            .bits = req.config.attrs[1].attr.values,            .mask = req.config.attrs[1].mask,        };        uint32_t after_init = apply_v2_values(&bank, &init_v);            struct gpio_v2_line_values step_v = {          .bits = 0x0ULL,            .mask = (1ULL << 0),        };        uint32_t after_mask0 = apply_v2_values(&bank, &step_v);            printf("legacy_gpio=%d v2_max_lines=%u consumer=%s\n",               legacy_global, (unsigned)GPIO_V2_LINES_MAX, req.consumer);        printf("init_pin3=%u init_pin7_phys=%u masked_pin3=%u pin7_kept=%u\n",               (after_init >> 3) & 1U, (after_init >> 7) & 1U,               (after_mask0 >> 3) & 1U, (after_mask0 >> 7) & 1U);        return EXIT_SUCCESS;    }
  1. bits and mask index slots 0 .. num_lines - 1 in req.offsets[] using unsigned 1ULL << i shifts.
  2. GPIO_V2_LINE_FLAG_ACTIVE_LOW on slot 1 (mask = 1ULL << 1) inverts logical 1 into physical 0V inside the kernel.
  3. GPIO_V2_LINE_ATTR_ID_OUTPUT_VALUES latches initial drive levels atomically with output direction enable.

Guided Practice: Packing Sparse Multi-Pin Masks

Suppose a 4-line request claims req.offsets = {2, 9, 14, 27} (num_lines = 4) and you must drive offsets[0] (pin 2) HIGH and offsets[2] (pin 14) LOW while leaving offsets[1] and offsets[3] untouched. Complete the struct gpio_v2_line_values assignment using these two cues:

  1. Cue 1 (Mask selection): Set .mask using 1ULL shifts for request indices 0 and 2 ((1ULL << 0) | (1ULL << 2) = 0x5ULL), never 1ULL << 14.
  2. Cue 2 (Bit values): Set .bits to (1ULL << 0) (0x1ULL) so index 0 becomes 1 and masked index 2 becomes 0.

Independent Practice: Runtime Direction Reconfiguration (SET_CONFIG_IOCTL)

Extend gpio_v2_controller.c with a helper demonstrating struct gpio_v2_line_config for GPIO_V2_LINE_SET_CONFIG_IOCTL: switch a bidirectional 1-wire data line at req.offsets[0] from GPIO_V2_LINE_FLAG_OUTPUT | GPIO_V2_LINE_FLAG_OPEN_DRAIN into GPIO_V2_LINE_FLAG_INPUT | GPIO_V2_LINE_FLAG_BIAS_PULL_UP without closing req.fd or releasing ownership of the line.

Compiling, Running & Inspecting Host vs Target Execution

Compile and run gpio_v2_controller.c, then trace its system calls with strace. Notice the host-versus-target execution boundary: on our host harness without a physical /dev/gpiochip0 wired to a modem, apply_v2_values() evaluates the exact <linux/gpio.h> structs in memory (1 write(1, ...) syscall in strace); on a target ARMv7 board, you replace apply_v2_values() with cfd = open("/dev/gpiochip0", O_RDONLY | O_CLOEXEC), ioctl(cfd, GPIO_V2_GET_LINE_IOCTL, &req), close(cfd), and ioctl(req.fd, GPIO_V2_LINE_SET_VALUES_IOCTL, &step_v).

learner@ksa: ~/gl-c04/m01-l02
learner@ksa:~/gl-c04/m01-l02gcc -std=c11 -Wall -Wextra -Werror -fdiagnostics-color=always gpio_v2_controller.c -o gpio_v2_controllerlearner@ksa:~/gl-c04/m01-l02./gpio_v2_controllerlegacy_gpio=112 v2_max_lines=64 consumer=ksa-modem-ctlinit_pin3=1 init_pin7_phys=0 masked_pin3=0 pin7_kept=0learner@ksa:~/gl-c04/m01-l02echo $?0learner@ksa:~/gl-c04/m01-l02ls -A --color=alwaysgpio_v2_controllergpio_v2_controller.clearner@ksa:~/gl-c04/m01-l02
strace — learner@ksa: ~/gl-c04/m01-l02
learner@ksa:~/gl-c04/m01-l02strace -s 40 -e trace=openat,ioctl,write,close \./gpio_v2_controlleropenat(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) = 3close(3)                                = 0write(1, "legacy_gpio=112 v2_max_lines=64 consumer"..., 110) = 110+++ exited with 0 +++

Decoding Polarity Inversion & Selective Bitmasks

Look at the four verified output bits in run_m01_l02:

  • During initial request (init_v.bits = 0x3ULL, init_v.mask = 0x3ULL), logical 1 on offsets[0] = 3 drove physical 1 (init_pin3=1), while logical 1 ("asserted") on ACTIVE_LOW offsets[1] = 7 drove physical 0 (init_pin7_phys=0). Application logic thinks in clean "asserted = 1" semantics regardless of board-revision inverter changes!
  • During step_v (.bits = 0x0ULL, .mask = 1ULL << 0), clearing bit 0 dropped pin 3 to 0 (masked_pin3=0) while bit 1's 0 in .mask preserved pin 7's physical 0 (pin7_kept=0) without requiring user space to read or shadow sibling pins.

Production Pitfalls & Diagnostic Verification

Output control via GPIO_V2_LINE_SET_VALUES_IOCTL handles synchronous writes cleanly, though polling input pins via GPIO_V2_LINE_GET_VALUES_IOCTL in a loop still wastes CPU cycles (solved in our next lesson via edge interrupts). Avoid these two common v2 bugs first.

warning: Symptom: Requesting a single pin req.offsets[0] = 19, req.num_lines = 1 succeeds, yet calling GPIO_V2_LINE_SET_VALUES_IOCTL with v.bits = (1ULL << 19), v.mask = (1ULL << 19) leaves GPIO 19 unchanged! Root Cause: struct gpio_v2_line_values indexes .bits and .mask by request-array slot 0 .. req.num_lines - 1, so bit 19 is ignored when num_lines == 1. Fix: Shift by slot index 0 (1ULL << 0), which maps to req.offsets[0] (19).

warning: Symptom: Issuing ioctl(cfd, GPIO_V2_LINE_SET_VALUES_IOCTL, &v) returns -1 with errno == ENOTTY (Inappropriate ioctl for device). Root Cause: cfd is the /dev/gpiochip0 controller discovery descriptor, whereas line read/write ioctls belong to the anonymous line descriptor returned in req.fd. Fix: Close cfd after GPIO_V2_GET_LINE_IOCTL and pass req.fd to GPIO_V2_LINE_SET_VALUES_IOCTL and GPIO_V2_LINE_GET_VALUES_IOCTL.

Diagnostic Checks & Spaced Retrieval

Verify your command of these UAPI invariants, bitmask contracts, and failure modes below.

quiz · 1 of 3

When two lines req.offsets[0] = 5 and req.offsets[1] = 19 (req.num_lines = 2) are claimed in one GPIO_V2_GET_LINE_IOCTL call, which struct gpio_v2_line_values initialization sets hardware offset 19 high while leaving offset 5 unchanged?

quiz · 2 of 3

Why does <linux/gpio.h> encode configuration flags and multi-line values in fixed-width __aligned_u64 integers manipulated with (1ULL << n) rather than C struct bit-fields (struct { unsigned line0:1; })?

quiz · 3 of 3

(Retrieval from Lesson 1.1) Before writing a steady intensity level to /sys/class/leds/<led>/brightness from C, what must your program do if trigger currently reads none [heartbeat] mmc0?

Key takeaways

  • Legacy /sys/class/gpio uses unstable global numbers (base + offset), lacks crash cleanup, and requires multiple non-atomic file writes.
  • Linux 6.12 /dev/gpiochipN v2 (<linux/gpio.h>) claims 1 to 64 bank-local offsets atomically via GPIO_V2_GET_LINE_IOCTL and returns an isolated req.fd handle with a visible consumer tag.
  • Attach GPIO_V2_LINE_ATTR_ID_OUTPUT_VALUES during GPIO_V2_GET_LINE_IOCTL for glitch-free output startup, and use GPIO_V2_LINE_FLAG_ACTIVE_LOW to invert active-low hardware cleanly.
  • struct gpio_v2_line_values indexes .bits and .mask by 0 .. req.num_lines - 1, closing req.fd (including on process crash) releases the lines automatically, and explicit unsigned shifts (1ULL << n) avoid implementation-defined, non-atomic C struct bit-fields.
  • Driving outputs atomically solves half of GPIO engineering; next we eliminate CPU-wasting input polling loops by wiring hardware rising/falling edge interrupts into poll() with nanosecond debounce and FIFO sequence auditing.
Progress is saved on this device.

search — fzf

0/0 ───────────────────────────────────────────

keyboard shortcuts — less

/
search
f
focus mode
[
previous
]
next
?
help
Esc
close

figure