85ab2fd6a66515ea77cf34b9a972f36adfdba0a2
[linux-2.6-microblaze.git] / net / netfilter / nf_conntrack_core.c
1 /* Connection state tracking for netfilter.  This is separated from,
2    but required by, the NAT layer; it can also be used by an iptables
3    extension. */
4
5 /* (C) 1999-2001 Paul `Rusty' Russell
6  * (C) 2002-2006 Netfilter Core Team <coreteam@netfilter.org>
7  * (C) 2003,2004 USAGI/WIDE Project <http://www.linux-ipv6.org>
8  * (C) 2005-2012 Patrick McHardy <kaber@trash.net>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License version 2 as
12  * published by the Free Software Foundation.
13  */
14
15 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
16
17 #include <linux/types.h>
18 #include <linux/netfilter.h>
19 #include <linux/module.h>
20 #include <linux/sched.h>
21 #include <linux/skbuff.h>
22 #include <linux/proc_fs.h>
23 #include <linux/vmalloc.h>
24 #include <linux/stddef.h>
25 #include <linux/slab.h>
26 #include <linux/random.h>
27 #include <linux/jhash.h>
28 #include <linux/err.h>
29 #include <linux/percpu.h>
30 #include <linux/moduleparam.h>
31 #include <linux/notifier.h>
32 #include <linux/kernel.h>
33 #include <linux/netdevice.h>
34 #include <linux/socket.h>
35 #include <linux/mm.h>
36 #include <linux/nsproxy.h>
37 #include <linux/rculist_nulls.h>
38
39 #include <net/netfilter/nf_conntrack.h>
40 #include <net/netfilter/nf_conntrack_l3proto.h>
41 #include <net/netfilter/nf_conntrack_l4proto.h>
42 #include <net/netfilter/nf_conntrack_expect.h>
43 #include <net/netfilter/nf_conntrack_helper.h>
44 #include <net/netfilter/nf_conntrack_seqadj.h>
45 #include <net/netfilter/nf_conntrack_core.h>
46 #include <net/netfilter/nf_conntrack_extend.h>
47 #include <net/netfilter/nf_conntrack_acct.h>
48 #include <net/netfilter/nf_conntrack_ecache.h>
49 #include <net/netfilter/nf_conntrack_zones.h>
50 #include <net/netfilter/nf_conntrack_timestamp.h>
51 #include <net/netfilter/nf_conntrack_timeout.h>
52 #include <net/netfilter/nf_conntrack_labels.h>
53 #include <net/netfilter/nf_conntrack_synproxy.h>
54 #include <net/netfilter/nf_nat.h>
55 #include <net/netfilter/nf_nat_core.h>
56 #include <net/netfilter/nf_nat_helper.h>
57 #include <net/netns/hash.h>
58
59 #include "nf_internals.h"
60
61 __cacheline_aligned_in_smp spinlock_t nf_conntrack_locks[CONNTRACK_LOCKS];
62 EXPORT_SYMBOL_GPL(nf_conntrack_locks);
63
64 __cacheline_aligned_in_smp DEFINE_SPINLOCK(nf_conntrack_expect_lock);
65 EXPORT_SYMBOL_GPL(nf_conntrack_expect_lock);
66
67 struct hlist_nulls_head *nf_conntrack_hash __read_mostly;
68 EXPORT_SYMBOL_GPL(nf_conntrack_hash);
69
70 struct conntrack_gc_work {
71         struct delayed_work     dwork;
72         u32                     last_bucket;
73         bool                    exiting;
74         bool                    early_drop;
75         long                    next_gc_run;
76 };
77
78 static __read_mostly struct kmem_cache *nf_conntrack_cachep;
79 static __read_mostly spinlock_t nf_conntrack_locks_all_lock;
80 static __read_mostly DEFINE_SPINLOCK(nf_conntrack_locks_all_lock);
81 static __read_mostly bool nf_conntrack_locks_all;
82
83 /* every gc cycle scans at most 1/GC_MAX_BUCKETS_DIV part of table */
84 #define GC_MAX_BUCKETS_DIV      128u
85 /* upper bound of full table scan */
86 #define GC_MAX_SCAN_JIFFIES     (16u * HZ)
87 /* desired ratio of entries found to be expired */
88 #define GC_EVICT_RATIO  50u
89
90 static struct conntrack_gc_work conntrack_gc_work;
91
92 void nf_conntrack_lock(spinlock_t *lock) __acquires(lock)
93 {
94         /* 1) Acquire the lock */
95         spin_lock(lock);
96
97         /* 2) read nf_conntrack_locks_all, with ACQUIRE semantics
98          * It pairs with the smp_store_release() in nf_conntrack_all_unlock()
99          */
100         if (likely(smp_load_acquire(&nf_conntrack_locks_all) == false))
101                 return;
102
103         /* fast path failed, unlock */
104         spin_unlock(lock);
105
106         /* Slow path 1) get global lock */
107         spin_lock(&nf_conntrack_locks_all_lock);
108
109         /* Slow path 2) get the lock we want */
110         spin_lock(lock);
111
112         /* Slow path 3) release the global lock */
113         spin_unlock(&nf_conntrack_locks_all_lock);
114 }
115 EXPORT_SYMBOL_GPL(nf_conntrack_lock);
116
117 static void nf_conntrack_double_unlock(unsigned int h1, unsigned int h2)
118 {
119         h1 %= CONNTRACK_LOCKS;
120         h2 %= CONNTRACK_LOCKS;
121         spin_unlock(&nf_conntrack_locks[h1]);
122         if (h1 != h2)
123                 spin_unlock(&nf_conntrack_locks[h2]);
124 }
125
126 /* return true if we need to recompute hashes (in case hash table was resized) */
127 static bool nf_conntrack_double_lock(struct net *net, unsigned int h1,
128                                      unsigned int h2, unsigned int sequence)
129 {
130         h1 %= CONNTRACK_LOCKS;
131         h2 %= CONNTRACK_LOCKS;
132         if (h1 <= h2) {
133                 nf_conntrack_lock(&nf_conntrack_locks[h1]);
134                 if (h1 != h2)
135                         spin_lock_nested(&nf_conntrack_locks[h2],
136                                          SINGLE_DEPTH_NESTING);
137         } else {
138                 nf_conntrack_lock(&nf_conntrack_locks[h2]);
139                 spin_lock_nested(&nf_conntrack_locks[h1],
140                                  SINGLE_DEPTH_NESTING);
141         }
142         if (read_seqcount_retry(&nf_conntrack_generation, sequence)) {
143                 nf_conntrack_double_unlock(h1, h2);
144                 return true;
145         }
146         return false;
147 }
148
149 static void nf_conntrack_all_lock(void)
150 {
151         int i;
152
153         spin_lock(&nf_conntrack_locks_all_lock);
154
155         nf_conntrack_locks_all = true;
156
157         for (i = 0; i < CONNTRACK_LOCKS; i++) {
158                 spin_lock(&nf_conntrack_locks[i]);
159
160                 /* This spin_unlock provides the "release" to ensure that
161                  * nf_conntrack_locks_all==true is visible to everyone that
162                  * acquired spin_lock(&nf_conntrack_locks[]).
163                  */
164                 spin_unlock(&nf_conntrack_locks[i]);
165         }
166 }
167
168 static void nf_conntrack_all_unlock(void)
169 {
170         /* All prior stores must be complete before we clear
171          * 'nf_conntrack_locks_all'. Otherwise nf_conntrack_lock()
172          * might observe the false value but not the entire
173          * critical section.
174          * It pairs with the smp_load_acquire() in nf_conntrack_lock()
175          */
176         smp_store_release(&nf_conntrack_locks_all, false);
177         spin_unlock(&nf_conntrack_locks_all_lock);
178 }
179
180 unsigned int nf_conntrack_htable_size __read_mostly;
181 EXPORT_SYMBOL_GPL(nf_conntrack_htable_size);
182
183 unsigned int nf_conntrack_max __read_mostly;
184 EXPORT_SYMBOL_GPL(nf_conntrack_max);
185 seqcount_t nf_conntrack_generation __read_mostly;
186 static unsigned int nf_conntrack_hash_rnd __read_mostly;
187
188 static u32 hash_conntrack_raw(const struct nf_conntrack_tuple *tuple,
189                               const struct net *net)
190 {
191         unsigned int n;
192         u32 seed;
193
194         get_random_once(&nf_conntrack_hash_rnd, sizeof(nf_conntrack_hash_rnd));
195
196         /* The direction must be ignored, so we hash everything up to the
197          * destination ports (which is a multiple of 4) and treat the last
198          * three bytes manually.
199          */
200         seed = nf_conntrack_hash_rnd ^ net_hash_mix(net);
201         n = (sizeof(tuple->src) + sizeof(tuple->dst.u3)) / sizeof(u32);
202         return jhash2((u32 *)tuple, n, seed ^
203                       (((__force __u16)tuple->dst.u.all << 16) |
204                       tuple->dst.protonum));
205 }
206
207 static u32 scale_hash(u32 hash)
208 {
209         return reciprocal_scale(hash, nf_conntrack_htable_size);
210 }
211
212 static u32 __hash_conntrack(const struct net *net,
213                             const struct nf_conntrack_tuple *tuple,
214                             unsigned int size)
215 {
216         return reciprocal_scale(hash_conntrack_raw(tuple, net), size);
217 }
218
219 static u32 hash_conntrack(const struct net *net,
220                           const struct nf_conntrack_tuple *tuple)
221 {
222         return scale_hash(hash_conntrack_raw(tuple, net));
223 }
224
225 bool
226 nf_ct_get_tuple(const struct sk_buff *skb,
227                 unsigned int nhoff,
228                 unsigned int dataoff,
229                 u_int16_t l3num,
230                 u_int8_t protonum,
231                 struct net *net,
232                 struct nf_conntrack_tuple *tuple,
233                 const struct nf_conntrack_l3proto *l3proto,
234                 const struct nf_conntrack_l4proto *l4proto)
235 {
236         memset(tuple, 0, sizeof(*tuple));
237
238         tuple->src.l3num = l3num;
239         if (l3proto->pkt_to_tuple(skb, nhoff, tuple) == 0)
240                 return false;
241
242         tuple->dst.protonum = protonum;
243         tuple->dst.dir = IP_CT_DIR_ORIGINAL;
244
245         return l4proto->pkt_to_tuple(skb, dataoff, net, tuple);
246 }
247 EXPORT_SYMBOL_GPL(nf_ct_get_tuple);
248
249 bool nf_ct_get_tuplepr(const struct sk_buff *skb, unsigned int nhoff,
250                        u_int16_t l3num,
251                        struct net *net, struct nf_conntrack_tuple *tuple)
252 {
253         const struct nf_conntrack_l3proto *l3proto;
254         const struct nf_conntrack_l4proto *l4proto;
255         unsigned int protoff;
256         u_int8_t protonum;
257         int ret;
258
259         rcu_read_lock();
260
261         l3proto = __nf_ct_l3proto_find(l3num);
262         ret = l3proto->get_l4proto(skb, nhoff, &protoff, &protonum);
263         if (ret != NF_ACCEPT) {
264                 rcu_read_unlock();
265                 return false;
266         }
267
268         l4proto = __nf_ct_l4proto_find(l3num, protonum);
269
270         ret = nf_ct_get_tuple(skb, nhoff, protoff, l3num, protonum, net, tuple,
271                               l3proto, l4proto);
272
273         rcu_read_unlock();
274         return ret;
275 }
276 EXPORT_SYMBOL_GPL(nf_ct_get_tuplepr);
277
278 bool
279 nf_ct_invert_tuple(struct nf_conntrack_tuple *inverse,
280                    const struct nf_conntrack_tuple *orig,
281                    const struct nf_conntrack_l3proto *l3proto,
282                    const struct nf_conntrack_l4proto *l4proto)
283 {
284         memset(inverse, 0, sizeof(*inverse));
285
286         inverse->src.l3num = orig->src.l3num;
287         if (l3proto->invert_tuple(inverse, orig) == 0)
288                 return false;
289
290         inverse->dst.dir = !orig->dst.dir;
291
292         inverse->dst.protonum = orig->dst.protonum;
293         return l4proto->invert_tuple(inverse, orig);
294 }
295 EXPORT_SYMBOL_GPL(nf_ct_invert_tuple);
296
297 static void
298 clean_from_lists(struct nf_conn *ct)
299 {
300         pr_debug("clean_from_lists(%p)\n", ct);
301         hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
302         hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode);
303
304         /* Destroy all pending expectations */
305         nf_ct_remove_expectations(ct);
306 }
307
308 /* must be called with local_bh_disable */
309 static void nf_ct_add_to_dying_list(struct nf_conn *ct)
310 {
311         struct ct_pcpu *pcpu;
312
313         /* add this conntrack to the (per cpu) dying list */
314         ct->cpu = smp_processor_id();
315         pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
316
317         spin_lock(&pcpu->lock);
318         hlist_nulls_add_head(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
319                              &pcpu->dying);
320         spin_unlock(&pcpu->lock);
321 }
322
323 /* must be called with local_bh_disable */
324 static void nf_ct_add_to_unconfirmed_list(struct nf_conn *ct)
325 {
326         struct ct_pcpu *pcpu;
327
328         /* add this conntrack to the (per cpu) unconfirmed list */
329         ct->cpu = smp_processor_id();
330         pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
331
332         spin_lock(&pcpu->lock);
333         hlist_nulls_add_head(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
334                              &pcpu->unconfirmed);
335         spin_unlock(&pcpu->lock);
336 }
337
338 /* must be called with local_bh_disable */
339 static void nf_ct_del_from_dying_or_unconfirmed_list(struct nf_conn *ct)
340 {
341         struct ct_pcpu *pcpu;
342
343         /* We overload first tuple to link into unconfirmed or dying list.*/
344         pcpu = per_cpu_ptr(nf_ct_net(ct)->ct.pcpu_lists, ct->cpu);
345
346         spin_lock(&pcpu->lock);
347         BUG_ON(hlist_nulls_unhashed(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode));
348         hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
349         spin_unlock(&pcpu->lock);
350 }
351
352 #define NFCT_ALIGN(len) (((len) + NFCT_INFOMASK) & ~NFCT_INFOMASK)
353
354 /* Released via destroy_conntrack() */
355 struct nf_conn *nf_ct_tmpl_alloc(struct net *net,
356                                  const struct nf_conntrack_zone *zone,
357                                  gfp_t flags)
358 {
359         struct nf_conn *tmpl, *p;
360
361         if (ARCH_KMALLOC_MINALIGN <= NFCT_INFOMASK) {
362                 tmpl = kzalloc(sizeof(*tmpl) + NFCT_INFOMASK, flags);
363                 if (!tmpl)
364                         return NULL;
365
366                 p = tmpl;
367                 tmpl = (struct nf_conn *)NFCT_ALIGN((unsigned long)p);
368                 if (tmpl != p) {
369                         tmpl = (struct nf_conn *)NFCT_ALIGN((unsigned long)p);
370                         tmpl->proto.tmpl_padto = (char *)tmpl - (char *)p;
371                 }
372         } else {
373                 tmpl = kzalloc(sizeof(*tmpl), flags);
374                 if (!tmpl)
375                         return NULL;
376         }
377
378         tmpl->status = IPS_TEMPLATE;
379         write_pnet(&tmpl->ct_net, net);
380         nf_ct_zone_add(tmpl, zone);
381         atomic_set(&tmpl->ct_general.use, 0);
382
383         return tmpl;
384 }
385 EXPORT_SYMBOL_GPL(nf_ct_tmpl_alloc);
386
387 void nf_ct_tmpl_free(struct nf_conn *tmpl)
388 {
389         nf_ct_ext_destroy(tmpl);
390         nf_ct_ext_free(tmpl);
391
392         if (ARCH_KMALLOC_MINALIGN <= NFCT_INFOMASK)
393                 kfree((char *)tmpl - tmpl->proto.tmpl_padto);
394         else
395                 kfree(tmpl);
396 }
397 EXPORT_SYMBOL_GPL(nf_ct_tmpl_free);
398
399 static void
400 destroy_conntrack(struct nf_conntrack *nfct)
401 {
402         struct nf_conn *ct = (struct nf_conn *)nfct;
403         const struct nf_conntrack_l4proto *l4proto;
404
405         pr_debug("destroy_conntrack(%p)\n", ct);
406         WARN_ON(atomic_read(&nfct->use) != 0);
407
408         if (unlikely(nf_ct_is_template(ct))) {
409                 nf_ct_tmpl_free(ct);
410                 return;
411         }
412         l4proto = __nf_ct_l4proto_find(nf_ct_l3num(ct), nf_ct_protonum(ct));
413         if (l4proto->destroy)
414                 l4proto->destroy(ct);
415
416         local_bh_disable();
417         /* Expectations will have been removed in clean_from_lists,
418          * except TFTP can create an expectation on the first packet,
419          * before connection is in the list, so we need to clean here,
420          * too.
421          */
422         nf_ct_remove_expectations(ct);
423
424         nf_ct_del_from_dying_or_unconfirmed_list(ct);
425
426         local_bh_enable();
427
428         if (ct->master)
429                 nf_ct_put(ct->master);
430
431         pr_debug("destroy_conntrack: returning ct=%p to slab\n", ct);
432         nf_conntrack_free(ct);
433 }
434
435 static void nf_ct_delete_from_lists(struct nf_conn *ct)
436 {
437         struct net *net = nf_ct_net(ct);
438         unsigned int hash, reply_hash;
439         unsigned int sequence;
440
441         nf_ct_helper_destroy(ct);
442
443         local_bh_disable();
444         do {
445                 sequence = read_seqcount_begin(&nf_conntrack_generation);
446                 hash = hash_conntrack(net,
447                                       &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
448                 reply_hash = hash_conntrack(net,
449                                            &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
450         } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
451
452         clean_from_lists(ct);
453         nf_conntrack_double_unlock(hash, reply_hash);
454
455         nf_ct_add_to_dying_list(ct);
456
457         local_bh_enable();
458 }
459
460 bool nf_ct_delete(struct nf_conn *ct, u32 portid, int report)
461 {
462         struct nf_conn_tstamp *tstamp;
463
464         if (test_and_set_bit(IPS_DYING_BIT, &ct->status))
465                 return false;
466
467         tstamp = nf_conn_tstamp_find(ct);
468         if (tstamp && tstamp->stop == 0)
469                 tstamp->stop = ktime_get_real_ns();
470
471         if (nf_conntrack_event_report(IPCT_DESTROY, ct,
472                                     portid, report) < 0) {
473                 /* destroy event was not delivered. nf_ct_put will
474                  * be done by event cache worker on redelivery.
475                  */
476                 nf_ct_delete_from_lists(ct);
477                 nf_conntrack_ecache_delayed_work(nf_ct_net(ct));
478                 return false;
479         }
480
481         nf_conntrack_ecache_work(nf_ct_net(ct));
482         nf_ct_delete_from_lists(ct);
483         nf_ct_put(ct);
484         return true;
485 }
486 EXPORT_SYMBOL_GPL(nf_ct_delete);
487
488 static inline bool
489 nf_ct_key_equal(struct nf_conntrack_tuple_hash *h,
490                 const struct nf_conntrack_tuple *tuple,
491                 const struct nf_conntrack_zone *zone,
492                 const struct net *net)
493 {
494         struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
495
496         /* A conntrack can be recreated with the equal tuple,
497          * so we need to check that the conntrack is confirmed
498          */
499         return nf_ct_tuple_equal(tuple, &h->tuple) &&
500                nf_ct_zone_equal(ct, zone, NF_CT_DIRECTION(h)) &&
501                nf_ct_is_confirmed(ct) &&
502                net_eq(net, nf_ct_net(ct));
503 }
504
505 /* caller must hold rcu readlock and none of the nf_conntrack_locks */
506 static void nf_ct_gc_expired(struct nf_conn *ct)
507 {
508         if (!atomic_inc_not_zero(&ct->ct_general.use))
509                 return;
510
511         if (nf_ct_should_gc(ct))
512                 nf_ct_kill(ct);
513
514         nf_ct_put(ct);
515 }
516
517 /*
518  * Warning :
519  * - Caller must take a reference on returned object
520  *   and recheck nf_ct_tuple_equal(tuple, &h->tuple)
521  */
522 static struct nf_conntrack_tuple_hash *
523 ____nf_conntrack_find(struct net *net, const struct nf_conntrack_zone *zone,
524                       const struct nf_conntrack_tuple *tuple, u32 hash)
525 {
526         struct nf_conntrack_tuple_hash *h;
527         struct hlist_nulls_head *ct_hash;
528         struct hlist_nulls_node *n;
529         unsigned int bucket, hsize;
530
531 begin:
532         nf_conntrack_get_ht(&ct_hash, &hsize);
533         bucket = reciprocal_scale(hash, hsize);
534
535         hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[bucket], hnnode) {
536                 struct nf_conn *ct;
537
538                 ct = nf_ct_tuplehash_to_ctrack(h);
539                 if (nf_ct_is_expired(ct)) {
540                         nf_ct_gc_expired(ct);
541                         continue;
542                 }
543
544                 if (nf_ct_is_dying(ct))
545                         continue;
546
547                 if (nf_ct_key_equal(h, tuple, zone, net))
548                         return h;
549         }
550         /*
551          * if the nulls value we got at the end of this lookup is
552          * not the expected one, we must restart lookup.
553          * We probably met an item that was moved to another chain.
554          */
555         if (get_nulls_value(n) != bucket) {
556                 NF_CT_STAT_INC_ATOMIC(net, search_restart);
557                 goto begin;
558         }
559
560         return NULL;
561 }
562
563 /* Find a connection corresponding to a tuple. */
564 static struct nf_conntrack_tuple_hash *
565 __nf_conntrack_find_get(struct net *net, const struct nf_conntrack_zone *zone,
566                         const struct nf_conntrack_tuple *tuple, u32 hash)
567 {
568         struct nf_conntrack_tuple_hash *h;
569         struct nf_conn *ct;
570
571         rcu_read_lock();
572 begin:
573         h = ____nf_conntrack_find(net, zone, tuple, hash);
574         if (h) {
575                 ct = nf_ct_tuplehash_to_ctrack(h);
576                 if (unlikely(nf_ct_is_dying(ct) ||
577                              !atomic_inc_not_zero(&ct->ct_general.use)))
578                         h = NULL;
579                 else {
580                         if (unlikely(!nf_ct_key_equal(h, tuple, zone, net))) {
581                                 nf_ct_put(ct);
582                                 goto begin;
583                         }
584                 }
585         }
586         rcu_read_unlock();
587
588         return h;
589 }
590
591 struct nf_conntrack_tuple_hash *
592 nf_conntrack_find_get(struct net *net, const struct nf_conntrack_zone *zone,
593                       const struct nf_conntrack_tuple *tuple)
594 {
595         return __nf_conntrack_find_get(net, zone, tuple,
596                                        hash_conntrack_raw(tuple, net));
597 }
598 EXPORT_SYMBOL_GPL(nf_conntrack_find_get);
599
600 static void __nf_conntrack_hash_insert(struct nf_conn *ct,
601                                        unsigned int hash,
602                                        unsigned int reply_hash)
603 {
604         hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
605                            &nf_conntrack_hash[hash]);
606         hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode,
607                            &nf_conntrack_hash[reply_hash]);
608 }
609
610 int
611 nf_conntrack_hash_check_insert(struct nf_conn *ct)
612 {
613         const struct nf_conntrack_zone *zone;
614         struct net *net = nf_ct_net(ct);
615         unsigned int hash, reply_hash;
616         struct nf_conntrack_tuple_hash *h;
617         struct hlist_nulls_node *n;
618         unsigned int sequence;
619
620         zone = nf_ct_zone(ct);
621
622         local_bh_disable();
623         do {
624                 sequence = read_seqcount_begin(&nf_conntrack_generation);
625                 hash = hash_conntrack(net,
626                                       &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
627                 reply_hash = hash_conntrack(net,
628                                            &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
629         } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
630
631         /* See if there's one in the list already, including reverse */
632         hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode)
633                 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
634                                     zone, net))
635                         goto out;
636
637         hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode)
638                 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
639                                     zone, net))
640                         goto out;
641
642         smp_wmb();
643         /* The caller holds a reference to this object */
644         atomic_set(&ct->ct_general.use, 2);
645         __nf_conntrack_hash_insert(ct, hash, reply_hash);
646         nf_conntrack_double_unlock(hash, reply_hash);
647         NF_CT_STAT_INC(net, insert);
648         local_bh_enable();
649         return 0;
650
651 out:
652         nf_conntrack_double_unlock(hash, reply_hash);
653         NF_CT_STAT_INC(net, insert_failed);
654         local_bh_enable();
655         return -EEXIST;
656 }
657 EXPORT_SYMBOL_GPL(nf_conntrack_hash_check_insert);
658
659 static inline void nf_ct_acct_update(struct nf_conn *ct,
660                                      enum ip_conntrack_info ctinfo,
661                                      unsigned int len)
662 {
663         struct nf_conn_acct *acct;
664
665         acct = nf_conn_acct_find(ct);
666         if (acct) {
667                 struct nf_conn_counter *counter = acct->counter;
668
669                 atomic64_inc(&counter[CTINFO2DIR(ctinfo)].packets);
670                 atomic64_add(len, &counter[CTINFO2DIR(ctinfo)].bytes);
671         }
672 }
673
674 static void nf_ct_acct_merge(struct nf_conn *ct, enum ip_conntrack_info ctinfo,
675                              const struct nf_conn *loser_ct)
676 {
677         struct nf_conn_acct *acct;
678
679         acct = nf_conn_acct_find(loser_ct);
680         if (acct) {
681                 struct nf_conn_counter *counter = acct->counter;
682                 unsigned int bytes;
683
684                 /* u32 should be fine since we must have seen one packet. */
685                 bytes = atomic64_read(&counter[CTINFO2DIR(ctinfo)].bytes);
686                 nf_ct_acct_update(ct, ctinfo, bytes);
687         }
688 }
689
690 /* Resolve race on insertion if this protocol allows this. */
691 static int nf_ct_resolve_clash(struct net *net, struct sk_buff *skb,
692                                enum ip_conntrack_info ctinfo,
693                                struct nf_conntrack_tuple_hash *h)
694 {
695         /* This is the conntrack entry already in hashes that won race. */
696         struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
697         const struct nf_conntrack_l4proto *l4proto;
698
699         l4proto = __nf_ct_l4proto_find(nf_ct_l3num(ct), nf_ct_protonum(ct));
700         if (l4proto->allow_clash &&
701             ((ct->status & IPS_NAT_DONE_MASK) == 0) &&
702             !nf_ct_is_dying(ct) &&
703             atomic_inc_not_zero(&ct->ct_general.use)) {
704                 enum ip_conntrack_info oldinfo;
705                 struct nf_conn *loser_ct = nf_ct_get(skb, &oldinfo);
706
707                 nf_ct_acct_merge(ct, ctinfo, loser_ct);
708                 nf_conntrack_put(&loser_ct->ct_general);
709                 nf_ct_set(skb, ct, oldinfo);
710                 return NF_ACCEPT;
711         }
712         NF_CT_STAT_INC(net, drop);
713         return NF_DROP;
714 }
715
716 /* Confirm a connection given skb; places it in hash table */
717 int
718 __nf_conntrack_confirm(struct sk_buff *skb)
719 {
720         const struct nf_conntrack_zone *zone;
721         unsigned int hash, reply_hash;
722         struct nf_conntrack_tuple_hash *h;
723         struct nf_conn *ct;
724         struct nf_conn_help *help;
725         struct nf_conn_tstamp *tstamp;
726         struct hlist_nulls_node *n;
727         enum ip_conntrack_info ctinfo;
728         struct net *net;
729         unsigned int sequence;
730         int ret = NF_DROP;
731
732         ct = nf_ct_get(skb, &ctinfo);
733         net = nf_ct_net(ct);
734
735         /* ipt_REJECT uses nf_conntrack_attach to attach related
736            ICMP/TCP RST packets in other direction.  Actual packet
737            which created connection will be IP_CT_NEW or for an
738            expected connection, IP_CT_RELATED. */
739         if (CTINFO2DIR(ctinfo) != IP_CT_DIR_ORIGINAL)
740                 return NF_ACCEPT;
741
742         zone = nf_ct_zone(ct);
743         local_bh_disable();
744
745         do {
746                 sequence = read_seqcount_begin(&nf_conntrack_generation);
747                 /* reuse the hash saved before */
748                 hash = *(unsigned long *)&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev;
749                 hash = scale_hash(hash);
750                 reply_hash = hash_conntrack(net,
751                                            &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
752
753         } while (nf_conntrack_double_lock(net, hash, reply_hash, sequence));
754
755         /* We're not in hash table, and we refuse to set up related
756          * connections for unconfirmed conns.  But packet copies and
757          * REJECT will give spurious warnings here.
758          */
759
760         /* No external references means no one else could have
761          * confirmed us.
762          */
763         WARN_ON(nf_ct_is_confirmed(ct));
764         pr_debug("Confirming conntrack %p\n", ct);
765         /* We have to check the DYING flag after unlink to prevent
766          * a race against nf_ct_get_next_corpse() possibly called from
767          * user context, else we insert an already 'dead' hash, blocking
768          * further use of that particular connection -JM.
769          */
770         nf_ct_del_from_dying_or_unconfirmed_list(ct);
771
772         if (unlikely(nf_ct_is_dying(ct))) {
773                 nf_ct_add_to_dying_list(ct);
774                 goto dying;
775         }
776
777         /* See if there's one in the list already, including reverse:
778            NAT could have grabbed it without realizing, since we're
779            not in the hash.  If there is, we lost race. */
780         hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[hash], hnnode)
781                 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
782                                     zone, net))
783                         goto out;
784
785         hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[reply_hash], hnnode)
786                 if (nf_ct_key_equal(h, &ct->tuplehash[IP_CT_DIR_REPLY].tuple,
787                                     zone, net))
788                         goto out;
789
790         /* Timer relative to confirmation time, not original
791            setting time, otherwise we'd get timer wrap in
792            weird delay cases. */
793         ct->timeout += nfct_time_stamp;
794         atomic_inc(&ct->ct_general.use);
795         ct->status |= IPS_CONFIRMED;
796
797         /* set conntrack timestamp, if enabled. */
798         tstamp = nf_conn_tstamp_find(ct);
799         if (tstamp) {
800                 if (skb->tstamp == 0)
801                         __net_timestamp(skb);
802
803                 tstamp->start = ktime_to_ns(skb->tstamp);
804         }
805         /* Since the lookup is lockless, hash insertion must be done after
806          * starting the timer and setting the CONFIRMED bit. The RCU barriers
807          * guarantee that no other CPU can find the conntrack before the above
808          * stores are visible.
809          */
810         __nf_conntrack_hash_insert(ct, hash, reply_hash);
811         nf_conntrack_double_unlock(hash, reply_hash);
812         local_bh_enable();
813
814         help = nfct_help(ct);
815         if (help && help->helper)
816                 nf_conntrack_event_cache(IPCT_HELPER, ct);
817
818         nf_conntrack_event_cache(master_ct(ct) ?
819                                  IPCT_RELATED : IPCT_NEW, ct);
820         return NF_ACCEPT;
821
822 out:
823         nf_ct_add_to_dying_list(ct);
824         ret = nf_ct_resolve_clash(net, skb, ctinfo, h);
825 dying:
826         nf_conntrack_double_unlock(hash, reply_hash);
827         NF_CT_STAT_INC(net, insert_failed);
828         local_bh_enable();
829         return ret;
830 }
831 EXPORT_SYMBOL_GPL(__nf_conntrack_confirm);
832
833 /* Returns true if a connection correspondings to the tuple (required
834    for NAT). */
835 int
836 nf_conntrack_tuple_taken(const struct nf_conntrack_tuple *tuple,
837                          const struct nf_conn *ignored_conntrack)
838 {
839         struct net *net = nf_ct_net(ignored_conntrack);
840         const struct nf_conntrack_zone *zone;
841         struct nf_conntrack_tuple_hash *h;
842         struct hlist_nulls_head *ct_hash;
843         unsigned int hash, hsize;
844         struct hlist_nulls_node *n;
845         struct nf_conn *ct;
846
847         zone = nf_ct_zone(ignored_conntrack);
848
849         rcu_read_lock();
850  begin:
851         nf_conntrack_get_ht(&ct_hash, &hsize);
852         hash = __hash_conntrack(net, tuple, hsize);
853
854         hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[hash], hnnode) {
855                 ct = nf_ct_tuplehash_to_ctrack(h);
856
857                 if (ct == ignored_conntrack)
858                         continue;
859
860                 if (nf_ct_is_expired(ct)) {
861                         nf_ct_gc_expired(ct);
862                         continue;
863                 }
864
865                 if (nf_ct_key_equal(h, tuple, zone, net)) {
866                         NF_CT_STAT_INC_ATOMIC(net, found);
867                         rcu_read_unlock();
868                         return 1;
869                 }
870         }
871
872         if (get_nulls_value(n) != hash) {
873                 NF_CT_STAT_INC_ATOMIC(net, search_restart);
874                 goto begin;
875         }
876
877         rcu_read_unlock();
878
879         return 0;
880 }
881 EXPORT_SYMBOL_GPL(nf_conntrack_tuple_taken);
882
883 #define NF_CT_EVICTION_RANGE    8
884
885 /* There's a small race here where we may free a just-assured
886    connection.  Too bad: we're in trouble anyway. */
887 static unsigned int early_drop_list(struct net *net,
888                                     struct hlist_nulls_head *head)
889 {
890         struct nf_conntrack_tuple_hash *h;
891         struct hlist_nulls_node *n;
892         unsigned int drops = 0;
893         struct nf_conn *tmp;
894
895         hlist_nulls_for_each_entry_rcu(h, n, head, hnnode) {
896                 tmp = nf_ct_tuplehash_to_ctrack(h);
897
898                 if (test_bit(IPS_OFFLOAD_BIT, &tmp->status))
899                         continue;
900
901                 if (nf_ct_is_expired(tmp)) {
902                         nf_ct_gc_expired(tmp);
903                         continue;
904                 }
905
906                 if (test_bit(IPS_ASSURED_BIT, &tmp->status) ||
907                     !net_eq(nf_ct_net(tmp), net) ||
908                     nf_ct_is_dying(tmp))
909                         continue;
910
911                 if (!atomic_inc_not_zero(&tmp->ct_general.use))
912                         continue;
913
914                 /* kill only if still in same netns -- might have moved due to
915                  * SLAB_TYPESAFE_BY_RCU rules.
916                  *
917                  * We steal the timer reference.  If that fails timer has
918                  * already fired or someone else deleted it. Just drop ref
919                  * and move to next entry.
920                  */
921                 if (net_eq(nf_ct_net(tmp), net) &&
922                     nf_ct_is_confirmed(tmp) &&
923                     nf_ct_delete(tmp, 0, 0))
924                         drops++;
925
926                 nf_ct_put(tmp);
927         }
928
929         return drops;
930 }
931
932 static noinline int early_drop(struct net *net, unsigned int _hash)
933 {
934         unsigned int i;
935
936         for (i = 0; i < NF_CT_EVICTION_RANGE; i++) {
937                 struct hlist_nulls_head *ct_hash;
938                 unsigned int hash, hsize, drops;
939
940                 rcu_read_lock();
941                 nf_conntrack_get_ht(&ct_hash, &hsize);
942                 hash = reciprocal_scale(_hash++, hsize);
943
944                 drops = early_drop_list(net, &ct_hash[hash]);
945                 rcu_read_unlock();
946
947                 if (drops) {
948                         NF_CT_STAT_ADD_ATOMIC(net, early_drop, drops);
949                         return true;
950                 }
951         }
952
953         return false;
954 }
955
956 static bool gc_worker_skip_ct(const struct nf_conn *ct)
957 {
958         return !nf_ct_is_confirmed(ct) || nf_ct_is_dying(ct);
959 }
960
961 static bool gc_worker_can_early_drop(const struct nf_conn *ct)
962 {
963         const struct nf_conntrack_l4proto *l4proto;
964
965         if (!test_bit(IPS_ASSURED_BIT, &ct->status))
966                 return true;
967
968         l4proto = __nf_ct_l4proto_find(nf_ct_l3num(ct), nf_ct_protonum(ct));
969         if (l4proto->can_early_drop && l4proto->can_early_drop(ct))
970                 return true;
971
972         return false;
973 }
974
975 #define DAY     (86400 * HZ)
976
977 /* Set an arbitrary timeout large enough not to ever expire, this save
978  * us a check for the IPS_OFFLOAD_BIT from the packet path via
979  * nf_ct_is_expired().
980  */
981 static void nf_ct_offload_timeout(struct nf_conn *ct)
982 {
983         if (nf_ct_expires(ct) < DAY / 2)
984                 ct->timeout = nfct_time_stamp + DAY;
985 }
986
987 static void gc_worker(struct work_struct *work)
988 {
989         unsigned int min_interval = max(HZ / GC_MAX_BUCKETS_DIV, 1u);
990         unsigned int i, goal, buckets = 0, expired_count = 0;
991         unsigned int nf_conntrack_max95 = 0;
992         struct conntrack_gc_work *gc_work;
993         unsigned int ratio, scanned = 0;
994         unsigned long next_run;
995
996         gc_work = container_of(work, struct conntrack_gc_work, dwork.work);
997
998         goal = nf_conntrack_htable_size / GC_MAX_BUCKETS_DIV;
999         i = gc_work->last_bucket;
1000         if (gc_work->early_drop)
1001                 nf_conntrack_max95 = nf_conntrack_max / 100u * 95u;
1002
1003         do {
1004                 struct nf_conntrack_tuple_hash *h;
1005                 struct hlist_nulls_head *ct_hash;
1006                 struct hlist_nulls_node *n;
1007                 unsigned int hashsz;
1008                 struct nf_conn *tmp;
1009
1010                 i++;
1011                 rcu_read_lock();
1012
1013                 nf_conntrack_get_ht(&ct_hash, &hashsz);
1014                 if (i >= hashsz)
1015                         i = 0;
1016
1017                 hlist_nulls_for_each_entry_rcu(h, n, &ct_hash[i], hnnode) {
1018                         struct net *net;
1019
1020                         tmp = nf_ct_tuplehash_to_ctrack(h);
1021
1022                         scanned++;
1023                         if (test_bit(IPS_OFFLOAD_BIT, &tmp->status)) {
1024                                 nf_ct_offload_timeout(tmp);
1025                                 continue;
1026                         }
1027
1028                         if (nf_ct_is_expired(tmp)) {
1029                                 nf_ct_gc_expired(tmp);
1030                                 expired_count++;
1031                                 continue;
1032                         }
1033
1034                         if (nf_conntrack_max95 == 0 || gc_worker_skip_ct(tmp))
1035                                 continue;
1036
1037                         net = nf_ct_net(tmp);
1038                         if (atomic_read(&net->ct.count) < nf_conntrack_max95)
1039                                 continue;
1040
1041                         /* need to take reference to avoid possible races */
1042                         if (!atomic_inc_not_zero(&tmp->ct_general.use))
1043                                 continue;
1044
1045                         if (gc_worker_skip_ct(tmp)) {
1046                                 nf_ct_put(tmp);
1047                                 continue;
1048                         }
1049
1050                         if (gc_worker_can_early_drop(tmp))
1051                                 nf_ct_kill(tmp);
1052
1053                         nf_ct_put(tmp);
1054                 }
1055
1056                 /* could check get_nulls_value() here and restart if ct
1057                  * was moved to another chain.  But given gc is best-effort
1058                  * we will just continue with next hash slot.
1059                  */
1060                 rcu_read_unlock();
1061                 cond_resched();
1062         } while (++buckets < goal);
1063
1064         if (gc_work->exiting)
1065                 return;
1066
1067         /*
1068          * Eviction will normally happen from the packet path, and not
1069          * from this gc worker.
1070          *
1071          * This worker is only here to reap expired entries when system went
1072          * idle after a busy period.
1073          *
1074          * The heuristics below are supposed to balance conflicting goals:
1075          *
1076          * 1. Minimize time until we notice a stale entry
1077          * 2. Maximize scan intervals to not waste cycles
1078          *
1079          * Normally, expire ratio will be close to 0.
1080          *
1081          * As soon as a sizeable fraction of the entries have expired
1082          * increase scan frequency.
1083          */
1084         ratio = scanned ? expired_count * 100 / scanned : 0;
1085         if (ratio > GC_EVICT_RATIO) {
1086                 gc_work->next_gc_run = min_interval;
1087         } else {
1088                 unsigned int max = GC_MAX_SCAN_JIFFIES / GC_MAX_BUCKETS_DIV;
1089
1090                 BUILD_BUG_ON((GC_MAX_SCAN_JIFFIES / GC_MAX_BUCKETS_DIV) == 0);
1091
1092                 gc_work->next_gc_run += min_interval;
1093                 if (gc_work->next_gc_run > max)
1094                         gc_work->next_gc_run = max;
1095         }
1096
1097         next_run = gc_work->next_gc_run;
1098         gc_work->last_bucket = i;
1099         gc_work->early_drop = false;
1100         queue_delayed_work(system_power_efficient_wq, &gc_work->dwork, next_run);
1101 }
1102
1103 static void conntrack_gc_work_init(struct conntrack_gc_work *gc_work)
1104 {
1105         INIT_DEFERRABLE_WORK(&gc_work->dwork, gc_worker);
1106         gc_work->next_gc_run = HZ;
1107         gc_work->exiting = false;
1108 }
1109
1110 static struct nf_conn *
1111 __nf_conntrack_alloc(struct net *net,
1112                      const struct nf_conntrack_zone *zone,
1113                      const struct nf_conntrack_tuple *orig,
1114                      const struct nf_conntrack_tuple *repl,
1115                      gfp_t gfp, u32 hash)
1116 {
1117         struct nf_conn *ct;
1118
1119         /* We don't want any race condition at early drop stage */
1120         atomic_inc(&net->ct.count);
1121
1122         if (nf_conntrack_max &&
1123             unlikely(atomic_read(&net->ct.count) > nf_conntrack_max)) {
1124                 if (!early_drop(net, hash)) {
1125                         if (!conntrack_gc_work.early_drop)
1126                                 conntrack_gc_work.early_drop = true;
1127                         atomic_dec(&net->ct.count);
1128                         net_warn_ratelimited("nf_conntrack: table full, dropping packet\n");
1129                         return ERR_PTR(-ENOMEM);
1130                 }
1131         }
1132
1133         /*
1134          * Do not use kmem_cache_zalloc(), as this cache uses
1135          * SLAB_TYPESAFE_BY_RCU.
1136          */
1137         ct = kmem_cache_alloc(nf_conntrack_cachep, gfp);
1138         if (ct == NULL)
1139                 goto out;
1140
1141         spin_lock_init(&ct->lock);
1142         ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple = *orig;
1143         ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode.pprev = NULL;
1144         ct->tuplehash[IP_CT_DIR_REPLY].tuple = *repl;
1145         /* save hash for reusing when confirming */
1146         *(unsigned long *)(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev) = hash;
1147         ct->status = 0;
1148         write_pnet(&ct->ct_net, net);
1149         memset(&ct->__nfct_init_offset[0], 0,
1150                offsetof(struct nf_conn, proto) -
1151                offsetof(struct nf_conn, __nfct_init_offset[0]));
1152
1153         nf_ct_zone_add(ct, zone);
1154
1155         /* Because we use RCU lookups, we set ct_general.use to zero before
1156          * this is inserted in any list.
1157          */
1158         atomic_set(&ct->ct_general.use, 0);
1159         return ct;
1160 out:
1161         atomic_dec(&net->ct.count);
1162         return ERR_PTR(-ENOMEM);
1163 }
1164
1165 struct nf_conn *nf_conntrack_alloc(struct net *net,
1166                                    const struct nf_conntrack_zone *zone,
1167                                    const struct nf_conntrack_tuple *orig,
1168                                    const struct nf_conntrack_tuple *repl,
1169                                    gfp_t gfp)
1170 {
1171         return __nf_conntrack_alloc(net, zone, orig, repl, gfp, 0);
1172 }
1173 EXPORT_SYMBOL_GPL(nf_conntrack_alloc);
1174
1175 void nf_conntrack_free(struct nf_conn *ct)
1176 {
1177         struct net *net = nf_ct_net(ct);
1178
1179         /* A freed object has refcnt == 0, that's
1180          * the golden rule for SLAB_TYPESAFE_BY_RCU
1181          */
1182         WARN_ON(atomic_read(&ct->ct_general.use) != 0);
1183
1184         nf_ct_ext_destroy(ct);
1185         nf_ct_ext_free(ct);
1186         kmem_cache_free(nf_conntrack_cachep, ct);
1187         smp_mb__before_atomic();
1188         atomic_dec(&net->ct.count);
1189 }
1190 EXPORT_SYMBOL_GPL(nf_conntrack_free);
1191
1192
1193 /* Allocate a new conntrack: we return -ENOMEM if classification
1194    failed due to stress.  Otherwise it really is unclassifiable. */
1195 static noinline struct nf_conntrack_tuple_hash *
1196 init_conntrack(struct net *net, struct nf_conn *tmpl,
1197                const struct nf_conntrack_tuple *tuple,
1198                const struct nf_conntrack_l3proto *l3proto,
1199                const struct nf_conntrack_l4proto *l4proto,
1200                struct sk_buff *skb,
1201                unsigned int dataoff, u32 hash)
1202 {
1203         struct nf_conn *ct;
1204         struct nf_conn_help *help;
1205         struct nf_conntrack_tuple repl_tuple;
1206         struct nf_conntrack_ecache *ecache;
1207         struct nf_conntrack_expect *exp = NULL;
1208         const struct nf_conntrack_zone *zone;
1209         struct nf_conn_timeout *timeout_ext;
1210         struct nf_conntrack_zone tmp;
1211         unsigned int *timeouts;
1212
1213         if (!nf_ct_invert_tuple(&repl_tuple, tuple, l3proto, l4proto)) {
1214                 pr_debug("Can't invert tuple.\n");
1215                 return NULL;
1216         }
1217
1218         zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1219         ct = __nf_conntrack_alloc(net, zone, tuple, &repl_tuple, GFP_ATOMIC,
1220                                   hash);
1221         if (IS_ERR(ct))
1222                 return (struct nf_conntrack_tuple_hash *)ct;
1223
1224         if (!nf_ct_add_synproxy(ct, tmpl)) {
1225                 nf_conntrack_free(ct);
1226                 return ERR_PTR(-ENOMEM);
1227         }
1228
1229         timeout_ext = tmpl ? nf_ct_timeout_find(tmpl) : NULL;
1230         if (timeout_ext) {
1231                 timeouts = nf_ct_timeout_data(timeout_ext);
1232                 if (unlikely(!timeouts))
1233                         timeouts = l4proto->get_timeouts(net);
1234         } else {
1235                 timeouts = l4proto->get_timeouts(net);
1236         }
1237
1238         if (!l4proto->new(ct, skb, dataoff, timeouts)) {
1239                 nf_conntrack_free(ct);
1240                 pr_debug("can't track with proto module\n");
1241                 return NULL;
1242         }
1243
1244         if (timeout_ext)
1245                 nf_ct_timeout_ext_add(ct, rcu_dereference(timeout_ext->timeout),
1246                                       GFP_ATOMIC);
1247
1248         nf_ct_acct_ext_add(ct, GFP_ATOMIC);
1249         nf_ct_tstamp_ext_add(ct, GFP_ATOMIC);
1250         nf_ct_labels_ext_add(ct);
1251
1252         ecache = tmpl ? nf_ct_ecache_find(tmpl) : NULL;
1253         nf_ct_ecache_ext_add(ct, ecache ? ecache->ctmask : 0,
1254                                  ecache ? ecache->expmask : 0,
1255                              GFP_ATOMIC);
1256
1257         local_bh_disable();
1258         if (net->ct.expect_count) {
1259                 spin_lock(&nf_conntrack_expect_lock);
1260                 exp = nf_ct_find_expectation(net, zone, tuple);
1261                 if (exp) {
1262                         pr_debug("expectation arrives ct=%p exp=%p\n",
1263                                  ct, exp);
1264                         /* Welcome, Mr. Bond.  We've been expecting you... */
1265                         __set_bit(IPS_EXPECTED_BIT, &ct->status);
1266                         /* exp->master safe, refcnt bumped in nf_ct_find_expectation */
1267                         ct->master = exp->master;
1268                         if (exp->helper) {
1269                                 help = nf_ct_helper_ext_add(ct, exp->helper,
1270                                                             GFP_ATOMIC);
1271                                 if (help)
1272                                         rcu_assign_pointer(help->helper, exp->helper);
1273                         }
1274
1275 #ifdef CONFIG_NF_CONNTRACK_MARK
1276                         ct->mark = exp->master->mark;
1277 #endif
1278 #ifdef CONFIG_NF_CONNTRACK_SECMARK
1279                         ct->secmark = exp->master->secmark;
1280 #endif
1281                         NF_CT_STAT_INC(net, expect_new);
1282                 }
1283                 spin_unlock(&nf_conntrack_expect_lock);
1284         }
1285         if (!exp)
1286                 __nf_ct_try_assign_helper(ct, tmpl, GFP_ATOMIC);
1287
1288         /* Now it is inserted into the unconfirmed list, bump refcount */
1289         nf_conntrack_get(&ct->ct_general);
1290         nf_ct_add_to_unconfirmed_list(ct);
1291
1292         local_bh_enable();
1293
1294         if (exp) {
1295                 if (exp->expectfn)
1296                         exp->expectfn(ct, exp);
1297                 nf_ct_expect_put(exp);
1298         }
1299
1300         return &ct->tuplehash[IP_CT_DIR_ORIGINAL];
1301 }
1302
1303 /* On success, returns 0, sets skb->_nfct | ctinfo */
1304 static int
1305 resolve_normal_ct(struct net *net, struct nf_conn *tmpl,
1306                   struct sk_buff *skb,
1307                   unsigned int dataoff,
1308                   u_int16_t l3num,
1309                   u_int8_t protonum,
1310                   const struct nf_conntrack_l3proto *l3proto,
1311                   const struct nf_conntrack_l4proto *l4proto)
1312 {
1313         const struct nf_conntrack_zone *zone;
1314         struct nf_conntrack_tuple tuple;
1315         struct nf_conntrack_tuple_hash *h;
1316         enum ip_conntrack_info ctinfo;
1317         struct nf_conntrack_zone tmp;
1318         struct nf_conn *ct;
1319         u32 hash;
1320
1321         if (!nf_ct_get_tuple(skb, skb_network_offset(skb),
1322                              dataoff, l3num, protonum, net, &tuple, l3proto,
1323                              l4proto)) {
1324                 pr_debug("Can't get tuple\n");
1325                 return 0;
1326         }
1327
1328         /* look for tuple match */
1329         zone = nf_ct_zone_tmpl(tmpl, skb, &tmp);
1330         hash = hash_conntrack_raw(&tuple, net);
1331         h = __nf_conntrack_find_get(net, zone, &tuple, hash);
1332         if (!h) {
1333                 h = init_conntrack(net, tmpl, &tuple, l3proto, l4proto,
1334                                    skb, dataoff, hash);
1335                 if (!h)
1336                         return 0;
1337                 if (IS_ERR(h))
1338                         return PTR_ERR(h);
1339         }
1340         ct = nf_ct_tuplehash_to_ctrack(h);
1341
1342         /* It exists; we have (non-exclusive) reference. */
1343         if (NF_CT_DIRECTION(h) == IP_CT_DIR_REPLY) {
1344                 ctinfo = IP_CT_ESTABLISHED_REPLY;
1345         } else {
1346                 /* Once we've had two way comms, always ESTABLISHED. */
1347                 if (test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) {
1348                         pr_debug("normal packet for %p\n", ct);
1349                         ctinfo = IP_CT_ESTABLISHED;
1350                 } else if (test_bit(IPS_EXPECTED_BIT, &ct->status)) {
1351                         pr_debug("related packet for %p\n", ct);
1352                         ctinfo = IP_CT_RELATED;
1353                 } else {
1354                         pr_debug("new packet for %p\n", ct);
1355                         ctinfo = IP_CT_NEW;
1356                 }
1357         }
1358         nf_ct_set(skb, ct, ctinfo);
1359         return 0;
1360 }
1361
1362 unsigned int
1363 nf_conntrack_in(struct net *net, u_int8_t pf, unsigned int hooknum,
1364                 struct sk_buff *skb)
1365 {
1366         const struct nf_conntrack_l3proto *l3proto;
1367         const struct nf_conntrack_l4proto *l4proto;
1368         struct nf_conn *ct, *tmpl;
1369         enum ip_conntrack_info ctinfo;
1370         unsigned int *timeouts;
1371         unsigned int dataoff;
1372         u_int8_t protonum;
1373         int ret;
1374
1375         tmpl = nf_ct_get(skb, &ctinfo);
1376         if (tmpl || ctinfo == IP_CT_UNTRACKED) {
1377                 /* Previously seen (loopback or untracked)?  Ignore. */
1378                 if ((tmpl && !nf_ct_is_template(tmpl)) ||
1379                      ctinfo == IP_CT_UNTRACKED) {
1380                         NF_CT_STAT_INC_ATOMIC(net, ignore);
1381                         return NF_ACCEPT;
1382                 }
1383                 skb->_nfct = 0;
1384         }
1385
1386         /* rcu_read_lock()ed by nf_hook_thresh */
1387         l3proto = __nf_ct_l3proto_find(pf);
1388         ret = l3proto->get_l4proto(skb, skb_network_offset(skb),
1389                                    &dataoff, &protonum);
1390         if (ret <= 0) {
1391                 pr_debug("not prepared to track yet or error occurred\n");
1392                 NF_CT_STAT_INC_ATOMIC(net, error);
1393                 NF_CT_STAT_INC_ATOMIC(net, invalid);
1394                 ret = -ret;
1395                 goto out;
1396         }
1397
1398         l4proto = __nf_ct_l4proto_find(pf, protonum);
1399
1400         /* It may be an special packet, error, unclean...
1401          * inverse of the return code tells to the netfilter
1402          * core what to do with the packet. */
1403         if (l4proto->error != NULL) {
1404                 ret = l4proto->error(net, tmpl, skb, dataoff, pf, hooknum);
1405                 if (ret <= 0) {
1406                         NF_CT_STAT_INC_ATOMIC(net, error);
1407                         NF_CT_STAT_INC_ATOMIC(net, invalid);
1408                         ret = -ret;
1409                         goto out;
1410                 }
1411                 /* ICMP[v6] protocol trackers may assign one conntrack. */
1412                 if (skb->_nfct)
1413                         goto out;
1414         }
1415 repeat:
1416         ret = resolve_normal_ct(net, tmpl, skb, dataoff, pf, protonum,
1417                                 l3proto, l4proto);
1418         if (ret < 0) {
1419                 /* Too stressed to deal. */
1420                 NF_CT_STAT_INC_ATOMIC(net, drop);
1421                 ret = NF_DROP;
1422                 goto out;
1423         }
1424
1425         ct = nf_ct_get(skb, &ctinfo);
1426         if (!ct) {
1427                 /* Not valid part of a connection */
1428                 NF_CT_STAT_INC_ATOMIC(net, invalid);
1429                 ret = NF_ACCEPT;
1430                 goto out;
1431         }
1432
1433         /* Decide what timeout policy we want to apply to this flow. */
1434         timeouts = nf_ct_timeout_lookup(net, ct, l4proto);
1435
1436         ret = l4proto->packet(ct, skb, dataoff, ctinfo, timeouts);
1437         if (ret <= 0) {
1438                 /* Invalid: inverse of the return code tells
1439                  * the netfilter core what to do */
1440                 pr_debug("nf_conntrack_in: Can't track with proto module\n");
1441                 nf_conntrack_put(&ct->ct_general);
1442                 skb->_nfct = 0;
1443                 NF_CT_STAT_INC_ATOMIC(net, invalid);
1444                 if (ret == -NF_DROP)
1445                         NF_CT_STAT_INC_ATOMIC(net, drop);
1446                 /* Special case: TCP tracker reports an attempt to reopen a
1447                  * closed/aborted connection. We have to go back and create a
1448                  * fresh conntrack.
1449                  */
1450                 if (ret == -NF_REPEAT)
1451                         goto repeat;
1452                 ret = -ret;
1453                 goto out;
1454         }
1455
1456         if (ctinfo == IP_CT_ESTABLISHED_REPLY &&
1457             !test_and_set_bit(IPS_SEEN_REPLY_BIT, &ct->status))
1458                 nf_conntrack_event_cache(IPCT_REPLY, ct);
1459 out:
1460         if (tmpl)
1461                 nf_ct_put(tmpl);
1462
1463         return ret;
1464 }
1465 EXPORT_SYMBOL_GPL(nf_conntrack_in);
1466
1467 bool nf_ct_invert_tuplepr(struct nf_conntrack_tuple *inverse,
1468                           const struct nf_conntrack_tuple *orig)
1469 {
1470         bool ret;
1471
1472         rcu_read_lock();
1473         ret = nf_ct_invert_tuple(inverse, orig,
1474                                  __nf_ct_l3proto_find(orig->src.l3num),
1475                                  __nf_ct_l4proto_find(orig->src.l3num,
1476                                                       orig->dst.protonum));
1477         rcu_read_unlock();
1478         return ret;
1479 }
1480 EXPORT_SYMBOL_GPL(nf_ct_invert_tuplepr);
1481
1482 /* Alter reply tuple (maybe alter helper).  This is for NAT, and is
1483    implicitly racy: see __nf_conntrack_confirm */
1484 void nf_conntrack_alter_reply(struct nf_conn *ct,
1485                               const struct nf_conntrack_tuple *newreply)
1486 {
1487         struct nf_conn_help *help = nfct_help(ct);
1488
1489         /* Should be unconfirmed, so not in hash table yet */
1490         WARN_ON(nf_ct_is_confirmed(ct));
1491
1492         pr_debug("Altering reply tuple of %p to ", ct);
1493         nf_ct_dump_tuple(newreply);
1494
1495         ct->tuplehash[IP_CT_DIR_REPLY].tuple = *newreply;
1496         if (ct->master || (help && !hlist_empty(&help->expectations)))
1497                 return;
1498
1499         rcu_read_lock();
1500         __nf_ct_try_assign_helper(ct, NULL, GFP_ATOMIC);
1501         rcu_read_unlock();
1502 }
1503 EXPORT_SYMBOL_GPL(nf_conntrack_alter_reply);
1504
1505 /* Refresh conntrack for this many jiffies and do accounting if do_acct is 1 */
1506 void __nf_ct_refresh_acct(struct nf_conn *ct,
1507                           enum ip_conntrack_info ctinfo,
1508                           const struct sk_buff *skb,
1509                           unsigned long extra_jiffies,
1510                           int do_acct)
1511 {
1512         WARN_ON(!skb);
1513
1514         /* Only update if this is not a fixed timeout */
1515         if (test_bit(IPS_FIXED_TIMEOUT_BIT, &ct->status))
1516                 goto acct;
1517
1518         /* If not in hash table, timer will not be active yet */
1519         if (nf_ct_is_confirmed(ct))
1520                 extra_jiffies += nfct_time_stamp;
1521
1522         ct->timeout = extra_jiffies;
1523 acct:
1524         if (do_acct)
1525                 nf_ct_acct_update(ct, ctinfo, skb->len);
1526 }
1527 EXPORT_SYMBOL_GPL(__nf_ct_refresh_acct);
1528
1529 bool nf_ct_kill_acct(struct nf_conn *ct,
1530                      enum ip_conntrack_info ctinfo,
1531                      const struct sk_buff *skb)
1532 {
1533         nf_ct_acct_update(ct, ctinfo, skb->len);
1534
1535         return nf_ct_delete(ct, 0, 0);
1536 }
1537 EXPORT_SYMBOL_GPL(nf_ct_kill_acct);
1538
1539 #if IS_ENABLED(CONFIG_NF_CT_NETLINK)
1540
1541 #include <linux/netfilter/nfnetlink.h>
1542 #include <linux/netfilter/nfnetlink_conntrack.h>
1543 #include <linux/mutex.h>
1544
1545 /* Generic function for tcp/udp/sctp/dccp and alike. This needs to be
1546  * in ip_conntrack_core, since we don't want the protocols to autoload
1547  * or depend on ctnetlink */
1548 int nf_ct_port_tuple_to_nlattr(struct sk_buff *skb,
1549                                const struct nf_conntrack_tuple *tuple)
1550 {
1551         if (nla_put_be16(skb, CTA_PROTO_SRC_PORT, tuple->src.u.tcp.port) ||
1552             nla_put_be16(skb, CTA_PROTO_DST_PORT, tuple->dst.u.tcp.port))
1553                 goto nla_put_failure;
1554         return 0;
1555
1556 nla_put_failure:
1557         return -1;
1558 }
1559 EXPORT_SYMBOL_GPL(nf_ct_port_tuple_to_nlattr);
1560
1561 const struct nla_policy nf_ct_port_nla_policy[CTA_PROTO_MAX+1] = {
1562         [CTA_PROTO_SRC_PORT]  = { .type = NLA_U16 },
1563         [CTA_PROTO_DST_PORT]  = { .type = NLA_U16 },
1564 };
1565 EXPORT_SYMBOL_GPL(nf_ct_port_nla_policy);
1566
1567 int nf_ct_port_nlattr_to_tuple(struct nlattr *tb[],
1568                                struct nf_conntrack_tuple *t)
1569 {
1570         if (!tb[CTA_PROTO_SRC_PORT] || !tb[CTA_PROTO_DST_PORT])
1571                 return -EINVAL;
1572
1573         t->src.u.tcp.port = nla_get_be16(tb[CTA_PROTO_SRC_PORT]);
1574         t->dst.u.tcp.port = nla_get_be16(tb[CTA_PROTO_DST_PORT]);
1575
1576         return 0;
1577 }
1578 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_to_tuple);
1579
1580 unsigned int nf_ct_port_nlattr_tuple_size(void)
1581 {
1582         static unsigned int size __read_mostly;
1583
1584         if (!size)
1585                 size = nla_policy_len(nf_ct_port_nla_policy, CTA_PROTO_MAX + 1);
1586
1587         return size;
1588 }
1589 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_tuple_size);
1590 #endif
1591
1592 /* Used by ipt_REJECT and ip6t_REJECT. */
1593 static void nf_conntrack_attach(struct sk_buff *nskb, const struct sk_buff *skb)
1594 {
1595         struct nf_conn *ct;
1596         enum ip_conntrack_info ctinfo;
1597
1598         /* This ICMP is in reverse direction to the packet which caused it */
1599         ct = nf_ct_get(skb, &ctinfo);
1600         if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL)
1601                 ctinfo = IP_CT_RELATED_REPLY;
1602         else
1603                 ctinfo = IP_CT_RELATED;
1604
1605         /* Attach to new skbuff, and increment count */
1606         nf_ct_set(nskb, ct, ctinfo);
1607         nf_conntrack_get(skb_nfct(nskb));
1608 }
1609
1610 static int nf_conntrack_update(struct net *net, struct sk_buff *skb)
1611 {
1612         const struct nf_conntrack_l3proto *l3proto;
1613         const struct nf_conntrack_l4proto *l4proto;
1614         struct nf_conntrack_tuple_hash *h;
1615         struct nf_conntrack_tuple tuple;
1616         enum ip_conntrack_info ctinfo;
1617         struct nf_nat_hook *nat_hook;
1618         unsigned int dataoff, status;
1619         struct nf_conn *ct;
1620         u16 l3num;
1621         u8 l4num;
1622
1623         ct = nf_ct_get(skb, &ctinfo);
1624         if (!ct || nf_ct_is_confirmed(ct))
1625                 return 0;
1626
1627         l3num = nf_ct_l3num(ct);
1628         l3proto = nf_ct_l3proto_find_get(l3num);
1629
1630         if (l3proto->get_l4proto(skb, skb_network_offset(skb), &dataoff,
1631                                  &l4num) <= 0)
1632                 return -1;
1633
1634         l4proto = nf_ct_l4proto_find_get(l3num, l4num);
1635
1636         if (!nf_ct_get_tuple(skb, skb_network_offset(skb), dataoff, l3num,
1637                              l4num, net, &tuple, l3proto, l4proto))
1638                 return -1;
1639
1640         if (ct->status & IPS_SRC_NAT) {
1641                 memcpy(tuple.src.u3.all,
1642                        ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u3.all,
1643                        sizeof(tuple.src.u3.all));
1644                 tuple.src.u.all =
1645                         ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.src.u.all;
1646         }
1647
1648         if (ct->status & IPS_DST_NAT) {
1649                 memcpy(tuple.dst.u3.all,
1650                        ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.u3.all,
1651                        sizeof(tuple.dst.u3.all));
1652                 tuple.dst.u.all =
1653                         ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple.dst.u.all;
1654         }
1655
1656         h = nf_conntrack_find_get(net, nf_ct_zone(ct), &tuple);
1657         if (!h)
1658                 return 0;
1659
1660         /* Store status bits of the conntrack that is clashing to re-do NAT
1661          * mangling according to what it has been done already to this packet.
1662          */
1663         status = ct->status;
1664
1665         nf_ct_put(ct);
1666         ct = nf_ct_tuplehash_to_ctrack(h);
1667         nf_ct_set(skb, ct, ctinfo);
1668
1669         nat_hook = rcu_dereference(nf_nat_hook);
1670         if (!nat_hook)
1671                 return 0;
1672
1673         if (status & IPS_SRC_NAT &&
1674             nat_hook->manip_pkt(skb, ct, NF_NAT_MANIP_SRC,
1675                                 IP_CT_DIR_ORIGINAL) == NF_DROP)
1676                 return -1;
1677
1678         if (status & IPS_DST_NAT &&
1679             nat_hook->manip_pkt(skb, ct, NF_NAT_MANIP_DST,
1680                                 IP_CT_DIR_ORIGINAL) == NF_DROP)
1681                 return -1;
1682
1683         return 0;
1684 }
1685
1686 static bool nf_conntrack_get_tuple_skb(struct nf_conntrack_tuple *dst_tuple,
1687                                        const struct sk_buff *skb)
1688 {
1689         const struct nf_conntrack_tuple *src_tuple;
1690         const struct nf_conntrack_tuple_hash *hash;
1691         struct nf_conntrack_tuple srctuple;
1692         enum ip_conntrack_info ctinfo;
1693         struct nf_conn *ct;
1694
1695         ct = nf_ct_get(skb, &ctinfo);
1696         if (ct) {
1697                 src_tuple = nf_ct_tuple(ct, CTINFO2DIR(ctinfo));
1698                 memcpy(dst_tuple, src_tuple, sizeof(*dst_tuple));
1699                 return true;
1700         }
1701
1702         if (!nf_ct_get_tuplepr(skb, skb_network_offset(skb),
1703                                NFPROTO_IPV4, dev_net(skb->dev),
1704                                &srctuple))
1705                 return false;
1706
1707         hash = nf_conntrack_find_get(dev_net(skb->dev),
1708                                      &nf_ct_zone_dflt,
1709                                      &srctuple);
1710         if (!hash)
1711                 return false;
1712
1713         ct = nf_ct_tuplehash_to_ctrack(hash);
1714         src_tuple = nf_ct_tuple(ct, !hash->tuple.dst.dir);
1715         memcpy(dst_tuple, src_tuple, sizeof(*dst_tuple));
1716         nf_ct_put(ct);
1717
1718         return true;
1719 }
1720
1721 /* Bring out ya dead! */
1722 static struct nf_conn *
1723 get_next_corpse(int (*iter)(struct nf_conn *i, void *data),
1724                 void *data, unsigned int *bucket)
1725 {
1726         struct nf_conntrack_tuple_hash *h;
1727         struct nf_conn *ct;
1728         struct hlist_nulls_node *n;
1729         spinlock_t *lockp;
1730
1731         for (; *bucket < nf_conntrack_htable_size; (*bucket)++) {
1732                 lockp = &nf_conntrack_locks[*bucket % CONNTRACK_LOCKS];
1733                 local_bh_disable();
1734                 nf_conntrack_lock(lockp);
1735                 if (*bucket < nf_conntrack_htable_size) {
1736                         hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[*bucket], hnnode) {
1737                                 if (NF_CT_DIRECTION(h) != IP_CT_DIR_ORIGINAL)
1738                                         continue;
1739                                 ct = nf_ct_tuplehash_to_ctrack(h);
1740                                 if (iter(ct, data))
1741                                         goto found;
1742                         }
1743                 }
1744                 spin_unlock(lockp);
1745                 local_bh_enable();
1746                 cond_resched();
1747         }
1748
1749         return NULL;
1750 found:
1751         atomic_inc(&ct->ct_general.use);
1752         spin_unlock(lockp);
1753         local_bh_enable();
1754         return ct;
1755 }
1756
1757 static void nf_ct_iterate_cleanup(int (*iter)(struct nf_conn *i, void *data),
1758                                   void *data, u32 portid, int report)
1759 {
1760         unsigned int bucket = 0, sequence;
1761         struct nf_conn *ct;
1762
1763         might_sleep();
1764
1765         for (;;) {
1766                 sequence = read_seqcount_begin(&nf_conntrack_generation);
1767
1768                 while ((ct = get_next_corpse(iter, data, &bucket)) != NULL) {
1769                         /* Time to push up daises... */
1770
1771                         nf_ct_delete(ct, portid, report);
1772                         nf_ct_put(ct);
1773                         cond_resched();
1774                 }
1775
1776                 if (!read_seqcount_retry(&nf_conntrack_generation, sequence))
1777                         break;
1778                 bucket = 0;
1779         }
1780 }
1781
1782 struct iter_data {
1783         int (*iter)(struct nf_conn *i, void *data);
1784         void *data;
1785         struct net *net;
1786 };
1787
1788 static int iter_net_only(struct nf_conn *i, void *data)
1789 {
1790         struct iter_data *d = data;
1791
1792         if (!net_eq(d->net, nf_ct_net(i)))
1793                 return 0;
1794
1795         return d->iter(i, d->data);
1796 }
1797
1798 static void
1799 __nf_ct_unconfirmed_destroy(struct net *net)
1800 {
1801         int cpu;
1802
1803         for_each_possible_cpu(cpu) {
1804                 struct nf_conntrack_tuple_hash *h;
1805                 struct hlist_nulls_node *n;
1806                 struct ct_pcpu *pcpu;
1807
1808                 pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
1809
1810                 spin_lock_bh(&pcpu->lock);
1811                 hlist_nulls_for_each_entry(h, n, &pcpu->unconfirmed, hnnode) {
1812                         struct nf_conn *ct;
1813
1814                         ct = nf_ct_tuplehash_to_ctrack(h);
1815
1816                         /* we cannot call iter() on unconfirmed list, the
1817                          * owning cpu can reallocate ct->ext at any time.
1818                          */
1819                         set_bit(IPS_DYING_BIT, &ct->status);
1820                 }
1821                 spin_unlock_bh(&pcpu->lock);
1822                 cond_resched();
1823         }
1824 }
1825
1826 void nf_ct_unconfirmed_destroy(struct net *net)
1827 {
1828         might_sleep();
1829
1830         if (atomic_read(&net->ct.count) > 0) {
1831                 __nf_ct_unconfirmed_destroy(net);
1832                 nf_queue_nf_hook_drop(net);
1833                 synchronize_net();
1834         }
1835 }
1836 EXPORT_SYMBOL_GPL(nf_ct_unconfirmed_destroy);
1837
1838 void nf_ct_iterate_cleanup_net(struct net *net,
1839                                int (*iter)(struct nf_conn *i, void *data),
1840                                void *data, u32 portid, int report)
1841 {
1842         struct iter_data d;
1843
1844         might_sleep();
1845
1846         if (atomic_read(&net->ct.count) == 0)
1847                 return;
1848
1849         d.iter = iter;
1850         d.data = data;
1851         d.net = net;
1852
1853         nf_ct_iterate_cleanup(iter_net_only, &d, portid, report);
1854 }
1855 EXPORT_SYMBOL_GPL(nf_ct_iterate_cleanup_net);
1856
1857 /**
1858  * nf_ct_iterate_destroy - destroy unconfirmed conntracks and iterate table
1859  * @iter: callback to invoke for each conntrack
1860  * @data: data to pass to @iter
1861  *
1862  * Like nf_ct_iterate_cleanup, but first marks conntracks on the
1863  * unconfirmed list as dying (so they will not be inserted into
1864  * main table).
1865  *
1866  * Can only be called in module exit path.
1867  */
1868 void
1869 nf_ct_iterate_destroy(int (*iter)(struct nf_conn *i, void *data), void *data)
1870 {
1871         struct net *net;
1872
1873         down_read(&net_rwsem);
1874         for_each_net(net) {
1875                 if (atomic_read(&net->ct.count) == 0)
1876                         continue;
1877                 __nf_ct_unconfirmed_destroy(net);
1878                 nf_queue_nf_hook_drop(net);
1879         }
1880         up_read(&net_rwsem);
1881
1882         /* Need to wait for netns cleanup worker to finish, if its
1883          * running -- it might have deleted a net namespace from
1884          * the global list, so our __nf_ct_unconfirmed_destroy() might
1885          * not have affected all namespaces.
1886          */
1887         net_ns_barrier();
1888
1889         /* a conntrack could have been unlinked from unconfirmed list
1890          * before we grabbed pcpu lock in __nf_ct_unconfirmed_destroy().
1891          * This makes sure its inserted into conntrack table.
1892          */
1893         synchronize_net();
1894
1895         nf_ct_iterate_cleanup(iter, data, 0, 0);
1896 }
1897 EXPORT_SYMBOL_GPL(nf_ct_iterate_destroy);
1898
1899 static int kill_all(struct nf_conn *i, void *data)
1900 {
1901         return net_eq(nf_ct_net(i), data);
1902 }
1903
1904 void nf_ct_free_hashtable(void *hash, unsigned int size)
1905 {
1906         if (is_vmalloc_addr(hash))
1907                 vfree(hash);
1908         else
1909                 free_pages((unsigned long)hash,
1910                            get_order(sizeof(struct hlist_head) * size));
1911 }
1912 EXPORT_SYMBOL_GPL(nf_ct_free_hashtable);
1913
1914 void nf_conntrack_cleanup_start(void)
1915 {
1916         conntrack_gc_work.exiting = true;
1917         RCU_INIT_POINTER(ip_ct_attach, NULL);
1918 }
1919
1920 void nf_conntrack_cleanup_end(void)
1921 {
1922         RCU_INIT_POINTER(nf_ct_hook, NULL);
1923         cancel_delayed_work_sync(&conntrack_gc_work.dwork);
1924         nf_ct_free_hashtable(nf_conntrack_hash, nf_conntrack_htable_size);
1925
1926         nf_conntrack_proto_fini();
1927         nf_conntrack_seqadj_fini();
1928         nf_conntrack_labels_fini();
1929         nf_conntrack_helper_fini();
1930         nf_conntrack_timeout_fini();
1931         nf_conntrack_ecache_fini();
1932         nf_conntrack_tstamp_fini();
1933         nf_conntrack_acct_fini();
1934         nf_conntrack_expect_fini();
1935
1936         kmem_cache_destroy(nf_conntrack_cachep);
1937 }
1938
1939 /*
1940  * Mishearing the voices in his head, our hero wonders how he's
1941  * supposed to kill the mall.
1942  */
1943 void nf_conntrack_cleanup_net(struct net *net)
1944 {
1945         LIST_HEAD(single);
1946
1947         list_add(&net->exit_list, &single);
1948         nf_conntrack_cleanup_net_list(&single);
1949 }
1950
1951 void nf_conntrack_cleanup_net_list(struct list_head *net_exit_list)
1952 {
1953         int busy;
1954         struct net *net;
1955
1956         /*
1957          * This makes sure all current packets have passed through
1958          *  netfilter framework.  Roll on, two-stage module
1959          *  delete...
1960          */
1961         synchronize_net();
1962 i_see_dead_people:
1963         busy = 0;
1964         list_for_each_entry(net, net_exit_list, exit_list) {
1965                 nf_ct_iterate_cleanup(kill_all, net, 0, 0);
1966                 if (atomic_read(&net->ct.count) != 0)
1967                         busy = 1;
1968         }
1969         if (busy) {
1970                 schedule();
1971                 goto i_see_dead_people;
1972         }
1973
1974         list_for_each_entry(net, net_exit_list, exit_list) {
1975                 nf_conntrack_proto_pernet_fini(net);
1976                 nf_conntrack_helper_pernet_fini(net);
1977                 nf_conntrack_ecache_pernet_fini(net);
1978                 nf_conntrack_tstamp_pernet_fini(net);
1979                 nf_conntrack_acct_pernet_fini(net);
1980                 nf_conntrack_expect_pernet_fini(net);
1981                 free_percpu(net->ct.stat);
1982                 free_percpu(net->ct.pcpu_lists);
1983         }
1984 }
1985
1986 void *nf_ct_alloc_hashtable(unsigned int *sizep, int nulls)
1987 {
1988         struct hlist_nulls_head *hash;
1989         unsigned int nr_slots, i;
1990         size_t sz;
1991
1992         if (*sizep > (UINT_MAX / sizeof(struct hlist_nulls_head)))
1993                 return NULL;
1994
1995         BUILD_BUG_ON(sizeof(struct hlist_nulls_head) != sizeof(struct hlist_head));
1996         nr_slots = *sizep = roundup(*sizep, PAGE_SIZE / sizeof(struct hlist_nulls_head));
1997
1998         if (nr_slots > (UINT_MAX / sizeof(struct hlist_nulls_head)))
1999                 return NULL;
2000
2001         sz = nr_slots * sizeof(struct hlist_nulls_head);
2002         hash = (void *)__get_free_pages(GFP_KERNEL | __GFP_NOWARN | __GFP_ZERO,
2003                                         get_order(sz));
2004         if (!hash)
2005                 hash = vzalloc(sz);
2006
2007         if (hash && nulls)
2008                 for (i = 0; i < nr_slots; i++)
2009                         INIT_HLIST_NULLS_HEAD(&hash[i], i);
2010
2011         return hash;
2012 }
2013 EXPORT_SYMBOL_GPL(nf_ct_alloc_hashtable);
2014
2015 int nf_conntrack_hash_resize(unsigned int hashsize)
2016 {
2017         int i, bucket;
2018         unsigned int old_size;
2019         struct hlist_nulls_head *hash, *old_hash;
2020         struct nf_conntrack_tuple_hash *h;
2021         struct nf_conn *ct;
2022
2023         if (!hashsize)
2024                 return -EINVAL;
2025
2026         hash = nf_ct_alloc_hashtable(&hashsize, 1);
2027         if (!hash)
2028                 return -ENOMEM;
2029
2030         old_size = nf_conntrack_htable_size;
2031         if (old_size == hashsize) {
2032                 nf_ct_free_hashtable(hash, hashsize);
2033                 return 0;
2034         }
2035
2036         local_bh_disable();
2037         nf_conntrack_all_lock();
2038         write_seqcount_begin(&nf_conntrack_generation);
2039
2040         /* Lookups in the old hash might happen in parallel, which means we
2041          * might get false negatives during connection lookup. New connections
2042          * created because of a false negative won't make it into the hash
2043          * though since that required taking the locks.
2044          */
2045
2046         for (i = 0; i < nf_conntrack_htable_size; i++) {
2047                 while (!hlist_nulls_empty(&nf_conntrack_hash[i])) {
2048                         h = hlist_nulls_entry(nf_conntrack_hash[i].first,
2049                                               struct nf_conntrack_tuple_hash, hnnode);
2050                         ct = nf_ct_tuplehash_to_ctrack(h);
2051                         hlist_nulls_del_rcu(&h->hnnode);
2052                         bucket = __hash_conntrack(nf_ct_net(ct),
2053                                                   &h->tuple, hashsize);
2054                         hlist_nulls_add_head_rcu(&h->hnnode, &hash[bucket]);
2055                 }
2056         }
2057         old_size = nf_conntrack_htable_size;
2058         old_hash = nf_conntrack_hash;
2059
2060         nf_conntrack_hash = hash;
2061         nf_conntrack_htable_size = hashsize;
2062
2063         write_seqcount_end(&nf_conntrack_generation);
2064         nf_conntrack_all_unlock();
2065         local_bh_enable();
2066
2067         synchronize_net();
2068         nf_ct_free_hashtable(old_hash, old_size);
2069         return 0;
2070 }
2071
2072 int nf_conntrack_set_hashsize(const char *val, const struct kernel_param *kp)
2073 {
2074         unsigned int hashsize;
2075         int rc;
2076
2077         if (current->nsproxy->net_ns != &init_net)
2078                 return -EOPNOTSUPP;
2079
2080         /* On boot, we can set this without any fancy locking. */
2081         if (!nf_conntrack_htable_size)
2082                 return param_set_uint(val, kp);
2083
2084         rc = kstrtouint(val, 0, &hashsize);
2085         if (rc)
2086                 return rc;
2087
2088         return nf_conntrack_hash_resize(hashsize);
2089 }
2090 EXPORT_SYMBOL_GPL(nf_conntrack_set_hashsize);
2091
2092 module_param_call(hashsize, nf_conntrack_set_hashsize, param_get_uint,
2093                   &nf_conntrack_htable_size, 0600);
2094
2095 static __always_inline unsigned int total_extension_size(void)
2096 {
2097         /* remember to add new extensions below */
2098         BUILD_BUG_ON(NF_CT_EXT_NUM > 9);
2099
2100         return sizeof(struct nf_ct_ext) +
2101                sizeof(struct nf_conn_help)
2102 #if IS_ENABLED(CONFIG_NF_NAT)
2103                 + sizeof(struct nf_conn_nat)
2104 #endif
2105                 + sizeof(struct nf_conn_seqadj)
2106                 + sizeof(struct nf_conn_acct)
2107 #ifdef CONFIG_NF_CONNTRACK_EVENTS
2108                 + sizeof(struct nf_conntrack_ecache)
2109 #endif
2110 #ifdef CONFIG_NF_CONNTRACK_TIMESTAMP
2111                 + sizeof(struct nf_conn_tstamp)
2112 #endif
2113 #ifdef CONFIG_NF_CONNTRACK_TIMEOUT
2114                 + sizeof(struct nf_conn_timeout)
2115 #endif
2116 #ifdef CONFIG_NF_CONNTRACK_LABELS
2117                 + sizeof(struct nf_conn_labels)
2118 #endif
2119 #if IS_ENABLED(CONFIG_NETFILTER_SYNPROXY)
2120                 + sizeof(struct nf_conn_synproxy)
2121 #endif
2122         ;
2123 };
2124
2125 int nf_conntrack_init_start(void)
2126 {
2127         int max_factor = 8;
2128         int ret = -ENOMEM;
2129         int i;
2130
2131         /* struct nf_ct_ext uses u8 to store offsets/size */
2132         BUILD_BUG_ON(total_extension_size() > 255u);
2133
2134         seqcount_init(&nf_conntrack_generation);
2135
2136         for (i = 0; i < CONNTRACK_LOCKS; i++)
2137                 spin_lock_init(&nf_conntrack_locks[i]);
2138
2139         if (!nf_conntrack_htable_size) {
2140                 /* Idea from tcp.c: use 1/16384 of memory.
2141                  * On i386: 32MB machine has 512 buckets.
2142                  * >= 1GB machines have 16384 buckets.
2143                  * >= 4GB machines have 65536 buckets.
2144                  */
2145                 nf_conntrack_htable_size
2146                         = (((totalram_pages << PAGE_SHIFT) / 16384)
2147                            / sizeof(struct hlist_head));
2148                 if (totalram_pages > (4 * (1024 * 1024 * 1024 / PAGE_SIZE)))
2149                         nf_conntrack_htable_size = 65536;
2150                 else if (totalram_pages > (1024 * 1024 * 1024 / PAGE_SIZE))
2151                         nf_conntrack_htable_size = 16384;
2152                 if (nf_conntrack_htable_size < 32)
2153                         nf_conntrack_htable_size = 32;
2154
2155                 /* Use a max. factor of four by default to get the same max as
2156                  * with the old struct list_heads. When a table size is given
2157                  * we use the old value of 8 to avoid reducing the max.
2158                  * entries. */
2159                 max_factor = 4;
2160         }
2161
2162         nf_conntrack_hash = nf_ct_alloc_hashtable(&nf_conntrack_htable_size, 1);
2163         if (!nf_conntrack_hash)
2164                 return -ENOMEM;
2165
2166         nf_conntrack_max = max_factor * nf_conntrack_htable_size;
2167
2168         nf_conntrack_cachep = kmem_cache_create("nf_conntrack",
2169                                                 sizeof(struct nf_conn),
2170                                                 NFCT_INFOMASK + 1,
2171                                                 SLAB_TYPESAFE_BY_RCU | SLAB_HWCACHE_ALIGN, NULL);
2172         if (!nf_conntrack_cachep)
2173                 goto err_cachep;
2174
2175         ret = nf_conntrack_expect_init();
2176         if (ret < 0)
2177                 goto err_expect;
2178
2179         ret = nf_conntrack_acct_init();
2180         if (ret < 0)
2181                 goto err_acct;
2182
2183         ret = nf_conntrack_tstamp_init();
2184         if (ret < 0)
2185                 goto err_tstamp;
2186
2187         ret = nf_conntrack_ecache_init();
2188         if (ret < 0)
2189                 goto err_ecache;
2190
2191         ret = nf_conntrack_timeout_init();
2192         if (ret < 0)
2193                 goto err_timeout;
2194
2195         ret = nf_conntrack_helper_init();
2196         if (ret < 0)
2197                 goto err_helper;
2198
2199         ret = nf_conntrack_labels_init();
2200         if (ret < 0)
2201                 goto err_labels;
2202
2203         ret = nf_conntrack_seqadj_init();
2204         if (ret < 0)
2205                 goto err_seqadj;
2206
2207         ret = nf_conntrack_proto_init();
2208         if (ret < 0)
2209                 goto err_proto;
2210
2211         conntrack_gc_work_init(&conntrack_gc_work);
2212         queue_delayed_work(system_power_efficient_wq, &conntrack_gc_work.dwork, HZ);
2213
2214         return 0;
2215
2216 err_proto:
2217         nf_conntrack_seqadj_fini();
2218 err_seqadj:
2219         nf_conntrack_labels_fini();
2220 err_labels:
2221         nf_conntrack_helper_fini();
2222 err_helper:
2223         nf_conntrack_timeout_fini();
2224 err_timeout:
2225         nf_conntrack_ecache_fini();
2226 err_ecache:
2227         nf_conntrack_tstamp_fini();
2228 err_tstamp:
2229         nf_conntrack_acct_fini();
2230 err_acct:
2231         nf_conntrack_expect_fini();
2232 err_expect:
2233         kmem_cache_destroy(nf_conntrack_cachep);
2234 err_cachep:
2235         nf_ct_free_hashtable(nf_conntrack_hash, nf_conntrack_htable_size);
2236         return ret;
2237 }
2238
2239 static struct nf_ct_hook nf_conntrack_hook = {
2240         .update         = nf_conntrack_update,
2241         .destroy        = destroy_conntrack,
2242         .get_tuple_skb  = nf_conntrack_get_tuple_skb,
2243 };
2244
2245 void nf_conntrack_init_end(void)
2246 {
2247         /* For use by REJECT target */
2248         RCU_INIT_POINTER(ip_ct_attach, nf_conntrack_attach);
2249         RCU_INIT_POINTER(nf_ct_hook, &nf_conntrack_hook);
2250 }
2251
2252 /*
2253  * We need to use special "null" values, not used in hash table
2254  */
2255 #define UNCONFIRMED_NULLS_VAL   ((1<<30)+0)
2256 #define DYING_NULLS_VAL         ((1<<30)+1)
2257 #define TEMPLATE_NULLS_VAL      ((1<<30)+2)
2258
2259 int nf_conntrack_init_net(struct net *net)
2260 {
2261         int ret = -ENOMEM;
2262         int cpu;
2263
2264         BUILD_BUG_ON(IP_CT_UNTRACKED == IP_CT_NUMBER);
2265         atomic_set(&net->ct.count, 0);
2266
2267         net->ct.pcpu_lists = alloc_percpu(struct ct_pcpu);
2268         if (!net->ct.pcpu_lists)
2269                 goto err_stat;
2270
2271         for_each_possible_cpu(cpu) {
2272                 struct ct_pcpu *pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
2273
2274                 spin_lock_init(&pcpu->lock);
2275                 INIT_HLIST_NULLS_HEAD(&pcpu->unconfirmed, UNCONFIRMED_NULLS_VAL);
2276                 INIT_HLIST_NULLS_HEAD(&pcpu->dying, DYING_NULLS_VAL);
2277         }
2278
2279         net->ct.stat = alloc_percpu(struct ip_conntrack_stat);
2280         if (!net->ct.stat)
2281                 goto err_pcpu_lists;
2282
2283         ret = nf_conntrack_expect_pernet_init(net);
2284         if (ret < 0)
2285                 goto err_expect;
2286         ret = nf_conntrack_acct_pernet_init(net);
2287         if (ret < 0)
2288                 goto err_acct;
2289         ret = nf_conntrack_tstamp_pernet_init(net);
2290         if (ret < 0)
2291                 goto err_tstamp;
2292         ret = nf_conntrack_ecache_pernet_init(net);
2293         if (ret < 0)
2294                 goto err_ecache;
2295         ret = nf_conntrack_helper_pernet_init(net);
2296         if (ret < 0)
2297                 goto err_helper;
2298         ret = nf_conntrack_proto_pernet_init(net);
2299         if (ret < 0)
2300                 goto err_proto;
2301         return 0;
2302
2303 err_proto:
2304         nf_conntrack_helper_pernet_fini(net);
2305 err_helper:
2306         nf_conntrack_ecache_pernet_fini(net);
2307 err_ecache:
2308         nf_conntrack_tstamp_pernet_fini(net);
2309 err_tstamp:
2310         nf_conntrack_acct_pernet_fini(net);
2311 err_acct:
2312         nf_conntrack_expect_pernet_fini(net);
2313 err_expect:
2314         free_percpu(net->ct.stat);
2315 err_pcpu_lists:
2316         free_percpu(net->ct.pcpu_lists);
2317 err_stat:
2318         return ret;
2319 }