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