1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Connection state tracking for netfilter. This is separated from,
3 but required by, the NAT layer; it can also be used by an iptables
6 /* (C) 1999-2001 Paul `Rusty' Russell
7 * (C) 2002-2006 Netfilter Core Team <coreteam@netfilter.org>
8 * (C) 2003,2004 USAGI/WIDE Project <http://www.linux-ipv6.org>
9 * (C) 2005-2012 Patrick McHardy <kaber@trash.net>
12 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
14 #include <linux/types.h>
15 #include <linux/netfilter.h>
16 #include <linux/module.h>
17 #include <linux/sched.h>
18 #include <linux/skbuff.h>
19 #include <linux/proc_fs.h>
20 #include <linux/vmalloc.h>
21 #include <linux/stddef.h>
22 #include <linux/slab.h>
23 #include <linux/random.h>
24 #include <linux/jhash.h>
25 #include <linux/siphash.h>
26 #include <linux/err.h>
27 #include <linux/percpu.h>
28 #include <linux/moduleparam.h>
29 #include <linux/notifier.h>
30 #include <linux/kernel.h>
31 #include <linux/netdevice.h>
32 #include <linux/socket.h>
34 #include <linux/nsproxy.h>
35 #include <linux/rculist_nulls.h>
37 #include <net/netfilter/nf_conntrack.h>
38 #include <net/netfilter/nf_conntrack_l4proto.h>
39 #include <net/netfilter/nf_conntrack_expect.h>
40 #include <net/netfilter/nf_conntrack_helper.h>
41 #include <net/netfilter/nf_conntrack_seqadj.h>
42 #include <net/netfilter/nf_conntrack_core.h>
43 #include <net/netfilter/nf_conntrack_extend.h>
44 #include <net/netfilter/nf_conntrack_acct.h>
45 #include <net/netfilter/nf_conntrack_ecache.h>
46 #include <net/netfilter/nf_conntrack_zones.h>
47 #include <net/netfilter/nf_conntrack_timestamp.h>
48 #include <net/netfilter/nf_conntrack_timeout.h>
49 #include <net/netfilter/nf_conntrack_labels.h>
50 #include <net/netfilter/nf_conntrack_synproxy.h>
51 #include <net/netfilter/nf_nat.h>
52 #include <net/netfilter/nf_nat_helper.h>
53 #include <net/netns/hash.h>
56 #include "nf_internals.h"
58 __cacheline_aligned_in_smp spinlock_t nf_conntrack_locks[CONNTRACK_LOCKS];
59 EXPORT_SYMBOL_GPL(nf_conntrack_locks);
61 __cacheline_aligned_in_smp DEFINE_SPINLOCK(nf_conntrack_expect_lock);
62 EXPORT_SYMBOL_GPL(nf_conntrack_expect_lock);
64 struct hlist_nulls_head *nf_conntrack_hash __read_mostly;
65 EXPORT_SYMBOL_GPL(nf_conntrack_hash);
67 struct conntrack_gc_work {
68 struct delayed_work dwork;
75 static __read_mostly struct kmem_cache *nf_conntrack_cachep;
76 static __read_mostly spinlock_t nf_conntrack_locks_all_lock;
77 static __read_mostly DEFINE_SPINLOCK(nf_conntrack_locks_all_lock);
78 static __read_mostly bool nf_conntrack_locks_all;
80 /* every gc cycle scans at most 1/GC_MAX_BUCKETS_DIV part of table */
81 #define GC_MAX_BUCKETS_DIV 128u
82 /* upper bound of full table scan */
83 #define GC_MAX_SCAN_JIFFIES (16u * HZ)
84 /* desired ratio of entries found to be expired */
85 #define GC_EVICT_RATIO 50u
87 static struct conntrack_gc_work conntrack_gc_work;
89 void nf_conntrack_lock(spinlock_t *lock) __acquires(lock)
91 /* 1) Acquire the lock */
94 /* 2) read nf_conntrack_locks_all, with ACQUIRE semantics
95 * It pairs with the smp_store_release() in nf_conntrack_all_unlock()
97 if (likely(smp_load_acquire(&nf_conntrack_locks_all) == false))
100 /* fast path failed, unlock */
103 /* Slow path 1) get global lock */
104 spin_lock(&nf_conntrack_locks_all_lock);
106 /* Slow path 2) get the lock we want */
109 /* Slow path 3) release the global lock */
110 spin_unlock(&nf_conntrack_locks_all_lock);
112 EXPORT_SYMBOL_GPL(nf_conntrack_lock);
114 static void nf_conntrack_double_unlock(unsigned int h1, unsigned int h2)
116 h1 %= CONNTRACK_LOCKS;
117 h2 %= CONNTRACK_LOCKS;
118 spin_unlock(&nf_conntrack_locks[h1]);
120 spin_unlock(&nf_conntrack_locks[h2]);
123 /* return true if we need to recompute hashes (in case hash table was resized) */
124 static bool nf_conntrack_double_lock(struct net *net, unsigned int h1,
125 unsigned int h2, unsigned int sequence)
127 h1 %= CONNTRACK_LOCKS;
128 h2 %= CONNTRACK_LOCKS;
130 nf_conntrack_lock(&nf_conntrack_locks[h1]);
132 spin_lock_nested(&nf_conntrack_locks[h2],
133 SINGLE_DEPTH_NESTING);
135 nf_conntrack_lock(&nf_conntrack_locks[h2]);
136 spin_lock_nested(&nf_conntrack_locks[h1],
137 SINGLE_DEPTH_NESTING);
139 if (read_seqcount_retry(&nf_conntrack_generation, sequence)) {
140 nf_conntrack_double_unlock(h1, h2);
146 static void nf_conntrack_all_lock(void)
150 spin_lock(&nf_conntrack_locks_all_lock);
152 nf_conntrack_locks_all = true;
154 for (i = 0; i < CONNTRACK_LOCKS; i++) {
155 spin_lock(&nf_conntrack_locks[i]);
157 /* This spin_unlock provides the "release" to ensure that
158 * nf_conntrack_locks_all==true is visible to everyone that
159 * acquired spin_lock(&nf_conntrack_locks[]).
161 spin_unlock(&nf_conntrack_locks[i]);
165 static void nf_conntrack_all_unlock(void)
167 /* All prior stores must be complete before we clear
168 * 'nf_conntrack_locks_all'. Otherwise nf_conntrack_lock()
169 * might observe the false value but not the entire
171 * It pairs with the smp_load_acquire() in nf_conntrack_lock()
173 smp_store_release(&nf_conntrack_locks_all, false);
174 spin_unlock(&nf_conntrack_locks_all_lock);
177 unsigned int nf_conntrack_htable_size __read_mostly;
178 EXPORT_SYMBOL_GPL(nf_conntrack_htable_size);
180 unsigned int nf_conntrack_max __read_mostly;
181 EXPORT_SYMBOL_GPL(nf_conntrack_max);
182 seqcount_t nf_conntrack_generation __read_mostly;
183 static unsigned int nf_conntrack_hash_rnd __read_mostly;
185 static u32 hash_conntrack_raw(const struct nf_conntrack_tuple *tuple,
186 const struct net *net)
191 get_random_once(&nf_conntrack_hash_rnd, sizeof(nf_conntrack_hash_rnd));
193 /* The direction must be ignored, so we hash everything up to the
194 * destination ports (which is a multiple of 4) and treat the last
195 * three bytes manually.
197 seed = nf_conntrack_hash_rnd ^ net_hash_mix(net);
198 n = (sizeof(tuple->src) + sizeof(tuple->dst.u3)) / sizeof(u32);
199 return jhash2((u32 *)tuple, n, seed ^
200 (((__force __u16)tuple->dst.u.all << 16) |
201 tuple->dst.protonum));
204 static u32 scale_hash(u32 hash)
206 return reciprocal_scale(hash, nf_conntrack_htable_size);
209 static u32 __hash_conntrack(const struct net *net,
210 const struct nf_conntrack_tuple *tuple,
213 return reciprocal_scale(hash_conntrack_raw(tuple, net), size);
216 static u32 hash_conntrack(const struct net *net,
217 const struct nf_conntrack_tuple *tuple)
219 return scale_hash(hash_conntrack_raw(tuple, net));
222 static bool nf_ct_get_tuple_ports(const struct sk_buff *skb,
223 unsigned int dataoff,
224 struct nf_conntrack_tuple *tuple)
228 } _inet_hdr, *inet_hdr;
230 /* Actually only need first 4 bytes to get ports. */
231 inet_hdr = skb_header_pointer(skb, dataoff, sizeof(_inet_hdr), &_inet_hdr);
235 tuple->src.u.udp.port = inet_hdr->sport;
236 tuple->dst.u.udp.port = inet_hdr->dport;
241 nf_ct_get_tuple(const struct sk_buff *skb,
243 unsigned int dataoff,
247 struct nf_conntrack_tuple *tuple)
253 memset(tuple, 0, sizeof(*tuple));
255 tuple->src.l3num = l3num;
258 nhoff += offsetof(struct iphdr, saddr);
259 size = 2 * sizeof(__be32);
262 nhoff += offsetof(struct ipv6hdr, saddr);
263 size = sizeof(_addrs);
269 ap = skb_header_pointer(skb, nhoff, size, _addrs);
275 tuple->src.u3.ip = ap[0];
276 tuple->dst.u3.ip = ap[1];
279 memcpy(tuple->src.u3.ip6, ap, sizeof(tuple->src.u3.ip6));
280 memcpy(tuple->dst.u3.ip6, ap + 4, sizeof(tuple->dst.u3.ip6));
284 tuple->dst.protonum = protonum;
285 tuple->dst.dir = IP_CT_DIR_ORIGINAL;
288 #if IS_ENABLED(CONFIG_IPV6)
290 return icmpv6_pkt_to_tuple(skb, dataoff, net, tuple);
293 return icmp_pkt_to_tuple(skb, dataoff, net, tuple);
294 #ifdef CONFIG_NF_CT_PROTO_GRE
296 return gre_pkt_to_tuple(skb, dataoff, net, tuple);
299 case IPPROTO_UDP: /* fallthrough */
300 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
301 #ifdef CONFIG_NF_CT_PROTO_UDPLITE
302 case IPPROTO_UDPLITE:
303 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
305 #ifdef CONFIG_NF_CT_PROTO_SCTP
307 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
309 #ifdef CONFIG_NF_CT_PROTO_DCCP
311 return nf_ct_get_tuple_ports(skb, dataoff, tuple);
320 static int ipv4_get_l4proto(const struct sk_buff *skb, unsigned int nhoff,
324 const struct iphdr *iph;
327 iph = skb_header_pointer(skb, nhoff, sizeof(_iph), &_iph);
331 /* Conntrack defragments packets, we might still see fragments
332 * inside ICMP packets though.
334 if (iph->frag_off & htons(IP_OFFSET))
337 dataoff = nhoff + (iph->ihl << 2);
338 *protonum = iph->protocol;
340 /* Check bogus IP headers */
341 if (dataoff > skb->len) {
342 pr_debug("bogus IPv4 packet: nhoff %u, ihl %u, skblen %u\n",
343 nhoff, iph->ihl << 2, skb->len);
349 #if IS_ENABLED(CONFIG_IPV6)
350 static int ipv6_get_l4proto(const struct sk_buff *skb, unsigned int nhoff,
354 unsigned int extoff = nhoff + sizeof(struct ipv6hdr);
358 if (skb_copy_bits(skb, nhoff + offsetof(struct ipv6hdr, nexthdr),
359 &nexthdr, sizeof(nexthdr)) != 0) {
360 pr_debug("can't get nexthdr\n");
363 protoff = ipv6_skip_exthdr(skb, extoff, &nexthdr, &frag_off);
365 * (protoff == skb->len) means the packet has not data, just
366 * IPv6 and possibly extensions headers, but it is tracked anyway
368 if (protoff < 0 || (frag_off & htons(~0x7)) != 0) {
369 pr_debug("can't find proto in pkt\n");
378 static int get_l4proto(const struct sk_buff *skb,
379 unsigned int nhoff, u8 pf, u8 *l4num)
383 return ipv4_get_l4proto(skb, nhoff, l4num);
384 #if IS_ENABLED(CONFIG_IPV6)
386 return ipv6_get_l4proto(skb, nhoff, l4num);
395 bool nf_ct_get_tuplepr(const struct sk_buff *skb, unsigned int nhoff,
397 struct net *net, struct nf_conntrack_tuple *tuple)
402 protoff = get_l4proto(skb, nhoff, l3num, &protonum);
406 return nf_ct_get_tuple(skb, nhoff, protoff, l3num, protonum, net, tuple);
408 EXPORT_SYMBOL_GPL(nf_ct_get_tuplepr);
411 nf_ct_invert_tuple(struct nf_conntrack_tuple *inverse,
412 const struct nf_conntrack_tuple *orig)
414 memset(inverse, 0, sizeof(*inverse));
416 inverse->src.l3num = orig->src.l3num;
418 switch (orig->src.l3num) {
420 inverse->src.u3.ip = orig->dst.u3.ip;
421 inverse->dst.u3.ip = orig->src.u3.ip;
424 inverse->src.u3.in6 = orig->dst.u3.in6;
425 inverse->dst.u3.in6 = orig->src.u3.in6;
431 inverse->dst.dir = !orig->dst.dir;
433 inverse->dst.protonum = orig->dst.protonum;
435 switch (orig->dst.protonum) {
437 return nf_conntrack_invert_icmp_tuple(inverse, orig);
438 #if IS_ENABLED(CONFIG_IPV6)
440 return nf_conntrack_invert_icmpv6_tuple(inverse, orig);
444 inverse->src.u.all = orig->dst.u.all;
445 inverse->dst.u.all = orig->src.u.all;
448 EXPORT_SYMBOL_GPL(nf_ct_invert_tuple);
450 /* Generate a almost-unique pseudo-id for a given conntrack.
452 * intentionally doesn't re-use any of the seeds used for hash
453 * table location, we assume id gets exposed to userspace.
455 * Following nf_conn items do not change throughout lifetime
456 * of the nf_conn after it has been committed to main hash table:
459 * 2. nf_conn->ext address
460 * 3. nf_conn->master address (normally NULL)
462 * 5. the associated net namespace
464 u32 nf_ct_get_id(const struct nf_conn *ct)
466 static __read_mostly siphash_key_t ct_id_seed;
467 unsigned long a, b, c, d;
469 net_get_random_once(&ct_id_seed, sizeof(ct_id_seed));
471 a = (unsigned long)ct;
472 b = (unsigned long)ct->master ^ net_hash_mix(nf_ct_net(ct));
473 c = (unsigned long)ct->ext;
474 d = (unsigned long)siphash(&ct->tuplehash, sizeof(ct->tuplehash),
477 return siphash_4u64((u64)a, (u64)b, (u64)c, (u64)d, &ct_id_seed);
479 return siphash_4u32((u32)a, (u32)b, (u32)c, (u32)d, &ct_id_seed);
482 EXPORT_SYMBOL_GPL(nf_ct_get_id);
485 clean_from_lists(struct nf_conn *ct)
487 pr_debug("clean_from_lists(%p)\n", ct);
488 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
489 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode);
491 /* Destroy all pending expectations */
492 nf_ct_remove_expectations(ct);
495 /* must be called with local_bh_disable */
496 static void nf_ct_add_to_dying_list(struct nf_conn *ct)
498 struct ct_pcpu *pcpu;
500 /* add this conntrack to the (per cpu) dying list */
501 ct->cpu = smp_processor_id();
502 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
504 spin_lock(&pcpu->lock);
505 hlist_nulls_add_head(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
507 spin_unlock(&pcpu->lock);
510 /* must be called with local_bh_disable */
511 static void nf_ct_add_to_unconfirmed_list(struct nf_conn *ct)
513 struct ct_pcpu *pcpu;
515 /* add this conntrack to the (per cpu) unconfirmed list */
516 ct->cpu = smp_processor_id();
517 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
519 spin_lock(&pcpu->lock);
520 hlist_nulls_add_head(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
522 spin_unlock(&pcpu->lock);
525 /* must be called with local_bh_disable */
526 static void nf_ct_del_from_dying_or_unconfirmed_list(struct nf_conn *ct)
528 struct ct_pcpu *pcpu;
530 /* We overload first tuple to link into unconfirmed or dying list.*/
531 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
533 spin_lock(&pcpu->lock);
534 BUG_ON(hlist_nulls_unhashed(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode));
535 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
536 spin_unlock(&pcpu->lock);
539 #define NFCT_ALIGN(len) (((len) + NFCT_INFOMASK) & ~NFCT_INFOMASK)
541 /* Released via destroy_conntrack() */
542 struct nf_conn *nf_ct_tmpl_alloc(struct net *net,
543 const struct nf_conntrack_zone *zone,
546 struct nf_conn *tmpl, *p;
548 if (ARCH_KMALLOC_MINALIGN <= NFCT_INFOMASK) {
549 tmpl = kzalloc(sizeof(*tmpl) + NFCT_INFOMASK, flags);
554 tmpl = (struct nf_conn *)NFCT_ALIGN((unsigned long)p);
556 tmpl = (struct nf_conn *)NFCT_ALIGN((unsigned long)p);
557 tmpl->proto.tmpl_padto = (char *)tmpl - (char *)p;
560 tmpl = kzalloc(sizeof(*tmpl), flags);
565 tmpl->status = IPS_TEMPLATE;
566 write_pnet(&tmpl->ct_net, net);
567 nf_ct_zone_add(tmpl, zone);
568 atomic_set(&tmpl->ct_general.use, 0);
572 EXPORT_SYMBOL_GPL(nf_ct_tmpl_alloc);
574 void nf_ct_tmpl_free(struct nf_conn *tmpl)
576 nf_ct_ext_destroy(tmpl);
577 nf_ct_ext_free(tmpl);
579 if (ARCH_KMALLOC_MINALIGN <= NFCT_INFOMASK)
580 kfree((char *)tmpl - tmpl->proto.tmpl_padto);
584 EXPORT_SYMBOL_GPL(nf_ct_tmpl_free);
586 static void destroy_gre_conntrack(struct nf_conn *ct)
588 #ifdef CONFIG_NF_CT_PROTO_GRE
589 struct nf_conn *master = ct->master;
592 nf_ct_gre_keymap_destroy(master);
597 destroy_conntrack(struct nf_conntrack *nfct)
599 struct nf_conn *ct = (struct nf_conn *)nfct;
601 pr_debug("destroy_conntrack(%p)\n", ct);
602 WARN_ON(atomic_read(&nfct->use) != 0);
604 if (unlikely(nf_ct_is_template(ct))) {
609 if (unlikely(nf_ct_protonum(ct) == IPPROTO_GRE))
610 destroy_gre_conntrack(ct);
613 /* Expectations will have been removed in clean_from_lists,
614 * except TFTP can create an expectation on the first packet,
615 * before connection is in the list, so we need to clean here,
618 nf_ct_remove_expectations(ct);
620 nf_ct_del_from_dying_or_unconfirmed_list(ct);
625 nf_ct_put(ct->master);
627 pr_debug("destroy_conntrack: returning ct=%p to slab\n", ct);
628 nf_conntrack_free(ct);
631 static void nf_ct_delete_from_lists(struct nf_conn *ct)
633 struct net *net = nf_ct_net(ct);
634 unsigned int hash, reply_hash;
635 unsigned int sequence;
637 nf_ct_helper_destroy(ct);
641 sequence = read_seqcount_begin(&nf_conntrack_generation);
642 hash = hash_conntrack(net,
643 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
644 reply_hash = hash_conntrack(net,
645 &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
646 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
648 clean_from_lists(ct);
649 nf_conntrack_double_unlock(hash, reply_hash);
651 nf_ct_add_to_dying_list(ct);
656 bool nf_ct_delete(struct nf_conn *ct, u32 portid, int report)
658 struct nf_conn_tstamp *tstamp;
660 if (test_and_set_bit(IPS_DYING_BIT, &ct->status))
663 tstamp = nf_conn_tstamp_find(ct);
664 if (tstamp && tstamp->stop == 0)
665 tstamp->stop = ktime_get_real_ns();
667 if (nf_conntrack_event_report(IPCT_DESTROY, ct,
668 portid, report) < 0) {
669 /* destroy event was not delivered. nf_ct_put will
670 * be done by event cache worker on redelivery.
672 nf_ct_delete_from_lists(ct);
673 nf_conntrack_ecache_delayed_work(nf_ct_net(ct));
677 nf_conntrack_ecache_work(nf_ct_net(ct));
678 nf_ct_delete_from_lists(ct);
682 EXPORT_SYMBOL_GPL(nf_ct_delete);
685 nf_ct_key_equal(struct nf_conntrack_tuple_hash *h,
686 const struct nf_conntrack_tuple *tuple,
687 const struct nf_conntrack_zone *zone,
688 const struct net *net)
690 struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
692 /* A conntrack can be recreated with the equal tuple,
693 * so we need to check that the conntrack is confirmed
695 return nf_ct_tuple_equal(tuple, &h->tuple) &&
696 nf_ct_zone_equal(ct, zone, NF_CT_DIRECTION(h)) &&
697 nf_ct_is_confirmed(ct) &&
698 net_eq(net, nf_ct_net(ct));
702 nf_ct_match(const struct nf_conn *ct1, const struct nf_conn *ct2)
704 return nf_ct_tuple_equal(&ct1->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
705 &ct2->tuplehash[IP_CT_DIR_ORIGINAL].tuple) &&
706 nf_ct_tuple_equal(&ct1->tuplehash[IP_CT_DIR_REPLY].tuple,
707 &ct2->tuplehash[IP_CT_DIR_REPLY].tuple) &&
708 nf_ct_zone_equal(ct1, nf_ct_zone(ct2), IP_CT_DIR_ORIGINAL) &&
709 nf_ct_zone_equal(ct1, nf_ct_zone(ct2), IP_CT_DIR_REPLY) &&
710 net_eq(nf_ct_net(ct1), nf_ct_net(ct2));
713 /* caller must hold rcu readlock and none of the nf_conntrack_locks */
714 static void nf_ct_gc_expired(struct nf_conn *ct)
716 if (!atomic_inc_not_zero(&ct->ct_general.use))
719 if (nf_ct_should_gc(ct))
727 * - Caller must take a reference on returned object
728 * and recheck nf_ct_tuple_equal(tuple, &h->tuple)
730 static struct nf_conntrack_tuple_hash *
731 ____nf_conntrack_find(struct net *net, const struct nf_conntrack_zone *zone,
732 const struct nf_conntrack_tuple *tuple, u32 hash)
734 struct nf_conntrack_tuple_hash *h;
735 struct hlist_nulls_head *ct_hash;
736 struct hlist_nulls_node *n;
737 unsigned int bucket, hsize;
740 nf_conntrack_get_ht(&ct_hash, &hsize);
741 bucket = reciprocal_scale(hash, hsize);
743 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[bucket], hnnode) {
746 ct = nf_ct_tuplehash_to_ctrack(h);
747 if (nf_ct_is_expired(ct)) {
748 nf_ct_gc_expired(ct);
752 if (nf_ct_key_equal(h, tuple, zone, net))
756 * if the nulls value we got at the end of this lookup is
757 * not the expected one, we must restart lookup.
758 * We probably met an item that was moved to another chain.
760 if (get_nulls_value(n) != bucket) {
761 NF_CT_STAT_INC_ATOMIC(net, search_restart);
768 /* Find a connection corresponding to a tuple. */
769 static struct nf_conntrack_tuple_hash *
770 __nf_conntrack_find_get(struct net *net, const struct nf_conntrack_zone *zone,
771 const struct nf_conntrack_tuple *tuple, u32 hash)
773 struct nf_conntrack_tuple_hash *h;
778 h = ____nf_conntrack_find(net, zone, tuple, hash);
780 /* We have a candidate that matches the tuple we're interested
781 * in, try to obtain a reference and re-check tuple
783 ct = nf_ct_tuplehash_to_ctrack(h);
784 if (likely(atomic_inc_not_zero(&ct->ct_general.use))) {
785 if (likely(nf_ct_key_equal(h, tuple, zone, net)))
788 /* TYPESAFE_BY_RCU recycled the candidate */
800 struct nf_conntrack_tuple_hash *
801 nf_conntrack_find_get(struct net *net, const struct nf_conntrack_zone *zone,
802 const struct nf_conntrack_tuple *tuple)
804 return __nf_conntrack_find_get(net, zone, tuple,
805 hash_conntrack_raw(tuple, net));
807 EXPORT_SYMBOL_GPL(nf_conntrack_find_get);
809 static void __nf_conntrack_hash_insert(struct nf_conn *ct,
811 unsigned int reply_hash)
813 hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
814 &nf_conntrack_hash[hash]);
815 hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode,
816 &nf_conntrack_hash[reply_hash]);
820 nf_conntrack_hash_check_insert(struct nf_conn *ct)
822 const struct nf_conntrack_zone *zone;
823 struct net *net = nf_ct_net(ct);
824 unsigned int hash, reply_hash;
825 struct nf_conntrack_tuple_hash *h;
826 struct hlist_nulls_node *n;
827 unsigned int sequence;
829 zone = nf_ct_zone(ct);
833 sequence = read_seqcount_begin(&nf_conntrack_generation);
834 hash = hash_conntrack(net,
835 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
836 reply_hash = hash_conntrack(net,
837 &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
838 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
840 /* See if there's one in the list already, including reverse */
841 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode)
842 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
846 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode)
847 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
852 /* The caller holds a reference to this object */
853 atomic_set(&ct->ct_general.use, 2);
854 __nf_conntrack_hash_insert(ct, hash, reply_hash);
855 nf_conntrack_double_unlock(hash, reply_hash);
856 NF_CT_STAT_INC(net, insert);
861 nf_conntrack_double_unlock(hash, reply_hash);
862 NF_CT_STAT_INC(net, insert_failed);
866 EXPORT_SYMBOL_GPL(nf_conntrack_hash_check_insert);
868 static inline void nf_ct_acct_update(struct nf_conn *ct,
869 enum ip_conntrack_info ctinfo,
872 struct nf_conn_acct *acct;
874 acct = nf_conn_acct_find(ct);
876 struct nf_conn_counter *counter = acct->counter;
878 atomic64_inc(&counter[CTINFO2DIR(ctinfo)].packets);
879 atomic64_add(len, &counter[CTINFO2DIR(ctinfo)].bytes);
883 static void nf_ct_acct_merge(struct nf_conn *ct, enum ip_conntrack_info ctinfo,
884 const struct nf_conn *loser_ct)
886 struct nf_conn_acct *acct;
888 acct = nf_conn_acct_find(loser_ct);
890 struct nf_conn_counter *counter = acct->counter;
893 /* u32 should be fine since we must have seen one packet. */
894 bytes = atomic64_read(&counter[CTINFO2DIR(ctinfo)].bytes);
895 nf_ct_acct_update(ct, ctinfo, bytes);
899 /* Resolve race on insertion if this protocol allows this. */
900 static int nf_ct_resolve_clash(struct net *net, struct sk_buff *skb,
901 enum ip_conntrack_info ctinfo,
902 struct nf_conntrack_tuple_hash *h)
904 /* This is the conntrack entry already in hashes that won race. */
905 struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
906 const struct nf_conntrack_l4proto *l4proto;
907 enum ip_conntrack_info oldinfo;
908 struct nf_conn *loser_ct = nf_ct_get(skb, &oldinfo);
910 l4proto = nf_ct_l4proto_find(nf_ct_protonum(ct));
911 if (l4proto->allow_clash &&
912 !nf_ct_is_dying(ct) &&
913 atomic_inc_not_zero(&ct->ct_general.use)) {
914 if (((ct->status & IPS_NAT_DONE_MASK) == 0) ||
915 nf_ct_match(ct, loser_ct)) {
916 nf_ct_acct_merge(ct, ctinfo, loser_ct);
917 nf_conntrack_put(&loser_ct->ct_general);
918 nf_ct_set(skb, ct, oldinfo);
923 NF_CT_STAT_INC(net, drop);
927 /* Confirm a connection given skb; places it in hash table */
929 __nf_conntrack_confirm(struct sk_buff *skb)
931 const struct nf_conntrack_zone *zone;
932 unsigned int hash, reply_hash;
933 struct nf_conntrack_tuple_hash *h;
935 struct nf_conn_help *help;
936 struct nf_conn_tstamp *tstamp;
937 struct hlist_nulls_node *n;
938 enum ip_conntrack_info ctinfo;
940 unsigned int sequence;
943 ct = nf_ct_get(skb, &ctinfo);
946 /* ipt_REJECT uses nf_conntrack_attach to attach related
947 ICMP/TCP RST packets in other direction. Actual packet
948 which created connection will be IP_CT_NEW or for an
949 expected connection, IP_CT_RELATED. */
950 if (CTINFO2DIR(ctinfo) != IP_CT_DIR_ORIGINAL)
953 zone = nf_ct_zone(ct);
957 sequence = read_seqcount_begin(&nf_conntrack_generation);
958 /* reuse the hash saved before */
959 hash = *(unsigned long *)&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev;
960 hash = scale_hash(hash);
961 reply_hash = hash_conntrack(net,
962 &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
964 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
966 /* We're not in hash table, and we refuse to set up related
967 * connections for unconfirmed conns. But packet copies and
968 * REJECT will give spurious warnings here.
971 /* Another skb with the same unconfirmed conntrack may
972 * win the race. This may happen for bridge(br_flood)
973 * or broadcast/multicast packets do skb_clone with
974 * unconfirmed conntrack.
976 if (unlikely(nf_ct_is_confirmed(ct))) {
978 nf_conntrack_double_unlock(hash, reply_hash);
983 pr_debug("Confirming conntrack %p\n", ct);
984 /* We have to check the DYING flag after unlink to prevent
985 * a race against nf_ct_get_next_corpse() possibly called from
986 * user context, else we insert an already 'dead' hash, blocking
987 * further use of that particular connection -JM.
989 nf_ct_del_from_dying_or_unconfirmed_list(ct);
991 if (unlikely(nf_ct_is_dying(ct))) {
992 nf_ct_add_to_dying_list(ct);
996 /* See if there's one in the list already, including reverse:
997 NAT could have grabbed it without realizing, since we're
998 not in the hash. If there is, we lost race. */
999 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode)
1000 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
1004 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode)
1005 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
1009 /* Timer relative to confirmation time, not original
1010 setting time, otherwise we'd get timer wrap in
1011 weird delay cases. */
1012 ct->timeout += nfct_time_stamp;
1013 atomic_inc(&ct->ct_general.use);
1014 ct->status |= IPS_CONFIRMED;
1016 /* set conntrack timestamp, if enabled. */
1017 tstamp = nf_conn_tstamp_find(ct);
1019 tstamp->start = ktime_get_real_ns();
1021 /* Since the lookup is lockless, hash insertion must be done after
1022 * starting the timer and setting the CONFIRMED bit. The RCU barriers
1023 * guarantee that no other CPU can find the conntrack before the above
1024 * stores are visible.
1026 __nf_conntrack_hash_insert(ct, hash, reply_hash);
1027 nf_conntrack_double_unlock(hash, reply_hash);
1030 help = nfct_help(ct);
1031 if (help && help->helper)
1032 nf_conntrack_event_cache(IPCT_HELPER, ct);
1034 nf_conntrack_event_cache(master_ct(ct) ?
1035 IPCT_RELATED : IPCT_NEW, ct);
1039 nf_ct_add_to_dying_list(ct);
1040 ret = nf_ct_resolve_clash(net, skb, ctinfo, h);
1042 nf_conntrack_double_unlock(hash, reply_hash);
1043 NF_CT_STAT_INC(net, insert_failed);
1047 EXPORT_SYMBOL_GPL(__nf_conntrack_confirm);
1049 /* Returns true if a connection correspondings to the tuple (required
1052 nf_conntrack_tuple_taken(const struct nf_conntrack_tuple *tuple,
1053 const struct nf_conn *ignored_conntrack)
1055 struct net *net = nf_ct_net(ignored_conntrack);
1056 const struct nf_conntrack_zone *zone;
1057 struct nf_conntrack_tuple_hash *h;
1058 struct hlist_nulls_head *ct_hash;
1059 unsigned int hash, hsize;
1060 struct hlist_nulls_node *n;
1063 zone = nf_ct_zone(ignored_conntrack);
1067 nf_conntrack_get_ht(&ct_hash, &hsize);
1068 hash = __hash_conntrack(net, tuple, hsize);
1070 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[hash], hnnode) {
1071 ct = nf_ct_tuplehash_to_ctrack(h);
1073 if (ct == ignored_conntrack)
1076 if (nf_ct_is_expired(ct)) {
1077 nf_ct_gc_expired(ct);
1081 if (nf_ct_key_equal(h, tuple, zone, net)) {
1082 /* Tuple is taken already, so caller will need to find
1083 * a new source port to use.
1086 * If the *original tuples* are identical, then both
1087 * conntracks refer to the same flow.
1088 * This is a rare situation, it can occur e.g. when
1089 * more than one UDP packet is sent from same socket
1090 * in different threads.
1092 * Let nf_ct_resolve_clash() deal with this later.
1094 if (nf_ct_tuple_equal(&ignored_conntrack->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
1095 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple))
1098 NF_CT_STAT_INC_ATOMIC(net, found);
1104 if (get_nulls_value(n) != hash) {
1105 NF_CT_STAT_INC_ATOMIC(net, search_restart);
1113 EXPORT_SYMBOL_GPL(nf_conntrack_tuple_taken);
1115 #define NF_CT_EVICTION_RANGE 8
1117 /* There's a small race here where we may free a just-assured
1118 connection. Too bad: we're in trouble anyway. */
1119 static unsigned int early_drop_list(struct net *net,
1120 struct hlist_nulls_head *head)
1122 struct nf_conntrack_tuple_hash *h;
1123 struct hlist_nulls_node *n;
1124 unsigned int drops = 0;
1125 struct nf_conn *tmp;
1127 hlist_nulls_for_each_entry_rcu(h, n, head, hnnode) {
1128 tmp = nf_ct_tuplehash_to_ctrack(h);
1130 if (test_bit(IPS_OFFLOAD_BIT, &tmp->status))
1133 if (nf_ct_is_expired(tmp)) {
1134 nf_ct_gc_expired(tmp);
1138 if (test_bit(IPS_ASSURED_BIT, &tmp->status) ||
1139 !net_eq(nf_ct_net(tmp), net) ||
1140 nf_ct_is_dying(tmp))
1143 if (!atomic_inc_not_zero(&tmp->ct_general.use))
1146 /* kill only if still in same netns -- might have moved due to
1147 * SLAB_TYPESAFE_BY_RCU rules.
1149 * We steal the timer reference. If that fails timer has
1150 * already fired or someone else deleted it. Just drop ref
1151 * and move to next entry.
1153 if (net_eq(nf_ct_net(tmp), net) &&
1154 nf_ct_is_confirmed(tmp) &&
1155 nf_ct_delete(tmp, 0, 0))
1164 static noinline int early_drop(struct net *net, unsigned int hash)
1166 unsigned int i, bucket;
1168 for (i = 0; i < NF_CT_EVICTION_RANGE; i++) {
1169 struct hlist_nulls_head *ct_hash;
1170 unsigned int hsize, drops;
1173 nf_conntrack_get_ht(&ct_hash, &hsize);
1175 bucket = reciprocal_scale(hash, hsize);
1177 bucket = (bucket + 1) % hsize;
1179 drops = early_drop_list(net, &ct_hash[bucket]);
1183 NF_CT_STAT_ADD_ATOMIC(net, early_drop, drops);
1191 static bool gc_worker_skip_ct(const struct nf_conn *ct)
1193 return !nf_ct_is_confirmed(ct) || nf_ct_is_dying(ct);
1196 static bool gc_worker_can_early_drop(const struct nf_conn *ct)
1198 const struct nf_conntrack_l4proto *l4proto;
1200 if (!test_bit(IPS_ASSURED_BIT, &ct->status))
1203 l4proto = nf_ct_l4proto_find(nf_ct_protonum(ct));
1204 if (l4proto->can_early_drop && l4proto->can_early_drop(ct))
1210 #define DAY (86400 * HZ)
1212 /* Set an arbitrary timeout large enough not to ever expire, this save
1213 * us a check for the IPS_OFFLOAD_BIT from the packet path via
1214 * nf_ct_is_expired().
1216 static void nf_ct_offload_timeout(struct nf_conn *ct)
1218 if (nf_ct_expires(ct) < DAY / 2)
1219 ct->timeout = nfct_time_stamp + DAY;
1222 static void gc_worker(struct work_struct *work)
1224 unsigned int min_interval = max(HZ / GC_MAX_BUCKETS_DIV, 1u);
1225 unsigned int i, goal, buckets = 0, expired_count = 0;
1226 unsigned int nf_conntrack_max95 = 0;
1227 struct conntrack_gc_work *gc_work;
1228 unsigned int ratio, scanned = 0;
1229 unsigned long next_run;
1231 gc_work = container_of(work, struct conntrack_gc_work, dwork.work);
1233 goal = nf_conntrack_htable_size / GC_MAX_BUCKETS_DIV;
1234 i = gc_work->last_bucket;
1235 if (gc_work->early_drop)
1236 nf_conntrack_max95 = nf_conntrack_max / 100u * 95u;
1239 struct nf_conntrack_tuple_hash *h;
1240 struct hlist_nulls_head *ct_hash;
1241 struct hlist_nulls_node *n;
1242 unsigned int hashsz;
1243 struct nf_conn *tmp;
1248 nf_conntrack_get_ht(&ct_hash, &hashsz);
1252 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[i], hnnode) {
1255 tmp = nf_ct_tuplehash_to_ctrack(h);
1258 if (test_bit(IPS_OFFLOAD_BIT, &tmp->status)) {
1259 nf_ct_offload_timeout(tmp);
1263 if (nf_ct_is_expired(tmp)) {
1264 nf_ct_gc_expired(tmp);
1269 if (nf_conntrack_max95 == 0 || gc_worker_skip_ct(tmp))
1272 net = nf_ct_net(tmp);
1273 if (atomic_read(&net->ct.count) < nf_conntrack_max95)
1276 /* need to take reference to avoid possible races */
1277 if (!atomic_inc_not_zero(&tmp->ct_general.use))
1280 if (gc_worker_skip_ct(tmp)) {
1285 if (gc_worker_can_early_drop(tmp))
1291 /* could check get_nulls_value() here and restart if ct
1292 * was moved to another chain. But given gc is best-effort
1293 * we will just continue with next hash slot.
1297 } while (++buckets < goal);
1299 if (gc_work->exiting)
1303 * Eviction will normally happen from the packet path, and not
1304 * from this gc worker.
1306 * This worker is only here to reap expired entries when system went
1307 * idle after a busy period.
1309 * The heuristics below are supposed to balance conflicting goals:
1311 * 1. Minimize time until we notice a stale entry
1312 * 2. Maximize scan intervals to not waste cycles
1314 * Normally, expire ratio will be close to 0.
1316 * As soon as a sizeable fraction of the entries have expired
1317 * increase scan frequency.
1319 ratio = scanned ? expired_count * 100 / scanned : 0;
1320 if (ratio > GC_EVICT_RATIO) {
1321 gc_work->next_gc_run = min_interval;
1323 unsigned int max = GC_MAX_SCAN_JIFFIES / GC_MAX_BUCKETS_DIV;
1325 BUILD_BUG_ON((GC_MAX_SCAN_JIFFIES / GC_MAX_BUCKETS_DIV) == 0);
1327 gc_work->next_gc_run += min_interval;
1328 if (gc_work->next_gc_run > max)
1329 gc_work->next_gc_run = max;
1332 next_run = gc_work->next_gc_run;
1333 gc_work->last_bucket = i;
1334 gc_work->early_drop = false;
1335 queue_delayed_work(system_power_efficient_wq, &gc_work->dwork, next_run);
1338 static void conntrack_gc_work_init(struct conntrack_gc_work *gc_work)
1340 INIT_DEFERRABLE_WORK(&gc_work->dwork, gc_worker);
1341 gc_work->next_gc_run = HZ;
1342 gc_work->exiting = false;
1345 static struct nf_conn *
1346 __nf_conntrack_alloc(struct net *net,
1347 const struct nf_conntrack_zone *zone,
1348 const struct nf_conntrack_tuple *orig,
1349 const struct nf_conntrack_tuple *repl,
1350 gfp_t gfp, u32 hash)
1354 /* We don't want any race condition at early drop stage */
1355 atomic_inc(&net->ct.count);
1357 if (nf_conntrack_max &&
1358 unlikely(atomic_read(&net->ct.count) > nf_conntrack_max)) {
1359 if (!early_drop(net, hash)) {
1360 if (!conntrack_gc_work.early_drop)
1361 conntrack_gc_work.early_drop = true;
1362 atomic_dec(&net->ct.count);
1363 net_warn_ratelimited("nf_conntrack: table full, dropping packet\n");
1364 return ERR_PTR(-ENOMEM);
1369 * Do not use kmem_cache_zalloc(), as this cache uses
1370 * SLAB_TYPESAFE_BY_RCU.
1372 ct = kmem_cache_alloc(nf_conntrack_cachep, gfp);
1376 spin_lock_init(&ct->lock);
1377 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple = *orig;
1378 ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode.pprev = NULL;
1379 ct->tuplehash[IP_CT_DIR_REPLY].tuple = *repl;
1380 /* save hash for reusing when confirming */
1381 *(unsigned long *)(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev) = hash;
1384 write_pnet(&ct->ct_net, net);
1385 memset(&ct->__nfct_init_offset[0], 0,
1386 offsetof(struct nf_conn, proto) -
1387 offsetof(struct nf_conn, __nfct_init_offset[0]));
1389 nf_ct_zone_add(ct, zone);
1391 /* Because we use RCU lookups, we set ct_general.use to zero before
1392 * this is inserted in any list.
1394 atomic_set(&ct->ct_general.use, 0);
1397 atomic_dec(&net->ct.count);
1398 return ERR_PTR(-ENOMEM);
1401 struct nf_conn *nf_conntrack_alloc(struct net *net,
1402 const struct nf_conntrack_zone *zone,
1403 const struct nf_conntrack_tuple *orig,
1404 const struct nf_conntrack_tuple *repl,
1407 return __nf_conntrack_alloc(net, zone, orig, repl, gfp, 0);
1409 EXPORT_SYMBOL_GPL(nf_conntrack_alloc);
1411 void nf_conntrack_free(struct nf_conn *ct)
1413 struct net *net = nf_ct_net(ct);
1415 /* A freed object has refcnt == 0, that's
1416 * the golden rule for SLAB_TYPESAFE_BY_RCU
1418 WARN_ON(atomic_read(&ct->ct_general.use) != 0);
1420 nf_ct_ext_destroy(ct);
1422 kmem_cache_free(nf_conntrack_cachep, ct);
1423 smp_mb__before_atomic();
1424 atomic_dec(&net->ct.count);
1426 EXPORT_SYMBOL_GPL(nf_conntrack_free);
1429 /* Allocate a new conntrack: we return -ENOMEM if classification
1430 failed due to stress. Otherwise it really is unclassifiable. */
1431 static noinline struct nf_conntrack_tuple_hash *
1432 init_conntrack(struct net *net, struct nf_conn *tmpl,
1433 const struct nf_conntrack_tuple *tuple,
1434 struct sk_buff *skb,
1435 unsigned int dataoff, u32 hash)
1438 struct nf_conn_help *help;
1439 struct nf_conntrack_tuple repl_tuple;
1440 struct nf_conntrack_ecache *ecache;
1441 struct nf_conntrack_expect *exp = NULL;
1442 const struct nf_conntrack_zone *zone;
1443 struct nf_conn_timeout *timeout_ext;
1444 struct nf_conntrack_zone tmp;
1446 if (!nf_ct_invert_tuple(&repl_tuple, tuple)) {
1447 pr_debug("Can't invert tuple.\n");
1451 zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1452 ct = __nf_conntrack_alloc(net, zone, tuple, &repl_tuple, GFP_ATOMIC,
1455 return (struct nf_conntrack_tuple_hash *)ct;
1457 if (!nf_ct_add_synproxy(ct, tmpl)) {
1458 nf_conntrack_free(ct);
1459 return ERR_PTR(-ENOMEM);
1462 timeout_ext = tmpl ? nf_ct_timeout_find(tmpl) : NULL;
1465 nf_ct_timeout_ext_add(ct, rcu_dereference(timeout_ext->timeout),
1468 nf_ct_acct_ext_add(ct, GFP_ATOMIC);
1469 nf_ct_tstamp_ext_add(ct, GFP_ATOMIC);
1470 nf_ct_labels_ext_add(ct);
1472 ecache = tmpl ? nf_ct_ecache_find(tmpl) : NULL;
1473 nf_ct_ecache_ext_add(ct, ecache ? ecache->ctmask : 0,
1474 ecache ? ecache->expmask : 0,
1478 if (net->ct.expect_count) {
1479 spin_lock(&nf_conntrack_expect_lock);
1480 exp = nf_ct_find_expectation(net, zone, tuple);
1482 pr_debug("expectation arrives ct=%p exp=%p\n",
1484 /* Welcome, Mr. Bond. We've been expecting you... */
1485 __set_bit(IPS_EXPECTED_BIT, &ct->status);
1486 /* exp->master safe, refcnt bumped in nf_ct_find_expectation */
1487 ct->master = exp->master;
1489 help = nf_ct_helper_ext_add(ct, GFP_ATOMIC);
1491 rcu_assign_pointer(help->helper, exp->helper);
1494 #ifdef CONFIG_NF_CONNTRACK_MARK
1495 ct->mark = exp->master->mark;
1497 #ifdef CONFIG_NF_CONNTRACK_SECMARK
1498 ct->secmark = exp->master->secmark;
1500 NF_CT_STAT_INC(net, expect_new);
1502 spin_unlock(&nf_conntrack_expect_lock);
1505 __nf_ct_try_assign_helper(ct, tmpl, GFP_ATOMIC);
1507 /* Now it is inserted into the unconfirmed list, bump refcount */
1508 nf_conntrack_get(&ct->ct_general);
1509 nf_ct_add_to_unconfirmed_list(ct);
1515 exp->expectfn(ct, exp);
1516 nf_ct_expect_put(exp);
1519 return &ct->tuplehash[IP_CT_DIR_ORIGINAL];
1522 /* On success, returns 0, sets skb->_nfct | ctinfo */
1524 resolve_normal_ct(struct nf_conn *tmpl,
1525 struct sk_buff *skb,
1526 unsigned int dataoff,
1528 const struct nf_hook_state *state)
1530 const struct nf_conntrack_zone *zone;
1531 struct nf_conntrack_tuple tuple;
1532 struct nf_conntrack_tuple_hash *h;
1533 enum ip_conntrack_info ctinfo;
1534 struct nf_conntrack_zone tmp;
1538 if (!nf_ct_get_tuple(skb, skb_network_offset(skb),
1539 dataoff, state->pf, protonum, state->net,
1541 pr_debug("Can't get tuple\n");
1545 /* look for tuple match */
1546 zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1547 hash = hash_conntrack_raw(&tuple, state->net);
1548 h = __nf_conntrack_find_get(state->net, zone, &tuple, hash);
1550 h = init_conntrack(state->net, tmpl, &tuple,
1551 skb, dataoff, hash);
1557 ct = nf_ct_tuplehash_to_ctrack(h);
1559 /* It exists; we have (non-exclusive) reference. */
1560 if (NF_CT_DIRECTION(h) == IP_CT_DIR_REPLY) {
1561 ctinfo = IP_CT_ESTABLISHED_REPLY;
1563 /* Once we've had two way comms, always ESTABLISHED. */
1564 if (test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) {
1565 pr_debug("normal packet for %p\n", ct);
1566 ctinfo = IP_CT_ESTABLISHED;
1567 } else if (test_bit(IPS_EXPECTED_BIT, &ct->status)) {
1568 pr_debug("related packet for %p\n", ct);
1569 ctinfo = IP_CT_RELATED;
1571 pr_debug("new packet for %p\n", ct);
1575 nf_ct_set(skb, ct, ctinfo);
1580 * icmp packets need special treatment to handle error messages that are
1581 * related to a connection.
1583 * Callers need to check if skb has a conntrack assigned when this
1584 * helper returns; in such case skb belongs to an already known connection.
1586 static unsigned int __cold
1587 nf_conntrack_handle_icmp(struct nf_conn *tmpl,
1588 struct sk_buff *skb,
1589 unsigned int dataoff,
1591 const struct nf_hook_state *state)
1595 if (state->pf == NFPROTO_IPV4 && protonum == IPPROTO_ICMP)
1596 ret = nf_conntrack_icmpv4_error(tmpl, skb, dataoff, state);
1597 #if IS_ENABLED(CONFIG_IPV6)
1598 else if (state->pf == NFPROTO_IPV6 && protonum == IPPROTO_ICMPV6)
1599 ret = nf_conntrack_icmpv6_error(tmpl, skb, dataoff, state);
1605 NF_CT_STAT_INC_ATOMIC(state->net, error);
1606 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1612 static int generic_packet(struct nf_conn *ct, struct sk_buff *skb,
1613 enum ip_conntrack_info ctinfo)
1615 const unsigned int *timeout = nf_ct_timeout_lookup(ct);
1618 timeout = &nf_generic_pernet(nf_ct_net(ct))->timeout;
1620 nf_ct_refresh_acct(ct, ctinfo, skb, *timeout);
1624 /* Returns verdict for packet, or -1 for invalid. */
1625 static int nf_conntrack_handle_packet(struct nf_conn *ct,
1626 struct sk_buff *skb,
1627 unsigned int dataoff,
1628 enum ip_conntrack_info ctinfo,
1629 const struct nf_hook_state *state)
1631 switch (nf_ct_protonum(ct)) {
1633 return nf_conntrack_tcp_packet(ct, skb, dataoff,
1636 return nf_conntrack_udp_packet(ct, skb, dataoff,
1639 return nf_conntrack_icmp_packet(ct, skb, ctinfo, state);
1640 #if IS_ENABLED(CONFIG_IPV6)
1641 case IPPROTO_ICMPV6:
1642 return nf_conntrack_icmpv6_packet(ct, skb, ctinfo, state);
1644 #ifdef CONFIG_NF_CT_PROTO_UDPLITE
1645 case IPPROTO_UDPLITE:
1646 return nf_conntrack_udplite_packet(ct, skb, dataoff,
1649 #ifdef CONFIG_NF_CT_PROTO_SCTP
1651 return nf_conntrack_sctp_packet(ct, skb, dataoff,
1654 #ifdef CONFIG_NF_CT_PROTO_DCCP
1656 return nf_conntrack_dccp_packet(ct, skb, dataoff,
1659 #ifdef CONFIG_NF_CT_PROTO_GRE
1661 return nf_conntrack_gre_packet(ct, skb, dataoff,
1666 return generic_packet(ct, skb, ctinfo);
1670 nf_conntrack_in(struct sk_buff *skb, const struct nf_hook_state *state)
1672 enum ip_conntrack_info ctinfo;
1673 struct nf_conn *ct, *tmpl;
1677 tmpl = nf_ct_get(skb, &ctinfo);
1678 if (tmpl || ctinfo == IP_CT_UNTRACKED) {
1679 /* Previously seen (loopback or untracked)? Ignore. */
1680 if ((tmpl && !nf_ct_is_template(tmpl)) ||
1681 ctinfo == IP_CT_UNTRACKED) {
1682 NF_CT_STAT_INC_ATOMIC(state->net, ignore);
1688 /* rcu_read_lock()ed by nf_hook_thresh */
1689 dataoff = get_l4proto(skb, skb_network_offset(skb), state->pf, &protonum);
1691 pr_debug("not prepared to track yet or error occurred\n");
1692 NF_CT_STAT_INC_ATOMIC(state->net, error);
1693 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1698 if (protonum == IPPROTO_ICMP || protonum == IPPROTO_ICMPV6) {
1699 ret = nf_conntrack_handle_icmp(tmpl, skb, dataoff,
1705 /* ICMP[v6] protocol trackers may assign one conntrack. */
1710 ret = resolve_normal_ct(tmpl, skb, dataoff,
1713 /* Too stressed to deal. */
1714 NF_CT_STAT_INC_ATOMIC(state->net, drop);
1719 ct = nf_ct_get(skb, &ctinfo);
1721 /* Not valid part of a connection */
1722 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1727 ret = nf_conntrack_handle_packet(ct, skb, dataoff, ctinfo, state);
1729 /* Invalid: inverse of the return code tells
1730 * the netfilter core what to do */
1731 pr_debug("nf_conntrack_in: Can't track with proto module\n");
1732 nf_conntrack_put(&ct->ct_general);
1734 NF_CT_STAT_INC_ATOMIC(state->net, invalid);
1735 if (ret == -NF_DROP)
1736 NF_CT_STAT_INC_ATOMIC(state->net, drop);
1737 /* Special case: TCP tracker reports an attempt to reopen a
1738 * closed/aborted connection. We have to go back and create a
1741 if (ret == -NF_REPEAT)
1747 if (ctinfo == IP_CT_ESTABLISHED_REPLY &&
1748 !test_and_set_bit(IPS_SEEN_REPLY_BIT, &ct->status))
1749 nf_conntrack_event_cache(IPCT_REPLY, ct);
1756 EXPORT_SYMBOL_GPL(nf_conntrack_in);
1758 /* Alter reply tuple (maybe alter helper). This is for NAT, and is
1759 implicitly racy: see __nf_conntrack_confirm */
1760 void nf_conntrack_alter_reply(struct nf_conn *ct,
1761 const struct nf_conntrack_tuple *newreply)
1763 struct nf_conn_help *help = nfct_help(ct);
1765 /* Should be unconfirmed, so not in hash table yet */
1766 WARN_ON(nf_ct_is_confirmed(ct));
1768 pr_debug("Altering reply tuple of %p to ", ct);
1769 nf_ct_dump_tuple(newreply);
1771 ct->tuplehash[IP_CT_DIR_REPLY].tuple = *newreply;
1772 if (ct->master || (help && !hlist_empty(&help->expectations)))
1776 __nf_ct_try_assign_helper(ct, NULL, GFP_ATOMIC);
1779 EXPORT_SYMBOL_GPL(nf_conntrack_alter_reply);
1781 /* Refresh conntrack for this many jiffies and do accounting if do_acct is 1 */
1782 void __nf_ct_refresh_acct(struct nf_conn *ct,
1783 enum ip_conntrack_info ctinfo,
1784 const struct sk_buff *skb,
1788 /* Only update if this is not a fixed timeout */
1789 if (test_bit(IPS_FIXED_TIMEOUT_BIT, &ct->status))
1792 /* If not in hash table, timer will not be active yet */
1793 if (nf_ct_is_confirmed(ct))
1794 extra_jiffies += nfct_time_stamp;
1796 if (ct->timeout != extra_jiffies)
1797 ct->timeout = extra_jiffies;
1800 nf_ct_acct_update(ct, ctinfo, skb->len);
1802 EXPORT_SYMBOL_GPL(__nf_ct_refresh_acct);
1804 bool nf_ct_kill_acct(struct nf_conn *ct,
1805 enum ip_conntrack_info ctinfo,
1806 const struct sk_buff *skb)
1808 nf_ct_acct_update(ct, ctinfo, skb->len);
1810 return nf_ct_delete(ct, 0, 0);
1812 EXPORT_SYMBOL_GPL(nf_ct_kill_acct);
1814 #if IS_ENABLED(CONFIG_NF_CT_NETLINK)
1816 #include <linux/netfilter/nfnetlink.h>
1817 #include <linux/netfilter/nfnetlink_conntrack.h>
1818 #include <linux/mutex.h>
1820 /* Generic function for tcp/udp/sctp/dccp and alike. This needs to be
1821 * in ip_conntrack_core, since we don't want the protocols to autoload
1822 * or depend on ctnetlink */
1823 int nf_ct_port_tuple_to_nlattr(struct sk_buff *skb,
1824 const struct nf_conntrack_tuple *tuple)
1826 if (nla_put_be16(skb, CTA_PROTO_SRC_PORT, tuple->src.u.tcp.port) ||
1827 nla_put_be16(skb, CTA_PROTO_DST_PORT, tuple->dst.u.tcp.port))
1828 goto nla_put_failure;
1834 EXPORT_SYMBOL_GPL(nf_ct_port_tuple_to_nlattr);
1836 const struct nla_policy nf_ct_port_nla_policy[CTA_PROTO_MAX+1] = {
1837 [CTA_PROTO_SRC_PORT] = { .type = NLA_U16 },
1838 [CTA_PROTO_DST_PORT] = { .type = NLA_U16 },
1840 EXPORT_SYMBOL_GPL(nf_ct_port_nla_policy);
1842 int nf_ct_port_nlattr_to_tuple(struct nlattr *tb[],
1843 struct nf_conntrack_tuple *t)
1845 if (!tb[CTA_PROTO_SRC_PORT] || !tb[CTA_PROTO_DST_PORT])
1848 t->src.u.tcp.port = nla_get_be16(tb[CTA_PROTO_SRC_PORT]);
1849 t->dst.u.tcp.port = nla_get_be16(tb[CTA_PROTO_DST_PORT]);
1853 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_to_tuple);
1855 unsigned int nf_ct_port_nlattr_tuple_size(void)
1857 static unsigned int size __read_mostly;
1860 size = nla_policy_len(nf_ct_port_nla_policy, CTA_PROTO_MAX + 1);
1864 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_tuple_size);
1867 /* Used by ipt_REJECT and ip6t_REJECT. */
1868 static void nf_conntrack_attach(struct sk_buff *nskb, const struct sk_buff *skb)
1871 enum ip_conntrack_info ctinfo;
1873 /* This ICMP is in reverse direction to the packet which caused it */
1874 ct = nf_ct_get(skb, &ctinfo);
1875 if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL)
1876 ctinfo = IP_CT_RELATED_REPLY;
1878 ctinfo = IP_CT_RELATED;
1880 /* Attach to new skbuff, and increment count */
1881 nf_ct_set(nskb, ct, ctinfo);
1882 nf_conntrack_get(skb_nfct(nskb));
1885 static int nf_conntrack_update(struct net *net, struct sk_buff *skb)
1887 struct nf_conntrack_tuple_hash *h;
1888 struct nf_conntrack_tuple tuple;
1889 enum ip_conntrack_info ctinfo;
1890 struct nf_nat_hook *nat_hook;
1891 unsigned int status;
1897 ct = nf_ct_get(skb, &ctinfo);
1898 if (!ct || nf_ct_is_confirmed(ct))
1901 l3num = nf_ct_l3num(ct);
1903 dataoff = get_l4proto(skb, skb_network_offset(skb), l3num, &l4num);
1907 if (!nf_ct_get_tuple(skb, skb_network_offset(skb), dataoff, l3num,
1908 l4num, net, &tuple))
1911 if (ct->status & IPS_SRC_NAT) {
1912 memcpy(tuple.src.u3.all,
1913 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u3.all,
1914 sizeof(tuple.src.u3.all));
1916 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u.all;
1919 if (ct->status & IPS_DST_NAT) {
1920 memcpy(tuple.dst.u3.all,
1921 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.u3.all,
1922 sizeof(tuple.dst.u3.all));
1924 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.u.all;
1927 h = nf_conntrack_find_get(net, nf_ct_zone(ct), &tuple);
1931 /* Store status bits of the conntrack that is clashing to re-do NAT
1932 * mangling according to what it has been done already to this packet.
1934 status = ct->status;
1937 ct = nf_ct_tuplehash_to_ctrack(h);
1938 nf_ct_set(skb, ct, ctinfo);
1940 nat_hook = rcu_dereference(nf_nat_hook);
1944 if (status & IPS_SRC_NAT &&
1945 nat_hook->manip_pkt(skb, ct, NF_NAT_MANIP_SRC,
1946 IP_CT_DIR_ORIGINAL) == NF_DROP)
1949 if (status & IPS_DST_NAT &&
1950 nat_hook->manip_pkt(skb, ct, NF_NAT_MANIP_DST,
1951 IP_CT_DIR_ORIGINAL) == NF_DROP)
1957 static bool nf_conntrack_get_tuple_skb(struct nf_conntrack_tuple *dst_tuple,
1958 const struct sk_buff *skb)
1960 const struct nf_conntrack_tuple *src_tuple;
1961 const struct nf_conntrack_tuple_hash *hash;
1962 struct nf_conntrack_tuple srctuple;
1963 enum ip_conntrack_info ctinfo;
1966 ct = nf_ct_get(skb, &ctinfo);
1968 src_tuple = nf_ct_tuple(ct, CTINFO2DIR(ctinfo));
1969 memcpy(dst_tuple, src_tuple, sizeof(*dst_tuple));
1973 if (!nf_ct_get_tuplepr(skb, skb_network_offset(skb),
1974 NFPROTO_IPV4, dev_net(skb->dev),
1978 hash = nf_conntrack_find_get(dev_net(skb->dev),
1984 ct = nf_ct_tuplehash_to_ctrack(hash);
1985 src_tuple = nf_ct_tuple(ct, !hash->tuple.dst.dir);
1986 memcpy(dst_tuple, src_tuple, sizeof(*dst_tuple));
1992 /* Bring out ya dead! */
1993 static struct nf_conn *
1994 get_next_corpse(int (*iter)(struct nf_conn *i, void *data),
1995 void *data, unsigned int *bucket)
1997 struct nf_conntrack_tuple_hash *h;
1999 struct hlist_nulls_node *n;
2002 for (; *bucket < nf_conntrack_htable_size; (*bucket)++) {
2003 lockp = &nf_conntrack_locks[*bucket % CONNTRACK_LOCKS];
2005 nf_conntrack_lock(lockp);
2006 if (*bucket < nf_conntrack_htable_size) {
2007 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[*bucket], hnnode) {
2008 if (NF_CT_DIRECTION(h) != IP_CT_DIR_ORIGINAL)
2010 ct = nf_ct_tuplehash_to_ctrack(h);
2022 atomic_inc(&ct->ct_general.use);
2028 static void nf_ct_iterate_cleanup(int (*iter)(struct nf_conn *i, void *data),
2029 void *data, u32 portid, int report)
2031 unsigned int bucket = 0, sequence;
2037 sequence = read_seqcount_begin(&nf_conntrack_generation);
2039 while ((ct = get_next_corpse(iter, data, &bucket)) != NULL) {
2040 /* Time to push up daises... */
2042 nf_ct_delete(ct, portid, report);
2047 if (!read_seqcount_retry(&nf_conntrack_generation, sequence))
2054 int (*iter)(struct nf_conn *i, void *data);
2059 static int iter_net_only(struct nf_conn *i, void *data)
2061 struct iter_data *d = data;
2063 if (!net_eq(d->net, nf_ct_net(i)))
2066 return d->iter(i, d->data);
2070 __nf_ct_unconfirmed_destroy(struct net *net)
2074 for_each_possible_cpu(cpu) {
2075 struct nf_conntrack_tuple_hash *h;
2076 struct hlist_nulls_node *n;
2077 struct ct_pcpu *pcpu;
2079 pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
2081 spin_lock_bh(&pcpu->lock);
2082 hlist_nulls_for_each_entry(h, n, &pcpu->unconfirmed, hnnode) {
2085 ct = nf_ct_tuplehash_to_ctrack(h);
2087 /* we cannot call iter() on unconfirmed list, the
2088 * owning cpu can reallocate ct->ext at any time.
2090 set_bit(IPS_DYING_BIT, &ct->status);
2092 spin_unlock_bh(&pcpu->lock);
2097 void nf_ct_unconfirmed_destroy(struct net *net)
2101 if (atomic_read(&net->ct.count) > 0) {
2102 __nf_ct_unconfirmed_destroy(net);
2103 nf_queue_nf_hook_drop(net);
2107 EXPORT_SYMBOL_GPL(nf_ct_unconfirmed_destroy);
2109 void nf_ct_iterate_cleanup_net(struct net *net,
2110 int (*iter)(struct nf_conn *i, void *data),
2111 void *data, u32 portid, int report)
2117 if (atomic_read(&net->ct.count) == 0)
2124 nf_ct_iterate_cleanup(iter_net_only, &d, portid, report);
2126 EXPORT_SYMBOL_GPL(nf_ct_iterate_cleanup_net);
2129 * nf_ct_iterate_destroy - destroy unconfirmed conntracks and iterate table
2130 * @iter: callback to invoke for each conntrack
2131 * @data: data to pass to @iter
2133 * Like nf_ct_iterate_cleanup, but first marks conntracks on the
2134 * unconfirmed list as dying (so they will not be inserted into
2137 * Can only be called in module exit path.
2140 nf_ct_iterate_destroy(int (*iter)(struct nf_conn *i, void *data), void *data)
2144 down_read(&net_rwsem);
2146 if (atomic_read(&net->ct.count) == 0)
2148 __nf_ct_unconfirmed_destroy(net);
2149 nf_queue_nf_hook_drop(net);
2151 up_read(&net_rwsem);
2153 /* Need to wait for netns cleanup worker to finish, if its
2154 * running -- it might have deleted a net namespace from
2155 * the global list, so our __nf_ct_unconfirmed_destroy() might
2156 * not have affected all namespaces.
2160 /* a conntrack could have been unlinked from unconfirmed list
2161 * before we grabbed pcpu lock in __nf_ct_unconfirmed_destroy().
2162 * This makes sure its inserted into conntrack table.
2166 nf_ct_iterate_cleanup(iter, data, 0, 0);
2168 EXPORT_SYMBOL_GPL(nf_ct_iterate_destroy);
2170 static int kill_all(struct nf_conn *i, void *data)
2172 return net_eq(nf_ct_net(i), data);
2175 void nf_conntrack_cleanup_start(void)
2177 conntrack_gc_work.exiting = true;
2178 RCU_INIT_POINTER(ip_ct_attach, NULL);
2181 void nf_conntrack_cleanup_end(void)
2183 RCU_INIT_POINTER(nf_ct_hook, NULL);
2184 cancel_delayed_work_sync(&conntrack_gc_work.dwork);
2185 kvfree(nf_conntrack_hash);
2187 nf_conntrack_proto_fini();
2188 nf_conntrack_seqadj_fini();
2189 nf_conntrack_labels_fini();
2190 nf_conntrack_helper_fini();
2191 nf_conntrack_timeout_fini();
2192 nf_conntrack_ecache_fini();
2193 nf_conntrack_tstamp_fini();
2194 nf_conntrack_acct_fini();
2195 nf_conntrack_expect_fini();
2197 kmem_cache_destroy(nf_conntrack_cachep);
2201 * Mishearing the voices in his head, our hero wonders how he's
2202 * supposed to kill the mall.
2204 void nf_conntrack_cleanup_net(struct net *net)
2208 list_add(&net->exit_list, &single);
2209 nf_conntrack_cleanup_net_list(&single);
2212 void nf_conntrack_cleanup_net_list(struct list_head *net_exit_list)
2218 * This makes sure all current packets have passed through
2219 * netfilter framework. Roll on, two-stage module
2225 list_for_each_entry(net, net_exit_list, exit_list) {
2226 nf_ct_iterate_cleanup(kill_all, net, 0, 0);
2227 if (atomic_read(&net->ct.count) != 0)
2232 goto i_see_dead_people;
2235 list_for_each_entry(net, net_exit_list, exit_list) {
2236 nf_conntrack_proto_pernet_fini(net);
2237 nf_conntrack_ecache_pernet_fini(net);
2238 nf_conntrack_expect_pernet_fini(net);
2239 free_percpu(net->ct.stat);
2240 free_percpu(net->ct.pcpu_lists);
2244 void *nf_ct_alloc_hashtable(unsigned int *sizep, int nulls)
2246 struct hlist_nulls_head *hash;
2247 unsigned int nr_slots, i;
2249 if (*sizep > (UINT_MAX / sizeof(struct hlist_nulls_head)))
2252 BUILD_BUG_ON(sizeof(struct hlist_nulls_head) != sizeof(struct hlist_head));
2253 nr_slots = *sizep = roundup(*sizep, PAGE_SIZE / sizeof(struct hlist_nulls_head));
2255 hash = kvmalloc_array(nr_slots, sizeof(struct hlist_nulls_head),
2256 GFP_KERNEL | __GFP_ZERO);
2259 for (i = 0; i < nr_slots; i++)
2260 INIT_HLIST_NULLS_HEAD(&hash[i], i);
2264 EXPORT_SYMBOL_GPL(nf_ct_alloc_hashtable);
2266 int nf_conntrack_hash_resize(unsigned int hashsize)
2269 unsigned int old_size;
2270 struct hlist_nulls_head *hash, *old_hash;
2271 struct nf_conntrack_tuple_hash *h;
2277 hash = nf_ct_alloc_hashtable(&hashsize, 1);
2281 old_size = nf_conntrack_htable_size;
2282 if (old_size == hashsize) {
2288 nf_conntrack_all_lock();
2289 write_seqcount_begin(&nf_conntrack_generation);
2291 /* Lookups in the old hash might happen in parallel, which means we
2292 * might get false negatives during connection lookup. New connections
2293 * created because of a false negative won't make it into the hash
2294 * though since that required taking the locks.
2297 for (i = 0; i < nf_conntrack_htable_size; i++) {
2298 while (!hlist_nulls_empty(&nf_conntrack_hash[i])) {
2299 h = hlist_nulls_entry(nf_conntrack_hash[i].first,
2300 struct nf_conntrack_tuple_hash, hnnode);
2301 ct = nf_ct_tuplehash_to_ctrack(h);
2302 hlist_nulls_del_rcu(&h->hnnode);
2303 bucket = __hash_conntrack(nf_ct_net(ct),
2304 &h->tuple, hashsize);
2305 hlist_nulls_add_head_rcu(&h->hnnode, &hash[bucket]);
2308 old_size = nf_conntrack_htable_size;
2309 old_hash = nf_conntrack_hash;
2311 nf_conntrack_hash = hash;
2312 nf_conntrack_htable_size = hashsize;
2314 write_seqcount_end(&nf_conntrack_generation);
2315 nf_conntrack_all_unlock();
2323 int nf_conntrack_set_hashsize(const char *val, const struct kernel_param *kp)
2325 unsigned int hashsize;
2328 if (current->nsproxy->net_ns != &init_net)
2331 /* On boot, we can set this without any fancy locking. */
2332 if (!nf_conntrack_hash)
2333 return param_set_uint(val, kp);
2335 rc = kstrtouint(val, 0, &hashsize);
2339 return nf_conntrack_hash_resize(hashsize);
2341 EXPORT_SYMBOL_GPL(nf_conntrack_set_hashsize);
2343 static __always_inline unsigned int total_extension_size(void)
2345 /* remember to add new extensions below */
2346 BUILD_BUG_ON(NF_CT_EXT_NUM > 9);
2348 return sizeof(struct nf_ct_ext) +
2349 sizeof(struct nf_conn_help)
2350 #if IS_ENABLED(CONFIG_NF_NAT)
2351 + sizeof(struct nf_conn_nat)
2353 + sizeof(struct nf_conn_seqadj)
2354 + sizeof(struct nf_conn_acct)
2355 #ifdef CONFIG_NF_CONNTRACK_EVENTS
2356 + sizeof(struct nf_conntrack_ecache)
2358 #ifdef CONFIG_NF_CONNTRACK_TIMESTAMP
2359 + sizeof(struct nf_conn_tstamp)
2361 #ifdef CONFIG_NF_CONNTRACK_TIMEOUT
2362 + sizeof(struct nf_conn_timeout)
2364 #ifdef CONFIG_NF_CONNTRACK_LABELS
2365 + sizeof(struct nf_conn_labels)
2367 #if IS_ENABLED(CONFIG_NETFILTER_SYNPROXY)
2368 + sizeof(struct nf_conn_synproxy)
2373 int nf_conntrack_init_start(void)
2375 unsigned long nr_pages = totalram_pages();
2380 /* struct nf_ct_ext uses u8 to store offsets/size */
2381 BUILD_BUG_ON(total_extension_size() > 255u);
2383 seqcount_init(&nf_conntrack_generation);
2385 for (i = 0; i < CONNTRACK_LOCKS; i++)
2386 spin_lock_init(&nf_conntrack_locks[i]);
2388 if (!nf_conntrack_htable_size) {
2389 /* Idea from tcp.c: use 1/16384 of memory.
2390 * On i386: 32MB machine has 512 buckets.
2391 * >= 1GB machines have 16384 buckets.
2392 * >= 4GB machines have 65536 buckets.
2394 nf_conntrack_htable_size
2395 = (((nr_pages << PAGE_SHIFT) / 16384)
2396 / sizeof(struct hlist_head));
2397 if (nr_pages > (4 * (1024 * 1024 * 1024 / PAGE_SIZE)))
2398 nf_conntrack_htable_size = 65536;
2399 else if (nr_pages > (1024 * 1024 * 1024 / PAGE_SIZE))
2400 nf_conntrack_htable_size = 16384;
2401 if (nf_conntrack_htable_size < 32)
2402 nf_conntrack_htable_size = 32;
2404 /* Use a max. factor of four by default to get the same max as
2405 * with the old struct list_heads. When a table size is given
2406 * we use the old value of 8 to avoid reducing the max.
2411 nf_conntrack_hash = nf_ct_alloc_hashtable(&nf_conntrack_htable_size, 1);
2412 if (!nf_conntrack_hash)
2415 nf_conntrack_max = max_factor * nf_conntrack_htable_size;
2417 nf_conntrack_cachep = kmem_cache_create("nf_conntrack",
2418 sizeof(struct nf_conn),
2420 SLAB_TYPESAFE_BY_RCU | SLAB_HWCACHE_ALIGN, NULL);
2421 if (!nf_conntrack_cachep)
2424 ret = nf_conntrack_expect_init();
2428 ret = nf_conntrack_acct_init();
2432 ret = nf_conntrack_tstamp_init();
2436 ret = nf_conntrack_ecache_init();
2440 ret = nf_conntrack_timeout_init();
2444 ret = nf_conntrack_helper_init();
2448 ret = nf_conntrack_labels_init();
2452 ret = nf_conntrack_seqadj_init();
2456 ret = nf_conntrack_proto_init();
2460 conntrack_gc_work_init(&conntrack_gc_work);
2461 queue_delayed_work(system_power_efficient_wq, &conntrack_gc_work.dwork, HZ);
2466 nf_conntrack_seqadj_fini();
2468 nf_conntrack_labels_fini();
2470 nf_conntrack_helper_fini();
2472 nf_conntrack_timeout_fini();
2474 nf_conntrack_ecache_fini();
2476 nf_conntrack_tstamp_fini();
2478 nf_conntrack_acct_fini();
2480 nf_conntrack_expect_fini();
2482 kmem_cache_destroy(nf_conntrack_cachep);
2484 kvfree(nf_conntrack_hash);
2488 static struct nf_ct_hook nf_conntrack_hook = {
2489 .update = nf_conntrack_update,
2490 .destroy = destroy_conntrack,
2491 .get_tuple_skb = nf_conntrack_get_tuple_skb,
2494 void nf_conntrack_init_end(void)
2496 /* For use by REJECT target */
2497 RCU_INIT_POINTER(ip_ct_attach, nf_conntrack_attach);
2498 RCU_INIT_POINTER(nf_ct_hook, &nf_conntrack_hook);
2502 * We need to use special "null" values, not used in hash table
2504 #define UNCONFIRMED_NULLS_VAL ((1<<30)+0)
2505 #define DYING_NULLS_VAL ((1<<30)+1)
2506 #define TEMPLATE_NULLS_VAL ((1<<30)+2)
2508 int nf_conntrack_init_net(struct net *net)
2513 BUILD_BUG_ON(IP_CT_UNTRACKED == IP_CT_NUMBER);
2514 BUILD_BUG_ON_NOT_POWER_OF_2(CONNTRACK_LOCKS);
2515 atomic_set(&net->ct.count, 0);
2517 net->ct.pcpu_lists = alloc_percpu(struct ct_pcpu);
2518 if (!net->ct.pcpu_lists)
2521 for_each_possible_cpu(cpu) {
2522 struct ct_pcpu *pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
2524 spin_lock_init(&pcpu->lock);
2525 INIT_HLIST_NULLS_HEAD(&pcpu->unconfirmed, UNCONFIRMED_NULLS_VAL);
2526 INIT_HLIST_NULLS_HEAD(&pcpu->dying, DYING_NULLS_VAL);
2529 net->ct.stat = alloc_percpu(struct ip_conntrack_stat);
2531 goto err_pcpu_lists;
2533 ret = nf_conntrack_expect_pernet_init(net);
2537 nf_conntrack_acct_pernet_init(net);
2538 nf_conntrack_tstamp_pernet_init(net);
2539 nf_conntrack_ecache_pernet_init(net);
2540 nf_conntrack_helper_pernet_init(net);
2541 nf_conntrack_proto_pernet_init(net);
2546 free_percpu(net->ct.stat);
2548 free_percpu(net->ct.pcpu_lists);