linux/net/core/gen_estimator.c 是 Linux 内核网络子系统中的一个源文件,用于实现通用速率估算器(Generic Estimator)。它的主要作用是周期性地估算网络设备或流量控制(TC, Traffic Control)对象的入/出速率(如 bytes per second、packets per second),供用户空间工具(如 tc, ip -s link)查看实时带宽统计。
📌 文件位置
- 路径:net/core/gen_estimator.c
- 所属模块:Linux 内核网络核心(Networking Core)
- 关联头文件:include/net/gen_stats.h
🔧 核心功能
该模块通过指数加权移动平均(EWMA, Exponentially Weighted Moving Average) 算法估算瞬时速率:
// 伪代码逻辑
rate = (current_bytes – last_bytes) / time_delta;
estimated_rate = (rate * weight) + (old_estimated_rate * (1 – weight));
实际实现中使用位移操作优化性能(避免浮点运算)。
// include/net/gen_stats.h
struct gnet_stats_basic_sync {
u64 bytes; // 总字节数(同步访问)
u64 packets; // 总包数
};
struct gnet_stats_rate_est {
u32 bps; // 估算的字节/秒 (bytes per second)
u32 pps; // 估算的包/秒 (packets per second)
};
函数 作用
gen_new_estimator() 为指定统计结构启动估算器(创建定时器)
gen_kill_estimator() 停止估算器(删除定时器)
est_timer() 定时器回调函数(默认每 500ms/1s/2s 触发)
gnet_stats_copy_basic() 安全复制统计计数(处理并发)
⚙️ 工作流程
初始化
当用户通过 tc 命令配置 qdisc/class 时(如 tc qdisc add dev eth0 root handle 1: htb),内核调用 gen_new_estimator() 启动估算。
定时采样
估算器以固定间隔(由 gen_estimator 的 interval 字段决定,默认 500ms/1s/2s)触发 est_timer():
- 读取当前 bytes/packets 计数
- 计算与上次采样的差值
- 更新 bps/pps 估算值
用户空间查询
用户执行 tc -s class show dev eth0 时,内核通过 netlink 返回包含 gnet_stats_rate_est 的统计信息。
🌰 使用示例
查看 HTB qdisc 的实时速率
tc -s class show dev eth0
输出中会包含:
rate 10Mbit 1250Kbps (估算值)
这些值由 gen_estimator.c 动态计算提供。
💡 关键设计特点
- 无锁设计:使用 u64_stats_fetch_begin_irq() 处理 64 位计数器的并发读取(避免在 32 位系统上撕裂读)
- 可配置间隔:通过 gen_estimator.interval 设置采样频率(值越小响应越快,但 CPU 开销越大)
- 通用性:不仅用于 TC,也用于网络设备统计(如 ip -s link 中的 RX/TX 速率)
📚 相关内核文档
- Documentation/networking/scheduler.rst
- TC 用户手册
如果需要分析具体代码实现细节或调试速率估算问题,可以进一步讨论!
网硕互联帮助中心

评论前必须登录!
注册