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_core.h>
55 #include <net/netfilter/nf_nat_helper.h>
56 #include <net/netns/hash.h>
59 #include "nf_internals.h"
61 __cacheline_aligned_in_smp spinlock_t nf_conntrack_locks[CONNTRACK_LOCKS];
62 EXPORT_SYMBOL_GPL(nf_conntrack_locks);
64 __cacheline_aligned_in_smp DEFINE_SPINLOCK(nf_conntrack_expect_lock);
65 EXPORT_SYMBOL_GPL(nf_conntrack_expect_lock);
67 struct hlist_nulls_head *nf_conntrack_hash __read_mostly;
68 EXPORT_SYMBOL_GPL(nf_conntrack_hash);
70 struct conntrack_gc_work {
71 struct delayed_work dwork;
78 static __read_mostly struct kmem_cache *nf_conntrack_cachep;
79 static __read_mostly spinlock_t nf_conntrack_locks_all_lock;
80 static __read_mostly DEFINE_SPINLOCK(nf_conntrack_locks_all_lock);
81 static __read_mostly bool nf_conntrack_locks_all;
83 /* every gc cycle scans at most 1/GC_MAX_BUCKETS_DIV part of table */
84 #define GC_MAX_BUCKETS_DIV 128u
85 /* upper bound of full table scan */
86 #define GC_MAX_SCAN_JIFFIES (16u * HZ)
87 /* desired ratio of entries found to be expired */
88 #define GC_EVICT_RATIO 50u
90 static struct conntrack_gc_work conntrack_gc_work;
92 void nf_conntrack_lock(spinlock_t *lock) __acquires(lock)
94 /* 1) Acquire the lock */
97 /* 2) read nf_conntrack_locks_all, with ACQUIRE semantics
98 * It pairs with the smp_store_release() in nf_conntrack_all_unlock()
100 if (likely(smp_load_acquire(&nf_conntrack_locks_all) == false))
103 /* fast path failed, unlock */
106 /* Slow path 1) get global lock */
107 spin_lock(&nf_conntrack_locks_all_lock);
109 /* Slow path 2) get the lock we want */
112 /* Slow path 3) release the global lock */
113 spin_unlock(&nf_conntrack_locks_all_lock);
115 EXPORT_SYMBOL_GPL(nf_conntrack_lock);
117 static void nf_conntrack_double_unlock(unsigned int h1, unsigned int h2)
119 h1 %= CONNTRACK_LOCKS;
120 h2 %= CONNTRACK_LOCKS;
121 spin_unlock(&nf_conntrack_locks[h1]);
123 spin_unlock(&nf_conntrack_locks[h2]);
126 /* return true if we need to recompute hashes (in case hash table was resized) */
127 static bool nf_conntrack_double_lock(struct net *net, unsigned int h1,
128 unsigned int h2, unsigned int sequence)
130 h1 %= CONNTRACK_LOCKS;
131 h2 %= CONNTRACK_LOCKS;
133 nf_conntrack_lock(&nf_conntrack_locks[h1]);
135 spin_lock_nested(&nf_conntrack_locks[h2],
136 SINGLE_DEPTH_NESTING);
138 nf_conntrack_lock(&nf_conntrack_locks[h2]);
139 spin_lock_nested(&nf_conntrack_locks[h1],
140 SINGLE_DEPTH_NESTING);
142 if (read_seqcount_retry(&nf_conntrack_generation, sequence)) {
143 nf_conntrack_double_unlock(h1, h2);
149 static void nf_conntrack_all_lock(void)
153 spin_lock(&nf_conntrack_locks_all_lock);
155 nf_conntrack_locks_all = true;
157 for (i = 0; i < CONNTRACK_LOCKS; i++) {
158 spin_lock(&nf_conntrack_locks[i]);
160 /* This spin_unlock provides the "release" to ensure that
161 * nf_conntrack_locks_all==true is visible to everyone that
162 * acquired spin_lock(&nf_conntrack_locks[]).
164 spin_unlock(&nf_conntrack_locks[i]);
168 static void nf_conntrack_all_unlock(void)
170 /* All prior stores must be complete before we clear
171 * 'nf_conntrack_locks_all'. Otherwise nf_conntrack_lock()
172 * might observe the false value but not the entire
174 * It pairs with the smp_load_acquire() in nf_conntrack_lock()
176 smp_store_release(&nf_conntrack_locks_all, false);
177 spin_unlock(&nf_conntrack_locks_all_lock);
180 unsigned int nf_conntrack_htable_size __read_mostly;
181 EXPORT_SYMBOL_GPL(nf_conntrack_htable_size);
183 unsigned int nf_conntrack_max __read_mostly;
184 EXPORT_SYMBOL_GPL(nf_conntrack_max);
185 seqcount_t nf_conntrack_generation __read_mostly;
186 static unsigned int nf_conntrack_hash_rnd __read_mostly;
188 static u32 hash_conntrack_raw(const struct nf_conntrack_tuple *tuple,
189 const struct net *net)
194 get_random_once(&nf_conntrack_hash_rnd, sizeof(nf_conntrack_hash_rnd));
196 /* The direction must be ignored, so we hash everything up to the
197 * destination ports (which is a multiple of 4) and treat the last
198 * three bytes manually.
200 seed = nf_conntrack_hash_rnd ^ net_hash_mix(net);
201 n = (sizeof(tuple->src) + sizeof(tuple->dst.u3)) / sizeof(u32);
202 return jhash2((u32 *)tuple, n, seed ^
203 (((__force __u16)tuple->dst.u.all << 16) |
204 tuple->dst.protonum));
207 static u32 scale_hash(u32 hash)
209 return reciprocal_scale(hash, nf_conntrack_htable_size);
212 static u32 __hash_conntrack(const struct net *net,
213 const struct nf_conntrack_tuple *tuple,
216 return reciprocal_scale(hash_conntrack_raw(tuple, net), size);
219 static u32 hash_conntrack(const struct net *net,
220 const struct nf_conntrack_tuple *tuple)
222 return scale_hash(hash_conntrack_raw(tuple, net));
225 static bool nf_ct_get_tuple_ports(const struct sk_buff *skb,
226 unsigned int dataoff,
227 struct nf_conntrack_tuple *tuple)
231 } _inet_hdr, *inet_hdr;
233 /* Actually only need first 4 bytes to get ports. */
234 inet_hdr = skb_header_pointer(skb, dataoff, sizeof(_inet_hdr), &_inet_hdr);
238 tuple->src.u.udp.port = inet_hdr->sport;
239 tuple->dst.u.udp.port = inet_hdr->dport;
244 nf_ct_get_tuple(const struct sk_buff *skb,
246 unsigned int dataoff,
250 struct nf_conntrack_tuple *tuple)
256 memset(tuple, 0, sizeof(*tuple));
258 tuple->src.l3num = l3num;
261 nhoff += offsetof(struct iphdr, saddr);
262 size = 2 * sizeof(__be32);
265 nhoff += offsetof(struct ipv6hdr, saddr);
266 size = sizeof(_addrs);
272 ap = skb_header_pointer(skb, nhoff, size, _addrs);
278 tuple->src.u3.ip = ap[0];
279 tuple->dst.u3.ip = ap[1];
282 memcpy(tuple->src.u3.ip6, ap, sizeof(tuple->src.u3.ip6));
283 memcpy(tuple->dst.u3.ip6, ap + 4, sizeof(tuple->dst.u3.ip6));
287 tuple->dst.protonum = protonum;
288 tuple->dst.dir = IP_CT_DIR_ORIGINAL;
291 #if IS_ENABLED(CONFIG_IPV6)
293 return icmpv6_pkt_to_tuple(skb, dataoff, net, tuple);
296 return icmp_pkt_to_tuple(skb, dataoff, net, tuple);
297 #ifdef CONFIG_NF_CT_PROTO_GRE
299 return gre_pkt_to_tuple(skb, dataoff, net, tuple);
302 case IPPROTO_UDP: /* fallthrough */
303 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
304 #ifdef CONFIG_NF_CT_PROTO_UDPLITE
305 case IPPROTO_UDPLITE:
306 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
308 #ifdef CONFIG_NF_CT_PROTO_SCTP
310 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
312 #ifdef CONFIG_NF_CT_PROTO_DCCP
314 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
323 static int ipv4_get_l4proto(const struct sk_buff *skb, unsigned int nhoff,
327 const struct iphdr *iph;
330 iph = skb_header_pointer(skb, nhoff, sizeof(_iph), &_iph);
334 /* Conntrack defragments packets, we might still see fragments
335 * inside ICMP packets though.
337 if (iph->frag_off & htons(IP_OFFSET))
340 dataoff = nhoff + (iph->ihl << 2);
341 *protonum = iph->protocol;
343 /* Check bogus IP headers */
344 if (dataoff > skb->len) {
345 pr_debug("bogus IPv4 packet: nhoff %u, ihl %u, skblen %u\n",
346 nhoff, iph->ihl << 2, skb->len);
352 #if IS_ENABLED(CONFIG_IPV6)
353 static int ipv6_get_l4proto(const struct sk_buff *skb, unsigned int nhoff,
357 unsigned int extoff = nhoff + sizeof(struct ipv6hdr);
361 if (skb_copy_bits(skb, nhoff + offsetof(struct ipv6hdr, nexthdr),
362 &nexthdr, sizeof(nexthdr)) != 0) {
363 pr_debug("can't get nexthdr\n");
366 protoff = ipv6_skip_exthdr(skb, extoff, &nexthdr, &frag_off);
368 * (protoff == skb->len) means the packet has not data, just
369 * IPv6 and possibly extensions headers, but it is tracked anyway
371 if (protoff < 0 || (frag_off & htons(~0x7)) != 0) {
372 pr_debug("can't find proto in pkt\n");
381 static int get_l4proto(const struct sk_buff *skb,
382 unsigned int nhoff, u8 pf, u8 *l4num)
386 return ipv4_get_l4proto(skb, nhoff, l4num);
387 #if IS_ENABLED(CONFIG_IPV6)
389 return ipv6_get_l4proto(skb, nhoff, l4num);
398 bool nf_ct_get_tuplepr(const struct sk_buff *skb, unsigned int nhoff,
400 struct net *net, struct nf_conntrack_tuple *tuple)
405 protoff = get_l4proto(skb, nhoff, l3num, &protonum);
409 return nf_ct_get_tuple(skb, nhoff, protoff, l3num, protonum, net, tuple);
411 EXPORT_SYMBOL_GPL(nf_ct_get_tuplepr);
414 nf_ct_invert_tuple(struct nf_conntrack_tuple *inverse,
415 const struct nf_conntrack_tuple *orig)
417 memset(inverse, 0, sizeof(*inverse));
419 inverse->src.l3num = orig->src.l3num;
421 switch (orig->src.l3num) {
423 inverse->src.u3.ip = orig->dst.u3.ip;
424 inverse->dst.u3.ip = orig->src.u3.ip;
427 inverse->src.u3.in6 = orig->dst.u3.in6;
428 inverse->dst.u3.in6 = orig->src.u3.in6;
434 inverse->dst.dir = !orig->dst.dir;
436 inverse->dst.protonum = orig->dst.protonum;
438 switch (orig->dst.protonum) {
440 return nf_conntrack_invert_icmp_tuple(inverse, orig);
441 #if IS_ENABLED(CONFIG_IPV6)
443 return nf_conntrack_invert_icmpv6_tuple(inverse, orig);
447 inverse->src.u.all = orig->dst.u.all;
448 inverse->dst.u.all = orig->src.u.all;
451 EXPORT_SYMBOL_GPL(nf_ct_invert_tuple);
454 clean_from_lists(struct nf_conn *ct)
456 pr_debug("clean_from_lists(%p)\n", ct);
457 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
458 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode);
460 /* Destroy all pending expectations */
461 nf_ct_remove_expectations(ct);
464 /* must be called with local_bh_disable */
465 static void nf_ct_add_to_dying_list(struct nf_conn *ct)
467 struct ct_pcpu *pcpu;
469 /* add this conntrack to the (per cpu) dying list */
470 ct->cpu = smp_processor_id();
471 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
473 spin_lock(&pcpu->lock);
474 hlist_nulls_add_head(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
476 spin_unlock(&pcpu->lock);
479 /* must be called with local_bh_disable */
480 static void nf_ct_add_to_unconfirmed_list(struct nf_conn *ct)
482 struct ct_pcpu *pcpu;
484 /* add this conntrack to the (per cpu) unconfirmed list */
485 ct->cpu = smp_processor_id();
486 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
488 spin_lock(&pcpu->lock);
489 hlist_nulls_add_head(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
491 spin_unlock(&pcpu->lock);
494 /* must be called with local_bh_disable */
495 static void nf_ct_del_from_dying_or_unconfirmed_list(struct nf_conn *ct)
497 struct ct_pcpu *pcpu;
499 /* We overload first tuple to link into unconfirmed or dying list.*/
500 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
502 spin_lock(&pcpu->lock);
503 BUG_ON(hlist_nulls_unhashed(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode));
504 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
505 spin_unlock(&pcpu->lock);
508 #define NFCT_ALIGN(len) (((len) + NFCT_INFOMASK) & ~NFCT_INFOMASK)
510 /* Released via destroy_conntrack() */
511 struct nf_conn *nf_ct_tmpl_alloc(struct net *net,
512 const struct nf_conntrack_zone *zone,
515 struct nf_conn *tmpl, *p;
517 if (ARCH_KMALLOC_MINALIGN <= NFCT_INFOMASK) {
518 tmpl = kzalloc(sizeof(*tmpl) + NFCT_INFOMASK, flags);
523 tmpl = (struct nf_conn *)NFCT_ALIGN((unsigned long)p);
525 tmpl = (struct nf_conn *)NFCT_ALIGN((unsigned long)p);
526 tmpl->proto.tmpl_padto = (char *)tmpl - (char *)p;
529 tmpl = kzalloc(sizeof(*tmpl), flags);
534 tmpl->status = IPS_TEMPLATE;
535 write_pnet(&tmpl->ct_net, net);
536 nf_ct_zone_add(tmpl, zone);
537 atomic_set(&tmpl->ct_general.use, 0);
541 EXPORT_SYMBOL_GPL(nf_ct_tmpl_alloc);
543 void nf_ct_tmpl_free(struct nf_conn *tmpl)
545 nf_ct_ext_destroy(tmpl);
546 nf_ct_ext_free(tmpl);
548 if (ARCH_KMALLOC_MINALIGN <= NFCT_INFOMASK)
549 kfree((char *)tmpl - tmpl->proto.tmpl_padto);
553 EXPORT_SYMBOL_GPL(nf_ct_tmpl_free);
555 static void destroy_gre_conntrack(struct nf_conn *ct)
557 #ifdef CONFIG_NF_CT_PROTO_GRE
558 struct nf_conn *master = ct->master;
561 nf_ct_gre_keymap_destroy(master);
566 destroy_conntrack(struct nf_conntrack *nfct)
568 struct nf_conn *ct = (struct nf_conn *)nfct;
570 pr_debug("destroy_conntrack(%p)\n", ct);
571 WARN_ON(atomic_read(&nfct->use) != 0);
573 if (unlikely(nf_ct_is_template(ct))) {
578 if (unlikely(nf_ct_protonum(ct) == IPPROTO_GRE))
579 destroy_gre_conntrack(ct);
582 /* Expectations will have been removed in clean_from_lists,
583 * except TFTP can create an expectation on the first packet,
584 * before connection is in the list, so we need to clean here,
587 nf_ct_remove_expectations(ct);
589 nf_ct_del_from_dying_or_unconfirmed_list(ct);
594 nf_ct_put(ct->master);
596 pr_debug("destroy_conntrack: returning ct=%p to slab\n", ct);
597 nf_conntrack_free(ct);
600 static void nf_ct_delete_from_lists(struct nf_conn *ct)
602 struct net *net = nf_ct_net(ct);
603 unsigned int hash, reply_hash;
604 unsigned int sequence;
606 nf_ct_helper_destroy(ct);
610 sequence = read_seqcount_begin(&nf_conntrack_generation);
611 hash = hash_conntrack(net,
612 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
613 reply_hash = hash_conntrack(net,
614 &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
615 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
617 clean_from_lists(ct);
618 nf_conntrack_double_unlock(hash, reply_hash);
620 nf_ct_add_to_dying_list(ct);
625 bool nf_ct_delete(struct nf_conn *ct, u32 portid, int report)
627 struct nf_conn_tstamp *tstamp;
629 if (test_and_set_bit(IPS_DYING_BIT, &ct->status))
632 tstamp = nf_conn_tstamp_find(ct);
633 if (tstamp && tstamp->stop == 0)
634 tstamp->stop = ktime_get_real_ns();
636 if (nf_conntrack_event_report(IPCT_DESTROY, ct,
637 portid, report) < 0) {
638 /* destroy event was not delivered. nf_ct_put will
639 * be done by event cache worker on redelivery.
641 nf_ct_delete_from_lists(ct);
642 nf_conntrack_ecache_delayed_work(nf_ct_net(ct));
646 nf_conntrack_ecache_work(nf_ct_net(ct));
647 nf_ct_delete_from_lists(ct);
651 EXPORT_SYMBOL_GPL(nf_ct_delete);
654 nf_ct_key_equal(struct nf_conntrack_tuple_hash *h,
655 const struct nf_conntrack_tuple *tuple,
656 const struct nf_conntrack_zone *zone,
657 const struct net *net)
659 struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
661 /* A conntrack can be recreated with the equal tuple,
662 * so we need to check that the conntrack is confirmed
664 return nf_ct_tuple_equal(tuple, &h->tuple) &&
665 nf_ct_zone_equal(ct, zone, NF_CT_DIRECTION(h)) &&
666 nf_ct_is_confirmed(ct) &&
667 net_eq(net, nf_ct_net(ct));
671 nf_ct_match(const struct nf_conn *ct1, const struct nf_conn *ct2)
673 return nf_ct_tuple_equal(&ct1->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
674 &ct2->tuplehash[IP_CT_DIR_ORIGINAL].tuple) &&
675 nf_ct_tuple_equal(&ct1->tuplehash[IP_CT_DIR_REPLY].tuple,
676 &ct2->tuplehash[IP_CT_DIR_REPLY].tuple) &&
677 nf_ct_zone_equal(ct1, nf_ct_zone(ct2), IP_CT_DIR_ORIGINAL) &&
678 nf_ct_zone_equal(ct1, nf_ct_zone(ct2), IP_CT_DIR_REPLY) &&
679 net_eq(nf_ct_net(ct1), nf_ct_net(ct2));
682 /* caller must hold rcu readlock and none of the nf_conntrack_locks */
683 static void nf_ct_gc_expired(struct nf_conn *ct)
685 if (!atomic_inc_not_zero(&ct->ct_general.use))
688 if (nf_ct_should_gc(ct))
696 * - Caller must take a reference on returned object
697 * and recheck nf_ct_tuple_equal(tuple, &h->tuple)
699 static struct nf_conntrack_tuple_hash *
700 ____nf_conntrack_find(struct net *net, const struct nf_conntrack_zone *zone,
701 const struct nf_conntrack_tuple *tuple, u32 hash)
703 struct nf_conntrack_tuple_hash *h;
704 struct hlist_nulls_head *ct_hash;
705 struct hlist_nulls_node *n;
706 unsigned int bucket, hsize;
709 nf_conntrack_get_ht(&ct_hash, &hsize);
710 bucket = reciprocal_scale(hash, hsize);
712 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[bucket], hnnode) {
715 ct = nf_ct_tuplehash_to_ctrack(h);
716 if (nf_ct_is_expired(ct)) {
717 nf_ct_gc_expired(ct);
721 if (nf_ct_is_dying(ct))
724 if (nf_ct_key_equal(h, tuple, zone, net))
728 * if the nulls value we got at the end of this lookup is
729 * not the expected one, we must restart lookup.
730 * We probably met an item that was moved to another chain.
732 if (get_nulls_value(n) != bucket) {
733 NF_CT_STAT_INC_ATOMIC(net, search_restart);
740 /* Find a connection corresponding to a tuple. */
741 static struct nf_conntrack_tuple_hash *
742 __nf_conntrack_find_get(struct net *net, const struct nf_conntrack_zone *zone,
743 const struct nf_conntrack_tuple *tuple, u32 hash)
745 struct nf_conntrack_tuple_hash *h;
750 h = ____nf_conntrack_find(net, zone, tuple, hash);
752 ct = nf_ct_tuplehash_to_ctrack(h);
753 if (unlikely(nf_ct_is_dying(ct) ||
754 !atomic_inc_not_zero(&ct->ct_general.use)))
757 if (unlikely(!nf_ct_key_equal(h, tuple, zone, net))) {
768 struct nf_conntrack_tuple_hash *
769 nf_conntrack_find_get(struct net *net, const struct nf_conntrack_zone *zone,
770 const struct nf_conntrack_tuple *tuple)
772 return __nf_conntrack_find_get(net, zone, tuple,
773 hash_conntrack_raw(tuple, net));
775 EXPORT_SYMBOL_GPL(nf_conntrack_find_get);
777 static void __nf_conntrack_hash_insert(struct nf_conn *ct,
779 unsigned int reply_hash)
781 hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
782 &nf_conntrack_hash[hash]);
783 hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode,
784 &nf_conntrack_hash[reply_hash]);
788 nf_conntrack_hash_check_insert(struct nf_conn *ct)
790 const struct nf_conntrack_zone *zone;
791 struct net *net = nf_ct_net(ct);
792 unsigned int hash, reply_hash;
793 struct nf_conntrack_tuple_hash *h;
794 struct hlist_nulls_node *n;
795 unsigned int sequence;
797 zone = nf_ct_zone(ct);
801 sequence = read_seqcount_begin(&nf_conntrack_generation);
802 hash = hash_conntrack(net,
803 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
804 reply_hash = hash_conntrack(net,
805 &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
806 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
808 /* See if there's one in the list already, including reverse */
809 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode)
810 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
814 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode)
815 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
820 /* The caller holds a reference to this object */
821 atomic_set(&ct->ct_general.use, 2);
822 __nf_conntrack_hash_insert(ct, hash, reply_hash);
823 nf_conntrack_double_unlock(hash, reply_hash);
824 NF_CT_STAT_INC(net, insert);
829 nf_conntrack_double_unlock(hash, reply_hash);
830 NF_CT_STAT_INC(net, insert_failed);
834 EXPORT_SYMBOL_GPL(nf_conntrack_hash_check_insert);
836 static inline void nf_ct_acct_update(struct nf_conn *ct,
837 enum ip_conntrack_info ctinfo,
840 struct nf_conn_acct *acct;
842 acct = nf_conn_acct_find(ct);
844 struct nf_conn_counter *counter = acct->counter;
846 atomic64_inc(&counter[CTINFO2DIR(ctinfo)].packets);
847 atomic64_add(len, &counter[CTINFO2DIR(ctinfo)].bytes);
851 static void nf_ct_acct_merge(struct nf_conn *ct, enum ip_conntrack_info ctinfo,
852 const struct nf_conn *loser_ct)
854 struct nf_conn_acct *acct;
856 acct = nf_conn_acct_find(loser_ct);
858 struct nf_conn_counter *counter = acct->counter;
861 /* u32 should be fine since we must have seen one packet. */
862 bytes = atomic64_read(&counter[CTINFO2DIR(ctinfo)].bytes);
863 nf_ct_acct_update(ct, ctinfo, bytes);
867 /* Resolve race on insertion if this protocol allows this. */
868 static int nf_ct_resolve_clash(struct net *net, struct sk_buff *skb,
869 enum ip_conntrack_info ctinfo,
870 struct nf_conntrack_tuple_hash *h)
872 /* This is the conntrack entry already in hashes that won race. */
873 struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
874 const struct nf_conntrack_l4proto *l4proto;
875 enum ip_conntrack_info oldinfo;
876 struct nf_conn *loser_ct = nf_ct_get(skb, &oldinfo);
878 l4proto = nf_ct_l4proto_find(nf_ct_protonum(ct));
879 if (l4proto->allow_clash &&
880 !nf_ct_is_dying(ct) &&
881 atomic_inc_not_zero(&ct->ct_general.use)) {
882 if (((ct->status & IPS_NAT_DONE_MASK) == 0) ||
883 nf_ct_match(ct, loser_ct)) {
884 nf_ct_acct_merge(ct, ctinfo, loser_ct);
885 nf_conntrack_put(&loser_ct->ct_general);
886 nf_ct_set(skb, ct, oldinfo);
891 NF_CT_STAT_INC(net, drop);
895 /* Confirm a connection given skb; places it in hash table */
897 __nf_conntrack_confirm(struct sk_buff *skb)
899 const struct nf_conntrack_zone *zone;
900 unsigned int hash, reply_hash;
901 struct nf_conntrack_tuple_hash *h;
903 struct nf_conn_help *help;
904 struct nf_conn_tstamp *tstamp;
905 struct hlist_nulls_node *n;
906 enum ip_conntrack_info ctinfo;
908 unsigned int sequence;
911 ct = nf_ct_get(skb, &ctinfo);
914 /* ipt_REJECT uses nf_conntrack_attach to attach related
915 ICMP/TCP RST packets in other direction. Actual packet
916 which created connection will be IP_CT_NEW or for an
917 expected connection, IP_CT_RELATED. */
918 if (CTINFO2DIR(ctinfo) != IP_CT_DIR_ORIGINAL)
921 zone = nf_ct_zone(ct);
925 sequence = read_seqcount_begin(&nf_conntrack_generation);
926 /* reuse the hash saved before */
927 hash = *(unsigned long *)&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev;
928 hash = scale_hash(hash);
929 reply_hash = hash_conntrack(net,
930 &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
932 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
934 /* We're not in hash table, and we refuse to set up related
935 * connections for unconfirmed conns. But packet copies and
936 * REJECT will give spurious warnings here.
939 /* Another skb with the same unconfirmed conntrack may
940 * win the race. This may happen for bridge(br_flood)
941 * or broadcast/multicast packets do skb_clone with
942 * unconfirmed conntrack.
944 if (unlikely(nf_ct_is_confirmed(ct))) {
946 nf_conntrack_double_unlock(hash, reply_hash);
951 pr_debug("Confirming conntrack %p\n", ct);
952 /* We have to check the DYING flag after unlink to prevent
953 * a race against nf_ct_get_next_corpse() possibly called from
954 * user context, else we insert an already 'dead' hash, blocking
955 * further use of that particular connection -JM.
957 nf_ct_del_from_dying_or_unconfirmed_list(ct);
959 if (unlikely(nf_ct_is_dying(ct))) {
960 nf_ct_add_to_dying_list(ct);
964 /* See if there's one in the list already, including reverse:
965 NAT could have grabbed it without realizing, since we're
966 not in the hash. If there is, we lost race. */
967 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode)
968 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
972 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode)
973 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
977 /* Timer relative to confirmation time, not original
978 setting time, otherwise we'd get timer wrap in
979 weird delay cases. */
980 ct->timeout += nfct_time_stamp;
981 atomic_inc(&ct->ct_general.use);
982 ct->status |= IPS_CONFIRMED;
984 /* set conntrack timestamp, if enabled. */
985 tstamp = nf_conn_tstamp_find(ct);
987 if (skb->tstamp == 0)
988 __net_timestamp(skb);
990 tstamp->start = ktime_to_ns(skb->tstamp);
992 /* Since the lookup is lockless, hash insertion must be done after
993 * starting the timer and setting the CONFIRMED bit. The RCU barriers
994 * guarantee that no other CPU can find the conntrack before the above
995 * stores are visible.
997 __nf_conntrack_hash_insert(ct, hash, reply_hash);
998 nf_conntrack_double_unlock(hash, reply_hash);
1001 help = nfct_help(ct);
1002 if (help && help->helper)
1003 nf_conntrack_event_cache(IPCT_HELPER, ct);
1005 nf_conntrack_event_cache(master_ct(ct) ?
1006 IPCT_RELATED : IPCT_NEW, ct);
1010 nf_ct_add_to_dying_list(ct);
1011 ret = nf_ct_resolve_clash(net, skb, ctinfo, h);
1013 nf_conntrack_double_unlock(hash, reply_hash);
1014 NF_CT_STAT_INC(net, insert_failed);
1018 EXPORT_SYMBOL_GPL(__nf_conntrack_confirm);
1020 /* Returns true if a connection correspondings to the tuple (required
1023 nf_conntrack_tuple_taken(const struct nf_conntrack_tuple *tuple,
1024 const struct nf_conn *ignored_conntrack)
1026 struct net *net = nf_ct_net(ignored_conntrack);
1027 const struct nf_conntrack_zone *zone;
1028 struct nf_conntrack_tuple_hash *h;
1029 struct hlist_nulls_head *ct_hash;
1030 unsigned int hash, hsize;
1031 struct hlist_nulls_node *n;
1034 zone = nf_ct_zone(ignored_conntrack);
1038 nf_conntrack_get_ht(&ct_hash, &hsize);
1039 hash = __hash_conntrack(net, tuple, hsize);
1041 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[hash], hnnode) {
1042 ct = nf_ct_tuplehash_to_ctrack(h);
1044 if (ct == ignored_conntrack)
1047 if (nf_ct_is_expired(ct)) {
1048 nf_ct_gc_expired(ct);
1052 if (nf_ct_key_equal(h, tuple, zone, net)) {
1053 /* Tuple is taken already, so caller will need to find
1054 * a new source port to use.
1057 * If the *original tuples* are identical, then both
1058 * conntracks refer to the same flow.
1059 * This is a rare situation, it can occur e.g. when
1060 * more than one UDP packet is sent from same socket
1061 * in different threads.
1063 * Let nf_ct_resolve_clash() deal with this later.
1065 if (nf_ct_tuple_equal(&ignored_conntrack->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
1066 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple))
1069 NF_CT_STAT_INC_ATOMIC(net, found);
1075 if (get_nulls_value(n) != hash) {
1076 NF_CT_STAT_INC_ATOMIC(net, search_restart);
1084 EXPORT_SYMBOL_GPL(nf_conntrack_tuple_taken);
1086 #define NF_CT_EVICTION_RANGE 8
1088 /* There's a small race here where we may free a just-assured
1089 connection. Too bad: we're in trouble anyway. */
1090 static unsigned int early_drop_list(struct net *net,
1091 struct hlist_nulls_head *head)
1093 struct nf_conntrack_tuple_hash *h;
1094 struct hlist_nulls_node *n;
1095 unsigned int drops = 0;
1096 struct nf_conn *tmp;
1098 hlist_nulls_for_each_entry_rcu(h, n, head, hnnode) {
1099 tmp = nf_ct_tuplehash_to_ctrack(h);
1101 if (test_bit(IPS_OFFLOAD_BIT, &tmp->status))
1104 if (nf_ct_is_expired(tmp)) {
1105 nf_ct_gc_expired(tmp);
1109 if (test_bit(IPS_ASSURED_BIT, &tmp->status) ||
1110 !net_eq(nf_ct_net(tmp), net) ||
1111 nf_ct_is_dying(tmp))
1114 if (!atomic_inc_not_zero(&tmp->ct_general.use))
1117 /* kill only if still in same netns -- might have moved due to
1118 * SLAB_TYPESAFE_BY_RCU rules.
1120 * We steal the timer reference. If that fails timer has
1121 * already fired or someone else deleted it. Just drop ref
1122 * and move to next entry.
1124 if (net_eq(nf_ct_net(tmp), net) &&
1125 nf_ct_is_confirmed(tmp) &&
1126 nf_ct_delete(tmp, 0, 0))
1135 static noinline int early_drop(struct net *net, unsigned int hash)
1137 unsigned int i, bucket;
1139 for (i = 0; i < NF_CT_EVICTION_RANGE; i++) {
1140 struct hlist_nulls_head *ct_hash;
1141 unsigned int hsize, drops;
1144 nf_conntrack_get_ht(&ct_hash, &hsize);
1146 bucket = reciprocal_scale(hash, hsize);
1148 bucket = (bucket + 1) % hsize;
1150 drops = early_drop_list(net, &ct_hash[bucket]);
1154 NF_CT_STAT_ADD_ATOMIC(net, early_drop, drops);
1162 static bool gc_worker_skip_ct(const struct nf_conn *ct)
1164 return !nf_ct_is_confirmed(ct) || nf_ct_is_dying(ct);
1167 static bool gc_worker_can_early_drop(const struct nf_conn *ct)
1169 const struct nf_conntrack_l4proto *l4proto;
1171 if (!test_bit(IPS_ASSURED_BIT, &ct->status))
1174 l4proto = nf_ct_l4proto_find(nf_ct_protonum(ct));
1175 if (l4proto->can_early_drop && l4proto->can_early_drop(ct))
1181 #define DAY (86400 * HZ)
1183 /* Set an arbitrary timeout large enough not to ever expire, this save
1184 * us a check for the IPS_OFFLOAD_BIT from the packet path via
1185 * nf_ct_is_expired().
1187 static void nf_ct_offload_timeout(struct nf_conn *ct)
1189 if (nf_ct_expires(ct) < DAY / 2)
1190 ct->timeout = nfct_time_stamp + DAY;
1193 static void gc_worker(struct work_struct *work)
1195 unsigned int min_interval = max(HZ / GC_MAX_BUCKETS_DIV, 1u);
1196 unsigned int i, goal, buckets = 0, expired_count = 0;
1197 unsigned int nf_conntrack_max95 = 0;
1198 struct conntrack_gc_work *gc_work;
1199 unsigned int ratio, scanned = 0;
1200 unsigned long next_run;
1202 gc_work = container_of(work, struct conntrack_gc_work, dwork.work);
1204 goal = nf_conntrack_htable_size / GC_MAX_BUCKETS_DIV;
1205 i = gc_work->last_bucket;
1206 if (gc_work->early_drop)
1207 nf_conntrack_max95 = nf_conntrack_max / 100u * 95u;
1210 struct nf_conntrack_tuple_hash *h;
1211 struct hlist_nulls_head *ct_hash;
1212 struct hlist_nulls_node *n;
1213 unsigned int hashsz;
1214 struct nf_conn *tmp;
1219 nf_conntrack_get_ht(&ct_hash, &hashsz);
1223 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[i], hnnode) {
1226 tmp = nf_ct_tuplehash_to_ctrack(h);
1229 if (test_bit(IPS_OFFLOAD_BIT, &tmp->status)) {
1230 nf_ct_offload_timeout(tmp);
1234 if (nf_ct_is_expired(tmp)) {
1235 nf_ct_gc_expired(tmp);
1240 if (nf_conntrack_max95 == 0 || gc_worker_skip_ct(tmp))
1243 net = nf_ct_net(tmp);
1244 if (atomic_read(&net->ct.count) < nf_conntrack_max95)
1247 /* need to take reference to avoid possible races */
1248 if (!atomic_inc_not_zero(&tmp->ct_general.use))
1251 if (gc_worker_skip_ct(tmp)) {
1256 if (gc_worker_can_early_drop(tmp))
1262 /* could check get_nulls_value() here and restart if ct
1263 * was moved to another chain. But given gc is best-effort
1264 * we will just continue with next hash slot.
1268 } while (++buckets < goal);
1270 if (gc_work->exiting)
1274 * Eviction will normally happen from the packet path, and not
1275 * from this gc worker.
1277 * This worker is only here to reap expired entries when system went
1278 * idle after a busy period.
1280 * The heuristics below are supposed to balance conflicting goals:
1282 * 1. Minimize time until we notice a stale entry
1283 * 2. Maximize scan intervals to not waste cycles
1285 * Normally, expire ratio will be close to 0.
1287 * As soon as a sizeable fraction of the entries have expired
1288 * increase scan frequency.
1290 ratio = scanned ? expired_count * 100 / scanned : 0;
1291 if (ratio > GC_EVICT_RATIO) {
1292 gc_work->next_gc_run = min_interval;
1294 unsigned int max = GC_MAX_SCAN_JIFFIES / GC_MAX_BUCKETS_DIV;
1296 BUILD_BUG_ON((GC_MAX_SCAN_JIFFIES / GC_MAX_BUCKETS_DIV) == 0);
1298 gc_work->next_gc_run += min_interval;
1299 if (gc_work->next_gc_run > max)
1300 gc_work->next_gc_run = max;
1303 next_run = gc_work->next_gc_run;
1304 gc_work->last_bucket = i;
1305 gc_work->early_drop = false;
1306 queue_delayed_work(system_power_efficient_wq, &gc_work->dwork, next_run);
1309 static void conntrack_gc_work_init(struct conntrack_gc_work *gc_work)
1311 INIT_DEFERRABLE_WORK(&gc_work->dwork, gc_worker);
1312 gc_work->next_gc_run = HZ;
1313 gc_work->exiting = false;
1316 static struct nf_conn *
1317 __nf_conntrack_alloc(struct net *net,
1318 const struct nf_conntrack_zone *zone,
1319 const struct nf_conntrack_tuple *orig,
1320 const struct nf_conntrack_tuple *repl,
1321 gfp_t gfp, u32 hash)
1325 /* We don't want any race condition at early drop stage */
1326 atomic_inc(&net->ct.count);
1328 if (nf_conntrack_max &&
1329 unlikely(atomic_read(&net->ct.count) > nf_conntrack_max)) {
1330 if (!early_drop(net, hash)) {
1331 if (!conntrack_gc_work.early_drop)
1332 conntrack_gc_work.early_drop = true;
1333 atomic_dec(&net->ct.count);
1334 net_warn_ratelimited("nf_conntrack: table full, dropping packet\n");
1335 return ERR_PTR(-ENOMEM);
1340 * Do not use kmem_cache_zalloc(), as this cache uses
1341 * SLAB_TYPESAFE_BY_RCU.
1343 ct = kmem_cache_alloc(nf_conntrack_cachep, gfp);
1347 spin_lock_init(&ct->lock);
1348 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple = *orig;
1349 ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode.pprev = NULL;
1350 ct->tuplehash[IP_CT_DIR_REPLY].tuple = *repl;
1351 /* save hash for reusing when confirming */
1352 *(unsigned long *)(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev) = hash;
1354 write_pnet(&ct->ct_net, net);
1355 memset(&ct->__nfct_init_offset[0], 0,
1356 offsetof(struct nf_conn, proto) -
1357 offsetof(struct nf_conn, __nfct_init_offset[0]));
1359 nf_ct_zone_add(ct, zone);
1361 /* Because we use RCU lookups, we set ct_general.use to zero before
1362 * this is inserted in any list.
1364 atomic_set(&ct->ct_general.use, 0);
1367 atomic_dec(&net->ct.count);
1368 return ERR_PTR(-ENOMEM);
1371 struct nf_conn *nf_conntrack_alloc(struct net *net,
1372 const struct nf_conntrack_zone *zone,
1373 const struct nf_conntrack_tuple *orig,
1374 const struct nf_conntrack_tuple *repl,
1377 return __nf_conntrack_alloc(net, zone, orig, repl, gfp, 0);
1379 EXPORT_SYMBOL_GPL(nf_conntrack_alloc);
1381 void nf_conntrack_free(struct nf_conn *ct)
1383 struct net *net = nf_ct_net(ct);
1385 /* A freed object has refcnt == 0, that's
1386 * the golden rule for SLAB_TYPESAFE_BY_RCU
1388 WARN_ON(atomic_read(&ct->ct_general.use) != 0);
1390 nf_ct_ext_destroy(ct);
1392 kmem_cache_free(nf_conntrack_cachep, ct);
1393 smp_mb__before_atomic();
1394 atomic_dec(&net->ct.count);
1396 EXPORT_SYMBOL_GPL(nf_conntrack_free);
1399 /* Allocate a new conntrack: we return -ENOMEM if classification
1400 failed due to stress. Otherwise it really is unclassifiable. */
1401 static noinline struct nf_conntrack_tuple_hash *
1402 init_conntrack(struct net *net, struct nf_conn *tmpl,
1403 const struct nf_conntrack_tuple *tuple,
1404 struct sk_buff *skb,
1405 unsigned int dataoff, u32 hash)
1408 struct nf_conn_help *help;
1409 struct nf_conntrack_tuple repl_tuple;
1410 struct nf_conntrack_ecache *ecache;
1411 struct nf_conntrack_expect *exp = NULL;
1412 const struct nf_conntrack_zone *zone;
1413 struct nf_conn_timeout *timeout_ext;
1414 struct nf_conntrack_zone tmp;
1416 if (!nf_ct_invert_tuple(&repl_tuple, tuple)) {
1417 pr_debug("Can't invert tuple.\n");
1421 zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1422 ct = __nf_conntrack_alloc(net, zone, tuple, &repl_tuple, GFP_ATOMIC,
1425 return (struct nf_conntrack_tuple_hash *)ct;
1427 if (!nf_ct_add_synproxy(ct, tmpl)) {
1428 nf_conntrack_free(ct);
1429 return ERR_PTR(-ENOMEM);
1432 timeout_ext = tmpl ? nf_ct_timeout_find(tmpl) : NULL;
1435 nf_ct_timeout_ext_add(ct, rcu_dereference(timeout_ext->timeout),
1438 nf_ct_acct_ext_add(ct, GFP_ATOMIC);
1439 nf_ct_tstamp_ext_add(ct, GFP_ATOMIC);
1440 nf_ct_labels_ext_add(ct);
1442 ecache = tmpl ? nf_ct_ecache_find(tmpl) : NULL;
1443 nf_ct_ecache_ext_add(ct, ecache ? ecache->ctmask : 0,
1444 ecache ? ecache->expmask : 0,
1448 if (net->ct.expect_count) {
1449 spin_lock(&nf_conntrack_expect_lock);
1450 exp = nf_ct_find_expectation(net, zone, tuple);
1452 pr_debug("expectation arrives ct=%p exp=%p\n",
1454 /* Welcome, Mr. Bond. We've been expecting you... */
1455 __set_bit(IPS_EXPECTED_BIT, &ct->status);
1456 /* exp->master safe, refcnt bumped in nf_ct_find_expectation */
1457 ct->master = exp->master;
1459 help = nf_ct_helper_ext_add(ct, GFP_ATOMIC);
1461 rcu_assign_pointer(help->helper, exp->helper);
1464 #ifdef CONFIG_NF_CONNTRACK_MARK
1465 ct->mark = exp->master->mark;
1467 #ifdef CONFIG_NF_CONNTRACK_SECMARK
1468 ct->secmark = exp->master->secmark;
1470 NF_CT_STAT_INC(net, expect_new);
1472 spin_unlock(&nf_conntrack_expect_lock);
1475 __nf_ct_try_assign_helper(ct, tmpl, GFP_ATOMIC);
1477 /* Now it is inserted into the unconfirmed list, bump refcount */
1478 nf_conntrack_get(&ct->ct_general);
1479 nf_ct_add_to_unconfirmed_list(ct);
1485 exp->expectfn(ct, exp);
1486 nf_ct_expect_put(exp);
1489 return &ct->tuplehash[IP_CT_DIR_ORIGINAL];
1492 /* On success, returns 0, sets skb->_nfct | ctinfo */
1494 resolve_normal_ct(struct nf_conn *tmpl,
1495 struct sk_buff *skb,
1496 unsigned int dataoff,
1498 const struct nf_hook_state *state)
1500 const struct nf_conntrack_zone *zone;
1501 struct nf_conntrack_tuple tuple;
1502 struct nf_conntrack_tuple_hash *h;
1503 enum ip_conntrack_info ctinfo;
1504 struct nf_conntrack_zone tmp;
1508 if (!nf_ct_get_tuple(skb, skb_network_offset(skb),
1509 dataoff, state->pf, protonum, state->net,
1511 pr_debug("Can't get tuple\n");
1515 /* look for tuple match */
1516 zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1517 hash = hash_conntrack_raw(&tuple, state->net);
1518 h = __nf_conntrack_find_get(state->net, zone, &tuple, hash);
1520 h = init_conntrack(state->net, tmpl, &tuple,
1521 skb, dataoff, hash);
1527 ct = nf_ct_tuplehash_to_ctrack(h);
1529 /* It exists; we have (non-exclusive) reference. */
1530 if (NF_CT_DIRECTION(h) == IP_CT_DIR_REPLY) {
1531 ctinfo = IP_CT_ESTABLISHED_REPLY;
1533 /* Once we've had two way comms, always ESTABLISHED. */
1534 if (test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) {
1535 pr_debug("normal packet for %p\n", ct);
1536 ctinfo = IP_CT_ESTABLISHED;
1537 } else if (test_bit(IPS_EXPECTED_BIT, &ct->status)) {
1538 pr_debug("related packet for %p\n", ct);
1539 ctinfo = IP_CT_RELATED;
1541 pr_debug("new packet for %p\n", ct);
1545 nf_ct_set(skb, ct, ctinfo);
1550 * icmp packets need special treatment to handle error messages that are
1551 * related to a connection.
1553 * Callers need to check if skb has a conntrack assigned when this
1554 * helper returns; in such case skb belongs to an already known connection.
1556 static unsigned int __cold
1557 nf_conntrack_handle_icmp(struct nf_conn *tmpl,
1558 struct sk_buff *skb,
1559 unsigned int dataoff,
1561 const struct nf_hook_state *state)
1565 if (state->pf == NFPROTO_IPV4 && protonum == IPPROTO_ICMP)
1566 ret = nf_conntrack_icmpv4_error(tmpl, skb, dataoff, state);
1567 #if IS_ENABLED(CONFIG_IPV6)
1568 else if (state->pf == NFPROTO_IPV6 && protonum == IPPROTO_ICMPV6)
1569 ret = nf_conntrack_icmpv6_error(tmpl, skb, dataoff, state);
1575 NF_CT_STAT_INC_ATOMIC(state->net, error);
1576 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1582 static int generic_packet(struct nf_conn *ct, struct sk_buff *skb,
1583 enum ip_conntrack_info ctinfo)
1585 const unsigned int *timeout = nf_ct_timeout_lookup(ct);
1588 timeout = &nf_generic_pernet(nf_ct_net(ct))->timeout;
1590 nf_ct_refresh_acct(ct, ctinfo, skb, *timeout);
1594 /* Returns verdict for packet, or -1 for invalid. */
1595 static int nf_conntrack_handle_packet(struct nf_conn *ct,
1596 struct sk_buff *skb,
1597 unsigned int dataoff,
1598 enum ip_conntrack_info ctinfo,
1599 const struct nf_hook_state *state)
1601 switch (nf_ct_protonum(ct)) {
1603 return nf_conntrack_tcp_packet(ct, skb, dataoff,
1606 return nf_conntrack_udp_packet(ct, skb, dataoff,
1609 return nf_conntrack_icmp_packet(ct, skb, ctinfo, state);
1610 #if IS_ENABLED(CONFIG_IPV6)
1611 case IPPROTO_ICMPV6:
1612 return nf_conntrack_icmpv6_packet(ct, skb, ctinfo, state);
1614 #ifdef CONFIG_NF_CT_PROTO_UDPLITE
1615 case IPPROTO_UDPLITE:
1616 return nf_conntrack_udplite_packet(ct, skb, dataoff,
1619 #ifdef CONFIG_NF_CT_PROTO_SCTP
1621 return nf_conntrack_sctp_packet(ct, skb, dataoff,
1624 #ifdef CONFIG_NF_CT_PROTO_DCCP
1626 return nf_conntrack_dccp_packet(ct, skb, dataoff,
1629 #ifdef CONFIG_NF_CT_PROTO_GRE
1631 return nf_conntrack_gre_packet(ct, skb, dataoff,
1636 return generic_packet(ct, skb, ctinfo);
1640 nf_conntrack_in(struct sk_buff *skb, const struct nf_hook_state *state)
1642 enum ip_conntrack_info ctinfo;
1643 struct nf_conn *ct, *tmpl;
1647 tmpl = nf_ct_get(skb, &ctinfo);
1648 if (tmpl || ctinfo == IP_CT_UNTRACKED) {
1649 /* Previously seen (loopback or untracked)? Ignore. */
1650 if ((tmpl && !nf_ct_is_template(tmpl)) ||
1651 ctinfo == IP_CT_UNTRACKED) {
1652 NF_CT_STAT_INC_ATOMIC(state->net, ignore);
1658 /* rcu_read_lock()ed by nf_hook_thresh */
1659 dataoff = get_l4proto(skb, skb_network_offset(skb), state->pf, &protonum);
1661 pr_debug("not prepared to track yet or error occurred\n");
1662 NF_CT_STAT_INC_ATOMIC(state->net, error);
1663 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1668 if (protonum == IPPROTO_ICMP || protonum == IPPROTO_ICMPV6) {
1669 ret = nf_conntrack_handle_icmp(tmpl, skb, dataoff,
1675 /* ICMP[v6] protocol trackers may assign one conntrack. */
1680 ret = resolve_normal_ct(tmpl, skb, dataoff,
1683 /* Too stressed to deal. */
1684 NF_CT_STAT_INC_ATOMIC(state->net, drop);
1689 ct = nf_ct_get(skb, &ctinfo);
1691 /* Not valid part of a connection */
1692 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1697 ret = nf_conntrack_handle_packet(ct, skb, dataoff, ctinfo, state);
1699 /* Invalid: inverse of the return code tells
1700 * the netfilter core what to do */
1701 pr_debug("nf_conntrack_in: Can't track with proto module\n");
1702 nf_conntrack_put(&ct->ct_general);
1704 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1705 if (ret == -NF_DROP)
1706 NF_CT_STAT_INC_ATOMIC(state->net, drop);
1707 /* Special case: TCP tracker reports an attempt to reopen a
1708 * closed/aborted connection. We have to go back and create a
1711 if (ret == -NF_REPEAT)
1717 if (ctinfo == IP_CT_ESTABLISHED_REPLY &&
1718 !test_and_set_bit(IPS_SEEN_REPLY_BIT, &ct->status))
1719 nf_conntrack_event_cache(IPCT_REPLY, ct);
1726 EXPORT_SYMBOL_GPL(nf_conntrack_in);
1728 /* Alter reply tuple (maybe alter helper). This is for NAT, and is
1729 implicitly racy: see __nf_conntrack_confirm */
1730 void nf_conntrack_alter_reply(struct nf_conn *ct,
1731 const struct nf_conntrack_tuple *newreply)
1733 struct nf_conn_help *help = nfct_help(ct);
1735 /* Should be unconfirmed, so not in hash table yet */
1736 WARN_ON(nf_ct_is_confirmed(ct));
1738 pr_debug("Altering reply tuple of %p to ", ct);
1739 nf_ct_dump_tuple(newreply);
1741 ct->tuplehash[IP_CT_DIR_REPLY].tuple = *newreply;
1742 if (ct->master || (help && !hlist_empty(&help->expectations)))
1746 __nf_ct_try_assign_helper(ct, NULL, GFP_ATOMIC);
1749 EXPORT_SYMBOL_GPL(nf_conntrack_alter_reply);
1751 /* Refresh conntrack for this many jiffies and do accounting if do_acct is 1 */
1752 void __nf_ct_refresh_acct(struct nf_conn *ct,
1753 enum ip_conntrack_info ctinfo,
1754 const struct sk_buff *skb,
1755 unsigned long extra_jiffies,
1760 /* Only update if this is not a fixed timeout */
1761 if (test_bit(IPS_FIXED_TIMEOUT_BIT, &ct->status))
1764 /* If not in hash table, timer will not be active yet */
1765 if (nf_ct_is_confirmed(ct))
1766 extra_jiffies += nfct_time_stamp;
1768 ct->timeout = extra_jiffies;
1771 nf_ct_acct_update(ct, ctinfo, skb->len);
1773 EXPORT_SYMBOL_GPL(__nf_ct_refresh_acct);
1775 bool nf_ct_kill_acct(struct nf_conn *ct,
1776 enum ip_conntrack_info ctinfo,
1777 const struct sk_buff *skb)
1779 nf_ct_acct_update(ct, ctinfo, skb->len);
1781 return nf_ct_delete(ct, 0, 0);
1783 EXPORT_SYMBOL_GPL(nf_ct_kill_acct);
1785 #if IS_ENABLED(CONFIG_NF_CT_NETLINK)
1787 #include <linux/netfilter/nfnetlink.h>
1788 #include <linux/netfilter/nfnetlink_conntrack.h>
1789 #include <linux/mutex.h>
1791 /* Generic function for tcp/udp/sctp/dccp and alike. This needs to be
1792 * in ip_conntrack_core, since we don't want the protocols to autoload
1793 * or depend on ctnetlink */
1794 int nf_ct_port_tuple_to_nlattr(struct sk_buff *skb,
1795 const struct nf_conntrack_tuple *tuple)
1797 if (nla_put_be16(skb, CTA_PROTO_SRC_PORT, tuple->src.u.tcp.port) ||
1798 nla_put_be16(skb, CTA_PROTO_DST_PORT, tuple->dst.u.tcp.port))
1799 goto nla_put_failure;
1805 EXPORT_SYMBOL_GPL(nf_ct_port_tuple_to_nlattr);
1807 const struct nla_policy nf_ct_port_nla_policy[CTA_PROTO_MAX+1] = {
1808 [CTA_PROTO_SRC_PORT] = { .type = NLA_U16 },
1809 [CTA_PROTO_DST_PORT] = { .type = NLA_U16 },
1811 EXPORT_SYMBOL_GPL(nf_ct_port_nla_policy);
1813 int nf_ct_port_nlattr_to_tuple(struct nlattr *tb[],
1814 struct nf_conntrack_tuple *t)
1816 if (!tb[CTA_PROTO_SRC_PORT] || !tb[CTA_PROTO_DST_PORT])
1819 t->src.u.tcp.port = nla_get_be16(tb[CTA_PROTO_SRC_PORT]);
1820 t->dst.u.tcp.port = nla_get_be16(tb[CTA_PROTO_DST_PORT]);
1824 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_to_tuple);
1826 unsigned int nf_ct_port_nlattr_tuple_size(void)
1828 static unsigned int size __read_mostly;
1831 size = nla_policy_len(nf_ct_port_nla_policy, CTA_PROTO_MAX + 1);
1835 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_tuple_size);
1838 /* Used by ipt_REJECT and ip6t_REJECT. */
1839 static void nf_conntrack_attach(struct sk_buff *nskb, const struct sk_buff *skb)
1842 enum ip_conntrack_info ctinfo;
1844 /* This ICMP is in reverse direction to the packet which caused it */
1845 ct = nf_ct_get(skb, &ctinfo);
1846 if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL)
1847 ctinfo = IP_CT_RELATED_REPLY;
1849 ctinfo = IP_CT_RELATED;
1851 /* Attach to new skbuff, and increment count */
1852 nf_ct_set(nskb, ct, ctinfo);
1853 nf_conntrack_get(skb_nfct(nskb));
1856 static int nf_conntrack_update(struct net *net, struct sk_buff *skb)
1858 struct nf_conntrack_tuple_hash *h;
1859 struct nf_conntrack_tuple tuple;
1860 enum ip_conntrack_info ctinfo;
1861 struct nf_nat_hook *nat_hook;
1862 unsigned int status;
1868 ct = nf_ct_get(skb, &ctinfo);
1869 if (!ct || nf_ct_is_confirmed(ct))
1872 l3num = nf_ct_l3num(ct);
1874 dataoff = get_l4proto(skb, skb_network_offset(skb), l3num, &l4num);
1878 if (!nf_ct_get_tuple(skb, skb_network_offset(skb), dataoff, l3num,
1879 l4num, net, &tuple))
1882 if (ct->status & IPS_SRC_NAT) {
1883 memcpy(tuple.src.u3.all,
1884 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u3.all,
1885 sizeof(tuple.src.u3.all));
1887 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u.all;
1890 if (ct->status & IPS_DST_NAT) {
1891 memcpy(tuple.dst.u3.all,
1892 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.u3.all,
1893 sizeof(tuple.dst.u3.all));
1895 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.u.all;
1898 h = nf_conntrack_find_get(net, nf_ct_zone(ct), &tuple);
1902 /* Store status bits of the conntrack that is clashing to re-do NAT
1903 * mangling according to what it has been done already to this packet.
1905 status = ct->status;
1908 ct = nf_ct_tuplehash_to_ctrack(h);
1909 nf_ct_set(skb, ct, ctinfo);
1911 nat_hook = rcu_dereference(nf_nat_hook);
1915 if (status & IPS_SRC_NAT &&
1916 nat_hook->manip_pkt(skb, ct, NF_NAT_MANIP_SRC,
1917 IP_CT_DIR_ORIGINAL) == NF_DROP)
1920 if (status & IPS_DST_NAT &&
1921 nat_hook->manip_pkt(skb, ct, NF_NAT_MANIP_DST,
1922 IP_CT_DIR_ORIGINAL) == NF_DROP)
1928 static bool nf_conntrack_get_tuple_skb(struct nf_conntrack_tuple *dst_tuple,
1929 const struct sk_buff *skb)
1931 const struct nf_conntrack_tuple *src_tuple;
1932 const struct nf_conntrack_tuple_hash *hash;
1933 struct nf_conntrack_tuple srctuple;
1934 enum ip_conntrack_info ctinfo;
1937 ct = nf_ct_get(skb, &ctinfo);
1939 src_tuple = nf_ct_tuple(ct, CTINFO2DIR(ctinfo));
1940 memcpy(dst_tuple, src_tuple, sizeof(*dst_tuple));
1944 if (!nf_ct_get_tuplepr(skb, skb_network_offset(skb),
1945 NFPROTO_IPV4, dev_net(skb->dev),
1949 hash = nf_conntrack_find_get(dev_net(skb->dev),
1955 ct = nf_ct_tuplehash_to_ctrack(hash);
1956 src_tuple = nf_ct_tuple(ct, !hash->tuple.dst.dir);
1957 memcpy(dst_tuple, src_tuple, sizeof(*dst_tuple));
1963 /* Bring out ya dead! */
1964 static struct nf_conn *
1965 get_next_corpse(int (*iter)(struct nf_conn *i, void *data),
1966 void *data, unsigned int *bucket)
1968 struct nf_conntrack_tuple_hash *h;
1970 struct hlist_nulls_node *n;
1973 for (; *bucket < nf_conntrack_htable_size; (*bucket)++) {
1974 lockp = &nf_conntrack_locks[*bucket % CONNTRACK_LOCKS];
1976 nf_conntrack_lock(lockp);
1977 if (*bucket < nf_conntrack_htable_size) {
1978 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[*bucket], hnnode) {
1979 if (NF_CT_DIRECTION(h) != IP_CT_DIR_ORIGINAL)
1981 ct = nf_ct_tuplehash_to_ctrack(h);
1993 atomic_inc(&ct->ct_general.use);
1999 static void nf_ct_iterate_cleanup(int (*iter)(struct nf_conn *i, void *data),
2000 void *data, u32 portid, int report)
2002 unsigned int bucket = 0, sequence;
2008 sequence = read_seqcount_begin(&nf_conntrack_generation);
2010 while ((ct = get_next_corpse(iter, data, &bucket)) != NULL) {
2011 /* Time to push up daises... */
2013 nf_ct_delete(ct, portid, report);
2018 if (!read_seqcount_retry(&nf_conntrack_generation, sequence))
2025 int (*iter)(struct nf_conn *i, void *data);
2030 static int iter_net_only(struct nf_conn *i, void *data)
2032 struct iter_data *d = data;
2034 if (!net_eq(d->net, nf_ct_net(i)))
2037 return d->iter(i, d->data);
2041 __nf_ct_unconfirmed_destroy(struct net *net)
2045 for_each_possible_cpu(cpu) {
2046 struct nf_conntrack_tuple_hash *h;
2047 struct hlist_nulls_node *n;
2048 struct ct_pcpu *pcpu;
2050 pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
2052 spin_lock_bh(&pcpu->lock);
2053 hlist_nulls_for_each_entry(h, n, &pcpu->unconfirmed, hnnode) {
2056 ct = nf_ct_tuplehash_to_ctrack(h);
2058 /* we cannot call iter() on unconfirmed list, the
2059 * owning cpu can reallocate ct->ext at any time.
2061 set_bit(IPS_DYING_BIT, &ct->status);
2063 spin_unlock_bh(&pcpu->lock);
2068 void nf_ct_unconfirmed_destroy(struct net *net)
2072 if (atomic_read(&net->ct.count) > 0) {
2073 __nf_ct_unconfirmed_destroy(net);
2074 nf_queue_nf_hook_drop(net);
2078 EXPORT_SYMBOL_GPL(nf_ct_unconfirmed_destroy);
2080 void nf_ct_iterate_cleanup_net(struct net *net,
2081 int (*iter)(struct nf_conn *i, void *data),
2082 void *data, u32 portid, int report)
2088 if (atomic_read(&net->ct.count) == 0)
2095 nf_ct_iterate_cleanup(iter_net_only, &d, portid, report);
2097 EXPORT_SYMBOL_GPL(nf_ct_iterate_cleanup_net);
2100 * nf_ct_iterate_destroy - destroy unconfirmed conntracks and iterate table
2101 * @iter: callback to invoke for each conntrack
2102 * @data: data to pass to @iter
2104 * Like nf_ct_iterate_cleanup, but first marks conntracks on the
2105 * unconfirmed list as dying (so they will not be inserted into
2108 * Can only be called in module exit path.
2111 nf_ct_iterate_destroy(int (*iter)(struct nf_conn *i, void *data), void *data)
2115 down_read(&net_rwsem);
2117 if (atomic_read(&net->ct.count) == 0)
2119 __nf_ct_unconfirmed_destroy(net);
2120 nf_queue_nf_hook_drop(net);
2122 up_read(&net_rwsem);
2124 /* Need to wait for netns cleanup worker to finish, if its
2125 * running -- it might have deleted a net namespace from
2126 * the global list, so our __nf_ct_unconfirmed_destroy() might
2127 * not have affected all namespaces.
2131 /* a conntrack could have been unlinked from unconfirmed list
2132 * before we grabbed pcpu lock in __nf_ct_unconfirmed_destroy().
2133 * This makes sure its inserted into conntrack table.
2137 nf_ct_iterate_cleanup(iter, data, 0, 0);
2139 EXPORT_SYMBOL_GPL(nf_ct_iterate_destroy);
2141 static int kill_all(struct nf_conn *i, void *data)
2143 return net_eq(nf_ct_net(i), data);
2146 void nf_conntrack_cleanup_start(void)
2148 conntrack_gc_work.exiting = true;
2149 RCU_INIT_POINTER(ip_ct_attach, NULL);
2152 void nf_conntrack_cleanup_end(void)
2154 RCU_INIT_POINTER(nf_ct_hook, NULL);
2155 cancel_delayed_work_sync(&conntrack_gc_work.dwork);
2156 kvfree(nf_conntrack_hash);
2158 nf_conntrack_proto_fini();
2159 nf_conntrack_seqadj_fini();
2160 nf_conntrack_labels_fini();
2161 nf_conntrack_helper_fini();
2162 nf_conntrack_timeout_fini();
2163 nf_conntrack_ecache_fini();
2164 nf_conntrack_tstamp_fini();
2165 nf_conntrack_acct_fini();
2166 nf_conntrack_expect_fini();
2168 kmem_cache_destroy(nf_conntrack_cachep);
2172 * Mishearing the voices in his head, our hero wonders how he's
2173 * supposed to kill the mall.
2175 void nf_conntrack_cleanup_net(struct net *net)
2179 list_add(&net->exit_list, &single);
2180 nf_conntrack_cleanup_net_list(&single);
2183 void nf_conntrack_cleanup_net_list(struct list_head *net_exit_list)
2189 * This makes sure all current packets have passed through
2190 * netfilter framework. Roll on, two-stage module
2196 list_for_each_entry(net, net_exit_list, exit_list) {
2197 nf_ct_iterate_cleanup(kill_all, net, 0, 0);
2198 if (atomic_read(&net->ct.count) != 0)
2203 goto i_see_dead_people;
2206 list_for_each_entry(net, net_exit_list, exit_list) {
2207 nf_conntrack_proto_pernet_fini(net);
2208 nf_conntrack_ecache_pernet_fini(net);
2209 nf_conntrack_expect_pernet_fini(net);
2210 free_percpu(net->ct.stat);
2211 free_percpu(net->ct.pcpu_lists);
2215 void *nf_ct_alloc_hashtable(unsigned int *sizep, int nulls)
2217 struct hlist_nulls_head *hash;
2218 unsigned int nr_slots, i;
2220 if (*sizep > (UINT_MAX / sizeof(struct hlist_nulls_head)))
2223 BUILD_BUG_ON(sizeof(struct hlist_nulls_head) != sizeof(struct hlist_head));
2224 nr_slots = *sizep = roundup(*sizep, PAGE_SIZE / sizeof(struct hlist_nulls_head));
2226 hash = kvmalloc_array(nr_slots, sizeof(struct hlist_nulls_head),
2227 GFP_KERNEL | __GFP_ZERO);
2230 for (i = 0; i < nr_slots; i++)
2231 INIT_HLIST_NULLS_HEAD(&hash[i], i);
2235 EXPORT_SYMBOL_GPL(nf_ct_alloc_hashtable);
2237 int nf_conntrack_hash_resize(unsigned int hashsize)
2240 unsigned int old_size;
2241 struct hlist_nulls_head *hash, *old_hash;
2242 struct nf_conntrack_tuple_hash *h;
2248 hash = nf_ct_alloc_hashtable(&hashsize, 1);
2252 old_size = nf_conntrack_htable_size;
2253 if (old_size == hashsize) {
2259 nf_conntrack_all_lock();
2260 write_seqcount_begin(&nf_conntrack_generation);
2262 /* Lookups in the old hash might happen in parallel, which means we
2263 * might get false negatives during connection lookup. New connections
2264 * created because of a false negative won't make it into the hash
2265 * though since that required taking the locks.
2268 for (i = 0; i < nf_conntrack_htable_size; i++) {
2269 while (!hlist_nulls_empty(&nf_conntrack_hash[i])) {
2270 h = hlist_nulls_entry(nf_conntrack_hash[i].first,
2271 struct nf_conntrack_tuple_hash, hnnode);
2272 ct = nf_ct_tuplehash_to_ctrack(h);
2273 hlist_nulls_del_rcu(&h->hnnode);
2274 bucket = __hash_conntrack(nf_ct_net(ct),
2275 &h->tuple, hashsize);
2276 hlist_nulls_add_head_rcu(&h->hnnode, &hash[bucket]);
2279 old_size = nf_conntrack_htable_size;
2280 old_hash = nf_conntrack_hash;
2282 nf_conntrack_hash = hash;
2283 nf_conntrack_htable_size = hashsize;
2285 write_seqcount_end(&nf_conntrack_generation);
2286 nf_conntrack_all_unlock();
2294 int nf_conntrack_set_hashsize(const char *val, const struct kernel_param *kp)
2296 unsigned int hashsize;
2299 if (current->nsproxy->net_ns != &init_net)
2302 /* On boot, we can set this without any fancy locking. */
2303 if (!nf_conntrack_hash)
2304 return param_set_uint(val, kp);
2306 rc = kstrtouint(val, 0, &hashsize);
2310 return nf_conntrack_hash_resize(hashsize);
2312 EXPORT_SYMBOL_GPL(nf_conntrack_set_hashsize);
2314 static __always_inline unsigned int total_extension_size(void)
2316 /* remember to add new extensions below */
2317 BUILD_BUG_ON(NF_CT_EXT_NUM > 9);
2319 return sizeof(struct nf_ct_ext) +
2320 sizeof(struct nf_conn_help)
2321 #if IS_ENABLED(CONFIG_NF_NAT)
2322 + sizeof(struct nf_conn_nat)
2324 + sizeof(struct nf_conn_seqadj)
2325 + sizeof(struct nf_conn_acct)
2326 #ifdef CONFIG_NF_CONNTRACK_EVENTS
2327 + sizeof(struct nf_conntrack_ecache)
2329 #ifdef CONFIG_NF_CONNTRACK_TIMESTAMP
2330 + sizeof(struct nf_conn_tstamp)
2332 #ifdef CONFIG_NF_CONNTRACK_TIMEOUT
2333 + sizeof(struct nf_conn_timeout)
2335 #ifdef CONFIG_NF_CONNTRACK_LABELS
2336 + sizeof(struct nf_conn_labels)
2338 #if IS_ENABLED(CONFIG_NETFILTER_SYNPROXY)
2339 + sizeof(struct nf_conn_synproxy)
2344 int nf_conntrack_init_start(void)
2346 unsigned long nr_pages = totalram_pages();
2351 /* struct nf_ct_ext uses u8 to store offsets/size */
2352 BUILD_BUG_ON(total_extension_size() > 255u);
2354 seqcount_init(&nf_conntrack_generation);
2356 for (i = 0; i < CONNTRACK_LOCKS; i++)
2357 spin_lock_init(&nf_conntrack_locks[i]);
2359 if (!nf_conntrack_htable_size) {
2360 /* Idea from tcp.c: use 1/16384 of memory.
2361 * On i386: 32MB machine has 512 buckets.
2362 * >= 1GB machines have 16384 buckets.
2363 * >= 4GB machines have 65536 buckets.
2365 nf_conntrack_htable_size
2366 = (((nr_pages << PAGE_SHIFT) / 16384)
2367 / sizeof(struct hlist_head));
2368 if (nr_pages > (4 * (1024 * 1024 * 1024 / PAGE_SIZE)))
2369 nf_conntrack_htable_size = 65536;
2370 else if (nr_pages > (1024 * 1024 * 1024 / PAGE_SIZE))
2371 nf_conntrack_htable_size = 16384;
2372 if (nf_conntrack_htable_size < 32)
2373 nf_conntrack_htable_size = 32;
2375 /* Use a max. factor of four by default to get the same max as
2376 * with the old struct list_heads. When a table size is given
2377 * we use the old value of 8 to avoid reducing the max.
2382 nf_conntrack_hash = nf_ct_alloc_hashtable(&nf_conntrack_htable_size, 1);
2383 if (!nf_conntrack_hash)
2386 nf_conntrack_max = max_factor * nf_conntrack_htable_size;
2388 nf_conntrack_cachep = kmem_cache_create("nf_conntrack",
2389 sizeof(struct nf_conn),
2391 SLAB_TYPESAFE_BY_RCU | SLAB_HWCACHE_ALIGN, NULL);
2392 if (!nf_conntrack_cachep)
2395 ret = nf_conntrack_expect_init();
2399 ret = nf_conntrack_acct_init();
2403 ret = nf_conntrack_tstamp_init();
2407 ret = nf_conntrack_ecache_init();
2411 ret = nf_conntrack_timeout_init();
2415 ret = nf_conntrack_helper_init();
2419 ret = nf_conntrack_labels_init();
2423 ret = nf_conntrack_seqadj_init();
2427 ret = nf_conntrack_proto_init();
2431 conntrack_gc_work_init(&conntrack_gc_work);
2432 queue_delayed_work(system_power_efficient_wq, &conntrack_gc_work.dwork, HZ);
2437 nf_conntrack_seqadj_fini();
2439 nf_conntrack_labels_fini();
2441 nf_conntrack_helper_fini();
2443 nf_conntrack_timeout_fini();
2445 nf_conntrack_ecache_fini();
2447 nf_conntrack_tstamp_fini();
2449 nf_conntrack_acct_fini();
2451 nf_conntrack_expect_fini();
2453 kmem_cache_destroy(nf_conntrack_cachep);
2455 kvfree(nf_conntrack_hash);
2459 static struct nf_ct_hook nf_conntrack_hook = {
2460 .update = nf_conntrack_update,
2461 .destroy = destroy_conntrack,
2462 .get_tuple_skb = nf_conntrack_get_tuple_skb,
2465 void nf_conntrack_init_end(void)
2467 /* For use by REJECT target */
2468 RCU_INIT_POINTER(ip_ct_attach, nf_conntrack_attach);
2469 RCU_INIT_POINTER(nf_ct_hook, &nf_conntrack_hook);
2473 * We need to use special "null" values, not used in hash table
2475 #define UNCONFIRMED_NULLS_VAL ((1<<30)+0)
2476 #define DYING_NULLS_VAL ((1<<30)+1)
2477 #define TEMPLATE_NULLS_VAL ((1<<30)+2)
2479 int nf_conntrack_init_net(struct net *net)
2484 BUILD_BUG_ON(IP_CT_UNTRACKED == IP_CT_NUMBER);
2485 atomic_set(&net->ct.count, 0);
2487 net->ct.pcpu_lists = alloc_percpu(struct ct_pcpu);
2488 if (!net->ct.pcpu_lists)
2491 for_each_possible_cpu(cpu) {
2492 struct ct_pcpu *pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
2494 spin_lock_init(&pcpu->lock);
2495 INIT_HLIST_NULLS_HEAD(&pcpu->unconfirmed, UNCONFIRMED_NULLS_VAL);
2496 INIT_HLIST_NULLS_HEAD(&pcpu->dying, DYING_NULLS_VAL);
2499 net->ct.stat = alloc_percpu(struct ip_conntrack_stat);
2501 goto err_pcpu_lists;
2503 ret = nf_conntrack_expect_pernet_init(net);
2507 nf_conntrack_acct_pernet_init(net);
2508 nf_conntrack_tstamp_pernet_init(net);
2509 nf_conntrack_ecache_pernet_init(net);
2510 nf_conntrack_helper_pernet_init(net);
2511 nf_conntrack_proto_pernet_init(net);
2516 free_percpu(net->ct.stat);
2518 free_percpu(net->ct.pcpu_lists);