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