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