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_l3proto.h>
41 #include <net/netfilter/nf_conntrack_l4proto.h>
42 #include <net/netfilter/nf_conntrack_expect.h>
43 #include <net/netfilter/nf_conntrack_helper.h>
44 #include <net/netfilter/nf_conntrack_seqadj.h>
45 #include <net/netfilter/nf_conntrack_core.h>
46 #include <net/netfilter/nf_conntrack_extend.h>
47 #include <net/netfilter/nf_conntrack_acct.h>
48 #include <net/netfilter/nf_conntrack_ecache.h>
49 #include <net/netfilter/nf_conntrack_zones.h>
50 #include <net/netfilter/nf_conntrack_timestamp.h>
51 #include <net/netfilter/nf_conntrack_timeout.h>
52 #include <net/netfilter/nf_conntrack_labels.h>
53 #include <net/netfilter/nf_conntrack_synproxy.h>
54 #include <net/netfilter/nf_nat.h>
55 #include <net/netfilter/nf_nat_core.h>
56 #include <net/netfilter/nf_nat_helper.h>
57 #include <net/netns/hash.h>
59 #define NF_CONNTRACK_VERSION "0.5.0"
61 int (*nfnetlink_parse_nat_setup_hook)(struct nf_conn *ct,
62 enum nf_nat_manip_type manip,
63 const struct nlattr *attr) __read_mostly;
64 EXPORT_SYMBOL_GPL(nfnetlink_parse_nat_setup_hook);
66 __cacheline_aligned_in_smp spinlock_t nf_conntrack_locks[CONNTRACK_LOCKS];
67 EXPORT_SYMBOL_GPL(nf_conntrack_locks);
69 __cacheline_aligned_in_smp DEFINE_SPINLOCK(nf_conntrack_expect_lock);
70 EXPORT_SYMBOL_GPL(nf_conntrack_expect_lock);
72 struct hlist_nulls_head *nf_conntrack_hash __read_mostly;
73 EXPORT_SYMBOL_GPL(nf_conntrack_hash);
75 struct conntrack_gc_work {
76 struct delayed_work dwork;
83 static __read_mostly struct kmem_cache *nf_conntrack_cachep;
84 static __read_mostly spinlock_t nf_conntrack_locks_all_lock;
85 static __read_mostly DEFINE_SPINLOCK(nf_conntrack_locks_all_lock);
86 static __read_mostly bool nf_conntrack_locks_all;
88 /* every gc cycle scans at most 1/GC_MAX_BUCKETS_DIV part of table */
89 #define GC_MAX_BUCKETS_DIV 128u
90 /* upper bound of full table scan */
91 #define GC_MAX_SCAN_JIFFIES (16u * HZ)
92 /* desired ratio of entries found to be expired */
93 #define GC_EVICT_RATIO 50u
95 static struct conntrack_gc_work conntrack_gc_work;
97 void nf_conntrack_lock(spinlock_t *lock) __acquires(lock)
100 while (unlikely(nf_conntrack_locks_all)) {
104 * Order the 'nf_conntrack_locks_all' load vs. the
105 * spin_unlock_wait() loads below, to ensure
106 * that 'nf_conntrack_locks_all_lock' is indeed held:
108 smp_rmb(); /* spin_lock(&nf_conntrack_locks_all_lock) */
109 spin_unlock_wait(&nf_conntrack_locks_all_lock);
113 EXPORT_SYMBOL_GPL(nf_conntrack_lock);
115 static void nf_conntrack_double_unlock(unsigned int h1, unsigned int h2)
117 h1 %= CONNTRACK_LOCKS;
118 h2 %= CONNTRACK_LOCKS;
119 spin_unlock(&nf_conntrack_locks[h1]);
121 spin_unlock(&nf_conntrack_locks[h2]);
124 /* return true if we need to recompute hashes (in case hash table was resized) */
125 static bool nf_conntrack_double_lock(struct net *net, unsigned int h1,
126 unsigned int h2, unsigned int sequence)
128 h1 %= CONNTRACK_LOCKS;
129 h2 %= CONNTRACK_LOCKS;
131 nf_conntrack_lock(&nf_conntrack_locks[h1]);
133 spin_lock_nested(&nf_conntrack_locks[h2],
134 SINGLE_DEPTH_NESTING);
136 nf_conntrack_lock(&nf_conntrack_locks[h2]);
137 spin_lock_nested(&nf_conntrack_locks[h1],
138 SINGLE_DEPTH_NESTING);
140 if (read_seqcount_retry(&nf_conntrack_generation, sequence)) {
141 nf_conntrack_double_unlock(h1, h2);
147 static void nf_conntrack_all_lock(void)
151 spin_lock(&nf_conntrack_locks_all_lock);
152 nf_conntrack_locks_all = true;
155 * Order the above store of 'nf_conntrack_locks_all' against
156 * the spin_unlock_wait() loads below, such that if
157 * nf_conntrack_lock() observes 'nf_conntrack_locks_all'
158 * we must observe nf_conntrack_locks[] held:
160 smp_mb(); /* spin_lock(&nf_conntrack_locks_all_lock) */
162 for (i = 0; i < CONNTRACK_LOCKS; i++) {
163 spin_unlock_wait(&nf_conntrack_locks[i]);
167 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
175 smp_store_release(&nf_conntrack_locks_all, false);
176 spin_unlock(&nf_conntrack_locks_all_lock);
179 unsigned int nf_conntrack_htable_size __read_mostly;
180 EXPORT_SYMBOL_GPL(nf_conntrack_htable_size);
182 unsigned int nf_conntrack_max __read_mostly;
183 seqcount_t nf_conntrack_generation __read_mostly;
184 static unsigned int nf_conntrack_hash_rnd __read_mostly;
186 static u32 hash_conntrack_raw(const struct nf_conntrack_tuple *tuple,
187 const struct net *net)
192 get_random_once(&nf_conntrack_hash_rnd, sizeof(nf_conntrack_hash_rnd));
194 /* The direction must be ignored, so we hash everything up to the
195 * destination ports (which is a multiple of 4) and treat the last
196 * three bytes manually.
198 seed = nf_conntrack_hash_rnd ^ net_hash_mix(net);
199 n = (sizeof(tuple->src) + sizeof(tuple->dst.u3)) / sizeof(u32);
200 return jhash2((u32 *)tuple, n, seed ^
201 (((__force __u16)tuple->dst.u.all << 16) |
202 tuple->dst.protonum));
205 static u32 scale_hash(u32 hash)
207 return reciprocal_scale(hash, nf_conntrack_htable_size);
210 static u32 __hash_conntrack(const struct net *net,
211 const struct nf_conntrack_tuple *tuple,
214 return reciprocal_scale(hash_conntrack_raw(tuple, net), size);
217 static u32 hash_conntrack(const struct net *net,
218 const struct nf_conntrack_tuple *tuple)
220 return scale_hash(hash_conntrack_raw(tuple, net));
224 nf_ct_get_tuple(const struct sk_buff *skb,
226 unsigned int dataoff,
230 struct nf_conntrack_tuple *tuple,
231 const struct nf_conntrack_l3proto *l3proto,
232 const struct nf_conntrack_l4proto *l4proto)
234 memset(tuple, 0, sizeof(*tuple));
236 tuple->src.l3num = l3num;
237 if (l3proto->pkt_to_tuple(skb, nhoff, tuple) == 0)
240 tuple->dst.protonum = protonum;
241 tuple->dst.dir = IP_CT_DIR_ORIGINAL;
243 return l4proto->pkt_to_tuple(skb, dataoff, net, tuple);
245 EXPORT_SYMBOL_GPL(nf_ct_get_tuple);
247 bool nf_ct_get_tuplepr(const struct sk_buff *skb, unsigned int nhoff,
249 struct net *net, struct nf_conntrack_tuple *tuple)
251 struct nf_conntrack_l3proto *l3proto;
252 struct nf_conntrack_l4proto *l4proto;
253 unsigned int protoff;
259 l3proto = __nf_ct_l3proto_find(l3num);
260 ret = l3proto->get_l4proto(skb, nhoff, &protoff, &protonum);
261 if (ret != NF_ACCEPT) {
266 l4proto = __nf_ct_l4proto_find(l3num, protonum);
268 ret = nf_ct_get_tuple(skb, nhoff, protoff, l3num, protonum, net, tuple,
274 EXPORT_SYMBOL_GPL(nf_ct_get_tuplepr);
277 nf_ct_invert_tuple(struct nf_conntrack_tuple *inverse,
278 const struct nf_conntrack_tuple *orig,
279 const struct nf_conntrack_l3proto *l3proto,
280 const struct nf_conntrack_l4proto *l4proto)
282 memset(inverse, 0, sizeof(*inverse));
284 inverse->src.l3num = orig->src.l3num;
285 if (l3proto->invert_tuple(inverse, orig) == 0)
288 inverse->dst.dir = !orig->dst.dir;
290 inverse->dst.protonum = orig->dst.protonum;
291 return l4proto->invert_tuple(inverse, orig);
293 EXPORT_SYMBOL_GPL(nf_ct_invert_tuple);
296 clean_from_lists(struct nf_conn *ct)
298 pr_debug("clean_from_lists(%p)\n", ct);
299 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
300 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode);
302 /* Destroy all pending expectations */
303 nf_ct_remove_expectations(ct);
306 /* must be called with local_bh_disable */
307 static void nf_ct_add_to_dying_list(struct nf_conn *ct)
309 struct ct_pcpu *pcpu;
311 /* add this conntrack to the (per cpu) dying list */
312 ct->cpu = smp_processor_id();
313 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
315 spin_lock(&pcpu->lock);
316 hlist_nulls_add_head(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
318 spin_unlock(&pcpu->lock);
321 /* must be called with local_bh_disable */
322 static void nf_ct_add_to_unconfirmed_list(struct nf_conn *ct)
324 struct ct_pcpu *pcpu;
326 /* add this conntrack to the (per cpu) unconfirmed list */
327 ct->cpu = smp_processor_id();
328 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
330 spin_lock(&pcpu->lock);
331 hlist_nulls_add_head(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
333 spin_unlock(&pcpu->lock);
336 /* must be called with local_bh_disable */
337 static void nf_ct_del_from_dying_or_unconfirmed_list(struct nf_conn *ct)
339 struct ct_pcpu *pcpu;
341 /* We overload first tuple to link into unconfirmed or dying list.*/
342 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
344 spin_lock(&pcpu->lock);
345 BUG_ON(hlist_nulls_unhashed(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode));
346 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
347 spin_unlock(&pcpu->lock);
350 #define NFCT_ALIGN(len) (((len) + NFCT_INFOMASK) & ~NFCT_INFOMASK)
352 /* Released via destroy_conntrack() */
353 struct nf_conn *nf_ct_tmpl_alloc(struct net *net,
354 const struct nf_conntrack_zone *zone,
357 struct nf_conn *tmpl, *p;
359 if (ARCH_KMALLOC_MINALIGN <= NFCT_INFOMASK) {
360 tmpl = kzalloc(sizeof(*tmpl) + NFCT_INFOMASK, flags);
365 tmpl = (struct nf_conn *)NFCT_ALIGN((unsigned long)p);
367 tmpl = (struct nf_conn *)NFCT_ALIGN((unsigned long)p);
368 tmpl->proto.tmpl_padto = (char *)tmpl - (char *)p;
371 tmpl = kzalloc(sizeof(*tmpl), flags);
376 tmpl->status = IPS_TEMPLATE;
377 write_pnet(&tmpl->ct_net, net);
378 nf_ct_zone_add(tmpl, zone);
379 atomic_set(&tmpl->ct_general.use, 0);
383 EXPORT_SYMBOL_GPL(nf_ct_tmpl_alloc);
385 void nf_ct_tmpl_free(struct nf_conn *tmpl)
387 nf_ct_ext_destroy(tmpl);
388 nf_ct_ext_free(tmpl);
390 if (ARCH_KMALLOC_MINALIGN <= NFCT_INFOMASK)
391 kfree((char *)tmpl - tmpl->proto.tmpl_padto);
395 EXPORT_SYMBOL_GPL(nf_ct_tmpl_free);
398 destroy_conntrack(struct nf_conntrack *nfct)
400 struct nf_conn *ct = (struct nf_conn *)nfct;
401 struct nf_conntrack_l4proto *l4proto;
403 pr_debug("destroy_conntrack(%p)\n", ct);
404 NF_CT_ASSERT(atomic_read(&nfct->use) == 0);
406 if (unlikely(nf_ct_is_template(ct))) {
411 l4proto = __nf_ct_l4proto_find(nf_ct_l3num(ct), nf_ct_protonum(ct));
412 if (l4proto->destroy)
413 l4proto->destroy(ct);
418 /* Expectations will have been removed in clean_from_lists,
419 * except TFTP can create an expectation on the first packet,
420 * before connection is in the list, so we need to clean here,
423 nf_ct_remove_expectations(ct);
425 nf_ct_del_from_dying_or_unconfirmed_list(ct);
430 nf_ct_put(ct->master);
432 pr_debug("destroy_conntrack: returning ct=%p to slab\n", ct);
433 nf_conntrack_free(ct);
436 static void nf_ct_delete_from_lists(struct nf_conn *ct)
438 struct net *net = nf_ct_net(ct);
439 unsigned int hash, reply_hash;
440 unsigned int sequence;
442 nf_ct_helper_destroy(ct);
446 sequence = read_seqcount_begin(&nf_conntrack_generation);
447 hash = hash_conntrack(net,
448 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
449 reply_hash = hash_conntrack(net,
450 &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
451 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
453 clean_from_lists(ct);
454 nf_conntrack_double_unlock(hash, reply_hash);
456 nf_ct_add_to_dying_list(ct);
461 bool nf_ct_delete(struct nf_conn *ct, u32 portid, int report)
463 struct nf_conn_tstamp *tstamp;
465 if (test_and_set_bit(IPS_DYING_BIT, &ct->status))
468 tstamp = nf_conn_tstamp_find(ct);
469 if (tstamp && tstamp->stop == 0)
470 tstamp->stop = ktime_get_real_ns();
472 if (nf_conntrack_event_report(IPCT_DESTROY, ct,
473 portid, report) < 0) {
474 /* destroy event was not delivered. nf_ct_put will
475 * be done by event cache worker on redelivery.
477 nf_ct_delete_from_lists(ct);
478 nf_conntrack_ecache_delayed_work(nf_ct_net(ct));
482 nf_conntrack_ecache_work(nf_ct_net(ct));
483 nf_ct_delete_from_lists(ct);
487 EXPORT_SYMBOL_GPL(nf_ct_delete);
490 nf_ct_key_equal(struct nf_conntrack_tuple_hash *h,
491 const struct nf_conntrack_tuple *tuple,
492 const struct nf_conntrack_zone *zone,
493 const struct net *net)
495 struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
497 /* A conntrack can be recreated with the equal tuple,
498 * so we need to check that the conntrack is confirmed
500 return nf_ct_tuple_equal(tuple, &h->tuple) &&
501 nf_ct_zone_equal(ct, zone, NF_CT_DIRECTION(h)) &&
502 nf_ct_is_confirmed(ct) &&
503 net_eq(net, nf_ct_net(ct));
506 /* caller must hold rcu readlock and none of the nf_conntrack_locks */
507 static void nf_ct_gc_expired(struct nf_conn *ct)
509 if (!atomic_inc_not_zero(&ct->ct_general.use))
512 if (nf_ct_should_gc(ct))
520 * - Caller must take a reference on returned object
521 * and recheck nf_ct_tuple_equal(tuple, &h->tuple)
523 static struct nf_conntrack_tuple_hash *
524 ____nf_conntrack_find(struct net *net, const struct nf_conntrack_zone *zone,
525 const struct nf_conntrack_tuple *tuple, u32 hash)
527 struct nf_conntrack_tuple_hash *h;
528 struct hlist_nulls_head *ct_hash;
529 struct hlist_nulls_node *n;
530 unsigned int bucket, hsize;
533 nf_conntrack_get_ht(&ct_hash, &hsize);
534 bucket = reciprocal_scale(hash, hsize);
536 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[bucket], hnnode) {
539 ct = nf_ct_tuplehash_to_ctrack(h);
540 if (nf_ct_is_expired(ct)) {
541 nf_ct_gc_expired(ct);
545 if (nf_ct_is_dying(ct))
548 if (nf_ct_key_equal(h, tuple, zone, net))
552 * if the nulls value we got at the end of this lookup is
553 * not the expected one, we must restart lookup.
554 * We probably met an item that was moved to another chain.
556 if (get_nulls_value(n) != bucket) {
557 NF_CT_STAT_INC_ATOMIC(net, search_restart);
564 /* Find a connection corresponding to a tuple. */
565 static struct nf_conntrack_tuple_hash *
566 __nf_conntrack_find_get(struct net *net, const struct nf_conntrack_zone *zone,
567 const struct nf_conntrack_tuple *tuple, u32 hash)
569 struct nf_conntrack_tuple_hash *h;
574 h = ____nf_conntrack_find(net, zone, tuple, hash);
576 ct = nf_ct_tuplehash_to_ctrack(h);
577 if (unlikely(nf_ct_is_dying(ct) ||
578 !atomic_inc_not_zero(&ct->ct_general.use)))
581 if (unlikely(!nf_ct_key_equal(h, tuple, zone, net))) {
592 struct nf_conntrack_tuple_hash *
593 nf_conntrack_find_get(struct net *net, const struct nf_conntrack_zone *zone,
594 const struct nf_conntrack_tuple *tuple)
596 return __nf_conntrack_find_get(net, zone, tuple,
597 hash_conntrack_raw(tuple, net));
599 EXPORT_SYMBOL_GPL(nf_conntrack_find_get);
601 static void __nf_conntrack_hash_insert(struct nf_conn *ct,
603 unsigned int reply_hash)
605 hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
606 &nf_conntrack_hash[hash]);
607 hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode,
608 &nf_conntrack_hash[reply_hash]);
612 nf_conntrack_hash_check_insert(struct nf_conn *ct)
614 const struct nf_conntrack_zone *zone;
615 struct net *net = nf_ct_net(ct);
616 unsigned int hash, reply_hash;
617 struct nf_conntrack_tuple_hash *h;
618 struct hlist_nulls_node *n;
619 unsigned int sequence;
621 zone = nf_ct_zone(ct);
625 sequence = read_seqcount_begin(&nf_conntrack_generation);
626 hash = hash_conntrack(net,
627 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
628 reply_hash = hash_conntrack(net,
629 &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
630 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
632 /* See if there's one in the list already, including reverse */
633 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode)
634 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
638 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode)
639 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
644 /* The caller holds a reference to this object */
645 atomic_set(&ct->ct_general.use, 2);
646 __nf_conntrack_hash_insert(ct, hash, reply_hash);
647 nf_conntrack_double_unlock(hash, reply_hash);
648 NF_CT_STAT_INC(net, insert);
653 nf_conntrack_double_unlock(hash, reply_hash);
654 NF_CT_STAT_INC(net, insert_failed);
658 EXPORT_SYMBOL_GPL(nf_conntrack_hash_check_insert);
660 static inline void nf_ct_acct_update(struct nf_conn *ct,
661 enum ip_conntrack_info ctinfo,
664 struct nf_conn_acct *acct;
666 acct = nf_conn_acct_find(ct);
668 struct nf_conn_counter *counter = acct->counter;
670 atomic64_inc(&counter[CTINFO2DIR(ctinfo)].packets);
671 atomic64_add(len, &counter[CTINFO2DIR(ctinfo)].bytes);
675 static void nf_ct_acct_merge(struct nf_conn *ct, enum ip_conntrack_info ctinfo,
676 const struct nf_conn *loser_ct)
678 struct nf_conn_acct *acct;
680 acct = nf_conn_acct_find(loser_ct);
682 struct nf_conn_counter *counter = acct->counter;
685 /* u32 should be fine since we must have seen one packet. */
686 bytes = atomic64_read(&counter[CTINFO2DIR(ctinfo)].bytes);
687 nf_ct_acct_update(ct, ctinfo, bytes);
691 /* Resolve race on insertion if this protocol allows this. */
692 static int nf_ct_resolve_clash(struct net *net, struct sk_buff *skb,
693 enum ip_conntrack_info ctinfo,
694 struct nf_conntrack_tuple_hash *h)
696 /* This is the conntrack entry already in hashes that won race. */
697 struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
698 struct nf_conntrack_l4proto *l4proto;
700 l4proto = __nf_ct_l4proto_find(nf_ct_l3num(ct), nf_ct_protonum(ct));
701 if (l4proto->allow_clash &&
702 ((ct->status & IPS_NAT_DONE_MASK) == 0) &&
703 !nf_ct_is_dying(ct) &&
704 atomic_inc_not_zero(&ct->ct_general.use)) {
705 enum ip_conntrack_info oldinfo;
706 struct nf_conn *loser_ct = nf_ct_get(skb, &oldinfo);
708 nf_ct_acct_merge(ct, ctinfo, loser_ct);
709 nf_conntrack_put(&loser_ct->ct_general);
710 nf_ct_set(skb, ct, oldinfo);
713 NF_CT_STAT_INC(net, drop);
717 /* Confirm a connection given skb; places it in hash table */
719 __nf_conntrack_confirm(struct sk_buff *skb)
721 const struct nf_conntrack_zone *zone;
722 unsigned int hash, reply_hash;
723 struct nf_conntrack_tuple_hash *h;
725 struct nf_conn_help *help;
726 struct nf_conn_tstamp *tstamp;
727 struct hlist_nulls_node *n;
728 enum ip_conntrack_info ctinfo;
730 unsigned int sequence;
733 ct = nf_ct_get(skb, &ctinfo);
736 /* ipt_REJECT uses nf_conntrack_attach to attach related
737 ICMP/TCP RST packets in other direction. Actual packet
738 which created connection will be IP_CT_NEW or for an
739 expected connection, IP_CT_RELATED. */
740 if (CTINFO2DIR(ctinfo) != IP_CT_DIR_ORIGINAL)
743 zone = nf_ct_zone(ct);
747 sequence = read_seqcount_begin(&nf_conntrack_generation);
748 /* reuse the hash saved before */
749 hash = *(unsigned long *)&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev;
750 hash = scale_hash(hash);
751 reply_hash = hash_conntrack(net,
752 &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
754 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
756 /* We're not in hash table, and we refuse to set up related
757 * connections for unconfirmed conns. But packet copies and
758 * REJECT will give spurious warnings here.
760 /* NF_CT_ASSERT(atomic_read(&ct->ct_general.use) == 1); */
762 /* No external references means no one else could have
765 NF_CT_ASSERT(!nf_ct_is_confirmed(ct));
766 pr_debug("Confirming conntrack %p\n", ct);
767 /* We have to check the DYING flag after unlink to prevent
768 * a race against nf_ct_get_next_corpse() possibly called from
769 * user context, else we insert an already 'dead' hash, blocking
770 * further use of that particular connection -JM.
772 nf_ct_del_from_dying_or_unconfirmed_list(ct);
774 if (unlikely(nf_ct_is_dying(ct))) {
775 nf_ct_add_to_dying_list(ct);
779 /* See if there's one in the list already, including reverse:
780 NAT could have grabbed it without realizing, since we're
781 not in the hash. If there is, we lost race. */
782 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode)
783 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
787 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode)
788 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
792 /* Timer relative to confirmation time, not original
793 setting time, otherwise we'd get timer wrap in
794 weird delay cases. */
795 ct->timeout += nfct_time_stamp;
796 atomic_inc(&ct->ct_general.use);
797 ct->status |= IPS_CONFIRMED;
799 /* set conntrack timestamp, if enabled. */
800 tstamp = nf_conn_tstamp_find(ct);
802 if (skb->tstamp == 0)
803 __net_timestamp(skb);
805 tstamp->start = ktime_to_ns(skb->tstamp);
807 /* Since the lookup is lockless, hash insertion must be done after
808 * starting the timer and setting the CONFIRMED bit. The RCU barriers
809 * guarantee that no other CPU can find the conntrack before the above
810 * stores are visible.
812 __nf_conntrack_hash_insert(ct, hash, reply_hash);
813 nf_conntrack_double_unlock(hash, reply_hash);
816 help = nfct_help(ct);
817 if (help && help->helper)
818 nf_conntrack_event_cache(IPCT_HELPER, ct);
820 nf_conntrack_event_cache(master_ct(ct) ?
821 IPCT_RELATED : IPCT_NEW, ct);
825 nf_ct_add_to_dying_list(ct);
826 ret = nf_ct_resolve_clash(net, skb, ctinfo, h);
828 nf_conntrack_double_unlock(hash, reply_hash);
829 NF_CT_STAT_INC(net, insert_failed);
833 EXPORT_SYMBOL_GPL(__nf_conntrack_confirm);
835 /* Returns true if a connection correspondings to the tuple (required
838 nf_conntrack_tuple_taken(const struct nf_conntrack_tuple *tuple,
839 const struct nf_conn *ignored_conntrack)
841 struct net *net = nf_ct_net(ignored_conntrack);
842 const struct nf_conntrack_zone *zone;
843 struct nf_conntrack_tuple_hash *h;
844 struct hlist_nulls_head *ct_hash;
845 unsigned int hash, hsize;
846 struct hlist_nulls_node *n;
849 zone = nf_ct_zone(ignored_conntrack);
853 nf_conntrack_get_ht(&ct_hash, &hsize);
854 hash = __hash_conntrack(net, tuple, hsize);
856 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[hash], hnnode) {
857 ct = nf_ct_tuplehash_to_ctrack(h);
859 if (ct == ignored_conntrack)
862 if (nf_ct_is_expired(ct)) {
863 nf_ct_gc_expired(ct);
867 if (nf_ct_key_equal(h, tuple, zone, net)) {
868 NF_CT_STAT_INC_ATOMIC(net, found);
874 if (get_nulls_value(n) != hash) {
875 NF_CT_STAT_INC_ATOMIC(net, search_restart);
883 EXPORT_SYMBOL_GPL(nf_conntrack_tuple_taken);
885 #define NF_CT_EVICTION_RANGE 8
887 /* There's a small race here where we may free a just-assured
888 connection. Too bad: we're in trouble anyway. */
889 static unsigned int early_drop_list(struct net *net,
890 struct hlist_nulls_head *head)
892 struct nf_conntrack_tuple_hash *h;
893 struct hlist_nulls_node *n;
894 unsigned int drops = 0;
897 hlist_nulls_for_each_entry_rcu(h, n, head, hnnode) {
898 tmp = nf_ct_tuplehash_to_ctrack(h);
900 if (nf_ct_is_expired(tmp)) {
901 nf_ct_gc_expired(tmp);
905 if (test_bit(IPS_ASSURED_BIT, &tmp->status) ||
906 !net_eq(nf_ct_net(tmp), net) ||
910 if (!atomic_inc_not_zero(&tmp->ct_general.use))
913 /* kill only if still in same netns -- might have moved due to
914 * SLAB_DESTROY_BY_RCU rules.
916 * We steal the timer reference. If that fails timer has
917 * already fired or someone else deleted it. Just drop ref
918 * and move to next entry.
920 if (net_eq(nf_ct_net(tmp), net) &&
921 nf_ct_is_confirmed(tmp) &&
922 nf_ct_delete(tmp, 0, 0))
931 static noinline int early_drop(struct net *net, unsigned int _hash)
935 for (i = 0; i < NF_CT_EVICTION_RANGE; i++) {
936 struct hlist_nulls_head *ct_hash;
937 unsigned int hash, hsize, drops;
940 nf_conntrack_get_ht(&ct_hash, &hsize);
941 hash = reciprocal_scale(_hash++, hsize);
943 drops = early_drop_list(net, &ct_hash[hash]);
947 NF_CT_STAT_ADD_ATOMIC(net, early_drop, drops);
955 static bool gc_worker_skip_ct(const struct nf_conn *ct)
957 return !nf_ct_is_confirmed(ct) || nf_ct_is_dying(ct);
960 static bool gc_worker_can_early_drop(const struct nf_conn *ct)
962 const struct nf_conntrack_l4proto *l4proto;
964 if (!test_bit(IPS_ASSURED_BIT, &ct->status))
967 l4proto = __nf_ct_l4proto_find(nf_ct_l3num(ct), nf_ct_protonum(ct));
968 if (l4proto->can_early_drop && l4proto->can_early_drop(ct))
974 static void gc_worker(struct work_struct *work)
976 unsigned int min_interval = max(HZ / GC_MAX_BUCKETS_DIV, 1u);
977 unsigned int i, goal, buckets = 0, expired_count = 0;
978 unsigned int nf_conntrack_max95 = 0;
979 struct conntrack_gc_work *gc_work;
980 unsigned int ratio, scanned = 0;
981 unsigned long next_run;
983 gc_work = container_of(work, struct conntrack_gc_work, dwork.work);
985 goal = nf_conntrack_htable_size / GC_MAX_BUCKETS_DIV;
986 i = gc_work->last_bucket;
987 if (gc_work->early_drop)
988 nf_conntrack_max95 = nf_conntrack_max / 100u * 95u;
991 struct nf_conntrack_tuple_hash *h;
992 struct hlist_nulls_head *ct_hash;
993 struct hlist_nulls_node *n;
1000 nf_conntrack_get_ht(&ct_hash, &hashsz);
1004 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[i], hnnode) {
1007 tmp = nf_ct_tuplehash_to_ctrack(h);
1010 if (nf_ct_is_expired(tmp)) {
1011 nf_ct_gc_expired(tmp);
1016 if (nf_conntrack_max95 == 0 || gc_worker_skip_ct(tmp))
1019 net = nf_ct_net(tmp);
1020 if (atomic_read(&net->ct.count) < nf_conntrack_max95)
1023 /* need to take reference to avoid possible races */
1024 if (!atomic_inc_not_zero(&tmp->ct_general.use))
1027 if (gc_worker_skip_ct(tmp)) {
1032 if (gc_worker_can_early_drop(tmp))
1038 /* could check get_nulls_value() here and restart if ct
1039 * was moved to another chain. But given gc is best-effort
1040 * we will just continue with next hash slot.
1043 cond_resched_rcu_qs();
1044 } while (++buckets < goal);
1046 if (gc_work->exiting)
1050 * Eviction will normally happen from the packet path, and not
1051 * from this gc worker.
1053 * This worker is only here to reap expired entries when system went
1054 * idle after a busy period.
1056 * The heuristics below are supposed to balance conflicting goals:
1058 * 1. Minimize time until we notice a stale entry
1059 * 2. Maximize scan intervals to not waste cycles
1061 * Normally, expire ratio will be close to 0.
1063 * As soon as a sizeable fraction of the entries have expired
1064 * increase scan frequency.
1066 ratio = scanned ? expired_count * 100 / scanned : 0;
1067 if (ratio > GC_EVICT_RATIO) {
1068 gc_work->next_gc_run = min_interval;
1070 unsigned int max = GC_MAX_SCAN_JIFFIES / GC_MAX_BUCKETS_DIV;
1072 BUILD_BUG_ON((GC_MAX_SCAN_JIFFIES / GC_MAX_BUCKETS_DIV) == 0);
1074 gc_work->next_gc_run += min_interval;
1075 if (gc_work->next_gc_run > max)
1076 gc_work->next_gc_run = max;
1079 next_run = gc_work->next_gc_run;
1080 gc_work->last_bucket = i;
1081 gc_work->early_drop = false;
1082 queue_delayed_work(system_long_wq, &gc_work->dwork, next_run);
1085 static void conntrack_gc_work_init(struct conntrack_gc_work *gc_work)
1087 INIT_DELAYED_WORK(&gc_work->dwork, gc_worker);
1088 gc_work->next_gc_run = HZ;
1089 gc_work->exiting = false;
1092 static struct nf_conn *
1093 __nf_conntrack_alloc(struct net *net,
1094 const struct nf_conntrack_zone *zone,
1095 const struct nf_conntrack_tuple *orig,
1096 const struct nf_conntrack_tuple *repl,
1097 gfp_t gfp, u32 hash)
1101 /* We don't want any race condition at early drop stage */
1102 atomic_inc(&net->ct.count);
1104 if (nf_conntrack_max &&
1105 unlikely(atomic_read(&net->ct.count) > nf_conntrack_max)) {
1106 if (!early_drop(net, hash)) {
1107 if (!conntrack_gc_work.early_drop)
1108 conntrack_gc_work.early_drop = true;
1109 atomic_dec(&net->ct.count);
1110 net_warn_ratelimited("nf_conntrack: table full, dropping packet\n");
1111 return ERR_PTR(-ENOMEM);
1116 * Do not use kmem_cache_zalloc(), as this cache uses
1117 * SLAB_DESTROY_BY_RCU.
1119 ct = kmem_cache_alloc(nf_conntrack_cachep, gfp);
1123 spin_lock_init(&ct->lock);
1124 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple = *orig;
1125 ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode.pprev = NULL;
1126 ct->tuplehash[IP_CT_DIR_REPLY].tuple = *repl;
1127 /* save hash for reusing when confirming */
1128 *(unsigned long *)(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev) = hash;
1130 write_pnet(&ct->ct_net, net);
1131 memset(&ct->__nfct_init_offset[0], 0,
1132 offsetof(struct nf_conn, proto) -
1133 offsetof(struct nf_conn, __nfct_init_offset[0]));
1135 nf_ct_zone_add(ct, zone);
1137 /* Because we use RCU lookups, we set ct_general.use to zero before
1138 * this is inserted in any list.
1140 atomic_set(&ct->ct_general.use, 0);
1143 atomic_dec(&net->ct.count);
1144 return ERR_PTR(-ENOMEM);
1147 struct nf_conn *nf_conntrack_alloc(struct net *net,
1148 const struct nf_conntrack_zone *zone,
1149 const struct nf_conntrack_tuple *orig,
1150 const struct nf_conntrack_tuple *repl,
1153 return __nf_conntrack_alloc(net, zone, orig, repl, gfp, 0);
1155 EXPORT_SYMBOL_GPL(nf_conntrack_alloc);
1157 void nf_conntrack_free(struct nf_conn *ct)
1159 struct net *net = nf_ct_net(ct);
1161 /* A freed object has refcnt == 0, that's
1162 * the golden rule for SLAB_DESTROY_BY_RCU
1164 NF_CT_ASSERT(atomic_read(&ct->ct_general.use) == 0);
1166 nf_ct_ext_destroy(ct);
1168 kmem_cache_free(nf_conntrack_cachep, ct);
1169 smp_mb__before_atomic();
1170 atomic_dec(&net->ct.count);
1172 EXPORT_SYMBOL_GPL(nf_conntrack_free);
1175 /* Allocate a new conntrack: we return -ENOMEM if classification
1176 failed due to stress. Otherwise it really is unclassifiable. */
1177 static noinline struct nf_conntrack_tuple_hash *
1178 init_conntrack(struct net *net, struct nf_conn *tmpl,
1179 const struct nf_conntrack_tuple *tuple,
1180 struct nf_conntrack_l3proto *l3proto,
1181 struct nf_conntrack_l4proto *l4proto,
1182 struct sk_buff *skb,
1183 unsigned int dataoff, u32 hash)
1186 struct nf_conn_help *help;
1187 struct nf_conntrack_tuple repl_tuple;
1188 struct nf_conntrack_ecache *ecache;
1189 struct nf_conntrack_expect *exp = NULL;
1190 const struct nf_conntrack_zone *zone;
1191 struct nf_conn_timeout *timeout_ext;
1192 struct nf_conntrack_zone tmp;
1193 unsigned int *timeouts;
1195 if (!nf_ct_invert_tuple(&repl_tuple, tuple, l3proto, l4proto)) {
1196 pr_debug("Can't invert tuple.\n");
1200 zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1201 ct = __nf_conntrack_alloc(net, zone, tuple, &repl_tuple, GFP_ATOMIC,
1204 return (struct nf_conntrack_tuple_hash *)ct;
1206 if (!nf_ct_add_synproxy(ct, tmpl)) {
1207 nf_conntrack_free(ct);
1208 return ERR_PTR(-ENOMEM);
1211 timeout_ext = tmpl ? nf_ct_timeout_find(tmpl) : NULL;
1213 timeouts = nf_ct_timeout_data(timeout_ext);
1214 if (unlikely(!timeouts))
1215 timeouts = l4proto->get_timeouts(net);
1217 timeouts = l4proto->get_timeouts(net);
1220 if (!l4proto->new(ct, skb, dataoff, timeouts)) {
1221 nf_conntrack_free(ct);
1222 pr_debug("can't track with proto module\n");
1227 nf_ct_timeout_ext_add(ct, rcu_dereference(timeout_ext->timeout),
1230 nf_ct_acct_ext_add(ct, GFP_ATOMIC);
1231 nf_ct_tstamp_ext_add(ct, GFP_ATOMIC);
1232 nf_ct_labels_ext_add(ct);
1234 ecache = tmpl ? nf_ct_ecache_find(tmpl) : NULL;
1235 nf_ct_ecache_ext_add(ct, ecache ? ecache->ctmask : 0,
1236 ecache ? ecache->expmask : 0,
1240 if (net->ct.expect_count) {
1241 spin_lock(&nf_conntrack_expect_lock);
1242 exp = nf_ct_find_expectation(net, zone, tuple);
1244 pr_debug("expectation arrives ct=%p exp=%p\n",
1246 /* Welcome, Mr. Bond. We've been expecting you... */
1247 __set_bit(IPS_EXPECTED_BIT, &ct->status);
1248 /* exp->master safe, refcnt bumped in nf_ct_find_expectation */
1249 ct->master = exp->master;
1251 help = nf_ct_helper_ext_add(ct, exp->helper,
1254 rcu_assign_pointer(help->helper, exp->helper);
1257 #ifdef CONFIG_NF_CONNTRACK_MARK
1258 ct->mark = exp->master->mark;
1260 #ifdef CONFIG_NF_CONNTRACK_SECMARK
1261 ct->secmark = exp->master->secmark;
1263 NF_CT_STAT_INC(net, expect_new);
1265 spin_unlock(&nf_conntrack_expect_lock);
1268 __nf_ct_try_assign_helper(ct, tmpl, GFP_ATOMIC);
1270 /* Now it is inserted into the unconfirmed list, bump refcount */
1271 nf_conntrack_get(&ct->ct_general);
1272 nf_ct_add_to_unconfirmed_list(ct);
1278 exp->expectfn(ct, exp);
1279 nf_ct_expect_put(exp);
1282 return &ct->tuplehash[IP_CT_DIR_ORIGINAL];
1285 /* On success, returns 0, sets skb->_nfct | ctinfo */
1287 resolve_normal_ct(struct net *net, struct nf_conn *tmpl,
1288 struct sk_buff *skb,
1289 unsigned int dataoff,
1292 struct nf_conntrack_l3proto *l3proto,
1293 struct nf_conntrack_l4proto *l4proto)
1295 const struct nf_conntrack_zone *zone;
1296 struct nf_conntrack_tuple tuple;
1297 struct nf_conntrack_tuple_hash *h;
1298 enum ip_conntrack_info ctinfo;
1299 struct nf_conntrack_zone tmp;
1303 if (!nf_ct_get_tuple(skb, skb_network_offset(skb),
1304 dataoff, l3num, protonum, net, &tuple, l3proto,
1306 pr_debug("Can't get tuple\n");
1310 /* look for tuple match */
1311 zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1312 hash = hash_conntrack_raw(&tuple, net);
1313 h = __nf_conntrack_find_get(net, zone, &tuple, hash);
1315 h = init_conntrack(net, tmpl, &tuple, l3proto, l4proto,
1316 skb, dataoff, hash);
1322 ct = nf_ct_tuplehash_to_ctrack(h);
1324 /* It exists; we have (non-exclusive) reference. */
1325 if (NF_CT_DIRECTION(h) == IP_CT_DIR_REPLY) {
1326 ctinfo = IP_CT_ESTABLISHED_REPLY;
1328 /* Once we've had two way comms, always ESTABLISHED. */
1329 if (test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) {
1330 pr_debug("normal packet for %p\n", ct);
1331 ctinfo = IP_CT_ESTABLISHED;
1332 } else if (test_bit(IPS_EXPECTED_BIT, &ct->status)) {
1333 pr_debug("related packet for %p\n", ct);
1334 ctinfo = IP_CT_RELATED;
1336 pr_debug("new packet for %p\n", ct);
1340 nf_ct_set(skb, ct, ctinfo);
1345 nf_conntrack_in(struct net *net, u_int8_t pf, unsigned int hooknum,
1346 struct sk_buff *skb)
1348 struct nf_conn *ct, *tmpl;
1349 enum ip_conntrack_info ctinfo;
1350 struct nf_conntrack_l3proto *l3proto;
1351 struct nf_conntrack_l4proto *l4proto;
1352 unsigned int *timeouts;
1353 unsigned int dataoff;
1357 tmpl = nf_ct_get(skb, &ctinfo);
1358 if (tmpl || ctinfo == IP_CT_UNTRACKED) {
1359 /* Previously seen (loopback or untracked)? Ignore. */
1360 if ((tmpl && !nf_ct_is_template(tmpl)) ||
1361 ctinfo == IP_CT_UNTRACKED) {
1362 NF_CT_STAT_INC_ATOMIC(net, ignore);
1368 /* rcu_read_lock()ed by nf_hook_thresh */
1369 l3proto = __nf_ct_l3proto_find(pf);
1370 ret = l3proto->get_l4proto(skb, skb_network_offset(skb),
1371 &dataoff, &protonum);
1373 pr_debug("not prepared to track yet or error occurred\n");
1374 NF_CT_STAT_INC_ATOMIC(net, error);
1375 NF_CT_STAT_INC_ATOMIC(net, invalid);
1380 l4proto = __nf_ct_l4proto_find(pf, protonum);
1382 /* It may be an special packet, error, unclean...
1383 * inverse of the return code tells to the netfilter
1384 * core what to do with the packet. */
1385 if (l4proto->error != NULL) {
1386 ret = l4proto->error(net, tmpl, skb, dataoff, pf, hooknum);
1388 NF_CT_STAT_INC_ATOMIC(net, error);
1389 NF_CT_STAT_INC_ATOMIC(net, invalid);
1393 /* ICMP[v6] protocol trackers may assign one conntrack. */
1398 ret = resolve_normal_ct(net, tmpl, skb, dataoff, pf, protonum,
1401 /* Too stressed to deal. */
1402 NF_CT_STAT_INC_ATOMIC(net, drop);
1407 ct = nf_ct_get(skb, &ctinfo);
1409 /* Not valid part of a connection */
1410 NF_CT_STAT_INC_ATOMIC(net, invalid);
1415 /* Decide what timeout policy we want to apply to this flow. */
1416 timeouts = nf_ct_timeout_lookup(net, ct, l4proto);
1418 ret = l4proto->packet(ct, skb, dataoff, ctinfo, pf, hooknum, timeouts);
1420 /* Invalid: inverse of the return code tells
1421 * the netfilter core what to do */
1422 pr_debug("nf_conntrack_in: Can't track with proto module\n");
1423 nf_conntrack_put(&ct->ct_general);
1425 NF_CT_STAT_INC_ATOMIC(net, invalid);
1426 if (ret == -NF_DROP)
1427 NF_CT_STAT_INC_ATOMIC(net, drop);
1428 /* Special case: TCP tracker reports an attempt to reopen a
1429 * closed/aborted connection. We have to go back and create a
1432 if (ret == -NF_REPEAT)
1438 if (ctinfo == IP_CT_ESTABLISHED_REPLY &&
1439 !test_and_set_bit(IPS_SEEN_REPLY_BIT, &ct->status))
1440 nf_conntrack_event_cache(IPCT_REPLY, ct);
1447 EXPORT_SYMBOL_GPL(nf_conntrack_in);
1449 bool nf_ct_invert_tuplepr(struct nf_conntrack_tuple *inverse,
1450 const struct nf_conntrack_tuple *orig)
1455 ret = nf_ct_invert_tuple(inverse, orig,
1456 __nf_ct_l3proto_find(orig->src.l3num),
1457 __nf_ct_l4proto_find(orig->src.l3num,
1458 orig->dst.protonum));
1462 EXPORT_SYMBOL_GPL(nf_ct_invert_tuplepr);
1464 /* Alter reply tuple (maybe alter helper). This is for NAT, and is
1465 implicitly racy: see __nf_conntrack_confirm */
1466 void nf_conntrack_alter_reply(struct nf_conn *ct,
1467 const struct nf_conntrack_tuple *newreply)
1469 struct nf_conn_help *help = nfct_help(ct);
1471 /* Should be unconfirmed, so not in hash table yet */
1472 NF_CT_ASSERT(!nf_ct_is_confirmed(ct));
1474 pr_debug("Altering reply tuple of %p to ", ct);
1475 nf_ct_dump_tuple(newreply);
1477 ct->tuplehash[IP_CT_DIR_REPLY].tuple = *newreply;
1478 if (ct->master || (help && !hlist_empty(&help->expectations)))
1482 __nf_ct_try_assign_helper(ct, NULL, GFP_ATOMIC);
1485 EXPORT_SYMBOL_GPL(nf_conntrack_alter_reply);
1487 /* Refresh conntrack for this many jiffies and do accounting if do_acct is 1 */
1488 void __nf_ct_refresh_acct(struct nf_conn *ct,
1489 enum ip_conntrack_info ctinfo,
1490 const struct sk_buff *skb,
1491 unsigned long extra_jiffies,
1496 /* Only update if this is not a fixed timeout */
1497 if (test_bit(IPS_FIXED_TIMEOUT_BIT, &ct->status))
1500 /* If not in hash table, timer will not be active yet */
1501 if (nf_ct_is_confirmed(ct))
1502 extra_jiffies += nfct_time_stamp;
1504 ct->timeout = extra_jiffies;
1507 nf_ct_acct_update(ct, ctinfo, skb->len);
1509 EXPORT_SYMBOL_GPL(__nf_ct_refresh_acct);
1511 bool nf_ct_kill_acct(struct nf_conn *ct,
1512 enum ip_conntrack_info ctinfo,
1513 const struct sk_buff *skb)
1515 nf_ct_acct_update(ct, ctinfo, skb->len);
1517 return nf_ct_delete(ct, 0, 0);
1519 EXPORT_SYMBOL_GPL(nf_ct_kill_acct);
1521 #if IS_ENABLED(CONFIG_NF_CT_NETLINK)
1523 #include <linux/netfilter/nfnetlink.h>
1524 #include <linux/netfilter/nfnetlink_conntrack.h>
1525 #include <linux/mutex.h>
1527 /* Generic function for tcp/udp/sctp/dccp and alike. This needs to be
1528 * in ip_conntrack_core, since we don't want the protocols to autoload
1529 * or depend on ctnetlink */
1530 int nf_ct_port_tuple_to_nlattr(struct sk_buff *skb,
1531 const struct nf_conntrack_tuple *tuple)
1533 if (nla_put_be16(skb, CTA_PROTO_SRC_PORT, tuple->src.u.tcp.port) ||
1534 nla_put_be16(skb, CTA_PROTO_DST_PORT, tuple->dst.u.tcp.port))
1535 goto nla_put_failure;
1541 EXPORT_SYMBOL_GPL(nf_ct_port_tuple_to_nlattr);
1543 const struct nla_policy nf_ct_port_nla_policy[CTA_PROTO_MAX+1] = {
1544 [CTA_PROTO_SRC_PORT] = { .type = NLA_U16 },
1545 [CTA_PROTO_DST_PORT] = { .type = NLA_U16 },
1547 EXPORT_SYMBOL_GPL(nf_ct_port_nla_policy);
1549 int nf_ct_port_nlattr_to_tuple(struct nlattr *tb[],
1550 struct nf_conntrack_tuple *t)
1552 if (!tb[CTA_PROTO_SRC_PORT] || !tb[CTA_PROTO_DST_PORT])
1555 t->src.u.tcp.port = nla_get_be16(tb[CTA_PROTO_SRC_PORT]);
1556 t->dst.u.tcp.port = nla_get_be16(tb[CTA_PROTO_DST_PORT]);
1560 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_to_tuple);
1562 int nf_ct_port_nlattr_tuple_size(void)
1564 return nla_policy_len(nf_ct_port_nla_policy, CTA_PROTO_MAX + 1);
1566 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_tuple_size);
1569 /* Used by ipt_REJECT and ip6t_REJECT. */
1570 static void nf_conntrack_attach(struct sk_buff *nskb, const struct sk_buff *skb)
1573 enum ip_conntrack_info ctinfo;
1575 /* This ICMP is in reverse direction to the packet which caused it */
1576 ct = nf_ct_get(skb, &ctinfo);
1577 if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL)
1578 ctinfo = IP_CT_RELATED_REPLY;
1580 ctinfo = IP_CT_RELATED;
1582 /* Attach to new skbuff, and increment count */
1583 nf_ct_set(nskb, ct, ctinfo);
1584 nf_conntrack_get(skb_nfct(nskb));
1587 /* Bring out ya dead! */
1588 static struct nf_conn *
1589 get_next_corpse(struct net *net, int (*iter)(struct nf_conn *i, void *data),
1590 void *data, unsigned int *bucket)
1592 struct nf_conntrack_tuple_hash *h;
1594 struct hlist_nulls_node *n;
1598 for (; *bucket < nf_conntrack_htable_size; (*bucket)++) {
1599 lockp = &nf_conntrack_locks[*bucket % CONNTRACK_LOCKS];
1601 nf_conntrack_lock(lockp);
1602 if (*bucket < nf_conntrack_htable_size) {
1603 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[*bucket], hnnode) {
1604 if (NF_CT_DIRECTION(h) != IP_CT_DIR_ORIGINAL)
1606 ct = nf_ct_tuplehash_to_ctrack(h);
1607 if (net_eq(nf_ct_net(ct), net) &&
1617 for_each_possible_cpu(cpu) {
1618 struct ct_pcpu *pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
1620 spin_lock_bh(&pcpu->lock);
1621 hlist_nulls_for_each_entry(h, n, &pcpu->unconfirmed, hnnode) {
1622 ct = nf_ct_tuplehash_to_ctrack(h);
1624 set_bit(IPS_DYING_BIT, &ct->status);
1626 spin_unlock_bh(&pcpu->lock);
1631 atomic_inc(&ct->ct_general.use);
1637 void nf_ct_iterate_cleanup(struct net *net,
1638 int (*iter)(struct nf_conn *i, void *data),
1639 void *data, u32 portid, int report)
1642 unsigned int bucket = 0;
1646 if (atomic_read(&net->ct.count) == 0)
1649 while ((ct = get_next_corpse(net, iter, data, &bucket)) != NULL) {
1650 /* Time to push up daises... */
1652 nf_ct_delete(ct, portid, report);
1657 EXPORT_SYMBOL_GPL(nf_ct_iterate_cleanup);
1659 static int kill_all(struct nf_conn *i, void *data)
1664 void nf_ct_free_hashtable(void *hash, unsigned int size)
1666 if (is_vmalloc_addr(hash))
1669 free_pages((unsigned long)hash,
1670 get_order(sizeof(struct hlist_head) * size));
1672 EXPORT_SYMBOL_GPL(nf_ct_free_hashtable);
1674 void nf_conntrack_cleanup_start(void)
1676 conntrack_gc_work.exiting = true;
1677 RCU_INIT_POINTER(ip_ct_attach, NULL);
1680 void nf_conntrack_cleanup_end(void)
1682 RCU_INIT_POINTER(nf_ct_destroy, NULL);
1684 cancel_delayed_work_sync(&conntrack_gc_work.dwork);
1685 nf_ct_free_hashtable(nf_conntrack_hash, nf_conntrack_htable_size);
1687 nf_conntrack_proto_fini();
1688 nf_conntrack_seqadj_fini();
1689 nf_conntrack_labels_fini();
1690 nf_conntrack_helper_fini();
1691 nf_conntrack_timeout_fini();
1692 nf_conntrack_ecache_fini();
1693 nf_conntrack_tstamp_fini();
1694 nf_conntrack_acct_fini();
1695 nf_conntrack_expect_fini();
1697 kmem_cache_destroy(nf_conntrack_cachep);
1701 * Mishearing the voices in his head, our hero wonders how he's
1702 * supposed to kill the mall.
1704 void nf_conntrack_cleanup_net(struct net *net)
1708 list_add(&net->exit_list, &single);
1709 nf_conntrack_cleanup_net_list(&single);
1712 void nf_conntrack_cleanup_net_list(struct list_head *net_exit_list)
1718 * This makes sure all current packets have passed through
1719 * netfilter framework. Roll on, two-stage module
1725 list_for_each_entry(net, net_exit_list, exit_list) {
1726 nf_ct_iterate_cleanup(net, kill_all, NULL, 0, 0);
1727 if (atomic_read(&net->ct.count) != 0)
1732 goto i_see_dead_people;
1735 list_for_each_entry(net, net_exit_list, exit_list) {
1736 nf_conntrack_proto_pernet_fini(net);
1737 nf_conntrack_helper_pernet_fini(net);
1738 nf_conntrack_ecache_pernet_fini(net);
1739 nf_conntrack_tstamp_pernet_fini(net);
1740 nf_conntrack_acct_pernet_fini(net);
1741 nf_conntrack_expect_pernet_fini(net);
1742 free_percpu(net->ct.stat);
1743 free_percpu(net->ct.pcpu_lists);
1747 void *nf_ct_alloc_hashtable(unsigned int *sizep, int nulls)
1749 struct hlist_nulls_head *hash;
1750 unsigned int nr_slots, i;
1753 if (*sizep > (UINT_MAX / sizeof(struct hlist_nulls_head)))
1756 BUILD_BUG_ON(sizeof(struct hlist_nulls_head) != sizeof(struct hlist_head));
1757 nr_slots = *sizep = roundup(*sizep, PAGE_SIZE / sizeof(struct hlist_nulls_head));
1759 if (nr_slots > (UINT_MAX / sizeof(struct hlist_nulls_head)))
1762 sz = nr_slots * sizeof(struct hlist_nulls_head);
1763 hash = (void *)__get_free_pages(GFP_KERNEL | __GFP_NOWARN | __GFP_ZERO,
1769 for (i = 0; i < nr_slots; i++)
1770 INIT_HLIST_NULLS_HEAD(&hash[i], i);
1774 EXPORT_SYMBOL_GPL(nf_ct_alloc_hashtable);
1776 int nf_conntrack_hash_resize(unsigned int hashsize)
1779 unsigned int old_size;
1780 struct hlist_nulls_head *hash, *old_hash;
1781 struct nf_conntrack_tuple_hash *h;
1787 hash = nf_ct_alloc_hashtable(&hashsize, 1);
1791 old_size = nf_conntrack_htable_size;
1792 if (old_size == hashsize) {
1793 nf_ct_free_hashtable(hash, hashsize);
1798 nf_conntrack_all_lock();
1799 write_seqcount_begin(&nf_conntrack_generation);
1801 /* Lookups in the old hash might happen in parallel, which means we
1802 * might get false negatives during connection lookup. New connections
1803 * created because of a false negative won't make it into the hash
1804 * though since that required taking the locks.
1807 for (i = 0; i < nf_conntrack_htable_size; i++) {
1808 while (!hlist_nulls_empty(&nf_conntrack_hash[i])) {
1809 h = hlist_nulls_entry(nf_conntrack_hash[i].first,
1810 struct nf_conntrack_tuple_hash, hnnode);
1811 ct = nf_ct_tuplehash_to_ctrack(h);
1812 hlist_nulls_del_rcu(&h->hnnode);
1813 bucket = __hash_conntrack(nf_ct_net(ct),
1814 &h->tuple, hashsize);
1815 hlist_nulls_add_head_rcu(&h->hnnode, &hash[bucket]);
1818 old_size = nf_conntrack_htable_size;
1819 old_hash = nf_conntrack_hash;
1821 nf_conntrack_hash = hash;
1822 nf_conntrack_htable_size = hashsize;
1824 write_seqcount_end(&nf_conntrack_generation);
1825 nf_conntrack_all_unlock();
1829 nf_ct_free_hashtable(old_hash, old_size);
1833 int nf_conntrack_set_hashsize(const char *val, struct kernel_param *kp)
1835 unsigned int hashsize;
1838 if (current->nsproxy->net_ns != &init_net)
1841 /* On boot, we can set this without any fancy locking. */
1842 if (!nf_conntrack_htable_size)
1843 return param_set_uint(val, kp);
1845 rc = kstrtouint(val, 0, &hashsize);
1849 return nf_conntrack_hash_resize(hashsize);
1851 EXPORT_SYMBOL_GPL(nf_conntrack_set_hashsize);
1853 module_param_call(hashsize, nf_conntrack_set_hashsize, param_get_uint,
1854 &nf_conntrack_htable_size, 0600);
1856 static unsigned int total_extension_size(void)
1858 /* remember to add new extensions below */
1859 BUILD_BUG_ON(NF_CT_EXT_NUM > 9);
1861 return sizeof(struct nf_ct_ext) +
1862 sizeof(struct nf_conn_help)
1863 #if IS_ENABLED(CONFIG_NF_NAT)
1864 + sizeof(struct nf_conn_nat)
1866 + sizeof(struct nf_conn_seqadj)
1867 + sizeof(struct nf_conn_acct)
1868 #ifdef CONFIG_NF_CONNTRACK_EVENTS
1869 + sizeof(struct nf_conntrack_ecache)
1871 #ifdef CONFIG_NF_CONNTRACK_TIMESTAMP
1872 + sizeof(struct nf_conn_tstamp)
1874 #ifdef CONFIG_NF_CONNTRACK_TIMEOUT
1875 + sizeof(struct nf_conn_timeout)
1877 #ifdef CONFIG_NF_CONNTRACK_LABELS
1878 + sizeof(struct nf_conn_labels)
1880 #if IS_ENABLED(CONFIG_NETFILTER_SYNPROXY)
1881 + sizeof(struct nf_conn_synproxy)
1886 int nf_conntrack_init_start(void)
1892 /* struct nf_ct_ext uses u8 to store offsets/size */
1893 BUILD_BUG_ON(total_extension_size() > 255u);
1895 seqcount_init(&nf_conntrack_generation);
1897 for (i = 0; i < CONNTRACK_LOCKS; i++)
1898 spin_lock_init(&nf_conntrack_locks[i]);
1900 if (!nf_conntrack_htable_size) {
1901 /* Idea from tcp.c: use 1/16384 of memory.
1902 * On i386: 32MB machine has 512 buckets.
1903 * >= 1GB machines have 16384 buckets.
1904 * >= 4GB machines have 65536 buckets.
1906 nf_conntrack_htable_size
1907 = (((totalram_pages << PAGE_SHIFT) / 16384)
1908 / sizeof(struct hlist_head));
1909 if (totalram_pages > (4 * (1024 * 1024 * 1024 / PAGE_SIZE)))
1910 nf_conntrack_htable_size = 65536;
1911 else if (totalram_pages > (1024 * 1024 * 1024 / PAGE_SIZE))
1912 nf_conntrack_htable_size = 16384;
1913 if (nf_conntrack_htable_size < 32)
1914 nf_conntrack_htable_size = 32;
1916 /* Use a max. factor of four by default to get the same max as
1917 * with the old struct list_heads. When a table size is given
1918 * we use the old value of 8 to avoid reducing the max.
1923 nf_conntrack_hash = nf_ct_alloc_hashtable(&nf_conntrack_htable_size, 1);
1924 if (!nf_conntrack_hash)
1927 nf_conntrack_max = max_factor * nf_conntrack_htable_size;
1929 nf_conntrack_cachep = kmem_cache_create("nf_conntrack",
1930 sizeof(struct nf_conn),
1932 SLAB_DESTROY_BY_RCU | SLAB_HWCACHE_ALIGN, NULL);
1933 if (!nf_conntrack_cachep)
1936 printk(KERN_INFO "nf_conntrack version %s (%u buckets, %d max)\n",
1937 NF_CONNTRACK_VERSION, nf_conntrack_htable_size,
1940 ret = nf_conntrack_expect_init();
1944 ret = nf_conntrack_acct_init();
1948 ret = nf_conntrack_tstamp_init();
1952 ret = nf_conntrack_ecache_init();
1956 ret = nf_conntrack_timeout_init();
1960 ret = nf_conntrack_helper_init();
1964 ret = nf_conntrack_labels_init();
1968 ret = nf_conntrack_seqadj_init();
1972 ret = nf_conntrack_proto_init();
1976 conntrack_gc_work_init(&conntrack_gc_work);
1977 queue_delayed_work(system_long_wq, &conntrack_gc_work.dwork, HZ);
1982 nf_conntrack_seqadj_fini();
1984 nf_conntrack_labels_fini();
1986 nf_conntrack_helper_fini();
1988 nf_conntrack_timeout_fini();
1990 nf_conntrack_ecache_fini();
1992 nf_conntrack_tstamp_fini();
1994 nf_conntrack_acct_fini();
1996 nf_conntrack_expect_fini();
1998 kmem_cache_destroy(nf_conntrack_cachep);
2000 nf_ct_free_hashtable(nf_conntrack_hash, nf_conntrack_htable_size);
2004 void nf_conntrack_init_end(void)
2006 /* For use by REJECT target */
2007 RCU_INIT_POINTER(ip_ct_attach, nf_conntrack_attach);
2008 RCU_INIT_POINTER(nf_ct_destroy, destroy_conntrack);
2012 * We need to use special "null" values, not used in hash table
2014 #define UNCONFIRMED_NULLS_VAL ((1<<30)+0)
2015 #define DYING_NULLS_VAL ((1<<30)+1)
2016 #define TEMPLATE_NULLS_VAL ((1<<30)+2)
2018 int nf_conntrack_init_net(struct net *net)
2023 BUILD_BUG_ON(IP_CT_UNTRACKED == IP_CT_NUMBER);
2024 atomic_set(&net->ct.count, 0);
2026 net->ct.pcpu_lists = alloc_percpu(struct ct_pcpu);
2027 if (!net->ct.pcpu_lists)
2030 for_each_possible_cpu(cpu) {
2031 struct ct_pcpu *pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
2033 spin_lock_init(&pcpu->lock);
2034 INIT_HLIST_NULLS_HEAD(&pcpu->unconfirmed, UNCONFIRMED_NULLS_VAL);
2035 INIT_HLIST_NULLS_HEAD(&pcpu->dying, DYING_NULLS_VAL);
2038 net->ct.stat = alloc_percpu(struct ip_conntrack_stat);
2040 goto err_pcpu_lists;
2042 ret = nf_conntrack_expect_pernet_init(net);
2045 ret = nf_conntrack_acct_pernet_init(net);
2048 ret = nf_conntrack_tstamp_pernet_init(net);
2051 ret = nf_conntrack_ecache_pernet_init(net);
2054 ret = nf_conntrack_helper_pernet_init(net);
2057 ret = nf_conntrack_proto_pernet_init(net);
2063 nf_conntrack_helper_pernet_fini(net);
2065 nf_conntrack_ecache_pernet_fini(net);
2067 nf_conntrack_tstamp_pernet_fini(net);
2069 nf_conntrack_acct_pernet_fini(net);
2071 nf_conntrack_expect_pernet_fini(net);
2073 free_percpu(net->ct.stat);
2075 free_percpu(net->ct.pcpu_lists);