跳到内容

pipe / pipe2(匿名管道) · 源码分析 ​

模块简介 ​

fs/pipe.c 是 Linux 内核中匿名管道(pipe(2)/pipe2(2))与命名管道 FIFO(mkfifo(2))的核心实现。 它以页为粒度组织一个环形缓冲区:写端把用户数据逐页拷入环中,读端按序取出; 在此之上提供 read/write/poll/ioctl/fcntl 全套文件操作,并通过 pipefs 伪文件系统为每个管道 分配一个不出现于任何挂载点的 inode。管道还承担按用户的内存页配额管理 (soft/hard limit),防止非特权用户用管道耗尽内存。更重要的是,pipe_buffer 抽象是 splice(2)/tee(2)/vmsplice(2) 零拷贝机制的基础:数据在内核中以 (page, offset, len) 的形式流转, 文件与管道之间可以直接搬页而不必逐字节复制。

源码分析:核心数据结构 ​

管道的控制块是 struct pipe_inode_info(定义于 include/linux/pipe_fs_i.h)。 其中 head/tail 是单调递增的写/读位置;ring_size 是环形 缓冲区的实际槽数;max_usage 是当前允许使用的槽数上限(写满判定用它而非 ring_size,二者仅在 watch_queue 管道上分离);nr_accounted 是已按用户记账的槽数。 readers/writers 统计两端打开计数,r_counter/w_counter 是 FIFO 打开配对用的单调计数。rd_wait/wr_wait 是读/写等待队列, fasync_readers/fasync_writers 维护 SIGIO 通知列表; tmp_page[] 是每管道页缓存;poll_usage 记录 epoll 是否关注过本管道; note_loss 标记 watch_queue 通知丢失;user 指向配额属主; mutex 则是保护这一切的大锁。

环形缓冲区的每个槽位是一个 struct pipe_buffer:page/offset/ len 描述一页内存中的一段数据,flags 携带 PIPE_BUF_FLAG_CAN_MERGE / PACKET / WHOLE 等语义,ops 指向 struct pipe_buf_operations—— release(读完释放)、try_steal(splice 偷页)、get (tee 加引用)三件套。正是这套操作集让不同来源的页(匿名管道、splice 自文件、 watch_queue 通知)能在同一个环里共存。

源码分析:环形缓冲区设计 ​

2019 年 David Howells 重写后,head 和 tail 都是单调递增的 unsigned int,只在解引用取槽位时才按 ring_size - 1 掩码取模, 溢出时自然回绕。这样环中不存在 dead spot(传统"head==tail 分不清空满"的浪费槽位问题), 数据量就是 head - tail(pipe_occupancy),代价是 ring_size 必须为 2 的幂且 不超过 2^31——round_pipe_size() 负责把任何容量请求规整到这个形式。

union pipe_index 把 head 和 tail 拼进同一个 64 位字段 head_tail:pipe_readable()、pipe_writable() 和 pipe_poll() 在不持锁的情况下用 READ_ONCE 一次原子地把两个索引读出来, 避免了分两次读可能拿到的"头尾撕裂"状态。这是管道在等待队列上睡眠时做条件判断的基础。

源码分析:写路径 anon_pipe_write ​

写入从两个前置检查开始:watch_queue 通知管道直接拒绝(-EXDEV,避免与普通管道的锁序纠缠); 无读者时发 SIGPIPE 并返回 -EPIPE(IOCB_NOSIGNAL 时不发信号)。随后是合并写: 若最后一槽带 PIPE_BUF_FLAG_CAN_MERGE 且剩余空间装得下不足一页的零头,就把零头追加进去—— 这既天然合并了连续小写,又顺势把跨页大写的剩余部分对齐到页边界。之后进入主循环, 每槽一整页:逐槽取页(锁外预分配 -> tmp_page[] 缓存 -> 锁内兜底), 每槽 copy_page_from_iter 至多 PAGE_SIZE;O_DIRECT 打开的管道走包模式,整槽打上 PIPE_BUF_FLAG_PACKET,不可合并、整包读出。

环写满时,非阻塞(O_NONBLOCK)或 IOCB_NOWAIT 直接返回 -EAGAIN;否则释放 pipe->mutex 睡到 wr_wait 上(wait_event_interruptible_exclusive,独占等待防惊群), 醒来重新持锁并复检空满。退出路径的唤醒非常讲究:was_empty 记录"本次写入是否 让管道由空变不空",是则用 wake_up_interruptible_sync_poll 做 WF_SYNC 同步唤醒读者—— GNU make jobserver 这类把小写当作信号的场景依赖这种即时唤醒;睡过觉的写者退出前置 wake_next_writer 接力唤醒下一个写者,与独占式等待配对。

源码分析:读路径 anon_pipe_read ​

读主循环逐槽把数据用 copy_page_to_iter 拷给用户。包模式语义体现在两个 flag 上: PIPE_BUF_FLAG_WHOLE 要求缓冲区足够整包吞下,否则 -ENOBUFS; PIPE_BUF_FLAG_PACKET 则让读到包尾即止、包内剩余字节直接丢弃。槽读空后由 pipe_update_tail 推进 tail:普通管道靠 mutex 足够,watch_queue 管道则必须额外持 rd_wait.lock 自旋锁——因为通知发布方只持这把自旋锁;同一临界区内还会置 note_loss,使读者随后先收到一条 WATCH_META_LOSS_NOTIFICATION 丢失通知。

读的唤醒策略与写对称:wake_writer 仅在"开始读时管道是满的、读完不再满"才成立, 由满变不满才 WF_SYNC 唤醒写者,避免每次读都骚扰写端;无数据且有写者时放锁睡 rd_wait,醒来后若环里还有剩余数据则置 wake_next_reader 接力唤醒 其他读者。管道空且无写者即 EOF(返回 0)。

源码分析:页分配优化体系 ​

这个版本(2026-07 主线)的写路径有一套完整的页供给优化。tmp_page[] 是每管道 页缓存:anon_pipe_put_page 在 page_count==1(确认没有 splice/tee 外部引用)时把页 stash 回缓存而不是 put_page,下次写直接取用。多页写则在拿锁之前由 anon_pipe_get_page_prealloc 做锁外预分配(至多 PIPE_PREALLOC_MAX=8 页): alloc_page 可能因回收而睡眠、还伴随 memcg 计费,放在临界区外做可避免卡住并发读者。 写完剩余的预分配页由 anon_pipe_refill_tmp_pages 塞回 tmp_page[],用不完的则由 anon_pipe_free_pages 在解锁后 put_page——把释放也移出临界区。

预分配刻意用 alloc_page 循环而不用 alloc_pages_bulk_*:bulk 路径在 memcg 下拒绝 __GFP_ACCOUNT(commit 8dcb3060d81d),会静默退化为只分配单页;逐页循环能对每一页 保持 memcg 计费和任务 NUMA mempolicy 生效,缺口由锁内的 alloc_page 兜底补齐。

源码分析:锁与唤醒机制 ​

pipe->mutex 保护管道的一切状态。但 pipe_lock()/pipe_unlock() 有一个特别约定:仅当 pipe->files 非零时才真正加锁——files 为 0 意味着管道已没有 打开文件、处于销毁路径。splice 需要同时锁两条管道时,pipe_double_lock 按指针地址 排序后先小后大加锁,杜绝 AB-BA 死锁;CONFIG_PROVE_LOCKING 下还通过 lock_set_cmp_fn 给 mutex 注册同样的地址比较函数,让 lockdep 能验证这一顺序。

读写路径的睡眠全部使用 wait_event_interruptible_exclusive 独占等待:一次只唤醒 一个等待者,配合退出时的 wake_next_reader/wake_next_writer 接力唤醒,避免惊群。唤醒用 wake_up_interruptible_sync_poll:WF_SYNC 语义提示唤醒者马上要睡眠,被唤醒者可以 直接在当前 CPU 上运行——这正是 GNU make jobserver 用小写唤醒待执行任务时依赖的低延迟行为。 fasync_readers/fasync_writers 则在数据、空间到来或对端关闭时发 SIGIO。

源码分析:容量调整与配额 ​

默认容量是 PIPE_DEF_BUFFERS=16 槽(64KB);单管道上限 pipe_max_size 默认 1MB, 可通过 /proc/sys/fs/pipe-max-size 调整(写入时经 proc_dopipe_max_size 自动按 round_pipe_size 取整)。fcntl 的 F_SETPIPE_SZ/F_GETPIPE_SZ 由 pipe_fcntl 分发到 pipe_set_size:扩容时非特权用户不得超过 pipe_max_size 和按用户的 soft/hard 页配额, 缩容永远允许。pipe_resize_ring 负责真正的搬迁:分配新环、把 [tail, head) 的有效槽 按序拷到新数组头部、head/tail 归零重排(数据量超过新槽数则 -EBUSY);注意 max_usage 与 ring_size 的区别——watch_queue 管道的 max_usage/nr_accounted 不随 resize 更新,这是配额语义的例外。

按用户配额在 alloc_pipe_info 和 pipe_set_size 两处把关:先记账 (account_pipe_buffers),超软上限的非特权用户被降级到 PIPE_MIN_DEF_BUFFERS=2 槽, 超硬上限直接失败。下限 2 是有讲究的:一个待读槽加一个可写槽,保证"向非空管道再写一页"不会 阻塞——GNU make jobserver 把管道当信号量用,多个进程可能都等着先把 token 写回去再读, 少于 2 槽就会死锁(见文件头英文注释引用的 lkml 讨论)。

源码分析:FIFO 打开语义 ​

fifo_open 实现 POSIX 的三种打开模式:O_RDONLY 阻塞时睡到 写端到来(wait_for_partner 靠 w_counter 配对计数判断),非阻塞时立即成功—— 并把 filp->f_pipe 记为当前 w_counter,pipe_poll 据此在"见过写者"之前抑制 EPOLLHUP;O_WRONLY 非阻塞且无读者时返回 -ENXIO,否则阻塞等读端; O_RDWR 永不阻塞(进程至少能自发自收),readers/writers 各加一。 配对的一侧计数从零变一时,wake_up_partner 唤醒在 rd_wait 上等待的对端 open。

FIFO 与匿名管道共用几乎全部代码,差异集中在两个 file_operations 上:pipefifo_fops 的读写是 fifo_pipe_read/fifo_pipe_write——前者在读成功后 file_accessed 更新 atime,后者在写成功后以 sb_start_write_trylock 保护 file_update_time 更新 mtime/ctime(FIFO 有真实文件系统的时间戳语义,且要避开 冻结中的文件系统);pipeanon_fops 则直接用 anon_pipe_read/anon_pipe_write,无文件语义。

源码分析:创建、pipefs 与 sysctl ​

pipe(2)/pipe2(2) 的链路是:do_pipe2 -> __do_pipe_flags(校验 flags、 申请两个未用 fd、audit_fd_pair 审计)-> create_pipe_files。 create_pipe_files 先用 get_pipe_inode 在 pipefs 上建伪 inode 并挂好 alloc_pipe_info 分配的控制块,再用 alloc_file_pseudo 创建写端 file、 alloc_file_clone 克隆出读端 file;两端都标 FMODE_NOWAIT(支持 IOCB_NOWAIT), 并用 file_set_fsnotify_mode 关掉权限/前置类 fsnotify 事件。pipe2 多一步 copy_to_user 把 fd 对写回用户数组,失败时完整回滚。

pipefs 是一个永不暴露给用户态挂载的伪文件系统:init_pseudo 建立 fs_context,kern_mount 内核态挂载;dentry 名字由 pipefs_dname 生成为 "pipe:[ino]"——这正是 /proc/<pid>/fd 里管道符号链接的样子,也省掉了 procfs 的特判。 init_pipe_fs 在 fs_initcall 阶段注册 pipefs、完成内核挂载,并注册 /proc/sys/fs/ 下的 pipe-max-size、pipe-user-pages-hard、pipe-user-pages-soft 三个 sysctl。

源码分析:splice 支持 ​

splice/tee/vmsplice 都以 pipe_buffer 为中转。匿名管道的操作集 anon_pipe_buf_ops:release 走 anon_pipe_put_page(可进 tmp_page[] 缓存), get 复用 generic_pipe_buf_get(try_get_page 加引用,tee 复制时用)。 最关键的是 anon_pipe_buf_try_steal:splice 把管道数据移入文件时尝试"偷页", 只有 page_count(page) == 1——即管道是该页唯一引用者——才允许偷取;成功后 memcg_kmem_uncharge_page 撤销页的 memcg kmem 计费(页已不属于管道子系统), __SetPageLocked 置上 PG_locked——页缓存约定新插入的页要以锁定态交接,调用方 随后把它据为己有、送进目标文件的页缓存,完成一次真正的零拷贝。

逐文件注释源码 ​

