Lab 1: Lab M01: Sysfs LED Controller and GPIO v2 Debounced Line Engine

55 minfree previewLinux 6.12C11glibc 2.39← module 1

Implement a warning-clean C11 embedded peripheral library (libgpio_led.a) that detaches active kernel LED triggers before clamping /sys/class/leds brightness, packs multi-line struct gpio_v2_line_values bitmasks atomically, and filters mechanical switch bounce while counting kernel kfifo sequence gaps across struct gpio_v2_line_event streams.

Prerequisites in this module

What ./check.sh verifies

  • Builds with -std=c11 -Wall -Wextra and no warnings.
  • Archives gpio_led_ctrl.o into libgpio_led.a and links gpio_led_cli.
  • sysfs_led_set_manual detaches trigger to none and clamps brightness to 255.
  • gpio_v2_pack_values populates .mask=0x25 and .bits=0x21 atomically.
step 1/16

step 1/16 · inspect starter files and specification

Implement a warning-clean C11 embedded peripheral library (libgpio_led.a) that detaches active kernel LED triggers before clamping /sys/class/leds brightness, packs multi-line struct gpio_v2_line_values bitmasks atomically, and filters mechanical switch bounce while counting kernel kfifo sequence gaps across struct gpio_v2_line_event streams.

learner@ksa: ~/gl-c04/lab-m01
learner@ksa:~/gl-c04/lab-m01ls -lastarter/Makefilestarter/gpio_led_cli.cstarter/gpio_led_ctrl.cstarter/gpio_led_ctrl.hlearner@ksa:~/gl-c04/lab-m01
starter: starter/Makefile
learner@ksa: ~/gl-c04/lab-m01
learner@ksa:~/gl-c04/lab-m01$ bat starter/Makefile File: starter/Makefile    CC      := gcc    AR      := ar    CFLAGS  := -std=c11 -Wall -Wextra -Werror -O2        .PHONY: all clean        all: libgpio_led.a gpio_led_cli        gpio_led_ctrl.o: gpio_led_ctrl.c gpio_led_ctrl.h    	$(CC) $(CFLAGS) -c gpio_led_ctrl.c -o gpio_led_ctrl.o        libgpio_led.a: gpio_led_ctrl.o    	$(AR) rcs libgpio_led.a gpio_led_ctrl.o        gpio_led_cli: gpio_led_cli.c libgpio_led.a gpio_led_ctrl.h    	$(CC) $(CFLAGS) gpio_led_cli.c libgpio_led.a -o gpio_led_cli        clean:    	rm -f *.o libgpio_led.a gpio_led_cli
starter: starter/gpio_led_cli.c
learner@ksa: ~/gl-c04/lab-m01
learner@ksa:~/gl-c04/lab-m01$ bat starter/gpio_led_cli.c File: starter/gpio_led_cli.c    #define _GNU_SOURCE    #include "gpio_led_ctrl.h"    #include <fcntl.h>    #include <stdio.h>    #include <stdlib.h>    #include <string.h>    #include <sys/stat.h>    #include <time.h>    #include <unistd.h>        static int cmp_u64(const void *a, const void *b)    {        uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b;        return (x > y) - (x < y);    }        static uint64_t mono_ns(void)    {        struct timespec ts;        clock_gettime(CLOCK_MONOTONIC, &ts);        return (uint64_t)ts.tv_sec * 1000000000ULL + (uint64_t)ts.tv_nsec;    }        static int run_once(const char *led_dir, int *applied,                        struct gpio_v2_line_values *vals,                        uint32_t *accepted, uint32_t *gaps)    {        if (sysfs_led_set_manual(led_dir, 999, applied) < 0)            return -1;        const uint32_t idx[3] = { 0u, 2u, 5u };        const uint8_t lvl[3] = { 1u, 0u, 1u };        gpio_v2_pack_values(idx, lvl, 3u, vals);            const struct gpio_v2_line_event stream[5] = {            { .timestamp_ns = 100000000ULL,              .id = GPIO_V2_LINE_EVENT_FALLING_EDGE, .line_seqno = 1u },            { .timestamp_ns = 102500000ULL,              .id = GPIO_V2_LINE_EVENT_RISING_EDGE,  .line_seqno = 2u },            { .timestamp_ns = 106000000ULL,              .id = GPIO_V2_LINE_EVENT_FALLING_EDGE, .line_seqno = 3u },            { .timestamp_ns = 125000000ULL,              .id = GPIO_V2_LINE_EVENT_RISING_EDGE,  .line_seqno = 6u },            { .timestamp_ns = 150000000ULL,              .id = GPIO_V2_LINE_EVENT_FALLING_EDGE, .line_seqno = 7u },        };        uint64_t last_ns = 0ULL;        uint32_t exp_seq = 1u;        *gaps = 0u;        *accepted = 0u;        for (size_t i = 0; i < 5u; ++i) {            if (gpio_v2_debounce_accept(&stream[i], &last_ns, &exp_seq,                                        10000000ULL, gaps))                ++(*accepted);        }        return 0;    }        int main(int argc, char **argv)    {        if (argc < 2) {            fprintf(stderr, "usage: %s <led_sysfs_dir> [--bench]\n", argv[0]);            return 2;        }        int bench = (strcmp(argv[1], "--bench") == 0) ||                    (argc > 2 && strcmp(argv[2], "--bench") == 0);        char tmp_dir[] = "/tmp/ksa_led_bench.XXXXXX";        const char *dir = argv[1];        if (strcmp(argv[1], "--bench") == 0) {            if (!mkdtemp(tmp_dir))                return 1;            dir = tmp_dir;            char p[96];            snprintf(p, sizeof(p), "%s/max_brightness", dir);            FILE *f = fopen(p, "w");            if (f) { fputs("255\n", f); fclose(f); }            snprintf(p, sizeof(p), "%s/trigger", dir);            f = fopen(p, "w");            if (f) { fputs("[heartbeat] timer none\n", f); fclose(f); }            snprintf(p, sizeof(p), "%s/brightness", dir);            f = fopen(p, "w");            if (f) { fputs("0\n", f); fclose(f); }        }            int applied = -1;        struct gpio_v2_line_values vals;        uint32_t accepted = 0u, gaps = 0u;        if (bench) {            uint64_t samples[100];            for (int i = 0; i < 16; ++i)                (void)run_once(dir, &applied, &vals, &accepted, &gaps);            for (int i = 0; i < 100; ++i) {                uint64_t t0 = mono_ns();                (void)run_once(dir, &applied, &vals, &accepted, &gaps);                samples[i] = mono_ns() - t0;            }            qsort(samples, 100u, sizeof(samples[0]), cmp_u64);            if (dir == tmp_dir) {                char p[96];                snprintf(p, sizeof(p), "%s/max_brightness", dir); unlink(p);                snprintf(p, sizeof(p), "%s/trigger", dir); unlink(p);                snprintf(p, sizeof(p), "%s/brightness", dir); unlink(p);                rmdir(dir);            }            printf("BENCH iterations=100 p50_ns=%llu p95_ns=%llu p99_ns=%llu\n",                   (unsigned long long)samples[49],                   (unsigned long long)samples[94],                   (unsigned long long)samples[98]);            return 0;        }            if (run_once(dir, &applied, &vals, &accepted, &gaps) < 0)            return 1;        printf("LED applied=%d mask=0x%02llX bits=0x%02llX accepted=%u seq_gaps=%u\n",               applied, (unsigned long long)vals.mask,               (unsigned long long)vals.bits, accepted, gaps);        return 0;    }
starter: starter/gpio_led_ctrl.c
learner@ksa: ~/gl-c04/lab-m01
learner@ksa:~/gl-c04/lab-m01$ bat starter/gpio_led_ctrl.c File: starter/gpio_led_ctrl.c    #define _GNU_SOURCE    #include "gpio_led_ctrl.h"    #include <fcntl.h>    #include <stdio.h>    #include <string.h>    #include <unistd.h>        int sysfs_led_set_manual(const char *led_dir, int req_brightness, int *applied_out)    {        /* BUG: forgets to write "none" to trigger and fails to clamp against max_brightness */        char path[256], num[32];        snprintf(path, sizeof(path), "%s/brightness", led_dir);        int fd = open(path, O_WRONLY | O_TRUNC | O_CLOEXEC);        if (fd < 0)            return -1;        int n = snprintf(num, sizeof(num), "%d", req_brightness);        if (write(fd, num, (size_t)n) != n) {            close(fd);            return -1;        }        close(fd);        *applied_out = req_brightness;        return 0;    }        void gpio_v2_pack_values(const uint32_t *req_indices, const uint8_t *levels,                             size_t count, struct gpio_v2_line_values *out)    {        /* BUG: sets bits without setting mask */        memset(out, 0, sizeof(*out));        for (size_t i = 0; i < count; ++i) {            if (levels[i])                out->bits |= (1ULL << req_indices[i]);        }    }        int gpio_v2_debounce_accept(const struct gpio_v2_line_event *ev,                                uint64_t *last_accept_ns,                                uint32_t *expected_line_seq,                                uint64_t debounce_ns,                                uint32_t *seq_gaps_out)    {        /* BUG: accepts every bounce unconditionally */        (void)debounce_ns;        (void)expected_line_seq;        (void)seq_gaps_out;        *last_accept_ns = ev->timestamp_ns;        return 1;    }
starter: starter/gpio_led_ctrl.h
learner@ksa: ~/gl-c04/lab-m01
learner@ksa:~/gl-c04/lab-m01$ bat starter/gpio_led_ctrl.h File: starter/gpio_led_ctrl.h    #ifndef KSA_GPIO_LED_CTRL_H    #define KSA_GPIO_LED_CTRL_H        #include <linux/gpio.h>    #include <stddef.h>    #include <stdint.h>        int sysfs_led_set_manual(const char *led_dir, int req_brightness, int *applied_out);        void gpio_v2_pack_values(const uint32_t *req_indices, const uint8_t *levels,                             size_t count, struct gpio_v2_line_values *out);        int gpio_v2_debounce_accept(const struct gpio_v2_line_event *ev,                                uint64_t *last_accept_ns,                                uint32_t *expected_line_seq,                                uint64_t debounce_ns,                                uint32_t *seq_gaps_out);        #endif

