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