以下为 pipe.c 全文(共 1650 行),保留原有英文注释,新增中文注释覆盖文件级说明、 头文件、宏、结构体、全部函数及关键行。

一、文件头、头文件与宏 ​

本小节包含 SPDX/版权头、全部 #include、配额相关的宏与全局变量(PIPE_MIN_DEF_BUFFERS、pipe_max_size、pipe_user_pages_hard/soft),以及环形缓冲区设计的历史注记。

c
// SPDX-License-Identifier: GPL-2.0
/*
 *  linux/fs/pipe.c
 *
 *  Copyright (C) 1991, 1992, 1999  Linus Torvalds
 */

/* 【文件功能】Linux 内核匿名管道与 FIFO 的核心实现(fs/pipe.c)
 * 本文件实现 pipe(2)/pipe2(2) 匿名管道与 mkfifo(2) 命名管道(FIFO)的全部核心逻辑:
 *   - 以"页"为粒度的环形缓冲区:head/tail 单调递增、仅解引用时按掩码取模;
 *   - 读路径 anon_pipe_read / 写路径 anon_pipe_write(含 O_DIRECT 包模式);
 *   - poll / ioctl / fcntl(F_SETPIPE_SZ 容量调整)与 fasync SIGIO 通知;
 *   - pipefs 伪文件系统:管道 inode 不出现在任何可见挂载点,dentry 名形如 "pipe:[ino]";
 *   - 按用户的内存页配额(soft/hard limit)与 pipe_max_size 单管道上限;
 *   - splice/tee/vmsplice 零拷贝机制的底层承载(pipe_buffer 操作集)。
 * 【主要数据结构】(定义于 include/linux/pipe_fs_i.h,本文件使用)
 *   struct pipe_inode_info      管道控制块:环形缓冲区 + 等待队列 + 配额记账
 *   struct pipe_buffer          环中一个槽位:一页内存的 (page, offset, len, ops, flags)
 *   struct pipe_buf_operations  release/try_steal/get 三件套,供 splice/tee 使用
 *   union pipe_index            把 head/tail 合成 64 位,一次原子读做无锁状态判断
 * 【调用链路】
 *   创建链路:pipe(2)/pipe2(2) -> do_pipe2 -> __do_pipe_flags -> create_pipe_files
 *     -> get_pipe_inode(pipefs 伪 inode)-> alloc_pipe_info
 *   read(2)  -> anon_pipe_read / fifo_pipe_read(FIFO)
 *   write(2) -> anon_pipe_write / fifo_pipe_write(FIFO)
 *   open(2)(FIFO 文件)-> pipefifo_fops.open = fifo_open
 *   容量调整:fcntl(F_SETPIPE_SZ) -> pipe_fcntl -> pipe_set_size -> pipe_resize_ring */
#include <linux/mm.h>  // 内存管理:alloc_page/put_page/page_count 等
#include <linux/file.h>  // 文件对象:alloc_file_pseudo/alloc_file_clone/fput 等
#include <linux/poll.h>  // poll/select 支持:poll_wait、__poll_t、EPOLL* 事件位
#include <linux/slab.h>  // slab 分配器:kzalloc_obj/kzalloc_objs/kfree
#include <linux/module.h>  // EXPORT_SYMBOL:导出符号给内核模块用
#include <linux/init.h>  // __init / fs_initcall 初始化标记
#include <linux/fs.h>  // VFS 核心:struct inode/file、i_fop、FMODE_* 等
#include <linux/log2.h>  // roundup_pow_of_two():容量向上取 2 的幂
#include <linux/mount.h>  // struct vfsmount:pipefs 的内核挂载
#include <linux/pseudo_fs.h>  // init_pseudo():伪文件系统辅助(无实际挂载点)
#include <linux/magic.h>  // PIPEFS_MAGIC 魔数
#include <linux/pipe_fs_i.h>  // 管道子系统头文件:struct pipe_inode_info/pipe_buffer、pipe_empty/pipe_full/pipe_buf 等内联助手
#include <linux/uio.h>  // iov_iter 用户缓冲区迭代器:copy_page_to_iter/copy_page_from_iter
#include <linux/highmem.h>  // highmem 支持(copy_page_to_iter 内部 kmap 用)
#include <linux/pagemap.h>  // 页缓存/文件时间戳接口:file_accessed/file_update_time 等
#include <linux/audit.h>  // audit_fd_pair():审计管道创建出的 fd 对
#include <linux/syscalls.h>  // SYSCALL_DEFINE 宏
#include <linux/fcntl.h>  // O_CLOEXEC/O_NONBLOCK/O_DIRECT/F_SETPIPE_SZ 等标志
#include <linux/memcontrol.h>  // memcg:__GFP_ACCOUNT、memcg_kmem_uncharge_page
#include <linux/watch_queue.h>  // watch_queue:内核通知队列(CONFIG_WATCH_QUEUE)
#include <linux/sysctl.h>  // register_sysctl_init:注册 /proc/sys/fs/pipe-* 参数
#include <linux/sort.h>  // cmp_int:lockdep 锁地址比较函数用

#include <linux/uaccess.h>  // 用户态内存访问:copy_to_user/put_user
#include <asm/ioctls.h>  // FIONREAD 等 ioctl 命令号

#include "internal.h"  // fs/ 目录内部头:本目录内跨文件使用的声明

/*
 * New pipe buffers will be restricted to this size while the user is exceeding
 * their pipe buffer quota. The general pipe use case needs at least two
 * buffers: one for data yet to be read, and one for new data. If this is less
 * than two, then a write to a non-empty pipe may block even if the pipe is not
 * full. This can occur with GNU make jobserver or similar uses of pipes as
 * semaphores: multiple processes may be waiting to write tokens back to the
 * pipe before reading tokens: https://lore.kernel.org/lkml/1628086770.5rn8p04n6j.none@localhost/.
 *
 * Users can reduce their pipe buffers with F_SETPIPE_SZ below this at their
 * own risk, namely: pipe writes to non-full pipes may block until the pipe is
 * emptied.
 */
#define PIPE_MIN_DEF_BUFFERS 2  // 每管道最少 2 个页槽:保证"非空管道仍可再写一页",防 GNU make jobserver 型死锁(见上方英文注释)

/*
 * The max size that a non-root user is allowed to grow the pipe. Can
 * be set by root in /proc/sys/fs/pipe-max-size
 */
static unsigned int pipe_max_size = 1048576;  // 非特权用户单管道容量上限,默认 1MB,可写 /proc/sys/fs/pipe-max-size 调整

/* Maximum allocatable pages per user. Hard limit is unset by default, soft
 * matches default values.
 */
static unsigned long pipe_user_pages_hard;  // 每用户管道页硬上限:默认 0 = 不限制
static unsigned long pipe_user_pages_soft = PIPE_DEF_BUFFERS * INR_OPEN_CUR;  // 每用户管道页软上限:默认 每管道 16 页(PIPE_DEF_BUFFERS) × 进程数软上限(INR_OPEN_CUR)

/*
 * We use head and tail indices that aren't masked off, except at the point of
 * dereference, but rather they're allowed to wrap naturally.  This means there
 * isn't a dead spot in the buffer, but the ring has to be a power of two and
 * <= 2^31.
 * -- David Howells 2019-09-23.
 *
 * Reads with count = 0 should always return 0.
 * -- Julian Bradfield 1999-06-07.
 *
 * FIFOs and Pipes now generate SIGIO for both readers and writers.
 * -- Jeremy Elson <jelson@circlemud.org> 2001-08-16
 *
 * pipe_read & write cleanup
 * -- Manfred Spraul <manfred@colorfullife.com> 2002-05-09
 */

二、锁辅助(pipe_lock / pipe_unlock / pipe_double_lock) ​

pipe_lock/pipe_unlock 的"files 非零才加锁"约定、pipe_double_lock 按地址排序的双锁,以及仅供 lockdep 使用的地址比较函数 pipe_lock_cmp_fn。

c
#ifdef CONFIG_PROVE_LOCKING
/* 【函数】pipe_lock_cmp_fn —— lockdep 锁比较函数(仅 CONFIG_PROVE_LOCKING)
 * 功能:pipe_double_lock 同时拿两把 pipe->mutex 时,lockdep 需要校验加锁顺序;
 *       本函数按锁的内存地址比较大小,与 pipe_double_lock 的"按地址排序"策略一致。
 * 参数:a、b —— 两个锁的 lockdep_map
 * 返回:负/0/正 的三态地址序比较结果 */
static int pipe_lock_cmp_fn(const struct lockdep_map *a,
                const struct lockdep_map *b)
{
    return cmp_int((unsigned long) a, (unsigned long) b);  // cmp_int():三态比较,地址小的排前,形成全局唯一加锁顺序
}
#endif

/* 【函数】pipe_lock —— 给管道加互斥锁
 * 功能:加 pipe->mutex。pipe->files 为 0 说明管道已没有打开文件(销毁路径),
 *       此时无需加锁——splice 等外部调用方依赖这一约定。
 * 参数:pipe —— 管道控制块 */
void pipe_lock(struct pipe_inode_info *pipe)
{
    if (pipe->files)  // 有打开文件才真正加锁;files==0 的管道已不可见,跳过
        mutex_lock(&pipe->mutex);
}
EXPORT_SYMBOL(pipe_lock);

/* 【函数】pipe_unlock —— 与 pipe_lock 配对的解锁:同样以 pipe->files 非零为条件 */
void pipe_unlock(struct pipe_inode_info *pipe)
{
    if (pipe->files)  // 与 pipe_lock 判断保持严格对称
        mutex_unlock(&pipe->mutex);
}
EXPORT_SYMBOL(pipe_unlock);

/* 【函数】pipe_double_lock —— 无死锁地同时锁住两条管道
 * 功能:splice 在两条管道间搬数据时需要同时持两把锁;按地址排序后先小后大加锁,
 *       配合 lockdep 的 pipe_lock_cmp_fn,杜绝 AB-BA 死锁。
 * 参数:pipe1、pipe2 —— 两条不同管道的控制块 */
void pipe_double_lock(struct pipe_inode_info *pipe1,
              struct pipe_inode_info *pipe2)
{
    BUG_ON(pipe1 == pipe2);  // 同一条管道双锁没有意义,直接 BUG

    if (pipe1 > pipe2)  // 按指针地址排序,固定加锁顺序
        swap(pipe1, pipe2);

    pipe_lock(pipe1);
    pipe_lock(pipe2);
}

三、页缓存与锁外预分配(anon_pipe_prealloc 系列) ​

anon_pipe_prealloc 描述符与一组取页/还页助手:写路径在锁外预分配页、用 tmp_page[] 做每管道页缓存、把 put_page 移出临界区。

c
#define PIPE_PREALLOC_MAX 8  // 锁外预分配的最大页数:一次写最多提前准备 8 页

/* 【struct anon_pipe_prealloc】写路径的锁外页预分配描述符
 * 在拿 pipe->mutex 之前先分配好页,进临界区后直接取用,缩短持锁时间。 */
struct anon_pipe_prealloc {
    struct page *pages[PIPE_PREALLOC_MAX];  // 预分配到的页指针数组
    unsigned int count;  // 实际预分配到的页数
};

/*
 * Pre-allocate pages outside pipe->mutex for multi-page writes.
 * alloc_page() with GFP_HIGHUSER can sleep in reclaim and runs memcg
 * charging; doing it under the mutex stalls a concurrent reader.
 *
 * Loop alloc_page() instead of alloc_pages_bulk_*(): the bulk path refuses
 * __GFP_ACCOUNT under memcg (see commit 8dcb3060d81d "memcg: page_alloc:
 * skip bulk allocator for __GFP_ACCOUNT") and silently degrades to a single
 * page. A per-page loop keeps memcg accounting and the task NUMA mempolicy
 * honoured for every page; the per-call overhead is small compared to the
 * pipe->mutex hold-time being shrunk. Any shortfall is covered by the
 * in-lock alloc_page() fallback in anon_pipe_get_page().
 */
/* 【函数】anon_pipe_get_page_prealloc —— 在锁外为多页写预分配页
 * 功能:total_len 超过一页时,循环 alloc_page() 预分配若干页(至多 PIPE_PREALLOC_MAX)。
 *       alloc_page 可能因回收而睡眠、还会做 memcg 计费,放到锁外做可避免阻塞并发读者。
 *       不用 alloc_pages_bulk_*():bulk 路径在 memcg 下拒绝 __GFP_ACCOUNT 并会静默退化为
 *       单页分配(commit 8dcb3060d81d);逐页循环能对每页保持 memcg 计费与 NUMA mempolicy,
 *       缺页由 anon_pipe_get_page() 的锁内兜底补齐。
 * 参数:prealloc —— 预分配描述符(输出);total_len —— 本次写的总字节数 */
