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