1 /* Connection state tracking for netfilter. This is separated from,
2 but required by, the NAT layer; it can also be used by an iptables
5 /* (C) 1999-2001 Paul `Rusty' Russell
6 * (C) 2002-2006 Netfilter Core Team <coreteam@netfilter.org>
7 * (C) 2003,2004 USAGI/WIDE Project <http://www.linux-ipv6.org>
8 * (C) 2005-2012 Patrick McHardy <kaber@trash.net>
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License version 2 as
12 * published by the Free Software Foundation.
15 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
17 #include <linux/types.h>
18 #include <linux/netfilter.h>
19 #include <linux/module.h>
20 #include <linux/sched.h>
21 #include <linux/skbuff.h>
22 #include <linux/proc_fs.h>
23 #include <linux/vmalloc.h>
24 #include <linux/stddef.h>
25 #include <linux/slab.h>
26 #include <linux/random.h>
27 #include <linux/jhash.h>
28 #include <linux/err.h>
29 #include <linux/percpu.h>
30 #include <linux/moduleparam.h>
31 #include <linux/notifier.h>
32 #include <linux/kernel.h>
33 #include <linux/netdevice.h>
34 #include <linux/socket.h>
36 #include <linux/nsproxy.h>
37 #include <linux/rculist_nulls.h>
39 #include <net/netfilter/nf_conntrack.h>
40 #include <net/netfilter/nf_conntrack_l4proto.h>
41 #include <net/netfilter/nf_conntrack_expect.h>
42 #include <net/netfilter/nf_conntrack_helper.h>
43 #include <net/netfilter/nf_conntrack_seqadj.h>
44 #include <net/netfilter/nf_conntrack_core.h>
45 #include <net/netfilter/nf_conntrack_extend.h>
46 #include <net/netfilter/nf_conntrack_acct.h>
47 #include <net/netfilter/nf_conntrack_ecache.h>
48 #include <net/netfilter/nf_conntrack_zones.h>
49 #include <net/netfilter/nf_conntrack_timestamp.h>
50 #include <net/netfilter/nf_conntrack_timeout.h>
51 #include <net/netfilter/nf_conntrack_labels.h>
52 #include <net/netfilter/nf_conntrack_synproxy.h>
53 #include <net/netfilter/nf_nat.h>
54 #include <net/netfilter/nf_nat_helper.h>
55 #include <net/netns/hash.h>
58 #include "nf_internals.h"
60 __cacheline_aligned_in_smp spinlock_t nf_conntrack_locks[CONNTRACK_LOCKS];
61 EXPORT_SYMBOL_GPL(nf_conntrack_locks);
63 __cacheline_aligned_in_smp DEFINE_SPINLOCK(nf_conntrack_expect_lock);
64 EXPORT_SYMBOL_GPL(nf_conntrack_expect_lock);
66 struct hlist_nulls_head *nf_conntrack_hash __read_mostly;
67 EXPORT_SYMBOL_GPL(nf_conntrack_hash);
69 struct conntrack_gc_work {
70 struct delayed_work dwork;
77 static __read_mostly struct kmem_cache *nf_conntrack_cachep;
78 static __read_mostly spinlock_t nf_conntrack_locks_all_lock;
79 static __read_mostly DEFINE_SPINLOCK(nf_conntrack_locks_all_lock);
80 static __read_mostly bool nf_conntrack_locks_all;
82 /* every gc cycle scans at most 1/GC_MAX_BUCKETS_DIV part of table */
83 #define GC_MAX_BUCKETS_DIV 128u
84 /* upper bound of full table scan */
85 #define GC_MAX_SCAN_JIFFIES (16u * HZ)
86 /* desired ratio of entries found to be expired */
87 #define GC_EVICT_RATIO 50u
89 static struct conntrack_gc_work conntrack_gc_work;
91 void nf_conntrack_lock(spinlock_t *lock) __acquires(lock)
93 /* 1) Acquire the lock */
96 /* 2) read nf_conntrack_locks_all, with ACQUIRE semantics
97 * It pairs with the smp_store_release() in nf_conntrack_all_unlock()
99 if (likely(smp_load_acquire(&nf_conntrack_locks_all) == false))
102 /* fast path failed, unlock */
105 /* Slow path 1) get global lock */
106 spin_lock(&nf_conntrack_locks_all_lock);
108 /* Slow path 2) get the lock we want */
111 /* Slow path 3) release the global lock */
112 spin_unlock(&nf_conntrack_locks_all_lock);
114 EXPORT_SYMBOL_GPL(nf_conntrack_lock);
116 static void nf_conntrack_double_unlock(unsigned int h1, unsigned int h2)
118 h1 %= CONNTRACK_LOCKS;
119 h2 %= CONNTRACK_LOCKS;
120 spin_unlock(&nf_conntrack_locks[h1]);
122 spin_unlock(&nf_conntrack_locks[h2]);
125 /* return true if we need to recompute hashes (in case hash table was resized) */
126 static bool nf_conntrack_double_lock(struct net *net, unsigned int h1,
127 unsigned int h2, unsigned int sequence)
129 h1 %= CONNTRACK_LOCKS;
130 h2 %= CONNTRACK_LOCKS;
132 nf_conntrack_lock(&nf_conntrack_locks[h1]);
134 spin_lock_nested(&nf_conntrack_locks[h2],
135 SINGLE_DEPTH_NESTING);
137 nf_conntrack_lock(&nf_conntrack_locks[h2]);
138 spin_lock_nested(&nf_conntrack_locks[h1],
139 SINGLE_DEPTH_NESTING);
141 if (read_seqcount_retry(&nf_conntrack_generation, sequence)) {
142 nf_conntrack_double_unlock(h1, h2);
148 static void nf_conntrack_all_lock(void)
152 spin_lock(&nf_conntrack_locks_all_lock);
154 nf_conntrack_locks_all = true;
156 for (i = 0; i < CONNTRACK_LOCKS; i++) {
157 spin_lock(&nf_conntrack_locks[i]);
159 /* This spin_unlock provides the "release" to ensure that
160 * nf_conntrack_locks_all==true is visible to everyone that
161 * acquired spin_lock(&nf_conntrack_locks[]).
163 spin_unlock(&nf_conntrack_locks[i]);
167 static void nf_conntrack_all_unlock(void)
169 /* All prior stores must be complete before we clear
170 * 'nf_conntrack_locks_all'. Otherwise nf_conntrack_lock()
171 * might observe the false value but not the entire
173 * It pairs with the smp_load_acquire() in nf_conntrack_lock()
175 smp_store_release(&nf_conntrack_locks_all, false);
176 spin_unlock(&nf_conntrack_locks_all_lock);
179 unsigned int nf_conntrack_htable_size __read_mostly;
180 EXPORT_SYMBOL_GPL(nf_conntrack_htable_size);
182 unsigned int nf_conntrack_max __read_mostly;
183 EXPORT_SYMBOL_GPL(nf_conntrack_max);
184 seqcount_t nf_conntrack_generation __read_mostly;
185 static unsigned int nf_conntrack_hash_rnd __read_mostly;
187 static u32 hash_conntrack_raw(const struct nf_conntrack_tuple *tuple,
188 const struct net *net)
193 get_random_once(&nf_conntrack_hash_rnd, sizeof(nf_conntrack_hash_rnd));
195 /* The direction must be ignored, so we hash everything up to the
196 * destination ports (which is a multiple of 4) and treat the last
197 * three bytes manually.
199 seed = nf_conntrack_hash_rnd ^ net_hash_mix(net);
200 n = (sizeof(tuple->src) + sizeof(tuple->dst.u3)) / sizeof(u32);
201 return jhash2((u32 *)tuple, n, seed ^
202 (((__force __u16)tuple->dst.u.all << 16) |
203 tuple->dst.protonum));
206 static u32 scale_hash(u32 hash)
208 return reciprocal_scale(hash, nf_conntrack_htable_size);
211 static u32 __hash_conntrack(const struct net *net,
212 const struct nf_conntrack_tuple *tuple,
215 return reciprocal_scale(hash_conntrack_raw(tuple, net), size);
218 static u32 hash_conntrack(const struct net *net,
219 const struct nf_conntrack_tuple *tuple)
221 return scale_hash(hash_conntrack_raw(tuple, net));
224 static bool nf_ct_get_tuple_ports(const struct sk_buff *skb,
225 unsigned int dataoff,
226 struct nf_conntrack_tuple *tuple)
230 } _inet_hdr, *inet_hdr;
232 /* Actually only need first 4 bytes to get ports. */
233 inet_hdr = skb_header_pointer(skb, dataoff, sizeof(_inet_hdr), &_inet_hdr);
237 tuple->src.u.udp.port = inet_hdr->sport;
238 tuple->dst.u.udp.port = inet_hdr->dport;
243 nf_ct_get_tuple(const struct sk_buff *skb,
245 unsigned int dataoff,
249 struct nf_conntrack_tuple *tuple)
255 memset(tuple, 0, sizeof(*tuple));
257 tuple->src.l3num = l3num;
260 nhoff += offsetof(struct iphdr, saddr);
261 size = 2 * sizeof(__be32);
264 nhoff += offsetof(struct ipv6hdr, saddr);
265 size = sizeof(_addrs);
271 ap = skb_header_pointer(skb, nhoff, size, _addrs);
277 tuple->src.u3.ip = ap[0];
278 tuple->dst.u3.ip = ap[1];
281 memcpy(tuple->src.u3.ip6, ap, sizeof(tuple->src.u3.ip6));
282 memcpy(tuple->dst.u3.ip6, ap + 4, sizeof(tuple->dst.u3.ip6));
286 tuple->dst.protonum = protonum;
287 tuple->dst.dir = IP_CT_DIR_ORIGINAL;
290 #if IS_ENABLED(CONFIG_IPV6)
292 return icmpv6_pkt_to_tuple(skb, dataoff, net, tuple);
295 return icmp_pkt_to_tuple(skb, dataoff, net, tuple);
296 #ifdef CONFIG_NF_CT_PROTO_GRE
298 return gre_pkt_to_tuple(skb, dataoff, net, tuple);
301 case IPPROTO_UDP: /* fallthrough */
302 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
303 #ifdef CONFIG_NF_CT_PROTO_UDPLITE
304 case IPPROTO_UDPLITE:
305 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
307 #ifdef CONFIG_NF_CT_PROTO_SCTP
309 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
311 #ifdef CONFIG_NF_CT_PROTO_DCCP
313 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
322 static int ipv4_get_l4proto(const struct sk_buff *skb, unsigned int nhoff,
326 const struct iphdr *iph;
329 iph = skb_header_pointer(skb, nhoff, sizeof(_iph), &_iph);
333 /* Conntrack defragments packets, we might still see fragments
334 * inside ICMP packets though.
336 if (iph->frag_off & htons(IP_OFFSET))
339 dataoff = nhoff + (iph->ihl << 2);
340 *protonum = iph->protocol;
342 /* Check bogus IP headers */
343 if (dataoff > skb->len) {
344 pr_debug("bogus IPv4 packet: nhoff %u, ihl %u, skblen %u\n",
345 nhoff, iph->ihl << 2, skb->len);
351 #if IS_ENABLED(CONFIG_IPV6)
352 static int ipv6_get_l4proto(const struct sk_buff *skb, unsigned int nhoff,
356 unsigned int extoff = nhoff + sizeof(struct ipv6hdr);
360 if (skb_copy_bits(skb, nhoff + offsetof(struct ipv6hdr, nexthdr),
361 &nexthdr, sizeof(nexthdr)) != 0) {
362 pr_debug("can't get nexthdr\n");
365 protoff = ipv6_skip_exthdr(skb, extoff, &nexthdr, &frag_off);
367 * (protoff == skb->len) means the packet has not data, just
368 * IPv6 and possibly extensions headers, but it is tracked anyway
370 if (protoff < 0 || (frag_off & htons(~0x7)) != 0) {
371 pr_debug("can't find proto in pkt\n");
380 static int get_l4proto(const struct sk_buff *skb,
381 unsigned int nhoff, u8 pf, u8 *l4num)
385 return ipv4_get_l4proto(skb, nhoff, l4num);
386 #if IS_ENABLED(CONFIG_IPV6)
388 return ipv6_get_l4proto(skb, nhoff, l4num);
397 bool nf_ct_get_tuplepr(const struct sk_buff *skb, unsigned int nhoff,
399 struct net *net, struct nf_conntrack_tuple *tuple)
404 protoff = get_l4proto(skb, nhoff, l3num, &protonum);
408 return nf_ct_get_tuple(skb, nhoff, protoff, l3num, protonum, net, tuple);
410 EXPORT_SYMBOL_GPL(nf_ct_get_tuplepr);
413 nf_ct_invert_tuple(struct nf_conntrack_tuple *inverse,
414 const struct nf_conntrack_tuple *orig)
416 memset(inverse, 0, sizeof(*inverse));
418 inverse->src.l3num = orig->src.l3num;
420 switch (orig->src.l3num) {
422 inverse->src.u3.ip = orig->dst.u3.ip;
423 inverse->dst.u3.ip = orig->src.u3.ip;
426 inverse->src.u3.in6 = orig->dst.u3.in6;
427 inverse->dst.u3.in6 = orig->src.u3.in6;
433 inverse->dst.dir = !orig->dst.dir;
435 inverse->dst.protonum = orig->dst.protonum;
437 switch (orig->dst.protonum) {
439 return nf_conntrack_invert_icmp_tuple(inverse, orig);
440 #if IS_ENABLED(CONFIG_IPV6)
442 return nf_conntrack_invert_icmpv6_tuple(inverse, orig);
446 inverse->src.u.all = orig->dst.u.all;
447 inverse->dst.u.all = orig->src.u.all;
450 EXPORT_SYMBOL_GPL(nf_ct_invert_tuple);
453 clean_from_lists(struct nf_conn *ct)
455 pr_debug("clean_from_lists(%p)\n", ct);
456 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
457 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode);
459 /* Destroy all pending expectations */
460 nf_ct_remove_expectations(ct);
463 /* must be called with local_bh_disable */
464 static void nf_ct_add_to_dying_list(struct nf_conn *ct)
466 struct ct_pcpu *pcpu;
468 /* add this conntrack to the (per cpu) dying list */
469 ct->cpu = smp_processor_id();
470 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
472 spin_lock(&pcpu->lock);
473 hlist_nulls_add_head(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
475 spin_unlock(&pcpu->lock);
478 /* must be called with local_bh_disable */
479 static void nf_ct_add_to_unconfirmed_list(struct nf_conn *ct)
481 struct ct_pcpu *pcpu;
483 /* add this conntrack to the (per cpu) unconfirmed list */
484 ct->cpu = smp_processor_id();
485 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
487 spin_lock(&pcpu->lock);
488 hlist_nulls_add_head(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
490 spin_unlock(&pcpu->lock);
493 /* must be called with local_bh_disable */
494 static void nf_ct_del_from_dying_or_unconfirmed_list(struct nf_conn *ct)
496 struct ct_pcpu *pcpu;
498 /* We overload first tuple to link into unconfirmed or dying list.*/
499 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
501 spin_lock(&pcpu->lock);
502 BUG_ON(hlist_nulls_unhashed(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode));
503 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
504 spin_unlock(&pcpu->lock);
507 #define NFCT_ALIGN(len) (((len) + NFCT_INFOMASK) & ~NFCT_INFOMASK)
509 /* Released via destroy_conntrack() */
510 struct nf_conn *nf_ct_tmpl_alloc(struct net *net,
511 const struct nf_conntrack_zone *zone,
514 struct nf_conn *tmpl, *p;
516 if (ARCH_KMALLOC_MINALIGN <= NFCT_INFOMASK) {
517 tmpl = kzalloc(sizeof(*tmpl) + NFCT_INFOMASK, flags);
522 tmpl = (struct nf_conn *)NFCT_ALIGN((unsigned long)p);
524 tmpl = (struct nf_conn *)NFCT_ALIGN((unsigned long)p);
525 tmpl->proto.tmpl_padto = (char *)tmpl - (char *)p;
528 tmpl = kzalloc(sizeof(*tmpl), flags);
533 tmpl->status = IPS_TEMPLATE;
534 write_pnet(&tmpl->ct_net, net);
535 nf_ct_zone_add(tmpl, zone);
536 atomic_set(&tmpl->ct_general.use, 0);
540 EXPORT_SYMBOL_GPL(nf_ct_tmpl_alloc);
542 void nf_ct_tmpl_free(struct nf_conn *tmpl)
544 nf_ct_ext_destroy(tmpl);
545 nf_ct_ext_free(tmpl);
547 if (ARCH_KMALLOC_MINALIGN <= NFCT_INFOMASK)
548 kfree((char *)tmpl - tmpl->proto.tmpl_padto);
552 EXPORT_SYMBOL_GPL(nf_ct_tmpl_free);
554 static void destroy_gre_conntrack(struct nf_conn *ct)
556 #ifdef CONFIG_NF_CT_PROTO_GRE
557 struct nf_conn *master = ct->master;
560 nf_ct_gre_keymap_destroy(master);
565 destroy_conntrack(struct nf_conntrack *nfct)
567 struct nf_conn *ct = (struct nf_conn *)nfct;
569 pr_debug("destroy_conntrack(%p)\n", ct);
570 WARN_ON(atomic_read(&nfct->use) != 0);
572 if (unlikely(nf_ct_is_template(ct))) {
577 if (unlikely(nf_ct_protonum(ct) == IPPROTO_GRE))
578 destroy_gre_conntrack(ct);
581 /* Expectations will have been removed in clean_from_lists,
582 * except TFTP can create an expectation on the first packet,
583 * before connection is in the list, so we need to clean here,
586 nf_ct_remove_expectations(ct);
588 nf_ct_del_from_dying_or_unconfirmed_list(ct);
593 nf_ct_put(ct->master);
595 pr_debug("destroy_conntrack: returning ct=%p to slab\n", ct);
596 nf_conntrack_free(ct);
599 static void nf_ct_delete_from_lists(struct nf_conn *ct)
601 struct net *net = nf_ct_net(ct);
602 unsigned int hash, reply_hash;
603 unsigned int sequence;
605 nf_ct_helper_destroy(ct);
609 sequence = read_seqcount_begin(&nf_conntrack_generation);
610 hash = hash_conntrack(net,
611 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
612 reply_hash = hash_conntrack(net,
613 &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
614 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
616 clean_from_lists(ct);
617 nf_conntrack_double_unlock(hash, reply_hash);
619 nf_ct_add_to_dying_list(ct);
624 bool nf_ct_delete(struct nf_conn *ct, u32 portid, int report)
626 struct nf_conn_tstamp *tstamp;
628 if (test_and_set_bit(IPS_DYING_BIT, &ct->status))
631 tstamp = nf_conn_tstamp_find(ct);
632 if (tstamp && tstamp->stop == 0)
633 tstamp->stop = ktime_get_real_ns();
635 if (nf_conntrack_event_report(IPCT_DESTROY, ct,
636 portid, report) < 0) {
637 /* destroy event was not delivered. nf_ct_put will
638 * be done by event cache worker on redelivery.
640 nf_ct_delete_from_lists(ct);
641 nf_conntrack_ecache_delayed_work(nf_ct_net(ct));
645 nf_conntrack_ecache_work(nf_ct_net(ct));
646 nf_ct_delete_from_lists(ct);
650 EXPORT_SYMBOL_GPL(nf_ct_delete);
653 nf_ct_key_equal(struct nf_conntrack_tuple_hash *h,
654 const struct nf_conntrack_tuple *tuple,
655 const struct nf_conntrack_zone *zone,
656 const struct net *net)
658 struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
660 /* A conntrack can be recreated with the equal tuple,
661 * so we need to check that the conntrack is confirmed
663 return nf_ct_tuple_equal(tuple, &h->tuple) &&
664 nf_ct_zone_equal(ct, zone, NF_CT_DIRECTION(h)) &&
665 nf_ct_is_confirmed(ct) &&
666 net_eq(net, nf_ct_net(ct));
670 nf_ct_match(const struct nf_conn *ct1, const struct nf_conn *ct2)
672 return nf_ct_tuple_equal(&ct1->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
673 &ct2->tuplehash[IP_CT_DIR_ORIGINAL].tuple) &&
674 nf_ct_tuple_equal(&ct1->tuplehash[IP_CT_DIR_REPLY].tuple,
675 &ct2->tuplehash[IP_CT_DIR_REPLY].tuple) &&
676 nf_ct_zone_equal(ct1, nf_ct_zone(ct2), IP_CT_DIR_ORIGINAL) &&
677 nf_ct_zone_equal(ct1, nf_ct_zone(ct2), IP_CT_DIR_REPLY) &&
678 net_eq(nf_ct_net(ct1), nf_ct_net(ct2));
681 /* caller must hold rcu readlock and none of the nf_conntrack_locks */
682 static void nf_ct_gc_expired(struct nf_conn *ct)
684 if (!atomic_inc_not_zero(&ct->ct_general.use))
687 if (nf_ct_should_gc(ct))
695 * - Caller must take a reference on returned object
696 * and recheck nf_ct_tuple_equal(tuple, &h->tuple)
698 static struct nf_conntrack_tuple_hash *
699 ____nf_conntrack_find(struct net *net, const struct nf_conntrack_zone *zone,
700 const struct nf_conntrack_tuple *tuple, u32 hash)
702 struct nf_conntrack_tuple_hash *h;
703 struct hlist_nulls_head *ct_hash;
704 struct hlist_nulls_node *n;
705 unsigned int bucket, hsize;
708 nf_conntrack_get_ht(&ct_hash, &hsize);
709 bucket = reciprocal_scale(hash, hsize);
711 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[bucket], hnnode) {
714 ct = nf_ct_tuplehash_to_ctrack(h);
715 if (nf_ct_is_expired(ct)) {
716 nf_ct_gc_expired(ct);
720 if (nf_ct_is_dying(ct))
723 if (nf_ct_key_equal(h, tuple, zone, net))
727 * if the nulls value we got at the end of this lookup is
728 * not the expected one, we must restart lookup.
729 * We probably met an item that was moved to another chain.
731 if (get_nulls_value(n) != bucket) {
732 NF_CT_STAT_INC_ATOMIC(net, search_restart);
739 /* Find a connection corresponding to a tuple. */
740 static struct nf_conntrack_tuple_hash *
741 __nf_conntrack_find_get(struct net *net, const struct nf_conntrack_zone *zone,
742 const struct nf_conntrack_tuple *tuple, u32 hash)
744 struct nf_conntrack_tuple_hash *h;
749 h = ____nf_conntrack_find(net, zone, tuple, hash);
751 ct = nf_ct_tuplehash_to_ctrack(h);
752 if (unlikely(nf_ct_is_dying(ct) ||
753 !atomic_inc_not_zero(&ct->ct_general.use)))
756 if (unlikely(!nf_ct_key_equal(h, tuple, zone, net))) {
767 struct nf_conntrack_tuple_hash *
768 nf_conntrack_find_get(struct net *net, const struct nf_conntrack_zone *zone,
769 const struct nf_conntrack_tuple *tuple)
771 return __nf_conntrack_find_get(net, zone, tuple,
772 hash_conntrack_raw(tuple, net));
774 EXPORT_SYMBOL_GPL(nf_conntrack_find_get);
776 static void __nf_conntrack_hash_insert(struct nf_conn *ct,
778 unsigned int reply_hash)
780 hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
781 &nf_conntrack_hash[hash]);
782 hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode,
783 &nf_conntrack_hash[reply_hash]);
787 nf_conntrack_hash_check_insert(struct nf_conn *ct)
789 const struct nf_conntrack_zone *zone;
790 struct net *net = nf_ct_net(ct);
791 unsigned int hash, reply_hash;
792 struct nf_conntrack_tuple_hash *h;
793 struct hlist_nulls_node *n;
794 unsigned int sequence;
796 zone = nf_ct_zone(ct);
800 sequence = read_seqcount_begin(&nf_conntrack_generation);
801 hash = hash_conntrack(net,
802 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
803 reply_hash = hash_conntrack(net,
804 &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
805 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
807 /* See if there's one in the list already, including reverse */
808 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode)
809 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
813 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode)
814 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
819 /* The caller holds a reference to this object */
820 atomic_set(&ct->ct_general.use, 2);
821 __nf_conntrack_hash_insert(ct, hash, reply_hash);
822 nf_conntrack_double_unlock(hash, reply_hash);
823 NF_CT_STAT_INC(net, insert);
828 nf_conntrack_double_unlock(hash, reply_hash);
829 NF_CT_STAT_INC(net, insert_failed);
833 EXPORT_SYMBOL_GPL(nf_conntrack_hash_check_insert);
835 static inline void nf_ct_acct_update(struct nf_conn *ct,
836 enum ip_conntrack_info ctinfo,
839 struct nf_conn_acct *acct;
841 acct = nf_conn_acct_find(ct);
843 struct nf_conn_counter *counter = acct->counter;
845 atomic64_inc(&counter[CTINFO2DIR(ctinfo)].packets);
846 atomic64_add(len, &counter[CTINFO2DIR(ctinfo)].bytes);
850 static void nf_ct_acct_merge(struct nf_conn *ct, enum ip_conntrack_info ctinfo,
851 const struct nf_conn *loser_ct)
853 struct nf_conn_acct *acct;
855 acct = nf_conn_acct_find(loser_ct);
857 struct nf_conn_counter *counter = acct->counter;
860 /* u32 should be fine since we must have seen one packet. */
861 bytes = atomic64_read(&counter[CTINFO2DIR(ctinfo)].bytes);
862 nf_ct_acct_update(ct, ctinfo, bytes);
866 /* Resolve race on insertion if this protocol allows this. */
867 static int nf_ct_resolve_clash(struct net *net, struct sk_buff *skb,
868 enum ip_conntrack_info ctinfo,
869 struct nf_conntrack_tuple_hash *h)
871 /* This is the conntrack entry already in hashes that won race. */
872 struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
873 const struct nf_conntrack_l4proto *l4proto;
874 enum ip_conntrack_info oldinfo;
875 struct nf_conn *loser_ct = nf_ct_get(skb, &oldinfo);
877 l4proto = nf_ct_l4proto_find(nf_ct_protonum(ct));
878 if (l4proto->allow_clash &&
879 !nf_ct_is_dying(ct) &&
880 atomic_inc_not_zero(&ct->ct_general.use)) {
881 if (((ct->status & IPS_NAT_DONE_MASK) == 0) ||
882 nf_ct_match(ct, loser_ct)) {
883 nf_ct_acct_merge(ct, ctinfo, loser_ct);
884 nf_conntrack_put(&loser_ct->ct_general);
885 nf_ct_set(skb, ct, oldinfo);
890 NF_CT_STAT_INC(net, drop);
894 /* Confirm a connection given skb; places it in hash table */
896 __nf_conntrack_confirm(struct sk_buff *skb)
898 const struct nf_conntrack_zone *zone;
899 unsigned int hash, reply_hash;
900 struct nf_conntrack_tuple_hash *h;
902 struct nf_conn_help *help;
903 struct nf_conn_tstamp *tstamp;
904 struct hlist_nulls_node *n;
905 enum ip_conntrack_info ctinfo;
907 unsigned int sequence;
910 ct = nf_ct_get(skb, &ctinfo);
913 /* ipt_REJECT uses nf_conntrack_attach to attach related
914 ICMP/TCP RST packets in other direction. Actual packet
915 which created connection will be IP_CT_NEW or for an
916 expected connection, IP_CT_RELATED. */
917 if (CTINFO2DIR(ctinfo) != IP_CT_DIR_ORIGINAL)
920 zone = nf_ct_zone(ct);
924 sequence = read_seqcount_begin(&nf_conntrack_generation);
925 /* reuse the hash saved before */
926 hash = *(unsigned long *)&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev;
927 hash = scale_hash(hash);
928 reply_hash = hash_conntrack(net,
929 &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
931 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
933 /* We're not in hash table, and we refuse to set up related
934 * connections for unconfirmed conns. But packet copies and
935 * REJECT will give spurious warnings here.
938 /* Another skb with the same unconfirmed conntrack may
939 * win the race. This may happen for bridge(br_flood)
940 * or broadcast/multicast packets do skb_clone with
941 * unconfirmed conntrack.
943 if (unlikely(nf_ct_is_confirmed(ct))) {
945 nf_conntrack_double_unlock(hash, reply_hash);
950 pr_debug("Confirming conntrack %p\n", ct);
951 /* We have to check the DYING flag after unlink to prevent
952 * a race against nf_ct_get_next_corpse() possibly called from
953 * user context, else we insert an already 'dead' hash, blocking
954 * further use of that particular connection -JM.
956 nf_ct_del_from_dying_or_unconfirmed_list(ct);
958 if (unlikely(nf_ct_is_dying(ct))) {
959 nf_ct_add_to_dying_list(ct);
963 /* See if there's one in the list already, including reverse:
964 NAT could have grabbed it without realizing, since we're
965 not in the hash. If there is, we lost race. */
966 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode)
967 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
971 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode)
972 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
976 /* Timer relative to confirmation time, not original
977 setting time, otherwise we'd get timer wrap in
978 weird delay cases. */
979 ct->timeout += nfct_time_stamp;
980 atomic_inc(&ct->ct_general.use);
981 ct->status |= IPS_CONFIRMED;
983 /* set conntrack timestamp, if enabled. */
984 tstamp = nf_conn_tstamp_find(ct);
986 if (skb->tstamp == 0)
987 __net_timestamp(skb);
989 tstamp->start = ktime_to_ns(skb->tstamp);
991 /* Since the lookup is lockless, hash insertion must be done after
992 * starting the timer and setting the CONFIRMED bit. The RCU barriers
993 * guarantee that no other CPU can find the conntrack before the above
994 * stores are visible.
996 __nf_conntrack_hash_insert(ct, hash, reply_hash);
997 nf_conntrack_double_unlock(hash, reply_hash);
1000 help = nfct_help(ct);
1001 if (help && help->helper)
1002 nf_conntrack_event_cache(IPCT_HELPER, ct);
1004 nf_conntrack_event_cache(master_ct(ct) ?
1005 IPCT_RELATED : IPCT_NEW, ct);
1009 nf_ct_add_to_dying_list(ct);
1010 ret = nf_ct_resolve_clash(net, skb, ctinfo, h);
1012 nf_conntrack_double_unlock(hash, reply_hash);
1013 NF_CT_STAT_INC(net, insert_failed);
1017 EXPORT_SYMBOL_GPL(__nf_conntrack_confirm);
1019 /* Returns true if a connection correspondings to the tuple (required
1022 nf_conntrack_tuple_taken(const struct nf_conntrack_tuple *tuple,
1023 const struct nf_conn *ignored_conntrack)
1025 struct net *net = nf_ct_net(ignored_conntrack);
1026 const struct nf_conntrack_zone *zone;
1027 struct nf_conntrack_tuple_hash *h;
1028 struct hlist_nulls_head *ct_hash;
1029 unsigned int hash, hsize;
1030 struct hlist_nulls_node *n;
1033 zone = nf_ct_zone(ignored_conntrack);
1037 nf_conntrack_get_ht(&ct_hash, &hsize);
1038 hash = __hash_conntrack(net, tuple, hsize);
1040 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[hash], hnnode) {
1041 ct = nf_ct_tuplehash_to_ctrack(h);
1043 if (ct == ignored_conntrack)
1046 if (nf_ct_is_expired(ct)) {
1047 nf_ct_gc_expired(ct);
1051 if (nf_ct_key_equal(h, tuple, zone, net)) {
1052 /* Tuple is taken already, so caller will need to find
1053 * a new source port to use.
1056 * If the *original tuples* are identical, then both
1057 * conntracks refer to the same flow.
1058 * This is a rare situation, it can occur e.g. when
1059 * more than one UDP packet is sent from same socket
1060 * in different threads.
1062 * Let nf_ct_resolve_clash() deal with this later.
1064 if (nf_ct_tuple_equal(&ignored_conntrack->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
1065 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple))
1068 NF_CT_STAT_INC_ATOMIC(net, found);
1074 if (get_nulls_value(n) != hash) {
1075 NF_CT_STAT_INC_ATOMIC(net, search_restart);
1083 EXPORT_SYMBOL_GPL(nf_conntrack_tuple_taken);
1085 #define NF_CT_EVICTION_RANGE 8
1087 /* There's a small race here where we may free a just-assured
1088 connection. Too bad: we're in trouble anyway. */
1089 static unsigned int early_drop_list(struct net *net,
1090 struct hlist_nulls_head *head)
1092 struct nf_conntrack_tuple_hash *h;
1093 struct hlist_nulls_node *n;
1094 unsigned int drops = 0;
1095 struct nf_conn *tmp;
1097 hlist_nulls_for_each_entry_rcu(h, n, head, hnnode) {
1098 tmp = nf_ct_tuplehash_to_ctrack(h);
1100 if (test_bit(IPS_OFFLOAD_BIT, &tmp->status))
1103 if (nf_ct_is_expired(tmp)) {
1104 nf_ct_gc_expired(tmp);
1108 if (test_bit(IPS_ASSURED_BIT, &tmp->status) ||
1109 !net_eq(nf_ct_net(tmp), net) ||
1110 nf_ct_is_dying(tmp))
1113 if (!atomic_inc_not_zero(&tmp->ct_general.use))
1116 /* kill only if still in same netns -- might have moved due to
1117 * SLAB_TYPESAFE_BY_RCU rules.
1119 * We steal the timer reference. If that fails timer has
1120 * already fired or someone else deleted it. Just drop ref
1121 * and move to next entry.
1123 if (net_eq(nf_ct_net(tmp), net) &&
1124 nf_ct_is_confirmed(tmp) &&
1125 nf_ct_delete(tmp, 0, 0))
1134 static noinline int early_drop(struct net *net, unsigned int hash)
1136 unsigned int i, bucket;
1138 for (i = 0; i < NF_CT_EVICTION_RANGE; i++) {
1139 struct hlist_nulls_head *ct_hash;
1140 unsigned int hsize, drops;
1143 nf_conntrack_get_ht(&ct_hash, &hsize);
1145 bucket = reciprocal_scale(hash, hsize);
1147 bucket = (bucket + 1) % hsize;
1149 drops = early_drop_list(net, &ct_hash[bucket]);
1153 NF_CT_STAT_ADD_ATOMIC(net, early_drop, drops);
1161 static bool gc_worker_skip_ct(const struct nf_conn *ct)
1163 return !nf_ct_is_confirmed(ct) || nf_ct_is_dying(ct);
1166 static bool gc_worker_can_early_drop(const struct nf_conn *ct)
1168 const struct nf_conntrack_l4proto *l4proto;
1170 if (!test_bit(IPS_ASSURED_BIT, &ct->status))
1173 l4proto = nf_ct_l4proto_find(nf_ct_protonum(ct));
1174 if (l4proto->can_early_drop && l4proto->can_early_drop(ct))
1180 #define DAY (86400 * HZ)
1182 /* Set an arbitrary timeout large enough not to ever expire, this save
1183 * us a check for the IPS_OFFLOAD_BIT from the packet path via
1184 * nf_ct_is_expired().
1186 static void nf_ct_offload_timeout(struct nf_conn *ct)
1188 if (nf_ct_expires(ct) < DAY / 2)
1189 ct->timeout = nfct_time_stamp + DAY;
1192 static void gc_worker(struct work_struct *work)
1194 unsigned int min_interval = max(HZ / GC_MAX_BUCKETS_DIV, 1u);
1195 unsigned int i, goal, buckets = 0, expired_count = 0;
1196 unsigned int nf_conntrack_max95 = 0;
1197 struct conntrack_gc_work *gc_work;
1198 unsigned int ratio, scanned = 0;
1199 unsigned long next_run;
1201 gc_work = container_of(work, struct conntrack_gc_work, dwork.work);
1203 goal = nf_conntrack_htable_size / GC_MAX_BUCKETS_DIV;
1204 i = gc_work->last_bucket;
1205 if (gc_work->early_drop)
1206 nf_conntrack_max95 = nf_conntrack_max / 100u * 95u;
1209 struct nf_conntrack_tuple_hash *h;
1210 struct hlist_nulls_head *ct_hash;
1211 struct hlist_nulls_node *n;
1212 unsigned int hashsz;
1213 struct nf_conn *tmp;
1218 nf_conntrack_get_ht(&ct_hash, &hashsz);
1222 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[i], hnnode) {
1225 tmp = nf_ct_tuplehash_to_ctrack(h);
1228 if (test_bit(IPS_OFFLOAD_BIT, &tmp->status)) {
1229 nf_ct_offload_timeout(tmp);
1233 if (nf_ct_is_expired(tmp)) {
1234 nf_ct_gc_expired(tmp);
1239 if (nf_conntrack_max95 == 0 || gc_worker_skip_ct(tmp))
1242 net = nf_ct_net(tmp);
1243 if (atomic_read(&net->ct.count) < nf_conntrack_max95)
1246 /* need to take reference to avoid possible races */
1247 if (!atomic_inc_not_zero(&tmp->ct_general.use))
1250 if (gc_worker_skip_ct(tmp)) {
1255 if (gc_worker_can_early_drop(tmp))
1261 /* could check get_nulls_value() here and restart if ct
1262 * was moved to another chain. But given gc is best-effort
1263 * we will just continue with next hash slot.
1267 } while (++buckets < goal);
1269 if (gc_work->exiting)
1273 * Eviction will normally happen from the packet path, and not
1274 * from this gc worker.
1276 * This worker is only here to reap expired entries when system went
1277 * idle after a busy period.
1279 * The heuristics below are supposed to balance conflicting goals:
1281 * 1. Minimize time until we notice a stale entry
1282 * 2. Maximize scan intervals to not waste cycles
1284 * Normally, expire ratio will be close to 0.
1286 * As soon as a sizeable fraction of the entries have expired
1287 * increase scan frequency.
1289 ratio = scanned ? expired_count * 100 / scanned : 0;
1290 if (ratio > GC_EVICT_RATIO) {
1291 gc_work->next_gc_run = min_interval;
1293 unsigned int max = GC_MAX_SCAN_JIFFIES / GC_MAX_BUCKETS_DIV;
1295 BUILD_BUG_ON((GC_MAX_SCAN_JIFFIES / GC_MAX_BUCKETS_DIV) == 0);
1297 gc_work->next_gc_run += min_interval;
1298 if (gc_work->next_gc_run > max)
1299 gc_work->next_gc_run = max;
1302 next_run = gc_work->next_gc_run;
1303 gc_work->last_bucket = i;
1304 gc_work->early_drop = false;
1305 queue_delayed_work(system_power_efficient_wq, &gc_work->dwork, next_run);
1308 static void conntrack_gc_work_init(struct conntrack_gc_work *gc_work)
1310 INIT_DEFERRABLE_WORK(&gc_work->dwork, gc_worker);
1311 gc_work->next_gc_run = HZ;
1312 gc_work->exiting = false;
1315 static struct nf_conn *
1316 __nf_conntrack_alloc(struct net *net,
1317 const struct nf_conntrack_zone *zone,
1318 const struct nf_conntrack_tuple *orig,
1319 const struct nf_conntrack_tuple *repl,
1320 gfp_t gfp, u32 hash)
1324 /* We don't want any race condition at early drop stage */
1325 atomic_inc(&net->ct.count);
1327 if (nf_conntrack_max &&
1328 unlikely(atomic_read(&net->ct.count) > nf_conntrack_max)) {
1329 if (!early_drop(net, hash)) {
1330 if (!conntrack_gc_work.early_drop)
1331 conntrack_gc_work.early_drop = true;
1332 atomic_dec(&net->ct.count);
1333 net_warn_ratelimited("nf_conntrack: table full, dropping packet\n");
1334 return ERR_PTR(-ENOMEM);
1339 * Do not use kmem_cache_zalloc(), as this cache uses
1340 * SLAB_TYPESAFE_BY_RCU.
1342 ct = kmem_cache_alloc(nf_conntrack_cachep, gfp);
1346 spin_lock_init(&ct->lock);
1347 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple = *orig;
1348 ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode.pprev = NULL;
1349 ct->tuplehash[IP_CT_DIR_REPLY].tuple = *repl;
1350 /* save hash for reusing when confirming */
1351 *(unsigned long *)(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev) = hash;
1353 write_pnet(&ct->ct_net, net);
1354 memset(&ct->__nfct_init_offset[0], 0,
1355 offsetof(struct nf_conn, proto) -
1356 offsetof(struct nf_conn, __nfct_init_offset[0]));
1358 nf_ct_zone_add(ct, zone);
1360 /* Because we use RCU lookups, we set ct_general.use to zero before
1361 * this is inserted in any list.
1363 atomic_set(&ct->ct_general.use, 0);
1366 atomic_dec(&net->ct.count);
1367 return ERR_PTR(-ENOMEM);
1370 struct nf_conn *nf_conntrack_alloc(struct net *net,
1371 const struct nf_conntrack_zone *zone,
1372 const struct nf_conntrack_tuple *orig,
1373 const struct nf_conntrack_tuple *repl,
1376 return __nf_conntrack_alloc(net, zone, orig, repl, gfp, 0);
1378 EXPORT_SYMBOL_GPL(nf_conntrack_alloc);
1380 void nf_conntrack_free(struct nf_conn *ct)
1382 struct net *net = nf_ct_net(ct);
1384 /* A freed object has refcnt == 0, that's
1385 * the golden rule for SLAB_TYPESAFE_BY_RCU
1387 WARN_ON(atomic_read(&ct->ct_general.use) != 0);
1389 nf_ct_ext_destroy(ct);
1391 kmem_cache_free(nf_conntrack_cachep, ct);
1392 smp_mb__before_atomic();
1393 atomic_dec(&net->ct.count);
1395 EXPORT_SYMBOL_GPL(nf_conntrack_free);
1398 /* Allocate a new conntrack: we return -ENOMEM if classification
1399 failed due to stress. Otherwise it really is unclassifiable. */
1400 static noinline struct nf_conntrack_tuple_hash *
1401 init_conntrack(struct net *net, struct nf_conn *tmpl,
1402 const struct nf_conntrack_tuple *tuple,
1403 struct sk_buff *skb,
1404 unsigned int dataoff, u32 hash)
1407 struct nf_conn_help *help;
1408 struct nf_conntrack_tuple repl_tuple;
1409 struct nf_conntrack_ecache *ecache;
1410 struct nf_conntrack_expect *exp = NULL;
1411 const struct nf_conntrack_zone *zone;
1412 struct nf_conn_timeout *timeout_ext;
1413 struct nf_conntrack_zone tmp;
1415 if (!nf_ct_invert_tuple(&repl_tuple, tuple)) {
1416 pr_debug("Can't invert tuple.\n");
1420 zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1421 ct = __nf_conntrack_alloc(net, zone, tuple, &repl_tuple, GFP_ATOMIC,
1424 return (struct nf_conntrack_tuple_hash *)ct;
1426 if (!nf_ct_add_synproxy(ct, tmpl)) {
1427 nf_conntrack_free(ct);
1428 return ERR_PTR(-ENOMEM);
1431 timeout_ext = tmpl ? nf_ct_timeout_find(tmpl) : NULL;
1434 nf_ct_timeout_ext_add(ct, rcu_dereference(timeout_ext->timeout),
1437 nf_ct_acct_ext_add(ct, GFP_ATOMIC);
1438 nf_ct_tstamp_ext_add(ct, GFP_ATOMIC);
1439 nf_ct_labels_ext_add(ct);
1441 ecache = tmpl ? nf_ct_ecache_find(tmpl) : NULL;
1442 nf_ct_ecache_ext_add(ct, ecache ? ecache->ctmask : 0,
1443 ecache ? ecache->expmask : 0,
1447 if (net->ct.expect_count) {
1448 spin_lock(&nf_conntrack_expect_lock);
1449 exp = nf_ct_find_expectation(net, zone, tuple);
1451 pr_debug("expectation arrives ct=%p exp=%p\n",
1453 /* Welcome, Mr. Bond. We've been expecting you... */
1454 __set_bit(IPS_EXPECTED_BIT, &ct->status);
1455 /* exp->master safe, refcnt bumped in nf_ct_find_expectation */
1456 ct->master = exp->master;
1458 help = nf_ct_helper_ext_add(ct, GFP_ATOMIC);
1460 rcu_assign_pointer(help->helper, exp->helper);
1463 #ifdef CONFIG_NF_CONNTRACK_MARK
1464 ct->mark = exp->master->mark;
1466 #ifdef CONFIG_NF_CONNTRACK_SECMARK
1467 ct->secmark = exp->master->secmark;
1469 NF_CT_STAT_INC(net, expect_new);
1471 spin_unlock(&nf_conntrack_expect_lock);
1474 __nf_ct_try_assign_helper(ct, tmpl, GFP_ATOMIC);
1476 /* Now it is inserted into the unconfirmed list, bump refcount */
1477 nf_conntrack_get(&ct->ct_general);
1478 nf_ct_add_to_unconfirmed_list(ct);
1484 exp->expectfn(ct, exp);
1485 nf_ct_expect_put(exp);
1488 return &ct->tuplehash[IP_CT_DIR_ORIGINAL];
1491 /* On success, returns 0, sets skb->_nfct | ctinfo */
1493 resolve_normal_ct(struct nf_conn *tmpl,
1494 struct sk_buff *skb,
1495 unsigned int dataoff,
1497 const struct nf_hook_state *state)
1499 const struct nf_conntrack_zone *zone;
1500 struct nf_conntrack_tuple tuple;
1501 struct nf_conntrack_tuple_hash *h;
1502 enum ip_conntrack_info ctinfo;
1503 struct nf_conntrack_zone tmp;
1507 if (!nf_ct_get_tuple(skb, skb_network_offset(skb),
1508 dataoff, state->pf, protonum, state->net,
1510 pr_debug("Can't get tuple\n");
1514 /* look for tuple match */
1515 zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1516 hash = hash_conntrack_raw(&tuple, state->net);
1517 h = __nf_conntrack_find_get(state->net, zone, &tuple, hash);
1519 h = init_conntrack(state->net, tmpl, &tuple,
1520 skb, dataoff, hash);
1526 ct = nf_ct_tuplehash_to_ctrack(h);
1528 /* It exists; we have (non-exclusive) reference. */
1529 if (NF_CT_DIRECTION(h) == IP_CT_DIR_REPLY) {
1530 ctinfo = IP_CT_ESTABLISHED_REPLY;
1532 /* Once we've had two way comms, always ESTABLISHED. */
1533 if (test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) {
1534 pr_debug("normal packet for %p\n", ct);
1535 ctinfo = IP_CT_ESTABLISHED;
1536 } else if (test_bit(IPS_EXPECTED_BIT, &ct->status)) {
1537 pr_debug("related packet for %p\n", ct);
1538 ctinfo = IP_CT_RELATED;
1540 pr_debug("new packet for %p\n", ct);
1544 nf_ct_set(skb, ct, ctinfo);
1549 * icmp packets need special treatment to handle error messages that are
1550 * related to a connection.
1552 * Callers need to check if skb has a conntrack assigned when this
1553 * helper returns; in such case skb belongs to an already known connection.
1555 static unsigned int __cold
1556 nf_conntrack_handle_icmp(struct nf_conn *tmpl,
1557 struct sk_buff *skb,
1558 unsigned int dataoff,
1560 const struct nf_hook_state *state)
1564 if (state->pf == NFPROTO_IPV4 && protonum == IPPROTO_ICMP)
1565 ret = nf_conntrack_icmpv4_error(tmpl, skb, dataoff, state);
1566 #if IS_ENABLED(CONFIG_IPV6)
1567 else if (state->pf == NFPROTO_IPV6 && protonum == IPPROTO_ICMPV6)
1568 ret = nf_conntrack_icmpv6_error(tmpl, skb, dataoff, state);
1574 NF_CT_STAT_INC_ATOMIC(state->net, error);
1575 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1581 static int generic_packet(struct nf_conn *ct, struct sk_buff *skb,
1582 enum ip_conntrack_info ctinfo)
1584 const unsigned int *timeout = nf_ct_timeout_lookup(ct);
1587 timeout = &nf_generic_pernet(nf_ct_net(ct))->timeout;
1589 nf_ct_refresh_acct(ct, ctinfo, skb, *timeout);
1593 /* Returns verdict for packet, or -1 for invalid. */
1594 static int nf_conntrack_handle_packet(struct nf_conn *ct,
1595 struct sk_buff *skb,
1596 unsigned int dataoff,
1597 enum ip_conntrack_info ctinfo,
1598 const struct nf_hook_state *state)
1600 switch (nf_ct_protonum(ct)) {
1602 return nf_conntrack_tcp_packet(ct, skb, dataoff,
1605 return nf_conntrack_udp_packet(ct, skb, dataoff,
1608 return nf_conntrack_icmp_packet(ct, skb, ctinfo, state);
1609 #if IS_ENABLED(CONFIG_IPV6)
1610 case IPPROTO_ICMPV6:
1611 return nf_conntrack_icmpv6_packet(ct, skb, ctinfo, state);
1613 #ifdef CONFIG_NF_CT_PROTO_UDPLITE
1614 case IPPROTO_UDPLITE:
1615 return nf_conntrack_udplite_packet(ct, skb, dataoff,
1618 #ifdef CONFIG_NF_CT_PROTO_SCTP
1620 return nf_conntrack_sctp_packet(ct, skb, dataoff,
1623 #ifdef CONFIG_NF_CT_PROTO_DCCP
1625 return nf_conntrack_dccp_packet(ct, skb, dataoff,
1628 #ifdef CONFIG_NF_CT_PROTO_GRE
1630 return nf_conntrack_gre_packet(ct, skb, dataoff,
1635 return generic_packet(ct, skb, ctinfo);
1639 nf_conntrack_in(struct sk_buff *skb, const struct nf_hook_state *state)
1641 enum ip_conntrack_info ctinfo;
1642 struct nf_conn *ct, *tmpl;
1646 tmpl = nf_ct_get(skb, &ctinfo);
1647 if (tmpl || ctinfo == IP_CT_UNTRACKED) {
1648 /* Previously seen (loopback or untracked)? Ignore. */
1649 if ((tmpl && !nf_ct_is_template(tmpl)) ||
1650 ctinfo == IP_CT_UNTRACKED) {
1651 NF_CT_STAT_INC_ATOMIC(state->net, ignore);
1657 /* rcu_read_lock()ed by nf_hook_thresh */
1658 dataoff = get_l4proto(skb, skb_network_offset(skb), state->pf, &protonum);
1660 pr_debug("not prepared to track yet or error occurred\n");
1661 NF_CT_STAT_INC_ATOMIC(state->net, error);
1662 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1667 if (protonum == IPPROTO_ICMP || protonum == IPPROTO_ICMPV6) {
1668 ret = nf_conntrack_handle_icmp(tmpl, skb, dataoff,
1674 /* ICMP[v6] protocol trackers may assign one conntrack. */
1679 ret = resolve_normal_ct(tmpl, skb, dataoff,
1682 /* Too stressed to deal. */
1683 NF_CT_STAT_INC_ATOMIC(state->net, drop);
1688 ct = nf_ct_get(skb, &ctinfo);
1690 /* Not valid part of a connection */
1691 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1696 ret = nf_conntrack_handle_packet(ct, skb, dataoff, ctinfo, state);
1698 /* Invalid: inverse of the return code tells
1699 * the netfilter core what to do */
1700 pr_debug("nf_conntrack_in: Can't track with proto module\n");
1701 nf_conntrack_put(&ct->ct_general);
1703 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1704 if (ret == -NF_DROP)
1705 NF_CT_STAT_INC_ATOMIC(state->net, drop);
1706 /* Special case: TCP tracker reports an attempt to reopen a
1707 * closed/aborted connection. We have to go back and create a
1710 if (ret == -NF_REPEAT)
1716 if (ctinfo == IP_CT_ESTABLISHED_REPLY &&
1717 !test_and_set_bit(IPS_SEEN_REPLY_BIT, &ct->status))
1718 nf_conntrack_event_cache(IPCT_REPLY, ct);
1725 EXPORT_SYMBOL_GPL(nf_conntrack_in);
1727 /* Alter reply tuple (maybe alter helper). This is for NAT, and is
1728 implicitly racy: see __nf_conntrack_confirm */
1729 void nf_conntrack_alter_reply(struct nf_conn *ct,
1730 const struct nf_conntrack_tuple *newreply)
1732 struct nf_conn_help *help = nfct_help(ct);
1734 /* Should be unconfirmed, so not in hash table yet */
1735 WARN_ON(nf_ct_is_confirmed(ct));
1737 pr_debug("Altering reply tuple of %p to ", ct);
1738 nf_ct_dump_tuple(newreply);
1740 ct->tuplehash[IP_CT_DIR_REPLY].tuple = *newreply;
1741 if (ct->master || (help && !hlist_empty(&help->expectations)))
1745 __nf_ct_try_assign_helper(ct, NULL, GFP_ATOMIC);
1748 EXPORT_SYMBOL_GPL(nf_conntrack_alter_reply);
1750 /* Refresh conntrack for this many jiffies and do accounting if do_acct is 1 */
1751 void __nf_ct_refresh_acct(struct nf_conn *ct,
1752 enum ip_conntrack_info ctinfo,
1753 const struct sk_buff *skb,
1757 /* Only update if this is not a fixed timeout */
1758 if (test_bit(IPS_FIXED_TIMEOUT_BIT, &ct->status))
1761 /* If not in hash table, timer will not be active yet */
1762 if (nf_ct_is_confirmed(ct))
1763 extra_jiffies += nfct_time_stamp;
1765 if (ct->timeout != extra_jiffies)
1766 ct->timeout = extra_jiffies;
1769 nf_ct_acct_update(ct, ctinfo, skb->len);
1771 EXPORT_SYMBOL_GPL(__nf_ct_refresh_acct);
1773 bool nf_ct_kill_acct(struct nf_conn *ct,
1774 enum ip_conntrack_info ctinfo,
1775 const struct sk_buff *skb)
1777 nf_ct_acct_update(ct, ctinfo, skb->len);
1779 return nf_ct_delete(ct, 0, 0);
1781 EXPORT_SYMBOL_GPL(nf_ct_kill_acct);
1783 #if IS_ENABLED(CONFIG_NF_CT_NETLINK)
1785 #include <linux/netfilter/nfnetlink.h>
1786 #include <linux/netfilter/nfnetlink_conntrack.h>
1787 #include <linux/mutex.h>
1789 /* Generic function for tcp/udp/sctp/dccp and alike. This needs to be
1790 * in ip_conntrack_core, since we don't want the protocols to autoload
1791 * or depend on ctnetlink */
1792 int nf_ct_port_tuple_to_nlattr(struct sk_buff *skb,
1793 const struct nf_conntrack_tuple *tuple)
1795 if (nla_put_be16(skb, CTA_PROTO_SRC_PORT, tuple->src.u.tcp.port) ||
1796 nla_put_be16(skb, CTA_PROTO_DST_PORT, tuple->dst.u.tcp.port))
1797 goto nla_put_failure;
1803 EXPORT_SYMBOL_GPL(nf_ct_port_tuple_to_nlattr);
1805 const struct nla_policy nf_ct_port_nla_policy[CTA_PROTO_MAX+1] = {
1806 [CTA_PROTO_SRC_PORT] = { .type = NLA_U16 },
1807 [CTA_PROTO_DST_PORT] = { .type = NLA_U16 },
1809 EXPORT_SYMBOL_GPL(nf_ct_port_nla_policy);
1811 int nf_ct_port_nlattr_to_tuple(struct nlattr *tb[],
1812 struct nf_conntrack_tuple *t)
1814 if (!tb[CTA_PROTO_SRC_PORT] || !tb[CTA_PROTO_DST_PORT])
1817 t->src.u.tcp.port = nla_get_be16(tb[CTA_PROTO_SRC_PORT]);
1818 t->dst.u.tcp.port = nla_get_be16(tb[CTA_PROTO_DST_PORT]);
1822 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_to_tuple);
1824 unsigned int nf_ct_port_nlattr_tuple_size(void)
1826 static unsigned int size __read_mostly;
1829 size = nla_policy_len(nf_ct_port_nla_policy, CTA_PROTO_MAX + 1);
1833 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_tuple_size);
1836 /* Used by ipt_REJECT and ip6t_REJECT. */
1837 static void nf_conntrack_attach(struct sk_buff *nskb, const struct sk_buff *skb)
1840 enum ip_conntrack_info ctinfo;
1842 /* This ICMP is in reverse direction to the packet which caused it */
1843 ct = nf_ct_get(skb, &ctinfo);
1844 if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL)
1845 ctinfo = IP_CT_RELATED_REPLY;
1847 ctinfo = IP_CT_RELATED;
1849 /* Attach to new skbuff, and increment count */
1850 nf_ct_set(nskb, ct, ctinfo);
1851 nf_conntrack_get(skb_nfct(nskb));
1854 static int nf_conntrack_update(struct net *net, struct sk_buff *skb)
1856 struct nf_conntrack_tuple_hash *h;
1857 struct nf_conntrack_tuple tuple;
1858 enum ip_conntrack_info ctinfo;
1859 struct nf_nat_hook *nat_hook;
1860 unsigned int status;
1866 ct = nf_ct_get(skb, &ctinfo);
1867 if (!ct || nf_ct_is_confirmed(ct))
1870 l3num = nf_ct_l3num(ct);
1872 dataoff = get_l4proto(skb, skb_network_offset(skb), l3num, &l4num);
1876 if (!nf_ct_get_tuple(skb, skb_network_offset(skb), dataoff, l3num,
1877 l4num, net, &tuple))
1880 if (ct->status & IPS_SRC_NAT) {
1881 memcpy(tuple.src.u3.all,
1882 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u3.all,
1883 sizeof(tuple.src.u3.all));
1885 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u.all;
1888 if (ct->status & IPS_DST_NAT) {
1889 memcpy(tuple.dst.u3.all,
1890 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.u3.all,
1891 sizeof(tuple.dst.u3.all));
1893 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.u.all;
1896 h = nf_conntrack_find_get(net, nf_ct_zone(ct), &tuple);
1900 /* Store status bits of the conntrack that is clashing to re-do NAT
1901 * mangling according to what it has been done already to this packet.
1903 status = ct->status;
1906 ct = nf_ct_tuplehash_to_ctrack(h);
1907 nf_ct_set(skb, ct, ctinfo);
1909 nat_hook = rcu_dereference(nf_nat_hook);
1913 if (status & IPS_SRC_NAT &&
1914 nat_hook->manip_pkt(skb, ct, NF_NAT_MANIP_SRC,
1915 IP_CT_DIR_ORIGINAL) == NF_DROP)
1918 if (status & IPS_DST_NAT &&
1919 nat_hook->manip_pkt(skb, ct, NF_NAT_MANIP_DST,
1920 IP_CT_DIR_ORIGINAL) == NF_DROP)
1926 static bool nf_conntrack_get_tuple_skb(struct nf_conntrack_tuple *dst_tuple,
1927 const struct sk_buff *skb)
1929 const struct nf_conntrack_tuple *src_tuple;
1930 const struct nf_conntrack_tuple_hash *hash;
1931 struct nf_conntrack_tuple srctuple;
1932 enum ip_conntrack_info ctinfo;
1935 ct = nf_ct_get(skb, &ctinfo);
1937 src_tuple = nf_ct_tuple(ct, CTINFO2DIR(ctinfo));
1938 memcpy(dst_tuple, src_tuple, sizeof(*dst_tuple));
1942 if (!nf_ct_get_tuplepr(skb, skb_network_offset(skb),
1943 NFPROTO_IPV4, dev_net(skb->dev),
1947 hash = nf_conntrack_find_get(dev_net(skb->dev),
1953 ct = nf_ct_tuplehash_to_ctrack(hash);
1954 src_tuple = nf_ct_tuple(ct, !hash->tuple.dst.dir);
1955 memcpy(dst_tuple, src_tuple, sizeof(*dst_tuple));
1961 /* Bring out ya dead! */
1962 static struct nf_conn *
1963 get_next_corpse(int (*iter)(struct nf_conn *i, void *data),
1964 void *data, unsigned int *bucket)
1966 struct nf_conntrack_tuple_hash *h;
1968 struct hlist_nulls_node *n;
1971 for (; *bucket < nf_conntrack_htable_size; (*bucket)++) {
1972 lockp = &nf_conntrack_locks[*bucket % CONNTRACK_LOCKS];
1974 nf_conntrack_lock(lockp);
1975 if (*bucket < nf_conntrack_htable_size) {
1976 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[*bucket], hnnode) {
1977 if (NF_CT_DIRECTION(h) != IP_CT_DIR_ORIGINAL)
1979 ct = nf_ct_tuplehash_to_ctrack(h);
1991 atomic_inc(&ct->ct_general.use);
1997 static void nf_ct_iterate_cleanup(int (*iter)(struct nf_conn *i, void *data),
1998 void *data, u32 portid, int report)
2000 unsigned int bucket = 0, sequence;
2006 sequence = read_seqcount_begin(&nf_conntrack_generation);
2008 while ((ct = get_next_corpse(iter, data, &bucket)) != NULL) {
2009 /* Time to push up daises... */
2011 nf_ct_delete(ct, portid, report);
2016 if (!read_seqcount_retry(&nf_conntrack_generation, sequence))
2023 int (*iter)(struct nf_conn *i, void *data);
2028 static int iter_net_only(struct nf_conn *i, void *data)
2030 struct iter_data *d = data;
2032 if (!net_eq(d->net, nf_ct_net(i)))
2035 return d->iter(i, d->data);
2039 __nf_ct_unconfirmed_destroy(struct net *net)
2043 for_each_possible_cpu(cpu) {
2044 struct nf_conntrack_tuple_hash *h;
2045 struct hlist_nulls_node *n;
2046 struct ct_pcpu *pcpu;
2048 pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
2050 spin_lock_bh(&pcpu->lock);
2051 hlist_nulls_for_each_entry(h, n, &pcpu->unconfirmed, hnnode) {
2054 ct = nf_ct_tuplehash_to_ctrack(h);
2056 /* we cannot call iter() on unconfirmed list, the
2057 * owning cpu can reallocate ct->ext at any time.
2059 set_bit(IPS_DYING_BIT, &ct->status);
2061 spin_unlock_bh(&pcpu->lock);
2066 void nf_ct_unconfirmed_destroy(struct net *net)
2070 if (atomic_read(&net->ct.count) > 0) {
2071 __nf_ct_unconfirmed_destroy(net);
2072 nf_queue_nf_hook_drop(net);
2076 EXPORT_SYMBOL_GPL(nf_ct_unconfirmed_destroy);
2078 void nf_ct_iterate_cleanup_net(struct net *net,
2079 int (*iter)(struct nf_conn *i, void *data),
2080 void *data, u32 portid, int report)
2086 if (atomic_read(&net->ct.count) == 0)
2093 nf_ct_iterate_cleanup(iter_net_only, &d, portid, report);
2095 EXPORT_SYMBOL_GPL(nf_ct_iterate_cleanup_net);
2098 * nf_ct_iterate_destroy - destroy unconfirmed conntracks and iterate table
2099 * @iter: callback to invoke for each conntrack
2100 * @data: data to pass to @iter
2102 * Like nf_ct_iterate_cleanup, but first marks conntracks on the
2103 * unconfirmed list as dying (so they will not be inserted into
2106 * Can only be called in module exit path.
2109 nf_ct_iterate_destroy(int (*iter)(struct nf_conn *i, void *data), void *data)
2113 down_read(&net_rwsem);
2115 if (atomic_read(&net->ct.count) == 0)
2117 __nf_ct_unconfirmed_destroy(net);
2118 nf_queue_nf_hook_drop(net);
2120 up_read(&net_rwsem);
2122 /* Need to wait for netns cleanup worker to finish, if its
2123 * running -- it might have deleted a net namespace from
2124 * the global list, so our __nf_ct_unconfirmed_destroy() might
2125 * not have affected all namespaces.
2129 /* a conntrack could have been unlinked from unconfirmed list
2130 * before we grabbed pcpu lock in __nf_ct_unconfirmed_destroy().
2131 * This makes sure its inserted into conntrack table.
2135 nf_ct_iterate_cleanup(iter, data, 0, 0);
2137 EXPORT_SYMBOL_GPL(nf_ct_iterate_destroy);
2139 static int kill_all(struct nf_conn *i, void *data)
2141 return net_eq(nf_ct_net(i), data);
2144 void nf_conntrack_cleanup_start(void)
2146 conntrack_gc_work.exiting = true;
2147 RCU_INIT_POINTER(ip_ct_attach, NULL);
2150 void nf_conntrack_cleanup_end(void)
2152 RCU_INIT_POINTER(nf_ct_hook, NULL);
2153 cancel_delayed_work_sync(&conntrack_gc_work.dwork);
2154 kvfree(nf_conntrack_hash);
2156 nf_conntrack_proto_fini();
2157 nf_conntrack_seqadj_fini();
2158 nf_conntrack_labels_fini();
2159 nf_conntrack_helper_fini();
2160 nf_conntrack_timeout_fini();
2161 nf_conntrack_ecache_fini();
2162 nf_conntrack_tstamp_fini();
2163 nf_conntrack_acct_fini();
2164 nf_conntrack_expect_fini();
2166 kmem_cache_destroy(nf_conntrack_cachep);
2170 * Mishearing the voices in his head, our hero wonders how he's
2171 * supposed to kill the mall.
2173 void nf_conntrack_cleanup_net(struct net *net)
2177 list_add(&net->exit_list, &single);
2178 nf_conntrack_cleanup_net_list(&single);
2181 void nf_conntrack_cleanup_net_list(struct list_head *net_exit_list)
2187 * This makes sure all current packets have passed through
2188 * netfilter framework. Roll on, two-stage module
2194 list_for_each_entry(net, net_exit_list, exit_list) {
2195 nf_ct_iterate_cleanup(kill_all, net, 0, 0);
2196 if (atomic_read(&net->ct.count) != 0)
2201 goto i_see_dead_people;
2204 list_for_each_entry(net, net_exit_list, exit_list) {
2205 nf_conntrack_proto_pernet_fini(net);
2206 nf_conntrack_ecache_pernet_fini(net);
2207 nf_conntrack_expect_pernet_fini(net);
2208 free_percpu(net->ct.stat);
2209 free_percpu(net->ct.pcpu_lists);
2213 void *nf_ct_alloc_hashtable(unsigned int *sizep, int nulls)
2215 struct hlist_nulls_head *hash;
2216 unsigned int nr_slots, i;
2218 if (*sizep > (UINT_MAX / sizeof(struct hlist_nulls_head)))
2221 BUILD_BUG_ON(sizeof(struct hlist_nulls_head) != sizeof(struct hlist_head));
2222 nr_slots = *sizep = roundup(*sizep, PAGE_SIZE / sizeof(struct hlist_nulls_head));
2224 hash = kvmalloc_array(nr_slots, sizeof(struct hlist_nulls_head),
2225 GFP_KERNEL | __GFP_ZERO);
2228 for (i = 0; i < nr_slots; i++)
2229 INIT_HLIST_NULLS_HEAD(&hash[i], i);
2233 EXPORT_SYMBOL_GPL(nf_ct_alloc_hashtable);
2235 int nf_conntrack_hash_resize(unsigned int hashsize)
2238 unsigned int old_size;
2239 struct hlist_nulls_head *hash, *old_hash;
2240 struct nf_conntrack_tuple_hash *h;
2246 hash = nf_ct_alloc_hashtable(&hashsize, 1);
2250 old_size = nf_conntrack_htable_size;
2251 if (old_size == hashsize) {
2257 nf_conntrack_all_lock();
2258 write_seqcount_begin(&nf_conntrack_generation);
2260 /* Lookups in the old hash might happen in parallel, which means we
2261 * might get false negatives during connection lookup. New connections
2262 * created because of a false negative won't make it into the hash
2263 * though since that required taking the locks.
2266 for (i = 0; i < nf_conntrack_htable_size; i++) {
2267 while (!hlist_nulls_empty(&nf_conntrack_hash[i])) {
2268 h = hlist_nulls_entry(nf_conntrack_hash[i].first,
2269 struct nf_conntrack_tuple_hash, hnnode);
2270 ct = nf_ct_tuplehash_to_ctrack(h);
2271 hlist_nulls_del_rcu(&h->hnnode);
2272 bucket = __hash_conntrack(nf_ct_net(ct),
2273 &h->tuple, hashsize);
2274 hlist_nulls_add_head_rcu(&h->hnnode, &hash[bucket]);
2277 old_size = nf_conntrack_htable_size;
2278 old_hash = nf_conntrack_hash;
2280 nf_conntrack_hash = hash;
2281 nf_conntrack_htable_size = hashsize;
2283 write_seqcount_end(&nf_conntrack_generation);
2284 nf_conntrack_all_unlock();
2292 int nf_conntrack_set_hashsize(const char *val, const struct kernel_param *kp)
2294 unsigned int hashsize;
2297 if (current->nsproxy->net_ns != &init_net)
2300 /* On boot, we can set this without any fancy locking. */
2301 if (!nf_conntrack_hash)
2302 return param_set_uint(val, kp);
2304 rc = kstrtouint(val, 0, &hashsize);
2308 return nf_conntrack_hash_resize(hashsize);
2310 EXPORT_SYMBOL_GPL(nf_conntrack_set_hashsize);
2312 static __always_inline unsigned int total_extension_size(void)
2314 /* remember to add new extensions below */
2315 BUILD_BUG_ON(NF_CT_EXT_NUM > 9);
2317 return sizeof(struct nf_ct_ext) +
2318 sizeof(struct nf_conn_help)
2319 #if IS_ENABLED(CONFIG_NF_NAT)
2320 + sizeof(struct nf_conn_nat)
2322 + sizeof(struct nf_conn_seqadj)
2323 + sizeof(struct nf_conn_acct)
2324 #ifdef CONFIG_NF_CONNTRACK_EVENTS
2325 + sizeof(struct nf_conntrack_ecache)
2327 #ifdef CONFIG_NF_CONNTRACK_TIMESTAMP
2328 + sizeof(struct nf_conn_tstamp)
2330 #ifdef CONFIG_NF_CONNTRACK_TIMEOUT
2331 + sizeof(struct nf_conn_timeout)
2333 #ifdef CONFIG_NF_CONNTRACK_LABELS
2334 + sizeof(struct nf_conn_labels)
2336 #if IS_ENABLED(CONFIG_NETFILTER_SYNPROXY)
2337 + sizeof(struct nf_conn_synproxy)
2342 int nf_conntrack_init_start(void)
2344 unsigned long nr_pages = totalram_pages();
2349 /* struct nf_ct_ext uses u8 to store offsets/size */
2350 BUILD_BUG_ON(total_extension_size() > 255u);
2352 seqcount_init(&nf_conntrack_generation);
2354 for (i = 0; i < CONNTRACK_LOCKS; i++)
2355 spin_lock_init(&nf_conntrack_locks[i]);
2357 if (!nf_conntrack_htable_size) {
2358 /* Idea from tcp.c: use 1/16384 of memory.
2359 * On i386: 32MB machine has 512 buckets.
2360 * >= 1GB machines have 16384 buckets.
2361 * >= 4GB machines have 65536 buckets.
2363 nf_conntrack_htable_size
2364 = (((nr_pages << PAGE_SHIFT) / 16384)
2365 / sizeof(struct hlist_head));
2366 if (nr_pages > (4 * (1024 * 1024 * 1024 / PAGE_SIZE)))
2367 nf_conntrack_htable_size = 65536;
2368 else if (nr_pages > (1024 * 1024 * 1024 / PAGE_SIZE))
2369 nf_conntrack_htable_size = 16384;
2370 if (nf_conntrack_htable_size < 32)
2371 nf_conntrack_htable_size = 32;
2373 /* Use a max. factor of four by default to get the same max as
2374 * with the old struct list_heads. When a table size is given
2375 * we use the old value of 8 to avoid reducing the max.
2380 nf_conntrack_hash = nf_ct_alloc_hashtable(&nf_conntrack_htable_size, 1);
2381 if (!nf_conntrack_hash)
2384 nf_conntrack_max = max_factor * nf_conntrack_htable_size;
2386 nf_conntrack_cachep = kmem_cache_create("nf_conntrack",
2387 sizeof(struct nf_conn),
2389 SLAB_TYPESAFE_BY_RCU | SLAB_HWCACHE_ALIGN, NULL);
2390 if (!nf_conntrack_cachep)
2393 ret = nf_conntrack_expect_init();
2397 ret = nf_conntrack_acct_init();
2401 ret = nf_conntrack_tstamp_init();
2405 ret = nf_conntrack_ecache_init();
2409 ret = nf_conntrack_timeout_init();
2413 ret = nf_conntrack_helper_init();
2417 ret = nf_conntrack_labels_init();
2421 ret = nf_conntrack_seqadj_init();
2425 ret = nf_conntrack_proto_init();
2429 conntrack_gc_work_init(&conntrack_gc_work);
2430 queue_delayed_work(system_power_efficient_wq, &conntrack_gc_work.dwork, HZ);
2435 nf_conntrack_seqadj_fini();
2437 nf_conntrack_labels_fini();
2439 nf_conntrack_helper_fini();
2441 nf_conntrack_timeout_fini();
2443 nf_conntrack_ecache_fini();
2445 nf_conntrack_tstamp_fini();
2447 nf_conntrack_acct_fini();
2449 nf_conntrack_expect_fini();
2451 kmem_cache_destroy(nf_conntrack_cachep);
2453 kvfree(nf_conntrack_hash);
2457 static struct nf_ct_hook nf_conntrack_hook = {
2458 .update = nf_conntrack_update,
2459 .destroy = destroy_conntrack,
2460 .get_tuple_skb = nf_conntrack_get_tuple_skb,
2463 void nf_conntrack_init_end(void)
2465 /* For use by REJECT target */
2466 RCU_INIT_POINTER(ip_ct_attach, nf_conntrack_attach);
2467 RCU_INIT_POINTER(nf_ct_hook, &nf_conntrack_hook);
2471 * We need to use special "null" values, not used in hash table
2473 #define UNCONFIRMED_NULLS_VAL ((1<<30)+0)
2474 #define DYING_NULLS_VAL ((1<<30)+1)
2475 #define TEMPLATE_NULLS_VAL ((1<<30)+2)
2477 int nf_conntrack_init_net(struct net *net)
2482 BUILD_BUG_ON(IP_CT_UNTRACKED == IP_CT_NUMBER);
2483 BUILD_BUG_ON_NOT_POWER_OF_2(CONNTRACK_LOCKS);
2484 atomic_set(&net->ct.count, 0);
2486 net->ct.pcpu_lists = alloc_percpu(struct ct_pcpu);
2487 if (!net->ct.pcpu_lists)
2490 for_each_possible_cpu(cpu) {
2491 struct ct_pcpu *pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
2493 spin_lock_init(&pcpu->lock);
2494 INIT_HLIST_NULLS_HEAD(&pcpu->unconfirmed, UNCONFIRMED_NULLS_VAL);
2495 INIT_HLIST_NULLS_HEAD(&pcpu->dying, DYING_NULLS_VAL);
2498 net->ct.stat = alloc_percpu(struct ip_conntrack_stat);
2500 goto err_pcpu_lists;
2502 ret = nf_conntrack_expect_pernet_init(net);
2506 nf_conntrack_acct_pernet_init(net);
2507 nf_conntrack_tstamp_pernet_init(net);
2508 nf_conntrack_ecache_pernet_init(net);
2509 nf_conntrack_helper_pernet_init(net);
2510 nf_conntrack_proto_pernet_init(net);
2515 free_percpu(net->ct.stat);
2517 free_percpu(net->ct.pcpu_lists);