xref: /openbmc/linux/net/xfrm/xfrm_state.c (revision f519cd13)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * xfrm_state.c
4  *
5  * Changes:
6  *	Mitsuru KANDA @USAGI
7  * 	Kazunori MIYAZAWA @USAGI
8  * 	Kunihiro Ishiguro <kunihiro@ipinfusion.com>
9  * 		IPv6 support
10  * 	YOSHIFUJI Hideaki @USAGI
11  * 		Split up af-specific functions
12  *	Derek Atkins <derek@ihtfp.com>
13  *		Add UDP Encapsulation
14  *
15  */
16 
17 #include <linux/workqueue.h>
18 #include <net/xfrm.h>
19 #include <linux/pfkeyv2.h>
20 #include <linux/ipsec.h>
21 #include <linux/module.h>
22 #include <linux/cache.h>
23 #include <linux/audit.h>
24 #include <linux/uaccess.h>
25 #include <linux/ktime.h>
26 #include <linux/slab.h>
27 #include <linux/interrupt.h>
28 #include <linux/kernel.h>
29 
30 #include <crypto/aead.h>
31 
32 #include "xfrm_hash.h"
33 
34 #define xfrm_state_deref_prot(table, net) \
35 	rcu_dereference_protected((table), lockdep_is_held(&(net)->xfrm.xfrm_state_lock))
36 
37 static void xfrm_state_gc_task(struct work_struct *work);
38 
39 /* Each xfrm_state may be linked to two tables:
40 
41    1. Hash table by (spi,daddr,ah/esp) to find SA by SPI. (input,ctl)
42    2. Hash table by (daddr,family,reqid) to find what SAs exist for given
43       destination/tunnel endpoint. (output)
44  */
45 
46 static unsigned int xfrm_state_hashmax __read_mostly = 1 * 1024 * 1024;
47 static __read_mostly seqcount_t xfrm_state_hash_generation = SEQCNT_ZERO(xfrm_state_hash_generation);
48 static struct kmem_cache *xfrm_state_cache __ro_after_init;
49 
50 static DECLARE_WORK(xfrm_state_gc_work, xfrm_state_gc_task);
51 static HLIST_HEAD(xfrm_state_gc_list);
52 
53 static inline bool xfrm_state_hold_rcu(struct xfrm_state __rcu *x)
54 {
55 	return refcount_inc_not_zero(&x->refcnt);
56 }
57 
58 static inline unsigned int xfrm_dst_hash(struct net *net,
59 					 const xfrm_address_t *daddr,
60 					 const xfrm_address_t *saddr,
61 					 u32 reqid,
62 					 unsigned short family)
63 {
64 	return __xfrm_dst_hash(daddr, saddr, reqid, family, net->xfrm.state_hmask);
65 }
66 
67 static inline unsigned int xfrm_src_hash(struct net *net,
68 					 const xfrm_address_t *daddr,
69 					 const xfrm_address_t *saddr,
70 					 unsigned short family)
71 {
72 	return __xfrm_src_hash(daddr, saddr, family, net->xfrm.state_hmask);
73 }
74 
75 static inline unsigned int
76 xfrm_spi_hash(struct net *net, const xfrm_address_t *daddr,
77 	      __be32 spi, u8 proto, unsigned short family)
78 {
79 	return __xfrm_spi_hash(daddr, spi, proto, family, net->xfrm.state_hmask);
80 }
81 
82 static void xfrm_hash_transfer(struct hlist_head *list,
83 			       struct hlist_head *ndsttable,
84 			       struct hlist_head *nsrctable,
85 			       struct hlist_head *nspitable,
86 			       unsigned int nhashmask)
87 {
88 	struct hlist_node *tmp;
89 	struct xfrm_state *x;
90 
91 	hlist_for_each_entry_safe(x, tmp, list, bydst) {
92 		unsigned int h;
93 
94 		h = __xfrm_dst_hash(&x->id.daddr, &x->props.saddr,
95 				    x->props.reqid, x->props.family,
96 				    nhashmask);
97 		hlist_add_head_rcu(&x->bydst, ndsttable + h);
98 
99 		h = __xfrm_src_hash(&x->id.daddr, &x->props.saddr,
100 				    x->props.family,
101 				    nhashmask);
102 		hlist_add_head_rcu(&x->bysrc, nsrctable + h);
103 
104 		if (x->id.spi) {
105 			h = __xfrm_spi_hash(&x->id.daddr, x->id.spi,
106 					    x->id.proto, x->props.family,
107 					    nhashmask);
108 			hlist_add_head_rcu(&x->byspi, nspitable + h);
109 		}
110 	}
111 }
112 
113 static unsigned long xfrm_hash_new_size(unsigned int state_hmask)
114 {
115 	return ((state_hmask + 1) << 1) * sizeof(struct hlist_head);
116 }
117 
118 static void xfrm_hash_resize(struct work_struct *work)
119 {
120 	struct net *net = container_of(work, struct net, xfrm.state_hash_work);
121 	struct hlist_head *ndst, *nsrc, *nspi, *odst, *osrc, *ospi;
122 	unsigned long nsize, osize;
123 	unsigned int nhashmask, ohashmask;
124 	int i;
125 
126 	nsize = xfrm_hash_new_size(net->xfrm.state_hmask);
127 	ndst = xfrm_hash_alloc(nsize);
128 	if (!ndst)
129 		return;
130 	nsrc = xfrm_hash_alloc(nsize);
131 	if (!nsrc) {
132 		xfrm_hash_free(ndst, nsize);
133 		return;
134 	}
135 	nspi = xfrm_hash_alloc(nsize);
136 	if (!nspi) {
137 		xfrm_hash_free(ndst, nsize);
138 		xfrm_hash_free(nsrc, nsize);
139 		return;
140 	}
141 
142 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
143 	write_seqcount_begin(&xfrm_state_hash_generation);
144 
145 	nhashmask = (nsize / sizeof(struct hlist_head)) - 1U;
146 	odst = xfrm_state_deref_prot(net->xfrm.state_bydst, net);
147 	for (i = net->xfrm.state_hmask; i >= 0; i--)
148 		xfrm_hash_transfer(odst + i, ndst, nsrc, nspi, nhashmask);
149 
150 	osrc = xfrm_state_deref_prot(net->xfrm.state_bysrc, net);
151 	ospi = xfrm_state_deref_prot(net->xfrm.state_byspi, net);
152 	ohashmask = net->xfrm.state_hmask;
153 
154 	rcu_assign_pointer(net->xfrm.state_bydst, ndst);
155 	rcu_assign_pointer(net->xfrm.state_bysrc, nsrc);
156 	rcu_assign_pointer(net->xfrm.state_byspi, nspi);
157 	net->xfrm.state_hmask = nhashmask;
158 
159 	write_seqcount_end(&xfrm_state_hash_generation);
160 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
161 
162 	osize = (ohashmask + 1) * sizeof(struct hlist_head);
163 
164 	synchronize_rcu();
165 
166 	xfrm_hash_free(odst, osize);
167 	xfrm_hash_free(osrc, osize);
168 	xfrm_hash_free(ospi, osize);
169 }
170 
171 static DEFINE_SPINLOCK(xfrm_state_afinfo_lock);
172 static struct xfrm_state_afinfo __rcu *xfrm_state_afinfo[NPROTO];
173 
174 static DEFINE_SPINLOCK(xfrm_state_gc_lock);
175 
176 int __xfrm_state_delete(struct xfrm_state *x);
177 
178 int km_query(struct xfrm_state *x, struct xfrm_tmpl *t, struct xfrm_policy *pol);
179 static bool km_is_alive(const struct km_event *c);
180 void km_state_expired(struct xfrm_state *x, int hard, u32 portid);
181 
182 int xfrm_register_type(const struct xfrm_type *type, unsigned short family)
183 {
184 	struct xfrm_state_afinfo *afinfo = xfrm_state_get_afinfo(family);
185 	int err = 0;
186 
187 	if (!afinfo)
188 		return -EAFNOSUPPORT;
189 
190 #define X(afi, T, name) do {			\
191 		WARN_ON((afi)->type_ ## name);	\
192 		(afi)->type_ ## name = (T);	\
193 	} while (0)
194 
195 	switch (type->proto) {
196 	case IPPROTO_COMP:
197 		X(afinfo, type, comp);
198 		break;
199 	case IPPROTO_AH:
200 		X(afinfo, type, ah);
201 		break;
202 	case IPPROTO_ESP:
203 		X(afinfo, type, esp);
204 		break;
205 	case IPPROTO_IPIP:
206 		X(afinfo, type, ipip);
207 		break;
208 	case IPPROTO_DSTOPTS:
209 		X(afinfo, type, dstopts);
210 		break;
211 	case IPPROTO_ROUTING:
212 		X(afinfo, type, routing);
213 		break;
214 	case IPPROTO_IPV6:
215 		X(afinfo, type, ipip6);
216 		break;
217 	default:
218 		WARN_ON(1);
219 		err = -EPROTONOSUPPORT;
220 		break;
221 	}
222 #undef X
223 	rcu_read_unlock();
224 	return err;
225 }
226 EXPORT_SYMBOL(xfrm_register_type);
227 
228 void xfrm_unregister_type(const struct xfrm_type *type, unsigned short family)
229 {
230 	struct xfrm_state_afinfo *afinfo = xfrm_state_get_afinfo(family);
231 
232 	if (unlikely(afinfo == NULL))
233 		return;
234 
235 #define X(afi, T, name) do {				\
236 		WARN_ON((afi)->type_ ## name != (T));	\
237 		(afi)->type_ ## name = NULL;		\
238 	} while (0)
239 
240 	switch (type->proto) {
241 	case IPPROTO_COMP:
242 		X(afinfo, type, comp);
243 		break;
244 	case IPPROTO_AH:
245 		X(afinfo, type, ah);
246 		break;
247 	case IPPROTO_ESP:
248 		X(afinfo, type, esp);
249 		break;
250 	case IPPROTO_IPIP:
251 		X(afinfo, type, ipip);
252 		break;
253 	case IPPROTO_DSTOPTS:
254 		X(afinfo, type, dstopts);
255 		break;
256 	case IPPROTO_ROUTING:
257 		X(afinfo, type, routing);
258 		break;
259 	case IPPROTO_IPV6:
260 		X(afinfo, type, ipip6);
261 		break;
262 	default:
263 		WARN_ON(1);
264 		break;
265 	}
266 #undef X
267 	rcu_read_unlock();
268 }
269 EXPORT_SYMBOL(xfrm_unregister_type);
270 
271 static const struct xfrm_type *xfrm_get_type(u8 proto, unsigned short family)
272 {
273 	const struct xfrm_type *type = NULL;
274 	struct xfrm_state_afinfo *afinfo;
275 	int modload_attempted = 0;
276 
277 retry:
278 	afinfo = xfrm_state_get_afinfo(family);
279 	if (unlikely(afinfo == NULL))
280 		return NULL;
281 
282 	switch (proto) {
283 	case IPPROTO_COMP:
284 		type = afinfo->type_comp;
285 		break;
286 	case IPPROTO_AH:
287 		type = afinfo->type_ah;
288 		break;
289 	case IPPROTO_ESP:
290 		type = afinfo->type_esp;
291 		break;
292 	case IPPROTO_IPIP:
293 		type = afinfo->type_ipip;
294 		break;
295 	case IPPROTO_DSTOPTS:
296 		type = afinfo->type_dstopts;
297 		break;
298 	case IPPROTO_ROUTING:
299 		type = afinfo->type_routing;
300 		break;
301 	case IPPROTO_IPV6:
302 		type = afinfo->type_ipip6;
303 		break;
304 	default:
305 		break;
306 	}
307 
308 	if (unlikely(type && !try_module_get(type->owner)))
309 		type = NULL;
310 
311 	rcu_read_unlock();
312 
313 	if (!type && !modload_attempted) {
314 		request_module("xfrm-type-%d-%d", family, proto);
315 		modload_attempted = 1;
316 		goto retry;
317 	}
318 
319 	return type;
320 }
321 
322 static void xfrm_put_type(const struct xfrm_type *type)
323 {
324 	module_put(type->owner);
325 }
326 
327 int xfrm_register_type_offload(const struct xfrm_type_offload *type,
328 			       unsigned short family)
329 {
330 	struct xfrm_state_afinfo *afinfo = xfrm_state_get_afinfo(family);
331 	int err = 0;
332 
333 	if (unlikely(afinfo == NULL))
334 		return -EAFNOSUPPORT;
335 
336 	switch (type->proto) {
337 	case IPPROTO_ESP:
338 		WARN_ON(afinfo->type_offload_esp);
339 		afinfo->type_offload_esp = type;
340 		break;
341 	default:
342 		WARN_ON(1);
343 		err = -EPROTONOSUPPORT;
344 		break;
345 	}
346 
347 	rcu_read_unlock();
348 	return err;
349 }
350 EXPORT_SYMBOL(xfrm_register_type_offload);
351 
352 void xfrm_unregister_type_offload(const struct xfrm_type_offload *type,
353 				  unsigned short family)
354 {
355 	struct xfrm_state_afinfo *afinfo = xfrm_state_get_afinfo(family);
356 
357 	if (unlikely(afinfo == NULL))
358 		return;
359 
360 	switch (type->proto) {
361 	case IPPROTO_ESP:
362 		WARN_ON(afinfo->type_offload_esp != type);
363 		afinfo->type_offload_esp = NULL;
364 		break;
365 	default:
366 		WARN_ON(1);
367 		break;
368 	}
369 	rcu_read_unlock();
370 }
371 EXPORT_SYMBOL(xfrm_unregister_type_offload);
372 
373 static const struct xfrm_type_offload *
374 xfrm_get_type_offload(u8 proto, unsigned short family, bool try_load)
375 {
376 	const struct xfrm_type_offload *type = NULL;
377 	struct xfrm_state_afinfo *afinfo;
378 
379 retry:
380 	afinfo = xfrm_state_get_afinfo(family);
381 	if (unlikely(afinfo == NULL))
382 		return NULL;
383 
384 	switch (proto) {
385 	case IPPROTO_ESP:
386 		type = afinfo->type_offload_esp;
387 		break;
388 	default:
389 		break;
390 	}
391 
392 	if ((type && !try_module_get(type->owner)))
393 		type = NULL;
394 
395 	rcu_read_unlock();
396 
397 	if (!type && try_load) {
398 		request_module("xfrm-offload-%d-%d", family, proto);
399 		try_load = false;
400 		goto retry;
401 	}
402 
403 	return type;
404 }
405 
406 static void xfrm_put_type_offload(const struct xfrm_type_offload *type)
407 {
408 	module_put(type->owner);
409 }
410 
411 static const struct xfrm_mode xfrm4_mode_map[XFRM_MODE_MAX] = {
412 	[XFRM_MODE_BEET] = {
413 		.encap = XFRM_MODE_BEET,
414 		.flags = XFRM_MODE_FLAG_TUNNEL,
415 		.family = AF_INET,
416 	},
417 	[XFRM_MODE_TRANSPORT] = {
418 		.encap = XFRM_MODE_TRANSPORT,
419 		.family = AF_INET,
420 	},
421 	[XFRM_MODE_TUNNEL] = {
422 		.encap = XFRM_MODE_TUNNEL,
423 		.flags = XFRM_MODE_FLAG_TUNNEL,
424 		.family = AF_INET,
425 	},
426 };
427 
428 static const struct xfrm_mode xfrm6_mode_map[XFRM_MODE_MAX] = {
429 	[XFRM_MODE_BEET] = {
430 		.encap = XFRM_MODE_BEET,
431 		.flags = XFRM_MODE_FLAG_TUNNEL,
432 		.family = AF_INET6,
433 	},
434 	[XFRM_MODE_ROUTEOPTIMIZATION] = {
435 		.encap = XFRM_MODE_ROUTEOPTIMIZATION,
436 		.family = AF_INET6,
437 	},
438 	[XFRM_MODE_TRANSPORT] = {
439 		.encap = XFRM_MODE_TRANSPORT,
440 		.family = AF_INET6,
441 	},
442 	[XFRM_MODE_TUNNEL] = {
443 		.encap = XFRM_MODE_TUNNEL,
444 		.flags = XFRM_MODE_FLAG_TUNNEL,
445 		.family = AF_INET6,
446 	},
447 };
448 
449 static const struct xfrm_mode *xfrm_get_mode(unsigned int encap, int family)
450 {
451 	const struct xfrm_mode *mode;
452 
453 	if (unlikely(encap >= XFRM_MODE_MAX))
454 		return NULL;
455 
456 	switch (family) {
457 	case AF_INET:
458 		mode = &xfrm4_mode_map[encap];
459 		if (mode->family == family)
460 			return mode;
461 		break;
462 	case AF_INET6:
463 		mode = &xfrm6_mode_map[encap];
464 		if (mode->family == family)
465 			return mode;
466 		break;
467 	default:
468 		break;
469 	}
470 
471 	return NULL;
472 }
473 
474 void xfrm_state_free(struct xfrm_state *x)
475 {
476 	kmem_cache_free(xfrm_state_cache, x);
477 }
478 EXPORT_SYMBOL(xfrm_state_free);
479 
480 static void ___xfrm_state_destroy(struct xfrm_state *x)
481 {
482 	hrtimer_cancel(&x->mtimer);
483 	del_timer_sync(&x->rtimer);
484 	kfree(x->aead);
485 	kfree(x->aalg);
486 	kfree(x->ealg);
487 	kfree(x->calg);
488 	kfree(x->encap);
489 	kfree(x->coaddr);
490 	kfree(x->replay_esn);
491 	kfree(x->preplay_esn);
492 	if (x->type_offload)
493 		xfrm_put_type_offload(x->type_offload);
494 	if (x->type) {
495 		x->type->destructor(x);
496 		xfrm_put_type(x->type);
497 	}
498 	if (x->xfrag.page)
499 		put_page(x->xfrag.page);
500 	xfrm_dev_state_free(x);
501 	security_xfrm_state_free(x);
502 	xfrm_state_free(x);
503 }
504 
505 static void xfrm_state_gc_task(struct work_struct *work)
506 {
507 	struct xfrm_state *x;
508 	struct hlist_node *tmp;
509 	struct hlist_head gc_list;
510 
511 	spin_lock_bh(&xfrm_state_gc_lock);
512 	hlist_move_list(&xfrm_state_gc_list, &gc_list);
513 	spin_unlock_bh(&xfrm_state_gc_lock);
514 
515 	synchronize_rcu();
516 
517 	hlist_for_each_entry_safe(x, tmp, &gc_list, gclist)
518 		___xfrm_state_destroy(x);
519 }
520 
521 static enum hrtimer_restart xfrm_timer_handler(struct hrtimer *me)
522 {
523 	struct xfrm_state *x = container_of(me, struct xfrm_state, mtimer);
524 	enum hrtimer_restart ret = HRTIMER_NORESTART;
525 	time64_t now = ktime_get_real_seconds();
526 	time64_t next = TIME64_MAX;
527 	int warn = 0;
528 	int err = 0;
529 
530 	spin_lock(&x->lock);
531 	if (x->km.state == XFRM_STATE_DEAD)
532 		goto out;
533 	if (x->km.state == XFRM_STATE_EXPIRED)
534 		goto expired;
535 	if (x->lft.hard_add_expires_seconds) {
536 		long tmo = x->lft.hard_add_expires_seconds +
537 			x->curlft.add_time - now;
538 		if (tmo <= 0) {
539 			if (x->xflags & XFRM_SOFT_EXPIRE) {
540 				/* enter hard expire without soft expire first?!
541 				 * setting a new date could trigger this.
542 				 * workaround: fix x->curflt.add_time by below:
543 				 */
544 				x->curlft.add_time = now - x->saved_tmo - 1;
545 				tmo = x->lft.hard_add_expires_seconds - x->saved_tmo;
546 			} else
547 				goto expired;
548 		}
549 		if (tmo < next)
550 			next = tmo;
551 	}
552 	if (x->lft.hard_use_expires_seconds) {
553 		long tmo = x->lft.hard_use_expires_seconds +
554 			(x->curlft.use_time ? : now) - now;
555 		if (tmo <= 0)
556 			goto expired;
557 		if (tmo < next)
558 			next = tmo;
559 	}
560 	if (x->km.dying)
561 		goto resched;
562 	if (x->lft.soft_add_expires_seconds) {
563 		long tmo = x->lft.soft_add_expires_seconds +
564 			x->curlft.add_time - now;
565 		if (tmo <= 0) {
566 			warn = 1;
567 			x->xflags &= ~XFRM_SOFT_EXPIRE;
568 		} else if (tmo < next) {
569 			next = tmo;
570 			x->xflags |= XFRM_SOFT_EXPIRE;
571 			x->saved_tmo = tmo;
572 		}
573 	}
574 	if (x->lft.soft_use_expires_seconds) {
575 		long tmo = x->lft.soft_use_expires_seconds +
576 			(x->curlft.use_time ? : now) - now;
577 		if (tmo <= 0)
578 			warn = 1;
579 		else if (tmo < next)
580 			next = tmo;
581 	}
582 
583 	x->km.dying = warn;
584 	if (warn)
585 		km_state_expired(x, 0, 0);
586 resched:
587 	if (next != TIME64_MAX) {
588 		hrtimer_forward_now(&x->mtimer, ktime_set(next, 0));
589 		ret = HRTIMER_RESTART;
590 	}
591 
592 	goto out;
593 
594 expired:
595 	if (x->km.state == XFRM_STATE_ACQ && x->id.spi == 0)
596 		x->km.state = XFRM_STATE_EXPIRED;
597 
598 	err = __xfrm_state_delete(x);
599 	if (!err)
600 		km_state_expired(x, 1, 0);
601 
602 	xfrm_audit_state_delete(x, err ? 0 : 1, true);
603 
604 out:
605 	spin_unlock(&x->lock);
606 	return ret;
607 }
608 
609 static void xfrm_replay_timer_handler(struct timer_list *t);
610 
611 struct xfrm_state *xfrm_state_alloc(struct net *net)
612 {
613 	struct xfrm_state *x;
614 
615 	x = kmem_cache_alloc(xfrm_state_cache, GFP_ATOMIC | __GFP_ZERO);
616 
617 	if (x) {
618 		write_pnet(&x->xs_net, net);
619 		refcount_set(&x->refcnt, 1);
620 		atomic_set(&x->tunnel_users, 0);
621 		INIT_LIST_HEAD(&x->km.all);
622 		INIT_HLIST_NODE(&x->bydst);
623 		INIT_HLIST_NODE(&x->bysrc);
624 		INIT_HLIST_NODE(&x->byspi);
625 		hrtimer_init(&x->mtimer, CLOCK_BOOTTIME, HRTIMER_MODE_ABS_SOFT);
626 		x->mtimer.function = xfrm_timer_handler;
627 		timer_setup(&x->rtimer, xfrm_replay_timer_handler, 0);
628 		x->curlft.add_time = ktime_get_real_seconds();
629 		x->lft.soft_byte_limit = XFRM_INF;
630 		x->lft.soft_packet_limit = XFRM_INF;
631 		x->lft.hard_byte_limit = XFRM_INF;
632 		x->lft.hard_packet_limit = XFRM_INF;
633 		x->replay_maxage = 0;
634 		x->replay_maxdiff = 0;
635 		spin_lock_init(&x->lock);
636 	}
637 	return x;
638 }
639 EXPORT_SYMBOL(xfrm_state_alloc);
640 
641 void __xfrm_state_destroy(struct xfrm_state *x, bool sync)
642 {
643 	WARN_ON(x->km.state != XFRM_STATE_DEAD);
644 
645 	if (sync) {
646 		synchronize_rcu();
647 		___xfrm_state_destroy(x);
648 	} else {
649 		spin_lock_bh(&xfrm_state_gc_lock);
650 		hlist_add_head(&x->gclist, &xfrm_state_gc_list);
651 		spin_unlock_bh(&xfrm_state_gc_lock);
652 		schedule_work(&xfrm_state_gc_work);
653 	}
654 }
655 EXPORT_SYMBOL(__xfrm_state_destroy);
656 
657 int __xfrm_state_delete(struct xfrm_state *x)
658 {
659 	struct net *net = xs_net(x);
660 	int err = -ESRCH;
661 
662 	if (x->km.state != XFRM_STATE_DEAD) {
663 		x->km.state = XFRM_STATE_DEAD;
664 		spin_lock(&net->xfrm.xfrm_state_lock);
665 		list_del(&x->km.all);
666 		hlist_del_rcu(&x->bydst);
667 		hlist_del_rcu(&x->bysrc);
668 		if (x->id.spi)
669 			hlist_del_rcu(&x->byspi);
670 		net->xfrm.state_num--;
671 		spin_unlock(&net->xfrm.xfrm_state_lock);
672 
673 		xfrm_dev_state_delete(x);
674 
675 		/* All xfrm_state objects are created by xfrm_state_alloc.
676 		 * The xfrm_state_alloc call gives a reference, and that
677 		 * is what we are dropping here.
678 		 */
679 		xfrm_state_put(x);
680 		err = 0;
681 	}
682 
683 	return err;
684 }
685 EXPORT_SYMBOL(__xfrm_state_delete);
686 
687 int xfrm_state_delete(struct xfrm_state *x)
688 {
689 	int err;
690 
691 	spin_lock_bh(&x->lock);
692 	err = __xfrm_state_delete(x);
693 	spin_unlock_bh(&x->lock);
694 
695 	return err;
696 }
697 EXPORT_SYMBOL(xfrm_state_delete);
698 
699 #ifdef CONFIG_SECURITY_NETWORK_XFRM
700 static inline int
701 xfrm_state_flush_secctx_check(struct net *net, u8 proto, bool task_valid)
702 {
703 	int i, err = 0;
704 
705 	for (i = 0; i <= net->xfrm.state_hmask; i++) {
706 		struct xfrm_state *x;
707 
708 		hlist_for_each_entry(x, net->xfrm.state_bydst+i, bydst) {
709 			if (xfrm_id_proto_match(x->id.proto, proto) &&
710 			   (err = security_xfrm_state_delete(x)) != 0) {
711 				xfrm_audit_state_delete(x, 0, task_valid);
712 				return err;
713 			}
714 		}
715 	}
716 
717 	return err;
718 }
719 
720 static inline int
721 xfrm_dev_state_flush_secctx_check(struct net *net, struct net_device *dev, bool task_valid)
722 {
723 	int i, err = 0;
724 
725 	for (i = 0; i <= net->xfrm.state_hmask; i++) {
726 		struct xfrm_state *x;
727 		struct xfrm_state_offload *xso;
728 
729 		hlist_for_each_entry(x, net->xfrm.state_bydst+i, bydst) {
730 			xso = &x->xso;
731 
732 			if (xso->dev == dev &&
733 			   (err = security_xfrm_state_delete(x)) != 0) {
734 				xfrm_audit_state_delete(x, 0, task_valid);
735 				return err;
736 			}
737 		}
738 	}
739 
740 	return err;
741 }
742 #else
743 static inline int
744 xfrm_state_flush_secctx_check(struct net *net, u8 proto, bool task_valid)
745 {
746 	return 0;
747 }
748 
749 static inline int
750 xfrm_dev_state_flush_secctx_check(struct net *net, struct net_device *dev, bool task_valid)
751 {
752 	return 0;
753 }
754 #endif
755 
756 int xfrm_state_flush(struct net *net, u8 proto, bool task_valid, bool sync)
757 {
758 	int i, err = 0, cnt = 0;
759 
760 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
761 	err = xfrm_state_flush_secctx_check(net, proto, task_valid);
762 	if (err)
763 		goto out;
764 
765 	err = -ESRCH;
766 	for (i = 0; i <= net->xfrm.state_hmask; i++) {
767 		struct xfrm_state *x;
768 restart:
769 		hlist_for_each_entry(x, net->xfrm.state_bydst+i, bydst) {
770 			if (!xfrm_state_kern(x) &&
771 			    xfrm_id_proto_match(x->id.proto, proto)) {
772 				xfrm_state_hold(x);
773 				spin_unlock_bh(&net->xfrm.xfrm_state_lock);
774 
775 				err = xfrm_state_delete(x);
776 				xfrm_audit_state_delete(x, err ? 0 : 1,
777 							task_valid);
778 				if (sync)
779 					xfrm_state_put_sync(x);
780 				else
781 					xfrm_state_put(x);
782 				if (!err)
783 					cnt++;
784 
785 				spin_lock_bh(&net->xfrm.xfrm_state_lock);
786 				goto restart;
787 			}
788 		}
789 	}
790 out:
791 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
792 	if (cnt)
793 		err = 0;
794 
795 	return err;
796 }
797 EXPORT_SYMBOL(xfrm_state_flush);
798 
799 int xfrm_dev_state_flush(struct net *net, struct net_device *dev, bool task_valid)
800 {
801 	int i, err = 0, cnt = 0;
802 
803 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
804 	err = xfrm_dev_state_flush_secctx_check(net, dev, task_valid);
805 	if (err)
806 		goto out;
807 
808 	err = -ESRCH;
809 	for (i = 0; i <= net->xfrm.state_hmask; i++) {
810 		struct xfrm_state *x;
811 		struct xfrm_state_offload *xso;
812 restart:
813 		hlist_for_each_entry(x, net->xfrm.state_bydst+i, bydst) {
814 			xso = &x->xso;
815 
816 			if (!xfrm_state_kern(x) && xso->dev == dev) {
817 				xfrm_state_hold(x);
818 				spin_unlock_bh(&net->xfrm.xfrm_state_lock);
819 
820 				err = xfrm_state_delete(x);
821 				xfrm_audit_state_delete(x, err ? 0 : 1,
822 							task_valid);
823 				xfrm_state_put(x);
824 				if (!err)
825 					cnt++;
826 
827 				spin_lock_bh(&net->xfrm.xfrm_state_lock);
828 				goto restart;
829 			}
830 		}
831 	}
832 	if (cnt)
833 		err = 0;
834 
835 out:
836 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
837 	return err;
838 }
839 EXPORT_SYMBOL(xfrm_dev_state_flush);
840 
841 void xfrm_sad_getinfo(struct net *net, struct xfrmk_sadinfo *si)
842 {
843 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
844 	si->sadcnt = net->xfrm.state_num;
845 	si->sadhcnt = net->xfrm.state_hmask + 1;
846 	si->sadhmcnt = xfrm_state_hashmax;
847 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
848 }
849 EXPORT_SYMBOL(xfrm_sad_getinfo);
850 
851 static void
852 __xfrm4_init_tempsel(struct xfrm_selector *sel, const struct flowi *fl)
853 {
854 	const struct flowi4 *fl4 = &fl->u.ip4;
855 
856 	sel->daddr.a4 = fl4->daddr;
857 	sel->saddr.a4 = fl4->saddr;
858 	sel->dport = xfrm_flowi_dport(fl, &fl4->uli);
859 	sel->dport_mask = htons(0xffff);
860 	sel->sport = xfrm_flowi_sport(fl, &fl4->uli);
861 	sel->sport_mask = htons(0xffff);
862 	sel->family = AF_INET;
863 	sel->prefixlen_d = 32;
864 	sel->prefixlen_s = 32;
865 	sel->proto = fl4->flowi4_proto;
866 	sel->ifindex = fl4->flowi4_oif;
867 }
868 
869 static void
870 __xfrm6_init_tempsel(struct xfrm_selector *sel, const struct flowi *fl)
871 {
872 	const struct flowi6 *fl6 = &fl->u.ip6;
873 
874 	/* Initialize temporary selector matching only to current session. */
875 	*(struct in6_addr *)&sel->daddr = fl6->daddr;
876 	*(struct in6_addr *)&sel->saddr = fl6->saddr;
877 	sel->dport = xfrm_flowi_dport(fl, &fl6->uli);
878 	sel->dport_mask = htons(0xffff);
879 	sel->sport = xfrm_flowi_sport(fl, &fl6->uli);
880 	sel->sport_mask = htons(0xffff);
881 	sel->family = AF_INET6;
882 	sel->prefixlen_d = 128;
883 	sel->prefixlen_s = 128;
884 	sel->proto = fl6->flowi6_proto;
885 	sel->ifindex = fl6->flowi6_oif;
886 }
887 
888 static void
889 xfrm_init_tempstate(struct xfrm_state *x, const struct flowi *fl,
890 		    const struct xfrm_tmpl *tmpl,
891 		    const xfrm_address_t *daddr, const xfrm_address_t *saddr,
892 		    unsigned short family)
893 {
894 	switch (family) {
895 	case AF_INET:
896 		__xfrm4_init_tempsel(&x->sel, fl);
897 		break;
898 	case AF_INET6:
899 		__xfrm6_init_tempsel(&x->sel, fl);
900 		break;
901 	}
902 
903 	x->id = tmpl->id;
904 
905 	switch (tmpl->encap_family) {
906 	case AF_INET:
907 		if (x->id.daddr.a4 == 0)
908 			x->id.daddr.a4 = daddr->a4;
909 		x->props.saddr = tmpl->saddr;
910 		if (x->props.saddr.a4 == 0)
911 			x->props.saddr.a4 = saddr->a4;
912 		break;
913 	case AF_INET6:
914 		if (ipv6_addr_any((struct in6_addr *)&x->id.daddr))
915 			memcpy(&x->id.daddr, daddr, sizeof(x->sel.daddr));
916 		memcpy(&x->props.saddr, &tmpl->saddr, sizeof(x->props.saddr));
917 		if (ipv6_addr_any((struct in6_addr *)&x->props.saddr))
918 			memcpy(&x->props.saddr, saddr, sizeof(x->props.saddr));
919 		break;
920 	}
921 
922 	x->props.mode = tmpl->mode;
923 	x->props.reqid = tmpl->reqid;
924 	x->props.family = tmpl->encap_family;
925 }
926 
927 static struct xfrm_state *__xfrm_state_lookup(struct net *net, u32 mark,
928 					      const xfrm_address_t *daddr,
929 					      __be32 spi, u8 proto,
930 					      unsigned short family)
931 {
932 	unsigned int h = xfrm_spi_hash(net, daddr, spi, proto, family);
933 	struct xfrm_state *x;
934 
935 	hlist_for_each_entry_rcu(x, net->xfrm.state_byspi + h, byspi) {
936 		if (x->props.family != family ||
937 		    x->id.spi       != spi ||
938 		    x->id.proto     != proto ||
939 		    !xfrm_addr_equal(&x->id.daddr, daddr, family))
940 			continue;
941 
942 		if ((mark & x->mark.m) != x->mark.v)
943 			continue;
944 		if (!xfrm_state_hold_rcu(x))
945 			continue;
946 		return x;
947 	}
948 
949 	return NULL;
950 }
951 
952 static struct xfrm_state *__xfrm_state_lookup_byaddr(struct net *net, u32 mark,
953 						     const xfrm_address_t *daddr,
954 						     const xfrm_address_t *saddr,
955 						     u8 proto, unsigned short family)
956 {
957 	unsigned int h = xfrm_src_hash(net, daddr, saddr, family);
958 	struct xfrm_state *x;
959 
960 	hlist_for_each_entry_rcu(x, net->xfrm.state_bysrc + h, bysrc) {
961 		if (x->props.family != family ||
962 		    x->id.proto     != proto ||
963 		    !xfrm_addr_equal(&x->id.daddr, daddr, family) ||
964 		    !xfrm_addr_equal(&x->props.saddr, saddr, family))
965 			continue;
966 
967 		if ((mark & x->mark.m) != x->mark.v)
968 			continue;
969 		if (!xfrm_state_hold_rcu(x))
970 			continue;
971 		return x;
972 	}
973 
974 	return NULL;
975 }
976 
977 static inline struct xfrm_state *
978 __xfrm_state_locate(struct xfrm_state *x, int use_spi, int family)
979 {
980 	struct net *net = xs_net(x);
981 	u32 mark = x->mark.v & x->mark.m;
982 
983 	if (use_spi)
984 		return __xfrm_state_lookup(net, mark, &x->id.daddr,
985 					   x->id.spi, x->id.proto, family);
986 	else
987 		return __xfrm_state_lookup_byaddr(net, mark,
988 						  &x->id.daddr,
989 						  &x->props.saddr,
990 						  x->id.proto, family);
991 }
992 
993 static void xfrm_hash_grow_check(struct net *net, int have_hash_collision)
994 {
995 	if (have_hash_collision &&
996 	    (net->xfrm.state_hmask + 1) < xfrm_state_hashmax &&
997 	    net->xfrm.state_num > net->xfrm.state_hmask)
998 		schedule_work(&net->xfrm.state_hash_work);
999 }
1000 
1001 static void xfrm_state_look_at(struct xfrm_policy *pol, struct xfrm_state *x,
1002 			       const struct flowi *fl, unsigned short family,
1003 			       struct xfrm_state **best, int *acq_in_progress,
1004 			       int *error)
1005 {
1006 	/* Resolution logic:
1007 	 * 1. There is a valid state with matching selector. Done.
1008 	 * 2. Valid state with inappropriate selector. Skip.
1009 	 *
1010 	 * Entering area of "sysdeps".
1011 	 *
1012 	 * 3. If state is not valid, selector is temporary, it selects
1013 	 *    only session which triggered previous resolution. Key
1014 	 *    manager will do something to install a state with proper
1015 	 *    selector.
1016 	 */
1017 	if (x->km.state == XFRM_STATE_VALID) {
1018 		if ((x->sel.family &&
1019 		     !xfrm_selector_match(&x->sel, fl, x->sel.family)) ||
1020 		    !security_xfrm_state_pol_flow_match(x, pol, fl))
1021 			return;
1022 
1023 		if (!*best ||
1024 		    (*best)->km.dying > x->km.dying ||
1025 		    ((*best)->km.dying == x->km.dying &&
1026 		     (*best)->curlft.add_time < x->curlft.add_time))
1027 			*best = x;
1028 	} else if (x->km.state == XFRM_STATE_ACQ) {
1029 		*acq_in_progress = 1;
1030 	} else if (x->km.state == XFRM_STATE_ERROR ||
1031 		   x->km.state == XFRM_STATE_EXPIRED) {
1032 		if (xfrm_selector_match(&x->sel, fl, x->sel.family) &&
1033 		    security_xfrm_state_pol_flow_match(x, pol, fl))
1034 			*error = -ESRCH;
1035 	}
1036 }
1037 
1038 struct xfrm_state *
1039 xfrm_state_find(const xfrm_address_t *daddr, const xfrm_address_t *saddr,
1040 		const struct flowi *fl, struct xfrm_tmpl *tmpl,
1041 		struct xfrm_policy *pol, int *err,
1042 		unsigned short family, u32 if_id)
1043 {
1044 	static xfrm_address_t saddr_wildcard = { };
1045 	struct net *net = xp_net(pol);
1046 	unsigned int h, h_wildcard;
1047 	struct xfrm_state *x, *x0, *to_put;
1048 	int acquire_in_progress = 0;
1049 	int error = 0;
1050 	struct xfrm_state *best = NULL;
1051 	u32 mark = pol->mark.v & pol->mark.m;
1052 	unsigned short encap_family = tmpl->encap_family;
1053 	unsigned int sequence;
1054 	struct km_event c;
1055 
1056 	to_put = NULL;
1057 
1058 	sequence = read_seqcount_begin(&xfrm_state_hash_generation);
1059 
1060 	rcu_read_lock();
1061 	h = xfrm_dst_hash(net, daddr, saddr, tmpl->reqid, encap_family);
1062 	hlist_for_each_entry_rcu(x, net->xfrm.state_bydst + h, bydst) {
1063 		if (x->props.family == encap_family &&
1064 		    x->props.reqid == tmpl->reqid &&
1065 		    (mark & x->mark.m) == x->mark.v &&
1066 		    x->if_id == if_id &&
1067 		    !(x->props.flags & XFRM_STATE_WILDRECV) &&
1068 		    xfrm_state_addr_check(x, daddr, saddr, encap_family) &&
1069 		    tmpl->mode == x->props.mode &&
1070 		    tmpl->id.proto == x->id.proto &&
1071 		    (tmpl->id.spi == x->id.spi || !tmpl->id.spi))
1072 			xfrm_state_look_at(pol, x, fl, encap_family,
1073 					   &best, &acquire_in_progress, &error);
1074 	}
1075 	if (best || acquire_in_progress)
1076 		goto found;
1077 
1078 	h_wildcard = xfrm_dst_hash(net, daddr, &saddr_wildcard, tmpl->reqid, encap_family);
1079 	hlist_for_each_entry_rcu(x, net->xfrm.state_bydst + h_wildcard, bydst) {
1080 		if (x->props.family == encap_family &&
1081 		    x->props.reqid == tmpl->reqid &&
1082 		    (mark & x->mark.m) == x->mark.v &&
1083 		    x->if_id == if_id &&
1084 		    !(x->props.flags & XFRM_STATE_WILDRECV) &&
1085 		    xfrm_addr_equal(&x->id.daddr, daddr, encap_family) &&
1086 		    tmpl->mode == x->props.mode &&
1087 		    tmpl->id.proto == x->id.proto &&
1088 		    (tmpl->id.spi == x->id.spi || !tmpl->id.spi))
1089 			xfrm_state_look_at(pol, x, fl, encap_family,
1090 					   &best, &acquire_in_progress, &error);
1091 	}
1092 
1093 found:
1094 	x = best;
1095 	if (!x && !error && !acquire_in_progress) {
1096 		if (tmpl->id.spi &&
1097 		    (x0 = __xfrm_state_lookup(net, mark, daddr, tmpl->id.spi,
1098 					      tmpl->id.proto, encap_family)) != NULL) {
1099 			to_put = x0;
1100 			error = -EEXIST;
1101 			goto out;
1102 		}
1103 
1104 		c.net = net;
1105 		/* If the KMs have no listeners (yet...), avoid allocating an SA
1106 		 * for each and every packet - garbage collection might not
1107 		 * handle the flood.
1108 		 */
1109 		if (!km_is_alive(&c)) {
1110 			error = -ESRCH;
1111 			goto out;
1112 		}
1113 
1114 		x = xfrm_state_alloc(net);
1115 		if (x == NULL) {
1116 			error = -ENOMEM;
1117 			goto out;
1118 		}
1119 		/* Initialize temporary state matching only
1120 		 * to current session. */
1121 		xfrm_init_tempstate(x, fl, tmpl, daddr, saddr, family);
1122 		memcpy(&x->mark, &pol->mark, sizeof(x->mark));
1123 		x->if_id = if_id;
1124 
1125 		error = security_xfrm_state_alloc_acquire(x, pol->security, fl->flowi_secid);
1126 		if (error) {
1127 			x->km.state = XFRM_STATE_DEAD;
1128 			to_put = x;
1129 			x = NULL;
1130 			goto out;
1131 		}
1132 
1133 		if (km_query(x, tmpl, pol) == 0) {
1134 			spin_lock_bh(&net->xfrm.xfrm_state_lock);
1135 			x->km.state = XFRM_STATE_ACQ;
1136 			list_add(&x->km.all, &net->xfrm.state_all);
1137 			hlist_add_head_rcu(&x->bydst, net->xfrm.state_bydst + h);
1138 			h = xfrm_src_hash(net, daddr, saddr, encap_family);
1139 			hlist_add_head_rcu(&x->bysrc, net->xfrm.state_bysrc + h);
1140 			if (x->id.spi) {
1141 				h = xfrm_spi_hash(net, &x->id.daddr, x->id.spi, x->id.proto, encap_family);
1142 				hlist_add_head_rcu(&x->byspi, net->xfrm.state_byspi + h);
1143 			}
1144 			x->lft.hard_add_expires_seconds = net->xfrm.sysctl_acq_expires;
1145 			hrtimer_start(&x->mtimer,
1146 				      ktime_set(net->xfrm.sysctl_acq_expires, 0),
1147 				      HRTIMER_MODE_REL_SOFT);
1148 			net->xfrm.state_num++;
1149 			xfrm_hash_grow_check(net, x->bydst.next != NULL);
1150 			spin_unlock_bh(&net->xfrm.xfrm_state_lock);
1151 		} else {
1152 			x->km.state = XFRM_STATE_DEAD;
1153 			to_put = x;
1154 			x = NULL;
1155 			error = -ESRCH;
1156 		}
1157 	}
1158 out:
1159 	if (x) {
1160 		if (!xfrm_state_hold_rcu(x)) {
1161 			*err = -EAGAIN;
1162 			x = NULL;
1163 		}
1164 	} else {
1165 		*err = acquire_in_progress ? -EAGAIN : error;
1166 	}
1167 	rcu_read_unlock();
1168 	if (to_put)
1169 		xfrm_state_put(to_put);
1170 
1171 	if (read_seqcount_retry(&xfrm_state_hash_generation, sequence)) {
1172 		*err = -EAGAIN;
1173 		if (x) {
1174 			xfrm_state_put(x);
1175 			x = NULL;
1176 		}
1177 	}
1178 
1179 	return x;
1180 }
1181 
1182 struct xfrm_state *
1183 xfrm_stateonly_find(struct net *net, u32 mark, u32 if_id,
1184 		    xfrm_address_t *daddr, xfrm_address_t *saddr,
1185 		    unsigned short family, u8 mode, u8 proto, u32 reqid)
1186 {
1187 	unsigned int h;
1188 	struct xfrm_state *rx = NULL, *x = NULL;
1189 
1190 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
1191 	h = xfrm_dst_hash(net, daddr, saddr, reqid, family);
1192 	hlist_for_each_entry(x, net->xfrm.state_bydst+h, bydst) {
1193 		if (x->props.family == family &&
1194 		    x->props.reqid == reqid &&
1195 		    (mark & x->mark.m) == x->mark.v &&
1196 		    x->if_id == if_id &&
1197 		    !(x->props.flags & XFRM_STATE_WILDRECV) &&
1198 		    xfrm_state_addr_check(x, daddr, saddr, family) &&
1199 		    mode == x->props.mode &&
1200 		    proto == x->id.proto &&
1201 		    x->km.state == XFRM_STATE_VALID) {
1202 			rx = x;
1203 			break;
1204 		}
1205 	}
1206 
1207 	if (rx)
1208 		xfrm_state_hold(rx);
1209 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
1210 
1211 
1212 	return rx;
1213 }
1214 EXPORT_SYMBOL(xfrm_stateonly_find);
1215 
1216 struct xfrm_state *xfrm_state_lookup_byspi(struct net *net, __be32 spi,
1217 					      unsigned short family)
1218 {
1219 	struct xfrm_state *x;
1220 	struct xfrm_state_walk *w;
1221 
1222 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
1223 	list_for_each_entry(w, &net->xfrm.state_all, all) {
1224 		x = container_of(w, struct xfrm_state, km);
1225 		if (x->props.family != family ||
1226 			x->id.spi != spi)
1227 			continue;
1228 
1229 		xfrm_state_hold(x);
1230 		spin_unlock_bh(&net->xfrm.xfrm_state_lock);
1231 		return x;
1232 	}
1233 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
1234 	return NULL;
1235 }
1236 EXPORT_SYMBOL(xfrm_state_lookup_byspi);
1237 
1238 static void __xfrm_state_insert(struct xfrm_state *x)
1239 {
1240 	struct net *net = xs_net(x);
1241 	unsigned int h;
1242 
1243 	list_add(&x->km.all, &net->xfrm.state_all);
1244 
1245 	h = xfrm_dst_hash(net, &x->id.daddr, &x->props.saddr,
1246 			  x->props.reqid, x->props.family);
1247 	hlist_add_head_rcu(&x->bydst, net->xfrm.state_bydst + h);
1248 
1249 	h = xfrm_src_hash(net, &x->id.daddr, &x->props.saddr, x->props.family);
1250 	hlist_add_head_rcu(&x->bysrc, net->xfrm.state_bysrc + h);
1251 
1252 	if (x->id.spi) {
1253 		h = xfrm_spi_hash(net, &x->id.daddr, x->id.spi, x->id.proto,
1254 				  x->props.family);
1255 
1256 		hlist_add_head_rcu(&x->byspi, net->xfrm.state_byspi + h);
1257 	}
1258 
1259 	hrtimer_start(&x->mtimer, ktime_set(1, 0), HRTIMER_MODE_REL_SOFT);
1260 	if (x->replay_maxage)
1261 		mod_timer(&x->rtimer, jiffies + x->replay_maxage);
1262 
1263 	net->xfrm.state_num++;
1264 
1265 	xfrm_hash_grow_check(net, x->bydst.next != NULL);
1266 }
1267 
1268 /* net->xfrm.xfrm_state_lock is held */
1269 static void __xfrm_state_bump_genids(struct xfrm_state *xnew)
1270 {
1271 	struct net *net = xs_net(xnew);
1272 	unsigned short family = xnew->props.family;
1273 	u32 reqid = xnew->props.reqid;
1274 	struct xfrm_state *x;
1275 	unsigned int h;
1276 	u32 mark = xnew->mark.v & xnew->mark.m;
1277 	u32 if_id = xnew->if_id;
1278 
1279 	h = xfrm_dst_hash(net, &xnew->id.daddr, &xnew->props.saddr, reqid, family);
1280 	hlist_for_each_entry(x, net->xfrm.state_bydst+h, bydst) {
1281 		if (x->props.family	== family &&
1282 		    x->props.reqid	== reqid &&
1283 		    x->if_id		== if_id &&
1284 		    (mark & x->mark.m) == x->mark.v &&
1285 		    xfrm_addr_equal(&x->id.daddr, &xnew->id.daddr, family) &&
1286 		    xfrm_addr_equal(&x->props.saddr, &xnew->props.saddr, family))
1287 			x->genid++;
1288 	}
1289 }
1290 
1291 void xfrm_state_insert(struct xfrm_state *x)
1292 {
1293 	struct net *net = xs_net(x);
1294 
1295 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
1296 	__xfrm_state_bump_genids(x);
1297 	__xfrm_state_insert(x);
1298 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
1299 }
1300 EXPORT_SYMBOL(xfrm_state_insert);
1301 
1302 /* net->xfrm.xfrm_state_lock is held */
1303 static struct xfrm_state *__find_acq_core(struct net *net,
1304 					  const struct xfrm_mark *m,
1305 					  unsigned short family, u8 mode,
1306 					  u32 reqid, u32 if_id, u8 proto,
1307 					  const xfrm_address_t *daddr,
1308 					  const xfrm_address_t *saddr,
1309 					  int create)
1310 {
1311 	unsigned int h = xfrm_dst_hash(net, daddr, saddr, reqid, family);
1312 	struct xfrm_state *x;
1313 	u32 mark = m->v & m->m;
1314 
1315 	hlist_for_each_entry(x, net->xfrm.state_bydst+h, bydst) {
1316 		if (x->props.reqid  != reqid ||
1317 		    x->props.mode   != mode ||
1318 		    x->props.family != family ||
1319 		    x->km.state     != XFRM_STATE_ACQ ||
1320 		    x->id.spi       != 0 ||
1321 		    x->id.proto	    != proto ||
1322 		    (mark & x->mark.m) != x->mark.v ||
1323 		    !xfrm_addr_equal(&x->id.daddr, daddr, family) ||
1324 		    !xfrm_addr_equal(&x->props.saddr, saddr, family))
1325 			continue;
1326 
1327 		xfrm_state_hold(x);
1328 		return x;
1329 	}
1330 
1331 	if (!create)
1332 		return NULL;
1333 
1334 	x = xfrm_state_alloc(net);
1335 	if (likely(x)) {
1336 		switch (family) {
1337 		case AF_INET:
1338 			x->sel.daddr.a4 = daddr->a4;
1339 			x->sel.saddr.a4 = saddr->a4;
1340 			x->sel.prefixlen_d = 32;
1341 			x->sel.prefixlen_s = 32;
1342 			x->props.saddr.a4 = saddr->a4;
1343 			x->id.daddr.a4 = daddr->a4;
1344 			break;
1345 
1346 		case AF_INET6:
1347 			x->sel.daddr.in6 = daddr->in6;
1348 			x->sel.saddr.in6 = saddr->in6;
1349 			x->sel.prefixlen_d = 128;
1350 			x->sel.prefixlen_s = 128;
1351 			x->props.saddr.in6 = saddr->in6;
1352 			x->id.daddr.in6 = daddr->in6;
1353 			break;
1354 		}
1355 
1356 		x->km.state = XFRM_STATE_ACQ;
1357 		x->id.proto = proto;
1358 		x->props.family = family;
1359 		x->props.mode = mode;
1360 		x->props.reqid = reqid;
1361 		x->if_id = if_id;
1362 		x->mark.v = m->v;
1363 		x->mark.m = m->m;
1364 		x->lft.hard_add_expires_seconds = net->xfrm.sysctl_acq_expires;
1365 		xfrm_state_hold(x);
1366 		hrtimer_start(&x->mtimer,
1367 			      ktime_set(net->xfrm.sysctl_acq_expires, 0),
1368 			      HRTIMER_MODE_REL_SOFT);
1369 		list_add(&x->km.all, &net->xfrm.state_all);
1370 		hlist_add_head_rcu(&x->bydst, net->xfrm.state_bydst + h);
1371 		h = xfrm_src_hash(net, daddr, saddr, family);
1372 		hlist_add_head_rcu(&x->bysrc, net->xfrm.state_bysrc + h);
1373 
1374 		net->xfrm.state_num++;
1375 
1376 		xfrm_hash_grow_check(net, x->bydst.next != NULL);
1377 	}
1378 
1379 	return x;
1380 }
1381 
1382 static struct xfrm_state *__xfrm_find_acq_byseq(struct net *net, u32 mark, u32 seq);
1383 
1384 int xfrm_state_add(struct xfrm_state *x)
1385 {
1386 	struct net *net = xs_net(x);
1387 	struct xfrm_state *x1, *to_put;
1388 	int family;
1389 	int err;
1390 	u32 mark = x->mark.v & x->mark.m;
1391 	int use_spi = xfrm_id_proto_match(x->id.proto, IPSEC_PROTO_ANY);
1392 
1393 	family = x->props.family;
1394 
1395 	to_put = NULL;
1396 
1397 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
1398 
1399 	x1 = __xfrm_state_locate(x, use_spi, family);
1400 	if (x1) {
1401 		to_put = x1;
1402 		x1 = NULL;
1403 		err = -EEXIST;
1404 		goto out;
1405 	}
1406 
1407 	if (use_spi && x->km.seq) {
1408 		x1 = __xfrm_find_acq_byseq(net, mark, x->km.seq);
1409 		if (x1 && ((x1->id.proto != x->id.proto) ||
1410 		    !xfrm_addr_equal(&x1->id.daddr, &x->id.daddr, family))) {
1411 			to_put = x1;
1412 			x1 = NULL;
1413 		}
1414 	}
1415 
1416 	if (use_spi && !x1)
1417 		x1 = __find_acq_core(net, &x->mark, family, x->props.mode,
1418 				     x->props.reqid, x->if_id, x->id.proto,
1419 				     &x->id.daddr, &x->props.saddr, 0);
1420 
1421 	__xfrm_state_bump_genids(x);
1422 	__xfrm_state_insert(x);
1423 	err = 0;
1424 
1425 out:
1426 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
1427 
1428 	if (x1) {
1429 		xfrm_state_delete(x1);
1430 		xfrm_state_put(x1);
1431 	}
1432 
1433 	if (to_put)
1434 		xfrm_state_put(to_put);
1435 
1436 	return err;
1437 }
1438 EXPORT_SYMBOL(xfrm_state_add);
1439 
1440 #ifdef CONFIG_XFRM_MIGRATE
1441 static struct xfrm_state *xfrm_state_clone(struct xfrm_state *orig,
1442 					   struct xfrm_encap_tmpl *encap)
1443 {
1444 	struct net *net = xs_net(orig);
1445 	struct xfrm_state *x = xfrm_state_alloc(net);
1446 	if (!x)
1447 		goto out;
1448 
1449 	memcpy(&x->id, &orig->id, sizeof(x->id));
1450 	memcpy(&x->sel, &orig->sel, sizeof(x->sel));
1451 	memcpy(&x->lft, &orig->lft, sizeof(x->lft));
1452 	x->props.mode = orig->props.mode;
1453 	x->props.replay_window = orig->props.replay_window;
1454 	x->props.reqid = orig->props.reqid;
1455 	x->props.family = orig->props.family;
1456 	x->props.saddr = orig->props.saddr;
1457 
1458 	if (orig->aalg) {
1459 		x->aalg = xfrm_algo_auth_clone(orig->aalg);
1460 		if (!x->aalg)
1461 			goto error;
1462 	}
1463 	x->props.aalgo = orig->props.aalgo;
1464 
1465 	if (orig->aead) {
1466 		x->aead = xfrm_algo_aead_clone(orig->aead);
1467 		x->geniv = orig->geniv;
1468 		if (!x->aead)
1469 			goto error;
1470 	}
1471 	if (orig->ealg) {
1472 		x->ealg = xfrm_algo_clone(orig->ealg);
1473 		if (!x->ealg)
1474 			goto error;
1475 	}
1476 	x->props.ealgo = orig->props.ealgo;
1477 
1478 	if (orig->calg) {
1479 		x->calg = xfrm_algo_clone(orig->calg);
1480 		if (!x->calg)
1481 			goto error;
1482 	}
1483 	x->props.calgo = orig->props.calgo;
1484 
1485 	if (encap || orig->encap) {
1486 		if (encap)
1487 			x->encap = kmemdup(encap, sizeof(*x->encap),
1488 					GFP_KERNEL);
1489 		else
1490 			x->encap = kmemdup(orig->encap, sizeof(*x->encap),
1491 					GFP_KERNEL);
1492 
1493 		if (!x->encap)
1494 			goto error;
1495 	}
1496 
1497 	if (orig->coaddr) {
1498 		x->coaddr = kmemdup(orig->coaddr, sizeof(*x->coaddr),
1499 				    GFP_KERNEL);
1500 		if (!x->coaddr)
1501 			goto error;
1502 	}
1503 
1504 	if (orig->replay_esn) {
1505 		if (xfrm_replay_clone(x, orig))
1506 			goto error;
1507 	}
1508 
1509 	memcpy(&x->mark, &orig->mark, sizeof(x->mark));
1510 
1511 	if (xfrm_init_state(x) < 0)
1512 		goto error;
1513 
1514 	x->props.flags = orig->props.flags;
1515 	x->props.extra_flags = orig->props.extra_flags;
1516 
1517 	x->if_id = orig->if_id;
1518 	x->tfcpad = orig->tfcpad;
1519 	x->replay_maxdiff = orig->replay_maxdiff;
1520 	x->replay_maxage = orig->replay_maxage;
1521 	x->curlft.add_time = orig->curlft.add_time;
1522 	x->km.state = orig->km.state;
1523 	x->km.seq = orig->km.seq;
1524 	x->replay = orig->replay;
1525 	x->preplay = orig->preplay;
1526 
1527 	return x;
1528 
1529  error:
1530 	xfrm_state_put(x);
1531 out:
1532 	return NULL;
1533 }
1534 
1535 struct xfrm_state *xfrm_migrate_state_find(struct xfrm_migrate *m, struct net *net)
1536 {
1537 	unsigned int h;
1538 	struct xfrm_state *x = NULL;
1539 
1540 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
1541 
1542 	if (m->reqid) {
1543 		h = xfrm_dst_hash(net, &m->old_daddr, &m->old_saddr,
1544 				  m->reqid, m->old_family);
1545 		hlist_for_each_entry(x, net->xfrm.state_bydst+h, bydst) {
1546 			if (x->props.mode != m->mode ||
1547 			    x->id.proto != m->proto)
1548 				continue;
1549 			if (m->reqid && x->props.reqid != m->reqid)
1550 				continue;
1551 			if (!xfrm_addr_equal(&x->id.daddr, &m->old_daddr,
1552 					     m->old_family) ||
1553 			    !xfrm_addr_equal(&x->props.saddr, &m->old_saddr,
1554 					     m->old_family))
1555 				continue;
1556 			xfrm_state_hold(x);
1557 			break;
1558 		}
1559 	} else {
1560 		h = xfrm_src_hash(net, &m->old_daddr, &m->old_saddr,
1561 				  m->old_family);
1562 		hlist_for_each_entry(x, net->xfrm.state_bysrc+h, bysrc) {
1563 			if (x->props.mode != m->mode ||
1564 			    x->id.proto != m->proto)
1565 				continue;
1566 			if (!xfrm_addr_equal(&x->id.daddr, &m->old_daddr,
1567 					     m->old_family) ||
1568 			    !xfrm_addr_equal(&x->props.saddr, &m->old_saddr,
1569 					     m->old_family))
1570 				continue;
1571 			xfrm_state_hold(x);
1572 			break;
1573 		}
1574 	}
1575 
1576 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
1577 
1578 	return x;
1579 }
1580 EXPORT_SYMBOL(xfrm_migrate_state_find);
1581 
1582 struct xfrm_state *xfrm_state_migrate(struct xfrm_state *x,
1583 				      struct xfrm_migrate *m,
1584 				      struct xfrm_encap_tmpl *encap)
1585 {
1586 	struct xfrm_state *xc;
1587 
1588 	xc = xfrm_state_clone(x, encap);
1589 	if (!xc)
1590 		return NULL;
1591 
1592 	memcpy(&xc->id.daddr, &m->new_daddr, sizeof(xc->id.daddr));
1593 	memcpy(&xc->props.saddr, &m->new_saddr, sizeof(xc->props.saddr));
1594 
1595 	/* add state */
1596 	if (xfrm_addr_equal(&x->id.daddr, &m->new_daddr, m->new_family)) {
1597 		/* a care is needed when the destination address of the
1598 		   state is to be updated as it is a part of triplet */
1599 		xfrm_state_insert(xc);
1600 	} else {
1601 		if (xfrm_state_add(xc) < 0)
1602 			goto error;
1603 	}
1604 
1605 	return xc;
1606 error:
1607 	xfrm_state_put(xc);
1608 	return NULL;
1609 }
1610 EXPORT_SYMBOL(xfrm_state_migrate);
1611 #endif
1612 
1613 int xfrm_state_update(struct xfrm_state *x)
1614 {
1615 	struct xfrm_state *x1, *to_put;
1616 	int err;
1617 	int use_spi = xfrm_id_proto_match(x->id.proto, IPSEC_PROTO_ANY);
1618 	struct net *net = xs_net(x);
1619 
1620 	to_put = NULL;
1621 
1622 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
1623 	x1 = __xfrm_state_locate(x, use_spi, x->props.family);
1624 
1625 	err = -ESRCH;
1626 	if (!x1)
1627 		goto out;
1628 
1629 	if (xfrm_state_kern(x1)) {
1630 		to_put = x1;
1631 		err = -EEXIST;
1632 		goto out;
1633 	}
1634 
1635 	if (x1->km.state == XFRM_STATE_ACQ) {
1636 		__xfrm_state_insert(x);
1637 		x = NULL;
1638 	}
1639 	err = 0;
1640 
1641 out:
1642 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
1643 
1644 	if (to_put)
1645 		xfrm_state_put(to_put);
1646 
1647 	if (err)
1648 		return err;
1649 
1650 	if (!x) {
1651 		xfrm_state_delete(x1);
1652 		xfrm_state_put(x1);
1653 		return 0;
1654 	}
1655 
1656 	err = -EINVAL;
1657 	spin_lock_bh(&x1->lock);
1658 	if (likely(x1->km.state == XFRM_STATE_VALID)) {
1659 		if (x->encap && x1->encap &&
1660 		    x->encap->encap_type == x1->encap->encap_type)
1661 			memcpy(x1->encap, x->encap, sizeof(*x1->encap));
1662 		else if (x->encap || x1->encap)
1663 			goto fail;
1664 
1665 		if (x->coaddr && x1->coaddr) {
1666 			memcpy(x1->coaddr, x->coaddr, sizeof(*x1->coaddr));
1667 		}
1668 		if (!use_spi && memcmp(&x1->sel, &x->sel, sizeof(x1->sel)))
1669 			memcpy(&x1->sel, &x->sel, sizeof(x1->sel));
1670 		memcpy(&x1->lft, &x->lft, sizeof(x1->lft));
1671 		x1->km.dying = 0;
1672 
1673 		hrtimer_start(&x1->mtimer, ktime_set(1, 0),
1674 			      HRTIMER_MODE_REL_SOFT);
1675 		if (x1->curlft.use_time)
1676 			xfrm_state_check_expire(x1);
1677 
1678 		if (x->props.smark.m || x->props.smark.v || x->if_id) {
1679 			spin_lock_bh(&net->xfrm.xfrm_state_lock);
1680 
1681 			if (x->props.smark.m || x->props.smark.v)
1682 				x1->props.smark = x->props.smark;
1683 
1684 			if (x->if_id)
1685 				x1->if_id = x->if_id;
1686 
1687 			__xfrm_state_bump_genids(x1);
1688 			spin_unlock_bh(&net->xfrm.xfrm_state_lock);
1689 		}
1690 
1691 		err = 0;
1692 		x->km.state = XFRM_STATE_DEAD;
1693 		__xfrm_state_put(x);
1694 	}
1695 
1696 fail:
1697 	spin_unlock_bh(&x1->lock);
1698 
1699 	xfrm_state_put(x1);
1700 
1701 	return err;
1702 }
1703 EXPORT_SYMBOL(xfrm_state_update);
1704 
1705 int xfrm_state_check_expire(struct xfrm_state *x)
1706 {
1707 	if (!x->curlft.use_time)
1708 		x->curlft.use_time = ktime_get_real_seconds();
1709 
1710 	if (x->curlft.bytes >= x->lft.hard_byte_limit ||
1711 	    x->curlft.packets >= x->lft.hard_packet_limit) {
1712 		x->km.state = XFRM_STATE_EXPIRED;
1713 		hrtimer_start(&x->mtimer, 0, HRTIMER_MODE_REL_SOFT);
1714 		return -EINVAL;
1715 	}
1716 
1717 	if (!x->km.dying &&
1718 	    (x->curlft.bytes >= x->lft.soft_byte_limit ||
1719 	     x->curlft.packets >= x->lft.soft_packet_limit)) {
1720 		x->km.dying = 1;
1721 		km_state_expired(x, 0, 0);
1722 	}
1723 	return 0;
1724 }
1725 EXPORT_SYMBOL(xfrm_state_check_expire);
1726 
1727 struct xfrm_state *
1728 xfrm_state_lookup(struct net *net, u32 mark, const xfrm_address_t *daddr, __be32 spi,
1729 		  u8 proto, unsigned short family)
1730 {
1731 	struct xfrm_state *x;
1732 
1733 	rcu_read_lock();
1734 	x = __xfrm_state_lookup(net, mark, daddr, spi, proto, family);
1735 	rcu_read_unlock();
1736 	return x;
1737 }
1738 EXPORT_SYMBOL(xfrm_state_lookup);
1739 
1740 struct xfrm_state *
1741 xfrm_state_lookup_byaddr(struct net *net, u32 mark,
1742 			 const xfrm_address_t *daddr, const xfrm_address_t *saddr,
1743 			 u8 proto, unsigned short family)
1744 {
1745 	struct xfrm_state *x;
1746 
1747 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
1748 	x = __xfrm_state_lookup_byaddr(net, mark, daddr, saddr, proto, family);
1749 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
1750 	return x;
1751 }
1752 EXPORT_SYMBOL(xfrm_state_lookup_byaddr);
1753 
1754 struct xfrm_state *
1755 xfrm_find_acq(struct net *net, const struct xfrm_mark *mark, u8 mode, u32 reqid,
1756 	      u32 if_id, u8 proto, const xfrm_address_t *daddr,
1757 	      const xfrm_address_t *saddr, int create, unsigned short family)
1758 {
1759 	struct xfrm_state *x;
1760 
1761 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
1762 	x = __find_acq_core(net, mark, family, mode, reqid, if_id, proto, daddr, saddr, create);
1763 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
1764 
1765 	return x;
1766 }
1767 EXPORT_SYMBOL(xfrm_find_acq);
1768 
1769 #ifdef CONFIG_XFRM_SUB_POLICY
1770 #if IS_ENABLED(CONFIG_IPV6)
1771 /* distribution counting sort function for xfrm_state and xfrm_tmpl */
1772 static void
1773 __xfrm6_sort(void **dst, void **src, int n,
1774 	     int (*cmp)(const void *p), int maxclass)
1775 {
1776 	int count[XFRM_MAX_DEPTH] = { };
1777 	int class[XFRM_MAX_DEPTH];
1778 	int i;
1779 
1780 	for (i = 0; i < n; i++) {
1781 		int c = cmp(src[i]);
1782 
1783 		class[i] = c;
1784 		count[c]++;
1785 	}
1786 
1787 	for (i = 2; i < maxclass; i++)
1788 		count[i] += count[i - 1];
1789 
1790 	for (i = 0; i < n; i++) {
1791 		dst[count[class[i] - 1]++] = src[i];
1792 		src[i] = NULL;
1793 	}
1794 }
1795 
1796 /* Rule for xfrm_state:
1797  *
1798  * rule 1: select IPsec transport except AH
1799  * rule 2: select MIPv6 RO or inbound trigger
1800  * rule 3: select IPsec transport AH
1801  * rule 4: select IPsec tunnel
1802  * rule 5: others
1803  */
1804 static int __xfrm6_state_sort_cmp(const void *p)
1805 {
1806 	const struct xfrm_state *v = p;
1807 
1808 	switch (v->props.mode) {
1809 	case XFRM_MODE_TRANSPORT:
1810 		if (v->id.proto != IPPROTO_AH)
1811 			return 1;
1812 		else
1813 			return 3;
1814 #if IS_ENABLED(CONFIG_IPV6_MIP6)
1815 	case XFRM_MODE_ROUTEOPTIMIZATION:
1816 	case XFRM_MODE_IN_TRIGGER:
1817 		return 2;
1818 #endif
1819 	case XFRM_MODE_TUNNEL:
1820 	case XFRM_MODE_BEET:
1821 		return 4;
1822 	}
1823 	return 5;
1824 }
1825 
1826 /* Rule for xfrm_tmpl:
1827  *
1828  * rule 1: select IPsec transport
1829  * rule 2: select MIPv6 RO or inbound trigger
1830  * rule 3: select IPsec tunnel
1831  * rule 4: others
1832  */
1833 static int __xfrm6_tmpl_sort_cmp(const void *p)
1834 {
1835 	const struct xfrm_tmpl *v = p;
1836 
1837 	switch (v->mode) {
1838 	case XFRM_MODE_TRANSPORT:
1839 		return 1;
1840 #if IS_ENABLED(CONFIG_IPV6_MIP6)
1841 	case XFRM_MODE_ROUTEOPTIMIZATION:
1842 	case XFRM_MODE_IN_TRIGGER:
1843 		return 2;
1844 #endif
1845 	case XFRM_MODE_TUNNEL:
1846 	case XFRM_MODE_BEET:
1847 		return 3;
1848 	}
1849 	return 4;
1850 }
1851 #else
1852 static inline int __xfrm6_state_sort_cmp(const void *p) { return 5; }
1853 static inline int __xfrm6_tmpl_sort_cmp(const void *p) { return 4; }
1854 
1855 static inline void
1856 __xfrm6_sort(void **dst, void **src, int n,
1857 	     int (*cmp)(const void *p), int maxclass)
1858 {
1859 	int i;
1860 
1861 	for (i = 0; i < n; i++)
1862 		dst[i] = src[i];
1863 }
1864 #endif /* CONFIG_IPV6 */
1865 
1866 void
1867 xfrm_tmpl_sort(struct xfrm_tmpl **dst, struct xfrm_tmpl **src, int n,
1868 	       unsigned short family)
1869 {
1870 	int i;
1871 
1872 	if (family == AF_INET6)
1873 		__xfrm6_sort((void **)dst, (void **)src, n,
1874 			     __xfrm6_tmpl_sort_cmp, 5);
1875 	else
1876 		for (i = 0; i < n; i++)
1877 			dst[i] = src[i];
1878 }
1879 
1880 void
1881 xfrm_state_sort(struct xfrm_state **dst, struct xfrm_state **src, int n,
1882 		unsigned short family)
1883 {
1884 	int i;
1885 
1886 	if (family == AF_INET6)
1887 		__xfrm6_sort((void **)dst, (void **)src, n,
1888 			     __xfrm6_state_sort_cmp, 6);
1889 	else
1890 		for (i = 0; i < n; i++)
1891 			dst[i] = src[i];
1892 }
1893 #endif
1894 
1895 /* Silly enough, but I'm lazy to build resolution list */
1896 
1897 static struct xfrm_state *__xfrm_find_acq_byseq(struct net *net, u32 mark, u32 seq)
1898 {
1899 	int i;
1900 
1901 	for (i = 0; i <= net->xfrm.state_hmask; i++) {
1902 		struct xfrm_state *x;
1903 
1904 		hlist_for_each_entry(x, net->xfrm.state_bydst+i, bydst) {
1905 			if (x->km.seq == seq &&
1906 			    (mark & x->mark.m) == x->mark.v &&
1907 			    x->km.state == XFRM_STATE_ACQ) {
1908 				xfrm_state_hold(x);
1909 				return x;
1910 			}
1911 		}
1912 	}
1913 	return NULL;
1914 }
1915 
1916 struct xfrm_state *xfrm_find_acq_byseq(struct net *net, u32 mark, u32 seq)
1917 {
1918 	struct xfrm_state *x;
1919 
1920 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
1921 	x = __xfrm_find_acq_byseq(net, mark, seq);
1922 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
1923 	return x;
1924 }
1925 EXPORT_SYMBOL(xfrm_find_acq_byseq);
1926 
1927 u32 xfrm_get_acqseq(void)
1928 {
1929 	u32 res;
1930 	static atomic_t acqseq;
1931 
1932 	do {
1933 		res = atomic_inc_return(&acqseq);
1934 	} while (!res);
1935 
1936 	return res;
1937 }
1938 EXPORT_SYMBOL(xfrm_get_acqseq);
1939 
1940 int verify_spi_info(u8 proto, u32 min, u32 max)
1941 {
1942 	switch (proto) {
1943 	case IPPROTO_AH:
1944 	case IPPROTO_ESP:
1945 		break;
1946 
1947 	case IPPROTO_COMP:
1948 		/* IPCOMP spi is 16-bits. */
1949 		if (max >= 0x10000)
1950 			return -EINVAL;
1951 		break;
1952 
1953 	default:
1954 		return -EINVAL;
1955 	}
1956 
1957 	if (min > max)
1958 		return -EINVAL;
1959 
1960 	return 0;
1961 }
1962 EXPORT_SYMBOL(verify_spi_info);
1963 
1964 int xfrm_alloc_spi(struct xfrm_state *x, u32 low, u32 high)
1965 {
1966 	struct net *net = xs_net(x);
1967 	unsigned int h;
1968 	struct xfrm_state *x0;
1969 	int err = -ENOENT;
1970 	__be32 minspi = htonl(low);
1971 	__be32 maxspi = htonl(high);
1972 	u32 mark = x->mark.v & x->mark.m;
1973 
1974 	spin_lock_bh(&x->lock);
1975 	if (x->km.state == XFRM_STATE_DEAD)
1976 		goto unlock;
1977 
1978 	err = 0;
1979 	if (x->id.spi)
1980 		goto unlock;
1981 
1982 	err = -ENOENT;
1983 
1984 	if (minspi == maxspi) {
1985 		x0 = xfrm_state_lookup(net, mark, &x->id.daddr, minspi, x->id.proto, x->props.family);
1986 		if (x0) {
1987 			xfrm_state_put(x0);
1988 			goto unlock;
1989 		}
1990 		x->id.spi = minspi;
1991 	} else {
1992 		u32 spi = 0;
1993 		for (h = 0; h < high-low+1; h++) {
1994 			spi = low + prandom_u32()%(high-low+1);
1995 			x0 = xfrm_state_lookup(net, mark, &x->id.daddr, htonl(spi), x->id.proto, x->props.family);
1996 			if (x0 == NULL) {
1997 				x->id.spi = htonl(spi);
1998 				break;
1999 			}
2000 			xfrm_state_put(x0);
2001 		}
2002 	}
2003 	if (x->id.spi) {
2004 		spin_lock_bh(&net->xfrm.xfrm_state_lock);
2005 		h = xfrm_spi_hash(net, &x->id.daddr, x->id.spi, x->id.proto, x->props.family);
2006 		hlist_add_head_rcu(&x->byspi, net->xfrm.state_byspi + h);
2007 		spin_unlock_bh(&net->xfrm.xfrm_state_lock);
2008 
2009 		err = 0;
2010 	}
2011 
2012 unlock:
2013 	spin_unlock_bh(&x->lock);
2014 
2015 	return err;
2016 }
2017 EXPORT_SYMBOL(xfrm_alloc_spi);
2018 
2019 static bool __xfrm_state_filter_match(struct xfrm_state *x,
2020 				      struct xfrm_address_filter *filter)
2021 {
2022 	if (filter) {
2023 		if ((filter->family == AF_INET ||
2024 		     filter->family == AF_INET6) &&
2025 		    x->props.family != filter->family)
2026 			return false;
2027 
2028 		return addr_match(&x->props.saddr, &filter->saddr,
2029 				  filter->splen) &&
2030 		       addr_match(&x->id.daddr, &filter->daddr,
2031 				  filter->dplen);
2032 	}
2033 	return true;
2034 }
2035 
2036 int xfrm_state_walk(struct net *net, struct xfrm_state_walk *walk,
2037 		    int (*func)(struct xfrm_state *, int, void*),
2038 		    void *data)
2039 {
2040 	struct xfrm_state *state;
2041 	struct xfrm_state_walk *x;
2042 	int err = 0;
2043 
2044 	if (walk->seq != 0 && list_empty(&walk->all))
2045 		return 0;
2046 
2047 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
2048 	if (list_empty(&walk->all))
2049 		x = list_first_entry(&net->xfrm.state_all, struct xfrm_state_walk, all);
2050 	else
2051 		x = list_first_entry(&walk->all, struct xfrm_state_walk, all);
2052 	list_for_each_entry_from(x, &net->xfrm.state_all, all) {
2053 		if (x->state == XFRM_STATE_DEAD)
2054 			continue;
2055 		state = container_of(x, struct xfrm_state, km);
2056 		if (!xfrm_id_proto_match(state->id.proto, walk->proto))
2057 			continue;
2058 		if (!__xfrm_state_filter_match(state, walk->filter))
2059 			continue;
2060 		err = func(state, walk->seq, data);
2061 		if (err) {
2062 			list_move_tail(&walk->all, &x->all);
2063 			goto out;
2064 		}
2065 		walk->seq++;
2066 	}
2067 	if (walk->seq == 0) {
2068 		err = -ENOENT;
2069 		goto out;
2070 	}
2071 	list_del_init(&walk->all);
2072 out:
2073 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
2074 	return err;
2075 }
2076 EXPORT_SYMBOL(xfrm_state_walk);
2077 
2078 void xfrm_state_walk_init(struct xfrm_state_walk *walk, u8 proto,
2079 			  struct xfrm_address_filter *filter)
2080 {
2081 	INIT_LIST_HEAD(&walk->all);
2082 	walk->proto = proto;
2083 	walk->state = XFRM_STATE_DEAD;
2084 	walk->seq = 0;
2085 	walk->filter = filter;
2086 }
2087 EXPORT_SYMBOL(xfrm_state_walk_init);
2088 
2089 void xfrm_state_walk_done(struct xfrm_state_walk *walk, struct net *net)
2090 {
2091 	kfree(walk->filter);
2092 
2093 	if (list_empty(&walk->all))
2094 		return;
2095 
2096 	spin_lock_bh(&net->xfrm.xfrm_state_lock);
2097 	list_del(&walk->all);
2098 	spin_unlock_bh(&net->xfrm.xfrm_state_lock);
2099 }
2100 EXPORT_SYMBOL(xfrm_state_walk_done);
2101 
2102 static void xfrm_replay_timer_handler(struct timer_list *t)
2103 {
2104 	struct xfrm_state *x = from_timer(x, t, rtimer);
2105 
2106 	spin_lock(&x->lock);
2107 
2108 	if (x->km.state == XFRM_STATE_VALID) {
2109 		if (xfrm_aevent_is_on(xs_net(x)))
2110 			x->repl->notify(x, XFRM_REPLAY_TIMEOUT);
2111 		else
2112 			x->xflags |= XFRM_TIME_DEFER;
2113 	}
2114 
2115 	spin_unlock(&x->lock);
2116 }
2117 
2118 static LIST_HEAD(xfrm_km_list);
2119 
2120 void km_policy_notify(struct xfrm_policy *xp, int dir, const struct km_event *c)
2121 {
2122 	struct xfrm_mgr *km;
2123 
2124 	rcu_read_lock();
2125 	list_for_each_entry_rcu(km, &xfrm_km_list, list)
2126 		if (km->notify_policy)
2127 			km->notify_policy(xp, dir, c);
2128 	rcu_read_unlock();
2129 }
2130 
2131 void km_state_notify(struct xfrm_state *x, const struct km_event *c)
2132 {
2133 	struct xfrm_mgr *km;
2134 	rcu_read_lock();
2135 	list_for_each_entry_rcu(km, &xfrm_km_list, list)
2136 		if (km->notify)
2137 			km->notify(x, c);
2138 	rcu_read_unlock();
2139 }
2140 
2141 EXPORT_SYMBOL(km_policy_notify);
2142 EXPORT_SYMBOL(km_state_notify);
2143 
2144 void km_state_expired(struct xfrm_state *x, int hard, u32 portid)
2145 {
2146 	struct km_event c;
2147 
2148 	c.data.hard = hard;
2149 	c.portid = portid;
2150 	c.event = XFRM_MSG_EXPIRE;
2151 	km_state_notify(x, &c);
2152 }
2153 
2154 EXPORT_SYMBOL(km_state_expired);
2155 /*
2156  * We send to all registered managers regardless of failure
2157  * We are happy with one success
2158 */
2159 int km_query(struct xfrm_state *x, struct xfrm_tmpl *t, struct xfrm_policy *pol)
2160 {
2161 	int err = -EINVAL, acqret;
2162 	struct xfrm_mgr *km;
2163 
2164 	rcu_read_lock();
2165 	list_for_each_entry_rcu(km, &xfrm_km_list, list) {
2166 		acqret = km->acquire(x, t, pol);
2167 		if (!acqret)
2168 			err = acqret;
2169 	}
2170 	rcu_read_unlock();
2171 	return err;
2172 }
2173 EXPORT_SYMBOL(km_query);
2174 
2175 int km_new_mapping(struct xfrm_state *x, xfrm_address_t *ipaddr, __be16 sport)
2176 {
2177 	int err = -EINVAL;
2178 	struct xfrm_mgr *km;
2179 
2180 	rcu_read_lock();
2181 	list_for_each_entry_rcu(km, &xfrm_km_list, list) {
2182 		if (km->new_mapping)
2183 			err = km->new_mapping(x, ipaddr, sport);
2184 		if (!err)
2185 			break;
2186 	}
2187 	rcu_read_unlock();
2188 	return err;
2189 }
2190 EXPORT_SYMBOL(km_new_mapping);
2191 
2192 void km_policy_expired(struct xfrm_policy *pol, int dir, int hard, u32 portid)
2193 {
2194 	struct km_event c;
2195 
2196 	c.data.hard = hard;
2197 	c.portid = portid;
2198 	c.event = XFRM_MSG_POLEXPIRE;
2199 	km_policy_notify(pol, dir, &c);
2200 }
2201 EXPORT_SYMBOL(km_policy_expired);
2202 
2203 #ifdef CONFIG_XFRM_MIGRATE
2204 int km_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
2205 	       const struct xfrm_migrate *m, int num_migrate,
2206 	       const struct xfrm_kmaddress *k,
2207 	       const struct xfrm_encap_tmpl *encap)
2208 {
2209 	int err = -EINVAL;
2210 	int ret;
2211 	struct xfrm_mgr *km;
2212 
2213 	rcu_read_lock();
2214 	list_for_each_entry_rcu(km, &xfrm_km_list, list) {
2215 		if (km->migrate) {
2216 			ret = km->migrate(sel, dir, type, m, num_migrate, k,
2217 					  encap);
2218 			if (!ret)
2219 				err = ret;
2220 		}
2221 	}
2222 	rcu_read_unlock();
2223 	return err;
2224 }
2225 EXPORT_SYMBOL(km_migrate);
2226 #endif
2227 
2228 int km_report(struct net *net, u8 proto, struct xfrm_selector *sel, xfrm_address_t *addr)
2229 {
2230 	int err = -EINVAL;
2231 	int ret;
2232 	struct xfrm_mgr *km;
2233 
2234 	rcu_read_lock();
2235 	list_for_each_entry_rcu(km, &xfrm_km_list, list) {
2236 		if (km->report) {
2237 			ret = km->report(net, proto, sel, addr);
2238 			if (!ret)
2239 				err = ret;
2240 		}
2241 	}
2242 	rcu_read_unlock();
2243 	return err;
2244 }
2245 EXPORT_SYMBOL(km_report);
2246 
2247 static bool km_is_alive(const struct km_event *c)
2248 {
2249 	struct xfrm_mgr *km;
2250 	bool is_alive = false;
2251 
2252 	rcu_read_lock();
2253 	list_for_each_entry_rcu(km, &xfrm_km_list, list) {
2254 		if (km->is_alive && km->is_alive(c)) {
2255 			is_alive = true;
2256 			break;
2257 		}
2258 	}
2259 	rcu_read_unlock();
2260 
2261 	return is_alive;
2262 }
2263 
2264 int xfrm_user_policy(struct sock *sk, int optname, u8 __user *optval, int optlen)
2265 {
2266 	int err;
2267 	u8 *data;
2268 	struct xfrm_mgr *km;
2269 	struct xfrm_policy *pol = NULL;
2270 
2271 	if (in_compat_syscall())
2272 		return -EOPNOTSUPP;
2273 
2274 	if (!optval && !optlen) {
2275 		xfrm_sk_policy_insert(sk, XFRM_POLICY_IN, NULL);
2276 		xfrm_sk_policy_insert(sk, XFRM_POLICY_OUT, NULL);
2277 		__sk_dst_reset(sk);
2278 		return 0;
2279 	}
2280 
2281 	if (optlen <= 0 || optlen > PAGE_SIZE)
2282 		return -EMSGSIZE;
2283 
2284 	data = memdup_user(optval, optlen);
2285 	if (IS_ERR(data))
2286 		return PTR_ERR(data);
2287 
2288 	err = -EINVAL;
2289 	rcu_read_lock();
2290 	list_for_each_entry_rcu(km, &xfrm_km_list, list) {
2291 		pol = km->compile_policy(sk, optname, data,
2292 					 optlen, &err);
2293 		if (err >= 0)
2294 			break;
2295 	}
2296 	rcu_read_unlock();
2297 
2298 	if (err >= 0) {
2299 		xfrm_sk_policy_insert(sk, err, pol);
2300 		xfrm_pol_put(pol);
2301 		__sk_dst_reset(sk);
2302 		err = 0;
2303 	}
2304 
2305 	kfree(data);
2306 	return err;
2307 }
2308 EXPORT_SYMBOL(xfrm_user_policy);
2309 
2310 static DEFINE_SPINLOCK(xfrm_km_lock);
2311 
2312 int xfrm_register_km(struct xfrm_mgr *km)
2313 {
2314 	spin_lock_bh(&xfrm_km_lock);
2315 	list_add_tail_rcu(&km->list, &xfrm_km_list);
2316 	spin_unlock_bh(&xfrm_km_lock);
2317 	return 0;
2318 }
2319 EXPORT_SYMBOL(xfrm_register_km);
2320 
2321 int xfrm_unregister_km(struct xfrm_mgr *km)
2322 {
2323 	spin_lock_bh(&xfrm_km_lock);
2324 	list_del_rcu(&km->list);
2325 	spin_unlock_bh(&xfrm_km_lock);
2326 	synchronize_rcu();
2327 	return 0;
2328 }
2329 EXPORT_SYMBOL(xfrm_unregister_km);
2330 
2331 int xfrm_state_register_afinfo(struct xfrm_state_afinfo *afinfo)
2332 {
2333 	int err = 0;
2334 
2335 	if (WARN_ON(afinfo->family >= NPROTO))
2336 		return -EAFNOSUPPORT;
2337 
2338 	spin_lock_bh(&xfrm_state_afinfo_lock);
2339 	if (unlikely(xfrm_state_afinfo[afinfo->family] != NULL))
2340 		err = -EEXIST;
2341 	else
2342 		rcu_assign_pointer(xfrm_state_afinfo[afinfo->family], afinfo);
2343 	spin_unlock_bh(&xfrm_state_afinfo_lock);
2344 	return err;
2345 }
2346 EXPORT_SYMBOL(xfrm_state_register_afinfo);
2347 
2348 int xfrm_state_unregister_afinfo(struct xfrm_state_afinfo *afinfo)
2349 {
2350 	int err = 0, family = afinfo->family;
2351 
2352 	if (WARN_ON(family >= NPROTO))
2353 		return -EAFNOSUPPORT;
2354 
2355 	spin_lock_bh(&xfrm_state_afinfo_lock);
2356 	if (likely(xfrm_state_afinfo[afinfo->family] != NULL)) {
2357 		if (rcu_access_pointer(xfrm_state_afinfo[family]) != afinfo)
2358 			err = -EINVAL;
2359 		else
2360 			RCU_INIT_POINTER(xfrm_state_afinfo[afinfo->family], NULL);
2361 	}
2362 	spin_unlock_bh(&xfrm_state_afinfo_lock);
2363 	synchronize_rcu();
2364 	return err;
2365 }
2366 EXPORT_SYMBOL(xfrm_state_unregister_afinfo);
2367 
2368 struct xfrm_state_afinfo *xfrm_state_afinfo_get_rcu(unsigned int family)
2369 {
2370 	if (unlikely(family >= NPROTO))
2371 		return NULL;
2372 
2373 	return rcu_dereference(xfrm_state_afinfo[family]);
2374 }
2375 EXPORT_SYMBOL_GPL(xfrm_state_afinfo_get_rcu);
2376 
2377 struct xfrm_state_afinfo *xfrm_state_get_afinfo(unsigned int family)
2378 {
2379 	struct xfrm_state_afinfo *afinfo;
2380 	if (unlikely(family >= NPROTO))
2381 		return NULL;
2382 	rcu_read_lock();
2383 	afinfo = rcu_dereference(xfrm_state_afinfo[family]);
2384 	if (unlikely(!afinfo))
2385 		rcu_read_unlock();
2386 	return afinfo;
2387 }
2388 
2389 void xfrm_flush_gc(void)
2390 {
2391 	flush_work(&xfrm_state_gc_work);
2392 }
2393 EXPORT_SYMBOL(xfrm_flush_gc);
2394 
2395 /* Temporarily located here until net/xfrm/xfrm_tunnel.c is created */
2396 void xfrm_state_delete_tunnel(struct xfrm_state *x)
2397 {
2398 	if (x->tunnel) {
2399 		struct xfrm_state *t = x->tunnel;
2400 
2401 		if (atomic_read(&t->tunnel_users) == 2)
2402 			xfrm_state_delete(t);
2403 		atomic_dec(&t->tunnel_users);
2404 		xfrm_state_put_sync(t);
2405 		x->tunnel = NULL;
2406 	}
2407 }
2408 EXPORT_SYMBOL(xfrm_state_delete_tunnel);
2409 
2410 u32 xfrm_state_mtu(struct xfrm_state *x, int mtu)
2411 {
2412 	const struct xfrm_type *type = READ_ONCE(x->type);
2413 	struct crypto_aead *aead;
2414 	u32 blksize, net_adj = 0;
2415 
2416 	if (x->km.state != XFRM_STATE_VALID ||
2417 	    !type || type->proto != IPPROTO_ESP)
2418 		return mtu - x->props.header_len;
2419 
2420 	aead = x->data;
2421 	blksize = ALIGN(crypto_aead_blocksize(aead), 4);
2422 
2423 	switch (x->props.mode) {
2424 	case XFRM_MODE_TRANSPORT:
2425 	case XFRM_MODE_BEET:
2426 		if (x->props.family == AF_INET)
2427 			net_adj = sizeof(struct iphdr);
2428 		else if (x->props.family == AF_INET6)
2429 			net_adj = sizeof(struct ipv6hdr);
2430 		break;
2431 	case XFRM_MODE_TUNNEL:
2432 		break;
2433 	default:
2434 		WARN_ON_ONCE(1);
2435 		break;
2436 	}
2437 
2438 	return ((mtu - x->props.header_len - crypto_aead_authsize(aead) -
2439 		 net_adj) & ~(blksize - 1)) + net_adj - 2;
2440 }
2441 EXPORT_SYMBOL_GPL(xfrm_state_mtu);
2442 
2443 int __xfrm_init_state(struct xfrm_state *x, bool init_replay, bool offload)
2444 {
2445 	const struct xfrm_mode *inner_mode;
2446 	const struct xfrm_mode *outer_mode;
2447 	int family = x->props.family;
2448 	int err;
2449 
2450 	if (family == AF_INET &&
2451 	    xs_net(x)->ipv4.sysctl_ip_no_pmtu_disc)
2452 		x->props.flags |= XFRM_STATE_NOPMTUDISC;
2453 
2454 	err = -EPROTONOSUPPORT;
2455 
2456 	if (x->sel.family != AF_UNSPEC) {
2457 		inner_mode = xfrm_get_mode(x->props.mode, x->sel.family);
2458 		if (inner_mode == NULL)
2459 			goto error;
2460 
2461 		if (!(inner_mode->flags & XFRM_MODE_FLAG_TUNNEL) &&
2462 		    family != x->sel.family)
2463 			goto error;
2464 
2465 		x->inner_mode = *inner_mode;
2466 	} else {
2467 		const struct xfrm_mode *inner_mode_iaf;
2468 		int iafamily = AF_INET;
2469 
2470 		inner_mode = xfrm_get_mode(x->props.mode, x->props.family);
2471 		if (inner_mode == NULL)
2472 			goto error;
2473 
2474 		if (!(inner_mode->flags & XFRM_MODE_FLAG_TUNNEL))
2475 			goto error;
2476 
2477 		x->inner_mode = *inner_mode;
2478 
2479 		if (x->props.family == AF_INET)
2480 			iafamily = AF_INET6;
2481 
2482 		inner_mode_iaf = xfrm_get_mode(x->props.mode, iafamily);
2483 		if (inner_mode_iaf) {
2484 			if (inner_mode_iaf->flags & XFRM_MODE_FLAG_TUNNEL)
2485 				x->inner_mode_iaf = *inner_mode_iaf;
2486 		}
2487 	}
2488 
2489 	x->type = xfrm_get_type(x->id.proto, family);
2490 	if (x->type == NULL)
2491 		goto error;
2492 
2493 	x->type_offload = xfrm_get_type_offload(x->id.proto, family, offload);
2494 
2495 	err = x->type->init_state(x);
2496 	if (err)
2497 		goto error;
2498 
2499 	outer_mode = xfrm_get_mode(x->props.mode, family);
2500 	if (!outer_mode) {
2501 		err = -EPROTONOSUPPORT;
2502 		goto error;
2503 	}
2504 
2505 	x->outer_mode = *outer_mode;
2506 	if (init_replay) {
2507 		err = xfrm_init_replay(x);
2508 		if (err)
2509 			goto error;
2510 	}
2511 
2512 error:
2513 	return err;
2514 }
2515 
2516 EXPORT_SYMBOL(__xfrm_init_state);
2517 
2518 int xfrm_init_state(struct xfrm_state *x)
2519 {
2520 	int err;
2521 
2522 	err = __xfrm_init_state(x, true, false);
2523 	if (!err)
2524 		x->km.state = XFRM_STATE_VALID;
2525 
2526 	return err;
2527 }
2528 
2529 EXPORT_SYMBOL(xfrm_init_state);
2530 
2531 int __net_init xfrm_state_init(struct net *net)
2532 {
2533 	unsigned int sz;
2534 
2535 	if (net_eq(net, &init_net))
2536 		xfrm_state_cache = KMEM_CACHE(xfrm_state,
2537 					      SLAB_HWCACHE_ALIGN | SLAB_PANIC);
2538 
2539 	INIT_LIST_HEAD(&net->xfrm.state_all);
2540 
2541 	sz = sizeof(struct hlist_head) * 8;
2542 
2543 	net->xfrm.state_bydst = xfrm_hash_alloc(sz);
2544 	if (!net->xfrm.state_bydst)
2545 		goto out_bydst;
2546 	net->xfrm.state_bysrc = xfrm_hash_alloc(sz);
2547 	if (!net->xfrm.state_bysrc)
2548 		goto out_bysrc;
2549 	net->xfrm.state_byspi = xfrm_hash_alloc(sz);
2550 	if (!net->xfrm.state_byspi)
2551 		goto out_byspi;
2552 	net->xfrm.state_hmask = ((sz / sizeof(struct hlist_head)) - 1);
2553 
2554 	net->xfrm.state_num = 0;
2555 	INIT_WORK(&net->xfrm.state_hash_work, xfrm_hash_resize);
2556 	spin_lock_init(&net->xfrm.xfrm_state_lock);
2557 	return 0;
2558 
2559 out_byspi:
2560 	xfrm_hash_free(net->xfrm.state_bysrc, sz);
2561 out_bysrc:
2562 	xfrm_hash_free(net->xfrm.state_bydst, sz);
2563 out_bydst:
2564 	return -ENOMEM;
2565 }
2566 
2567 void xfrm_state_fini(struct net *net)
2568 {
2569 	unsigned int sz;
2570 
2571 	flush_work(&net->xfrm.state_hash_work);
2572 	flush_work(&xfrm_state_gc_work);
2573 	xfrm_state_flush(net, 0, false, true);
2574 
2575 	WARN_ON(!list_empty(&net->xfrm.state_all));
2576 
2577 	sz = (net->xfrm.state_hmask + 1) * sizeof(struct hlist_head);
2578 	WARN_ON(!hlist_empty(net->xfrm.state_byspi));
2579 	xfrm_hash_free(net->xfrm.state_byspi, sz);
2580 	WARN_ON(!hlist_empty(net->xfrm.state_bysrc));
2581 	xfrm_hash_free(net->xfrm.state_bysrc, sz);
2582 	WARN_ON(!hlist_empty(net->xfrm.state_bydst));
2583 	xfrm_hash_free(net->xfrm.state_bydst, sz);
2584 }
2585 
2586 #ifdef CONFIG_AUDITSYSCALL
2587 static void xfrm_audit_helper_sainfo(struct xfrm_state *x,
2588 				     struct audit_buffer *audit_buf)
2589 {
2590 	struct xfrm_sec_ctx *ctx = x->security;
2591 	u32 spi = ntohl(x->id.spi);
2592 
2593 	if (ctx)
2594 		audit_log_format(audit_buf, " sec_alg=%u sec_doi=%u sec_obj=%s",
2595 				 ctx->ctx_alg, ctx->ctx_doi, ctx->ctx_str);
2596 
2597 	switch (x->props.family) {
2598 	case AF_INET:
2599 		audit_log_format(audit_buf, " src=%pI4 dst=%pI4",
2600 				 &x->props.saddr.a4, &x->id.daddr.a4);
2601 		break;
2602 	case AF_INET6:
2603 		audit_log_format(audit_buf, " src=%pI6 dst=%pI6",
2604 				 x->props.saddr.a6, x->id.daddr.a6);
2605 		break;
2606 	}
2607 
2608 	audit_log_format(audit_buf, " spi=%u(0x%x)", spi, spi);
2609 }
2610 
2611 static void xfrm_audit_helper_pktinfo(struct sk_buff *skb, u16 family,
2612 				      struct audit_buffer *audit_buf)
2613 {
2614 	const struct iphdr *iph4;
2615 	const struct ipv6hdr *iph6;
2616 
2617 	switch (family) {
2618 	case AF_INET:
2619 		iph4 = ip_hdr(skb);
2620 		audit_log_format(audit_buf, " src=%pI4 dst=%pI4",
2621 				 &iph4->saddr, &iph4->daddr);
2622 		break;
2623 	case AF_INET6:
2624 		iph6 = ipv6_hdr(skb);
2625 		audit_log_format(audit_buf,
2626 				 " src=%pI6 dst=%pI6 flowlbl=0x%x%02x%02x",
2627 				 &iph6->saddr, &iph6->daddr,
2628 				 iph6->flow_lbl[0] & 0x0f,
2629 				 iph6->flow_lbl[1],
2630 				 iph6->flow_lbl[2]);
2631 		break;
2632 	}
2633 }
2634 
2635 void xfrm_audit_state_add(struct xfrm_state *x, int result, bool task_valid)
2636 {
2637 	struct audit_buffer *audit_buf;
2638 
2639 	audit_buf = xfrm_audit_start("SAD-add");
2640 	if (audit_buf == NULL)
2641 		return;
2642 	xfrm_audit_helper_usrinfo(task_valid, audit_buf);
2643 	xfrm_audit_helper_sainfo(x, audit_buf);
2644 	audit_log_format(audit_buf, " res=%u", result);
2645 	audit_log_end(audit_buf);
2646 }
2647 EXPORT_SYMBOL_GPL(xfrm_audit_state_add);
2648 
2649 void xfrm_audit_state_delete(struct xfrm_state *x, int result, bool task_valid)
2650 {
2651 	struct audit_buffer *audit_buf;
2652 
2653 	audit_buf = xfrm_audit_start("SAD-delete");
2654 	if (audit_buf == NULL)
2655 		return;
2656 	xfrm_audit_helper_usrinfo(task_valid, audit_buf);
2657 	xfrm_audit_helper_sainfo(x, audit_buf);
2658 	audit_log_format(audit_buf, " res=%u", result);
2659 	audit_log_end(audit_buf);
2660 }
2661 EXPORT_SYMBOL_GPL(xfrm_audit_state_delete);
2662 
2663 void xfrm_audit_state_replay_overflow(struct xfrm_state *x,
2664 				      struct sk_buff *skb)
2665 {
2666 	struct audit_buffer *audit_buf;
2667 	u32 spi;
2668 
2669 	audit_buf = xfrm_audit_start("SA-replay-overflow");
2670 	if (audit_buf == NULL)
2671 		return;
2672 	xfrm_audit_helper_pktinfo(skb, x->props.family, audit_buf);
2673 	/* don't record the sequence number because it's inherent in this kind
2674 	 * of audit message */
2675 	spi = ntohl(x->id.spi);
2676 	audit_log_format(audit_buf, " spi=%u(0x%x)", spi, spi);
2677 	audit_log_end(audit_buf);
2678 }
2679 EXPORT_SYMBOL_GPL(xfrm_audit_state_replay_overflow);
2680 
2681 void xfrm_audit_state_replay(struct xfrm_state *x,
2682 			     struct sk_buff *skb, __be32 net_seq)
2683 {
2684 	struct audit_buffer *audit_buf;
2685 	u32 spi;
2686 
2687 	audit_buf = xfrm_audit_start("SA-replayed-pkt");
2688 	if (audit_buf == NULL)
2689 		return;
2690 	xfrm_audit_helper_pktinfo(skb, x->props.family, audit_buf);
2691 	spi = ntohl(x->id.spi);
2692 	audit_log_format(audit_buf, " spi=%u(0x%x) seqno=%u",
2693 			 spi, spi, ntohl(net_seq));
2694 	audit_log_end(audit_buf);
2695 }
2696 EXPORT_SYMBOL_GPL(xfrm_audit_state_replay);
2697 
2698 void xfrm_audit_state_notfound_simple(struct sk_buff *skb, u16 family)
2699 {
2700 	struct audit_buffer *audit_buf;
2701 
2702 	audit_buf = xfrm_audit_start("SA-notfound");
2703 	if (audit_buf == NULL)
2704 		return;
2705 	xfrm_audit_helper_pktinfo(skb, family, audit_buf);
2706 	audit_log_end(audit_buf);
2707 }
2708 EXPORT_SYMBOL_GPL(xfrm_audit_state_notfound_simple);
2709 
2710 void xfrm_audit_state_notfound(struct sk_buff *skb, u16 family,
2711 			       __be32 net_spi, __be32 net_seq)
2712 {
2713 	struct audit_buffer *audit_buf;
2714 	u32 spi;
2715 
2716 	audit_buf = xfrm_audit_start("SA-notfound");
2717 	if (audit_buf == NULL)
2718 		return;
2719 	xfrm_audit_helper_pktinfo(skb, family, audit_buf);
2720 	spi = ntohl(net_spi);
2721 	audit_log_format(audit_buf, " spi=%u(0x%x) seqno=%u",
2722 			 spi, spi, ntohl(net_seq));
2723 	audit_log_end(audit_buf);
2724 }
2725 EXPORT_SYMBOL_GPL(xfrm_audit_state_notfound);
2726 
2727 void xfrm_audit_state_icvfail(struct xfrm_state *x,
2728 			      struct sk_buff *skb, u8 proto)
2729 {
2730 	struct audit_buffer *audit_buf;
2731 	__be32 net_spi;
2732 	__be32 net_seq;
2733 
2734 	audit_buf = xfrm_audit_start("SA-icv-failure");
2735 	if (audit_buf == NULL)
2736 		return;
2737 	xfrm_audit_helper_pktinfo(skb, x->props.family, audit_buf);
2738 	if (xfrm_parse_spi(skb, proto, &net_spi, &net_seq) == 0) {
2739 		u32 spi = ntohl(net_spi);
2740 		audit_log_format(audit_buf, " spi=%u(0x%x) seqno=%u",
2741 				 spi, spi, ntohl(net_seq));
2742 	}
2743 	audit_log_end(audit_buf);
2744 }
2745 EXPORT_SYMBOL_GPL(xfrm_audit_state_icvfail);
2746 #endif /* CONFIG_AUDITSYSCALL */
2747