xref: /openbmc/linux/net/xfrm/xfrm_policy.c (revision 26b8f996)
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 <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
35 
36 #include "xfrm_hash.h"
37 
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
41 
42 struct xfrm_flo {
43 	struct dst_entry *dst_orig;
44 	u8 flags;
45 };
46 
47 static DEFINE_SPINLOCK(xfrm_policy_afinfo_lock);
48 static struct xfrm_policy_afinfo __rcu *xfrm_policy_afinfo[NPROTO]
49 						__read_mostly;
50 
51 static struct kmem_cache *xfrm_dst_cache __read_mostly;
52 
53 static void xfrm_init_pmtu(struct dst_entry *dst);
54 static int stale_bundle(struct dst_entry *dst);
55 static int xfrm_bundle_ok(struct xfrm_dst *xdst);
56 static void xfrm_policy_queue_process(unsigned long arg);
57 
58 static void __xfrm_policy_link(struct xfrm_policy *pol, int dir);
59 static struct xfrm_policy *__xfrm_policy_unlink(struct xfrm_policy *pol,
60 						int dir);
61 
62 static inline bool
63 __xfrm4_selector_match(const struct xfrm_selector *sel, const struct flowi *fl)
64 {
65 	const struct flowi4 *fl4 = &fl->u.ip4;
66 
67 	return  addr4_match(fl4->daddr, sel->daddr.a4, sel->prefixlen_d) &&
68 		addr4_match(fl4->saddr, sel->saddr.a4, sel->prefixlen_s) &&
69 		!((xfrm_flowi_dport(fl, &fl4->uli) ^ sel->dport) & sel->dport_mask) &&
70 		!((xfrm_flowi_sport(fl, &fl4->uli) ^ sel->sport) & sel->sport_mask) &&
71 		(fl4->flowi4_proto == sel->proto || !sel->proto) &&
72 		(fl4->flowi4_oif == sel->ifindex || !sel->ifindex);
73 }
74 
75 static inline bool
76 __xfrm6_selector_match(const struct xfrm_selector *sel, const struct flowi *fl)
77 {
78 	const struct flowi6 *fl6 = &fl->u.ip6;
79 
80 	return  addr_match(&fl6->daddr, &sel->daddr, sel->prefixlen_d) &&
81 		addr_match(&fl6->saddr, &sel->saddr, sel->prefixlen_s) &&
82 		!((xfrm_flowi_dport(fl, &fl6->uli) ^ sel->dport) & sel->dport_mask) &&
83 		!((xfrm_flowi_sport(fl, &fl6->uli) ^ sel->sport) & sel->sport_mask) &&
84 		(fl6->flowi6_proto == sel->proto || !sel->proto) &&
85 		(fl6->flowi6_oif == sel->ifindex || !sel->ifindex);
86 }
87 
88 bool xfrm_selector_match(const struct xfrm_selector *sel, const struct flowi *fl,
89 			 unsigned short family)
90 {
91 	switch (family) {
92 	case AF_INET:
93 		return __xfrm4_selector_match(sel, fl);
94 	case AF_INET6:
95 		return __xfrm6_selector_match(sel, fl);
96 	}
97 	return false;
98 }
99 
100 static struct xfrm_policy_afinfo *xfrm_policy_get_afinfo(unsigned short family)
101 {
102 	struct xfrm_policy_afinfo *afinfo;
103 
104 	if (unlikely(family >= NPROTO))
105 		return NULL;
106 	rcu_read_lock();
107 	afinfo = rcu_dereference(xfrm_policy_afinfo[family]);
108 	if (unlikely(!afinfo))
109 		rcu_read_unlock();
110 	return afinfo;
111 }
112 
113 static void xfrm_policy_put_afinfo(struct xfrm_policy_afinfo *afinfo)
114 {
115 	rcu_read_unlock();
116 }
117 
118 static inline struct dst_entry *__xfrm_dst_lookup(struct net *net,
119 						  int tos, int oif,
120 						  const xfrm_address_t *saddr,
121 						  const xfrm_address_t *daddr,
122 						  int family)
123 {
124 	struct xfrm_policy_afinfo *afinfo;
125 	struct dst_entry *dst;
126 
127 	afinfo = xfrm_policy_get_afinfo(family);
128 	if (unlikely(afinfo == NULL))
129 		return ERR_PTR(-EAFNOSUPPORT);
130 
131 	dst = afinfo->dst_lookup(net, tos, oif, saddr, daddr);
132 
133 	xfrm_policy_put_afinfo(afinfo);
134 
135 	return dst;
136 }
137 
138 static inline struct dst_entry *xfrm_dst_lookup(struct xfrm_state *x,
139 						int tos, int oif,
140 						xfrm_address_t *prev_saddr,
141 						xfrm_address_t *prev_daddr,
142 						int family)
143 {
144 	struct net *net = xs_net(x);
145 	xfrm_address_t *saddr = &x->props.saddr;
146 	xfrm_address_t *daddr = &x->id.daddr;
147 	struct dst_entry *dst;
148 
149 	if (x->type->flags & XFRM_TYPE_LOCAL_COADDR) {
150 		saddr = x->coaddr;
151 		daddr = prev_daddr;
152 	}
153 	if (x->type->flags & XFRM_TYPE_REMOTE_COADDR) {
154 		saddr = prev_saddr;
155 		daddr = x->coaddr;
156 	}
157 
158 	dst = __xfrm_dst_lookup(net, tos, oif, saddr, daddr, family);
159 
160 	if (!IS_ERR(dst)) {
161 		if (prev_saddr != saddr)
162 			memcpy(prev_saddr, saddr,  sizeof(*prev_saddr));
163 		if (prev_daddr != daddr)
164 			memcpy(prev_daddr, daddr,  sizeof(*prev_daddr));
165 	}
166 
167 	return dst;
168 }
169 
170 static inline unsigned long make_jiffies(long secs)
171 {
172 	if (secs >= (MAX_SCHEDULE_TIMEOUT-1)/HZ)
173 		return MAX_SCHEDULE_TIMEOUT-1;
174 	else
175 		return secs*HZ;
176 }
177 
178 static void xfrm_policy_timer(unsigned long data)
179 {
180 	struct xfrm_policy *xp = (struct xfrm_policy *)data;
181 	unsigned long now = get_seconds();
182 	long next = LONG_MAX;
183 	int warn = 0;
184 	int dir;
185 
186 	read_lock(&xp->lock);
187 
188 	if (unlikely(xp->walk.dead))
189 		goto out;
190 
191 	dir = xfrm_policy_id2dir(xp->index);
192 
193 	if (xp->lft.hard_add_expires_seconds) {
194 		long tmo = xp->lft.hard_add_expires_seconds +
195 			xp->curlft.add_time - now;
196 		if (tmo <= 0)
197 			goto expired;
198 		if (tmo < next)
199 			next = tmo;
200 	}
201 	if (xp->lft.hard_use_expires_seconds) {
202 		long tmo = xp->lft.hard_use_expires_seconds +
203 			(xp->curlft.use_time ? : xp->curlft.add_time) - now;
204 		if (tmo <= 0)
205 			goto expired;
206 		if (tmo < next)
207 			next = tmo;
208 	}
209 	if (xp->lft.soft_add_expires_seconds) {
210 		long tmo = xp->lft.soft_add_expires_seconds +
211 			xp->curlft.add_time - now;
212 		if (tmo <= 0) {
213 			warn = 1;
214 			tmo = XFRM_KM_TIMEOUT;
215 		}
216 		if (tmo < next)
217 			next = tmo;
218 	}
219 	if (xp->lft.soft_use_expires_seconds) {
220 		long tmo = xp->lft.soft_use_expires_seconds +
221 			(xp->curlft.use_time ? : xp->curlft.add_time) - now;
222 		if (tmo <= 0) {
223 			warn = 1;
224 			tmo = XFRM_KM_TIMEOUT;
225 		}
226 		if (tmo < next)
227 			next = tmo;
228 	}
229 
230 	if (warn)
231 		km_policy_expired(xp, dir, 0, 0);
232 	if (next != LONG_MAX &&
233 	    !mod_timer(&xp->timer, jiffies + make_jiffies(next)))
234 		xfrm_pol_hold(xp);
235 
236 out:
237 	read_unlock(&xp->lock);
238 	xfrm_pol_put(xp);
239 	return;
240 
241 expired:
242 	read_unlock(&xp->lock);
243 	if (!xfrm_policy_delete(xp, dir))
244 		km_policy_expired(xp, dir, 1, 0);
245 	xfrm_pol_put(xp);
246 }
247 
248 static struct flow_cache_object *xfrm_policy_flo_get(struct flow_cache_object *flo)
249 {
250 	struct xfrm_policy *pol = container_of(flo, struct xfrm_policy, flo);
251 
252 	if (unlikely(pol->walk.dead))
253 		flo = NULL;
254 	else
255 		xfrm_pol_hold(pol);
256 
257 	return flo;
258 }
259 
260 static int xfrm_policy_flo_check(struct flow_cache_object *flo)
261 {
262 	struct xfrm_policy *pol = container_of(flo, struct xfrm_policy, flo);
263 
264 	return !pol->walk.dead;
265 }
266 
267 static void xfrm_policy_flo_delete(struct flow_cache_object *flo)
268 {
269 	xfrm_pol_put(container_of(flo, struct xfrm_policy, flo));
270 }
271 
272 static const struct flow_cache_ops xfrm_policy_fc_ops = {
273 	.get = xfrm_policy_flo_get,
274 	.check = xfrm_policy_flo_check,
275 	.delete = xfrm_policy_flo_delete,
276 };
277 
278 /* Allocate xfrm_policy. Not used here, it is supposed to be used by pfkeyv2
279  * SPD calls.
280  */
281 
282 struct xfrm_policy *xfrm_policy_alloc(struct net *net, gfp_t gfp)
283 {
284 	struct xfrm_policy *policy;
285 
286 	policy = kzalloc(sizeof(struct xfrm_policy), gfp);
287 
288 	if (policy) {
289 		write_pnet(&policy->xp_net, net);
290 		INIT_LIST_HEAD(&policy->walk.all);
291 		INIT_HLIST_NODE(&policy->bydst);
292 		INIT_HLIST_NODE(&policy->byidx);
293 		rwlock_init(&policy->lock);
294 		atomic_set(&policy->refcnt, 1);
295 		skb_queue_head_init(&policy->polq.hold_queue);
296 		setup_timer(&policy->timer, xfrm_policy_timer,
297 				(unsigned long)policy);
298 		setup_timer(&policy->polq.hold_timer, xfrm_policy_queue_process,
299 			    (unsigned long)policy);
300 		policy->flo.ops = &xfrm_policy_fc_ops;
301 	}
302 	return policy;
303 }
304 EXPORT_SYMBOL(xfrm_policy_alloc);
305 
306 /* Destroy xfrm_policy: descendant resources must be released to this moment. */
307 
308 void xfrm_policy_destroy(struct xfrm_policy *policy)
309 {
310 	BUG_ON(!policy->walk.dead);
311 
312 	if (del_timer(&policy->timer) || del_timer(&policy->polq.hold_timer))
313 		BUG();
314 
315 	security_xfrm_policy_free(policy->security);
316 	kfree(policy);
317 }
318 EXPORT_SYMBOL(xfrm_policy_destroy);
319 
320 /* Rule must be locked. Release descentant resources, announce
321  * entry dead. The rule must be unlinked from lists to the moment.
322  */
323 
324 static void xfrm_policy_kill(struct xfrm_policy *policy)
325 {
326 	policy->walk.dead = 1;
327 
328 	atomic_inc(&policy->genid);
329 
330 	if (del_timer(&policy->polq.hold_timer))
331 		xfrm_pol_put(policy);
332 	skb_queue_purge(&policy->polq.hold_queue);
333 
334 	if (del_timer(&policy->timer))
335 		xfrm_pol_put(policy);
336 
337 	xfrm_pol_put(policy);
338 }
339 
340 static unsigned int xfrm_policy_hashmax __read_mostly = 1 * 1024 * 1024;
341 
342 static inline unsigned int idx_hash(struct net *net, u32 index)
343 {
344 	return __idx_hash(index, net->xfrm.policy_idx_hmask);
345 }
346 
347 /* calculate policy hash thresholds */
348 static void __get_hash_thresh(struct net *net,
349 			      unsigned short family, int dir,
350 			      u8 *dbits, u8 *sbits)
351 {
352 	switch (family) {
353 	case AF_INET:
354 		*dbits = net->xfrm.policy_bydst[dir].dbits4;
355 		*sbits = net->xfrm.policy_bydst[dir].sbits4;
356 		break;
357 
358 	case AF_INET6:
359 		*dbits = net->xfrm.policy_bydst[dir].dbits6;
360 		*sbits = net->xfrm.policy_bydst[dir].sbits6;
361 		break;
362 
363 	default:
364 		*dbits = 0;
365 		*sbits = 0;
366 	}
367 }
368 
369 static struct hlist_head *policy_hash_bysel(struct net *net,
370 					    const struct xfrm_selector *sel,
371 					    unsigned short family, int dir)
372 {
373 	unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
374 	unsigned int hash;
375 	u8 dbits;
376 	u8 sbits;
377 
378 	__get_hash_thresh(net, family, dir, &dbits, &sbits);
379 	hash = __sel_hash(sel, family, hmask, dbits, sbits);
380 
381 	return (hash == hmask + 1 ?
382 		&net->xfrm.policy_inexact[dir] :
383 		net->xfrm.policy_bydst[dir].table + hash);
384 }
385 
386 static struct hlist_head *policy_hash_direct(struct net *net,
387 					     const xfrm_address_t *daddr,
388 					     const xfrm_address_t *saddr,
389 					     unsigned short family, int dir)
390 {
391 	unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
392 	unsigned int hash;
393 	u8 dbits;
394 	u8 sbits;
395 
396 	__get_hash_thresh(net, family, dir, &dbits, &sbits);
397 	hash = __addr_hash(daddr, saddr, family, hmask, dbits, sbits);
398 
399 	return net->xfrm.policy_bydst[dir].table + hash;
400 }
401 
402 static void xfrm_dst_hash_transfer(struct net *net,
403 				   struct hlist_head *list,
404 				   struct hlist_head *ndsttable,
405 				   unsigned int nhashmask,
406 				   int dir)
407 {
408 	struct hlist_node *tmp, *entry0 = NULL;
409 	struct xfrm_policy *pol;
410 	unsigned int h0 = 0;
411 	u8 dbits;
412 	u8 sbits;
413 
414 redo:
415 	hlist_for_each_entry_safe(pol, tmp, list, bydst) {
416 		unsigned int h;
417 
418 		__get_hash_thresh(net, pol->family, dir, &dbits, &sbits);
419 		h = __addr_hash(&pol->selector.daddr, &pol->selector.saddr,
420 				pol->family, nhashmask, dbits, sbits);
421 		if (!entry0) {
422 			hlist_del(&pol->bydst);
423 			hlist_add_head(&pol->bydst, ndsttable+h);
424 			h0 = h;
425 		} else {
426 			if (h != h0)
427 				continue;
428 			hlist_del(&pol->bydst);
429 			hlist_add_behind(&pol->bydst, entry0);
430 		}
431 		entry0 = &pol->bydst;
432 	}
433 	if (!hlist_empty(list)) {
434 		entry0 = NULL;
435 		goto redo;
436 	}
437 }
438 
439 static void xfrm_idx_hash_transfer(struct hlist_head *list,
440 				   struct hlist_head *nidxtable,
441 				   unsigned int nhashmask)
442 {
443 	struct hlist_node *tmp;
444 	struct xfrm_policy *pol;
445 
446 	hlist_for_each_entry_safe(pol, tmp, list, byidx) {
447 		unsigned int h;
448 
449 		h = __idx_hash(pol->index, nhashmask);
450 		hlist_add_head(&pol->byidx, nidxtable+h);
451 	}
452 }
453 
454 static unsigned long xfrm_new_hash_mask(unsigned int old_hmask)
455 {
456 	return ((old_hmask + 1) << 1) - 1;
457 }
458 
459 static void xfrm_bydst_resize(struct net *net, int dir)
460 {
461 	unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
462 	unsigned int nhashmask = xfrm_new_hash_mask(hmask);
463 	unsigned int nsize = (nhashmask + 1) * sizeof(struct hlist_head);
464 	struct hlist_head *odst = net->xfrm.policy_bydst[dir].table;
465 	struct hlist_head *ndst = xfrm_hash_alloc(nsize);
466 	int i;
467 
468 	if (!ndst)
469 		return;
470 
471 	write_lock_bh(&net->xfrm.xfrm_policy_lock);
472 
473 	for (i = hmask; i >= 0; i--)
474 		xfrm_dst_hash_transfer(net, odst + i, ndst, nhashmask, dir);
475 
476 	net->xfrm.policy_bydst[dir].table = ndst;
477 	net->xfrm.policy_bydst[dir].hmask = nhashmask;
478 
479 	write_unlock_bh(&net->xfrm.xfrm_policy_lock);
480 
481 	xfrm_hash_free(odst, (hmask + 1) * sizeof(struct hlist_head));
482 }
483 
484 static void xfrm_byidx_resize(struct net *net, int total)
485 {
486 	unsigned int hmask = net->xfrm.policy_idx_hmask;
487 	unsigned int nhashmask = xfrm_new_hash_mask(hmask);
488 	unsigned int nsize = (nhashmask + 1) * sizeof(struct hlist_head);
489 	struct hlist_head *oidx = net->xfrm.policy_byidx;
490 	struct hlist_head *nidx = xfrm_hash_alloc(nsize);
491 	int i;
492 
493 	if (!nidx)
494 		return;
495 
496 	write_lock_bh(&net->xfrm.xfrm_policy_lock);
497 
498 	for (i = hmask; i >= 0; i--)
499 		xfrm_idx_hash_transfer(oidx + i, nidx, nhashmask);
500 
501 	net->xfrm.policy_byidx = nidx;
502 	net->xfrm.policy_idx_hmask = nhashmask;
503 
504 	write_unlock_bh(&net->xfrm.xfrm_policy_lock);
505 
506 	xfrm_hash_free(oidx, (hmask + 1) * sizeof(struct hlist_head));
507 }
508 
509 static inline int xfrm_bydst_should_resize(struct net *net, int dir, int *total)
510 {
511 	unsigned int cnt = net->xfrm.policy_count[dir];
512 	unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
513 
514 	if (total)
515 		*total += cnt;
516 
517 	if ((hmask + 1) < xfrm_policy_hashmax &&
518 	    cnt > hmask)
519 		return 1;
520 
521 	return 0;
522 }
523 
524 static inline int xfrm_byidx_should_resize(struct net *net, int total)
525 {
526 	unsigned int hmask = net->xfrm.policy_idx_hmask;
527 
528 	if ((hmask + 1) < xfrm_policy_hashmax &&
529 	    total > hmask)
530 		return 1;
531 
532 	return 0;
533 }
534 
535 void xfrm_spd_getinfo(struct net *net, struct xfrmk_spdinfo *si)
536 {
537 	read_lock_bh(&net->xfrm.xfrm_policy_lock);
538 	si->incnt = net->xfrm.policy_count[XFRM_POLICY_IN];
539 	si->outcnt = net->xfrm.policy_count[XFRM_POLICY_OUT];
540 	si->fwdcnt = net->xfrm.policy_count[XFRM_POLICY_FWD];
541 	si->inscnt = net->xfrm.policy_count[XFRM_POLICY_IN+XFRM_POLICY_MAX];
542 	si->outscnt = net->xfrm.policy_count[XFRM_POLICY_OUT+XFRM_POLICY_MAX];
543 	si->fwdscnt = net->xfrm.policy_count[XFRM_POLICY_FWD+XFRM_POLICY_MAX];
544 	si->spdhcnt = net->xfrm.policy_idx_hmask;
545 	si->spdhmcnt = xfrm_policy_hashmax;
546 	read_unlock_bh(&net->xfrm.xfrm_policy_lock);
547 }
548 EXPORT_SYMBOL(xfrm_spd_getinfo);
549 
550 static DEFINE_MUTEX(hash_resize_mutex);
551 static void xfrm_hash_resize(struct work_struct *work)
552 {
553 	struct net *net = container_of(work, struct net, xfrm.policy_hash_work);
554 	int dir, total;
555 
556 	mutex_lock(&hash_resize_mutex);
557 
558 	total = 0;
559 	for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
560 		if (xfrm_bydst_should_resize(net, dir, &total))
561 			xfrm_bydst_resize(net, dir);
562 	}
563 	if (xfrm_byidx_should_resize(net, total))
564 		xfrm_byidx_resize(net, total);
565 
566 	mutex_unlock(&hash_resize_mutex);
567 }
568 
569 static void xfrm_hash_rebuild(struct work_struct *work)
570 {
571 	struct net *net = container_of(work, struct net,
572 				       xfrm.policy_hthresh.work);
573 	unsigned int hmask;
574 	struct xfrm_policy *pol;
575 	struct xfrm_policy *policy;
576 	struct hlist_head *chain;
577 	struct hlist_head *odst;
578 	struct hlist_node *newpos;
579 	int i;
580 	int dir;
581 	unsigned seq;
582 	u8 lbits4, rbits4, lbits6, rbits6;
583 
584 	mutex_lock(&hash_resize_mutex);
585 
586 	/* read selector prefixlen thresholds */
587 	do {
588 		seq = read_seqbegin(&net->xfrm.policy_hthresh.lock);
589 
590 		lbits4 = net->xfrm.policy_hthresh.lbits4;
591 		rbits4 = net->xfrm.policy_hthresh.rbits4;
592 		lbits6 = net->xfrm.policy_hthresh.lbits6;
593 		rbits6 = net->xfrm.policy_hthresh.rbits6;
594 	} while (read_seqretry(&net->xfrm.policy_hthresh.lock, seq));
595 
596 	write_lock_bh(&net->xfrm.xfrm_policy_lock);
597 
598 	/* reset the bydst and inexact table in all directions */
599 	for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
600 		INIT_HLIST_HEAD(&net->xfrm.policy_inexact[dir]);
601 		hmask = net->xfrm.policy_bydst[dir].hmask;
602 		odst = net->xfrm.policy_bydst[dir].table;
603 		for (i = hmask; i >= 0; i--)
604 			INIT_HLIST_HEAD(odst + i);
605 		if ((dir & XFRM_POLICY_MASK) == XFRM_POLICY_OUT) {
606 			/* dir out => dst = remote, src = local */
607 			net->xfrm.policy_bydst[dir].dbits4 = rbits4;
608 			net->xfrm.policy_bydst[dir].sbits4 = lbits4;
609 			net->xfrm.policy_bydst[dir].dbits6 = rbits6;
610 			net->xfrm.policy_bydst[dir].sbits6 = lbits6;
611 		} else {
612 			/* dir in/fwd => dst = local, src = remote */
613 			net->xfrm.policy_bydst[dir].dbits4 = lbits4;
614 			net->xfrm.policy_bydst[dir].sbits4 = rbits4;
615 			net->xfrm.policy_bydst[dir].dbits6 = lbits6;
616 			net->xfrm.policy_bydst[dir].sbits6 = rbits6;
617 		}
618 	}
619 
620 	/* re-insert all policies by order of creation */
621 	list_for_each_entry_reverse(policy, &net->xfrm.policy_all, walk.all) {
622 		newpos = NULL;
623 		chain = policy_hash_bysel(net, &policy->selector,
624 					  policy->family,
625 					  xfrm_policy_id2dir(policy->index));
626 		hlist_for_each_entry(pol, chain, bydst) {
627 			if (policy->priority >= pol->priority)
628 				newpos = &pol->bydst;
629 			else
630 				break;
631 		}
632 		if (newpos)
633 			hlist_add_behind(&policy->bydst, newpos);
634 		else
635 			hlist_add_head(&policy->bydst, chain);
636 	}
637 
638 	write_unlock_bh(&net->xfrm.xfrm_policy_lock);
639 
640 	mutex_unlock(&hash_resize_mutex);
641 }
642 
643 void xfrm_policy_hash_rebuild(struct net *net)
644 {
645 	schedule_work(&net->xfrm.policy_hthresh.work);
646 }
647 EXPORT_SYMBOL(xfrm_policy_hash_rebuild);
648 
649 /* Generate new index... KAME seems to generate them ordered by cost
650  * of an absolute inpredictability of ordering of rules. This will not pass. */
651 static u32 xfrm_gen_index(struct net *net, int dir, u32 index)
652 {
653 	static u32 idx_generator;
654 
655 	for (;;) {
656 		struct hlist_head *list;
657 		struct xfrm_policy *p;
658 		u32 idx;
659 		int found;
660 
661 		if (!index) {
662 			idx = (idx_generator | dir);
663 			idx_generator += 8;
664 		} else {
665 			idx = index;
666 			index = 0;
667 		}
668 
669 		if (idx == 0)
670 			idx = 8;
671 		list = net->xfrm.policy_byidx + idx_hash(net, idx);
672 		found = 0;
673 		hlist_for_each_entry(p, list, byidx) {
674 			if (p->index == idx) {
675 				found = 1;
676 				break;
677 			}
678 		}
679 		if (!found)
680 			return idx;
681 	}
682 }
683 
684 static inline int selector_cmp(struct xfrm_selector *s1, struct xfrm_selector *s2)
685 {
686 	u32 *p1 = (u32 *) s1;
687 	u32 *p2 = (u32 *) s2;
688 	int len = sizeof(struct xfrm_selector) / sizeof(u32);
689 	int i;
690 
691 	for (i = 0; i < len; i++) {
692 		if (p1[i] != p2[i])
693 			return 1;
694 	}
695 
696 	return 0;
697 }
698 
699 static void xfrm_policy_requeue(struct xfrm_policy *old,
700 				struct xfrm_policy *new)
701 {
702 	struct xfrm_policy_queue *pq = &old->polq;
703 	struct sk_buff_head list;
704 
705 	if (skb_queue_empty(&pq->hold_queue))
706 		return;
707 
708 	__skb_queue_head_init(&list);
709 
710 	spin_lock_bh(&pq->hold_queue.lock);
711 	skb_queue_splice_init(&pq->hold_queue, &list);
712 	if (del_timer(&pq->hold_timer))
713 		xfrm_pol_put(old);
714 	spin_unlock_bh(&pq->hold_queue.lock);
715 
716 	pq = &new->polq;
717 
718 	spin_lock_bh(&pq->hold_queue.lock);
719 	skb_queue_splice(&list, &pq->hold_queue);
720 	pq->timeout = XFRM_QUEUE_TMO_MIN;
721 	if (!mod_timer(&pq->hold_timer, jiffies))
722 		xfrm_pol_hold(new);
723 	spin_unlock_bh(&pq->hold_queue.lock);
724 }
725 
726 static bool xfrm_policy_mark_match(struct xfrm_policy *policy,
727 				   struct xfrm_policy *pol)
728 {
729 	u32 mark = policy->mark.v & policy->mark.m;
730 
731 	if (policy->mark.v == pol->mark.v && policy->mark.m == pol->mark.m)
732 		return true;
733 
734 	if ((mark & pol->mark.m) == pol->mark.v &&
735 	    policy->priority == pol->priority)
736 		return true;
737 
738 	return false;
739 }
740 
741 int xfrm_policy_insert(int dir, struct xfrm_policy *policy, int excl)
742 {
743 	struct net *net = xp_net(policy);
744 	struct xfrm_policy *pol;
745 	struct xfrm_policy *delpol;
746 	struct hlist_head *chain;
747 	struct hlist_node *newpos;
748 
749 	write_lock_bh(&net->xfrm.xfrm_policy_lock);
750 	chain = policy_hash_bysel(net, &policy->selector, policy->family, dir);
751 	delpol = NULL;
752 	newpos = NULL;
753 	hlist_for_each_entry(pol, chain, bydst) {
754 		if (pol->type == policy->type &&
755 		    !selector_cmp(&pol->selector, &policy->selector) &&
756 		    xfrm_policy_mark_match(policy, pol) &&
757 		    xfrm_sec_ctx_match(pol->security, policy->security) &&
758 		    !WARN_ON(delpol)) {
759 			if (excl) {
760 				write_unlock_bh(&net->xfrm.xfrm_policy_lock);
761 				return -EEXIST;
762 			}
763 			delpol = pol;
764 			if (policy->priority > pol->priority)
765 				continue;
766 		} else if (policy->priority >= pol->priority) {
767 			newpos = &pol->bydst;
768 			continue;
769 		}
770 		if (delpol)
771 			break;
772 	}
773 	if (newpos)
774 		hlist_add_behind(&policy->bydst, newpos);
775 	else
776 		hlist_add_head(&policy->bydst, chain);
777 	__xfrm_policy_link(policy, dir);
778 	atomic_inc(&net->xfrm.flow_cache_genid);
779 
780 	/* After previous checking, family can either be AF_INET or AF_INET6 */
781 	if (policy->family == AF_INET)
782 		rt_genid_bump_ipv4(net);
783 	else
784 		rt_genid_bump_ipv6(net);
785 
786 	if (delpol) {
787 		xfrm_policy_requeue(delpol, policy);
788 		__xfrm_policy_unlink(delpol, dir);
789 	}
790 	policy->index = delpol ? delpol->index : xfrm_gen_index(net, dir, policy->index);
791 	hlist_add_head(&policy->byidx, net->xfrm.policy_byidx+idx_hash(net, policy->index));
792 	policy->curlft.add_time = get_seconds();
793 	policy->curlft.use_time = 0;
794 	if (!mod_timer(&policy->timer, jiffies + HZ))
795 		xfrm_pol_hold(policy);
796 	write_unlock_bh(&net->xfrm.xfrm_policy_lock);
797 
798 	if (delpol)
799 		xfrm_policy_kill(delpol);
800 	else if (xfrm_bydst_should_resize(net, dir, NULL))
801 		schedule_work(&net->xfrm.policy_hash_work);
802 
803 	return 0;
804 }
805 EXPORT_SYMBOL(xfrm_policy_insert);
806 
807 struct xfrm_policy *xfrm_policy_bysel_ctx(struct net *net, u32 mark, u8 type,
808 					  int dir, struct xfrm_selector *sel,
809 					  struct xfrm_sec_ctx *ctx, int delete,
810 					  int *err)
811 {
812 	struct xfrm_policy *pol, *ret;
813 	struct hlist_head *chain;
814 
815 	*err = 0;
816 	write_lock_bh(&net->xfrm.xfrm_policy_lock);
817 	chain = policy_hash_bysel(net, sel, sel->family, dir);
818 	ret = NULL;
819 	hlist_for_each_entry(pol, chain, bydst) {
820 		if (pol->type == type &&
821 		    (mark & pol->mark.m) == pol->mark.v &&
822 		    !selector_cmp(sel, &pol->selector) &&
823 		    xfrm_sec_ctx_match(ctx, pol->security)) {
824 			xfrm_pol_hold(pol);
825 			if (delete) {
826 				*err = security_xfrm_policy_delete(
827 								pol->security);
828 				if (*err) {
829 					write_unlock_bh(&net->xfrm.xfrm_policy_lock);
830 					return pol;
831 				}
832 				__xfrm_policy_unlink(pol, dir);
833 			}
834 			ret = pol;
835 			break;
836 		}
837 	}
838 	write_unlock_bh(&net->xfrm.xfrm_policy_lock);
839 
840 	if (ret && delete)
841 		xfrm_policy_kill(ret);
842 	return ret;
843 }
844 EXPORT_SYMBOL(xfrm_policy_bysel_ctx);
845 
846 struct xfrm_policy *xfrm_policy_byid(struct net *net, u32 mark, u8 type,
847 				     int dir, u32 id, int delete, int *err)
848 {
849 	struct xfrm_policy *pol, *ret;
850 	struct hlist_head *chain;
851 
852 	*err = -ENOENT;
853 	if (xfrm_policy_id2dir(id) != dir)
854 		return NULL;
855 
856 	*err = 0;
857 	write_lock_bh(&net->xfrm.xfrm_policy_lock);
858 	chain = net->xfrm.policy_byidx + idx_hash(net, id);
859 	ret = NULL;
860 	hlist_for_each_entry(pol, chain, byidx) {
861 		if (pol->type == type && pol->index == id &&
862 		    (mark & pol->mark.m) == pol->mark.v) {
863 			xfrm_pol_hold(pol);
864 			if (delete) {
865 				*err = security_xfrm_policy_delete(
866 								pol->security);
867 				if (*err) {
868 					write_unlock_bh(&net->xfrm.xfrm_policy_lock);
869 					return pol;
870 				}
871 				__xfrm_policy_unlink(pol, dir);
872 			}
873 			ret = pol;
874 			break;
875 		}
876 	}
877 	write_unlock_bh(&net->xfrm.xfrm_policy_lock);
878 
879 	if (ret && delete)
880 		xfrm_policy_kill(ret);
881 	return ret;
882 }
883 EXPORT_SYMBOL(xfrm_policy_byid);
884 
885 #ifdef CONFIG_SECURITY_NETWORK_XFRM
886 static inline int
887 xfrm_policy_flush_secctx_check(struct net *net, u8 type, bool task_valid)
888 {
889 	int dir, err = 0;
890 
891 	for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
892 		struct xfrm_policy *pol;
893 		int i;
894 
895 		hlist_for_each_entry(pol,
896 				     &net->xfrm.policy_inexact[dir], bydst) {
897 			if (pol->type != type)
898 				continue;
899 			err = security_xfrm_policy_delete(pol->security);
900 			if (err) {
901 				xfrm_audit_policy_delete(pol, 0, task_valid);
902 				return err;
903 			}
904 		}
905 		for (i = net->xfrm.policy_bydst[dir].hmask; i >= 0; i--) {
906 			hlist_for_each_entry(pol,
907 					     net->xfrm.policy_bydst[dir].table + i,
908 					     bydst) {
909 				if (pol->type != type)
910 					continue;
911 				err = security_xfrm_policy_delete(
912 								pol->security);
913 				if (err) {
914 					xfrm_audit_policy_delete(pol, 0,
915 								 task_valid);
916 					return err;
917 				}
918 			}
919 		}
920 	}
921 	return err;
922 }
923 #else
924 static inline int
925 xfrm_policy_flush_secctx_check(struct net *net, u8 type, bool task_valid)
926 {
927 	return 0;
928 }
929 #endif
930 
931 int xfrm_policy_flush(struct net *net, u8 type, bool task_valid)
932 {
933 	int dir, err = 0, cnt = 0;
934 
935 	write_lock_bh(&net->xfrm.xfrm_policy_lock);
936 
937 	err = xfrm_policy_flush_secctx_check(net, type, task_valid);
938 	if (err)
939 		goto out;
940 
941 	for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
942 		struct xfrm_policy *pol;
943 		int i;
944 
945 	again1:
946 		hlist_for_each_entry(pol,
947 				     &net->xfrm.policy_inexact[dir], bydst) {
948 			if (pol->type != type)
949 				continue;
950 			__xfrm_policy_unlink(pol, dir);
951 			write_unlock_bh(&net->xfrm.xfrm_policy_lock);
952 			cnt++;
953 
954 			xfrm_audit_policy_delete(pol, 1, task_valid);
955 
956 			xfrm_policy_kill(pol);
957 
958 			write_lock_bh(&net->xfrm.xfrm_policy_lock);
959 			goto again1;
960 		}
961 
962 		for (i = net->xfrm.policy_bydst[dir].hmask; i >= 0; i--) {
963 	again2:
964 			hlist_for_each_entry(pol,
965 					     net->xfrm.policy_bydst[dir].table + i,
966 					     bydst) {
967 				if (pol->type != type)
968 					continue;
969 				__xfrm_policy_unlink(pol, dir);
970 				write_unlock_bh(&net->xfrm.xfrm_policy_lock);
971 				cnt++;
972 
973 				xfrm_audit_policy_delete(pol, 1, task_valid);
974 				xfrm_policy_kill(pol);
975 
976 				write_lock_bh(&net->xfrm.xfrm_policy_lock);
977 				goto again2;
978 			}
979 		}
980 
981 	}
982 	if (!cnt)
983 		err = -ESRCH;
984 out:
985 	write_unlock_bh(&net->xfrm.xfrm_policy_lock);
986 	return err;
987 }
988 EXPORT_SYMBOL(xfrm_policy_flush);
989 
990 int xfrm_policy_walk(struct net *net, struct xfrm_policy_walk *walk,
991 		     int (*func)(struct xfrm_policy *, int, int, void*),
992 		     void *data)
993 {
994 	struct xfrm_policy *pol;
995 	struct xfrm_policy_walk_entry *x;
996 	int error = 0;
997 
998 	if (walk->type >= XFRM_POLICY_TYPE_MAX &&
999 	    walk->type != XFRM_POLICY_TYPE_ANY)
1000 		return -EINVAL;
1001 
1002 	if (list_empty(&walk->walk.all) && walk->seq != 0)
1003 		return 0;
1004 
1005 	write_lock_bh(&net->xfrm.xfrm_policy_lock);
1006 	if (list_empty(&walk->walk.all))
1007 		x = list_first_entry(&net->xfrm.policy_all, struct xfrm_policy_walk_entry, all);
1008 	else
1009 		x = list_first_entry(&walk->walk.all,
1010 				     struct xfrm_policy_walk_entry, all);
1011 
1012 	list_for_each_entry_from(x, &net->xfrm.policy_all, all) {
1013 		if (x->dead)
1014 			continue;
1015 		pol = container_of(x, struct xfrm_policy, walk);
1016 		if (walk->type != XFRM_POLICY_TYPE_ANY &&
1017 		    walk->type != pol->type)
1018 			continue;
1019 		error = func(pol, xfrm_policy_id2dir(pol->index),
1020 			     walk->seq, data);
1021 		if (error) {
1022 			list_move_tail(&walk->walk.all, &x->all);
1023 			goto out;
1024 		}
1025 		walk->seq++;
1026 	}
1027 	if (walk->seq == 0) {
1028 		error = -ENOENT;
1029 		goto out;
1030 	}
1031 	list_del_init(&walk->walk.all);
1032 out:
1033 	write_unlock_bh(&net->xfrm.xfrm_policy_lock);
1034 	return error;
1035 }
1036 EXPORT_SYMBOL(xfrm_policy_walk);
1037 
1038 void xfrm_policy_walk_init(struct xfrm_policy_walk *walk, u8 type)
1039 {
1040 	INIT_LIST_HEAD(&walk->walk.all);
1041 	walk->walk.dead = 1;
1042 	walk->type = type;
1043 	walk->seq = 0;
1044 }
1045 EXPORT_SYMBOL(xfrm_policy_walk_init);
1046 
1047 void xfrm_policy_walk_done(struct xfrm_policy_walk *walk, struct net *net)
1048 {
1049 	if (list_empty(&walk->walk.all))
1050 		return;
1051 
1052 	write_lock_bh(&net->xfrm.xfrm_policy_lock); /*FIXME where is net? */
1053 	list_del(&walk->walk.all);
1054 	write_unlock_bh(&net->xfrm.xfrm_policy_lock);
1055 }
1056 EXPORT_SYMBOL(xfrm_policy_walk_done);
1057 
1058 /*
1059  * Find policy to apply to this flow.
1060  *
1061  * Returns 0 if policy found, else an -errno.
1062  */
1063 static int xfrm_policy_match(const struct xfrm_policy *pol,
1064 			     const struct flowi *fl,
1065 			     u8 type, u16 family, int dir)
1066 {
1067 	const struct xfrm_selector *sel = &pol->selector;
1068 	int ret = -ESRCH;
1069 	bool match;
1070 
1071 	if (pol->family != family ||
1072 	    (fl->flowi_mark & pol->mark.m) != pol->mark.v ||
1073 	    pol->type != type)
1074 		return ret;
1075 
1076 	match = xfrm_selector_match(sel, fl, family);
1077 	if (match)
1078 		ret = security_xfrm_policy_lookup(pol->security, fl->flowi_secid,
1079 						  dir);
1080 
1081 	return ret;
1082 }
1083 
1084 static struct xfrm_policy *xfrm_policy_lookup_bytype(struct net *net, u8 type,
1085 						     const struct flowi *fl,
1086 						     u16 family, u8 dir)
1087 {
1088 	int err;
1089 	struct xfrm_policy *pol, *ret;
1090 	const xfrm_address_t *daddr, *saddr;
1091 	struct hlist_head *chain;
1092 	u32 priority = ~0U;
1093 
1094 	daddr = xfrm_flowi_daddr(fl, family);
1095 	saddr = xfrm_flowi_saddr(fl, family);
1096 	if (unlikely(!daddr || !saddr))
1097 		return NULL;
1098 
1099 	read_lock_bh(&net->xfrm.xfrm_policy_lock);
1100 	chain = policy_hash_direct(net, daddr, saddr, family, dir);
1101 	ret = NULL;
1102 	hlist_for_each_entry(pol, chain, bydst) {
1103 		err = xfrm_policy_match(pol, fl, type, family, dir);
1104 		if (err) {
1105 			if (err == -ESRCH)
1106 				continue;
1107 			else {
1108 				ret = ERR_PTR(err);
1109 				goto fail;
1110 			}
1111 		} else {
1112 			ret = pol;
1113 			priority = ret->priority;
1114 			break;
1115 		}
1116 	}
1117 	chain = &net->xfrm.policy_inexact[dir];
1118 	hlist_for_each_entry(pol, chain, bydst) {
1119 		if ((pol->priority >= priority) && ret)
1120 			break;
1121 
1122 		err = xfrm_policy_match(pol, fl, type, family, dir);
1123 		if (err) {
1124 			if (err == -ESRCH)
1125 				continue;
1126 			else {
1127 				ret = ERR_PTR(err);
1128 				goto fail;
1129 			}
1130 		} else {
1131 			ret = pol;
1132 			break;
1133 		}
1134 	}
1135 
1136 	xfrm_pol_hold(ret);
1137 fail:
1138 	read_unlock_bh(&net->xfrm.xfrm_policy_lock);
1139 
1140 	return ret;
1141 }
1142 
1143 static struct xfrm_policy *
1144 __xfrm_policy_lookup(struct net *net, const struct flowi *fl, u16 family, u8 dir)
1145 {
1146 #ifdef CONFIG_XFRM_SUB_POLICY
1147 	struct xfrm_policy *pol;
1148 
1149 	pol = xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_SUB, fl, family, dir);
1150 	if (pol != NULL)
1151 		return pol;
1152 #endif
1153 	return xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_MAIN, fl, family, dir);
1154 }
1155 
1156 static int flow_to_policy_dir(int dir)
1157 {
1158 	if (XFRM_POLICY_IN == FLOW_DIR_IN &&
1159 	    XFRM_POLICY_OUT == FLOW_DIR_OUT &&
1160 	    XFRM_POLICY_FWD == FLOW_DIR_FWD)
1161 		return dir;
1162 
1163 	switch (dir) {
1164 	default:
1165 	case FLOW_DIR_IN:
1166 		return XFRM_POLICY_IN;
1167 	case FLOW_DIR_OUT:
1168 		return XFRM_POLICY_OUT;
1169 	case FLOW_DIR_FWD:
1170 		return XFRM_POLICY_FWD;
1171 	}
1172 }
1173 
1174 static struct flow_cache_object *
1175 xfrm_policy_lookup(struct net *net, const struct flowi *fl, u16 family,
1176 		   u8 dir, struct flow_cache_object *old_obj, void *ctx)
1177 {
1178 	struct xfrm_policy *pol;
1179 
1180 	if (old_obj)
1181 		xfrm_pol_put(container_of(old_obj, struct xfrm_policy, flo));
1182 
1183 	pol = __xfrm_policy_lookup(net, fl, family, flow_to_policy_dir(dir));
1184 	if (IS_ERR_OR_NULL(pol))
1185 		return ERR_CAST(pol);
1186 
1187 	/* Resolver returns two references:
1188 	 * one for cache and one for caller of flow_cache_lookup() */
1189 	xfrm_pol_hold(pol);
1190 
1191 	return &pol->flo;
1192 }
1193 
1194 static inline int policy_to_flow_dir(int dir)
1195 {
1196 	if (XFRM_POLICY_IN == FLOW_DIR_IN &&
1197 	    XFRM_POLICY_OUT == FLOW_DIR_OUT &&
1198 	    XFRM_POLICY_FWD == FLOW_DIR_FWD)
1199 		return dir;
1200 	switch (dir) {
1201 	default:
1202 	case XFRM_POLICY_IN:
1203 		return FLOW_DIR_IN;
1204 	case XFRM_POLICY_OUT:
1205 		return FLOW_DIR_OUT;
1206 	case XFRM_POLICY_FWD:
1207 		return FLOW_DIR_FWD;
1208 	}
1209 }
1210 
1211 static struct xfrm_policy *xfrm_sk_policy_lookup(struct sock *sk, int dir,
1212 						 const struct flowi *fl)
1213 {
1214 	struct xfrm_policy *pol;
1215 	struct net *net = sock_net(sk);
1216 
1217 	read_lock_bh(&net->xfrm.xfrm_policy_lock);
1218 	if ((pol = sk->sk_policy[dir]) != NULL) {
1219 		bool match = xfrm_selector_match(&pol->selector, fl,
1220 						 sk->sk_family);
1221 		int err = 0;
1222 
1223 		if (match) {
1224 			if ((sk->sk_mark & pol->mark.m) != pol->mark.v) {
1225 				pol = NULL;
1226 				goto out;
1227 			}
1228 			err = security_xfrm_policy_lookup(pol->security,
1229 						      fl->flowi_secid,
1230 						      policy_to_flow_dir(dir));
1231 			if (!err)
1232 				xfrm_pol_hold(pol);
1233 			else if (err == -ESRCH)
1234 				pol = NULL;
1235 			else
1236 				pol = ERR_PTR(err);
1237 		} else
1238 			pol = NULL;
1239 	}
1240 out:
1241 	read_unlock_bh(&net->xfrm.xfrm_policy_lock);
1242 	return pol;
1243 }
1244 
1245 static void __xfrm_policy_link(struct xfrm_policy *pol, int dir)
1246 {
1247 	struct net *net = xp_net(pol);
1248 
1249 	list_add(&pol->walk.all, &net->xfrm.policy_all);
1250 	net->xfrm.policy_count[dir]++;
1251 	xfrm_pol_hold(pol);
1252 }
1253 
1254 static struct xfrm_policy *__xfrm_policy_unlink(struct xfrm_policy *pol,
1255 						int dir)
1256 {
1257 	struct net *net = xp_net(pol);
1258 
1259 	if (list_empty(&pol->walk.all))
1260 		return NULL;
1261 
1262 	/* Socket policies are not hashed. */
1263 	if (!hlist_unhashed(&pol->bydst)) {
1264 		hlist_del(&pol->bydst);
1265 		hlist_del(&pol->byidx);
1266 	}
1267 
1268 	list_del_init(&pol->walk.all);
1269 	net->xfrm.policy_count[dir]--;
1270 
1271 	return pol;
1272 }
1273 
1274 static void xfrm_sk_policy_link(struct xfrm_policy *pol, int dir)
1275 {
1276 	__xfrm_policy_link(pol, XFRM_POLICY_MAX + dir);
1277 }
1278 
1279 static void xfrm_sk_policy_unlink(struct xfrm_policy *pol, int dir)
1280 {
1281 	__xfrm_policy_unlink(pol, XFRM_POLICY_MAX + dir);
1282 }
1283 
1284 int xfrm_policy_delete(struct xfrm_policy *pol, int dir)
1285 {
1286 	struct net *net = xp_net(pol);
1287 
1288 	write_lock_bh(&net->xfrm.xfrm_policy_lock);
1289 	pol = __xfrm_policy_unlink(pol, dir);
1290 	write_unlock_bh(&net->xfrm.xfrm_policy_lock);
1291 	if (pol) {
1292 		xfrm_policy_kill(pol);
1293 		return 0;
1294 	}
1295 	return -ENOENT;
1296 }
1297 EXPORT_SYMBOL(xfrm_policy_delete);
1298 
1299 int xfrm_sk_policy_insert(struct sock *sk, int dir, struct xfrm_policy *pol)
1300 {
1301 	struct net *net = xp_net(pol);
1302 	struct xfrm_policy *old_pol;
1303 
1304 #ifdef CONFIG_XFRM_SUB_POLICY
1305 	if (pol && pol->type != XFRM_POLICY_TYPE_MAIN)
1306 		return -EINVAL;
1307 #endif
1308 
1309 	write_lock_bh(&net->xfrm.xfrm_policy_lock);
1310 	old_pol = sk->sk_policy[dir];
1311 	sk->sk_policy[dir] = pol;
1312 	if (pol) {
1313 		pol->curlft.add_time = get_seconds();
1314 		pol->index = xfrm_gen_index(net, XFRM_POLICY_MAX+dir, 0);
1315 		xfrm_sk_policy_link(pol, dir);
1316 	}
1317 	if (old_pol) {
1318 		if (pol)
1319 			xfrm_policy_requeue(old_pol, pol);
1320 
1321 		/* Unlinking succeeds always. This is the only function
1322 		 * allowed to delete or replace socket policy.
1323 		 */
1324 		xfrm_sk_policy_unlink(old_pol, dir);
1325 	}
1326 	write_unlock_bh(&net->xfrm.xfrm_policy_lock);
1327 
1328 	if (old_pol) {
1329 		xfrm_policy_kill(old_pol);
1330 	}
1331 	return 0;
1332 }
1333 
1334 static struct xfrm_policy *clone_policy(const struct xfrm_policy *old, int dir)
1335 {
1336 	struct xfrm_policy *newp = xfrm_policy_alloc(xp_net(old), GFP_ATOMIC);
1337 	struct net *net = xp_net(old);
1338 
1339 	if (newp) {
1340 		newp->selector = old->selector;
1341 		if (security_xfrm_policy_clone(old->security,
1342 					       &newp->security)) {
1343 			kfree(newp);
1344 			return NULL;  /* ENOMEM */
1345 		}
1346 		newp->lft = old->lft;
1347 		newp->curlft = old->curlft;
1348 		newp->mark = old->mark;
1349 		newp->action = old->action;
1350 		newp->flags = old->flags;
1351 		newp->xfrm_nr = old->xfrm_nr;
1352 		newp->index = old->index;
1353 		newp->type = old->type;
1354 		memcpy(newp->xfrm_vec, old->xfrm_vec,
1355 		       newp->xfrm_nr*sizeof(struct xfrm_tmpl));
1356 		write_lock_bh(&net->xfrm.xfrm_policy_lock);
1357 		xfrm_sk_policy_link(newp, dir);
1358 		write_unlock_bh(&net->xfrm.xfrm_policy_lock);
1359 		xfrm_pol_put(newp);
1360 	}
1361 	return newp;
1362 }
1363 
1364 int __xfrm_sk_clone_policy(struct sock *sk)
1365 {
1366 	struct xfrm_policy *p0 = sk->sk_policy[0],
1367 			   *p1 = sk->sk_policy[1];
1368 
1369 	sk->sk_policy[0] = sk->sk_policy[1] = NULL;
1370 	if (p0 && (sk->sk_policy[0] = clone_policy(p0, 0)) == NULL)
1371 		return -ENOMEM;
1372 	if (p1 && (sk->sk_policy[1] = clone_policy(p1, 1)) == NULL)
1373 		return -ENOMEM;
1374 	return 0;
1375 }
1376 
1377 static int
1378 xfrm_get_saddr(struct net *net, int oif, xfrm_address_t *local,
1379 	       xfrm_address_t *remote, unsigned short family)
1380 {
1381 	int err;
1382 	struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1383 
1384 	if (unlikely(afinfo == NULL))
1385 		return -EINVAL;
1386 	err = afinfo->get_saddr(net, oif, local, remote);
1387 	xfrm_policy_put_afinfo(afinfo);
1388 	return err;
1389 }
1390 
1391 /* Resolve list of templates for the flow, given policy. */
1392 
1393 static int
1394 xfrm_tmpl_resolve_one(struct xfrm_policy *policy, const struct flowi *fl,
1395 		      struct xfrm_state **xfrm, unsigned short family)
1396 {
1397 	struct net *net = xp_net(policy);
1398 	int nx;
1399 	int i, error;
1400 	xfrm_address_t *daddr = xfrm_flowi_daddr(fl, family);
1401 	xfrm_address_t *saddr = xfrm_flowi_saddr(fl, family);
1402 	xfrm_address_t tmp;
1403 
1404 	for (nx = 0, i = 0; i < policy->xfrm_nr; i++) {
1405 		struct xfrm_state *x;
1406 		xfrm_address_t *remote = daddr;
1407 		xfrm_address_t *local  = saddr;
1408 		struct xfrm_tmpl *tmpl = &policy->xfrm_vec[i];
1409 
1410 		if (tmpl->mode == XFRM_MODE_TUNNEL ||
1411 		    tmpl->mode == XFRM_MODE_BEET) {
1412 			remote = &tmpl->id.daddr;
1413 			local = &tmpl->saddr;
1414 			if (xfrm_addr_any(local, tmpl->encap_family)) {
1415 				error = xfrm_get_saddr(net, fl->flowi_oif,
1416 						       &tmp, remote,
1417 						       tmpl->encap_family);
1418 				if (error)
1419 					goto fail;
1420 				local = &tmp;
1421 			}
1422 		}
1423 
1424 		x = xfrm_state_find(remote, local, fl, tmpl, policy, &error, family);
1425 
1426 		if (x && x->km.state == XFRM_STATE_VALID) {
1427 			xfrm[nx++] = x;
1428 			daddr = remote;
1429 			saddr = local;
1430 			continue;
1431 		}
1432 		if (x) {
1433 			error = (x->km.state == XFRM_STATE_ERROR ?
1434 				 -EINVAL : -EAGAIN);
1435 			xfrm_state_put(x);
1436 		} else if (error == -ESRCH) {
1437 			error = -EAGAIN;
1438 		}
1439 
1440 		if (!tmpl->optional)
1441 			goto fail;
1442 	}
1443 	return nx;
1444 
1445 fail:
1446 	for (nx--; nx >= 0; nx--)
1447 		xfrm_state_put(xfrm[nx]);
1448 	return error;
1449 }
1450 
1451 static int
1452 xfrm_tmpl_resolve(struct xfrm_policy **pols, int npols, const struct flowi *fl,
1453 		  struct xfrm_state **xfrm, unsigned short family)
1454 {
1455 	struct xfrm_state *tp[XFRM_MAX_DEPTH];
1456 	struct xfrm_state **tpp = (npols > 1) ? tp : xfrm;
1457 	int cnx = 0;
1458 	int error;
1459 	int ret;
1460 	int i;
1461 
1462 	for (i = 0; i < npols; i++) {
1463 		if (cnx + pols[i]->xfrm_nr >= XFRM_MAX_DEPTH) {
1464 			error = -ENOBUFS;
1465 			goto fail;
1466 		}
1467 
1468 		ret = xfrm_tmpl_resolve_one(pols[i], fl, &tpp[cnx], family);
1469 		if (ret < 0) {
1470 			error = ret;
1471 			goto fail;
1472 		} else
1473 			cnx += ret;
1474 	}
1475 
1476 	/* found states are sorted for outbound processing */
1477 	if (npols > 1)
1478 		xfrm_state_sort(xfrm, tpp, cnx, family);
1479 
1480 	return cnx;
1481 
1482  fail:
1483 	for (cnx--; cnx >= 0; cnx--)
1484 		xfrm_state_put(tpp[cnx]);
1485 	return error;
1486 
1487 }
1488 
1489 /* Check that the bundle accepts the flow and its components are
1490  * still valid.
1491  */
1492 
1493 static inline int xfrm_get_tos(const struct flowi *fl, int family)
1494 {
1495 	struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1496 	int tos;
1497 
1498 	if (!afinfo)
1499 		return -EINVAL;
1500 
1501 	tos = afinfo->get_tos(fl);
1502 
1503 	xfrm_policy_put_afinfo(afinfo);
1504 
1505 	return tos;
1506 }
1507 
1508 static struct flow_cache_object *xfrm_bundle_flo_get(struct flow_cache_object *flo)
1509 {
1510 	struct xfrm_dst *xdst = container_of(flo, struct xfrm_dst, flo);
1511 	struct dst_entry *dst = &xdst->u.dst;
1512 
1513 	if (xdst->route == NULL) {
1514 		/* Dummy bundle - if it has xfrms we were not
1515 		 * able to build bundle as template resolution failed.
1516 		 * It means we need to try again resolving. */
1517 		if (xdst->num_xfrms > 0)
1518 			return NULL;
1519 	} else if (dst->flags & DST_XFRM_QUEUE) {
1520 		return NULL;
1521 	} else {
1522 		/* Real bundle */
1523 		if (stale_bundle(dst))
1524 			return NULL;
1525 	}
1526 
1527 	dst_hold(dst);
1528 	return flo;
1529 }
1530 
1531 static int xfrm_bundle_flo_check(struct flow_cache_object *flo)
1532 {
1533 	struct xfrm_dst *xdst = container_of(flo, struct xfrm_dst, flo);
1534 	struct dst_entry *dst = &xdst->u.dst;
1535 
1536 	if (!xdst->route)
1537 		return 0;
1538 	if (stale_bundle(dst))
1539 		return 0;
1540 
1541 	return 1;
1542 }
1543 
1544 static void xfrm_bundle_flo_delete(struct flow_cache_object *flo)
1545 {
1546 	struct xfrm_dst *xdst = container_of(flo, struct xfrm_dst, flo);
1547 	struct dst_entry *dst = &xdst->u.dst;
1548 
1549 	dst_free(dst);
1550 }
1551 
1552 static const struct flow_cache_ops xfrm_bundle_fc_ops = {
1553 	.get = xfrm_bundle_flo_get,
1554 	.check = xfrm_bundle_flo_check,
1555 	.delete = xfrm_bundle_flo_delete,
1556 };
1557 
1558 static inline struct xfrm_dst *xfrm_alloc_dst(struct net *net, int family)
1559 {
1560 	struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1561 	struct dst_ops *dst_ops;
1562 	struct xfrm_dst *xdst;
1563 
1564 	if (!afinfo)
1565 		return ERR_PTR(-EINVAL);
1566 
1567 	switch (family) {
1568 	case AF_INET:
1569 		dst_ops = &net->xfrm.xfrm4_dst_ops;
1570 		break;
1571 #if IS_ENABLED(CONFIG_IPV6)
1572 	case AF_INET6:
1573 		dst_ops = &net->xfrm.xfrm6_dst_ops;
1574 		break;
1575 #endif
1576 	default:
1577 		BUG();
1578 	}
1579 	xdst = dst_alloc(dst_ops, NULL, 0, DST_OBSOLETE_NONE, 0);
1580 
1581 	if (likely(xdst)) {
1582 		struct dst_entry *dst = &xdst->u.dst;
1583 
1584 		memset(dst + 1, 0, sizeof(*xdst) - sizeof(*dst));
1585 		xdst->flo.ops = &xfrm_bundle_fc_ops;
1586 		if (afinfo->init_dst)
1587 			afinfo->init_dst(net, xdst);
1588 	} else
1589 		xdst = ERR_PTR(-ENOBUFS);
1590 
1591 	xfrm_policy_put_afinfo(afinfo);
1592 
1593 	return xdst;
1594 }
1595 
1596 static inline int xfrm_init_path(struct xfrm_dst *path, struct dst_entry *dst,
1597 				 int nfheader_len)
1598 {
1599 	struct xfrm_policy_afinfo *afinfo =
1600 		xfrm_policy_get_afinfo(dst->ops->family);
1601 	int err;
1602 
1603 	if (!afinfo)
1604 		return -EINVAL;
1605 
1606 	err = afinfo->init_path(path, dst, nfheader_len);
1607 
1608 	xfrm_policy_put_afinfo(afinfo);
1609 
1610 	return err;
1611 }
1612 
1613 static inline int xfrm_fill_dst(struct xfrm_dst *xdst, struct net_device *dev,
1614 				const struct flowi *fl)
1615 {
1616 	struct xfrm_policy_afinfo *afinfo =
1617 		xfrm_policy_get_afinfo(xdst->u.dst.ops->family);
1618 	int err;
1619 
1620 	if (!afinfo)
1621 		return -EINVAL;
1622 
1623 	err = afinfo->fill_dst(xdst, dev, fl);
1624 
1625 	xfrm_policy_put_afinfo(afinfo);
1626 
1627 	return err;
1628 }
1629 
1630 
1631 /* Allocate chain of dst_entry's, attach known xfrm's, calculate
1632  * all the metrics... Shortly, bundle a bundle.
1633  */
1634 
1635 static struct dst_entry *xfrm_bundle_create(struct xfrm_policy *policy,
1636 					    struct xfrm_state **xfrm, int nx,
1637 					    const struct flowi *fl,
1638 					    struct dst_entry *dst)
1639 {
1640 	struct net *net = xp_net(policy);
1641 	unsigned long now = jiffies;
1642 	struct net_device *dev;
1643 	struct xfrm_mode *inner_mode;
1644 	struct dst_entry *dst_prev = NULL;
1645 	struct dst_entry *dst0 = NULL;
1646 	int i = 0;
1647 	int err;
1648 	int header_len = 0;
1649 	int nfheader_len = 0;
1650 	int trailer_len = 0;
1651 	int tos;
1652 	int family = policy->selector.family;
1653 	xfrm_address_t saddr, daddr;
1654 
1655 	xfrm_flowi_addr_get(fl, &saddr, &daddr, family);
1656 
1657 	tos = xfrm_get_tos(fl, family);
1658 	err = tos;
1659 	if (tos < 0)
1660 		goto put_states;
1661 
1662 	dst_hold(dst);
1663 
1664 	for (; i < nx; i++) {
1665 		struct xfrm_dst *xdst = xfrm_alloc_dst(net, family);
1666 		struct dst_entry *dst1 = &xdst->u.dst;
1667 
1668 		err = PTR_ERR(xdst);
1669 		if (IS_ERR(xdst)) {
1670 			dst_release(dst);
1671 			goto put_states;
1672 		}
1673 
1674 		if (xfrm[i]->sel.family == AF_UNSPEC) {
1675 			inner_mode = xfrm_ip2inner_mode(xfrm[i],
1676 							xfrm_af2proto(family));
1677 			if (!inner_mode) {
1678 				err = -EAFNOSUPPORT;
1679 				dst_release(dst);
1680 				goto put_states;
1681 			}
1682 		} else
1683 			inner_mode = xfrm[i]->inner_mode;
1684 
1685 		if (!dst_prev)
1686 			dst0 = dst1;
1687 		else {
1688 			dst_prev->child = dst_clone(dst1);
1689 			dst1->flags |= DST_NOHASH;
1690 		}
1691 
1692 		xdst->route = dst;
1693 		dst_copy_metrics(dst1, dst);
1694 
1695 		if (xfrm[i]->props.mode != XFRM_MODE_TRANSPORT) {
1696 			family = xfrm[i]->props.family;
1697 			dst = xfrm_dst_lookup(xfrm[i], tos, fl->flowi_oif,
1698 					      &saddr, &daddr, family);
1699 			err = PTR_ERR(dst);
1700 			if (IS_ERR(dst))
1701 				goto put_states;
1702 		} else
1703 			dst_hold(dst);
1704 
1705 		dst1->xfrm = xfrm[i];
1706 		xdst->xfrm_genid = xfrm[i]->genid;
1707 
1708 		dst1->obsolete = DST_OBSOLETE_FORCE_CHK;
1709 		dst1->flags |= DST_HOST;
1710 		dst1->lastuse = now;
1711 
1712 		dst1->input = dst_discard;
1713 		dst1->output = inner_mode->afinfo->output;
1714 
1715 		dst1->next = dst_prev;
1716 		dst_prev = dst1;
1717 
1718 		header_len += xfrm[i]->props.header_len;
1719 		if (xfrm[i]->type->flags & XFRM_TYPE_NON_FRAGMENT)
1720 			nfheader_len += xfrm[i]->props.header_len;
1721 		trailer_len += xfrm[i]->props.trailer_len;
1722 	}
1723 
1724 	dst_prev->child = dst;
1725 	dst0->path = dst;
1726 
1727 	err = -ENODEV;
1728 	dev = dst->dev;
1729 	if (!dev)
1730 		goto free_dst;
1731 
1732 	xfrm_init_path((struct xfrm_dst *)dst0, dst, nfheader_len);
1733 	xfrm_init_pmtu(dst_prev);
1734 
1735 	for (dst_prev = dst0; dst_prev != dst; dst_prev = dst_prev->child) {
1736 		struct xfrm_dst *xdst = (struct xfrm_dst *)dst_prev;
1737 
1738 		err = xfrm_fill_dst(xdst, dev, fl);
1739 		if (err)
1740 			goto free_dst;
1741 
1742 		dst_prev->header_len = header_len;
1743 		dst_prev->trailer_len = trailer_len;
1744 		header_len -= xdst->u.dst.xfrm->props.header_len;
1745 		trailer_len -= xdst->u.dst.xfrm->props.trailer_len;
1746 	}
1747 
1748 out:
1749 	return dst0;
1750 
1751 put_states:
1752 	for (; i < nx; i++)
1753 		xfrm_state_put(xfrm[i]);
1754 free_dst:
1755 	if (dst0)
1756 		dst_free(dst0);
1757 	dst0 = ERR_PTR(err);
1758 	goto out;
1759 }
1760 
1761 #ifdef CONFIG_XFRM_SUB_POLICY
1762 static int xfrm_dst_alloc_copy(void **target, const void *src, int size)
1763 {
1764 	if (!*target) {
1765 		*target = kmalloc(size, GFP_ATOMIC);
1766 		if (!*target)
1767 			return -ENOMEM;
1768 	}
1769 
1770 	memcpy(*target, src, size);
1771 	return 0;
1772 }
1773 #endif
1774 
1775 static int xfrm_dst_update_parent(struct dst_entry *dst,
1776 				  const struct xfrm_selector *sel)
1777 {
1778 #ifdef CONFIG_XFRM_SUB_POLICY
1779 	struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
1780 	return xfrm_dst_alloc_copy((void **)&(xdst->partner),
1781 				   sel, sizeof(*sel));
1782 #else
1783 	return 0;
1784 #endif
1785 }
1786 
1787 static int xfrm_dst_update_origin(struct dst_entry *dst,
1788 				  const struct flowi *fl)
1789 {
1790 #ifdef CONFIG_XFRM_SUB_POLICY
1791 	struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
1792 	return xfrm_dst_alloc_copy((void **)&(xdst->origin), fl, sizeof(*fl));
1793 #else
1794 	return 0;
1795 #endif
1796 }
1797 
1798 static int xfrm_expand_policies(const struct flowi *fl, u16 family,
1799 				struct xfrm_policy **pols,
1800 				int *num_pols, int *num_xfrms)
1801 {
1802 	int i;
1803 
1804 	if (*num_pols == 0 || !pols[0]) {
1805 		*num_pols = 0;
1806 		*num_xfrms = 0;
1807 		return 0;
1808 	}
1809 	if (IS_ERR(pols[0]))
1810 		return PTR_ERR(pols[0]);
1811 
1812 	*num_xfrms = pols[0]->xfrm_nr;
1813 
1814 #ifdef CONFIG_XFRM_SUB_POLICY
1815 	if (pols[0] && pols[0]->action == XFRM_POLICY_ALLOW &&
1816 	    pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
1817 		pols[1] = xfrm_policy_lookup_bytype(xp_net(pols[0]),
1818 						    XFRM_POLICY_TYPE_MAIN,
1819 						    fl, family,
1820 						    XFRM_POLICY_OUT);
1821 		if (pols[1]) {
1822 			if (IS_ERR(pols[1])) {
1823 				xfrm_pols_put(pols, *num_pols);
1824 				return PTR_ERR(pols[1]);
1825 			}
1826 			(*num_pols)++;
1827 			(*num_xfrms) += pols[1]->xfrm_nr;
1828 		}
1829 	}
1830 #endif
1831 	for (i = 0; i < *num_pols; i++) {
1832 		if (pols[i]->action != XFRM_POLICY_ALLOW) {
1833 			*num_xfrms = -1;
1834 			break;
1835 		}
1836 	}
1837 
1838 	return 0;
1839 
1840 }
1841 
1842 static struct xfrm_dst *
1843 xfrm_resolve_and_create_bundle(struct xfrm_policy **pols, int num_pols,
1844 			       const struct flowi *fl, u16 family,
1845 			       struct dst_entry *dst_orig)
1846 {
1847 	struct net *net = xp_net(pols[0]);
1848 	struct xfrm_state *xfrm[XFRM_MAX_DEPTH];
1849 	struct dst_entry *dst;
1850 	struct xfrm_dst *xdst;
1851 	int err;
1852 
1853 	/* Try to instantiate a bundle */
1854 	err = xfrm_tmpl_resolve(pols, num_pols, fl, xfrm, family);
1855 	if (err <= 0) {
1856 		if (err != 0 && err != -EAGAIN)
1857 			XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLERROR);
1858 		return ERR_PTR(err);
1859 	}
1860 
1861 	dst = xfrm_bundle_create(pols[0], xfrm, err, fl, dst_orig);
1862 	if (IS_ERR(dst)) {
1863 		XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTBUNDLEGENERROR);
1864 		return ERR_CAST(dst);
1865 	}
1866 
1867 	xdst = (struct xfrm_dst *)dst;
1868 	xdst->num_xfrms = err;
1869 	if (num_pols > 1)
1870 		err = xfrm_dst_update_parent(dst, &pols[1]->selector);
1871 	else
1872 		err = xfrm_dst_update_origin(dst, fl);
1873 	if (unlikely(err)) {
1874 		dst_free(dst);
1875 		XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTBUNDLECHECKERROR);
1876 		return ERR_PTR(err);
1877 	}
1878 
1879 	xdst->num_pols = num_pols;
1880 	memcpy(xdst->pols, pols, sizeof(struct xfrm_policy *) * num_pols);
1881 	xdst->policy_genid = atomic_read(&pols[0]->genid);
1882 
1883 	return xdst;
1884 }
1885 
1886 static void xfrm_policy_queue_process(unsigned long arg)
1887 {
1888 	struct sk_buff *skb;
1889 	struct sock *sk;
1890 	struct dst_entry *dst;
1891 	struct xfrm_policy *pol = (struct xfrm_policy *)arg;
1892 	struct xfrm_policy_queue *pq = &pol->polq;
1893 	struct flowi fl;
1894 	struct sk_buff_head list;
1895 
1896 	spin_lock(&pq->hold_queue.lock);
1897 	skb = skb_peek(&pq->hold_queue);
1898 	if (!skb) {
1899 		spin_unlock(&pq->hold_queue.lock);
1900 		goto out;
1901 	}
1902 	dst = skb_dst(skb);
1903 	sk = skb->sk;
1904 	xfrm_decode_session(skb, &fl, dst->ops->family);
1905 	spin_unlock(&pq->hold_queue.lock);
1906 
1907 	dst_hold(dst->path);
1908 	dst = xfrm_lookup(xp_net(pol), dst->path, &fl,
1909 			  sk, 0);
1910 	if (IS_ERR(dst))
1911 		goto purge_queue;
1912 
1913 	if (dst->flags & DST_XFRM_QUEUE) {
1914 		dst_release(dst);
1915 
1916 		if (pq->timeout >= XFRM_QUEUE_TMO_MAX)
1917 			goto purge_queue;
1918 
1919 		pq->timeout = pq->timeout << 1;
1920 		if (!mod_timer(&pq->hold_timer, jiffies + pq->timeout))
1921 			xfrm_pol_hold(pol);
1922 	goto out;
1923 	}
1924 
1925 	dst_release(dst);
1926 
1927 	__skb_queue_head_init(&list);
1928 
1929 	spin_lock(&pq->hold_queue.lock);
1930 	pq->timeout = 0;
1931 	skb_queue_splice_init(&pq->hold_queue, &list);
1932 	spin_unlock(&pq->hold_queue.lock);
1933 
1934 	while (!skb_queue_empty(&list)) {
1935 		skb = __skb_dequeue(&list);
1936 
1937 		xfrm_decode_session(skb, &fl, skb_dst(skb)->ops->family);
1938 		dst_hold(skb_dst(skb)->path);
1939 		dst = xfrm_lookup(xp_net(pol), skb_dst(skb)->path,
1940 				  &fl, skb->sk, 0);
1941 		if (IS_ERR(dst)) {
1942 			kfree_skb(skb);
1943 			continue;
1944 		}
1945 
1946 		nf_reset(skb);
1947 		skb_dst_drop(skb);
1948 		skb_dst_set(skb, dst);
1949 
1950 		dst_output(skb);
1951 	}
1952 
1953 out:
1954 	xfrm_pol_put(pol);
1955 	return;
1956 
1957 purge_queue:
1958 	pq->timeout = 0;
1959 	skb_queue_purge(&pq->hold_queue);
1960 	xfrm_pol_put(pol);
1961 }
1962 
1963 static int xdst_queue_output(struct sock *sk, struct sk_buff *skb)
1964 {
1965 	unsigned long sched_next;
1966 	struct dst_entry *dst = skb_dst(skb);
1967 	struct xfrm_dst *xdst = (struct xfrm_dst *) dst;
1968 	struct xfrm_policy *pol = xdst->pols[0];
1969 	struct xfrm_policy_queue *pq = &pol->polq;
1970 
1971 	if (unlikely(skb_fclone_busy(sk, skb))) {
1972 		kfree_skb(skb);
1973 		return 0;
1974 	}
1975 
1976 	if (pq->hold_queue.qlen > XFRM_MAX_QUEUE_LEN) {
1977 		kfree_skb(skb);
1978 		return -EAGAIN;
1979 	}
1980 
1981 	skb_dst_force(skb);
1982 
1983 	spin_lock_bh(&pq->hold_queue.lock);
1984 
1985 	if (!pq->timeout)
1986 		pq->timeout = XFRM_QUEUE_TMO_MIN;
1987 
1988 	sched_next = jiffies + pq->timeout;
1989 
1990 	if (del_timer(&pq->hold_timer)) {
1991 		if (time_before(pq->hold_timer.expires, sched_next))
1992 			sched_next = pq->hold_timer.expires;
1993 		xfrm_pol_put(pol);
1994 	}
1995 
1996 	__skb_queue_tail(&pq->hold_queue, skb);
1997 	if (!mod_timer(&pq->hold_timer, sched_next))
1998 		xfrm_pol_hold(pol);
1999 
2000 	spin_unlock_bh(&pq->hold_queue.lock);
2001 
2002 	return 0;
2003 }
2004 
2005 static struct xfrm_dst *xfrm_create_dummy_bundle(struct net *net,
2006 						 struct xfrm_flo *xflo,
2007 						 const struct flowi *fl,
2008 						 int num_xfrms,
2009 						 u16 family)
2010 {
2011 	int err;
2012 	struct net_device *dev;
2013 	struct dst_entry *dst;
2014 	struct dst_entry *dst1;
2015 	struct xfrm_dst *xdst;
2016 
2017 	xdst = xfrm_alloc_dst(net, family);
2018 	if (IS_ERR(xdst))
2019 		return xdst;
2020 
2021 	if (!(xflo->flags & XFRM_LOOKUP_QUEUE) ||
2022 	    net->xfrm.sysctl_larval_drop ||
2023 	    num_xfrms <= 0)
2024 		return xdst;
2025 
2026 	dst = xflo->dst_orig;
2027 	dst1 = &xdst->u.dst;
2028 	dst_hold(dst);
2029 	xdst->route = dst;
2030 
2031 	dst_copy_metrics(dst1, dst);
2032 
2033 	dst1->obsolete = DST_OBSOLETE_FORCE_CHK;
2034 	dst1->flags |= DST_HOST | DST_XFRM_QUEUE;
2035 	dst1->lastuse = jiffies;
2036 
2037 	dst1->input = dst_discard;
2038 	dst1->output = xdst_queue_output;
2039 
2040 	dst_hold(dst);
2041 	dst1->child = dst;
2042 	dst1->path = dst;
2043 
2044 	xfrm_init_path((struct xfrm_dst *)dst1, dst, 0);
2045 
2046 	err = -ENODEV;
2047 	dev = dst->dev;
2048 	if (!dev)
2049 		goto free_dst;
2050 
2051 	err = xfrm_fill_dst(xdst, dev, fl);
2052 	if (err)
2053 		goto free_dst;
2054 
2055 out:
2056 	return xdst;
2057 
2058 free_dst:
2059 	dst_release(dst1);
2060 	xdst = ERR_PTR(err);
2061 	goto out;
2062 }
2063 
2064 static struct flow_cache_object *
2065 xfrm_bundle_lookup(struct net *net, const struct flowi *fl, u16 family, u8 dir,
2066 		   struct flow_cache_object *oldflo, void *ctx)
2067 {
2068 	struct xfrm_flo *xflo = (struct xfrm_flo *)ctx;
2069 	struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
2070 	struct xfrm_dst *xdst, *new_xdst;
2071 	int num_pols = 0, num_xfrms = 0, i, err, pol_dead;
2072 
2073 	/* Check if the policies from old bundle are usable */
2074 	xdst = NULL;
2075 	if (oldflo) {
2076 		xdst = container_of(oldflo, struct xfrm_dst, flo);
2077 		num_pols = xdst->num_pols;
2078 		num_xfrms = xdst->num_xfrms;
2079 		pol_dead = 0;
2080 		for (i = 0; i < num_pols; i++) {
2081 			pols[i] = xdst->pols[i];
2082 			pol_dead |= pols[i]->walk.dead;
2083 		}
2084 		if (pol_dead) {
2085 			dst_free(&xdst->u.dst);
2086 			xdst = NULL;
2087 			num_pols = 0;
2088 			num_xfrms = 0;
2089 			oldflo = NULL;
2090 		}
2091 	}
2092 
2093 	/* Resolve policies to use if we couldn't get them from
2094 	 * previous cache entry */
2095 	if (xdst == NULL) {
2096 		num_pols = 1;
2097 		pols[0] = __xfrm_policy_lookup(net, fl, family,
2098 					       flow_to_policy_dir(dir));
2099 		err = xfrm_expand_policies(fl, family, pols,
2100 					   &num_pols, &num_xfrms);
2101 		if (err < 0)
2102 			goto inc_error;
2103 		if (num_pols == 0)
2104 			return NULL;
2105 		if (num_xfrms <= 0)
2106 			goto make_dummy_bundle;
2107 	}
2108 
2109 	new_xdst = xfrm_resolve_and_create_bundle(pols, num_pols, fl, family,
2110 						  xflo->dst_orig);
2111 	if (IS_ERR(new_xdst)) {
2112 		err = PTR_ERR(new_xdst);
2113 		if (err != -EAGAIN)
2114 			goto error;
2115 		if (oldflo == NULL)
2116 			goto make_dummy_bundle;
2117 		dst_hold(&xdst->u.dst);
2118 		return oldflo;
2119 	} else if (new_xdst == NULL) {
2120 		num_xfrms = 0;
2121 		if (oldflo == NULL)
2122 			goto make_dummy_bundle;
2123 		xdst->num_xfrms = 0;
2124 		dst_hold(&xdst->u.dst);
2125 		return oldflo;
2126 	}
2127 
2128 	/* Kill the previous bundle */
2129 	if (xdst) {
2130 		/* The policies were stolen for newly generated bundle */
2131 		xdst->num_pols = 0;
2132 		dst_free(&xdst->u.dst);
2133 	}
2134 
2135 	/* Flow cache does not have reference, it dst_free()'s,
2136 	 * but we do need to return one reference for original caller */
2137 	dst_hold(&new_xdst->u.dst);
2138 	return &new_xdst->flo;
2139 
2140 make_dummy_bundle:
2141 	/* We found policies, but there's no bundles to instantiate:
2142 	 * either because the policy blocks, has no transformations or
2143 	 * we could not build template (no xfrm_states).*/
2144 	xdst = xfrm_create_dummy_bundle(net, xflo, fl, num_xfrms, family);
2145 	if (IS_ERR(xdst)) {
2146 		xfrm_pols_put(pols, num_pols);
2147 		return ERR_CAST(xdst);
2148 	}
2149 	xdst->num_pols = num_pols;
2150 	xdst->num_xfrms = num_xfrms;
2151 	memcpy(xdst->pols, pols, sizeof(struct xfrm_policy *) * num_pols);
2152 
2153 	dst_hold(&xdst->u.dst);
2154 	return &xdst->flo;
2155 
2156 inc_error:
2157 	XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLERROR);
2158 error:
2159 	if (xdst != NULL)
2160 		dst_free(&xdst->u.dst);
2161 	else
2162 		xfrm_pols_put(pols, num_pols);
2163 	return ERR_PTR(err);
2164 }
2165 
2166 static struct dst_entry *make_blackhole(struct net *net, u16 family,
2167 					struct dst_entry *dst_orig)
2168 {
2169 	struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
2170 	struct dst_entry *ret;
2171 
2172 	if (!afinfo) {
2173 		dst_release(dst_orig);
2174 		return ERR_PTR(-EINVAL);
2175 	} else {
2176 		ret = afinfo->blackhole_route(net, dst_orig);
2177 	}
2178 	xfrm_policy_put_afinfo(afinfo);
2179 
2180 	return ret;
2181 }
2182 
2183 /* Main function: finds/creates a bundle for given flow.
2184  *
2185  * At the moment we eat a raw IP route. Mostly to speed up lookups
2186  * on interfaces with disabled IPsec.
2187  */
2188 struct dst_entry *xfrm_lookup(struct net *net, struct dst_entry *dst_orig,
2189 			      const struct flowi *fl,
2190 			      struct sock *sk, int flags)
2191 {
2192 	struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
2193 	struct flow_cache_object *flo;
2194 	struct xfrm_dst *xdst;
2195 	struct dst_entry *dst, *route;
2196 	u16 family = dst_orig->ops->family;
2197 	u8 dir = policy_to_flow_dir(XFRM_POLICY_OUT);
2198 	int i, err, num_pols, num_xfrms = 0, drop_pols = 0;
2199 
2200 	dst = NULL;
2201 	xdst = NULL;
2202 	route = NULL;
2203 
2204 	if (sk && sk->sk_policy[XFRM_POLICY_OUT]) {
2205 		num_pols = 1;
2206 		pols[0] = xfrm_sk_policy_lookup(sk, XFRM_POLICY_OUT, fl);
2207 		err = xfrm_expand_policies(fl, family, pols,
2208 					   &num_pols, &num_xfrms);
2209 		if (err < 0)
2210 			goto dropdst;
2211 
2212 		if (num_pols) {
2213 			if (num_xfrms <= 0) {
2214 				drop_pols = num_pols;
2215 				goto no_transform;
2216 			}
2217 
2218 			xdst = xfrm_resolve_and_create_bundle(
2219 					pols, num_pols, fl,
2220 					family, dst_orig);
2221 			if (IS_ERR(xdst)) {
2222 				xfrm_pols_put(pols, num_pols);
2223 				err = PTR_ERR(xdst);
2224 				goto dropdst;
2225 			} else if (xdst == NULL) {
2226 				num_xfrms = 0;
2227 				drop_pols = num_pols;
2228 				goto no_transform;
2229 			}
2230 
2231 			dst_hold(&xdst->u.dst);
2232 			xdst->u.dst.flags |= DST_NOCACHE;
2233 			route = xdst->route;
2234 		}
2235 	}
2236 
2237 	if (xdst == NULL) {
2238 		struct xfrm_flo xflo;
2239 
2240 		xflo.dst_orig = dst_orig;
2241 		xflo.flags = flags;
2242 
2243 		/* To accelerate a bit...  */
2244 		if ((dst_orig->flags & DST_NOXFRM) ||
2245 		    !net->xfrm.policy_count[XFRM_POLICY_OUT])
2246 			goto nopol;
2247 
2248 		flo = flow_cache_lookup(net, fl, family, dir,
2249 					xfrm_bundle_lookup, &xflo);
2250 		if (flo == NULL)
2251 			goto nopol;
2252 		if (IS_ERR(flo)) {
2253 			err = PTR_ERR(flo);
2254 			goto dropdst;
2255 		}
2256 		xdst = container_of(flo, struct xfrm_dst, flo);
2257 
2258 		num_pols = xdst->num_pols;
2259 		num_xfrms = xdst->num_xfrms;
2260 		memcpy(pols, xdst->pols, sizeof(struct xfrm_policy *) * num_pols);
2261 		route = xdst->route;
2262 	}
2263 
2264 	dst = &xdst->u.dst;
2265 	if (route == NULL && num_xfrms > 0) {
2266 		/* The only case when xfrm_bundle_lookup() returns a
2267 		 * bundle with null route, is when the template could
2268 		 * not be resolved. It means policies are there, but
2269 		 * bundle could not be created, since we don't yet
2270 		 * have the xfrm_state's. We need to wait for KM to
2271 		 * negotiate new SA's or bail out with error.*/
2272 		if (net->xfrm.sysctl_larval_drop) {
2273 			XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTNOSTATES);
2274 			err = -EREMOTE;
2275 			goto error;
2276 		}
2277 
2278 		err = -EAGAIN;
2279 
2280 		XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTNOSTATES);
2281 		goto error;
2282 	}
2283 
2284 no_transform:
2285 	if (num_pols == 0)
2286 		goto nopol;
2287 
2288 	if ((flags & XFRM_LOOKUP_ICMP) &&
2289 	    !(pols[0]->flags & XFRM_POLICY_ICMP)) {
2290 		err = -ENOENT;
2291 		goto error;
2292 	}
2293 
2294 	for (i = 0; i < num_pols; i++)
2295 		pols[i]->curlft.use_time = get_seconds();
2296 
2297 	if (num_xfrms < 0) {
2298 		/* Prohibit the flow */
2299 		XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLBLOCK);
2300 		err = -EPERM;
2301 		goto error;
2302 	} else if (num_xfrms > 0) {
2303 		/* Flow transformed */
2304 		dst_release(dst_orig);
2305 	} else {
2306 		/* Flow passes untransformed */
2307 		dst_release(dst);
2308 		dst = dst_orig;
2309 	}
2310 ok:
2311 	xfrm_pols_put(pols, drop_pols);
2312 	if (dst && dst->xfrm &&
2313 	    dst->xfrm->props.mode == XFRM_MODE_TUNNEL)
2314 		dst->flags |= DST_XFRM_TUNNEL;
2315 	return dst;
2316 
2317 nopol:
2318 	if (!(flags & XFRM_LOOKUP_ICMP)) {
2319 		dst = dst_orig;
2320 		goto ok;
2321 	}
2322 	err = -ENOENT;
2323 error:
2324 	dst_release(dst);
2325 dropdst:
2326 	if (!(flags & XFRM_LOOKUP_KEEP_DST_REF))
2327 		dst_release(dst_orig);
2328 	xfrm_pols_put(pols, drop_pols);
2329 	return ERR_PTR(err);
2330 }
2331 EXPORT_SYMBOL(xfrm_lookup);
2332 
2333 /* Callers of xfrm_lookup_route() must ensure a call to dst_output().
2334  * Otherwise we may send out blackholed packets.
2335  */
2336 struct dst_entry *xfrm_lookup_route(struct net *net, struct dst_entry *dst_orig,
2337 				    const struct flowi *fl,
2338 				    struct sock *sk, int flags)
2339 {
2340 	struct dst_entry *dst = xfrm_lookup(net, dst_orig, fl, sk,
2341 					    flags | XFRM_LOOKUP_QUEUE |
2342 					    XFRM_LOOKUP_KEEP_DST_REF);
2343 
2344 	if (IS_ERR(dst) && PTR_ERR(dst) == -EREMOTE)
2345 		return make_blackhole(net, dst_orig->ops->family, dst_orig);
2346 
2347 	return dst;
2348 }
2349 EXPORT_SYMBOL(xfrm_lookup_route);
2350 
2351 static inline int
2352 xfrm_secpath_reject(int idx, struct sk_buff *skb, const struct flowi *fl)
2353 {
2354 	struct xfrm_state *x;
2355 
2356 	if (!skb->sp || idx < 0 || idx >= skb->sp->len)
2357 		return 0;
2358 	x = skb->sp->xvec[idx];
2359 	if (!x->type->reject)
2360 		return 0;
2361 	return x->type->reject(x, skb, fl);
2362 }
2363 
2364 /* When skb is transformed back to its "native" form, we have to
2365  * check policy restrictions. At the moment we make this in maximally
2366  * stupid way. Shame on me. :-) Of course, connected sockets must
2367  * have policy cached at them.
2368  */
2369 
2370 static inline int
2371 xfrm_state_ok(const struct xfrm_tmpl *tmpl, const struct xfrm_state *x,
2372 	      unsigned short family)
2373 {
2374 	if (xfrm_state_kern(x))
2375 		return tmpl->optional && !xfrm_state_addr_cmp(tmpl, x, tmpl->encap_family);
2376 	return	x->id.proto == tmpl->id.proto &&
2377 		(x->id.spi == tmpl->id.spi || !tmpl->id.spi) &&
2378 		(x->props.reqid == tmpl->reqid || !tmpl->reqid) &&
2379 		x->props.mode == tmpl->mode &&
2380 		(tmpl->allalgs || (tmpl->aalgos & (1<<x->props.aalgo)) ||
2381 		 !(xfrm_id_proto_match(tmpl->id.proto, IPSEC_PROTO_ANY))) &&
2382 		!(x->props.mode != XFRM_MODE_TRANSPORT &&
2383 		  xfrm_state_addr_cmp(tmpl, x, family));
2384 }
2385 
2386 /*
2387  * 0 or more than 0 is returned when validation is succeeded (either bypass
2388  * because of optional transport mode, or next index of the mathced secpath
2389  * state with the template.
2390  * -1 is returned when no matching template is found.
2391  * Otherwise "-2 - errored_index" is returned.
2392  */
2393 static inline int
2394 xfrm_policy_ok(const struct xfrm_tmpl *tmpl, const struct sec_path *sp, int start,
2395 	       unsigned short family)
2396 {
2397 	int idx = start;
2398 
2399 	if (tmpl->optional) {
2400 		if (tmpl->mode == XFRM_MODE_TRANSPORT)
2401 			return start;
2402 	} else
2403 		start = -1;
2404 	for (; idx < sp->len; idx++) {
2405 		if (xfrm_state_ok(tmpl, sp->xvec[idx], family))
2406 			return ++idx;
2407 		if (sp->xvec[idx]->props.mode != XFRM_MODE_TRANSPORT) {
2408 			if (start == -1)
2409 				start = -2-idx;
2410 			break;
2411 		}
2412 	}
2413 	return start;
2414 }
2415 
2416 int __xfrm_decode_session(struct sk_buff *skb, struct flowi *fl,
2417 			  unsigned int family, int reverse)
2418 {
2419 	struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
2420 	int err;
2421 
2422 	if (unlikely(afinfo == NULL))
2423 		return -EAFNOSUPPORT;
2424 
2425 	afinfo->decode_session(skb, fl, reverse);
2426 	err = security_xfrm_decode_session(skb, &fl->flowi_secid);
2427 	xfrm_policy_put_afinfo(afinfo);
2428 	return err;
2429 }
2430 EXPORT_SYMBOL(__xfrm_decode_session);
2431 
2432 static inline int secpath_has_nontransport(const struct sec_path *sp, int k, int *idxp)
2433 {
2434 	for (; k < sp->len; k++) {
2435 		if (sp->xvec[k]->props.mode != XFRM_MODE_TRANSPORT) {
2436 			*idxp = k;
2437 			return 1;
2438 		}
2439 	}
2440 
2441 	return 0;
2442 }
2443 
2444 int __xfrm_policy_check(struct sock *sk, int dir, struct sk_buff *skb,
2445 			unsigned short family)
2446 {
2447 	struct net *net = dev_net(skb->dev);
2448 	struct xfrm_policy *pol;
2449 	struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
2450 	int npols = 0;
2451 	int xfrm_nr;
2452 	int pi;
2453 	int reverse;
2454 	struct flowi fl;
2455 	u8 fl_dir;
2456 	int xerr_idx = -1;
2457 
2458 	reverse = dir & ~XFRM_POLICY_MASK;
2459 	dir &= XFRM_POLICY_MASK;
2460 	fl_dir = policy_to_flow_dir(dir);
2461 
2462 	if (__xfrm_decode_session(skb, &fl, family, reverse) < 0) {
2463 		XFRM_INC_STATS(net, LINUX_MIB_XFRMINHDRERROR);
2464 		return 0;
2465 	}
2466 
2467 	nf_nat_decode_session(skb, &fl, family);
2468 
2469 	/* First, check used SA against their selectors. */
2470 	if (skb->sp) {
2471 		int i;
2472 
2473 		for (i = skb->sp->len-1; i >= 0; i--) {
2474 			struct xfrm_state *x = skb->sp->xvec[i];
2475 			if (!xfrm_selector_match(&x->sel, &fl, family)) {
2476 				XFRM_INC_STATS(net, LINUX_MIB_XFRMINSTATEMISMATCH);
2477 				return 0;
2478 			}
2479 		}
2480 	}
2481 
2482 	pol = NULL;
2483 	if (sk && sk->sk_policy[dir]) {
2484 		pol = xfrm_sk_policy_lookup(sk, dir, &fl);
2485 		if (IS_ERR(pol)) {
2486 			XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
2487 			return 0;
2488 		}
2489 	}
2490 
2491 	if (!pol) {
2492 		struct flow_cache_object *flo;
2493 
2494 		flo = flow_cache_lookup(net, &fl, family, fl_dir,
2495 					xfrm_policy_lookup, NULL);
2496 		if (IS_ERR_OR_NULL(flo))
2497 			pol = ERR_CAST(flo);
2498 		else
2499 			pol = container_of(flo, struct xfrm_policy, flo);
2500 	}
2501 
2502 	if (IS_ERR(pol)) {
2503 		XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
2504 		return 0;
2505 	}
2506 
2507 	if (!pol) {
2508 		if (skb->sp && secpath_has_nontransport(skb->sp, 0, &xerr_idx)) {
2509 			xfrm_secpath_reject(xerr_idx, skb, &fl);
2510 			XFRM_INC_STATS(net, LINUX_MIB_XFRMINNOPOLS);
2511 			return 0;
2512 		}
2513 		return 1;
2514 	}
2515 
2516 	pol->curlft.use_time = get_seconds();
2517 
2518 	pols[0] = pol;
2519 	npols++;
2520 #ifdef CONFIG_XFRM_SUB_POLICY
2521 	if (pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
2522 		pols[1] = xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_MAIN,
2523 						    &fl, family,
2524 						    XFRM_POLICY_IN);
2525 		if (pols[1]) {
2526 			if (IS_ERR(pols[1])) {
2527 				XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
2528 				return 0;
2529 			}
2530 			pols[1]->curlft.use_time = get_seconds();
2531 			npols++;
2532 		}
2533 	}
2534 #endif
2535 
2536 	if (pol->action == XFRM_POLICY_ALLOW) {
2537 		struct sec_path *sp;
2538 		static struct sec_path dummy;
2539 		struct xfrm_tmpl *tp[XFRM_MAX_DEPTH];
2540 		struct xfrm_tmpl *stp[XFRM_MAX_DEPTH];
2541 		struct xfrm_tmpl **tpp = tp;
2542 		int ti = 0;
2543 		int i, k;
2544 
2545 		if ((sp = skb->sp) == NULL)
2546 			sp = &dummy;
2547 
2548 		for (pi = 0; pi < npols; pi++) {
2549 			if (pols[pi] != pol &&
2550 			    pols[pi]->action != XFRM_POLICY_ALLOW) {
2551 				XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLBLOCK);
2552 				goto reject;
2553 			}
2554 			if (ti + pols[pi]->xfrm_nr >= XFRM_MAX_DEPTH) {
2555 				XFRM_INC_STATS(net, LINUX_MIB_XFRMINBUFFERERROR);
2556 				goto reject_error;
2557 			}
2558 			for (i = 0; i < pols[pi]->xfrm_nr; i++)
2559 				tpp[ti++] = &pols[pi]->xfrm_vec[i];
2560 		}
2561 		xfrm_nr = ti;
2562 		if (npols > 1) {
2563 			xfrm_tmpl_sort(stp, tpp, xfrm_nr, family, net);
2564 			tpp = stp;
2565 		}
2566 
2567 		/* For each tunnel xfrm, find the first matching tmpl.
2568 		 * For each tmpl before that, find corresponding xfrm.
2569 		 * Order is _important_. Later we will implement
2570 		 * some barriers, but at the moment barriers
2571 		 * are implied between each two transformations.
2572 		 */
2573 		for (i = xfrm_nr-1, k = 0; i >= 0; i--) {
2574 			k = xfrm_policy_ok(tpp[i], sp, k, family);
2575 			if (k < 0) {
2576 				if (k < -1)
2577 					/* "-2 - errored_index" returned */
2578 					xerr_idx = -(2+k);
2579 				XFRM_INC_STATS(net, LINUX_MIB_XFRMINTMPLMISMATCH);
2580 				goto reject;
2581 			}
2582 		}
2583 
2584 		if (secpath_has_nontransport(sp, k, &xerr_idx)) {
2585 			XFRM_INC_STATS(net, LINUX_MIB_XFRMINTMPLMISMATCH);
2586 			goto reject;
2587 		}
2588 
2589 		xfrm_pols_put(pols, npols);
2590 		return 1;
2591 	}
2592 	XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLBLOCK);
2593 
2594 reject:
2595 	xfrm_secpath_reject(xerr_idx, skb, &fl);
2596 reject_error:
2597 	xfrm_pols_put(pols, npols);
2598 	return 0;
2599 }
2600 EXPORT_SYMBOL(__xfrm_policy_check);
2601 
2602 int __xfrm_route_forward(struct sk_buff *skb, unsigned short family)
2603 {
2604 	struct net *net = dev_net(skb->dev);
2605 	struct flowi fl;
2606 	struct dst_entry *dst;
2607 	int res = 1;
2608 
2609 	if (xfrm_decode_session(skb, &fl, family) < 0) {
2610 		XFRM_INC_STATS(net, LINUX_MIB_XFRMFWDHDRERROR);
2611 		return 0;
2612 	}
2613 
2614 	skb_dst_force(skb);
2615 
2616 	dst = xfrm_lookup(net, skb_dst(skb), &fl, NULL, XFRM_LOOKUP_QUEUE);
2617 	if (IS_ERR(dst)) {
2618 		res = 0;
2619 		dst = NULL;
2620 	}
2621 	skb_dst_set(skb, dst);
2622 	return res;
2623 }
2624 EXPORT_SYMBOL(__xfrm_route_forward);
2625 
2626 /* Optimize later using cookies and generation ids. */
2627 
2628 static struct dst_entry *xfrm_dst_check(struct dst_entry *dst, u32 cookie)
2629 {
2630 	/* Code (such as __xfrm4_bundle_create()) sets dst->obsolete
2631 	 * to DST_OBSOLETE_FORCE_CHK to force all XFRM destinations to
2632 	 * get validated by dst_ops->check on every use.  We do this
2633 	 * because when a normal route referenced by an XFRM dst is
2634 	 * obsoleted we do not go looking around for all parent
2635 	 * referencing XFRM dsts so that we can invalidate them.  It
2636 	 * is just too much work.  Instead we make the checks here on
2637 	 * every use.  For example:
2638 	 *
2639 	 *	XFRM dst A --> IPv4 dst X
2640 	 *
2641 	 * X is the "xdst->route" of A (X is also the "dst->path" of A
2642 	 * in this example).  If X is marked obsolete, "A" will not
2643 	 * notice.  That's what we are validating here via the
2644 	 * stale_bundle() check.
2645 	 *
2646 	 * When a policy's bundle is pruned, we dst_free() the XFRM
2647 	 * dst which causes it's ->obsolete field to be set to
2648 	 * DST_OBSOLETE_DEAD.  If an XFRM dst has been pruned like
2649 	 * this, we want to force a new route lookup.
2650 	 */
2651 	if (dst->obsolete < 0 && !stale_bundle(dst))
2652 		return dst;
2653 
2654 	return NULL;
2655 }
2656 
2657 static int stale_bundle(struct dst_entry *dst)
2658 {
2659 	return !xfrm_bundle_ok((struct xfrm_dst *)dst);
2660 }
2661 
2662 void xfrm_dst_ifdown(struct dst_entry *dst, struct net_device *dev)
2663 {
2664 	while ((dst = dst->child) && dst->xfrm && dst->dev == dev) {
2665 		dst->dev = dev_net(dev)->loopback_dev;
2666 		dev_hold(dst->dev);
2667 		dev_put(dev);
2668 	}
2669 }
2670 EXPORT_SYMBOL(xfrm_dst_ifdown);
2671 
2672 static void xfrm_link_failure(struct sk_buff *skb)
2673 {
2674 	/* Impossible. Such dst must be popped before reaches point of failure. */
2675 }
2676 
2677 static struct dst_entry *xfrm_negative_advice(struct dst_entry *dst)
2678 {
2679 	if (dst) {
2680 		if (dst->obsolete) {
2681 			dst_release(dst);
2682 			dst = NULL;
2683 		}
2684 	}
2685 	return dst;
2686 }
2687 
2688 void xfrm_garbage_collect(struct net *net)
2689 {
2690 	flow_cache_flush(net);
2691 }
2692 EXPORT_SYMBOL(xfrm_garbage_collect);
2693 
2694 static void xfrm_garbage_collect_deferred(struct net *net)
2695 {
2696 	flow_cache_flush_deferred(net);
2697 }
2698 
2699 static void xfrm_init_pmtu(struct dst_entry *dst)
2700 {
2701 	do {
2702 		struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
2703 		u32 pmtu, route_mtu_cached;
2704 
2705 		pmtu = dst_mtu(dst->child);
2706 		xdst->child_mtu_cached = pmtu;
2707 
2708 		pmtu = xfrm_state_mtu(dst->xfrm, pmtu);
2709 
2710 		route_mtu_cached = dst_mtu(xdst->route);
2711 		xdst->route_mtu_cached = route_mtu_cached;
2712 
2713 		if (pmtu > route_mtu_cached)
2714 			pmtu = route_mtu_cached;
2715 
2716 		dst_metric_set(dst, RTAX_MTU, pmtu);
2717 	} while ((dst = dst->next));
2718 }
2719 
2720 /* Check that the bundle accepts the flow and its components are
2721  * still valid.
2722  */
2723 
2724 static int xfrm_bundle_ok(struct xfrm_dst *first)
2725 {
2726 	struct dst_entry *dst = &first->u.dst;
2727 	struct xfrm_dst *last;
2728 	u32 mtu;
2729 
2730 	if (!dst_check(dst->path, ((struct xfrm_dst *)dst)->path_cookie) ||
2731 	    (dst->dev && !netif_running(dst->dev)))
2732 		return 0;
2733 
2734 	if (dst->flags & DST_XFRM_QUEUE)
2735 		return 1;
2736 
2737 	last = NULL;
2738 
2739 	do {
2740 		struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
2741 
2742 		if (dst->xfrm->km.state != XFRM_STATE_VALID)
2743 			return 0;
2744 		if (xdst->xfrm_genid != dst->xfrm->genid)
2745 			return 0;
2746 		if (xdst->num_pols > 0 &&
2747 		    xdst->policy_genid != atomic_read(&xdst->pols[0]->genid))
2748 			return 0;
2749 
2750 		mtu = dst_mtu(dst->child);
2751 		if (xdst->child_mtu_cached != mtu) {
2752 			last = xdst;
2753 			xdst->child_mtu_cached = mtu;
2754 		}
2755 
2756 		if (!dst_check(xdst->route, xdst->route_cookie))
2757 			return 0;
2758 		mtu = dst_mtu(xdst->route);
2759 		if (xdst->route_mtu_cached != mtu) {
2760 			last = xdst;
2761 			xdst->route_mtu_cached = mtu;
2762 		}
2763 
2764 		dst = dst->child;
2765 	} while (dst->xfrm);
2766 
2767 	if (likely(!last))
2768 		return 1;
2769 
2770 	mtu = last->child_mtu_cached;
2771 	for (;;) {
2772 		dst = &last->u.dst;
2773 
2774 		mtu = xfrm_state_mtu(dst->xfrm, mtu);
2775 		if (mtu > last->route_mtu_cached)
2776 			mtu = last->route_mtu_cached;
2777 		dst_metric_set(dst, RTAX_MTU, mtu);
2778 
2779 		if (last == first)
2780 			break;
2781 
2782 		last = (struct xfrm_dst *)last->u.dst.next;
2783 		last->child_mtu_cached = mtu;
2784 	}
2785 
2786 	return 1;
2787 }
2788 
2789 static unsigned int xfrm_default_advmss(const struct dst_entry *dst)
2790 {
2791 	return dst_metric_advmss(dst->path);
2792 }
2793 
2794 static unsigned int xfrm_mtu(const struct dst_entry *dst)
2795 {
2796 	unsigned int mtu = dst_metric_raw(dst, RTAX_MTU);
2797 
2798 	return mtu ? : dst_mtu(dst->path);
2799 }
2800 
2801 static struct neighbour *xfrm_neigh_lookup(const struct dst_entry *dst,
2802 					   struct sk_buff *skb,
2803 					   const void *daddr)
2804 {
2805 	return dst->path->ops->neigh_lookup(dst, skb, daddr);
2806 }
2807 
2808 int xfrm_policy_register_afinfo(struct xfrm_policy_afinfo *afinfo)
2809 {
2810 	struct net *net;
2811 	int err = 0;
2812 	if (unlikely(afinfo == NULL))
2813 		return -EINVAL;
2814 	if (unlikely(afinfo->family >= NPROTO))
2815 		return -EAFNOSUPPORT;
2816 	spin_lock(&xfrm_policy_afinfo_lock);
2817 	if (unlikely(xfrm_policy_afinfo[afinfo->family] != NULL))
2818 		err = -EEXIST;
2819 	else {
2820 		struct dst_ops *dst_ops = afinfo->dst_ops;
2821 		if (likely(dst_ops->kmem_cachep == NULL))
2822 			dst_ops->kmem_cachep = xfrm_dst_cache;
2823 		if (likely(dst_ops->check == NULL))
2824 			dst_ops->check = xfrm_dst_check;
2825 		if (likely(dst_ops->default_advmss == NULL))
2826 			dst_ops->default_advmss = xfrm_default_advmss;
2827 		if (likely(dst_ops->mtu == NULL))
2828 			dst_ops->mtu = xfrm_mtu;
2829 		if (likely(dst_ops->negative_advice == NULL))
2830 			dst_ops->negative_advice = xfrm_negative_advice;
2831 		if (likely(dst_ops->link_failure == NULL))
2832 			dst_ops->link_failure = xfrm_link_failure;
2833 		if (likely(dst_ops->neigh_lookup == NULL))
2834 			dst_ops->neigh_lookup = xfrm_neigh_lookup;
2835 		if (likely(afinfo->garbage_collect == NULL))
2836 			afinfo->garbage_collect = xfrm_garbage_collect_deferred;
2837 		rcu_assign_pointer(xfrm_policy_afinfo[afinfo->family], afinfo);
2838 	}
2839 	spin_unlock(&xfrm_policy_afinfo_lock);
2840 
2841 	rtnl_lock();
2842 	for_each_net(net) {
2843 		struct dst_ops *xfrm_dst_ops;
2844 
2845 		switch (afinfo->family) {
2846 		case AF_INET:
2847 			xfrm_dst_ops = &net->xfrm.xfrm4_dst_ops;
2848 			break;
2849 #if IS_ENABLED(CONFIG_IPV6)
2850 		case AF_INET6:
2851 			xfrm_dst_ops = &net->xfrm.xfrm6_dst_ops;
2852 			break;
2853 #endif
2854 		default:
2855 			BUG();
2856 		}
2857 		*xfrm_dst_ops = *afinfo->dst_ops;
2858 	}
2859 	rtnl_unlock();
2860 
2861 	return err;
2862 }
2863 EXPORT_SYMBOL(xfrm_policy_register_afinfo);
2864 
2865 int xfrm_policy_unregister_afinfo(struct xfrm_policy_afinfo *afinfo)
2866 {
2867 	int err = 0;
2868 	if (unlikely(afinfo == NULL))
2869 		return -EINVAL;
2870 	if (unlikely(afinfo->family >= NPROTO))
2871 		return -EAFNOSUPPORT;
2872 	spin_lock(&xfrm_policy_afinfo_lock);
2873 	if (likely(xfrm_policy_afinfo[afinfo->family] != NULL)) {
2874 		if (unlikely(xfrm_policy_afinfo[afinfo->family] != afinfo))
2875 			err = -EINVAL;
2876 		else
2877 			RCU_INIT_POINTER(xfrm_policy_afinfo[afinfo->family],
2878 					 NULL);
2879 	}
2880 	spin_unlock(&xfrm_policy_afinfo_lock);
2881 	if (!err) {
2882 		struct dst_ops *dst_ops = afinfo->dst_ops;
2883 
2884 		synchronize_rcu();
2885 
2886 		dst_ops->kmem_cachep = NULL;
2887 		dst_ops->check = NULL;
2888 		dst_ops->negative_advice = NULL;
2889 		dst_ops->link_failure = NULL;
2890 		afinfo->garbage_collect = NULL;
2891 	}
2892 	return err;
2893 }
2894 EXPORT_SYMBOL(xfrm_policy_unregister_afinfo);
2895 
2896 static void __net_init xfrm_dst_ops_init(struct net *net)
2897 {
2898 	struct xfrm_policy_afinfo *afinfo;
2899 
2900 	rcu_read_lock();
2901 	afinfo = rcu_dereference(xfrm_policy_afinfo[AF_INET]);
2902 	if (afinfo)
2903 		net->xfrm.xfrm4_dst_ops = *afinfo->dst_ops;
2904 #if IS_ENABLED(CONFIG_IPV6)
2905 	afinfo = rcu_dereference(xfrm_policy_afinfo[AF_INET6]);
2906 	if (afinfo)
2907 		net->xfrm.xfrm6_dst_ops = *afinfo->dst_ops;
2908 #endif
2909 	rcu_read_unlock();
2910 }
2911 
2912 static int xfrm_dev_event(struct notifier_block *this, unsigned long event, void *ptr)
2913 {
2914 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
2915 
2916 	switch (event) {
2917 	case NETDEV_DOWN:
2918 		xfrm_garbage_collect(dev_net(dev));
2919 	}
2920 	return NOTIFY_DONE;
2921 }
2922 
2923 static struct notifier_block xfrm_dev_notifier = {
2924 	.notifier_call	= xfrm_dev_event,
2925 };
2926 
2927 #ifdef CONFIG_XFRM_STATISTICS
2928 static int __net_init xfrm_statistics_init(struct net *net)
2929 {
2930 	int rv;
2931 	net->mib.xfrm_statistics = alloc_percpu(struct linux_xfrm_mib);
2932 	if (!net->mib.xfrm_statistics)
2933 		return -ENOMEM;
2934 	rv = xfrm_proc_init(net);
2935 	if (rv < 0)
2936 		free_percpu(net->mib.xfrm_statistics);
2937 	return rv;
2938 }
2939 
2940 static void xfrm_statistics_fini(struct net *net)
2941 {
2942 	xfrm_proc_fini(net);
2943 	free_percpu(net->mib.xfrm_statistics);
2944 }
2945 #else
2946 static int __net_init xfrm_statistics_init(struct net *net)
2947 {
2948 	return 0;
2949 }
2950 
2951 static void xfrm_statistics_fini(struct net *net)
2952 {
2953 }
2954 #endif
2955 
2956 static int __net_init xfrm_policy_init(struct net *net)
2957 {
2958 	unsigned int hmask, sz;
2959 	int dir;
2960 
2961 	if (net_eq(net, &init_net))
2962 		xfrm_dst_cache = kmem_cache_create("xfrm_dst_cache",
2963 					   sizeof(struct xfrm_dst),
2964 					   0, SLAB_HWCACHE_ALIGN|SLAB_PANIC,
2965 					   NULL);
2966 
2967 	hmask = 8 - 1;
2968 	sz = (hmask+1) * sizeof(struct hlist_head);
2969 
2970 	net->xfrm.policy_byidx = xfrm_hash_alloc(sz);
2971 	if (!net->xfrm.policy_byidx)
2972 		goto out_byidx;
2973 	net->xfrm.policy_idx_hmask = hmask;
2974 
2975 	for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
2976 		struct xfrm_policy_hash *htab;
2977 
2978 		net->xfrm.policy_count[dir] = 0;
2979 		net->xfrm.policy_count[XFRM_POLICY_MAX + dir] = 0;
2980 		INIT_HLIST_HEAD(&net->xfrm.policy_inexact[dir]);
2981 
2982 		htab = &net->xfrm.policy_bydst[dir];
2983 		htab->table = xfrm_hash_alloc(sz);
2984 		if (!htab->table)
2985 			goto out_bydst;
2986 		htab->hmask = hmask;
2987 		htab->dbits4 = 32;
2988 		htab->sbits4 = 32;
2989 		htab->dbits6 = 128;
2990 		htab->sbits6 = 128;
2991 	}
2992 	net->xfrm.policy_hthresh.lbits4 = 32;
2993 	net->xfrm.policy_hthresh.rbits4 = 32;
2994 	net->xfrm.policy_hthresh.lbits6 = 128;
2995 	net->xfrm.policy_hthresh.rbits6 = 128;
2996 
2997 	seqlock_init(&net->xfrm.policy_hthresh.lock);
2998 
2999 	INIT_LIST_HEAD(&net->xfrm.policy_all);
3000 	INIT_WORK(&net->xfrm.policy_hash_work, xfrm_hash_resize);
3001 	INIT_WORK(&net->xfrm.policy_hthresh.work, xfrm_hash_rebuild);
3002 	if (net_eq(net, &init_net))
3003 		register_netdevice_notifier(&xfrm_dev_notifier);
3004 	return 0;
3005 
3006 out_bydst:
3007 	for (dir--; dir >= 0; dir--) {
3008 		struct xfrm_policy_hash *htab;
3009 
3010 		htab = &net->xfrm.policy_bydst[dir];
3011 		xfrm_hash_free(htab->table, sz);
3012 	}
3013 	xfrm_hash_free(net->xfrm.policy_byidx, sz);
3014 out_byidx:
3015 	return -ENOMEM;
3016 }
3017 
3018 static void xfrm_policy_fini(struct net *net)
3019 {
3020 	unsigned int sz;
3021 	int dir;
3022 
3023 	flush_work(&net->xfrm.policy_hash_work);
3024 #ifdef CONFIG_XFRM_SUB_POLICY
3025 	xfrm_policy_flush(net, XFRM_POLICY_TYPE_SUB, false);
3026 #endif
3027 	xfrm_policy_flush(net, XFRM_POLICY_TYPE_MAIN, false);
3028 
3029 	WARN_ON(!list_empty(&net->xfrm.policy_all));
3030 
3031 	for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
3032 		struct xfrm_policy_hash *htab;
3033 
3034 		WARN_ON(!hlist_empty(&net->xfrm.policy_inexact[dir]));
3035 
3036 		htab = &net->xfrm.policy_bydst[dir];
3037 		sz = (htab->hmask + 1) * sizeof(struct hlist_head);
3038 		WARN_ON(!hlist_empty(htab->table));
3039 		xfrm_hash_free(htab->table, sz);
3040 	}
3041 
3042 	sz = (net->xfrm.policy_idx_hmask + 1) * sizeof(struct hlist_head);
3043 	WARN_ON(!hlist_empty(net->xfrm.policy_byidx));
3044 	xfrm_hash_free(net->xfrm.policy_byidx, sz);
3045 }
3046 
3047 static int __net_init xfrm_net_init(struct net *net)
3048 {
3049 	int rv;
3050 
3051 	rv = xfrm_statistics_init(net);
3052 	if (rv < 0)
3053 		goto out_statistics;
3054 	rv = xfrm_state_init(net);
3055 	if (rv < 0)
3056 		goto out_state;
3057 	rv = xfrm_policy_init(net);
3058 	if (rv < 0)
3059 		goto out_policy;
3060 	xfrm_dst_ops_init(net);
3061 	rv = xfrm_sysctl_init(net);
3062 	if (rv < 0)
3063 		goto out_sysctl;
3064 	rv = flow_cache_init(net);
3065 	if (rv < 0)
3066 		goto out;
3067 
3068 	/* Initialize the per-net locks here */
3069 	spin_lock_init(&net->xfrm.xfrm_state_lock);
3070 	rwlock_init(&net->xfrm.xfrm_policy_lock);
3071 	mutex_init(&net->xfrm.xfrm_cfg_mutex);
3072 
3073 	return 0;
3074 
3075 out:
3076 	xfrm_sysctl_fini(net);
3077 out_sysctl:
3078 	xfrm_policy_fini(net);
3079 out_policy:
3080 	xfrm_state_fini(net);
3081 out_state:
3082 	xfrm_statistics_fini(net);
3083 out_statistics:
3084 	return rv;
3085 }
3086 
3087 static void __net_exit xfrm_net_exit(struct net *net)
3088 {
3089 	flow_cache_fini(net);
3090 	xfrm_sysctl_fini(net);
3091 	xfrm_policy_fini(net);
3092 	xfrm_state_fini(net);
3093 	xfrm_statistics_fini(net);
3094 }
3095 
3096 static struct pernet_operations __net_initdata xfrm_net_ops = {
3097 	.init = xfrm_net_init,
3098 	.exit = xfrm_net_exit,
3099 };
3100 
3101 void __init xfrm_init(void)
3102 {
3103 	register_pernet_subsys(&xfrm_net_ops);
3104 	xfrm_input_init();
3105 }
3106 
3107 #ifdef CONFIG_AUDITSYSCALL
3108 static void xfrm_audit_common_policyinfo(struct xfrm_policy *xp,
3109 					 struct audit_buffer *audit_buf)
3110 {
3111 	struct xfrm_sec_ctx *ctx = xp->security;
3112 	struct xfrm_selector *sel = &xp->selector;
3113 
3114 	if (ctx)
3115 		audit_log_format(audit_buf, " sec_alg=%u sec_doi=%u sec_obj=%s",
3116 				 ctx->ctx_alg, ctx->ctx_doi, ctx->ctx_str);
3117 
3118 	switch (sel->family) {
3119 	case AF_INET:
3120 		audit_log_format(audit_buf, " src=%pI4", &sel->saddr.a4);
3121 		if (sel->prefixlen_s != 32)
3122 			audit_log_format(audit_buf, " src_prefixlen=%d",
3123 					 sel->prefixlen_s);
3124 		audit_log_format(audit_buf, " dst=%pI4", &sel->daddr.a4);
3125 		if (sel->prefixlen_d != 32)
3126 			audit_log_format(audit_buf, " dst_prefixlen=%d",
3127 					 sel->prefixlen_d);
3128 		break;
3129 	case AF_INET6:
3130 		audit_log_format(audit_buf, " src=%pI6", sel->saddr.a6);
3131 		if (sel->prefixlen_s != 128)
3132 			audit_log_format(audit_buf, " src_prefixlen=%d",
3133 					 sel->prefixlen_s);
3134 		audit_log_format(audit_buf, " dst=%pI6", sel->daddr.a6);
3135 		if (sel->prefixlen_d != 128)
3136 			audit_log_format(audit_buf, " dst_prefixlen=%d",
3137 					 sel->prefixlen_d);
3138 		break;
3139 	}
3140 }
3141 
3142 void xfrm_audit_policy_add(struct xfrm_policy *xp, int result, bool task_valid)
3143 {
3144 	struct audit_buffer *audit_buf;
3145 
3146 	audit_buf = xfrm_audit_start("SPD-add");
3147 	if (audit_buf == NULL)
3148 		return;
3149 	xfrm_audit_helper_usrinfo(task_valid, audit_buf);
3150 	audit_log_format(audit_buf, " res=%u", result);
3151 	xfrm_audit_common_policyinfo(xp, audit_buf);
3152 	audit_log_end(audit_buf);
3153 }
3154 EXPORT_SYMBOL_GPL(xfrm_audit_policy_add);
3155 
3156 void xfrm_audit_policy_delete(struct xfrm_policy *xp, int result,
3157 			      bool task_valid)
3158 {
3159 	struct audit_buffer *audit_buf;
3160 
3161 	audit_buf = xfrm_audit_start("SPD-delete");
3162 	if (audit_buf == NULL)
3163 		return;
3164 	xfrm_audit_helper_usrinfo(task_valid, audit_buf);
3165 	audit_log_format(audit_buf, " res=%u", result);
3166 	xfrm_audit_common_policyinfo(xp, audit_buf);
3167 	audit_log_end(audit_buf);
3168 }
3169 EXPORT_SYMBOL_GPL(xfrm_audit_policy_delete);
3170 #endif
3171 
3172 #ifdef CONFIG_XFRM_MIGRATE
3173 static bool xfrm_migrate_selector_match(const struct xfrm_selector *sel_cmp,
3174 					const struct xfrm_selector *sel_tgt)
3175 {
3176 	if (sel_cmp->proto == IPSEC_ULPROTO_ANY) {
3177 		if (sel_tgt->family == sel_cmp->family &&
3178 		    xfrm_addr_equal(&sel_tgt->daddr, &sel_cmp->daddr,
3179 				    sel_cmp->family) &&
3180 		    xfrm_addr_equal(&sel_tgt->saddr, &sel_cmp->saddr,
3181 				    sel_cmp->family) &&
3182 		    sel_tgt->prefixlen_d == sel_cmp->prefixlen_d &&
3183 		    sel_tgt->prefixlen_s == sel_cmp->prefixlen_s) {
3184 			return true;
3185 		}
3186 	} else {
3187 		if (memcmp(sel_tgt, sel_cmp, sizeof(*sel_tgt)) == 0) {
3188 			return true;
3189 		}
3190 	}
3191 	return false;
3192 }
3193 
3194 static struct xfrm_policy *xfrm_migrate_policy_find(const struct xfrm_selector *sel,
3195 						    u8 dir, u8 type, struct net *net)
3196 {
3197 	struct xfrm_policy *pol, *ret = NULL;
3198 	struct hlist_head *chain;
3199 	u32 priority = ~0U;
3200 
3201 	read_lock_bh(&net->xfrm.xfrm_policy_lock); /*FIXME*/
3202 	chain = policy_hash_direct(net, &sel->daddr, &sel->saddr, sel->family, dir);
3203 	hlist_for_each_entry(pol, chain, bydst) {
3204 		if (xfrm_migrate_selector_match(sel, &pol->selector) &&
3205 		    pol->type == type) {
3206 			ret = pol;
3207 			priority = ret->priority;
3208 			break;
3209 		}
3210 	}
3211 	chain = &net->xfrm.policy_inexact[dir];
3212 	hlist_for_each_entry(pol, chain, bydst) {
3213 		if ((pol->priority >= priority) && ret)
3214 			break;
3215 
3216 		if (xfrm_migrate_selector_match(sel, &pol->selector) &&
3217 		    pol->type == type) {
3218 			ret = pol;
3219 			break;
3220 		}
3221 	}
3222 
3223 	xfrm_pol_hold(ret);
3224 
3225 	read_unlock_bh(&net->xfrm.xfrm_policy_lock);
3226 
3227 	return ret;
3228 }
3229 
3230 static int migrate_tmpl_match(const struct xfrm_migrate *m, const struct xfrm_tmpl *t)
3231 {
3232 	int match = 0;
3233 
3234 	if (t->mode == m->mode && t->id.proto == m->proto &&
3235 	    (m->reqid == 0 || t->reqid == m->reqid)) {
3236 		switch (t->mode) {
3237 		case XFRM_MODE_TUNNEL:
3238 		case XFRM_MODE_BEET:
3239 			if (xfrm_addr_equal(&t->id.daddr, &m->old_daddr,
3240 					    m->old_family) &&
3241 			    xfrm_addr_equal(&t->saddr, &m->old_saddr,
3242 					    m->old_family)) {
3243 				match = 1;
3244 			}
3245 			break;
3246 		case XFRM_MODE_TRANSPORT:
3247 			/* in case of transport mode, template does not store
3248 			   any IP addresses, hence we just compare mode and
3249 			   protocol */
3250 			match = 1;
3251 			break;
3252 		default:
3253 			break;
3254 		}
3255 	}
3256 	return match;
3257 }
3258 
3259 /* update endpoint address(es) of template(s) */
3260 static int xfrm_policy_migrate(struct xfrm_policy *pol,
3261 			       struct xfrm_migrate *m, int num_migrate)
3262 {
3263 	struct xfrm_migrate *mp;
3264 	int i, j, n = 0;
3265 
3266 	write_lock_bh(&pol->lock);
3267 	if (unlikely(pol->walk.dead)) {
3268 		/* target policy has been deleted */
3269 		write_unlock_bh(&pol->lock);
3270 		return -ENOENT;
3271 	}
3272 
3273 	for (i = 0; i < pol->xfrm_nr; i++) {
3274 		for (j = 0, mp = m; j < num_migrate; j++, mp++) {
3275 			if (!migrate_tmpl_match(mp, &pol->xfrm_vec[i]))
3276 				continue;
3277 			n++;
3278 			if (pol->xfrm_vec[i].mode != XFRM_MODE_TUNNEL &&
3279 			    pol->xfrm_vec[i].mode != XFRM_MODE_BEET)
3280 				continue;
3281 			/* update endpoints */
3282 			memcpy(&pol->xfrm_vec[i].id.daddr, &mp->new_daddr,
3283 			       sizeof(pol->xfrm_vec[i].id.daddr));
3284 			memcpy(&pol->xfrm_vec[i].saddr, &mp->new_saddr,
3285 			       sizeof(pol->xfrm_vec[i].saddr));
3286 			pol->xfrm_vec[i].encap_family = mp->new_family;
3287 			/* flush bundles */
3288 			atomic_inc(&pol->genid);
3289 		}
3290 	}
3291 
3292 	write_unlock_bh(&pol->lock);
3293 
3294 	if (!n)
3295 		return -ENODATA;
3296 
3297 	return 0;
3298 }
3299 
3300 static int xfrm_migrate_check(const struct xfrm_migrate *m, int num_migrate)
3301 {
3302 	int i, j;
3303 
3304 	if (num_migrate < 1 || num_migrate > XFRM_MAX_DEPTH)
3305 		return -EINVAL;
3306 
3307 	for (i = 0; i < num_migrate; i++) {
3308 		if (xfrm_addr_equal(&m[i].old_daddr, &m[i].new_daddr,
3309 				    m[i].old_family) &&
3310 		    xfrm_addr_equal(&m[i].old_saddr, &m[i].new_saddr,
3311 				    m[i].old_family))
3312 			return -EINVAL;
3313 		if (xfrm_addr_any(&m[i].new_daddr, m[i].new_family) ||
3314 		    xfrm_addr_any(&m[i].new_saddr, m[i].new_family))
3315 			return -EINVAL;
3316 
3317 		/* check if there is any duplicated entry */
3318 		for (j = i + 1; j < num_migrate; j++) {
3319 			if (!memcmp(&m[i].old_daddr, &m[j].old_daddr,
3320 				    sizeof(m[i].old_daddr)) &&
3321 			    !memcmp(&m[i].old_saddr, &m[j].old_saddr,
3322 				    sizeof(m[i].old_saddr)) &&
3323 			    m[i].proto == m[j].proto &&
3324 			    m[i].mode == m[j].mode &&
3325 			    m[i].reqid == m[j].reqid &&
3326 			    m[i].old_family == m[j].old_family)
3327 				return -EINVAL;
3328 		}
3329 	}
3330 
3331 	return 0;
3332 }
3333 
3334 int xfrm_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
3335 		 struct xfrm_migrate *m, int num_migrate,
3336 		 struct xfrm_kmaddress *k, struct net *net)
3337 {
3338 	int i, err, nx_cur = 0, nx_new = 0;
3339 	struct xfrm_policy *pol = NULL;
3340 	struct xfrm_state *x, *xc;
3341 	struct xfrm_state *x_cur[XFRM_MAX_DEPTH];
3342 	struct xfrm_state *x_new[XFRM_MAX_DEPTH];
3343 	struct xfrm_migrate *mp;
3344 
3345 	if ((err = xfrm_migrate_check(m, num_migrate)) < 0)
3346 		goto out;
3347 
3348 	/* Stage 1 - find policy */
3349 	if ((pol = xfrm_migrate_policy_find(sel, dir, type, net)) == NULL) {
3350 		err = -ENOENT;
3351 		goto out;
3352 	}
3353 
3354 	/* Stage 2 - find and update state(s) */
3355 	for (i = 0, mp = m; i < num_migrate; i++, mp++) {
3356 		if ((x = xfrm_migrate_state_find(mp, net))) {
3357 			x_cur[nx_cur] = x;
3358 			nx_cur++;
3359 			if ((xc = xfrm_state_migrate(x, mp))) {
3360 				x_new[nx_new] = xc;
3361 				nx_new++;
3362 			} else {
3363 				err = -ENODATA;
3364 				goto restore_state;
3365 			}
3366 		}
3367 	}
3368 
3369 	/* Stage 3 - update policy */
3370 	if ((err = xfrm_policy_migrate(pol, m, num_migrate)) < 0)
3371 		goto restore_state;
3372 
3373 	/* Stage 4 - delete old state(s) */
3374 	if (nx_cur) {
3375 		xfrm_states_put(x_cur, nx_cur);
3376 		xfrm_states_delete(x_cur, nx_cur);
3377 	}
3378 
3379 	/* Stage 5 - announce */
3380 	km_migrate(sel, dir, type, m, num_migrate, k);
3381 
3382 	xfrm_pol_put(pol);
3383 
3384 	return 0;
3385 out:
3386 	return err;
3387 
3388 restore_state:
3389 	if (pol)
3390 		xfrm_pol_put(pol);
3391 	if (nx_cur)
3392 		xfrm_states_put(x_cur, nx_cur);
3393 	if (nx_new)
3394 		xfrm_states_delete(x_new, nx_new);
3395 
3396 	return err;
3397 }
3398 EXPORT_SYMBOL(xfrm_migrate);
3399 #endif
3400