User Copies, Residual Counts & Overflow-Safe Bounds

Cross the Ring-3/Ring-0 boundary safely on ARMv7-A Linux 6.12: understand CP15 domain isolation and __ex_table fault fixup, decode unsigned copy residuals, block 32-bit size_t multiplication wraparound, and stage commands before hardware commit.

20 minfree previewLinux 6.12C11U-Boot 2025.01→ module 1 lab
What you'll learn
  • Given a driver trace, compute residual and successful byte counts for partial user copies.
  • Given a driver trace, reject oversized requests before multiplication or buffer access.
  • Given a driver trace, diagnose why a partial command must not update device state.

Why Ring-0 Drivers Cannot Dereference User Virtual Pointers Directly

When a user-space process invokes write(fd, buf, 8), your driver's .write callback executes in Ring 0 (SVC mode) and receives const char __user *user = buf. Since Ring 0 is privileged and TTBR0 still maps the calling task's 0x0000_0000 .. 0xBEFF_FFFF user space, why can't a driver simply read unsigned char cmd = *user;? Because a user virtual address is an untrusted numeric claim, not a validated kernel buffer! Even if user != NULL, the buffer can point into kernel space (>= 0xBF00_0000), point to a swapped-out page on flash, be concurrently munmap()-ed by another thread, or straddle a 4 KiB page boundary (0x76F0_0FFD .. 0x76F0_1004) where the first 3 bytes sit in valid RAM and the remaining 5 bytes hit an unmapped guard page!

Trace Figure 1.2a to see what happens in silicon and in the Linux kernel across that boundary:

  1. __user is compile-time documentation, not runtime armor: Defined for sparse (C=1) as __attribute__((noderef, address_space(1))), __user emits zero ARM instructions.
  2. Software Domain Isolation (CPU_SW_DOMAIN_PAN) & __ex_table Fault Recovery: Cortex-A7 (ARMv7-A) predates ARMv8.1 hardware PAN (Privileged Access Never). Instead, classic ARM32 Linux configures CP15 Domain Access Control (DACR) so user pages (Domain 1) are marked No Access during normal kernel execution (catching accidental raw *user dereferences, though configurations without domain PAN silently read/corrupt mapped user pages—making raw dereference a security bug, not a reliable crash test!). Inside copy_from_user(dst, user, 8), the helper checks access_ok(), temporarily enables Domain 1 client access, and executes load instructions whose exact PC addresses are recorded in the ELF __ex_table exception table. If byte 3 faults on unmapped 0x76F0_1000 (after handle_mm_fault() confirms it is not a valid swapped page), do_DataAbort() looks up the faulting PC in __ex_table, jumps to .fixup instead of triggering a Kernel Oops, zeros uncopied destination bytes, and returns the unsigned residual count 5 (requested 8 - copied 3)!
fig_m01_l02_a.svg — Crossing the Ring-3 / Ring-0 boundary — CP15 DACR…

Figure 1.2a. Crossing the Ring-3 / Ring-0 boundary — CP15 DACR domain gating, __ex_table fault recovery, staging prefix mutation, and residual byte return.

mental model: A freight courier returning 5 undelivered crates from an 8-crate manifest reports what remains uncopied (residual = 5), not the 3 crates unloaded onto the staging dock—and you never actuate hardware from a half-delivered command packet.

Where it stops working: Unlike sealed crates, a partial copy_from_user() has already overwritten a prefix of your kernel staging buffer and may sleep resolving valid user page faults.

definition (User-Access Residual Counts, __user Annotation & Overflow-Safe Staging): copy_from_user(to, from, n) and copy_to_user(to, from, n) transfer up to n bytes across the user/kernel boundary in sleepable process context and return the unsigned number of bytes NOT copied (0 means complete n-byte transfer; 1..n means fault after n - residual bytes). __user marks untrusted user-space pointers for static analysis without validating mappings at runtime. check_mul_overflow(count, width, &bytes) (or division count <= capacity / width) blocks size_t multiplication wraparound before allocation or copying, and transactional staging mutates hardware state only after a complete (residual == 0), range-checked copy into kernel-owned memory.

Step through the four-stage validation, staging, and commit pipeline below:

