xref: /openbmc/linux/net/xfrm/xfrm_policy.c (revision b58c6630)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * xfrm_policy.c
4  *
5  * Changes:
6  *	Mitsuru KANDA @USAGI
7  * 	Kazunori MIYAZAWA @USAGI
8  * 	Kunihiro Ishiguro <kunihiro@ipinfusion.com>
9  * 		IPv6 support
10  * 	Kazunori MIYAZAWA @USAGI
11  * 	YOSHIFUJI Hideaki
12  * 		Split up af-specific portion
13  *	Derek Atkins <derek@ihtfp.com>		Add the post_input processor
14  *
15  */
16 
17 #include <linux/err.h>
18 #include <linux/slab.h>
19 #include <linux/kmod.h>
20 #include <linux/list.h>
21 #include <linux/spinlock.h>
22 #include <linux/workqueue.h>
23 #include <linux/notifier.h>
24 #include <linux/netdevice.h>
25 #include <linux/netfilter.h>
26 #include <linux/module.h>
27 #include <linux/cache.h>
28 #include <linux/cpu.h>
29 #include <linux/audit.h>
30 #include <linux/rhashtable.h>
31 #include <linux/if_tunnel.h>
32 #include <net/dst.h>
33 #include <net/flow.h>
34 #include <net/xfrm.h>
35 #include <net/ip.h>
36 #if IS_ENABLED(CONFIG_IPV6_MIP6)
37 #include <net/mip6.h>
38 #endif
39 #ifdef CONFIG_XFRM_STATISTICS
40 #include <net/snmp.h>
41 #endif
42 #ifdef CONFIG_INET_ESPINTCP
43 #include <net/espintcp.h>
44 #endif
45 
46 #include "xfrm_hash.h"
47 
48 #define XFRM_QUEUE_TMO_MIN ((unsigned)(HZ/10))
49 #define XFRM_QUEUE_TMO_MAX ((unsigned)(60*HZ))
50 #define XFRM_MAX_QUEUE_LEN	100
51 
52 struct xfrm_flo {
53 	struct dst_entry *dst_orig;
54 	u8 flags;
55 };
56 
57 /* prefixes smaller than this are stored in lists, not trees. */
58 #define INEXACT_PREFIXLEN_IPV4	16
59 #define INEXACT_PREFIXLEN_IPV6	48
60 
61 struct xfrm_pol_inexact_node {
62 	struct rb_node node;
63 	union {
64 		xfrm_address_t addr;
65 		struct rcu_head rcu;
66 	};
67 	u8 prefixlen;
68 
69 	struct rb_root root;
70 
71 	/* the policies matching this node, can be empty list */
72 	struct hlist_head hhead;
73 };
74 
75 /* xfrm inexact policy search tree:
76  * xfrm_pol_inexact_bin = hash(dir,type,family,if_id);
77  *  |
78  * +---- root_d: sorted by daddr:prefix
79  * |                 |
80  * |        xfrm_pol_inexact_node
81  * |                 |
82  * |                 +- root: sorted by saddr/prefix
83  * |                 |              |
84  * |                 |         xfrm_pol_inexact_node
85  * |                 |              |
86  * |                 |              + root: unused
87  * |                 |              |
88  * |                 |              + hhead: saddr:daddr policies
89  * |                 |
90  * |                 +- coarse policies and all any:daddr policies
91  * |
92  * +---- root_s: sorted by saddr:prefix
93  * |                 |
94  * |        xfrm_pol_inexact_node
95  * |                 |
96  * |                 + root: unused
97  * |                 |
98  * |                 + hhead: saddr:any policies
99  * |
100  * +---- coarse policies and all any:any policies
101  *
102  * Lookups return four candidate lists:
103  * 1. any:any list from top-level xfrm_pol_inexact_bin
104  * 2. any:daddr list from daddr tree
105  * 3. saddr:daddr list from 2nd level daddr tree
106  * 4. saddr:any list from saddr tree
107  *
108  * This result set then needs to be searched for the policy with
109  * the lowest priority.  If two results have same prio, youngest one wins.
110  */
111 
112 struct xfrm_pol_inexact_key {
113 	possible_net_t net;
114 	u32 if_id;
115 	u16 family;
116 	u8 dir, type;
117 };
118 
119 struct xfrm_pol_inexact_bin {
120 	struct xfrm_pol_inexact_key k;
121 	struct rhash_head head;
122 	/* list containing '*:*' policies */
123 	struct hlist_head hhead;
124 
125 	seqcount_t count;
126 	/* tree sorted by daddr/prefix */
127 	struct rb_root root_d;
128 
129 	/* tree sorted by saddr/prefix */
130 	struct rb_root root_s;
131 
132 	/* slow path below */
133 	struct list_head inexact_bins;
134 	struct rcu_head rcu;
135 };
136 
137 enum xfrm_pol_inexact_candidate_type {
138 	XFRM_POL_CAND_BOTH,
139 	XFRM_POL_CAND_SADDR,
140 	XFRM_POL_CAND_DADDR,
141 	XFRM_POL_CAND_ANY,
142 
143 	XFRM_POL_CAND_MAX,
144 };
145 
146 struct xfrm_pol_inexact_candidates {
147 	struct hlist_head *res[XFRM_POL_CAND_MAX];
148 };
149 
150 static DEFINE_SPINLOCK(xfrm_if_cb_lock);
151 static struct xfrm_if_cb const __rcu *xfrm_if_cb __read_mostly;
152 
153 static DEFINE_SPINLOCK(xfrm_policy_afinfo_lock);
154 static struct xfrm_policy_afinfo const __rcu *xfrm_policy_afinfo[AF_INET6 + 1]
155 						__read_mostly;
156 
157 static struct kmem_cache *xfrm_dst_cache __ro_after_init;
158 static __read_mostly seqcount_t xfrm_policy_hash_generation;
159 
160 static struct rhashtable xfrm_policy_inexact_table;
161 static const struct rhashtable_params xfrm_pol_inexact_params;
162 
163 static void xfrm_init_pmtu(struct xfrm_dst **bundle, int nr);
164 static int stale_bundle(struct dst_entry *dst);
165 static int xfrm_bundle_ok(struct xfrm_dst *xdst);
166 static void xfrm_policy_queue_process(struct timer_list *t);
167 
168 static void __xfrm_policy_link(struct xfrm_policy *pol, int dir);
169 static struct xfrm_policy *__xfrm_policy_unlink(struct xfrm_policy *pol,
170 						int dir);
171 
172 static struct xfrm_pol_inexact_bin *
173 xfrm_policy_inexact_lookup(struct net *net, u8 type, u16 family, u8 dir,
174 			   u32 if_id);
175 
176 static struct xfrm_pol_inexact_bin *
177 xfrm_policy_inexact_lookup_rcu(struct net *net,
178 			       u8 type, u16 family, u8 dir, u32 if_id);
179 static struct xfrm_policy *
180 xfrm_policy_insert_list(struct hlist_head *chain, struct xfrm_policy *policy,
181 			bool excl);
182 static void xfrm_policy_insert_inexact_list(struct hlist_head *chain,
183 					    struct xfrm_policy *policy);
184 
185 static bool
186 xfrm_policy_find_inexact_candidates(struct xfrm_pol_inexact_candidates *cand,
187 				    struct xfrm_pol_inexact_bin *b,
188 				    const xfrm_address_t *saddr,
189 				    const xfrm_address_t *daddr);
190 
191 static inline bool xfrm_pol_hold_rcu(struct xfrm_policy *policy)
192 {
193 	return refcount_inc_not_zero(&policy->refcnt);
194 }
195 
196 static inline bool
197 __xfrm4_selector_match(const struct xfrm_selector *sel, const struct flowi *fl)
198 {
199 	const struct flowi4 *fl4 = &fl->u.ip4;
200 
201 	return  addr4_match(fl4->daddr, sel->daddr.a4, sel->prefixlen_d) &&
202 		addr4_match(fl4->saddr, sel->saddr.a4, sel->prefixlen_s) &&
203 		!((xfrm_flowi_dport(fl, &fl4->uli) ^ sel->dport) & sel->dport_mask) &&
204 		!((xfrm_flowi_sport(fl, &fl4->uli) ^ sel->sport) & sel->sport_mask) &&
205 		(fl4->flowi4_proto == sel->proto || !sel->proto) &&
206 		(fl4->flowi4_oif == sel->ifindex || !sel->ifindex);
207 }
208 
209 static inline bool
210 __xfrm6_selector_match(const struct xfrm_selector *sel, const struct flowi *fl)
211 {
212 	const struct flowi6 *fl6 = &fl->u.ip6;
213 
214 	return  addr_match(&fl6->daddr, &sel->daddr, sel->prefixlen_d) &&
215 		addr_match(&fl6->saddr, &sel->saddr, sel->prefixlen_s) &&
216 		!((xfrm_flowi_dport(fl, &fl6->uli) ^ sel->dport) & sel->dport_mask) &&
217 		!((xfrm_flowi_sport(fl, &fl6->uli) ^ sel->sport) & sel->sport_mask) &&
218 		(fl6->flowi6_proto == sel->proto || !sel->proto) &&
219 		(fl6->flowi6_oif == sel->ifindex || !sel->ifindex);
220 }
221 
222 bool xfrm_selector_match(const struct xfrm_selector *sel, const struct flowi *fl,
223 			 unsigned short family)
224 {
225 	switch (family) {
226 	case AF_INET:
227 		return __xfrm4_selector_match(sel, fl);
228 	case AF_INET6:
229 		return __xfrm6_selector_match(sel, fl);
230 	}
231 	return false;
232 }
233 
234 static const struct xfrm_policy_afinfo *xfrm_policy_get_afinfo(unsigned short family)
235 {
236 	const struct xfrm_policy_afinfo *afinfo;
237 
238 	if (unlikely(family >= ARRAY_SIZE(xfrm_policy_afinfo)))
239 		return NULL;
240 	rcu_read_lock();
241 	afinfo = rcu_dereference(xfrm_policy_afinfo[family]);
242 	if (unlikely(!afinfo))
243 		rcu_read_unlock();
244 	return afinfo;
245 }
246 
247 /* Called with rcu_read_lock(). */
248 static const struct xfrm_if_cb *xfrm_if_get_cb(void)
249 {
250 	return rcu_dereference(xfrm_if_cb);
251 }
252 
253 struct dst_entry *__xfrm_dst_lookup(struct net *net, int tos, int oif,
254 				    const xfrm_address_t *saddr,
255 				    const xfrm_address_t *daddr,
256 				    int family, u32 mark)
257 {
258 	const struct xfrm_policy_afinfo *afinfo;
259 	struct dst_entry *dst;
260 
261 	afinfo = xfrm_policy_get_afinfo(family);
262 	if (unlikely(afinfo == NULL))
263 		return ERR_PTR(-EAFNOSUPPORT);
264 
265 	dst = afinfo->dst_lookup(net, tos, oif, saddr, daddr, mark);
266 
267 	rcu_read_unlock();
268 
269 	return dst;
270 }
271 EXPORT_SYMBOL(__xfrm_dst_lookup);
272 
273 static inline struct dst_entry *xfrm_dst_lookup(struct xfrm_state *x,
274 						int tos, int oif,
275 						xfrm_address_t *prev_saddr,
276 						xfrm_address_t *prev_daddr,
277 						int family, u32 mark)
278 {
279 	struct net *net = xs_net(x);
280 	xfrm_address_t *saddr = &x->props.saddr;
281 	xfrm_address_t *daddr = &x->id.daddr;
282 	struct dst_entry *dst;
283 
284 	if (x->type->flags & XFRM_TYPE_LOCAL_COADDR) {
285 		saddr = x->coaddr;
286 		daddr = prev_daddr;
287 	}
288 	if (x->type->flags & XFRM_TYPE_REMOTE_COADDR) {
289 		saddr = prev_saddr;
290 		daddr = x->coaddr;
291 	}
292 
293 	dst = __xfrm_dst_lookup(net, tos, oif, saddr, daddr, family, mark);
294 
295 	if (!IS_ERR(dst)) {
296 		if (prev_saddr != saddr)
297 			memcpy(prev_saddr, saddr,  sizeof(*prev_saddr));
298 		if (prev_daddr != daddr)
299 			memcpy(prev_daddr, daddr,  sizeof(*prev_daddr));
300 	}
301 
302 	return dst;
303 }
304 
305 static inline unsigned long make_jiffies(long secs)
306 {
307 	if (secs >= (MAX_SCHEDULE_TIMEOUT-1)/HZ)
308 		return MAX_SCHEDULE_TIMEOUT-1;
309 	else
310 		return secs*HZ;
311 }
312 
313 static void xfrm_policy_timer(struct timer_list *t)
314 {
315 	struct xfrm_policy *xp = from_timer(xp, t, timer);
316 	time64_t now = ktime_get_real_seconds();
317 	time64_t next = TIME64_MAX;
318 	int warn = 0;
319 	int dir;
320 
321 	read_lock(&xp->lock);
322 
323 	if (unlikely(xp->walk.dead))
324 		goto out;
325 
326 	dir = xfrm_policy_id2dir(xp->index);
327 
328 	if (xp->lft.hard_add_expires_seconds) {
329 		time64_t tmo = xp->lft.hard_add_expires_seconds +
330 			xp->curlft.add_time - now;
331 		if (tmo <= 0)
332 			goto expired;
333 		if (tmo < next)
334 			next = tmo;
335 	}
336 	if (xp->lft.hard_use_expires_seconds) {
337 		time64_t tmo = xp->lft.hard_use_expires_seconds +
338 			(xp->curlft.use_time ? : xp->curlft.add_time) - now;
339 		if (tmo <= 0)
340 			goto expired;
341 		if (tmo < next)
342 			next = tmo;
343 	}
344 	if (xp->lft.soft_add_expires_seconds) {
345 		time64_t tmo = xp->lft.soft_add_expires_seconds +
346 			xp->curlft.add_time - now;
347 		if (tmo <= 0) {
348 			warn = 1;
349 			tmo = XFRM_KM_TIMEOUT;
350 		}
351 		if (tmo < next)
352 			next = tmo;
353 	}
354 	if (xp->lft.soft_use_expires_seconds) {
355 		time64_t tmo = xp->lft.soft_use_expires_seconds +
356 			(xp->curlft.use_time ? : xp->curlft.add_time) - now;
357 		if (tmo <= 0) {
358 			warn = 1;
359 			tmo = XFRM_KM_TIMEOUT;
360 		}
361 		if (tmo < next)
362 			next = tmo;
363 	}
364 
365 	if (warn)
366 		km_policy_expired(xp, dir, 0, 0);
367 	if (next != TIME64_MAX &&
368 	    !mod_timer(&xp->timer, jiffies + make_jiffies(next)))
369 		xfrm_pol_hold(xp);
370 
371 out:
372 	read_unlock(&xp->lock);
373 	xfrm_pol_put(xp);
374 	return;
375 
376 expired:
377 	read_unlock(&xp->lock);
378 	if (!xfrm_policy_delete(xp, dir))
379 		km_policy_expired(xp, dir, 1, 0);
380 	xfrm_pol_put(xp);
381 }
382 
383 /* Allocate xfrm_policy. Not used here, it is supposed to be used by pfkeyv2
384  * SPD calls.
385  */
386 
387 struct xfrm_policy *xfrm_policy_alloc(struct net *net, gfp_t gfp)
388 {
389 	struct xfrm_policy *policy;
390 
391 	policy = kzalloc(sizeof(struct xfrm_policy), gfp);
392 
393 	if (policy) {
394 		write_pnet(&policy->xp_net, net);
395 		INIT_LIST_HEAD(&policy->walk.all);
396 		INIT_HLIST_NODE(&policy->bydst_inexact_list);
397 		INIT_HLIST_NODE(&policy->bydst);
398 		INIT_HLIST_NODE(&policy->byidx);
399 		rwlock_init(&policy->lock);
400 		refcount_set(&policy->refcnt, 1);
401 		skb_queue_head_init(&policy->polq.hold_queue);
402 		timer_setup(&policy->timer, xfrm_policy_timer, 0);
403 		timer_setup(&policy->polq.hold_timer,
404 			    xfrm_policy_queue_process, 0);
405 	}
406 	return policy;
407 }
408 EXPORT_SYMBOL(xfrm_policy_alloc);
409 
410 static void xfrm_policy_destroy_rcu(struct rcu_head *head)
411 {
412 	struct xfrm_policy *policy = container_of(head, struct xfrm_policy, rcu);
413 
414 	security_xfrm_policy_free(policy->security);
415 	kfree(policy);
416 }
417 
418 /* Destroy xfrm_policy: descendant resources must be released to this moment. */
419 
420 void xfrm_policy_destroy(struct xfrm_policy *policy)
421 {
422 	BUG_ON(!policy->walk.dead);
423 
424 	if (del_timer(&policy->timer) || del_timer(&policy->polq.hold_timer))
425 		BUG();
426 
427 	call_rcu(&policy->rcu, xfrm_policy_destroy_rcu);
428 }
429 EXPORT_SYMBOL(xfrm_policy_destroy);
430 
431 /* Rule must be locked. Release descendant resources, announce
432  * entry dead. The rule must be unlinked from lists to the moment.
433  */
434 
435 static void xfrm_policy_kill(struct xfrm_policy *policy)
436 {
437 	write_lock_bh(&policy->lock);
438 	policy->walk.dead = 1;
439 	write_unlock_bh(&policy->lock);
440 
441 	atomic_inc(&policy->genid);
442 
443 	if (del_timer(&policy->polq.hold_timer))
444 		xfrm_pol_put(policy);
445 	skb_queue_purge(&policy->polq.hold_queue);
446 
447 	if (del_timer(&policy->timer))
448 		xfrm_pol_put(policy);
449 
450 	xfrm_pol_put(policy);
451 }
452 
453 static unsigned int xfrm_policy_hashmax __read_mostly = 1 * 1024 * 1024;
454 
455 static inline unsigned int idx_hash(struct net *net, u32 index)
456 {
457 	return __idx_hash(index, net->xfrm.policy_idx_hmask);
458 }
459 
460 /* calculate policy hash thresholds */
461 static void __get_hash_thresh(struct net *net,
462 			      unsigned short family, int dir,
463 			      u8 *dbits, u8 *sbits)
464 {
465 	switch (family) {
466 	case AF_INET:
467 		*dbits = net->xfrm.policy_bydst[dir].dbits4;
468 		*sbits = net->xfrm.policy_bydst[dir].sbits4;
469 		break;
470 
471 	case AF_INET6:
472 		*dbits = net->xfrm.policy_bydst[dir].dbits6;
473 		*sbits = net->xfrm.policy_bydst[dir].sbits6;
474 		break;
475 
476 	default:
477 		*dbits = 0;
478 		*sbits = 0;
479 	}
480 }
481 
482 static struct hlist_head *policy_hash_bysel(struct net *net,
483 					    const struct xfrm_selector *sel,
484 					    unsigned short family, int dir)
485 {
486 	unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
487 	unsigned int hash;
488 	u8 dbits;
489 	u8 sbits;
490 
491 	__get_hash_thresh(net, family, dir, &dbits, &sbits);
492 	hash = __sel_hash(sel, family, hmask, dbits, sbits);
493 
494 	if (hash == hmask + 1)
495 		return NULL;
496 
497 	return rcu_dereference_check(net->xfrm.policy_bydst[dir].table,
498 		     lockdep_is_held(&net->xfrm.xfrm_policy_lock)) + hash;
499 }
500 
501 static struct hlist_head *policy_hash_direct(struct net *net,
502 					     const xfrm_address_t *daddr,
503 					     const xfrm_address_t *saddr,
504 					     unsigned short family, int dir)
505 {
506 	unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
507 	unsigned int hash;
508 	u8 dbits;
509 	u8 sbits;
510 
511 	__get_hash_thresh(net, family, dir, &dbits, &sbits);
512 	hash = __addr_hash(daddr, saddr, family, hmask, dbits, sbits);
513 
514 	return rcu_dereference_check(net->xfrm.policy_bydst[dir].table,
515 		     lockdep_is_held(&net->xfrm.xfrm_policy_lock)) + hash;
516 }
517 
518 static void xfrm_dst_hash_transfer(struct net *net,
519 				   struct hlist_head *list,
520 				   struct hlist_head *ndsttable,
521 				   unsigned int nhashmask,
522 				   int dir)
523 {
524 	struct hlist_node *tmp, *entry0 = NULL;
525 	struct xfrm_policy *pol;
526 	unsigned int h0 = 0;
527 	u8 dbits;
528 	u8 sbits;
529 
530 redo:
531 	hlist_for_each_entry_safe(pol, tmp, list, bydst) {
532 		unsigned int h;
533 
534 		__get_hash_thresh(net, pol->family, dir, &dbits, &sbits);
535 		h = __addr_hash(&pol->selector.daddr, &pol->selector.saddr,
536 				pol->family, nhashmask, dbits, sbits);
537 		if (!entry0) {
538 			hlist_del_rcu(&pol->bydst);
539 			hlist_add_head_rcu(&pol->bydst, ndsttable + h);
540 			h0 = h;
541 		} else {
542 			if (h != h0)
543 				continue;
544 			hlist_del_rcu(&pol->bydst);
545 			hlist_add_behind_rcu(&pol->bydst, entry0);
546 		}
547 		entry0 = &pol->bydst;
548 	}
549 	if (!hlist_empty(list)) {
550 		entry0 = NULL;
551 		goto redo;
552 	}
553 }
554 
555 static void xfrm_idx_hash_transfer(struct hlist_head *list,
556 				   struct hlist_head *nidxtable,
557 				   unsigned int nhashmask)
558 {
559 	struct hlist_node *tmp;
560 	struct xfrm_policy *pol;
561 
562 	hlist_for_each_entry_safe(pol, tmp, list, byidx) {
563 		unsigned int h;
564 
565 		h = __idx_hash(pol->index, nhashmask);
566 		hlist_add_head(&pol->byidx, nidxtable+h);
567 	}
568 }
569 
570 static unsigned long xfrm_new_hash_mask(unsigned int old_hmask)
571 {
572 	return ((old_hmask + 1) << 1) - 1;
573 }
574 
575 static void xfrm_bydst_resize(struct net *net, int dir)
576 {
577 	unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
578 	unsigned int nhashmask = xfrm_new_hash_mask(hmask);
579 	unsigned int nsize = (nhashmask + 1) * sizeof(struct hlist_head);
580 	struct hlist_head *ndst = xfrm_hash_alloc(nsize);
581 	struct hlist_head *odst;
582 	int i;
583 
584 	if (!ndst)
585 		return;
586 
587 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
588 	write_seqcount_begin(&xfrm_policy_hash_generation);
589 
590 	odst = rcu_dereference_protected(net->xfrm.policy_bydst[dir].table,
591 				lockdep_is_held(&net->xfrm.xfrm_policy_lock));
592 
593 	for (i = hmask; i >= 0; i--)
594 		xfrm_dst_hash_transfer(net, odst + i, ndst, nhashmask, dir);
595 
596 	rcu_assign_pointer(net->xfrm.policy_bydst[dir].table, ndst);
597 	net->xfrm.policy_bydst[dir].hmask = nhashmask;
598 
599 	write_seqcount_end(&xfrm_policy_hash_generation);
600 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
601 
602 	synchronize_rcu();
603 
604 	xfrm_hash_free(odst, (hmask + 1) * sizeof(struct hlist_head));
605 }
606 
607 static void xfrm_byidx_resize(struct net *net, int total)
608 {
609 	unsigned int hmask = net->xfrm.policy_idx_hmask;
610 	unsigned int nhashmask = xfrm_new_hash_mask(hmask);
611 	unsigned int nsize = (nhashmask + 1) * sizeof(struct hlist_head);
612 	struct hlist_head *oidx = net->xfrm.policy_byidx;
613 	struct hlist_head *nidx = xfrm_hash_alloc(nsize);
614 	int i;
615 
616 	if (!nidx)
617 		return;
618 
619 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
620 
621 	for (i = hmask; i >= 0; i--)
622 		xfrm_idx_hash_transfer(oidx + i, nidx, nhashmask);
623 
624 	net->xfrm.policy_byidx = nidx;
625 	net->xfrm.policy_idx_hmask = nhashmask;
626 
627 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
628 
629 	xfrm_hash_free(oidx, (hmask + 1) * sizeof(struct hlist_head));
630 }
631 
632 static inline int xfrm_bydst_should_resize(struct net *net, int dir, int *total)
633 {
634 	unsigned int cnt = net->xfrm.policy_count[dir];
635 	unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
636 
637 	if (total)
638 		*total += cnt;
639 
640 	if ((hmask + 1) < xfrm_policy_hashmax &&
641 	    cnt > hmask)
642 		return 1;
643 
644 	return 0;
645 }
646 
647 static inline int xfrm_byidx_should_resize(struct net *net, int total)
648 {
649 	unsigned int hmask = net->xfrm.policy_idx_hmask;
650 
651 	if ((hmask + 1) < xfrm_policy_hashmax &&
652 	    total > hmask)
653 		return 1;
654 
655 	return 0;
656 }
657 
658 void xfrm_spd_getinfo(struct net *net, struct xfrmk_spdinfo *si)
659 {
660 	si->incnt = net->xfrm.policy_count[XFRM_POLICY_IN];
661 	si->outcnt = net->xfrm.policy_count[XFRM_POLICY_OUT];
662 	si->fwdcnt = net->xfrm.policy_count[XFRM_POLICY_FWD];
663 	si->inscnt = net->xfrm.policy_count[XFRM_POLICY_IN+XFRM_POLICY_MAX];
664 	si->outscnt = net->xfrm.policy_count[XFRM_POLICY_OUT+XFRM_POLICY_MAX];
665 	si->fwdscnt = net->xfrm.policy_count[XFRM_POLICY_FWD+XFRM_POLICY_MAX];
666 	si->spdhcnt = net->xfrm.policy_idx_hmask;
667 	si->spdhmcnt = xfrm_policy_hashmax;
668 }
669 EXPORT_SYMBOL(xfrm_spd_getinfo);
670 
671 static DEFINE_MUTEX(hash_resize_mutex);
672 static void xfrm_hash_resize(struct work_struct *work)
673 {
674 	struct net *net = container_of(work, struct net, xfrm.policy_hash_work);
675 	int dir, total;
676 
677 	mutex_lock(&hash_resize_mutex);
678 
679 	total = 0;
680 	for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
681 		if (xfrm_bydst_should_resize(net, dir, &total))
682 			xfrm_bydst_resize(net, dir);
683 	}
684 	if (xfrm_byidx_should_resize(net, total))
685 		xfrm_byidx_resize(net, total);
686 
687 	mutex_unlock(&hash_resize_mutex);
688 }
689 
690 /* Make sure *pol can be inserted into fastbin.
691  * Useful to check that later insert requests will be sucessful
692  * (provided xfrm_policy_lock is held throughout).
693  */
694 static struct xfrm_pol_inexact_bin *
695 xfrm_policy_inexact_alloc_bin(const struct xfrm_policy *pol, u8 dir)
696 {
697 	struct xfrm_pol_inexact_bin *bin, *prev;
698 	struct xfrm_pol_inexact_key k = {
699 		.family = pol->family,
700 		.type = pol->type,
701 		.dir = dir,
702 		.if_id = pol->if_id,
703 	};
704 	struct net *net = xp_net(pol);
705 
706 	lockdep_assert_held(&net->xfrm.xfrm_policy_lock);
707 
708 	write_pnet(&k.net, net);
709 	bin = rhashtable_lookup_fast(&xfrm_policy_inexact_table, &k,
710 				     xfrm_pol_inexact_params);
711 	if (bin)
712 		return bin;
713 
714 	bin = kzalloc(sizeof(*bin), GFP_ATOMIC);
715 	if (!bin)
716 		return NULL;
717 
718 	bin->k = k;
719 	INIT_HLIST_HEAD(&bin->hhead);
720 	bin->root_d = RB_ROOT;
721 	bin->root_s = RB_ROOT;
722 	seqcount_init(&bin->count);
723 
724 	prev = rhashtable_lookup_get_insert_key(&xfrm_policy_inexact_table,
725 						&bin->k, &bin->head,
726 						xfrm_pol_inexact_params);
727 	if (!prev) {
728 		list_add(&bin->inexact_bins, &net->xfrm.inexact_bins);
729 		return bin;
730 	}
731 
732 	kfree(bin);
733 
734 	return IS_ERR(prev) ? NULL : prev;
735 }
736 
737 static bool xfrm_pol_inexact_addr_use_any_list(const xfrm_address_t *addr,
738 					       int family, u8 prefixlen)
739 {
740 	if (xfrm_addr_any(addr, family))
741 		return true;
742 
743 	if (family == AF_INET6 && prefixlen < INEXACT_PREFIXLEN_IPV6)
744 		return true;
745 
746 	if (family == AF_INET && prefixlen < INEXACT_PREFIXLEN_IPV4)
747 		return true;
748 
749 	return false;
750 }
751 
752 static bool
753 xfrm_policy_inexact_insert_use_any_list(const struct xfrm_policy *policy)
754 {
755 	const xfrm_address_t *addr;
756 	bool saddr_any, daddr_any;
757 	u8 prefixlen;
758 
759 	addr = &policy->selector.saddr;
760 	prefixlen = policy->selector.prefixlen_s;
761 
762 	saddr_any = xfrm_pol_inexact_addr_use_any_list(addr,
763 						       policy->family,
764 						       prefixlen);
765 	addr = &policy->selector.daddr;
766 	prefixlen = policy->selector.prefixlen_d;
767 	daddr_any = xfrm_pol_inexact_addr_use_any_list(addr,
768 						       policy->family,
769 						       prefixlen);
770 	return saddr_any && daddr_any;
771 }
772 
773 static void xfrm_pol_inexact_node_init(struct xfrm_pol_inexact_node *node,
774 				       const xfrm_address_t *addr, u8 prefixlen)
775 {
776 	node->addr = *addr;
777 	node->prefixlen = prefixlen;
778 }
779 
780 static struct xfrm_pol_inexact_node *
781 xfrm_pol_inexact_node_alloc(const xfrm_address_t *addr, u8 prefixlen)
782 {
783 	struct xfrm_pol_inexact_node *node;
784 
785 	node = kzalloc(sizeof(*node), GFP_ATOMIC);
786 	if (node)
787 		xfrm_pol_inexact_node_init(node, addr, prefixlen);
788 
789 	return node;
790 }
791 
792 static int xfrm_policy_addr_delta(const xfrm_address_t *a,
793 				  const xfrm_address_t *b,
794 				  u8 prefixlen, u16 family)
795 {
796 	unsigned int pdw, pbi;
797 	int delta = 0;
798 
799 	switch (family) {
800 	case AF_INET:
801 		if (sizeof(long) == 4 && prefixlen == 0)
802 			return ntohl(a->a4) - ntohl(b->a4);
803 		return (ntohl(a->a4) & ((~0UL << (32 - prefixlen)))) -
804 		       (ntohl(b->a4) & ((~0UL << (32 - prefixlen))));
805 	case AF_INET6:
806 		pdw = prefixlen >> 5;
807 		pbi = prefixlen & 0x1f;
808 
809 		if (pdw) {
810 			delta = memcmp(a->a6, b->a6, pdw << 2);
811 			if (delta)
812 				return delta;
813 		}
814 		if (pbi) {
815 			u32 mask = ~0u << (32 - pbi);
816 
817 			delta = (ntohl(a->a6[pdw]) & mask) -
818 				(ntohl(b->a6[pdw]) & mask);
819 		}
820 		break;
821 	default:
822 		break;
823 	}
824 
825 	return delta;
826 }
827 
828 static void xfrm_policy_inexact_list_reinsert(struct net *net,
829 					      struct xfrm_pol_inexact_node *n,
830 					      u16 family)
831 {
832 	unsigned int matched_s, matched_d;
833 	struct xfrm_policy *policy, *p;
834 
835 	matched_s = 0;
836 	matched_d = 0;
837 
838 	list_for_each_entry_reverse(policy, &net->xfrm.policy_all, walk.all) {
839 		struct hlist_node *newpos = NULL;
840 		bool matches_s, matches_d;
841 
842 		if (!policy->bydst_reinsert)
843 			continue;
844 
845 		WARN_ON_ONCE(policy->family != family);
846 
847 		policy->bydst_reinsert = false;
848 		hlist_for_each_entry(p, &n->hhead, bydst) {
849 			if (policy->priority > p->priority)
850 				newpos = &p->bydst;
851 			else if (policy->priority == p->priority &&
852 				 policy->pos > p->pos)
853 				newpos = &p->bydst;
854 			else
855 				break;
856 		}
857 
858 		if (newpos)
859 			hlist_add_behind_rcu(&policy->bydst, newpos);
860 		else
861 			hlist_add_head_rcu(&policy->bydst, &n->hhead);
862 
863 		/* paranoia checks follow.
864 		 * Check that the reinserted policy matches at least
865 		 * saddr or daddr for current node prefix.
866 		 *
867 		 * Matching both is fine, matching saddr in one policy
868 		 * (but not daddr) and then matching only daddr in another
869 		 * is a bug.
870 		 */
871 		matches_s = xfrm_policy_addr_delta(&policy->selector.saddr,
872 						   &n->addr,
873 						   n->prefixlen,
874 						   family) == 0;
875 		matches_d = xfrm_policy_addr_delta(&policy->selector.daddr,
876 						   &n->addr,
877 						   n->prefixlen,
878 						   family) == 0;
879 		if (matches_s && matches_d)
880 			continue;
881 
882 		WARN_ON_ONCE(!matches_s && !matches_d);
883 		if (matches_s)
884 			matched_s++;
885 		if (matches_d)
886 			matched_d++;
887 		WARN_ON_ONCE(matched_s && matched_d);
888 	}
889 }
890 
891 static void xfrm_policy_inexact_node_reinsert(struct net *net,
892 					      struct xfrm_pol_inexact_node *n,
893 					      struct rb_root *new,
894 					      u16 family)
895 {
896 	struct xfrm_pol_inexact_node *node;
897 	struct rb_node **p, *parent;
898 
899 	/* we should not have another subtree here */
900 	WARN_ON_ONCE(!RB_EMPTY_ROOT(&n->root));
901 restart:
902 	parent = NULL;
903 	p = &new->rb_node;
904 	while (*p) {
905 		u8 prefixlen;
906 		int delta;
907 
908 		parent = *p;
909 		node = rb_entry(*p, struct xfrm_pol_inexact_node, node);
910 
911 		prefixlen = min(node->prefixlen, n->prefixlen);
912 
913 		delta = xfrm_policy_addr_delta(&n->addr, &node->addr,
914 					       prefixlen, family);
915 		if (delta < 0) {
916 			p = &parent->rb_left;
917 		} else if (delta > 0) {
918 			p = &parent->rb_right;
919 		} else {
920 			bool same_prefixlen = node->prefixlen == n->prefixlen;
921 			struct xfrm_policy *tmp;
922 
923 			hlist_for_each_entry(tmp, &n->hhead, bydst) {
924 				tmp->bydst_reinsert = true;
925 				hlist_del_rcu(&tmp->bydst);
926 			}
927 
928 			node->prefixlen = prefixlen;
929 
930 			xfrm_policy_inexact_list_reinsert(net, node, family);
931 
932 			if (same_prefixlen) {
933 				kfree_rcu(n, rcu);
934 				return;
935 			}
936 
937 			rb_erase(*p, new);
938 			kfree_rcu(n, rcu);
939 			n = node;
940 			goto restart;
941 		}
942 	}
943 
944 	rb_link_node_rcu(&n->node, parent, p);
945 	rb_insert_color(&n->node, new);
946 }
947 
948 /* merge nodes v and n */
949 static void xfrm_policy_inexact_node_merge(struct net *net,
950 					   struct xfrm_pol_inexact_node *v,
951 					   struct xfrm_pol_inexact_node *n,
952 					   u16 family)
953 {
954 	struct xfrm_pol_inexact_node *node;
955 	struct xfrm_policy *tmp;
956 	struct rb_node *rnode;
957 
958 	/* To-be-merged node v has a subtree.
959 	 *
960 	 * Dismantle it and insert its nodes to n->root.
961 	 */
962 	while ((rnode = rb_first(&v->root)) != NULL) {
963 		node = rb_entry(rnode, struct xfrm_pol_inexact_node, node);
964 		rb_erase(&node->node, &v->root);
965 		xfrm_policy_inexact_node_reinsert(net, node, &n->root,
966 						  family);
967 	}
968 
969 	hlist_for_each_entry(tmp, &v->hhead, bydst) {
970 		tmp->bydst_reinsert = true;
971 		hlist_del_rcu(&tmp->bydst);
972 	}
973 
974 	xfrm_policy_inexact_list_reinsert(net, n, family);
975 }
976 
977 static struct xfrm_pol_inexact_node *
978 xfrm_policy_inexact_insert_node(struct net *net,
979 				struct rb_root *root,
980 				xfrm_address_t *addr,
981 				u16 family, u8 prefixlen, u8 dir)
982 {
983 	struct xfrm_pol_inexact_node *cached = NULL;
984 	struct rb_node **p, *parent = NULL;
985 	struct xfrm_pol_inexact_node *node;
986 
987 	p = &root->rb_node;
988 	while (*p) {
989 		int delta;
990 
991 		parent = *p;
992 		node = rb_entry(*p, struct xfrm_pol_inexact_node, node);
993 
994 		delta = xfrm_policy_addr_delta(addr, &node->addr,
995 					       node->prefixlen,
996 					       family);
997 		if (delta == 0 && prefixlen >= node->prefixlen) {
998 			WARN_ON_ONCE(cached); /* ipsec policies got lost */
999 			return node;
1000 		}
1001 
1002 		if (delta < 0)
1003 			p = &parent->rb_left;
1004 		else
1005 			p = &parent->rb_right;
1006 
1007 		if (prefixlen < node->prefixlen) {
1008 			delta = xfrm_policy_addr_delta(addr, &node->addr,
1009 						       prefixlen,
1010 						       family);
1011 			if (delta)
1012 				continue;
1013 
1014 			/* This node is a subnet of the new prefix. It needs
1015 			 * to be removed and re-inserted with the smaller
1016 			 * prefix and all nodes that are now also covered
1017 			 * by the reduced prefixlen.
1018 			 */
1019 			rb_erase(&node->node, root);
1020 
1021 			if (!cached) {
1022 				xfrm_pol_inexact_node_init(node, addr,
1023 							   prefixlen);
1024 				cached = node;
1025 			} else {
1026 				/* This node also falls within the new
1027 				 * prefixlen. Merge the to-be-reinserted
1028 				 * node and this one.
1029 				 */
1030 				xfrm_policy_inexact_node_merge(net, node,
1031 							       cached, family);
1032 				kfree_rcu(node, rcu);
1033 			}
1034 
1035 			/* restart */
1036 			p = &root->rb_node;
1037 			parent = NULL;
1038 		}
1039 	}
1040 
1041 	node = cached;
1042 	if (!node) {
1043 		node = xfrm_pol_inexact_node_alloc(addr, prefixlen);
1044 		if (!node)
1045 			return NULL;
1046 	}
1047 
1048 	rb_link_node_rcu(&node->node, parent, p);
1049 	rb_insert_color(&node->node, root);
1050 
1051 	return node;
1052 }
1053 
1054 static void xfrm_policy_inexact_gc_tree(struct rb_root *r, bool rm)
1055 {
1056 	struct xfrm_pol_inexact_node *node;
1057 	struct rb_node *rn = rb_first(r);
1058 
1059 	while (rn) {
1060 		node = rb_entry(rn, struct xfrm_pol_inexact_node, node);
1061 
1062 		xfrm_policy_inexact_gc_tree(&node->root, rm);
1063 		rn = rb_next(rn);
1064 
1065 		if (!hlist_empty(&node->hhead) || !RB_EMPTY_ROOT(&node->root)) {
1066 			WARN_ON_ONCE(rm);
1067 			continue;
1068 		}
1069 
1070 		rb_erase(&node->node, r);
1071 		kfree_rcu(node, rcu);
1072 	}
1073 }
1074 
1075 static void __xfrm_policy_inexact_prune_bin(struct xfrm_pol_inexact_bin *b, bool net_exit)
1076 {
1077 	write_seqcount_begin(&b->count);
1078 	xfrm_policy_inexact_gc_tree(&b->root_d, net_exit);
1079 	xfrm_policy_inexact_gc_tree(&b->root_s, net_exit);
1080 	write_seqcount_end(&b->count);
1081 
1082 	if (!RB_EMPTY_ROOT(&b->root_d) || !RB_EMPTY_ROOT(&b->root_s) ||
1083 	    !hlist_empty(&b->hhead)) {
1084 		WARN_ON_ONCE(net_exit);
1085 		return;
1086 	}
1087 
1088 	if (rhashtable_remove_fast(&xfrm_policy_inexact_table, &b->head,
1089 				   xfrm_pol_inexact_params) == 0) {
1090 		list_del(&b->inexact_bins);
1091 		kfree_rcu(b, rcu);
1092 	}
1093 }
1094 
1095 static void xfrm_policy_inexact_prune_bin(struct xfrm_pol_inexact_bin *b)
1096 {
1097 	struct net *net = read_pnet(&b->k.net);
1098 
1099 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1100 	__xfrm_policy_inexact_prune_bin(b, false);
1101 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1102 }
1103 
1104 static void __xfrm_policy_inexact_flush(struct net *net)
1105 {
1106 	struct xfrm_pol_inexact_bin *bin, *t;
1107 
1108 	lockdep_assert_held(&net->xfrm.xfrm_policy_lock);
1109 
1110 	list_for_each_entry_safe(bin, t, &net->xfrm.inexact_bins, inexact_bins)
1111 		__xfrm_policy_inexact_prune_bin(bin, false);
1112 }
1113 
1114 static struct hlist_head *
1115 xfrm_policy_inexact_alloc_chain(struct xfrm_pol_inexact_bin *bin,
1116 				struct xfrm_policy *policy, u8 dir)
1117 {
1118 	struct xfrm_pol_inexact_node *n;
1119 	struct net *net;
1120 
1121 	net = xp_net(policy);
1122 	lockdep_assert_held(&net->xfrm.xfrm_policy_lock);
1123 
1124 	if (xfrm_policy_inexact_insert_use_any_list(policy))
1125 		return &bin->hhead;
1126 
1127 	if (xfrm_pol_inexact_addr_use_any_list(&policy->selector.daddr,
1128 					       policy->family,
1129 					       policy->selector.prefixlen_d)) {
1130 		write_seqcount_begin(&bin->count);
1131 		n = xfrm_policy_inexact_insert_node(net,
1132 						    &bin->root_s,
1133 						    &policy->selector.saddr,
1134 						    policy->family,
1135 						    policy->selector.prefixlen_s,
1136 						    dir);
1137 		write_seqcount_end(&bin->count);
1138 		if (!n)
1139 			return NULL;
1140 
1141 		return &n->hhead;
1142 	}
1143 
1144 	/* daddr is fixed */
1145 	write_seqcount_begin(&bin->count);
1146 	n = xfrm_policy_inexact_insert_node(net,
1147 					    &bin->root_d,
1148 					    &policy->selector.daddr,
1149 					    policy->family,
1150 					    policy->selector.prefixlen_d, dir);
1151 	write_seqcount_end(&bin->count);
1152 	if (!n)
1153 		return NULL;
1154 
1155 	/* saddr is wildcard */
1156 	if (xfrm_pol_inexact_addr_use_any_list(&policy->selector.saddr,
1157 					       policy->family,
1158 					       policy->selector.prefixlen_s))
1159 		return &n->hhead;
1160 
1161 	write_seqcount_begin(&bin->count);
1162 	n = xfrm_policy_inexact_insert_node(net,
1163 					    &n->root,
1164 					    &policy->selector.saddr,
1165 					    policy->family,
1166 					    policy->selector.prefixlen_s, dir);
1167 	write_seqcount_end(&bin->count);
1168 	if (!n)
1169 		return NULL;
1170 
1171 	return &n->hhead;
1172 }
1173 
1174 static struct xfrm_policy *
1175 xfrm_policy_inexact_insert(struct xfrm_policy *policy, u8 dir, int excl)
1176 {
1177 	struct xfrm_pol_inexact_bin *bin;
1178 	struct xfrm_policy *delpol;
1179 	struct hlist_head *chain;
1180 	struct net *net;
1181 
1182 	bin = xfrm_policy_inexact_alloc_bin(policy, dir);
1183 	if (!bin)
1184 		return ERR_PTR(-ENOMEM);
1185 
1186 	net = xp_net(policy);
1187 	lockdep_assert_held(&net->xfrm.xfrm_policy_lock);
1188 
1189 	chain = xfrm_policy_inexact_alloc_chain(bin, policy, dir);
1190 	if (!chain) {
1191 		__xfrm_policy_inexact_prune_bin(bin, false);
1192 		return ERR_PTR(-ENOMEM);
1193 	}
1194 
1195 	delpol = xfrm_policy_insert_list(chain, policy, excl);
1196 	if (delpol && excl) {
1197 		__xfrm_policy_inexact_prune_bin(bin, false);
1198 		return ERR_PTR(-EEXIST);
1199 	}
1200 
1201 	chain = &net->xfrm.policy_inexact[dir];
1202 	xfrm_policy_insert_inexact_list(chain, policy);
1203 
1204 	if (delpol)
1205 		__xfrm_policy_inexact_prune_bin(bin, false);
1206 
1207 	return delpol;
1208 }
1209 
1210 static void xfrm_hash_rebuild(struct work_struct *work)
1211 {
1212 	struct net *net = container_of(work, struct net,
1213 				       xfrm.policy_hthresh.work);
1214 	unsigned int hmask;
1215 	struct xfrm_policy *pol;
1216 	struct xfrm_policy *policy;
1217 	struct hlist_head *chain;
1218 	struct hlist_head *odst;
1219 	struct hlist_node *newpos;
1220 	int i;
1221 	int dir;
1222 	unsigned seq;
1223 	u8 lbits4, rbits4, lbits6, rbits6;
1224 
1225 	mutex_lock(&hash_resize_mutex);
1226 
1227 	/* read selector prefixlen thresholds */
1228 	do {
1229 		seq = read_seqbegin(&net->xfrm.policy_hthresh.lock);
1230 
1231 		lbits4 = net->xfrm.policy_hthresh.lbits4;
1232 		rbits4 = net->xfrm.policy_hthresh.rbits4;
1233 		lbits6 = net->xfrm.policy_hthresh.lbits6;
1234 		rbits6 = net->xfrm.policy_hthresh.rbits6;
1235 	} while (read_seqretry(&net->xfrm.policy_hthresh.lock, seq));
1236 
1237 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1238 	write_seqcount_begin(&xfrm_policy_hash_generation);
1239 
1240 	/* make sure that we can insert the indirect policies again before
1241 	 * we start with destructive action.
1242 	 */
1243 	list_for_each_entry(policy, &net->xfrm.policy_all, walk.all) {
1244 		struct xfrm_pol_inexact_bin *bin;
1245 		u8 dbits, sbits;
1246 
1247 		dir = xfrm_policy_id2dir(policy->index);
1248 		if (policy->walk.dead || dir >= XFRM_POLICY_MAX)
1249 			continue;
1250 
1251 		if ((dir & XFRM_POLICY_MASK) == XFRM_POLICY_OUT) {
1252 			if (policy->family == AF_INET) {
1253 				dbits = rbits4;
1254 				sbits = lbits4;
1255 			} else {
1256 				dbits = rbits6;
1257 				sbits = lbits6;
1258 			}
1259 		} else {
1260 			if (policy->family == AF_INET) {
1261 				dbits = lbits4;
1262 				sbits = rbits4;
1263 			} else {
1264 				dbits = lbits6;
1265 				sbits = rbits6;
1266 			}
1267 		}
1268 
1269 		if (policy->selector.prefixlen_d < dbits ||
1270 		    policy->selector.prefixlen_s < sbits)
1271 			continue;
1272 
1273 		bin = xfrm_policy_inexact_alloc_bin(policy, dir);
1274 		if (!bin)
1275 			goto out_unlock;
1276 
1277 		if (!xfrm_policy_inexact_alloc_chain(bin, policy, dir))
1278 			goto out_unlock;
1279 	}
1280 
1281 	/* reset the bydst and inexact table in all directions */
1282 	for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
1283 		struct hlist_node *n;
1284 
1285 		hlist_for_each_entry_safe(policy, n,
1286 					  &net->xfrm.policy_inexact[dir],
1287 					  bydst_inexact_list) {
1288 			hlist_del_rcu(&policy->bydst);
1289 			hlist_del_init(&policy->bydst_inexact_list);
1290 		}
1291 
1292 		hmask = net->xfrm.policy_bydst[dir].hmask;
1293 		odst = net->xfrm.policy_bydst[dir].table;
1294 		for (i = hmask; i >= 0; i--) {
1295 			hlist_for_each_entry_safe(policy, n, odst + i, bydst)
1296 				hlist_del_rcu(&policy->bydst);
1297 		}
1298 		if ((dir & XFRM_POLICY_MASK) == XFRM_POLICY_OUT) {
1299 			/* dir out => dst = remote, src = local */
1300 			net->xfrm.policy_bydst[dir].dbits4 = rbits4;
1301 			net->xfrm.policy_bydst[dir].sbits4 = lbits4;
1302 			net->xfrm.policy_bydst[dir].dbits6 = rbits6;
1303 			net->xfrm.policy_bydst[dir].sbits6 = lbits6;
1304 		} else {
1305 			/* dir in/fwd => dst = local, src = remote */
1306 			net->xfrm.policy_bydst[dir].dbits4 = lbits4;
1307 			net->xfrm.policy_bydst[dir].sbits4 = rbits4;
1308 			net->xfrm.policy_bydst[dir].dbits6 = lbits6;
1309 			net->xfrm.policy_bydst[dir].sbits6 = rbits6;
1310 		}
1311 	}
1312 
1313 	/* re-insert all policies by order of creation */
1314 	list_for_each_entry_reverse(policy, &net->xfrm.policy_all, walk.all) {
1315 		if (policy->walk.dead)
1316 			continue;
1317 		dir = xfrm_policy_id2dir(policy->index);
1318 		if (dir >= XFRM_POLICY_MAX) {
1319 			/* skip socket policies */
1320 			continue;
1321 		}
1322 		newpos = NULL;
1323 		chain = policy_hash_bysel(net, &policy->selector,
1324 					  policy->family, dir);
1325 
1326 		if (!chain) {
1327 			void *p = xfrm_policy_inexact_insert(policy, dir, 0);
1328 
1329 			WARN_ONCE(IS_ERR(p), "reinsert: %ld\n", PTR_ERR(p));
1330 			continue;
1331 		}
1332 
1333 		hlist_for_each_entry(pol, chain, bydst) {
1334 			if (policy->priority >= pol->priority)
1335 				newpos = &pol->bydst;
1336 			else
1337 				break;
1338 		}
1339 		if (newpos)
1340 			hlist_add_behind_rcu(&policy->bydst, newpos);
1341 		else
1342 			hlist_add_head_rcu(&policy->bydst, chain);
1343 	}
1344 
1345 out_unlock:
1346 	__xfrm_policy_inexact_flush(net);
1347 	write_seqcount_end(&xfrm_policy_hash_generation);
1348 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1349 
1350 	mutex_unlock(&hash_resize_mutex);
1351 }
1352 
1353 void xfrm_policy_hash_rebuild(struct net *net)
1354 {
1355 	schedule_work(&net->xfrm.policy_hthresh.work);
1356 }
1357 EXPORT_SYMBOL(xfrm_policy_hash_rebuild);
1358 
1359 /* Generate new index... KAME seems to generate them ordered by cost
1360  * of an absolute inpredictability of ordering of rules. This will not pass. */
1361 static u32 xfrm_gen_index(struct net *net, int dir, u32 index)
1362 {
1363 	static u32 idx_generator;
1364 
1365 	for (;;) {
1366 		struct hlist_head *list;
1367 		struct xfrm_policy *p;
1368 		u32 idx;
1369 		int found;
1370 
1371 		if (!index) {
1372 			idx = (idx_generator | dir);
1373 			idx_generator += 8;
1374 		} else {
1375 			idx = index;
1376 			index = 0;
1377 		}
1378 
1379 		if (idx == 0)
1380 			idx = 8;
1381 		list = net->xfrm.policy_byidx + idx_hash(net, idx);
1382 		found = 0;
1383 		hlist_for_each_entry(p, list, byidx) {
1384 			if (p->index == idx) {
1385 				found = 1;
1386 				break;
1387 			}
1388 		}
1389 		if (!found)
1390 			return idx;
1391 	}
1392 }
1393 
1394 static inline int selector_cmp(struct xfrm_selector *s1, struct xfrm_selector *s2)
1395 {
1396 	u32 *p1 = (u32 *) s1;
1397 	u32 *p2 = (u32 *) s2;
1398 	int len = sizeof(struct xfrm_selector) / sizeof(u32);
1399 	int i;
1400 
1401 	for (i = 0; i < len; i++) {
1402 		if (p1[i] != p2[i])
1403 			return 1;
1404 	}
1405 
1406 	return 0;
1407 }
1408 
1409 static void xfrm_policy_requeue(struct xfrm_policy *old,
1410 				struct xfrm_policy *new)
1411 {
1412 	struct xfrm_policy_queue *pq = &old->polq;
1413 	struct sk_buff_head list;
1414 
1415 	if (skb_queue_empty(&pq->hold_queue))
1416 		return;
1417 
1418 	__skb_queue_head_init(&list);
1419 
1420 	spin_lock_bh(&pq->hold_queue.lock);
1421 	skb_queue_splice_init(&pq->hold_queue, &list);
1422 	if (del_timer(&pq->hold_timer))
1423 		xfrm_pol_put(old);
1424 	spin_unlock_bh(&pq->hold_queue.lock);
1425 
1426 	pq = &new->polq;
1427 
1428 	spin_lock_bh(&pq->hold_queue.lock);
1429 	skb_queue_splice(&list, &pq->hold_queue);
1430 	pq->timeout = XFRM_QUEUE_TMO_MIN;
1431 	if (!mod_timer(&pq->hold_timer, jiffies))
1432 		xfrm_pol_hold(new);
1433 	spin_unlock_bh(&pq->hold_queue.lock);
1434 }
1435 
1436 static bool xfrm_policy_mark_match(struct xfrm_policy *policy,
1437 				   struct xfrm_policy *pol)
1438 {
1439 	u32 mark = policy->mark.v & policy->mark.m;
1440 
1441 	if (policy->mark.v == pol->mark.v && policy->mark.m == pol->mark.m)
1442 		return true;
1443 
1444 	if ((mark & pol->mark.m) == pol->mark.v &&
1445 	    policy->priority == pol->priority)
1446 		return true;
1447 
1448 	return false;
1449 }
1450 
1451 static u32 xfrm_pol_bin_key(const void *data, u32 len, u32 seed)
1452 {
1453 	const struct xfrm_pol_inexact_key *k = data;
1454 	u32 a = k->type << 24 | k->dir << 16 | k->family;
1455 
1456 	return jhash_3words(a, k->if_id, net_hash_mix(read_pnet(&k->net)),
1457 			    seed);
1458 }
1459 
1460 static u32 xfrm_pol_bin_obj(const void *data, u32 len, u32 seed)
1461 {
1462 	const struct xfrm_pol_inexact_bin *b = data;
1463 
1464 	return xfrm_pol_bin_key(&b->k, 0, seed);
1465 }
1466 
1467 static int xfrm_pol_bin_cmp(struct rhashtable_compare_arg *arg,
1468 			    const void *ptr)
1469 {
1470 	const struct xfrm_pol_inexact_key *key = arg->key;
1471 	const struct xfrm_pol_inexact_bin *b = ptr;
1472 	int ret;
1473 
1474 	if (!net_eq(read_pnet(&b->k.net), read_pnet(&key->net)))
1475 		return -1;
1476 
1477 	ret = b->k.dir ^ key->dir;
1478 	if (ret)
1479 		return ret;
1480 
1481 	ret = b->k.type ^ key->type;
1482 	if (ret)
1483 		return ret;
1484 
1485 	ret = b->k.family ^ key->family;
1486 	if (ret)
1487 		return ret;
1488 
1489 	return b->k.if_id ^ key->if_id;
1490 }
1491 
1492 static const struct rhashtable_params xfrm_pol_inexact_params = {
1493 	.head_offset		= offsetof(struct xfrm_pol_inexact_bin, head),
1494 	.hashfn			= xfrm_pol_bin_key,
1495 	.obj_hashfn		= xfrm_pol_bin_obj,
1496 	.obj_cmpfn		= xfrm_pol_bin_cmp,
1497 	.automatic_shrinking	= true,
1498 };
1499 
1500 static void xfrm_policy_insert_inexact_list(struct hlist_head *chain,
1501 					    struct xfrm_policy *policy)
1502 {
1503 	struct xfrm_policy *pol, *delpol = NULL;
1504 	struct hlist_node *newpos = NULL;
1505 	int i = 0;
1506 
1507 	hlist_for_each_entry(pol, chain, bydst_inexact_list) {
1508 		if (pol->type == policy->type &&
1509 		    pol->if_id == policy->if_id &&
1510 		    !selector_cmp(&pol->selector, &policy->selector) &&
1511 		    xfrm_policy_mark_match(policy, pol) &&
1512 		    xfrm_sec_ctx_match(pol->security, policy->security) &&
1513 		    !WARN_ON(delpol)) {
1514 			delpol = pol;
1515 			if (policy->priority > pol->priority)
1516 				continue;
1517 		} else if (policy->priority >= pol->priority) {
1518 			newpos = &pol->bydst_inexact_list;
1519 			continue;
1520 		}
1521 		if (delpol)
1522 			break;
1523 	}
1524 
1525 	if (newpos)
1526 		hlist_add_behind_rcu(&policy->bydst_inexact_list, newpos);
1527 	else
1528 		hlist_add_head_rcu(&policy->bydst_inexact_list, chain);
1529 
1530 	hlist_for_each_entry(pol, chain, bydst_inexact_list) {
1531 		pol->pos = i;
1532 		i++;
1533 	}
1534 }
1535 
1536 static struct xfrm_policy *xfrm_policy_insert_list(struct hlist_head *chain,
1537 						   struct xfrm_policy *policy,
1538 						   bool excl)
1539 {
1540 	struct xfrm_policy *pol, *newpos = NULL, *delpol = NULL;
1541 
1542 	hlist_for_each_entry(pol, chain, bydst) {
1543 		if (pol->type == policy->type &&
1544 		    pol->if_id == policy->if_id &&
1545 		    !selector_cmp(&pol->selector, &policy->selector) &&
1546 		    xfrm_policy_mark_match(policy, pol) &&
1547 		    xfrm_sec_ctx_match(pol->security, policy->security) &&
1548 		    !WARN_ON(delpol)) {
1549 			if (excl)
1550 				return ERR_PTR(-EEXIST);
1551 			delpol = pol;
1552 			if (policy->priority > pol->priority)
1553 				continue;
1554 		} else if (policy->priority >= pol->priority) {
1555 			newpos = pol;
1556 			continue;
1557 		}
1558 		if (delpol)
1559 			break;
1560 	}
1561 
1562 	if (newpos)
1563 		hlist_add_behind_rcu(&policy->bydst, &newpos->bydst);
1564 	else
1565 		hlist_add_head_rcu(&policy->bydst, chain);
1566 
1567 	return delpol;
1568 }
1569 
1570 int xfrm_policy_insert(int dir, struct xfrm_policy *policy, int excl)
1571 {
1572 	struct net *net = xp_net(policy);
1573 	struct xfrm_policy *delpol;
1574 	struct hlist_head *chain;
1575 
1576 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1577 	chain = policy_hash_bysel(net, &policy->selector, policy->family, dir);
1578 	if (chain)
1579 		delpol = xfrm_policy_insert_list(chain, policy, excl);
1580 	else
1581 		delpol = xfrm_policy_inexact_insert(policy, dir, excl);
1582 
1583 	if (IS_ERR(delpol)) {
1584 		spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1585 		return PTR_ERR(delpol);
1586 	}
1587 
1588 	__xfrm_policy_link(policy, dir);
1589 
1590 	/* After previous checking, family can either be AF_INET or AF_INET6 */
1591 	if (policy->family == AF_INET)
1592 		rt_genid_bump_ipv4(net);
1593 	else
1594 		rt_genid_bump_ipv6(net);
1595 
1596 	if (delpol) {
1597 		xfrm_policy_requeue(delpol, policy);
1598 		__xfrm_policy_unlink(delpol, dir);
1599 	}
1600 	policy->index = delpol ? delpol->index : xfrm_gen_index(net, dir, policy->index);
1601 	hlist_add_head(&policy->byidx, net->xfrm.policy_byidx+idx_hash(net, policy->index));
1602 	policy->curlft.add_time = ktime_get_real_seconds();
1603 	policy->curlft.use_time = 0;
1604 	if (!mod_timer(&policy->timer, jiffies + HZ))
1605 		xfrm_pol_hold(policy);
1606 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1607 
1608 	if (delpol)
1609 		xfrm_policy_kill(delpol);
1610 	else if (xfrm_bydst_should_resize(net, dir, NULL))
1611 		schedule_work(&net->xfrm.policy_hash_work);
1612 
1613 	return 0;
1614 }
1615 EXPORT_SYMBOL(xfrm_policy_insert);
1616 
1617 static struct xfrm_policy *
1618 __xfrm_policy_bysel_ctx(struct hlist_head *chain, u32 mark, u32 if_id,
1619 			u8 type, int dir,
1620 			struct xfrm_selector *sel,
1621 			struct xfrm_sec_ctx *ctx)
1622 {
1623 	struct xfrm_policy *pol;
1624 
1625 	if (!chain)
1626 		return NULL;
1627 
1628 	hlist_for_each_entry(pol, chain, bydst) {
1629 		if (pol->type == type &&
1630 		    pol->if_id == if_id &&
1631 		    (mark & pol->mark.m) == pol->mark.v &&
1632 		    !selector_cmp(sel, &pol->selector) &&
1633 		    xfrm_sec_ctx_match(ctx, pol->security))
1634 			return pol;
1635 	}
1636 
1637 	return NULL;
1638 }
1639 
1640 struct xfrm_policy *xfrm_policy_bysel_ctx(struct net *net, u32 mark, u32 if_id,
1641 					  u8 type, int dir,
1642 					  struct xfrm_selector *sel,
1643 					  struct xfrm_sec_ctx *ctx, int delete,
1644 					  int *err)
1645 {
1646 	struct xfrm_pol_inexact_bin *bin = NULL;
1647 	struct xfrm_policy *pol, *ret = NULL;
1648 	struct hlist_head *chain;
1649 
1650 	*err = 0;
1651 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1652 	chain = policy_hash_bysel(net, sel, sel->family, dir);
1653 	if (!chain) {
1654 		struct xfrm_pol_inexact_candidates cand;
1655 		int i;
1656 
1657 		bin = xfrm_policy_inexact_lookup(net, type,
1658 						 sel->family, dir, if_id);
1659 		if (!bin) {
1660 			spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1661 			return NULL;
1662 		}
1663 
1664 		if (!xfrm_policy_find_inexact_candidates(&cand, bin,
1665 							 &sel->saddr,
1666 							 &sel->daddr)) {
1667 			spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1668 			return NULL;
1669 		}
1670 
1671 		pol = NULL;
1672 		for (i = 0; i < ARRAY_SIZE(cand.res); i++) {
1673 			struct xfrm_policy *tmp;
1674 
1675 			tmp = __xfrm_policy_bysel_ctx(cand.res[i], mark,
1676 						      if_id, type, dir,
1677 						      sel, ctx);
1678 			if (!tmp)
1679 				continue;
1680 
1681 			if (!pol || tmp->pos < pol->pos)
1682 				pol = tmp;
1683 		}
1684 	} else {
1685 		pol = __xfrm_policy_bysel_ctx(chain, mark, if_id, type, dir,
1686 					      sel, ctx);
1687 	}
1688 
1689 	if (pol) {
1690 		xfrm_pol_hold(pol);
1691 		if (delete) {
1692 			*err = security_xfrm_policy_delete(pol->security);
1693 			if (*err) {
1694 				spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1695 				return pol;
1696 			}
1697 			__xfrm_policy_unlink(pol, dir);
1698 		}
1699 		ret = pol;
1700 	}
1701 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1702 
1703 	if (ret && delete)
1704 		xfrm_policy_kill(ret);
1705 	if (bin && delete)
1706 		xfrm_policy_inexact_prune_bin(bin);
1707 	return ret;
1708 }
1709 EXPORT_SYMBOL(xfrm_policy_bysel_ctx);
1710 
1711 struct xfrm_policy *xfrm_policy_byid(struct net *net, u32 mark, u32 if_id,
1712 				     u8 type, int dir, u32 id, int delete,
1713 				     int *err)
1714 {
1715 	struct xfrm_policy *pol, *ret;
1716 	struct hlist_head *chain;
1717 
1718 	*err = -ENOENT;
1719 	if (xfrm_policy_id2dir(id) != dir)
1720 		return NULL;
1721 
1722 	*err = 0;
1723 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1724 	chain = net->xfrm.policy_byidx + idx_hash(net, id);
1725 	ret = NULL;
1726 	hlist_for_each_entry(pol, chain, byidx) {
1727 		if (pol->type == type && pol->index == id &&
1728 		    pol->if_id == if_id &&
1729 		    (mark & pol->mark.m) == pol->mark.v) {
1730 			xfrm_pol_hold(pol);
1731 			if (delete) {
1732 				*err = security_xfrm_policy_delete(
1733 								pol->security);
1734 				if (*err) {
1735 					spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1736 					return pol;
1737 				}
1738 				__xfrm_policy_unlink(pol, dir);
1739 			}
1740 			ret = pol;
1741 			break;
1742 		}
1743 	}
1744 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1745 
1746 	if (ret && delete)
1747 		xfrm_policy_kill(ret);
1748 	return ret;
1749 }
1750 EXPORT_SYMBOL(xfrm_policy_byid);
1751 
1752 #ifdef CONFIG_SECURITY_NETWORK_XFRM
1753 static inline int
1754 xfrm_policy_flush_secctx_check(struct net *net, u8 type, bool task_valid)
1755 {
1756 	struct xfrm_policy *pol;
1757 	int err = 0;
1758 
1759 	list_for_each_entry(pol, &net->xfrm.policy_all, walk.all) {
1760 		if (pol->walk.dead ||
1761 		    xfrm_policy_id2dir(pol->index) >= XFRM_POLICY_MAX ||
1762 		    pol->type != type)
1763 			continue;
1764 
1765 		err = security_xfrm_policy_delete(pol->security);
1766 		if (err) {
1767 			xfrm_audit_policy_delete(pol, 0, task_valid);
1768 			return err;
1769 		}
1770 	}
1771 	return err;
1772 }
1773 #else
1774 static inline int
1775 xfrm_policy_flush_secctx_check(struct net *net, u8 type, bool task_valid)
1776 {
1777 	return 0;
1778 }
1779 #endif
1780 
1781 int xfrm_policy_flush(struct net *net, u8 type, bool task_valid)
1782 {
1783 	int dir, err = 0, cnt = 0;
1784 	struct xfrm_policy *pol;
1785 
1786 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1787 
1788 	err = xfrm_policy_flush_secctx_check(net, type, task_valid);
1789 	if (err)
1790 		goto out;
1791 
1792 again:
1793 	list_for_each_entry(pol, &net->xfrm.policy_all, walk.all) {
1794 		dir = xfrm_policy_id2dir(pol->index);
1795 		if (pol->walk.dead ||
1796 		    dir >= XFRM_POLICY_MAX ||
1797 		    pol->type != type)
1798 			continue;
1799 
1800 		__xfrm_policy_unlink(pol, dir);
1801 		spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1802 		cnt++;
1803 		xfrm_audit_policy_delete(pol, 1, task_valid);
1804 		xfrm_policy_kill(pol);
1805 		spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1806 		goto again;
1807 	}
1808 	if (cnt)
1809 		__xfrm_policy_inexact_flush(net);
1810 	else
1811 		err = -ESRCH;
1812 out:
1813 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1814 	return err;
1815 }
1816 EXPORT_SYMBOL(xfrm_policy_flush);
1817 
1818 int xfrm_policy_walk(struct net *net, struct xfrm_policy_walk *walk,
1819 		     int (*func)(struct xfrm_policy *, int, int, void*),
1820 		     void *data)
1821 {
1822 	struct xfrm_policy *pol;
1823 	struct xfrm_policy_walk_entry *x;
1824 	int error = 0;
1825 
1826 	if (walk->type >= XFRM_POLICY_TYPE_MAX &&
1827 	    walk->type != XFRM_POLICY_TYPE_ANY)
1828 		return -EINVAL;
1829 
1830 	if (list_empty(&walk->walk.all) && walk->seq != 0)
1831 		return 0;
1832 
1833 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1834 	if (list_empty(&walk->walk.all))
1835 		x = list_first_entry(&net->xfrm.policy_all, struct xfrm_policy_walk_entry, all);
1836 	else
1837 		x = list_first_entry(&walk->walk.all,
1838 				     struct xfrm_policy_walk_entry, all);
1839 
1840 	list_for_each_entry_from(x, &net->xfrm.policy_all, all) {
1841 		if (x->dead)
1842 			continue;
1843 		pol = container_of(x, struct xfrm_policy, walk);
1844 		if (walk->type != XFRM_POLICY_TYPE_ANY &&
1845 		    walk->type != pol->type)
1846 			continue;
1847 		error = func(pol, xfrm_policy_id2dir(pol->index),
1848 			     walk->seq, data);
1849 		if (error) {
1850 			list_move_tail(&walk->walk.all, &x->all);
1851 			goto out;
1852 		}
1853 		walk->seq++;
1854 	}
1855 	if (walk->seq == 0) {
1856 		error = -ENOENT;
1857 		goto out;
1858 	}
1859 	list_del_init(&walk->walk.all);
1860 out:
1861 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1862 	return error;
1863 }
1864 EXPORT_SYMBOL(xfrm_policy_walk);
1865 
1866 void xfrm_policy_walk_init(struct xfrm_policy_walk *walk, u8 type)
1867 {
1868 	INIT_LIST_HEAD(&walk->walk.all);
1869 	walk->walk.dead = 1;
1870 	walk->type = type;
1871 	walk->seq = 0;
1872 }
1873 EXPORT_SYMBOL(xfrm_policy_walk_init);
1874 
1875 void xfrm_policy_walk_done(struct xfrm_policy_walk *walk, struct net *net)
1876 {
1877 	if (list_empty(&walk->walk.all))
1878 		return;
1879 
1880 	spin_lock_bh(&net->xfrm.xfrm_policy_lock); /*FIXME where is net? */
1881 	list_del(&walk->walk.all);
1882 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1883 }
1884 EXPORT_SYMBOL(xfrm_policy_walk_done);
1885 
1886 /*
1887  * Find policy to apply to this flow.
1888  *
1889  * Returns 0 if policy found, else an -errno.
1890  */
1891 static int xfrm_policy_match(const struct xfrm_policy *pol,
1892 			     const struct flowi *fl,
1893 			     u8 type, u16 family, int dir, u32 if_id)
1894 {
1895 	const struct xfrm_selector *sel = &pol->selector;
1896 	int ret = -ESRCH;
1897 	bool match;
1898 
1899 	if (pol->family != family ||
1900 	    pol->if_id != if_id ||
1901 	    (fl->flowi_mark & pol->mark.m) != pol->mark.v ||
1902 	    pol->type != type)
1903 		return ret;
1904 
1905 	match = xfrm_selector_match(sel, fl, family);
1906 	if (match)
1907 		ret = security_xfrm_policy_lookup(pol->security, fl->flowi_secid,
1908 						  dir);
1909 	return ret;
1910 }
1911 
1912 static struct xfrm_pol_inexact_node *
1913 xfrm_policy_lookup_inexact_addr(const struct rb_root *r,
1914 				seqcount_t *count,
1915 				const xfrm_address_t *addr, u16 family)
1916 {
1917 	const struct rb_node *parent;
1918 	int seq;
1919 
1920 again:
1921 	seq = read_seqcount_begin(count);
1922 
1923 	parent = rcu_dereference_raw(r->rb_node);
1924 	while (parent) {
1925 		struct xfrm_pol_inexact_node *node;
1926 		int delta;
1927 
1928 		node = rb_entry(parent, struct xfrm_pol_inexact_node, node);
1929 
1930 		delta = xfrm_policy_addr_delta(addr, &node->addr,
1931 					       node->prefixlen, family);
1932 		if (delta < 0) {
1933 			parent = rcu_dereference_raw(parent->rb_left);
1934 			continue;
1935 		} else if (delta > 0) {
1936 			parent = rcu_dereference_raw(parent->rb_right);
1937 			continue;
1938 		}
1939 
1940 		return node;
1941 	}
1942 
1943 	if (read_seqcount_retry(count, seq))
1944 		goto again;
1945 
1946 	return NULL;
1947 }
1948 
1949 static bool
1950 xfrm_policy_find_inexact_candidates(struct xfrm_pol_inexact_candidates *cand,
1951 				    struct xfrm_pol_inexact_bin *b,
1952 				    const xfrm_address_t *saddr,
1953 				    const xfrm_address_t *daddr)
1954 {
1955 	struct xfrm_pol_inexact_node *n;
1956 	u16 family;
1957 
1958 	if (!b)
1959 		return false;
1960 
1961 	family = b->k.family;
1962 	memset(cand, 0, sizeof(*cand));
1963 	cand->res[XFRM_POL_CAND_ANY] = &b->hhead;
1964 
1965 	n = xfrm_policy_lookup_inexact_addr(&b->root_d, &b->count, daddr,
1966 					    family);
1967 	if (n) {
1968 		cand->res[XFRM_POL_CAND_DADDR] = &n->hhead;
1969 		n = xfrm_policy_lookup_inexact_addr(&n->root, &b->count, saddr,
1970 						    family);
1971 		if (n)
1972 			cand->res[XFRM_POL_CAND_BOTH] = &n->hhead;
1973 	}
1974 
1975 	n = xfrm_policy_lookup_inexact_addr(&b->root_s, &b->count, saddr,
1976 					    family);
1977 	if (n)
1978 		cand->res[XFRM_POL_CAND_SADDR] = &n->hhead;
1979 
1980 	return true;
1981 }
1982 
1983 static struct xfrm_pol_inexact_bin *
1984 xfrm_policy_inexact_lookup_rcu(struct net *net, u8 type, u16 family,
1985 			       u8 dir, u32 if_id)
1986 {
1987 	struct xfrm_pol_inexact_key k = {
1988 		.family = family,
1989 		.type = type,
1990 		.dir = dir,
1991 		.if_id = if_id,
1992 	};
1993 
1994 	write_pnet(&k.net, net);
1995 
1996 	return rhashtable_lookup(&xfrm_policy_inexact_table, &k,
1997 				 xfrm_pol_inexact_params);
1998 }
1999 
2000 static struct xfrm_pol_inexact_bin *
2001 xfrm_policy_inexact_lookup(struct net *net, u8 type, u16 family,
2002 			   u8 dir, u32 if_id)
2003 {
2004 	struct xfrm_pol_inexact_bin *bin;
2005 
2006 	lockdep_assert_held(&net->xfrm.xfrm_policy_lock);
2007 
2008 	rcu_read_lock();
2009 	bin = xfrm_policy_inexact_lookup_rcu(net, type, family, dir, if_id);
2010 	rcu_read_unlock();
2011 
2012 	return bin;
2013 }
2014 
2015 static struct xfrm_policy *
2016 __xfrm_policy_eval_candidates(struct hlist_head *chain,
2017 			      struct xfrm_policy *prefer,
2018 			      const struct flowi *fl,
2019 			      u8 type, u16 family, int dir, u32 if_id)
2020 {
2021 	u32 priority = prefer ? prefer->priority : ~0u;
2022 	struct xfrm_policy *pol;
2023 
2024 	if (!chain)
2025 		return NULL;
2026 
2027 	hlist_for_each_entry_rcu(pol, chain, bydst) {
2028 		int err;
2029 
2030 		if (pol->priority > priority)
2031 			break;
2032 
2033 		err = xfrm_policy_match(pol, fl, type, family, dir, if_id);
2034 		if (err) {
2035 			if (err != -ESRCH)
2036 				return ERR_PTR(err);
2037 
2038 			continue;
2039 		}
2040 
2041 		if (prefer) {
2042 			/* matches.  Is it older than *prefer? */
2043 			if (pol->priority == priority &&
2044 			    prefer->pos < pol->pos)
2045 				return prefer;
2046 		}
2047 
2048 		return pol;
2049 	}
2050 
2051 	return NULL;
2052 }
2053 
2054 static struct xfrm_policy *
2055 xfrm_policy_eval_candidates(struct xfrm_pol_inexact_candidates *cand,
2056 			    struct xfrm_policy *prefer,
2057 			    const struct flowi *fl,
2058 			    u8 type, u16 family, int dir, u32 if_id)
2059 {
2060 	struct xfrm_policy *tmp;
2061 	int i;
2062 
2063 	for (i = 0; i < ARRAY_SIZE(cand->res); i++) {
2064 		tmp = __xfrm_policy_eval_candidates(cand->res[i],
2065 						    prefer,
2066 						    fl, type, family, dir,
2067 						    if_id);
2068 		if (!tmp)
2069 			continue;
2070 
2071 		if (IS_ERR(tmp))
2072 			return tmp;
2073 		prefer = tmp;
2074 	}
2075 
2076 	return prefer;
2077 }
2078 
2079 static struct xfrm_policy *xfrm_policy_lookup_bytype(struct net *net, u8 type,
2080 						     const struct flowi *fl,
2081 						     u16 family, u8 dir,
2082 						     u32 if_id)
2083 {
2084 	struct xfrm_pol_inexact_candidates cand;
2085 	const xfrm_address_t *daddr, *saddr;
2086 	struct xfrm_pol_inexact_bin *bin;
2087 	struct xfrm_policy *pol, *ret;
2088 	struct hlist_head *chain;
2089 	unsigned int sequence;
2090 	int err;
2091 
2092 	daddr = xfrm_flowi_daddr(fl, family);
2093 	saddr = xfrm_flowi_saddr(fl, family);
2094 	if (unlikely(!daddr || !saddr))
2095 		return NULL;
2096 
2097 	rcu_read_lock();
2098  retry:
2099 	do {
2100 		sequence = read_seqcount_begin(&xfrm_policy_hash_generation);
2101 		chain = policy_hash_direct(net, daddr, saddr, family, dir);
2102 	} while (read_seqcount_retry(&xfrm_policy_hash_generation, sequence));
2103 
2104 	ret = NULL;
2105 	hlist_for_each_entry_rcu(pol, chain, bydst) {
2106 		err = xfrm_policy_match(pol, fl, type, family, dir, if_id);
2107 		if (err) {
2108 			if (err == -ESRCH)
2109 				continue;
2110 			else {
2111 				ret = ERR_PTR(err);
2112 				goto fail;
2113 			}
2114 		} else {
2115 			ret = pol;
2116 			break;
2117 		}
2118 	}
2119 	bin = xfrm_policy_inexact_lookup_rcu(net, type, family, dir, if_id);
2120 	if (!bin || !xfrm_policy_find_inexact_candidates(&cand, bin, saddr,
2121 							 daddr))
2122 		goto skip_inexact;
2123 
2124 	pol = xfrm_policy_eval_candidates(&cand, ret, fl, type,
2125 					  family, dir, if_id);
2126 	if (pol) {
2127 		ret = pol;
2128 		if (IS_ERR(pol))
2129 			goto fail;
2130 	}
2131 
2132 skip_inexact:
2133 	if (read_seqcount_retry(&xfrm_policy_hash_generation, sequence))
2134 		goto retry;
2135 
2136 	if (ret && !xfrm_pol_hold_rcu(ret))
2137 		goto retry;
2138 fail:
2139 	rcu_read_unlock();
2140 
2141 	return ret;
2142 }
2143 
2144 static struct xfrm_policy *xfrm_policy_lookup(struct net *net,
2145 					      const struct flowi *fl,
2146 					      u16 family, u8 dir, u32 if_id)
2147 {
2148 #ifdef CONFIG_XFRM_SUB_POLICY
2149 	struct xfrm_policy *pol;
2150 
2151 	pol = xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_SUB, fl, family,
2152 					dir, if_id);
2153 	if (pol != NULL)
2154 		return pol;
2155 #endif
2156 	return xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_MAIN, fl, family,
2157 					 dir, if_id);
2158 }
2159 
2160 static struct xfrm_policy *xfrm_sk_policy_lookup(const struct sock *sk, int dir,
2161 						 const struct flowi *fl,
2162 						 u16 family, u32 if_id)
2163 {
2164 	struct xfrm_policy *pol;
2165 
2166 	rcu_read_lock();
2167  again:
2168 	pol = rcu_dereference(sk->sk_policy[dir]);
2169 	if (pol != NULL) {
2170 		bool match;
2171 		int err = 0;
2172 
2173 		if (pol->family != family) {
2174 			pol = NULL;
2175 			goto out;
2176 		}
2177 
2178 		match = xfrm_selector_match(&pol->selector, fl, family);
2179 		if (match) {
2180 			if ((sk->sk_mark & pol->mark.m) != pol->mark.v ||
2181 			    pol->if_id != if_id) {
2182 				pol = NULL;
2183 				goto out;
2184 			}
2185 			err = security_xfrm_policy_lookup(pol->security,
2186 						      fl->flowi_secid,
2187 						      dir);
2188 			if (!err) {
2189 				if (!xfrm_pol_hold_rcu(pol))
2190 					goto again;
2191 			} else if (err == -ESRCH) {
2192 				pol = NULL;
2193 			} else {
2194 				pol = ERR_PTR(err);
2195 			}
2196 		} else
2197 			pol = NULL;
2198 	}
2199 out:
2200 	rcu_read_unlock();
2201 	return pol;
2202 }
2203 
2204 static void __xfrm_policy_link(struct xfrm_policy *pol, int dir)
2205 {
2206 	struct net *net = xp_net(pol);
2207 
2208 	list_add(&pol->walk.all, &net->xfrm.policy_all);
2209 	net->xfrm.policy_count[dir]++;
2210 	xfrm_pol_hold(pol);
2211 }
2212 
2213 static struct xfrm_policy *__xfrm_policy_unlink(struct xfrm_policy *pol,
2214 						int dir)
2215 {
2216 	struct net *net = xp_net(pol);
2217 
2218 	if (list_empty(&pol->walk.all))
2219 		return NULL;
2220 
2221 	/* Socket policies are not hashed. */
2222 	if (!hlist_unhashed(&pol->bydst)) {
2223 		hlist_del_rcu(&pol->bydst);
2224 		hlist_del_init(&pol->bydst_inexact_list);
2225 		hlist_del(&pol->byidx);
2226 	}
2227 
2228 	list_del_init(&pol->walk.all);
2229 	net->xfrm.policy_count[dir]--;
2230 
2231 	return pol;
2232 }
2233 
2234 static void xfrm_sk_policy_link(struct xfrm_policy *pol, int dir)
2235 {
2236 	__xfrm_policy_link(pol, XFRM_POLICY_MAX + dir);
2237 }
2238 
2239 static void xfrm_sk_policy_unlink(struct xfrm_policy *pol, int dir)
2240 {
2241 	__xfrm_policy_unlink(pol, XFRM_POLICY_MAX + dir);
2242 }
2243 
2244 int xfrm_policy_delete(struct xfrm_policy *pol, int dir)
2245 {
2246 	struct net *net = xp_net(pol);
2247 
2248 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
2249 	pol = __xfrm_policy_unlink(pol, dir);
2250 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
2251 	if (pol) {
2252 		xfrm_policy_kill(pol);
2253 		return 0;
2254 	}
2255 	return -ENOENT;
2256 }
2257 EXPORT_SYMBOL(xfrm_policy_delete);
2258 
2259 int xfrm_sk_policy_insert(struct sock *sk, int dir, struct xfrm_policy *pol)
2260 {
2261 	struct net *net = sock_net(sk);
2262 	struct xfrm_policy *old_pol;
2263 
2264 #ifdef CONFIG_XFRM_SUB_POLICY
2265 	if (pol && pol->type != XFRM_POLICY_TYPE_MAIN)
2266 		return -EINVAL;
2267 #endif
2268 
2269 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
2270 	old_pol = rcu_dereference_protected(sk->sk_policy[dir],
2271 				lockdep_is_held(&net->xfrm.xfrm_policy_lock));
2272 	if (pol) {
2273 		pol->curlft.add_time = ktime_get_real_seconds();
2274 		pol->index = xfrm_gen_index(net, XFRM_POLICY_MAX+dir, 0);
2275 		xfrm_sk_policy_link(pol, dir);
2276 	}
2277 	rcu_assign_pointer(sk->sk_policy[dir], pol);
2278 	if (old_pol) {
2279 		if (pol)
2280 			xfrm_policy_requeue(old_pol, pol);
2281 
2282 		/* Unlinking succeeds always. This is the only function
2283 		 * allowed to delete or replace socket policy.
2284 		 */
2285 		xfrm_sk_policy_unlink(old_pol, dir);
2286 	}
2287 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
2288 
2289 	if (old_pol) {
2290 		xfrm_policy_kill(old_pol);
2291 	}
2292 	return 0;
2293 }
2294 
2295 static struct xfrm_policy *clone_policy(const struct xfrm_policy *old, int dir)
2296 {
2297 	struct xfrm_policy *newp = xfrm_policy_alloc(xp_net(old), GFP_ATOMIC);
2298 	struct net *net = xp_net(old);
2299 
2300 	if (newp) {
2301 		newp->selector = old->selector;
2302 		if (security_xfrm_policy_clone(old->security,
2303 					       &newp->security)) {
2304 			kfree(newp);
2305 			return NULL;  /* ENOMEM */
2306 		}
2307 		newp->lft = old->lft;
2308 		newp->curlft = old->curlft;
2309 		newp->mark = old->mark;
2310 		newp->if_id = old->if_id;
2311 		newp->action = old->action;
2312 		newp->flags = old->flags;
2313 		newp->xfrm_nr = old->xfrm_nr;
2314 		newp->index = old->index;
2315 		newp->type = old->type;
2316 		newp->family = old->family;
2317 		memcpy(newp->xfrm_vec, old->xfrm_vec,
2318 		       newp->xfrm_nr*sizeof(struct xfrm_tmpl));
2319 		spin_lock_bh(&net->xfrm.xfrm_policy_lock);
2320 		xfrm_sk_policy_link(newp, dir);
2321 		spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
2322 		xfrm_pol_put(newp);
2323 	}
2324 	return newp;
2325 }
2326 
2327 int __xfrm_sk_clone_policy(struct sock *sk, const struct sock *osk)
2328 {
2329 	const struct xfrm_policy *p;
2330 	struct xfrm_policy *np;
2331 	int i, ret = 0;
2332 
2333 	rcu_read_lock();
2334 	for (i = 0; i < 2; i++) {
2335 		p = rcu_dereference(osk->sk_policy[i]);
2336 		if (p) {
2337 			np = clone_policy(p, i);
2338 			if (unlikely(!np)) {
2339 				ret = -ENOMEM;
2340 				break;
2341 			}
2342 			rcu_assign_pointer(sk->sk_policy[i], np);
2343 		}
2344 	}
2345 	rcu_read_unlock();
2346 	return ret;
2347 }
2348 
2349 static int
2350 xfrm_get_saddr(struct net *net, int oif, xfrm_address_t *local,
2351 	       xfrm_address_t *remote, unsigned short family, u32 mark)
2352 {
2353 	int err;
2354 	const struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
2355 
2356 	if (unlikely(afinfo == NULL))
2357 		return -EINVAL;
2358 	err = afinfo->get_saddr(net, oif, local, remote, mark);
2359 	rcu_read_unlock();
2360 	return err;
2361 }
2362 
2363 /* Resolve list of templates for the flow, given policy. */
2364 
2365 static int
2366 xfrm_tmpl_resolve_one(struct xfrm_policy *policy, const struct flowi *fl,
2367 		      struct xfrm_state **xfrm, unsigned short family)
2368 {
2369 	struct net *net = xp_net(policy);
2370 	int nx;
2371 	int i, error;
2372 	xfrm_address_t *daddr = xfrm_flowi_daddr(fl, family);
2373 	xfrm_address_t *saddr = xfrm_flowi_saddr(fl, family);
2374 	xfrm_address_t tmp;
2375 
2376 	for (nx = 0, i = 0; i < policy->xfrm_nr; i++) {
2377 		struct xfrm_state *x;
2378 		xfrm_address_t *remote = daddr;
2379 		xfrm_address_t *local  = saddr;
2380 		struct xfrm_tmpl *tmpl = &policy->xfrm_vec[i];
2381 
2382 		if (tmpl->mode == XFRM_MODE_TUNNEL ||
2383 		    tmpl->mode == XFRM_MODE_BEET) {
2384 			remote = &tmpl->id.daddr;
2385 			local = &tmpl->saddr;
2386 			if (xfrm_addr_any(local, tmpl->encap_family)) {
2387 				error = xfrm_get_saddr(net, fl->flowi_oif,
2388 						       &tmp, remote,
2389 						       tmpl->encap_family, 0);
2390 				if (error)
2391 					goto fail;
2392 				local = &tmp;
2393 			}
2394 		}
2395 
2396 		x = xfrm_state_find(remote, local, fl, tmpl, policy, &error,
2397 				    family, policy->if_id);
2398 
2399 		if (x && x->km.state == XFRM_STATE_VALID) {
2400 			xfrm[nx++] = x;
2401 			daddr = remote;
2402 			saddr = local;
2403 			continue;
2404 		}
2405 		if (x) {
2406 			error = (x->km.state == XFRM_STATE_ERROR ?
2407 				 -EINVAL : -EAGAIN);
2408 			xfrm_state_put(x);
2409 		} else if (error == -ESRCH) {
2410 			error = -EAGAIN;
2411 		}
2412 
2413 		if (!tmpl->optional)
2414 			goto fail;
2415 	}
2416 	return nx;
2417 
2418 fail:
2419 	for (nx--; nx >= 0; nx--)
2420 		xfrm_state_put(xfrm[nx]);
2421 	return error;
2422 }
2423 
2424 static int
2425 xfrm_tmpl_resolve(struct xfrm_policy **pols, int npols, const struct flowi *fl,
2426 		  struct xfrm_state **xfrm, unsigned short family)
2427 {
2428 	struct xfrm_state *tp[XFRM_MAX_DEPTH];
2429 	struct xfrm_state **tpp = (npols > 1) ? tp : xfrm;
2430 	int cnx = 0;
2431 	int error;
2432 	int ret;
2433 	int i;
2434 
2435 	for (i = 0; i < npols; i++) {
2436 		if (cnx + pols[i]->xfrm_nr >= XFRM_MAX_DEPTH) {
2437 			error = -ENOBUFS;
2438 			goto fail;
2439 		}
2440 
2441 		ret = xfrm_tmpl_resolve_one(pols[i], fl, &tpp[cnx], family);
2442 		if (ret < 0) {
2443 			error = ret;
2444 			goto fail;
2445 		} else
2446 			cnx += ret;
2447 	}
2448 
2449 	/* found states are sorted for outbound processing */
2450 	if (npols > 1)
2451 		xfrm_state_sort(xfrm, tpp, cnx, family);
2452 
2453 	return cnx;
2454 
2455  fail:
2456 	for (cnx--; cnx >= 0; cnx--)
2457 		xfrm_state_put(tpp[cnx]);
2458 	return error;
2459 
2460 }
2461 
2462 static int xfrm_get_tos(const struct flowi *fl, int family)
2463 {
2464 	if (family == AF_INET)
2465 		return IPTOS_RT_MASK & fl->u.ip4.flowi4_tos;
2466 
2467 	return 0;
2468 }
2469 
2470 static inline struct xfrm_dst *xfrm_alloc_dst(struct net *net, int family)
2471 {
2472 	const struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
2473 	struct dst_ops *dst_ops;
2474 	struct xfrm_dst *xdst;
2475 
2476 	if (!afinfo)
2477 		return ERR_PTR(-EINVAL);
2478 
2479 	switch (family) {
2480 	case AF_INET:
2481 		dst_ops = &net->xfrm.xfrm4_dst_ops;
2482 		break;
2483 #if IS_ENABLED(CONFIG_IPV6)
2484 	case AF_INET6:
2485 		dst_ops = &net->xfrm.xfrm6_dst_ops;
2486 		break;
2487 #endif
2488 	default:
2489 		BUG();
2490 	}
2491 	xdst = dst_alloc(dst_ops, NULL, 1, DST_OBSOLETE_NONE, 0);
2492 
2493 	if (likely(xdst)) {
2494 		struct dst_entry *dst = &xdst->u.dst;
2495 
2496 		memset(dst + 1, 0, sizeof(*xdst) - sizeof(*dst));
2497 	} else
2498 		xdst = ERR_PTR(-ENOBUFS);
2499 
2500 	rcu_read_unlock();
2501 
2502 	return xdst;
2503 }
2504 
2505 static void xfrm_init_path(struct xfrm_dst *path, struct dst_entry *dst,
2506 			   int nfheader_len)
2507 {
2508 	if (dst->ops->family == AF_INET6) {
2509 		struct rt6_info *rt = (struct rt6_info *)dst;
2510 		path->path_cookie = rt6_get_cookie(rt);
2511 		path->u.rt6.rt6i_nfheader_len = nfheader_len;
2512 	}
2513 }
2514 
2515 static inline int xfrm_fill_dst(struct xfrm_dst *xdst, struct net_device *dev,
2516 				const struct flowi *fl)
2517 {
2518 	const struct xfrm_policy_afinfo *afinfo =
2519 		xfrm_policy_get_afinfo(xdst->u.dst.ops->family);
2520 	int err;
2521 
2522 	if (!afinfo)
2523 		return -EINVAL;
2524 
2525 	err = afinfo->fill_dst(xdst, dev, fl);
2526 
2527 	rcu_read_unlock();
2528 
2529 	return err;
2530 }
2531 
2532 
2533 /* Allocate chain of dst_entry's, attach known xfrm's, calculate
2534  * all the metrics... Shortly, bundle a bundle.
2535  */
2536 
2537 static struct dst_entry *xfrm_bundle_create(struct xfrm_policy *policy,
2538 					    struct xfrm_state **xfrm,
2539 					    struct xfrm_dst **bundle,
2540 					    int nx,
2541 					    const struct flowi *fl,
2542 					    struct dst_entry *dst)
2543 {
2544 	const struct xfrm_state_afinfo *afinfo;
2545 	const struct xfrm_mode *inner_mode;
2546 	struct net *net = xp_net(policy);
2547 	unsigned long now = jiffies;
2548 	struct net_device *dev;
2549 	struct xfrm_dst *xdst_prev = NULL;
2550 	struct xfrm_dst *xdst0 = NULL;
2551 	int i = 0;
2552 	int err;
2553 	int header_len = 0;
2554 	int nfheader_len = 0;
2555 	int trailer_len = 0;
2556 	int tos;
2557 	int family = policy->selector.family;
2558 	xfrm_address_t saddr, daddr;
2559 
2560 	xfrm_flowi_addr_get(fl, &saddr, &daddr, family);
2561 
2562 	tos = xfrm_get_tos(fl, family);
2563 
2564 	dst_hold(dst);
2565 
2566 	for (; i < nx; i++) {
2567 		struct xfrm_dst *xdst = xfrm_alloc_dst(net, family);
2568 		struct dst_entry *dst1 = &xdst->u.dst;
2569 
2570 		err = PTR_ERR(xdst);
2571 		if (IS_ERR(xdst)) {
2572 			dst_release(dst);
2573 			goto put_states;
2574 		}
2575 
2576 		bundle[i] = xdst;
2577 		if (!xdst_prev)
2578 			xdst0 = xdst;
2579 		else
2580 			/* Ref count is taken during xfrm_alloc_dst()
2581 			 * No need to do dst_clone() on dst1
2582 			 */
2583 			xfrm_dst_set_child(xdst_prev, &xdst->u.dst);
2584 
2585 		if (xfrm[i]->sel.family == AF_UNSPEC) {
2586 			inner_mode = xfrm_ip2inner_mode(xfrm[i],
2587 							xfrm_af2proto(family));
2588 			if (!inner_mode) {
2589 				err = -EAFNOSUPPORT;
2590 				dst_release(dst);
2591 				goto put_states;
2592 			}
2593 		} else
2594 			inner_mode = &xfrm[i]->inner_mode;
2595 
2596 		xdst->route = dst;
2597 		dst_copy_metrics(dst1, dst);
2598 
2599 		if (xfrm[i]->props.mode != XFRM_MODE_TRANSPORT) {
2600 			__u32 mark = 0;
2601 
2602 			if (xfrm[i]->props.smark.v || xfrm[i]->props.smark.m)
2603 				mark = xfrm_smark_get(fl->flowi_mark, xfrm[i]);
2604 
2605 			family = xfrm[i]->props.family;
2606 			dst = xfrm_dst_lookup(xfrm[i], tos, fl->flowi_oif,
2607 					      &saddr, &daddr, family, mark);
2608 			err = PTR_ERR(dst);
2609 			if (IS_ERR(dst))
2610 				goto put_states;
2611 		} else
2612 			dst_hold(dst);
2613 
2614 		dst1->xfrm = xfrm[i];
2615 		xdst->xfrm_genid = xfrm[i]->genid;
2616 
2617 		dst1->obsolete = DST_OBSOLETE_FORCE_CHK;
2618 		dst1->lastuse = now;
2619 
2620 		dst1->input = dst_discard;
2621 
2622 		rcu_read_lock();
2623 		afinfo = xfrm_state_afinfo_get_rcu(inner_mode->family);
2624 		if (likely(afinfo))
2625 			dst1->output = afinfo->output;
2626 		else
2627 			dst1->output = dst_discard_out;
2628 		rcu_read_unlock();
2629 
2630 		xdst_prev = xdst;
2631 
2632 		header_len += xfrm[i]->props.header_len;
2633 		if (xfrm[i]->type->flags & XFRM_TYPE_NON_FRAGMENT)
2634 			nfheader_len += xfrm[i]->props.header_len;
2635 		trailer_len += xfrm[i]->props.trailer_len;
2636 	}
2637 
2638 	xfrm_dst_set_child(xdst_prev, dst);
2639 	xdst0->path = dst;
2640 
2641 	err = -ENODEV;
2642 	dev = dst->dev;
2643 	if (!dev)
2644 		goto free_dst;
2645 
2646 	xfrm_init_path(xdst0, dst, nfheader_len);
2647 	xfrm_init_pmtu(bundle, nx);
2648 
2649 	for (xdst_prev = xdst0; xdst_prev != (struct xfrm_dst *)dst;
2650 	     xdst_prev = (struct xfrm_dst *) xfrm_dst_child(&xdst_prev->u.dst)) {
2651 		err = xfrm_fill_dst(xdst_prev, dev, fl);
2652 		if (err)
2653 			goto free_dst;
2654 
2655 		xdst_prev->u.dst.header_len = header_len;
2656 		xdst_prev->u.dst.trailer_len = trailer_len;
2657 		header_len -= xdst_prev->u.dst.xfrm->props.header_len;
2658 		trailer_len -= xdst_prev->u.dst.xfrm->props.trailer_len;
2659 	}
2660 
2661 	return &xdst0->u.dst;
2662 
2663 put_states:
2664 	for (; i < nx; i++)
2665 		xfrm_state_put(xfrm[i]);
2666 free_dst:
2667 	if (xdst0)
2668 		dst_release_immediate(&xdst0->u.dst);
2669 
2670 	return ERR_PTR(err);
2671 }
2672 
2673 static int xfrm_expand_policies(const struct flowi *fl, u16 family,
2674 				struct xfrm_policy **pols,
2675 				int *num_pols, int *num_xfrms)
2676 {
2677 	int i;
2678 
2679 	if (*num_pols == 0 || !pols[0]) {
2680 		*num_pols = 0;
2681 		*num_xfrms = 0;
2682 		return 0;
2683 	}
2684 	if (IS_ERR(pols[0]))
2685 		return PTR_ERR(pols[0]);
2686 
2687 	*num_xfrms = pols[0]->xfrm_nr;
2688 
2689 #ifdef CONFIG_XFRM_SUB_POLICY
2690 	if (pols[0] && pols[0]->action == XFRM_POLICY_ALLOW &&
2691 	    pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
2692 		pols[1] = xfrm_policy_lookup_bytype(xp_net(pols[0]),
2693 						    XFRM_POLICY_TYPE_MAIN,
2694 						    fl, family,
2695 						    XFRM_POLICY_OUT,
2696 						    pols[0]->if_id);
2697 		if (pols[1]) {
2698 			if (IS_ERR(pols[1])) {
2699 				xfrm_pols_put(pols, *num_pols);
2700 				return PTR_ERR(pols[1]);
2701 			}
2702 			(*num_pols)++;
2703 			(*num_xfrms) += pols[1]->xfrm_nr;
2704 		}
2705 	}
2706 #endif
2707 	for (i = 0; i < *num_pols; i++) {
2708 		if (pols[i]->action != XFRM_POLICY_ALLOW) {
2709 			*num_xfrms = -1;
2710 			break;
2711 		}
2712 	}
2713 
2714 	return 0;
2715 
2716 }
2717 
2718 static struct xfrm_dst *
2719 xfrm_resolve_and_create_bundle(struct xfrm_policy **pols, int num_pols,
2720 			       const struct flowi *fl, u16 family,
2721 			       struct dst_entry *dst_orig)
2722 {
2723 	struct net *net = xp_net(pols[0]);
2724 	struct xfrm_state *xfrm[XFRM_MAX_DEPTH];
2725 	struct xfrm_dst *bundle[XFRM_MAX_DEPTH];
2726 	struct xfrm_dst *xdst;
2727 	struct dst_entry *dst;
2728 	int err;
2729 
2730 	/* Try to instantiate a bundle */
2731 	err = xfrm_tmpl_resolve(pols, num_pols, fl, xfrm, family);
2732 	if (err <= 0) {
2733 		if (err == 0)
2734 			return NULL;
2735 
2736 		if (err != -EAGAIN)
2737 			XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLERROR);
2738 		return ERR_PTR(err);
2739 	}
2740 
2741 	dst = xfrm_bundle_create(pols[0], xfrm, bundle, err, fl, dst_orig);
2742 	if (IS_ERR(dst)) {
2743 		XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTBUNDLEGENERROR);
2744 		return ERR_CAST(dst);
2745 	}
2746 
2747 	xdst = (struct xfrm_dst *)dst;
2748 	xdst->num_xfrms = err;
2749 	xdst->num_pols = num_pols;
2750 	memcpy(xdst->pols, pols, sizeof(struct xfrm_policy *) * num_pols);
2751 	xdst->policy_genid = atomic_read(&pols[0]->genid);
2752 
2753 	return xdst;
2754 }
2755 
2756 static void xfrm_policy_queue_process(struct timer_list *t)
2757 {
2758 	struct sk_buff *skb;
2759 	struct sock *sk;
2760 	struct dst_entry *dst;
2761 	struct xfrm_policy *pol = from_timer(pol, t, polq.hold_timer);
2762 	struct net *net = xp_net(pol);
2763 	struct xfrm_policy_queue *pq = &pol->polq;
2764 	struct flowi fl;
2765 	struct sk_buff_head list;
2766 
2767 	spin_lock(&pq->hold_queue.lock);
2768 	skb = skb_peek(&pq->hold_queue);
2769 	if (!skb) {
2770 		spin_unlock(&pq->hold_queue.lock);
2771 		goto out;
2772 	}
2773 	dst = skb_dst(skb);
2774 	sk = skb->sk;
2775 	xfrm_decode_session(skb, &fl, dst->ops->family);
2776 	spin_unlock(&pq->hold_queue.lock);
2777 
2778 	dst_hold(xfrm_dst_path(dst));
2779 	dst = xfrm_lookup(net, xfrm_dst_path(dst), &fl, sk, XFRM_LOOKUP_QUEUE);
2780 	if (IS_ERR(dst))
2781 		goto purge_queue;
2782 
2783 	if (dst->flags & DST_XFRM_QUEUE) {
2784 		dst_release(dst);
2785 
2786 		if (pq->timeout >= XFRM_QUEUE_TMO_MAX)
2787 			goto purge_queue;
2788 
2789 		pq->timeout = pq->timeout << 1;
2790 		if (!mod_timer(&pq->hold_timer, jiffies + pq->timeout))
2791 			xfrm_pol_hold(pol);
2792 		goto out;
2793 	}
2794 
2795 	dst_release(dst);
2796 
2797 	__skb_queue_head_init(&list);
2798 
2799 	spin_lock(&pq->hold_queue.lock);
2800 	pq->timeout = 0;
2801 	skb_queue_splice_init(&pq->hold_queue, &list);
2802 	spin_unlock(&pq->hold_queue.lock);
2803 
2804 	while (!skb_queue_empty(&list)) {
2805 		skb = __skb_dequeue(&list);
2806 
2807 		xfrm_decode_session(skb, &fl, skb_dst(skb)->ops->family);
2808 		dst_hold(xfrm_dst_path(skb_dst(skb)));
2809 		dst = xfrm_lookup(net, xfrm_dst_path(skb_dst(skb)), &fl, skb->sk, 0);
2810 		if (IS_ERR(dst)) {
2811 			kfree_skb(skb);
2812 			continue;
2813 		}
2814 
2815 		nf_reset_ct(skb);
2816 		skb_dst_drop(skb);
2817 		skb_dst_set(skb, dst);
2818 
2819 		dst_output(net, skb->sk, skb);
2820 	}
2821 
2822 out:
2823 	xfrm_pol_put(pol);
2824 	return;
2825 
2826 purge_queue:
2827 	pq->timeout = 0;
2828 	skb_queue_purge(&pq->hold_queue);
2829 	xfrm_pol_put(pol);
2830 }
2831 
2832 static int xdst_queue_output(struct net *net, struct sock *sk, struct sk_buff *skb)
2833 {
2834 	unsigned long sched_next;
2835 	struct dst_entry *dst = skb_dst(skb);
2836 	struct xfrm_dst *xdst = (struct xfrm_dst *) dst;
2837 	struct xfrm_policy *pol = xdst->pols[0];
2838 	struct xfrm_policy_queue *pq = &pol->polq;
2839 
2840 	if (unlikely(skb_fclone_busy(sk, skb))) {
2841 		kfree_skb(skb);
2842 		return 0;
2843 	}
2844 
2845 	if (pq->hold_queue.qlen > XFRM_MAX_QUEUE_LEN) {
2846 		kfree_skb(skb);
2847 		return -EAGAIN;
2848 	}
2849 
2850 	skb_dst_force(skb);
2851 
2852 	spin_lock_bh(&pq->hold_queue.lock);
2853 
2854 	if (!pq->timeout)
2855 		pq->timeout = XFRM_QUEUE_TMO_MIN;
2856 
2857 	sched_next = jiffies + pq->timeout;
2858 
2859 	if (del_timer(&pq->hold_timer)) {
2860 		if (time_before(pq->hold_timer.expires, sched_next))
2861 			sched_next = pq->hold_timer.expires;
2862 		xfrm_pol_put(pol);
2863 	}
2864 
2865 	__skb_queue_tail(&pq->hold_queue, skb);
2866 	if (!mod_timer(&pq->hold_timer, sched_next))
2867 		xfrm_pol_hold(pol);
2868 
2869 	spin_unlock_bh(&pq->hold_queue.lock);
2870 
2871 	return 0;
2872 }
2873 
2874 static struct xfrm_dst *xfrm_create_dummy_bundle(struct net *net,
2875 						 struct xfrm_flo *xflo,
2876 						 const struct flowi *fl,
2877 						 int num_xfrms,
2878 						 u16 family)
2879 {
2880 	int err;
2881 	struct net_device *dev;
2882 	struct dst_entry *dst;
2883 	struct dst_entry *dst1;
2884 	struct xfrm_dst *xdst;
2885 
2886 	xdst = xfrm_alloc_dst(net, family);
2887 	if (IS_ERR(xdst))
2888 		return xdst;
2889 
2890 	if (!(xflo->flags & XFRM_LOOKUP_QUEUE) ||
2891 	    net->xfrm.sysctl_larval_drop ||
2892 	    num_xfrms <= 0)
2893 		return xdst;
2894 
2895 	dst = xflo->dst_orig;
2896 	dst1 = &xdst->u.dst;
2897 	dst_hold(dst);
2898 	xdst->route = dst;
2899 
2900 	dst_copy_metrics(dst1, dst);
2901 
2902 	dst1->obsolete = DST_OBSOLETE_FORCE_CHK;
2903 	dst1->flags |= DST_XFRM_QUEUE;
2904 	dst1->lastuse = jiffies;
2905 
2906 	dst1->input = dst_discard;
2907 	dst1->output = xdst_queue_output;
2908 
2909 	dst_hold(dst);
2910 	xfrm_dst_set_child(xdst, dst);
2911 	xdst->path = dst;
2912 
2913 	xfrm_init_path((struct xfrm_dst *)dst1, dst, 0);
2914 
2915 	err = -ENODEV;
2916 	dev = dst->dev;
2917 	if (!dev)
2918 		goto free_dst;
2919 
2920 	err = xfrm_fill_dst(xdst, dev, fl);
2921 	if (err)
2922 		goto free_dst;
2923 
2924 out:
2925 	return xdst;
2926 
2927 free_dst:
2928 	dst_release(dst1);
2929 	xdst = ERR_PTR(err);
2930 	goto out;
2931 }
2932 
2933 static struct xfrm_dst *xfrm_bundle_lookup(struct net *net,
2934 					   const struct flowi *fl,
2935 					   u16 family, u8 dir,
2936 					   struct xfrm_flo *xflo, u32 if_id)
2937 {
2938 	struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
2939 	int num_pols = 0, num_xfrms = 0, err;
2940 	struct xfrm_dst *xdst;
2941 
2942 	/* Resolve policies to use if we couldn't get them from
2943 	 * previous cache entry */
2944 	num_pols = 1;
2945 	pols[0] = xfrm_policy_lookup(net, fl, family, dir, if_id);
2946 	err = xfrm_expand_policies(fl, family, pols,
2947 					   &num_pols, &num_xfrms);
2948 	if (err < 0)
2949 		goto inc_error;
2950 	if (num_pols == 0)
2951 		return NULL;
2952 	if (num_xfrms <= 0)
2953 		goto make_dummy_bundle;
2954 
2955 	xdst = xfrm_resolve_and_create_bundle(pols, num_pols, fl, family,
2956 					      xflo->dst_orig);
2957 	if (IS_ERR(xdst)) {
2958 		err = PTR_ERR(xdst);
2959 		if (err == -EREMOTE) {
2960 			xfrm_pols_put(pols, num_pols);
2961 			return NULL;
2962 		}
2963 
2964 		if (err != -EAGAIN)
2965 			goto error;
2966 		goto make_dummy_bundle;
2967 	} else if (xdst == NULL) {
2968 		num_xfrms = 0;
2969 		goto make_dummy_bundle;
2970 	}
2971 
2972 	return xdst;
2973 
2974 make_dummy_bundle:
2975 	/* We found policies, but there's no bundles to instantiate:
2976 	 * either because the policy blocks, has no transformations or
2977 	 * we could not build template (no xfrm_states).*/
2978 	xdst = xfrm_create_dummy_bundle(net, xflo, fl, num_xfrms, family);
2979 	if (IS_ERR(xdst)) {
2980 		xfrm_pols_put(pols, num_pols);
2981 		return ERR_CAST(xdst);
2982 	}
2983 	xdst->num_pols = num_pols;
2984 	xdst->num_xfrms = num_xfrms;
2985 	memcpy(xdst->pols, pols, sizeof(struct xfrm_policy *) * num_pols);
2986 
2987 	return xdst;
2988 
2989 inc_error:
2990 	XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLERROR);
2991 error:
2992 	xfrm_pols_put(pols, num_pols);
2993 	return ERR_PTR(err);
2994 }
2995 
2996 static struct dst_entry *make_blackhole(struct net *net, u16 family,
2997 					struct dst_entry *dst_orig)
2998 {
2999 	const struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
3000 	struct dst_entry *ret;
3001 
3002 	if (!afinfo) {
3003 		dst_release(dst_orig);
3004 		return ERR_PTR(-EINVAL);
3005 	} else {
3006 		ret = afinfo->blackhole_route(net, dst_orig);
3007 	}
3008 	rcu_read_unlock();
3009 
3010 	return ret;
3011 }
3012 
3013 /* Finds/creates a bundle for given flow and if_id
3014  *
3015  * At the moment we eat a raw IP route. Mostly to speed up lookups
3016  * on interfaces with disabled IPsec.
3017  *
3018  * xfrm_lookup uses an if_id of 0 by default, and is provided for
3019  * compatibility
3020  */
3021 struct dst_entry *xfrm_lookup_with_ifid(struct net *net,
3022 					struct dst_entry *dst_orig,
3023 					const struct flowi *fl,
3024 					const struct sock *sk,
3025 					int flags, u32 if_id)
3026 {
3027 	struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
3028 	struct xfrm_dst *xdst;
3029 	struct dst_entry *dst, *route;
3030 	u16 family = dst_orig->ops->family;
3031 	u8 dir = XFRM_POLICY_OUT;
3032 	int i, err, num_pols, num_xfrms = 0, drop_pols = 0;
3033 
3034 	dst = NULL;
3035 	xdst = NULL;
3036 	route = NULL;
3037 
3038 	sk = sk_const_to_full_sk(sk);
3039 	if (sk && sk->sk_policy[XFRM_POLICY_OUT]) {
3040 		num_pols = 1;
3041 		pols[0] = xfrm_sk_policy_lookup(sk, XFRM_POLICY_OUT, fl, family,
3042 						if_id);
3043 		err = xfrm_expand_policies(fl, family, pols,
3044 					   &num_pols, &num_xfrms);
3045 		if (err < 0)
3046 			goto dropdst;
3047 
3048 		if (num_pols) {
3049 			if (num_xfrms <= 0) {
3050 				drop_pols = num_pols;
3051 				goto no_transform;
3052 			}
3053 
3054 			xdst = xfrm_resolve_and_create_bundle(
3055 					pols, num_pols, fl,
3056 					family, dst_orig);
3057 
3058 			if (IS_ERR(xdst)) {
3059 				xfrm_pols_put(pols, num_pols);
3060 				err = PTR_ERR(xdst);
3061 				if (err == -EREMOTE)
3062 					goto nopol;
3063 
3064 				goto dropdst;
3065 			} else if (xdst == NULL) {
3066 				num_xfrms = 0;
3067 				drop_pols = num_pols;
3068 				goto no_transform;
3069 			}
3070 
3071 			route = xdst->route;
3072 		}
3073 	}
3074 
3075 	if (xdst == NULL) {
3076 		struct xfrm_flo xflo;
3077 
3078 		xflo.dst_orig = dst_orig;
3079 		xflo.flags = flags;
3080 
3081 		/* To accelerate a bit...  */
3082 		if ((dst_orig->flags & DST_NOXFRM) ||
3083 		    !net->xfrm.policy_count[XFRM_POLICY_OUT])
3084 			goto nopol;
3085 
3086 		xdst = xfrm_bundle_lookup(net, fl, family, dir, &xflo, if_id);
3087 		if (xdst == NULL)
3088 			goto nopol;
3089 		if (IS_ERR(xdst)) {
3090 			err = PTR_ERR(xdst);
3091 			goto dropdst;
3092 		}
3093 
3094 		num_pols = xdst->num_pols;
3095 		num_xfrms = xdst->num_xfrms;
3096 		memcpy(pols, xdst->pols, sizeof(struct xfrm_policy *) * num_pols);
3097 		route = xdst->route;
3098 	}
3099 
3100 	dst = &xdst->u.dst;
3101 	if (route == NULL && num_xfrms > 0) {
3102 		/* The only case when xfrm_bundle_lookup() returns a
3103 		 * bundle with null route, is when the template could
3104 		 * not be resolved. It means policies are there, but
3105 		 * bundle could not be created, since we don't yet
3106 		 * have the xfrm_state's. We need to wait for KM to
3107 		 * negotiate new SA's or bail out with error.*/
3108 		if (net->xfrm.sysctl_larval_drop) {
3109 			XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTNOSTATES);
3110 			err = -EREMOTE;
3111 			goto error;
3112 		}
3113 
3114 		err = -EAGAIN;
3115 
3116 		XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTNOSTATES);
3117 		goto error;
3118 	}
3119 
3120 no_transform:
3121 	if (num_pols == 0)
3122 		goto nopol;
3123 
3124 	if ((flags & XFRM_LOOKUP_ICMP) &&
3125 	    !(pols[0]->flags & XFRM_POLICY_ICMP)) {
3126 		err = -ENOENT;
3127 		goto error;
3128 	}
3129 
3130 	for (i = 0; i < num_pols; i++)
3131 		pols[i]->curlft.use_time = ktime_get_real_seconds();
3132 
3133 	if (num_xfrms < 0) {
3134 		/* Prohibit the flow */
3135 		XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLBLOCK);
3136 		err = -EPERM;
3137 		goto error;
3138 	} else if (num_xfrms > 0) {
3139 		/* Flow transformed */
3140 		dst_release(dst_orig);
3141 	} else {
3142 		/* Flow passes untransformed */
3143 		dst_release(dst);
3144 		dst = dst_orig;
3145 	}
3146 ok:
3147 	xfrm_pols_put(pols, drop_pols);
3148 	if (dst && dst->xfrm &&
3149 	    dst->xfrm->props.mode == XFRM_MODE_TUNNEL)
3150 		dst->flags |= DST_XFRM_TUNNEL;
3151 	return dst;
3152 
3153 nopol:
3154 	if (!(flags & XFRM_LOOKUP_ICMP)) {
3155 		dst = dst_orig;
3156 		goto ok;
3157 	}
3158 	err = -ENOENT;
3159 error:
3160 	dst_release(dst);
3161 dropdst:
3162 	if (!(flags & XFRM_LOOKUP_KEEP_DST_REF))
3163 		dst_release(dst_orig);
3164 	xfrm_pols_put(pols, drop_pols);
3165 	return ERR_PTR(err);
3166 }
3167 EXPORT_SYMBOL(xfrm_lookup_with_ifid);
3168 
3169 /* Main function: finds/creates a bundle for given flow.
3170  *
3171  * At the moment we eat a raw IP route. Mostly to speed up lookups
3172  * on interfaces with disabled IPsec.
3173  */
3174 struct dst_entry *xfrm_lookup(struct net *net, struct dst_entry *dst_orig,
3175 			      const struct flowi *fl, const struct sock *sk,
3176 			      int flags)
3177 {
3178 	return xfrm_lookup_with_ifid(net, dst_orig, fl, sk, flags, 0);
3179 }
3180 EXPORT_SYMBOL(xfrm_lookup);
3181 
3182 /* Callers of xfrm_lookup_route() must ensure a call to dst_output().
3183  * Otherwise we may send out blackholed packets.
3184  */
3185 struct dst_entry *xfrm_lookup_route(struct net *net, struct dst_entry *dst_orig,
3186 				    const struct flowi *fl,
3187 				    const struct sock *sk, int flags)
3188 {
3189 	struct dst_entry *dst = xfrm_lookup(net, dst_orig, fl, sk,
3190 					    flags | XFRM_LOOKUP_QUEUE |
3191 					    XFRM_LOOKUP_KEEP_DST_REF);
3192 
3193 	if (PTR_ERR(dst) == -EREMOTE)
3194 		return make_blackhole(net, dst_orig->ops->family, dst_orig);
3195 
3196 	if (IS_ERR(dst))
3197 		dst_release(dst_orig);
3198 
3199 	return dst;
3200 }
3201 EXPORT_SYMBOL(xfrm_lookup_route);
3202 
3203 static inline int
3204 xfrm_secpath_reject(int idx, struct sk_buff *skb, const struct flowi *fl)
3205 {
3206 	struct sec_path *sp = skb_sec_path(skb);
3207 	struct xfrm_state *x;
3208 
3209 	if (!sp || idx < 0 || idx >= sp->len)
3210 		return 0;
3211 	x = sp->xvec[idx];
3212 	if (!x->type->reject)
3213 		return 0;
3214 	return x->type->reject(x, skb, fl);
3215 }
3216 
3217 /* When skb is transformed back to its "native" form, we have to
3218  * check policy restrictions. At the moment we make this in maximally
3219  * stupid way. Shame on me. :-) Of course, connected sockets must
3220  * have policy cached at them.
3221  */
3222 
3223 static inline int
3224 xfrm_state_ok(const struct xfrm_tmpl *tmpl, const struct xfrm_state *x,
3225 	      unsigned short family)
3226 {
3227 	if (xfrm_state_kern(x))
3228 		return tmpl->optional && !xfrm_state_addr_cmp(tmpl, x, tmpl->encap_family);
3229 	return	x->id.proto == tmpl->id.proto &&
3230 		(x->id.spi == tmpl->id.spi || !tmpl->id.spi) &&
3231 		(x->props.reqid == tmpl->reqid || !tmpl->reqid) &&
3232 		x->props.mode == tmpl->mode &&
3233 		(tmpl->allalgs || (tmpl->aalgos & (1<<x->props.aalgo)) ||
3234 		 !(xfrm_id_proto_match(tmpl->id.proto, IPSEC_PROTO_ANY))) &&
3235 		!(x->props.mode != XFRM_MODE_TRANSPORT &&
3236 		  xfrm_state_addr_cmp(tmpl, x, family));
3237 }
3238 
3239 /*
3240  * 0 or more than 0 is returned when validation is succeeded (either bypass
3241  * because of optional transport mode, or next index of the mathced secpath
3242  * state with the template.
3243  * -1 is returned when no matching template is found.
3244  * Otherwise "-2 - errored_index" is returned.
3245  */
3246 static inline int
3247 xfrm_policy_ok(const struct xfrm_tmpl *tmpl, const struct sec_path *sp, int start,
3248 	       unsigned short family)
3249 {
3250 	int idx = start;
3251 
3252 	if (tmpl->optional) {
3253 		if (tmpl->mode == XFRM_MODE_TRANSPORT)
3254 			return start;
3255 	} else
3256 		start = -1;
3257 	for (; idx < sp->len; idx++) {
3258 		if (xfrm_state_ok(tmpl, sp->xvec[idx], family))
3259 			return ++idx;
3260 		if (sp->xvec[idx]->props.mode != XFRM_MODE_TRANSPORT) {
3261 			if (start == -1)
3262 				start = -2-idx;
3263 			break;
3264 		}
3265 	}
3266 	return start;
3267 }
3268 
3269 static void
3270 decode_session4(struct sk_buff *skb, struct flowi *fl, bool reverse)
3271 {
3272 	const struct iphdr *iph = ip_hdr(skb);
3273 	int ihl = iph->ihl;
3274 	u8 *xprth = skb_network_header(skb) + ihl * 4;
3275 	struct flowi4 *fl4 = &fl->u.ip4;
3276 	int oif = 0;
3277 
3278 	if (skb_dst(skb) && skb_dst(skb)->dev)
3279 		oif = skb_dst(skb)->dev->ifindex;
3280 
3281 	memset(fl4, 0, sizeof(struct flowi4));
3282 	fl4->flowi4_mark = skb->mark;
3283 	fl4->flowi4_oif = reverse ? skb->skb_iif : oif;
3284 
3285 	fl4->flowi4_proto = iph->protocol;
3286 	fl4->daddr = reverse ? iph->saddr : iph->daddr;
3287 	fl4->saddr = reverse ? iph->daddr : iph->saddr;
3288 	fl4->flowi4_tos = iph->tos;
3289 
3290 	if (!ip_is_fragment(iph)) {
3291 		switch (iph->protocol) {
3292 		case IPPROTO_UDP:
3293 		case IPPROTO_UDPLITE:
3294 		case IPPROTO_TCP:
3295 		case IPPROTO_SCTP:
3296 		case IPPROTO_DCCP:
3297 			if (xprth + 4 < skb->data ||
3298 			    pskb_may_pull(skb, xprth + 4 - skb->data)) {
3299 				__be16 *ports;
3300 
3301 				xprth = skb_network_header(skb) + ihl * 4;
3302 				ports = (__be16 *)xprth;
3303 
3304 				fl4->fl4_sport = ports[!!reverse];
3305 				fl4->fl4_dport = ports[!reverse];
3306 			}
3307 			break;
3308 		case IPPROTO_ICMP:
3309 			if (xprth + 2 < skb->data ||
3310 			    pskb_may_pull(skb, xprth + 2 - skb->data)) {
3311 				u8 *icmp;
3312 
3313 				xprth = skb_network_header(skb) + ihl * 4;
3314 				icmp = xprth;
3315 
3316 				fl4->fl4_icmp_type = icmp[0];
3317 				fl4->fl4_icmp_code = icmp[1];
3318 			}
3319 			break;
3320 		case IPPROTO_ESP:
3321 			if (xprth + 4 < skb->data ||
3322 			    pskb_may_pull(skb, xprth + 4 - skb->data)) {
3323 				__be32 *ehdr;
3324 
3325 				xprth = skb_network_header(skb) + ihl * 4;
3326 				ehdr = (__be32 *)xprth;
3327 
3328 				fl4->fl4_ipsec_spi = ehdr[0];
3329 			}
3330 			break;
3331 		case IPPROTO_AH:
3332 			if (xprth + 8 < skb->data ||
3333 			    pskb_may_pull(skb, xprth + 8 - skb->data)) {
3334 				__be32 *ah_hdr;
3335 
3336 				xprth = skb_network_header(skb) + ihl * 4;
3337 				ah_hdr = (__be32 *)xprth;
3338 
3339 				fl4->fl4_ipsec_spi = ah_hdr[1];
3340 			}
3341 			break;
3342 		case IPPROTO_COMP:
3343 			if (xprth + 4 < skb->data ||
3344 			    pskb_may_pull(skb, xprth + 4 - skb->data)) {
3345 				__be16 *ipcomp_hdr;
3346 
3347 				xprth = skb_network_header(skb) + ihl * 4;
3348 				ipcomp_hdr = (__be16 *)xprth;
3349 
3350 				fl4->fl4_ipsec_spi = htonl(ntohs(ipcomp_hdr[1]));
3351 			}
3352 			break;
3353 		case IPPROTO_GRE:
3354 			if (xprth + 12 < skb->data ||
3355 			    pskb_may_pull(skb, xprth + 12 - skb->data)) {
3356 				__be16 *greflags;
3357 				__be32 *gre_hdr;
3358 
3359 				xprth = skb_network_header(skb) + ihl * 4;
3360 				greflags = (__be16 *)xprth;
3361 				gre_hdr = (__be32 *)xprth;
3362 
3363 				if (greflags[0] & GRE_KEY) {
3364 					if (greflags[0] & GRE_CSUM)
3365 						gre_hdr++;
3366 					fl4->fl4_gre_key = gre_hdr[1];
3367 				}
3368 			}
3369 			break;
3370 		default:
3371 			fl4->fl4_ipsec_spi = 0;
3372 			break;
3373 		}
3374 	}
3375 }
3376 
3377 #if IS_ENABLED(CONFIG_IPV6)
3378 static void
3379 decode_session6(struct sk_buff *skb, struct flowi *fl, bool reverse)
3380 {
3381 	struct flowi6 *fl6 = &fl->u.ip6;
3382 	int onlyproto = 0;
3383 	const struct ipv6hdr *hdr = ipv6_hdr(skb);
3384 	u32 offset = sizeof(*hdr);
3385 	struct ipv6_opt_hdr *exthdr;
3386 	const unsigned char *nh = skb_network_header(skb);
3387 	u16 nhoff = IP6CB(skb)->nhoff;
3388 	int oif = 0;
3389 	u8 nexthdr;
3390 
3391 	if (!nhoff)
3392 		nhoff = offsetof(struct ipv6hdr, nexthdr);
3393 
3394 	nexthdr = nh[nhoff];
3395 
3396 	if (skb_dst(skb) && skb_dst(skb)->dev)
3397 		oif = skb_dst(skb)->dev->ifindex;
3398 
3399 	memset(fl6, 0, sizeof(struct flowi6));
3400 	fl6->flowi6_mark = skb->mark;
3401 	fl6->flowi6_oif = reverse ? skb->skb_iif : oif;
3402 
3403 	fl6->daddr = reverse ? hdr->saddr : hdr->daddr;
3404 	fl6->saddr = reverse ? hdr->daddr : hdr->saddr;
3405 
3406 	while (nh + offset + sizeof(*exthdr) < skb->data ||
3407 	       pskb_may_pull(skb, nh + offset + sizeof(*exthdr) - skb->data)) {
3408 		nh = skb_network_header(skb);
3409 		exthdr = (struct ipv6_opt_hdr *)(nh + offset);
3410 
3411 		switch (nexthdr) {
3412 		case NEXTHDR_FRAGMENT:
3413 			onlyproto = 1;
3414 			/* fall through */
3415 		case NEXTHDR_ROUTING:
3416 		case NEXTHDR_HOP:
3417 		case NEXTHDR_DEST:
3418 			offset += ipv6_optlen(exthdr);
3419 			nexthdr = exthdr->nexthdr;
3420 			exthdr = (struct ipv6_opt_hdr *)(nh + offset);
3421 			break;
3422 		case IPPROTO_UDP:
3423 		case IPPROTO_UDPLITE:
3424 		case IPPROTO_TCP:
3425 		case IPPROTO_SCTP:
3426 		case IPPROTO_DCCP:
3427 			if (!onlyproto && (nh + offset + 4 < skb->data ||
3428 			     pskb_may_pull(skb, nh + offset + 4 - skb->data))) {
3429 				__be16 *ports;
3430 
3431 				nh = skb_network_header(skb);
3432 				ports = (__be16 *)(nh + offset);
3433 				fl6->fl6_sport = ports[!!reverse];
3434 				fl6->fl6_dport = ports[!reverse];
3435 			}
3436 			fl6->flowi6_proto = nexthdr;
3437 			return;
3438 		case IPPROTO_ICMPV6:
3439 			if (!onlyproto && (nh + offset + 2 < skb->data ||
3440 			    pskb_may_pull(skb, nh + offset + 2 - skb->data))) {
3441 				u8 *icmp;
3442 
3443 				nh = skb_network_header(skb);
3444 				icmp = (u8 *)(nh + offset);
3445 				fl6->fl6_icmp_type = icmp[0];
3446 				fl6->fl6_icmp_code = icmp[1];
3447 			}
3448 			fl6->flowi6_proto = nexthdr;
3449 			return;
3450 #if IS_ENABLED(CONFIG_IPV6_MIP6)
3451 		case IPPROTO_MH:
3452 			offset += ipv6_optlen(exthdr);
3453 			if (!onlyproto && (nh + offset + 3 < skb->data ||
3454 			    pskb_may_pull(skb, nh + offset + 3 - skb->data))) {
3455 				struct ip6_mh *mh;
3456 
3457 				nh = skb_network_header(skb);
3458 				mh = (struct ip6_mh *)(nh + offset);
3459 				fl6->fl6_mh_type = mh->ip6mh_type;
3460 			}
3461 			fl6->flowi6_proto = nexthdr;
3462 			return;
3463 #endif
3464 		/* XXX Why are there these headers? */
3465 		case IPPROTO_AH:
3466 		case IPPROTO_ESP:
3467 		case IPPROTO_COMP:
3468 		default:
3469 			fl6->fl6_ipsec_spi = 0;
3470 			fl6->flowi6_proto = nexthdr;
3471 			return;
3472 		}
3473 	}
3474 }
3475 #endif
3476 
3477 int __xfrm_decode_session(struct sk_buff *skb, struct flowi *fl,
3478 			  unsigned int family, int reverse)
3479 {
3480 	switch (family) {
3481 	case AF_INET:
3482 		decode_session4(skb, fl, reverse);
3483 		break;
3484 #if IS_ENABLED(CONFIG_IPV6)
3485 	case AF_INET6:
3486 		decode_session6(skb, fl, reverse);
3487 		break;
3488 #endif
3489 	default:
3490 		return -EAFNOSUPPORT;
3491 	}
3492 
3493 	return security_xfrm_decode_session(skb, &fl->flowi_secid);
3494 }
3495 EXPORT_SYMBOL(__xfrm_decode_session);
3496 
3497 static inline int secpath_has_nontransport(const struct sec_path *sp, int k, int *idxp)
3498 {
3499 	for (; k < sp->len; k++) {
3500 		if (sp->xvec[k]->props.mode != XFRM_MODE_TRANSPORT) {
3501 			*idxp = k;
3502 			return 1;
3503 		}
3504 	}
3505 
3506 	return 0;
3507 }
3508 
3509 int __xfrm_policy_check(struct sock *sk, int dir, struct sk_buff *skb,
3510 			unsigned short family)
3511 {
3512 	struct net *net = dev_net(skb->dev);
3513 	struct xfrm_policy *pol;
3514 	struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
3515 	int npols = 0;
3516 	int xfrm_nr;
3517 	int pi;
3518 	int reverse;
3519 	struct flowi fl;
3520 	int xerr_idx = -1;
3521 	const struct xfrm_if_cb *ifcb;
3522 	struct sec_path *sp;
3523 	struct xfrm_if *xi;
3524 	u32 if_id = 0;
3525 
3526 	rcu_read_lock();
3527 	ifcb = xfrm_if_get_cb();
3528 
3529 	if (ifcb) {
3530 		xi = ifcb->decode_session(skb, family);
3531 		if (xi) {
3532 			if_id = xi->p.if_id;
3533 			net = xi->net;
3534 		}
3535 	}
3536 	rcu_read_unlock();
3537 
3538 	reverse = dir & ~XFRM_POLICY_MASK;
3539 	dir &= XFRM_POLICY_MASK;
3540 
3541 	if (__xfrm_decode_session(skb, &fl, family, reverse) < 0) {
3542 		XFRM_INC_STATS(net, LINUX_MIB_XFRMINHDRERROR);
3543 		return 0;
3544 	}
3545 
3546 	nf_nat_decode_session(skb, &fl, family);
3547 
3548 	/* First, check used SA against their selectors. */
3549 	sp = skb_sec_path(skb);
3550 	if (sp) {
3551 		int i;
3552 
3553 		for (i = sp->len - 1; i >= 0; i--) {
3554 			struct xfrm_state *x = sp->xvec[i];
3555 			if (!xfrm_selector_match(&x->sel, &fl, family)) {
3556 				XFRM_INC_STATS(net, LINUX_MIB_XFRMINSTATEMISMATCH);
3557 				return 0;
3558 			}
3559 		}
3560 	}
3561 
3562 	pol = NULL;
3563 	sk = sk_to_full_sk(sk);
3564 	if (sk && sk->sk_policy[dir]) {
3565 		pol = xfrm_sk_policy_lookup(sk, dir, &fl, family, if_id);
3566 		if (IS_ERR(pol)) {
3567 			XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
3568 			return 0;
3569 		}
3570 	}
3571 
3572 	if (!pol)
3573 		pol = xfrm_policy_lookup(net, &fl, family, dir, if_id);
3574 
3575 	if (IS_ERR(pol)) {
3576 		XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
3577 		return 0;
3578 	}
3579 
3580 	if (!pol) {
3581 		if (sp && secpath_has_nontransport(sp, 0, &xerr_idx)) {
3582 			xfrm_secpath_reject(xerr_idx, skb, &fl);
3583 			XFRM_INC_STATS(net, LINUX_MIB_XFRMINNOPOLS);
3584 			return 0;
3585 		}
3586 		return 1;
3587 	}
3588 
3589 	pol->curlft.use_time = ktime_get_real_seconds();
3590 
3591 	pols[0] = pol;
3592 	npols++;
3593 #ifdef CONFIG_XFRM_SUB_POLICY
3594 	if (pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
3595 		pols[1] = xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_MAIN,
3596 						    &fl, family,
3597 						    XFRM_POLICY_IN, if_id);
3598 		if (pols[1]) {
3599 			if (IS_ERR(pols[1])) {
3600 				XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
3601 				return 0;
3602 			}
3603 			pols[1]->curlft.use_time = ktime_get_real_seconds();
3604 			npols++;
3605 		}
3606 	}
3607 #endif
3608 
3609 	if (pol->action == XFRM_POLICY_ALLOW) {
3610 		static struct sec_path dummy;
3611 		struct xfrm_tmpl *tp[XFRM_MAX_DEPTH];
3612 		struct xfrm_tmpl *stp[XFRM_MAX_DEPTH];
3613 		struct xfrm_tmpl **tpp = tp;
3614 		int ti = 0;
3615 		int i, k;
3616 
3617 		sp = skb_sec_path(skb);
3618 		if (!sp)
3619 			sp = &dummy;
3620 
3621 		for (pi = 0; pi < npols; pi++) {
3622 			if (pols[pi] != pol &&
3623 			    pols[pi]->action != XFRM_POLICY_ALLOW) {
3624 				XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLBLOCK);
3625 				goto reject;
3626 			}
3627 			if (ti + pols[pi]->xfrm_nr >= XFRM_MAX_DEPTH) {
3628 				XFRM_INC_STATS(net, LINUX_MIB_XFRMINBUFFERERROR);
3629 				goto reject_error;
3630 			}
3631 			for (i = 0; i < pols[pi]->xfrm_nr; i++)
3632 				tpp[ti++] = &pols[pi]->xfrm_vec[i];
3633 		}
3634 		xfrm_nr = ti;
3635 		if (npols > 1) {
3636 			xfrm_tmpl_sort(stp, tpp, xfrm_nr, family);
3637 			tpp = stp;
3638 		}
3639 
3640 		/* For each tunnel xfrm, find the first matching tmpl.
3641 		 * For each tmpl before that, find corresponding xfrm.
3642 		 * Order is _important_. Later we will implement
3643 		 * some barriers, but at the moment barriers
3644 		 * are implied between each two transformations.
3645 		 */
3646 		for (i = xfrm_nr-1, k = 0; i >= 0; i--) {
3647 			k = xfrm_policy_ok(tpp[i], sp, k, family);
3648 			if (k < 0) {
3649 				if (k < -1)
3650 					/* "-2 - errored_index" returned */
3651 					xerr_idx = -(2+k);
3652 				XFRM_INC_STATS(net, LINUX_MIB_XFRMINTMPLMISMATCH);
3653 				goto reject;
3654 			}
3655 		}
3656 
3657 		if (secpath_has_nontransport(sp, k, &xerr_idx)) {
3658 			XFRM_INC_STATS(net, LINUX_MIB_XFRMINTMPLMISMATCH);
3659 			goto reject;
3660 		}
3661 
3662 		xfrm_pols_put(pols, npols);
3663 		return 1;
3664 	}
3665 	XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLBLOCK);
3666 
3667 reject:
3668 	xfrm_secpath_reject(xerr_idx, skb, &fl);
3669 reject_error:
3670 	xfrm_pols_put(pols, npols);
3671 	return 0;
3672 }
3673 EXPORT_SYMBOL(__xfrm_policy_check);
3674 
3675 int __xfrm_route_forward(struct sk_buff *skb, unsigned short family)
3676 {
3677 	struct net *net = dev_net(skb->dev);
3678 	struct flowi fl;
3679 	struct dst_entry *dst;
3680 	int res = 1;
3681 
3682 	if (xfrm_decode_session(skb, &fl, family) < 0) {
3683 		XFRM_INC_STATS(net, LINUX_MIB_XFRMFWDHDRERROR);
3684 		return 0;
3685 	}
3686 
3687 	skb_dst_force(skb);
3688 	if (!skb_dst(skb)) {
3689 		XFRM_INC_STATS(net, LINUX_MIB_XFRMFWDHDRERROR);
3690 		return 0;
3691 	}
3692 
3693 	dst = xfrm_lookup(net, skb_dst(skb), &fl, NULL, XFRM_LOOKUP_QUEUE);
3694 	if (IS_ERR(dst)) {
3695 		res = 0;
3696 		dst = NULL;
3697 	}
3698 	skb_dst_set(skb, dst);
3699 	return res;
3700 }
3701 EXPORT_SYMBOL(__xfrm_route_forward);
3702 
3703 /* Optimize later using cookies and generation ids. */
3704 
3705 static struct dst_entry *xfrm_dst_check(struct dst_entry *dst, u32 cookie)
3706 {
3707 	/* Code (such as __xfrm4_bundle_create()) sets dst->obsolete
3708 	 * to DST_OBSOLETE_FORCE_CHK to force all XFRM destinations to
3709 	 * get validated by dst_ops->check on every use.  We do this
3710 	 * because when a normal route referenced by an XFRM dst is
3711 	 * obsoleted we do not go looking around for all parent
3712 	 * referencing XFRM dsts so that we can invalidate them.  It
3713 	 * is just too much work.  Instead we make the checks here on
3714 	 * every use.  For example:
3715 	 *
3716 	 *	XFRM dst A --> IPv4 dst X
3717 	 *
3718 	 * X is the "xdst->route" of A (X is also the "dst->path" of A
3719 	 * in this example).  If X is marked obsolete, "A" will not
3720 	 * notice.  That's what we are validating here via the
3721 	 * stale_bundle() check.
3722 	 *
3723 	 * When a dst is removed from the fib tree, DST_OBSOLETE_DEAD will
3724 	 * be marked on it.
3725 	 * This will force stale_bundle() to fail on any xdst bundle with
3726 	 * this dst linked in it.
3727 	 */
3728 	if (dst->obsolete < 0 && !stale_bundle(dst))
3729 		return dst;
3730 
3731 	return NULL;
3732 }
3733 
3734 static int stale_bundle(struct dst_entry *dst)
3735 {
3736 	return !xfrm_bundle_ok((struct xfrm_dst *)dst);
3737 }
3738 
3739 void xfrm_dst_ifdown(struct dst_entry *dst, struct net_device *dev)
3740 {
3741 	while ((dst = xfrm_dst_child(dst)) && dst->xfrm && dst->dev == dev) {
3742 		dst->dev = dev_net(dev)->loopback_dev;
3743 		dev_hold(dst->dev);
3744 		dev_put(dev);
3745 	}
3746 }
3747 EXPORT_SYMBOL(xfrm_dst_ifdown);
3748 
3749 static void xfrm_link_failure(struct sk_buff *skb)
3750 {
3751 	/* Impossible. Such dst must be popped before reaches point of failure. */
3752 }
3753 
3754 static struct dst_entry *xfrm_negative_advice(struct dst_entry *dst)
3755 {
3756 	if (dst) {
3757 		if (dst->obsolete) {
3758 			dst_release(dst);
3759 			dst = NULL;
3760 		}
3761 	}
3762 	return dst;
3763 }
3764 
3765 static void xfrm_init_pmtu(struct xfrm_dst **bundle, int nr)
3766 {
3767 	while (nr--) {
3768 		struct xfrm_dst *xdst = bundle[nr];
3769 		u32 pmtu, route_mtu_cached;
3770 		struct dst_entry *dst;
3771 
3772 		dst = &xdst->u.dst;
3773 		pmtu = dst_mtu(xfrm_dst_child(dst));
3774 		xdst->child_mtu_cached = pmtu;
3775 
3776 		pmtu = xfrm_state_mtu(dst->xfrm, pmtu);
3777 
3778 		route_mtu_cached = dst_mtu(xdst->route);
3779 		xdst->route_mtu_cached = route_mtu_cached;
3780 
3781 		if (pmtu > route_mtu_cached)
3782 			pmtu = route_mtu_cached;
3783 
3784 		dst_metric_set(dst, RTAX_MTU, pmtu);
3785 	}
3786 }
3787 
3788 /* Check that the bundle accepts the flow and its components are
3789  * still valid.
3790  */
3791 
3792 static int xfrm_bundle_ok(struct xfrm_dst *first)
3793 {
3794 	struct xfrm_dst *bundle[XFRM_MAX_DEPTH];
3795 	struct dst_entry *dst = &first->u.dst;
3796 	struct xfrm_dst *xdst;
3797 	int start_from, nr;
3798 	u32 mtu;
3799 
3800 	if (!dst_check(xfrm_dst_path(dst), ((struct xfrm_dst *)dst)->path_cookie) ||
3801 	    (dst->dev && !netif_running(dst->dev)))
3802 		return 0;
3803 
3804 	if (dst->flags & DST_XFRM_QUEUE)
3805 		return 1;
3806 
3807 	start_from = nr = 0;
3808 	do {
3809 		struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
3810 
3811 		if (dst->xfrm->km.state != XFRM_STATE_VALID)
3812 			return 0;
3813 		if (xdst->xfrm_genid != dst->xfrm->genid)
3814 			return 0;
3815 		if (xdst->num_pols > 0 &&
3816 		    xdst->policy_genid != atomic_read(&xdst->pols[0]->genid))
3817 			return 0;
3818 
3819 		bundle[nr++] = xdst;
3820 
3821 		mtu = dst_mtu(xfrm_dst_child(dst));
3822 		if (xdst->child_mtu_cached != mtu) {
3823 			start_from = nr;
3824 			xdst->child_mtu_cached = mtu;
3825 		}
3826 
3827 		if (!dst_check(xdst->route, xdst->route_cookie))
3828 			return 0;
3829 		mtu = dst_mtu(xdst->route);
3830 		if (xdst->route_mtu_cached != mtu) {
3831 			start_from = nr;
3832 			xdst->route_mtu_cached = mtu;
3833 		}
3834 
3835 		dst = xfrm_dst_child(dst);
3836 	} while (dst->xfrm);
3837 
3838 	if (likely(!start_from))
3839 		return 1;
3840 
3841 	xdst = bundle[start_from - 1];
3842 	mtu = xdst->child_mtu_cached;
3843 	while (start_from--) {
3844 		dst = &xdst->u.dst;
3845 
3846 		mtu = xfrm_state_mtu(dst->xfrm, mtu);
3847 		if (mtu > xdst->route_mtu_cached)
3848 			mtu = xdst->route_mtu_cached;
3849 		dst_metric_set(dst, RTAX_MTU, mtu);
3850 		if (!start_from)
3851 			break;
3852 
3853 		xdst = bundle[start_from - 1];
3854 		xdst->child_mtu_cached = mtu;
3855 	}
3856 
3857 	return 1;
3858 }
3859 
3860 static unsigned int xfrm_default_advmss(const struct dst_entry *dst)
3861 {
3862 	return dst_metric_advmss(xfrm_dst_path(dst));
3863 }
3864 
3865 static unsigned int xfrm_mtu(const struct dst_entry *dst)
3866 {
3867 	unsigned int mtu = dst_metric_raw(dst, RTAX_MTU);
3868 
3869 	return mtu ? : dst_mtu(xfrm_dst_path(dst));
3870 }
3871 
3872 static const void *xfrm_get_dst_nexthop(const struct dst_entry *dst,
3873 					const void *daddr)
3874 {
3875 	while (dst->xfrm) {
3876 		const struct xfrm_state *xfrm = dst->xfrm;
3877 
3878 		dst = xfrm_dst_child(dst);
3879 
3880 		if (xfrm->props.mode == XFRM_MODE_TRANSPORT)
3881 			continue;
3882 		if (xfrm->type->flags & XFRM_TYPE_REMOTE_COADDR)
3883 			daddr = xfrm->coaddr;
3884 		else if (!(xfrm->type->flags & XFRM_TYPE_LOCAL_COADDR))
3885 			daddr = &xfrm->id.daddr;
3886 	}
3887 	return daddr;
3888 }
3889 
3890 static struct neighbour *xfrm_neigh_lookup(const struct dst_entry *dst,
3891 					   struct sk_buff *skb,
3892 					   const void *daddr)
3893 {
3894 	const struct dst_entry *path = xfrm_dst_path(dst);
3895 
3896 	if (!skb)
3897 		daddr = xfrm_get_dst_nexthop(dst, daddr);
3898 	return path->ops->neigh_lookup(path, skb, daddr);
3899 }
3900 
3901 static void xfrm_confirm_neigh(const struct dst_entry *dst, const void *daddr)
3902 {
3903 	const struct dst_entry *path = xfrm_dst_path(dst);
3904 
3905 	daddr = xfrm_get_dst_nexthop(dst, daddr);
3906 	path->ops->confirm_neigh(path, daddr);
3907 }
3908 
3909 int xfrm_policy_register_afinfo(const struct xfrm_policy_afinfo *afinfo, int family)
3910 {
3911 	int err = 0;
3912 
3913 	if (WARN_ON(family >= ARRAY_SIZE(xfrm_policy_afinfo)))
3914 		return -EAFNOSUPPORT;
3915 
3916 	spin_lock(&xfrm_policy_afinfo_lock);
3917 	if (unlikely(xfrm_policy_afinfo[family] != NULL))
3918 		err = -EEXIST;
3919 	else {
3920 		struct dst_ops *dst_ops = afinfo->dst_ops;
3921 		if (likely(dst_ops->kmem_cachep == NULL))
3922 			dst_ops->kmem_cachep = xfrm_dst_cache;
3923 		if (likely(dst_ops->check == NULL))
3924 			dst_ops->check = xfrm_dst_check;
3925 		if (likely(dst_ops->default_advmss == NULL))
3926 			dst_ops->default_advmss = xfrm_default_advmss;
3927 		if (likely(dst_ops->mtu == NULL))
3928 			dst_ops->mtu = xfrm_mtu;
3929 		if (likely(dst_ops->negative_advice == NULL))
3930 			dst_ops->negative_advice = xfrm_negative_advice;
3931 		if (likely(dst_ops->link_failure == NULL))
3932 			dst_ops->link_failure = xfrm_link_failure;
3933 		if (likely(dst_ops->neigh_lookup == NULL))
3934 			dst_ops->neigh_lookup = xfrm_neigh_lookup;
3935 		if (likely(!dst_ops->confirm_neigh))
3936 			dst_ops->confirm_neigh = xfrm_confirm_neigh;
3937 		rcu_assign_pointer(xfrm_policy_afinfo[family], afinfo);
3938 	}
3939 	spin_unlock(&xfrm_policy_afinfo_lock);
3940 
3941 	return err;
3942 }
3943 EXPORT_SYMBOL(xfrm_policy_register_afinfo);
3944 
3945 void xfrm_policy_unregister_afinfo(const struct xfrm_policy_afinfo *afinfo)
3946 {
3947 	struct dst_ops *dst_ops = afinfo->dst_ops;
3948 	int i;
3949 
3950 	for (i = 0; i < ARRAY_SIZE(xfrm_policy_afinfo); i++) {
3951 		if (xfrm_policy_afinfo[i] != afinfo)
3952 			continue;
3953 		RCU_INIT_POINTER(xfrm_policy_afinfo[i], NULL);
3954 		break;
3955 	}
3956 
3957 	synchronize_rcu();
3958 
3959 	dst_ops->kmem_cachep = NULL;
3960 	dst_ops->check = NULL;
3961 	dst_ops->negative_advice = NULL;
3962 	dst_ops->link_failure = NULL;
3963 }
3964 EXPORT_SYMBOL(xfrm_policy_unregister_afinfo);
3965 
3966 void xfrm_if_register_cb(const struct xfrm_if_cb *ifcb)
3967 {
3968 	spin_lock(&xfrm_if_cb_lock);
3969 	rcu_assign_pointer(xfrm_if_cb, ifcb);
3970 	spin_unlock(&xfrm_if_cb_lock);
3971 }
3972 EXPORT_SYMBOL(xfrm_if_register_cb);
3973 
3974 void xfrm_if_unregister_cb(void)
3975 {
3976 	RCU_INIT_POINTER(xfrm_if_cb, NULL);
3977 	synchronize_rcu();
3978 }
3979 EXPORT_SYMBOL(xfrm_if_unregister_cb);
3980 
3981 #ifdef CONFIG_XFRM_STATISTICS
3982 static int __net_init xfrm_statistics_init(struct net *net)
3983 {
3984 	int rv;
3985 	net->mib.xfrm_statistics = alloc_percpu(struct linux_xfrm_mib);
3986 	if (!net->mib.xfrm_statistics)
3987 		return -ENOMEM;
3988 	rv = xfrm_proc_init(net);
3989 	if (rv < 0)
3990 		free_percpu(net->mib.xfrm_statistics);
3991 	return rv;
3992 }
3993 
3994 static void xfrm_statistics_fini(struct net *net)
3995 {
3996 	xfrm_proc_fini(net);
3997 	free_percpu(net->mib.xfrm_statistics);
3998 }
3999 #else
4000 static int __net_init xfrm_statistics_init(struct net *net)
4001 {
4002 	return 0;
4003 }
4004 
4005 static void xfrm_statistics_fini(struct net *net)
4006 {
4007 }
4008 #endif
4009 
4010 static int __net_init xfrm_policy_init(struct net *net)
4011 {
4012 	unsigned int hmask, sz;
4013 	int dir, err;
4014 
4015 	if (net_eq(net, &init_net)) {
4016 		xfrm_dst_cache = kmem_cache_create("xfrm_dst_cache",
4017 					   sizeof(struct xfrm_dst),
4018 					   0, SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4019 					   NULL);
4020 		err = rhashtable_init(&xfrm_policy_inexact_table,
4021 				      &xfrm_pol_inexact_params);
4022 		BUG_ON(err);
4023 	}
4024 
4025 	hmask = 8 - 1;
4026 	sz = (hmask+1) * sizeof(struct hlist_head);
4027 
4028 	net->xfrm.policy_byidx = xfrm_hash_alloc(sz);
4029 	if (!net->xfrm.policy_byidx)
4030 		goto out_byidx;
4031 	net->xfrm.policy_idx_hmask = hmask;
4032 
4033 	for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
4034 		struct xfrm_policy_hash *htab;
4035 
4036 		net->xfrm.policy_count[dir] = 0;
4037 		net->xfrm.policy_count[XFRM_POLICY_MAX + dir] = 0;
4038 		INIT_HLIST_HEAD(&net->xfrm.policy_inexact[dir]);
4039 
4040 		htab = &net->xfrm.policy_bydst[dir];
4041 		htab->table = xfrm_hash_alloc(sz);
4042 		if (!htab->table)
4043 			goto out_bydst;
4044 		htab->hmask = hmask;
4045 		htab->dbits4 = 32;
4046 		htab->sbits4 = 32;
4047 		htab->dbits6 = 128;
4048 		htab->sbits6 = 128;
4049 	}
4050 	net->xfrm.policy_hthresh.lbits4 = 32;
4051 	net->xfrm.policy_hthresh.rbits4 = 32;
4052 	net->xfrm.policy_hthresh.lbits6 = 128;
4053 	net->xfrm.policy_hthresh.rbits6 = 128;
4054 
4055 	seqlock_init(&net->xfrm.policy_hthresh.lock);
4056 
4057 	INIT_LIST_HEAD(&net->xfrm.policy_all);
4058 	INIT_LIST_HEAD(&net->xfrm.inexact_bins);
4059 	INIT_WORK(&net->xfrm.policy_hash_work, xfrm_hash_resize);
4060 	INIT_WORK(&net->xfrm.policy_hthresh.work, xfrm_hash_rebuild);
4061 	return 0;
4062 
4063 out_bydst:
4064 	for (dir--; dir >= 0; dir--) {
4065 		struct xfrm_policy_hash *htab;
4066 
4067 		htab = &net->xfrm.policy_bydst[dir];
4068 		xfrm_hash_free(htab->table, sz);
4069 	}
4070 	xfrm_hash_free(net->xfrm.policy_byidx, sz);
4071 out_byidx:
4072 	return -ENOMEM;
4073 }
4074 
4075 static void xfrm_policy_fini(struct net *net)
4076 {
4077 	struct xfrm_pol_inexact_bin *b, *t;
4078 	unsigned int sz;
4079 	int dir;
4080 
4081 	flush_work(&net->xfrm.policy_hash_work);
4082 #ifdef CONFIG_XFRM_SUB_POLICY
4083 	xfrm_policy_flush(net, XFRM_POLICY_TYPE_SUB, false);
4084 #endif
4085 	xfrm_policy_flush(net, XFRM_POLICY_TYPE_MAIN, false);
4086 
4087 	WARN_ON(!list_empty(&net->xfrm.policy_all));
4088 
4089 	for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
4090 		struct xfrm_policy_hash *htab;
4091 
4092 		WARN_ON(!hlist_empty(&net->xfrm.policy_inexact[dir]));
4093 
4094 		htab = &net->xfrm.policy_bydst[dir];
4095 		sz = (htab->hmask + 1) * sizeof(struct hlist_head);
4096 		WARN_ON(!hlist_empty(htab->table));
4097 		xfrm_hash_free(htab->table, sz);
4098 	}
4099 
4100 	sz = (net->xfrm.policy_idx_hmask + 1) * sizeof(struct hlist_head);
4101 	WARN_ON(!hlist_empty(net->xfrm.policy_byidx));
4102 	xfrm_hash_free(net->xfrm.policy_byidx, sz);
4103 
4104 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
4105 	list_for_each_entry_safe(b, t, &net->xfrm.inexact_bins, inexact_bins)
4106 		__xfrm_policy_inexact_prune_bin(b, true);
4107 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
4108 }
4109 
4110 static int __net_init xfrm_net_init(struct net *net)
4111 {
4112 	int rv;
4113 
4114 	/* Initialize the per-net locks here */
4115 	spin_lock_init(&net->xfrm.xfrm_state_lock);
4116 	spin_lock_init(&net->xfrm.xfrm_policy_lock);
4117 	mutex_init(&net->xfrm.xfrm_cfg_mutex);
4118 
4119 	rv = xfrm_statistics_init(net);
4120 	if (rv < 0)
4121 		goto out_statistics;
4122 	rv = xfrm_state_init(net);
4123 	if (rv < 0)
4124 		goto out_state;
4125 	rv = xfrm_policy_init(net);
4126 	if (rv < 0)
4127 		goto out_policy;
4128 	rv = xfrm_sysctl_init(net);
4129 	if (rv < 0)
4130 		goto out_sysctl;
4131 
4132 	return 0;
4133 
4134 out_sysctl:
4135 	xfrm_policy_fini(net);
4136 out_policy:
4137 	xfrm_state_fini(net);
4138 out_state:
4139 	xfrm_statistics_fini(net);
4140 out_statistics:
4141 	return rv;
4142 }
4143 
4144 static void __net_exit xfrm_net_exit(struct net *net)
4145 {
4146 	xfrm_sysctl_fini(net);
4147 	xfrm_policy_fini(net);
4148 	xfrm_state_fini(net);
4149 	xfrm_statistics_fini(net);
4150 }
4151 
4152 static struct pernet_operations __net_initdata xfrm_net_ops = {
4153 	.init = xfrm_net_init,
4154 	.exit = xfrm_net_exit,
4155 };
4156 
4157 void __init xfrm_init(void)
4158 {
4159 	register_pernet_subsys(&xfrm_net_ops);
4160 	xfrm_dev_init();
4161 	seqcount_init(&xfrm_policy_hash_generation);
4162 	xfrm_input_init();
4163 
4164 #ifdef CONFIG_INET_ESPINTCP
4165 	espintcp_init();
4166 #endif
4167 
4168 	RCU_INIT_POINTER(xfrm_if_cb, NULL);
4169 	synchronize_rcu();
4170 }
4171 
4172 #ifdef CONFIG_AUDITSYSCALL
4173 static void xfrm_audit_common_policyinfo(struct xfrm_policy *xp,
4174 					 struct audit_buffer *audit_buf)
4175 {
4176 	struct xfrm_sec_ctx *ctx = xp->security;
4177 	struct xfrm_selector *sel = &xp->selector;
4178 
4179 	if (ctx)
4180 		audit_log_format(audit_buf, " sec_alg=%u sec_doi=%u sec_obj=%s",
4181 				 ctx->ctx_alg, ctx->ctx_doi, ctx->ctx_str);
4182 
4183 	switch (sel->family) {
4184 	case AF_INET:
4185 		audit_log_format(audit_buf, " src=%pI4", &sel->saddr.a4);
4186 		if (sel->prefixlen_s != 32)
4187 			audit_log_format(audit_buf, " src_prefixlen=%d",
4188 					 sel->prefixlen_s);
4189 		audit_log_format(audit_buf, " dst=%pI4", &sel->daddr.a4);
4190 		if (sel->prefixlen_d != 32)
4191 			audit_log_format(audit_buf, " dst_prefixlen=%d",
4192 					 sel->prefixlen_d);
4193 		break;
4194 	case AF_INET6:
4195 		audit_log_format(audit_buf, " src=%pI6", sel->saddr.a6);
4196 		if (sel->prefixlen_s != 128)
4197 			audit_log_format(audit_buf, " src_prefixlen=%d",
4198 					 sel->prefixlen_s);
4199 		audit_log_format(audit_buf, " dst=%pI6", sel->daddr.a6);
4200 		if (sel->prefixlen_d != 128)
4201 			audit_log_format(audit_buf, " dst_prefixlen=%d",
4202 					 sel->prefixlen_d);
4203 		break;
4204 	}
4205 }
4206 
4207 void xfrm_audit_policy_add(struct xfrm_policy *xp, int result, bool task_valid)
4208 {
4209 	struct audit_buffer *audit_buf;
4210 
4211 	audit_buf = xfrm_audit_start("SPD-add");
4212 	if (audit_buf == NULL)
4213 		return;
4214 	xfrm_audit_helper_usrinfo(task_valid, audit_buf);
4215 	audit_log_format(audit_buf, " res=%u", result);
4216 	xfrm_audit_common_policyinfo(xp, audit_buf);
4217 	audit_log_end(audit_buf);
4218 }
4219 EXPORT_SYMBOL_GPL(xfrm_audit_policy_add);
4220 
4221 void xfrm_audit_policy_delete(struct xfrm_policy *xp, int result,
4222 			      bool task_valid)
4223 {
4224 	struct audit_buffer *audit_buf;
4225 
4226 	audit_buf = xfrm_audit_start("SPD-delete");
4227 	if (audit_buf == NULL)
4228 		return;
4229 	xfrm_audit_helper_usrinfo(task_valid, audit_buf);
4230 	audit_log_format(audit_buf, " res=%u", result);
4231 	xfrm_audit_common_policyinfo(xp, audit_buf);
4232 	audit_log_end(audit_buf);
4233 }
4234 EXPORT_SYMBOL_GPL(xfrm_audit_policy_delete);
4235 #endif
4236 
4237 #ifdef CONFIG_XFRM_MIGRATE
4238 static bool xfrm_migrate_selector_match(const struct xfrm_selector *sel_cmp,
4239 					const struct xfrm_selector *sel_tgt)
4240 {
4241 	if (sel_cmp->proto == IPSEC_ULPROTO_ANY) {
4242 		if (sel_tgt->family == sel_cmp->family &&
4243 		    xfrm_addr_equal(&sel_tgt->daddr, &sel_cmp->daddr,
4244 				    sel_cmp->family) &&
4245 		    xfrm_addr_equal(&sel_tgt->saddr, &sel_cmp->saddr,
4246 				    sel_cmp->family) &&
4247 		    sel_tgt->prefixlen_d == sel_cmp->prefixlen_d &&
4248 		    sel_tgt->prefixlen_s == sel_cmp->prefixlen_s) {
4249 			return true;
4250 		}
4251 	} else {
4252 		if (memcmp(sel_tgt, sel_cmp, sizeof(*sel_tgt)) == 0) {
4253 			return true;
4254 		}
4255 	}
4256 	return false;
4257 }
4258 
4259 static struct xfrm_policy *xfrm_migrate_policy_find(const struct xfrm_selector *sel,
4260 						    u8 dir, u8 type, struct net *net)
4261 {
4262 	struct xfrm_policy *pol, *ret = NULL;
4263 	struct hlist_head *chain;
4264 	u32 priority = ~0U;
4265 
4266 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
4267 	chain = policy_hash_direct(net, &sel->daddr, &sel->saddr, sel->family, dir);
4268 	hlist_for_each_entry(pol, chain, bydst) {
4269 		if (xfrm_migrate_selector_match(sel, &pol->selector) &&
4270 		    pol->type == type) {
4271 			ret = pol;
4272 			priority = ret->priority;
4273 			break;
4274 		}
4275 	}
4276 	chain = &net->xfrm.policy_inexact[dir];
4277 	hlist_for_each_entry(pol, chain, bydst_inexact_list) {
4278 		if ((pol->priority >= priority) && ret)
4279 			break;
4280 
4281 		if (xfrm_migrate_selector_match(sel, &pol->selector) &&
4282 		    pol->type == type) {
4283 			ret = pol;
4284 			break;
4285 		}
4286 	}
4287 
4288 	xfrm_pol_hold(ret);
4289 
4290 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
4291 
4292 	return ret;
4293 }
4294 
4295 static int migrate_tmpl_match(const struct xfrm_migrate *m, const struct xfrm_tmpl *t)
4296 {
4297 	int match = 0;
4298 
4299 	if (t->mode == m->mode && t->id.proto == m->proto &&
4300 	    (m->reqid == 0 || t->reqid == m->reqid)) {
4301 		switch (t->mode) {
4302 		case XFRM_MODE_TUNNEL:
4303 		case XFRM_MODE_BEET:
4304 			if (xfrm_addr_equal(&t->id.daddr, &m->old_daddr,
4305 					    m->old_family) &&
4306 			    xfrm_addr_equal(&t->saddr, &m->old_saddr,
4307 					    m->old_family)) {
4308 				match = 1;
4309 			}
4310 			break;
4311 		case XFRM_MODE_TRANSPORT:
4312 			/* in case of transport mode, template does not store
4313 			   any IP addresses, hence we just compare mode and
4314 			   protocol */
4315 			match = 1;
4316 			break;
4317 		default:
4318 			break;
4319 		}
4320 	}
4321 	return match;
4322 }
4323 
4324 /* update endpoint address(es) of template(s) */
4325 static int xfrm_policy_migrate(struct xfrm_policy *pol,
4326 			       struct xfrm_migrate *m, int num_migrate)
4327 {
4328 	struct xfrm_migrate *mp;
4329 	int i, j, n = 0;
4330 
4331 	write_lock_bh(&pol->lock);
4332 	if (unlikely(pol->walk.dead)) {
4333 		/* target policy has been deleted */
4334 		write_unlock_bh(&pol->lock);
4335 		return -ENOENT;
4336 	}
4337 
4338 	for (i = 0; i < pol->xfrm_nr; i++) {
4339 		for (j = 0, mp = m; j < num_migrate; j++, mp++) {
4340 			if (!migrate_tmpl_match(mp, &pol->xfrm_vec[i]))
4341 				continue;
4342 			n++;
4343 			if (pol->xfrm_vec[i].mode != XFRM_MODE_TUNNEL &&
4344 			    pol->xfrm_vec[i].mode != XFRM_MODE_BEET)
4345 				continue;
4346 			/* update endpoints */
4347 			memcpy(&pol->xfrm_vec[i].id.daddr, &mp->new_daddr,
4348 			       sizeof(pol->xfrm_vec[i].id.daddr));
4349 			memcpy(&pol->xfrm_vec[i].saddr, &mp->new_saddr,
4350 			       sizeof(pol->xfrm_vec[i].saddr));
4351 			pol->xfrm_vec[i].encap_family = mp->new_family;
4352 			/* flush bundles */
4353 			atomic_inc(&pol->genid);
4354 		}
4355 	}
4356 
4357 	write_unlock_bh(&pol->lock);
4358 
4359 	if (!n)
4360 		return -ENODATA;
4361 
4362 	return 0;
4363 }
4364 
4365 static int xfrm_migrate_check(const struct xfrm_migrate *m, int num_migrate)
4366 {
4367 	int i, j;
4368 
4369 	if (num_migrate < 1 || num_migrate > XFRM_MAX_DEPTH)
4370 		return -EINVAL;
4371 
4372 	for (i = 0; i < num_migrate; i++) {
4373 		if (xfrm_addr_any(&m[i].new_daddr, m[i].new_family) ||
4374 		    xfrm_addr_any(&m[i].new_saddr, m[i].new_family))
4375 			return -EINVAL;
4376 
4377 		/* check if there is any duplicated entry */
4378 		for (j = i + 1; j < num_migrate; j++) {
4379 			if (!memcmp(&m[i].old_daddr, &m[j].old_daddr,
4380 				    sizeof(m[i].old_daddr)) &&
4381 			    !memcmp(&m[i].old_saddr, &m[j].old_saddr,
4382 				    sizeof(m[i].old_saddr)) &&
4383 			    m[i].proto == m[j].proto &&
4384 			    m[i].mode == m[j].mode &&
4385 			    m[i].reqid == m[j].reqid &&
4386 			    m[i].old_family == m[j].old_family)
4387 				return -EINVAL;
4388 		}
4389 	}
4390 
4391 	return 0;
4392 }
4393 
4394 int xfrm_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
4395 		 struct xfrm_migrate *m, int num_migrate,
4396 		 struct xfrm_kmaddress *k, struct net *net,
4397 		 struct xfrm_encap_tmpl *encap)
4398 {
4399 	int i, err, nx_cur = 0, nx_new = 0;
4400 	struct xfrm_policy *pol = NULL;
4401 	struct xfrm_state *x, *xc;
4402 	struct xfrm_state *x_cur[XFRM_MAX_DEPTH];
4403 	struct xfrm_state *x_new[XFRM_MAX_DEPTH];
4404 	struct xfrm_migrate *mp;
4405 
4406 	/* Stage 0 - sanity checks */
4407 	if ((err = xfrm_migrate_check(m, num_migrate)) < 0)
4408 		goto out;
4409 
4410 	if (dir >= XFRM_POLICY_MAX) {
4411 		err = -EINVAL;
4412 		goto out;
4413 	}
4414 
4415 	/* Stage 1 - find policy */
4416 	if ((pol = xfrm_migrate_policy_find(sel, dir, type, net)) == NULL) {
4417 		err = -ENOENT;
4418 		goto out;
4419 	}
4420 
4421 	/* Stage 2 - find and update state(s) */
4422 	for (i = 0, mp = m; i < num_migrate; i++, mp++) {
4423 		if ((x = xfrm_migrate_state_find(mp, net))) {
4424 			x_cur[nx_cur] = x;
4425 			nx_cur++;
4426 			xc = xfrm_state_migrate(x, mp, encap);
4427 			if (xc) {
4428 				x_new[nx_new] = xc;
4429 				nx_new++;
4430 			} else {
4431 				err = -ENODATA;
4432 				goto restore_state;
4433 			}
4434 		}
4435 	}
4436 
4437 	/* Stage 3 - update policy */
4438 	if ((err = xfrm_policy_migrate(pol, m, num_migrate)) < 0)
4439 		goto restore_state;
4440 
4441 	/* Stage 4 - delete old state(s) */
4442 	if (nx_cur) {
4443 		xfrm_states_put(x_cur, nx_cur);
4444 		xfrm_states_delete(x_cur, nx_cur);
4445 	}
4446 
4447 	/* Stage 5 - announce */
4448 	km_migrate(sel, dir, type, m, num_migrate, k, encap);
4449 
4450 	xfrm_pol_put(pol);
4451 
4452 	return 0;
4453 out:
4454 	return err;
4455 
4456 restore_state:
4457 	if (pol)
4458 		xfrm_pol_put(pol);
4459 	if (nx_cur)
4460 		xfrm_states_put(x_cur, nx_cur);
4461 	if (nx_new)
4462 		xfrm_states_delete(x_new, nx_new);
4463 
4464 	return err;
4465 }
4466 EXPORT_SYMBOL(xfrm_migrate);
4467 #endif
4468