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