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