54b50a20804fe37fce3f1345e2ef1a11e31c868c
[safe/jmp/linux-2.6] / 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/xfrm.h>
30 #include <net/ip.h>
31 #ifdef CONFIG_XFRM_STATISTICS
32 #include <net/snmp.h>
33 #endif
34
35 #include "xfrm_hash.h"
36
37 int sysctl_xfrm_larval_drop __read_mostly = 1;
38
39 #ifdef CONFIG_XFRM_STATISTICS
40 DEFINE_SNMP_STAT(struct linux_xfrm_mib, xfrm_statistics) __read_mostly;
41 EXPORT_SYMBOL(xfrm_statistics);
42 #endif
43
44 DEFINE_MUTEX(xfrm_cfg_mutex);
45 EXPORT_SYMBOL(xfrm_cfg_mutex);
46
47 static DEFINE_RWLOCK(xfrm_policy_lock);
48
49 static DEFINE_RWLOCK(xfrm_policy_afinfo_lock);
50 static struct xfrm_policy_afinfo *xfrm_policy_afinfo[NPROTO];
51
52 static struct kmem_cache *xfrm_dst_cache __read_mostly;
53
54 static HLIST_HEAD(xfrm_policy_gc_list);
55 static DEFINE_SPINLOCK(xfrm_policy_gc_lock);
56
57 static struct xfrm_policy_afinfo *xfrm_policy_get_afinfo(unsigned short family);
58 static void xfrm_policy_put_afinfo(struct xfrm_policy_afinfo *afinfo);
59 static void xfrm_init_pmtu(struct dst_entry *dst);
60
61 static inline int
62 __xfrm4_selector_match(struct xfrm_selector *sel, struct flowi *fl)
63 {
64         return  addr_match(&fl->fl4_dst, &sel->daddr, sel->prefixlen_d) &&
65                 addr_match(&fl->fl4_src, &sel->saddr, sel->prefixlen_s) &&
66                 !((xfrm_flowi_dport(fl) ^ sel->dport) & sel->dport_mask) &&
67                 !((xfrm_flowi_sport(fl) ^ sel->sport) & sel->sport_mask) &&
68                 (fl->proto == sel->proto || !sel->proto) &&
69                 (fl->oif == sel->ifindex || !sel->ifindex);
70 }
71
72 static inline int
73 __xfrm6_selector_match(struct xfrm_selector *sel, struct flowi *fl)
74 {
75         return  addr_match(&fl->fl6_dst, &sel->daddr, sel->prefixlen_d) &&
76                 addr_match(&fl->fl6_src, &sel->saddr, sel->prefixlen_s) &&
77                 !((xfrm_flowi_dport(fl) ^ sel->dport) & sel->dport_mask) &&
78                 !((xfrm_flowi_sport(fl) ^ sel->sport) & sel->sport_mask) &&
79                 (fl->proto == sel->proto || !sel->proto) &&
80                 (fl->oif == sel->ifindex || !sel->ifindex);
81 }
82
83 int xfrm_selector_match(struct xfrm_selector *sel, struct flowi *fl,
84                     unsigned short family)
85 {
86         switch (family) {
87         case AF_INET:
88                 return __xfrm4_selector_match(sel, fl);
89         case AF_INET6:
90                 return __xfrm6_selector_match(sel, fl);
91         }
92         return 0;
93 }
94
95 static inline struct dst_entry *__xfrm_dst_lookup(int tos,
96                                                   xfrm_address_t *saddr,
97                                                   xfrm_address_t *daddr,
98                                                   int family)
99 {
100         struct xfrm_policy_afinfo *afinfo;
101         struct dst_entry *dst;
102
103         afinfo = xfrm_policy_get_afinfo(family);
104         if (unlikely(afinfo == NULL))
105                 return ERR_PTR(-EAFNOSUPPORT);
106
107         dst = afinfo->dst_lookup(tos, saddr, daddr);
108
109         xfrm_policy_put_afinfo(afinfo);
110
111         return dst;
112 }
113
114 static inline struct dst_entry *xfrm_dst_lookup(struct xfrm_state *x, int tos,
115                                                 xfrm_address_t *prev_saddr,
116                                                 xfrm_address_t *prev_daddr,
117                                                 int family)
118 {
119         xfrm_address_t *saddr = &x->props.saddr;
120         xfrm_address_t *daddr = &x->id.daddr;
121         struct dst_entry *dst;
122
123         if (x->type->flags & XFRM_TYPE_LOCAL_COADDR) {
124                 saddr = x->coaddr;
125                 daddr = prev_daddr;
126         }
127         if (x->type->flags & XFRM_TYPE_REMOTE_COADDR) {
128                 saddr = prev_saddr;
129                 daddr = x->coaddr;
130         }
131
132         dst = __xfrm_dst_lookup(tos, saddr, daddr, family);
133
134         if (!IS_ERR(dst)) {
135                 if (prev_saddr != saddr)
136                         memcpy(prev_saddr, saddr,  sizeof(*prev_saddr));
137                 if (prev_daddr != daddr)
138                         memcpy(prev_daddr, daddr,  sizeof(*prev_daddr));
139         }
140
141         return dst;
142 }
143
144 static inline unsigned long make_jiffies(long secs)
145 {
146         if (secs >= (MAX_SCHEDULE_TIMEOUT-1)/HZ)
147                 return MAX_SCHEDULE_TIMEOUT-1;
148         else
149                 return secs*HZ;
150 }
151
152 static void xfrm_policy_timer(unsigned long data)
153 {
154         struct xfrm_policy *xp = (struct xfrm_policy*)data;
155         unsigned long now = get_seconds();
156         long next = LONG_MAX;
157         int warn = 0;
158         int dir;
159
160         read_lock(&xp->lock);
161
162         if (xp->walk.dead)
163                 goto out;
164
165         dir = xfrm_policy_id2dir(xp->index);
166
167         if (xp->lft.hard_add_expires_seconds) {
168                 long tmo = xp->lft.hard_add_expires_seconds +
169                         xp->curlft.add_time - now;
170                 if (tmo <= 0)
171                         goto expired;
172                 if (tmo < next)
173                         next = tmo;
174         }
175         if (xp->lft.hard_use_expires_seconds) {
176                 long tmo = xp->lft.hard_use_expires_seconds +
177                         (xp->curlft.use_time ? : xp->curlft.add_time) - now;
178                 if (tmo <= 0)
179                         goto expired;
180                 if (tmo < next)
181                         next = tmo;
182         }
183         if (xp->lft.soft_add_expires_seconds) {
184                 long tmo = xp->lft.soft_add_expires_seconds +
185                         xp->curlft.add_time - now;
186                 if (tmo <= 0) {
187                         warn = 1;
188                         tmo = XFRM_KM_TIMEOUT;
189                 }
190                 if (tmo < next)
191                         next = tmo;
192         }
193         if (xp->lft.soft_use_expires_seconds) {
194                 long tmo = xp->lft.soft_use_expires_seconds +
195                         (xp->curlft.use_time ? : xp->curlft.add_time) - now;
196                 if (tmo <= 0) {
197                         warn = 1;
198                         tmo = XFRM_KM_TIMEOUT;
199                 }
200                 if (tmo < next)
201                         next = tmo;
202         }
203
204         if (warn)
205                 km_policy_expired(xp, dir, 0, 0);
206         if (next != LONG_MAX &&
207             !mod_timer(&xp->timer, jiffies + make_jiffies(next)))
208                 xfrm_pol_hold(xp);
209
210 out:
211         read_unlock(&xp->lock);
212         xfrm_pol_put(xp);
213         return;
214
215 expired:
216         read_unlock(&xp->lock);
217         if (!xfrm_policy_delete(xp, dir))
218                 km_policy_expired(xp, dir, 1, 0);
219         xfrm_pol_put(xp);
220 }
221
222
223 /* Allocate xfrm_policy. Not used here, it is supposed to be used by pfkeyv2
224  * SPD calls.
225  */
226
227 struct xfrm_policy *xfrm_policy_alloc(struct net *net, gfp_t gfp)
228 {
229         struct xfrm_policy *policy;
230
231         policy = kzalloc(sizeof(struct xfrm_policy), gfp);
232
233         if (policy) {
234                 write_pnet(&policy->xp_net, net);
235                 INIT_LIST_HEAD(&policy->walk.all);
236                 INIT_HLIST_NODE(&policy->bydst);
237                 INIT_HLIST_NODE(&policy->byidx);
238                 rwlock_init(&policy->lock);
239                 atomic_set(&policy->refcnt, 1);
240                 setup_timer(&policy->timer, xfrm_policy_timer,
241                                 (unsigned long)policy);
242         }
243         return policy;
244 }
245 EXPORT_SYMBOL(xfrm_policy_alloc);
246
247 /* Destroy xfrm_policy: descendant resources must be released to this moment. */
248
249 void xfrm_policy_destroy(struct xfrm_policy *policy)
250 {
251         BUG_ON(!policy->walk.dead);
252
253         BUG_ON(policy->bundles);
254
255         if (del_timer(&policy->timer))
256                 BUG();
257
258         security_xfrm_policy_free(policy->security);
259         kfree(policy);
260 }
261 EXPORT_SYMBOL(xfrm_policy_destroy);
262
263 static void xfrm_policy_gc_kill(struct xfrm_policy *policy)
264 {
265         struct dst_entry *dst;
266
267         while ((dst = policy->bundles) != NULL) {
268                 policy->bundles = dst->next;
269                 dst_free(dst);
270         }
271
272         if (del_timer(&policy->timer))
273                 atomic_dec(&policy->refcnt);
274
275         if (atomic_read(&policy->refcnt) > 1)
276                 flow_cache_flush();
277
278         xfrm_pol_put(policy);
279 }
280
281 static void xfrm_policy_gc_task(struct work_struct *work)
282 {
283         struct xfrm_policy *policy;
284         struct hlist_node *entry, *tmp;
285         struct hlist_head gc_list;
286
287         spin_lock_bh(&xfrm_policy_gc_lock);
288         gc_list.first = xfrm_policy_gc_list.first;
289         INIT_HLIST_HEAD(&xfrm_policy_gc_list);
290         spin_unlock_bh(&xfrm_policy_gc_lock);
291
292         hlist_for_each_entry_safe(policy, entry, tmp, &gc_list, bydst)
293                 xfrm_policy_gc_kill(policy);
294 }
295 static DECLARE_WORK(xfrm_policy_gc_work, xfrm_policy_gc_task);
296
297 /* Rule must be locked. Release descentant resources, announce
298  * entry dead. The rule must be unlinked from lists to the moment.
299  */
300
301 static void xfrm_policy_kill(struct xfrm_policy *policy)
302 {
303         int dead;
304
305         write_lock_bh(&policy->lock);
306         dead = policy->walk.dead;
307         policy->walk.dead = 1;
308         write_unlock_bh(&policy->lock);
309
310         if (unlikely(dead)) {
311                 WARN_ON(1);
312                 return;
313         }
314
315         spin_lock_bh(&xfrm_policy_gc_lock);
316         hlist_add_head(&policy->bydst, &xfrm_policy_gc_list);
317         spin_unlock_bh(&xfrm_policy_gc_lock);
318
319         schedule_work(&xfrm_policy_gc_work);
320 }
321
322 static unsigned int xfrm_policy_hashmax __read_mostly = 1 * 1024 * 1024;
323
324 static inline unsigned int idx_hash(struct net *net, u32 index)
325 {
326         return __idx_hash(index, net->xfrm.policy_idx_hmask);
327 }
328
329 static struct hlist_head *policy_hash_bysel(struct net *net, struct xfrm_selector *sel, unsigned short family, int dir)
330 {
331         unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
332         unsigned int hash = __sel_hash(sel, family, hmask);
333
334         return (hash == hmask + 1 ?
335                 &net->xfrm.policy_inexact[dir] :
336                 net->xfrm.policy_bydst[dir].table + hash);
337 }
338
339 static struct hlist_head *policy_hash_direct(struct net *net, xfrm_address_t *daddr, xfrm_address_t *saddr, unsigned short family, int dir)
340 {
341         unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
342         unsigned int hash = __addr_hash(daddr, saddr, family, hmask);
343
344         return net->xfrm.policy_bydst[dir].table + hash;
345 }
346
347 static void xfrm_dst_hash_transfer(struct hlist_head *list,
348                                    struct hlist_head *ndsttable,
349                                    unsigned int nhashmask)
350 {
351         struct hlist_node *entry, *tmp, *entry0 = NULL;
352         struct xfrm_policy *pol;
353         unsigned int h0 = 0;
354
355 redo:
356         hlist_for_each_entry_safe(pol, entry, tmp, list, bydst) {
357                 unsigned int h;
358
359                 h = __addr_hash(&pol->selector.daddr, &pol->selector.saddr,
360                                 pol->family, nhashmask);
361                 if (!entry0) {
362                         hlist_del(entry);
363                         hlist_add_head(&pol->bydst, ndsttable+h);
364                         h0 = h;
365                 } else {
366                         if (h != h0)
367                                 continue;
368                         hlist_del(entry);
369                         hlist_add_after(entry0, &pol->bydst);
370                 }
371                 entry0 = entry;
372         }
373         if (!hlist_empty(list)) {
374                 entry0 = NULL;
375                 goto redo;
376         }
377 }
378
379 static void xfrm_idx_hash_transfer(struct hlist_head *list,
380                                    struct hlist_head *nidxtable,
381                                    unsigned int nhashmask)
382 {
383         struct hlist_node *entry, *tmp;
384         struct xfrm_policy *pol;
385
386         hlist_for_each_entry_safe(pol, entry, tmp, list, byidx) {
387                 unsigned int h;
388
389                 h = __idx_hash(pol->index, nhashmask);
390                 hlist_add_head(&pol->byidx, nidxtable+h);
391         }
392 }
393
394 static unsigned long xfrm_new_hash_mask(unsigned int old_hmask)
395 {
396         return ((old_hmask + 1) << 1) - 1;
397 }
398
399 static void xfrm_bydst_resize(struct net *net, int dir)
400 {
401         unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
402         unsigned int nhashmask = xfrm_new_hash_mask(hmask);
403         unsigned int nsize = (nhashmask + 1) * sizeof(struct hlist_head);
404         struct hlist_head *odst = net->xfrm.policy_bydst[dir].table;
405         struct hlist_head *ndst = xfrm_hash_alloc(nsize);
406         int i;
407
408         if (!ndst)
409                 return;
410
411         write_lock_bh(&xfrm_policy_lock);
412
413         for (i = hmask; i >= 0; i--)
414                 xfrm_dst_hash_transfer(odst + i, ndst, nhashmask);
415
416         net->xfrm.policy_bydst[dir].table = ndst;
417         net->xfrm.policy_bydst[dir].hmask = nhashmask;
418
419         write_unlock_bh(&xfrm_policy_lock);
420
421         xfrm_hash_free(odst, (hmask + 1) * sizeof(struct hlist_head));
422 }
423
424 static void xfrm_byidx_resize(struct net *net, int total)
425 {
426         unsigned int hmask = net->xfrm.policy_idx_hmask;
427         unsigned int nhashmask = xfrm_new_hash_mask(hmask);
428         unsigned int nsize = (nhashmask + 1) * sizeof(struct hlist_head);
429         struct hlist_head *oidx = net->xfrm.policy_byidx;
430         struct hlist_head *nidx = xfrm_hash_alloc(nsize);
431         int i;
432
433         if (!nidx)
434                 return;
435
436         write_lock_bh(&xfrm_policy_lock);
437
438         for (i = hmask; i >= 0; i--)
439                 xfrm_idx_hash_transfer(oidx + i, nidx, nhashmask);
440
441         net->xfrm.policy_byidx = nidx;
442         net->xfrm.policy_idx_hmask = nhashmask;
443
444         write_unlock_bh(&xfrm_policy_lock);
445
446         xfrm_hash_free(oidx, (hmask + 1) * sizeof(struct hlist_head));
447 }
448
449 static inline int xfrm_bydst_should_resize(struct net *net, int dir, int *total)
450 {
451         unsigned int cnt = net->xfrm.policy_count[dir];
452         unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
453
454         if (total)
455                 *total += cnt;
456
457         if ((hmask + 1) < xfrm_policy_hashmax &&
458             cnt > hmask)
459                 return 1;
460
461         return 0;
462 }
463
464 static inline int xfrm_byidx_should_resize(struct net *net, int total)
465 {
466         unsigned int hmask = net->xfrm.policy_idx_hmask;
467
468         if ((hmask + 1) < xfrm_policy_hashmax &&
469             total > hmask)
470                 return 1;
471
472         return 0;
473 }
474
475 void xfrm_spd_getinfo(struct xfrmk_spdinfo *si)
476 {
477         read_lock_bh(&xfrm_policy_lock);
478         si->incnt = init_net.xfrm.policy_count[XFRM_POLICY_IN];
479         si->outcnt = init_net.xfrm.policy_count[XFRM_POLICY_OUT];
480         si->fwdcnt = init_net.xfrm.policy_count[XFRM_POLICY_FWD];
481         si->inscnt = init_net.xfrm.policy_count[XFRM_POLICY_IN+XFRM_POLICY_MAX];
482         si->outscnt = init_net.xfrm.policy_count[XFRM_POLICY_OUT+XFRM_POLICY_MAX];
483         si->fwdscnt = init_net.xfrm.policy_count[XFRM_POLICY_FWD+XFRM_POLICY_MAX];
484         si->spdhcnt = init_net.xfrm.policy_idx_hmask;
485         si->spdhmcnt = xfrm_policy_hashmax;
486         read_unlock_bh(&xfrm_policy_lock);
487 }
488 EXPORT_SYMBOL(xfrm_spd_getinfo);
489
490 static DEFINE_MUTEX(hash_resize_mutex);
491 static void xfrm_hash_resize(struct work_struct *work)
492 {
493         struct net *net = container_of(work, struct net, xfrm.policy_hash_work);
494         int dir, total;
495
496         mutex_lock(&hash_resize_mutex);
497
498         total = 0;
499         for (dir = 0; dir < XFRM_POLICY_MAX * 2; dir++) {
500                 if (xfrm_bydst_should_resize(net, dir, &total))
501                         xfrm_bydst_resize(net, dir);
502         }
503         if (xfrm_byidx_should_resize(net, total))
504                 xfrm_byidx_resize(net, total);
505
506         mutex_unlock(&hash_resize_mutex);
507 }
508
509 /* Generate new index... KAME seems to generate them ordered by cost
510  * of an absolute inpredictability of ordering of rules. This will not pass. */
511 static u32 xfrm_gen_index(struct net *net, int dir)
512 {
513         static u32 idx_generator;
514
515         for (;;) {
516                 struct hlist_node *entry;
517                 struct hlist_head *list;
518                 struct xfrm_policy *p;
519                 u32 idx;
520                 int found;
521
522                 idx = (idx_generator | dir);
523                 idx_generator += 8;
524                 if (idx == 0)
525                         idx = 8;
526                 list = net->xfrm.policy_byidx + idx_hash(net, idx);
527                 found = 0;
528                 hlist_for_each_entry(p, entry, list, byidx) {
529                         if (p->index == idx) {
530                                 found = 1;
531                                 break;
532                         }
533                 }
534                 if (!found)
535                         return idx;
536         }
537 }
538
539 static inline int selector_cmp(struct xfrm_selector *s1, struct xfrm_selector *s2)
540 {
541         u32 *p1 = (u32 *) s1;
542         u32 *p2 = (u32 *) s2;
543         int len = sizeof(struct xfrm_selector) / sizeof(u32);
544         int i;
545
546         for (i = 0; i < len; i++) {
547                 if (p1[i] != p2[i])
548                         return 1;
549         }
550
551         return 0;
552 }
553
554 int xfrm_policy_insert(int dir, struct xfrm_policy *policy, int excl)
555 {
556         struct net *net = xp_net(policy);
557         struct xfrm_policy *pol;
558         struct xfrm_policy *delpol;
559         struct hlist_head *chain;
560         struct hlist_node *entry, *newpos;
561         struct dst_entry *gc_list;
562
563         write_lock_bh(&xfrm_policy_lock);
564         chain = policy_hash_bysel(net, &policy->selector, policy->family, dir);
565         delpol = NULL;
566         newpos = NULL;
567         hlist_for_each_entry(pol, entry, chain, bydst) {
568                 if (pol->type == policy->type &&
569                     !selector_cmp(&pol->selector, &policy->selector) &&
570                     xfrm_sec_ctx_match(pol->security, policy->security) &&
571                     !WARN_ON(delpol)) {
572                         if (excl) {
573                                 write_unlock_bh(&xfrm_policy_lock);
574                                 return -EEXIST;
575                         }
576                         delpol = pol;
577                         if (policy->priority > pol->priority)
578                                 continue;
579                 } else if (policy->priority >= pol->priority) {
580                         newpos = &pol->bydst;
581                         continue;
582                 }
583                 if (delpol)
584                         break;
585         }
586         if (newpos)
587                 hlist_add_after(newpos, &policy->bydst);
588         else
589                 hlist_add_head(&policy->bydst, chain);
590         xfrm_pol_hold(policy);
591         net->xfrm.policy_count[dir]++;
592         atomic_inc(&flow_cache_genid);
593         if (delpol) {
594                 hlist_del(&delpol->bydst);
595                 hlist_del(&delpol->byidx);
596                 list_del(&delpol->walk.all);
597                 net->xfrm.policy_count[dir]--;
598         }
599         policy->index = delpol ? delpol->index : xfrm_gen_index(net, dir);
600         hlist_add_head(&policy->byidx, net->xfrm.policy_byidx+idx_hash(net, policy->index));
601         policy->curlft.add_time = get_seconds();
602         policy->curlft.use_time = 0;
603         if (!mod_timer(&policy->timer, jiffies + HZ))
604                 xfrm_pol_hold(policy);
605         list_add(&policy->walk.all, &net->xfrm.policy_all);
606         write_unlock_bh(&xfrm_policy_lock);
607
608         if (delpol)
609                 xfrm_policy_kill(delpol);
610         else if (xfrm_bydst_should_resize(net, dir, NULL))
611                 schedule_work(&net->xfrm.policy_hash_work);
612
613         read_lock_bh(&xfrm_policy_lock);
614         gc_list = NULL;
615         entry = &policy->bydst;
616         hlist_for_each_entry_continue(policy, entry, bydst) {
617                 struct dst_entry *dst;
618
619                 write_lock(&policy->lock);
620                 dst = policy->bundles;
621                 if (dst) {
622                         struct dst_entry *tail = dst;
623                         while (tail->next)
624                                 tail = tail->next;
625                         tail->next = gc_list;
626                         gc_list = dst;
627
628                         policy->bundles = NULL;
629                 }
630                 write_unlock(&policy->lock);
631         }
632         read_unlock_bh(&xfrm_policy_lock);
633
634         while (gc_list) {
635                 struct dst_entry *dst = gc_list;
636
637                 gc_list = dst->next;
638                 dst_free(dst);
639         }
640
641         return 0;
642 }
643 EXPORT_SYMBOL(xfrm_policy_insert);
644
645 struct xfrm_policy *xfrm_policy_bysel_ctx(struct net *net, u8 type, int dir,
646                                           struct xfrm_selector *sel,
647                                           struct xfrm_sec_ctx *ctx, int delete,
648                                           int *err)
649 {
650         struct xfrm_policy *pol, *ret;
651         struct hlist_head *chain;
652         struct hlist_node *entry;
653
654         *err = 0;
655         write_lock_bh(&xfrm_policy_lock);
656         chain = policy_hash_bysel(net, sel, sel->family, dir);
657         ret = NULL;
658         hlist_for_each_entry(pol, entry, chain, bydst) {
659                 if (pol->type == type &&
660                     !selector_cmp(sel, &pol->selector) &&
661                     xfrm_sec_ctx_match(ctx, pol->security)) {
662                         xfrm_pol_hold(pol);
663                         if (delete) {
664                                 *err = security_xfrm_policy_delete(
665                                                                 pol->security);
666                                 if (*err) {
667                                         write_unlock_bh(&xfrm_policy_lock);
668                                         return pol;
669                                 }
670                                 hlist_del(&pol->bydst);
671                                 hlist_del(&pol->byidx);
672                                 list_del(&pol->walk.all);
673                                 net->xfrm.policy_count[dir]--;
674                         }
675                         ret = pol;
676                         break;
677                 }
678         }
679         write_unlock_bh(&xfrm_policy_lock);
680
681         if (ret && delete) {
682                 atomic_inc(&flow_cache_genid);
683                 xfrm_policy_kill(ret);
684         }
685         return ret;
686 }
687 EXPORT_SYMBOL(xfrm_policy_bysel_ctx);
688
689 struct xfrm_policy *xfrm_policy_byid(struct net *net, u8 type, int dir, u32 id,
690                                      int delete, int *err)
691 {
692         struct xfrm_policy *pol, *ret;
693         struct hlist_head *chain;
694         struct hlist_node *entry;
695
696         *err = -ENOENT;
697         if (xfrm_policy_id2dir(id) != dir)
698                 return NULL;
699
700         *err = 0;
701         write_lock_bh(&xfrm_policy_lock);
702         chain = net->xfrm.policy_byidx + idx_hash(net, id);
703         ret = NULL;
704         hlist_for_each_entry(pol, entry, chain, byidx) {
705                 if (pol->type == type && pol->index == id) {
706                         xfrm_pol_hold(pol);
707                         if (delete) {
708                                 *err = security_xfrm_policy_delete(
709                                                                 pol->security);
710                                 if (*err) {
711                                         write_unlock_bh(&xfrm_policy_lock);
712                                         return pol;
713                                 }
714                                 hlist_del(&pol->bydst);
715                                 hlist_del(&pol->byidx);
716                                 list_del(&pol->walk.all);
717                                 net->xfrm.policy_count[dir]--;
718                         }
719                         ret = pol;
720                         break;
721                 }
722         }
723         write_unlock_bh(&xfrm_policy_lock);
724
725         if (ret && delete) {
726                 atomic_inc(&flow_cache_genid);
727                 xfrm_policy_kill(ret);
728         }
729         return ret;
730 }
731 EXPORT_SYMBOL(xfrm_policy_byid);
732
733 #ifdef CONFIG_SECURITY_NETWORK_XFRM
734 static inline int
735 xfrm_policy_flush_secctx_check(struct net *net, u8 type, struct xfrm_audit *audit_info)
736 {
737         int dir, err = 0;
738
739         for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
740                 struct xfrm_policy *pol;
741                 struct hlist_node *entry;
742                 int i;
743
744                 hlist_for_each_entry(pol, entry,
745                                      &net->xfrm.policy_inexact[dir], bydst) {
746                         if (pol->type != type)
747                                 continue;
748                         err = security_xfrm_policy_delete(pol->security);
749                         if (err) {
750                                 xfrm_audit_policy_delete(pol, 0,
751                                                          audit_info->loginuid,
752                                                          audit_info->sessionid,
753                                                          audit_info->secid);
754                                 return err;
755                         }
756                 }
757                 for (i = net->xfrm.policy_bydst[dir].hmask; i >= 0; i--) {
758                         hlist_for_each_entry(pol, entry,
759                                              net->xfrm.policy_bydst[dir].table + i,
760                                              bydst) {
761                                 if (pol->type != type)
762                                         continue;
763                                 err = security_xfrm_policy_delete(
764                                                                 pol->security);
765                                 if (err) {
766                                         xfrm_audit_policy_delete(pol, 0,
767                                                         audit_info->loginuid,
768                                                         audit_info->sessionid,
769                                                         audit_info->secid);
770                                         return err;
771                                 }
772                         }
773                 }
774         }
775         return err;
776 }
777 #else
778 static inline int
779 xfrm_policy_flush_secctx_check(struct net *net, u8 type, struct xfrm_audit *audit_info)
780 {
781         return 0;
782 }
783 #endif
784
785 int xfrm_policy_flush(struct net *net, u8 type, struct xfrm_audit *audit_info)
786 {
787         int dir, err = 0;
788
789         write_lock_bh(&xfrm_policy_lock);
790
791         err = xfrm_policy_flush_secctx_check(net, type, audit_info);
792         if (err)
793                 goto out;
794
795         for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
796                 struct xfrm_policy *pol;
797                 struct hlist_node *entry;
798                 int i, killed;
799
800                 killed = 0;
801         again1:
802                 hlist_for_each_entry(pol, entry,
803                                      &net->xfrm.policy_inexact[dir], bydst) {
804                         if (pol->type != type)
805                                 continue;
806                         hlist_del(&pol->bydst);
807                         hlist_del(&pol->byidx);
808                         write_unlock_bh(&xfrm_policy_lock);
809
810                         xfrm_audit_policy_delete(pol, 1, audit_info->loginuid,
811                                                  audit_info->sessionid,
812                                                  audit_info->secid);
813
814                         xfrm_policy_kill(pol);
815                         killed++;
816
817                         write_lock_bh(&xfrm_policy_lock);
818                         goto again1;
819                 }
820
821                 for (i = net->xfrm.policy_bydst[dir].hmask; i >= 0; i--) {
822         again2:
823                         hlist_for_each_entry(pol, entry,
824                                              net->xfrm.policy_bydst[dir].table + i,
825                                              bydst) {
826                                 if (pol->type != type)
827                                         continue;
828                                 hlist_del(&pol->bydst);
829                                 hlist_del(&pol->byidx);
830                                 list_del(&pol->walk.all);
831                                 write_unlock_bh(&xfrm_policy_lock);
832
833                                 xfrm_audit_policy_delete(pol, 1,
834                                                          audit_info->loginuid,
835                                                          audit_info->sessionid,
836                                                          audit_info->secid);
837                                 xfrm_policy_kill(pol);
838                                 killed++;
839
840                                 write_lock_bh(&xfrm_policy_lock);
841                                 goto again2;
842                         }
843                 }
844
845                 net->xfrm.policy_count[dir] -= killed;
846         }
847         atomic_inc(&flow_cache_genid);
848 out:
849         write_unlock_bh(&xfrm_policy_lock);
850         return err;
851 }
852 EXPORT_SYMBOL(xfrm_policy_flush);
853
854 int xfrm_policy_walk(struct net *net, struct xfrm_policy_walk *walk,
855                      int (*func)(struct xfrm_policy *, int, int, void*),
856                      void *data)
857 {
858         struct xfrm_policy *pol;
859         struct xfrm_policy_walk_entry *x;
860         int error = 0;
861
862         if (walk->type >= XFRM_POLICY_TYPE_MAX &&
863             walk->type != XFRM_POLICY_TYPE_ANY)
864                 return -EINVAL;
865
866         if (list_empty(&walk->walk.all) && walk->seq != 0)
867                 return 0;
868
869         write_lock_bh(&xfrm_policy_lock);
870         if (list_empty(&walk->walk.all))
871                 x = list_first_entry(&net->xfrm.policy_all, struct xfrm_policy_walk_entry, all);
872         else
873                 x = list_entry(&walk->walk.all, struct xfrm_policy_walk_entry, all);
874         list_for_each_entry_from(x, &net->xfrm.policy_all, all) {
875                 if (x->dead)
876                         continue;
877                 pol = container_of(x, struct xfrm_policy, walk);
878                 if (walk->type != XFRM_POLICY_TYPE_ANY &&
879                     walk->type != pol->type)
880                         continue;
881                 error = func(pol, xfrm_policy_id2dir(pol->index),
882                              walk->seq, data);
883                 if (error) {
884                         list_move_tail(&walk->walk.all, &x->all);
885                         goto out;
886                 }
887                 walk->seq++;
888         }
889         if (walk->seq == 0) {
890                 error = -ENOENT;
891                 goto out;
892         }
893         list_del_init(&walk->walk.all);
894 out:
895         write_unlock_bh(&xfrm_policy_lock);
896         return error;
897 }
898 EXPORT_SYMBOL(xfrm_policy_walk);
899
900 void xfrm_policy_walk_init(struct xfrm_policy_walk *walk, u8 type)
901 {
902         INIT_LIST_HEAD(&walk->walk.all);
903         walk->walk.dead = 1;
904         walk->type = type;
905         walk->seq = 0;
906 }
907 EXPORT_SYMBOL(xfrm_policy_walk_init);
908
909 void xfrm_policy_walk_done(struct xfrm_policy_walk *walk)
910 {
911         if (list_empty(&walk->walk.all))
912                 return;
913
914         write_lock_bh(&xfrm_policy_lock);
915         list_del(&walk->walk.all);
916         write_unlock_bh(&xfrm_policy_lock);
917 }
918 EXPORT_SYMBOL(xfrm_policy_walk_done);
919
920 /*
921  * Find policy to apply to this flow.
922  *
923  * Returns 0 if policy found, else an -errno.
924  */
925 static int xfrm_policy_match(struct xfrm_policy *pol, struct flowi *fl,
926                              u8 type, u16 family, int dir)
927 {
928         struct xfrm_selector *sel = &pol->selector;
929         int match, ret = -ESRCH;
930
931         if (pol->family != family ||
932             pol->type != type)
933                 return ret;
934
935         match = xfrm_selector_match(sel, fl, family);
936         if (match)
937                 ret = security_xfrm_policy_lookup(pol->security, fl->secid,
938                                                   dir);
939
940         return ret;
941 }
942
943 static struct xfrm_policy *xfrm_policy_lookup_bytype(struct net *net, u8 type,
944                                                      struct flowi *fl,
945                                                      u16 family, u8 dir)
946 {
947         int err;
948         struct xfrm_policy *pol, *ret;
949         xfrm_address_t *daddr, *saddr;
950         struct hlist_node *entry;
951         struct hlist_head *chain;
952         u32 priority = ~0U;
953
954         daddr = xfrm_flowi_daddr(fl, family);
955         saddr = xfrm_flowi_saddr(fl, family);
956         if (unlikely(!daddr || !saddr))
957                 return NULL;
958
959         read_lock_bh(&xfrm_policy_lock);
960         chain = policy_hash_direct(net, daddr, saddr, family, dir);
961         ret = NULL;
962         hlist_for_each_entry(pol, entry, chain, bydst) {
963                 err = xfrm_policy_match(pol, fl, type, family, dir);
964                 if (err) {
965                         if (err == -ESRCH)
966                                 continue;
967                         else {
968                                 ret = ERR_PTR(err);
969                                 goto fail;
970                         }
971                 } else {
972                         ret = pol;
973                         priority = ret->priority;
974                         break;
975                 }
976         }
977         chain = &net->xfrm.policy_inexact[dir];
978         hlist_for_each_entry(pol, entry, chain, bydst) {
979                 err = xfrm_policy_match(pol, fl, type, family, dir);
980                 if (err) {
981                         if (err == -ESRCH)
982                                 continue;
983                         else {
984                                 ret = ERR_PTR(err);
985                                 goto fail;
986                         }
987                 } else if (pol->priority < priority) {
988                         ret = pol;
989                         break;
990                 }
991         }
992         if (ret)
993                 xfrm_pol_hold(ret);
994 fail:
995         read_unlock_bh(&xfrm_policy_lock);
996
997         return ret;
998 }
999
1000 static int xfrm_policy_lookup(struct net *net, struct flowi *fl, u16 family,
1001                               u8 dir, void **objp, atomic_t **obj_refp)
1002 {
1003         struct xfrm_policy *pol;
1004         int err = 0;
1005
1006 #ifdef CONFIG_XFRM_SUB_POLICY
1007         pol = xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_SUB, fl, family, dir);
1008         if (IS_ERR(pol)) {
1009                 err = PTR_ERR(pol);
1010                 pol = NULL;
1011         }
1012         if (pol || err)
1013                 goto end;
1014 #endif
1015         pol = xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_MAIN, fl, family, dir);
1016         if (IS_ERR(pol)) {
1017                 err = PTR_ERR(pol);
1018                 pol = NULL;
1019         }
1020 #ifdef CONFIG_XFRM_SUB_POLICY
1021 end:
1022 #endif
1023         if ((*objp = (void *) pol) != NULL)
1024                 *obj_refp = &pol->refcnt;
1025         return err;
1026 }
1027
1028 static inline int policy_to_flow_dir(int dir)
1029 {
1030         if (XFRM_POLICY_IN == FLOW_DIR_IN &&
1031             XFRM_POLICY_OUT == FLOW_DIR_OUT &&
1032             XFRM_POLICY_FWD == FLOW_DIR_FWD)
1033                 return dir;
1034         switch (dir) {
1035         default:
1036         case XFRM_POLICY_IN:
1037                 return FLOW_DIR_IN;
1038         case XFRM_POLICY_OUT:
1039                 return FLOW_DIR_OUT;
1040         case XFRM_POLICY_FWD:
1041                 return FLOW_DIR_FWD;
1042         }
1043 }
1044
1045 static struct xfrm_policy *xfrm_sk_policy_lookup(struct sock *sk, int dir, struct flowi *fl)
1046 {
1047         struct xfrm_policy *pol;
1048
1049         read_lock_bh(&xfrm_policy_lock);
1050         if ((pol = sk->sk_policy[dir]) != NULL) {
1051                 int match = xfrm_selector_match(&pol->selector, fl,
1052                                                 sk->sk_family);
1053                 int err = 0;
1054
1055                 if (match) {
1056                         err = security_xfrm_policy_lookup(pol->security,
1057                                                       fl->secid,
1058                                                       policy_to_flow_dir(dir));
1059                         if (!err)
1060                                 xfrm_pol_hold(pol);
1061                         else if (err == -ESRCH)
1062                                 pol = NULL;
1063                         else
1064                                 pol = ERR_PTR(err);
1065                 } else
1066                         pol = NULL;
1067         }
1068         read_unlock_bh(&xfrm_policy_lock);
1069         return pol;
1070 }
1071
1072 static void __xfrm_policy_link(struct xfrm_policy *pol, int dir)
1073 {
1074         struct net *net = xp_net(pol);
1075         struct hlist_head *chain = policy_hash_bysel(net, &pol->selector,
1076                                                      pol->family, dir);
1077
1078         list_add(&pol->walk.all, &net->xfrm.policy_all);
1079         hlist_add_head(&pol->bydst, chain);
1080         hlist_add_head(&pol->byidx, net->xfrm.policy_byidx+idx_hash(net, pol->index));
1081         net->xfrm.policy_count[dir]++;
1082         xfrm_pol_hold(pol);
1083
1084         if (xfrm_bydst_should_resize(net, dir, NULL))
1085                 schedule_work(&net->xfrm.policy_hash_work);
1086 }
1087
1088 static struct xfrm_policy *__xfrm_policy_unlink(struct xfrm_policy *pol,
1089                                                 int dir)
1090 {
1091         struct net *net = xp_net(pol);
1092
1093         if (hlist_unhashed(&pol->bydst))
1094                 return NULL;
1095
1096         hlist_del(&pol->bydst);
1097         hlist_del(&pol->byidx);
1098         list_del(&pol->walk.all);
1099         net->xfrm.policy_count[dir]--;
1100
1101         return pol;
1102 }
1103
1104 int xfrm_policy_delete(struct xfrm_policy *pol, int dir)
1105 {
1106         write_lock_bh(&xfrm_policy_lock);
1107         pol = __xfrm_policy_unlink(pol, dir);
1108         write_unlock_bh(&xfrm_policy_lock);
1109         if (pol) {
1110                 if (dir < XFRM_POLICY_MAX)
1111                         atomic_inc(&flow_cache_genid);
1112                 xfrm_policy_kill(pol);
1113                 return 0;
1114         }
1115         return -ENOENT;
1116 }
1117 EXPORT_SYMBOL(xfrm_policy_delete);
1118
1119 int xfrm_sk_policy_insert(struct sock *sk, int dir, struct xfrm_policy *pol)
1120 {
1121         struct net *net = xp_net(pol);
1122         struct xfrm_policy *old_pol;
1123
1124 #ifdef CONFIG_XFRM_SUB_POLICY
1125         if (pol && pol->type != XFRM_POLICY_TYPE_MAIN)
1126                 return -EINVAL;
1127 #endif
1128
1129         write_lock_bh(&xfrm_policy_lock);
1130         old_pol = sk->sk_policy[dir];
1131         sk->sk_policy[dir] = pol;
1132         if (pol) {
1133                 pol->curlft.add_time = get_seconds();
1134                 pol->index = xfrm_gen_index(net, XFRM_POLICY_MAX+dir);
1135                 __xfrm_policy_link(pol, XFRM_POLICY_MAX+dir);
1136         }
1137         if (old_pol)
1138                 __xfrm_policy_unlink(old_pol, XFRM_POLICY_MAX+dir);
1139         write_unlock_bh(&xfrm_policy_lock);
1140
1141         if (old_pol) {
1142                 xfrm_policy_kill(old_pol);
1143         }
1144         return 0;
1145 }
1146
1147 static struct xfrm_policy *clone_policy(struct xfrm_policy *old, int dir)
1148 {
1149         struct xfrm_policy *newp = xfrm_policy_alloc(xp_net(old), GFP_ATOMIC);
1150
1151         if (newp) {
1152                 newp->selector = old->selector;
1153                 if (security_xfrm_policy_clone(old->security,
1154                                                &newp->security)) {
1155                         kfree(newp);
1156                         return NULL;  /* ENOMEM */
1157                 }
1158                 newp->lft = old->lft;
1159                 newp->curlft = old->curlft;
1160                 newp->action = old->action;
1161                 newp->flags = old->flags;
1162                 newp->xfrm_nr = old->xfrm_nr;
1163                 newp->index = old->index;
1164                 newp->type = old->type;
1165                 memcpy(newp->xfrm_vec, old->xfrm_vec,
1166                        newp->xfrm_nr*sizeof(struct xfrm_tmpl));
1167                 write_lock_bh(&xfrm_policy_lock);
1168                 __xfrm_policy_link(newp, XFRM_POLICY_MAX+dir);
1169                 write_unlock_bh(&xfrm_policy_lock);
1170                 xfrm_pol_put(newp);
1171         }
1172         return newp;
1173 }
1174
1175 int __xfrm_sk_clone_policy(struct sock *sk)
1176 {
1177         struct xfrm_policy *p0 = sk->sk_policy[0],
1178                            *p1 = sk->sk_policy[1];
1179
1180         sk->sk_policy[0] = sk->sk_policy[1] = NULL;
1181         if (p0 && (sk->sk_policy[0] = clone_policy(p0, 0)) == NULL)
1182                 return -ENOMEM;
1183         if (p1 && (sk->sk_policy[1] = clone_policy(p1, 1)) == NULL)
1184                 return -ENOMEM;
1185         return 0;
1186 }
1187
1188 static int
1189 xfrm_get_saddr(xfrm_address_t *local, xfrm_address_t *remote,
1190                unsigned short family)
1191 {
1192         int err;
1193         struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1194
1195         if (unlikely(afinfo == NULL))
1196                 return -EINVAL;
1197         err = afinfo->get_saddr(local, remote);
1198         xfrm_policy_put_afinfo(afinfo);
1199         return err;
1200 }
1201
1202 /* Resolve list of templates for the flow, given policy. */
1203
1204 static int
1205 xfrm_tmpl_resolve_one(struct xfrm_policy *policy, struct flowi *fl,
1206                       struct xfrm_state **xfrm,
1207                       unsigned short family)
1208 {
1209         int nx;
1210         int i, error;
1211         xfrm_address_t *daddr = xfrm_flowi_daddr(fl, family);
1212         xfrm_address_t *saddr = xfrm_flowi_saddr(fl, family);
1213         xfrm_address_t tmp;
1214
1215         for (nx=0, i = 0; i < policy->xfrm_nr; i++) {
1216                 struct xfrm_state *x;
1217                 xfrm_address_t *remote = daddr;
1218                 xfrm_address_t *local  = saddr;
1219                 struct xfrm_tmpl *tmpl = &policy->xfrm_vec[i];
1220
1221                 if (tmpl->mode == XFRM_MODE_TUNNEL ||
1222                     tmpl->mode == XFRM_MODE_BEET) {
1223                         remote = &tmpl->id.daddr;
1224                         local = &tmpl->saddr;
1225                         family = tmpl->encap_family;
1226                         if (xfrm_addr_any(local, family)) {
1227                                 error = xfrm_get_saddr(&tmp, remote, family);
1228                                 if (error)
1229                                         goto fail;
1230                                 local = &tmp;
1231                         }
1232                 }
1233
1234                 x = xfrm_state_find(remote, local, fl, tmpl, policy, &error, family);
1235
1236                 if (x && x->km.state == XFRM_STATE_VALID) {
1237                         xfrm[nx++] = x;
1238                         daddr = remote;
1239                         saddr = local;
1240                         continue;
1241                 }
1242                 if (x) {
1243                         error = (x->km.state == XFRM_STATE_ERROR ?
1244                                  -EINVAL : -EAGAIN);
1245                         xfrm_state_put(x);
1246                 }
1247                 else if (error == -ESRCH)
1248                         error = -EAGAIN;
1249
1250                 if (!tmpl->optional)
1251                         goto fail;
1252         }
1253         return nx;
1254
1255 fail:
1256         for (nx--; nx>=0; nx--)
1257                 xfrm_state_put(xfrm[nx]);
1258         return error;
1259 }
1260
1261 static int
1262 xfrm_tmpl_resolve(struct xfrm_policy **pols, int npols, struct flowi *fl,
1263                   struct xfrm_state **xfrm,
1264                   unsigned short family)
1265 {
1266         struct xfrm_state *tp[XFRM_MAX_DEPTH];
1267         struct xfrm_state **tpp = (npols > 1) ? tp : xfrm;
1268         int cnx = 0;
1269         int error;
1270         int ret;
1271         int i;
1272
1273         for (i = 0; i < npols; i++) {
1274                 if (cnx + pols[i]->xfrm_nr >= XFRM_MAX_DEPTH) {
1275                         error = -ENOBUFS;
1276                         goto fail;
1277                 }
1278
1279                 ret = xfrm_tmpl_resolve_one(pols[i], fl, &tpp[cnx], family);
1280                 if (ret < 0) {
1281                         error = ret;
1282                         goto fail;
1283                 } else
1284                         cnx += ret;
1285         }
1286
1287         /* found states are sorted for outbound processing */
1288         if (npols > 1)
1289                 xfrm_state_sort(xfrm, tpp, cnx, family);
1290
1291         return cnx;
1292
1293  fail:
1294         for (cnx--; cnx>=0; cnx--)
1295                 xfrm_state_put(tpp[cnx]);
1296         return error;
1297
1298 }
1299
1300 /* Check that the bundle accepts the flow and its components are
1301  * still valid.
1302  */
1303
1304 static struct dst_entry *
1305 xfrm_find_bundle(struct flowi *fl, struct xfrm_policy *policy, unsigned short family)
1306 {
1307         struct dst_entry *x;
1308         struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1309         if (unlikely(afinfo == NULL))
1310                 return ERR_PTR(-EINVAL);
1311         x = afinfo->find_bundle(fl, policy);
1312         xfrm_policy_put_afinfo(afinfo);
1313         return x;
1314 }
1315
1316 static inline int xfrm_get_tos(struct flowi *fl, int family)
1317 {
1318         struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1319         int tos;
1320
1321         if (!afinfo)
1322                 return -EINVAL;
1323
1324         tos = afinfo->get_tos(fl);
1325
1326         xfrm_policy_put_afinfo(afinfo);
1327
1328         return tos;
1329 }
1330
1331 static inline struct xfrm_dst *xfrm_alloc_dst(int family)
1332 {
1333         struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1334         struct xfrm_dst *xdst;
1335
1336         if (!afinfo)
1337                 return ERR_PTR(-EINVAL);
1338
1339         xdst = dst_alloc(afinfo->dst_ops) ?: ERR_PTR(-ENOBUFS);
1340
1341         xfrm_policy_put_afinfo(afinfo);
1342
1343         return xdst;
1344 }
1345
1346 static inline int xfrm_init_path(struct xfrm_dst *path, struct dst_entry *dst,
1347                                  int nfheader_len)
1348 {
1349         struct xfrm_policy_afinfo *afinfo =
1350                 xfrm_policy_get_afinfo(dst->ops->family);
1351         int err;
1352
1353         if (!afinfo)
1354                 return -EINVAL;
1355
1356         err = afinfo->init_path(path, dst, nfheader_len);
1357
1358         xfrm_policy_put_afinfo(afinfo);
1359
1360         return err;
1361 }
1362
1363 static inline int xfrm_fill_dst(struct xfrm_dst *xdst, struct net_device *dev)
1364 {
1365         struct xfrm_policy_afinfo *afinfo =
1366                 xfrm_policy_get_afinfo(xdst->u.dst.ops->family);
1367         int err;
1368
1369         if (!afinfo)
1370                 return -EINVAL;
1371
1372         err = afinfo->fill_dst(xdst, dev);
1373
1374         xfrm_policy_put_afinfo(afinfo);
1375
1376         return err;
1377 }
1378
1379 /* Allocate chain of dst_entry's, attach known xfrm's, calculate
1380  * all the metrics... Shortly, bundle a bundle.
1381  */
1382
1383 static struct dst_entry *xfrm_bundle_create(struct xfrm_policy *policy,
1384                                             struct xfrm_state **xfrm, int nx,
1385                                             struct flowi *fl,
1386                                             struct dst_entry *dst)
1387 {
1388         unsigned long now = jiffies;
1389         struct net_device *dev;
1390         struct dst_entry *dst_prev = NULL;
1391         struct dst_entry *dst0 = NULL;
1392         int i = 0;
1393         int err;
1394         int header_len = 0;
1395         int nfheader_len = 0;
1396         int trailer_len = 0;
1397         int tos;
1398         int family = policy->selector.family;
1399         xfrm_address_t saddr, daddr;
1400
1401         xfrm_flowi_addr_get(fl, &saddr, &daddr, family);
1402
1403         tos = xfrm_get_tos(fl, family);
1404         err = tos;
1405         if (tos < 0)
1406                 goto put_states;
1407
1408         dst_hold(dst);
1409
1410         for (; i < nx; i++) {
1411                 struct xfrm_dst *xdst = xfrm_alloc_dst(family);
1412                 struct dst_entry *dst1 = &xdst->u.dst;
1413
1414                 err = PTR_ERR(xdst);
1415                 if (IS_ERR(xdst)) {
1416                         dst_release(dst);
1417                         goto put_states;
1418                 }
1419
1420                 if (!dst_prev)
1421                         dst0 = dst1;
1422                 else {
1423                         dst_prev->child = dst_clone(dst1);
1424                         dst1->flags |= DST_NOHASH;
1425                 }
1426
1427                 xdst->route = dst;
1428                 memcpy(&dst1->metrics, &dst->metrics, sizeof(dst->metrics));
1429
1430                 if (xfrm[i]->props.mode != XFRM_MODE_TRANSPORT) {
1431                         family = xfrm[i]->props.family;
1432                         dst = xfrm_dst_lookup(xfrm[i], tos, &saddr, &daddr,
1433                                               family);
1434                         err = PTR_ERR(dst);
1435                         if (IS_ERR(dst))
1436                                 goto put_states;
1437                 } else
1438                         dst_hold(dst);
1439
1440                 dst1->xfrm = xfrm[i];
1441                 xdst->genid = xfrm[i]->genid;
1442
1443                 dst1->obsolete = -1;
1444                 dst1->flags |= DST_HOST;
1445                 dst1->lastuse = now;
1446
1447                 dst1->input = dst_discard;
1448                 dst1->output = xfrm[i]->outer_mode->afinfo->output;
1449
1450                 dst1->next = dst_prev;
1451                 dst_prev = dst1;
1452
1453                 header_len += xfrm[i]->props.header_len;
1454                 if (xfrm[i]->type->flags & XFRM_TYPE_NON_FRAGMENT)
1455                         nfheader_len += xfrm[i]->props.header_len;
1456                 trailer_len += xfrm[i]->props.trailer_len;
1457         }
1458
1459         dst_prev->child = dst;
1460         dst0->path = dst;
1461
1462         err = -ENODEV;
1463         dev = dst->dev;
1464         if (!dev)
1465                 goto free_dst;
1466
1467         /* Copy neighbout for reachability confirmation */
1468         dst0->neighbour = neigh_clone(dst->neighbour);
1469
1470         xfrm_init_path((struct xfrm_dst *)dst0, dst, nfheader_len);
1471         xfrm_init_pmtu(dst_prev);
1472
1473         for (dst_prev = dst0; dst_prev != dst; dst_prev = dst_prev->child) {
1474                 struct xfrm_dst *xdst = (struct xfrm_dst *)dst_prev;
1475
1476                 err = xfrm_fill_dst(xdst, dev);
1477                 if (err)
1478                         goto free_dst;
1479
1480                 dst_prev->header_len = header_len;
1481                 dst_prev->trailer_len = trailer_len;
1482                 header_len -= xdst->u.dst.xfrm->props.header_len;
1483                 trailer_len -= xdst->u.dst.xfrm->props.trailer_len;
1484         }
1485
1486 out:
1487         return dst0;
1488
1489 put_states:
1490         for (; i < nx; i++)
1491                 xfrm_state_put(xfrm[i]);
1492 free_dst:
1493         if (dst0)
1494                 dst_free(dst0);
1495         dst0 = ERR_PTR(err);
1496         goto out;
1497 }
1498
1499 static int inline
1500 xfrm_dst_alloc_copy(void **target, void *src, int size)
1501 {
1502         if (!*target) {
1503                 *target = kmalloc(size, GFP_ATOMIC);
1504                 if (!*target)
1505                         return -ENOMEM;
1506         }
1507         memcpy(*target, src, size);
1508         return 0;
1509 }
1510
1511 static int inline
1512 xfrm_dst_update_parent(struct dst_entry *dst, struct xfrm_selector *sel)
1513 {
1514 #ifdef CONFIG_XFRM_SUB_POLICY
1515         struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
1516         return xfrm_dst_alloc_copy((void **)&(xdst->partner),
1517                                    sel, sizeof(*sel));
1518 #else
1519         return 0;
1520 #endif
1521 }
1522
1523 static int inline
1524 xfrm_dst_update_origin(struct dst_entry *dst, struct flowi *fl)
1525 {
1526 #ifdef CONFIG_XFRM_SUB_POLICY
1527         struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
1528         return xfrm_dst_alloc_copy((void **)&(xdst->origin), fl, sizeof(*fl));
1529 #else
1530         return 0;
1531 #endif
1532 }
1533
1534 static int stale_bundle(struct dst_entry *dst);
1535
1536 /* Main function: finds/creates a bundle for given flow.
1537  *
1538  * At the moment we eat a raw IP route. Mostly to speed up lookups
1539  * on interfaces with disabled IPsec.
1540  */
1541 int __xfrm_lookup(struct net *net, struct dst_entry **dst_p, struct flowi *fl,
1542                   struct sock *sk, int flags)
1543 {
1544         struct xfrm_policy *policy;
1545         struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
1546         int npols;
1547         int pol_dead;
1548         int xfrm_nr;
1549         int pi;
1550         struct xfrm_state *xfrm[XFRM_MAX_DEPTH];
1551         struct dst_entry *dst, *dst_orig = *dst_p;
1552         int nx = 0;
1553         int err;
1554         u32 genid;
1555         u16 family;
1556         u8 dir = policy_to_flow_dir(XFRM_POLICY_OUT);
1557
1558 restart:
1559         genid = atomic_read(&flow_cache_genid);
1560         policy = NULL;
1561         for (pi = 0; pi < ARRAY_SIZE(pols); pi++)
1562                 pols[pi] = NULL;
1563         npols = 0;
1564         pol_dead = 0;
1565         xfrm_nr = 0;
1566
1567         if (sk && sk->sk_policy[XFRM_POLICY_OUT]) {
1568                 policy = xfrm_sk_policy_lookup(sk, XFRM_POLICY_OUT, fl);
1569                 err = PTR_ERR(policy);
1570                 if (IS_ERR(policy)) {
1571                         XFRM_INC_STATS(LINUX_MIB_XFRMOUTPOLERROR);
1572                         goto dropdst;
1573                 }
1574         }
1575
1576         if (!policy) {
1577                 /* To accelerate a bit...  */
1578                 if ((dst_orig->flags & DST_NOXFRM) ||
1579                     !net->xfrm.policy_count[XFRM_POLICY_OUT])
1580                         goto nopol;
1581
1582                 policy = flow_cache_lookup(net, fl, dst_orig->ops->family,
1583                                            dir, xfrm_policy_lookup);
1584                 err = PTR_ERR(policy);
1585                 if (IS_ERR(policy)) {
1586                         XFRM_INC_STATS(LINUX_MIB_XFRMOUTPOLERROR);
1587                         goto dropdst;
1588                 }
1589         }
1590
1591         if (!policy)
1592                 goto nopol;
1593
1594         family = dst_orig->ops->family;
1595         pols[0] = policy;
1596         npols ++;
1597         xfrm_nr += pols[0]->xfrm_nr;
1598
1599         err = -ENOENT;
1600         if ((flags & XFRM_LOOKUP_ICMP) && !(policy->flags & XFRM_POLICY_ICMP))
1601                 goto error;
1602
1603         policy->curlft.use_time = get_seconds();
1604
1605         switch (policy->action) {
1606         default:
1607         case XFRM_POLICY_BLOCK:
1608                 /* Prohibit the flow */
1609                 XFRM_INC_STATS(LINUX_MIB_XFRMOUTPOLBLOCK);
1610                 err = -EPERM;
1611                 goto error;
1612
1613         case XFRM_POLICY_ALLOW:
1614 #ifndef CONFIG_XFRM_SUB_POLICY
1615                 if (policy->xfrm_nr == 0) {
1616                         /* Flow passes not transformed. */
1617                         xfrm_pol_put(policy);
1618                         return 0;
1619                 }
1620 #endif
1621
1622                 /* Try to find matching bundle.
1623                  *
1624                  * LATER: help from flow cache. It is optional, this
1625                  * is required only for output policy.
1626                  */
1627                 dst = xfrm_find_bundle(fl, policy, family);
1628                 if (IS_ERR(dst)) {
1629                         XFRM_INC_STATS(LINUX_MIB_XFRMOUTBUNDLECHECKERROR);
1630                         err = PTR_ERR(dst);
1631                         goto error;
1632                 }
1633
1634                 if (dst)
1635                         break;
1636
1637 #ifdef CONFIG_XFRM_SUB_POLICY
1638                 if (pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
1639                         pols[1] = xfrm_policy_lookup_bytype(net,
1640                                                             XFRM_POLICY_TYPE_MAIN,
1641                                                             fl, family,
1642                                                             XFRM_POLICY_OUT);
1643                         if (pols[1]) {
1644                                 if (IS_ERR(pols[1])) {
1645                                         XFRM_INC_STATS(LINUX_MIB_XFRMOUTPOLERROR);
1646                                         err = PTR_ERR(pols[1]);
1647                                         goto error;
1648                                 }
1649                                 if (pols[1]->action == XFRM_POLICY_BLOCK) {
1650                                         XFRM_INC_STATS(LINUX_MIB_XFRMOUTPOLBLOCK);
1651                                         err = -EPERM;
1652                                         goto error;
1653                                 }
1654                                 npols ++;
1655                                 xfrm_nr += pols[1]->xfrm_nr;
1656                         }
1657                 }
1658
1659                 /*
1660                  * Because neither flowi nor bundle information knows about
1661                  * transformation template size. On more than one policy usage
1662                  * we can realize whether all of them is bypass or not after
1663                  * they are searched. See above not-transformed bypass
1664                  * is surrounded by non-sub policy configuration, too.
1665                  */
1666                 if (xfrm_nr == 0) {
1667                         /* Flow passes not transformed. */
1668                         xfrm_pols_put(pols, npols);
1669                         return 0;
1670                 }
1671
1672 #endif
1673                 nx = xfrm_tmpl_resolve(pols, npols, fl, xfrm, family);
1674
1675                 if (unlikely(nx<0)) {
1676                         err = nx;
1677                         if (err == -EAGAIN && sysctl_xfrm_larval_drop) {
1678                                 /* EREMOTE tells the caller to generate
1679                                  * a one-shot blackhole route.
1680                                  */
1681                                 XFRM_INC_STATS(LINUX_MIB_XFRMOUTNOSTATES);
1682                                 xfrm_pol_put(policy);
1683                                 return -EREMOTE;
1684                         }
1685                         if (err == -EAGAIN && (flags & XFRM_LOOKUP_WAIT)) {
1686                                 DECLARE_WAITQUEUE(wait, current);
1687
1688                                 add_wait_queue(&net->xfrm.km_waitq, &wait);
1689                                 set_current_state(TASK_INTERRUPTIBLE);
1690                                 schedule();
1691                                 set_current_state(TASK_RUNNING);
1692                                 remove_wait_queue(&net->xfrm.km_waitq, &wait);
1693
1694                                 nx = xfrm_tmpl_resolve(pols, npols, fl, xfrm, family);
1695
1696                                 if (nx == -EAGAIN && signal_pending(current)) {
1697                                         XFRM_INC_STATS(LINUX_MIB_XFRMOUTNOSTATES);
1698                                         err = -ERESTART;
1699                                         goto error;
1700                                 }
1701                                 if (nx == -EAGAIN ||
1702                                     genid != atomic_read(&flow_cache_genid)) {
1703                                         xfrm_pols_put(pols, npols);
1704                                         goto restart;
1705                                 }
1706                                 err = nx;
1707                         }
1708                         if (err < 0) {
1709                                 XFRM_INC_STATS(LINUX_MIB_XFRMOUTNOSTATES);
1710                                 goto error;
1711                         }
1712                 }
1713                 if (nx == 0) {
1714                         /* Flow passes not transformed. */
1715                         xfrm_pols_put(pols, npols);
1716                         return 0;
1717                 }
1718
1719                 dst = xfrm_bundle_create(policy, xfrm, nx, fl, dst_orig);
1720                 err = PTR_ERR(dst);
1721                 if (IS_ERR(dst)) {
1722                         XFRM_INC_STATS(LINUX_MIB_XFRMOUTBUNDLEGENERROR);
1723                         goto error;
1724                 }
1725
1726                 for (pi = 0; pi < npols; pi++) {
1727                         read_lock_bh(&pols[pi]->lock);
1728                         pol_dead |= pols[pi]->walk.dead;
1729                         read_unlock_bh(&pols[pi]->lock);
1730                 }
1731
1732                 write_lock_bh(&policy->lock);
1733                 if (unlikely(pol_dead || stale_bundle(dst))) {
1734                         /* Wow! While we worked on resolving, this
1735                          * policy has gone. Retry. It is not paranoia,
1736                          * we just cannot enlist new bundle to dead object.
1737                          * We can't enlist stable bundles either.
1738                          */
1739                         write_unlock_bh(&policy->lock);
1740                         dst_free(dst);
1741
1742                         if (pol_dead)
1743                                 XFRM_INC_STATS(LINUX_MIB_XFRMOUTPOLDEAD);
1744                         else
1745                                 XFRM_INC_STATS(LINUX_MIB_XFRMOUTBUNDLECHECKERROR);
1746                         err = -EHOSTUNREACH;
1747                         goto error;
1748                 }
1749
1750                 if (npols > 1)
1751                         err = xfrm_dst_update_parent(dst, &pols[1]->selector);
1752                 else
1753                         err = xfrm_dst_update_origin(dst, fl);
1754                 if (unlikely(err)) {
1755                         write_unlock_bh(&policy->lock);
1756                         dst_free(dst);
1757                         XFRM_INC_STATS(LINUX_MIB_XFRMOUTBUNDLECHECKERROR);
1758                         goto error;
1759                 }
1760
1761                 dst->next = policy->bundles;
1762                 policy->bundles = dst;
1763                 dst_hold(dst);
1764                 write_unlock_bh(&policy->lock);
1765         }
1766         *dst_p = dst;
1767         dst_release(dst_orig);
1768         xfrm_pols_put(pols, npols);
1769         return 0;
1770
1771 error:
1772         xfrm_pols_put(pols, npols);
1773 dropdst:
1774         dst_release(dst_orig);
1775         *dst_p = NULL;
1776         return err;
1777
1778 nopol:
1779         err = -ENOENT;
1780         if (flags & XFRM_LOOKUP_ICMP)
1781                 goto dropdst;
1782         return 0;
1783 }
1784 EXPORT_SYMBOL(__xfrm_lookup);
1785
1786 int xfrm_lookup(struct net *net, struct dst_entry **dst_p, struct flowi *fl,
1787                 struct sock *sk, int flags)
1788 {
1789         int err = __xfrm_lookup(net, dst_p, fl, sk, flags);
1790
1791         if (err == -EREMOTE) {
1792                 dst_release(*dst_p);
1793                 *dst_p = NULL;
1794                 err = -EAGAIN;
1795         }
1796
1797         return err;
1798 }
1799 EXPORT_SYMBOL(xfrm_lookup);
1800
1801 static inline int
1802 xfrm_secpath_reject(int idx, struct sk_buff *skb, struct flowi *fl)
1803 {
1804         struct xfrm_state *x;
1805
1806         if (!skb->sp || idx < 0 || idx >= skb->sp->len)
1807                 return 0;
1808         x = skb->sp->xvec[idx];
1809         if (!x->type->reject)
1810                 return 0;
1811         return x->type->reject(x, skb, fl);
1812 }
1813
1814 /* When skb is transformed back to its "native" form, we have to
1815  * check policy restrictions. At the moment we make this in maximally
1816  * stupid way. Shame on me. :-) Of course, connected sockets must
1817  * have policy cached at them.
1818  */
1819
1820 static inline int
1821 xfrm_state_ok(struct xfrm_tmpl *tmpl, struct xfrm_state *x,
1822               unsigned short family)
1823 {
1824         if (xfrm_state_kern(x))
1825                 return tmpl->optional && !xfrm_state_addr_cmp(tmpl, x, tmpl->encap_family);
1826         return  x->id.proto == tmpl->id.proto &&
1827                 (x->id.spi == tmpl->id.spi || !tmpl->id.spi) &&
1828                 (x->props.reqid == tmpl->reqid || !tmpl->reqid) &&
1829                 x->props.mode == tmpl->mode &&
1830                 (tmpl->allalgs || (tmpl->aalgos & (1<<x->props.aalgo)) ||
1831                  !(xfrm_id_proto_match(tmpl->id.proto, IPSEC_PROTO_ANY))) &&
1832                 !(x->props.mode != XFRM_MODE_TRANSPORT &&
1833                   xfrm_state_addr_cmp(tmpl, x, family));
1834 }
1835
1836 /*
1837  * 0 or more than 0 is returned when validation is succeeded (either bypass
1838  * because of optional transport mode, or next index of the mathced secpath
1839  * state with the template.
1840  * -1 is returned when no matching template is found.
1841  * Otherwise "-2 - errored_index" is returned.
1842  */
1843 static inline int
1844 xfrm_policy_ok(struct xfrm_tmpl *tmpl, struct sec_path *sp, int start,
1845                unsigned short family)
1846 {
1847         int idx = start;
1848
1849         if (tmpl->optional) {
1850                 if (tmpl->mode == XFRM_MODE_TRANSPORT)
1851                         return start;
1852         } else
1853                 start = -1;
1854         for (; idx < sp->len; idx++) {
1855                 if (xfrm_state_ok(tmpl, sp->xvec[idx], family))
1856                         return ++idx;
1857                 if (sp->xvec[idx]->props.mode != XFRM_MODE_TRANSPORT) {
1858                         if (start == -1)
1859                                 start = -2-idx;
1860                         break;
1861                 }
1862         }
1863         return start;
1864 }
1865
1866 int __xfrm_decode_session(struct sk_buff *skb, struct flowi *fl,
1867                           unsigned int family, int reverse)
1868 {
1869         struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1870         int err;
1871
1872         if (unlikely(afinfo == NULL))
1873                 return -EAFNOSUPPORT;
1874
1875         afinfo->decode_session(skb, fl, reverse);
1876         err = security_xfrm_decode_session(skb, &fl->secid);
1877         xfrm_policy_put_afinfo(afinfo);
1878         return err;
1879 }
1880 EXPORT_SYMBOL(__xfrm_decode_session);
1881
1882 static inline int secpath_has_nontransport(struct sec_path *sp, int k, int *idxp)
1883 {
1884         for (; k < sp->len; k++) {
1885                 if (sp->xvec[k]->props.mode != XFRM_MODE_TRANSPORT) {
1886                         *idxp = k;
1887                         return 1;
1888                 }
1889         }
1890
1891         return 0;
1892 }
1893
1894 int __xfrm_policy_check(struct sock *sk, int dir, struct sk_buff *skb,
1895                         unsigned short family)
1896 {
1897         struct net *net = dev_net(skb->dev);
1898         struct xfrm_policy *pol;
1899         struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
1900         int npols = 0;
1901         int xfrm_nr;
1902         int pi;
1903         int reverse;
1904         struct flowi fl;
1905         u8 fl_dir;
1906         int xerr_idx = -1;
1907
1908         reverse = dir & ~XFRM_POLICY_MASK;
1909         dir &= XFRM_POLICY_MASK;
1910         fl_dir = policy_to_flow_dir(dir);
1911
1912         if (__xfrm_decode_session(skb, &fl, family, reverse) < 0) {
1913                 XFRM_INC_STATS(LINUX_MIB_XFRMINHDRERROR);
1914                 return 0;
1915         }
1916
1917         nf_nat_decode_session(skb, &fl, family);
1918
1919         /* First, check used SA against their selectors. */
1920         if (skb->sp) {
1921                 int i;
1922
1923                 for (i=skb->sp->len-1; i>=0; i--) {
1924                         struct xfrm_state *x = skb->sp->xvec[i];
1925                         if (!xfrm_selector_match(&x->sel, &fl, family)) {
1926                                 XFRM_INC_STATS(LINUX_MIB_XFRMINSTATEMISMATCH);
1927                                 return 0;
1928                         }
1929                 }
1930         }
1931
1932         pol = NULL;
1933         if (sk && sk->sk_policy[dir]) {
1934                 pol = xfrm_sk_policy_lookup(sk, dir, &fl);
1935                 if (IS_ERR(pol)) {
1936                         XFRM_INC_STATS(LINUX_MIB_XFRMINPOLERROR);
1937                         return 0;
1938                 }
1939         }
1940
1941         if (!pol)
1942                 pol = flow_cache_lookup(net, &fl, family, fl_dir,
1943                                         xfrm_policy_lookup);
1944
1945         if (IS_ERR(pol)) {
1946                 XFRM_INC_STATS(LINUX_MIB_XFRMINPOLERROR);
1947                 return 0;
1948         }
1949
1950         if (!pol) {
1951                 if (skb->sp && secpath_has_nontransport(skb->sp, 0, &xerr_idx)) {
1952                         xfrm_secpath_reject(xerr_idx, skb, &fl);
1953                         XFRM_INC_STATS(LINUX_MIB_XFRMINNOPOLS);
1954                         return 0;
1955                 }
1956                 return 1;
1957         }
1958
1959         pol->curlft.use_time = get_seconds();
1960
1961         pols[0] = pol;
1962         npols ++;
1963 #ifdef CONFIG_XFRM_SUB_POLICY
1964         if (pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
1965                 pols[1] = xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_MAIN,
1966                                                     &fl, family,
1967                                                     XFRM_POLICY_IN);
1968                 if (pols[1]) {
1969                         if (IS_ERR(pols[1])) {
1970                                 XFRM_INC_STATS(LINUX_MIB_XFRMINPOLERROR);
1971                                 return 0;
1972                         }
1973                         pols[1]->curlft.use_time = get_seconds();
1974                         npols ++;
1975                 }
1976         }
1977 #endif
1978
1979         if (pol->action == XFRM_POLICY_ALLOW) {
1980                 struct sec_path *sp;
1981                 static struct sec_path dummy;
1982                 struct xfrm_tmpl *tp[XFRM_MAX_DEPTH];
1983                 struct xfrm_tmpl *stp[XFRM_MAX_DEPTH];
1984                 struct xfrm_tmpl **tpp = tp;
1985                 int ti = 0;
1986                 int i, k;
1987
1988                 if ((sp = skb->sp) == NULL)
1989                         sp = &dummy;
1990
1991                 for (pi = 0; pi < npols; pi++) {
1992                         if (pols[pi] != pol &&
1993                             pols[pi]->action != XFRM_POLICY_ALLOW) {
1994                                 XFRM_INC_STATS(LINUX_MIB_XFRMINPOLBLOCK);
1995                                 goto reject;
1996                         }
1997                         if (ti + pols[pi]->xfrm_nr >= XFRM_MAX_DEPTH) {
1998                                 XFRM_INC_STATS(LINUX_MIB_XFRMINBUFFERERROR);
1999                                 goto reject_error;
2000                         }
2001                         for (i = 0; i < pols[pi]->xfrm_nr; i++)
2002                                 tpp[ti++] = &pols[pi]->xfrm_vec[i];
2003                 }
2004                 xfrm_nr = ti;
2005                 if (npols > 1) {
2006                         xfrm_tmpl_sort(stp, tpp, xfrm_nr, family);
2007                         tpp = stp;
2008                 }
2009
2010                 /* For each tunnel xfrm, find the first matching tmpl.
2011                  * For each tmpl before that, find corresponding xfrm.
2012                  * Order is _important_. Later we will implement
2013                  * some barriers, but at the moment barriers
2014                  * are implied between each two transformations.
2015                  */
2016                 for (i = xfrm_nr-1, k = 0; i >= 0; i--) {
2017                         k = xfrm_policy_ok(tpp[i], sp, k, family);
2018                         if (k < 0) {
2019                                 if (k < -1)
2020                                         /* "-2 - errored_index" returned */
2021                                         xerr_idx = -(2+k);
2022                                 XFRM_INC_STATS(LINUX_MIB_XFRMINTMPLMISMATCH);
2023                                 goto reject;
2024                         }
2025                 }
2026
2027                 if (secpath_has_nontransport(sp, k, &xerr_idx)) {
2028                         XFRM_INC_STATS(LINUX_MIB_XFRMINTMPLMISMATCH);
2029                         goto reject;
2030                 }
2031
2032                 xfrm_pols_put(pols, npols);
2033                 return 1;
2034         }
2035         XFRM_INC_STATS(LINUX_MIB_XFRMINPOLBLOCK);
2036
2037 reject:
2038         xfrm_secpath_reject(xerr_idx, skb, &fl);
2039 reject_error:
2040         xfrm_pols_put(pols, npols);
2041         return 0;
2042 }
2043 EXPORT_SYMBOL(__xfrm_policy_check);
2044
2045 int __xfrm_route_forward(struct sk_buff *skb, unsigned short family)
2046 {
2047         struct net *net = dev_net(skb->dev);
2048         struct flowi fl;
2049
2050         if (xfrm_decode_session(skb, &fl, family) < 0) {
2051                 /* XXX: we should have something like FWDHDRERROR here. */
2052                 XFRM_INC_STATS(LINUX_MIB_XFRMINHDRERROR);
2053                 return 0;
2054         }
2055
2056         return xfrm_lookup(net, &skb->dst, &fl, NULL, 0) == 0;
2057 }
2058 EXPORT_SYMBOL(__xfrm_route_forward);
2059
2060 /* Optimize later using cookies and generation ids. */
2061
2062 static struct dst_entry *xfrm_dst_check(struct dst_entry *dst, u32 cookie)
2063 {
2064         /* Code (such as __xfrm4_bundle_create()) sets dst->obsolete
2065          * to "-1" to force all XFRM destinations to get validated by
2066          * dst_ops->check on every use.  We do this because when a
2067          * normal route referenced by an XFRM dst is obsoleted we do
2068          * not go looking around for all parent referencing XFRM dsts
2069          * so that we can invalidate them.  It is just too much work.
2070          * Instead we make the checks here on every use.  For example:
2071          *
2072          *      XFRM dst A --> IPv4 dst X
2073          *
2074          * X is the "xdst->route" of A (X is also the "dst->path" of A
2075          * in this example).  If X is marked obsolete, "A" will not
2076          * notice.  That's what we are validating here via the
2077          * stale_bundle() check.
2078          *
2079          * When a policy's bundle is pruned, we dst_free() the XFRM
2080          * dst which causes it's ->obsolete field to be set to a
2081          * positive non-zero integer.  If an XFRM dst has been pruned
2082          * like this, we want to force a new route lookup.
2083          */
2084         if (dst->obsolete < 0 && !stale_bundle(dst))
2085                 return dst;
2086
2087         return NULL;
2088 }
2089
2090 static int stale_bundle(struct dst_entry *dst)
2091 {
2092         return !xfrm_bundle_ok(NULL, (struct xfrm_dst *)dst, NULL, AF_UNSPEC, 0);
2093 }
2094
2095 void xfrm_dst_ifdown(struct dst_entry *dst, struct net_device *dev)
2096 {
2097         while ((dst = dst->child) && dst->xfrm && dst->dev == dev) {
2098                 dst->dev = dev_net(dev)->loopback_dev;
2099                 dev_hold(dst->dev);
2100                 dev_put(dev);
2101         }
2102 }
2103 EXPORT_SYMBOL(xfrm_dst_ifdown);
2104
2105 static void xfrm_link_failure(struct sk_buff *skb)
2106 {
2107         /* Impossible. Such dst must be popped before reaches point of failure. */
2108         return;
2109 }
2110
2111 static struct dst_entry *xfrm_negative_advice(struct dst_entry *dst)
2112 {
2113         if (dst) {
2114                 if (dst->obsolete) {
2115                         dst_release(dst);
2116                         dst = NULL;
2117                 }
2118         }
2119         return dst;
2120 }
2121
2122 static void prune_one_bundle(struct xfrm_policy *pol, int (*func)(struct dst_entry *), struct dst_entry **gc_list_p)
2123 {
2124         struct dst_entry *dst, **dstp;
2125
2126         write_lock(&pol->lock);
2127         dstp = &pol->bundles;
2128         while ((dst=*dstp) != NULL) {
2129                 if (func(dst)) {
2130                         *dstp = dst->next;
2131                         dst->next = *gc_list_p;
2132                         *gc_list_p = dst;
2133                 } else {
2134                         dstp = &dst->next;
2135                 }
2136         }
2137         write_unlock(&pol->lock);
2138 }
2139
2140 static void xfrm_prune_bundles(int (*func)(struct dst_entry *))
2141 {
2142         struct dst_entry *gc_list = NULL;
2143         int dir;
2144
2145         read_lock_bh(&xfrm_policy_lock);
2146         for (dir = 0; dir < XFRM_POLICY_MAX * 2; dir++) {
2147                 struct xfrm_policy *pol;
2148                 struct hlist_node *entry;
2149                 struct hlist_head *table;
2150                 int i;
2151
2152                 hlist_for_each_entry(pol, entry,
2153                                      &init_net.xfrm.policy_inexact[dir], bydst)
2154                         prune_one_bundle(pol, func, &gc_list);
2155
2156                 table = init_net.xfrm.policy_bydst[dir].table;
2157                 for (i = init_net.xfrm.policy_bydst[dir].hmask; i >= 0; i--) {
2158                         hlist_for_each_entry(pol, entry, table + i, bydst)
2159                                 prune_one_bundle(pol, func, &gc_list);
2160                 }
2161         }
2162         read_unlock_bh(&xfrm_policy_lock);
2163
2164         while (gc_list) {
2165                 struct dst_entry *dst = gc_list;
2166                 gc_list = dst->next;
2167                 dst_free(dst);
2168         }
2169 }
2170
2171 static int unused_bundle(struct dst_entry *dst)
2172 {
2173         return !atomic_read(&dst->__refcnt);
2174 }
2175
2176 static void __xfrm_garbage_collect(void)
2177 {
2178         xfrm_prune_bundles(unused_bundle);
2179 }
2180
2181 static int xfrm_flush_bundles(void)
2182 {
2183         xfrm_prune_bundles(stale_bundle);
2184         return 0;
2185 }
2186
2187 static void xfrm_init_pmtu(struct dst_entry *dst)
2188 {
2189         do {
2190                 struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
2191                 u32 pmtu, route_mtu_cached;
2192
2193                 pmtu = dst_mtu(dst->child);
2194                 xdst->child_mtu_cached = pmtu;
2195
2196                 pmtu = xfrm_state_mtu(dst->xfrm, pmtu);
2197
2198                 route_mtu_cached = dst_mtu(xdst->route);
2199                 xdst->route_mtu_cached = route_mtu_cached;
2200
2201                 if (pmtu > route_mtu_cached)
2202                         pmtu = route_mtu_cached;
2203
2204                 dst->metrics[RTAX_MTU-1] = pmtu;
2205         } while ((dst = dst->next));
2206 }
2207
2208 /* Check that the bundle accepts the flow and its components are
2209  * still valid.
2210  */
2211
2212 int xfrm_bundle_ok(struct xfrm_policy *pol, struct xfrm_dst *first,
2213                 struct flowi *fl, int family, int strict)
2214 {
2215         struct dst_entry *dst = &first->u.dst;
2216         struct xfrm_dst *last;
2217         u32 mtu;
2218
2219         if (!dst_check(dst->path, ((struct xfrm_dst *)dst)->path_cookie) ||
2220             (dst->dev && !netif_running(dst->dev)))
2221                 return 0;
2222 #ifdef CONFIG_XFRM_SUB_POLICY
2223         if (fl) {
2224                 if (first->origin && !flow_cache_uli_match(first->origin, fl))
2225                         return 0;
2226                 if (first->partner &&
2227                     !xfrm_selector_match(first->partner, fl, family))
2228                         return 0;
2229         }
2230 #endif
2231
2232         last = NULL;
2233
2234         do {
2235                 struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
2236
2237                 if (fl && !xfrm_selector_match(&dst->xfrm->sel, fl, family))
2238                         return 0;
2239                 if (fl && pol &&
2240                     !security_xfrm_state_pol_flow_match(dst->xfrm, pol, fl))
2241                         return 0;
2242                 if (dst->xfrm->km.state != XFRM_STATE_VALID)
2243                         return 0;
2244                 if (xdst->genid != dst->xfrm->genid)
2245                         return 0;
2246
2247                 if (strict && fl &&
2248                     !(dst->xfrm->outer_mode->flags & XFRM_MODE_FLAG_TUNNEL) &&
2249                     !xfrm_state_addr_flow_check(dst->xfrm, fl, family))
2250                         return 0;
2251
2252                 mtu = dst_mtu(dst->child);
2253                 if (xdst->child_mtu_cached != mtu) {
2254                         last = xdst;
2255                         xdst->child_mtu_cached = mtu;
2256                 }
2257
2258                 if (!dst_check(xdst->route, xdst->route_cookie))
2259                         return 0;
2260                 mtu = dst_mtu(xdst->route);
2261                 if (xdst->route_mtu_cached != mtu) {
2262                         last = xdst;
2263                         xdst->route_mtu_cached = mtu;
2264                 }
2265
2266                 dst = dst->child;
2267         } while (dst->xfrm);
2268
2269         if (likely(!last))
2270                 return 1;
2271
2272         mtu = last->child_mtu_cached;
2273         for (;;) {
2274                 dst = &last->u.dst;
2275
2276                 mtu = xfrm_state_mtu(dst->xfrm, mtu);
2277                 if (mtu > last->route_mtu_cached)
2278                         mtu = last->route_mtu_cached;
2279                 dst->metrics[RTAX_MTU-1] = mtu;
2280
2281                 if (last == first)
2282                         break;
2283
2284                 last = (struct xfrm_dst *)last->u.dst.next;
2285                 last->child_mtu_cached = mtu;
2286         }
2287
2288         return 1;
2289 }
2290
2291 EXPORT_SYMBOL(xfrm_bundle_ok);
2292
2293 int xfrm_policy_register_afinfo(struct xfrm_policy_afinfo *afinfo)
2294 {
2295         int err = 0;
2296         if (unlikely(afinfo == NULL))
2297                 return -EINVAL;
2298         if (unlikely(afinfo->family >= NPROTO))
2299                 return -EAFNOSUPPORT;
2300         write_lock_bh(&xfrm_policy_afinfo_lock);
2301         if (unlikely(xfrm_policy_afinfo[afinfo->family] != NULL))
2302                 err = -ENOBUFS;
2303         else {
2304                 struct dst_ops *dst_ops = afinfo->dst_ops;
2305                 if (likely(dst_ops->kmem_cachep == NULL))
2306                         dst_ops->kmem_cachep = xfrm_dst_cache;
2307                 if (likely(dst_ops->check == NULL))
2308                         dst_ops->check = xfrm_dst_check;
2309                 if (likely(dst_ops->negative_advice == NULL))
2310                         dst_ops->negative_advice = xfrm_negative_advice;
2311                 if (likely(dst_ops->link_failure == NULL))
2312                         dst_ops->link_failure = xfrm_link_failure;
2313                 if (likely(afinfo->garbage_collect == NULL))
2314                         afinfo->garbage_collect = __xfrm_garbage_collect;
2315                 xfrm_policy_afinfo[afinfo->family] = afinfo;
2316         }
2317         write_unlock_bh(&xfrm_policy_afinfo_lock);
2318         return err;
2319 }
2320 EXPORT_SYMBOL(xfrm_policy_register_afinfo);
2321
2322 int xfrm_policy_unregister_afinfo(struct xfrm_policy_afinfo *afinfo)
2323 {
2324         int err = 0;
2325         if (unlikely(afinfo == NULL))
2326                 return -EINVAL;
2327         if (unlikely(afinfo->family >= NPROTO))
2328                 return -EAFNOSUPPORT;
2329         write_lock_bh(&xfrm_policy_afinfo_lock);
2330         if (likely(xfrm_policy_afinfo[afinfo->family] != NULL)) {
2331                 if (unlikely(xfrm_policy_afinfo[afinfo->family] != afinfo))
2332                         err = -EINVAL;
2333                 else {
2334                         struct dst_ops *dst_ops = afinfo->dst_ops;
2335                         xfrm_policy_afinfo[afinfo->family] = NULL;
2336                         dst_ops->kmem_cachep = NULL;
2337                         dst_ops->check = NULL;
2338                         dst_ops->negative_advice = NULL;
2339                         dst_ops->link_failure = NULL;
2340                         afinfo->garbage_collect = NULL;
2341                 }
2342         }
2343         write_unlock_bh(&xfrm_policy_afinfo_lock);
2344         return err;
2345 }
2346 EXPORT_SYMBOL(xfrm_policy_unregister_afinfo);
2347
2348 static struct xfrm_policy_afinfo *xfrm_policy_get_afinfo(unsigned short family)
2349 {
2350         struct xfrm_policy_afinfo *afinfo;
2351         if (unlikely(family >= NPROTO))
2352                 return NULL;
2353         read_lock(&xfrm_policy_afinfo_lock);
2354         afinfo = xfrm_policy_afinfo[family];
2355         if (unlikely(!afinfo))
2356                 read_unlock(&xfrm_policy_afinfo_lock);
2357         return afinfo;
2358 }
2359
2360 static void xfrm_policy_put_afinfo(struct xfrm_policy_afinfo *afinfo)
2361 {
2362         read_unlock(&xfrm_policy_afinfo_lock);
2363 }
2364
2365 static int xfrm_dev_event(struct notifier_block *this, unsigned long event, void *ptr)
2366 {
2367         struct net_device *dev = ptr;
2368
2369         if (!net_eq(dev_net(dev), &init_net))
2370                 return NOTIFY_DONE;
2371
2372         switch (event) {
2373         case NETDEV_DOWN:
2374                 xfrm_flush_bundles();
2375         }
2376         return NOTIFY_DONE;
2377 }
2378
2379 static struct notifier_block xfrm_dev_notifier = {
2380         .notifier_call  = xfrm_dev_event,
2381 };
2382
2383 #ifdef CONFIG_XFRM_STATISTICS
2384 static int __init xfrm_statistics_init(void)
2385 {
2386         if (snmp_mib_init((void **)xfrm_statistics,
2387                           sizeof(struct linux_xfrm_mib)) < 0)
2388                 return -ENOMEM;
2389         return 0;
2390 }
2391 #endif
2392
2393 static int __net_init xfrm_policy_init(struct net *net)
2394 {
2395         unsigned int hmask, sz;
2396         int dir;
2397
2398         if (net_eq(net, &init_net))
2399                 xfrm_dst_cache = kmem_cache_create("xfrm_dst_cache",
2400                                            sizeof(struct xfrm_dst),
2401                                            0, SLAB_HWCACHE_ALIGN|SLAB_PANIC,
2402                                            NULL);
2403
2404         hmask = 8 - 1;
2405         sz = (hmask+1) * sizeof(struct hlist_head);
2406
2407         net->xfrm.policy_byidx = xfrm_hash_alloc(sz);
2408         if (!net->xfrm.policy_byidx)
2409                 goto out_byidx;
2410         net->xfrm.policy_idx_hmask = hmask;
2411
2412         for (dir = 0; dir < XFRM_POLICY_MAX * 2; dir++) {
2413                 struct xfrm_policy_hash *htab;
2414
2415                 net->xfrm.policy_count[dir] = 0;
2416                 INIT_HLIST_HEAD(&net->xfrm.policy_inexact[dir]);
2417
2418                 htab = &net->xfrm.policy_bydst[dir];
2419                 htab->table = xfrm_hash_alloc(sz);
2420                 if (!htab->table)
2421                         goto out_bydst;
2422                 htab->hmask = hmask;
2423         }
2424
2425         INIT_LIST_HEAD(&net->xfrm.policy_all);
2426         INIT_WORK(&net->xfrm.policy_hash_work, xfrm_hash_resize);
2427         if (net_eq(net, &init_net))
2428                 register_netdevice_notifier(&xfrm_dev_notifier);
2429         return 0;
2430
2431 out_bydst:
2432         for (dir--; dir >= 0; dir--) {
2433                 struct xfrm_policy_hash *htab;
2434
2435                 htab = &net->xfrm.policy_bydst[dir];
2436                 xfrm_hash_free(htab->table, sz);
2437         }
2438         xfrm_hash_free(net->xfrm.policy_byidx, sz);
2439 out_byidx:
2440         return -ENOMEM;
2441 }
2442
2443 static void xfrm_policy_fini(struct net *net)
2444 {
2445         unsigned int sz;
2446         int dir;
2447
2448         WARN_ON(!list_empty(&net->xfrm.policy_all));
2449
2450         for (dir = 0; dir < XFRM_POLICY_MAX * 2; dir++) {
2451                 struct xfrm_policy_hash *htab;
2452
2453                 WARN_ON(!hlist_empty(&net->xfrm.policy_inexact[dir]));
2454
2455                 htab = &net->xfrm.policy_bydst[dir];
2456                 sz = (htab->hmask + 1);
2457                 WARN_ON(!hlist_empty(htab->table));
2458                 xfrm_hash_free(htab->table, sz);
2459         }
2460
2461         sz = (net->xfrm.policy_idx_hmask + 1) * sizeof(struct hlist_head);
2462         WARN_ON(!hlist_empty(net->xfrm.policy_byidx));
2463         xfrm_hash_free(net->xfrm.policy_byidx, sz);
2464 }
2465
2466 static int __net_init xfrm_net_init(struct net *net)
2467 {
2468         int rv;
2469
2470         rv = xfrm_state_init(net);
2471         if (rv < 0)
2472                 goto out_state;
2473         rv = xfrm_policy_init(net);
2474         if (rv < 0)
2475                 goto out_policy;
2476         return 0;
2477
2478 out_policy:
2479         xfrm_state_fini(net);
2480 out_state:
2481         return rv;
2482 }
2483
2484 static void __net_exit xfrm_net_exit(struct net *net)
2485 {
2486         xfrm_policy_fini(net);
2487         xfrm_state_fini(net);
2488 }
2489
2490 static struct pernet_operations __net_initdata xfrm_net_ops = {
2491         .init = xfrm_net_init,
2492         .exit = xfrm_net_exit,
2493 };
2494
2495 void __init xfrm_init(void)
2496 {
2497         register_pernet_subsys(&xfrm_net_ops);
2498 #ifdef CONFIG_XFRM_STATISTICS
2499         xfrm_statistics_init();
2500 #endif
2501         xfrm_input_init();
2502 #ifdef CONFIG_XFRM_STATISTICS
2503         xfrm_proc_init();
2504 #endif
2505 }
2506
2507 #ifdef CONFIG_AUDITSYSCALL
2508 static void xfrm_audit_common_policyinfo(struct xfrm_policy *xp,
2509                                          struct audit_buffer *audit_buf)
2510 {
2511         struct xfrm_sec_ctx *ctx = xp->security;
2512         struct xfrm_selector *sel = &xp->selector;
2513
2514         if (ctx)
2515                 audit_log_format(audit_buf, " sec_alg=%u sec_doi=%u sec_obj=%s",
2516                                  ctx->ctx_alg, ctx->ctx_doi, ctx->ctx_str);
2517
2518         switch(sel->family) {
2519         case AF_INET:
2520                 audit_log_format(audit_buf, " src=%pI4", &sel->saddr.a4);
2521                 if (sel->prefixlen_s != 32)
2522                         audit_log_format(audit_buf, " src_prefixlen=%d",
2523                                          sel->prefixlen_s);
2524                 audit_log_format(audit_buf, " dst=%pI4", &sel->daddr.a4);
2525                 if (sel->prefixlen_d != 32)
2526                         audit_log_format(audit_buf, " dst_prefixlen=%d",
2527                                          sel->prefixlen_d);
2528                 break;
2529         case AF_INET6:
2530                 audit_log_format(audit_buf, " src=%pI6", sel->saddr.a6);
2531                 if (sel->prefixlen_s != 128)
2532                         audit_log_format(audit_buf, " src_prefixlen=%d",
2533                                          sel->prefixlen_s);
2534                 audit_log_format(audit_buf, " dst=%pI6", sel->daddr.a6);
2535                 if (sel->prefixlen_d != 128)
2536                         audit_log_format(audit_buf, " dst_prefixlen=%d",
2537                                          sel->prefixlen_d);
2538                 break;
2539         }
2540 }
2541
2542 void xfrm_audit_policy_add(struct xfrm_policy *xp, int result,
2543                            uid_t auid, u32 sessionid, u32 secid)
2544 {
2545         struct audit_buffer *audit_buf;
2546
2547         audit_buf = xfrm_audit_start("SPD-add");
2548         if (audit_buf == NULL)
2549                 return;
2550         xfrm_audit_helper_usrinfo(auid, sessionid, secid, audit_buf);
2551         audit_log_format(audit_buf, " res=%u", result);
2552         xfrm_audit_common_policyinfo(xp, audit_buf);
2553         audit_log_end(audit_buf);
2554 }
2555 EXPORT_SYMBOL_GPL(xfrm_audit_policy_add);
2556
2557 void xfrm_audit_policy_delete(struct xfrm_policy *xp, int result,
2558                               uid_t auid, u32 sessionid, u32 secid)
2559 {
2560         struct audit_buffer *audit_buf;
2561
2562         audit_buf = xfrm_audit_start("SPD-delete");
2563         if (audit_buf == NULL)
2564                 return;
2565         xfrm_audit_helper_usrinfo(auid, sessionid, secid, audit_buf);
2566         audit_log_format(audit_buf, " res=%u", result);
2567         xfrm_audit_common_policyinfo(xp, audit_buf);
2568         audit_log_end(audit_buf);
2569 }
2570 EXPORT_SYMBOL_GPL(xfrm_audit_policy_delete);
2571 #endif
2572
2573 #ifdef CONFIG_XFRM_MIGRATE
2574 static int xfrm_migrate_selector_match(struct xfrm_selector *sel_cmp,
2575                                        struct xfrm_selector *sel_tgt)
2576 {
2577         if (sel_cmp->proto == IPSEC_ULPROTO_ANY) {
2578                 if (sel_tgt->family == sel_cmp->family &&
2579                     xfrm_addr_cmp(&sel_tgt->daddr, &sel_cmp->daddr,
2580                                   sel_cmp->family) == 0 &&
2581                     xfrm_addr_cmp(&sel_tgt->saddr, &sel_cmp->saddr,
2582                                   sel_cmp->family) == 0 &&
2583                     sel_tgt->prefixlen_d == sel_cmp->prefixlen_d &&
2584                     sel_tgt->prefixlen_s == sel_cmp->prefixlen_s) {
2585                         return 1;
2586                 }
2587         } else {
2588                 if (memcmp(sel_tgt, sel_cmp, sizeof(*sel_tgt)) == 0) {
2589                         return 1;
2590                 }
2591         }
2592         return 0;
2593 }
2594
2595 static struct xfrm_policy * xfrm_migrate_policy_find(struct xfrm_selector *sel,
2596                                                      u8 dir, u8 type)
2597 {
2598         struct xfrm_policy *pol, *ret = NULL;
2599         struct hlist_node *entry;
2600         struct hlist_head *chain;
2601         u32 priority = ~0U;
2602
2603         read_lock_bh(&xfrm_policy_lock);
2604         chain = policy_hash_direct(&init_net, &sel->daddr, &sel->saddr, sel->family, dir);
2605         hlist_for_each_entry(pol, entry, chain, bydst) {
2606                 if (xfrm_migrate_selector_match(sel, &pol->selector) &&
2607                     pol->type == type) {
2608                         ret = pol;
2609                         priority = ret->priority;
2610                         break;
2611                 }
2612         }
2613         chain = &init_net.xfrm.policy_inexact[dir];
2614         hlist_for_each_entry(pol, entry, chain, bydst) {
2615                 if (xfrm_migrate_selector_match(sel, &pol->selector) &&
2616                     pol->type == type &&
2617                     pol->priority < priority) {
2618                         ret = pol;
2619                         break;
2620                 }
2621         }
2622
2623         if (ret)
2624                 xfrm_pol_hold(ret);
2625
2626         read_unlock_bh(&xfrm_policy_lock);
2627
2628         return ret;
2629 }
2630
2631 static int migrate_tmpl_match(struct xfrm_migrate *m, struct xfrm_tmpl *t)
2632 {
2633         int match = 0;
2634
2635         if (t->mode == m->mode && t->id.proto == m->proto &&
2636             (m->reqid == 0 || t->reqid == m->reqid)) {
2637                 switch (t->mode) {
2638                 case XFRM_MODE_TUNNEL:
2639                 case XFRM_MODE_BEET:
2640                         if (xfrm_addr_cmp(&t->id.daddr, &m->old_daddr,
2641                                           m->old_family) == 0 &&
2642                             xfrm_addr_cmp(&t->saddr, &m->old_saddr,
2643                                           m->old_family) == 0) {
2644                                 match = 1;
2645                         }
2646                         break;
2647                 case XFRM_MODE_TRANSPORT:
2648                         /* in case of transport mode, template does not store
2649                            any IP addresses, hence we just compare mode and
2650                            protocol */
2651                         match = 1;
2652                         break;
2653                 default:
2654                         break;
2655                 }
2656         }
2657         return match;
2658 }
2659
2660 /* update endpoint address(es) of template(s) */
2661 static int xfrm_policy_migrate(struct xfrm_policy *pol,
2662                                struct xfrm_migrate *m, int num_migrate)
2663 {
2664         struct xfrm_migrate *mp;
2665         struct dst_entry *dst;
2666         int i, j, n = 0;
2667
2668         write_lock_bh(&pol->lock);
2669         if (unlikely(pol->walk.dead)) {
2670                 /* target policy has been deleted */
2671                 write_unlock_bh(&pol->lock);
2672                 return -ENOENT;
2673         }
2674
2675         for (i = 0; i < pol->xfrm_nr; i++) {
2676                 for (j = 0, mp = m; j < num_migrate; j++, mp++) {
2677                         if (!migrate_tmpl_match(mp, &pol->xfrm_vec[i]))
2678                                 continue;
2679                         n++;
2680                         if (pol->xfrm_vec[i].mode != XFRM_MODE_TUNNEL &&
2681                             pol->xfrm_vec[i].mode != XFRM_MODE_BEET)
2682                                 continue;
2683                         /* update endpoints */
2684                         memcpy(&pol->xfrm_vec[i].id.daddr, &mp->new_daddr,
2685                                sizeof(pol->xfrm_vec[i].id.daddr));
2686                         memcpy(&pol->xfrm_vec[i].saddr, &mp->new_saddr,
2687                                sizeof(pol->xfrm_vec[i].saddr));
2688                         pol->xfrm_vec[i].encap_family = mp->new_family;
2689                         /* flush bundles */
2690                         while ((dst = pol->bundles) != NULL) {
2691                                 pol->bundles = dst->next;
2692                                 dst_free(dst);
2693                         }
2694                 }
2695         }
2696
2697         write_unlock_bh(&pol->lock);
2698
2699         if (!n)
2700                 return -ENODATA;
2701
2702         return 0;
2703 }
2704
2705 static int xfrm_migrate_check(struct xfrm_migrate *m, int num_migrate)
2706 {
2707         int i, j;
2708
2709         if (num_migrate < 1 || num_migrate > XFRM_MAX_DEPTH)
2710                 return -EINVAL;
2711
2712         for (i = 0; i < num_migrate; i++) {
2713                 if ((xfrm_addr_cmp(&m[i].old_daddr, &m[i].new_daddr,
2714                                    m[i].old_family) == 0) &&
2715                     (xfrm_addr_cmp(&m[i].old_saddr, &m[i].new_saddr,
2716                                    m[i].old_family) == 0))
2717                         return -EINVAL;
2718                 if (xfrm_addr_any(&m[i].new_daddr, m[i].new_family) ||
2719                     xfrm_addr_any(&m[i].new_saddr, m[i].new_family))
2720                         return -EINVAL;
2721
2722                 /* check if there is any duplicated entry */
2723                 for (j = i + 1; j < num_migrate; j++) {
2724                         if (!memcmp(&m[i].old_daddr, &m[j].old_daddr,
2725                                     sizeof(m[i].old_daddr)) &&
2726                             !memcmp(&m[i].old_saddr, &m[j].old_saddr,
2727                                     sizeof(m[i].old_saddr)) &&
2728                             m[i].proto == m[j].proto &&
2729                             m[i].mode == m[j].mode &&
2730                             m[i].reqid == m[j].reqid &&
2731                             m[i].old_family == m[j].old_family)
2732                                 return -EINVAL;
2733                 }
2734         }
2735
2736         return 0;
2737 }
2738
2739 int xfrm_migrate(struct xfrm_selector *sel, u8 dir, u8 type,
2740                  struct xfrm_migrate *m, int num_migrate,
2741                  struct xfrm_kmaddress *k)
2742 {
2743         int i, err, nx_cur = 0, nx_new = 0;
2744         struct xfrm_policy *pol = NULL;
2745         struct xfrm_state *x, *xc;
2746         struct xfrm_state *x_cur[XFRM_MAX_DEPTH];
2747         struct xfrm_state *x_new[XFRM_MAX_DEPTH];
2748         struct xfrm_migrate *mp;
2749
2750         if ((err = xfrm_migrate_check(m, num_migrate)) < 0)
2751                 goto out;
2752
2753         /* Stage 1 - find policy */
2754         if ((pol = xfrm_migrate_policy_find(sel, dir, type)) == NULL) {
2755                 err = -ENOENT;
2756                 goto out;
2757         }
2758
2759         /* Stage 2 - find and update state(s) */
2760         for (i = 0, mp = m; i < num_migrate; i++, mp++) {
2761                 if ((x = xfrm_migrate_state_find(mp))) {
2762                         x_cur[nx_cur] = x;
2763                         nx_cur++;
2764                         if ((xc = xfrm_state_migrate(x, mp))) {
2765                                 x_new[nx_new] = xc;
2766                                 nx_new++;
2767                         } else {
2768                                 err = -ENODATA;
2769                                 goto restore_state;
2770                         }
2771                 }
2772         }
2773
2774         /* Stage 3 - update policy */
2775         if ((err = xfrm_policy_migrate(pol, m, num_migrate)) < 0)
2776                 goto restore_state;
2777
2778         /* Stage 4 - delete old state(s) */
2779         if (nx_cur) {
2780                 xfrm_states_put(x_cur, nx_cur);
2781                 xfrm_states_delete(x_cur, nx_cur);
2782         }
2783
2784         /* Stage 5 - announce */
2785         km_migrate(sel, dir, type, m, num_migrate, k);
2786
2787         xfrm_pol_put(pol);
2788
2789         return 0;
2790 out:
2791         return err;
2792
2793 restore_state:
2794         if (pol)
2795                 xfrm_pol_put(pol);
2796         if (nx_cur)
2797                 xfrm_states_put(x_cur, nx_cur);
2798         if (nx_new)
2799                 xfrm_states_delete(x_new, nx_new);
2800
2801         return err;
2802 }
2803 EXPORT_SYMBOL(xfrm_migrate);
2804 #endif