static void anon_pipe_get_page_prealloc(struct anon_pipe_prealloc *prealloc,
                    size_t total_len)
{
    unsigned int want, i;
    struct page *page;

    prealloc->count = 0;
    if (total_len <= PAGE_SIZE)  // 单页以内的写不必预分配:tmp_page[] 缓存与锁内兜底足够
        return;

    want = min_t(unsigned int, DIV_ROUND_UP(total_len, PAGE_SIZE),  // 需要的页数向上取整,封顶 PIPE_PREALLOC_MAX
             PIPE_PREALLOC_MAX);

    for (i = 0; i < want; i++) {
        page = alloc_page(GFP_HIGHUSER | __GFP_ACCOUNT);  // __GFP_ACCOUNT:计入 memcg;分配失败即停,剩余由锁内兜底
        if (!page)
            break;
        prealloc->pages[prealloc->count++] = page;
    }
}

/* 【函数】anon_pipe_prealloc_pop —— 从预分配数组弹出一页(LIFO),空则返回 NULL */
static struct page *anon_pipe_prealloc_pop(struct anon_pipe_prealloc *prealloc)
{
    if (!prealloc->count)
        return NULL;

    prealloc->count--;

    return prealloc->pages[prealloc->count];
}

/* 【函数】anon_pipe_get_page —— 写路径取一页(持 pipe->mutex 时调用)
 * 取页优先级:1) 锁外预分配数组;2) 管道自带 tmp_page[] 页缓存;3) 锁内 alloc_page 兜底。
 * 先耗尽预分配页,是为了让 tmp_page[] 保持"热",留给后续的小写使用。 */
static struct page *anon_pipe_get_page(struct pipe_inode_info *pipe,
                       struct anon_pipe_prealloc *prealloc)
{
    struct page *page;

    /* Drain prealloc first to keep tmp_page[] hot for later small writes. */
    page = anon_pipe_prealloc_pop(prealloc);  // 先取锁外预分配的页
    if (page)
        return page;

    for (int i = 0; i < ARRAY_SIZE(pipe->tmp_page); i++) {  // 再查每管道页缓存 tmp_page[],取到即清空该槽
        if (pipe->tmp_page[i]) {
            page = pipe->tmp_page[i];
            pipe->tmp_page[i] = NULL;
            return page;
        }
    }

    /* FWIW: This is called with pipe->mutex held */
    return alloc_page(GFP_HIGHUSER | __GFP_ACCOUNT);  // 兜底:临界区内直接分配(英文注释指出此时持锁)
}

/* 【函数】anon_pipe_put_page —— 释放一页:优先塞回 tmp_page[] 页缓存
 * 只有 page_count==1(无 splice/tee 外部引用)才可缓存,否则真的 put_page。 */
static void anon_pipe_put_page(struct pipe_inode_info *pipe,
                   struct page *page)
{
    if (page_count(page) == 1) {  // 引用计数为 1 才能缓存:确认没有零拷贝外部引用
        for (int i = 0; i < ARRAY_SIZE(pipe->tmp_page); i++) {
            if (!pipe->tmp_page[i]) {
                pipe->tmp_page[i] = page;
                return;
            }
        }
    }

    put_page(page);
}

/*
 * Stash leftover prealloc pages in tmp_page[] so the next write to this
 * pipe gets a hot page without entering the allocator.
 */
/* 【函数】anon_pipe_refill_tmp_pages —— 写结束后把剩余预分配页塞进 tmp_page[]
 * 让本管道的下一次写直接拿到热页,不必再进分配器。 */
static void anon_pipe_refill_tmp_pages(struct pipe_inode_info *pipe,
                       struct anon_pipe_prealloc *prealloc)
{
    int i, idx;

    if (!prealloc->count)
        return;

    for (i = 0; i < ARRAY_SIZE(pipe->tmp_page); i++) {
        if (pipe->tmp_page[i])
            continue;
        if (!prealloc->count)
            return;
        idx = --prealloc->count;
        pipe->tmp_page[i] = prealloc->pages[idx];
        prealloc->pages[idx] = NULL;
    }
}

/* Runs after mutex_unlock() to keep put_page() out of the critical section. */
/* 【函数】anon_pipe_free_pages —— 释放仍用不完的预分配页
 * 在 mutex_unlock 之后调用(见英文注释):put_page 可能触发回收路径,移出临界区。 */
static void anon_pipe_free_pages(struct anon_pipe_prealloc *prealloc)
{
    while (prealloc->count) {
        prealloc->count--;
        put_page(prealloc->pages[prealloc->count]);  // put_page 在锁外执行
    }
}

四、pipe_buffer 操作集(release / try_steal / get) ​

匿名管道的 release/try_steal/get 三件套与通用版本;anon_pipe_buf_ops 是 splice/tee 零拷贝机制的挂载点。

c
/* 【函数】anon_pipe_buf_release —— 匿名管道 pipe_buffer 的 release 操作
 * 数据被读完(或管道销毁)时释放该槽位的页:走 anon_pipe_put_page,可被 tmp_page[] 回收。 */
static void anon_pipe_buf_release(struct pipe_inode_info *pipe,
                  struct pipe_buffer *buf)
{
    struct page *page = buf->page;

    anon_pipe_put_page(pipe, page);
}

/* 【函数】anon_pipe_buf_try_steal —— splice 偷页:把缓冲区页据为己有
 * 功能:splice 把管道页直接送进目标文件页缓存时调用。只有 page_count==1
 *       (唯一引用)才允许偷;成功后解除 memcg kmem 计费并置 PG_locked
 *       (页缓存约定:新插入页缓存的页要以锁定态返回)。
 * 返回:true = 偷取成功且页已锁定;false = 有外部引用,不能偷 */
static bool anon_pipe_buf_try_steal(struct pipe_inode_info *pipe,
        struct pipe_buffer *buf)
{
    struct page *page = buf->page;

    if (page_count(page) != 1)  // 引用计数不为 1:页被 tee/splice 复制过,不能独占
        return false;
    memcg_kmem_uncharge_page(page, 0);  // 页将离开管道归入页缓存,撤销其 memcg kmem 计费
    __SetPageLocked(page);  // 置 PG_locked:符合"页缓存中的新页处于锁定态"的约定
    return true;
}

/**
 * generic_pipe_buf_try_steal - attempt to take ownership of a &pipe_buffer
 * @pipe:    the pipe that the buffer belongs to
 * @buf:    the buffer to attempt to steal
 *
 * Description:
 *    This function attempts to steal the &struct page attached to
 *    @buf. If successful, this function returns 0 and returns with
 *    the page locked. The caller may then reuse the page for whatever
 *    he wishes; the typical use is insertion into a different file
 *    page cache.
 */
/* 【函数】generic_pipe_buf_try_steal —— 通用版偷页(供其他 pipe_buffer 类型复用)
 * 与匿名管道版不同:用 lock_page() 等待获得页锁,而不是直接 __SetPageLocked。 */
bool generic_pipe_buf_try_steal(struct pipe_inode_info *pipe,
        struct pipe_buffer *buf)
{
    struct page *page = buf->page;

    /*
     * A reference of one is golden, that means that the owner of this
     * page is the only one holding a reference to it. lock the page
     * and return OK.
     */
    if (page_count(page) == 1) {  // 引用计数为 1 = 唯一属主,可以安全独占(见英文注释)
        lock_page(page);
        return true;
    }
    return false;
}
EXPORT_SYMBOL(generic_pipe_buf_try_steal);

/**
 * generic_pipe_buf_get - get a reference to a &pipe_buffer
 * @pipe:    the pipe that the buffer belongs to
 * @buf:    the buffer to get a reference to
 *
 * Description:
 *    This function grabs an extra reference to @buf. It's used in
 *    the tee() system call, when we duplicate the buffers in one
 *    pipe into another.
 */
/* 【函数】generic_pipe_buf_get —— 给 pipe_buffer 的页加引用:tee() 复制缓冲区时用 */
bool generic_pipe_buf_get(struct pipe_inode_info *pipe, struct pipe_buffer *buf)
{
    return try_get_page(buf->page);
}
EXPORT_SYMBOL(generic_pipe_buf_get);

/**
 * generic_pipe_buf_release - put a reference to a &pipe_buffer
 * @pipe:    the pipe that the buffer belongs to
 * @buf:    the buffer to put a reference to
 *
 * Description:
 *    This function releases a reference to @buf.
 */
/* 【函数】generic_pipe_buf_release —— 通用版释放:直接 put_page */
void generic_pipe_buf_release(struct pipe_inode_info *pipe,
                  struct pipe_buffer *buf)
{
    put_page(buf->page);
}
EXPORT_SYMBOL(generic_pipe_buf_release);

/* 匿名管道的 pipe_buffer 操作集:release 走页缓存回收、try_steal 支持 splice 偷页、get 复用通用版 */
static const struct pipe_buf_operations anon_pipe_buf_ops = {
    .release    = anon_pipe_buf_release,  // 数据读完/管道销毁时调用
    .try_steal    = anon_pipe_buf_try_steal,  // splice 移出页时调用
    .get        = generic_pipe_buf_get,  // tee 复制缓冲区时调用
};

五、读路径(pipe_readable / pipe_update_tail / anon_pipe_read / fifo_pipe_read) ​

无锁谓词 pipe_readable、tail 推进 pipe_update_tail、读主循环 anon_pipe_read(含 PACKET/WHOLE 语义与 note_loss 丢失通知)及 FIFO 封装 fifo_pipe_read。

c
/* Done while waiting without holding the pipe lock - thus the READ_ONCE() */
/* 【函数】pipe_readable —— 无锁判断"管道是否可读"(等待队列的条件谓词)
 * 睡眠等待时不持锁,所以用 READ_ONCE + union pipe_index 把 head/tail 合成一个 64 位值
 * 一次原子读入,避免头尾撕裂(见英文注释)。
 * 返回:缓冲区非空 或 没有写者(EOF 也算"可读",read 返回 0)即为真。 */
static inline bool pipe_readable(const struct pipe_inode_info *pipe)
{
    union pipe_index idx = { .head_tail = READ_ONCE(pipe->head_tail) };  // 64 位一次性原子读 head+tail,避免分开读到的撕裂状态
    unsigned int writers = READ_ONCE(pipe->writers);  // writers 同样无锁读

    return !pipe_empty(idx.head, idx.tail) || !writers;  // 有数据可读,或写者已全部关闭(读到 EOF),都视为可读
}

/* 【函数】pipe_update_tail —— 读完一个 pipe_buffer 后推进 tail
 * 功能:先 release 该槽位的页,再把 tail+1 写回 pipe->tail。
 *       watch_queue 管道的通知发布方只持 rd_wait.lock 自旋锁(不持 mutex),
 *       所以写 tail 必须在同一自旋锁下完成;普通管道 mutex 已足够。
 * 返回:推进后的新 tail */
static inline unsigned int pipe_update_tail(struct pipe_inode_info *pipe,
                        struct pipe_buffer *buf,
                        unsigned int tail)
{
    pipe_buf_release(pipe, buf);  // 释放该槽位的页(ops->release;匿名管道会尝试塞回 tmp_page[])

    /*
     * If the pipe has a watch_queue, we need additional protection
     * by the spinlock because notifications get posted with only
     * this spinlock, no mutex
     */
    if (pipe_has_watch_queue(pipe)) {  // watch_queue 管道:通知发布方只拿这个自旋锁,tail 更新必须与其互斥
        spin_lock_irq(&pipe->rd_wait.lock);
#ifdef CONFIG_WATCH_QUEUE
        if (buf->flags & PIPE_BUF_FLAG_LOSS)  // 丢过通知:记录 note_loss,读者随后会读到 LOSS 元通知
            pipe->note_loss = true;
#endif
        pipe->tail = ++tail;  // 自旋锁保护下推进 tail
        spin_unlock_irq(&pipe->rd_wait.lock);
        return tail;
    }

    /*
     * Without a watch_queue, we can simply increment the tail
     * without the spinlock - the mutex is enough.
     */
    pipe->tail = ++tail;  // 普通管道:mutex 已保证互斥,直接推进 tail
    return tail;
}

/* 【函数】anon_pipe_read —— 匿名管道读路径(.read_iter 实现)
 * 功能:把环形缓冲区中的数据按 (page, offset, len) 逐槽 copy_page_to_iter 到用户态。
 * 参数:iocb —— I/O 控制块(ki_filp 取文件,ki_flags 含 IOCB_NOWAIT);
 *       to   —— 用户缓冲区迭代器
 * 返回:实际读到的字节数;0 = EOF(无写者);负 errno(-EAGAIN/-ENOBUFS/-EFAULT/-ERESTARTSYS)
 * 关键逻辑:
 *   1. PIPE_BUF_FLAG_WHOLE:包模式下缓冲区要么整包读走,要么 -ENOBUFS;
 *   2. PIPE_BUF_FLAG_PACKET:读到一个包即止,包内剩余字节直接丢弃;
 *   3. wake_writer:仅当"开始读时是满的、读完不再满"才唤醒写者,避免无意义唤醒;
 *   4. 无数据且无写者 -> EOF;无数据有写者 -> 非阻塞 -EAGAIN,阻塞则放锁睡 rd_wait;
 *   5. 被唤醒后若仍有剩余数据,置 wake_next_reader 接力唤醒下一个读者(防惊群);
 *   6. watch_queue 管道优先吐出 note_loss 丢失通知(WATCH_META_LOSS_NOTIFICATION)。 */
