Linux-libre 5.4.49-gnu
[librecmc/linux-libre.git] / net / xfrm / xfrm_policy.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * xfrm_policy.c
4  *
5  * Changes:
6  *      Mitsuru KANDA @USAGI
7  *      Kazunori MIYAZAWA @USAGI
8  *      Kunihiro Ishiguro <kunihiro@ipinfusion.com>
9  *              IPv6 support
10  *      Kazunori MIYAZAWA @USAGI
11  *      YOSHIFUJI Hideaki
12  *              Split up af-specific portion
13  *      Derek Atkins <derek@ihtfp.com>          Add the post_input processor
14  *
15  */
16
17 #include <linux/err.h>
18 #include <linux/slab.h>
19 #include <linux/kmod.h>
20 #include <linux/list.h>
21 #include <linux/spinlock.h>
22 #include <linux/workqueue.h>
23 #include <linux/notifier.h>
24 #include <linux/netdevice.h>
25 #include <linux/netfilter.h>
26 #include <linux/module.h>
27 #include <linux/cache.h>
28 #include <linux/cpu.h>
29 #include <linux/audit.h>
30 #include <linux/rhashtable.h>
31 #include <linux/if_tunnel.h>
32 #include <net/dst.h>
33 #include <net/flow.h>
34 #include <net/xfrm.h>
35 #include <net/ip.h>
36 #if IS_ENABLED(CONFIG_IPV6_MIP6)
37 #include <net/mip6.h>
38 #endif
39 #ifdef CONFIG_XFRM_STATISTICS
40 #include <net/snmp.h>
41 #endif
42
43 #include "xfrm_hash.h"
44
45 #define XFRM_QUEUE_TMO_MIN ((unsigned)(HZ/10))
46 #define XFRM_QUEUE_TMO_MAX ((unsigned)(60*HZ))
47 #define XFRM_MAX_QUEUE_LEN      100
48
49 struct xfrm_flo {
50         struct dst_entry *dst_orig;
51         u8 flags;
52 };
53
54 /* prefixes smaller than this are stored in lists, not trees. */
55 #define INEXACT_PREFIXLEN_IPV4  16
56 #define INEXACT_PREFIXLEN_IPV6  48
57
58 struct xfrm_pol_inexact_node {
59         struct rb_node node;
60         union {
61                 xfrm_address_t addr;
62                 struct rcu_head rcu;
63         };
64         u8 prefixlen;
65
66         struct rb_root root;
67
68         /* the policies matching this node, can be empty list */
69         struct hlist_head hhead;
70 };
71
72 /* xfrm inexact policy search tree:
73  * xfrm_pol_inexact_bin = hash(dir,type,family,if_id);
74  *  |
75  * +---- root_d: sorted by daddr:prefix
76  * |                 |
77  * |        xfrm_pol_inexact_node
78  * |                 |
79  * |                 +- root: sorted by saddr/prefix
80  * |                 |              |
81  * |                 |         xfrm_pol_inexact_node
82  * |                 |              |
83  * |                 |              + root: unused
84  * |                 |              |
85  * |                 |              + hhead: saddr:daddr policies
86  * |                 |
87  * |                 +- coarse policies and all any:daddr policies
88  * |
89  * +---- root_s: sorted by saddr:prefix
90  * |                 |
91  * |        xfrm_pol_inexact_node
92  * |                 |
93  * |                 + root: unused
94  * |                 |
95  * |                 + hhead: saddr:any policies
96  * |
97  * +---- coarse policies and all any:any policies
98  *
99  * Lookups return four candidate lists:
100  * 1. any:any list from top-level xfrm_pol_inexact_bin
101  * 2. any:daddr list from daddr tree
102  * 3. saddr:daddr list from 2nd level daddr tree
103  * 4. saddr:any list from saddr tree
104  *
105  * This result set then needs to be searched for the policy with
106  * the lowest priority.  If two results have same prio, youngest one wins.
107  */
108
109 struct xfrm_pol_inexact_key {
110         possible_net_t net;
111         u32 if_id;
112         u16 family;
113         u8 dir, type;
114 };
115
116 struct xfrm_pol_inexact_bin {
117         struct xfrm_pol_inexact_key k;
118         struct rhash_head head;
119         /* list containing '*:*' policies */
120         struct hlist_head hhead;
121
122         seqcount_t count;
123         /* tree sorted by daddr/prefix */
124         struct rb_root root_d;
125
126         /* tree sorted by saddr/prefix */
127         struct rb_root root_s;
128
129         /* slow path below */
130         struct list_head inexact_bins;
131         struct rcu_head rcu;
132 };
133
134 enum xfrm_pol_inexact_candidate_type {
135         XFRM_POL_CAND_BOTH,
136         XFRM_POL_CAND_SADDR,
137         XFRM_POL_CAND_DADDR,
138         XFRM_POL_CAND_ANY,
139
140         XFRM_POL_CAND_MAX,
141 };
142
143 struct xfrm_pol_inexact_candidates {
144         struct hlist_head *res[XFRM_POL_CAND_MAX];
145 };
146
147 static DEFINE_SPINLOCK(xfrm_if_cb_lock);
148 static struct xfrm_if_cb const __rcu *xfrm_if_cb __read_mostly;
149
150 static DEFINE_SPINLOCK(xfrm_policy_afinfo_lock);
151 static struct xfrm_policy_afinfo const __rcu *xfrm_policy_afinfo[AF_INET6 + 1]
152                                                 __read_mostly;
153
154 static struct kmem_cache *xfrm_dst_cache __ro_after_init;
155 static __read_mostly seqcount_t xfrm_policy_hash_generation;
156
157 static struct rhashtable xfrm_policy_inexact_table;
158 static const struct rhashtable_params xfrm_pol_inexact_params;
159
160 static void xfrm_init_pmtu(struct xfrm_dst **bundle, int nr);
161 static int stale_bundle(struct dst_entry *dst);
162 static int xfrm_bundle_ok(struct xfrm_dst *xdst);
163 static void xfrm_policy_queue_process(struct timer_list *t);
164
165 static void __xfrm_policy_link(struct xfrm_policy *pol, int dir);
166 static struct xfrm_policy *__xfrm_policy_unlink(struct xfrm_policy *pol,
167                                                 int dir);
168
169 static struct xfrm_pol_inexact_bin *
170 xfrm_policy_inexact_lookup(struct net *net, u8 type, u16 family, u8 dir,
171                            u32 if_id);
172
173 static struct xfrm_pol_inexact_bin *
174 xfrm_policy_inexact_lookup_rcu(struct net *net,
175                                u8 type, u16 family, u8 dir, u32 if_id);
176 static struct xfrm_policy *
177 xfrm_policy_insert_list(struct hlist_head *chain, struct xfrm_policy *policy,
178                         bool excl);
179 static void xfrm_policy_insert_inexact_list(struct hlist_head *chain,
180                                             struct xfrm_policy *policy);
181
182 static bool
183 xfrm_policy_find_inexact_candidates(struct xfrm_pol_inexact_candidates *cand,
184                                     struct xfrm_pol_inexact_bin *b,
185                                     const xfrm_address_t *saddr,
186                                     const xfrm_address_t *daddr);
187
188 static inline bool xfrm_pol_hold_rcu(struct xfrm_policy *policy)
189 {
190         return refcount_inc_not_zero(&policy->refcnt);
191 }
192
193 static inline bool
194 __xfrm4_selector_match(const struct xfrm_selector *sel, const struct flowi *fl)
195 {
196         const struct flowi4 *fl4 = &fl->u.ip4;
197
198         return  addr4_match(fl4->daddr, sel->daddr.a4, sel->prefixlen_d) &&
199                 addr4_match(fl4->saddr, sel->saddr.a4, sel->prefixlen_s) &&
200                 !((xfrm_flowi_dport(fl, &fl4->uli) ^ sel->dport) & sel->dport_mask) &&
201                 !((xfrm_flowi_sport(fl, &fl4->uli) ^ sel->sport) & sel->sport_mask) &&
202                 (fl4->flowi4_proto == sel->proto || !sel->proto) &&
203                 (fl4->flowi4_oif == sel->ifindex || !sel->ifindex);
204 }
205
206 static inline bool
207 __xfrm6_selector_match(const struct xfrm_selector *sel, const struct flowi *fl)
208 {
209         const struct flowi6 *fl6 = &fl->u.ip6;
210
211         return  addr_match(&fl6->daddr, &sel->daddr, sel->prefixlen_d) &&
212                 addr_match(&fl6->saddr, &sel->saddr, sel->prefixlen_s) &&
213                 !((xfrm_flowi_dport(fl, &fl6->uli) ^ sel->dport) & sel->dport_mask) &&
214                 !((xfrm_flowi_sport(fl, &fl6->uli) ^ sel->sport) & sel->sport_mask) &&
215                 (fl6->flowi6_proto == sel->proto || !sel->proto) &&
216                 (fl6->flowi6_oif == sel->ifindex || !sel->ifindex);
217 }
218
219 bool xfrm_selector_match(const struct xfrm_selector *sel, const struct flowi *fl,
220                          unsigned short family)
221 {
222         switch (family) {
223         case AF_INET:
224                 return __xfrm4_selector_match(sel, fl);
225         case AF_INET6:
226                 return __xfrm6_selector_match(sel, fl);
227         }
228         return false;
229 }
230
231 static const struct xfrm_policy_afinfo *xfrm_policy_get_afinfo(unsigned short family)
232 {
233         const struct xfrm_policy_afinfo *afinfo;
234
235         if (unlikely(family >= ARRAY_SIZE(xfrm_policy_afinfo)))
236                 return NULL;
237         rcu_read_lock();
238         afinfo = rcu_dereference(xfrm_policy_afinfo[family]);
239         if (unlikely(!afinfo))
240                 rcu_read_unlock();
241         return afinfo;
242 }
243
244 /* Called with rcu_read_lock(). */
245 static const struct xfrm_if_cb *xfrm_if_get_cb(void)
246 {
247         return rcu_dereference(xfrm_if_cb);
248 }
249
250 struct dst_entry *__xfrm_dst_lookup(struct net *net, int tos, int oif,
251                                     const xfrm_address_t *saddr,
252                                     const xfrm_address_t *daddr,
253                                     int family, u32 mark)
254 {
255         const struct xfrm_policy_afinfo *afinfo;
256         struct dst_entry *dst;
257
258         afinfo = xfrm_policy_get_afinfo(family);
259         if (unlikely(afinfo == NULL))
260                 return ERR_PTR(-EAFNOSUPPORT);
261
262         dst = afinfo->dst_lookup(net, tos, oif, saddr, daddr, mark);
263
264         rcu_read_unlock();
265
266         return dst;
267 }
268 EXPORT_SYMBOL(__xfrm_dst_lookup);
269
270 static inline struct dst_entry *xfrm_dst_lookup(struct xfrm_state *x,
271                                                 int tos, int oif,
272                                                 xfrm_address_t *prev_saddr,
273                                                 xfrm_address_t *prev_daddr,
274                                                 int family, u32 mark)
275 {
276         struct net *net = xs_net(x);
277         xfrm_address_t *saddr = &x->props.saddr;
278         xfrm_address_t *daddr = &x->id.daddr;
279         struct dst_entry *dst;
280
281         if (x->type->flags & XFRM_TYPE_LOCAL_COADDR) {
282                 saddr = x->coaddr;
283                 daddr = prev_daddr;
284         }
285         if (x->type->flags & XFRM_TYPE_REMOTE_COADDR) {
286                 saddr = prev_saddr;
287                 daddr = x->coaddr;
288         }
289
290         dst = __xfrm_dst_lookup(net, tos, oif, saddr, daddr, family, mark);
291
292         if (!IS_ERR(dst)) {
293                 if (prev_saddr != saddr)
294                         memcpy(prev_saddr, saddr,  sizeof(*prev_saddr));
295                 if (prev_daddr != daddr)
296                         memcpy(prev_daddr, daddr,  sizeof(*prev_daddr));
297         }
298
299         return dst;
300 }
301
302 static inline unsigned long make_jiffies(long secs)
303 {
304         if (secs >= (MAX_SCHEDULE_TIMEOUT-1)/HZ)
305                 return MAX_SCHEDULE_TIMEOUT-1;
306         else
307                 return secs*HZ;
308 }
309
310 static void xfrm_policy_timer(struct timer_list *t)
311 {
312         struct xfrm_policy *xp = from_timer(xp, t, timer);
313         time64_t now = ktime_get_real_seconds();
314         time64_t next = TIME64_MAX;
315         int warn = 0;
316         int dir;
317
318         read_lock(&xp->lock);
319
320         if (unlikely(xp->walk.dead))
321                 goto out;
322
323         dir = xfrm_policy_id2dir(xp->index);
324
325         if (xp->lft.hard_add_expires_seconds) {
326                 time64_t tmo = xp->lft.hard_add_expires_seconds +
327                         xp->curlft.add_time - now;
328                 if (tmo <= 0)
329                         goto expired;
330                 if (tmo < next)
331                         next = tmo;
332         }
333         if (xp->lft.hard_use_expires_seconds) {
334                 time64_t tmo = xp->lft.hard_use_expires_seconds +
335                         (xp->curlft.use_time ? : xp->curlft.add_time) - now;
336                 if (tmo <= 0)
337                         goto expired;
338                 if (tmo < next)
339                         next = tmo;
340         }
341         if (xp->lft.soft_add_expires_seconds) {
342                 time64_t tmo = xp->lft.soft_add_expires_seconds +
343                         xp->curlft.add_time - now;
344                 if (tmo <= 0) {
345                         warn = 1;
346                         tmo = XFRM_KM_TIMEOUT;
347                 }
348                 if (tmo < next)
349                         next = tmo;
350         }
351         if (xp->lft.soft_use_expires_seconds) {
352                 time64_t tmo = xp->lft.soft_use_expires_seconds +
353                         (xp->curlft.use_time ? : xp->curlft.add_time) - now;
354                 if (tmo <= 0) {
355                         warn = 1;
356                         tmo = XFRM_KM_TIMEOUT;
357                 }
358                 if (tmo < next)
359                         next = tmo;
360         }
361
362         if (warn)
363                 km_policy_expired(xp, dir, 0, 0);
364         if (next != TIME64_MAX &&
365             !mod_timer(&xp->timer, jiffies + make_jiffies(next)))
366                 xfrm_pol_hold(xp);
367
368 out:
369         read_unlock(&xp->lock);
370         xfrm_pol_put(xp);
371         return;
372
373 expired:
374         read_unlock(&xp->lock);
375         if (!xfrm_policy_delete(xp, dir))
376                 km_policy_expired(xp, dir, 1, 0);
377         xfrm_pol_put(xp);
378 }
379
380 /* Allocate xfrm_policy. Not used here, it is supposed to be used by pfkeyv2
381  * SPD calls.
382  */
383
384 struct xfrm_policy *xfrm_policy_alloc(struct net *net, gfp_t gfp)
385 {
386         struct xfrm_policy *policy;
387
388         policy = kzalloc(sizeof(struct xfrm_policy), gfp);
389
390         if (policy) {
391                 write_pnet(&policy->xp_net, net);
392                 INIT_LIST_HEAD(&policy->walk.all);
393                 INIT_HLIST_NODE(&policy->bydst_inexact_list);
394                 INIT_HLIST_NODE(&policy->bydst);
395                 INIT_HLIST_NODE(&policy->byidx);
396                 rwlock_init(&policy->lock);
397                 refcount_set(&policy->refcnt, 1);
398                 skb_queue_head_init(&policy->polq.hold_queue);
399                 timer_setup(&policy->timer, xfrm_policy_timer, 0);
400                 timer_setup(&policy->polq.hold_timer,
401                             xfrm_policy_queue_process, 0);
402         }
403         return policy;
404 }
405 EXPORT_SYMBOL(xfrm_policy_alloc);
406
407 static void xfrm_policy_destroy_rcu(struct rcu_head *head)
408 {
409         struct xfrm_policy *policy = container_of(head, struct xfrm_policy, rcu);
410
411         security_xfrm_policy_free(policy->security);
412         kfree(policy);
413 }
414
415 /* Destroy xfrm_policy: descendant resources must be released to this moment. */
416
417 void xfrm_policy_destroy(struct xfrm_policy *policy)
418 {
419         BUG_ON(!policy->walk.dead);
420
421         if (del_timer(&policy->timer) || del_timer(&policy->polq.hold_timer))
422                 BUG();
423
424         call_rcu(&policy->rcu, xfrm_policy_destroy_rcu);
425 }
426 EXPORT_SYMBOL(xfrm_policy_destroy);
427
428 /* Rule must be locked. Release descendant resources, announce
429  * entry dead. The rule must be unlinked from lists to the moment.
430  */
431
432 static void xfrm_policy_kill(struct xfrm_policy *policy)
433 {
434         write_lock_bh(&policy->lock);
435         policy->walk.dead = 1;
436         write_unlock_bh(&policy->lock);
437
438         atomic_inc(&policy->genid);
439
440         if (del_timer(&policy->polq.hold_timer))
441                 xfrm_pol_put(policy);
442         skb_queue_purge(&policy->polq.hold_queue);
443
444         if (del_timer(&policy->timer))
445                 xfrm_pol_put(policy);
446
447         xfrm_pol_put(policy);
448 }
449
450 static unsigned int xfrm_policy_hashmax __read_mostly = 1 * 1024 * 1024;
451
452 static inline unsigned int idx_hash(struct net *net, u32 index)
453 {
454         return __idx_hash(index, net->xfrm.policy_idx_hmask);
455 }
456
457 /* calculate policy hash thresholds */
458 static void __get_hash_thresh(struct net *net,
459                               unsigned short family, int dir,
460                               u8 *dbits, u8 *sbits)
461 {
462         switch (family) {
463         case AF_INET:
464                 *dbits = net->xfrm.policy_bydst[dir].dbits4;
465                 *sbits = net->xfrm.policy_bydst[dir].sbits4;
466                 break;
467
468         case AF_INET6:
469                 *dbits = net->xfrm.policy_bydst[dir].dbits6;
470                 *sbits = net->xfrm.policy_bydst[dir].sbits6;
471                 break;
472
473         default:
474                 *dbits = 0;
475                 *sbits = 0;
476         }
477 }
478
479 static struct hlist_head *policy_hash_bysel(struct net *net,
480                                             const struct xfrm_selector *sel,
481                                             unsigned short family, int dir)
482 {
483         unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
484         unsigned int hash;
485         u8 dbits;
486         u8 sbits;
487
488         __get_hash_thresh(net, family, dir, &dbits, &sbits);
489         hash = __sel_hash(sel, family, hmask, dbits, sbits);
490
491         if (hash == hmask + 1)
492                 return NULL;
493
494         return rcu_dereference_check(net->xfrm.policy_bydst[dir].table,
495                      lockdep_is_held(&net->xfrm.xfrm_policy_lock)) + hash;
496 }
497
498 static struct hlist_head *policy_hash_direct(struct net *net,
499                                              const xfrm_address_t *daddr,
500                                              const xfrm_address_t *saddr,
501                                              unsigned short family, int dir)
502 {
503         unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
504         unsigned int hash;
505         u8 dbits;
506         u8 sbits;
507
508         __get_hash_thresh(net, family, dir, &dbits, &sbits);
509         hash = __addr_hash(daddr, saddr, family, hmask, dbits, sbits);
510
511         return rcu_dereference_check(net->xfrm.policy_bydst[dir].table,
512                      lockdep_is_held(&net->xfrm.xfrm_policy_lock)) + hash;
513 }
514
515 static void xfrm_dst_hash_transfer(struct net *net,
516                                    struct hlist_head *list,
517                                    struct hlist_head *ndsttable,
518                                    unsigned int nhashmask,
519                                    int dir)
520 {
521         struct hlist_node *tmp, *entry0 = NULL;
522         struct xfrm_policy *pol;
523         unsigned int h0 = 0;
524         u8 dbits;
525         u8 sbits;
526
527 redo:
528         hlist_for_each_entry_safe(pol, tmp, list, bydst) {
529                 unsigned int h;
530
531                 __get_hash_thresh(net, pol->family, dir, &dbits, &sbits);
532                 h = __addr_hash(&pol->selector.daddr, &pol->selector.saddr,
533                                 pol->family, nhashmask, dbits, sbits);
534                 if (!entry0) {
535                         hlist_del_rcu(&pol->bydst);
536                         hlist_add_head_rcu(&pol->bydst, ndsttable + h);
537                         h0 = h;
538                 } else {
539                         if (h != h0)
540                                 continue;
541                         hlist_del_rcu(&pol->bydst);
542                         hlist_add_behind_rcu(&pol->bydst, entry0);
543                 }
544                 entry0 = &pol->bydst;
545         }
546         if (!hlist_empty(list)) {
547                 entry0 = NULL;
548                 goto redo;
549         }
550 }
551
552 static void xfrm_idx_hash_transfer(struct hlist_head *list,
553                                    struct hlist_head *nidxtable,
554                                    unsigned int nhashmask)
555 {
556         struct hlist_node *tmp;
557         struct xfrm_policy *pol;
558
559         hlist_for_each_entry_safe(pol, tmp, list, byidx) {
560                 unsigned int h;
561
562                 h = __idx_hash(pol->index, nhashmask);
563                 hlist_add_head(&pol->byidx, nidxtable+h);
564         }
565 }
566
567 static unsigned long xfrm_new_hash_mask(unsigned int old_hmask)
568 {
569         return ((old_hmask + 1) << 1) - 1;
570 }
571
572 static void xfrm_bydst_resize(struct net *net, int dir)
573 {
574         unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
575         unsigned int nhashmask = xfrm_new_hash_mask(hmask);
576         unsigned int nsize = (nhashmask + 1) * sizeof(struct hlist_head);
577         struct hlist_head *ndst = xfrm_hash_alloc(nsize);
578         struct hlist_head *odst;
579         int i;
580
581         if (!ndst)
582                 return;
583
584         spin_lock_bh(&net->xfrm.xfrm_policy_lock);
585         write_seqcount_begin(&xfrm_policy_hash_generation);
586
587         odst = rcu_dereference_protected(net->xfrm.policy_bydst[dir].table,
588                                 lockdep_is_held(&net->xfrm.xfrm_policy_lock));
589
590         for (i = hmask; i >= 0; i--)
591                 xfrm_dst_hash_transfer(net, odst + i, ndst, nhashmask, dir);
592
593         rcu_assign_pointer(net->xfrm.policy_bydst[dir].table, ndst);
594         net->xfrm.policy_bydst[dir].hmask = nhashmask;
595
596         write_seqcount_end(&xfrm_policy_hash_generation);
597         spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
598
599         synchronize_rcu();
600
601         xfrm_hash_free(odst, (hmask + 1) * sizeof(struct hlist_head));
602 }
603
604 static void xfrm_byidx_resize(struct net *net, int total)
605 {
606         unsigned int hmask = net->xfrm.policy_idx_hmask;
607         unsigned int nhashmask = xfrm_new_hash_mask(hmask);
608         unsigned int nsize = (nhashmask + 1) * sizeof(struct hlist_head);
609         struct hlist_head *oidx = net->xfrm.policy_byidx;
610         struct hlist_head *nidx = xfrm_hash_alloc(nsize);
611         int i;
612
613         if (!nidx)
614                 return;
615
616         spin_lock_bh(&net->xfrm.xfrm_policy_lock);
617
618         for (i = hmask; i >= 0; i--)
619                 xfrm_idx_hash_transfer(oidx + i, nidx, nhashmask);
620
621         net->xfrm.policy_byidx = nidx;
622         net->xfrm.policy_idx_hmask = nhashmask;
623
624         spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
625
626         xfrm_hash_free(oidx, (hmask + 1) * sizeof(struct hlist_head));
627 }
628
629 static inline int xfrm_bydst_should_resize(struct net *net, int dir, int *total)
630 {
631         unsigned int cnt = net->xfrm.policy_count[dir];
632         unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
633
634         if (total)
635                 *total += cnt;
636
637         if ((hmask + 1) < xfrm_policy_hashmax &&
638             cnt > hmask)
639                 return 1;
640
641         return 0;
642 }
643
644 static inline int xfrm_byidx_should_resize(struct net *net, int total)
645 {
646         unsigned int hmask = net->xfrm.policy_idx_hmask;
647
648         if ((hmask + 1) < xfrm_policy_hashmax &&
649             total > hmask)
650                 return 1;
651
652         return 0;
653 }
654
655 void xfrm_spd_getinfo(struct net *net, struct xfrmk_spdinfo *si)
656 {
657         si->incnt = net->xfrm.policy_count[XFRM_POLICY_IN];
658         si->outcnt = net->xfrm.policy_count[XFRM_POLICY_OUT];
659         si->fwdcnt = net->xfrm.policy_count[XFRM_POLICY_FWD];
660         si->inscnt = net->xfrm.policy_count[XFRM_POLICY_IN+XFRM_POLICY_MAX];
661         si->outscnt = net->xfrm.policy_count[XFRM_POLICY_OUT+XFRM_POLICY_MAX];
662         si->fwdscnt = net->xfrm.policy_count[XFRM_POLICY_FWD+XFRM_POLICY_MAX];
663         si->spdhcnt = net->xfrm.policy_idx_hmask;
664         si->spdhmcnt = xfrm_policy_hashmax;
665 }
666 EXPORT_SYMBOL(xfrm_spd_getinfo);
667
668 static DEFINE_MUTEX(hash_resize_mutex);
669 static void xfrm_hash_resize(struct work_struct *work)
670 {
671         struct net *net = container_of(work, struct net, xfrm.policy_hash_work);
672         int dir, total;
673
674         mutex_lock(&hash_resize_mutex);
675
676         total = 0;
677         for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
678                 if (xfrm_bydst_should_resize(net, dir, &total))
679                         xfrm_bydst_resize(net, dir);
680         }
681         if (xfrm_byidx_should_resize(net, total))
682                 xfrm_byidx_resize(net, total);
683
684         mutex_unlock(&hash_resize_mutex);
685 }
686
687 /* Make sure *pol can be inserted into fastbin.
688  * Useful to check that later insert requests will be sucessful
689  * (provided xfrm_policy_lock is held throughout).
690  */
691 static struct xfrm_pol_inexact_bin *
692 xfrm_policy_inexact_alloc_bin(const struct xfrm_policy *pol, u8 dir)
693 {
694         struct xfrm_pol_inexact_bin *bin, *prev;
695         struct xfrm_pol_inexact_key k = {
696                 .family = pol->family,
697                 .type = pol->type,
698                 .dir = dir,
699                 .if_id = pol->if_id,
700         };
701         struct net *net = xp_net(pol);
702
703         lockdep_assert_held(&net->xfrm.xfrm_policy_lock);
704
705         write_pnet(&k.net, net);
706         bin = rhashtable_lookup_fast(&xfrm_policy_inexact_table, &k,
707                                      xfrm_pol_inexact_params);
708         if (bin)
709                 return bin;
710
711         bin = kzalloc(sizeof(*bin), GFP_ATOMIC);
712         if (!bin)
713                 return NULL;
714
715         bin->k = k;
716         INIT_HLIST_HEAD(&bin->hhead);
717         bin->root_d = RB_ROOT;
718         bin->root_s = RB_ROOT;
719         seqcount_init(&bin->count);
720
721         prev = rhashtable_lookup_get_insert_key(&xfrm_policy_inexact_table,
722                                                 &bin->k, &bin->head,
723                                                 xfrm_pol_inexact_params);
724         if (!prev) {
725                 list_add(&bin->inexact_bins, &net->xfrm.inexact_bins);
726                 return bin;
727         }
728
729         kfree(bin);
730
731         return IS_ERR(prev) ? NULL : prev;
732 }
733
734 static bool xfrm_pol_inexact_addr_use_any_list(const xfrm_address_t *addr,
735                                                int family, u8 prefixlen)
736 {
737         if (xfrm_addr_any(addr, family))
738                 return true;
739
740         if (family == AF_INET6 && prefixlen < INEXACT_PREFIXLEN_IPV6)
741                 return true;
742
743         if (family == AF_INET && prefixlen < INEXACT_PREFIXLEN_IPV4)
744                 return true;
745
746         return false;
747 }
748
749 static bool
750 xfrm_policy_inexact_insert_use_any_list(const struct xfrm_policy *policy)
751 {
752         const xfrm_address_t *addr;
753         bool saddr_any, daddr_any;
754         u8 prefixlen;
755
756         addr = &policy->selector.saddr;
757         prefixlen = policy->selector.prefixlen_s;
758
759         saddr_any = xfrm_pol_inexact_addr_use_any_list(addr,
760                                                        policy->family,
761                                                        prefixlen);
762         addr = &policy->selector.daddr;
763         prefixlen = policy->selector.prefixlen_d;
764         daddr_any = xfrm_pol_inexact_addr_use_any_list(addr,
765                                                        policy->family,
766                                                        prefixlen);
767         return saddr_any && daddr_any;
768 }
769
770 static void xfrm_pol_inexact_node_init(struct xfrm_pol_inexact_node *node,
771                                        const xfrm_address_t *addr, u8 prefixlen)
772 {
773         node->addr = *addr;
774         node->prefixlen = prefixlen;
775 }
776
777 static struct xfrm_pol_inexact_node *
778 xfrm_pol_inexact_node_alloc(const xfrm_address_t *addr, u8 prefixlen)
779 {
780         struct xfrm_pol_inexact_node *node;
781
782         node = kzalloc(sizeof(*node), GFP_ATOMIC);
783         if (node)
784                 xfrm_pol_inexact_node_init(node, addr, prefixlen);
785
786         return node;
787 }
788
789 static int xfrm_policy_addr_delta(const xfrm_address_t *a,
790                                   const xfrm_address_t *b,
791                                   u8 prefixlen, u16 family)
792 {
793         unsigned int pdw, pbi;
794         int delta = 0;
795
796         switch (family) {
797         case AF_INET:
798                 if (sizeof(long) == 4 && prefixlen == 0)
799                         return ntohl(a->a4) - ntohl(b->a4);
800                 return (ntohl(a->a4) & ((~0UL << (32 - prefixlen)))) -
801                        (ntohl(b->a4) & ((~0UL << (32 - prefixlen))));
802         case AF_INET6:
803                 pdw = prefixlen >> 5;
804                 pbi = prefixlen & 0x1f;
805
806                 if (pdw) {
807                         delta = memcmp(a->a6, b->a6, pdw << 2);
808                         if (delta)
809                                 return delta;
810                 }
811                 if (pbi) {
812                         u32 mask = ~0u << (32 - pbi);
813
814                         delta = (ntohl(a->a6[pdw]) & mask) -
815                                 (ntohl(b->a6[pdw]) & mask);
816                 }
817                 break;
818         default:
819                 break;
820         }
821
822         return delta;
823 }
824
825 static void xfrm_policy_inexact_list_reinsert(struct net *net,
826                                               struct xfrm_pol_inexact_node *n,
827                                               u16 family)
828 {
829         unsigned int matched_s, matched_d;
830         struct xfrm_policy *policy, *p;
831
832         matched_s = 0;
833         matched_d = 0;
834
835         list_for_each_entry_reverse(policy, &net->xfrm.policy_all, walk.all) {
836                 struct hlist_node *newpos = NULL;
837                 bool matches_s, matches_d;
838
839                 if (!policy->bydst_reinsert)
840                         continue;
841
842                 WARN_ON_ONCE(policy->family != family);
843
844                 policy->bydst_reinsert = false;
845                 hlist_for_each_entry(p, &n->hhead, bydst) {
846                         if (policy->priority > p->priority)
847                                 newpos = &p->bydst;
848                         else if (policy->priority == p->priority &&
849                                  policy->pos > p->pos)
850                                 newpos = &p->bydst;
851                         else
852                                 break;
853                 }
854
855                 if (newpos)
856                         hlist_add_behind_rcu(&policy->bydst, newpos);
857                 else
858                         hlist_add_head_rcu(&policy->bydst, &n->hhead);
859
860                 /* paranoia checks follow.
861                  * Check that the reinserted policy matches at least
862                  * saddr or daddr for current node prefix.
863                  *
864                  * Matching both is fine, matching saddr in one policy
865                  * (but not daddr) and then matching only daddr in another
866                  * is a bug.
867                  */
868                 matches_s = xfrm_policy_addr_delta(&policy->selector.saddr,
869                                                    &n->addr,
870                                                    n->prefixlen,
871                                                    family) == 0;
872                 matches_d = xfrm_policy_addr_delta(&policy->selector.daddr,
873                                                    &n->addr,
874                                                    n->prefixlen,
875                                                    family) == 0;
876                 if (matches_s && matches_d)
877                         continue;
878
879                 WARN_ON_ONCE(!matches_s && !matches_d);
880                 if (matches_s)
881                         matched_s++;
882                 if (matches_d)
883                         matched_d++;
884                 WARN_ON_ONCE(matched_s && matched_d);
885         }
886 }
887
888 static void xfrm_policy_inexact_node_reinsert(struct net *net,
889                                               struct xfrm_pol_inexact_node *n,
890                                               struct rb_root *new,
891                                               u16 family)
892 {
893         struct xfrm_pol_inexact_node *node;
894         struct rb_node **p, *parent;
895
896         /* we should not have another subtree here */
897         WARN_ON_ONCE(!RB_EMPTY_ROOT(&n->root));
898 restart:
899         parent = NULL;
900         p = &new->rb_node;
901         while (*p) {
902                 u8 prefixlen;
903                 int delta;
904
905                 parent = *p;
906                 node = rb_entry(*p, struct xfrm_pol_inexact_node, node);
907
908                 prefixlen = min(node->prefixlen, n->prefixlen);
909
910                 delta = xfrm_policy_addr_delta(&n->addr, &node->addr,
911                                                prefixlen, family);
912                 if (delta < 0) {
913                         p = &parent->rb_left;
914                 } else if (delta > 0) {
915                         p = &parent->rb_right;
916                 } else {
917                         bool same_prefixlen = node->prefixlen == n->prefixlen;
918                         struct xfrm_policy *tmp;
919
920                         hlist_for_each_entry(tmp, &n->hhead, bydst) {
921                                 tmp->bydst_reinsert = true;
922                                 hlist_del_rcu(&tmp->bydst);
923                         }
924
925                         node->prefixlen = prefixlen;
926
927                         xfrm_policy_inexact_list_reinsert(net, node, family);
928
929                         if (same_prefixlen) {
930                                 kfree_rcu(n, rcu);
931                                 return;
932                         }
933
934                         rb_erase(*p, new);
935                         kfree_rcu(n, rcu);
936                         n = node;
937                         goto restart;
938                 }
939         }
940
941         rb_link_node_rcu(&n->node, parent, p);
942         rb_insert_color(&n->node, new);
943 }
944
945 /* merge nodes v and n */
946 static void xfrm_policy_inexact_node_merge(struct net *net,
947                                            struct xfrm_pol_inexact_node *v,
948                                            struct xfrm_pol_inexact_node *n,
949                                            u16 family)
950 {
951         struct xfrm_pol_inexact_node *node;
952         struct xfrm_policy *tmp;
953         struct rb_node *rnode;
954
955         /* To-be-merged node v has a subtree.
956          *
957          * Dismantle it and insert its nodes to n->root.
958          */
959         while ((rnode = rb_first(&v->root)) != NULL) {
960                 node = rb_entry(rnode, struct xfrm_pol_inexact_node, node);
961                 rb_erase(&node->node, &v->root);
962                 xfrm_policy_inexact_node_reinsert(net, node, &n->root,
963                                                   family);
964         }
965
966         hlist_for_each_entry(tmp, &v->hhead, bydst) {
967                 tmp->bydst_reinsert = true;
968                 hlist_del_rcu(&tmp->bydst);
969         }
970
971         xfrm_policy_inexact_list_reinsert(net, n, family);
972 }
973
974 static struct xfrm_pol_inexact_node *
975 xfrm_policy_inexact_insert_node(struct net *net,
976                                 struct rb_root *root,
977                                 xfrm_address_t *addr,
978                                 u16 family, u8 prefixlen, u8 dir)
979 {
980         struct xfrm_pol_inexact_node *cached = NULL;
981         struct rb_node **p, *parent = NULL;
982         struct xfrm_pol_inexact_node *node;
983
984         p = &root->rb_node;
985         while (*p) {
986                 int delta;
987
988                 parent = *p;
989                 node = rb_entry(*p, struct xfrm_pol_inexact_node, node);
990
991                 delta = xfrm_policy_addr_delta(addr, &node->addr,
992                                                node->prefixlen,
993                                                family);
994                 if (delta == 0 && prefixlen >= node->prefixlen) {
995                         WARN_ON_ONCE(cached); /* ipsec policies got lost */
996                         return node;
997                 }
998
999                 if (delta < 0)
1000                         p = &parent->rb_left;
1001                 else
1002                         p = &parent->rb_right;
1003
1004                 if (prefixlen < node->prefixlen) {
1005                         delta = xfrm_policy_addr_delta(addr, &node->addr,
1006                                                        prefixlen,
1007                                                        family);
1008                         if (delta)
1009                                 continue;
1010
1011                         /* This node is a subnet of the new prefix. It needs
1012                          * to be removed and re-inserted with the smaller
1013                          * prefix and all nodes that are now also covered
1014                          * by the reduced prefixlen.
1015                          */
1016                         rb_erase(&node->node, root);
1017
1018                         if (!cached) {
1019                                 xfrm_pol_inexact_node_init(node, addr,
1020                                                            prefixlen);
1021                                 cached = node;
1022                         } else {
1023                                 /* This node also falls within the new
1024                                  * prefixlen. Merge the to-be-reinserted
1025                                  * node and this one.
1026                                  */
1027                                 xfrm_policy_inexact_node_merge(net, node,
1028                                                                cached, family);
1029                                 kfree_rcu(node, rcu);
1030                         }
1031
1032                         /* restart */
1033                         p = &root->rb_node;
1034                         parent = NULL;
1035                 }
1036         }
1037
1038         node = cached;
1039         if (!node) {
1040                 node = xfrm_pol_inexact_node_alloc(addr, prefixlen);
1041                 if (!node)
1042                         return NULL;
1043         }
1044
1045         rb_link_node_rcu(&node->node, parent, p);
1046         rb_insert_color(&node->node, root);
1047
1048         return node;
1049 }
1050
1051 static void xfrm_policy_inexact_gc_tree(struct rb_root *r, bool rm)
1052 {
1053         struct xfrm_pol_inexact_node *node;
1054         struct rb_node *rn = rb_first(r);
1055
1056         while (rn) {
1057                 node = rb_entry(rn, struct xfrm_pol_inexact_node, node);
1058
1059                 xfrm_policy_inexact_gc_tree(&node->root, rm);
1060                 rn = rb_next(rn);
1061
1062                 if (!hlist_empty(&node->hhead) || !RB_EMPTY_ROOT(&node->root)) {
1063                         WARN_ON_ONCE(rm);
1064                         continue;
1065                 }
1066
1067                 rb_erase(&node->node, r);
1068                 kfree_rcu(node, rcu);
1069         }
1070 }
1071
1072 static void __xfrm_policy_inexact_prune_bin(struct xfrm_pol_inexact_bin *b, bool net_exit)
1073 {
1074         write_seqcount_begin(&b->count);
1075         xfrm_policy_inexact_gc_tree(&b->root_d, net_exit);
1076         xfrm_policy_inexact_gc_tree(&b->root_s, net_exit);
1077         write_seqcount_end(&b->count);
1078
1079         if (!RB_EMPTY_ROOT(&b->root_d) || !RB_EMPTY_ROOT(&b->root_s) ||
1080             !hlist_empty(&b->hhead)) {
1081                 WARN_ON_ONCE(net_exit);
1082                 return;
1083         }
1084
1085         if (rhashtable_remove_fast(&xfrm_policy_inexact_table, &b->head,
1086                                    xfrm_pol_inexact_params) == 0) {
1087                 list_del(&b->inexact_bins);
1088                 kfree_rcu(b, rcu);
1089         }
1090 }
1091
1092 static void xfrm_policy_inexact_prune_bin(struct xfrm_pol_inexact_bin *b)
1093 {
1094         struct net *net = read_pnet(&b->k.net);
1095
1096         spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1097         __xfrm_policy_inexact_prune_bin(b, false);
1098         spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1099 }
1100
1101 static void __xfrm_policy_inexact_flush(struct net *net)
1102 {
1103         struct xfrm_pol_inexact_bin *bin, *t;
1104
1105         lockdep_assert_held(&net->xfrm.xfrm_policy_lock);
1106
1107         list_for_each_entry_safe(bin, t, &net->xfrm.inexact_bins, inexact_bins)
1108                 __xfrm_policy_inexact_prune_bin(bin, false);
1109 }
1110
1111 static struct hlist_head *
1112 xfrm_policy_inexact_alloc_chain(struct xfrm_pol_inexact_bin *bin,
1113                                 struct xfrm_policy *policy, u8 dir)
1114 {
1115         struct xfrm_pol_inexact_node *n;
1116         struct net *net;
1117
1118         net = xp_net(policy);
1119         lockdep_assert_held(&net->xfrm.xfrm_policy_lock);
1120
1121         if (xfrm_policy_inexact_insert_use_any_list(policy))
1122                 return &bin->hhead;
1123
1124         if (xfrm_pol_inexact_addr_use_any_list(&policy->selector.daddr,
1125                                                policy->family,
1126                                                policy->selector.prefixlen_d)) {
1127                 write_seqcount_begin(&bin->count);
1128                 n = xfrm_policy_inexact_insert_node(net,
1129                                                     &bin->root_s,
1130                                                     &policy->selector.saddr,
1131                                                     policy->family,
1132                                                     policy->selector.prefixlen_s,
1133                                                     dir);
1134                 write_seqcount_end(&bin->count);
1135                 if (!n)
1136                         return NULL;
1137
1138                 return &n->hhead;
1139         }
1140
1141         /* daddr is fixed */
1142         write_seqcount_begin(&bin->count);
1143         n = xfrm_policy_inexact_insert_node(net,
1144                                             &bin->root_d,
1145                                             &policy->selector.daddr,
1146                                             policy->family,
1147                                             policy->selector.prefixlen_d, dir);
1148         write_seqcount_end(&bin->count);
1149         if (!n)
1150                 return NULL;
1151
1152         /* saddr is wildcard */
1153         if (xfrm_pol_inexact_addr_use_any_list(&policy->selector.saddr,
1154                                                policy->family,
1155                                                policy->selector.prefixlen_s))
1156                 return &n->hhead;
1157
1158         write_seqcount_begin(&bin->count);
1159         n = xfrm_policy_inexact_insert_node(net,
1160                                             &n->root,
1161                                             &policy->selector.saddr,
1162                                             policy->family,
1163                                             policy->selector.prefixlen_s, dir);
1164         write_seqcount_end(&bin->count);
1165         if (!n)
1166                 return NULL;
1167
1168         return &n->hhead;
1169 }
1170
1171 static struct xfrm_policy *
1172 xfrm_policy_inexact_insert(struct xfrm_policy *policy, u8 dir, int excl)
1173 {
1174         struct xfrm_pol_inexact_bin *bin;
1175         struct xfrm_policy *delpol;
1176         struct hlist_head *chain;
1177         struct net *net;
1178
1179         bin = xfrm_policy_inexact_alloc_bin(policy, dir);
1180         if (!bin)
1181                 return ERR_PTR(-ENOMEM);
1182
1183         net = xp_net(policy);
1184         lockdep_assert_held(&net->xfrm.xfrm_policy_lock);
1185
1186         chain = xfrm_policy_inexact_alloc_chain(bin, policy, dir);
1187         if (!chain) {
1188                 __xfrm_policy_inexact_prune_bin(bin, false);
1189                 return ERR_PTR(-ENOMEM);
1190         }
1191
1192         delpol = xfrm_policy_insert_list(chain, policy, excl);
1193         if (delpol && excl) {
1194                 __xfrm_policy_inexact_prune_bin(bin, false);
1195                 return ERR_PTR(-EEXIST);
1196         }
1197
1198         chain = &net->xfrm.policy_inexact[dir];
1199         xfrm_policy_insert_inexact_list(chain, policy);
1200
1201         if (delpol)
1202                 __xfrm_policy_inexact_prune_bin(bin, false);
1203
1204         return delpol;
1205 }
1206
1207 static void xfrm_hash_rebuild(struct work_struct *work)
1208 {
1209         struct net *net = container_of(work, struct net,
1210                                        xfrm.policy_hthresh.work);
1211         unsigned int hmask;
1212         struct xfrm_policy *pol;
1213         struct xfrm_policy *policy;
1214         struct hlist_head *chain;
1215         struct hlist_head *odst;
1216         struct hlist_node *newpos;
1217         int i;
1218         int dir;
1219         unsigned seq;
1220         u8 lbits4, rbits4, lbits6, rbits6;
1221
1222         mutex_lock(&hash_resize_mutex);
1223
1224         /* read selector prefixlen thresholds */
1225         do {
1226                 seq = read_seqbegin(&net->xfrm.policy_hthresh.lock);
1227
1228                 lbits4 = net->xfrm.policy_hthresh.lbits4;
1229                 rbits4 = net->xfrm.policy_hthresh.rbits4;
1230                 lbits6 = net->xfrm.policy_hthresh.lbits6;
1231                 rbits6 = net->xfrm.policy_hthresh.rbits6;
1232         } while (read_seqretry(&net->xfrm.policy_hthresh.lock, seq));
1233
1234         spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1235         write_seqcount_begin(&xfrm_policy_hash_generation);
1236
1237         /* make sure that we can insert the indirect policies again before
1238          * we start with destructive action.
1239          */
1240         list_for_each_entry(policy, &net->xfrm.policy_all, walk.all) {
1241                 struct xfrm_pol_inexact_bin *bin;
1242                 u8 dbits, sbits;
1243
1244                 dir = xfrm_policy_id2dir(policy->index);
1245                 if (policy->walk.dead || dir >= XFRM_POLICY_MAX)
1246                         continue;
1247
1248                 if ((dir & XFRM_POLICY_MASK) == XFRM_POLICY_OUT) {
1249                         if (policy->family == AF_INET) {
1250                                 dbits = rbits4;
1251                                 sbits = lbits4;
1252                         } else {
1253                                 dbits = rbits6;
1254                                 sbits = lbits6;
1255                         }
1256                 } else {
1257                         if (policy->family == AF_INET) {
1258                                 dbits = lbits4;
1259                                 sbits = rbits4;
1260                         } else {
1261                                 dbits = lbits6;
1262                                 sbits = rbits6;
1263                         }
1264                 }
1265
1266                 if (policy->selector.prefixlen_d < dbits ||
1267                     policy->selector.prefixlen_s < sbits)
1268                         continue;
1269
1270                 bin = xfrm_policy_inexact_alloc_bin(policy, dir);
1271                 if (!bin)
1272                         goto out_unlock;
1273
1274                 if (!xfrm_policy_inexact_alloc_chain(bin, policy, dir))
1275                         goto out_unlock;
1276         }
1277
1278         /* reset the bydst and inexact table in all directions */
1279         for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
1280                 struct hlist_node *n;
1281
1282                 hlist_for_each_entry_safe(policy, n,
1283                                           &net->xfrm.policy_inexact[dir],
1284                                           bydst_inexact_list) {
1285                         hlist_del_rcu(&policy->bydst);
1286                         hlist_del_init(&policy->bydst_inexact_list);
1287                 }
1288
1289                 hmask = net->xfrm.policy_bydst[dir].hmask;
1290                 odst = net->xfrm.policy_bydst[dir].table;
1291                 for (i = hmask; i >= 0; i--) {
1292                         hlist_for_each_entry_safe(policy, n, odst + i, bydst)
1293                                 hlist_del_rcu(&policy->bydst);
1294                 }
1295                 if ((dir & XFRM_POLICY_MASK) == XFRM_POLICY_OUT) {
1296                         /* dir out => dst = remote, src = local */
1297                         net->xfrm.policy_bydst[dir].dbits4 = rbits4;
1298                         net->xfrm.policy_bydst[dir].sbits4 = lbits4;
1299                         net->xfrm.policy_bydst[dir].dbits6 = rbits6;
1300                         net->xfrm.policy_bydst[dir].sbits6 = lbits6;
1301                 } else {
1302                         /* dir in/fwd => dst = local, src = remote */
1303                         net->xfrm.policy_bydst[dir].dbits4 = lbits4;
1304                         net->xfrm.policy_bydst[dir].sbits4 = rbits4;
1305                         net->xfrm.policy_bydst[dir].dbits6 = lbits6;
1306                         net->xfrm.policy_bydst[dir].sbits6 = rbits6;
1307                 }
1308         }
1309
1310         /* re-insert all policies by order of creation */
1311         list_for_each_entry_reverse(policy, &net->xfrm.policy_all, walk.all) {
1312                 if (policy->walk.dead)
1313                         continue;
1314                 dir = xfrm_policy_id2dir(policy->index);
1315                 if (dir >= XFRM_POLICY_MAX) {
1316                         /* skip socket policies */
1317                         continue;
1318                 }
1319                 newpos = NULL;
1320                 chain = policy_hash_bysel(net, &policy->selector,
1321                                           policy->family, dir);
1322
1323                 if (!chain) {
1324                         void *p = xfrm_policy_inexact_insert(policy, dir, 0);
1325
1326                         WARN_ONCE(IS_ERR(p), "reinsert: %ld\n", PTR_ERR(p));
1327                         continue;
1328                 }
1329
1330                 hlist_for_each_entry(pol, chain, bydst) {
1331                         if (policy->priority >= pol->priority)
1332                                 newpos = &pol->bydst;
1333                         else
1334                                 break;
1335                 }
1336                 if (newpos)
1337                         hlist_add_behind_rcu(&policy->bydst, newpos);
1338                 else
1339                         hlist_add_head_rcu(&policy->bydst, chain);
1340         }
1341
1342 out_unlock:
1343         __xfrm_policy_inexact_flush(net);
1344         write_seqcount_end(&xfrm_policy_hash_generation);
1345         spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1346
1347         mutex_unlock(&hash_resize_mutex);
1348 }
1349
1350 void xfrm_policy_hash_rebuild(struct net *net)
1351 {
1352         schedule_work(&net->xfrm.policy_hthresh.work);
1353 }
1354 EXPORT_SYMBOL(xfrm_policy_hash_rebuild);
1355
1356 /* Generate new index... KAME seems to generate them ordered by cost
1357  * of an absolute inpredictability of ordering of rules. This will not pass. */
1358 static u32 xfrm_gen_index(struct net *net, int dir, u32 index)
1359 {
1360         static u32 idx_generator;
1361
1362         for (;;) {
1363                 struct hlist_head *list;
1364                 struct xfrm_policy *p;
1365                 u32 idx;
1366                 int found;
1367
1368                 if (!index) {
1369                         idx = (idx_generator | dir);
1370                         idx_generator += 8;
1371                 } else {
1372                         idx = index;
1373                         index = 0;
1374                 }
1375
1376                 if (idx == 0)
1377                         idx = 8;
1378                 list = net->xfrm.policy_byidx + idx_hash(net, idx);
1379                 found = 0;
1380                 hlist_for_each_entry(p, list, byidx) {
1381                         if (p->index == idx) {
1382                                 found = 1;
1383                                 break;
1384                         }
1385                 }
1386                 if (!found)
1387                         return idx;
1388         }
1389 }
1390
1391 static inline int selector_cmp(struct xfrm_selector *s1, struct xfrm_selector *s2)
1392 {
1393         u32 *p1 = (u32 *) s1;
1394         u32 *p2 = (u32 *) s2;
1395         int len = sizeof(struct xfrm_selector) / sizeof(u32);
1396         int i;
1397
1398         for (i = 0; i < len; i++) {
1399                 if (p1[i] != p2[i])
1400                         return 1;
1401         }
1402
1403         return 0;
1404 }
1405
1406 static void xfrm_policy_requeue(struct xfrm_policy *old,
1407                                 struct xfrm_policy *new)
1408 {
1409         struct xfrm_policy_queue *pq = &old->polq;
1410         struct sk_buff_head list;
1411
1412         if (skb_queue_empty(&pq->hold_queue))
1413                 return;
1414
1415         __skb_queue_head_init(&list);
1416
1417         spin_lock_bh(&pq->hold_queue.lock);
1418         skb_queue_splice_init(&pq->hold_queue, &list);
1419         if (del_timer(&pq->hold_timer))
1420                 xfrm_pol_put(old);
1421         spin_unlock_bh(&pq->hold_queue.lock);
1422
1423         pq = &new->polq;
1424
1425         spin_lock_bh(&pq->hold_queue.lock);
1426         skb_queue_splice(&list, &pq->hold_queue);
1427         pq->timeout = XFRM_QUEUE_TMO_MIN;
1428         if (!mod_timer(&pq->hold_timer, jiffies))
1429                 xfrm_pol_hold(new);
1430         spin_unlock_bh(&pq->hold_queue.lock);
1431 }
1432
1433 static bool xfrm_policy_mark_match(struct xfrm_policy *policy,
1434                                    struct xfrm_policy *pol)
1435 {
1436         if (policy->mark.v == pol->mark.v &&
1437             policy->priority == pol->priority)
1438                 return true;
1439
1440         return false;
1441 }
1442
1443 static u32 xfrm_pol_bin_key(const void *data, u32 len, u32 seed)
1444 {
1445         const struct xfrm_pol_inexact_key *k = data;
1446         u32 a = k->type << 24 | k->dir << 16 | k->family;
1447
1448         return jhash_3words(a, k->if_id, net_hash_mix(read_pnet(&k->net)),
1449                             seed);
1450 }
1451
1452 static u32 xfrm_pol_bin_obj(const void *data, u32 len, u32 seed)
1453 {
1454         const struct xfrm_pol_inexact_bin *b = data;
1455
1456         return xfrm_pol_bin_key(&b->k, 0, seed);
1457 }
1458
1459 static int xfrm_pol_bin_cmp(struct rhashtable_compare_arg *arg,
1460                             const void *ptr)
1461 {
1462         const struct xfrm_pol_inexact_key *key = arg->key;
1463         const struct xfrm_pol_inexact_bin *b = ptr;
1464         int ret;
1465
1466         if (!net_eq(read_pnet(&b->k.net), read_pnet(&key->net)))
1467                 return -1;
1468
1469         ret = b->k.dir ^ key->dir;
1470         if (ret)
1471                 return ret;
1472
1473         ret = b->k.type ^ key->type;
1474         if (ret)
1475                 return ret;
1476
1477         ret = b->k.family ^ key->family;
1478         if (ret)
1479                 return ret;
1480
1481         return b->k.if_id ^ key->if_id;
1482 }
1483
1484 static const struct rhashtable_params xfrm_pol_inexact_params = {
1485         .head_offset            = offsetof(struct xfrm_pol_inexact_bin, head),
1486         .hashfn                 = xfrm_pol_bin_key,
1487         .obj_hashfn             = xfrm_pol_bin_obj,
1488         .obj_cmpfn              = xfrm_pol_bin_cmp,
1489         .automatic_shrinking    = true,
1490 };
1491
1492 static void xfrm_policy_insert_inexact_list(struct hlist_head *chain,
1493                                             struct xfrm_policy *policy)
1494 {
1495         struct xfrm_policy *pol, *delpol = NULL;
1496         struct hlist_node *newpos = NULL;
1497         int i = 0;
1498
1499         hlist_for_each_entry(pol, chain, bydst_inexact_list) {
1500                 if (pol->type == policy->type &&
1501                     pol->if_id == policy->if_id &&
1502                     !selector_cmp(&pol->selector, &policy->selector) &&
1503                     xfrm_policy_mark_match(policy, pol) &&
1504                     xfrm_sec_ctx_match(pol->security, policy->security) &&
1505                     !WARN_ON(delpol)) {
1506                         delpol = pol;
1507                         if (policy->priority > pol->priority)
1508                                 continue;
1509                 } else if (policy->priority >= pol->priority) {
1510                         newpos = &pol->bydst_inexact_list;
1511                         continue;
1512                 }
1513                 if (delpol)
1514                         break;
1515         }
1516
1517         if (newpos)
1518                 hlist_add_behind_rcu(&policy->bydst_inexact_list, newpos);
1519         else
1520                 hlist_add_head_rcu(&policy->bydst_inexact_list, chain);
1521
1522         hlist_for_each_entry(pol, chain, bydst_inexact_list) {
1523                 pol->pos = i;
1524                 i++;
1525         }
1526 }
1527
1528 static struct xfrm_policy *xfrm_policy_insert_list(struct hlist_head *chain,
1529                                                    struct xfrm_policy *policy,
1530                                                    bool excl)
1531 {
1532         struct xfrm_policy *pol, *newpos = NULL, *delpol = NULL;
1533
1534         hlist_for_each_entry(pol, chain, bydst) {
1535                 if (pol->type == policy->type &&
1536                     pol->if_id == policy->if_id &&
1537                     !selector_cmp(&pol->selector, &policy->selector) &&
1538                     xfrm_policy_mark_match(policy, pol) &&
1539                     xfrm_sec_ctx_match(pol->security, policy->security) &&
1540                     !WARN_ON(delpol)) {
1541                         if (excl)
1542                                 return ERR_PTR(-EEXIST);
1543                         delpol = pol;
1544                         if (policy->priority > pol->priority)
1545                                 continue;
1546                 } else if (policy->priority >= pol->priority) {
1547                         newpos = pol;
1548                         continue;
1549                 }
1550                 if (delpol)
1551                         break;
1552         }
1553
1554         if (newpos)
1555                 hlist_add_behind_rcu(&policy->bydst, &newpos->bydst);
1556         else
1557                 hlist_add_head_rcu(&policy->bydst, chain);
1558
1559         return delpol;
1560 }
1561
1562 int xfrm_policy_insert(int dir, struct xfrm_policy *policy, int excl)
1563 {
1564         struct net *net = xp_net(policy);
1565         struct xfrm_policy *delpol;
1566         struct hlist_head *chain;
1567
1568         spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1569         chain = policy_hash_bysel(net, &policy->selector, policy->family, dir);
1570         if (chain)
1571                 delpol = xfrm_policy_insert_list(chain, policy, excl);
1572         else
1573                 delpol = xfrm_policy_inexact_insert(policy, dir, excl);
1574
1575         if (IS_ERR(delpol)) {
1576                 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1577                 return PTR_ERR(delpol);
1578         }
1579
1580         __xfrm_policy_link(policy, dir);
1581
1582         /* After previous checking, family can either be AF_INET or AF_INET6 */
1583         if (policy->family == AF_INET)
1584                 rt_genid_bump_ipv4(net);
1585         else
1586                 rt_genid_bump_ipv6(net);
1587
1588         if (delpol) {
1589                 xfrm_policy_requeue(delpol, policy);
1590                 __xfrm_policy_unlink(delpol, dir);
1591         }
1592         policy->index = delpol ? delpol->index : xfrm_gen_index(net, dir, policy->index);
1593         hlist_add_head(&policy->byidx, net->xfrm.policy_byidx+idx_hash(net, policy->index));
1594         policy->curlft.add_time = ktime_get_real_seconds();
1595         policy->curlft.use_time = 0;
1596         if (!mod_timer(&policy->timer, jiffies + HZ))
1597                 xfrm_pol_hold(policy);
1598         spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1599
1600         if (delpol)
1601                 xfrm_policy_kill(delpol);
1602         else if (xfrm_bydst_should_resize(net, dir, NULL))
1603                 schedule_work(&net->xfrm.policy_hash_work);
1604
1605         return 0;
1606 }
1607 EXPORT_SYMBOL(xfrm_policy_insert);
1608
1609 static struct xfrm_policy *
1610 __xfrm_policy_bysel_ctx(struct hlist_head *chain, u32 mark, u32 if_id,
1611                         u8 type, int dir,
1612                         struct xfrm_selector *sel,
1613                         struct xfrm_sec_ctx *ctx)
1614 {
1615         struct xfrm_policy *pol;
1616
1617         if (!chain)
1618                 return NULL;
1619
1620         hlist_for_each_entry(pol, chain, bydst) {
1621                 if (pol->type == type &&
1622                     pol->if_id == if_id &&
1623                     (mark & pol->mark.m) == pol->mark.v &&
1624                     !selector_cmp(sel, &pol->selector) &&
1625                     xfrm_sec_ctx_match(ctx, pol->security))
1626                         return pol;
1627         }
1628
1629         return NULL;
1630 }
1631
1632 struct xfrm_policy *xfrm_policy_bysel_ctx(struct net *net, u32 mark, u32 if_id,
1633                                           u8 type, int dir,
1634                                           struct xfrm_selector *sel,
1635                                           struct xfrm_sec_ctx *ctx, int delete,
1636                                           int *err)
1637 {
1638         struct xfrm_pol_inexact_bin *bin = NULL;
1639         struct xfrm_policy *pol, *ret = NULL;
1640         struct hlist_head *chain;
1641
1642         *err = 0;
1643         spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1644         chain = policy_hash_bysel(net, sel, sel->family, dir);
1645         if (!chain) {
1646                 struct xfrm_pol_inexact_candidates cand;
1647                 int i;
1648
1649                 bin = xfrm_policy_inexact_lookup(net, type,
1650                                                  sel->family, dir, if_id);
1651                 if (!bin) {
1652                         spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1653                         return NULL;
1654                 }
1655
1656                 if (!xfrm_policy_find_inexact_candidates(&cand, bin,
1657                                                          &sel->saddr,
1658                                                          &sel->daddr)) {
1659                         spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1660                         return NULL;
1661                 }
1662
1663                 pol = NULL;
1664                 for (i = 0; i < ARRAY_SIZE(cand.res); i++) {
1665                         struct xfrm_policy *tmp;
1666
1667                         tmp = __xfrm_policy_bysel_ctx(cand.res[i], mark,
1668                                                       if_id, type, dir,
1669                                                       sel, ctx);
1670                         if (!tmp)
1671                                 continue;
1672
1673                         if (!pol || tmp->pos < pol->pos)
1674                                 pol = tmp;
1675                 }
1676         } else {
1677                 pol = __xfrm_policy_bysel_ctx(chain, mark, if_id, type, dir,
1678                                               sel, ctx);
1679         }
1680
1681         if (pol) {
1682                 xfrm_pol_hold(pol);
1683                 if (delete) {
1684                         *err = security_xfrm_policy_delete(pol->security);
1685                         if (*err) {
1686                                 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1687                                 return pol;
1688                         }
1689                         __xfrm_policy_unlink(pol, dir);
1690                 }
1691                 ret = pol;
1692         }
1693         spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1694
1695         if (ret && delete)
1696                 xfrm_policy_kill(ret);
1697         if (bin && delete)
1698                 xfrm_policy_inexact_prune_bin(bin);
1699         return ret;
1700 }
1701 EXPORT_SYMBOL(xfrm_policy_bysel_ctx);
1702
1703 struct xfrm_policy *xfrm_policy_byid(struct net *net, u32 mark, u32 if_id,
1704                                      u8 type, int dir, u32 id, int delete,
1705                                      int *err)
1706 {
1707         struct xfrm_policy *pol, *ret;
1708         struct hlist_head *chain;
1709
1710         *err = -ENOENT;
1711         if (xfrm_policy_id2dir(id) != dir)
1712                 return NULL;
1713
1714         *err = 0;
1715         spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1716         chain = net->xfrm.policy_byidx + idx_hash(net, id);
1717         ret = NULL;
1718         hlist_for_each_entry(pol, chain, byidx) {
1719                 if (pol->type == type && pol->index == id &&
1720                     pol->if_id == if_id &&
1721                     (mark & pol->mark.m) == pol->mark.v) {
1722                         xfrm_pol_hold(pol);
1723                         if (delete) {
1724                                 *err = security_xfrm_policy_delete(
1725                                                                 pol->security);
1726                                 if (*err) {
1727                                         spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1728                                         return pol;
1729                                 }
1730                                 __xfrm_policy_unlink(pol, dir);
1731                         }
1732                         ret = pol;
1733                         break;
1734                 }
1735         }
1736         spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1737
1738         if (ret && delete)
1739                 xfrm_policy_kill(ret);
1740         return ret;
1741 }
1742 EXPORT_SYMBOL(xfrm_policy_byid);
1743
1744 #ifdef CONFIG_SECURITY_NETWORK_XFRM
1745 static inline int
1746 xfrm_policy_flush_secctx_check(struct net *net, u8 type, bool task_valid)
1747 {
1748         struct xfrm_policy *pol;
1749         int err = 0;
1750
1751         list_for_each_entry(pol, &net->xfrm.policy_all, walk.all) {
1752                 if (pol->walk.dead ||
1753                     xfrm_policy_id2dir(pol->index) >= XFRM_POLICY_MAX ||
1754                     pol->type != type)
1755                         continue;
1756
1757                 err = security_xfrm_policy_delete(pol->security);
1758                 if (err) {
1759                         xfrm_audit_policy_delete(pol, 0, task_valid);
1760                         return err;
1761                 }
1762         }
1763         return err;
1764 }
1765 #else
1766 static inline int
1767 xfrm_policy_flush_secctx_check(struct net *net, u8 type, bool task_valid)
1768 {
1769         return 0;
1770 }
1771 #endif
1772
1773 int xfrm_policy_flush(struct net *net, u8 type, bool task_valid)
1774 {
1775         int dir, err = 0, cnt = 0;
1776         struct xfrm_policy *pol;
1777
1778         spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1779
1780         err = xfrm_policy_flush_secctx_check(net, type, task_valid);
1781         if (err)
1782                 goto out;
1783
1784 again:
1785         list_for_each_entry(pol, &net->xfrm.policy_all, walk.all) {
1786                 dir = xfrm_policy_id2dir(pol->index);
1787                 if (pol->walk.dead ||
1788                     dir >= XFRM_POLICY_MAX ||
1789                     pol->type != type)
1790                         continue;
1791
1792                 __xfrm_policy_unlink(pol, dir);
1793                 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1794                 cnt++;
1795                 xfrm_audit_policy_delete(pol, 1, task_valid);
1796                 xfrm_policy_kill(pol);
1797                 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1798                 goto again;
1799         }
1800         if (cnt)
1801                 __xfrm_policy_inexact_flush(net);
1802         else
1803                 err = -ESRCH;
1804 out:
1805         spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1806         return err;
1807 }
1808 EXPORT_SYMBOL(xfrm_policy_flush);
1809
1810 int xfrm_policy_walk(struct net *net, struct xfrm_policy_walk *walk,
1811                      int (*func)(struct xfrm_policy *, int, int, void*),
1812                      void *data)
1813 {
1814         struct xfrm_policy *pol;
1815         struct xfrm_policy_walk_entry *x;
1816         int error = 0;
1817
1818         if (walk->type >= XFRM_POLICY_TYPE_MAX &&
1819             walk->type != XFRM_POLICY_TYPE_ANY)
1820                 return -EINVAL;
1821
1822         if (list_empty(&walk->walk.all) && walk->seq != 0)
1823                 return 0;
1824
1825         spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1826         if (list_empty(&walk->walk.all))
1827                 x = list_first_entry(&net->xfrm.policy_all, struct xfrm_policy_walk_entry, all);
1828         else
1829                 x = list_first_entry(&walk->walk.all,
1830                                      struct xfrm_policy_walk_entry, all);
1831
1832         list_for_each_entry_from(x, &net->xfrm.policy_all, all) {
1833                 if (x->dead)
1834                         continue;
1835                 pol = container_of(x, struct xfrm_policy, walk);
1836                 if (walk->type != XFRM_POLICY_TYPE_ANY &&
1837                     walk->type != pol->type)
1838                         continue;
1839                 error = func(pol, xfrm_policy_id2dir(pol->index),
1840                              walk->seq, data);
1841                 if (error) {
1842                         list_move_tail(&walk->walk.all, &x->all);
1843                         goto out;
1844                 }
1845                 walk->seq++;
1846         }
1847         if (walk->seq == 0) {
1848                 error = -ENOENT;
1849                 goto out;
1850         }
1851         list_del_init(&walk->walk.all);
1852 out:
1853         spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1854         return error;
1855 }
1856 EXPORT_SYMBOL(xfrm_policy_walk);
1857
1858 void xfrm_policy_walk_init(struct xfrm_policy_walk *walk, u8 type)
1859 {
1860         INIT_LIST_HEAD(&walk->walk.all);
1861         walk->walk.dead = 1;
1862         walk->type = type;
1863         walk->seq = 0;
1864 }
1865 EXPORT_SYMBOL(xfrm_policy_walk_init);
1866
1867 void xfrm_policy_walk_done(struct xfrm_policy_walk *walk, struct net *net)
1868 {
1869         if (list_empty(&walk->walk.all))
1870                 return;
1871
1872         spin_lock_bh(&net->xfrm.xfrm_policy_lock); /*FIXME where is net? */
1873         list_del(&walk->walk.all);
1874         spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1875 }
1876 EXPORT_SYMBOL(xfrm_policy_walk_done);
1877
1878 /*
1879  * Find policy to apply to this flow.
1880  *
1881  * Returns 0 if policy found, else an -errno.
1882  */
1883 static int xfrm_policy_match(const struct xfrm_policy *pol,
1884                              const struct flowi *fl,
1885                              u8 type, u16 family, int dir, u32 if_id)
1886 {
1887         const struct xfrm_selector *sel = &pol->selector;
1888         int ret = -ESRCH;
1889         bool match;
1890
1891         if (pol->family != family ||
1892             pol->if_id != if_id ||
1893             (fl->flowi_mark & pol->mark.m) != pol->mark.v ||
1894             pol->type != type)
1895                 return ret;
1896
1897         match = xfrm_selector_match(sel, fl, family);
1898         if (match)
1899                 ret = security_xfrm_policy_lookup(pol->security, fl->flowi_secid,
1900                                                   dir);
1901         return ret;
1902 }
1903
1904 static struct xfrm_pol_inexact_node *
1905 xfrm_policy_lookup_inexact_addr(const struct rb_root *r,
1906                                 seqcount_t *count,
1907                                 const xfrm_address_t *addr, u16 family)
1908 {
1909         const struct rb_node *parent;
1910         int seq;
1911
1912 again:
1913         seq = read_seqcount_begin(count);
1914
1915         parent = rcu_dereference_raw(r->rb_node);
1916         while (parent) {
1917                 struct xfrm_pol_inexact_node *node;
1918                 int delta;
1919
1920                 node = rb_entry(parent, struct xfrm_pol_inexact_node, node);
1921
1922                 delta = xfrm_policy_addr_delta(addr, &node->addr,
1923                                                node->prefixlen, family);
1924                 if (delta < 0) {
1925                         parent = rcu_dereference_raw(parent->rb_left);
1926                         continue;
1927                 } else if (delta > 0) {
1928                         parent = rcu_dereference_raw(parent->rb_right);
1929                         continue;
1930                 }
1931
1932                 return node;
1933         }
1934
1935         if (read_seqcount_retry(count, seq))
1936                 goto again;
1937
1938         return NULL;
1939 }
1940
1941 static bool
1942 xfrm_policy_find_inexact_candidates(struct xfrm_pol_inexact_candidates *cand,
1943                                     struct xfrm_pol_inexact_bin *b,
1944                                     const xfrm_address_t *saddr,
1945                                     const xfrm_address_t *daddr)
1946 {
1947         struct xfrm_pol_inexact_node *n;
1948         u16 family;
1949
1950         if (!b)
1951                 return false;
1952
1953         family = b->k.family;
1954         memset(cand, 0, sizeof(*cand));
1955         cand->res[XFRM_POL_CAND_ANY] = &b->hhead;
1956
1957         n = xfrm_policy_lookup_inexact_addr(&b->root_d, &b->count, daddr,
1958                                             family);
1959         if (n) {
1960                 cand->res[XFRM_POL_CAND_DADDR] = &n->hhead;
1961                 n = xfrm_policy_lookup_inexact_addr(&n->root, &b->count, saddr,
1962                                                     family);
1963                 if (n)
1964                         cand->res[XFRM_POL_CAND_BOTH] = &n->hhead;
1965         }
1966
1967         n = xfrm_policy_lookup_inexact_addr(&b->root_s, &b->count, saddr,
1968                                             family);
1969         if (n)
1970                 cand->res[XFRM_POL_CAND_SADDR] = &n->hhead;
1971
1972         return true;
1973 }
1974
1975 static struct xfrm_pol_inexact_bin *
1976 xfrm_policy_inexact_lookup_rcu(struct net *net, u8 type, u16 family,
1977                                u8 dir, u32 if_id)
1978 {
1979         struct xfrm_pol_inexact_key k = {
1980                 .family = family,
1981                 .type = type,
1982                 .dir = dir,
1983                 .if_id = if_id,
1984         };
1985
1986         write_pnet(&k.net, net);
1987
1988         return rhashtable_lookup(&xfrm_policy_inexact_table, &k,
1989                                  xfrm_pol_inexact_params);
1990 }
1991
1992 static struct xfrm_pol_inexact_bin *
1993 xfrm_policy_inexact_lookup(struct net *net, u8 type, u16 family,
1994                            u8 dir, u32 if_id)
1995 {
1996         struct xfrm_pol_inexact_bin *bin;
1997
1998         lockdep_assert_held(&net->xfrm.xfrm_policy_lock);
1999
2000         rcu_read_lock();
2001         bin = xfrm_policy_inexact_lookup_rcu(net, type, family, dir, if_id);
2002         rcu_read_unlock();
2003
2004         return bin;
2005 }
2006
2007 static struct xfrm_policy *
2008 __xfrm_policy_eval_candidates(struct hlist_head *chain,
2009                               struct xfrm_policy *prefer,
2010                               const struct flowi *fl,
2011                               u8 type, u16 family, int dir, u32 if_id)
2012 {
2013         u32 priority = prefer ? prefer->priority : ~0u;
2014         struct xfrm_policy *pol;
2015
2016         if (!chain)
2017                 return NULL;
2018
2019         hlist_for_each_entry_rcu(pol, chain, bydst) {
2020                 int err;
2021
2022                 if (pol->priority > priority)
2023                         break;
2024
2025                 err = xfrm_policy_match(pol, fl, type, family, dir, if_id);
2026                 if (err) {
2027                         if (err != -ESRCH)
2028                                 return ERR_PTR(err);
2029
2030                         continue;
2031                 }
2032
2033                 if (prefer) {
2034                         /* matches.  Is it older than *prefer? */
2035                         if (pol->priority == priority &&
2036                             prefer->pos < pol->pos)
2037                                 return prefer;
2038                 }
2039
2040                 return pol;
2041         }
2042
2043         return NULL;
2044 }
2045
2046 static struct xfrm_policy *
2047 xfrm_policy_eval_candidates(struct xfrm_pol_inexact_candidates *cand,
2048                             struct xfrm_policy *prefer,
2049                             const struct flowi *fl,
2050                             u8 type, u16 family, int dir, u32 if_id)
2051 {
2052         struct xfrm_policy *tmp;
2053         int i;
2054
2055         for (i = 0; i < ARRAY_SIZE(cand->res); i++) {
2056                 tmp = __xfrm_policy_eval_candidates(cand->res[i],
2057                                                     prefer,
2058                                                     fl, type, family, dir,
2059                                                     if_id);
2060                 if (!tmp)
2061                         continue;
2062
2063                 if (IS_ERR(tmp))
2064                         return tmp;
2065                 prefer = tmp;
2066         }
2067
2068         return prefer;
2069 }
2070
2071 static struct xfrm_policy *xfrm_policy_lookup_bytype(struct net *net, u8 type,
2072                                                      const struct flowi *fl,
2073                                                      u16 family, u8 dir,
2074                                                      u32 if_id)
2075 {
2076         struct xfrm_pol_inexact_candidates cand;
2077         const xfrm_address_t *daddr, *saddr;
2078         struct xfrm_pol_inexact_bin *bin;
2079         struct xfrm_policy *pol, *ret;
2080         struct hlist_head *chain;
2081         unsigned int sequence;
2082         int err;
2083
2084         daddr = xfrm_flowi_daddr(fl, family);
2085         saddr = xfrm_flowi_saddr(fl, family);
2086         if (unlikely(!daddr || !saddr))
2087                 return NULL;
2088
2089         rcu_read_lock();
2090  retry:
2091         do {
2092                 sequence = read_seqcount_begin(&xfrm_policy_hash_generation);
2093                 chain = policy_hash_direct(net, daddr, saddr, family, dir);
2094         } while (read_seqcount_retry(&xfrm_policy_hash_generation, sequence));
2095
2096         ret = NULL;
2097         hlist_for_each_entry_rcu(pol, chain, bydst) {
2098                 err = xfrm_policy_match(pol, fl, type, family, dir, if_id);
2099                 if (err) {
2100                         if (err == -ESRCH)
2101                                 continue;
2102                         else {
2103                                 ret = ERR_PTR(err);
2104                                 goto fail;
2105                         }
2106                 } else {
2107                         ret = pol;
2108                         break;
2109                 }
2110         }
2111         bin = xfrm_policy_inexact_lookup_rcu(net, type, family, dir, if_id);
2112         if (!bin || !xfrm_policy_find_inexact_candidates(&cand, bin, saddr,
2113                                                          daddr))
2114                 goto skip_inexact;
2115
2116         pol = xfrm_policy_eval_candidates(&cand, ret, fl, type,
2117                                           family, dir, if_id);
2118         if (pol) {
2119                 ret = pol;
2120                 if (IS_ERR(pol))
2121                         goto fail;
2122         }
2123
2124 skip_inexact:
2125         if (read_seqcount_retry(&xfrm_policy_hash_generation, sequence))
2126                 goto retry;
2127
2128         if (ret && !xfrm_pol_hold_rcu(ret))
2129                 goto retry;
2130 fail:
2131         rcu_read_unlock();
2132
2133         return ret;
2134 }
2135
2136 static struct xfrm_policy *xfrm_policy_lookup(struct net *net,
2137                                               const struct flowi *fl,
2138                                               u16 family, u8 dir, u32 if_id)
2139 {
2140 #ifdef CONFIG_XFRM_SUB_POLICY
2141         struct xfrm_policy *pol;
2142
2143         pol = xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_SUB, fl, family,
2144                                         dir, if_id);
2145         if (pol != NULL)
2146                 return pol;
2147 #endif
2148         return xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_MAIN, fl, family,
2149                                          dir, if_id);
2150 }
2151
2152 static struct xfrm_policy *xfrm_sk_policy_lookup(const struct sock *sk, int dir,
2153                                                  const struct flowi *fl,
2154                                                  u16 family, u32 if_id)
2155 {
2156         struct xfrm_policy *pol;
2157
2158         rcu_read_lock();
2159  again:
2160         pol = rcu_dereference(sk->sk_policy[dir]);
2161         if (pol != NULL) {
2162                 bool match;
2163                 int err = 0;
2164
2165                 if (pol->family != family) {
2166                         pol = NULL;
2167                         goto out;
2168                 }
2169
2170                 match = xfrm_selector_match(&pol->selector, fl, family);
2171                 if (match) {
2172                         if ((sk->sk_mark & pol->mark.m) != pol->mark.v ||
2173                             pol->if_id != if_id) {
2174                                 pol = NULL;
2175                                 goto out;
2176                         }
2177                         err = security_xfrm_policy_lookup(pol->security,
2178                                                       fl->flowi_secid,
2179                                                       dir);
2180                         if (!err) {
2181                                 if (!xfrm_pol_hold_rcu(pol))
2182                                         goto again;
2183                         } else if (err == -ESRCH) {
2184                                 pol = NULL;
2185                         } else {
2186                                 pol = ERR_PTR(err);
2187                         }
2188                 } else
2189                         pol = NULL;
2190         }
2191 out:
2192         rcu_read_unlock();
2193         return pol;
2194 }
2195
2196 static void __xfrm_policy_link(struct xfrm_policy *pol, int dir)
2197 {
2198         struct net *net = xp_net(pol);
2199
2200         list_add(&pol->walk.all, &net->xfrm.policy_all);
2201         net->xfrm.policy_count[dir]++;
2202         xfrm_pol_hold(pol);
2203 }
2204
2205 static struct xfrm_policy *__xfrm_policy_unlink(struct xfrm_policy *pol,
2206                                                 int dir)
2207 {
2208         struct net *net = xp_net(pol);
2209
2210         if (list_empty(&pol->walk.all))
2211                 return NULL;
2212
2213         /* Socket policies are not hashed. */
2214         if (!hlist_unhashed(&pol->bydst)) {
2215                 hlist_del_rcu(&pol->bydst);
2216                 hlist_del_init(&pol->bydst_inexact_list);
2217                 hlist_del(&pol->byidx);
2218         }
2219
2220         list_del_init(&pol->walk.all);
2221         net->xfrm.policy_count[dir]--;
2222
2223         return pol;
2224 }
2225
2226 static void xfrm_sk_policy_link(struct xfrm_policy *pol, int dir)
2227 {
2228         __xfrm_policy_link(pol, XFRM_POLICY_MAX + dir);
2229 }
2230
2231 static void xfrm_sk_policy_unlink(struct xfrm_policy *pol, int dir)
2232 {
2233         __xfrm_policy_unlink(pol, XFRM_POLICY_MAX + dir);
2234 }
2235
2236 int xfrm_policy_delete(struct xfrm_policy *pol, int dir)
2237 {
2238         struct net *net = xp_net(pol);
2239
2240         spin_lock_bh(&net->xfrm.xfrm_policy_lock);
2241         pol = __xfrm_policy_unlink(pol, dir);
2242         spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
2243         if (pol) {
2244                 xfrm_policy_kill(pol);
2245                 return 0;
2246         }
2247         return -ENOENT;
2248 }
2249 EXPORT_SYMBOL(xfrm_policy_delete);
2250
2251 int xfrm_sk_policy_insert(struct sock *sk, int dir, struct xfrm_policy *pol)
2252 {
2253         struct net *net = sock_net(sk);
2254         struct xfrm_policy *old_pol;
2255
2256 #ifdef CONFIG_XFRM_SUB_POLICY
2257         if (pol && pol->type != XFRM_POLICY_TYPE_MAIN)
2258                 return -EINVAL;
2259 #endif
2260
2261         spin_lock_bh(&net->xfrm.xfrm_policy_lock);
2262         old_pol = rcu_dereference_protected(sk->sk_policy[dir],
2263                                 lockdep_is_held(&net->xfrm.xfrm_policy_lock));
2264         if (pol) {
2265                 pol->curlft.add_time = ktime_get_real_seconds();
2266                 pol->index = xfrm_gen_index(net, XFRM_POLICY_MAX+dir, 0);
2267                 xfrm_sk_policy_link(pol, dir);
2268         }
2269         rcu_assign_pointer(sk->sk_policy[dir], pol);
2270         if (old_pol) {
2271                 if (pol)
2272                         xfrm_policy_requeue(old_pol, pol);
2273
2274                 /* Unlinking succeeds always. This is the only function
2275                  * allowed to delete or replace socket policy.
2276                  */
2277                 xfrm_sk_policy_unlink(old_pol, dir);
2278         }
2279         spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
2280
2281         if (old_pol) {
2282                 xfrm_policy_kill(old_pol);
2283         }
2284         return 0;
2285 }
2286
2287 static struct xfrm_policy *clone_policy(const struct xfrm_policy *old, int dir)
2288 {
2289         struct xfrm_policy *newp = xfrm_policy_alloc(xp_net(old), GFP_ATOMIC);
2290         struct net *net = xp_net(old);
2291
2292         if (newp) {
2293                 newp->selector = old->selector;
2294                 if (security_xfrm_policy_clone(old->security,
2295                                                &newp->security)) {
2296                         kfree(newp);
2297                         return NULL;  /* ENOMEM */
2298                 }
2299                 newp->lft = old->lft;
2300                 newp->curlft = old->curlft;
2301                 newp->mark = old->mark;
2302                 newp->if_id = old->if_id;
2303                 newp->action = old->action;
2304                 newp->flags = old->flags;
2305                 newp->xfrm_nr = old->xfrm_nr;
2306                 newp->index = old->index;
2307                 newp->type = old->type;
2308                 newp->family = old->family;
2309                 memcpy(newp->xfrm_vec, old->xfrm_vec,
2310                        newp->xfrm_nr*sizeof(struct xfrm_tmpl));
2311                 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
2312                 xfrm_sk_policy_link(newp, dir);
2313                 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
2314                 xfrm_pol_put(newp);
2315         }
2316         return newp;
2317 }
2318
2319 int __xfrm_sk_clone_policy(struct sock *sk, const struct sock *osk)
2320 {
2321         const struct xfrm_policy *p;
2322         struct xfrm_policy *np;
2323         int i, ret = 0;
2324
2325         rcu_read_lock();
2326         for (i = 0; i < 2; i++) {
2327                 p = rcu_dereference(osk->sk_policy[i]);
2328                 if (p) {
2329                         np = clone_policy(p, i);
2330                         if (unlikely(!np)) {
2331                                 ret = -ENOMEM;
2332                                 break;
2333                         }
2334                         rcu_assign_pointer(sk->sk_policy[i], np);
2335                 }
2336         }
2337         rcu_read_unlock();
2338         return ret;
2339 }
2340
2341 static int
2342 xfrm_get_saddr(struct net *net, int oif, xfrm_address_t *local,
2343                xfrm_address_t *remote, unsigned short family, u32 mark)
2344 {
2345         int err;
2346         const struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
2347
2348         if (unlikely(afinfo == NULL))
2349                 return -EINVAL;
2350         err = afinfo->get_saddr(net, oif, local, remote, mark);
2351         rcu_read_unlock();
2352         return err;
2353 }
2354
2355 /* Resolve list of templates for the flow, given policy. */
2356
2357 static int
2358 xfrm_tmpl_resolve_one(struct xfrm_policy *policy, const struct flowi *fl,
2359                       struct xfrm_state **xfrm, unsigned short family)
2360 {
2361         struct net *net = xp_net(policy);
2362         int nx;
2363         int i, error;
2364         xfrm_address_t *daddr = xfrm_flowi_daddr(fl, family);
2365         xfrm_address_t *saddr = xfrm_flowi_saddr(fl, family);
2366         xfrm_address_t tmp;
2367
2368         for (nx = 0, i = 0; i < policy->xfrm_nr; i++) {
2369                 struct xfrm_state *x;
2370                 xfrm_address_t *remote = daddr;
2371                 xfrm_address_t *local  = saddr;
2372                 struct xfrm_tmpl *tmpl = &policy->xfrm_vec[i];
2373
2374                 if (tmpl->mode == XFRM_MODE_TUNNEL ||
2375                     tmpl->mode == XFRM_MODE_BEET) {
2376                         remote = &tmpl->id.daddr;
2377                         local = &tmpl->saddr;
2378                         if (xfrm_addr_any(local, tmpl->encap_family)) {
2379                                 error = xfrm_get_saddr(net, fl->flowi_oif,
2380                                                        &tmp, remote,
2381                                                        tmpl->encap_family, 0);
2382                                 if (error)
2383                                         goto fail;
2384                                 local = &tmp;
2385                         }
2386                 }
2387
2388                 x = xfrm_state_find(remote, local, fl, tmpl, policy, &error,
2389                                     family, policy->if_id);
2390
2391                 if (x && x->km.state == XFRM_STATE_VALID) {
2392                         xfrm[nx++] = x;
2393                         daddr = remote;
2394                         saddr = local;
2395                         continue;
2396                 }
2397                 if (x) {
2398                         error = (x->km.state == XFRM_STATE_ERROR ?
2399                                  -EINVAL : -EAGAIN);
2400                         xfrm_state_put(x);
2401                 } else if (error == -ESRCH) {
2402                         error = -EAGAIN;
2403                 }
2404
2405                 if (!tmpl->optional)
2406                         goto fail;
2407         }
2408         return nx;
2409
2410 fail:
2411         for (nx--; nx >= 0; nx--)
2412                 xfrm_state_put(xfrm[nx]);
2413         return error;
2414 }
2415
2416 static int
2417 xfrm_tmpl_resolve(struct xfrm_policy **pols, int npols, const struct flowi *fl,
2418                   struct xfrm_state **xfrm, unsigned short family)
2419 {
2420         struct xfrm_state *tp[XFRM_MAX_DEPTH];
2421         struct xfrm_state **tpp = (npols > 1) ? tp : xfrm;
2422         int cnx = 0;
2423         int error;
2424         int ret;
2425         int i;
2426
2427         for (i = 0; i < npols; i++) {
2428                 if (cnx + pols[i]->xfrm_nr >= XFRM_MAX_DEPTH) {
2429                         error = -ENOBUFS;
2430                         goto fail;
2431                 }
2432
2433                 ret = xfrm_tmpl_resolve_one(pols[i], fl, &tpp[cnx], family);
2434                 if (ret < 0) {
2435                         error = ret;
2436                         goto fail;
2437                 } else
2438                         cnx += ret;
2439         }
2440
2441         /* found states are sorted for outbound processing */
2442         if (npols > 1)
2443                 xfrm_state_sort(xfrm, tpp, cnx, family);
2444
2445         return cnx;
2446
2447  fail:
2448         for (cnx--; cnx >= 0; cnx--)
2449                 xfrm_state_put(tpp[cnx]);
2450         return error;
2451
2452 }
2453
2454 static int xfrm_get_tos(const struct flowi *fl, int family)
2455 {
2456         if (family == AF_INET)
2457                 return IPTOS_RT_MASK & fl->u.ip4.flowi4_tos;
2458
2459         return 0;
2460 }
2461
2462 static inline struct xfrm_dst *xfrm_alloc_dst(struct net *net, int family)
2463 {
2464         const struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
2465         struct dst_ops *dst_ops;
2466         struct xfrm_dst *xdst;
2467
2468         if (!afinfo)
2469                 return ERR_PTR(-EINVAL);
2470
2471         switch (family) {
2472         case AF_INET:
2473                 dst_ops = &net->xfrm.xfrm4_dst_ops;
2474                 break;
2475 #if IS_ENABLED(CONFIG_IPV6)
2476         case AF_INET6:
2477                 dst_ops = &net->xfrm.xfrm6_dst_ops;
2478                 break;
2479 #endif
2480         default:
2481                 BUG();
2482         }
2483         xdst = dst_alloc(dst_ops, NULL, 1, DST_OBSOLETE_NONE, 0);
2484
2485         if (likely(xdst)) {
2486                 struct dst_entry *dst = &xdst->u.dst;
2487
2488                 memset(dst + 1, 0, sizeof(*xdst) - sizeof(*dst));
2489         } else
2490                 xdst = ERR_PTR(-ENOBUFS);
2491
2492         rcu_read_unlock();
2493
2494         return xdst;
2495 }
2496
2497 static void xfrm_init_path(struct xfrm_dst *path, struct dst_entry *dst,
2498                            int nfheader_len)
2499 {
2500         if (dst->ops->family == AF_INET6) {
2501                 struct rt6_info *rt = (struct rt6_info *)dst;
2502                 path->path_cookie = rt6_get_cookie(rt);
2503                 path->u.rt6.rt6i_nfheader_len = nfheader_len;
2504         }
2505 }
2506
2507 static inline int xfrm_fill_dst(struct xfrm_dst *xdst, struct net_device *dev,
2508                                 const struct flowi *fl)
2509 {
2510         const struct xfrm_policy_afinfo *afinfo =
2511                 xfrm_policy_get_afinfo(xdst->u.dst.ops->family);
2512         int err;
2513
2514         if (!afinfo)
2515                 return -EINVAL;
2516
2517         err = afinfo->fill_dst(xdst, dev, fl);
2518
2519         rcu_read_unlock();
2520
2521         return err;
2522 }
2523
2524
2525 /* Allocate chain of dst_entry's, attach known xfrm's, calculate
2526  * all the metrics... Shortly, bundle a bundle.
2527  */
2528
2529 static struct dst_entry *xfrm_bundle_create(struct xfrm_policy *policy,
2530                                             struct xfrm_state **xfrm,
2531                                             struct xfrm_dst **bundle,
2532                                             int nx,
2533                                             const struct flowi *fl,
2534                                             struct dst_entry *dst)
2535 {
2536         const struct xfrm_state_afinfo *afinfo;
2537         const struct xfrm_mode *inner_mode;
2538         struct net *net = xp_net(policy);
2539         unsigned long now = jiffies;
2540         struct net_device *dev;
2541         struct xfrm_dst *xdst_prev = NULL;
2542         struct xfrm_dst *xdst0 = NULL;
2543         int i = 0;
2544         int err;
2545         int header_len = 0;
2546         int nfheader_len = 0;
2547         int trailer_len = 0;
2548         int tos;
2549         int family = policy->selector.family;
2550         xfrm_address_t saddr, daddr;
2551
2552         xfrm_flowi_addr_get(fl, &saddr, &daddr, family);
2553
2554         tos = xfrm_get_tos(fl, family);
2555
2556         dst_hold(dst);
2557
2558         for (; i < nx; i++) {
2559                 struct xfrm_dst *xdst = xfrm_alloc_dst(net, family);
2560                 struct dst_entry *dst1 = &xdst->u.dst;
2561
2562                 err = PTR_ERR(xdst);
2563                 if (IS_ERR(xdst)) {
2564                         dst_release(dst);
2565                         goto put_states;
2566                 }
2567
2568                 bundle[i] = xdst;
2569                 if (!xdst_prev)
2570                         xdst0 = xdst;
2571                 else
2572                         /* Ref count is taken during xfrm_alloc_dst()
2573                          * No need to do dst_clone() on dst1
2574                          */
2575                         xfrm_dst_set_child(xdst_prev, &xdst->u.dst);
2576
2577                 if (xfrm[i]->sel.family == AF_UNSPEC) {
2578                         inner_mode = xfrm_ip2inner_mode(xfrm[i],
2579                                                         xfrm_af2proto(family));
2580                         if (!inner_mode) {
2581                                 err = -EAFNOSUPPORT;
2582                                 dst_release(dst);
2583                                 goto put_states;
2584                         }
2585                 } else
2586                         inner_mode = &xfrm[i]->inner_mode;
2587
2588                 xdst->route = dst;
2589                 dst_copy_metrics(dst1, dst);
2590
2591                 if (xfrm[i]->props.mode != XFRM_MODE_TRANSPORT) {
2592                         __u32 mark = 0;
2593
2594                         if (xfrm[i]->props.smark.v || xfrm[i]->props.smark.m)
2595                                 mark = xfrm_smark_get(fl->flowi_mark, xfrm[i]);
2596
2597                         family = xfrm[i]->props.family;
2598                         dst = xfrm_dst_lookup(xfrm[i], tos, fl->flowi_oif,
2599                                               &saddr, &daddr, family, mark);
2600                         err = PTR_ERR(dst);
2601                         if (IS_ERR(dst))
2602                                 goto put_states;
2603                 } else
2604                         dst_hold(dst);
2605
2606                 dst1->xfrm = xfrm[i];
2607                 xdst->xfrm_genid = xfrm[i]->genid;
2608
2609                 dst1->obsolete = DST_OBSOLETE_FORCE_CHK;
2610                 dst1->flags |= DST_HOST;
2611                 dst1->lastuse = now;
2612
2613                 dst1->input = dst_discard;
2614
2615                 rcu_read_lock();
2616                 afinfo = xfrm_state_afinfo_get_rcu(inner_mode->family);
2617                 if (likely(afinfo))
2618                         dst1->output = afinfo->output;
2619                 else
2620                         dst1->output = dst_discard_out;
2621                 rcu_read_unlock();
2622
2623                 xdst_prev = xdst;
2624
2625                 header_len += xfrm[i]->props.header_len;
2626                 if (xfrm[i]->type->flags & XFRM_TYPE_NON_FRAGMENT)
2627                         nfheader_len += xfrm[i]->props.header_len;
2628                 trailer_len += xfrm[i]->props.trailer_len;
2629         }
2630
2631         xfrm_dst_set_child(xdst_prev, dst);
2632         xdst0->path = dst;
2633
2634         err = -ENODEV;
2635         dev = dst->dev;
2636         if (!dev)
2637                 goto free_dst;
2638
2639         xfrm_init_path(xdst0, dst, nfheader_len);
2640         xfrm_init_pmtu(bundle, nx);
2641
2642         for (xdst_prev = xdst0; xdst_prev != (struct xfrm_dst *)dst;
2643              xdst_prev = (struct xfrm_dst *) xfrm_dst_child(&xdst_prev->u.dst)) {
2644                 err = xfrm_fill_dst(xdst_prev, dev, fl);
2645                 if (err)
2646                         goto free_dst;
2647
2648                 xdst_prev->u.dst.header_len = header_len;
2649                 xdst_prev->u.dst.trailer_len = trailer_len;
2650                 header_len -= xdst_prev->u.dst.xfrm->props.header_len;
2651                 trailer_len -= xdst_prev->u.dst.xfrm->props.trailer_len;
2652         }
2653
2654         return &xdst0->u.dst;
2655
2656 put_states:
2657         for (; i < nx; i++)
2658                 xfrm_state_put(xfrm[i]);
2659 free_dst:
2660         if (xdst0)
2661                 dst_release_immediate(&xdst0->u.dst);
2662
2663         return ERR_PTR(err);
2664 }
2665
2666 static int xfrm_expand_policies(const struct flowi *fl, u16 family,
2667                                 struct xfrm_policy **pols,
2668                                 int *num_pols, int *num_xfrms)
2669 {
2670         int i;
2671
2672         if (*num_pols == 0 || !pols[0]) {
2673                 *num_pols = 0;
2674                 *num_xfrms = 0;
2675                 return 0;
2676         }
2677         if (IS_ERR(pols[0]))
2678                 return PTR_ERR(pols[0]);
2679
2680         *num_xfrms = pols[0]->xfrm_nr;
2681
2682 #ifdef CONFIG_XFRM_SUB_POLICY
2683         if (pols[0] && pols[0]->action == XFRM_POLICY_ALLOW &&
2684             pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
2685                 pols[1] = xfrm_policy_lookup_bytype(xp_net(pols[0]),
2686                                                     XFRM_POLICY_TYPE_MAIN,
2687                                                     fl, family,
2688                                                     XFRM_POLICY_OUT,
2689                                                     pols[0]->if_id);
2690                 if (pols[1]) {
2691                         if (IS_ERR(pols[1])) {
2692                                 xfrm_pols_put(pols, *num_pols);
2693                                 return PTR_ERR(pols[1]);
2694                         }
2695                         (*num_pols)++;
2696                         (*num_xfrms) += pols[1]->xfrm_nr;
2697                 }
2698         }
2699 #endif
2700         for (i = 0; i < *num_pols; i++) {
2701                 if (pols[i]->action != XFRM_POLICY_ALLOW) {
2702                         *num_xfrms = -1;
2703                         break;
2704                 }
2705         }
2706
2707         return 0;
2708
2709 }
2710
2711 static struct xfrm_dst *
2712 xfrm_resolve_and_create_bundle(struct xfrm_policy **pols, int num_pols,
2713                                const struct flowi *fl, u16 family,
2714                                struct dst_entry *dst_orig)
2715 {
2716         struct net *net = xp_net(pols[0]);
2717         struct xfrm_state *xfrm[XFRM_MAX_DEPTH];
2718         struct xfrm_dst *bundle[XFRM_MAX_DEPTH];
2719         struct xfrm_dst *xdst;
2720         struct dst_entry *dst;
2721         int err;
2722
2723         /* Try to instantiate a bundle */
2724         err = xfrm_tmpl_resolve(pols, num_pols, fl, xfrm, family);
2725         if (err <= 0) {
2726                 if (err == 0)
2727                         return NULL;
2728
2729                 if (err != -EAGAIN)
2730                         XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLERROR);
2731                 return ERR_PTR(err);
2732         }
2733
2734         dst = xfrm_bundle_create(pols[0], xfrm, bundle, err, fl, dst_orig);
2735         if (IS_ERR(dst)) {
2736                 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTBUNDLEGENERROR);
2737                 return ERR_CAST(dst);
2738         }
2739
2740         xdst = (struct xfrm_dst *)dst;
2741         xdst->num_xfrms = err;
2742         xdst->num_pols = num_pols;
2743         memcpy(xdst->pols, pols, sizeof(struct xfrm_policy *) * num_pols);
2744         xdst->policy_genid = atomic_read(&pols[0]->genid);
2745
2746         return xdst;
2747 }
2748
2749 static void xfrm_policy_queue_process(struct timer_list *t)
2750 {
2751         struct sk_buff *skb;
2752         struct sock *sk;
2753         struct dst_entry *dst;
2754         struct xfrm_policy *pol = from_timer(pol, t, polq.hold_timer);
2755         struct net *net = xp_net(pol);
2756         struct xfrm_policy_queue *pq = &pol->polq;
2757         struct flowi fl;
2758         struct sk_buff_head list;
2759
2760         spin_lock(&pq->hold_queue.lock);
2761         skb = skb_peek(&pq->hold_queue);
2762         if (!skb) {
2763                 spin_unlock(&pq->hold_queue.lock);
2764                 goto out;
2765         }
2766         dst = skb_dst(skb);
2767         sk = skb->sk;
2768         xfrm_decode_session(skb, &fl, dst->ops->family);
2769         spin_unlock(&pq->hold_queue.lock);
2770
2771         dst_hold(xfrm_dst_path(dst));
2772         dst = xfrm_lookup(net, xfrm_dst_path(dst), &fl, sk, XFRM_LOOKUP_QUEUE);
2773         if (IS_ERR(dst))
2774                 goto purge_queue;
2775
2776         if (dst->flags & DST_XFRM_QUEUE) {
2777                 dst_release(dst);
2778
2779                 if (pq->timeout >= XFRM_QUEUE_TMO_MAX)
2780                         goto purge_queue;
2781
2782                 pq->timeout = pq->timeout << 1;
2783                 if (!mod_timer(&pq->hold_timer, jiffies + pq->timeout))
2784                         xfrm_pol_hold(pol);
2785                 goto out;
2786         }
2787
2788         dst_release(dst);
2789
2790         __skb_queue_head_init(&list);
2791
2792         spin_lock(&pq->hold_queue.lock);
2793         pq->timeout = 0;
2794         skb_queue_splice_init(&pq->hold_queue, &list);
2795         spin_unlock(&pq->hold_queue.lock);
2796
2797         while (!skb_queue_empty(&list)) {
2798                 skb = __skb_dequeue(&list);
2799
2800                 xfrm_decode_session(skb, &fl, skb_dst(skb)->ops->family);
2801                 dst_hold(xfrm_dst_path(skb_dst(skb)));
2802                 dst = xfrm_lookup(net, xfrm_dst_path(skb_dst(skb)), &fl, skb->sk, 0);
2803                 if (IS_ERR(dst)) {
2804                         kfree_skb(skb);
2805                         continue;
2806                 }
2807
2808                 nf_reset_ct(skb);
2809                 skb_dst_drop(skb);
2810                 skb_dst_set(skb, dst);
2811
2812                 dst_output(net, skb->sk, skb);
2813         }
2814
2815 out:
2816         xfrm_pol_put(pol);
2817         return;
2818
2819 purge_queue:
2820         pq->timeout = 0;
2821         skb_queue_purge(&pq->hold_queue);
2822         xfrm_pol_put(pol);
2823 }
2824
2825 static int xdst_queue_output(struct net *net, struct sock *sk, struct sk_buff *skb)
2826 {
2827         unsigned long sched_next;
2828         struct dst_entry *dst = skb_dst(skb);
2829         struct xfrm_dst *xdst = (struct xfrm_dst *) dst;
2830         struct xfrm_policy *pol = xdst->pols[0];
2831         struct xfrm_policy_queue *pq = &pol->polq;
2832
2833         if (unlikely(skb_fclone_busy(sk, skb))) {
2834                 kfree_skb(skb);
2835                 return 0;
2836         }
2837
2838         if (pq->hold_queue.qlen > XFRM_MAX_QUEUE_LEN) {
2839                 kfree_skb(skb);
2840                 return -EAGAIN;
2841         }
2842
2843         skb_dst_force(skb);
2844
2845         spin_lock_bh(&pq->hold_queue.lock);
2846
2847         if (!pq->timeout)
2848                 pq->timeout = XFRM_QUEUE_TMO_MIN;
2849
2850         sched_next = jiffies + pq->timeout;
2851
2852         if (del_timer(&pq->hold_timer)) {
2853                 if (time_before(pq->hold_timer.expires, sched_next))
2854                         sched_next = pq->hold_timer.expires;
2855                 xfrm_pol_put(pol);
2856         }
2857
2858         __skb_queue_tail(&pq->hold_queue, skb);
2859         if (!mod_timer(&pq->hold_timer, sched_next))
2860                 xfrm_pol_hold(pol);
2861
2862         spin_unlock_bh(&pq->hold_queue.lock);
2863
2864         return 0;
2865 }
2866
2867 static struct xfrm_dst *xfrm_create_dummy_bundle(struct net *net,
2868                                                  struct xfrm_flo *xflo,
2869                                                  const struct flowi *fl,
2870                                                  int num_xfrms,
2871                                                  u16 family)
2872 {
2873         int err;
2874         struct net_device *dev;
2875         struct dst_entry *dst;
2876         struct dst_entry *dst1;
2877         struct xfrm_dst *xdst;
2878
2879         xdst = xfrm_alloc_dst(net, family);
2880         if (IS_ERR(xdst))
2881                 return xdst;
2882
2883         if (!(xflo->flags & XFRM_LOOKUP_QUEUE) ||
2884             net->xfrm.sysctl_larval_drop ||
2885             num_xfrms <= 0)
2886                 return xdst;
2887
2888         dst = xflo->dst_orig;
2889         dst1 = &xdst->u.dst;
2890         dst_hold(dst);
2891         xdst->route = dst;
2892
2893         dst_copy_metrics(dst1, dst);
2894
2895         dst1->obsolete = DST_OBSOLETE_FORCE_CHK;
2896         dst1->flags |= DST_HOST | DST_XFRM_QUEUE;
2897         dst1->lastuse = jiffies;
2898
2899         dst1->input = dst_discard;
2900         dst1->output = xdst_queue_output;
2901
2902         dst_hold(dst);
2903         xfrm_dst_set_child(xdst, dst);
2904         xdst->path = dst;
2905
2906         xfrm_init_path((struct xfrm_dst *)dst1, dst, 0);
2907
2908         err = -ENODEV;
2909         dev = dst->dev;
2910         if (!dev)
2911                 goto free_dst;
2912
2913         err = xfrm_fill_dst(xdst, dev, fl);
2914         if (err)
2915                 goto free_dst;
2916
2917 out:
2918         return xdst;
2919
2920 free_dst:
2921         dst_release(dst1);
2922         xdst = ERR_PTR(err);
2923         goto out;
2924 }
2925
2926 static struct xfrm_dst *xfrm_bundle_lookup(struct net *net,
2927                                            const struct flowi *fl,
2928                                            u16 family, u8 dir,
2929                                            struct xfrm_flo *xflo, u32 if_id)
2930 {
2931         struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
2932         int num_pols = 0, num_xfrms = 0, err;
2933         struct xfrm_dst *xdst;
2934
2935         /* Resolve policies to use if we couldn't get them from
2936          * previous cache entry */
2937         num_pols = 1;
2938         pols[0] = xfrm_policy_lookup(net, fl, family, dir, if_id);
2939         err = xfrm_expand_policies(fl, family, pols,
2940                                            &num_pols, &num_xfrms);
2941         if (err < 0)
2942                 goto inc_error;
2943         if (num_pols == 0)
2944                 return NULL;
2945         if (num_xfrms <= 0)
2946                 goto make_dummy_bundle;
2947
2948         xdst = xfrm_resolve_and_create_bundle(pols, num_pols, fl, family,
2949                                               xflo->dst_orig);
2950         if (IS_ERR(xdst)) {
2951                 err = PTR_ERR(xdst);
2952                 if (err == -EREMOTE) {
2953                         xfrm_pols_put(pols, num_pols);
2954                         return NULL;
2955                 }
2956
2957                 if (err != -EAGAIN)
2958                         goto error;
2959                 goto make_dummy_bundle;
2960         } else if (xdst == NULL) {
2961                 num_xfrms = 0;
2962                 goto make_dummy_bundle;
2963         }
2964
2965         return xdst;
2966
2967 make_dummy_bundle:
2968         /* We found policies, but there's no bundles to instantiate:
2969          * either because the policy blocks, has no transformations or
2970          * we could not build template (no xfrm_states).*/
2971         xdst = xfrm_create_dummy_bundle(net, xflo, fl, num_xfrms, family);
2972         if (IS_ERR(xdst)) {
2973                 xfrm_pols_put(pols, num_pols);
2974                 return ERR_CAST(xdst);
2975         }
2976         xdst->num_pols = num_pols;
2977         xdst->num_xfrms = num_xfrms;
2978         memcpy(xdst->pols, pols, sizeof(struct xfrm_policy *) * num_pols);
2979
2980         return xdst;
2981
2982 inc_error:
2983         XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLERROR);
2984 error:
2985         xfrm_pols_put(pols, num_pols);
2986         return ERR_PTR(err);
2987 }
2988
2989 static struct dst_entry *make_blackhole(struct net *net, u16 family,
2990                                         struct dst_entry *dst_orig)
2991 {
2992         const struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
2993         struct dst_entry *ret;
2994
2995         if (!afinfo) {
2996                 dst_release(dst_orig);
2997                 return ERR_PTR(-EINVAL);
2998         } else {
2999                 ret = afinfo->blackhole_route(net, dst_orig);
3000         }
3001         rcu_read_unlock();
3002
3003         return ret;
3004 }
3005
3006 /* Finds/creates a bundle for given flow and if_id
3007  *
3008  * At the moment we eat a raw IP route. Mostly to speed up lookups
3009  * on interfaces with disabled IPsec.
3010  *
3011  * xfrm_lookup uses an if_id of 0 by default, and is provided for
3012  * compatibility
3013  */
3014 struct dst_entry *xfrm_lookup_with_ifid(struct net *net,
3015                                         struct dst_entry *dst_orig,
3016                                         const struct flowi *fl,
3017                                         const struct sock *sk,
3018                                         int flags, u32 if_id)
3019 {
3020         struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
3021         struct xfrm_dst *xdst;
3022         struct dst_entry *dst, *route;
3023         u16 family = dst_orig->ops->family;
3024         u8 dir = XFRM_POLICY_OUT;
3025         int i, err, num_pols, num_xfrms = 0, drop_pols = 0;
3026
3027         dst = NULL;
3028         xdst = NULL;
3029         route = NULL;
3030
3031         sk = sk_const_to_full_sk(sk);
3032         if (sk && sk->sk_policy[XFRM_POLICY_OUT]) {
3033                 num_pols = 1;
3034                 pols[0] = xfrm_sk_policy_lookup(sk, XFRM_POLICY_OUT, fl, family,
3035                                                 if_id);
3036                 err = xfrm_expand_policies(fl, family, pols,
3037                                            &num_pols, &num_xfrms);
3038                 if (err < 0)
3039                         goto dropdst;
3040
3041                 if (num_pols) {
3042                         if (num_xfrms <= 0) {
3043                                 drop_pols = num_pols;
3044                                 goto no_transform;
3045                         }
3046
3047                         xdst = xfrm_resolve_and_create_bundle(
3048                                         pols, num_pols, fl,
3049                                         family, dst_orig);
3050
3051                         if (IS_ERR(xdst)) {
3052                                 xfrm_pols_put(pols, num_pols);
3053                                 err = PTR_ERR(xdst);
3054                                 if (err == -EREMOTE)
3055                                         goto nopol;
3056
3057                                 goto dropdst;
3058                         } else if (xdst == NULL) {
3059                                 num_xfrms = 0;
3060                                 drop_pols = num_pols;
3061                                 goto no_transform;
3062                         }
3063
3064                         route = xdst->route;
3065                 }
3066         }
3067
3068         if (xdst == NULL) {
3069                 struct xfrm_flo xflo;
3070
3071                 xflo.dst_orig = dst_orig;
3072                 xflo.flags = flags;
3073
3074                 /* To accelerate a bit...  */
3075                 if ((dst_orig->flags & DST_NOXFRM) ||
3076                     !net->xfrm.policy_count[XFRM_POLICY_OUT])
3077                         goto nopol;
3078
3079                 xdst = xfrm_bundle_lookup(net, fl, family, dir, &xflo, if_id);
3080                 if (xdst == NULL)
3081                         goto nopol;
3082                 if (IS_ERR(xdst)) {
3083                         err = PTR_ERR(xdst);
3084                         goto dropdst;
3085                 }
3086
3087                 num_pols = xdst->num_pols;
3088                 num_xfrms = xdst->num_xfrms;
3089                 memcpy(pols, xdst->pols, sizeof(struct xfrm_policy *) * num_pols);
3090                 route = xdst->route;
3091         }
3092
3093         dst = &xdst->u.dst;
3094         if (route == NULL && num_xfrms > 0) {
3095                 /* The only case when xfrm_bundle_lookup() returns a
3096                  * bundle with null route, is when the template could
3097                  * not be resolved. It means policies are there, but
3098                  * bundle could not be created, since we don't yet
3099                  * have the xfrm_state's. We need to wait for KM to
3100                  * negotiate new SA's or bail out with error.*/
3101                 if (net->xfrm.sysctl_larval_drop) {
3102                         XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTNOSTATES);
3103                         err = -EREMOTE;
3104                         goto error;
3105                 }
3106
3107                 err = -EAGAIN;
3108
3109                 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTNOSTATES);
3110                 goto error;
3111         }
3112
3113 no_transform:
3114         if (num_pols == 0)
3115                 goto nopol;
3116
3117         if ((flags & XFRM_LOOKUP_ICMP) &&
3118             !(pols[0]->flags & XFRM_POLICY_ICMP)) {
3119                 err = -ENOENT;
3120                 goto error;
3121         }
3122
3123         for (i = 0; i < num_pols; i++)
3124                 pols[i]->curlft.use_time = ktime_get_real_seconds();
3125
3126         if (num_xfrms < 0) {
3127                 /* Prohibit the flow */
3128                 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLBLOCK);
3129                 err = -EPERM;
3130                 goto error;
3131         } else if (num_xfrms > 0) {
3132                 /* Flow transformed */
3133                 dst_release(dst_orig);
3134         } else {
3135                 /* Flow passes untransformed */
3136                 dst_release(dst);
3137                 dst = dst_orig;
3138         }
3139 ok:
3140         xfrm_pols_put(pols, drop_pols);
3141         if (dst && dst->xfrm &&
3142             dst->xfrm->props.mode == XFRM_MODE_TUNNEL)
3143                 dst->flags |= DST_XFRM_TUNNEL;
3144         return dst;
3145
3146 nopol:
3147         if (!(flags & XFRM_LOOKUP_ICMP)) {
3148                 dst = dst_orig;
3149                 goto ok;
3150         }
3151         err = -ENOENT;
3152 error:
3153         dst_release(dst);
3154 dropdst:
3155         if (!(flags & XFRM_LOOKUP_KEEP_DST_REF))
3156                 dst_release(dst_orig);
3157         xfrm_pols_put(pols, drop_pols);
3158         return ERR_PTR(err);
3159 }
3160 EXPORT_SYMBOL(xfrm_lookup_with_ifid);
3161
3162 /* Main function: finds/creates a bundle for given flow.
3163  *
3164  * At the moment we eat a raw IP route. Mostly to speed up lookups
3165  * on interfaces with disabled IPsec.
3166  */
3167 struct dst_entry *xfrm_lookup(struct net *net, struct dst_entry *dst_orig,
3168                               const struct flowi *fl, const struct sock *sk,
3169                               int flags)
3170 {
3171         return xfrm_lookup_with_ifid(net, dst_orig, fl, sk, flags, 0);
3172 }
3173 EXPORT_SYMBOL(xfrm_lookup);
3174
3175 /* Callers of xfrm_lookup_route() must ensure a call to dst_output().
3176  * Otherwise we may send out blackholed packets.
3177  */
3178 struct dst_entry *xfrm_lookup_route(struct net *net, struct dst_entry *dst_orig,
3179                                     const struct flowi *fl,
3180                                     const struct sock *sk, int flags)
3181 {
3182         struct dst_entry *dst = xfrm_lookup(net, dst_orig, fl, sk,
3183                                             flags | XFRM_LOOKUP_QUEUE |
3184                                             XFRM_LOOKUP_KEEP_DST_REF);
3185
3186         if (IS_ERR(dst) && PTR_ERR(dst) == -EREMOTE)
3187                 return make_blackhole(net, dst_orig->ops->family, dst_orig);
3188
3189         if (IS_ERR(dst))
3190                 dst_release(dst_orig);
3191
3192         return dst;
3193 }
3194 EXPORT_SYMBOL(xfrm_lookup_route);
3195
3196 static inline int
3197 xfrm_secpath_reject(int idx, struct sk_buff *skb, const struct flowi *fl)
3198 {
3199         struct sec_path *sp = skb_sec_path(skb);
3200         struct xfrm_state *x;
3201
3202         if (!sp || idx < 0 || idx >= sp->len)
3203                 return 0;
3204         x = sp->xvec[idx];
3205         if (!x->type->reject)
3206                 return 0;
3207         return x->type->reject(x, skb, fl);
3208 }
3209
3210 /* When skb is transformed back to its "native" form, we have to
3211  * check policy restrictions. At the moment we make this in maximally
3212  * stupid way. Shame on me. :-) Of course, connected sockets must
3213  * have policy cached at them.
3214  */
3215
3216 static inline int
3217 xfrm_state_ok(const struct xfrm_tmpl *tmpl, const struct xfrm_state *x,
3218               unsigned short family)
3219 {
3220         if (xfrm_state_kern(x))
3221                 return tmpl->optional && !xfrm_state_addr_cmp(tmpl, x, tmpl->encap_family);
3222         return  x->id.proto == tmpl->id.proto &&
3223                 (x->id.spi == tmpl->id.spi || !tmpl->id.spi) &&
3224                 (x->props.reqid == tmpl->reqid || !tmpl->reqid) &&
3225                 x->props.mode == tmpl->mode &&
3226                 (tmpl->allalgs || (tmpl->aalgos & (1<<x->props.aalgo)) ||
3227                  !(xfrm_id_proto_match(tmpl->id.proto, IPSEC_PROTO_ANY))) &&
3228                 !(x->props.mode != XFRM_MODE_TRANSPORT &&
3229                   xfrm_state_addr_cmp(tmpl, x, family));
3230 }
3231
3232 /*
3233  * 0 or more than 0 is returned when validation is succeeded (either bypass
3234  * because of optional transport mode, or next index of the mathced secpath
3235  * state with the template.
3236  * -1 is returned when no matching template is found.
3237  * Otherwise "-2 - errored_index" is returned.
3238  */
3239 static inline int
3240 xfrm_policy_ok(const struct xfrm_tmpl *tmpl, const struct sec_path *sp, int start,
3241                unsigned short family)
3242 {
3243         int idx = start;
3244
3245         if (tmpl->optional) {
3246                 if (tmpl->mode == XFRM_MODE_TRANSPORT)
3247                         return start;
3248         } else
3249                 start = -1;
3250         for (; idx < sp->len; idx++) {
3251                 if (xfrm_state_ok(tmpl, sp->xvec[idx], family))
3252                         return ++idx;
3253                 if (sp->xvec[idx]->props.mode != XFRM_MODE_TRANSPORT) {
3254                         if (start == -1)
3255                                 start = -2-idx;
3256                         break;
3257                 }
3258         }
3259         return start;
3260 }
3261
3262 static void
3263 decode_session4(struct sk_buff *skb, struct flowi *fl, bool reverse)
3264 {
3265         const struct iphdr *iph = ip_hdr(skb);
3266         int ihl = iph->ihl;
3267         u8 *xprth = skb_network_header(skb) + ihl * 4;
3268         struct flowi4 *fl4 = &fl->u.ip4;
3269         int oif = 0;
3270
3271         if (skb_dst(skb) && skb_dst(skb)->dev)
3272                 oif = skb_dst(skb)->dev->ifindex;
3273
3274         memset(fl4, 0, sizeof(struct flowi4));
3275         fl4->flowi4_mark = skb->mark;
3276         fl4->flowi4_oif = reverse ? skb->skb_iif : oif;
3277
3278         fl4->flowi4_proto = iph->protocol;
3279         fl4->daddr = reverse ? iph->saddr : iph->daddr;
3280         fl4->saddr = reverse ? iph->daddr : iph->saddr;
3281         fl4->flowi4_tos = iph->tos;
3282
3283         if (!ip_is_fragment(iph)) {
3284                 switch (iph->protocol) {
3285                 case IPPROTO_UDP:
3286                 case IPPROTO_UDPLITE:
3287                 case IPPROTO_TCP:
3288                 case IPPROTO_SCTP:
3289                 case IPPROTO_DCCP:
3290                         if (xprth + 4 < skb->data ||
3291                             pskb_may_pull(skb, xprth + 4 - skb->data)) {
3292                                 __be16 *ports;
3293
3294                                 xprth = skb_network_header(skb) + ihl * 4;
3295                                 ports = (__be16 *)xprth;
3296
3297                                 fl4->fl4_sport = ports[!!reverse];
3298                                 fl4->fl4_dport = ports[!reverse];
3299                         }
3300                         break;
3301                 case IPPROTO_ICMP:
3302                         if (xprth + 2 < skb->data ||
3303                             pskb_may_pull(skb, xprth + 2 - skb->data)) {
3304                                 u8 *icmp;
3305
3306                                 xprth = skb_network_header(skb) + ihl * 4;
3307                                 icmp = xprth;
3308
3309                                 fl4->fl4_icmp_type = icmp[0];
3310                                 fl4->fl4_icmp_code = icmp[1];
3311                         }
3312                         break;
3313                 case IPPROTO_ESP:
3314                         if (xprth + 4 < skb->data ||
3315                             pskb_may_pull(skb, xprth + 4 - skb->data)) {
3316                                 __be32 *ehdr;
3317
3318                                 xprth = skb_network_header(skb) + ihl * 4;
3319                                 ehdr = (__be32 *)xprth;
3320
3321                                 fl4->fl4_ipsec_spi = ehdr[0];
3322                         }
3323                         break;
3324                 case IPPROTO_AH:
3325                         if (xprth + 8 < skb->data ||
3326                             pskb_may_pull(skb, xprth + 8 - skb->data)) {
3327                                 __be32 *ah_hdr;
3328
3329                                 xprth = skb_network_header(skb) + ihl * 4;
3330                                 ah_hdr = (__be32 *)xprth;
3331
3332                                 fl4->fl4_ipsec_spi = ah_hdr[1];
3333                         }
3334                         break;
3335                 case IPPROTO_COMP:
3336                         if (xprth + 4 < skb->data ||
3337                             pskb_may_pull(skb, xprth + 4 - skb->data)) {
3338                                 __be16 *ipcomp_hdr;
3339
3340                                 xprth = skb_network_header(skb) + ihl * 4;
3341                                 ipcomp_hdr = (__be16 *)xprth;
3342
3343                                 fl4->fl4_ipsec_spi = htonl(ntohs(ipcomp_hdr[1]));
3344                         }
3345                         break;
3346                 case IPPROTO_GRE:
3347                         if (xprth + 12 < skb->data ||
3348                             pskb_may_pull(skb, xprth + 12 - skb->data)) {
3349                                 __be16 *greflags;
3350                                 __be32 *gre_hdr;
3351
3352                                 xprth = skb_network_header(skb) + ihl * 4;
3353                                 greflags = (__be16 *)xprth;
3354                                 gre_hdr = (__be32 *)xprth;
3355
3356                                 if (greflags[0] & GRE_KEY) {
3357                                         if (greflags[0] & GRE_CSUM)
3358                                                 gre_hdr++;
3359                                         fl4->fl4_gre_key = gre_hdr[1];
3360                                 }
3361                         }
3362                         break;
3363                 default:
3364                         fl4->fl4_ipsec_spi = 0;
3365                         break;
3366                 }
3367         }
3368 }
3369
3370 #if IS_ENABLED(CONFIG_IPV6)
3371 static void
3372 decode_session6(struct sk_buff *skb, struct flowi *fl, bool reverse)
3373 {
3374         struct flowi6 *fl6 = &fl->u.ip6;
3375         int onlyproto = 0;
3376         const struct ipv6hdr *hdr = ipv6_hdr(skb);
3377         u32 offset = sizeof(*hdr);
3378         struct ipv6_opt_hdr *exthdr;
3379         const unsigned char *nh = skb_network_header(skb);
3380         u16 nhoff = IP6CB(skb)->nhoff;
3381         int oif = 0;
3382         u8 nexthdr;
3383
3384         if (!nhoff)
3385                 nhoff = offsetof(struct ipv6hdr, nexthdr);
3386
3387         nexthdr = nh[nhoff];
3388
3389         if (skb_dst(skb) && skb_dst(skb)->dev)
3390                 oif = skb_dst(skb)->dev->ifindex;
3391
3392         memset(fl6, 0, sizeof(struct flowi6));
3393         fl6->flowi6_mark = skb->mark;
3394         fl6->flowi6_oif = reverse ? skb->skb_iif : oif;
3395
3396         fl6->daddr = reverse ? hdr->saddr : hdr->daddr;
3397         fl6->saddr = reverse ? hdr->daddr : hdr->saddr;
3398
3399         while (nh + offset + sizeof(*exthdr) < skb->data ||
3400                pskb_may_pull(skb, nh + offset + sizeof(*exthdr) - skb->data)) {
3401                 nh = skb_network_header(skb);
3402                 exthdr = (struct ipv6_opt_hdr *)(nh + offset);
3403
3404                 switch (nexthdr) {
3405                 case NEXTHDR_FRAGMENT:
3406                         onlyproto = 1;
3407                         /* fall through */
3408                 case NEXTHDR_ROUTING:
3409                 case NEXTHDR_HOP:
3410                 case NEXTHDR_DEST:
3411                         offset += ipv6_optlen(exthdr);
3412                         nexthdr = exthdr->nexthdr;
3413                         exthdr = (struct ipv6_opt_hdr *)(nh + offset);
3414                         break;
3415                 case IPPROTO_UDP:
3416                 case IPPROTO_UDPLITE:
3417                 case IPPROTO_TCP:
3418                 case IPPROTO_SCTP:
3419                 case IPPROTO_DCCP:
3420                         if (!onlyproto && (nh + offset + 4 < skb->data ||
3421                              pskb_may_pull(skb, nh + offset + 4 - skb->data))) {
3422                                 __be16 *ports;
3423
3424                                 nh = skb_network_header(skb);
3425                                 ports = (__be16 *)(nh + offset);
3426                                 fl6->fl6_sport = ports[!!reverse];
3427                                 fl6->fl6_dport = ports[!reverse];
3428                         }
3429                         fl6->flowi6_proto = nexthdr;
3430                         return;
3431                 case IPPROTO_ICMPV6:
3432                         if (!onlyproto && (nh + offset + 2 < skb->data ||
3433                             pskb_may_pull(skb, nh + offset + 2 - skb->data))) {
3434                                 u8 *icmp;
3435
3436                                 nh = skb_network_header(skb);
3437                                 icmp = (u8 *)(nh + offset);
3438                                 fl6->fl6_icmp_type = icmp[0];
3439                                 fl6->fl6_icmp_code = icmp[1];
3440                         }
3441                         fl6->flowi6_proto = nexthdr;
3442                         return;
3443 #if IS_ENABLED(CONFIG_IPV6_MIP6)
3444                 case IPPROTO_MH:
3445                         offset += ipv6_optlen(exthdr);
3446                         if (!onlyproto && (nh + offset + 3 < skb->data ||
3447                             pskb_may_pull(skb, nh + offset + 3 - skb->data))) {
3448                                 struct ip6_mh *mh;
3449
3450                                 nh = skb_network_header(skb);
3451                                 mh = (struct ip6_mh *)(nh + offset);
3452                                 fl6->fl6_mh_type = mh->ip6mh_type;
3453                         }
3454                         fl6->flowi6_proto = nexthdr;
3455                         return;
3456 #endif
3457                 /* XXX Why are there these headers? */
3458                 case IPPROTO_AH:
3459                 case IPPROTO_ESP:
3460                 case IPPROTO_COMP:
3461                 default:
3462                         fl6->fl6_ipsec_spi = 0;
3463                         fl6->flowi6_proto = nexthdr;
3464                         return;
3465                 }
3466         }
3467 }
3468 #endif
3469
3470 int __xfrm_decode_session(struct sk_buff *skb, struct flowi *fl,
3471                           unsigned int family, int reverse)
3472 {
3473         switch (family) {
3474         case AF_INET:
3475                 decode_session4(skb, fl, reverse);
3476                 break;
3477 #if IS_ENABLED(CONFIG_IPV6)
3478         case AF_INET6:
3479                 decode_session6(skb, fl, reverse);
3480                 break;
3481 #endif
3482         default:
3483                 return -EAFNOSUPPORT;
3484         }
3485
3486         return security_xfrm_decode_session(skb, &fl->flowi_secid);
3487 }
3488 EXPORT_SYMBOL(__xfrm_decode_session);
3489
3490 static inline int secpath_has_nontransport(const struct sec_path *sp, int k, int *idxp)
3491 {
3492         for (; k < sp->len; k++) {
3493                 if (sp->xvec[k]->props.mode != XFRM_MODE_TRANSPORT) {
3494                         *idxp = k;
3495                         return 1;
3496                 }
3497         }
3498
3499         return 0;
3500 }
3501
3502 int __xfrm_policy_check(struct sock *sk, int dir, struct sk_buff *skb,
3503                         unsigned short family)
3504 {
3505         struct net *net = dev_net(skb->dev);
3506         struct xfrm_policy *pol;
3507         struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
3508         int npols = 0;
3509         int xfrm_nr;
3510         int pi;
3511         int reverse;
3512         struct flowi fl;
3513         int xerr_idx = -1;
3514         const struct xfrm_if_cb *ifcb;
3515         struct sec_path *sp;
3516         struct xfrm_if *xi;
3517         u32 if_id = 0;
3518
3519         rcu_read_lock();
3520         ifcb = xfrm_if_get_cb();
3521
3522         if (ifcb) {
3523                 xi = ifcb->decode_session(skb, family);
3524                 if (xi) {
3525                         if_id = xi->p.if_id;
3526                         net = xi->net;
3527                 }
3528         }
3529         rcu_read_unlock();
3530
3531         reverse = dir & ~XFRM_POLICY_MASK;
3532         dir &= XFRM_POLICY_MASK;
3533
3534         if (__xfrm_decode_session(skb, &fl, family, reverse) < 0) {
3535                 XFRM_INC_STATS(net, LINUX_MIB_XFRMINHDRERROR);
3536                 return 0;
3537         }
3538
3539         nf_nat_decode_session(skb, &fl, family);
3540
3541         /* First, check used SA against their selectors. */
3542         sp = skb_sec_path(skb);
3543         if (sp) {
3544                 int i;
3545
3546                 for (i = sp->len - 1; i >= 0; i--) {
3547                         struct xfrm_state *x = sp->xvec[i];
3548                         if (!xfrm_selector_match(&x->sel, &fl, family)) {
3549                                 XFRM_INC_STATS(net, LINUX_MIB_XFRMINSTATEMISMATCH);
3550                                 return 0;
3551                         }
3552                 }
3553         }
3554
3555         pol = NULL;
3556         sk = sk_to_full_sk(sk);
3557         if (sk && sk->sk_policy[dir]) {
3558                 pol = xfrm_sk_policy_lookup(sk, dir, &fl, family, if_id);
3559                 if (IS_ERR(pol)) {
3560                         XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
3561                         return 0;
3562                 }
3563         }
3564
3565         if (!pol)
3566                 pol = xfrm_policy_lookup(net, &fl, family, dir, if_id);
3567
3568         if (IS_ERR(pol)) {
3569                 XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
3570                 return 0;
3571         }
3572
3573         if (!pol) {
3574                 if (sp && secpath_has_nontransport(sp, 0, &xerr_idx)) {
3575                         xfrm_secpath_reject(xerr_idx, skb, &fl);
3576                         XFRM_INC_STATS(net, LINUX_MIB_XFRMINNOPOLS);
3577                         return 0;
3578                 }
3579                 return 1;
3580         }
3581
3582         pol->curlft.use_time = ktime_get_real_seconds();
3583
3584         pols[0] = pol;
3585         npols++;
3586 #ifdef CONFIG_XFRM_SUB_POLICY
3587         if (pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
3588                 pols[1] = xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_MAIN,
3589                                                     &fl, family,
3590                                                     XFRM_POLICY_IN, if_id);
3591                 if (pols[1]) {
3592                         if (IS_ERR(pols[1])) {
3593                                 XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
3594                                 return 0;
3595                         }
3596                         pols[1]->curlft.use_time = ktime_get_real_seconds();
3597                         npols++;
3598                 }
3599         }
3600 #endif
3601
3602         if (pol->action == XFRM_POLICY_ALLOW) {
3603                 static struct sec_path dummy;
3604                 struct xfrm_tmpl *tp[XFRM_MAX_DEPTH];
3605                 struct xfrm_tmpl *stp[XFRM_MAX_DEPTH];
3606                 struct xfrm_tmpl **tpp = tp;
3607                 int ti = 0;
3608                 int i, k;
3609
3610                 sp = skb_sec_path(skb);
3611                 if (!sp)
3612                         sp = &dummy;
3613
3614                 for (pi = 0; pi < npols; pi++) {
3615                         if (pols[pi] != pol &&
3616                             pols[pi]->action != XFRM_POLICY_ALLOW) {
3617                                 XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLBLOCK);
3618                                 goto reject;
3619                         }
3620                         if (ti + pols[pi]->xfrm_nr >= XFRM_MAX_DEPTH) {
3621                                 XFRM_INC_STATS(net, LINUX_MIB_XFRMINBUFFERERROR);
3622                                 goto reject_error;
3623                         }
3624                         for (i = 0; i < pols[pi]->xfrm_nr; i++)
3625                                 tpp[ti++] = &pols[pi]->xfrm_vec[i];
3626                 }
3627                 xfrm_nr = ti;
3628                 if (npols > 1) {
3629                         xfrm_tmpl_sort(stp, tpp, xfrm_nr, family);
3630                         tpp = stp;
3631                 }
3632
3633                 /* For each tunnel xfrm, find the first matching tmpl.
3634                  * For each tmpl before that, find corresponding xfrm.
3635                  * Order is _important_. Later we will implement
3636                  * some barriers, but at the moment barriers
3637                  * are implied between each two transformations.
3638                  */
3639                 for (i = xfrm_nr-1, k = 0; i >= 0; i--) {
3640                         k = xfrm_policy_ok(tpp[i], sp, k, family);
3641                         if (k < 0) {
3642                                 if (k < -1)
3643                                         /* "-2 - errored_index" returned */
3644                                         xerr_idx = -(2+k);
3645                                 XFRM_INC_STATS(net, LINUX_MIB_XFRMINTMPLMISMATCH);
3646                                 goto reject;
3647                         }
3648                 }
3649
3650                 if (secpath_has_nontransport(sp, k, &xerr_idx)) {
3651                         XFRM_INC_STATS(net, LINUX_MIB_XFRMINTMPLMISMATCH);
3652                         goto reject;
3653                 }
3654
3655                 xfrm_pols_put(pols, npols);
3656                 return 1;
3657         }
3658         XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLBLOCK);
3659
3660 reject:
3661         xfrm_secpath_reject(xerr_idx, skb, &fl);
3662 reject_error:
3663         xfrm_pols_put(pols, npols);
3664         return 0;
3665 }
3666 EXPORT_SYMBOL(__xfrm_policy_check);
3667
3668 int __xfrm_route_forward(struct sk_buff *skb, unsigned short family)
3669 {
3670         struct net *net = dev_net(skb->dev);
3671         struct flowi fl;
3672         struct dst_entry *dst;
3673         int res = 1;
3674
3675         if (xfrm_decode_session(skb, &fl, family) < 0) {
3676                 XFRM_INC_STATS(net, LINUX_MIB_XFRMFWDHDRERROR);
3677                 return 0;
3678         }
3679
3680         skb_dst_force(skb);
3681         if (!skb_dst(skb)) {
3682                 XFRM_INC_STATS(net, LINUX_MIB_XFRMFWDHDRERROR);
3683                 return 0;
3684         }
3685
3686         dst = xfrm_lookup(net, skb_dst(skb), &fl, NULL, XFRM_LOOKUP_QUEUE);
3687         if (IS_ERR(dst)) {
3688                 res = 0;
3689                 dst = NULL;
3690         }
3691         skb_dst_set(skb, dst);
3692         return res;
3693 }
3694 EXPORT_SYMBOL(__xfrm_route_forward);
3695
3696 /* Optimize later using cookies and generation ids. */
3697
3698 static struct dst_entry *xfrm_dst_check(struct dst_entry *dst, u32 cookie)
3699 {
3700         /* Code (such as __xfrm4_bundle_create()) sets dst->obsolete
3701          * to DST_OBSOLETE_FORCE_CHK to force all XFRM destinations to
3702          * get validated by dst_ops->check on every use.  We do this
3703          * because when a normal route referenced by an XFRM dst is
3704          * obsoleted we do not go looking around for all parent
3705          * referencing XFRM dsts so that we can invalidate them.  It
3706          * is just too much work.  Instead we make the checks here on
3707          * every use.  For example:
3708          *
3709          *      XFRM dst A --> IPv4 dst X
3710          *
3711          * X is the "xdst->route" of A (X is also the "dst->path" of A
3712          * in this example).  If X is marked obsolete, "A" will not
3713          * notice.  That's what we are validating here via the
3714          * stale_bundle() check.
3715          *
3716          * When a dst is removed from the fib tree, DST_OBSOLETE_DEAD will
3717          * be marked on it.
3718          * This will force stale_bundle() to fail on any xdst bundle with
3719          * this dst linked in it.
3720          */
3721         if (dst->obsolete < 0 && !stale_bundle(dst))
3722                 return dst;
3723
3724         return NULL;
3725 }
3726
3727 static int stale_bundle(struct dst_entry *dst)
3728 {
3729         return !xfrm_bundle_ok((struct xfrm_dst *)dst);
3730 }
3731
3732 void xfrm_dst_ifdown(struct dst_entry *dst, struct net_device *dev)
3733 {
3734         while ((dst = xfrm_dst_child(dst)) && dst->xfrm && dst->dev == dev) {
3735                 dst->dev = dev_net(dev)->loopback_dev;
3736                 dev_hold(dst->dev);
3737                 dev_put(dev);
3738         }
3739 }
3740 EXPORT_SYMBOL(xfrm_dst_ifdown);
3741
3742 static void xfrm_link_failure(struct sk_buff *skb)
3743 {
3744         /* Impossible. Such dst must be popped before reaches point of failure. */
3745 }
3746
3747 static struct dst_entry *xfrm_negative_advice(struct dst_entry *dst)
3748 {
3749         if (dst) {
3750                 if (dst->obsolete) {
3751                         dst_release(dst);
3752                         dst = NULL;
3753                 }
3754         }
3755         return dst;
3756 }
3757
3758 static void xfrm_init_pmtu(struct xfrm_dst **bundle, int nr)
3759 {
3760         while (nr--) {
3761                 struct xfrm_dst *xdst = bundle[nr];
3762                 u32 pmtu, route_mtu_cached;
3763                 struct dst_entry *dst;
3764
3765                 dst = &xdst->u.dst;
3766                 pmtu = dst_mtu(xfrm_dst_child(dst));
3767                 xdst->child_mtu_cached = pmtu;
3768
3769                 pmtu = xfrm_state_mtu(dst->xfrm, pmtu);
3770
3771                 route_mtu_cached = dst_mtu(xdst->route);
3772                 xdst->route_mtu_cached = route_mtu_cached;
3773
3774                 if (pmtu > route_mtu_cached)
3775                         pmtu = route_mtu_cached;
3776
3777                 dst_metric_set(dst, RTAX_MTU, pmtu);
3778         }
3779 }
3780
3781 /* Check that the bundle accepts the flow and its components are
3782  * still valid.
3783  */
3784
3785 static int xfrm_bundle_ok(struct xfrm_dst *first)
3786 {
3787         struct xfrm_dst *bundle[XFRM_MAX_DEPTH];
3788         struct dst_entry *dst = &first->u.dst;
3789         struct xfrm_dst *xdst;
3790         int start_from, nr;
3791         u32 mtu;
3792
3793         if (!dst_check(xfrm_dst_path(dst), ((struct xfrm_dst *)dst)->path_cookie) ||
3794             (dst->dev && !netif_running(dst->dev)))
3795                 return 0;
3796
3797         if (dst->flags & DST_XFRM_QUEUE)
3798                 return 1;
3799
3800         start_from = nr = 0;
3801         do {
3802                 struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
3803
3804                 if (dst->xfrm->km.state != XFRM_STATE_VALID)
3805                         return 0;
3806                 if (xdst->xfrm_genid != dst->xfrm->genid)
3807                         return 0;
3808                 if (xdst->num_pols > 0 &&
3809                     xdst->policy_genid != atomic_read(&xdst->pols[0]->genid))
3810                         return 0;
3811
3812                 bundle[nr++] = xdst;
3813
3814                 mtu = dst_mtu(xfrm_dst_child(dst));
3815                 if (xdst->child_mtu_cached != mtu) {
3816                         start_from = nr;
3817                         xdst->child_mtu_cached = mtu;
3818                 }
3819
3820                 if (!dst_check(xdst->route, xdst->route_cookie))
3821                         return 0;
3822                 mtu = dst_mtu(xdst->route);
3823                 if (xdst->route_mtu_cached != mtu) {
3824                         start_from = nr;
3825                         xdst->route_mtu_cached = mtu;
3826                 }
3827
3828                 dst = xfrm_dst_child(dst);
3829         } while (dst->xfrm);
3830
3831         if (likely(!start_from))
3832                 return 1;
3833
3834         xdst = bundle[start_from - 1];
3835         mtu = xdst->child_mtu_cached;
3836         while (start_from--) {
3837                 dst = &xdst->u.dst;
3838
3839                 mtu = xfrm_state_mtu(dst->xfrm, mtu);
3840                 if (mtu > xdst->route_mtu_cached)
3841                         mtu = xdst->route_mtu_cached;
3842                 dst_metric_set(dst, RTAX_MTU, mtu);
3843                 if (!start_from)
3844                         break;
3845
3846                 xdst = bundle[start_from - 1];
3847                 xdst->child_mtu_cached = mtu;
3848         }
3849
3850         return 1;
3851 }
3852
3853 static unsigned int xfrm_default_advmss(const struct dst_entry *dst)
3854 {
3855         return dst_metric_advmss(xfrm_dst_path(dst));
3856 }
3857
3858 static unsigned int xfrm_mtu(const struct dst_entry *dst)
3859 {
3860         unsigned int mtu = dst_metric_raw(dst, RTAX_MTU);
3861
3862         return mtu ? : dst_mtu(xfrm_dst_path(dst));
3863 }
3864
3865 static const void *xfrm_get_dst_nexthop(const struct dst_entry *dst,
3866                                         const void *daddr)
3867 {
3868         while (dst->xfrm) {
3869                 const struct xfrm_state *xfrm = dst->xfrm;
3870
3871                 dst = xfrm_dst_child(dst);
3872
3873                 if (xfrm->props.mode == XFRM_MODE_TRANSPORT)
3874                         continue;
3875                 if (xfrm->type->flags & XFRM_TYPE_REMOTE_COADDR)
3876                         daddr = xfrm->coaddr;
3877                 else if (!(xfrm->type->flags & XFRM_TYPE_LOCAL_COADDR))
3878                         daddr = &xfrm->id.daddr;
3879         }
3880         return daddr;
3881 }
3882
3883 static struct neighbour *xfrm_neigh_lookup(const struct dst_entry *dst,
3884                                            struct sk_buff *skb,
3885                                            const void *daddr)
3886 {
3887         const struct dst_entry *path = xfrm_dst_path(dst);
3888
3889         if (!skb)
3890                 daddr = xfrm_get_dst_nexthop(dst, daddr);
3891         return path->ops->neigh_lookup(path, skb, daddr);
3892 }
3893
3894 static void xfrm_confirm_neigh(const struct dst_entry *dst, const void *daddr)
3895 {
3896         const struct dst_entry *path = xfrm_dst_path(dst);
3897
3898         daddr = xfrm_get_dst_nexthop(dst, daddr);
3899         path->ops->confirm_neigh(path, daddr);
3900 }
3901
3902 int xfrm_policy_register_afinfo(const struct xfrm_policy_afinfo *afinfo, int family)
3903 {
3904         int err = 0;
3905
3906         if (WARN_ON(family >= ARRAY_SIZE(xfrm_policy_afinfo)))
3907                 return -EAFNOSUPPORT;
3908
3909         spin_lock(&xfrm_policy_afinfo_lock);
3910         if (unlikely(xfrm_policy_afinfo[family] != NULL))
3911                 err = -EEXIST;
3912         else {
3913                 struct dst_ops *dst_ops = afinfo->dst_ops;
3914                 if (likely(dst_ops->kmem_cachep == NULL))
3915                         dst_ops->kmem_cachep = xfrm_dst_cache;
3916                 if (likely(dst_ops->check == NULL))
3917                         dst_ops->check = xfrm_dst_check;
3918                 if (likely(dst_ops->default_advmss == NULL))
3919                         dst_ops->default_advmss = xfrm_default_advmss;
3920                 if (likely(dst_ops->mtu == NULL))
3921                         dst_ops->mtu = xfrm_mtu;
3922                 if (likely(dst_ops->negative_advice == NULL))
3923                         dst_ops->negative_advice = xfrm_negative_advice;
3924                 if (likely(dst_ops->link_failure == NULL))
3925                         dst_ops->link_failure = xfrm_link_failure;
3926                 if (likely(dst_ops->neigh_lookup == NULL))
3927                         dst_ops->neigh_lookup = xfrm_neigh_lookup;
3928                 if (likely(!dst_ops->confirm_neigh))
3929                         dst_ops->confirm_neigh = xfrm_confirm_neigh;
3930                 rcu_assign_pointer(xfrm_policy_afinfo[family], afinfo);
3931         }
3932         spin_unlock(&xfrm_policy_afinfo_lock);
3933
3934         return err;
3935 }
3936 EXPORT_SYMBOL(xfrm_policy_register_afinfo);
3937
3938 void xfrm_policy_unregister_afinfo(const struct xfrm_policy_afinfo *afinfo)
3939 {
3940         struct dst_ops *dst_ops = afinfo->dst_ops;
3941         int i;
3942
3943         for (i = 0; i < ARRAY_SIZE(xfrm_policy_afinfo); i++) {
3944                 if (xfrm_policy_afinfo[i] != afinfo)
3945                         continue;
3946                 RCU_INIT_POINTER(xfrm_policy_afinfo[i], NULL);
3947                 break;
3948         }
3949
3950         synchronize_rcu();
3951
3952         dst_ops->kmem_cachep = NULL;
3953         dst_ops->check = NULL;
3954         dst_ops->negative_advice = NULL;
3955         dst_ops->link_failure = NULL;
3956 }
3957 EXPORT_SYMBOL(xfrm_policy_unregister_afinfo);
3958
3959 void xfrm_if_register_cb(const struct xfrm_if_cb *ifcb)
3960 {
3961         spin_lock(&xfrm_if_cb_lock);
3962         rcu_assign_pointer(xfrm_if_cb, ifcb);
3963         spin_unlock(&xfrm_if_cb_lock);
3964 }
3965 EXPORT_SYMBOL(xfrm_if_register_cb);
3966
3967 void xfrm_if_unregister_cb(void)
3968 {
3969         RCU_INIT_POINTER(xfrm_if_cb, NULL);
3970         synchronize_rcu();
3971 }
3972 EXPORT_SYMBOL(xfrm_if_unregister_cb);
3973
3974 #ifdef CONFIG_XFRM_STATISTICS
3975 static int __net_init xfrm_statistics_init(struct net *net)
3976 {
3977         int rv;
3978         net->mib.xfrm_statistics = alloc_percpu(struct linux_xfrm_mib);
3979         if (!net->mib.xfrm_statistics)
3980                 return -ENOMEM;
3981         rv = xfrm_proc_init(net);
3982         if (rv < 0)
3983                 free_percpu(net->mib.xfrm_statistics);
3984         return rv;
3985 }
3986
3987 static void xfrm_statistics_fini(struct net *net)
3988 {
3989         xfrm_proc_fini(net);
3990         free_percpu(net->mib.xfrm_statistics);
3991 }
3992 #else
3993 static int __net_init xfrm_statistics_init(struct net *net)
3994 {
3995         return 0;
3996 }
3997
3998 static void xfrm_statistics_fini(struct net *net)
3999 {
4000 }
4001 #endif
4002
4003 static int __net_init xfrm_policy_init(struct net *net)
4004 {
4005         unsigned int hmask, sz;
4006         int dir, err;
4007
4008         if (net_eq(net, &init_net)) {
4009                 xfrm_dst_cache = kmem_cache_create("xfrm_dst_cache",
4010                                            sizeof(struct xfrm_dst),
4011                                            0, SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4012                                            NULL);
4013                 err = rhashtable_init(&xfrm_policy_inexact_table,
4014                                       &xfrm_pol_inexact_params);
4015                 BUG_ON(err);
4016         }
4017
4018         hmask = 8 - 1;
4019         sz = (hmask+1) * sizeof(struct hlist_head);
4020
4021         net->xfrm.policy_byidx = xfrm_hash_alloc(sz);
4022         if (!net->xfrm.policy_byidx)
4023                 goto out_byidx;
4024         net->xfrm.policy_idx_hmask = hmask;
4025
4026         for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
4027                 struct xfrm_policy_hash *htab;
4028
4029                 net->xfrm.policy_count[dir] = 0;
4030                 net->xfrm.policy_count[XFRM_POLICY_MAX + dir] = 0;
4031                 INIT_HLIST_HEAD(&net->xfrm.policy_inexact[dir]);
4032
4033                 htab = &net->xfrm.policy_bydst[dir];
4034                 htab->table = xfrm_hash_alloc(sz);
4035                 if (!htab->table)
4036                         goto out_bydst;
4037                 htab->hmask = hmask;
4038                 htab->dbits4 = 32;
4039                 htab->sbits4 = 32;
4040                 htab->dbits6 = 128;
4041                 htab->sbits6 = 128;
4042         }
4043         net->xfrm.policy_hthresh.lbits4 = 32;
4044         net->xfrm.policy_hthresh.rbits4 = 32;
4045         net->xfrm.policy_hthresh.lbits6 = 128;
4046         net->xfrm.policy_hthresh.rbits6 = 128;
4047
4048         seqlock_init(&net->xfrm.policy_hthresh.lock);
4049
4050         INIT_LIST_HEAD(&net->xfrm.policy_all);
4051         INIT_LIST_HEAD(&net->xfrm.inexact_bins);
4052         INIT_WORK(&net->xfrm.policy_hash_work, xfrm_hash_resize);
4053         INIT_WORK(&net->xfrm.policy_hthresh.work, xfrm_hash_rebuild);
4054         return 0;
4055
4056 out_bydst:
4057         for (dir--; dir >= 0; dir--) {
4058                 struct xfrm_policy_hash *htab;
4059
4060                 htab = &net->xfrm.policy_bydst[dir];
4061                 xfrm_hash_free(htab->table, sz);
4062         }
4063         xfrm_hash_free(net->xfrm.policy_byidx, sz);
4064 out_byidx:
4065         return -ENOMEM;
4066 }
4067
4068 static void xfrm_policy_fini(struct net *net)
4069 {
4070         struct xfrm_pol_inexact_bin *b, *t;
4071         unsigned int sz;
4072         int dir;
4073
4074         flush_work(&net->xfrm.policy_hash_work);
4075 #ifdef CONFIG_XFRM_SUB_POLICY
4076         xfrm_policy_flush(net, XFRM_POLICY_TYPE_SUB, false);
4077 #endif
4078         xfrm_policy_flush(net, XFRM_POLICY_TYPE_MAIN, false);
4079
4080         WARN_ON(!list_empty(&net->xfrm.policy_all));
4081
4082         for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
4083                 struct xfrm_policy_hash *htab;
4084
4085                 WARN_ON(!hlist_empty(&net->xfrm.policy_inexact[dir]));
4086
4087                 htab = &net->xfrm.policy_bydst[dir];
4088                 sz = (htab->hmask + 1) * sizeof(struct hlist_head);
4089                 WARN_ON(!hlist_empty(htab->table));
4090                 xfrm_hash_free(htab->table, sz);
4091         }
4092
4093         sz = (net->xfrm.policy_idx_hmask + 1) * sizeof(struct hlist_head);
4094         WARN_ON(!hlist_empty(net->xfrm.policy_byidx));
4095         xfrm_hash_free(net->xfrm.policy_byidx, sz);
4096
4097         spin_lock_bh(&net->xfrm.xfrm_policy_lock);
4098         list_for_each_entry_safe(b, t, &net->xfrm.inexact_bins, inexact_bins)
4099                 __xfrm_policy_inexact_prune_bin(b, true);
4100         spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
4101 }
4102
4103 static int __net_init xfrm_net_init(struct net *net)
4104 {
4105         int rv;
4106
4107         /* Initialize the per-net locks here */
4108         spin_lock_init(&net->xfrm.xfrm_state_lock);
4109         spin_lock_init(&net->xfrm.xfrm_policy_lock);
4110         mutex_init(&net->xfrm.xfrm_cfg_mutex);
4111
4112         rv = xfrm_statistics_init(net);
4113         if (rv < 0)
4114                 goto out_statistics;
4115         rv = xfrm_state_init(net);
4116         if (rv < 0)
4117                 goto out_state;
4118         rv = xfrm_policy_init(net);
4119         if (rv < 0)
4120                 goto out_policy;
4121         rv = xfrm_sysctl_init(net);
4122         if (rv < 0)
4123                 goto out_sysctl;
4124
4125         return 0;
4126
4127 out_sysctl:
4128         xfrm_policy_fini(net);
4129 out_policy:
4130         xfrm_state_fini(net);
4131 out_state:
4132         xfrm_statistics_fini(net);
4133 out_statistics:
4134         return rv;
4135 }
4136
4137 static void __net_exit xfrm_net_exit(struct net *net)
4138 {
4139         xfrm_sysctl_fini(net);
4140         xfrm_policy_fini(net);
4141         xfrm_state_fini(net);
4142         xfrm_statistics_fini(net);
4143 }
4144
4145 static struct pernet_operations __net_initdata xfrm_net_ops = {
4146         .init = xfrm_net_init,
4147         .exit = xfrm_net_exit,
4148 };
4149
4150 void __init xfrm_init(void)
4151 {
4152         register_pernet_subsys(&xfrm_net_ops);
4153         xfrm_dev_init();
4154         seqcount_init(&xfrm_policy_hash_generation);
4155         xfrm_input_init();
4156
4157         RCU_INIT_POINTER(xfrm_if_cb, NULL);
4158         synchronize_rcu();
4159 }
4160
4161 #ifdef CONFIG_AUDITSYSCALL
4162 static void xfrm_audit_common_policyinfo(struct xfrm_policy *xp,
4163                                          struct audit_buffer *audit_buf)
4164 {
4165         struct xfrm_sec_ctx *ctx = xp->security;
4166         struct xfrm_selector *sel = &xp->selector;
4167
4168         if (ctx)
4169                 audit_log_format(audit_buf, " sec_alg=%u sec_doi=%u sec_obj=%s",
4170                                  ctx->ctx_alg, ctx->ctx_doi, ctx->ctx_str);
4171
4172         switch (sel->family) {
4173         case AF_INET:
4174                 audit_log_format(audit_buf, " src=%pI4", &sel->saddr.a4);
4175                 if (sel->prefixlen_s != 32)
4176                         audit_log_format(audit_buf, " src_prefixlen=%d",
4177                                          sel->prefixlen_s);
4178                 audit_log_format(audit_buf, " dst=%pI4", &sel->daddr.a4);
4179                 if (sel->prefixlen_d != 32)
4180                         audit_log_format(audit_buf, " dst_prefixlen=%d",
4181                                          sel->prefixlen_d);
4182                 break;
4183         case AF_INET6:
4184                 audit_log_format(audit_buf, " src=%pI6", sel->saddr.a6);
4185                 if (sel->prefixlen_s != 128)
4186                         audit_log_format(audit_buf, " src_prefixlen=%d",
4187                                          sel->prefixlen_s);
4188                 audit_log_format(audit_buf, " dst=%pI6", sel->daddr.a6);
4189                 if (sel->prefixlen_d != 128)
4190                         audit_log_format(audit_buf, " dst_prefixlen=%d",
4191                                          sel->prefixlen_d);
4192                 break;
4193         }
4194 }
4195
4196 void xfrm_audit_policy_add(struct xfrm_policy *xp, int result, bool task_valid)
4197 {
4198         struct audit_buffer *audit_buf;
4199
4200         audit_buf = xfrm_audit_start("SPD-add");
4201         if (audit_buf == NULL)
4202                 return;
4203         xfrm_audit_helper_usrinfo(task_valid, audit_buf);
4204         audit_log_format(audit_buf, " res=%u", result);
4205         xfrm_audit_common_policyinfo(xp, audit_buf);
4206         audit_log_end(audit_buf);
4207 }
4208 EXPORT_SYMBOL_GPL(xfrm_audit_policy_add);
4209
4210 void xfrm_audit_policy_delete(struct xfrm_policy *xp, int result,
4211                               bool task_valid)
4212 {
4213         struct audit_buffer *audit_buf;
4214
4215         audit_buf = xfrm_audit_start("SPD-delete");
4216         if (audit_buf == NULL)
4217                 return;
4218         xfrm_audit_helper_usrinfo(task_valid, audit_buf);
4219         audit_log_format(audit_buf, " res=%u", result);
4220         xfrm_audit_common_policyinfo(xp, audit_buf);
4221         audit_log_end(audit_buf);
4222 }
4223 EXPORT_SYMBOL_GPL(xfrm_audit_policy_delete);
4224 #endif
4225
4226 #ifdef CONFIG_XFRM_MIGRATE
4227 static bool xfrm_migrate_selector_match(const struct xfrm_selector *sel_cmp,
4228                                         const struct xfrm_selector *sel_tgt)
4229 {
4230         if (sel_cmp->proto == IPSEC_ULPROTO_ANY) {
4231                 if (sel_tgt->family == sel_cmp->family &&
4232                     xfrm_addr_equal(&sel_tgt->daddr, &sel_cmp->daddr,
4233                                     sel_cmp->family) &&
4234                     xfrm_addr_equal(&sel_tgt->saddr, &sel_cmp->saddr,
4235                                     sel_cmp->family) &&
4236                     sel_tgt->prefixlen_d == sel_cmp->prefixlen_d &&
4237                     sel_tgt->prefixlen_s == sel_cmp->prefixlen_s) {
4238                         return true;
4239                 }
4240         } else {
4241                 if (memcmp(sel_tgt, sel_cmp, sizeof(*sel_tgt)) == 0) {
4242                         return true;
4243                 }
4244         }
4245         return false;
4246 }
4247
4248 static struct xfrm_policy *xfrm_migrate_policy_find(const struct xfrm_selector *sel,
4249                                                     u8 dir, u8 type, struct net *net)
4250 {
4251         struct xfrm_policy *pol, *ret = NULL;
4252         struct hlist_head *chain;
4253         u32 priority = ~0U;
4254
4255         spin_lock_bh(&net->xfrm.xfrm_policy_lock);
4256         chain = policy_hash_direct(net, &sel->daddr, &sel->saddr, sel->family, dir);
4257         hlist_for_each_entry(pol, chain, bydst) {
4258                 if (xfrm_migrate_selector_match(sel, &pol->selector) &&
4259                     pol->type == type) {
4260                         ret = pol;
4261                         priority = ret->priority;
4262                         break;
4263                 }
4264         }
4265         chain = &net->xfrm.policy_inexact[dir];
4266         hlist_for_each_entry(pol, chain, bydst_inexact_list) {
4267                 if ((pol->priority >= priority) && ret)
4268                         break;
4269
4270                 if (xfrm_migrate_selector_match(sel, &pol->selector) &&
4271                     pol->type == type) {
4272                         ret = pol;
4273                         break;
4274                 }
4275         }
4276
4277         xfrm_pol_hold(ret);
4278
4279         spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
4280
4281         return ret;
4282 }
4283
4284 static int migrate_tmpl_match(const struct xfrm_migrate *m, const struct xfrm_tmpl *t)
4285 {
4286         int match = 0;
4287
4288         if (t->mode == m->mode && t->id.proto == m->proto &&
4289             (m->reqid == 0 || t->reqid == m->reqid)) {
4290                 switch (t->mode) {
4291                 case XFRM_MODE_TUNNEL:
4292                 case XFRM_MODE_BEET:
4293                         if (xfrm_addr_equal(&t->id.daddr, &m->old_daddr,
4294                                             m->old_family) &&
4295                             xfrm_addr_equal(&t->saddr, &m->old_saddr,
4296                                             m->old_family)) {
4297                                 match = 1;
4298                         }
4299                         break;
4300                 case XFRM_MODE_TRANSPORT:
4301                         /* in case of transport mode, template does not store
4302                            any IP addresses, hence we just compare mode and
4303                            protocol */
4304                         match = 1;
4305                         break;
4306                 default:
4307                         break;
4308                 }
4309         }
4310         return match;
4311 }
4312
4313 /* update endpoint address(es) of template(s) */
4314 static int xfrm_policy_migrate(struct xfrm_policy *pol,
4315                                struct xfrm_migrate *m, int num_migrate)
4316 {
4317         struct xfrm_migrate *mp;
4318         int i, j, n = 0;
4319
4320         write_lock_bh(&pol->lock);
4321         if (unlikely(pol->walk.dead)) {
4322                 /* target policy has been deleted */
4323                 write_unlock_bh(&pol->lock);
4324                 return -ENOENT;
4325         }
4326
4327         for (i = 0; i < pol->xfrm_nr; i++) {
4328                 for (j = 0, mp = m; j < num_migrate; j++, mp++) {
4329                         if (!migrate_tmpl_match(mp, &pol->xfrm_vec[i]))
4330                                 continue;
4331                         n++;
4332                         if (pol->xfrm_vec[i].mode != XFRM_MODE_TUNNEL &&
4333                             pol->xfrm_vec[i].mode != XFRM_MODE_BEET)
4334                                 continue;
4335                         /* update endpoints */
4336                         memcpy(&pol->xfrm_vec[i].id.daddr, &mp->new_daddr,
4337                                sizeof(pol->xfrm_vec[i].id.daddr));
4338                         memcpy(&pol->xfrm_vec[i].saddr, &mp->new_saddr,
4339                                sizeof(pol->xfrm_vec[i].saddr));
4340                         pol->xfrm_vec[i].encap_family = mp->new_family;
4341                         /* flush bundles */
4342                         atomic_inc(&pol->genid);
4343                 }
4344         }
4345
4346         write_unlock_bh(&pol->lock);
4347
4348         if (!n)
4349                 return -ENODATA;
4350
4351         return 0;
4352 }
4353
4354 static int xfrm_migrate_check(const struct xfrm_migrate *m, int num_migrate)
4355 {
4356         int i, j;
4357
4358         if (num_migrate < 1 || num_migrate > XFRM_MAX_DEPTH)
4359                 return -EINVAL;
4360
4361         for (i = 0; i < num_migrate; i++) {
4362                 if (xfrm_addr_any(&m[i].new_daddr, m[i].new_family) ||
4363                     xfrm_addr_any(&m[i].new_saddr, m[i].new_family))
4364                         return -EINVAL;
4365
4366                 /* check if there is any duplicated entry */
4367                 for (j = i + 1; j < num_migrate; j++) {
4368                         if (!memcmp(&m[i].old_daddr, &m[j].old_daddr,
4369                                     sizeof(m[i].old_daddr)) &&
4370                             !memcmp(&m[i].old_saddr, &m[j].old_saddr,
4371                                     sizeof(m[i].old_saddr)) &&
4372                             m[i].proto == m[j].proto &&
4373                             m[i].mode == m[j].mode &&
4374                             m[i].reqid == m[j].reqid &&
4375                             m[i].old_family == m[j].old_family)
4376                                 return -EINVAL;
4377                 }
4378         }
4379
4380         return 0;
4381 }
4382
4383 int xfrm_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
4384                  struct xfrm_migrate *m, int num_migrate,
4385                  struct xfrm_kmaddress *k, struct net *net,
4386                  struct xfrm_encap_tmpl *encap)
4387 {
4388         int i, err, nx_cur = 0, nx_new = 0;
4389         struct xfrm_policy *pol = NULL;
4390         struct xfrm_state *x, *xc;
4391         struct xfrm_state *x_cur[XFRM_MAX_DEPTH];
4392         struct xfrm_state *x_new[XFRM_MAX_DEPTH];
4393         struct xfrm_migrate *mp;
4394
4395         /* Stage 0 - sanity checks */
4396         if ((err = xfrm_migrate_check(m, num_migrate)) < 0)
4397                 goto out;
4398
4399         if (dir >= XFRM_POLICY_MAX) {
4400                 err = -EINVAL;
4401                 goto out;
4402         }
4403
4404         /* Stage 1 - find policy */
4405         if ((pol = xfrm_migrate_policy_find(sel, dir, type, net)) == NULL) {
4406                 err = -ENOENT;
4407                 goto out;
4408         }
4409
4410         /* Stage 2 - find and update state(s) */
4411         for (i = 0, mp = m; i < num_migrate; i++, mp++) {
4412                 if ((x = xfrm_migrate_state_find(mp, net))) {
4413                         x_cur[nx_cur] = x;
4414                         nx_cur++;
4415                         xc = xfrm_state_migrate(x, mp, encap);
4416                         if (xc) {
4417                                 x_new[nx_new] = xc;
4418                                 nx_new++;
4419                         } else {
4420                                 err = -ENODATA;
4421                                 goto restore_state;
4422                         }
4423                 }
4424         }
4425
4426         /* Stage 3 - update policy */
4427         if ((err = xfrm_policy_migrate(pol, m, num_migrate)) < 0)
4428                 goto restore_state;
4429
4430         /* Stage 4 - delete old state(s) */
4431         if (nx_cur) {
4432                 xfrm_states_put(x_cur, nx_cur);
4433                 xfrm_states_delete(x_cur, nx_cur);
4434         }
4435
4436         /* Stage 5 - announce */
4437         km_migrate(sel, dir, type, m, num_migrate, k, encap);
4438
4439         xfrm_pol_put(pol);
4440
4441         return 0;
4442 out:
4443         return err;
4444
4445 restore_state:
4446         if (pol)
4447                 xfrm_pol_put(pol);
4448         if (nx_cur)
4449                 xfrm_states_put(x_cur, nx_cur);
4450         if (nx_new)
4451                 xfrm_states_delete(x_new, nx_new);
4452
4453         return err;
4454 }
4455 EXPORT_SYMBOL(xfrm_migrate);
4456 #endif