路由查找完成之後,緊接著的動作是替這條路由綁定一個鄰居項。本文從 arp_bind_neighbour() 出發,追進 neigh_create() 與 arp_constructor()。
int arp_bind_neighbour(struct dst_entry *dst)
{
struct net_device *dev = dst->dev;
struct neighbour *n = dst->neighbour;
if (dev == NULL)
return -EINVAL;
if (n == NULL) {
u32 nexthop = ((struct rtable *)dst)->rt_gateway;
if (dev->flags & (IFF_LOOPBACK | IFF_POINTOPOINT))
nexthop = 0;
n = __neigh_lookup_errno(
#if defined(CONFIG_ATM_CLIP) || defined(CONFIG_ATM_CLIP_MODULE)
dev->type == ARPHRD_ATM ? clip_tbl_hook :
#endif
&arp_tbl, &nexthop, dev);
if (IS_ERR(n))
return PTR_ERR(n);
dst->neighbour = n;
}
return 0;
}
注意下一跳的算法:回環與點對點介面沒有「下一跳」的概念,因此直接把 nexthop 歸零;ATM CLIP 則改用專屬的 clip_tbl_hook 表。
__neigh_lookup_errno(struct neigh_table *tbl, const void *pkey,
struct net_device *dev)
{
struct neighbour *n = neigh_lookup(tbl, pkey, dev);
if (n)
return n;
return neigh_create(tbl, pkey, dev);
}
先查表,查不到才新建。而在 neigh_create() 中,雜湊鍵值就是目的 IP:
memcpy(n->primary_key, pkey, key_len);
n->dev = dev;
dev_hold(dev);
if (tbl->constructor && (error = tbl->constructor(n)) < 0) { ... }
if (n->parms->neigh_setup &&
(error = n->parms->neigh_setup(n)) < 0) { ... }
n->confirmed = jiffies - (n->parms->base_reachable_time << 1);
然後在寫鎖保護下做三件事:容量檢查、雜湊定位、去重插入。
write_lock_bh(&tbl->lock);
/* 超過當前容量就擴表 */
if (tbl->entries > (tbl->hash_mask + 1))
neigh_hash_grow(tbl, (tbl->hash_mask + 1) << 1);
hash_val = tbl->hash(pkey, dev) & tbl->hash_mask;
if (n->parms->dead) { rc = ERR_PTR(-EINVAL); goto out_tbl_unlock; }
/* 桶內若已有同鍵同裝置的項,改為共用並加參照 */
for (n1 = tbl->hash_buckets[hash_val]; n1; n1 = n1->next) {
if (dev == n1->dev && !memcmp(n1->primary_key, pkey, key_len)) {
neigh_hold(n1);
rc = n1;
goto out_tbl_unlock;
}
}
/* 否則插入桶頭 */
n->next = tbl->hash_buckets[hash_val];
tbl->hash_buckets[hash_val] = n;
n->dead = 0;
neigh_hold(n);
write_unlock_bh(&tbl->lock);
去重那一段是併發環境下的必要防禦:即使在鎖外配置了新結構,進鎖後仍可能發現別人已經建好,這時就丟掉自己這份、改用既有項。
arp_tbl 的 constructor 指向 arp_constructor():
static int arp_constructor(struct neighbour *neigh)
{
u32 addr = *(u32 *)neigh->primary_key;
struct net_device *dev = neigh->dev;
struct in_device *in_dev;
struct neigh_parms *parms;
neigh->type = inet_addr_type(addr);
rcu_read_lock();
in_dev = rcu_dereference(__in_dev_get(dev));
if (in_dev == NULL) {
rcu_read_unlock();
return -EINVAL;
}
parms = in_dev->arp_parms;
__neigh_parms_put(neigh->parms);
它依目的 IP 判定位址型別(單播、廣播、多重播),再從介面的 in_device 取得 ARP 參數集。這個 constructor 就是「協議相關」與「協議無關」兩層的接縫:鄰居子系統負責表、雜湊、狀態機與回收,具體的位址語意則交由各協議自行填寫。