nds32: fix build error "relocation truncated to fit: R_NDS32_25_PCREL_RELA" when
[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 /* Bring out ya dead! */
1687 static struct nf_conn *
1688 get_next_corpse(int (*iter)(struct nf_conn *i, void *data),
1689                 void *data, unsigned int *bucket)
1690 {
1691         struct nf_conntrack_tuple_hash *h;
1692         struct nf_conn *ct;
1693         struct hlist_nulls_node *n;
1694         spinlock_t *lockp;
1695
1696         for (; *bucket < nf_conntrack_htable_size; (*bucket)++) {
1697                 lockp = &nf_conntrack_locks[*bucket % CONNTRACK_LOCKS];
1698                 local_bh_disable();
1699                 nf_conntrack_lock(lockp);
1700                 if (*bucket < nf_conntrack_htable_size) {
1701                         hlist_nulls_for_each_entry(h, n, &nf_conntrack_hash[*bucket], hnnode) {
1702                                 if (NF_CT_DIRECTION(h) != IP_CT_DIR_ORIGINAL)
1703                                         continue;
1704                                 ct = nf_ct_tuplehash_to_ctrack(h);
1705                                 if (iter(ct, data))
1706                                         goto found;
1707                         }
1708                 }
1709                 spin_unlock(lockp);
1710                 local_bh_enable();
1711                 cond_resched();
1712         }
1713
1714         return NULL;
1715 found:
1716         atomic_inc(&ct->ct_general.use);
1717         spin_unlock(lockp);
1718         local_bh_enable();
1719         return ct;
1720 }
1721
1722 static void nf_ct_iterate_cleanup(int (*iter)(struct nf_conn *i, void *data),
1723                                   void *data, u32 portid, int report)
1724 {
1725         unsigned int bucket = 0, sequence;
1726         struct nf_conn *ct;
1727
1728         might_sleep();
1729
1730         for (;;) {
1731                 sequence = read_seqcount_begin(&nf_conntrack_generation);
1732
1733                 while ((ct = get_next_corpse(iter, data, &bucket)) != NULL) {
1734                         /* Time to push up daises... */
1735
1736                         nf_ct_delete(ct, portid, report);
1737                         nf_ct_put(ct);
1738                         cond_resched();
1739                 }
1740
1741                 if (!read_seqcount_retry(&nf_conntrack_generation, sequence))
1742                         break;
1743                 bucket = 0;
1744         }
1745 }
1746
1747 struct iter_data {
1748         int (*iter)(struct nf_conn *i, void *data);
1749         void *data;
1750         struct net *net;
1751 };
1752
1753 static int iter_net_only(struct nf_conn *i, void *data)
1754 {
1755         struct iter_data *d = data;
1756
1757         if (!net_eq(d->net, nf_ct_net(i)))
1758                 return 0;
1759
1760         return d->iter(i, d->data);
1761 }
1762
1763 static void
1764 __nf_ct_unconfirmed_destroy(struct net *net)
1765 {
1766         int cpu;
1767
1768         for_each_possible_cpu(cpu) {
1769                 struct nf_conntrack_tuple_hash *h;
1770                 struct hlist_nulls_node *n;
1771                 struct ct_pcpu *pcpu;
1772
1773                 pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
1774
1775                 spin_lock_bh(&pcpu->lock);
1776                 hlist_nulls_for_each_entry(h, n, &pcpu->unconfirmed, hnnode) {
1777                         struct nf_conn *ct;
1778
1779                         ct = nf_ct_tuplehash_to_ctrack(h);
1780
1781                         /* we cannot call iter() on unconfirmed list, the
1782                          * owning cpu can reallocate ct->ext at any time.
1783                          */
1784                         set_bit(IPS_DYING_BIT, &ct->status);
1785                 }
1786                 spin_unlock_bh(&pcpu->lock);
1787                 cond_resched();
1788         }
1789 }
1790
1791 void nf_ct_unconfirmed_destroy(struct net *net)
1792 {
1793         might_sleep();
1794
1795         if (atomic_read(&net->ct.count) > 0) {
1796                 __nf_ct_unconfirmed_destroy(net);
1797                 nf_queue_nf_hook_drop(net);
1798                 synchronize_net();
1799         }
1800 }
1801 EXPORT_SYMBOL_GPL(nf_ct_unconfirmed_destroy);
1802
1803 void nf_ct_iterate_cleanup_net(struct net *net,
1804                                int (*iter)(struct nf_conn *i, void *data),
1805                                void *data, u32 portid, int report)
1806 {
1807         struct iter_data d;
1808
1809         might_sleep();
1810
1811         if (atomic_read(&net->ct.count) == 0)
1812                 return;
1813
1814         d.iter = iter;
1815         d.data = data;
1816         d.net = net;
1817
1818         nf_ct_iterate_cleanup(iter_net_only, &d, portid, report);
1819 }
1820 EXPORT_SYMBOL_GPL(nf_ct_iterate_cleanup_net);
1821
1822 /**
1823  * nf_ct_iterate_destroy - destroy unconfirmed conntracks and iterate table
1824  * @iter: callback to invoke for each conntrack
1825  * @data: data to pass to @iter
1826  *
1827  * Like nf_ct_iterate_cleanup, but first marks conntracks on the
1828  * unconfirmed list as dying (so they will not be inserted into
1829  * main table).
1830  *
1831  * Can only be called in module exit path.
1832  */
1833 void
1834 nf_ct_iterate_destroy(int (*iter)(struct nf_conn *i, void *data), void *data)
1835 {
1836         struct net *net;
1837
1838         down_read(&net_rwsem);
1839         for_each_net(net) {
1840                 if (atomic_read(&net->ct.count) == 0)
1841                         continue;
1842                 __nf_ct_unconfirmed_destroy(net);
1843                 nf_queue_nf_hook_drop(net);
1844         }
1845         up_read(&net_rwsem);
1846
1847         /* Need to wait for netns cleanup worker to finish, if its
1848          * running -- it might have deleted a net namespace from
1849          * the global list, so our __nf_ct_unconfirmed_destroy() might
1850          * not have affected all namespaces.
1851          */
1852         net_ns_barrier();
1853
1854         /* a conntrack could have been unlinked from unconfirmed list
1855          * before we grabbed pcpu lock in __nf_ct_unconfirmed_destroy().
1856          * This makes sure its inserted into conntrack table.
1857          */
1858         synchronize_net();
1859
1860         nf_ct_iterate_cleanup(iter, data, 0, 0);
1861 }
1862 EXPORT_SYMBOL_GPL(nf_ct_iterate_destroy);
1863
1864 static int kill_all(struct nf_conn *i, void *data)
1865 {
1866         return net_eq(nf_ct_net(i), data);
1867 }
1868
1869 void nf_ct_free_hashtable(void *hash, unsigned int size)
1870 {
1871         if (is_vmalloc_addr(hash))
1872                 vfree(hash);
1873         else
1874                 free_pages((unsigned long)hash,
1875                            get_order(sizeof(struct hlist_head) * size));
1876 }
1877 EXPORT_SYMBOL_GPL(nf_ct_free_hashtable);
1878
1879 void nf_conntrack_cleanup_start(void)
1880 {
1881         conntrack_gc_work.exiting = true;
1882         RCU_INIT_POINTER(ip_ct_attach, NULL);
1883 }
1884
1885 void nf_conntrack_cleanup_end(void)
1886 {
1887         RCU_INIT_POINTER(nf_ct_hook, NULL);
1888         cancel_delayed_work_sync(&conntrack_gc_work.dwork);
1889         nf_ct_free_hashtable(nf_conntrack_hash, nf_conntrack_htable_size);
1890
1891         nf_conntrack_proto_fini();
1892         nf_conntrack_seqadj_fini();
1893         nf_conntrack_labels_fini();
1894         nf_conntrack_helper_fini();
1895         nf_conntrack_timeout_fini();
1896         nf_conntrack_ecache_fini();
1897         nf_conntrack_tstamp_fini();
1898         nf_conntrack_acct_fini();
1899         nf_conntrack_expect_fini();
1900
1901         kmem_cache_destroy(nf_conntrack_cachep);
1902 }
1903
1904 /*
1905  * Mishearing the voices in his head, our hero wonders how he's
1906  * supposed to kill the mall.
1907  */
1908 void nf_conntrack_cleanup_net(struct net *net)
1909 {
1910         LIST_HEAD(single);
1911
1912         list_add(&net->exit_list, &single);
1913         nf_conntrack_cleanup_net_list(&single);
1914 }
1915
1916 void nf_conntrack_cleanup_net_list(struct list_head *net_exit_list)
1917 {
1918         int busy;
1919         struct net *net;
1920
1921         /*
1922          * This makes sure all current packets have passed through
1923          *  netfilter framework.  Roll on, two-stage module
1924          *  delete...
1925          */
1926         synchronize_net();
1927 i_see_dead_people:
1928         busy = 0;
1929         list_for_each_entry(net, net_exit_list, exit_list) {
1930                 nf_ct_iterate_cleanup(kill_all, net, 0, 0);
1931                 if (atomic_read(&net->ct.count) != 0)
1932                         busy = 1;
1933         }
1934         if (busy) {
1935                 schedule();
1936                 goto i_see_dead_people;
1937         }
1938
1939         list_for_each_entry(net, net_exit_list, exit_list) {
1940                 nf_conntrack_proto_pernet_fini(net);
1941                 nf_conntrack_helper_pernet_fini(net);
1942                 nf_conntrack_ecache_pernet_fini(net);
1943                 nf_conntrack_tstamp_pernet_fini(net);
1944                 nf_conntrack_acct_pernet_fini(net);
1945                 nf_conntrack_expect_pernet_fini(net);
1946                 free_percpu(net->ct.stat);
1947                 free_percpu(net->ct.pcpu_lists);
1948         }
1949 }
1950
1951 void *nf_ct_alloc_hashtable(unsigned int *sizep, int nulls)
1952 {
1953         struct hlist_nulls_head *hash;
1954         unsigned int nr_slots, i;
1955         size_t sz;
1956
1957         if (*sizep > (UINT_MAX / sizeof(struct hlist_nulls_head)))
1958                 return NULL;
1959
1960         BUILD_BUG_ON(sizeof(struct hlist_nulls_head) != sizeof(struct hlist_head));
1961         nr_slots = *sizep = roundup(*sizep, PAGE_SIZE / sizeof(struct hlist_nulls_head));
1962
1963         if (nr_slots > (UINT_MAX / sizeof(struct hlist_nulls_head)))
1964                 return NULL;
1965
1966         sz = nr_slots * sizeof(struct hlist_nulls_head);
1967         hash = (void *)__get_free_pages(GFP_KERNEL | __GFP_NOWARN | __GFP_ZERO,
1968                                         get_order(sz));
1969         if (!hash)
1970                 hash = vzalloc(sz);
1971
1972         if (hash && nulls)
1973                 for (i = 0; i < nr_slots; i++)
1974                         INIT_HLIST_NULLS_HEAD(&hash[i], i);
1975
1976         return hash;
1977 }
1978 EXPORT_SYMBOL_GPL(nf_ct_alloc_hashtable);
1979
1980 int nf_conntrack_hash_resize(unsigned int hashsize)
1981 {
1982         int i, bucket;
1983         unsigned int old_size;
1984         struct hlist_nulls_head *hash, *old_hash;
1985         struct nf_conntrack_tuple_hash *h;
1986         struct nf_conn *ct;
1987
1988         if (!hashsize)
1989                 return -EINVAL;
1990
1991         hash = nf_ct_alloc_hashtable(&hashsize, 1);
1992         if (!hash)
1993                 return -ENOMEM;
1994
1995         old_size = nf_conntrack_htable_size;
1996         if (old_size == hashsize) {
1997                 nf_ct_free_hashtable(hash, hashsize);
1998                 return 0;
1999         }
2000
2001         local_bh_disable();
2002         nf_conntrack_all_lock();
2003         write_seqcount_begin(&nf_conntrack_generation);
2004
2005         /* Lookups in the old hash might happen in parallel, which means we
2006          * might get false negatives during connection lookup. New connections
2007          * created because of a false negative won't make it into the hash
2008          * though since that required taking the locks.
2009          */
2010
2011         for (i = 0; i < nf_conntrack_htable_size; i++) {
2012                 while (!hlist_nulls_empty(&nf_conntrack_hash[i])) {
2013                         h = hlist_nulls_entry(nf_conntrack_hash[i].first,
2014                                               struct nf_conntrack_tuple_hash, hnnode);
2015                         ct = nf_ct_tuplehash_to_ctrack(h);
2016                         hlist_nulls_del_rcu(&h->hnnode);
2017                         bucket = __hash_conntrack(nf_ct_net(ct),
2018                                                   &h->tuple, hashsize);
2019                         hlist_nulls_add_head_rcu(&h->hnnode, &hash[bucket]);
2020                 }
2021         }
2022         old_size = nf_conntrack_htable_size;
2023         old_hash = nf_conntrack_hash;
2024
2025         nf_conntrack_hash = hash;
2026         nf_conntrack_htable_size = hashsize;
2027
2028         write_seqcount_end(&nf_conntrack_generation);
2029         nf_conntrack_all_unlock();
2030         local_bh_enable();
2031
2032         synchronize_net();
2033         nf_ct_free_hashtable(old_hash, old_size);
2034         return 0;
2035 }
2036
2037 int nf_conntrack_set_hashsize(const char *val, const struct kernel_param *kp)
2038 {
2039         unsigned int hashsize;
2040         int rc;
2041
2042         if (current->nsproxy->net_ns != &init_net)
2043                 return -EOPNOTSUPP;
2044
2045         /* On boot, we can set this without any fancy locking. */
2046         if (!nf_conntrack_htable_size)
2047                 return param_set_uint(val, kp);
2048
2049         rc = kstrtouint(val, 0, &hashsize);
2050         if (rc)
2051                 return rc;
2052
2053         return nf_conntrack_hash_resize(hashsize);
2054 }
2055 EXPORT_SYMBOL_GPL(nf_conntrack_set_hashsize);
2056
2057 module_param_call(hashsize, nf_conntrack_set_hashsize, param_get_uint,
2058                   &nf_conntrack_htable_size, 0600);
2059
2060 static __always_inline unsigned int total_extension_size(void)
2061 {
2062         /* remember to add new extensions below */
2063         BUILD_BUG_ON(NF_CT_EXT_NUM > 9);
2064
2065         return sizeof(struct nf_ct_ext) +
2066                sizeof(struct nf_conn_help)
2067 #if IS_ENABLED(CONFIG_NF_NAT)
2068                 + sizeof(struct nf_conn_nat)
2069 #endif
2070                 + sizeof(struct nf_conn_seqadj)
2071                 + sizeof(struct nf_conn_acct)
2072 #ifdef CONFIG_NF_CONNTRACK_EVENTS
2073                 + sizeof(struct nf_conntrack_ecache)
2074 #endif
2075 #ifdef CONFIG_NF_CONNTRACK_TIMESTAMP
2076                 + sizeof(struct nf_conn_tstamp)
2077 #endif
2078 #ifdef CONFIG_NF_CONNTRACK_TIMEOUT
2079                 + sizeof(struct nf_conn_timeout)
2080 #endif
2081 #ifdef CONFIG_NF_CONNTRACK_LABELS
2082                 + sizeof(struct nf_conn_labels)
2083 #endif
2084 #if IS_ENABLED(CONFIG_NETFILTER_SYNPROXY)
2085                 + sizeof(struct nf_conn_synproxy)
2086 #endif
2087         ;
2088 };
2089
2090 int nf_conntrack_init_start(void)
2091 {
2092         int max_factor = 8;
2093         int ret = -ENOMEM;
2094         int i;
2095
2096         /* struct nf_ct_ext uses u8 to store offsets/size */
2097         BUILD_BUG_ON(total_extension_size() > 255u);
2098
2099         seqcount_init(&nf_conntrack_generation);
2100
2101         for (i = 0; i < CONNTRACK_LOCKS; i++)
2102                 spin_lock_init(&nf_conntrack_locks[i]);
2103
2104         if (!nf_conntrack_htable_size) {
2105                 /* Idea from tcp.c: use 1/16384 of memory.
2106                  * On i386: 32MB machine has 512 buckets.
2107                  * >= 1GB machines have 16384 buckets.
2108                  * >= 4GB machines have 65536 buckets.
2109                  */
2110                 nf_conntrack_htable_size
2111                         = (((totalram_pages << PAGE_SHIFT) / 16384)
2112                            / sizeof(struct hlist_head));
2113                 if (totalram_pages > (4 * (1024 * 1024 * 1024 / PAGE_SIZE)))
2114                         nf_conntrack_htable_size = 65536;
2115                 else if (totalram_pages > (1024 * 1024 * 1024 / PAGE_SIZE))
2116                         nf_conntrack_htable_size = 16384;
2117                 if (nf_conntrack_htable_size < 32)
2118                         nf_conntrack_htable_size = 32;
2119
2120                 /* Use a max. factor of four by default to get the same max as
2121                  * with the old struct list_heads. When a table size is given
2122                  * we use the old value of 8 to avoid reducing the max.
2123                  * entries. */
2124                 max_factor = 4;
2125         }
2126
2127         nf_conntrack_hash = nf_ct_alloc_hashtable(&nf_conntrack_htable_size, 1);
2128         if (!nf_conntrack_hash)
2129                 return -ENOMEM;
2130
2131         nf_conntrack_max = max_factor * nf_conntrack_htable_size;
2132
2133         nf_conntrack_cachep = kmem_cache_create("nf_conntrack",
2134                                                 sizeof(struct nf_conn),
2135                                                 NFCT_INFOMASK + 1,
2136                                                 SLAB_TYPESAFE_BY_RCU | SLAB_HWCACHE_ALIGN, NULL);
2137         if (!nf_conntrack_cachep)
2138                 goto err_cachep;
2139
2140         ret = nf_conntrack_expect_init();
2141         if (ret < 0)
2142                 goto err_expect;
2143
2144         ret = nf_conntrack_acct_init();
2145         if (ret < 0)
2146                 goto err_acct;
2147
2148         ret = nf_conntrack_tstamp_init();
2149         if (ret < 0)
2150                 goto err_tstamp;
2151
2152         ret = nf_conntrack_ecache_init();
2153         if (ret < 0)
2154                 goto err_ecache;
2155
2156         ret = nf_conntrack_timeout_init();
2157         if (ret < 0)
2158                 goto err_timeout;
2159
2160         ret = nf_conntrack_helper_init();
2161         if (ret < 0)
2162                 goto err_helper;
2163
2164         ret = nf_conntrack_labels_init();
2165         if (ret < 0)
2166                 goto err_labels;
2167
2168         ret = nf_conntrack_seqadj_init();
2169         if (ret < 0)
2170                 goto err_seqadj;
2171
2172         ret = nf_conntrack_proto_init();
2173         if (ret < 0)
2174                 goto err_proto;
2175
2176         conntrack_gc_work_init(&conntrack_gc_work);
2177         queue_delayed_work(system_power_efficient_wq, &conntrack_gc_work.dwork, HZ);
2178
2179         return 0;
2180
2181 err_proto:
2182         nf_conntrack_seqadj_fini();
2183 err_seqadj:
2184         nf_conntrack_labels_fini();
2185 err_labels:
2186         nf_conntrack_helper_fini();
2187 err_helper:
2188         nf_conntrack_timeout_fini();
2189 err_timeout:
2190         nf_conntrack_ecache_fini();
2191 err_ecache:
2192         nf_conntrack_tstamp_fini();
2193 err_tstamp:
2194         nf_conntrack_acct_fini();
2195 err_acct:
2196         nf_conntrack_expect_fini();
2197 err_expect:
2198         kmem_cache_destroy(nf_conntrack_cachep);
2199 err_cachep:
2200         nf_ct_free_hashtable(nf_conntrack_hash, nf_conntrack_htable_size);
2201         return ret;
2202 }
2203
2204 static struct nf_ct_hook nf_conntrack_hook = {
2205         .update         = nf_conntrack_update,
2206         .destroy        = destroy_conntrack,
2207 };
2208
2209 void nf_conntrack_init_end(void)
2210 {
2211         /* For use by REJECT target */
2212         RCU_INIT_POINTER(ip_ct_attach, nf_conntrack_attach);
2213         RCU_INIT_POINTER(nf_ct_hook, &nf_conntrack_hook);
2214 }
2215
2216 /*
2217  * We need to use special "null" values, not used in hash table
2218  */
2219 #define UNCONFIRMED_NULLS_VAL   ((1<<30)+0)
2220 #define DYING_NULLS_VAL         ((1<<30)+1)
2221 #define TEMPLATE_NULLS_VAL      ((1<<30)+2)
2222
2223 int nf_conntrack_init_net(struct net *net)
2224 {
2225         int ret = -ENOMEM;
2226         int cpu;
2227
2228         BUILD_BUG_ON(IP_CT_UNTRACKED == IP_CT_NUMBER);
2229         atomic_set(&net->ct.count, 0);
2230
2231         net->ct.pcpu_lists = alloc_percpu(struct ct_pcpu);
2232         if (!net->ct.pcpu_lists)
2233                 goto err_stat;
2234
2235         for_each_possible_cpu(cpu) {
2236                 struct ct_pcpu *pcpu = per_cpu_ptr(net->ct.pcpu_lists, cpu);
2237
2238                 spin_lock_init(&pcpu->lock);
2239                 INIT_HLIST_NULLS_HEAD(&pcpu->unconfirmed, UNCONFIRMED_NULLS_VAL);
2240                 INIT_HLIST_NULLS_HEAD(&pcpu->dying, DYING_NULLS_VAL);
2241         }
2242
2243         net->ct.stat = alloc_percpu(struct ip_conntrack_stat);
2244         if (!net->ct.stat)
2245                 goto err_pcpu_lists;
2246
2247         ret = nf_conntrack_expect_pernet_init(net);
2248         if (ret < 0)
2249                 goto err_expect;
2250         ret = nf_conntrack_acct_pernet_init(net);
2251         if (ret < 0)
2252                 goto err_acct;
2253         ret = nf_conntrack_tstamp_pernet_init(net);
2254         if (ret < 0)
2255                 goto err_tstamp;
2256         ret = nf_conntrack_ecache_pernet_init(net);
2257         if (ret < 0)
2258                 goto err_ecache;
2259         ret = nf_conntrack_helper_pernet_init(net);
2260         if (ret < 0)
2261                 goto err_helper;
2262         ret = nf_conntrack_proto_pernet_init(net);
2263         if (ret < 0)
2264                 goto err_proto;
2265         return 0;
2266
2267 err_proto:
2268         nf_conntrack_helper_pernet_fini(net);
2269 err_helper:
2270         nf_conntrack_ecache_pernet_fini(net);
2271 err_ecache:
2272         nf_conntrack_tstamp_pernet_fini(net);
2273 err_tstamp:
2274         nf_conntrack_acct_pernet_fini(net);
2275 err_acct:
2276         nf_conntrack_expect_pernet_fini(net);
2277 err_expect:
2278         free_percpu(net->ct.stat);
2279 err_pcpu_lists:
2280         free_percpu(net->ct.pcpu_lists);
2281 err_stat:
2282         return ret;
2283 }