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