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