step 2/16 · 1. motivation

Field-deployed industrial controllers drive panel status LEDs via /sys/class/leds while monitoring safety interlock switches and multi-pin relay banks through /dev/gpiochipN v2 (<linux/gpio.h>). Three silent C11 bugs cause real hardware incidents in production daemons: writing brightness while a kernel heartbeat or timer trigger still owns the LED (leaving periodic kernel blinks overriding manual fault states), populating gpio_v2_line_values.bits while leaving .mask = 0 (turning GPIO_V2_LINE_SET_VALUES_IOCTL into a silent kernel no-op), and filtering timestamp_ns contact bounce before inspecting line_seqno (hiding dropped interrupts when the kernel 16-event kfifo overflows under CPU load). This studio lab integrates all three Module 1 contracts into a static C11 library validated deterministically on any Linux 6.12 host.

step 3/16 · 2. learning objectives

  • Detach kernel LED triggers by writing "none" to <led_dir>/trigger via openat(2) before clamping requested brightness to [0, max_brightness].
  • Construct atomic struct gpio_v2_line_values payloads setting (1ULL << req_idx) in .mask for every targeted line and in .bits for logic-high levels.
  • Implement monotonic CLOCK_MONOTONIC contact-bounce suppression (timestamp_ns >= last_accept_ns + debounce_ns) while unconditionally tracking line_seqno discontinuities across kernel kfifo reads.
  • Measure end-to-end p50, p95, and p99 execution latency with CLOCK_MONOTONIC and explain the VFS syscall cost boundary between sysfs attribute writes and in-RAM gpio_v2 struct packing.

