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