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