[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7AQJ4G7SPDRW33GF0BRZAG6":3,"skill-same:01M7AQJ4G7SPDRW33GF0BRZAG6":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M7AQJ4G7SPDRW33GF0BRZAG6","linux-kernel-architecture-and-code",null,"Use when reading or writing Linux kernel code. Covers the shape of the kernel, processes and threads, scheduling (EEVDF, RT, deadline), memory (virtual memory, the page cache, allocators), VFS and the block layer, interrupts and deferred work; kernel C vs the C you know, the rules that get patches rejected, a minimal module line by line, the driver model and devicetree, userspace-facing interfaces (sysfs, ioctl, netlink), Rust in the kernel; and kernel concurrency — the locking primitives, RCU, memory barriers, and the deadlock rules. Includes the router for the whole os-development-kernel-shell reference.","the-vibey-project\u002Fvibey","the-vibey-project","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F329298758?v=4","01M7AJHGZ9722CTJ4JNQZVRH0Q","the vibey project","01M7AJHGZVMG2K7TGXQ6XFHVG3",5,"MIT","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fos-development-kernel-shell\u002Fskills\u002Flinux-kernel-architecture-and-code\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: linux-kernel-architecture-and-code\ndescription: \"Use when reading or writing Linux kernel code. Covers the shape of the kernel, processes and threads, scheduling (EEVDF, RT, deadline), memory (virtual memory, the page cache, allocators), VFS and the block layer, interrupts and deferred work; kernel C vs the C you know, the rules that get patches rejected, a minimal module line by line, the driver model and devicetree, userspace-facing interfaces (sysfs, ioctl, netlink), Rust in the kernel; and kernel concurrency — the locking primitives, RCU, memory barriers, and the deadlock rules. Includes the router for the whole os-development-kernel-shell reference.\"\n---\n\n# Linux Kernel & Shell: Kernel Architecture, Writing Kernel Code, and Kernel Concurrency\n\n> **Part 1 of 5** of the *OS Development — Linux Kernel and Shell* reference (plugin `os-development-kernel-shell`), covering §0–§3. Sibling skills: `linux-syscalls-ebpf-boot-and-init` (§4–§7), `linux-shell-scripting-and-userland` (§8–§11), `linux-kernel-debugging-process-and-hardening` (§12–§14), `linux-kernel-shell-reference` (§15–§20). Section numbers are shared across the set; a reference written as §N → `skill` points into that sibling skill.\n>\n> **Currency:** Verified August 2026. See §17 → `linux-kernel-shell-reference` for the currency snapshot and what goes stale first.\n\n> **How to read this.** Reference, not tutorial. Sections are independent. Three markers:\n> - **[DURABLE]** — architecture, algorithms, or semantics that have been stable for\n>   decades and will outlive this document.\n> - **[VERSIONED]** — depends on a kernel version, a shell version, or a distro. Check\n>   `Documentation\u002F`, the man page, or the source for your version.\n> - **[CONTESTED]** — the kernel community itself disagrees, publicly and at length.\n>   Both cases given.\n>\n> **⚠️ GOTCHA** boxes mark the mistakes that produce kernel oopses, data loss, silent\n> corruption, or a patch rejected on the mailing list.\n>\n> **The framing that matters most:** the kernel is not \"a big program.\" It is a\n> **hostile-input state machine running with no memory protection, no exceptions, a\n> hard limit on stack depth, and a promise never to break userspace**. Almost every\n> kernel-specific rule below descends from one of those five facts.\n\n---\n\n## §0. Routing\n\n### 0.1 What kind of OS work is this?\n\n| Task | Where it lives | Language | Risk if wrong |\n|---|---|---|---|\n| Observe the system | eBPF, ftrace, perf | BPF C \u002F bpftrace | Low — verifier catches most of it |\n| Change scheduling policy | **sched_ext** BPF scheduler | BPF C \u002F Rust | Low — kernel reverts to fair class on error |\n| Drive new hardware | Kernel module \u002F driver | C or **Rust** | High — oops, corruption |\n| Add a syscall or change ABI | Core kernel | C | **Permanent.** You can never take it back |\n| New filesystem | fs\u002F | C | Data loss |\n| Userspace init\u002Fservice | systemd unit, D-Bus | Config \u002F any | Medium |\n| Automate a system task | Shell \u002F Python | bash, POSIX sh | **Very high** — `rm -rf \"$UNSET\u002F\"` |\n| Build a distro \u002F image | Yocto, Buildroot, mkosi | Recipes | Medium |\n| Harden a system | sysctl, LSM, seccomp, lockdown | Config | Medium |\n\n**[DURABLE] Before writing kernel code, ask whether you can do it in userspace or in\nBPF instead.** The kernel community asks this first and so should you. A driver that\ncould be a `uio`\u002F`vfio` userspace driver, a filesystem that could be FUSE, a monitor that\ncould be eBPF — all are better engineering *and* faster to ship, because they don't\nrequire review by a maintainer who has been burned a thousand times.\n\n### 0.2 The question router\n\n| Asked about... | Go to |\n|---|---|\n| What is the kernel actually doing? Processes, scheduling, memory, VFS | §1 |\n| Writing kernel code — modules, drivers, C idioms, Rust | §2 |\n| Locking, RCU, memory barriers, per-CPU, preemption | §3 |\n| Syscalls, the ABI, \"don't break userspace\", vDSO | §4 → `linux-syscalls-ebpf-boot-and-init` |\n| eBPF, sched_ext, tracing programs | §5 → `linux-syscalls-ebpf-boot-and-init` |\n| Boot: firmware → bootloader → initramfs → init | §6 → `linux-syscalls-ebpf-boot-and-init` |\n| systemd, units, cgroups, namespaces, containers | §7 → `linux-syscalls-ebpf-boot-and-init` |\n| Shell semantics — word splitting, quoting, expansion | §8 → `linux-shell-scripting-and-userland` |\n| Bash vs zsh vs fish vs nushell; which to use | §9 → `linux-shell-scripting-and-userland` |\n| Writing shell that doesn't destroy things | §10 → `linux-shell-scripting-and-userland` |\n| The userland: coreutils, text processing, process tools | §11 → `linux-shell-scripting-and-userland` |\n| Debugging: ftrace, perf, KASAN, crash, printk | §12 → `linux-kernel-debugging-process-and-hardening` |\n| Kernel dev process: patches, maintainers, stable, CVEs | §13 → `linux-kernel-debugging-process-and-hardening` |\n| Security: LSM, seccomp, lockdown, hardening, attack surface | §14 → `linux-kernel-debugging-process-and-hardening` |\n| \"Don't do this\" | §15 → `linux-kernel-shell-reference` |\n| \"Which is better, X or Y?\" | §16 → `linux-kernel-shell-reference` (contested) |\n| \"Is this still current?\" | §17 → `linux-kernel-shell-reference` |\n| Books, docs, people | §18 → `linux-kernel-shell-reference` |\n\n---\n\n## §1. Kernel Architecture\n\n### 1.1 The shape of it\n\n```\n┌───────────────────────────────────────────────────────────────┐\n│ USERSPACE   applications · libc (glibc\u002Fmusl) · systemd         │\n└────────────────────────────┬──────────────────────────────────┘\n                    syscalls │ vDSO │ \u002Fproc \u002Fsys \u002Fdev │ netlink │ BPF\n┌────────────────────────────┴──────────────────────────────────┐\n│ SYSTEM CALL INTERFACE                                          │\n├──────────┬──────────┬──────────┬──────────┬───────────────────┤\n│ Process  │ Memory   │ VFS      │ Network  │ Device drivers    │\n│ sched,   │ mm, page │ fs, page │ netdev,  │ (60%+ of the      │\n│ signals, │ alloc,   │ cache,   │ TCP\u002FIP,  │  source tree)     │\n│ futex,   │ slab,    │ block    │ netfilter│                   │\n│ cgroups  │ swap     │ layer    │ XDP      │                   │\n├──────────┴──────────┴──────────┴──────────┴───────────────────┤\n│ CORE: locking · RCU · workqueues · timers · IRQ · DMA · BPF    │\n├───────────────────────────────────────────────────────────────┤\n│ ARCH: x86 \u002F arm64 \u002F riscv \u002F loongarch \u002F s390 \u002F powerpc         │\n└───────────────────────────────────────────────────────────────┘\n```\n\n**[DURABLE] Linux is a monolithic kernel with loadable modules.** Everything runs in one\naddress space at ring 0. There is no IPC boundary between the scheduler and your driver.\nThat is the source of both its performance and its blast radius: a NULL dereference in a\nUSB driver takes down the machine.\n\n**The source tree, by orientation:**\n| Directory | Contents |\n|---|---|\n| `kernel\u002F` | Core: scheduler (`kernel\u002Fsched\u002F`), signals, time, futex, cgroups, BPF (`kernel\u002Fbpf\u002F`) |\n| `mm\u002F` | Memory management: page allocator, slab, VMA, page cache, swap, OOM |\n| `fs\u002F` | VFS + every filesystem (`ext4\u002F`, `xfs\u002F`, `btrfs\u002F`, `overlayfs\u002F`, `proc\u002F`) |\n| `drivers\u002F` | **The majority of the tree.** By subsystem |\n| `net\u002F` | Protocol stacks, netfilter, sockets, XDP |\n| `arch\u002F` | Per-architecture: entry code, page tables, atomics, boot |\n| `include\u002Flinux\u002F` | Internal headers — the kernel's real API surface |\n| `include\u002Fuapi\u002F` | **The userspace ABI.** Change with extreme care (§4 → `linux-syscalls-ebpf-boot-and-init`) |\n| `lib\u002F`, `crypto\u002F`, `security\u002F`, `block\u002F`, `ipc\u002F`, `init\u002F` | As named |\n| `Documentation\u002F` | **Read this.** It is unusually good and constantly out-of-date in exactly the places you'd expect |\n| `tools\u002F` | perf, bpftool, selftests, sched_ext examples |\n| `rust\u002F` | Rust core abstractions and the `kernel` crate (§2.6) |\n\n### 1.2 Processes and threads\n\n**[DURABLE] Linux has no separate \"thread\" concept in the kernel.** There is\n`struct task_struct`, and threads are tasks that share resources. `clone()` with flags\ndecides *what* is shared:\n\n| Flag | Shares |\n|---|---|\n| `CLONE_VM` | Address space → this is what makes it \"a thread\" |\n| `CLONE_FS` | cwd, umask, root |\n| `CLONE_FILES` | File descriptor table |\n| `CLONE_SIGHAND` | Signal handlers |\n| `CLONE_THREAD` | Thread group (same TGID → same \"PID\" to userspace) |\n| `CLONE_NEWNS\u002FNEWPID\u002FNEWNET\u002F…` | **Namespaces** — this is how containers are built (§7.3 → `linux-syscalls-ebpf-boot-and-init`) |\n\n`fork()` = `clone()` with almost nothing shared. `pthread_create()` = `clone()` with\nVM|FS|FILES|SIGHAND|THREAD. **Containers are the same primitive with namespace flags.**\nThere is no \"container\" object in the kernel — a container is a process with unusual\nnamespace, cgroup, and LSM settings.\n\n**Process states** (`\u002Fproc\u002FPID\u002Fstat`): R (running\u002Frunnable), S (interruptible sleep),\n**D (uninterruptible sleep — waiting on I\u002FO; cannot be killed, and a pile of D-state\nprocesses means storage or a network filesystem is stuck)**, T (stopped), Z (zombie —\nexited but not reaped; the parent's fault, not the child's), X (dead).\n\n### 1.3 Scheduling\n\n**Scheduling classes, in priority order** [VERSIONED — this list has grown]:\n```\nstop_sched_class     — CPU hotplug\u002Fmigration. Preempts everything.\ndl_sched_class       — SCHED_DEADLINE (EDF + constant bandwidth server)\nrt_sched_class       — SCHED_FIFO, SCHED_RR (priorities 1–99)\nfair_sched_class     — SCHED_NORMAL\u002FBATCH\u002FIDLE. EEVDF since 6.6 (replaced CFS)\next_sched_class      — SCHED_EXT (sched_ext, BPF schedulers) — since 6.12\nidle_sched_class     — the idle task\n```\n\n**EEVDF** (Earliest Eligible Virtual Deadline First) replaced CFS as the fair-class\nalgorithm in 6.6. The key concepts: each task accrues **virtual runtime** scaled by\nweight (from `nice`); a task is **eligible** when its `vruntime` is at or behind the\nweighted average; among eligible tasks the one with the earliest **virtual deadline**\nruns. `sched_latency`-style tuning knobs from CFS largely don't apply; the per-task\n`slice` (settable via `sched_setattr`) is the modern lever.\n\n**[DURABLE] Real-time on Linux, precisely:**\n- `SCHED_FIFO`\u002F`SCHED_RR` tasks preempt all fair tasks and run until they block or yield.\n  A runaway `SCHED_FIFO` task at priority 99 with a busy loop **hangs that CPU**;\n  `sched_rt_runtime_us` (default 950000 of 1000000 µs) is the throttle that saves you.\n- `SCHED_DEADLINE` takes (runtime, deadline, period) and does admission control — the\n  kernel *refuses* to admit a task set it can't schedule. It's the only class with a\n  real guarantee.\n- **PREEMPT_RT was merged into mainline in Linux 6.12** (Sept 2024) for x86, arm64, and\n  RISC-V, ending a ~20-year out-of-tree effort. This makes most spinlocks sleeping\n  rt_mutexes and most IRQ handlers threaded. **It does not make Linux hard real-time** —\n  it takes worst-case latency from milliseconds to tens of microseconds, which is a\n  different claim.\n- Achieving that in practice needs the whole stack: `isolcpus`\u002F`nohz_full`\u002F`rcu_nocbs`,\n  IRQ affinity moved off isolated cores, `mlockall()`, no page faults in the hot path,\n  C-states and frequency scaling pinned, and **`cyclictest` under representative load as\n  proof**. A max-latency number without a load description is meaningless.\n\n### 1.4 Memory\n\n**Virtual memory layout** (x86-64, 4-level paging, 48-bit): userspace `0x0000...` up to\n128 TiB, a non-canonical hole, then kernel space in the top half — direct map of all\nphysical memory, vmalloc area, kernel text. Since 5.x there is optional 5-level paging\n(57-bit) for very large machines.\n\n**Allocators, and when to use which** [DURABLE]:\n| API | Backing | Size | Contiguity | Context |\n|---|---|---|---|---|\n| `kmalloc(size, gfp)` | slab | ≤ a few MB (order-limited) | **Physically contiguous** | Anywhere (gfp-dependent) |\n| `kzalloc` \u002F `kcalloc` | slab | \" | \" | Zeroed. Prefer these. |\n| `vmalloc(size)` | pages + PTEs | large | Virtually only | **Sleeps.** Not for DMA |\n| `alloc_pages(gfp, order)` | buddy | 2^order pages | Physically contiguous | Page granularity |\n| `kmem_cache_alloc` | dedicated slab cache | fixed | contiguous | Hot objects of one type |\n| `dma_alloc_coherent` | DMA API | | DMA-capable | **The only correct way to get DMA memory** |\n| `devm_kzalloc` | slab, device-managed | | contiguous | **Auto-freed on driver detach — use it** |\n\n**GFP flags are the most important thing to get right:**\n- `GFP_KERNEL` — may sleep. **Cannot be used in atomic context** (interrupt handler,\n  spinlock held, RCU read-side critical section).\n- `GFP_ATOMIC` — will not sleep, may fail, dips into emergency reserves. Use in\n  interrupt context.\n- `GFP_NOWAIT` — no sleep, no reserves.\n- `GFP_NOIO` \u002F `GFP_NOFS` — may sleep but must not recurse into I\u002FO or the filesystem.\n  Required in block\u002Ffs writeback paths or you deadlock against yourself.\n- `__GFP_ZERO`, `__GFP_NOWARN`, `__GFP_NOFAIL` (almost never justified).\n\n> **⚠️ GOTCHA — sleeping in atomic context.** `might_sleep()` and\n> `CONFIG_DEBUG_ATOMIC_SLEEP` exist because this is the single most common kernel bug\n> class. `GFP_KERNEL` under a spinlock produces \"BUG: sleeping function called from\n> invalid context\" — *if* you have the debug options on. If you don't, you get a rare,\n> load-dependent deadlock in production instead. **Always develop with the debug configs\n> enabled (§12.1 → `linux-kernel-debugging-process-and-hardening`).**\n\n**The page cache** unifies file I\u002FO and mmap: `read()` populates it, `mmap()` maps it,\nwriteback flushes dirty pages per `vm.dirty_ratio`\u002F`dirty_background_ratio`. Understanding\nthis explains most Linux I\u002FO behaviour, including why `free` \"shows no free memory\"\n(cache is reclaimable and that's the point) and why `fsync()` is the only durability\nprimitive that means anything.\n\n**The OOM killer** picks by `oom_score` (roughly, memory footprint adjusted by\n`oom_score_adj`). Under cgroup v2, memory pressure is contained per-cgroup with\n`memory.max` \u002F `memory.high`, and **PSI** (`\u002Fproc\u002Fpressure\u002F{cpu,memory,io}`) is the\nmodern signal for \"this machine is thrashing\" — far better than load average.\n\n### 1.5 VFS and the block layer\n\n```\nsyscall (read\u002Fwrite\u002Fopenat)\n  → VFS: struct file → struct dentry → struct inode → struct super_block\n    → filesystem (ext4, xfs, btrfs, overlayfs, nfs, fuse…)\n      → page cache\n        → block layer: bio → request queue → I\u002FO scheduler (mq-deadline, bfq, none)\n          → blk-mq (multiqueue) → driver (nvme, virtio-blk, scsi)\n```\n\n**[DURABLE] The VFS's four objects** — superblock (a mounted fs), inode (a file's\nmetadata), dentry (a name→inode cache entry; the dcache is why path lookup is fast), and\nfile (an open file description, with the offset). Understanding that **dentries cache\nnames and inodes cache files** explains hard links, rename semantics, and why\n`\u002Fproc\u002FPID\u002Ffd` shows what it shows.\n\n**Durability, correctly [DURABLE and constantly gotten wrong]:**\n```\nwrite()            → page cache. NOT durable. Survives process crash, not power loss.\nfsync(fd)          → file data + metadata for that file to stable storage.\nfdatasync(fd)      → data + only metadata needed to read it back. Cheaper.\nfsync(dirfd)       → REQUIRED after create\u002Frename\u002Funlink to persist the DIRECTORY ENTRY.\nO_SYNC \u002F O_DSYNC   → implicit sync on each write. Slow.\nO_DIRECT           → bypass page cache. Alignment requirements. Not a durability guarantee.\n```\n> **⚠️ GOTCHA — the atomic-rename recipe.** The only portable way to replace a file\n> without risking a truncated result across a power loss:\n> `open(tmp) → write() → fsync(tmp) → close → rename(tmp, target) → fsync(parent dir)`.\n> Skipping the **parent directory fsync** is the step everyone omits, and it means the\n> rename may not be durable even though the data is.\n> Also: **`fsync()` can fail, and on Linux historically a failed `fsync()` could clear\n> the error flag** — the \"fsyncgate\" problem that changed PostgreSQL's design. On error,\n> the correct response is to treat the data as lost, not to retry.\n\n**Filesystem selection** [VERSIONED]: **ext4** (default, boring, extremely well tested),\n**XFS** (large files, high parallelism, online repair since ~6.18), **Btrfs** (CoW,\nsnapshots, checksums, subvolumes; RAID5\u002F6 still not recommended), **ZFS** (out-of-tree,\nCDDL\u002FGPL licence incompatibility means it will never merge), **overlayfs** (the container\nlayering filesystem), **F2FS** (flash), **tmpfs**, **FUSE** (userspace).\n**bcachefs** — see §17 → `linux-kernel-shell-reference`; it is no longer in the kernel tree.\n\n### 1.6 Interrupts and deferred work\n\n**[DURABLE] The two-half rule.** Hardware IRQ handlers run with interrupts disabled on\nthat line, cannot sleep, and must be as short as possible: acknowledge, grab the data,\nschedule the rest.\n\n| Mechanism | Context | Can sleep | Use for |\n|---|---|---|---|\n| Hard IRQ handler | interrupt | **No** | Ack hardware, wake the bottom half |\n| **Threaded IRQ** (`request_threaded_irq`) | process | **Yes** | The modern default — the \"bottom half\" is a kernel thread |\n| Softirq | interrupt (deferred) | No | Core subsystems only (net, block, timers). Don't add new ones |\n| Tasklet | interrupt (deferred) | No | **Deprecated.** Use threaded IRQ or workqueue |\n| **Workqueue** (`queue_work`) | process (kworker) | **Yes** | General deferred work. The right default |\n| Kthread | process | Yes | Long-running per-device work |\n\n**[VERSIONED] Write new drivers with `request_threaded_irq()`.** It gives you a sleeping\ncontext for free and behaves correctly under PREEMPT_RT, where softirqs and tasklets have\ndifferent semantics.\n\n---\n\n## §2. Writing Kernel Code\n\n### 2.1 The kernel is not C as you know it\n\n**[DURABLE] What you do not have:**\n- **No libc.** No `printf`, `malloc`, `strcpy` in the userspace sense. The kernel has its\n  own: `printk`\u002F`pr_*`, `kmalloc`, `strscpy`, `kstrtoint`.\n- **No floating point** (without `kernel_fpu_begin\u002Fend`, and you almost certainly\n  shouldn't). The FPU state isn't saved across kernel entry.\n- **A tiny, fixed stack** — typically **16 KB** on x86-64 (`THREAD_SIZE`), shared with\n  interrupt frames on some configs. **No large stack arrays, no deep recursion, no\n  variable-length arrays.** `CONFIG_FRAME_WARN` yells at ~1–2 KB per frame.\n- **No exceptions and no unwinding.** Errors are `int` return codes: `0` on success,\n  **negative errno** (`-ENOMEM`, `-EINVAL`, `-EIO`) on failure. `ERR_PTR()`\u002F`IS_ERR()`\u002F\n  `PTR_ERR()` encode errors in pointer returns.\n- **No memory protection.** A bad pointer corrupts unrelated subsystems. The symptom\n  appears far from the cause. This is why KASAN exists (§12.3 → `linux-kernel-debugging-process-and-hardening`).\n- **Preemption and concurrency everywhere.** Your function can be entered on every CPU\n  simultaneously, and preempted mid-way. Assume it.\n\n**Kernel C dialect:** GNU C (not ISO), currently gnu11-ish with strong movement toward\nnewer standards; `__attribute__`s, statement expressions, `typeof`, and inline asm are\nnormal. `-fno-strict-aliasing` and `-fno-delete-null-pointer-checks` are on, which is why\nsome UB that would bite userspace doesn't bite here — do not rely on that.\n\n**The idioms you will read constantly:**\n```c\n\u002F* Error handling with goto — the canonical single-exit cleanup ladder.\n   MISRA-style \"no goto\" rules do not apply here; this IS the kernel style. *\u002F\nstatic int foo_probe(struct platform_device *pdev)\n{\n        struct foo *f;\n        int ret;\n\n        f = devm_kzalloc(&pdev->dev, sizeof(*f), GFP_KERNEL);\n        if (!f)\n                return -ENOMEM;                    \u002F* devm_ = auto-freed. Prefer it. *\u002F\n\n        f->clk = devm_clk_get(&pdev->dev, NULL);\n        if (IS_ERR(f->clk))\n                return dev_err_probe(&pdev->dev, PTR_ERR(f->clk), \"no clock\\n\");\n                \u002F* dev_err_probe handles -EPROBE_DEFER quietly. Use it. *\u002F\n\n        ret = clk_prepare_enable(f->clk);\n        if (ret)\n                return ret;\n\n        ret = foo_hw_init(f);\n        if (ret)\n                goto err_clk;                      \u002F* unwind in reverse order *\u002F\n\n        platform_set_drvdata(pdev, f);\n        return 0;\n\nerr_clk:\n        clk_disable_unprepare(f->clk);\n        return ret;\n}\n\n\u002F* container_of — how the kernel does \"inheritance\" without inheritance.\n   Given a pointer to an embedded member, recover the enclosing struct. *\u002F\nstruct my_dev { int id; struct device dev; };\nstatic struct my_dev *to_my_dev(struct device *d)\n{ return container_of(d, struct my_dev, dev); }\n\n\u002F* Intrusive linked lists — the node lives IN your struct, no allocation. *\u002F\nstruct my_item { struct list_head list; int value; };\nLIST_HEAD(items);\nlist_add_tail(&item->list, &items);\nlist_for_each_entry(item, &items, list) { ... }\nlist_for_each_entry_safe(item, tmp, &items, list) { list_del(&item->list); kfree(item); }\n```\n\n### 2.2 The rules that get patches rejected\n\n**[DURABLE, and enforced socially as much as technically]:**\n1. **Follow `Documentation\u002Fprocess\u002Fcoding-style.rst`.** Tabs of 8. 80 columns is a\n   soft limit (100 tolerated). Braces K&R-ish. `checkpatch.pl --strict` before sending.\n2. **One logical change per patch.** A series that mixes a cleanup with a fix will be\n   asked to be split.\n3. **`Signed-off-by:` is a legal statement** (the Developer Certificate of Origin), not\n   a formality.\n4. **Never break userspace.** §4 → `linux-syscalls-ebpf-boot-and-init`. This is the one rule Linus enforces personally and\n   loudly.\n5. **No new `\u002Fproc` files** for arbitrary data; use sysfs (one value per file) or debugfs\n   (unstable, debug-only) as appropriate. sysfs has an ABI stability expectation.\n6. **Document your locking.** A comment saying which lock protects which field is\n   expected. `lockdep` (§12.2 → `linux-kernel-debugging-process-and-hardening`) will verify it.\n7. **`__user` annotations and `copy_from_user`\u002F`copy_to_user`** for every userspace\n   pointer. Sparse (`make C=1`) checks this. Dereferencing a `__user` pointer directly\n   is both a bug and a security hole.\n8. **Check every return value.** `__must_check` exists.\n\n### 2.3 A minimal module, and why each line is there\n\n```c\n\u002F\u002F SPDX-License-Identifier: GPL-2.0        \u002F* Required. Machine-checkable. *\u002F\n#include \u003Clinux\u002Fmodule.h>\n#include \u003Clinux\u002Fkernel.h>\n#include \u003Clinux\u002Finit.h>\n\nstatic int __init hello_init(void)         \u002F* __init: freed after boot *\u002F\n{\n        pr_info(\"hello: loaded\\n\");        \u002F* pr_* honours the module prefix *\u002F\n        return 0;                          \u002F* nonzero = module load fails *\u002F\n}\n\nstatic void __exit hello_exit(void)        \u002F* __exit: dropped if built-in *\u002F\n{\n        pr_info(\"hello: unloaded\\n\");\n}\n\nmodule_init(hello_init);\nmodule_exit(hello_exit);\n\nMODULE_LICENSE(\"GPL\");    \u002F* Non-GPL taints the kernel and loses EXPORT_SYMBOL_GPL *\u002F\nMODULE_AUTHOR(\"...\");\nMODULE_DESCRIPTION(\"...\");\n```\nBuild out-of-tree against the running kernel's headers:\n```makefile\nobj-m += hello.o\nall:\n\t$(MAKE) -C \u002Flib\u002Fmodules\u002F$(shell uname -r)\u002Fbuild M=$(PWD) modules\nclean:\n\t$(MAKE) -C \u002Flib\u002Fmodules\u002F$(shell uname -r)\u002Fbuild M=$(PWD) clean\n```\n\n> **⚠️ GOTCHA — there is no stable in-kernel ABI, deliberately.** A module built for\n> 6.18.40 will not load on 6.18.41 if the relevant symbols' CRCs changed. This is policy,\n> not oversight: the kernel reserves the right to change internal interfaces, and the\n> cost of that policy is borne by out-of-tree modules. The consequences: DKMS rebuilds on\n> every kernel update, `MODULE_VERSION`\u002F`modversions` mismatches, and the reason vendors\n> push hard to get drivers upstream. **Getting your driver merged is the only durable\n> maintenance strategy.**\n\n### 2.4 Driver model and devicetree\n\nModern drivers plug into the **driver model**: a `struct device` bound to a `struct\ndevice_driver` by a **bus** (platform, PCI, USB, I2C, SPI). The bus matches by\ncompatible string (devicetree), ACPI ID, or vendor\u002Fdevice ID, then calls `probe()`.\n\n```c\nstatic const struct of_device_id foo_of_match[] = {\n        { .compatible = \"vendor,foo-v2\" },\n        { }\n};\nMODULE_DEVICE_TABLE(of, foo_of_match);   \u002F* enables autoloading via modalias *\u002F\n\nstatic struct platform_driver foo_driver = {\n        .probe  = foo_probe,\n        .remove = foo_remove,\n        .driver = {\n                .name           = \"foo\",\n                .of_match_table = foo_of_match,\n                .pm             = &foo_pm_ops,\n        },\n};\nmodule_platform_driver(foo_driver);\n```\n**Devicetree** describes non-discoverable hardware (most ARM\u002FRISC-V embedded); ACPI does\nthe same job on x86 servers. `-EPROBE_DEFER` is the mechanism for \"my dependency isn't\nready yet, retry later\" — return it, don't spin.\n\n**Use the `devm_` (device-managed) API for everything you can.** Resources are released\nautomatically on probe failure and on detach, which eliminates the single largest source\nof driver leak bugs.\n\n### 2.5 Userspace-facing interfaces\n\n| Interface | Stability | Use for |\n|---|---|---|\n| **syscall** | Forever (§4 → `linux-syscalls-ebpf-boot-and-init`) | Fundamental new capability. Very high bar |\n| **ioctl** | Per-driver, versioned | Device-specific commands. **Design the struct with padding and a size\u002Fversion field from day one** |\n| **sysfs** (`\u002Fsys`) | ABI-stable, documented in `Documentation\u002FABI\u002F` | One value per file, text |\n| **debugfs** (`\u002Fsys\u002Fkernel\u002Fdebug`) | **None** | Debugging only. Never rely on it in production tooling |\n| **procfs** (`\u002Fproc`) | Legacy stable | Process info. Don't add new non-process files |\n| **netlink** | Stable | Structured, async, multicast config (networking, but not only) |\n| **char device** | Per-driver | Streaming data |\n| **BPF** | Stable-ish | Programmable hooks (§5 → `linux-syscalls-ebpf-boot-and-init`) |\n\n### 2.6 Rust in the kernel\n\n**[VERSIONED — this changed materially in 2026.]** Rust support landed experimentally in\n6.1; **Linux 7.0 (12 April 2026) removed the experimental designation, making Rust a\nfirst-class kernel language.** The \"Rust experiment\" was formally concluded at the 2025\nKernel Maintainers Summit in Tokyo with an explicit coexistence policy: **Rust for new\ncode, C for existing subsystems, no forced migrations.** Kernel builds now require only\nstable Rust releases (minimum anchored to the Debian stable toolchain, ~1.93 at the time\nof the 7.0 release). Reported at Open Source Summit India in July 2026: some subsystems —\n**graphics notably** — intend to accept only Rust for *new* drivers going forward.\n\n**What exists:** the `kernel` crate with abstractions over PCI device enumeration,\ninterrupt handling, DMA mapping, platform device registration, `dev_printk` on all device\ntypes, and generic I\u002FO back-ends. Real drivers: Android's **ashmem** shipped in Rust on\nkernel 6.12 (putting Rust kernel code on hundreds of millions of devices), NVIDIA's\n**Nova** DRM driver for Turing-era hardware, Rust NVMe work, and PuzzleFS.\n\n**What's actually hard about it** [the honest list]:\n- **No `std`.** You get `core`, `alloc`, and the kernel's own `kernel` crate.\n- **Fallible allocation everywhere.** `Box::new` can't panic in the kernel, so you use\n  the kernel's fallible variants and handle `-ENOMEM` explicitly.\n- **Toolchain management overhead** — a specific minimum Rust version, and some carefully\n  used unstable features.\n- **Two skill sets.** You need kernel programming *and* Rust; the intersection is small.\n- **Documentation lags** the C side substantially.\n- Abstractions for a subsystem may simply not exist yet, in which case you write them —\n  which is a much bigger job than writing the driver.\n\n**[CONTESTED] Rust in the kernel.** The disagreement is real, public, and has cost\nmaintainers. *For:* memory-safety bugs are the dominant kernel CVE class and Rust\neliminates them by construction; Google reports zero memory-safety bugs in production\nfrom its Rust Android driver code where equivalent C drivers had CVEs. *Against (the\nstrongest version):* a second language doubles the maintenance surface for subsystem\nmaintainers who must now review both; refactoring a C interface now requires fixing Rust\nbindings maintained by someone else; and the kernel's rule that C changes shouldn't be\nblocked by Rust breakage is easier to state than to live with. One maintainer publicly\nresigned over this. **Both the technical case and the social cost are real; the policy\nquestion is settled, the friction is not.**\n\n---\n\n## §3. Concurrency in the Kernel\n\n### 3.1 The primitives\n\n| Primitive | Sleeps | Context | Use for |\n|---|---|---|---|\n| `spinlock_t` | No (busy-waits) | Any, incl. IRQ | Short critical sections. **Under PREEMPT_RT these become sleeping rt_mutexes** |\n| `spin_lock_irqsave\u002Firqrestore` | No | When an IRQ handler takes the same lock | The safe default when in doubt |\n| `raw_spinlock_t` | No, ever | Truly atomic paths | Stays a real spinlock even on RT |\n| `struct mutex` | **Yes** | Process context only | Longer sections; the default choice |\n| `rw_semaphore` | Yes | Process | Many readers, rare writers |\n| `seqlock_t` | No | Any | Read-mostly; readers retry, never block writers |\n| **RCU** | Readers: no | Any | **Read-mostly data structures. The kernel's signature technique** |\n| `atomic_t` \u002F `atomic64_t` | No | Any | Counters, flags |\n| `refcount_t` | No | Any | **Reference counts — use this, not atomic_t.** It detects overflow\u002FUAF |\n| `completion` | Yes | Process | \"Wait until this finishes\" |\n| `wait_queue_head_t` | Yes | Process | Sleep until a condition |\n| `percpu` variables | — | Any | Avoid sharing entirely — the fastest lock is no lock |\n\n### 3.2 RCU — the thing that makes Linux scale\n\n**[DURABLE] Read-Copy-Update:** readers are (almost) free — no locks, no atomics, no\ncache-line bouncing. Writers make a *copy*, publish it atomically, and defer freeing the\nold version until every pre-existing reader has finished.\n\n```c\n\u002F* Reader — cheap. rcu_read_lock() is essentially a preempt-disable. *\u002F\nrcu_read_lock();\np = rcu_dereference(gp);            \u002F* ensures the load isn't reordered ahead *\u002F\nif (p) do_something(p->field);      \u002F* p is guaranteed valid until unlock *\u002F\nrcu_read_unlock();\n\n\u002F* Writer *\u002F\nnew = kmalloc(sizeof(*new), GFP_KERNEL);\n*new = *old;\nnew->field = value;\nrcu_assign_pointer(gp, new);        \u002F* publish: barrier + store *\u002F\nsynchronize_rcu();                  \u002F* wait for a GRACE PERIOD (may sleep, may be slow) *\u002F\nkfree(old);\n\u002F* or: call_rcu(&old->rcu, free_cb);  — async, doesn't block the writer *\u002F\n```\n**The grace period** is the whole idea: a period after which every CPU has passed through\na quiescent state, so no reader can still hold the old pointer.\n\n> **⚠️ GOTCHA — RCU read-side is atomic context.** You cannot sleep between\n> `rcu_read_lock()` and `rcu_read_unlock()`. No `GFP_KERNEL`, no mutex, no\n> `copy_to_user`. (SRCU exists if you need to sleep; it has its own costs.)\n> `CONFIG_PROVE_RCU` catches violations.\n\n### 3.3 Memory barriers\n\n**[DURABLE] The compiler and the CPU both reorder memory accesses.** The kernel's model\nis documented in `Documentation\u002Fmemory-barriers.txt` — long, dense, and the definitive\nsource.\n\n| Barrier | Effect |\n|---|---|\n| `barrier()` | Compiler only |\n| `smp_mb()` | Full barrier (SMP only; compiles away on UP) |\n| `smp_rmb()` \u002F `smp_wmb()` | Read \u002F write barrier |\n| `smp_store_release()` \u002F `smp_load_acquire()` | **The preferred modern idiom.** Cheaper than full barriers and expresses intent |\n| `mb()`, `rmb()`, `wmb()` | Including for MMIO\u002FDMA |\n| `READ_ONCE()` \u002F `WRITE_ONCE()` | Prevent the compiler from tearing, fusing, or inventing accesses |\n\n**[DURABLE] `volatile` is nearly always wrong in kernel code.** Use `READ_ONCE`\u002F\n`WRITE_ONCE` for single accesses and proper locking or barriers for ordering.\n`Documentation\u002Fprocess\u002Fvolatile-considered-harmful.rst` exists for a reason.\n\n### 3.4 The deadlock rules\n\n1. **Establish a global lock ordering and document it.** Nested locks must always be\n   taken in the same order everywhere.\n2. **Never sleep holding a spinlock.**\n3. **If an IRQ handler takes lock L, every other acquirer of L must disable interrupts**\n   (`spin_lock_irqsave`), or you deadlock against yourself.\n4. **Prefer one lock over two.** Prefer per-CPU or RCU over one.\n5. **Turn on lockdep** (`CONFIG_PROVE_LOCKING`). It builds a lock dependency graph at\n   runtime and reports a potential deadlock the first time it sees an inconsistent\n   ordering — *even if the deadlock doesn't happen*. It is one of the best debugging\n   tools in any system, anywhere.\n","# Linux Kernel & Shell: Kernel Architecture, Writing Kernel Code, and Kernel Concurrency\n\n> **Part 1 of 5** of the *OS Development — Linux Kernel and Shell* reference (plugin `os-development-kernel-shell`), covering §0–§3. Sibling skills: `linux-syscalls-ebpf-boot-and-init` (§4–§7), `linux-shell-scripting-and-userland` (§8–§11), `linux-kernel-debugging-process-and-hardening` (§12–§14), `linux-kernel-shell-reference` (§15–§20). Section numbers are shared across the set; a reference written as §N → `skill` points into that sibling skill.\n>\n> **Currency:** Verified August 2026. See §17 → `linux-kernel-shell-reference` for the currency snapshot and what goes stale first.\n\n> **How to read this.** Reference, not tutorial. Sections are independent. Three markers:\n> - **[DURABLE]** — architecture, algorithms, or semantics that have been stable for\n>   decades and will outlive this document.\n> - **[VERSIONED]** — depends on a kernel version, a shell version, or a distro. Check\n>   `Documentation\u002F`, the man page, or the source for your version.\n> - **[CONTESTED]** — the kernel community itself disagrees, publicly and at length.\n>   Both cases given.\n>\n> **⚠️ GOTCHA** boxes mark the mistakes that produce kernel oopses, data loss, silent\n> corruption, or a patch rejected on the mailing list.\n>\n> **The framing that matters most:** the kernel is not \"a big program.\" It is a\n> **hostile-input state machine running with no memory protection, no exceptions, a\n> hard limit on stack depth, and a promise never to break userspace**. Almost every\n> kernel-specific rule below descends from one of those five facts.\n\n---\n\n## §0. Routing\n\n### 0.1 What kind of OS work is this?\n\n| Task | Where it lives | Language | Risk if wrong |\n|---|---|---|---|\n| Observe the system | eBPF, ftrace, perf | BPF C \u002F bpftrace | Low — verifier catches most of it |\n| Change scheduling policy | **sched_ext** BPF scheduler | BPF C \u002F Rust | Low — kernel reverts to fair class on error |\n| Drive new hardware | Kernel module \u002F driver | C or **Rust** | High — oops, corruption |\n| Add a syscall or change ABI | Core kernel | C | **Permanent.** You can never take it back |\n| New filesystem | fs\u002F | C | Data loss |\n| Userspace init\u002Fservice | systemd unit, D-Bus | Config \u002F any | Medium |\n| Automate a system task | Shell \u002F Python | bash, POSIX sh | **Very high** — `rm -rf \"$UNSET\u002F\"` |\n| Build a distro \u002F image | Yocto, Buildroot, mkosi | Recipes | Medium |\n| Harden a system | sysctl, LSM, seccomp, lockdown | Config | Medium |\n\n**[DURABLE] Before writing kernel code, ask whether you can do it in userspace or in\nBPF instead.** The kernel community asks this first and so should you. A driver that\ncould be a `uio`\u002F`vfio` userspace driver, a filesystem that could be FUSE, a monitor that\ncould be eBPF — all are better engineering *and* faster to ship, because they don't\nrequire review by a maintainer who has been burned a thousand times.\n\n### 0.2 The question router\n\n| Asked about... | Go to |\n|---|---|\n| What is the kernel actually doing? Processes, scheduling, memory, VFS | §1 |\n| Writing kernel code — modules, drivers, C idioms, Rust | §2 |\n| Locking, RCU, memory barriers, per-CPU, preemption | §3 |\n| Syscalls, the ABI, \"don't break userspace\", vDSO | §4 → `linux-syscalls-ebpf-boot-and-init` |\n| eBPF, sched_ext, tracing programs | §5 → `linux-syscalls-ebpf-boot-and-init` |\n| Boot: firmware → bootloader → initramfs → init | §6 → `linux-syscalls-ebpf-boot-and-init` |\n| systemd, units, cgroups, namespaces, containers | §7 → `linux-syscalls-ebpf-boot-and-init` |\n| Shell semantics — word splitting, quoting, expansion | §8 → `linux-shell-scripting-and-userland` |\n| Bash vs zsh vs fish vs nushell; which to use | §9 → `linux-shell-scripting-and-userland` |\n| Writing shell that doesn't destroy things | §10 → `linux-shell-scripting-and-userland` |\n| The userland: coreutils, text processing, process tools | §11 → `linux-shell-scripting-and-userland` |\n| Debugging: ftrace, perf, KASAN, crash, printk | §12 → `linux-kernel-debugging-process-and-hardening` |\n| Kernel dev process: patches, maintainers, stable, CVEs | §13 → `linux-kernel-debugging-process-and-hardening` |\n| Security: LSM, seccomp, lockdown, hardening, attack surface | §14 → `linux-kernel-debugging-process-and-hardening` |\n| \"Don't do this\" | §15 → `linux-kernel-shell-reference` |\n| \"Which is better, X or Y?\" | §16 → `linux-kernel-shell-reference` (contested) |\n| \"Is this still current?\" | §17 → `linux-kernel-shell-reference` |\n| Books, docs, people | §18 → `linux-kernel-shell-reference` |\n\n---\n\n## §1. Kernel Architecture\n\n### 1.1 The shape of it\n\n```\n┌───────────────────────────────────────────────────────────────┐\n│ USERSPACE   applications · libc (glibc\u002Fmusl) · systemd         │\n└────────────────────────────┬──────────────────────────────────┘\n                    syscalls │ vDSO │ \u002Fproc \u002Fsys \u002Fdev │ netlink │ BPF\n┌────────────────────────────┴──────────────────────────────────┐\n│ SYSTEM CALL INTERFACE                                          │\n├──────────┬──────────┬──────────┬──────────┬───────────────────┤\n│ Process  │ Memory   │ VFS      │ Network  │ Device drivers    │\n│ sched,   │ mm, page │ fs, page │ netdev,  │ (60%+ of the      │\n│ signals, │ alloc,   │ cache,   │ TCP\u002FIP,  │  source tree)     │\n│ futex,   │ slab,    │ block    │ netfilter│                   │\n│ cgroups  │ swap     │ layer    │ XDP      │                   │\n├──────────┴──────────┴──────────┴──────────┴───────────────────┤\n│ CORE: locking · RCU · workqueues · timers · IRQ · DMA · BPF    │\n├───────────────────────────────────────────────────────────────┤\n│ ARCH: x86 \u002F arm64 \u002F riscv \u002F loongarch \u002F s390 \u002F powerpc         │\n└───────────────────────────────────────────────────────────────┘\n```\n\n**[DURABLE] Linux is a monolithic kernel with loadable modules.** Everything runs in one\naddress space at ring 0. There is no IPC boundary between the scheduler and your driver.\nThat is the source of both its performance and its blast radius: a NULL dereference in a\nUSB driver takes down the machine.\n\n**The source tree, by orientation:**\n| Directory | Contents |\n|---|---|\n| `kernel\u002F` | Core: scheduler (`kernel\u002Fsched\u002F`), signals, time, futex, cgroups, BPF (`kernel\u002Fbpf\u002F`) |\n| `mm\u002F` | Memory management: page allocator, slab, VMA, page cache, swap, OOM |\n| `fs\u002F` | VFS + every filesystem (`ext4\u002F`, `xfs\u002F`, `btrfs\u002F`, `overlayfs\u002F`, `proc\u002F`) |\n| `drivers\u002F` | **The majority of the tree.** By subsystem |\n| `net\u002F` | Protocol stacks, netfilter, sockets, XDP |\n| `arch\u002F` | Per-architecture: entry code, page tables, atomics, boot |\n| `include\u002Flinux\u002F` | Internal headers — the kernel's real API surface |\n| `include\u002Fuapi\u002F` | **The userspace ABI.** Change with extreme care (§4 → `linux-syscalls-ebpf-boot-and-init`) |\n| `lib\u002F`, `crypto\u002F`, `security\u002F`, `block\u002F`, `ipc\u002F`, `init\u002F` | As named |\n| `Documentation\u002F` | **Read this.** It is unusually good and constantly out-of-date in exactly the places you'd expect |\n| `tools\u002F` | perf, bpftool, selftests, sched_ext examples |\n| `rust\u002F` | Rust core abstractions and the `kernel` crate (§2.6) |\n\n### 1.2 Processes and threads\n\n**[DURABLE] Linux has no separate \"thread\" concept in the kernel.** There is\n`struct task_struct`, and threads are tasks that share resources. `clone()` with flags\ndecides *what* is shared:\n\n| Flag | Shares |\n|---|---|\n| `CLONE_VM` | Address space → this is what makes it \"a thread\" |\n| `CLONE_FS` | cwd, umask, root |\n| `CLONE_FILES` | File descriptor table |\n| `CLONE_SIGHAND` | Signal handlers |\n| `CLONE_THREAD` | Thread group (same TGID → same \"PID\" to userspace) |\n| `CLONE_NEWNS\u002FNEWPID\u002FNEWNET\u002F…` | **Namespaces** — this is how containers are built (§7.3 → `linux-syscalls-ebpf-boot-and-init`) |\n\n`fork()` = `clone()` with almost nothing shared. `pthread_create()` = `clone()` with\nVM|FS|FILES|SIGHAND|THREAD. **Containers are the same primitive with namespace flags.**\nThere is no \"container\" object in the kernel — a container is a process with unusual\nnamespace, cgroup, and LSM settings.\n\n**Process states** (`\u002Fproc\u002FPID\u002Fstat`): R (running\u002Frunnable), S (interruptible sleep),\n**D (uninterruptible sleep — waiting on I\u002FO; cannot be killed, and a pile of D-state\nprocesses means storage or a network filesystem is stuck)**, T (stopped), Z (zombie —\nexited but not reaped; the parent's fault, not the child's), X (dead).\n\n### 1.3 Scheduling\n\n**Scheduling classes, in priority order** [VERSIONED — this list has grown]:\n```\nstop_sched_class     — CPU hotplug\u002Fmigration. Preempts everything.\ndl_sched_class       — SCHED_DEADLINE (EDF + constant bandwidth server)\nrt_sched_class       — SCHED_FIFO, SCHED_RR (priorities 1–99)\nfair_sched_class     — SCHED_NORMAL\u002FBATCH\u002FIDLE. EEVDF since 6.6 (replaced CFS)\next_sched_class      — SCHED_EXT (sched_ext, BPF schedulers) — since 6.12\nidle_sched_class     — the idle task\n```\n\n**EEVDF** (Earliest Eligible Virtual Deadline First) replaced CFS as the fair-class\nalgorithm in 6.6. The key concepts: each task accrues **virtual runtime** scaled by\nweight (from `nice`); a task is **eligible** when its `vruntime` is at or behind the\nweighted average; among eligible tasks the one with the earliest **virtual deadline**\nruns. `sched_latency`-style tuning knobs from CFS largely don't apply; the per-task\n`slice` (settable via `sched_setattr`) is the modern lever.\n\n**[DURABLE] Real-time on Linux, precisely:**\n- `SCHED_FIFO`\u002F`SCHED_RR` tasks preempt all fair tasks and run until they block or yield.\n  A runaway `SCHED_FIFO` task at priority 99 with a busy loop **hangs that CPU**;\n  `sched_rt_runtime_us` (default 950000 of 1000000 µs) is the throttle that saves you.\n- `SCHED_DEADLINE` takes (runtime, deadline, period) and does admission control — the\n  kernel *refuses* to admit a task set it can't schedule. It's the only class with a\n  real guarantee.\n- **PREEMPT_RT was merged into mainline in Linux 6.12** (Sept 2024) for x86, arm64, and\n  RISC-V, ending a ~20-year out-of-tree effort. This makes most spinlocks sleeping\n  rt_mutexes and most IRQ handlers threaded. **It does not make Linux hard real-time** —\n  it takes worst-case latency from milliseconds to tens of microseconds, which is a\n  different claim.\n- Achieving that in practice needs the whole stack: `isolcpus`\u002F`nohz_full`\u002F`rcu_nocbs`,\n  IRQ affinity moved off isolated cores, `mlockall()`, no page faults in the hot path,\n  C-states and frequency scaling pinned, and **`cyclictest` under representative load as\n  proof**. A max-latency number without a load description is meaningless.\n\n### 1.4 Memory\n\n**Virtual memory layout** (x86-64, 4-level paging, 48-bit): userspace `0x0000...` up to\n128 TiB, a non-canonical hole, then kernel space in the top half — direct map of all\nphysical memory, vmalloc area, kernel text. Since 5.x there is optional 5-level paging\n(57-bit) for very large machines.\n\n**Allocators, and when to use which** [DURABLE]:\n| API | Backing | Size | Contiguity | Context |\n|---|---|---|---|---|\n| `kmalloc(size, gfp)` | slab | ≤ a few MB (order-limited) | **Physically contiguous** | Anywhere (gfp-dependent) |\n| `kzalloc` \u002F `kcalloc` | slab | \" | \" | Zeroed. Prefer these. |\n| `vmalloc(size)` | pages + PTEs | large | Virtually only | **Sleeps.** Not for DMA |\n| `alloc_pages(gfp, order)` | buddy | 2^order pages | Physically contiguous | Page granularity |\n| `kmem_cache_alloc` | dedicated slab cache | fixed | contiguous | Hot objects of one type |\n| `dma_alloc_coherent` | DMA API | | DMA-capable | **The only correct way to get DMA memory** |\n| `devm_kzalloc` | slab, device-managed | | contiguous | **Auto-freed on driver detach — use it** |\n\n**GFP flags are the most important thing to get right:**\n- `GFP_KERNEL` — may sleep. **Cannot be used in atomic context** (interrupt handler,\n  spinlock held, RCU read-side critical section).\n- `GFP_ATOMIC` — will not sleep, may fail, dips into emergency reserves. Use in\n  interrupt context.\n- `GFP_NOWAIT` — no sleep, no reserves.\n- `GFP_NOIO` \u002F `GFP_NOFS` — may sleep but must not recurse into I\u002FO or the filesystem.\n  Required in block\u002Ffs writeback paths or you deadlock against yourself.\n- `__GFP_ZERO`, `__GFP_NOWARN`, `__GFP_NOFAIL` (almost never justified).\n\n> **⚠️ GOTCHA — sleeping in atomic context.** `might_sleep()` and\n> `CONFIG_DEBUG_ATOMIC_SLEEP` exist because this is the single most common kernel bug\n> class. `GFP_KERNEL` under a spinlock produces \"BUG: sleeping function called from\n> invalid context\" — *if* you have the debug options on. If you don't, you get a rare,\n> load-dependent deadlock in production instead. **Always develop with the debug configs\n> enabled (§12.1 → `linux-kernel-debugging-process-and-hardening`).**\n\n**The page cache** unifies file I\u002FO and mmap: `read()` populates it, `mmap()` maps it,\nwriteback flushes dirty pages per `vm.dirty_ratio`\u002F`dirty_background_ratio`. Understanding\nthis explains most Linux I\u002FO behaviour, including why `free` \"shows no free memory\"\n(cache is reclaimable and that's the point) and why `fsync()` is the only durability\nprimitive that means anything.\n\n**The OOM killer** picks by `oom_score` (roughly, memory footprint adjusted by\n`oom_score_adj`). Under cgroup v2, memory pressure is contained per-cgroup with\n`memory.max` \u002F `memory.high`, and **PSI** (`\u002Fproc\u002Fpressure\u002F{cpu,memory,io}`) is the\nmodern signal for \"this machine is thrashing\" — far better than load average.\n\n### 1.5 VFS and the block layer\n\n```\nsyscall (read\u002Fwrite\u002Fopenat)\n  → VFS: struct file → struct dentry → struct inode → struct super_block\n    → filesystem (ext4, xfs, btrfs, overlayfs, nfs, fuse…)\n      → page cache\n        → block layer: bio → request queue → I\u002FO scheduler (mq-deadline, bfq, none)\n          → blk-mq (multiqueue) → driver (nvme, virtio-blk, scsi)\n```\n\n**[DURABLE] The VFS's four objects** — superblock (a mounted fs), inode (a file's\nmetadata), dentry (a name→inode cache entry; the dcache is why path lookup is fast), and\nfile (an open file description, with the offset). Understanding that **dentries cache\nnames and inodes cache files** explains hard links, rename semantics, and why\n`\u002Fproc\u002FPID\u002Ffd` shows what it shows.\n\n**Durability, correctly [DURABLE and constantly gotten wrong]:**\n```\nwrite()            → page cache. NOT durable. Survives process crash, not power loss.\nfsync(fd)          → file data + metadata for that file to stable storage.\nfdatasync(fd)      → data + only metadata needed to read it back. Cheaper.\nfsync(dirfd)       → REQUIRED after create\u002Frename\u002Funlink to persist the DIRECTORY ENTRY.\nO_SYNC \u002F O_DSYNC   → implicit sync on each write. Slow.\nO_DIRECT           → bypass page cache. Alignment requirements. Not a durability guarantee.\n```\n> **⚠️ GOTCHA — the atomic-rename recipe.** The only portable way to replace a file\n> without risking a truncated result across a power loss:\n> `open(tmp) → write() → fsync(tmp) → close → rename(tmp, target) → fsync(parent dir)`.\n> Skipping the **parent directory fsync** is the step everyone omits, and it means the\n> rename may not be durable even though the data is.\n> Also: **`fsync()` can fail, and on Linux historically a failed `fsync()` could clear\n> the error flag** — the \"fsyncgate\" problem that changed PostgreSQL's design. On error,\n> the correct response is to treat the data as lost, not to retry.\n\n**Filesystem selection** [VERSIONED]: **ext4** (default, boring, extremely well tested),\n**XFS** (large files, high parallelism, online repair since ~6.18), **Btrfs** (CoW,\nsnapshots, checksums, subvolumes; RAID5\u002F6 still not recommended), **ZFS** (out-of-tree,\nCDDL\u002FGPL licence incompatibility means it will never merge), **overlayfs** (the container\nlayering filesystem), **F2FS** (flash), **tmpfs**, **FUSE** (userspace).\n**bcachefs** — see §17 → `linux-kernel-shell-reference`; it is no longer in the kernel tree.\n\n### 1.6 Interrupts and deferred work\n\n**[DURABLE] The two-half rule.** Hardware IRQ handlers run with interrupts disabled on\nthat line, cannot sleep, and must be as short as possible: acknowledge, grab the data,\nschedule the rest.\n\n| Mechanism | Context | Can sleep | Use for |\n|---|---|---|---|\n| Hard IRQ handler | interrupt | **No** | Ack hardware, wake the bottom half |\n| **Threaded IRQ** (`request_threaded_irq`) | process | **Yes** | The modern default — the \"bottom half\" is a kernel thread |\n| Softirq | interrupt (deferred) | No | Core subsystems only (net, block, timers). Don't add new ones |\n| Tasklet | interrupt (deferred) | No | **Deprecated.** Use threaded IRQ or workqueue |\n| **Workqueue** (`queue_work`) | process (kworker) | **Yes** | General deferred work. The right default |\n| Kthread | process | Yes | Long-running per-device work |\n\n**[VERSIONED] Write new drivers with `request_threaded_irq()`.** It gives you a sleeping\ncontext for free and behaves correctly under PREEMPT_RT, where softirqs and tasklets have\ndifferent semantics.\n\n---\n\n## §2. Writing Kernel Code\n\n### 2.1 The kernel is not C as you know it\n\n**[DURABLE] What you do not have:**\n- **No libc.** No `printf`, `malloc`, `strcpy` in the userspace sense. The kernel has its\n  own: `printk`\u002F`pr_*`, `kmalloc`, `strscpy`, `kstrtoint`.\n- **No floating point** (without `kernel_fpu_begin\u002Fend`, and you almost certainly\n  shouldn't). The FPU state isn't saved across kernel entry.\n- **A tiny, fixed stack** — typically **16 KB** on x86-64 (`THREAD_SIZE`), shared with\n  interrupt frames on some configs. **No large stack arrays, no deep recursion, no\n  variable-length arrays.** `CONFIG_FRAME_WARN` yells at ~1–2 KB per frame.\n- **No exceptions and no unwinding.** Errors are `int` return codes: `0` on success,\n  **negative errno** (`-ENOMEM`, `-EINVAL`, `-EIO`) on failure. `ERR_PTR()`\u002F`IS_ERR()`\u002F\n  `PTR_ERR()` encode errors in pointer returns.\n- **No memory protection.** A bad pointer corrupts unrelated subsystems. The symptom\n  appears far from the cause. This is why KASAN exists (§12.3 → `linux-kernel-debugging-process-and-hardening`).\n- **Preemption and concurrency everywhere.** Your function can be entered on every CPU\n  simultaneously, and preempted mid-way. Assume it.\n\n**Kernel C dialect:** GNU C (not ISO), currently gnu11-ish with strong movement toward\nnewer standards; `__attribute__`s, statement expressions, `typeof`, and inline asm are\nnormal. `-fno-strict-aliasing` and `-fno-delete-null-pointer-checks` are on, which is why\nsome UB that would bite userspace doesn't bite here — do not rely on that.\n\n**The idioms you will read constantly:**\n```c\n\u002F* Error handling with goto — the canonical single-exit cleanup ladder.\n   MISRA-style \"no goto\" rules do not apply here; this IS the kernel style. *\u002F\nstatic int foo_probe(struct platform_device *pdev)\n{\n        struct foo *f;\n        int ret;\n\n        f = devm_kzalloc(&pdev->dev, sizeof(*f), GFP_KERNEL);\n        if (!f)\n                return -ENOMEM;                    \u002F* devm_ = auto-freed. Prefer it. *\u002F\n\n        f->clk = devm_clk_get(&pdev->dev, NULL);\n        if (IS_ERR(f->clk))\n                return dev_err_probe(&pdev->dev, PTR_ERR(f->clk), \"no clock\\n\");\n                \u002F* dev_err_probe handles -EPROBE_DEFER quietly. Use it. *\u002F\n\n        ret = clk_prepare_enable(f->clk);\n        if (ret)\n                return ret;\n\n        ret = foo_hw_init(f);\n        if (ret)\n                goto err_clk;                      \u002F* unwind in reverse order *\u002F\n\n        platform_set_drvdata(pdev, f);\n        return 0;\n\nerr_clk:\n        clk_disable_unprepare(f->clk);\n        return ret;\n}\n\n\u002F* container_of — how the kernel does \"inheritance\" without inheritance.\n   Given a pointer to an embedded member, recover the enclosing struct. *\u002F\nstruct my_dev { int id; struct device dev; };\nstatic struct my_dev *to_my_dev(struct device *d)\n{ return container_of(d, struct my_dev, dev); }\n\n\u002F* Intrusive linked lists — the node lives IN your struct, no allocation. *\u002F\nstruct my_item { struct list_head list; int value; };\nLIST_HEAD(items);\nlist_add_tail(&item->list, &items);\nlist_for_each_entry(item, &items, list) { ... }\nlist_for_each_entry_safe(item, tmp, &items, list) { list_del(&item->list); kfree(item); }\n```\n\n### 2.2 The rules that get patches rejected\n\n**[DURABLE, and enforced socially as much as technically]:**\n1. **Follow `Documentation\u002Fprocess\u002Fcoding-style.rst`.** Tabs of 8. 80 columns is a\n   soft limit (100 tolerated). Braces K&R-ish. `checkpatch.pl --strict` before sending.\n2. **One logical change per patch.** A series that mixes a cleanup with a fix will be\n   asked to be split.\n3. **`Signed-off-by:` is a legal statement** (the Developer Certificate of Origin), not\n   a formality.\n4. **Never break userspace.** §4 → `linux-syscalls-ebpf-boot-and-init`. This is the one rule Linus enforces personally and\n   loudly.\n5. **No new `\u002Fproc` files** for arbitrary data; use sysfs (one value per file) or debugfs\n   (unstable, debug-only) as appropriate. sysfs has an ABI stability expectation.\n6. **Document your locking.** A comment saying which lock protects which field is\n   expected. `lockdep` (§12.2 → `linux-kernel-debugging-process-and-hardening`) will verify it.\n7. **`__user` annotations and `copy_from_user`\u002F`copy_to_user`** for every userspace\n   pointer. Sparse (`make C=1`) checks this. Dereferencing a `__user` pointer directly\n   is both a bug and a security hole.\n8. **Check every return value.** `__must_check` exists.\n\n### 2.3 A minimal module, and why each line is there\n\n```c\n\u002F\u002F SPDX-License-Identifier: GPL-2.0        \u002F* Required. Machine-checkable. *\u002F\n#include \u003Clinux\u002Fmodule.h>\n#include \u003Clinux\u002Fkernel.h>\n#include \u003Clinux\u002Finit.h>\n\nstatic int __init hello_init(void)         \u002F* __init: freed after boot *\u002F\n{\n        pr_info(\"hello: loaded\\n\");        \u002F* pr_* honours the module prefix *\u002F\n        return 0;                          \u002F* nonzero = module load fails *\u002F\n}\n\nstatic void __exit hello_exit(void)        \u002F* __exit: dropped if built-in *\u002F\n{\n        pr_info(\"hello: unloaded\\n\");\n}\n\nmodule_init(hello_init);\nmodule_exit(hello_exit);\n\nMODULE_LICENSE(\"GPL\");    \u002F* Non-GPL taints the kernel and loses EXPORT_SYMBOL_GPL *\u002F\nMODULE_AUTHOR(\"...\");\nMODULE_DESCRIPTION(\"...\");\n```\nBuild out-of-tree against the running kernel's headers:\n```makefile\nobj-m += hello.o\nall:\n\t$(MAKE) -C \u002Flib\u002Fmodules\u002F$(shell uname -r)\u002Fbuild M=$(PWD) modules\nclean:\n\t$(MAKE) -C \u002Flib\u002Fmodules\u002F$(shell uname -r)\u002Fbuild M=$(PWD) clean\n```\n\n> **⚠️ GOTCHA — there is no stable in-kernel ABI, deliberately.** A module built for\n> 6.18.40 will not load on 6.18.41 if the relevant symbols' CRCs changed. This is policy,\n> not oversight: the kernel reserves the right to change internal interfaces, and the\n> cost of that policy is borne by out-of-tree modules. The consequences: DKMS rebuilds on\n> every kernel update, `MODULE_VERSION`\u002F`modversions` mismatches, and the reason vendors\n> push hard to get drivers upstream. **Getting your driver merged is the only durable\n> maintenance strategy.**\n\n### 2.4 Driver model and devicetree\n\nModern drivers plug into the **driver model**: a `struct device` bound to a `struct\ndevice_driver` by a **bus** (platform, PCI, USB, I2C, SPI). The bus matches by\ncompatible string (devicetree), ACPI ID, or vendor\u002Fdevice ID, then calls `probe()`.\n\n```c\nstatic const struct of_device_id foo_of_match[] = {\n        { .compatible = \"vendor,foo-v2\" },\n        { }\n};\nMODULE_DEVICE_TABLE(of, foo_of_match);   \u002F* enables autoloading via modalias *\u002F\n\nstatic struct platform_driver foo_driver = {\n        .probe  = foo_probe,\n        .remove = foo_remove,\n        .driver = {\n                .name           = \"foo\",\n                .of_match_table = foo_of_match,\n                .pm             = &foo_pm_ops,\n        },\n};\nmodule_platform_driver(foo_driver);\n```\n**Devicetree** describes non-discoverable hardware (most ARM\u002FRISC-V embedded); ACPI does\nthe same job on x86 servers. `-EPROBE_DEFER` is the mechanism for \"my dependency isn't\nready yet, retry later\" — return it, don't spin.\n\n**Use the `devm_` (device-managed) API for everything you can.** Resources are released\nautomatically on probe failure and on detach, which eliminates the single largest source\nof driver leak bugs.\n\n### 2.5 Userspace-facing interfaces\n\n| Interface | Stability | Use for |\n|---|---|---|\n| **syscall** | Forever (§4 → `linux-syscalls-ebpf-boot-and-init`) | Fundamental new capability. Very high bar |\n| **ioctl** | Per-driver, versioned | Device-specific commands. **Design the struct with padding and a size\u002Fversion field from day one** |\n| **sysfs** (`\u002Fsys`) | ABI-stable, documented in `Documentation\u002FABI\u002F` | One value per file, text |\n| **debugfs** (`\u002Fsys\u002Fkernel\u002Fdebug`) | **None** | Debugging only. Never rely on it in production tooling |\n| **procfs** (`\u002Fproc`) | Legacy stable | Process info. Don't add new non-process files |\n| **netlink** | Stable | Structured, async, multicast config (networking, but not only) |\n| **char device** | Per-driver | Streaming data |\n| **BPF** | Stable-ish | Programmable hooks (§5 → `linux-syscalls-ebpf-boot-and-init`) |\n\n### 2.6 Rust in the kernel\n\n**[VERSIONED — this changed materially in 2026.]** Rust support landed experimentally in\n6.1; **Linux 7.0 (12 April 2026) removed the experimental designation, making Rust a\nfirst-class kernel language.** The \"Rust experiment\" was formally concluded at the 2025\nKernel Maintainers Summit in Tokyo with an explicit coexistence policy: **Rust for new\ncode, C for existing subsystems, no forced migrations.** Kernel builds now require only\nstable Rust releases (minimum anchored to the Debian stable toolchain, ~1.93 at the time\nof the 7.0 release). Reported at Open Source Summit India in July 2026: some subsystems —\n**graphics notably** — intend to accept only Rust for *new* drivers going forward.\n\n**What exists:** the `kernel` crate with abstractions over PCI device enumeration,\ninterrupt handling, DMA mapping, platform device registration, `dev_printk` on all device\ntypes, and generic I\u002FO back-ends. Real drivers: Android's **ashmem** shipped in Rust on\nkernel 6.12 (putting Rust kernel code on hundreds of millions of devices), NVIDIA's\n**Nova** DRM driver for Turing-era hardware, Rust NVMe work, and PuzzleFS.\n\n**What's actually hard about it** [the honest list]:\n- **No `std`.** You get `core`, `alloc`, and the kernel's own `kernel` crate.\n- **Fallible allocation everywhere.** `Box::new` can't panic in the kernel, so you use\n  the kernel's fallible variants and handle `-ENOMEM` explicitly.\n- **Toolchain management overhead** — a specific minimum Rust version, and some carefully\n  used unstable features.\n- **Two skill sets.** You need kernel programming *and* Rust; the intersection is small.\n- **Documentation lags** the C side substantially.\n- Abstractions for a subsystem may simply not exist yet, in which case you write them —\n  which is a much bigger job than writing the driver.\n\n**[CONTESTED] Rust in the kernel.** The disagreement is real, public, and has cost\nmaintainers. *For:* memory-safety bugs are the dominant kernel CVE class and Rust\neliminates them by construction; Google reports zero memory-safety bugs in production\nfrom its Rust Android driver code where equivalent C drivers had CVEs. *Against (the\nstrongest version):* a second language doubles the maintenance surface for subsystem\nmaintainers who must now review both; refactoring a C interface now requires fixing Rust\nbindings maintained by someone else; and the kernel's rule that C changes shouldn't be\nblocked by Rust breakage is easier to state than to live with. One maintainer publicly\nresigned over this. **Both the technical case and the social cost are real; the policy\nquestion is settled, the friction is not.**\n\n---\n\n## §3. Concurrency in the Kernel\n\n### 3.1 The primitives\n\n| Primitive | Sleeps | Context | Use for |\n|---|---|---|---|\n| `spinlock_t` | No (busy-waits) | Any, incl. IRQ | Short critical sections. **Under PREEMPT_RT these become sleeping rt_mutexes** |\n| `spin_lock_irqsave\u002Firqrestore` | No | When an IRQ handler takes the same lock | The safe default when in doubt |\n| `raw_spinlock_t` | No, ever | Truly atomic paths | Stays a real spinlock even on RT |\n| `struct mutex` | **Yes** | Process context only | Longer sections; the default choice |\n| `rw_semaphore` | Yes | Process | Many readers, rare writers |\n| `seqlock_t` | No | Any | Read-mostly; readers retry, never block writers |\n| **RCU** | Readers: no | Any | **Read-mostly data structures. The kernel's signature technique** |\n| `atomic_t` \u002F `atomic64_t` | No | Any | Counters, flags |\n| `refcount_t` | No | Any | **Reference counts — use this, not atomic_t.** It detects overflow\u002FUAF |\n| `completion` | Yes | Process | \"Wait until this finishes\" |\n| `wait_queue_head_t` | Yes | Process | Sleep until a condition |\n| `percpu` variables | — | Any | Avoid sharing entirely — the fastest lock is no lock |\n\n### 3.2 RCU — the thing that makes Linux scale\n\n**[DURABLE] Read-Copy-Update:** readers are (almost) free — no locks, no atomics, no\ncache-line bouncing. Writers make a *copy*, publish it atomically, and defer freeing the\nold version until every pre-existing reader has finished.\n\n```c\n\u002F* Reader — cheap. rcu_read_lock() is essentially a preempt-disable. *\u002F\nrcu_read_lock();\np = rcu_dereference(gp);            \u002F* ensures the load isn't reordered ahead *\u002F\nif (p) do_something(p->field);      \u002F* p is guaranteed valid until unlock *\u002F\nrcu_read_unlock();\n\n\u002F* Writer *\u002F\nnew = kmalloc(sizeof(*new), GFP_KERNEL);\n*new = *old;\nnew->field = value;\nrcu_assign_pointer(gp, new);        \u002F* publish: barrier + store *\u002F\nsynchronize_rcu();                  \u002F* wait for a GRACE PERIOD (may sleep, may be slow) *\u002F\nkfree(old);\n\u002F* or: call_rcu(&old->rcu, free_cb);  — async, doesn't block the writer *\u002F\n```\n**The grace period** is the whole idea: a period after which every CPU has passed through\na quiescent state, so no reader can still hold the old pointer.\n\n> **⚠️ GOTCHA — RCU read-side is atomic context.** You cannot sleep between\n> `rcu_read_lock()` and `rcu_read_unlock()`. No `GFP_KERNEL`, no mutex, no\n> `copy_to_user`. (SRCU exists if you need to sleep; it has its own costs.)\n> `CONFIG_PROVE_RCU` catches violations.\n\n### 3.3 Memory barriers\n\n**[DURABLE] The compiler and the CPU both reorder memory accesses.** The kernel's model\nis documented in `Documentation\u002Fmemory-barriers.txt` — long, dense, and the definitive\nsource.\n\n| Barrier | Effect |\n|---|---|\n| `barrier()` | Compiler only |\n| `smp_mb()` | Full barrier (SMP only; compiles away on UP) |\n| `smp_rmb()` \u002F `smp_wmb()` | Read \u002F write barrier |\n| `smp_store_release()` \u002F `smp_load_acquire()` | **The preferred modern idiom.** Cheaper than full barriers and expresses intent |\n| `mb()`, `rmb()`, `wmb()` | Including for MMIO\u002FDMA |\n| `READ_ONCE()` \u002F `WRITE_ONCE()` | Prevent the compiler from tearing, fusing, or inventing accesses |\n\n**[DURABLE] `volatile` is nearly always wrong in kernel code.** Use `READ_ONCE`\u002F\n`WRITE_ONCE` for single accesses and proper locking or barriers for ordering.\n`Documentation\u002Fprocess\u002Fvolatile-considered-harmful.rst` exists for a reason.\n\n### 3.4 The deadlock rules\n\n1. **Establish a global lock ordering and document it.** Nested locks must always be\n   taken in the same order everywhere.\n2. **Never sleep holding a spinlock.**\n3. **If an IRQ handler takes lock L, every other acquirer of L must disable interrupts**\n   (`spin_lock_irqsave`), or you deadlock against yourself.\n4. **Prefer one lock over two.** Prefer per-CPU or RCU over one.\n5. **Turn on lockdep** (`CONFIG_PROVE_LOCKING`). It builds a lock dependency graph at\n   runtime and reports a potential deadlock the first time it sees an inconsistent\n   ordering — *even if the deadlock doesn't happen*. It is one of the best debugging\n   tools in any system, anywhere.\n",{"name":5,"description":7},"develop","ae32736a1aabddabca5d2c96d665aa0ebc7d8700","src\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fos-development-kernel-shell\u002Fskills\u002Flinux-kernel-architecture-and-code",3,"https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey","https:\u002F\u002Fthe-vibey-project.github.io\u002Fvibey\u002F","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project","https:\u002F\u002Fvibewithadam.matthewsteinberger.com","freedom for software engineers","2026-11-15 05:47:42",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add the-vibey-project\u002Fvibey --skill linux-kernel-architecture-and-code",{"tool":40,"command":41},"bunx","bunx skills add the-vibey-project\u002Fvibey --skill linux-kernel-architecture-and-code",{"tool":43,"command":44},"pnpm","pnpm dlx skills add the-vibey-project\u002Fvibey --skill linux-kernel-architecture-and-code","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fos-development-kernel-shell\u002Fskills\u002Flinux-kernel-architecture-and-code\u002FSKILL.md",true,[],[49,56,63,70,77,84],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":19},"01M7AT1FQJAE1FQYAMDTF490Y4","white-paper-writing","Use when writing white papers, technical reports, policy documents, thought leadership pieces, or any long-form authoritative document. Triggers on requests to write, structure, outline, or review white papers, technical reports, position papers, policy briefs, or evidence-driven arguments. Also use for B2B content marketing strategy, technical documentation requiring authority, academic-style reports, or any document that must educate while persuading. Use when someone asks \"how should I structure this\" for a long-form document.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fwhite-paper-writing\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":19},"01M7AT16BJRJJKK2MASXRZS76G","prose-technical-mechanics","Use when editing or writing prose at a technical\u002Fmechanical level: choosing between Anglo-Saxon and Latinate diction, placing information in topic vs stress positions, writing periodic vs cumulative sentences, handling sentence rhythm, punctuation as logic, transitions, paragraph structure, or phonesthetics. Use when someone wants to understand WHY prose works or doesn't, not just surface-level style advice. Triggers on word choice, sentence structure, emphasis, rhythm, diction, or any deep writing mechanics question.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fprose-technical-mechanics\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":19},"01M7AT0W9HT0ZZ9Y287NW99MR3","prose-mechanics","Use when writing, editing, or analyzing prose style; when trying to avoid generic AI-sounding writing; when applying specific prose styles such as journalistic, academic, narrative, KJV biblical, Hemingway plain, Latinate\u002FJamesian, Orwellian, Augustan, Victorian, Early Modern (Bacon, Browne, Milton), or free indirect discourse; or when coaching someone on writing voice and mechanics. Triggers on any request to improve, analyze, or write in a specific prose style, to fix \"AI-sounding\" writing, to make prose more vivid or concrete, to vary sentence rhythm, or to understand how a particular writer achieves their effects.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fprose-mechanics\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M7AT0KR635JX66X2X6F3E2CP","narrative-structure","Use when structuring stories, pitches, presentations, white papers, or any persuasive narrative; analyzing the hero's journey in fiction or non-fiction; applying StoryBrand for business communication; designing narrative arcs for thought leadership; or understanding Vogler, Snyder, Propp, or Campbell frameworks. Triggers on any narrative structure, storytelling, pitch structure, StoryBrand, hero's journey, three-act structure, Freytag, Save the Cat, narrative arc, or \"how should I structure this story\u002Fpitch\u002Fpresentation\" request.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fnarrative-structure\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M7AT0AKGW09NKKZDYBT8VRDE","legal-brief-writing","Use when writing legal briefs, motions, or any court filing; when analyzing judicial cognition and persuasion; when applying elite brief-writing techniques from Roberts, Clement, Kagan, Garner; or when structuring legal arguments for maximum persuasion. Also use for autistic\u002Fneurodivergent advocates who need to understand how their natural communication style maps to elite legal advocacy. Triggers on any legal writing, brief drafting, motion preparation, or legal argument structuring request.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Flegal-brief-writing\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M7AT00VWPS4Q8B5VEMXX9NQT","journal-publishability-criteria","Use whenever a research paper, article or preprint is being written, revised, reviewed or published, and specifically before every publication of docs\u002Fpaper.md. Covers what legitimate journals actually gate on, in order of gating — the editor's desk screen (scope, novelty, package problems), what reviewers judge (methodological soundness, claims the evidence can carry, statistical and qualitative reporting), EQUATOR reporting guidelines, the ICMJE authorship criteria, COPE's view of text recycling, the near-universal generative-AI policy (no AI author, disclosure, author responsibility), TOP 2025 transparency standards, how to verify a journal is legitimate, submitting without an institution, and a pre-submission checklist. Triggers on requests to evaluate, review, prepare or submit a paper, to judge publishability, to write a declarations or data-availability section, to disclose AI use, or to check a journal.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fjournal-publishability-criteria\u002FSKILL.md",[],[]]