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