ASoC: fsl_esai: fix channel swap issue when stream starts
[linux/fpc-iii.git] / net / xfrm / xfrm_policy.c
blob155b1591b17a205eb1d9c6acd7eef6e14a2b799e
1 /*
2 * xfrm_policy.c
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
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 <linux/audit.h>
28 #include <net/dst.h>
29 #include <net/flow.h>
30 #include <net/xfrm.h>
31 #include <net/ip.h>
32 #ifdef CONFIG_XFRM_STATISTICS
33 #include <net/snmp.h>
34 #endif
36 #include "xfrm_hash.h"
38 #define XFRM_QUEUE_TMO_MIN ((unsigned)(HZ/10))
39 #define XFRM_QUEUE_TMO_MAX ((unsigned)(60*HZ))
40 #define XFRM_MAX_QUEUE_LEN 100
42 struct xfrm_flo {
43 struct dst_entry *dst_orig;
44 u8 flags;
47 static DEFINE_SPINLOCK(xfrm_policy_afinfo_lock);
48 static struct xfrm_policy_afinfo __rcu *xfrm_policy_afinfo[NPROTO]
49 __read_mostly;
51 static struct kmem_cache *xfrm_dst_cache __read_mostly;
52 static __read_mostly seqcount_t xfrm_policy_hash_generation;
54 static void xfrm_init_pmtu(struct dst_entry *dst);
55 static int stale_bundle(struct dst_entry *dst);
56 static int xfrm_bundle_ok(struct xfrm_dst *xdst);
57 static void xfrm_policy_queue_process(unsigned long arg);
59 static void __xfrm_policy_link(struct xfrm_policy *pol, int dir);
60 static struct xfrm_policy *__xfrm_policy_unlink(struct xfrm_policy *pol,
61 int dir);
63 static inline bool xfrm_pol_hold_rcu(struct xfrm_policy *policy)
65 return atomic_inc_not_zero(&policy->refcnt);
68 static inline bool
69 __xfrm4_selector_match(const struct xfrm_selector *sel, const struct flowi *fl)
71 const struct flowi4 *fl4 = &fl->u.ip4;
73 return addr4_match(fl4->daddr, sel->daddr.a4, sel->prefixlen_d) &&
74 addr4_match(fl4->saddr, sel->saddr.a4, sel->prefixlen_s) &&
75 !((xfrm_flowi_dport(fl, &fl4->uli) ^ sel->dport) & sel->dport_mask) &&
76 !((xfrm_flowi_sport(fl, &fl4->uli) ^ sel->sport) & sel->sport_mask) &&
77 (fl4->flowi4_proto == sel->proto || !sel->proto) &&
78 (fl4->flowi4_oif == sel->ifindex || !sel->ifindex);
81 static inline bool
82 __xfrm6_selector_match(const struct xfrm_selector *sel, const struct flowi *fl)
84 const struct flowi6 *fl6 = &fl->u.ip6;
86 return addr_match(&fl6->daddr, &sel->daddr, sel->prefixlen_d) &&
87 addr_match(&fl6->saddr, &sel->saddr, sel->prefixlen_s) &&
88 !((xfrm_flowi_dport(fl, &fl6->uli) ^ sel->dport) & sel->dport_mask) &&
89 !((xfrm_flowi_sport(fl, &fl6->uli) ^ sel->sport) & sel->sport_mask) &&
90 (fl6->flowi6_proto == sel->proto || !sel->proto) &&
91 (fl6->flowi6_oif == sel->ifindex || !sel->ifindex);
94 bool xfrm_selector_match(const struct xfrm_selector *sel, const struct flowi *fl,
95 unsigned short family)
97 switch (family) {
98 case AF_INET:
99 return __xfrm4_selector_match(sel, fl);
100 case AF_INET6:
101 return __xfrm6_selector_match(sel, fl);
103 return false;
106 static struct xfrm_policy_afinfo *xfrm_policy_get_afinfo(unsigned short family)
108 struct xfrm_policy_afinfo *afinfo;
110 if (unlikely(family >= NPROTO))
111 return NULL;
112 rcu_read_lock();
113 afinfo = rcu_dereference(xfrm_policy_afinfo[family]);
114 if (unlikely(!afinfo))
115 rcu_read_unlock();
116 return afinfo;
119 static void xfrm_policy_put_afinfo(struct xfrm_policy_afinfo *afinfo)
121 rcu_read_unlock();
124 static inline struct dst_entry *__xfrm_dst_lookup(struct net *net,
125 int tos, int oif,
126 const xfrm_address_t *saddr,
127 const xfrm_address_t *daddr,
128 int family)
130 struct xfrm_policy_afinfo *afinfo;
131 struct dst_entry *dst;
133 afinfo = xfrm_policy_get_afinfo(family);
134 if (unlikely(afinfo == NULL))
135 return ERR_PTR(-EAFNOSUPPORT);
137 dst = afinfo->dst_lookup(net, tos, oif, saddr, daddr);
139 xfrm_policy_put_afinfo(afinfo);
141 return dst;
144 static inline struct dst_entry *xfrm_dst_lookup(struct xfrm_state *x,
145 int tos, int oif,
146 xfrm_address_t *prev_saddr,
147 xfrm_address_t *prev_daddr,
148 int family)
150 struct net *net = xs_net(x);
151 xfrm_address_t *saddr = &x->props.saddr;
152 xfrm_address_t *daddr = &x->id.daddr;
153 struct dst_entry *dst;
155 if (x->type->flags & XFRM_TYPE_LOCAL_COADDR) {
156 saddr = x->coaddr;
157 daddr = prev_daddr;
159 if (x->type->flags & XFRM_TYPE_REMOTE_COADDR) {
160 saddr = prev_saddr;
161 daddr = x->coaddr;
164 dst = __xfrm_dst_lookup(net, tos, oif, saddr, daddr, family);
166 if (!IS_ERR(dst)) {
167 if (prev_saddr != saddr)
168 memcpy(prev_saddr, saddr, sizeof(*prev_saddr));
169 if (prev_daddr != daddr)
170 memcpy(prev_daddr, daddr, sizeof(*prev_daddr));
173 return dst;
176 static inline unsigned long make_jiffies(long secs)
178 if (secs >= (MAX_SCHEDULE_TIMEOUT-1)/HZ)
179 return MAX_SCHEDULE_TIMEOUT-1;
180 else
181 return secs*HZ;
184 static void xfrm_policy_timer(unsigned long data)
186 struct xfrm_policy *xp = (struct xfrm_policy *)data;
187 unsigned long now = get_seconds();
188 long next = LONG_MAX;
189 int warn = 0;
190 int dir;
192 read_lock(&xp->lock);
194 if (unlikely(xp->walk.dead))
195 goto out;
197 dir = xfrm_policy_id2dir(xp->index);
199 if (xp->lft.hard_add_expires_seconds) {
200 long tmo = xp->lft.hard_add_expires_seconds +
201 xp->curlft.add_time - now;
202 if (tmo <= 0)
203 goto expired;
204 if (tmo < next)
205 next = tmo;
207 if (xp->lft.hard_use_expires_seconds) {
208 long tmo = xp->lft.hard_use_expires_seconds +
209 (xp->curlft.use_time ? : xp->curlft.add_time) - now;
210 if (tmo <= 0)
211 goto expired;
212 if (tmo < next)
213 next = tmo;
215 if (xp->lft.soft_add_expires_seconds) {
216 long tmo = xp->lft.soft_add_expires_seconds +
217 xp->curlft.add_time - now;
218 if (tmo <= 0) {
219 warn = 1;
220 tmo = XFRM_KM_TIMEOUT;
222 if (tmo < next)
223 next = tmo;
225 if (xp->lft.soft_use_expires_seconds) {
226 long tmo = xp->lft.soft_use_expires_seconds +
227 (xp->curlft.use_time ? : xp->curlft.add_time) - now;
228 if (tmo <= 0) {
229 warn = 1;
230 tmo = XFRM_KM_TIMEOUT;
232 if (tmo < next)
233 next = tmo;
236 if (warn)
237 km_policy_expired(xp, dir, 0, 0);
238 if (next != LONG_MAX &&
239 !mod_timer(&xp->timer, jiffies + make_jiffies(next)))
240 xfrm_pol_hold(xp);
242 out:
243 read_unlock(&xp->lock);
244 xfrm_pol_put(xp);
245 return;
247 expired:
248 read_unlock(&xp->lock);
249 if (!xfrm_policy_delete(xp, dir))
250 km_policy_expired(xp, dir, 1, 0);
251 xfrm_pol_put(xp);
254 static struct flow_cache_object *xfrm_policy_flo_get(struct flow_cache_object *flo)
256 struct xfrm_policy *pol = container_of(flo, struct xfrm_policy, flo);
258 if (unlikely(pol->walk.dead))
259 flo = NULL;
260 else
261 xfrm_pol_hold(pol);
263 return flo;
266 static int xfrm_policy_flo_check(struct flow_cache_object *flo)
268 struct xfrm_policy *pol = container_of(flo, struct xfrm_policy, flo);
270 return !pol->walk.dead;
273 static void xfrm_policy_flo_delete(struct flow_cache_object *flo)
275 xfrm_pol_put(container_of(flo, struct xfrm_policy, flo));
278 static const struct flow_cache_ops xfrm_policy_fc_ops = {
279 .get = xfrm_policy_flo_get,
280 .check = xfrm_policy_flo_check,
281 .delete = xfrm_policy_flo_delete,
284 /* Allocate xfrm_policy. Not used here, it is supposed to be used by pfkeyv2
285 * SPD calls.
288 struct xfrm_policy *xfrm_policy_alloc(struct net *net, gfp_t gfp)
290 struct xfrm_policy *policy;
292 policy = kzalloc(sizeof(struct xfrm_policy), gfp);
294 if (policy) {
295 write_pnet(&policy->xp_net, net);
296 INIT_LIST_HEAD(&policy->walk.all);
297 INIT_HLIST_NODE(&policy->bydst);
298 INIT_HLIST_NODE(&policy->byidx);
299 rwlock_init(&policy->lock);
300 atomic_set(&policy->refcnt, 1);
301 skb_queue_head_init(&policy->polq.hold_queue);
302 setup_timer(&policy->timer, xfrm_policy_timer,
303 (unsigned long)policy);
304 setup_timer(&policy->polq.hold_timer, xfrm_policy_queue_process,
305 (unsigned long)policy);
306 policy->flo.ops = &xfrm_policy_fc_ops;
308 return policy;
310 EXPORT_SYMBOL(xfrm_policy_alloc);
312 static void xfrm_policy_destroy_rcu(struct rcu_head *head)
314 struct xfrm_policy *policy = container_of(head, struct xfrm_policy, rcu);
316 security_xfrm_policy_free(policy->security);
317 kfree(policy);
320 /* Destroy xfrm_policy: descendant resources must be released to this moment. */
322 void xfrm_policy_destroy(struct xfrm_policy *policy)
324 BUG_ON(!policy->walk.dead);
326 if (del_timer(&policy->timer) || del_timer(&policy->polq.hold_timer))
327 BUG();
329 call_rcu(&policy->rcu, xfrm_policy_destroy_rcu);
331 EXPORT_SYMBOL(xfrm_policy_destroy);
333 /* Rule must be locked. Release descentant resources, announce
334 * entry dead. The rule must be unlinked from lists to the moment.
337 static void xfrm_policy_kill(struct xfrm_policy *policy)
339 policy->walk.dead = 1;
341 atomic_inc(&policy->genid);
343 if (del_timer(&policy->polq.hold_timer))
344 xfrm_pol_put(policy);
345 skb_queue_purge(&policy->polq.hold_queue);
347 if (del_timer(&policy->timer))
348 xfrm_pol_put(policy);
350 xfrm_pol_put(policy);
353 static unsigned int xfrm_policy_hashmax __read_mostly = 1 * 1024 * 1024;
355 static inline unsigned int idx_hash(struct net *net, u32 index)
357 return __idx_hash(index, net->xfrm.policy_idx_hmask);
360 /* calculate policy hash thresholds */
361 static void __get_hash_thresh(struct net *net,
362 unsigned short family, int dir,
363 u8 *dbits, u8 *sbits)
365 switch (family) {
366 case AF_INET:
367 *dbits = net->xfrm.policy_bydst[dir].dbits4;
368 *sbits = net->xfrm.policy_bydst[dir].sbits4;
369 break;
371 case AF_INET6:
372 *dbits = net->xfrm.policy_bydst[dir].dbits6;
373 *sbits = net->xfrm.policy_bydst[dir].sbits6;
374 break;
376 default:
377 *dbits = 0;
378 *sbits = 0;
382 static struct hlist_head *policy_hash_bysel(struct net *net,
383 const struct xfrm_selector *sel,
384 unsigned short family, int dir)
386 unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
387 unsigned int hash;
388 u8 dbits;
389 u8 sbits;
391 __get_hash_thresh(net, family, dir, &dbits, &sbits);
392 hash = __sel_hash(sel, family, hmask, dbits, sbits);
394 if (hash == hmask + 1)
395 return &net->xfrm.policy_inexact[dir];
397 return rcu_dereference_check(net->xfrm.policy_bydst[dir].table,
398 lockdep_is_held(&net->xfrm.xfrm_policy_lock)) + hash;
401 static struct hlist_head *policy_hash_direct(struct net *net,
402 const xfrm_address_t *daddr,
403 const xfrm_address_t *saddr,
404 unsigned short family, int dir)
406 unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
407 unsigned int hash;
408 u8 dbits;
409 u8 sbits;
411 __get_hash_thresh(net, family, dir, &dbits, &sbits);
412 hash = __addr_hash(daddr, saddr, family, hmask, dbits, sbits);
414 return rcu_dereference_check(net->xfrm.policy_bydst[dir].table,
415 lockdep_is_held(&net->xfrm.xfrm_policy_lock)) + hash;
418 static void xfrm_dst_hash_transfer(struct net *net,
419 struct hlist_head *list,
420 struct hlist_head *ndsttable,
421 unsigned int nhashmask,
422 int dir)
424 struct hlist_node *tmp, *entry0 = NULL;
425 struct xfrm_policy *pol;
426 unsigned int h0 = 0;
427 u8 dbits;
428 u8 sbits;
430 redo:
431 hlist_for_each_entry_safe(pol, tmp, list, bydst) {
432 unsigned int h;
434 __get_hash_thresh(net, pol->family, dir, &dbits, &sbits);
435 h = __addr_hash(&pol->selector.daddr, &pol->selector.saddr,
436 pol->family, nhashmask, dbits, sbits);
437 if (!entry0) {
438 hlist_del_rcu(&pol->bydst);
439 hlist_add_head_rcu(&pol->bydst, ndsttable + h);
440 h0 = h;
441 } else {
442 if (h != h0)
443 continue;
444 hlist_del_rcu(&pol->bydst);
445 hlist_add_behind_rcu(&pol->bydst, entry0);
447 entry0 = &pol->bydst;
449 if (!hlist_empty(list)) {
450 entry0 = NULL;
451 goto redo;
455 static void xfrm_idx_hash_transfer(struct hlist_head *list,
456 struct hlist_head *nidxtable,
457 unsigned int nhashmask)
459 struct hlist_node *tmp;
460 struct xfrm_policy *pol;
462 hlist_for_each_entry_safe(pol, tmp, list, byidx) {
463 unsigned int h;
465 h = __idx_hash(pol->index, nhashmask);
466 hlist_add_head(&pol->byidx, nidxtable+h);
470 static unsigned long xfrm_new_hash_mask(unsigned int old_hmask)
472 return ((old_hmask + 1) << 1) - 1;
475 static void xfrm_bydst_resize(struct net *net, int dir)
477 unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
478 unsigned int nhashmask = xfrm_new_hash_mask(hmask);
479 unsigned int nsize = (nhashmask + 1) * sizeof(struct hlist_head);
480 struct hlist_head *ndst = xfrm_hash_alloc(nsize);
481 struct hlist_head *odst;
482 int i;
484 if (!ndst)
485 return;
487 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
488 write_seqcount_begin(&xfrm_policy_hash_generation);
490 odst = rcu_dereference_protected(net->xfrm.policy_bydst[dir].table,
491 lockdep_is_held(&net->xfrm.xfrm_policy_lock));
493 odst = rcu_dereference_protected(net->xfrm.policy_bydst[dir].table,
494 lockdep_is_held(&net->xfrm.xfrm_policy_lock));
496 for (i = hmask; i >= 0; i--)
497 xfrm_dst_hash_transfer(net, odst + i, ndst, nhashmask, dir);
499 rcu_assign_pointer(net->xfrm.policy_bydst[dir].table, ndst);
500 net->xfrm.policy_bydst[dir].hmask = nhashmask;
502 write_seqcount_end(&xfrm_policy_hash_generation);
503 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
505 synchronize_rcu();
507 xfrm_hash_free(odst, (hmask + 1) * sizeof(struct hlist_head));
510 static void xfrm_byidx_resize(struct net *net, int total)
512 unsigned int hmask = net->xfrm.policy_idx_hmask;
513 unsigned int nhashmask = xfrm_new_hash_mask(hmask);
514 unsigned int nsize = (nhashmask + 1) * sizeof(struct hlist_head);
515 struct hlist_head *oidx = net->xfrm.policy_byidx;
516 struct hlist_head *nidx = xfrm_hash_alloc(nsize);
517 int i;
519 if (!nidx)
520 return;
522 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
524 for (i = hmask; i >= 0; i--)
525 xfrm_idx_hash_transfer(oidx + i, nidx, nhashmask);
527 net->xfrm.policy_byidx = nidx;
528 net->xfrm.policy_idx_hmask = nhashmask;
530 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
532 xfrm_hash_free(oidx, (hmask + 1) * sizeof(struct hlist_head));
535 static inline int xfrm_bydst_should_resize(struct net *net, int dir, int *total)
537 unsigned int cnt = net->xfrm.policy_count[dir];
538 unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
540 if (total)
541 *total += cnt;
543 if ((hmask + 1) < xfrm_policy_hashmax &&
544 cnt > hmask)
545 return 1;
547 return 0;
550 static inline int xfrm_byidx_should_resize(struct net *net, int total)
552 unsigned int hmask = net->xfrm.policy_idx_hmask;
554 if ((hmask + 1) < xfrm_policy_hashmax &&
555 total > hmask)
556 return 1;
558 return 0;
561 void xfrm_spd_getinfo(struct net *net, struct xfrmk_spdinfo *si)
563 si->incnt = net->xfrm.policy_count[XFRM_POLICY_IN];
564 si->outcnt = net->xfrm.policy_count[XFRM_POLICY_OUT];
565 si->fwdcnt = net->xfrm.policy_count[XFRM_POLICY_FWD];
566 si->inscnt = net->xfrm.policy_count[XFRM_POLICY_IN+XFRM_POLICY_MAX];
567 si->outscnt = net->xfrm.policy_count[XFRM_POLICY_OUT+XFRM_POLICY_MAX];
568 si->fwdscnt = net->xfrm.policy_count[XFRM_POLICY_FWD+XFRM_POLICY_MAX];
569 si->spdhcnt = net->xfrm.policy_idx_hmask;
570 si->spdhmcnt = xfrm_policy_hashmax;
572 EXPORT_SYMBOL(xfrm_spd_getinfo);
574 static DEFINE_MUTEX(hash_resize_mutex);
575 static void xfrm_hash_resize(struct work_struct *work)
577 struct net *net = container_of(work, struct net, xfrm.policy_hash_work);
578 int dir, total;
580 mutex_lock(&hash_resize_mutex);
582 total = 0;
583 for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
584 if (xfrm_bydst_should_resize(net, dir, &total))
585 xfrm_bydst_resize(net, dir);
587 if (xfrm_byidx_should_resize(net, total))
588 xfrm_byidx_resize(net, total);
590 mutex_unlock(&hash_resize_mutex);
593 static void xfrm_hash_rebuild(struct work_struct *work)
595 struct net *net = container_of(work, struct net,
596 xfrm.policy_hthresh.work);
597 unsigned int hmask;
598 struct xfrm_policy *pol;
599 struct xfrm_policy *policy;
600 struct hlist_head *chain;
601 struct hlist_head *odst;
602 struct hlist_node *newpos;
603 int i;
604 int dir;
605 unsigned seq;
606 u8 lbits4, rbits4, lbits6, rbits6;
608 mutex_lock(&hash_resize_mutex);
610 /* read selector prefixlen thresholds */
611 do {
612 seq = read_seqbegin(&net->xfrm.policy_hthresh.lock);
614 lbits4 = net->xfrm.policy_hthresh.lbits4;
615 rbits4 = net->xfrm.policy_hthresh.rbits4;
616 lbits6 = net->xfrm.policy_hthresh.lbits6;
617 rbits6 = net->xfrm.policy_hthresh.rbits6;
618 } while (read_seqretry(&net->xfrm.policy_hthresh.lock, seq));
620 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
622 /* reset the bydst and inexact table in all directions */
623 for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
624 INIT_HLIST_HEAD(&net->xfrm.policy_inexact[dir]);
625 hmask = net->xfrm.policy_bydst[dir].hmask;
626 odst = net->xfrm.policy_bydst[dir].table;
627 for (i = hmask; i >= 0; i--)
628 INIT_HLIST_HEAD(odst + i);
629 if ((dir & XFRM_POLICY_MASK) == XFRM_POLICY_OUT) {
630 /* dir out => dst = remote, src = local */
631 net->xfrm.policy_bydst[dir].dbits4 = rbits4;
632 net->xfrm.policy_bydst[dir].sbits4 = lbits4;
633 net->xfrm.policy_bydst[dir].dbits6 = rbits6;
634 net->xfrm.policy_bydst[dir].sbits6 = lbits6;
635 } else {
636 /* dir in/fwd => dst = local, src = remote */
637 net->xfrm.policy_bydst[dir].dbits4 = lbits4;
638 net->xfrm.policy_bydst[dir].sbits4 = rbits4;
639 net->xfrm.policy_bydst[dir].dbits6 = lbits6;
640 net->xfrm.policy_bydst[dir].sbits6 = rbits6;
644 /* re-insert all policies by order of creation */
645 list_for_each_entry_reverse(policy, &net->xfrm.policy_all, walk.all) {
646 if (policy->walk.dead ||
647 xfrm_policy_id2dir(policy->index) >= XFRM_POLICY_MAX) {
648 /* skip socket policies */
649 continue;
651 newpos = NULL;
652 chain = policy_hash_bysel(net, &policy->selector,
653 policy->family,
654 xfrm_policy_id2dir(policy->index));
655 hlist_for_each_entry(pol, chain, bydst) {
656 if (policy->priority >= pol->priority)
657 newpos = &pol->bydst;
658 else
659 break;
661 if (newpos)
662 hlist_add_behind_rcu(&policy->bydst, newpos);
663 else
664 hlist_add_head_rcu(&policy->bydst, chain);
667 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
669 mutex_unlock(&hash_resize_mutex);
672 void xfrm_policy_hash_rebuild(struct net *net)
674 schedule_work(&net->xfrm.policy_hthresh.work);
676 EXPORT_SYMBOL(xfrm_policy_hash_rebuild);
678 /* Generate new index... KAME seems to generate them ordered by cost
679 * of an absolute inpredictability of ordering of rules. This will not pass. */
680 static u32 xfrm_gen_index(struct net *net, int dir, u32 index)
682 static u32 idx_generator;
684 for (;;) {
685 struct hlist_head *list;
686 struct xfrm_policy *p;
687 u32 idx;
688 int found;
690 if (!index) {
691 idx = (idx_generator | dir);
692 idx_generator += 8;
693 } else {
694 idx = index;
695 index = 0;
698 if (idx == 0)
699 idx = 8;
700 list = net->xfrm.policy_byidx + idx_hash(net, idx);
701 found = 0;
702 hlist_for_each_entry(p, list, byidx) {
703 if (p->index == idx) {
704 found = 1;
705 break;
708 if (!found)
709 return idx;
713 static inline int selector_cmp(struct xfrm_selector *s1, struct xfrm_selector *s2)
715 u32 *p1 = (u32 *) s1;
716 u32 *p2 = (u32 *) s2;
717 int len = sizeof(struct xfrm_selector) / sizeof(u32);
718 int i;
720 for (i = 0; i < len; i++) {
721 if (p1[i] != p2[i])
722 return 1;
725 return 0;
728 static void xfrm_policy_requeue(struct xfrm_policy *old,
729 struct xfrm_policy *new)
731 struct xfrm_policy_queue *pq = &old->polq;
732 struct sk_buff_head list;
734 if (skb_queue_empty(&pq->hold_queue))
735 return;
737 __skb_queue_head_init(&list);
739 spin_lock_bh(&pq->hold_queue.lock);
740 skb_queue_splice_init(&pq->hold_queue, &list);
741 if (del_timer(&pq->hold_timer))
742 xfrm_pol_put(old);
743 spin_unlock_bh(&pq->hold_queue.lock);
745 pq = &new->polq;
747 spin_lock_bh(&pq->hold_queue.lock);
748 skb_queue_splice(&list, &pq->hold_queue);
749 pq->timeout = XFRM_QUEUE_TMO_MIN;
750 if (!mod_timer(&pq->hold_timer, jiffies))
751 xfrm_pol_hold(new);
752 spin_unlock_bh(&pq->hold_queue.lock);
755 static bool xfrm_policy_mark_match(struct xfrm_policy *policy,
756 struct xfrm_policy *pol)
758 u32 mark = policy->mark.v & policy->mark.m;
760 if (policy->mark.v == pol->mark.v && policy->mark.m == pol->mark.m)
761 return true;
763 if ((mark & pol->mark.m) == pol->mark.v &&
764 policy->priority == pol->priority)
765 return true;
767 return false;
770 int xfrm_policy_insert(int dir, struct xfrm_policy *policy, int excl)
772 struct net *net = xp_net(policy);
773 struct xfrm_policy *pol;
774 struct xfrm_policy *delpol;
775 struct hlist_head *chain;
776 struct hlist_node *newpos;
778 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
779 chain = policy_hash_bysel(net, &policy->selector, policy->family, dir);
780 delpol = NULL;
781 newpos = NULL;
782 hlist_for_each_entry(pol, chain, bydst) {
783 if (pol->type == policy->type &&
784 !selector_cmp(&pol->selector, &policy->selector) &&
785 xfrm_policy_mark_match(policy, pol) &&
786 xfrm_sec_ctx_match(pol->security, policy->security) &&
787 !WARN_ON(delpol)) {
788 if (excl) {
789 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
790 return -EEXIST;
792 delpol = pol;
793 if (policy->priority > pol->priority)
794 continue;
795 } else if (policy->priority >= pol->priority) {
796 newpos = &pol->bydst;
797 continue;
799 if (delpol)
800 break;
802 if (newpos)
803 hlist_add_behind_rcu(&policy->bydst, newpos);
804 else
805 hlist_add_head_rcu(&policy->bydst, chain);
806 __xfrm_policy_link(policy, dir);
807 atomic_inc(&net->xfrm.flow_cache_genid);
809 /* After previous checking, family can either be AF_INET or AF_INET6 */
810 if (policy->family == AF_INET)
811 rt_genid_bump_ipv4(net);
812 else
813 rt_genid_bump_ipv6(net);
815 if (delpol) {
816 xfrm_policy_requeue(delpol, policy);
817 __xfrm_policy_unlink(delpol, dir);
819 policy->index = delpol ? delpol->index : xfrm_gen_index(net, dir, policy->index);
820 hlist_add_head(&policy->byidx, net->xfrm.policy_byidx+idx_hash(net, policy->index));
821 policy->curlft.add_time = get_seconds();
822 policy->curlft.use_time = 0;
823 if (!mod_timer(&policy->timer, jiffies + HZ))
824 xfrm_pol_hold(policy);
825 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
827 if (delpol)
828 xfrm_policy_kill(delpol);
829 else if (xfrm_bydst_should_resize(net, dir, NULL))
830 schedule_work(&net->xfrm.policy_hash_work);
832 return 0;
834 EXPORT_SYMBOL(xfrm_policy_insert);
836 struct xfrm_policy *xfrm_policy_bysel_ctx(struct net *net, u32 mark, u8 type,
837 int dir, struct xfrm_selector *sel,
838 struct xfrm_sec_ctx *ctx, int delete,
839 int *err)
841 struct xfrm_policy *pol, *ret;
842 struct hlist_head *chain;
844 *err = 0;
845 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
846 chain = policy_hash_bysel(net, sel, sel->family, dir);
847 ret = NULL;
848 hlist_for_each_entry(pol, chain, bydst) {
849 if (pol->type == type &&
850 (mark & pol->mark.m) == pol->mark.v &&
851 !selector_cmp(sel, &pol->selector) &&
852 xfrm_sec_ctx_match(ctx, pol->security)) {
853 xfrm_pol_hold(pol);
854 if (delete) {
855 *err = security_xfrm_policy_delete(
856 pol->security);
857 if (*err) {
858 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
859 return pol;
861 __xfrm_policy_unlink(pol, dir);
863 ret = pol;
864 break;
867 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
869 if (ret && delete)
870 xfrm_policy_kill(ret);
871 return ret;
873 EXPORT_SYMBOL(xfrm_policy_bysel_ctx);
875 struct xfrm_policy *xfrm_policy_byid(struct net *net, u32 mark, u8 type,
876 int dir, u32 id, int delete, int *err)
878 struct xfrm_policy *pol, *ret;
879 struct hlist_head *chain;
881 *err = -ENOENT;
882 if (xfrm_policy_id2dir(id) != dir)
883 return NULL;
885 *err = 0;
886 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
887 chain = net->xfrm.policy_byidx + idx_hash(net, id);
888 ret = NULL;
889 hlist_for_each_entry(pol, chain, byidx) {
890 if (pol->type == type && pol->index == id &&
891 (mark & pol->mark.m) == pol->mark.v) {
892 xfrm_pol_hold(pol);
893 if (delete) {
894 *err = security_xfrm_policy_delete(
895 pol->security);
896 if (*err) {
897 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
898 return pol;
900 __xfrm_policy_unlink(pol, dir);
902 ret = pol;
903 break;
906 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
908 if (ret && delete)
909 xfrm_policy_kill(ret);
910 return ret;
912 EXPORT_SYMBOL(xfrm_policy_byid);
914 #ifdef CONFIG_SECURITY_NETWORK_XFRM
915 static inline int
916 xfrm_policy_flush_secctx_check(struct net *net, u8 type, bool task_valid)
918 int dir, err = 0;
920 for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
921 struct xfrm_policy *pol;
922 int i;
924 hlist_for_each_entry(pol,
925 &net->xfrm.policy_inexact[dir], bydst) {
926 if (pol->type != type)
927 continue;
928 err = security_xfrm_policy_delete(pol->security);
929 if (err) {
930 xfrm_audit_policy_delete(pol, 0, task_valid);
931 return err;
934 for (i = net->xfrm.policy_bydst[dir].hmask; i >= 0; i--) {
935 hlist_for_each_entry(pol,
936 net->xfrm.policy_bydst[dir].table + i,
937 bydst) {
938 if (pol->type != type)
939 continue;
940 err = security_xfrm_policy_delete(
941 pol->security);
942 if (err) {
943 xfrm_audit_policy_delete(pol, 0,
944 task_valid);
945 return err;
950 return err;
952 #else
953 static inline int
954 xfrm_policy_flush_secctx_check(struct net *net, u8 type, bool task_valid)
956 return 0;
958 #endif
960 int xfrm_policy_flush(struct net *net, u8 type, bool task_valid)
962 int dir, err = 0, cnt = 0;
964 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
966 err = xfrm_policy_flush_secctx_check(net, type, task_valid);
967 if (err)
968 goto out;
970 for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
971 struct xfrm_policy *pol;
972 int i;
974 again1:
975 hlist_for_each_entry(pol,
976 &net->xfrm.policy_inexact[dir], bydst) {
977 if (pol->type != type)
978 continue;
979 __xfrm_policy_unlink(pol, dir);
980 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
981 cnt++;
983 xfrm_audit_policy_delete(pol, 1, task_valid);
985 xfrm_policy_kill(pol);
987 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
988 goto again1;
991 for (i = net->xfrm.policy_bydst[dir].hmask; i >= 0; i--) {
992 again2:
993 hlist_for_each_entry(pol,
994 net->xfrm.policy_bydst[dir].table + i,
995 bydst) {
996 if (pol->type != type)
997 continue;
998 __xfrm_policy_unlink(pol, dir);
999 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1000 cnt++;
1002 xfrm_audit_policy_delete(pol, 1, task_valid);
1003 xfrm_policy_kill(pol);
1005 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1006 goto again2;
1011 if (!cnt)
1012 err = -ESRCH;
1013 out:
1014 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1015 return err;
1017 EXPORT_SYMBOL(xfrm_policy_flush);
1019 int xfrm_policy_walk(struct net *net, struct xfrm_policy_walk *walk,
1020 int (*func)(struct xfrm_policy *, int, int, void*),
1021 void *data)
1023 struct xfrm_policy *pol;
1024 struct xfrm_policy_walk_entry *x;
1025 int error = 0;
1027 if (walk->type >= XFRM_POLICY_TYPE_MAX &&
1028 walk->type != XFRM_POLICY_TYPE_ANY)
1029 return -EINVAL;
1031 if (list_empty(&walk->walk.all) && walk->seq != 0)
1032 return 0;
1034 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1035 if (list_empty(&walk->walk.all))
1036 x = list_first_entry(&net->xfrm.policy_all, struct xfrm_policy_walk_entry, all);
1037 else
1038 x = list_first_entry(&walk->walk.all,
1039 struct xfrm_policy_walk_entry, all);
1041 list_for_each_entry_from(x, &net->xfrm.policy_all, all) {
1042 if (x->dead)
1043 continue;
1044 pol = container_of(x, struct xfrm_policy, walk);
1045 if (walk->type != XFRM_POLICY_TYPE_ANY &&
1046 walk->type != pol->type)
1047 continue;
1048 error = func(pol, xfrm_policy_id2dir(pol->index),
1049 walk->seq, data);
1050 if (error) {
1051 list_move_tail(&walk->walk.all, &x->all);
1052 goto out;
1054 walk->seq++;
1056 if (walk->seq == 0) {
1057 error = -ENOENT;
1058 goto out;
1060 list_del_init(&walk->walk.all);
1061 out:
1062 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1063 return error;
1065 EXPORT_SYMBOL(xfrm_policy_walk);
1067 void xfrm_policy_walk_init(struct xfrm_policy_walk *walk, u8 type)
1069 INIT_LIST_HEAD(&walk->walk.all);
1070 walk->walk.dead = 1;
1071 walk->type = type;
1072 walk->seq = 0;
1074 EXPORT_SYMBOL(xfrm_policy_walk_init);
1076 void xfrm_policy_walk_done(struct xfrm_policy_walk *walk, struct net *net)
1078 if (list_empty(&walk->walk.all))
1079 return;
1081 spin_lock_bh(&net->xfrm.xfrm_policy_lock); /*FIXME where is net? */
1082 list_del(&walk->walk.all);
1083 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1085 EXPORT_SYMBOL(xfrm_policy_walk_done);
1088 * Find policy to apply to this flow.
1090 * Returns 0 if policy found, else an -errno.
1092 static int xfrm_policy_match(const struct xfrm_policy *pol,
1093 const struct flowi *fl,
1094 u8 type, u16 family, int dir)
1096 const struct xfrm_selector *sel = &pol->selector;
1097 int ret = -ESRCH;
1098 bool match;
1100 if (pol->family != family ||
1101 (fl->flowi_mark & pol->mark.m) != pol->mark.v ||
1102 pol->type != type)
1103 return ret;
1105 match = xfrm_selector_match(sel, fl, family);
1106 if (match)
1107 ret = security_xfrm_policy_lookup(pol->security, fl->flowi_secid,
1108 dir);
1110 return ret;
1113 static struct xfrm_policy *xfrm_policy_lookup_bytype(struct net *net, u8 type,
1114 const struct flowi *fl,
1115 u16 family, u8 dir)
1117 int err;
1118 struct xfrm_policy *pol, *ret;
1119 const xfrm_address_t *daddr, *saddr;
1120 struct hlist_head *chain;
1121 unsigned int sequence;
1122 u32 priority;
1124 daddr = xfrm_flowi_daddr(fl, family);
1125 saddr = xfrm_flowi_saddr(fl, family);
1126 if (unlikely(!daddr || !saddr))
1127 return NULL;
1129 rcu_read_lock();
1130 retry:
1131 do {
1132 sequence = read_seqcount_begin(&xfrm_policy_hash_generation);
1133 chain = policy_hash_direct(net, daddr, saddr, family, dir);
1134 } while (read_seqcount_retry(&xfrm_policy_hash_generation, sequence));
1136 priority = ~0U;
1137 ret = NULL;
1138 hlist_for_each_entry_rcu(pol, chain, bydst) {
1139 err = xfrm_policy_match(pol, fl, type, family, dir);
1140 if (err) {
1141 if (err == -ESRCH)
1142 continue;
1143 else {
1144 ret = ERR_PTR(err);
1145 goto fail;
1147 } else {
1148 ret = pol;
1149 priority = ret->priority;
1150 break;
1153 chain = &net->xfrm.policy_inexact[dir];
1154 hlist_for_each_entry_rcu(pol, chain, bydst) {
1155 if ((pol->priority >= priority) && ret)
1156 break;
1158 err = xfrm_policy_match(pol, fl, type, family, dir);
1159 if (err) {
1160 if (err == -ESRCH)
1161 continue;
1162 else {
1163 ret = ERR_PTR(err);
1164 goto fail;
1166 } else {
1167 ret = pol;
1168 break;
1172 if (read_seqcount_retry(&xfrm_policy_hash_generation, sequence))
1173 goto retry;
1175 if (ret && !xfrm_pol_hold_rcu(ret))
1176 goto retry;
1177 fail:
1178 rcu_read_unlock();
1180 return ret;
1183 static struct xfrm_policy *
1184 __xfrm_policy_lookup(struct net *net, const struct flowi *fl, u16 family, u8 dir)
1186 #ifdef CONFIG_XFRM_SUB_POLICY
1187 struct xfrm_policy *pol;
1189 pol = xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_SUB, fl, family, dir);
1190 if (pol != NULL)
1191 return pol;
1192 #endif
1193 return xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_MAIN, fl, family, dir);
1196 static int flow_to_policy_dir(int dir)
1198 if (XFRM_POLICY_IN == FLOW_DIR_IN &&
1199 XFRM_POLICY_OUT == FLOW_DIR_OUT &&
1200 XFRM_POLICY_FWD == FLOW_DIR_FWD)
1201 return dir;
1203 switch (dir) {
1204 default:
1205 case FLOW_DIR_IN:
1206 return XFRM_POLICY_IN;
1207 case FLOW_DIR_OUT:
1208 return XFRM_POLICY_OUT;
1209 case FLOW_DIR_FWD:
1210 return XFRM_POLICY_FWD;
1214 static struct flow_cache_object *
1215 xfrm_policy_lookup(struct net *net, const struct flowi *fl, u16 family,
1216 u8 dir, struct flow_cache_object *old_obj, void *ctx)
1218 struct xfrm_policy *pol;
1220 if (old_obj)
1221 xfrm_pol_put(container_of(old_obj, struct xfrm_policy, flo));
1223 pol = __xfrm_policy_lookup(net, fl, family, flow_to_policy_dir(dir));
1224 if (IS_ERR_OR_NULL(pol))
1225 return ERR_CAST(pol);
1227 /* Resolver returns two references:
1228 * one for cache and one for caller of flow_cache_lookup() */
1229 xfrm_pol_hold(pol);
1231 return &pol->flo;
1234 static inline int policy_to_flow_dir(int dir)
1236 if (XFRM_POLICY_IN == FLOW_DIR_IN &&
1237 XFRM_POLICY_OUT == FLOW_DIR_OUT &&
1238 XFRM_POLICY_FWD == FLOW_DIR_FWD)
1239 return dir;
1240 switch (dir) {
1241 default:
1242 case XFRM_POLICY_IN:
1243 return FLOW_DIR_IN;
1244 case XFRM_POLICY_OUT:
1245 return FLOW_DIR_OUT;
1246 case XFRM_POLICY_FWD:
1247 return FLOW_DIR_FWD;
1251 static struct xfrm_policy *xfrm_sk_policy_lookup(const struct sock *sk, int dir,
1252 const struct flowi *fl, u16 family)
1254 struct xfrm_policy *pol;
1256 rcu_read_lock();
1257 again:
1258 pol = rcu_dereference(sk->sk_policy[dir]);
1259 if (pol != NULL) {
1260 bool match;
1261 int err = 0;
1263 if (pol->family != family) {
1264 pol = NULL;
1265 goto out;
1268 match = xfrm_selector_match(&pol->selector, fl, family);
1269 if (match) {
1270 if ((sk->sk_mark & pol->mark.m) != pol->mark.v) {
1271 pol = NULL;
1272 goto out;
1274 err = security_xfrm_policy_lookup(pol->security,
1275 fl->flowi_secid,
1276 policy_to_flow_dir(dir));
1277 if (!err) {
1278 if (!xfrm_pol_hold_rcu(pol))
1279 goto again;
1280 } else if (err == -ESRCH) {
1281 pol = NULL;
1282 } else {
1283 pol = ERR_PTR(err);
1285 } else
1286 pol = NULL;
1288 out:
1289 rcu_read_unlock();
1290 return pol;
1293 static void __xfrm_policy_link(struct xfrm_policy *pol, int dir)
1295 struct net *net = xp_net(pol);
1297 list_add(&pol->walk.all, &net->xfrm.policy_all);
1298 net->xfrm.policy_count[dir]++;
1299 xfrm_pol_hold(pol);
1302 static struct xfrm_policy *__xfrm_policy_unlink(struct xfrm_policy *pol,
1303 int dir)
1305 struct net *net = xp_net(pol);
1307 if (list_empty(&pol->walk.all))
1308 return NULL;
1310 /* Socket policies are not hashed. */
1311 if (!hlist_unhashed(&pol->bydst)) {
1312 hlist_del_rcu(&pol->bydst);
1313 hlist_del(&pol->byidx);
1316 list_del_init(&pol->walk.all);
1317 net->xfrm.policy_count[dir]--;
1319 return pol;
1322 static void xfrm_sk_policy_link(struct xfrm_policy *pol, int dir)
1324 __xfrm_policy_link(pol, XFRM_POLICY_MAX + dir);
1327 static void xfrm_sk_policy_unlink(struct xfrm_policy *pol, int dir)
1329 __xfrm_policy_unlink(pol, XFRM_POLICY_MAX + dir);
1332 int xfrm_policy_delete(struct xfrm_policy *pol, int dir)
1334 struct net *net = xp_net(pol);
1336 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1337 pol = __xfrm_policy_unlink(pol, dir);
1338 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1339 if (pol) {
1340 xfrm_policy_kill(pol);
1341 return 0;
1343 return -ENOENT;
1345 EXPORT_SYMBOL(xfrm_policy_delete);
1347 int xfrm_sk_policy_insert(struct sock *sk, int dir, struct xfrm_policy *pol)
1349 struct net *net = sock_net(sk);
1350 struct xfrm_policy *old_pol;
1352 #ifdef CONFIG_XFRM_SUB_POLICY
1353 if (pol && pol->type != XFRM_POLICY_TYPE_MAIN)
1354 return -EINVAL;
1355 #endif
1357 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1358 old_pol = rcu_dereference_protected(sk->sk_policy[dir],
1359 lockdep_is_held(&net->xfrm.xfrm_policy_lock));
1360 if (pol) {
1361 pol->curlft.add_time = get_seconds();
1362 pol->index = xfrm_gen_index(net, XFRM_POLICY_MAX+dir, 0);
1363 xfrm_sk_policy_link(pol, dir);
1365 rcu_assign_pointer(sk->sk_policy[dir], pol);
1366 if (old_pol) {
1367 if (pol)
1368 xfrm_policy_requeue(old_pol, pol);
1370 /* Unlinking succeeds always. This is the only function
1371 * allowed to delete or replace socket policy.
1373 xfrm_sk_policy_unlink(old_pol, dir);
1375 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1377 if (old_pol) {
1378 xfrm_policy_kill(old_pol);
1380 return 0;
1383 static struct xfrm_policy *clone_policy(const struct xfrm_policy *old, int dir)
1385 struct xfrm_policy *newp = xfrm_policy_alloc(xp_net(old), GFP_ATOMIC);
1386 struct net *net = xp_net(old);
1388 if (newp) {
1389 newp->selector = old->selector;
1390 if (security_xfrm_policy_clone(old->security,
1391 &newp->security)) {
1392 kfree(newp);
1393 return NULL; /* ENOMEM */
1395 newp->lft = old->lft;
1396 newp->curlft = old->curlft;
1397 newp->mark = old->mark;
1398 newp->action = old->action;
1399 newp->flags = old->flags;
1400 newp->xfrm_nr = old->xfrm_nr;
1401 newp->index = old->index;
1402 newp->type = old->type;
1403 newp->family = old->family;
1404 memcpy(newp->xfrm_vec, old->xfrm_vec,
1405 newp->xfrm_nr*sizeof(struct xfrm_tmpl));
1406 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1407 xfrm_sk_policy_link(newp, dir);
1408 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1409 xfrm_pol_put(newp);
1411 return newp;
1414 int __xfrm_sk_clone_policy(struct sock *sk, const struct sock *osk)
1416 const struct xfrm_policy *p;
1417 struct xfrm_policy *np;
1418 int i, ret = 0;
1420 rcu_read_lock();
1421 for (i = 0; i < 2; i++) {
1422 p = rcu_dereference(osk->sk_policy[i]);
1423 if (p) {
1424 np = clone_policy(p, i);
1425 if (unlikely(!np)) {
1426 ret = -ENOMEM;
1427 break;
1429 rcu_assign_pointer(sk->sk_policy[i], np);
1432 rcu_read_unlock();
1433 return ret;
1436 static int
1437 xfrm_get_saddr(struct net *net, int oif, xfrm_address_t *local,
1438 xfrm_address_t *remote, unsigned short family)
1440 int err;
1441 struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1443 if (unlikely(afinfo == NULL))
1444 return -EINVAL;
1445 err = afinfo->get_saddr(net, oif, local, remote);
1446 xfrm_policy_put_afinfo(afinfo);
1447 return err;
1450 /* Resolve list of templates for the flow, given policy. */
1452 static int
1453 xfrm_tmpl_resolve_one(struct xfrm_policy *policy, const struct flowi *fl,
1454 struct xfrm_state **xfrm, unsigned short family)
1456 struct net *net = xp_net(policy);
1457 int nx;
1458 int i, error;
1459 xfrm_address_t *daddr = xfrm_flowi_daddr(fl, family);
1460 xfrm_address_t *saddr = xfrm_flowi_saddr(fl, family);
1461 xfrm_address_t tmp;
1463 for (nx = 0, i = 0; i < policy->xfrm_nr; i++) {
1464 struct xfrm_state *x;
1465 xfrm_address_t *remote = daddr;
1466 xfrm_address_t *local = saddr;
1467 struct xfrm_tmpl *tmpl = &policy->xfrm_vec[i];
1469 if (tmpl->mode == XFRM_MODE_TUNNEL ||
1470 tmpl->mode == XFRM_MODE_BEET) {
1471 remote = &tmpl->id.daddr;
1472 local = &tmpl->saddr;
1473 if (xfrm_addr_any(local, tmpl->encap_family)) {
1474 error = xfrm_get_saddr(net, fl->flowi_oif,
1475 &tmp, remote,
1476 tmpl->encap_family);
1477 if (error)
1478 goto fail;
1479 local = &tmp;
1483 x = xfrm_state_find(remote, local, fl, tmpl, policy, &error, family);
1485 if (x && x->km.state == XFRM_STATE_VALID) {
1486 xfrm[nx++] = x;
1487 daddr = remote;
1488 saddr = local;
1489 continue;
1491 if (x) {
1492 error = (x->km.state == XFRM_STATE_ERROR ?
1493 -EINVAL : -EAGAIN);
1494 xfrm_state_put(x);
1495 } else if (error == -ESRCH) {
1496 error = -EAGAIN;
1499 if (!tmpl->optional)
1500 goto fail;
1502 return nx;
1504 fail:
1505 for (nx--; nx >= 0; nx--)
1506 xfrm_state_put(xfrm[nx]);
1507 return error;
1510 static int
1511 xfrm_tmpl_resolve(struct xfrm_policy **pols, int npols, const struct flowi *fl,
1512 struct xfrm_state **xfrm, unsigned short family)
1514 struct xfrm_state *tp[XFRM_MAX_DEPTH];
1515 struct xfrm_state **tpp = (npols > 1) ? tp : xfrm;
1516 int cnx = 0;
1517 int error;
1518 int ret;
1519 int i;
1521 for (i = 0; i < npols; i++) {
1522 if (cnx + pols[i]->xfrm_nr >= XFRM_MAX_DEPTH) {
1523 error = -ENOBUFS;
1524 goto fail;
1527 ret = xfrm_tmpl_resolve_one(pols[i], fl, &tpp[cnx], family);
1528 if (ret < 0) {
1529 error = ret;
1530 goto fail;
1531 } else
1532 cnx += ret;
1535 /* found states are sorted for outbound processing */
1536 if (npols > 1)
1537 xfrm_state_sort(xfrm, tpp, cnx, family);
1539 return cnx;
1541 fail:
1542 for (cnx--; cnx >= 0; cnx--)
1543 xfrm_state_put(tpp[cnx]);
1544 return error;
1548 /* Check that the bundle accepts the flow and its components are
1549 * still valid.
1552 static inline int xfrm_get_tos(const struct flowi *fl, int family)
1554 struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1555 int tos;
1557 if (!afinfo)
1558 return -EINVAL;
1560 tos = afinfo->get_tos(fl);
1562 xfrm_policy_put_afinfo(afinfo);
1564 return tos;
1567 static struct flow_cache_object *xfrm_bundle_flo_get(struct flow_cache_object *flo)
1569 struct xfrm_dst *xdst = container_of(flo, struct xfrm_dst, flo);
1570 struct dst_entry *dst = &xdst->u.dst;
1572 if (xdst->route == NULL) {
1573 /* Dummy bundle - if it has xfrms we were not
1574 * able to build bundle as template resolution failed.
1575 * It means we need to try again resolving. */
1576 if (xdst->num_xfrms > 0)
1577 return NULL;
1578 } else if (dst->flags & DST_XFRM_QUEUE) {
1579 return NULL;
1580 } else {
1581 /* Real bundle */
1582 if (stale_bundle(dst))
1583 return NULL;
1586 dst_hold(dst);
1587 return flo;
1590 static int xfrm_bundle_flo_check(struct flow_cache_object *flo)
1592 struct xfrm_dst *xdst = container_of(flo, struct xfrm_dst, flo);
1593 struct dst_entry *dst = &xdst->u.dst;
1595 if (!xdst->route)
1596 return 0;
1597 if (stale_bundle(dst))
1598 return 0;
1600 return 1;
1603 static void xfrm_bundle_flo_delete(struct flow_cache_object *flo)
1605 struct xfrm_dst *xdst = container_of(flo, struct xfrm_dst, flo);
1606 struct dst_entry *dst = &xdst->u.dst;
1608 dst_free(dst);
1611 static const struct flow_cache_ops xfrm_bundle_fc_ops = {
1612 .get = xfrm_bundle_flo_get,
1613 .check = xfrm_bundle_flo_check,
1614 .delete = xfrm_bundle_flo_delete,
1617 static inline struct xfrm_dst *xfrm_alloc_dst(struct net *net, int family)
1619 struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1620 struct dst_ops *dst_ops;
1621 struct xfrm_dst *xdst;
1623 if (!afinfo)
1624 return ERR_PTR(-EINVAL);
1626 switch (family) {
1627 case AF_INET:
1628 dst_ops = &net->xfrm.xfrm4_dst_ops;
1629 break;
1630 #if IS_ENABLED(CONFIG_IPV6)
1631 case AF_INET6:
1632 dst_ops = &net->xfrm.xfrm6_dst_ops;
1633 break;
1634 #endif
1635 default:
1636 BUG();
1638 xdst = dst_alloc(dst_ops, NULL, 0, DST_OBSOLETE_NONE, 0);
1640 if (likely(xdst)) {
1641 struct dst_entry *dst = &xdst->u.dst;
1643 memset(dst + 1, 0, sizeof(*xdst) - sizeof(*dst));
1644 xdst->flo.ops = &xfrm_bundle_fc_ops;
1645 } else
1646 xdst = ERR_PTR(-ENOBUFS);
1648 xfrm_policy_put_afinfo(afinfo);
1650 return xdst;
1653 static inline int xfrm_init_path(struct xfrm_dst *path, struct dst_entry *dst,
1654 int nfheader_len)
1656 struct xfrm_policy_afinfo *afinfo =
1657 xfrm_policy_get_afinfo(dst->ops->family);
1658 int err;
1660 if (!afinfo)
1661 return -EINVAL;
1663 err = afinfo->init_path(path, dst, nfheader_len);
1665 xfrm_policy_put_afinfo(afinfo);
1667 return err;
1670 static inline int xfrm_fill_dst(struct xfrm_dst *xdst, struct net_device *dev,
1671 const struct flowi *fl)
1673 struct xfrm_policy_afinfo *afinfo =
1674 xfrm_policy_get_afinfo(xdst->u.dst.ops->family);
1675 int err;
1677 if (!afinfo)
1678 return -EINVAL;
1680 err = afinfo->fill_dst(xdst, dev, fl);
1682 xfrm_policy_put_afinfo(afinfo);
1684 return err;
1688 /* Allocate chain of dst_entry's, attach known xfrm's, calculate
1689 * all the metrics... Shortly, bundle a bundle.
1692 static struct dst_entry *xfrm_bundle_create(struct xfrm_policy *policy,
1693 struct xfrm_state **xfrm, int nx,
1694 const struct flowi *fl,
1695 struct dst_entry *dst)
1697 struct net *net = xp_net(policy);
1698 unsigned long now = jiffies;
1699 struct net_device *dev;
1700 struct xfrm_mode *inner_mode;
1701 struct dst_entry *dst_prev = NULL;
1702 struct dst_entry *dst0 = NULL;
1703 int i = 0;
1704 int err;
1705 int header_len = 0;
1706 int nfheader_len = 0;
1707 int trailer_len = 0;
1708 int tos;
1709 int family = policy->selector.family;
1710 xfrm_address_t saddr, daddr;
1712 xfrm_flowi_addr_get(fl, &saddr, &daddr, family);
1714 tos = xfrm_get_tos(fl, family);
1715 err = tos;
1716 if (tos < 0)
1717 goto put_states;
1719 dst_hold(dst);
1721 for (; i < nx; i++) {
1722 struct xfrm_dst *xdst = xfrm_alloc_dst(net, family);
1723 struct dst_entry *dst1 = &xdst->u.dst;
1725 err = PTR_ERR(xdst);
1726 if (IS_ERR(xdst)) {
1727 dst_release(dst);
1728 goto put_states;
1731 if (xfrm[i]->sel.family == AF_UNSPEC) {
1732 inner_mode = xfrm_ip2inner_mode(xfrm[i],
1733 xfrm_af2proto(family));
1734 if (!inner_mode) {
1735 err = -EAFNOSUPPORT;
1736 dst_release(dst);
1737 goto put_states;
1739 } else
1740 inner_mode = xfrm[i]->inner_mode;
1742 if (!dst_prev)
1743 dst0 = dst1;
1744 else {
1745 dst_prev->child = dst_clone(dst1);
1746 dst1->flags |= DST_NOHASH;
1749 xdst->route = dst;
1750 dst_copy_metrics(dst1, dst);
1752 if (xfrm[i]->props.mode != XFRM_MODE_TRANSPORT) {
1753 family = xfrm[i]->props.family;
1754 dst = xfrm_dst_lookup(xfrm[i], tos, fl->flowi_oif,
1755 &saddr, &daddr, family);
1756 err = PTR_ERR(dst);
1757 if (IS_ERR(dst))
1758 goto put_states;
1759 } else
1760 dst_hold(dst);
1762 dst1->xfrm = xfrm[i];
1763 xdst->xfrm_genid = xfrm[i]->genid;
1765 dst1->obsolete = DST_OBSOLETE_FORCE_CHK;
1766 dst1->flags |= DST_HOST;
1767 dst1->lastuse = now;
1769 dst1->input = dst_discard;
1770 dst1->output = inner_mode->afinfo->output;
1772 dst1->next = dst_prev;
1773 dst_prev = dst1;
1775 header_len += xfrm[i]->props.header_len;
1776 if (xfrm[i]->type->flags & XFRM_TYPE_NON_FRAGMENT)
1777 nfheader_len += xfrm[i]->props.header_len;
1778 trailer_len += xfrm[i]->props.trailer_len;
1781 dst_prev->child = dst;
1782 dst0->path = dst;
1784 err = -ENODEV;
1785 dev = dst->dev;
1786 if (!dev)
1787 goto free_dst;
1789 xfrm_init_path((struct xfrm_dst *)dst0, dst, nfheader_len);
1790 xfrm_init_pmtu(dst_prev);
1792 for (dst_prev = dst0; dst_prev != dst; dst_prev = dst_prev->child) {
1793 struct xfrm_dst *xdst = (struct xfrm_dst *)dst_prev;
1795 err = xfrm_fill_dst(xdst, dev, fl);
1796 if (err)
1797 goto free_dst;
1799 dst_prev->header_len = header_len;
1800 dst_prev->trailer_len = trailer_len;
1801 header_len -= xdst->u.dst.xfrm->props.header_len;
1802 trailer_len -= xdst->u.dst.xfrm->props.trailer_len;
1805 out:
1806 return dst0;
1808 put_states:
1809 for (; i < nx; i++)
1810 xfrm_state_put(xfrm[i]);
1811 free_dst:
1812 if (dst0)
1813 dst_free(dst0);
1814 dst0 = ERR_PTR(err);
1815 goto out;
1818 static int xfrm_expand_policies(const struct flowi *fl, u16 family,
1819 struct xfrm_policy **pols,
1820 int *num_pols, int *num_xfrms)
1822 int i;
1824 if (*num_pols == 0 || !pols[0]) {
1825 *num_pols = 0;
1826 *num_xfrms = 0;
1827 return 0;
1829 if (IS_ERR(pols[0]))
1830 return PTR_ERR(pols[0]);
1832 *num_xfrms = pols[0]->xfrm_nr;
1834 #ifdef CONFIG_XFRM_SUB_POLICY
1835 if (pols[0] && pols[0]->action == XFRM_POLICY_ALLOW &&
1836 pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
1837 pols[1] = xfrm_policy_lookup_bytype(xp_net(pols[0]),
1838 XFRM_POLICY_TYPE_MAIN,
1839 fl, family,
1840 XFRM_POLICY_OUT);
1841 if (pols[1]) {
1842 if (IS_ERR(pols[1])) {
1843 xfrm_pols_put(pols, *num_pols);
1844 return PTR_ERR(pols[1]);
1846 (*num_pols)++;
1847 (*num_xfrms) += pols[1]->xfrm_nr;
1850 #endif
1851 for (i = 0; i < *num_pols; i++) {
1852 if (pols[i]->action != XFRM_POLICY_ALLOW) {
1853 *num_xfrms = -1;
1854 break;
1858 return 0;
1862 static struct xfrm_dst *
1863 xfrm_resolve_and_create_bundle(struct xfrm_policy **pols, int num_pols,
1864 const struct flowi *fl, u16 family,
1865 struct dst_entry *dst_orig)
1867 struct net *net = xp_net(pols[0]);
1868 struct xfrm_state *xfrm[XFRM_MAX_DEPTH];
1869 struct dst_entry *dst;
1870 struct xfrm_dst *xdst;
1871 int err;
1873 /* Try to instantiate a bundle */
1874 err = xfrm_tmpl_resolve(pols, num_pols, fl, xfrm, family);
1875 if (err <= 0) {
1876 if (err == 0)
1877 return NULL;
1879 if (err != -EAGAIN)
1880 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLERROR);
1881 return ERR_PTR(err);
1884 dst = xfrm_bundle_create(pols[0], xfrm, err, fl, dst_orig);
1885 if (IS_ERR(dst)) {
1886 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTBUNDLEGENERROR);
1887 return ERR_CAST(dst);
1890 xdst = (struct xfrm_dst *)dst;
1891 xdst->num_xfrms = err;
1892 xdst->num_pols = num_pols;
1893 memcpy(xdst->pols, pols, sizeof(struct xfrm_policy *) * num_pols);
1894 xdst->policy_genid = atomic_read(&pols[0]->genid);
1896 return xdst;
1899 static void xfrm_policy_queue_process(unsigned long arg)
1901 struct sk_buff *skb;
1902 struct sock *sk;
1903 struct dst_entry *dst;
1904 struct xfrm_policy *pol = (struct xfrm_policy *)arg;
1905 struct net *net = xp_net(pol);
1906 struct xfrm_policy_queue *pq = &pol->polq;
1907 struct flowi fl;
1908 struct sk_buff_head list;
1910 spin_lock(&pq->hold_queue.lock);
1911 skb = skb_peek(&pq->hold_queue);
1912 if (!skb) {
1913 spin_unlock(&pq->hold_queue.lock);
1914 goto out;
1916 dst = skb_dst(skb);
1917 sk = skb->sk;
1918 xfrm_decode_session(skb, &fl, dst->ops->family);
1919 spin_unlock(&pq->hold_queue.lock);
1921 dst_hold(dst->path);
1922 dst = xfrm_lookup(net, dst->path, &fl, sk, 0);
1923 if (IS_ERR(dst))
1924 goto purge_queue;
1926 if (dst->flags & DST_XFRM_QUEUE) {
1927 dst_release(dst);
1929 if (pq->timeout >= XFRM_QUEUE_TMO_MAX)
1930 goto purge_queue;
1932 pq->timeout = pq->timeout << 1;
1933 if (!mod_timer(&pq->hold_timer, jiffies + pq->timeout))
1934 xfrm_pol_hold(pol);
1935 goto out;
1938 dst_release(dst);
1940 __skb_queue_head_init(&list);
1942 spin_lock(&pq->hold_queue.lock);
1943 pq->timeout = 0;
1944 skb_queue_splice_init(&pq->hold_queue, &list);
1945 spin_unlock(&pq->hold_queue.lock);
1947 while (!skb_queue_empty(&list)) {
1948 skb = __skb_dequeue(&list);
1950 xfrm_decode_session(skb, &fl, skb_dst(skb)->ops->family);
1951 dst_hold(skb_dst(skb)->path);
1952 dst = xfrm_lookup(net, skb_dst(skb)->path, &fl, skb->sk, 0);
1953 if (IS_ERR(dst)) {
1954 kfree_skb(skb);
1955 continue;
1958 nf_reset(skb);
1959 skb_dst_drop(skb);
1960 skb_dst_set(skb, dst);
1962 dst_output(net, skb->sk, skb);
1965 out:
1966 xfrm_pol_put(pol);
1967 return;
1969 purge_queue:
1970 pq->timeout = 0;
1971 skb_queue_purge(&pq->hold_queue);
1972 xfrm_pol_put(pol);
1975 static int xdst_queue_output(struct net *net, struct sock *sk, struct sk_buff *skb)
1977 unsigned long sched_next;
1978 struct dst_entry *dst = skb_dst(skb);
1979 struct xfrm_dst *xdst = (struct xfrm_dst *) dst;
1980 struct xfrm_policy *pol = xdst->pols[0];
1981 struct xfrm_policy_queue *pq = &pol->polq;
1983 if (unlikely(skb_fclone_busy(sk, skb))) {
1984 kfree_skb(skb);
1985 return 0;
1988 if (pq->hold_queue.qlen > XFRM_MAX_QUEUE_LEN) {
1989 kfree_skb(skb);
1990 return -EAGAIN;
1993 skb_dst_force(skb);
1995 spin_lock_bh(&pq->hold_queue.lock);
1997 if (!pq->timeout)
1998 pq->timeout = XFRM_QUEUE_TMO_MIN;
2000 sched_next = jiffies + pq->timeout;
2002 if (del_timer(&pq->hold_timer)) {
2003 if (time_before(pq->hold_timer.expires, sched_next))
2004 sched_next = pq->hold_timer.expires;
2005 xfrm_pol_put(pol);
2008 __skb_queue_tail(&pq->hold_queue, skb);
2009 if (!mod_timer(&pq->hold_timer, sched_next))
2010 xfrm_pol_hold(pol);
2012 spin_unlock_bh(&pq->hold_queue.lock);
2014 return 0;
2017 static struct xfrm_dst *xfrm_create_dummy_bundle(struct net *net,
2018 struct xfrm_flo *xflo,
2019 const struct flowi *fl,
2020 int num_xfrms,
2021 u16 family)
2023 int err;
2024 struct net_device *dev;
2025 struct dst_entry *dst;
2026 struct dst_entry *dst1;
2027 struct xfrm_dst *xdst;
2029 xdst = xfrm_alloc_dst(net, family);
2030 if (IS_ERR(xdst))
2031 return xdst;
2033 if (!(xflo->flags & XFRM_LOOKUP_QUEUE) ||
2034 net->xfrm.sysctl_larval_drop ||
2035 num_xfrms <= 0)
2036 return xdst;
2038 dst = xflo->dst_orig;
2039 dst1 = &xdst->u.dst;
2040 dst_hold(dst);
2041 xdst->route = dst;
2043 dst_copy_metrics(dst1, dst);
2045 dst1->obsolete = DST_OBSOLETE_FORCE_CHK;
2046 dst1->flags |= DST_HOST | DST_XFRM_QUEUE;
2047 dst1->lastuse = jiffies;
2049 dst1->input = dst_discard;
2050 dst1->output = xdst_queue_output;
2052 dst_hold(dst);
2053 dst1->child = dst;
2054 dst1->path = dst;
2056 xfrm_init_path((struct xfrm_dst *)dst1, dst, 0);
2058 err = -ENODEV;
2059 dev = dst->dev;
2060 if (!dev)
2061 goto free_dst;
2063 err = xfrm_fill_dst(xdst, dev, fl);
2064 if (err)
2065 goto free_dst;
2067 out:
2068 return xdst;
2070 free_dst:
2071 dst_release(dst1);
2072 xdst = ERR_PTR(err);
2073 goto out;
2076 static struct flow_cache_object *
2077 xfrm_bundle_lookup(struct net *net, const struct flowi *fl, u16 family, u8 dir,
2078 struct flow_cache_object *oldflo, void *ctx)
2080 struct xfrm_flo *xflo = (struct xfrm_flo *)ctx;
2081 struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
2082 struct xfrm_dst *xdst, *new_xdst;
2083 int num_pols = 0, num_xfrms = 0, i, err, pol_dead;
2085 /* Check if the policies from old bundle are usable */
2086 xdst = NULL;
2087 if (oldflo) {
2088 xdst = container_of(oldflo, struct xfrm_dst, flo);
2089 num_pols = xdst->num_pols;
2090 num_xfrms = xdst->num_xfrms;
2091 pol_dead = 0;
2092 for (i = 0; i < num_pols; i++) {
2093 pols[i] = xdst->pols[i];
2094 pol_dead |= pols[i]->walk.dead;
2096 if (pol_dead) {
2097 dst_free(&xdst->u.dst);
2098 xdst = NULL;
2099 num_pols = 0;
2100 num_xfrms = 0;
2101 oldflo = NULL;
2105 /* Resolve policies to use if we couldn't get them from
2106 * previous cache entry */
2107 if (xdst == NULL) {
2108 num_pols = 1;
2109 pols[0] = __xfrm_policy_lookup(net, fl, family,
2110 flow_to_policy_dir(dir));
2111 err = xfrm_expand_policies(fl, family, pols,
2112 &num_pols, &num_xfrms);
2113 if (err < 0)
2114 goto inc_error;
2115 if (num_pols == 0)
2116 return NULL;
2117 if (num_xfrms <= 0)
2118 goto make_dummy_bundle;
2121 new_xdst = xfrm_resolve_and_create_bundle(pols, num_pols, fl, family,
2122 xflo->dst_orig);
2123 if (IS_ERR(new_xdst)) {
2124 err = PTR_ERR(new_xdst);
2125 if (err != -EAGAIN)
2126 goto error;
2127 if (oldflo == NULL)
2128 goto make_dummy_bundle;
2129 dst_hold(&xdst->u.dst);
2130 return oldflo;
2131 } else if (new_xdst == NULL) {
2132 num_xfrms = 0;
2133 if (oldflo == NULL)
2134 goto make_dummy_bundle;
2135 xdst->num_xfrms = 0;
2136 dst_hold(&xdst->u.dst);
2137 return oldflo;
2140 /* Kill the previous bundle */
2141 if (xdst) {
2142 /* The policies were stolen for newly generated bundle */
2143 xdst->num_pols = 0;
2144 dst_free(&xdst->u.dst);
2147 /* Flow cache does not have reference, it dst_free()'s,
2148 * but we do need to return one reference for original caller */
2149 dst_hold(&new_xdst->u.dst);
2150 return &new_xdst->flo;
2152 make_dummy_bundle:
2153 /* We found policies, but there's no bundles to instantiate:
2154 * either because the policy blocks, has no transformations or
2155 * we could not build template (no xfrm_states).*/
2156 xdst = xfrm_create_dummy_bundle(net, xflo, fl, num_xfrms, family);
2157 if (IS_ERR(xdst)) {
2158 xfrm_pols_put(pols, num_pols);
2159 return ERR_CAST(xdst);
2161 xdst->num_pols = num_pols;
2162 xdst->num_xfrms = num_xfrms;
2163 memcpy(xdst->pols, pols, sizeof(struct xfrm_policy *) * num_pols);
2165 dst_hold(&xdst->u.dst);
2166 return &xdst->flo;
2168 inc_error:
2169 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLERROR);
2170 error:
2171 if (xdst != NULL)
2172 dst_free(&xdst->u.dst);
2173 else
2174 xfrm_pols_put(pols, num_pols);
2175 return ERR_PTR(err);
2178 static struct dst_entry *make_blackhole(struct net *net, u16 family,
2179 struct dst_entry *dst_orig)
2181 struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
2182 struct dst_entry *ret;
2184 if (!afinfo) {
2185 dst_release(dst_orig);
2186 return ERR_PTR(-EINVAL);
2187 } else {
2188 ret = afinfo->blackhole_route(net, dst_orig);
2190 xfrm_policy_put_afinfo(afinfo);
2192 return ret;
2195 /* Main function: finds/creates a bundle for given flow.
2197 * At the moment we eat a raw IP route. Mostly to speed up lookups
2198 * on interfaces with disabled IPsec.
2200 struct dst_entry *xfrm_lookup(struct net *net, struct dst_entry *dst_orig,
2201 const struct flowi *fl,
2202 const struct sock *sk, int flags)
2204 struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
2205 struct flow_cache_object *flo;
2206 struct xfrm_dst *xdst;
2207 struct dst_entry *dst, *route;
2208 u16 family = dst_orig->ops->family;
2209 u8 dir = policy_to_flow_dir(XFRM_POLICY_OUT);
2210 int i, err, num_pols, num_xfrms = 0, drop_pols = 0;
2212 dst = NULL;
2213 xdst = NULL;
2214 route = NULL;
2216 sk = sk_const_to_full_sk(sk);
2217 if (sk && sk->sk_policy[XFRM_POLICY_OUT]) {
2218 num_pols = 1;
2219 pols[0] = xfrm_sk_policy_lookup(sk, XFRM_POLICY_OUT, fl, family);
2220 err = xfrm_expand_policies(fl, family, pols,
2221 &num_pols, &num_xfrms);
2222 if (err < 0)
2223 goto dropdst;
2225 if (num_pols) {
2226 if (num_xfrms <= 0) {
2227 drop_pols = num_pols;
2228 goto no_transform;
2231 xdst = xfrm_resolve_and_create_bundle(
2232 pols, num_pols, fl,
2233 family, dst_orig);
2234 if (IS_ERR(xdst)) {
2235 xfrm_pols_put(pols, num_pols);
2236 err = PTR_ERR(xdst);
2237 goto dropdst;
2238 } else if (xdst == NULL) {
2239 num_xfrms = 0;
2240 drop_pols = num_pols;
2241 goto no_transform;
2244 dst_hold(&xdst->u.dst);
2245 xdst->u.dst.flags |= DST_NOCACHE;
2246 route = xdst->route;
2250 if (xdst == NULL) {
2251 struct xfrm_flo xflo;
2253 xflo.dst_orig = dst_orig;
2254 xflo.flags = flags;
2256 /* To accelerate a bit... */
2257 if ((dst_orig->flags & DST_NOXFRM) ||
2258 !net->xfrm.policy_count[XFRM_POLICY_OUT])
2259 goto nopol;
2261 flo = flow_cache_lookup(net, fl, family, dir,
2262 xfrm_bundle_lookup, &xflo);
2263 if (flo == NULL)
2264 goto nopol;
2265 if (IS_ERR(flo)) {
2266 err = PTR_ERR(flo);
2267 goto dropdst;
2269 xdst = container_of(flo, struct xfrm_dst, flo);
2271 num_pols = xdst->num_pols;
2272 num_xfrms = xdst->num_xfrms;
2273 memcpy(pols, xdst->pols, sizeof(struct xfrm_policy *) * num_pols);
2274 route = xdst->route;
2277 dst = &xdst->u.dst;
2278 if (route == NULL && num_xfrms > 0) {
2279 /* The only case when xfrm_bundle_lookup() returns a
2280 * bundle with null route, is when the template could
2281 * not be resolved. It means policies are there, but
2282 * bundle could not be created, since we don't yet
2283 * have the xfrm_state's. We need to wait for KM to
2284 * negotiate new SA's or bail out with error.*/
2285 if (net->xfrm.sysctl_larval_drop) {
2286 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTNOSTATES);
2287 err = -EREMOTE;
2288 goto error;
2291 err = -EAGAIN;
2293 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTNOSTATES);
2294 goto error;
2297 no_transform:
2298 if (num_pols == 0)
2299 goto nopol;
2301 if ((flags & XFRM_LOOKUP_ICMP) &&
2302 !(pols[0]->flags & XFRM_POLICY_ICMP)) {
2303 err = -ENOENT;
2304 goto error;
2307 for (i = 0; i < num_pols; i++)
2308 pols[i]->curlft.use_time = get_seconds();
2310 if (num_xfrms < 0) {
2311 /* Prohibit the flow */
2312 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLBLOCK);
2313 err = -EPERM;
2314 goto error;
2315 } else if (num_xfrms > 0) {
2316 /* Flow transformed */
2317 dst_release(dst_orig);
2318 } else {
2319 /* Flow passes untransformed */
2320 dst_release(dst);
2321 dst = dst_orig;
2324 xfrm_pols_put(pols, drop_pols);
2325 if (dst && dst->xfrm &&
2326 dst->xfrm->props.mode == XFRM_MODE_TUNNEL)
2327 dst->flags |= DST_XFRM_TUNNEL;
2328 return dst;
2330 nopol:
2331 if (!(flags & XFRM_LOOKUP_ICMP)) {
2332 dst = dst_orig;
2333 goto ok;
2335 err = -ENOENT;
2336 error:
2337 dst_release(dst);
2338 dropdst:
2339 if (!(flags & XFRM_LOOKUP_KEEP_DST_REF))
2340 dst_release(dst_orig);
2341 xfrm_pols_put(pols, drop_pols);
2342 return ERR_PTR(err);
2344 EXPORT_SYMBOL(xfrm_lookup);
2346 /* Callers of xfrm_lookup_route() must ensure a call to dst_output().
2347 * Otherwise we may send out blackholed packets.
2349 struct dst_entry *xfrm_lookup_route(struct net *net, struct dst_entry *dst_orig,
2350 const struct flowi *fl,
2351 const struct sock *sk, int flags)
2353 struct dst_entry *dst = xfrm_lookup(net, dst_orig, fl, sk,
2354 flags | XFRM_LOOKUP_QUEUE |
2355 XFRM_LOOKUP_KEEP_DST_REF);
2357 if (IS_ERR(dst) && PTR_ERR(dst) == -EREMOTE)
2358 return make_blackhole(net, dst_orig->ops->family, dst_orig);
2360 if (IS_ERR(dst))
2361 dst_release(dst_orig);
2363 return dst;
2365 EXPORT_SYMBOL(xfrm_lookup_route);
2367 static inline int
2368 xfrm_secpath_reject(int idx, struct sk_buff *skb, const struct flowi *fl)
2370 struct xfrm_state *x;
2372 if (!skb->sp || idx < 0 || idx >= skb->sp->len)
2373 return 0;
2374 x = skb->sp->xvec[idx];
2375 if (!x->type->reject)
2376 return 0;
2377 return x->type->reject(x, skb, fl);
2380 /* When skb is transformed back to its "native" form, we have to
2381 * check policy restrictions. At the moment we make this in maximally
2382 * stupid way. Shame on me. :-) Of course, connected sockets must
2383 * have policy cached at them.
2386 static inline int
2387 xfrm_state_ok(const struct xfrm_tmpl *tmpl, const struct xfrm_state *x,
2388 unsigned short family)
2390 if (xfrm_state_kern(x))
2391 return tmpl->optional && !xfrm_state_addr_cmp(tmpl, x, tmpl->encap_family);
2392 return x->id.proto == tmpl->id.proto &&
2393 (x->id.spi == tmpl->id.spi || !tmpl->id.spi) &&
2394 (x->props.reqid == tmpl->reqid || !tmpl->reqid) &&
2395 x->props.mode == tmpl->mode &&
2396 (tmpl->allalgs || (tmpl->aalgos & (1<<x->props.aalgo)) ||
2397 !(xfrm_id_proto_match(tmpl->id.proto, IPSEC_PROTO_ANY))) &&
2398 !(x->props.mode != XFRM_MODE_TRANSPORT &&
2399 xfrm_state_addr_cmp(tmpl, x, family));
2403 * 0 or more than 0 is returned when validation is succeeded (either bypass
2404 * because of optional transport mode, or next index of the mathced secpath
2405 * state with the template.
2406 * -1 is returned when no matching template is found.
2407 * Otherwise "-2 - errored_index" is returned.
2409 static inline int
2410 xfrm_policy_ok(const struct xfrm_tmpl *tmpl, const struct sec_path *sp, int start,
2411 unsigned short family)
2413 int idx = start;
2415 if (tmpl->optional) {
2416 if (tmpl->mode == XFRM_MODE_TRANSPORT)
2417 return start;
2418 } else
2419 start = -1;
2420 for (; idx < sp->len; idx++) {
2421 if (xfrm_state_ok(tmpl, sp->xvec[idx], family))
2422 return ++idx;
2423 if (sp->xvec[idx]->props.mode != XFRM_MODE_TRANSPORT) {
2424 if (start == -1)
2425 start = -2-idx;
2426 break;
2429 return start;
2432 int __xfrm_decode_session(struct sk_buff *skb, struct flowi *fl,
2433 unsigned int family, int reverse)
2435 struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
2436 int err;
2438 if (unlikely(afinfo == NULL))
2439 return -EAFNOSUPPORT;
2441 afinfo->decode_session(skb, fl, reverse);
2442 err = security_xfrm_decode_session(skb, &fl->flowi_secid);
2443 xfrm_policy_put_afinfo(afinfo);
2444 return err;
2446 EXPORT_SYMBOL(__xfrm_decode_session);
2448 static inline int secpath_has_nontransport(const struct sec_path *sp, int k, int *idxp)
2450 for (; k < sp->len; k++) {
2451 if (sp->xvec[k]->props.mode != XFRM_MODE_TRANSPORT) {
2452 *idxp = k;
2453 return 1;
2457 return 0;
2460 int __xfrm_policy_check(struct sock *sk, int dir, struct sk_buff *skb,
2461 unsigned short family)
2463 struct net *net = dev_net(skb->dev);
2464 struct xfrm_policy *pol;
2465 struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
2466 int npols = 0;
2467 int xfrm_nr;
2468 int pi;
2469 int reverse;
2470 struct flowi fl;
2471 u8 fl_dir;
2472 int xerr_idx = -1;
2474 reverse = dir & ~XFRM_POLICY_MASK;
2475 dir &= XFRM_POLICY_MASK;
2476 fl_dir = policy_to_flow_dir(dir);
2478 if (__xfrm_decode_session(skb, &fl, family, reverse) < 0) {
2479 XFRM_INC_STATS(net, LINUX_MIB_XFRMINHDRERROR);
2480 return 0;
2483 nf_nat_decode_session(skb, &fl, family);
2485 /* First, check used SA against their selectors. */
2486 if (skb->sp) {
2487 int i;
2489 for (i = skb->sp->len-1; i >= 0; i--) {
2490 struct xfrm_state *x = skb->sp->xvec[i];
2491 if (!xfrm_selector_match(&x->sel, &fl, family)) {
2492 XFRM_INC_STATS(net, LINUX_MIB_XFRMINSTATEMISMATCH);
2493 return 0;
2498 pol = NULL;
2499 sk = sk_to_full_sk(sk);
2500 if (sk && sk->sk_policy[dir]) {
2501 pol = xfrm_sk_policy_lookup(sk, dir, &fl, family);
2502 if (IS_ERR(pol)) {
2503 XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
2504 return 0;
2508 if (!pol) {
2509 struct flow_cache_object *flo;
2511 flo = flow_cache_lookup(net, &fl, family, fl_dir,
2512 xfrm_policy_lookup, NULL);
2513 if (IS_ERR_OR_NULL(flo))
2514 pol = ERR_CAST(flo);
2515 else
2516 pol = container_of(flo, struct xfrm_policy, flo);
2519 if (IS_ERR(pol)) {
2520 XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
2521 return 0;
2524 if (!pol) {
2525 if (skb->sp && secpath_has_nontransport(skb->sp, 0, &xerr_idx)) {
2526 xfrm_secpath_reject(xerr_idx, skb, &fl);
2527 XFRM_INC_STATS(net, LINUX_MIB_XFRMINNOPOLS);
2528 return 0;
2530 return 1;
2533 pol->curlft.use_time = get_seconds();
2535 pols[0] = pol;
2536 npols++;
2537 #ifdef CONFIG_XFRM_SUB_POLICY
2538 if (pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
2539 pols[1] = xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_MAIN,
2540 &fl, family,
2541 XFRM_POLICY_IN);
2542 if (pols[1]) {
2543 if (IS_ERR(pols[1])) {
2544 XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
2545 return 0;
2547 pols[1]->curlft.use_time = get_seconds();
2548 npols++;
2551 #endif
2553 if (pol->action == XFRM_POLICY_ALLOW) {
2554 struct sec_path *sp;
2555 static struct sec_path dummy;
2556 struct xfrm_tmpl *tp[XFRM_MAX_DEPTH];
2557 struct xfrm_tmpl *stp[XFRM_MAX_DEPTH];
2558 struct xfrm_tmpl **tpp = tp;
2559 int ti = 0;
2560 int i, k;
2562 if ((sp = skb->sp) == NULL)
2563 sp = &dummy;
2565 for (pi = 0; pi < npols; pi++) {
2566 if (pols[pi] != pol &&
2567 pols[pi]->action != XFRM_POLICY_ALLOW) {
2568 XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLBLOCK);
2569 goto reject;
2571 if (ti + pols[pi]->xfrm_nr >= XFRM_MAX_DEPTH) {
2572 XFRM_INC_STATS(net, LINUX_MIB_XFRMINBUFFERERROR);
2573 goto reject_error;
2575 for (i = 0; i < pols[pi]->xfrm_nr; i++)
2576 tpp[ti++] = &pols[pi]->xfrm_vec[i];
2578 xfrm_nr = ti;
2579 if (npols > 1) {
2580 xfrm_tmpl_sort(stp, tpp, xfrm_nr, family, net);
2581 tpp = stp;
2584 /* For each tunnel xfrm, find the first matching tmpl.
2585 * For each tmpl before that, find corresponding xfrm.
2586 * Order is _important_. Later we will implement
2587 * some barriers, but at the moment barriers
2588 * are implied between each two transformations.
2590 for (i = xfrm_nr-1, k = 0; i >= 0; i--) {
2591 k = xfrm_policy_ok(tpp[i], sp, k, family);
2592 if (k < 0) {
2593 if (k < -1)
2594 /* "-2 - errored_index" returned */
2595 xerr_idx = -(2+k);
2596 XFRM_INC_STATS(net, LINUX_MIB_XFRMINTMPLMISMATCH);
2597 goto reject;
2601 if (secpath_has_nontransport(sp, k, &xerr_idx)) {
2602 XFRM_INC_STATS(net, LINUX_MIB_XFRMINTMPLMISMATCH);
2603 goto reject;
2606 xfrm_pols_put(pols, npols);
2607 return 1;
2609 XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLBLOCK);
2611 reject:
2612 xfrm_secpath_reject(xerr_idx, skb, &fl);
2613 reject_error:
2614 xfrm_pols_put(pols, npols);
2615 return 0;
2617 EXPORT_SYMBOL(__xfrm_policy_check);
2619 int __xfrm_route_forward(struct sk_buff *skb, unsigned short family)
2621 struct net *net = dev_net(skb->dev);
2622 struct flowi fl;
2623 struct dst_entry *dst;
2624 int res = 1;
2626 if (xfrm_decode_session(skb, &fl, family) < 0) {
2627 XFRM_INC_STATS(net, LINUX_MIB_XFRMFWDHDRERROR);
2628 return 0;
2631 skb_dst_force(skb);
2633 dst = xfrm_lookup(net, skb_dst(skb), &fl, NULL, XFRM_LOOKUP_QUEUE);
2634 if (IS_ERR(dst)) {
2635 res = 0;
2636 dst = NULL;
2638 skb_dst_set(skb, dst);
2639 return res;
2641 EXPORT_SYMBOL(__xfrm_route_forward);
2643 /* Optimize later using cookies and generation ids. */
2645 static struct dst_entry *xfrm_dst_check(struct dst_entry *dst, u32 cookie)
2647 /* Code (such as __xfrm4_bundle_create()) sets dst->obsolete
2648 * to DST_OBSOLETE_FORCE_CHK to force all XFRM destinations to
2649 * get validated by dst_ops->check on every use. We do this
2650 * because when a normal route referenced by an XFRM dst is
2651 * obsoleted we do not go looking around for all parent
2652 * referencing XFRM dsts so that we can invalidate them. It
2653 * is just too much work. Instead we make the checks here on
2654 * every use. For example:
2656 * XFRM dst A --> IPv4 dst X
2658 * X is the "xdst->route" of A (X is also the "dst->path" of A
2659 * in this example). If X is marked obsolete, "A" will not
2660 * notice. That's what we are validating here via the
2661 * stale_bundle() check.
2663 * When a policy's bundle is pruned, we dst_free() the XFRM
2664 * dst which causes it's ->obsolete field to be set to
2665 * DST_OBSOLETE_DEAD. If an XFRM dst has been pruned like
2666 * this, we want to force a new route lookup.
2668 if (dst->obsolete < 0 && !stale_bundle(dst))
2669 return dst;
2671 return NULL;
2674 static int stale_bundle(struct dst_entry *dst)
2676 return !xfrm_bundle_ok((struct xfrm_dst *)dst);
2679 void xfrm_dst_ifdown(struct dst_entry *dst, struct net_device *dev)
2681 while ((dst = dst->child) && dst->xfrm && dst->dev == dev) {
2682 dst->dev = dev_net(dev)->loopback_dev;
2683 dev_hold(dst->dev);
2684 dev_put(dev);
2687 EXPORT_SYMBOL(xfrm_dst_ifdown);
2689 static void xfrm_link_failure(struct sk_buff *skb)
2691 /* Impossible. Such dst must be popped before reaches point of failure. */
2694 static struct dst_entry *xfrm_negative_advice(struct dst_entry *dst)
2696 if (dst) {
2697 if (dst->obsolete) {
2698 dst_release(dst);
2699 dst = NULL;
2702 return dst;
2705 void xfrm_garbage_collect(struct net *net)
2707 flow_cache_flush(net);
2709 EXPORT_SYMBOL(xfrm_garbage_collect);
2711 static void xfrm_garbage_collect_deferred(struct net *net)
2713 flow_cache_flush_deferred(net);
2716 static void xfrm_init_pmtu(struct dst_entry *dst)
2718 do {
2719 struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
2720 u32 pmtu, route_mtu_cached;
2722 pmtu = dst_mtu(dst->child);
2723 xdst->child_mtu_cached = pmtu;
2725 pmtu = xfrm_state_mtu(dst->xfrm, pmtu);
2727 route_mtu_cached = dst_mtu(xdst->route);
2728 xdst->route_mtu_cached = route_mtu_cached;
2730 if (pmtu > route_mtu_cached)
2731 pmtu = route_mtu_cached;
2733 dst_metric_set(dst, RTAX_MTU, pmtu);
2734 } while ((dst = dst->next));
2737 /* Check that the bundle accepts the flow and its components are
2738 * still valid.
2741 static int xfrm_bundle_ok(struct xfrm_dst *first)
2743 struct dst_entry *dst = &first->u.dst;
2744 struct xfrm_dst *last;
2745 u32 mtu;
2747 if (!dst_check(dst->path, ((struct xfrm_dst *)dst)->path_cookie) ||
2748 (dst->dev && !netif_running(dst->dev)))
2749 return 0;
2751 if (dst->flags & DST_XFRM_QUEUE)
2752 return 1;
2754 last = NULL;
2756 do {
2757 struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
2759 if (dst->xfrm->km.state != XFRM_STATE_VALID)
2760 return 0;
2761 if (xdst->xfrm_genid != dst->xfrm->genid)
2762 return 0;
2763 if (xdst->num_pols > 0 &&
2764 xdst->policy_genid != atomic_read(&xdst->pols[0]->genid))
2765 return 0;
2767 mtu = dst_mtu(dst->child);
2768 if (xdst->child_mtu_cached != mtu) {
2769 last = xdst;
2770 xdst->child_mtu_cached = mtu;
2773 if (!dst_check(xdst->route, xdst->route_cookie))
2774 return 0;
2775 mtu = dst_mtu(xdst->route);
2776 if (xdst->route_mtu_cached != mtu) {
2777 last = xdst;
2778 xdst->route_mtu_cached = mtu;
2781 dst = dst->child;
2782 } while (dst->xfrm);
2784 if (likely(!last))
2785 return 1;
2787 mtu = last->child_mtu_cached;
2788 for (;;) {
2789 dst = &last->u.dst;
2791 mtu = xfrm_state_mtu(dst->xfrm, mtu);
2792 if (mtu > last->route_mtu_cached)
2793 mtu = last->route_mtu_cached;
2794 dst_metric_set(dst, RTAX_MTU, mtu);
2796 if (last == first)
2797 break;
2799 last = (struct xfrm_dst *)last->u.dst.next;
2800 last->child_mtu_cached = mtu;
2803 return 1;
2806 static unsigned int xfrm_default_advmss(const struct dst_entry *dst)
2808 return dst_metric_advmss(dst->path);
2811 static unsigned int xfrm_mtu(const struct dst_entry *dst)
2813 unsigned int mtu = dst_metric_raw(dst, RTAX_MTU);
2815 return mtu ? : dst_mtu(dst->path);
2818 static struct neighbour *xfrm_neigh_lookup(const struct dst_entry *dst,
2819 struct sk_buff *skb,
2820 const void *daddr)
2822 return dst->path->ops->neigh_lookup(dst, skb, daddr);
2825 int xfrm_policy_register_afinfo(struct xfrm_policy_afinfo *afinfo)
2827 int err = 0;
2828 if (unlikely(afinfo == NULL))
2829 return -EINVAL;
2830 if (unlikely(afinfo->family >= NPROTO))
2831 return -EAFNOSUPPORT;
2832 spin_lock(&xfrm_policy_afinfo_lock);
2833 if (unlikely(xfrm_policy_afinfo[afinfo->family] != NULL))
2834 err = -EEXIST;
2835 else {
2836 struct dst_ops *dst_ops = afinfo->dst_ops;
2837 if (likely(dst_ops->kmem_cachep == NULL))
2838 dst_ops->kmem_cachep = xfrm_dst_cache;
2839 if (likely(dst_ops->check == NULL))
2840 dst_ops->check = xfrm_dst_check;
2841 if (likely(dst_ops->default_advmss == NULL))
2842 dst_ops->default_advmss = xfrm_default_advmss;
2843 if (likely(dst_ops->mtu == NULL))
2844 dst_ops->mtu = xfrm_mtu;
2845 if (likely(dst_ops->negative_advice == NULL))
2846 dst_ops->negative_advice = xfrm_negative_advice;
2847 if (likely(dst_ops->link_failure == NULL))
2848 dst_ops->link_failure = xfrm_link_failure;
2849 if (likely(dst_ops->neigh_lookup == NULL))
2850 dst_ops->neigh_lookup = xfrm_neigh_lookup;
2851 if (likely(afinfo->garbage_collect == NULL))
2852 afinfo->garbage_collect = xfrm_garbage_collect_deferred;
2853 rcu_assign_pointer(xfrm_policy_afinfo[afinfo->family], afinfo);
2855 spin_unlock(&xfrm_policy_afinfo_lock);
2857 return err;
2859 EXPORT_SYMBOL(xfrm_policy_register_afinfo);
2861 int xfrm_policy_unregister_afinfo(struct xfrm_policy_afinfo *afinfo)
2863 int err = 0;
2864 if (unlikely(afinfo == NULL))
2865 return -EINVAL;
2866 if (unlikely(afinfo->family >= NPROTO))
2867 return -EAFNOSUPPORT;
2868 spin_lock(&xfrm_policy_afinfo_lock);
2869 if (likely(xfrm_policy_afinfo[afinfo->family] != NULL)) {
2870 if (unlikely(xfrm_policy_afinfo[afinfo->family] != afinfo))
2871 err = -EINVAL;
2872 else
2873 RCU_INIT_POINTER(xfrm_policy_afinfo[afinfo->family],
2874 NULL);
2876 spin_unlock(&xfrm_policy_afinfo_lock);
2877 if (!err) {
2878 struct dst_ops *dst_ops = afinfo->dst_ops;
2880 synchronize_rcu();
2882 dst_ops->kmem_cachep = NULL;
2883 dst_ops->check = NULL;
2884 dst_ops->negative_advice = NULL;
2885 dst_ops->link_failure = NULL;
2886 afinfo->garbage_collect = NULL;
2888 return err;
2890 EXPORT_SYMBOL(xfrm_policy_unregister_afinfo);
2892 static int xfrm_dev_event(struct notifier_block *this, unsigned long event, void *ptr)
2894 struct net_device *dev = netdev_notifier_info_to_dev(ptr);
2896 switch (event) {
2897 case NETDEV_DOWN:
2898 xfrm_garbage_collect(dev_net(dev));
2900 return NOTIFY_DONE;
2903 static struct notifier_block xfrm_dev_notifier = {
2904 .notifier_call = xfrm_dev_event,
2907 #ifdef CONFIG_XFRM_STATISTICS
2908 static int __net_init xfrm_statistics_init(struct net *net)
2910 int rv;
2911 net->mib.xfrm_statistics = alloc_percpu(struct linux_xfrm_mib);
2912 if (!net->mib.xfrm_statistics)
2913 return -ENOMEM;
2914 rv = xfrm_proc_init(net);
2915 if (rv < 0)
2916 free_percpu(net->mib.xfrm_statistics);
2917 return rv;
2920 static void xfrm_statistics_fini(struct net *net)
2922 xfrm_proc_fini(net);
2923 free_percpu(net->mib.xfrm_statistics);
2925 #else
2926 static int __net_init xfrm_statistics_init(struct net *net)
2928 return 0;
2931 static void xfrm_statistics_fini(struct net *net)
2934 #endif
2936 static int __net_init xfrm_policy_init(struct net *net)
2938 unsigned int hmask, sz;
2939 int dir;
2941 if (net_eq(net, &init_net))
2942 xfrm_dst_cache = kmem_cache_create("xfrm_dst_cache",
2943 sizeof(struct xfrm_dst),
2944 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC,
2945 NULL);
2947 hmask = 8 - 1;
2948 sz = (hmask+1) * sizeof(struct hlist_head);
2950 net->xfrm.policy_byidx = xfrm_hash_alloc(sz);
2951 if (!net->xfrm.policy_byidx)
2952 goto out_byidx;
2953 net->xfrm.policy_idx_hmask = hmask;
2955 for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
2956 struct xfrm_policy_hash *htab;
2958 net->xfrm.policy_count[dir] = 0;
2959 net->xfrm.policy_count[XFRM_POLICY_MAX + dir] = 0;
2960 INIT_HLIST_HEAD(&net->xfrm.policy_inexact[dir]);
2962 htab = &net->xfrm.policy_bydst[dir];
2963 htab->table = xfrm_hash_alloc(sz);
2964 if (!htab->table)
2965 goto out_bydst;
2966 htab->hmask = hmask;
2967 htab->dbits4 = 32;
2968 htab->sbits4 = 32;
2969 htab->dbits6 = 128;
2970 htab->sbits6 = 128;
2972 net->xfrm.policy_hthresh.lbits4 = 32;
2973 net->xfrm.policy_hthresh.rbits4 = 32;
2974 net->xfrm.policy_hthresh.lbits6 = 128;
2975 net->xfrm.policy_hthresh.rbits6 = 128;
2977 seqlock_init(&net->xfrm.policy_hthresh.lock);
2979 INIT_LIST_HEAD(&net->xfrm.policy_all);
2980 INIT_WORK(&net->xfrm.policy_hash_work, xfrm_hash_resize);
2981 INIT_WORK(&net->xfrm.policy_hthresh.work, xfrm_hash_rebuild);
2982 if (net_eq(net, &init_net))
2983 register_netdevice_notifier(&xfrm_dev_notifier);
2984 return 0;
2986 out_bydst:
2987 for (dir--; dir >= 0; dir--) {
2988 struct xfrm_policy_hash *htab;
2990 htab = &net->xfrm.policy_bydst[dir];
2991 xfrm_hash_free(htab->table, sz);
2993 xfrm_hash_free(net->xfrm.policy_byidx, sz);
2994 out_byidx:
2995 return -ENOMEM;
2998 static void xfrm_policy_fini(struct net *net)
3000 unsigned int sz;
3001 int dir;
3003 flush_work(&net->xfrm.policy_hash_work);
3004 #ifdef CONFIG_XFRM_SUB_POLICY
3005 xfrm_policy_flush(net, XFRM_POLICY_TYPE_SUB, false);
3006 #endif
3007 xfrm_policy_flush(net, XFRM_POLICY_TYPE_MAIN, false);
3009 WARN_ON(!list_empty(&net->xfrm.policy_all));
3011 for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
3012 struct xfrm_policy_hash *htab;
3014 WARN_ON(!hlist_empty(&net->xfrm.policy_inexact[dir]));
3016 htab = &net->xfrm.policy_bydst[dir];
3017 sz = (htab->hmask + 1) * sizeof(struct hlist_head);
3018 WARN_ON(!hlist_empty(htab->table));
3019 xfrm_hash_free(htab->table, sz);
3022 sz = (net->xfrm.policy_idx_hmask + 1) * sizeof(struct hlist_head);
3023 WARN_ON(!hlist_empty(net->xfrm.policy_byidx));
3024 xfrm_hash_free(net->xfrm.policy_byidx, sz);
3027 static int __net_init xfrm_net_init(struct net *net)
3029 int rv;
3031 /* Initialize the per-net locks here */
3032 spin_lock_init(&net->xfrm.xfrm_state_lock);
3033 spin_lock_init(&net->xfrm.xfrm_policy_lock);
3034 mutex_init(&net->xfrm.xfrm_cfg_mutex);
3036 rv = xfrm_statistics_init(net);
3037 if (rv < 0)
3038 goto out_statistics;
3039 rv = xfrm_state_init(net);
3040 if (rv < 0)
3041 goto out_state;
3042 rv = xfrm_policy_init(net);
3043 if (rv < 0)
3044 goto out_policy;
3045 rv = xfrm_sysctl_init(net);
3046 if (rv < 0)
3047 goto out_sysctl;
3048 rv = flow_cache_init(net);
3049 if (rv < 0)
3050 goto out;
3052 return 0;
3054 out:
3055 xfrm_sysctl_fini(net);
3056 out_sysctl:
3057 xfrm_policy_fini(net);
3058 out_policy:
3059 xfrm_state_fini(net);
3060 out_state:
3061 xfrm_statistics_fini(net);
3062 out_statistics:
3063 return rv;
3066 static void __net_exit xfrm_net_exit(struct net *net)
3068 flow_cache_fini(net);
3069 xfrm_sysctl_fini(net);
3070 xfrm_policy_fini(net);
3071 xfrm_state_fini(net);
3072 xfrm_statistics_fini(net);
3075 static struct pernet_operations __net_initdata xfrm_net_ops = {
3076 .init = xfrm_net_init,
3077 .exit = xfrm_net_exit,
3080 void __init xfrm_init(void)
3082 register_pernet_subsys(&xfrm_net_ops);
3083 seqcount_init(&xfrm_policy_hash_generation);
3084 xfrm_input_init();
3087 #ifdef CONFIG_AUDITSYSCALL
3088 static void xfrm_audit_common_policyinfo(struct xfrm_policy *xp,
3089 struct audit_buffer *audit_buf)
3091 struct xfrm_sec_ctx *ctx = xp->security;
3092 struct xfrm_selector *sel = &xp->selector;
3094 if (ctx)
3095 audit_log_format(audit_buf, " sec_alg=%u sec_doi=%u sec_obj=%s",
3096 ctx->ctx_alg, ctx->ctx_doi, ctx->ctx_str);
3098 switch (sel->family) {
3099 case AF_INET:
3100 audit_log_format(audit_buf, " src=%pI4", &sel->saddr.a4);
3101 if (sel->prefixlen_s != 32)
3102 audit_log_format(audit_buf, " src_prefixlen=%d",
3103 sel->prefixlen_s);
3104 audit_log_format(audit_buf, " dst=%pI4", &sel->daddr.a4);
3105 if (sel->prefixlen_d != 32)
3106 audit_log_format(audit_buf, " dst_prefixlen=%d",
3107 sel->prefixlen_d);
3108 break;
3109 case AF_INET6:
3110 audit_log_format(audit_buf, " src=%pI6", sel->saddr.a6);
3111 if (sel->prefixlen_s != 128)
3112 audit_log_format(audit_buf, " src_prefixlen=%d",
3113 sel->prefixlen_s);
3114 audit_log_format(audit_buf, " dst=%pI6", sel->daddr.a6);
3115 if (sel->prefixlen_d != 128)
3116 audit_log_format(audit_buf, " dst_prefixlen=%d",
3117 sel->prefixlen_d);
3118 break;
3122 void xfrm_audit_policy_add(struct xfrm_policy *xp, int result, bool task_valid)
3124 struct audit_buffer *audit_buf;
3126 audit_buf = xfrm_audit_start("SPD-add");
3127 if (audit_buf == NULL)
3128 return;
3129 xfrm_audit_helper_usrinfo(task_valid, audit_buf);
3130 audit_log_format(audit_buf, " res=%u", result);
3131 xfrm_audit_common_policyinfo(xp, audit_buf);
3132 audit_log_end(audit_buf);
3134 EXPORT_SYMBOL_GPL(xfrm_audit_policy_add);
3136 void xfrm_audit_policy_delete(struct xfrm_policy *xp, int result,
3137 bool task_valid)
3139 struct audit_buffer *audit_buf;
3141 audit_buf = xfrm_audit_start("SPD-delete");
3142 if (audit_buf == NULL)
3143 return;
3144 xfrm_audit_helper_usrinfo(task_valid, audit_buf);
3145 audit_log_format(audit_buf, " res=%u", result);
3146 xfrm_audit_common_policyinfo(xp, audit_buf);
3147 audit_log_end(audit_buf);
3149 EXPORT_SYMBOL_GPL(xfrm_audit_policy_delete);
3150 #endif
3152 #ifdef CONFIG_XFRM_MIGRATE
3153 static bool xfrm_migrate_selector_match(const struct xfrm_selector *sel_cmp,
3154 const struct xfrm_selector *sel_tgt)
3156 if (sel_cmp->proto == IPSEC_ULPROTO_ANY) {
3157 if (sel_tgt->family == sel_cmp->family &&
3158 xfrm_addr_equal(&sel_tgt->daddr, &sel_cmp->daddr,
3159 sel_cmp->family) &&
3160 xfrm_addr_equal(&sel_tgt->saddr, &sel_cmp->saddr,
3161 sel_cmp->family) &&
3162 sel_tgt->prefixlen_d == sel_cmp->prefixlen_d &&
3163 sel_tgt->prefixlen_s == sel_cmp->prefixlen_s) {
3164 return true;
3166 } else {
3167 if (memcmp(sel_tgt, sel_cmp, sizeof(*sel_tgt)) == 0) {
3168 return true;
3171 return false;
3174 static struct xfrm_policy *xfrm_migrate_policy_find(const struct xfrm_selector *sel,
3175 u8 dir, u8 type, struct net *net)
3177 struct xfrm_policy *pol, *ret = NULL;
3178 struct hlist_head *chain;
3179 u32 priority = ~0U;
3181 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
3182 chain = policy_hash_direct(net, &sel->daddr, &sel->saddr, sel->family, dir);
3183 hlist_for_each_entry(pol, chain, bydst) {
3184 if (xfrm_migrate_selector_match(sel, &pol->selector) &&
3185 pol->type == type) {
3186 ret = pol;
3187 priority = ret->priority;
3188 break;
3191 chain = &net->xfrm.policy_inexact[dir];
3192 hlist_for_each_entry(pol, chain, bydst) {
3193 if ((pol->priority >= priority) && ret)
3194 break;
3196 if (xfrm_migrate_selector_match(sel, &pol->selector) &&
3197 pol->type == type) {
3198 ret = pol;
3199 break;
3203 xfrm_pol_hold(ret);
3205 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
3207 return ret;
3210 static int migrate_tmpl_match(const struct xfrm_migrate *m, const struct xfrm_tmpl *t)
3212 int match = 0;
3214 if (t->mode == m->mode && t->id.proto == m->proto &&
3215 (m->reqid == 0 || t->reqid == m->reqid)) {
3216 switch (t->mode) {
3217 case XFRM_MODE_TUNNEL:
3218 case XFRM_MODE_BEET:
3219 if (xfrm_addr_equal(&t->id.daddr, &m->old_daddr,
3220 m->old_family) &&
3221 xfrm_addr_equal(&t->saddr, &m->old_saddr,
3222 m->old_family)) {
3223 match = 1;
3225 break;
3226 case XFRM_MODE_TRANSPORT:
3227 /* in case of transport mode, template does not store
3228 any IP addresses, hence we just compare mode and
3229 protocol */
3230 match = 1;
3231 break;
3232 default:
3233 break;
3236 return match;
3239 /* update endpoint address(es) of template(s) */
3240 static int xfrm_policy_migrate(struct xfrm_policy *pol,
3241 struct xfrm_migrate *m, int num_migrate)
3243 struct xfrm_migrate *mp;
3244 int i, j, n = 0;
3246 write_lock_bh(&pol->lock);
3247 if (unlikely(pol->walk.dead)) {
3248 /* target policy has been deleted */
3249 write_unlock_bh(&pol->lock);
3250 return -ENOENT;
3253 for (i = 0; i < pol->xfrm_nr; i++) {
3254 for (j = 0, mp = m; j < num_migrate; j++, mp++) {
3255 if (!migrate_tmpl_match(mp, &pol->xfrm_vec[i]))
3256 continue;
3257 n++;
3258 if (pol->xfrm_vec[i].mode != XFRM_MODE_TUNNEL &&
3259 pol->xfrm_vec[i].mode != XFRM_MODE_BEET)
3260 continue;
3261 /* update endpoints */
3262 memcpy(&pol->xfrm_vec[i].id.daddr, &mp->new_daddr,
3263 sizeof(pol->xfrm_vec[i].id.daddr));
3264 memcpy(&pol->xfrm_vec[i].saddr, &mp->new_saddr,
3265 sizeof(pol->xfrm_vec[i].saddr));
3266 pol->xfrm_vec[i].encap_family = mp->new_family;
3267 /* flush bundles */
3268 atomic_inc(&pol->genid);
3272 write_unlock_bh(&pol->lock);
3274 if (!n)
3275 return -ENODATA;
3277 return 0;
3280 static int xfrm_migrate_check(const struct xfrm_migrate *m, int num_migrate)
3282 int i, j;
3284 if (num_migrate < 1 || num_migrate > XFRM_MAX_DEPTH)
3285 return -EINVAL;
3287 for (i = 0; i < num_migrate; i++) {
3288 if (xfrm_addr_equal(&m[i].old_daddr, &m[i].new_daddr,
3289 m[i].old_family) &&
3290 xfrm_addr_equal(&m[i].old_saddr, &m[i].new_saddr,
3291 m[i].old_family))
3292 return -EINVAL;
3293 if (xfrm_addr_any(&m[i].new_daddr, m[i].new_family) ||
3294 xfrm_addr_any(&m[i].new_saddr, m[i].new_family))
3295 return -EINVAL;
3297 /* check if there is any duplicated entry */
3298 for (j = i + 1; j < num_migrate; j++) {
3299 if (!memcmp(&m[i].old_daddr, &m[j].old_daddr,
3300 sizeof(m[i].old_daddr)) &&
3301 !memcmp(&m[i].old_saddr, &m[j].old_saddr,
3302 sizeof(m[i].old_saddr)) &&
3303 m[i].proto == m[j].proto &&
3304 m[i].mode == m[j].mode &&
3305 m[i].reqid == m[j].reqid &&
3306 m[i].old_family == m[j].old_family)
3307 return -EINVAL;
3311 return 0;
3314 int xfrm_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
3315 struct xfrm_migrate *m, int num_migrate,
3316 struct xfrm_kmaddress *k, struct net *net)
3318 int i, err, nx_cur = 0, nx_new = 0;
3319 struct xfrm_policy *pol = NULL;
3320 struct xfrm_state *x, *xc;
3321 struct xfrm_state *x_cur[XFRM_MAX_DEPTH];
3322 struct xfrm_state *x_new[XFRM_MAX_DEPTH];
3323 struct xfrm_migrate *mp;
3325 /* Stage 0 - sanity checks */
3326 if ((err = xfrm_migrate_check(m, num_migrate)) < 0)
3327 goto out;
3329 if (dir >= XFRM_POLICY_MAX) {
3330 err = -EINVAL;
3331 goto out;
3334 /* Stage 1 - find policy */
3335 if ((pol = xfrm_migrate_policy_find(sel, dir, type, net)) == NULL) {
3336 err = -ENOENT;
3337 goto out;
3340 /* Stage 2 - find and update state(s) */
3341 for (i = 0, mp = m; i < num_migrate; i++, mp++) {
3342 if ((x = xfrm_migrate_state_find(mp, net))) {
3343 x_cur[nx_cur] = x;
3344 nx_cur++;
3345 if ((xc = xfrm_state_migrate(x, mp))) {
3346 x_new[nx_new] = xc;
3347 nx_new++;
3348 } else {
3349 err = -ENODATA;
3350 goto restore_state;
3355 /* Stage 3 - update policy */
3356 if ((err = xfrm_policy_migrate(pol, m, num_migrate)) < 0)
3357 goto restore_state;
3359 /* Stage 4 - delete old state(s) */
3360 if (nx_cur) {
3361 xfrm_states_put(x_cur, nx_cur);
3362 xfrm_states_delete(x_cur, nx_cur);
3365 /* Stage 5 - announce */
3366 km_migrate(sel, dir, type, m, num_migrate, k);
3368 xfrm_pol_put(pol);
3370 return 0;
3371 out:
3372 return err;
3374 restore_state:
3375 if (pol)
3376 xfrm_pol_put(pol);
3377 if (nx_cur)
3378 xfrm_states_put(x_cur, nx_cur);
3379 if (nx_new)
3380 xfrm_states_delete(x_new, nx_new);
3382 return err;
3384 EXPORT_SYMBOL(xfrm_migrate);
3385 #endif