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