GNU Linux-libre 4.9.304-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 bool xfrm_policy_mark_match(struct xfrm_policy *policy,
758                                    struct xfrm_policy *pol)
759 {
760         if (policy->mark.v == pol->mark.v &&
761             policy->priority == pol->priority)
762                 return true;
763
764         return false;
765 }
766
767 int xfrm_policy_insert(int dir, struct xfrm_policy *policy, int excl)
768 {
769         struct net *net = xp_net(policy);
770         struct xfrm_policy *pol;
771         struct xfrm_policy *delpol;
772         struct hlist_head *chain;
773         struct hlist_node *newpos;
774
775         spin_lock_bh(&net->xfrm.xfrm_policy_lock);
776         chain = policy_hash_bysel(net, &policy->selector, policy->family, dir);
777         delpol = NULL;
778         newpos = NULL;
779         hlist_for_each_entry(pol, chain, bydst) {
780                 if (pol->type == policy->type &&
781                     !selector_cmp(&pol->selector, &policy->selector) &&
782                     xfrm_policy_mark_match(policy, pol) &&
783                     xfrm_sec_ctx_match(pol->security, policy->security) &&
784                     !WARN_ON(delpol)) {
785                         if (excl) {
786                                 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
787                                 return -EEXIST;
788                         }
789                         delpol = pol;
790                         if (policy->priority > pol->priority)
791                                 continue;
792                 } else if (policy->priority >= pol->priority) {
793                         newpos = &pol->bydst;
794                         continue;
795                 }
796                 if (delpol)
797                         break;
798         }
799         if (newpos)
800                 hlist_add_behind_rcu(&policy->bydst, newpos);
801         else
802                 hlist_add_head_rcu(&policy->bydst, chain);
803         __xfrm_policy_link(policy, dir);
804         atomic_inc(&net->xfrm.flow_cache_genid);
805
806         /* After previous checking, family can either be AF_INET or AF_INET6 */
807         if (policy->family == AF_INET)
808                 rt_genid_bump_ipv4(net);
809         else
810                 rt_genid_bump_ipv6(net);
811
812         if (delpol) {
813                 xfrm_policy_requeue(delpol, policy);
814                 __xfrm_policy_unlink(delpol, dir);
815         }
816         policy->index = delpol ? delpol->index : xfrm_gen_index(net, dir, policy->index);
817         hlist_add_head(&policy->byidx, net->xfrm.policy_byidx+idx_hash(net, policy->index));
818         policy->curlft.add_time = get_seconds();
819         policy->curlft.use_time = 0;
820         if (!mod_timer(&policy->timer, jiffies + HZ))
821                 xfrm_pol_hold(policy);
822         spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
823
824         if (delpol)
825                 xfrm_policy_kill(delpol);
826         else if (xfrm_bydst_should_resize(net, dir, NULL))
827                 schedule_work(&net->xfrm.policy_hash_work);
828
829         return 0;
830 }
831 EXPORT_SYMBOL(xfrm_policy_insert);
832
833 struct xfrm_policy *xfrm_policy_bysel_ctx(struct net *net, u32 mark, u8 type,
834                                           int dir, struct xfrm_selector *sel,
835                                           struct xfrm_sec_ctx *ctx, int delete,
836                                           int *err)
837 {
838         struct xfrm_policy *pol, *ret;
839         struct hlist_head *chain;
840
841         *err = 0;
842         spin_lock_bh(&net->xfrm.xfrm_policy_lock);
843         chain = policy_hash_bysel(net, sel, sel->family, dir);
844         ret = NULL;
845         hlist_for_each_entry(pol, chain, bydst) {
846                 if (pol->type == type &&
847                     (mark & pol->mark.m) == pol->mark.v &&
848                     !selector_cmp(sel, &pol->selector) &&
849                     xfrm_sec_ctx_match(ctx, pol->security)) {
850                         xfrm_pol_hold(pol);
851                         if (delete) {
852                                 *err = security_xfrm_policy_delete(
853                                                                 pol->security);
854                                 if (*err) {
855                                         spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
856                                         return pol;
857                                 }
858                                 __xfrm_policy_unlink(pol, dir);
859                         }
860                         ret = pol;
861                         break;
862                 }
863         }
864         spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
865
866         if (ret && delete)
867                 xfrm_policy_kill(ret);
868         return ret;
869 }
870 EXPORT_SYMBOL(xfrm_policy_bysel_ctx);
871
872 struct xfrm_policy *xfrm_policy_byid(struct net *net, u32 mark, u8 type,
873                                      int dir, u32 id, int delete, int *err)
874 {
875         struct xfrm_policy *pol, *ret;
876         struct hlist_head *chain;
877
878         *err = -ENOENT;
879         if (xfrm_policy_id2dir(id) != dir)
880                 return NULL;
881
882         *err = 0;
883         spin_lock_bh(&net->xfrm.xfrm_policy_lock);
884         chain = net->xfrm.policy_byidx + idx_hash(net, id);
885         ret = NULL;
886         hlist_for_each_entry(pol, chain, byidx) {
887                 if (pol->type == type && pol->index == id &&
888                     (mark & pol->mark.m) == pol->mark.v) {
889                         xfrm_pol_hold(pol);
890                         if (delete) {
891                                 *err = security_xfrm_policy_delete(
892                                                                 pol->security);
893                                 if (*err) {
894                                         spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
895                                         return pol;
896                                 }
897                                 __xfrm_policy_unlink(pol, dir);
898                         }
899                         ret = pol;
900                         break;
901                 }
902         }
903         spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
904
905         if (ret && delete)
906                 xfrm_policy_kill(ret);
907         return ret;
908 }
909 EXPORT_SYMBOL(xfrm_policy_byid);
910
911 #ifdef CONFIG_SECURITY_NETWORK_XFRM
912 static inline int
913 xfrm_policy_flush_secctx_check(struct net *net, u8 type, bool task_valid)
914 {
915         int dir, err = 0;
916
917         for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
918                 struct xfrm_policy *pol;
919                 int i;
920
921                 hlist_for_each_entry(pol,
922                                      &net->xfrm.policy_inexact[dir], bydst) {
923                         if (pol->type != type)
924                                 continue;
925                         err = security_xfrm_policy_delete(pol->security);
926                         if (err) {
927                                 xfrm_audit_policy_delete(pol, 0, task_valid);
928                                 return err;
929                         }
930                 }
931                 for (i = net->xfrm.policy_bydst[dir].hmask; i >= 0; i--) {
932                         hlist_for_each_entry(pol,
933                                              net->xfrm.policy_bydst[dir].table + i,
934                                              bydst) {
935                                 if (pol->type != type)
936                                         continue;
937                                 err = security_xfrm_policy_delete(
938                                                                 pol->security);
939                                 if (err) {
940                                         xfrm_audit_policy_delete(pol, 0,
941                                                                  task_valid);
942                                         return err;
943                                 }
944                         }
945                 }
946         }
947         return err;
948 }
949 #else
950 static inline int
951 xfrm_policy_flush_secctx_check(struct net *net, u8 type, bool task_valid)
952 {
953         return 0;
954 }
955 #endif
956
957 int xfrm_policy_flush(struct net *net, u8 type, bool task_valid)
958 {
959         int dir, err = 0, cnt = 0;
960
961         spin_lock_bh(&net->xfrm.xfrm_policy_lock);
962
963         err = xfrm_policy_flush_secctx_check(net, type, task_valid);
964         if (err)
965                 goto out;
966
967         for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
968                 struct xfrm_policy *pol;
969                 int i;
970
971         again1:
972                 hlist_for_each_entry(pol,
973                                      &net->xfrm.policy_inexact[dir], bydst) {
974                         if (pol->type != type)
975                                 continue;
976                         __xfrm_policy_unlink(pol, dir);
977                         spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
978                         cnt++;
979
980                         xfrm_audit_policy_delete(pol, 1, task_valid);
981
982                         xfrm_policy_kill(pol);
983
984                         spin_lock_bh(&net->xfrm.xfrm_policy_lock);
985                         goto again1;
986                 }
987
988                 for (i = net->xfrm.policy_bydst[dir].hmask; i >= 0; i--) {
989         again2:
990                         hlist_for_each_entry(pol,
991                                              net->xfrm.policy_bydst[dir].table + i,
992                                              bydst) {
993                                 if (pol->type != type)
994                                         continue;
995                                 __xfrm_policy_unlink(pol, dir);
996                                 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
997                                 cnt++;
998
999                                 xfrm_audit_policy_delete(pol, 1, task_valid);
1000                                 xfrm_policy_kill(pol);
1001
1002                                 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1003                                 goto again2;
1004                         }
1005                 }
1006
1007         }
1008         if (!cnt)
1009                 err = -ESRCH;
1010 out:
1011         spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1012         return err;
1013 }
1014 EXPORT_SYMBOL(xfrm_policy_flush);
1015
1016 int xfrm_policy_walk(struct net *net, struct xfrm_policy_walk *walk,
1017                      int (*func)(struct xfrm_policy *, int, int, void*),
1018                      void *data)
1019 {
1020         struct xfrm_policy *pol;
1021         struct xfrm_policy_walk_entry *x;
1022         int error = 0;
1023
1024         if (walk->type >= XFRM_POLICY_TYPE_MAX &&
1025             walk->type != XFRM_POLICY_TYPE_ANY)
1026                 return -EINVAL;
1027
1028         if (list_empty(&walk->walk.all) && walk->seq != 0)
1029                 return 0;
1030
1031         spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1032         if (list_empty(&walk->walk.all))
1033                 x = list_first_entry(&net->xfrm.policy_all, struct xfrm_policy_walk_entry, all);
1034         else
1035                 x = list_first_entry(&walk->walk.all,
1036                                      struct xfrm_policy_walk_entry, all);
1037
1038         list_for_each_entry_from(x, &net->xfrm.policy_all, all) {
1039                 if (x->dead)
1040                         continue;
1041                 pol = container_of(x, struct xfrm_policy, walk);
1042                 if (walk->type != XFRM_POLICY_TYPE_ANY &&
1043                     walk->type != pol->type)
1044                         continue;
1045                 error = func(pol, xfrm_policy_id2dir(pol->index),
1046                              walk->seq, data);
1047                 if (error) {
1048                         list_move_tail(&walk->walk.all, &x->all);
1049                         goto out;
1050                 }
1051                 walk->seq++;
1052         }
1053         if (walk->seq == 0) {
1054                 error = -ENOENT;
1055                 goto out;
1056         }
1057         list_del_init(&walk->walk.all);
1058 out:
1059         spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1060         return error;
1061 }
1062 EXPORT_SYMBOL(xfrm_policy_walk);
1063
1064 void xfrm_policy_walk_init(struct xfrm_policy_walk *walk, u8 type)
1065 {
1066         INIT_LIST_HEAD(&walk->walk.all);
1067         walk->walk.dead = 1;
1068         walk->type = type;
1069         walk->seq = 0;
1070 }
1071 EXPORT_SYMBOL(xfrm_policy_walk_init);
1072
1073 void xfrm_policy_walk_done(struct xfrm_policy_walk *walk, struct net *net)
1074 {
1075         if (list_empty(&walk->walk.all))
1076                 return;
1077
1078         spin_lock_bh(&net->xfrm.xfrm_policy_lock); /*FIXME where is net? */
1079         list_del(&walk->walk.all);
1080         spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1081 }
1082 EXPORT_SYMBOL(xfrm_policy_walk_done);
1083
1084 /*
1085  * Find policy to apply to this flow.
1086  *
1087  * Returns 0 if policy found, else an -errno.
1088  */
1089 static int xfrm_policy_match(const struct xfrm_policy *pol,
1090                              const struct flowi *fl,
1091                              u8 type, u16 family, int dir)
1092 {
1093         const struct xfrm_selector *sel = &pol->selector;
1094         int ret = -ESRCH;
1095         bool match;
1096
1097         if (pol->family != family ||
1098             (fl->flowi_mark & pol->mark.m) != pol->mark.v ||
1099             pol->type != type)
1100                 return ret;
1101
1102         match = xfrm_selector_match(sel, fl, family);
1103         if (match)
1104                 ret = security_xfrm_policy_lookup(pol->security, fl->flowi_secid,
1105                                                   dir);
1106
1107         return ret;
1108 }
1109
1110 static struct xfrm_policy *xfrm_policy_lookup_bytype(struct net *net, u8 type,
1111                                                      const struct flowi *fl,
1112                                                      u16 family, u8 dir)
1113 {
1114         int err;
1115         struct xfrm_policy *pol, *ret;
1116         const xfrm_address_t *daddr, *saddr;
1117         struct hlist_head *chain;
1118         unsigned int sequence;
1119         u32 priority;
1120
1121         daddr = xfrm_flowi_daddr(fl, family);
1122         saddr = xfrm_flowi_saddr(fl, family);
1123         if (unlikely(!daddr || !saddr))
1124                 return NULL;
1125
1126         rcu_read_lock();
1127  retry:
1128         do {
1129                 sequence = read_seqcount_begin(&xfrm_policy_hash_generation);
1130                 chain = policy_hash_direct(net, daddr, saddr, family, dir);
1131         } while (read_seqcount_retry(&xfrm_policy_hash_generation, sequence));
1132
1133         priority = ~0U;
1134         ret = NULL;
1135         hlist_for_each_entry_rcu(pol, chain, bydst) {
1136                 err = xfrm_policy_match(pol, fl, type, family, dir);
1137                 if (err) {
1138                         if (err == -ESRCH)
1139                                 continue;
1140                         else {
1141                                 ret = ERR_PTR(err);
1142                                 goto fail;
1143                         }
1144                 } else {
1145                         ret = pol;
1146                         priority = ret->priority;
1147                         break;
1148                 }
1149         }
1150         chain = &net->xfrm.policy_inexact[dir];
1151         hlist_for_each_entry_rcu(pol, chain, bydst) {
1152                 if ((pol->priority >= priority) && ret)
1153                         break;
1154
1155                 err = xfrm_policy_match(pol, fl, type, family, dir);
1156                 if (err) {
1157                         if (err == -ESRCH)
1158                                 continue;
1159                         else {
1160                                 ret = ERR_PTR(err);
1161                                 goto fail;
1162                         }
1163                 } else {
1164                         ret = pol;
1165                         break;
1166                 }
1167         }
1168
1169         if (read_seqcount_retry(&xfrm_policy_hash_generation, sequence))
1170                 goto retry;
1171
1172         if (ret && !xfrm_pol_hold_rcu(ret))
1173                 goto retry;
1174 fail:
1175         rcu_read_unlock();
1176
1177         return ret;
1178 }
1179
1180 static struct xfrm_policy *
1181 __xfrm_policy_lookup(struct net *net, const struct flowi *fl, u16 family, u8 dir)
1182 {
1183 #ifdef CONFIG_XFRM_SUB_POLICY
1184         struct xfrm_policy *pol;
1185
1186         pol = xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_SUB, fl, family, dir);
1187         if (pol != NULL)
1188                 return pol;
1189 #endif
1190         return xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_MAIN, fl, family, dir);
1191 }
1192
1193 static int flow_to_policy_dir(int dir)
1194 {
1195         if (XFRM_POLICY_IN == FLOW_DIR_IN &&
1196             XFRM_POLICY_OUT == FLOW_DIR_OUT &&
1197             XFRM_POLICY_FWD == FLOW_DIR_FWD)
1198                 return dir;
1199
1200         switch (dir) {
1201         default:
1202         case FLOW_DIR_IN:
1203                 return XFRM_POLICY_IN;
1204         case FLOW_DIR_OUT:
1205                 return XFRM_POLICY_OUT;
1206         case FLOW_DIR_FWD:
1207                 return XFRM_POLICY_FWD;
1208         }
1209 }
1210
1211 static struct flow_cache_object *
1212 xfrm_policy_lookup(struct net *net, const struct flowi *fl, u16 family,
1213                    u8 dir, struct flow_cache_object *old_obj, void *ctx)
1214 {
1215         struct xfrm_policy *pol;
1216
1217         if (old_obj)
1218                 xfrm_pol_put(container_of(old_obj, struct xfrm_policy, flo));
1219
1220         pol = __xfrm_policy_lookup(net, fl, family, flow_to_policy_dir(dir));
1221         if (IS_ERR_OR_NULL(pol))
1222                 return ERR_CAST(pol);
1223
1224         /* Resolver returns two references:
1225          * one for cache and one for caller of flow_cache_lookup() */
1226         xfrm_pol_hold(pol);
1227
1228         return &pol->flo;
1229 }
1230
1231 static inline int policy_to_flow_dir(int dir)
1232 {
1233         if (XFRM_POLICY_IN == FLOW_DIR_IN &&
1234             XFRM_POLICY_OUT == FLOW_DIR_OUT &&
1235             XFRM_POLICY_FWD == FLOW_DIR_FWD)
1236                 return dir;
1237         switch (dir) {
1238         default:
1239         case XFRM_POLICY_IN:
1240                 return FLOW_DIR_IN;
1241         case XFRM_POLICY_OUT:
1242                 return FLOW_DIR_OUT;
1243         case XFRM_POLICY_FWD:
1244                 return FLOW_DIR_FWD;
1245         }
1246 }
1247
1248 static struct xfrm_policy *xfrm_sk_policy_lookup(const struct sock *sk, int dir,
1249                                                  const struct flowi *fl, u16 family)
1250 {
1251         struct xfrm_policy *pol;
1252
1253         rcu_read_lock();
1254  again:
1255         pol = rcu_dereference(sk->sk_policy[dir]);
1256         if (pol != NULL) {
1257                 bool match;
1258                 int err = 0;
1259
1260                 if (pol->family != family) {
1261                         pol = NULL;
1262                         goto out;
1263                 }
1264
1265                 match = xfrm_selector_match(&pol->selector, fl, family);
1266                 if (match) {
1267                         if ((sk->sk_mark & pol->mark.m) != pol->mark.v) {
1268                                 pol = NULL;
1269                                 goto out;
1270                         }
1271                         err = security_xfrm_policy_lookup(pol->security,
1272                                                       fl->flowi_secid,
1273                                                       policy_to_flow_dir(dir));
1274                         if (!err) {
1275                                 if (!xfrm_pol_hold_rcu(pol))
1276                                         goto again;
1277                         } else if (err == -ESRCH) {
1278                                 pol = NULL;
1279                         } else {
1280                                 pol = ERR_PTR(err);
1281                         }
1282                 } else
1283                         pol = NULL;
1284         }
1285 out:
1286         rcu_read_unlock();
1287         return pol;
1288 }
1289
1290 static void __xfrm_policy_link(struct xfrm_policy *pol, int dir)
1291 {
1292         struct net *net = xp_net(pol);
1293
1294         list_add(&pol->walk.all, &net->xfrm.policy_all);
1295         net->xfrm.policy_count[dir]++;
1296         xfrm_pol_hold(pol);
1297 }
1298
1299 static struct xfrm_policy *__xfrm_policy_unlink(struct xfrm_policy *pol,
1300                                                 int dir)
1301 {
1302         struct net *net = xp_net(pol);
1303
1304         if (list_empty(&pol->walk.all))
1305                 return NULL;
1306
1307         /* Socket policies are not hashed. */
1308         if (!hlist_unhashed(&pol->bydst)) {
1309                 hlist_del_rcu(&pol->bydst);
1310                 hlist_del(&pol->byidx);
1311         }
1312
1313         list_del_init(&pol->walk.all);
1314         net->xfrm.policy_count[dir]--;
1315
1316         return pol;
1317 }
1318
1319 static void xfrm_sk_policy_link(struct xfrm_policy *pol, int dir)
1320 {
1321         __xfrm_policy_link(pol, XFRM_POLICY_MAX + dir);
1322 }
1323
1324 static void xfrm_sk_policy_unlink(struct xfrm_policy *pol, int dir)
1325 {
1326         __xfrm_policy_unlink(pol, XFRM_POLICY_MAX + dir);
1327 }
1328
1329 int xfrm_policy_delete(struct xfrm_policy *pol, int dir)
1330 {
1331         struct net *net = xp_net(pol);
1332
1333         spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1334         pol = __xfrm_policy_unlink(pol, dir);
1335         spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1336         if (pol) {
1337                 xfrm_policy_kill(pol);
1338                 return 0;
1339         }
1340         return -ENOENT;
1341 }
1342 EXPORT_SYMBOL(xfrm_policy_delete);
1343
1344 int xfrm_sk_policy_insert(struct sock *sk, int dir, struct xfrm_policy *pol)
1345 {
1346         struct net *net = sock_net(sk);
1347         struct xfrm_policy *old_pol;
1348
1349 #ifdef CONFIG_XFRM_SUB_POLICY
1350         if (pol && pol->type != XFRM_POLICY_TYPE_MAIN)
1351                 return -EINVAL;
1352 #endif
1353
1354         spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1355         old_pol = rcu_dereference_protected(sk->sk_policy[dir],
1356                                 lockdep_is_held(&net->xfrm.xfrm_policy_lock));
1357         if (pol) {
1358                 pol->curlft.add_time = get_seconds();
1359                 pol->index = xfrm_gen_index(net, XFRM_POLICY_MAX+dir, 0);
1360                 xfrm_sk_policy_link(pol, dir);
1361         }
1362         rcu_assign_pointer(sk->sk_policy[dir], pol);
1363         if (old_pol) {
1364                 if (pol)
1365                         xfrm_policy_requeue(old_pol, pol);
1366
1367                 /* Unlinking succeeds always. This is the only function
1368                  * allowed to delete or replace socket policy.
1369                  */
1370                 xfrm_sk_policy_unlink(old_pol, dir);
1371         }
1372         spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1373
1374         if (old_pol) {
1375                 xfrm_policy_kill(old_pol);
1376         }
1377         return 0;
1378 }
1379
1380 static struct xfrm_policy *clone_policy(const struct xfrm_policy *old, int dir)
1381 {
1382         struct xfrm_policy *newp = xfrm_policy_alloc(xp_net(old), GFP_ATOMIC);
1383         struct net *net = xp_net(old);
1384
1385         if (newp) {
1386                 newp->selector = old->selector;
1387                 if (security_xfrm_policy_clone(old->security,
1388                                                &newp->security)) {
1389                         kfree(newp);
1390                         return NULL;  /* ENOMEM */
1391                 }
1392                 newp->lft = old->lft;
1393                 newp->curlft = old->curlft;
1394                 newp->mark = old->mark;
1395                 newp->action = old->action;
1396                 newp->flags = old->flags;
1397                 newp->xfrm_nr = old->xfrm_nr;
1398                 newp->index = old->index;
1399                 newp->type = old->type;
1400                 newp->family = old->family;
1401                 memcpy(newp->xfrm_vec, old->xfrm_vec,
1402                        newp->xfrm_nr*sizeof(struct xfrm_tmpl));
1403                 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1404                 xfrm_sk_policy_link(newp, dir);
1405                 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1406                 xfrm_pol_put(newp);
1407         }
1408         return newp;
1409 }
1410
1411 int __xfrm_sk_clone_policy(struct sock *sk, const struct sock *osk)
1412 {
1413         const struct xfrm_policy *p;
1414         struct xfrm_policy *np;
1415         int i, ret = 0;
1416
1417         rcu_read_lock();
1418         for (i = 0; i < 2; i++) {
1419                 p = rcu_dereference(osk->sk_policy[i]);
1420                 if (p) {
1421                         np = clone_policy(p, i);
1422                         if (unlikely(!np)) {
1423                                 ret = -ENOMEM;
1424                                 break;
1425                         }
1426                         rcu_assign_pointer(sk->sk_policy[i], np);
1427                 }
1428         }
1429         rcu_read_unlock();
1430         return ret;
1431 }
1432
1433 static int
1434 xfrm_get_saddr(struct net *net, int oif, xfrm_address_t *local,
1435                xfrm_address_t *remote, unsigned short family)
1436 {
1437         int err;
1438         struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1439
1440         if (unlikely(afinfo == NULL))
1441                 return -EINVAL;
1442         err = afinfo->get_saddr(net, oif, local, remote);
1443         xfrm_policy_put_afinfo(afinfo);
1444         return err;
1445 }
1446
1447 /* Resolve list of templates for the flow, given policy. */
1448
1449 static int
1450 xfrm_tmpl_resolve_one(struct xfrm_policy *policy, const struct flowi *fl,
1451                       struct xfrm_state **xfrm, unsigned short family)
1452 {
1453         struct net *net = xp_net(policy);
1454         int nx;
1455         int i, error;
1456         xfrm_address_t *daddr = xfrm_flowi_daddr(fl, family);
1457         xfrm_address_t *saddr = xfrm_flowi_saddr(fl, family);
1458         xfrm_address_t tmp;
1459
1460         for (nx = 0, i = 0; i < policy->xfrm_nr; i++) {
1461                 struct xfrm_state *x;
1462                 xfrm_address_t *remote = daddr;
1463                 xfrm_address_t *local  = saddr;
1464                 struct xfrm_tmpl *tmpl = &policy->xfrm_vec[i];
1465
1466                 if (tmpl->mode == XFRM_MODE_TUNNEL ||
1467                     tmpl->mode == XFRM_MODE_BEET) {
1468                         remote = &tmpl->id.daddr;
1469                         local = &tmpl->saddr;
1470                         if (xfrm_addr_any(local, tmpl->encap_family)) {
1471                                 error = xfrm_get_saddr(net, fl->flowi_oif,
1472                                                        &tmp, remote,
1473                                                        tmpl->encap_family);
1474                                 if (error)
1475                                         goto fail;
1476                                 local = &tmp;
1477                         }
1478                 }
1479
1480                 x = xfrm_state_find(remote, local, fl, tmpl, policy, &error, family);
1481
1482                 if (x && x->km.state == XFRM_STATE_VALID) {
1483                         xfrm[nx++] = x;
1484                         daddr = remote;
1485                         saddr = local;
1486                         continue;
1487                 }
1488                 if (x) {
1489                         error = (x->km.state == XFRM_STATE_ERROR ?
1490                                  -EINVAL : -EAGAIN);
1491                         xfrm_state_put(x);
1492                 } else if (error == -ESRCH) {
1493                         error = -EAGAIN;
1494                 }
1495
1496                 if (!tmpl->optional)
1497                         goto fail;
1498         }
1499         return nx;
1500
1501 fail:
1502         for (nx--; nx >= 0; nx--)
1503                 xfrm_state_put(xfrm[nx]);
1504         return error;
1505 }
1506
1507 static int
1508 xfrm_tmpl_resolve(struct xfrm_policy **pols, int npols, const struct flowi *fl,
1509                   struct xfrm_state **xfrm, unsigned short family)
1510 {
1511         struct xfrm_state *tp[XFRM_MAX_DEPTH];
1512         struct xfrm_state **tpp = (npols > 1) ? tp : xfrm;
1513         int cnx = 0;
1514         int error;
1515         int ret;
1516         int i;
1517
1518         for (i = 0; i < npols; i++) {
1519                 if (cnx + pols[i]->xfrm_nr >= XFRM_MAX_DEPTH) {
1520                         error = -ENOBUFS;
1521                         goto fail;
1522                 }
1523
1524                 ret = xfrm_tmpl_resolve_one(pols[i], fl, &tpp[cnx], family);
1525                 if (ret < 0) {
1526                         error = ret;
1527                         goto fail;
1528                 } else
1529                         cnx += ret;
1530         }
1531
1532         /* found states are sorted for outbound processing */
1533         if (npols > 1)
1534                 xfrm_state_sort(xfrm, tpp, cnx, family);
1535
1536         return cnx;
1537
1538  fail:
1539         for (cnx--; cnx >= 0; cnx--)
1540                 xfrm_state_put(tpp[cnx]);
1541         return error;
1542
1543 }
1544
1545 /* Check that the bundle accepts the flow and its components are
1546  * still valid.
1547  */
1548
1549 static inline int xfrm_get_tos(const struct flowi *fl, int family)
1550 {
1551         struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1552         int tos;
1553
1554         if (!afinfo)
1555                 return -EINVAL;
1556
1557         tos = afinfo->get_tos(fl);
1558
1559         xfrm_policy_put_afinfo(afinfo);
1560
1561         return tos;
1562 }
1563
1564 static struct flow_cache_object *xfrm_bundle_flo_get(struct flow_cache_object *flo)
1565 {
1566         struct xfrm_dst *xdst = container_of(flo, struct xfrm_dst, flo);
1567         struct dst_entry *dst = &xdst->u.dst;
1568
1569         if (xdst->route == NULL) {
1570                 /* Dummy bundle - if it has xfrms we were not
1571                  * able to build bundle as template resolution failed.
1572                  * It means we need to try again resolving. */
1573                 if (xdst->num_xfrms > 0)
1574                         return NULL;
1575         } else if (dst->flags & DST_XFRM_QUEUE) {
1576                 return NULL;
1577         } else {
1578                 /* Real bundle */
1579                 if (stale_bundle(dst))
1580                         return NULL;
1581         }
1582
1583         dst_hold(dst);
1584         return flo;
1585 }
1586
1587 static int xfrm_bundle_flo_check(struct flow_cache_object *flo)
1588 {
1589         struct xfrm_dst *xdst = container_of(flo, struct xfrm_dst, flo);
1590         struct dst_entry *dst = &xdst->u.dst;
1591
1592         if (!xdst->route)
1593                 return 0;
1594         if (stale_bundle(dst))
1595                 return 0;
1596
1597         return 1;
1598 }
1599
1600 static void xfrm_bundle_flo_delete(struct flow_cache_object *flo)
1601 {
1602         struct xfrm_dst *xdst = container_of(flo, struct xfrm_dst, flo);
1603         struct dst_entry *dst = &xdst->u.dst;
1604
1605         dst_free(dst);
1606 }
1607
1608 static const struct flow_cache_ops xfrm_bundle_fc_ops = {
1609         .get = xfrm_bundle_flo_get,
1610         .check = xfrm_bundle_flo_check,
1611         .delete = xfrm_bundle_flo_delete,
1612 };
1613
1614 static inline struct xfrm_dst *xfrm_alloc_dst(struct net *net, int family)
1615 {
1616         struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1617         struct dst_ops *dst_ops;
1618         struct xfrm_dst *xdst;
1619
1620         if (!afinfo)
1621                 return ERR_PTR(-EINVAL);
1622
1623         switch (family) {
1624         case AF_INET:
1625                 dst_ops = &net->xfrm.xfrm4_dst_ops;
1626                 break;
1627 #if IS_ENABLED(CONFIG_IPV6)
1628         case AF_INET6:
1629                 dst_ops = &net->xfrm.xfrm6_dst_ops;
1630                 break;
1631 #endif
1632         default:
1633                 BUG();
1634         }
1635         xdst = dst_alloc(dst_ops, NULL, 0, DST_OBSOLETE_NONE, 0);
1636
1637         if (likely(xdst)) {
1638                 struct dst_entry *dst = &xdst->u.dst;
1639
1640                 memset(dst + 1, 0, sizeof(*xdst) - sizeof(*dst));
1641                 xdst->flo.ops = &xfrm_bundle_fc_ops;
1642         } else
1643                 xdst = ERR_PTR(-ENOBUFS);
1644
1645         xfrm_policy_put_afinfo(afinfo);
1646
1647         return xdst;
1648 }
1649
1650 static inline int xfrm_init_path(struct xfrm_dst *path, struct dst_entry *dst,
1651                                  int nfheader_len)
1652 {
1653         struct xfrm_policy_afinfo *afinfo =
1654                 xfrm_policy_get_afinfo(dst->ops->family);
1655         int err;
1656
1657         if (!afinfo)
1658                 return -EINVAL;
1659
1660         err = afinfo->init_path(path, dst, nfheader_len);
1661
1662         xfrm_policy_put_afinfo(afinfo);
1663
1664         return err;
1665 }
1666
1667 static inline int xfrm_fill_dst(struct xfrm_dst *xdst, struct net_device *dev,
1668                                 const struct flowi *fl)
1669 {
1670         struct xfrm_policy_afinfo *afinfo =
1671                 xfrm_policy_get_afinfo(xdst->u.dst.ops->family);
1672         int err;
1673
1674         if (!afinfo)
1675                 return -EINVAL;
1676
1677         err = afinfo->fill_dst(xdst, dev, fl);
1678
1679         xfrm_policy_put_afinfo(afinfo);
1680
1681         return err;
1682 }
1683
1684
1685 /* Allocate chain of dst_entry's, attach known xfrm's, calculate
1686  * all the metrics... Shortly, bundle a bundle.
1687  */
1688
1689 static struct dst_entry *xfrm_bundle_create(struct xfrm_policy *policy,
1690                                             struct xfrm_state **xfrm, int nx,
1691                                             const struct flowi *fl,
1692                                             struct dst_entry *dst)
1693 {
1694         struct net *net = xp_net(policy);
1695         unsigned long now = jiffies;
1696         struct net_device *dev;
1697         struct xfrm_mode *inner_mode;
1698         struct dst_entry *dst_prev = NULL;
1699         struct dst_entry *dst0 = NULL;
1700         int i = 0;
1701         int err;
1702         int header_len = 0;
1703         int nfheader_len = 0;
1704         int trailer_len = 0;
1705         int tos;
1706         int family = policy->selector.family;
1707         xfrm_address_t saddr, daddr;
1708
1709         xfrm_flowi_addr_get(fl, &saddr, &daddr, family);
1710
1711         tos = xfrm_get_tos(fl, family);
1712         err = tos;
1713         if (tos < 0)
1714                 goto put_states;
1715
1716         dst_hold(dst);
1717
1718         for (; i < nx; i++) {
1719                 struct xfrm_dst *xdst = xfrm_alloc_dst(net, family);
1720                 struct dst_entry *dst1 = &xdst->u.dst;
1721
1722                 err = PTR_ERR(xdst);
1723                 if (IS_ERR(xdst)) {
1724                         dst_release(dst);
1725                         goto put_states;
1726                 }
1727
1728                 if (xfrm[i]->sel.family == AF_UNSPEC) {
1729                         inner_mode = xfrm_ip2inner_mode(xfrm[i],
1730                                                         xfrm_af2proto(family));
1731                         if (!inner_mode) {
1732                                 err = -EAFNOSUPPORT;
1733                                 dst_release(dst);
1734                                 goto put_states;
1735                         }
1736                 } else
1737                         inner_mode = xfrm[i]->inner_mode;
1738
1739                 if (!dst_prev)
1740                         dst0 = dst1;
1741                 else {
1742                         dst_prev->child = dst_clone(dst1);
1743                         dst1->flags |= DST_NOHASH;
1744                 }
1745
1746                 xdst->route = dst;
1747                 dst_copy_metrics(dst1, dst);
1748
1749                 if (xfrm[i]->props.mode != XFRM_MODE_TRANSPORT) {
1750                         family = xfrm[i]->props.family;
1751                         dst = xfrm_dst_lookup(xfrm[i], tos, fl->flowi_oif,
1752                                               &saddr, &daddr, family);
1753                         err = PTR_ERR(dst);
1754                         if (IS_ERR(dst))
1755                                 goto put_states;
1756                 } else
1757                         dst_hold(dst);
1758
1759                 dst1->xfrm = xfrm[i];
1760                 xdst->xfrm_genid = xfrm[i]->genid;
1761
1762                 dst1->obsolete = DST_OBSOLETE_FORCE_CHK;
1763                 dst1->flags |= DST_HOST;
1764                 dst1->lastuse = now;
1765
1766                 dst1->input = dst_discard;
1767                 dst1->output = inner_mode->afinfo->output;
1768
1769                 dst1->next = dst_prev;
1770                 dst_prev = dst1;
1771
1772                 header_len += xfrm[i]->props.header_len;
1773                 if (xfrm[i]->type->flags & XFRM_TYPE_NON_FRAGMENT)
1774                         nfheader_len += xfrm[i]->props.header_len;
1775                 trailer_len += xfrm[i]->props.trailer_len;
1776         }
1777
1778         dst_prev->child = dst;
1779         dst0->path = dst;
1780
1781         err = -ENODEV;
1782         dev = dst->dev;
1783         if (!dev)
1784                 goto free_dst;
1785
1786         xfrm_init_path((struct xfrm_dst *)dst0, dst, nfheader_len);
1787         xfrm_init_pmtu(dst_prev);
1788
1789         for (dst_prev = dst0; dst_prev != dst; dst_prev = dst_prev->child) {
1790                 struct xfrm_dst *xdst = (struct xfrm_dst *)dst_prev;
1791
1792                 err = xfrm_fill_dst(xdst, dev, fl);
1793                 if (err)
1794                         goto free_dst;
1795
1796                 dst_prev->header_len = header_len;
1797                 dst_prev->trailer_len = trailer_len;
1798                 header_len -= xdst->u.dst.xfrm->props.header_len;
1799                 trailer_len -= xdst->u.dst.xfrm->props.trailer_len;
1800         }
1801
1802 out:
1803         return dst0;
1804
1805 put_states:
1806         for (; i < nx; i++)
1807                 xfrm_state_put(xfrm[i]);
1808 free_dst:
1809         if (dst0)
1810                 dst_free(dst0);
1811         dst0 = ERR_PTR(err);
1812         goto out;
1813 }
1814
1815 static int xfrm_expand_policies(const struct flowi *fl, u16 family,
1816                                 struct xfrm_policy **pols,
1817                                 int *num_pols, int *num_xfrms)
1818 {
1819         int i;
1820
1821         if (*num_pols == 0 || !pols[0]) {
1822                 *num_pols = 0;
1823                 *num_xfrms = 0;
1824                 return 0;
1825         }
1826         if (IS_ERR(pols[0]))
1827                 return PTR_ERR(pols[0]);
1828
1829         *num_xfrms = pols[0]->xfrm_nr;
1830
1831 #ifdef CONFIG_XFRM_SUB_POLICY
1832         if (pols[0] && pols[0]->action == XFRM_POLICY_ALLOW &&
1833             pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
1834                 pols[1] = xfrm_policy_lookup_bytype(xp_net(pols[0]),
1835                                                     XFRM_POLICY_TYPE_MAIN,
1836                                                     fl, family,
1837                                                     XFRM_POLICY_OUT);
1838                 if (pols[1]) {
1839                         if (IS_ERR(pols[1])) {
1840                                 xfrm_pols_put(pols, *num_pols);
1841                                 return PTR_ERR(pols[1]);
1842                         }
1843                         (*num_pols)++;
1844                         (*num_xfrms) += pols[1]->xfrm_nr;
1845                 }
1846         }
1847 #endif
1848         for (i = 0; i < *num_pols; i++) {
1849                 if (pols[i]->action != XFRM_POLICY_ALLOW) {
1850                         *num_xfrms = -1;
1851                         break;
1852                 }
1853         }
1854
1855         return 0;
1856
1857 }
1858
1859 static struct xfrm_dst *
1860 xfrm_resolve_and_create_bundle(struct xfrm_policy **pols, int num_pols,
1861                                const struct flowi *fl, u16 family,
1862                                struct dst_entry *dst_orig)
1863 {
1864         struct net *net = xp_net(pols[0]);
1865         struct xfrm_state *xfrm[XFRM_MAX_DEPTH];
1866         struct dst_entry *dst;
1867         struct xfrm_dst *xdst;
1868         int err;
1869
1870         /* Try to instantiate a bundle */
1871         err = xfrm_tmpl_resolve(pols, num_pols, fl, xfrm, family);
1872         if (err <= 0) {
1873                 if (err == 0)
1874                         return NULL;
1875
1876                 if (err != -EAGAIN)
1877                         XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLERROR);
1878                 return ERR_PTR(err);
1879         }
1880
1881         dst = xfrm_bundle_create(pols[0], xfrm, err, fl, dst_orig);
1882         if (IS_ERR(dst)) {
1883                 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTBUNDLEGENERROR);
1884                 return ERR_CAST(dst);
1885         }
1886
1887         xdst = (struct xfrm_dst *)dst;
1888         xdst->num_xfrms = err;
1889         xdst->num_pols = num_pols;
1890         memcpy(xdst->pols, pols, sizeof(struct xfrm_policy *) * num_pols);
1891         xdst->policy_genid = atomic_read(&pols[0]->genid);
1892
1893         return xdst;
1894 }
1895
1896 static void xfrm_policy_queue_process(unsigned long arg)
1897 {
1898         struct sk_buff *skb;
1899         struct sock *sk;
1900         struct dst_entry *dst;
1901         struct xfrm_policy *pol = (struct xfrm_policy *)arg;
1902         struct net *net = xp_net(pol);
1903         struct xfrm_policy_queue *pq = &pol->polq;
1904         struct flowi fl;
1905         struct sk_buff_head list;
1906
1907         spin_lock(&pq->hold_queue.lock);
1908         skb = skb_peek(&pq->hold_queue);
1909         if (!skb) {
1910                 spin_unlock(&pq->hold_queue.lock);
1911                 goto out;
1912         }
1913         dst = skb_dst(skb);
1914         sk = skb->sk;
1915         xfrm_decode_session(skb, &fl, dst->ops->family);
1916         spin_unlock(&pq->hold_queue.lock);
1917
1918         dst_hold(dst->path);
1919         dst = xfrm_lookup(net, dst->path, &fl, sk, 0);
1920         if (IS_ERR(dst))
1921                 goto purge_queue;
1922
1923         if (dst->flags & DST_XFRM_QUEUE) {
1924                 dst_release(dst);
1925
1926                 if (pq->timeout >= XFRM_QUEUE_TMO_MAX)
1927                         goto purge_queue;
1928
1929                 pq->timeout = pq->timeout << 1;
1930                 if (!mod_timer(&pq->hold_timer, jiffies + pq->timeout))
1931                         xfrm_pol_hold(pol);
1932         goto out;
1933         }
1934
1935         dst_release(dst);
1936
1937         __skb_queue_head_init(&list);
1938
1939         spin_lock(&pq->hold_queue.lock);
1940         pq->timeout = 0;
1941         skb_queue_splice_init(&pq->hold_queue, &list);
1942         spin_unlock(&pq->hold_queue.lock);
1943
1944         while (!skb_queue_empty(&list)) {
1945                 skb = __skb_dequeue(&list);
1946
1947                 xfrm_decode_session(skb, &fl, skb_dst(skb)->ops->family);
1948                 dst_hold(skb_dst(skb)->path);
1949                 dst = xfrm_lookup(net, skb_dst(skb)->path, &fl, skb->sk, 0);
1950                 if (IS_ERR(dst)) {
1951                         kfree_skb(skb);
1952                         continue;
1953                 }
1954
1955                 nf_reset(skb);
1956                 skb_dst_drop(skb);
1957                 skb_dst_set(skb, dst);
1958
1959                 dst_output(net, skb->sk, skb);
1960         }
1961
1962 out:
1963         xfrm_pol_put(pol);
1964         return;
1965
1966 purge_queue:
1967         pq->timeout = 0;
1968         skb_queue_purge(&pq->hold_queue);
1969         xfrm_pol_put(pol);
1970 }
1971
1972 static int xdst_queue_output(struct net *net, struct sock *sk, struct sk_buff *skb)
1973 {
1974         unsigned long sched_next;
1975         struct dst_entry *dst = skb_dst(skb);
1976         struct xfrm_dst *xdst = (struct xfrm_dst *) dst;
1977         struct xfrm_policy *pol = xdst->pols[0];
1978         struct xfrm_policy_queue *pq = &pol->polq;
1979
1980         if (unlikely(skb_fclone_busy(sk, skb))) {
1981                 kfree_skb(skb);
1982                 return 0;
1983         }
1984
1985         if (pq->hold_queue.qlen > XFRM_MAX_QUEUE_LEN) {
1986                 kfree_skb(skb);
1987                 return -EAGAIN;
1988         }
1989
1990         skb_dst_force(skb);
1991
1992         spin_lock_bh(&pq->hold_queue.lock);
1993
1994         if (!pq->timeout)
1995                 pq->timeout = XFRM_QUEUE_TMO_MIN;
1996
1997         sched_next = jiffies + pq->timeout;
1998
1999         if (del_timer(&pq->hold_timer)) {
2000                 if (time_before(pq->hold_timer.expires, sched_next))
2001                         sched_next = pq->hold_timer.expires;
2002                 xfrm_pol_put(pol);
2003         }
2004
2005         __skb_queue_tail(&pq->hold_queue, skb);
2006         if (!mod_timer(&pq->hold_timer, sched_next))
2007                 xfrm_pol_hold(pol);
2008
2009         spin_unlock_bh(&pq->hold_queue.lock);
2010
2011         return 0;
2012 }
2013
2014 static struct xfrm_dst *xfrm_create_dummy_bundle(struct net *net,
2015                                                  struct xfrm_flo *xflo,
2016                                                  const struct flowi *fl,
2017                                                  int num_xfrms,
2018                                                  u16 family)
2019 {
2020         int err;
2021         struct net_device *dev;
2022         struct dst_entry *dst;
2023         struct dst_entry *dst1;
2024         struct xfrm_dst *xdst;
2025
2026         xdst = xfrm_alloc_dst(net, family);
2027         if (IS_ERR(xdst))
2028                 return xdst;
2029
2030         if (!(xflo->flags & XFRM_LOOKUP_QUEUE) ||
2031             net->xfrm.sysctl_larval_drop ||
2032             num_xfrms <= 0)
2033                 return xdst;
2034
2035         dst = xflo->dst_orig;
2036         dst1 = &xdst->u.dst;
2037         dst_hold(dst);
2038         xdst->route = dst;
2039
2040         dst_copy_metrics(dst1, dst);
2041
2042         dst1->obsolete = DST_OBSOLETE_FORCE_CHK;
2043         dst1->flags |= DST_HOST | DST_XFRM_QUEUE;
2044         dst1->lastuse = jiffies;
2045
2046         dst1->input = dst_discard;
2047         dst1->output = xdst_queue_output;
2048
2049         dst_hold(dst);
2050         dst1->child = dst;
2051         dst1->path = dst;
2052
2053         xfrm_init_path((struct xfrm_dst *)dst1, dst, 0);
2054
2055         err = -ENODEV;
2056         dev = dst->dev;
2057         if (!dev)
2058                 goto free_dst;
2059
2060         err = xfrm_fill_dst(xdst, dev, fl);
2061         if (err)
2062                 goto free_dst;
2063
2064 out:
2065         return xdst;
2066
2067 free_dst:
2068         dst_release(dst1);
2069         xdst = ERR_PTR(err);
2070         goto out;
2071 }
2072
2073 static struct flow_cache_object *
2074 xfrm_bundle_lookup(struct net *net, const struct flowi *fl, u16 family, u8 dir,
2075                    struct flow_cache_object *oldflo, void *ctx)
2076 {
2077         struct xfrm_flo *xflo = (struct xfrm_flo *)ctx;
2078         struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
2079         struct xfrm_dst *xdst, *new_xdst;
2080         int num_pols = 0, num_xfrms = 0, i, err, pol_dead;
2081
2082         /* Check if the policies from old bundle are usable */
2083         xdst = NULL;
2084         if (oldflo) {
2085                 xdst = container_of(oldflo, struct xfrm_dst, flo);
2086                 num_pols = xdst->num_pols;
2087                 num_xfrms = xdst->num_xfrms;
2088                 pol_dead = 0;
2089                 for (i = 0; i < num_pols; i++) {
2090                         pols[i] = xdst->pols[i];
2091                         pol_dead |= pols[i]->walk.dead;
2092                 }
2093                 if (pol_dead) {
2094                         dst_free(&xdst->u.dst);
2095                         xdst = NULL;
2096                         num_pols = 0;
2097                         num_xfrms = 0;
2098                         oldflo = NULL;
2099                 }
2100         }
2101
2102         /* Resolve policies to use if we couldn't get them from
2103          * previous cache entry */
2104         if (xdst == NULL) {
2105                 num_pols = 1;
2106                 pols[0] = __xfrm_policy_lookup(net, fl, family,
2107                                                flow_to_policy_dir(dir));
2108                 err = xfrm_expand_policies(fl, family, pols,
2109                                            &num_pols, &num_xfrms);
2110                 if (err < 0)
2111                         goto inc_error;
2112                 if (num_pols == 0)
2113                         return NULL;
2114                 if (num_xfrms <= 0)
2115                         goto make_dummy_bundle;
2116         }
2117
2118         new_xdst = xfrm_resolve_and_create_bundle(pols, num_pols, fl, family,
2119                                                   xflo->dst_orig);
2120         if (IS_ERR(new_xdst)) {
2121                 err = PTR_ERR(new_xdst);
2122                 if (err != -EAGAIN)
2123                         goto error;
2124                 if (oldflo == NULL)
2125                         goto make_dummy_bundle;
2126                 dst_hold(&xdst->u.dst);
2127                 return oldflo;
2128         } else if (new_xdst == NULL) {
2129                 num_xfrms = 0;
2130                 if (oldflo == NULL)
2131                         goto make_dummy_bundle;
2132                 xdst->num_xfrms = 0;
2133                 dst_hold(&xdst->u.dst);
2134                 return oldflo;
2135         }
2136
2137         /* Kill the previous bundle */
2138         if (xdst) {
2139                 /* The policies were stolen for newly generated bundle */
2140                 xdst->num_pols = 0;
2141                 dst_free(&xdst->u.dst);
2142         }
2143
2144         /* Flow cache does not have reference, it dst_free()'s,
2145          * but we do need to return one reference for original caller */
2146         dst_hold(&new_xdst->u.dst);
2147         return &new_xdst->flo;
2148
2149 make_dummy_bundle:
2150         /* We found policies, but there's no bundles to instantiate:
2151          * either because the policy blocks, has no transformations or
2152          * we could not build template (no xfrm_states).*/
2153         xdst = xfrm_create_dummy_bundle(net, xflo, fl, num_xfrms, family);
2154         if (IS_ERR(xdst)) {
2155                 xfrm_pols_put(pols, num_pols);
2156                 return ERR_CAST(xdst);
2157         }
2158         xdst->num_pols = num_pols;
2159         xdst->num_xfrms = num_xfrms;
2160         memcpy(xdst->pols, pols, sizeof(struct xfrm_policy *) * num_pols);
2161
2162         dst_hold(&xdst->u.dst);
2163         return &xdst->flo;
2164
2165 inc_error:
2166         XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLERROR);
2167 error:
2168         if (xdst != NULL)
2169                 dst_free(&xdst->u.dst);
2170         else
2171                 xfrm_pols_put(pols, num_pols);
2172         return ERR_PTR(err);
2173 }
2174
2175 static struct dst_entry *make_blackhole(struct net *net, u16 family,
2176                                         struct dst_entry *dst_orig)
2177 {
2178         struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
2179         struct dst_entry *ret;
2180
2181         if (!afinfo) {
2182                 dst_release(dst_orig);
2183                 return ERR_PTR(-EINVAL);
2184         } else {
2185                 ret = afinfo->blackhole_route(net, dst_orig);
2186         }
2187         xfrm_policy_put_afinfo(afinfo);
2188
2189         return ret;
2190 }
2191
2192 /* Main function: finds/creates a bundle for given flow.
2193  *
2194  * At the moment we eat a raw IP route. Mostly to speed up lookups
2195  * on interfaces with disabled IPsec.
2196  */
2197 struct dst_entry *xfrm_lookup(struct net *net, struct dst_entry *dst_orig,
2198                               const struct flowi *fl,
2199                               const struct sock *sk, int flags)
2200 {
2201         struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
2202         struct flow_cache_object *flo;
2203         struct xfrm_dst *xdst;
2204         struct dst_entry *dst, *route;
2205         u16 family = dst_orig->ops->family;
2206         u8 dir = policy_to_flow_dir(XFRM_POLICY_OUT);
2207         int i, err, num_pols, num_xfrms = 0, drop_pols = 0;
2208
2209         dst = NULL;
2210         xdst = NULL;
2211         route = NULL;
2212
2213         sk = sk_const_to_full_sk(sk);
2214         if (sk && sk->sk_policy[XFRM_POLICY_OUT]) {
2215                 num_pols = 1;
2216                 pols[0] = xfrm_sk_policy_lookup(sk, XFRM_POLICY_OUT, fl, family);
2217                 err = xfrm_expand_policies(fl, family, pols,
2218                                            &num_pols, &num_xfrms);
2219                 if (err < 0)
2220                         goto dropdst;
2221
2222                 if (num_pols) {
2223                         if (num_xfrms <= 0) {
2224                                 drop_pols = num_pols;
2225                                 goto no_transform;
2226                         }
2227
2228                         xdst = xfrm_resolve_and_create_bundle(
2229                                         pols, num_pols, fl,
2230                                         family, dst_orig);
2231                         if (IS_ERR(xdst)) {
2232                                 xfrm_pols_put(pols, num_pols);
2233                                 err = PTR_ERR(xdst);
2234                                 goto dropdst;
2235                         } else if (xdst == NULL) {
2236                                 num_xfrms = 0;
2237                                 drop_pols = num_pols;
2238                                 goto no_transform;
2239                         }
2240
2241                         dst_hold(&xdst->u.dst);
2242                         xdst->u.dst.flags |= DST_NOCACHE;
2243                         route = xdst->route;
2244                 }
2245         }
2246
2247         if (xdst == NULL) {
2248                 struct xfrm_flo xflo;
2249
2250                 xflo.dst_orig = dst_orig;
2251                 xflo.flags = flags;
2252
2253                 /* To accelerate a bit...  */
2254                 if ((dst_orig->flags & DST_NOXFRM) ||
2255                     !net->xfrm.policy_count[XFRM_POLICY_OUT])
2256                         goto nopol;
2257
2258                 flo = flow_cache_lookup(net, fl, family, dir,
2259                                         xfrm_bundle_lookup, &xflo);
2260                 if (flo == NULL)
2261                         goto nopol;
2262                 if (IS_ERR(flo)) {
2263                         err = PTR_ERR(flo);
2264                         goto dropdst;
2265                 }
2266                 xdst = container_of(flo, struct xfrm_dst, flo);
2267
2268                 num_pols = xdst->num_pols;
2269                 num_xfrms = xdst->num_xfrms;
2270                 memcpy(pols, xdst->pols, sizeof(struct xfrm_policy *) * num_pols);
2271                 route = xdst->route;
2272         }
2273
2274         dst = &xdst->u.dst;
2275         if (route == NULL && num_xfrms > 0) {
2276                 /* The only case when xfrm_bundle_lookup() returns a
2277                  * bundle with null route, is when the template could
2278                  * not be resolved. It means policies are there, but
2279                  * bundle could not be created, since we don't yet
2280                  * have the xfrm_state's. We need to wait for KM to
2281                  * negotiate new SA's or bail out with error.*/
2282                 if (net->xfrm.sysctl_larval_drop) {
2283                         XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTNOSTATES);
2284                         err = -EREMOTE;
2285                         goto error;
2286                 }
2287
2288                 err = -EAGAIN;
2289
2290                 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTNOSTATES);
2291                 goto error;
2292         }
2293
2294 no_transform:
2295         if (num_pols == 0)
2296                 goto nopol;
2297
2298         if ((flags & XFRM_LOOKUP_ICMP) &&
2299             !(pols[0]->flags & XFRM_POLICY_ICMP)) {
2300                 err = -ENOENT;
2301                 goto error;
2302         }
2303
2304         for (i = 0; i < num_pols; i++)
2305                 pols[i]->curlft.use_time = get_seconds();
2306
2307         if (num_xfrms < 0) {
2308                 /* Prohibit the flow */
2309                 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLBLOCK);
2310                 err = -EPERM;
2311                 goto error;
2312         } else if (num_xfrms > 0) {
2313                 /* Flow transformed */
2314                 dst_release(dst_orig);
2315         } else {
2316                 /* Flow passes untransformed */
2317                 dst_release(dst);
2318                 dst = dst_orig;
2319         }
2320 ok:
2321         xfrm_pols_put(pols, drop_pols);
2322         if (dst && dst->xfrm &&
2323             dst->xfrm->props.mode == XFRM_MODE_TUNNEL)
2324                 dst->flags |= DST_XFRM_TUNNEL;
2325         return dst;
2326
2327 nopol:
2328         if (!(flags & XFRM_LOOKUP_ICMP)) {
2329                 dst = dst_orig;
2330                 goto ok;
2331         }
2332         err = -ENOENT;
2333 error:
2334         dst_release(dst);
2335 dropdst:
2336         if (!(flags & XFRM_LOOKUP_KEEP_DST_REF))
2337                 dst_release(dst_orig);
2338         xfrm_pols_put(pols, drop_pols);
2339         return ERR_PTR(err);
2340 }
2341 EXPORT_SYMBOL(xfrm_lookup);
2342
2343 /* Callers of xfrm_lookup_route() must ensure a call to dst_output().
2344  * Otherwise we may send out blackholed packets.
2345  */
2346 struct dst_entry *xfrm_lookup_route(struct net *net, struct dst_entry *dst_orig,
2347                                     const struct flowi *fl,
2348                                     const struct sock *sk, int flags)
2349 {
2350         struct dst_entry *dst = xfrm_lookup(net, dst_orig, fl, sk,
2351                                             flags | XFRM_LOOKUP_QUEUE |
2352                                             XFRM_LOOKUP_KEEP_DST_REF);
2353
2354         if (IS_ERR(dst) && PTR_ERR(dst) == -EREMOTE)
2355                 return make_blackhole(net, dst_orig->ops->family, dst_orig);
2356
2357         if (IS_ERR(dst))
2358                 dst_release(dst_orig);
2359
2360         return dst;
2361 }
2362 EXPORT_SYMBOL(xfrm_lookup_route);
2363
2364 static inline int
2365 xfrm_secpath_reject(int idx, struct sk_buff *skb, const struct flowi *fl)
2366 {
2367         struct xfrm_state *x;
2368
2369         if (!skb->sp || idx < 0 || idx >= skb->sp->len)
2370                 return 0;
2371         x = skb->sp->xvec[idx];
2372         if (!x->type->reject)
2373                 return 0;
2374         return x->type->reject(x, skb, fl);
2375 }
2376
2377 /* When skb is transformed back to its "native" form, we have to
2378  * check policy restrictions. At the moment we make this in maximally
2379  * stupid way. Shame on me. :-) Of course, connected sockets must
2380  * have policy cached at them.
2381  */
2382
2383 static inline int
2384 xfrm_state_ok(const struct xfrm_tmpl *tmpl, const struct xfrm_state *x,
2385               unsigned short family)
2386 {
2387         if (xfrm_state_kern(x))
2388                 return tmpl->optional && !xfrm_state_addr_cmp(tmpl, x, tmpl->encap_family);
2389         return  x->id.proto == tmpl->id.proto &&
2390                 (x->id.spi == tmpl->id.spi || !tmpl->id.spi) &&
2391                 (x->props.reqid == tmpl->reqid || !tmpl->reqid) &&
2392                 x->props.mode == tmpl->mode &&
2393                 (tmpl->allalgs || (tmpl->aalgos & (1<<x->props.aalgo)) ||
2394                  !(xfrm_id_proto_match(tmpl->id.proto, IPSEC_PROTO_ANY))) &&
2395                 !(x->props.mode != XFRM_MODE_TRANSPORT &&
2396                   xfrm_state_addr_cmp(tmpl, x, family));
2397 }
2398
2399 /*
2400  * 0 or more than 0 is returned when validation is succeeded (either bypass
2401  * because of optional transport mode, or next index of the mathced secpath
2402  * state with the template.
2403  * -1 is returned when no matching template is found.
2404  * Otherwise "-2 - errored_index" is returned.
2405  */
2406 static inline int
2407 xfrm_policy_ok(const struct xfrm_tmpl *tmpl, const struct sec_path *sp, int start,
2408                unsigned short family)
2409 {
2410         int idx = start;
2411
2412         if (tmpl->optional) {
2413                 if (tmpl->mode == XFRM_MODE_TRANSPORT)
2414                         return start;
2415         } else
2416                 start = -1;
2417         for (; idx < sp->len; idx++) {
2418                 if (xfrm_state_ok(tmpl, sp->xvec[idx], family))
2419                         return ++idx;
2420                 if (sp->xvec[idx]->props.mode != XFRM_MODE_TRANSPORT) {
2421                         if (start == -1)
2422                                 start = -2-idx;
2423                         break;
2424                 }
2425         }
2426         return start;
2427 }
2428
2429 int __xfrm_decode_session(struct sk_buff *skb, struct flowi *fl,
2430                           unsigned int family, int reverse)
2431 {
2432         struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
2433         int err;
2434
2435         if (unlikely(afinfo == NULL))
2436                 return -EAFNOSUPPORT;
2437
2438         afinfo->decode_session(skb, fl, reverse);
2439         err = security_xfrm_decode_session(skb, &fl->flowi_secid);
2440         xfrm_policy_put_afinfo(afinfo);
2441         return err;
2442 }
2443 EXPORT_SYMBOL(__xfrm_decode_session);
2444
2445 static inline int secpath_has_nontransport(const struct sec_path *sp, int k, int *idxp)
2446 {
2447         for (; k < sp->len; k++) {
2448                 if (sp->xvec[k]->props.mode != XFRM_MODE_TRANSPORT) {
2449                         *idxp = k;
2450                         return 1;
2451                 }
2452         }
2453
2454         return 0;
2455 }
2456
2457 int __xfrm_policy_check(struct sock *sk, int dir, struct sk_buff *skb,
2458                         unsigned short family)
2459 {
2460         struct net *net = dev_net(skb->dev);
2461         struct xfrm_policy *pol;
2462         struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
2463         int npols = 0;
2464         int xfrm_nr;
2465         int pi;
2466         int reverse;
2467         struct flowi fl;
2468         u8 fl_dir;
2469         int xerr_idx = -1;
2470
2471         reverse = dir & ~XFRM_POLICY_MASK;
2472         dir &= XFRM_POLICY_MASK;
2473         fl_dir = policy_to_flow_dir(dir);
2474
2475         if (__xfrm_decode_session(skb, &fl, family, reverse) < 0) {
2476                 XFRM_INC_STATS(net, LINUX_MIB_XFRMINHDRERROR);
2477                 return 0;
2478         }
2479
2480         nf_nat_decode_session(skb, &fl, family);
2481
2482         /* First, check used SA against their selectors. */
2483         if (skb->sp) {
2484                 int i;
2485
2486                 for (i = skb->sp->len-1; i >= 0; i--) {
2487                         struct xfrm_state *x = skb->sp->xvec[i];
2488                         if (!xfrm_selector_match(&x->sel, &fl, family)) {
2489                                 XFRM_INC_STATS(net, LINUX_MIB_XFRMINSTATEMISMATCH);
2490                                 return 0;
2491                         }
2492                 }
2493         }
2494
2495         pol = NULL;
2496         sk = sk_to_full_sk(sk);
2497         if (sk && sk->sk_policy[dir]) {
2498                 pol = xfrm_sk_policy_lookup(sk, dir, &fl, family);
2499                 if (IS_ERR(pol)) {
2500                         XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
2501                         return 0;
2502                 }
2503         }
2504
2505         if (!pol) {
2506                 struct flow_cache_object *flo;
2507
2508                 flo = flow_cache_lookup(net, &fl, family, fl_dir,
2509                                         xfrm_policy_lookup, NULL);
2510                 if (IS_ERR_OR_NULL(flo))
2511                         pol = ERR_CAST(flo);
2512                 else
2513                         pol = container_of(flo, struct xfrm_policy, flo);
2514         }
2515
2516         if (IS_ERR(pol)) {
2517                 XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
2518                 return 0;
2519         }
2520
2521         if (!pol) {
2522                 if (skb->sp && secpath_has_nontransport(skb->sp, 0, &xerr_idx)) {
2523                         xfrm_secpath_reject(xerr_idx, skb, &fl);
2524                         XFRM_INC_STATS(net, LINUX_MIB_XFRMINNOPOLS);
2525                         return 0;
2526                 }
2527                 return 1;
2528         }
2529
2530         pol->curlft.use_time = get_seconds();
2531
2532         pols[0] = pol;
2533         npols++;
2534 #ifdef CONFIG_XFRM_SUB_POLICY
2535         if (pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
2536                 pols[1] = xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_MAIN,
2537                                                     &fl, family,
2538                                                     XFRM_POLICY_IN);
2539                 if (pols[1]) {
2540                         if (IS_ERR(pols[1])) {
2541                                 XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
2542                                 return 0;
2543                         }
2544                         pols[1]->curlft.use_time = get_seconds();
2545                         npols++;
2546                 }
2547         }
2548 #endif
2549
2550         if (pol->action == XFRM_POLICY_ALLOW) {
2551                 struct sec_path *sp;
2552                 static struct sec_path dummy;
2553                 struct xfrm_tmpl *tp[XFRM_MAX_DEPTH];
2554                 struct xfrm_tmpl *stp[XFRM_MAX_DEPTH];
2555                 struct xfrm_tmpl **tpp = tp;
2556                 int ti = 0;
2557                 int i, k;
2558
2559                 if ((sp = skb->sp) == NULL)
2560                         sp = &dummy;
2561
2562                 for (pi = 0; pi < npols; pi++) {
2563                         if (pols[pi] != pol &&
2564                             pols[pi]->action != XFRM_POLICY_ALLOW) {
2565                                 XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLBLOCK);
2566                                 goto reject;
2567                         }
2568                         if (ti + pols[pi]->xfrm_nr >= XFRM_MAX_DEPTH) {
2569                                 XFRM_INC_STATS(net, LINUX_MIB_XFRMINBUFFERERROR);
2570                                 goto reject_error;
2571                         }
2572                         for (i = 0; i < pols[pi]->xfrm_nr; i++)
2573                                 tpp[ti++] = &pols[pi]->xfrm_vec[i];
2574                 }
2575                 xfrm_nr = ti;
2576                 if (npols > 1) {
2577                         xfrm_tmpl_sort(stp, tpp, xfrm_nr, family, net);
2578                         tpp = stp;
2579                 }
2580
2581                 /* For each tunnel xfrm, find the first matching tmpl.
2582                  * For each tmpl before that, find corresponding xfrm.
2583                  * Order is _important_. Later we will implement
2584                  * some barriers, but at the moment barriers
2585                  * are implied between each two transformations.
2586                  */
2587                 for (i = xfrm_nr-1, k = 0; i >= 0; i--) {
2588                         k = xfrm_policy_ok(tpp[i], sp, k, family);
2589                         if (k < 0) {
2590                                 if (k < -1)
2591                                         /* "-2 - errored_index" returned */
2592                                         xerr_idx = -(2+k);
2593                                 XFRM_INC_STATS(net, LINUX_MIB_XFRMINTMPLMISMATCH);
2594                                 goto reject;
2595                         }
2596                 }
2597
2598                 if (secpath_has_nontransport(sp, k, &xerr_idx)) {
2599                         XFRM_INC_STATS(net, LINUX_MIB_XFRMINTMPLMISMATCH);
2600                         goto reject;
2601                 }
2602
2603                 xfrm_pols_put(pols, npols);
2604                 return 1;
2605         }
2606         XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLBLOCK);
2607
2608 reject:
2609         xfrm_secpath_reject(xerr_idx, skb, &fl);
2610 reject_error:
2611         xfrm_pols_put(pols, npols);
2612         return 0;
2613 }
2614 EXPORT_SYMBOL(__xfrm_policy_check);
2615
2616 int __xfrm_route_forward(struct sk_buff *skb, unsigned short family)
2617 {
2618         struct net *net = dev_net(skb->dev);
2619         struct flowi fl;
2620         struct dst_entry *dst;
2621         int res = 1;
2622
2623         if (xfrm_decode_session(skb, &fl, family) < 0) {
2624                 XFRM_INC_STATS(net, LINUX_MIB_XFRMFWDHDRERROR);
2625                 return 0;
2626         }
2627
2628         skb_dst_force(skb);
2629
2630         dst = xfrm_lookup(net, skb_dst(skb), &fl, NULL, XFRM_LOOKUP_QUEUE);
2631         if (IS_ERR(dst)) {
2632                 res = 0;
2633                 dst = NULL;
2634         }
2635         skb_dst_set(skb, dst);
2636         return res;
2637 }
2638 EXPORT_SYMBOL(__xfrm_route_forward);
2639
2640 /* Optimize later using cookies and generation ids. */
2641
2642 static struct dst_entry *xfrm_dst_check(struct dst_entry *dst, u32 cookie)
2643 {
2644         /* Code (such as __xfrm4_bundle_create()) sets dst->obsolete
2645          * to DST_OBSOLETE_FORCE_CHK to force all XFRM destinations to
2646          * get validated by dst_ops->check on every use.  We do this
2647          * because when a normal route referenced by an XFRM dst is
2648          * obsoleted we do not go looking around for all parent
2649          * referencing XFRM dsts so that we can invalidate them.  It
2650          * is just too much work.  Instead we make the checks here on
2651          * every use.  For example:
2652          *
2653          *      XFRM dst A --> IPv4 dst X
2654          *
2655          * X is the "xdst->route" of A (X is also the "dst->path" of A
2656          * in this example).  If X is marked obsolete, "A" will not
2657          * notice.  That's what we are validating here via the
2658          * stale_bundle() check.
2659          *
2660          * When a policy's bundle is pruned, we dst_free() the XFRM
2661          * dst which causes it's ->obsolete field to be set to
2662          * DST_OBSOLETE_DEAD.  If an XFRM dst has been pruned like
2663          * this, we want to force a new route lookup.
2664          */
2665         if (dst->obsolete < 0 && !stale_bundle(dst))
2666                 return dst;
2667
2668         return NULL;
2669 }
2670
2671 static int stale_bundle(struct dst_entry *dst)
2672 {
2673         return !xfrm_bundle_ok((struct xfrm_dst *)dst);
2674 }
2675
2676 void xfrm_dst_ifdown(struct dst_entry *dst, struct net_device *dev)
2677 {
2678         while ((dst = dst->child) && dst->xfrm && dst->dev == dev) {
2679                 dst->dev = dev_net(dev)->loopback_dev;
2680                 dev_hold(dst->dev);
2681                 dev_put(dev);
2682         }
2683 }
2684 EXPORT_SYMBOL(xfrm_dst_ifdown);
2685
2686 static void xfrm_link_failure(struct sk_buff *skb)
2687 {
2688         /* Impossible. Such dst must be popped before reaches point of failure. */
2689 }
2690
2691 static struct dst_entry *xfrm_negative_advice(struct dst_entry *dst)
2692 {
2693         if (dst) {
2694                 if (dst->obsolete) {
2695                         dst_release(dst);
2696                         dst = NULL;
2697                 }
2698         }
2699         return dst;
2700 }
2701
2702 void xfrm_garbage_collect(struct net *net)
2703 {
2704         flow_cache_flush(net);
2705 }
2706 EXPORT_SYMBOL(xfrm_garbage_collect);
2707
2708 static void xfrm_garbage_collect_deferred(struct net *net)
2709 {
2710         flow_cache_flush_deferred(net);
2711 }
2712
2713 static void xfrm_init_pmtu(struct dst_entry *dst)
2714 {
2715         do {
2716                 struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
2717                 u32 pmtu, route_mtu_cached;
2718
2719                 pmtu = dst_mtu(dst->child);
2720                 xdst->child_mtu_cached = pmtu;
2721
2722                 pmtu = xfrm_state_mtu(dst->xfrm, pmtu);
2723
2724                 route_mtu_cached = dst_mtu(xdst->route);
2725                 xdst->route_mtu_cached = route_mtu_cached;
2726
2727                 if (pmtu > route_mtu_cached)
2728                         pmtu = route_mtu_cached;
2729
2730                 dst_metric_set(dst, RTAX_MTU, pmtu);
2731         } while ((dst = dst->next));
2732 }
2733
2734 /* Check that the bundle accepts the flow and its components are
2735  * still valid.
2736  */
2737
2738 static int xfrm_bundle_ok(struct xfrm_dst *first)
2739 {
2740         struct dst_entry *dst = &first->u.dst;
2741         struct xfrm_dst *last;
2742         u32 mtu;
2743
2744         if (!dst_check(dst->path, ((struct xfrm_dst *)dst)->path_cookie) ||
2745             (dst->dev && !netif_running(dst->dev)))
2746                 return 0;
2747
2748         if (dst->flags & DST_XFRM_QUEUE)
2749                 return 1;
2750
2751         last = NULL;
2752
2753         do {
2754                 struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
2755
2756                 if (dst->xfrm->km.state != XFRM_STATE_VALID)
2757                         return 0;
2758                 if (xdst->xfrm_genid != dst->xfrm->genid)
2759                         return 0;
2760                 if (xdst->num_pols > 0 &&
2761                     xdst->policy_genid != atomic_read(&xdst->pols[0]->genid))
2762                         return 0;
2763
2764                 mtu = dst_mtu(dst->child);
2765                 if (xdst->child_mtu_cached != mtu) {
2766                         last = xdst;
2767                         xdst->child_mtu_cached = mtu;
2768                 }
2769
2770                 if (!dst_check(xdst->route, xdst->route_cookie))
2771                         return 0;
2772                 mtu = dst_mtu(xdst->route);
2773                 if (xdst->route_mtu_cached != mtu) {
2774                         last = xdst;
2775                         xdst->route_mtu_cached = mtu;
2776                 }
2777
2778                 dst = dst->child;
2779         } while (dst->xfrm);
2780
2781         if (likely(!last))
2782                 return 1;
2783
2784         mtu = last->child_mtu_cached;
2785         for (;;) {
2786                 dst = &last->u.dst;
2787
2788                 mtu = xfrm_state_mtu(dst->xfrm, mtu);
2789                 if (mtu > last->route_mtu_cached)
2790                         mtu = last->route_mtu_cached;
2791                 dst_metric_set(dst, RTAX_MTU, mtu);
2792
2793                 if (last == first)
2794                         break;
2795
2796                 last = (struct xfrm_dst *)last->u.dst.next;
2797                 last->child_mtu_cached = mtu;
2798         }
2799
2800         return 1;
2801 }
2802
2803 static unsigned int xfrm_default_advmss(const struct dst_entry *dst)
2804 {
2805         return dst_metric_advmss(dst->path);
2806 }
2807
2808 static unsigned int xfrm_mtu(const struct dst_entry *dst)
2809 {
2810         unsigned int mtu = dst_metric_raw(dst, RTAX_MTU);
2811
2812         return mtu ? : dst_mtu(dst->path);
2813 }
2814
2815 static struct neighbour *xfrm_neigh_lookup(const struct dst_entry *dst,
2816                                            struct sk_buff *skb,
2817                                            const void *daddr)
2818 {
2819         return dst->path->ops->neigh_lookup(dst, skb, daddr);
2820 }
2821
2822 int xfrm_policy_register_afinfo(struct xfrm_policy_afinfo *afinfo)
2823 {
2824         int err = 0;
2825         if (unlikely(afinfo == NULL))
2826                 return -EINVAL;
2827         if (unlikely(afinfo->family >= NPROTO))
2828                 return -EAFNOSUPPORT;
2829         spin_lock(&xfrm_policy_afinfo_lock);
2830         if (unlikely(xfrm_policy_afinfo[afinfo->family] != NULL))
2831                 err = -EEXIST;
2832         else {
2833                 struct dst_ops *dst_ops = afinfo->dst_ops;
2834                 if (likely(dst_ops->kmem_cachep == NULL))
2835                         dst_ops->kmem_cachep = xfrm_dst_cache;
2836                 if (likely(dst_ops->check == NULL))
2837                         dst_ops->check = xfrm_dst_check;
2838                 if (likely(dst_ops->default_advmss == NULL))
2839                         dst_ops->default_advmss = xfrm_default_advmss;
2840                 if (likely(dst_ops->mtu == NULL))
2841                         dst_ops->mtu = xfrm_mtu;
2842                 if (likely(dst_ops->negative_advice == NULL))
2843                         dst_ops->negative_advice = xfrm_negative_advice;
2844                 if (likely(dst_ops->link_failure == NULL))
2845                         dst_ops->link_failure = xfrm_link_failure;
2846                 if (likely(dst_ops->neigh_lookup == NULL))
2847                         dst_ops->neigh_lookup = xfrm_neigh_lookup;
2848                 if (likely(afinfo->garbage_collect == NULL))
2849                         afinfo->garbage_collect = xfrm_garbage_collect_deferred;
2850                 rcu_assign_pointer(xfrm_policy_afinfo[afinfo->family], afinfo);
2851         }
2852         spin_unlock(&xfrm_policy_afinfo_lock);
2853
2854         return err;
2855 }
2856 EXPORT_SYMBOL(xfrm_policy_register_afinfo);
2857
2858 int xfrm_policy_unregister_afinfo(struct xfrm_policy_afinfo *afinfo)
2859 {
2860         int err = 0;
2861         if (unlikely(afinfo == NULL))
2862                 return -EINVAL;
2863         if (unlikely(afinfo->family >= NPROTO))
2864                 return -EAFNOSUPPORT;
2865         spin_lock(&xfrm_policy_afinfo_lock);
2866         if (likely(xfrm_policy_afinfo[afinfo->family] != NULL)) {
2867                 if (unlikely(xfrm_policy_afinfo[afinfo->family] != afinfo))
2868                         err = -EINVAL;
2869                 else
2870                         RCU_INIT_POINTER(xfrm_policy_afinfo[afinfo->family],
2871                                          NULL);
2872         }
2873         spin_unlock(&xfrm_policy_afinfo_lock);
2874         if (!err) {
2875                 struct dst_ops *dst_ops = afinfo->dst_ops;
2876
2877                 synchronize_rcu();
2878
2879                 dst_ops->kmem_cachep = NULL;
2880                 dst_ops->check = NULL;
2881                 dst_ops->negative_advice = NULL;
2882                 dst_ops->link_failure = NULL;
2883                 afinfo->garbage_collect = NULL;
2884         }
2885         return err;
2886 }
2887 EXPORT_SYMBOL(xfrm_policy_unregister_afinfo);
2888
2889 static int xfrm_dev_event(struct notifier_block *this, unsigned long event, void *ptr)
2890 {
2891         struct net_device *dev = netdev_notifier_info_to_dev(ptr);
2892
2893         switch (event) {
2894         case NETDEV_DOWN:
2895                 xfrm_garbage_collect(dev_net(dev));
2896         }
2897         return NOTIFY_DONE;
2898 }
2899
2900 static struct notifier_block xfrm_dev_notifier = {
2901         .notifier_call  = xfrm_dev_event,
2902 };
2903
2904 #ifdef CONFIG_XFRM_STATISTICS
2905 static int __net_init xfrm_statistics_init(struct net *net)
2906 {
2907         int rv;
2908         net->mib.xfrm_statistics = alloc_percpu(struct linux_xfrm_mib);
2909         if (!net->mib.xfrm_statistics)
2910                 return -ENOMEM;
2911         rv = xfrm_proc_init(net);
2912         if (rv < 0)
2913                 free_percpu(net->mib.xfrm_statistics);
2914         return rv;
2915 }
2916
2917 static void xfrm_statistics_fini(struct net *net)
2918 {
2919         xfrm_proc_fini(net);
2920         free_percpu(net->mib.xfrm_statistics);
2921 }
2922 #else
2923 static int __net_init xfrm_statistics_init(struct net *net)
2924 {
2925         return 0;
2926 }
2927
2928 static void xfrm_statistics_fini(struct net *net)
2929 {
2930 }
2931 #endif
2932
2933 static int __net_init xfrm_policy_init(struct net *net)
2934 {
2935         unsigned int hmask, sz;
2936         int dir;
2937
2938         if (net_eq(net, &init_net))
2939                 xfrm_dst_cache = kmem_cache_create("xfrm_dst_cache",
2940                                            sizeof(struct xfrm_dst),
2941                                            0, SLAB_HWCACHE_ALIGN|SLAB_PANIC,
2942                                            NULL);
2943
2944         hmask = 8 - 1;
2945         sz = (hmask+1) * sizeof(struct hlist_head);
2946
2947         net->xfrm.policy_byidx = xfrm_hash_alloc(sz);
2948         if (!net->xfrm.policy_byidx)
2949                 goto out_byidx;
2950         net->xfrm.policy_idx_hmask = hmask;
2951
2952         for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
2953                 struct xfrm_policy_hash *htab;
2954
2955                 net->xfrm.policy_count[dir] = 0;
2956                 net->xfrm.policy_count[XFRM_POLICY_MAX + dir] = 0;
2957                 INIT_HLIST_HEAD(&net->xfrm.policy_inexact[dir]);
2958
2959                 htab = &net->xfrm.policy_bydst[dir];
2960                 htab->table = xfrm_hash_alloc(sz);
2961                 if (!htab->table)
2962                         goto out_bydst;
2963                 htab->hmask = hmask;
2964                 htab->dbits4 = 32;
2965                 htab->sbits4 = 32;
2966                 htab->dbits6 = 128;
2967                 htab->sbits6 = 128;
2968         }
2969         net->xfrm.policy_hthresh.lbits4 = 32;
2970         net->xfrm.policy_hthresh.rbits4 = 32;
2971         net->xfrm.policy_hthresh.lbits6 = 128;
2972         net->xfrm.policy_hthresh.rbits6 = 128;
2973
2974         seqlock_init(&net->xfrm.policy_hthresh.lock);
2975
2976         INIT_LIST_HEAD(&net->xfrm.policy_all);
2977         INIT_WORK(&net->xfrm.policy_hash_work, xfrm_hash_resize);
2978         INIT_WORK(&net->xfrm.policy_hthresh.work, xfrm_hash_rebuild);
2979         if (net_eq(net, &init_net))
2980                 register_netdevice_notifier(&xfrm_dev_notifier);
2981         return 0;
2982
2983 out_bydst:
2984         for (dir--; dir >= 0; dir--) {
2985                 struct xfrm_policy_hash *htab;
2986
2987                 htab = &net->xfrm.policy_bydst[dir];
2988                 xfrm_hash_free(htab->table, sz);
2989         }
2990         xfrm_hash_free(net->xfrm.policy_byidx, sz);
2991 out_byidx:
2992         return -ENOMEM;
2993 }
2994
2995 static void xfrm_policy_fini(struct net *net)
2996 {
2997         unsigned int sz;
2998         int dir;
2999
3000         flush_work(&net->xfrm.policy_hash_work);
3001 #ifdef CONFIG_XFRM_SUB_POLICY
3002         xfrm_policy_flush(net, XFRM_POLICY_TYPE_SUB, false);
3003 #endif
3004         xfrm_policy_flush(net, XFRM_POLICY_TYPE_MAIN, false);
3005
3006         WARN_ON(!list_empty(&net->xfrm.policy_all));
3007
3008         for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
3009                 struct xfrm_policy_hash *htab;
3010
3011                 WARN_ON(!hlist_empty(&net->xfrm.policy_inexact[dir]));
3012
3013                 htab = &net->xfrm.policy_bydst[dir];
3014                 sz = (htab->hmask + 1) * sizeof(struct hlist_head);
3015                 WARN_ON(!hlist_empty(htab->table));
3016                 xfrm_hash_free(htab->table, sz);
3017         }
3018
3019         sz = (net->xfrm.policy_idx_hmask + 1) * sizeof(struct hlist_head);
3020         WARN_ON(!hlist_empty(net->xfrm.policy_byidx));
3021         xfrm_hash_free(net->xfrm.policy_byidx, sz);
3022 }
3023
3024 static int __net_init xfrm_net_init(struct net *net)
3025 {
3026         int rv;
3027
3028         /* Initialize the per-net locks here */
3029         spin_lock_init(&net->xfrm.xfrm_state_lock);
3030         spin_lock_init(&net->xfrm.xfrm_policy_lock);
3031         mutex_init(&net->xfrm.xfrm_cfg_mutex);
3032
3033         rv = xfrm_statistics_init(net);
3034         if (rv < 0)
3035                 goto out_statistics;
3036         rv = xfrm_state_init(net);
3037         if (rv < 0)
3038                 goto out_state;
3039         rv = xfrm_policy_init(net);
3040         if (rv < 0)
3041                 goto out_policy;
3042         rv = xfrm_sysctl_init(net);
3043         if (rv < 0)
3044                 goto out_sysctl;
3045         rv = flow_cache_init(net);
3046         if (rv < 0)
3047                 goto out;
3048
3049         return 0;
3050
3051 out:
3052         xfrm_sysctl_fini(net);
3053 out_sysctl:
3054         xfrm_policy_fini(net);
3055 out_policy:
3056         xfrm_state_fini(net);
3057 out_state:
3058         xfrm_statistics_fini(net);
3059 out_statistics:
3060         return rv;
3061 }
3062
3063 static void __net_exit xfrm_net_exit(struct net *net)
3064 {
3065         flow_cache_fini(net);
3066         xfrm_sysctl_fini(net);
3067         xfrm_policy_fini(net);
3068         xfrm_state_fini(net);
3069         xfrm_statistics_fini(net);
3070 }
3071
3072 static struct pernet_operations __net_initdata xfrm_net_ops = {
3073         .init = xfrm_net_init,
3074         .exit = xfrm_net_exit,
3075 };
3076
3077 void __init xfrm_init(void)
3078 {
3079         register_pernet_subsys(&xfrm_net_ops);
3080         seqcount_init(&xfrm_policy_hash_generation);
3081         xfrm_input_init();
3082 }
3083
3084 #ifdef CONFIG_AUDITSYSCALL
3085 static void xfrm_audit_common_policyinfo(struct xfrm_policy *xp,
3086                                          struct audit_buffer *audit_buf)
3087 {
3088         struct xfrm_sec_ctx *ctx = xp->security;
3089         struct xfrm_selector *sel = &xp->selector;
3090
3091         if (ctx)
3092                 audit_log_format(audit_buf, " sec_alg=%u sec_doi=%u sec_obj=%s",
3093                                  ctx->ctx_alg, ctx->ctx_doi, ctx->ctx_str);
3094
3095         switch (sel->family) {
3096         case AF_INET:
3097                 audit_log_format(audit_buf, " src=%pI4", &sel->saddr.a4);
3098                 if (sel->prefixlen_s != 32)
3099                         audit_log_format(audit_buf, " src_prefixlen=%d",
3100                                          sel->prefixlen_s);
3101                 audit_log_format(audit_buf, " dst=%pI4", &sel->daddr.a4);
3102                 if (sel->prefixlen_d != 32)
3103                         audit_log_format(audit_buf, " dst_prefixlen=%d",
3104                                          sel->prefixlen_d);
3105                 break;
3106         case AF_INET6:
3107                 audit_log_format(audit_buf, " src=%pI6", sel->saddr.a6);
3108                 if (sel->prefixlen_s != 128)
3109                         audit_log_format(audit_buf, " src_prefixlen=%d",
3110                                          sel->prefixlen_s);
3111                 audit_log_format(audit_buf, " dst=%pI6", sel->daddr.a6);
3112                 if (sel->prefixlen_d != 128)
3113                         audit_log_format(audit_buf, " dst_prefixlen=%d",
3114                                          sel->prefixlen_d);
3115                 break;
3116         }
3117 }
3118
3119 void xfrm_audit_policy_add(struct xfrm_policy *xp, int result, bool task_valid)
3120 {
3121         struct audit_buffer *audit_buf;
3122
3123         audit_buf = xfrm_audit_start("SPD-add");
3124         if (audit_buf == NULL)
3125                 return;
3126         xfrm_audit_helper_usrinfo(task_valid, audit_buf);
3127         audit_log_format(audit_buf, " res=%u", result);
3128         xfrm_audit_common_policyinfo(xp, audit_buf);
3129         audit_log_end(audit_buf);
3130 }
3131 EXPORT_SYMBOL_GPL(xfrm_audit_policy_add);
3132
3133 void xfrm_audit_policy_delete(struct xfrm_policy *xp, int result,
3134                               bool task_valid)
3135 {
3136         struct audit_buffer *audit_buf;
3137
3138         audit_buf = xfrm_audit_start("SPD-delete");
3139         if (audit_buf == NULL)
3140                 return;
3141         xfrm_audit_helper_usrinfo(task_valid, audit_buf);
3142         audit_log_format(audit_buf, " res=%u", result);
3143         xfrm_audit_common_policyinfo(xp, audit_buf);
3144         audit_log_end(audit_buf);
3145 }
3146 EXPORT_SYMBOL_GPL(xfrm_audit_policy_delete);
3147 #endif
3148
3149 #ifdef CONFIG_XFRM_MIGRATE
3150 static bool xfrm_migrate_selector_match(const struct xfrm_selector *sel_cmp,
3151                                         const struct xfrm_selector *sel_tgt)
3152 {
3153         if (sel_cmp->proto == IPSEC_ULPROTO_ANY) {
3154                 if (sel_tgt->family == sel_cmp->family &&
3155                     xfrm_addr_equal(&sel_tgt->daddr, &sel_cmp->daddr,
3156                                     sel_cmp->family) &&
3157                     xfrm_addr_equal(&sel_tgt->saddr, &sel_cmp->saddr,
3158                                     sel_cmp->family) &&
3159                     sel_tgt->prefixlen_d == sel_cmp->prefixlen_d &&
3160                     sel_tgt->prefixlen_s == sel_cmp->prefixlen_s) {
3161                         return true;
3162                 }
3163         } else {
3164                 if (memcmp(sel_tgt, sel_cmp, sizeof(*sel_tgt)) == 0) {
3165                         return true;
3166                 }
3167         }
3168         return false;
3169 }
3170
3171 static struct xfrm_policy *xfrm_migrate_policy_find(const struct xfrm_selector *sel,
3172                                                     u8 dir, u8 type, struct net *net)
3173 {
3174         struct xfrm_policy *pol, *ret = NULL;
3175         struct hlist_head *chain;
3176         u32 priority = ~0U;
3177
3178         spin_lock_bh(&net->xfrm.xfrm_policy_lock);
3179         chain = policy_hash_direct(net, &sel->daddr, &sel->saddr, sel->family, dir);
3180         hlist_for_each_entry(pol, chain, bydst) {
3181                 if (xfrm_migrate_selector_match(sel, &pol->selector) &&
3182                     pol->type == type) {
3183                         ret = pol;
3184                         priority = ret->priority;
3185                         break;
3186                 }
3187         }
3188         chain = &net->xfrm.policy_inexact[dir];
3189         hlist_for_each_entry(pol, chain, bydst) {
3190                 if ((pol->priority >= priority) && ret)
3191                         break;
3192
3193                 if (xfrm_migrate_selector_match(sel, &pol->selector) &&
3194                     pol->type == type) {
3195                         ret = pol;
3196                         break;
3197                 }
3198         }
3199
3200         xfrm_pol_hold(ret);
3201
3202         spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
3203
3204         return ret;
3205 }
3206
3207 static int migrate_tmpl_match(const struct xfrm_migrate *m, const struct xfrm_tmpl *t)
3208 {
3209         int match = 0;
3210
3211         if (t->mode == m->mode && t->id.proto == m->proto &&
3212             (m->reqid == 0 || t->reqid == m->reqid)) {
3213                 switch (t->mode) {
3214                 case XFRM_MODE_TUNNEL:
3215                 case XFRM_MODE_BEET:
3216                         if (xfrm_addr_equal(&t->id.daddr, &m->old_daddr,
3217                                             m->old_family) &&
3218                             xfrm_addr_equal(&t->saddr, &m->old_saddr,
3219                                             m->old_family)) {
3220                                 match = 1;
3221                         }
3222                         break;
3223                 case XFRM_MODE_TRANSPORT:
3224                         /* in case of transport mode, template does not store
3225                            any IP addresses, hence we just compare mode and
3226                            protocol */
3227                         match = 1;
3228                         break;
3229                 default:
3230                         break;
3231                 }
3232         }
3233         return match;
3234 }
3235
3236 /* update endpoint address(es) of template(s) */
3237 static int xfrm_policy_migrate(struct xfrm_policy *pol,
3238                                struct xfrm_migrate *m, int num_migrate)
3239 {
3240         struct xfrm_migrate *mp;
3241         int i, j, n = 0;
3242
3243         write_lock_bh(&pol->lock);
3244         if (unlikely(pol->walk.dead)) {
3245                 /* target policy has been deleted */
3246                 write_unlock_bh(&pol->lock);
3247                 return -ENOENT;
3248         }
3249
3250         for (i = 0; i < pol->xfrm_nr; i++) {
3251                 for (j = 0, mp = m; j < num_migrate; j++, mp++) {
3252                         if (!migrate_tmpl_match(mp, &pol->xfrm_vec[i]))
3253                                 continue;
3254                         n++;
3255                         if (pol->xfrm_vec[i].mode != XFRM_MODE_TUNNEL &&
3256                             pol->xfrm_vec[i].mode != XFRM_MODE_BEET)
3257                                 continue;
3258                         /* update endpoints */
3259                         memcpy(&pol->xfrm_vec[i].id.daddr, &mp->new_daddr,
3260                                sizeof(pol->xfrm_vec[i].id.daddr));
3261                         memcpy(&pol->xfrm_vec[i].saddr, &mp->new_saddr,
3262                                sizeof(pol->xfrm_vec[i].saddr));
3263                         pol->xfrm_vec[i].encap_family = mp->new_family;
3264                         /* flush bundles */
3265                         atomic_inc(&pol->genid);
3266                 }
3267         }
3268
3269         write_unlock_bh(&pol->lock);
3270
3271         if (!n)
3272                 return -ENODATA;
3273
3274         return 0;
3275 }
3276
3277 static int xfrm_migrate_check(const struct xfrm_migrate *m, int num_migrate)
3278 {
3279         int i, j;
3280
3281         if (num_migrate < 1 || num_migrate > XFRM_MAX_DEPTH)
3282                 return -EINVAL;
3283
3284         for (i = 0; i < num_migrate; i++) {
3285                 if (xfrm_addr_equal(&m[i].old_daddr, &m[i].new_daddr,
3286                                     m[i].old_family) &&
3287                     xfrm_addr_equal(&m[i].old_saddr, &m[i].new_saddr,
3288                                     m[i].old_family))
3289                         return -EINVAL;
3290                 if (xfrm_addr_any(&m[i].new_daddr, m[i].new_family) ||
3291                     xfrm_addr_any(&m[i].new_saddr, m[i].new_family))
3292                         return -EINVAL;
3293
3294                 /* check if there is any duplicated entry */
3295                 for (j = i + 1; j < num_migrate; j++) {
3296                         if (!memcmp(&m[i].old_daddr, &m[j].old_daddr,
3297                                     sizeof(m[i].old_daddr)) &&
3298                             !memcmp(&m[i].old_saddr, &m[j].old_saddr,
3299                                     sizeof(m[i].old_saddr)) &&
3300                             m[i].proto == m[j].proto &&
3301                             m[i].mode == m[j].mode &&
3302                             m[i].reqid == m[j].reqid &&
3303                             m[i].old_family == m[j].old_family)
3304                                 return -EINVAL;
3305                 }
3306         }
3307
3308         return 0;
3309 }
3310
3311 int xfrm_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
3312                  struct xfrm_migrate *m, int num_migrate,
3313                  struct xfrm_kmaddress *k, struct net *net)
3314 {
3315         int i, err, nx_cur = 0, nx_new = 0;
3316         struct xfrm_policy *pol = NULL;
3317         struct xfrm_state *x, *xc;
3318         struct xfrm_state *x_cur[XFRM_MAX_DEPTH];
3319         struct xfrm_state *x_new[XFRM_MAX_DEPTH];
3320         struct xfrm_migrate *mp;
3321
3322         /* Stage 0 - sanity checks */
3323         if ((err = xfrm_migrate_check(m, num_migrate)) < 0)
3324                 goto out;
3325
3326         if (dir >= XFRM_POLICY_MAX) {
3327                 err = -EINVAL;
3328                 goto out;
3329         }
3330
3331         /* Stage 1 - find policy */
3332         if ((pol = xfrm_migrate_policy_find(sel, dir, type, net)) == NULL) {
3333                 err = -ENOENT;
3334                 goto out;
3335         }
3336
3337         /* Stage 2 - find and update state(s) */
3338         for (i = 0, mp = m; i < num_migrate; i++, mp++) {
3339                 if ((x = xfrm_migrate_state_find(mp, net))) {
3340                         x_cur[nx_cur] = x;
3341                         nx_cur++;
3342                         if ((xc = xfrm_state_migrate(x, mp))) {
3343                                 x_new[nx_new] = xc;
3344                                 nx_new++;
3345                         } else {
3346                                 err = -ENODATA;
3347                                 goto restore_state;
3348                         }
3349                 }
3350         }
3351
3352         /* Stage 3 - update policy */
3353         if ((err = xfrm_policy_migrate(pol, m, num_migrate)) < 0)
3354                 goto restore_state;
3355
3356         /* Stage 4 - delete old state(s) */
3357         if (nx_cur) {
3358                 xfrm_states_put(x_cur, nx_cur);
3359                 xfrm_states_delete(x_cur, nx_cur);
3360         }
3361
3362         /* Stage 5 - announce */
3363         km_migrate(sel, dir, type, m, num_migrate, k);
3364
3365         xfrm_pol_put(pol);
3366
3367         return 0;
3368 out:
3369         return err;
3370
3371 restore_state:
3372         if (pol)
3373                 xfrm_pol_put(pol);
3374         if (nx_cur)
3375                 xfrm_states_put(x_cur, nx_cur);
3376         if (nx_new)
3377                 xfrm_states_delete(x_new, nx_new);
3378
3379         return err;
3380 }
3381 EXPORT_SYMBOL(xfrm_migrate);
3382 #endif