]> asedeno.scripts.mit.edu Git - linux.git/blob - net/openvswitch/conntrack.c
sunrpc: correct the computation for page_ptr when truncating
[linux.git] / net / openvswitch / conntrack.c
1 /*
2  * Copyright (c) 2015 Nicira, Inc.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of version 2 of the GNU General Public
6  * License as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11  * General Public License for more details.
12  */
13
14 #include <linux/module.h>
15 #include <linux/openvswitch.h>
16 #include <linux/tcp.h>
17 #include <linux/udp.h>
18 #include <linux/sctp.h>
19 #include <linux/static_key.h>
20 #include <net/ip.h>
21 #include <net/genetlink.h>
22 #include <net/netfilter/nf_conntrack_core.h>
23 #include <net/netfilter/nf_conntrack_count.h>
24 #include <net/netfilter/nf_conntrack_helper.h>
25 #include <net/netfilter/nf_conntrack_labels.h>
26 #include <net/netfilter/nf_conntrack_seqadj.h>
27 #include <net/netfilter/nf_conntrack_zones.h>
28 #include <net/netfilter/ipv6/nf_defrag_ipv6.h>
29 #include <net/ipv6_frag.h>
30
31 #ifdef CONFIG_NF_NAT_NEEDED
32 #include <linux/netfilter/nf_nat.h>
33 #include <net/netfilter/nf_nat_core.h>
34 #include <net/netfilter/nf_nat_l3proto.h>
35 #endif
36
37 #include "datapath.h"
38 #include "conntrack.h"
39 #include "flow.h"
40 #include "flow_netlink.h"
41
42 struct ovs_ct_len_tbl {
43         int maxlen;
44         int minlen;
45 };
46
47 /* Metadata mark for masked write to conntrack mark */
48 struct md_mark {
49         u32 value;
50         u32 mask;
51 };
52
53 /* Metadata label for masked write to conntrack label. */
54 struct md_labels {
55         struct ovs_key_ct_labels value;
56         struct ovs_key_ct_labels mask;
57 };
58
59 enum ovs_ct_nat {
60         OVS_CT_NAT = 1 << 0,     /* NAT for committed connections only. */
61         OVS_CT_SRC_NAT = 1 << 1, /* Source NAT for NEW connections. */
62         OVS_CT_DST_NAT = 1 << 2, /* Destination NAT for NEW connections. */
63 };
64
65 /* Conntrack action context for execution. */
66 struct ovs_conntrack_info {
67         struct nf_conntrack_helper *helper;
68         struct nf_conntrack_zone zone;
69         struct nf_conn *ct;
70         u8 commit : 1;
71         u8 nat : 3;                 /* enum ovs_ct_nat */
72         u8 force : 1;
73         u8 have_eventmask : 1;
74         u16 family;
75         u32 eventmask;              /* Mask of 1 << IPCT_*. */
76         struct md_mark mark;
77         struct md_labels labels;
78 #ifdef CONFIG_NF_NAT_NEEDED
79         struct nf_nat_range2 range;  /* Only present for SRC NAT and DST NAT. */
80 #endif
81 };
82
83 #if     IS_ENABLED(CONFIG_NETFILTER_CONNCOUNT)
84 #define OVS_CT_LIMIT_UNLIMITED  0
85 #define OVS_CT_LIMIT_DEFAULT OVS_CT_LIMIT_UNLIMITED
86 #define CT_LIMIT_HASH_BUCKETS 512
87 static DEFINE_STATIC_KEY_FALSE(ovs_ct_limit_enabled);
88
89 struct ovs_ct_limit {
90         /* Elements in ovs_ct_limit_info->limits hash table */
91         struct hlist_node hlist_node;
92         struct rcu_head rcu;
93         u16 zone;
94         u32 limit;
95 };
96
97 struct ovs_ct_limit_info {
98         u32 default_limit;
99         struct hlist_head *limits;
100         struct nf_conncount_data *data;
101 };
102
103 static const struct nla_policy ct_limit_policy[OVS_CT_LIMIT_ATTR_MAX + 1] = {
104         [OVS_CT_LIMIT_ATTR_ZONE_LIMIT] = { .type = NLA_NESTED, },
105 };
106 #endif
107
108 static bool labels_nonzero(const struct ovs_key_ct_labels *labels);
109
110 static void __ovs_ct_free_action(struct ovs_conntrack_info *ct_info);
111
112 static u16 key_to_nfproto(const struct sw_flow_key *key)
113 {
114         switch (ntohs(key->eth.type)) {
115         case ETH_P_IP:
116                 return NFPROTO_IPV4;
117         case ETH_P_IPV6:
118                 return NFPROTO_IPV6;
119         default:
120                 return NFPROTO_UNSPEC;
121         }
122 }
123
124 /* Map SKB connection state into the values used by flow definition. */
125 static u8 ovs_ct_get_state(enum ip_conntrack_info ctinfo)
126 {
127         u8 ct_state = OVS_CS_F_TRACKED;
128
129         switch (ctinfo) {
130         case IP_CT_ESTABLISHED_REPLY:
131         case IP_CT_RELATED_REPLY:
132                 ct_state |= OVS_CS_F_REPLY_DIR;
133                 break;
134         default:
135                 break;
136         }
137
138         switch (ctinfo) {
139         case IP_CT_ESTABLISHED:
140         case IP_CT_ESTABLISHED_REPLY:
141                 ct_state |= OVS_CS_F_ESTABLISHED;
142                 break;
143         case IP_CT_RELATED:
144         case IP_CT_RELATED_REPLY:
145                 ct_state |= OVS_CS_F_RELATED;
146                 break;
147         case IP_CT_NEW:
148                 ct_state |= OVS_CS_F_NEW;
149                 break;
150         default:
151                 break;
152         }
153
154         return ct_state;
155 }
156
157 static u32 ovs_ct_get_mark(const struct nf_conn *ct)
158 {
159 #if IS_ENABLED(CONFIG_NF_CONNTRACK_MARK)
160         return ct ? ct->mark : 0;
161 #else
162         return 0;
163 #endif
164 }
165
166 /* Guard against conntrack labels max size shrinking below 128 bits. */
167 #if NF_CT_LABELS_MAX_SIZE < 16
168 #error NF_CT_LABELS_MAX_SIZE must be at least 16 bytes
169 #endif
170
171 static void ovs_ct_get_labels(const struct nf_conn *ct,
172                               struct ovs_key_ct_labels *labels)
173 {
174         struct nf_conn_labels *cl = ct ? nf_ct_labels_find(ct) : NULL;
175
176         if (cl)
177                 memcpy(labels, cl->bits, OVS_CT_LABELS_LEN);
178         else
179                 memset(labels, 0, OVS_CT_LABELS_LEN);
180 }
181
182 static void __ovs_ct_update_key_orig_tp(struct sw_flow_key *key,
183                                         const struct nf_conntrack_tuple *orig,
184                                         u8 icmp_proto)
185 {
186         key->ct_orig_proto = orig->dst.protonum;
187         if (orig->dst.protonum == icmp_proto) {
188                 key->ct.orig_tp.src = htons(orig->dst.u.icmp.type);
189                 key->ct.orig_tp.dst = htons(orig->dst.u.icmp.code);
190         } else {
191                 key->ct.orig_tp.src = orig->src.u.all;
192                 key->ct.orig_tp.dst = orig->dst.u.all;
193         }
194 }
195
196 static void __ovs_ct_update_key(struct sw_flow_key *key, u8 state,
197                                 const struct nf_conntrack_zone *zone,
198                                 const struct nf_conn *ct)
199 {
200         key->ct_state = state;
201         key->ct_zone = zone->id;
202         key->ct.mark = ovs_ct_get_mark(ct);
203         ovs_ct_get_labels(ct, &key->ct.labels);
204
205         if (ct) {
206                 const struct nf_conntrack_tuple *orig;
207
208                 /* Use the master if we have one. */
209                 if (ct->master)
210                         ct = ct->master;
211                 orig = &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple;
212
213                 /* IP version must match with the master connection. */
214                 if (key->eth.type == htons(ETH_P_IP) &&
215                     nf_ct_l3num(ct) == NFPROTO_IPV4) {
216                         key->ipv4.ct_orig.src = orig->src.u3.ip;
217                         key->ipv4.ct_orig.dst = orig->dst.u3.ip;
218                         __ovs_ct_update_key_orig_tp(key, orig, IPPROTO_ICMP);
219                         return;
220                 } else if (key->eth.type == htons(ETH_P_IPV6) &&
221                            !sw_flow_key_is_nd(key) &&
222                            nf_ct_l3num(ct) == NFPROTO_IPV6) {
223                         key->ipv6.ct_orig.src = orig->src.u3.in6;
224                         key->ipv6.ct_orig.dst = orig->dst.u3.in6;
225                         __ovs_ct_update_key_orig_tp(key, orig, NEXTHDR_ICMP);
226                         return;
227                 }
228         }
229         /* Clear 'ct_orig_proto' to mark the non-existence of conntrack
230          * original direction key fields.
231          */
232         key->ct_orig_proto = 0;
233 }
234
235 /* Update 'key' based on skb->_nfct.  If 'post_ct' is true, then OVS has
236  * previously sent the packet to conntrack via the ct action.  If
237  * 'keep_nat_flags' is true, the existing NAT flags retained, else they are
238  * initialized from the connection status.
239  */
240 static void ovs_ct_update_key(const struct sk_buff *skb,
241                               const struct ovs_conntrack_info *info,
242                               struct sw_flow_key *key, bool post_ct,
243                               bool keep_nat_flags)
244 {
245         const struct nf_conntrack_zone *zone = &nf_ct_zone_dflt;
246         enum ip_conntrack_info ctinfo;
247         struct nf_conn *ct;
248         u8 state = 0;
249
250         ct = nf_ct_get(skb, &ctinfo);
251         if (ct) {
252                 state = ovs_ct_get_state(ctinfo);
253                 /* All unconfirmed entries are NEW connections. */
254                 if (!nf_ct_is_confirmed(ct))
255                         state |= OVS_CS_F_NEW;
256                 /* OVS persists the related flag for the duration of the
257                  * connection.
258                  */
259                 if (ct->master)
260                         state |= OVS_CS_F_RELATED;
261                 if (keep_nat_flags) {
262                         state |= key->ct_state & OVS_CS_F_NAT_MASK;
263                 } else {
264                         if (ct->status & IPS_SRC_NAT)
265                                 state |= OVS_CS_F_SRC_NAT;
266                         if (ct->status & IPS_DST_NAT)
267                                 state |= OVS_CS_F_DST_NAT;
268                 }
269                 zone = nf_ct_zone(ct);
270         } else if (post_ct) {
271                 state = OVS_CS_F_TRACKED | OVS_CS_F_INVALID;
272                 if (info)
273                         zone = &info->zone;
274         }
275         __ovs_ct_update_key(key, state, zone, ct);
276 }
277
278 /* This is called to initialize CT key fields possibly coming in from the local
279  * stack.
280  */
281 void ovs_ct_fill_key(const struct sk_buff *skb, struct sw_flow_key *key)
282 {
283         ovs_ct_update_key(skb, NULL, key, false, false);
284 }
285
286 #define IN6_ADDR_INITIALIZER(ADDR) \
287         { (ADDR).s6_addr32[0], (ADDR).s6_addr32[1], \
288           (ADDR).s6_addr32[2], (ADDR).s6_addr32[3] }
289
290 int ovs_ct_put_key(const struct sw_flow_key *swkey,
291                    const struct sw_flow_key *output, struct sk_buff *skb)
292 {
293         if (nla_put_u32(skb, OVS_KEY_ATTR_CT_STATE, output->ct_state))
294                 return -EMSGSIZE;
295
296         if (IS_ENABLED(CONFIG_NF_CONNTRACK_ZONES) &&
297             nla_put_u16(skb, OVS_KEY_ATTR_CT_ZONE, output->ct_zone))
298                 return -EMSGSIZE;
299
300         if (IS_ENABLED(CONFIG_NF_CONNTRACK_MARK) &&
301             nla_put_u32(skb, OVS_KEY_ATTR_CT_MARK, output->ct.mark))
302                 return -EMSGSIZE;
303
304         if (IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS) &&
305             nla_put(skb, OVS_KEY_ATTR_CT_LABELS, sizeof(output->ct.labels),
306                     &output->ct.labels))
307                 return -EMSGSIZE;
308
309         if (swkey->ct_orig_proto) {
310                 if (swkey->eth.type == htons(ETH_P_IP)) {
311                         struct ovs_key_ct_tuple_ipv4 orig = {
312                                 output->ipv4.ct_orig.src,
313                                 output->ipv4.ct_orig.dst,
314                                 output->ct.orig_tp.src,
315                                 output->ct.orig_tp.dst,
316                                 output->ct_orig_proto,
317                         };
318                         if (nla_put(skb, OVS_KEY_ATTR_CT_ORIG_TUPLE_IPV4,
319                                     sizeof(orig), &orig))
320                                 return -EMSGSIZE;
321                 } else if (swkey->eth.type == htons(ETH_P_IPV6)) {
322                         struct ovs_key_ct_tuple_ipv6 orig = {
323                                 IN6_ADDR_INITIALIZER(output->ipv6.ct_orig.src),
324                                 IN6_ADDR_INITIALIZER(output->ipv6.ct_orig.dst),
325                                 output->ct.orig_tp.src,
326                                 output->ct.orig_tp.dst,
327                                 output->ct_orig_proto,
328                         };
329                         if (nla_put(skb, OVS_KEY_ATTR_CT_ORIG_TUPLE_IPV6,
330                                     sizeof(orig), &orig))
331                                 return -EMSGSIZE;
332                 }
333         }
334
335         return 0;
336 }
337
338 static int ovs_ct_set_mark(struct nf_conn *ct, struct sw_flow_key *key,
339                            u32 ct_mark, u32 mask)
340 {
341 #if IS_ENABLED(CONFIG_NF_CONNTRACK_MARK)
342         u32 new_mark;
343
344         new_mark = ct_mark | (ct->mark & ~(mask));
345         if (ct->mark != new_mark) {
346                 ct->mark = new_mark;
347                 if (nf_ct_is_confirmed(ct))
348                         nf_conntrack_event_cache(IPCT_MARK, ct);
349                 key->ct.mark = new_mark;
350         }
351
352         return 0;
353 #else
354         return -ENOTSUPP;
355 #endif
356 }
357
358 static struct nf_conn_labels *ovs_ct_get_conn_labels(struct nf_conn *ct)
359 {
360         struct nf_conn_labels *cl;
361
362         cl = nf_ct_labels_find(ct);
363         if (!cl) {
364                 nf_ct_labels_ext_add(ct);
365                 cl = nf_ct_labels_find(ct);
366         }
367
368         return cl;
369 }
370
371 /* Initialize labels for a new, yet to be committed conntrack entry.  Note that
372  * since the new connection is not yet confirmed, and thus no-one else has
373  * access to it's labels, we simply write them over.
374  */
375 static int ovs_ct_init_labels(struct nf_conn *ct, struct sw_flow_key *key,
376                               const struct ovs_key_ct_labels *labels,
377                               const struct ovs_key_ct_labels *mask)
378 {
379         struct nf_conn_labels *cl, *master_cl;
380         bool have_mask = labels_nonzero(mask);
381
382         /* Inherit master's labels to the related connection? */
383         master_cl = ct->master ? nf_ct_labels_find(ct->master) : NULL;
384
385         if (!master_cl && !have_mask)
386                 return 0;   /* Nothing to do. */
387
388         cl = ovs_ct_get_conn_labels(ct);
389         if (!cl)
390                 return -ENOSPC;
391
392         /* Inherit the master's labels, if any. */
393         if (master_cl)
394                 *cl = *master_cl;
395
396         if (have_mask) {
397                 u32 *dst = (u32 *)cl->bits;
398                 int i;
399
400                 for (i = 0; i < OVS_CT_LABELS_LEN_32; i++)
401                         dst[i] = (dst[i] & ~mask->ct_labels_32[i]) |
402                                 (labels->ct_labels_32[i]
403                                  & mask->ct_labels_32[i]);
404         }
405
406         /* Labels are included in the IPCTNL_MSG_CT_NEW event only if the
407          * IPCT_LABEL bit is set in the event cache.
408          */
409         nf_conntrack_event_cache(IPCT_LABEL, ct);
410
411         memcpy(&key->ct.labels, cl->bits, OVS_CT_LABELS_LEN);
412
413         return 0;
414 }
415
416 static int ovs_ct_set_labels(struct nf_conn *ct, struct sw_flow_key *key,
417                              const struct ovs_key_ct_labels *labels,
418                              const struct ovs_key_ct_labels *mask)
419 {
420         struct nf_conn_labels *cl;
421         int err;
422
423         cl = ovs_ct_get_conn_labels(ct);
424         if (!cl)
425                 return -ENOSPC;
426
427         err = nf_connlabels_replace(ct, labels->ct_labels_32,
428                                     mask->ct_labels_32,
429                                     OVS_CT_LABELS_LEN_32);
430         if (err)
431                 return err;
432
433         memcpy(&key->ct.labels, cl->bits, OVS_CT_LABELS_LEN);
434
435         return 0;
436 }
437
438 /* 'skb' should already be pulled to nh_ofs. */
439 static int ovs_ct_helper(struct sk_buff *skb, u16 proto)
440 {
441         const struct nf_conntrack_helper *helper;
442         const struct nf_conn_help *help;
443         enum ip_conntrack_info ctinfo;
444         unsigned int protoff;
445         struct nf_conn *ct;
446         int err;
447
448         ct = nf_ct_get(skb, &ctinfo);
449         if (!ct || ctinfo == IP_CT_RELATED_REPLY)
450                 return NF_ACCEPT;
451
452         help = nfct_help(ct);
453         if (!help)
454                 return NF_ACCEPT;
455
456         helper = rcu_dereference(help->helper);
457         if (!helper)
458                 return NF_ACCEPT;
459
460         switch (proto) {
461         case NFPROTO_IPV4:
462                 protoff = ip_hdrlen(skb);
463                 break;
464         case NFPROTO_IPV6: {
465                 u8 nexthdr = ipv6_hdr(skb)->nexthdr;
466                 __be16 frag_off;
467                 int ofs;
468
469                 ofs = ipv6_skip_exthdr(skb, sizeof(struct ipv6hdr), &nexthdr,
470                                        &frag_off);
471                 if (ofs < 0 || (frag_off & htons(~0x7)) != 0) {
472                         pr_debug("proto header not found\n");
473                         return NF_ACCEPT;
474                 }
475                 protoff = ofs;
476                 break;
477         }
478         default:
479                 WARN_ONCE(1, "helper invoked on non-IP family!");
480                 return NF_DROP;
481         }
482
483         err = helper->help(skb, protoff, ct, ctinfo);
484         if (err != NF_ACCEPT)
485                 return err;
486
487         /* Adjust seqs after helper.  This is needed due to some helpers (e.g.,
488          * FTP with NAT) adusting the TCP payload size when mangling IP
489          * addresses and/or port numbers in the text-based control connection.
490          */
491         if (test_bit(IPS_SEQ_ADJUST_BIT, &ct->status) &&
492             !nf_ct_seq_adjust(skb, ct, ctinfo, protoff))
493                 return NF_DROP;
494         return NF_ACCEPT;
495 }
496
497 /* Returns 0 on success, -EINPROGRESS if 'skb' is stolen, or other nonzero
498  * value if 'skb' is freed.
499  */
500 static int handle_fragments(struct net *net, struct sw_flow_key *key,
501                             u16 zone, struct sk_buff *skb)
502 {
503         struct ovs_skb_cb ovs_cb = *OVS_CB(skb);
504         int err;
505
506         if (key->eth.type == htons(ETH_P_IP)) {
507                 enum ip_defrag_users user = IP_DEFRAG_CONNTRACK_IN + zone;
508
509                 memset(IPCB(skb), 0, sizeof(struct inet_skb_parm));
510                 err = ip_defrag(net, skb, user);
511                 if (err)
512                         return err;
513
514                 ovs_cb.mru = IPCB(skb)->frag_max_size;
515 #if IS_ENABLED(CONFIG_NF_DEFRAG_IPV6)
516         } else if (key->eth.type == htons(ETH_P_IPV6)) {
517                 enum ip6_defrag_users user = IP6_DEFRAG_CONNTRACK_IN + zone;
518
519                 memset(IP6CB(skb), 0, sizeof(struct inet6_skb_parm));
520                 err = nf_ct_frag6_gather(net, skb, user);
521                 if (err) {
522                         if (err != -EINPROGRESS)
523                                 kfree_skb(skb);
524                         return err;
525                 }
526
527                 key->ip.proto = ipv6_hdr(skb)->nexthdr;
528                 ovs_cb.mru = IP6CB(skb)->frag_max_size;
529 #endif
530         } else {
531                 kfree_skb(skb);
532                 return -EPFNOSUPPORT;
533         }
534
535         key->ip.frag = OVS_FRAG_TYPE_NONE;
536         skb_clear_hash(skb);
537         skb->ignore_df = 1;
538         *OVS_CB(skb) = ovs_cb;
539
540         return 0;
541 }
542
543 static struct nf_conntrack_expect *
544 ovs_ct_expect_find(struct net *net, const struct nf_conntrack_zone *zone,
545                    u16 proto, const struct sk_buff *skb)
546 {
547         struct nf_conntrack_tuple tuple;
548         struct nf_conntrack_expect *exp;
549
550         if (!nf_ct_get_tuplepr(skb, skb_network_offset(skb), proto, net, &tuple))
551                 return NULL;
552
553         exp = __nf_ct_expect_find(net, zone, &tuple);
554         if (exp) {
555                 struct nf_conntrack_tuple_hash *h;
556
557                 /* Delete existing conntrack entry, if it clashes with the
558                  * expectation.  This can happen since conntrack ALGs do not
559                  * check for clashes between (new) expectations and existing
560                  * conntrack entries.  nf_conntrack_in() will check the
561                  * expectations only if a conntrack entry can not be found,
562                  * which can lead to OVS finding the expectation (here) in the
563                  * init direction, but which will not be removed by the
564                  * nf_conntrack_in() call, if a matching conntrack entry is
565                  * found instead.  In this case all init direction packets
566                  * would be reported as new related packets, while reply
567                  * direction packets would be reported as un-related
568                  * established packets.
569                  */
570                 h = nf_conntrack_find_get(net, zone, &tuple);
571                 if (h) {
572                         struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
573
574                         nf_ct_delete(ct, 0, 0);
575                         nf_conntrack_put(&ct->ct_general);
576                 }
577         }
578
579         return exp;
580 }
581
582 /* This replicates logic from nf_conntrack_core.c that is not exported. */
583 static enum ip_conntrack_info
584 ovs_ct_get_info(const struct nf_conntrack_tuple_hash *h)
585 {
586         const struct nf_conn *ct = nf_ct_tuplehash_to_ctrack(h);
587
588         if (NF_CT_DIRECTION(h) == IP_CT_DIR_REPLY)
589                 return IP_CT_ESTABLISHED_REPLY;
590         /* Once we've had two way comms, always ESTABLISHED. */
591         if (test_bit(IPS_SEEN_REPLY_BIT, &ct->status))
592                 return IP_CT_ESTABLISHED;
593         if (test_bit(IPS_EXPECTED_BIT, &ct->status))
594                 return IP_CT_RELATED;
595         return IP_CT_NEW;
596 }
597
598 /* Find an existing connection which this packet belongs to without
599  * re-attributing statistics or modifying the connection state.  This allows an
600  * skb->_nfct lost due to an upcall to be recovered during actions execution.
601  *
602  * Must be called with rcu_read_lock.
603  *
604  * On success, populates skb->_nfct and returns the connection.  Returns NULL
605  * if there is no existing entry.
606  */
607 static struct nf_conn *
608 ovs_ct_find_existing(struct net *net, const struct nf_conntrack_zone *zone,
609                      u8 l3num, struct sk_buff *skb, bool natted)
610 {
611         struct nf_conntrack_tuple tuple;
612         struct nf_conntrack_tuple_hash *h;
613         struct nf_conn *ct;
614
615         if (!nf_ct_get_tuplepr(skb, skb_network_offset(skb), l3num,
616                                net, &tuple)) {
617                 pr_debug("ovs_ct_find_existing: Can't get tuple\n");
618                 return NULL;
619         }
620
621         /* Must invert the tuple if skb has been transformed by NAT. */
622         if (natted) {
623                 struct nf_conntrack_tuple inverse;
624
625                 if (!nf_ct_invert_tuplepr(&inverse, &tuple)) {
626                         pr_debug("ovs_ct_find_existing: Inversion failed!\n");
627                         return NULL;
628                 }
629                 tuple = inverse;
630         }
631
632         /* look for tuple match */
633         h = nf_conntrack_find_get(net, zone, &tuple);
634         if (!h)
635                 return NULL;   /* Not found. */
636
637         ct = nf_ct_tuplehash_to_ctrack(h);
638
639         /* Inverted packet tuple matches the reverse direction conntrack tuple,
640          * select the other tuplehash to get the right 'ctinfo' bits for this
641          * packet.
642          */
643         if (natted)
644                 h = &ct->tuplehash[!h->tuple.dst.dir];
645
646         nf_ct_set(skb, ct, ovs_ct_get_info(h));
647         return ct;
648 }
649
650 static
651 struct nf_conn *ovs_ct_executed(struct net *net,
652                                 const struct sw_flow_key *key,
653                                 const struct ovs_conntrack_info *info,
654                                 struct sk_buff *skb,
655                                 bool *ct_executed)
656 {
657         struct nf_conn *ct = NULL;
658
659         /* If no ct, check if we have evidence that an existing conntrack entry
660          * might be found for this skb.  This happens when we lose a skb->_nfct
661          * due to an upcall, or if the direction is being forced.  If the
662          * connection was not confirmed, it is not cached and needs to be run
663          * through conntrack again.
664          */
665         *ct_executed = (key->ct_state & OVS_CS_F_TRACKED) &&
666                        !(key->ct_state & OVS_CS_F_INVALID) &&
667                        (key->ct_zone == info->zone.id);
668
669         if (*ct_executed || (!key->ct_state && info->force)) {
670                 ct = ovs_ct_find_existing(net, &info->zone, info->family, skb,
671                                           !!(key->ct_state &
672                                           OVS_CS_F_NAT_MASK));
673         }
674
675         return ct;
676 }
677
678 /* Determine whether skb->_nfct is equal to the result of conntrack lookup. */
679 static bool skb_nfct_cached(struct net *net,
680                             const struct sw_flow_key *key,
681                             const struct ovs_conntrack_info *info,
682                             struct sk_buff *skb)
683 {
684         enum ip_conntrack_info ctinfo;
685         struct nf_conn *ct;
686         bool ct_executed = true;
687
688         ct = nf_ct_get(skb, &ctinfo);
689         if (!ct)
690                 ct = ovs_ct_executed(net, key, info, skb, &ct_executed);
691
692         if (ct)
693                 nf_ct_get(skb, &ctinfo);
694         else
695                 return false;
696
697         if (!net_eq(net, read_pnet(&ct->ct_net)))
698                 return false;
699         if (!nf_ct_zone_equal_any(info->ct, nf_ct_zone(ct)))
700                 return false;
701         if (info->helper) {
702                 struct nf_conn_help *help;
703
704                 help = nf_ct_ext_find(ct, NF_CT_EXT_HELPER);
705                 if (help && rcu_access_pointer(help->helper) != info->helper)
706                         return false;
707         }
708         /* Force conntrack entry direction to the current packet? */
709         if (info->force && CTINFO2DIR(ctinfo) != IP_CT_DIR_ORIGINAL) {
710                 /* Delete the conntrack entry if confirmed, else just release
711                  * the reference.
712                  */
713                 if (nf_ct_is_confirmed(ct))
714                         nf_ct_delete(ct, 0, 0);
715
716                 nf_conntrack_put(&ct->ct_general);
717                 nf_ct_set(skb, NULL, 0);
718                 return false;
719         }
720
721         return ct_executed;
722 }
723
724 #ifdef CONFIG_NF_NAT_NEEDED
725 /* Modelled after nf_nat_ipv[46]_fn().
726  * range is only used for new, uninitialized NAT state.
727  * Returns either NF_ACCEPT or NF_DROP.
728  */
729 static int ovs_ct_nat_execute(struct sk_buff *skb, struct nf_conn *ct,
730                               enum ip_conntrack_info ctinfo,
731                               const struct nf_nat_range2 *range,
732                               enum nf_nat_manip_type maniptype)
733 {
734         int hooknum, nh_off, err = NF_ACCEPT;
735
736         nh_off = skb_network_offset(skb);
737         skb_pull_rcsum(skb, nh_off);
738
739         /* See HOOK2MANIP(). */
740         if (maniptype == NF_NAT_MANIP_SRC)
741                 hooknum = NF_INET_LOCAL_IN; /* Source NAT */
742         else
743                 hooknum = NF_INET_LOCAL_OUT; /* Destination NAT */
744
745         switch (ctinfo) {
746         case IP_CT_RELATED:
747         case IP_CT_RELATED_REPLY:
748                 if (IS_ENABLED(CONFIG_NF_NAT_IPV4) &&
749                     skb->protocol == htons(ETH_P_IP) &&
750                     ip_hdr(skb)->protocol == IPPROTO_ICMP) {
751                         if (!nf_nat_icmp_reply_translation(skb, ct, ctinfo,
752                                                            hooknum))
753                                 err = NF_DROP;
754                         goto push;
755                 } else if (IS_ENABLED(CONFIG_NF_NAT_IPV6) &&
756                            skb->protocol == htons(ETH_P_IPV6)) {
757                         __be16 frag_off;
758                         u8 nexthdr = ipv6_hdr(skb)->nexthdr;
759                         int hdrlen = ipv6_skip_exthdr(skb,
760                                                       sizeof(struct ipv6hdr),
761                                                       &nexthdr, &frag_off);
762
763                         if (hdrlen >= 0 && nexthdr == IPPROTO_ICMPV6) {
764                                 if (!nf_nat_icmpv6_reply_translation(skb, ct,
765                                                                      ctinfo,
766                                                                      hooknum,
767                                                                      hdrlen))
768                                         err = NF_DROP;
769                                 goto push;
770                         }
771                 }
772                 /* Non-ICMP, fall thru to initialize if needed. */
773                 /* fall through */
774         case IP_CT_NEW:
775                 /* Seen it before?  This can happen for loopback, retrans,
776                  * or local packets.
777                  */
778                 if (!nf_nat_initialized(ct, maniptype)) {
779                         /* Initialize according to the NAT action. */
780                         err = (range && range->flags & NF_NAT_RANGE_MAP_IPS)
781                                 /* Action is set up to establish a new
782                                  * mapping.
783                                  */
784                                 ? nf_nat_setup_info(ct, range, maniptype)
785                                 : nf_nat_alloc_null_binding(ct, hooknum);
786                         if (err != NF_ACCEPT)
787                                 goto push;
788                 }
789                 break;
790
791         case IP_CT_ESTABLISHED:
792         case IP_CT_ESTABLISHED_REPLY:
793                 break;
794
795         default:
796                 err = NF_DROP;
797                 goto push;
798         }
799
800         err = nf_nat_packet(ct, ctinfo, hooknum, skb);
801 push:
802         skb_push(skb, nh_off);
803         skb_postpush_rcsum(skb, skb->data, nh_off);
804
805         return err;
806 }
807
808 static void ovs_nat_update_key(struct sw_flow_key *key,
809                                const struct sk_buff *skb,
810                                enum nf_nat_manip_type maniptype)
811 {
812         if (maniptype == NF_NAT_MANIP_SRC) {
813                 __be16 src;
814
815                 key->ct_state |= OVS_CS_F_SRC_NAT;
816                 if (key->eth.type == htons(ETH_P_IP))
817                         key->ipv4.addr.src = ip_hdr(skb)->saddr;
818                 else if (key->eth.type == htons(ETH_P_IPV6))
819                         memcpy(&key->ipv6.addr.src, &ipv6_hdr(skb)->saddr,
820                                sizeof(key->ipv6.addr.src));
821                 else
822                         return;
823
824                 if (key->ip.proto == IPPROTO_UDP)
825                         src = udp_hdr(skb)->source;
826                 else if (key->ip.proto == IPPROTO_TCP)
827                         src = tcp_hdr(skb)->source;
828                 else if (key->ip.proto == IPPROTO_SCTP)
829                         src = sctp_hdr(skb)->source;
830                 else
831                         return;
832
833                 key->tp.src = src;
834         } else {
835                 __be16 dst;
836
837                 key->ct_state |= OVS_CS_F_DST_NAT;
838                 if (key->eth.type == htons(ETH_P_IP))
839                         key->ipv4.addr.dst = ip_hdr(skb)->daddr;
840                 else if (key->eth.type == htons(ETH_P_IPV6))
841                         memcpy(&key->ipv6.addr.dst, &ipv6_hdr(skb)->daddr,
842                                sizeof(key->ipv6.addr.dst));
843                 else
844                         return;
845
846                 if (key->ip.proto == IPPROTO_UDP)
847                         dst = udp_hdr(skb)->dest;
848                 else if (key->ip.proto == IPPROTO_TCP)
849                         dst = tcp_hdr(skb)->dest;
850                 else if (key->ip.proto == IPPROTO_SCTP)
851                         dst = sctp_hdr(skb)->dest;
852                 else
853                         return;
854
855                 key->tp.dst = dst;
856         }
857 }
858
859 /* Returns NF_DROP if the packet should be dropped, NF_ACCEPT otherwise. */
860 static int ovs_ct_nat(struct net *net, struct sw_flow_key *key,
861                       const struct ovs_conntrack_info *info,
862                       struct sk_buff *skb, struct nf_conn *ct,
863                       enum ip_conntrack_info ctinfo)
864 {
865         enum nf_nat_manip_type maniptype;
866         int err;
867
868         /* Add NAT extension if not confirmed yet. */
869         if (!nf_ct_is_confirmed(ct) && !nf_ct_nat_ext_add(ct))
870                 return NF_ACCEPT;   /* Can't NAT. */
871
872         /* Determine NAT type.
873          * Check if the NAT type can be deduced from the tracked connection.
874          * Make sure new expected connections (IP_CT_RELATED) are NATted only
875          * when committing.
876          */
877         if (info->nat & OVS_CT_NAT && ctinfo != IP_CT_NEW &&
878             ct->status & IPS_NAT_MASK &&
879             (ctinfo != IP_CT_RELATED || info->commit)) {
880                 /* NAT an established or related connection like before. */
881                 if (CTINFO2DIR(ctinfo) == IP_CT_DIR_REPLY)
882                         /* This is the REPLY direction for a connection
883                          * for which NAT was applied in the forward
884                          * direction.  Do the reverse NAT.
885                          */
886                         maniptype = ct->status & IPS_SRC_NAT
887                                 ? NF_NAT_MANIP_DST : NF_NAT_MANIP_SRC;
888                 else
889                         maniptype = ct->status & IPS_SRC_NAT
890                                 ? NF_NAT_MANIP_SRC : NF_NAT_MANIP_DST;
891         } else if (info->nat & OVS_CT_SRC_NAT) {
892                 maniptype = NF_NAT_MANIP_SRC;
893         } else if (info->nat & OVS_CT_DST_NAT) {
894                 maniptype = NF_NAT_MANIP_DST;
895         } else {
896                 return NF_ACCEPT; /* Connection is not NATed. */
897         }
898         err = ovs_ct_nat_execute(skb, ct, ctinfo, &info->range, maniptype);
899
900         /* Mark NAT done if successful and update the flow key. */
901         if (err == NF_ACCEPT)
902                 ovs_nat_update_key(key, skb, maniptype);
903
904         return err;
905 }
906 #else /* !CONFIG_NF_NAT_NEEDED */
907 static int ovs_ct_nat(struct net *net, struct sw_flow_key *key,
908                       const struct ovs_conntrack_info *info,
909                       struct sk_buff *skb, struct nf_conn *ct,
910                       enum ip_conntrack_info ctinfo)
911 {
912         return NF_ACCEPT;
913 }
914 #endif
915
916 /* Pass 'skb' through conntrack in 'net', using zone configured in 'info', if
917  * not done already.  Update key with new CT state after passing the packet
918  * through conntrack.
919  * Note that if the packet is deemed invalid by conntrack, skb->_nfct will be
920  * set to NULL and 0 will be returned.
921  */
922 static int __ovs_ct_lookup(struct net *net, struct sw_flow_key *key,
923                            const struct ovs_conntrack_info *info,
924                            struct sk_buff *skb)
925 {
926         /* If we are recirculating packets to match on conntrack fields and
927          * committing with a separate conntrack action,  then we don't need to
928          * actually run the packet through conntrack twice unless it's for a
929          * different zone.
930          */
931         bool cached = skb_nfct_cached(net, key, info, skb);
932         enum ip_conntrack_info ctinfo;
933         struct nf_conn *ct;
934
935         if (!cached) {
936                 struct nf_hook_state state = {
937                         .hook = NF_INET_PRE_ROUTING,
938                         .pf = info->family,
939                         .net = net,
940                 };
941                 struct nf_conn *tmpl = info->ct;
942                 int err;
943
944                 /* Associate skb with specified zone. */
945                 if (tmpl) {
946                         if (skb_nfct(skb))
947                                 nf_conntrack_put(skb_nfct(skb));
948                         nf_conntrack_get(&tmpl->ct_general);
949                         nf_ct_set(skb, tmpl, IP_CT_NEW);
950                 }
951
952                 err = nf_conntrack_in(skb, &state);
953                 if (err != NF_ACCEPT)
954                         return -ENOENT;
955
956                 /* Clear CT state NAT flags to mark that we have not yet done
957                  * NAT after the nf_conntrack_in() call.  We can actually clear
958                  * the whole state, as it will be re-initialized below.
959                  */
960                 key->ct_state = 0;
961
962                 /* Update the key, but keep the NAT flags. */
963                 ovs_ct_update_key(skb, info, key, true, true);
964         }
965
966         ct = nf_ct_get(skb, &ctinfo);
967         if (ct) {
968                 /* Packets starting a new connection must be NATted before the
969                  * helper, so that the helper knows about the NAT.  We enforce
970                  * this by delaying both NAT and helper calls for unconfirmed
971                  * connections until the committing CT action.  For later
972                  * packets NAT and Helper may be called in either order.
973                  *
974                  * NAT will be done only if the CT action has NAT, and only
975                  * once per packet (per zone), as guarded by the NAT bits in
976                  * the key->ct_state.
977                  */
978                 if (info->nat && !(key->ct_state & OVS_CS_F_NAT_MASK) &&
979                     (nf_ct_is_confirmed(ct) || info->commit) &&
980                     ovs_ct_nat(net, key, info, skb, ct, ctinfo) != NF_ACCEPT) {
981                         return -EINVAL;
982                 }
983
984                 /* Userspace may decide to perform a ct lookup without a helper
985                  * specified followed by a (recirculate and) commit with one.
986                  * Therefore, for unconfirmed connections which we will commit,
987                  * we need to attach the helper here.
988                  */
989                 if (!nf_ct_is_confirmed(ct) && info->commit &&
990                     info->helper && !nfct_help(ct)) {
991                         int err = __nf_ct_try_assign_helper(ct, info->ct,
992                                                             GFP_ATOMIC);
993                         if (err)
994                                 return err;
995                 }
996
997                 /* Call the helper only if:
998                  * - nf_conntrack_in() was executed above ("!cached") for a
999                  *   confirmed connection, or
1000                  * - When committing an unconfirmed connection.
1001                  */
1002                 if ((nf_ct_is_confirmed(ct) ? !cached : info->commit) &&
1003                     ovs_ct_helper(skb, info->family) != NF_ACCEPT) {
1004                         return -EINVAL;
1005                 }
1006         }
1007
1008         return 0;
1009 }
1010
1011 /* Lookup connection and read fields into key. */
1012 static int ovs_ct_lookup(struct net *net, struct sw_flow_key *key,
1013                          const struct ovs_conntrack_info *info,
1014                          struct sk_buff *skb)
1015 {
1016         struct nf_conntrack_expect *exp;
1017
1018         /* If we pass an expected packet through nf_conntrack_in() the
1019          * expectation is typically removed, but the packet could still be
1020          * lost in upcall processing.  To prevent this from happening we
1021          * perform an explicit expectation lookup.  Expected connections are
1022          * always new, and will be passed through conntrack only when they are
1023          * committed, as it is OK to remove the expectation at that time.
1024          */
1025         exp = ovs_ct_expect_find(net, &info->zone, info->family, skb);
1026         if (exp) {
1027                 u8 state;
1028
1029                 /* NOTE: New connections are NATted and Helped only when
1030                  * committed, so we are not calling into NAT here.
1031                  */
1032                 state = OVS_CS_F_TRACKED | OVS_CS_F_NEW | OVS_CS_F_RELATED;
1033                 __ovs_ct_update_key(key, state, &info->zone, exp->master);
1034         } else {
1035                 struct nf_conn *ct;
1036                 int err;
1037
1038                 err = __ovs_ct_lookup(net, key, info, skb);
1039                 if (err)
1040                         return err;
1041
1042                 ct = (struct nf_conn *)skb_nfct(skb);
1043                 if (ct)
1044                         nf_ct_deliver_cached_events(ct);
1045         }
1046
1047         return 0;
1048 }
1049
1050 static bool labels_nonzero(const struct ovs_key_ct_labels *labels)
1051 {
1052         size_t i;
1053
1054         for (i = 0; i < OVS_CT_LABELS_LEN_32; i++)
1055                 if (labels->ct_labels_32[i])
1056                         return true;
1057
1058         return false;
1059 }
1060
1061 #if     IS_ENABLED(CONFIG_NETFILTER_CONNCOUNT)
1062 static struct hlist_head *ct_limit_hash_bucket(
1063         const struct ovs_ct_limit_info *info, u16 zone)
1064 {
1065         return &info->limits[zone & (CT_LIMIT_HASH_BUCKETS - 1)];
1066 }
1067
1068 /* Call with ovs_mutex */
1069 static void ct_limit_set(const struct ovs_ct_limit_info *info,
1070                          struct ovs_ct_limit *new_ct_limit)
1071 {
1072         struct ovs_ct_limit *ct_limit;
1073         struct hlist_head *head;
1074
1075         head = ct_limit_hash_bucket(info, new_ct_limit->zone);
1076         hlist_for_each_entry_rcu(ct_limit, head, hlist_node) {
1077                 if (ct_limit->zone == new_ct_limit->zone) {
1078                         hlist_replace_rcu(&ct_limit->hlist_node,
1079                                           &new_ct_limit->hlist_node);
1080                         kfree_rcu(ct_limit, rcu);
1081                         return;
1082                 }
1083         }
1084
1085         hlist_add_head_rcu(&new_ct_limit->hlist_node, head);
1086 }
1087
1088 /* Call with ovs_mutex */
1089 static void ct_limit_del(const struct ovs_ct_limit_info *info, u16 zone)
1090 {
1091         struct ovs_ct_limit *ct_limit;
1092         struct hlist_head *head;
1093         struct hlist_node *n;
1094
1095         head = ct_limit_hash_bucket(info, zone);
1096         hlist_for_each_entry_safe(ct_limit, n, head, hlist_node) {
1097                 if (ct_limit->zone == zone) {
1098                         hlist_del_rcu(&ct_limit->hlist_node);
1099                         kfree_rcu(ct_limit, rcu);
1100                         return;
1101                 }
1102         }
1103 }
1104
1105 /* Call with RCU read lock */
1106 static u32 ct_limit_get(const struct ovs_ct_limit_info *info, u16 zone)
1107 {
1108         struct ovs_ct_limit *ct_limit;
1109         struct hlist_head *head;
1110
1111         head = ct_limit_hash_bucket(info, zone);
1112         hlist_for_each_entry_rcu(ct_limit, head, hlist_node) {
1113                 if (ct_limit->zone == zone)
1114                         return ct_limit->limit;
1115         }
1116
1117         return info->default_limit;
1118 }
1119
1120 static int ovs_ct_check_limit(struct net *net,
1121                               const struct ovs_conntrack_info *info,
1122                               const struct nf_conntrack_tuple *tuple)
1123 {
1124         struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
1125         const struct ovs_ct_limit_info *ct_limit_info = ovs_net->ct_limit_info;
1126         u32 per_zone_limit, connections;
1127         u32 conncount_key;
1128
1129         conncount_key = info->zone.id;
1130
1131         per_zone_limit = ct_limit_get(ct_limit_info, info->zone.id);
1132         if (per_zone_limit == OVS_CT_LIMIT_UNLIMITED)
1133                 return 0;
1134
1135         connections = nf_conncount_count(net, ct_limit_info->data,
1136                                          &conncount_key, tuple, &info->zone);
1137         if (connections > per_zone_limit)
1138                 return -ENOMEM;
1139
1140         return 0;
1141 }
1142 #endif
1143
1144 /* Lookup connection and confirm if unconfirmed. */
1145 static int ovs_ct_commit(struct net *net, struct sw_flow_key *key,
1146                          const struct ovs_conntrack_info *info,
1147                          struct sk_buff *skb)
1148 {
1149         enum ip_conntrack_info ctinfo;
1150         struct nf_conn *ct;
1151         int err;
1152
1153         err = __ovs_ct_lookup(net, key, info, skb);
1154         if (err)
1155                 return err;
1156
1157         /* The connection could be invalid, in which case this is a no-op.*/
1158         ct = nf_ct_get(skb, &ctinfo);
1159         if (!ct)
1160                 return 0;
1161
1162 #if     IS_ENABLED(CONFIG_NETFILTER_CONNCOUNT)
1163         if (static_branch_unlikely(&ovs_ct_limit_enabled)) {
1164                 if (!nf_ct_is_confirmed(ct)) {
1165                         err = ovs_ct_check_limit(net, info,
1166                                 &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
1167                         if (err) {
1168                                 net_warn_ratelimited("openvswitch: zone: %u "
1169                                         "execeeds conntrack limit\n",
1170                                         info->zone.id);
1171                                 return err;
1172                         }
1173                 }
1174         }
1175 #endif
1176
1177         /* Set the conntrack event mask if given.  NEW and DELETE events have
1178          * their own groups, but the NFNLGRP_CONNTRACK_UPDATE group listener
1179          * typically would receive many kinds of updates.  Setting the event
1180          * mask allows those events to be filtered.  The set event mask will
1181          * remain in effect for the lifetime of the connection unless changed
1182          * by a further CT action with both the commit flag and the eventmask
1183          * option. */
1184         if (info->have_eventmask) {
1185                 struct nf_conntrack_ecache *cache = nf_ct_ecache_find(ct);
1186
1187                 if (cache)
1188                         cache->ctmask = info->eventmask;
1189         }
1190
1191         /* Apply changes before confirming the connection so that the initial
1192          * conntrack NEW netlink event carries the values given in the CT
1193          * action.
1194          */
1195         if (info->mark.mask) {
1196                 err = ovs_ct_set_mark(ct, key, info->mark.value,
1197                                       info->mark.mask);
1198                 if (err)
1199                         return err;
1200         }
1201         if (!nf_ct_is_confirmed(ct)) {
1202                 err = ovs_ct_init_labels(ct, key, &info->labels.value,
1203                                          &info->labels.mask);
1204                 if (err)
1205                         return err;
1206         } else if (labels_nonzero(&info->labels.mask)) {
1207                 err = ovs_ct_set_labels(ct, key, &info->labels.value,
1208                                         &info->labels.mask);
1209                 if (err)
1210                         return err;
1211         }
1212         /* This will take care of sending queued events even if the connection
1213          * is already confirmed.
1214          */
1215         if (nf_conntrack_confirm(skb) != NF_ACCEPT)
1216                 return -EINVAL;
1217
1218         return 0;
1219 }
1220
1221 /* Trim the skb to the length specified by the IP/IPv6 header,
1222  * removing any trailing lower-layer padding. This prepares the skb
1223  * for higher-layer processing that assumes skb->len excludes padding
1224  * (such as nf_ip_checksum). The caller needs to pull the skb to the
1225  * network header, and ensure ip_hdr/ipv6_hdr points to valid data.
1226  */
1227 static int ovs_skb_network_trim(struct sk_buff *skb)
1228 {
1229         unsigned int len;
1230         int err;
1231
1232         switch (skb->protocol) {
1233         case htons(ETH_P_IP):
1234                 len = ntohs(ip_hdr(skb)->tot_len);
1235                 break;
1236         case htons(ETH_P_IPV6):
1237                 len = sizeof(struct ipv6hdr)
1238                         + ntohs(ipv6_hdr(skb)->payload_len);
1239                 break;
1240         default:
1241                 len = skb->len;
1242         }
1243
1244         err = pskb_trim_rcsum(skb, len);
1245         if (err)
1246                 kfree_skb(skb);
1247
1248         return err;
1249 }
1250
1251 /* Returns 0 on success, -EINPROGRESS if 'skb' is stolen, or other nonzero
1252  * value if 'skb' is freed.
1253  */
1254 int ovs_ct_execute(struct net *net, struct sk_buff *skb,
1255                    struct sw_flow_key *key,
1256                    const struct ovs_conntrack_info *info)
1257 {
1258         int nh_ofs;
1259         int err;
1260
1261         /* The conntrack module expects to be working at L3. */
1262         nh_ofs = skb_network_offset(skb);
1263         skb_pull_rcsum(skb, nh_ofs);
1264
1265         err = ovs_skb_network_trim(skb);
1266         if (err)
1267                 return err;
1268
1269         if (key->ip.frag != OVS_FRAG_TYPE_NONE) {
1270                 err = handle_fragments(net, key, info->zone.id, skb);
1271                 if (err)
1272                         return err;
1273         }
1274
1275         if (info->commit)
1276                 err = ovs_ct_commit(net, key, info, skb);
1277         else
1278                 err = ovs_ct_lookup(net, key, info, skb);
1279
1280         skb_push(skb, nh_ofs);
1281         skb_postpush_rcsum(skb, skb->data, nh_ofs);
1282         if (err)
1283                 kfree_skb(skb);
1284         return err;
1285 }
1286
1287 int ovs_ct_clear(struct sk_buff *skb, struct sw_flow_key *key)
1288 {
1289         if (skb_nfct(skb)) {
1290                 nf_conntrack_put(skb_nfct(skb));
1291                 nf_ct_set(skb, NULL, IP_CT_UNTRACKED);
1292                 ovs_ct_fill_key(skb, key);
1293         }
1294
1295         return 0;
1296 }
1297
1298 static int ovs_ct_add_helper(struct ovs_conntrack_info *info, const char *name,
1299                              const struct sw_flow_key *key, bool log)
1300 {
1301         struct nf_conntrack_helper *helper;
1302         struct nf_conn_help *help;
1303
1304         helper = nf_conntrack_helper_try_module_get(name, info->family,
1305                                                     key->ip.proto);
1306         if (!helper) {
1307                 OVS_NLERR(log, "Unknown helper \"%s\"", name);
1308                 return -EINVAL;
1309         }
1310
1311         help = nf_ct_helper_ext_add(info->ct, GFP_KERNEL);
1312         if (!help) {
1313                 nf_conntrack_helper_put(helper);
1314                 return -ENOMEM;
1315         }
1316
1317         rcu_assign_pointer(help->helper, helper);
1318         info->helper = helper;
1319
1320         if (info->nat)
1321                 request_module("ip_nat_%s", name);
1322
1323         return 0;
1324 }
1325
1326 #ifdef CONFIG_NF_NAT_NEEDED
1327 static int parse_nat(const struct nlattr *attr,
1328                      struct ovs_conntrack_info *info, bool log)
1329 {
1330         struct nlattr *a;
1331         int rem;
1332         bool have_ip_max = false;
1333         bool have_proto_max = false;
1334         bool ip_vers = (info->family == NFPROTO_IPV6);
1335
1336         nla_for_each_nested(a, attr, rem) {
1337                 static const int ovs_nat_attr_lens[OVS_NAT_ATTR_MAX + 1][2] = {
1338                         [OVS_NAT_ATTR_SRC] = {0, 0},
1339                         [OVS_NAT_ATTR_DST] = {0, 0},
1340                         [OVS_NAT_ATTR_IP_MIN] = {sizeof(struct in_addr),
1341                                                  sizeof(struct in6_addr)},
1342                         [OVS_NAT_ATTR_IP_MAX] = {sizeof(struct in_addr),
1343                                                  sizeof(struct in6_addr)},
1344                         [OVS_NAT_ATTR_PROTO_MIN] = {sizeof(u16), sizeof(u16)},
1345                         [OVS_NAT_ATTR_PROTO_MAX] = {sizeof(u16), sizeof(u16)},
1346                         [OVS_NAT_ATTR_PERSISTENT] = {0, 0},
1347                         [OVS_NAT_ATTR_PROTO_HASH] = {0, 0},
1348                         [OVS_NAT_ATTR_PROTO_RANDOM] = {0, 0},
1349                 };
1350                 int type = nla_type(a);
1351
1352                 if (type > OVS_NAT_ATTR_MAX) {
1353                         OVS_NLERR(log, "Unknown NAT attribute (type=%d, max=%d)",
1354                                   type, OVS_NAT_ATTR_MAX);
1355                         return -EINVAL;
1356                 }
1357
1358                 if (nla_len(a) != ovs_nat_attr_lens[type][ip_vers]) {
1359                         OVS_NLERR(log, "NAT attribute type %d has unexpected length (%d != %d)",
1360                                   type, nla_len(a),
1361                                   ovs_nat_attr_lens[type][ip_vers]);
1362                         return -EINVAL;
1363                 }
1364
1365                 switch (type) {
1366                 case OVS_NAT_ATTR_SRC:
1367                 case OVS_NAT_ATTR_DST:
1368                         if (info->nat) {
1369                                 OVS_NLERR(log, "Only one type of NAT may be specified");
1370                                 return -ERANGE;
1371                         }
1372                         info->nat |= OVS_CT_NAT;
1373                         info->nat |= ((type == OVS_NAT_ATTR_SRC)
1374                                         ? OVS_CT_SRC_NAT : OVS_CT_DST_NAT);
1375                         break;
1376
1377                 case OVS_NAT_ATTR_IP_MIN:
1378                         nla_memcpy(&info->range.min_addr, a,
1379                                    sizeof(info->range.min_addr));
1380                         info->range.flags |= NF_NAT_RANGE_MAP_IPS;
1381                         break;
1382
1383                 case OVS_NAT_ATTR_IP_MAX:
1384                         have_ip_max = true;
1385                         nla_memcpy(&info->range.max_addr, a,
1386                                    sizeof(info->range.max_addr));
1387                         info->range.flags |= NF_NAT_RANGE_MAP_IPS;
1388                         break;
1389
1390                 case OVS_NAT_ATTR_PROTO_MIN:
1391                         info->range.min_proto.all = htons(nla_get_u16(a));
1392                         info->range.flags |= NF_NAT_RANGE_PROTO_SPECIFIED;
1393                         break;
1394
1395                 case OVS_NAT_ATTR_PROTO_MAX:
1396                         have_proto_max = true;
1397                         info->range.max_proto.all = htons(nla_get_u16(a));
1398                         info->range.flags |= NF_NAT_RANGE_PROTO_SPECIFIED;
1399                         break;
1400
1401                 case OVS_NAT_ATTR_PERSISTENT:
1402                         info->range.flags |= NF_NAT_RANGE_PERSISTENT;
1403                         break;
1404
1405                 case OVS_NAT_ATTR_PROTO_HASH:
1406                         info->range.flags |= NF_NAT_RANGE_PROTO_RANDOM;
1407                         break;
1408
1409                 case OVS_NAT_ATTR_PROTO_RANDOM:
1410                         info->range.flags |= NF_NAT_RANGE_PROTO_RANDOM_FULLY;
1411                         break;
1412
1413                 default:
1414                         OVS_NLERR(log, "Unknown nat attribute (%d)", type);
1415                         return -EINVAL;
1416                 }
1417         }
1418
1419         if (rem > 0) {
1420                 OVS_NLERR(log, "NAT attribute has %d unknown bytes", rem);
1421                 return -EINVAL;
1422         }
1423         if (!info->nat) {
1424                 /* Do not allow flags if no type is given. */
1425                 if (info->range.flags) {
1426                         OVS_NLERR(log,
1427                                   "NAT flags may be given only when NAT range (SRC or DST) is also specified."
1428                                   );
1429                         return -EINVAL;
1430                 }
1431                 info->nat = OVS_CT_NAT;   /* NAT existing connections. */
1432         } else if (!info->commit) {
1433                 OVS_NLERR(log,
1434                           "NAT attributes may be specified only when CT COMMIT flag is also specified."
1435                           );
1436                 return -EINVAL;
1437         }
1438         /* Allow missing IP_MAX. */
1439         if (info->range.flags & NF_NAT_RANGE_MAP_IPS && !have_ip_max) {
1440                 memcpy(&info->range.max_addr, &info->range.min_addr,
1441                        sizeof(info->range.max_addr));
1442         }
1443         /* Allow missing PROTO_MAX. */
1444         if (info->range.flags & NF_NAT_RANGE_PROTO_SPECIFIED &&
1445             !have_proto_max) {
1446                 info->range.max_proto.all = info->range.min_proto.all;
1447         }
1448         return 0;
1449 }
1450 #endif
1451
1452 static const struct ovs_ct_len_tbl ovs_ct_attr_lens[OVS_CT_ATTR_MAX + 1] = {
1453         [OVS_CT_ATTR_COMMIT]    = { .minlen = 0, .maxlen = 0 },
1454         [OVS_CT_ATTR_FORCE_COMMIT]      = { .minlen = 0, .maxlen = 0 },
1455         [OVS_CT_ATTR_ZONE]      = { .minlen = sizeof(u16),
1456                                     .maxlen = sizeof(u16) },
1457         [OVS_CT_ATTR_MARK]      = { .minlen = sizeof(struct md_mark),
1458                                     .maxlen = sizeof(struct md_mark) },
1459         [OVS_CT_ATTR_LABELS]    = { .minlen = sizeof(struct md_labels),
1460                                     .maxlen = sizeof(struct md_labels) },
1461         [OVS_CT_ATTR_HELPER]    = { .minlen = 1,
1462                                     .maxlen = NF_CT_HELPER_NAME_LEN },
1463 #ifdef CONFIG_NF_NAT_NEEDED
1464         /* NAT length is checked when parsing the nested attributes. */
1465         [OVS_CT_ATTR_NAT]       = { .minlen = 0, .maxlen = INT_MAX },
1466 #endif
1467         [OVS_CT_ATTR_EVENTMASK] = { .minlen = sizeof(u32),
1468                                     .maxlen = sizeof(u32) },
1469 };
1470
1471 static int parse_ct(const struct nlattr *attr, struct ovs_conntrack_info *info,
1472                     const char **helper, bool log)
1473 {
1474         struct nlattr *a;
1475         int rem;
1476
1477         nla_for_each_nested(a, attr, rem) {
1478                 int type = nla_type(a);
1479                 int maxlen;
1480                 int minlen;
1481
1482                 if (type > OVS_CT_ATTR_MAX) {
1483                         OVS_NLERR(log,
1484                                   "Unknown conntrack attr (type=%d, max=%d)",
1485                                   type, OVS_CT_ATTR_MAX);
1486                         return -EINVAL;
1487                 }
1488
1489                 maxlen = ovs_ct_attr_lens[type].maxlen;
1490                 minlen = ovs_ct_attr_lens[type].minlen;
1491                 if (nla_len(a) < minlen || nla_len(a) > maxlen) {
1492                         OVS_NLERR(log,
1493                                   "Conntrack attr type has unexpected length (type=%d, length=%d, expected=%d)",
1494                                   type, nla_len(a), maxlen);
1495                         return -EINVAL;
1496                 }
1497
1498                 switch (type) {
1499                 case OVS_CT_ATTR_FORCE_COMMIT:
1500                         info->force = true;
1501                         /* fall through. */
1502                 case OVS_CT_ATTR_COMMIT:
1503                         info->commit = true;
1504                         break;
1505 #ifdef CONFIG_NF_CONNTRACK_ZONES
1506                 case OVS_CT_ATTR_ZONE:
1507                         info->zone.id = nla_get_u16(a);
1508                         break;
1509 #endif
1510 #ifdef CONFIG_NF_CONNTRACK_MARK
1511                 case OVS_CT_ATTR_MARK: {
1512                         struct md_mark *mark = nla_data(a);
1513
1514                         if (!mark->mask) {
1515                                 OVS_NLERR(log, "ct_mark mask cannot be 0");
1516                                 return -EINVAL;
1517                         }
1518                         info->mark = *mark;
1519                         break;
1520                 }
1521 #endif
1522 #ifdef CONFIG_NF_CONNTRACK_LABELS
1523                 case OVS_CT_ATTR_LABELS: {
1524                         struct md_labels *labels = nla_data(a);
1525
1526                         if (!labels_nonzero(&labels->mask)) {
1527                                 OVS_NLERR(log, "ct_labels mask cannot be 0");
1528                                 return -EINVAL;
1529                         }
1530                         info->labels = *labels;
1531                         break;
1532                 }
1533 #endif
1534                 case OVS_CT_ATTR_HELPER:
1535                         *helper = nla_data(a);
1536                         if (!memchr(*helper, '\0', nla_len(a))) {
1537                                 OVS_NLERR(log, "Invalid conntrack helper");
1538                                 return -EINVAL;
1539                         }
1540                         break;
1541 #ifdef CONFIG_NF_NAT_NEEDED
1542                 case OVS_CT_ATTR_NAT: {
1543                         int err = parse_nat(a, info, log);
1544
1545                         if (err)
1546                                 return err;
1547                         break;
1548                 }
1549 #endif
1550                 case OVS_CT_ATTR_EVENTMASK:
1551                         info->have_eventmask = true;
1552                         info->eventmask = nla_get_u32(a);
1553                         break;
1554
1555                 default:
1556                         OVS_NLERR(log, "Unknown conntrack attr (%d)",
1557                                   type);
1558                         return -EINVAL;
1559                 }
1560         }
1561
1562 #ifdef CONFIG_NF_CONNTRACK_MARK
1563         if (!info->commit && info->mark.mask) {
1564                 OVS_NLERR(log,
1565                           "Setting conntrack mark requires 'commit' flag.");
1566                 return -EINVAL;
1567         }
1568 #endif
1569 #ifdef CONFIG_NF_CONNTRACK_LABELS
1570         if (!info->commit && labels_nonzero(&info->labels.mask)) {
1571                 OVS_NLERR(log,
1572                           "Setting conntrack labels requires 'commit' flag.");
1573                 return -EINVAL;
1574         }
1575 #endif
1576         if (rem > 0) {
1577                 OVS_NLERR(log, "Conntrack attr has %d unknown bytes", rem);
1578                 return -EINVAL;
1579         }
1580
1581         return 0;
1582 }
1583
1584 bool ovs_ct_verify(struct net *net, enum ovs_key_attr attr)
1585 {
1586         if (attr == OVS_KEY_ATTR_CT_STATE)
1587                 return true;
1588         if (IS_ENABLED(CONFIG_NF_CONNTRACK_ZONES) &&
1589             attr == OVS_KEY_ATTR_CT_ZONE)
1590                 return true;
1591         if (IS_ENABLED(CONFIG_NF_CONNTRACK_MARK) &&
1592             attr == OVS_KEY_ATTR_CT_MARK)
1593                 return true;
1594         if (IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS) &&
1595             attr == OVS_KEY_ATTR_CT_LABELS) {
1596                 struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
1597
1598                 return ovs_net->xt_label;
1599         }
1600
1601         return false;
1602 }
1603
1604 int ovs_ct_copy_action(struct net *net, const struct nlattr *attr,
1605                        const struct sw_flow_key *key,
1606                        struct sw_flow_actions **sfa,  bool log)
1607 {
1608         struct ovs_conntrack_info ct_info;
1609         const char *helper = NULL;
1610         u16 family;
1611         int err;
1612
1613         family = key_to_nfproto(key);
1614         if (family == NFPROTO_UNSPEC) {
1615                 OVS_NLERR(log, "ct family unspecified");
1616                 return -EINVAL;
1617         }
1618
1619         memset(&ct_info, 0, sizeof(ct_info));
1620         ct_info.family = family;
1621
1622         nf_ct_zone_init(&ct_info.zone, NF_CT_DEFAULT_ZONE_ID,
1623                         NF_CT_DEFAULT_ZONE_DIR, 0);
1624
1625         err = parse_ct(attr, &ct_info, &helper, log);
1626         if (err)
1627                 return err;
1628
1629         /* Set up template for tracking connections in specific zones. */
1630         ct_info.ct = nf_ct_tmpl_alloc(net, &ct_info.zone, GFP_KERNEL);
1631         if (!ct_info.ct) {
1632                 OVS_NLERR(log, "Failed to allocate conntrack template");
1633                 return -ENOMEM;
1634         }
1635         if (helper) {
1636                 err = ovs_ct_add_helper(&ct_info, helper, key, log);
1637                 if (err)
1638                         goto err_free_ct;
1639         }
1640
1641         err = ovs_nla_add_action(sfa, OVS_ACTION_ATTR_CT, &ct_info,
1642                                  sizeof(ct_info), log);
1643         if (err)
1644                 goto err_free_ct;
1645
1646         __set_bit(IPS_CONFIRMED_BIT, &ct_info.ct->status);
1647         nf_conntrack_get(&ct_info.ct->ct_general);
1648         return 0;
1649 err_free_ct:
1650         __ovs_ct_free_action(&ct_info);
1651         return err;
1652 }
1653
1654 #ifdef CONFIG_NF_NAT_NEEDED
1655 static bool ovs_ct_nat_to_attr(const struct ovs_conntrack_info *info,
1656                                struct sk_buff *skb)
1657 {
1658         struct nlattr *start;
1659
1660         start = nla_nest_start(skb, OVS_CT_ATTR_NAT);
1661         if (!start)
1662                 return false;
1663
1664         if (info->nat & OVS_CT_SRC_NAT) {
1665                 if (nla_put_flag(skb, OVS_NAT_ATTR_SRC))
1666                         return false;
1667         } else if (info->nat & OVS_CT_DST_NAT) {
1668                 if (nla_put_flag(skb, OVS_NAT_ATTR_DST))
1669                         return false;
1670         } else {
1671                 goto out;
1672         }
1673
1674         if (info->range.flags & NF_NAT_RANGE_MAP_IPS) {
1675                 if (IS_ENABLED(CONFIG_NF_NAT_IPV4) &&
1676                     info->family == NFPROTO_IPV4) {
1677                         if (nla_put_in_addr(skb, OVS_NAT_ATTR_IP_MIN,
1678                                             info->range.min_addr.ip) ||
1679                             (info->range.max_addr.ip
1680                              != info->range.min_addr.ip &&
1681                              (nla_put_in_addr(skb, OVS_NAT_ATTR_IP_MAX,
1682                                               info->range.max_addr.ip))))
1683                                 return false;
1684                 } else if (IS_ENABLED(CONFIG_NF_NAT_IPV6) &&
1685                            info->family == NFPROTO_IPV6) {
1686                         if (nla_put_in6_addr(skb, OVS_NAT_ATTR_IP_MIN,
1687                                              &info->range.min_addr.in6) ||
1688                             (memcmp(&info->range.max_addr.in6,
1689                                     &info->range.min_addr.in6,
1690                                     sizeof(info->range.max_addr.in6)) &&
1691                              (nla_put_in6_addr(skb, OVS_NAT_ATTR_IP_MAX,
1692                                                &info->range.max_addr.in6))))
1693                                 return false;
1694                 } else {
1695                         return false;
1696                 }
1697         }
1698         if (info->range.flags & NF_NAT_RANGE_PROTO_SPECIFIED &&
1699             (nla_put_u16(skb, OVS_NAT_ATTR_PROTO_MIN,
1700                          ntohs(info->range.min_proto.all)) ||
1701              (info->range.max_proto.all != info->range.min_proto.all &&
1702               nla_put_u16(skb, OVS_NAT_ATTR_PROTO_MAX,
1703                           ntohs(info->range.max_proto.all)))))
1704                 return false;
1705
1706         if (info->range.flags & NF_NAT_RANGE_PERSISTENT &&
1707             nla_put_flag(skb, OVS_NAT_ATTR_PERSISTENT))
1708                 return false;
1709         if (info->range.flags & NF_NAT_RANGE_PROTO_RANDOM &&
1710             nla_put_flag(skb, OVS_NAT_ATTR_PROTO_HASH))
1711                 return false;
1712         if (info->range.flags & NF_NAT_RANGE_PROTO_RANDOM_FULLY &&
1713             nla_put_flag(skb, OVS_NAT_ATTR_PROTO_RANDOM))
1714                 return false;
1715 out:
1716         nla_nest_end(skb, start);
1717
1718         return true;
1719 }
1720 #endif
1721
1722 int ovs_ct_action_to_attr(const struct ovs_conntrack_info *ct_info,
1723                           struct sk_buff *skb)
1724 {
1725         struct nlattr *start;
1726
1727         start = nla_nest_start(skb, OVS_ACTION_ATTR_CT);
1728         if (!start)
1729                 return -EMSGSIZE;
1730
1731         if (ct_info->commit && nla_put_flag(skb, ct_info->force
1732                                             ? OVS_CT_ATTR_FORCE_COMMIT
1733                                             : OVS_CT_ATTR_COMMIT))
1734                 return -EMSGSIZE;
1735         if (IS_ENABLED(CONFIG_NF_CONNTRACK_ZONES) &&
1736             nla_put_u16(skb, OVS_CT_ATTR_ZONE, ct_info->zone.id))
1737                 return -EMSGSIZE;
1738         if (IS_ENABLED(CONFIG_NF_CONNTRACK_MARK) && ct_info->mark.mask &&
1739             nla_put(skb, OVS_CT_ATTR_MARK, sizeof(ct_info->mark),
1740                     &ct_info->mark))
1741                 return -EMSGSIZE;
1742         if (IS_ENABLED(CONFIG_NF_CONNTRACK_LABELS) &&
1743             labels_nonzero(&ct_info->labels.mask) &&
1744             nla_put(skb, OVS_CT_ATTR_LABELS, sizeof(ct_info->labels),
1745                     &ct_info->labels))
1746                 return -EMSGSIZE;
1747         if (ct_info->helper) {
1748                 if (nla_put_string(skb, OVS_CT_ATTR_HELPER,
1749                                    ct_info->helper->name))
1750                         return -EMSGSIZE;
1751         }
1752         if (ct_info->have_eventmask &&
1753             nla_put_u32(skb, OVS_CT_ATTR_EVENTMASK, ct_info->eventmask))
1754                 return -EMSGSIZE;
1755
1756 #ifdef CONFIG_NF_NAT_NEEDED
1757         if (ct_info->nat && !ovs_ct_nat_to_attr(ct_info, skb))
1758                 return -EMSGSIZE;
1759 #endif
1760         nla_nest_end(skb, start);
1761
1762         return 0;
1763 }
1764
1765 void ovs_ct_free_action(const struct nlattr *a)
1766 {
1767         struct ovs_conntrack_info *ct_info = nla_data(a);
1768
1769         __ovs_ct_free_action(ct_info);
1770 }
1771
1772 static void __ovs_ct_free_action(struct ovs_conntrack_info *ct_info)
1773 {
1774         if (ct_info->helper)
1775                 nf_conntrack_helper_put(ct_info->helper);
1776         if (ct_info->ct)
1777                 nf_ct_tmpl_free(ct_info->ct);
1778 }
1779
1780 #if     IS_ENABLED(CONFIG_NETFILTER_CONNCOUNT)
1781 static int ovs_ct_limit_init(struct net *net, struct ovs_net *ovs_net)
1782 {
1783         int i, err;
1784
1785         ovs_net->ct_limit_info = kmalloc(sizeof(*ovs_net->ct_limit_info),
1786                                          GFP_KERNEL);
1787         if (!ovs_net->ct_limit_info)
1788                 return -ENOMEM;
1789
1790         ovs_net->ct_limit_info->default_limit = OVS_CT_LIMIT_DEFAULT;
1791         ovs_net->ct_limit_info->limits =
1792                 kmalloc_array(CT_LIMIT_HASH_BUCKETS, sizeof(struct hlist_head),
1793                               GFP_KERNEL);
1794         if (!ovs_net->ct_limit_info->limits) {
1795                 kfree(ovs_net->ct_limit_info);
1796                 return -ENOMEM;
1797         }
1798
1799         for (i = 0; i < CT_LIMIT_HASH_BUCKETS; i++)
1800                 INIT_HLIST_HEAD(&ovs_net->ct_limit_info->limits[i]);
1801
1802         ovs_net->ct_limit_info->data =
1803                 nf_conncount_init(net, NFPROTO_INET, sizeof(u32));
1804
1805         if (IS_ERR(ovs_net->ct_limit_info->data)) {
1806                 err = PTR_ERR(ovs_net->ct_limit_info->data);
1807                 kfree(ovs_net->ct_limit_info->limits);
1808                 kfree(ovs_net->ct_limit_info);
1809                 pr_err("openvswitch: failed to init nf_conncount %d\n", err);
1810                 return err;
1811         }
1812         return 0;
1813 }
1814
1815 static void ovs_ct_limit_exit(struct net *net, struct ovs_net *ovs_net)
1816 {
1817         const struct ovs_ct_limit_info *info = ovs_net->ct_limit_info;
1818         int i;
1819
1820         nf_conncount_destroy(net, NFPROTO_INET, info->data);
1821         for (i = 0; i < CT_LIMIT_HASH_BUCKETS; ++i) {
1822                 struct hlist_head *head = &info->limits[i];
1823                 struct ovs_ct_limit *ct_limit;
1824
1825                 hlist_for_each_entry_rcu(ct_limit, head, hlist_node)
1826                         kfree_rcu(ct_limit, rcu);
1827         }
1828         kfree(ovs_net->ct_limit_info->limits);
1829         kfree(ovs_net->ct_limit_info);
1830 }
1831
1832 static struct sk_buff *
1833 ovs_ct_limit_cmd_reply_start(struct genl_info *info, u8 cmd,
1834                              struct ovs_header **ovs_reply_header)
1835 {
1836         struct ovs_header *ovs_header = info->userhdr;
1837         struct sk_buff *skb;
1838
1839         skb = genlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
1840         if (!skb)
1841                 return ERR_PTR(-ENOMEM);
1842
1843         *ovs_reply_header = genlmsg_put(skb, info->snd_portid,
1844                                         info->snd_seq,
1845                                         &dp_ct_limit_genl_family, 0, cmd);
1846
1847         if (!*ovs_reply_header) {
1848                 nlmsg_free(skb);
1849                 return ERR_PTR(-EMSGSIZE);
1850         }
1851         (*ovs_reply_header)->dp_ifindex = ovs_header->dp_ifindex;
1852
1853         return skb;
1854 }
1855
1856 static bool check_zone_id(int zone_id, u16 *pzone)
1857 {
1858         if (zone_id >= 0 && zone_id <= 65535) {
1859                 *pzone = (u16)zone_id;
1860                 return true;
1861         }
1862         return false;
1863 }
1864
1865 static int ovs_ct_limit_set_zone_limit(struct nlattr *nla_zone_limit,
1866                                        struct ovs_ct_limit_info *info)
1867 {
1868         struct ovs_zone_limit *zone_limit;
1869         int rem;
1870         u16 zone;
1871
1872         rem = NLA_ALIGN(nla_len(nla_zone_limit));
1873         zone_limit = (struct ovs_zone_limit *)nla_data(nla_zone_limit);
1874
1875         while (rem >= sizeof(*zone_limit)) {
1876                 if (unlikely(zone_limit->zone_id ==
1877                                 OVS_ZONE_LIMIT_DEFAULT_ZONE)) {
1878                         ovs_lock();
1879                         info->default_limit = zone_limit->limit;
1880                         ovs_unlock();
1881                 } else if (unlikely(!check_zone_id(
1882                                 zone_limit->zone_id, &zone))) {
1883                         OVS_NLERR(true, "zone id is out of range");
1884                 } else {
1885                         struct ovs_ct_limit *ct_limit;
1886
1887                         ct_limit = kmalloc(sizeof(*ct_limit), GFP_KERNEL);
1888                         if (!ct_limit)
1889                                 return -ENOMEM;
1890
1891                         ct_limit->zone = zone;
1892                         ct_limit->limit = zone_limit->limit;
1893
1894                         ovs_lock();
1895                         ct_limit_set(info, ct_limit);
1896                         ovs_unlock();
1897                 }
1898                 rem -= NLA_ALIGN(sizeof(*zone_limit));
1899                 zone_limit = (struct ovs_zone_limit *)((u8 *)zone_limit +
1900                                 NLA_ALIGN(sizeof(*zone_limit)));
1901         }
1902
1903         if (rem)
1904                 OVS_NLERR(true, "set zone limit has %d unknown bytes", rem);
1905
1906         return 0;
1907 }
1908
1909 static int ovs_ct_limit_del_zone_limit(struct nlattr *nla_zone_limit,
1910                                        struct ovs_ct_limit_info *info)
1911 {
1912         struct ovs_zone_limit *zone_limit;
1913         int rem;
1914         u16 zone;
1915
1916         rem = NLA_ALIGN(nla_len(nla_zone_limit));
1917         zone_limit = (struct ovs_zone_limit *)nla_data(nla_zone_limit);
1918
1919         while (rem >= sizeof(*zone_limit)) {
1920                 if (unlikely(zone_limit->zone_id ==
1921                                 OVS_ZONE_LIMIT_DEFAULT_ZONE)) {
1922                         ovs_lock();
1923                         info->default_limit = OVS_CT_LIMIT_DEFAULT;
1924                         ovs_unlock();
1925                 } else if (unlikely(!check_zone_id(
1926                                 zone_limit->zone_id, &zone))) {
1927                         OVS_NLERR(true, "zone id is out of range");
1928                 } else {
1929                         ovs_lock();
1930                         ct_limit_del(info, zone);
1931                         ovs_unlock();
1932                 }
1933                 rem -= NLA_ALIGN(sizeof(*zone_limit));
1934                 zone_limit = (struct ovs_zone_limit *)((u8 *)zone_limit +
1935                                 NLA_ALIGN(sizeof(*zone_limit)));
1936         }
1937
1938         if (rem)
1939                 OVS_NLERR(true, "del zone limit has %d unknown bytes", rem);
1940
1941         return 0;
1942 }
1943
1944 static int ovs_ct_limit_get_default_limit(struct ovs_ct_limit_info *info,
1945                                           struct sk_buff *reply)
1946 {
1947         struct ovs_zone_limit zone_limit;
1948         int err;
1949
1950         zone_limit.zone_id = OVS_ZONE_LIMIT_DEFAULT_ZONE;
1951         zone_limit.limit = info->default_limit;
1952         err = nla_put_nohdr(reply, sizeof(zone_limit), &zone_limit);
1953         if (err)
1954                 return err;
1955
1956         return 0;
1957 }
1958
1959 static int __ovs_ct_limit_get_zone_limit(struct net *net,
1960                                          struct nf_conncount_data *data,
1961                                          u16 zone_id, u32 limit,
1962                                          struct sk_buff *reply)
1963 {
1964         struct nf_conntrack_zone ct_zone;
1965         struct ovs_zone_limit zone_limit;
1966         u32 conncount_key = zone_id;
1967
1968         zone_limit.zone_id = zone_id;
1969         zone_limit.limit = limit;
1970         nf_ct_zone_init(&ct_zone, zone_id, NF_CT_DEFAULT_ZONE_DIR, 0);
1971
1972         zone_limit.count = nf_conncount_count(net, data, &conncount_key, NULL,
1973                                               &ct_zone);
1974         return nla_put_nohdr(reply, sizeof(zone_limit), &zone_limit);
1975 }
1976
1977 static int ovs_ct_limit_get_zone_limit(struct net *net,
1978                                        struct nlattr *nla_zone_limit,
1979                                        struct ovs_ct_limit_info *info,
1980                                        struct sk_buff *reply)
1981 {
1982         struct ovs_zone_limit *zone_limit;
1983         int rem, err;
1984         u32 limit;
1985         u16 zone;
1986
1987         rem = NLA_ALIGN(nla_len(nla_zone_limit));
1988         zone_limit = (struct ovs_zone_limit *)nla_data(nla_zone_limit);
1989
1990         while (rem >= sizeof(*zone_limit)) {
1991                 if (unlikely(zone_limit->zone_id ==
1992                                 OVS_ZONE_LIMIT_DEFAULT_ZONE)) {
1993                         err = ovs_ct_limit_get_default_limit(info, reply);
1994                         if (err)
1995                                 return err;
1996                 } else if (unlikely(!check_zone_id(zone_limit->zone_id,
1997                                                         &zone))) {
1998                         OVS_NLERR(true, "zone id is out of range");
1999                 } else {
2000                         rcu_read_lock();
2001                         limit = ct_limit_get(info, zone);
2002                         rcu_read_unlock();
2003
2004                         err = __ovs_ct_limit_get_zone_limit(
2005                                 net, info->data, zone, limit, reply);
2006                         if (err)
2007                                 return err;
2008                 }
2009                 rem -= NLA_ALIGN(sizeof(*zone_limit));
2010                 zone_limit = (struct ovs_zone_limit *)((u8 *)zone_limit +
2011                                 NLA_ALIGN(sizeof(*zone_limit)));
2012         }
2013
2014         if (rem)
2015                 OVS_NLERR(true, "get zone limit has %d unknown bytes", rem);
2016
2017         return 0;
2018 }
2019
2020 static int ovs_ct_limit_get_all_zone_limit(struct net *net,
2021                                            struct ovs_ct_limit_info *info,
2022                                            struct sk_buff *reply)
2023 {
2024         struct ovs_ct_limit *ct_limit;
2025         struct hlist_head *head;
2026         int i, err = 0;
2027
2028         err = ovs_ct_limit_get_default_limit(info, reply);
2029         if (err)
2030                 return err;
2031
2032         rcu_read_lock();
2033         for (i = 0; i < CT_LIMIT_HASH_BUCKETS; ++i) {
2034                 head = &info->limits[i];
2035                 hlist_for_each_entry_rcu(ct_limit, head, hlist_node) {
2036                         err = __ovs_ct_limit_get_zone_limit(net, info->data,
2037                                 ct_limit->zone, ct_limit->limit, reply);
2038                         if (err)
2039                                 goto exit_err;
2040                 }
2041         }
2042
2043 exit_err:
2044         rcu_read_unlock();
2045         return err;
2046 }
2047
2048 static int ovs_ct_limit_cmd_set(struct sk_buff *skb, struct genl_info *info)
2049 {
2050         struct nlattr **a = info->attrs;
2051         struct sk_buff *reply;
2052         struct ovs_header *ovs_reply_header;
2053         struct ovs_net *ovs_net = net_generic(sock_net(skb->sk), ovs_net_id);
2054         struct ovs_ct_limit_info *ct_limit_info = ovs_net->ct_limit_info;
2055         int err;
2056
2057         reply = ovs_ct_limit_cmd_reply_start(info, OVS_CT_LIMIT_CMD_SET,
2058                                              &ovs_reply_header);
2059         if (IS_ERR(reply))
2060                 return PTR_ERR(reply);
2061
2062         if (!a[OVS_CT_LIMIT_ATTR_ZONE_LIMIT]) {
2063                 err = -EINVAL;
2064                 goto exit_err;
2065         }
2066
2067         err = ovs_ct_limit_set_zone_limit(a[OVS_CT_LIMIT_ATTR_ZONE_LIMIT],
2068                                           ct_limit_info);
2069         if (err)
2070                 goto exit_err;
2071
2072         static_branch_enable(&ovs_ct_limit_enabled);
2073
2074         genlmsg_end(reply, ovs_reply_header);
2075         return genlmsg_reply(reply, info);
2076
2077 exit_err:
2078         nlmsg_free(reply);
2079         return err;
2080 }
2081
2082 static int ovs_ct_limit_cmd_del(struct sk_buff *skb, struct genl_info *info)
2083 {
2084         struct nlattr **a = info->attrs;
2085         struct sk_buff *reply;
2086         struct ovs_header *ovs_reply_header;
2087         struct ovs_net *ovs_net = net_generic(sock_net(skb->sk), ovs_net_id);
2088         struct ovs_ct_limit_info *ct_limit_info = ovs_net->ct_limit_info;
2089         int err;
2090
2091         reply = ovs_ct_limit_cmd_reply_start(info, OVS_CT_LIMIT_CMD_DEL,
2092                                              &ovs_reply_header);
2093         if (IS_ERR(reply))
2094                 return PTR_ERR(reply);
2095
2096         if (!a[OVS_CT_LIMIT_ATTR_ZONE_LIMIT]) {
2097                 err = -EINVAL;
2098                 goto exit_err;
2099         }
2100
2101         err = ovs_ct_limit_del_zone_limit(a[OVS_CT_LIMIT_ATTR_ZONE_LIMIT],
2102                                           ct_limit_info);
2103         if (err)
2104                 goto exit_err;
2105
2106         genlmsg_end(reply, ovs_reply_header);
2107         return genlmsg_reply(reply, info);
2108
2109 exit_err:
2110         nlmsg_free(reply);
2111         return err;
2112 }
2113
2114 static int ovs_ct_limit_cmd_get(struct sk_buff *skb, struct genl_info *info)
2115 {
2116         struct nlattr **a = info->attrs;
2117         struct nlattr *nla_reply;
2118         struct sk_buff *reply;
2119         struct ovs_header *ovs_reply_header;
2120         struct net *net = sock_net(skb->sk);
2121         struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
2122         struct ovs_ct_limit_info *ct_limit_info = ovs_net->ct_limit_info;
2123         int err;
2124
2125         reply = ovs_ct_limit_cmd_reply_start(info, OVS_CT_LIMIT_CMD_GET,
2126                                              &ovs_reply_header);
2127         if (IS_ERR(reply))
2128                 return PTR_ERR(reply);
2129
2130         nla_reply = nla_nest_start(reply, OVS_CT_LIMIT_ATTR_ZONE_LIMIT);
2131
2132         if (a[OVS_CT_LIMIT_ATTR_ZONE_LIMIT]) {
2133                 err = ovs_ct_limit_get_zone_limit(
2134                         net, a[OVS_CT_LIMIT_ATTR_ZONE_LIMIT], ct_limit_info,
2135                         reply);
2136                 if (err)
2137                         goto exit_err;
2138         } else {
2139                 err = ovs_ct_limit_get_all_zone_limit(net, ct_limit_info,
2140                                                       reply);
2141                 if (err)
2142                         goto exit_err;
2143         }
2144
2145         nla_nest_end(reply, nla_reply);
2146         genlmsg_end(reply, ovs_reply_header);
2147         return genlmsg_reply(reply, info);
2148
2149 exit_err:
2150         nlmsg_free(reply);
2151         return err;
2152 }
2153
2154 static struct genl_ops ct_limit_genl_ops[] = {
2155         { .cmd = OVS_CT_LIMIT_CMD_SET,
2156                 .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN
2157                                            * privilege. */
2158                 .policy = ct_limit_policy,
2159                 .doit = ovs_ct_limit_cmd_set,
2160         },
2161         { .cmd = OVS_CT_LIMIT_CMD_DEL,
2162                 .flags = GENL_ADMIN_PERM, /* Requires CAP_NET_ADMIN
2163                                            * privilege. */
2164                 .policy = ct_limit_policy,
2165                 .doit = ovs_ct_limit_cmd_del,
2166         },
2167         { .cmd = OVS_CT_LIMIT_CMD_GET,
2168                 .flags = 0,               /* OK for unprivileged users. */
2169                 .policy = ct_limit_policy,
2170                 .doit = ovs_ct_limit_cmd_get,
2171         },
2172 };
2173
2174 static const struct genl_multicast_group ovs_ct_limit_multicast_group = {
2175         .name = OVS_CT_LIMIT_MCGROUP,
2176 };
2177
2178 struct genl_family dp_ct_limit_genl_family __ro_after_init = {
2179         .hdrsize = sizeof(struct ovs_header),
2180         .name = OVS_CT_LIMIT_FAMILY,
2181         .version = OVS_CT_LIMIT_VERSION,
2182         .maxattr = OVS_CT_LIMIT_ATTR_MAX,
2183         .netnsok = true,
2184         .parallel_ops = true,
2185         .ops = ct_limit_genl_ops,
2186         .n_ops = ARRAY_SIZE(ct_limit_genl_ops),
2187         .mcgrps = &ovs_ct_limit_multicast_group,
2188         .n_mcgrps = 1,
2189         .module = THIS_MODULE,
2190 };
2191 #endif
2192
2193 int ovs_ct_init(struct net *net)
2194 {
2195         unsigned int n_bits = sizeof(struct ovs_key_ct_labels) * BITS_PER_BYTE;
2196         struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
2197
2198         if (nf_connlabels_get(net, n_bits - 1)) {
2199                 ovs_net->xt_label = false;
2200                 OVS_NLERR(true, "Failed to set connlabel length");
2201         } else {
2202                 ovs_net->xt_label = true;
2203         }
2204
2205 #if     IS_ENABLED(CONFIG_NETFILTER_CONNCOUNT)
2206         return ovs_ct_limit_init(net, ovs_net);
2207 #else
2208         return 0;
2209 #endif
2210 }
2211
2212 void ovs_ct_exit(struct net *net)
2213 {
2214         struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
2215
2216 #if     IS_ENABLED(CONFIG_NETFILTER_CONNCOUNT)
2217         ovs_ct_limit_exit(net, ovs_net);
2218 #endif
2219
2220         if (ovs_net->xt_label)
2221                 nf_connlabels_put(net);
2222 }