Lab 1: Loadable Modules, User Copies & MMIO

60 minfree previewLinux 6.12C11U-Boot 2025.01← module 1

Build a failure-safe module contract with residual-count copies and masked register updates.

Prerequisites in this module

What ./check.sh verifies

  • Strict ISO C11 archive and executable build.
  • Repair the reported contract before submitting the lab.
step 1/15

step 1/15 · inspect starter files and specification

A module insertion fails after its second acquisition, but a later insertion reports the same resource busy. Returning the loader's error did not undo the first insertion's partial work. Cleanup must follow ownership even when no usable device ever appeared.

This studio joins acquisition rollback, residual-count copies and masked register updates into one inspectable contract. Predict which scenario first exposes a residual reported as bytes copied before editing. A warning-clean build is the starting condition, not evidence that a return value uses the correct unit.

learner@ksa: ~/gl-e04/lab-m01
learner@ksa:~/gl-e04/lab-m01ls -lastarter/Makefilestarter/benchmark.cstarter/contract.cstarter/contract.hstarter/verify.clearner@ksa:~/gl-e04/lab-m01
starter: starter/Makefile
learner@ksa: ~/gl-e04/lab-m01
learner@ksa:~/gl-e04/lab-m01$ bat starter/Makefile File: starter/Makefile    CC = gcc    override CFLAGS += -std=c11 -Wall -Wextra -Werror -O2 -pthread    .PHONY: all clean    all: verify benchmark    contract.o: contract.c contract.h    	$(CC) $(CFLAGS) -c contract.c -o $@    libcontract.a: contract.o    	ar rcs $@ $^    verify: verify.c libcontract.a contract.h    	$(CC) $(CFLAGS) verify.c libcontract.a -o $@    clean:    	rm -f verify benchmark contract.o libcontract.a        benchmark: benchmark.c verify.c libcontract.a contract.h    	$(CC) $(CFLAGS) benchmark.c libcontract.a -o $@
starter: starter/benchmark.c
learner@ksa: ~/gl-e04/lab-m01
learner@ksa:~/gl-e04/lab-m01$ bat starter/benchmark.c File: starter/benchmark.c    #define _POSIX_C_SOURCE 200809L    #include <inttypes.h>    #include <stdio.h>    #include <time.h>    static int quiet_puts(const char *s) { (void)s; return 0; }    #define puts quiet_puts    #define main contract_verify_main    #include "verify.c"    #undef main    #undef puts        static uint64_t now_ns(void)    {        struct timespec t;        if (clock_gettime(CLOCK_MONOTONIC, &t) != 0) {            perror("clock_gettime");            exit(2);        }        return (uint64_t)t.tv_sec * UINT64_C(1000000000) + (uint64_t)t.tv_nsec;    }    static int order(const void *a, const void *b)    {        uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b;        return (x > y) - (x < y);    }    int main(void)    {        enum { WARMUP = 5, SAMPLES = 40 };        uint64_t values[SAMPLES];        char *args[] = { "verify", "all", NULL };        for (unsigned i = 0; i < WARMUP; ++i)            if (contract_verify_main(2, args) != 0) return 1;        for (unsigned i = 0; i < SAMPLES; ++i) {            uint64_t start = now_ns();            if (contract_verify_main(2, args) != 0) return 1;            values[i] = now_ns() - start;        }        qsort(values, SAMPLES, sizeof values[0], order);        /* Nearest-rank quantiles: ceil(p * 40) - 1. */        printf("{\"clock\":\"CLOCK_MONOTONIC\",\"warmup\":%d,\"n\":%d,"               "\"unit\":\"ns per complete four-scenario suite\","               "\"p50\":%" PRIu64 ",\"p95\":%" PRIu64 ",\"p99\":%" PRIu64 ","               "\"min\":%" PRIu64 ",\"max\":%" PRIu64 ",\"samples_ns\":[",               WARMUP, SAMPLES, values[19], values[37], values[39],               values[0], values[39]);        for (unsigned i = 0; i < SAMPLES; ++i)            printf("%s%" PRIu64, i ? "," : "", values[i]);        puts("]}");        return 0;    }
starter: starter/contract.c
learner@ksa: ~/gl-e04/lab-m01
learner@ksa:~/gl-e04/lab-m01$ bat starter/contract.c File: starter/contract.c    /* GL-E04: preserve the API result's meaning before committing retained state.     * This is a native C11 contract model, not kernel or MMIO execution.     * Keep failure ownership visible; the immutable verifier names the invariant.     */    #include "contract.h"    #include <string.h>    int module_start(struct module_model *m, unsigned fail_at)    {        *m = (struct module_model){0};        for (unsigned stage = 1; stage <= 3; ++stage) {            if (stage == fail_at) {                for (unsigned undo = stage - 1; undo > 0; --undo)                    m->cleanup = m->cleanup * 10U + undo;                m->live = 0;                return -1;            }            m->live |= 1U << (stage - 1U);        }        return 0;    }    int module_stop(struct module_model *m)    {        if (m->refs != 0U) return -1;        for (unsigned undo = 3; undo > 0; --undo) {            if ((m->live & (1U << (undo - 1U))) != 0U)                m->cleanup = m->cleanup * 10U + undo;        }        m->live = 0;        return 0;    }    bool bytes_fit(size_t count, size_t width, size_t capacity)    {        return width == 0U || count <= capacity / width;    }    size_t copy_model(unsigned char *dst, const unsigned char *src,                      size_t requested, size_t accessible)    {        size_t copied = requested < accessible ? requested : accessible;        if (copied != 0U) memcpy(dst, src, copied);        return copied;    }    uint32_t mmio_update(uint32_t old, uint32_t mask, uint32_t value)    {        return (old & ~mask) | (value & mask);    }
starter: starter/contract.h
learner@ksa: ~/gl-e04/lab-m01
learner@ksa:~/gl-e04/lab-m01$ bat starter/contract.h File: starter/contract.h    #ifndef KSA_BOUNDARY_H    #define KSA_BOUNDARY_H    #include <stdbool.h>    #include <stddef.h>    #include <stdint.h>    struct module_model { unsigned live; unsigned refs; unsigned cleanup; };    int module_start(struct module_model *m, unsigned fail_at);    int module_stop(struct module_model *m);    bool bytes_fit(size_t count, size_t width, size_t capacity);    size_t copy_model(unsigned char *dst, const unsigned char *src,                      size_t requested, size_t accessible);    uint32_t mmio_update(uint32_t old, uint32_t mask, uint32_t value);    #endif
starter: starter/verify.c
learner@ksa: ~/gl-e04/lab-m01
learner@ksa:~/gl-e04/lab-m01$ bat starter/verify.c File: starter/verify.c    #include "contract.h"    #include <stdio.h>    #include <stdlib.h>    #include <string.h>    #include <limits.h>    #define CHECK(x) do { if (!(x)) { fprintf(stderr,"FAIL: line %d: %s\n",__LINE__,#x); return 1; } } while (0)    static int scenario_1(void)    {    struct module_model m;    CHECK(module_start(&m, 0) == 0 && m.live == 7U);    m.refs = 1; CHECK(module_stop(&m) == -1 && m.live == 7U);    m.refs = 0; CHECK(module_stop(&m) == 0 && m.cleanup == 321U);    puts("lifecycle: publication=7 busy-unload=rejected reverse=321");    return 0;    }    static int scenario_2(void)    {    unsigned char src[8] = {1,2,3,4,5,6,7,8}, dst[8] = {0};    CHECK(copy_model(dst, src, 8, 3) == 5);    CHECK(dst[2] == 3 && dst[3] == 0);    CHECK(copy_model(dst, src, 8, 0) == 8);    CHECK(copy_model(dst, src, 0, 0) == 0);    puts("uaccess: requested=8 copied=3 residual=5 zero=0");    return 0;    }    static int scenario_3(void)    {    CHECK(bytes_fit(8, 4, 32));    CHECK(!bytes_fit(9, 4, 32));    CHECK(!bytes_fit(SIZE_MAX, 2, 32));    CHECK(bytes_fit(SIZE_MAX, 0, 32));    uint32_t old = UINT32_C(0xa5a5a5a5);    CHECK(mmio_update(old, 8, 8) == (old | 8U));    CHECK(mmio_update(old, 8, 0) == (old & ~8U));    CHECK((mmio_update(old, 8, UINT32_MAX) & ~8U) == (old & ~8U));    puts("MMIO: mask=0x8 unrelated-bits=preserved overflow=rejected");    return 0;    }    static int scenario_4(void)    {    for (unsigned fail = 1; fail <= 3; ++fail) {        struct module_model m;        CHECK(module_start(&m, fail) == -1 && m.live == 0);        unsigned expected[] = {0,0,1,21};        CHECK(m.cleanup == expected[fail]);    }    puts("faults: failed-init stages=1,2,3 all resources unwound");    return 0;    }    int main(int argc, char **argv)    {    if (argc != 2) return 2;    if (strcmp(argv[1],"1") == 0) return scenario_1();    if (strcmp(argv[1],"2") == 0) return scenario_2();    if (strcmp(argv[1],"3") == 0) return scenario_3();    if (strcmp(argv[1],"4") == 0) return scenario_4();    if (strcmp(argv[1],"all") != 0) return 2;    return scenario_1() || scenario_2() || scenario_3() || scenario_4();    }