static ssize_t
anon_pipe_read(struct kiocb *iocb, struct iov_iter *to)
{
    size_t total_len = iov_iter_count(to);
    struct file *filp = iocb->ki_filp;
    struct pipe_inode_info *pipe = filp->private_data;
    bool wake_writer = false, wake_next_reader = false;
    ssize_t ret;

    /* Null read succeeds. */
    if (unlikely(total_len == 0))  // count==0 的读永远成功返回 0(POSIX)
        return 0;

    ret = 0;
    mutex_lock(&pipe->mutex);  // 读路径全程持 pipe->mutex

    /*
     * We only wake up writers if the pipe was full when we started reading
     * and it is no longer full after reading to avoid unnecessary wakeups.
     *
     * But when we do wake up writers, we do so using a sync wakeup
     * (WF_SYNC), because we want them to get going and generate more
     * data for us.
     */
    for (;;) {
        /* Read ->head with a barrier vs post_one_notification() */
        unsigned int head = smp_load_acquire(&pipe->head);  // acquire 语义读 head:与 watch_queue 通知发布配对(见英文注释)
        unsigned int tail = pipe->tail;

#ifdef CONFIG_WATCH_QUEUE
        if (pipe->note_loss) {  // 有丢失通知要优先上报
            struct watch_notification n;

            if (total_len < 8) {  // 用户缓冲区放不下 8 字节元通知:-ENOBUFS
                if (ret == 0)
                    ret = -ENOBUFS;
                break;
            }

            n.type = WATCH_TYPE_META;  // 构造"通知丢失"元通知
            n.subtype = WATCH_META_LOSS_NOTIFICATION;
            n.info = watch_sizeof(n);
            if (copy_to_iter(&n, sizeof(n), to) != sizeof(n)) {  // 拷贝失败:-EFAULT
                if (ret == 0)
                    ret = -EFAULT;
                break;
            }
            ret += sizeof(n);
            total_len -= sizeof(n);
            pipe->note_loss = false;  // 丢失通知只上报一次
        }
#endif

        if (!pipe_empty(head, tail)) {  // 环非空:有数据可读
            struct pipe_buffer *buf = pipe_buf(pipe, tail);  // 取 tail 处的槽位(pipe_buf 内部按掩码取模)
            size_t chars = buf->len;
            size_t written;
            int error;

            if (chars > total_len) {  // 用户要的字节比该槽现有数据少
                if (buf->flags & PIPE_BUF_FLAG_WHOLE) {  // WHOLE 包:不允许拆读,缓冲区太小报 -ENOBUFS
                    if (ret == 0)
                        ret = -ENOBUFS;
                    break;
                }
                chars = total_len;
            }

            error = pipe_buf_confirm(pipe, buf);  // confirm:缓冲区有效性确认(watch_queue 等使用)
            if (error) {
                if (!ret)
                    ret = error;
                break;
            }

            written = copy_page_to_iter(buf->page, buf->offset, chars, to);  // 核心拷贝:把页内 [offset, offset+chars) 拷给用户
            if (unlikely(written < chars)) {
                if (!ret)
                    ret = -EFAULT;
                break;
            }
            ret += chars;
            buf->offset += chars;
            buf->len -= chars;

            /* Was it a packet buffer? Clean up and exit */
            if (buf->flags & PIPE_BUF_FLAG_PACKET) {  // PACKET 包模式:本次读结束,包内剩余字节丢弃
                total_len = chars;
                buf->len = 0;
            }

            if (!buf->len) {
                wake_writer |= pipe_full(head, tail, pipe->max_usage);  // 仅当"读之前是满的"才记录需要唤醒写者(由满变不满)
                tail = pipe_update_tail(pipe, buf, tail);  // 槽已读空:推进 tail 并释放页
            }
            total_len -= chars;
            if (!total_len)
                break;    /* common path: read succeeded */
            if (!pipe_empty(head, tail))    /* More to do? */
                continue;
        }

        if (!pipe->writers)  // 无写者:EOF
            break;
        if (ret)  // 已读到数据:返回部分数据,不再阻塞
            break;
        if ((filp->f_flags & O_NONBLOCK) ||  // 非阻塞或 NOWAIT:无数据直接 -EAGAIN
            (iocb->ki_flags & IOCB_NOWAIT)) {
            ret = -EAGAIN;
            break;
        }
        mutex_unlock(&pipe->mutex);  // 睡前放锁:写者需要拿锁才能补数据
        /*
         * We only get here if we didn't actually read anything.
         *
         * But because we didn't read anything, at this point we can
         * just return directly with -ERESTARTSYS if we're interrupted,
         * since we've done any required wakeups and there's no need
         * to mark anything accessed. And we've dropped the lock.
         */
        if (wait_event_interruptible_exclusive(pipe->rd_wait, pipe_readable(pipe)) < 0)  // 独占式可中断等待:一次只醒一个读者;被信号打断且没读到数据则 -ERESTARTSYS
            return -ERESTARTSYS;

        wake_next_reader = true;  // 醒来后重新持锁;稍后视情况接力唤醒下一个读者
        mutex_lock(&pipe->mutex);
    }
    if (pipe_is_empty(pipe))  // 管道已空:无需接力唤醒其他读者
        wake_next_reader = false;
    mutex_unlock(&pipe->mutex);

    if (wake_writer)  // 由满变不满:WF_SYNC 同步唤醒写者,让它尽快补数据
        wake_up_interruptible_sync_poll(&pipe->wr_wait, EPOLLOUT | EPOLLWRNORM);
    if (wake_next_reader)  // 接力唤醒其他读者(与独占式等待配对)
        wake_up_interruptible_sync_poll(&pipe->rd_wait, EPOLLIN | EPOLLRDNORM);
    kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);  // fasync:给写者发 SIGIO/POLL_OUT(管道双向都支持 SIGIO)
    return ret;
}

/* 【函数】fifo_pipe_read —— FIFO 读封装:复用 anon_pipe_read,
 * 成功读到数据后 file_accessed() 更新 atime(FIFO 挂在真实文件系统上,有时间戳语义)。 */
static ssize_t
fifo_pipe_read(struct kiocb *iocb, struct iov_iter *to)
{
    int ret = anon_pipe_read(iocb, to);
    if (ret > 0)
        file_accessed(iocb->ki_filp);  // 更新文件访问时间
    return ret;
}

六、写路径(is_packetized / pipe_writable / anon_pipe_write / fifo_pipe_write) ​

包模式判定 is_packetized、无锁谓词 pipe_writable、写主循环 anon_pipe_write(CAN_MERGE 合并写、每槽一整页、写满睡眠与接力唤醒)及 FIFO 封装 fifo_pipe_write。

c
/* 【函数】is_packetized —— 是否包模式:O_DIRECT 打开的管道按"包"写入(PIPE_BUF_FLAG_PACKET) */
static inline int is_packetized(struct file *file)
{
    return (file->f_flags & O_DIRECT) != 0;
}

/* Done while waiting without holding the pipe lock - thus the READ_ONCE() */
/* 【函数】pipe_writable —— 无锁判断"管道是否可写"(等待队列的条件谓词)
 * 与 pipe_readable 同理:union pipe_index 一次 64 位原子读 head/tail;
 * max_usage/readers 各自 READ_ONCE。缓冲区不满 或 没有读者(写会立即 -EPIPE)即为真。 */
static inline bool pipe_writable(const struct pipe_inode_info *pipe)
{
    union pipe_index idx = { .head_tail = READ_ONCE(pipe->head_tail) };
    unsigned int max_usage = READ_ONCE(pipe->max_usage);

    return !pipe_full(idx.head, idx.tail, max_usage) ||  // 环未满,或读者已全部关闭(写必然失败,别睡了)
        !READ_ONCE(pipe->readers);
}

/* 【函数】anon_pipe_write —— 匿名管道写路径(.write_iter 实现)
 * 功能:把用户数据按页拷进环形缓冲区;支持 CAN_MERGE 合并写与 O_DIRECT 包模式。
 * 参数:iocb —— I/O 控制块;from —— 用户数据迭代器
 * 返回:实际写入字节数;负 errno(-EPIPE/-EAGAIN/-ENOMEM/-EFAULT/-ERESTARTSYS/-EXDEV)
 * 关键逻辑:
 *   1. watch_queue 通知管道拒写(-EXDEV):避免与普通管道产生锁序问题;
 *   2. 无读者:发 SIGPIPE 并 -EPIPE(IOCB_NOSIGNAL 时不发信号);
 *   3. 合并写:最后一槽带 CAN_MERGE 且剩余空间够,则先合并写入——既合并小写,
 *      又顺势把跨页大写的后续部分对齐到页边界;
 *   4. 每槽一整页:逐槽取页(预分配 -> tmp_page[] -> 锁内兜底),每槽至多拷 PAGE_SIZE;
 *   5. 写满:非阻塞 -EAGAIN;否则放锁睡 wr_wait,醒后重检空满并置接力唤醒;
 *   6. was_empty/poll_usage:管道由空变不空(或 epoll 在场)时 WF_SYNC 唤醒读者,
 *      GNU make jobserver 依赖小写的即时唤醒;
 *   7. wake_next_writer:让出锁睡过觉的写者,退出前接力唤醒下一个写者。 */