ast_m01_l02.svg — Validate count and overflow bounds first, stage user…step 1/4
  1. Step 1. Step 1: Treat the incoming __user pointer and count as untrusted claims; handle count == 0 cleanly.
  2. Step 2. Step 2: Reject oversized or wrapping count * width requests BEFORE multiplying or touching memory.
  3. Step 3. Step 3: Run copy_from_user() into kernel staging outside spinlocks; abort (-EFAULT) if residual != 0.
  4. Step 4. Step 4: Validate command fields in staging RAM before acquiring the device lock to commit state.

Figure 1.2b. Validate count and overflow bounds first, stage user bytes in process context, check residual == 0, and commit only validated commands.

Defeating 32-Bit size_t Multiplication Wrap & Sleeping-Under-Spinlock Bugs

Inspect Figure 1.2b before writing array or frame ioctls on 32-bit ARMv7-A, where size_t is 32 bits wide (0xFFFF_FFFF max). If user space requests count = 0x4000_0002 elements of width = 4 bytes and your driver checks if (count * width > 32), the 32-bit ALU wraps 0x4000_0002 * 4 modulo 2^32 to 8 bytes! The 8 <= 32 check passes, kmalloc(8, GFP_KERNEL) succeeds, and the subsequent loop corrupts gigabytes of kernel heap! Calling <linux/overflow.h>'s check_mul_overflow(count, width, &bytes) (or testing count <= capacity / width for width > 0) catches the overflow before any product wraps.

Two additional rules govern ksa_write() in target.c:

  1. Never hold a spinlock across copy_from_user() / copy_to_user(): Even when a user pointer is completely valid, its physical page may currently sit in swap or an mmap-ed file; handle_mm_fault() sleeps waiting for storage I/O, which is illegal inside a non-sleeping spin_lock_irqsave() critical section! Always copy into a bounded kernel variable (command) first, validate command <= 1, and acquire the device lock only around the final commit.
  2. All-or-error command policy vs stream short counts: Byte-stream .read/.write FIFOs sometimes return a positive short ssize_t (requested - residual) if partial bytes transferred, whereas a binary device command (ksa_write) must be atomic: any residual != 0 returns -EFAULT without touching hardware!
fig_m01_l02_b.svg — How 32-bit count * width wraps past naive bounds checks…

Figure 1.2b. How 32-bit count * width wraps past naive bounds checks (left), overflow-safe guards (right), and unsigned residual vs signed VFS ssize_t contracts (bottom).

Boundary / OperationNaive Broken IdiomLinux 6.12 Safe IdiomFailure Prevented
Pointer dereferencecmd = *user; after user != NULLcopy_from_user(&cmd, user, sizeof(cmd))Kernel Oops or SW_DOMAIN_PAN bypass
Array byte sizeif (count * width > cap)`check_mul_overflow(count, width, &b) \\b > cap`32-bit size_t wrap -> heap corruption
Partial command copyCommit prefix when copied > 0if (residual != 0) return -EFAULT; before commitExecuting half-written actuator command
Locking vs page faultspin_lock_irqsave around copyStage on stack -> validate -> lock -> commitScheduling-while-atomic crash on page fault
learner@ksa: ~/gl-e04/m01-l02
learner@ksa:~/gl-e04/m01-l02$ bat -H 15 -H 16 -H 26 target.c File: target.c    #include <linux/errno.h>    #include <linux/fs.h>    #include <linux/overflow.h>    #include <linux/uaccess.h>        static ssize_t ksa_write(struct file *file, const char __user *user,                             size_t count, loff_t *offset)    {        unsigned char command;        (void)file;        (void)offset;        if (count == 0)            return 0;        if (count != sizeof(command))          return -EINVAL;        if (copy_from_user(&command, user, sizeof(command)) != 0)            return -EFAULT;        if (command > 1)            return -EINVAL;        /* Commit a validated command under the device's process-context lock. */        return sizeof(command);    }        static int ksa_array_bytes(size_t count, size_t width, size_t capacity,                               size_t *bytes)  {        if (check_mul_overflow(count, width, bytes) || *bytes > capacity)            return -E2BIG;        return 0;    }
  1. copy_from_user() runs in process context outside any spinlock; any non-zero residual returns -EFAULT before reaching the commit step.
  2. check_mul_overflow() detects 32-bit size_t wraparound before comparing *bytes against capacity.

Verifying Residual Math, Prefix Mutation & Overflow Guards on the Host

