]> err.no Git - linux-2.6/blob - net/netfilter/nf_conntrack_core.c
[NETFILTER]: TCP conntrack: factorize out the PUSH flag
[linux-2.6] / 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  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License version 2 as
11  * published by the Free Software Foundation.
12  *
13  * 23 Apr 2001: Harald Welte <laforge@gnumonks.org>
14  *      - new API and handling of conntrack/nat helpers
15  *      - now capable of multiple expectations for one master
16  * 16 Jul 2002: Harald Welte <laforge@gnumonks.org>
17  *      - add usage/reference counts to ip_conntrack_expect
18  *      - export ip_conntrack[_expect]_{find_get,put} functions
19  * 16 Dec 2003: Yasuyuki Kozakai @USAGI <yasuyuki.kozakai@toshiba.co.jp>
20  *      - generalize L3 protocol denendent part.
21  * 23 Mar 2004: Yasuyuki Kozakai @USAGI <yasuyuki.kozakai@toshiba.co.jp>
22  *      - add support various size of conntrack structures.
23  * 26 Jan 2006: Harald Welte <laforge@netfilter.org>
24  *      - restructure nf_conn (introduce nf_conn_help)
25  *      - redesign 'features' how they were originally intended
26  * 26 Feb 2006: Pablo Neira Ayuso <pablo@eurodev.net>
27  *      - add support for L3 protocol module load on demand.
28  *
29  * Derived from net/ipv4/netfilter/ip_conntrack_core.c
30  */
31
32 #include <linux/types.h>
33 #include <linux/netfilter.h>
34 #include <linux/module.h>
35 #include <linux/skbuff.h>
36 #include <linux/proc_fs.h>
37 #include <linux/vmalloc.h>
38 #include <linux/stddef.h>
39 #include <linux/slab.h>
40 #include <linux/random.h>
41 #include <linux/jhash.h>
42 #include <linux/err.h>
43 #include <linux/percpu.h>
44 #include <linux/moduleparam.h>
45 #include <linux/notifier.h>
46 #include <linux/kernel.h>
47 #include <linux/netdevice.h>
48 #include <linux/socket.h>
49 #include <linux/mm.h>
50
51 #include <net/netfilter/nf_conntrack.h>
52 #include <net/netfilter/nf_conntrack_l3proto.h>
53 #include <net/netfilter/nf_conntrack_l4proto.h>
54 #include <net/netfilter/nf_conntrack_expect.h>
55 #include <net/netfilter/nf_conntrack_helper.h>
56 #include <net/netfilter/nf_conntrack_core.h>
57
58 #define NF_CONNTRACK_VERSION    "0.5.0"
59
60 #if 0
61 #define DEBUGP printk
62 #else
63 #define DEBUGP(format, args...)
64 #endif
65
66 DEFINE_RWLOCK(nf_conntrack_lock);
67 EXPORT_SYMBOL_GPL(nf_conntrack_lock);
68
69 /* nf_conntrack_standalone needs this */
70 atomic_t nf_conntrack_count = ATOMIC_INIT(0);
71 EXPORT_SYMBOL_GPL(nf_conntrack_count);
72
73 void (*nf_conntrack_destroyed)(struct nf_conn *conntrack);
74 EXPORT_SYMBOL_GPL(nf_conntrack_destroyed);
75
76 unsigned int nf_conntrack_htable_size __read_mostly;
77 EXPORT_SYMBOL_GPL(nf_conntrack_htable_size);
78
79 int nf_conntrack_max __read_mostly;
80 EXPORT_SYMBOL_GPL(nf_conntrack_max);
81
82 struct list_head *nf_conntrack_hash __read_mostly;
83 EXPORT_SYMBOL_GPL(nf_conntrack_hash);
84
85 struct nf_conn nf_conntrack_untracked __read_mostly;
86 EXPORT_SYMBOL_GPL(nf_conntrack_untracked);
87
88 unsigned int nf_ct_log_invalid __read_mostly;
89 LIST_HEAD(unconfirmed);
90 static int nf_conntrack_vmalloc __read_mostly;
91
92 static unsigned int nf_conntrack_next_id;
93
94 DEFINE_PER_CPU(struct ip_conntrack_stat, nf_conntrack_stat);
95 EXPORT_PER_CPU_SYMBOL(nf_conntrack_stat);
96
97 /*
98  * This scheme offers various size of "struct nf_conn" dependent on
99  * features(helper, nat, ...)
100  */
101
102 #define NF_CT_FEATURES_NAMELEN  256
103 static struct {
104         /* name of slab cache. printed in /proc/slabinfo */
105         char *name;
106
107         /* size of slab cache */
108         size_t size;
109
110         /* slab cache pointer */
111         struct kmem_cache *cachep;
112
113         /* allocated slab cache + modules which uses this slab cache */
114         int use;
115
116 } nf_ct_cache[NF_CT_F_NUM];
117
118 /* protect members of nf_ct_cache except of "use" */
119 DEFINE_RWLOCK(nf_ct_cache_lock);
120
121 /* This avoids calling kmem_cache_create() with same name simultaneously */
122 static DEFINE_MUTEX(nf_ct_cache_mutex);
123
124 static int nf_conntrack_hash_rnd_initted;
125 static unsigned int nf_conntrack_hash_rnd;
126
127 static u_int32_t __hash_conntrack(const struct nf_conntrack_tuple *tuple,
128                                   unsigned int size, unsigned int rnd)
129 {
130         unsigned int a, b;
131
132         a = jhash2(tuple->src.u3.all, ARRAY_SIZE(tuple->src.u3.all),
133                    (tuple->src.l3num << 16) | tuple->dst.protonum);
134         b = jhash2(tuple->dst.u3.all, ARRAY_SIZE(tuple->dst.u3.all),
135                    (tuple->src.u.all << 16) | tuple->dst.u.all);
136
137         return jhash_2words(a, b, rnd) % size;
138 }
139
140 static inline u_int32_t hash_conntrack(const struct nf_conntrack_tuple *tuple)
141 {
142         return __hash_conntrack(tuple, nf_conntrack_htable_size,
143                                 nf_conntrack_hash_rnd);
144 }
145
146 int nf_conntrack_register_cache(u_int32_t features, const char *name,
147                                 size_t size)
148 {
149         int ret = 0;
150         char *cache_name;
151         struct kmem_cache *cachep;
152
153         DEBUGP("nf_conntrack_register_cache: features=0x%x, name=%s, size=%d\n",
154                features, name, size);
155
156         if (features < NF_CT_F_BASIC || features >= NF_CT_F_NUM) {
157                 DEBUGP("nf_conntrack_register_cache: invalid features.: 0x%x\n",
158                         features);
159                 return -EINVAL;
160         }
161
162         mutex_lock(&nf_ct_cache_mutex);
163
164         write_lock_bh(&nf_ct_cache_lock);
165         /* e.g: multiple helpers are loaded */
166         if (nf_ct_cache[features].use > 0) {
167                 DEBUGP("nf_conntrack_register_cache: already resisterd.\n");
168                 if ((!strncmp(nf_ct_cache[features].name, name,
169                               NF_CT_FEATURES_NAMELEN))
170                     && nf_ct_cache[features].size == size) {
171                         DEBUGP("nf_conntrack_register_cache: reusing.\n");
172                         nf_ct_cache[features].use++;
173                         ret = 0;
174                 } else
175                         ret = -EBUSY;
176
177                 write_unlock_bh(&nf_ct_cache_lock);
178                 mutex_unlock(&nf_ct_cache_mutex);
179                 return ret;
180         }
181         write_unlock_bh(&nf_ct_cache_lock);
182
183         /*
184          * The memory space for name of slab cache must be alive until
185          * cache is destroyed.
186          */
187         cache_name = kmalloc(sizeof(char)*NF_CT_FEATURES_NAMELEN, GFP_ATOMIC);
188         if (cache_name == NULL) {
189                 DEBUGP("nf_conntrack_register_cache: can't alloc cache_name\n");
190                 ret = -ENOMEM;
191                 goto out_up_mutex;
192         }
193
194         if (strlcpy(cache_name, name, NF_CT_FEATURES_NAMELEN)
195                                                 >= NF_CT_FEATURES_NAMELEN) {
196                 printk("nf_conntrack_register_cache: name too long\n");
197                 ret = -EINVAL;
198                 goto out_free_name;
199         }
200
201         cachep = kmem_cache_create(cache_name, size, 0, 0,
202                                    NULL, NULL);
203         if (!cachep) {
204                 printk("nf_conntrack_register_cache: Can't create slab cache "
205                        "for the features = 0x%x\n", features);
206                 ret = -ENOMEM;
207                 goto out_free_name;
208         }
209
210         write_lock_bh(&nf_ct_cache_lock);
211         nf_ct_cache[features].use = 1;
212         nf_ct_cache[features].size = size;
213         nf_ct_cache[features].cachep = cachep;
214         nf_ct_cache[features].name = cache_name;
215         write_unlock_bh(&nf_ct_cache_lock);
216
217         goto out_up_mutex;
218
219 out_free_name:
220         kfree(cache_name);
221 out_up_mutex:
222         mutex_unlock(&nf_ct_cache_mutex);
223         return ret;
224 }
225 EXPORT_SYMBOL_GPL(nf_conntrack_register_cache);
226
227 /* FIXME: In the current, only nf_conntrack_cleanup() can call this function. */
228 void nf_conntrack_unregister_cache(u_int32_t features)
229 {
230         struct kmem_cache *cachep;
231         char *name;
232
233         /*
234          * This assures that kmem_cache_create() isn't called before destroying
235          * slab cache.
236          */
237         DEBUGP("nf_conntrack_unregister_cache: 0x%04x\n", features);
238         mutex_lock(&nf_ct_cache_mutex);
239
240         write_lock_bh(&nf_ct_cache_lock);
241         if (--nf_ct_cache[features].use > 0) {
242                 write_unlock_bh(&nf_ct_cache_lock);
243                 mutex_unlock(&nf_ct_cache_mutex);
244                 return;
245         }
246         cachep = nf_ct_cache[features].cachep;
247         name = nf_ct_cache[features].name;
248         nf_ct_cache[features].cachep = NULL;
249         nf_ct_cache[features].name = NULL;
250         nf_ct_cache[features].size = 0;
251         write_unlock_bh(&nf_ct_cache_lock);
252
253         synchronize_net();
254
255         kmem_cache_destroy(cachep);
256         kfree(name);
257
258         mutex_unlock(&nf_ct_cache_mutex);
259 }
260 EXPORT_SYMBOL_GPL(nf_conntrack_unregister_cache);
261
262 int
263 nf_ct_get_tuple(const struct sk_buff *skb,
264                 unsigned int nhoff,
265                 unsigned int dataoff,
266                 u_int16_t l3num,
267                 u_int8_t protonum,
268                 struct nf_conntrack_tuple *tuple,
269                 const struct nf_conntrack_l3proto *l3proto,
270                 const struct nf_conntrack_l4proto *l4proto)
271 {
272         NF_CT_TUPLE_U_BLANK(tuple);
273
274         tuple->src.l3num = l3num;
275         if (l3proto->pkt_to_tuple(skb, nhoff, tuple) == 0)
276                 return 0;
277
278         tuple->dst.protonum = protonum;
279         tuple->dst.dir = IP_CT_DIR_ORIGINAL;
280
281         return l4proto->pkt_to_tuple(skb, dataoff, tuple);
282 }
283 EXPORT_SYMBOL_GPL(nf_ct_get_tuple);
284
285 int
286 nf_ct_invert_tuple(struct nf_conntrack_tuple *inverse,
287                    const struct nf_conntrack_tuple *orig,
288                    const struct nf_conntrack_l3proto *l3proto,
289                    const struct nf_conntrack_l4proto *l4proto)
290 {
291         NF_CT_TUPLE_U_BLANK(inverse);
292
293         inverse->src.l3num = orig->src.l3num;
294         if (l3proto->invert_tuple(inverse, orig) == 0)
295                 return 0;
296
297         inverse->dst.dir = !orig->dst.dir;
298
299         inverse->dst.protonum = orig->dst.protonum;
300         return l4proto->invert_tuple(inverse, orig);
301 }
302 EXPORT_SYMBOL_GPL(nf_ct_invert_tuple);
303
304 static void
305 clean_from_lists(struct nf_conn *ct)
306 {
307         DEBUGP("clean_from_lists(%p)\n", ct);
308         list_del(&ct->tuplehash[IP_CT_DIR_ORIGINAL].list);
309         list_del(&ct->tuplehash[IP_CT_DIR_REPLY].list);
310
311         /* Destroy all pending expectations */
312         nf_ct_remove_expectations(ct);
313 }
314
315 static void
316 destroy_conntrack(struct nf_conntrack *nfct)
317 {
318         struct nf_conn *ct = (struct nf_conn *)nfct;
319         struct nf_conn_help *help = nfct_help(ct);
320         struct nf_conntrack_l3proto *l3proto;
321         struct nf_conntrack_l4proto *l4proto;
322         typeof(nf_conntrack_destroyed) destroyed;
323
324         DEBUGP("destroy_conntrack(%p)\n", ct);
325         NF_CT_ASSERT(atomic_read(&nfct->use) == 0);
326         NF_CT_ASSERT(!timer_pending(&ct->timeout));
327
328         nf_conntrack_event(IPCT_DESTROY, ct);
329         set_bit(IPS_DYING_BIT, &ct->status);
330
331         if (help && help->helper && help->helper->destroy)
332                 help->helper->destroy(ct);
333
334         /* To make sure we don't get any weird locking issues here:
335          * destroy_conntrack() MUST NOT be called with a write lock
336          * to nf_conntrack_lock!!! -HW */
337         rcu_read_lock();
338         l3proto = __nf_ct_l3proto_find(ct->tuplehash[IP_CT_DIR_REPLY].tuple.src.l3num);
339         if (l3proto && l3proto->destroy)
340                 l3proto->destroy(ct);
341
342         l4proto = __nf_ct_l4proto_find(ct->tuplehash[IP_CT_DIR_REPLY].tuple.src.l3num,
343                                        ct->tuplehash[IP_CT_DIR_REPLY].tuple.dst.protonum);
344         if (l4proto && l4proto->destroy)
345                 l4proto->destroy(ct);
346
347         destroyed = rcu_dereference(nf_conntrack_destroyed);
348         if (destroyed)
349                 destroyed(ct);
350
351         rcu_read_unlock();
352
353         write_lock_bh(&nf_conntrack_lock);
354         /* Expectations will have been removed in clean_from_lists,
355          * except TFTP can create an expectation on the first packet,
356          * before connection is in the list, so we need to clean here,
357          * too. */
358         nf_ct_remove_expectations(ct);
359
360         /* We overload first tuple to link into unconfirmed list. */
361         if (!nf_ct_is_confirmed(ct)) {
362                 BUG_ON(list_empty(&ct->tuplehash[IP_CT_DIR_ORIGINAL].list));
363                 list_del(&ct->tuplehash[IP_CT_DIR_ORIGINAL].list);
364         }
365
366         NF_CT_STAT_INC(delete);
367         write_unlock_bh(&nf_conntrack_lock);
368
369         if (ct->master)
370                 nf_ct_put(ct->master);
371
372         DEBUGP("destroy_conntrack: returning ct=%p to slab\n", ct);
373         nf_conntrack_free(ct);
374 }
375
376 static void death_by_timeout(unsigned long ul_conntrack)
377 {
378         struct nf_conn *ct = (void *)ul_conntrack;
379
380         write_lock_bh(&nf_conntrack_lock);
381         /* Inside lock so preempt is disabled on module removal path.
382          * Otherwise we can get spurious warnings. */
383         NF_CT_STAT_INC(delete_list);
384         clean_from_lists(ct);
385         write_unlock_bh(&nf_conntrack_lock);
386         nf_ct_put(ct);
387 }
388
389 struct nf_conntrack_tuple_hash *
390 __nf_conntrack_find(const struct nf_conntrack_tuple *tuple,
391                     const struct nf_conn *ignored_conntrack)
392 {
393         struct nf_conntrack_tuple_hash *h;
394         unsigned int hash = hash_conntrack(tuple);
395
396         list_for_each_entry(h, &nf_conntrack_hash[hash], list) {
397                 if (nf_ct_tuplehash_to_ctrack(h) != ignored_conntrack &&
398                     nf_ct_tuple_equal(tuple, &h->tuple)) {
399                         NF_CT_STAT_INC(found);
400                         return h;
401                 }
402                 NF_CT_STAT_INC(searched);
403         }
404
405         return NULL;
406 }
407 EXPORT_SYMBOL_GPL(__nf_conntrack_find);
408
409 /* Find a connection corresponding to a tuple. */
410 struct nf_conntrack_tuple_hash *
411 nf_conntrack_find_get(const struct nf_conntrack_tuple *tuple,
412                       const struct nf_conn *ignored_conntrack)
413 {
414         struct nf_conntrack_tuple_hash *h;
415
416         read_lock_bh(&nf_conntrack_lock);
417         h = __nf_conntrack_find(tuple, ignored_conntrack);
418         if (h)
419                 atomic_inc(&nf_ct_tuplehash_to_ctrack(h)->ct_general.use);
420         read_unlock_bh(&nf_conntrack_lock);
421
422         return h;
423 }
424 EXPORT_SYMBOL_GPL(nf_conntrack_find_get);
425
426 static void __nf_conntrack_hash_insert(struct nf_conn *ct,
427                                        unsigned int hash,
428                                        unsigned int repl_hash)
429 {
430         ct->id = ++nf_conntrack_next_id;
431         list_add(&ct->tuplehash[IP_CT_DIR_ORIGINAL].list,
432                  &nf_conntrack_hash[hash]);
433         list_add(&ct->tuplehash[IP_CT_DIR_REPLY].list,
434                  &nf_conntrack_hash[repl_hash]);
435 }
436
437 void nf_conntrack_hash_insert(struct nf_conn *ct)
438 {
439         unsigned int hash, repl_hash;
440
441         hash = hash_conntrack(&ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
442         repl_hash = hash_conntrack(&ct->tuplehash[IP_CT_DIR_REPLY].tuple);
443
444         write_lock_bh(&nf_conntrack_lock);
445         __nf_conntrack_hash_insert(ct, hash, repl_hash);
446         write_unlock_bh(&nf_conntrack_lock);
447 }
448 EXPORT_SYMBOL_GPL(nf_conntrack_hash_insert);
449
450 /* Confirm a connection given skb; places it in hash table */
451 int
452 __nf_conntrack_confirm(struct sk_buff **pskb)
453 {
454         unsigned int hash, repl_hash;
455         struct nf_conntrack_tuple_hash *h;
456         struct nf_conn *ct;
457         struct nf_conn_help *help;
458         enum ip_conntrack_info ctinfo;
459
460         ct = nf_ct_get(*pskb, &ctinfo);
461
462         /* ipt_REJECT uses nf_conntrack_attach to attach related
463            ICMP/TCP RST packets in other direction.  Actual packet
464            which created connection will be IP_CT_NEW or for an
465            expected connection, IP_CT_RELATED. */
466         if (CTINFO2DIR(ctinfo) != IP_CT_DIR_ORIGINAL)
467                 return NF_ACCEPT;
468
469         hash = hash_conntrack(&ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
470         repl_hash = hash_conntrack(&ct->tuplehash[IP_CT_DIR_REPLY].tuple);
471
472         /* We're not in hash table, and we refuse to set up related
473            connections for unconfirmed conns.  But packet copies and
474            REJECT will give spurious warnings here. */
475         /* NF_CT_ASSERT(atomic_read(&ct->ct_general.use) == 1); */
476
477         /* No external references means noone else could have
478            confirmed us. */
479         NF_CT_ASSERT(!nf_ct_is_confirmed(ct));
480         DEBUGP("Confirming conntrack %p\n", ct);
481
482         write_lock_bh(&nf_conntrack_lock);
483
484         /* See if there's one in the list already, including reverse:
485            NAT could have grabbed it without realizing, since we're
486            not in the hash.  If there is, we lost race. */
487         list_for_each_entry(h, &nf_conntrack_hash[hash], list)
488                 if (nf_ct_tuple_equal(&ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
489                                       &h->tuple))
490                         goto out;
491         list_for_each_entry(h, &nf_conntrack_hash[repl_hash], list)
492                 if (nf_ct_tuple_equal(&ct->tuplehash[IP_CT_DIR_REPLY].tuple,
493                                       &h->tuple))
494                         goto out;
495
496         /* Remove from unconfirmed list */
497         list_del(&ct->tuplehash[IP_CT_DIR_ORIGINAL].list);
498
499         __nf_conntrack_hash_insert(ct, hash, repl_hash);
500         /* Timer relative to confirmation time, not original
501            setting time, otherwise we'd get timer wrap in
502            weird delay cases. */
503         ct->timeout.expires += jiffies;
504         add_timer(&ct->timeout);
505         atomic_inc(&ct->ct_general.use);
506         set_bit(IPS_CONFIRMED_BIT, &ct->status);
507         NF_CT_STAT_INC(insert);
508         write_unlock_bh(&nf_conntrack_lock);
509         help = nfct_help(ct);
510         if (help && help->helper)
511                 nf_conntrack_event_cache(IPCT_HELPER, *pskb);
512 #ifdef CONFIG_NF_NAT_NEEDED
513         if (test_bit(IPS_SRC_NAT_DONE_BIT, &ct->status) ||
514             test_bit(IPS_DST_NAT_DONE_BIT, &ct->status))
515                 nf_conntrack_event_cache(IPCT_NATINFO, *pskb);
516 #endif
517         nf_conntrack_event_cache(master_ct(ct) ?
518                                  IPCT_RELATED : IPCT_NEW, *pskb);
519         return NF_ACCEPT;
520
521 out:
522         NF_CT_STAT_INC(insert_failed);
523         write_unlock_bh(&nf_conntrack_lock);
524         return NF_DROP;
525 }
526 EXPORT_SYMBOL_GPL(__nf_conntrack_confirm);
527
528 /* Returns true if a connection correspondings to the tuple (required
529    for NAT). */
530 int
531 nf_conntrack_tuple_taken(const struct nf_conntrack_tuple *tuple,
532                          const struct nf_conn *ignored_conntrack)
533 {
534         struct nf_conntrack_tuple_hash *h;
535
536         read_lock_bh(&nf_conntrack_lock);
537         h = __nf_conntrack_find(tuple, ignored_conntrack);
538         read_unlock_bh(&nf_conntrack_lock);
539
540         return h != NULL;
541 }
542 EXPORT_SYMBOL_GPL(nf_conntrack_tuple_taken);
543
544 /* There's a small race here where we may free a just-assured
545    connection.  Too bad: we're in trouble anyway. */
546 static int early_drop(struct list_head *chain)
547 {
548         /* Traverse backwards: gives us oldest, which is roughly LRU */
549         struct nf_conntrack_tuple_hash *h;
550         struct nf_conn *ct = NULL, *tmp;
551         int dropped = 0;
552
553         read_lock_bh(&nf_conntrack_lock);
554         list_for_each_entry_reverse(h, chain, list) {
555                 tmp = nf_ct_tuplehash_to_ctrack(h);
556                 if (!test_bit(IPS_ASSURED_BIT, &tmp->status)) {
557                         ct = tmp;
558                         atomic_inc(&ct->ct_general.use);
559                         break;
560                 }
561         }
562         read_unlock_bh(&nf_conntrack_lock);
563
564         if (!ct)
565                 return dropped;
566
567         if (del_timer(&ct->timeout)) {
568                 death_by_timeout((unsigned long)ct);
569                 dropped = 1;
570                 NF_CT_STAT_INC_ATOMIC(early_drop);
571         }
572         nf_ct_put(ct);
573         return dropped;
574 }
575
576 static struct nf_conn *
577 __nf_conntrack_alloc(const struct nf_conntrack_tuple *orig,
578                      const struct nf_conntrack_tuple *repl,
579                      const struct nf_conntrack_l3proto *l3proto,
580                      u_int32_t features)
581 {
582         struct nf_conn *conntrack = NULL;
583         struct nf_conntrack_helper *helper;
584
585         if (unlikely(!nf_conntrack_hash_rnd_initted)) {
586                 get_random_bytes(&nf_conntrack_hash_rnd, 4);
587                 nf_conntrack_hash_rnd_initted = 1;
588         }
589
590         /* We don't want any race condition at early drop stage */
591         atomic_inc(&nf_conntrack_count);
592
593         if (nf_conntrack_max
594             && atomic_read(&nf_conntrack_count) > nf_conntrack_max) {
595                 unsigned int hash = hash_conntrack(orig);
596                 /* Try dropping from this hash chain. */
597                 if (!early_drop(&nf_conntrack_hash[hash])) {
598                         atomic_dec(&nf_conntrack_count);
599                         if (net_ratelimit())
600                                 printk(KERN_WARNING
601                                        "nf_conntrack: table full, dropping"
602                                        " packet.\n");
603                         return ERR_PTR(-ENOMEM);
604                 }
605         }
606
607         /*  find features needed by this conntrack. */
608         features |= l3proto->get_features(orig);
609
610         /* FIXME: protect helper list per RCU */
611         read_lock_bh(&nf_conntrack_lock);
612         helper = __nf_ct_helper_find(repl);
613         /* NAT might want to assign a helper later */
614         if (helper || features & NF_CT_F_NAT)
615                 features |= NF_CT_F_HELP;
616         read_unlock_bh(&nf_conntrack_lock);
617
618         DEBUGP("nf_conntrack_alloc: features=0x%x\n", features);
619
620         read_lock_bh(&nf_ct_cache_lock);
621
622         if (unlikely(!nf_ct_cache[features].use)) {
623                 DEBUGP("nf_conntrack_alloc: not supported features = 0x%x\n",
624                         features);
625                 goto out;
626         }
627
628         conntrack = kmem_cache_alloc(nf_ct_cache[features].cachep, GFP_ATOMIC);
629         if (conntrack == NULL) {
630                 DEBUGP("nf_conntrack_alloc: Can't alloc conntrack from cache\n");
631                 goto out;
632         }
633
634         memset(conntrack, 0, nf_ct_cache[features].size);
635         conntrack->features = features;
636         atomic_set(&conntrack->ct_general.use, 1);
637         conntrack->ct_general.destroy = destroy_conntrack;
638         conntrack->tuplehash[IP_CT_DIR_ORIGINAL].tuple = *orig;
639         conntrack->tuplehash[IP_CT_DIR_REPLY].tuple = *repl;
640         /* Don't set timer yet: wait for confirmation */
641         init_timer(&conntrack->timeout);
642         conntrack->timeout.data = (unsigned long)conntrack;
643         conntrack->timeout.function = death_by_timeout;
644         read_unlock_bh(&nf_ct_cache_lock);
645
646         return conntrack;
647 out:
648         read_unlock_bh(&nf_ct_cache_lock);
649         atomic_dec(&nf_conntrack_count);
650         return conntrack;
651 }
652
653 struct nf_conn *nf_conntrack_alloc(const struct nf_conntrack_tuple *orig,
654                                    const struct nf_conntrack_tuple *repl)
655 {
656         struct nf_conntrack_l3proto *l3proto;
657         struct nf_conn *ct;
658
659         rcu_read_lock();
660         l3proto = __nf_ct_l3proto_find(orig->src.l3num);
661         ct = __nf_conntrack_alloc(orig, repl, l3proto, 0);
662         rcu_read_unlock();
663
664         return ct;
665 }
666 EXPORT_SYMBOL_GPL(nf_conntrack_alloc);
667
668 void nf_conntrack_free(struct nf_conn *conntrack)
669 {
670         u_int32_t features = conntrack->features;
671         NF_CT_ASSERT(features >= NF_CT_F_BASIC && features < NF_CT_F_NUM);
672         DEBUGP("nf_conntrack_free: features = 0x%x, conntrack=%p\n", features,
673                conntrack);
674         kmem_cache_free(nf_ct_cache[features].cachep, conntrack);
675         atomic_dec(&nf_conntrack_count);
676 }
677 EXPORT_SYMBOL_GPL(nf_conntrack_free);
678
679 /* Allocate a new conntrack: we return -ENOMEM if classification
680    failed due to stress.  Otherwise it really is unclassifiable. */
681 static struct nf_conntrack_tuple_hash *
682 init_conntrack(const struct nf_conntrack_tuple *tuple,
683                struct nf_conntrack_l3proto *l3proto,
684                struct nf_conntrack_l4proto *l4proto,
685                struct sk_buff *skb,
686                unsigned int dataoff)
687 {
688         struct nf_conn *conntrack;
689         struct nf_conntrack_tuple repl_tuple;
690         struct nf_conntrack_expect *exp;
691         u_int32_t features = 0;
692
693         if (!nf_ct_invert_tuple(&repl_tuple, tuple, l3proto, l4proto)) {
694                 DEBUGP("Can't invert tuple.\n");
695                 return NULL;
696         }
697
698         read_lock_bh(&nf_conntrack_lock);
699         exp = __nf_conntrack_expect_find(tuple);
700         if (exp && exp->helper)
701                 features = NF_CT_F_HELP;
702         read_unlock_bh(&nf_conntrack_lock);
703
704         conntrack = __nf_conntrack_alloc(tuple, &repl_tuple, l3proto, features);
705         if (conntrack == NULL || IS_ERR(conntrack)) {
706                 DEBUGP("Can't allocate conntrack.\n");
707                 return (struct nf_conntrack_tuple_hash *)conntrack;
708         }
709
710         if (!l4proto->new(conntrack, skb, dataoff)) {
711                 nf_conntrack_free(conntrack);
712                 DEBUGP("init conntrack: can't track with proto module\n");
713                 return NULL;
714         }
715
716         write_lock_bh(&nf_conntrack_lock);
717         exp = find_expectation(tuple);
718
719         if (exp) {
720                 DEBUGP("conntrack: expectation arrives ct=%p exp=%p\n",
721                         conntrack, exp);
722                 /* Welcome, Mr. Bond.  We've been expecting you... */
723                 __set_bit(IPS_EXPECTED_BIT, &conntrack->status);
724                 conntrack->master = exp->master;
725                 if (exp->helper)
726                         nfct_help(conntrack)->helper = exp->helper;
727 #ifdef CONFIG_NF_CONNTRACK_MARK
728                 conntrack->mark = exp->master->mark;
729 #endif
730 #ifdef CONFIG_NF_CONNTRACK_SECMARK
731                 conntrack->secmark = exp->master->secmark;
732 #endif
733                 nf_conntrack_get(&conntrack->master->ct_general);
734                 NF_CT_STAT_INC(expect_new);
735         } else {
736                 struct nf_conn_help *help = nfct_help(conntrack);
737
738                 if (help)
739                         help->helper = __nf_ct_helper_find(&repl_tuple);
740                 NF_CT_STAT_INC(new);
741         }
742
743         /* Overload tuple linked list to put us in unconfirmed list. */
744         list_add(&conntrack->tuplehash[IP_CT_DIR_ORIGINAL].list, &unconfirmed);
745
746         write_unlock_bh(&nf_conntrack_lock);
747
748         if (exp) {
749                 if (exp->expectfn)
750                         exp->expectfn(conntrack, exp);
751                 nf_conntrack_expect_put(exp);
752         }
753
754         return &conntrack->tuplehash[IP_CT_DIR_ORIGINAL];
755 }
756
757 /* On success, returns conntrack ptr, sets skb->nfct and ctinfo */
758 static inline struct nf_conn *
759 resolve_normal_ct(struct sk_buff *skb,
760                   unsigned int dataoff,
761                   u_int16_t l3num,
762                   u_int8_t protonum,
763                   struct nf_conntrack_l3proto *l3proto,
764                   struct nf_conntrack_l4proto *l4proto,
765                   int *set_reply,
766                   enum ip_conntrack_info *ctinfo)
767 {
768         struct nf_conntrack_tuple tuple;
769         struct nf_conntrack_tuple_hash *h;
770         struct nf_conn *ct;
771
772         if (!nf_ct_get_tuple(skb, skb_network_offset(skb),
773                              dataoff, l3num, protonum, &tuple, l3proto,
774                              l4proto)) {
775                 DEBUGP("resolve_normal_ct: Can't get tuple\n");
776                 return NULL;
777         }
778
779         /* look for tuple match */
780         h = nf_conntrack_find_get(&tuple, NULL);
781         if (!h) {
782                 h = init_conntrack(&tuple, l3proto, l4proto, skb, dataoff);
783                 if (!h)
784                         return NULL;
785                 if (IS_ERR(h))
786                         return (void *)h;
787         }
788         ct = nf_ct_tuplehash_to_ctrack(h);
789
790         /* It exists; we have (non-exclusive) reference. */
791         if (NF_CT_DIRECTION(h) == IP_CT_DIR_REPLY) {
792                 *ctinfo = IP_CT_ESTABLISHED + IP_CT_IS_REPLY;
793                 /* Please set reply bit if this packet OK */
794                 *set_reply = 1;
795         } else {
796                 /* Once we've had two way comms, always ESTABLISHED. */
797                 if (test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) {
798                         DEBUGP("nf_conntrack_in: normal packet for %p\n", ct);
799                         *ctinfo = IP_CT_ESTABLISHED;
800                 } else if (test_bit(IPS_EXPECTED_BIT, &ct->status)) {
801                         DEBUGP("nf_conntrack_in: related packet for %p\n", ct);
802                         *ctinfo = IP_CT_RELATED;
803                 } else {
804                         DEBUGP("nf_conntrack_in: new packet for %p\n", ct);
805                         *ctinfo = IP_CT_NEW;
806                 }
807                 *set_reply = 0;
808         }
809         skb->nfct = &ct->ct_general;
810         skb->nfctinfo = *ctinfo;
811         return ct;
812 }
813
814 unsigned int
815 nf_conntrack_in(int pf, unsigned int hooknum, struct sk_buff **pskb)
816 {
817         struct nf_conn *ct;
818         enum ip_conntrack_info ctinfo;
819         struct nf_conntrack_l3proto *l3proto;
820         struct nf_conntrack_l4proto *l4proto;
821         unsigned int dataoff;
822         u_int8_t protonum;
823         int set_reply = 0;
824         int ret;
825
826         /* Previously seen (loopback or untracked)?  Ignore. */
827         if ((*pskb)->nfct) {
828                 NF_CT_STAT_INC_ATOMIC(ignore);
829                 return NF_ACCEPT;
830         }
831
832         /* rcu_read_lock()ed by nf_hook_slow */
833         l3proto = __nf_ct_l3proto_find((u_int16_t)pf);
834
835         if ((ret = l3proto->prepare(pskb, hooknum, &dataoff, &protonum)) <= 0) {
836                 DEBUGP("not prepared to track yet or error occured\n");
837                 return -ret;
838         }
839
840         l4proto = __nf_ct_l4proto_find((u_int16_t)pf, protonum);
841
842         /* It may be an special packet, error, unclean...
843          * inverse of the return code tells to the netfilter
844          * core what to do with the packet. */
845         if (l4proto->error != NULL &&
846             (ret = l4proto->error(*pskb, dataoff, &ctinfo, pf, hooknum)) <= 0) {
847                 NF_CT_STAT_INC_ATOMIC(error);
848                 NF_CT_STAT_INC_ATOMIC(invalid);
849                 return -ret;
850         }
851
852         ct = resolve_normal_ct(*pskb, dataoff, pf, protonum, l3proto, l4proto,
853                                &set_reply, &ctinfo);
854         if (!ct) {
855                 /* Not valid part of a connection */
856                 NF_CT_STAT_INC_ATOMIC(invalid);
857                 return NF_ACCEPT;
858         }
859
860         if (IS_ERR(ct)) {
861                 /* Too stressed to deal. */
862                 NF_CT_STAT_INC_ATOMIC(drop);
863                 return NF_DROP;
864         }
865
866         NF_CT_ASSERT((*pskb)->nfct);
867
868         ret = l4proto->packet(ct, *pskb, dataoff, ctinfo, pf, hooknum);
869         if (ret < 0) {
870                 /* Invalid: inverse of the return code tells
871                  * the netfilter core what to do */
872                 DEBUGP("nf_conntrack_in: Can't track with proto module\n");
873                 nf_conntrack_put((*pskb)->nfct);
874                 (*pskb)->nfct = NULL;
875                 NF_CT_STAT_INC_ATOMIC(invalid);
876                 return -ret;
877         }
878
879         if (set_reply && !test_and_set_bit(IPS_SEEN_REPLY_BIT, &ct->status))
880                 nf_conntrack_event_cache(IPCT_STATUS, *pskb);
881
882         return ret;
883 }
884 EXPORT_SYMBOL_GPL(nf_conntrack_in);
885
886 int nf_ct_invert_tuplepr(struct nf_conntrack_tuple *inverse,
887                          const struct nf_conntrack_tuple *orig)
888 {
889         int ret;
890
891         rcu_read_lock();
892         ret = nf_ct_invert_tuple(inverse, orig,
893                                  __nf_ct_l3proto_find(orig->src.l3num),
894                                  __nf_ct_l4proto_find(orig->src.l3num,
895                                                       orig->dst.protonum));
896         rcu_read_unlock();
897         return ret;
898 }
899 EXPORT_SYMBOL_GPL(nf_ct_invert_tuplepr);
900
901 /* Alter reply tuple (maybe alter helper).  This is for NAT, and is
902    implicitly racy: see __nf_conntrack_confirm */
903 void nf_conntrack_alter_reply(struct nf_conn *ct,
904                               const struct nf_conntrack_tuple *newreply)
905 {
906         struct nf_conn_help *help = nfct_help(ct);
907
908         write_lock_bh(&nf_conntrack_lock);
909         /* Should be unconfirmed, so not in hash table yet */
910         NF_CT_ASSERT(!nf_ct_is_confirmed(ct));
911
912         DEBUGP("Altering reply tuple of %p to ", ct);
913         NF_CT_DUMP_TUPLE(newreply);
914
915         ct->tuplehash[IP_CT_DIR_REPLY].tuple = *newreply;
916         if (!ct->master && help && help->expecting == 0)
917                 help->helper = __nf_ct_helper_find(newreply);
918         write_unlock_bh(&nf_conntrack_lock);
919 }
920 EXPORT_SYMBOL_GPL(nf_conntrack_alter_reply);
921
922 /* Refresh conntrack for this many jiffies and do accounting if do_acct is 1 */
923 void __nf_ct_refresh_acct(struct nf_conn *ct,
924                           enum ip_conntrack_info ctinfo,
925                           const struct sk_buff *skb,
926                           unsigned long extra_jiffies,
927                           int do_acct)
928 {
929         int event = 0;
930
931         NF_CT_ASSERT(ct->timeout.data == (unsigned long)ct);
932         NF_CT_ASSERT(skb);
933
934         write_lock_bh(&nf_conntrack_lock);
935
936         /* Only update if this is not a fixed timeout */
937         if (test_bit(IPS_FIXED_TIMEOUT_BIT, &ct->status)) {
938                 write_unlock_bh(&nf_conntrack_lock);
939                 return;
940         }
941
942         /* If not in hash table, timer will not be active yet */
943         if (!nf_ct_is_confirmed(ct)) {
944                 ct->timeout.expires = extra_jiffies;
945                 event = IPCT_REFRESH;
946         } else {
947                 unsigned long newtime = jiffies + extra_jiffies;
948
949                 /* Only update the timeout if the new timeout is at least
950                    HZ jiffies from the old timeout. Need del_timer for race
951                    avoidance (may already be dying). */
952                 if (newtime - ct->timeout.expires >= HZ
953                     && del_timer(&ct->timeout)) {
954                         ct->timeout.expires = newtime;
955                         add_timer(&ct->timeout);
956                         event = IPCT_REFRESH;
957                 }
958         }
959
960 #ifdef CONFIG_NF_CT_ACCT
961         if (do_acct) {
962                 ct->counters[CTINFO2DIR(ctinfo)].packets++;
963                 ct->counters[CTINFO2DIR(ctinfo)].bytes +=
964                         skb->len - skb_network_offset(skb);
965
966                 if ((ct->counters[CTINFO2DIR(ctinfo)].packets & 0x80000000)
967                     || (ct->counters[CTINFO2DIR(ctinfo)].bytes & 0x80000000))
968                         event |= IPCT_COUNTER_FILLING;
969         }
970 #endif
971
972         write_unlock_bh(&nf_conntrack_lock);
973
974         /* must be unlocked when calling event cache */
975         if (event)
976                 nf_conntrack_event_cache(event, skb);
977 }
978 EXPORT_SYMBOL_GPL(__nf_ct_refresh_acct);
979
980 #if defined(CONFIG_NF_CT_NETLINK) || defined(CONFIG_NF_CT_NETLINK_MODULE)
981
982 #include <linux/netfilter/nfnetlink.h>
983 #include <linux/netfilter/nfnetlink_conntrack.h>
984 #include <linux/mutex.h>
985
986
987 /* Generic function for tcp/udp/sctp/dccp and alike. This needs to be
988  * in ip_conntrack_core, since we don't want the protocols to autoload
989  * or depend on ctnetlink */
990 int nf_ct_port_tuple_to_nfattr(struct sk_buff *skb,
991                                const struct nf_conntrack_tuple *tuple)
992 {
993         NFA_PUT(skb, CTA_PROTO_SRC_PORT, sizeof(u_int16_t),
994                 &tuple->src.u.tcp.port);
995         NFA_PUT(skb, CTA_PROTO_DST_PORT, sizeof(u_int16_t),
996                 &tuple->dst.u.tcp.port);
997         return 0;
998
999 nfattr_failure:
1000         return -1;
1001 }
1002 EXPORT_SYMBOL_GPL(nf_ct_port_tuple_to_nfattr);
1003
1004 static const size_t cta_min_proto[CTA_PROTO_MAX] = {
1005         [CTA_PROTO_SRC_PORT-1]  = sizeof(u_int16_t),
1006         [CTA_PROTO_DST_PORT-1]  = sizeof(u_int16_t)
1007 };
1008
1009 int nf_ct_port_nfattr_to_tuple(struct nfattr *tb[],
1010                                struct nf_conntrack_tuple *t)
1011 {
1012         if (!tb[CTA_PROTO_SRC_PORT-1] || !tb[CTA_PROTO_DST_PORT-1])
1013                 return -EINVAL;
1014
1015         if (nfattr_bad_size(tb, CTA_PROTO_MAX, cta_min_proto))
1016                 return -EINVAL;
1017
1018         t->src.u.tcp.port = *(__be16 *)NFA_DATA(tb[CTA_PROTO_SRC_PORT-1]);
1019         t->dst.u.tcp.port = *(__be16 *)NFA_DATA(tb[CTA_PROTO_DST_PORT-1]);
1020
1021         return 0;
1022 }
1023 EXPORT_SYMBOL_GPL(nf_ct_port_nfattr_to_tuple);
1024 #endif
1025
1026 /* Used by ipt_REJECT and ip6t_REJECT. */
1027 void __nf_conntrack_attach(struct sk_buff *nskb, struct sk_buff *skb)
1028 {
1029         struct nf_conn *ct;
1030         enum ip_conntrack_info ctinfo;
1031
1032         /* This ICMP is in reverse direction to the packet which caused it */
1033         ct = nf_ct_get(skb, &ctinfo);
1034         if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL)
1035                 ctinfo = IP_CT_RELATED + IP_CT_IS_REPLY;
1036         else
1037                 ctinfo = IP_CT_RELATED;
1038
1039         /* Attach to new skbuff, and increment count */
1040         nskb->nfct = &ct->ct_general;
1041         nskb->nfctinfo = ctinfo;
1042         nf_conntrack_get(nskb->nfct);
1043 }
1044 EXPORT_SYMBOL_GPL(__nf_conntrack_attach);
1045
1046 static inline int
1047 do_iter(const struct nf_conntrack_tuple_hash *i,
1048         int (*iter)(struct nf_conn *i, void *data),
1049         void *data)
1050 {
1051         return iter(nf_ct_tuplehash_to_ctrack(i), data);
1052 }
1053
1054 /* Bring out ya dead! */
1055 static struct nf_conn *
1056 get_next_corpse(int (*iter)(struct nf_conn *i, void *data),
1057                 void *data, unsigned int *bucket)
1058 {
1059         struct nf_conntrack_tuple_hash *h;
1060         struct nf_conn *ct;
1061
1062         write_lock_bh(&nf_conntrack_lock);
1063         for (; *bucket < nf_conntrack_htable_size; (*bucket)++) {
1064                 list_for_each_entry(h, &nf_conntrack_hash[*bucket], list) {
1065                         ct = nf_ct_tuplehash_to_ctrack(h);
1066                         if (iter(ct, data))
1067                                 goto found;
1068                 }
1069         }
1070         list_for_each_entry(h, &unconfirmed, list) {
1071                 ct = nf_ct_tuplehash_to_ctrack(h);
1072                 if (iter(ct, data))
1073                         set_bit(IPS_DYING_BIT, &ct->status);
1074         }
1075         write_unlock_bh(&nf_conntrack_lock);
1076         return NULL;
1077 found:
1078         atomic_inc(&ct->ct_general.use);
1079         write_unlock_bh(&nf_conntrack_lock);
1080         return ct;
1081 }
1082
1083 void
1084 nf_ct_iterate_cleanup(int (*iter)(struct nf_conn *i, void *data), void *data)
1085 {
1086         struct nf_conn *ct;
1087         unsigned int bucket = 0;
1088
1089         while ((ct = get_next_corpse(iter, data, &bucket)) != NULL) {
1090                 /* Time to push up daises... */
1091                 if (del_timer(&ct->timeout))
1092                         death_by_timeout((unsigned long)ct);
1093                 /* ... else the timer will get him soon. */
1094
1095                 nf_ct_put(ct);
1096         }
1097 }
1098 EXPORT_SYMBOL_GPL(nf_ct_iterate_cleanup);
1099
1100 static int kill_all(struct nf_conn *i, void *data)
1101 {
1102         return 1;
1103 }
1104
1105 static void free_conntrack_hash(struct list_head *hash, int vmalloced, int size)
1106 {
1107         if (vmalloced)
1108                 vfree(hash);
1109         else
1110                 free_pages((unsigned long)hash,
1111                            get_order(sizeof(struct list_head) * size));
1112 }
1113
1114 void nf_conntrack_flush(void)
1115 {
1116         nf_ct_iterate_cleanup(kill_all, NULL);
1117 }
1118 EXPORT_SYMBOL_GPL(nf_conntrack_flush);
1119
1120 /* Mishearing the voices in his head, our hero wonders how he's
1121    supposed to kill the mall. */
1122 void nf_conntrack_cleanup(void)
1123 {
1124         int i;
1125
1126         rcu_assign_pointer(ip_ct_attach, NULL);
1127
1128         /* This makes sure all current packets have passed through
1129            netfilter framework.  Roll on, two-stage module
1130            delete... */
1131         synchronize_net();
1132
1133         nf_ct_event_cache_flush();
1134  i_see_dead_people:
1135         nf_conntrack_flush();
1136         if (atomic_read(&nf_conntrack_count) != 0) {
1137                 schedule();
1138                 goto i_see_dead_people;
1139         }
1140         /* wait until all references to nf_conntrack_untracked are dropped */
1141         while (atomic_read(&nf_conntrack_untracked.ct_general.use) > 1)
1142                 schedule();
1143
1144         for (i = 0; i < NF_CT_F_NUM; i++) {
1145                 if (nf_ct_cache[i].use == 0)
1146                         continue;
1147
1148                 NF_CT_ASSERT(nf_ct_cache[i].use == 1);
1149                 nf_ct_cache[i].use = 1;
1150                 nf_conntrack_unregister_cache(i);
1151         }
1152         kmem_cache_destroy(nf_conntrack_expect_cachep);
1153         free_conntrack_hash(nf_conntrack_hash, nf_conntrack_vmalloc,
1154                             nf_conntrack_htable_size);
1155
1156         nf_conntrack_proto_fini();
1157 }
1158
1159 static struct list_head *alloc_hashtable(int size, int *vmalloced)
1160 {
1161         struct list_head *hash;
1162         unsigned int i;
1163
1164         *vmalloced = 0;
1165         hash = (void*)__get_free_pages(GFP_KERNEL,
1166                                        get_order(sizeof(struct list_head)
1167                                                  * size));
1168         if (!hash) {
1169                 *vmalloced = 1;
1170                 printk(KERN_WARNING "nf_conntrack: falling back to vmalloc.\n");
1171                 hash = vmalloc(sizeof(struct list_head) * size);
1172         }
1173
1174         if (hash)
1175                 for (i = 0; i < size; i++)
1176                         INIT_LIST_HEAD(&hash[i]);
1177
1178         return hash;
1179 }
1180
1181 int set_hashsize(const char *val, struct kernel_param *kp)
1182 {
1183         int i, bucket, hashsize, vmalloced;
1184         int old_vmalloced, old_size;
1185         int rnd;
1186         struct list_head *hash, *old_hash;
1187         struct nf_conntrack_tuple_hash *h;
1188
1189         /* On boot, we can set this without any fancy locking. */
1190         if (!nf_conntrack_htable_size)
1191                 return param_set_uint(val, kp);
1192
1193         hashsize = simple_strtol(val, NULL, 0);
1194         if (!hashsize)
1195                 return -EINVAL;
1196
1197         hash = alloc_hashtable(hashsize, &vmalloced);
1198         if (!hash)
1199                 return -ENOMEM;
1200
1201         /* We have to rehahs for the new table anyway, so we also can
1202          * use a newrandom seed */
1203         get_random_bytes(&rnd, 4);
1204
1205         write_lock_bh(&nf_conntrack_lock);
1206         for (i = 0; i < nf_conntrack_htable_size; i++) {
1207                 while (!list_empty(&nf_conntrack_hash[i])) {
1208                         h = list_entry(nf_conntrack_hash[i].next,
1209                                        struct nf_conntrack_tuple_hash, list);
1210                         list_del(&h->list);
1211                         bucket = __hash_conntrack(&h->tuple, hashsize, rnd);
1212                         list_add_tail(&h->list, &hash[bucket]);
1213                 }
1214         }
1215         old_size = nf_conntrack_htable_size;
1216         old_vmalloced = nf_conntrack_vmalloc;
1217         old_hash = nf_conntrack_hash;
1218
1219         nf_conntrack_htable_size = hashsize;
1220         nf_conntrack_vmalloc = vmalloced;
1221         nf_conntrack_hash = hash;
1222         nf_conntrack_hash_rnd = rnd;
1223         write_unlock_bh(&nf_conntrack_lock);
1224
1225         free_conntrack_hash(old_hash, old_vmalloced, old_size);
1226         return 0;
1227 }
1228
1229 module_param_call(hashsize, set_hashsize, param_get_uint,
1230                   &nf_conntrack_htable_size, 0600);
1231
1232 int __init nf_conntrack_init(void)
1233 {
1234         int ret;
1235
1236         /* Idea from tcp.c: use 1/16384 of memory.  On i386: 32MB
1237          * machine has 256 buckets.  >= 1GB machines have 8192 buckets. */
1238         if (!nf_conntrack_htable_size) {
1239                 nf_conntrack_htable_size
1240                         = (((num_physpages << PAGE_SHIFT) / 16384)
1241                            / sizeof(struct list_head));
1242                 if (num_physpages > (1024 * 1024 * 1024 / PAGE_SIZE))
1243                         nf_conntrack_htable_size = 8192;
1244                 if (nf_conntrack_htable_size < 16)
1245                         nf_conntrack_htable_size = 16;
1246         }
1247         nf_conntrack_max = 8 * nf_conntrack_htable_size;
1248
1249         printk("nf_conntrack version %s (%u buckets, %d max)\n",
1250                NF_CONNTRACK_VERSION, nf_conntrack_htable_size,
1251                nf_conntrack_max);
1252
1253         nf_conntrack_hash = alloc_hashtable(nf_conntrack_htable_size,
1254                                             &nf_conntrack_vmalloc);
1255         if (!nf_conntrack_hash) {
1256                 printk(KERN_ERR "Unable to create nf_conntrack_hash\n");
1257                 goto err_out;
1258         }
1259
1260         ret = nf_conntrack_register_cache(NF_CT_F_BASIC, "nf_conntrack:basic",
1261                                           sizeof(struct nf_conn));
1262         if (ret < 0) {
1263                 printk(KERN_ERR "Unable to create nf_conn slab cache\n");
1264                 goto err_free_hash;
1265         }
1266
1267         nf_conntrack_expect_cachep = kmem_cache_create("nf_conntrack_expect",
1268                                         sizeof(struct nf_conntrack_expect),
1269                                         0, 0, NULL, NULL);
1270         if (!nf_conntrack_expect_cachep) {
1271                 printk(KERN_ERR "Unable to create nf_expect slab cache\n");
1272                 goto err_free_conntrack_slab;
1273         }
1274
1275         ret = nf_conntrack_proto_init();
1276         if (ret < 0)
1277                 goto out_free_expect_slab;
1278
1279         /* For use by REJECT target */
1280         rcu_assign_pointer(ip_ct_attach, __nf_conntrack_attach);
1281
1282         /* Set up fake conntrack:
1283             - to never be deleted, not in any hashes */
1284         atomic_set(&nf_conntrack_untracked.ct_general.use, 1);
1285         /*  - and look it like as a confirmed connection */
1286         set_bit(IPS_CONFIRMED_BIT, &nf_conntrack_untracked.status);
1287
1288         return ret;
1289
1290 out_free_expect_slab:
1291         kmem_cache_destroy(nf_conntrack_expect_cachep);
1292 err_free_conntrack_slab:
1293         nf_conntrack_unregister_cache(NF_CT_F_BASIC);
1294 err_free_hash:
1295         free_conntrack_hash(nf_conntrack_hash, nf_conntrack_vmalloc,
1296                             nf_conntrack_htable_size);
1297 err_out:
1298         return -ENOMEM;
1299 }