[XFRM]: Export SPD info
[cascardo/linux.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 = get_seconds();
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 void xfrm_spd_getinfo(struct xfrm_spdinfo *si)
583 {
584         read_lock_bh(&xfrm_policy_lock);
585         si->incnt = xfrm_policy_count[XFRM_POLICY_IN];
586         si->outcnt = xfrm_policy_count[XFRM_POLICY_OUT];
587         si->fwdcnt = xfrm_policy_count[XFRM_POLICY_FWD];
588         si->inscnt = xfrm_policy_count[XFRM_POLICY_IN+XFRM_POLICY_MAX];
589         si->outscnt = xfrm_policy_count[XFRM_POLICY_OUT+XFRM_POLICY_MAX];
590         si->fwdscnt = xfrm_policy_count[XFRM_POLICY_FWD+XFRM_POLICY_MAX];
591         si->spdhcnt = xfrm_idx_hmask;
592         si->spdhmcnt = xfrm_policy_hashmax;
593         read_unlock_bh(&xfrm_policy_lock);
594 }
595 EXPORT_SYMBOL(xfrm_spd_getinfo);
596
597 static DEFINE_MUTEX(hash_resize_mutex);
598 static void xfrm_hash_resize(struct work_struct *__unused)
599 {
600         int dir, total;
601
602         mutex_lock(&hash_resize_mutex);
603
604         total = 0;
605         for (dir = 0; dir < XFRM_POLICY_MAX * 2; dir++) {
606                 if (xfrm_bydst_should_resize(dir, &total))
607                         xfrm_bydst_resize(dir);
608         }
609         if (xfrm_byidx_should_resize(total))
610                 xfrm_byidx_resize(total);
611
612         mutex_unlock(&hash_resize_mutex);
613 }
614
615 static DECLARE_WORK(xfrm_hash_work, xfrm_hash_resize);
616
617 /* Generate new index... KAME seems to generate them ordered by cost
618  * of an absolute inpredictability of ordering of rules. This will not pass. */
619 static u32 xfrm_gen_index(u8 type, int dir)
620 {
621         static u32 idx_generator;
622
623         for (;;) {
624                 struct hlist_node *entry;
625                 struct hlist_head *list;
626                 struct xfrm_policy *p;
627                 u32 idx;
628                 int found;
629
630                 idx = (idx_generator | dir);
631                 idx_generator += 8;
632                 if (idx == 0)
633                         idx = 8;
634                 list = xfrm_policy_byidx + idx_hash(idx);
635                 found = 0;
636                 hlist_for_each_entry(p, entry, list, byidx) {
637                         if (p->index == idx) {
638                                 found = 1;
639                                 break;
640                         }
641                 }
642                 if (!found)
643                         return idx;
644         }
645 }
646
647 static inline int selector_cmp(struct xfrm_selector *s1, struct xfrm_selector *s2)
648 {
649         u32 *p1 = (u32 *) s1;
650         u32 *p2 = (u32 *) s2;
651         int len = sizeof(struct xfrm_selector) / sizeof(u32);
652         int i;
653
654         for (i = 0; i < len; i++) {
655                 if (p1[i] != p2[i])
656                         return 1;
657         }
658
659         return 0;
660 }
661
662 int xfrm_policy_insert(int dir, struct xfrm_policy *policy, int excl)
663 {
664         struct xfrm_policy *pol;
665         struct xfrm_policy *delpol;
666         struct hlist_head *chain;
667         struct hlist_node *entry, *newpos;
668         struct dst_entry *gc_list;
669
670         write_lock_bh(&xfrm_policy_lock);
671         chain = policy_hash_bysel(&policy->selector, policy->family, dir);
672         delpol = NULL;
673         newpos = NULL;
674         hlist_for_each_entry(pol, entry, chain, bydst) {
675                 if (pol->type == policy->type &&
676                     !selector_cmp(&pol->selector, &policy->selector) &&
677                     xfrm_sec_ctx_match(pol->security, policy->security) &&
678                     !WARN_ON(delpol)) {
679                         if (excl) {
680                                 write_unlock_bh(&xfrm_policy_lock);
681                                 return -EEXIST;
682                         }
683                         delpol = pol;
684                         if (policy->priority > pol->priority)
685                                 continue;
686                 } else if (policy->priority >= pol->priority) {
687                         newpos = &pol->bydst;
688                         continue;
689                 }
690                 if (delpol)
691                         break;
692         }
693         if (newpos)
694                 hlist_add_after(newpos, &policy->bydst);
695         else
696                 hlist_add_head(&policy->bydst, chain);
697         xfrm_pol_hold(policy);
698         xfrm_policy_count[dir]++;
699         atomic_inc(&flow_cache_genid);
700         if (delpol) {
701                 hlist_del(&delpol->bydst);
702                 hlist_del(&delpol->byidx);
703                 xfrm_policy_count[dir]--;
704         }
705         policy->index = delpol ? delpol->index : xfrm_gen_index(policy->type, dir);
706         hlist_add_head(&policy->byidx, xfrm_policy_byidx+idx_hash(policy->index));
707         policy->curlft.add_time = get_seconds();
708         policy->curlft.use_time = 0;
709         if (!mod_timer(&policy->timer, jiffies + HZ))
710                 xfrm_pol_hold(policy);
711         write_unlock_bh(&xfrm_policy_lock);
712
713         if (delpol)
714                 xfrm_policy_kill(delpol);
715         else if (xfrm_bydst_should_resize(dir, NULL))
716                 schedule_work(&xfrm_hash_work);
717
718         read_lock_bh(&xfrm_policy_lock);
719         gc_list = NULL;
720         entry = &policy->bydst;
721         hlist_for_each_entry_continue(policy, entry, bydst) {
722                 struct dst_entry *dst;
723
724                 write_lock(&policy->lock);
725                 dst = policy->bundles;
726                 if (dst) {
727                         struct dst_entry *tail = dst;
728                         while (tail->next)
729                                 tail = tail->next;
730                         tail->next = gc_list;
731                         gc_list = dst;
732
733                         policy->bundles = NULL;
734                 }
735                 write_unlock(&policy->lock);
736         }
737         read_unlock_bh(&xfrm_policy_lock);
738
739         while (gc_list) {
740                 struct dst_entry *dst = gc_list;
741
742                 gc_list = dst->next;
743                 dst_free(dst);
744         }
745
746         return 0;
747 }
748 EXPORT_SYMBOL(xfrm_policy_insert);
749
750 struct xfrm_policy *xfrm_policy_bysel_ctx(u8 type, int dir,
751                                           struct xfrm_selector *sel,
752                                           struct xfrm_sec_ctx *ctx, int delete,
753                                           int *err)
754 {
755         struct xfrm_policy *pol, *ret;
756         struct hlist_head *chain;
757         struct hlist_node *entry;
758
759         *err = 0;
760         write_lock_bh(&xfrm_policy_lock);
761         chain = policy_hash_bysel(sel, sel->family, dir);
762         ret = NULL;
763         hlist_for_each_entry(pol, entry, chain, bydst) {
764                 if (pol->type == type &&
765                     !selector_cmp(sel, &pol->selector) &&
766                     xfrm_sec_ctx_match(ctx, pol->security)) {
767                         xfrm_pol_hold(pol);
768                         if (delete) {
769                                 *err = security_xfrm_policy_delete(pol);
770                                 if (*err) {
771                                         write_unlock_bh(&xfrm_policy_lock);
772                                         return pol;
773                                 }
774                                 hlist_del(&pol->bydst);
775                                 hlist_del(&pol->byidx);
776                                 xfrm_policy_count[dir]--;
777                         }
778                         ret = pol;
779                         break;
780                 }
781         }
782         write_unlock_bh(&xfrm_policy_lock);
783
784         if (ret && delete) {
785                 atomic_inc(&flow_cache_genid);
786                 xfrm_policy_kill(ret);
787         }
788         return ret;
789 }
790 EXPORT_SYMBOL(xfrm_policy_bysel_ctx);
791
792 struct xfrm_policy *xfrm_policy_byid(u8 type, int dir, u32 id, int delete,
793                                      int *err)
794 {
795         struct xfrm_policy *pol, *ret;
796         struct hlist_head *chain;
797         struct hlist_node *entry;
798
799         *err = 0;
800         write_lock_bh(&xfrm_policy_lock);
801         chain = xfrm_policy_byidx + idx_hash(id);
802         ret = NULL;
803         hlist_for_each_entry(pol, entry, chain, byidx) {
804                 if (pol->type == type && pol->index == id) {
805                         xfrm_pol_hold(pol);
806                         if (delete) {
807                                 *err = security_xfrm_policy_delete(pol);
808                                 if (*err) {
809                                         write_unlock_bh(&xfrm_policy_lock);
810                                         return pol;
811                                 }
812                                 hlist_del(&pol->bydst);
813                                 hlist_del(&pol->byidx);
814                                 xfrm_policy_count[dir]--;
815                         }
816                         ret = pol;
817                         break;
818                 }
819         }
820         write_unlock_bh(&xfrm_policy_lock);
821
822         if (ret && delete) {
823                 atomic_inc(&flow_cache_genid);
824                 xfrm_policy_kill(ret);
825         }
826         return ret;
827 }
828 EXPORT_SYMBOL(xfrm_policy_byid);
829
830 void xfrm_policy_flush(u8 type, struct xfrm_audit *audit_info)
831 {
832         int dir;
833
834         write_lock_bh(&xfrm_policy_lock);
835         for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
836                 struct xfrm_policy *pol;
837                 struct hlist_node *entry;
838                 int i, killed;
839
840                 killed = 0;
841         again1:
842                 hlist_for_each_entry(pol, entry,
843                                      &xfrm_policy_inexact[dir], bydst) {
844                         if (pol->type != type)
845                                 continue;
846                         hlist_del(&pol->bydst);
847                         hlist_del(&pol->byidx);
848                         write_unlock_bh(&xfrm_policy_lock);
849
850                         xfrm_audit_log(audit_info->loginuid, audit_info->secid,
851                                        AUDIT_MAC_IPSEC_DELSPD, 1, pol, NULL);
852
853                         xfrm_policy_kill(pol);
854                         killed++;
855
856                         write_lock_bh(&xfrm_policy_lock);
857                         goto again1;
858                 }
859
860                 for (i = xfrm_policy_bydst[dir].hmask; i >= 0; i--) {
861         again2:
862                         hlist_for_each_entry(pol, entry,
863                                              xfrm_policy_bydst[dir].table + i,
864                                              bydst) {
865                                 if (pol->type != type)
866                                         continue;
867                                 hlist_del(&pol->bydst);
868                                 hlist_del(&pol->byidx);
869                                 write_unlock_bh(&xfrm_policy_lock);
870
871                                 xfrm_audit_log(audit_info->loginuid,
872                                                audit_info->secid,
873                                                AUDIT_MAC_IPSEC_DELSPD, 1,
874                                                pol, NULL);
875
876                                 xfrm_policy_kill(pol);
877                                 killed++;
878
879                                 write_lock_bh(&xfrm_policy_lock);
880                                 goto again2;
881                         }
882                 }
883
884                 xfrm_policy_count[dir] -= killed;
885         }
886         atomic_inc(&flow_cache_genid);
887         write_unlock_bh(&xfrm_policy_lock);
888 }
889 EXPORT_SYMBOL(xfrm_policy_flush);
890
891 int xfrm_policy_walk(u8 type, int (*func)(struct xfrm_policy *, int, int, void*),
892                      void *data)
893 {
894         struct xfrm_policy *pol, *last = NULL;
895         struct hlist_node *entry;
896         int dir, last_dir = 0, count, error;
897
898         read_lock_bh(&xfrm_policy_lock);
899         count = 0;
900
901         for (dir = 0; dir < 2*XFRM_POLICY_MAX; dir++) {
902                 struct hlist_head *table = xfrm_policy_bydst[dir].table;
903                 int i;
904
905                 hlist_for_each_entry(pol, entry,
906                                      &xfrm_policy_inexact[dir], bydst) {
907                         if (pol->type != type)
908                                 continue;
909                         if (last) {
910                                 error = func(last, last_dir % XFRM_POLICY_MAX,
911                                              count, data);
912                                 if (error)
913                                         goto out;
914                         }
915                         last = pol;
916                         last_dir = dir;
917                         count++;
918                 }
919                 for (i = xfrm_policy_bydst[dir].hmask; i >= 0; i--) {
920                         hlist_for_each_entry(pol, entry, table + i, bydst) {
921                                 if (pol->type != type)
922                                         continue;
923                                 if (last) {
924                                         error = func(last, last_dir % XFRM_POLICY_MAX,
925                                                      count, data);
926                                         if (error)
927                                                 goto out;
928                                 }
929                                 last = pol;
930                                 last_dir = dir;
931                                 count++;
932                         }
933                 }
934         }
935         if (count == 0) {
936                 error = -ENOENT;
937                 goto out;
938         }
939         error = func(last, last_dir % XFRM_POLICY_MAX, 0, data);
940 out:
941         read_unlock_bh(&xfrm_policy_lock);
942         return error;
943 }
944 EXPORT_SYMBOL(xfrm_policy_walk);
945
946 /*
947  * Find policy to apply to this flow.
948  *
949  * Returns 0 if policy found, else an -errno.
950  */
951 static int xfrm_policy_match(struct xfrm_policy *pol, struct flowi *fl,
952                              u8 type, u16 family, int dir)
953 {
954         struct xfrm_selector *sel = &pol->selector;
955         int match, ret = -ESRCH;
956
957         if (pol->family != family ||
958             pol->type != type)
959                 return ret;
960
961         match = xfrm_selector_match(sel, fl, family);
962         if (match)
963                 ret = security_xfrm_policy_lookup(pol, fl->secid, dir);
964
965         return ret;
966 }
967
968 static struct xfrm_policy *xfrm_policy_lookup_bytype(u8 type, struct flowi *fl,
969                                                      u16 family, u8 dir)
970 {
971         int err;
972         struct xfrm_policy *pol, *ret;
973         xfrm_address_t *daddr, *saddr;
974         struct hlist_node *entry;
975         struct hlist_head *chain;
976         u32 priority = ~0U;
977
978         daddr = xfrm_flowi_daddr(fl, family);
979         saddr = xfrm_flowi_saddr(fl, family);
980         if (unlikely(!daddr || !saddr))
981                 return NULL;
982
983         read_lock_bh(&xfrm_policy_lock);
984         chain = policy_hash_direct(daddr, saddr, family, dir);
985         ret = NULL;
986         hlist_for_each_entry(pol, entry, chain, bydst) {
987                 err = xfrm_policy_match(pol, fl, type, family, dir);
988                 if (err) {
989                         if (err == -ESRCH)
990                                 continue;
991                         else {
992                                 ret = ERR_PTR(err);
993                                 goto fail;
994                         }
995                 } else {
996                         ret = pol;
997                         priority = ret->priority;
998                         break;
999                 }
1000         }
1001         chain = &xfrm_policy_inexact[dir];
1002         hlist_for_each_entry(pol, entry, chain, bydst) {
1003                 err = xfrm_policy_match(pol, fl, type, family, dir);
1004                 if (err) {
1005                         if (err == -ESRCH)
1006                                 continue;
1007                         else {
1008                                 ret = ERR_PTR(err);
1009                                 goto fail;
1010                         }
1011                 } else if (pol->priority < priority) {
1012                         ret = pol;
1013                         break;
1014                 }
1015         }
1016         if (ret)
1017                 xfrm_pol_hold(ret);
1018 fail:
1019         read_unlock_bh(&xfrm_policy_lock);
1020
1021         return ret;
1022 }
1023
1024 static int xfrm_policy_lookup(struct flowi *fl, u16 family, u8 dir,
1025                                void **objp, atomic_t **obj_refp)
1026 {
1027         struct xfrm_policy *pol;
1028         int err = 0;
1029
1030 #ifdef CONFIG_XFRM_SUB_POLICY
1031         pol = xfrm_policy_lookup_bytype(XFRM_POLICY_TYPE_SUB, fl, family, dir);
1032         if (IS_ERR(pol)) {
1033                 err = PTR_ERR(pol);
1034                 pol = NULL;
1035         }
1036         if (pol || err)
1037                 goto end;
1038 #endif
1039         pol = xfrm_policy_lookup_bytype(XFRM_POLICY_TYPE_MAIN, fl, family, dir);
1040         if (IS_ERR(pol)) {
1041                 err = PTR_ERR(pol);
1042                 pol = NULL;
1043         }
1044 #ifdef CONFIG_XFRM_SUB_POLICY
1045 end:
1046 #endif
1047         if ((*objp = (void *) pol) != NULL)
1048                 *obj_refp = &pol->refcnt;
1049         return err;
1050 }
1051
1052 static inline int policy_to_flow_dir(int dir)
1053 {
1054         if (XFRM_POLICY_IN == FLOW_DIR_IN &&
1055             XFRM_POLICY_OUT == FLOW_DIR_OUT &&
1056             XFRM_POLICY_FWD == FLOW_DIR_FWD)
1057                 return dir;
1058         switch (dir) {
1059         default:
1060         case XFRM_POLICY_IN:
1061                 return FLOW_DIR_IN;
1062         case XFRM_POLICY_OUT:
1063                 return FLOW_DIR_OUT;
1064         case XFRM_POLICY_FWD:
1065                 return FLOW_DIR_FWD;
1066         }
1067 }
1068
1069 static struct xfrm_policy *xfrm_sk_policy_lookup(struct sock *sk, int dir, struct flowi *fl)
1070 {
1071         struct xfrm_policy *pol;
1072
1073         read_lock_bh(&xfrm_policy_lock);
1074         if ((pol = sk->sk_policy[dir]) != NULL) {
1075                 int match = xfrm_selector_match(&pol->selector, fl,
1076                                                 sk->sk_family);
1077                 int err = 0;
1078
1079                 if (match) {
1080                         err = security_xfrm_policy_lookup(pol, fl->secid,
1081                                         policy_to_flow_dir(dir));
1082                         if (!err)
1083                                 xfrm_pol_hold(pol);
1084                         else if (err == -ESRCH)
1085                                 pol = NULL;
1086                         else
1087                                 pol = ERR_PTR(err);
1088                 } else
1089                         pol = NULL;
1090         }
1091         read_unlock_bh(&xfrm_policy_lock);
1092         return pol;
1093 }
1094
1095 static void __xfrm_policy_link(struct xfrm_policy *pol, int dir)
1096 {
1097         struct hlist_head *chain = policy_hash_bysel(&pol->selector,
1098                                                      pol->family, dir);
1099
1100         hlist_add_head(&pol->bydst, chain);
1101         hlist_add_head(&pol->byidx, xfrm_policy_byidx+idx_hash(pol->index));
1102         xfrm_policy_count[dir]++;
1103         xfrm_pol_hold(pol);
1104
1105         if (xfrm_bydst_should_resize(dir, NULL))
1106                 schedule_work(&xfrm_hash_work);
1107 }
1108
1109 static struct xfrm_policy *__xfrm_policy_unlink(struct xfrm_policy *pol,
1110                                                 int dir)
1111 {
1112         if (hlist_unhashed(&pol->bydst))
1113                 return NULL;
1114
1115         hlist_del(&pol->bydst);
1116         hlist_del(&pol->byidx);
1117         xfrm_policy_count[dir]--;
1118
1119         return pol;
1120 }
1121
1122 int xfrm_policy_delete(struct xfrm_policy *pol, int dir)
1123 {
1124         write_lock_bh(&xfrm_policy_lock);
1125         pol = __xfrm_policy_unlink(pol, dir);
1126         write_unlock_bh(&xfrm_policy_lock);
1127         if (pol) {
1128                 if (dir < XFRM_POLICY_MAX)
1129                         atomic_inc(&flow_cache_genid);
1130                 xfrm_policy_kill(pol);
1131                 return 0;
1132         }
1133         return -ENOENT;
1134 }
1135 EXPORT_SYMBOL(xfrm_policy_delete);
1136
1137 int xfrm_sk_policy_insert(struct sock *sk, int dir, struct xfrm_policy *pol)
1138 {
1139         struct xfrm_policy *old_pol;
1140
1141 #ifdef CONFIG_XFRM_SUB_POLICY
1142         if (pol && pol->type != XFRM_POLICY_TYPE_MAIN)
1143                 return -EINVAL;
1144 #endif
1145
1146         write_lock_bh(&xfrm_policy_lock);
1147         old_pol = sk->sk_policy[dir];
1148         sk->sk_policy[dir] = pol;
1149         if (pol) {
1150                 pol->curlft.add_time = get_seconds();
1151                 pol->index = xfrm_gen_index(pol->type, XFRM_POLICY_MAX+dir);
1152                 __xfrm_policy_link(pol, XFRM_POLICY_MAX+dir);
1153         }
1154         if (old_pol)
1155                 __xfrm_policy_unlink(old_pol, XFRM_POLICY_MAX+dir);
1156         write_unlock_bh(&xfrm_policy_lock);
1157
1158         if (old_pol) {
1159                 xfrm_policy_kill(old_pol);
1160         }
1161         return 0;
1162 }
1163
1164 static struct xfrm_policy *clone_policy(struct xfrm_policy *old, int dir)
1165 {
1166         struct xfrm_policy *newp = xfrm_policy_alloc(GFP_ATOMIC);
1167
1168         if (newp) {
1169                 newp->selector = old->selector;
1170                 if (security_xfrm_policy_clone(old, newp)) {
1171                         kfree(newp);
1172                         return NULL;  /* ENOMEM */
1173                 }
1174                 newp->lft = old->lft;
1175                 newp->curlft = old->curlft;
1176                 newp->action = old->action;
1177                 newp->flags = old->flags;
1178                 newp->xfrm_nr = old->xfrm_nr;
1179                 newp->index = old->index;
1180                 newp->type = old->type;
1181                 memcpy(newp->xfrm_vec, old->xfrm_vec,
1182                        newp->xfrm_nr*sizeof(struct xfrm_tmpl));
1183                 write_lock_bh(&xfrm_policy_lock);
1184                 __xfrm_policy_link(newp, XFRM_POLICY_MAX+dir);
1185                 write_unlock_bh(&xfrm_policy_lock);
1186                 xfrm_pol_put(newp);
1187         }
1188         return newp;
1189 }
1190
1191 int __xfrm_sk_clone_policy(struct sock *sk)
1192 {
1193         struct xfrm_policy *p0 = sk->sk_policy[0],
1194                            *p1 = sk->sk_policy[1];
1195
1196         sk->sk_policy[0] = sk->sk_policy[1] = NULL;
1197         if (p0 && (sk->sk_policy[0] = clone_policy(p0, 0)) == NULL)
1198                 return -ENOMEM;
1199         if (p1 && (sk->sk_policy[1] = clone_policy(p1, 1)) == NULL)
1200                 return -ENOMEM;
1201         return 0;
1202 }
1203
1204 static int
1205 xfrm_get_saddr(xfrm_address_t *local, xfrm_address_t *remote,
1206                unsigned short family)
1207 {
1208         int err;
1209         struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1210
1211         if (unlikely(afinfo == NULL))
1212                 return -EINVAL;
1213         err = afinfo->get_saddr(local, remote);
1214         xfrm_policy_put_afinfo(afinfo);
1215         return err;
1216 }
1217
1218 /* Resolve list of templates for the flow, given policy. */
1219
1220 static int
1221 xfrm_tmpl_resolve_one(struct xfrm_policy *policy, struct flowi *fl,
1222                       struct xfrm_state **xfrm,
1223                       unsigned short family)
1224 {
1225         int nx;
1226         int i, error;
1227         xfrm_address_t *daddr = xfrm_flowi_daddr(fl, family);
1228         xfrm_address_t *saddr = xfrm_flowi_saddr(fl, family);
1229         xfrm_address_t tmp;
1230
1231         for (nx=0, i = 0; i < policy->xfrm_nr; i++) {
1232                 struct xfrm_state *x;
1233                 xfrm_address_t *remote = daddr;
1234                 xfrm_address_t *local  = saddr;
1235                 struct xfrm_tmpl *tmpl = &policy->xfrm_vec[i];
1236
1237                 if (tmpl->mode == XFRM_MODE_TUNNEL) {
1238                         remote = &tmpl->id.daddr;
1239                         local = &tmpl->saddr;
1240                         family = tmpl->encap_family;
1241                         if (xfrm_addr_any(local, family)) {
1242                                 error = xfrm_get_saddr(&tmp, remote, family);
1243                                 if (error)
1244                                         goto fail;
1245                                 local = &tmp;
1246                         }
1247                 }
1248
1249                 x = xfrm_state_find(remote, local, fl, tmpl, policy, &error, family);
1250
1251                 if (x && x->km.state == XFRM_STATE_VALID) {
1252                         xfrm[nx++] = x;
1253                         daddr = remote;
1254                         saddr = local;
1255                         continue;
1256                 }
1257                 if (x) {
1258                         error = (x->km.state == XFRM_STATE_ERROR ?
1259                                  -EINVAL : -EAGAIN);
1260                         xfrm_state_put(x);
1261                 }
1262
1263                 if (!tmpl->optional)
1264                         goto fail;
1265         }
1266         return nx;
1267
1268 fail:
1269         for (nx--; nx>=0; nx--)
1270                 xfrm_state_put(xfrm[nx]);
1271         return error;
1272 }
1273
1274 static int
1275 xfrm_tmpl_resolve(struct xfrm_policy **pols, int npols, struct flowi *fl,
1276                   struct xfrm_state **xfrm,
1277                   unsigned short family)
1278 {
1279         struct xfrm_state *tp[XFRM_MAX_DEPTH];
1280         struct xfrm_state **tpp = (npols > 1) ? tp : xfrm;
1281         int cnx = 0;
1282         int error;
1283         int ret;
1284         int i;
1285
1286         for (i = 0; i < npols; i++) {
1287                 if (cnx + pols[i]->xfrm_nr >= XFRM_MAX_DEPTH) {
1288                         error = -ENOBUFS;
1289                         goto fail;
1290                 }
1291
1292                 ret = xfrm_tmpl_resolve_one(pols[i], fl, &tpp[cnx], family);
1293                 if (ret < 0) {
1294                         error = ret;
1295                         goto fail;
1296                 } else
1297                         cnx += ret;
1298         }
1299
1300         /* found states are sorted for outbound processing */
1301         if (npols > 1)
1302                 xfrm_state_sort(xfrm, tpp, cnx, family);
1303
1304         return cnx;
1305
1306  fail:
1307         for (cnx--; cnx>=0; cnx--)
1308                 xfrm_state_put(tpp[cnx]);
1309         return error;
1310
1311 }
1312
1313 /* Check that the bundle accepts the flow and its components are
1314  * still valid.
1315  */
1316
1317 static struct dst_entry *
1318 xfrm_find_bundle(struct flowi *fl, struct xfrm_policy *policy, unsigned short family)
1319 {
1320         struct dst_entry *x;
1321         struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1322         if (unlikely(afinfo == NULL))
1323                 return ERR_PTR(-EINVAL);
1324         x = afinfo->find_bundle(fl, policy);
1325         xfrm_policy_put_afinfo(afinfo);
1326         return x;
1327 }
1328
1329 /* Allocate chain of dst_entry's, attach known xfrm's, calculate
1330  * all the metrics... Shortly, bundle a bundle.
1331  */
1332
1333 static int
1334 xfrm_bundle_create(struct xfrm_policy *policy, struct xfrm_state **xfrm, int nx,
1335                    struct flowi *fl, struct dst_entry **dst_p,
1336                    unsigned short family)
1337 {
1338         int err;
1339         struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1340         if (unlikely(afinfo == NULL))
1341                 return -EINVAL;
1342         err = afinfo->bundle_create(policy, xfrm, nx, fl, dst_p);
1343         xfrm_policy_put_afinfo(afinfo);
1344         return err;
1345 }
1346
1347
1348 static int stale_bundle(struct dst_entry *dst);
1349
1350 /* Main function: finds/creates a bundle for given flow.
1351  *
1352  * At the moment we eat a raw IP route. Mostly to speed up lookups
1353  * on interfaces with disabled IPsec.
1354  */
1355 int xfrm_lookup(struct dst_entry **dst_p, struct flowi *fl,
1356                 struct sock *sk, int flags)
1357 {
1358         struct xfrm_policy *policy;
1359         struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
1360         int npols;
1361         int pol_dead;
1362         int xfrm_nr;
1363         int pi;
1364         struct xfrm_state *xfrm[XFRM_MAX_DEPTH];
1365         struct dst_entry *dst, *dst_orig = *dst_p;
1366         int nx = 0;
1367         int err;
1368         u32 genid;
1369         u16 family;
1370         u8 dir = policy_to_flow_dir(XFRM_POLICY_OUT);
1371
1372 restart:
1373         genid = atomic_read(&flow_cache_genid);
1374         policy = NULL;
1375         for (pi = 0; pi < ARRAY_SIZE(pols); pi++)
1376                 pols[pi] = NULL;
1377         npols = 0;
1378         pol_dead = 0;
1379         xfrm_nr = 0;
1380
1381         if (sk && sk->sk_policy[1]) {
1382                 policy = xfrm_sk_policy_lookup(sk, XFRM_POLICY_OUT, fl);
1383                 if (IS_ERR(policy))
1384                         return PTR_ERR(policy);
1385         }
1386
1387         if (!policy) {
1388                 /* To accelerate a bit...  */
1389                 if ((dst_orig->flags & DST_NOXFRM) ||
1390                     !xfrm_policy_count[XFRM_POLICY_OUT])
1391                         return 0;
1392
1393                 policy = flow_cache_lookup(fl, dst_orig->ops->family,
1394                                            dir, xfrm_policy_lookup);
1395                 if (IS_ERR(policy))
1396                         return PTR_ERR(policy);
1397         }
1398
1399         if (!policy)
1400                 return 0;
1401
1402         family = dst_orig->ops->family;
1403         policy->curlft.use_time = get_seconds();
1404         pols[0] = policy;
1405         npols ++;
1406         xfrm_nr += pols[0]->xfrm_nr;
1407
1408         switch (policy->action) {
1409         case XFRM_POLICY_BLOCK:
1410                 /* Prohibit the flow */
1411                 err = -EPERM;
1412                 goto error;
1413
1414         case XFRM_POLICY_ALLOW:
1415 #ifndef CONFIG_XFRM_SUB_POLICY
1416                 if (policy->xfrm_nr == 0) {
1417                         /* Flow passes not transformed. */
1418                         xfrm_pol_put(policy);
1419                         return 0;
1420                 }
1421 #endif
1422
1423                 /* Try to find matching bundle.
1424                  *
1425                  * LATER: help from flow cache. It is optional, this
1426                  * is required only for output policy.
1427                  */
1428                 dst = xfrm_find_bundle(fl, policy, family);
1429                 if (IS_ERR(dst)) {
1430                         err = PTR_ERR(dst);
1431                         goto error;
1432                 }
1433
1434                 if (dst)
1435                         break;
1436
1437 #ifdef CONFIG_XFRM_SUB_POLICY
1438                 if (pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
1439                         pols[1] = xfrm_policy_lookup_bytype(XFRM_POLICY_TYPE_MAIN,
1440                                                             fl, family,
1441                                                             XFRM_POLICY_OUT);
1442                         if (pols[1]) {
1443                                 if (IS_ERR(pols[1])) {
1444                                         err = PTR_ERR(pols[1]);
1445                                         goto error;
1446                                 }
1447                                 if (pols[1]->action == XFRM_POLICY_BLOCK) {
1448                                         err = -EPERM;
1449                                         goto error;
1450                                 }
1451                                 npols ++;
1452                                 xfrm_nr += pols[1]->xfrm_nr;
1453                         }
1454                 }
1455
1456                 /*
1457                  * Because neither flowi nor bundle information knows about
1458                  * transformation template size. On more than one policy usage
1459                  * we can realize whether all of them is bypass or not after
1460                  * they are searched. See above not-transformed bypass
1461                  * is surrounded by non-sub policy configuration, too.
1462                  */
1463                 if (xfrm_nr == 0) {
1464                         /* Flow passes not transformed. */
1465                         xfrm_pols_put(pols, npols);
1466                         return 0;
1467                 }
1468
1469 #endif
1470                 nx = xfrm_tmpl_resolve(pols, npols, fl, xfrm, family);
1471
1472                 if (unlikely(nx<0)) {
1473                         err = nx;
1474                         if (err == -EAGAIN && flags) {
1475                                 DECLARE_WAITQUEUE(wait, current);
1476
1477                                 add_wait_queue(&km_waitq, &wait);
1478                                 set_current_state(TASK_INTERRUPTIBLE);
1479                                 schedule();
1480                                 set_current_state(TASK_RUNNING);
1481                                 remove_wait_queue(&km_waitq, &wait);
1482
1483                                 nx = xfrm_tmpl_resolve(pols, npols, fl, xfrm, family);
1484
1485                                 if (nx == -EAGAIN && signal_pending(current)) {
1486                                         err = -ERESTART;
1487                                         goto error;
1488                                 }
1489                                 if (nx == -EAGAIN ||
1490                                     genid != atomic_read(&flow_cache_genid)) {
1491                                         xfrm_pols_put(pols, npols);
1492                                         goto restart;
1493                                 }
1494                                 err = nx;
1495                         }
1496                         if (err < 0)
1497                                 goto error;
1498                 }
1499                 if (nx == 0) {
1500                         /* Flow passes not transformed. */
1501                         xfrm_pols_put(pols, npols);
1502                         return 0;
1503                 }
1504
1505                 dst = dst_orig;
1506                 err = xfrm_bundle_create(policy, xfrm, nx, fl, &dst, family);
1507
1508                 if (unlikely(err)) {
1509                         int i;
1510                         for (i=0; i<nx; i++)
1511                                 xfrm_state_put(xfrm[i]);
1512                         goto error;
1513                 }
1514
1515                 for (pi = 0; pi < npols; pi++) {
1516                         read_lock_bh(&pols[pi]->lock);
1517                         pol_dead |= pols[pi]->dead;
1518                         read_unlock_bh(&pols[pi]->lock);
1519                 }
1520
1521                 write_lock_bh(&policy->lock);
1522                 if (unlikely(pol_dead || stale_bundle(dst))) {
1523                         /* Wow! While we worked on resolving, this
1524                          * policy has gone. Retry. It is not paranoia,
1525                          * we just cannot enlist new bundle to dead object.
1526                          * We can't enlist stable bundles either.
1527                          */
1528                         write_unlock_bh(&policy->lock);
1529                         if (dst)
1530                                 dst_free(dst);
1531
1532                         err = -EHOSTUNREACH;
1533                         goto error;
1534                 }
1535                 dst->next = policy->bundles;
1536                 policy->bundles = dst;
1537                 dst_hold(dst);
1538                 write_unlock_bh(&policy->lock);
1539         }
1540         *dst_p = dst;
1541         dst_release(dst_orig);
1542         xfrm_pols_put(pols, npols);
1543         return 0;
1544
1545 error:
1546         dst_release(dst_orig);
1547         xfrm_pols_put(pols, npols);
1548         *dst_p = NULL;
1549         return err;
1550 }
1551 EXPORT_SYMBOL(xfrm_lookup);
1552
1553 static inline int
1554 xfrm_secpath_reject(int idx, struct sk_buff *skb, struct flowi *fl)
1555 {
1556         struct xfrm_state *x;
1557         int err;
1558
1559         if (!skb->sp || idx < 0 || idx >= skb->sp->len)
1560                 return 0;
1561         x = skb->sp->xvec[idx];
1562         if (!x->type->reject)
1563                 return 0;
1564         xfrm_state_hold(x);
1565         err = x->type->reject(x, skb, fl);
1566         xfrm_state_put(x);
1567         return err;
1568 }
1569
1570 /* When skb is transformed back to its "native" form, we have to
1571  * check policy restrictions. At the moment we make this in maximally
1572  * stupid way. Shame on me. :-) Of course, connected sockets must
1573  * have policy cached at them.
1574  */
1575
1576 static inline int
1577 xfrm_state_ok(struct xfrm_tmpl *tmpl, struct xfrm_state *x,
1578               unsigned short family)
1579 {
1580         if (xfrm_state_kern(x))
1581                 return tmpl->optional && !xfrm_state_addr_cmp(tmpl, x, tmpl->encap_family);
1582         return  x->id.proto == tmpl->id.proto &&
1583                 (x->id.spi == tmpl->id.spi || !tmpl->id.spi) &&
1584                 (x->props.reqid == tmpl->reqid || !tmpl->reqid) &&
1585                 x->props.mode == tmpl->mode &&
1586                 ((tmpl->aalgos & (1<<x->props.aalgo)) ||
1587                  !(xfrm_id_proto_match(tmpl->id.proto, IPSEC_PROTO_ANY))) &&
1588                 !(x->props.mode != XFRM_MODE_TRANSPORT &&
1589                   xfrm_state_addr_cmp(tmpl, x, family));
1590 }
1591
1592 /*
1593  * 0 or more than 0 is returned when validation is succeeded (either bypass
1594  * because of optional transport mode, or next index of the mathced secpath
1595  * state with the template.
1596  * -1 is returned when no matching template is found.
1597  * Otherwise "-2 - errored_index" is returned.
1598  */
1599 static inline int
1600 xfrm_policy_ok(struct xfrm_tmpl *tmpl, struct sec_path *sp, int start,
1601                unsigned short family)
1602 {
1603         int idx = start;
1604
1605         if (tmpl->optional) {
1606                 if (tmpl->mode == XFRM_MODE_TRANSPORT)
1607                         return start;
1608         } else
1609                 start = -1;
1610         for (; idx < sp->len; idx++) {
1611                 if (xfrm_state_ok(tmpl, sp->xvec[idx], family))
1612                         return ++idx;
1613                 if (sp->xvec[idx]->props.mode != XFRM_MODE_TRANSPORT) {
1614                         if (start == -1)
1615                                 start = -2-idx;
1616                         break;
1617                 }
1618         }
1619         return start;
1620 }
1621
1622 int
1623 xfrm_decode_session(struct sk_buff *skb, struct flowi *fl, unsigned short family)
1624 {
1625         struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1626         int err;
1627
1628         if (unlikely(afinfo == NULL))
1629                 return -EAFNOSUPPORT;
1630
1631         afinfo->decode_session(skb, fl);
1632         err = security_xfrm_decode_session(skb, &fl->secid);
1633         xfrm_policy_put_afinfo(afinfo);
1634         return err;
1635 }
1636 EXPORT_SYMBOL(xfrm_decode_session);
1637
1638 static inline int secpath_has_nontransport(struct sec_path *sp, int k, int *idxp)
1639 {
1640         for (; k < sp->len; k++) {
1641                 if (sp->xvec[k]->props.mode != XFRM_MODE_TRANSPORT) {
1642                         *idxp = k;
1643                         return 1;
1644                 }
1645         }
1646
1647         return 0;
1648 }
1649
1650 int __xfrm_policy_check(struct sock *sk, int dir, struct sk_buff *skb,
1651                         unsigned short family)
1652 {
1653         struct xfrm_policy *pol;
1654         struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
1655         int npols = 0;
1656         int xfrm_nr;
1657         int pi;
1658         struct flowi fl;
1659         u8 fl_dir = policy_to_flow_dir(dir);
1660         int xerr_idx = -1;
1661
1662         if (xfrm_decode_session(skb, &fl, family) < 0)
1663                 return 0;
1664         nf_nat_decode_session(skb, &fl, family);
1665
1666         /* First, check used SA against their selectors. */
1667         if (skb->sp) {
1668                 int i;
1669
1670                 for (i=skb->sp->len-1; i>=0; i--) {
1671                         struct xfrm_state *x = skb->sp->xvec[i];
1672                         if (!xfrm_selector_match(&x->sel, &fl, family))
1673                                 return 0;
1674                 }
1675         }
1676
1677         pol = NULL;
1678         if (sk && sk->sk_policy[dir]) {
1679                 pol = xfrm_sk_policy_lookup(sk, dir, &fl);
1680                 if (IS_ERR(pol))
1681                         return 0;
1682         }
1683
1684         if (!pol)
1685                 pol = flow_cache_lookup(&fl, family, fl_dir,
1686                                         xfrm_policy_lookup);
1687
1688         if (IS_ERR(pol))
1689                 return 0;
1690
1691         if (!pol) {
1692                 if (skb->sp && secpath_has_nontransport(skb->sp, 0, &xerr_idx)) {
1693                         xfrm_secpath_reject(xerr_idx, skb, &fl);
1694                         return 0;
1695                 }
1696                 return 1;
1697         }
1698
1699         pol->curlft.use_time = get_seconds();
1700
1701         pols[0] = pol;
1702         npols ++;
1703 #ifdef CONFIG_XFRM_SUB_POLICY
1704         if (pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
1705                 pols[1] = xfrm_policy_lookup_bytype(XFRM_POLICY_TYPE_MAIN,
1706                                                     &fl, family,
1707                                                     XFRM_POLICY_IN);
1708                 if (pols[1]) {
1709                         if (IS_ERR(pols[1]))
1710                                 return 0;
1711                         pols[1]->curlft.use_time = get_seconds();
1712                         npols ++;
1713                 }
1714         }
1715 #endif
1716
1717         if (pol->action == XFRM_POLICY_ALLOW) {
1718                 struct sec_path *sp;
1719                 static struct sec_path dummy;
1720                 struct xfrm_tmpl *tp[XFRM_MAX_DEPTH];
1721                 struct xfrm_tmpl *stp[XFRM_MAX_DEPTH];
1722                 struct xfrm_tmpl **tpp = tp;
1723                 int ti = 0;
1724                 int i, k;
1725
1726                 if ((sp = skb->sp) == NULL)
1727                         sp = &dummy;
1728
1729                 for (pi = 0; pi < npols; pi++) {
1730                         if (pols[pi] != pol &&
1731                             pols[pi]->action != XFRM_POLICY_ALLOW)
1732                                 goto reject;
1733                         if (ti + pols[pi]->xfrm_nr >= XFRM_MAX_DEPTH)
1734                                 goto reject_error;
1735                         for (i = 0; i < pols[pi]->xfrm_nr; i++)
1736                                 tpp[ti++] = &pols[pi]->xfrm_vec[i];
1737                 }
1738                 xfrm_nr = ti;
1739                 if (npols > 1) {
1740                         xfrm_tmpl_sort(stp, tpp, xfrm_nr, family);
1741                         tpp = stp;
1742                 }
1743
1744                 /* For each tunnel xfrm, find the first matching tmpl.
1745                  * For each tmpl before that, find corresponding xfrm.
1746                  * Order is _important_. Later we will implement
1747                  * some barriers, but at the moment barriers
1748                  * are implied between each two transformations.
1749                  */
1750                 for (i = xfrm_nr-1, k = 0; i >= 0; i--) {
1751                         k = xfrm_policy_ok(tpp[i], sp, k, family);
1752                         if (k < 0) {
1753                                 if (k < -1)
1754                                         /* "-2 - errored_index" returned */
1755                                         xerr_idx = -(2+k);
1756                                 goto reject;
1757                         }
1758                 }
1759
1760                 if (secpath_has_nontransport(sp, k, &xerr_idx))
1761                         goto reject;
1762
1763                 xfrm_pols_put(pols, npols);
1764                 return 1;
1765         }
1766
1767 reject:
1768         xfrm_secpath_reject(xerr_idx, skb, &fl);
1769 reject_error:
1770         xfrm_pols_put(pols, npols);
1771         return 0;
1772 }
1773 EXPORT_SYMBOL(__xfrm_policy_check);
1774
1775 int __xfrm_route_forward(struct sk_buff *skb, unsigned short family)
1776 {
1777         struct flowi fl;
1778
1779         if (xfrm_decode_session(skb, &fl, family) < 0)
1780                 return 0;
1781
1782         return xfrm_lookup(&skb->dst, &fl, NULL, 0) == 0;
1783 }
1784 EXPORT_SYMBOL(__xfrm_route_forward);
1785
1786 /* Optimize later using cookies and generation ids. */
1787
1788 static struct dst_entry *xfrm_dst_check(struct dst_entry *dst, u32 cookie)
1789 {
1790         /* Code (such as __xfrm4_bundle_create()) sets dst->obsolete
1791          * to "-1" to force all XFRM destinations to get validated by
1792          * dst_ops->check on every use.  We do this because when a
1793          * normal route referenced by an XFRM dst is obsoleted we do
1794          * not go looking around for all parent referencing XFRM dsts
1795          * so that we can invalidate them.  It is just too much work.
1796          * Instead we make the checks here on every use.  For example:
1797          *
1798          *      XFRM dst A --> IPv4 dst X
1799          *
1800          * X is the "xdst->route" of A (X is also the "dst->path" of A
1801          * in this example).  If X is marked obsolete, "A" will not
1802          * notice.  That's what we are validating here via the
1803          * stale_bundle() check.
1804          *
1805          * When a policy's bundle is pruned, we dst_free() the XFRM
1806          * dst which causes it's ->obsolete field to be set to a
1807          * positive non-zero integer.  If an XFRM dst has been pruned
1808          * like this, we want to force a new route lookup.
1809          */
1810         if (dst->obsolete < 0 && !stale_bundle(dst))
1811                 return dst;
1812
1813         return NULL;
1814 }
1815
1816 static int stale_bundle(struct dst_entry *dst)
1817 {
1818         return !xfrm_bundle_ok(NULL, (struct xfrm_dst *)dst, NULL, AF_UNSPEC, 0);
1819 }
1820
1821 void xfrm_dst_ifdown(struct dst_entry *dst, struct net_device *dev)
1822 {
1823         while ((dst = dst->child) && dst->xfrm && dst->dev == dev) {
1824                 dst->dev = &loopback_dev;
1825                 dev_hold(&loopback_dev);
1826                 dev_put(dev);
1827         }
1828 }
1829 EXPORT_SYMBOL(xfrm_dst_ifdown);
1830
1831 static void xfrm_link_failure(struct sk_buff *skb)
1832 {
1833         /* Impossible. Such dst must be popped before reaches point of failure. */
1834         return;
1835 }
1836
1837 static struct dst_entry *xfrm_negative_advice(struct dst_entry *dst)
1838 {
1839         if (dst) {
1840                 if (dst->obsolete) {
1841                         dst_release(dst);
1842                         dst = NULL;
1843                 }
1844         }
1845         return dst;
1846 }
1847
1848 static void prune_one_bundle(struct xfrm_policy *pol, int (*func)(struct dst_entry *), struct dst_entry **gc_list_p)
1849 {
1850         struct dst_entry *dst, **dstp;
1851
1852         write_lock(&pol->lock);
1853         dstp = &pol->bundles;
1854         while ((dst=*dstp) != NULL) {
1855                 if (func(dst)) {
1856                         *dstp = dst->next;
1857                         dst->next = *gc_list_p;
1858                         *gc_list_p = dst;
1859                 } else {
1860                         dstp = &dst->next;
1861                 }
1862         }
1863         write_unlock(&pol->lock);
1864 }
1865
1866 static void xfrm_prune_bundles(int (*func)(struct dst_entry *))
1867 {
1868         struct dst_entry *gc_list = NULL;
1869         int dir;
1870
1871         read_lock_bh(&xfrm_policy_lock);
1872         for (dir = 0; dir < XFRM_POLICY_MAX * 2; dir++) {
1873                 struct xfrm_policy *pol;
1874                 struct hlist_node *entry;
1875                 struct hlist_head *table;
1876                 int i;
1877
1878                 hlist_for_each_entry(pol, entry,
1879                                      &xfrm_policy_inexact[dir], bydst)
1880                         prune_one_bundle(pol, func, &gc_list);
1881
1882                 table = xfrm_policy_bydst[dir].table;
1883                 for (i = xfrm_policy_bydst[dir].hmask; i >= 0; i--) {
1884                         hlist_for_each_entry(pol, entry, table + i, bydst)
1885                                 prune_one_bundle(pol, func, &gc_list);
1886                 }
1887         }
1888         read_unlock_bh(&xfrm_policy_lock);
1889
1890         while (gc_list) {
1891                 struct dst_entry *dst = gc_list;
1892                 gc_list = dst->next;
1893                 dst_free(dst);
1894         }
1895 }
1896
1897 static int unused_bundle(struct dst_entry *dst)
1898 {
1899         return !atomic_read(&dst->__refcnt);
1900 }
1901
1902 static void __xfrm_garbage_collect(void)
1903 {
1904         xfrm_prune_bundles(unused_bundle);
1905 }
1906
1907 static int xfrm_flush_bundles(void)
1908 {
1909         xfrm_prune_bundles(stale_bundle);
1910         return 0;
1911 }
1912
1913 void xfrm_init_pmtu(struct dst_entry *dst)
1914 {
1915         do {
1916                 struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
1917                 u32 pmtu, route_mtu_cached;
1918
1919                 pmtu = dst_mtu(dst->child);
1920                 xdst->child_mtu_cached = pmtu;
1921
1922                 pmtu = xfrm_state_mtu(dst->xfrm, pmtu);
1923
1924                 route_mtu_cached = dst_mtu(xdst->route);
1925                 xdst->route_mtu_cached = route_mtu_cached;
1926
1927                 if (pmtu > route_mtu_cached)
1928                         pmtu = route_mtu_cached;
1929
1930                 dst->metrics[RTAX_MTU-1] = pmtu;
1931         } while ((dst = dst->next));
1932 }
1933
1934 EXPORT_SYMBOL(xfrm_init_pmtu);
1935
1936 /* Check that the bundle accepts the flow and its components are
1937  * still valid.
1938  */
1939
1940 int xfrm_bundle_ok(struct xfrm_policy *pol, struct xfrm_dst *first,
1941                 struct flowi *fl, int family, int strict)
1942 {
1943         struct dst_entry *dst = &first->u.dst;
1944         struct xfrm_dst *last;
1945         u32 mtu;
1946
1947         if (!dst_check(dst->path, ((struct xfrm_dst *)dst)->path_cookie) ||
1948             (dst->dev && !netif_running(dst->dev)))
1949                 return 0;
1950
1951         last = NULL;
1952
1953         do {
1954                 struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
1955
1956                 if (fl && !xfrm_selector_match(&dst->xfrm->sel, fl, family))
1957                         return 0;
1958                 if (fl && pol &&
1959                     !security_xfrm_state_pol_flow_match(dst->xfrm, pol, fl))
1960                         return 0;
1961                 if (dst->xfrm->km.state != XFRM_STATE_VALID)
1962                         return 0;
1963                 if (xdst->genid != dst->xfrm->genid)
1964                         return 0;
1965
1966                 if (strict && fl && dst->xfrm->props.mode != XFRM_MODE_TUNNEL &&
1967                     !xfrm_state_addr_flow_check(dst->xfrm, fl, family))
1968                         return 0;
1969
1970                 mtu = dst_mtu(dst->child);
1971                 if (xdst->child_mtu_cached != mtu) {
1972                         last = xdst;
1973                         xdst->child_mtu_cached = mtu;
1974                 }
1975
1976                 if (!dst_check(xdst->route, xdst->route_cookie))
1977                         return 0;
1978                 mtu = dst_mtu(xdst->route);
1979                 if (xdst->route_mtu_cached != mtu) {
1980                         last = xdst;
1981                         xdst->route_mtu_cached = mtu;
1982                 }
1983
1984                 dst = dst->child;
1985         } while (dst->xfrm);
1986
1987         if (likely(!last))
1988                 return 1;
1989
1990         mtu = last->child_mtu_cached;
1991         for (;;) {
1992                 dst = &last->u.dst;
1993
1994                 mtu = xfrm_state_mtu(dst->xfrm, mtu);
1995                 if (mtu > last->route_mtu_cached)
1996                         mtu = last->route_mtu_cached;
1997                 dst->metrics[RTAX_MTU-1] = mtu;
1998
1999                 if (last == first)
2000                         break;
2001
2002                 last = last->u.next;
2003                 last->child_mtu_cached = mtu;
2004         }
2005
2006         return 1;
2007 }
2008
2009 EXPORT_SYMBOL(xfrm_bundle_ok);
2010
2011 #ifdef CONFIG_AUDITSYSCALL
2012 /* Audit addition and deletion of SAs and ipsec policy */
2013
2014 void xfrm_audit_log(uid_t auid, u32 sid, int type, int result,
2015                     struct xfrm_policy *xp, struct xfrm_state *x)
2016 {
2017
2018         char *secctx;
2019         u32 secctx_len;
2020         struct xfrm_sec_ctx *sctx = NULL;
2021         struct audit_buffer *audit_buf;
2022         int family;
2023         extern int audit_enabled;
2024
2025         if (audit_enabled == 0)
2026                 return;
2027
2028         BUG_ON((type == AUDIT_MAC_IPSEC_ADDSA ||
2029                 type == AUDIT_MAC_IPSEC_DELSA) && !x);
2030         BUG_ON((type == AUDIT_MAC_IPSEC_ADDSPD ||
2031                 type == AUDIT_MAC_IPSEC_DELSPD) && !xp);
2032
2033         audit_buf = audit_log_start(current->audit_context, GFP_ATOMIC, type);
2034         if (audit_buf == NULL)
2035                 return;
2036
2037         switch(type) {
2038         case AUDIT_MAC_IPSEC_ADDSA:
2039                 audit_log_format(audit_buf, "SAD add: auid=%u", auid);
2040                 break;
2041         case AUDIT_MAC_IPSEC_DELSA:
2042                 audit_log_format(audit_buf, "SAD delete: auid=%u", auid);
2043                 break;
2044         case AUDIT_MAC_IPSEC_ADDSPD:
2045                 audit_log_format(audit_buf, "SPD add: auid=%u", auid);
2046                 break;
2047         case AUDIT_MAC_IPSEC_DELSPD:
2048                 audit_log_format(audit_buf, "SPD delete: auid=%u", auid);
2049                 break;
2050         default:
2051                 return;
2052         }
2053
2054         if (sid != 0 &&
2055                 security_secid_to_secctx(sid, &secctx, &secctx_len) == 0)
2056                 audit_log_format(audit_buf, " subj=%s", secctx);
2057         else
2058                 audit_log_task_context(audit_buf);
2059
2060         if (xp) {
2061                 family = xp->selector.family;
2062                 if (xp->security)
2063                         sctx = xp->security;
2064         } else {
2065                 family = x->props.family;
2066                 if (x->security)
2067                         sctx = x->security;
2068         }
2069
2070         if (sctx)
2071                 audit_log_format(audit_buf,
2072                                 " sec_alg=%u sec_doi=%u sec_obj=%s",
2073                                 sctx->ctx_alg, sctx->ctx_doi, sctx->ctx_str);
2074
2075         switch(family) {
2076         case AF_INET:
2077                 {
2078                         struct in_addr saddr, daddr;
2079                         if (xp) {
2080                                 saddr.s_addr = xp->selector.saddr.a4;
2081                                 daddr.s_addr = xp->selector.daddr.a4;
2082                         } else {
2083                                 saddr.s_addr = x->props.saddr.a4;
2084                                 daddr.s_addr = x->id.daddr.a4;
2085                         }
2086                         audit_log_format(audit_buf,
2087                                          " src=%u.%u.%u.%u dst=%u.%u.%u.%u",
2088                                          NIPQUAD(saddr), NIPQUAD(daddr));
2089                 }
2090                         break;
2091         case AF_INET6:
2092                 {
2093                         struct in6_addr saddr6, daddr6;
2094                         if (xp) {
2095                                 memcpy(&saddr6, xp->selector.saddr.a6,
2096                                         sizeof(struct in6_addr));
2097                                 memcpy(&daddr6, xp->selector.daddr.a6,
2098                                         sizeof(struct in6_addr));
2099                         } else {
2100                                 memcpy(&saddr6, x->props.saddr.a6,
2101                                         sizeof(struct in6_addr));
2102                                 memcpy(&daddr6, x->id.daddr.a6,
2103                                         sizeof(struct in6_addr));
2104                         }
2105                         audit_log_format(audit_buf,
2106                                          " src=" NIP6_FMT " dst=" NIP6_FMT,
2107                                          NIP6(saddr6), NIP6(daddr6));
2108                 }
2109                 break;
2110         }
2111
2112         if (x)
2113                 audit_log_format(audit_buf, " spi=%lu(0x%lx) protocol=%s",
2114                                 (unsigned long)ntohl(x->id.spi),
2115                                 (unsigned long)ntohl(x->id.spi),
2116                                 x->id.proto == IPPROTO_AH ? "AH" :
2117                                 (x->id.proto == IPPROTO_ESP ?
2118                                 "ESP" : "IPCOMP"));
2119
2120         audit_log_format(audit_buf, " res=%u", result);
2121         audit_log_end(audit_buf);
2122 }
2123
2124 EXPORT_SYMBOL(xfrm_audit_log);
2125 #endif /* CONFIG_AUDITSYSCALL */
2126
2127 int xfrm_policy_register_afinfo(struct xfrm_policy_afinfo *afinfo)
2128 {
2129         int err = 0;
2130         if (unlikely(afinfo == NULL))
2131                 return -EINVAL;
2132         if (unlikely(afinfo->family >= NPROTO))
2133                 return -EAFNOSUPPORT;
2134         write_lock_bh(&xfrm_policy_afinfo_lock);
2135         if (unlikely(xfrm_policy_afinfo[afinfo->family] != NULL))
2136                 err = -ENOBUFS;
2137         else {
2138                 struct dst_ops *dst_ops = afinfo->dst_ops;
2139                 if (likely(dst_ops->kmem_cachep == NULL))
2140                         dst_ops->kmem_cachep = xfrm_dst_cache;
2141                 if (likely(dst_ops->check == NULL))
2142                         dst_ops->check = xfrm_dst_check;
2143                 if (likely(dst_ops->negative_advice == NULL))
2144                         dst_ops->negative_advice = xfrm_negative_advice;
2145                 if (likely(dst_ops->link_failure == NULL))
2146                         dst_ops->link_failure = xfrm_link_failure;
2147                 if (likely(afinfo->garbage_collect == NULL))
2148                         afinfo->garbage_collect = __xfrm_garbage_collect;
2149                 xfrm_policy_afinfo[afinfo->family] = afinfo;
2150         }
2151         write_unlock_bh(&xfrm_policy_afinfo_lock);
2152         return err;
2153 }
2154 EXPORT_SYMBOL(xfrm_policy_register_afinfo);
2155
2156 int xfrm_policy_unregister_afinfo(struct xfrm_policy_afinfo *afinfo)
2157 {
2158         int err = 0;
2159         if (unlikely(afinfo == NULL))
2160                 return -EINVAL;
2161         if (unlikely(afinfo->family >= NPROTO))
2162                 return -EAFNOSUPPORT;
2163         write_lock_bh(&xfrm_policy_afinfo_lock);
2164         if (likely(xfrm_policy_afinfo[afinfo->family] != NULL)) {
2165                 if (unlikely(xfrm_policy_afinfo[afinfo->family] != afinfo))
2166                         err = -EINVAL;
2167                 else {
2168                         struct dst_ops *dst_ops = afinfo->dst_ops;
2169                         xfrm_policy_afinfo[afinfo->family] = NULL;
2170                         dst_ops->kmem_cachep = NULL;
2171                         dst_ops->check = NULL;
2172                         dst_ops->negative_advice = NULL;
2173                         dst_ops->link_failure = NULL;
2174                         afinfo->garbage_collect = NULL;
2175                 }
2176         }
2177         write_unlock_bh(&xfrm_policy_afinfo_lock);
2178         return err;
2179 }
2180 EXPORT_SYMBOL(xfrm_policy_unregister_afinfo);
2181
2182 static struct xfrm_policy_afinfo *xfrm_policy_get_afinfo(unsigned short family)
2183 {
2184         struct xfrm_policy_afinfo *afinfo;
2185         if (unlikely(family >= NPROTO))
2186                 return NULL;
2187         read_lock(&xfrm_policy_afinfo_lock);
2188         afinfo = xfrm_policy_afinfo[family];
2189         if (unlikely(!afinfo))
2190                 read_unlock(&xfrm_policy_afinfo_lock);
2191         return afinfo;
2192 }
2193
2194 static void xfrm_policy_put_afinfo(struct xfrm_policy_afinfo *afinfo)
2195 {
2196         read_unlock(&xfrm_policy_afinfo_lock);
2197 }
2198
2199 static struct xfrm_policy_afinfo *xfrm_policy_lock_afinfo(unsigned int family)
2200 {
2201         struct xfrm_policy_afinfo *afinfo;
2202         if (unlikely(family >= NPROTO))
2203                 return NULL;
2204         write_lock_bh(&xfrm_policy_afinfo_lock);
2205         afinfo = xfrm_policy_afinfo[family];
2206         if (unlikely(!afinfo))
2207                 write_unlock_bh(&xfrm_policy_afinfo_lock);
2208         return afinfo;
2209 }
2210
2211 static void xfrm_policy_unlock_afinfo(struct xfrm_policy_afinfo *afinfo)
2212 {
2213         write_unlock_bh(&xfrm_policy_afinfo_lock);
2214 }
2215
2216 static int xfrm_dev_event(struct notifier_block *this, unsigned long event, void *ptr)
2217 {
2218         switch (event) {
2219         case NETDEV_DOWN:
2220                 xfrm_flush_bundles();
2221         }
2222         return NOTIFY_DONE;
2223 }
2224
2225 static struct notifier_block xfrm_dev_notifier = {
2226         xfrm_dev_event,
2227         NULL,
2228         0
2229 };
2230
2231 static void __init xfrm_policy_init(void)
2232 {
2233         unsigned int hmask, sz;
2234         int dir;
2235
2236         xfrm_dst_cache = kmem_cache_create("xfrm_dst_cache",
2237                                            sizeof(struct xfrm_dst),
2238                                            0, SLAB_HWCACHE_ALIGN|SLAB_PANIC,
2239                                            NULL, NULL);
2240
2241         hmask = 8 - 1;
2242         sz = (hmask+1) * sizeof(struct hlist_head);
2243
2244         xfrm_policy_byidx = xfrm_hash_alloc(sz);
2245         xfrm_idx_hmask = hmask;
2246         if (!xfrm_policy_byidx)
2247                 panic("XFRM: failed to allocate byidx hash\n");
2248
2249         for (dir = 0; dir < XFRM_POLICY_MAX * 2; dir++) {
2250                 struct xfrm_policy_hash *htab;
2251
2252                 INIT_HLIST_HEAD(&xfrm_policy_inexact[dir]);
2253
2254                 htab = &xfrm_policy_bydst[dir];
2255                 htab->table = xfrm_hash_alloc(sz);
2256                 htab->hmask = hmask;
2257                 if (!htab->table)
2258                         panic("XFRM: failed to allocate bydst hash\n");
2259         }
2260
2261         INIT_WORK(&xfrm_policy_gc_work, xfrm_policy_gc_task);
2262         register_netdevice_notifier(&xfrm_dev_notifier);
2263 }
2264
2265 void __init xfrm_init(void)
2266 {
2267         xfrm_state_init();
2268         xfrm_policy_init();
2269         xfrm_input_init();
2270 }
2271
2272 #ifdef CONFIG_XFRM_MIGRATE
2273 static int xfrm_migrate_selector_match(struct xfrm_selector *sel_cmp,
2274                                        struct xfrm_selector *sel_tgt)
2275 {
2276         if (sel_cmp->proto == IPSEC_ULPROTO_ANY) {
2277                 if (sel_tgt->family == sel_cmp->family &&
2278                     xfrm_addr_cmp(&sel_tgt->daddr, &sel_cmp->daddr,
2279                                   sel_cmp->family) == 0 &&
2280                     xfrm_addr_cmp(&sel_tgt->saddr, &sel_cmp->saddr,
2281                                   sel_cmp->family) == 0 &&
2282                     sel_tgt->prefixlen_d == sel_cmp->prefixlen_d &&
2283                     sel_tgt->prefixlen_s == sel_cmp->prefixlen_s) {
2284                         return 1;
2285                 }
2286         } else {
2287                 if (memcmp(sel_tgt, sel_cmp, sizeof(*sel_tgt)) == 0) {
2288                         return 1;
2289                 }
2290         }
2291         return 0;
2292 }
2293
2294 static struct xfrm_policy * xfrm_migrate_policy_find(struct xfrm_selector *sel,
2295                                                      u8 dir, u8 type)
2296 {
2297         struct xfrm_policy *pol, *ret = NULL;
2298         struct hlist_node *entry;
2299         struct hlist_head *chain;
2300         u32 priority = ~0U;
2301
2302         read_lock_bh(&xfrm_policy_lock);
2303         chain = policy_hash_direct(&sel->daddr, &sel->saddr, sel->family, dir);
2304         hlist_for_each_entry(pol, entry, chain, bydst) {
2305                 if (xfrm_migrate_selector_match(sel, &pol->selector) &&
2306                     pol->type == type) {
2307                         ret = pol;
2308                         priority = ret->priority;
2309                         break;
2310                 }
2311         }
2312         chain = &xfrm_policy_inexact[dir];
2313         hlist_for_each_entry(pol, entry, chain, bydst) {
2314                 if (xfrm_migrate_selector_match(sel, &pol->selector) &&
2315                     pol->type == type &&
2316                     pol->priority < priority) {
2317                         ret = pol;
2318                         break;
2319                 }
2320         }
2321
2322         if (ret)
2323                 xfrm_pol_hold(ret);
2324
2325         read_unlock_bh(&xfrm_policy_lock);
2326
2327         return ret;
2328 }
2329
2330 static int migrate_tmpl_match(struct xfrm_migrate *m, struct xfrm_tmpl *t)
2331 {
2332         int match = 0;
2333
2334         if (t->mode == m->mode && t->id.proto == m->proto &&
2335             (m->reqid == 0 || t->reqid == m->reqid)) {
2336                 switch (t->mode) {
2337                 case XFRM_MODE_TUNNEL:
2338                 case XFRM_MODE_BEET:
2339                         if (xfrm_addr_cmp(&t->id.daddr, &m->old_daddr,
2340                                           m->old_family) == 0 &&
2341                             xfrm_addr_cmp(&t->saddr, &m->old_saddr,
2342                                           m->old_family) == 0) {
2343                                 match = 1;
2344                         }
2345                         break;
2346                 case XFRM_MODE_TRANSPORT:
2347                         /* in case of transport mode, template does not store
2348                            any IP addresses, hence we just compare mode and
2349                            protocol */
2350                         match = 1;
2351                         break;
2352                 default:
2353                         break;
2354                 }
2355         }
2356         return match;
2357 }
2358
2359 /* update endpoint address(es) of template(s) */
2360 static int xfrm_policy_migrate(struct xfrm_policy *pol,
2361                                struct xfrm_migrate *m, int num_migrate)
2362 {
2363         struct xfrm_migrate *mp;
2364         struct dst_entry *dst;
2365         int i, j, n = 0;
2366
2367         write_lock_bh(&pol->lock);
2368         if (unlikely(pol->dead)) {
2369                 /* target policy has been deleted */
2370                 write_unlock_bh(&pol->lock);
2371                 return -ENOENT;
2372         }
2373
2374         for (i = 0; i < pol->xfrm_nr; i++) {
2375                 for (j = 0, mp = m; j < num_migrate; j++, mp++) {
2376                         if (!migrate_tmpl_match(mp, &pol->xfrm_vec[i]))
2377                                 continue;
2378                         n++;
2379                         if (pol->xfrm_vec[i].mode != XFRM_MODE_TUNNEL)
2380                                 continue;
2381                         /* update endpoints */
2382                         memcpy(&pol->xfrm_vec[i].id.daddr, &mp->new_daddr,
2383                                sizeof(pol->xfrm_vec[i].id.daddr));
2384                         memcpy(&pol->xfrm_vec[i].saddr, &mp->new_saddr,
2385                                sizeof(pol->xfrm_vec[i].saddr));
2386                         pol->xfrm_vec[i].encap_family = mp->new_family;
2387                         /* flush bundles */
2388                         while ((dst = pol->bundles) != NULL) {
2389                                 pol->bundles = dst->next;
2390                                 dst_free(dst);
2391                         }
2392                 }
2393         }
2394
2395         write_unlock_bh(&pol->lock);
2396
2397         if (!n)
2398                 return -ENODATA;
2399
2400         return 0;
2401 }
2402
2403 static int xfrm_migrate_check(struct xfrm_migrate *m, int num_migrate)
2404 {
2405         int i, j;
2406
2407         if (num_migrate < 1 || num_migrate > XFRM_MAX_DEPTH)
2408                 return -EINVAL;
2409
2410         for (i = 0; i < num_migrate; i++) {
2411                 if ((xfrm_addr_cmp(&m[i].old_daddr, &m[i].new_daddr,
2412                                    m[i].old_family) == 0) &&
2413                     (xfrm_addr_cmp(&m[i].old_saddr, &m[i].new_saddr,
2414                                    m[i].old_family) == 0))
2415                         return -EINVAL;
2416                 if (xfrm_addr_any(&m[i].new_daddr, m[i].new_family) ||
2417                     xfrm_addr_any(&m[i].new_saddr, m[i].new_family))
2418                         return -EINVAL;
2419
2420                 /* check if there is any duplicated entry */
2421                 for (j = i + 1; j < num_migrate; j++) {
2422                         if (!memcmp(&m[i].old_daddr, &m[j].old_daddr,
2423                                     sizeof(m[i].old_daddr)) &&
2424                             !memcmp(&m[i].old_saddr, &m[j].old_saddr,
2425                                     sizeof(m[i].old_saddr)) &&
2426                             m[i].proto == m[j].proto &&
2427                             m[i].mode == m[j].mode &&
2428                             m[i].reqid == m[j].reqid &&
2429                             m[i].old_family == m[j].old_family)
2430                                 return -EINVAL;
2431                 }
2432         }
2433
2434         return 0;
2435 }
2436
2437 int xfrm_migrate(struct xfrm_selector *sel, u8 dir, u8 type,
2438                  struct xfrm_migrate *m, int num_migrate)
2439 {
2440         int i, err, nx_cur = 0, nx_new = 0;
2441         struct xfrm_policy *pol = NULL;
2442         struct xfrm_state *x, *xc;
2443         struct xfrm_state *x_cur[XFRM_MAX_DEPTH];
2444         struct xfrm_state *x_new[XFRM_MAX_DEPTH];
2445         struct xfrm_migrate *mp;
2446
2447         if ((err = xfrm_migrate_check(m, num_migrate)) < 0)
2448                 goto out;
2449
2450         /* Stage 1 - find policy */
2451         if ((pol = xfrm_migrate_policy_find(sel, dir, type)) == NULL) {
2452                 err = -ENOENT;
2453                 goto out;
2454         }
2455
2456         /* Stage 2 - find and update state(s) */
2457         for (i = 0, mp = m; i < num_migrate; i++, mp++) {
2458                 if ((x = xfrm_migrate_state_find(mp))) {
2459                         x_cur[nx_cur] = x;
2460                         nx_cur++;
2461                         if ((xc = xfrm_state_migrate(x, mp))) {
2462                                 x_new[nx_new] = xc;
2463                                 nx_new++;
2464                         } else {
2465                                 err = -ENODATA;
2466                                 goto restore_state;
2467                         }
2468                 }
2469         }
2470
2471         /* Stage 3 - update policy */
2472         if ((err = xfrm_policy_migrate(pol, m, num_migrate)) < 0)
2473                 goto restore_state;
2474
2475         /* Stage 4 - delete old state(s) */
2476         if (nx_cur) {
2477                 xfrm_states_put(x_cur, nx_cur);
2478                 xfrm_states_delete(x_cur, nx_cur);
2479         }
2480
2481         /* Stage 5 - announce */
2482         km_migrate(sel, dir, type, m, num_migrate);
2483
2484         xfrm_pol_put(pol);
2485
2486         return 0;
2487 out:
2488         return err;
2489
2490 restore_state:
2491         if (pol)
2492                 xfrm_pol_put(pol);
2493         if (nx_cur)
2494                 xfrm_states_put(x_cur, nx_cur);
2495         if (nx_new)
2496                 xfrm_states_delete(x_new, nx_new);
2497
2498         return err;
2499 }
2500 EXPORT_SYMBOL(xfrm_migrate);
2501 #endif
2502