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