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