Merge branch 'ib/5.17-cros-ec-keyb' into next
[platform/kernel/linux-starfive.git] / net / netfilter / nf_conntrack_core.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Connection state tracking for netfilter.  This is separated from,
3    but required by, the NAT layer; it can also be used by an iptables
4    extension. */
5
6 /* (C) 1999-2001 Paul `Rusty' Russell
7  * (C) 2002-2006 Netfilter Core Team <coreteam@netfilter.org>
8  * (C) 2003,2004 USAGI/WIDE Project <http://www.linux-ipv6.org>
9  * (C) 2005-2012 Patrick McHardy <kaber@trash.net>
10  */
11
12 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
13
14 #include <linux/types.h>
15 #include <linux/netfilter.h>
16 #include <linux/module.h>
17 #include <linux/sched.h>
18 #include <linux/skbuff.h>
19 #include <linux/proc_fs.h>
20 #include <linux/vmalloc.h>
21 #include <linux/stddef.h>
22 #include <linux/slab.h>
23 #include <linux/random.h>
24 #include <linux/siphash.h>
25 #include <linux/err.h>
26 #include <linux/percpu.h>
27 #include <linux/moduleparam.h>
28 #include <linux/notifier.h>
29 #include <linux/kernel.h>
30 #include <linux/netdevice.h>
31 #include <linux/socket.h>
32 #include <linux/mm.h>
33 #include <linux/nsproxy.h>
34 #include <linux/rculist_nulls.h>
35
36 #include <net/netfilter/nf_conntrack.h>
37 #include <net/netfilter/nf_conntrack_l4proto.h>
38 #include <net/netfilter/nf_conntrack_expect.h>
39 #include <net/netfilter/nf_conntrack_helper.h>
40 #include <net/netfilter/nf_conntrack_seqadj.h>
41 #include <net/netfilter/nf_conntrack_core.h>
42 #include <net/netfilter/nf_conntrack_extend.h>
43 #include <net/netfilter/nf_conntrack_acct.h>
44 #include <net/netfilter/nf_conntrack_ecache.h>
45 #include <net/netfilter/nf_conntrack_zones.h>
46 #include <net/netfilter/nf_conntrack_timestamp.h>
47 #include <net/netfilter/nf_conntrack_timeout.h>
48 #include <net/netfilter/nf_conntrack_labels.h>
49 #include <net/netfilter/nf_conntrack_synproxy.h>
50 #include <net/netfilter/nf_conntrack_act_ct.h>
51 #include <net/netfilter/nf_nat.h>
52 #include <net/netfilter/nf_nat_helper.h>
53 #include <net/netns/hash.h>
54 #include <net/ip.h>
55
56 #include "nf_internals.h"
57
58 __cacheline_aligned_in_smp spinlock_t nf_conntrack_locks[CONNTRACK_LOCKS];
59 EXPORT_SYMBOL_GPL(nf_conntrack_locks);
60
61 __cacheline_aligned_in_smp DEFINE_SPINLOCK(nf_conntrack_expect_lock);
62 EXPORT_SYMBOL_GPL(nf_conntrack_expect_lock);
63
64 struct hlist_nulls_head *nf_conntrack_hash __read_mostly;
65 EXPORT_SYMBOL_GPL(nf_conntrack_hash);
66
67 struct conntrack_gc_work {
68         struct delayed_work     dwork;
69         u32                     next_bucket;
70         bool                    exiting;
71         bool                    early_drop;
72 };
73
74 static __read_mostly struct kmem_cache *nf_conntrack_cachep;
75 static DEFINE_SPINLOCK(nf_conntrack_locks_all_lock);
76 static __read_mostly bool nf_conntrack_locks_all;
77
78 /* serialize hash resizes and nf_ct_iterate_cleanup */
79 static DEFINE_MUTEX(nf_conntrack_mutex);
80
81 #define GC_SCAN_INTERVAL        (120u * HZ)
82 #define GC_SCAN_MAX_DURATION    msecs_to_jiffies(10)
83
84 #define MIN_CHAINLEN    8u
85 #define MAX_CHAINLEN    (32u - MIN_CHAINLEN)
86
87 static struct conntrack_gc_work conntrack_gc_work;
88
89 void nf_conntrack_lock(spinlock_t *lock) __acquires(lock)
90 {
91         /* 1) Acquire the lock */
92         spin_lock(lock);
93
94         /* 2) read nf_conntrack_locks_all, with ACQUIRE semantics
95          * It pairs with the smp_store_release() in nf_conntrack_all_unlock()
96          */
97         if (likely(smp_load_acquire(&nf_conntrack_locks_all) == false))
98                 return;
99
100         /* fast path failed, unlock */
101         spin_unlock(lock);
102
103         /* Slow path 1) get global lock */
104         spin_lock(&nf_conntrack_locks_all_lock);
105
106         /* Slow path 2) get the lock we want */
107         spin_lock(lock);
108
109         /* Slow path 3) release the global lock */
110         spin_unlock(&nf_conntrack_locks_all_lock);
111 }
112 EXPORT_SYMBOL_GPL(nf_conntrack_lock);
113
114 static void nf_conntrack_double_unlock(unsigned int h1, unsigned int h2)
115 {
116         h1 %= CONNTRACK_LOCKS;
117         h2 %= CONNTRACK_LOCKS;
118         spin_unlock(&nf_conntrack_locks[h1]);
119         if (h1 != h2)
120                 spin_unlock(&nf_conntrack_locks[h2]);
121 }
122
123 /* return true if we need to recompute hashes (in case hash table was resized) */
124 static bool nf_conntrack_double_lock(struct net *net, unsigned int h1,
125                                      unsigned int h2, unsigned int sequence)
126 {
127         h1 %= CONNTRACK_LOCKS;
128         h2 %= CONNTRACK_LOCKS;
129         if (h1 <= h2) {
130                 nf_conntrack_lock(&nf_conntrack_locks[h1]);
131                 if (h1 != h2)
132                         spin_lock_nested(&nf_conntrack_locks[h2],
133                                          SINGLE_DEPTH_NESTING);
134         } else {
135                 nf_conntrack_lock(&nf_conntrack_locks[h2]);
136                 spin_lock_nested(&nf_conntrack_locks[h1],
137                                  SINGLE_DEPTH_NESTING);
138         }
139         if (read_seqcount_retry(&nf_conntrack_generation, sequence)) {
140                 nf_conntrack_double_unlock(h1, h2);
141                 return true;
142         }
143         return false;
144 }
145
146 static void nf_conntrack_all_lock(void)
147         __acquires(&nf_conntrack_locks_all_lock)
148 {
149         int i;
150
151         spin_lock(&nf_conntrack_locks_all_lock);
152
153         /* For nf_contrack_locks_all, only the latest time when another
154          * CPU will see an update is controlled, by the "release" of the
155          * spin_lock below.
156          * The earliest time is not controlled, an thus KCSAN could detect
157          * a race when nf_conntract_lock() reads the variable.
158          * WRITE_ONCE() is used to ensure the compiler will not
159          * optimize the write.
160          */
161         WRITE_ONCE(nf_conntrack_locks_all, true);
162
163         for (i = 0; i < CONNTRACK_LOCKS; i++) {
164                 spin_lock(&nf_conntrack_locks[i]);
165
166                 /* This spin_unlock provides the "release" to ensure that
167                  * nf_conntrack_locks_all==true is visible to everyone that
168                  * acquired spin_lock(&nf_conntrack_locks[]).
169                  */
170                 spin_unlock(&nf_conntrack_locks[i]);
171         }
172 }
173
174 static void nf_conntrack_all_unlock(void)
175         __releases(&nf_conntrack_locks_all_lock)
176 {
177         /* All prior stores must be complete before we clear
178          * 'nf_conntrack_locks_all'. Otherwise nf_conntrack_lock()
179          * might observe the false value but not the entire
180          * critical section.
181          * It pairs with the smp_load_acquire() in nf_conntrack_lock()
182          */
183         smp_store_release(&nf_conntrack_locks_all, false);
184         spin_unlock(&nf_conntrack_locks_all_lock);
185 }
186
187 unsigned int nf_conntrack_htable_size __read_mostly;
188 EXPORT_SYMBOL_GPL(nf_conntrack_htable_size);
189
190 unsigned int nf_conntrack_max __read_mostly;
191 EXPORT_SYMBOL_GPL(nf_conntrack_max);
192 seqcount_spinlock_t nf_conntrack_generation __read_mostly;
193 static siphash_aligned_key_t nf_conntrack_hash_rnd;
194
195 static u32 hash_conntrack_raw(const struct nf_conntrack_tuple *tuple,
196                               unsigned int zoneid,
197                               const struct net *net)
198 {
199         struct {
200                 struct nf_conntrack_man src;
201                 union nf_inet_addr dst_addr;
202                 unsigned int zone;
203                 u32 net_mix;
204                 u16 dport;
205                 u16 proto;
206         } __aligned(SIPHASH_ALIGNMENT) combined;
207
208         get_random_once(&nf_conntrack_hash_rnd, sizeof(nf_conntrack_hash_rnd));
209
210         memset(&combined, 0, sizeof(combined));
211
212         /* The direction must be ignored, so handle usable members manually. */
213         combined.src = tuple->src;
214         combined.dst_addr = tuple->dst.u3;
215         combined.zone = zoneid;
216         combined.net_mix = net_hash_mix(net);
217         combined.dport = (__force __u16)tuple->dst.u.all;
218         combined.proto = tuple->dst.protonum;
219
220         return (u32)siphash(&combined, sizeof(combined), &nf_conntrack_hash_rnd);
221 }
222
223 static u32 scale_hash(u32 hash)
224 {
225         return reciprocal_scale(hash, nf_conntrack_htable_size);
226 }
227
228 static u32 __hash_conntrack(const struct net *net,
229                             const struct nf_conntrack_tuple *tuple,
230                             unsigned int zoneid,
231                             unsigned int size)
232 {
233         return reciprocal_scale(hash_conntrack_raw(tuple, zoneid, net), size);
234 }
235
236 static u32 hash_conntrack(const struct net *net,
237                           const struct nf_conntrack_tuple *tuple,
238                           unsigned int zoneid)
239 {
240         return scale_hash(hash_conntrack_raw(tuple, zoneid, net));
241 }
242
243 static bool nf_ct_get_tuple_ports(const struct sk_buff *skb,
244                                   unsigned int dataoff,
245                                   struct nf_conntrack_tuple *tuple)
246 {       struct {
247                 __be16 sport;
248                 __be16 dport;
249         } _inet_hdr, *inet_hdr;
250
251         /* Actually only need first 4 bytes to get ports. */
252         inet_hdr = skb_header_pointer(skb, dataoff, sizeof(_inet_hdr), &_inet_hdr);
253         if (!inet_hdr)
254                 return false;
255
256         tuple->src.u.udp.port = inet_hdr->sport;
257         tuple->dst.u.udp.port = inet_hdr->dport;
258         return true;
259 }
260
261 static bool
262 nf_ct_get_tuple(const struct sk_buff *skb,
263                 unsigned int nhoff,
264                 unsigned int dataoff,
265                 u_int16_t l3num,
266                 u_int8_t protonum,
267                 struct net *net,
268                 struct nf_conntrack_tuple *tuple)
269 {
270         unsigned int size;
271         const __be32 *ap;
272         __be32 _addrs[8];
273
274         memset(tuple, 0, sizeof(*tuple));
275
276         tuple->src.l3num = l3num;
277         switch (l3num) {
278         case NFPROTO_IPV4:
279                 nhoff += offsetof(struct iphdr, saddr);
280                 size = 2 * sizeof(__be32);
281                 break;
282         case NFPROTO_IPV6:
283                 nhoff += offsetof(struct ipv6hdr, saddr);
284                 size = sizeof(_addrs);
285                 break;
286         default:
287                 return true;
288         }
289
290         ap = skb_header_pointer(skb, nhoff, size, _addrs);
291         if (!ap)
292                 return false;
293
294         switch (l3num) {
295         case NFPROTO_IPV4:
296                 tuple->src.u3.ip = ap[0];
297                 tuple->dst.u3.ip = ap[1];
298                 break;
299         case NFPROTO_IPV6:
300                 memcpy(tuple->src.u3.ip6, ap, sizeof(tuple->src.u3.ip6));
301                 memcpy(tuple->dst.u3.ip6, ap + 4, sizeof(tuple->dst.u3.ip6));
302                 break;
303         }
304
305         tuple->dst.protonum = protonum;
306         tuple->dst.dir = IP_CT_DIR_ORIGINAL;
307
308         switch (protonum) {
309 #if IS_ENABLED(CONFIG_IPV6)
310         case IPPROTO_ICMPV6:
311                 return icmpv6_pkt_to_tuple(skb, dataoff, net, tuple);
312 #endif
313         case IPPROTO_ICMP:
314                 return icmp_pkt_to_tuple(skb, dataoff, net, tuple);
315 #ifdef CONFIG_NF_CT_PROTO_GRE
316         case IPPROTO_GRE:
317                 return gre_pkt_to_tuple(skb, dataoff, net, tuple);
318 #endif
319         case IPPROTO_TCP:
320         case IPPROTO_UDP: /* fallthrough */
321                 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
322 #ifdef CONFIG_NF_CT_PROTO_UDPLITE
323         case IPPROTO_UDPLITE:
324                 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
325 #endif
326 #ifdef CONFIG_NF_CT_PROTO_SCTP
327         case IPPROTO_SCTP:
328                 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
329 #endif
330 #ifdef CONFIG_NF_CT_PROTO_DCCP
331         case IPPROTO_DCCP:
332                 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
333 #endif
334         default:
335                 break;
336         }
337
338         return true;
339 }
340
341 static int ipv4_get_l4proto(const struct sk_buff *skb, unsigned int nhoff,
342                             u_int8_t *protonum)
343 {
344         int dataoff = -1;
345         const struct iphdr *iph;
346         struct iphdr _iph;
347
348         iph = skb_header_pointer(skb, nhoff, sizeof(_iph), &_iph);
349         if (!iph)
350                 return -1;
351
352         /* Conntrack defragments packets, we might still see fragments
353          * inside ICMP packets though.
354          */
355         if (iph->frag_off & htons(IP_OFFSET))
356                 return -1;
357
358         dataoff = nhoff + (iph->ihl << 2);
359         *protonum = iph->protocol;
360
361         /* Check bogus IP headers */
362         if (dataoff > skb->len) {
363                 pr_debug("bogus IPv4 packet: nhoff %u, ihl %u, skblen %u\n",
364                          nhoff, iph->ihl << 2, skb->len);
365                 return -1;
366         }
367         return dataoff;
368 }
369
370 #if IS_ENABLED(CONFIG_IPV6)
371 static int ipv6_get_l4proto(const struct sk_buff *skb, unsigned int nhoff,
372                             u8 *protonum)
373 {
374         int protoff = -1;
375         unsigned int extoff = nhoff + sizeof(struct ipv6hdr);
376         __be16 frag_off;
377         u8 nexthdr;
378
379         if (skb_copy_bits(skb, nhoff + offsetof(struct ipv6hdr, nexthdr),
380                           &nexthdr, sizeof(nexthdr)) != 0) {
381                 pr_debug("can't get nexthdr\n");
382                 return -1;
383         }
384         protoff = ipv6_skip_exthdr(skb, extoff, &nexthdr, &frag_off);
385         /*
386          * (protoff == skb->len) means the packet has not data, just
387          * IPv6 and possibly extensions headers, but it is tracked anyway
388          */
389         if (protoff < 0 || (frag_off & htons(~0x7)) != 0) {
390                 pr_debug("can't find proto in pkt\n");
391                 return -1;
392         }
393
394         *protonum = nexthdr;
395         return protoff;
396 }
397 #endif
398
399 static int get_l4proto(const struct sk_buff *skb,
400                        unsigned int nhoff, u8 pf, u8 *l4num)
401 {
402         switch (pf) {
403         case NFPROTO_IPV4:
404                 return ipv4_get_l4proto(skb, nhoff, l4num);
405 #if IS_ENABLED(CONFIG_IPV6)
406         case NFPROTO_IPV6:
407                 return ipv6_get_l4proto(skb, nhoff, l4num);
408 #endif
409         default:
410                 *l4num = 0;
411                 break;
412         }
413         return -1;
414 }
415
416 bool nf_ct_get_tuplepr(const struct sk_buff *skb, unsigned int nhoff,
417                        u_int16_t l3num,
418                        struct net *net, struct nf_conntrack_tuple *tuple)
419 {
420         u8 protonum;
421         int protoff;
422
423         protoff = get_l4proto(skb, nhoff, l3num, &protonum);
424         if (protoff <= 0)
425                 return false;
426
427         return nf_ct_get_tuple(skb, nhoff, protoff, l3num, protonum, net, tuple);
428 }
429 EXPORT_SYMBOL_GPL(nf_ct_get_tuplepr);
430
431 bool
432 nf_ct_invert_tuple(struct nf_conntrack_tuple *inverse,
433                    const struct nf_conntrack_tuple *orig)
434 {
435         memset(inverse, 0, sizeof(*inverse));
436
437         inverse->src.l3num = orig->src.l3num;
438
439         switch (orig->src.l3num) {
440         case NFPROTO_IPV4:
441                 inverse->src.u3.ip = orig->dst.u3.ip;
442                 inverse->dst.u3.ip = orig->src.u3.ip;
443                 break;
444         case NFPROTO_IPV6:
445                 inverse->src.u3.in6 = orig->dst.u3.in6;
446                 inverse->dst.u3.in6 = orig->src.u3.in6;
447                 break;
448         default:
449                 break;
450         }
451
452         inverse->dst.dir = !orig->dst.dir;
453
454         inverse->dst.protonum = orig->dst.protonum;
455
456         switch (orig->dst.protonum) {
457         case IPPROTO_ICMP:
458                 return nf_conntrack_invert_icmp_tuple(inverse, orig);
459 #if IS_ENABLED(CONFIG_IPV6)
460         case IPPROTO_ICMPV6:
461                 return nf_conntrack_invert_icmpv6_tuple(inverse, orig);
462 #endif
463         }
464
465         inverse->src.u.all = orig->dst.u.all;
466         inverse->dst.u.all = orig->src.u.all;
467         return true;
468 }
469 EXPORT_SYMBOL_GPL(nf_ct_invert_tuple);
470
471 /* Generate a almost-unique pseudo-id for a given conntrack.
472  *
473  * intentionally doesn't re-use any of the seeds used for hash
474  * table location, we assume id gets exposed to userspace.
475  *
476  * Following nf_conn items do not change throughout lifetime
477  * of the nf_conn:
478  *
479  * 1. nf_conn address
480  * 2. nf_conn->master address (normally NULL)
481  * 3. the associated net namespace
482  * 4. the original direction tuple
483  */
484 u32 nf_ct_get_id(const struct nf_conn *ct)
485 {
486         static siphash_aligned_key_t ct_id_seed;
487         unsigned long a, b, c, d;
488
489         net_get_random_once(&ct_id_seed, sizeof(ct_id_seed));
490
491         a = (unsigned long)ct;
492         b = (unsigned long)ct->master;
493         c = (unsigned long)nf_ct_net(ct);
494         d = (unsigned long)siphash(&ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
495                                    sizeof(ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple),
496                                    &ct_id_seed);
497 #ifdef CONFIG_64BIT
498         return siphash_4u64((u64)a, (u64)b, (u64)c, (u64)d, &ct_id_seed);
499 #else
500         return siphash_4u32((u32)a, (u32)b, (u32)c, (u32)d, &ct_id_seed);
501 #endif
502 }
503 EXPORT_SYMBOL_GPL(nf_ct_get_id);
504
505 static void
506 clean_from_lists(struct nf_conn *ct)
507 {
508         pr_debug("clean_from_lists(%p)\n", ct);
509         hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
510         hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode);
511
512         /* Destroy all pending expectations */
513         nf_ct_remove_expectations(ct);
514 }
515
516 /* must be called with local_bh_disable */
517 static void nf_ct_add_to_dying_list(struct nf_conn *ct)
518 {
519         struct ct_pcpu *pcpu;
520
521         /* add this conntrack to the (per cpu) dying list */
522         ct->cpu = smp_processor_id();
523         pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
524
525         spin_lock(&pcpu->lock);
526         hlist_nulls_add_head(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
527                              &pcpu->dying);
528         spin_unlock(&pcpu->lock);
529 }
530
531 /* must be called with local_bh_disable */
532 static void nf_ct_add_to_unconfirmed_list(struct nf_conn *ct)
533 {
534         struct ct_pcpu *pcpu;
535
536         /* add this conntrack to the (per cpu) unconfirmed list */
537         ct->cpu = smp_processor_id();
538         pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
539
540         spin_lock(&pcpu->lock);
541         hlist_nulls_add_head(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
542                              &pcpu->unconfirmed);
543         spin_unlock(&pcpu->lock);
544 }
545
546 /* must be called with local_bh_disable */
547 static void nf_ct_del_from_dying_or_unconfirmed_list(struct nf_conn *ct)
548 {
549         struct ct_pcpu *pcpu;
550
551         /* We overload first tuple to link into unconfirmed or dying list.*/
552         pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
553
554         spin_lock(&pcpu->lock);
555         BUG_ON(hlist_nulls_unhashed(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode));
556         hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
557         spin_unlock(&pcpu->lock);
558 }
559
560 #define NFCT_ALIGN(len) (((len) + NFCT_INFOMASK) & ~NFCT_INFOMASK)
561
562 /* Released via nf_ct_destroy() */
563 struct nf_conn *nf_ct_tmpl_alloc(struct net *net,
564                                  const struct nf_conntrack_zone *zone,
565                                  gfp_t flags)
566 {
567         struct nf_conn *tmpl, *p;
568
569         if (ARCH_KMALLOC_MINALIGN <= NFCT_INFOMASK) {
570                 tmpl = kzalloc(sizeof(*tmpl) + NFCT_INFOMASK, flags);
571                 if (!tmpl)
572                         return NULL;
573
574                 p = tmpl;
575                 tmpl = (struct nf_conn *)NFCT_ALIGN((unsigned long)p);
576                 if (tmpl != p) {
577                         tmpl = (struct nf_conn *)NFCT_ALIGN((unsigned long)p);
578                         tmpl->proto.tmpl_padto = (char *)tmpl - (char *)p;
579                 }
580         } else {
581                 tmpl = kzalloc(sizeof(*tmpl), flags);
582                 if (!tmpl)
583                         return NULL;
584         }
585
586         tmpl->status = IPS_TEMPLATE;
587         write_pnet(&tmpl->ct_net, net);
588         nf_ct_zone_add(tmpl, zone);
589         refcount_set(&tmpl->ct_general.use, 1);
590
591         return tmpl;
592 }
593 EXPORT_SYMBOL_GPL(nf_ct_tmpl_alloc);
594
595 void nf_ct_tmpl_free(struct nf_conn *tmpl)
596 {
597         nf_ct_ext_destroy(tmpl);
598
599         if (ARCH_KMALLOC_MINALIGN <= NFCT_INFOMASK)
600                 kfree((char *)tmpl - tmpl->proto.tmpl_padto);
601         else
602                 kfree(tmpl);
603 }
604 EXPORT_SYMBOL_GPL(nf_ct_tmpl_free);
605
606 static void destroy_gre_conntrack(struct nf_conn *ct)
607 {
608 #ifdef CONFIG_NF_CT_PROTO_GRE
609         struct nf_conn *master = ct->master;
610
611         if (master)
612                 nf_ct_gre_keymap_destroy(master);
613 #endif
614 }
615
616 void nf_ct_destroy(struct nf_conntrack *nfct)
617 {
618         struct nf_conn *ct = (struct nf_conn *)nfct;
619
620         pr_debug("%s(%p)\n", __func__, ct);
621         WARN_ON(refcount_read(&nfct->use) != 0);
622
623         if (unlikely(nf_ct_is_template(ct))) {
624                 nf_ct_tmpl_free(ct);
625                 return;
626         }
627
628         if (unlikely(nf_ct_protonum(ct) == IPPROTO_GRE))
629                 destroy_gre_conntrack(ct);
630
631         local_bh_disable();
632         /* Expectations will have been removed in clean_from_lists,
633          * except TFTP can create an expectation on the first packet,
634          * before connection is in the list, so we need to clean here,
635          * too.
636          */
637         nf_ct_remove_expectations(ct);
638
639         nf_ct_del_from_dying_or_unconfirmed_list(ct);
640
641         local_bh_enable();
642
643         if (ct->master)
644                 nf_ct_put(ct->master);
645
646         pr_debug("%s: returning ct=%p to slab\n", __func__, ct);
647         nf_conntrack_free(ct);
648 }
649 EXPORT_SYMBOL(nf_ct_destroy);
650
651 static void nf_ct_delete_from_lists(struct nf_conn *ct)
652 {
653         struct net *net = nf_ct_net(ct);
654         unsigned int hash, reply_hash;
655         unsigned int sequence;
656
657         nf_ct_helper_destroy(ct);
658
659         local_bh_disable();
660         do {
661                 sequence = read_seqcount_begin(&nf_conntrack_generation);
662                 hash = hash_conntrack(net,
663                                       &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
664                                       nf_ct_zone_id(nf_ct_zone(ct), IP_CT_DIR_ORIGINAL));
665                 reply_hash = hash_conntrack(net,
666                                            &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
667                                            nf_ct_zone_id(nf_ct_zone(ct), IP_CT_DIR_REPLY));
668         } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
669
670         clean_from_lists(ct);
671         nf_conntrack_double_unlock(hash, reply_hash);
672
673         nf_ct_add_to_dying_list(ct);
674
675         local_bh_enable();
676 }
677
678 bool nf_ct_delete(struct nf_conn *ct, u32 portid, int report)
679 {
680         struct nf_conn_tstamp *tstamp;
681         struct net *net;
682
683         if (test_and_set_bit(IPS_DYING_BIT, &ct->status))
684                 return false;
685
686         tstamp = nf_conn_tstamp_find(ct);
687         if (tstamp) {
688                 s32 timeout = READ_ONCE(ct->timeout) - nfct_time_stamp;
689
690                 tstamp->stop = ktime_get_real_ns();
691                 if (timeout < 0)
692                         tstamp->stop -= jiffies_to_nsecs(-timeout);
693         }
694
695         if (nf_conntrack_event_report(IPCT_DESTROY, ct,
696                                     portid, report) < 0) {
697                 /* destroy event was not delivered. nf_ct_put will
698                  * be done by event cache worker on redelivery.
699                  */
700                 nf_ct_delete_from_lists(ct);
701                 nf_conntrack_ecache_work(nf_ct_net(ct), NFCT_ECACHE_DESTROY_FAIL);
702                 return false;
703         }
704
705         net = nf_ct_net(ct);
706         if (nf_conntrack_ecache_dwork_pending(net))
707                 nf_conntrack_ecache_work(net, NFCT_ECACHE_DESTROY_SENT);
708         nf_ct_delete_from_lists(ct);
709         nf_ct_put(ct);
710         return true;
711 }
712 EXPORT_SYMBOL_GPL(nf_ct_delete);
713
714 static inline bool
715 nf_ct_key_equal(struct nf_conntrack_tuple_hash *h,
716                 const struct nf_conntrack_tuple *tuple,
717                 const struct nf_conntrack_zone *zone,
718                 const struct net *net)
719 {
720         struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
721
722         /* A conntrack can be recreated with the equal tuple,
723          * so we need to check that the conntrack is confirmed
724          */
725         return nf_ct_tuple_equal(tuple, &h->tuple) &&
726                nf_ct_zone_equal(ct, zone, NF_CT_DIRECTION(h)) &&
727                nf_ct_is_confirmed(ct) &&
728                net_eq(net, nf_ct_net(ct));
729 }
730
731 static inline bool
732 nf_ct_match(const struct nf_conn *ct1, const struct nf_conn *ct2)
733 {
734         return nf_ct_tuple_equal(&ct1->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
735                                  &ct2->tuplehash[IP_CT_DIR_ORIGINAL].tuple) &&
736                nf_ct_tuple_equal(&ct1->tuplehash[IP_CT_DIR_REPLY].tuple,
737                                  &ct2->tuplehash[IP_CT_DIR_REPLY].tuple) &&
738                nf_ct_zone_equal(ct1, nf_ct_zone(ct2), IP_CT_DIR_ORIGINAL) &&
739                nf_ct_zone_equal(ct1, nf_ct_zone(ct2), IP_CT_DIR_REPLY) &&
740                net_eq(nf_ct_net(ct1), nf_ct_net(ct2));
741 }
742
743 /* caller must hold rcu readlock and none of the nf_conntrack_locks */
744 static void nf_ct_gc_expired(struct nf_conn *ct)
745 {
746         if (!refcount_inc_not_zero(&ct->ct_general.use))
747                 return;
748
749         if (nf_ct_should_gc(ct))
750                 nf_ct_kill(ct);
751
752         nf_ct_put(ct);
753 }
754
755 /*
756  * Warning :
757  * - Caller must take a reference on returned object
758  *   and recheck nf_ct_tuple_equal(tuple, &h->tuple)
759  */
760 static struct nf_conntrack_tuple_hash *
761 ____nf_conntrack_find(struct net *net, const struct nf_conntrack_zone *zone,
762                       const struct nf_conntrack_tuple *tuple, u32 hash)
763 {
764         struct nf_conntrack_tuple_hash *h;
765         struct hlist_nulls_head *ct_hash;
766         struct hlist_nulls_node *n;
767         unsigned int bucket, hsize;
768
769 begin:
770         nf_conntrack_get_ht(&ct_hash, &hsize);
771         bucket = reciprocal_scale(hash, hsize);
772
773         hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[bucket], hnnode) {
774                 struct nf_conn *ct;
775
776                 ct = nf_ct_tuplehash_to_ctrack(h);
777                 if (nf_ct_is_expired(ct)) {
778                         nf_ct_gc_expired(ct);
779                         continue;
780                 }
781
782                 if (nf_ct_key_equal(h, tuple, zone, net))
783                         return h;
784         }
785         /*
786          * if the nulls value we got at the end of this lookup is
787          * not the expected one, we must restart lookup.
788          * We probably met an item that was moved to another chain.
789          */
790         if (get_nulls_value(n) != bucket) {
791                 NF_CT_STAT_INC_ATOMIC(net, search_restart);
792                 goto begin;
793         }
794
795         return NULL;
796 }
797
798 /* Find a connection corresponding to a tuple. */
799 static struct nf_conntrack_tuple_hash *
800 __nf_conntrack_find_get(struct net *net, const struct nf_conntrack_zone *zone,
801                         const struct nf_conntrack_tuple *tuple, u32 hash)
802 {
803         struct nf_conntrack_tuple_hash *h;
804         struct nf_conn *ct;
805
806         rcu_read_lock();
807
808         h = ____nf_conntrack_find(net, zone, tuple, hash);
809         if (h) {
810                 /* We have a candidate that matches the tuple we're interested
811                  * in, try to obtain a reference and re-check tuple
812                  */
813                 ct = nf_ct_tuplehash_to_ctrack(h);
814                 if (likely(refcount_inc_not_zero(&ct->ct_general.use))) {
815                         if (likely(nf_ct_key_equal(h, tuple, zone, net)))
816                                 goto found;
817
818                         /* TYPESAFE_BY_RCU recycled the candidate */
819                         nf_ct_put(ct);
820                 }
821
822                 h = NULL;
823         }
824 found:
825         rcu_read_unlock();
826
827         return h;
828 }
829
830 struct nf_conntrack_tuple_hash *
831 nf_conntrack_find_get(struct net *net, const struct nf_conntrack_zone *zone,
832                       const struct nf_conntrack_tuple *tuple)
833 {
834         unsigned int rid, zone_id = nf_ct_zone_id(zone, IP_CT_DIR_ORIGINAL);
835         struct nf_conntrack_tuple_hash *thash;
836
837         thash = __nf_conntrack_find_get(net, zone, tuple,
838                                         hash_conntrack_raw(tuple, zone_id, net));
839
840         if (thash)
841                 return thash;
842
843         rid = nf_ct_zone_id(zone, IP_CT_DIR_REPLY);
844         if (rid != zone_id)
845                 return __nf_conntrack_find_get(net, zone, tuple,
846                                                hash_conntrack_raw(tuple, rid, net));
847         return thash;
848 }
849 EXPORT_SYMBOL_GPL(nf_conntrack_find_get);
850
851 static void __nf_conntrack_hash_insert(struct nf_conn *ct,
852                                        unsigned int hash,
853                                        unsigned int reply_hash)
854 {
855         hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
856                            &nf_conntrack_hash[hash]);
857         hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode,
858                            &nf_conntrack_hash[reply_hash]);
859 }
860
861 int
862 nf_conntrack_hash_check_insert(struct nf_conn *ct)
863 {
864         const struct nf_conntrack_zone *zone;
865         struct net *net = nf_ct_net(ct);
866         unsigned int hash, reply_hash;
867         struct nf_conntrack_tuple_hash *h;
868         struct hlist_nulls_node *n;
869         unsigned int max_chainlen;
870         unsigned int chainlen = 0;
871         unsigned int sequence;
872         int err = -EEXIST;
873
874         zone = nf_ct_zone(ct);
875
876         local_bh_disable();
877         do {
878                 sequence = read_seqcount_begin(&nf_conntrack_generation);
879                 hash = hash_conntrack(net,
880                                       &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
881                                       nf_ct_zone_id(nf_ct_zone(ct), IP_CT_DIR_ORIGINAL));
882                 reply_hash = hash_conntrack(net,
883                                            &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
884                                            nf_ct_zone_id(nf_ct_zone(ct), IP_CT_DIR_REPLY));
885         } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
886
887         max_chainlen = MIN_CHAINLEN + prandom_u32_max(MAX_CHAINLEN);
888
889         /* See if there's one in the list already, including reverse */
890         hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode) {
891                 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
892                                     zone, net))
893                         goto out;
894
895                 if (chainlen++ > max_chainlen)
896                         goto chaintoolong;
897         }
898
899         chainlen = 0;
900
901         hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode) {
902                 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
903                                     zone, net))
904                         goto out;
905                 if (chainlen++ > max_chainlen)
906                         goto chaintoolong;
907         }
908
909         smp_wmb();
910         /* The caller holds a reference to this object */
911         refcount_set(&ct->ct_general.use, 2);
912         __nf_conntrack_hash_insert(ct, hash, reply_hash);
913         nf_conntrack_double_unlock(hash, reply_hash);
914         NF_CT_STAT_INC(net, insert);
915         local_bh_enable();
916         return 0;
917 chaintoolong:
918         NF_CT_STAT_INC(net, chaintoolong);
919         err = -ENOSPC;
920 out:
921         nf_conntrack_double_unlock(hash, reply_hash);
922         local_bh_enable();
923         return err;
924 }
925 EXPORT_SYMBOL_GPL(nf_conntrack_hash_check_insert);
926
927 void nf_ct_acct_add(struct nf_conn *ct, u32 dir, unsigned int packets,
928                     unsigned int bytes)
929 {
930         struct nf_conn_acct *acct;
931
932         acct = nf_conn_acct_find(ct);
933         if (acct) {
934                 struct nf_conn_counter *counter = acct->counter;
935
936                 atomic64_add(packets, &counter[dir].packets);
937                 atomic64_add(bytes, &counter[dir].bytes);
938         }
939 }
940 EXPORT_SYMBOL_GPL(nf_ct_acct_add);
941
942 static void nf_ct_acct_merge(struct nf_conn *ct, enum ip_conntrack_info ctinfo,
943                              const struct nf_conn *loser_ct)
944 {
945         struct nf_conn_acct *acct;
946
947         acct = nf_conn_acct_find(loser_ct);
948         if (acct) {
949                 struct nf_conn_counter *counter = acct->counter;
950                 unsigned int bytes;
951
952                 /* u32 should be fine since we must have seen one packet. */
953                 bytes = atomic64_read(&counter[CTINFO2DIR(ctinfo)].bytes);
954                 nf_ct_acct_update(ct, CTINFO2DIR(ctinfo), bytes);
955         }
956 }
957
958 static void __nf_conntrack_insert_prepare(struct nf_conn *ct)
959 {
960         struct nf_conn_tstamp *tstamp;
961
962         refcount_inc(&ct->ct_general.use);
963         ct->status |= IPS_CONFIRMED;
964
965         /* set conntrack timestamp, if enabled. */
966         tstamp = nf_conn_tstamp_find(ct);
967         if (tstamp)
968                 tstamp->start = ktime_get_real_ns();
969 }
970
971 /* caller must hold locks to prevent concurrent changes */
972 static int __nf_ct_resolve_clash(struct sk_buff *skb,
973                                  struct nf_conntrack_tuple_hash *h)
974 {
975         /* This is the conntrack entry already in hashes that won race. */
976         struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
977         enum ip_conntrack_info ctinfo;
978         struct nf_conn *loser_ct;
979
980         loser_ct = nf_ct_get(skb, &ctinfo);
981
982         if (nf_ct_is_dying(ct))
983                 return NF_DROP;
984
985         if (((ct->status & IPS_NAT_DONE_MASK) == 0) ||
986             nf_ct_match(ct, loser_ct)) {
987                 struct net *net = nf_ct_net(ct);
988
989                 nf_conntrack_get(&ct->ct_general);
990
991                 nf_ct_acct_merge(ct, ctinfo, loser_ct);
992                 nf_ct_add_to_dying_list(loser_ct);
993                 nf_ct_put(loser_ct);
994                 nf_ct_set(skb, ct, ctinfo);
995
996                 NF_CT_STAT_INC(net, clash_resolve);
997                 return NF_ACCEPT;
998         }
999
1000         return NF_DROP;
1001 }
1002
1003 /**
1004  * nf_ct_resolve_clash_harder - attempt to insert clashing conntrack entry
1005  *
1006  * @skb: skb that causes the collision
1007  * @repl_idx: hash slot for reply direction
1008  *
1009  * Called when origin or reply direction had a clash.
1010  * The skb can be handled without packet drop provided the reply direction
1011  * is unique or there the existing entry has the identical tuple in both
1012  * directions.
1013  *
1014  * Caller must hold conntrack table locks to prevent concurrent updates.
1015  *
1016  * Returns NF_DROP if the clash could not be handled.
1017  */
1018 static int nf_ct_resolve_clash_harder(struct sk_buff *skb, u32 repl_idx)
1019 {
1020         struct nf_conn *loser_ct = (struct nf_conn *)skb_nfct(skb);
1021         const struct nf_conntrack_zone *zone;
1022         struct nf_conntrack_tuple_hash *h;
1023         struct hlist_nulls_node *n;
1024         struct net *net;
1025
1026         zone = nf_ct_zone(loser_ct);
1027         net = nf_ct_net(loser_ct);
1028
1029         /* Reply direction must never result in a clash, unless both origin
1030          * and reply tuples are identical.
1031          */
1032         hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[repl_idx], hnnode) {
1033                 if (nf_ct_key_equal(h,
1034                                     &loser_ct->tuplehash[IP_CT_DIR_REPLY].tuple,
1035                                     zone, net))
1036                         return __nf_ct_resolve_clash(skb, h);
1037         }
1038
1039         /* We want the clashing entry to go away real soon: 1 second timeout. */
1040         WRITE_ONCE(loser_ct->timeout, nfct_time_stamp + HZ);
1041
1042         /* IPS_NAT_CLASH removes the entry automatically on the first
1043          * reply.  Also prevents UDP tracker from moving the entry to
1044          * ASSURED state, i.e. the entry can always be evicted under
1045          * pressure.
1046          */
1047         loser_ct->status |= IPS_FIXED_TIMEOUT | IPS_NAT_CLASH;
1048
1049         __nf_conntrack_insert_prepare(loser_ct);
1050
1051         /* fake add for ORIGINAL dir: we want lookups to only find the entry
1052          * already in the table.  This also hides the clashing entry from
1053          * ctnetlink iteration, i.e. conntrack -L won't show them.
1054          */
1055         hlist_nulls_add_fake(&loser_ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
1056
1057         hlist_nulls_add_head_rcu(&loser_ct->tuplehash[IP_CT_DIR_REPLY].hnnode,
1058                                  &nf_conntrack_hash[repl_idx]);
1059
1060         NF_CT_STAT_INC(net, clash_resolve);
1061         return NF_ACCEPT;
1062 }
1063
1064 /**
1065  * nf_ct_resolve_clash - attempt to handle clash without packet drop
1066  *
1067  * @skb: skb that causes the clash
1068  * @h: tuplehash of the clashing entry already in table
1069  * @reply_hash: hash slot for reply direction
1070  *
1071  * A conntrack entry can be inserted to the connection tracking table
1072  * if there is no existing entry with an identical tuple.
1073  *
1074  * If there is one, @skb (and the assocated, unconfirmed conntrack) has
1075  * to be dropped.  In case @skb is retransmitted, next conntrack lookup
1076  * will find the already-existing entry.
1077  *
1078  * The major problem with such packet drop is the extra delay added by
1079  * the packet loss -- it will take some time for a retransmit to occur
1080  * (or the sender to time out when waiting for a reply).
1081  *
1082  * This function attempts to handle the situation without packet drop.
1083  *
1084  * If @skb has no NAT transformation or if the colliding entries are
1085  * exactly the same, only the to-be-confirmed conntrack entry is discarded
1086  * and @skb is associated with the conntrack entry already in the table.
1087  *
1088  * Failing that, the new, unconfirmed conntrack is still added to the table
1089  * provided that the collision only occurs in the ORIGINAL direction.
1090  * The new entry will be added only in the non-clashing REPLY direction,
1091  * so packets in the ORIGINAL direction will continue to match the existing
1092  * entry.  The new entry will also have a fixed timeout so it expires --
1093  * due to the collision, it will only see reply traffic.
1094  *
1095  * Returns NF_DROP if the clash could not be resolved.
1096  */
1097 static __cold noinline int
1098 nf_ct_resolve_clash(struct sk_buff *skb, struct nf_conntrack_tuple_hash *h,
1099                     u32 reply_hash)
1100 {
1101         /* This is the conntrack entry already in hashes that won race. */
1102         struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
1103         const struct nf_conntrack_l4proto *l4proto;
1104         enum ip_conntrack_info ctinfo;
1105         struct nf_conn *loser_ct;
1106         struct net *net;
1107         int ret;
1108
1109         loser_ct = nf_ct_get(skb, &ctinfo);
1110         net = nf_ct_net(loser_ct);
1111
1112         l4proto = nf_ct_l4proto_find(nf_ct_protonum(ct));
1113         if (!l4proto->allow_clash)
1114                 goto drop;
1115
1116         ret = __nf_ct_resolve_clash(skb, h);
1117         if (ret == NF_ACCEPT)
1118                 return ret;
1119
1120         ret = nf_ct_resolve_clash_harder(skb, reply_hash);
1121         if (ret == NF_ACCEPT)
1122                 return ret;
1123
1124 drop:
1125         nf_ct_add_to_dying_list(loser_ct);
1126         NF_CT_STAT_INC(net, drop);
1127         NF_CT_STAT_INC(net, insert_failed);
1128         return NF_DROP;
1129 }
1130
1131 /* Confirm a connection given skb; places it in hash table */
1132 int
1133 __nf_conntrack_confirm(struct sk_buff *skb)
1134 {
1135         unsigned int chainlen = 0, sequence, max_chainlen;
1136         const struct nf_conntrack_zone *zone;
1137         unsigned int hash, reply_hash;
1138         struct nf_conntrack_tuple_hash *h;
1139         struct nf_conn *ct;
1140         struct nf_conn_help *help;
1141         struct hlist_nulls_node *n;
1142         enum ip_conntrack_info ctinfo;
1143         struct net *net;
1144         int ret = NF_DROP;
1145
1146         ct = nf_ct_get(skb, &ctinfo);
1147         net = nf_ct_net(ct);
1148
1149         /* ipt_REJECT uses nf_conntrack_attach to attach related
1150            ICMP/TCP RST packets in other direction.  Actual packet
1151            which created connection will be IP_CT_NEW or for an
1152            expected connection, IP_CT_RELATED. */
1153         if (CTINFO2DIR(ctinfo) != IP_CT_DIR_ORIGINAL)
1154                 return NF_ACCEPT;
1155
1156         zone = nf_ct_zone(ct);
1157         local_bh_disable();
1158
1159         do {
1160                 sequence = read_seqcount_begin(&nf_conntrack_generation);
1161                 /* reuse the hash saved before */
1162                 hash = *(unsigned long *)&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev;
1163                 hash = scale_hash(hash);
1164                 reply_hash = hash_conntrack(net,
1165                                            &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
1166                                            nf_ct_zone_id(nf_ct_zone(ct), IP_CT_DIR_REPLY));
1167         } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
1168
1169         /* We're not in hash table, and we refuse to set up related
1170          * connections for unconfirmed conns.  But packet copies and
1171          * REJECT will give spurious warnings here.
1172          */
1173
1174         /* Another skb with the same unconfirmed conntrack may
1175          * win the race. This may happen for bridge(br_flood)
1176          * or broadcast/multicast packets do skb_clone with
1177          * unconfirmed conntrack.
1178          */
1179         if (unlikely(nf_ct_is_confirmed(ct))) {
1180                 WARN_ON_ONCE(1);
1181                 nf_conntrack_double_unlock(hash, reply_hash);
1182                 local_bh_enable();
1183                 return NF_DROP;
1184         }
1185
1186         pr_debug("Confirming conntrack %p\n", ct);
1187         /* We have to check the DYING flag after unlink to prevent
1188          * a race against nf_ct_get_next_corpse() possibly called from
1189          * user context, else we insert an already 'dead' hash, blocking
1190          * further use of that particular connection -JM.
1191          */
1192         nf_ct_del_from_dying_or_unconfirmed_list(ct);
1193
1194         if (unlikely(nf_ct_is_dying(ct))) {
1195                 nf_ct_add_to_dying_list(ct);
1196                 NF_CT_STAT_INC(net, insert_failed);
1197                 goto dying;
1198         }
1199
1200         max_chainlen = MIN_CHAINLEN + prandom_u32_max(MAX_CHAINLEN);
1201         /* See if there's one in the list already, including reverse:
1202            NAT could have grabbed it without realizing, since we're
1203            not in the hash.  If there is, we lost race. */
1204         hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode) {
1205                 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
1206                                     zone, net))
1207                         goto out;
1208                 if (chainlen++ > max_chainlen)
1209                         goto chaintoolong;
1210         }
1211
1212         chainlen = 0;
1213         hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode) {
1214                 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
1215                                     zone, net))
1216                         goto out;
1217                 if (chainlen++ > max_chainlen) {
1218 chaintoolong:
1219                         nf_ct_add_to_dying_list(ct);
1220                         NF_CT_STAT_INC(net, chaintoolong);
1221                         NF_CT_STAT_INC(net, insert_failed);
1222                         ret = NF_DROP;
1223                         goto dying;
1224                 }
1225         }
1226
1227         /* Timer relative to confirmation time, not original
1228            setting time, otherwise we'd get timer wrap in
1229            weird delay cases. */
1230         ct->timeout += nfct_time_stamp;
1231
1232         __nf_conntrack_insert_prepare(ct);
1233
1234         /* Since the lookup is lockless, hash insertion must be done after
1235          * starting the timer and setting the CONFIRMED bit. The RCU barriers
1236          * guarantee that no other CPU can find the conntrack before the above
1237          * stores are visible.
1238          */
1239         __nf_conntrack_hash_insert(ct, hash, reply_hash);
1240         nf_conntrack_double_unlock(hash, reply_hash);
1241         local_bh_enable();
1242
1243         help = nfct_help(ct);
1244         if (help && help->helper)
1245                 nf_conntrack_event_cache(IPCT_HELPER, ct);
1246
1247         nf_conntrack_event_cache(master_ct(ct) ?
1248                                  IPCT_RELATED : IPCT_NEW, ct);
1249         return NF_ACCEPT;
1250
1251 out:
1252         ret = nf_ct_resolve_clash(skb, h, reply_hash);
1253 dying:
1254         nf_conntrack_double_unlock(hash, reply_hash);
1255         local_bh_enable();
1256         return ret;
1257 }
1258 EXPORT_SYMBOL_GPL(__nf_conntrack_confirm);
1259
1260 /* Returns true if a connection correspondings to the tuple (required
1261    for NAT). */
1262 int
1263 nf_conntrack_tuple_taken(const struct nf_conntrack_tuple *tuple,
1264                          const struct nf_conn *ignored_conntrack)
1265 {
1266         struct net *net = nf_ct_net(ignored_conntrack);
1267         const struct nf_conntrack_zone *zone;
1268         struct nf_conntrack_tuple_hash *h;
1269         struct hlist_nulls_head *ct_hash;
1270         unsigned int hash, hsize;
1271         struct hlist_nulls_node *n;
1272         struct nf_conn *ct;
1273
1274         zone = nf_ct_zone(ignored_conntrack);
1275
1276         rcu_read_lock();
1277  begin:
1278         nf_conntrack_get_ht(&ct_hash, &hsize);
1279         hash = __hash_conntrack(net, tuple, nf_ct_zone_id(zone, IP_CT_DIR_REPLY), hsize);
1280
1281         hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[hash], hnnode) {
1282                 ct = nf_ct_tuplehash_to_ctrack(h);
1283
1284                 if (ct == ignored_conntrack)
1285                         continue;
1286
1287                 if (nf_ct_is_expired(ct)) {
1288                         nf_ct_gc_expired(ct);
1289                         continue;
1290                 }
1291
1292                 if (nf_ct_key_equal(h, tuple, zone, net)) {
1293                         /* Tuple is taken already, so caller will need to find
1294                          * a new source port to use.
1295                          *
1296                          * Only exception:
1297                          * If the *original tuples* are identical, then both
1298                          * conntracks refer to the same flow.
1299                          * This is a rare situation, it can occur e.g. when
1300                          * more than one UDP packet is sent from same socket
1301                          * in different threads.
1302                          *
1303                          * Let nf_ct_resolve_clash() deal with this later.
1304                          */
1305                         if (nf_ct_tuple_equal(&ignored_conntrack->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
1306                                               &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple) &&
1307                                               nf_ct_zone_equal(ct, zone, IP_CT_DIR_ORIGINAL))
1308                                 continue;
1309
1310                         NF_CT_STAT_INC_ATOMIC(net, found);
1311                         rcu_read_unlock();
1312                         return 1;
1313                 }
1314         }
1315
1316         if (get_nulls_value(n) != hash) {
1317                 NF_CT_STAT_INC_ATOMIC(net, search_restart);
1318                 goto begin;
1319         }
1320
1321         rcu_read_unlock();
1322
1323         return 0;
1324 }
1325 EXPORT_SYMBOL_GPL(nf_conntrack_tuple_taken);
1326
1327 #define NF_CT_EVICTION_RANGE    8
1328
1329 /* There's a small race here where we may free a just-assured
1330    connection.  Too bad: we're in trouble anyway. */
1331 static unsigned int early_drop_list(struct net *net,
1332                                     struct hlist_nulls_head *head)
1333 {
1334         struct nf_conntrack_tuple_hash *h;
1335         struct hlist_nulls_node *n;
1336         unsigned int drops = 0;
1337         struct nf_conn *tmp;
1338
1339         hlist_nulls_for_each_entry_rcu(h, n, head, hnnode) {
1340                 tmp = nf_ct_tuplehash_to_ctrack(h);
1341
1342                 if (test_bit(IPS_OFFLOAD_BIT, &tmp->status))
1343                         continue;
1344
1345                 if (nf_ct_is_expired(tmp)) {
1346                         nf_ct_gc_expired(tmp);
1347                         continue;
1348                 }
1349
1350                 if (test_bit(IPS_ASSURED_BIT, &tmp->status) ||
1351                     !net_eq(nf_ct_net(tmp), net) ||
1352                     nf_ct_is_dying(tmp))
1353                         continue;
1354
1355                 if (!refcount_inc_not_zero(&tmp->ct_general.use))
1356                         continue;
1357
1358                 /* kill only if still in same netns -- might have moved due to
1359                  * SLAB_TYPESAFE_BY_RCU rules.
1360                  *
1361                  * We steal the timer reference.  If that fails timer has
1362                  * already fired or someone else deleted it. Just drop ref
1363                  * and move to next entry.
1364                  */
1365                 if (net_eq(nf_ct_net(tmp), net) &&
1366                     nf_ct_is_confirmed(tmp) &&
1367                     nf_ct_delete(tmp, 0, 0))
1368                         drops++;
1369
1370                 nf_ct_put(tmp);
1371         }
1372
1373         return drops;
1374 }
1375
1376 static noinline int early_drop(struct net *net, unsigned int hash)
1377 {
1378         unsigned int i, bucket;
1379
1380         for (i = 0; i < NF_CT_EVICTION_RANGE; i++) {
1381                 struct hlist_nulls_head *ct_hash;
1382                 unsigned int hsize, drops;
1383
1384                 rcu_read_lock();
1385                 nf_conntrack_get_ht(&ct_hash, &hsize);
1386                 if (!i)
1387                         bucket = reciprocal_scale(hash, hsize);
1388                 else
1389                         bucket = (bucket + 1) % hsize;
1390
1391                 drops = early_drop_list(net, &ct_hash[bucket]);
1392                 rcu_read_unlock();
1393
1394                 if (drops) {
1395                         NF_CT_STAT_ADD_ATOMIC(net, early_drop, drops);
1396                         return true;
1397                 }
1398         }
1399
1400         return false;
1401 }
1402
1403 static bool gc_worker_skip_ct(const struct nf_conn *ct)
1404 {
1405         return !nf_ct_is_confirmed(ct) || nf_ct_is_dying(ct);
1406 }
1407
1408 static bool gc_worker_can_early_drop(const struct nf_conn *ct)
1409 {
1410         const struct nf_conntrack_l4proto *l4proto;
1411
1412         if (!test_bit(IPS_ASSURED_BIT, &ct->status))
1413                 return true;
1414
1415         l4proto = nf_ct_l4proto_find(nf_ct_protonum(ct));
1416         if (l4proto->can_early_drop && l4proto->can_early_drop(ct))
1417                 return true;
1418
1419         return false;
1420 }
1421
1422 static void gc_worker(struct work_struct *work)
1423 {
1424         unsigned long end_time = jiffies + GC_SCAN_MAX_DURATION;
1425         unsigned int i, hashsz, nf_conntrack_max95 = 0;
1426         unsigned long next_run = GC_SCAN_INTERVAL;
1427         struct conntrack_gc_work *gc_work;
1428         gc_work = container_of(work, struct conntrack_gc_work, dwork.work);
1429
1430         i = gc_work->next_bucket;
1431         if (gc_work->early_drop)
1432                 nf_conntrack_max95 = nf_conntrack_max / 100u * 95u;
1433
1434         do {
1435                 struct nf_conntrack_tuple_hash *h;
1436                 struct hlist_nulls_head *ct_hash;
1437                 struct hlist_nulls_node *n;
1438                 struct nf_conn *tmp;
1439
1440                 rcu_read_lock();
1441
1442                 nf_conntrack_get_ht(&ct_hash, &hashsz);
1443                 if (i >= hashsz) {
1444                         rcu_read_unlock();
1445                         break;
1446                 }
1447
1448                 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[i], hnnode) {
1449                         struct nf_conntrack_net *cnet;
1450                         struct net *net;
1451
1452                         tmp = nf_ct_tuplehash_to_ctrack(h);
1453
1454                         if (test_bit(IPS_OFFLOAD_BIT, &tmp->status)) {
1455                                 nf_ct_offload_timeout(tmp);
1456                                 continue;
1457                         }
1458
1459                         if (nf_ct_is_expired(tmp)) {
1460                                 nf_ct_gc_expired(tmp);
1461                                 continue;
1462                         }
1463
1464                         if (nf_conntrack_max95 == 0 || gc_worker_skip_ct(tmp))
1465                                 continue;
1466
1467                         net = nf_ct_net(tmp);
1468                         cnet = nf_ct_pernet(net);
1469                         if (atomic_read(&cnet->count) < nf_conntrack_max95)
1470                                 continue;
1471
1472                         /* need to take reference to avoid possible races */
1473                         if (!refcount_inc_not_zero(&tmp->ct_general.use))
1474                                 continue;
1475
1476                         if (gc_worker_skip_ct(tmp)) {
1477                                 nf_ct_put(tmp);
1478                                 continue;
1479                         }
1480
1481                         if (gc_worker_can_early_drop(tmp))
1482                                 nf_ct_kill(tmp);
1483
1484                         nf_ct_put(tmp);
1485                 }
1486
1487                 /* could check get_nulls_value() here and restart if ct
1488                  * was moved to another chain.  But given gc is best-effort
1489                  * we will just continue with next hash slot.
1490                  */
1491                 rcu_read_unlock();
1492                 cond_resched();
1493                 i++;
1494
1495                 if (time_after(jiffies, end_time) && i < hashsz) {
1496                         gc_work->next_bucket = i;
1497                         next_run = 0;
1498                         break;
1499                 }
1500         } while (i < hashsz);
1501
1502         if (gc_work->exiting)
1503                 return;
1504
1505         /*
1506          * Eviction will normally happen from the packet path, and not
1507          * from this gc worker.
1508          *
1509          * This worker is only here to reap expired entries when system went
1510          * idle after a busy period.
1511          */
1512         if (next_run) {
1513                 gc_work->early_drop = false;
1514                 gc_work->next_bucket = 0;
1515         }
1516         queue_delayed_work(system_power_efficient_wq, &gc_work->dwork, next_run);
1517 }
1518
1519 static void conntrack_gc_work_init(struct conntrack_gc_work *gc_work)
1520 {
1521         INIT_DEFERRABLE_WORK(&gc_work->dwork, gc_worker);
1522         gc_work->exiting = false;
1523 }
1524
1525 static struct nf_conn *
1526 __nf_conntrack_alloc(struct net *net,
1527                      const struct nf_conntrack_zone *zone,
1528                      const struct nf_conntrack_tuple *orig,
1529                      const struct nf_conntrack_tuple *repl,
1530                      gfp_t gfp, u32 hash)
1531 {
1532         struct nf_conntrack_net *cnet = nf_ct_pernet(net);
1533         unsigned int ct_count;
1534         struct nf_conn *ct;
1535
1536         /* We don't want any race condition at early drop stage */
1537         ct_count = atomic_inc_return(&cnet->count);
1538
1539         if (nf_conntrack_max && unlikely(ct_count > nf_conntrack_max)) {
1540                 if (!early_drop(net, hash)) {
1541                         if (!conntrack_gc_work.early_drop)
1542                                 conntrack_gc_work.early_drop = true;
1543                         atomic_dec(&cnet->count);
1544                         net_warn_ratelimited("nf_conntrack: table full, dropping packet\n");
1545                         return ERR_PTR(-ENOMEM);
1546                 }
1547         }
1548
1549         /*
1550          * Do not use kmem_cache_zalloc(), as this cache uses
1551          * SLAB_TYPESAFE_BY_RCU.
1552          */
1553         ct = kmem_cache_alloc(nf_conntrack_cachep, gfp);
1554         if (ct == NULL)
1555                 goto out;
1556
1557         spin_lock_init(&ct->lock);
1558         ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple = *orig;
1559         ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode.pprev = NULL;
1560         ct->tuplehash[IP_CT_DIR_REPLY].tuple = *repl;
1561         /* save hash for reusing when confirming */
1562         *(unsigned long *)(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev) = hash;
1563         ct->status = 0;
1564         WRITE_ONCE(ct->timeout, 0);
1565         write_pnet(&ct->ct_net, net);
1566         memset_after(ct, 0, __nfct_init_offset);
1567
1568         nf_ct_zone_add(ct, zone);
1569
1570         /* Because we use RCU lookups, we set ct_general.use to zero before
1571          * this is inserted in any list.
1572          */
1573         refcount_set(&ct->ct_general.use, 0);
1574         return ct;
1575 out:
1576         atomic_dec(&cnet->count);
1577         return ERR_PTR(-ENOMEM);
1578 }
1579
1580 struct nf_conn *nf_conntrack_alloc(struct net *net,
1581                                    const struct nf_conntrack_zone *zone,
1582                                    const struct nf_conntrack_tuple *orig,
1583                                    const struct nf_conntrack_tuple *repl,
1584                                    gfp_t gfp)
1585 {
1586         return __nf_conntrack_alloc(net, zone, orig, repl, gfp, 0);
1587 }
1588 EXPORT_SYMBOL_GPL(nf_conntrack_alloc);
1589
1590 void nf_conntrack_free(struct nf_conn *ct)
1591 {
1592         struct net *net = nf_ct_net(ct);
1593         struct nf_conntrack_net *cnet;
1594
1595         /* A freed object has refcnt == 0, that's
1596          * the golden rule for SLAB_TYPESAFE_BY_RCU
1597          */
1598         WARN_ON(refcount_read(&ct->ct_general.use) != 0);
1599
1600         nf_ct_ext_destroy(ct);
1601         kmem_cache_free(nf_conntrack_cachep, ct);
1602         cnet = nf_ct_pernet(net);
1603
1604         smp_mb__before_atomic();
1605         atomic_dec(&cnet->count);
1606 }
1607 EXPORT_SYMBOL_GPL(nf_conntrack_free);
1608
1609
1610 /* Allocate a new conntrack: we return -ENOMEM if classification
1611    failed due to stress.  Otherwise it really is unclassifiable. */
1612 static noinline struct nf_conntrack_tuple_hash *
1613 init_conntrack(struct net *net, struct nf_conn *tmpl,
1614                const struct nf_conntrack_tuple *tuple,
1615                struct sk_buff *skb,
1616                unsigned int dataoff, u32 hash)
1617 {
1618         struct nf_conn *ct;
1619         struct nf_conn_help *help;
1620         struct nf_conntrack_tuple repl_tuple;
1621         struct nf_conntrack_ecache *ecache;
1622         struct nf_conntrack_expect *exp = NULL;
1623         const struct nf_conntrack_zone *zone;
1624         struct nf_conn_timeout *timeout_ext;
1625         struct nf_conntrack_zone tmp;
1626         struct nf_conntrack_net *cnet;
1627
1628         if (!nf_ct_invert_tuple(&repl_tuple, tuple)) {
1629                 pr_debug("Can't invert tuple.\n");
1630                 return NULL;
1631         }
1632
1633         zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1634         ct = __nf_conntrack_alloc(net, zone, tuple, &repl_tuple, GFP_ATOMIC,
1635                                   hash);
1636         if (IS_ERR(ct))
1637                 return (struct nf_conntrack_tuple_hash *)ct;
1638
1639         if (!nf_ct_add_synproxy(ct, tmpl)) {
1640                 nf_conntrack_free(ct);
1641                 return ERR_PTR(-ENOMEM);
1642         }
1643
1644         timeout_ext = tmpl ? nf_ct_timeout_find(tmpl) : NULL;
1645
1646         if (timeout_ext)
1647                 nf_ct_timeout_ext_add(ct, rcu_dereference(timeout_ext->timeout),
1648                                       GFP_ATOMIC);
1649
1650         nf_ct_acct_ext_add(ct, GFP_ATOMIC);
1651         nf_ct_tstamp_ext_add(ct, GFP_ATOMIC);
1652         nf_ct_labels_ext_add(ct);
1653
1654         ecache = tmpl ? nf_ct_ecache_find(tmpl) : NULL;
1655         nf_ct_ecache_ext_add(ct, ecache ? ecache->ctmask : 0,
1656                                  ecache ? ecache->expmask : 0,
1657                              GFP_ATOMIC);
1658
1659         local_bh_disable();
1660         cnet = nf_ct_pernet(net);
1661         if (cnet->expect_count) {
1662                 spin_lock(&nf_conntrack_expect_lock);
1663                 exp = nf_ct_find_expectation(net, zone, tuple);
1664                 if (exp) {
1665                         pr_debug("expectation arrives ct=%p exp=%p\n",
1666                                  ct, exp);
1667                         /* Welcome, Mr. Bond.  We've been expecting you... */
1668                         __set_bit(IPS_EXPECTED_BIT, &ct->status);
1669                         /* exp->master safe, refcnt bumped in nf_ct_find_expectation */
1670                         ct->master = exp->master;
1671                         if (exp->helper) {
1672                                 help = nf_ct_helper_ext_add(ct, GFP_ATOMIC);
1673                                 if (help)
1674                                         rcu_assign_pointer(help->helper, exp->helper);
1675                         }
1676
1677 #ifdef CONFIG_NF_CONNTRACK_MARK
1678                         ct->mark = exp->master->mark;
1679 #endif
1680 #ifdef CONFIG_NF_CONNTRACK_SECMARK
1681                         ct->secmark = exp->master->secmark;
1682 #endif
1683                         NF_CT_STAT_INC(net, expect_new);
1684                 }
1685                 spin_unlock(&nf_conntrack_expect_lock);
1686         }
1687         if (!exp)
1688                 __nf_ct_try_assign_helper(ct, tmpl, GFP_ATOMIC);
1689
1690         /* Now it is inserted into the unconfirmed list, set refcount to 1. */
1691         refcount_set(&ct->ct_general.use, 1);
1692         nf_ct_add_to_unconfirmed_list(ct);
1693
1694         local_bh_enable();
1695
1696         if (exp) {
1697                 if (exp->expectfn)
1698                         exp->expectfn(ct, exp);
1699                 nf_ct_expect_put(exp);
1700         }
1701
1702         return &ct->tuplehash[IP_CT_DIR_ORIGINAL];
1703 }
1704
1705 /* On success, returns 0, sets skb->_nfct | ctinfo */
1706 static int
1707 resolve_normal_ct(struct nf_conn *tmpl,
1708                   struct sk_buff *skb,
1709                   unsigned int dataoff,
1710                   u_int8_t protonum,
1711                   const struct nf_hook_state *state)
1712 {
1713         const struct nf_conntrack_zone *zone;
1714         struct nf_conntrack_tuple tuple;
1715         struct nf_conntrack_tuple_hash *h;
1716         enum ip_conntrack_info ctinfo;
1717         struct nf_conntrack_zone tmp;
1718         u32 hash, zone_id, rid;
1719         struct nf_conn *ct;
1720
1721         if (!nf_ct_get_tuple(skb, skb_network_offset(skb),
1722                              dataoff, state->pf, protonum, state->net,
1723                              &tuple)) {
1724                 pr_debug("Can't get tuple\n");
1725                 return 0;
1726         }
1727
1728         /* look for tuple match */
1729         zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1730
1731         zone_id = nf_ct_zone_id(zone, IP_CT_DIR_ORIGINAL);
1732         hash = hash_conntrack_raw(&tuple, zone_id, state->net);
1733         h = __nf_conntrack_find_get(state->net, zone, &tuple, hash);
1734
1735         if (!h) {
1736                 rid = nf_ct_zone_id(zone, IP_CT_DIR_REPLY);
1737                 if (zone_id != rid) {
1738                         u32 tmp = hash_conntrack_raw(&tuple, rid, state->net);
1739
1740                         h = __nf_conntrack_find_get(state->net, zone, &tuple, tmp);
1741                 }
1742         }
1743
1744         if (!h) {
1745                 h = init_conntrack(state->net, tmpl, &tuple,
1746                                    skb, dataoff, hash);
1747                 if (!h)
1748                         return 0;
1749                 if (IS_ERR(h))
1750                         return PTR_ERR(h);
1751         }
1752         ct = nf_ct_tuplehash_to_ctrack(h);
1753
1754         /* It exists; we have (non-exclusive) reference. */
1755         if (NF_CT_DIRECTION(h) == IP_CT_DIR_REPLY) {
1756                 ctinfo = IP_CT_ESTABLISHED_REPLY;
1757         } else {
1758                 /* Once we've had two way comms, always ESTABLISHED. */
1759                 if (test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) {
1760                         pr_debug("normal packet for %p\n", ct);
1761                         ctinfo = IP_CT_ESTABLISHED;
1762                 } else if (test_bit(IPS_EXPECTED_BIT, &ct->status)) {
1763                         pr_debug("related packet for %p\n", ct);
1764                         ctinfo = IP_CT_RELATED;
1765                 } else {
1766                         pr_debug("new packet for %p\n", ct);
1767                         ctinfo = IP_CT_NEW;
1768                 }
1769         }
1770         nf_ct_set(skb, ct, ctinfo);
1771         return 0;
1772 }
1773
1774 /*
1775  * icmp packets need special treatment to handle error messages that are
1776  * related to a connection.
1777  *
1778  * Callers need to check if skb has a conntrack assigned when this
1779  * helper returns; in such case skb belongs to an already known connection.
1780  */
1781 static unsigned int __cold
1782 nf_conntrack_handle_icmp(struct nf_conn *tmpl,
1783                          struct sk_buff *skb,
1784                          unsigned int dataoff,
1785                          u8 protonum,
1786                          const struct nf_hook_state *state)
1787 {
1788         int ret;
1789
1790         if (state->pf == NFPROTO_IPV4 && protonum == IPPROTO_ICMP)
1791                 ret = nf_conntrack_icmpv4_error(tmpl, skb, dataoff, state);
1792 #if IS_ENABLED(CONFIG_IPV6)
1793         else if (state->pf == NFPROTO_IPV6 && protonum == IPPROTO_ICMPV6)
1794                 ret = nf_conntrack_icmpv6_error(tmpl, skb, dataoff, state);
1795 #endif
1796         else
1797                 return NF_ACCEPT;
1798
1799         if (ret <= 0)
1800                 NF_CT_STAT_INC_ATOMIC(state->net, error);
1801
1802         return ret;
1803 }
1804
1805 static int generic_packet(struct nf_conn *ct, struct sk_buff *skb,
1806                           enum ip_conntrack_info ctinfo)
1807 {
1808         const unsigned int *timeout = nf_ct_timeout_lookup(ct);
1809
1810         if (!timeout)
1811                 timeout = &nf_generic_pernet(nf_ct_net(ct))->timeout;
1812
1813         nf_ct_refresh_acct(ct, ctinfo, skb, *timeout);
1814         return NF_ACCEPT;
1815 }
1816
1817 /* Returns verdict for packet, or -1 for invalid. */
1818 static int nf_conntrack_handle_packet(struct nf_conn *ct,
1819                                       struct sk_buff *skb,
1820                                       unsigned int dataoff,
1821                                       enum ip_conntrack_info ctinfo,
1822                                       const struct nf_hook_state *state)
1823 {
1824         switch (nf_ct_protonum(ct)) {
1825         case IPPROTO_TCP:
1826                 return nf_conntrack_tcp_packet(ct, skb, dataoff,
1827                                                ctinfo, state);
1828         case IPPROTO_UDP:
1829                 return nf_conntrack_udp_packet(ct, skb, dataoff,
1830                                                ctinfo, state);
1831         case IPPROTO_ICMP:
1832                 return nf_conntrack_icmp_packet(ct, skb, ctinfo, state);
1833 #if IS_ENABLED(CONFIG_IPV6)
1834         case IPPROTO_ICMPV6:
1835                 return nf_conntrack_icmpv6_packet(ct, skb, ctinfo, state);
1836 #endif
1837 #ifdef CONFIG_NF_CT_PROTO_UDPLITE
1838         case IPPROTO_UDPLITE:
1839                 return nf_conntrack_udplite_packet(ct, skb, dataoff,
1840                                                    ctinfo, state);
1841 #endif
1842 #ifdef CONFIG_NF_CT_PROTO_SCTP
1843         case IPPROTO_SCTP:
1844                 return nf_conntrack_sctp_packet(ct, skb, dataoff,
1845                                                 ctinfo, state);
1846 #endif
1847 #ifdef CONFIG_NF_CT_PROTO_DCCP
1848         case IPPROTO_DCCP:
1849                 return nf_conntrack_dccp_packet(ct, skb, dataoff,
1850                                                 ctinfo, state);
1851 #endif
1852 #ifdef CONFIG_NF_CT_PROTO_GRE
1853         case IPPROTO_GRE:
1854                 return nf_conntrack_gre_packet(ct, skb, dataoff,
1855                                                ctinfo, state);
1856 #endif
1857         }
1858
1859         return generic_packet(ct, skb, ctinfo);
1860 }
1861
1862 unsigned int
1863 nf_conntrack_in(struct sk_buff *skb, const struct nf_hook_state *state)
1864 {
1865         enum ip_conntrack_info ctinfo;
1866         struct nf_conn *ct, *tmpl;
1867         u_int8_t protonum;
1868         int dataoff, ret;
1869
1870         tmpl = nf_ct_get(skb, &ctinfo);
1871         if (tmpl || ctinfo == IP_CT_UNTRACKED) {
1872                 /* Previously seen (loopback or untracked)?  Ignore. */
1873                 if ((tmpl && !nf_ct_is_template(tmpl)) ||
1874                      ctinfo == IP_CT_UNTRACKED)
1875                         return NF_ACCEPT;
1876                 skb->_nfct = 0;
1877         }
1878
1879         /* rcu_read_lock()ed by nf_hook_thresh */
1880         dataoff = get_l4proto(skb, skb_network_offset(skb), state->pf, &protonum);
1881         if (dataoff <= 0) {
1882                 pr_debug("not prepared to track yet or error occurred\n");
1883                 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1884                 ret = NF_ACCEPT;
1885                 goto out;
1886         }
1887
1888         if (protonum == IPPROTO_ICMP || protonum == IPPROTO_ICMPV6) {
1889                 ret = nf_conntrack_handle_icmp(tmpl, skb, dataoff,
1890                                                protonum, state);
1891                 if (ret <= 0) {
1892                         ret = -ret;
1893                         goto out;
1894                 }
1895                 /* ICMP[v6] protocol trackers may assign one conntrack. */
1896                 if (skb->_nfct)
1897                         goto out;
1898         }
1899 repeat:
1900         ret = resolve_normal_ct(tmpl, skb, dataoff,
1901                                 protonum, state);
1902         if (ret < 0) {
1903                 /* Too stressed to deal. */
1904                 NF_CT_STAT_INC_ATOMIC(state->net, drop);
1905                 ret = NF_DROP;
1906                 goto out;
1907         }
1908
1909         ct = nf_ct_get(skb, &ctinfo);
1910         if (!ct) {
1911                 /* Not valid part of a connection */
1912                 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1913                 ret = NF_ACCEPT;
1914                 goto out;
1915         }
1916
1917         ret = nf_conntrack_handle_packet(ct, skb, dataoff, ctinfo, state);
1918         if (ret <= 0) {
1919                 /* Invalid: inverse of the return code tells
1920                  * the netfilter core what to do */
1921                 pr_debug("nf_conntrack_in: Can't track with proto module\n");
1922                 nf_ct_put(ct);
1923                 skb->_nfct = 0;
1924                 /* Special case: TCP tracker reports an attempt to reopen a
1925                  * closed/aborted connection. We have to go back and create a
1926                  * fresh conntrack.
1927                  */
1928                 if (ret == -NF_REPEAT)
1929                         goto repeat;
1930
1931                 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1932                 if (ret == -NF_DROP)
1933                         NF_CT_STAT_INC_ATOMIC(state->net, drop);
1934
1935                 ret = -ret;
1936                 goto out;
1937         }
1938
1939         if (ctinfo == IP_CT_ESTABLISHED_REPLY &&
1940             !test_and_set_bit(IPS_SEEN_REPLY_BIT, &ct->status))
1941                 nf_conntrack_event_cache(IPCT_REPLY, ct);
1942 out:
1943         if (tmpl)
1944                 nf_ct_put(tmpl);
1945
1946         return ret;
1947 }
1948 EXPORT_SYMBOL_GPL(nf_conntrack_in);
1949
1950 /* Alter reply tuple (maybe alter helper).  This is for NAT, and is
1951    implicitly racy: see __nf_conntrack_confirm */
1952 void nf_conntrack_alter_reply(struct nf_conn *ct,
1953                               const struct nf_conntrack_tuple *newreply)
1954 {
1955         struct nf_conn_help *help = nfct_help(ct);
1956
1957         /* Should be unconfirmed, so not in hash table yet */
1958         WARN_ON(nf_ct_is_confirmed(ct));
1959
1960         pr_debug("Altering reply tuple of %p to ", ct);
1961         nf_ct_dump_tuple(newreply);
1962
1963         ct->tuplehash[IP_CT_DIR_REPLY].tuple = *newreply;
1964         if (ct->master || (help && !hlist_empty(&help->expectations)))
1965                 return;
1966
1967         rcu_read_lock();
1968         __nf_ct_try_assign_helper(ct, NULL, GFP_ATOMIC);
1969         rcu_read_unlock();
1970 }
1971 EXPORT_SYMBOL_GPL(nf_conntrack_alter_reply);
1972
1973 /* Refresh conntrack for this many jiffies and do accounting if do_acct is 1 */
1974 void __nf_ct_refresh_acct(struct nf_conn *ct,
1975                           enum ip_conntrack_info ctinfo,
1976                           const struct sk_buff *skb,
1977                           u32 extra_jiffies,
1978                           bool do_acct)
1979 {
1980         /* Only update if this is not a fixed timeout */
1981         if (test_bit(IPS_FIXED_TIMEOUT_BIT, &ct->status))
1982                 goto acct;
1983
1984         /* If not in hash table, timer will not be active yet */
1985         if (nf_ct_is_confirmed(ct))
1986                 extra_jiffies += nfct_time_stamp;
1987
1988         if (READ_ONCE(ct->timeout) != extra_jiffies)
1989                 WRITE_ONCE(ct->timeout, extra_jiffies);
1990 acct:
1991         if (do_acct)
1992                 nf_ct_acct_update(ct, CTINFO2DIR(ctinfo), skb->len);
1993 }
1994 EXPORT_SYMBOL_GPL(__nf_ct_refresh_acct);
1995
1996 bool nf_ct_kill_acct(struct nf_conn *ct,
1997                      enum ip_conntrack_info ctinfo,
1998                      const struct sk_buff *skb)
1999 {
2000         nf_ct_acct_update(ct, CTINFO2DIR(ctinfo), skb->len);
2001
2002         return nf_ct_delete(ct, 0, 0);
2003 }
2004 EXPORT_SYMBOL_GPL(nf_ct_kill_acct);
2005
2006 #if IS_ENABLED(CONFIG_NF_CT_NETLINK)
2007
2008 #include <linux/netfilter/nfnetlink.h>
2009 #include <linux/netfilter/nfnetlink_conntrack.h>
2010 #include <linux/mutex.h>
2011
2012 /* Generic function for tcp/udp/sctp/dccp and alike. */
2013 int nf_ct_port_tuple_to_nlattr(struct sk_buff *skb,
2014                                const struct nf_conntrack_tuple *tuple)
2015 {
2016         if (nla_put_be16(skb, CTA_PROTO_SRC_PORT, tuple->src.u.tcp.port) ||
2017             nla_put_be16(skb, CTA_PROTO_DST_PORT, tuple->dst.u.tcp.port))
2018                 goto nla_put_failure;
2019         return 0;
2020
2021 nla_put_failure:
2022         return -1;
2023 }
2024 EXPORT_SYMBOL_GPL(nf_ct_port_tuple_to_nlattr);
2025
2026 const struct nla_policy nf_ct_port_nla_policy[CTA_PROTO_MAX+1] = {
2027         [CTA_PROTO_SRC_PORT]  = { .type = NLA_U16 },
2028         [CTA_PROTO_DST_PORT]  = { .type = NLA_U16 },
2029 };
2030 EXPORT_SYMBOL_GPL(nf_ct_port_nla_policy);
2031
2032 int nf_ct_port_nlattr_to_tuple(struct nlattr *tb[],
2033                                struct nf_conntrack_tuple *t,
2034                                u_int32_t flags)
2035 {
2036         if (flags & CTA_FILTER_FLAG(CTA_PROTO_SRC_PORT)) {
2037                 if (!tb[CTA_PROTO_SRC_PORT])
2038                         return -EINVAL;
2039
2040                 t->src.u.tcp.port = nla_get_be16(tb[CTA_PROTO_SRC_PORT]);
2041         }
2042
2043         if (flags & CTA_FILTER_FLAG(CTA_PROTO_DST_PORT)) {
2044                 if (!tb[CTA_PROTO_DST_PORT])
2045                         return -EINVAL;
2046
2047                 t->dst.u.tcp.port = nla_get_be16(tb[CTA_PROTO_DST_PORT]);
2048         }
2049
2050         return 0;
2051 }
2052 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_to_tuple);
2053
2054 unsigned int nf_ct_port_nlattr_tuple_size(void)
2055 {
2056         static unsigned int size __read_mostly;
2057
2058         if (!size)
2059                 size = nla_policy_len(nf_ct_port_nla_policy, CTA_PROTO_MAX + 1);
2060
2061         return size;
2062 }
2063 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_tuple_size);
2064 #endif
2065
2066 /* Used by ipt_REJECT and ip6t_REJECT. */
2067 static void nf_conntrack_attach(struct sk_buff *nskb, const struct sk_buff *skb)
2068 {
2069         struct nf_conn *ct;
2070         enum ip_conntrack_info ctinfo;
2071
2072         /* This ICMP is in reverse direction to the packet which caused it */
2073         ct = nf_ct_get(skb, &ctinfo);
2074         if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL)
2075                 ctinfo = IP_CT_RELATED_REPLY;
2076         else
2077                 ctinfo = IP_CT_RELATED;
2078
2079         /* Attach to new skbuff, and increment count */
2080         nf_ct_set(nskb, ct, ctinfo);
2081         nf_conntrack_get(skb_nfct(nskb));
2082 }
2083
2084 static int __nf_conntrack_update(struct net *net, struct sk_buff *skb,
2085                                  struct nf_conn *ct,
2086                                  enum ip_conntrack_info ctinfo)
2087 {
2088         const struct nf_nat_hook *nat_hook;
2089         struct nf_conntrack_tuple_hash *h;
2090         struct nf_conntrack_tuple tuple;
2091         unsigned int status;
2092         int dataoff;
2093         u16 l3num;
2094         u8 l4num;
2095
2096         l3num = nf_ct_l3num(ct);
2097
2098         dataoff = get_l4proto(skb, skb_network_offset(skb), l3num, &l4num);
2099         if (dataoff <= 0)
2100                 return -1;
2101
2102         if (!nf_ct_get_tuple(skb, skb_network_offset(skb), dataoff, l3num,
2103                              l4num, net, &tuple))
2104                 return -1;
2105
2106         if (ct->status & IPS_SRC_NAT) {
2107                 memcpy(tuple.src.u3.all,
2108                        ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u3.all,
2109                        sizeof(tuple.src.u3.all));
2110                 tuple.src.u.all =
2111                         ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u.all;
2112         }
2113
2114         if (ct->status & IPS_DST_NAT) {
2115                 memcpy(tuple.dst.u3.all,
2116                        ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.u3.all,
2117                        sizeof(tuple.dst.u3.all));
2118                 tuple.dst.u.all =
2119                         ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.u.all;
2120         }
2121
2122         h = nf_conntrack_find_get(net, nf_ct_zone(ct), &tuple);
2123         if (!h)
2124                 return 0;
2125
2126         /* Store status bits of the conntrack that is clashing to re-do NAT
2127          * mangling according to what it has been done already to this packet.
2128          */
2129         status = ct->status;
2130
2131         nf_ct_put(ct);
2132         ct = nf_ct_tuplehash_to_ctrack(h);
2133         nf_ct_set(skb, ct, ctinfo);
2134
2135         nat_hook = rcu_dereference(nf_nat_hook);
2136         if (!nat_hook)
2137                 return 0;
2138
2139         if (status & IPS_SRC_NAT &&
2140             nat_hook->manip_pkt(skb, ct, NF_NAT_MANIP_SRC,
2141                                 IP_CT_DIR_ORIGINAL) == NF_DROP)
2142                 return -1;
2143
2144         if (status & IPS_DST_NAT &&
2145             nat_hook->manip_pkt(skb, ct, NF_NAT_MANIP_DST,
2146                                 IP_CT_DIR_ORIGINAL) == NF_DROP)
2147                 return -1;
2148
2149         return 0;
2150 }
2151
2152 /* This packet is coming from userspace via nf_queue, complete the packet
2153  * processing after the helper invocation in nf_confirm().
2154  */
2155 static int nf_confirm_cthelper(struct sk_buff *skb, struct nf_conn *ct,
2156                                enum ip_conntrack_info ctinfo)
2157 {
2158         const struct nf_conntrack_helper *helper;
2159         const struct nf_conn_help *help;
2160         int protoff;
2161
2162         help = nfct_help(ct);
2163         if (!help)
2164                 return 0;
2165
2166         helper = rcu_dereference(help->helper);
2167         if (!(helper->flags & NF_CT_HELPER_F_USERSPACE))
2168                 return 0;
2169
2170         switch (nf_ct_l3num(ct)) {
2171         case NFPROTO_IPV4:
2172                 protoff = skb_network_offset(skb) + ip_hdrlen(skb);
2173                 break;
2174 #if IS_ENABLED(CONFIG_IPV6)
2175         case NFPROTO_IPV6: {
2176                 __be16 frag_off;
2177                 u8 pnum;
2178
2179                 pnum = ipv6_hdr(skb)->nexthdr;
2180                 protoff = ipv6_skip_exthdr(skb, sizeof(struct ipv6hdr), &pnum,
2181                                            &frag_off);
2182                 if (protoff < 0 || (frag_off & htons(~0x7)) != 0)
2183                         return 0;
2184                 break;
2185         }
2186 #endif
2187         default:
2188                 return 0;
2189         }
2190
2191         if (test_bit(IPS_SEQ_ADJUST_BIT, &ct->status) &&
2192             !nf_is_loopback_packet(skb)) {
2193                 if (!nf_ct_seq_adjust(skb, ct, ctinfo, protoff)) {
2194                         NF_CT_STAT_INC_ATOMIC(nf_ct_net(ct), drop);
2195                         return -1;
2196                 }
2197         }
2198
2199         /* We've seen it coming out the other side: confirm it */
2200         return nf_conntrack_confirm(skb) == NF_DROP ? - 1 : 0;
2201 }
2202
2203 static int nf_conntrack_update(struct net *net, struct sk_buff *skb)
2204 {
2205         enum ip_conntrack_info ctinfo;
2206         struct nf_conn *ct;
2207         int err;
2208
2209         ct = nf_ct_get(skb, &ctinfo);
2210         if (!ct)
2211                 return 0;
2212
2213         if (!nf_ct_is_confirmed(ct)) {
2214                 err = __nf_conntrack_update(net, skb, ct, ctinfo);
2215                 if (err < 0)
2216                         return err;
2217
2218                 ct = nf_ct_get(skb, &ctinfo);
2219         }
2220
2221         return nf_confirm_cthelper(skb, ct, ctinfo);
2222 }
2223
2224 static bool nf_conntrack_get_tuple_skb(struct nf_conntrack_tuple *dst_tuple,
2225                                        const struct sk_buff *skb)
2226 {
2227         const struct nf_conntrack_tuple *src_tuple;
2228         const struct nf_conntrack_tuple_hash *hash;
2229         struct nf_conntrack_tuple srctuple;
2230         enum ip_conntrack_info ctinfo;
2231         struct nf_conn *ct;
2232
2233         ct = nf_ct_get(skb, &ctinfo);
2234         if (ct) {
2235                 src_tuple = nf_ct_tuple(ct, CTINFO2DIR(ctinfo));
2236                 memcpy(dst_tuple, src_tuple, sizeof(*dst_tuple));
2237                 return true;
2238         }
2239
2240         if (!nf_ct_get_tuplepr(skb, skb_network_offset(skb),
2241                                NFPROTO_IPV4, dev_net(skb->dev),
2242                                &srctuple))
2243                 return false;
2244
2245         hash = nf_conntrack_find_get(dev_net(skb->dev),
2246                                      &nf_ct_zone_dflt,
2247                                      &srctuple);
2248         if (!hash)
2249                 return false;
2250
2251         ct = nf_ct_tuplehash_to_ctrack(hash);
2252         src_tuple = nf_ct_tuple(ct, !hash->tuple.dst.dir);
2253         memcpy(dst_tuple, src_tuple, sizeof(*dst_tuple));
2254         nf_ct_put(ct);
2255
2256         return true;
2257 }
2258
2259 /* Bring out ya dead! */
2260 static struct nf_conn *
2261 get_next_corpse(int (*iter)(struct nf_conn *i, void *data),
2262                 void *data, unsigned int *bucket)
2263 {
2264         struct nf_conntrack_tuple_hash *h;
2265         struct nf_conn *ct;
2266         struct hlist_nulls_node *n;
2267         spinlock_t *lockp;
2268
2269         for (; *bucket < nf_conntrack_htable_size; (*bucket)++) {
2270                 struct hlist_nulls_head *hslot = &nf_conntrack_hash[*bucket];
2271
2272                 if (hlist_nulls_empty(hslot))
2273                         continue;
2274
2275                 lockp = &nf_conntrack_locks[*bucket % CONNTRACK_LOCKS];
2276                 local_bh_disable();
2277                 nf_conntrack_lock(lockp);
2278                 hlist_nulls_for_each_entry(h, n, hslot, hnnode) {
2279                         if (NF_CT_DIRECTION(h) != IP_CT_DIR_REPLY)
2280                                 continue;
2281                         /* All nf_conn objects are added to hash table twice, one
2282                          * for original direction tuple, once for the reply tuple.
2283                          *
2284                          * Exception: In the IPS_NAT_CLASH case, only the reply
2285                          * tuple is added (the original tuple already existed for
2286                          * a different object).
2287                          *
2288                          * We only need to call the iterator once for each
2289                          * conntrack, so we just use the 'reply' direction
2290                          * tuple while iterating.
2291                          */
2292                         ct = nf_ct_tuplehash_to_ctrack(h);
2293                         if (iter(ct, data))
2294                                 goto found;
2295                 }
2296                 spin_unlock(lockp);
2297                 local_bh_enable();
2298                 cond_resched();
2299         }
2300
2301         return NULL;
2302 found:
2303         refcount_inc(&ct->ct_general.use);
2304         spin_unlock(lockp);
2305         local_bh_enable();
2306         return ct;
2307 }
2308
2309 static void nf_ct_iterate_cleanup(int (*iter)(struct nf_conn *i, void *data),
2310                                   void *data, u32 portid, int report)
2311 {
2312         unsigned int bucket = 0;
2313         struct nf_conn *ct;
2314
2315         might_sleep();
2316
2317         mutex_lock(&nf_conntrack_mutex);
2318         while ((ct = get_next_corpse(iter, data, &bucket)) != NULL) {
2319                 /* Time to push up daises... */
2320
2321                 nf_ct_delete(ct, portid, report);
2322                 nf_ct_put(ct);
2323                 cond_resched();
2324         }
2325         mutex_unlock(&nf_conntrack_mutex);
2326 }
2327
2328 struct iter_data {
2329         int (*iter)(struct nf_conn *i, void *data);
2330         void *data;
2331         struct net *net;
2332 };
2333
2334 static int iter_net_only(struct nf_conn *i, void *data)
2335 {
2336         struct iter_data *d = data;
2337
2338         if (!net_eq(d->net, nf_ct_net(i)))
2339                 return 0;
2340
2341         return d->iter(i, d->data);
2342 }
2343
2344 static void
2345 __nf_ct_unconfirmed_destroy(struct net *net)
2346 {
2347         int cpu;
2348
2349         for_each_possible_cpu(cpu) {
2350                 struct nf_conntrack_tuple_hash *h;
2351                 struct hlist_nulls_node *n;
2352                 struct ct_pcpu *pcpu;
2353
2354                 pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
2355
2356                 spin_lock_bh(&pcpu->lock);
2357                 hlist_nulls_for_each_entry(h, n, &pcpu->unconfirmed, hnnode) {
2358                         struct nf_conn *ct;
2359
2360                         ct = nf_ct_tuplehash_to_ctrack(h);
2361
2362                         /* we cannot call iter() on unconfirmed list, the
2363                          * owning cpu can reallocate ct->ext at any time.
2364                          */
2365                         set_bit(IPS_DYING_BIT, &ct->status);
2366                 }
2367                 spin_unlock_bh(&pcpu->lock);
2368                 cond_resched();
2369         }
2370 }
2371
2372 void nf_ct_unconfirmed_destroy(struct net *net)
2373 {
2374         struct nf_conntrack_net *cnet = nf_ct_pernet(net);
2375
2376         might_sleep();
2377
2378         if (atomic_read(&cnet->count) > 0) {
2379                 __nf_ct_unconfirmed_destroy(net);
2380                 nf_queue_nf_hook_drop(net);
2381                 synchronize_net();
2382         }
2383 }
2384 EXPORT_SYMBOL_GPL(nf_ct_unconfirmed_destroy);
2385
2386 void nf_ct_iterate_cleanup_net(struct net *net,
2387                                int (*iter)(struct nf_conn *i, void *data),
2388                                void *data, u32 portid, int report)
2389 {
2390         struct nf_conntrack_net *cnet = nf_ct_pernet(net);
2391         struct iter_data d;
2392
2393         might_sleep();
2394
2395         if (atomic_read(&cnet->count) == 0)
2396                 return;
2397
2398         d.iter = iter;
2399         d.data = data;
2400         d.net = net;
2401
2402         nf_ct_iterate_cleanup(iter_net_only, &d, portid, report);
2403 }
2404 EXPORT_SYMBOL_GPL(nf_ct_iterate_cleanup_net);
2405
2406 /**
2407  * nf_ct_iterate_destroy - destroy unconfirmed conntracks and iterate table
2408  * @iter: callback to invoke for each conntrack
2409  * @data: data to pass to @iter
2410  *
2411  * Like nf_ct_iterate_cleanup, but first marks conntracks on the
2412  * unconfirmed list as dying (so they will not be inserted into
2413  * main table).
2414  *
2415  * Can only be called in module exit path.
2416  */
2417 void
2418 nf_ct_iterate_destroy(int (*iter)(struct nf_conn *i, void *data), void *data)
2419 {
2420         struct net *net;
2421
2422         down_read(&net_rwsem);
2423         for_each_net(net) {
2424                 struct nf_conntrack_net *cnet = nf_ct_pernet(net);
2425
2426                 if (atomic_read(&cnet->count) == 0)
2427                         continue;
2428                 __nf_ct_unconfirmed_destroy(net);
2429                 nf_queue_nf_hook_drop(net);
2430         }
2431         up_read(&net_rwsem);
2432
2433         /* Need to wait for netns cleanup worker to finish, if its
2434          * running -- it might have deleted a net namespace from
2435          * the global list, so our __nf_ct_unconfirmed_destroy() might
2436          * not have affected all namespaces.
2437          */
2438         net_ns_barrier();
2439
2440         /* a conntrack could have been unlinked from unconfirmed list
2441          * before we grabbed pcpu lock in __nf_ct_unconfirmed_destroy().
2442          * This makes sure its inserted into conntrack table.
2443          */
2444         synchronize_net();
2445
2446         nf_ct_iterate_cleanup(iter, data, 0, 0);
2447 }
2448 EXPORT_SYMBOL_GPL(nf_ct_iterate_destroy);
2449
2450 static int kill_all(struct nf_conn *i, void *data)
2451 {
2452         return net_eq(nf_ct_net(i), data);
2453 }
2454
2455 void nf_conntrack_cleanup_start(void)
2456 {
2457         conntrack_gc_work.exiting = true;
2458 }
2459
2460 void nf_conntrack_cleanup_end(void)
2461 {
2462         RCU_INIT_POINTER(nf_ct_hook, NULL);
2463         cancel_delayed_work_sync(&conntrack_gc_work.dwork);
2464         kvfree(nf_conntrack_hash);
2465
2466         nf_conntrack_proto_fini();
2467         nf_conntrack_seqadj_fini();
2468         nf_conntrack_labels_fini();
2469         nf_conntrack_helper_fini();
2470         nf_conntrack_timeout_fini();
2471         nf_conntrack_ecache_fini();
2472         nf_conntrack_tstamp_fini();
2473         nf_conntrack_acct_fini();
2474         nf_conntrack_expect_fini();
2475
2476         kmem_cache_destroy(nf_conntrack_cachep);
2477 }
2478
2479 /*
2480  * Mishearing the voices in his head, our hero wonders how he's
2481  * supposed to kill the mall.
2482  */
2483 void nf_conntrack_cleanup_net(struct net *net)
2484 {
2485         LIST_HEAD(single);
2486
2487         list_add(&net->exit_list, &single);
2488         nf_conntrack_cleanup_net_list(&single);
2489 }
2490
2491 void nf_conntrack_cleanup_net_list(struct list_head *net_exit_list)
2492 {
2493         int busy;
2494         struct net *net;
2495
2496         /*
2497          * This makes sure all current packets have passed through
2498          *  netfilter framework.  Roll on, two-stage module
2499          *  delete...
2500          */
2501         synchronize_net();
2502 i_see_dead_people:
2503         busy = 0;
2504         list_for_each_entry(net, net_exit_list, exit_list) {
2505                 struct nf_conntrack_net *cnet = nf_ct_pernet(net);
2506
2507                 nf_ct_iterate_cleanup(kill_all, net, 0, 0);
2508                 if (atomic_read(&cnet->count) != 0)
2509                         busy = 1;
2510         }
2511         if (busy) {
2512                 schedule();
2513                 goto i_see_dead_people;
2514         }
2515
2516         list_for_each_entry(net, net_exit_list, exit_list) {
2517                 nf_conntrack_ecache_pernet_fini(net);
2518                 nf_conntrack_expect_pernet_fini(net);
2519                 free_percpu(net->ct.stat);
2520                 free_percpu(net->ct.pcpu_lists);
2521         }
2522 }
2523
2524 void *nf_ct_alloc_hashtable(unsigned int *sizep, int nulls)
2525 {
2526         struct hlist_nulls_head *hash;
2527         unsigned int nr_slots, i;
2528
2529         if (*sizep > (UINT_MAX / sizeof(struct hlist_nulls_head)))
2530                 return NULL;
2531
2532         BUILD_BUG_ON(sizeof(struct hlist_nulls_head) != sizeof(struct hlist_head));
2533         nr_slots = *sizep = roundup(*sizep, PAGE_SIZE / sizeof(struct hlist_nulls_head));
2534
2535         hash = kvcalloc(nr_slots, sizeof(struct hlist_nulls_head), GFP_KERNEL);
2536
2537         if (hash && nulls)
2538                 for (i = 0; i < nr_slots; i++)
2539                         INIT_HLIST_NULLS_HEAD(&hash[i], i);
2540
2541         return hash;
2542 }
2543 EXPORT_SYMBOL_GPL(nf_ct_alloc_hashtable);
2544
2545 int nf_conntrack_hash_resize(unsigned int hashsize)
2546 {
2547         int i, bucket;
2548         unsigned int old_size;
2549         struct hlist_nulls_head *hash, *old_hash;
2550         struct nf_conntrack_tuple_hash *h;
2551         struct nf_conn *ct;
2552
2553         if (!hashsize)
2554                 return -EINVAL;
2555
2556         hash = nf_ct_alloc_hashtable(&hashsize, 1);
2557         if (!hash)
2558                 return -ENOMEM;
2559
2560         mutex_lock(&nf_conntrack_mutex);
2561         old_size = nf_conntrack_htable_size;
2562         if (old_size == hashsize) {
2563                 mutex_unlock(&nf_conntrack_mutex);
2564                 kvfree(hash);
2565                 return 0;
2566         }
2567
2568         local_bh_disable();
2569         nf_conntrack_all_lock();
2570         write_seqcount_begin(&nf_conntrack_generation);
2571
2572         /* Lookups in the old hash might happen in parallel, which means we
2573          * might get false negatives during connection lookup. New connections
2574          * created because of a false negative won't make it into the hash
2575          * though since that required taking the locks.
2576          */
2577
2578         for (i = 0; i < nf_conntrack_htable_size; i++) {
2579                 while (!hlist_nulls_empty(&nf_conntrack_hash[i])) {
2580                         unsigned int zone_id;
2581
2582                         h = hlist_nulls_entry(nf_conntrack_hash[i].first,
2583                                               struct nf_conntrack_tuple_hash, hnnode);
2584                         ct = nf_ct_tuplehash_to_ctrack(h);
2585                         hlist_nulls_del_rcu(&h->hnnode);
2586
2587                         zone_id = nf_ct_zone_id(nf_ct_zone(ct), NF_CT_DIRECTION(h));
2588                         bucket = __hash_conntrack(nf_ct_net(ct),
2589                                                   &h->tuple, zone_id, hashsize);
2590                         hlist_nulls_add_head_rcu(&h->hnnode, &hash[bucket]);
2591                 }
2592         }
2593         old_hash = nf_conntrack_hash;
2594
2595         nf_conntrack_hash = hash;
2596         nf_conntrack_htable_size = hashsize;
2597
2598         write_seqcount_end(&nf_conntrack_generation);
2599         nf_conntrack_all_unlock();
2600         local_bh_enable();
2601
2602         mutex_unlock(&nf_conntrack_mutex);
2603
2604         synchronize_net();
2605         kvfree(old_hash);
2606         return 0;
2607 }
2608
2609 int nf_conntrack_set_hashsize(const char *val, const struct kernel_param *kp)
2610 {
2611         unsigned int hashsize;
2612         int rc;
2613
2614         if (current->nsproxy->net_ns != &init_net)
2615                 return -EOPNOTSUPP;
2616
2617         /* On boot, we can set this without any fancy locking. */
2618         if (!nf_conntrack_hash)
2619                 return param_set_uint(val, kp);
2620
2621         rc = kstrtouint(val, 0, &hashsize);
2622         if (rc)
2623                 return rc;
2624
2625         return nf_conntrack_hash_resize(hashsize);
2626 }
2627
2628 static __always_inline unsigned int total_extension_size(void)
2629 {
2630         /* remember to add new extensions below */
2631         BUILD_BUG_ON(NF_CT_EXT_NUM > 10);
2632
2633         return sizeof(struct nf_ct_ext) +
2634                sizeof(struct nf_conn_help)
2635 #if IS_ENABLED(CONFIG_NF_NAT)
2636                 + sizeof(struct nf_conn_nat)
2637 #endif
2638                 + sizeof(struct nf_conn_seqadj)
2639                 + sizeof(struct nf_conn_acct)
2640 #ifdef CONFIG_NF_CONNTRACK_EVENTS
2641                 + sizeof(struct nf_conntrack_ecache)
2642 #endif
2643 #ifdef CONFIG_NF_CONNTRACK_TIMESTAMP
2644                 + sizeof(struct nf_conn_tstamp)
2645 #endif
2646 #ifdef CONFIG_NF_CONNTRACK_TIMEOUT
2647                 + sizeof(struct nf_conn_timeout)
2648 #endif
2649 #ifdef CONFIG_NF_CONNTRACK_LABELS
2650                 + sizeof(struct nf_conn_labels)
2651 #endif
2652 #if IS_ENABLED(CONFIG_NETFILTER_SYNPROXY)
2653                 + sizeof(struct nf_conn_synproxy)
2654 #endif
2655 #if IS_ENABLED(CONFIG_NET_ACT_CT)
2656                 + sizeof(struct nf_conn_act_ct_ext)
2657 #endif
2658         ;
2659 };
2660
2661 int nf_conntrack_init_start(void)
2662 {
2663         unsigned long nr_pages = totalram_pages();
2664         int max_factor = 8;
2665         int ret = -ENOMEM;
2666         int i;
2667
2668         /* struct nf_ct_ext uses u8 to store offsets/size */
2669         BUILD_BUG_ON(total_extension_size() > 255u);
2670
2671         seqcount_spinlock_init(&nf_conntrack_generation,
2672                                &nf_conntrack_locks_all_lock);
2673
2674         for (i = 0; i < CONNTRACK_LOCKS; i++)
2675                 spin_lock_init(&nf_conntrack_locks[i]);
2676
2677         if (!nf_conntrack_htable_size) {
2678                 nf_conntrack_htable_size
2679                         = (((nr_pages << PAGE_SHIFT) / 16384)
2680                            / sizeof(struct hlist_head));
2681                 if (BITS_PER_LONG >= 64 &&
2682                     nr_pages > (4 * (1024 * 1024 * 1024 / PAGE_SIZE)))
2683                         nf_conntrack_htable_size = 262144;
2684                 else if (nr_pages > (1024 * 1024 * 1024 / PAGE_SIZE))
2685                         nf_conntrack_htable_size = 65536;
2686
2687                 if (nf_conntrack_htable_size < 1024)
2688                         nf_conntrack_htable_size = 1024;
2689                 /* Use a max. factor of one by default to keep the average
2690                  * hash chain length at 2 entries.  Each entry has to be added
2691                  * twice (once for original direction, once for reply).
2692                  * When a table size is given we use the old value of 8 to
2693                  * avoid implicit reduction of the max entries setting.
2694                  */
2695                 max_factor = 1;
2696         }
2697
2698         nf_conntrack_hash = nf_ct_alloc_hashtable(&nf_conntrack_htable_size, 1);
2699         if (!nf_conntrack_hash)
2700                 return -ENOMEM;
2701
2702         nf_conntrack_max = max_factor * nf_conntrack_htable_size;
2703
2704         nf_conntrack_cachep = kmem_cache_create("nf_conntrack",
2705                                                 sizeof(struct nf_conn),
2706                                                 NFCT_INFOMASK + 1,
2707                                                 SLAB_TYPESAFE_BY_RCU | SLAB_HWCACHE_ALIGN, NULL);
2708         if (!nf_conntrack_cachep)
2709                 goto err_cachep;
2710
2711         ret = nf_conntrack_expect_init();
2712         if (ret < 0)
2713                 goto err_expect;
2714
2715         ret = nf_conntrack_acct_init();
2716         if (ret < 0)
2717                 goto err_acct;
2718
2719         ret = nf_conntrack_tstamp_init();
2720         if (ret < 0)
2721                 goto err_tstamp;
2722
2723         ret = nf_conntrack_ecache_init();
2724         if (ret < 0)
2725                 goto err_ecache;
2726
2727         ret = nf_conntrack_timeout_init();
2728         if (ret < 0)
2729                 goto err_timeout;
2730
2731         ret = nf_conntrack_helper_init();
2732         if (ret < 0)
2733                 goto err_helper;
2734
2735         ret = nf_conntrack_labels_init();
2736         if (ret < 0)
2737                 goto err_labels;
2738
2739         ret = nf_conntrack_seqadj_init();
2740         if (ret < 0)
2741                 goto err_seqadj;
2742
2743         ret = nf_conntrack_proto_init();
2744         if (ret < 0)
2745                 goto err_proto;
2746
2747         conntrack_gc_work_init(&conntrack_gc_work);
2748         queue_delayed_work(system_power_efficient_wq, &conntrack_gc_work.dwork, HZ);
2749
2750         return 0;
2751
2752 err_proto:
2753         nf_conntrack_seqadj_fini();
2754 err_seqadj:
2755         nf_conntrack_labels_fini();
2756 err_labels:
2757         nf_conntrack_helper_fini();
2758 err_helper:
2759         nf_conntrack_timeout_fini();
2760 err_timeout:
2761         nf_conntrack_ecache_fini();
2762 err_ecache:
2763         nf_conntrack_tstamp_fini();
2764 err_tstamp:
2765         nf_conntrack_acct_fini();
2766 err_acct:
2767         nf_conntrack_expect_fini();
2768 err_expect:
2769         kmem_cache_destroy(nf_conntrack_cachep);
2770 err_cachep:
2771         kvfree(nf_conntrack_hash);
2772         return ret;
2773 }
2774
2775 static const struct nf_ct_hook nf_conntrack_hook = {
2776         .update         = nf_conntrack_update,
2777         .destroy        = nf_ct_destroy,
2778         .get_tuple_skb  = nf_conntrack_get_tuple_skb,
2779         .attach         = nf_conntrack_attach,
2780 };
2781
2782 void nf_conntrack_init_end(void)
2783 {
2784         RCU_INIT_POINTER(nf_ct_hook, &nf_conntrack_hook);
2785 }
2786
2787 /*
2788  * We need to use special "null" values, not used in hash table
2789  */
2790 #define UNCONFIRMED_NULLS_VAL   ((1<<30)+0)
2791 #define DYING_NULLS_VAL         ((1<<30)+1)
2792
2793 int nf_conntrack_init_net(struct net *net)
2794 {
2795         struct nf_conntrack_net *cnet = nf_ct_pernet(net);
2796         int ret = -ENOMEM;
2797         int cpu;
2798
2799         BUILD_BUG_ON(IP_CT_UNTRACKED == IP_CT_NUMBER);
2800         BUILD_BUG_ON_NOT_POWER_OF_2(CONNTRACK_LOCKS);
2801         atomic_set(&cnet->count, 0);
2802
2803         net->ct.pcpu_lists = alloc_percpu(struct ct_pcpu);
2804         if (!net->ct.pcpu_lists)
2805                 goto err_stat;
2806
2807         for_each_possible_cpu(cpu) {
2808                 struct ct_pcpu *pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
2809
2810                 spin_lock_init(&pcpu->lock);
2811                 INIT_HLIST_NULLS_HEAD(&pcpu->unconfirmed, UNCONFIRMED_NULLS_VAL);
2812                 INIT_HLIST_NULLS_HEAD(&pcpu->dying, DYING_NULLS_VAL);
2813         }
2814
2815         net->ct.stat = alloc_percpu(struct ip_conntrack_stat);
2816         if (!net->ct.stat)
2817                 goto err_pcpu_lists;
2818
2819         ret = nf_conntrack_expect_pernet_init(net);
2820         if (ret < 0)
2821                 goto err_expect;
2822
2823         nf_conntrack_acct_pernet_init(net);
2824         nf_conntrack_tstamp_pernet_init(net);
2825         nf_conntrack_ecache_pernet_init(net);
2826         nf_conntrack_helper_pernet_init(net);
2827         nf_conntrack_proto_pernet_init(net);
2828
2829         return 0;
2830
2831 err_expect:
2832         free_percpu(net->ct.stat);
2833 err_pcpu_lists:
2834         free_percpu(net->ct.pcpu_lists);
2835 err_stat:
2836         return ret;
2837 }