In verify.c, copy_model(dst, src, requested, accessible) models copy_from_user()'s exact byte accounting: given requested = 8 and accessible = 3, it copies 3 bytes into dst[0..2], leaves dst[3..7] untouched, and returns residual = 5 (8 when accessible = 0, and 0 when requested = 0). Next, bytes_fit(count, width, capacity) uses division (count <= capacity / width) to reject 9 * 4 > 32 and SIZE_MAX * 2 without overflowing, and proves committed stays 0 on residual == 5 while incrementing to 1 only when residual == 0.

learner@ksa: ~/gl-e04/m01-l02
learner@ksa:~/gl-e04/m01-l02$ bat -H 19 -H 25 -H 26 -H 27 -H 46 -H 47 -H 48 verify.c File: verify.c    /* m01-l02 / user-copy residual and capacity: native model, not a loaded Linux driver. */    #include <stdbool.h>    #include <stddef.h>    #include <stdint.h>    #include <stdio.h>    #include <stdlib.h>    #include <string.h>    #include <limits.h>    #include <errno.h>    #include <stdatomic.h>    #include <threads.h>        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);        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 requested - copied;    }        #define CHECK(x) do { if (!(x)) { fprintf(stderr, "check failed at line %d: %s\n", __LINE__, #x); return EXIT_FAILURE; } } while (0)    int main(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");    }    {    CHECK(bytes_fit(8,4,32) && !bytes_fit(9,4,32));    CHECK(!bytes_fit(SIZE_MAX,2,32) && bytes_fit(SIZE_MAX,0,32));    unsigned char src[8]={1,2,3,4,5,6,7,8}, staged[8]={0};    unsigned committed=0;    size_t residual=copy_model(staged,src,8,3);  if (residual == 0) ++committed;    CHECK(residual == 5 && committed == 0 && staged[3] == 0);    residual=copy_model(staged,src,8,8);    if (residual == 0) ++committed;    CHECK(residual == 0 && committed == 1 && staged[7] == 8);    puts("capacity: overflow rejected; partial staging cannot commit command");    }    return EXIT_SUCCESS;    }
  1. Division capacity / width checks the exact element ceiling without forming a wrapping count * width product.
  2. Return requested - copied (the uncopied residual), matching Linux copy_from_user() / copy_to_user().
  3. Staging buffer staged[0..2] was already mutated during the partial copy, yet committed remains 0 because residual == 5 != 0.

Running the Residual & Overflow Verifier

Compile and run verify.c. Keep the host/target proof distinction sharp: verify proves residual arithmetic, overflow-free quotient bounds, and staging-before-commit invariants in user RAM, whereas exercising real __ex_table Data Abort recovery requires passing an mmap(..., PROT_NONE) boundary pointer to the loaded .ko on the ARMv7-A target and confirming both -EFAULT and unchanged hardware state.

learner@ksa: ~/gl-e04/m01-l02
learner@ksa:~/gl-e04/m01-l02gcc -std=c11 -Wall -Wextra -Werror -O2 -pthread verify.c -o verifylearner@ksa:~/gl-e04/m01-l02./verifyuaccess: requested=8 copied=3 residual=5 zero=0capacity: overflow rejected; partial staging cannot commit commandlearner@ksa:~/gl-e04/m01-l02echo $?0learner@ksa:~/gl-e04/m01-l02readelf -h verifyELF Header:  Magic:   7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00   Class:                             ELF64  Data:                              2's complement, little endian  Version:                           1 (current)  OS/ABI:                            UNIX - System V  ABI Version:                       0  Type:                              DYN (Position-Independent Executable file)  Machine:                           Advanced Micro Devices X86-64  Version:                           0x1  Entry point address:               0x1270  Start of program headers:          64 (bytes into file)  Start of section headers:          14232 (bytes into file)  Flags:                             0x0  Size of this header:               64 (bytes)  Size of program headers:           56 (bytes)  Number of program headers:         13  Size of section headers:           64 (bytes)  Number of section headers:         31  Section header string table index: 30learner@ksa:~/gl-e04/m01-l02
strace — learner@ksa: ~/gl-e04/m01-l02
learner@ksa:~/gl-e04/m01-l02strace -e trace=write,exit_group ./verifywrite(1, "uaccess: requested=8 copied=3 re"..., 115) = 115exit_group(0)                           = ?+++ exited with 0 +++

