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 #include "nf_internals.h"
61 __cacheline_aligned_in_smp spinlock_t nf_conntrack_locks[CONNTRACK_LOCKS];
62 EXPORT_SYMBOL_GPL(nf_conntrack_locks);
64 __cacheline_aligned_in_smp DEFINE_SPINLOCK(nf_conntrack_expect_lock);
65 EXPORT_SYMBOL_GPL(nf_conntrack_expect_lock);
67 struct hlist_nulls_head *nf_conntrack_hash __read_mostly;
68 EXPORT_SYMBOL_GPL(nf_conntrack_hash);
70 struct conntrack_gc_work {
71 struct delayed_work dwork;
78 static __read_mostly struct kmem_cache *nf_conntrack_cachep;
79 static __read_mostly spinlock_t nf_conntrack_locks_all_lock;
80 static __read_mostly DEFINE_SPINLOCK(nf_conntrack_locks_all_lock);
81 static __read_mostly bool nf_conntrack_locks_all;
83 /* every gc cycle scans at most 1/GC_MAX_BUCKETS_DIV part of table */
84 #define GC_MAX_BUCKETS_DIV 128u
85 /* upper bound of full table scan */
86 #define GC_MAX_SCAN_JIFFIES (16u * HZ)
87 /* desired ratio of entries found to be expired */
88 #define GC_EVICT_RATIO 50u
90 static struct conntrack_gc_work conntrack_gc_work;
92 void nf_conntrack_lock(spinlock_t *lock) __acquires(lock)
94 /* 1) Acquire the lock */
97 /* 2) read nf_conntrack_locks_all, with ACQUIRE semantics
98 * It pairs with the smp_store_release() in nf_conntrack_all_unlock()
100 if (likely(smp_load_acquire(&nf_conntrack_locks_all) == false))
103 /* fast path failed, unlock */
106 /* Slow path 1) get global lock */
107 spin_lock(&nf_conntrack_locks_all_lock);
109 /* Slow path 2) get the lock we want */
112 /* Slow path 3) release the global lock */
113 spin_unlock(&nf_conntrack_locks_all_lock);
115 EXPORT_SYMBOL_GPL(nf_conntrack_lock);
117 static void nf_conntrack_double_unlock(unsigned int h1, unsigned int h2)
119 h1 %= CONNTRACK_LOCKS;
120 h2 %= CONNTRACK_LOCKS;
121 spin_unlock(&nf_conntrack_locks[h1]);
123 spin_unlock(&nf_conntrack_locks[h2]);
126 /* return true if we need to recompute hashes (in case hash table was resized) */
127 static bool nf_conntrack_double_lock(struct net *net, unsigned int h1,
128 unsigned int h2, unsigned int sequence)
130 h1 %= CONNTRACK_LOCKS;
131 h2 %= CONNTRACK_LOCKS;
133 nf_conntrack_lock(&nf_conntrack_locks[h1]);
135 spin_lock_nested(&nf_conntrack_locks[h2],
136 SINGLE_DEPTH_NESTING);
138 nf_conntrack_lock(&nf_conntrack_locks[h2]);
139 spin_lock_nested(&nf_conntrack_locks[h1],
140 SINGLE_DEPTH_NESTING);
142 if (read_seqcount_retry(&nf_conntrack_generation, sequence)) {
143 nf_conntrack_double_unlock(h1, h2);
149 static void nf_conntrack_all_lock(void)
153 spin_lock(&nf_conntrack_locks_all_lock);
155 nf_conntrack_locks_all = true;
157 for (i = 0; i < CONNTRACK_LOCKS; i++) {
158 spin_lock(&nf_conntrack_locks[i]);
160 /* This spin_unlock provides the "release" to ensure that
161 * nf_conntrack_locks_all==true is visible to everyone that
162 * acquired spin_lock(&nf_conntrack_locks[]).
164 spin_unlock(&nf_conntrack_locks[i]);
168 static void nf_conntrack_all_unlock(void)
170 /* All prior stores must be complete before we clear
171 * 'nf_conntrack_locks_all'. Otherwise nf_conntrack_lock()
172 * might observe the false value but not the entire
174 * It pairs with the smp_load_acquire() in nf_conntrack_lock()
176 smp_store_release(&nf_conntrack_locks_all, false);
177 spin_unlock(&nf_conntrack_locks_all_lock);
180 unsigned int nf_conntrack_htable_size __read_mostly;
181 EXPORT_SYMBOL_GPL(nf_conntrack_htable_size);
183 unsigned int nf_conntrack_max __read_mostly;
184 EXPORT_SYMBOL_GPL(nf_conntrack_max);
185 seqcount_t nf_conntrack_generation __read_mostly;
186 static unsigned int nf_conntrack_hash_rnd __read_mostly;
188 static u32 hash_conntrack_raw(const struct nf_conntrack_tuple *tuple,
189 const struct net *net)
194 get_random_once(&nf_conntrack_hash_rnd, sizeof(nf_conntrack_hash_rnd));
196 /* The direction must be ignored, so we hash everything up to the
197 * destination ports (which is a multiple of 4) and treat the last
198 * three bytes manually.
200 seed = nf_conntrack_hash_rnd ^ net_hash_mix(net);
201 n = (sizeof(tuple->src) + sizeof(tuple->dst.u3)) / sizeof(u32);
202 return jhash2((u32 *)tuple, n, seed ^
203 (((__force __u16)tuple->dst.u.all << 16) |
204 tuple->dst.protonum));
207 static u32 scale_hash(u32 hash)
209 return reciprocal_scale(hash, nf_conntrack_htable_size);
212 static u32 __hash_conntrack(const struct net *net,
213 const struct nf_conntrack_tuple *tuple,
216 return reciprocal_scale(hash_conntrack_raw(tuple, net), size);
219 static u32 hash_conntrack(const struct net *net,
220 const struct nf_conntrack_tuple *tuple)
222 return scale_hash(hash_conntrack_raw(tuple, net));
226 nf_ct_get_tuple(const struct sk_buff *skb,
228 unsigned int dataoff,
232 struct nf_conntrack_tuple *tuple,
233 const struct nf_conntrack_l3proto *l3proto,
234 const struct nf_conntrack_l4proto *l4proto)
236 memset(tuple, 0, sizeof(*tuple));
238 tuple->src.l3num = l3num;
239 if (l3proto->pkt_to_tuple(skb, nhoff, tuple) == 0)
242 tuple->dst.protonum = protonum;
243 tuple->dst.dir = IP_CT_DIR_ORIGINAL;
245 return l4proto->pkt_to_tuple(skb, dataoff, net, tuple);
247 EXPORT_SYMBOL_GPL(nf_ct_get_tuple);
249 bool nf_ct_get_tuplepr(const struct sk_buff *skb, unsigned int nhoff,
251 struct net *net, struct nf_conntrack_tuple *tuple)
253 const struct nf_conntrack_l3proto *l3proto;
254 const struct nf_conntrack_l4proto *l4proto;
255 unsigned int protoff;
261 l3proto = __nf_ct_l3proto_find(l3num);
262 ret = l3proto->get_l4proto(skb, nhoff, &protoff, &protonum);
263 if (ret != NF_ACCEPT) {
268 l4proto = __nf_ct_l4proto_find(l3num, protonum);
270 ret = nf_ct_get_tuple(skb, nhoff, protoff, l3num, protonum, net, tuple,
276 EXPORT_SYMBOL_GPL(nf_ct_get_tuplepr);
279 nf_ct_invert_tuple(struct nf_conntrack_tuple *inverse,
280 const struct nf_conntrack_tuple *orig,
281 const struct nf_conntrack_l3proto *l3proto,
282 const struct nf_conntrack_l4proto *l4proto)
284 memset(inverse, 0, sizeof(*inverse));
286 inverse->src.l3num = orig->src.l3num;
287 if (l3proto->invert_tuple(inverse, orig) == 0)
290 inverse->dst.dir = !orig->dst.dir;
292 inverse->dst.protonum = orig->dst.protonum;
293 return l4proto->invert_tuple(inverse, orig);
295 EXPORT_SYMBOL_GPL(nf_ct_invert_tuple);
298 clean_from_lists(struct nf_conn *ct)
300 pr_debug("clean_from_lists(%p)\n", ct);
301 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
302 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode);
304 /* Destroy all pending expectations */
305 nf_ct_remove_expectations(ct);
308 /* must be called with local_bh_disable */
309 static void nf_ct_add_to_dying_list(struct nf_conn *ct)
311 struct ct_pcpu *pcpu;
313 /* add this conntrack to the (per cpu) dying list */
314 ct->cpu = smp_processor_id();
315 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
317 spin_lock(&pcpu->lock);
318 hlist_nulls_add_head(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
320 spin_unlock(&pcpu->lock);
323 /* must be called with local_bh_disable */
324 static void nf_ct_add_to_unconfirmed_list(struct nf_conn *ct)
326 struct ct_pcpu *pcpu;
328 /* add this conntrack to the (per cpu) unconfirmed list */
329 ct->cpu = smp_processor_id();
330 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
332 spin_lock(&pcpu->lock);
333 hlist_nulls_add_head(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
335 spin_unlock(&pcpu->lock);
338 /* must be called with local_bh_disable */
339 static void nf_ct_del_from_dying_or_unconfirmed_list(struct nf_conn *ct)
341 struct ct_pcpu *pcpu;
343 /* We overload first tuple to link into unconfirmed or dying list.*/
344 pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
346 spin_lock(&pcpu->lock);
347 BUG_ON(hlist_nulls_unhashed(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode));
348 hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
349 spin_unlock(&pcpu->lock);
352 #define NFCT_ALIGN(len) (((len) + NFCT_INFOMASK) & ~NFCT_INFOMASK)
354 /* Released via destroy_conntrack() */
355 struct nf_conn *nf_ct_tmpl_alloc(struct net *net,
356 const struct nf_conntrack_zone *zone,
359 struct nf_conn *tmpl, *p;
361 if (ARCH_KMALLOC_MINALIGN <= NFCT_INFOMASK) {
362 tmpl = kzalloc(sizeof(*tmpl) + NFCT_INFOMASK, flags);
367 tmpl = (struct nf_conn *)NFCT_ALIGN((unsigned long)p);
369 tmpl = (struct nf_conn *)NFCT_ALIGN((unsigned long)p);
370 tmpl->proto.tmpl_padto = (char *)tmpl - (char *)p;
373 tmpl = kzalloc(sizeof(*tmpl), flags);
378 tmpl->status = IPS_TEMPLATE;
379 write_pnet(&tmpl->ct_net, net);
380 nf_ct_zone_add(tmpl, zone);
381 atomic_set(&tmpl->ct_general.use, 0);
385 EXPORT_SYMBOL_GPL(nf_ct_tmpl_alloc);
387 void nf_ct_tmpl_free(struct nf_conn *tmpl)
389 nf_ct_ext_destroy(tmpl);
390 nf_ct_ext_free(tmpl);
392 if (ARCH_KMALLOC_MINALIGN <= NFCT_INFOMASK)
393 kfree((char *)tmpl - tmpl->proto.tmpl_padto);
397 EXPORT_SYMBOL_GPL(nf_ct_tmpl_free);
400 destroy_conntrack(struct nf_conntrack *nfct)
402 struct nf_conn *ct = (struct nf_conn *)nfct;
403 const struct nf_conntrack_l4proto *l4proto;
405 pr_debug("destroy_conntrack(%p)\n", ct);
406 WARN_ON(atomic_read(&nfct->use) != 0);
408 if (unlikely(nf_ct_is_template(ct))) {
412 l4proto = __nf_ct_l4proto_find(nf_ct_l3num(ct), nf_ct_protonum(ct));
413 if (l4proto->destroy)
414 l4proto->destroy(ct);
417 /* Expectations will have been removed in clean_from_lists,
418 * except TFTP can create an expectation on the first packet,
419 * before connection is in the list, so we need to clean here,
422 nf_ct_remove_expectations(ct);
424 nf_ct_del_from_dying_or_unconfirmed_list(ct);
429 nf_ct_put(ct->master);
431 pr_debug("destroy_conntrack: returning ct=%p to slab\n", ct);
432 nf_conntrack_free(ct);
435 static void nf_ct_delete_from_lists(struct nf_conn *ct)
437 struct net *net = nf_ct_net(ct);
438 unsigned int hash, reply_hash;
439 unsigned int sequence;
441 nf_ct_helper_destroy(ct);
445 sequence = read_seqcount_begin(&nf_conntrack_generation);
446 hash = hash_conntrack(net,
447 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
448 reply_hash = hash_conntrack(net,
449 &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
450 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
452 clean_from_lists(ct);
453 nf_conntrack_double_unlock(hash, reply_hash);
455 nf_ct_add_to_dying_list(ct);
460 bool nf_ct_delete(struct nf_conn *ct, u32 portid, int report)
462 struct nf_conn_tstamp *tstamp;
464 if (test_and_set_bit(IPS_DYING_BIT, &ct->status))
467 tstamp = nf_conn_tstamp_find(ct);
468 if (tstamp && tstamp->stop == 0)
469 tstamp->stop = ktime_get_real_ns();
471 if (nf_conntrack_event_report(IPCT_DESTROY, ct,
472 portid, report) < 0) {
473 /* destroy event was not delivered. nf_ct_put will
474 * be done by event cache worker on redelivery.
476 nf_ct_delete_from_lists(ct);
477 nf_conntrack_ecache_delayed_work(nf_ct_net(ct));
481 nf_conntrack_ecache_work(nf_ct_net(ct));
482 nf_ct_delete_from_lists(ct);
486 EXPORT_SYMBOL_GPL(nf_ct_delete);
489 nf_ct_key_equal(struct nf_conntrack_tuple_hash *h,
490 const struct nf_conntrack_tuple *tuple,
491 const struct nf_conntrack_zone *zone,
492 const struct net *net)
494 struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
496 /* A conntrack can be recreated with the equal tuple,
497 * so we need to check that the conntrack is confirmed
499 return nf_ct_tuple_equal(tuple, &h->tuple) &&
500 nf_ct_zone_equal(ct, zone, NF_CT_DIRECTION(h)) &&
501 nf_ct_is_confirmed(ct) &&
502 net_eq(net, nf_ct_net(ct));
505 /* caller must hold rcu readlock and none of the nf_conntrack_locks */
506 static void nf_ct_gc_expired(struct nf_conn *ct)
508 if (!atomic_inc_not_zero(&ct->ct_general.use))
511 if (nf_ct_should_gc(ct))
519 * - Caller must take a reference on returned object
520 * and recheck nf_ct_tuple_equal(tuple, &h->tuple)
522 static struct nf_conntrack_tuple_hash *
523 ____nf_conntrack_find(struct net *net, const struct nf_conntrack_zone *zone,
524 const struct nf_conntrack_tuple *tuple, u32 hash)
526 struct nf_conntrack_tuple_hash *h;
527 struct hlist_nulls_head *ct_hash;
528 struct hlist_nulls_node *n;
529 unsigned int bucket, hsize;
532 nf_conntrack_get_ht(&ct_hash, &hsize);
533 bucket = reciprocal_scale(hash, hsize);
535 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[bucket], hnnode) {
538 ct = nf_ct_tuplehash_to_ctrack(h);
539 if (nf_ct_is_expired(ct)) {
540 nf_ct_gc_expired(ct);
544 if (nf_ct_is_dying(ct))
547 if (nf_ct_key_equal(h, tuple, zone, net))
551 * if the nulls value we got at the end of this lookup is
552 * not the expected one, we must restart lookup.
553 * We probably met an item that was moved to another chain.
555 if (get_nulls_value(n) != bucket) {
556 NF_CT_STAT_INC_ATOMIC(net, search_restart);
563 /* Find a connection corresponding to a tuple. */
564 static struct nf_conntrack_tuple_hash *
565 __nf_conntrack_find_get(struct net *net, const struct nf_conntrack_zone *zone,
566 const struct nf_conntrack_tuple *tuple, u32 hash)
568 struct nf_conntrack_tuple_hash *h;
573 h = ____nf_conntrack_find(net, zone, tuple, hash);
575 ct = nf_ct_tuplehash_to_ctrack(h);
576 if (unlikely(nf_ct_is_dying(ct) ||
577 !atomic_inc_not_zero(&ct->ct_general.use)))
580 if (unlikely(!nf_ct_key_equal(h, tuple, zone, net))) {
591 struct nf_conntrack_tuple_hash *
592 nf_conntrack_find_get(struct net *net, const struct nf_conntrack_zone *zone,
593 const struct nf_conntrack_tuple *tuple)
595 return __nf_conntrack_find_get(net, zone, tuple,
596 hash_conntrack_raw(tuple, net));
598 EXPORT_SYMBOL_GPL(nf_conntrack_find_get);
600 static void __nf_conntrack_hash_insert(struct nf_conn *ct,
602 unsigned int reply_hash)
604 hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
605 &nf_conntrack_hash[hash]);
606 hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode,
607 &nf_conntrack_hash[reply_hash]);
611 nf_conntrack_hash_check_insert(struct nf_conn *ct)
613 const struct nf_conntrack_zone *zone;
614 struct net *net = nf_ct_net(ct);
615 unsigned int hash, reply_hash;
616 struct nf_conntrack_tuple_hash *h;
617 struct hlist_nulls_node *n;
618 unsigned int sequence;
620 zone = nf_ct_zone(ct);
624 sequence = read_seqcount_begin(&nf_conntrack_generation);
625 hash = hash_conntrack(net,
626 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
627 reply_hash = hash_conntrack(net,
628 &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
629 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
631 /* See if there's one in the list already, including reverse */
632 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode)
633 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
637 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode)
638 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
643 /* The caller holds a reference to this object */
644 atomic_set(&ct->ct_general.use, 2);
645 __nf_conntrack_hash_insert(ct, hash, reply_hash);
646 nf_conntrack_double_unlock(hash, reply_hash);
647 NF_CT_STAT_INC(net, insert);
652 nf_conntrack_double_unlock(hash, reply_hash);
653 NF_CT_STAT_INC(net, insert_failed);
657 EXPORT_SYMBOL_GPL(nf_conntrack_hash_check_insert);
659 static inline void nf_ct_acct_update(struct nf_conn *ct,
660 enum ip_conntrack_info ctinfo,
663 struct nf_conn_acct *acct;
665 acct = nf_conn_acct_find(ct);
667 struct nf_conn_counter *counter = acct->counter;
669 atomic64_inc(&counter[CTINFO2DIR(ctinfo)].packets);
670 atomic64_add(len, &counter[CTINFO2DIR(ctinfo)].bytes);
674 static void nf_ct_acct_merge(struct nf_conn *ct, enum ip_conntrack_info ctinfo,
675 const struct nf_conn *loser_ct)
677 struct nf_conn_acct *acct;
679 acct = nf_conn_acct_find(loser_ct);
681 struct nf_conn_counter *counter = acct->counter;
684 /* u32 should be fine since we must have seen one packet. */
685 bytes = atomic64_read(&counter[CTINFO2DIR(ctinfo)].bytes);
686 nf_ct_acct_update(ct, ctinfo, bytes);
690 /* Resolve race on insertion if this protocol allows this. */
691 static int nf_ct_resolve_clash(struct net *net, struct sk_buff *skb,
692 enum ip_conntrack_info ctinfo,
693 struct nf_conntrack_tuple_hash *h)
695 /* This is the conntrack entry already in hashes that won race. */
696 struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
697 const struct nf_conntrack_l4proto *l4proto;
699 l4proto = __nf_ct_l4proto_find(nf_ct_l3num(ct), nf_ct_protonum(ct));
700 if (l4proto->allow_clash &&
701 ((ct->status & IPS_NAT_DONE_MASK) == 0) &&
702 !nf_ct_is_dying(ct) &&
703 atomic_inc_not_zero(&ct->ct_general.use)) {
704 enum ip_conntrack_info oldinfo;
705 struct nf_conn *loser_ct = nf_ct_get(skb, &oldinfo);
707 nf_ct_acct_merge(ct, ctinfo, loser_ct);
708 nf_conntrack_put(&loser_ct->ct_general);
709 nf_ct_set(skb, ct, oldinfo);
712 NF_CT_STAT_INC(net, drop);
716 /* Confirm a connection given skb; places it in hash table */
718 __nf_conntrack_confirm(struct sk_buff *skb)
720 const struct nf_conntrack_zone *zone;
721 unsigned int hash, reply_hash;
722 struct nf_conntrack_tuple_hash *h;
724 struct nf_conn_help *help;
725 struct nf_conn_tstamp *tstamp;
726 struct hlist_nulls_node *n;
727 enum ip_conntrack_info ctinfo;
729 unsigned int sequence;
732 ct = nf_ct_get(skb, &ctinfo);
735 /* ipt_REJECT uses nf_conntrack_attach to attach related
736 ICMP/TCP RST packets in other direction. Actual packet
737 which created connection will be IP_CT_NEW or for an
738 expected connection, IP_CT_RELATED. */
739 if (CTINFO2DIR(ctinfo) != IP_CT_DIR_ORIGINAL)
742 zone = nf_ct_zone(ct);
746 sequence = read_seqcount_begin(&nf_conntrack_generation);
747 /* reuse the hash saved before */
748 hash = *(unsigned long *)&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev;
749 hash = scale_hash(hash);
750 reply_hash = hash_conntrack(net,
751 &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
753 } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
755 /* We're not in hash table, and we refuse to set up related
756 * connections for unconfirmed conns. But packet copies and
757 * REJECT will give spurious warnings here.
760 /* No external references means no one else could have
763 WARN_ON(nf_ct_is_confirmed(ct));
764 pr_debug("Confirming conntrack %p\n", ct);
765 /* We have to check the DYING flag after unlink to prevent
766 * a race against nf_ct_get_next_corpse() possibly called from
767 * user context, else we insert an already 'dead' hash, blocking
768 * further use of that particular connection -JM.
770 nf_ct_del_from_dying_or_unconfirmed_list(ct);
772 if (unlikely(nf_ct_is_dying(ct))) {
773 nf_ct_add_to_dying_list(ct);
777 /* See if there's one in the list already, including reverse:
778 NAT could have grabbed it without realizing, since we're
779 not in the hash. If there is, we lost race. */
780 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode)
781 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
785 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode)
786 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
790 /* Timer relative to confirmation time, not original
791 setting time, otherwise we'd get timer wrap in
792 weird delay cases. */
793 ct->timeout += nfct_time_stamp;
794 atomic_inc(&ct->ct_general.use);
795 ct->status |= IPS_CONFIRMED;
797 /* set conntrack timestamp, if enabled. */
798 tstamp = nf_conn_tstamp_find(ct);
800 if (skb->tstamp == 0)
801 __net_timestamp(skb);
803 tstamp->start = ktime_to_ns(skb->tstamp);
805 /* Since the lookup is lockless, hash insertion must be done after
806 * starting the timer and setting the CONFIRMED bit. The RCU barriers
807 * guarantee that no other CPU can find the conntrack before the above
808 * stores are visible.
810 __nf_conntrack_hash_insert(ct, hash, reply_hash);
811 nf_conntrack_double_unlock(hash, reply_hash);
814 help = nfct_help(ct);
815 if (help && help->helper)
816 nf_conntrack_event_cache(IPCT_HELPER, ct);
818 nf_conntrack_event_cache(master_ct(ct) ?
819 IPCT_RELATED : IPCT_NEW, ct);
823 nf_ct_add_to_dying_list(ct);
824 ret = nf_ct_resolve_clash(net, skb, ctinfo, h);
826 nf_conntrack_double_unlock(hash, reply_hash);
827 NF_CT_STAT_INC(net, insert_failed);
831 EXPORT_SYMBOL_GPL(__nf_conntrack_confirm);
833 /* Returns true if a connection correspondings to the tuple (required
836 nf_conntrack_tuple_taken(const struct nf_conntrack_tuple *tuple,
837 const struct nf_conn *ignored_conntrack)
839 struct net *net = nf_ct_net(ignored_conntrack);
840 const struct nf_conntrack_zone *zone;
841 struct nf_conntrack_tuple_hash *h;
842 struct hlist_nulls_head *ct_hash;
843 unsigned int hash, hsize;
844 struct hlist_nulls_node *n;
847 zone = nf_ct_zone(ignored_conntrack);
851 nf_conntrack_get_ht(&ct_hash, &hsize);
852 hash = __hash_conntrack(net, tuple, hsize);
854 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[hash], hnnode) {
855 ct = nf_ct_tuplehash_to_ctrack(h);
857 if (ct == ignored_conntrack)
860 if (nf_ct_is_expired(ct)) {
861 nf_ct_gc_expired(ct);
865 if (nf_ct_key_equal(h, tuple, zone, net)) {
866 NF_CT_STAT_INC_ATOMIC(net, found);
872 if (get_nulls_value(n) != hash) {
873 NF_CT_STAT_INC_ATOMIC(net, search_restart);
881 EXPORT_SYMBOL_GPL(nf_conntrack_tuple_taken);
883 #define NF_CT_EVICTION_RANGE 8
885 /* There's a small race here where we may free a just-assured
886 connection. Too bad: we're in trouble anyway. */
887 static unsigned int early_drop_list(struct net *net,
888 struct hlist_nulls_head *head)
890 struct nf_conntrack_tuple_hash *h;
891 struct hlist_nulls_node *n;
892 unsigned int drops = 0;
895 hlist_nulls_for_each_entry_rcu(h, n, head, hnnode) {
896 tmp = nf_ct_tuplehash_to_ctrack(h);
898 if (test_bit(IPS_OFFLOAD_BIT, &tmp->status))
901 if (nf_ct_is_expired(tmp)) {
902 nf_ct_gc_expired(tmp);
906 if (test_bit(IPS_ASSURED_BIT, &tmp->status) ||
907 !net_eq(nf_ct_net(tmp), net) ||
911 if (!atomic_inc_not_zero(&tmp->ct_general.use))
914 /* kill only if still in same netns -- might have moved due to
915 * SLAB_TYPESAFE_BY_RCU rules.
917 * We steal the timer reference. If that fails timer has
918 * already fired or someone else deleted it. Just drop ref
919 * and move to next entry.
921 if (net_eq(nf_ct_net(tmp), net) &&
922 nf_ct_is_confirmed(tmp) &&
923 nf_ct_delete(tmp, 0, 0))
932 static noinline int early_drop(struct net *net, unsigned int _hash)
936 for (i = 0; i < NF_CT_EVICTION_RANGE; i++) {
937 struct hlist_nulls_head *ct_hash;
938 unsigned int hash, hsize, drops;
941 nf_conntrack_get_ht(&ct_hash, &hsize);
942 hash = reciprocal_scale(_hash++, hsize);
944 drops = early_drop_list(net, &ct_hash[hash]);
948 NF_CT_STAT_ADD_ATOMIC(net, early_drop, drops);
956 static bool gc_worker_skip_ct(const struct nf_conn *ct)
958 return !nf_ct_is_confirmed(ct) || nf_ct_is_dying(ct);
961 static bool gc_worker_can_early_drop(const struct nf_conn *ct)
963 const struct nf_conntrack_l4proto *l4proto;
965 if (!test_bit(IPS_ASSURED_BIT, &ct->status))
968 l4proto = __nf_ct_l4proto_find(nf_ct_l3num(ct), nf_ct_protonum(ct));
969 if (l4proto->can_early_drop && l4proto->can_early_drop(ct))
975 #define DAY (86400 * HZ)
977 /* Set an arbitrary timeout large enough not to ever expire, this save
978 * us a check for the IPS_OFFLOAD_BIT from the packet path via
979 * nf_ct_is_expired().
981 static void nf_ct_offload_timeout(struct nf_conn *ct)
983 if (nf_ct_expires(ct) < DAY / 2)
984 ct->timeout = nfct_time_stamp + DAY;
987 static void gc_worker(struct work_struct *work)
989 unsigned int min_interval = max(HZ / GC_MAX_BUCKETS_DIV, 1u);
990 unsigned int i, goal, buckets = 0, expired_count = 0;
991 unsigned int nf_conntrack_max95 = 0;
992 struct conntrack_gc_work *gc_work;
993 unsigned int ratio, scanned = 0;
994 unsigned long next_run;
996 gc_work = container_of(work, struct conntrack_gc_work, dwork.work);
998 goal = nf_conntrack_htable_size / GC_MAX_BUCKETS_DIV;
999 i = gc_work->last_bucket;
1000 if (gc_work->early_drop)
1001 nf_conntrack_max95 = nf_conntrack_max / 100u * 95u;
1004 struct nf_conntrack_tuple_hash *h;
1005 struct hlist_nulls_head *ct_hash;
1006 struct hlist_nulls_node *n;
1007 unsigned int hashsz;
1008 struct nf_conn *tmp;
1013 nf_conntrack_get_ht(&ct_hash, &hashsz);
1017 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[i], hnnode) {
1020 tmp = nf_ct_tuplehash_to_ctrack(h);
1023 if (test_bit(IPS_OFFLOAD_BIT, &tmp->status)) {
1024 nf_ct_offload_timeout(tmp);
1028 if (nf_ct_is_expired(tmp)) {
1029 nf_ct_gc_expired(tmp);
1034 if (nf_conntrack_max95 == 0 || gc_worker_skip_ct(tmp))
1037 net = nf_ct_net(tmp);
1038 if (atomic_read(&net->ct.count) < nf_conntrack_max95)
1041 /* need to take reference to avoid possible races */
1042 if (!atomic_inc_not_zero(&tmp->ct_general.use))
1045 if (gc_worker_skip_ct(tmp)) {
1050 if (gc_worker_can_early_drop(tmp))
1056 /* could check get_nulls_value() here and restart if ct
1057 * was moved to another chain. But given gc is best-effort
1058 * we will just continue with next hash slot.
1062 } while (++buckets < goal);
1064 if (gc_work->exiting)
1068 * Eviction will normally happen from the packet path, and not
1069 * from this gc worker.
1071 * This worker is only here to reap expired entries when system went
1072 * idle after a busy period.
1074 * The heuristics below are supposed to balance conflicting goals:
1076 * 1. Minimize time until we notice a stale entry
1077 * 2. Maximize scan intervals to not waste cycles
1079 * Normally, expire ratio will be close to 0.
1081 * As soon as a sizeable fraction of the entries have expired
1082 * increase scan frequency.
1084 ratio = scanned ? expired_count * 100 / scanned : 0;
1085 if (ratio > GC_EVICT_RATIO) {
1086 gc_work->next_gc_run = min_interval;
1088 unsigned int max = GC_MAX_SCAN_JIFFIES / GC_MAX_BUCKETS_DIV;
1090 BUILD_BUG_ON((GC_MAX_SCAN_JIFFIES / GC_MAX_BUCKETS_DIV) == 0);
1092 gc_work->next_gc_run += min_interval;
1093 if (gc_work->next_gc_run > max)
1094 gc_work->next_gc_run = max;
1097 next_run = gc_work->next_gc_run;
1098 gc_work->last_bucket = i;
1099 gc_work->early_drop = false;
1100 queue_delayed_work(system_power_efficient_wq, &gc_work->dwork, next_run);
1103 static void conntrack_gc_work_init(struct conntrack_gc_work *gc_work)
1105 INIT_DEFERRABLE_WORK(&gc_work->dwork, gc_worker);
1106 gc_work->next_gc_run = HZ;
1107 gc_work->exiting = false;
1110 static struct nf_conn *
1111 __nf_conntrack_alloc(struct net *net,
1112 const struct nf_conntrack_zone *zone,
1113 const struct nf_conntrack_tuple *orig,
1114 const struct nf_conntrack_tuple *repl,
1115 gfp_t gfp, u32 hash)
1119 /* We don't want any race condition at early drop stage */
1120 atomic_inc(&net->ct.count);
1122 if (nf_conntrack_max &&
1123 unlikely(atomic_read(&net->ct.count) > nf_conntrack_max)) {
1124 if (!early_drop(net, hash)) {
1125 if (!conntrack_gc_work.early_drop)
1126 conntrack_gc_work.early_drop = true;
1127 atomic_dec(&net->ct.count);
1128 net_warn_ratelimited("nf_conntrack: table full, dropping packet\n");
1129 return ERR_PTR(-ENOMEM);
1134 * Do not use kmem_cache_zalloc(), as this cache uses
1135 * SLAB_TYPESAFE_BY_RCU.
1137 ct = kmem_cache_alloc(nf_conntrack_cachep, gfp);
1141 spin_lock_init(&ct->lock);
1142 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple = *orig;
1143 ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode.pprev = NULL;
1144 ct->tuplehash[IP_CT_DIR_REPLY].tuple = *repl;
1145 /* save hash for reusing when confirming */
1146 *(unsigned long *)(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev) = hash;
1148 write_pnet(&ct->ct_net, net);
1149 memset(&ct->__nfct_init_offset[0], 0,
1150 offsetof(struct nf_conn, proto) -
1151 offsetof(struct nf_conn, __nfct_init_offset[0]));
1153 nf_ct_zone_add(ct, zone);
1155 /* Because we use RCU lookups, we set ct_general.use to zero before
1156 * this is inserted in any list.
1158 atomic_set(&ct->ct_general.use, 0);
1161 atomic_dec(&net->ct.count);
1162 return ERR_PTR(-ENOMEM);
1165 struct nf_conn *nf_conntrack_alloc(struct net *net,
1166 const struct nf_conntrack_zone *zone,
1167 const struct nf_conntrack_tuple *orig,
1168 const struct nf_conntrack_tuple *repl,
1171 return __nf_conntrack_alloc(net, zone, orig, repl, gfp, 0);
1173 EXPORT_SYMBOL_GPL(nf_conntrack_alloc);
1175 void nf_conntrack_free(struct nf_conn *ct)
1177 struct net *net = nf_ct_net(ct);
1179 /* A freed object has refcnt == 0, that's
1180 * the golden rule for SLAB_TYPESAFE_BY_RCU
1182 WARN_ON(atomic_read(&ct->ct_general.use) != 0);
1184 nf_ct_ext_destroy(ct);
1186 kmem_cache_free(nf_conntrack_cachep, ct);
1187 smp_mb__before_atomic();
1188 atomic_dec(&net->ct.count);
1190 EXPORT_SYMBOL_GPL(nf_conntrack_free);
1193 /* Allocate a new conntrack: we return -ENOMEM if classification
1194 failed due to stress. Otherwise it really is unclassifiable. */
1195 static noinline struct nf_conntrack_tuple_hash *
1196 init_conntrack(struct net *net, struct nf_conn *tmpl,
1197 const struct nf_conntrack_tuple *tuple,
1198 const struct nf_conntrack_l3proto *l3proto,
1199 const struct nf_conntrack_l4proto *l4proto,
1200 struct sk_buff *skb,
1201 unsigned int dataoff, u32 hash)
1204 struct nf_conn_help *help;
1205 struct nf_conntrack_tuple repl_tuple;
1206 struct nf_conntrack_ecache *ecache;
1207 struct nf_conntrack_expect *exp = NULL;
1208 const struct nf_conntrack_zone *zone;
1209 struct nf_conn_timeout *timeout_ext;
1210 struct nf_conntrack_zone tmp;
1211 unsigned int *timeouts;
1213 if (!nf_ct_invert_tuple(&repl_tuple, tuple, l3proto, l4proto)) {
1214 pr_debug("Can't invert tuple.\n");
1218 zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1219 ct = __nf_conntrack_alloc(net, zone, tuple, &repl_tuple, GFP_ATOMIC,
1222 return (struct nf_conntrack_tuple_hash *)ct;
1224 if (!nf_ct_add_synproxy(ct, tmpl)) {
1225 nf_conntrack_free(ct);
1226 return ERR_PTR(-ENOMEM);
1229 timeout_ext = tmpl ? nf_ct_timeout_find(tmpl) : NULL;
1231 timeouts = nf_ct_timeout_data(timeout_ext);
1232 if (unlikely(!timeouts))
1233 timeouts = l4proto->get_timeouts(net);
1235 timeouts = l4proto->get_timeouts(net);
1238 if (!l4proto->new(ct, skb, dataoff, timeouts)) {
1239 nf_conntrack_free(ct);
1240 pr_debug("can't track with proto module\n");
1245 nf_ct_timeout_ext_add(ct, rcu_dereference(timeout_ext->timeout),
1248 nf_ct_acct_ext_add(ct, GFP_ATOMIC);
1249 nf_ct_tstamp_ext_add(ct, GFP_ATOMIC);
1250 nf_ct_labels_ext_add(ct);
1252 ecache = tmpl ? nf_ct_ecache_find(tmpl) : NULL;
1253 nf_ct_ecache_ext_add(ct, ecache ? ecache->ctmask : 0,
1254 ecache ? ecache->expmask : 0,
1258 if (net->ct.expect_count) {
1259 spin_lock(&nf_conntrack_expect_lock);
1260 exp = nf_ct_find_expectation(net, zone, tuple);
1262 pr_debug("expectation arrives ct=%p exp=%p\n",
1264 /* Welcome, Mr. Bond. We've been expecting you... */
1265 __set_bit(IPS_EXPECTED_BIT, &ct->status);
1266 /* exp->master safe, refcnt bumped in nf_ct_find_expectation */
1267 ct->master = exp->master;
1269 help = nf_ct_helper_ext_add(ct, exp->helper,
1272 rcu_assign_pointer(help->helper, exp->helper);
1275 #ifdef CONFIG_NF_CONNTRACK_MARK
1276 ct->mark = exp->master->mark;
1278 #ifdef CONFIG_NF_CONNTRACK_SECMARK
1279 ct->secmark = exp->master->secmark;
1281 NF_CT_STAT_INC(net, expect_new);
1283 spin_unlock(&nf_conntrack_expect_lock);
1286 __nf_ct_try_assign_helper(ct, tmpl, GFP_ATOMIC);
1288 /* Now it is inserted into the unconfirmed list, bump refcount */
1289 nf_conntrack_get(&ct->ct_general);
1290 nf_ct_add_to_unconfirmed_list(ct);
1296 exp->expectfn(ct, exp);
1297 nf_ct_expect_put(exp);
1300 return &ct->tuplehash[IP_CT_DIR_ORIGINAL];
1303 /* On success, returns 0, sets skb->_nfct | ctinfo */
1305 resolve_normal_ct(struct net *net, struct nf_conn *tmpl,
1306 struct sk_buff *skb,
1307 unsigned int dataoff,
1310 const struct nf_conntrack_l3proto *l3proto,
1311 const struct nf_conntrack_l4proto *l4proto)
1313 const struct nf_conntrack_zone *zone;
1314 struct nf_conntrack_tuple tuple;
1315 struct nf_conntrack_tuple_hash *h;
1316 enum ip_conntrack_info ctinfo;
1317 struct nf_conntrack_zone tmp;
1321 if (!nf_ct_get_tuple(skb, skb_network_offset(skb),
1322 dataoff, l3num, protonum, net, &tuple, l3proto,
1324 pr_debug("Can't get tuple\n");
1328 /* look for tuple match */
1329 zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1330 hash = hash_conntrack_raw(&tuple, net);
1331 h = __nf_conntrack_find_get(net, zone, &tuple, hash);
1333 h = init_conntrack(net, tmpl, &tuple, l3proto, l4proto,
1334 skb, dataoff, hash);
1340 ct = nf_ct_tuplehash_to_ctrack(h);
1342 /* It exists; we have (non-exclusive) reference. */
1343 if (NF_CT_DIRECTION(h) == IP_CT_DIR_REPLY) {
1344 ctinfo = IP_CT_ESTABLISHED_REPLY;
1346 /* Once we've had two way comms, always ESTABLISHED. */
1347 if (test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) {
1348 pr_debug("normal packet for %p\n", ct);
1349 ctinfo = IP_CT_ESTABLISHED;
1350 } else if (test_bit(IPS_EXPECTED_BIT, &ct->status)) {
1351 pr_debug("related packet for %p\n", ct);
1352 ctinfo = IP_CT_RELATED;
1354 pr_debug("new packet for %p\n", ct);
1358 nf_ct_set(skb, ct, ctinfo);
1363 nf_conntrack_in(struct net *net, u_int8_t pf, unsigned int hooknum,
1364 struct sk_buff *skb)
1366 const struct nf_conntrack_l3proto *l3proto;
1367 const struct nf_conntrack_l4proto *l4proto;
1368 struct nf_conn *ct, *tmpl;
1369 enum ip_conntrack_info ctinfo;
1370 unsigned int *timeouts;
1371 unsigned int dataoff;
1375 tmpl = nf_ct_get(skb, &ctinfo);
1376 if (tmpl || ctinfo == IP_CT_UNTRACKED) {
1377 /* Previously seen (loopback or untracked)? Ignore. */
1378 if ((tmpl && !nf_ct_is_template(tmpl)) ||
1379 ctinfo == IP_CT_UNTRACKED) {
1380 NF_CT_STAT_INC_ATOMIC(net, ignore);
1386 /* rcu_read_lock()ed by nf_hook_thresh */
1387 l3proto = __nf_ct_l3proto_find(pf);
1388 ret = l3proto->get_l4proto(skb, skb_network_offset(skb),
1389 &dataoff, &protonum);
1391 pr_debug("not prepared to track yet or error occurred\n");
1392 NF_CT_STAT_INC_ATOMIC(net, error);
1393 NF_CT_STAT_INC_ATOMIC(net, invalid);
1398 l4proto = __nf_ct_l4proto_find(pf, protonum);
1400 /* It may be an special packet, error, unclean...
1401 * inverse of the return code tells to the netfilter
1402 * core what to do with the packet. */
1403 if (l4proto->error != NULL) {
1404 ret = l4proto->error(net, tmpl, skb, dataoff, pf, hooknum);
1406 NF_CT_STAT_INC_ATOMIC(net, error);
1407 NF_CT_STAT_INC_ATOMIC(net, invalid);
1411 /* ICMP[v6] protocol trackers may assign one conntrack. */
1416 ret = resolve_normal_ct(net, tmpl, skb, dataoff, pf, protonum,
1419 /* Too stressed to deal. */
1420 NF_CT_STAT_INC_ATOMIC(net, drop);
1425 ct = nf_ct_get(skb, &ctinfo);
1427 /* Not valid part of a connection */
1428 NF_CT_STAT_INC_ATOMIC(net, invalid);
1433 /* Decide what timeout policy we want to apply to this flow. */
1434 timeouts = nf_ct_timeout_lookup(net, ct, l4proto);
1436 ret = l4proto->packet(ct, skb, dataoff, ctinfo, timeouts);
1438 /* Invalid: inverse of the return code tells
1439 * the netfilter core what to do */
1440 pr_debug("nf_conntrack_in: Can't track with proto module\n");
1441 nf_conntrack_put(&ct->ct_general);
1443 NF_CT_STAT_INC_ATOMIC(net, invalid);
1444 if (ret == -NF_DROP)
1445 NF_CT_STAT_INC_ATOMIC(net, drop);
1446 /* Special case: TCP tracker reports an attempt to reopen a
1447 * closed/aborted connection. We have to go back and create a
1450 if (ret == -NF_REPEAT)
1456 if (ctinfo == IP_CT_ESTABLISHED_REPLY &&
1457 !test_and_set_bit(IPS_SEEN_REPLY_BIT, &ct->status))
1458 nf_conntrack_event_cache(IPCT_REPLY, ct);
1465 EXPORT_SYMBOL_GPL(nf_conntrack_in);
1467 bool nf_ct_invert_tuplepr(struct nf_conntrack_tuple *inverse,
1468 const struct nf_conntrack_tuple *orig)
1473 ret = nf_ct_invert_tuple(inverse, orig,
1474 __nf_ct_l3proto_find(orig->src.l3num),
1475 __nf_ct_l4proto_find(orig->src.l3num,
1476 orig->dst.protonum));
1480 EXPORT_SYMBOL_GPL(nf_ct_invert_tuplepr);
1482 /* Alter reply tuple (maybe alter helper). This is for NAT, and is
1483 implicitly racy: see __nf_conntrack_confirm */
1484 void nf_conntrack_alter_reply(struct nf_conn *ct,
1485 const struct nf_conntrack_tuple *newreply)
1487 struct nf_conn_help *help = nfct_help(ct);
1489 /* Should be unconfirmed, so not in hash table yet */
1490 WARN_ON(nf_ct_is_confirmed(ct));
1492 pr_debug("Altering reply tuple of %p to ", ct);
1493 nf_ct_dump_tuple(newreply);
1495 ct->tuplehash[IP_CT_DIR_REPLY].tuple = *newreply;
1496 if (ct->master || (help && !hlist_empty(&help->expectations)))
1500 __nf_ct_try_assign_helper(ct, NULL, GFP_ATOMIC);
1503 EXPORT_SYMBOL_GPL(nf_conntrack_alter_reply);
1505 /* Refresh conntrack for this many jiffies and do accounting if do_acct is 1 */
1506 void __nf_ct_refresh_acct(struct nf_conn *ct,
1507 enum ip_conntrack_info ctinfo,
1508 const struct sk_buff *skb,
1509 unsigned long extra_jiffies,
1514 /* Only update if this is not a fixed timeout */
1515 if (test_bit(IPS_FIXED_TIMEOUT_BIT, &ct->status))
1518 /* If not in hash table, timer will not be active yet */
1519 if (nf_ct_is_confirmed(ct))
1520 extra_jiffies += nfct_time_stamp;
1522 ct->timeout = extra_jiffies;
1525 nf_ct_acct_update(ct, ctinfo, skb->len);
1527 EXPORT_SYMBOL_GPL(__nf_ct_refresh_acct);
1529 bool nf_ct_kill_acct(struct nf_conn *ct,
1530 enum ip_conntrack_info ctinfo,
1531 const struct sk_buff *skb)
1533 nf_ct_acct_update(ct, ctinfo, skb->len);
1535 return nf_ct_delete(ct, 0, 0);
1537 EXPORT_SYMBOL_GPL(nf_ct_kill_acct);
1539 #if IS_ENABLED(CONFIG_NF_CT_NETLINK)
1541 #include <linux/netfilter/nfnetlink.h>
1542 #include <linux/netfilter/nfnetlink_conntrack.h>
1543 #include <linux/mutex.h>
1545 /* Generic function for tcp/udp/sctp/dccp and alike. This needs to be
1546 * in ip_conntrack_core, since we don't want the protocols to autoload
1547 * or depend on ctnetlink */
1548 int nf_ct_port_tuple_to_nlattr(struct sk_buff *skb,
1549 const struct nf_conntrack_tuple *tuple)
1551 if (nla_put_be16(skb, CTA_PROTO_SRC_PORT, tuple->src.u.tcp.port) ||
1552 nla_put_be16(skb, CTA_PROTO_DST_PORT, tuple->dst.u.tcp.port))
1553 goto nla_put_failure;
1559 EXPORT_SYMBOL_GPL(nf_ct_port_tuple_to_nlattr);
1561 const struct nla_policy nf_ct_port_nla_policy[CTA_PROTO_MAX+1] = {
1562 [CTA_PROTO_SRC_PORT] = { .type = NLA_U16 },
1563 [CTA_PROTO_DST_PORT] = { .type = NLA_U16 },
1565 EXPORT_SYMBOL_GPL(nf_ct_port_nla_policy);
1567 int nf_ct_port_nlattr_to_tuple(struct nlattr *tb[],
1568 struct nf_conntrack_tuple *t)
1570 if (!tb[CTA_PROTO_SRC_PORT] || !tb[CTA_PROTO_DST_PORT])
1573 t->src.u.tcp.port = nla_get_be16(tb[CTA_PROTO_SRC_PORT]);
1574 t->dst.u.tcp.port = nla_get_be16(tb[CTA_PROTO_DST_PORT]);
1578 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_to_tuple);
1580 unsigned int nf_ct_port_nlattr_tuple_size(void)
1582 static unsigned int size __read_mostly;
1585 size = nla_policy_len(nf_ct_port_nla_policy, CTA_PROTO_MAX + 1);
1589 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_tuple_size);
1592 /* Used by ipt_REJECT and ip6t_REJECT. */
1593 static void nf_conntrack_attach(struct sk_buff *nskb, const struct sk_buff *skb)
1596 enum ip_conntrack_info ctinfo;
1598 /* This ICMP is in reverse direction to the packet which caused it */
1599 ct = nf_ct_get(skb, &ctinfo);
1600 if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL)
1601 ctinfo = IP_CT_RELATED_REPLY;
1603 ctinfo = IP_CT_RELATED;
1605 /* Attach to new skbuff, and increment count */
1606 nf_ct_set(nskb, ct, ctinfo);
1607 nf_conntrack_get(skb_nfct(nskb));
1610 static int nf_conntrack_update(struct net *net, struct sk_buff *skb)
1612 const struct nf_conntrack_l3proto *l3proto;
1613 const struct nf_conntrack_l4proto *l4proto;
1614 struct nf_conntrack_tuple_hash *h;
1615 struct nf_conntrack_tuple tuple;
1616 enum ip_conntrack_info ctinfo;
1617 struct nf_nat_hook *nat_hook;
1618 unsigned int dataoff, status;
1623 ct = nf_ct_get(skb, &ctinfo);
1624 if (!ct || nf_ct_is_confirmed(ct))
1627 l3num = nf_ct_l3num(ct);
1628 l3proto = nf_ct_l3proto_find_get(l3num);
1630 if (l3proto->get_l4proto(skb, skb_network_offset(skb), &dataoff,
1634 l4proto = nf_ct_l4proto_find_get(l3num, l4num);
1636 if (!nf_ct_get_tuple(skb, skb_network_offset(skb), dataoff, l3num,
1637 l4num, net, &tuple, l3proto, l4proto))
1640 if (ct->status & IPS_SRC_NAT) {
1641 memcpy(tuple.src.u3.all,
1642 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u3.all,
1643 sizeof(tuple.src.u3.all));
1645 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u.all;
1648 if (ct->status & IPS_DST_NAT) {
1649 memcpy(tuple.dst.u3.all,
1650 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.u3.all,
1651 sizeof(tuple.dst.u3.all));
1653 ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.u.all;
1656 h = nf_conntrack_find_get(net, nf_ct_zone(ct), &tuple);
1660 /* Store status bits of the conntrack that is clashing to re-do NAT
1661 * mangling according to what it has been done already to this packet.
1663 status = ct->status;
1666 ct = nf_ct_tuplehash_to_ctrack(h);
1667 nf_ct_set(skb, ct, ctinfo);
1669 nat_hook = rcu_dereference(nf_nat_hook);
1673 if (status & IPS_SRC_NAT &&
1674 nat_hook->manip_pkt(skb, ct, NF_NAT_MANIP_SRC,
1675 IP_CT_DIR_ORIGINAL) == NF_DROP)
1678 if (status & IPS_DST_NAT &&
1679 nat_hook->manip_pkt(skb, ct, NF_NAT_MANIP_DST,
1680 IP_CT_DIR_ORIGINAL) == NF_DROP)
1686 /* Bring out ya dead! */
1687 static struct nf_conn *
1688 get_next_corpse(int (*iter)(struct nf_conn *i, void *data),
1689 void *data, unsigned int *bucket)
1691 struct nf_conntrack_tuple_hash *h;
1693 struct hlist_nulls_node *n;
1696 for (; *bucket < nf_conntrack_htable_size; (*bucket)++) {
1697 lockp = &nf_conntrack_locks[*bucket % CONNTRACK_LOCKS];
1699 nf_conntrack_lock(lockp);
1700 if (*bucket < nf_conntrack_htable_size) {
1701 hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[*bucket], hnnode) {
1702 if (NF_CT_DIRECTION(h) != IP_CT_DIR_ORIGINAL)
1704 ct = nf_ct_tuplehash_to_ctrack(h);
1716 atomic_inc(&ct->ct_general.use);
1722 static void nf_ct_iterate_cleanup(int (*iter)(struct nf_conn *i, void *data),
1723 void *data, u32 portid, int report)
1725 unsigned int bucket = 0, sequence;
1731 sequence = read_seqcount_begin(&nf_conntrack_generation);
1733 while ((ct = get_next_corpse(iter, data, &bucket)) != NULL) {
1734 /* Time to push up daises... */
1736 nf_ct_delete(ct, portid, report);
1741 if (!read_seqcount_retry(&nf_conntrack_generation, sequence))
1748 int (*iter)(struct nf_conn *i, void *data);
1753 static int iter_net_only(struct nf_conn *i, void *data)
1755 struct iter_data *d = data;
1757 if (!net_eq(d->net, nf_ct_net(i)))
1760 return d->iter(i, d->data);
1764 __nf_ct_unconfirmed_destroy(struct net *net)
1768 for_each_possible_cpu(cpu) {
1769 struct nf_conntrack_tuple_hash *h;
1770 struct hlist_nulls_node *n;
1771 struct ct_pcpu *pcpu;
1773 pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
1775 spin_lock_bh(&pcpu->lock);
1776 hlist_nulls_for_each_entry(h, n, &pcpu->unconfirmed, hnnode) {
1779 ct = nf_ct_tuplehash_to_ctrack(h);
1781 /* we cannot call iter() on unconfirmed list, the
1782 * owning cpu can reallocate ct->ext at any time.
1784 set_bit(IPS_DYING_BIT, &ct->status);
1786 spin_unlock_bh(&pcpu->lock);
1791 void nf_ct_unconfirmed_destroy(struct net *net)
1795 if (atomic_read(&net->ct.count) > 0) {
1796 __nf_ct_unconfirmed_destroy(net);
1797 nf_queue_nf_hook_drop(net);
1801 EXPORT_SYMBOL_GPL(nf_ct_unconfirmed_destroy);
1803 void nf_ct_iterate_cleanup_net(struct net *net,
1804 int (*iter)(struct nf_conn *i, void *data),
1805 void *data, u32 portid, int report)
1811 if (atomic_read(&net->ct.count) == 0)
1818 nf_ct_iterate_cleanup(iter_net_only, &d, portid, report);
1820 EXPORT_SYMBOL_GPL(nf_ct_iterate_cleanup_net);
1823 * nf_ct_iterate_destroy - destroy unconfirmed conntracks and iterate table
1824 * @iter: callback to invoke for each conntrack
1825 * @data: data to pass to @iter
1827 * Like nf_ct_iterate_cleanup, but first marks conntracks on the
1828 * unconfirmed list as dying (so they will not be inserted into
1831 * Can only be called in module exit path.
1834 nf_ct_iterate_destroy(int (*iter)(struct nf_conn *i, void *data), void *data)
1838 down_read(&net_rwsem);
1840 if (atomic_read(&net->ct.count) == 0)
1842 __nf_ct_unconfirmed_destroy(net);
1843 nf_queue_nf_hook_drop(net);
1845 up_read(&net_rwsem);
1847 /* Need to wait for netns cleanup worker to finish, if its
1848 * running -- it might have deleted a net namespace from
1849 * the global list, so our __nf_ct_unconfirmed_destroy() might
1850 * not have affected all namespaces.
1854 /* a conntrack could have been unlinked from unconfirmed list
1855 * before we grabbed pcpu lock in __nf_ct_unconfirmed_destroy().
1856 * This makes sure its inserted into conntrack table.
1860 nf_ct_iterate_cleanup(iter, data, 0, 0);
1862 EXPORT_SYMBOL_GPL(nf_ct_iterate_destroy);
1864 static int kill_all(struct nf_conn *i, void *data)
1866 return net_eq(nf_ct_net(i), data);
1869 void nf_ct_free_hashtable(void *hash, unsigned int size)
1871 if (is_vmalloc_addr(hash))
1874 free_pages((unsigned long)hash,
1875 get_order(sizeof(struct hlist_head) * size));
1877 EXPORT_SYMBOL_GPL(nf_ct_free_hashtable);
1879 void nf_conntrack_cleanup_start(void)
1881 conntrack_gc_work.exiting = true;
1882 RCU_INIT_POINTER(ip_ct_attach, NULL);
1885 void nf_conntrack_cleanup_end(void)
1887 RCU_INIT_POINTER(nf_ct_hook, NULL);
1888 cancel_delayed_work_sync(&conntrack_gc_work.dwork);
1889 nf_ct_free_hashtable(nf_conntrack_hash, nf_conntrack_htable_size);
1891 nf_conntrack_proto_fini();
1892 nf_conntrack_seqadj_fini();
1893 nf_conntrack_labels_fini();
1894 nf_conntrack_helper_fini();
1895 nf_conntrack_timeout_fini();
1896 nf_conntrack_ecache_fini();
1897 nf_conntrack_tstamp_fini();
1898 nf_conntrack_acct_fini();
1899 nf_conntrack_expect_fini();
1901 kmem_cache_destroy(nf_conntrack_cachep);
1905 * Mishearing the voices in his head, our hero wonders how he's
1906 * supposed to kill the mall.
1908 void nf_conntrack_cleanup_net(struct net *net)
1912 list_add(&net->exit_list, &single);
1913 nf_conntrack_cleanup_net_list(&single);
1916 void nf_conntrack_cleanup_net_list(struct list_head *net_exit_list)
1922 * This makes sure all current packets have passed through
1923 * netfilter framework. Roll on, two-stage module
1929 list_for_each_entry(net, net_exit_list, exit_list) {
1930 nf_ct_iterate_cleanup(kill_all, net, 0, 0);
1931 if (atomic_read(&net->ct.count) != 0)
1936 goto i_see_dead_people;
1939 list_for_each_entry(net, net_exit_list, exit_list) {
1940 nf_conntrack_proto_pernet_fini(net);
1941 nf_conntrack_helper_pernet_fini(net);
1942 nf_conntrack_ecache_pernet_fini(net);
1943 nf_conntrack_tstamp_pernet_fini(net);
1944 nf_conntrack_acct_pernet_fini(net);
1945 nf_conntrack_expect_pernet_fini(net);
1946 free_percpu(net->ct.stat);
1947 free_percpu(net->ct.pcpu_lists);
1951 void *nf_ct_alloc_hashtable(unsigned int *sizep, int nulls)
1953 struct hlist_nulls_head *hash;
1954 unsigned int nr_slots, i;
1957 if (*sizep > (UINT_MAX / sizeof(struct hlist_nulls_head)))
1960 BUILD_BUG_ON(sizeof(struct hlist_nulls_head) != sizeof(struct hlist_head));
1961 nr_slots = *sizep = roundup(*sizep, PAGE_SIZE / sizeof(struct hlist_nulls_head));
1963 if (nr_slots > (UINT_MAX / sizeof(struct hlist_nulls_head)))
1966 sz = nr_slots * sizeof(struct hlist_nulls_head);
1967 hash = (void *)__get_free_pages(GFP_KERNEL | __GFP_NOWARN | __GFP_ZERO,
1973 for (i = 0; i < nr_slots; i++)
1974 INIT_HLIST_NULLS_HEAD(&hash[i], i);
1978 EXPORT_SYMBOL_GPL(nf_ct_alloc_hashtable);
1980 int nf_conntrack_hash_resize(unsigned int hashsize)
1983 unsigned int old_size;
1984 struct hlist_nulls_head *hash, *old_hash;
1985 struct nf_conntrack_tuple_hash *h;
1991 hash = nf_ct_alloc_hashtable(&hashsize, 1);
1995 old_size = nf_conntrack_htable_size;
1996 if (old_size == hashsize) {
1997 nf_ct_free_hashtable(hash, hashsize);
2002 nf_conntrack_all_lock();
2003 write_seqcount_begin(&nf_conntrack_generation);
2005 /* Lookups in the old hash might happen in parallel, which means we
2006 * might get false negatives during connection lookup. New connections
2007 * created because of a false negative won't make it into the hash
2008 * though since that required taking the locks.
2011 for (i = 0; i < nf_conntrack_htable_size; i++) {
2012 while (!hlist_nulls_empty(&nf_conntrack_hash[i])) {
2013 h = hlist_nulls_entry(nf_conntrack_hash[i].first,
2014 struct nf_conntrack_tuple_hash, hnnode);
2015 ct = nf_ct_tuplehash_to_ctrack(h);
2016 hlist_nulls_del_rcu(&h->hnnode);
2017 bucket = __hash_conntrack(nf_ct_net(ct),
2018 &h->tuple, hashsize);
2019 hlist_nulls_add_head_rcu(&h->hnnode, &hash[bucket]);
2022 old_size = nf_conntrack_htable_size;
2023 old_hash = nf_conntrack_hash;
2025 nf_conntrack_hash = hash;
2026 nf_conntrack_htable_size = hashsize;
2028 write_seqcount_end(&nf_conntrack_generation);
2029 nf_conntrack_all_unlock();
2033 nf_ct_free_hashtable(old_hash, old_size);
2037 int nf_conntrack_set_hashsize(const char *val, const struct kernel_param *kp)
2039 unsigned int hashsize;
2042 if (current->nsproxy->net_ns != &init_net)
2045 /* On boot, we can set this without any fancy locking. */
2046 if (!nf_conntrack_htable_size)
2047 return param_set_uint(val, kp);
2049 rc = kstrtouint(val, 0, &hashsize);
2053 return nf_conntrack_hash_resize(hashsize);
2055 EXPORT_SYMBOL_GPL(nf_conntrack_set_hashsize);
2057 module_param_call(hashsize, nf_conntrack_set_hashsize, param_get_uint,
2058 &nf_conntrack_htable_size, 0600);
2060 static __always_inline unsigned int total_extension_size(void)
2062 /* remember to add new extensions below */
2063 BUILD_BUG_ON(NF_CT_EXT_NUM > 9);
2065 return sizeof(struct nf_ct_ext) +
2066 sizeof(struct nf_conn_help)
2067 #if IS_ENABLED(CONFIG_NF_NAT)
2068 + sizeof(struct nf_conn_nat)
2070 + sizeof(struct nf_conn_seqadj)
2071 + sizeof(struct nf_conn_acct)
2072 #ifdef CONFIG_NF_CONNTRACK_EVENTS
2073 + sizeof(struct nf_conntrack_ecache)
2075 #ifdef CONFIG_NF_CONNTRACK_TIMESTAMP
2076 + sizeof(struct nf_conn_tstamp)
2078 #ifdef CONFIG_NF_CONNTRACK_TIMEOUT
2079 + sizeof(struct nf_conn_timeout)
2081 #ifdef CONFIG_NF_CONNTRACK_LABELS
2082 + sizeof(struct nf_conn_labels)
2084 #if IS_ENABLED(CONFIG_NETFILTER_SYNPROXY)
2085 + sizeof(struct nf_conn_synproxy)
2090 int nf_conntrack_init_start(void)
2096 /* struct nf_ct_ext uses u8 to store offsets/size */
2097 BUILD_BUG_ON(total_extension_size() > 255u);
2099 seqcount_init(&nf_conntrack_generation);
2101 for (i = 0; i < CONNTRACK_LOCKS; i++)
2102 spin_lock_init(&nf_conntrack_locks[i]);
2104 if (!nf_conntrack_htable_size) {
2105 /* Idea from tcp.c: use 1/16384 of memory.
2106 * On i386: 32MB machine has 512 buckets.
2107 * >= 1GB machines have 16384 buckets.
2108 * >= 4GB machines have 65536 buckets.
2110 nf_conntrack_htable_size
2111 = (((totalram_pages << PAGE_SHIFT) / 16384)
2112 / sizeof(struct hlist_head));
2113 if (totalram_pages > (4 * (1024 * 1024 * 1024 / PAGE_SIZE)))
2114 nf_conntrack_htable_size = 65536;
2115 else if (totalram_pages > (1024 * 1024 * 1024 / PAGE_SIZE))
2116 nf_conntrack_htable_size = 16384;
2117 if (nf_conntrack_htable_size < 32)
2118 nf_conntrack_htable_size = 32;
2120 /* Use a max. factor of four by default to get the same max as
2121 * with the old struct list_heads. When a table size is given
2122 * we use the old value of 8 to avoid reducing the max.
2127 nf_conntrack_hash = nf_ct_alloc_hashtable(&nf_conntrack_htable_size, 1);
2128 if (!nf_conntrack_hash)
2131 nf_conntrack_max = max_factor * nf_conntrack_htable_size;
2133 nf_conntrack_cachep = kmem_cache_create("nf_conntrack",
2134 sizeof(struct nf_conn),
2136 SLAB_TYPESAFE_BY_RCU | SLAB_HWCACHE_ALIGN, NULL);
2137 if (!nf_conntrack_cachep)
2140 ret = nf_conntrack_expect_init();
2144 ret = nf_conntrack_acct_init();
2148 ret = nf_conntrack_tstamp_init();
2152 ret = nf_conntrack_ecache_init();
2156 ret = nf_conntrack_timeout_init();
2160 ret = nf_conntrack_helper_init();
2164 ret = nf_conntrack_labels_init();
2168 ret = nf_conntrack_seqadj_init();
2172 ret = nf_conntrack_proto_init();
2176 conntrack_gc_work_init(&conntrack_gc_work);
2177 queue_delayed_work(system_power_efficient_wq, &conntrack_gc_work.dwork, HZ);
2182 nf_conntrack_seqadj_fini();
2184 nf_conntrack_labels_fini();
2186 nf_conntrack_helper_fini();
2188 nf_conntrack_timeout_fini();
2190 nf_conntrack_ecache_fini();
2192 nf_conntrack_tstamp_fini();
2194 nf_conntrack_acct_fini();
2196 nf_conntrack_expect_fini();
2198 kmem_cache_destroy(nf_conntrack_cachep);
2200 nf_ct_free_hashtable(nf_conntrack_hash, nf_conntrack_htable_size);
2204 static struct nf_ct_hook nf_conntrack_hook = {
2205 .update = nf_conntrack_update,
2206 .destroy = destroy_conntrack,
2209 void nf_conntrack_init_end(void)
2211 /* For use by REJECT target */
2212 RCU_INIT_POINTER(ip_ct_attach, nf_conntrack_attach);
2213 RCU_INIT_POINTER(nf_ct_hook, &nf_conntrack_hook);
2217 * We need to use special "null" values, not used in hash table
2219 #define UNCONFIRMED_NULLS_VAL ((1<<30)+0)
2220 #define DYING_NULLS_VAL ((1<<30)+1)
2221 #define TEMPLATE_NULLS_VAL ((1<<30)+2)
2223 int nf_conntrack_init_net(struct net *net)
2228 BUILD_BUG_ON(IP_CT_UNTRACKED == IP_CT_NUMBER);
2229 atomic_set(&net->ct.count, 0);
2231 net->ct.pcpu_lists = alloc_percpu(struct ct_pcpu);
2232 if (!net->ct.pcpu_lists)
2235 for_each_possible_cpu(cpu) {
2236 struct ct_pcpu *pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
2238 spin_lock_init(&pcpu->lock);
2239 INIT_HLIST_NULLS_HEAD(&pcpu->unconfirmed, UNCONFIRMED_NULLS_VAL);
2240 INIT_HLIST_NULLS_HEAD(&pcpu->dying, DYING_NULLS_VAL);
2243 net->ct.stat = alloc_percpu(struct ip_conntrack_stat);
2245 goto err_pcpu_lists;
2247 ret = nf_conntrack_expect_pernet_init(net);
2250 ret = nf_conntrack_acct_pernet_init(net);
2253 ret = nf_conntrack_tstamp_pernet_init(net);
2256 ret = nf_conntrack_ecache_pernet_init(net);
2259 ret = nf_conntrack_helper_pernet_init(net);
2262 ret = nf_conntrack_proto_pernet_init(net);
2268 nf_conntrack_helper_pernet_fini(net);
2270 nf_conntrack_ecache_pernet_fini(net);
2272 nf_conntrack_tstamp_pernet_fini(net);
2274 nf_conntrack_acct_pernet_fini(net);
2276 nf_conntrack_expect_pernet_fini(net);
2278 free_percpu(net->ct.stat);
2280 free_percpu(net->ct.pcpu_lists);