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