step 4/16 · 3. environment requirements

  • Operating System: Linux 6.x (x86_64 or aarch64 development workstation or container) exposing Linux 6.12 UAPI <linux/gpio.h>.
  • Compiler & Archive Toolchain: gcc supporting -std=c11 -Wall -Wextra -Werror, GNU make, and ar/ranlib (binutils).
  • Diagnostics: strace (>= 5.x) for inspecting openat, read, and write VFS syscall counts.
  • Privileges: Unprivileged user account (0 root or /dev/gpiochip0 hardware permissions required for the deterministic host harness).

step 5/16 · 4. required software and hardware

  • Host Simulation Harness (Required): check.sh and gpio_led_cli synthesize a real POSIX directory (sys_led0/ containing max_brightness, trigger, and brightness) and feed exact <linux/gpio.h> struct gpio_v2_line_values and struct gpio_v2_line_event payloads in user space.
  • Target ARMv7-A Hardware (Optional Extension): Any Linux 6.12 SBC exposing /sys/class/leds/<name>/ and /dev/gpiochipN (GPIO_V2_GET_LINE_IOCTL, GPIO_V2_LINE_SET_VALUES_IOCTL, and poll(POLLIN) edge events). On target hardware, sysfs_led_set_manual("/sys/class/leds/status", 255, &applied) operates directly on the kernel leds-gpio driver without changing a single line of C.

