xref: /linux/net/xfrm/xfrm_policy.c (revision 9fa903b24b1f46b4ff5443bcd4aca23e5c57f9c1)
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 	rcu_read_lock();
2774 	dev = dst_dev_rcu(dst);
2775 	if (!dev) {
2776 		rcu_read_unlock();
2777 		goto free_dst;
2778 	}
2779 
2780 	xfrm_init_path(xdst0, dst, nfheader_len);
2781 	xfrm_init_pmtu(bundle, nx);
2782 
2783 	for (xdst_prev = xdst0; xdst_prev != (struct xfrm_dst *)dst;
2784 	     xdst_prev = (struct xfrm_dst *) xfrm_dst_child(&xdst_prev->u.dst)) {
2785 		err = xfrm_fill_dst(xdst_prev, dev, fl);
2786 		if (err) {
2787 			rcu_read_unlock();
2788 			goto free_dst;
2789 		}
2790 
2791 		xdst_prev->u.dst.header_len = header_len;
2792 		xdst_prev->u.dst.trailer_len = trailer_len;
2793 		header_len -= xdst_prev->u.dst.xfrm->props.header_len;
2794 		trailer_len -= xdst_prev->u.dst.xfrm->props.trailer_len;
2795 	}
2796 
2797 	rcu_read_unlock();
2798 	return &xdst0->u.dst;
2799 
2800 put_states:
2801 	for (; i < nx; i++)
2802 		xfrm_state_put(xfrm[i]);
2803 free_dst:
2804 	if (xdst0)
2805 		dst_release_immediate(&xdst0->u.dst);
2806 
2807 	return ERR_PTR(err);
2808 }
2809 
2810 static int xfrm_expand_policies(const struct flowi *fl, u16 family,
2811 				struct xfrm_policy **pols,
2812 				int *num_pols, int *num_xfrms)
2813 {
2814 	int i;
2815 
2816 	if (*num_pols == 0 || !pols[0]) {
2817 		*num_pols = 0;
2818 		*num_xfrms = 0;
2819 		return 0;
2820 	}
2821 	if (IS_ERR(pols[0])) {
2822 		*num_pols = 0;
2823 		return PTR_ERR(pols[0]);
2824 	}
2825 
2826 	*num_xfrms = pols[0]->xfrm_nr;
2827 
2828 #ifdef CONFIG_XFRM_SUB_POLICY
2829 	if (pols[0]->action == XFRM_POLICY_ALLOW &&
2830 	    pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
2831 		pols[1] = xfrm_policy_lookup_bytype(xp_net(pols[0]),
2832 						    XFRM_POLICY_TYPE_MAIN,
2833 						    fl, family,
2834 						    XFRM_POLICY_OUT,
2835 						    pols[0]->if_id);
2836 		if (pols[1]) {
2837 			if (IS_ERR(pols[1])) {
2838 				xfrm_pols_put(pols, *num_pols);
2839 				*num_pols = 0;
2840 				return PTR_ERR(pols[1]);
2841 			}
2842 			(*num_pols)++;
2843 			(*num_xfrms) += pols[1]->xfrm_nr;
2844 		}
2845 	}
2846 #endif
2847 	for (i = 0; i < *num_pols; i++) {
2848 		if (pols[i]->action != XFRM_POLICY_ALLOW) {
2849 			*num_xfrms = -1;
2850 			break;
2851 		}
2852 	}
2853 
2854 	return 0;
2855 
2856 }
2857 
2858 static struct xfrm_dst *
2859 xfrm_resolve_and_create_bundle(struct xfrm_policy **pols, int num_pols,
2860 			       const struct flowi *fl, u16 family,
2861 			       struct dst_entry *dst_orig)
2862 {
2863 	struct net *net = xp_net(pols[0]);
2864 	struct xfrm_state *xfrm[XFRM_MAX_DEPTH];
2865 	struct xfrm_dst *bundle[XFRM_MAX_DEPTH];
2866 	struct xfrm_dst *xdst;
2867 	struct dst_entry *dst;
2868 	int err;
2869 
2870 	/* Try to instantiate a bundle */
2871 	err = xfrm_tmpl_resolve(pols, num_pols, fl, xfrm, family);
2872 	if (err <= 0) {
2873 		if (err == 0)
2874 			return NULL;
2875 
2876 		if (err != -EAGAIN)
2877 			XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLERROR);
2878 		return ERR_PTR(err);
2879 	}
2880 
2881 	dst = xfrm_bundle_create(pols[0], xfrm, bundle, err, fl, dst_orig);
2882 	if (IS_ERR(dst)) {
2883 		XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTBUNDLEGENERROR);
2884 		return ERR_CAST(dst);
2885 	}
2886 
2887 	xdst = (struct xfrm_dst *)dst;
2888 	xdst->num_xfrms = err;
2889 	xdst->num_pols = num_pols;
2890 	memcpy(xdst->pols, pols, sizeof(struct xfrm_policy *) * num_pols);
2891 	xdst->policy_genid = atomic_read(&pols[0]->genid);
2892 
2893 	return xdst;
2894 }
2895 
2896 static void xfrm_policy_queue_process(struct timer_list *t)
2897 {
2898 	struct sk_buff *skb;
2899 	struct sock *sk;
2900 	struct dst_entry *dst;
2901 	struct xfrm_policy *pol = timer_container_of(pol, t, polq.hold_timer);
2902 	struct net *net = xp_net(pol);
2903 	struct xfrm_policy_queue *pq = &pol->polq;
2904 	struct flowi fl;
2905 	struct sk_buff_head list;
2906 	__u32 skb_mark;
2907 
2908 	spin_lock(&pq->hold_queue.lock);
2909 	skb = skb_peek(&pq->hold_queue);
2910 	if (!skb) {
2911 		spin_unlock(&pq->hold_queue.lock);
2912 		goto out;
2913 	}
2914 	dst = skb_dst(skb);
2915 	sk = skb->sk;
2916 
2917 	/* Fixup the mark to support VTI. */
2918 	skb_mark = skb->mark;
2919 	skb->mark = pol->mark.v;
2920 	xfrm_decode_session(net, skb, &fl, dst->ops->family);
2921 	skb->mark = skb_mark;
2922 	spin_unlock(&pq->hold_queue.lock);
2923 
2924 	dst_hold(xfrm_dst_path(dst));
2925 	dst = xfrm_lookup(net, xfrm_dst_path(dst), &fl, sk, XFRM_LOOKUP_QUEUE);
2926 	if (IS_ERR(dst))
2927 		goto purge_queue;
2928 
2929 	if (dst->flags & DST_XFRM_QUEUE) {
2930 		dst_release(dst);
2931 
2932 		if (pq->timeout >= XFRM_QUEUE_TMO_MAX)
2933 			goto purge_queue;
2934 
2935 		pq->timeout = pq->timeout << 1;
2936 		if (!mod_timer(&pq->hold_timer, jiffies + pq->timeout))
2937 			xfrm_pol_hold(pol);
2938 		goto out;
2939 	}
2940 
2941 	dst_release(dst);
2942 
2943 	__skb_queue_head_init(&list);
2944 
2945 	spin_lock(&pq->hold_queue.lock);
2946 	pq->timeout = 0;
2947 	skb_queue_splice_init(&pq->hold_queue, &list);
2948 	spin_unlock(&pq->hold_queue.lock);
2949 
2950 	while (!skb_queue_empty(&list)) {
2951 		skb = __skb_dequeue(&list);
2952 
2953 		/* Fixup the mark to support VTI. */
2954 		skb_mark = skb->mark;
2955 		skb->mark = pol->mark.v;
2956 		xfrm_decode_session(net, skb, &fl, skb_dst(skb)->ops->family);
2957 		skb->mark = skb_mark;
2958 
2959 		dst_hold(xfrm_dst_path(skb_dst(skb)));
2960 		dst = xfrm_lookup(net, xfrm_dst_path(skb_dst(skb)), &fl, skb->sk, 0);
2961 		if (IS_ERR(dst)) {
2962 			kfree_skb(skb);
2963 			continue;
2964 		}
2965 
2966 		nf_reset_ct(skb);
2967 		skb_dst_drop(skb);
2968 		skb_dst_set(skb, dst);
2969 
2970 		dst_output(net, skb_to_full_sk(skb), skb);
2971 	}
2972 
2973 out:
2974 	xfrm_pol_put(pol);
2975 	return;
2976 
2977 purge_queue:
2978 	pq->timeout = 0;
2979 	skb_queue_purge(&pq->hold_queue);
2980 	xfrm_pol_put(pol);
2981 }
2982 
2983 static int xdst_queue_output(struct net *net, struct sock *sk, struct sk_buff *skb)
2984 {
2985 	unsigned long sched_next;
2986 	struct dst_entry *dst = skb_dst(skb);
2987 	struct xfrm_dst *xdst = (struct xfrm_dst *) dst;
2988 	struct xfrm_policy *pol = xdst->pols[0];
2989 	struct xfrm_policy_queue *pq = &pol->polq;
2990 
2991 	if (unlikely(skb_fclone_busy(sk, skb))) {
2992 		kfree_skb(skb);
2993 		return 0;
2994 	}
2995 
2996 	if (pq->hold_queue.qlen > XFRM_MAX_QUEUE_LEN) {
2997 		kfree_skb(skb);
2998 		return -EAGAIN;
2999 	}
3000 
3001 	skb_dst_force(skb);
3002 
3003 	spin_lock_bh(&pq->hold_queue.lock);
3004 
3005 	if (!pq->timeout)
3006 		pq->timeout = XFRM_QUEUE_TMO_MIN;
3007 
3008 	sched_next = jiffies + pq->timeout;
3009 
3010 	if (timer_delete(&pq->hold_timer)) {
3011 		if (time_before(pq->hold_timer.expires, sched_next))
3012 			sched_next = pq->hold_timer.expires;
3013 		xfrm_pol_put(pol);
3014 	}
3015 
3016 	__skb_queue_tail(&pq->hold_queue, skb);
3017 	if (!mod_timer(&pq->hold_timer, sched_next))
3018 		xfrm_pol_hold(pol);
3019 
3020 	spin_unlock_bh(&pq->hold_queue.lock);
3021 
3022 	return 0;
3023 }
3024 
3025 static struct xfrm_dst *xfrm_create_dummy_bundle(struct net *net,
3026 						 struct xfrm_flo *xflo,
3027 						 const struct flowi *fl,
3028 						 int num_xfrms,
3029 						 u16 family)
3030 {
3031 	int err;
3032 	struct net_device *dev;
3033 	struct dst_entry *dst;
3034 	struct dst_entry *dst1;
3035 	struct xfrm_dst *xdst;
3036 
3037 	xdst = xfrm_alloc_dst(net, family);
3038 	if (IS_ERR(xdst))
3039 		return xdst;
3040 
3041 	if (!(xflo->flags & XFRM_LOOKUP_QUEUE) ||
3042 	    net->xfrm.sysctl_larval_drop ||
3043 	    num_xfrms <= 0)
3044 		return xdst;
3045 
3046 	dst = xflo->dst_orig;
3047 	dst1 = &xdst->u.dst;
3048 	dst_hold(dst);
3049 	xdst->route = dst;
3050 
3051 	dst_copy_metrics(dst1, dst);
3052 
3053 	dst1->obsolete = DST_OBSOLETE_FORCE_CHK;
3054 	dst1->flags |= DST_XFRM_QUEUE;
3055 	dst1->lastuse = jiffies;
3056 
3057 	dst1->input = dst_discard;
3058 	dst1->output = xdst_queue_output;
3059 
3060 	dst_hold(dst);
3061 	xfrm_dst_set_child(xdst, dst);
3062 	xdst->path = dst;
3063 
3064 	xfrm_init_path((struct xfrm_dst *)dst1, dst, 0);
3065 
3066 	err = -ENODEV;
3067 	rcu_read_lock();
3068 	dev = dst_dev_rcu(dst);
3069 	if (!dev) {
3070 		rcu_read_unlock();
3071 		goto free_dst;
3072 	}
3073 
3074 	err = xfrm_fill_dst(xdst, dev, fl);
3075 	rcu_read_unlock();
3076 	if (err)
3077 		goto free_dst;
3078 
3079 out:
3080 	return xdst;
3081 
3082 free_dst:
3083 	dst_release(dst1);
3084 	xdst = ERR_PTR(err);
3085 	goto out;
3086 }
3087 
3088 static struct xfrm_dst *xfrm_bundle_lookup(struct net *net,
3089 					   const struct flowi *fl,
3090 					   u16 family, u8 dir,
3091 					   struct xfrm_flo *xflo, u32 if_id)
3092 {
3093 	struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
3094 	int num_pols = 0, num_xfrms = 0, err;
3095 	struct xfrm_dst *xdst;
3096 
3097 	/* Resolve policies to use if we couldn't get them from
3098 	 * previous cache entry */
3099 	num_pols = 1;
3100 	pols[0] = xfrm_policy_lookup(net, fl, family, dir, if_id);
3101 	err = xfrm_expand_policies(fl, family, pols,
3102 					   &num_pols, &num_xfrms);
3103 	if (err < 0)
3104 		goto inc_error;
3105 	if (num_pols == 0)
3106 		return NULL;
3107 	if (num_xfrms <= 0)
3108 		goto make_dummy_bundle;
3109 
3110 	xdst = xfrm_resolve_and_create_bundle(pols, num_pols, fl, family,
3111 					      xflo->dst_orig);
3112 	if (IS_ERR(xdst)) {
3113 		err = PTR_ERR(xdst);
3114 		if (err == -EREMOTE) {
3115 			xfrm_pols_put(pols, num_pols);
3116 			return NULL;
3117 		}
3118 
3119 		if (err != -EAGAIN)
3120 			goto error;
3121 		goto make_dummy_bundle;
3122 	} else if (xdst == NULL) {
3123 		num_xfrms = 0;
3124 		goto make_dummy_bundle;
3125 	}
3126 
3127 	return xdst;
3128 
3129 make_dummy_bundle:
3130 	/* We found policies, but there's no bundles to instantiate:
3131 	 * either because the policy blocks, has no transformations or
3132 	 * we could not build template (no xfrm_states).*/
3133 	xdst = xfrm_create_dummy_bundle(net, xflo, fl, num_xfrms, family);
3134 	if (IS_ERR(xdst)) {
3135 		xfrm_pols_put(pols, num_pols);
3136 		return ERR_CAST(xdst);
3137 	}
3138 	xdst->num_pols = num_pols;
3139 	xdst->num_xfrms = num_xfrms;
3140 	memcpy(xdst->pols, pols, sizeof(struct xfrm_policy *) * num_pols);
3141 
3142 	return xdst;
3143 
3144 inc_error:
3145 	XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLERROR);
3146 error:
3147 	xfrm_pols_put(pols, num_pols);
3148 	return ERR_PTR(err);
3149 }
3150 
3151 static struct dst_entry *make_blackhole(struct net *net, u16 family,
3152 					struct dst_entry *dst_orig)
3153 {
3154 	const struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
3155 	struct dst_entry *ret;
3156 
3157 	if (!afinfo) {
3158 		dst_release(dst_orig);
3159 		return ERR_PTR(-EINVAL);
3160 	} else {
3161 		ret = afinfo->blackhole_route(net, dst_orig);
3162 	}
3163 	rcu_read_unlock();
3164 
3165 	return ret;
3166 }
3167 
3168 /* Finds/creates a bundle for given flow and if_id
3169  *
3170  * At the moment we eat a raw IP route. Mostly to speed up lookups
3171  * on interfaces with disabled IPsec.
3172  *
3173  * xfrm_lookup uses an if_id of 0 by default, and is provided for
3174  * compatibility
3175  */
3176 struct dst_entry *xfrm_lookup_with_ifid(struct net *net,
3177 					struct dst_entry *dst_orig,
3178 					const struct flowi *fl,
3179 					const struct sock *sk,
3180 					int flags, u32 if_id)
3181 {
3182 	struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
3183 	struct xfrm_dst *xdst;
3184 	struct dst_entry *dst, *route;
3185 	u16 family = dst_orig->ops->family;
3186 	u8 dir = XFRM_POLICY_OUT;
3187 	int i, err, num_pols, num_xfrms = 0, drop_pols = 0;
3188 
3189 	dst = NULL;
3190 	xdst = NULL;
3191 	route = NULL;
3192 
3193 	sk = sk_const_to_full_sk(sk);
3194 	if (sk && sk->sk_policy[XFRM_POLICY_OUT]) {
3195 		num_pols = 1;
3196 		pols[0] = xfrm_sk_policy_lookup(sk, XFRM_POLICY_OUT, fl, family,
3197 						if_id);
3198 		err = xfrm_expand_policies(fl, family, pols,
3199 					   &num_pols, &num_xfrms);
3200 		if (err < 0)
3201 			goto dropdst;
3202 
3203 		if (num_pols) {
3204 			if (num_xfrms <= 0) {
3205 				drop_pols = num_pols;
3206 				goto no_transform;
3207 			}
3208 
3209 			xdst = xfrm_resolve_and_create_bundle(
3210 					pols, num_pols, fl,
3211 					family, dst_orig);
3212 
3213 			if (IS_ERR(xdst)) {
3214 				xfrm_pols_put(pols, num_pols);
3215 				err = PTR_ERR(xdst);
3216 				if (err == -EREMOTE)
3217 					goto nopol;
3218 
3219 				goto dropdst;
3220 			} else if (xdst == NULL) {
3221 				num_xfrms = 0;
3222 				drop_pols = num_pols;
3223 				goto no_transform;
3224 			}
3225 
3226 			route = xdst->route;
3227 		}
3228 	}
3229 
3230 	if (xdst == NULL) {
3231 		struct xfrm_flo xflo;
3232 
3233 		xflo.dst_orig = dst_orig;
3234 		xflo.flags = flags;
3235 
3236 		/* To accelerate a bit...  */
3237 		if (!if_id && ((dst_orig->flags & DST_NOXFRM) ||
3238 			       !READ_ONCE(net->xfrm.policy_count[XFRM_POLICY_OUT])))
3239 			goto nopol;
3240 
3241 		xdst = xfrm_bundle_lookup(net, fl, family, dir, &xflo, if_id);
3242 		if (xdst == NULL)
3243 			goto nopol;
3244 		if (IS_ERR(xdst)) {
3245 			err = PTR_ERR(xdst);
3246 			goto dropdst;
3247 		}
3248 
3249 		num_pols = xdst->num_pols;
3250 		num_xfrms = xdst->num_xfrms;
3251 		memcpy(pols, xdst->pols, sizeof(struct xfrm_policy *) * num_pols);
3252 		route = xdst->route;
3253 	}
3254 
3255 	dst = &xdst->u.dst;
3256 	if (route == NULL && num_xfrms > 0) {
3257 		/* The only case when xfrm_bundle_lookup() returns a
3258 		 * bundle with null route, is when the template could
3259 		 * not be resolved. It means policies are there, but
3260 		 * bundle could not be created, since we don't yet
3261 		 * have the xfrm_state's. We need to wait for KM to
3262 		 * negotiate new SA's or bail out with error.*/
3263 		if (net->xfrm.sysctl_larval_drop) {
3264 			XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTNOSTATES);
3265 			err = -EREMOTE;
3266 			goto error;
3267 		}
3268 
3269 		err = -EAGAIN;
3270 
3271 		XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTNOSTATES);
3272 		goto error;
3273 	}
3274 
3275 no_transform:
3276 	if (num_pols == 0)
3277 		goto nopol;
3278 
3279 	if ((flags & XFRM_LOOKUP_ICMP) &&
3280 	    !(pols[0]->flags & XFRM_POLICY_ICMP)) {
3281 		err = -ENOENT;
3282 		goto error;
3283 	}
3284 
3285 	for (i = 0; i < num_pols; i++)
3286 		WRITE_ONCE(pols[i]->curlft.use_time, ktime_get_real_seconds());
3287 
3288 	if (num_xfrms < 0) {
3289 		/* Prohibit the flow */
3290 		XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLBLOCK);
3291 		err = -EPERM;
3292 		goto error;
3293 	} else if (num_xfrms > 0) {
3294 		/* Flow transformed */
3295 		dst_release(dst_orig);
3296 	} else {
3297 		/* Flow passes untransformed */
3298 		dst_release(dst);
3299 		dst = dst_orig;
3300 	}
3301 
3302 ok:
3303 	xfrm_pols_put(pols, drop_pols);
3304 	if (dst->xfrm &&
3305 	    (dst->xfrm->props.mode == XFRM_MODE_TUNNEL ||
3306 	     dst->xfrm->props.mode == XFRM_MODE_IPTFS))
3307 		dst->flags |= DST_XFRM_TUNNEL;
3308 	return dst;
3309 
3310 nopol:
3311 	if ((!dst_orig->dev || !(dst_orig->dev->flags & IFF_LOOPBACK)) &&
3312 	    READ_ONCE(net->xfrm.policy_default[dir]) == XFRM_USERPOLICY_BLOCK) {
3313 		err = -EPERM;
3314 		goto error;
3315 	}
3316 	if (!(flags & XFRM_LOOKUP_ICMP)) {
3317 		dst = dst_orig;
3318 		goto ok;
3319 	}
3320 	err = -ENOENT;
3321 error:
3322 	dst_release(dst);
3323 dropdst:
3324 	if (!(flags & XFRM_LOOKUP_KEEP_DST_REF))
3325 		dst_release(dst_orig);
3326 	xfrm_pols_put(pols, drop_pols);
3327 	return ERR_PTR(err);
3328 }
3329 EXPORT_SYMBOL(xfrm_lookup_with_ifid);
3330 
3331 /* Main function: finds/creates a bundle for given flow.
3332  *
3333  * At the moment we eat a raw IP route. Mostly to speed up lookups
3334  * on interfaces with disabled IPsec.
3335  */
3336 struct dst_entry *xfrm_lookup(struct net *net, struct dst_entry *dst_orig,
3337 			      const struct flowi *fl, const struct sock *sk,
3338 			      int flags)
3339 {
3340 	return xfrm_lookup_with_ifid(net, dst_orig, fl, sk, flags, 0);
3341 }
3342 EXPORT_SYMBOL(xfrm_lookup);
3343 
3344 /* Callers of xfrm_lookup_route() must ensure a call to dst_output().
3345  * Otherwise we may send out blackholed packets.
3346  */
3347 struct dst_entry *xfrm_lookup_route(struct net *net, struct dst_entry *dst_orig,
3348 				    const struct flowi *fl,
3349 				    const struct sock *sk, int flags)
3350 {
3351 	struct dst_entry *dst = xfrm_lookup(net, dst_orig, fl, sk,
3352 					    flags | XFRM_LOOKUP_QUEUE |
3353 					    XFRM_LOOKUP_KEEP_DST_REF);
3354 
3355 	if (PTR_ERR(dst) == -EREMOTE)
3356 		return make_blackhole(net, dst_orig->ops->family, dst_orig);
3357 
3358 	if (IS_ERR(dst))
3359 		dst_release(dst_orig);
3360 
3361 	return dst;
3362 }
3363 EXPORT_SYMBOL(xfrm_lookup_route);
3364 
3365 static inline int
3366 xfrm_secpath_reject(int idx, struct sk_buff *skb, const struct flowi *fl)
3367 {
3368 	struct sec_path *sp = skb_sec_path(skb);
3369 	struct xfrm_state *x;
3370 
3371 	if (!sp || idx < 0 || idx >= sp->len)
3372 		return 0;
3373 	x = sp->xvec[idx];
3374 	if (!x->type->reject)
3375 		return 0;
3376 	return x->type->reject(x, skb, fl);
3377 }
3378 
3379 /* When skb is transformed back to its "native" form, we have to
3380  * check policy restrictions. At the moment we make this in maximally
3381  * stupid way. Shame on me. :-) Of course, connected sockets must
3382  * have policy cached at them.
3383  */
3384 
3385 static inline int
3386 xfrm_state_ok(const struct xfrm_tmpl *tmpl, const struct xfrm_state *x,
3387 	      unsigned short family, u32 if_id)
3388 {
3389 	if (xfrm_state_kern(x))
3390 		return tmpl->optional && !xfrm_state_addr_cmp(tmpl, x, tmpl->encap_family);
3391 	return	x->id.proto == tmpl->id.proto &&
3392 		(x->id.spi == tmpl->id.spi || !tmpl->id.spi) &&
3393 		(x->props.reqid == tmpl->reqid || !tmpl->reqid) &&
3394 		x->props.mode == tmpl->mode &&
3395 		(tmpl->allalgs || (tmpl->aalgos & (1<<x->props.aalgo)) ||
3396 		 !(xfrm_id_proto_match(tmpl->id.proto, IPSEC_PROTO_ANY))) &&
3397 		!(x->props.mode != XFRM_MODE_TRANSPORT &&
3398 		  xfrm_state_addr_cmp(tmpl, x, family)) &&
3399 		(if_id == 0 || if_id == x->if_id);
3400 }
3401 
3402 /*
3403  * 0 or more than 0 is returned when validation is succeeded (either bypass
3404  * because of optional transport mode, or next index of the matched secpath
3405  * state with the template.
3406  * -1 is returned when no matching template is found.
3407  * Otherwise "-2 - errored_index" is returned.
3408  */
3409 static inline int
3410 xfrm_policy_ok(const struct xfrm_tmpl *tmpl, const struct sec_path *sp, int start,
3411 	       unsigned short family, u32 if_id)
3412 {
3413 	int idx = start;
3414 
3415 	if (tmpl->optional) {
3416 		if (tmpl->mode == XFRM_MODE_TRANSPORT)
3417 			return start;
3418 	} else
3419 		start = -1;
3420 	for (; idx < sp->len; idx++) {
3421 		if (xfrm_state_ok(tmpl, sp->xvec[idx], family, if_id))
3422 			return ++idx;
3423 		if (sp->xvec[idx]->props.mode != XFRM_MODE_TRANSPORT) {
3424 			if (idx < sp->verified_cnt) {
3425 				/* Secpath entry previously verified, consider optional and
3426 				 * continue searching
3427 				 */
3428 				continue;
3429 			}
3430 
3431 			if (start == -1)
3432 				start = -2-idx;
3433 			break;
3434 		}
3435 	}
3436 	return start;
3437 }
3438 
3439 static void
3440 decode_session4(const struct xfrm_flow_keys *flkeys, struct flowi *fl, bool reverse)
3441 {
3442 	struct flowi4 *fl4 = &fl->u.ip4;
3443 
3444 	memset(fl4, 0, sizeof(struct flowi4));
3445 
3446 	if (reverse) {
3447 		fl4->saddr = flkeys->addrs.ipv4.dst;
3448 		fl4->daddr = flkeys->addrs.ipv4.src;
3449 		fl4->fl4_sport = flkeys->ports.dst;
3450 		fl4->fl4_dport = flkeys->ports.src;
3451 	} else {
3452 		fl4->saddr = flkeys->addrs.ipv4.src;
3453 		fl4->daddr = flkeys->addrs.ipv4.dst;
3454 		fl4->fl4_sport = flkeys->ports.src;
3455 		fl4->fl4_dport = flkeys->ports.dst;
3456 	}
3457 
3458 	switch (flkeys->basic.ip_proto) {
3459 	case IPPROTO_GRE:
3460 		fl4->fl4_gre_key = flkeys->gre.keyid;
3461 		break;
3462 	case IPPROTO_ICMP:
3463 		fl4->fl4_icmp_type = flkeys->icmp.type;
3464 		fl4->fl4_icmp_code = flkeys->icmp.code;
3465 		break;
3466 	}
3467 
3468 	fl4->flowi4_proto = flkeys->basic.ip_proto;
3469 	fl4->flowi4_dscp = inet_dsfield_to_dscp(flkeys->ip.tos);
3470 }
3471 
3472 #if IS_ENABLED(CONFIG_IPV6)
3473 static void
3474 decode_session6(const struct xfrm_flow_keys *flkeys, struct flowi *fl, bool reverse)
3475 {
3476 	struct flowi6 *fl6 = &fl->u.ip6;
3477 
3478 	memset(fl6, 0, sizeof(struct flowi6));
3479 
3480 	if (reverse) {
3481 		fl6->saddr = flkeys->addrs.ipv6.dst;
3482 		fl6->daddr = flkeys->addrs.ipv6.src;
3483 		fl6->fl6_sport = flkeys->ports.dst;
3484 		fl6->fl6_dport = flkeys->ports.src;
3485 	} else {
3486 		fl6->saddr = flkeys->addrs.ipv6.src;
3487 		fl6->daddr = flkeys->addrs.ipv6.dst;
3488 		fl6->fl6_sport = flkeys->ports.src;
3489 		fl6->fl6_dport = flkeys->ports.dst;
3490 	}
3491 
3492 	switch (flkeys->basic.ip_proto) {
3493 	case IPPROTO_GRE:
3494 		fl6->fl6_gre_key = flkeys->gre.keyid;
3495 		break;
3496 	case IPPROTO_ICMPV6:
3497 		fl6->fl6_icmp_type = flkeys->icmp.type;
3498 		fl6->fl6_icmp_code = flkeys->icmp.code;
3499 		break;
3500 	}
3501 
3502 	fl6->flowi6_proto = flkeys->basic.ip_proto;
3503 }
3504 #endif
3505 
3506 int __xfrm_decode_session(struct net *net, struct sk_buff *skb, struct flowi *fl,
3507 			  unsigned int family, int reverse)
3508 {
3509 	struct xfrm_flow_keys flkeys;
3510 
3511 	memset(&flkeys, 0, sizeof(flkeys));
3512 	__skb_flow_dissect(net, skb, &xfrm_session_dissector, &flkeys,
3513 			   NULL, 0, 0, 0, FLOW_DISSECTOR_F_STOP_AT_ENCAP);
3514 
3515 	switch (family) {
3516 	case AF_INET:
3517 		decode_session4(&flkeys, fl, reverse);
3518 		break;
3519 #if IS_ENABLED(CONFIG_IPV6)
3520 	case AF_INET6:
3521 		decode_session6(&flkeys, fl, reverse);
3522 		break;
3523 #endif
3524 	default:
3525 		return -EAFNOSUPPORT;
3526 	}
3527 
3528 	fl->flowi_mark = skb->mark;
3529 	if (reverse) {
3530 		fl->flowi_oif = skb->skb_iif;
3531 	} else {
3532 		int oif = 0;
3533 
3534 		if (skb_dst(skb) && skb_dst(skb)->dev)
3535 			oif = skb_dst(skb)->dev->ifindex;
3536 
3537 		fl->flowi_oif = oif;
3538 	}
3539 
3540 	return security_xfrm_decode_session(skb, &fl->flowi_secid);
3541 }
3542 EXPORT_SYMBOL(__xfrm_decode_session);
3543 
3544 static inline int secpath_has_nontransport(const struct sec_path *sp, int k, int *idxp)
3545 {
3546 	for (; k < sp->len; k++) {
3547 		if (sp->xvec[k]->props.mode != XFRM_MODE_TRANSPORT) {
3548 			*idxp = k;
3549 			return 1;
3550 		}
3551 	}
3552 
3553 	return 0;
3554 }
3555 
3556 static bool icmp_err_packet(const struct flowi *fl, unsigned short family)
3557 {
3558 	const struct flowi4 *fl4 = &fl->u.ip4;
3559 
3560 	if (family == AF_INET &&
3561 	    fl4->flowi4_proto == IPPROTO_ICMP &&
3562 	    (fl4->fl4_icmp_type == ICMP_DEST_UNREACH ||
3563 	     fl4->fl4_icmp_type == ICMP_TIME_EXCEEDED))
3564 		return true;
3565 
3566 #if IS_ENABLED(CONFIG_IPV6)
3567 	if (family == AF_INET6) {
3568 		const struct flowi6 *fl6 = &fl->u.ip6;
3569 
3570 		if (fl6->flowi6_proto == IPPROTO_ICMPV6 &&
3571 		    (fl6->fl6_icmp_type == ICMPV6_DEST_UNREACH ||
3572 		    fl6->fl6_icmp_type == ICMPV6_PKT_TOOBIG ||
3573 		    fl6->fl6_icmp_type == ICMPV6_TIME_EXCEED))
3574 			return true;
3575 	}
3576 #endif
3577 	return false;
3578 }
3579 
3580 static bool xfrm_icmp_flow_decode(struct sk_buff *skb, unsigned short family,
3581 				  const struct flowi *fl, struct flowi *fl1)
3582 {
3583 	bool ret = true;
3584 	struct sk_buff *newskb = skb_clone(skb, GFP_ATOMIC);
3585 	int hl = family == AF_INET ? (sizeof(struct iphdr) +  sizeof(struct icmphdr)) :
3586 		 (sizeof(struct ipv6hdr) + sizeof(struct icmp6hdr));
3587 
3588 	if (!newskb)
3589 		return true;
3590 
3591 	if (!pskb_pull(newskb, hl))
3592 		goto out;
3593 
3594 	skb_reset_network_header(newskb);
3595 
3596 	if (xfrm_decode_session_reverse(dev_net(skb->dev), newskb, fl1, family) < 0)
3597 		goto out;
3598 
3599 	fl1->flowi_oif = fl->flowi_oif;
3600 	fl1->flowi_mark = fl->flowi_mark;
3601 	fl1->flowi_dscp = fl->flowi_dscp;
3602 	nf_nat_decode_session(newskb, fl1, family);
3603 	ret = false;
3604 
3605 out:
3606 	consume_skb(newskb);
3607 	return ret;
3608 }
3609 
3610 static bool xfrm_selector_inner_icmp_match(struct sk_buff *skb, unsigned short family,
3611 					   const struct xfrm_selector *sel,
3612 					   const struct flowi *fl)
3613 {
3614 	bool ret = false;
3615 
3616 	if (icmp_err_packet(fl, family)) {
3617 		struct flowi fl1;
3618 
3619 		if (xfrm_icmp_flow_decode(skb, family, fl, &fl1))
3620 			return ret;
3621 
3622 		ret = xfrm_selector_match(sel, &fl1, family);
3623 	}
3624 
3625 	return ret;
3626 }
3627 
3628 static inline struct
3629 xfrm_policy *xfrm_in_fwd_icmp(struct sk_buff *skb,
3630 			      const struct flowi *fl, unsigned short family,
3631 			      u32 if_id)
3632 {
3633 	struct xfrm_policy *pol = NULL;
3634 
3635 	if (icmp_err_packet(fl, family)) {
3636 		struct flowi fl1;
3637 		struct net *net = dev_net(skb->dev);
3638 
3639 		if (xfrm_icmp_flow_decode(skb, family, fl, &fl1))
3640 			return pol;
3641 
3642 		pol = xfrm_policy_lookup(net, &fl1, family, XFRM_POLICY_FWD, if_id);
3643 		if (IS_ERR(pol))
3644 			pol = NULL;
3645 	}
3646 
3647 	return pol;
3648 }
3649 
3650 static inline struct
3651 dst_entry *xfrm_out_fwd_icmp(struct sk_buff *skb, struct flowi *fl,
3652 			     unsigned short family, struct dst_entry *dst)
3653 {
3654 	if (icmp_err_packet(fl, family)) {
3655 		struct net *net = dev_net(skb->dev);
3656 		struct dst_entry *dst2;
3657 		struct flowi fl1;
3658 
3659 		if (xfrm_icmp_flow_decode(skb, family, fl, &fl1))
3660 			return dst;
3661 
3662 		dst_hold(dst);
3663 
3664 		dst2 = xfrm_lookup(net, dst, &fl1, NULL, (XFRM_LOOKUP_QUEUE | XFRM_LOOKUP_ICMP));
3665 
3666 		if (IS_ERR(dst2))
3667 			return dst;
3668 
3669 		if (dst2->xfrm) {
3670 			dst_release(dst);
3671 			dst = dst2;
3672 		} else {
3673 			dst_release(dst2);
3674 		}
3675 	}
3676 
3677 	return dst;
3678 }
3679 
3680 int __xfrm_policy_check(struct sock *sk, int dir, struct sk_buff *skb,
3681 			unsigned short family)
3682 {
3683 	struct net *net = dev_net(skb->dev);
3684 	struct xfrm_policy *pol;
3685 	struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
3686 	int npols = 0;
3687 	int xfrm_nr;
3688 	int pi;
3689 	int reverse;
3690 	struct flowi fl;
3691 	int xerr_idx = -1;
3692 	const struct xfrm_if_cb *ifcb;
3693 	struct sec_path *sp;
3694 	u32 if_id = 0;
3695 
3696 	rcu_read_lock();
3697 	ifcb = xfrm_if_get_cb();
3698 
3699 	if (ifcb) {
3700 		struct xfrm_if_decode_session_result r;
3701 
3702 		if (ifcb->decode_session(skb, family, &r)) {
3703 			if_id = r.if_id;
3704 			net = r.net;
3705 		}
3706 	}
3707 	rcu_read_unlock();
3708 
3709 	reverse = dir & ~XFRM_POLICY_MASK;
3710 	dir &= XFRM_POLICY_MASK;
3711 
3712 	if (__xfrm_decode_session(net, skb, &fl, family, reverse) < 0) {
3713 		XFRM_INC_STATS(net, LINUX_MIB_XFRMINHDRERROR);
3714 		return 0;
3715 	}
3716 
3717 	nf_nat_decode_session(skb, &fl, family);
3718 
3719 	/* First, check used SA against their selectors. */
3720 	sp = skb_sec_path(skb);
3721 	if (sp) {
3722 		int i;
3723 
3724 		for (i = sp->len - 1; i >= 0; i--) {
3725 			struct xfrm_state *x = sp->xvec[i];
3726 			int ret = 0;
3727 
3728 			if (!xfrm_selector_match(&x->sel, &fl, family)) {
3729 				ret = 1;
3730 				if (x->props.flags & XFRM_STATE_ICMP &&
3731 				    xfrm_selector_inner_icmp_match(skb, family, &x->sel, &fl))
3732 					ret = 0;
3733 				if (ret) {
3734 					XFRM_INC_STATS(net, LINUX_MIB_XFRMINSTATEMISMATCH);
3735 					return 0;
3736 				}
3737 			}
3738 		}
3739 	}
3740 
3741 	pol = NULL;
3742 	sk = sk_to_full_sk(sk);
3743 	if (sk && sk->sk_policy[dir]) {
3744 		pol = xfrm_sk_policy_lookup(sk, dir, &fl, family, if_id);
3745 		if (IS_ERR(pol)) {
3746 			XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
3747 			return 0;
3748 		}
3749 	}
3750 
3751 	if (!pol)
3752 		pol = xfrm_policy_lookup(net, &fl, family, dir, if_id);
3753 
3754 	if (IS_ERR(pol)) {
3755 		XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
3756 		return 0;
3757 	}
3758 
3759 	if (!pol && dir == XFRM_POLICY_FWD)
3760 		pol = xfrm_in_fwd_icmp(skb, &fl, family, if_id);
3761 
3762 	if (!pol) {
3763 		const bool is_crypto_offload = sp &&
3764 			(xfrm_input_state(skb)->xso.type == XFRM_DEV_OFFLOAD_CRYPTO);
3765 
3766 		if (READ_ONCE(net->xfrm.policy_default[dir]) == XFRM_USERPOLICY_BLOCK) {
3767 			XFRM_INC_STATS(net, LINUX_MIB_XFRMINNOPOLS);
3768 			return 0;
3769 		}
3770 
3771 		if (sp && secpath_has_nontransport(sp, 0, &xerr_idx) && !is_crypto_offload) {
3772 			xfrm_secpath_reject(xerr_idx, skb, &fl);
3773 			XFRM_INC_STATS(net, LINUX_MIB_XFRMINNOPOLS);
3774 			return 0;
3775 		}
3776 		return 1;
3777 	}
3778 
3779 	/* This lockless write can happen from different cpus. */
3780 	WRITE_ONCE(pol->curlft.use_time, ktime_get_real_seconds());
3781 
3782 	pols[0] = pol;
3783 	npols++;
3784 #ifdef CONFIG_XFRM_SUB_POLICY
3785 	if (pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
3786 		pols[1] = xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_MAIN,
3787 						    &fl, family,
3788 						    XFRM_POLICY_IN, if_id);
3789 		if (pols[1]) {
3790 			if (IS_ERR(pols[1])) {
3791 				XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
3792 				xfrm_pol_put(pols[0]);
3793 				return 0;
3794 			}
3795 			/* This write can happen from different cpus. */
3796 			WRITE_ONCE(pols[1]->curlft.use_time,
3797 				   ktime_get_real_seconds());
3798 			npols++;
3799 		}
3800 	}
3801 #endif
3802 
3803 	if (pol->action == XFRM_POLICY_ALLOW) {
3804 		static struct sec_path dummy;
3805 		struct xfrm_tmpl *tp[XFRM_MAX_DEPTH];
3806 		struct xfrm_tmpl *stp[XFRM_MAX_DEPTH];
3807 		struct xfrm_tmpl **tpp = tp;
3808 		int i, k = 0;
3809 		int ti = 0;
3810 
3811 		sp = skb_sec_path(skb);
3812 		if (!sp)
3813 			sp = &dummy;
3814 
3815 		for (pi = 0; pi < npols; pi++) {
3816 			if (pols[pi] != pol &&
3817 			    pols[pi]->action != XFRM_POLICY_ALLOW) {
3818 				XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLBLOCK);
3819 				goto reject;
3820 			}
3821 			if (ti + pols[pi]->xfrm_nr >= XFRM_MAX_DEPTH) {
3822 				XFRM_INC_STATS(net, LINUX_MIB_XFRMINBUFFERERROR);
3823 				goto reject_error;
3824 			}
3825 			for (i = 0; i < pols[pi]->xfrm_nr; i++)
3826 				tpp[ti++] = &pols[pi]->xfrm_vec[i];
3827 		}
3828 		xfrm_nr = ti;
3829 
3830 		if (npols > 1) {
3831 			xfrm_tmpl_sort(stp, tpp, xfrm_nr, family);
3832 			tpp = stp;
3833 		}
3834 
3835 		if (pol->xdo.type == XFRM_DEV_OFFLOAD_PACKET && sp == &dummy)
3836 			/* This policy template was already checked by HW
3837 			 * and secpath was removed in __xfrm_policy_check2.
3838 			 */
3839 			goto out;
3840 
3841 		/* For each tunnel xfrm, find the first matching tmpl.
3842 		 * For each tmpl before that, find corresponding xfrm.
3843 		 * Order is _important_. Later we will implement
3844 		 * some barriers, but at the moment barriers
3845 		 * are implied between each two transformations.
3846 		 * Upon success, marks secpath entries as having been
3847 		 * verified to allow them to be skipped in future policy
3848 		 * checks (e.g. nested tunnels).
3849 		 */
3850 		for (i = xfrm_nr - 1; i >= 0; i--) {
3851 			k = xfrm_policy_ok(tpp[i], sp, k, family, if_id);
3852 			if (k < 0) {
3853 				if (k < -1)
3854 					/* "-2 - errored_index" returned */
3855 					xerr_idx = -(2+k);
3856 				XFRM_INC_STATS(net, LINUX_MIB_XFRMINTMPLMISMATCH);
3857 				goto reject;
3858 			}
3859 		}
3860 
3861 		if (secpath_has_nontransport(sp, k, &xerr_idx)) {
3862 			XFRM_INC_STATS(net, LINUX_MIB_XFRMINTMPLMISMATCH);
3863 			goto reject;
3864 		}
3865 
3866 out:
3867 		xfrm_pols_put(pols, npols);
3868 		sp->verified_cnt = k;
3869 
3870 		return 1;
3871 	}
3872 	XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLBLOCK);
3873 
3874 reject:
3875 	xfrm_secpath_reject(xerr_idx, skb, &fl);
3876 reject_error:
3877 	xfrm_pols_put(pols, npols);
3878 	return 0;
3879 }
3880 EXPORT_SYMBOL(__xfrm_policy_check);
3881 
3882 int __xfrm_route_forward(struct sk_buff *skb, unsigned short family)
3883 {
3884 	struct net *net = dev_net(skb->dev);
3885 	struct flowi fl;
3886 	struct dst_entry *dst;
3887 	int res = 1;
3888 
3889 	if (xfrm_decode_session(net, skb, &fl, family) < 0) {
3890 		XFRM_INC_STATS(net, LINUX_MIB_XFRMFWDHDRERROR);
3891 		return 0;
3892 	}
3893 
3894 	skb_dst_force(skb);
3895 	dst = skb_dst(skb);
3896 	if (!dst) {
3897 		XFRM_INC_STATS(net, LINUX_MIB_XFRMFWDHDRERROR);
3898 		return 0;
3899 	}
3900 
3901 	/* ignore return value from skb_dstref_steal, xfrm_lookup takes
3902 	 * care of dropping the refcnt if needed.
3903 	 */
3904 	skb_dstref_steal(skb);
3905 
3906 	dst = xfrm_lookup(net, dst, &fl, NULL, XFRM_LOOKUP_QUEUE);
3907 	if (IS_ERR(dst)) {
3908 		res = 0;
3909 		dst = NULL;
3910 	}
3911 
3912 	if (dst && !dst->xfrm)
3913 		dst = xfrm_out_fwd_icmp(skb, &fl, family, dst);
3914 
3915 	skb_dst_set(skb, dst);
3916 	return res;
3917 }
3918 EXPORT_SYMBOL(__xfrm_route_forward);
3919 
3920 /* Optimize later using cookies and generation ids. */
3921 
3922 static struct dst_entry *xfrm_dst_check(struct dst_entry *dst, u32 cookie)
3923 {
3924 	/* Code (such as xfrm_bundle_create()) sets dst->obsolete
3925 	 * to DST_OBSOLETE_FORCE_CHK to force all XFRM destinations to
3926 	 * get validated by dst_ops->check on every use.  We do this
3927 	 * because when a normal route referenced by an XFRM dst is
3928 	 * obsoleted we do not go looking around for all parent
3929 	 * referencing XFRM dsts so that we can invalidate them.  It
3930 	 * is just too much work.  Instead we make the checks here on
3931 	 * every use.  For example:
3932 	 *
3933 	 *	XFRM dst A --> IPv4 dst X
3934 	 *
3935 	 * X is the "xdst->route" of A (X is also the "dst->path" of A
3936 	 * in this example).  If X is marked obsolete, "A" will not
3937 	 * notice.  That's what we are validating here via the
3938 	 * stale_bundle() check.
3939 	 *
3940 	 * When a dst is removed from the fib tree, DST_OBSOLETE_DEAD will
3941 	 * be marked on it.
3942 	 * This will force stale_bundle() to fail on any xdst bundle with
3943 	 * this dst linked in it.
3944 	 */
3945 	if (READ_ONCE(dst->obsolete) < 0 && !stale_bundle(dst))
3946 		return dst;
3947 
3948 	return NULL;
3949 }
3950 
3951 static int stale_bundle(struct dst_entry *dst)
3952 {
3953 	return !xfrm_bundle_ok((struct xfrm_dst *)dst);
3954 }
3955 
3956 void xfrm_dst_ifdown(struct dst_entry *dst, struct net_device *dev)
3957 {
3958 	while ((dst = xfrm_dst_child(dst)) && dst->xfrm && dst->dev == dev) {
3959 		dst->dev = blackhole_netdev;
3960 		dev_hold(dst->dev);
3961 		dev_put(dev);
3962 	}
3963 }
3964 EXPORT_SYMBOL(xfrm_dst_ifdown);
3965 
3966 static void xfrm_link_failure(struct sk_buff *skb)
3967 {
3968 	/* Impossible. Such dst must be popped before reaches point of failure. */
3969 }
3970 
3971 static void xfrm_negative_advice(struct sock *sk, struct dst_entry *dst)
3972 {
3973 	if (READ_ONCE(dst->obsolete))
3974 		sk_dst_reset(sk);
3975 }
3976 
3977 static void xfrm_init_pmtu(struct xfrm_dst **bundle, int nr)
3978 {
3979 	while (nr--) {
3980 		struct xfrm_dst *xdst = bundle[nr];
3981 		u32 pmtu, route_mtu_cached;
3982 		struct dst_entry *dst;
3983 
3984 		dst = &xdst->u.dst;
3985 		pmtu = dst_mtu(xfrm_dst_child(dst));
3986 		xdst->child_mtu_cached = pmtu;
3987 
3988 		pmtu = xfrm_state_mtu(dst->xfrm, pmtu);
3989 
3990 		route_mtu_cached = dst_mtu(xdst->route);
3991 		xdst->route_mtu_cached = route_mtu_cached;
3992 
3993 		if (pmtu > route_mtu_cached)
3994 			pmtu = route_mtu_cached;
3995 
3996 		dst_metric_set(dst, RTAX_MTU, pmtu);
3997 	}
3998 }
3999 
4000 /* Check that the bundle accepts the flow and its components are
4001  * still valid.
4002  */
4003 
4004 static int xfrm_bundle_ok(struct xfrm_dst *first)
4005 {
4006 	struct xfrm_dst *bundle[XFRM_MAX_DEPTH];
4007 	struct dst_entry *dst = &first->u.dst;
4008 	struct xfrm_dst *xdst;
4009 	int start_from, nr;
4010 	u32 mtu;
4011 
4012 	if (!dst_check(xfrm_dst_path(dst), ((struct xfrm_dst *)dst)->path_cookie) ||
4013 	    (dst->dev && !netif_running(dst->dev)))
4014 		return 0;
4015 
4016 	if (dst->flags & DST_XFRM_QUEUE)
4017 		return 1;
4018 
4019 	start_from = nr = 0;
4020 	do {
4021 		struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
4022 
4023 		if (dst->xfrm->km.state != XFRM_STATE_VALID)
4024 			return 0;
4025 		if (xdst->xfrm_genid != dst->xfrm->genid)
4026 			return 0;
4027 		if (xdst->num_pols > 0 &&
4028 		    xdst->policy_genid != atomic_read(&xdst->pols[0]->genid))
4029 			return 0;
4030 
4031 		bundle[nr++] = xdst;
4032 
4033 		mtu = dst_mtu(xfrm_dst_child(dst));
4034 		if (xdst->child_mtu_cached != mtu) {
4035 			start_from = nr;
4036 			xdst->child_mtu_cached = mtu;
4037 		}
4038 
4039 		if (!dst_check(xdst->route, xdst->route_cookie))
4040 			return 0;
4041 		mtu = dst_mtu(xdst->route);
4042 		if (xdst->route_mtu_cached != mtu) {
4043 			start_from = nr;
4044 			xdst->route_mtu_cached = mtu;
4045 		}
4046 
4047 		dst = xfrm_dst_child(dst);
4048 	} while (dst->xfrm);
4049 
4050 	if (likely(!start_from))
4051 		return 1;
4052 
4053 	xdst = bundle[start_from - 1];
4054 	mtu = xdst->child_mtu_cached;
4055 	while (start_from--) {
4056 		dst = &xdst->u.dst;
4057 
4058 		mtu = xfrm_state_mtu(dst->xfrm, mtu);
4059 		if (mtu > xdst->route_mtu_cached)
4060 			mtu = xdst->route_mtu_cached;
4061 		dst_metric_set(dst, RTAX_MTU, mtu);
4062 		if (!start_from)
4063 			break;
4064 
4065 		xdst = bundle[start_from - 1];
4066 		xdst->child_mtu_cached = mtu;
4067 	}
4068 
4069 	return 1;
4070 }
4071 
4072 static unsigned int xfrm_default_advmss(const struct dst_entry *dst)
4073 {
4074 	return dst_metric_advmss(xfrm_dst_path(dst));
4075 }
4076 
4077 static unsigned int xfrm_mtu(const struct dst_entry *dst)
4078 {
4079 	unsigned int mtu = dst_metric_raw(dst, RTAX_MTU);
4080 
4081 	return mtu ? : dst_mtu(xfrm_dst_path(dst));
4082 }
4083 
4084 static const void *xfrm_get_dst_nexthop(const struct dst_entry *dst,
4085 					const void *daddr)
4086 {
4087 	while (dst->xfrm) {
4088 		const struct xfrm_state *xfrm = dst->xfrm;
4089 
4090 		dst = xfrm_dst_child(dst);
4091 
4092 		if (xfrm->props.mode == XFRM_MODE_TRANSPORT)
4093 			continue;
4094 		if (xfrm->type->flags & XFRM_TYPE_REMOTE_COADDR)
4095 			daddr = xfrm->coaddr;
4096 		else if (!(xfrm->type->flags & XFRM_TYPE_LOCAL_COADDR))
4097 			daddr = &xfrm->id.daddr;
4098 	}
4099 	return daddr;
4100 }
4101 
4102 static struct neighbour *xfrm_neigh_lookup(const struct dst_entry *dst,
4103 					   struct sk_buff *skb,
4104 					   const void *daddr)
4105 {
4106 	const struct dst_entry *path = xfrm_dst_path(dst);
4107 
4108 	if (!skb)
4109 		daddr = xfrm_get_dst_nexthop(dst, daddr);
4110 	return path->ops->neigh_lookup(path, skb, daddr);
4111 }
4112 
4113 static void xfrm_confirm_neigh(const struct dst_entry *dst, const void *daddr)
4114 {
4115 	const struct dst_entry *path = xfrm_dst_path(dst);
4116 
4117 	daddr = xfrm_get_dst_nexthop(dst, daddr);
4118 	path->ops->confirm_neigh(path, daddr);
4119 }
4120 
4121 int xfrm_policy_register_afinfo(const struct xfrm_policy_afinfo *afinfo, int family)
4122 {
4123 	int err = 0;
4124 
4125 	if (WARN_ON(family >= ARRAY_SIZE(xfrm_policy_afinfo)))
4126 		return -EAFNOSUPPORT;
4127 
4128 	spin_lock(&xfrm_policy_afinfo_lock);
4129 	if (unlikely(xfrm_policy_afinfo[family] != NULL))
4130 		err = -EEXIST;
4131 	else {
4132 		struct dst_ops *dst_ops = afinfo->dst_ops;
4133 		if (likely(dst_ops->kmem_cachep == NULL))
4134 			dst_ops->kmem_cachep = xfrm_dst_cache;
4135 		if (likely(dst_ops->check == NULL))
4136 			dst_ops->check = xfrm_dst_check;
4137 		if (likely(dst_ops->default_advmss == NULL))
4138 			dst_ops->default_advmss = xfrm_default_advmss;
4139 		if (likely(dst_ops->mtu == NULL))
4140 			dst_ops->mtu = xfrm_mtu;
4141 		if (likely(dst_ops->negative_advice == NULL))
4142 			dst_ops->negative_advice = xfrm_negative_advice;
4143 		if (likely(dst_ops->link_failure == NULL))
4144 			dst_ops->link_failure = xfrm_link_failure;
4145 		if (likely(dst_ops->neigh_lookup == NULL))
4146 			dst_ops->neigh_lookup = xfrm_neigh_lookup;
4147 		if (likely(!dst_ops->confirm_neigh))
4148 			dst_ops->confirm_neigh = xfrm_confirm_neigh;
4149 		rcu_assign_pointer(xfrm_policy_afinfo[family], afinfo);
4150 	}
4151 	spin_unlock(&xfrm_policy_afinfo_lock);
4152 
4153 	return err;
4154 }
4155 EXPORT_SYMBOL(xfrm_policy_register_afinfo);
4156 
4157 void xfrm_policy_unregister_afinfo(const struct xfrm_policy_afinfo *afinfo)
4158 {
4159 	struct dst_ops *dst_ops = afinfo->dst_ops;
4160 	int i;
4161 
4162 	for (i = 0; i < ARRAY_SIZE(xfrm_policy_afinfo); i++) {
4163 		if (rcu_access_pointer(xfrm_policy_afinfo[i]) != afinfo)
4164 			continue;
4165 		RCU_INIT_POINTER(xfrm_policy_afinfo[i], NULL);
4166 		break;
4167 	}
4168 
4169 	synchronize_rcu();
4170 
4171 	dst_ops->kmem_cachep = NULL;
4172 	dst_ops->check = NULL;
4173 	dst_ops->negative_advice = NULL;
4174 	dst_ops->link_failure = NULL;
4175 }
4176 EXPORT_SYMBOL(xfrm_policy_unregister_afinfo);
4177 
4178 void xfrm_if_register_cb(const struct xfrm_if_cb *ifcb)
4179 {
4180 	spin_lock(&xfrm_if_cb_lock);
4181 	rcu_assign_pointer(xfrm_if_cb, ifcb);
4182 	spin_unlock(&xfrm_if_cb_lock);
4183 }
4184 EXPORT_SYMBOL(xfrm_if_register_cb);
4185 
4186 void xfrm_if_unregister_cb(void)
4187 {
4188 	RCU_INIT_POINTER(xfrm_if_cb, NULL);
4189 	synchronize_rcu();
4190 }
4191 EXPORT_SYMBOL(xfrm_if_unregister_cb);
4192 
4193 #ifdef CONFIG_XFRM_STATISTICS
4194 static int __net_init xfrm_statistics_init(struct net *net)
4195 {
4196 	int rv;
4197 	net->mib.xfrm_statistics = alloc_percpu(struct linux_xfrm_mib);
4198 	if (!net->mib.xfrm_statistics)
4199 		return -ENOMEM;
4200 	rv = xfrm_proc_init(net);
4201 	if (rv < 0)
4202 		free_percpu(net->mib.xfrm_statistics);
4203 	return rv;
4204 }
4205 
4206 static void xfrm_statistics_fini(struct net *net)
4207 {
4208 	xfrm_proc_fini(net);
4209 	free_percpu(net->mib.xfrm_statistics);
4210 }
4211 #else
4212 static int __net_init xfrm_statistics_init(struct net *net)
4213 {
4214 	return 0;
4215 }
4216 
4217 static void xfrm_statistics_fini(struct net *net)
4218 {
4219 }
4220 #endif
4221 
4222 static int __net_init xfrm_policy_init(struct net *net)
4223 {
4224 	unsigned int hmask, sz;
4225 	int dir, err;
4226 
4227 	if (net_eq(net, &init_net)) {
4228 		xfrm_dst_cache = KMEM_CACHE(xfrm_dst, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
4229 		err = rhashtable_init(&xfrm_policy_inexact_table,
4230 				      &xfrm_pol_inexact_params);
4231 		BUG_ON(err);
4232 	}
4233 
4234 	hmask = 8 - 1;
4235 	sz = (hmask+1) * sizeof(struct hlist_head);
4236 
4237 	net->xfrm.policy_byidx = xfrm_hash_alloc(sz);
4238 	if (!net->xfrm.policy_byidx)
4239 		goto out_byidx;
4240 	net->xfrm.policy_idx_hmask = hmask;
4241 
4242 	for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
4243 		struct xfrm_policy_hash *htab;
4244 
4245 		net->xfrm.policy_count[dir] = 0;
4246 		net->xfrm.policy_count[XFRM_POLICY_MAX + dir] = 0;
4247 
4248 		htab = &net->xfrm.policy_bydst[dir];
4249 		rcu_assign_pointer(htab->table, xfrm_hash_alloc(sz));
4250 		if (!htab->table)
4251 			goto out_bydst;
4252 		htab->hmask = hmask;
4253 		htab->dbits4 = 32;
4254 		htab->sbits4 = 32;
4255 		htab->dbits6 = 128;
4256 		htab->sbits6 = 128;
4257 	}
4258 	net->xfrm.policy_hthresh.lbits4 = 32;
4259 	net->xfrm.policy_hthresh.rbits4 = 32;
4260 	net->xfrm.policy_hthresh.lbits6 = 128;
4261 	net->xfrm.policy_hthresh.rbits6 = 128;
4262 
4263 	seqlock_init(&net->xfrm.policy_hthresh.lock);
4264 
4265 	INIT_LIST_HEAD(&net->xfrm.policy_all);
4266 	INIT_LIST_HEAD(&net->xfrm.inexact_bins);
4267 	INIT_WORK(&net->xfrm.policy_hash_work, xfrm_hash_resize);
4268 	INIT_WORK(&net->xfrm.policy_hthresh.work, xfrm_hash_rebuild);
4269 	return 0;
4270 
4271 out_bydst:
4272 	for (dir--; dir >= 0; dir--) {
4273 		struct xfrm_policy_hash *htab;
4274 
4275 		htab = &net->xfrm.policy_bydst[dir];
4276 		xfrm_hash_free(rcu_dereference_protected(htab->table, true), sz);
4277 	}
4278 	xfrm_hash_free(net->xfrm.policy_byidx, sz);
4279 out_byidx:
4280 	return -ENOMEM;
4281 }
4282 
4283 static void __net_exit xfrm_net_pre_exit(struct net *net)
4284 {
4285 	disable_work_sync(&net->xfrm.policy_hthresh.work);
4286 	flush_work(&net->xfrm.policy_hash_work);
4287 #ifdef CONFIG_XFRM_SUB_POLICY
4288 	xfrm_policy_flush(net, XFRM_POLICY_TYPE_SUB, false);
4289 #endif
4290 	xfrm_policy_flush(net, XFRM_POLICY_TYPE_MAIN, false);
4291 }
4292 
4293 static void xfrm_policy_fini(struct net *net)
4294 {
4295 	struct xfrm_pol_inexact_bin *b, *t;
4296 	unsigned int sz;
4297 	int dir;
4298 
4299 	WARN_ON(!list_empty(&net->xfrm.policy_all));
4300 
4301 	for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
4302 		struct xfrm_policy_hash *htab;
4303 
4304 		htab = &net->xfrm.policy_bydst[dir];
4305 		sz = (htab->hmask + 1) * sizeof(struct hlist_head);
4306 		WARN_ON(!hlist_empty(rcu_dereference_protected(htab->table, true)));
4307 		xfrm_hash_free(rcu_dereference_protected(htab->table, true), sz);
4308 	}
4309 
4310 	sz = (net->xfrm.policy_idx_hmask + 1) * sizeof(struct hlist_head);
4311 	WARN_ON(!hlist_empty(net->xfrm.policy_byidx));
4312 	xfrm_hash_free(net->xfrm.policy_byidx, sz);
4313 
4314 	spin_lock_bh(&net->xfrm.xfrm_policy_lock);
4315 	list_for_each_entry_safe(b, t, &net->xfrm.inexact_bins, inexact_bins)
4316 		__xfrm_policy_inexact_prune_bin(b, true);
4317 	spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
4318 }
4319 
4320 static int __net_init xfrm_net_init(struct net *net)
4321 {
4322 	int rv;
4323 
4324 	/* Initialize the per-net locks here */
4325 	spin_lock_init(&net->xfrm.xfrm_state_lock);
4326 	spin_lock_init(&net->xfrm.xfrm_policy_lock);
4327 	seqcount_spinlock_init(&net->xfrm.xfrm_policy_hash_generation, &net->xfrm.xfrm_policy_lock);
4328 	mutex_init(&net->xfrm.xfrm_cfg_mutex);
4329 	net->xfrm.policy_default[XFRM_POLICY_IN] = XFRM_USERPOLICY_ACCEPT;
4330 	net->xfrm.policy_default[XFRM_POLICY_FWD] = XFRM_USERPOLICY_ACCEPT;
4331 	net->xfrm.policy_default[XFRM_POLICY_OUT] = XFRM_USERPOLICY_ACCEPT;
4332 
4333 	rv = xfrm_statistics_init(net);
4334 	if (rv < 0)
4335 		goto out_statistics;
4336 	rv = xfrm_state_init(net);
4337 	if (rv < 0)
4338 		goto out_state;
4339 	rv = xfrm_policy_init(net);
4340 	if (rv < 0)
4341 		goto out_policy;
4342 	rv = xfrm_sysctl_init(net);
4343 	if (rv < 0)
4344 		goto out_sysctl;
4345 
4346 	rv = xfrm_nat_keepalive_net_init(net);
4347 	if (rv < 0)
4348 		goto out_nat_keepalive;
4349 
4350 	return 0;
4351 
4352 out_nat_keepalive:
4353 	xfrm_sysctl_fini(net);
4354 out_sysctl:
4355 	xfrm_policy_fini(net);
4356 out_policy:
4357 	xfrm_state_fini(net);
4358 out_state:
4359 	xfrm_statistics_fini(net);
4360 out_statistics:
4361 	return rv;
4362 }
4363 
4364 static void __net_exit xfrm_net_exit(struct net *net)
4365 {
4366 	xfrm_nat_keepalive_net_fini(net);
4367 	xfrm_sysctl_fini(net);
4368 	xfrm_policy_fini(net);
4369 	xfrm_state_fini(net);
4370 	xfrm_statistics_fini(net);
4371 }
4372 
4373 static struct pernet_operations __net_initdata xfrm_net_ops = {
4374 	.init = xfrm_net_init,
4375 	.pre_exit = xfrm_net_pre_exit,
4376 	.exit = xfrm_net_exit,
4377 };
4378 
4379 static const struct flow_dissector_key xfrm_flow_dissector_keys[] = {
4380 	{
4381 		.key_id = FLOW_DISSECTOR_KEY_CONTROL,
4382 		.offset = offsetof(struct xfrm_flow_keys, control),
4383 	},
4384 	{
4385 		.key_id = FLOW_DISSECTOR_KEY_BASIC,
4386 		.offset = offsetof(struct xfrm_flow_keys, basic),
4387 	},
4388 	{
4389 		.key_id = FLOW_DISSECTOR_KEY_IPV4_ADDRS,
4390 		.offset = offsetof(struct xfrm_flow_keys, addrs.ipv4),
4391 	},
4392 	{
4393 		.key_id = FLOW_DISSECTOR_KEY_IPV6_ADDRS,
4394 		.offset = offsetof(struct xfrm_flow_keys, addrs.ipv6),
4395 	},
4396 	{
4397 		.key_id = FLOW_DISSECTOR_KEY_PORTS,
4398 		.offset = offsetof(struct xfrm_flow_keys, ports),
4399 	},
4400 	{
4401 		.key_id = FLOW_DISSECTOR_KEY_GRE_KEYID,
4402 		.offset = offsetof(struct xfrm_flow_keys, gre),
4403 	},
4404 	{
4405 		.key_id = FLOW_DISSECTOR_KEY_IP,
4406 		.offset = offsetof(struct xfrm_flow_keys, ip),
4407 	},
4408 	{
4409 		.key_id = FLOW_DISSECTOR_KEY_ICMP,
4410 		.offset = offsetof(struct xfrm_flow_keys, icmp),
4411 	},
4412 };
4413 
4414 void __init xfrm_init(void)
4415 {
4416 	skb_flow_dissector_init(&xfrm_session_dissector,
4417 				xfrm_flow_dissector_keys,
4418 				ARRAY_SIZE(xfrm_flow_dissector_keys));
4419 
4420 	register_pernet_subsys(&xfrm_net_ops);
4421 	xfrm_dev_init();
4422 	xfrm_input_init();
4423 
4424 #ifdef CONFIG_XFRM_ESPINTCP
4425 	espintcp_init();
4426 #endif
4427 
4428 	register_xfrm_state_bpf();
4429 	xfrm_nat_keepalive_init(AF_INET);
4430 }
4431 
4432 #ifdef CONFIG_AUDITSYSCALL
4433 static void xfrm_audit_common_policyinfo(struct xfrm_policy *xp,
4434 					 struct audit_buffer *audit_buf)
4435 {
4436 	struct xfrm_sec_ctx *ctx = xp->security;
4437 	struct xfrm_selector *sel = &xp->selector;
4438 
4439 	if (ctx)
4440 		audit_log_format(audit_buf, " sec_alg=%u sec_doi=%u sec_obj=%s",
4441 				 ctx->ctx_alg, ctx->ctx_doi, ctx->ctx_str);
4442 
4443 	switch (sel->family) {
4444 	case AF_INET:
4445 		audit_log_format(audit_buf, " src=%pI4", &sel->saddr.a4);
4446 		if (sel->prefixlen_s != 32)
4447 			audit_log_format(audit_buf, " src_prefixlen=%d",
4448 					 sel->prefixlen_s);
4449 		audit_log_format(audit_buf, " dst=%pI4", &sel->daddr.a4);
4450 		if (sel->prefixlen_d != 32)
4451 			audit_log_format(audit_buf, " dst_prefixlen=%d",
4452 					 sel->prefixlen_d);
4453 		break;
4454 	case AF_INET6:
4455 		audit_log_format(audit_buf, " src=%pI6", sel->saddr.a6);
4456 		if (sel->prefixlen_s != 128)
4457 			audit_log_format(audit_buf, " src_prefixlen=%d",
4458 					 sel->prefixlen_s);
4459 		audit_log_format(audit_buf, " dst=%pI6", sel->daddr.a6);
4460 		if (sel->prefixlen_d != 128)
4461 			audit_log_format(audit_buf, " dst_prefixlen=%d",
4462 					 sel->prefixlen_d);
4463 		break;
4464 	}
4465 }
4466 
4467 void xfrm_audit_policy_add(struct xfrm_policy *xp, int result, bool task_valid)
4468 {
4469 	struct audit_buffer *audit_buf;
4470 
4471 	audit_buf = xfrm_audit_start("SPD-add");
4472 	if (audit_buf == NULL)
4473 		return;
4474 	xfrm_audit_helper_usrinfo(task_valid, audit_buf);
4475 	audit_log_format(audit_buf, " res=%u", result);
4476 	xfrm_audit_common_policyinfo(xp, audit_buf);
4477 	audit_log_end(audit_buf);
4478 }
4479 EXPORT_SYMBOL_GPL(xfrm_audit_policy_add);
4480 
4481 void xfrm_audit_policy_delete(struct xfrm_policy *xp, int result,
4482 			      bool task_valid)
4483 {
4484 	struct audit_buffer *audit_buf;
4485 
4486 	audit_buf = xfrm_audit_start("SPD-delete");
4487 	if (audit_buf == NULL)
4488 		return;
4489 	xfrm_audit_helper_usrinfo(task_valid, audit_buf);
4490 	audit_log_format(audit_buf, " res=%u", result);
4491 	xfrm_audit_common_policyinfo(xp, audit_buf);
4492 	audit_log_end(audit_buf);
4493 }
4494 EXPORT_SYMBOL_GPL(xfrm_audit_policy_delete);
4495 #endif
4496 
4497 #ifdef CONFIG_XFRM_MIGRATE
4498 static struct xfrm_policy *xfrm_migrate_policy_find(const struct xfrm_selector *sel,
4499 						    u8 dir, u8 type, struct net *net, u32 if_id)
4500 {
4501 	struct xfrm_policy *pol;
4502 	struct flowi fl;
4503 
4504 	memset(&fl, 0, sizeof(fl));
4505 
4506 	fl.flowi_proto = sel->proto;
4507 
4508 	switch (sel->family) {
4509 	case AF_INET:
4510 		fl.u.ip4.saddr = sel->saddr.a4;
4511 		fl.u.ip4.daddr = sel->daddr.a4;
4512 		if (sel->proto == IPSEC_ULPROTO_ANY)
4513 			break;
4514 		fl.u.flowi4_oif = sel->ifindex;
4515 		fl.u.ip4.fl4_sport = sel->sport;
4516 		fl.u.ip4.fl4_dport = sel->dport;
4517 		break;
4518 	case AF_INET6:
4519 		fl.u.ip6.saddr = sel->saddr.in6;
4520 		fl.u.ip6.daddr = sel->daddr.in6;
4521 		if (sel->proto == IPSEC_ULPROTO_ANY)
4522 			break;
4523 		fl.u.flowi6_oif = sel->ifindex;
4524 		fl.u.ip6.fl4_sport = sel->sport;
4525 		fl.u.ip6.fl4_dport = sel->dport;
4526 		break;
4527 	default:
4528 		return ERR_PTR(-EAFNOSUPPORT);
4529 	}
4530 
4531 	rcu_read_lock();
4532 
4533 	pol = xfrm_policy_lookup_bytype(net, type, &fl, sel->family, dir, if_id);
4534 	if (IS_ERR_OR_NULL(pol))
4535 		goto out_unlock;
4536 out_unlock:
4537 	rcu_read_unlock();
4538 	return pol;
4539 }
4540 
4541 static int migrate_tmpl_match(const struct xfrm_migrate *m, const struct xfrm_tmpl *t)
4542 {
4543 	int match = 0;
4544 
4545 	if (t->mode == m->mode && t->id.proto == m->proto &&
4546 	    (m->old_reqid == 0 || t->reqid == m->old_reqid)) {
4547 		switch (t->mode) {
4548 		case XFRM_MODE_TUNNEL:
4549 		case XFRM_MODE_BEET:
4550 		case XFRM_MODE_IPTFS:
4551 			if (xfrm_addr_equal(&t->id.daddr, &m->old_daddr,
4552 					    m->old_family) &&
4553 			    xfrm_addr_equal(&t->saddr, &m->old_saddr,
4554 					    m->old_family)) {
4555 				match = 1;
4556 			}
4557 			break;
4558 		case XFRM_MODE_TRANSPORT:
4559 			/* in case of transport mode, template does not store
4560 			   any IP addresses, hence we just compare mode and
4561 			   protocol */
4562 			match = 1;
4563 			break;
4564 		default:
4565 			break;
4566 		}
4567 	}
4568 	return match;
4569 }
4570 
4571 /* update endpoint address(es) of template(s) */
4572 static int xfrm_policy_migrate(struct xfrm_policy *pol,
4573 			       struct xfrm_migrate *m, int num_migrate,
4574 			       struct netlink_ext_ack *extack)
4575 {
4576 	struct xfrm_migrate *mp;
4577 	int i, j, n = 0;
4578 
4579 	write_lock_bh(&pol->lock);
4580 	if (unlikely(pol->walk.dead)) {
4581 		/* target policy has been deleted */
4582 		NL_SET_ERR_MSG(extack, "Target policy not found");
4583 		write_unlock_bh(&pol->lock);
4584 		return -ENOENT;
4585 	}
4586 
4587 	for (i = 0; i < pol->xfrm_nr; i++) {
4588 		for (j = 0, mp = m; j < num_migrate; j++, mp++) {
4589 			if (!migrate_tmpl_match(mp, &pol->xfrm_vec[i]))
4590 				continue;
4591 			n++;
4592 			if (pol->xfrm_vec[i].mode != XFRM_MODE_TUNNEL &&
4593 			    pol->xfrm_vec[i].mode != XFRM_MODE_BEET &&
4594 			    pol->xfrm_vec[i].mode != XFRM_MODE_IPTFS)
4595 				continue;
4596 			/* update endpoints */
4597 			memcpy(&pol->xfrm_vec[i].id.daddr, &mp->new_daddr,
4598 			       sizeof(pol->xfrm_vec[i].id.daddr));
4599 			memcpy(&pol->xfrm_vec[i].saddr, &mp->new_saddr,
4600 			       sizeof(pol->xfrm_vec[i].saddr));
4601 			pol->xfrm_vec[i].encap_family = mp->new_family;
4602 			/* flush bundles */
4603 			atomic_inc(&pol->genid);
4604 		}
4605 	}
4606 
4607 	write_unlock_bh(&pol->lock);
4608 
4609 	if (!n)
4610 		return -ENODATA;
4611 
4612 	return 0;
4613 }
4614 
4615 static int xfrm_migrate_check(const struct xfrm_migrate *m, int num_migrate,
4616 			      struct netlink_ext_ack *extack)
4617 {
4618 	int i, j;
4619 
4620 	if (num_migrate < 1 || num_migrate > XFRM_MAX_DEPTH) {
4621 		NL_SET_ERR_MSG(extack, "Invalid number of SAs to migrate, must be 0 < num <= XFRM_MAX_DEPTH (6)");
4622 		return -EINVAL;
4623 	}
4624 
4625 	for (i = 0; i < num_migrate; i++) {
4626 		if (xfrm_addr_any(&m[i].new_daddr, m[i].new_family) ||
4627 		    xfrm_addr_any(&m[i].new_saddr, m[i].new_family)) {
4628 			NL_SET_ERR_MSG(extack, "Addresses in the MIGRATE attribute's list cannot be null");
4629 			return -EINVAL;
4630 		}
4631 
4632 		/* check if there is any duplicated entry */
4633 		for (j = i + 1; j < num_migrate; j++) {
4634 			if (!memcmp(&m[i].old_daddr, &m[j].old_daddr,
4635 				    sizeof(m[i].old_daddr)) &&
4636 			    !memcmp(&m[i].old_saddr, &m[j].old_saddr,
4637 				    sizeof(m[i].old_saddr)) &&
4638 			    m[i].proto == m[j].proto &&
4639 			    m[i].mode == m[j].mode &&
4640 			    m[i].old_reqid == m[j].old_reqid &&
4641 			    m[i].old_family == m[j].old_family) {
4642 				NL_SET_ERR_MSG(extack, "Entries in the MIGRATE attribute's list must be unique");
4643 				return -EINVAL;
4644 			}
4645 		}
4646 	}
4647 
4648 	return 0;
4649 }
4650 
4651 /*
4652  * Fill migrate fields that are invariant in XFRM_MSG_MIGRATE: inherited
4653  * from the existing SA unchanged. XFRM_MSG_MIGRATE_STATE can update these.
4654  */
4655 static void xfrm_migrate_copy_old(const struct xfrm_state *x,
4656 				  struct xfrm_migrate *mp)
4657 {
4658 	mp->msg_type               = XFRM_MSG_MIGRATE;
4659 	mp->smark                  = x->props.smark;
4660 	mp->new_reqid              = x->props.reqid;
4661 	mp->nat_keepalive_interval = x->nat_keepalive_interval;
4662 	mp->mapping_maxage         = x->mapping_maxage;
4663 	mp->new_mark               = &x->mark;
4664 }
4665 
4666 int xfrm_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
4667 		 struct xfrm_migrate *m, int num_migrate,
4668 		 struct xfrm_kmaddress *k, struct net *net,
4669 		 struct xfrm_encap_tmpl *encap, u32 if_id,
4670 		 struct netlink_ext_ack *extack, struct xfrm_user_offload *xuo)
4671 {
4672 	int i, err, nx_cur = 0, nx_new = 0;
4673 	struct xfrm_policy *pol = NULL;
4674 	struct xfrm_state *x, *xc;
4675 	struct xfrm_state *x_cur[XFRM_MAX_DEPTH];
4676 	struct xfrm_state *x_new[XFRM_MAX_DEPTH];
4677 	struct xfrm_migrate *mp;
4678 
4679 	/* Stage 0 - sanity checks */
4680 	err = xfrm_migrate_check(m, num_migrate, extack);
4681 	if (err < 0)
4682 		goto out;
4683 
4684 	if (dir >= XFRM_POLICY_MAX) {
4685 		NL_SET_ERR_MSG(extack, "Invalid policy direction");
4686 		err = -EINVAL;
4687 		goto out;
4688 	}
4689 
4690 	/* Stage 1 - find policy */
4691 	pol = xfrm_migrate_policy_find(sel, dir, type, net, if_id);
4692 	if (IS_ERR_OR_NULL(pol)) {
4693 		NL_SET_ERR_MSG(extack, "Target policy not found");
4694 		err = IS_ERR(pol) ? PTR_ERR(pol) : -ENOENT;
4695 		goto out;
4696 	}
4697 
4698 	/* Stage 2 - find and update state(s) */
4699 	for (i = 0, mp = m; i < num_migrate; i++, mp++) {
4700 		if ((x = xfrm_migrate_state_find(mp, net, if_id))) {
4701 			x_cur[nx_cur] = x;
4702 			nx_cur++;
4703 			mp->encap = encap;
4704 			mp->xuo = xuo;
4705 			xfrm_migrate_copy_old(x, mp);
4706 
4707 			xc = xfrm_state_migrate(x, mp, net, extack);
4708 			if (xc) {
4709 				x_new[nx_new] = xc;
4710 				nx_new++;
4711 			} else {
4712 				err = -ENODATA;
4713 				goto restore_state;
4714 			}
4715 		}
4716 	}
4717 
4718 	/* Stage 3 - update policy */
4719 	err = xfrm_policy_migrate(pol, m, num_migrate, extack);
4720 	if (err < 0)
4721 		goto restore_state;
4722 
4723 	/* Stage 4 - delete old state(s) */
4724 	if (nx_cur) {
4725 		xfrm_states_put(x_cur, nx_cur);
4726 		xfrm_states_delete(x_cur, nx_cur);
4727 	}
4728 
4729 	/* Stage 5 - announce */
4730 	km_migrate(sel, dir, type, m, num_migrate, k, net, encap);
4731 
4732 	xfrm_pol_put(pol);
4733 
4734 	return 0;
4735 out:
4736 	return err;
4737 
4738 restore_state:
4739 	if (pol)
4740 		xfrm_pol_put(pol);
4741 	if (nx_cur)
4742 		xfrm_states_put(x_cur, nx_cur);
4743 	if (nx_new)
4744 		xfrm_states_delete(x_new, nx_new);
4745 
4746 	return err;
4747 }
4748 EXPORT_SYMBOL(xfrm_migrate);
4749 #endif
4750