static ssize_t
anon_pipe_write(struct kiocb *iocb, struct iov_iter *from)
{
    struct file *filp = iocb->ki_filp;
    struct pipe_inode_info *pipe = filp->private_data;
    struct anon_pipe_prealloc prealloc;
    unsigned int head;
    ssize_t ret = 0;
    size_t total_len = iov_iter_count(from);
    ssize_t chars;
    bool was_empty = false;
    bool wake_next_writer = false;

    /*
     * Reject writing to watch queue pipes before the point where we lock
     * the pipe.
     * Otherwise, lockdep would be unhappy if the caller already has another
     * pipe locked.
     * If we had to support locking a normal pipe and a notification pipe at
     * the same time, we could set up lockdep annotations for that, but
     * since we don't actually need that, it's simpler to just bail here.
     */
    if (pipe_has_watch_queue(pipe))  // 通知管道不可写:直接 -EXDEV(见上方英文注释的 lockdep 说明)
        return -EXDEV;

    /* Null write succeeds. */
    if (unlikely(total_len == 0))  // count==0 的写永远成功
        return 0;

    anon_pipe_get_page_prealloc(&prealloc, total_len);  // 锁外预分配页(多页写时)

    mutex_lock(&pipe->mutex);  // 写路径全程持 pipe->mutex

    if (!pipe->readers) {  // 无读者:SIGPIPE + -EPIPE
        if ((iocb->ki_flags & IOCB_NOSIGNAL) == 0)  // IOCB_NOSIGNAL(如 splice 来时)不发信号
            send_sig(SIGPIPE, current, 0);
        ret = -EPIPE;
        goto out;
    }

    /*
     * If it wasn't empty we try to merge new data into
     * the last buffer.
     *
     * That naturally merges small writes, but it also
     * page-aligns the rest of the writes for large writes
     * spanning multiple pages.
     */
    head = pipe->head;  // 重读 head 并记录起始是否为空(之后唤醒读者要用)
    was_empty = pipe_empty(head, pipe->tail);
    chars = total_len & (PAGE_SIZE-1);  // 取不足一页的零头:先尝试合并进最后一槽
    if (chars && !was_empty) {
        struct pipe_buffer *buf = pipe_buf(pipe, head - 1);
        int offset = buf->offset + buf->len;

        if ((buf->flags & PIPE_BUF_FLAG_CAN_MERGE) &&  // CAN_MERGE 且槽内剩余空间足够,才可合并
            offset + chars <= PAGE_SIZE) {
            ret = pipe_buf_confirm(pipe, buf);
            if (ret)
                goto out;

            ret = copy_page_from_iter(buf->page, offset, chars, from);  // 把零头追加到最后一页的尾部
            if (unlikely(ret < chars)) {
                ret = -EFAULT;
                goto out;
            }

            buf->len += ret;  // 更新槽长度;若用户数据刚好写完,直接收工
            if (!iov_iter_count(from))
                goto out;
        }
    }

    for (;;) {
        if (!pipe->readers) {  // 循环里每次重查读者:等待期间读者可能全部消失
            if ((iocb->ki_flags & IOCB_NOSIGNAL) == 0)
                send_sig(SIGPIPE, current, 0);
            if (!ret)
                ret = -EPIPE;
            break;
        }

        head = pipe->head;
        if (!pipe_full(head, pipe->tail, pipe->max_usage)) {  // 环未满:还有空槽可写
            struct pipe_buffer *buf;
            struct page *page;
            int copied;

            page = anon_pipe_get_page(pipe, &prealloc);  // 取页:预分配 -> tmp_page[] -> 锁内分配兜底
            if (unlikely(!page)) {
                if (!ret)
                    ret = -ENOMEM;
                break;
            }

            copied = copy_page_from_iter(page, 0, PAGE_SIZE, from);  // 每槽一整页:最多拷 PAGE_SIZE
            if (unlikely(copied < PAGE_SIZE && iov_iter_count(from))) {  // 拷贝不足一页且用户还有数据:用户缓冲区故障,-EFAULT
                anon_pipe_put_page(pipe, page);
                if (!ret)
                    ret = -EFAULT;
                break;
            }

            pipe->head = head + 1;  // 先推进 head,再填槽(head 单调递增,解引用时才掩码)
            /* Insert it into the buffer array */
            buf = pipe_buf(pipe, head);
            buf->page = page;
            buf->ops = &anon_pipe_buf_ops;  // 挂上匿名管道操作集:供读完后 release、splice 时 try_steal
            buf->offset = 0;
            if (is_packetized(filp))  // O_DIRECT 包模式:整槽是一个包,不可合并
                buf->flags = PIPE_BUF_FLAG_PACKET;
            else
                buf->flags = PIPE_BUF_FLAG_CAN_MERGE;  // 普通模式:允许后续写合并进来

            buf->len = copied;
            ret += copied;

            if (!iov_iter_count(from))
                break;

            continue;
        }

        /* Wait for buffer space to become available. */
        if ((filp->f_flags & O_NONBLOCK) ||  // 写满且非阻塞/NOWAIT:-EAGAIN
            (iocb->ki_flags & IOCB_NOWAIT)) {
            if (!ret)
                ret = -EAGAIN;
            break;
        }
        if (signal_pending(current)) {  // 有信号待处理:未写任何数据则 -ERESTARTSYS
            if (!ret)
                ret = -ERESTARTSYS;
            break;
        }

        /*
         * We're going to release the pipe lock and wait for more
         * space. We wake up any readers if necessary, and then
         * after waiting we need to re-check whether the pipe
         * become empty while we dropped the lock.
         */
        mutex_unlock(&pipe->mutex);  // 睡前放锁:读者需要拿锁才能腾出空间
        if (was_empty)
            wake_up_interruptible_sync_poll(&pipe->rd_wait, EPOLLIN | EPOLLRDNORM);  // 若入睡时管道是空的,先唤醒读者来读
        kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);  // fasync:给读者发 SIGIO/POLL_IN
        wait_event_interruptible_exclusive(pipe->wr_wait, pipe_writable(pipe));  // 独占式等待"可写":一次只醒一个写者
        mutex_lock(&pipe->mutex);
        was_empty = pipe_is_empty(pipe);  // 重新持锁后重查空满(放锁期间状态可能已变)
        wake_next_writer = true;  // 睡过觉的写者:退出时接力唤醒下一个写者
    }
out:
    anon_pipe_refill_tmp_pages(pipe, &prealloc);  // 剩余预分配页塞回 tmp_page[] 页缓存
    if (pipe_is_full(pipe))  // 写完后管道仍是满的:不接力唤醒写者(唤醒也无槽可用)
        wake_next_writer = false;
    mutex_unlock(&pipe->mutex);
    anon_pipe_free_pages(&prealloc);  // 锁外释放用不完的预分配页

    /*
     * If we do do a wakeup event, we do a 'sync' wakeup, because we
     * want the reader to start processing things asap, rather than
     * leave the data pending.
     *
     * This is particularly important for small writes, because of
     * how (for example) the GNU make jobserver uses small writes to
     * wake up pending jobs
     *
     * Epoll nonsensically wants a wakeup whether the pipe
     * was already empty or not.
     */
    if (was_empty || pipe->poll_usage)  // 由空变不空(或 epoll 关注):WF_SYNC 同步唤醒读者——小写即时唤醒(jobserver 场景)
        wake_up_interruptible_sync_poll(&pipe->rd_wait, EPOLLIN | EPOLLRDNORM);
    kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);  // fasync:给读者发 SIGIO/POLL_IN
    if (wake_next_writer)  // 接力唤醒其他写者
        wake_up_interruptible_sync_poll(&pipe->wr_wait, EPOLLOUT | EPOLLWRNORM);
    return ret;
}

/* 【函数】fifo_pipe_write —— FIFO 写封装:复用 anon_pipe_write,
 * 成功后更新 mtime/ctime;sb_start_write_trylock 保证不在文件系统冻结期间更新。 */
static ssize_t
fifo_pipe_write(struct kiocb *iocb, struct iov_iter *from)
{
    int ret = anon_pipe_write(iocb, from);
    if (ret > 0) {
        struct file *filp = iocb->ki_filp;
        if (sb_start_write_trylock(file_inode(filp)->i_sb)) {  // 文件系统未冻结时才更新时间戳
            int err = file_update_time(filp);  // 更新 mtime/ctime
            if (err)
                ret = err;
            sb_end_write(file_inode(filp)->i_sb);
        }
    }
    return ret;
}

七、pipe_ioctl 与 pipe_poll ​

FIONREAD 统计可读字节数、watch_queue 的两个配置命令,以及全程不持锁的 pipe_poll。

c
/* 【函数】pipe_ioctl —— 管道 ioctl
 * FIONREAD:返回可读字节总数(各槽 len 之和);
 * IOC_WATCH_QUEUE_SET_SIZE/FILTER:配置 watch_queue 通知管道(CONFIG_WATCH_QUEUE)。 */
static long pipe_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
    struct pipe_inode_info *pipe = filp->private_data;
    unsigned int count, head, tail;

    switch (cmd) {
    case FIONREAD:  // FIONREAD:统计当前可读字节总数
        mutex_lock(&pipe->mutex);
        count = 0;
        head = pipe->head;
        tail = pipe->tail;

        while (!pipe_empty(head, tail)) {  // 遍历环中所有有数据的槽,累加 len
            count += pipe_buf(pipe, tail)->len;
            tail++;
        }
        mutex_unlock(&pipe->mutex);

        return put_user(count, (int __user *)arg);  // 结果写回用户态 int

#ifdef CONFIG_WATCH_QUEUE
    case IOC_WATCH_QUEUE_SET_SIZE: {  // 设置 watch_queue 的通知槽数(通知管道专用)
        int ret;
        mutex_lock(&pipe->mutex);
        ret = watch_queue_set_size(pipe, arg);
        mutex_unlock(&pipe->mutex);
        return ret;
    }

    case IOC_WATCH_QUEUE_SET_FILTER:  // 设置通知过滤器
        return watch_queue_set_filter(
            pipe, (struct watch_notification_filter __user *)arg);
#endif

    default:
        return -ENOIOCTLCMD;  // 不支持的命令
    }
}

/* No kernel lock held - fine */
/* 【函数】pipe_poll —— select/poll/epoll 的底层实现
 * 全程不持锁:先 poll_wait 挂等待队列,再做"有竞态"的状态判断——即使判断错了,
 * 之后的唤醒也会纠错(见英文注释)。首次调用时顺手置位 poll_usage(epoll 的历史语义:
 * 写端写完无论管道是否由空变不空都要收到唤醒)。 */
static __poll_t
pipe_poll(struct file *filp, poll_table *wait)
{
    __poll_t mask;
    struct pipe_inode_info *pipe = filp->private_data;
    union pipe_index idx;

    /* Epoll has some historical nasty semantics, this enables them */
    if (unlikely(!READ_ONCE(pipe->poll_usage)))  // 首次 poll:置位 poll_usage,使能 epoll 的"总是唤醒"历史语义
        WRITE_ONCE(pipe->poll_usage, true);

    /*
     * Reading pipe state only -- no need for acquiring the semaphore.
     *
     * But because this is racy, the code has to add the
     * entry to the poll table _first_ ..
     */
    if (filp->f_mode & FMODE_READ)  // 读端挂 rd_wait
        poll_wait(filp, &pipe->rd_wait, wait);
    if (filp->f_mode & FMODE_WRITE)  // 写端挂 wr_wait
        poll_wait(filp, &pipe->wr_wait, wait);

    /*
     * .. and only then can you do the racy tests. That way,
     * if something changes and you got it wrong, the poll
     * table entry will wake you up and fix it.
     */
    idx.head_tail = READ_ONCE(pipe->head_tail);  // 64 位原子读 head/tail

    mask = 0;
    if (filp->f_mode & FMODE_READ) {
        if (!pipe_empty(idx.head, idx.tail))  // 有数据:EPOLLIN
            mask |= EPOLLIN | EPOLLRDNORM;
        if (!pipe->writers && filp->f_pipe != pipe->w_counter)  // 无写者且本端见过写者(f_pipe 配对计数):EPOLLHUP;fifo_open 负责抑制未见写者时的 HUP
            mask |= EPOLLHUP;
    }

    if (filp->f_mode & FMODE_WRITE) {
        if (!pipe_full(idx.head, idx.tail, pipe->max_usage))  // 不满:EPOLLOUT
            mask |= EPOLLOUT | EPOLLWRNORM;
        /*
         * Most Unices do not set EPOLLERR for FIFOs but on Linux they
         * behave exactly like pipes for poll().
         */
        if (!pipe->readers)  // 无读者:EPOLLERR(Linux 上 FIFO 与管道行为一致)
            mask |= EPOLLERR;
    }

    return mask;
}

八、release / fasync 与配额记账 ​

文件关闭钩子 pipe_release、SIGIO 的 fasync 管理,以及按用户的管道页记账与软/硬上限判定。

c
/* 【函数】put_pipe_info —— files 引用计数减一;归零时彻底销毁管道
 * files 的增减在 inode->i_lock 自旋锁下完成,与 fifo_open 的并发打开互斥。 */
static void put_pipe_info(struct inode *inode, struct pipe_inode_info *pipe)
{
    int kill = 0;

    spin_lock(&inode->i_lock);
    if (!--pipe->files) {  // 最后一个文件关闭:摘下 inode->i_pipe 并标记销毁
        inode->i_pipe = NULL;
        kill = 1;
    }
    spin_unlock(&inode->i_lock);

    if (kill)
        free_pipe_info(pipe);  // 真正释放管道控制块
}

/* 【函数】pipe_release —— 文件关闭钩子(.release)
 * 递减 readers/writers;若仅剩一端(读者或写者之一归零而另一端非零),
 * 唤醒两端所有等待者并发 SIGIO——对端要感知"再也不会有数据/空间了"。 */
static int
pipe_release(struct inode *inode, struct file *file)
{
    struct pipe_inode_info *pipe = file->private_data;

    mutex_lock(&pipe->mutex);
    if (file->f_mode & FMODE_READ)  // 按打开模式递减读者计数
        pipe->readers--;
    if (file->f_mode & FMODE_WRITE)  // 按打开模式递减写者计数
        pipe->writers--;

    /* Was that the last reader or writer, but not the other side? */
    if (!pipe->readers != !pipe->writers) {  // 一端归零而另一端非零:!a != !b 的异或判断
        wake_up_interruptible_all(&pipe->rd_wait);  // 全部唤醒(不是独占式):挂起的一端都要看到对端关闭
        wake_up_interruptible_all(&pipe->wr_wait);
        kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
        kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
    }
    mutex_unlock(&pipe->mutex);

    put_pipe_info(inode, pipe);
    return 0;
}

/* 【函数】pipe_fasync —— O_ASYNC 的 fasync 管理
 * 读端挂 fasync_readers、写端挂 fasync_writers;写端挂载失败时回滚读端(仅 on==1 会失败)。 */
static int
pipe_fasync(int fd, struct file *filp, int on)
{
    struct pipe_inode_info *pipe = filp->private_data;
    int retval = 0;

    mutex_lock(&pipe->mutex);
    if (filp->f_mode & FMODE_READ)
        retval = fasync_helper(fd, filp, on, &pipe->fasync_readers);  // 读端 SIGIO 列表
    if ((filp->f_mode & FMODE_WRITE) && retval >= 0) {  // 写端 SIGIO 列表
        retval = fasync_helper(fd, filp, on, &pipe->fasync_writers);
        if (retval < 0 && (filp->f_mode & FMODE_READ))
            /* this can happen only if on == T */
            fasync_helper(-1, filp, 0, &pipe->fasync_readers);  // 回滚读端(见英文注释:只有 on==1 才会走到这)
    }
    mutex_unlock(&pipe->mutex);
    return retval;
}