step 2/15 · 2. learning objectives

  • Build a failure-safe module contract with residual-count copies and masked register updates.
  • Diagnose the starter's semantic fault using the smallest distinguishing input.
  • Defend each return value and retained state across a partial failure.
  • Measure the supplied native workload and limit the conclusion to that workload.

step 3/15 · 3. environment requirements

Use an ordinary Linux host with a writable course-local working directory. No administrator privileges are needed: acquisition state, the bounded copy and the register mask run as a native C11 model. The target integration environment is 32-bit ARMv7-A Cortex-A7 with Linux 6.12 LTS, matching build configuration and board-specific firmware; no target module is built, loaded or unloaded in these captures.

step 4/15 · 4. required software and hardware

Install GCC, GNU Make, binutils ar, and a POSIX shell. The suite is single-threaded, while the benchmark additionally uses clock_gettime(CLOCK_MONOTONIC). Hardware is not required for the native model. A target board, serial console and a matching cross-toolchain are required only for a separately documented module load-and-unload experiment.

step 5/15 · 5. complete executable commands

Run from this lab's directory. Keep the canonical solution and tests unchanged:

learner@ksa: ~/gl-e04/lab-m01
learner@ksa:~/gl-e04/lab-m01$ bat script.sh File: script.sh    mkdir work    cp -R starter work/files    cp check.sh work/check.sh    cd work    sh check.sh    # Expected exit 1 and FAIL: the starter reports copied bytes as the residual.    make -C files clean all    ./files/verify all    # Repair the copy_model return value in work/files/contract.c;    # keep verify.c and its assertions unchanged.    sh check.sh    ./files/benchmark

