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