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