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