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