/* 【函数】account_pipe_buffers —— 按用户记账管道页数(用 new 替换 old),返回该用户当前总数 */
unsigned long account_pipe_buffers(struct user_struct *user,
                   unsigned long old, unsigned long new)
{
    return atomic_long_add_return(new - old, &user->pipe_bufs);  // atomic_long_add_return:多线程下安全增减 user->pipe_bufs
}

/* 【函数】too_many_pipe_buffers_soft —— 该用户是否超过管道页软上限(0 = 不限制) */
bool too_many_pipe_buffers_soft(unsigned long user_bufs)
{
    unsigned long soft_limit = READ_ONCE(pipe_user_pages_soft);

    return soft_limit && user_bufs > soft_limit;
}

/* 【函数】too_many_pipe_buffers_hard —— 该用户是否超过管道页硬上限(0 = 不限制) */
bool too_many_pipe_buffers_hard(unsigned long user_bufs)
{
    unsigned long hard_limit = READ_ONCE(pipe_user_pages_hard);

    return hard_limit && user_bufs > hard_limit;
}

/* 【函数】pipe_is_unprivileged_user —— 无 CAP_SYS_RESOURCE/CAP_SYS_ADMIN 即"非特权用户",配额只约束他们 */
bool pipe_is_unprivileged_user(void)
{
    return !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN);
}

九、alloc_pipe_info / free_pipe_info ​

管道控制块的分配(含配额检查与降级流程)与销毁。

c
/* 【函数】alloc_pipe_info —— 分配并初始化管道控制块
 * 配额流程:先按 PIPE_DEF_BUFFERS(16) 记账 -> 超软上限的非特权用户降级为
 * PIPE_MIN_DEF_BUFFERS(2)(保住 jobserver 语义的最低限度)-> 超硬上限直接失败。
 * 容量还受 pipe_max_size 约束(有 CAP_SYS_RESOURCE 可豁免)。
 * 返回:初始化好的 pipe_inode_info;失败返回 NULL */
struct pipe_inode_info *alloc_pipe_info(void)
{
    struct pipe_inode_info *pipe;
    unsigned long pipe_bufs = PIPE_DEF_BUFFERS;  // 默认 16 槽(PIPE_DEF_BUFFERS = 64KB)
    struct user_struct *user = get_current_user();  // 拿当前用户结构引用:配额记在它头上
    unsigned long user_bufs;
    unsigned int max_size = READ_ONCE(pipe_max_size);

    pipe = kzalloc_obj(struct pipe_inode_info, GFP_KERNEL_ACCOUNT);  // kzalloc_obj:类型化分配(kzalloc + 类型安全),GFP_KERNEL_ACCOUNT 计入 memcg
    if (pipe == NULL)
        goto out_free_uid;

    if (pipe_bufs * PAGE_SIZE > max_size && !capable(CAP_SYS_RESOURCE))  // 非特权用户的默认容量不能超过 pipe_max_size
        pipe_bufs = max_size >> PAGE_SHIFT;

    user_bufs = account_pipe_buffers(user, 0, pipe_bufs);  // 记账:0 -> pipe_bufs

    if (too_many_pipe_buffers_soft(user_bufs) && pipe_is_unprivileged_user()) {  // 超软上限:降级为最小 2 槽并重新记账(防 jobserver 死锁,见文件头英文注释)
        user_bufs = account_pipe_buffers(user, pipe_bufs, PIPE_MIN_DEF_BUFFERS);
        pipe_bufs = PIPE_MIN_DEF_BUFFERS;
    }

    if (too_many_pipe_buffers_hard(user_bufs) && pipe_is_unprivileged_user())  // 超硬上限:直接失败
        goto out_revert_acct;

    pipe->bufs = kzalloc_objs(struct pipe_buffer, pipe_bufs,  // kzalloc_objs:类型化数组分配 pipe_buffer 环
                  GFP_KERNEL_ACCOUNT);

    if (pipe->bufs) {
        init_waitqueue_head(&pipe->rd_wait);
        init_waitqueue_head(&pipe->wr_wait);
        pipe->r_counter = pipe->w_counter = 1;  // r_counter/w_counter 配对计数:fifo_open 对端等待、f_pipe 抑制 EPOLLHUP 用
        pipe->max_usage = pipe_bufs;  // max_usage:当前允许使用的槽数上限(写满判定用)
        pipe->ring_size = pipe_bufs;  // ring_size:环的实际槽数(分配大小)
        pipe->nr_accounted = pipe_bufs;  // nr_accounted:已按用户记账的槽数
        pipe->user = user;
        mutex_init(&pipe->mutex);
        lock_set_cmp_fn(&pipe->mutex, pipe_lock_cmp_fn, NULL);  // 注册 lockdep 地址比较函数(仅 PROVE_LOCKING 下生效)
        return pipe;
    }

out_revert_acct:  // 配额回滚:把刚记的账减掉
    (void) account_pipe_buffers(user, pipe_bufs, 0);
    kfree(pipe);
out_free_uid:  // 释放 get_current_user() 拿的引用
    free_uid(user);
    return NULL;
}

/* 【函数】free_pipe_info —— 销毁管道:清 watch_queue、回滚配额、逐槽 release 页、
 * 释放 tmp_page[] 页缓存、释放环数组与控制块。 */
void free_pipe_info(struct pipe_inode_info *pipe)
{
    unsigned int i;

#ifdef CONFIG_WATCH_QUEUE
    if (pipe->watch_queue)  // 清空中转的通知队列
        watch_queue_clear(pipe->watch_queue);
#endif

    (void) account_pipe_buffers(pipe->user, pipe->nr_accounted, 0);  // 配额全部回滚
    free_uid(pipe->user);
    for (i = 0; i < pipe->ring_size; i++) {  // 遍历整个环,释放仍占着页的槽
        struct pipe_buffer *buf = pipe->bufs + i;
        if (buf->ops)
            pipe_buf_release(pipe, buf);
    }
#ifdef CONFIG_WATCH_QUEUE
    if (pipe->watch_queue)
        put_watch_queue(pipe->watch_queue);
#endif
    for (i = 0; i < ARRAY_SIZE(pipe->tmp_page); i++) {  // 释放页缓存中暂存的页
        if (pipe->tmp_page[i])
            __free_page(pipe->tmp_page[i]);
    }
    kfree(pipe->bufs);
    kfree(pipe);
}

十、pipefs、get_pipe_inode 与 create_pipe_files ​

pipefs 伪文件系统的 dentry 命名(pipe:[ino])、伪 inode 创建,以及读/写两个 file 对象的构建。

c
static struct vfsmount *pipe_mnt __ro_after_init;  // pipefs 的内核挂载点(__ro_after_init:初始化后只读,防篡改)

/*
 * pipefs_dname() is called from d_path().
 */
/* 【函数】pipefs_dname —— 生成管道 dentry 的名字:"pipe:[ino]",
 * /proc/<pid>/fd 下的符号链接就长这样(由 d_path() 回调)。 */
static char *pipefs_dname(struct dentry *dentry, char *buffer, int buflen)
{
    return dynamic_dname(buffer, buflen, "pipe:[%llu]",  // 动态生成 "pipe:[ino]" 形式的名字
                d_inode(dentry)->i_ino);
}

static const struct dentry_operations pipefs_dentry_operations = {
    .d_dname    = pipefs_dname,
};

static const struct file_operations pipeanon_fops;

/* 【函数】get_pipe_inode —— 在 pipefs 上创建一个伪 inode 并挂好管道控制块
 * 初始化 files=2(读端+写端两个 file)、readers=writers=1、i_fop=pipeanon_fops;
 * 故意把 inode 置为 I_DIRTY 原始态,使它永远不会再被挂进脏链表(见英文注释)。 */
static struct inode * get_pipe_inode(void)
{
    struct inode *inode = new_inode_pseudo(pipe_mnt->mnt_sb);  // 伪文件系统 inode:无真实目录项
    struct pipe_inode_info *pipe;

    if (!inode)
        goto fail_inode;

    inode->i_ino = get_next_ino();

    pipe = alloc_pipe_info();
    if (!pipe)
        goto fail_iput;

    inode->i_pipe = pipe;
    pipe->files = 2;  // 两个 file(读端+写端)引用本管道
    pipe->readers = pipe->writers = 1;
    inode->i_fop = &pipeanon_fops;

    /*
     * Mark the inode dirty from the very beginning,
     * that way it will never be moved to the dirty
     * list because "mark_inode_dirty()" will think
     * that it already _is_ on the dirty list.
     */
    inode_state_assign_raw(inode, I_DIRTY);  // 一步到位置脏:此后 mark_inode_dirty 认为它已在脏链表,跳过处理
    inode->i_mode = S_IFIFO | S_IRUSR | S_IWUSR;  // FIFO 类型 + 属主读写权限
    inode->i_uid = current_fsuid();
    inode->i_gid = current_fsgid();
    simple_inode_init_ts(inode);

    return inode;

fail_iput:  // 失败:释放 inode
    iput(inode);

fail_inode:
    return NULL;
}

/* 【函数】create_pipe_files —— 创建管道的两个 file 对象(res[0]=读端,res[1]=写端)
 * 用 alloc_file_pseudo 建写端、alloc_file_clone 克隆读端;两端都标 FMODE_NOWAIT
 * (支持 IOCB_NOWAIT)并以 file_set_fsnotify_mode 关掉权限/前置 fsnotify 事件。
 * flags 带 O_NOTIFICATION_PIPE 时初始化为 watch_queue 通知管道。 */
int create_pipe_files(struct file **res, int flags)
{
    struct inode *inode = get_pipe_inode();
    struct file *f;
    int error;

    if (!inode)
        return -ENFILE;

    if (flags & O_NOTIFICATION_PIPE) {  // 通知管道:初始化 watch_queue
        error = watch_queue_init(inode->i_pipe);
        if (error) {
            free_pipe_info(inode->i_pipe);
            iput(inode);
            return error;
        }
    }

    f = alloc_file_pseudo(inode, pipe_mnt, "",  // 写端 file:O_WRONLY,继承 O_NONBLOCK|O_DIRECT
                O_WRONLY | (flags & (O_NONBLOCK | O_DIRECT)),
                &pipeanon_fops);
    if (IS_ERR(f)) {
        free_pipe_info(inode->i_pipe);
        iput(inode);
        return PTR_ERR(f);
    }

    f->private_data = inode->i_pipe;
    f->f_pipe = 0;

    res[0] = alloc_file_clone(f, O_RDONLY | (flags & O_NONBLOCK),  // 读端 file:从写端克隆,O_RDONLY
                  &pipeanon_fops);
    if (IS_ERR(res[0])) {
        put_pipe_info(inode, inode->i_pipe);
        fput(f);
        return PTR_ERR(res[0]);
    }
    res[0]->private_data = inode->i_pipe;
    res[0]->f_pipe = 0;
    res[1] = f;
    stream_open(inode, res[0]);  // stream_open:管道不可 seek(清 FMODE_LSEEK 等)
    stream_open(inode, res[1]);

    /* pipe groks IOCB_NOWAIT */
    res[0]->f_mode |= FMODE_NOWAIT;  // 两端都支持 IOCB_NOWAIT(nowait 下直接 -EAGAIN 而不睡眠)
    res[1]->f_mode |= FMODE_NOWAIT;

    /*
     * Disable permission and pre-content events, but enable legacy
     * inotify events for legacy users.
     */
    file_set_fsnotify_mode(res[0], FMODE_NONOTIFY_PERM);  // 关闭权限/前置类 fsnotify 事件,保留传统 inotify 事件
    file_set_fsnotify_mode(res[1], FMODE_NONOTIFY_PERM);
    return 0;
}

十一、pipe / pipe2 系统调用 ​

__do_pipe_flags 主流程、do_pipe_flags/do_pipe2 两种收尾方式,以及 pipe、pipe2 两个 SYSCALL_DEFINE 入口。

c
/* 【函数】__do_pipe_flags —— 管道创建主流程:校验 flags -> create_pipe_files ->
 * 申请两个未用 fd -> audit_fd_pair 审计。调用方负责 fd_install 或 copy_to_user。 */
static int __do_pipe_flags(int *fd, struct file **files, int flags)
{
    int error;
    int fdw, fdr;

    if (flags & ~(O_CLOEXEC | O_NONBLOCK | O_DIRECT | O_NOTIFICATION_PIPE))  // 只接受这四种 flag,其余 -EINVAL
        return -EINVAL;

    error = create_pipe_files(files, flags);
    if (error)
        return error;

    error = get_unused_fd_flags(flags);  // 读端 fd
    if (error < 0)
        goto err_read_pipe;
    fdr = error;

    error = get_unused_fd_flags(flags);  // 写端 fd
    if (error < 0)
        goto err_fdr;
    fdw = error;

    audit_fd_pair(fdr, fdw);  // 审计 fd 对
    fd[0] = fdr;
    fd[1] = fdw;
    return 0;

 err_fdr:  // 出错回滚:回收 fd、关闭两个 file
    put_unused_fd(fdr);
 err_read_pipe:
    fput(files[0]);
    fput(files[1]);
    return error;
}

