Merge tag 'spi-fix-v4.9-rc3' of git://git.kernel.org/pub/scm/linux/kernel/git/broonie/spi
[cascardo/linux.git] / net / netfilter / nf_conntrack_core.c
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
3    extension. */
4
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>
9  *
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.
13  */
14
15 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
16
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>
35 #include <linux/mm.h>
36 #include <linux/nsproxy.h>
37 #include <linux/rculist_nulls.h>
38
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>
58
59 #define NF_CONNTRACK_VERSION    "0.5.0"
60
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);
65
66 __cacheline_aligned_in_smp spinlock_t nf_conntrack_locks[CONNTRACK_LOCKS];
67 EXPORT_SYMBOL_GPL(nf_conntrack_locks);
68
69 __cacheline_aligned_in_smp DEFINE_SPINLOCK(nf_conntrack_expect_lock);
70 EXPORT_SYMBOL_GPL(nf_conntrack_expect_lock);
71
72 struct hlist_nulls_head *nf_conntrack_hash __read_mostly;
73 EXPORT_SYMBOL_GPL(nf_conntrack_hash);
74
75 struct conntrack_gc_work {
76         struct delayed_work     dwork;
77         u32                     last_bucket;
78         bool                    exiting;
79 };
80
81 static __read_mostly struct kmem_cache *nf_conntrack_cachep;
82 static __read_mostly spinlock_t nf_conntrack_locks_all_lock;
83 static __read_mostly DEFINE_SPINLOCK(nf_conntrack_locks_all_lock);
84 static __read_mostly bool nf_conntrack_locks_all;
85
86 #define GC_MAX_BUCKETS_DIV      64u
87 #define GC_MAX_BUCKETS          8192u
88 #define GC_INTERVAL             (5 * HZ)
89 #define GC_MAX_EVICTS           256u
90
91 static struct conntrack_gc_work conntrack_gc_work;
92
93 void nf_conntrack_lock(spinlock_t *lock) __acquires(lock)
94 {
95         spin_lock(lock);
96         while (unlikely(nf_conntrack_locks_all)) {
97                 spin_unlock(lock);
98
99                 /*
100                  * Order the 'nf_conntrack_locks_all' load vs. the
101                  * spin_unlock_wait() loads below, to ensure
102                  * that 'nf_conntrack_locks_all_lock' is indeed held:
103                  */
104                 smp_rmb(); /* spin_lock(&nf_conntrack_locks_all_lock) */
105                 spin_unlock_wait(&nf_conntrack_locks_all_lock);
106                 spin_lock(lock);
107         }
108 }
109 EXPORT_SYMBOL_GPL(nf_conntrack_lock);
110
111 static void nf_conntrack_double_unlock(unsigned int h1, unsigned int h2)
112 {
113         h1 %= CONNTRACK_LOCKS;
114         h2 %= CONNTRACK_LOCKS;
115         spin_unlock(&nf_conntrack_locks[h1]);
116         if (h1 != h2)
117                 spin_unlock(&nf_conntrack_locks[h2]);
118 }
119
120 /* return true if we need to recompute hashes (in case hash table was resized) */
121 static bool nf_conntrack_double_lock(struct net *net, unsigned int h1,
122                                      unsigned int h2, unsigned int sequence)
123 {
124         h1 %= CONNTRACK_LOCKS;
125         h2 %= CONNTRACK_LOCKS;
126         if (h1 <= h2) {
127                 nf_conntrack_lock(&nf_conntrack_locks[h1]);
128                 if (h1 != h2)
129                         spin_lock_nested(&nf_conntrack_locks[h2],
130                                          SINGLE_DEPTH_NESTING);
131         } else {
132                 nf_conntrack_lock(&nf_conntrack_locks[h2]);
133                 spin_lock_nested(&nf_conntrack_locks[h1],
134                                  SINGLE_DEPTH_NESTING);
135         }
136         if (read_seqcount_retry(&nf_conntrack_generation, sequence)) {
137                 nf_conntrack_double_unlock(h1, h2);
138                 return true;
139         }
140         return false;
141 }
142
143 static void nf_conntrack_all_lock(void)
144 {
145         int i;
146
147         spin_lock(&nf_conntrack_locks_all_lock);
148         nf_conntrack_locks_all = true;
149
150         /*
151          * Order the above store of 'nf_conntrack_locks_all' against
152          * the spin_unlock_wait() loads below, such that if
153          * nf_conntrack_lock() observes 'nf_conntrack_locks_all'
154          * we must observe nf_conntrack_locks[] held:
155          */
156         smp_mb(); /* spin_lock(&nf_conntrack_locks_all_lock) */
157
158         for (i = 0; i < CONNTRACK_LOCKS; i++) {
159                 spin_unlock_wait(&nf_conntrack_locks[i]);
160         }
161 }
162
163 static void nf_conntrack_all_unlock(void)
164 {
165         /*
166          * All prior stores must be complete before we clear
167          * 'nf_conntrack_locks_all'. Otherwise nf_conntrack_lock()
168          * might observe the false value but not the entire
169          * critical section:
170          */
171         smp_store_release(&nf_conntrack_locks_all, false);
172         spin_unlock(&nf_conntrack_locks_all_lock);
173 }
174
175 unsigned int nf_conntrack_htable_size __read_mostly;
176 EXPORT_SYMBOL_GPL(nf_conntrack_htable_size);
177
178 unsigned int nf_conntrack_max __read_mostly;
179 seqcount_t nf_conntrack_generation __read_mostly;
180
181 DEFINE_PER_CPU(struct nf_conn, nf_conntrack_untracked);
182 EXPORT_PER_CPU_SYMBOL(nf_conntrack_untracked);
183
184 static unsigned int nf_conntrack_hash_rnd __read_mostly;
185
186 static u32 hash_conntrack_raw(const struct nf_conntrack_tuple *tuple,
187                               const struct net *net)
188 {
189         unsigned int n;
190         u32 seed;
191
192         get_random_once(&nf_conntrack_hash_rnd, sizeof(nf_conntrack_hash_rnd));
193
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.
197          */
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));
203 }
204
205 static u32 scale_hash(u32 hash)
206 {
207         return reciprocal_scale(hash, nf_conntrack_htable_size);
208 }
209
210 static u32 __hash_conntrack(const struct net *net,
211                             const struct nf_conntrack_tuple *tuple,
212                             unsigned int size)
213 {
214         return reciprocal_scale(hash_conntrack_raw(tuple, net), size);
215 }
216
217 static u32 hash_conntrack(const struct net *net,
218                           const struct nf_conntrack_tuple *tuple)
219 {
220         return scale_hash(hash_conntrack_raw(tuple, net));
221 }
222
223 bool
224 nf_ct_get_tuple(const struct sk_buff *skb,
225                 unsigned int nhoff,
226                 unsigned int dataoff,
227                 u_int16_t l3num,
228                 u_int8_t protonum,
229                 struct net *net,
230                 struct nf_conntrack_tuple *tuple,
231                 const struct nf_conntrack_l3proto *l3proto,
232                 const struct nf_conntrack_l4proto *l4proto)
233 {
234         memset(tuple, 0, sizeof(*tuple));
235
236         tuple->src.l3num = l3num;
237         if (l3proto->pkt_to_tuple(skb, nhoff, tuple) == 0)
238                 return false;
239
240         tuple->dst.protonum = protonum;
241         tuple->dst.dir = IP_CT_DIR_ORIGINAL;
242
243         return l4proto->pkt_to_tuple(skb, dataoff, net, tuple);
244 }
245 EXPORT_SYMBOL_GPL(nf_ct_get_tuple);
246
247 bool nf_ct_get_tuplepr(const struct sk_buff *skb, unsigned int nhoff,
248                        u_int16_t l3num,
249                        struct net *net, struct nf_conntrack_tuple *tuple)
250 {
251         struct nf_conntrack_l3proto *l3proto;
252         struct nf_conntrack_l4proto *l4proto;
253         unsigned int protoff;
254         u_int8_t protonum;
255         int ret;
256
257         rcu_read_lock();
258
259         l3proto = __nf_ct_l3proto_find(l3num);
260         ret = l3proto->get_l4proto(skb, nhoff, &protoff, &protonum);
261         if (ret != NF_ACCEPT) {
262                 rcu_read_unlock();
263                 return false;
264         }
265
266         l4proto = __nf_ct_l4proto_find(l3num, protonum);
267
268         ret = nf_ct_get_tuple(skb, nhoff, protoff, l3num, protonum, net, tuple,
269                               l3proto, l4proto);
270
271         rcu_read_unlock();
272         return ret;
273 }
274 EXPORT_SYMBOL_GPL(nf_ct_get_tuplepr);
275
276 bool
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)
281 {
282         memset(inverse, 0, sizeof(*inverse));
283
284         inverse->src.l3num = orig->src.l3num;
285         if (l3proto->invert_tuple(inverse, orig) == 0)
286                 return false;
287
288         inverse->dst.dir = !orig->dst.dir;
289
290         inverse->dst.protonum = orig->dst.protonum;
291         return l4proto->invert_tuple(inverse, orig);
292 }
293 EXPORT_SYMBOL_GPL(nf_ct_invert_tuple);
294
295 static void
296 clean_from_lists(struct nf_conn *ct)
297 {
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);
301
302         /* Destroy all pending expectations */
303         nf_ct_remove_expectations(ct);
304 }
305
306 /* must be called with local_bh_disable */
307 static void nf_ct_add_to_dying_list(struct nf_conn *ct)
308 {
309         struct ct_pcpu *pcpu;
310
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);
314
315         spin_lock(&pcpu->lock);
316         hlist_nulls_add_head(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
317                              &pcpu->dying);
318         spin_unlock(&pcpu->lock);
319 }
320
321 /* must be called with local_bh_disable */
322 static void nf_ct_add_to_unconfirmed_list(struct nf_conn *ct)
323 {
324         struct ct_pcpu *pcpu;
325
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);
329
330         spin_lock(&pcpu->lock);
331         hlist_nulls_add_head(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
332                              &pcpu->unconfirmed);
333         spin_unlock(&pcpu->lock);
334 }
335
336 /* must be called with local_bh_disable */
337 static void nf_ct_del_from_dying_or_unconfirmed_list(struct nf_conn *ct)
338 {
339         struct ct_pcpu *pcpu;
340
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);
343
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);
348 }
349
350 /* Released via destroy_conntrack() */
351 struct nf_conn *nf_ct_tmpl_alloc(struct net *net,
352                                  const struct nf_conntrack_zone *zone,
353                                  gfp_t flags)
354 {
355         struct nf_conn *tmpl;
356
357         tmpl = kzalloc(sizeof(*tmpl), flags);
358         if (tmpl == NULL)
359                 return NULL;
360
361         tmpl->status = IPS_TEMPLATE;
362         write_pnet(&tmpl->ct_net, net);
363         nf_ct_zone_add(tmpl, zone);
364         atomic_set(&tmpl->ct_general.use, 0);
365
366         return tmpl;
367 }
368 EXPORT_SYMBOL_GPL(nf_ct_tmpl_alloc);
369
370 void nf_ct_tmpl_free(struct nf_conn *tmpl)
371 {
372         nf_ct_ext_destroy(tmpl);
373         nf_ct_ext_free(tmpl);
374         kfree(tmpl);
375 }
376 EXPORT_SYMBOL_GPL(nf_ct_tmpl_free);
377
378 static void
379 destroy_conntrack(struct nf_conntrack *nfct)
380 {
381         struct nf_conn *ct = (struct nf_conn *)nfct;
382         struct nf_conntrack_l4proto *l4proto;
383
384         pr_debug("destroy_conntrack(%p)\n", ct);
385         NF_CT_ASSERT(atomic_read(&nfct->use) == 0);
386
387         if (unlikely(nf_ct_is_template(ct))) {
388                 nf_ct_tmpl_free(ct);
389                 return;
390         }
391         rcu_read_lock();
392         l4proto = __nf_ct_l4proto_find(nf_ct_l3num(ct), nf_ct_protonum(ct));
393         if (l4proto->destroy)
394                 l4proto->destroy(ct);
395
396         rcu_read_unlock();
397
398         local_bh_disable();
399         /* Expectations will have been removed in clean_from_lists,
400          * except TFTP can create an expectation on the first packet,
401          * before connection is in the list, so we need to clean here,
402          * too.
403          */
404         nf_ct_remove_expectations(ct);
405
406         nf_ct_del_from_dying_or_unconfirmed_list(ct);
407
408         local_bh_enable();
409
410         if (ct->master)
411                 nf_ct_put(ct->master);
412
413         pr_debug("destroy_conntrack: returning ct=%p to slab\n", ct);
414         nf_conntrack_free(ct);
415 }
416
417 static void nf_ct_delete_from_lists(struct nf_conn *ct)
418 {
419         struct net *net = nf_ct_net(ct);
420         unsigned int hash, reply_hash;
421         unsigned int sequence;
422
423         nf_ct_helper_destroy(ct);
424
425         local_bh_disable();
426         do {
427                 sequence = read_seqcount_begin(&nf_conntrack_generation);
428                 hash = hash_conntrack(net,
429                                       &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
430                 reply_hash = hash_conntrack(net,
431                                            &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
432         } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
433
434         clean_from_lists(ct);
435         nf_conntrack_double_unlock(hash, reply_hash);
436
437         nf_ct_add_to_dying_list(ct);
438
439         local_bh_enable();
440 }
441
442 bool nf_ct_delete(struct nf_conn *ct, u32 portid, int report)
443 {
444         struct nf_conn_tstamp *tstamp;
445
446         if (test_and_set_bit(IPS_DYING_BIT, &ct->status))
447                 return false;
448
449         tstamp = nf_conn_tstamp_find(ct);
450         if (tstamp && tstamp->stop == 0)
451                 tstamp->stop = ktime_get_real_ns();
452
453         if (nf_conntrack_event_report(IPCT_DESTROY, ct,
454                                     portid, report) < 0) {
455                 /* destroy event was not delivered. nf_ct_put will
456                  * be done by event cache worker on redelivery.
457                  */
458                 nf_ct_delete_from_lists(ct);
459                 nf_conntrack_ecache_delayed_work(nf_ct_net(ct));
460                 return false;
461         }
462
463         nf_conntrack_ecache_work(nf_ct_net(ct));
464         nf_ct_delete_from_lists(ct);
465         nf_ct_put(ct);
466         return true;
467 }
468 EXPORT_SYMBOL_GPL(nf_ct_delete);
469
470 static inline bool
471 nf_ct_key_equal(struct nf_conntrack_tuple_hash *h,
472                 const struct nf_conntrack_tuple *tuple,
473                 const struct nf_conntrack_zone *zone,
474                 const struct net *net)
475 {
476         struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
477
478         /* A conntrack can be recreated with the equal tuple,
479          * so we need to check that the conntrack is confirmed
480          */
481         return nf_ct_tuple_equal(tuple, &h->tuple) &&
482                nf_ct_zone_equal(ct, zone, NF_CT_DIRECTION(h)) &&
483                nf_ct_is_confirmed(ct) &&
484                net_eq(net, nf_ct_net(ct));
485 }
486
487 /* caller must hold rcu readlock and none of the nf_conntrack_locks */
488 static void nf_ct_gc_expired(struct nf_conn *ct)
489 {
490         if (!atomic_inc_not_zero(&ct->ct_general.use))
491                 return;
492
493         if (nf_ct_should_gc(ct))
494                 nf_ct_kill(ct);
495
496         nf_ct_put(ct);
497 }
498
499 /*
500  * Warning :
501  * - Caller must take a reference on returned object
502  *   and recheck nf_ct_tuple_equal(tuple, &h->tuple)
503  */
504 static struct nf_conntrack_tuple_hash *
505 ____nf_conntrack_find(struct net *net, const struct nf_conntrack_zone *zone,
506                       const struct nf_conntrack_tuple *tuple, u32 hash)
507 {
508         struct nf_conntrack_tuple_hash *h;
509         struct hlist_nulls_head *ct_hash;
510         struct hlist_nulls_node *n;
511         unsigned int bucket, hsize;
512
513 begin:
514         nf_conntrack_get_ht(&ct_hash, &hsize);
515         bucket = reciprocal_scale(hash, hsize);
516
517         hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[bucket], hnnode) {
518                 struct nf_conn *ct;
519
520                 ct = nf_ct_tuplehash_to_ctrack(h);
521                 if (nf_ct_is_expired(ct)) {
522                         nf_ct_gc_expired(ct);
523                         continue;
524                 }
525
526                 if (nf_ct_is_dying(ct))
527                         continue;
528
529                 if (nf_ct_key_equal(h, tuple, zone, net))
530                         return h;
531         }
532         /*
533          * if the nulls value we got at the end of this lookup is
534          * not the expected one, we must restart lookup.
535          * We probably met an item that was moved to another chain.
536          */
537         if (get_nulls_value(n) != bucket) {
538                 NF_CT_STAT_INC_ATOMIC(net, search_restart);
539                 goto begin;
540         }
541
542         return NULL;
543 }
544
545 /* Find a connection corresponding to a tuple. */
546 static struct nf_conntrack_tuple_hash *
547 __nf_conntrack_find_get(struct net *net, const struct nf_conntrack_zone *zone,
548                         const struct nf_conntrack_tuple *tuple, u32 hash)
549 {
550         struct nf_conntrack_tuple_hash *h;
551         struct nf_conn *ct;
552
553         rcu_read_lock();
554 begin:
555         h = ____nf_conntrack_find(net, zone, tuple, hash);
556         if (h) {
557                 ct = nf_ct_tuplehash_to_ctrack(h);
558                 if (unlikely(nf_ct_is_dying(ct) ||
559                              !atomic_inc_not_zero(&ct->ct_general.use)))
560                         h = NULL;
561                 else {
562                         if (unlikely(!nf_ct_key_equal(h, tuple, zone, net))) {
563                                 nf_ct_put(ct);
564                                 goto begin;
565                         }
566                 }
567         }
568         rcu_read_unlock();
569
570         return h;
571 }
572
573 struct nf_conntrack_tuple_hash *
574 nf_conntrack_find_get(struct net *net, const struct nf_conntrack_zone *zone,
575                       const struct nf_conntrack_tuple *tuple)
576 {
577         return __nf_conntrack_find_get(net, zone, tuple,
578                                        hash_conntrack_raw(tuple, net));
579 }
580 EXPORT_SYMBOL_GPL(nf_conntrack_find_get);
581
582 static void __nf_conntrack_hash_insert(struct nf_conn *ct,
583                                        unsigned int hash,
584                                        unsigned int reply_hash)
585 {
586         hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
587                            &nf_conntrack_hash[hash]);
588         hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode,
589                            &nf_conntrack_hash[reply_hash]);
590 }
591
592 int
593 nf_conntrack_hash_check_insert(struct nf_conn *ct)
594 {
595         const struct nf_conntrack_zone *zone;
596         struct net *net = nf_ct_net(ct);
597         unsigned int hash, reply_hash;
598         struct nf_conntrack_tuple_hash *h;
599         struct hlist_nulls_node *n;
600         unsigned int sequence;
601
602         zone = nf_ct_zone(ct);
603
604         local_bh_disable();
605         do {
606                 sequence = read_seqcount_begin(&nf_conntrack_generation);
607                 hash = hash_conntrack(net,
608                                       &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
609                 reply_hash = hash_conntrack(net,
610                                            &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
611         } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
612
613         /* See if there's one in the list already, including reverse */
614         hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode)
615                 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
616                                     zone, net))
617                         goto out;
618
619         hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode)
620                 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
621                                     zone, net))
622                         goto out;
623
624         smp_wmb();
625         /* The caller holds a reference to this object */
626         atomic_set(&ct->ct_general.use, 2);
627         __nf_conntrack_hash_insert(ct, hash, reply_hash);
628         nf_conntrack_double_unlock(hash, reply_hash);
629         NF_CT_STAT_INC(net, insert);
630         local_bh_enable();
631         return 0;
632
633 out:
634         nf_conntrack_double_unlock(hash, reply_hash);
635         NF_CT_STAT_INC(net, insert_failed);
636         local_bh_enable();
637         return -EEXIST;
638 }
639 EXPORT_SYMBOL_GPL(nf_conntrack_hash_check_insert);
640
641 static inline void nf_ct_acct_update(struct nf_conn *ct,
642                                      enum ip_conntrack_info ctinfo,
643                                      unsigned int len)
644 {
645         struct nf_conn_acct *acct;
646
647         acct = nf_conn_acct_find(ct);
648         if (acct) {
649                 struct nf_conn_counter *counter = acct->counter;
650
651                 atomic64_inc(&counter[CTINFO2DIR(ctinfo)].packets);
652                 atomic64_add(len, &counter[CTINFO2DIR(ctinfo)].bytes);
653         }
654 }
655
656 static void nf_ct_acct_merge(struct nf_conn *ct, enum ip_conntrack_info ctinfo,
657                              const struct nf_conn *loser_ct)
658 {
659         struct nf_conn_acct *acct;
660
661         acct = nf_conn_acct_find(loser_ct);
662         if (acct) {
663                 struct nf_conn_counter *counter = acct->counter;
664                 unsigned int bytes;
665
666                 /* u32 should be fine since we must have seen one packet. */
667                 bytes = atomic64_read(&counter[CTINFO2DIR(ctinfo)].bytes);
668                 nf_ct_acct_update(ct, ctinfo, bytes);
669         }
670 }
671
672 /* Resolve race on insertion if this protocol allows this. */
673 static int nf_ct_resolve_clash(struct net *net, struct sk_buff *skb,
674                                enum ip_conntrack_info ctinfo,
675                                struct nf_conntrack_tuple_hash *h)
676 {
677         /* This is the conntrack entry already in hashes that won race. */
678         struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
679         struct nf_conntrack_l4proto *l4proto;
680
681         l4proto = __nf_ct_l4proto_find(nf_ct_l3num(ct), nf_ct_protonum(ct));
682         if (l4proto->allow_clash &&
683             !nfct_nat(ct) &&
684             !nf_ct_is_dying(ct) &&
685             atomic_inc_not_zero(&ct->ct_general.use)) {
686                 nf_ct_acct_merge(ct, ctinfo, (struct nf_conn *)skb->nfct);
687                 nf_conntrack_put(skb->nfct);
688                 /* Assign conntrack already in hashes to this skbuff. Don't
689                  * modify skb->nfctinfo to ensure consistent stateful filtering.
690                  */
691                 skb->nfct = &ct->ct_general;
692                 return NF_ACCEPT;
693         }
694         NF_CT_STAT_INC(net, drop);
695         return NF_DROP;
696 }
697
698 /* Confirm a connection given skb; places it in hash table */
699 int
700 __nf_conntrack_confirm(struct sk_buff *skb)
701 {
702         const struct nf_conntrack_zone *zone;
703         unsigned int hash, reply_hash;
704         struct nf_conntrack_tuple_hash *h;
705         struct nf_conn *ct;
706         struct nf_conn_help *help;
707         struct nf_conn_tstamp *tstamp;
708         struct hlist_nulls_node *n;
709         enum ip_conntrack_info ctinfo;
710         struct net *net;
711         unsigned int sequence;
712         int ret = NF_DROP;
713
714         ct = nf_ct_get(skb, &ctinfo);
715         net = nf_ct_net(ct);
716
717         /* ipt_REJECT uses nf_conntrack_attach to attach related
718            ICMP/TCP RST packets in other direction.  Actual packet
719            which created connection will be IP_CT_NEW or for an
720            expected connection, IP_CT_RELATED. */
721         if (CTINFO2DIR(ctinfo) != IP_CT_DIR_ORIGINAL)
722                 return NF_ACCEPT;
723
724         zone = nf_ct_zone(ct);
725         local_bh_disable();
726
727         do {
728                 sequence = read_seqcount_begin(&nf_conntrack_generation);
729                 /* reuse the hash saved before */
730                 hash = *(unsigned long *)&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev;
731                 hash = scale_hash(hash);
732                 reply_hash = hash_conntrack(net,
733                                            &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
734
735         } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
736
737         /* We're not in hash table, and we refuse to set up related
738          * connections for unconfirmed conns.  But packet copies and
739          * REJECT will give spurious warnings here.
740          */
741         /* NF_CT_ASSERT(atomic_read(&ct->ct_general.use) == 1); */
742
743         /* No external references means no one else could have
744          * confirmed us.
745          */
746         NF_CT_ASSERT(!nf_ct_is_confirmed(ct));
747         pr_debug("Confirming conntrack %p\n", ct);
748         /* We have to check the DYING flag after unlink to prevent
749          * a race against nf_ct_get_next_corpse() possibly called from
750          * user context, else we insert an already 'dead' hash, blocking
751          * further use of that particular connection -JM.
752          */
753         nf_ct_del_from_dying_or_unconfirmed_list(ct);
754
755         if (unlikely(nf_ct_is_dying(ct))) {
756                 nf_ct_add_to_dying_list(ct);
757                 goto dying;
758         }
759
760         /* See if there's one in the list already, including reverse:
761            NAT could have grabbed it without realizing, since we're
762            not in the hash.  If there is, we lost race. */
763         hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode)
764                 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
765                                     zone, net))
766                         goto out;
767
768         hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode)
769                 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
770                                     zone, net))
771                         goto out;
772
773         /* Timer relative to confirmation time, not original
774            setting time, otherwise we'd get timer wrap in
775            weird delay cases. */
776         ct->timeout += nfct_time_stamp;
777         atomic_inc(&ct->ct_general.use);
778         ct->status |= IPS_CONFIRMED;
779
780         /* set conntrack timestamp, if enabled. */
781         tstamp = nf_conn_tstamp_find(ct);
782         if (tstamp) {
783                 if (skb->tstamp.tv64 == 0)
784                         __net_timestamp(skb);
785
786                 tstamp->start = ktime_to_ns(skb->tstamp);
787         }
788         /* Since the lookup is lockless, hash insertion must be done after
789          * starting the timer and setting the CONFIRMED bit. The RCU barriers
790          * guarantee that no other CPU can find the conntrack before the above
791          * stores are visible.
792          */
793         __nf_conntrack_hash_insert(ct, hash, reply_hash);
794         nf_conntrack_double_unlock(hash, reply_hash);
795         local_bh_enable();
796
797         help = nfct_help(ct);
798         if (help && help->helper)
799                 nf_conntrack_event_cache(IPCT_HELPER, ct);
800
801         nf_conntrack_event_cache(master_ct(ct) ?
802                                  IPCT_RELATED : IPCT_NEW, ct);
803         return NF_ACCEPT;
804
805 out:
806         nf_ct_add_to_dying_list(ct);
807         ret = nf_ct_resolve_clash(net, skb, ctinfo, h);
808 dying:
809         nf_conntrack_double_unlock(hash, reply_hash);
810         NF_CT_STAT_INC(net, insert_failed);
811         local_bh_enable();
812         return ret;
813 }
814 EXPORT_SYMBOL_GPL(__nf_conntrack_confirm);
815
816 /* Returns true if a connection correspondings to the tuple (required
817    for NAT). */
818 int
819 nf_conntrack_tuple_taken(const struct nf_conntrack_tuple *tuple,
820                          const struct nf_conn *ignored_conntrack)
821 {
822         struct net *net = nf_ct_net(ignored_conntrack);
823         const struct nf_conntrack_zone *zone;
824         struct nf_conntrack_tuple_hash *h;
825         struct hlist_nulls_head *ct_hash;
826         unsigned int hash, hsize;
827         struct hlist_nulls_node *n;
828         struct nf_conn *ct;
829
830         zone = nf_ct_zone(ignored_conntrack);
831
832         rcu_read_lock();
833  begin:
834         nf_conntrack_get_ht(&ct_hash, &hsize);
835         hash = __hash_conntrack(net, tuple, hsize);
836
837         hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[hash], hnnode) {
838                 ct = nf_ct_tuplehash_to_ctrack(h);
839
840                 if (ct == ignored_conntrack)
841                         continue;
842
843                 if (nf_ct_is_expired(ct)) {
844                         nf_ct_gc_expired(ct);
845                         continue;
846                 }
847
848                 if (nf_ct_key_equal(h, tuple, zone, net)) {
849                         NF_CT_STAT_INC_ATOMIC(net, found);
850                         rcu_read_unlock();
851                         return 1;
852                 }
853         }
854
855         if (get_nulls_value(n) != hash) {
856                 NF_CT_STAT_INC_ATOMIC(net, search_restart);
857                 goto begin;
858         }
859
860         rcu_read_unlock();
861
862         return 0;
863 }
864 EXPORT_SYMBOL_GPL(nf_conntrack_tuple_taken);
865
866 #define NF_CT_EVICTION_RANGE    8
867
868 /* There's a small race here where we may free a just-assured
869    connection.  Too bad: we're in trouble anyway. */
870 static unsigned int early_drop_list(struct net *net,
871                                     struct hlist_nulls_head *head)
872 {
873         struct nf_conntrack_tuple_hash *h;
874         struct hlist_nulls_node *n;
875         unsigned int drops = 0;
876         struct nf_conn *tmp;
877
878         hlist_nulls_for_each_entry_rcu(h, n, head, hnnode) {
879                 tmp = nf_ct_tuplehash_to_ctrack(h);
880
881                 if (nf_ct_is_expired(tmp)) {
882                         nf_ct_gc_expired(tmp);
883                         continue;
884                 }
885
886                 if (test_bit(IPS_ASSURED_BIT, &tmp->status) ||
887                     !net_eq(nf_ct_net(tmp), net) ||
888                     nf_ct_is_dying(tmp))
889                         continue;
890
891                 if (!atomic_inc_not_zero(&tmp->ct_general.use))
892                         continue;
893
894                 /* kill only if still in same netns -- might have moved due to
895                  * SLAB_DESTROY_BY_RCU rules.
896                  *
897                  * We steal the timer reference.  If that fails timer has
898                  * already fired or someone else deleted it. Just drop ref
899                  * and move to next entry.
900                  */
901                 if (net_eq(nf_ct_net(tmp), net) &&
902                     nf_ct_is_confirmed(tmp) &&
903                     nf_ct_delete(tmp, 0, 0))
904                         drops++;
905
906                 nf_ct_put(tmp);
907         }
908
909         return drops;
910 }
911
912 static noinline int early_drop(struct net *net, unsigned int _hash)
913 {
914         unsigned int i;
915
916         for (i = 0; i < NF_CT_EVICTION_RANGE; i++) {
917                 struct hlist_nulls_head *ct_hash;
918                 unsigned int hash, hsize, drops;
919
920                 rcu_read_lock();
921                 nf_conntrack_get_ht(&ct_hash, &hsize);
922                 hash = reciprocal_scale(_hash++, hsize);
923
924                 drops = early_drop_list(net, &ct_hash[hash]);
925                 rcu_read_unlock();
926
927                 if (drops) {
928                         NF_CT_STAT_ADD_ATOMIC(net, early_drop, drops);
929                         return true;
930                 }
931         }
932
933         return false;
934 }
935
936 static void gc_worker(struct work_struct *work)
937 {
938         unsigned int i, goal, buckets = 0, expired_count = 0;
939         unsigned long next_run = GC_INTERVAL;
940         unsigned int ratio, scanned = 0;
941         struct conntrack_gc_work *gc_work;
942
943         gc_work = container_of(work, struct conntrack_gc_work, dwork.work);
944
945         goal = min(nf_conntrack_htable_size / GC_MAX_BUCKETS_DIV, GC_MAX_BUCKETS);
946         i = gc_work->last_bucket;
947
948         do {
949                 struct nf_conntrack_tuple_hash *h;
950                 struct hlist_nulls_head *ct_hash;
951                 struct hlist_nulls_node *n;
952                 unsigned int hashsz;
953                 struct nf_conn *tmp;
954
955                 i++;
956                 rcu_read_lock();
957
958                 nf_conntrack_get_ht(&ct_hash, &hashsz);
959                 if (i >= hashsz)
960                         i = 0;
961
962                 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[i], hnnode) {
963                         tmp = nf_ct_tuplehash_to_ctrack(h);
964
965                         scanned++;
966                         if (nf_ct_is_expired(tmp)) {
967                                 nf_ct_gc_expired(tmp);
968                                 expired_count++;
969                                 continue;
970                         }
971                 }
972
973                 /* could check get_nulls_value() here and restart if ct
974                  * was moved to another chain.  But given gc is best-effort
975                  * we will just continue with next hash slot.
976                  */
977                 rcu_read_unlock();
978                 cond_resched_rcu_qs();
979         } while (++buckets < goal &&
980                  expired_count < GC_MAX_EVICTS);
981
982         if (gc_work->exiting)
983                 return;
984
985         ratio = scanned ? expired_count * 100 / scanned : 0;
986         if (ratio >= 90 || expired_count == GC_MAX_EVICTS)
987                 next_run = 0;
988
989         gc_work->last_bucket = i;
990         schedule_delayed_work(&gc_work->dwork, next_run);
991 }
992
993 static void conntrack_gc_work_init(struct conntrack_gc_work *gc_work)
994 {
995         INIT_DELAYED_WORK(&gc_work->dwork, gc_worker);
996         gc_work->exiting = false;
997 }
998
999 static struct nf_conn *
1000 __nf_conntrack_alloc(struct net *net,
1001                      const struct nf_conntrack_zone *zone,
1002                      const struct nf_conntrack_tuple *orig,
1003                      const struct nf_conntrack_tuple *repl,
1004                      gfp_t gfp, u32 hash)
1005 {
1006         struct nf_conn *ct;
1007
1008         /* We don't want any race condition at early drop stage */
1009         atomic_inc(&net->ct.count);
1010
1011         if (nf_conntrack_max &&
1012             unlikely(atomic_read(&net->ct.count) > nf_conntrack_max)) {
1013                 if (!early_drop(net, hash)) {
1014                         atomic_dec(&net->ct.count);
1015                         net_warn_ratelimited("nf_conntrack: table full, dropping packet\n");
1016                         return ERR_PTR(-ENOMEM);
1017                 }
1018         }
1019
1020         /*
1021          * Do not use kmem_cache_zalloc(), as this cache uses
1022          * SLAB_DESTROY_BY_RCU.
1023          */
1024         ct = kmem_cache_alloc(nf_conntrack_cachep, gfp);
1025         if (ct == NULL)
1026                 goto out;
1027
1028         spin_lock_init(&ct->lock);
1029         ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple = *orig;
1030         ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode.pprev = NULL;
1031         ct->tuplehash[IP_CT_DIR_REPLY].tuple = *repl;
1032         /* save hash for reusing when confirming */
1033         *(unsigned long *)(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev) = hash;
1034         ct->status = 0;
1035         write_pnet(&ct->ct_net, net);
1036         memset(&ct->__nfct_init_offset[0], 0,
1037                offsetof(struct nf_conn, proto) -
1038                offsetof(struct nf_conn, __nfct_init_offset[0]));
1039
1040         nf_ct_zone_add(ct, zone);
1041
1042         /* Because we use RCU lookups, we set ct_general.use to zero before
1043          * this is inserted in any list.
1044          */
1045         atomic_set(&ct->ct_general.use, 0);
1046         return ct;
1047 out:
1048         atomic_dec(&net->ct.count);
1049         return ERR_PTR(-ENOMEM);
1050 }
1051
1052 struct nf_conn *nf_conntrack_alloc(struct net *net,
1053                                    const struct nf_conntrack_zone *zone,
1054                                    const struct nf_conntrack_tuple *orig,
1055                                    const struct nf_conntrack_tuple *repl,
1056                                    gfp_t gfp)
1057 {
1058         return __nf_conntrack_alloc(net, zone, orig, repl, gfp, 0);
1059 }
1060 EXPORT_SYMBOL_GPL(nf_conntrack_alloc);
1061
1062 void nf_conntrack_free(struct nf_conn *ct)
1063 {
1064         struct net *net = nf_ct_net(ct);
1065
1066         /* A freed object has refcnt == 0, that's
1067          * the golden rule for SLAB_DESTROY_BY_RCU
1068          */
1069         NF_CT_ASSERT(atomic_read(&ct->ct_general.use) == 0);
1070
1071         nf_ct_ext_destroy(ct);
1072         nf_ct_ext_free(ct);
1073         kmem_cache_free(nf_conntrack_cachep, ct);
1074         smp_mb__before_atomic();
1075         atomic_dec(&net->ct.count);
1076 }
1077 EXPORT_SYMBOL_GPL(nf_conntrack_free);
1078
1079
1080 /* Allocate a new conntrack: we return -ENOMEM if classification
1081    failed due to stress.  Otherwise it really is unclassifiable. */
1082 static struct nf_conntrack_tuple_hash *
1083 init_conntrack(struct net *net, struct nf_conn *tmpl,
1084                const struct nf_conntrack_tuple *tuple,
1085                struct nf_conntrack_l3proto *l3proto,
1086                struct nf_conntrack_l4proto *l4proto,
1087                struct sk_buff *skb,
1088                unsigned int dataoff, u32 hash)
1089 {
1090         struct nf_conn *ct;
1091         struct nf_conn_help *help;
1092         struct nf_conntrack_tuple repl_tuple;
1093         struct nf_conntrack_ecache *ecache;
1094         struct nf_conntrack_expect *exp = NULL;
1095         const struct nf_conntrack_zone *zone;
1096         struct nf_conn_timeout *timeout_ext;
1097         struct nf_conntrack_zone tmp;
1098         unsigned int *timeouts;
1099
1100         if (!nf_ct_invert_tuple(&repl_tuple, tuple, l3proto, l4proto)) {
1101                 pr_debug("Can't invert tuple.\n");
1102                 return NULL;
1103         }
1104
1105         zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1106         ct = __nf_conntrack_alloc(net, zone, tuple, &repl_tuple, GFP_ATOMIC,
1107                                   hash);
1108         if (IS_ERR(ct))
1109                 return (struct nf_conntrack_tuple_hash *)ct;
1110
1111         if (!nf_ct_add_synproxy(ct, tmpl)) {
1112                 nf_conntrack_free(ct);
1113                 return ERR_PTR(-ENOMEM);
1114         }
1115
1116         timeout_ext = tmpl ? nf_ct_timeout_find(tmpl) : NULL;
1117         if (timeout_ext) {
1118                 timeouts = nf_ct_timeout_data(timeout_ext);
1119                 if (unlikely(!timeouts))
1120                         timeouts = l4proto->get_timeouts(net);
1121         } else {
1122                 timeouts = l4proto->get_timeouts(net);
1123         }
1124
1125         if (!l4proto->new(ct, skb, dataoff, timeouts)) {
1126                 nf_conntrack_free(ct);
1127                 pr_debug("can't track with proto module\n");
1128                 return NULL;
1129         }
1130
1131         if (timeout_ext)
1132                 nf_ct_timeout_ext_add(ct, rcu_dereference(timeout_ext->timeout),
1133                                       GFP_ATOMIC);
1134
1135         nf_ct_acct_ext_add(ct, GFP_ATOMIC);
1136         nf_ct_tstamp_ext_add(ct, GFP_ATOMIC);
1137         nf_ct_labels_ext_add(ct);
1138
1139         ecache = tmpl ? nf_ct_ecache_find(tmpl) : NULL;
1140         nf_ct_ecache_ext_add(ct, ecache ? ecache->ctmask : 0,
1141                                  ecache ? ecache->expmask : 0,
1142                              GFP_ATOMIC);
1143
1144         local_bh_disable();
1145         if (net->ct.expect_count) {
1146                 spin_lock(&nf_conntrack_expect_lock);
1147                 exp = nf_ct_find_expectation(net, zone, tuple);
1148                 if (exp) {
1149                         pr_debug("expectation arrives ct=%p exp=%p\n",
1150                                  ct, exp);
1151                         /* Welcome, Mr. Bond.  We've been expecting you... */
1152                         __set_bit(IPS_EXPECTED_BIT, &ct->status);
1153                         /* exp->master safe, refcnt bumped in nf_ct_find_expectation */
1154                         ct->master = exp->master;
1155                         if (exp->helper) {
1156                                 help = nf_ct_helper_ext_add(ct, exp->helper,
1157                                                             GFP_ATOMIC);
1158                                 if (help)
1159                                         rcu_assign_pointer(help->helper, exp->helper);
1160                         }
1161
1162 #ifdef CONFIG_NF_CONNTRACK_MARK
1163                         ct->mark = exp->master->mark;
1164 #endif
1165 #ifdef CONFIG_NF_CONNTRACK_SECMARK
1166                         ct->secmark = exp->master->secmark;
1167 #endif
1168                         NF_CT_STAT_INC(net, expect_new);
1169                 }
1170                 spin_unlock(&nf_conntrack_expect_lock);
1171         }
1172         if (!exp)
1173                 __nf_ct_try_assign_helper(ct, tmpl, GFP_ATOMIC);
1174
1175         /* Now it is inserted into the unconfirmed list, bump refcount */
1176         nf_conntrack_get(&ct->ct_general);
1177         nf_ct_add_to_unconfirmed_list(ct);
1178
1179         local_bh_enable();
1180
1181         if (exp) {
1182                 if (exp->expectfn)
1183                         exp->expectfn(ct, exp);
1184                 nf_ct_expect_put(exp);
1185         }
1186
1187         return &ct->tuplehash[IP_CT_DIR_ORIGINAL];
1188 }
1189
1190 /* On success, returns conntrack ptr, sets skb->nfct and ctinfo */
1191 static inline struct nf_conn *
1192 resolve_normal_ct(struct net *net, struct nf_conn *tmpl,
1193                   struct sk_buff *skb,
1194                   unsigned int dataoff,
1195                   u_int16_t l3num,
1196                   u_int8_t protonum,
1197                   struct nf_conntrack_l3proto *l3proto,
1198                   struct nf_conntrack_l4proto *l4proto,
1199                   int *set_reply,
1200                   enum ip_conntrack_info *ctinfo)
1201 {
1202         const struct nf_conntrack_zone *zone;
1203         struct nf_conntrack_tuple tuple;
1204         struct nf_conntrack_tuple_hash *h;
1205         struct nf_conntrack_zone tmp;
1206         struct nf_conn *ct;
1207         u32 hash;
1208
1209         if (!nf_ct_get_tuple(skb, skb_network_offset(skb),
1210                              dataoff, l3num, protonum, net, &tuple, l3proto,
1211                              l4proto)) {
1212                 pr_debug("Can't get tuple\n");
1213                 return NULL;
1214         }
1215
1216         /* look for tuple match */
1217         zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1218         hash = hash_conntrack_raw(&tuple, net);
1219         h = __nf_conntrack_find_get(net, zone, &tuple, hash);
1220         if (!h) {
1221                 h = init_conntrack(net, tmpl, &tuple, l3proto, l4proto,
1222                                    skb, dataoff, hash);
1223                 if (!h)
1224                         return NULL;
1225                 if (IS_ERR(h))
1226                         return (void *)h;
1227         }
1228         ct = nf_ct_tuplehash_to_ctrack(h);
1229
1230         /* It exists; we have (non-exclusive) reference. */
1231         if (NF_CT_DIRECTION(h) == IP_CT_DIR_REPLY) {
1232                 *ctinfo = IP_CT_ESTABLISHED_REPLY;
1233                 /* Please set reply bit if this packet OK */
1234                 *set_reply = 1;
1235         } else {
1236                 /* Once we've had two way comms, always ESTABLISHED. */
1237                 if (test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) {
1238                         pr_debug("normal packet for %p\n", ct);
1239                         *ctinfo = IP_CT_ESTABLISHED;
1240                 } else if (test_bit(IPS_EXPECTED_BIT, &ct->status)) {
1241                         pr_debug("related packet for %p\n", ct);
1242                         *ctinfo = IP_CT_RELATED;
1243                 } else {
1244                         pr_debug("new packet for %p\n", ct);
1245                         *ctinfo = IP_CT_NEW;
1246                 }
1247                 *set_reply = 0;
1248         }
1249         skb->nfct = &ct->ct_general;
1250         skb->nfctinfo = *ctinfo;
1251         return ct;
1252 }
1253
1254 unsigned int
1255 nf_conntrack_in(struct net *net, u_int8_t pf, unsigned int hooknum,
1256                 struct sk_buff *skb)
1257 {
1258         struct nf_conn *ct, *tmpl = NULL;
1259         enum ip_conntrack_info ctinfo;
1260         struct nf_conntrack_l3proto *l3proto;
1261         struct nf_conntrack_l4proto *l4proto;
1262         unsigned int *timeouts;
1263         unsigned int dataoff;
1264         u_int8_t protonum;
1265         int set_reply = 0;
1266         int ret;
1267
1268         if (skb->nfct) {
1269                 /* Previously seen (loopback or untracked)?  Ignore. */
1270                 tmpl = (struct nf_conn *)skb->nfct;
1271                 if (!nf_ct_is_template(tmpl)) {
1272                         NF_CT_STAT_INC_ATOMIC(net, ignore);
1273                         return NF_ACCEPT;
1274                 }
1275                 skb->nfct = NULL;
1276         }
1277
1278         /* rcu_read_lock()ed by nf_hook_thresh */
1279         l3proto = __nf_ct_l3proto_find(pf);
1280         ret = l3proto->get_l4proto(skb, skb_network_offset(skb),
1281                                    &dataoff, &protonum);
1282         if (ret <= 0) {
1283                 pr_debug("not prepared to track yet or error occurred\n");
1284                 NF_CT_STAT_INC_ATOMIC(net, error);
1285                 NF_CT_STAT_INC_ATOMIC(net, invalid);
1286                 ret = -ret;
1287                 goto out;
1288         }
1289
1290         l4proto = __nf_ct_l4proto_find(pf, protonum);
1291
1292         /* It may be an special packet, error, unclean...
1293          * inverse of the return code tells to the netfilter
1294          * core what to do with the packet. */
1295         if (l4proto->error != NULL) {
1296                 ret = l4proto->error(net, tmpl, skb, dataoff, &ctinfo,
1297                                      pf, hooknum);
1298                 if (ret <= 0) {
1299                         NF_CT_STAT_INC_ATOMIC(net, error);
1300                         NF_CT_STAT_INC_ATOMIC(net, invalid);
1301                         ret = -ret;
1302                         goto out;
1303                 }
1304                 /* ICMP[v6] protocol trackers may assign one conntrack. */
1305                 if (skb->nfct)
1306                         goto out;
1307         }
1308
1309         ct = resolve_normal_ct(net, tmpl, skb, dataoff, pf, protonum,
1310                                l3proto, l4proto, &set_reply, &ctinfo);
1311         if (!ct) {
1312                 /* Not valid part of a connection */
1313                 NF_CT_STAT_INC_ATOMIC(net, invalid);
1314                 ret = NF_ACCEPT;
1315                 goto out;
1316         }
1317
1318         if (IS_ERR(ct)) {
1319                 /* Too stressed to deal. */
1320                 NF_CT_STAT_INC_ATOMIC(net, drop);
1321                 ret = NF_DROP;
1322                 goto out;
1323         }
1324
1325         NF_CT_ASSERT(skb->nfct);
1326
1327         /* Decide what timeout policy we want to apply to this flow. */
1328         timeouts = nf_ct_timeout_lookup(net, ct, l4proto);
1329
1330         ret = l4proto->packet(ct, skb, dataoff, ctinfo, pf, hooknum, timeouts);
1331         if (ret <= 0) {
1332                 /* Invalid: inverse of the return code tells
1333                  * the netfilter core what to do */
1334                 pr_debug("nf_conntrack_in: Can't track with proto module\n");
1335                 nf_conntrack_put(skb->nfct);
1336                 skb->nfct = NULL;
1337                 NF_CT_STAT_INC_ATOMIC(net, invalid);
1338                 if (ret == -NF_DROP)
1339                         NF_CT_STAT_INC_ATOMIC(net, drop);
1340                 ret = -ret;
1341                 goto out;
1342         }
1343
1344         if (set_reply && !test_and_set_bit(IPS_SEEN_REPLY_BIT, &ct->status))
1345                 nf_conntrack_event_cache(IPCT_REPLY, ct);
1346 out:
1347         if (tmpl) {
1348                 /* Special case: we have to repeat this hook, assign the
1349                  * template again to this packet. We assume that this packet
1350                  * has no conntrack assigned. This is used by nf_ct_tcp. */
1351                 if (ret == NF_REPEAT)
1352                         skb->nfct = (struct nf_conntrack *)tmpl;
1353                 else
1354                         nf_ct_put(tmpl);
1355         }
1356
1357         return ret;
1358 }
1359 EXPORT_SYMBOL_GPL(nf_conntrack_in);
1360
1361 bool nf_ct_invert_tuplepr(struct nf_conntrack_tuple *inverse,
1362                           const struct nf_conntrack_tuple *orig)
1363 {
1364         bool ret;
1365
1366         rcu_read_lock();
1367         ret = nf_ct_invert_tuple(inverse, orig,
1368                                  __nf_ct_l3proto_find(orig->src.l3num),
1369                                  __nf_ct_l4proto_find(orig->src.l3num,
1370                                                       orig->dst.protonum));
1371         rcu_read_unlock();
1372         return ret;
1373 }
1374 EXPORT_SYMBOL_GPL(nf_ct_invert_tuplepr);
1375
1376 /* Alter reply tuple (maybe alter helper).  This is for NAT, and is
1377    implicitly racy: see __nf_conntrack_confirm */
1378 void nf_conntrack_alter_reply(struct nf_conn *ct,
1379                               const struct nf_conntrack_tuple *newreply)
1380 {
1381         struct nf_conn_help *help = nfct_help(ct);
1382
1383         /* Should be unconfirmed, so not in hash table yet */
1384         NF_CT_ASSERT(!nf_ct_is_confirmed(ct));
1385
1386         pr_debug("Altering reply tuple of %p to ", ct);
1387         nf_ct_dump_tuple(newreply);
1388
1389         ct->tuplehash[IP_CT_DIR_REPLY].tuple = *newreply;
1390         if (ct->master || (help && !hlist_empty(&help->expectations)))
1391                 return;
1392
1393         rcu_read_lock();
1394         __nf_ct_try_assign_helper(ct, NULL, GFP_ATOMIC);
1395         rcu_read_unlock();
1396 }
1397 EXPORT_SYMBOL_GPL(nf_conntrack_alter_reply);
1398
1399 /* Refresh conntrack for this many jiffies and do accounting if do_acct is 1 */
1400 void __nf_ct_refresh_acct(struct nf_conn *ct,
1401                           enum ip_conntrack_info ctinfo,
1402                           const struct sk_buff *skb,
1403                           unsigned long extra_jiffies,
1404                           int do_acct)
1405 {
1406         NF_CT_ASSERT(skb);
1407
1408         /* Only update if this is not a fixed timeout */
1409         if (test_bit(IPS_FIXED_TIMEOUT_BIT, &ct->status))
1410                 goto acct;
1411
1412         /* If not in hash table, timer will not be active yet */
1413         if (nf_ct_is_confirmed(ct))
1414                 extra_jiffies += nfct_time_stamp;
1415
1416         ct->timeout = extra_jiffies;
1417 acct:
1418         if (do_acct)
1419                 nf_ct_acct_update(ct, ctinfo, skb->len);
1420 }
1421 EXPORT_SYMBOL_GPL(__nf_ct_refresh_acct);
1422
1423 bool nf_ct_kill_acct(struct nf_conn *ct,
1424                      enum ip_conntrack_info ctinfo,
1425                      const struct sk_buff *skb)
1426 {
1427         nf_ct_acct_update(ct, ctinfo, skb->len);
1428
1429         return nf_ct_delete(ct, 0, 0);
1430 }
1431 EXPORT_SYMBOL_GPL(nf_ct_kill_acct);
1432
1433 #if IS_ENABLED(CONFIG_NF_CT_NETLINK)
1434
1435 #include <linux/netfilter/nfnetlink.h>
1436 #include <linux/netfilter/nfnetlink_conntrack.h>
1437 #include <linux/mutex.h>
1438
1439 /* Generic function for tcp/udp/sctp/dccp and alike. This needs to be
1440  * in ip_conntrack_core, since we don't want the protocols to autoload
1441  * or depend on ctnetlink */
1442 int nf_ct_port_tuple_to_nlattr(struct sk_buff *skb,
1443                                const struct nf_conntrack_tuple *tuple)
1444 {
1445         if (nla_put_be16(skb, CTA_PROTO_SRC_PORT, tuple->src.u.tcp.port) ||
1446             nla_put_be16(skb, CTA_PROTO_DST_PORT, tuple->dst.u.tcp.port))
1447                 goto nla_put_failure;
1448         return 0;
1449
1450 nla_put_failure:
1451         return -1;
1452 }
1453 EXPORT_SYMBOL_GPL(nf_ct_port_tuple_to_nlattr);
1454
1455 const struct nla_policy nf_ct_port_nla_policy[CTA_PROTO_MAX+1] = {
1456         [CTA_PROTO_SRC_PORT]  = { .type = NLA_U16 },
1457         [CTA_PROTO_DST_PORT]  = { .type = NLA_U16 },
1458 };
1459 EXPORT_SYMBOL_GPL(nf_ct_port_nla_policy);
1460
1461 int nf_ct_port_nlattr_to_tuple(struct nlattr *tb[],
1462                                struct nf_conntrack_tuple *t)
1463 {
1464         if (!tb[CTA_PROTO_SRC_PORT] || !tb[CTA_PROTO_DST_PORT])
1465                 return -EINVAL;
1466
1467         t->src.u.tcp.port = nla_get_be16(tb[CTA_PROTO_SRC_PORT]);
1468         t->dst.u.tcp.port = nla_get_be16(tb[CTA_PROTO_DST_PORT]);
1469
1470         return 0;
1471 }
1472 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_to_tuple);
1473
1474 int nf_ct_port_nlattr_tuple_size(void)
1475 {
1476         return nla_policy_len(nf_ct_port_nla_policy, CTA_PROTO_MAX + 1);
1477 }
1478 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_tuple_size);
1479 #endif
1480
1481 /* Used by ipt_REJECT and ip6t_REJECT. */
1482 static void nf_conntrack_attach(struct sk_buff *nskb, const struct sk_buff *skb)
1483 {
1484         struct nf_conn *ct;
1485         enum ip_conntrack_info ctinfo;
1486
1487         /* This ICMP is in reverse direction to the packet which caused it */
1488         ct = nf_ct_get(skb, &ctinfo);
1489         if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL)
1490                 ctinfo = IP_CT_RELATED_REPLY;
1491         else
1492                 ctinfo = IP_CT_RELATED;
1493
1494         /* Attach to new skbuff, and increment count */
1495         nskb->nfct = &ct->ct_general;
1496         nskb->nfctinfo = ctinfo;
1497         nf_conntrack_get(nskb->nfct);
1498 }
1499
1500 /* Bring out ya dead! */
1501 static struct nf_conn *
1502 get_next_corpse(struct net *net, int (*iter)(struct nf_conn *i, void *data),
1503                 void *data, unsigned int *bucket)
1504 {
1505         struct nf_conntrack_tuple_hash *h;
1506         struct nf_conn *ct;
1507         struct hlist_nulls_node *n;
1508         int cpu;
1509         spinlock_t *lockp;
1510
1511         for (; *bucket < nf_conntrack_htable_size; (*bucket)++) {
1512                 lockp = &nf_conntrack_locks[*bucket % CONNTRACK_LOCKS];
1513                 local_bh_disable();
1514                 nf_conntrack_lock(lockp);
1515                 if (*bucket < nf_conntrack_htable_size) {
1516                         hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[*bucket], hnnode) {
1517                                 if (NF_CT_DIRECTION(h) != IP_CT_DIR_ORIGINAL)
1518                                         continue;
1519                                 ct = nf_ct_tuplehash_to_ctrack(h);
1520                                 if (net_eq(nf_ct_net(ct), net) &&
1521                                     iter(ct, data))
1522                                         goto found;
1523                         }
1524                 }
1525                 spin_unlock(lockp);
1526                 local_bh_enable();
1527                 cond_resched();
1528         }
1529
1530         for_each_possible_cpu(cpu) {
1531                 struct ct_pcpu *pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
1532
1533                 spin_lock_bh(&pcpu->lock);
1534                 hlist_nulls_for_each_entry(h, n, &pcpu->unconfirmed, hnnode) {
1535                         ct = nf_ct_tuplehash_to_ctrack(h);
1536                         if (iter(ct, data))
1537                                 set_bit(IPS_DYING_BIT, &ct->status);
1538                 }
1539                 spin_unlock_bh(&pcpu->lock);
1540                 cond_resched();
1541         }
1542         return NULL;
1543 found:
1544         atomic_inc(&ct->ct_general.use);
1545         spin_unlock(lockp);
1546         local_bh_enable();
1547         return ct;
1548 }
1549
1550 void nf_ct_iterate_cleanup(struct net *net,
1551                            int (*iter)(struct nf_conn *i, void *data),
1552                            void *data, u32 portid, int report)
1553 {
1554         struct nf_conn *ct;
1555         unsigned int bucket = 0;
1556
1557         might_sleep();
1558
1559         if (atomic_read(&net->ct.count) == 0)
1560                 return;
1561
1562         while ((ct = get_next_corpse(net, iter, data, &bucket)) != NULL) {
1563                 /* Time to push up daises... */
1564
1565                 nf_ct_delete(ct, portid, report);
1566                 nf_ct_put(ct);
1567                 cond_resched();
1568         }
1569 }
1570 EXPORT_SYMBOL_GPL(nf_ct_iterate_cleanup);
1571
1572 static int kill_all(struct nf_conn *i, void *data)
1573 {
1574         return 1;
1575 }
1576
1577 void nf_ct_free_hashtable(void *hash, unsigned int size)
1578 {
1579         if (is_vmalloc_addr(hash))
1580                 vfree(hash);
1581         else
1582                 free_pages((unsigned long)hash,
1583                            get_order(sizeof(struct hlist_head) * size));
1584 }
1585 EXPORT_SYMBOL_GPL(nf_ct_free_hashtable);
1586
1587 static int untrack_refs(void)
1588 {
1589         int cnt = 0, cpu;
1590
1591         for_each_possible_cpu(cpu) {
1592                 struct nf_conn *ct = &per_cpu(nf_conntrack_untracked, cpu);
1593
1594                 cnt += atomic_read(&ct->ct_general.use) - 1;
1595         }
1596         return cnt;
1597 }
1598
1599 void nf_conntrack_cleanup_start(void)
1600 {
1601         conntrack_gc_work.exiting = true;
1602         RCU_INIT_POINTER(ip_ct_attach, NULL);
1603 }
1604
1605 void nf_conntrack_cleanup_end(void)
1606 {
1607         RCU_INIT_POINTER(nf_ct_destroy, NULL);
1608         while (untrack_refs() > 0)
1609                 schedule();
1610
1611         cancel_delayed_work_sync(&conntrack_gc_work.dwork);
1612         nf_ct_free_hashtable(nf_conntrack_hash, nf_conntrack_htable_size);
1613
1614         nf_conntrack_proto_fini();
1615         nf_conntrack_seqadj_fini();
1616         nf_conntrack_labels_fini();
1617         nf_conntrack_helper_fini();
1618         nf_conntrack_timeout_fini();
1619         nf_conntrack_ecache_fini();
1620         nf_conntrack_tstamp_fini();
1621         nf_conntrack_acct_fini();
1622         nf_conntrack_expect_fini();
1623
1624         kmem_cache_destroy(nf_conntrack_cachep);
1625 }
1626
1627 /*
1628  * Mishearing the voices in his head, our hero wonders how he's
1629  * supposed to kill the mall.
1630  */
1631 void nf_conntrack_cleanup_net(struct net *net)
1632 {
1633         LIST_HEAD(single);
1634
1635         list_add(&net->exit_list, &single);
1636         nf_conntrack_cleanup_net_list(&single);
1637 }
1638
1639 void nf_conntrack_cleanup_net_list(struct list_head *net_exit_list)
1640 {
1641         int busy;
1642         struct net *net;
1643
1644         /*
1645          * This makes sure all current packets have passed through
1646          *  netfilter framework.  Roll on, two-stage module
1647          *  delete...
1648          */
1649         synchronize_net();
1650 i_see_dead_people:
1651         busy = 0;
1652         list_for_each_entry(net, net_exit_list, exit_list) {
1653                 nf_ct_iterate_cleanup(net, kill_all, NULL, 0, 0);
1654                 if (atomic_read(&net->ct.count) != 0)
1655                         busy = 1;
1656         }
1657         if (busy) {
1658                 schedule();
1659                 goto i_see_dead_people;
1660         }
1661
1662         list_for_each_entry(net, net_exit_list, exit_list) {
1663                 nf_conntrack_proto_pernet_fini(net);
1664                 nf_conntrack_helper_pernet_fini(net);
1665                 nf_conntrack_ecache_pernet_fini(net);
1666                 nf_conntrack_tstamp_pernet_fini(net);
1667                 nf_conntrack_acct_pernet_fini(net);
1668                 nf_conntrack_expect_pernet_fini(net);
1669                 free_percpu(net->ct.stat);
1670                 free_percpu(net->ct.pcpu_lists);
1671         }
1672 }
1673
1674 void *nf_ct_alloc_hashtable(unsigned int *sizep, int nulls)
1675 {
1676         struct hlist_nulls_head *hash;
1677         unsigned int nr_slots, i;
1678         size_t sz;
1679
1680         if (*sizep > (UINT_MAX / sizeof(struct hlist_nulls_head)))
1681                 return NULL;
1682
1683         BUILD_BUG_ON(sizeof(struct hlist_nulls_head) != sizeof(struct hlist_head));
1684         nr_slots = *sizep = roundup(*sizep, PAGE_SIZE / sizeof(struct hlist_nulls_head));
1685
1686         if (nr_slots > (UINT_MAX / sizeof(struct hlist_nulls_head)))
1687                 return NULL;
1688
1689         sz = nr_slots * sizeof(struct hlist_nulls_head);
1690         hash = (void *)__get_free_pages(GFP_KERNEL | __GFP_NOWARN | __GFP_ZERO,
1691                                         get_order(sz));
1692         if (!hash)
1693                 hash = vzalloc(sz);
1694
1695         if (hash && nulls)
1696                 for (i = 0; i < nr_slots; i++)
1697                         INIT_HLIST_NULLS_HEAD(&hash[i], i);
1698
1699         return hash;
1700 }
1701 EXPORT_SYMBOL_GPL(nf_ct_alloc_hashtable);
1702
1703 int nf_conntrack_hash_resize(unsigned int hashsize)
1704 {
1705         int i, bucket;
1706         unsigned int old_size;
1707         struct hlist_nulls_head *hash, *old_hash;
1708         struct nf_conntrack_tuple_hash *h;
1709         struct nf_conn *ct;
1710
1711         if (!hashsize)
1712                 return -EINVAL;
1713
1714         hash = nf_ct_alloc_hashtable(&hashsize, 1);
1715         if (!hash)
1716                 return -ENOMEM;
1717
1718         old_size = nf_conntrack_htable_size;
1719         if (old_size == hashsize) {
1720                 nf_ct_free_hashtable(hash, hashsize);
1721                 return 0;
1722         }
1723
1724         local_bh_disable();
1725         nf_conntrack_all_lock();
1726         write_seqcount_begin(&nf_conntrack_generation);
1727
1728         /* Lookups in the old hash might happen in parallel, which means we
1729          * might get false negatives during connection lookup. New connections
1730          * created because of a false negative won't make it into the hash
1731          * though since that required taking the locks.
1732          */
1733
1734         for (i = 0; i < nf_conntrack_htable_size; i++) {
1735                 while (!hlist_nulls_empty(&nf_conntrack_hash[i])) {
1736                         h = hlist_nulls_entry(nf_conntrack_hash[i].first,
1737                                               struct nf_conntrack_tuple_hash, hnnode);
1738                         ct = nf_ct_tuplehash_to_ctrack(h);
1739                         hlist_nulls_del_rcu(&h->hnnode);
1740                         bucket = __hash_conntrack(nf_ct_net(ct),
1741                                                   &h->tuple, hashsize);
1742                         hlist_nulls_add_head_rcu(&h->hnnode, &hash[bucket]);
1743                 }
1744         }
1745         old_size = nf_conntrack_htable_size;
1746         old_hash = nf_conntrack_hash;
1747
1748         nf_conntrack_hash = hash;
1749         nf_conntrack_htable_size = hashsize;
1750
1751         write_seqcount_end(&nf_conntrack_generation);
1752         nf_conntrack_all_unlock();
1753         local_bh_enable();
1754
1755         synchronize_net();
1756         nf_ct_free_hashtable(old_hash, old_size);
1757         return 0;
1758 }
1759
1760 int nf_conntrack_set_hashsize(const char *val, struct kernel_param *kp)
1761 {
1762         unsigned int hashsize;
1763         int rc;
1764
1765         if (current->nsproxy->net_ns != &init_net)
1766                 return -EOPNOTSUPP;
1767
1768         /* On boot, we can set this without any fancy locking. */
1769         if (!nf_conntrack_htable_size)
1770                 return param_set_uint(val, kp);
1771
1772         rc = kstrtouint(val, 0, &hashsize);
1773         if (rc)
1774                 return rc;
1775
1776         return nf_conntrack_hash_resize(hashsize);
1777 }
1778 EXPORT_SYMBOL_GPL(nf_conntrack_set_hashsize);
1779
1780 module_param_call(hashsize, nf_conntrack_set_hashsize, param_get_uint,
1781                   &nf_conntrack_htable_size, 0600);
1782
1783 void nf_ct_untracked_status_or(unsigned long bits)
1784 {
1785         int cpu;
1786
1787         for_each_possible_cpu(cpu)
1788                 per_cpu(nf_conntrack_untracked, cpu).status |= bits;
1789 }
1790 EXPORT_SYMBOL_GPL(nf_ct_untracked_status_or);
1791
1792 int nf_conntrack_init_start(void)
1793 {
1794         int max_factor = 8;
1795         int ret = -ENOMEM;
1796         int i, cpu;
1797
1798         seqcount_init(&nf_conntrack_generation);
1799
1800         for (i = 0; i < CONNTRACK_LOCKS; i++)
1801                 spin_lock_init(&nf_conntrack_locks[i]);
1802
1803         if (!nf_conntrack_htable_size) {
1804                 /* Idea from tcp.c: use 1/16384 of memory.
1805                  * On i386: 32MB machine has 512 buckets.
1806                  * >= 1GB machines have 16384 buckets.
1807                  * >= 4GB machines have 65536 buckets.
1808                  */
1809                 nf_conntrack_htable_size
1810                         = (((totalram_pages << PAGE_SHIFT) / 16384)
1811                            / sizeof(struct hlist_head));
1812                 if (totalram_pages > (4 * (1024 * 1024 * 1024 / PAGE_SIZE)))
1813                         nf_conntrack_htable_size = 65536;
1814                 else if (totalram_pages > (1024 * 1024 * 1024 / PAGE_SIZE))
1815                         nf_conntrack_htable_size = 16384;
1816                 if (nf_conntrack_htable_size < 32)
1817                         nf_conntrack_htable_size = 32;
1818
1819                 /* Use a max. factor of four by default to get the same max as
1820                  * with the old struct list_heads. When a table size is given
1821                  * we use the old value of 8 to avoid reducing the max.
1822                  * entries. */
1823                 max_factor = 4;
1824         }
1825
1826         nf_conntrack_hash = nf_ct_alloc_hashtable(&nf_conntrack_htable_size, 1);
1827         if (!nf_conntrack_hash)
1828                 return -ENOMEM;
1829
1830         nf_conntrack_max = max_factor * nf_conntrack_htable_size;
1831
1832         nf_conntrack_cachep = kmem_cache_create("nf_conntrack",
1833                                                 sizeof(struct nf_conn), 0,
1834                                                 SLAB_DESTROY_BY_RCU | SLAB_HWCACHE_ALIGN, NULL);
1835         if (!nf_conntrack_cachep)
1836                 goto err_cachep;
1837
1838         printk(KERN_INFO "nf_conntrack version %s (%u buckets, %d max)\n",
1839                NF_CONNTRACK_VERSION, nf_conntrack_htable_size,
1840                nf_conntrack_max);
1841
1842         ret = nf_conntrack_expect_init();
1843         if (ret < 0)
1844                 goto err_expect;
1845
1846         ret = nf_conntrack_acct_init();
1847         if (ret < 0)
1848                 goto err_acct;
1849
1850         ret = nf_conntrack_tstamp_init();
1851         if (ret < 0)
1852                 goto err_tstamp;
1853
1854         ret = nf_conntrack_ecache_init();
1855         if (ret < 0)
1856                 goto err_ecache;
1857
1858         ret = nf_conntrack_timeout_init();
1859         if (ret < 0)
1860                 goto err_timeout;
1861
1862         ret = nf_conntrack_helper_init();
1863         if (ret < 0)
1864                 goto err_helper;
1865
1866         ret = nf_conntrack_labels_init();
1867         if (ret < 0)
1868                 goto err_labels;
1869
1870         ret = nf_conntrack_seqadj_init();
1871         if (ret < 0)
1872                 goto err_seqadj;
1873
1874         ret = nf_conntrack_proto_init();
1875         if (ret < 0)
1876                 goto err_proto;
1877
1878         /* Set up fake conntrack: to never be deleted, not in any hashes */
1879         for_each_possible_cpu(cpu) {
1880                 struct nf_conn *ct = &per_cpu(nf_conntrack_untracked, cpu);
1881                 write_pnet(&ct->ct_net, &init_net);
1882                 atomic_set(&ct->ct_general.use, 1);
1883         }
1884         /*  - and look it like as a confirmed connection */
1885         nf_ct_untracked_status_or(IPS_CONFIRMED | IPS_UNTRACKED);
1886
1887         conntrack_gc_work_init(&conntrack_gc_work);
1888         schedule_delayed_work(&conntrack_gc_work.dwork, GC_INTERVAL);
1889
1890         return 0;
1891
1892 err_proto:
1893         nf_conntrack_seqadj_fini();
1894 err_seqadj:
1895         nf_conntrack_labels_fini();
1896 err_labels:
1897         nf_conntrack_helper_fini();
1898 err_helper:
1899         nf_conntrack_timeout_fini();
1900 err_timeout:
1901         nf_conntrack_ecache_fini();
1902 err_ecache:
1903         nf_conntrack_tstamp_fini();
1904 err_tstamp:
1905         nf_conntrack_acct_fini();
1906 err_acct:
1907         nf_conntrack_expect_fini();
1908 err_expect:
1909         kmem_cache_destroy(nf_conntrack_cachep);
1910 err_cachep:
1911         nf_ct_free_hashtable(nf_conntrack_hash, nf_conntrack_htable_size);
1912         return ret;
1913 }
1914
1915 void nf_conntrack_init_end(void)
1916 {
1917         /* For use by REJECT target */
1918         RCU_INIT_POINTER(ip_ct_attach, nf_conntrack_attach);
1919         RCU_INIT_POINTER(nf_ct_destroy, destroy_conntrack);
1920 }
1921
1922 /*
1923  * We need to use special "null" values, not used in hash table
1924  */
1925 #define UNCONFIRMED_NULLS_VAL   ((1<<30)+0)
1926 #define DYING_NULLS_VAL         ((1<<30)+1)
1927 #define TEMPLATE_NULLS_VAL      ((1<<30)+2)
1928
1929 int nf_conntrack_init_net(struct net *net)
1930 {
1931         int ret = -ENOMEM;
1932         int cpu;
1933
1934         atomic_set(&net->ct.count, 0);
1935
1936         net->ct.pcpu_lists = alloc_percpu(struct ct_pcpu);
1937         if (!net->ct.pcpu_lists)
1938                 goto err_stat;
1939
1940         for_each_possible_cpu(cpu) {
1941                 struct ct_pcpu *pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
1942
1943                 spin_lock_init(&pcpu->lock);
1944                 INIT_HLIST_NULLS_HEAD(&pcpu->unconfirmed, UNCONFIRMED_NULLS_VAL);
1945                 INIT_HLIST_NULLS_HEAD(&pcpu->dying, DYING_NULLS_VAL);
1946         }
1947
1948         net->ct.stat = alloc_percpu(struct ip_conntrack_stat);
1949         if (!net->ct.stat)
1950                 goto err_pcpu_lists;
1951
1952         ret = nf_conntrack_expect_pernet_init(net);
1953         if (ret < 0)
1954                 goto err_expect;
1955         ret = nf_conntrack_acct_pernet_init(net);
1956         if (ret < 0)
1957                 goto err_acct;
1958         ret = nf_conntrack_tstamp_pernet_init(net);
1959         if (ret < 0)
1960                 goto err_tstamp;
1961         ret = nf_conntrack_ecache_pernet_init(net);
1962         if (ret < 0)
1963                 goto err_ecache;
1964         ret = nf_conntrack_helper_pernet_init(net);
1965         if (ret < 0)
1966                 goto err_helper;
1967         ret = nf_conntrack_proto_pernet_init(net);
1968         if (ret < 0)
1969                 goto err_proto;
1970         return 0;
1971
1972 err_proto:
1973         nf_conntrack_helper_pernet_fini(net);
1974 err_helper:
1975         nf_conntrack_ecache_pernet_fini(net);
1976 err_ecache:
1977         nf_conntrack_tstamp_pernet_fini(net);
1978 err_tstamp:
1979         nf_conntrack_acct_pernet_fini(net);
1980 err_acct:
1981         nf_conntrack_expect_pernet_fini(net);
1982 err_expect:
1983         free_percpu(net->ct.stat);
1984 err_pcpu_lists:
1985         free_percpu(net->ct.pcpu_lists);
1986 err_stat:
1987         return ret;
1988 }