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