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