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