Read-Side Snapshots, access_ok() Myths & Lifetime Isolation

Apply the exact mirror discipline on .read (copy_to_user()): under your lock, copy device fields into a fully zero-initialized kernel stack struct (struct ksa_status snap = {0}; so struct padding bytes never leak kernel stack secrets!), release the spinlock, and then call copy_to_user(user, &snap, sizeof(snap)) in sleepable process context. Never treat access_ok(user, n) as permission to dereference *user directly (access_ok only checks the TASK_SIZE address ceiling—it neither maps pages nor installs an __ex_table fixup!), and never store a __user pointer inside driver state for later use after .write returns. Later: Lesson m01-l03 moves to the hardware side of that commit boundary (ioremap, readl/writel, and W1C registers), and Module m06 preserves FIFO events across failed copy_to_user() deliveries.

Common Production Pitfalls

warning: Symptom: A user test passes a buffer straddling an unmapped PROT_NONE page (write returns -EFAULT), yet the board LED still toggles to a corrupted state! Root Cause: The driver copied directly into its live state struct (or actuated hardware before checking copy_from_user() != 0), allowing the 3-byte prefix copied prior to the fault to mutate live state. Fix: Copy into a separate temporary staging variable in process context, verify residual == 0 and field validity, and only then commit to live driver state.

warning: Symptom: Enabling CONFIG_DEBUG_ATOMIC_SLEEP logs BUG: sleeping function called from invalid context inside .read or .write under memory pressure. Root Cause: The driver called copy_to_user() or copy_from_user() while holding spin_lock_irqsave(), and a valid user buffer page faulted into handle_mm_fault() to page in from storage. Fix: Stage user copies outside spinlocked critical sections (or use a sleeping mutex when synchronizing purely process-context state).

Practice & Retrieval

Guided Practice: Computing Residuals & Staging Bytes

Suppose user space calls write(fd, ubuf, 8) where 5 bytes sit before an unmapped page boundary (accessible = 5). Predict: (1) the exact unsigned value returned by copy_from_user(staged, ubuf, 8) (8 - 5 = 3), (2) which indices of staged[0..7] hold user bytes (staged[0..4]) versus zeroed fixup padding (staged[5..7]), and (3) what ssize_t an atomic 8-byte command parser must return (-EFAULT, with 0 hardware writes!).

Independent Practice: Adversarial Page-Boundary Test Harness (uaccess_boundary_test.c)

Write a POSIX user-space test uaccess_boundary_test.c using mmap(NULL, 8192, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0) followed by mprotect((char *)p + 4096, 4096, PROT_NONE) to place a 16-byte command at (char *)p + 4090 (6 accessible bytes + 10 faulting bytes), and pair it with a host parser proving bytes_fit() rejects (0x40000002U, 4U, 64U) on 32-bit arithmetic.

quiz · 1 of 3

copy_from_user(staged, user, 8) returns 5. What happened during the transfer?

quiz · 2 of 3

Which check safely rejects an oversized array of count elements of width > 0 bytes against capacity without suffering size_t multiplication wraparound?

quiz · 3 of 3

Retrieval: why is qualifying a parameter with __user insufficient to make unsigned char v = *user; safe inside a Ring 0 ARMv7-A driver callback?

Key takeaways

  • copy_from_user() and copy_to_user() return bytes not copied (0 = complete transfer); on ARMv7-A Linux 6.12 they pair CP15 DACR domain gating with __ex_table fault fixups so bad user pointers return residuals instead of crashing the kernel.
  • __user is a static sparse address-space tag, not runtime validation, and user-copy helpers may sleep on page faults—never invoke them inside a spinlock!
  • Prevent 32-bit size_t multiplication wraparound with check_mul_overflow(count, width, &bytes) (or count <= capacity / width) before allocating or copying.
  • Stage incoming commands in kernel memory and mutate hardware only after residual == 0 and domain validation pass. Later: Lesson m01-l03 maps physical peripheral registers via ioremap() and readl()/writel().
  • copy_to_user() and copy_from_user() return bytes not copied; zero means complete success rather than zero progress.
  • Check multiplication with division or check_mul_overflow() before allocation or copying, and bound the result against object capacity.
  • A write that changes hardware only after a complete checked copy avoids committing a command from partially supplied input.
Progress is saved on this device.

search — fzf

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

keyboard shortcuts — less

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

figure