xref: /openbmc/linux/net/xfrm/xfrm_policy.c (revision 22fd411a)
1 /*
2  * xfrm_policy.c
3  *
4  * Changes:
5  *	Mitsuru KANDA @USAGI
6  * 	Kazunori MIYAZAWA @USAGI
7  * 	Kunihiro Ishiguro <kunihiro@ipinfusion.com>
8  * 		IPv6 support
9  * 	Kazunori MIYAZAWA @USAGI
10  * 	YOSHIFUJI Hideaki
11  * 		Split up af-specific portion
12  *	Derek Atkins <derek@ihtfp.com>		Add the post_input processor
13  *
14  */
15 
16 #include <linux/err.h>
17 #include <linux/slab.h>
18 #include <linux/kmod.h>
19 #include <linux/list.h>
20 #include <linux/spinlock.h>
21 #include <linux/workqueue.h>
22 #include <linux/notifier.h>
23 #include <linux/netdevice.h>
24 #include <linux/netfilter.h>
25 #include <linux/module.h>
26 #include <linux/cache.h>
27 #include <linux/audit.h>
28 #include <net/dst.h>
29 #include <net/xfrm.h>
30 #include <net/ip.h>
31 #ifdef CONFIG_XFRM_STATISTICS
32 #include <net/snmp.h>
33 #endif
34 
35 #include "xfrm_hash.h"
36 
37 DEFINE_MUTEX(xfrm_cfg_mutex);
38 EXPORT_SYMBOL(xfrm_cfg_mutex);
39 
40 static DEFINE_SPINLOCK(xfrm_policy_sk_bundle_lock);
41 static struct dst_entry *xfrm_policy_sk_bundles;
42 static DEFINE_RWLOCK(xfrm_policy_lock);
43 
44 static DEFINE_RWLOCK(xfrm_policy_afinfo_lock);
45 static struct xfrm_policy_afinfo *xfrm_policy_afinfo[NPROTO];
46 
47 static struct kmem_cache *xfrm_dst_cache __read_mostly;
48 
49 static struct xfrm_policy_afinfo *xfrm_policy_get_afinfo(unsigned short family);
50 static void xfrm_policy_put_afinfo(struct xfrm_policy_afinfo *afinfo);
51 static void xfrm_init_pmtu(struct dst_entry *dst);
52 static int stale_bundle(struct dst_entry *dst);
53 static int xfrm_bundle_ok(struct xfrm_policy *pol, struct xfrm_dst *xdst,
54 			  struct flowi *fl, int family, int strict);
55 
56 
57 static struct xfrm_policy *__xfrm_policy_unlink(struct xfrm_policy *pol,
58 						int dir);
59 
60 static inline int
61 __xfrm4_selector_match(struct xfrm_selector *sel, struct flowi *fl)
62 {
63 	return  addr_match(&fl->fl4_dst, &sel->daddr, sel->prefixlen_d) &&
64 		addr_match(&fl->fl4_src, &sel->saddr, sel->prefixlen_s) &&
65 		!((xfrm_flowi_dport(fl) ^ sel->dport) & sel->dport_mask) &&
66 		!((xfrm_flowi_sport(fl) ^ sel->sport) & sel->sport_mask) &&
67 		(fl->proto == sel->proto || !sel->proto) &&
68 		(fl->oif == sel->ifindex || !sel->ifindex);
69 }
70 
71 static inline int
72 __xfrm6_selector_match(struct xfrm_selector *sel, struct flowi *fl)
73 {
74 	return  addr_match(&fl->fl6_dst, &sel->daddr, sel->prefixlen_d) &&
75 		addr_match(&fl->fl6_src, &sel->saddr, sel->prefixlen_s) &&
76 		!((xfrm_flowi_dport(fl) ^ sel->dport) & sel->dport_mask) &&
77 		!((xfrm_flowi_sport(fl) ^ sel->sport) & sel->sport_mask) &&
78 		(fl->proto == sel->proto || !sel->proto) &&
79 		(fl->oif == sel->ifindex || !sel->ifindex);
80 }
81 
82 int xfrm_selector_match(struct xfrm_selector *sel, struct flowi *fl,
83 		    unsigned short family)
84 {
85 	switch (family) {
86 	case AF_INET:
87 		return __xfrm4_selector_match(sel, fl);
88 	case AF_INET6:
89 		return __xfrm6_selector_match(sel, fl);
90 	}
91 	return 0;
92 }
93 
94 static inline struct dst_entry *__xfrm_dst_lookup(struct net *net, int tos,
95 						  xfrm_address_t *saddr,
96 						  xfrm_address_t *daddr,
97 						  int family)
98 {
99 	struct xfrm_policy_afinfo *afinfo;
100 	struct dst_entry *dst;
101 
102 	afinfo = xfrm_policy_get_afinfo(family);
103 	if (unlikely(afinfo == NULL))
104 		return ERR_PTR(-EAFNOSUPPORT);
105 
106 	dst = afinfo->dst_lookup(net, tos, saddr, daddr);
107 
108 	xfrm_policy_put_afinfo(afinfo);
109 
110 	return dst;
111 }
112 
113 static inline struct dst_entry *xfrm_dst_lookup(struct xfrm_state *x, int tos,
114 						xfrm_address_t *prev_saddr,
115 						xfrm_address_t *prev_daddr,
116 						int family)
117 {
118 	struct net *net = xs_net(x);
119 	xfrm_address_t *saddr = &x->props.saddr;
120 	xfrm_address_t *daddr = &x->id.daddr;
121 	struct dst_entry *dst;
122 
123 	if (x->type->flags & XFRM_TYPE_LOCAL_COADDR) {
124 		saddr = x->coaddr;
125 		daddr = prev_daddr;
126 	}
127 	if (x->type->flags & XFRM_TYPE_REMOTE_COADDR) {
128 		saddr = prev_saddr;
129 		daddr = x->coaddr;
130 	}
131 
132 	dst = __xfrm_dst_lookup(net, tos, saddr, daddr, family);
133 
134 	if (!IS_ERR(dst)) {
135 		if (prev_saddr != saddr)
136 			memcpy(prev_saddr, saddr,  sizeof(*prev_saddr));
137 		if (prev_daddr != daddr)
138 			memcpy(prev_daddr, daddr,  sizeof(*prev_daddr));
139 	}
140 
141 	return dst;
142 }
143 
144 static inline unsigned long make_jiffies(long secs)
145 {
146 	if (secs >= (MAX_SCHEDULE_TIMEOUT-1)/HZ)
147 		return MAX_SCHEDULE_TIMEOUT-1;
148 	else
149 		return secs*HZ;
150 }
151 
152 static void xfrm_policy_timer(unsigned long data)
153 {
154 	struct xfrm_policy *xp = (struct xfrm_policy*)data;
155 	unsigned long now = get_seconds();
156 	long next = LONG_MAX;
157 	int warn = 0;
158 	int dir;
159 
160 	read_lock(&xp->lock);
161 
162 	if (unlikely(xp->walk.dead))
163 		goto out;
164 
165 	dir = xfrm_policy_id2dir(xp->index);
166 
167 	if (xp->lft.hard_add_expires_seconds) {
168 		long tmo = xp->lft.hard_add_expires_seconds +
169 			xp->curlft.add_time - now;
170 		if (tmo <= 0)
171 			goto expired;
172 		if (tmo < next)
173 			next = tmo;
174 	}
175 	if (xp->lft.hard_use_expires_seconds) {
176 		long tmo = xp->lft.hard_use_expires_seconds +
177 			(xp->curlft.use_time ? : xp->curlft.add_time) - now;
178 		if (tmo <= 0)
179 			goto expired;
180 		if (tmo < next)
181 			next = tmo;
182 	}
183 	if (xp->lft.soft_add_expires_seconds) {
184 		long tmo = xp->lft.soft_add_expires_seconds +
185 			xp->curlft.add_time - now;
186 		if (tmo <= 0) {
187 			warn = 1;
188 			tmo = XFRM_KM_TIMEOUT;
189 		}
190 		if (tmo < next)
191 			next = tmo;
192 	}
193 	if (xp->lft.soft_use_expires_seconds) {
194 		long tmo = xp->lft.soft_use_expires_seconds +
195 			(xp->curlft.use_time ? : xp->curlft.add_time) - now;
196 		if (tmo <= 0) {
197 			warn = 1;
198 			tmo = XFRM_KM_TIMEOUT;
199 		}
200 		if (tmo < next)
201 			next = tmo;
202 	}
203 
204 	if (warn)
205 		km_policy_expired(xp, dir, 0, 0);
206 	if (next != LONG_MAX &&
207 	    !mod_timer(&xp->timer, jiffies + make_jiffies(next)))
208 		xfrm_pol_hold(xp);
209 
210 out:
211 	read_unlock(&xp->lock);
212 	xfrm_pol_put(xp);
213 	return;
214 
215 expired:
216 	read_unlock(&xp->lock);
217 	if (!xfrm_policy_delete(xp, dir))
218 		km_policy_expired(xp, dir, 1, 0);
219 	xfrm_pol_put(xp);
220 }
221 
222 static struct flow_cache_object *xfrm_policy_flo_get(struct flow_cache_object *flo)
223 {
224 	struct xfrm_policy *pol = container_of(flo, struct xfrm_policy, flo);
225 
226 	if (unlikely(pol->walk.dead))
227 		flo = NULL;
228 	else
229 		xfrm_pol_hold(pol);
230 
231 	return flo;
232 }
233 
234 static int xfrm_policy_flo_check(struct flow_cache_object *flo)
235 {
236 	struct xfrm_policy *pol = container_of(flo, struct xfrm_policy, flo);
237 
238 	return !pol->walk.dead;
239 }
240 
241 static void xfrm_policy_flo_delete(struct flow_cache_object *flo)
242 {
243 	xfrm_pol_put(container_of(flo, struct xfrm_policy, flo));
244 }
245 
246 static const struct flow_cache_ops xfrm_policy_fc_ops = {
247 	.get = xfrm_policy_flo_get,
248 	.check = xfrm_policy_flo_check,
249 	.delete = xfrm_policy_flo_delete,
250 };
251 
252 /* Allocate xfrm_policy. Not used here, it is supposed to be used by pfkeyv2
253  * SPD calls.
254  */
255 
256 struct xfrm_policy *xfrm_policy_alloc(struct net *net, gfp_t gfp)
257 {
258 	struct xfrm_policy *policy;
259 
260 	policy = kzalloc(sizeof(struct xfrm_policy), gfp);
261 
262 	if (policy) {
263 		write_pnet(&policy->xp_net, net);
264 		INIT_LIST_HEAD(&policy->walk.all);
265 		INIT_HLIST_NODE(&policy->bydst);
266 		INIT_HLIST_NODE(&policy->byidx);
267 		rwlock_init(&policy->lock);
268 		atomic_set(&policy->refcnt, 1);
269 		setup_timer(&policy->timer, xfrm_policy_timer,
270 				(unsigned long)policy);
271 		policy->flo.ops = &xfrm_policy_fc_ops;
272 	}
273 	return policy;
274 }
275 EXPORT_SYMBOL(xfrm_policy_alloc);
276 
277 /* Destroy xfrm_policy: descendant resources must be released to this moment. */
278 
279 void xfrm_policy_destroy(struct xfrm_policy *policy)
280 {
281 	BUG_ON(!policy->walk.dead);
282 
283 	if (del_timer(&policy->timer))
284 		BUG();
285 
286 	security_xfrm_policy_free(policy->security);
287 	kfree(policy);
288 }
289 EXPORT_SYMBOL(xfrm_policy_destroy);
290 
291 /* Rule must be locked. Release descentant resources, announce
292  * entry dead. The rule must be unlinked from lists to the moment.
293  */
294 
295 static void xfrm_policy_kill(struct xfrm_policy *policy)
296 {
297 	policy->walk.dead = 1;
298 
299 	atomic_inc(&policy->genid);
300 
301 	if (del_timer(&policy->timer))
302 		xfrm_pol_put(policy);
303 
304 	xfrm_pol_put(policy);
305 }
306 
307 static unsigned int xfrm_policy_hashmax __read_mostly = 1 * 1024 * 1024;
308 
309 static inline unsigned int idx_hash(struct net *net, u32 index)
310 {
311 	return __idx_hash(index, net->xfrm.policy_idx_hmask);
312 }
313 
314 static struct hlist_head *policy_hash_bysel(struct net *net, struct xfrm_selector *sel, unsigned short family, int dir)
315 {
316 	unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
317 	unsigned int hash = __sel_hash(sel, family, hmask);
318 
319 	return (hash == hmask + 1 ?
320 		&net->xfrm.policy_inexact[dir] :
321 		net->xfrm.policy_bydst[dir].table + hash);
322 }
323 
324 static struct hlist_head *policy_hash_direct(struct net *net, xfrm_address_t *daddr, xfrm_address_t *saddr, unsigned short family, int dir)
325 {
326 	unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
327 	unsigned int hash = __addr_hash(daddr, saddr, family, hmask);
328 
329 	return net->xfrm.policy_bydst[dir].table + hash;
330 }
331 
332 static void xfrm_dst_hash_transfer(struct hlist_head *list,
333 				   struct hlist_head *ndsttable,
334 				   unsigned int nhashmask)
335 {
336 	struct hlist_node *entry, *tmp, *entry0 = NULL;
337 	struct xfrm_policy *pol;
338 	unsigned int h0 = 0;
339 
340 redo:
341 	hlist_for_each_entry_safe(pol, entry, tmp, list, bydst) {
342 		unsigned int h;
343 
344 		h = __addr_hash(&pol->selector.daddr, &pol->selector.saddr,
345 				pol->family, nhashmask);
346 		if (!entry0) {
347 			hlist_del(entry);
348 			hlist_add_head(&pol->bydst, ndsttable+h);
349 			h0 = h;
350 		} else {
351 			if (h != h0)
352 				continue;
353 			hlist_del(entry);
354 			hlist_add_after(entry0, &pol->bydst);
355 		}
356 		entry0 = entry;
357 	}
358 	if (!hlist_empty(list)) {
359 		entry0 = NULL;
360 		goto redo;
361 	}
362 }
363 
364 static void xfrm_idx_hash_transfer(struct hlist_head *list,
365 				   struct hlist_head *nidxtable,
366 				   unsigned int nhashmask)
367 {
368 	struct hlist_node *entry, *tmp;
369 	struct xfrm_policy *pol;
370 
371 	hlist_for_each_entry_safe(pol, entry, tmp, list, byidx) {
372 		unsigned int h;
373 
374 		h = __idx_hash(pol->index, nhashmask);
375 		hlist_add_head(&pol->byidx, nidxtable+h);
376 	}
377 }
378 
379 static unsigned long xfrm_new_hash_mask(unsigned int old_hmask)
380 {
381 	return ((old_hmask + 1) << 1) - 1;
382 }
383 
384 static void xfrm_bydst_resize(struct net *net, int dir)
385 {
386 	unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
387 	unsigned int nhashmask = xfrm_new_hash_mask(hmask);
388 	unsigned int nsize = (nhashmask + 1) * sizeof(struct hlist_head);
389 	struct hlist_head *odst = net->xfrm.policy_bydst[dir].table;
390 	struct hlist_head *ndst = xfrm_hash_alloc(nsize);
391 	int i;
392 
393 	if (!ndst)
394 		return;
395 
396 	write_lock_bh(&xfrm_policy_lock);
397 
398 	for (i = hmask; i >= 0; i--)
399 		xfrm_dst_hash_transfer(odst + i, ndst, nhashmask);
400 
401 	net->xfrm.policy_bydst[dir].table = ndst;
402 	net->xfrm.policy_bydst[dir].hmask = nhashmask;
403 
404 	write_unlock_bh(&xfrm_policy_lock);
405 
406 	xfrm_hash_free(odst, (hmask + 1) * sizeof(struct hlist_head));
407 }
408 
409 static void xfrm_byidx_resize(struct net *net, int total)
410 {
411 	unsigned int hmask = net->xfrm.policy_idx_hmask;
412 	unsigned int nhashmask = xfrm_new_hash_mask(hmask);
413 	unsigned int nsize = (nhashmask + 1) * sizeof(struct hlist_head);
414 	struct hlist_head *oidx = net->xfrm.policy_byidx;
415 	struct hlist_head *nidx = xfrm_hash_alloc(nsize);
416 	int i;
417 
418 	if (!nidx)
419 		return;
420 
421 	write_lock_bh(&xfrm_policy_lock);
422 
423 	for (i = hmask; i >= 0; i--)
424 		xfrm_idx_hash_transfer(oidx + i, nidx, nhashmask);
425 
426 	net->xfrm.policy_byidx = nidx;
427 	net->xfrm.policy_idx_hmask = nhashmask;
428 
429 	write_unlock_bh(&xfrm_policy_lock);
430 
431 	xfrm_hash_free(oidx, (hmask + 1) * sizeof(struct hlist_head));
432 }
433 
434 static inline int xfrm_bydst_should_resize(struct net *net, int dir, int *total)
435 {
436 	unsigned int cnt = net->xfrm.policy_count[dir];
437 	unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
438 
439 	if (total)
440 		*total += cnt;
441 
442 	if ((hmask + 1) < xfrm_policy_hashmax &&
443 	    cnt > hmask)
444 		return 1;
445 
446 	return 0;
447 }
448 
449 static inline int xfrm_byidx_should_resize(struct net *net, int total)
450 {
451 	unsigned int hmask = net->xfrm.policy_idx_hmask;
452 
453 	if ((hmask + 1) < xfrm_policy_hashmax &&
454 	    total > hmask)
455 		return 1;
456 
457 	return 0;
458 }
459 
460 void xfrm_spd_getinfo(struct net *net, struct xfrmk_spdinfo *si)
461 {
462 	read_lock_bh(&xfrm_policy_lock);
463 	si->incnt = net->xfrm.policy_count[XFRM_POLICY_IN];
464 	si->outcnt = net->xfrm.policy_count[XFRM_POLICY_OUT];
465 	si->fwdcnt = net->xfrm.policy_count[XFRM_POLICY_FWD];
466 	si->inscnt = net->xfrm.policy_count[XFRM_POLICY_IN+XFRM_POLICY_MAX];
467 	si->outscnt = net->xfrm.policy_count[XFRM_POLICY_OUT+XFRM_POLICY_MAX];
468 	si->fwdscnt = net->xfrm.policy_count[XFRM_POLICY_FWD+XFRM_POLICY_MAX];
469 	si->spdhcnt = net->xfrm.policy_idx_hmask;
470 	si->spdhmcnt = xfrm_policy_hashmax;
471 	read_unlock_bh(&xfrm_policy_lock);
472 }
473 EXPORT_SYMBOL(xfrm_spd_getinfo);
474 
475 static DEFINE_MUTEX(hash_resize_mutex);
476 static void xfrm_hash_resize(struct work_struct *work)
477 {
478 	struct net *net = container_of(work, struct net, xfrm.policy_hash_work);
479 	int dir, total;
480 
481 	mutex_lock(&hash_resize_mutex);
482 
483 	total = 0;
484 	for (dir = 0; dir < XFRM_POLICY_MAX * 2; dir++) {
485 		if (xfrm_bydst_should_resize(net, dir, &total))
486 			xfrm_bydst_resize(net, dir);
487 	}
488 	if (xfrm_byidx_should_resize(net, total))
489 		xfrm_byidx_resize(net, total);
490 
491 	mutex_unlock(&hash_resize_mutex);
492 }
493 
494 /* Generate new index... KAME seems to generate them ordered by cost
495  * of an absolute inpredictability of ordering of rules. This will not pass. */
496 static u32 xfrm_gen_index(struct net *net, int dir)
497 {
498 	static u32 idx_generator;
499 
500 	for (;;) {
501 		struct hlist_node *entry;
502 		struct hlist_head *list;
503 		struct xfrm_policy *p;
504 		u32 idx;
505 		int found;
506 
507 		idx = (idx_generator | dir);
508 		idx_generator += 8;
509 		if (idx == 0)
510 			idx = 8;
511 		list = net->xfrm.policy_byidx + idx_hash(net, idx);
512 		found = 0;
513 		hlist_for_each_entry(p, entry, list, byidx) {
514 			if (p->index == idx) {
515 				found = 1;
516 				break;
517 			}
518 		}
519 		if (!found)
520 			return idx;
521 	}
522 }
523 
524 static inline int selector_cmp(struct xfrm_selector *s1, struct xfrm_selector *s2)
525 {
526 	u32 *p1 = (u32 *) s1;
527 	u32 *p2 = (u32 *) s2;
528 	int len = sizeof(struct xfrm_selector) / sizeof(u32);
529 	int i;
530 
531 	for (i = 0; i < len; i++) {
532 		if (p1[i] != p2[i])
533 			return 1;
534 	}
535 
536 	return 0;
537 }
538 
539 int xfrm_policy_insert(int dir, struct xfrm_policy *policy, int excl)
540 {
541 	struct net *net = xp_net(policy);
542 	struct xfrm_policy *pol;
543 	struct xfrm_policy *delpol;
544 	struct hlist_head *chain;
545 	struct hlist_node *entry, *newpos;
546 	u32 mark = policy->mark.v & policy->mark.m;
547 
548 	write_lock_bh(&xfrm_policy_lock);
549 	chain = policy_hash_bysel(net, &policy->selector, policy->family, dir);
550 	delpol = NULL;
551 	newpos = NULL;
552 	hlist_for_each_entry(pol, entry, chain, bydst) {
553 		if (pol->type == policy->type &&
554 		    !selector_cmp(&pol->selector, &policy->selector) &&
555 		    (mark & pol->mark.m) == pol->mark.v &&
556 		    xfrm_sec_ctx_match(pol->security, policy->security) &&
557 		    !WARN_ON(delpol)) {
558 			if (excl) {
559 				write_unlock_bh(&xfrm_policy_lock);
560 				return -EEXIST;
561 			}
562 			delpol = pol;
563 			if (policy->priority > pol->priority)
564 				continue;
565 		} else if (policy->priority >= pol->priority) {
566 			newpos = &pol->bydst;
567 			continue;
568 		}
569 		if (delpol)
570 			break;
571 	}
572 	if (newpos)
573 		hlist_add_after(newpos, &policy->bydst);
574 	else
575 		hlist_add_head(&policy->bydst, chain);
576 	xfrm_pol_hold(policy);
577 	net->xfrm.policy_count[dir]++;
578 	atomic_inc(&flow_cache_genid);
579 	if (delpol)
580 		__xfrm_policy_unlink(delpol, dir);
581 	policy->index = delpol ? delpol->index : xfrm_gen_index(net, dir);
582 	hlist_add_head(&policy->byidx, net->xfrm.policy_byidx+idx_hash(net, policy->index));
583 	policy->curlft.add_time = get_seconds();
584 	policy->curlft.use_time = 0;
585 	if (!mod_timer(&policy->timer, jiffies + HZ))
586 		xfrm_pol_hold(policy);
587 	list_add(&policy->walk.all, &net->xfrm.policy_all);
588 	write_unlock_bh(&xfrm_policy_lock);
589 
590 	if (delpol)
591 		xfrm_policy_kill(delpol);
592 	else if (xfrm_bydst_should_resize(net, dir, NULL))
593 		schedule_work(&net->xfrm.policy_hash_work);
594 
595 	return 0;
596 }
597 EXPORT_SYMBOL(xfrm_policy_insert);
598 
599 struct xfrm_policy *xfrm_policy_bysel_ctx(struct net *net, u32 mark, u8 type,
600 					  int dir, struct xfrm_selector *sel,
601 					  struct xfrm_sec_ctx *ctx, int delete,
602 					  int *err)
603 {
604 	struct xfrm_policy *pol, *ret;
605 	struct hlist_head *chain;
606 	struct hlist_node *entry;
607 
608 	*err = 0;
609 	write_lock_bh(&xfrm_policy_lock);
610 	chain = policy_hash_bysel(net, sel, sel->family, dir);
611 	ret = NULL;
612 	hlist_for_each_entry(pol, entry, chain, bydst) {
613 		if (pol->type == type &&
614 		    (mark & pol->mark.m) == pol->mark.v &&
615 		    !selector_cmp(sel, &pol->selector) &&
616 		    xfrm_sec_ctx_match(ctx, pol->security)) {
617 			xfrm_pol_hold(pol);
618 			if (delete) {
619 				*err = security_xfrm_policy_delete(
620 								pol->security);
621 				if (*err) {
622 					write_unlock_bh(&xfrm_policy_lock);
623 					return pol;
624 				}
625 				__xfrm_policy_unlink(pol, dir);
626 			}
627 			ret = pol;
628 			break;
629 		}
630 	}
631 	write_unlock_bh(&xfrm_policy_lock);
632 
633 	if (ret && delete)
634 		xfrm_policy_kill(ret);
635 	return ret;
636 }
637 EXPORT_SYMBOL(xfrm_policy_bysel_ctx);
638 
639 struct xfrm_policy *xfrm_policy_byid(struct net *net, u32 mark, u8 type,
640 				     int dir, u32 id, int delete, int *err)
641 {
642 	struct xfrm_policy *pol, *ret;
643 	struct hlist_head *chain;
644 	struct hlist_node *entry;
645 
646 	*err = -ENOENT;
647 	if (xfrm_policy_id2dir(id) != dir)
648 		return NULL;
649 
650 	*err = 0;
651 	write_lock_bh(&xfrm_policy_lock);
652 	chain = net->xfrm.policy_byidx + idx_hash(net, id);
653 	ret = NULL;
654 	hlist_for_each_entry(pol, entry, chain, byidx) {
655 		if (pol->type == type && pol->index == id &&
656 		    (mark & pol->mark.m) == pol->mark.v) {
657 			xfrm_pol_hold(pol);
658 			if (delete) {
659 				*err = security_xfrm_policy_delete(
660 								pol->security);
661 				if (*err) {
662 					write_unlock_bh(&xfrm_policy_lock);
663 					return pol;
664 				}
665 				__xfrm_policy_unlink(pol, dir);
666 			}
667 			ret = pol;
668 			break;
669 		}
670 	}
671 	write_unlock_bh(&xfrm_policy_lock);
672 
673 	if (ret && delete)
674 		xfrm_policy_kill(ret);
675 	return ret;
676 }
677 EXPORT_SYMBOL(xfrm_policy_byid);
678 
679 #ifdef CONFIG_SECURITY_NETWORK_XFRM
680 static inline int
681 xfrm_policy_flush_secctx_check(struct net *net, u8 type, struct xfrm_audit *audit_info)
682 {
683 	int dir, err = 0;
684 
685 	for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
686 		struct xfrm_policy *pol;
687 		struct hlist_node *entry;
688 		int i;
689 
690 		hlist_for_each_entry(pol, entry,
691 				     &net->xfrm.policy_inexact[dir], bydst) {
692 			if (pol->type != type)
693 				continue;
694 			err = security_xfrm_policy_delete(pol->security);
695 			if (err) {
696 				xfrm_audit_policy_delete(pol, 0,
697 							 audit_info->loginuid,
698 							 audit_info->sessionid,
699 							 audit_info->secid);
700 				return err;
701 			}
702 		}
703 		for (i = net->xfrm.policy_bydst[dir].hmask; i >= 0; i--) {
704 			hlist_for_each_entry(pol, entry,
705 					     net->xfrm.policy_bydst[dir].table + i,
706 					     bydst) {
707 				if (pol->type != type)
708 					continue;
709 				err = security_xfrm_policy_delete(
710 								pol->security);
711 				if (err) {
712 					xfrm_audit_policy_delete(pol, 0,
713 							audit_info->loginuid,
714 							audit_info->sessionid,
715 							audit_info->secid);
716 					return err;
717 				}
718 			}
719 		}
720 	}
721 	return err;
722 }
723 #else
724 static inline int
725 xfrm_policy_flush_secctx_check(struct net *net, u8 type, struct xfrm_audit *audit_info)
726 {
727 	return 0;
728 }
729 #endif
730 
731 int xfrm_policy_flush(struct net *net, u8 type, struct xfrm_audit *audit_info)
732 {
733 	int dir, err = 0, cnt = 0;
734 
735 	write_lock_bh(&xfrm_policy_lock);
736 
737 	err = xfrm_policy_flush_secctx_check(net, type, audit_info);
738 	if (err)
739 		goto out;
740 
741 	for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
742 		struct xfrm_policy *pol;
743 		struct hlist_node *entry;
744 		int i;
745 
746 	again1:
747 		hlist_for_each_entry(pol, entry,
748 				     &net->xfrm.policy_inexact[dir], bydst) {
749 			if (pol->type != type)
750 				continue;
751 			__xfrm_policy_unlink(pol, dir);
752 			write_unlock_bh(&xfrm_policy_lock);
753 			cnt++;
754 
755 			xfrm_audit_policy_delete(pol, 1, audit_info->loginuid,
756 						 audit_info->sessionid,
757 						 audit_info->secid);
758 
759 			xfrm_policy_kill(pol);
760 
761 			write_lock_bh(&xfrm_policy_lock);
762 			goto again1;
763 		}
764 
765 		for (i = net->xfrm.policy_bydst[dir].hmask; i >= 0; i--) {
766 	again2:
767 			hlist_for_each_entry(pol, entry,
768 					     net->xfrm.policy_bydst[dir].table + i,
769 					     bydst) {
770 				if (pol->type != type)
771 					continue;
772 				__xfrm_policy_unlink(pol, dir);
773 				write_unlock_bh(&xfrm_policy_lock);
774 				cnt++;
775 
776 				xfrm_audit_policy_delete(pol, 1,
777 							 audit_info->loginuid,
778 							 audit_info->sessionid,
779 							 audit_info->secid);
780 				xfrm_policy_kill(pol);
781 
782 				write_lock_bh(&xfrm_policy_lock);
783 				goto again2;
784 			}
785 		}
786 
787 	}
788 	if (!cnt)
789 		err = -ESRCH;
790 out:
791 	write_unlock_bh(&xfrm_policy_lock);
792 	return err;
793 }
794 EXPORT_SYMBOL(xfrm_policy_flush);
795 
796 int xfrm_policy_walk(struct net *net, struct xfrm_policy_walk *walk,
797 		     int (*func)(struct xfrm_policy *, int, int, void*),
798 		     void *data)
799 {
800 	struct xfrm_policy *pol;
801 	struct xfrm_policy_walk_entry *x;
802 	int error = 0;
803 
804 	if (walk->type >= XFRM_POLICY_TYPE_MAX &&
805 	    walk->type != XFRM_POLICY_TYPE_ANY)
806 		return -EINVAL;
807 
808 	if (list_empty(&walk->walk.all) && walk->seq != 0)
809 		return 0;
810 
811 	write_lock_bh(&xfrm_policy_lock);
812 	if (list_empty(&walk->walk.all))
813 		x = list_first_entry(&net->xfrm.policy_all, struct xfrm_policy_walk_entry, all);
814 	else
815 		x = list_entry(&walk->walk.all, struct xfrm_policy_walk_entry, all);
816 	list_for_each_entry_from(x, &net->xfrm.policy_all, all) {
817 		if (x->dead)
818 			continue;
819 		pol = container_of(x, struct xfrm_policy, walk);
820 		if (walk->type != XFRM_POLICY_TYPE_ANY &&
821 		    walk->type != pol->type)
822 			continue;
823 		error = func(pol, xfrm_policy_id2dir(pol->index),
824 			     walk->seq, data);
825 		if (error) {
826 			list_move_tail(&walk->walk.all, &x->all);
827 			goto out;
828 		}
829 		walk->seq++;
830 	}
831 	if (walk->seq == 0) {
832 		error = -ENOENT;
833 		goto out;
834 	}
835 	list_del_init(&walk->walk.all);
836 out:
837 	write_unlock_bh(&xfrm_policy_lock);
838 	return error;
839 }
840 EXPORT_SYMBOL(xfrm_policy_walk);
841 
842 void xfrm_policy_walk_init(struct xfrm_policy_walk *walk, u8 type)
843 {
844 	INIT_LIST_HEAD(&walk->walk.all);
845 	walk->walk.dead = 1;
846 	walk->type = type;
847 	walk->seq = 0;
848 }
849 EXPORT_SYMBOL(xfrm_policy_walk_init);
850 
851 void xfrm_policy_walk_done(struct xfrm_policy_walk *walk)
852 {
853 	if (list_empty(&walk->walk.all))
854 		return;
855 
856 	write_lock_bh(&xfrm_policy_lock);
857 	list_del(&walk->walk.all);
858 	write_unlock_bh(&xfrm_policy_lock);
859 }
860 EXPORT_SYMBOL(xfrm_policy_walk_done);
861 
862 /*
863  * Find policy to apply to this flow.
864  *
865  * Returns 0 if policy found, else an -errno.
866  */
867 static int xfrm_policy_match(struct xfrm_policy *pol, struct flowi *fl,
868 			     u8 type, u16 family, int dir)
869 {
870 	struct xfrm_selector *sel = &pol->selector;
871 	int match, ret = -ESRCH;
872 
873 	if (pol->family != family ||
874 	    (fl->mark & pol->mark.m) != pol->mark.v ||
875 	    pol->type != type)
876 		return ret;
877 
878 	match = xfrm_selector_match(sel, fl, family);
879 	if (match)
880 		ret = security_xfrm_policy_lookup(pol->security, fl->secid,
881 						  dir);
882 
883 	return ret;
884 }
885 
886 static struct xfrm_policy *xfrm_policy_lookup_bytype(struct net *net, u8 type,
887 						     struct flowi *fl,
888 						     u16 family, u8 dir)
889 {
890 	int err;
891 	struct xfrm_policy *pol, *ret;
892 	xfrm_address_t *daddr, *saddr;
893 	struct hlist_node *entry;
894 	struct hlist_head *chain;
895 	u32 priority = ~0U;
896 
897 	daddr = xfrm_flowi_daddr(fl, family);
898 	saddr = xfrm_flowi_saddr(fl, family);
899 	if (unlikely(!daddr || !saddr))
900 		return NULL;
901 
902 	read_lock_bh(&xfrm_policy_lock);
903 	chain = policy_hash_direct(net, daddr, saddr, family, dir);
904 	ret = NULL;
905 	hlist_for_each_entry(pol, entry, chain, bydst) {
906 		err = xfrm_policy_match(pol, fl, type, family, dir);
907 		if (err) {
908 			if (err == -ESRCH)
909 				continue;
910 			else {
911 				ret = ERR_PTR(err);
912 				goto fail;
913 			}
914 		} else {
915 			ret = pol;
916 			priority = ret->priority;
917 			break;
918 		}
919 	}
920 	chain = &net->xfrm.policy_inexact[dir];
921 	hlist_for_each_entry(pol, entry, chain, bydst) {
922 		err = xfrm_policy_match(pol, fl, type, family, dir);
923 		if (err) {
924 			if (err == -ESRCH)
925 				continue;
926 			else {
927 				ret = ERR_PTR(err);
928 				goto fail;
929 			}
930 		} else if (pol->priority < priority) {
931 			ret = pol;
932 			break;
933 		}
934 	}
935 	if (ret)
936 		xfrm_pol_hold(ret);
937 fail:
938 	read_unlock_bh(&xfrm_policy_lock);
939 
940 	return ret;
941 }
942 
943 static struct xfrm_policy *
944 __xfrm_policy_lookup(struct net *net, struct flowi *fl, u16 family, u8 dir)
945 {
946 #ifdef CONFIG_XFRM_SUB_POLICY
947 	struct xfrm_policy *pol;
948 
949 	pol = xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_SUB, fl, family, dir);
950 	if (pol != NULL)
951 		return pol;
952 #endif
953 	return xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_MAIN, fl, family, dir);
954 }
955 
956 static struct flow_cache_object *
957 xfrm_policy_lookup(struct net *net, struct flowi *fl, u16 family,
958 		   u8 dir, struct flow_cache_object *old_obj, void *ctx)
959 {
960 	struct xfrm_policy *pol;
961 
962 	if (old_obj)
963 		xfrm_pol_put(container_of(old_obj, struct xfrm_policy, flo));
964 
965 	pol = __xfrm_policy_lookup(net, fl, family, dir);
966 	if (IS_ERR_OR_NULL(pol))
967 		return ERR_CAST(pol);
968 
969 	/* Resolver returns two references:
970 	 * one for cache and one for caller of flow_cache_lookup() */
971 	xfrm_pol_hold(pol);
972 
973 	return &pol->flo;
974 }
975 
976 static inline int policy_to_flow_dir(int dir)
977 {
978 	if (XFRM_POLICY_IN == FLOW_DIR_IN &&
979 	    XFRM_POLICY_OUT == FLOW_DIR_OUT &&
980 	    XFRM_POLICY_FWD == FLOW_DIR_FWD)
981 		return dir;
982 	switch (dir) {
983 	default:
984 	case XFRM_POLICY_IN:
985 		return FLOW_DIR_IN;
986 	case XFRM_POLICY_OUT:
987 		return FLOW_DIR_OUT;
988 	case XFRM_POLICY_FWD:
989 		return FLOW_DIR_FWD;
990 	}
991 }
992 
993 static struct xfrm_policy *xfrm_sk_policy_lookup(struct sock *sk, int dir, struct flowi *fl)
994 {
995 	struct xfrm_policy *pol;
996 
997 	read_lock_bh(&xfrm_policy_lock);
998 	if ((pol = sk->sk_policy[dir]) != NULL) {
999 		int match = xfrm_selector_match(&pol->selector, fl,
1000 						sk->sk_family);
1001 		int err = 0;
1002 
1003 		if (match) {
1004 			if ((sk->sk_mark & pol->mark.m) != pol->mark.v) {
1005 				pol = NULL;
1006 				goto out;
1007 			}
1008 			err = security_xfrm_policy_lookup(pol->security,
1009 						      fl->secid,
1010 						      policy_to_flow_dir(dir));
1011 			if (!err)
1012 				xfrm_pol_hold(pol);
1013 			else if (err == -ESRCH)
1014 				pol = NULL;
1015 			else
1016 				pol = ERR_PTR(err);
1017 		} else
1018 			pol = NULL;
1019 	}
1020 out:
1021 	read_unlock_bh(&xfrm_policy_lock);
1022 	return pol;
1023 }
1024 
1025 static void __xfrm_policy_link(struct xfrm_policy *pol, int dir)
1026 {
1027 	struct net *net = xp_net(pol);
1028 	struct hlist_head *chain = policy_hash_bysel(net, &pol->selector,
1029 						     pol->family, dir);
1030 
1031 	list_add(&pol->walk.all, &net->xfrm.policy_all);
1032 	hlist_add_head(&pol->bydst, chain);
1033 	hlist_add_head(&pol->byidx, net->xfrm.policy_byidx+idx_hash(net, pol->index));
1034 	net->xfrm.policy_count[dir]++;
1035 	xfrm_pol_hold(pol);
1036 
1037 	if (xfrm_bydst_should_resize(net, dir, NULL))
1038 		schedule_work(&net->xfrm.policy_hash_work);
1039 }
1040 
1041 static struct xfrm_policy *__xfrm_policy_unlink(struct xfrm_policy *pol,
1042 						int dir)
1043 {
1044 	struct net *net = xp_net(pol);
1045 
1046 	if (hlist_unhashed(&pol->bydst))
1047 		return NULL;
1048 
1049 	hlist_del(&pol->bydst);
1050 	hlist_del(&pol->byidx);
1051 	list_del(&pol->walk.all);
1052 	net->xfrm.policy_count[dir]--;
1053 
1054 	return pol;
1055 }
1056 
1057 int xfrm_policy_delete(struct xfrm_policy *pol, int dir)
1058 {
1059 	write_lock_bh(&xfrm_policy_lock);
1060 	pol = __xfrm_policy_unlink(pol, dir);
1061 	write_unlock_bh(&xfrm_policy_lock);
1062 	if (pol) {
1063 		xfrm_policy_kill(pol);
1064 		return 0;
1065 	}
1066 	return -ENOENT;
1067 }
1068 EXPORT_SYMBOL(xfrm_policy_delete);
1069 
1070 int xfrm_sk_policy_insert(struct sock *sk, int dir, struct xfrm_policy *pol)
1071 {
1072 	struct net *net = xp_net(pol);
1073 	struct xfrm_policy *old_pol;
1074 
1075 #ifdef CONFIG_XFRM_SUB_POLICY
1076 	if (pol && pol->type != XFRM_POLICY_TYPE_MAIN)
1077 		return -EINVAL;
1078 #endif
1079 
1080 	write_lock_bh(&xfrm_policy_lock);
1081 	old_pol = sk->sk_policy[dir];
1082 	sk->sk_policy[dir] = pol;
1083 	if (pol) {
1084 		pol->curlft.add_time = get_seconds();
1085 		pol->index = xfrm_gen_index(net, XFRM_POLICY_MAX+dir);
1086 		__xfrm_policy_link(pol, XFRM_POLICY_MAX+dir);
1087 	}
1088 	if (old_pol)
1089 		/* Unlinking succeeds always. This is the only function
1090 		 * allowed to delete or replace socket policy.
1091 		 */
1092 		__xfrm_policy_unlink(old_pol, XFRM_POLICY_MAX+dir);
1093 	write_unlock_bh(&xfrm_policy_lock);
1094 
1095 	if (old_pol) {
1096 		xfrm_policy_kill(old_pol);
1097 	}
1098 	return 0;
1099 }
1100 
1101 static struct xfrm_policy *clone_policy(struct xfrm_policy *old, int dir)
1102 {
1103 	struct xfrm_policy *newp = xfrm_policy_alloc(xp_net(old), GFP_ATOMIC);
1104 
1105 	if (newp) {
1106 		newp->selector = old->selector;
1107 		if (security_xfrm_policy_clone(old->security,
1108 					       &newp->security)) {
1109 			kfree(newp);
1110 			return NULL;  /* ENOMEM */
1111 		}
1112 		newp->lft = old->lft;
1113 		newp->curlft = old->curlft;
1114 		newp->mark = old->mark;
1115 		newp->action = old->action;
1116 		newp->flags = old->flags;
1117 		newp->xfrm_nr = old->xfrm_nr;
1118 		newp->index = old->index;
1119 		newp->type = old->type;
1120 		memcpy(newp->xfrm_vec, old->xfrm_vec,
1121 		       newp->xfrm_nr*sizeof(struct xfrm_tmpl));
1122 		write_lock_bh(&xfrm_policy_lock);
1123 		__xfrm_policy_link(newp, XFRM_POLICY_MAX+dir);
1124 		write_unlock_bh(&xfrm_policy_lock);
1125 		xfrm_pol_put(newp);
1126 	}
1127 	return newp;
1128 }
1129 
1130 int __xfrm_sk_clone_policy(struct sock *sk)
1131 {
1132 	struct xfrm_policy *p0 = sk->sk_policy[0],
1133 			   *p1 = sk->sk_policy[1];
1134 
1135 	sk->sk_policy[0] = sk->sk_policy[1] = NULL;
1136 	if (p0 && (sk->sk_policy[0] = clone_policy(p0, 0)) == NULL)
1137 		return -ENOMEM;
1138 	if (p1 && (sk->sk_policy[1] = clone_policy(p1, 1)) == NULL)
1139 		return -ENOMEM;
1140 	return 0;
1141 }
1142 
1143 static int
1144 xfrm_get_saddr(struct net *net, xfrm_address_t *local, xfrm_address_t *remote,
1145 	       unsigned short family)
1146 {
1147 	int err;
1148 	struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1149 
1150 	if (unlikely(afinfo == NULL))
1151 		return -EINVAL;
1152 	err = afinfo->get_saddr(net, local, remote);
1153 	xfrm_policy_put_afinfo(afinfo);
1154 	return err;
1155 }
1156 
1157 /* Resolve list of templates for the flow, given policy. */
1158 
1159 static int
1160 xfrm_tmpl_resolve_one(struct xfrm_policy *policy, struct flowi *fl,
1161 		      struct xfrm_state **xfrm,
1162 		      unsigned short family)
1163 {
1164 	struct net *net = xp_net(policy);
1165 	int nx;
1166 	int i, error;
1167 	xfrm_address_t *daddr = xfrm_flowi_daddr(fl, family);
1168 	xfrm_address_t *saddr = xfrm_flowi_saddr(fl, family);
1169 	xfrm_address_t tmp;
1170 
1171 	for (nx=0, i = 0; i < policy->xfrm_nr; i++) {
1172 		struct xfrm_state *x;
1173 		xfrm_address_t *remote = daddr;
1174 		xfrm_address_t *local  = saddr;
1175 		struct xfrm_tmpl *tmpl = &policy->xfrm_vec[i];
1176 
1177 		if (tmpl->mode == XFRM_MODE_TUNNEL ||
1178 		    tmpl->mode == XFRM_MODE_BEET) {
1179 			remote = &tmpl->id.daddr;
1180 			local = &tmpl->saddr;
1181 			if (xfrm_addr_any(local, tmpl->encap_family)) {
1182 				error = xfrm_get_saddr(net, &tmp, remote, tmpl->encap_family);
1183 				if (error)
1184 					goto fail;
1185 				local = &tmp;
1186 			}
1187 		}
1188 
1189 		x = xfrm_state_find(remote, local, fl, tmpl, policy, &error, family);
1190 
1191 		if (x && x->km.state == XFRM_STATE_VALID) {
1192 			xfrm[nx++] = x;
1193 			daddr = remote;
1194 			saddr = local;
1195 			continue;
1196 		}
1197 		if (x) {
1198 			error = (x->km.state == XFRM_STATE_ERROR ?
1199 				 -EINVAL : -EAGAIN);
1200 			xfrm_state_put(x);
1201 		}
1202 		else if (error == -ESRCH)
1203 			error = -EAGAIN;
1204 
1205 		if (!tmpl->optional)
1206 			goto fail;
1207 	}
1208 	return nx;
1209 
1210 fail:
1211 	for (nx--; nx>=0; nx--)
1212 		xfrm_state_put(xfrm[nx]);
1213 	return error;
1214 }
1215 
1216 static int
1217 xfrm_tmpl_resolve(struct xfrm_policy **pols, int npols, struct flowi *fl,
1218 		  struct xfrm_state **xfrm,
1219 		  unsigned short family)
1220 {
1221 	struct xfrm_state *tp[XFRM_MAX_DEPTH];
1222 	struct xfrm_state **tpp = (npols > 1) ? tp : xfrm;
1223 	int cnx = 0;
1224 	int error;
1225 	int ret;
1226 	int i;
1227 
1228 	for (i = 0; i < npols; i++) {
1229 		if (cnx + pols[i]->xfrm_nr >= XFRM_MAX_DEPTH) {
1230 			error = -ENOBUFS;
1231 			goto fail;
1232 		}
1233 
1234 		ret = xfrm_tmpl_resolve_one(pols[i], fl, &tpp[cnx], family);
1235 		if (ret < 0) {
1236 			error = ret;
1237 			goto fail;
1238 		} else
1239 			cnx += ret;
1240 	}
1241 
1242 	/* found states are sorted for outbound processing */
1243 	if (npols > 1)
1244 		xfrm_state_sort(xfrm, tpp, cnx, family);
1245 
1246 	return cnx;
1247 
1248  fail:
1249 	for (cnx--; cnx>=0; cnx--)
1250 		xfrm_state_put(tpp[cnx]);
1251 	return error;
1252 
1253 }
1254 
1255 /* Check that the bundle accepts the flow and its components are
1256  * still valid.
1257  */
1258 
1259 static inline int xfrm_get_tos(struct flowi *fl, int family)
1260 {
1261 	struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1262 	int tos;
1263 
1264 	if (!afinfo)
1265 		return -EINVAL;
1266 
1267 	tos = afinfo->get_tos(fl);
1268 
1269 	xfrm_policy_put_afinfo(afinfo);
1270 
1271 	return tos;
1272 }
1273 
1274 static struct flow_cache_object *xfrm_bundle_flo_get(struct flow_cache_object *flo)
1275 {
1276 	struct xfrm_dst *xdst = container_of(flo, struct xfrm_dst, flo);
1277 	struct dst_entry *dst = &xdst->u.dst;
1278 
1279 	if (xdst->route == NULL) {
1280 		/* Dummy bundle - if it has xfrms we were not
1281 		 * able to build bundle as template resolution failed.
1282 		 * It means we need to try again resolving. */
1283 		if (xdst->num_xfrms > 0)
1284 			return NULL;
1285 	} else {
1286 		/* Real bundle */
1287 		if (stale_bundle(dst))
1288 			return NULL;
1289 	}
1290 
1291 	dst_hold(dst);
1292 	return flo;
1293 }
1294 
1295 static int xfrm_bundle_flo_check(struct flow_cache_object *flo)
1296 {
1297 	struct xfrm_dst *xdst = container_of(flo, struct xfrm_dst, flo);
1298 	struct dst_entry *dst = &xdst->u.dst;
1299 
1300 	if (!xdst->route)
1301 		return 0;
1302 	if (stale_bundle(dst))
1303 		return 0;
1304 
1305 	return 1;
1306 }
1307 
1308 static void xfrm_bundle_flo_delete(struct flow_cache_object *flo)
1309 {
1310 	struct xfrm_dst *xdst = container_of(flo, struct xfrm_dst, flo);
1311 	struct dst_entry *dst = &xdst->u.dst;
1312 
1313 	dst_free(dst);
1314 }
1315 
1316 static const struct flow_cache_ops xfrm_bundle_fc_ops = {
1317 	.get = xfrm_bundle_flo_get,
1318 	.check = xfrm_bundle_flo_check,
1319 	.delete = xfrm_bundle_flo_delete,
1320 };
1321 
1322 static inline struct xfrm_dst *xfrm_alloc_dst(struct net *net, int family)
1323 {
1324 	struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1325 	struct dst_ops *dst_ops;
1326 	struct xfrm_dst *xdst;
1327 
1328 	if (!afinfo)
1329 		return ERR_PTR(-EINVAL);
1330 
1331 	switch (family) {
1332 	case AF_INET:
1333 		dst_ops = &net->xfrm.xfrm4_dst_ops;
1334 		break;
1335 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
1336 	case AF_INET6:
1337 		dst_ops = &net->xfrm.xfrm6_dst_ops;
1338 		break;
1339 #endif
1340 	default:
1341 		BUG();
1342 	}
1343 	xdst = dst_alloc(dst_ops) ?: ERR_PTR(-ENOBUFS);
1344 	xfrm_policy_put_afinfo(afinfo);
1345 
1346 	xdst->flo.ops = &xfrm_bundle_fc_ops;
1347 
1348 	return xdst;
1349 }
1350 
1351 static inline int xfrm_init_path(struct xfrm_dst *path, struct dst_entry *dst,
1352 				 int nfheader_len)
1353 {
1354 	struct xfrm_policy_afinfo *afinfo =
1355 		xfrm_policy_get_afinfo(dst->ops->family);
1356 	int err;
1357 
1358 	if (!afinfo)
1359 		return -EINVAL;
1360 
1361 	err = afinfo->init_path(path, dst, nfheader_len);
1362 
1363 	xfrm_policy_put_afinfo(afinfo);
1364 
1365 	return err;
1366 }
1367 
1368 static inline int xfrm_fill_dst(struct xfrm_dst *xdst, struct net_device *dev,
1369 				struct flowi *fl)
1370 {
1371 	struct xfrm_policy_afinfo *afinfo =
1372 		xfrm_policy_get_afinfo(xdst->u.dst.ops->family);
1373 	int err;
1374 
1375 	if (!afinfo)
1376 		return -EINVAL;
1377 
1378 	err = afinfo->fill_dst(xdst, dev, fl);
1379 
1380 	xfrm_policy_put_afinfo(afinfo);
1381 
1382 	return err;
1383 }
1384 
1385 
1386 /* Allocate chain of dst_entry's, attach known xfrm's, calculate
1387  * all the metrics... Shortly, bundle a bundle.
1388  */
1389 
1390 static struct dst_entry *xfrm_bundle_create(struct xfrm_policy *policy,
1391 					    struct xfrm_state **xfrm, int nx,
1392 					    struct flowi *fl,
1393 					    struct dst_entry *dst)
1394 {
1395 	struct net *net = xp_net(policy);
1396 	unsigned long now = jiffies;
1397 	struct net_device *dev;
1398 	struct dst_entry *dst_prev = NULL;
1399 	struct dst_entry *dst0 = NULL;
1400 	int i = 0;
1401 	int err;
1402 	int header_len = 0;
1403 	int nfheader_len = 0;
1404 	int trailer_len = 0;
1405 	int tos;
1406 	int family = policy->selector.family;
1407 	xfrm_address_t saddr, daddr;
1408 
1409 	xfrm_flowi_addr_get(fl, &saddr, &daddr, family);
1410 
1411 	tos = xfrm_get_tos(fl, family);
1412 	err = tos;
1413 	if (tos < 0)
1414 		goto put_states;
1415 
1416 	dst_hold(dst);
1417 
1418 	for (; i < nx; i++) {
1419 		struct xfrm_dst *xdst = xfrm_alloc_dst(net, family);
1420 		struct dst_entry *dst1 = &xdst->u.dst;
1421 
1422 		err = PTR_ERR(xdst);
1423 		if (IS_ERR(xdst)) {
1424 			dst_release(dst);
1425 			goto put_states;
1426 		}
1427 
1428 		if (!dst_prev)
1429 			dst0 = dst1;
1430 		else {
1431 			dst_prev->child = dst_clone(dst1);
1432 			dst1->flags |= DST_NOHASH;
1433 		}
1434 
1435 		xdst->route = dst;
1436 		dst_copy_metrics(dst1, dst);
1437 
1438 		if (xfrm[i]->props.mode != XFRM_MODE_TRANSPORT) {
1439 			family = xfrm[i]->props.family;
1440 			dst = xfrm_dst_lookup(xfrm[i], tos, &saddr, &daddr,
1441 					      family);
1442 			err = PTR_ERR(dst);
1443 			if (IS_ERR(dst))
1444 				goto put_states;
1445 		} else
1446 			dst_hold(dst);
1447 
1448 		dst1->xfrm = xfrm[i];
1449 		xdst->xfrm_genid = xfrm[i]->genid;
1450 
1451 		dst1->obsolete = -1;
1452 		dst1->flags |= DST_HOST;
1453 		dst1->lastuse = now;
1454 
1455 		dst1->input = dst_discard;
1456 		dst1->output = xfrm[i]->outer_mode->afinfo->output;
1457 
1458 		dst1->next = dst_prev;
1459 		dst_prev = dst1;
1460 
1461 		header_len += xfrm[i]->props.header_len;
1462 		if (xfrm[i]->type->flags & XFRM_TYPE_NON_FRAGMENT)
1463 			nfheader_len += xfrm[i]->props.header_len;
1464 		trailer_len += xfrm[i]->props.trailer_len;
1465 	}
1466 
1467 	dst_prev->child = dst;
1468 	dst0->path = dst;
1469 
1470 	err = -ENODEV;
1471 	dev = dst->dev;
1472 	if (!dev)
1473 		goto free_dst;
1474 
1475 	/* Copy neighbour for reachability confirmation */
1476 	dst0->neighbour = neigh_clone(dst->neighbour);
1477 
1478 	xfrm_init_path((struct xfrm_dst *)dst0, dst, nfheader_len);
1479 	xfrm_init_pmtu(dst_prev);
1480 
1481 	for (dst_prev = dst0; dst_prev != dst; dst_prev = dst_prev->child) {
1482 		struct xfrm_dst *xdst = (struct xfrm_dst *)dst_prev;
1483 
1484 		err = xfrm_fill_dst(xdst, dev, fl);
1485 		if (err)
1486 			goto free_dst;
1487 
1488 		dst_prev->header_len = header_len;
1489 		dst_prev->trailer_len = trailer_len;
1490 		header_len -= xdst->u.dst.xfrm->props.header_len;
1491 		trailer_len -= xdst->u.dst.xfrm->props.trailer_len;
1492 	}
1493 
1494 out:
1495 	return dst0;
1496 
1497 put_states:
1498 	for (; i < nx; i++)
1499 		xfrm_state_put(xfrm[i]);
1500 free_dst:
1501 	if (dst0)
1502 		dst_free(dst0);
1503 	dst0 = ERR_PTR(err);
1504 	goto out;
1505 }
1506 
1507 static int inline
1508 xfrm_dst_alloc_copy(void **target, void *src, int size)
1509 {
1510 	if (!*target) {
1511 		*target = kmalloc(size, GFP_ATOMIC);
1512 		if (!*target)
1513 			return -ENOMEM;
1514 	}
1515 	memcpy(*target, src, size);
1516 	return 0;
1517 }
1518 
1519 static int inline
1520 xfrm_dst_update_parent(struct dst_entry *dst, struct xfrm_selector *sel)
1521 {
1522 #ifdef CONFIG_XFRM_SUB_POLICY
1523 	struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
1524 	return xfrm_dst_alloc_copy((void **)&(xdst->partner),
1525 				   sel, sizeof(*sel));
1526 #else
1527 	return 0;
1528 #endif
1529 }
1530 
1531 static int inline
1532 xfrm_dst_update_origin(struct dst_entry *dst, struct flowi *fl)
1533 {
1534 #ifdef CONFIG_XFRM_SUB_POLICY
1535 	struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
1536 	return xfrm_dst_alloc_copy((void **)&(xdst->origin), fl, sizeof(*fl));
1537 #else
1538 	return 0;
1539 #endif
1540 }
1541 
1542 static int xfrm_expand_policies(struct flowi *fl, u16 family,
1543 				struct xfrm_policy **pols,
1544 				int *num_pols, int *num_xfrms)
1545 {
1546 	int i;
1547 
1548 	if (*num_pols == 0 || !pols[0]) {
1549 		*num_pols = 0;
1550 		*num_xfrms = 0;
1551 		return 0;
1552 	}
1553 	if (IS_ERR(pols[0]))
1554 		return PTR_ERR(pols[0]);
1555 
1556 	*num_xfrms = pols[0]->xfrm_nr;
1557 
1558 #ifdef CONFIG_XFRM_SUB_POLICY
1559 	if (pols[0] && pols[0]->action == XFRM_POLICY_ALLOW &&
1560 	    pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
1561 		pols[1] = xfrm_policy_lookup_bytype(xp_net(pols[0]),
1562 						    XFRM_POLICY_TYPE_MAIN,
1563 						    fl, family,
1564 						    XFRM_POLICY_OUT);
1565 		if (pols[1]) {
1566 			if (IS_ERR(pols[1])) {
1567 				xfrm_pols_put(pols, *num_pols);
1568 				return PTR_ERR(pols[1]);
1569 			}
1570 			(*num_pols) ++;
1571 			(*num_xfrms) += pols[1]->xfrm_nr;
1572 		}
1573 	}
1574 #endif
1575 	for (i = 0; i < *num_pols; i++) {
1576 		if (pols[i]->action != XFRM_POLICY_ALLOW) {
1577 			*num_xfrms = -1;
1578 			break;
1579 		}
1580 	}
1581 
1582 	return 0;
1583 
1584 }
1585 
1586 static struct xfrm_dst *
1587 xfrm_resolve_and_create_bundle(struct xfrm_policy **pols, int num_pols,
1588 			       struct flowi *fl, u16 family,
1589 			       struct dst_entry *dst_orig)
1590 {
1591 	struct net *net = xp_net(pols[0]);
1592 	struct xfrm_state *xfrm[XFRM_MAX_DEPTH];
1593 	struct dst_entry *dst;
1594 	struct xfrm_dst *xdst;
1595 	int err;
1596 
1597 	/* Try to instantiate a bundle */
1598 	err = xfrm_tmpl_resolve(pols, num_pols, fl, xfrm, family);
1599 	if (err <= 0) {
1600 		if (err != 0 && err != -EAGAIN)
1601 			XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLERROR);
1602 		return ERR_PTR(err);
1603 	}
1604 
1605 	dst = xfrm_bundle_create(pols[0], xfrm, err, fl, dst_orig);
1606 	if (IS_ERR(dst)) {
1607 		XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTBUNDLEGENERROR);
1608 		return ERR_CAST(dst);
1609 	}
1610 
1611 	xdst = (struct xfrm_dst *)dst;
1612 	xdst->num_xfrms = err;
1613 	if (num_pols > 1)
1614 		err = xfrm_dst_update_parent(dst, &pols[1]->selector);
1615 	else
1616 		err = xfrm_dst_update_origin(dst, fl);
1617 	if (unlikely(err)) {
1618 		dst_free(dst);
1619 		XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTBUNDLECHECKERROR);
1620 		return ERR_PTR(err);
1621 	}
1622 
1623 	xdst->num_pols = num_pols;
1624 	memcpy(xdst->pols, pols, sizeof(struct xfrm_policy*) * num_pols);
1625 	xdst->policy_genid = atomic_read(&pols[0]->genid);
1626 
1627 	return xdst;
1628 }
1629 
1630 static struct flow_cache_object *
1631 xfrm_bundle_lookup(struct net *net, struct flowi *fl, u16 family, u8 dir,
1632 		   struct flow_cache_object *oldflo, void *ctx)
1633 {
1634 	struct dst_entry *dst_orig = (struct dst_entry *)ctx;
1635 	struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
1636 	struct xfrm_dst *xdst, *new_xdst;
1637 	int num_pols = 0, num_xfrms = 0, i, err, pol_dead;
1638 
1639 	/* Check if the policies from old bundle are usable */
1640 	xdst = NULL;
1641 	if (oldflo) {
1642 		xdst = container_of(oldflo, struct xfrm_dst, flo);
1643 		num_pols = xdst->num_pols;
1644 		num_xfrms = xdst->num_xfrms;
1645 		pol_dead = 0;
1646 		for (i = 0; i < num_pols; i++) {
1647 			pols[i] = xdst->pols[i];
1648 			pol_dead |= pols[i]->walk.dead;
1649 		}
1650 		if (pol_dead) {
1651 			dst_free(&xdst->u.dst);
1652 			xdst = NULL;
1653 			num_pols = 0;
1654 			num_xfrms = 0;
1655 			oldflo = NULL;
1656 		}
1657 	}
1658 
1659 	/* Resolve policies to use if we couldn't get them from
1660 	 * previous cache entry */
1661 	if (xdst == NULL) {
1662 		num_pols = 1;
1663 		pols[0] = __xfrm_policy_lookup(net, fl, family, dir);
1664 		err = xfrm_expand_policies(fl, family, pols,
1665 					   &num_pols, &num_xfrms);
1666 		if (err < 0)
1667 			goto inc_error;
1668 		if (num_pols == 0)
1669 			return NULL;
1670 		if (num_xfrms <= 0)
1671 			goto make_dummy_bundle;
1672 	}
1673 
1674 	new_xdst = xfrm_resolve_and_create_bundle(pols, num_pols, fl, family, dst_orig);
1675 	if (IS_ERR(new_xdst)) {
1676 		err = PTR_ERR(new_xdst);
1677 		if (err != -EAGAIN)
1678 			goto error;
1679 		if (oldflo == NULL)
1680 			goto make_dummy_bundle;
1681 		dst_hold(&xdst->u.dst);
1682 		return oldflo;
1683 	} else if (new_xdst == NULL) {
1684 		num_xfrms = 0;
1685 		if (oldflo == NULL)
1686 			goto make_dummy_bundle;
1687 		xdst->num_xfrms = 0;
1688 		dst_hold(&xdst->u.dst);
1689 		return oldflo;
1690 	}
1691 
1692 	/* Kill the previous bundle */
1693 	if (xdst) {
1694 		/* The policies were stolen for newly generated bundle */
1695 		xdst->num_pols = 0;
1696 		dst_free(&xdst->u.dst);
1697 	}
1698 
1699 	/* Flow cache does not have reference, it dst_free()'s,
1700 	 * but we do need to return one reference for original caller */
1701 	dst_hold(&new_xdst->u.dst);
1702 	return &new_xdst->flo;
1703 
1704 make_dummy_bundle:
1705 	/* We found policies, but there's no bundles to instantiate:
1706 	 * either because the policy blocks, has no transformations or
1707 	 * we could not build template (no xfrm_states).*/
1708 	xdst = xfrm_alloc_dst(net, family);
1709 	if (IS_ERR(xdst)) {
1710 		xfrm_pols_put(pols, num_pols);
1711 		return ERR_CAST(xdst);
1712 	}
1713 	xdst->num_pols = num_pols;
1714 	xdst->num_xfrms = num_xfrms;
1715 	memcpy(xdst->pols, pols, sizeof(struct xfrm_policy*) * num_pols);
1716 
1717 	dst_hold(&xdst->u.dst);
1718 	return &xdst->flo;
1719 
1720 inc_error:
1721 	XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLERROR);
1722 error:
1723 	if (xdst != NULL)
1724 		dst_free(&xdst->u.dst);
1725 	else
1726 		xfrm_pols_put(pols, num_pols);
1727 	return ERR_PTR(err);
1728 }
1729 
1730 /* Main function: finds/creates a bundle for given flow.
1731  *
1732  * At the moment we eat a raw IP route. Mostly to speed up lookups
1733  * on interfaces with disabled IPsec.
1734  */
1735 int __xfrm_lookup(struct net *net, struct dst_entry **dst_p, struct flowi *fl,
1736 		  struct sock *sk, int flags)
1737 {
1738 	struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
1739 	struct flow_cache_object *flo;
1740 	struct xfrm_dst *xdst;
1741 	struct dst_entry *dst, *dst_orig = *dst_p, *route;
1742 	u16 family = dst_orig->ops->family;
1743 	u8 dir = policy_to_flow_dir(XFRM_POLICY_OUT);
1744 	int i, err, num_pols, num_xfrms = 0, drop_pols = 0;
1745 
1746 restart:
1747 	dst = NULL;
1748 	xdst = NULL;
1749 	route = NULL;
1750 
1751 	if (sk && sk->sk_policy[XFRM_POLICY_OUT]) {
1752 		num_pols = 1;
1753 		pols[0] = xfrm_sk_policy_lookup(sk, XFRM_POLICY_OUT, fl);
1754 		err = xfrm_expand_policies(fl, family, pols,
1755 					   &num_pols, &num_xfrms);
1756 		if (err < 0)
1757 			goto dropdst;
1758 
1759 		if (num_pols) {
1760 			if (num_xfrms <= 0) {
1761 				drop_pols = num_pols;
1762 				goto no_transform;
1763 			}
1764 
1765 			xdst = xfrm_resolve_and_create_bundle(
1766 					pols, num_pols, fl,
1767 					family, dst_orig);
1768 			if (IS_ERR(xdst)) {
1769 				xfrm_pols_put(pols, num_pols);
1770 				err = PTR_ERR(xdst);
1771 				goto dropdst;
1772 			} else if (xdst == NULL) {
1773 				num_xfrms = 0;
1774 				drop_pols = num_pols;
1775 				goto no_transform;
1776 			}
1777 
1778 			spin_lock_bh(&xfrm_policy_sk_bundle_lock);
1779 			xdst->u.dst.next = xfrm_policy_sk_bundles;
1780 			xfrm_policy_sk_bundles = &xdst->u.dst;
1781 			spin_unlock_bh(&xfrm_policy_sk_bundle_lock);
1782 
1783 			route = xdst->route;
1784 		}
1785 	}
1786 
1787 	if (xdst == NULL) {
1788 		/* To accelerate a bit...  */
1789 		if ((dst_orig->flags & DST_NOXFRM) ||
1790 		    !net->xfrm.policy_count[XFRM_POLICY_OUT])
1791 			goto nopol;
1792 
1793 		flo = flow_cache_lookup(net, fl, family, dir,
1794 					xfrm_bundle_lookup, dst_orig);
1795 		if (flo == NULL)
1796 			goto nopol;
1797 		if (IS_ERR(flo)) {
1798 			err = PTR_ERR(flo);
1799 			goto dropdst;
1800 		}
1801 		xdst = container_of(flo, struct xfrm_dst, flo);
1802 
1803 		num_pols = xdst->num_pols;
1804 		num_xfrms = xdst->num_xfrms;
1805 		memcpy(pols, xdst->pols, sizeof(struct xfrm_policy*) * num_pols);
1806 		route = xdst->route;
1807 	}
1808 
1809 	dst = &xdst->u.dst;
1810 	if (route == NULL && num_xfrms > 0) {
1811 		/* The only case when xfrm_bundle_lookup() returns a
1812 		 * bundle with null route, is when the template could
1813 		 * not be resolved. It means policies are there, but
1814 		 * bundle could not be created, since we don't yet
1815 		 * have the xfrm_state's. We need to wait for KM to
1816 		 * negotiate new SA's or bail out with error.*/
1817 		if (net->xfrm.sysctl_larval_drop) {
1818 			/* EREMOTE tells the caller to generate
1819 			 * a one-shot blackhole route. */
1820 			dst_release(dst);
1821 			xfrm_pols_put(pols, drop_pols);
1822 			XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTNOSTATES);
1823 			return -EREMOTE;
1824 		}
1825 		if (flags & XFRM_LOOKUP_WAIT) {
1826 			DECLARE_WAITQUEUE(wait, current);
1827 
1828 			add_wait_queue(&net->xfrm.km_waitq, &wait);
1829 			set_current_state(TASK_INTERRUPTIBLE);
1830 			schedule();
1831 			set_current_state(TASK_RUNNING);
1832 			remove_wait_queue(&net->xfrm.km_waitq, &wait);
1833 
1834 			if (!signal_pending(current)) {
1835 				dst_release(dst);
1836 				goto restart;
1837 			}
1838 
1839 			err = -ERESTART;
1840 		} else
1841 			err = -EAGAIN;
1842 
1843 		XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTNOSTATES);
1844 		goto error;
1845 	}
1846 
1847 no_transform:
1848 	if (num_pols == 0)
1849 		goto nopol;
1850 
1851 	if ((flags & XFRM_LOOKUP_ICMP) &&
1852 	    !(pols[0]->flags & XFRM_POLICY_ICMP)) {
1853 		err = -ENOENT;
1854 		goto error;
1855 	}
1856 
1857 	for (i = 0; i < num_pols; i++)
1858 		pols[i]->curlft.use_time = get_seconds();
1859 
1860 	if (num_xfrms < 0) {
1861 		/* Prohibit the flow */
1862 		XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLBLOCK);
1863 		err = -EPERM;
1864 		goto error;
1865 	} else if (num_xfrms > 0) {
1866 		/* Flow transformed */
1867 		*dst_p = dst;
1868 		dst_release(dst_orig);
1869 	} else {
1870 		/* Flow passes untransformed */
1871 		dst_release(dst);
1872 	}
1873 ok:
1874 	xfrm_pols_put(pols, drop_pols);
1875 	return 0;
1876 
1877 nopol:
1878 	if (!(flags & XFRM_LOOKUP_ICMP))
1879 		goto ok;
1880 	err = -ENOENT;
1881 error:
1882 	dst_release(dst);
1883 dropdst:
1884 	dst_release(dst_orig);
1885 	*dst_p = NULL;
1886 	xfrm_pols_put(pols, drop_pols);
1887 	return err;
1888 }
1889 EXPORT_SYMBOL(__xfrm_lookup);
1890 
1891 int xfrm_lookup(struct net *net, struct dst_entry **dst_p, struct flowi *fl,
1892 		struct sock *sk, int flags)
1893 {
1894 	int err = __xfrm_lookup(net, dst_p, fl, sk, flags);
1895 
1896 	if (err == -EREMOTE) {
1897 		dst_release(*dst_p);
1898 		*dst_p = NULL;
1899 		err = -EAGAIN;
1900 	}
1901 
1902 	return err;
1903 }
1904 EXPORT_SYMBOL(xfrm_lookup);
1905 
1906 static inline int
1907 xfrm_secpath_reject(int idx, struct sk_buff *skb, struct flowi *fl)
1908 {
1909 	struct xfrm_state *x;
1910 
1911 	if (!skb->sp || idx < 0 || idx >= skb->sp->len)
1912 		return 0;
1913 	x = skb->sp->xvec[idx];
1914 	if (!x->type->reject)
1915 		return 0;
1916 	return x->type->reject(x, skb, fl);
1917 }
1918 
1919 /* When skb is transformed back to its "native" form, we have to
1920  * check policy restrictions. At the moment we make this in maximally
1921  * stupid way. Shame on me. :-) Of course, connected sockets must
1922  * have policy cached at them.
1923  */
1924 
1925 static inline int
1926 xfrm_state_ok(struct xfrm_tmpl *tmpl, struct xfrm_state *x,
1927 	      unsigned short family)
1928 {
1929 	if (xfrm_state_kern(x))
1930 		return tmpl->optional && !xfrm_state_addr_cmp(tmpl, x, tmpl->encap_family);
1931 	return	x->id.proto == tmpl->id.proto &&
1932 		(x->id.spi == tmpl->id.spi || !tmpl->id.spi) &&
1933 		(x->props.reqid == tmpl->reqid || !tmpl->reqid) &&
1934 		x->props.mode == tmpl->mode &&
1935 		(tmpl->allalgs || (tmpl->aalgos & (1<<x->props.aalgo)) ||
1936 		 !(xfrm_id_proto_match(tmpl->id.proto, IPSEC_PROTO_ANY))) &&
1937 		!(x->props.mode != XFRM_MODE_TRANSPORT &&
1938 		  xfrm_state_addr_cmp(tmpl, x, family));
1939 }
1940 
1941 /*
1942  * 0 or more than 0 is returned when validation is succeeded (either bypass
1943  * because of optional transport mode, or next index of the mathced secpath
1944  * state with the template.
1945  * -1 is returned when no matching template is found.
1946  * Otherwise "-2 - errored_index" is returned.
1947  */
1948 static inline int
1949 xfrm_policy_ok(struct xfrm_tmpl *tmpl, struct sec_path *sp, int start,
1950 	       unsigned short family)
1951 {
1952 	int idx = start;
1953 
1954 	if (tmpl->optional) {
1955 		if (tmpl->mode == XFRM_MODE_TRANSPORT)
1956 			return start;
1957 	} else
1958 		start = -1;
1959 	for (; idx < sp->len; idx++) {
1960 		if (xfrm_state_ok(tmpl, sp->xvec[idx], family))
1961 			return ++idx;
1962 		if (sp->xvec[idx]->props.mode != XFRM_MODE_TRANSPORT) {
1963 			if (start == -1)
1964 				start = -2-idx;
1965 			break;
1966 		}
1967 	}
1968 	return start;
1969 }
1970 
1971 int __xfrm_decode_session(struct sk_buff *skb, struct flowi *fl,
1972 			  unsigned int family, int reverse)
1973 {
1974 	struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1975 	int err;
1976 
1977 	if (unlikely(afinfo == NULL))
1978 		return -EAFNOSUPPORT;
1979 
1980 	afinfo->decode_session(skb, fl, reverse);
1981 	err = security_xfrm_decode_session(skb, &fl->secid);
1982 	xfrm_policy_put_afinfo(afinfo);
1983 	return err;
1984 }
1985 EXPORT_SYMBOL(__xfrm_decode_session);
1986 
1987 static inline int secpath_has_nontransport(struct sec_path *sp, int k, int *idxp)
1988 {
1989 	for (; k < sp->len; k++) {
1990 		if (sp->xvec[k]->props.mode != XFRM_MODE_TRANSPORT) {
1991 			*idxp = k;
1992 			return 1;
1993 		}
1994 	}
1995 
1996 	return 0;
1997 }
1998 
1999 int __xfrm_policy_check(struct sock *sk, int dir, struct sk_buff *skb,
2000 			unsigned short family)
2001 {
2002 	struct net *net = dev_net(skb->dev);
2003 	struct xfrm_policy *pol;
2004 	struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
2005 	int npols = 0;
2006 	int xfrm_nr;
2007 	int pi;
2008 	int reverse;
2009 	struct flowi fl;
2010 	u8 fl_dir;
2011 	int xerr_idx = -1;
2012 
2013 	reverse = dir & ~XFRM_POLICY_MASK;
2014 	dir &= XFRM_POLICY_MASK;
2015 	fl_dir = policy_to_flow_dir(dir);
2016 
2017 	if (__xfrm_decode_session(skb, &fl, family, reverse) < 0) {
2018 		XFRM_INC_STATS(net, LINUX_MIB_XFRMINHDRERROR);
2019 		return 0;
2020 	}
2021 
2022 	nf_nat_decode_session(skb, &fl, family);
2023 
2024 	/* First, check used SA against their selectors. */
2025 	if (skb->sp) {
2026 		int i;
2027 
2028 		for (i=skb->sp->len-1; i>=0; i--) {
2029 			struct xfrm_state *x = skb->sp->xvec[i];
2030 			if (!xfrm_selector_match(&x->sel, &fl, family)) {
2031 				XFRM_INC_STATS(net, LINUX_MIB_XFRMINSTATEMISMATCH);
2032 				return 0;
2033 			}
2034 		}
2035 	}
2036 
2037 	pol = NULL;
2038 	if (sk && sk->sk_policy[dir]) {
2039 		pol = xfrm_sk_policy_lookup(sk, dir, &fl);
2040 		if (IS_ERR(pol)) {
2041 			XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
2042 			return 0;
2043 		}
2044 	}
2045 
2046 	if (!pol) {
2047 		struct flow_cache_object *flo;
2048 
2049 		flo = flow_cache_lookup(net, &fl, family, fl_dir,
2050 					xfrm_policy_lookup, NULL);
2051 		if (IS_ERR_OR_NULL(flo))
2052 			pol = ERR_CAST(flo);
2053 		else
2054 			pol = container_of(flo, struct xfrm_policy, flo);
2055 	}
2056 
2057 	if (IS_ERR(pol)) {
2058 		XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
2059 		return 0;
2060 	}
2061 
2062 	if (!pol) {
2063 		if (skb->sp && secpath_has_nontransport(skb->sp, 0, &xerr_idx)) {
2064 			xfrm_secpath_reject(xerr_idx, skb, &fl);
2065 			XFRM_INC_STATS(net, LINUX_MIB_XFRMINNOPOLS);
2066 			return 0;
2067 		}
2068 		return 1;
2069 	}
2070 
2071 	pol->curlft.use_time = get_seconds();
2072 
2073 	pols[0] = pol;
2074 	npols ++;
2075 #ifdef CONFIG_XFRM_SUB_POLICY
2076 	if (pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
2077 		pols[1] = xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_MAIN,
2078 						    &fl, family,
2079 						    XFRM_POLICY_IN);
2080 		if (pols[1]) {
2081 			if (IS_ERR(pols[1])) {
2082 				XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
2083 				return 0;
2084 			}
2085 			pols[1]->curlft.use_time = get_seconds();
2086 			npols ++;
2087 		}
2088 	}
2089 #endif
2090 
2091 	if (pol->action == XFRM_POLICY_ALLOW) {
2092 		struct sec_path *sp;
2093 		static struct sec_path dummy;
2094 		struct xfrm_tmpl *tp[XFRM_MAX_DEPTH];
2095 		struct xfrm_tmpl *stp[XFRM_MAX_DEPTH];
2096 		struct xfrm_tmpl **tpp = tp;
2097 		int ti = 0;
2098 		int i, k;
2099 
2100 		if ((sp = skb->sp) == NULL)
2101 			sp = &dummy;
2102 
2103 		for (pi = 0; pi < npols; pi++) {
2104 			if (pols[pi] != pol &&
2105 			    pols[pi]->action != XFRM_POLICY_ALLOW) {
2106 				XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLBLOCK);
2107 				goto reject;
2108 			}
2109 			if (ti + pols[pi]->xfrm_nr >= XFRM_MAX_DEPTH) {
2110 				XFRM_INC_STATS(net, LINUX_MIB_XFRMINBUFFERERROR);
2111 				goto reject_error;
2112 			}
2113 			for (i = 0; i < pols[pi]->xfrm_nr; i++)
2114 				tpp[ti++] = &pols[pi]->xfrm_vec[i];
2115 		}
2116 		xfrm_nr = ti;
2117 		if (npols > 1) {
2118 			xfrm_tmpl_sort(stp, tpp, xfrm_nr, family);
2119 			tpp = stp;
2120 		}
2121 
2122 		/* For each tunnel xfrm, find the first matching tmpl.
2123 		 * For each tmpl before that, find corresponding xfrm.
2124 		 * Order is _important_. Later we will implement
2125 		 * some barriers, but at the moment barriers
2126 		 * are implied between each two transformations.
2127 		 */
2128 		for (i = xfrm_nr-1, k = 0; i >= 0; i--) {
2129 			k = xfrm_policy_ok(tpp[i], sp, k, family);
2130 			if (k < 0) {
2131 				if (k < -1)
2132 					/* "-2 - errored_index" returned */
2133 					xerr_idx = -(2+k);
2134 				XFRM_INC_STATS(net, LINUX_MIB_XFRMINTMPLMISMATCH);
2135 				goto reject;
2136 			}
2137 		}
2138 
2139 		if (secpath_has_nontransport(sp, k, &xerr_idx)) {
2140 			XFRM_INC_STATS(net, LINUX_MIB_XFRMINTMPLMISMATCH);
2141 			goto reject;
2142 		}
2143 
2144 		xfrm_pols_put(pols, npols);
2145 		return 1;
2146 	}
2147 	XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLBLOCK);
2148 
2149 reject:
2150 	xfrm_secpath_reject(xerr_idx, skb, &fl);
2151 reject_error:
2152 	xfrm_pols_put(pols, npols);
2153 	return 0;
2154 }
2155 EXPORT_SYMBOL(__xfrm_policy_check);
2156 
2157 int __xfrm_route_forward(struct sk_buff *skb, unsigned short family)
2158 {
2159 	struct net *net = dev_net(skb->dev);
2160 	struct flowi fl;
2161 	struct dst_entry *dst;
2162 	int res;
2163 
2164 	if (xfrm_decode_session(skb, &fl, family) < 0) {
2165 		XFRM_INC_STATS(net, LINUX_MIB_XFRMFWDHDRERROR);
2166 		return 0;
2167 	}
2168 
2169 	skb_dst_force(skb);
2170 	dst = skb_dst(skb);
2171 
2172 	res = xfrm_lookup(net, &dst, &fl, NULL, 0) == 0;
2173 	skb_dst_set(skb, dst);
2174 	return res;
2175 }
2176 EXPORT_SYMBOL(__xfrm_route_forward);
2177 
2178 /* Optimize later using cookies and generation ids. */
2179 
2180 static struct dst_entry *xfrm_dst_check(struct dst_entry *dst, u32 cookie)
2181 {
2182 	/* Code (such as __xfrm4_bundle_create()) sets dst->obsolete
2183 	 * to "-1" to force all XFRM destinations to get validated by
2184 	 * dst_ops->check on every use.  We do this because when a
2185 	 * normal route referenced by an XFRM dst is obsoleted we do
2186 	 * not go looking around for all parent referencing XFRM dsts
2187 	 * so that we can invalidate them.  It is just too much work.
2188 	 * Instead we make the checks here on every use.  For example:
2189 	 *
2190 	 *	XFRM dst A --> IPv4 dst X
2191 	 *
2192 	 * X is the "xdst->route" of A (X is also the "dst->path" of A
2193 	 * in this example).  If X is marked obsolete, "A" will not
2194 	 * notice.  That's what we are validating here via the
2195 	 * stale_bundle() check.
2196 	 *
2197 	 * When a policy's bundle is pruned, we dst_free() the XFRM
2198 	 * dst which causes it's ->obsolete field to be set to a
2199 	 * positive non-zero integer.  If an XFRM dst has been pruned
2200 	 * like this, we want to force a new route lookup.
2201 	 */
2202 	if (dst->obsolete < 0 && !stale_bundle(dst))
2203 		return dst;
2204 
2205 	return NULL;
2206 }
2207 
2208 static int stale_bundle(struct dst_entry *dst)
2209 {
2210 	return !xfrm_bundle_ok(NULL, (struct xfrm_dst *)dst, NULL, AF_UNSPEC, 0);
2211 }
2212 
2213 void xfrm_dst_ifdown(struct dst_entry *dst, struct net_device *dev)
2214 {
2215 	while ((dst = dst->child) && dst->xfrm && dst->dev == dev) {
2216 		dst->dev = dev_net(dev)->loopback_dev;
2217 		dev_hold(dst->dev);
2218 		dev_put(dev);
2219 	}
2220 }
2221 EXPORT_SYMBOL(xfrm_dst_ifdown);
2222 
2223 static void xfrm_link_failure(struct sk_buff *skb)
2224 {
2225 	/* Impossible. Such dst must be popped before reaches point of failure. */
2226 }
2227 
2228 static struct dst_entry *xfrm_negative_advice(struct dst_entry *dst)
2229 {
2230 	if (dst) {
2231 		if (dst->obsolete) {
2232 			dst_release(dst);
2233 			dst = NULL;
2234 		}
2235 	}
2236 	return dst;
2237 }
2238 
2239 static void __xfrm_garbage_collect(struct net *net)
2240 {
2241 	struct dst_entry *head, *next;
2242 
2243 	flow_cache_flush();
2244 
2245 	spin_lock_bh(&xfrm_policy_sk_bundle_lock);
2246 	head = xfrm_policy_sk_bundles;
2247 	xfrm_policy_sk_bundles = NULL;
2248 	spin_unlock_bh(&xfrm_policy_sk_bundle_lock);
2249 
2250 	while (head) {
2251 		next = head->next;
2252 		dst_free(head);
2253 		head = next;
2254 	}
2255 }
2256 
2257 static void xfrm_init_pmtu(struct dst_entry *dst)
2258 {
2259 	do {
2260 		struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
2261 		u32 pmtu, route_mtu_cached;
2262 
2263 		pmtu = dst_mtu(dst->child);
2264 		xdst->child_mtu_cached = pmtu;
2265 
2266 		pmtu = xfrm_state_mtu(dst->xfrm, pmtu);
2267 
2268 		route_mtu_cached = dst_mtu(xdst->route);
2269 		xdst->route_mtu_cached = route_mtu_cached;
2270 
2271 		if (pmtu > route_mtu_cached)
2272 			pmtu = route_mtu_cached;
2273 
2274 		dst_metric_set(dst, RTAX_MTU, pmtu);
2275 	} while ((dst = dst->next));
2276 }
2277 
2278 /* Check that the bundle accepts the flow and its components are
2279  * still valid.
2280  */
2281 
2282 static int xfrm_bundle_ok(struct xfrm_policy *pol, struct xfrm_dst *first,
2283 		struct flowi *fl, int family, int strict)
2284 {
2285 	struct dst_entry *dst = &first->u.dst;
2286 	struct xfrm_dst *last;
2287 	u32 mtu;
2288 
2289 	if (!dst_check(dst->path, ((struct xfrm_dst *)dst)->path_cookie) ||
2290 	    (dst->dev && !netif_running(dst->dev)))
2291 		return 0;
2292 #ifdef CONFIG_XFRM_SUB_POLICY
2293 	if (fl) {
2294 		if (first->origin && !flow_cache_uli_match(first->origin, fl))
2295 			return 0;
2296 		if (first->partner &&
2297 		    !xfrm_selector_match(first->partner, fl, family))
2298 			return 0;
2299 	}
2300 #endif
2301 
2302 	last = NULL;
2303 
2304 	do {
2305 		struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
2306 
2307 		if (fl && !xfrm_selector_match(&dst->xfrm->sel, fl, family))
2308 			return 0;
2309 		if (fl && pol &&
2310 		    !security_xfrm_state_pol_flow_match(dst->xfrm, pol, fl))
2311 			return 0;
2312 		if (dst->xfrm->km.state != XFRM_STATE_VALID)
2313 			return 0;
2314 		if (xdst->xfrm_genid != dst->xfrm->genid)
2315 			return 0;
2316 		if (xdst->num_pols > 0 &&
2317 		    xdst->policy_genid != atomic_read(&xdst->pols[0]->genid))
2318 			return 0;
2319 
2320 		if (strict && fl &&
2321 		    !(dst->xfrm->outer_mode->flags & XFRM_MODE_FLAG_TUNNEL) &&
2322 		    !xfrm_state_addr_flow_check(dst->xfrm, fl, family))
2323 			return 0;
2324 
2325 		mtu = dst_mtu(dst->child);
2326 		if (xdst->child_mtu_cached != mtu) {
2327 			last = xdst;
2328 			xdst->child_mtu_cached = mtu;
2329 		}
2330 
2331 		if (!dst_check(xdst->route, xdst->route_cookie))
2332 			return 0;
2333 		mtu = dst_mtu(xdst->route);
2334 		if (xdst->route_mtu_cached != mtu) {
2335 			last = xdst;
2336 			xdst->route_mtu_cached = mtu;
2337 		}
2338 
2339 		dst = dst->child;
2340 	} while (dst->xfrm);
2341 
2342 	if (likely(!last))
2343 		return 1;
2344 
2345 	mtu = last->child_mtu_cached;
2346 	for (;;) {
2347 		dst = &last->u.dst;
2348 
2349 		mtu = xfrm_state_mtu(dst->xfrm, mtu);
2350 		if (mtu > last->route_mtu_cached)
2351 			mtu = last->route_mtu_cached;
2352 		dst_metric_set(dst, RTAX_MTU, mtu);
2353 
2354 		if (last == first)
2355 			break;
2356 
2357 		last = (struct xfrm_dst *)last->u.dst.next;
2358 		last->child_mtu_cached = mtu;
2359 	}
2360 
2361 	return 1;
2362 }
2363 
2364 static unsigned int xfrm_default_advmss(const struct dst_entry *dst)
2365 {
2366 	return dst_metric_advmss(dst->path);
2367 }
2368 
2369 static unsigned int xfrm_default_mtu(const struct dst_entry *dst)
2370 {
2371 	return dst_mtu(dst->path);
2372 }
2373 
2374 int xfrm_policy_register_afinfo(struct xfrm_policy_afinfo *afinfo)
2375 {
2376 	struct net *net;
2377 	int err = 0;
2378 	if (unlikely(afinfo == NULL))
2379 		return -EINVAL;
2380 	if (unlikely(afinfo->family >= NPROTO))
2381 		return -EAFNOSUPPORT;
2382 	write_lock_bh(&xfrm_policy_afinfo_lock);
2383 	if (unlikely(xfrm_policy_afinfo[afinfo->family] != NULL))
2384 		err = -ENOBUFS;
2385 	else {
2386 		struct dst_ops *dst_ops = afinfo->dst_ops;
2387 		if (likely(dst_ops->kmem_cachep == NULL))
2388 			dst_ops->kmem_cachep = xfrm_dst_cache;
2389 		if (likely(dst_ops->check == NULL))
2390 			dst_ops->check = xfrm_dst_check;
2391 		if (likely(dst_ops->default_advmss == NULL))
2392 			dst_ops->default_advmss = xfrm_default_advmss;
2393 		if (likely(dst_ops->default_mtu == NULL))
2394 			dst_ops->default_mtu = xfrm_default_mtu;
2395 		if (likely(dst_ops->negative_advice == NULL))
2396 			dst_ops->negative_advice = xfrm_negative_advice;
2397 		if (likely(dst_ops->link_failure == NULL))
2398 			dst_ops->link_failure = xfrm_link_failure;
2399 		if (likely(afinfo->garbage_collect == NULL))
2400 			afinfo->garbage_collect = __xfrm_garbage_collect;
2401 		xfrm_policy_afinfo[afinfo->family] = afinfo;
2402 	}
2403 	write_unlock_bh(&xfrm_policy_afinfo_lock);
2404 
2405 	rtnl_lock();
2406 	for_each_net(net) {
2407 		struct dst_ops *xfrm_dst_ops;
2408 
2409 		switch (afinfo->family) {
2410 		case AF_INET:
2411 			xfrm_dst_ops = &net->xfrm.xfrm4_dst_ops;
2412 			break;
2413 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
2414 		case AF_INET6:
2415 			xfrm_dst_ops = &net->xfrm.xfrm6_dst_ops;
2416 			break;
2417 #endif
2418 		default:
2419 			BUG();
2420 		}
2421 		*xfrm_dst_ops = *afinfo->dst_ops;
2422 	}
2423 	rtnl_unlock();
2424 
2425 	return err;
2426 }
2427 EXPORT_SYMBOL(xfrm_policy_register_afinfo);
2428 
2429 int xfrm_policy_unregister_afinfo(struct xfrm_policy_afinfo *afinfo)
2430 {
2431 	int err = 0;
2432 	if (unlikely(afinfo == NULL))
2433 		return -EINVAL;
2434 	if (unlikely(afinfo->family >= NPROTO))
2435 		return -EAFNOSUPPORT;
2436 	write_lock_bh(&xfrm_policy_afinfo_lock);
2437 	if (likely(xfrm_policy_afinfo[afinfo->family] != NULL)) {
2438 		if (unlikely(xfrm_policy_afinfo[afinfo->family] != afinfo))
2439 			err = -EINVAL;
2440 		else {
2441 			struct dst_ops *dst_ops = afinfo->dst_ops;
2442 			xfrm_policy_afinfo[afinfo->family] = NULL;
2443 			dst_ops->kmem_cachep = NULL;
2444 			dst_ops->check = NULL;
2445 			dst_ops->negative_advice = NULL;
2446 			dst_ops->link_failure = NULL;
2447 			afinfo->garbage_collect = NULL;
2448 		}
2449 	}
2450 	write_unlock_bh(&xfrm_policy_afinfo_lock);
2451 	return err;
2452 }
2453 EXPORT_SYMBOL(xfrm_policy_unregister_afinfo);
2454 
2455 static void __net_init xfrm_dst_ops_init(struct net *net)
2456 {
2457 	struct xfrm_policy_afinfo *afinfo;
2458 
2459 	read_lock_bh(&xfrm_policy_afinfo_lock);
2460 	afinfo = xfrm_policy_afinfo[AF_INET];
2461 	if (afinfo)
2462 		net->xfrm.xfrm4_dst_ops = *afinfo->dst_ops;
2463 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
2464 	afinfo = xfrm_policy_afinfo[AF_INET6];
2465 	if (afinfo)
2466 		net->xfrm.xfrm6_dst_ops = *afinfo->dst_ops;
2467 #endif
2468 	read_unlock_bh(&xfrm_policy_afinfo_lock);
2469 }
2470 
2471 static struct xfrm_policy_afinfo *xfrm_policy_get_afinfo(unsigned short family)
2472 {
2473 	struct xfrm_policy_afinfo *afinfo;
2474 	if (unlikely(family >= NPROTO))
2475 		return NULL;
2476 	read_lock(&xfrm_policy_afinfo_lock);
2477 	afinfo = xfrm_policy_afinfo[family];
2478 	if (unlikely(!afinfo))
2479 		read_unlock(&xfrm_policy_afinfo_lock);
2480 	return afinfo;
2481 }
2482 
2483 static void xfrm_policy_put_afinfo(struct xfrm_policy_afinfo *afinfo)
2484 {
2485 	read_unlock(&xfrm_policy_afinfo_lock);
2486 }
2487 
2488 static int xfrm_dev_event(struct notifier_block *this, unsigned long event, void *ptr)
2489 {
2490 	struct net_device *dev = ptr;
2491 
2492 	switch (event) {
2493 	case NETDEV_DOWN:
2494 		__xfrm_garbage_collect(dev_net(dev));
2495 	}
2496 	return NOTIFY_DONE;
2497 }
2498 
2499 static struct notifier_block xfrm_dev_notifier = {
2500 	.notifier_call	= xfrm_dev_event,
2501 };
2502 
2503 #ifdef CONFIG_XFRM_STATISTICS
2504 static int __net_init xfrm_statistics_init(struct net *net)
2505 {
2506 	int rv;
2507 
2508 	if (snmp_mib_init((void __percpu **)net->mib.xfrm_statistics,
2509 			  sizeof(struct linux_xfrm_mib),
2510 			  __alignof__(struct linux_xfrm_mib)) < 0)
2511 		return -ENOMEM;
2512 	rv = xfrm_proc_init(net);
2513 	if (rv < 0)
2514 		snmp_mib_free((void __percpu **)net->mib.xfrm_statistics);
2515 	return rv;
2516 }
2517 
2518 static void xfrm_statistics_fini(struct net *net)
2519 {
2520 	xfrm_proc_fini(net);
2521 	snmp_mib_free((void __percpu **)net->mib.xfrm_statistics);
2522 }
2523 #else
2524 static int __net_init xfrm_statistics_init(struct net *net)
2525 {
2526 	return 0;
2527 }
2528 
2529 static void xfrm_statistics_fini(struct net *net)
2530 {
2531 }
2532 #endif
2533 
2534 static int __net_init xfrm_policy_init(struct net *net)
2535 {
2536 	unsigned int hmask, sz;
2537 	int dir;
2538 
2539 	if (net_eq(net, &init_net))
2540 		xfrm_dst_cache = kmem_cache_create("xfrm_dst_cache",
2541 					   sizeof(struct xfrm_dst),
2542 					   0, SLAB_HWCACHE_ALIGN|SLAB_PANIC,
2543 					   NULL);
2544 
2545 	hmask = 8 - 1;
2546 	sz = (hmask+1) * sizeof(struct hlist_head);
2547 
2548 	net->xfrm.policy_byidx = xfrm_hash_alloc(sz);
2549 	if (!net->xfrm.policy_byidx)
2550 		goto out_byidx;
2551 	net->xfrm.policy_idx_hmask = hmask;
2552 
2553 	for (dir = 0; dir < XFRM_POLICY_MAX * 2; dir++) {
2554 		struct xfrm_policy_hash *htab;
2555 
2556 		net->xfrm.policy_count[dir] = 0;
2557 		INIT_HLIST_HEAD(&net->xfrm.policy_inexact[dir]);
2558 
2559 		htab = &net->xfrm.policy_bydst[dir];
2560 		htab->table = xfrm_hash_alloc(sz);
2561 		if (!htab->table)
2562 			goto out_bydst;
2563 		htab->hmask = hmask;
2564 	}
2565 
2566 	INIT_LIST_HEAD(&net->xfrm.policy_all);
2567 	INIT_WORK(&net->xfrm.policy_hash_work, xfrm_hash_resize);
2568 	if (net_eq(net, &init_net))
2569 		register_netdevice_notifier(&xfrm_dev_notifier);
2570 	return 0;
2571 
2572 out_bydst:
2573 	for (dir--; dir >= 0; dir--) {
2574 		struct xfrm_policy_hash *htab;
2575 
2576 		htab = &net->xfrm.policy_bydst[dir];
2577 		xfrm_hash_free(htab->table, sz);
2578 	}
2579 	xfrm_hash_free(net->xfrm.policy_byidx, sz);
2580 out_byidx:
2581 	return -ENOMEM;
2582 }
2583 
2584 static void xfrm_policy_fini(struct net *net)
2585 {
2586 	struct xfrm_audit audit_info;
2587 	unsigned int sz;
2588 	int dir;
2589 
2590 	flush_work(&net->xfrm.policy_hash_work);
2591 #ifdef CONFIG_XFRM_SUB_POLICY
2592 	audit_info.loginuid = -1;
2593 	audit_info.sessionid = -1;
2594 	audit_info.secid = 0;
2595 	xfrm_policy_flush(net, XFRM_POLICY_TYPE_SUB, &audit_info);
2596 #endif
2597 	audit_info.loginuid = -1;
2598 	audit_info.sessionid = -1;
2599 	audit_info.secid = 0;
2600 	xfrm_policy_flush(net, XFRM_POLICY_TYPE_MAIN, &audit_info);
2601 
2602 	WARN_ON(!list_empty(&net->xfrm.policy_all));
2603 
2604 	for (dir = 0; dir < XFRM_POLICY_MAX * 2; dir++) {
2605 		struct xfrm_policy_hash *htab;
2606 
2607 		WARN_ON(!hlist_empty(&net->xfrm.policy_inexact[dir]));
2608 
2609 		htab = &net->xfrm.policy_bydst[dir];
2610 		sz = (htab->hmask + 1);
2611 		WARN_ON(!hlist_empty(htab->table));
2612 		xfrm_hash_free(htab->table, sz);
2613 	}
2614 
2615 	sz = (net->xfrm.policy_idx_hmask + 1) * sizeof(struct hlist_head);
2616 	WARN_ON(!hlist_empty(net->xfrm.policy_byidx));
2617 	xfrm_hash_free(net->xfrm.policy_byidx, sz);
2618 }
2619 
2620 static int __net_init xfrm_net_init(struct net *net)
2621 {
2622 	int rv;
2623 
2624 	rv = xfrm_statistics_init(net);
2625 	if (rv < 0)
2626 		goto out_statistics;
2627 	rv = xfrm_state_init(net);
2628 	if (rv < 0)
2629 		goto out_state;
2630 	rv = xfrm_policy_init(net);
2631 	if (rv < 0)
2632 		goto out_policy;
2633 	xfrm_dst_ops_init(net);
2634 	rv = xfrm_sysctl_init(net);
2635 	if (rv < 0)
2636 		goto out_sysctl;
2637 	return 0;
2638 
2639 out_sysctl:
2640 	xfrm_policy_fini(net);
2641 out_policy:
2642 	xfrm_state_fini(net);
2643 out_state:
2644 	xfrm_statistics_fini(net);
2645 out_statistics:
2646 	return rv;
2647 }
2648 
2649 static void __net_exit xfrm_net_exit(struct net *net)
2650 {
2651 	xfrm_sysctl_fini(net);
2652 	xfrm_policy_fini(net);
2653 	xfrm_state_fini(net);
2654 	xfrm_statistics_fini(net);
2655 }
2656 
2657 static struct pernet_operations __net_initdata xfrm_net_ops = {
2658 	.init = xfrm_net_init,
2659 	.exit = xfrm_net_exit,
2660 };
2661 
2662 void __init xfrm_init(void)
2663 {
2664 	register_pernet_subsys(&xfrm_net_ops);
2665 	xfrm_input_init();
2666 }
2667 
2668 #ifdef CONFIG_AUDITSYSCALL
2669 static void xfrm_audit_common_policyinfo(struct xfrm_policy *xp,
2670 					 struct audit_buffer *audit_buf)
2671 {
2672 	struct xfrm_sec_ctx *ctx = xp->security;
2673 	struct xfrm_selector *sel = &xp->selector;
2674 
2675 	if (ctx)
2676 		audit_log_format(audit_buf, " sec_alg=%u sec_doi=%u sec_obj=%s",
2677 				 ctx->ctx_alg, ctx->ctx_doi, ctx->ctx_str);
2678 
2679 	switch(sel->family) {
2680 	case AF_INET:
2681 		audit_log_format(audit_buf, " src=%pI4", &sel->saddr.a4);
2682 		if (sel->prefixlen_s != 32)
2683 			audit_log_format(audit_buf, " src_prefixlen=%d",
2684 					 sel->prefixlen_s);
2685 		audit_log_format(audit_buf, " dst=%pI4", &sel->daddr.a4);
2686 		if (sel->prefixlen_d != 32)
2687 			audit_log_format(audit_buf, " dst_prefixlen=%d",
2688 					 sel->prefixlen_d);
2689 		break;
2690 	case AF_INET6:
2691 		audit_log_format(audit_buf, " src=%pI6", sel->saddr.a6);
2692 		if (sel->prefixlen_s != 128)
2693 			audit_log_format(audit_buf, " src_prefixlen=%d",
2694 					 sel->prefixlen_s);
2695 		audit_log_format(audit_buf, " dst=%pI6", sel->daddr.a6);
2696 		if (sel->prefixlen_d != 128)
2697 			audit_log_format(audit_buf, " dst_prefixlen=%d",
2698 					 sel->prefixlen_d);
2699 		break;
2700 	}
2701 }
2702 
2703 void xfrm_audit_policy_add(struct xfrm_policy *xp, int result,
2704 			   uid_t auid, u32 sessionid, u32 secid)
2705 {
2706 	struct audit_buffer *audit_buf;
2707 
2708 	audit_buf = xfrm_audit_start("SPD-add");
2709 	if (audit_buf == NULL)
2710 		return;
2711 	xfrm_audit_helper_usrinfo(auid, sessionid, secid, audit_buf);
2712 	audit_log_format(audit_buf, " res=%u", result);
2713 	xfrm_audit_common_policyinfo(xp, audit_buf);
2714 	audit_log_end(audit_buf);
2715 }
2716 EXPORT_SYMBOL_GPL(xfrm_audit_policy_add);
2717 
2718 void xfrm_audit_policy_delete(struct xfrm_policy *xp, int result,
2719 			      uid_t auid, u32 sessionid, u32 secid)
2720 {
2721 	struct audit_buffer *audit_buf;
2722 
2723 	audit_buf = xfrm_audit_start("SPD-delete");
2724 	if (audit_buf == NULL)
2725 		return;
2726 	xfrm_audit_helper_usrinfo(auid, sessionid, secid, audit_buf);
2727 	audit_log_format(audit_buf, " res=%u", result);
2728 	xfrm_audit_common_policyinfo(xp, audit_buf);
2729 	audit_log_end(audit_buf);
2730 }
2731 EXPORT_SYMBOL_GPL(xfrm_audit_policy_delete);
2732 #endif
2733 
2734 #ifdef CONFIG_XFRM_MIGRATE
2735 static int xfrm_migrate_selector_match(struct xfrm_selector *sel_cmp,
2736 				       struct xfrm_selector *sel_tgt)
2737 {
2738 	if (sel_cmp->proto == IPSEC_ULPROTO_ANY) {
2739 		if (sel_tgt->family == sel_cmp->family &&
2740 		    xfrm_addr_cmp(&sel_tgt->daddr, &sel_cmp->daddr,
2741 				  sel_cmp->family) == 0 &&
2742 		    xfrm_addr_cmp(&sel_tgt->saddr, &sel_cmp->saddr,
2743 				  sel_cmp->family) == 0 &&
2744 		    sel_tgt->prefixlen_d == sel_cmp->prefixlen_d &&
2745 		    sel_tgt->prefixlen_s == sel_cmp->prefixlen_s) {
2746 			return 1;
2747 		}
2748 	} else {
2749 		if (memcmp(sel_tgt, sel_cmp, sizeof(*sel_tgt)) == 0) {
2750 			return 1;
2751 		}
2752 	}
2753 	return 0;
2754 }
2755 
2756 static struct xfrm_policy * xfrm_migrate_policy_find(struct xfrm_selector *sel,
2757 						     u8 dir, u8 type)
2758 {
2759 	struct xfrm_policy *pol, *ret = NULL;
2760 	struct hlist_node *entry;
2761 	struct hlist_head *chain;
2762 	u32 priority = ~0U;
2763 
2764 	read_lock_bh(&xfrm_policy_lock);
2765 	chain = policy_hash_direct(&init_net, &sel->daddr, &sel->saddr, sel->family, dir);
2766 	hlist_for_each_entry(pol, entry, chain, bydst) {
2767 		if (xfrm_migrate_selector_match(sel, &pol->selector) &&
2768 		    pol->type == type) {
2769 			ret = pol;
2770 			priority = ret->priority;
2771 			break;
2772 		}
2773 	}
2774 	chain = &init_net.xfrm.policy_inexact[dir];
2775 	hlist_for_each_entry(pol, entry, chain, bydst) {
2776 		if (xfrm_migrate_selector_match(sel, &pol->selector) &&
2777 		    pol->type == type &&
2778 		    pol->priority < priority) {
2779 			ret = pol;
2780 			break;
2781 		}
2782 	}
2783 
2784 	if (ret)
2785 		xfrm_pol_hold(ret);
2786 
2787 	read_unlock_bh(&xfrm_policy_lock);
2788 
2789 	return ret;
2790 }
2791 
2792 static int migrate_tmpl_match(struct xfrm_migrate *m, struct xfrm_tmpl *t)
2793 {
2794 	int match = 0;
2795 
2796 	if (t->mode == m->mode && t->id.proto == m->proto &&
2797 	    (m->reqid == 0 || t->reqid == m->reqid)) {
2798 		switch (t->mode) {
2799 		case XFRM_MODE_TUNNEL:
2800 		case XFRM_MODE_BEET:
2801 			if (xfrm_addr_cmp(&t->id.daddr, &m->old_daddr,
2802 					  m->old_family) == 0 &&
2803 			    xfrm_addr_cmp(&t->saddr, &m->old_saddr,
2804 					  m->old_family) == 0) {
2805 				match = 1;
2806 			}
2807 			break;
2808 		case XFRM_MODE_TRANSPORT:
2809 			/* in case of transport mode, template does not store
2810 			   any IP addresses, hence we just compare mode and
2811 			   protocol */
2812 			match = 1;
2813 			break;
2814 		default:
2815 			break;
2816 		}
2817 	}
2818 	return match;
2819 }
2820 
2821 /* update endpoint address(es) of template(s) */
2822 static int xfrm_policy_migrate(struct xfrm_policy *pol,
2823 			       struct xfrm_migrate *m, int num_migrate)
2824 {
2825 	struct xfrm_migrate *mp;
2826 	int i, j, n = 0;
2827 
2828 	write_lock_bh(&pol->lock);
2829 	if (unlikely(pol->walk.dead)) {
2830 		/* target policy has been deleted */
2831 		write_unlock_bh(&pol->lock);
2832 		return -ENOENT;
2833 	}
2834 
2835 	for (i = 0; i < pol->xfrm_nr; i++) {
2836 		for (j = 0, mp = m; j < num_migrate; j++, mp++) {
2837 			if (!migrate_tmpl_match(mp, &pol->xfrm_vec[i]))
2838 				continue;
2839 			n++;
2840 			if (pol->xfrm_vec[i].mode != XFRM_MODE_TUNNEL &&
2841 			    pol->xfrm_vec[i].mode != XFRM_MODE_BEET)
2842 				continue;
2843 			/* update endpoints */
2844 			memcpy(&pol->xfrm_vec[i].id.daddr, &mp->new_daddr,
2845 			       sizeof(pol->xfrm_vec[i].id.daddr));
2846 			memcpy(&pol->xfrm_vec[i].saddr, &mp->new_saddr,
2847 			       sizeof(pol->xfrm_vec[i].saddr));
2848 			pol->xfrm_vec[i].encap_family = mp->new_family;
2849 			/* flush bundles */
2850 			atomic_inc(&pol->genid);
2851 		}
2852 	}
2853 
2854 	write_unlock_bh(&pol->lock);
2855 
2856 	if (!n)
2857 		return -ENODATA;
2858 
2859 	return 0;
2860 }
2861 
2862 static int xfrm_migrate_check(struct xfrm_migrate *m, int num_migrate)
2863 {
2864 	int i, j;
2865 
2866 	if (num_migrate < 1 || num_migrate > XFRM_MAX_DEPTH)
2867 		return -EINVAL;
2868 
2869 	for (i = 0; i < num_migrate; i++) {
2870 		if ((xfrm_addr_cmp(&m[i].old_daddr, &m[i].new_daddr,
2871 				   m[i].old_family) == 0) &&
2872 		    (xfrm_addr_cmp(&m[i].old_saddr, &m[i].new_saddr,
2873 				   m[i].old_family) == 0))
2874 			return -EINVAL;
2875 		if (xfrm_addr_any(&m[i].new_daddr, m[i].new_family) ||
2876 		    xfrm_addr_any(&m[i].new_saddr, m[i].new_family))
2877 			return -EINVAL;
2878 
2879 		/* check if there is any duplicated entry */
2880 		for (j = i + 1; j < num_migrate; j++) {
2881 			if (!memcmp(&m[i].old_daddr, &m[j].old_daddr,
2882 				    sizeof(m[i].old_daddr)) &&
2883 			    !memcmp(&m[i].old_saddr, &m[j].old_saddr,
2884 				    sizeof(m[i].old_saddr)) &&
2885 			    m[i].proto == m[j].proto &&
2886 			    m[i].mode == m[j].mode &&
2887 			    m[i].reqid == m[j].reqid &&
2888 			    m[i].old_family == m[j].old_family)
2889 				return -EINVAL;
2890 		}
2891 	}
2892 
2893 	return 0;
2894 }
2895 
2896 int xfrm_migrate(struct xfrm_selector *sel, u8 dir, u8 type,
2897 		 struct xfrm_migrate *m, int num_migrate,
2898 		 struct xfrm_kmaddress *k)
2899 {
2900 	int i, err, nx_cur = 0, nx_new = 0;
2901 	struct xfrm_policy *pol = NULL;
2902 	struct xfrm_state *x, *xc;
2903 	struct xfrm_state *x_cur[XFRM_MAX_DEPTH];
2904 	struct xfrm_state *x_new[XFRM_MAX_DEPTH];
2905 	struct xfrm_migrate *mp;
2906 
2907 	if ((err = xfrm_migrate_check(m, num_migrate)) < 0)
2908 		goto out;
2909 
2910 	/* Stage 1 - find policy */
2911 	if ((pol = xfrm_migrate_policy_find(sel, dir, type)) == NULL) {
2912 		err = -ENOENT;
2913 		goto out;
2914 	}
2915 
2916 	/* Stage 2 - find and update state(s) */
2917 	for (i = 0, mp = m; i < num_migrate; i++, mp++) {
2918 		if ((x = xfrm_migrate_state_find(mp))) {
2919 			x_cur[nx_cur] = x;
2920 			nx_cur++;
2921 			if ((xc = xfrm_state_migrate(x, mp))) {
2922 				x_new[nx_new] = xc;
2923 				nx_new++;
2924 			} else {
2925 				err = -ENODATA;
2926 				goto restore_state;
2927 			}
2928 		}
2929 	}
2930 
2931 	/* Stage 3 - update policy */
2932 	if ((err = xfrm_policy_migrate(pol, m, num_migrate)) < 0)
2933 		goto restore_state;
2934 
2935 	/* Stage 4 - delete old state(s) */
2936 	if (nx_cur) {
2937 		xfrm_states_put(x_cur, nx_cur);
2938 		xfrm_states_delete(x_cur, nx_cur);
2939 	}
2940 
2941 	/* Stage 5 - announce */
2942 	km_migrate(sel, dir, type, m, num_migrate, k);
2943 
2944 	xfrm_pol_put(pol);
2945 
2946 	return 0;
2947 out:
2948 	return err;
2949 
2950 restore_state:
2951 	if (pol)
2952 		xfrm_pol_put(pol);
2953 	if (nx_cur)
2954 		xfrm_states_put(x_cur, nx_cur);
2955 	if (nx_new)
2956 		xfrm_states_delete(x_new, nx_new);
2957 
2958 	return err;
2959 }
2960 EXPORT_SYMBOL(xfrm_migrate);
2961 #endif
2962