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