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