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