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