ipv6: make fib6 serial number per namespace
[pandora-kernel.git] / net / ipv6 / ip6_fib.c
1 /*
2  *      Linux INET6 implementation
3  *      Forwarding Information Database
4  *
5  *      Authors:
6  *      Pedro Roque             <roque@di.fc.ul.pt>
7  *
8  *      This program is free software; you can redistribute it and/or
9  *      modify it under the terms of the GNU General Public License
10  *      as published by the Free Software Foundation; either version
11  *      2 of the License, or (at your option) any later version.
12  *
13  *      Changes:
14  *      Yuji SEKIYA @USAGI:     Support default route on router node;
15  *                              remove ip6_null_entry from the top of
16  *                              routing table.
17  *      Ville Nuorvala:         Fixed routing subtrees.
18  */
19
20 #define pr_fmt(fmt) "IPv6: " fmt
21
22 #include <linux/errno.h>
23 #include <linux/types.h>
24 #include <linux/net.h>
25 #include <linux/route.h>
26 #include <linux/netdevice.h>
27 #include <linux/in6.h>
28 #include <linux/init.h>
29 #include <linux/list.h>
30 #include <linux/slab.h>
31
32 #include <net/ipv6.h>
33 #include <net/ndisc.h>
34 #include <net/addrconf.h>
35
36 #include <net/ip6_fib.h>
37 #include <net/ip6_route.h>
38
39 #define RT6_DEBUG 2
40
41 #if RT6_DEBUG >= 3
42 #define RT6_TRACE(x...) pr_debug(x)
43 #else
44 #define RT6_TRACE(x...) do { ; } while (0)
45 #endif
46
47 static struct kmem_cache *fib6_node_kmem __read_mostly;
48
49 struct fib6_cleaner {
50         struct fib6_walker w;
51         struct net *net;
52         int (*func)(struct rt6_info *, void *arg);
53         void *arg;
54 };
55
56 static DEFINE_RWLOCK(fib6_walker_lock);
57
58 #ifdef CONFIG_IPV6_SUBTREES
59 #define FWS_INIT FWS_S
60 #else
61 #define FWS_INIT FWS_L
62 #endif
63
64 static void fib6_prune_clones(struct net *net, struct fib6_node *fn);
65 static struct rt6_info *fib6_find_prefix(struct net *net, struct fib6_node *fn);
66 static struct fib6_node *fib6_repair_tree(struct net *net, struct fib6_node *fn);
67 static int fib6_walk(struct fib6_walker *w);
68 static int fib6_walk_continue(struct fib6_walker *w);
69
70 /*
71  *      A routing update causes an increase of the serial number on the
72  *      affected subtree. This allows for cached routes to be asynchronously
73  *      tested when modifications are made to the destination cache as a
74  *      result of redirects, path MTU changes, etc.
75  */
76
77 static void fib6_gc_timer_cb(unsigned long arg);
78
79 static LIST_HEAD(fib6_walkers);
80 #define FOR_WALKERS(w) list_for_each_entry(w, &fib6_walkers, lh)
81
82 static void fib6_walker_link(struct fib6_walker *w)
83 {
84         write_lock_bh(&fib6_walker_lock);
85         list_add(&w->lh, &fib6_walkers);
86         write_unlock_bh(&fib6_walker_lock);
87 }
88
89 static void fib6_walker_unlink(struct fib6_walker *w)
90 {
91         write_lock_bh(&fib6_walker_lock);
92         list_del(&w->lh);
93         write_unlock_bh(&fib6_walker_lock);
94 }
95
96 static int fib6_new_sernum(struct net *net)
97 {
98         int new, old;
99
100         do {
101                 old = atomic_read(&net->ipv6.fib6_sernum);
102                 new = old < INT_MAX ? old + 1 : 1;
103         } while (atomic_cmpxchg(&net->ipv6.fib6_sernum,
104                                 old, new) != old);
105         return new;
106 }
107
108 /*
109  *      Auxiliary address test functions for the radix tree.
110  *
111  *      These assume a 32bit processor (although it will work on
112  *      64bit processors)
113  */
114
115 /*
116  *      test bit
117  */
118 #if defined(__LITTLE_ENDIAN)
119 # define BITOP_BE32_SWIZZLE     (0x1F & ~7)
120 #else
121 # define BITOP_BE32_SWIZZLE     0
122 #endif
123
124 static __be32 addr_bit_set(const void *token, int fn_bit)
125 {
126         const __be32 *addr = token;
127         /*
128          * Here,
129          *      1 << ((~fn_bit ^ BITOP_BE32_SWIZZLE) & 0x1f)
130          * is optimized version of
131          *      htonl(1 << ((~fn_bit)&0x1F))
132          * See include/asm-generic/bitops/le.h.
133          */
134         return (__force __be32)(1 << ((~fn_bit ^ BITOP_BE32_SWIZZLE) & 0x1f)) &
135                addr[fn_bit >> 5];
136 }
137
138 static struct fib6_node *node_alloc(void)
139 {
140         struct fib6_node *fn;
141
142         fn = kmem_cache_zalloc(fib6_node_kmem, GFP_ATOMIC);
143
144         return fn;
145 }
146
147 static void node_free(struct fib6_node *fn)
148 {
149         kmem_cache_free(fib6_node_kmem, fn);
150 }
151
152 static void rt6_release(struct rt6_info *rt)
153 {
154         if (atomic_dec_and_test(&rt->rt6i_ref))
155                 dst_free(&rt->dst);
156 }
157
158 static void fib6_link_table(struct net *net, struct fib6_table *tb)
159 {
160         unsigned int h;
161
162         /*
163          * Initialize table lock at a single place to give lockdep a key,
164          * tables aren't visible prior to being linked to the list.
165          */
166         rwlock_init(&tb->tb6_lock);
167
168         h = tb->tb6_id & (FIB6_TABLE_HASHSZ - 1);
169
170         /*
171          * No protection necessary, this is the only list mutatation
172          * operation, tables never disappear once they exist.
173          */
174         hlist_add_head_rcu(&tb->tb6_hlist, &net->ipv6.fib_table_hash[h]);
175 }
176
177 #ifdef CONFIG_IPV6_MULTIPLE_TABLES
178
179 static struct fib6_table *fib6_alloc_table(struct net *net, u32 id)
180 {
181         struct fib6_table *table;
182
183         table = kzalloc(sizeof(*table), GFP_ATOMIC);
184         if (table) {
185                 table->tb6_id = id;
186                 table->tb6_root.leaf = net->ipv6.ip6_null_entry;
187                 table->tb6_root.fn_flags = RTN_ROOT | RTN_TL_ROOT | RTN_RTINFO;
188                 inet_peer_base_init(&table->tb6_peers);
189         }
190
191         return table;
192 }
193
194 struct fib6_table *fib6_new_table(struct net *net, u32 id)
195 {
196         struct fib6_table *tb;
197
198         if (id == 0)
199                 id = RT6_TABLE_MAIN;
200         tb = fib6_get_table(net, id);
201         if (tb)
202                 return tb;
203
204         tb = fib6_alloc_table(net, id);
205         if (tb)
206                 fib6_link_table(net, tb);
207
208         return tb;
209 }
210
211 struct fib6_table *fib6_get_table(struct net *net, u32 id)
212 {
213         struct fib6_table *tb;
214         struct hlist_head *head;
215         unsigned int h;
216
217         if (id == 0)
218                 id = RT6_TABLE_MAIN;
219         h = id & (FIB6_TABLE_HASHSZ - 1);
220         rcu_read_lock();
221         head = &net->ipv6.fib_table_hash[h];
222         hlist_for_each_entry_rcu(tb, head, tb6_hlist) {
223                 if (tb->tb6_id == id) {
224                         rcu_read_unlock();
225                         return tb;
226                 }
227         }
228         rcu_read_unlock();
229
230         return NULL;
231 }
232
233 static void __net_init fib6_tables_init(struct net *net)
234 {
235         fib6_link_table(net, net->ipv6.fib6_main_tbl);
236         fib6_link_table(net, net->ipv6.fib6_local_tbl);
237 }
238 #else
239
240 struct fib6_table *fib6_new_table(struct net *net, u32 id)
241 {
242         return fib6_get_table(net, id);
243 }
244
245 struct fib6_table *fib6_get_table(struct net *net, u32 id)
246 {
247           return net->ipv6.fib6_main_tbl;
248 }
249
250 struct dst_entry *fib6_rule_lookup(struct net *net, struct flowi6 *fl6,
251                                    int flags, pol_lookup_t lookup)
252 {
253         return (struct dst_entry *) lookup(net, net->ipv6.fib6_main_tbl, fl6, flags);
254 }
255
256 static void __net_init fib6_tables_init(struct net *net)
257 {
258         fib6_link_table(net, net->ipv6.fib6_main_tbl);
259 }
260
261 #endif
262
263 static int fib6_dump_node(struct fib6_walker *w)
264 {
265         int res;
266         struct rt6_info *rt;
267
268         for (rt = w->leaf; rt; rt = rt->dst.rt6_next) {
269                 res = rt6_dump_route(rt, w->args);
270                 if (res < 0) {
271                         /* Frame is full, suspend walking */
272                         w->leaf = rt;
273                         return 1;
274                 }
275                 WARN_ON(res == 0);
276         }
277         w->leaf = NULL;
278         return 0;
279 }
280
281 static void fib6_dump_end(struct netlink_callback *cb)
282 {
283         struct fib6_walker *w = (void *)cb->args[2];
284
285         if (w) {
286                 if (cb->args[4]) {
287                         cb->args[4] = 0;
288                         fib6_walker_unlink(w);
289                 }
290                 cb->args[2] = 0;
291                 kfree(w);
292         }
293         cb->done = (void *)cb->args[3];
294         cb->args[1] = 3;
295 }
296
297 static int fib6_dump_done(struct netlink_callback *cb)
298 {
299         fib6_dump_end(cb);
300         return cb->done ? cb->done(cb) : 0;
301 }
302
303 static int fib6_dump_table(struct fib6_table *table, struct sk_buff *skb,
304                            struct netlink_callback *cb)
305 {
306         struct fib6_walker *w;
307         int res;
308
309         w = (void *)cb->args[2];
310         w->root = &table->tb6_root;
311
312         if (cb->args[4] == 0) {
313                 w->count = 0;
314                 w->skip = 0;
315
316                 read_lock_bh(&table->tb6_lock);
317                 res = fib6_walk(w);
318                 read_unlock_bh(&table->tb6_lock);
319                 if (res > 0) {
320                         cb->args[4] = 1;
321                         cb->args[5] = w->root->fn_sernum;
322                 }
323         } else {
324                 if (cb->args[5] != w->root->fn_sernum) {
325                         /* Begin at the root if the tree changed */
326                         cb->args[5] = w->root->fn_sernum;
327                         w->state = FWS_INIT;
328                         w->node = w->root;
329                         w->skip = w->count;
330                 } else
331                         w->skip = 0;
332
333                 read_lock_bh(&table->tb6_lock);
334                 res = fib6_walk_continue(w);
335                 read_unlock_bh(&table->tb6_lock);
336                 if (res <= 0) {
337                         fib6_walker_unlink(w);
338                         cb->args[4] = 0;
339                 }
340         }
341
342         return res;
343 }
344
345 static int inet6_dump_fib(struct sk_buff *skb, struct netlink_callback *cb)
346 {
347         struct net *net = sock_net(skb->sk);
348         unsigned int h, s_h;
349         unsigned int e = 0, s_e;
350         struct rt6_rtnl_dump_arg arg;
351         struct fib6_walker *w;
352         struct fib6_table *tb;
353         struct hlist_head *head;
354         int res = 0;
355
356         s_h = cb->args[0];
357         s_e = cb->args[1];
358
359         w = (void *)cb->args[2];
360         if (!w) {
361                 /* New dump:
362                  *
363                  * 1. hook callback destructor.
364                  */
365                 cb->args[3] = (long)cb->done;
366                 cb->done = fib6_dump_done;
367
368                 /*
369                  * 2. allocate and initialize walker.
370                  */
371                 w = kzalloc(sizeof(*w), GFP_ATOMIC);
372                 if (!w)
373                         return -ENOMEM;
374                 w->func = fib6_dump_node;
375                 cb->args[2] = (long)w;
376         }
377
378         arg.skb = skb;
379         arg.cb = cb;
380         arg.net = net;
381         w->args = &arg;
382
383         rcu_read_lock();
384         for (h = s_h; h < FIB6_TABLE_HASHSZ; h++, s_e = 0) {
385                 e = 0;
386                 head = &net->ipv6.fib_table_hash[h];
387                 hlist_for_each_entry_rcu(tb, head, tb6_hlist) {
388                         if (e < s_e)
389                                 goto next;
390                         res = fib6_dump_table(tb, skb, cb);
391                         if (res != 0)
392                                 goto out;
393 next:
394                         e++;
395                 }
396         }
397 out:
398         rcu_read_unlock();
399         cb->args[1] = e;
400         cb->args[0] = h;
401
402         res = res < 0 ? res : skb->len;
403         if (res <= 0)
404                 fib6_dump_end(cb);
405         return res;
406 }
407
408 /*
409  *      Routing Table
410  *
411  *      return the appropriate node for a routing tree "add" operation
412  *      by either creating and inserting or by returning an existing
413  *      node.
414  */
415
416 static struct fib6_node *fib6_add_1(struct fib6_node *root,
417                                      struct in6_addr *addr, int plen,
418                                      int offset, int allow_create,
419                                      int replace_required, int sernum)
420 {
421         struct fib6_node *fn, *in, *ln;
422         struct fib6_node *pn = NULL;
423         struct rt6key *key;
424         int     bit;
425         __be32  dir = 0;
426
427         RT6_TRACE("fib6_add_1\n");
428
429         /* insert node in tree */
430
431         fn = root;
432
433         do {
434                 key = (struct rt6key *)((u8 *)fn->leaf + offset);
435
436                 /*
437                  *      Prefix match
438                  */
439                 if (plen < fn->fn_bit ||
440                     !ipv6_prefix_equal(&key->addr, addr, fn->fn_bit)) {
441                         if (!allow_create) {
442                                 if (replace_required) {
443                                         pr_warn("Can't replace route, no match found\n");
444                                         return ERR_PTR(-ENOENT);
445                                 }
446                                 pr_warn("NLM_F_CREATE should be set when creating new route\n");
447                         }
448                         goto insert_above;
449                 }
450
451                 /*
452                  *      Exact match ?
453                  */
454
455                 if (plen == fn->fn_bit) {
456                         /* clean up an intermediate node */
457                         if (!(fn->fn_flags & RTN_RTINFO)) {
458                                 rt6_release(fn->leaf);
459                                 fn->leaf = NULL;
460                         }
461
462                         fn->fn_sernum = sernum;
463
464                         return fn;
465                 }
466
467                 /*
468                  *      We have more bits to go
469                  */
470
471                 /* Try to walk down on tree. */
472                 fn->fn_sernum = sernum;
473                 dir = addr_bit_set(addr, fn->fn_bit);
474                 pn = fn;
475                 fn = dir ? fn->right : fn->left;
476         } while (fn);
477
478         if (!allow_create) {
479                 /* We should not create new node because
480                  * NLM_F_REPLACE was specified without NLM_F_CREATE
481                  * I assume it is safe to require NLM_F_CREATE when
482                  * REPLACE flag is used! Later we may want to remove the
483                  * check for replace_required, because according
484                  * to netlink specification, NLM_F_CREATE
485                  * MUST be specified if new route is created.
486                  * That would keep IPv6 consistent with IPv4
487                  */
488                 if (replace_required) {
489                         pr_warn("Can't replace route, no match found\n");
490                         return ERR_PTR(-ENOENT);
491                 }
492                 pr_warn("NLM_F_CREATE should be set when creating new route\n");
493         }
494         /*
495          *      We walked to the bottom of tree.
496          *      Create new leaf node without children.
497          */
498
499         ln = node_alloc();
500
501         if (!ln)
502                 return ERR_PTR(-ENOMEM);
503         ln->fn_bit = plen;
504
505         ln->parent = pn;
506         ln->fn_sernum = sernum;
507
508         if (dir)
509                 pn->right = ln;
510         else
511                 pn->left  = ln;
512
513         return ln;
514
515
516 insert_above:
517         /*
518          * split since we don't have a common prefix anymore or
519          * we have a less significant route.
520          * we've to insert an intermediate node on the list
521          * this new node will point to the one we need to create
522          * and the current
523          */
524
525         pn = fn->parent;
526
527         /* find 1st bit in difference between the 2 addrs.
528
529            See comment in __ipv6_addr_diff: bit may be an invalid value,
530            but if it is >= plen, the value is ignored in any case.
531          */
532
533         bit = __ipv6_addr_diff(addr, &key->addr, sizeof(*addr));
534
535         /*
536          *              (intermediate)[in]
537          *                /        \
538          *      (new leaf node)[ln] (old node)[fn]
539          */
540         if (plen > bit) {
541                 in = node_alloc();
542                 ln = node_alloc();
543
544                 if (!in || !ln) {
545                         if (in)
546                                 node_free(in);
547                         if (ln)
548                                 node_free(ln);
549                         return ERR_PTR(-ENOMEM);
550                 }
551
552                 /*
553                  * new intermediate node.
554                  * RTN_RTINFO will
555                  * be off since that an address that chooses one of
556                  * the branches would not match less specific routes
557                  * in the other branch
558                  */
559
560                 in->fn_bit = bit;
561
562                 in->parent = pn;
563                 in->leaf = fn->leaf;
564                 atomic_inc(&in->leaf->rt6i_ref);
565
566                 in->fn_sernum = sernum;
567
568                 /* update parent pointer */
569                 if (dir)
570                         pn->right = in;
571                 else
572                         pn->left  = in;
573
574                 ln->fn_bit = plen;
575
576                 ln->parent = in;
577                 fn->parent = in;
578
579                 ln->fn_sernum = sernum;
580
581                 if (addr_bit_set(addr, bit)) {
582                         in->right = ln;
583                         in->left  = fn;
584                 } else {
585                         in->left  = ln;
586                         in->right = fn;
587                 }
588         } else { /* plen <= bit */
589
590                 /*
591                  *              (new leaf node)[ln]
592                  *                /        \
593                  *           (old node)[fn] NULL
594                  */
595
596                 ln = node_alloc();
597
598                 if (!ln)
599                         return ERR_PTR(-ENOMEM);
600
601                 ln->fn_bit = plen;
602
603                 ln->parent = pn;
604
605                 ln->fn_sernum = sernum;
606
607                 if (dir)
608                         pn->right = ln;
609                 else
610                         pn->left  = ln;
611
612                 if (addr_bit_set(&key->addr, plen))
613                         ln->right = fn;
614                 else
615                         ln->left  = fn;
616
617                 fn->parent = ln;
618         }
619         return ln;
620 }
621
622 static bool rt6_qualify_for_ecmp(struct rt6_info *rt)
623 {
624         return (rt->rt6i_flags & (RTF_GATEWAY|RTF_ADDRCONF|RTF_DYNAMIC)) ==
625                RTF_GATEWAY;
626 }
627
628 static int fib6_commit_metrics(struct dst_entry *dst,
629                                struct nlattr *mx, int mx_len)
630 {
631         struct nlattr *nla;
632         int remaining;
633         u32 *mp;
634
635         if (dst->flags & DST_HOST) {
636                 mp = dst_metrics_write_ptr(dst);
637         } else {
638                 mp = kzalloc(sizeof(u32) * RTAX_MAX, GFP_ATOMIC);
639                 if (!mp)
640                         return -ENOMEM;
641                 dst_init_metrics(dst, mp, 0);
642         }
643
644         nla_for_each_attr(nla, mx, mx_len, remaining) {
645                 int type = nla_type(nla);
646
647                 if (type) {
648                         if (type > RTAX_MAX)
649                                 return -EINVAL;
650
651                         mp[type - 1] = nla_get_u32(nla);
652                 }
653         }
654         return 0;
655 }
656
657 /*
658  *      Insert routing information in a node.
659  */
660
661 static int fib6_add_rt2node(struct fib6_node *fn, struct rt6_info *rt,
662                             struct nl_info *info, struct nlattr *mx, int mx_len)
663 {
664         struct rt6_info *iter = NULL;
665         struct rt6_info **ins;
666         int replace = (info->nlh &&
667                        (info->nlh->nlmsg_flags & NLM_F_REPLACE));
668         int add = (!info->nlh ||
669                    (info->nlh->nlmsg_flags & NLM_F_CREATE));
670         int found = 0;
671         bool rt_can_ecmp = rt6_qualify_for_ecmp(rt);
672         int err;
673
674         ins = &fn->leaf;
675
676         for (iter = fn->leaf; iter; iter = iter->dst.rt6_next) {
677                 /*
678                  *      Search for duplicates
679                  */
680
681                 if (iter->rt6i_metric == rt->rt6i_metric) {
682                         /*
683                          *      Same priority level
684                          */
685                         if (info->nlh &&
686                             (info->nlh->nlmsg_flags & NLM_F_EXCL))
687                                 return -EEXIST;
688                         if (replace) {
689                                 found++;
690                                 break;
691                         }
692
693                         if (iter->dst.dev == rt->dst.dev &&
694                             iter->rt6i_idev == rt->rt6i_idev &&
695                             ipv6_addr_equal(&iter->rt6i_gateway,
696                                             &rt->rt6i_gateway)) {
697                                 if (rt->rt6i_nsiblings)
698                                         rt->rt6i_nsiblings = 0;
699                                 if (!(iter->rt6i_flags & RTF_EXPIRES))
700                                         return -EEXIST;
701                                 if (!(rt->rt6i_flags & RTF_EXPIRES))
702                                         rt6_clean_expires(iter);
703                                 else
704                                         rt6_set_expires(iter, rt->dst.expires);
705                                 return -EEXIST;
706                         }
707                         /* If we have the same destination and the same metric,
708                          * but not the same gateway, then the route we try to
709                          * add is sibling to this route, increment our counter
710                          * of siblings, and later we will add our route to the
711                          * list.
712                          * Only static routes (which don't have flag
713                          * RTF_EXPIRES) are used for ECMPv6.
714                          *
715                          * To avoid long list, we only had siblings if the
716                          * route have a gateway.
717                          */
718                         if (rt_can_ecmp &&
719                             rt6_qualify_for_ecmp(iter))
720                                 rt->rt6i_nsiblings++;
721                 }
722
723                 if (iter->rt6i_metric > rt->rt6i_metric)
724                         break;
725
726                 ins = &iter->dst.rt6_next;
727         }
728
729         /* Reset round-robin state, if necessary */
730         if (ins == &fn->leaf)
731                 fn->rr_ptr = NULL;
732
733         /* Link this route to others same route. */
734         if (rt->rt6i_nsiblings) {
735                 unsigned int rt6i_nsiblings;
736                 struct rt6_info *sibling, *temp_sibling;
737
738                 /* Find the first route that have the same metric */
739                 sibling = fn->leaf;
740                 while (sibling) {
741                         if (sibling->rt6i_metric == rt->rt6i_metric &&
742                             rt6_qualify_for_ecmp(sibling)) {
743                                 list_add_tail(&rt->rt6i_siblings,
744                                               &sibling->rt6i_siblings);
745                                 break;
746                         }
747                         sibling = sibling->dst.rt6_next;
748                 }
749                 /* For each sibling in the list, increment the counter of
750                  * siblings. BUG() if counters does not match, list of siblings
751                  * is broken!
752                  */
753                 rt6i_nsiblings = 0;
754                 list_for_each_entry_safe(sibling, temp_sibling,
755                                          &rt->rt6i_siblings, rt6i_siblings) {
756                         sibling->rt6i_nsiblings++;
757                         BUG_ON(sibling->rt6i_nsiblings != rt->rt6i_nsiblings);
758                         rt6i_nsiblings++;
759                 }
760                 BUG_ON(rt6i_nsiblings != rt->rt6i_nsiblings);
761         }
762
763         /*
764          *      insert node
765          */
766         if (!replace) {
767                 if (!add)
768                         pr_warn("NLM_F_CREATE should be set when creating new route\n");
769
770 add:
771                 if (mx) {
772                         err = fib6_commit_metrics(&rt->dst, mx, mx_len);
773                         if (err)
774                                 return err;
775                 }
776                 rt->dst.rt6_next = iter;
777                 *ins = rt;
778                 rt->rt6i_node = fn;
779                 atomic_inc(&rt->rt6i_ref);
780                 inet6_rt_notify(RTM_NEWROUTE, rt, info);
781                 info->nl_net->ipv6.rt6_stats->fib_rt_entries++;
782
783                 if (!(fn->fn_flags & RTN_RTINFO)) {
784                         info->nl_net->ipv6.rt6_stats->fib_route_nodes++;
785                         fn->fn_flags |= RTN_RTINFO;
786                 }
787
788         } else {
789                 if (!found) {
790                         if (add)
791                                 goto add;
792                         pr_warn("NLM_F_REPLACE set, but no existing node found!\n");
793                         return -ENOENT;
794                 }
795                 if (mx) {
796                         err = fib6_commit_metrics(&rt->dst, mx, mx_len);
797                         if (err)
798                                 return err;
799                 }
800                 *ins = rt;
801                 rt->rt6i_node = fn;
802                 rt->dst.rt6_next = iter->dst.rt6_next;
803                 atomic_inc(&rt->rt6i_ref);
804                 inet6_rt_notify(RTM_NEWROUTE, rt, info);
805                 rt6_release(iter);
806                 if (!(fn->fn_flags & RTN_RTINFO)) {
807                         info->nl_net->ipv6.rt6_stats->fib_route_nodes++;
808                         fn->fn_flags |= RTN_RTINFO;
809                 }
810         }
811
812         return 0;
813 }
814
815 static void fib6_start_gc(struct net *net, struct rt6_info *rt)
816 {
817         if (!timer_pending(&net->ipv6.ip6_fib_timer) &&
818             (rt->rt6i_flags & (RTF_EXPIRES | RTF_CACHE)))
819                 mod_timer(&net->ipv6.ip6_fib_timer,
820                           jiffies + net->ipv6.sysctl.ip6_rt_gc_interval);
821 }
822
823 void fib6_force_start_gc(struct net *net)
824 {
825         if (!timer_pending(&net->ipv6.ip6_fib_timer))
826                 mod_timer(&net->ipv6.ip6_fib_timer,
827                           jiffies + net->ipv6.sysctl.ip6_rt_gc_interval);
828 }
829
830 /*
831  *      Add routing information to the routing tree.
832  *      <destination addr>/<source addr>
833  *      with source addr info in sub-trees
834  */
835
836 int fib6_add(struct fib6_node *root, struct rt6_info *rt, struct nl_info *info,
837              struct nlattr *mx, int mx_len)
838 {
839         struct fib6_node *fn, *pn = NULL;
840         int err = -ENOMEM;
841         int allow_create = 1;
842         int replace_required = 0;
843         int sernum = fib6_new_sernum(info->nl_net);
844
845         if (info->nlh) {
846                 if (!(info->nlh->nlmsg_flags & NLM_F_CREATE))
847                         allow_create = 0;
848                 if (info->nlh->nlmsg_flags & NLM_F_REPLACE)
849                         replace_required = 1;
850         }
851         if (!allow_create && !replace_required)
852                 pr_warn("RTM_NEWROUTE with no NLM_F_CREATE or NLM_F_REPLACE\n");
853
854         fn = fib6_add_1(root, &rt->rt6i_dst.addr, rt->rt6i_dst.plen,
855                         offsetof(struct rt6_info, rt6i_dst), allow_create,
856                         replace_required, sernum);
857         if (IS_ERR(fn)) {
858                 err = PTR_ERR(fn);
859                 fn = NULL;
860                 goto out;
861         }
862
863         pn = fn;
864
865 #ifdef CONFIG_IPV6_SUBTREES
866         if (rt->rt6i_src.plen) {
867                 struct fib6_node *sn;
868
869                 if (!fn->subtree) {
870                         struct fib6_node *sfn;
871
872                         /*
873                          * Create subtree.
874                          *
875                          *              fn[main tree]
876                          *              |
877                          *              sfn[subtree root]
878                          *                 \
879                          *                  sn[new leaf node]
880                          */
881
882                         /* Create subtree root node */
883                         sfn = node_alloc();
884                         if (!sfn)
885                                 goto st_failure;
886
887                         sfn->leaf = info->nl_net->ipv6.ip6_null_entry;
888                         atomic_inc(&info->nl_net->ipv6.ip6_null_entry->rt6i_ref);
889                         sfn->fn_flags = RTN_ROOT;
890                         sfn->fn_sernum = sernum;
891
892                         /* Now add the first leaf node to new subtree */
893
894                         sn = fib6_add_1(sfn, &rt->rt6i_src.addr,
895                                         rt->rt6i_src.plen,
896                                         offsetof(struct rt6_info, rt6i_src),
897                                         allow_create, replace_required, sernum);
898
899                         if (IS_ERR(sn)) {
900                                 /* If it is failed, discard just allocated
901                                    root, and then (in st_failure) stale node
902                                    in main tree.
903                                  */
904                                 node_free(sfn);
905                                 err = PTR_ERR(sn);
906                                 goto st_failure;
907                         }
908
909                         /* Now link new subtree to main tree */
910                         sfn->parent = fn;
911                         fn->subtree = sfn;
912                 } else {
913                         sn = fib6_add_1(fn->subtree, &rt->rt6i_src.addr,
914                                         rt->rt6i_src.plen,
915                                         offsetof(struct rt6_info, rt6i_src),
916                                         allow_create, replace_required, sernum);
917
918                         if (IS_ERR(sn)) {
919                                 err = PTR_ERR(sn);
920                                 goto st_failure;
921                         }
922                 }
923
924                 if (!fn->leaf) {
925                         fn->leaf = rt;
926                         atomic_inc(&rt->rt6i_ref);
927                 }
928                 fn = sn;
929         }
930 #endif
931
932         err = fib6_add_rt2node(fn, rt, info, mx, mx_len);
933         if (!err) {
934                 fib6_start_gc(info->nl_net, rt);
935                 if (!(rt->rt6i_flags & RTF_CACHE))
936                         fib6_prune_clones(info->nl_net, pn);
937         }
938
939 out:
940         if (err) {
941 #ifdef CONFIG_IPV6_SUBTREES
942                 /*
943                  * If fib6_add_1 has cleared the old leaf pointer in the
944                  * super-tree leaf node we have to find a new one for it.
945                  */
946                 if (pn != fn && pn->leaf == rt) {
947                         pn->leaf = NULL;
948                         atomic_dec(&rt->rt6i_ref);
949                 }
950                 if (pn != fn && !pn->leaf && !(pn->fn_flags & RTN_RTINFO)) {
951                         pn->leaf = fib6_find_prefix(info->nl_net, pn);
952 #if RT6_DEBUG >= 2
953                         if (!pn->leaf) {
954                                 WARN_ON(pn->leaf == NULL);
955                                 pn->leaf = info->nl_net->ipv6.ip6_null_entry;
956                         }
957 #endif
958                         atomic_inc(&pn->leaf->rt6i_ref);
959                 }
960 #endif
961                 dst_free(&rt->dst);
962         }
963         return err;
964
965 #ifdef CONFIG_IPV6_SUBTREES
966         /* Subtree creation failed, probably main tree node
967            is orphan. If it is, shoot it.
968          */
969 st_failure:
970         if (fn && !(fn->fn_flags & (RTN_RTINFO|RTN_ROOT)))
971                 fib6_repair_tree(info->nl_net, fn);
972         dst_free(&rt->dst);
973         return err;
974 #endif
975 }
976
977 /*
978  *      Routing tree lookup
979  *
980  */
981
982 struct lookup_args {
983         int                     offset;         /* key offset on rt6_info       */
984         const struct in6_addr   *addr;          /* search key                   */
985 };
986
987 static struct fib6_node *fib6_lookup_1(struct fib6_node *root,
988                                        struct lookup_args *args)
989 {
990         struct fib6_node *fn;
991         __be32 dir;
992
993         if (unlikely(args->offset == 0))
994                 return NULL;
995
996         /*
997          *      Descend on a tree
998          */
999
1000         fn = root;
1001
1002         for (;;) {
1003                 struct fib6_node *next;
1004
1005                 dir = addr_bit_set(args->addr, fn->fn_bit);
1006
1007                 next = dir ? fn->right : fn->left;
1008
1009                 if (next) {
1010                         fn = next;
1011                         continue;
1012                 }
1013                 break;
1014         }
1015
1016         while (fn) {
1017                 if (FIB6_SUBTREE(fn) || fn->fn_flags & RTN_RTINFO) {
1018                         struct rt6key *key;
1019
1020                         key = (struct rt6key *) ((u8 *) fn->leaf +
1021                                                  args->offset);
1022
1023                         if (ipv6_prefix_equal(&key->addr, args->addr, key->plen)) {
1024 #ifdef CONFIG_IPV6_SUBTREES
1025                                 if (fn->subtree) {
1026                                         struct fib6_node *sfn;
1027                                         sfn = fib6_lookup_1(fn->subtree,
1028                                                             args + 1);
1029                                         if (!sfn)
1030                                                 goto backtrack;
1031                                         fn = sfn;
1032                                 }
1033 #endif
1034                                 if (fn->fn_flags & RTN_RTINFO)
1035                                         return fn;
1036                         }
1037                 }
1038 #ifdef CONFIG_IPV6_SUBTREES
1039 backtrack:
1040 #endif
1041                 if (fn->fn_flags & RTN_ROOT)
1042                         break;
1043
1044                 fn = fn->parent;
1045         }
1046
1047         return NULL;
1048 }
1049
1050 struct fib6_node *fib6_lookup(struct fib6_node *root, const struct in6_addr *daddr,
1051                               const struct in6_addr *saddr)
1052 {
1053         struct fib6_node *fn;
1054         struct lookup_args args[] = {
1055                 {
1056                         .offset = offsetof(struct rt6_info, rt6i_dst),
1057                         .addr = daddr,
1058                 },
1059 #ifdef CONFIG_IPV6_SUBTREES
1060                 {
1061                         .offset = offsetof(struct rt6_info, rt6i_src),
1062                         .addr = saddr,
1063                 },
1064 #endif
1065                 {
1066                         .offset = 0,    /* sentinel */
1067                 }
1068         };
1069
1070         fn = fib6_lookup_1(root, daddr ? args : args + 1);
1071         if (!fn || fn->fn_flags & RTN_TL_ROOT)
1072                 fn = root;
1073
1074         return fn;
1075 }
1076
1077 /*
1078  *      Get node with specified destination prefix (and source prefix,
1079  *      if subtrees are used)
1080  */
1081
1082
1083 static struct fib6_node *fib6_locate_1(struct fib6_node *root,
1084                                        const struct in6_addr *addr,
1085                                        int plen, int offset)
1086 {
1087         struct fib6_node *fn;
1088
1089         for (fn = root; fn ; ) {
1090                 struct rt6key *key = (struct rt6key *)((u8 *)fn->leaf + offset);
1091
1092                 /*
1093                  *      Prefix match
1094                  */
1095                 if (plen < fn->fn_bit ||
1096                     !ipv6_prefix_equal(&key->addr, addr, fn->fn_bit))
1097                         return NULL;
1098
1099                 if (plen == fn->fn_bit)
1100                         return fn;
1101
1102                 /*
1103                  *      We have more bits to go
1104                  */
1105                 if (addr_bit_set(addr, fn->fn_bit))
1106                         fn = fn->right;
1107                 else
1108                         fn = fn->left;
1109         }
1110         return NULL;
1111 }
1112
1113 struct fib6_node *fib6_locate(struct fib6_node *root,
1114                               const struct in6_addr *daddr, int dst_len,
1115                               const struct in6_addr *saddr, int src_len)
1116 {
1117         struct fib6_node *fn;
1118
1119         fn = fib6_locate_1(root, daddr, dst_len,
1120                            offsetof(struct rt6_info, rt6i_dst));
1121
1122 #ifdef CONFIG_IPV6_SUBTREES
1123         if (src_len) {
1124                 WARN_ON(saddr == NULL);
1125                 if (fn && fn->subtree)
1126                         fn = fib6_locate_1(fn->subtree, saddr, src_len,
1127                                            offsetof(struct rt6_info, rt6i_src));
1128         }
1129 #endif
1130
1131         if (fn && fn->fn_flags & RTN_RTINFO)
1132                 return fn;
1133
1134         return NULL;
1135 }
1136
1137
1138 /*
1139  *      Deletion
1140  *
1141  */
1142
1143 static struct rt6_info *fib6_find_prefix(struct net *net, struct fib6_node *fn)
1144 {
1145         if (fn->fn_flags & RTN_ROOT)
1146                 return net->ipv6.ip6_null_entry;
1147
1148         while (fn) {
1149                 if (fn->left)
1150                         return fn->left->leaf;
1151                 if (fn->right)
1152                         return fn->right->leaf;
1153
1154                 fn = FIB6_SUBTREE(fn);
1155         }
1156         return NULL;
1157 }
1158
1159 /*
1160  *      Called to trim the tree of intermediate nodes when possible. "fn"
1161  *      is the node we want to try and remove.
1162  */
1163
1164 static struct fib6_node *fib6_repair_tree(struct net *net,
1165                                            struct fib6_node *fn)
1166 {
1167         int children;
1168         int nstate;
1169         struct fib6_node *child, *pn;
1170         struct fib6_walker *w;
1171         int iter = 0;
1172
1173         for (;;) {
1174                 RT6_TRACE("fixing tree: plen=%d iter=%d\n", fn->fn_bit, iter);
1175                 iter++;
1176
1177                 WARN_ON(fn->fn_flags & RTN_RTINFO);
1178                 WARN_ON(fn->fn_flags & RTN_TL_ROOT);
1179                 WARN_ON(fn->leaf != NULL);
1180
1181                 children = 0;
1182                 child = NULL;
1183                 if (fn->right)
1184                         child = fn->right, children |= 1;
1185                 if (fn->left)
1186                         child = fn->left, children |= 2;
1187
1188                 if (children == 3 || FIB6_SUBTREE(fn)
1189 #ifdef CONFIG_IPV6_SUBTREES
1190                     /* Subtree root (i.e. fn) may have one child */
1191                     || (children && fn->fn_flags & RTN_ROOT)
1192 #endif
1193                     ) {
1194                         fn->leaf = fib6_find_prefix(net, fn);
1195 #if RT6_DEBUG >= 2
1196                         if (!fn->leaf) {
1197                                 WARN_ON(!fn->leaf);
1198                                 fn->leaf = net->ipv6.ip6_null_entry;
1199                         }
1200 #endif
1201                         atomic_inc(&fn->leaf->rt6i_ref);
1202                         return fn->parent;
1203                 }
1204
1205                 pn = fn->parent;
1206 #ifdef CONFIG_IPV6_SUBTREES
1207                 if (FIB6_SUBTREE(pn) == fn) {
1208                         WARN_ON(!(fn->fn_flags & RTN_ROOT));
1209                         FIB6_SUBTREE(pn) = NULL;
1210                         nstate = FWS_L;
1211                 } else {
1212                         WARN_ON(fn->fn_flags & RTN_ROOT);
1213 #endif
1214                         if (pn->right == fn)
1215                                 pn->right = child;
1216                         else if (pn->left == fn)
1217                                 pn->left = child;
1218 #if RT6_DEBUG >= 2
1219                         else
1220                                 WARN_ON(1);
1221 #endif
1222                         if (child)
1223                                 child->parent = pn;
1224                         nstate = FWS_R;
1225 #ifdef CONFIG_IPV6_SUBTREES
1226                 }
1227 #endif
1228
1229                 read_lock(&fib6_walker_lock);
1230                 FOR_WALKERS(w) {
1231                         if (!child) {
1232                                 if (w->root == fn) {
1233                                         w->root = w->node = NULL;
1234                                         RT6_TRACE("W %p adjusted by delroot 1\n", w);
1235                                 } else if (w->node == fn) {
1236                                         RT6_TRACE("W %p adjusted by delnode 1, s=%d/%d\n", w, w->state, nstate);
1237                                         w->node = pn;
1238                                         w->state = nstate;
1239                                 }
1240                         } else {
1241                                 if (w->root == fn) {
1242                                         w->root = child;
1243                                         RT6_TRACE("W %p adjusted by delroot 2\n", w);
1244                                 }
1245                                 if (w->node == fn) {
1246                                         w->node = child;
1247                                         if (children&2) {
1248                                                 RT6_TRACE("W %p adjusted by delnode 2, s=%d\n", w, w->state);
1249                                                 w->state = w->state >= FWS_R ? FWS_U : FWS_INIT;
1250                                         } else {
1251                                                 RT6_TRACE("W %p adjusted by delnode 2, s=%d\n", w, w->state);
1252                                                 w->state = w->state >= FWS_C ? FWS_U : FWS_INIT;
1253                                         }
1254                                 }
1255                         }
1256                 }
1257                 read_unlock(&fib6_walker_lock);
1258
1259                 node_free(fn);
1260                 if (pn->fn_flags & RTN_RTINFO || FIB6_SUBTREE(pn))
1261                         return pn;
1262
1263                 rt6_release(pn->leaf);
1264                 pn->leaf = NULL;
1265                 fn = pn;
1266         }
1267 }
1268
1269 static void fib6_del_route(struct fib6_node *fn, struct rt6_info **rtp,
1270                            struct nl_info *info)
1271 {
1272         struct fib6_walker *w;
1273         struct rt6_info *rt = *rtp;
1274         struct net *net = info->nl_net;
1275
1276         RT6_TRACE("fib6_del_route\n");
1277
1278         /* Unlink it */
1279         *rtp = rt->dst.rt6_next;
1280         rt->rt6i_node = NULL;
1281         net->ipv6.rt6_stats->fib_rt_entries--;
1282         net->ipv6.rt6_stats->fib_discarded_routes++;
1283
1284         /* Reset round-robin state, if necessary */
1285         if (fn->rr_ptr == rt)
1286                 fn->rr_ptr = NULL;
1287
1288         /* Remove this entry from other siblings */
1289         if (rt->rt6i_nsiblings) {
1290                 struct rt6_info *sibling, *next_sibling;
1291
1292                 list_for_each_entry_safe(sibling, next_sibling,
1293                                          &rt->rt6i_siblings, rt6i_siblings)
1294                         sibling->rt6i_nsiblings--;
1295                 rt->rt6i_nsiblings = 0;
1296                 list_del_init(&rt->rt6i_siblings);
1297         }
1298
1299         /* Adjust walkers */
1300         read_lock(&fib6_walker_lock);
1301         FOR_WALKERS(w) {
1302                 if (w->state == FWS_C && w->leaf == rt) {
1303                         RT6_TRACE("walker %p adjusted by delroute\n", w);
1304                         w->leaf = rt->dst.rt6_next;
1305                         if (!w->leaf)
1306                                 w->state = FWS_U;
1307                 }
1308         }
1309         read_unlock(&fib6_walker_lock);
1310
1311         rt->dst.rt6_next = NULL;
1312
1313         /* If it was last route, expunge its radix tree node */
1314         if (!fn->leaf) {
1315                 fn->fn_flags &= ~RTN_RTINFO;
1316                 net->ipv6.rt6_stats->fib_route_nodes--;
1317                 fn = fib6_repair_tree(net, fn);
1318         }
1319
1320         if (atomic_read(&rt->rt6i_ref) != 1) {
1321                 /* This route is used as dummy address holder in some split
1322                  * nodes. It is not leaked, but it still holds other resources,
1323                  * which must be released in time. So, scan ascendant nodes
1324                  * and replace dummy references to this route with references
1325                  * to still alive ones.
1326                  */
1327                 while (fn) {
1328                         if (!(fn->fn_flags & RTN_RTINFO) && fn->leaf == rt) {
1329                                 fn->leaf = fib6_find_prefix(net, fn);
1330                                 atomic_inc(&fn->leaf->rt6i_ref);
1331                                 rt6_release(rt);
1332                         }
1333                         fn = fn->parent;
1334                 }
1335                 /* No more references are possible at this point. */
1336                 BUG_ON(atomic_read(&rt->rt6i_ref) != 1);
1337         }
1338
1339         inet6_rt_notify(RTM_DELROUTE, rt, info);
1340         rt6_release(rt);
1341 }
1342
1343 int fib6_del(struct rt6_info *rt, struct nl_info *info)
1344 {
1345         struct net *net = info->nl_net;
1346         struct fib6_node *fn = rt->rt6i_node;
1347         struct rt6_info **rtp;
1348
1349 #if RT6_DEBUG >= 2
1350         if (rt->dst.obsolete > 0) {
1351                 WARN_ON(fn != NULL);
1352                 return -ENOENT;
1353         }
1354 #endif
1355         if (!fn || rt == net->ipv6.ip6_null_entry)
1356                 return -ENOENT;
1357
1358         WARN_ON(!(fn->fn_flags & RTN_RTINFO));
1359
1360         if (!(rt->rt6i_flags & RTF_CACHE)) {
1361                 struct fib6_node *pn = fn;
1362 #ifdef CONFIG_IPV6_SUBTREES
1363                 /* clones of this route might be in another subtree */
1364                 if (rt->rt6i_src.plen) {
1365                         while (!(pn->fn_flags & RTN_ROOT))
1366                                 pn = pn->parent;
1367                         pn = pn->parent;
1368                 }
1369 #endif
1370                 fib6_prune_clones(info->nl_net, pn);
1371         }
1372
1373         /*
1374          *      Walk the leaf entries looking for ourself
1375          */
1376
1377         for (rtp = &fn->leaf; *rtp; rtp = &(*rtp)->dst.rt6_next) {
1378                 if (*rtp == rt) {
1379                         fib6_del_route(fn, rtp, info);
1380                         return 0;
1381                 }
1382         }
1383         return -ENOENT;
1384 }
1385
1386 /*
1387  *      Tree traversal function.
1388  *
1389  *      Certainly, it is not interrupt safe.
1390  *      However, it is internally reenterable wrt itself and fib6_add/fib6_del.
1391  *      It means, that we can modify tree during walking
1392  *      and use this function for garbage collection, clone pruning,
1393  *      cleaning tree when a device goes down etc. etc.
1394  *
1395  *      It guarantees that every node will be traversed,
1396  *      and that it will be traversed only once.
1397  *
1398  *      Callback function w->func may return:
1399  *      0 -> continue walking.
1400  *      positive value -> walking is suspended (used by tree dumps,
1401  *      and probably by gc, if it will be split to several slices)
1402  *      negative value -> terminate walking.
1403  *
1404  *      The function itself returns:
1405  *      0   -> walk is complete.
1406  *      >0  -> walk is incomplete (i.e. suspended)
1407  *      <0  -> walk is terminated by an error.
1408  */
1409
1410 static int fib6_walk_continue(struct fib6_walker *w)
1411 {
1412         struct fib6_node *fn, *pn;
1413
1414         for (;;) {
1415                 fn = w->node;
1416                 if (!fn)
1417                         return 0;
1418
1419                 if (w->prune && fn != w->root &&
1420                     fn->fn_flags & RTN_RTINFO && w->state < FWS_C) {
1421                         w->state = FWS_C;
1422                         w->leaf = fn->leaf;
1423                 }
1424                 switch (w->state) {
1425 #ifdef CONFIG_IPV6_SUBTREES
1426                 case FWS_S:
1427                         if (FIB6_SUBTREE(fn)) {
1428                                 w->node = FIB6_SUBTREE(fn);
1429                                 continue;
1430                         }
1431                         w->state = FWS_L;
1432 #endif
1433                 case FWS_L:
1434                         if (fn->left) {
1435                                 w->node = fn->left;
1436                                 w->state = FWS_INIT;
1437                                 continue;
1438                         }
1439                         w->state = FWS_R;
1440                 case FWS_R:
1441                         if (fn->right) {
1442                                 w->node = fn->right;
1443                                 w->state = FWS_INIT;
1444                                 continue;
1445                         }
1446                         w->state = FWS_C;
1447                         w->leaf = fn->leaf;
1448                 case FWS_C:
1449                         if (w->leaf && fn->fn_flags & RTN_RTINFO) {
1450                                 int err;
1451
1452                                 if (w->skip) {
1453                                         w->skip--;
1454                                         goto skip;
1455                                 }
1456
1457                                 err = w->func(w);
1458                                 if (err)
1459                                         return err;
1460
1461                                 w->count++;
1462                                 continue;
1463                         }
1464 skip:
1465                         w->state = FWS_U;
1466                 case FWS_U:
1467                         if (fn == w->root)
1468                                 return 0;
1469                         pn = fn->parent;
1470                         w->node = pn;
1471 #ifdef CONFIG_IPV6_SUBTREES
1472                         if (FIB6_SUBTREE(pn) == fn) {
1473                                 WARN_ON(!(fn->fn_flags & RTN_ROOT));
1474                                 w->state = FWS_L;
1475                                 continue;
1476                         }
1477 #endif
1478                         if (pn->left == fn) {
1479                                 w->state = FWS_R;
1480                                 continue;
1481                         }
1482                         if (pn->right == fn) {
1483                                 w->state = FWS_C;
1484                                 w->leaf = w->node->leaf;
1485                                 continue;
1486                         }
1487 #if RT6_DEBUG >= 2
1488                         WARN_ON(1);
1489 #endif
1490                 }
1491         }
1492 }
1493
1494 static int fib6_walk(struct fib6_walker *w)
1495 {
1496         int res;
1497
1498         w->state = FWS_INIT;
1499         w->node = w->root;
1500
1501         fib6_walker_link(w);
1502         res = fib6_walk_continue(w);
1503         if (res <= 0)
1504                 fib6_walker_unlink(w);
1505         return res;
1506 }
1507
1508 static int fib6_clean_node(struct fib6_walker *w)
1509 {
1510         int res;
1511         struct rt6_info *rt;
1512         struct fib6_cleaner *c = container_of(w, struct fib6_cleaner, w);
1513         struct nl_info info = {
1514                 .nl_net = c->net,
1515         };
1516
1517         for (rt = w->leaf; rt; rt = rt->dst.rt6_next) {
1518                 res = c->func(rt, c->arg);
1519                 if (res < 0) {
1520                         w->leaf = rt;
1521                         res = fib6_del(rt, &info);
1522                         if (res) {
1523 #if RT6_DEBUG >= 2
1524                                 pr_debug("%s: del failed: rt=%p@%p err=%d\n",
1525                                          __func__, rt, rt->rt6i_node, res);
1526 #endif
1527                                 continue;
1528                         }
1529                         return 0;
1530                 }
1531                 WARN_ON(res != 0);
1532         }
1533         w->leaf = rt;
1534         return 0;
1535 }
1536
1537 /*
1538  *      Convenient frontend to tree walker.
1539  *
1540  *      func is called on each route.
1541  *              It may return -1 -> delete this route.
1542  *                            0  -> continue walking
1543  *
1544  *      prune==1 -> only immediate children of node (certainly,
1545  *      ignoring pure split nodes) will be scanned.
1546  */
1547
1548 static void fib6_clean_tree(struct net *net, struct fib6_node *root,
1549                             int (*func)(struct rt6_info *, void *arg),
1550                             bool prune, void *arg)
1551 {
1552         struct fib6_cleaner c;
1553
1554         c.w.root = root;
1555         c.w.func = fib6_clean_node;
1556         c.w.prune = prune;
1557         c.w.count = 0;
1558         c.w.skip = 0;
1559         c.func = func;
1560         c.arg = arg;
1561         c.net = net;
1562
1563         fib6_walk(&c.w);
1564 }
1565
1566 void fib6_clean_all(struct net *net, int (*func)(struct rt6_info *, void *arg),
1567                     void *arg)
1568 {
1569         struct fib6_table *table;
1570         struct hlist_head *head;
1571         unsigned int h;
1572
1573         rcu_read_lock();
1574         for (h = 0; h < FIB6_TABLE_HASHSZ; h++) {
1575                 head = &net->ipv6.fib_table_hash[h];
1576                 hlist_for_each_entry_rcu(table, head, tb6_hlist) {
1577                         write_lock_bh(&table->tb6_lock);
1578                         fib6_clean_tree(net, &table->tb6_root,
1579                                         func, false, arg);
1580                         write_unlock_bh(&table->tb6_lock);
1581                 }
1582         }
1583         rcu_read_unlock();
1584 }
1585
1586 static int fib6_prune_clone(struct rt6_info *rt, void *arg)
1587 {
1588         if (rt->rt6i_flags & RTF_CACHE) {
1589                 RT6_TRACE("pruning clone %p\n", rt);
1590                 return -1;
1591         }
1592
1593         return 0;
1594 }
1595
1596 static void fib6_prune_clones(struct net *net, struct fib6_node *fn)
1597 {
1598         fib6_clean_tree(net, fn, fib6_prune_clone, true, NULL);
1599 }
1600
1601 static int fib6_update_sernum(struct rt6_info *rt, void *arg)
1602 {
1603         int sernum = *(int *)arg;
1604
1605         if (rt->rt6i_node &&
1606             rt->rt6i_node->fn_sernum != sernum)
1607                 rt->rt6i_node->fn_sernum = sernum;
1608
1609         return 0;
1610 }
1611
1612 static void fib6_flush_trees(struct net *net)
1613 {
1614         int new_sernum = fib6_new_sernum(net);
1615
1616         fib6_clean_all(net, fib6_update_sernum, &new_sernum);
1617 }
1618
1619 /*
1620  *      Garbage collection
1621  */
1622
1623 static struct fib6_gc_args
1624 {
1625         int                     timeout;
1626         int                     more;
1627 } gc_args;
1628
1629 static int fib6_age(struct rt6_info *rt, void *arg)
1630 {
1631         unsigned long now = jiffies;
1632
1633         /*
1634          *      check addrconf expiration here.
1635          *      Routes are expired even if they are in use.
1636          *
1637          *      Also age clones. Note, that clones are aged out
1638          *      only if they are not in use now.
1639          */
1640
1641         if (rt->rt6i_flags & RTF_EXPIRES && rt->dst.expires) {
1642                 if (time_after(now, rt->dst.expires)) {
1643                         RT6_TRACE("expiring %p\n", rt);
1644                         return -1;
1645                 }
1646                 gc_args.more++;
1647         } else if (rt->rt6i_flags & RTF_CACHE) {
1648                 if (atomic_read(&rt->dst.__refcnt) == 0 &&
1649                     time_after_eq(now, rt->dst.lastuse + gc_args.timeout)) {
1650                         RT6_TRACE("aging clone %p\n", rt);
1651                         return -1;
1652                 } else if (rt->rt6i_flags & RTF_GATEWAY) {
1653                         struct neighbour *neigh;
1654                         __u8 neigh_flags = 0;
1655
1656                         neigh = dst_neigh_lookup(&rt->dst, &rt->rt6i_gateway);
1657                         if (neigh) {
1658                                 neigh_flags = neigh->flags;
1659                                 neigh_release(neigh);
1660                         }
1661                         if (!(neigh_flags & NTF_ROUTER)) {
1662                                 RT6_TRACE("purging route %p via non-router but gateway\n",
1663                                           rt);
1664                                 return -1;
1665                         }
1666                 }
1667                 gc_args.more++;
1668         }
1669
1670         return 0;
1671 }
1672
1673 static DEFINE_SPINLOCK(fib6_gc_lock);
1674
1675 void fib6_run_gc(unsigned long expires, struct net *net, bool force)
1676 {
1677         unsigned long now;
1678
1679         if (force) {
1680                 spin_lock_bh(&fib6_gc_lock);
1681         } else if (!spin_trylock_bh(&fib6_gc_lock)) {
1682                 mod_timer(&net->ipv6.ip6_fib_timer, jiffies + HZ);
1683                 return;
1684         }
1685         gc_args.timeout = expires ? (int)expires :
1686                           net->ipv6.sysctl.ip6_rt_gc_interval;
1687
1688         gc_args.more = icmp6_dst_gc();
1689
1690         fib6_clean_all(net, fib6_age, NULL);
1691         now = jiffies;
1692         net->ipv6.ip6_rt_last_gc = now;
1693
1694         if (gc_args.more)
1695                 mod_timer(&net->ipv6.ip6_fib_timer,
1696                           round_jiffies(now
1697                                         + net->ipv6.sysctl.ip6_rt_gc_interval));
1698         else
1699                 del_timer(&net->ipv6.ip6_fib_timer);
1700         spin_unlock_bh(&fib6_gc_lock);
1701 }
1702
1703 static void fib6_gc_timer_cb(unsigned long arg)
1704 {
1705         fib6_run_gc(0, (struct net *)arg, true);
1706 }
1707
1708 static int __net_init fib6_net_init(struct net *net)
1709 {
1710         size_t size = sizeof(struct hlist_head) * FIB6_TABLE_HASHSZ;
1711
1712         setup_timer(&net->ipv6.ip6_fib_timer, fib6_gc_timer_cb, (unsigned long)net);
1713
1714         net->ipv6.rt6_stats = kzalloc(sizeof(*net->ipv6.rt6_stats), GFP_KERNEL);
1715         if (!net->ipv6.rt6_stats)
1716                 goto out_timer;
1717
1718         /* Avoid false sharing : Use at least a full cache line */
1719         size = max_t(size_t, size, L1_CACHE_BYTES);
1720
1721         net->ipv6.fib_table_hash = kzalloc(size, GFP_KERNEL);
1722         if (!net->ipv6.fib_table_hash)
1723                 goto out_rt6_stats;
1724
1725         net->ipv6.fib6_main_tbl = kzalloc(sizeof(*net->ipv6.fib6_main_tbl),
1726                                           GFP_KERNEL);
1727         if (!net->ipv6.fib6_main_tbl)
1728                 goto out_fib_table_hash;
1729
1730         net->ipv6.fib6_main_tbl->tb6_id = RT6_TABLE_MAIN;
1731         net->ipv6.fib6_main_tbl->tb6_root.leaf = net->ipv6.ip6_null_entry;
1732         net->ipv6.fib6_main_tbl->tb6_root.fn_flags =
1733                 RTN_ROOT | RTN_TL_ROOT | RTN_RTINFO;
1734         inet_peer_base_init(&net->ipv6.fib6_main_tbl->tb6_peers);
1735
1736 #ifdef CONFIG_IPV6_MULTIPLE_TABLES
1737         net->ipv6.fib6_local_tbl = kzalloc(sizeof(*net->ipv6.fib6_local_tbl),
1738                                            GFP_KERNEL);
1739         if (!net->ipv6.fib6_local_tbl)
1740                 goto out_fib6_main_tbl;
1741         net->ipv6.fib6_local_tbl->tb6_id = RT6_TABLE_LOCAL;
1742         net->ipv6.fib6_local_tbl->tb6_root.leaf = net->ipv6.ip6_null_entry;
1743         net->ipv6.fib6_local_tbl->tb6_root.fn_flags =
1744                 RTN_ROOT | RTN_TL_ROOT | RTN_RTINFO;
1745         inet_peer_base_init(&net->ipv6.fib6_local_tbl->tb6_peers);
1746 #endif
1747         fib6_tables_init(net);
1748
1749         return 0;
1750
1751 #ifdef CONFIG_IPV6_MULTIPLE_TABLES
1752 out_fib6_main_tbl:
1753         kfree(net->ipv6.fib6_main_tbl);
1754 #endif
1755 out_fib_table_hash:
1756         kfree(net->ipv6.fib_table_hash);
1757 out_rt6_stats:
1758         kfree(net->ipv6.rt6_stats);
1759 out_timer:
1760         return -ENOMEM;
1761 }
1762
1763 static void fib6_net_exit(struct net *net)
1764 {
1765         rt6_ifdown(net, NULL);
1766         del_timer_sync(&net->ipv6.ip6_fib_timer);
1767
1768 #ifdef CONFIG_IPV6_MULTIPLE_TABLES
1769         inetpeer_invalidate_tree(&net->ipv6.fib6_local_tbl->tb6_peers);
1770         kfree(net->ipv6.fib6_local_tbl);
1771 #endif
1772         inetpeer_invalidate_tree(&net->ipv6.fib6_main_tbl->tb6_peers);
1773         kfree(net->ipv6.fib6_main_tbl);
1774         kfree(net->ipv6.fib_table_hash);
1775         kfree(net->ipv6.rt6_stats);
1776 }
1777
1778 static struct pernet_operations fib6_net_ops = {
1779         .init = fib6_net_init,
1780         .exit = fib6_net_exit,
1781 };
1782
1783 int __init fib6_init(void)
1784 {
1785         int ret = -ENOMEM;
1786
1787         fib6_node_kmem = kmem_cache_create("fib6_nodes",
1788                                            sizeof(struct fib6_node),
1789                                            0, SLAB_HWCACHE_ALIGN,
1790                                            NULL);
1791         if (!fib6_node_kmem)
1792                 goto out;
1793
1794         ret = register_pernet_subsys(&fib6_net_ops);
1795         if (ret)
1796                 goto out_kmem_cache_create;
1797
1798         ret = __rtnl_register(PF_INET6, RTM_GETROUTE, NULL, inet6_dump_fib,
1799                               NULL);
1800         if (ret)
1801                 goto out_unregister_subsys;
1802
1803         __fib6_flush_trees = fib6_flush_trees;
1804 out:
1805         return ret;
1806
1807 out_unregister_subsys:
1808         unregister_pernet_subsys(&fib6_net_ops);
1809 out_kmem_cache_create:
1810         kmem_cache_destroy(fib6_node_kmem);
1811         goto out;
1812 }
1813
1814 void fib6_gc_cleanup(void)
1815 {
1816         unregister_pernet_subsys(&fib6_net_ops);
1817         kmem_cache_destroy(fib6_node_kmem);
1818 }
1819
1820 #ifdef CONFIG_PROC_FS
1821
1822 struct ipv6_route_iter {
1823         struct seq_net_private p;
1824         struct fib6_walker w;
1825         loff_t skip;
1826         struct fib6_table *tbl;
1827         int sernum;
1828 };
1829
1830 static int ipv6_route_seq_show(struct seq_file *seq, void *v)
1831 {
1832         struct rt6_info *rt = v;
1833         struct ipv6_route_iter *iter = seq->private;
1834
1835         seq_printf(seq, "%pi6 %02x ", &rt->rt6i_dst.addr, rt->rt6i_dst.plen);
1836
1837 #ifdef CONFIG_IPV6_SUBTREES
1838         seq_printf(seq, "%pi6 %02x ", &rt->rt6i_src.addr, rt->rt6i_src.plen);
1839 #else
1840         seq_puts(seq, "00000000000000000000000000000000 00 ");
1841 #endif
1842         if (rt->rt6i_flags & RTF_GATEWAY)
1843                 seq_printf(seq, "%pi6", &rt->rt6i_gateway);
1844         else
1845                 seq_puts(seq, "00000000000000000000000000000000");
1846
1847         seq_printf(seq, " %08x %08x %08x %08x %8s\n",
1848                    rt->rt6i_metric, atomic_read(&rt->dst.__refcnt),
1849                    rt->dst.__use, rt->rt6i_flags,
1850                    rt->dst.dev ? rt->dst.dev->name : "");
1851         iter->w.leaf = NULL;
1852         return 0;
1853 }
1854
1855 static int ipv6_route_yield(struct fib6_walker *w)
1856 {
1857         struct ipv6_route_iter *iter = w->args;
1858
1859         if (!iter->skip)
1860                 return 1;
1861
1862         do {
1863                 iter->w.leaf = iter->w.leaf->dst.rt6_next;
1864                 iter->skip--;
1865                 if (!iter->skip && iter->w.leaf)
1866                         return 1;
1867         } while (iter->w.leaf);
1868
1869         return 0;
1870 }
1871
1872 static void ipv6_route_seq_setup_walk(struct ipv6_route_iter *iter)
1873 {
1874         memset(&iter->w, 0, sizeof(iter->w));
1875         iter->w.func = ipv6_route_yield;
1876         iter->w.root = &iter->tbl->tb6_root;
1877         iter->w.state = FWS_INIT;
1878         iter->w.node = iter->w.root;
1879         iter->w.args = iter;
1880         iter->sernum = iter->w.root->fn_sernum;
1881         INIT_LIST_HEAD(&iter->w.lh);
1882         fib6_walker_link(&iter->w);
1883 }
1884
1885 static struct fib6_table *ipv6_route_seq_next_table(struct fib6_table *tbl,
1886                                                     struct net *net)
1887 {
1888         unsigned int h;
1889         struct hlist_node *node;
1890
1891         if (tbl) {
1892                 h = (tbl->tb6_id & (FIB6_TABLE_HASHSZ - 1)) + 1;
1893                 node = rcu_dereference_bh(hlist_next_rcu(&tbl->tb6_hlist));
1894         } else {
1895                 h = 0;
1896                 node = NULL;
1897         }
1898
1899         while (!node && h < FIB6_TABLE_HASHSZ) {
1900                 node = rcu_dereference_bh(
1901                         hlist_first_rcu(&net->ipv6.fib_table_hash[h++]));
1902         }
1903         return hlist_entry_safe(node, struct fib6_table, tb6_hlist);
1904 }
1905
1906 static void ipv6_route_check_sernum(struct ipv6_route_iter *iter)
1907 {
1908         if (iter->sernum != iter->w.root->fn_sernum) {
1909                 iter->sernum = iter->w.root->fn_sernum;
1910                 iter->w.state = FWS_INIT;
1911                 iter->w.node = iter->w.root;
1912                 WARN_ON(iter->w.skip);
1913                 iter->w.skip = iter->w.count;
1914         }
1915 }
1916
1917 static void *ipv6_route_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1918 {
1919         int r;
1920         struct rt6_info *n;
1921         struct net *net = seq_file_net(seq);
1922         struct ipv6_route_iter *iter = seq->private;
1923
1924         if (!v)
1925                 goto iter_table;
1926
1927         n = ((struct rt6_info *)v)->dst.rt6_next;
1928         if (n) {
1929                 ++*pos;
1930                 return n;
1931         }
1932
1933 iter_table:
1934         ipv6_route_check_sernum(iter);
1935         read_lock(&iter->tbl->tb6_lock);
1936         r = fib6_walk_continue(&iter->w);
1937         read_unlock(&iter->tbl->tb6_lock);
1938         if (r > 0) {
1939                 if (v)
1940                         ++*pos;
1941                 return iter->w.leaf;
1942         } else if (r < 0) {
1943                 fib6_walker_unlink(&iter->w);
1944                 return NULL;
1945         }
1946         fib6_walker_unlink(&iter->w);
1947
1948         iter->tbl = ipv6_route_seq_next_table(iter->tbl, net);
1949         if (!iter->tbl)
1950                 return NULL;
1951
1952         ipv6_route_seq_setup_walk(iter);
1953         goto iter_table;
1954 }
1955
1956 static void *ipv6_route_seq_start(struct seq_file *seq, loff_t *pos)
1957         __acquires(RCU_BH)
1958 {
1959         struct net *net = seq_file_net(seq);
1960         struct ipv6_route_iter *iter = seq->private;
1961
1962         rcu_read_lock_bh();
1963         iter->tbl = ipv6_route_seq_next_table(NULL, net);
1964         iter->skip = *pos;
1965
1966         if (iter->tbl) {
1967                 ipv6_route_seq_setup_walk(iter);
1968                 return ipv6_route_seq_next(seq, NULL, pos);
1969         } else {
1970                 return NULL;
1971         }
1972 }
1973
1974 static bool ipv6_route_iter_active(struct ipv6_route_iter *iter)
1975 {
1976         struct fib6_walker *w = &iter->w;
1977         return w->node && !(w->state == FWS_U && w->node == w->root);
1978 }
1979
1980 static void ipv6_route_seq_stop(struct seq_file *seq, void *v)
1981         __releases(RCU_BH)
1982 {
1983         struct ipv6_route_iter *iter = seq->private;
1984
1985         if (ipv6_route_iter_active(iter))
1986                 fib6_walker_unlink(&iter->w);
1987
1988         rcu_read_unlock_bh();
1989 }
1990
1991 static const struct seq_operations ipv6_route_seq_ops = {
1992         .start  = ipv6_route_seq_start,
1993         .next   = ipv6_route_seq_next,
1994         .stop   = ipv6_route_seq_stop,
1995         .show   = ipv6_route_seq_show
1996 };
1997
1998 int ipv6_route_open(struct inode *inode, struct file *file)
1999 {
2000         return seq_open_net(inode, file, &ipv6_route_seq_ops,
2001                             sizeof(struct ipv6_route_iter));
2002 }
2003
2004 #endif /* CONFIG_PROC_FS */