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