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