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