clk: Drop the rate range on clk_put()
[linux-2.6-microblaze.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                 ct->local_origin = state->hook == NF_INET_LOCAL_OUT;
1754         }
1755         ct = nf_ct_tuplehash_to_ctrack(h);
1756
1757         /* It exists; we have (non-exclusive) reference. */
1758         if (NF_CT_DIRECTION(h) == IP_CT_DIR_REPLY) {
1759                 ctinfo = IP_CT_ESTABLISHED_REPLY;
1760         } else {
1761                 /* Once we've had two way comms, always ESTABLISHED. */
1762                 if (test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) {
1763                         pr_debug("normal packet for %p\n", ct);
1764                         ctinfo = IP_CT_ESTABLISHED;
1765                 } else if (test_bit(IPS_EXPECTED_BIT, &ct->status)) {
1766                         pr_debug("related packet for %p\n", ct);
1767                         ctinfo = IP_CT_RELATED;
1768                 } else {
1769                         pr_debug("new packet for %p\n", ct);
1770                         ctinfo = IP_CT_NEW;
1771                 }
1772         }
1773         nf_ct_set(skb, ct, ctinfo);
1774         return 0;
1775 }
1776
1777 /*
1778  * icmp packets need special treatment to handle error messages that are
1779  * related to a connection.
1780  *
1781  * Callers need to check if skb has a conntrack assigned when this
1782  * helper returns; in such case skb belongs to an already known connection.
1783  */
1784 static unsigned int __cold
1785 nf_conntrack_handle_icmp(struct nf_conn *tmpl,
1786                          struct sk_buff *skb,
1787                          unsigned int dataoff,
1788                          u8 protonum,
1789                          const struct nf_hook_state *state)
1790 {
1791         int ret;
1792
1793         if (state->pf == NFPROTO_IPV4 && protonum == IPPROTO_ICMP)
1794                 ret = nf_conntrack_icmpv4_error(tmpl, skb, dataoff, state);
1795 #if IS_ENABLED(CONFIG_IPV6)
1796         else if (state->pf == NFPROTO_IPV6 && protonum == IPPROTO_ICMPV6)
1797                 ret = nf_conntrack_icmpv6_error(tmpl, skb, dataoff, state);
1798 #endif
1799         else
1800                 return NF_ACCEPT;
1801
1802         if (ret <= 0)
1803                 NF_CT_STAT_INC_ATOMIC(state->net, error);
1804
1805         return ret;
1806 }
1807
1808 static int generic_packet(struct nf_conn *ct, struct sk_buff *skb,
1809                           enum ip_conntrack_info ctinfo)
1810 {
1811         const unsigned int *timeout = nf_ct_timeout_lookup(ct);
1812
1813         if (!timeout)
1814                 timeout = &nf_generic_pernet(nf_ct_net(ct))->timeout;
1815
1816         nf_ct_refresh_acct(ct, ctinfo, skb, *timeout);
1817         return NF_ACCEPT;
1818 }
1819
1820 /* Returns verdict for packet, or -1 for invalid. */
1821 static int nf_conntrack_handle_packet(struct nf_conn *ct,
1822                                       struct sk_buff *skb,
1823                                       unsigned int dataoff,
1824                                       enum ip_conntrack_info ctinfo,
1825                                       const struct nf_hook_state *state)
1826 {
1827         switch (nf_ct_protonum(ct)) {
1828         case IPPROTO_TCP:
1829                 return nf_conntrack_tcp_packet(ct, skb, dataoff,
1830                                                ctinfo, state);
1831         case IPPROTO_UDP:
1832                 return nf_conntrack_udp_packet(ct, skb, dataoff,
1833                                                ctinfo, state);
1834         case IPPROTO_ICMP:
1835                 return nf_conntrack_icmp_packet(ct, skb, ctinfo, state);
1836 #if IS_ENABLED(CONFIG_IPV6)
1837         case IPPROTO_ICMPV6:
1838                 return nf_conntrack_icmpv6_packet(ct, skb, ctinfo, state);
1839 #endif
1840 #ifdef CONFIG_NF_CT_PROTO_UDPLITE
1841         case IPPROTO_UDPLITE:
1842                 return nf_conntrack_udplite_packet(ct, skb, dataoff,
1843                                                    ctinfo, state);
1844 #endif
1845 #ifdef CONFIG_NF_CT_PROTO_SCTP
1846         case IPPROTO_SCTP:
1847                 return nf_conntrack_sctp_packet(ct, skb, dataoff,
1848                                                 ctinfo, state);
1849 #endif
1850 #ifdef CONFIG_NF_CT_PROTO_DCCP
1851         case IPPROTO_DCCP:
1852                 return nf_conntrack_dccp_packet(ct, skb, dataoff,
1853                                                 ctinfo, state);
1854 #endif
1855 #ifdef CONFIG_NF_CT_PROTO_GRE
1856         case IPPROTO_GRE:
1857                 return nf_conntrack_gre_packet(ct, skb, dataoff,
1858                                                ctinfo, state);
1859 #endif
1860         }
1861
1862         return generic_packet(ct, skb, ctinfo);
1863 }
1864
1865 unsigned int
1866 nf_conntrack_in(struct sk_buff *skb, const struct nf_hook_state *state)
1867 {
1868         enum ip_conntrack_info ctinfo;
1869         struct nf_conn *ct, *tmpl;
1870         u_int8_t protonum;
1871         int dataoff, ret;
1872
1873         tmpl = nf_ct_get(skb, &ctinfo);
1874         if (tmpl || ctinfo == IP_CT_UNTRACKED) {
1875                 /* Previously seen (loopback or untracked)?  Ignore. */
1876                 if ((tmpl && !nf_ct_is_template(tmpl)) ||
1877                      ctinfo == IP_CT_UNTRACKED)
1878                         return NF_ACCEPT;
1879                 skb->_nfct = 0;
1880         }
1881
1882         /* rcu_read_lock()ed by nf_hook_thresh */
1883         dataoff = get_l4proto(skb, skb_network_offset(skb), state->pf, &protonum);
1884         if (dataoff <= 0) {
1885                 pr_debug("not prepared to track yet or error occurred\n");
1886                 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1887                 ret = NF_ACCEPT;
1888                 goto out;
1889         }
1890
1891         if (protonum == IPPROTO_ICMP || protonum == IPPROTO_ICMPV6) {
1892                 ret = nf_conntrack_handle_icmp(tmpl, skb, dataoff,
1893                                                protonum, state);
1894                 if (ret <= 0) {
1895                         ret = -ret;
1896                         goto out;
1897                 }
1898                 /* ICMP[v6] protocol trackers may assign one conntrack. */
1899                 if (skb->_nfct)
1900                         goto out;
1901         }
1902 repeat:
1903         ret = resolve_normal_ct(tmpl, skb, dataoff,
1904                                 protonum, state);
1905         if (ret < 0) {
1906                 /* Too stressed to deal. */
1907                 NF_CT_STAT_INC_ATOMIC(state->net, drop);
1908                 ret = NF_DROP;
1909                 goto out;
1910         }
1911
1912         ct = nf_ct_get(skb, &ctinfo);
1913         if (!ct) {
1914                 /* Not valid part of a connection */
1915                 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1916                 ret = NF_ACCEPT;
1917                 goto out;
1918         }
1919
1920         ret = nf_conntrack_handle_packet(ct, skb, dataoff, ctinfo, state);
1921         if (ret <= 0) {
1922                 /* Invalid: inverse of the return code tells
1923                  * the netfilter core what to do */
1924                 pr_debug("nf_conntrack_in: Can't track with proto module\n");
1925                 nf_ct_put(ct);
1926                 skb->_nfct = 0;
1927                 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1928                 if (ret == -NF_DROP)
1929                         NF_CT_STAT_INC_ATOMIC(state->net, drop);
1930                 /* Special case: TCP tracker reports an attempt to reopen a
1931                  * closed/aborted connection. We have to go back and create a
1932                  * fresh conntrack.
1933                  */
1934                 if (ret == -NF_REPEAT)
1935                         goto repeat;
1936                 ret = -ret;
1937                 goto out;
1938         }
1939
1940         if (ctinfo == IP_CT_ESTABLISHED_REPLY &&
1941             !test_and_set_bit(IPS_SEEN_REPLY_BIT, &ct->status))
1942                 nf_conntrack_event_cache(IPCT_REPLY, ct);
1943 out:
1944         if (tmpl)
1945                 nf_ct_put(tmpl);
1946
1947         return ret;
1948 }
1949 EXPORT_SYMBOL_GPL(nf_conntrack_in);
1950
1951 /* Alter reply tuple (maybe alter helper).  This is for NAT, and is
1952    implicitly racy: see __nf_conntrack_confirm */
1953 void nf_conntrack_alter_reply(struct nf_conn *ct,
1954                               const struct nf_conntrack_tuple *newreply)
1955 {
1956         struct nf_conn_help *help = nfct_help(ct);
1957
1958         /* Should be unconfirmed, so not in hash table yet */
1959         WARN_ON(nf_ct_is_confirmed(ct));
1960
1961         pr_debug("Altering reply tuple of %p to ", ct);
1962         nf_ct_dump_tuple(newreply);
1963
1964         ct->tuplehash[IP_CT_DIR_REPLY].tuple = *newreply;
1965         if (ct->master || (help && !hlist_empty(&help->expectations)))
1966                 return;
1967
1968         rcu_read_lock();
1969         __nf_ct_try_assign_helper(ct, NULL, GFP_ATOMIC);
1970         rcu_read_unlock();
1971 }
1972 EXPORT_SYMBOL_GPL(nf_conntrack_alter_reply);
1973
1974 /* Refresh conntrack for this many jiffies and do accounting if do_acct is 1 */
1975 void __nf_ct_refresh_acct(struct nf_conn *ct,
1976                           enum ip_conntrack_info ctinfo,
1977                           const struct sk_buff *skb,
1978                           u32 extra_jiffies,
1979                           bool do_acct)
1980 {
1981         /* Only update if this is not a fixed timeout */
1982         if (test_bit(IPS_FIXED_TIMEOUT_BIT, &ct->status))
1983                 goto acct;
1984
1985         /* If not in hash table, timer will not be active yet */
1986         if (nf_ct_is_confirmed(ct))
1987                 extra_jiffies += nfct_time_stamp;
1988
1989         if (READ_ONCE(ct->timeout) != extra_jiffies)
1990                 WRITE_ONCE(ct->timeout, extra_jiffies);
1991 acct:
1992         if (do_acct)
1993                 nf_ct_acct_update(ct, CTINFO2DIR(ctinfo), skb->len);
1994 }
1995 EXPORT_SYMBOL_GPL(__nf_ct_refresh_acct);
1996
1997 bool nf_ct_kill_acct(struct nf_conn *ct,
1998                      enum ip_conntrack_info ctinfo,
1999                      const struct sk_buff *skb)
2000 {
2001         nf_ct_acct_update(ct, CTINFO2DIR(ctinfo), skb->len);
2002
2003         return nf_ct_delete(ct, 0, 0);
2004 }
2005 EXPORT_SYMBOL_GPL(nf_ct_kill_acct);
2006
2007 #if IS_ENABLED(CONFIG_NF_CT_NETLINK)
2008
2009 #include <linux/netfilter/nfnetlink.h>
2010 #include <linux/netfilter/nfnetlink_conntrack.h>
2011 #include <linux/mutex.h>
2012
2013 /* Generic function for tcp/udp/sctp/dccp and alike. */
2014 int nf_ct_port_tuple_to_nlattr(struct sk_buff *skb,
2015                                const struct nf_conntrack_tuple *tuple)
2016 {
2017         if (nla_put_be16(skb, CTA_PROTO_SRC_PORT, tuple->src.u.tcp.port) ||
2018             nla_put_be16(skb, CTA_PROTO_DST_PORT, tuple->dst.u.tcp.port))
2019                 goto nla_put_failure;
2020         return 0;
2021
2022 nla_put_failure:
2023         return -1;
2024 }
2025 EXPORT_SYMBOL_GPL(nf_ct_port_tuple_to_nlattr);
2026
2027 const struct nla_policy nf_ct_port_nla_policy[CTA_PROTO_MAX+1] = {
2028         [CTA_PROTO_SRC_PORT]  = { .type = NLA_U16 },
2029         [CTA_PROTO_DST_PORT]  = { .type = NLA_U16 },
2030 };
2031 EXPORT_SYMBOL_GPL(nf_ct_port_nla_policy);
2032
2033 int nf_ct_port_nlattr_to_tuple(struct nlattr *tb[],
2034                                struct nf_conntrack_tuple *t,
2035                                u_int32_t flags)
2036 {
2037         if (flags & CTA_FILTER_FLAG(CTA_PROTO_SRC_PORT)) {
2038                 if (!tb[CTA_PROTO_SRC_PORT])
2039                         return -EINVAL;
2040
2041                 t->src.u.tcp.port = nla_get_be16(tb[CTA_PROTO_SRC_PORT]);
2042         }
2043
2044         if (flags & CTA_FILTER_FLAG(CTA_PROTO_DST_PORT)) {
2045                 if (!tb[CTA_PROTO_DST_PORT])
2046                         return -EINVAL;
2047
2048                 t->dst.u.tcp.port = nla_get_be16(tb[CTA_PROTO_DST_PORT]);
2049         }
2050
2051         return 0;
2052 }
2053 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_to_tuple);
2054
2055 unsigned int nf_ct_port_nlattr_tuple_size(void)
2056 {
2057         static unsigned int size __read_mostly;
2058
2059         if (!size)
2060                 size = nla_policy_len(nf_ct_port_nla_policy, CTA_PROTO_MAX + 1);
2061
2062         return size;
2063 }
2064 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_tuple_size);
2065 #endif
2066
2067 /* Used by ipt_REJECT and ip6t_REJECT. */
2068 static void nf_conntrack_attach(struct sk_buff *nskb, const struct sk_buff *skb)
2069 {
2070         struct nf_conn *ct;
2071         enum ip_conntrack_info ctinfo;
2072
2073         /* This ICMP is in reverse direction to the packet which caused it */
2074         ct = nf_ct_get(skb, &ctinfo);
2075         if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL)
2076                 ctinfo = IP_CT_RELATED_REPLY;
2077         else
2078                 ctinfo = IP_CT_RELATED;
2079
2080         /* Attach to new skbuff, and increment count */
2081         nf_ct_set(nskb, ct, ctinfo);
2082         nf_conntrack_get(skb_nfct(nskb));
2083 }
2084
2085 static int __nf_conntrack_update(struct net *net, struct sk_buff *skb,
2086                                  struct nf_conn *ct,
2087                                  enum ip_conntrack_info ctinfo)
2088 {
2089         const struct nf_nat_hook *nat_hook;
2090         struct nf_conntrack_tuple_hash *h;
2091         struct nf_conntrack_tuple tuple;
2092         unsigned int status;
2093         int dataoff;
2094         u16 l3num;
2095         u8 l4num;
2096
2097         l3num = nf_ct_l3num(ct);
2098
2099         dataoff = get_l4proto(skb, skb_network_offset(skb), l3num, &l4num);
2100         if (dataoff <= 0)
2101                 return -1;
2102
2103         if (!nf_ct_get_tuple(skb, skb_network_offset(skb), dataoff, l3num,
2104                              l4num, net, &tuple))
2105                 return -1;
2106
2107         if (ct->status & IPS_SRC_NAT) {
2108                 memcpy(tuple.src.u3.all,
2109                        ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u3.all,
2110                        sizeof(tuple.src.u3.all));
2111                 tuple.src.u.all =
2112                         ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u.all;
2113         }
2114
2115         if (ct->status & IPS_DST_NAT) {
2116                 memcpy(tuple.dst.u3.all,
2117                        ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.u3.all,
2118                        sizeof(tuple.dst.u3.all));
2119                 tuple.dst.u.all =
2120                         ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.u.all;
2121         }
2122
2123         h = nf_conntrack_find_get(net, nf_ct_zone(ct), &tuple);
2124         if (!h)
2125                 return 0;
2126
2127         /* Store status bits of the conntrack that is clashing to re-do NAT
2128          * mangling according to what it has been done already to this packet.
2129          */
2130         status = ct->status;
2131
2132         nf_ct_put(ct);
2133         ct = nf_ct_tuplehash_to_ctrack(h);
2134         nf_ct_set(skb, ct, ctinfo);
2135
2136         nat_hook = rcu_dereference(nf_nat_hook);
2137         if (!nat_hook)
2138                 return 0;
2139
2140         if (status & IPS_SRC_NAT &&
2141             nat_hook->manip_pkt(skb, ct, NF_NAT_MANIP_SRC,
2142                                 IP_CT_DIR_ORIGINAL) == NF_DROP)
2143                 return -1;
2144
2145         if (status & IPS_DST_NAT &&
2146             nat_hook->manip_pkt(skb, ct, NF_NAT_MANIP_DST,
2147                                 IP_CT_DIR_ORIGINAL) == NF_DROP)
2148                 return -1;
2149
2150         return 0;
2151 }
2152
2153 /* This packet is coming from userspace via nf_queue, complete the packet
2154  * processing after the helper invocation in nf_confirm().
2155  */
2156 static int nf_confirm_cthelper(struct sk_buff *skb, struct nf_conn *ct,
2157                                enum ip_conntrack_info ctinfo)
2158 {
2159         const struct nf_conntrack_helper *helper;
2160         const struct nf_conn_help *help;
2161         int protoff;
2162
2163         help = nfct_help(ct);
2164         if (!help)
2165                 return 0;
2166
2167         helper = rcu_dereference(help->helper);
2168         if (!(helper->flags & NF_CT_HELPER_F_USERSPACE))
2169                 return 0;
2170
2171         switch (nf_ct_l3num(ct)) {
2172         case NFPROTO_IPV4:
2173                 protoff = skb_network_offset(skb) + ip_hdrlen(skb);
2174                 break;
2175 #if IS_ENABLED(CONFIG_IPV6)
2176         case NFPROTO_IPV6: {
2177                 __be16 frag_off;
2178                 u8 pnum;
2179
2180                 pnum = ipv6_hdr(skb)->nexthdr;
2181                 protoff = ipv6_skip_exthdr(skb, sizeof(struct ipv6hdr), &pnum,
2182                                            &frag_off);
2183                 if (protoff < 0 || (frag_off & htons(~0x7)) != 0)
2184                         return 0;
2185                 break;
2186         }
2187 #endif
2188         default:
2189                 return 0;
2190         }
2191
2192         if (test_bit(IPS_SEQ_ADJUST_BIT, &ct->status) &&
2193             !nf_is_loopback_packet(skb)) {
2194                 if (!nf_ct_seq_adjust(skb, ct, ctinfo, protoff)) {
2195                         NF_CT_STAT_INC_ATOMIC(nf_ct_net(ct), drop);
2196                         return -1;
2197                 }
2198         }
2199
2200         /* We've seen it coming out the other side: confirm it */
2201         return nf_conntrack_confirm(skb) == NF_DROP ? - 1 : 0;
2202 }
2203
2204 static int nf_conntrack_update(struct net *net, struct sk_buff *skb)
2205 {
2206         enum ip_conntrack_info ctinfo;
2207         struct nf_conn *ct;
2208         int err;
2209
2210         ct = nf_ct_get(skb, &ctinfo);
2211         if (!ct)
2212                 return 0;
2213
2214         if (!nf_ct_is_confirmed(ct)) {
2215                 err = __nf_conntrack_update(net, skb, ct, ctinfo);
2216                 if (err < 0)
2217                         return err;
2218
2219                 ct = nf_ct_get(skb, &ctinfo);
2220         }
2221
2222         return nf_confirm_cthelper(skb, ct, ctinfo);
2223 }
2224
2225 static bool nf_conntrack_get_tuple_skb(struct nf_conntrack_tuple *dst_tuple,
2226                                        const struct sk_buff *skb)
2227 {
2228         const struct nf_conntrack_tuple *src_tuple;
2229         const struct nf_conntrack_tuple_hash *hash;
2230         struct nf_conntrack_tuple srctuple;
2231         enum ip_conntrack_info ctinfo;
2232         struct nf_conn *ct;
2233
2234         ct = nf_ct_get(skb, &ctinfo);
2235         if (ct) {
2236                 src_tuple = nf_ct_tuple(ct, CTINFO2DIR(ctinfo));
2237                 memcpy(dst_tuple, src_tuple, sizeof(*dst_tuple));
2238                 return true;
2239         }
2240
2241         if (!nf_ct_get_tuplepr(skb, skb_network_offset(skb),
2242                                NFPROTO_IPV4, dev_net(skb->dev),
2243                                &srctuple))
2244                 return false;
2245
2246         hash = nf_conntrack_find_get(dev_net(skb->dev),
2247                                      &nf_ct_zone_dflt,
2248                                      &srctuple);
2249         if (!hash)
2250                 return false;
2251
2252         ct = nf_ct_tuplehash_to_ctrack(hash);
2253         src_tuple = nf_ct_tuple(ct, !hash->tuple.dst.dir);
2254         memcpy(dst_tuple, src_tuple, sizeof(*dst_tuple));
2255         nf_ct_put(ct);
2256
2257         return true;
2258 }
2259
2260 /* Bring out ya dead! */
2261 static struct nf_conn *
2262 get_next_corpse(int (*iter)(struct nf_conn *i, void *data),
2263                 void *data, unsigned int *bucket)
2264 {
2265         struct nf_conntrack_tuple_hash *h;
2266         struct nf_conn *ct;
2267         struct hlist_nulls_node *n;
2268         spinlock_t *lockp;
2269
2270         for (; *bucket < nf_conntrack_htable_size; (*bucket)++) {
2271                 struct hlist_nulls_head *hslot = &nf_conntrack_hash[*bucket];
2272
2273                 if (hlist_nulls_empty(hslot))
2274                         continue;
2275
2276                 lockp = &nf_conntrack_locks[*bucket % CONNTRACK_LOCKS];
2277                 local_bh_disable();
2278                 nf_conntrack_lock(lockp);
2279                 hlist_nulls_for_each_entry(h, n, hslot, hnnode) {
2280                         if (NF_CT_DIRECTION(h) != IP_CT_DIR_REPLY)
2281                                 continue;
2282                         /* All nf_conn objects are added to hash table twice, one
2283                          * for original direction tuple, once for the reply tuple.
2284                          *
2285                          * Exception: In the IPS_NAT_CLASH case, only the reply
2286                          * tuple is added (the original tuple already existed for
2287                          * a different object).
2288                          *
2289                          * We only need to call the iterator once for each
2290                          * conntrack, so we just use the 'reply' direction
2291                          * tuple while iterating.
2292                          */
2293                         ct = nf_ct_tuplehash_to_ctrack(h);
2294                         if (iter(ct, data))
2295                                 goto found;
2296                 }
2297                 spin_unlock(lockp);
2298                 local_bh_enable();
2299                 cond_resched();
2300         }
2301
2302         return NULL;
2303 found:
2304         refcount_inc(&ct->ct_general.use);
2305         spin_unlock(lockp);
2306         local_bh_enable();
2307         return ct;
2308 }
2309
2310 static void nf_ct_iterate_cleanup(int (*iter)(struct nf_conn *i, void *data),
2311                                   void *data, u32 portid, int report)
2312 {
2313         unsigned int bucket = 0;
2314         struct nf_conn *ct;
2315
2316         might_sleep();
2317
2318         mutex_lock(&nf_conntrack_mutex);
2319         while ((ct = get_next_corpse(iter, data, &bucket)) != NULL) {
2320                 /* Time to push up daises... */
2321
2322                 nf_ct_delete(ct, portid, report);
2323                 nf_ct_put(ct);
2324                 cond_resched();
2325         }
2326         mutex_unlock(&nf_conntrack_mutex);
2327 }
2328
2329 struct iter_data {
2330         int (*iter)(struct nf_conn *i, void *data);
2331         void *data;
2332         struct net *net;
2333 };
2334
2335 static int iter_net_only(struct nf_conn *i, void *data)
2336 {
2337         struct iter_data *d = data;
2338
2339         if (!net_eq(d->net, nf_ct_net(i)))
2340                 return 0;
2341
2342         return d->iter(i, d->data);
2343 }
2344
2345 static void
2346 __nf_ct_unconfirmed_destroy(struct net *net)
2347 {
2348         int cpu;
2349
2350         for_each_possible_cpu(cpu) {
2351                 struct nf_conntrack_tuple_hash *h;
2352                 struct hlist_nulls_node *n;
2353                 struct ct_pcpu *pcpu;
2354
2355                 pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
2356
2357                 spin_lock_bh(&pcpu->lock);
2358                 hlist_nulls_for_each_entry(h, n, &pcpu->unconfirmed, hnnode) {
2359                         struct nf_conn *ct;
2360
2361                         ct = nf_ct_tuplehash_to_ctrack(h);
2362
2363                         /* we cannot call iter() on unconfirmed list, the
2364                          * owning cpu can reallocate ct->ext at any time.
2365                          */
2366                         set_bit(IPS_DYING_BIT, &ct->status);
2367                 }
2368                 spin_unlock_bh(&pcpu->lock);
2369                 cond_resched();
2370         }
2371 }
2372
2373 void nf_ct_unconfirmed_destroy(struct net *net)
2374 {
2375         struct nf_conntrack_net *cnet = nf_ct_pernet(net);
2376
2377         might_sleep();
2378
2379         if (atomic_read(&cnet->count) > 0) {
2380                 __nf_ct_unconfirmed_destroy(net);
2381                 nf_queue_nf_hook_drop(net);
2382                 synchronize_net();
2383         }
2384 }
2385 EXPORT_SYMBOL_GPL(nf_ct_unconfirmed_destroy);
2386
2387 void nf_ct_iterate_cleanup_net(struct net *net,
2388                                int (*iter)(struct nf_conn *i, void *data),
2389                                void *data, u32 portid, int report)
2390 {
2391         struct nf_conntrack_net *cnet = nf_ct_pernet(net);
2392         struct iter_data d;
2393
2394         might_sleep();
2395
2396         if (atomic_read(&cnet->count) == 0)
2397                 return;
2398
2399         d.iter = iter;
2400         d.data = data;
2401         d.net = net;
2402
2403         nf_ct_iterate_cleanup(iter_net_only, &d, portid, report);
2404 }
2405 EXPORT_SYMBOL_GPL(nf_ct_iterate_cleanup_net);
2406
2407 /**
2408  * nf_ct_iterate_destroy - destroy unconfirmed conntracks and iterate table
2409  * @iter: callback to invoke for each conntrack
2410  * @data: data to pass to @iter
2411  *
2412  * Like nf_ct_iterate_cleanup, but first marks conntracks on the
2413  * unconfirmed list as dying (so they will not be inserted into
2414  * main table).
2415  *
2416  * Can only be called in module exit path.
2417  */
2418 void
2419 nf_ct_iterate_destroy(int (*iter)(struct nf_conn *i, void *data), void *data)
2420 {
2421         struct net *net;
2422
2423         down_read(&net_rwsem);
2424         for_each_net(net) {
2425                 struct nf_conntrack_net *cnet = nf_ct_pernet(net);
2426
2427                 if (atomic_read(&cnet->count) == 0)
2428                         continue;
2429                 __nf_ct_unconfirmed_destroy(net);
2430                 nf_queue_nf_hook_drop(net);
2431         }
2432         up_read(&net_rwsem);
2433
2434         /* Need to wait for netns cleanup worker to finish, if its
2435          * running -- it might have deleted a net namespace from
2436          * the global list, so our __nf_ct_unconfirmed_destroy() might
2437          * not have affected all namespaces.
2438          */
2439         net_ns_barrier();
2440
2441         /* a conntrack could have been unlinked from unconfirmed list
2442          * before we grabbed pcpu lock in __nf_ct_unconfirmed_destroy().
2443          * This makes sure its inserted into conntrack table.
2444          */
2445         synchronize_net();
2446
2447         nf_ct_iterate_cleanup(iter, data, 0, 0);
2448 }
2449 EXPORT_SYMBOL_GPL(nf_ct_iterate_destroy);
2450
2451 static int kill_all(struct nf_conn *i, void *data)
2452 {
2453         return net_eq(nf_ct_net(i), data);
2454 }
2455
2456 void nf_conntrack_cleanup_start(void)
2457 {
2458         conntrack_gc_work.exiting = true;
2459 }
2460
2461 void nf_conntrack_cleanup_end(void)
2462 {
2463         RCU_INIT_POINTER(nf_ct_hook, NULL);
2464         cancel_delayed_work_sync(&conntrack_gc_work.dwork);
2465         kvfree(nf_conntrack_hash);
2466
2467         nf_conntrack_proto_fini();
2468         nf_conntrack_seqadj_fini();
2469         nf_conntrack_labels_fini();
2470         nf_conntrack_helper_fini();
2471         nf_conntrack_timeout_fini();
2472         nf_conntrack_ecache_fini();
2473         nf_conntrack_tstamp_fini();
2474         nf_conntrack_acct_fini();
2475         nf_conntrack_expect_fini();
2476
2477         kmem_cache_destroy(nf_conntrack_cachep);
2478 }
2479
2480 /*
2481  * Mishearing the voices in his head, our hero wonders how he's
2482  * supposed to kill the mall.
2483  */
2484 void nf_conntrack_cleanup_net(struct net *net)
2485 {
2486         LIST_HEAD(single);
2487
2488         list_add(&net->exit_list, &single);
2489         nf_conntrack_cleanup_net_list(&single);
2490 }
2491
2492 void nf_conntrack_cleanup_net_list(struct list_head *net_exit_list)
2493 {
2494         int busy;
2495         struct net *net;
2496
2497         /*
2498          * This makes sure all current packets have passed through
2499          *  netfilter framework.  Roll on, two-stage module
2500          *  delete...
2501          */
2502         synchronize_net();
2503 i_see_dead_people:
2504         busy = 0;
2505         list_for_each_entry(net, net_exit_list, exit_list) {
2506                 struct nf_conntrack_net *cnet = nf_ct_pernet(net);
2507
2508                 nf_ct_iterate_cleanup(kill_all, net, 0, 0);
2509                 if (atomic_read(&cnet->count) != 0)
2510                         busy = 1;
2511         }
2512         if (busy) {
2513                 schedule();
2514                 goto i_see_dead_people;
2515         }
2516
2517         list_for_each_entry(net, net_exit_list, exit_list) {
2518                 nf_conntrack_ecache_pernet_fini(net);
2519                 nf_conntrack_expect_pernet_fini(net);
2520                 free_percpu(net->ct.stat);
2521                 free_percpu(net->ct.pcpu_lists);
2522         }
2523 }
2524
2525 void *nf_ct_alloc_hashtable(unsigned int *sizep, int nulls)
2526 {
2527         struct hlist_nulls_head *hash;
2528         unsigned int nr_slots, i;
2529
2530         if (*sizep > (UINT_MAX / sizeof(struct hlist_nulls_head)))
2531                 return NULL;
2532
2533         BUILD_BUG_ON(sizeof(struct hlist_nulls_head) != sizeof(struct hlist_head));
2534         nr_slots = *sizep = roundup(*sizep, PAGE_SIZE / sizeof(struct hlist_nulls_head));
2535
2536         hash = kvcalloc(nr_slots, sizeof(struct hlist_nulls_head), GFP_KERNEL);
2537
2538         if (hash && nulls)
2539                 for (i = 0; i < nr_slots; i++)
2540                         INIT_HLIST_NULLS_HEAD(&hash[i], i);
2541
2542         return hash;
2543 }
2544 EXPORT_SYMBOL_GPL(nf_ct_alloc_hashtable);
2545
2546 int nf_conntrack_hash_resize(unsigned int hashsize)
2547 {
2548         int i, bucket;
2549         unsigned int old_size;
2550         struct hlist_nulls_head *hash, *old_hash;
2551         struct nf_conntrack_tuple_hash *h;
2552         struct nf_conn *ct;
2553
2554         if (!hashsize)
2555                 return -EINVAL;
2556
2557         hash = nf_ct_alloc_hashtable(&hashsize, 1);
2558         if (!hash)
2559                 return -ENOMEM;
2560
2561         mutex_lock(&nf_conntrack_mutex);
2562         old_size = nf_conntrack_htable_size;
2563         if (old_size == hashsize) {
2564                 mutex_unlock(&nf_conntrack_mutex);
2565                 kvfree(hash);
2566                 return 0;
2567         }
2568
2569         local_bh_disable();
2570         nf_conntrack_all_lock();
2571         write_seqcount_begin(&nf_conntrack_generation);
2572
2573         /* Lookups in the old hash might happen in parallel, which means we
2574          * might get false negatives during connection lookup. New connections
2575          * created because of a false negative won't make it into the hash
2576          * though since that required taking the locks.
2577          */
2578
2579         for (i = 0; i < nf_conntrack_htable_size; i++) {
2580                 while (!hlist_nulls_empty(&nf_conntrack_hash[i])) {
2581                         unsigned int zone_id;
2582
2583                         h = hlist_nulls_entry(nf_conntrack_hash[i].first,
2584                                               struct nf_conntrack_tuple_hash, hnnode);
2585                         ct = nf_ct_tuplehash_to_ctrack(h);
2586                         hlist_nulls_del_rcu(&h->hnnode);
2587
2588                         zone_id = nf_ct_zone_id(nf_ct_zone(ct), NF_CT_DIRECTION(h));
2589                         bucket = __hash_conntrack(nf_ct_net(ct),
2590                                                   &h->tuple, zone_id, hashsize);
2591                         hlist_nulls_add_head_rcu(&h->hnnode, &hash[bucket]);
2592                 }
2593         }
2594         old_hash = nf_conntrack_hash;
2595
2596         nf_conntrack_hash = hash;
2597         nf_conntrack_htable_size = hashsize;
2598
2599         write_seqcount_end(&nf_conntrack_generation);
2600         nf_conntrack_all_unlock();
2601         local_bh_enable();
2602
2603         mutex_unlock(&nf_conntrack_mutex);
2604
2605         synchronize_net();
2606         kvfree(old_hash);
2607         return 0;
2608 }
2609
2610 int nf_conntrack_set_hashsize(const char *val, const struct kernel_param *kp)
2611 {
2612         unsigned int hashsize;
2613         int rc;
2614
2615         if (current->nsproxy->net_ns != &init_net)
2616                 return -EOPNOTSUPP;
2617
2618         /* On boot, we can set this without any fancy locking. */
2619         if (!nf_conntrack_hash)
2620                 return param_set_uint(val, kp);
2621
2622         rc = kstrtouint(val, 0, &hashsize);
2623         if (rc)
2624                 return rc;
2625
2626         return nf_conntrack_hash_resize(hashsize);
2627 }
2628
2629 static __always_inline unsigned int total_extension_size(void)
2630 {
2631         /* remember to add new extensions below */
2632         BUILD_BUG_ON(NF_CT_EXT_NUM > 10);
2633
2634         return sizeof(struct nf_ct_ext) +
2635                sizeof(struct nf_conn_help)
2636 #if IS_ENABLED(CONFIG_NF_NAT)
2637                 + sizeof(struct nf_conn_nat)
2638 #endif
2639                 + sizeof(struct nf_conn_seqadj)
2640                 + sizeof(struct nf_conn_acct)
2641 #ifdef CONFIG_NF_CONNTRACK_EVENTS
2642                 + sizeof(struct nf_conntrack_ecache)
2643 #endif
2644 #ifdef CONFIG_NF_CONNTRACK_TIMESTAMP
2645                 + sizeof(struct nf_conn_tstamp)
2646 #endif
2647 #ifdef CONFIG_NF_CONNTRACK_TIMEOUT
2648                 + sizeof(struct nf_conn_timeout)
2649 #endif
2650 #ifdef CONFIG_NF_CONNTRACK_LABELS
2651                 + sizeof(struct nf_conn_labels)
2652 #endif
2653 #if IS_ENABLED(CONFIG_NETFILTER_SYNPROXY)
2654                 + sizeof(struct nf_conn_synproxy)
2655 #endif
2656 #if IS_ENABLED(CONFIG_NET_ACT_CT)
2657                 + sizeof(struct nf_conn_act_ct_ext)
2658 #endif
2659         ;
2660 };
2661
2662 int nf_conntrack_init_start(void)
2663 {
2664         unsigned long nr_pages = totalram_pages();
2665         int max_factor = 8;
2666         int ret = -ENOMEM;
2667         int i;
2668
2669         /* struct nf_ct_ext uses u8 to store offsets/size */
2670         BUILD_BUG_ON(total_extension_size() > 255u);
2671
2672         seqcount_spinlock_init(&nf_conntrack_generation,
2673                                &nf_conntrack_locks_all_lock);
2674
2675         for (i = 0; i < CONNTRACK_LOCKS; i++)
2676                 spin_lock_init(&nf_conntrack_locks[i]);
2677
2678         if (!nf_conntrack_htable_size) {
2679                 nf_conntrack_htable_size
2680                         = (((nr_pages << PAGE_SHIFT) / 16384)
2681                            / sizeof(struct hlist_head));
2682                 if (BITS_PER_LONG >= 64 &&
2683                     nr_pages > (4 * (1024 * 1024 * 1024 / PAGE_SIZE)))
2684                         nf_conntrack_htable_size = 262144;
2685                 else if (nr_pages > (1024 * 1024 * 1024 / PAGE_SIZE))
2686                         nf_conntrack_htable_size = 65536;
2687
2688                 if (nf_conntrack_htable_size < 1024)
2689                         nf_conntrack_htable_size = 1024;
2690                 /* Use a max. factor of one by default to keep the average
2691                  * hash chain length at 2 entries.  Each entry has to be added
2692                  * twice (once for original direction, once for reply).
2693                  * When a table size is given we use the old value of 8 to
2694                  * avoid implicit reduction of the max entries setting.
2695                  */
2696                 max_factor = 1;
2697         }
2698
2699         nf_conntrack_hash = nf_ct_alloc_hashtable(&nf_conntrack_htable_size, 1);
2700         if (!nf_conntrack_hash)
2701                 return -ENOMEM;
2702
2703         nf_conntrack_max = max_factor * nf_conntrack_htable_size;
2704
2705         nf_conntrack_cachep = kmem_cache_create("nf_conntrack",
2706                                                 sizeof(struct nf_conn),
2707                                                 NFCT_INFOMASK + 1,
2708                                                 SLAB_TYPESAFE_BY_RCU | SLAB_HWCACHE_ALIGN, NULL);
2709         if (!nf_conntrack_cachep)
2710                 goto err_cachep;
2711
2712         ret = nf_conntrack_expect_init();
2713         if (ret < 0)
2714                 goto err_expect;
2715
2716         ret = nf_conntrack_acct_init();
2717         if (ret < 0)
2718                 goto err_acct;
2719
2720         ret = nf_conntrack_tstamp_init();
2721         if (ret < 0)
2722                 goto err_tstamp;
2723
2724         ret = nf_conntrack_ecache_init();
2725         if (ret < 0)
2726                 goto err_ecache;
2727
2728         ret = nf_conntrack_timeout_init();
2729         if (ret < 0)
2730                 goto err_timeout;
2731
2732         ret = nf_conntrack_helper_init();
2733         if (ret < 0)
2734                 goto err_helper;
2735
2736         ret = nf_conntrack_labels_init();
2737         if (ret < 0)
2738                 goto err_labels;
2739
2740         ret = nf_conntrack_seqadj_init();
2741         if (ret < 0)
2742                 goto err_seqadj;
2743
2744         ret = nf_conntrack_proto_init();
2745         if (ret < 0)
2746                 goto err_proto;
2747
2748         conntrack_gc_work_init(&conntrack_gc_work);
2749         queue_delayed_work(system_power_efficient_wq, &conntrack_gc_work.dwork, HZ);
2750
2751         return 0;
2752
2753 err_proto:
2754         nf_conntrack_seqadj_fini();
2755 err_seqadj:
2756         nf_conntrack_labels_fini();
2757 err_labels:
2758         nf_conntrack_helper_fini();
2759 err_helper:
2760         nf_conntrack_timeout_fini();
2761 err_timeout:
2762         nf_conntrack_ecache_fini();
2763 err_ecache:
2764         nf_conntrack_tstamp_fini();
2765 err_tstamp:
2766         nf_conntrack_acct_fini();
2767 err_acct:
2768         nf_conntrack_expect_fini();
2769 err_expect:
2770         kmem_cache_destroy(nf_conntrack_cachep);
2771 err_cachep:
2772         kvfree(nf_conntrack_hash);
2773         return ret;
2774 }
2775
2776 static const struct nf_ct_hook nf_conntrack_hook = {
2777         .update         = nf_conntrack_update,
2778         .destroy        = nf_ct_destroy,
2779         .get_tuple_skb  = nf_conntrack_get_tuple_skb,
2780         .attach         = nf_conntrack_attach,
2781 };
2782
2783 void nf_conntrack_init_end(void)
2784 {
2785         RCU_INIT_POINTER(nf_ct_hook, &nf_conntrack_hook);
2786 }
2787
2788 /*
2789  * We need to use special "null" values, not used in hash table
2790  */
2791 #define UNCONFIRMED_NULLS_VAL   ((1<<30)+0)
2792 #define DYING_NULLS_VAL         ((1<<30)+1)
2793
2794 int nf_conntrack_init_net(struct net *net)
2795 {
2796         struct nf_conntrack_net *cnet = nf_ct_pernet(net);
2797         int ret = -ENOMEM;
2798         int cpu;
2799
2800         BUILD_BUG_ON(IP_CT_UNTRACKED == IP_CT_NUMBER);
2801         BUILD_BUG_ON_NOT_POWER_OF_2(CONNTRACK_LOCKS);
2802         atomic_set(&cnet->count, 0);
2803
2804         net->ct.pcpu_lists = alloc_percpu(struct ct_pcpu);
2805         if (!net->ct.pcpu_lists)
2806                 goto err_stat;
2807
2808         for_each_possible_cpu(cpu) {
2809                 struct ct_pcpu *pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
2810
2811                 spin_lock_init(&pcpu->lock);
2812                 INIT_HLIST_NULLS_HEAD(&pcpu->unconfirmed, UNCONFIRMED_NULLS_VAL);
2813                 INIT_HLIST_NULLS_HEAD(&pcpu->dying, DYING_NULLS_VAL);
2814         }
2815
2816         net->ct.stat = alloc_percpu(struct ip_conntrack_stat);
2817         if (!net->ct.stat)
2818                 goto err_pcpu_lists;
2819
2820         ret = nf_conntrack_expect_pernet_init(net);
2821         if (ret < 0)
2822                 goto err_expect;
2823
2824         nf_conntrack_acct_pernet_init(net);
2825         nf_conntrack_tstamp_pernet_init(net);
2826         nf_conntrack_ecache_pernet_init(net);
2827         nf_conntrack_helper_pernet_init(net);
2828         nf_conntrack_proto_pernet_init(net);
2829
2830         return 0;
2831
2832 err_expect:
2833         free_percpu(net->ct.stat);
2834 err_pcpu_lists:
2835         free_percpu(net->ct.pcpu_lists);
2836 err_stat:
2837         return ret;
2838 }