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