[XFRM]: Add sorting interface for state and template.
[pandora-kernel.git] / net / xfrm / xfrm_policy.c
1 /* 
2  * xfrm_policy.c
3  *
4  * Changes:
5  *      Mitsuru KANDA @USAGI
6  *      Kazunori MIYAZAWA @USAGI
7  *      Kunihiro Ishiguro <kunihiro@ipinfusion.com>
8  *              IPv6 support
9  *      Kazunori MIYAZAWA @USAGI
10  *      YOSHIFUJI Hideaki
11  *              Split up af-specific portion
12  *      Derek Atkins <derek@ihtfp.com>          Add the post_input processor
13  *
14  */
15
16 #include <linux/slab.h>
17 #include <linux/kmod.h>
18 #include <linux/list.h>
19 #include <linux/spinlock.h>
20 #include <linux/workqueue.h>
21 #include <linux/notifier.h>
22 #include <linux/netdevice.h>
23 #include <linux/netfilter.h>
24 #include <linux/module.h>
25 #include <net/xfrm.h>
26 #include <net/ip.h>
27
28 DEFINE_MUTEX(xfrm_cfg_mutex);
29 EXPORT_SYMBOL(xfrm_cfg_mutex);
30
31 static DEFINE_RWLOCK(xfrm_policy_lock);
32
33 struct xfrm_policy *xfrm_policy_list[XFRM_POLICY_MAX*2];
34 EXPORT_SYMBOL(xfrm_policy_list);
35 #ifdef CONFIG_XFRM_SUB_POLICY
36 struct xfrm_policy *xfrm_policy_list_sub[XFRM_POLICY_MAX*2];
37 EXPORT_SYMBOL(xfrm_policy_list_sub);
38
39 #define XFRM_POLICY_LISTS(type) \
40         ((type == XFRM_POLICY_TYPE_SUB) ? xfrm_policy_list_sub : \
41          xfrm_policy_list)
42 #define XFRM_POLICY_LISTHEAD(type, dir) \
43         ((type == XFRM_POLICY_TYPE_SUB) ? xfrm_policy_list_sub[dir] : \
44          xfrm_policy_list[dir])
45 #define XFRM_POLICY_LISTHEADP(type, dir) \
46         ((type == XFRM_POLICY_TYPE_SUB) ? &xfrm_policy_list_sub[dir] : \
47          &xfrm_policy_list[dir])
48 #else
49 #define XFRM_POLICY_LISTS(type)              xfrm_policy_list
50 #define XFRM_POLICY_LISTHEAD(type, dif)      xfrm_policy_list[dir]
51 #define XFRM_POLICY_LISTHEADP(type, dif)     &xfrm_policy_list[dir]
52 #endif
53
54 static DEFINE_RWLOCK(xfrm_policy_afinfo_lock);
55 static struct xfrm_policy_afinfo *xfrm_policy_afinfo[NPROTO];
56
57 static kmem_cache_t *xfrm_dst_cache __read_mostly;
58
59 static struct work_struct xfrm_policy_gc_work;
60 static struct list_head xfrm_policy_gc_list =
61         LIST_HEAD_INIT(xfrm_policy_gc_list);
62 static DEFINE_SPINLOCK(xfrm_policy_gc_lock);
63
64 static struct xfrm_policy_afinfo *xfrm_policy_get_afinfo(unsigned short family);
65 static void xfrm_policy_put_afinfo(struct xfrm_policy_afinfo *afinfo);
66 static struct xfrm_policy_afinfo *xfrm_policy_lock_afinfo(unsigned int family);
67 static void xfrm_policy_unlock_afinfo(struct xfrm_policy_afinfo *afinfo);
68
69 int xfrm_register_type(struct xfrm_type *type, unsigned short family)
70 {
71         struct xfrm_policy_afinfo *afinfo = xfrm_policy_lock_afinfo(family);
72         struct xfrm_type **typemap;
73         int err = 0;
74
75         if (unlikely(afinfo == NULL))
76                 return -EAFNOSUPPORT;
77         typemap = afinfo->type_map;
78
79         if (likely(typemap[type->proto] == NULL))
80                 typemap[type->proto] = type;
81         else
82                 err = -EEXIST;
83         xfrm_policy_unlock_afinfo(afinfo);
84         return err;
85 }
86 EXPORT_SYMBOL(xfrm_register_type);
87
88 int xfrm_unregister_type(struct xfrm_type *type, unsigned short family)
89 {
90         struct xfrm_policy_afinfo *afinfo = xfrm_policy_lock_afinfo(family);
91         struct xfrm_type **typemap;
92         int err = 0;
93
94         if (unlikely(afinfo == NULL))
95                 return -EAFNOSUPPORT;
96         typemap = afinfo->type_map;
97
98         if (unlikely(typemap[type->proto] != type))
99                 err = -ENOENT;
100         else
101                 typemap[type->proto] = NULL;
102         xfrm_policy_unlock_afinfo(afinfo);
103         return err;
104 }
105 EXPORT_SYMBOL(xfrm_unregister_type);
106
107 struct xfrm_type *xfrm_get_type(u8 proto, unsigned short family)
108 {
109         struct xfrm_policy_afinfo *afinfo;
110         struct xfrm_type **typemap;
111         struct xfrm_type *type;
112         int modload_attempted = 0;
113
114 retry:
115         afinfo = xfrm_policy_get_afinfo(family);
116         if (unlikely(afinfo == NULL))
117                 return NULL;
118         typemap = afinfo->type_map;
119
120         type = typemap[proto];
121         if (unlikely(type && !try_module_get(type->owner)))
122                 type = NULL;
123         if (!type && !modload_attempted) {
124                 xfrm_policy_put_afinfo(afinfo);
125                 request_module("xfrm-type-%d-%d",
126                                (int) family, (int) proto);
127                 modload_attempted = 1;
128                 goto retry;
129         }
130
131         xfrm_policy_put_afinfo(afinfo);
132         return type;
133 }
134
135 int xfrm_dst_lookup(struct xfrm_dst **dst, struct flowi *fl, 
136                     unsigned short family)
137 {
138         struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
139         int err = 0;
140
141         if (unlikely(afinfo == NULL))
142                 return -EAFNOSUPPORT;
143
144         if (likely(afinfo->dst_lookup != NULL))
145                 err = afinfo->dst_lookup(dst, fl);
146         else
147                 err = -EINVAL;
148         xfrm_policy_put_afinfo(afinfo);
149         return err;
150 }
151 EXPORT_SYMBOL(xfrm_dst_lookup);
152
153 void xfrm_put_type(struct xfrm_type *type)
154 {
155         module_put(type->owner);
156 }
157
158 int xfrm_register_mode(struct xfrm_mode *mode, int family)
159 {
160         struct xfrm_policy_afinfo *afinfo;
161         struct xfrm_mode **modemap;
162         int err;
163
164         if (unlikely(mode->encap >= XFRM_MODE_MAX))
165                 return -EINVAL;
166
167         afinfo = xfrm_policy_lock_afinfo(family);
168         if (unlikely(afinfo == NULL))
169                 return -EAFNOSUPPORT;
170
171         err = -EEXIST;
172         modemap = afinfo->mode_map;
173         if (likely(modemap[mode->encap] == NULL)) {
174                 modemap[mode->encap] = mode;
175                 err = 0;
176         }
177
178         xfrm_policy_unlock_afinfo(afinfo);
179         return err;
180 }
181 EXPORT_SYMBOL(xfrm_register_mode);
182
183 int xfrm_unregister_mode(struct xfrm_mode *mode, int family)
184 {
185         struct xfrm_policy_afinfo *afinfo;
186         struct xfrm_mode **modemap;
187         int err;
188
189         if (unlikely(mode->encap >= XFRM_MODE_MAX))
190                 return -EINVAL;
191
192         afinfo = xfrm_policy_lock_afinfo(family);
193         if (unlikely(afinfo == NULL))
194                 return -EAFNOSUPPORT;
195
196         err = -ENOENT;
197         modemap = afinfo->mode_map;
198         if (likely(modemap[mode->encap] == mode)) {
199                 modemap[mode->encap] = NULL;
200                 err = 0;
201         }
202
203         xfrm_policy_unlock_afinfo(afinfo);
204         return err;
205 }
206 EXPORT_SYMBOL(xfrm_unregister_mode);
207
208 struct xfrm_mode *xfrm_get_mode(unsigned int encap, int family)
209 {
210         struct xfrm_policy_afinfo *afinfo;
211         struct xfrm_mode *mode;
212         int modload_attempted = 0;
213
214         if (unlikely(encap >= XFRM_MODE_MAX))
215                 return NULL;
216
217 retry:
218         afinfo = xfrm_policy_get_afinfo(family);
219         if (unlikely(afinfo == NULL))
220                 return NULL;
221
222         mode = afinfo->mode_map[encap];
223         if (unlikely(mode && !try_module_get(mode->owner)))
224                 mode = NULL;
225         if (!mode && !modload_attempted) {
226                 xfrm_policy_put_afinfo(afinfo);
227                 request_module("xfrm-mode-%d-%d", family, encap);
228                 modload_attempted = 1;
229                 goto retry;
230         }
231
232         xfrm_policy_put_afinfo(afinfo);
233         return mode;
234 }
235
236 void xfrm_put_mode(struct xfrm_mode *mode)
237 {
238         module_put(mode->owner);
239 }
240
241 static inline unsigned long make_jiffies(long secs)
242 {
243         if (secs >= (MAX_SCHEDULE_TIMEOUT-1)/HZ)
244                 return MAX_SCHEDULE_TIMEOUT-1;
245         else
246                 return secs*HZ;
247 }
248
249 static void xfrm_policy_timer(unsigned long data)
250 {
251         struct xfrm_policy *xp = (struct xfrm_policy*)data;
252         unsigned long now = (unsigned long)xtime.tv_sec;
253         long next = LONG_MAX;
254         int warn = 0;
255         int dir;
256
257         read_lock(&xp->lock);
258
259         if (xp->dead)
260                 goto out;
261
262         dir = xfrm_policy_id2dir(xp->index);
263
264         if (xp->lft.hard_add_expires_seconds) {
265                 long tmo = xp->lft.hard_add_expires_seconds +
266                         xp->curlft.add_time - now;
267                 if (tmo <= 0)
268                         goto expired;
269                 if (tmo < next)
270                         next = tmo;
271         }
272         if (xp->lft.hard_use_expires_seconds) {
273                 long tmo = xp->lft.hard_use_expires_seconds +
274                         (xp->curlft.use_time ? : xp->curlft.add_time) - now;
275                 if (tmo <= 0)
276                         goto expired;
277                 if (tmo < next)
278                         next = tmo;
279         }
280         if (xp->lft.soft_add_expires_seconds) {
281                 long tmo = xp->lft.soft_add_expires_seconds +
282                         xp->curlft.add_time - now;
283                 if (tmo <= 0) {
284                         warn = 1;
285                         tmo = XFRM_KM_TIMEOUT;
286                 }
287                 if (tmo < next)
288                         next = tmo;
289         }
290         if (xp->lft.soft_use_expires_seconds) {
291                 long tmo = xp->lft.soft_use_expires_seconds +
292                         (xp->curlft.use_time ? : xp->curlft.add_time) - now;
293                 if (tmo <= 0) {
294                         warn = 1;
295                         tmo = XFRM_KM_TIMEOUT;
296                 }
297                 if (tmo < next)
298                         next = tmo;
299         }
300
301         if (warn)
302                 km_policy_expired(xp, dir, 0, 0);
303         if (next != LONG_MAX &&
304             !mod_timer(&xp->timer, jiffies + make_jiffies(next)))
305                 xfrm_pol_hold(xp);
306
307 out:
308         read_unlock(&xp->lock);
309         xfrm_pol_put(xp);
310         return;
311
312 expired:
313         read_unlock(&xp->lock);
314         if (!xfrm_policy_delete(xp, dir))
315                 km_policy_expired(xp, dir, 1, 0);
316         xfrm_pol_put(xp);
317 }
318
319
320 /* Allocate xfrm_policy. Not used here, it is supposed to be used by pfkeyv2
321  * SPD calls.
322  */
323
324 struct xfrm_policy *xfrm_policy_alloc(gfp_t gfp)
325 {
326         struct xfrm_policy *policy;
327
328         policy = kzalloc(sizeof(struct xfrm_policy), gfp);
329
330         if (policy) {
331                 atomic_set(&policy->refcnt, 1);
332                 rwlock_init(&policy->lock);
333                 init_timer(&policy->timer);
334                 policy->timer.data = (unsigned long)policy;
335                 policy->timer.function = xfrm_policy_timer;
336         }
337         return policy;
338 }
339 EXPORT_SYMBOL(xfrm_policy_alloc);
340
341 /* Destroy xfrm_policy: descendant resources must be released to this moment. */
342
343 void __xfrm_policy_destroy(struct xfrm_policy *policy)
344 {
345         BUG_ON(!policy->dead);
346
347         BUG_ON(policy->bundles);
348
349         if (del_timer(&policy->timer))
350                 BUG();
351
352         security_xfrm_policy_free(policy);
353         kfree(policy);
354 }
355 EXPORT_SYMBOL(__xfrm_policy_destroy);
356
357 static void xfrm_policy_gc_kill(struct xfrm_policy *policy)
358 {
359         struct dst_entry *dst;
360
361         while ((dst = policy->bundles) != NULL) {
362                 policy->bundles = dst->next;
363                 dst_free(dst);
364         }
365
366         if (del_timer(&policy->timer))
367                 atomic_dec(&policy->refcnt);
368
369         if (atomic_read(&policy->refcnt) > 1)
370                 flow_cache_flush();
371
372         xfrm_pol_put(policy);
373 }
374
375 static void xfrm_policy_gc_task(void *data)
376 {
377         struct xfrm_policy *policy;
378         struct list_head *entry, *tmp;
379         struct list_head gc_list = LIST_HEAD_INIT(gc_list);
380
381         spin_lock_bh(&xfrm_policy_gc_lock);
382         list_splice_init(&xfrm_policy_gc_list, &gc_list);
383         spin_unlock_bh(&xfrm_policy_gc_lock);
384
385         list_for_each_safe(entry, tmp, &gc_list) {
386                 policy = list_entry(entry, struct xfrm_policy, list);
387                 xfrm_policy_gc_kill(policy);
388         }
389 }
390
391 /* Rule must be locked. Release descentant resources, announce
392  * entry dead. The rule must be unlinked from lists to the moment.
393  */
394
395 static void xfrm_policy_kill(struct xfrm_policy *policy)
396 {
397         int dead;
398
399         write_lock_bh(&policy->lock);
400         dead = policy->dead;
401         policy->dead = 1;
402         write_unlock_bh(&policy->lock);
403
404         if (unlikely(dead)) {
405                 WARN_ON(1);
406                 return;
407         }
408
409         spin_lock(&xfrm_policy_gc_lock);
410         list_add(&policy->list, &xfrm_policy_gc_list);
411         spin_unlock(&xfrm_policy_gc_lock);
412
413         schedule_work(&xfrm_policy_gc_work);
414 }
415
416 /* Generate new index... KAME seems to generate them ordered by cost
417  * of an absolute inpredictability of ordering of rules. This will not pass. */
418 static u32 xfrm_gen_index(u8 type, int dir)
419 {
420         u32 idx;
421         struct xfrm_policy *p;
422         static u32 idx_generator;
423
424         for (;;) {
425                 idx = (idx_generator | dir);
426                 idx_generator += 8;
427                 if (idx == 0)
428                         idx = 8;
429                 for (p = XFRM_POLICY_LISTHEAD(type, dir); p; p = p->next) {
430                         if (p->index == idx)
431                                 break;
432                 }
433                 if (!p)
434                         return idx;
435         }
436 }
437
438 int xfrm_policy_insert(int dir, struct xfrm_policy *policy, int excl)
439 {
440         struct xfrm_policy *pol, **p;
441         struct xfrm_policy *delpol = NULL;
442         struct xfrm_policy **newpos = NULL;
443         struct dst_entry *gc_list;
444
445         write_lock_bh(&xfrm_policy_lock);
446         for (p = XFRM_POLICY_LISTHEADP(policy->type, dir); (pol=*p)!=NULL;) {
447                 if (!delpol && memcmp(&policy->selector, &pol->selector, sizeof(pol->selector)) == 0 &&
448                     xfrm_sec_ctx_match(pol->security, policy->security)) {
449                         if (excl) {
450                                 write_unlock_bh(&xfrm_policy_lock);
451                                 return -EEXIST;
452                         }
453                         *p = pol->next;
454                         delpol = pol;
455                         if (policy->priority > pol->priority)
456                                 continue;
457                 } else if (policy->priority >= pol->priority) {
458                         p = &pol->next;
459                         continue;
460                 }
461                 if (!newpos)
462                         newpos = p;
463                 if (delpol)
464                         break;
465                 p = &pol->next;
466         }
467         if (newpos)
468                 p = newpos;
469         xfrm_pol_hold(policy);
470         policy->next = *p;
471         *p = policy;
472         atomic_inc(&flow_cache_genid);
473         policy->index = delpol ? delpol->index : xfrm_gen_index(policy->type, dir);
474         policy->curlft.add_time = (unsigned long)xtime.tv_sec;
475         policy->curlft.use_time = 0;
476         if (!mod_timer(&policy->timer, jiffies + HZ))
477                 xfrm_pol_hold(policy);
478         write_unlock_bh(&xfrm_policy_lock);
479
480         if (delpol)
481                 xfrm_policy_kill(delpol);
482
483         read_lock_bh(&xfrm_policy_lock);
484         gc_list = NULL;
485         for (policy = policy->next; policy; policy = policy->next) {
486                 struct dst_entry *dst;
487
488                 write_lock(&policy->lock);
489                 dst = policy->bundles;
490                 if (dst) {
491                         struct dst_entry *tail = dst;
492                         while (tail->next)
493                                 tail = tail->next;
494                         tail->next = gc_list;
495                         gc_list = dst;
496
497                         policy->bundles = NULL;
498                 }
499                 write_unlock(&policy->lock);
500         }
501         read_unlock_bh(&xfrm_policy_lock);
502
503         while (gc_list) {
504                 struct dst_entry *dst = gc_list;
505
506                 gc_list = dst->next;
507                 dst_free(dst);
508         }
509
510         return 0;
511 }
512 EXPORT_SYMBOL(xfrm_policy_insert);
513
514 struct xfrm_policy *xfrm_policy_bysel_ctx(u8 type, int dir,
515                                           struct xfrm_selector *sel,
516                                           struct xfrm_sec_ctx *ctx, int delete)
517 {
518         struct xfrm_policy *pol, **p;
519
520         write_lock_bh(&xfrm_policy_lock);
521         for (p = XFRM_POLICY_LISTHEADP(type, dir); (pol=*p)!=NULL; p = &pol->next) {
522                 if ((memcmp(sel, &pol->selector, sizeof(*sel)) == 0) &&
523                     (xfrm_sec_ctx_match(ctx, pol->security))) {
524                         xfrm_pol_hold(pol);
525                         if (delete)
526                                 *p = pol->next;
527                         break;
528                 }
529         }
530         write_unlock_bh(&xfrm_policy_lock);
531
532         if (pol && delete) {
533                 atomic_inc(&flow_cache_genid);
534                 xfrm_policy_kill(pol);
535         }
536         return pol;
537 }
538 EXPORT_SYMBOL(xfrm_policy_bysel_ctx);
539
540 struct xfrm_policy *xfrm_policy_byid(u8 type, int dir, u32 id, int delete)
541 {
542         struct xfrm_policy *pol, **p;
543
544         write_lock_bh(&xfrm_policy_lock);
545         for (p = XFRM_POLICY_LISTHEADP(type, dir); (pol=*p)!=NULL; p = &pol->next) {
546                 if (pol->index == id) {
547                         xfrm_pol_hold(pol);
548                         if (delete)
549                                 *p = pol->next;
550                         break;
551                 }
552         }
553         write_unlock_bh(&xfrm_policy_lock);
554
555         if (pol && delete) {
556                 atomic_inc(&flow_cache_genid);
557                 xfrm_policy_kill(pol);
558         }
559         return pol;
560 }
561 EXPORT_SYMBOL(xfrm_policy_byid);
562
563 void xfrm_policy_flush(u8 type)
564 {
565         struct xfrm_policy *xp;
566         struct xfrm_policy **p_list = XFRM_POLICY_LISTS(type);
567         int dir;
568
569         write_lock_bh(&xfrm_policy_lock);
570         for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
571                 while ((xp = p_list[dir]) != NULL) {
572                         p_list[dir] = xp->next;
573                         write_unlock_bh(&xfrm_policy_lock);
574
575                         xfrm_policy_kill(xp);
576
577                         write_lock_bh(&xfrm_policy_lock);
578                 }
579         }
580         atomic_inc(&flow_cache_genid);
581         write_unlock_bh(&xfrm_policy_lock);
582 }
583 EXPORT_SYMBOL(xfrm_policy_flush);
584
585 int xfrm_policy_walk(u8 type, int (*func)(struct xfrm_policy *, int, int, void*),
586                      void *data)
587 {
588         struct xfrm_policy *xp;
589         int dir;
590         int count = 0;
591         int error = 0;
592
593         read_lock_bh(&xfrm_policy_lock);
594         for (dir = 0; dir < 2*XFRM_POLICY_MAX; dir++) {
595                 for (xp = XFRM_POLICY_LISTHEAD(type, dir); xp; xp = xp->next)
596                         count++;
597         }
598
599         if (count == 0) {
600                 error = -ENOENT;
601                 goto out;
602         }
603
604         for (dir = 0; dir < 2*XFRM_POLICY_MAX; dir++) {
605                 for (xp = XFRM_POLICY_LISTHEAD(type, dir); xp; xp = xp->next) {
606                         error = func(xp, dir%XFRM_POLICY_MAX, --count, data);
607                         if (error)
608                                 goto out;
609                 }
610         }
611
612 out:
613         read_unlock_bh(&xfrm_policy_lock);
614         return error;
615 }
616 EXPORT_SYMBOL(xfrm_policy_walk);
617
618 /* Find policy to apply to this flow. */
619
620 static struct xfrm_policy *xfrm_policy_lookup_bytype(u8 type, struct flowi *fl,
621                                                      u16 family, u8 dir)
622 {
623         struct xfrm_policy *pol;
624
625         read_lock_bh(&xfrm_policy_lock);
626         for (pol = XFRM_POLICY_LISTHEAD(type, dir); pol; pol = pol->next) {
627                 struct xfrm_selector *sel = &pol->selector;
628                 int match;
629
630                 if (pol->family != family)
631                         continue;
632
633                 match = xfrm_selector_match(sel, fl, family);
634
635                 if (match) {
636                         if (!security_xfrm_policy_lookup(pol, fl->secid, dir)) {
637                                 xfrm_pol_hold(pol);
638                                 break;
639                         }
640                 }
641         }
642         read_unlock_bh(&xfrm_policy_lock);
643
644         return pol;
645 }
646
647 static void xfrm_policy_lookup(struct flowi *fl, u16 family, u8 dir,
648                                void **objp, atomic_t **obj_refp)
649 {
650         struct xfrm_policy *pol;
651
652 #ifdef CONFIG_XFRM_SUB_POLICY
653         pol = xfrm_policy_lookup_bytype(XFRM_POLICY_TYPE_SUB, fl, family, dir);
654         if (pol)
655                 goto end;
656 #endif
657         pol = xfrm_policy_lookup_bytype(XFRM_POLICY_TYPE_MAIN, fl, family, dir);
658
659 #ifdef CONFIG_XFRM_SUB_POLICY
660  end:
661 #endif
662         if ((*objp = (void *) pol) != NULL)
663                 *obj_refp = &pol->refcnt;
664 }
665
666 static inline int policy_to_flow_dir(int dir)
667 {
668         if (XFRM_POLICY_IN == FLOW_DIR_IN &&
669             XFRM_POLICY_OUT == FLOW_DIR_OUT &&
670             XFRM_POLICY_FWD == FLOW_DIR_FWD)
671                 return dir;
672         switch (dir) {
673         default:
674         case XFRM_POLICY_IN:
675                 return FLOW_DIR_IN;
676         case XFRM_POLICY_OUT:
677                 return FLOW_DIR_OUT;
678         case XFRM_POLICY_FWD:
679                 return FLOW_DIR_FWD;
680         };
681 }
682
683 static struct xfrm_policy *xfrm_sk_policy_lookup(struct sock *sk, int dir, struct flowi *fl)
684 {
685         struct xfrm_policy *pol;
686
687         read_lock_bh(&xfrm_policy_lock);
688         if ((pol = sk->sk_policy[dir]) != NULL) {
689                 int match = xfrm_selector_match(&pol->selector, fl,
690                                                 sk->sk_family);
691                 int err = 0;
692
693                 if (match)
694                   err = security_xfrm_policy_lookup(pol, fl->secid, policy_to_flow_dir(dir));
695
696                 if (match && !err)
697                         xfrm_pol_hold(pol);
698                 else
699                         pol = NULL;
700         }
701         read_unlock_bh(&xfrm_policy_lock);
702         return pol;
703 }
704
705 static void __xfrm_policy_link(struct xfrm_policy *pol, int dir)
706 {
707         struct xfrm_policy **p_list = XFRM_POLICY_LISTS(pol->type);
708
709         pol->next = p_list[dir];
710         p_list[dir] = pol;
711         xfrm_pol_hold(pol);
712 }
713
714 static struct xfrm_policy *__xfrm_policy_unlink(struct xfrm_policy *pol,
715                                                 int dir)
716 {
717         struct xfrm_policy **polp;
718
719         for (polp = XFRM_POLICY_LISTHEADP(pol->type, dir);
720              *polp != NULL; polp = &(*polp)->next) {
721                 if (*polp == pol) {
722                         *polp = pol->next;
723                         return pol;
724                 }
725         }
726         return NULL;
727 }
728
729 int xfrm_policy_delete(struct xfrm_policy *pol, int dir)
730 {
731         write_lock_bh(&xfrm_policy_lock);
732         pol = __xfrm_policy_unlink(pol, dir);
733         write_unlock_bh(&xfrm_policy_lock);
734         if (pol) {
735                 if (dir < XFRM_POLICY_MAX)
736                         atomic_inc(&flow_cache_genid);
737                 xfrm_policy_kill(pol);
738                 return 0;
739         }
740         return -ENOENT;
741 }
742 EXPORT_SYMBOL(xfrm_policy_delete);
743
744 int xfrm_sk_policy_insert(struct sock *sk, int dir, struct xfrm_policy *pol)
745 {
746         struct xfrm_policy *old_pol;
747
748 #ifdef CONFIG_XFRM_SUB_POLICY
749         if (pol && pol->type != XFRM_POLICY_TYPE_MAIN)
750                 return -EINVAL;
751 #endif
752
753         write_lock_bh(&xfrm_policy_lock);
754         old_pol = sk->sk_policy[dir];
755         sk->sk_policy[dir] = pol;
756         if (pol) {
757                 pol->curlft.add_time = (unsigned long)xtime.tv_sec;
758                 pol->index = xfrm_gen_index(pol->type, XFRM_POLICY_MAX+dir);
759                 __xfrm_policy_link(pol, XFRM_POLICY_MAX+dir);
760         }
761         if (old_pol)
762                 __xfrm_policy_unlink(old_pol, XFRM_POLICY_MAX+dir);
763         write_unlock_bh(&xfrm_policy_lock);
764
765         if (old_pol) {
766                 xfrm_policy_kill(old_pol);
767         }
768         return 0;
769 }
770
771 static struct xfrm_policy *clone_policy(struct xfrm_policy *old, int dir)
772 {
773         struct xfrm_policy *newp = xfrm_policy_alloc(GFP_ATOMIC);
774
775         if (newp) {
776                 newp->selector = old->selector;
777                 if (security_xfrm_policy_clone(old, newp)) {
778                         kfree(newp);
779                         return NULL;  /* ENOMEM */
780                 }
781                 newp->lft = old->lft;
782                 newp->curlft = old->curlft;
783                 newp->action = old->action;
784                 newp->flags = old->flags;
785                 newp->xfrm_nr = old->xfrm_nr;
786                 newp->index = old->index;
787                 newp->type = old->type;
788                 memcpy(newp->xfrm_vec, old->xfrm_vec,
789                        newp->xfrm_nr*sizeof(struct xfrm_tmpl));
790                 write_lock_bh(&xfrm_policy_lock);
791                 __xfrm_policy_link(newp, XFRM_POLICY_MAX+dir);
792                 write_unlock_bh(&xfrm_policy_lock);
793                 xfrm_pol_put(newp);
794         }
795         return newp;
796 }
797
798 int __xfrm_sk_clone_policy(struct sock *sk)
799 {
800         struct xfrm_policy *p0 = sk->sk_policy[0],
801                            *p1 = sk->sk_policy[1];
802
803         sk->sk_policy[0] = sk->sk_policy[1] = NULL;
804         if (p0 && (sk->sk_policy[0] = clone_policy(p0, 0)) == NULL)
805                 return -ENOMEM;
806         if (p1 && (sk->sk_policy[1] = clone_policy(p1, 1)) == NULL)
807                 return -ENOMEM;
808         return 0;
809 }
810
811 /* Resolve list of templates for the flow, given policy. */
812
813 static int
814 xfrm_tmpl_resolve_one(struct xfrm_policy *policy, struct flowi *fl,
815                       struct xfrm_state **xfrm,
816                       unsigned short family)
817 {
818         int nx;
819         int i, error;
820         xfrm_address_t *daddr = xfrm_flowi_daddr(fl, family);
821         xfrm_address_t *saddr = xfrm_flowi_saddr(fl, family);
822
823         for (nx=0, i = 0; i < policy->xfrm_nr; i++) {
824                 struct xfrm_state *x;
825                 xfrm_address_t *remote = daddr;
826                 xfrm_address_t *local  = saddr;
827                 struct xfrm_tmpl *tmpl = &policy->xfrm_vec[i];
828
829                 if (tmpl->mode == XFRM_MODE_TUNNEL) {
830                         remote = &tmpl->id.daddr;
831                         local = &tmpl->saddr;
832                 }
833
834                 x = xfrm_state_find(remote, local, fl, tmpl, policy, &error, family);
835
836                 if (x && x->km.state == XFRM_STATE_VALID) {
837                         xfrm[nx++] = x;
838                         daddr = remote;
839                         saddr = local;
840                         continue;
841                 }
842                 if (x) {
843                         error = (x->km.state == XFRM_STATE_ERROR ?
844                                  -EINVAL : -EAGAIN);
845                         xfrm_state_put(x);
846                 }
847
848                 if (!tmpl->optional)
849                         goto fail;
850         }
851         return nx;
852
853 fail:
854         for (nx--; nx>=0; nx--)
855                 xfrm_state_put(xfrm[nx]);
856         return error;
857 }
858
859 static int
860 xfrm_tmpl_resolve(struct xfrm_policy **pols, int npols, struct flowi *fl,
861                   struct xfrm_state **xfrm,
862                   unsigned short family)
863 {
864         struct xfrm_state *tp[XFRM_MAX_DEPTH];
865         struct xfrm_state **tpp = (npols > 1) ? tp : xfrm;
866         int cnx = 0;
867         int error;
868         int ret;
869         int i;
870
871         for (i = 0; i < npols; i++) {
872                 if (cnx + pols[i]->xfrm_nr >= XFRM_MAX_DEPTH) {
873                         error = -ENOBUFS;
874                         goto fail;
875                 }
876
877                 ret = xfrm_tmpl_resolve_one(pols[i], fl, &tpp[cnx], family);
878                 if (ret < 0) {
879                         error = ret;
880                         goto fail;
881                 } else
882                         cnx += ret;
883         }
884
885         /* found states are sorted for outbound processing */
886         if (npols > 1)
887                 xfrm_state_sort(xfrm, tpp, cnx, family);
888
889         return cnx;
890
891  fail:
892         for (cnx--; cnx>=0; cnx--)
893                 xfrm_state_put(tpp[cnx]);
894         return error;
895
896 }
897
898 /* Check that the bundle accepts the flow and its components are
899  * still valid.
900  */
901
902 static struct dst_entry *
903 xfrm_find_bundle(struct flowi *fl, struct xfrm_policy *policy, unsigned short family)
904 {
905         struct dst_entry *x;
906         struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
907         if (unlikely(afinfo == NULL))
908                 return ERR_PTR(-EINVAL);
909         x = afinfo->find_bundle(fl, policy);
910         xfrm_policy_put_afinfo(afinfo);
911         return x;
912 }
913
914 /* Allocate chain of dst_entry's, attach known xfrm's, calculate
915  * all the metrics... Shortly, bundle a bundle.
916  */
917
918 static int
919 xfrm_bundle_create(struct xfrm_policy *policy, struct xfrm_state **xfrm, int nx,
920                    struct flowi *fl, struct dst_entry **dst_p,
921                    unsigned short family)
922 {
923         int err;
924         struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
925         if (unlikely(afinfo == NULL))
926                 return -EINVAL;
927         err = afinfo->bundle_create(policy, xfrm, nx, fl, dst_p);
928         xfrm_policy_put_afinfo(afinfo);
929         return err;
930 }
931
932
933 static int stale_bundle(struct dst_entry *dst);
934
935 /* Main function: finds/creates a bundle for given flow.
936  *
937  * At the moment we eat a raw IP route. Mostly to speed up lookups
938  * on interfaces with disabled IPsec.
939  */
940 int xfrm_lookup(struct dst_entry **dst_p, struct flowi *fl,
941                 struct sock *sk, int flags)
942 {
943         struct xfrm_policy *policy;
944         struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
945         int npols;
946         int pol_dead;
947         int xfrm_nr;
948         int pi;
949         struct xfrm_state *xfrm[XFRM_MAX_DEPTH];
950         struct dst_entry *dst, *dst_orig = *dst_p;
951         int nx = 0;
952         int err;
953         u32 genid;
954         u16 family;
955         u8 dir = policy_to_flow_dir(XFRM_POLICY_OUT);
956
957 restart:
958         genid = atomic_read(&flow_cache_genid);
959         policy = NULL;
960         for (pi = 0; pi < ARRAY_SIZE(pols); pi++)
961                 pols[pi] = NULL;
962         npols = 0;
963         pol_dead = 0;
964         xfrm_nr = 0;
965
966         if (sk && sk->sk_policy[1])
967                 policy = xfrm_sk_policy_lookup(sk, XFRM_POLICY_OUT, fl);
968
969         if (!policy) {
970                 /* To accelerate a bit...  */
971                 if ((dst_orig->flags & DST_NOXFRM) || xfrm_policy_lists_empty(XFRM_POLICY_OUT))
972                         return 0;
973
974                 policy = flow_cache_lookup(fl, dst_orig->ops->family,
975                                            dir, xfrm_policy_lookup);
976         }
977
978         if (!policy)
979                 return 0;
980
981         family = dst_orig->ops->family;
982         policy->curlft.use_time = (unsigned long)xtime.tv_sec;
983         pols[0] = policy;
984         npols ++;
985         xfrm_nr += pols[0]->xfrm_nr;
986
987         switch (policy->action) {
988         case XFRM_POLICY_BLOCK:
989                 /* Prohibit the flow */
990                 err = -EPERM;
991                 goto error;
992
993         case XFRM_POLICY_ALLOW:
994 #ifndef CONFIG_XFRM_SUB_POLICY
995                 if (policy->xfrm_nr == 0) {
996                         /* Flow passes not transformed. */
997                         xfrm_pol_put(policy);
998                         return 0;
999                 }
1000 #endif
1001
1002                 /* Try to find matching bundle.
1003                  *
1004                  * LATER: help from flow cache. It is optional, this
1005                  * is required only for output policy.
1006                  */
1007                 dst = xfrm_find_bundle(fl, policy, family);
1008                 if (IS_ERR(dst)) {
1009                         err = PTR_ERR(dst);
1010                         goto error;
1011                 }
1012
1013                 if (dst)
1014                         break;
1015
1016 #ifdef CONFIG_XFRM_SUB_POLICY
1017                 if (pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
1018                         pols[1] = xfrm_policy_lookup_bytype(XFRM_POLICY_TYPE_MAIN,
1019                                                             fl, family,
1020                                                             XFRM_POLICY_OUT);
1021                         if (pols[1]) {
1022                                 if (pols[1]->action == XFRM_POLICY_BLOCK) {
1023                                         err = -EPERM;
1024                                         goto error;
1025                                 }
1026                                 npols ++;
1027                                 xfrm_nr += pols[1]->xfrm_nr;
1028                         }
1029                 }
1030
1031                 /*
1032                  * Because neither flowi nor bundle information knows about
1033                  * transformation template size. On more than one policy usage
1034                  * we can realize whether all of them is bypass or not after
1035                  * they are searched. See above not-transformed bypass
1036                  * is surrounded by non-sub policy configuration, too.
1037                  */
1038                 if (xfrm_nr == 0) {
1039                         /* Flow passes not transformed. */
1040                         xfrm_pols_put(pols, npols);
1041                         return 0;
1042                 }
1043
1044 #endif
1045                 nx = xfrm_tmpl_resolve(pols, npols, fl, xfrm, family);
1046
1047                 if (unlikely(nx<0)) {
1048                         err = nx;
1049                         if (err == -EAGAIN && flags) {
1050                                 DECLARE_WAITQUEUE(wait, current);
1051
1052                                 add_wait_queue(&km_waitq, &wait);
1053                                 set_current_state(TASK_INTERRUPTIBLE);
1054                                 schedule();
1055                                 set_current_state(TASK_RUNNING);
1056                                 remove_wait_queue(&km_waitq, &wait);
1057
1058                                 nx = xfrm_tmpl_resolve(pols, npols, fl, xfrm, family);
1059
1060                                 if (nx == -EAGAIN && signal_pending(current)) {
1061                                         err = -ERESTART;
1062                                         goto error;
1063                                 }
1064                                 if (nx == -EAGAIN ||
1065                                     genid != atomic_read(&flow_cache_genid)) {
1066                                         xfrm_pols_put(pols, npols);
1067                                         goto restart;
1068                                 }
1069                                 err = nx;
1070                         }
1071                         if (err < 0)
1072                                 goto error;
1073                 }
1074                 if (nx == 0) {
1075                         /* Flow passes not transformed. */
1076                         xfrm_pols_put(pols, npols);
1077                         return 0;
1078                 }
1079
1080                 dst = dst_orig;
1081                 err = xfrm_bundle_create(policy, xfrm, nx, fl, &dst, family);
1082
1083                 if (unlikely(err)) {
1084                         int i;
1085                         for (i=0; i<nx; i++)
1086                                 xfrm_state_put(xfrm[i]);
1087                         goto error;
1088                 }
1089
1090                 for (pi = 0; pi < npols; pi++) {
1091                         read_lock_bh(&pols[pi]->lock);
1092                         pol_dead |= pols[pi]->dead;
1093                         read_unlock_bh(&pols[pi]->lock);
1094                 }
1095
1096                 write_lock_bh(&policy->lock);
1097                 if (unlikely(pol_dead || stale_bundle(dst))) {
1098                         /* Wow! While we worked on resolving, this
1099                          * policy has gone. Retry. It is not paranoia,
1100                          * we just cannot enlist new bundle to dead object.
1101                          * We can't enlist stable bundles either.
1102                          */
1103                         write_unlock_bh(&policy->lock);
1104                         if (dst)
1105                                 dst_free(dst);
1106
1107                         err = -EHOSTUNREACH;
1108                         goto error;
1109                 }
1110                 dst->next = policy->bundles;
1111                 policy->bundles = dst;
1112                 dst_hold(dst);
1113                 write_unlock_bh(&policy->lock);
1114         }
1115         *dst_p = dst;
1116         dst_release(dst_orig);
1117         xfrm_pols_put(pols, npols);
1118         return 0;
1119
1120 error:
1121         dst_release(dst_orig);
1122         xfrm_pols_put(pols, npols);
1123         *dst_p = NULL;
1124         return err;
1125 }
1126 EXPORT_SYMBOL(xfrm_lookup);
1127
1128 static inline int
1129 xfrm_secpath_reject(int idx, struct sk_buff *skb, struct flowi *fl)
1130 {
1131         struct xfrm_state *x;
1132         int err;
1133
1134         if (!skb->sp || idx < 0 || idx >= skb->sp->len)
1135                 return 0;
1136         x = skb->sp->xvec[idx];
1137         if (!x->type->reject)
1138                 return 0;
1139         xfrm_state_hold(x);
1140         err = x->type->reject(x, skb, fl);
1141         xfrm_state_put(x);
1142         return err;
1143 }
1144
1145 /* When skb is transformed back to its "native" form, we have to
1146  * check policy restrictions. At the moment we make this in maximally
1147  * stupid way. Shame on me. :-) Of course, connected sockets must
1148  * have policy cached at them.
1149  */
1150
1151 static inline int
1152 xfrm_state_ok(struct xfrm_tmpl *tmpl, struct xfrm_state *x, 
1153               unsigned short family)
1154 {
1155         if (xfrm_state_kern(x))
1156                 return tmpl->optional && !xfrm_state_addr_cmp(tmpl, x, family);
1157         return  x->id.proto == tmpl->id.proto &&
1158                 (x->id.spi == tmpl->id.spi || !tmpl->id.spi) &&
1159                 (x->props.reqid == tmpl->reqid || !tmpl->reqid) &&
1160                 x->props.mode == tmpl->mode &&
1161                 ((tmpl->aalgos & (1<<x->props.aalgo)) ||
1162                  !(xfrm_id_proto_match(tmpl->id.proto, IPSEC_PROTO_ANY))) &&
1163                 !(x->props.mode != XFRM_MODE_TRANSPORT &&
1164                   xfrm_state_addr_cmp(tmpl, x, family));
1165 }
1166
1167 /*
1168  * 0 or more than 0 is returned when validation is succeeded (either bypass
1169  * because of optional transport mode, or next index of the mathced secpath
1170  * state with the template.
1171  * -1 is returned when no matching template is found.
1172  * Otherwise "-2 - errored_index" is returned.
1173  */
1174 static inline int
1175 xfrm_policy_ok(struct xfrm_tmpl *tmpl, struct sec_path *sp, int start,
1176                unsigned short family)
1177 {
1178         int idx = start;
1179
1180         if (tmpl->optional) {
1181                 if (tmpl->mode == XFRM_MODE_TRANSPORT)
1182                         return start;
1183         } else
1184                 start = -1;
1185         for (; idx < sp->len; idx++) {
1186                 if (xfrm_state_ok(tmpl, sp->xvec[idx], family))
1187                         return ++idx;
1188                 if (sp->xvec[idx]->props.mode != XFRM_MODE_TRANSPORT) {
1189                         if (start == -1)
1190                                 start = -2-idx;
1191                         break;
1192                 }
1193         }
1194         return start;
1195 }
1196
1197 int
1198 xfrm_decode_session(struct sk_buff *skb, struct flowi *fl, unsigned short family)
1199 {
1200         struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1201         int err;
1202
1203         if (unlikely(afinfo == NULL))
1204                 return -EAFNOSUPPORT;
1205
1206         afinfo->decode_session(skb, fl);
1207         err = security_xfrm_decode_session(skb, &fl->secid);
1208         xfrm_policy_put_afinfo(afinfo);
1209         return err;
1210 }
1211 EXPORT_SYMBOL(xfrm_decode_session);
1212
1213 static inline int secpath_has_nontransport(struct sec_path *sp, int k, int *idxp)
1214 {
1215         for (; k < sp->len; k++) {
1216                 if (sp->xvec[k]->props.mode != XFRM_MODE_TRANSPORT) {
1217                         if (idxp)
1218                                 *idxp = k;
1219                         return 1;
1220                 }
1221         }
1222
1223         return 0;
1224 }
1225
1226 int __xfrm_policy_check(struct sock *sk, int dir, struct sk_buff *skb, 
1227                         unsigned short family)
1228 {
1229         struct xfrm_policy *pol;
1230         struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
1231         int npols = 0;
1232         int xfrm_nr;
1233         int pi;
1234         struct flowi fl;
1235         u8 fl_dir = policy_to_flow_dir(dir);
1236         int xerr_idx = -1;
1237         int *xerr_idxp = &xerr_idx;
1238
1239         if (xfrm_decode_session(skb, &fl, family) < 0)
1240                 return 0;
1241         nf_nat_decode_session(skb, &fl, family);
1242
1243         /* First, check used SA against their selectors. */
1244         if (skb->sp) {
1245                 int i;
1246
1247                 for (i=skb->sp->len-1; i>=0; i--) {
1248                         struct xfrm_state *x = skb->sp->xvec[i];
1249                         if (!xfrm_selector_match(&x->sel, &fl, family))
1250                                 return 0;
1251                 }
1252         }
1253
1254         pol = NULL;
1255         if (sk && sk->sk_policy[dir])
1256                 pol = xfrm_sk_policy_lookup(sk, dir, &fl);
1257
1258         if (!pol)
1259                 pol = flow_cache_lookup(&fl, family, fl_dir,
1260                                         xfrm_policy_lookup);
1261
1262         if (!pol) {
1263                 if (skb->sp && secpath_has_nontransport(skb->sp, 0, xerr_idxp)) {
1264                         xfrm_secpath_reject(xerr_idx, skb, &fl);
1265                         return 0;
1266                 }
1267                 return 1;
1268         }
1269
1270         pol->curlft.use_time = (unsigned long)xtime.tv_sec;
1271
1272         pols[0] = pol;
1273         npols ++;
1274 #ifdef CONFIG_XFRM_SUB_POLICY
1275         if (pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
1276                 pols[1] = xfrm_policy_lookup_bytype(XFRM_POLICY_TYPE_MAIN,
1277                                                     &fl, family,
1278                                                     XFRM_POLICY_IN);
1279                 if (pols[1]) {
1280                         pols[1]->curlft.use_time = (unsigned long)xtime.tv_sec;
1281                         npols ++;
1282                 }
1283         }
1284 #endif
1285
1286         if (pol->action == XFRM_POLICY_ALLOW) {
1287                 struct sec_path *sp;
1288                 static struct sec_path dummy;
1289                 struct xfrm_tmpl *tp[XFRM_MAX_DEPTH];
1290                 struct xfrm_tmpl *stp[XFRM_MAX_DEPTH];
1291                 struct xfrm_tmpl **tpp = tp;
1292                 int ti = 0;
1293                 int i, k;
1294
1295                 if ((sp = skb->sp) == NULL)
1296                         sp = &dummy;
1297
1298                 for (pi = 0; pi < npols; pi++) {
1299                         if (pols[pi] != pol &&
1300                             pols[pi]->action != XFRM_POLICY_ALLOW)
1301                                 goto reject;
1302                         if (ti + pols[pi]->xfrm_nr >= XFRM_MAX_DEPTH)
1303                                 goto reject_error;
1304                         for (i = 0; i < pols[pi]->xfrm_nr; i++)
1305                                 tpp[ti++] = &pols[pi]->xfrm_vec[i];
1306                 }
1307                 xfrm_nr = ti;
1308                 if (npols > 1) {
1309                         xfrm_tmpl_sort(stp, tpp, xfrm_nr, family);
1310                         tpp = stp;
1311                 }
1312
1313                 /* For each tunnel xfrm, find the first matching tmpl.
1314                  * For each tmpl before that, find corresponding xfrm.
1315                  * Order is _important_. Later we will implement
1316                  * some barriers, but at the moment barriers
1317                  * are implied between each two transformations.
1318                  */
1319                 for (i = xfrm_nr-1, k = 0; i >= 0; i--) {
1320                         k = xfrm_policy_ok(tpp[i], sp, k, family);
1321                         if (k < 0) {
1322                                 if (k < -1 && xerr_idxp)
1323                                         *xerr_idxp = -(2+k);
1324                                 goto reject;
1325                         }
1326                 }
1327
1328                 if (secpath_has_nontransport(sp, k, xerr_idxp))
1329                         goto reject;
1330
1331                 xfrm_pols_put(pols, npols);
1332                 return 1;
1333         }
1334
1335 reject:
1336         xfrm_secpath_reject(xerr_idx, skb, &fl);
1337 reject_error:
1338         xfrm_pols_put(pols, npols);
1339         return 0;
1340 }
1341 EXPORT_SYMBOL(__xfrm_policy_check);
1342
1343 int __xfrm_route_forward(struct sk_buff *skb, unsigned short family)
1344 {
1345         struct flowi fl;
1346
1347         if (xfrm_decode_session(skb, &fl, family) < 0)
1348                 return 0;
1349
1350         return xfrm_lookup(&skb->dst, &fl, NULL, 0) == 0;
1351 }
1352 EXPORT_SYMBOL(__xfrm_route_forward);
1353
1354 /* Optimize later using cookies and generation ids. */
1355
1356 static struct dst_entry *xfrm_dst_check(struct dst_entry *dst, u32 cookie)
1357 {
1358         /* Code (such as __xfrm4_bundle_create()) sets dst->obsolete
1359          * to "-1" to force all XFRM destinations to get validated by
1360          * dst_ops->check on every use.  We do this because when a
1361          * normal route referenced by an XFRM dst is obsoleted we do
1362          * not go looking around for all parent referencing XFRM dsts
1363          * so that we can invalidate them.  It is just too much work.
1364          * Instead we make the checks here on every use.  For example:
1365          *
1366          *      XFRM dst A --> IPv4 dst X
1367          *
1368          * X is the "xdst->route" of A (X is also the "dst->path" of A
1369          * in this example).  If X is marked obsolete, "A" will not
1370          * notice.  That's what we are validating here via the
1371          * stale_bundle() check.
1372          *
1373          * When a policy's bundle is pruned, we dst_free() the XFRM
1374          * dst which causes it's ->obsolete field to be set to a
1375          * positive non-zero integer.  If an XFRM dst has been pruned
1376          * like this, we want to force a new route lookup.
1377          */
1378         if (dst->obsolete < 0 && !stale_bundle(dst))
1379                 return dst;
1380
1381         return NULL;
1382 }
1383
1384 static int stale_bundle(struct dst_entry *dst)
1385 {
1386         return !xfrm_bundle_ok((struct xfrm_dst *)dst, NULL, AF_UNSPEC, 0);
1387 }
1388
1389 void xfrm_dst_ifdown(struct dst_entry *dst, struct net_device *dev)
1390 {
1391         while ((dst = dst->child) && dst->xfrm && dst->dev == dev) {
1392                 dst->dev = &loopback_dev;
1393                 dev_hold(&loopback_dev);
1394                 dev_put(dev);
1395         }
1396 }
1397 EXPORT_SYMBOL(xfrm_dst_ifdown);
1398
1399 static void xfrm_link_failure(struct sk_buff *skb)
1400 {
1401         /* Impossible. Such dst must be popped before reaches point of failure. */
1402         return;
1403 }
1404
1405 static struct dst_entry *xfrm_negative_advice(struct dst_entry *dst)
1406 {
1407         if (dst) {
1408                 if (dst->obsolete) {
1409                         dst_release(dst);
1410                         dst = NULL;
1411                 }
1412         }
1413         return dst;
1414 }
1415
1416 static void xfrm_prune_bundles(int (*func)(struct dst_entry *))
1417 {
1418         int i;
1419         struct xfrm_policy *pol;
1420         struct dst_entry *dst, **dstp, *gc_list = NULL;
1421
1422         read_lock_bh(&xfrm_policy_lock);
1423         for (i=0; i<2*XFRM_POLICY_MAX; i++) {
1424 #ifdef CONFIG_XFRM_SUB_POLICY
1425                 for (pol = xfrm_policy_list_sub[i]; pol; pol = pol->next) {
1426                         write_lock(&pol->lock);
1427                         dstp = &pol->bundles;
1428                         while ((dst=*dstp) != NULL) {
1429                                 if (func(dst)) {
1430                                         *dstp = dst->next;
1431                                         dst->next = gc_list;
1432                                         gc_list = dst;
1433                                 } else {
1434                                         dstp = &dst->next;
1435                                 }
1436                         }
1437                         write_unlock(&pol->lock);
1438                 }
1439
1440 #endif
1441                 for (pol = xfrm_policy_list[i]; pol; pol = pol->next) {
1442                         write_lock(&pol->lock);
1443                         dstp = &pol->bundles;
1444                         while ((dst=*dstp) != NULL) {
1445                                 if (func(dst)) {
1446                                         *dstp = dst->next;
1447                                         dst->next = gc_list;
1448                                         gc_list = dst;
1449                                 } else {
1450                                         dstp = &dst->next;
1451                                 }
1452                         }
1453                         write_unlock(&pol->lock);
1454                 }
1455         }
1456         read_unlock_bh(&xfrm_policy_lock);
1457
1458         while (gc_list) {
1459                 dst = gc_list;
1460                 gc_list = dst->next;
1461                 dst_free(dst);
1462         }
1463 }
1464
1465 static int unused_bundle(struct dst_entry *dst)
1466 {
1467         return !atomic_read(&dst->__refcnt);
1468 }
1469
1470 static void __xfrm_garbage_collect(void)
1471 {
1472         xfrm_prune_bundles(unused_bundle);
1473 }
1474
1475 int xfrm_flush_bundles(void)
1476 {
1477         xfrm_prune_bundles(stale_bundle);
1478         return 0;
1479 }
1480
1481 static int always_true(struct dst_entry *dst)
1482 {
1483         return 1;
1484 }
1485
1486 void xfrm_flush_all_bundles(void)
1487 {
1488         xfrm_prune_bundles(always_true);
1489 }
1490
1491 void xfrm_init_pmtu(struct dst_entry *dst)
1492 {
1493         do {
1494                 struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
1495                 u32 pmtu, route_mtu_cached;
1496
1497                 pmtu = dst_mtu(dst->child);
1498                 xdst->child_mtu_cached = pmtu;
1499
1500                 pmtu = xfrm_state_mtu(dst->xfrm, pmtu);
1501
1502                 route_mtu_cached = dst_mtu(xdst->route);
1503                 xdst->route_mtu_cached = route_mtu_cached;
1504
1505                 if (pmtu > route_mtu_cached)
1506                         pmtu = route_mtu_cached;
1507
1508                 dst->metrics[RTAX_MTU-1] = pmtu;
1509         } while ((dst = dst->next));
1510 }
1511
1512 EXPORT_SYMBOL(xfrm_init_pmtu);
1513
1514 /* Check that the bundle accepts the flow and its components are
1515  * still valid.
1516  */
1517
1518 int xfrm_bundle_ok(struct xfrm_dst *first, struct flowi *fl, int family, int strict)
1519 {
1520         struct dst_entry *dst = &first->u.dst;
1521         struct xfrm_dst *last;
1522         u32 mtu;
1523
1524         if (!dst_check(dst->path, ((struct xfrm_dst *)dst)->path_cookie) ||
1525             (dst->dev && !netif_running(dst->dev)))
1526                 return 0;
1527
1528         last = NULL;
1529
1530         do {
1531                 struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
1532
1533                 if (fl && !xfrm_selector_match(&dst->xfrm->sel, fl, family))
1534                         return 0;
1535                 if (fl && !security_xfrm_flow_state_match(fl, dst->xfrm))
1536                         return 0;
1537                 if (dst->xfrm->km.state != XFRM_STATE_VALID)
1538                         return 0;
1539
1540                 if (strict && fl && dst->xfrm->props.mode != XFRM_MODE_TUNNEL &&
1541                     !xfrm_state_addr_flow_check(dst->xfrm, fl, family))
1542                         return 0;
1543
1544                 mtu = dst_mtu(dst->child);
1545                 if (xdst->child_mtu_cached != mtu) {
1546                         last = xdst;
1547                         xdst->child_mtu_cached = mtu;
1548                 }
1549
1550                 if (!dst_check(xdst->route, xdst->route_cookie))
1551                         return 0;
1552                 mtu = dst_mtu(xdst->route);
1553                 if (xdst->route_mtu_cached != mtu) {
1554                         last = xdst;
1555                         xdst->route_mtu_cached = mtu;
1556                 }
1557
1558                 dst = dst->child;
1559         } while (dst->xfrm);
1560
1561         if (likely(!last))
1562                 return 1;
1563
1564         mtu = last->child_mtu_cached;
1565         for (;;) {
1566                 dst = &last->u.dst;
1567
1568                 mtu = xfrm_state_mtu(dst->xfrm, mtu);
1569                 if (mtu > last->route_mtu_cached)
1570                         mtu = last->route_mtu_cached;
1571                 dst->metrics[RTAX_MTU-1] = mtu;
1572
1573                 if (last == first)
1574                         break;
1575
1576                 last = last->u.next;
1577                 last->child_mtu_cached = mtu;
1578         }
1579
1580         return 1;
1581 }
1582
1583 EXPORT_SYMBOL(xfrm_bundle_ok);
1584
1585 int xfrm_policy_register_afinfo(struct xfrm_policy_afinfo *afinfo)
1586 {
1587         int err = 0;
1588         if (unlikely(afinfo == NULL))
1589                 return -EINVAL;
1590         if (unlikely(afinfo->family >= NPROTO))
1591                 return -EAFNOSUPPORT;
1592         write_lock_bh(&xfrm_policy_afinfo_lock);
1593         if (unlikely(xfrm_policy_afinfo[afinfo->family] != NULL))
1594                 err = -ENOBUFS;
1595         else {
1596                 struct dst_ops *dst_ops = afinfo->dst_ops;
1597                 if (likely(dst_ops->kmem_cachep == NULL))
1598                         dst_ops->kmem_cachep = xfrm_dst_cache;
1599                 if (likely(dst_ops->check == NULL))
1600                         dst_ops->check = xfrm_dst_check;
1601                 if (likely(dst_ops->negative_advice == NULL))
1602                         dst_ops->negative_advice = xfrm_negative_advice;
1603                 if (likely(dst_ops->link_failure == NULL))
1604                         dst_ops->link_failure = xfrm_link_failure;
1605                 if (likely(afinfo->garbage_collect == NULL))
1606                         afinfo->garbage_collect = __xfrm_garbage_collect;
1607                 xfrm_policy_afinfo[afinfo->family] = afinfo;
1608         }
1609         write_unlock_bh(&xfrm_policy_afinfo_lock);
1610         return err;
1611 }
1612 EXPORT_SYMBOL(xfrm_policy_register_afinfo);
1613
1614 int xfrm_policy_unregister_afinfo(struct xfrm_policy_afinfo *afinfo)
1615 {
1616         int err = 0;
1617         if (unlikely(afinfo == NULL))
1618                 return -EINVAL;
1619         if (unlikely(afinfo->family >= NPROTO))
1620                 return -EAFNOSUPPORT;
1621         write_lock_bh(&xfrm_policy_afinfo_lock);
1622         if (likely(xfrm_policy_afinfo[afinfo->family] != NULL)) {
1623                 if (unlikely(xfrm_policy_afinfo[afinfo->family] != afinfo))
1624                         err = -EINVAL;
1625                 else {
1626                         struct dst_ops *dst_ops = afinfo->dst_ops;
1627                         xfrm_policy_afinfo[afinfo->family] = NULL;
1628                         dst_ops->kmem_cachep = NULL;
1629                         dst_ops->check = NULL;
1630                         dst_ops->negative_advice = NULL;
1631                         dst_ops->link_failure = NULL;
1632                         afinfo->garbage_collect = NULL;
1633                 }
1634         }
1635         write_unlock_bh(&xfrm_policy_afinfo_lock);
1636         return err;
1637 }
1638 EXPORT_SYMBOL(xfrm_policy_unregister_afinfo);
1639
1640 static struct xfrm_policy_afinfo *xfrm_policy_get_afinfo(unsigned short family)
1641 {
1642         struct xfrm_policy_afinfo *afinfo;
1643         if (unlikely(family >= NPROTO))
1644                 return NULL;
1645         read_lock(&xfrm_policy_afinfo_lock);
1646         afinfo = xfrm_policy_afinfo[family];
1647         if (unlikely(!afinfo))
1648                 read_unlock(&xfrm_policy_afinfo_lock);
1649         return afinfo;
1650 }
1651
1652 static void xfrm_policy_put_afinfo(struct xfrm_policy_afinfo *afinfo)
1653 {
1654         read_unlock(&xfrm_policy_afinfo_lock);
1655 }
1656
1657 static struct xfrm_policy_afinfo *xfrm_policy_lock_afinfo(unsigned int family)
1658 {
1659         struct xfrm_policy_afinfo *afinfo;
1660         if (unlikely(family >= NPROTO))
1661                 return NULL;
1662         write_lock_bh(&xfrm_policy_afinfo_lock);
1663         afinfo = xfrm_policy_afinfo[family];
1664         if (unlikely(!afinfo))
1665                 write_unlock_bh(&xfrm_policy_afinfo_lock);
1666         return afinfo;
1667 }
1668
1669 static void xfrm_policy_unlock_afinfo(struct xfrm_policy_afinfo *afinfo)
1670 {
1671         write_unlock_bh(&xfrm_policy_afinfo_lock);
1672 }
1673
1674 static int xfrm_dev_event(struct notifier_block *this, unsigned long event, void *ptr)
1675 {
1676         switch (event) {
1677         case NETDEV_DOWN:
1678                 xfrm_flush_bundles();
1679         }
1680         return NOTIFY_DONE;
1681 }
1682
1683 static struct notifier_block xfrm_dev_notifier = {
1684         xfrm_dev_event,
1685         NULL,
1686         0
1687 };
1688
1689 static void __init xfrm_policy_init(void)
1690 {
1691         xfrm_dst_cache = kmem_cache_create("xfrm_dst_cache",
1692                                            sizeof(struct xfrm_dst),
1693                                            0, SLAB_HWCACHE_ALIGN,
1694                                            NULL, NULL);
1695         if (!xfrm_dst_cache)
1696                 panic("XFRM: failed to allocate xfrm_dst_cache\n");
1697
1698         INIT_WORK(&xfrm_policy_gc_work, xfrm_policy_gc_task, NULL);
1699         register_netdevice_notifier(&xfrm_dev_notifier);
1700 }
1701
1702 void __init xfrm_init(void)
1703 {
1704         xfrm_state_init();
1705         xfrm_policy_init();
1706         xfrm_input_init();
1707 }
1708