step 6/16 · 5. executable commands and rationale

Run each command from labs/lab_m01_gpio_led_ctrl/ and note why each step exists:

learner@ksa: ~/gl-c04/lab-m01
learner@ksa:~/gl-c04/lab-m01$ bat script.sh File: script.sh    # 1. Run the TAP 13 harness against the broken starter baseline to observe    #    exact diagnostic failures before editing files/gpio_led_ctrl.c:    cp -R starter files_work && mv files files_ref && mv files_work files    ./check.sh || true    rm -rf files && mv files_ref files        # 2. Compile libgpio_led.a and gpio_led_cli with -std=c11 -Wall -Wextra -Werror    #    so implicit conversions and unused parameters fail at compile time:    make -C files clean && make -C files        # 3. Execute the full 5-point TAP version 13 verification suite:    ./check.sh        # 4. Run the CLOCK_MONOTONIC microbenchmark (16 warmups + 100 timed iterations)    #    to quantify sysfs VFS attribute overhead:    ./files/gpio_led_cli --bench        # 5. Trace VFS syscalls across one CLI invocation with strace -fc:    mkdir -p /tmp/ksa_led0    printf '255\n' >/tmp/ksa_led0/max_brightness    printf '[heartbeat] timer none\n' >/tmp/ksa_led0/trigger    printf '0\n' >/tmp/ksa_led0/brightness    strace -fc ./files/gpio_led_cli /tmp/ksa_led0    rm -rf /tmp/ksa_led0

step 7/16 · 6. annotated source code

Flawed starter/gpio_led_ctrl.c Baseline (3 Intentional Defects):

  • sysfs_led_set_manual() writes raw req_brightness (999) directly to brightness without reading max_brightness (255) or writing "none" to trigger.
  • gpio_v2_pack_values() sets out->bits |= (1ULL << req_indices[i]) when levels[i] != 0, leaving out->mask == 0x00 so the kernel ignores all 3 pins.
  • gpio_v2_debounce_accept() casts (void)debounce_ns and (void)seq_gaps_out, accepting sub-10 ms bounce noise (accepted=5) and reporting seq_gaps=0 across the 3 -> 6 line_seqno jump.

Warning-Clean files/gpio_led_ctrl.c Reference Architecture:

  • Directory-relative openat(2) (lines 9-68): Opens led_dir once with O_RDONLY | O_DIRECTORY | O_CLOEXEC, reads max_brightness via strtol, writes "none" to trigger (O_WRONLY | O_TRUNC | O_CLOEXEC), clamps req_brightness into [0, max_b], and writes the ASCII integer to brightness.
  • 64-bit request-index bitpacking (lines 70-82): Zeroes *out with memset, guards req_indices[i] < 64u, and sets uint64_t bit = 1ULL << req_indices[i] in out->mask unconditionally while setting out->bits |= bit only when levels[i] != 0 (idx={0,2,5}, lvl={1,0,1} -> mask=0x25, bits=0x21).
  • Sequence-first debounce state machine (lines 84-98): Checks ev->line_seqno > *expected_line_seq before evaluating the debounce_ns window so kfifo drops are never masked by debounce rejection, updates *expected_line_seq = ev->line_seqno + 1u, and suppresses edges arriving earlier than *last_accept_ns + debounce_ns.

step 8/16 · 7. expected output

Host Harness (./check.sh on files/):

learner@ksa: ~/gl-c04/lab-m01
learner@ksa:~/gl-c04/lab-m01$ bat listing.txt File: listing.txt    TAP version 13    1..5    ok 1 - builds with -std=c11 -Wall -Wextra and no warnings    ok 2 - archives gpio_led_ctrl.o into libgpio_led.a and links gpio_led_cli    ok 3 - sysfs_led_set_manual detaches trigger to none and clamps brightness to 255    ok 4 - gpio_v2_pack_values populates .mask=0x25 and .bits=0x21 atomically    ok 5 - gpio_v2_debounce_accept drops <10ms contact bounce and counts kfifo seq_gaps=2    # pass 5/5

