姚军
4K 随机读,队列深度 QD=1:
| 引擎 | IOPS | p99 延迟 |
|---|---|---|
| 同步 pread | 基准 | 最低 |
| io_uring | 略低 | 略高 |
队列深度 QD=32:
| 引擎 | IOPS | p99 延迟 |
|---|---|---|
| 同步 pread(多线程) | 受线程数限制 | 抖动大 |
| io_uring | 更稳定 |
io_uring 不是“更快的 IO”,是
这意味着硬件天生支持
| 设备类型 | 随机读延迟 |
|---|---|
| 企业级 NVMe | 3 ~ 10 μs |
| 消费级 NVMe | 20 ~ 100 μs |
| SATA SSD | 100 ~ 500 μs |
| 机械盘 | 5 ~ 10 ms |
单次 IO 只要几微秒,
这解释了一个现象:
| 模式 | 瓶颈 | 优化方向 |
|---|---|---|
| 4K 随机 | IOPS、队列深度 | 提高并发、减少 syscall |
| 128K 顺序 | 带宽 | 大块传输、减少拷贝 |
所以“要不要上 io_uring”,先看你的负载属于哪一类。
一次 IO 至少两次上下文切换,加上一次数据拷贝。
io_submit 仍是系统调用,完成通知依赖轮询或 eventfd。这就是 io_uring 出现的直接原因。
mmap 映射到用户态。极端情况下(SQPOLL),提交完全不需要系统调用。
| 能力 | 作用 |
|---|---|
| 批量提交 | 一次 io_uring_submit 提交多条命令 |
| 注册缓冲区 | 避免每次 IO 做页面锁定 |
| 注册文件 | 减少 fd 查找开销 |
| 链式操作 | 多条命令按顺序执行,如写 + fsync |
#include <liburing.h>
io_uring ring;
io_uring_queue_init(256, &ring, 0);
struct io_uring_sqe *sqe = io_uring_get_sqe(&ring);
io_uring_prep_read(sqe, fd, buf, 4096, offset);
io_uring_submit(&ring);
struct io_uring_cqe *cqe;
io_uring_wait_cqe(&ring, &cqe);
int ret = cqe->res;
io_uring_cqe_seen(&ring, cqe);
这是“能用”;要“吃满”,还得加上注册缓冲区和批量提交。
io_uring_queue_init(256, &ring, IORING_SETUP_SQPOLL);
io_uring_enter 的开销。判断标准:
// 写日志 + 刷盘,链式提交
sqe1 = io_uring_get_sqe(&ring);
io_uring_prep_write(sqe1, fd, buf, len, off);
sqe2 = io_uring_get_sqe(&ring);
io_uring_prep_fsync(sqe2, fd, IORING_FSYNC_DATASYNC);
sqe1->flags |= IOSQE_IO_LINK; // 顺序执行
把“写 + fsync”合并成一次提交,减少往返,是 WAL 场景的常见优化。
IORING_SETUP_SQ_AFF 绑定核。注意:多个 ring 共享同一块设备时,设备侧仍然是统一调度的,
IORING_OP_ACCEPT 的 multishot 模式,一次提交持续接受连接。IORING_OP_RECV 的 multishot,持续收包。这把“事件循环”从 epoll 的“通知 + 再 read”变成“直接投递读请求”。
| 场景 | 为什么不适合 |
|---|---|
| QD=1 的低延迟单次 IO | 提交开销占比高 |
| 顺序大块读且命中 page cache | 内核路径已经足够快 |
| 元数据密集(大量 open/stat) | 提升有限,复杂度高 |
| 内核版本过旧 | 功能和稳定性都不完整 |
# io_uring
fio --name=randread --ioengine=io_uring --iodepth=32 \
--bs=4k --rw=randread --direct=1 --filename=/dev/nvme0n1 \
--runtime=60 --time_based
# libaio
fio --name=randread --ioengine=libaio --iodepth=32 \
--bs=4k --rw=randread --direct=1 --filename=/dev/nvme0n1
# 同步
fio --name=randread --ioengine=psync --iodepth=1 \
--bs=4k --rw=randread --direct=1 --filename=/dev/nvme0n1
一定要扫 QD:1、8、32、128、256,才能看出拐点。
| 指标 | 含义 |
|---|---|
| IOPS | 吞吐能力 |
| p50 / p99 / p999 延迟 | 尾延迟是否可控 |
| CPU per IO | 每次 IO 消耗多少 CPU |
| 上下文切换次数 | vmstat -w、pidstat -w |
io_uring 的收益常常体现在
下一节:把 io_uring 接进存储引擎,还要处理完成顺序、错误恢复和优雅退出。