To inspect the supplied solution from the lab root, run:

learner@ksa: ~/gl-e04/lab-m01
learner@ksa:~/gl-e04/lab-m01$ bat script.sh File: script.sh    make -C files clean all    sh check.sh    ./files/verify all    ./files/benchmark

step 6/15 · 6. annotated source code

starter/contract.c is complete, compilable and deliberately wrong in one semantic decision: copy_model() returns copied where the contract requires requested - copied, so an eight-byte request over three accessible bytes reports residual 3 instead of 5. files/contract.c implements the solution. The header documents the shared interface, while verify.c names the lifecycle, copy, MMIO and fault-injection scenarios. Read each CHECK as an invariant over its immediately preceding setup. benchmark.c reuses those same scenario functions with progress printing muted; it does not replace assertions with timing calls. Its warmup loop excludes first allocation and code-cache setup from the recorded sample set, but the separately captured build remains available.

step 7/15 · 7. expected output

The solution's checker emits the exact TAP envelope below: one strict build check plus four behavior checks covering acquisition rollback, the residual copy, the masked update and injected failures. The starter passes the build check but fails the residual-copy scenario, followed by FAIL:.

./check.sh — gl-c01
learner@ksa:~/gl-c01./check.shTAP version 131..5ok 1 - strict ISO C11 archive and executable buildok 2 - functional scenario 1ok 3 - functional scenario 2ok 4 - functional scenario 3ok 5 - functional scenario 4# pass 5/5