Direct CLI Output (./files/gpio_led_cli ./sys_led0):

learner@ksa: ~/gl-c04/lab-m01
learner@ksa:~/gl-c04/lab-m01$ bat listing.txt File: listing.txt    LED applied=255 mask=0x25 bits=0x21 accepted=3 seq_gaps=2

Host vs Target Distinction: On the host, sys_led0/trigger stores the literal string "none" on tmpfs; on an ARMv7-A target kernel (leds-gpio), reading /sys/class/leds/<led>/trigger back after writing "none" returns "[none] timer heartbeat ..." with brackets around [none] indicating the active kernel trigger.

step 9/16 · 8. explanation of observed behavior

  1. applied=255: gpio_led_cli requests req_brightness = 999 against max_brightness = 255; sysfs_led_set_manual() detaches [heartbeat] by writing "none" to trigger and clamps the written value to 255.
  2. mask=0x25 bits=0x21: Request indices {0, 2, 5} map to bits 2^0 + 2^2 + 2^5 = 1 + 4 + 32 = 37 = 0x25 in .mask. Because index 2 has desired level 0 while indices 0 and 5 have level 1, .bits = 2^0 + 2^5 = 33 = 0x21.
  3. accepted=3 seq_gaps=2: Event 1 (100.0 ms, seq=1) is accepted (last_ns = 100.0 ms). Events 2 (102.5 ms, seq=2) and 3 (106.0 ms, seq=3) arrive 2.5 ms and 6.0 ms after Event 1 (< 10.0 ms debounce window) and are suppressed. Event 4 (125.0 ms, seq=6) jumps from expected seq=4 to 6 (seq_gaps += 2) and is 25.0 ms >= 10.0 ms past 100.0 ms, so it is accepted (last_ns = 125.0 ms). Event 5 (150.0 ms, seq=7) arrives 25.0 ms later with zero gap and is accepted (accepted = 3, seq_gaps = 2).

step 10/16 · 9. experiment variations

  • Near Transfer (Active-Low Relay Polarity): Add GPIO_V2_LINE_FLAG_ACTIVE_LOW awareness in user-space diagnostics: verify that with ACTIVE_LOW set during GPIO_V2_GET_LINE_IOCTL, bits = 0x21 represents logical assertion (1 = active) while the kernel gpiolib hardware driver drives physical 0 V on indices 0 and 5.
  • Far Transfer (Per-Offset Independent Debounce Table): Extend gpio_v2_debounce_accept() into a multi-line tracker indexed by ev->offset (struct line_state states[64]) so a 4-button keypad sharing one req.fd tracks last_accept_ns and line_seqno independently per pin while cross-checking ev->seqno for aggregate req.fd kfifo drops.

step 11/16 · 10. performance measurements

Measured on Linux 6.12 (x86_64, gcc -O2 -std=c11) using CLOCK_MONOTONIC (16 cache/dentry warmup runs followed by N = 100 timed iterations via ./files/gpio_led_cli --bench) and strace -fc:

MetricMeasured Host ValueKernel Mechanism Accounting for Cost
BENCH p50 latency57,059 ns (57.1 us)1 directory open + 3 openat/read-or-write/close sysfs VFS cycles
BENCH p95 latency66,094 ns (66.1 us)dentry/inode lock acquisition and tmpfs page-cache writeback
BENCH p99 latency176,008 ns (176.0 us)Scheduler tick preemption during repeated O_TRUNC file updates
Syscalls per CLI run (strace -fc)45 total (6 openat, 3 write, 2 read)4 sysfs file opens (led_dir, max_brightness, trigger, brightness) + libc startup
In-RAM pack_values + debounce< 80 ns (0 syscalls)Pure register bit-shifts; on target hardware GPIO_V2_LINE_SET_VALUES_IOCTL adds 1 ioctl (~1.2 us)

step 12/16 · 11. troubleshooting

