~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/net/xfrm/xfrm_policy.c

Version: ~ [ linux-5.8-rc4 ] ~ [ linux-5.7.7 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.50 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.131 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.187 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.229 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.229 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.140 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.85 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

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

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp