Merge master.kernel.org:/pub/scm/linux/kernel/git/davem/net-2.6
[linux-2.6.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 <linux/cache.h>
26 #include <net/xfrm.h>
27 #include <net/ip.h>
28 #include <linux/audit.h>
29
30 #include "xfrm_hash.h"
31
32 DEFINE_MUTEX(xfrm_cfg_mutex);
33 EXPORT_SYMBOL(xfrm_cfg_mutex);
34
35 static DEFINE_RWLOCK(xfrm_policy_lock);
36
37 unsigned int xfrm_policy_count[XFRM_POLICY_MAX*2];
38 EXPORT_SYMBOL(xfrm_policy_count);
39
40 static DEFINE_RWLOCK(xfrm_policy_afinfo_lock);
41 static struct xfrm_policy_afinfo *xfrm_policy_afinfo[NPROTO];
42
43 static struct kmem_cache *xfrm_dst_cache __read_mostly;
44
45 static struct work_struct xfrm_policy_gc_work;
46 static HLIST_HEAD(xfrm_policy_gc_list);
47 static DEFINE_SPINLOCK(xfrm_policy_gc_lock);
48
49 static struct xfrm_policy_afinfo *xfrm_policy_get_afinfo(unsigned short family);
50 static void xfrm_policy_put_afinfo(struct xfrm_policy_afinfo *afinfo);
51 static struct xfrm_policy_afinfo *xfrm_policy_lock_afinfo(unsigned int family);
52 static void xfrm_policy_unlock_afinfo(struct xfrm_policy_afinfo *afinfo);
53
54 static inline int
55 __xfrm4_selector_match(struct xfrm_selector *sel, struct flowi *fl)
56 {
57         return  addr_match(&fl->fl4_dst, &sel->daddr, sel->prefixlen_d) &&
58                 addr_match(&fl->fl4_src, &sel->saddr, sel->prefixlen_s) &&
59                 !((xfrm_flowi_dport(fl) ^ sel->dport) & sel->dport_mask) &&
60                 !((xfrm_flowi_sport(fl) ^ sel->sport) & sel->sport_mask) &&
61                 (fl->proto == sel->proto || !sel->proto) &&
62                 (fl->oif == sel->ifindex || !sel->ifindex);
63 }
64
65 static inline int
66 __xfrm6_selector_match(struct xfrm_selector *sel, struct flowi *fl)
67 {
68         return  addr_match(&fl->fl6_dst, &sel->daddr, sel->prefixlen_d) &&
69                 addr_match(&fl->fl6_src, &sel->saddr, sel->prefixlen_s) &&
70                 !((xfrm_flowi_dport(fl) ^ sel->dport) & sel->dport_mask) &&
71                 !((xfrm_flowi_sport(fl) ^ sel->sport) & sel->sport_mask) &&
72                 (fl->proto == sel->proto || !sel->proto) &&
73                 (fl->oif == sel->ifindex || !sel->ifindex);
74 }
75
76 int xfrm_selector_match(struct xfrm_selector *sel, struct flowi *fl,
77                     unsigned short family)
78 {
79         switch (family) {
80         case AF_INET:
81                 return __xfrm4_selector_match(sel, fl);
82         case AF_INET6:
83                 return __xfrm6_selector_match(sel, fl);
84         }
85         return 0;
86 }
87
88 int xfrm_register_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 (likely(typemap[type->proto] == NULL))
99                 typemap[type->proto] = type;
100         else
101                 err = -EEXIST;
102         xfrm_policy_unlock_afinfo(afinfo);
103         return err;
104 }
105 EXPORT_SYMBOL(xfrm_register_type);
106
107 int xfrm_unregister_type(struct xfrm_type *type, unsigned short family)
108 {
109         struct xfrm_policy_afinfo *afinfo = xfrm_policy_lock_afinfo(family);
110         struct xfrm_type **typemap;
111         int err = 0;
112
113         if (unlikely(afinfo == NULL))
114                 return -EAFNOSUPPORT;
115         typemap = afinfo->type_map;
116
117         if (unlikely(typemap[type->proto] != type))
118                 err = -ENOENT;
119         else
120                 typemap[type->proto] = NULL;
121         xfrm_policy_unlock_afinfo(afinfo);
122         return err;
123 }
124 EXPORT_SYMBOL(xfrm_unregister_type);
125
126 struct xfrm_type *xfrm_get_type(u8 proto, unsigned short family)
127 {
128         struct xfrm_policy_afinfo *afinfo;
129         struct xfrm_type **typemap;
130         struct xfrm_type *type;
131         int modload_attempted = 0;
132
133 retry:
134         afinfo = xfrm_policy_get_afinfo(family);
135         if (unlikely(afinfo == NULL))
136                 return NULL;
137         typemap = afinfo->type_map;
138
139         type = typemap[proto];
140         if (unlikely(type && !try_module_get(type->owner)))
141                 type = NULL;
142         if (!type && !modload_attempted) {
143                 xfrm_policy_put_afinfo(afinfo);
144                 request_module("xfrm-type-%d-%d",
145                                (int) family, (int) proto);
146                 modload_attempted = 1;
147                 goto retry;
148         }
149
150         xfrm_policy_put_afinfo(afinfo);
151         return type;
152 }
153
154 int xfrm_dst_lookup(struct xfrm_dst **dst, struct flowi *fl, 
155                     unsigned short family)
156 {
157         struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
158         int err = 0;
159
160         if (unlikely(afinfo == NULL))
161                 return -EAFNOSUPPORT;
162
163         if (likely(afinfo->dst_lookup != NULL))
164                 err = afinfo->dst_lookup(dst, fl);
165         else
166                 err = -EINVAL;
167         xfrm_policy_put_afinfo(afinfo);
168         return err;
169 }
170 EXPORT_SYMBOL(xfrm_dst_lookup);
171
172 void xfrm_put_type(struct xfrm_type *type)
173 {
174         module_put(type->owner);
175 }
176
177 int xfrm_register_mode(struct xfrm_mode *mode, int family)
178 {
179         struct xfrm_policy_afinfo *afinfo;
180         struct xfrm_mode **modemap;
181         int err;
182
183         if (unlikely(mode->encap >= XFRM_MODE_MAX))
184                 return -EINVAL;
185
186         afinfo = xfrm_policy_lock_afinfo(family);
187         if (unlikely(afinfo == NULL))
188                 return -EAFNOSUPPORT;
189
190         err = -EEXIST;
191         modemap = afinfo->mode_map;
192         if (likely(modemap[mode->encap] == NULL)) {
193                 modemap[mode->encap] = mode;
194                 err = 0;
195         }
196
197         xfrm_policy_unlock_afinfo(afinfo);
198         return err;
199 }
200 EXPORT_SYMBOL(xfrm_register_mode);
201
202 int xfrm_unregister_mode(struct xfrm_mode *mode, int family)
203 {
204         struct xfrm_policy_afinfo *afinfo;
205         struct xfrm_mode **modemap;
206         int err;
207
208         if (unlikely(mode->encap >= XFRM_MODE_MAX))
209                 return -EINVAL;
210
211         afinfo = xfrm_policy_lock_afinfo(family);
212         if (unlikely(afinfo == NULL))
213                 return -EAFNOSUPPORT;
214
215         err = -ENOENT;
216         modemap = afinfo->mode_map;
217         if (likely(modemap[mode->encap] == mode)) {
218                 modemap[mode->encap] = NULL;
219                 err = 0;
220         }
221
222         xfrm_policy_unlock_afinfo(afinfo);
223         return err;
224 }
225 EXPORT_SYMBOL(xfrm_unregister_mode);
226
227 struct xfrm_mode *xfrm_get_mode(unsigned int encap, int family)
228 {
229         struct xfrm_policy_afinfo *afinfo;
230         struct xfrm_mode *mode;
231         int modload_attempted = 0;
232
233         if (unlikely(encap >= XFRM_MODE_MAX))
234                 return NULL;
235
236 retry:
237         afinfo = xfrm_policy_get_afinfo(family);
238         if (unlikely(afinfo == NULL))
239                 return NULL;
240
241         mode = afinfo->mode_map[encap];
242         if (unlikely(mode && !try_module_get(mode->owner)))
243                 mode = NULL;
244         if (!mode && !modload_attempted) {
245                 xfrm_policy_put_afinfo(afinfo);
246                 request_module("xfrm-mode-%d-%d", family, encap);
247                 modload_attempted = 1;
248                 goto retry;
249         }
250
251         xfrm_policy_put_afinfo(afinfo);
252         return mode;
253 }
254
255 void xfrm_put_mode(struct xfrm_mode *mode)
256 {
257         module_put(mode->owner);
258 }
259
260 static inline unsigned long make_jiffies(long secs)
261 {
262         if (secs >= (MAX_SCHEDULE_TIMEOUT-1)/HZ)
263                 return MAX_SCHEDULE_TIMEOUT-1;
264         else
265                 return secs*HZ;
266 }
267
268 static void xfrm_policy_timer(unsigned long data)
269 {
270         struct xfrm_policy *xp = (struct xfrm_policy*)data;
271         unsigned long now = (unsigned long)xtime.tv_sec;
272         long next = LONG_MAX;
273         int warn = 0;
274         int dir;
275
276         read_lock(&xp->lock);
277
278         if (xp->dead)
279                 goto out;
280
281         dir = xfrm_policy_id2dir(xp->index);
282
283         if (xp->lft.hard_add_expires_seconds) {
284                 long tmo = xp->lft.hard_add_expires_seconds +
285                         xp->curlft.add_time - now;
286                 if (tmo <= 0)
287                         goto expired;
288                 if (tmo < next)
289                         next = tmo;
290         }
291         if (xp->lft.hard_use_expires_seconds) {
292                 long tmo = xp->lft.hard_use_expires_seconds +
293                         (xp->curlft.use_time ? : xp->curlft.add_time) - now;
294                 if (tmo <= 0)
295                         goto expired;
296                 if (tmo < next)
297                         next = tmo;
298         }
299         if (xp->lft.soft_add_expires_seconds) {
300                 long tmo = xp->lft.soft_add_expires_seconds +
301                         xp->curlft.add_time - now;
302                 if (tmo <= 0) {
303                         warn = 1;
304                         tmo = XFRM_KM_TIMEOUT;
305                 }
306                 if (tmo < next)
307                         next = tmo;
308         }
309         if (xp->lft.soft_use_expires_seconds) {
310                 long tmo = xp->lft.soft_use_expires_seconds +
311                         (xp->curlft.use_time ? : xp->curlft.add_time) - now;
312                 if (tmo <= 0) {
313                         warn = 1;
314                         tmo = XFRM_KM_TIMEOUT;
315                 }
316                 if (tmo < next)
317                         next = tmo;
318         }
319
320         if (warn)
321                 km_policy_expired(xp, dir, 0, 0);
322         if (next != LONG_MAX &&
323             !mod_timer(&xp->timer, jiffies + make_jiffies(next)))
324                 xfrm_pol_hold(xp);
325
326 out:
327         read_unlock(&xp->lock);
328         xfrm_pol_put(xp);
329         return;
330
331 expired:
332         read_unlock(&xp->lock);
333         if (!xfrm_policy_delete(xp, dir))
334                 km_policy_expired(xp, dir, 1, 0);
335         xfrm_pol_put(xp);
336 }
337
338
339 /* Allocate xfrm_policy. Not used here, it is supposed to be used by pfkeyv2
340  * SPD calls.
341  */
342
343 struct xfrm_policy *xfrm_policy_alloc(gfp_t gfp)
344 {
345         struct xfrm_policy *policy;
346
347         policy = kzalloc(sizeof(struct xfrm_policy), gfp);
348
349         if (policy) {
350                 INIT_HLIST_NODE(&policy->bydst);
351                 INIT_HLIST_NODE(&policy->byidx);
352                 rwlock_init(&policy->lock);
353                 atomic_set(&policy->refcnt, 1);
354                 init_timer(&policy->timer);
355                 policy->timer.data = (unsigned long)policy;
356                 policy->timer.function = xfrm_policy_timer;
357         }
358         return policy;
359 }
360 EXPORT_SYMBOL(xfrm_policy_alloc);
361
362 /* Destroy xfrm_policy: descendant resources must be released to this moment. */
363
364 void __xfrm_policy_destroy(struct xfrm_policy *policy)
365 {
366         BUG_ON(!policy->dead);
367
368         BUG_ON(policy->bundles);
369
370         if (del_timer(&policy->timer))
371                 BUG();
372
373         security_xfrm_policy_free(policy);
374         kfree(policy);
375 }
376 EXPORT_SYMBOL(__xfrm_policy_destroy);
377
378 static void xfrm_policy_gc_kill(struct xfrm_policy *policy)
379 {
380         struct dst_entry *dst;
381
382         while ((dst = policy->bundles) != NULL) {
383                 policy->bundles = dst->next;
384                 dst_free(dst);
385         }
386
387         if (del_timer(&policy->timer))
388                 atomic_dec(&policy->refcnt);
389
390         if (atomic_read(&policy->refcnt) > 1)
391                 flow_cache_flush();
392
393         xfrm_pol_put(policy);
394 }
395
396 static void xfrm_policy_gc_task(struct work_struct *work)
397 {
398         struct xfrm_policy *policy;
399         struct hlist_node *entry, *tmp;
400         struct hlist_head gc_list;
401
402         spin_lock_bh(&xfrm_policy_gc_lock);
403         gc_list.first = xfrm_policy_gc_list.first;
404         INIT_HLIST_HEAD(&xfrm_policy_gc_list);
405         spin_unlock_bh(&xfrm_policy_gc_lock);
406
407         hlist_for_each_entry_safe(policy, entry, tmp, &gc_list, bydst)
408                 xfrm_policy_gc_kill(policy);
409 }
410
411 /* Rule must be locked. Release descentant resources, announce
412  * entry dead. The rule must be unlinked from lists to the moment.
413  */
414
415 static void xfrm_policy_kill(struct xfrm_policy *policy)
416 {
417         int dead;
418
419         write_lock_bh(&policy->lock);
420         dead = policy->dead;
421         policy->dead = 1;
422         write_unlock_bh(&policy->lock);
423
424         if (unlikely(dead)) {
425                 WARN_ON(1);
426                 return;
427         }
428
429         spin_lock(&xfrm_policy_gc_lock);
430         hlist_add_head(&policy->bydst, &xfrm_policy_gc_list);
431         spin_unlock(&xfrm_policy_gc_lock);
432
433         schedule_work(&xfrm_policy_gc_work);
434 }
435
436 struct xfrm_policy_hash {
437         struct hlist_head       *table;
438         unsigned int            hmask;
439 };
440
441 static struct hlist_head xfrm_policy_inexact[XFRM_POLICY_MAX*2];
442 static struct xfrm_policy_hash xfrm_policy_bydst[XFRM_POLICY_MAX*2] __read_mostly;
443 static struct hlist_head *xfrm_policy_byidx __read_mostly;
444 static unsigned int xfrm_idx_hmask __read_mostly;
445 static unsigned int xfrm_policy_hashmax __read_mostly = 1 * 1024 * 1024;
446
447 static inline unsigned int idx_hash(u32 index)
448 {
449         return __idx_hash(index, xfrm_idx_hmask);
450 }
451
452 static struct hlist_head *policy_hash_bysel(struct xfrm_selector *sel, unsigned short family, int dir)
453 {
454         unsigned int hmask = xfrm_policy_bydst[dir].hmask;
455         unsigned int hash = __sel_hash(sel, family, hmask);
456
457         return (hash == hmask + 1 ?
458                 &xfrm_policy_inexact[dir] :
459                 xfrm_policy_bydst[dir].table + hash);
460 }
461
462 static struct hlist_head *policy_hash_direct(xfrm_address_t *daddr, xfrm_address_t *saddr, unsigned short family, int dir)
463 {
464         unsigned int hmask = xfrm_policy_bydst[dir].hmask;
465         unsigned int hash = __addr_hash(daddr, saddr, family, hmask);
466
467         return xfrm_policy_bydst[dir].table + hash;
468 }
469
470 static void xfrm_dst_hash_transfer(struct hlist_head *list,
471                                    struct hlist_head *ndsttable,
472                                    unsigned int nhashmask)
473 {
474         struct hlist_node *entry, *tmp;
475         struct xfrm_policy *pol;
476
477         hlist_for_each_entry_safe(pol, entry, tmp, list, bydst) {
478                 unsigned int h;
479
480                 h = __addr_hash(&pol->selector.daddr, &pol->selector.saddr,
481                                 pol->family, nhashmask);
482                 hlist_add_head(&pol->bydst, ndsttable+h);
483         }
484 }
485
486 static void xfrm_idx_hash_transfer(struct hlist_head *list,
487                                    struct hlist_head *nidxtable,
488                                    unsigned int nhashmask)
489 {
490         struct hlist_node *entry, *tmp;
491         struct xfrm_policy *pol;
492
493         hlist_for_each_entry_safe(pol, entry, tmp, list, byidx) {
494                 unsigned int h;
495
496                 h = __idx_hash(pol->index, nhashmask);
497                 hlist_add_head(&pol->byidx, nidxtable+h);
498         }
499 }
500
501 static unsigned long xfrm_new_hash_mask(unsigned int old_hmask)
502 {
503         return ((old_hmask + 1) << 1) - 1;
504 }
505
506 static void xfrm_bydst_resize(int dir)
507 {
508         unsigned int hmask = xfrm_policy_bydst[dir].hmask;
509         unsigned int nhashmask = xfrm_new_hash_mask(hmask);
510         unsigned int nsize = (nhashmask + 1) * sizeof(struct hlist_head);
511         struct hlist_head *odst = xfrm_policy_bydst[dir].table;
512         struct hlist_head *ndst = xfrm_hash_alloc(nsize);
513         int i;
514
515         if (!ndst)
516                 return;
517
518         write_lock_bh(&xfrm_policy_lock);
519
520         for (i = hmask; i >= 0; i--)
521                 xfrm_dst_hash_transfer(odst + i, ndst, nhashmask);
522
523         xfrm_policy_bydst[dir].table = ndst;
524         xfrm_policy_bydst[dir].hmask = nhashmask;
525
526         write_unlock_bh(&xfrm_policy_lock);
527
528         xfrm_hash_free(odst, (hmask + 1) * sizeof(struct hlist_head));
529 }
530
531 static void xfrm_byidx_resize(int total)
532 {
533         unsigned int hmask = xfrm_idx_hmask;
534         unsigned int nhashmask = xfrm_new_hash_mask(hmask);
535         unsigned int nsize = (nhashmask + 1) * sizeof(struct hlist_head);
536         struct hlist_head *oidx = xfrm_policy_byidx;
537         struct hlist_head *nidx = xfrm_hash_alloc(nsize);
538         int i;
539
540         if (!nidx)
541                 return;
542
543         write_lock_bh(&xfrm_policy_lock);
544
545         for (i = hmask; i >= 0; i--)
546                 xfrm_idx_hash_transfer(oidx + i, nidx, nhashmask);
547
548         xfrm_policy_byidx = nidx;
549         xfrm_idx_hmask = nhashmask;
550
551         write_unlock_bh(&xfrm_policy_lock);
552
553         xfrm_hash_free(oidx, (hmask + 1) * sizeof(struct hlist_head));
554 }
555
556 static inline int xfrm_bydst_should_resize(int dir, int *total)
557 {
558         unsigned int cnt = xfrm_policy_count[dir];
559         unsigned int hmask = xfrm_policy_bydst[dir].hmask;
560
561         if (total)
562                 *total += cnt;
563
564         if ((hmask + 1) < xfrm_policy_hashmax &&
565             cnt > hmask)
566                 return 1;
567
568         return 0;
569 }
570
571 static inline int xfrm_byidx_should_resize(int total)
572 {
573         unsigned int hmask = xfrm_idx_hmask;
574
575         if ((hmask + 1) < xfrm_policy_hashmax &&
576             total > hmask)
577                 return 1;
578
579         return 0;
580 }
581
582 static DEFINE_MUTEX(hash_resize_mutex);
583
584 static void xfrm_hash_resize(struct work_struct *__unused)
585 {
586         int dir, total;
587
588         mutex_lock(&hash_resize_mutex);
589
590         total = 0;
591         for (dir = 0; dir < XFRM_POLICY_MAX * 2; dir++) {
592                 if (xfrm_bydst_should_resize(dir, &total))
593                         xfrm_bydst_resize(dir);
594         }
595         if (xfrm_byidx_should_resize(total))
596                 xfrm_byidx_resize(total);
597
598         mutex_unlock(&hash_resize_mutex);
599 }
600
601 static DECLARE_WORK(xfrm_hash_work, xfrm_hash_resize);
602
603 /* Generate new index... KAME seems to generate them ordered by cost
604  * of an absolute inpredictability of ordering of rules. This will not pass. */
605 static u32 xfrm_gen_index(u8 type, int dir)
606 {
607         static u32 idx_generator;
608
609         for (;;) {
610                 struct hlist_node *entry;
611                 struct hlist_head *list;
612                 struct xfrm_policy *p;
613                 u32 idx;
614                 int found;
615
616                 idx = (idx_generator | dir);
617                 idx_generator += 8;
618                 if (idx == 0)
619                         idx = 8;
620                 list = xfrm_policy_byidx + idx_hash(idx);
621                 found = 0;
622                 hlist_for_each_entry(p, entry, list, byidx) {
623                         if (p->index == idx) {
624                                 found = 1;
625                                 break;
626                         }
627                 }
628                 if (!found)
629                         return idx;
630         }
631 }
632
633 static inline int selector_cmp(struct xfrm_selector *s1, struct xfrm_selector *s2)
634 {
635         u32 *p1 = (u32 *) s1;
636         u32 *p2 = (u32 *) s2;
637         int len = sizeof(struct xfrm_selector) / sizeof(u32);
638         int i;
639
640         for (i = 0; i < len; i++) {
641                 if (p1[i] != p2[i])
642                         return 1;
643         }
644
645         return 0;
646 }
647
648 int xfrm_policy_insert(int dir, struct xfrm_policy *policy, int excl)
649 {
650         struct xfrm_policy *pol;
651         struct xfrm_policy *delpol;
652         struct hlist_head *chain;
653         struct hlist_node *entry, *newpos, *last;
654         struct dst_entry *gc_list;
655
656         write_lock_bh(&xfrm_policy_lock);
657         chain = policy_hash_bysel(&policy->selector, policy->family, dir);
658         delpol = NULL;
659         newpos = NULL;
660         last = NULL;
661         hlist_for_each_entry(pol, entry, chain, bydst) {
662                 if (!delpol &&
663                     pol->type == policy->type &&
664                     !selector_cmp(&pol->selector, &policy->selector) &&
665                     xfrm_sec_ctx_match(pol->security, policy->security)) {
666                         if (excl) {
667                                 write_unlock_bh(&xfrm_policy_lock);
668                                 return -EEXIST;
669                         }
670                         delpol = pol;
671                         if (policy->priority > pol->priority)
672                                 continue;
673                 } else if (policy->priority >= pol->priority) {
674                         last = &pol->bydst;
675                         continue;
676                 }
677                 if (!newpos)
678                         newpos = &pol->bydst;
679                 if (delpol)
680                         break;
681                 last = &pol->bydst;
682         }
683         if (!newpos)
684                 newpos = last;
685         if (newpos)
686                 hlist_add_after(newpos, &policy->bydst);
687         else
688                 hlist_add_head(&policy->bydst, chain);
689         xfrm_pol_hold(policy);
690         xfrm_policy_count[dir]++;
691         atomic_inc(&flow_cache_genid);
692         if (delpol) {
693                 hlist_del(&delpol->bydst);
694                 hlist_del(&delpol->byidx);
695                 xfrm_policy_count[dir]--;
696         }
697         policy->index = delpol ? delpol->index : xfrm_gen_index(policy->type, dir);
698         hlist_add_head(&policy->byidx, xfrm_policy_byidx+idx_hash(policy->index));
699         policy->curlft.add_time = (unsigned long)xtime.tv_sec;
700         policy->curlft.use_time = 0;
701         if (!mod_timer(&policy->timer, jiffies + HZ))
702                 xfrm_pol_hold(policy);
703         write_unlock_bh(&xfrm_policy_lock);
704
705         if (delpol)
706                 xfrm_policy_kill(delpol);
707         else if (xfrm_bydst_should_resize(dir, NULL))
708                 schedule_work(&xfrm_hash_work);
709
710         read_lock_bh(&xfrm_policy_lock);
711         gc_list = NULL;
712         entry = &policy->bydst;
713         hlist_for_each_entry_continue(policy, entry, bydst) {
714                 struct dst_entry *dst;
715
716                 write_lock(&policy->lock);
717                 dst = policy->bundles;
718                 if (dst) {
719                         struct dst_entry *tail = dst;
720                         while (tail->next)
721                                 tail = tail->next;
722                         tail->next = gc_list;
723                         gc_list = dst;
724
725                         policy->bundles = NULL;
726                 }
727                 write_unlock(&policy->lock);
728         }
729         read_unlock_bh(&xfrm_policy_lock);
730
731         while (gc_list) {
732                 struct dst_entry *dst = gc_list;
733
734                 gc_list = dst->next;
735                 dst_free(dst);
736         }
737
738         return 0;
739 }
740 EXPORT_SYMBOL(xfrm_policy_insert);
741
742 struct xfrm_policy *xfrm_policy_bysel_ctx(u8 type, int dir,
743                                           struct xfrm_selector *sel,
744                                           struct xfrm_sec_ctx *ctx, int delete)
745 {
746         struct xfrm_policy *pol, *ret;
747         struct hlist_head *chain;
748         struct hlist_node *entry;
749
750         write_lock_bh(&xfrm_policy_lock);
751         chain = policy_hash_bysel(sel, sel->family, dir);
752         ret = NULL;
753         hlist_for_each_entry(pol, entry, chain, bydst) {
754                 if (pol->type == type &&
755                     !selector_cmp(sel, &pol->selector) &&
756                     xfrm_sec_ctx_match(ctx, pol->security)) {
757                         xfrm_pol_hold(pol);
758                         if (delete) {
759                                 hlist_del(&pol->bydst);
760                                 hlist_del(&pol->byidx);
761                                 xfrm_policy_count[dir]--;
762                         }
763                         ret = pol;
764                         break;
765                 }
766         }
767         write_unlock_bh(&xfrm_policy_lock);
768
769         if (ret && delete) {
770                 atomic_inc(&flow_cache_genid);
771                 xfrm_policy_kill(ret);
772         }
773         return ret;
774 }
775 EXPORT_SYMBOL(xfrm_policy_bysel_ctx);
776
777 struct xfrm_policy *xfrm_policy_byid(u8 type, int dir, u32 id, int delete)
778 {
779         struct xfrm_policy *pol, *ret;
780         struct hlist_head *chain;
781         struct hlist_node *entry;
782
783         write_lock_bh(&xfrm_policy_lock);
784         chain = xfrm_policy_byidx + idx_hash(id);
785         ret = NULL;
786         hlist_for_each_entry(pol, entry, chain, byidx) {
787                 if (pol->type == type && pol->index == id) {
788                         xfrm_pol_hold(pol);
789                         if (delete) {
790                                 hlist_del(&pol->bydst);
791                                 hlist_del(&pol->byidx);
792                                 xfrm_policy_count[dir]--;
793                         }
794                         ret = pol;
795                         break;
796                 }
797         }
798         write_unlock_bh(&xfrm_policy_lock);
799
800         if (ret && delete) {
801                 atomic_inc(&flow_cache_genid);
802                 xfrm_policy_kill(ret);
803         }
804         return ret;
805 }
806 EXPORT_SYMBOL(xfrm_policy_byid);
807
808 void xfrm_policy_flush(u8 type, struct xfrm_audit *audit_info)
809 {
810         int dir;
811
812         write_lock_bh(&xfrm_policy_lock);
813         for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
814                 struct xfrm_policy *pol;
815                 struct hlist_node *entry;
816                 int i, killed;
817
818                 killed = 0;
819         again1:
820                 hlist_for_each_entry(pol, entry,
821                                      &xfrm_policy_inexact[dir], bydst) {
822                         if (pol->type != type)
823                                 continue;
824                         hlist_del(&pol->bydst);
825                         hlist_del(&pol->byidx);
826                         write_unlock_bh(&xfrm_policy_lock);
827
828                         xfrm_audit_log(audit_info->loginuid, audit_info->secid,
829                                        AUDIT_MAC_IPSEC_DELSPD, 1, pol, NULL);
830
831                         xfrm_policy_kill(pol);
832                         killed++;
833
834                         write_lock_bh(&xfrm_policy_lock);
835                         goto again1;
836                 }
837
838                 for (i = xfrm_policy_bydst[dir].hmask; i >= 0; i--) {
839         again2:
840                         hlist_for_each_entry(pol, entry,
841                                              xfrm_policy_bydst[dir].table + i,
842                                              bydst) {
843                                 if (pol->type != type)
844                                         continue;
845                                 hlist_del(&pol->bydst);
846                                 hlist_del(&pol->byidx);
847                                 write_unlock_bh(&xfrm_policy_lock);
848
849                                 xfrm_audit_log(audit_info->loginuid,
850                                                audit_info->secid,
851                                                AUDIT_MAC_IPSEC_DELSPD, 1,
852                                                pol, NULL);
853
854                                 xfrm_policy_kill(pol);
855                                 killed++;
856
857                                 write_lock_bh(&xfrm_policy_lock);
858                                 goto again2;
859                         }
860                 }
861
862                 xfrm_policy_count[dir] -= killed;
863         }
864         atomic_inc(&flow_cache_genid);
865         write_unlock_bh(&xfrm_policy_lock);
866 }
867 EXPORT_SYMBOL(xfrm_policy_flush);
868
869 int xfrm_policy_walk(u8 type, int (*func)(struct xfrm_policy *, int, int, void*),
870                      void *data)
871 {
872         struct xfrm_policy *pol, *last = NULL;
873         struct hlist_node *entry;
874         int dir, last_dir = 0, count, error;
875
876         read_lock_bh(&xfrm_policy_lock);
877         count = 0;
878
879         for (dir = 0; dir < 2*XFRM_POLICY_MAX; dir++) {
880                 struct hlist_head *table = xfrm_policy_bydst[dir].table;
881                 int i;
882
883                 hlist_for_each_entry(pol, entry,
884                                      &xfrm_policy_inexact[dir], bydst) {
885                         if (pol->type != type)
886                                 continue;
887                         if (last) {
888                                 error = func(last, last_dir % XFRM_POLICY_MAX,
889                                              count, data);
890                                 if (error)
891                                         goto out;
892                         }
893                         last = pol;
894                         last_dir = dir;
895                         count++;
896                 }
897                 for (i = xfrm_policy_bydst[dir].hmask; i >= 0; i--) {
898                         hlist_for_each_entry(pol, entry, table + i, bydst) {
899                                 if (pol->type != type)
900                                         continue;
901                                 if (last) {
902                                         error = func(last, last_dir % XFRM_POLICY_MAX,
903                                                      count, data);
904                                         if (error)
905                                                 goto out;
906                                 }
907                                 last = pol;
908                                 last_dir = dir;
909                                 count++;
910                         }
911                 }
912         }
913         if (count == 0) {
914                 error = -ENOENT;
915                 goto out;
916         }
917         error = func(last, last_dir % XFRM_POLICY_MAX, 0, data);
918 out:
919         read_unlock_bh(&xfrm_policy_lock);
920         return error;
921 }
922 EXPORT_SYMBOL(xfrm_policy_walk);
923
924 /*
925  * Find policy to apply to this flow.
926  *
927  * Returns 0 if policy found, else an -errno.
928  */
929 static int xfrm_policy_match(struct xfrm_policy *pol, struct flowi *fl,
930                              u8 type, u16 family, int dir)
931 {
932         struct xfrm_selector *sel = &pol->selector;
933         int match, ret = -ESRCH;
934
935         if (pol->family != family ||
936             pol->type != type)
937                 return ret;
938
939         match = xfrm_selector_match(sel, fl, family);
940         if (match)
941                 ret = security_xfrm_policy_lookup(pol, fl->secid, dir);
942
943         return ret;
944 }
945
946 static struct xfrm_policy *xfrm_policy_lookup_bytype(u8 type, struct flowi *fl,
947                                                      u16 family, u8 dir)
948 {
949         int err;
950         struct xfrm_policy *pol, *ret;
951         xfrm_address_t *daddr, *saddr;
952         struct hlist_node *entry;
953         struct hlist_head *chain;
954         u32 priority = ~0U;
955
956         daddr = xfrm_flowi_daddr(fl, family);
957         saddr = xfrm_flowi_saddr(fl, family);
958         if (unlikely(!daddr || !saddr))
959                 return NULL;
960
961         read_lock_bh(&xfrm_policy_lock);
962         chain = policy_hash_direct(daddr, saddr, family, dir);
963         ret = NULL;
964         hlist_for_each_entry(pol, entry, chain, bydst) {
965                 err = xfrm_policy_match(pol, fl, type, family, dir);
966                 if (err) {
967                         if (err == -ESRCH)
968                                 continue;
969                         else {
970                                 ret = ERR_PTR(err);
971                                 goto fail;
972                         }
973                 } else {
974                         ret = pol;
975                         priority = ret->priority;
976                         break;
977                 }
978         }
979         chain = &xfrm_policy_inexact[dir];
980         hlist_for_each_entry(pol, entry, chain, bydst) {
981                 err = xfrm_policy_match(pol, fl, type, family, dir);
982                 if (err) {
983                         if (err == -ESRCH)
984                                 continue;
985                         else {
986                                 ret = ERR_PTR(err);
987                                 goto fail;
988                         }
989                 } else if (pol->priority < priority) {
990                         ret = pol;
991                         break;
992                 }
993         }
994         if (ret)
995                 xfrm_pol_hold(ret);
996 fail:
997         read_unlock_bh(&xfrm_policy_lock);
998
999         return ret;
1000 }
1001
1002 static int xfrm_policy_lookup(struct flowi *fl, u16 family, u8 dir,
1003                                void **objp, atomic_t **obj_refp)
1004 {
1005         struct xfrm_policy *pol;
1006         int err = 0;
1007
1008 #ifdef CONFIG_XFRM_SUB_POLICY
1009         pol = xfrm_policy_lookup_bytype(XFRM_POLICY_TYPE_SUB, fl, family, dir);
1010         if (IS_ERR(pol)) {
1011                 err = PTR_ERR(pol);
1012                 pol = NULL;
1013         }
1014         if (pol || err)
1015                 goto end;
1016 #endif
1017         pol = xfrm_policy_lookup_bytype(XFRM_POLICY_TYPE_MAIN, fl, family, dir);
1018         if (IS_ERR(pol)) {
1019                 err = PTR_ERR(pol);
1020                 pol = NULL;
1021         }
1022 #ifdef CONFIG_XFRM_SUB_POLICY
1023 end:
1024 #endif
1025         if ((*objp = (void *) pol) != NULL)
1026                 *obj_refp = &pol->refcnt;
1027         return err;
1028 }
1029
1030 static inline int policy_to_flow_dir(int dir)
1031 {
1032         if (XFRM_POLICY_IN == FLOW_DIR_IN &&
1033             XFRM_POLICY_OUT == FLOW_DIR_OUT &&
1034             XFRM_POLICY_FWD == FLOW_DIR_FWD)
1035                 return dir;
1036         switch (dir) {
1037         default:
1038         case XFRM_POLICY_IN:
1039                 return FLOW_DIR_IN;
1040         case XFRM_POLICY_OUT:
1041                 return FLOW_DIR_OUT;
1042         case XFRM_POLICY_FWD:
1043                 return FLOW_DIR_FWD;
1044         };
1045 }
1046
1047 static struct xfrm_policy *xfrm_sk_policy_lookup(struct sock *sk, int dir, struct flowi *fl)
1048 {
1049         struct xfrm_policy *pol;
1050
1051         read_lock_bh(&xfrm_policy_lock);
1052         if ((pol = sk->sk_policy[dir]) != NULL) {
1053                 int match = xfrm_selector_match(&pol->selector, fl,
1054                                                 sk->sk_family);
1055                 int err = 0;
1056
1057                 if (match) {
1058                         err = security_xfrm_policy_lookup(pol, fl->secid,
1059                                         policy_to_flow_dir(dir));
1060                         if (!err)
1061                                 xfrm_pol_hold(pol);
1062                         else if (err == -ESRCH)
1063                                 pol = NULL;
1064                         else
1065                                 pol = ERR_PTR(err);
1066                 } else
1067                         pol = NULL;
1068         }
1069         read_unlock_bh(&xfrm_policy_lock);
1070         return pol;
1071 }
1072
1073 static void __xfrm_policy_link(struct xfrm_policy *pol, int dir)
1074 {
1075         struct hlist_head *chain = policy_hash_bysel(&pol->selector,
1076                                                      pol->family, dir);
1077
1078         hlist_add_head(&pol->bydst, chain);
1079         hlist_add_head(&pol->byidx, xfrm_policy_byidx+idx_hash(pol->index));
1080         xfrm_policy_count[dir]++;
1081         xfrm_pol_hold(pol);
1082
1083         if (xfrm_bydst_should_resize(dir, NULL))
1084                 schedule_work(&xfrm_hash_work);
1085 }
1086
1087 static struct xfrm_policy *__xfrm_policy_unlink(struct xfrm_policy *pol,
1088                                                 int dir)
1089 {
1090         if (hlist_unhashed(&pol->bydst))
1091                 return NULL;
1092
1093         hlist_del(&pol->bydst);
1094         hlist_del(&pol->byidx);
1095         xfrm_policy_count[dir]--;
1096
1097         return pol;
1098 }
1099
1100 int xfrm_policy_delete(struct xfrm_policy *pol, int dir)
1101 {
1102         write_lock_bh(&xfrm_policy_lock);
1103         pol = __xfrm_policy_unlink(pol, dir);
1104         write_unlock_bh(&xfrm_policy_lock);
1105         if (pol) {
1106                 if (dir < XFRM_POLICY_MAX)
1107                         atomic_inc(&flow_cache_genid);
1108                 xfrm_policy_kill(pol);
1109                 return 0;
1110         }
1111         return -ENOENT;
1112 }
1113 EXPORT_SYMBOL(xfrm_policy_delete);
1114
1115 int xfrm_sk_policy_insert(struct sock *sk, int dir, struct xfrm_policy *pol)
1116 {
1117         struct xfrm_policy *old_pol;
1118
1119 #ifdef CONFIG_XFRM_SUB_POLICY
1120         if (pol && pol->type != XFRM_POLICY_TYPE_MAIN)
1121                 return -EINVAL;
1122 #endif
1123
1124         write_lock_bh(&xfrm_policy_lock);
1125         old_pol = sk->sk_policy[dir];
1126         sk->sk_policy[dir] = pol;
1127         if (pol) {
1128                 pol->curlft.add_time = (unsigned long)xtime.tv_sec;
1129                 pol->index = xfrm_gen_index(pol->type, XFRM_POLICY_MAX+dir);
1130                 __xfrm_policy_link(pol, XFRM_POLICY_MAX+dir);
1131         }
1132         if (old_pol)
1133                 __xfrm_policy_unlink(old_pol, XFRM_POLICY_MAX+dir);
1134         write_unlock_bh(&xfrm_policy_lock);
1135
1136         if (old_pol) {
1137                 xfrm_policy_kill(old_pol);
1138         }
1139         return 0;
1140 }
1141
1142 static struct xfrm_policy *clone_policy(struct xfrm_policy *old, int dir)
1143 {
1144         struct xfrm_policy *newp = xfrm_policy_alloc(GFP_ATOMIC);
1145
1146         if (newp) {
1147                 newp->selector = old->selector;
1148                 if (security_xfrm_policy_clone(old, newp)) {
1149                         kfree(newp);
1150                         return NULL;  /* ENOMEM */
1151                 }
1152                 newp->lft = old->lft;
1153                 newp->curlft = old->curlft;
1154                 newp->action = old->action;
1155                 newp->flags = old->flags;
1156                 newp->xfrm_nr = old->xfrm_nr;
1157                 newp->index = old->index;
1158                 newp->type = old->type;
1159                 memcpy(newp->xfrm_vec, old->xfrm_vec,
1160                        newp->xfrm_nr*sizeof(struct xfrm_tmpl));
1161                 write_lock_bh(&xfrm_policy_lock);
1162                 __xfrm_policy_link(newp, XFRM_POLICY_MAX+dir);
1163                 write_unlock_bh(&xfrm_policy_lock);
1164                 xfrm_pol_put(newp);
1165         }
1166         return newp;
1167 }
1168
1169 int __xfrm_sk_clone_policy(struct sock *sk)
1170 {
1171         struct xfrm_policy *p0 = sk->sk_policy[0],
1172                            *p1 = sk->sk_policy[1];
1173
1174         sk->sk_policy[0] = sk->sk_policy[1] = NULL;
1175         if (p0 && (sk->sk_policy[0] = clone_policy(p0, 0)) == NULL)
1176                 return -ENOMEM;
1177         if (p1 && (sk->sk_policy[1] = clone_policy(p1, 1)) == NULL)
1178                 return -ENOMEM;
1179         return 0;
1180 }
1181
1182 static int
1183 xfrm_get_saddr(xfrm_address_t *local, xfrm_address_t *remote,
1184                unsigned short family)
1185 {
1186         int err;
1187         struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1188
1189         if (unlikely(afinfo == NULL))
1190                 return -EINVAL;
1191         err = afinfo->get_saddr(local, remote);
1192         xfrm_policy_put_afinfo(afinfo);
1193         return err;
1194 }
1195
1196 /* Resolve list of templates for the flow, given policy. */
1197
1198 static int
1199 xfrm_tmpl_resolve_one(struct xfrm_policy *policy, struct flowi *fl,
1200                       struct xfrm_state **xfrm,
1201                       unsigned short family)
1202 {
1203         int nx;
1204         int i, error;
1205         xfrm_address_t *daddr = xfrm_flowi_daddr(fl, family);
1206         xfrm_address_t *saddr = xfrm_flowi_saddr(fl, family);
1207         xfrm_address_t tmp;
1208
1209         for (nx=0, i = 0; i < policy->xfrm_nr; i++) {
1210                 struct xfrm_state *x;
1211                 xfrm_address_t *remote = daddr;
1212                 xfrm_address_t *local  = saddr;
1213                 struct xfrm_tmpl *tmpl = &policy->xfrm_vec[i];
1214
1215                 if (tmpl->mode == XFRM_MODE_TUNNEL) {
1216                         remote = &tmpl->id.daddr;
1217                         local = &tmpl->saddr;
1218                         family = tmpl->encap_family;
1219                         if (xfrm_addr_any(local, family)) {
1220                                 error = xfrm_get_saddr(&tmp, remote, family);
1221                                 if (error)
1222                                         goto fail;
1223                                 local = &tmp;
1224                         }
1225                 }
1226
1227                 x = xfrm_state_find(remote, local, fl, tmpl, policy, &error, family);
1228
1229                 if (x && x->km.state == XFRM_STATE_VALID) {
1230                         xfrm[nx++] = x;
1231                         daddr = remote;
1232                         saddr = local;
1233                         continue;
1234                 }
1235                 if (x) {
1236                         error = (x->km.state == XFRM_STATE_ERROR ?
1237                                  -EINVAL : -EAGAIN);
1238                         xfrm_state_put(x);
1239                 }
1240
1241                 if (!tmpl->optional)
1242                         goto fail;
1243         }
1244         return nx;
1245
1246 fail:
1247         for (nx--; nx>=0; nx--)
1248                 xfrm_state_put(xfrm[nx]);
1249         return error;
1250 }
1251
1252 static int
1253 xfrm_tmpl_resolve(struct xfrm_policy **pols, int npols, struct flowi *fl,
1254                   struct xfrm_state **xfrm,
1255                   unsigned short family)
1256 {
1257         struct xfrm_state *tp[XFRM_MAX_DEPTH];
1258         struct xfrm_state **tpp = (npols > 1) ? tp : xfrm;
1259         int cnx = 0;
1260         int error;
1261         int ret;
1262         int i;
1263
1264         for (i = 0; i < npols; i++) {
1265                 if (cnx + pols[i]->xfrm_nr >= XFRM_MAX_DEPTH) {
1266                         error = -ENOBUFS;
1267                         goto fail;
1268                 }
1269
1270                 ret = xfrm_tmpl_resolve_one(pols[i], fl, &tpp[cnx], family);
1271                 if (ret < 0) {
1272                         error = ret;
1273                         goto fail;
1274                 } else
1275                         cnx += ret;
1276         }
1277
1278         /* found states are sorted for outbound processing */
1279         if (npols > 1)
1280                 xfrm_state_sort(xfrm, tpp, cnx, family);
1281
1282         return cnx;
1283
1284  fail:
1285         for (cnx--; cnx>=0; cnx--)
1286                 xfrm_state_put(tpp[cnx]);
1287         return error;
1288
1289 }
1290
1291 /* Check that the bundle accepts the flow and its components are
1292  * still valid.
1293  */
1294
1295 static struct dst_entry *
1296 xfrm_find_bundle(struct flowi *fl, struct xfrm_policy *policy, unsigned short family)
1297 {
1298         struct dst_entry *x;
1299         struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1300         if (unlikely(afinfo == NULL))
1301                 return ERR_PTR(-EINVAL);
1302         x = afinfo->find_bundle(fl, policy);
1303         xfrm_policy_put_afinfo(afinfo);
1304         return x;
1305 }
1306
1307 /* Allocate chain of dst_entry's, attach known xfrm's, calculate
1308  * all the metrics... Shortly, bundle a bundle.
1309  */
1310
1311 static int
1312 xfrm_bundle_create(struct xfrm_policy *policy, struct xfrm_state **xfrm, int nx,
1313                    struct flowi *fl, struct dst_entry **dst_p,
1314                    unsigned short family)
1315 {
1316         int err;
1317         struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1318         if (unlikely(afinfo == NULL))
1319                 return -EINVAL;
1320         err = afinfo->bundle_create(policy, xfrm, nx, fl, dst_p);
1321         xfrm_policy_put_afinfo(afinfo);
1322         return err;
1323 }
1324
1325
1326 static int stale_bundle(struct dst_entry *dst);
1327
1328 /* Main function: finds/creates a bundle for given flow.
1329  *
1330  * At the moment we eat a raw IP route. Mostly to speed up lookups
1331  * on interfaces with disabled IPsec.
1332  */
1333 int xfrm_lookup(struct dst_entry **dst_p, struct flowi *fl,
1334                 struct sock *sk, int flags)
1335 {
1336         struct xfrm_policy *policy;
1337         struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
1338         int npols;
1339         int pol_dead;
1340         int xfrm_nr;
1341         int pi;
1342         struct xfrm_state *xfrm[XFRM_MAX_DEPTH];
1343         struct dst_entry *dst, *dst_orig = *dst_p;
1344         int nx = 0;
1345         int err;
1346         u32 genid;
1347         u16 family;
1348         u8 dir = policy_to_flow_dir(XFRM_POLICY_OUT);
1349
1350 restart:
1351         genid = atomic_read(&flow_cache_genid);
1352         policy = NULL;
1353         for (pi = 0; pi < ARRAY_SIZE(pols); pi++)
1354                 pols[pi] = NULL;
1355         npols = 0;
1356         pol_dead = 0;
1357         xfrm_nr = 0;
1358
1359         if (sk && sk->sk_policy[1]) {
1360                 policy = xfrm_sk_policy_lookup(sk, XFRM_POLICY_OUT, fl);
1361                 if (IS_ERR(policy))
1362                         return PTR_ERR(policy);
1363         }
1364
1365         if (!policy) {
1366                 /* To accelerate a bit...  */
1367                 if ((dst_orig->flags & DST_NOXFRM) ||
1368                     !xfrm_policy_count[XFRM_POLICY_OUT])
1369                         return 0;
1370
1371                 policy = flow_cache_lookup(fl, dst_orig->ops->family,
1372                                            dir, xfrm_policy_lookup);
1373                 if (IS_ERR(policy))
1374                         return PTR_ERR(policy);
1375         }
1376
1377         if (!policy)
1378                 return 0;
1379
1380         family = dst_orig->ops->family;
1381         policy->curlft.use_time = (unsigned long)xtime.tv_sec;
1382         pols[0] = policy;
1383         npols ++;
1384         xfrm_nr += pols[0]->xfrm_nr;
1385
1386         switch (policy->action) {
1387         case XFRM_POLICY_BLOCK:
1388                 /* Prohibit the flow */
1389                 err = -EPERM;
1390                 goto error;
1391
1392         case XFRM_POLICY_ALLOW:
1393 #ifndef CONFIG_XFRM_SUB_POLICY
1394                 if (policy->xfrm_nr == 0) {
1395                         /* Flow passes not transformed. */
1396                         xfrm_pol_put(policy);
1397                         return 0;
1398                 }
1399 #endif
1400
1401                 /* Try to find matching bundle.
1402                  *
1403                  * LATER: help from flow cache. It is optional, this
1404                  * is required only for output policy.
1405                  */
1406                 dst = xfrm_find_bundle(fl, policy, family);
1407                 if (IS_ERR(dst)) {
1408                         err = PTR_ERR(dst);
1409                         goto error;
1410                 }
1411
1412                 if (dst)
1413                         break;
1414
1415 #ifdef CONFIG_XFRM_SUB_POLICY
1416                 if (pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
1417                         pols[1] = xfrm_policy_lookup_bytype(XFRM_POLICY_TYPE_MAIN,
1418                                                             fl, family,
1419                                                             XFRM_POLICY_OUT);
1420                         if (pols[1]) {
1421                                 if (IS_ERR(pols[1])) {
1422                                         err = PTR_ERR(pols[1]);
1423                                         goto error;
1424                                 }
1425                                 if (pols[1]->action == XFRM_POLICY_BLOCK) {
1426                                         err = -EPERM;
1427                                         goto error;
1428                                 }
1429                                 npols ++;
1430                                 xfrm_nr += pols[1]->xfrm_nr;
1431                         }
1432                 }
1433
1434                 /*
1435                  * Because neither flowi nor bundle information knows about
1436                  * transformation template size. On more than one policy usage
1437                  * we can realize whether all of them is bypass or not after
1438                  * they are searched. See above not-transformed bypass
1439                  * is surrounded by non-sub policy configuration, too.
1440                  */
1441                 if (xfrm_nr == 0) {
1442                         /* Flow passes not transformed. */
1443                         xfrm_pols_put(pols, npols);
1444                         return 0;
1445                 }
1446
1447 #endif
1448                 nx = xfrm_tmpl_resolve(pols, npols, fl, xfrm, family);
1449
1450                 if (unlikely(nx<0)) {
1451                         err = nx;
1452                         if (err == -EAGAIN && flags) {
1453                                 DECLARE_WAITQUEUE(wait, current);
1454
1455                                 add_wait_queue(&km_waitq, &wait);
1456                                 set_current_state(TASK_INTERRUPTIBLE);
1457                                 schedule();
1458                                 set_current_state(TASK_RUNNING);
1459                                 remove_wait_queue(&km_waitq, &wait);
1460
1461                                 nx = xfrm_tmpl_resolve(pols, npols, fl, xfrm, family);
1462
1463                                 if (nx == -EAGAIN && signal_pending(current)) {
1464                                         err = -ERESTART;
1465                                         goto error;
1466                                 }
1467                                 if (nx == -EAGAIN ||
1468                                     genid != atomic_read(&flow_cache_genid)) {
1469                                         xfrm_pols_put(pols, npols);
1470                                         goto restart;
1471                                 }
1472                                 err = nx;
1473                         }
1474                         if (err < 0)
1475                                 goto error;
1476                 }
1477                 if (nx == 0) {
1478                         /* Flow passes not transformed. */
1479                         xfrm_pols_put(pols, npols);
1480                         return 0;
1481                 }
1482
1483                 dst = dst_orig;
1484                 err = xfrm_bundle_create(policy, xfrm, nx, fl, &dst, family);
1485
1486                 if (unlikely(err)) {
1487                         int i;
1488                         for (i=0; i<nx; i++)
1489                                 xfrm_state_put(xfrm[i]);
1490                         goto error;
1491                 }
1492
1493                 for (pi = 0; pi < npols; pi++) {
1494                         read_lock_bh(&pols[pi]->lock);
1495                         pol_dead |= pols[pi]->dead;
1496                         read_unlock_bh(&pols[pi]->lock);
1497                 }
1498
1499                 write_lock_bh(&policy->lock);
1500                 if (unlikely(pol_dead || stale_bundle(dst))) {
1501                         /* Wow! While we worked on resolving, this
1502                          * policy has gone. Retry. It is not paranoia,
1503                          * we just cannot enlist new bundle to dead object.
1504                          * We can't enlist stable bundles either.
1505                          */
1506                         write_unlock_bh(&policy->lock);
1507                         if (dst)
1508                                 dst_free(dst);
1509
1510                         err = -EHOSTUNREACH;
1511                         goto error;
1512                 }
1513                 dst->next = policy->bundles;
1514                 policy->bundles = dst;
1515                 dst_hold(dst);
1516                 write_unlock_bh(&policy->lock);
1517         }
1518         *dst_p = dst;
1519         dst_release(dst_orig);
1520         xfrm_pols_put(pols, npols);
1521         return 0;
1522
1523 error:
1524         dst_release(dst_orig);
1525         xfrm_pols_put(pols, npols);
1526         *dst_p = NULL;
1527         return err;
1528 }
1529 EXPORT_SYMBOL(xfrm_lookup);
1530
1531 static inline int
1532 xfrm_secpath_reject(int idx, struct sk_buff *skb, struct flowi *fl)
1533 {
1534         struct xfrm_state *x;
1535         int err;
1536
1537         if (!skb->sp || idx < 0 || idx >= skb->sp->len)
1538                 return 0;
1539         x = skb->sp->xvec[idx];
1540         if (!x->type->reject)
1541                 return 0;
1542         xfrm_state_hold(x);
1543         err = x->type->reject(x, skb, fl);
1544         xfrm_state_put(x);
1545         return err;
1546 }
1547
1548 /* When skb is transformed back to its "native" form, we have to
1549  * check policy restrictions. At the moment we make this in maximally
1550  * stupid way. Shame on me. :-) Of course, connected sockets must
1551  * have policy cached at them.
1552  */
1553
1554 static inline int
1555 xfrm_state_ok(struct xfrm_tmpl *tmpl, struct xfrm_state *x, 
1556               unsigned short family)
1557 {
1558         if (xfrm_state_kern(x))
1559                 return tmpl->optional && !xfrm_state_addr_cmp(tmpl, x, family);
1560         return  x->id.proto == tmpl->id.proto &&
1561                 (x->id.spi == tmpl->id.spi || !tmpl->id.spi) &&
1562                 (x->props.reqid == tmpl->reqid || !tmpl->reqid) &&
1563                 x->props.mode == tmpl->mode &&
1564                 ((tmpl->aalgos & (1<<x->props.aalgo)) ||
1565                  !(xfrm_id_proto_match(tmpl->id.proto, IPSEC_PROTO_ANY))) &&
1566                 !(x->props.mode != XFRM_MODE_TRANSPORT &&
1567                   xfrm_state_addr_cmp(tmpl, x, family));
1568 }
1569
1570 /*
1571  * 0 or more than 0 is returned when validation is succeeded (either bypass
1572  * because of optional transport mode, or next index of the mathced secpath
1573  * state with the template.
1574  * -1 is returned when no matching template is found.
1575  * Otherwise "-2 - errored_index" is returned.
1576  */
1577 static inline int
1578 xfrm_policy_ok(struct xfrm_tmpl *tmpl, struct sec_path *sp, int start,
1579                unsigned short family)
1580 {
1581         int idx = start;
1582
1583         if (tmpl->optional) {
1584                 if (tmpl->mode == XFRM_MODE_TRANSPORT)
1585                         return start;
1586         } else
1587                 start = -1;
1588         for (; idx < sp->len; idx++) {
1589                 if (xfrm_state_ok(tmpl, sp->xvec[idx], family))
1590                         return ++idx;
1591                 if (sp->xvec[idx]->props.mode != XFRM_MODE_TRANSPORT) {
1592                         if (start == -1)
1593                                 start = -2-idx;
1594                         break;
1595                 }
1596         }
1597         return start;
1598 }
1599
1600 int
1601 xfrm_decode_session(struct sk_buff *skb, struct flowi *fl, unsigned short family)
1602 {
1603         struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1604         int err;
1605
1606         if (unlikely(afinfo == NULL))
1607                 return -EAFNOSUPPORT;
1608
1609         afinfo->decode_session(skb, fl);
1610         err = security_xfrm_decode_session(skb, &fl->secid);
1611         xfrm_policy_put_afinfo(afinfo);
1612         return err;
1613 }
1614 EXPORT_SYMBOL(xfrm_decode_session);
1615
1616 static inline int secpath_has_nontransport(struct sec_path *sp, int k, int *idxp)
1617 {
1618         for (; k < sp->len; k++) {
1619                 if (sp->xvec[k]->props.mode != XFRM_MODE_TRANSPORT) {
1620                         *idxp = k;
1621                         return 1;
1622                 }
1623         }
1624
1625         return 0;
1626 }
1627
1628 int __xfrm_policy_check(struct sock *sk, int dir, struct sk_buff *skb, 
1629                         unsigned short family)
1630 {
1631         struct xfrm_policy *pol;
1632         struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
1633         int npols = 0;
1634         int xfrm_nr;
1635         int pi;
1636         struct flowi fl;
1637         u8 fl_dir = policy_to_flow_dir(dir);
1638         int xerr_idx = -1;
1639
1640         if (xfrm_decode_session(skb, &fl, family) < 0)
1641                 return 0;
1642         nf_nat_decode_session(skb, &fl, family);
1643
1644         /* First, check used SA against their selectors. */
1645         if (skb->sp) {
1646                 int i;
1647
1648                 for (i=skb->sp->len-1; i>=0; i--) {
1649                         struct xfrm_state *x = skb->sp->xvec[i];
1650                         if (!xfrm_selector_match(&x->sel, &fl, family))
1651                                 return 0;
1652                 }
1653         }
1654
1655         pol = NULL;
1656         if (sk && sk->sk_policy[dir]) {
1657                 pol = xfrm_sk_policy_lookup(sk, dir, &fl);
1658                 if (IS_ERR(pol))
1659                         return 0;
1660         }
1661
1662         if (!pol)
1663                 pol = flow_cache_lookup(&fl, family, fl_dir,
1664                                         xfrm_policy_lookup);
1665
1666         if (IS_ERR(pol))
1667                 return 0;
1668
1669         if (!pol) {
1670                 if (skb->sp && secpath_has_nontransport(skb->sp, 0, &xerr_idx)) {
1671                         xfrm_secpath_reject(xerr_idx, skb, &fl);
1672                         return 0;
1673                 }
1674                 return 1;
1675         }
1676
1677         pol->curlft.use_time = (unsigned long)xtime.tv_sec;
1678
1679         pols[0] = pol;
1680         npols ++;
1681 #ifdef CONFIG_XFRM_SUB_POLICY
1682         if (pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
1683                 pols[1] = xfrm_policy_lookup_bytype(XFRM_POLICY_TYPE_MAIN,
1684                                                     &fl, family,
1685                                                     XFRM_POLICY_IN);
1686                 if (pols[1]) {
1687                         if (IS_ERR(pols[1]))
1688                                 return 0;
1689                         pols[1]->curlft.use_time = (unsigned long)xtime.tv_sec;
1690                         npols ++;
1691                 }
1692         }
1693 #endif
1694
1695         if (pol->action == XFRM_POLICY_ALLOW) {
1696                 struct sec_path *sp;
1697                 static struct sec_path dummy;
1698                 struct xfrm_tmpl *tp[XFRM_MAX_DEPTH];
1699                 struct xfrm_tmpl *stp[XFRM_MAX_DEPTH];
1700                 struct xfrm_tmpl **tpp = tp;
1701                 int ti = 0;
1702                 int i, k;
1703
1704                 if ((sp = skb->sp) == NULL)
1705                         sp = &dummy;
1706
1707                 for (pi = 0; pi < npols; pi++) {
1708                         if (pols[pi] != pol &&
1709                             pols[pi]->action != XFRM_POLICY_ALLOW)
1710                                 goto reject;
1711                         if (ti + pols[pi]->xfrm_nr >= XFRM_MAX_DEPTH)
1712                                 goto reject_error;
1713                         for (i = 0; i < pols[pi]->xfrm_nr; i++)
1714                                 tpp[ti++] = &pols[pi]->xfrm_vec[i];
1715                 }
1716                 xfrm_nr = ti;
1717                 if (npols > 1) {
1718                         xfrm_tmpl_sort(stp, tpp, xfrm_nr, family);
1719                         tpp = stp;
1720                 }
1721
1722                 /* For each tunnel xfrm, find the first matching tmpl.
1723                  * For each tmpl before that, find corresponding xfrm.
1724                  * Order is _important_. Later we will implement
1725                  * some barriers, but at the moment barriers
1726                  * are implied between each two transformations.
1727                  */
1728                 for (i = xfrm_nr-1, k = 0; i >= 0; i--) {
1729                         k = xfrm_policy_ok(tpp[i], sp, k, family);
1730                         if (k < 0) {
1731                                 if (k < -1)
1732                                         /* "-2 - errored_index" returned */
1733                                         xerr_idx = -(2+k);
1734                                 goto reject;
1735                         }
1736                 }
1737
1738                 if (secpath_has_nontransport(sp, k, &xerr_idx))
1739                         goto reject;
1740
1741                 xfrm_pols_put(pols, npols);
1742                 return 1;
1743         }
1744
1745 reject:
1746         xfrm_secpath_reject(xerr_idx, skb, &fl);
1747 reject_error:
1748         xfrm_pols_put(pols, npols);
1749         return 0;
1750 }
1751 EXPORT_SYMBOL(__xfrm_policy_check);
1752
1753 int __xfrm_route_forward(struct sk_buff *skb, unsigned short family)
1754 {
1755         struct flowi fl;
1756
1757         if (xfrm_decode_session(skb, &fl, family) < 0)
1758                 return 0;
1759
1760         return xfrm_lookup(&skb->dst, &fl, NULL, 0) == 0;
1761 }
1762 EXPORT_SYMBOL(__xfrm_route_forward);
1763
1764 /* Optimize later using cookies and generation ids. */
1765
1766 static struct dst_entry *xfrm_dst_check(struct dst_entry *dst, u32 cookie)
1767 {
1768         /* Code (such as __xfrm4_bundle_create()) sets dst->obsolete
1769          * to "-1" to force all XFRM destinations to get validated by
1770          * dst_ops->check on every use.  We do this because when a
1771          * normal route referenced by an XFRM dst is obsoleted we do
1772          * not go looking around for all parent referencing XFRM dsts
1773          * so that we can invalidate them.  It is just too much work.
1774          * Instead we make the checks here on every use.  For example:
1775          *
1776          *      XFRM dst A --> IPv4 dst X
1777          *
1778          * X is the "xdst->route" of A (X is also the "dst->path" of A
1779          * in this example).  If X is marked obsolete, "A" will not
1780          * notice.  That's what we are validating here via the
1781          * stale_bundle() check.
1782          *
1783          * When a policy's bundle is pruned, we dst_free() the XFRM
1784          * dst which causes it's ->obsolete field to be set to a
1785          * positive non-zero integer.  If an XFRM dst has been pruned
1786          * like this, we want to force a new route lookup.
1787          */
1788         if (dst->obsolete < 0 && !stale_bundle(dst))
1789                 return dst;
1790
1791         return NULL;
1792 }
1793
1794 static int stale_bundle(struct dst_entry *dst)
1795 {
1796         return !xfrm_bundle_ok(NULL, (struct xfrm_dst *)dst, NULL, AF_UNSPEC, 0);
1797 }
1798
1799 void xfrm_dst_ifdown(struct dst_entry *dst, struct net_device *dev)
1800 {
1801         while ((dst = dst->child) && dst->xfrm && dst->dev == dev) {
1802                 dst->dev = &loopback_dev;
1803                 dev_hold(&loopback_dev);
1804                 dev_put(dev);
1805         }
1806 }
1807 EXPORT_SYMBOL(xfrm_dst_ifdown);
1808
1809 static void xfrm_link_failure(struct sk_buff *skb)
1810 {
1811         /* Impossible. Such dst must be popped before reaches point of failure. */
1812         return;
1813 }
1814
1815 static struct dst_entry *xfrm_negative_advice(struct dst_entry *dst)
1816 {
1817         if (dst) {
1818                 if (dst->obsolete) {
1819                         dst_release(dst);
1820                         dst = NULL;
1821                 }
1822         }
1823         return dst;
1824 }
1825
1826 static void prune_one_bundle(struct xfrm_policy *pol, int (*func)(struct dst_entry *), struct dst_entry **gc_list_p)
1827 {
1828         struct dst_entry *dst, **dstp;
1829
1830         write_lock(&pol->lock);
1831         dstp = &pol->bundles;
1832         while ((dst=*dstp) != NULL) {
1833                 if (func(dst)) {
1834                         *dstp = dst->next;
1835                         dst->next = *gc_list_p;
1836                         *gc_list_p = dst;
1837                 } else {
1838                         dstp = &dst->next;
1839                 }
1840         }
1841         write_unlock(&pol->lock);
1842 }
1843
1844 static void xfrm_prune_bundles(int (*func)(struct dst_entry *))
1845 {
1846         struct dst_entry *gc_list = NULL;
1847         int dir;
1848
1849         read_lock_bh(&xfrm_policy_lock);
1850         for (dir = 0; dir < XFRM_POLICY_MAX * 2; dir++) {
1851                 struct xfrm_policy *pol;
1852                 struct hlist_node *entry;
1853                 struct hlist_head *table;
1854                 int i;
1855
1856                 hlist_for_each_entry(pol, entry,
1857                                      &xfrm_policy_inexact[dir], bydst)
1858                         prune_one_bundle(pol, func, &gc_list);
1859
1860                 table = xfrm_policy_bydst[dir].table;
1861                 for (i = xfrm_policy_bydst[dir].hmask; i >= 0; i--) {
1862                         hlist_for_each_entry(pol, entry, table + i, bydst)
1863                                 prune_one_bundle(pol, func, &gc_list);
1864                 }
1865         }
1866         read_unlock_bh(&xfrm_policy_lock);
1867
1868         while (gc_list) {
1869                 struct dst_entry *dst = gc_list;
1870                 gc_list = dst->next;
1871                 dst_free(dst);
1872         }
1873 }
1874
1875 static int unused_bundle(struct dst_entry *dst)
1876 {
1877         return !atomic_read(&dst->__refcnt);
1878 }
1879
1880 static void __xfrm_garbage_collect(void)
1881 {
1882         xfrm_prune_bundles(unused_bundle);
1883 }
1884
1885 static int xfrm_flush_bundles(void)
1886 {
1887         xfrm_prune_bundles(stale_bundle);
1888         return 0;
1889 }
1890
1891 void xfrm_init_pmtu(struct dst_entry *dst)
1892 {
1893         do {
1894                 struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
1895                 u32 pmtu, route_mtu_cached;
1896
1897                 pmtu = dst_mtu(dst->child);
1898                 xdst->child_mtu_cached = pmtu;
1899
1900                 pmtu = xfrm_state_mtu(dst->xfrm, pmtu);
1901
1902                 route_mtu_cached = dst_mtu(xdst->route);
1903                 xdst->route_mtu_cached = route_mtu_cached;
1904
1905                 if (pmtu > route_mtu_cached)
1906                         pmtu = route_mtu_cached;
1907
1908                 dst->metrics[RTAX_MTU-1] = pmtu;
1909         } while ((dst = dst->next));
1910 }
1911
1912 EXPORT_SYMBOL(xfrm_init_pmtu);
1913
1914 /* Check that the bundle accepts the flow and its components are
1915  * still valid.
1916  */
1917
1918 int xfrm_bundle_ok(struct xfrm_policy *pol, struct xfrm_dst *first,
1919                 struct flowi *fl, int family, int strict)
1920 {
1921         struct dst_entry *dst = &first->u.dst;
1922         struct xfrm_dst *last;
1923         u32 mtu;
1924
1925         if (!dst_check(dst->path, ((struct xfrm_dst *)dst)->path_cookie) ||
1926             (dst->dev && !netif_running(dst->dev)))
1927                 return 0;
1928
1929         last = NULL;
1930
1931         do {
1932                 struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
1933
1934                 if (fl && !xfrm_selector_match(&dst->xfrm->sel, fl, family))
1935                         return 0;
1936                 if (fl && pol &&
1937                     !security_xfrm_state_pol_flow_match(dst->xfrm, pol, fl))
1938                         return 0;
1939                 if (dst->xfrm->km.state != XFRM_STATE_VALID)
1940                         return 0;
1941                 if (xdst->genid != dst->xfrm->genid)
1942                         return 0;
1943
1944                 if (strict && fl && dst->xfrm->props.mode != XFRM_MODE_TUNNEL &&
1945                     !xfrm_state_addr_flow_check(dst->xfrm, fl, family))
1946                         return 0;
1947
1948                 mtu = dst_mtu(dst->child);
1949                 if (xdst->child_mtu_cached != mtu) {
1950                         last = xdst;
1951                         xdst->child_mtu_cached = mtu;
1952                 }
1953
1954                 if (!dst_check(xdst->route, xdst->route_cookie))
1955                         return 0;
1956                 mtu = dst_mtu(xdst->route);
1957                 if (xdst->route_mtu_cached != mtu) {
1958                         last = xdst;
1959                         xdst->route_mtu_cached = mtu;
1960                 }
1961
1962                 dst = dst->child;
1963         } while (dst->xfrm);
1964
1965         if (likely(!last))
1966                 return 1;
1967
1968         mtu = last->child_mtu_cached;
1969         for (;;) {
1970                 dst = &last->u.dst;
1971
1972                 mtu = xfrm_state_mtu(dst->xfrm, mtu);
1973                 if (mtu > last->route_mtu_cached)
1974                         mtu = last->route_mtu_cached;
1975                 dst->metrics[RTAX_MTU-1] = mtu;
1976
1977                 if (last == first)
1978                         break;
1979
1980                 last = last->u.next;
1981                 last->child_mtu_cached = mtu;
1982         }
1983
1984         return 1;
1985 }
1986
1987 EXPORT_SYMBOL(xfrm_bundle_ok);
1988
1989 #ifdef CONFIG_AUDITSYSCALL
1990 /* Audit addition and deletion of SAs and ipsec policy */
1991
1992 void xfrm_audit_log(uid_t auid, u32 sid, int type, int result,
1993                     struct xfrm_policy *xp, struct xfrm_state *x)
1994 {
1995
1996         char *secctx;
1997         u32 secctx_len;
1998         struct xfrm_sec_ctx *sctx = NULL;
1999         struct audit_buffer *audit_buf;
2000         int family;
2001         extern int audit_enabled;
2002
2003         if (audit_enabled == 0)
2004                 return;
2005
2006         audit_buf = audit_log_start(current->audit_context, GFP_ATOMIC, type);
2007         if (audit_buf == NULL)
2008         return;
2009
2010         switch(type) {
2011         case AUDIT_MAC_IPSEC_ADDSA:
2012                 audit_log_format(audit_buf, "SAD add: auid=%u", auid);
2013                 break;
2014         case AUDIT_MAC_IPSEC_DELSA:
2015                 audit_log_format(audit_buf, "SAD delete: auid=%u", auid);
2016                 break;
2017         case AUDIT_MAC_IPSEC_ADDSPD:
2018                 audit_log_format(audit_buf, "SPD add: auid=%u", auid);
2019                 break;
2020         case AUDIT_MAC_IPSEC_DELSPD:
2021                 audit_log_format(audit_buf, "SPD delete: auid=%u", auid);
2022                 break;
2023         default:
2024                 return;
2025         }
2026
2027         if (sid != 0 &&
2028                 security_secid_to_secctx(sid, &secctx, &secctx_len) == 0)
2029                 audit_log_format(audit_buf, " subj=%s", secctx);
2030         else
2031                 audit_log_task_context(audit_buf);
2032
2033         if (xp) {
2034                 family = xp->selector.family;
2035                 if (xp->security)
2036                         sctx = xp->security;
2037         } else {
2038                 family = x->props.family;
2039                 if (x->security)
2040                         sctx = x->security;
2041         }
2042
2043         if (sctx)
2044                 audit_log_format(audit_buf,
2045                                 " sec_alg=%u sec_doi=%u sec_obj=%s",
2046                                 sctx->ctx_alg, sctx->ctx_doi, sctx->ctx_str);
2047
2048         switch(family) {
2049         case AF_INET:
2050                 {
2051                         struct in_addr saddr, daddr;
2052                         if (xp) {
2053                                 saddr.s_addr = xp->selector.saddr.a4;
2054                                 daddr.s_addr = xp->selector.daddr.a4;
2055                         } else {
2056                                 saddr.s_addr = x->props.saddr.a4;
2057                                 daddr.s_addr = x->id.daddr.a4;
2058                         }
2059                         audit_log_format(audit_buf,
2060                                          " src=%u.%u.%u.%u dst=%u.%u.%u.%u",
2061                                          NIPQUAD(saddr), NIPQUAD(daddr));
2062                 }
2063                         break;
2064         case AF_INET6:
2065                 {
2066                         struct in6_addr saddr6, daddr6;
2067                         if (xp) {
2068                                 memcpy(&saddr6, xp->selector.saddr.a6,
2069                                         sizeof(struct in6_addr));
2070                                 memcpy(&daddr6, xp->selector.daddr.a6,
2071                                         sizeof(struct in6_addr));
2072                         } else {
2073                                 memcpy(&saddr6, x->props.saddr.a6,
2074                                         sizeof(struct in6_addr));
2075                                 memcpy(&daddr6, x->id.daddr.a6,
2076                                         sizeof(struct in6_addr));
2077                         }
2078                         audit_log_format(audit_buf,
2079                                          " src=" NIP6_FMT "dst=" NIP6_FMT,
2080                                          NIP6(saddr6), NIP6(daddr6));
2081                 }
2082                 break;
2083         }
2084
2085         if (x)
2086                 audit_log_format(audit_buf, " spi=%lu(0x%lx) protocol=%s",
2087                                 (unsigned long)ntohl(x->id.spi),
2088                                 (unsigned long)ntohl(x->id.spi),
2089                                 x->id.proto == IPPROTO_AH ? "AH" :
2090                                 (x->id.proto == IPPROTO_ESP ?
2091                                 "ESP" : "IPCOMP"));
2092
2093         audit_log_format(audit_buf, " res=%u", result);
2094         audit_log_end(audit_buf);
2095 }
2096
2097 EXPORT_SYMBOL(xfrm_audit_log);
2098 #endif /* CONFIG_AUDITSYSCALL */
2099
2100 int xfrm_policy_register_afinfo(struct xfrm_policy_afinfo *afinfo)
2101 {
2102         int err = 0;
2103         if (unlikely(afinfo == NULL))
2104                 return -EINVAL;
2105         if (unlikely(afinfo->family >= NPROTO))
2106                 return -EAFNOSUPPORT;
2107         write_lock_bh(&xfrm_policy_afinfo_lock);
2108         if (unlikely(xfrm_policy_afinfo[afinfo->family] != NULL))
2109                 err = -ENOBUFS;
2110         else {
2111                 struct dst_ops *dst_ops = afinfo->dst_ops;
2112                 if (likely(dst_ops->kmem_cachep == NULL))
2113                         dst_ops->kmem_cachep = xfrm_dst_cache;
2114                 if (likely(dst_ops->check == NULL))
2115                         dst_ops->check = xfrm_dst_check;
2116                 if (likely(dst_ops->negative_advice == NULL))
2117                         dst_ops->negative_advice = xfrm_negative_advice;
2118                 if (likely(dst_ops->link_failure == NULL))
2119                         dst_ops->link_failure = xfrm_link_failure;
2120                 if (likely(afinfo->garbage_collect == NULL))
2121                         afinfo->garbage_collect = __xfrm_garbage_collect;
2122                 xfrm_policy_afinfo[afinfo->family] = afinfo;
2123         }
2124         write_unlock_bh(&xfrm_policy_afinfo_lock);
2125         return err;
2126 }
2127 EXPORT_SYMBOL(xfrm_policy_register_afinfo);
2128
2129 int xfrm_policy_unregister_afinfo(struct xfrm_policy_afinfo *afinfo)
2130 {
2131         int err = 0;
2132         if (unlikely(afinfo == NULL))
2133                 return -EINVAL;
2134         if (unlikely(afinfo->family >= NPROTO))
2135                 return -EAFNOSUPPORT;
2136         write_lock_bh(&xfrm_policy_afinfo_lock);
2137         if (likely(xfrm_policy_afinfo[afinfo->family] != NULL)) {
2138                 if (unlikely(xfrm_policy_afinfo[afinfo->family] != afinfo))
2139                         err = -EINVAL;
2140                 else {
2141                         struct dst_ops *dst_ops = afinfo->dst_ops;
2142                         xfrm_policy_afinfo[afinfo->family] = NULL;
2143                         dst_ops->kmem_cachep = NULL;
2144                         dst_ops->check = NULL;
2145                         dst_ops->negative_advice = NULL;
2146                         dst_ops->link_failure = NULL;
2147                         afinfo->garbage_collect = NULL;
2148                 }
2149         }
2150         write_unlock_bh(&xfrm_policy_afinfo_lock);
2151         return err;
2152 }
2153 EXPORT_SYMBOL(xfrm_policy_unregister_afinfo);
2154
2155 static struct xfrm_policy_afinfo *xfrm_policy_get_afinfo(unsigned short family)
2156 {
2157         struct xfrm_policy_afinfo *afinfo;
2158         if (unlikely(family >= NPROTO))
2159                 return NULL;
2160         read_lock(&xfrm_policy_afinfo_lock);
2161         afinfo = xfrm_policy_afinfo[family];
2162         if (unlikely(!afinfo))
2163                 read_unlock(&xfrm_policy_afinfo_lock);
2164         return afinfo;
2165 }
2166
2167 static void xfrm_policy_put_afinfo(struct xfrm_policy_afinfo *afinfo)
2168 {
2169         read_unlock(&xfrm_policy_afinfo_lock);
2170 }
2171
2172 static struct xfrm_policy_afinfo *xfrm_policy_lock_afinfo(unsigned int family)
2173 {
2174         struct xfrm_policy_afinfo *afinfo;
2175         if (unlikely(family >= NPROTO))
2176                 return NULL;
2177         write_lock_bh(&xfrm_policy_afinfo_lock);
2178         afinfo = xfrm_policy_afinfo[family];
2179         if (unlikely(!afinfo))
2180                 write_unlock_bh(&xfrm_policy_afinfo_lock);
2181         return afinfo;
2182 }
2183
2184 static void xfrm_policy_unlock_afinfo(struct xfrm_policy_afinfo *afinfo)
2185 {
2186         write_unlock_bh(&xfrm_policy_afinfo_lock);
2187 }
2188
2189 static int xfrm_dev_event(struct notifier_block *this, unsigned long event, void *ptr)
2190 {
2191         switch (event) {
2192         case NETDEV_DOWN:
2193                 xfrm_flush_bundles();
2194         }
2195         return NOTIFY_DONE;
2196 }
2197
2198 static struct notifier_block xfrm_dev_notifier = {
2199         xfrm_dev_event,
2200         NULL,
2201         0
2202 };
2203
2204 static void __init xfrm_policy_init(void)
2205 {
2206         unsigned int hmask, sz;
2207         int dir;
2208
2209         xfrm_dst_cache = kmem_cache_create("xfrm_dst_cache",
2210                                            sizeof(struct xfrm_dst),
2211                                            0, SLAB_HWCACHE_ALIGN|SLAB_PANIC,
2212                                            NULL, NULL);
2213
2214         hmask = 8 - 1;
2215         sz = (hmask+1) * sizeof(struct hlist_head);
2216
2217         xfrm_policy_byidx = xfrm_hash_alloc(sz);
2218         xfrm_idx_hmask = hmask;
2219         if (!xfrm_policy_byidx)
2220                 panic("XFRM: failed to allocate byidx hash\n");
2221
2222         for (dir = 0; dir < XFRM_POLICY_MAX * 2; dir++) {
2223                 struct xfrm_policy_hash *htab;
2224
2225                 INIT_HLIST_HEAD(&xfrm_policy_inexact[dir]);
2226
2227                 htab = &xfrm_policy_bydst[dir];
2228                 htab->table = xfrm_hash_alloc(sz);
2229                 htab->hmask = hmask;
2230                 if (!htab->table)
2231                         panic("XFRM: failed to allocate bydst hash\n");
2232         }
2233
2234         INIT_WORK(&xfrm_policy_gc_work, xfrm_policy_gc_task);
2235         register_netdevice_notifier(&xfrm_dev_notifier);
2236 }
2237
2238 void __init xfrm_init(void)
2239 {
2240         xfrm_state_init();
2241         xfrm_policy_init();
2242         xfrm_input_init();
2243 }
2244