內核裡有兩套東西:路由表 fib_table_hash 與路由緩存表 rt_hash_table。每次查詢都是先緩存後路由表,道理和 CPU cache 一樣——緩存存最近用過的表項,容量小、查得快;路由表存全部表項,容量大、查得慢。
先回到 route 指令的輸出,理解一條路由到底在說什麼:
![Linux 內核剖析—網路[四]:路由表的多級索引結構](https://www.unixlinux.online/unixlinux/UploadFiles_9426/201703/2017030316382223.jpg)
一條路由做的事就是告訴主機:要到某個目的網段,下一跳該往哪走。例如發往 192.168.22.3 的報文查表後得知下一跳是 192.168.123.254,然後照此送出。表項裡還有一個重要屬性 scope,代表到目的網路的「距離」。
scope 可取 RT_SCOPE_UNIVERSE、RT_SCOPE_LINK、RT_SCOPE_HOST。轉發過程中,每轉一次到目的網路的距離必須不變或更小,否則永遠到不了;查找時表項的 scope 一定小於或等於報文的 scope(例如報文是 RT_SCOPE_LINK,表項只能是 LINK 或 HOST),這就自然保證了距離單調收斂。
緩存在內核中是一個雜湊表:
static struct rt_hash_bucket *rt_hash_table __read_mostly; [net/ipv4/route.c]
由 ip_route_input() 進入,先用 [src_ip, dst_ip, iif, rt_genid] 算雜湊:
hash = rt_hash (daddr, saddr, iif, rt_genid(net));
於是 rt_hash_table[hash].chain 就是要操作的鏈表,例如遍歷:
for (rth = rt_hash_table[hash].chain; rth; rth = rth->u.dst.rt_next)
也就是先算雜湊取出這組表項,再逐一遍歷找出完全匹配 [src_ip, dst_ip, iif, tos, mark, net] 的那一筆。struct rtable 裡有專門的鍵值欄位 struct flowi 供查找使用:
/* Cache lookup keys */ struct flowi fl;
找到後更新最後訪問時間並取出 dst:
dst_use (&rth->u.dst, jiffies); skb_dst_set(skb, &rth->u.dst);
緩存的建立路徑是 inet_init () -> ip_init() -> ip_rt_init():
rt_hash_table = (struct rt_hash_bucket *)
alloc_large_system_hash("IP route cache",
sizeof(struct rt_hash_bucket),
rhash_entries,
(totalram_pages >= 128 * 1024) ?
15 : 17,
0,
&rt_hash_log,
&rt_hash_mask,
rhash_entries ? 0 : 512 * 1024);
rt_hash_mask 是表大小,rt_hash_log = log(rt_hash_mask),建立後的樣子如下圖:
![Linux 內核剖析—網路[四]:路由表的多級索引結構](https://www.unixlinux.online/unixlinux/UploadFiles_9426/201703/2017030316382262.gif)
插入由 rt_intern_hash() 負責,要插的是 rt、雜湊是 hash,先定位 bucket:
rthp = &rt_hash_table[hash].chain;
然後掃一遍,目的有兩個:過期的直接刪;鍵值相同的先摘掉,再把 rt 插到鏈頭返回。
while ((rth = *rthp) != NULL) {
if (rt_is_expired(rth)) { // 超時的條目
*rthp = rth->u.dst.rt_next;
rt_free (rth);
continue;
}
if (compare_keys(&rth->fl, &rt->fl) && compare_netns (rth, rt)) { //重複的條目
*rthp = rth->u.dst.rt_next;
rcu_assign_pointer(rth->u.dst.rt_next, rt_hash_table[hash].chain);
rcu_assign_pointer(rt_hash_table[hash].chain, rth);
……
}
……
rthp = &rth->u.dst.rt_next;
}
掃完若 rt 還不存在,就插到鏈頭:
rt ->u.dst.rt_next = rt_hash_table[hash].chain;
rcu_assign_pointer(rt_hash_table[hash].chain, rt);
新插入的 rt 若滿足條件,還會與 ARP 鄰居表綁定。
Hint:每個 bucket 沒有頭結點,是純單向鏈表,它的插入與刪除寫法簡單實用,值得學。
刪除由 rt_del() 負責,同樣先定位 bucket,再遍歷,遇到過期或目標就摘掉:
rthp = &rt_hash_table[hash].chain;
spin_lock_bh(rt_hash_lock_addr(hash));
ip_rt_put(rt);
while ((aux = *rthp) != NULL) {
if (aux == rt || rt_is_expired(aux)) {
*rthp = aux->u.dst.rt_next;
rt_free(aux);
continue;
}
rthp = &aux->u.dst.rt_next;
}
spin_unlock_bh(rt_hash_lock_addr(hash));
路徑:inet_init() -> ip_init() -> ip_fib_init() -> fib_net_init() -> ip_fib_net_init() [net/ipv4/fib_frontend.c]
先配置表頭陣列,每個 hlist_head 之後都會各自串一張路由表,FIB_TABLE_HASHSZ 決定配置幾張,通常至少兩張——LOCAL 與 MAIN。注意此時只分配了表頭空間:
net->ipv4.fib_table_hash = kzalloc( sizeof(struct hlist_head)*FIB_TABLE_HASHSZ, GFP_KERNEL);
接著 ip_fib_net_init() -> fib4_rules_init() 才真正配置路由表本體:
local_table = fib_hash_table(RT_TABLE_LOCAL); main_table = fib_hash_table(RT_TABLE_MAIN);
然後把兩張表掛進 fib_table_hash:
hlist_add_head_rcu (&local_table->tb_hlist, &net->ipv4.fib_table_hash [TABLE_LOCAL_INDEX]); hlist_add_head_rcu(&main_table->tb_hlist, &net->ipv4.fib_table_hash[TABLE_MAIN_INDEX]);
最終 LOCAL 位於 fib_table_hash[0]、MAIN 位於 fib_table_hash[1],兩者靠 tb_hlist 串成鏈表,tb_id 標示功能(255 是 LOCAL,254 是 MAIN)。
這裡的 struct fn_hash 表示按子網掩碼長度切分的 33 個雜湊表(fn_zone,0~32),而 fn_hash 的實作就是 fib_table 的最後一個參數 unsigned char tb_data[0]。
![Linux 內核剖析—網路[四]:路由表的多級索引結構](https://www.unixlinux.online/unixlinux/UploadFiles_9426/201703/2017030316382229.gif)
此時 fn_zone 還是空指標,初始化只完成一半。開機階段還會走 inet_rtm_newroute() -> fib_table_insert() -> fn_new_zone() [fib_hash.c] 把 fn_zone 建出來。掩碼長度 0(/0)是預設路由,一般只有一條,所以 fz_centerisor 設為 1,其餘設為 16;fz_centerisor 就是 fz->fz_hash 這張雜湊表的大小:
struct fn_zone *fz = kzalloc (sizeof(struct fn_zone), GFP_KERNEL);
if (z) {
fz->fz_centerisor = 16;
} else {
fz->fz_centerisor = 1;
}
其他欄位各有分工:fz_hashmask 供取餘數(hash & fz_hashmask 得到桶位置)、fz_hash 是下一層雜湊表、fz_order 是掩碼長度、fz_mask 是掩碼本身:
fz->fz_hashmask = (fz->fz_centerisor - 1); fz->fz_hash = fz_hash_alloc(fz->fz_centerisor); fz->fz_order = z; fz->fz_mask = inet_make_mask(z);
接著從掩碼更長且非空的 fn_zones[i] 中挑一個,把新 fz 接到它後面,再按掩碼長度歸位;fn_zone_list 永遠指向掩碼最長的那個:
for (i=z+1; i<=32; i++)
if (table->fn_zones[i])
break;
if (i>32) {
fz->fz_next = table->fn_zone_list;
table->fn_zone_list = fz;
} else {
fz->fz_next = table->fn_zones[i]->fz_next;
table->fn_zones[i]->fz_next = fz;
}
table->fn_zones[z] = fz;
fn_hash 是陣列與鏈表的混合體:
struct fn_hash {
struct fn_zone *fn_zones [33];
struct fn_zone *fn_zone_list;
};
33 個元素各存一個掩碼長度的 fn_zone(fn_zone[i] 存掩碼 i),彼此再用 fz_next 串成單向鏈,fn_zone_list 是鏈頭,且鏈的順序是「掩碼由長到短」的倒序:
![Linux 內核剖析—網路[四]:路由表的多級索引結構](https://www.unixlinux.online/unixlinux/UploadFiles_9426/201703/2017030316382217.gif)
fz_hash 此時還是空的,填內容的是 fib_insert_node()。
inet_rtm_newroute() -> fib_table_insert() -> fib_insert_node() [net/ipv4/fib_hash.c]
f 是 fib_node,可理解為「同一網路位址的表項集合」。依 fn_key(網路位址)與 fz(掩碼長度)算雜湊,決定掛到 fz_hash 的哪個桶:
struct hlist_head *head = &fz->fz_hash[fn_hash(f->fn_key, fz)]; hlist_add_head(&f->fn_hash, head);
若 fib_node 不存在就配置一個(kmem_cache_zalloc 本質上就是記憶體配置):
new_f = kmem_cache_zalloc (fn_hash_kmem, GFP_KERNEL); if (new_f == NULL) goto out; INIT_HLIST_NODE(&new_f->fn_hash); INIT_LIST_HEAD(&new_f->fn_alias); new_f->fn_key = key; f = new_f;
路由表最底層是 fib_info,真正的路由資訊都存在這裡,由 fib_create_info() 建立。配置大小為 fib_info + nhs * fib_nh,其中 fib_nh 是下一跳資訊、nhs 是下一跳數量(一般為 1,除非設了多路徑):
fi = kzalloc(sizeof(*fi)+nhs*sizeof(struct fib_nh), GFP_KERNEL);
填寫基本欄位:
fi->fib_net = hold_net(net); fi->fib_protocol = cfg->fc_protocol; fi->fib_flags = cfg->fc_flags; fi->fib_priority = cfg->fc_priority; fi->fib_prefsrc = cfg->fc_prefsrc; fi->fib_nhs = nhs;
再讓每個 nh->nh_parent 回指 fi:
change_nexthops(fi) {
nexthop_nh->nh_parent = fi;
} endfor_nexthops(fi)
![Linux 內核剖析—網路[四]:路由表的多級索引結構](https://www.unixlinux.online/unixlinux/UploadFiles_9426/201703/2017030316382394.gif)
設定 fib_nh 屬性(以單一路徑為例):
struct fib_nh *nh = fi->fib_nh; nh->nh_oif = cfg->fc_oif; nh->nh_gw = cfg->fc_gw; nh->nh_flags = cfg->fc_flags;
然後依 cfg->fc_scope 分兩路。scope 為 RT_SCOPE_HOST 時,下一跳 scope 設為 RT_SCOPE_NOWHERE:
if (cfg->fc_scope == RT_SCOPE_HOST) {
struct fib_nh *nh = fi->fib_nh;
nh->nh_scope = RT_SCOPE_NOWHERE;
nh->nh_dev = dev_get_by_index(net, fi->fib_nh->nh_oif);
}
scope 為 RT_SCOPE_LINK 或 RT_SCOPE_UNIVERSE 時,走 fib_check_nh 檢查:
change_nexthops(fi) {
if ((err = fib_check_nh(cfg, fi, nexthop_nh)) != 0)
goto failure;
} endfor_nexthops(fi)
最後把 fi 掛進雜湊表。注意所有已建立的 fib_info 都會進 fib_info_hash,若用了優先位址屬性,還會多進 fib_info_laddrhash:
hlist_add_head(&fi->fib_hash,
&fib_info_hash[fib_info_hashfn(fi)]);
if (fi->fib_prefsrc) {
struct hlist_head *head;
head = &fib_info_laddrhash[fib_laddr_hashfn(fi->fib_prefsrc)];
hlist_add_head(&fi->fib_lhash, head);
}
不論 fib_info 掛在哪個掩碼、哪個網段之下,都與這兩張雜湊表無關——它們獨立存在,專門用來加速 fib_info 的查找。表大小為 fib_hash_size,超標時擴為兩倍(雜湊函數夠好的話,每個桶剛好一筆):
![Linux 內核剖析—網路[四]:路由表的多級索引結構](https://www.unixlinux.online/unixlinux/UploadFiles_9426/201703/2017030316382338.gif)
另外,路由資訊也可能以設備 dev 為鍵被搜到,因此還有 fib_info_devhash,存的是 nh 的 dev->ifindex:
change_nexthops(fi) {
hash = fib_devindex_hashfn(nexthop_nh->nh_dev->ifindex);
head = &fib_info_devhash[hash];
hlist_add_head(&nexthop_nh->nh_hash, head);
} endfor_nexthops (fi)
先取出掩碼長度為 fc_dst_len 的 fn_zone,沒有就建一個:
fz = table->fn_zones[cfg->fc_dst_len]; if (!fz && !(fz = fn_new_zone(table, cfg->fc_dst_len))) return - ENOBUFS;
建立 fib_info:
fi = fib_create_info(cfg);
在該掩碼的桶中查找指定網路位址 key(例如 145.222.33.0/24):
f = fib_find_node(fz, key);
![Linux 內核剖析—網路[四]:路由表的多級索引結構](https://www.unixlinux.online/unixlinux/UploadFiles_9426/201703/2017030316382308.gif)
查不到就配置 fib_node 並插入 fz_hash:
if (!f) {
new_f = kmem_cache_zalloc(fn_hash_kmem, GFP_KERNEL);
if (new_f == NULL)
goto out;
INIT_HLIST_NODE(&new_f->fn_hash);
INIT_LIST_HEAD(&new_f->fn_alias);
new_f->fn_key = key;
f = new_f;
}
……
fib_insert_node(fz, new_f);
若已存在,就在 fn_alias 中以 tos 與 fi->fib_priority 為鍵查找。一個 fib_node 可以掛多個 fib_alias,以鏈表串起並按 tos 由大到小排列,因此 fib_find_alias 找到的是「第一個 tos 不大於目標 tos」的那筆:
fa = fib_find_alias(&f->fn_alias, tos, fi->fib_priority);
若找到的 fa 與要插入的完全相同,就依標記位處理:NLM_F_REPLACE 取代舊的,NLM_F_APPEND 接在後面。
設定新 fib_alias 的欄位,其中最重要的是 fa_info 指向 fi:
new_fa->fa_info = fi; new_fa->fa_tos = tos; new_fa->fa_type = cfg->fc_type; new_fa->fa_scope = cfg->fc_scope; new_fa->fa_state = 0;
若原本沒有對應的 fib_node(前面已新建),現在把它插入路由表,再把 new_fa 掛進 fn_alias:
if (new_f) fib_insert_node(fz, new_f); list_add_tail(&new_fa->fa_list, (fa ? &fa->fa_list : &f->fn_alias));
最後因為新增了表項,會向所有加入 RTNLGRP_IPV4_ROUTE 的成員發通告,用 ip route monitor 就能看到。最終樣子如下圖:
rtmsg_fib(RTM_NEWROUTE, key, new_fa, cfg->fc_dst_len, tb->tb_id, &cfg->fc_nlinfo, 0);
![Linux 內核剖析—網路[四]:路由表的多級索引結構](https://www.unixlinux.online/unixlinux/UploadFiles_9426/201703/2017030316382312.gif)
小結一下:查找效率擺第一,所以內核用多級索引加速——
第一級:fn_zone 按掩碼長度分類(如 /5 與 /24);
第二級:fib_node 按網路位址分類(如 124.44.33.0/24);
第三級:fib_info 存放下一跳資訊。