/* 【函数】do_pipe_flags —— __do_pipe_flags 成功后把两个 fd 装进当前进程 fd 表(内核内部使用) */
int do_pipe_flags(int *fd, int flags)
{
    struct file *files[2];
    int error = __do_pipe_flags(fd, files, flags);
    if (!error) {
        fd_install(fd[0], files[0]);  // fd_install 后文件对进程可见
        fd_install(fd[1], files[1]);
    }
    return error;
}

/*
 * sys_pipe() is the normal C calling standard for creating
 * a pipe. It's not the way Unix traditionally does this, though.
 */
/* 【函数】do_pipe2 —— pipe2 系统调用的实现主体
 * 与 do_pipe_flags 的区别:fd 通过 copy_to_user 写回用户数组,失败要完整回滚。 */
static int do_pipe2(int __user *fildes, int flags)
{
    struct file *files[2];
    int fd[2];
    int error;

    error = __do_pipe_flags(fd, files, flags);
    if (!error) {
        if (unlikely(copy_to_user(fildes, fd, sizeof(fd)))) {  // 回拷失败:关闭文件、回收 fd,报 -EFAULT
            fput(files[0]);
            fput(files[1]);
            put_unused_fd(fd[0]);
            put_unused_fd(fd[1]);
            error = -EFAULT;
        } else {
            fd_install(fd[0], files[0]);
            fd_install(fd[1], files[1]);
        }
    }
    return error;
}

/* 【系统调用】pipe2(2):带 flags 创建管道(O_CLOEXEC/O_NONBLOCK/O_DIRECT/O_NOTIFICATION_PIPE) */
SYSCALL_DEFINE2(pipe2, int __user *, fildes, int, flags)
{
    return do_pipe2(fildes, flags);
}

/* 【系统调用】pipe(2):等价于 pipe2(fildes, 0) */
SYSCALL_DEFINE1(pipe, int __user *, fildes)
{
    return do_pipe2(fildes, 0);
}

十二、pipe_wait_* 与 fifo_open ​

供外部子系统(splice 等)使用的等待助手,以及 FIFO 打开的三模式 POSIX 语义实现。

c
/*
 * This is the stupid "wait for pipe to be readable or writable"
 * model.
 *
 * See pipe_read/write() for the proper kind of exclusive wait,
 * but that requires that we wake up any other readers/writers
 * if we then do not end up reading everything (ie the whole
 * "wake_next_reader/writer" logic in pipe_read/write()).
 */
/* 【函数】pipe_wait_readable —— 供外部子系统(如 splice)使用的"等可读":
 * 放锁 -> 普通(非独占)等待 -> 重新加锁。与读写路径的独占等待不同,见上方英文注释。 */
void pipe_wait_readable(struct pipe_inode_info *pipe)
{
    pipe_unlock(pipe);  // 睡前放锁
    wait_event_interruptible(pipe->rd_wait, pipe_readable(pipe));  // 非独占等待:醒一批,由调用者自己保证进展
    pipe_lock(pipe);
}

/* 【函数】pipe_wait_writable —— 与 pipe_wait_readable 对称的"等可写"版本 */
void pipe_wait_writable(struct pipe_inode_info *pipe)
{
    pipe_unlock(pipe);
    wait_event_interruptible(pipe->wr_wait, pipe_writable(pipe));
    pipe_lock(pipe);
}

/*
 * This depends on both the wait (here) and the wakeup (wake_up_partner)
 * holding the pipe lock, so "*cnt" is stable and we know a wakeup cannot
 * race with the count check and waitqueue prep.
 *
 * Normally in order to avoid races, you'd do the prepare_to_wait() first,
 * then check the condition you're waiting for, and only then sleep. But
 * because of the pipe lock, we can check the condition before being on
 * the wait queue.
 *
 * We use the 'rd_wait' waitqueue for pipe partner waiting.
 */
/* 【函数】wait_for_partner —— FIFO open 阻塞等"对端"到来
 * 等待条件是对端配对计数 *cnt 变化。依赖调用方与 wake_up_partner 都持 pipe 锁:
 * 计数判断与睡眠准备之间不会丢失唤醒(见上方英文注释)。借 rd_wait 队列睡眠。
 * 返回:0 = 对端已来;-ERESTARTSYS = 被信号打断 */
static int wait_for_partner(struct pipe_inode_info *pipe, unsigned int *cnt)
{
    DEFINE_WAIT(rdwait);  // 等待队列项
    int cur = *cnt;

    while (cur == *cnt) {  // 计数不变就继续睡
        prepare_to_wait(&pipe->rd_wait, &rdwait, TASK_INTERRUPTIBLE);  // 准备睡眠(先于放锁,靠 pipe 锁保证不丢唤醒)
        pipe_unlock(pipe);
        schedule();
        finish_wait(&pipe->rd_wait, &rdwait);
        pipe_lock(pipe);
        if (signal_pending(current))  // 被信号打断:退出循环返回 -ERESTARTSYS
            break;
    }
    return cur == *cnt ? -ERESTARTSYS : 0;
}

/* 【函数】wake_up_partner —— 对端到来:唤醒 rd_wait 上所有等待的 open */
static void wake_up_partner(struct pipe_inode_info *pipe)
{
    wake_up_interruptible_all(&pipe->rd_wait);
}

/* 【函数】fifo_open —— FIFO 与匿名管道 file 的 .open 实现
 * 三种打开模式(POSIX 语义):
 *   O_RDONLY:非阻塞时立即成功(f_pipe 抑制未见写者的 EPOLLHUP);阻塞时等写端;
 *   O_WRONLY:非阻塞且无读者 -> -ENXIO;阻塞时等读端;
 *   O_RDWR :永不阻塞(至少能自发自收),readers/writers 各加一。
 * r_counter/w_counter 是单调配对计数,wait_for_partner 靠它判断"对端来了"。
 * 首次打开时惰性分配 pipe_inode_info(i_lock 下防止并发重复分配)。 */
static int fifo_open(struct inode *inode, struct file *filp)
{
    bool is_pipe = inode->i_fop == &pipeanon_fops;  // 区分匿名管道还是 FIFO(FIFO 才有对端等待语义)
    struct pipe_inode_info *pipe;
    int ret;

    filp->f_pipe = 0;

    spin_lock(&inode->i_lock);
    if (inode->i_pipe) {  // 已有管道:i_lock 下引用计数 +1
        pipe = inode->i_pipe;
        pipe->files++;
        spin_unlock(&inode->i_lock);
    } else {
        spin_unlock(&inode->i_lock);
        pipe = alloc_pipe_info();  // 首次打开:锁外分配管道控制块
        if (!pipe)
            return -ENOMEM;
        pipe->files = 1;
        spin_lock(&inode->i_lock);
        if (unlikely(inode->i_pipe)) {  // 并发竞争:别人先装上了,放弃自己分配的,用对方那份
            inode->i_pipe->files++;
            spin_unlock(&inode->i_lock);
            free_pipe_info(pipe);
            pipe = inode->i_pipe;
        } else {
            inode->i_pipe = pipe;
            spin_unlock(&inode->i_lock);
        }
    }
    filp->private_data = pipe;
    /* OK, we have a pipe and it's pinned down */

    mutex_lock(&pipe->mutex);

    /* We can only do regular read/write on fifos */
    stream_open(inode, filp);  // FIFO 只允许普通读写(不可 seek)

    switch (filp->f_mode & (FMODE_READ | FMODE_WRITE)) {
    case FMODE_READ:
    /*
     *  O_RDONLY
     *  POSIX.1 says that O_NONBLOCK means return with the FIFO
     *  opened, even when there is no process writing the FIFO.
     */
        pipe->r_counter++;  // 读者配对计数 +1
        if (pipe->readers++ == 0)  // 首个读者:唤醒等待中的写端 open
            wake_up_partner(pipe);

        if (!is_pipe && !pipe->writers) {  // FIFO 且尚无写者
            if ((filp->f_flags & O_NONBLOCK)) {
                /* suppress EPOLLHUP until we have
                 * seen a writer */
                filp->f_pipe = pipe->w_counter;  // 非阻塞读端:记录当前 w_counter,pipe_poll 据此在见过写者前不给 EPOLLHUP
            } else {
                if (wait_for_partner(pipe, &pipe->w_counter))  // 阻塞读端:等写端到来
                    goto err_rd;
            }
        }
        break;

    case FMODE_WRITE:
    /*
     *  O_WRONLY
     *  POSIX.1 says that O_NONBLOCK means return -1 with
     *  errno=ENXIO when there is no process reading the FIFO.
     */
        ret = -ENXIO;  // 非阻塞写端无读者:POSIX 规定 -ENXIO
        if (!is_pipe && (filp->f_flags & O_NONBLOCK) && !pipe->readers)
            goto err;

        pipe->w_counter++;  // 写者配对计数 +1
        if (!pipe->writers++)  // 首个写者:唤醒等待中的读端 open
            wake_up_partner(pipe);

        if (!is_pipe && !pipe->readers) {  // 阻塞写端:等读端到来
            if (wait_for_partner(pipe, &pipe->r_counter))
                goto err_wr;
        }
        break;

    case FMODE_READ | FMODE_WRITE:
    /*
     *  O_RDWR
     *  POSIX.1 leaves this case "undefined" when O_NONBLOCK is set.
     *  This implementation will NEVER block on a O_RDWR open, since
     *  the process can at least talk to itself.
     */

        pipe->readers++;  // O_RDWR:两端计数都加,永不等待
        pipe->writers++;
        pipe->r_counter++;
        pipe->w_counter++;
        if (pipe->readers == 1 || pipe->writers == 1)  // 本进程的到来可能正好凑成对端
            wake_up_partner(pipe);
        break;

    default:
        ret = -EINVAL;
        goto err;
    }

    /* Ok! */
    mutex_unlock(&pipe->mutex);
    return 0;

err_rd:  // 打开失败回滚:撤销读者计数,必要时唤醒写端
    if (!--pipe->readers)
        wake_up_interruptible(&pipe->wr_wait);
    ret = -ERESTARTSYS;
    goto err;

err_wr:  // 撤销写者计数,必要时唤醒读端
    if (!--pipe->writers)
        wake_up_interruptible_all(&pipe->rd_wait);
    ret = -ERESTARTSYS;
    goto err;

err:
    mutex_unlock(&pipe->mutex);

    put_pipe_info(inode, pipe);
    return ret;
}

十三、fops 表与容量调整(round_pipe_size / pipe_resize_ring / pipe_set_size / get_pipe_info / pipe_fcntl) ​

pipefifo_fops 与 pipeanon_fops 两张操作表;容量取整、环形缓冲区搬迁扩容、配额校验与 F_SETPIPE_SZ/F_GETPIPE_SZ。

c
/* FIFO 的 file_operations:读写带文件语义(atime/mtime),open 有对端等待 */
const struct file_operations pipefifo_fops = {
    .open        = fifo_open,
    .read_iter    = fifo_pipe_read,
    .write_iter    = fifo_pipe_write,
    .poll        = pipe_poll,
    .unlocked_ioctl    = pipe_ioctl,
    .release    = pipe_release,
    .fasync        = pipe_fasync,
    .splice_write    = iter_file_splice_write,
};

/* 匿名管道的 file_operations:读写走纯 anon 路径;open 复用 fifo_open(is_pipe 分支直通) */
static const struct file_operations pipeanon_fops = {
    .open        = fifo_open,
    .read_iter    = anon_pipe_read,
    .write_iter    = anon_pipe_write,
    .poll        = pipe_poll,
    .unlocked_ioctl    = pipe_ioctl,
    .release    = pipe_release,
    .fasync        = pipe_fasync,
    .splice_write    = iter_file_splice_write,
};

/*
 * Currently we rely on the pipe array holding a power-of-2 number
 * of pages. Returns 0 on error.
 */
/* 【函数】round_pipe_size —— 把字节数规整为合法的管道容量:
 * 下限一页(POSIX 要求)、上限 2^31,向上取 2 的幂(环形掩码的前提)。返回 0 表示非法。 */
unsigned int round_pipe_size(unsigned int size)
{
    if (size > (1U << 31))  // 超过 2^31 无法表示(head/tail 索引上限)
        return 0;

    /* Minimum pipe size, as required by POSIX */
    if (size < PAGE_SIZE)  // POSIX 要求至少一页
        return PAGE_SIZE;

    return roundup_pow_of_two(size);  // 向上取 2 的幂:环形掩码 ring_size-1 的前提
}

