[IPV6] ROUTE: Purge clones on other trees when deleting a route.
[safe/jmp/linux-2.6] / 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  *      $Id: ip6_fib.c,v 1.25 2001/10/31 21:55:55 davem Exp $
9  *
10  *      This program is free software; you can redistribute it and/or
11  *      modify it under the terms of the GNU General Public License
12  *      as published by the Free Software Foundation; either version
13  *      2 of the License, or (at your option) any later version.
14  */
15
16 /*
17  *      Changes:
18  *      Yuji SEKIYA @USAGI:     Support default route on router node;
19  *                              remove ip6_null_entry from the top of
20  *                              routing table.
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
31 #ifdef  CONFIG_PROC_FS
32 #include <linux/proc_fs.h>
33 #endif
34
35 #include <net/ipv6.h>
36 #include <net/ndisc.h>
37 #include <net/addrconf.h>
38
39 #include <net/ip6_fib.h>
40 #include <net/ip6_route.h>
41
42 #define RT6_DEBUG 2
43
44 #if RT6_DEBUG >= 3
45 #define RT6_TRACE(x...) printk(KERN_DEBUG x)
46 #else
47 #define RT6_TRACE(x...) do { ; } while (0)
48 #endif
49
50 struct rt6_statistics   rt6_stats;
51
52 static kmem_cache_t * fib6_node_kmem __read_mostly;
53
54 enum fib_walk_state_t
55 {
56 #ifdef CONFIG_IPV6_SUBTREES
57         FWS_S,
58 #endif
59         FWS_L,
60         FWS_R,
61         FWS_C,
62         FWS_U
63 };
64
65 struct fib6_cleaner_t
66 {
67         struct fib6_walker_t w;
68         int (*func)(struct rt6_info *, void *arg);
69         void *arg;
70 };
71
72 static DEFINE_RWLOCK(fib6_walker_lock);
73
74 #ifdef CONFIG_IPV6_SUBTREES
75 #define FWS_INIT FWS_S
76 #else
77 #define FWS_INIT FWS_L
78 #endif
79
80 static void fib6_prune_clones(struct fib6_node *fn, struct rt6_info *rt);
81 static struct rt6_info * fib6_find_prefix(struct fib6_node *fn);
82 static struct fib6_node * fib6_repair_tree(struct fib6_node *fn);
83 static int fib6_walk(struct fib6_walker_t *w);
84 static int fib6_walk_continue(struct fib6_walker_t *w);
85
86 /*
87  *      A routing update causes an increase of the serial number on the
88  *      affected subtree. This allows for cached routes to be asynchronously
89  *      tested when modifications are made to the destination cache as a
90  *      result of redirects, path MTU changes, etc.
91  */
92
93 static __u32 rt_sernum;
94
95 static DEFINE_TIMER(ip6_fib_timer, fib6_run_gc, 0, 0);
96
97 static struct fib6_walker_t fib6_walker_list = {
98         .prev   = &fib6_walker_list,
99         .next   = &fib6_walker_list, 
100 };
101
102 #define FOR_WALKERS(w) for ((w)=fib6_walker_list.next; (w) != &fib6_walker_list; (w)=(w)->next)
103
104 static inline void fib6_walker_link(struct fib6_walker_t *w)
105 {
106         write_lock_bh(&fib6_walker_lock);
107         w->next = fib6_walker_list.next;
108         w->prev = &fib6_walker_list;
109         w->next->prev = w;
110         w->prev->next = w;
111         write_unlock_bh(&fib6_walker_lock);
112 }
113
114 static inline void fib6_walker_unlink(struct fib6_walker_t *w)
115 {
116         write_lock_bh(&fib6_walker_lock);
117         w->next->prev = w->prev;
118         w->prev->next = w->next;
119         w->prev = w->next = w;
120         write_unlock_bh(&fib6_walker_lock);
121 }
122 static __inline__ u32 fib6_new_sernum(void)
123 {
124         u32 n = ++rt_sernum;
125         if ((__s32)n <= 0)
126                 rt_sernum = n = 1;
127         return n;
128 }
129
130 /*
131  *      Auxiliary address test functions for the radix tree.
132  *
133  *      These assume a 32bit processor (although it will work on 
134  *      64bit processors)
135  */
136
137 /*
138  *      test bit
139  */
140
141 static __inline__ int addr_bit_set(void *token, int fn_bit)
142 {
143         __u32 *addr = token;
144
145         return htonl(1 << ((~fn_bit)&0x1F)) & addr[fn_bit>>5];
146 }
147
148 static __inline__ struct fib6_node * node_alloc(void)
149 {
150         struct fib6_node *fn;
151
152         if ((fn = kmem_cache_alloc(fib6_node_kmem, SLAB_ATOMIC)) != NULL)
153                 memset(fn, 0, sizeof(struct fib6_node));
154
155         return fn;
156 }
157
158 static __inline__ void node_free(struct fib6_node * fn)
159 {
160         kmem_cache_free(fib6_node_kmem, fn);
161 }
162
163 static __inline__ void rt6_release(struct rt6_info *rt)
164 {
165         if (atomic_dec_and_test(&rt->rt6i_ref))
166                 dst_free(&rt->u.dst);
167 }
168
169 static struct fib6_table fib6_main_tbl = {
170         .tb6_id         = RT6_TABLE_MAIN,
171         .tb6_lock       = RW_LOCK_UNLOCKED,
172         .tb6_root       = {
173                 .leaf           = &ip6_null_entry,
174                 .fn_flags       = RTN_ROOT | RTN_TL_ROOT | RTN_RTINFO,
175         },
176 };
177
178 #ifdef CONFIG_IPV6_MULTIPLE_TABLES
179 #define FIB_TABLE_HASHSZ 256
180 #else
181 #define FIB_TABLE_HASHSZ 1
182 #endif
183 static struct hlist_head fib_table_hash[FIB_TABLE_HASHSZ];
184
185 static void fib6_link_table(struct fib6_table *tb)
186 {
187         unsigned int h;
188
189         h = tb->tb6_id & (FIB_TABLE_HASHSZ - 1);
190
191         /*
192          * No protection necessary, this is the only list mutatation
193          * operation, tables never disappear once they exist.
194          */
195         hlist_add_head_rcu(&tb->tb6_hlist, &fib_table_hash[h]);
196 }
197
198 #ifdef CONFIG_IPV6_MULTIPLE_TABLES
199 static struct fib6_table fib6_local_tbl = {
200         .tb6_id         = RT6_TABLE_LOCAL,
201         .tb6_lock       = RW_LOCK_UNLOCKED,
202         .tb6_root       = {
203                 .leaf           = &ip6_null_entry,
204                 .fn_flags       = RTN_ROOT | RTN_TL_ROOT | RTN_RTINFO,
205         },
206 };
207
208 static struct fib6_table *fib6_alloc_table(u32 id)
209 {
210         struct fib6_table *table;
211
212         table = kzalloc(sizeof(*table), GFP_ATOMIC);
213         if (table != NULL) {
214                 table->tb6_id = id;
215                 table->tb6_lock = RW_LOCK_UNLOCKED;
216                 table->tb6_root.leaf = &ip6_null_entry;
217                 table->tb6_root.fn_flags = RTN_ROOT | RTN_TL_ROOT | RTN_RTINFO;
218         }
219
220         return table;
221 }
222
223 struct fib6_table *fib6_new_table(u32 id)
224 {
225         struct fib6_table *tb;
226
227         if (id == 0)
228                 id = RT6_TABLE_MAIN;
229         tb = fib6_get_table(id);
230         if (tb)
231                 return tb;
232
233         tb = fib6_alloc_table(id);
234         if (tb != NULL)
235                 fib6_link_table(tb);
236
237         return tb;
238 }
239
240 struct fib6_table *fib6_get_table(u32 id)
241 {
242         struct fib6_table *tb;
243         struct hlist_node *node;
244         unsigned int h;
245
246         if (id == 0)
247                 id = RT6_TABLE_MAIN;
248         h = id & (FIB_TABLE_HASHSZ - 1);
249         rcu_read_lock();
250         hlist_for_each_entry_rcu(tb, node, &fib_table_hash[h], tb6_hlist) {
251                 if (tb->tb6_id == id) {
252                         rcu_read_unlock();
253                         return tb;
254                 }
255         }
256         rcu_read_unlock();
257
258         return NULL;
259 }
260
261 static void __init fib6_tables_init(void)
262 {
263         fib6_link_table(&fib6_main_tbl);
264         fib6_link_table(&fib6_local_tbl);
265 }
266
267 #else
268
269 struct fib6_table *fib6_new_table(u32 id)
270 {
271         return fib6_get_table(id);
272 }
273
274 struct fib6_table *fib6_get_table(u32 id)
275 {
276         return &fib6_main_tbl;
277 }
278
279 struct dst_entry *fib6_rule_lookup(struct flowi *fl, int flags,
280                                    pol_lookup_t lookup)
281 {
282         return (struct dst_entry *) lookup(&fib6_main_tbl, fl, flags);
283 }
284
285 static void __init fib6_tables_init(void)
286 {
287         fib6_link_table(&fib6_main_tbl);
288 }
289
290 #endif
291
292 static int fib6_dump_node(struct fib6_walker_t *w)
293 {
294         int res;
295         struct rt6_info *rt;
296
297         for (rt = w->leaf; rt; rt = rt->u.next) {
298                 res = rt6_dump_route(rt, w->args);
299                 if (res < 0) {
300                         /* Frame is full, suspend walking */
301                         w->leaf = rt;
302                         return 1;
303                 }
304                 BUG_TRAP(res!=0);
305         }
306         w->leaf = NULL;
307         return 0;
308 }
309
310 static void fib6_dump_end(struct netlink_callback *cb)
311 {
312         struct fib6_walker_t *w = (void*)cb->args[2];
313
314         if (w) {
315                 cb->args[2] = 0;
316                 kfree(w);
317         }
318         cb->done = (void*)cb->args[3];
319         cb->args[1] = 3;
320 }
321
322 static int fib6_dump_done(struct netlink_callback *cb)
323 {
324         fib6_dump_end(cb);
325         return cb->done ? cb->done(cb) : 0;
326 }
327
328 static int fib6_dump_table(struct fib6_table *table, struct sk_buff *skb,
329                            struct netlink_callback *cb)
330 {
331         struct fib6_walker_t *w;
332         int res;
333
334         w = (void *)cb->args[2];
335         w->root = &table->tb6_root;
336
337         if (cb->args[4] == 0) {
338                 read_lock_bh(&table->tb6_lock);
339                 res = fib6_walk(w);
340                 read_unlock_bh(&table->tb6_lock);
341                 if (res > 0)
342                         cb->args[4] = 1;
343         } else {
344                 read_lock_bh(&table->tb6_lock);
345                 res = fib6_walk_continue(w);
346                 read_unlock_bh(&table->tb6_lock);
347                 if (res != 0) {
348                         if (res < 0)
349                                 fib6_walker_unlink(w);
350                         goto end;
351                 }
352                 fib6_walker_unlink(w);
353                 cb->args[4] = 0;
354         }
355 end:
356         return res;
357 }
358
359 int inet6_dump_fib(struct sk_buff *skb, struct netlink_callback *cb)
360 {
361         unsigned int h, s_h;
362         unsigned int e = 0, s_e;
363         struct rt6_rtnl_dump_arg arg;
364         struct fib6_walker_t *w;
365         struct fib6_table *tb;
366         struct hlist_node *node;
367         int res = 0;
368
369         s_h = cb->args[0];
370         s_e = cb->args[1];
371
372         w = (void *)cb->args[2];
373         if (w == NULL) {
374                 /* New dump:
375                  *
376                  * 1. hook callback destructor.
377                  */
378                 cb->args[3] = (long)cb->done;
379                 cb->done = fib6_dump_done;
380
381                 /*
382                  * 2. allocate and initialize walker.
383                  */
384                 w = kzalloc(sizeof(*w), GFP_ATOMIC);
385                 if (w == NULL)
386                         return -ENOMEM;
387                 w->func = fib6_dump_node;
388                 cb->args[2] = (long)w;
389         }
390
391         arg.skb = skb;
392         arg.cb = cb;
393         w->args = &arg;
394
395         for (h = s_h; h < FIB_TABLE_HASHSZ; h++, s_e = 0) {
396                 e = 0;
397                 hlist_for_each_entry(tb, node, &fib_table_hash[h], tb6_hlist) {
398                         if (e < s_e)
399                                 goto next;
400                         res = fib6_dump_table(tb, skb, cb);
401                         if (res != 0)
402                                 goto out;
403 next:
404                         e++;
405                 }
406         }
407 out:
408         cb->args[1] = e;
409         cb->args[0] = h;
410
411         res = res < 0 ? res : skb->len;
412         if (res <= 0)
413                 fib6_dump_end(cb);
414         return res;
415 }
416
417 /*
418  *      Routing Table
419  *
420  *      return the appropriate node for a routing tree "add" operation
421  *      by either creating and inserting or by returning an existing
422  *      node.
423  */
424
425 static struct fib6_node * fib6_add_1(struct fib6_node *root, void *addr,
426                                      int addrlen, int plen,
427                                      int offset)
428 {
429         struct fib6_node *fn, *in, *ln;
430         struct fib6_node *pn = NULL;
431         struct rt6key *key;
432         int     bit;
433         int     dir = 0;
434         __u32   sernum = fib6_new_sernum();
435
436         RT6_TRACE("fib6_add_1\n");
437
438         /* insert node in tree */
439
440         fn = root;
441
442         do {
443                 key = (struct rt6key *)((u8 *)fn->leaf + offset);
444
445                 /*
446                  *      Prefix match
447                  */
448                 if (plen < fn->fn_bit ||
449                     !ipv6_prefix_equal(&key->addr, addr, fn->fn_bit))
450                         goto insert_above;
451                 
452                 /*
453                  *      Exact match ?
454                  */
455                          
456                 if (plen == fn->fn_bit) {
457                         /* clean up an intermediate node */
458                         if ((fn->fn_flags & RTN_RTINFO) == 0) {
459                                 rt6_release(fn->leaf);
460                                 fn->leaf = NULL;
461                         }
462                         
463                         fn->fn_sernum = sernum;
464                                 
465                         return fn;
466                 }
467
468                 /*
469                  *      We have more bits to go
470                  */
471                          
472                 /* Try to walk down on tree. */
473                 fn->fn_sernum = sernum;
474                 dir = addr_bit_set(addr, fn->fn_bit);
475                 pn = fn;
476                 fn = dir ? fn->right: fn->left;
477         } while (fn);
478
479         /*
480          *      We walked to the bottom of tree.
481          *      Create new leaf node without children.
482          */
483
484         ln = node_alloc();
485
486         if (ln == NULL)
487                 return NULL;
488         ln->fn_bit = plen;
489                         
490         ln->parent = pn;
491         ln->fn_sernum = sernum;
492
493         if (dir)
494                 pn->right = ln;
495         else
496                 pn->left  = ln;
497
498         return ln;
499
500
501 insert_above:
502         /*
503          * split since we don't have a common prefix anymore or 
504          * we have a less significant route.
505          * we've to insert an intermediate node on the list
506          * this new node will point to the one we need to create
507          * and the current
508          */
509
510         pn = fn->parent;
511
512         /* find 1st bit in difference between the 2 addrs.
513
514            See comment in __ipv6_addr_diff: bit may be an invalid value,
515            but if it is >= plen, the value is ignored in any case.
516          */
517         
518         bit = __ipv6_addr_diff(addr, &key->addr, addrlen);
519
520         /* 
521          *              (intermediate)[in]      
522          *                /        \
523          *      (new leaf node)[ln] (old node)[fn]
524          */
525         if (plen > bit) {
526                 in = node_alloc();
527                 ln = node_alloc();
528                 
529                 if (in == NULL || ln == NULL) {
530                         if (in)
531                                 node_free(in);
532                         if (ln)
533                                 node_free(ln);
534                         return NULL;
535                 }
536
537                 /* 
538                  * new intermediate node. 
539                  * RTN_RTINFO will
540                  * be off since that an address that chooses one of
541                  * the branches would not match less specific routes
542                  * in the other branch
543                  */
544
545                 in->fn_bit = bit;
546
547                 in->parent = pn;
548                 in->leaf = fn->leaf;
549                 atomic_inc(&in->leaf->rt6i_ref);
550
551                 in->fn_sernum = sernum;
552
553                 /* update parent pointer */
554                 if (dir)
555                         pn->right = in;
556                 else
557                         pn->left  = in;
558
559                 ln->fn_bit = plen;
560
561                 ln->parent = in;
562                 fn->parent = in;
563
564                 ln->fn_sernum = sernum;
565
566                 if (addr_bit_set(addr, bit)) {
567                         in->right = ln;
568                         in->left  = fn;
569                 } else {
570                         in->left  = ln;
571                         in->right = fn;
572                 }
573         } else { /* plen <= bit */
574
575                 /* 
576                  *              (new leaf node)[ln]
577                  *                /        \
578                  *           (old node)[fn] NULL
579                  */
580
581                 ln = node_alloc();
582
583                 if (ln == NULL)
584                         return NULL;
585
586                 ln->fn_bit = plen;
587
588                 ln->parent = pn;
589
590                 ln->fn_sernum = sernum;
591                 
592                 if (dir)
593                         pn->right = ln;
594                 else
595                         pn->left  = ln;
596
597                 if (addr_bit_set(&key->addr, plen))
598                         ln->right = fn;
599                 else
600                         ln->left  = fn;
601
602                 fn->parent = ln;
603         }
604         return ln;
605 }
606
607 /*
608  *      Insert routing information in a node.
609  */
610
611 static int fib6_add_rt2node(struct fib6_node *fn, struct rt6_info *rt,
612                             struct nl_info *info)
613 {
614         struct rt6_info *iter = NULL;
615         struct rt6_info **ins;
616
617         ins = &fn->leaf;
618
619         if (fn->fn_flags&RTN_TL_ROOT &&
620             fn->leaf == &ip6_null_entry &&
621             !(rt->rt6i_flags & (RTF_DEFAULT | RTF_ADDRCONF)) ){
622                 fn->leaf = rt;
623                 rt->u.next = NULL;
624                 goto out;
625         }
626
627         for (iter = fn->leaf; iter; iter=iter->u.next) {
628                 /*
629                  *      Search for duplicates
630                  */
631
632                 if (iter->rt6i_metric == rt->rt6i_metric) {
633                         /*
634                          *      Same priority level
635                          */
636
637                         if (iter->rt6i_dev == rt->rt6i_dev &&
638                             iter->rt6i_idev == rt->rt6i_idev &&
639                             ipv6_addr_equal(&iter->rt6i_gateway,
640                                             &rt->rt6i_gateway)) {
641                                 if (!(iter->rt6i_flags&RTF_EXPIRES))
642                                         return -EEXIST;
643                                 iter->rt6i_expires = rt->rt6i_expires;
644                                 if (!(rt->rt6i_flags&RTF_EXPIRES)) {
645                                         iter->rt6i_flags &= ~RTF_EXPIRES;
646                                         iter->rt6i_expires = 0;
647                                 }
648                                 return -EEXIST;
649                         }
650                 }
651
652                 if (iter->rt6i_metric > rt->rt6i_metric)
653                         break;
654
655                 ins = &iter->u.next;
656         }
657
658         /*
659          *      insert node
660          */
661
662 out:
663         rt->u.next = iter;
664         *ins = rt;
665         rt->rt6i_node = fn;
666         atomic_inc(&rt->rt6i_ref);
667         inet6_rt_notify(RTM_NEWROUTE, rt, info);
668         rt6_stats.fib_rt_entries++;
669
670         if ((fn->fn_flags & RTN_RTINFO) == 0) {
671                 rt6_stats.fib_route_nodes++;
672                 fn->fn_flags |= RTN_RTINFO;
673         }
674
675         return 0;
676 }
677
678 static __inline__ void fib6_start_gc(struct rt6_info *rt)
679 {
680         if (ip6_fib_timer.expires == 0 &&
681             (rt->rt6i_flags & (RTF_EXPIRES|RTF_CACHE)))
682                 mod_timer(&ip6_fib_timer, jiffies + ip6_rt_gc_interval);
683 }
684
685 void fib6_force_start_gc(void)
686 {
687         if (ip6_fib_timer.expires == 0)
688                 mod_timer(&ip6_fib_timer, jiffies + ip6_rt_gc_interval);
689 }
690
691 /*
692  *      Add routing information to the routing tree.
693  *      <destination addr>/<source addr>
694  *      with source addr info in sub-trees
695  */
696
697 int fib6_add(struct fib6_node *root, struct rt6_info *rt, struct nl_info *info)
698 {
699         struct fib6_node *fn, *pn = NULL;
700         int err = -ENOMEM;
701
702         fn = fib6_add_1(root, &rt->rt6i_dst.addr, sizeof(struct in6_addr),
703                         rt->rt6i_dst.plen, offsetof(struct rt6_info, rt6i_dst));
704
705         if (fn == NULL)
706                 goto out;
707
708         pn = fn;
709
710 #ifdef CONFIG_IPV6_SUBTREES
711         if (rt->rt6i_src.plen) {
712                 struct fib6_node *sn;
713
714                 if (fn->subtree == NULL) {
715                         struct fib6_node *sfn;
716
717                         /*
718                          * Create subtree.
719                          *
720                          *              fn[main tree]
721                          *              |
722                          *              sfn[subtree root]
723                          *                 \
724                          *                  sn[new leaf node]
725                          */
726
727                         /* Create subtree root node */
728                         sfn = node_alloc();
729                         if (sfn == NULL)
730                                 goto st_failure;
731
732                         sfn->leaf = &ip6_null_entry;
733                         atomic_inc(&ip6_null_entry.rt6i_ref);
734                         sfn->fn_flags = RTN_ROOT;
735                         sfn->fn_sernum = fib6_new_sernum();
736
737                         /* Now add the first leaf node to new subtree */
738
739                         sn = fib6_add_1(sfn, &rt->rt6i_src.addr,
740                                         sizeof(struct in6_addr), rt->rt6i_src.plen,
741                                         offsetof(struct rt6_info, rt6i_src));
742
743                         if (sn == NULL) {
744                                 /* If it is failed, discard just allocated
745                                    root, and then (in st_failure) stale node
746                                    in main tree.
747                                  */
748                                 node_free(sfn);
749                                 goto st_failure;
750                         }
751
752                         /* Now link new subtree to main tree */
753                         sfn->parent = fn;
754                         fn->subtree = sfn;
755                 } else {
756                         sn = fib6_add_1(fn->subtree, &rt->rt6i_src.addr,
757                                         sizeof(struct in6_addr), rt->rt6i_src.plen,
758                                         offsetof(struct rt6_info, rt6i_src));
759
760                         if (sn == NULL)
761                                 goto st_failure;
762                 }
763
764                 if (fn->leaf == NULL) {
765                         fn->leaf = rt;
766                         atomic_inc(&rt->rt6i_ref);
767                 }
768                 fn = sn;
769         }
770 #endif
771
772         err = fib6_add_rt2node(fn, rt, info);
773
774         if (err == 0) {
775                 fib6_start_gc(rt);
776                 if (!(rt->rt6i_flags&RTF_CACHE))
777                         fib6_prune_clones(pn, rt);
778         }
779
780 out:
781         if (err) {
782 #ifdef CONFIG_IPV6_SUBTREES
783                 /*
784                  * If fib6_add_1 has cleared the old leaf pointer in the
785                  * super-tree leaf node we have to find a new one for it.
786                  */
787                 if (pn != fn && !pn->leaf && !(pn->fn_flags & RTN_RTINFO)) {
788                         pn->leaf = fib6_find_prefix(pn);
789 #if RT6_DEBUG >= 2
790                         if (!pn->leaf) {
791                                 BUG_TRAP(pn->leaf != NULL);
792                                 pn->leaf = &ip6_null_entry;
793                         }
794 #endif
795                         atomic_inc(&pn->leaf->rt6i_ref);
796                 }
797 #endif
798                 dst_free(&rt->u.dst);
799         }
800         return err;
801
802 #ifdef CONFIG_IPV6_SUBTREES
803         /* Subtree creation failed, probably main tree node
804            is orphan. If it is, shoot it.
805          */
806 st_failure:
807         if (fn && !(fn->fn_flags & (RTN_RTINFO|RTN_ROOT)))
808                 fib6_repair_tree(fn);
809         dst_free(&rt->u.dst);
810         return err;
811 #endif
812 }
813
814 /*
815  *      Routing tree lookup
816  *
817  */
818
819 struct lookup_args {
820         int             offset;         /* key offset on rt6_info       */
821         struct in6_addr *addr;          /* search key                   */
822 };
823
824 static struct fib6_node * fib6_lookup_1(struct fib6_node *root,
825                                         struct lookup_args *args)
826 {
827         struct fib6_node *fn;
828         int dir;
829
830         if (unlikely(args->offset == 0))
831                 return NULL;
832
833         /*
834          *      Descend on a tree
835          */
836
837         fn = root;
838
839         for (;;) {
840                 struct fib6_node *next;
841
842                 dir = addr_bit_set(args->addr, fn->fn_bit);
843
844                 next = dir ? fn->right : fn->left;
845
846                 if (next) {
847                         fn = next;
848                         continue;
849                 }
850
851                 break;
852         }
853
854         while(fn) {
855                 if (FIB6_SUBTREE(fn) || fn->fn_flags & RTN_RTINFO) {
856                         struct rt6key *key;
857
858                         key = (struct rt6key *) ((u8 *) fn->leaf +
859                                                  args->offset);
860
861                         if (ipv6_prefix_equal(&key->addr, args->addr, key->plen)) {
862 #ifdef CONFIG_IPV6_SUBTREES
863                                 if (fn->subtree)
864                                         fn = fib6_lookup_1(fn->subtree, args + 1);
865 #endif
866                                 if (!fn || fn->fn_flags & RTN_RTINFO)
867                                         return fn;
868                         }
869                 }
870
871                 if (fn->fn_flags & RTN_ROOT)
872                         break;
873
874                 fn = fn->parent;
875         }
876
877         return NULL;
878 }
879
880 struct fib6_node * fib6_lookup(struct fib6_node *root, struct in6_addr *daddr,
881                                struct in6_addr *saddr)
882 {
883         struct fib6_node *fn;
884         struct lookup_args args[] = {
885                 {
886                         .offset = offsetof(struct rt6_info, rt6i_dst),
887                         .addr = daddr,
888                 },
889 #ifdef CONFIG_IPV6_SUBTREES
890                 {
891                         .offset = offsetof(struct rt6_info, rt6i_src),
892                         .addr = saddr,
893                 },
894 #endif
895                 {
896                         .offset = 0,    /* sentinel */
897                 }
898         };
899
900         fn = fib6_lookup_1(root, daddr ? args : args + 1);
901
902         if (fn == NULL || fn->fn_flags & RTN_TL_ROOT)
903                 fn = root;
904
905         return fn;
906 }
907
908 /*
909  *      Get node with specified destination prefix (and source prefix,
910  *      if subtrees are used)
911  */
912
913
914 static struct fib6_node * fib6_locate_1(struct fib6_node *root,
915                                         struct in6_addr *addr,
916                                         int plen, int offset)
917 {
918         struct fib6_node *fn;
919
920         for (fn = root; fn ; ) {
921                 struct rt6key *key = (struct rt6key *)((u8 *)fn->leaf + offset);
922
923                 /*
924                  *      Prefix match
925                  */
926                 if (plen < fn->fn_bit ||
927                     !ipv6_prefix_equal(&key->addr, addr, fn->fn_bit))
928                         return NULL;
929
930                 if (plen == fn->fn_bit)
931                         return fn;
932
933                 /*
934                  *      We have more bits to go
935                  */
936                 if (addr_bit_set(addr, fn->fn_bit))
937                         fn = fn->right;
938                 else
939                         fn = fn->left;
940         }
941         return NULL;
942 }
943
944 struct fib6_node * fib6_locate(struct fib6_node *root,
945                                struct in6_addr *daddr, int dst_len,
946                                struct in6_addr *saddr, int src_len)
947 {
948         struct fib6_node *fn;
949
950         fn = fib6_locate_1(root, daddr, dst_len,
951                            offsetof(struct rt6_info, rt6i_dst));
952
953 #ifdef CONFIG_IPV6_SUBTREES
954         if (src_len) {
955                 BUG_TRAP(saddr!=NULL);
956                 if (fn && fn->subtree)
957                         fn = fib6_locate_1(fn->subtree, saddr, src_len,
958                                            offsetof(struct rt6_info, rt6i_src));
959         }
960 #endif
961
962         if (fn && fn->fn_flags&RTN_RTINFO)
963                 return fn;
964
965         return NULL;
966 }
967
968
969 /*
970  *      Deletion
971  *
972  */
973
974 static struct rt6_info * fib6_find_prefix(struct fib6_node *fn)
975 {
976         if (fn->fn_flags&RTN_ROOT)
977                 return &ip6_null_entry;
978
979         while(fn) {
980                 if(fn->left)
981                         return fn->left->leaf;
982
983                 if(fn->right)
984                         return fn->right->leaf;
985
986                 fn = FIB6_SUBTREE(fn);
987         }
988         return NULL;
989 }
990
991 /*
992  *      Called to trim the tree of intermediate nodes when possible. "fn"
993  *      is the node we want to try and remove.
994  */
995
996 static struct fib6_node * fib6_repair_tree(struct fib6_node *fn)
997 {
998         int children;
999         int nstate;
1000         struct fib6_node *child, *pn;
1001         struct fib6_walker_t *w;
1002         int iter = 0;
1003
1004         for (;;) {
1005                 RT6_TRACE("fixing tree: plen=%d iter=%d\n", fn->fn_bit, iter);
1006                 iter++;
1007
1008                 BUG_TRAP(!(fn->fn_flags&RTN_RTINFO));
1009                 BUG_TRAP(!(fn->fn_flags&RTN_TL_ROOT));
1010                 BUG_TRAP(fn->leaf==NULL);
1011
1012                 children = 0;
1013                 child = NULL;
1014                 if (fn->right) child = fn->right, children |= 1;
1015                 if (fn->left) child = fn->left, children |= 2;
1016
1017                 if (children == 3 || FIB6_SUBTREE(fn)
1018 #ifdef CONFIG_IPV6_SUBTREES
1019                     /* Subtree root (i.e. fn) may have one child */
1020                     || (children && fn->fn_flags&RTN_ROOT)
1021 #endif
1022                     ) {
1023                         fn->leaf = fib6_find_prefix(fn);
1024 #if RT6_DEBUG >= 2
1025                         if (fn->leaf==NULL) {
1026                                 BUG_TRAP(fn->leaf);
1027                                 fn->leaf = &ip6_null_entry;
1028                         }
1029 #endif
1030                         atomic_inc(&fn->leaf->rt6i_ref);
1031                         return fn->parent;
1032                 }
1033
1034                 pn = fn->parent;
1035 #ifdef CONFIG_IPV6_SUBTREES
1036                 if (FIB6_SUBTREE(pn) == fn) {
1037                         BUG_TRAP(fn->fn_flags&RTN_ROOT);
1038                         FIB6_SUBTREE(pn) = NULL;
1039                         nstate = FWS_L;
1040                 } else {
1041                         BUG_TRAP(!(fn->fn_flags&RTN_ROOT));
1042 #endif
1043                         if (pn->right == fn) pn->right = child;
1044                         else if (pn->left == fn) pn->left = child;
1045 #if RT6_DEBUG >= 2
1046                         else BUG_TRAP(0);
1047 #endif
1048                         if (child)
1049                                 child->parent = pn;
1050                         nstate = FWS_R;
1051 #ifdef CONFIG_IPV6_SUBTREES
1052                 }
1053 #endif
1054
1055                 read_lock(&fib6_walker_lock);
1056                 FOR_WALKERS(w) {
1057                         if (child == NULL) {
1058                                 if (w->root == fn) {
1059                                         w->root = w->node = NULL;
1060                                         RT6_TRACE("W %p adjusted by delroot 1\n", w);
1061                                 } else if (w->node == fn) {
1062                                         RT6_TRACE("W %p adjusted by delnode 1, s=%d/%d\n", w, w->state, nstate);
1063                                         w->node = pn;
1064                                         w->state = nstate;
1065                                 }
1066                         } else {
1067                                 if (w->root == fn) {
1068                                         w->root = child;
1069                                         RT6_TRACE("W %p adjusted by delroot 2\n", w);
1070                                 }
1071                                 if (w->node == fn) {
1072                                         w->node = child;
1073                                         if (children&2) {
1074                                                 RT6_TRACE("W %p adjusted by delnode 2, s=%d\n", w, w->state);
1075                                                 w->state = w->state>=FWS_R ? FWS_U : FWS_INIT;
1076                                         } else {
1077                                                 RT6_TRACE("W %p adjusted by delnode 2, s=%d\n", w, w->state);
1078                                                 w->state = w->state>=FWS_C ? FWS_U : FWS_INIT;
1079                                         }
1080                                 }
1081                         }
1082                 }
1083                 read_unlock(&fib6_walker_lock);
1084
1085                 node_free(fn);
1086                 if (pn->fn_flags&RTN_RTINFO || FIB6_SUBTREE(pn))
1087                         return pn;
1088
1089                 rt6_release(pn->leaf);
1090                 pn->leaf = NULL;
1091                 fn = pn;
1092         }
1093 }
1094
1095 static void fib6_del_route(struct fib6_node *fn, struct rt6_info **rtp,
1096                            struct nl_info *info)
1097 {
1098         struct fib6_walker_t *w;
1099         struct rt6_info *rt = *rtp;
1100
1101         RT6_TRACE("fib6_del_route\n");
1102
1103         /* Unlink it */
1104         *rtp = rt->u.next;
1105         rt->rt6i_node = NULL;
1106         rt6_stats.fib_rt_entries--;
1107         rt6_stats.fib_discarded_routes++;
1108
1109         /* Adjust walkers */
1110         read_lock(&fib6_walker_lock);
1111         FOR_WALKERS(w) {
1112                 if (w->state == FWS_C && w->leaf == rt) {
1113                         RT6_TRACE("walker %p adjusted by delroute\n", w);
1114                         w->leaf = rt->u.next;
1115                         if (w->leaf == NULL)
1116                                 w->state = FWS_U;
1117                 }
1118         }
1119         read_unlock(&fib6_walker_lock);
1120
1121         rt->u.next = NULL;
1122
1123         if (fn->leaf == NULL && fn->fn_flags&RTN_TL_ROOT)
1124                 fn->leaf = &ip6_null_entry;
1125
1126         /* If it was last route, expunge its radix tree node */
1127         if (fn->leaf == NULL) {
1128                 fn->fn_flags &= ~RTN_RTINFO;
1129                 rt6_stats.fib_route_nodes--;
1130                 fn = fib6_repair_tree(fn);
1131         }
1132
1133         if (atomic_read(&rt->rt6i_ref) != 1) {
1134                 /* This route is used as dummy address holder in some split
1135                  * nodes. It is not leaked, but it still holds other resources,
1136                  * which must be released in time. So, scan ascendant nodes
1137                  * and replace dummy references to this route with references
1138                  * to still alive ones.
1139                  */
1140                 while (fn) {
1141                         if (!(fn->fn_flags&RTN_RTINFO) && fn->leaf == rt) {
1142                                 fn->leaf = fib6_find_prefix(fn);
1143                                 atomic_inc(&fn->leaf->rt6i_ref);
1144                                 rt6_release(rt);
1145                         }
1146                         fn = fn->parent;
1147                 }
1148                 /* No more references are possible at this point. */
1149                 if (atomic_read(&rt->rt6i_ref) != 1) BUG();
1150         }
1151
1152         inet6_rt_notify(RTM_DELROUTE, rt, info);
1153         rt6_release(rt);
1154 }
1155
1156 int fib6_del(struct rt6_info *rt, struct nl_info *info)
1157 {
1158         struct fib6_node *fn = rt->rt6i_node;
1159         struct rt6_info **rtp;
1160
1161 #if RT6_DEBUG >= 2
1162         if (rt->u.dst.obsolete>0) {
1163                 BUG_TRAP(fn==NULL);
1164                 return -ENOENT;
1165         }
1166 #endif
1167         if (fn == NULL || rt == &ip6_null_entry)
1168                 return -ENOENT;
1169
1170         BUG_TRAP(fn->fn_flags&RTN_RTINFO);
1171
1172         if (!(rt->rt6i_flags&RTF_CACHE)) {
1173                 struct fib6_node *pn = fn;
1174 #ifdef CONFIG_IPV6_SUBTREES
1175                 /* clones of this route might be in another subtree */
1176                 if (rt->rt6i_src.plen) {
1177                         while (!(pn->fn_flags&RTN_ROOT))
1178                                 pn = pn->parent;
1179                         pn = pn->parent;
1180                 }
1181 #endif
1182                 fib6_prune_clones(pn, rt);
1183         }
1184
1185         /*
1186          *      Walk the leaf entries looking for ourself
1187          */
1188
1189         for (rtp = &fn->leaf; *rtp; rtp = &(*rtp)->u.next) {
1190                 if (*rtp == rt) {
1191                         fib6_del_route(fn, rtp, info);
1192                         return 0;
1193                 }
1194         }
1195         return -ENOENT;
1196 }
1197
1198 /*
1199  *      Tree traversal function.
1200  *
1201  *      Certainly, it is not interrupt safe.
1202  *      However, it is internally reenterable wrt itself and fib6_add/fib6_del.
1203  *      It means, that we can modify tree during walking
1204  *      and use this function for garbage collection, clone pruning,
1205  *      cleaning tree when a device goes down etc. etc. 
1206  *
1207  *      It guarantees that every node will be traversed,
1208  *      and that it will be traversed only once.
1209  *
1210  *      Callback function w->func may return:
1211  *      0 -> continue walking.
1212  *      positive value -> walking is suspended (used by tree dumps,
1213  *      and probably by gc, if it will be split to several slices)
1214  *      negative value -> terminate walking.
1215  *
1216  *      The function itself returns:
1217  *      0   -> walk is complete.
1218  *      >0  -> walk is incomplete (i.e. suspended)
1219  *      <0  -> walk is terminated by an error.
1220  */
1221
1222 static int fib6_walk_continue(struct fib6_walker_t *w)
1223 {
1224         struct fib6_node *fn, *pn;
1225
1226         for (;;) {
1227                 fn = w->node;
1228                 if (fn == NULL)
1229                         return 0;
1230
1231                 if (w->prune && fn != w->root &&
1232                     fn->fn_flags&RTN_RTINFO && w->state < FWS_C) {
1233                         w->state = FWS_C;
1234                         w->leaf = fn->leaf;
1235                 }
1236                 switch (w->state) {
1237 #ifdef CONFIG_IPV6_SUBTREES
1238                 case FWS_S:
1239                         if (FIB6_SUBTREE(fn)) {
1240                                 w->node = FIB6_SUBTREE(fn);
1241                                 continue;
1242                         }
1243                         w->state = FWS_L;
1244 #endif  
1245                 case FWS_L:
1246                         if (fn->left) {
1247                                 w->node = fn->left;
1248                                 w->state = FWS_INIT;
1249                                 continue;
1250                         }
1251                         w->state = FWS_R;
1252                 case FWS_R:
1253                         if (fn->right) {
1254                                 w->node = fn->right;
1255                                 w->state = FWS_INIT;
1256                                 continue;
1257                         }
1258                         w->state = FWS_C;
1259                         w->leaf = fn->leaf;
1260                 case FWS_C:
1261                         if (w->leaf && fn->fn_flags&RTN_RTINFO) {
1262                                 int err = w->func(w);
1263                                 if (err)
1264                                         return err;
1265                                 continue;
1266                         }
1267                         w->state = FWS_U;
1268                 case FWS_U:
1269                         if (fn == w->root)
1270                                 return 0;
1271                         pn = fn->parent;
1272                         w->node = pn;
1273 #ifdef CONFIG_IPV6_SUBTREES
1274                         if (FIB6_SUBTREE(pn) == fn) {
1275                                 BUG_TRAP(fn->fn_flags&RTN_ROOT);
1276                                 w->state = FWS_L;
1277                                 continue;
1278                         }
1279 #endif
1280                         if (pn->left == fn) {
1281                                 w->state = FWS_R;
1282                                 continue;
1283                         }
1284                         if (pn->right == fn) {
1285                                 w->state = FWS_C;
1286                                 w->leaf = w->node->leaf;
1287                                 continue;
1288                         }
1289 #if RT6_DEBUG >= 2
1290                         BUG_TRAP(0);
1291 #endif
1292                 }
1293         }
1294 }
1295
1296 static int fib6_walk(struct fib6_walker_t *w)
1297 {
1298         int res;
1299
1300         w->state = FWS_INIT;
1301         w->node = w->root;
1302
1303         fib6_walker_link(w);
1304         res = fib6_walk_continue(w);
1305         if (res <= 0)
1306                 fib6_walker_unlink(w);
1307         return res;
1308 }
1309
1310 static int fib6_clean_node(struct fib6_walker_t *w)
1311 {
1312         int res;
1313         struct rt6_info *rt;
1314         struct fib6_cleaner_t *c = (struct fib6_cleaner_t*)w;
1315
1316         for (rt = w->leaf; rt; rt = rt->u.next) {
1317                 res = c->func(rt, c->arg);
1318                 if (res < 0) {
1319                         w->leaf = rt;
1320                         res = fib6_del(rt, NULL);
1321                         if (res) {
1322 #if RT6_DEBUG >= 2
1323                                 printk(KERN_DEBUG "fib6_clean_node: del failed: rt=%p@%p err=%d\n", rt, rt->rt6i_node, res);
1324 #endif
1325                                 continue;
1326                         }
1327                         return 0;
1328                 }
1329                 BUG_TRAP(res==0);
1330         }
1331         w->leaf = rt;
1332         return 0;
1333 }
1334
1335 /*
1336  *      Convenient frontend to tree walker.
1337  *      
1338  *      func is called on each route.
1339  *              It may return -1 -> delete this route.
1340  *                            0  -> continue walking
1341  *
1342  *      prune==1 -> only immediate children of node (certainly,
1343  *      ignoring pure split nodes) will be scanned.
1344  */
1345
1346 static void fib6_clean_tree(struct fib6_node *root,
1347                             int (*func)(struct rt6_info *, void *arg),
1348                             int prune, void *arg)
1349 {
1350         struct fib6_cleaner_t c;
1351
1352         c.w.root = root;
1353         c.w.func = fib6_clean_node;
1354         c.w.prune = prune;
1355         c.func = func;
1356         c.arg = arg;
1357
1358         fib6_walk(&c.w);
1359 }
1360
1361 void fib6_clean_all(int (*func)(struct rt6_info *, void *arg),
1362                     int prune, void *arg)
1363 {
1364         struct fib6_table *table;
1365         struct hlist_node *node;
1366         unsigned int h;
1367
1368         rcu_read_lock();
1369         for (h = 0; h < FIB_TABLE_HASHSZ; h++) {
1370                 hlist_for_each_entry_rcu(table, node, &fib_table_hash[h],
1371                                          tb6_hlist) {
1372                         write_lock_bh(&table->tb6_lock);
1373                         fib6_clean_tree(&table->tb6_root, func, prune, arg);
1374                         write_unlock_bh(&table->tb6_lock);
1375                 }
1376         }
1377         rcu_read_unlock();
1378 }
1379
1380 static int fib6_prune_clone(struct rt6_info *rt, void *arg)
1381 {
1382         if (rt->rt6i_flags & RTF_CACHE) {
1383                 RT6_TRACE("pruning clone %p\n", rt);
1384                 return -1;
1385         }
1386
1387         return 0;
1388 }
1389
1390 static void fib6_prune_clones(struct fib6_node *fn, struct rt6_info *rt)
1391 {
1392         fib6_clean_tree(fn, fib6_prune_clone, 1, rt);
1393 }
1394
1395 /*
1396  *      Garbage collection
1397  */
1398
1399 static struct fib6_gc_args
1400 {
1401         int                     timeout;
1402         int                     more;
1403 } gc_args;
1404
1405 static int fib6_age(struct rt6_info *rt, void *arg)
1406 {
1407         unsigned long now = jiffies;
1408
1409         /*
1410          *      check addrconf expiration here.
1411          *      Routes are expired even if they are in use.
1412          *
1413          *      Also age clones. Note, that clones are aged out
1414          *      only if they are not in use now.
1415          */
1416
1417         if (rt->rt6i_flags&RTF_EXPIRES && rt->rt6i_expires) {
1418                 if (time_after(now, rt->rt6i_expires)) {
1419                         RT6_TRACE("expiring %p\n", rt);
1420                         return -1;
1421                 }
1422                 gc_args.more++;
1423         } else if (rt->rt6i_flags & RTF_CACHE) {
1424                 if (atomic_read(&rt->u.dst.__refcnt) == 0 &&
1425                     time_after_eq(now, rt->u.dst.lastuse + gc_args.timeout)) {
1426                         RT6_TRACE("aging clone %p\n", rt);
1427                         return -1;
1428                 } else if ((rt->rt6i_flags & RTF_GATEWAY) &&
1429                            (!(rt->rt6i_nexthop->flags & NTF_ROUTER))) {
1430                         RT6_TRACE("purging route %p via non-router but gateway\n",
1431                                   rt);
1432                         return -1;
1433                 }
1434                 gc_args.more++;
1435         }
1436
1437         return 0;
1438 }
1439
1440 static DEFINE_SPINLOCK(fib6_gc_lock);
1441
1442 void fib6_run_gc(unsigned long dummy)
1443 {
1444         if (dummy != ~0UL) {
1445                 spin_lock_bh(&fib6_gc_lock);
1446                 gc_args.timeout = dummy ? (int)dummy : ip6_rt_gc_interval;
1447         } else {
1448                 local_bh_disable();
1449                 if (!spin_trylock(&fib6_gc_lock)) {
1450                         mod_timer(&ip6_fib_timer, jiffies + HZ);
1451                         local_bh_enable();
1452                         return;
1453                 }
1454                 gc_args.timeout = ip6_rt_gc_interval;
1455         }
1456         gc_args.more = 0;
1457
1458         ndisc_dst_gc(&gc_args.more);
1459         fib6_clean_all(fib6_age, 0, NULL);
1460
1461         if (gc_args.more)
1462                 mod_timer(&ip6_fib_timer, jiffies + ip6_rt_gc_interval);
1463         else {
1464                 del_timer(&ip6_fib_timer);
1465                 ip6_fib_timer.expires = 0;
1466         }
1467         spin_unlock_bh(&fib6_gc_lock);
1468 }
1469
1470 void __init fib6_init(void)
1471 {
1472         fib6_node_kmem = kmem_cache_create("fib6_nodes",
1473                                            sizeof(struct fib6_node),
1474                                            0, SLAB_HWCACHE_ALIGN,
1475                                            NULL, NULL);
1476         if (!fib6_node_kmem)
1477                 panic("cannot create fib6_nodes cache");
1478
1479         fib6_tables_init();
1480 }
1481
1482 void fib6_gc_cleanup(void)
1483 {
1484         del_timer(&ip6_fib_timer);
1485         kmem_cache_destroy(fib6_node_kmem);
1486 }