2 * This program is free software; you can redistribute it and/or
3 * modify it under the terms of the GNU General Public License
4 * as published by the Free Software Foundation; either version
5 * 2 of the License, or (at your option) any later version.
7 * Robert Olsson <robert.olsson@its.uu.se> Uppsala Universitet
8 * & Swedish University of Agricultural Sciences.
10 * Jens Laas <jens.laas@data.slu.se> Swedish University of
11 * Agricultural Sciences.
13 * Hans Liss <hans.liss@its.uu.se> Uppsala Universitet
15 * This work is based on the LPC-trie which is originally described in:
17 * An experimental study of compression methods for dynamic tries
18 * Stefan Nilsson and Matti Tikkanen. Algorithmica, 33(1):19-33, 2002.
19 * http://www.csc.kth.se/~snilsson/software/dyntrie2/
22 * IP-address lookup using LC-tries. Stefan Nilsson and Gunnar Karlsson
23 * IEEE Journal on Selected Areas in Communications, 17(6):1083-1092, June 1999
26 * Code from fib_hash has been reused which includes the following header:
29 * INET An implementation of the TCP/IP protocol suite for the LINUX
30 * operating system. INET is implemented using the BSD Socket
31 * interface as the means of communication with the user level.
33 * IPv4 FIB: lookup engine and maintenance routines.
36 * Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
38 * This program is free software; you can redistribute it and/or
39 * modify it under the terms of the GNU General Public License
40 * as published by the Free Software Foundation; either version
41 * 2 of the License, or (at your option) any later version.
43 * Substantial contributions to this work comes from:
45 * David S. Miller, <davem@davemloft.net>
46 * Stephen Hemminger <shemminger@osdl.org>
47 * Paul E. McKenney <paulmck@us.ibm.com>
48 * Patrick McHardy <kaber@trash.net>
51 #define VERSION "0.409"
53 #include <asm/uaccess.h>
54 #include <linux/bitops.h>
55 #include <linux/types.h>
56 #include <linux/kernel.h>
58 #include <linux/string.h>
59 #include <linux/socket.h>
60 #include <linux/sockios.h>
61 #include <linux/errno.h>
63 #include <linux/inet.h>
64 #include <linux/inetdevice.h>
65 #include <linux/netdevice.h>
66 #include <linux/if_arp.h>
67 #include <linux/proc_fs.h>
68 #include <linux/rcupdate.h>
69 #include <linux/skbuff.h>
70 #include <linux/netlink.h>
71 #include <linux/init.h>
72 #include <linux/list.h>
73 #include <linux/slab.h>
74 #include <linux/export.h>
75 #include <net/net_namespace.h>
77 #include <net/protocol.h>
78 #include <net/route.h>
81 #include <net/ip_fib.h>
82 #include "fib_lookup.h"
84 #define MAX_STAT_DEPTH 32
86 #define KEYLENGTH (8*sizeof(t_key))
88 typedef unsigned int t_key;
90 #define IS_TNODE(n) ((n)->bits)
91 #define IS_LEAF(n) (!(n)->bits)
93 #define get_index(_key, _kv) (((_key) ^ (_kv)->key) >> (_kv)->pos)
97 unsigned char bits; /* 2log(KEYLENGTH) bits needed */
98 unsigned char pos; /* 2log(KEYLENGTH) bits needed */
99 struct tnode __rcu *parent;
102 /* The fields in this struct are valid if bits > 0 (TNODE) */
104 unsigned int full_children; /* KEYLENGTH bits needed */
105 unsigned int empty_children; /* KEYLENGTH bits needed */
106 struct tnode __rcu *child[0];
108 /* This list pointer if valid if bits == 0 (LEAF) */
109 struct hlist_head list;
114 struct hlist_node hlist;
116 u32 mask_plen; /* ntohl(inet_make_mask(plen)) */
117 struct list_head falh;
121 #ifdef CONFIG_IP_FIB_TRIE_STATS
122 struct trie_use_stats {
124 unsigned int backtrack;
125 unsigned int semantic_match_passed;
126 unsigned int semantic_match_miss;
127 unsigned int null_node_hit;
128 unsigned int resize_node_skipped;
133 unsigned int totdepth;
134 unsigned int maxdepth;
137 unsigned int nullpointers;
138 unsigned int prefixes;
139 unsigned int nodesizes[MAX_STAT_DEPTH];
143 struct tnode __rcu *trie;
144 #ifdef CONFIG_IP_FIB_TRIE_STATS
145 struct trie_use_stats __percpu *stats;
149 static void resize(struct trie *t, struct tnode *tn);
150 static size_t tnode_free_size;
153 * synchronize_rcu after call_rcu for that many pages; it should be especially
154 * useful before resizing the root node with PREEMPT_NONE configs; the value was
155 * obtained experimentally, aiming to avoid visible slowdown.
157 static const int sync_pages = 128;
159 static struct kmem_cache *fn_alias_kmem __read_mostly;
160 static struct kmem_cache *trie_leaf_kmem __read_mostly;
162 /* caller must hold RTNL */
163 #define node_parent(n) rtnl_dereference((n)->parent)
165 /* caller must hold RCU read lock or RTNL */
166 #define node_parent_rcu(n) rcu_dereference_rtnl((n)->parent)
168 /* wrapper for rcu_assign_pointer */
169 static inline void node_set_parent(struct tnode *n, struct tnode *tp)
172 rcu_assign_pointer(n->parent, tp);
175 #define NODE_INIT_PARENT(n, p) RCU_INIT_POINTER((n)->parent, p)
177 /* This provides us with the number of children in this node, in the case of a
178 * leaf this will return 0 meaning none of the children are accessible.
180 static inline unsigned long tnode_child_length(const struct tnode *tn)
182 return (1ul << tn->bits) & ~(1ul);
185 /* caller must hold RTNL */
186 static inline struct tnode *tnode_get_child(const struct tnode *tn,
189 BUG_ON(i >= tnode_child_length(tn));
191 return rtnl_dereference(tn->child[i]);
194 /* caller must hold RCU read lock or RTNL */
195 static inline struct tnode *tnode_get_child_rcu(const struct tnode *tn,
198 BUG_ON(i >= tnode_child_length(tn));
200 return rcu_dereference_rtnl(tn->child[i]);
203 /* To understand this stuff, an understanding of keys and all their bits is
204 * necessary. Every node in the trie has a key associated with it, but not
205 * all of the bits in that key are significant.
207 * Consider a node 'n' and its parent 'tp'.
209 * If n is a leaf, every bit in its key is significant. Its presence is
210 * necessitated by path compression, since during a tree traversal (when
211 * searching for a leaf - unless we are doing an insertion) we will completely
212 * ignore all skipped bits we encounter. Thus we need to verify, at the end of
213 * a potentially successful search, that we have indeed been walking the
216 * Note that we can never "miss" the correct key in the tree if present by
217 * following the wrong path. Path compression ensures that segments of the key
218 * that are the same for all keys with a given prefix are skipped, but the
219 * skipped part *is* identical for each node in the subtrie below the skipped
220 * bit! trie_insert() in this implementation takes care of that.
222 * if n is an internal node - a 'tnode' here, the various parts of its key
223 * have many different meanings.
226 * _________________________________________________________________
227 * | i | i | i | i | i | i | i | N | N | N | S | S | S | S | S | C |
228 * -----------------------------------------------------------------
229 * 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16
231 * _________________________________________________________________
232 * | C | C | C | u | u | u | u | u | u | u | u | u | u | u | u | u |
233 * -----------------------------------------------------------------
234 * 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
241 * First, let's just ignore the bits that come before the parent tp, that is
242 * the bits from (tp->pos + tp->bits) to 31. They are *known* but at this
243 * point we do not use them for anything.
245 * The bits from (tp->pos) to (tp->pos + tp->bits - 1) - "N", above - are the
246 * index into the parent's child array. That is, they will be used to find
247 * 'n' among tp's children.
249 * The bits from (n->pos + n->bits) to (tn->pos - 1) - "S" - are skipped bits
252 * All the bits we have seen so far are significant to the node n. The rest
253 * of the bits are really not needed or indeed known in n->key.
255 * The bits from (n->pos) to (n->pos + n->bits - 1) - "C" - are the index into
256 * n's child array, and will of course be different for each child.
258 * The rest of the bits, from 0 to (n->pos + n->bits), are completely unknown
262 static const int halve_threshold = 25;
263 static const int inflate_threshold = 50;
264 static const int halve_threshold_root = 15;
265 static const int inflate_threshold_root = 30;
267 static void __alias_free_mem(struct rcu_head *head)
269 struct fib_alias *fa = container_of(head, struct fib_alias, rcu);
270 kmem_cache_free(fn_alias_kmem, fa);
273 static inline void alias_free_mem_rcu(struct fib_alias *fa)
275 call_rcu(&fa->rcu, __alias_free_mem);
278 #define TNODE_KMALLOC_MAX \
279 ilog2((PAGE_SIZE - sizeof(struct tnode)) / sizeof(struct tnode *))
281 static void __node_free_rcu(struct rcu_head *head)
283 struct tnode *n = container_of(head, struct tnode, rcu);
286 kmem_cache_free(trie_leaf_kmem, n);
287 else if (n->bits <= TNODE_KMALLOC_MAX)
293 #define node_free(n) call_rcu(&n->rcu, __node_free_rcu)
295 static inline void free_leaf_info(struct leaf_info *leaf)
297 kfree_rcu(leaf, rcu);
300 static struct tnode *tnode_alloc(size_t size)
302 if (size <= PAGE_SIZE)
303 return kzalloc(size, GFP_KERNEL);
305 return vzalloc(size);
308 static struct tnode *leaf_new(t_key key)
310 struct tnode *l = kmem_cache_alloc(trie_leaf_kmem, GFP_KERNEL);
313 /* set key and pos to reflect full key value
314 * any trailing zeros in the key should be ignored
315 * as the nodes are searched
319 /* set bits to 0 indicating we are not a tnode */
322 INIT_HLIST_HEAD(&l->list);
327 static struct leaf_info *leaf_info_new(int plen)
329 struct leaf_info *li = kmalloc(sizeof(struct leaf_info), GFP_KERNEL);
332 li->mask_plen = ntohl(inet_make_mask(plen));
333 INIT_LIST_HEAD(&li->falh);
338 static struct tnode *tnode_new(t_key key, int pos, int bits)
340 size_t sz = offsetof(struct tnode, child[1 << bits]);
341 struct tnode *tn = tnode_alloc(sz);
342 unsigned int shift = pos + bits;
344 /* verify bits and pos their msb bits clear and values are valid */
345 BUG_ON(!bits || (shift > KEYLENGTH));
351 tn->key = (shift < KEYLENGTH) ? (key >> shift) << shift : 0;
352 tn->full_children = 0;
353 tn->empty_children = 1<<bits;
356 pr_debug("AT %p s=%zu %zu\n", tn, sizeof(struct tnode),
357 sizeof(struct tnode *) << bits);
361 /* Check whether a tnode 'n' is "full", i.e. it is an internal node
362 * and no bits are skipped. See discussion in dyntree paper p. 6
364 static inline int tnode_full(const struct tnode *tn, const struct tnode *n)
366 return n && ((n->pos + n->bits) == tn->pos) && IS_TNODE(n);
369 /* Add a child at position i overwriting the old value.
370 * Update the value of full_children and empty_children.
372 static void put_child(struct tnode *tn, unsigned long i, struct tnode *n)
374 struct tnode *chi = rtnl_dereference(tn->child[i]);
377 BUG_ON(i >= tnode_child_length(tn));
379 /* update emptyChildren */
380 if (n == NULL && chi != NULL)
381 tn->empty_children++;
382 else if (n != NULL && chi == NULL)
383 tn->empty_children--;
385 /* update fullChildren */
386 wasfull = tnode_full(tn, chi);
387 isfull = tnode_full(tn, n);
389 if (wasfull && !isfull)
391 else if (!wasfull && isfull)
394 rcu_assign_pointer(tn->child[i], n);
397 static void put_child_root(struct tnode *tp, struct trie *t,
398 t_key key, struct tnode *n)
401 put_child(tp, get_index(key, tp), n);
403 rcu_assign_pointer(t->trie, n);
406 static inline void tnode_free_init(struct tnode *tn)
411 static inline void tnode_free_append(struct tnode *tn, struct tnode *n)
413 n->rcu.next = tn->rcu.next;
414 tn->rcu.next = &n->rcu;
417 static void tnode_free(struct tnode *tn)
419 struct callback_head *head = &tn->rcu;
423 tnode_free_size += offsetof(struct tnode, child[1 << tn->bits]);
426 tn = container_of(head, struct tnode, rcu);
429 if (tnode_free_size >= PAGE_SIZE * sync_pages) {
435 static int inflate(struct trie *t, struct tnode *oldtnode)
437 struct tnode *inode, *node0, *node1, *tn, *tp;
438 unsigned long i, j, k;
441 pr_debug("In inflate\n");
443 tn = tnode_new(oldtnode->key, oldtnode->pos - 1, oldtnode->bits + 1);
447 /* Assemble all of the pointers in our cluster, in this case that
448 * represents all of the pointers out of our allocated nodes that
449 * point to existing tnodes and the links between our allocated
452 for (i = tnode_child_length(oldtnode), m = 1u << tn->pos; i;) {
453 inode = tnode_get_child(oldtnode, --i);
459 /* A leaf or an internal node with skipped bits */
460 if (!tnode_full(oldtnode, inode)) {
461 put_child(tn, get_index(inode->key, tn), inode);
465 /* An internal node with two children */
466 if (inode->bits == 1) {
467 put_child(tn, 2 * i + 1, tnode_get_child(inode, 1));
468 put_child(tn, 2 * i, tnode_get_child(inode, 0));
472 /* We will replace this node 'inode' with two new
473 * ones, 'node0' and 'node1', each with half of the
474 * original children. The two new nodes will have
475 * a position one bit further down the key and this
476 * means that the "significant" part of their keys
477 * (see the discussion near the top of this file)
478 * will differ by one bit, which will be "0" in
479 * node0's key and "1" in node1's key. Since we are
480 * moving the key position by one step, the bit that
481 * we are moving away from - the bit at position
482 * (tn->pos) - is the one that will differ between
483 * node0 and node1. So... we synthesize that bit in the
486 node1 = tnode_new(inode->key | m, inode->pos, inode->bits - 1);
489 tnode_free_append(tn, node1);
491 node0 = tnode_new(inode->key & ~m, inode->pos, inode->bits - 1);
494 tnode_free_append(tn, node0);
496 /* populate child pointers in new nodes */
497 for (k = tnode_child_length(inode), j = k / 2; j;) {
498 put_child(node1, --j, tnode_get_child(inode, --k));
499 put_child(node0, j, tnode_get_child(inode, j));
500 put_child(node1, --j, tnode_get_child(inode, --k));
501 put_child(node0, j, tnode_get_child(inode, j));
504 /* link new nodes to parent */
505 NODE_INIT_PARENT(node1, tn);
506 NODE_INIT_PARENT(node0, tn);
508 /* link parent to nodes */
509 put_child(tn, 2 * i + 1, node1);
510 put_child(tn, 2 * i, node0);
513 /* setup the parent pointer into and out of this node */
514 tp = node_parent(oldtnode);
515 NODE_INIT_PARENT(tn, tp);
516 put_child_root(tp, t, tn->key, tn);
518 /* prepare oldtnode to be freed */
519 tnode_free_init(oldtnode);
521 /* update all child nodes parent pointers to route to us */
522 for (i = tnode_child_length(oldtnode); i;) {
523 inode = tnode_get_child(oldtnode, --i);
525 /* A leaf or an internal node with skipped bits */
526 if (!tnode_full(oldtnode, inode)) {
527 node_set_parent(inode, tn);
531 /* drop the node in the old tnode free list */
532 tnode_free_append(oldtnode, inode);
534 /* fetch new nodes */
535 node1 = tnode_get_child(tn, 2 * i + 1);
536 node0 = tnode_get_child(tn, 2 * i);
538 /* bits == 1 then node0 and node1 represent inode's children */
539 if (inode->bits == 1) {
540 node_set_parent(node1, tn);
541 node_set_parent(node0, tn);
545 /* update parent pointers in child node's children */
546 for (k = tnode_child_length(inode), j = k / 2; j;) {
547 node_set_parent(tnode_get_child(inode, --k), node1);
548 node_set_parent(tnode_get_child(inode, --j), node0);
549 node_set_parent(tnode_get_child(inode, --k), node1);
550 node_set_parent(tnode_get_child(inode, --j), node0);
553 /* resize child nodes */
558 /* we completed without error, prepare to free old node */
559 tnode_free(oldtnode);
562 /* all pointers should be clean so we are done */
567 static int halve(struct trie *t, struct tnode *oldtnode)
569 struct tnode *tn, *tp, *inode, *node0, *node1;
572 pr_debug("In halve\n");
574 tn = tnode_new(oldtnode->key, oldtnode->pos + 1, oldtnode->bits - 1);
578 /* Assemble all of the pointers in our cluster, in this case that
579 * represents all of the pointers out of our allocated nodes that
580 * point to existing tnodes and the links between our allocated
583 for (i = tnode_child_length(oldtnode); i;) {
584 node1 = tnode_get_child(oldtnode, --i);
585 node0 = tnode_get_child(oldtnode, --i);
587 /* At least one of the children is empty */
588 if (!node1 || !node0) {
589 put_child(tn, i / 2, node1 ? : node0);
593 /* Two nonempty children */
594 inode = tnode_new(node0->key, oldtnode->pos, 1);
599 tnode_free_append(tn, inode);
601 /* initialize pointers out of node */
602 put_child(inode, 1, node1);
603 put_child(inode, 0, node0);
604 NODE_INIT_PARENT(inode, tn);
606 /* link parent to node */
607 put_child(tn, i / 2, inode);
610 /* setup the parent pointer out of and back into this node */
611 tp = node_parent(oldtnode);
612 NODE_INIT_PARENT(tn, tp);
613 put_child_root(tp, t, tn->key, tn);
615 /* prepare oldtnode to be freed */
616 tnode_free_init(oldtnode);
618 /* update all of the child parent pointers */
619 for (i = tnode_child_length(tn); i;) {
620 inode = tnode_get_child(tn, --i);
622 /* only new tnodes will be considered "full" nodes */
623 if (!tnode_full(tn, inode)) {
624 node_set_parent(inode, tn);
628 /* Two nonempty children */
629 node_set_parent(tnode_get_child(inode, 1), inode);
630 node_set_parent(tnode_get_child(inode, 0), inode);
632 /* resize child node */
636 /* all pointers should be clean so we are done */
637 tnode_free(oldtnode);
642 /* From "Implementing a dynamic compressed trie" by Stefan Nilsson of
643 * the Helsinki University of Technology and Matti Tikkanen of Nokia
644 * Telecommunications, page 6:
645 * "A node is doubled if the ratio of non-empty children to all
646 * children in the *doubled* node is at least 'high'."
648 * 'high' in this instance is the variable 'inflate_threshold'. It
649 * is expressed as a percentage, so we multiply it with
650 * tnode_child_length() and instead of multiplying by 2 (since the
651 * child array will be doubled by inflate()) and multiplying
652 * the left-hand side by 100 (to handle the percentage thing) we
653 * multiply the left-hand side by 50.
655 * The left-hand side may look a bit weird: tnode_child_length(tn)
656 * - tn->empty_children is of course the number of non-null children
657 * in the current node. tn->full_children is the number of "full"
658 * children, that is non-null tnodes with a skip value of 0.
659 * All of those will be doubled in the resulting inflated tnode, so
660 * we just count them one extra time here.
662 * A clearer way to write this would be:
664 * to_be_doubled = tn->full_children;
665 * not_to_be_doubled = tnode_child_length(tn) - tn->empty_children -
668 * new_child_length = tnode_child_length(tn) * 2;
670 * new_fill_factor = 100 * (not_to_be_doubled + 2*to_be_doubled) /
672 * if (new_fill_factor >= inflate_threshold)
674 * ...and so on, tho it would mess up the while () loop.
677 * 100 * (not_to_be_doubled + 2*to_be_doubled) / new_child_length >=
681 * 100 * (not_to_be_doubled + 2*to_be_doubled) >=
682 * inflate_threshold * new_child_length
684 * expand not_to_be_doubled and to_be_doubled, and shorten:
685 * 100 * (tnode_child_length(tn) - tn->empty_children +
686 * tn->full_children) >= inflate_threshold * new_child_length
688 * expand new_child_length:
689 * 100 * (tnode_child_length(tn) - tn->empty_children +
690 * tn->full_children) >=
691 * inflate_threshold * tnode_child_length(tn) * 2
694 * 50 * (tn->full_children + tnode_child_length(tn) -
695 * tn->empty_children) >= inflate_threshold *
696 * tnode_child_length(tn)
699 static bool should_inflate(const struct tnode *tp, const struct tnode *tn)
701 unsigned long used = tnode_child_length(tn);
702 unsigned long threshold = used;
704 /* Keep root node larger */
705 threshold *= tp ? inflate_threshold : inflate_threshold_root;
706 used += tn->full_children;
707 used -= tn->empty_children;
709 return tn->pos && ((50 * used) >= threshold);
712 static bool should_halve(const struct tnode *tp, const struct tnode *tn)
714 unsigned long used = tnode_child_length(tn);
715 unsigned long threshold = used;
717 /* Keep root node larger */
718 threshold *= tp ? halve_threshold : halve_threshold_root;
719 used -= tn->empty_children;
721 return (tn->bits > 1) && ((100 * used) < threshold);
725 static void resize(struct trie *t, struct tnode *tn)
727 struct tnode *tp = node_parent(tn), *n = NULL;
728 struct tnode __rcu **cptr;
731 pr_debug("In tnode_resize %p inflate_threshold=%d threshold=%d\n",
732 tn, inflate_threshold, halve_threshold);
734 /* track the tnode via the pointer from the parent instead of
735 * doing it ourselves. This way we can let RCU fully do its
736 * thing without us interfering
738 cptr = tp ? &tp->child[get_index(tn->key, tp)] : &t->trie;
739 BUG_ON(tn != rtnl_dereference(*cptr));
742 if (tn->empty_children > (tnode_child_length(tn) - 1))
746 if (tn->empty_children == (tnode_child_length(tn) - 1))
749 /* Double as long as the resulting node has a number of
750 * nonempty nodes that are above the threshold.
753 while (should_inflate(tp, tn) && max_work--) {
754 if (inflate(t, tn)) {
755 #ifdef CONFIG_IP_FIB_TRIE_STATS
756 this_cpu_inc(t->stats->resize_node_skipped);
761 tn = rtnl_dereference(*cptr);
764 /* Return if at least one inflate is run */
765 if (max_work != MAX_WORK)
768 /* Halve as long as the number of empty children in this
769 * node is above threshold.
772 while (should_halve(tp, tn) && max_work--) {
774 #ifdef CONFIG_IP_FIB_TRIE_STATS
775 this_cpu_inc(t->stats->resize_node_skipped);
780 tn = rtnl_dereference(*cptr);
783 /* Only one child remains */
784 if (tn->empty_children == (tnode_child_length(tn) - 1)) {
787 for (i = tnode_child_length(tn); !n && i;)
788 n = tnode_get_child(tn, --i);
790 /* compress one level */
791 put_child_root(tp, t, tn->key, n);
792 node_set_parent(n, tp);
800 /* readside must use rcu_read_lock currently dump routines
801 via get_fa_head and dump */
803 static struct leaf_info *find_leaf_info(struct tnode *l, int plen)
805 struct hlist_head *head = &l->list;
806 struct leaf_info *li;
808 hlist_for_each_entry_rcu(li, head, hlist)
809 if (li->plen == plen)
815 static inline struct list_head *get_fa_head(struct tnode *l, int plen)
817 struct leaf_info *li = find_leaf_info(l, plen);
825 static void insert_leaf_info(struct hlist_head *head, struct leaf_info *new)
827 struct leaf_info *li = NULL, *last = NULL;
829 if (hlist_empty(head)) {
830 hlist_add_head_rcu(&new->hlist, head);
832 hlist_for_each_entry(li, head, hlist) {
833 if (new->plen > li->plen)
839 hlist_add_behind_rcu(&new->hlist, &last->hlist);
841 hlist_add_before_rcu(&new->hlist, &li->hlist);
845 /* rcu_read_lock needs to be hold by caller from readside */
846 static struct tnode *fib_find_node(struct trie *t, u32 key)
848 struct tnode *n = rcu_dereference_rtnl(t->trie);
851 unsigned long index = get_index(key, n);
853 /* This bit of code is a bit tricky but it combines multiple
854 * checks into a single check. The prefix consists of the
855 * prefix plus zeros for the bits in the cindex. The index
856 * is the difference between the key and this value. From
857 * this we can actually derive several pieces of data.
858 * if !(index >> bits)
859 * we know the value is cindex
861 * we have a mismatch in skip bits and failed
863 if (index >> n->bits)
866 /* we have found a leaf. Prefixes have already been compared */
870 n = rcu_dereference_rtnl(n->child[index]);
876 static void trie_rebalance(struct trie *t, struct tnode *tn)
880 while ((tp = node_parent(tn)) != NULL) {
885 /* Handle last (top) tnode */
890 /* only used from updater-side */
892 static struct list_head *fib_insert_node(struct trie *t, u32 key, int plen)
894 struct list_head *fa_head = NULL;
895 struct tnode *l, *n, *tp = NULL;
896 struct leaf_info *li;
898 li = leaf_info_new(plen);
903 n = rtnl_dereference(t->trie);
905 /* If we point to NULL, stop. Either the tree is empty and we should
906 * just put a new leaf in if, or we have reached an empty child slot,
907 * and we should just put our new leaf in that.
909 * If we hit a node with a key that does't match then we should stop
910 * and create a new tnode to replace that node and insert ourselves
911 * and the other node into the new tnode.
914 unsigned long index = get_index(key, n);
916 /* This bit of code is a bit tricky but it combines multiple
917 * checks into a single check. The prefix consists of the
918 * prefix plus zeros for the "bits" in the prefix. The index
919 * is the difference between the key and this value. From
920 * this we can actually derive several pieces of data.
921 * if !(index >> bits)
922 * we know the value is child index
924 * we have a mismatch in skip bits and failed
926 if (index >> n->bits)
929 /* we have found a leaf. Prefixes have already been compared */
931 /* Case 1: n is a leaf, and prefixes match*/
932 insert_leaf_info(&n->list, li);
937 n = rcu_dereference_rtnl(n->child[index]);
946 insert_leaf_info(&l->list, li);
948 /* Case 2: n is a LEAF or a TNODE and the key doesn't match.
950 * Add a new tnode here
951 * first tnode need some special handling
952 * leaves us in position for handling as case 3
957 tn = tnode_new(key, __fls(key ^ n->key), 1);
964 /* initialize routes out of node */
965 NODE_INIT_PARENT(tn, tp);
966 put_child(tn, get_index(key, tn) ^ 1, n);
968 /* start adding routes into the node */
969 put_child_root(tp, t, key, tn);
970 node_set_parent(n, tn);
972 /* parent now has a NULL spot where the leaf can go */
976 /* Case 3: n is NULL, and will just insert a new leaf */
978 NODE_INIT_PARENT(l, tp);
979 put_child(tp, get_index(key, tp), l);
980 trie_rebalance(t, tp);
982 rcu_assign_pointer(t->trie, l);
989 * Caller must hold RTNL.
991 int fib_table_insert(struct fib_table *tb, struct fib_config *cfg)
993 struct trie *t = (struct trie *) tb->tb_data;
994 struct fib_alias *fa, *new_fa;
995 struct list_head *fa_head = NULL;
997 int plen = cfg->fc_dst_len;
998 u8 tos = cfg->fc_tos;
1006 key = ntohl(cfg->fc_dst);
1008 pr_debug("Insert table=%u %08x/%d\n", tb->tb_id, key, plen);
1010 mask = ntohl(inet_make_mask(plen));
1017 fi = fib_create_info(cfg);
1023 l = fib_find_node(t, key);
1027 fa_head = get_fa_head(l, plen);
1028 fa = fib_find_alias(fa_head, tos, fi->fib_priority);
1031 /* Now fa, if non-NULL, points to the first fib alias
1032 * with the same keys [prefix,tos,priority], if such key already
1033 * exists or to the node before which we will insert new one.
1035 * If fa is NULL, we will need to allocate a new one and
1036 * insert to the head of f.
1038 * If f is NULL, no fib node matched the destination key
1039 * and we need to allocate a new one of those as well.
1042 if (fa && fa->fa_tos == tos &&
1043 fa->fa_info->fib_priority == fi->fib_priority) {
1044 struct fib_alias *fa_first, *fa_match;
1047 if (cfg->fc_nlflags & NLM_F_EXCL)
1051 * 1. Find exact match for type, scope, fib_info to avoid
1053 * 2. Find next 'fa' (or head), NLM_F_APPEND inserts before it
1057 fa = list_entry(fa->fa_list.prev, struct fib_alias, fa_list);
1058 list_for_each_entry_continue(fa, fa_head, fa_list) {
1059 if (fa->fa_tos != tos)
1061 if (fa->fa_info->fib_priority != fi->fib_priority)
1063 if (fa->fa_type == cfg->fc_type &&
1064 fa->fa_info == fi) {
1070 if (cfg->fc_nlflags & NLM_F_REPLACE) {
1071 struct fib_info *fi_drop;
1081 new_fa = kmem_cache_alloc(fn_alias_kmem, GFP_KERNEL);
1085 fi_drop = fa->fa_info;
1086 new_fa->fa_tos = fa->fa_tos;
1087 new_fa->fa_info = fi;
1088 new_fa->fa_type = cfg->fc_type;
1089 state = fa->fa_state;
1090 new_fa->fa_state = state & ~FA_S_ACCESSED;
1092 list_replace_rcu(&fa->fa_list, &new_fa->fa_list);
1093 alias_free_mem_rcu(fa);
1095 fib_release_info(fi_drop);
1096 if (state & FA_S_ACCESSED)
1097 rt_cache_flush(cfg->fc_nlinfo.nl_net);
1098 rtmsg_fib(RTM_NEWROUTE, htonl(key), new_fa, plen,
1099 tb->tb_id, &cfg->fc_nlinfo, NLM_F_REPLACE);
1103 /* Error if we find a perfect match which
1104 * uses the same scope, type, and nexthop
1110 if (!(cfg->fc_nlflags & NLM_F_APPEND))
1114 if (!(cfg->fc_nlflags & NLM_F_CREATE))
1118 new_fa = kmem_cache_alloc(fn_alias_kmem, GFP_KERNEL);
1122 new_fa->fa_info = fi;
1123 new_fa->fa_tos = tos;
1124 new_fa->fa_type = cfg->fc_type;
1125 new_fa->fa_state = 0;
1127 * Insert new entry to the list.
1131 fa_head = fib_insert_node(t, key, plen);
1132 if (unlikely(!fa_head)) {
1134 goto out_free_new_fa;
1139 tb->tb_num_default++;
1141 list_add_tail_rcu(&new_fa->fa_list,
1142 (fa ? &fa->fa_list : fa_head));
1144 rt_cache_flush(cfg->fc_nlinfo.nl_net);
1145 rtmsg_fib(RTM_NEWROUTE, htonl(key), new_fa, plen, tb->tb_id,
1146 &cfg->fc_nlinfo, 0);
1151 kmem_cache_free(fn_alias_kmem, new_fa);
1153 fib_release_info(fi);
1158 static inline t_key prefix_mismatch(t_key key, struct tnode *n)
1160 t_key prefix = n->key;
1162 return (key ^ prefix) & (prefix | -prefix);
1165 /* should be called with rcu_read_lock */
1166 int fib_table_lookup(struct fib_table *tb, const struct flowi4 *flp,
1167 struct fib_result *res, int fib_flags)
1169 struct trie *t = (struct trie *)tb->tb_data;
1170 #ifdef CONFIG_IP_FIB_TRIE_STATS
1171 struct trie_use_stats __percpu *stats = t->stats;
1173 const t_key key = ntohl(flp->daddr);
1174 struct tnode *n, *pn;
1175 struct leaf_info *li;
1178 n = rcu_dereference(t->trie);
1182 #ifdef CONFIG_IP_FIB_TRIE_STATS
1183 this_cpu_inc(stats->gets);
1189 /* Step 1: Travel to the longest prefix match in the trie */
1191 unsigned long index = get_index(key, n);
1193 /* This bit of code is a bit tricky but it combines multiple
1194 * checks into a single check. The prefix consists of the
1195 * prefix plus zeros for the "bits" in the prefix. The index
1196 * is the difference between the key and this value. From
1197 * this we can actually derive several pieces of data.
1198 * if !(index >> bits)
1199 * we know the value is child index
1201 * we have a mismatch in skip bits and failed
1203 if (index >> n->bits)
1206 /* we have found a leaf. Prefixes have already been compared */
1210 /* only record pn and cindex if we are going to be chopping
1211 * bits later. Otherwise we are just wasting cycles.
1218 n = rcu_dereference(n->child[index]);
1223 /* Step 2: Sort out leaves and begin backtracing for longest prefix */
1225 /* record the pointer where our next node pointer is stored */
1226 struct tnode __rcu **cptr = n->child;
1228 /* This test verifies that none of the bits that differ
1229 * between the key and the prefix exist in the region of
1230 * the lsb and higher in the prefix.
1232 if (unlikely(prefix_mismatch(key, n)))
1235 /* exit out and process leaf */
1236 if (unlikely(IS_LEAF(n)))
1239 /* Don't bother recording parent info. Since we are in
1240 * prefix match mode we will have to come back to wherever
1241 * we started this traversal anyway
1244 while ((n = rcu_dereference(*cptr)) == NULL) {
1246 #ifdef CONFIG_IP_FIB_TRIE_STATS
1248 this_cpu_inc(stats->null_node_hit);
1250 /* If we are at cindex 0 there are no more bits for
1251 * us to strip at this level so we must ascend back
1252 * up one level to see if there are any more bits to
1253 * be stripped there.
1256 t_key pkey = pn->key;
1258 pn = node_parent_rcu(pn);
1261 #ifdef CONFIG_IP_FIB_TRIE_STATS
1262 this_cpu_inc(stats->backtrack);
1264 /* Get Child's index */
1265 cindex = get_index(pkey, pn);
1268 /* strip the least significant bit from the cindex */
1269 cindex &= cindex - 1;
1271 /* grab pointer for next child node */
1272 cptr = &pn->child[cindex];
1277 /* Step 3: Process the leaf, if that fails fall back to backtracing */
1278 hlist_for_each_entry_rcu(li, &n->list, hlist) {
1279 struct fib_alias *fa;
1281 if ((key ^ n->key) & li->mask_plen)
1284 list_for_each_entry_rcu(fa, &li->falh, fa_list) {
1285 struct fib_info *fi = fa->fa_info;
1288 if (fa->fa_tos && fa->fa_tos != flp->flowi4_tos)
1292 if (fa->fa_info->fib_scope < flp->flowi4_scope)
1294 fib_alias_accessed(fa);
1295 err = fib_props[fa->fa_type].error;
1296 if (unlikely(err < 0)) {
1297 #ifdef CONFIG_IP_FIB_TRIE_STATS
1298 this_cpu_inc(stats->semantic_match_passed);
1302 if (fi->fib_flags & RTNH_F_DEAD)
1304 for (nhsel = 0; nhsel < fi->fib_nhs; nhsel++) {
1305 const struct fib_nh *nh = &fi->fib_nh[nhsel];
1307 if (nh->nh_flags & RTNH_F_DEAD)
1309 if (flp->flowi4_oif && flp->flowi4_oif != nh->nh_oif)
1312 if (!(fib_flags & FIB_LOOKUP_NOREF))
1313 atomic_inc(&fi->fib_clntref);
1315 res->prefixlen = li->plen;
1316 res->nh_sel = nhsel;
1317 res->type = fa->fa_type;
1318 res->scope = fi->fib_scope;
1321 res->fa_head = &li->falh;
1322 #ifdef CONFIG_IP_FIB_TRIE_STATS
1323 this_cpu_inc(stats->semantic_match_passed);
1329 #ifdef CONFIG_IP_FIB_TRIE_STATS
1330 this_cpu_inc(stats->semantic_match_miss);
1335 EXPORT_SYMBOL_GPL(fib_table_lookup);
1338 * Remove the leaf and return parent.
1340 static void trie_leaf_remove(struct trie *t, struct tnode *l)
1342 struct tnode *tp = node_parent(l);
1344 pr_debug("entering trie_leaf_remove(%p)\n", l);
1347 put_child(tp, get_index(l->key, tp), NULL);
1348 trie_rebalance(t, tp);
1350 RCU_INIT_POINTER(t->trie, NULL);
1357 * Caller must hold RTNL.
1359 int fib_table_delete(struct fib_table *tb, struct fib_config *cfg)
1361 struct trie *t = (struct trie *) tb->tb_data;
1363 int plen = cfg->fc_dst_len;
1364 u8 tos = cfg->fc_tos;
1365 struct fib_alias *fa, *fa_to_delete;
1366 struct list_head *fa_head;
1368 struct leaf_info *li;
1373 key = ntohl(cfg->fc_dst);
1374 mask = ntohl(inet_make_mask(plen));
1380 l = fib_find_node(t, key);
1385 li = find_leaf_info(l, plen);
1390 fa_head = &li->falh;
1391 fa = fib_find_alias(fa_head, tos, 0);
1396 pr_debug("Deleting %08x/%d tos=%d t=%p\n", key, plen, tos, t);
1398 fa_to_delete = NULL;
1399 fa = list_entry(fa->fa_list.prev, struct fib_alias, fa_list);
1400 list_for_each_entry_continue(fa, fa_head, fa_list) {
1401 struct fib_info *fi = fa->fa_info;
1403 if (fa->fa_tos != tos)
1406 if ((!cfg->fc_type || fa->fa_type == cfg->fc_type) &&
1407 (cfg->fc_scope == RT_SCOPE_NOWHERE ||
1408 fa->fa_info->fib_scope == cfg->fc_scope) &&
1409 (!cfg->fc_prefsrc ||
1410 fi->fib_prefsrc == cfg->fc_prefsrc) &&
1411 (!cfg->fc_protocol ||
1412 fi->fib_protocol == cfg->fc_protocol) &&
1413 fib_nh_match(cfg, fi) == 0) {
1423 rtmsg_fib(RTM_DELROUTE, htonl(key), fa, plen, tb->tb_id,
1424 &cfg->fc_nlinfo, 0);
1426 list_del_rcu(&fa->fa_list);
1429 tb->tb_num_default--;
1431 if (list_empty(fa_head)) {
1432 hlist_del_rcu(&li->hlist);
1436 if (hlist_empty(&l->list))
1437 trie_leaf_remove(t, l);
1439 if (fa->fa_state & FA_S_ACCESSED)
1440 rt_cache_flush(cfg->fc_nlinfo.nl_net);
1442 fib_release_info(fa->fa_info);
1443 alias_free_mem_rcu(fa);
1447 static int trie_flush_list(struct list_head *head)
1449 struct fib_alias *fa, *fa_node;
1452 list_for_each_entry_safe(fa, fa_node, head, fa_list) {
1453 struct fib_info *fi = fa->fa_info;
1455 if (fi && (fi->fib_flags & RTNH_F_DEAD)) {
1456 list_del_rcu(&fa->fa_list);
1457 fib_release_info(fa->fa_info);
1458 alias_free_mem_rcu(fa);
1465 static int trie_flush_leaf(struct tnode *l)
1468 struct hlist_head *lih = &l->list;
1469 struct hlist_node *tmp;
1470 struct leaf_info *li = NULL;
1472 hlist_for_each_entry_safe(li, tmp, lih, hlist) {
1473 found += trie_flush_list(&li->falh);
1475 if (list_empty(&li->falh)) {
1476 hlist_del_rcu(&li->hlist);
1484 * Scan for the next right leaf starting at node p->child[idx]
1485 * Since we have back pointer, no recursion necessary.
1487 static struct tnode *leaf_walk_rcu(struct tnode *p, struct tnode *c)
1490 unsigned long idx = c ? idx = get_index(c->key, p) + 1 : 0;
1492 while (idx < tnode_child_length(p)) {
1493 c = tnode_get_child_rcu(p, idx++);
1500 /* Rescan start scanning in new node */
1505 /* Node empty, walk back up to parent */
1507 } while ((p = node_parent_rcu(c)) != NULL);
1509 return NULL; /* Root of trie */
1512 static struct tnode *trie_firstleaf(struct trie *t)
1514 struct tnode *n = rcu_dereference_rtnl(t->trie);
1519 if (IS_LEAF(n)) /* trie is just a leaf */
1522 return leaf_walk_rcu(n, NULL);
1525 static struct tnode *trie_nextleaf(struct tnode *l)
1527 struct tnode *p = node_parent_rcu(l);
1530 return NULL; /* trie with just one leaf */
1532 return leaf_walk_rcu(p, l);
1535 static struct tnode *trie_leafindex(struct trie *t, int index)
1537 struct tnode *l = trie_firstleaf(t);
1539 while (l && index-- > 0)
1540 l = trie_nextleaf(l);
1547 * Caller must hold RTNL.
1549 int fib_table_flush(struct fib_table *tb)
1551 struct trie *t = (struct trie *) tb->tb_data;
1552 struct tnode *l, *ll = NULL;
1555 for (l = trie_firstleaf(t); l; l = trie_nextleaf(l)) {
1556 found += trie_flush_leaf(l);
1558 if (ll && hlist_empty(&ll->list))
1559 trie_leaf_remove(t, ll);
1563 if (ll && hlist_empty(&ll->list))
1564 trie_leaf_remove(t, ll);
1566 pr_debug("trie_flush found=%d\n", found);
1570 void fib_free_table(struct fib_table *tb)
1572 #ifdef CONFIG_IP_FIB_TRIE_STATS
1573 struct trie *t = (struct trie *)tb->tb_data;
1575 free_percpu(t->stats);
1576 #endif /* CONFIG_IP_FIB_TRIE_STATS */
1580 static int fn_trie_dump_fa(t_key key, int plen, struct list_head *fah,
1581 struct fib_table *tb,
1582 struct sk_buff *skb, struct netlink_callback *cb)
1585 struct fib_alias *fa;
1586 __be32 xkey = htonl(key);
1591 /* rcu_read_lock is hold by caller */
1593 list_for_each_entry_rcu(fa, fah, fa_list) {
1599 if (fib_dump_info(skb, NETLINK_CB(cb->skb).portid,
1607 fa->fa_info, NLM_F_MULTI) < 0) {
1617 static int fn_trie_dump_leaf(struct tnode *l, struct fib_table *tb,
1618 struct sk_buff *skb, struct netlink_callback *cb)
1620 struct leaf_info *li;
1626 /* rcu_read_lock is hold by caller */
1627 hlist_for_each_entry_rcu(li, &l->list, hlist) {
1636 if (list_empty(&li->falh))
1639 if (fn_trie_dump_fa(l->key, li->plen, &li->falh, tb, skb, cb) < 0) {
1650 int fib_table_dump(struct fib_table *tb, struct sk_buff *skb,
1651 struct netlink_callback *cb)
1654 struct trie *t = (struct trie *) tb->tb_data;
1655 t_key key = cb->args[2];
1656 int count = cb->args[3];
1659 /* Dump starting at last key.
1660 * Note: 0.0.0.0/0 (ie default) is first key.
1663 l = trie_firstleaf(t);
1665 /* Normally, continue from last key, but if that is missing
1666 * fallback to using slow rescan
1668 l = fib_find_node(t, key);
1670 l = trie_leafindex(t, count);
1674 cb->args[2] = l->key;
1675 if (fn_trie_dump_leaf(l, tb, skb, cb) < 0) {
1676 cb->args[3] = count;
1682 l = trie_nextleaf(l);
1683 memset(&cb->args[4], 0,
1684 sizeof(cb->args) - 4*sizeof(cb->args[0]));
1686 cb->args[3] = count;
1692 void __init fib_trie_init(void)
1694 fn_alias_kmem = kmem_cache_create("ip_fib_alias",
1695 sizeof(struct fib_alias),
1696 0, SLAB_PANIC, NULL);
1698 trie_leaf_kmem = kmem_cache_create("ip_fib_trie",
1699 max(sizeof(struct tnode),
1700 sizeof(struct leaf_info)),
1701 0, SLAB_PANIC, NULL);
1705 struct fib_table *fib_trie_table(u32 id)
1707 struct fib_table *tb;
1710 tb = kmalloc(sizeof(struct fib_table) + sizeof(struct trie),
1716 tb->tb_default = -1;
1717 tb->tb_num_default = 0;
1719 t = (struct trie *) tb->tb_data;
1720 RCU_INIT_POINTER(t->trie, NULL);
1721 #ifdef CONFIG_IP_FIB_TRIE_STATS
1722 t->stats = alloc_percpu(struct trie_use_stats);
1732 #ifdef CONFIG_PROC_FS
1733 /* Depth first Trie walk iterator */
1734 struct fib_trie_iter {
1735 struct seq_net_private p;
1736 struct fib_table *tb;
1737 struct tnode *tnode;
1742 static struct tnode *fib_trie_get_next(struct fib_trie_iter *iter)
1744 unsigned long cindex = iter->index;
1745 struct tnode *tn = iter->tnode;
1748 /* A single entry routing table */
1752 pr_debug("get_next iter={node=%p index=%d depth=%d}\n",
1753 iter->tnode, iter->index, iter->depth);
1755 while (cindex < tnode_child_length(tn)) {
1756 struct tnode *n = tnode_get_child_rcu(tn, cindex);
1761 iter->index = cindex + 1;
1763 /* push down one level */
1774 /* Current node exhausted, pop back up */
1775 p = node_parent_rcu(tn);
1777 cindex = get_index(tn->key, p) + 1;
1787 static struct tnode *fib_trie_get_first(struct fib_trie_iter *iter,
1795 n = rcu_dereference(t->trie);
1812 static void trie_collect_stats(struct trie *t, struct trie_stat *s)
1815 struct fib_trie_iter iter;
1817 memset(s, 0, sizeof(*s));
1820 for (n = fib_trie_get_first(&iter, t); n; n = fib_trie_get_next(&iter)) {
1822 struct leaf_info *li;
1825 s->totdepth += iter.depth;
1826 if (iter.depth > s->maxdepth)
1827 s->maxdepth = iter.depth;
1829 hlist_for_each_entry_rcu(li, &n->list, hlist)
1835 if (n->bits < MAX_STAT_DEPTH)
1836 s->nodesizes[n->bits]++;
1838 for (i = 0; i < tnode_child_length(n); i++) {
1839 if (!rcu_access_pointer(n->child[i]))
1848 * This outputs /proc/net/fib_triestats
1850 static void trie_show_stats(struct seq_file *seq, struct trie_stat *stat)
1852 unsigned int i, max, pointers, bytes, avdepth;
1855 avdepth = stat->totdepth*100 / stat->leaves;
1859 seq_printf(seq, "\tAver depth: %u.%02d\n",
1860 avdepth / 100, avdepth % 100);
1861 seq_printf(seq, "\tMax depth: %u\n", stat->maxdepth);
1863 seq_printf(seq, "\tLeaves: %u\n", stat->leaves);
1864 bytes = sizeof(struct tnode) * stat->leaves;
1866 seq_printf(seq, "\tPrefixes: %u\n", stat->prefixes);
1867 bytes += sizeof(struct leaf_info) * stat->prefixes;
1869 seq_printf(seq, "\tInternal nodes: %u\n\t", stat->tnodes);
1870 bytes += sizeof(struct tnode) * stat->tnodes;
1872 max = MAX_STAT_DEPTH;
1873 while (max > 0 && stat->nodesizes[max-1] == 0)
1877 for (i = 1; i < max; i++)
1878 if (stat->nodesizes[i] != 0) {
1879 seq_printf(seq, " %u: %u", i, stat->nodesizes[i]);
1880 pointers += (1<<i) * stat->nodesizes[i];
1882 seq_putc(seq, '\n');
1883 seq_printf(seq, "\tPointers: %u\n", pointers);
1885 bytes += sizeof(struct tnode *) * pointers;
1886 seq_printf(seq, "Null ptrs: %u\n", stat->nullpointers);
1887 seq_printf(seq, "Total size: %u kB\n", (bytes + 1023) / 1024);
1890 #ifdef CONFIG_IP_FIB_TRIE_STATS
1891 static void trie_show_usage(struct seq_file *seq,
1892 const struct trie_use_stats __percpu *stats)
1894 struct trie_use_stats s = { 0 };
1897 /* loop through all of the CPUs and gather up the stats */
1898 for_each_possible_cpu(cpu) {
1899 const struct trie_use_stats *pcpu = per_cpu_ptr(stats, cpu);
1901 s.gets += pcpu->gets;
1902 s.backtrack += pcpu->backtrack;
1903 s.semantic_match_passed += pcpu->semantic_match_passed;
1904 s.semantic_match_miss += pcpu->semantic_match_miss;
1905 s.null_node_hit += pcpu->null_node_hit;
1906 s.resize_node_skipped += pcpu->resize_node_skipped;
1909 seq_printf(seq, "\nCounters:\n---------\n");
1910 seq_printf(seq, "gets = %u\n", s.gets);
1911 seq_printf(seq, "backtracks = %u\n", s.backtrack);
1912 seq_printf(seq, "semantic match passed = %u\n",
1913 s.semantic_match_passed);
1914 seq_printf(seq, "semantic match miss = %u\n", s.semantic_match_miss);
1915 seq_printf(seq, "null node hit= %u\n", s.null_node_hit);
1916 seq_printf(seq, "skipped node resize = %u\n\n", s.resize_node_skipped);
1918 #endif /* CONFIG_IP_FIB_TRIE_STATS */
1920 static void fib_table_print(struct seq_file *seq, struct fib_table *tb)
1922 if (tb->tb_id == RT_TABLE_LOCAL)
1923 seq_puts(seq, "Local:\n");
1924 else if (tb->tb_id == RT_TABLE_MAIN)
1925 seq_puts(seq, "Main:\n");
1927 seq_printf(seq, "Id %d:\n", tb->tb_id);
1931 static int fib_triestat_seq_show(struct seq_file *seq, void *v)
1933 struct net *net = (struct net *)seq->private;
1937 "Basic info: size of leaf:"
1938 " %Zd bytes, size of tnode: %Zd bytes.\n",
1939 sizeof(struct tnode), sizeof(struct tnode));
1941 for (h = 0; h < FIB_TABLE_HASHSZ; h++) {
1942 struct hlist_head *head = &net->ipv4.fib_table_hash[h];
1943 struct fib_table *tb;
1945 hlist_for_each_entry_rcu(tb, head, tb_hlist) {
1946 struct trie *t = (struct trie *) tb->tb_data;
1947 struct trie_stat stat;
1952 fib_table_print(seq, tb);
1954 trie_collect_stats(t, &stat);
1955 trie_show_stats(seq, &stat);
1956 #ifdef CONFIG_IP_FIB_TRIE_STATS
1957 trie_show_usage(seq, t->stats);
1965 static int fib_triestat_seq_open(struct inode *inode, struct file *file)
1967 return single_open_net(inode, file, fib_triestat_seq_show);
1970 static const struct file_operations fib_triestat_fops = {
1971 .owner = THIS_MODULE,
1972 .open = fib_triestat_seq_open,
1974 .llseek = seq_lseek,
1975 .release = single_release_net,
1978 static struct tnode *fib_trie_get_idx(struct seq_file *seq, loff_t pos)
1980 struct fib_trie_iter *iter = seq->private;
1981 struct net *net = seq_file_net(seq);
1985 for (h = 0; h < FIB_TABLE_HASHSZ; h++) {
1986 struct hlist_head *head = &net->ipv4.fib_table_hash[h];
1987 struct fib_table *tb;
1989 hlist_for_each_entry_rcu(tb, head, tb_hlist) {
1992 for (n = fib_trie_get_first(iter,
1993 (struct trie *) tb->tb_data);
1994 n; n = fib_trie_get_next(iter))
2005 static void *fib_trie_seq_start(struct seq_file *seq, loff_t *pos)
2009 return fib_trie_get_idx(seq, *pos);
2012 static void *fib_trie_seq_next(struct seq_file *seq, void *v, loff_t *pos)
2014 struct fib_trie_iter *iter = seq->private;
2015 struct net *net = seq_file_net(seq);
2016 struct fib_table *tb = iter->tb;
2017 struct hlist_node *tb_node;
2022 /* next node in same table */
2023 n = fib_trie_get_next(iter);
2027 /* walk rest of this hash chain */
2028 h = tb->tb_id & (FIB_TABLE_HASHSZ - 1);
2029 while ((tb_node = rcu_dereference(hlist_next_rcu(&tb->tb_hlist)))) {
2030 tb = hlist_entry(tb_node, struct fib_table, tb_hlist);
2031 n = fib_trie_get_first(iter, (struct trie *) tb->tb_data);
2036 /* new hash chain */
2037 while (++h < FIB_TABLE_HASHSZ) {
2038 struct hlist_head *head = &net->ipv4.fib_table_hash[h];
2039 hlist_for_each_entry_rcu(tb, head, tb_hlist) {
2040 n = fib_trie_get_first(iter, (struct trie *) tb->tb_data);
2052 static void fib_trie_seq_stop(struct seq_file *seq, void *v)
2058 static void seq_indent(struct seq_file *seq, int n)
2064 static inline const char *rtn_scope(char *buf, size_t len, enum rt_scope_t s)
2067 case RT_SCOPE_UNIVERSE: return "universe";
2068 case RT_SCOPE_SITE: return "site";
2069 case RT_SCOPE_LINK: return "link";
2070 case RT_SCOPE_HOST: return "host";
2071 case RT_SCOPE_NOWHERE: return "nowhere";
2073 snprintf(buf, len, "scope=%d", s);
2078 static const char *const rtn_type_names[__RTN_MAX] = {
2079 [RTN_UNSPEC] = "UNSPEC",
2080 [RTN_UNICAST] = "UNICAST",
2081 [RTN_LOCAL] = "LOCAL",
2082 [RTN_BROADCAST] = "BROADCAST",
2083 [RTN_ANYCAST] = "ANYCAST",
2084 [RTN_MULTICAST] = "MULTICAST",
2085 [RTN_BLACKHOLE] = "BLACKHOLE",
2086 [RTN_UNREACHABLE] = "UNREACHABLE",
2087 [RTN_PROHIBIT] = "PROHIBIT",
2088 [RTN_THROW] = "THROW",
2090 [RTN_XRESOLVE] = "XRESOLVE",
2093 static inline const char *rtn_type(char *buf, size_t len, unsigned int t)
2095 if (t < __RTN_MAX && rtn_type_names[t])
2096 return rtn_type_names[t];
2097 snprintf(buf, len, "type %u", t);
2101 /* Pretty print the trie */
2102 static int fib_trie_seq_show(struct seq_file *seq, void *v)
2104 const struct fib_trie_iter *iter = seq->private;
2105 struct tnode *n = v;
2107 if (!node_parent_rcu(n))
2108 fib_table_print(seq, iter->tb);
2111 __be32 prf = htonl(n->key);
2113 seq_indent(seq, iter->depth-1);
2114 seq_printf(seq, " +-- %pI4/%zu %u %u %u\n",
2115 &prf, KEYLENGTH - n->pos - n->bits, n->bits,
2116 n->full_children, n->empty_children);
2118 struct leaf_info *li;
2119 __be32 val = htonl(n->key);
2121 seq_indent(seq, iter->depth);
2122 seq_printf(seq, " |-- %pI4\n", &val);
2124 hlist_for_each_entry_rcu(li, &n->list, hlist) {
2125 struct fib_alias *fa;
2127 list_for_each_entry_rcu(fa, &li->falh, fa_list) {
2128 char buf1[32], buf2[32];
2130 seq_indent(seq, iter->depth+1);
2131 seq_printf(seq, " /%d %s %s", li->plen,
2132 rtn_scope(buf1, sizeof(buf1),
2133 fa->fa_info->fib_scope),
2134 rtn_type(buf2, sizeof(buf2),
2137 seq_printf(seq, " tos=%d", fa->fa_tos);
2138 seq_putc(seq, '\n');
2146 static const struct seq_operations fib_trie_seq_ops = {
2147 .start = fib_trie_seq_start,
2148 .next = fib_trie_seq_next,
2149 .stop = fib_trie_seq_stop,
2150 .show = fib_trie_seq_show,
2153 static int fib_trie_seq_open(struct inode *inode, struct file *file)
2155 return seq_open_net(inode, file, &fib_trie_seq_ops,
2156 sizeof(struct fib_trie_iter));
2159 static const struct file_operations fib_trie_fops = {
2160 .owner = THIS_MODULE,
2161 .open = fib_trie_seq_open,
2163 .llseek = seq_lseek,
2164 .release = seq_release_net,
2167 struct fib_route_iter {
2168 struct seq_net_private p;
2169 struct trie *main_trie;
2174 static struct tnode *fib_route_get_idx(struct fib_route_iter *iter, loff_t pos)
2176 struct tnode *l = NULL;
2177 struct trie *t = iter->main_trie;
2179 /* use cache location of last found key */
2180 if (iter->pos > 0 && pos >= iter->pos && (l = fib_find_node(t, iter->key)))
2184 l = trie_firstleaf(t);
2187 while (l && pos-- > 0) {
2189 l = trie_nextleaf(l);
2193 iter->key = pos; /* remember it */
2195 iter->pos = 0; /* forget it */
2200 static void *fib_route_seq_start(struct seq_file *seq, loff_t *pos)
2203 struct fib_route_iter *iter = seq->private;
2204 struct fib_table *tb;
2207 tb = fib_get_table(seq_file_net(seq), RT_TABLE_MAIN);
2211 iter->main_trie = (struct trie *) tb->tb_data;
2213 return SEQ_START_TOKEN;
2215 return fib_route_get_idx(iter, *pos - 1);
2218 static void *fib_route_seq_next(struct seq_file *seq, void *v, loff_t *pos)
2220 struct fib_route_iter *iter = seq->private;
2221 struct tnode *l = v;
2224 if (v == SEQ_START_TOKEN) {
2226 l = trie_firstleaf(iter->main_trie);
2229 l = trie_nextleaf(l);
2239 static void fib_route_seq_stop(struct seq_file *seq, void *v)
2245 static unsigned int fib_flag_trans(int type, __be32 mask, const struct fib_info *fi)
2247 unsigned int flags = 0;
2249 if (type == RTN_UNREACHABLE || type == RTN_PROHIBIT)
2251 if (fi && fi->fib_nh->nh_gw)
2252 flags |= RTF_GATEWAY;
2253 if (mask == htonl(0xFFFFFFFF))
2260 * This outputs /proc/net/route.
2261 * The format of the file is not supposed to be changed
2262 * and needs to be same as fib_hash output to avoid breaking
2265 static int fib_route_seq_show(struct seq_file *seq, void *v)
2267 struct tnode *l = v;
2268 struct leaf_info *li;
2270 if (v == SEQ_START_TOKEN) {
2271 seq_printf(seq, "%-127s\n", "Iface\tDestination\tGateway "
2272 "\tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU"
2277 hlist_for_each_entry_rcu(li, &l->list, hlist) {
2278 struct fib_alias *fa;
2279 __be32 mask, prefix;
2281 mask = inet_make_mask(li->plen);
2282 prefix = htonl(l->key);
2284 list_for_each_entry_rcu(fa, &li->falh, fa_list) {
2285 const struct fib_info *fi = fa->fa_info;
2286 unsigned int flags = fib_flag_trans(fa->fa_type, mask, fi);
2288 if (fa->fa_type == RTN_BROADCAST
2289 || fa->fa_type == RTN_MULTICAST)
2292 seq_setwidth(seq, 127);
2296 "%s\t%08X\t%08X\t%04X\t%d\t%u\t"
2297 "%d\t%08X\t%d\t%u\t%u",
2298 fi->fib_dev ? fi->fib_dev->name : "*",
2300 fi->fib_nh->nh_gw, flags, 0, 0,
2304 fi->fib_advmss + 40 : 0),
2309 "*\t%08X\t%08X\t%04X\t%d\t%u\t"
2310 "%d\t%08X\t%d\t%u\t%u",
2311 prefix, 0, flags, 0, 0, 0,
2321 static const struct seq_operations fib_route_seq_ops = {
2322 .start = fib_route_seq_start,
2323 .next = fib_route_seq_next,
2324 .stop = fib_route_seq_stop,
2325 .show = fib_route_seq_show,
2328 static int fib_route_seq_open(struct inode *inode, struct file *file)
2330 return seq_open_net(inode, file, &fib_route_seq_ops,
2331 sizeof(struct fib_route_iter));
2334 static const struct file_operations fib_route_fops = {
2335 .owner = THIS_MODULE,
2336 .open = fib_route_seq_open,
2338 .llseek = seq_lseek,
2339 .release = seq_release_net,
2342 int __net_init fib_proc_init(struct net *net)
2344 if (!proc_create("fib_trie", S_IRUGO, net->proc_net, &fib_trie_fops))
2347 if (!proc_create("fib_triestat", S_IRUGO, net->proc_net,
2348 &fib_triestat_fops))
2351 if (!proc_create("route", S_IRUGO, net->proc_net, &fib_route_fops))
2357 remove_proc_entry("fib_triestat", net->proc_net);
2359 remove_proc_entry("fib_trie", net->proc_net);
2364 void __net_exit fib_proc_exit(struct net *net)
2366 remove_proc_entry("fib_trie", net->proc_net);
2367 remove_proc_entry("fib_triestat", net->proc_net);
2368 remove_proc_entry("route", net->proc_net);
2371 #endif /* CONFIG_PROC_FS */