SymptomRoot CauseFix
not ok 3 with trigger="[heartbeat] timer none"sysfs_led_set_manual() wrote brightness without detaching trigger firstWrite "none" (4 bytes, no brackets) to trigger before writing brightness
not ok 4 with mask=0x00 bits=0x21Only set out->bits or shifted by 1U << idx (32-bit UB for idx >= 32)Use uint64_t bit = 1ULL << req_indices[i] and OR into out->mask for every requested index
not ok 5 with accepted=3 seq_gaps=0Placed if (ev->timestamp_ns < ...) before line_seqno gap calculationAlways update seq_gaps_out and *expected_line_seq = ev->line_seqno + 1u before returning 0 on bounce
Compiler error on 1ULL << 64Unchecked req_indices[i] >= 64u triggers C11 shift-width UBGuard loop body with if (req_indices[i] < 64u) (GPIO_V2_LINES_MAX == 64)

step 13/16 · 12. guided questions

  1. Question: Why does gpio_v2_pack_values() shift by req_indices[i] (0..63 position inside req.offsets[]) rather than the hardware GPIO bank pin offset (for example pin 18 or 23)?
  • *Hint 1:* Inspect <linux/gpio.h> comments on struct gpio_v2_line_values and how GPIO_V2_GET_LINE_IOCTL orders lines in req.offsets[0..num_lines-1].
  • *Hint 2:* Consider a GPIO controller with 128 lines: a 64-bit .mask could not address pin 95 by bank offset, whereas req.num_lines <= 64 maps every claimed line to 0..63.
  1. Question: Why does sysfs_led_set_manual() open led_dir with O_RDONLY | O_DIRECTORY | O_CLOEXEC and use openat(dfd, ...) instead of three snprintf("%s/...", ...) calls?
  • *Hint 1:* What happens if led_dir is a /sys/class/leds/status symlink that gets rebound or exceeds fixed stack buffer assumptions?
  • *Hint 2:* Count VFS path-resolution traversals: openat(dfd, "brightness", ...) resolves directly inside the pinned directory inode without re-walking /sys/class/leds/....

step 14/16 · 13. independent challenges

  1. Multi-Event Batch read() Loop: Write a helper ssize_t gpio_v2_drain_fd(int req_fd, uint64_t *last_ns, uint32_t *exp_seq, uint64_t debounce_ns, uint32_t *gaps) that reads struct gpio_v2_line_event buf[16] in one read(2) call (sizeof(buf) == 16 * 48 == 768 bytes), handles -1 with errno == EAGAIN, verifies (r % sizeof(struct gpio_v2_line_event)) == 0, and returns the count of debounced edges.
  2. Hardware Debounce Fallback: Construct a struct gpio_v2_line_request initializer requesting GPIO_V2_LINE_ATTR_ID_DEBOUNCE (debounce_period_us = 10000); if ioctl(chip_fd, GPIO_V2_GET_LINE_IOCTL, &req) returns -1 with errno == EINVAL or ENOTSUP, fall back automatically to software gpio_v2_debounce_accept().

step 15/16 · 14. solutions and explanations

  • Guided Question 1 Solution: struct gpio_v2_line_values bits 0..63 index the req.offsets[] array passed when req.fd was created (GPIO_V2_LINES_MAX = 64). Even if a GPIO bank exposes 160 pins, any single req.fd holds at most 64 lines, allowing .mask and .bits to update any subset of those 64 lines atomically in a single uint64_t pair.
  • Guided Question 2 Solution: open(led_dir, O_RDONLY | O_DIRECTORY | O_CLOEXEC) pins the target kobject directory inode once, avoids fixed-buffer truncation risks, prevents file-descriptor leaks across fork+exec (O_CLOEXEC), and skips redundant VFS path-walk lookups across max_brightness, trigger, and brightness.
  • Challenge 1 Key Invariant: Never read() fewer than sizeof(struct gpio_v2_line_event) (48 bytes); the kernel linereq_read() driver returns -EINVAL if the user buffer is smaller than one complete event record, and batching 16 events drains a full default kfifo in one user/kernel transition.

step 16/16 · run verification and inspect output

Run the verification command and confirm the output matches the expected contract.

learner@ksa: ~/gl-c04/lab-m01
learner@ksa:~/gl-c04/lab-m01./files/gpio_led_cli ./sys_led0learner@ksa:~/gl-c04/lab-m01
expected output
LED applied=255 mask=0x25 bits=0x21 accepted=3 seq_gaps=2

Progressive hints & solution

hint 1

Compare starter/Makefile against the module lessons. Focus first on: Builds with -std=c11 -Wall -Wextra and no warnings.

hint 2

Compile with -std=c11 -Wall -Wextra -Werror, check every system-call return value before touching output buffers, and verify cleanup on error paths.

