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