The measured values below are one actual host run, in nanoseconds per complete four-scenario suite covering rollback, residual copies, masked updates and fault injection. They are not grading thresholds.

SamplesWarmup suitesp50p95p99
40569 ns105 ns174 ns

step 8/15 · 8. explanation of observed behavior

A residual of five distinguishes requested bytes from transferred bytes. All three failed acquisition boundaries return live ownership to zero, and a retained reference rejects unload. The MMIO case changes a RAM word only, not a device register.

An assertion failure identifies an input and a violated relation, not necessarily the faulty line. Write down requested bytes, accessible bytes, the value returned and the bytes actually mutated. Compare those four observations with the residual contract before changing the return expression.

step 9/15 · 9. experiment variations

  1. Repeat the eight-byte request with accessible lengths of zero, three and eight, predicting each residual.
  2. Move failure injection to every acquisition boundary and predict the cleanup ledger before each run.
  3. Run a failed insertion followed by a successful one; predict whether the partially acquired resources remain owned.
  4. Flip one mask bit in the MMIO scenario and predict which assertion observes the lost unrelated bits without weakening any original check.

step 10/15 · 10. performance measurements

Run ./files/benchmark as a fresh process. It performs five warmup suites and 40 measured suites of the lifecycle, copy, MMIO and fault-injection scenarios using CLOCK_MONOTONIC, sorts raw samples and uses nearest-rank quantiles: indexes 19, 37 and 39 for p50, p95 and p99. Raw values, units, host kernel and strict build transcript are retained in measurements.json.

The workload includes all four scenario functions, including the adversarial fault-injection loop. Each suite is short arithmetic and branch work, so timer-read overhead is a material fraction of every sample. No subtraction estimates an imaginary hardware latency. Repeat under explicit load and report both distributions rather than declaring a single noisy number a regression. With only 40 samples p99 is the maximum, not a reliable rare-tail estimate. Use at least 1000 samples before interpreting a target p99.

step 11/15 · 11. troubleshooting instructions

SymptomRoot cause to investigateFix
Build check failsToolchain, headers or an introduced warningRestore the strict build before reasoning about runtime
Starter unexpectedly passesWrong working files or weakened assertionsConfirm work/files contains the supplied starter and retain every check
Only the copy scenario failsReturn unit confused: copied versus not-copiedReturn requested - copied and recheck zero and full transfers
Unload scenario fails after repairRollback released a stage that was never acquiredRelease only completed stages in reverse order
Timing varies widelyScheduling, frequency or a different workloadRecord environment and samples; do not invent a target explanation

step 12/15 · 12. guided questions and hint ladder

Replace the displayed accessible length with five while keeping an eight-byte request. Predict the residual, the first unchanged destination byte and whether a command may commit. Hint 1: subtract progress from request. Hint 2: bytes in a temporary buffer are not yet device state.

Which observation separates returning copied from returning requested - copied on the same input? Hint 1: state the API's result unit. Hint 2: trace the eight-over-three copy and compare destination bytes and the returned number. After a repair, explain why the zero-length and full-length requests still return zero residual.

step 13/15 · 13. independent challenges

Design a register-access review for an ordinary control register and a write-one-to-clear status register. State the resource owner and teardown ordering without assuming a physical address. Far transfer: compare a configuration update with an acknowledgement message whose bits consume events.

