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