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