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