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