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