在复杂的网络通信中,内核需要维护大量与远端主机相关的长期状态信息(如ICMP速率限制、路径MTU等)。Linux内核通过INETPEER机制实现对端信息的统一管理,其设计精妙地平衡了性能、内存效率和安全性。本文将深入剖析这一核心机制。
一、设计目标:不只是数据存储
INETPEER的设计围绕四个核心目标:
-
长期信息存储:独立于路由系统,保存对端IP的持久状态
-
自动内存回收:基于引用计数+TTL实现智能垃圾回收
-
抗DoS攻击:避免传统哈希表在碰撞时的性能退化
-
高效并发:支持高并发场景下的安全读写
二、关键数据结构剖析
1. 对端节点(struct inet_peer)
struct inet_peer {
struct rb_node rb_node; // 红黑树节点
struct inetpeer_addr daddr; // 对端IP(IPv4/IPv6)
__u32 dtime; // 最后使用时间戳
refcount_t refcnt; // 原子引用计数
unsigned long rate_tokens; // 令牌桶计数
unsigned long rate_last; // 最后令牌更新时间
// ... 其他协议相关字段
};
2. 存储池(struct inet_peer_base)
struct inet_peer_base {
struct rb_root rb_root; // 红黑树根节点
seqlock_t lock; // 序列锁
int total; // 当前节点总数
};
三、动态初始化策略
系统启动时,inet_initpeers()根据物理内存动态调整回收阈值:
void __init inet_initpeers(void) {
struct sysinfo si;
si_meminfo(&si); // 获取内存信息
if (si.totalram <= (32768*1024)/PAGE_SIZE)
inet_peer_threshold >>= 1; // 低内存设备阈值减半
// ...
}
-
全局参数:
-
inet_peer_threshold:触发激进GC的节点数阈值 -
inet_peer_minttl:高负载下最小TTL(120秒) -
inet_peer_maxttl:正常TTL(10分钟)
-
四、节点生命周期管理
1. 查找与创建(inet_getpeer)
采用双路径查找策略:
struct inet_peer *inet_getpeer(/*...*/) {
// 无锁快速路径
rcu_read_lock();
p = lookup(daddr, base, seq, NULL, &gc_cnt, &parent, &pp);
rcu_read_unlock();
if (!p) {
// 加锁慢路径
write_seqlock_bh(&base->lock);
if (create) kmem_cache_alloc(peer_cachep, GFP_ATOMIC); // 原子分配
rb_insert_color(&p->rb_node, &base->rb_root); // 插入红黑树
}
}
-
无锁读:RCU+序列号检查实现安全访问
-
惰性创建:仅当必要且不存在时才分配新节点
2. 引用控制
-
inet_getpeer:引用计数+1 -
inet_putpeer:引用计数-1,归零时RCU释放
void inet_putpeer(struct inet_peer *p) {
if (refcount_dec_and_test(&p->refcnt))
call_rcu(&p->rcu, inetpeer_free_rcu); // 延迟释放
}
五、垃圾回收机制(inet_peer_gc)
回收策略随系统负载动态调整:
static void inet_peer_gc(/*...*/) {
if (base->total >= inet_peer_threshold)
ttl = 0; // 超限时立即回收
else
ttl = maxttl - (maxttl - minttl) * (负载比例); // 动态TTL
for (each gc_candidate) {
if ((jiffies - p->dtime) > ttl && refcount_dec_if_one(&p->refcnt))
rb_erase(&p->rb_node, &base->rb_root); // 从树中移除
}
}
-
两级回收策略:
-
查找时收集候选节点(gc_stack)
-
根据系统负载动态计算TTL
-
六、速率限制:令牌桶算法
inet_peer_xrlim_allow为ICMP等协议提供公平的速率控制:
bool inet_peer_xrlim_allow(struct inet_peer *peer, int timeout) {
token += now - peer->rate_last; // 累积令牌
if (token > XRLIM_BURST_FACTOR * timeout) // 限制突发
token = XRLIM_BURST_FACTOR * timeout;
if (token >= timeout) { // 检查是否允许发送
token -= timeout; // 扣除令牌
return true;
}
}
-
突发处理:XRLIM_BURST_FACTOR(6)允许短暂突发流量
-
双级限制:同时作用于源IP和目的IP
七、并发控制设计
-
序列锁(seqlock):
-
写锁:
write_seqlock_bh(&base->lock) -
读校验:
read_seqretry(&base->lock, seq)
-
-
原子引用计数:
-
refcount_inc_not_zero()确保安全获取
-
-
RCU释放:
-
节点释放通过
call_rcu()延迟执行
-
八、设计哲学与创新点
-
红黑树抗DoS:避免哈希碰撞攻击(传统链表退化问题)
-
动态TTL策略:

graph LR A[总节点数] -->|≥阈值| B[TTL=0 立即回收] A -->|<阈值| C[TTL=10min-动态衰减] -
无锁读优化:结合RCU和序列锁实现高效读取
-
令牌桶算法:XRLIM_BURST_FACTOR提供合理突发余量
九、典型应用场景
-
ICMP错误消息限制:
// icmp_send.c if (!inet_peer_xrlim_allow(peer, 10*HZ)) return; // 限速丢弃 -
TCP协议:
-
存储对端MSS、窗口缩放因子
-
维护路径MTU信息
-
-
IP分片重组:关联同一对端的分片包
十、总结
INETPEER机制通过三大核心设计成为网络子系统的基石:
-
高效存储结构:红黑树实现O(log n)操作复杂度
-
自适应回收策略:动态TTL平衡内存与性能
-
安全并发模型:RCU+序列锁+原子操作的黄金组合
其设计哲学体现了Linux内核"不做无谓优化,但在关键路径极致优化"的理念,为高负载网络环境提供了可靠的基础设施保障。随着云计算和5G网络的发展,这种对资源精细管控的设计思维将愈发重要。

/*
* INETPEER - A storage for permanent information about peers
*
* This source is covered by the GNU GPL, the same as all kernel sources.
*
* Authors: Andrey V. Savochkin <saw@msu.ru>
*/
#include <linux/cache.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/spinlock.h>
#include <linux/random.h>
#include <linux/timer.h>
#include <linux/time.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/net.h>
#include <linux/workqueue.h>
#include <net/ip.h>
#include <net/inetpeer.h>
#include <net/secure_seq.h>
/*
* Theory of operations.
* We keep one entry for each peer IP address. The nodes contains long-living
* information about the peer which doesn't depend on routes.
*
* Nodes are removed only when reference counter goes to 0.
* When it's happened the node may be removed when a sufficient amount of
* time has been passed since its last use. The less-recently-used entry can
* also be removed if the pool is overloaded i.e. if the total amount of
* entries is greater-or-equal than the threshold.
*
* Node pool is organised as an RB tree.
* Such an implementation has been chosen not just for fun. It's a way to
* prevent easy and efficient DoS attacks by creating hash collisions. A huge
* amount of long living nodes in a single hash slot would significantly delay
* lookups performed with disabled BHs.
*
* Serialisation issues.
* 1. Nodes may appear in the tree only with the pool lock held.
* 2. Nodes may disappear from the tree only with the pool lock held
* AND reference count being 0.
* 3. Global variable peer_total is modified under the pool lock.
* 4. struct inet_peer fields modification:
* rb_node: pool lock
* refcnt: atomically against modifications on other CPU;
* usually under some other lock to prevent node disappearing
* daddr: unchangeable
*/
static struct kmem_cache *peer_cachep __ro_after_init;
void inet_peer_base_init(struct inet_peer_base *bp)
{
bp->rb_root = RB_ROOT;
seqlock_init(&bp->lock);
bp->total = 0;
}
EXPORT_SYMBOL_GPL(inet_peer_base_init);
#define PEER_MAX_GC 32
/* Exported for sysctl_net_ipv4. */
int inet_peer_threshold __read_mostly = 65536 + 128; /* start to throw entries more
* aggressively at this stage */
int inet_peer_minttl __read_mostly = 120 * HZ; /* TTL under high load: 120 sec */
int inet_peer_maxttl __read_mostly = 10 * 60 * HZ; /* usual time to live: 10 min */
/* Called from ip_output.c:ip_init */
void __init inet_initpeers(void)
{
struct sysinfo si;
/* Use the straight interface to information about memory. */
si_meminfo(&si);
/* The values below were suggested by Alexey Kuznetsov
* <kuznet@ms2.inr.ac.ru>. I don't have any opinion about the values
* myself. --SAW
*/
if (si.totalram <= (32768*1024)/PAGE_SIZE)
inet_peer_threshold >>= 1; /* max pool size about 1MB on IA32 */
if (si.totalram <= (16384*1024)/PAGE_SIZE)
inet_peer_threshold >>= 1; /* about 512KB */
if (si.totalram <= (8192*1024)/PAGE_SIZE)
inet_peer_threshold >>= 2; /* about 128KB */
peer_cachep = kmem_cache_create("inet_peer_cache",
sizeof(struct inet_peer),
0, SLAB_HWCACHE_ALIGN | SLAB_PANIC,
NULL);
}
/* Called with rcu_read_lock() or base->lock held */
static struct inet_peer *lookup(const struct inetpeer_addr *daddr,
struct inet_peer_base *base,
unsigned int seq,
struct inet_peer *gc_stack[],
unsigned int *gc_cnt,
struct rb_node **parent_p,
struct rb_node ***pp_p)
{
struct rb_node **pp, *parent, *next;
struct inet_peer *p;
pp = &base->rb_root.rb_node;
parent = NULL;
while (1) {
int cmp;
next = rcu_dereference_raw(*pp);
if (!next)
break;
parent = next;
p = rb_entry(parent, struct inet_peer, rb_node);
cmp = inetpeer_addr_cmp(daddr, &p->daddr);
if (cmp == 0) {
if (!refcount_inc_not_zero(&p->refcnt))
break;
return p;
}
if (gc_stack) {
if (*gc_cnt < PEER_MAX_GC)
gc_stack[(*gc_cnt)++] = p;
} else if (unlikely(read_seqretry(&base->lock, seq))) {
break;
}
if (cmp == -1)
pp = &next->rb_left;
else
pp = &next->rb_right;
}
*parent_p = parent;
*pp_p = pp;
return NULL;
}
static void inetpeer_free_rcu(struct rcu_head *head)
{
kmem_cache_free(peer_cachep, container_of(head, struct inet_peer, rcu));
}
/* perform garbage collect on all items stacked during a lookup */
static void inet_peer_gc(struct inet_peer_base *base,
struct inet_peer *gc_stack[],
unsigned int gc_cnt)
{
struct inet_peer *p;
__u32 delta, ttl;
int i;
if (base->total >= inet_peer_threshold)
ttl = 0; /* be aggressive */
else
ttl = inet_peer_maxttl
- (inet_peer_maxttl - inet_peer_minttl) / HZ *
base->total / inet_peer_threshold * HZ;
for (i = 0; i < gc_cnt; i++) {
p = gc_stack[i];
delta = (__u32)jiffies - p->dtime;
if (delta < ttl || !refcount_dec_if_one(&p->refcnt))
gc_stack[i] = NULL;
}
for (i = 0; i < gc_cnt; i++) {
p = gc_stack[i];
if (p) {
rb_erase(&p->rb_node, &base->rb_root);
base->total--;
call_rcu(&p->rcu, inetpeer_free_rcu);
}
}
}
struct inet_peer *inet_getpeer(struct inet_peer_base *base,
const struct inetpeer_addr *daddr,
int create)
{
struct inet_peer *p, *gc_stack[PEER_MAX_GC];
struct rb_node **pp, *parent;
unsigned int gc_cnt, seq;
int invalidated;
/* Attempt a lockless lookup first.
* Because of a concurrent writer, we might not find an existing entry.
*/
rcu_read_lock();
seq = read_seqbegin(&base->lock);
p = lookup(daddr, base, seq, NULL, &gc_cnt, &parent, &pp);
invalidated = read_seqretry(&base->lock, seq);
rcu_read_unlock();
if (p)
return p;
/* If no writer did a change during our lookup, we can return early. */
if (!create && !invalidated)
return NULL;
/* retry an exact lookup, taking the lock before.
* At least, nodes should be hot in our cache.
*/
parent = NULL;
write_seqlock_bh(&base->lock);
gc_cnt = 0;
p = lookup(daddr, base, seq, gc_stack, &gc_cnt, &parent, &pp);
if (!p && create) {
p = kmem_cache_alloc(peer_cachep, GFP_ATOMIC);
if (p) {
p->daddr = *daddr;
p->dtime = (__u32)jiffies;
refcount_set(&p->refcnt, 2);
atomic_set(&p->rid, 0);
p->metrics[RTAX_LOCK-1] = INETPEER_METRICS_NEW;
p->rate_tokens = 0;
p->n_redirects = 0;
/* 60*HZ is arbitrary, but chosen enough high so that the first
* calculation of tokens is at its maximum.
*/
p->rate_last = jiffies - 60*HZ;
rb_link_node(&p->rb_node, parent, pp);
rb_insert_color(&p->rb_node, &base->rb_root);
base->total++;
}
}
if (gc_cnt)
inet_peer_gc(base, gc_stack, gc_cnt);
write_sequnlock_bh(&base->lock);
return p;
}
EXPORT_SYMBOL_GPL(inet_getpeer);
void inet_putpeer(struct inet_peer *p)
{
p->dtime = (__u32)jiffies;
if (refcount_dec_and_test(&p->refcnt))
call_rcu(&p->rcu, inetpeer_free_rcu);
}
EXPORT_SYMBOL_GPL(inet_putpeer);
/*
* Check transmit rate limitation for given message.
* The rate information is held in the inet_peer entries now.
* This function is generic and could be used for other purposes
* too. It uses a Token bucket filter as suggested by Alexey Kuznetsov.
*
* Note that the same inet_peer fields are modified by functions in
* route.c too, but these work for packet destinations while xrlim_allow
* works for icmp destinations. This means the rate limiting information
* for one "ip object" is shared - and these ICMPs are twice limited:
* by source and by destination.
*
* RFC 1812: 4.3.2.8 SHOULD be able to limit error message rate
* SHOULD allow setting of rate limits
*
* Shared between ICMPv4 and ICMPv6.
*/
#define XRLIM_BURST_FACTOR 6
bool inet_peer_xrlim_allow(struct inet_peer *peer, int timeout)
{
unsigned long now, token;
bool rc = false;
if (!peer)
return true;
token = peer->rate_tokens;
now = jiffies;
token += now - peer->rate_last;
peer->rate_last = now;
if (token > XRLIM_BURST_FACTOR * timeout)
token = XRLIM_BURST_FACTOR * timeout;
if (token >= timeout) {
token -= timeout;
rc = true;
}
peer->rate_tokens = token;
return rc;
}
EXPORT_SYMBOL(inet_peer_xrlim_allow);
void inetpeer_invalidate_tree(struct inet_peer_base *base)
{
struct rb_node *p = rb_first(&base->rb_root);
while (p) {
struct inet_peer *peer = rb_entry(p, struct inet_peer, rb_node);
p = rb_next(p);
rb_erase(&peer->rb_node, &base->rb_root);
inet_putpeer(peer);
cond_resched();
}
base->total = 0;
}
EXPORT_SYMBOL(inetpeer_invalidate_tree);
这个文件实现了 Linux 内核中的 INETPEER 机制,用于存储网络对端(peer)的长期信息(独立于路由)。以下是对其核心功能和实现原理的详细讲解:
核心目标
-
长期信息存储
存储与远端 IP 地址相关的持久化数据(如 ICMP 速率限制状态)。 -
自动垃圾回收 (GC)
当节点引用计数为 0 且超过生存时间 (TTL) 时自动释放。 -
抗 DoS 攻击
使用红黑树(而非哈希表)避免碰撞攻击导致性能退化。 -
高效并发
通过序列锁(seqlock)和原子操作实现读写并发。
关键数据结构
1. struct inet_peer
-
核心字段:
-
daddr:对端 IP 地址(IPv4/IPv6) -
refcnt:引用计数(原子操作) -
dtime:最后使用时间戳(用于 GC) -
rate_tokens/rate_last:令牌桶算法参数(速率限制) -
rb_node:红黑树节点指针
-
-
生命周期:节点通过
kmem_cache分配,引用计数归零时通过 RCU 延迟释放。
2. struct inet_peer_base
-
核心字段:
-
rb_root:红黑树根节点 -
lock:序列锁(保护树结构) -
total:当前节点总数
-
核心机制详解
1. 初始化与配置
-
inet_initpeers()
根据系统内存动态调整inet_peer_threshold(节点池阈值):-
内存 ≤ 32MB:阈值 = 64KB
-
内存 ≤ 16MB:阈值 = 32KB
-
内存 ≤ 8MB:阈值 = 16KB
-
-
全局参数:
-
inet_peer_threshold:触发积极 GC 的节点数阈值 -
inet_peer_minttl:高负载下最小 TTL(120 秒) -
inet_peer_maxttl:正常 TTL(10 分钟)
-
2. 节点查找与创建 (inet_getpeer)
-
无锁快速路径
使用read_seqbegin()读取序列号,在 RCU 保护下遍历红黑树查找节点。-
找到节点:增加
refcnt并返回。 -
未找到:若无需创建,直接返回
NULL。
-
-
加锁慢路径
获取写锁后:-
再次查找节点(避免重复创建)。
-
若需创建:
-
从
peer_cachep分配新节点。 -
初始化字段(地址、时间戳、引用计数=2)。
-
插入红黑树,增加
base->total。
-
-
垃圾回收:若查找过程中收集到候选节点(
gc_stack),调用inet_peer_gc()。
-
3. 垃圾回收 (inet_peer_gc)
-
触发条件:
-
显式:查找过程中收集到候选节点(
gc_stack)。 -
隐式:节点总数 ≥
inet_peer_threshold。
-
-
回收策略:
if (base->total >= inet_peer_threshold) ttl = 0; // 高负载:立即回收 else ttl = maxttl - (maxttl - minttl) * (当前负载比例); -
回收逻辑:
-
检查节点存活时间:
delta = jiffies - p->dtime。 -
若
delta > ttl且refcnt == 1(无外部引用):-
从红黑树中移除节点。
-
通过 RCU 回调释放内存。
-
-
4. 速率限制 (inet_peer_xrlim_allow)
-
令牌桶算法:
-
令牌累积:
token += (now - rate_last)。 -
令牌上限:
token ≤ 6 * timeout(突发因子)。 -
检查逻辑:若
token ≥ timeout,允许发送并扣除timeout令牌。
-
-
示例:限制 ICMP 错误消息发送速率,避免泛洪。
5. 销毁与清理
-
inet_putpeer():
减少引用计数,若归零则安排 RCU 释放。 -
inetpeer_invalidate_tree():
遍历红黑树强制移除所有节点(用于模块卸载等场景)。
并发与同步
-
红黑树操作:通过序列锁(
base->lock)保护。 -
引用计数:
refcnt使用原子操作(refcount_t)。 -
内存释放:RCU 回调(
call_rcu())确保无锁安全。
关键设计亮点
-
抗 DoS 的红黑树
避免哈希碰撞攻击导致的链表退化。 -
两级 GC 策略
动态 TTL 机制平衡内存与节点复用效率。 -
无锁读路径
结合序列号检查和 RCU 实现高效读取。 -
令牌桶速率限制
为 ICMP 等协议提供公平的消息发送限制。
典型使用场景
-
ICMP 错误消息速率限制
通过inet_peer_xrlim_allow()控制发送频率。 -
TCP 协议
存储对端路径 MTU、窗口缩放因子等长期参数。 -
IP 分片重组
关联同一对端的分片包。
总结
inetpeer.c 实现了一个高效、抗攻击的对端信息存储系统,其核心是通过红黑树管理节点生命周期,结合动态垃圾回收和 RCU 同步机制,为网络协议栈提供可靠的长时状态存储支持。


1596

被折叠的 条评论
为什么被折叠?