solution

Run the check

From labs/lab_m01_gpio_led_ctrl/, run ./check.sh. A complete solution emits TAP version 13 with every test point marked ok and exits 0:

./check.sh — lab m01
learner@ksa:~/gl-c04/lab-m01./check.shTAP version 131..5ok 1 - builds with -std=c11 -Wall -Wextra and no warningsok 2 - archives gpio_led_ctrl.o into libgpio_led.a and links gpio_led_cliok 3 - sysfs_led_set_manual detaches trigger to none and clamps brightness to 255ok 4 - gpio_v2_pack_values populates .mask=0x25 and .bits=0x21 atomicallyok 5 - gpio_v2_debounce_accept drops <10ms contact bounce and counts kfifo seq_gaps=2# pass 5/5

On an incomplete starter tree, ./check.sh exits non-zero and marks the unmet assertion not ok with an indented YAML diagnostic block:

./check.sh — lab m01 (starter)
learner@ksa:~/gl-c04/lab-m01./check.shTAP version 131..5ok 1 - builds with -std=c11 -Wall -Wextra and no warningsok 2 - archives gpio_led_ctrl.o into libgpio_led.a and links gpio_led_clinot ok 3 - sysfs_led_set_manual detaches trigger to none and clamps brightness to 255  ---  message: 'trigger="[heartbeat] timer none" (expected "none"), brightness="999" (expected "255")'  hint: 'write "none" to <led_dir>/trigger before writing clamped [0..max_brightness] to brightness'  ...not ok 4 - gpio_v2_pack_values populates .mask=0x25 and .bits=0x21 atomically  ---  message: 'expected mask=0x25 bits=0x21 in "LED applied=999 mask=0x00 bits=0x21 accepted=5 seq_gaps=0"'  hint: 'set (1ULL << idx) in out->mask for every requested line and in out->bits when level != 0'  ...not ok 5 - gpio_v2_debounce_accept drops <10ms contact bounce and counts kfifo seq_gaps=2  ---  message: 'expected "LED applied=255 mask=0x25 bits=0x21 accepted=3 seq_gaps=2", got "LED applied=999 mask=0x00 bits=0x21 accepted=5 seq_gaps=0"'  hint: 'track line_seqno gaps before timestamp_ns >= last_accept_ns + debounce_ns filtering'  ...# pass 2/5FAIL: 2/5 TAP checks passed (inspect YAML diagnostics above)

note: How to read TAP diagnostics: 1..N states the total test plan; each ok k confirms a passed check; not ok k pinpoints the failing check alongside message: (what went wrong) and hint: (where to look next) between --- and ....

