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