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