inspect harness: check.sh
learner@ksa: ~/gl-c04/lab-m01
learner@ksa:~/gl-c04/lab-m01$ bat check.sh File: check.sh    #!/bin/sh    set -u        PASS=0    TOTAL=5        clean_msg() {        printf '%s' "$1" | tr '\r\n' '  ' | tr "'" '"' | sed 's/  */ /g; s/^ //; s/ $//'    }        emit_diag() {        printf "  ---\n  message: '%s'\n  hint: '%s'\n  ...\n" "$(clean_msg "$1")" "$(clean_msg "$2")"    }        WORKDIR="$(mktemp -d "${TMPDIR:-/tmp}/ksa_lab_c04_m01.XXXXXX")"    trap 'rm -rf "$WORKDIR"' EXIT        printf 'TAP version 13\n1..%d\n' "$TOTAL"        MISSING=""    for req in files/Makefile files/gpio_led_ctrl.h files/gpio_led_ctrl.c files/gpio_led_cli.c; do        if [ ! -f "$req" ]; then            MISSING="$MISSING $req"        fi    done        BUILD_OK=0    if [ -n "$MISSING" ]; then        echo "not ok 1 - builds with -std=c11 -Wall -Wextra and no warnings"        emit_diag "missing required files:$MISSING" "provide Makefile, gpio_led_ctrl.h, gpio_led_ctrl.c, and gpio_led_cli.c in files/"    else        cp -R files "$WORKDIR/build"        if make -C "$WORKDIR/build" >"$WORKDIR/mk.out" 2>"$WORKDIR/mk.err"; then            echo "ok 1 - builds with -std=c11 -Wall -Wextra and no warnings"            PASS=$((PASS + 1))            BUILD_OK=1        else            ERR="$(cat "$WORKDIR/mk.err" 2>/dev/null)"            echo "not ok 1 - builds with -std=c11 -Wall -Wextra and no warnings"            emit_diag "make build failed: ${ERR:-non-zero exit}" "compile with gcc -std=c11 -Wall -Wextra -Werror in files/Makefile"        fi    fi        if [ "$BUILD_OK" -eq 1 ] && [ -f "$WORKDIR/build/libgpio_led.a" ] && \       ar t "$WORKDIR/build/libgpio_led.a" 2>/dev/null | grep -q "gpio_led_ctrl.o" && \       [ -x "$WORKDIR/build/gpio_led_cli" ]; then        echo "ok 2 - archives gpio_led_ctrl.o into libgpio_led.a and links gpio_led_cli"        PASS=$((PASS + 1))    else        echo "not ok 2 - archives gpio_led_ctrl.o into libgpio_led.a and links gpio_led_cli"        emit_diag "missing libgpio_led.a (with gpio_led_ctrl.o) or executable gpio_led_cli" "archive gpio_led_ctrl.o into libgpio_led.a and link gpio_led_cli in files/Makefile"    fi        LED="$WORKDIR/sys_led0"    mkdir -p "$LED"    printf '255\n' > "$LED/max_brightness"    printf '[heartbeat] timer none\n' > "$LED/trigger"    printf '0\n' > "$LED/brightness"        OUT=""    if [ -x "$WORKDIR/build/gpio_led_cli" ]; then        OUT="$("$WORKDIR/build/gpio_led_cli" "$LED" 2>&1 || true)"    fi    TRIG="$(cat "$LED/trigger" 2>/dev/null || true)"    BR="$(cat "$LED/brightness" 2>/dev/null || true)"        if [ "$TRIG" = "none" ] && [ "$BR" = "255" ]; then        echo "ok 3 - sysfs_led_set_manual detaches trigger to none and clamps brightness to 255"        PASS=$((PASS + 1))    else        echo "not ok 3 - sysfs_led_set_manual detaches trigger to none and clamps brightness to 255"        emit_diag "trigger='$TRIG' (expected 'none'), brightness='$BR' (expected '255')" "write 'none' to <led_dir>/trigger before writing clamped [0..max_brightness] to brightness"    fi        case "$OUT" in        *"mask=0x25 bits=0x21"*)            echo "ok 4 - gpio_v2_pack_values populates .mask=0x25 and .bits=0x21 atomically"            PASS=$((PASS + 1))            ;;        *)            echo "not ok 4 - gpio_v2_pack_values populates .mask=0x25 and .bits=0x21 atomically"            emit_diag "expected mask=0x25 bits=0x21 in '$OUT'" "set (1ULL << idx) in out->mask for every requested line and in out->bits when level != 0"            ;;    esac        if [ "$OUT" = "LED applied=255 mask=0x25 bits=0x21 accepted=3 seq_gaps=2" ]; then        echo "ok 5 - gpio_v2_debounce_accept drops <10ms contact bounce and counts kfifo seq_gaps=2"        PASS=$((PASS + 1))    else        echo "not ok 5 - gpio_v2_debounce_accept drops <10ms contact bounce and counts kfifo seq_gaps=2"        emit_diag "expected 'LED applied=255 mask=0x25 bits=0x21 accepted=3 seq_gaps=2', got '${OUT:-empty}'" "track line_seqno gaps before timestamp_ns >= last_accept_ns + debounce_ns filtering"    fi        printf '# pass %d/%d\n' "$PASS" "$TOTAL"    if [ "$PASS" -ne "$TOTAL" ]; then        printf 'FAIL: %d/%d TAP checks passed (inspect YAML diagnostics above)\n' "$PASS" "$TOTAL"        exit 1    fi    exit 0

Definition of done

Verification checklist

status: 0/3 checks verified

Troubleshooting

Compiler fails under -Werror on sign conversion or unused args

Use exact POSIX return types (ssize_t for read()/write(), size_t for byte counts) rather than relaxing flags.

./check.sh reports missing files in files/

Invoke ./check.sh from inside labs/lab_m01_gpio_led_ctrl/ so relative paths to files/ resolve directly.

Progress is saved on this device.

search — fzf

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

keyboard shortcuts — less

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

figure