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