OSDN Git Service

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