xref: /linux/net/xfrm/xfrm_policy.c (revision 69fb09f6ccdb2f070557fd1f4c56c4d646694c8e)
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 struct dst_entry *__xfrm_dst_lookup(struct net *net, int tos, int oif,
120 				    const xfrm_address_t *saddr,
121 				    const xfrm_address_t *daddr,
122 				    int family)
123 {
124 	const struct xfrm_policy_afinfo *afinfo;
125 	struct dst_entry *dst;
126 
127 	afinfo = xfrm_policy_get_afinfo(family);
128 	if (unlikely(afinfo == NULL))
129 		return ERR_PTR(-EAFNOSUPPORT);
130 
131 	dst = afinfo->dst_lookup(net, tos, oif, saddr, daddr);
132 
133 	rcu_read_unlock();
134 
135 	return dst;
136 }
137 EXPORT_SYMBOL(__xfrm_dst_lookup);
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, u16 family)
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, family);
1255 		int err = 0;
1256 
1257 		if (match) {
1258 			if ((sk->sk_mark & pol->mark.m) != pol->mark.v) {
1259 				pol = NULL;
1260 				goto out;
1261 			}
1262 			err = security_xfrm_policy_lookup(pol->security,
1263 						      fl->flowi_secid,
1264 						      policy_to_flow_dir(dir));
1265 			if (!err) {
1266 				if (!xfrm_pol_hold_rcu(pol))
1267 					goto again;
1268 			} else if (err == -ESRCH) {
1269 				pol = NULL;
1270 			} else {
1271 				pol = ERR_PTR(err);
1272 			}
1273 		} else
1274 			pol = NULL;
1275 	}
1276 out:
1277 	rcu_read_unlock();
1278 	return pol;
1279 }
1280 
1281 static void __xfrm_policy_link(struct xfrm_policy *pol, int dir)
1282 {
1283 	struct net *net = xp_net(pol);
1284 
1285 	list_add(&pol->walk.all, &net->xfrm.policy_all);
1286 	net->xfrm.policy_count[dir]++;
1287 	xfrm_pol_hold(pol);
1288 }
1289 
1290 static struct xfrm_policy *__xfrm_policy_unlink(struct xfrm_policy *pol,
1291 						int dir)
1292 {
1293 	struct net *net = xp_net(pol);
1294 
1295 	if (list_empty(&pol->walk.all))
1296 		return NULL;
1297 
1298 	/* Socket policies are not hashed. */
1299 	if (!hlist_unhashed(&pol->bydst)) {
1300 		hlist_del_rcu(&pol->bydst);
1301 		hlist_del(&pol->byidx);
1302 	}
1303 
1304 	list_del_init(&pol->walk.all);
1305 	net->xfrm.policy_count[dir]--;
1306 
1307 	return pol;
1308 }
1309 
1310 static void xfrm_sk_policy_link(struct xfrm_policy *pol, int dir)
1311 {
1312 	__xfrm_policy_link(pol, XFRM_POLICY_MAX + dir);
1313 }
1314 
1315 static void xfrm_sk_policy_unlink(struct xfrm_policy *pol, int dir)
1316 {
1317 	__xfrm_policy_unlink(pol, XFRM_POLICY_MAX + dir);
1318 }
1319 
1320 int xfrm_policy_delete(struct xfrm_policy *pol, int dir)
1321 {
1322 	struct net *net = xp_net(pol);
1323 
1324 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1325 	pol = __xfrm_policy_unlink(pol, dir);
1326 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1327 	if (pol) {
1328 		xfrm_policy_kill(pol);
1329 		return 0;
1330 	}
1331 	return -ENOENT;
1332 }
1333 EXPORT_SYMBOL(xfrm_policy_delete);
1334 
1335 int xfrm_sk_policy_insert(struct sock *sk, int dir, struct xfrm_policy *pol)
1336 {
1337 	struct net *net = xp_net(pol);
1338 	struct xfrm_policy *old_pol;
1339 
1340 #ifdef CONFIG_XFRM_SUB_POLICY
1341 	if (pol && pol->type != XFRM_POLICY_TYPE_MAIN)
1342 		return -EINVAL;
1343 #endif
1344 
1345 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1346 	old_pol = rcu_dereference_protected(sk->sk_policy[dir],
1347 				lockdep_is_held(&net->xfrm.xfrm_policy_lock));
1348 	if (pol) {
1349 		pol->curlft.add_time = get_seconds();
1350 		pol->index = xfrm_gen_index(net, XFRM_POLICY_MAX+dir, 0);
1351 		xfrm_sk_policy_link(pol, dir);
1352 	}
1353 	rcu_assign_pointer(sk->sk_policy[dir], pol);
1354 	if (old_pol) {
1355 		if (pol)
1356 			xfrm_policy_requeue(old_pol, pol);
1357 
1358 		/* Unlinking succeeds always. This is the only function
1359 		 * allowed to delete or replace socket policy.
1360 		 */
1361 		xfrm_sk_policy_unlink(old_pol, dir);
1362 	}
1363 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1364 
1365 	if (old_pol) {
1366 		xfrm_policy_kill(old_pol);
1367 	}
1368 	return 0;
1369 }
1370 
1371 static struct xfrm_policy *clone_policy(const struct xfrm_policy *old, int dir)
1372 {
1373 	struct xfrm_policy *newp = xfrm_policy_alloc(xp_net(old), GFP_ATOMIC);
1374 	struct net *net = xp_net(old);
1375 
1376 	if (newp) {
1377 		newp->selector = old->selector;
1378 		if (security_xfrm_policy_clone(old->security,
1379 					       &newp->security)) {
1380 			kfree(newp);
1381 			return NULL;  /* ENOMEM */
1382 		}
1383 		newp->lft = old->lft;
1384 		newp->curlft = old->curlft;
1385 		newp->mark = old->mark;
1386 		newp->action = old->action;
1387 		newp->flags = old->flags;
1388 		newp->xfrm_nr = old->xfrm_nr;
1389 		newp->index = old->index;
1390 		newp->type = old->type;
1391 		memcpy(newp->xfrm_vec, old->xfrm_vec,
1392 		       newp->xfrm_nr*sizeof(struct xfrm_tmpl));
1393 		spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1394 		xfrm_sk_policy_link(newp, dir);
1395 		spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1396 		xfrm_pol_put(newp);
1397 	}
1398 	return newp;
1399 }
1400 
1401 int __xfrm_sk_clone_policy(struct sock *sk, const struct sock *osk)
1402 {
1403 	const struct xfrm_policy *p;
1404 	struct xfrm_policy *np;
1405 	int i, ret = 0;
1406 
1407 	rcu_read_lock();
1408 	for (i = 0; i < 2; i++) {
1409 		p = rcu_dereference(osk->sk_policy[i]);
1410 		if (p) {
1411 			np = clone_policy(p, i);
1412 			if (unlikely(!np)) {
1413 				ret = -ENOMEM;
1414 				break;
1415 			}
1416 			rcu_assign_pointer(sk->sk_policy[i], np);
1417 		}
1418 	}
1419 	rcu_read_unlock();
1420 	return ret;
1421 }
1422 
1423 static int
1424 xfrm_get_saddr(struct net *net, int oif, xfrm_address_t *local,
1425 	       xfrm_address_t *remote, unsigned short family)
1426 {
1427 	int err;
1428 	const struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1429 
1430 	if (unlikely(afinfo == NULL))
1431 		return -EINVAL;
1432 	err = afinfo->get_saddr(net, oif, local, remote);
1433 	rcu_read_unlock();
1434 	return err;
1435 }
1436 
1437 /* Resolve list of templates for the flow, given policy. */
1438 
1439 static int
1440 xfrm_tmpl_resolve_one(struct xfrm_policy *policy, const struct flowi *fl,
1441 		      struct xfrm_state **xfrm, unsigned short family)
1442 {
1443 	struct net *net = xp_net(policy);
1444 	int nx;
1445 	int i, error;
1446 	xfrm_address_t *daddr = xfrm_flowi_daddr(fl, family);
1447 	xfrm_address_t *saddr = xfrm_flowi_saddr(fl, family);
1448 	xfrm_address_t tmp;
1449 
1450 	for (nx = 0, i = 0; i < policy->xfrm_nr; i++) {
1451 		struct xfrm_state *x;
1452 		xfrm_address_t *remote = daddr;
1453 		xfrm_address_t *local  = saddr;
1454 		struct xfrm_tmpl *tmpl = &policy->xfrm_vec[i];
1455 
1456 		if (tmpl->mode == XFRM_MODE_TUNNEL ||
1457 		    tmpl->mode == XFRM_MODE_BEET) {
1458 			remote = &tmpl->id.daddr;
1459 			local = &tmpl->saddr;
1460 			if (xfrm_addr_any(local, tmpl->encap_family)) {
1461 				error = xfrm_get_saddr(net, fl->flowi_oif,
1462 						       &tmp, remote,
1463 						       tmpl->encap_family);
1464 				if (error)
1465 					goto fail;
1466 				local = &tmp;
1467 			}
1468 		}
1469 
1470 		x = xfrm_state_find(remote, local, fl, tmpl, policy, &error, family);
1471 
1472 		if (x && x->km.state == XFRM_STATE_VALID) {
1473 			xfrm[nx++] = x;
1474 			daddr = remote;
1475 			saddr = local;
1476 			continue;
1477 		}
1478 		if (x) {
1479 			error = (x->km.state == XFRM_STATE_ERROR ?
1480 				 -EINVAL : -EAGAIN);
1481 			xfrm_state_put(x);
1482 		} else if (error == -ESRCH) {
1483 			error = -EAGAIN;
1484 		}
1485 
1486 		if (!tmpl->optional)
1487 			goto fail;
1488 	}
1489 	return nx;
1490 
1491 fail:
1492 	for (nx--; nx >= 0; nx--)
1493 		xfrm_state_put(xfrm[nx]);
1494 	return error;
1495 }
1496 
1497 static int
1498 xfrm_tmpl_resolve(struct xfrm_policy **pols, int npols, const struct flowi *fl,
1499 		  struct xfrm_state **xfrm, unsigned short family)
1500 {
1501 	struct xfrm_state *tp[XFRM_MAX_DEPTH];
1502 	struct xfrm_state **tpp = (npols > 1) ? tp : xfrm;
1503 	int cnx = 0;
1504 	int error;
1505 	int ret;
1506 	int i;
1507 
1508 	for (i = 0; i < npols; i++) {
1509 		if (cnx + pols[i]->xfrm_nr >= XFRM_MAX_DEPTH) {
1510 			error = -ENOBUFS;
1511 			goto fail;
1512 		}
1513 
1514 		ret = xfrm_tmpl_resolve_one(pols[i], fl, &tpp[cnx], family);
1515 		if (ret < 0) {
1516 			error = ret;
1517 			goto fail;
1518 		} else
1519 			cnx += ret;
1520 	}
1521 
1522 	/* found states are sorted for outbound processing */
1523 	if (npols > 1)
1524 		xfrm_state_sort(xfrm, tpp, cnx, family);
1525 
1526 	return cnx;
1527 
1528  fail:
1529 	for (cnx--; cnx >= 0; cnx--)
1530 		xfrm_state_put(tpp[cnx]);
1531 	return error;
1532 
1533 }
1534 
1535 static int xfrm_get_tos(const struct flowi *fl, int family)
1536 {
1537 	const struct xfrm_policy_afinfo *afinfo;
1538 	int tos = 0;
1539 
1540 	afinfo = xfrm_policy_get_afinfo(family);
1541 	tos = afinfo ? afinfo->get_tos(fl) : 0;
1542 
1543 	rcu_read_unlock();
1544 
1545 	return tos;
1546 }
1547 
1548 static struct flow_cache_object *xfrm_bundle_flo_get(struct flow_cache_object *flo)
1549 {
1550 	struct xfrm_dst *xdst = container_of(flo, struct xfrm_dst, flo);
1551 	struct dst_entry *dst = &xdst->u.dst;
1552 
1553 	if (xdst->route == NULL) {
1554 		/* Dummy bundle - if it has xfrms we were not
1555 		 * able to build bundle as template resolution failed.
1556 		 * It means we need to try again resolving. */
1557 		if (xdst->num_xfrms > 0)
1558 			return NULL;
1559 	} else if (dst->flags & DST_XFRM_QUEUE) {
1560 		return NULL;
1561 	} else {
1562 		/* Real bundle */
1563 		if (stale_bundle(dst))
1564 			return NULL;
1565 	}
1566 
1567 	dst_hold(dst);
1568 	return flo;
1569 }
1570 
1571 static int xfrm_bundle_flo_check(struct flow_cache_object *flo)
1572 {
1573 	struct xfrm_dst *xdst = container_of(flo, struct xfrm_dst, flo);
1574 	struct dst_entry *dst = &xdst->u.dst;
1575 
1576 	if (!xdst->route)
1577 		return 0;
1578 	if (stale_bundle(dst))
1579 		return 0;
1580 
1581 	return 1;
1582 }
1583 
1584 static void xfrm_bundle_flo_delete(struct flow_cache_object *flo)
1585 {
1586 	struct xfrm_dst *xdst = container_of(flo, struct xfrm_dst, flo);
1587 	struct dst_entry *dst = &xdst->u.dst;
1588 
1589 	dst_free(dst);
1590 }
1591 
1592 static const struct flow_cache_ops xfrm_bundle_fc_ops = {
1593 	.get = xfrm_bundle_flo_get,
1594 	.check = xfrm_bundle_flo_check,
1595 	.delete = xfrm_bundle_flo_delete,
1596 };
1597 
1598 static inline struct xfrm_dst *xfrm_alloc_dst(struct net *net, int family)
1599 {
1600 	const struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1601 	struct dst_ops *dst_ops;
1602 	struct xfrm_dst *xdst;
1603 
1604 	if (!afinfo)
1605 		return ERR_PTR(-EINVAL);
1606 
1607 	switch (family) {
1608 	case AF_INET:
1609 		dst_ops = &net->xfrm.xfrm4_dst_ops;
1610 		break;
1611 #if IS_ENABLED(CONFIG_IPV6)
1612 	case AF_INET6:
1613 		dst_ops = &net->xfrm.xfrm6_dst_ops;
1614 		break;
1615 #endif
1616 	default:
1617 		BUG();
1618 	}
1619 	xdst = dst_alloc(dst_ops, NULL, 0, DST_OBSOLETE_NONE, 0);
1620 
1621 	if (likely(xdst)) {
1622 		struct dst_entry *dst = &xdst->u.dst;
1623 
1624 		memset(dst + 1, 0, sizeof(*xdst) - sizeof(*dst));
1625 		xdst->flo.ops = &xfrm_bundle_fc_ops;
1626 	} else
1627 		xdst = ERR_PTR(-ENOBUFS);
1628 
1629 	rcu_read_unlock();
1630 
1631 	return xdst;
1632 }
1633 
1634 static inline int xfrm_init_path(struct xfrm_dst *path, struct dst_entry *dst,
1635 				 int nfheader_len)
1636 {
1637 	const struct xfrm_policy_afinfo *afinfo =
1638 		xfrm_policy_get_afinfo(dst->ops->family);
1639 	int err;
1640 
1641 	if (!afinfo)
1642 		return -EINVAL;
1643 
1644 	err = afinfo->init_path(path, dst, nfheader_len);
1645 
1646 	rcu_read_unlock();
1647 
1648 	return err;
1649 }
1650 
1651 static inline int xfrm_fill_dst(struct xfrm_dst *xdst, struct net_device *dev,
1652 				const struct flowi *fl)
1653 {
1654 	const struct xfrm_policy_afinfo *afinfo =
1655 		xfrm_policy_get_afinfo(xdst->u.dst.ops->family);
1656 	int err;
1657 
1658 	if (!afinfo)
1659 		return -EINVAL;
1660 
1661 	err = afinfo->fill_dst(xdst, dev, fl);
1662 
1663 	rcu_read_unlock();
1664 
1665 	return err;
1666 }
1667 
1668 
1669 /* Allocate chain of dst_entry's, attach known xfrm's, calculate
1670  * all the metrics... Shortly, bundle a bundle.
1671  */
1672 
1673 static struct dst_entry *xfrm_bundle_create(struct xfrm_policy *policy,
1674 					    struct xfrm_state **xfrm, int nx,
1675 					    const struct flowi *fl,
1676 					    struct dst_entry *dst)
1677 {
1678 	struct net *net = xp_net(policy);
1679 	unsigned long now = jiffies;
1680 	struct net_device *dev;
1681 	struct xfrm_mode *inner_mode;
1682 	struct dst_entry *dst_prev = NULL;
1683 	struct dst_entry *dst0 = NULL;
1684 	int i = 0;
1685 	int err;
1686 	int header_len = 0;
1687 	int nfheader_len = 0;
1688 	int trailer_len = 0;
1689 	int tos;
1690 	int family = policy->selector.family;
1691 	xfrm_address_t saddr, daddr;
1692 
1693 	xfrm_flowi_addr_get(fl, &saddr, &daddr, family);
1694 
1695 	tos = xfrm_get_tos(fl, family);
1696 
1697 	dst_hold(dst);
1698 
1699 	for (; i < nx; i++) {
1700 		struct xfrm_dst *xdst = xfrm_alloc_dst(net, family);
1701 		struct dst_entry *dst1 = &xdst->u.dst;
1702 
1703 		err = PTR_ERR(xdst);
1704 		if (IS_ERR(xdst)) {
1705 			dst_release(dst);
1706 			goto put_states;
1707 		}
1708 
1709 		if (xfrm[i]->sel.family == AF_UNSPEC) {
1710 			inner_mode = xfrm_ip2inner_mode(xfrm[i],
1711 							xfrm_af2proto(family));
1712 			if (!inner_mode) {
1713 				err = -EAFNOSUPPORT;
1714 				dst_release(dst);
1715 				goto put_states;
1716 			}
1717 		} else
1718 			inner_mode = xfrm[i]->inner_mode;
1719 
1720 		if (!dst_prev)
1721 			dst0 = dst1;
1722 		else {
1723 			dst_prev->child = dst_clone(dst1);
1724 			dst1->flags |= DST_NOHASH;
1725 		}
1726 
1727 		xdst->route = dst;
1728 		dst_copy_metrics(dst1, dst);
1729 
1730 		if (xfrm[i]->props.mode != XFRM_MODE_TRANSPORT) {
1731 			family = xfrm[i]->props.family;
1732 			dst = xfrm_dst_lookup(xfrm[i], tos, fl->flowi_oif,
1733 					      &saddr, &daddr, family);
1734 			err = PTR_ERR(dst);
1735 			if (IS_ERR(dst))
1736 				goto put_states;
1737 		} else
1738 			dst_hold(dst);
1739 
1740 		dst1->xfrm = xfrm[i];
1741 		xdst->xfrm_genid = xfrm[i]->genid;
1742 
1743 		dst1->obsolete = DST_OBSOLETE_FORCE_CHK;
1744 		dst1->flags |= DST_HOST;
1745 		dst1->lastuse = now;
1746 
1747 		dst1->input = dst_discard;
1748 		dst1->output = inner_mode->afinfo->output;
1749 
1750 		dst1->next = dst_prev;
1751 		dst_prev = dst1;
1752 
1753 		header_len += xfrm[i]->props.header_len;
1754 		if (xfrm[i]->type->flags & XFRM_TYPE_NON_FRAGMENT)
1755 			nfheader_len += xfrm[i]->props.header_len;
1756 		trailer_len += xfrm[i]->props.trailer_len;
1757 	}
1758 
1759 	dst_prev->child = dst;
1760 	dst0->path = dst;
1761 
1762 	err = -ENODEV;
1763 	dev = dst->dev;
1764 	if (!dev)
1765 		goto free_dst;
1766 
1767 	xfrm_init_path((struct xfrm_dst *)dst0, dst, nfheader_len);
1768 	xfrm_init_pmtu(dst_prev);
1769 
1770 	for (dst_prev = dst0; dst_prev != dst; dst_prev = dst_prev->child) {
1771 		struct xfrm_dst *xdst = (struct xfrm_dst *)dst_prev;
1772 
1773 		err = xfrm_fill_dst(xdst, dev, fl);
1774 		if (err)
1775 			goto free_dst;
1776 
1777 		dst_prev->header_len = header_len;
1778 		dst_prev->trailer_len = trailer_len;
1779 		header_len -= xdst->u.dst.xfrm->props.header_len;
1780 		trailer_len -= xdst->u.dst.xfrm->props.trailer_len;
1781 	}
1782 
1783 out:
1784 	return dst0;
1785 
1786 put_states:
1787 	for (; i < nx; i++)
1788 		xfrm_state_put(xfrm[i]);
1789 free_dst:
1790 	if (dst0)
1791 		dst_free(dst0);
1792 	dst0 = ERR_PTR(err);
1793 	goto out;
1794 }
1795 
1796 static int xfrm_expand_policies(const struct flowi *fl, u16 family,
1797 				struct xfrm_policy **pols,
1798 				int *num_pols, int *num_xfrms)
1799 {
1800 	int i;
1801 
1802 	if (*num_pols == 0 || !pols[0]) {
1803 		*num_pols = 0;
1804 		*num_xfrms = 0;
1805 		return 0;
1806 	}
1807 	if (IS_ERR(pols[0]))
1808 		return PTR_ERR(pols[0]);
1809 
1810 	*num_xfrms = pols[0]->xfrm_nr;
1811 
1812 #ifdef CONFIG_XFRM_SUB_POLICY
1813 	if (pols[0] && pols[0]->action == XFRM_POLICY_ALLOW &&
1814 	    pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
1815 		pols[1] = xfrm_policy_lookup_bytype(xp_net(pols[0]),
1816 						    XFRM_POLICY_TYPE_MAIN,
1817 						    fl, family,
1818 						    XFRM_POLICY_OUT);
1819 		if (pols[1]) {
1820 			if (IS_ERR(pols[1])) {
1821 				xfrm_pols_put(pols, *num_pols);
1822 				return PTR_ERR(pols[1]);
1823 			}
1824 			(*num_pols)++;
1825 			(*num_xfrms) += pols[1]->xfrm_nr;
1826 		}
1827 	}
1828 #endif
1829 	for (i = 0; i < *num_pols; i++) {
1830 		if (pols[i]->action != XFRM_POLICY_ALLOW) {
1831 			*num_xfrms = -1;
1832 			break;
1833 		}
1834 	}
1835 
1836 	return 0;
1837 
1838 }
1839 
1840 static struct xfrm_dst *
1841 xfrm_resolve_and_create_bundle(struct xfrm_policy **pols, int num_pols,
1842 			       const struct flowi *fl, u16 family,
1843 			       struct dst_entry *dst_orig)
1844 {
1845 	struct net *net = xp_net(pols[0]);
1846 	struct xfrm_state *xfrm[XFRM_MAX_DEPTH];
1847 	struct dst_entry *dst;
1848 	struct xfrm_dst *xdst;
1849 	int err;
1850 
1851 	/* Try to instantiate a bundle */
1852 	err = xfrm_tmpl_resolve(pols, num_pols, fl, xfrm, family);
1853 	if (err <= 0) {
1854 		if (err != 0 && err != -EAGAIN)
1855 			XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLERROR);
1856 		return ERR_PTR(err);
1857 	}
1858 
1859 	dst = xfrm_bundle_create(pols[0], xfrm, err, fl, dst_orig);
1860 	if (IS_ERR(dst)) {
1861 		XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTBUNDLEGENERROR);
1862 		return ERR_CAST(dst);
1863 	}
1864 
1865 	xdst = (struct xfrm_dst *)dst;
1866 	xdst->num_xfrms = err;
1867 	xdst->num_pols = num_pols;
1868 	memcpy(xdst->pols, pols, sizeof(struct xfrm_policy *) * num_pols);
1869 	xdst->policy_genid = atomic_read(&pols[0]->genid);
1870 
1871 	return xdst;
1872 }
1873 
1874 static void xfrm_policy_queue_process(unsigned long arg)
1875 {
1876 	struct sk_buff *skb;
1877 	struct sock *sk;
1878 	struct dst_entry *dst;
1879 	struct xfrm_policy *pol = (struct xfrm_policy *)arg;
1880 	struct net *net = xp_net(pol);
1881 	struct xfrm_policy_queue *pq = &pol->polq;
1882 	struct flowi fl;
1883 	struct sk_buff_head list;
1884 
1885 	spin_lock(&pq->hold_queue.lock);
1886 	skb = skb_peek(&pq->hold_queue);
1887 	if (!skb) {
1888 		spin_unlock(&pq->hold_queue.lock);
1889 		goto out;
1890 	}
1891 	dst = skb_dst(skb);
1892 	sk = skb->sk;
1893 	xfrm_decode_session(skb, &fl, dst->ops->family);
1894 	spin_unlock(&pq->hold_queue.lock);
1895 
1896 	dst_hold(dst->path);
1897 	dst = xfrm_lookup(net, dst->path, &fl, sk, 0);
1898 	if (IS_ERR(dst))
1899 		goto purge_queue;
1900 
1901 	if (dst->flags & DST_XFRM_QUEUE) {
1902 		dst_release(dst);
1903 
1904 		if (pq->timeout >= XFRM_QUEUE_TMO_MAX)
1905 			goto purge_queue;
1906 
1907 		pq->timeout = pq->timeout << 1;
1908 		if (!mod_timer(&pq->hold_timer, jiffies + pq->timeout))
1909 			xfrm_pol_hold(pol);
1910 	goto out;
1911 	}
1912 
1913 	dst_release(dst);
1914 
1915 	__skb_queue_head_init(&list);
1916 
1917 	spin_lock(&pq->hold_queue.lock);
1918 	pq->timeout = 0;
1919 	skb_queue_splice_init(&pq->hold_queue, &list);
1920 	spin_unlock(&pq->hold_queue.lock);
1921 
1922 	while (!skb_queue_empty(&list)) {
1923 		skb = __skb_dequeue(&list);
1924 
1925 		xfrm_decode_session(skb, &fl, skb_dst(skb)->ops->family);
1926 		dst_hold(skb_dst(skb)->path);
1927 		dst = xfrm_lookup(net, skb_dst(skb)->path, &fl, skb->sk, 0);
1928 		if (IS_ERR(dst)) {
1929 			kfree_skb(skb);
1930 			continue;
1931 		}
1932 
1933 		nf_reset(skb);
1934 		skb_dst_drop(skb);
1935 		skb_dst_set(skb, dst);
1936 
1937 		dst_output(net, skb->sk, skb);
1938 	}
1939 
1940 out:
1941 	xfrm_pol_put(pol);
1942 	return;
1943 
1944 purge_queue:
1945 	pq->timeout = 0;
1946 	skb_queue_purge(&pq->hold_queue);
1947 	xfrm_pol_put(pol);
1948 }
1949 
1950 static int xdst_queue_output(struct net *net, struct sock *sk, struct sk_buff *skb)
1951 {
1952 	unsigned long sched_next;
1953 	struct dst_entry *dst = skb_dst(skb);
1954 	struct xfrm_dst *xdst = (struct xfrm_dst *) dst;
1955 	struct xfrm_policy *pol = xdst->pols[0];
1956 	struct xfrm_policy_queue *pq = &pol->polq;
1957 
1958 	if (unlikely(skb_fclone_busy(sk, skb))) {
1959 		kfree_skb(skb);
1960 		return 0;
1961 	}
1962 
1963 	if (pq->hold_queue.qlen > XFRM_MAX_QUEUE_LEN) {
1964 		kfree_skb(skb);
1965 		return -EAGAIN;
1966 	}
1967 
1968 	skb_dst_force(skb);
1969 
1970 	spin_lock_bh(&pq->hold_queue.lock);
1971 
1972 	if (!pq->timeout)
1973 		pq->timeout = XFRM_QUEUE_TMO_MIN;
1974 
1975 	sched_next = jiffies + pq->timeout;
1976 
1977 	if (del_timer(&pq->hold_timer)) {
1978 		if (time_before(pq->hold_timer.expires, sched_next))
1979 			sched_next = pq->hold_timer.expires;
1980 		xfrm_pol_put(pol);
1981 	}
1982 
1983 	__skb_queue_tail(&pq->hold_queue, skb);
1984 	if (!mod_timer(&pq->hold_timer, sched_next))
1985 		xfrm_pol_hold(pol);
1986 
1987 	spin_unlock_bh(&pq->hold_queue.lock);
1988 
1989 	return 0;
1990 }
1991 
1992 static struct xfrm_dst *xfrm_create_dummy_bundle(struct net *net,
1993 						 struct xfrm_flo *xflo,
1994 						 const struct flowi *fl,
1995 						 int num_xfrms,
1996 						 u16 family)
1997 {
1998 	int err;
1999 	struct net_device *dev;
2000 	struct dst_entry *dst;
2001 	struct dst_entry *dst1;
2002 	struct xfrm_dst *xdst;
2003 
2004 	xdst = xfrm_alloc_dst(net, family);
2005 	if (IS_ERR(xdst))
2006 		return xdst;
2007 
2008 	if (!(xflo->flags & XFRM_LOOKUP_QUEUE) ||
2009 	    net->xfrm.sysctl_larval_drop ||
2010 	    num_xfrms <= 0)
2011 		return xdst;
2012 
2013 	dst = xflo->dst_orig;
2014 	dst1 = &xdst->u.dst;
2015 	dst_hold(dst);
2016 	xdst->route = dst;
2017 
2018 	dst_copy_metrics(dst1, dst);
2019 
2020 	dst1->obsolete = DST_OBSOLETE_FORCE_CHK;
2021 	dst1->flags |= DST_HOST | DST_XFRM_QUEUE;
2022 	dst1->lastuse = jiffies;
2023 
2024 	dst1->input = dst_discard;
2025 	dst1->output = xdst_queue_output;
2026 
2027 	dst_hold(dst);
2028 	dst1->child = dst;
2029 	dst1->path = dst;
2030 
2031 	xfrm_init_path((struct xfrm_dst *)dst1, dst, 0);
2032 
2033 	err = -ENODEV;
2034 	dev = dst->dev;
2035 	if (!dev)
2036 		goto free_dst;
2037 
2038 	err = xfrm_fill_dst(xdst, dev, fl);
2039 	if (err)
2040 		goto free_dst;
2041 
2042 out:
2043 	return xdst;
2044 
2045 free_dst:
2046 	dst_release(dst1);
2047 	xdst = ERR_PTR(err);
2048 	goto out;
2049 }
2050 
2051 static struct flow_cache_object *
2052 xfrm_bundle_lookup(struct net *net, const struct flowi *fl, u16 family, u8 dir,
2053 		   struct flow_cache_object *oldflo, void *ctx)
2054 {
2055 	struct xfrm_flo *xflo = (struct xfrm_flo *)ctx;
2056 	struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
2057 	struct xfrm_dst *xdst, *new_xdst;
2058 	int num_pols = 0, num_xfrms = 0, i, err, pol_dead;
2059 
2060 	/* Check if the policies from old bundle are usable */
2061 	xdst = NULL;
2062 	if (oldflo) {
2063 		xdst = container_of(oldflo, struct xfrm_dst, flo);
2064 		num_pols = xdst->num_pols;
2065 		num_xfrms = xdst->num_xfrms;
2066 		pol_dead = 0;
2067 		for (i = 0; i < num_pols; i++) {
2068 			pols[i] = xdst->pols[i];
2069 			pol_dead |= pols[i]->walk.dead;
2070 		}
2071 		if (pol_dead) {
2072 			dst_free(&xdst->u.dst);
2073 			xdst = NULL;
2074 			num_pols = 0;
2075 			num_xfrms = 0;
2076 			oldflo = NULL;
2077 		}
2078 	}
2079 
2080 	/* Resolve policies to use if we couldn't get them from
2081 	 * previous cache entry */
2082 	if (xdst == NULL) {
2083 		num_pols = 1;
2084 		pols[0] = __xfrm_policy_lookup(net, fl, family,
2085 					       flow_to_policy_dir(dir));
2086 		err = xfrm_expand_policies(fl, family, pols,
2087 					   &num_pols, &num_xfrms);
2088 		if (err < 0)
2089 			goto inc_error;
2090 		if (num_pols == 0)
2091 			return NULL;
2092 		if (num_xfrms <= 0)
2093 			goto make_dummy_bundle;
2094 	}
2095 
2096 	new_xdst = xfrm_resolve_and_create_bundle(pols, num_pols, fl, family,
2097 						  xflo->dst_orig);
2098 	if (IS_ERR(new_xdst)) {
2099 		err = PTR_ERR(new_xdst);
2100 		if (err != -EAGAIN)
2101 			goto error;
2102 		if (oldflo == NULL)
2103 			goto make_dummy_bundle;
2104 		dst_hold(&xdst->u.dst);
2105 		return oldflo;
2106 	} else if (new_xdst == NULL) {
2107 		num_xfrms = 0;
2108 		if (oldflo == NULL)
2109 			goto make_dummy_bundle;
2110 		xdst->num_xfrms = 0;
2111 		dst_hold(&xdst->u.dst);
2112 		return oldflo;
2113 	}
2114 
2115 	/* Kill the previous bundle */
2116 	if (xdst) {
2117 		/* The policies were stolen for newly generated bundle */
2118 		xdst->num_pols = 0;
2119 		dst_free(&xdst->u.dst);
2120 	}
2121 
2122 	/* Flow cache does not have reference, it dst_free()'s,
2123 	 * but we do need to return one reference for original caller */
2124 	dst_hold(&new_xdst->u.dst);
2125 	return &new_xdst->flo;
2126 
2127 make_dummy_bundle:
2128 	/* We found policies, but there's no bundles to instantiate:
2129 	 * either because the policy blocks, has no transformations or
2130 	 * we could not build template (no xfrm_states).*/
2131 	xdst = xfrm_create_dummy_bundle(net, xflo, fl, num_xfrms, family);
2132 	if (IS_ERR(xdst)) {
2133 		xfrm_pols_put(pols, num_pols);
2134 		return ERR_CAST(xdst);
2135 	}
2136 	xdst->num_pols = num_pols;
2137 	xdst->num_xfrms = num_xfrms;
2138 	memcpy(xdst->pols, pols, sizeof(struct xfrm_policy *) * num_pols);
2139 
2140 	dst_hold(&xdst->u.dst);
2141 	return &xdst->flo;
2142 
2143 inc_error:
2144 	XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLERROR);
2145 error:
2146 	if (xdst != NULL)
2147 		dst_free(&xdst->u.dst);
2148 	else
2149 		xfrm_pols_put(pols, num_pols);
2150 	return ERR_PTR(err);
2151 }
2152 
2153 static struct dst_entry *make_blackhole(struct net *net, u16 family,
2154 					struct dst_entry *dst_orig)
2155 {
2156 	const struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
2157 	struct dst_entry *ret;
2158 
2159 	if (!afinfo) {
2160 		dst_release(dst_orig);
2161 		return ERR_PTR(-EINVAL);
2162 	} else {
2163 		ret = afinfo->blackhole_route(net, dst_orig);
2164 	}
2165 	rcu_read_unlock();
2166 
2167 	return ret;
2168 }
2169 
2170 /* Main function: finds/creates a bundle for given flow.
2171  *
2172  * At the moment we eat a raw IP route. Mostly to speed up lookups
2173  * on interfaces with disabled IPsec.
2174  */
2175 struct dst_entry *xfrm_lookup(struct net *net, struct dst_entry *dst_orig,
2176 			      const struct flowi *fl,
2177 			      const struct sock *sk, int flags)
2178 {
2179 	struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
2180 	struct flow_cache_object *flo;
2181 	struct xfrm_dst *xdst;
2182 	struct dst_entry *dst, *route;
2183 	u16 family = dst_orig->ops->family;
2184 	u8 dir = policy_to_flow_dir(XFRM_POLICY_OUT);
2185 	int i, err, num_pols, num_xfrms = 0, drop_pols = 0;
2186 
2187 	dst = NULL;
2188 	xdst = NULL;
2189 	route = NULL;
2190 
2191 	sk = sk_const_to_full_sk(sk);
2192 	if (sk && sk->sk_policy[XFRM_POLICY_OUT]) {
2193 		num_pols = 1;
2194 		pols[0] = xfrm_sk_policy_lookup(sk, XFRM_POLICY_OUT, fl, family);
2195 		err = xfrm_expand_policies(fl, family, pols,
2196 					   &num_pols, &num_xfrms);
2197 		if (err < 0)
2198 			goto dropdst;
2199 
2200 		if (num_pols) {
2201 			if (num_xfrms <= 0) {
2202 				drop_pols = num_pols;
2203 				goto no_transform;
2204 			}
2205 
2206 			xdst = xfrm_resolve_and_create_bundle(
2207 					pols, num_pols, fl,
2208 					family, dst_orig);
2209 			if (IS_ERR(xdst)) {
2210 				xfrm_pols_put(pols, num_pols);
2211 				err = PTR_ERR(xdst);
2212 				goto dropdst;
2213 			} else if (xdst == NULL) {
2214 				num_xfrms = 0;
2215 				drop_pols = num_pols;
2216 				goto no_transform;
2217 			}
2218 
2219 			dst_hold(&xdst->u.dst);
2220 			xdst->u.dst.flags |= DST_NOCACHE;
2221 			route = xdst->route;
2222 		}
2223 	}
2224 
2225 	if (xdst == NULL) {
2226 		struct xfrm_flo xflo;
2227 
2228 		xflo.dst_orig = dst_orig;
2229 		xflo.flags = flags;
2230 
2231 		/* To accelerate a bit...  */
2232 		if ((dst_orig->flags & DST_NOXFRM) ||
2233 		    !net->xfrm.policy_count[XFRM_POLICY_OUT])
2234 			goto nopol;
2235 
2236 		flo = flow_cache_lookup(net, fl, family, dir,
2237 					xfrm_bundle_lookup, &xflo);
2238 		if (flo == NULL)
2239 			goto nopol;
2240 		if (IS_ERR(flo)) {
2241 			err = PTR_ERR(flo);
2242 			goto dropdst;
2243 		}
2244 		xdst = container_of(flo, struct xfrm_dst, flo);
2245 
2246 		num_pols = xdst->num_pols;
2247 		num_xfrms = xdst->num_xfrms;
2248 		memcpy(pols, xdst->pols, sizeof(struct xfrm_policy *) * num_pols);
2249 		route = xdst->route;
2250 	}
2251 
2252 	dst = &xdst->u.dst;
2253 	if (route == NULL && num_xfrms > 0) {
2254 		/* The only case when xfrm_bundle_lookup() returns a
2255 		 * bundle with null route, is when the template could
2256 		 * not be resolved. It means policies are there, but
2257 		 * bundle could not be created, since we don't yet
2258 		 * have the xfrm_state's. We need to wait for KM to
2259 		 * negotiate new SA's or bail out with error.*/
2260 		if (net->xfrm.sysctl_larval_drop) {
2261 			XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTNOSTATES);
2262 			err = -EREMOTE;
2263 			goto error;
2264 		}
2265 
2266 		err = -EAGAIN;
2267 
2268 		XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTNOSTATES);
2269 		goto error;
2270 	}
2271 
2272 no_transform:
2273 	if (num_pols == 0)
2274 		goto nopol;
2275 
2276 	if ((flags & XFRM_LOOKUP_ICMP) &&
2277 	    !(pols[0]->flags & XFRM_POLICY_ICMP)) {
2278 		err = -ENOENT;
2279 		goto error;
2280 	}
2281 
2282 	for (i = 0; i < num_pols; i++)
2283 		pols[i]->curlft.use_time = get_seconds();
2284 
2285 	if (num_xfrms < 0) {
2286 		/* Prohibit the flow */
2287 		XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLBLOCK);
2288 		err = -EPERM;
2289 		goto error;
2290 	} else if (num_xfrms > 0) {
2291 		/* Flow transformed */
2292 		dst_release(dst_orig);
2293 	} else {
2294 		/* Flow passes untransformed */
2295 		dst_release(dst);
2296 		dst = dst_orig;
2297 	}
2298 ok:
2299 	xfrm_pols_put(pols, drop_pols);
2300 	if (dst && dst->xfrm &&
2301 	    dst->xfrm->props.mode == XFRM_MODE_TUNNEL)
2302 		dst->flags |= DST_XFRM_TUNNEL;
2303 	return dst;
2304 
2305 nopol:
2306 	if (!(flags & XFRM_LOOKUP_ICMP)) {
2307 		dst = dst_orig;
2308 		goto ok;
2309 	}
2310 	err = -ENOENT;
2311 error:
2312 	dst_release(dst);
2313 dropdst:
2314 	if (!(flags & XFRM_LOOKUP_KEEP_DST_REF))
2315 		dst_release(dst_orig);
2316 	xfrm_pols_put(pols, drop_pols);
2317 	return ERR_PTR(err);
2318 }
2319 EXPORT_SYMBOL(xfrm_lookup);
2320 
2321 /* Callers of xfrm_lookup_route() must ensure a call to dst_output().
2322  * Otherwise we may send out blackholed packets.
2323  */
2324 struct dst_entry *xfrm_lookup_route(struct net *net, struct dst_entry *dst_orig,
2325 				    const struct flowi *fl,
2326 				    const struct sock *sk, int flags)
2327 {
2328 	struct dst_entry *dst = xfrm_lookup(net, dst_orig, fl, sk,
2329 					    flags | XFRM_LOOKUP_QUEUE |
2330 					    XFRM_LOOKUP_KEEP_DST_REF);
2331 
2332 	if (IS_ERR(dst) && PTR_ERR(dst) == -EREMOTE)
2333 		return make_blackhole(net, dst_orig->ops->family, dst_orig);
2334 
2335 	return dst;
2336 }
2337 EXPORT_SYMBOL(xfrm_lookup_route);
2338 
2339 static inline int
2340 xfrm_secpath_reject(int idx, struct sk_buff *skb, const struct flowi *fl)
2341 {
2342 	struct xfrm_state *x;
2343 
2344 	if (!skb->sp || idx < 0 || idx >= skb->sp->len)
2345 		return 0;
2346 	x = skb->sp->xvec[idx];
2347 	if (!x->type->reject)
2348 		return 0;
2349 	return x->type->reject(x, skb, fl);
2350 }
2351 
2352 /* When skb is transformed back to its "native" form, we have to
2353  * check policy restrictions. At the moment we make this in maximally
2354  * stupid way. Shame on me. :-) Of course, connected sockets must
2355  * have policy cached at them.
2356  */
2357 
2358 static inline int
2359 xfrm_state_ok(const struct xfrm_tmpl *tmpl, const struct xfrm_state *x,
2360 	      unsigned short family)
2361 {
2362 	if (xfrm_state_kern(x))
2363 		return tmpl->optional && !xfrm_state_addr_cmp(tmpl, x, tmpl->encap_family);
2364 	return	x->id.proto == tmpl->id.proto &&
2365 		(x->id.spi == tmpl->id.spi || !tmpl->id.spi) &&
2366 		(x->props.reqid == tmpl->reqid || !tmpl->reqid) &&
2367 		x->props.mode == tmpl->mode &&
2368 		(tmpl->allalgs || (tmpl->aalgos & (1<<x->props.aalgo)) ||
2369 		 !(xfrm_id_proto_match(tmpl->id.proto, IPSEC_PROTO_ANY))) &&
2370 		!(x->props.mode != XFRM_MODE_TRANSPORT &&
2371 		  xfrm_state_addr_cmp(tmpl, x, family));
2372 }
2373 
2374 /*
2375  * 0 or more than 0 is returned when validation is succeeded (either bypass
2376  * because of optional transport mode, or next index of the mathced secpath
2377  * state with the template.
2378  * -1 is returned when no matching template is found.
2379  * Otherwise "-2 - errored_index" is returned.
2380  */
2381 static inline int
2382 xfrm_policy_ok(const struct xfrm_tmpl *tmpl, const struct sec_path *sp, int start,
2383 	       unsigned short family)
2384 {
2385 	int idx = start;
2386 
2387 	if (tmpl->optional) {
2388 		if (tmpl->mode == XFRM_MODE_TRANSPORT)
2389 			return start;
2390 	} else
2391 		start = -1;
2392 	for (; idx < sp->len; idx++) {
2393 		if (xfrm_state_ok(tmpl, sp->xvec[idx], family))
2394 			return ++idx;
2395 		if (sp->xvec[idx]->props.mode != XFRM_MODE_TRANSPORT) {
2396 			if (start == -1)
2397 				start = -2-idx;
2398 			break;
2399 		}
2400 	}
2401 	return start;
2402 }
2403 
2404 int __xfrm_decode_session(struct sk_buff *skb, struct flowi *fl,
2405 			  unsigned int family, int reverse)
2406 {
2407 	const struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
2408 	int err;
2409 
2410 	if (unlikely(afinfo == NULL))
2411 		return -EAFNOSUPPORT;
2412 
2413 	afinfo->decode_session(skb, fl, reverse);
2414 	err = security_xfrm_decode_session(skb, &fl->flowi_secid);
2415 	rcu_read_unlock();
2416 	return err;
2417 }
2418 EXPORT_SYMBOL(__xfrm_decode_session);
2419 
2420 static inline int secpath_has_nontransport(const struct sec_path *sp, int k, int *idxp)
2421 {
2422 	for (; k < sp->len; k++) {
2423 		if (sp->xvec[k]->props.mode != XFRM_MODE_TRANSPORT) {
2424 			*idxp = k;
2425 			return 1;
2426 		}
2427 	}
2428 
2429 	return 0;
2430 }
2431 
2432 int __xfrm_policy_check(struct sock *sk, int dir, struct sk_buff *skb,
2433 			unsigned short family)
2434 {
2435 	struct net *net = dev_net(skb->dev);
2436 	struct xfrm_policy *pol;
2437 	struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
2438 	int npols = 0;
2439 	int xfrm_nr;
2440 	int pi;
2441 	int reverse;
2442 	struct flowi fl;
2443 	u8 fl_dir;
2444 	int xerr_idx = -1;
2445 
2446 	reverse = dir & ~XFRM_POLICY_MASK;
2447 	dir &= XFRM_POLICY_MASK;
2448 	fl_dir = policy_to_flow_dir(dir);
2449 
2450 	if (__xfrm_decode_session(skb, &fl, family, reverse) < 0) {
2451 		XFRM_INC_STATS(net, LINUX_MIB_XFRMINHDRERROR);
2452 		return 0;
2453 	}
2454 
2455 	nf_nat_decode_session(skb, &fl, family);
2456 
2457 	/* First, check used SA against their selectors. */
2458 	if (skb->sp) {
2459 		int i;
2460 
2461 		for (i = skb->sp->len-1; i >= 0; i--) {
2462 			struct xfrm_state *x = skb->sp->xvec[i];
2463 			if (!xfrm_selector_match(&x->sel, &fl, family)) {
2464 				XFRM_INC_STATS(net, LINUX_MIB_XFRMINSTATEMISMATCH);
2465 				return 0;
2466 			}
2467 		}
2468 	}
2469 
2470 	pol = NULL;
2471 	sk = sk_to_full_sk(sk);
2472 	if (sk && sk->sk_policy[dir]) {
2473 		pol = xfrm_sk_policy_lookup(sk, dir, &fl, family);
2474 		if (IS_ERR(pol)) {
2475 			XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
2476 			return 0;
2477 		}
2478 	}
2479 
2480 	if (!pol) {
2481 		struct flow_cache_object *flo;
2482 
2483 		flo = flow_cache_lookup(net, &fl, family, fl_dir,
2484 					xfrm_policy_lookup, NULL);
2485 		if (IS_ERR_OR_NULL(flo))
2486 			pol = ERR_CAST(flo);
2487 		else
2488 			pol = container_of(flo, struct xfrm_policy, flo);
2489 	}
2490 
2491 	if (IS_ERR(pol)) {
2492 		XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
2493 		return 0;
2494 	}
2495 
2496 	if (!pol) {
2497 		if (skb->sp && secpath_has_nontransport(skb->sp, 0, &xerr_idx)) {
2498 			xfrm_secpath_reject(xerr_idx, skb, &fl);
2499 			XFRM_INC_STATS(net, LINUX_MIB_XFRMINNOPOLS);
2500 			return 0;
2501 		}
2502 		return 1;
2503 	}
2504 
2505 	pol->curlft.use_time = get_seconds();
2506 
2507 	pols[0] = pol;
2508 	npols++;
2509 #ifdef CONFIG_XFRM_SUB_POLICY
2510 	if (pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
2511 		pols[1] = xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_MAIN,
2512 						    &fl, family,
2513 						    XFRM_POLICY_IN);
2514 		if (pols[1]) {
2515 			if (IS_ERR(pols[1])) {
2516 				XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
2517 				return 0;
2518 			}
2519 			pols[1]->curlft.use_time = get_seconds();
2520 			npols++;
2521 		}
2522 	}
2523 #endif
2524 
2525 	if (pol->action == XFRM_POLICY_ALLOW) {
2526 		struct sec_path *sp;
2527 		static struct sec_path dummy;
2528 		struct xfrm_tmpl *tp[XFRM_MAX_DEPTH];
2529 		struct xfrm_tmpl *stp[XFRM_MAX_DEPTH];
2530 		struct xfrm_tmpl **tpp = tp;
2531 		int ti = 0;
2532 		int i, k;
2533 
2534 		if ((sp = skb->sp) == NULL)
2535 			sp = &dummy;
2536 
2537 		for (pi = 0; pi < npols; pi++) {
2538 			if (pols[pi] != pol &&
2539 			    pols[pi]->action != XFRM_POLICY_ALLOW) {
2540 				XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLBLOCK);
2541 				goto reject;
2542 			}
2543 			if (ti + pols[pi]->xfrm_nr >= XFRM_MAX_DEPTH) {
2544 				XFRM_INC_STATS(net, LINUX_MIB_XFRMINBUFFERERROR);
2545 				goto reject_error;
2546 			}
2547 			for (i = 0; i < pols[pi]->xfrm_nr; i++)
2548 				tpp[ti++] = &pols[pi]->xfrm_vec[i];
2549 		}
2550 		xfrm_nr = ti;
2551 		if (npols > 1) {
2552 			xfrm_tmpl_sort(stp, tpp, xfrm_nr, family, net);
2553 			tpp = stp;
2554 		}
2555 
2556 		/* For each tunnel xfrm, find the first matching tmpl.
2557 		 * For each tmpl before that, find corresponding xfrm.
2558 		 * Order is _important_. Later we will implement
2559 		 * some barriers, but at the moment barriers
2560 		 * are implied between each two transformations.
2561 		 */
2562 		for (i = xfrm_nr-1, k = 0; i >= 0; i--) {
2563 			k = xfrm_policy_ok(tpp[i], sp, k, family);
2564 			if (k < 0) {
2565 				if (k < -1)
2566 					/* "-2 - errored_index" returned */
2567 					xerr_idx = -(2+k);
2568 				XFRM_INC_STATS(net, LINUX_MIB_XFRMINTMPLMISMATCH);
2569 				goto reject;
2570 			}
2571 		}
2572 
2573 		if (secpath_has_nontransport(sp, k, &xerr_idx)) {
2574 			XFRM_INC_STATS(net, LINUX_MIB_XFRMINTMPLMISMATCH);
2575 			goto reject;
2576 		}
2577 
2578 		xfrm_pols_put(pols, npols);
2579 		return 1;
2580 	}
2581 	XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLBLOCK);
2582 
2583 reject:
2584 	xfrm_secpath_reject(xerr_idx, skb, &fl);
2585 reject_error:
2586 	xfrm_pols_put(pols, npols);
2587 	return 0;
2588 }
2589 EXPORT_SYMBOL(__xfrm_policy_check);
2590 
2591 int __xfrm_route_forward(struct sk_buff *skb, unsigned short family)
2592 {
2593 	struct net *net = dev_net(skb->dev);
2594 	struct flowi fl;
2595 	struct dst_entry *dst;
2596 	int res = 1;
2597 
2598 	if (xfrm_decode_session(skb, &fl, family) < 0) {
2599 		XFRM_INC_STATS(net, LINUX_MIB_XFRMFWDHDRERROR);
2600 		return 0;
2601 	}
2602 
2603 	skb_dst_force(skb);
2604 
2605 	dst = xfrm_lookup(net, skb_dst(skb), &fl, NULL, XFRM_LOOKUP_QUEUE);
2606 	if (IS_ERR(dst)) {
2607 		res = 0;
2608 		dst = NULL;
2609 	}
2610 	skb_dst_set(skb, dst);
2611 	return res;
2612 }
2613 EXPORT_SYMBOL(__xfrm_route_forward);
2614 
2615 /* Optimize later using cookies and generation ids. */
2616 
2617 static struct dst_entry *xfrm_dst_check(struct dst_entry *dst, u32 cookie)
2618 {
2619 	/* Code (such as __xfrm4_bundle_create()) sets dst->obsolete
2620 	 * to DST_OBSOLETE_FORCE_CHK to force all XFRM destinations to
2621 	 * get validated by dst_ops->check on every use.  We do this
2622 	 * because when a normal route referenced by an XFRM dst is
2623 	 * obsoleted we do not go looking around for all parent
2624 	 * referencing XFRM dsts so that we can invalidate them.  It
2625 	 * is just too much work.  Instead we make the checks here on
2626 	 * every use.  For example:
2627 	 *
2628 	 *	XFRM dst A --> IPv4 dst X
2629 	 *
2630 	 * X is the "xdst->route" of A (X is also the "dst->path" of A
2631 	 * in this example).  If X is marked obsolete, "A" will not
2632 	 * notice.  That's what we are validating here via the
2633 	 * stale_bundle() check.
2634 	 *
2635 	 * When a policy's bundle is pruned, we dst_free() the XFRM
2636 	 * dst which causes it's ->obsolete field to be set to
2637 	 * DST_OBSOLETE_DEAD.  If an XFRM dst has been pruned like
2638 	 * this, we want to force a new route lookup.
2639 	 */
2640 	if (dst->obsolete < 0 && !stale_bundle(dst))
2641 		return dst;
2642 
2643 	return NULL;
2644 }
2645 
2646 static int stale_bundle(struct dst_entry *dst)
2647 {
2648 	return !xfrm_bundle_ok((struct xfrm_dst *)dst);
2649 }
2650 
2651 void xfrm_dst_ifdown(struct dst_entry *dst, struct net_device *dev)
2652 {
2653 	while ((dst = dst->child) && dst->xfrm && dst->dev == dev) {
2654 		dst->dev = dev_net(dev)->loopback_dev;
2655 		dev_hold(dst->dev);
2656 		dev_put(dev);
2657 	}
2658 }
2659 EXPORT_SYMBOL(xfrm_dst_ifdown);
2660 
2661 static void xfrm_link_failure(struct sk_buff *skb)
2662 {
2663 	/* Impossible. Such dst must be popped before reaches point of failure. */
2664 }
2665 
2666 static struct dst_entry *xfrm_negative_advice(struct dst_entry *dst)
2667 {
2668 	if (dst) {
2669 		if (dst->obsolete) {
2670 			dst_release(dst);
2671 			dst = NULL;
2672 		}
2673 	}
2674 	return dst;
2675 }
2676 
2677 void xfrm_garbage_collect(struct net *net)
2678 {
2679 	flow_cache_flush(net);
2680 }
2681 EXPORT_SYMBOL(xfrm_garbage_collect);
2682 
2683 void xfrm_garbage_collect_deferred(struct net *net)
2684 {
2685 	flow_cache_flush_deferred(net);
2686 }
2687 EXPORT_SYMBOL(xfrm_garbage_collect_deferred);
2688 
2689 static void xfrm_init_pmtu(struct dst_entry *dst)
2690 {
2691 	do {
2692 		struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
2693 		u32 pmtu, route_mtu_cached;
2694 
2695 		pmtu = dst_mtu(dst->child);
2696 		xdst->child_mtu_cached = pmtu;
2697 
2698 		pmtu = xfrm_state_mtu(dst->xfrm, pmtu);
2699 
2700 		route_mtu_cached = dst_mtu(xdst->route);
2701 		xdst->route_mtu_cached = route_mtu_cached;
2702 
2703 		if (pmtu > route_mtu_cached)
2704 			pmtu = route_mtu_cached;
2705 
2706 		dst_metric_set(dst, RTAX_MTU, pmtu);
2707 	} while ((dst = dst->next));
2708 }
2709 
2710 /* Check that the bundle accepts the flow and its components are
2711  * still valid.
2712  */
2713 
2714 static int xfrm_bundle_ok(struct xfrm_dst *first)
2715 {
2716 	struct dst_entry *dst = &first->u.dst;
2717 	struct xfrm_dst *last;
2718 	u32 mtu;
2719 
2720 	if (!dst_check(dst->path, ((struct xfrm_dst *)dst)->path_cookie) ||
2721 	    (dst->dev && !netif_running(dst->dev)))
2722 		return 0;
2723 
2724 	if (dst->flags & DST_XFRM_QUEUE)
2725 		return 1;
2726 
2727 	last = NULL;
2728 
2729 	do {
2730 		struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
2731 
2732 		if (dst->xfrm->km.state != XFRM_STATE_VALID)
2733 			return 0;
2734 		if (xdst->xfrm_genid != dst->xfrm->genid)
2735 			return 0;
2736 		if (xdst->num_pols > 0 &&
2737 		    xdst->policy_genid != atomic_read(&xdst->pols[0]->genid))
2738 			return 0;
2739 
2740 		mtu = dst_mtu(dst->child);
2741 		if (xdst->child_mtu_cached != mtu) {
2742 			last = xdst;
2743 			xdst->child_mtu_cached = mtu;
2744 		}
2745 
2746 		if (!dst_check(xdst->route, xdst->route_cookie))
2747 			return 0;
2748 		mtu = dst_mtu(xdst->route);
2749 		if (xdst->route_mtu_cached != mtu) {
2750 			last = xdst;
2751 			xdst->route_mtu_cached = mtu;
2752 		}
2753 
2754 		dst = dst->child;
2755 	} while (dst->xfrm);
2756 
2757 	if (likely(!last))
2758 		return 1;
2759 
2760 	mtu = last->child_mtu_cached;
2761 	for (;;) {
2762 		dst = &last->u.dst;
2763 
2764 		mtu = xfrm_state_mtu(dst->xfrm, mtu);
2765 		if (mtu > last->route_mtu_cached)
2766 			mtu = last->route_mtu_cached;
2767 		dst_metric_set(dst, RTAX_MTU, mtu);
2768 
2769 		if (last == first)
2770 			break;
2771 
2772 		last = (struct xfrm_dst *)last->u.dst.next;
2773 		last->child_mtu_cached = mtu;
2774 	}
2775 
2776 	return 1;
2777 }
2778 
2779 static unsigned int xfrm_default_advmss(const struct dst_entry *dst)
2780 {
2781 	return dst_metric_advmss(dst->path);
2782 }
2783 
2784 static unsigned int xfrm_mtu(const struct dst_entry *dst)
2785 {
2786 	unsigned int mtu = dst_metric_raw(dst, RTAX_MTU);
2787 
2788 	return mtu ? : dst_mtu(dst->path);
2789 }
2790 
2791 static const void *xfrm_get_dst_nexthop(const struct dst_entry *dst,
2792 					const void *daddr)
2793 {
2794 	const struct dst_entry *path = dst->path;
2795 
2796 	for (; dst != path; dst = dst->child) {
2797 		const struct xfrm_state *xfrm = dst->xfrm;
2798 
2799 		if (xfrm->props.mode == XFRM_MODE_TRANSPORT)
2800 			continue;
2801 		if (xfrm->type->flags & XFRM_TYPE_REMOTE_COADDR)
2802 			daddr = xfrm->coaddr;
2803 		else if (!(xfrm->type->flags & XFRM_TYPE_LOCAL_COADDR))
2804 			daddr = &xfrm->id.daddr;
2805 	}
2806 	return daddr;
2807 }
2808 
2809 static struct neighbour *xfrm_neigh_lookup(const struct dst_entry *dst,
2810 					   struct sk_buff *skb,
2811 					   const void *daddr)
2812 {
2813 	const struct dst_entry *path = dst->path;
2814 
2815 	if (!skb)
2816 		daddr = xfrm_get_dst_nexthop(dst, daddr);
2817 	return path->ops->neigh_lookup(path, skb, daddr);
2818 }
2819 
2820 static void xfrm_confirm_neigh(const struct dst_entry *dst, const void *daddr)
2821 {
2822 	const struct dst_entry *path = dst->path;
2823 
2824 	daddr = xfrm_get_dst_nexthop(dst, daddr);
2825 	path->ops->confirm_neigh(path, daddr);
2826 }
2827 
2828 int xfrm_policy_register_afinfo(const struct xfrm_policy_afinfo *afinfo, int family)
2829 {
2830 	int err = 0;
2831 
2832 	if (WARN_ON(family >= ARRAY_SIZE(xfrm_policy_afinfo)))
2833 		return -EAFNOSUPPORT;
2834 
2835 	spin_lock(&xfrm_policy_afinfo_lock);
2836 	if (unlikely(xfrm_policy_afinfo[family] != NULL))
2837 		err = -EEXIST;
2838 	else {
2839 		struct dst_ops *dst_ops = afinfo->dst_ops;
2840 		if (likely(dst_ops->kmem_cachep == NULL))
2841 			dst_ops->kmem_cachep = xfrm_dst_cache;
2842 		if (likely(dst_ops->check == NULL))
2843 			dst_ops->check = xfrm_dst_check;
2844 		if (likely(dst_ops->default_advmss == NULL))
2845 			dst_ops->default_advmss = xfrm_default_advmss;
2846 		if (likely(dst_ops->mtu == NULL))
2847 			dst_ops->mtu = xfrm_mtu;
2848 		if (likely(dst_ops->negative_advice == NULL))
2849 			dst_ops->negative_advice = xfrm_negative_advice;
2850 		if (likely(dst_ops->link_failure == NULL))
2851 			dst_ops->link_failure = xfrm_link_failure;
2852 		if (likely(dst_ops->neigh_lookup == NULL))
2853 			dst_ops->neigh_lookup = xfrm_neigh_lookup;
2854 		if (likely(!dst_ops->confirm_neigh))
2855 			dst_ops->confirm_neigh = xfrm_confirm_neigh;
2856 		rcu_assign_pointer(xfrm_policy_afinfo[family], afinfo);
2857 	}
2858 	spin_unlock(&xfrm_policy_afinfo_lock);
2859 
2860 	return err;
2861 }
2862 EXPORT_SYMBOL(xfrm_policy_register_afinfo);
2863 
2864 void xfrm_policy_unregister_afinfo(const struct xfrm_policy_afinfo *afinfo)
2865 {
2866 	struct dst_ops *dst_ops = afinfo->dst_ops;
2867 	int i;
2868 
2869 	for (i = 0; i < ARRAY_SIZE(xfrm_policy_afinfo); i++) {
2870 		if (xfrm_policy_afinfo[i] != afinfo)
2871 			continue;
2872 		RCU_INIT_POINTER(xfrm_policy_afinfo[i], NULL);
2873 		break;
2874 	}
2875 
2876 	synchronize_rcu();
2877 
2878 	dst_ops->kmem_cachep = NULL;
2879 	dst_ops->check = NULL;
2880 	dst_ops->negative_advice = NULL;
2881 	dst_ops->link_failure = NULL;
2882 }
2883 EXPORT_SYMBOL(xfrm_policy_unregister_afinfo);
2884 
2885 #ifdef CONFIG_XFRM_STATISTICS
2886 static int __net_init xfrm_statistics_init(struct net *net)
2887 {
2888 	int rv;
2889 	net->mib.xfrm_statistics = alloc_percpu(struct linux_xfrm_mib);
2890 	if (!net->mib.xfrm_statistics)
2891 		return -ENOMEM;
2892 	rv = xfrm_proc_init(net);
2893 	if (rv < 0)
2894 		free_percpu(net->mib.xfrm_statistics);
2895 	return rv;
2896 }
2897 
2898 static void xfrm_statistics_fini(struct net *net)
2899 {
2900 	xfrm_proc_fini(net);
2901 	free_percpu(net->mib.xfrm_statistics);
2902 }
2903 #else
2904 static int __net_init xfrm_statistics_init(struct net *net)
2905 {
2906 	return 0;
2907 }
2908 
2909 static void xfrm_statistics_fini(struct net *net)
2910 {
2911 }
2912 #endif
2913 
2914 static int __net_init xfrm_policy_init(struct net *net)
2915 {
2916 	unsigned int hmask, sz;
2917 	int dir;
2918 
2919 	if (net_eq(net, &init_net))
2920 		xfrm_dst_cache = kmem_cache_create("xfrm_dst_cache",
2921 					   sizeof(struct xfrm_dst),
2922 					   0, SLAB_HWCACHE_ALIGN|SLAB_PANIC,
2923 					   NULL);
2924 
2925 	hmask = 8 - 1;
2926 	sz = (hmask+1) * sizeof(struct hlist_head);
2927 
2928 	net->xfrm.policy_byidx = xfrm_hash_alloc(sz);
2929 	if (!net->xfrm.policy_byidx)
2930 		goto out_byidx;
2931 	net->xfrm.policy_idx_hmask = hmask;
2932 
2933 	for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
2934 		struct xfrm_policy_hash *htab;
2935 
2936 		net->xfrm.policy_count[dir] = 0;
2937 		net->xfrm.policy_count[XFRM_POLICY_MAX + dir] = 0;
2938 		INIT_HLIST_HEAD(&net->xfrm.policy_inexact[dir]);
2939 
2940 		htab = &net->xfrm.policy_bydst[dir];
2941 		htab->table = xfrm_hash_alloc(sz);
2942 		if (!htab->table)
2943 			goto out_bydst;
2944 		htab->hmask = hmask;
2945 		htab->dbits4 = 32;
2946 		htab->sbits4 = 32;
2947 		htab->dbits6 = 128;
2948 		htab->sbits6 = 128;
2949 	}
2950 	net->xfrm.policy_hthresh.lbits4 = 32;
2951 	net->xfrm.policy_hthresh.rbits4 = 32;
2952 	net->xfrm.policy_hthresh.lbits6 = 128;
2953 	net->xfrm.policy_hthresh.rbits6 = 128;
2954 
2955 	seqlock_init(&net->xfrm.policy_hthresh.lock);
2956 
2957 	INIT_LIST_HEAD(&net->xfrm.policy_all);
2958 	INIT_WORK(&net->xfrm.policy_hash_work, xfrm_hash_resize);
2959 	INIT_WORK(&net->xfrm.policy_hthresh.work, xfrm_hash_rebuild);
2960 	if (net_eq(net, &init_net))
2961 		xfrm_dev_init();
2962 	return 0;
2963 
2964 out_bydst:
2965 	for (dir--; dir >= 0; dir--) {
2966 		struct xfrm_policy_hash *htab;
2967 
2968 		htab = &net->xfrm.policy_bydst[dir];
2969 		xfrm_hash_free(htab->table, sz);
2970 	}
2971 	xfrm_hash_free(net->xfrm.policy_byidx, sz);
2972 out_byidx:
2973 	return -ENOMEM;
2974 }
2975 
2976 static void xfrm_policy_fini(struct net *net)
2977 {
2978 	unsigned int sz;
2979 	int dir;
2980 
2981 	flush_work(&net->xfrm.policy_hash_work);
2982 #ifdef CONFIG_XFRM_SUB_POLICY
2983 	xfrm_policy_flush(net, XFRM_POLICY_TYPE_SUB, false);
2984 #endif
2985 	xfrm_policy_flush(net, XFRM_POLICY_TYPE_MAIN, false);
2986 
2987 	WARN_ON(!list_empty(&net->xfrm.policy_all));
2988 
2989 	for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
2990 		struct xfrm_policy_hash *htab;
2991 
2992 		WARN_ON(!hlist_empty(&net->xfrm.policy_inexact[dir]));
2993 
2994 		htab = &net->xfrm.policy_bydst[dir];
2995 		sz = (htab->hmask + 1) * sizeof(struct hlist_head);
2996 		WARN_ON(!hlist_empty(htab->table));
2997 		xfrm_hash_free(htab->table, sz);
2998 	}
2999 
3000 	sz = (net->xfrm.policy_idx_hmask + 1) * sizeof(struct hlist_head);
3001 	WARN_ON(!hlist_empty(net->xfrm.policy_byidx));
3002 	xfrm_hash_free(net->xfrm.policy_byidx, sz);
3003 }
3004 
3005 static int __net_init xfrm_net_init(struct net *net)
3006 {
3007 	int rv;
3008 
3009 	/* Initialize the per-net locks here */
3010 	spin_lock_init(&net->xfrm.xfrm_state_lock);
3011 	spin_lock_init(&net->xfrm.xfrm_policy_lock);
3012 	mutex_init(&net->xfrm.xfrm_cfg_mutex);
3013 
3014 	rv = xfrm_statistics_init(net);
3015 	if (rv < 0)
3016 		goto out_statistics;
3017 	rv = xfrm_state_init(net);
3018 	if (rv < 0)
3019 		goto out_state;
3020 	rv = xfrm_policy_init(net);
3021 	if (rv < 0)
3022 		goto out_policy;
3023 	rv = xfrm_sysctl_init(net);
3024 	if (rv < 0)
3025 		goto out_sysctl;
3026 	rv = flow_cache_init(net);
3027 	if (rv < 0)
3028 		goto out;
3029 
3030 	return 0;
3031 
3032 out:
3033 	xfrm_sysctl_fini(net);
3034 out_sysctl:
3035 	xfrm_policy_fini(net);
3036 out_policy:
3037 	xfrm_state_fini(net);
3038 out_state:
3039 	xfrm_statistics_fini(net);
3040 out_statistics:
3041 	return rv;
3042 }
3043 
3044 static void __net_exit xfrm_net_exit(struct net *net)
3045 {
3046 	flow_cache_fini(net);
3047 	xfrm_sysctl_fini(net);
3048 	xfrm_policy_fini(net);
3049 	xfrm_state_fini(net);
3050 	xfrm_statistics_fini(net);
3051 }
3052 
3053 static struct pernet_operations __net_initdata xfrm_net_ops = {
3054 	.init = xfrm_net_init,
3055 	.exit = xfrm_net_exit,
3056 };
3057 
3058 void __init xfrm_init(void)
3059 {
3060 	flow_cache_hp_init();
3061 	register_pernet_subsys(&xfrm_net_ops);
3062 	seqcount_init(&xfrm_policy_hash_generation);
3063 	xfrm_input_init();
3064 }
3065 
3066 #ifdef CONFIG_AUDITSYSCALL
3067 static void xfrm_audit_common_policyinfo(struct xfrm_policy *xp,
3068 					 struct audit_buffer *audit_buf)
3069 {
3070 	struct xfrm_sec_ctx *ctx = xp->security;
3071 	struct xfrm_selector *sel = &xp->selector;
3072 
3073 	if (ctx)
3074 		audit_log_format(audit_buf, " sec_alg=%u sec_doi=%u sec_obj=%s",
3075 				 ctx->ctx_alg, ctx->ctx_doi, ctx->ctx_str);
3076 
3077 	switch (sel->family) {
3078 	case AF_INET:
3079 		audit_log_format(audit_buf, " src=%pI4", &sel->saddr.a4);
3080 		if (sel->prefixlen_s != 32)
3081 			audit_log_format(audit_buf, " src_prefixlen=%d",
3082 					 sel->prefixlen_s);
3083 		audit_log_format(audit_buf, " dst=%pI4", &sel->daddr.a4);
3084 		if (sel->prefixlen_d != 32)
3085 			audit_log_format(audit_buf, " dst_prefixlen=%d",
3086 					 sel->prefixlen_d);
3087 		break;
3088 	case AF_INET6:
3089 		audit_log_format(audit_buf, " src=%pI6", sel->saddr.a6);
3090 		if (sel->prefixlen_s != 128)
3091 			audit_log_format(audit_buf, " src_prefixlen=%d",
3092 					 sel->prefixlen_s);
3093 		audit_log_format(audit_buf, " dst=%pI6", sel->daddr.a6);
3094 		if (sel->prefixlen_d != 128)
3095 			audit_log_format(audit_buf, " dst_prefixlen=%d",
3096 					 sel->prefixlen_d);
3097 		break;
3098 	}
3099 }
3100 
3101 void xfrm_audit_policy_add(struct xfrm_policy *xp, int result, bool task_valid)
3102 {
3103 	struct audit_buffer *audit_buf;
3104 
3105 	audit_buf = xfrm_audit_start("SPD-add");
3106 	if (audit_buf == NULL)
3107 		return;
3108 	xfrm_audit_helper_usrinfo(task_valid, audit_buf);
3109 	audit_log_format(audit_buf, " res=%u", result);
3110 	xfrm_audit_common_policyinfo(xp, audit_buf);
3111 	audit_log_end(audit_buf);
3112 }
3113 EXPORT_SYMBOL_GPL(xfrm_audit_policy_add);
3114 
3115 void xfrm_audit_policy_delete(struct xfrm_policy *xp, int result,
3116 			      bool task_valid)
3117 {
3118 	struct audit_buffer *audit_buf;
3119 
3120 	audit_buf = xfrm_audit_start("SPD-delete");
3121 	if (audit_buf == NULL)
3122 		return;
3123 	xfrm_audit_helper_usrinfo(task_valid, audit_buf);
3124 	audit_log_format(audit_buf, " res=%u", result);
3125 	xfrm_audit_common_policyinfo(xp, audit_buf);
3126 	audit_log_end(audit_buf);
3127 }
3128 EXPORT_SYMBOL_GPL(xfrm_audit_policy_delete);
3129 #endif
3130 
3131 #ifdef CONFIG_XFRM_MIGRATE
3132 static bool xfrm_migrate_selector_match(const struct xfrm_selector *sel_cmp,
3133 					const struct xfrm_selector *sel_tgt)
3134 {
3135 	if (sel_cmp->proto == IPSEC_ULPROTO_ANY) {
3136 		if (sel_tgt->family == sel_cmp->family &&
3137 		    xfrm_addr_equal(&sel_tgt->daddr, &sel_cmp->daddr,
3138 				    sel_cmp->family) &&
3139 		    xfrm_addr_equal(&sel_tgt->saddr, &sel_cmp->saddr,
3140 				    sel_cmp->family) &&
3141 		    sel_tgt->prefixlen_d == sel_cmp->prefixlen_d &&
3142 		    sel_tgt->prefixlen_s == sel_cmp->prefixlen_s) {
3143 			return true;
3144 		}
3145 	} else {
3146 		if (memcmp(sel_tgt, sel_cmp, sizeof(*sel_tgt)) == 0) {
3147 			return true;
3148 		}
3149 	}
3150 	return false;
3151 }
3152 
3153 static struct xfrm_policy *xfrm_migrate_policy_find(const struct xfrm_selector *sel,
3154 						    u8 dir, u8 type, struct net *net)
3155 {
3156 	struct xfrm_policy *pol, *ret = NULL;
3157 	struct hlist_head *chain;
3158 	u32 priority = ~0U;
3159 
3160 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
3161 	chain = policy_hash_direct(net, &sel->daddr, &sel->saddr, sel->family, dir);
3162 	hlist_for_each_entry(pol, chain, bydst) {
3163 		if (xfrm_migrate_selector_match(sel, &pol->selector) &&
3164 		    pol->type == type) {
3165 			ret = pol;
3166 			priority = ret->priority;
3167 			break;
3168 		}
3169 	}
3170 	chain = &net->xfrm.policy_inexact[dir];
3171 	hlist_for_each_entry(pol, chain, bydst) {
3172 		if ((pol->priority >= priority) && ret)
3173 			break;
3174 
3175 		if (xfrm_migrate_selector_match(sel, &pol->selector) &&
3176 		    pol->type == type) {
3177 			ret = pol;
3178 			break;
3179 		}
3180 	}
3181 
3182 	xfrm_pol_hold(ret);
3183 
3184 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
3185 
3186 	return ret;
3187 }
3188 
3189 static int migrate_tmpl_match(const struct xfrm_migrate *m, const struct xfrm_tmpl *t)
3190 {
3191 	int match = 0;
3192 
3193 	if (t->mode == m->mode && t->id.proto == m->proto &&
3194 	    (m->reqid == 0 || t->reqid == m->reqid)) {
3195 		switch (t->mode) {
3196 		case XFRM_MODE_TUNNEL:
3197 		case XFRM_MODE_BEET:
3198 			if (xfrm_addr_equal(&t->id.daddr, &m->old_daddr,
3199 					    m->old_family) &&
3200 			    xfrm_addr_equal(&t->saddr, &m->old_saddr,
3201 					    m->old_family)) {
3202 				match = 1;
3203 			}
3204 			break;
3205 		case XFRM_MODE_TRANSPORT:
3206 			/* in case of transport mode, template does not store
3207 			   any IP addresses, hence we just compare mode and
3208 			   protocol */
3209 			match = 1;
3210 			break;
3211 		default:
3212 			break;
3213 		}
3214 	}
3215 	return match;
3216 }
3217 
3218 /* update endpoint address(es) of template(s) */
3219 static int xfrm_policy_migrate(struct xfrm_policy *pol,
3220 			       struct xfrm_migrate *m, int num_migrate)
3221 {
3222 	struct xfrm_migrate *mp;
3223 	int i, j, n = 0;
3224 
3225 	write_lock_bh(&pol->lock);
3226 	if (unlikely(pol->walk.dead)) {
3227 		/* target policy has been deleted */
3228 		write_unlock_bh(&pol->lock);
3229 		return -ENOENT;
3230 	}
3231 
3232 	for (i = 0; i < pol->xfrm_nr; i++) {
3233 		for (j = 0, mp = m; j < num_migrate; j++, mp++) {
3234 			if (!migrate_tmpl_match(mp, &pol->xfrm_vec[i]))
3235 				continue;
3236 			n++;
3237 			if (pol->xfrm_vec[i].mode != XFRM_MODE_TUNNEL &&
3238 			    pol->xfrm_vec[i].mode != XFRM_MODE_BEET)
3239 				continue;
3240 			/* update endpoints */
3241 			memcpy(&pol->xfrm_vec[i].id.daddr, &mp->new_daddr,
3242 			       sizeof(pol->xfrm_vec[i].id.daddr));
3243 			memcpy(&pol->xfrm_vec[i].saddr, &mp->new_saddr,
3244 			       sizeof(pol->xfrm_vec[i].saddr));
3245 			pol->xfrm_vec[i].encap_family = mp->new_family;
3246 			/* flush bundles */
3247 			atomic_inc(&pol->genid);
3248 		}
3249 	}
3250 
3251 	write_unlock_bh(&pol->lock);
3252 
3253 	if (!n)
3254 		return -ENODATA;
3255 
3256 	return 0;
3257 }
3258 
3259 static int xfrm_migrate_check(const struct xfrm_migrate *m, int num_migrate)
3260 {
3261 	int i, j;
3262 
3263 	if (num_migrate < 1 || num_migrate > XFRM_MAX_DEPTH)
3264 		return -EINVAL;
3265 
3266 	for (i = 0; i < num_migrate; i++) {
3267 		if (xfrm_addr_equal(&m[i].old_daddr, &m[i].new_daddr,
3268 				    m[i].old_family) &&
3269 		    xfrm_addr_equal(&m[i].old_saddr, &m[i].new_saddr,
3270 				    m[i].old_family))
3271 			return -EINVAL;
3272 		if (xfrm_addr_any(&m[i].new_daddr, m[i].new_family) ||
3273 		    xfrm_addr_any(&m[i].new_saddr, m[i].new_family))
3274 			return -EINVAL;
3275 
3276 		/* check if there is any duplicated entry */
3277 		for (j = i + 1; j < num_migrate; j++) {
3278 			if (!memcmp(&m[i].old_daddr, &m[j].old_daddr,
3279 				    sizeof(m[i].old_daddr)) &&
3280 			    !memcmp(&m[i].old_saddr, &m[j].old_saddr,
3281 				    sizeof(m[i].old_saddr)) &&
3282 			    m[i].proto == m[j].proto &&
3283 			    m[i].mode == m[j].mode &&
3284 			    m[i].reqid == m[j].reqid &&
3285 			    m[i].old_family == m[j].old_family)
3286 				return -EINVAL;
3287 		}
3288 	}
3289 
3290 	return 0;
3291 }
3292 
3293 int xfrm_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
3294 		 struct xfrm_migrate *m, int num_migrate,
3295 		 struct xfrm_kmaddress *k, struct net *net)
3296 {
3297 	int i, err, nx_cur = 0, nx_new = 0;
3298 	struct xfrm_policy *pol = NULL;
3299 	struct xfrm_state *x, *xc;
3300 	struct xfrm_state *x_cur[XFRM_MAX_DEPTH];
3301 	struct xfrm_state *x_new[XFRM_MAX_DEPTH];
3302 	struct xfrm_migrate *mp;
3303 
3304 	if ((err = xfrm_migrate_check(m, num_migrate)) < 0)
3305 		goto out;
3306 
3307 	/* Stage 1 - find policy */
3308 	if ((pol = xfrm_migrate_policy_find(sel, dir, type, net)) == NULL) {
3309 		err = -ENOENT;
3310 		goto out;
3311 	}
3312 
3313 	/* Stage 2 - find and update state(s) */
3314 	for (i = 0, mp = m; i < num_migrate; i++, mp++) {
3315 		if ((x = xfrm_migrate_state_find(mp, net))) {
3316 			x_cur[nx_cur] = x;
3317 			nx_cur++;
3318 			if ((xc = xfrm_state_migrate(x, mp))) {
3319 				x_new[nx_new] = xc;
3320 				nx_new++;
3321 			} else {
3322 				err = -ENODATA;
3323 				goto restore_state;
3324 			}
3325 		}
3326 	}
3327 
3328 	/* Stage 3 - update policy */
3329 	if ((err = xfrm_policy_migrate(pol, m, num_migrate)) < 0)
3330 		goto restore_state;
3331 
3332 	/* Stage 4 - delete old state(s) */
3333 	if (nx_cur) {
3334 		xfrm_states_put(x_cur, nx_cur);
3335 		xfrm_states_delete(x_cur, nx_cur);
3336 	}
3337 
3338 	/* Stage 5 - announce */
3339 	km_migrate(sel, dir, type, m, num_migrate, k);
3340 
3341 	xfrm_pol_put(pol);
3342 
3343 	return 0;
3344 out:
3345 	return err;
3346 
3347 restore_state:
3348 	if (pol)
3349 		xfrm_pol_put(pol);
3350 	if (nx_cur)
3351 		xfrm_states_put(x_cur, nx_cur);
3352 	if (nx_new)
3353 		xfrm_states_delete(x_new, nx_new);
3354 
3355 	return err;
3356 }
3357 EXPORT_SYMBOL(xfrm_migrate);
3358 #endif
3359