Lab 1: Lab M01: Sysfs LED Controller and GPIO v2 Debounced Line Engine
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_manualdetaches trigger to none and clamps brightness to 255.gpio_v2_pack_valuespopulates .mask=0x25 and .bits=0x21 atomically.
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-m01ls -lastarter/Makefilestarter/gpio_led_cli.cstarter/gpio_led_ctrl.cstarter/gpio_led_ctrl.hlearner@ksa:~/gl-c04/lab-m01starter: starter/Makefile
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_clistarter: starter/gpio_led_cli.c
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$ 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$ 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); #endifstep 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>/triggerviaopenat(2)before clamping requested brightness to[0, max_brightness]. - Construct atomic
struct gpio_v2_line_valuespayloads setting(1ULL << req_idx)in.maskfor every targeted line and in.bitsfor logic-high levels. - Implement monotonic
CLOCK_MONOTONICcontact-bounce suppression (timestamp_ns >= last_accept_ns + debounce_ns) while unconditionally trackingline_seqnodiscontinuities across kernelkfiforeads. - Measure end-to-end
p50,p95, andp99execution latency withCLOCK_MONOTONICand explain the VFS syscall cost boundary betweensysfsattribute writes and in-RAMgpio_v2struct packing.
step 4/16 · 3. environment requirements
- Operating System: Linux 6.x (
x86_64oraarch64development workstation or container) exposing Linux 6.12 UAPI<linux/gpio.h>. - Compiler & Archive Toolchain:
gccsupporting-std=c11 -Wall -Wextra -Werror, GNUmake, andar/ranlib(binutils). - Diagnostics:
strace(>= 5.x) for inspectingopenat,read, andwriteVFS syscall counts. - Privileges: Unprivileged user account (
0root or/dev/gpiochip0hardware permissions required for the deterministic host harness).
step 5/16 · 4. required software and hardware
- Host Simulation Harness (Required):
check.shandgpio_led_clisynthesize a real POSIX directory (sys_led0/containingmax_brightness,trigger, andbrightness) and feed exact<linux/gpio.h>struct gpio_v2_line_valuesandstruct gpio_v2_line_eventpayloads 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, andpoll(POLLIN)edge events). On target hardware,sysfs_led_set_manual("/sys/class/leds/status", 255, &applied)operates directly on the kernelleds-gpiodriver 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$ 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_led0step 7/16 · 6. annotated source code
Flawed starter/gpio_led_ctrl.c Baseline (3 Intentional Defects):
sysfs_led_set_manual()writes rawreq_brightness(999) directly tobrightnesswithout readingmax_brightness(255) or writing"none"totrigger.gpio_v2_pack_values()setsout->bits |= (1ULL << req_indices[i])whenlevels[i] != 0, leavingout->mask == 0x00so the kernel ignores all 3 pins.gpio_v2_debounce_accept()casts(void)debounce_nsand(void)seq_gaps_out, accepting sub-10 ms bounce noise (accepted=5) and reportingseq_gaps=0across the3 -> 6line_seqnojump.
Warning-Clean files/gpio_led_ctrl.c Reference Architecture:
- Directory-relative
openat(2)(lines 9-68): Opensled_dironce withO_RDONLY | O_DIRECTORY | O_CLOEXEC, readsmax_brightnessviastrtol, writes"none"totrigger(O_WRONLY | O_TRUNC | O_CLOEXEC), clampsreq_brightnessinto[0, max_b], and writes the ASCII integer tobrightness. - 64-bit request-index bitpacking (
lines 70-82): Zeroes*outwithmemset, guardsreq_indices[i] < 64u, and setsuint64_t bit = 1ULL << req_indices[i]inout->maskunconditionally while settingout->bits |= bitonly whenlevels[i] != 0(idx={0,2,5},lvl={1,0,1}->mask=0x25,bits=0x21). - Sequence-first debounce state machine (
lines 84-98): Checksev->line_seqno > *expected_line_seqbefore evaluating thedebounce_nswindow sokfifodrops 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$ 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/5Direct CLI Output (./files/gpio_led_cli ./sys_led0):
learner@ksa:~/gl-c04/lab-m01$ bat listing.txt File: listing.txt LED applied=255 mask=0x25 bits=0x21 accepted=3 seq_gaps=2Host 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
applied=255:gpio_led_clirequestsreq_brightness = 999againstmax_brightness = 255;sysfs_led_set_manual()detaches[heartbeat]by writing"none"totriggerand clamps the written value to255.mask=0x25 bits=0x21: Request indices{0, 2, 5}map to bits2^0 + 2^2 + 2^5 = 1 + 4 + 32 = 37 = 0x25in.mask. Because index2has desired level0while indices0and5have level1,.bits = 2^0 + 2^5 = 33 = 0x21.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) arrive2.5 msand6.0 msafter Event 1 (< 10.0 msdebounce window) and are suppressed. Event 4 (125.0 ms,seq=6) jumps from expectedseq=4to6(seq_gaps += 2) and is25.0 ms >= 10.0 mspast100.0 ms, so it is accepted (last_ns = 125.0 ms). Event 5 (150.0 ms,seq=7) arrives25.0 mslater 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_LOWawareness in user-space diagnostics: verify that withACTIVE_LOWset duringGPIO_V2_GET_LINE_IOCTL,bits = 0x21represents logical assertion (1 = active) while the kernelgpiolibhardware driver drives physical0 Von indices0and5. - Far Transfer (Per-Offset Independent Debounce Table): Extend
gpio_v2_debounce_accept()into a multi-line tracker indexed byev->offset(struct line_state states[64]) so a4-button keypad sharing onereq.fdtrackslast_accept_nsandline_seqnoindependently per pin while cross-checkingev->seqnofor aggregatereq.fdkfifodrops.
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:
| Metric | Measured Host Value | Kernel Mechanism Accounting for Cost |
|---|---|---|
BENCH p50 latency | 57,059 ns (57.1 us) | 1 directory open + 3 openat/read-or-write/close sysfs VFS cycles |
BENCH p95 latency | 66,094 ns (66.1 us) | dentry/inode lock acquisition and tmpfs page-cache writeback |
BENCH p99 latency | 176,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
| Symptom | Root Cause | Fix |
|---|---|---|
not ok 3 with trigger="[heartbeat] timer none" | sysfs_led_set_manual() wrote brightness without detaching trigger first | Write "none" (4 bytes, no brackets) to trigger before writing brightness |
not ok 4 with mask=0x00 bits=0x21 | Only 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=0 | Placed if (ev->timestamp_ns < ...) before line_seqno gap calculation | Always update seq_gaps_out and *expected_line_seq = ev->line_seqno + 1u before returning 0 on bounce |
Compiler error on 1ULL << 64 | Unchecked req_indices[i] >= 64u triggers C11 shift-width UB | Guard loop body with if (req_indices[i] < 64u) (GPIO_V2_LINES_MAX == 64) |
step 13/16 · 12. guided questions
- Question: Why does
gpio_v2_pack_values()shift byreq_indices[i](0..63position insidereq.offsets[]) rather than the hardware GPIO bank pin offset (for example pin18or23)?
- *Hint 1:* Inspect
<linux/gpio.h>comments onstruct gpio_v2_line_valuesand howGPIO_V2_GET_LINE_IOCTLorders lines inreq.offsets[0..num_lines-1]. - *Hint 2:* Consider a GPIO controller with 128 lines: a 64-bit
.maskcould not address pin95by bank offset, whereasreq.num_lines <= 64maps every claimed line to0..63.
- Question: Why does
sysfs_led_set_manual()openled_dirwithO_RDONLY | O_DIRECTORY | O_CLOEXECand useopenat(dfd, ...)instead of threesnprintf("%s/...", ...)calls?
- *Hint 1:* What happens if
led_diris a/sys/class/leds/statussymlink 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
- Multi-Event Batch
read()Loop: Write a helperssize_t gpio_v2_drain_fd(int req_fd, uint64_t *last_ns, uint32_t *exp_seq, uint64_t debounce_ns, uint32_t *gaps)that readsstruct gpio_v2_line_event buf[16]in oneread(2)call (sizeof(buf) == 16 * 48 == 768bytes), handles-1witherrno == EAGAIN, verifies(r % sizeof(struct gpio_v2_line_event)) == 0, and returns the count of debounced edges. - Hardware Debounce Fallback: Construct a
struct gpio_v2_line_requestinitializer requestingGPIO_V2_LINE_ATTR_ID_DEBOUNCE(debounce_period_us = 10000); ifioctl(chip_fd, GPIO_V2_GET_LINE_IOCTL, &req)returns-1witherrno == EINVALorENOTSUP, fall back automatically to softwaregpio_v2_debounce_accept().
step 15/16 · 14. solutions and explanations
- Guided Question 1 Solution:
struct gpio_v2_line_valuesbits0..63index thereq.offsets[]array passed whenreq.fdwas created (GPIO_V2_LINES_MAX = 64). Even if a GPIO bank exposes 160 pins, any singlereq.fdholds at most 64 lines, allowing.maskand.bitsto update any subset of those 64 lines atomically in a singleuint64_tpair. - Guided Question 2 Solution:
open(led_dir, O_RDONLY | O_DIRECTORY | O_CLOEXEC)pins the targetkobjectdirectory inode once, avoids fixed-buffer truncation risks, prevents file-descriptor leaks acrossfork+exec(O_CLOEXEC), and skips redundant VFS path-walk lookups acrossmax_brightness,trigger, andbrightness. - Challenge 1 Key Invariant: Never
read()fewer thansizeof(struct gpio_v2_line_event)(48bytes); the kernellinereq_read()driver returns-EINVALif the user buffer is smaller than one complete event record, and batching16events drains a full defaultkfifoin 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./files/gpio_led_cli ./sys_led0learner@ksa:~/gl-c04/lab-m01LED applied=255 mask=0x25 bits=0x21 accepted=3 seq_gaps=2Progressive 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
warning: Reveal the reference solution files? Running ./check.sh against your own attempt first builds stronger retention.
solution: files/Makefile
learner@ksa:~/gl-c04/lab-m01$ bat files/Makefile File: files/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_clisolution: files/gpio_led_cli.c
learner@ksa:~/gl-c04/lab-m01$ bat files/gpio_led_cli.c File: files/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; }solution: files/gpio_led_ctrl.c
learner@ksa:~/gl-c04/lab-m01$ bat files/gpio_led_ctrl.c File: files/gpio_led_ctrl.c #define _GNU_SOURCE #include "gpio_led_ctrl.h" #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> static int write_attr_str(int dirfd, const char *name, const char *val) { int fd = openat(dirfd, name, O_WRONLY | O_TRUNC | O_CLOEXEC); if (fd < 0) return -1; size_t n = strlen(val); ssize_t w = write(fd, val, n); close(fd); return (w == (ssize_t)n) ? 0 : -1; } static int read_attr_int(int dirfd, const char *name, int *out) { int fd = openat(dirfd, name, O_RDONLY | O_CLOEXEC); if (fd < 0) return -1; char buf[64]; ssize_t r = read(fd, buf, sizeof(buf) - 1u); close(fd); if (r <= 0) return -1; buf[r] = '\0'; *out = (int)strtol(buf, NULL, 10); return 0; } int sysfs_led_set_manual(const char *led_dir, int req_brightness, int *applied_out) { if (!led_dir || !applied_out) return -1; int dfd = open(led_dir, O_RDONLY | O_DIRECTORY | O_CLOEXEC); if (dfd < 0) return -1; int max_b = 0; if (read_attr_int(dfd, "max_brightness", &max_b) < 0 || max_b < 0) { close(dfd); return -1; } if (write_attr_str(dfd, "trigger", "none") < 0) { close(dfd); return -1; } int clamped = req_brightness; if (clamped < 0) clamped = 0; if (clamped > max_b) clamped = max_b; char num[32]; snprintf(num, sizeof(num), "%d", clamped); if (write_attr_str(dfd, "brightness", num) < 0) { close(dfd); return -1; } close(dfd); *applied_out = clamped; 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) { memset(out, 0, sizeof(*out)); for (size_t i = 0; i < count; ++i) { if (req_indices[i] < 64u) { uint64_t bit = 1ULL << req_indices[i]; out->mask |= bit; if (levels[i]) out->bits |= bit; } } } 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) { if (*expected_line_seq != 0u && ev->line_seqno > *expected_line_seq) *seq_gaps_out += (ev->line_seqno - *expected_line_seq); *expected_line_seq = ev->line_seqno + 1u; if (*last_accept_ns != 0ULL && ev->timestamp_ns < *last_accept_ns + debounce_ns) return 0; *last_accept_ns = ev->timestamp_ns; return 1; }solution: files/gpio_led_ctrl.h
learner@ksa:~/gl-c04/lab-m01$ bat files/gpio_led_ctrl.h File: files/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); #endifRun 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:
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/5On an incomplete starter tree, ./check.sh exits non-zero and marks the unmet assertion not ok with an indented YAML diagnostic block:
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$ 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 0Definition 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.