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