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