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