/*
 * Resize the pipe ring to a number of slots.
 *
 * Note the pipe can be reduced in capacity, but only if the current
 * occupancy doesn't exceed nr_slots; if it does, EBUSY will be
 * returned instead.
 */
/* 【函数】pipe_resize_ring —— 调整环形缓冲区槽数
 * 数据搬迁:把环中 [tail, head) 的有效槽按序拷到新数组头部,head/tail 归零重排。
 * 缩容时若当前数据量超过新槽数 -> -EBUSY。全程持 rd_wait.lock(与 watch_queue
 * 通知发布互斥)。watch_queue 管道不更新 max_usage/nr_accounted(配额语义例外)。
 * 返回:0 或负 errno */
int pipe_resize_ring(struct pipe_inode_info *pipe, unsigned int nr_slots)
{
    struct pipe_buffer *bufs;
    unsigned int head, tail, mask, n;

    /* nr_slots larger than limits of pipe->{head,tail} */
    if (unlikely(nr_slots > (pipe_index_t)-1u))  // 槽数不能超过 head/tail 索引类型上限(pipe_index_t,2^31-1)
        return -EINVAL;

    bufs = kzalloc_objs(*bufs, nr_slots, GFP_KERNEL_ACCOUNT | __GFP_NOWARN);  // 分配新环(NOWARN:失败不打印告警)
    if (unlikely(!bufs))
        return -ENOMEM;

    spin_lock_irq(&pipe->rd_wait.lock);  // 搬迁期间用自旋锁把读写两侧挡在外面
    mask = pipe->ring_size - 1;
    head = pipe->head;
    tail = pipe->tail;

    n = pipe_occupancy(head, tail);  // 当前数据量 = head - tail
    if (nr_slots < n) {  // 缩容放不下现有数据:-EBUSY
        spin_unlock_irq(&pipe->rd_wait.lock);
        kfree(bufs);
        return -EBUSY;
    }

    /*
     * The pipe array wraps around, so just start the new one at zero
     * and adjust the indices.
     */
    if (n > 0) {
        unsigned int h = head & mask;
        unsigned int t = tail & mask;
        if (h > t) {  // 有效槽未跨界:一次 memcpy 搞定
            memcpy(bufs, pipe->bufs + t,
                   n * sizeof(struct pipe_buffer));
        } else {
            unsigned int tsize = pipe->ring_size - t;  // 跨界环绕:分两段拷贝
            if (h > 0)
                memcpy(bufs + tsize, pipe->bufs,
                       h * sizeof(struct pipe_buffer));
            memcpy(bufs, pipe->bufs + t,
                   tsize * sizeof(struct pipe_buffer));
        }
    }

    head = n;  // 新环从 0 开始重排:tail=0,head=数据量
    tail = 0;

    kfree(pipe->bufs);
    pipe->bufs = bufs;
    pipe->ring_size = nr_slots;
    if (pipe->max_usage > nr_slots)  // max_usage 不允许超过新环大小
        pipe->max_usage = nr_slots;
    pipe->tail = tail;
    pipe->head = head;

    if (!pipe_has_watch_queue(pipe)) {  // 普通管道:容量与记账一并更新;watch_queue 管道保持原配额(例外)
        pipe->max_usage = nr_slots;
        pipe->nr_accounted = nr_slots;
    }

    spin_unlock_irq(&pipe->rd_wait.lock);

    /* This might have made more room for writers */
    wake_up_interruptible(&pipe->wr_wait);  // 扩容可能给写者腾出了空间
    return 0;
}

/*
 * Allocate a new array of pipe buffers and copy the info over. Returns the
 * pipe size if successful, or return -ERROR on error.
 */
/* 【函数】pipe_set_size —— F_SETPIPE_SZ 的实现:容量校验 + 配额检查 + pipe_resize_ring
 * 扩容时:非特权用户不得超过 pipe_max_size、不得超 soft/hard 页配额;缩容永远允许。
 * 返回:新容量(max_usage * PAGE_SIZE)或负 errno */
static long pipe_set_size(struct pipe_inode_info *pipe, unsigned int arg)
{
    unsigned long user_bufs;
    unsigned int nr_slots, size;
    long ret = 0;

    if (pipe_has_watch_queue(pipe))  // watch_queue 管道的容量由 ioctl 管理,禁止 fcntl 调整
        return -EBUSY;

    size = round_pipe_size(arg);  // 字节数规整为 2 的幂
    nr_slots = size >> PAGE_SHIFT;  // 换算成槽数(页数)

    if (!nr_slots)
        return -EINVAL;

    /*
     * If trying to increase the pipe capacity, check that an
     * unprivileged user is not trying to exceed various limits
     * (soft limit check here, hard limit check just below).
     * Decreasing the pipe capacity is always permitted, even
     * if the user is currently over a limit.
     */
    if (nr_slots > pipe->max_usage &&  // 扩容且超 pipe_max_size:需要 CAP_SYS_RESOURCE
            size > pipe_max_size && !capable(CAP_SYS_RESOURCE))
        return -EPERM;

    user_bufs = account_pipe_buffers(pipe->user, pipe->nr_accounted, nr_slots);  // 先按新值记账,再检查

    if (nr_slots > pipe->max_usage &&  // 扩容且超用户 soft/hard 配额:-EPERM 并回滚记账
            (too_many_pipe_buffers_hard(user_bufs) ||
             too_many_pipe_buffers_soft(user_bufs)) &&
            pipe_is_unprivileged_user()) {
        ret = -EPERM;
        goto out_revert_acct;
    }

    ret = pipe_resize_ring(pipe, nr_slots);
    if (ret < 0)
        goto out_revert_acct;

    return pipe->max_usage * PAGE_SIZE;  // 返回实际可用容量

out_revert_acct:
    (void) account_pipe_buffers(pipe->user, nr_slots, pipe->nr_accounted);  // 失败:记账回滚
    return ret;
}

/*
 * Note that i_pipe and i_cdev share the same location, so checking ->i_pipe is
 * not enough to verify that this is a pipe.
 */
/* 【函数】get_pipe_info —— 校验一个 file 是否真的是管道(i_pipe 与 i_cdev 共用存储,
 * 只看 i_pipe 不够,必须比对 f_op);for_splice 时拒绝 watch_queue 管道。 */
struct pipe_inode_info *get_pipe_info(struct file *file, bool for_splice)
{
    struct pipe_inode_info *pipe = file->private_data;

    if (!pipe)
        return NULL;
    if (file->f_op != &pipefifo_fops && file->f_op != &pipeanon_fops)  // f_op 必须是两张管道操作表之一
        return NULL;
    if (for_splice && pipe_has_watch_queue(pipe))  // splice 不支持通知管道
        return NULL;
    return pipe;
}

/* 【函数】pipe_fcntl —— F_SETPIPE_SZ 调容量 / F_GETPIPE_SZ 读容量(返回 max_usage*PAGE_SIZE) */
long pipe_fcntl(struct file *file, unsigned int cmd, unsigned int arg)
{
    struct pipe_inode_info *pipe;
    long ret;

    pipe = get_pipe_info(file, false);
    if (!pipe)
        return -EBADF;

    mutex_lock(&pipe->mutex);

    switch (cmd) {
    case F_SETPIPE_SZ:  // 设置容量(字节数)
        ret = pipe_set_size(pipe, arg);
        break;
    case F_GETPIPE_SZ:  // 读取当前容量
        ret = pipe->max_usage * PAGE_SIZE;
        break;
    default:
        ret = -EINVAL;
        break;
    }

    mutex_unlock(&pipe->mutex);
    return ret;
}

十四、pipefs 注册、sysctl 与 init_pipe_fs ​

pipefs 文件系统类型的注册与内核挂载、/proc/sys/fs/pipe-* 三个 sysctl 参数,以及 fs_initcall 初始化入口。

c
/* pipefs 的 super_operations:伪文件系统,只需销毁 inode 与 statfs 两个钩子 */
static const struct super_operations pipefs_ops = {
    .destroy_inode = free_inode_nonrcu,
    .statfs = simple_statfs,
};

/*
 * pipefs should _never_ be mounted by userland - too much of security hassle,
 * no real gain from having the whole file system mounted. So we don't need
 * any operations on the root directory. However, we need a non-trivial
 * d_name - pipe: will go nicely and kill the special-casing in procfs.
 */

/* 【函数】pipefs_init_fs_context —— 用 init_pseudo 建 pipefs 的 fs_context
 * pipefs 永不暴露给用户态挂载(见英文注释);dentry 名 "pipe:[ino]" 顺便省去 procfs 特判。 */
static int pipefs_init_fs_context(struct fs_context *fc)
{
    struct pseudo_fs_context *ctx = init_pseudo(fc, PIPEFS_MAGIC);  // 伪文件系统上下文:PIPEFS_MAGIC
    if (!ctx)
        return -ENOMEM;
    ctx->ops = &pipefs_ops;
    ctx->dops = &pipefs_dentry_operations;
    return 0;
}

/* pipefs 文件系统类型:name="pipefs",卸载用 kill_anon_super */
static struct file_system_type pipe_fs_type = {
    .name        = "pipefs",
    .init_fs_context = pipefs_init_fs_context,
    .kill_sb    = kill_anon_super,
};

#ifdef CONFIG_SYSCTL

/* sysctl 辅助:把用户写入的 pipe-max-size 也按 round_pipe_size 规整(ulong 包装) */
static ulong round_pipe_size_ul(ulong size)
{
    return round_pipe_size(size);
}

/* 【函数】u2k_pipe_maxsz —— 用户值 -> 内核值 的转换钩子:写入时自动取整 */
static int u2k_pipe_maxsz(const ulong *u_ptr, uint *k_ptr)
{
    return proc_uint_u2k_conv_uop(u_ptr, k_ptr, round_pipe_size_ul);
}

/* 【函数】do_proc_uint_conv_pipe_maxsz —— 串起 u2k(取整)与 k2u(原样)两个转换方向 */
static int do_proc_uint_conv_pipe_maxsz(ulong *u_ptr, uint *k_ptr,
                    int dir, const struct ctl_table *table)
{
    return proc_uint_conv(u_ptr, k_ptr, dir, table, true,
                  u2k_pipe_maxsz,
                  proc_uint_k2u_conv);
}

/* 【函数】proc_dopipe_max_size —— pipe-max-size 的 proc 处理函数(基于 proc_douintvec_conv) */
static int proc_dopipe_max_size(const struct ctl_table *table, int write,
                void *buffer, size_t *lenp, loff_t *ppos)
{
    return proc_douintvec_conv(table, write, buffer, lenp, ppos,
                   do_proc_uint_conv_pipe_maxsz);
}

/* /proc/sys/fs/ 下的三个管道参数表:pipe-max-size(写入时自动取整)、每用户页硬/软上限 */
static const struct ctl_table fs_pipe_sysctls[] = {
    {
        .procname    = "pipe-max-size",
        .data        = &pipe_max_size,
        .maxlen        = sizeof(pipe_max_size),
        .mode        = 0644,
        .proc_handler    = proc_dopipe_max_size,
        .extra1        = SYSCTL_ONE,  // 最小值为 1
    },
    {
        .procname    = "pipe-user-pages-hard",
        .data        = &pipe_user_pages_hard,
        .maxlen        = sizeof(pipe_user_pages_hard),
        .mode        = 0644,
        .proc_handler    = proc_doulongvec_minmax,
    },
    {
        .procname    = "pipe-user-pages-soft",
        .data        = &pipe_user_pages_soft,
        .maxlen        = sizeof(pipe_user_pages_soft),
        .mode        = 0644,
        .proc_handler    = proc_doulongvec_minmax,
    },
};
#endif

/* 【函数】init_pipe_fs —— 初始化入口:注册 pipefs、内核挂载、注册三个 sysctl(fs_initcall) */
static int __init init_pipe_fs(void)
{
    int err = register_filesystem(&pipe_fs_type);  // 注册文件系统类型

    if (!err) {
        pipe_mnt = kern_mount(&pipe_fs_type);  // 内核态挂载(用户态不可见)
        if (IS_ERR(pipe_mnt)) {
            err = PTR_ERR(pipe_mnt);
            unregister_filesystem(&pipe_fs_type);
        }
    }
#ifdef CONFIG_SYSCTL
    register_sysctl_init("fs", fs_pipe_sysctls);  // 注册 /proc/sys/fs/pipe-max-size、pipe-user-pages-hard/soft
#endif
    return err;
}

fs_initcall(init_pipe_fs);  // fs_initcall:内核启动时随 VFS 子系统一起初始化

© fukaiqiang.com · 个人技术学习笔记 · 冀ICP备2026026950号 · 京公网安备11010802049509号