Submit a changed-input prediction, a new adversarial check and a rationale without consulting the solution first: for example a request larger than the destination, or an accessible length that changes mid-command. Include a disconfirming observation that would force you to revise the design. Your target transfer plan must name the actual user-copy API, the commit point for the device command and the missing hardware measurement.

step 14/15 · 14. solutions and explanations

After submitting the independent attempt, compare starter/contract.c with files/contract.c. The solution preserves these module-specific mechanisms: A residual of five distinguishes requested bytes from transferred bytes. All three failed acquisition boundaries return live ownership to zero, and a retained reference rejects unload. The MMIO case changes a RAM word only, not a device register.

The canonical solution passes every immutable scenario, not only the starter's failing copy check. captures.json contains actual failing starter and passing solution checks, exit codes and the measurement command. A host pass certifies this ownership-and-residual model only. No target module was built or loaded, no user-copy exception path was exercised and no peripheral observed a masked write.

Use this four-level evidence rubric: 0 changes expected answers or has no reproducer; 1 repairs the residual without a state argument; 2 passes all checks and explains rollback ownership across injected failures; 3 additionally supplies an independent counterexample, a justified copy-fault transfer plan and honest measurement limits.

step 15/15 · run verification and inspect output

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

learner@ksa: ~/gl-e04/lab-m01
learner@ksa:~/gl-e04/lab-m01./files/verify alllearner@ksa:~/gl-e04/lab-m01
expected output
lifecycle: publication=7 busy-unload=rejected reverse=321uaccess: requested=8 copied=3 residual=5 zero=0MMIO: mask=0x8 unrelated-bits=preserved overflow=rejected

Progressive hints & solution

hint 1

Compare starter/Makefile against the module lessons. Focus first on: Strict ISO C11 archive and executable build.

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_chrdev_mmio_copy/, 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-e04/lab-m01./check.shTAP version 131..5ok 1 - strict ISO C11 archive and executable buildok 2 - functional scenario 1ok 3 - functional scenario 2ok 4 - functional scenario 3ok 5 - functional scenario 4# 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-e04/lab-m01./check.shTAP version 131..5ok 1 - strict ISO C11 archive and executable buildok 2 - functional scenario 1not ok 3 - functional scenario 2  ---  message: 'Restore scenario 2 contract; run files/verify 2 for the failing assertion'  ...ok 4 - functional scenario 3ok 5 - functional scenario 4# pass 4/5

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-e04/lab-m01
learner@ksa:~/gl-e04/lab-m01$ bat check.sh File: check.sh    #!/bin/sh    set -u    cd "$(dirname "$0")" || exit 1    work=$(mktemp -d "$PWD/.check.XXXXXX") || exit 1    trap 'rm -rf "$work"' EXIT HUP INT TERM    pass=0    printf 'TAP version 13\n1..5\n'    if cp -R files "$work/build" && make -C "$work/build" clean all >"$work/build.log" 2>&1; then        printf 'ok 1 - strict ISO C11 archive and executable build\n'        pass=$((pass+1))    else        printf 'not ok 1 - strict ISO C11 archive and executable build\n'        printf "  ---\n  message: 'Restore the warning-clean library and CLI build'\n  ...\n"    fi    for scenario in 1 2 3 4; do        number=$((scenario+1))        if "$work/build/verify" "$scenario" >"$work/case.log" 2>&1; then            printf 'ok %d - functional scenario %d\n' "$number" "$scenario"            pass=$((pass+1))        else            printf 'not ok %d - functional scenario %d\n' "$number" "$scenario"            printf "  ---\n  message: 'Restore scenario %s contract; run files/verify %s for the failing assertion'\n  ...\n" "$scenario" "$scenario"        fi    done    printf '# pass %d/5\n' "$pass"    if [ "$pass" -ne 5 ]; then        printf 'FAIL: repair the reported contract before submitting the lab\n' >&2        exit 1    fi

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_chrdev_mmio_copy/ 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