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