xref: /linux/net/openvswitch/datapath.c (revision 33f016b23a219fe034213849b51436b8e79df251)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (c) 2007-2014 Nicira, Inc.
4  */
5 
6 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
7 
8 #include <linux/init.h>
9 #include <linux/module.h>
10 #include <linux/if_arp.h>
11 #include <linux/if_vlan.h>
12 #include <linux/in.h>
13 #include <linux/ip.h>
14 #include <linux/jhash.h>
15 #include <linux/delay.h>
16 #include <linux/time.h>
17 #include <linux/etherdevice.h>
18 #include <linux/kernel.h>
19 #include <linux/kthread.h>
20 #include <linux/mutex.h>
21 #include <linux/percpu.h>
22 #include <linux/rcupdate.h>
23 #include <linux/tcp.h>
24 #include <linux/udp.h>
25 #include <linux/ethtool.h>
26 #include <linux/wait.h>
27 #include <asm/div64.h>
28 #include <linux/highmem.h>
29 #include <linux/netfilter_bridge.h>
30 #include <linux/netfilter_ipv4.h>
31 #include <linux/inetdevice.h>
32 #include <linux/list.h>
33 #include <linux/openvswitch.h>
34 #include <linux/rculist.h>
35 #include <linux/dmi.h>
36 #include <net/genetlink.h>
37 #include <net/gso.h>
38 #include <net/net_namespace.h>
39 #include <net/netns/generic.h>
40 #include <net/pkt_cls.h>
41 
42 #include "datapath.h"
43 #include "drop.h"
44 #include "flow.h"
45 #include "flow_table.h"
46 #include "flow_netlink.h"
47 #include "meter.h"
48 #include "openvswitch_trace.h"
49 #include "vport-internal_dev.h"
50 #include "vport-netdev.h"
51 
52 unsigned int ovs_net_id __read_mostly;
53 
54 static struct genl_family dp_packet_genl_family;
55 static struct genl_family dp_flow_genl_family;
56 static struct genl_family dp_datapath_genl_family;
57 
58 static const struct nla_policy flow_policy[];
59 
60 static const struct genl_multicast_group ovs_dp_flow_multicast_group = {
61 	.name = OVS_FLOW_MCGROUP,
62 };
63 
64 static const struct genl_multicast_group ovs_dp_datapath_multicast_group = {
65 	.name = OVS_DATAPATH_MCGROUP,
66 };
67 
68 static const struct genl_multicast_group ovs_dp_vport_multicast_group = {
69 	.name = OVS_VPORT_MCGROUP,
70 };
71 
72 /* Check if need to build a reply message.
73  * OVS userspace sets the NLM_F_ECHO flag if it needs the reply. */
74 static bool ovs_must_notify(struct genl_family *family, struct genl_info *info,
75 			    unsigned int group)
76 {
77 	return info->nlhdr->nlmsg_flags & NLM_F_ECHO ||
78 	       genl_has_listeners(family, genl_info_net(info), group);
79 }
80 
81 static void ovs_notify(struct genl_family *family,
82 		       struct sk_buff *skb, struct genl_info *info)
83 {
84 	genl_notify(family, skb, info, 0, GFP_KERNEL);
85 }
86 
87 /**
88  * DOC: Locking:
89  *
90  * All writes e.g. Writes to device state (add/remove datapath, port, set
91  * operations on vports, etc.), Writes to other state (flow table
92  * modifications, set miscellaneous datapath parameters, etc.) are protected
93  * by ovs_lock.
94  *
95  * Reads are protected by RCU.
96  *
97  * There are a few special cases (mostly stats) that have their own
98  * synchronization but they nest under all of above and don't interact with
99  * each other.
100  *
101  * The RTNL lock nests inside ovs_mutex.
102  */
103 
104 static DEFINE_MUTEX(ovs_mutex);
105 
106 void ovs_lock(void)
107 {
108 	mutex_lock(&ovs_mutex);
109 }
110 
111 void ovs_unlock(void)
112 {
113 	mutex_unlock(&ovs_mutex);
114 }
115 
116 #ifdef CONFIG_LOCKDEP
117 int lockdep_ovsl_is_held(void)
118 {
119 	if (debug_locks)
120 		return lockdep_is_held(&ovs_mutex);
121 	else
122 		return 1;
123 }
124 #endif
125 
126 static struct vport *new_vport(const struct vport_parms *);
127 static int queue_gso_packets(struct datapath *dp, struct sk_buff *,
128 			     const struct sw_flow_key *,
129 			     const struct dp_upcall_info *,
130 			     uint32_t cutlen);
131 static int queue_userspace_packet(struct datapath *dp, struct sk_buff *,
132 				  const struct sw_flow_key *,
133 				  const struct dp_upcall_info *,
134 				  uint32_t cutlen);
135 
136 static void ovs_dp_masks_rebalance(struct work_struct *work);
137 
138 static int ovs_dp_set_upcall_portids(struct datapath *, const struct nlattr *);
139 
140 /* Must be called with rcu_read_lock or ovs_mutex. */
141 const char *ovs_dp_name(const struct datapath *dp)
142 {
143 	struct vport *vport = ovs_vport_ovsl_rcu(dp, OVSP_LOCAL);
144 	return ovs_vport_name(vport);
145 }
146 
147 static int get_dpifindex(const struct datapath *dp)
148 {
149 	struct vport *local;
150 	int ifindex;
151 
152 	rcu_read_lock();
153 
154 	local = ovs_vport_rcu(dp, OVSP_LOCAL);
155 	if (local)
156 		ifindex = local->dev->ifindex;
157 	else
158 		ifindex = 0;
159 
160 	rcu_read_unlock();
161 
162 	return ifindex;
163 }
164 
165 static void destroy_dp_rcu(struct rcu_head *rcu)
166 {
167 	struct datapath *dp = container_of(rcu, struct datapath, rcu);
168 
169 	ovs_flow_tbl_destroy(&dp->table);
170 	free_percpu(dp->stats_percpu);
171 	kfree(dp->ports);
172 	ovs_meters_exit(dp);
173 	kfree(rcu_dereference_raw(dp->upcall_portids));
174 	kfree(dp);
175 }
176 
177 static struct hlist_head *vport_hash_bucket(const struct datapath *dp,
178 					    u16 port_no)
179 {
180 	return &dp->ports[port_no & (DP_VPORT_HASH_BUCKETS - 1)];
181 }
182 
183 /* Called with ovs_mutex or RCU read lock. */
184 struct vport *ovs_lookup_vport(const struct datapath *dp, u16 port_no)
185 {
186 	struct vport *vport;
187 	struct hlist_head *head;
188 
189 	head = vport_hash_bucket(dp, port_no);
190 	hlist_for_each_entry_rcu(vport, head, dp_hash_node,
191 				 lockdep_ovsl_is_held()) {
192 		if (vport->port_no == port_no)
193 			return vport;
194 	}
195 	return NULL;
196 }
197 
198 /* Called with ovs_mutex. */
199 static struct vport *new_vport(const struct vport_parms *parms)
200 {
201 	struct vport *vport;
202 
203 	vport = ovs_vport_add(parms);
204 	if (!IS_ERR(vport)) {
205 		struct datapath *dp = parms->dp;
206 		struct hlist_head *head = vport_hash_bucket(dp, vport->port_no);
207 
208 		hlist_add_head_rcu(&vport->dp_hash_node, head);
209 	}
210 	return vport;
211 }
212 
213 static void ovs_vport_update_upcall_stats(struct sk_buff *skb,
214 					  const struct dp_upcall_info *upcall_info,
215 					  bool upcall_result)
216 {
217 	struct vport *p = OVS_CB(skb)->input_vport;
218 	struct vport_upcall_stats_percpu *stats;
219 
220 	if (upcall_info->cmd != OVS_PACKET_CMD_MISS &&
221 	    upcall_info->cmd != OVS_PACKET_CMD_ACTION)
222 		return;
223 
224 	stats = this_cpu_ptr(p->upcall_stats);
225 	u64_stats_update_begin(&stats->syncp);
226 	if (upcall_result)
227 		u64_stats_inc(&stats->n_success);
228 	else
229 		u64_stats_inc(&stats->n_fail);
230 	u64_stats_update_end(&stats->syncp);
231 }
232 
233 void ovs_dp_detach_port(struct vport *p)
234 {
235 	ASSERT_OVSL();
236 
237 	/* First drop references to device. */
238 	hlist_del_rcu(&p->dp_hash_node);
239 
240 	/* Then destroy it. */
241 	ovs_vport_del(p);
242 }
243 
244 /* Must be called with rcu_read_lock. */
245 void ovs_dp_process_packet(struct sk_buff *skb, struct sw_flow_key *key)
246 {
247 	struct ovs_pcpu_storage *ovs_pcpu = this_cpu_ptr(ovs_pcpu_storage);
248 	const struct vport *p = OVS_CB(skb)->input_vport;
249 	struct datapath *dp = p->dp;
250 	struct sw_flow *flow;
251 	struct sw_flow_actions *sf_acts;
252 	struct dp_stats_percpu *stats;
253 	bool ovs_pcpu_locked = false;
254 	u64 *stats_counter;
255 	u32 n_mask_hit;
256 	u32 n_cache_hit;
257 	int error;
258 
259 	stats = this_cpu_ptr(dp->stats_percpu);
260 
261 	/* Look up flow. */
262 	flow = ovs_flow_tbl_lookup_stats(&dp->table, key, skb_get_hash(skb),
263 					 &n_mask_hit, &n_cache_hit);
264 	if (unlikely(!flow)) {
265 		struct dp_upcall_info upcall;
266 
267 		memset(&upcall, 0, sizeof(upcall));
268 		upcall.cmd = OVS_PACKET_CMD_MISS;
269 
270 		if (OVS_CB(skb)->upcall_pid)
271 			upcall.portid = OVS_CB(skb)->upcall_pid;
272 		else if (dp->user_features & OVS_DP_F_DISPATCH_UPCALL_PER_CPU)
273 			upcall.portid =
274 			    ovs_dp_get_upcall_portid(dp, smp_processor_id());
275 		else
276 			upcall.portid = ovs_vport_find_upcall_portid(p, skb);
277 
278 		upcall.mru = OVS_CB(skb)->mru;
279 		error = ovs_dp_upcall(dp, skb, key, &upcall, U32_MAX);
280 		switch (error) {
281 		case 0:
282 		case -EAGAIN:
283 		case -ERESTARTSYS:
284 		case -EINTR:
285 			consume_skb(skb);
286 			break;
287 		default:
288 			kfree_skb(skb);
289 			break;
290 		}
291 		stats_counter = &stats->n_missed;
292 		goto out;
293 	}
294 
295 	ovs_flow_stats_update(flow, key->tp.flags, skb);
296 	sf_acts = rcu_dereference(flow->sf_acts);
297 	/* This path can be invoked recursively: Use the current task to
298 	 * identify recursive invocation - the lock must be acquired only once.
299 	 * Even with disabled bottom halves this can be preempted on PREEMPT_RT.
300 	 * Limit the locking to RT to avoid assigning `owner' if it can be
301 	 * avoided.
302 	 */
303 	if (IS_ENABLED(CONFIG_PREEMPT_RT) && ovs_pcpu->owner != current) {
304 		local_lock_nested_bh(&ovs_pcpu_storage->bh_lock);
305 		ovs_pcpu->owner = current;
306 		ovs_pcpu_locked = true;
307 	}
308 
309 	error = ovs_execute_actions(dp, skb, sf_acts, key);
310 	if (unlikely(error))
311 		net_dbg_ratelimited("ovs: action execution error on datapath %s: %d\n",
312 				    ovs_dp_name(dp), error);
313 	if (ovs_pcpu_locked) {
314 		ovs_pcpu->owner = NULL;
315 		local_unlock_nested_bh(&ovs_pcpu_storage->bh_lock);
316 	}
317 
318 	stats_counter = &stats->n_hit;
319 
320 out:
321 	/* Update datapath statistics. */
322 	u64_stats_update_begin(&stats->syncp);
323 	(*stats_counter)++;
324 	stats->n_mask_hit += n_mask_hit;
325 	stats->n_cache_hit += n_cache_hit;
326 	u64_stats_update_end(&stats->syncp);
327 }
328 
329 int ovs_dp_upcall(struct datapath *dp, struct sk_buff *skb,
330 		  const struct sw_flow_key *key,
331 		  const struct dp_upcall_info *upcall_info,
332 		  uint32_t cutlen)
333 {
334 	struct dp_stats_percpu *stats;
335 	int err;
336 
337 	if (trace_ovs_dp_upcall_enabled())
338 		trace_ovs_dp_upcall(dp, skb, key, upcall_info);
339 
340 	if (upcall_info->portid == 0) {
341 		err = -ENOTCONN;
342 		goto err;
343 	}
344 
345 	if (!skb_is_gso(skb))
346 		err = queue_userspace_packet(dp, skb, key, upcall_info, cutlen);
347 	else
348 		err = queue_gso_packets(dp, skb, key, upcall_info, cutlen);
349 
350 	ovs_vport_update_upcall_stats(skb, upcall_info, !err);
351 	if (err)
352 		goto err;
353 
354 	return 0;
355 
356 err:
357 	stats = this_cpu_ptr(dp->stats_percpu);
358 
359 	u64_stats_update_begin(&stats->syncp);
360 	stats->n_lost++;
361 	u64_stats_update_end(&stats->syncp);
362 
363 	return err;
364 }
365 
366 static int queue_gso_packets(struct datapath *dp, struct sk_buff *skb,
367 			     const struct sw_flow_key *key,
368 			     const struct dp_upcall_info *upcall_info,
369 			     uint32_t cutlen)
370 {
371 	unsigned int gso_type = skb_shinfo(skb)->gso_type;
372 	struct sw_flow_key later_key;
373 	struct sk_buff *segs, *nskb;
374 	int err;
375 
376 	BUILD_BUG_ON(sizeof(*OVS_CB(skb)) > SKB_GSO_CB_OFFSET);
377 	segs = __skb_gso_segment(skb, NETIF_F_SG, false);
378 	if (IS_ERR(segs))
379 		return PTR_ERR(segs);
380 	if (segs == NULL)
381 		return -EINVAL;
382 
383 	if (gso_type & SKB_GSO_UDP) {
384 		/* The initial flow key extracted by ovs_flow_key_extract()
385 		 * in this case is for a first fragment, so we need to
386 		 * properly mark later fragments.
387 		 */
388 		later_key = *key;
389 		later_key.ip.frag = OVS_FRAG_TYPE_LATER;
390 	}
391 
392 	/* Queue all of the segments. */
393 	skb_list_walk_safe(segs, skb, nskb) {
394 		if (gso_type & SKB_GSO_UDP && skb != segs)
395 			key = &later_key;
396 
397 		err = queue_userspace_packet(dp, skb, key, upcall_info, cutlen);
398 		if (err)
399 			break;
400 
401 	}
402 
403 	/* Free all of the segments. */
404 	skb_list_walk_safe(segs, skb, nskb) {
405 		if (err)
406 			kfree_skb(skb);
407 		else
408 			consume_skb(skb);
409 	}
410 	return err;
411 }
412 
413 static size_t upcall_msg_size(const struct dp_upcall_info *upcall_info,
414 			      unsigned int hdrlen, int actions_attrlen)
415 {
416 	size_t size = NLMSG_ALIGN(sizeof(struct ovs_header))
417 		+ nla_total_size(hdrlen) /* OVS_PACKET_ATTR_PACKET */
418 		+ nla_total_size(ovs_key_attr_size()) /* OVS_PACKET_ATTR_KEY */
419 		+ nla_total_size(sizeof(unsigned int)) /* OVS_PACKET_ATTR_LEN */
420 		+ nla_total_size(sizeof(u64)); /* OVS_PACKET_ATTR_HASH */
421 
422 	/* OVS_PACKET_ATTR_USERDATA */
423 	if (upcall_info->userdata)
424 		size += NLA_ALIGN(upcall_info->userdata->nla_len);
425 
426 	/* OVS_PACKET_ATTR_EGRESS_TUN_KEY */
427 	if (upcall_info->egress_tun_info)
428 		size += nla_total_size(ovs_tun_key_attr_size());
429 
430 	/* OVS_PACKET_ATTR_ACTIONS */
431 	if (upcall_info->actions_len)
432 		size += nla_total_size(actions_attrlen);
433 
434 	/* OVS_PACKET_ATTR_MRU */
435 	if (upcall_info->mru)
436 		size += nla_total_size(sizeof(upcall_info->mru));
437 
438 	return size;
439 }
440 
441 static void pad_packet(struct datapath *dp, struct sk_buff *skb)
442 {
443 	if (!(dp->user_features & OVS_DP_F_UNALIGNED)) {
444 		size_t plen = NLA_ALIGN(skb->len) - skb->len;
445 
446 		if (plen > 0)
447 			skb_put_zero(skb, plen);
448 	}
449 }
450 
451 static int queue_userspace_packet(struct datapath *dp, struct sk_buff *skb,
452 				  const struct sw_flow_key *key,
453 				  const struct dp_upcall_info *upcall_info,
454 				  uint32_t cutlen)
455 {
456 	struct ovs_header *upcall;
457 	struct sk_buff *nskb = NULL;
458 	struct sk_buff *user_skb = NULL; /* to be queued to userspace */
459 	struct nlattr *nla;
460 	size_t msg_size;
461 	size_t skb_len;
462 	unsigned int hlen;
463 	int err, dp_ifindex;
464 	u64 hash;
465 
466 	dp_ifindex = get_dpifindex(dp);
467 	if (!dp_ifindex)
468 		return -ENODEV;
469 
470 	if (skb_vlan_tag_present(skb)) {
471 		nskb = skb_clone(skb, GFP_ATOMIC);
472 		if (!nskb)
473 			return -ENOMEM;
474 
475 		nskb = __vlan_hwaccel_push_inside(nskb);
476 		if (!nskb)
477 			return -ENOMEM;
478 
479 		skb = nskb;
480 	}
481 
482 	skb_len = min(skb->len, cutlen);
483 	if (nla_attr_size(skb_len) > USHRT_MAX) {
484 		err = -EFBIG;
485 		goto out;
486 	}
487 
488 	/* Complete checksum if needed */
489 	if (skb->ip_summed == CHECKSUM_PARTIAL &&
490 	    (err = skb_csum_hwoffload_help(skb, 0)))
491 		goto out;
492 
493 	/* Older versions of OVS user space enforce alignment of the last
494 	 * Netlink attribute to NLA_ALIGNTO which would require extensive
495 	 * padding logic. Only perform zerocopy if padding is not required.
496 	 */
497 	if (dp->user_features & OVS_DP_F_UNALIGNED)
498 		hlen = min(skb_zerocopy_headlen(skb), cutlen);
499 	else
500 		hlen = skb_len;
501 
502 	msg_size = upcall_msg_size(upcall_info, hlen,
503 				   OVS_CB(skb)->acts_origlen);
504 	user_skb = genlmsg_new(msg_size, GFP_ATOMIC);
505 	if (!user_skb) {
506 		err = -ENOMEM;
507 		goto out;
508 	}
509 
510 	upcall = genlmsg_put(user_skb, 0, 0, &dp_packet_genl_family,
511 			     0, upcall_info->cmd);
512 	if (!upcall) {
513 		err = -EINVAL;
514 		goto out;
515 	}
516 	upcall->dp_ifindex = dp_ifindex;
517 
518 	err = ovs_nla_put_key(key, key, OVS_PACKET_ATTR_KEY, false, user_skb);
519 	if (err)
520 		goto out;
521 
522 	if (upcall_info->userdata)
523 		__nla_put(user_skb, OVS_PACKET_ATTR_USERDATA,
524 			  nla_len(upcall_info->userdata),
525 			  nla_data(upcall_info->userdata));
526 
527 	if (upcall_info->egress_tun_info) {
528 		nla = nla_nest_start_noflag(user_skb,
529 					    OVS_PACKET_ATTR_EGRESS_TUN_KEY);
530 		if (!nla) {
531 			err = -EMSGSIZE;
532 			goto out;
533 		}
534 		err = ovs_nla_put_tunnel_info(user_skb,
535 					      upcall_info->egress_tun_info);
536 		if (err)
537 			goto out;
538 
539 		nla_nest_end(user_skb, nla);
540 	}
541 
542 	if (upcall_info->actions_len) {
543 		nla = nla_nest_start_noflag(user_skb, OVS_PACKET_ATTR_ACTIONS);
544 		if (!nla) {
545 			err = -EMSGSIZE;
546 			goto out;
547 		}
548 		err = ovs_nla_put_actions(upcall_info->actions,
549 					  upcall_info->actions_len,
550 					  user_skb);
551 		if (!err)
552 			nla_nest_end(user_skb, nla);
553 		else
554 			nla_nest_cancel(user_skb, nla);
555 	}
556 
557 	/* Add OVS_PACKET_ATTR_MRU */
558 	if (upcall_info->mru &&
559 	    nla_put_u16(user_skb, OVS_PACKET_ATTR_MRU, upcall_info->mru)) {
560 		err = -ENOBUFS;
561 		goto out;
562 	}
563 
564 	/* Add OVS_PACKET_ATTR_LEN when packet is truncated */
565 	if (skb_len < skb->len &&
566 	    nla_put_u32(user_skb, OVS_PACKET_ATTR_LEN, skb->len)) {
567 		err = -ENOBUFS;
568 		goto out;
569 	}
570 
571 	/* Add OVS_PACKET_ATTR_HASH */
572 	hash = skb_get_hash_raw(skb);
573 	if (skb->sw_hash)
574 		hash |= OVS_PACKET_HASH_SW_BIT;
575 
576 	if (skb->l4_hash)
577 		hash |= OVS_PACKET_HASH_L4_BIT;
578 
579 	if (nla_put(user_skb, OVS_PACKET_ATTR_HASH, sizeof (u64), &hash)) {
580 		err = -ENOBUFS;
581 		goto out;
582 	}
583 
584 	/* Only reserve room for attribute header, packet data is added
585 	 * in skb_zerocopy() */
586 	if (!(nla = nla_reserve(user_skb, OVS_PACKET_ATTR_PACKET, 0))) {
587 		err = -ENOBUFS;
588 		goto out;
589 	}
590 	nla->nla_len = nla_attr_size(skb_len);
591 
592 	err = skb_zerocopy(user_skb, skb, skb_len, hlen);
593 	if (err)
594 		goto out;
595 
596 	/* Pad OVS_PACKET_ATTR_PACKET if linear copy was performed */
597 	pad_packet(dp, user_skb);
598 
599 	((struct nlmsghdr *) user_skb->data)->nlmsg_len = user_skb->len;
600 
601 	err = genlmsg_unicast(ovs_dp_get_net(dp), user_skb, upcall_info->portid);
602 	user_skb = NULL;
603 out:
604 	if (err)
605 		skb_tx_error(skb);
606 	consume_skb(user_skb);
607 	consume_skb(nskb);
608 
609 	return err;
610 }
611 
612 static int ovs_packet_cmd_execute(struct sk_buff *skb, struct genl_info *info)
613 {
614 	struct ovs_header *ovs_header = genl_info_userhdr(info);
615 	struct net *net = sock_net(skb->sk);
616 	struct nlattr **a = info->attrs;
617 	struct sw_flow_actions *acts;
618 	struct sk_buff *packet;
619 	struct sw_flow *flow;
620 	struct sw_flow_actions *sf_acts;
621 	struct datapath *dp;
622 	struct vport *input_vport;
623 	u16 mru = 0;
624 	u64 hash;
625 	int len;
626 	int err;
627 	bool log = !a[OVS_PACKET_ATTR_PROBE];
628 
629 	err = -EINVAL;
630 	if (!a[OVS_PACKET_ATTR_PACKET] || !a[OVS_PACKET_ATTR_KEY] ||
631 	    !a[OVS_PACKET_ATTR_ACTIONS])
632 		goto err;
633 
634 	len = nla_len(a[OVS_PACKET_ATTR_PACKET]);
635 	packet = __dev_alloc_skb(NET_IP_ALIGN + len, GFP_KERNEL);
636 	err = -ENOMEM;
637 	if (!packet)
638 		goto err;
639 	skb_reserve(packet, NET_IP_ALIGN);
640 
641 	nla_memcpy(__skb_put(packet, len), a[OVS_PACKET_ATTR_PACKET], len);
642 
643 	/* Set packet's mru */
644 	if (a[OVS_PACKET_ATTR_MRU]) {
645 		mru = nla_get_u16(a[OVS_PACKET_ATTR_MRU]);
646 		packet->ignore_df = 1;
647 	}
648 	OVS_CB(packet)->mru = mru;
649 	OVS_CB(packet)->cutlen = U32_MAX;
650 
651 	if (a[OVS_PACKET_ATTR_HASH]) {
652 		hash = nla_get_u64(a[OVS_PACKET_ATTR_HASH]);
653 
654 		__skb_set_hash(packet, hash & 0xFFFFFFFFULL,
655 			       !!(hash & OVS_PACKET_HASH_SW_BIT),
656 			       !!(hash & OVS_PACKET_HASH_L4_BIT));
657 	}
658 
659 	OVS_CB(packet)->upcall_pid =
660 		nla_get_u32_default(a[OVS_PACKET_ATTR_UPCALL_PID], 0);
661 
662 	/* Build an sw_flow for sending this packet. */
663 	flow = ovs_flow_alloc();
664 	err = PTR_ERR(flow);
665 	if (IS_ERR(flow))
666 		goto err_kfree_skb;
667 
668 	err = ovs_flow_key_extract_userspace(net, a[OVS_PACKET_ATTR_KEY],
669 					     packet, &flow->key, log);
670 	if (err)
671 		goto err_flow_free;
672 
673 	err = ovs_nla_copy_actions(net, a[OVS_PACKET_ATTR_ACTIONS],
674 				   &flow->key, &acts, log);
675 	if (err)
676 		goto err_flow_free;
677 
678 	rcu_assign_pointer(flow->sf_acts, acts);
679 	packet->priority = flow->key.phy.priority;
680 	packet->mark = flow->key.phy.skb_mark;
681 
682 	rcu_read_lock();
683 	dp = get_dp_rcu(net, ovs_header->dp_ifindex);
684 	err = -ENODEV;
685 	if (!dp)
686 		goto err_unlock;
687 
688 	input_vport = ovs_vport_rcu(dp, flow->key.phy.in_port);
689 	if (!input_vport)
690 		input_vport = ovs_vport_rcu(dp, OVSP_LOCAL);
691 
692 	if (!input_vport)
693 		goto err_unlock;
694 
695 	packet->dev = input_vport->dev;
696 	OVS_CB(packet)->input_vport = input_vport;
697 	sf_acts = rcu_dereference(flow->sf_acts);
698 
699 	local_bh_disable();
700 	local_lock_nested_bh(&ovs_pcpu_storage->bh_lock);
701 	if (IS_ENABLED(CONFIG_PREEMPT_RT))
702 		this_cpu_write(ovs_pcpu_storage->owner, current);
703 	err = ovs_execute_actions(dp, packet, sf_acts, &flow->key);
704 	if (IS_ENABLED(CONFIG_PREEMPT_RT))
705 		this_cpu_write(ovs_pcpu_storage->owner, NULL);
706 	local_unlock_nested_bh(&ovs_pcpu_storage->bh_lock);
707 	local_bh_enable();
708 	rcu_read_unlock();
709 
710 	ovs_flow_free(flow, false);
711 	return err;
712 
713 err_unlock:
714 	rcu_read_unlock();
715 err_flow_free:
716 	ovs_flow_free(flow, false);
717 err_kfree_skb:
718 	kfree_skb(packet);
719 err:
720 	return err;
721 }
722 
723 static const struct nla_policy packet_policy[OVS_PACKET_ATTR_MAX + 1] = {
724 	[OVS_PACKET_ATTR_PACKET] = { .len = ETH_HLEN },
725 	[OVS_PACKET_ATTR_KEY] = { .type = NLA_NESTED },
726 	[OVS_PACKET_ATTR_ACTIONS] = { .type = NLA_NESTED },
727 	[OVS_PACKET_ATTR_PROBE] = { .type = NLA_FLAG },
728 	[OVS_PACKET_ATTR_MRU] = { .type = NLA_U16 },
729 	[OVS_PACKET_ATTR_HASH] = { .type = NLA_U64 },
730 	[OVS_PACKET_ATTR_UPCALL_PID] = { .type = NLA_U32 },
731 };
732 
733 static const struct genl_small_ops dp_packet_genl_ops[] = {
734 	{ .cmd = OVS_PACKET_CMD_EXECUTE,
735 	  .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
736 	  .flags = GENL_UNS_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
737 	  .doit = ovs_packet_cmd_execute
738 	}
739 };
740 
741 static struct genl_family dp_packet_genl_family __ro_after_init = {
742 	.hdrsize = sizeof(struct ovs_header),
743 	.name = OVS_PACKET_FAMILY,
744 	.version = OVS_PACKET_VERSION,
745 	.maxattr = OVS_PACKET_ATTR_MAX,
746 	.policy = packet_policy,
747 	.netnsok = true,
748 	.parallel_ops = true,
749 	.small_ops = dp_packet_genl_ops,
750 	.n_small_ops = ARRAY_SIZE(dp_packet_genl_ops),
751 	.resv_start_op = OVS_PACKET_CMD_EXECUTE + 1,
752 	.module = THIS_MODULE,
753 };
754 
755 static void get_dp_stats(const struct datapath *dp, struct ovs_dp_stats *stats,
756 			 struct ovs_dp_megaflow_stats *mega_stats)
757 {
758 	int i;
759 
760 	memset(mega_stats, 0, sizeof(*mega_stats));
761 
762 	stats->n_flows = ovs_flow_tbl_count(&dp->table);
763 	mega_stats->n_masks = ovs_flow_tbl_num_masks(&dp->table);
764 
765 	stats->n_hit = stats->n_missed = stats->n_lost = 0;
766 
767 	for_each_possible_cpu(i) {
768 		const struct dp_stats_percpu *percpu_stats;
769 		struct dp_stats_percpu local_stats;
770 		unsigned int start;
771 
772 		percpu_stats = per_cpu_ptr(dp->stats_percpu, i);
773 
774 		do {
775 			start = u64_stats_fetch_begin(&percpu_stats->syncp);
776 			local_stats = *percpu_stats;
777 		} while (u64_stats_fetch_retry(&percpu_stats->syncp, start));
778 
779 		stats->n_hit += local_stats.n_hit;
780 		stats->n_missed += local_stats.n_missed;
781 		stats->n_lost += local_stats.n_lost;
782 		mega_stats->n_mask_hit += local_stats.n_mask_hit;
783 		mega_stats->n_cache_hit += local_stats.n_cache_hit;
784 	}
785 }
786 
787 static bool should_fill_key(const struct sw_flow_id *sfid, uint32_t ufid_flags)
788 {
789 	return ovs_identifier_is_ufid(sfid) &&
790 	       !(ufid_flags & OVS_UFID_F_OMIT_KEY);
791 }
792 
793 static bool should_fill_mask(uint32_t ufid_flags)
794 {
795 	return !(ufid_flags & OVS_UFID_F_OMIT_MASK);
796 }
797 
798 static bool should_fill_actions(uint32_t ufid_flags)
799 {
800 	return !(ufid_flags & OVS_UFID_F_OMIT_ACTIONS);
801 }
802 
803 static size_t ovs_flow_cmd_msg_size(const struct sw_flow_actions *acts,
804 				    const struct sw_flow_id *sfid,
805 				    uint32_t ufid_flags)
806 {
807 	size_t len = NLMSG_ALIGN(sizeof(struct ovs_header));
808 
809 	/* OVS_FLOW_ATTR_UFID, or unmasked flow key as fallback
810 	 * see ovs_nla_put_identifier()
811 	 */
812 	if (sfid && ovs_identifier_is_ufid(sfid))
813 		len += nla_total_size(sfid->ufid_len);
814 	else
815 		len += nla_total_size(ovs_key_attr_size());
816 
817 	/* OVS_FLOW_ATTR_KEY */
818 	if (!sfid || should_fill_key(sfid, ufid_flags))
819 		len += nla_total_size(ovs_key_attr_size());
820 
821 	/* OVS_FLOW_ATTR_MASK */
822 	if (should_fill_mask(ufid_flags))
823 		len += nla_total_size(ovs_key_attr_size());
824 
825 	/* OVS_FLOW_ATTR_ACTIONS */
826 	if (should_fill_actions(ufid_flags))
827 		len += nla_total_size(acts->orig_len);
828 
829 	return len
830 		+ nla_total_size_64bit(sizeof(struct ovs_flow_stats)) /* OVS_FLOW_ATTR_STATS */
831 		+ nla_total_size(1) /* OVS_FLOW_ATTR_TCP_FLAGS */
832 		+ nla_total_size_64bit(8); /* OVS_FLOW_ATTR_USED */
833 }
834 
835 /* Called with ovs_mutex or RCU read lock. */
836 static int ovs_flow_cmd_fill_stats(const struct sw_flow *flow,
837 				   struct sk_buff *skb)
838 {
839 	struct ovs_flow_stats stats;
840 	__be16 tcp_flags;
841 	unsigned long used;
842 
843 	ovs_flow_stats_get(flow, &stats, &used, &tcp_flags);
844 
845 	if (used &&
846 	    nla_put_u64_64bit(skb, OVS_FLOW_ATTR_USED, ovs_flow_used_time(used),
847 			      OVS_FLOW_ATTR_PAD))
848 		return -EMSGSIZE;
849 
850 	if (stats.n_packets &&
851 	    nla_put_64bit(skb, OVS_FLOW_ATTR_STATS,
852 			  sizeof(struct ovs_flow_stats), &stats,
853 			  OVS_FLOW_ATTR_PAD))
854 		return -EMSGSIZE;
855 
856 	if ((u8)ntohs(tcp_flags) &&
857 	     nla_put_u8(skb, OVS_FLOW_ATTR_TCP_FLAGS, (u8)ntohs(tcp_flags)))
858 		return -EMSGSIZE;
859 
860 	return 0;
861 }
862 
863 /* Called with ovs_mutex or RCU read lock. */
864 static int ovs_flow_cmd_fill_actions(const struct sw_flow *flow,
865 				     struct sk_buff *skb, int skb_orig_len)
866 {
867 	struct nlattr *start;
868 	int err;
869 
870 	/* If OVS_FLOW_ATTR_ACTIONS doesn't fit, skip dumping the actions if
871 	 * this is the first flow to be dumped into 'skb'.  This is unusual for
872 	 * Netlink but individual action lists can be longer than
873 	 * NLMSG_GOODSIZE and thus entirely undumpable if we didn't do this.
874 	 * The userspace caller can always fetch the actions separately if it
875 	 * really wants them.  (Most userspace callers in fact don't care.)
876 	 *
877 	 * This can only fail for dump operations because the skb is always
878 	 * properly sized for single flows.
879 	 */
880 	start = nla_nest_start_noflag(skb, OVS_FLOW_ATTR_ACTIONS);
881 	if (start) {
882 		const struct sw_flow_actions *sf_acts;
883 
884 		sf_acts = rcu_dereference_ovsl(flow->sf_acts);
885 		err = ovs_nla_put_actions(sf_acts->actions,
886 					  sf_acts->actions_len, skb);
887 
888 		if (!err)
889 			nla_nest_end(skb, start);
890 		else {
891 			if (skb_orig_len)
892 				return err;
893 
894 			nla_nest_cancel(skb, start);
895 		}
896 	} else if (skb_orig_len) {
897 		return -EMSGSIZE;
898 	}
899 
900 	return 0;
901 }
902 
903 /* Called with ovs_mutex or RCU read lock. */
904 static int ovs_flow_cmd_fill_info(const struct sw_flow *flow, int dp_ifindex,
905 				  struct sk_buff *skb, u32 portid,
906 				  u32 seq, u32 flags, u8 cmd, u32 ufid_flags)
907 {
908 	const int skb_orig_len = skb->len;
909 	struct ovs_header *ovs_header;
910 	int err;
911 
912 	ovs_header = genlmsg_put(skb, portid, seq, &dp_flow_genl_family,
913 				 flags, cmd);
914 	if (!ovs_header)
915 		return -EMSGSIZE;
916 
917 	ovs_header->dp_ifindex = dp_ifindex;
918 
919 	err = ovs_nla_put_identifier(flow, skb);
920 	if (err)
921 		goto error;
922 
923 	if (should_fill_key(&flow->id, ufid_flags)) {
924 		err = ovs_nla_put_masked_key(flow, skb);
925 		if (err)
926 			goto error;
927 	}
928 
929 	if (should_fill_mask(ufid_flags)) {
930 		err = ovs_nla_put_mask(flow, skb);
931 		if (err)
932 			goto error;
933 	}
934 
935 	err = ovs_flow_cmd_fill_stats(flow, skb);
936 	if (err)
937 		goto error;
938 
939 	if (should_fill_actions(ufid_flags)) {
940 		err = ovs_flow_cmd_fill_actions(flow, skb, skb_orig_len);
941 		if (err)
942 			goto error;
943 	}
944 
945 	genlmsg_end(skb, ovs_header);
946 	return 0;
947 
948 error:
949 	genlmsg_cancel(skb, ovs_header);
950 	return err;
951 }
952 
953 /* May not be called with RCU read lock. */
954 static struct sk_buff *ovs_flow_cmd_alloc_info(const struct sw_flow_actions *acts,
955 					       const struct sw_flow_id *sfid,
956 					       struct genl_info *info,
957 					       bool always,
958 					       uint32_t ufid_flags)
959 {
960 	struct sk_buff *skb;
961 	size_t len;
962 
963 	if (!always && !ovs_must_notify(&dp_flow_genl_family, info, 0))
964 		return NULL;
965 
966 	len = ovs_flow_cmd_msg_size(acts, sfid, ufid_flags);
967 	skb = genlmsg_new(len, GFP_KERNEL);
968 	if (!skb)
969 		return ERR_PTR(-ENOMEM);
970 
971 	return skb;
972 }
973 
974 /* Called with ovs_mutex. */
975 static struct sk_buff *ovs_flow_cmd_build_info(const struct sw_flow *flow,
976 					       int dp_ifindex,
977 					       struct genl_info *info, u8 cmd,
978 					       bool always, u32 ufid_flags)
979 {
980 	struct sk_buff *skb;
981 	int retval;
982 
983 	skb = ovs_flow_cmd_alloc_info(ovsl_dereference(flow->sf_acts),
984 				      &flow->id, info, always, ufid_flags);
985 	if (IS_ERR_OR_NULL(skb))
986 		return skb;
987 
988 	retval = ovs_flow_cmd_fill_info(flow, dp_ifindex, skb,
989 					info->snd_portid, info->snd_seq, 0,
990 					cmd, ufid_flags);
991 	if (WARN_ON_ONCE(retval < 0)) {
992 		kfree_skb(skb);
993 		skb = ERR_PTR(retval);
994 	}
995 	return skb;
996 }
997 
998 static int ovs_flow_cmd_new(struct sk_buff *skb, struct genl_info *info)
999 {
1000 	struct net *net = sock_net(skb->sk);
1001 	struct nlattr **a = info->attrs;
1002 	struct ovs_header *ovs_header = genl_info_userhdr(info);
1003 	struct sw_flow *flow = NULL, *new_flow;
1004 	struct sw_flow_mask mask;
1005 	struct sk_buff *reply;
1006 	struct datapath *dp;
1007 	struct sw_flow_key *key;
1008 	struct sw_flow_actions *acts;
1009 	struct sw_flow_match match;
1010 	u32 ufid_flags = ovs_nla_get_ufid_flags(a[OVS_FLOW_ATTR_UFID_FLAGS]);
1011 	int error;
1012 	bool log = !a[OVS_FLOW_ATTR_PROBE];
1013 
1014 	/* Must have key and actions. */
1015 	error = -EINVAL;
1016 	if (!a[OVS_FLOW_ATTR_KEY]) {
1017 		OVS_NLERR(log, "Flow key attr not present in new flow.");
1018 		goto error;
1019 	}
1020 	if (!a[OVS_FLOW_ATTR_ACTIONS]) {
1021 		OVS_NLERR(log, "Flow actions attr not present in new flow.");
1022 		goto error;
1023 	}
1024 
1025 	/* Most of the time we need to allocate a new flow, do it before
1026 	 * locking.
1027 	 */
1028 	new_flow = ovs_flow_alloc();
1029 	if (IS_ERR(new_flow)) {
1030 		error = PTR_ERR(new_flow);
1031 		goto error;
1032 	}
1033 
1034 	/* Extract key. */
1035 	key = kzalloc_obj(*key);
1036 	if (!key) {
1037 		error = -ENOMEM;
1038 		goto err_kfree_flow;
1039 	}
1040 
1041 	ovs_match_init(&match, key, false, &mask);
1042 	error = ovs_nla_get_match(net, &match, a[OVS_FLOW_ATTR_KEY],
1043 				  a[OVS_FLOW_ATTR_MASK], log);
1044 	if (error)
1045 		goto err_kfree_key;
1046 
1047 	ovs_flow_mask_key(&new_flow->key, key, true, &mask);
1048 
1049 	/* Extract flow identifier. */
1050 	error = ovs_nla_get_identifier(&new_flow->id, a[OVS_FLOW_ATTR_UFID],
1051 				       key, log);
1052 	if (error)
1053 		goto err_kfree_key;
1054 
1055 	/* Validate actions. */
1056 	error = ovs_nla_copy_actions(net, a[OVS_FLOW_ATTR_ACTIONS],
1057 				     &new_flow->key, &acts, log);
1058 	if (error) {
1059 		OVS_NLERR(log, "Flow actions may not be safe on all matching packets.");
1060 		goto err_kfree_key;
1061 	}
1062 
1063 	reply = ovs_flow_cmd_alloc_info(acts, &new_flow->id, info, false,
1064 					ufid_flags);
1065 	if (IS_ERR(reply)) {
1066 		error = PTR_ERR(reply);
1067 		goto err_kfree_acts;
1068 	}
1069 
1070 	ovs_lock();
1071 	dp = get_dp(net, ovs_header->dp_ifindex);
1072 	if (unlikely(!dp)) {
1073 		error = -ENODEV;
1074 		goto err_unlock_ovs;
1075 	}
1076 
1077 	/* Check if this is a duplicate flow */
1078 	if (ovs_identifier_is_ufid(&new_flow->id))
1079 		flow = ovs_flow_tbl_lookup_ufid(&dp->table, &new_flow->id);
1080 	if (!flow)
1081 		flow = ovs_flow_tbl_lookup(&dp->table, key);
1082 	if (likely(!flow)) {
1083 		rcu_assign_pointer(new_flow->sf_acts, acts);
1084 
1085 		/* Put flow in bucket. */
1086 		error = ovs_flow_tbl_insert(&dp->table, new_flow, &mask);
1087 		if (unlikely(error)) {
1088 			acts = NULL;
1089 			goto err_unlock_ovs;
1090 		}
1091 
1092 		if (unlikely(reply)) {
1093 			error = ovs_flow_cmd_fill_info(new_flow,
1094 						       ovs_header->dp_ifindex,
1095 						       reply, info->snd_portid,
1096 						       info->snd_seq, 0,
1097 						       OVS_FLOW_CMD_NEW,
1098 						       ufid_flags);
1099 			BUG_ON(error < 0);
1100 		}
1101 		ovs_unlock();
1102 	} else {
1103 		struct sw_flow_actions *old_acts;
1104 
1105 		/* Bail out if we're not allowed to modify an existing flow.
1106 		 * We accept NLM_F_CREATE in place of the intended NLM_F_EXCL
1107 		 * because Generic Netlink treats the latter as a dump
1108 		 * request.  We also accept NLM_F_EXCL in case that bug ever
1109 		 * gets fixed.
1110 		 */
1111 		if (unlikely(info->nlhdr->nlmsg_flags & (NLM_F_CREATE
1112 							 | NLM_F_EXCL))) {
1113 			error = -EEXIST;
1114 			goto err_unlock_ovs;
1115 		}
1116 
1117 		/* Look for any overlapping flow. */
1118 		if (unlikely(!ovs_flow_cmp(flow, &match))) {
1119 			if (ovs_identifier_is_key(&flow->id))
1120 				flow = ovs_flow_tbl_lookup_exact(&dp->table,
1121 								 &match);
1122 			else /* UFID matches but key is different */
1123 				flow = NULL;
1124 			if (!flow) {
1125 				error = -ENOENT;
1126 				goto err_unlock_ovs;
1127 			}
1128 		}
1129 
1130 		if (unlikely(reply)) {
1131 			size_t cur, req;
1132 
1133 			cur = ovs_flow_cmd_msg_size(acts, &new_flow->id,
1134 						    ufid_flags);
1135 			req = ovs_flow_cmd_msg_size(acts, &flow->id,
1136 						    ufid_flags);
1137 			if (cur < req) {
1138 				struct sk_buff *resized;
1139 
1140 				resized = ovs_flow_cmd_alloc_info(acts,
1141 								  &flow->id,
1142 								  info, false,
1143 								  ufid_flags);
1144 				if (IS_ERR(resized)) {
1145 					error = PTR_ERR(resized);
1146 					goto err_unlock_ovs;
1147 				}
1148 				kfree_skb(reply);
1149 				reply = resized;
1150 			}
1151 		}
1152 
1153 		/* Update actions. */
1154 		old_acts = ovsl_dereference(flow->sf_acts);
1155 		rcu_assign_pointer(flow->sf_acts, acts);
1156 
1157 		if (unlikely(reply)) {
1158 			error = ovs_flow_cmd_fill_info(flow,
1159 						       ovs_header->dp_ifindex,
1160 						       reply, info->snd_portid,
1161 						       info->snd_seq, 0,
1162 						       OVS_FLOW_CMD_NEW,
1163 						       ufid_flags);
1164 			BUG_ON(error < 0);
1165 		}
1166 		ovs_unlock();
1167 
1168 		ovs_nla_free_flow_actions_rcu(old_acts);
1169 		ovs_flow_free(new_flow, false);
1170 	}
1171 
1172 	if (reply)
1173 		ovs_notify(&dp_flow_genl_family, reply, info);
1174 
1175 	kfree(key);
1176 	return 0;
1177 
1178 err_unlock_ovs:
1179 	ovs_unlock();
1180 	kfree_skb(reply);
1181 err_kfree_acts:
1182 	ovs_nla_free_flow_actions(acts);
1183 err_kfree_key:
1184 	kfree(key);
1185 err_kfree_flow:
1186 	ovs_flow_free(new_flow, false);
1187 error:
1188 	return error;
1189 }
1190 
1191 /* Factor out action copy to avoid "Wframe-larger-than=1024" warning. */
1192 static noinline_for_stack
1193 struct sw_flow_actions *get_flow_actions(struct net *net,
1194 					 const struct nlattr *a,
1195 					 const struct sw_flow_key *key,
1196 					 const struct sw_flow_mask *mask,
1197 					 bool log)
1198 {
1199 	struct sw_flow_actions *acts;
1200 	struct sw_flow_key masked_key;
1201 	int error;
1202 
1203 	ovs_flow_mask_key(&masked_key, key, true, mask);
1204 	error = ovs_nla_copy_actions(net, a, &masked_key, &acts, log);
1205 	if (error) {
1206 		OVS_NLERR(log,
1207 			  "Actions may not be safe on all matching packets");
1208 		return ERR_PTR(error);
1209 	}
1210 
1211 	return acts;
1212 }
1213 
1214 /* Factor out match-init and action-copy to avoid
1215  * "Wframe-larger-than=1024" warning. Because mask is only
1216  * used to get actions, we new a function to save some
1217  * stack space.
1218  *
1219  * If there are not key and action attrs, we return 0
1220  * directly. In the case, the caller will also not use the
1221  * match as before. If there is action attr, we try to get
1222  * actions and save them to *acts. Before returning from
1223  * the function, we reset the match->mask pointer. Because
1224  * we should not to return match object with dangling reference
1225  * to mask.
1226  * */
1227 static noinline_for_stack int
1228 ovs_nla_init_match_and_action(struct net *net,
1229 			      struct sw_flow_match *match,
1230 			      struct sw_flow_key *key,
1231 			      struct nlattr **a,
1232 			      struct sw_flow_actions **acts,
1233 			      bool log)
1234 {
1235 	struct sw_flow_mask mask;
1236 	int error = 0;
1237 
1238 	if (a[OVS_FLOW_ATTR_KEY]) {
1239 		ovs_match_init(match, key, true, &mask);
1240 		error = ovs_nla_get_match(net, match, a[OVS_FLOW_ATTR_KEY],
1241 					  a[OVS_FLOW_ATTR_MASK], log);
1242 		if (error)
1243 			goto error;
1244 	}
1245 
1246 	if (a[OVS_FLOW_ATTR_ACTIONS]) {
1247 		if (!a[OVS_FLOW_ATTR_KEY]) {
1248 			OVS_NLERR(log,
1249 				  "Flow key attribute not present in set flow.");
1250 			error = -EINVAL;
1251 			goto error;
1252 		}
1253 
1254 		*acts = get_flow_actions(net, a[OVS_FLOW_ATTR_ACTIONS], key,
1255 					 &mask, log);
1256 		if (IS_ERR(*acts)) {
1257 			error = PTR_ERR(*acts);
1258 			goto error;
1259 		}
1260 	}
1261 
1262 	/* On success, error is 0. */
1263 error:
1264 	match->mask = NULL;
1265 	return error;
1266 }
1267 
1268 static int ovs_flow_cmd_set(struct sk_buff *skb, struct genl_info *info)
1269 {
1270 	struct net *net = sock_net(skb->sk);
1271 	struct nlattr **a = info->attrs;
1272 	struct ovs_header *ovs_header = genl_info_userhdr(info);
1273 	struct sw_flow_key key;
1274 	struct sw_flow *flow;
1275 	struct sk_buff *reply = NULL;
1276 	struct datapath *dp;
1277 	struct sw_flow_actions *old_acts = NULL, *acts = NULL;
1278 	struct sw_flow_match match;
1279 	struct sw_flow_id sfid;
1280 	u32 ufid_flags = ovs_nla_get_ufid_flags(a[OVS_FLOW_ATTR_UFID_FLAGS]);
1281 	int error = 0;
1282 	bool log = !a[OVS_FLOW_ATTR_PROBE];
1283 	bool ufid_present;
1284 
1285 	ufid_present = ovs_nla_get_ufid(&sfid, a[OVS_FLOW_ATTR_UFID], log);
1286 	if (!a[OVS_FLOW_ATTR_KEY] && !ufid_present) {
1287 		OVS_NLERR(log,
1288 			  "Flow set message rejected, Key attribute missing.");
1289 		return -EINVAL;
1290 	}
1291 
1292 	error = ovs_nla_init_match_and_action(net, &match, &key, a,
1293 					      &acts, log);
1294 	if (error)
1295 		goto error;
1296 
1297 	if (acts) {
1298 		/* Can allocate before locking if have acts. */
1299 		reply = ovs_flow_cmd_alloc_info(acts, &sfid, info, false,
1300 						ufid_flags);
1301 		if (IS_ERR(reply)) {
1302 			error = PTR_ERR(reply);
1303 			goto err_kfree_acts;
1304 		}
1305 	}
1306 
1307 	ovs_lock();
1308 	dp = get_dp(net, ovs_header->dp_ifindex);
1309 	if (unlikely(!dp)) {
1310 		error = -ENODEV;
1311 		goto err_unlock_ovs;
1312 	}
1313 	/* Check that the flow exists. */
1314 	if (ufid_present)
1315 		flow = ovs_flow_tbl_lookup_ufid(&dp->table, &sfid);
1316 	else
1317 		flow = ovs_flow_tbl_lookup_exact(&dp->table, &match);
1318 	if (unlikely(!flow)) {
1319 		error = -ENOENT;
1320 		goto err_unlock_ovs;
1321 	}
1322 
1323 	/* Update actions, if present. */
1324 	if (likely(acts)) {
1325 		old_acts = ovsl_dereference(flow->sf_acts);
1326 		rcu_assign_pointer(flow->sf_acts, acts);
1327 
1328 		if (unlikely(reply)) {
1329 			error = ovs_flow_cmd_fill_info(flow,
1330 						       ovs_header->dp_ifindex,
1331 						       reply, info->snd_portid,
1332 						       info->snd_seq, 0,
1333 						       OVS_FLOW_CMD_SET,
1334 						       ufid_flags);
1335 			BUG_ON(error < 0);
1336 		}
1337 	} else {
1338 		/* Could not alloc without acts before locking. */
1339 		reply = ovs_flow_cmd_build_info(flow, ovs_header->dp_ifindex,
1340 						info, OVS_FLOW_CMD_SET, false,
1341 						ufid_flags);
1342 
1343 		if (IS_ERR(reply)) {
1344 			error = PTR_ERR(reply);
1345 			reply = NULL;
1346 			goto err_unlock_ovs;
1347 		}
1348 	}
1349 
1350 	/* Clear stats. */
1351 	if (a[OVS_FLOW_ATTR_CLEAR])
1352 		ovs_flow_stats_clear(flow);
1353 	ovs_unlock();
1354 
1355 	if (reply)
1356 		ovs_notify(&dp_flow_genl_family, reply, info);
1357 	if (old_acts)
1358 		ovs_nla_free_flow_actions_rcu(old_acts);
1359 
1360 	return 0;
1361 
1362 err_unlock_ovs:
1363 	ovs_unlock();
1364 	kfree_skb(reply);
1365 err_kfree_acts:
1366 	ovs_nla_free_flow_actions(acts);
1367 error:
1368 	return error;
1369 }
1370 
1371 static int ovs_flow_cmd_get(struct sk_buff *skb, struct genl_info *info)
1372 {
1373 	struct nlattr **a = info->attrs;
1374 	struct ovs_header *ovs_header = genl_info_userhdr(info);
1375 	struct net *net = sock_net(skb->sk);
1376 	struct sw_flow_key key;
1377 	struct sk_buff *reply;
1378 	struct sw_flow *flow;
1379 	struct datapath *dp;
1380 	struct sw_flow_match match;
1381 	struct sw_flow_id ufid;
1382 	u32 ufid_flags = ovs_nla_get_ufid_flags(a[OVS_FLOW_ATTR_UFID_FLAGS]);
1383 	int err = 0;
1384 	bool log = !a[OVS_FLOW_ATTR_PROBE];
1385 	bool ufid_present;
1386 
1387 	ufid_present = ovs_nla_get_ufid(&ufid, a[OVS_FLOW_ATTR_UFID], log);
1388 	if (a[OVS_FLOW_ATTR_KEY]) {
1389 		ovs_match_init(&match, &key, true, NULL);
1390 		err = ovs_nla_get_match(net, &match, a[OVS_FLOW_ATTR_KEY], NULL,
1391 					log);
1392 	} else if (!ufid_present) {
1393 		OVS_NLERR(log,
1394 			  "Flow get message rejected, Key attribute missing.");
1395 		err = -EINVAL;
1396 	}
1397 	if (err)
1398 		return err;
1399 
1400 	ovs_lock();
1401 	dp = get_dp(sock_net(skb->sk), ovs_header->dp_ifindex);
1402 	if (!dp) {
1403 		err = -ENODEV;
1404 		goto unlock;
1405 	}
1406 
1407 	if (ufid_present)
1408 		flow = ovs_flow_tbl_lookup_ufid(&dp->table, &ufid);
1409 	else
1410 		flow = ovs_flow_tbl_lookup_exact(&dp->table, &match);
1411 	if (!flow) {
1412 		err = -ENOENT;
1413 		goto unlock;
1414 	}
1415 
1416 	reply = ovs_flow_cmd_build_info(flow, ovs_header->dp_ifindex, info,
1417 					OVS_FLOW_CMD_GET, true, ufid_flags);
1418 	if (IS_ERR(reply)) {
1419 		err = PTR_ERR(reply);
1420 		goto unlock;
1421 	}
1422 
1423 	ovs_unlock();
1424 	return genlmsg_reply(reply, info);
1425 unlock:
1426 	ovs_unlock();
1427 	return err;
1428 }
1429 
1430 static int ovs_flow_cmd_del(struct sk_buff *skb, struct genl_info *info)
1431 {
1432 	struct nlattr **a = info->attrs;
1433 	struct ovs_header *ovs_header = genl_info_userhdr(info);
1434 	struct net *net = sock_net(skb->sk);
1435 	struct sw_flow_key key;
1436 	struct sk_buff *reply;
1437 	struct sw_flow *flow = NULL;
1438 	struct datapath *dp;
1439 	struct sw_flow_match match;
1440 	struct sw_flow_id ufid;
1441 	u32 ufid_flags = ovs_nla_get_ufid_flags(a[OVS_FLOW_ATTR_UFID_FLAGS]);
1442 	int err;
1443 	bool log = !a[OVS_FLOW_ATTR_PROBE];
1444 	bool ufid_present;
1445 
1446 	ufid_present = ovs_nla_get_ufid(&ufid, a[OVS_FLOW_ATTR_UFID], log);
1447 	if (a[OVS_FLOW_ATTR_KEY]) {
1448 		ovs_match_init(&match, &key, true, NULL);
1449 		err = ovs_nla_get_match(net, &match, a[OVS_FLOW_ATTR_KEY],
1450 					NULL, log);
1451 		if (unlikely(err))
1452 			return err;
1453 	}
1454 
1455 	ovs_lock();
1456 	dp = get_dp(sock_net(skb->sk), ovs_header->dp_ifindex);
1457 	if (unlikely(!dp)) {
1458 		err = -ENODEV;
1459 		goto unlock;
1460 	}
1461 
1462 	if (unlikely(!a[OVS_FLOW_ATTR_KEY] && !ufid_present)) {
1463 		err = ovs_flow_tbl_flush(&dp->table);
1464 		goto unlock;
1465 	}
1466 
1467 	if (ufid_present)
1468 		flow = ovs_flow_tbl_lookup_ufid(&dp->table, &ufid);
1469 	else
1470 		flow = ovs_flow_tbl_lookup_exact(&dp->table, &match);
1471 	if (unlikely(!flow)) {
1472 		err = -ENOENT;
1473 		goto unlock;
1474 	}
1475 
1476 	ovs_flow_tbl_remove(&dp->table, flow);
1477 	ovs_unlock();
1478 
1479 	reply = ovs_flow_cmd_alloc_info((const struct sw_flow_actions __force *) flow->sf_acts,
1480 					&flow->id, info, false, ufid_flags);
1481 	if (likely(reply)) {
1482 		if (!IS_ERR(reply)) {
1483 			rcu_read_lock();	/*To keep RCU checker happy. */
1484 			err = ovs_flow_cmd_fill_info(flow, ovs_header->dp_ifindex,
1485 						     reply, info->snd_portid,
1486 						     info->snd_seq, 0,
1487 						     OVS_FLOW_CMD_DEL,
1488 						     ufid_flags);
1489 			rcu_read_unlock();
1490 			if (WARN_ON_ONCE(err < 0)) {
1491 				kfree_skb(reply);
1492 				goto out_free;
1493 			}
1494 
1495 			ovs_notify(&dp_flow_genl_family, reply, info);
1496 		} else {
1497 			netlink_set_err(sock_net(skb->sk)->genl_sock, 0, 0,
1498 					PTR_ERR(reply));
1499 		}
1500 	}
1501 
1502 out_free:
1503 	ovs_flow_free(flow, true);
1504 	return 0;
1505 unlock:
1506 	ovs_unlock();
1507 	return err;
1508 }
1509 
1510 static int ovs_flow_cmd_dump(struct sk_buff *skb, struct netlink_callback *cb)
1511 {
1512 	struct nlattr *a[__OVS_FLOW_ATTR_MAX];
1513 	struct ovs_header *ovs_header = genlmsg_data(nlmsg_data(cb->nlh));
1514 	struct table_instance *ti;
1515 	struct datapath *dp;
1516 	u32 ufid_flags;
1517 	int err;
1518 
1519 	err = genlmsg_parse_deprecated(cb->nlh, &dp_flow_genl_family, a,
1520 				       OVS_FLOW_ATTR_MAX, flow_policy, NULL);
1521 	if (err)
1522 		return err;
1523 	ufid_flags = ovs_nla_get_ufid_flags(a[OVS_FLOW_ATTR_UFID_FLAGS]);
1524 
1525 	rcu_read_lock();
1526 	dp = get_dp_rcu(sock_net(skb->sk), ovs_header->dp_ifindex);
1527 	if (!dp) {
1528 		rcu_read_unlock();
1529 		return -ENODEV;
1530 	}
1531 
1532 	ti = rcu_dereference(dp->table.ti);
1533 	for (;;) {
1534 		struct sw_flow *flow;
1535 		u32 bucket, obj;
1536 
1537 		bucket = cb->args[0];
1538 		obj = cb->args[1];
1539 		flow = ovs_flow_tbl_dump_next(ti, &bucket, &obj);
1540 		if (!flow)
1541 			break;
1542 
1543 		if (ovs_flow_cmd_fill_info(flow, ovs_header->dp_ifindex, skb,
1544 					   NETLINK_CB(cb->skb).portid,
1545 					   cb->nlh->nlmsg_seq, NLM_F_MULTI,
1546 					   OVS_FLOW_CMD_GET, ufid_flags) < 0)
1547 			break;
1548 
1549 		cb->args[0] = bucket;
1550 		cb->args[1] = obj;
1551 	}
1552 	rcu_read_unlock();
1553 	return skb->len;
1554 }
1555 
1556 static const struct nla_policy flow_policy[OVS_FLOW_ATTR_MAX + 1] = {
1557 	[OVS_FLOW_ATTR_KEY] = { .type = NLA_NESTED },
1558 	[OVS_FLOW_ATTR_MASK] = { .type = NLA_NESTED },
1559 	[OVS_FLOW_ATTR_ACTIONS] = { .type = NLA_NESTED },
1560 	[OVS_FLOW_ATTR_CLEAR] = { .type = NLA_FLAG },
1561 	[OVS_FLOW_ATTR_PROBE] = { .type = NLA_FLAG },
1562 	[OVS_FLOW_ATTR_UFID] = { .type = NLA_UNSPEC, .len = 1 },
1563 	[OVS_FLOW_ATTR_UFID_FLAGS] = { .type = NLA_U32 },
1564 };
1565 
1566 static const struct genl_small_ops dp_flow_genl_ops[] = {
1567 	{ .cmd = OVS_FLOW_CMD_NEW,
1568 	  .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
1569 	  .flags = GENL_UNS_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1570 	  .doit = ovs_flow_cmd_new
1571 	},
1572 	{ .cmd = OVS_FLOW_CMD_DEL,
1573 	  .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
1574 	  .flags = GENL_UNS_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1575 	  .doit = ovs_flow_cmd_del
1576 	},
1577 	{ .cmd = OVS_FLOW_CMD_GET,
1578 	  .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
1579 	  .flags = 0,		    /* OK for unprivileged users. */
1580 	  .doit = ovs_flow_cmd_get,
1581 	  .dumpit = ovs_flow_cmd_dump
1582 	},
1583 	{ .cmd = OVS_FLOW_CMD_SET,
1584 	  .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
1585 	  .flags = GENL_UNS_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1586 	  .doit = ovs_flow_cmd_set,
1587 	},
1588 };
1589 
1590 static struct genl_family dp_flow_genl_family __ro_after_init = {
1591 	.hdrsize = sizeof(struct ovs_header),
1592 	.name = OVS_FLOW_FAMILY,
1593 	.version = OVS_FLOW_VERSION,
1594 	.maxattr = OVS_FLOW_ATTR_MAX,
1595 	.policy = flow_policy,
1596 	.netnsok = true,
1597 	.parallel_ops = true,
1598 	.small_ops = dp_flow_genl_ops,
1599 	.n_small_ops = ARRAY_SIZE(dp_flow_genl_ops),
1600 	.resv_start_op = OVS_FLOW_CMD_SET + 1,
1601 	.mcgrps = &ovs_dp_flow_multicast_group,
1602 	.n_mcgrps = 1,
1603 	.module = THIS_MODULE,
1604 };
1605 
1606 static size_t ovs_dp_cmd_msg_size(void)
1607 {
1608 	size_t msgsize = NLMSG_ALIGN(sizeof(struct ovs_header));
1609 
1610 	msgsize += nla_total_size(IFNAMSIZ);
1611 	msgsize += nla_total_size_64bit(sizeof(struct ovs_dp_stats));
1612 	msgsize += nla_total_size_64bit(sizeof(struct ovs_dp_megaflow_stats));
1613 	msgsize += nla_total_size(sizeof(u32)); /* OVS_DP_ATTR_USER_FEATURES */
1614 	msgsize += nla_total_size(sizeof(u32)); /* OVS_DP_ATTR_MASKS_CACHE_SIZE */
1615 	msgsize += nla_total_size(sizeof(u32) * nr_cpu_ids); /* OVS_DP_ATTR_PER_CPU_PIDS */
1616 
1617 	return msgsize;
1618 }
1619 
1620 /* Called with ovs_mutex. */
1621 static int ovs_dp_cmd_fill_info(struct datapath *dp, struct sk_buff *skb,
1622 				u32 portid, u32 seq, u32 flags, u8 cmd)
1623 {
1624 	struct ovs_header *ovs_header;
1625 	struct ovs_dp_stats dp_stats;
1626 	struct ovs_dp_megaflow_stats dp_megaflow_stats;
1627 	struct dp_nlsk_pids *pids = ovsl_dereference(dp->upcall_portids);
1628 	int err, pids_len;
1629 
1630 	ovs_header = genlmsg_put(skb, portid, seq, &dp_datapath_genl_family,
1631 				 flags, cmd);
1632 	if (!ovs_header)
1633 		goto error;
1634 
1635 	ovs_header->dp_ifindex = get_dpifindex(dp);
1636 
1637 	err = nla_put_string(skb, OVS_DP_ATTR_NAME, ovs_dp_name(dp));
1638 	if (err)
1639 		goto nla_put_failure;
1640 
1641 	get_dp_stats(dp, &dp_stats, &dp_megaflow_stats);
1642 	if (nla_put_64bit(skb, OVS_DP_ATTR_STATS, sizeof(struct ovs_dp_stats),
1643 			  &dp_stats, OVS_DP_ATTR_PAD))
1644 		goto nla_put_failure;
1645 
1646 	if (nla_put_64bit(skb, OVS_DP_ATTR_MEGAFLOW_STATS,
1647 			  sizeof(struct ovs_dp_megaflow_stats),
1648 			  &dp_megaflow_stats, OVS_DP_ATTR_PAD))
1649 		goto nla_put_failure;
1650 
1651 	if (nla_put_u32(skb, OVS_DP_ATTR_USER_FEATURES, dp->user_features))
1652 		goto nla_put_failure;
1653 
1654 	if (nla_put_u32(skb, OVS_DP_ATTR_MASKS_CACHE_SIZE,
1655 			ovs_flow_tbl_masks_cache_size(&dp->table)))
1656 		goto nla_put_failure;
1657 
1658 	if (dp->user_features & OVS_DP_F_DISPATCH_UPCALL_PER_CPU && pids) {
1659 		pids_len = min(pids->n_pids, nr_cpu_ids) * sizeof(u32);
1660 		if (nla_put(skb, OVS_DP_ATTR_PER_CPU_PIDS, pids_len, &pids->pids))
1661 			goto nla_put_failure;
1662 	}
1663 
1664 	genlmsg_end(skb, ovs_header);
1665 	return 0;
1666 
1667 nla_put_failure:
1668 	genlmsg_cancel(skb, ovs_header);
1669 error:
1670 	return -EMSGSIZE;
1671 }
1672 
1673 static struct sk_buff *ovs_dp_cmd_alloc_info(void)
1674 {
1675 	return genlmsg_new(ovs_dp_cmd_msg_size(), GFP_KERNEL);
1676 }
1677 
1678 /* Called with rcu_read_lock or ovs_mutex. */
1679 static struct datapath *lookup_datapath(struct net *net,
1680 					const struct ovs_header *ovs_header,
1681 					struct nlattr *a[OVS_DP_ATTR_MAX + 1])
1682 {
1683 	struct datapath *dp;
1684 
1685 	if (!a[OVS_DP_ATTR_NAME])
1686 		dp = get_dp(net, ovs_header->dp_ifindex);
1687 	else {
1688 		struct vport *vport;
1689 
1690 		vport = ovs_vport_locate(net, nla_data(a[OVS_DP_ATTR_NAME]));
1691 		dp = vport && vport->port_no == OVSP_LOCAL ? vport->dp : NULL;
1692 	}
1693 	return dp ? dp : ERR_PTR(-ENODEV);
1694 }
1695 
1696 static void ovs_dp_reset_user_features(struct sk_buff *skb,
1697 				       struct genl_info *info)
1698 {
1699 	struct datapath *dp;
1700 
1701 	dp = lookup_datapath(sock_net(skb->sk), genl_info_userhdr(info),
1702 			     info->attrs);
1703 	if (IS_ERR(dp))
1704 		return;
1705 
1706 	pr_warn("%s: Dropping previously announced user features\n",
1707 		ovs_dp_name(dp));
1708 	dp->user_features = 0;
1709 }
1710 
1711 static int ovs_dp_set_upcall_portids(struct datapath *dp,
1712 			      const struct nlattr *ids)
1713 {
1714 	struct dp_nlsk_pids *old, *dp_nlsk_pids;
1715 
1716 	if (!nla_len(ids) || nla_len(ids) % sizeof(u32))
1717 		return -EINVAL;
1718 
1719 	old = ovsl_dereference(dp->upcall_portids);
1720 
1721 	dp_nlsk_pids = kmalloc(sizeof(*dp_nlsk_pids) + nla_len(ids),
1722 			       GFP_KERNEL);
1723 	if (!dp_nlsk_pids)
1724 		return -ENOMEM;
1725 
1726 	dp_nlsk_pids->n_pids = nla_len(ids) / sizeof(u32);
1727 	nla_memcpy(dp_nlsk_pids->pids, ids, nla_len(ids));
1728 
1729 	rcu_assign_pointer(dp->upcall_portids, dp_nlsk_pids);
1730 
1731 	kfree_rcu(old, rcu);
1732 
1733 	return 0;
1734 }
1735 
1736 u32 ovs_dp_get_upcall_portid(const struct datapath *dp, uint32_t cpu_id)
1737 {
1738 	struct dp_nlsk_pids *dp_nlsk_pids;
1739 
1740 	dp_nlsk_pids = rcu_dereference(dp->upcall_portids);
1741 
1742 	if (dp_nlsk_pids) {
1743 		if (cpu_id < dp_nlsk_pids->n_pids) {
1744 			return dp_nlsk_pids->pids[cpu_id];
1745 		} else if (dp_nlsk_pids->n_pids > 0 &&
1746 			   cpu_id >= dp_nlsk_pids->n_pids) {
1747 			/* If the number of netlink PIDs is mismatched with
1748 			 * the number of CPUs as seen by the kernel, log this
1749 			 * and send the upcall to an arbitrary socket (0) in
1750 			 * order to not drop packets
1751 			 */
1752 			pr_info_ratelimited("cpu_id mismatch with handler threads");
1753 			return dp_nlsk_pids->pids[cpu_id %
1754 						  dp_nlsk_pids->n_pids];
1755 		} else {
1756 			return 0;
1757 		}
1758 	} else {
1759 		return 0;
1760 	}
1761 }
1762 
1763 static int ovs_dp_change(struct datapath *dp, struct nlattr *a[])
1764 {
1765 	u32 user_features = 0, old_features = dp->user_features;
1766 	int err;
1767 
1768 	if (a[OVS_DP_ATTR_USER_FEATURES]) {
1769 		user_features = nla_get_u32(a[OVS_DP_ATTR_USER_FEATURES]);
1770 
1771 		if (user_features & ~(OVS_DP_F_VPORT_PIDS |
1772 				      OVS_DP_F_UNALIGNED |
1773 				      OVS_DP_F_TC_RECIRC_SHARING |
1774 				      OVS_DP_F_DISPATCH_UPCALL_PER_CPU))
1775 			return -EOPNOTSUPP;
1776 
1777 #if !IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
1778 		if (user_features & OVS_DP_F_TC_RECIRC_SHARING)
1779 			return -EOPNOTSUPP;
1780 #endif
1781 	}
1782 
1783 	if (a[OVS_DP_ATTR_MASKS_CACHE_SIZE]) {
1784 		int err;
1785 		u32 cache_size;
1786 
1787 		cache_size = nla_get_u32(a[OVS_DP_ATTR_MASKS_CACHE_SIZE]);
1788 		err = ovs_flow_tbl_masks_cache_resize(&dp->table, cache_size);
1789 		if (err)
1790 			return err;
1791 	}
1792 
1793 	dp->user_features = user_features;
1794 
1795 	if (dp->user_features & OVS_DP_F_DISPATCH_UPCALL_PER_CPU &&
1796 	    a[OVS_DP_ATTR_PER_CPU_PIDS]) {
1797 		/* Upcall Netlink Port IDs have been updated */
1798 		err = ovs_dp_set_upcall_portids(dp,
1799 						a[OVS_DP_ATTR_PER_CPU_PIDS]);
1800 		if (err)
1801 			return err;
1802 	}
1803 
1804 	if ((dp->user_features & OVS_DP_F_TC_RECIRC_SHARING) &&
1805 	    !(old_features & OVS_DP_F_TC_RECIRC_SHARING))
1806 		tc_skb_ext_tc_enable();
1807 	else if (!(dp->user_features & OVS_DP_F_TC_RECIRC_SHARING) &&
1808 		 (old_features & OVS_DP_F_TC_RECIRC_SHARING))
1809 		tc_skb_ext_tc_disable();
1810 
1811 	return 0;
1812 }
1813 
1814 static int ovs_dp_stats_init(struct datapath *dp)
1815 {
1816 	dp->stats_percpu = netdev_alloc_pcpu_stats(struct dp_stats_percpu);
1817 	if (!dp->stats_percpu)
1818 		return -ENOMEM;
1819 
1820 	return 0;
1821 }
1822 
1823 static int ovs_dp_vport_init(struct datapath *dp)
1824 {
1825 	int i;
1826 
1827 	dp->ports = kmalloc_objs(struct hlist_head, DP_VPORT_HASH_BUCKETS);
1828 	if (!dp->ports)
1829 		return -ENOMEM;
1830 
1831 	for (i = 0; i < DP_VPORT_HASH_BUCKETS; i++)
1832 		INIT_HLIST_HEAD(&dp->ports[i]);
1833 
1834 	return 0;
1835 }
1836 
1837 static int ovs_dp_cmd_new(struct sk_buff *skb, struct genl_info *info)
1838 {
1839 	struct nlattr **a = info->attrs;
1840 	struct vport_parms parms;
1841 	struct sk_buff *reply;
1842 	struct datapath *dp;
1843 	struct vport *vport;
1844 	struct ovs_net *ovs_net;
1845 	int err;
1846 
1847 	err = -EINVAL;
1848 	if (!a[OVS_DP_ATTR_NAME] || !a[OVS_DP_ATTR_UPCALL_PID])
1849 		goto err;
1850 
1851 	reply = ovs_dp_cmd_alloc_info();
1852 	if (!reply)
1853 		return -ENOMEM;
1854 
1855 	err = -ENOMEM;
1856 	dp = kzalloc_obj(*dp);
1857 	if (dp == NULL)
1858 		goto err_destroy_reply;
1859 
1860 	ovs_dp_set_net(dp, sock_net(skb->sk));
1861 
1862 	/* Allocate table. */
1863 	err = ovs_flow_tbl_init(&dp->table);
1864 	if (err)
1865 		goto err_destroy_dp;
1866 
1867 	err = ovs_dp_stats_init(dp);
1868 	if (err)
1869 		goto err_destroy_table;
1870 
1871 	err = ovs_dp_vport_init(dp);
1872 	if (err)
1873 		goto err_destroy_stats;
1874 
1875 	err = ovs_meters_init(dp);
1876 	if (err)
1877 		goto err_destroy_ports;
1878 
1879 	/* Set up our datapath device. */
1880 	parms.name = nla_data(a[OVS_DP_ATTR_NAME]);
1881 	parms.type = OVS_VPORT_TYPE_INTERNAL;
1882 	parms.options = NULL;
1883 	parms.dp = dp;
1884 	parms.port_no = OVSP_LOCAL;
1885 	parms.upcall_portids = a[OVS_DP_ATTR_UPCALL_PID];
1886 	parms.desired_ifindex = nla_get_s32_default(a[OVS_DP_ATTR_IFINDEX], 0);
1887 
1888 	/* So far only local changes have been made, now need the lock. */
1889 	ovs_lock();
1890 
1891 	err = ovs_dp_change(dp, a);
1892 	if (err)
1893 		goto err_unlock_and_destroy_meters;
1894 
1895 	vport = new_vport(&parms);
1896 	if (IS_ERR(vport)) {
1897 		err = PTR_ERR(vport);
1898 		if (err == -EBUSY)
1899 			err = -EEXIST;
1900 
1901 		if (err == -EEXIST) {
1902 			/* An outdated user space instance that does not understand
1903 			 * the concept of user_features has attempted to create a new
1904 			 * datapath and is likely to reuse it. Drop all user features.
1905 			 */
1906 			if (info->genlhdr->version < OVS_DP_VER_FEATURES)
1907 				ovs_dp_reset_user_features(skb, info);
1908 		}
1909 
1910 		goto err_destroy_portids;
1911 	}
1912 
1913 	err = ovs_dp_cmd_fill_info(dp, reply, info->snd_portid,
1914 				   info->snd_seq, 0, OVS_DP_CMD_NEW);
1915 	BUG_ON(err < 0);
1916 
1917 	ovs_net = net_generic(ovs_dp_get_net(dp), ovs_net_id);
1918 	list_add_tail_rcu(&dp->list_node, &ovs_net->dps);
1919 
1920 	ovs_unlock();
1921 
1922 	ovs_notify(&dp_datapath_genl_family, reply, info);
1923 	return 0;
1924 
1925 err_destroy_portids:
1926 	kfree(rcu_dereference_raw(dp->upcall_portids));
1927 err_unlock_and_destroy_meters:
1928 	ovs_unlock();
1929 	ovs_meters_exit(dp);
1930 err_destroy_ports:
1931 	kfree(dp->ports);
1932 err_destroy_stats:
1933 	free_percpu(dp->stats_percpu);
1934 err_destroy_table:
1935 	ovs_flow_tbl_destroy(&dp->table);
1936 err_destroy_dp:
1937 	kfree(dp);
1938 err_destroy_reply:
1939 	kfree_skb(reply);
1940 err:
1941 	return err;
1942 }
1943 
1944 /* Called with ovs_mutex. */
1945 static void __dp_destroy(struct datapath *dp)
1946 {
1947 	struct flow_table *table = &dp->table;
1948 	int i;
1949 
1950 	if (dp->user_features & OVS_DP_F_TC_RECIRC_SHARING)
1951 		tc_skb_ext_tc_disable();
1952 
1953 	for (i = 0; i < DP_VPORT_HASH_BUCKETS; i++) {
1954 		struct vport *vport;
1955 		struct hlist_node *n;
1956 
1957 		hlist_for_each_entry_safe(vport, n, &dp->ports[i], dp_hash_node)
1958 			if (vport->port_no != OVSP_LOCAL)
1959 				ovs_dp_detach_port(vport);
1960 	}
1961 
1962 	list_del_rcu(&dp->list_node);
1963 
1964 	/* OVSP_LOCAL is datapath internal port. We need to make sure that
1965 	 * all ports in datapath are destroyed first before freeing datapath.
1966 	 */
1967 	ovs_dp_detach_port(ovs_vport_ovsl(dp, OVSP_LOCAL));
1968 
1969 	/* Flush sw_flow in the tables. RCU cb only releases resource
1970 	 * such as dp, ports and tables. That may avoid some issues
1971 	 * such as RCU usage warning.
1972 	 */
1973 	table_instance_flow_flush(table, ovsl_dereference(table->ti),
1974 				  ovsl_dereference(table->ufid_ti));
1975 
1976 	/* RCU destroy the ports, meters and flow tables. */
1977 	call_rcu(&dp->rcu, destroy_dp_rcu);
1978 }
1979 
1980 static int ovs_dp_cmd_del(struct sk_buff *skb, struct genl_info *info)
1981 {
1982 	struct sk_buff *reply;
1983 	struct datapath *dp;
1984 	int err;
1985 
1986 	reply = ovs_dp_cmd_alloc_info();
1987 	if (!reply)
1988 		return -ENOMEM;
1989 
1990 	ovs_lock();
1991 	dp = lookup_datapath(sock_net(skb->sk), genl_info_userhdr(info),
1992 			     info->attrs);
1993 	err = PTR_ERR(dp);
1994 	if (IS_ERR(dp))
1995 		goto err_unlock_free;
1996 
1997 	err = ovs_dp_cmd_fill_info(dp, reply, info->snd_portid,
1998 				   info->snd_seq, 0, OVS_DP_CMD_DEL);
1999 	BUG_ON(err < 0);
2000 
2001 	__dp_destroy(dp);
2002 	ovs_unlock();
2003 
2004 	ovs_notify(&dp_datapath_genl_family, reply, info);
2005 
2006 	return 0;
2007 
2008 err_unlock_free:
2009 	ovs_unlock();
2010 	kfree_skb(reply);
2011 	return err;
2012 }
2013 
2014 static int ovs_dp_cmd_set(struct sk_buff *skb, struct genl_info *info)
2015 {
2016 	struct sk_buff *reply;
2017 	struct datapath *dp;
2018 	int err;
2019 
2020 	reply = ovs_dp_cmd_alloc_info();
2021 	if (!reply)
2022 		return -ENOMEM;
2023 
2024 	ovs_lock();
2025 	dp = lookup_datapath(sock_net(skb->sk), genl_info_userhdr(info),
2026 			     info->attrs);
2027 	err = PTR_ERR(dp);
2028 	if (IS_ERR(dp))
2029 		goto err_unlock_free;
2030 
2031 	err = ovs_dp_change(dp, info->attrs);
2032 	if (err)
2033 		goto err_unlock_free;
2034 
2035 	err = ovs_dp_cmd_fill_info(dp, reply, info->snd_portid,
2036 				   info->snd_seq, 0, OVS_DP_CMD_SET);
2037 	BUG_ON(err < 0);
2038 
2039 	ovs_unlock();
2040 	ovs_notify(&dp_datapath_genl_family, reply, info);
2041 
2042 	return 0;
2043 
2044 err_unlock_free:
2045 	ovs_unlock();
2046 	kfree_skb(reply);
2047 	return err;
2048 }
2049 
2050 static int ovs_dp_cmd_get(struct sk_buff *skb, struct genl_info *info)
2051 {
2052 	struct sk_buff *reply;
2053 	struct datapath *dp;
2054 	int err;
2055 
2056 	reply = ovs_dp_cmd_alloc_info();
2057 	if (!reply)
2058 		return -ENOMEM;
2059 
2060 	ovs_lock();
2061 	dp = lookup_datapath(sock_net(skb->sk), genl_info_userhdr(info),
2062 			     info->attrs);
2063 	if (IS_ERR(dp)) {
2064 		err = PTR_ERR(dp);
2065 		goto err_unlock_free;
2066 	}
2067 	err = ovs_dp_cmd_fill_info(dp, reply, info->snd_portid,
2068 				   info->snd_seq, 0, OVS_DP_CMD_GET);
2069 	BUG_ON(err < 0);
2070 	ovs_unlock();
2071 
2072 	return genlmsg_reply(reply, info);
2073 
2074 err_unlock_free:
2075 	ovs_unlock();
2076 	kfree_skb(reply);
2077 	return err;
2078 }
2079 
2080 static int ovs_dp_cmd_dump(struct sk_buff *skb, struct netlink_callback *cb)
2081 {
2082 	struct ovs_net *ovs_net = net_generic(sock_net(skb->sk), ovs_net_id);
2083 	struct datapath *dp;
2084 	int skip = cb->args[0];
2085 	int i = 0;
2086 
2087 	ovs_lock();
2088 	list_for_each_entry(dp, &ovs_net->dps, list_node) {
2089 		if (i >= skip &&
2090 		    ovs_dp_cmd_fill_info(dp, skb, NETLINK_CB(cb->skb).portid,
2091 					 cb->nlh->nlmsg_seq, NLM_F_MULTI,
2092 					 OVS_DP_CMD_GET) < 0)
2093 			break;
2094 		i++;
2095 	}
2096 	ovs_unlock();
2097 
2098 	cb->args[0] = i;
2099 
2100 	return skb->len;
2101 }
2102 
2103 static const struct nla_policy datapath_policy[OVS_DP_ATTR_MAX + 1] = {
2104 	[OVS_DP_ATTR_NAME] = { .type = NLA_NUL_STRING, .len = IFNAMSIZ - 1 },
2105 	[OVS_DP_ATTR_UPCALL_PID] = { .type = NLA_U32 },
2106 	[OVS_DP_ATTR_USER_FEATURES] = { .type = NLA_U32 },
2107 	[OVS_DP_ATTR_MASKS_CACHE_SIZE] =  NLA_POLICY_RANGE(NLA_U32, 0,
2108 		PCPU_MIN_UNIT_SIZE / sizeof(struct mask_cache_entry)),
2109 	[OVS_DP_ATTR_IFINDEX] = NLA_POLICY_MIN(NLA_S32, 0),
2110 };
2111 
2112 static const struct genl_small_ops dp_datapath_genl_ops[] = {
2113 	{ .cmd = OVS_DP_CMD_NEW,
2114 	  .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2115 	  .flags = GENL_UNS_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
2116 	  .doit = ovs_dp_cmd_new
2117 	},
2118 	{ .cmd = OVS_DP_CMD_DEL,
2119 	  .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2120 	  .flags = GENL_UNS_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
2121 	  .doit = ovs_dp_cmd_del
2122 	},
2123 	{ .cmd = OVS_DP_CMD_GET,
2124 	  .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2125 	  .flags = 0,		    /* OK for unprivileged users. */
2126 	  .doit = ovs_dp_cmd_get,
2127 	  .dumpit = ovs_dp_cmd_dump
2128 	},
2129 	{ .cmd = OVS_DP_CMD_SET,
2130 	  .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2131 	  .flags = GENL_UNS_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
2132 	  .doit = ovs_dp_cmd_set,
2133 	},
2134 };
2135 
2136 static struct genl_family dp_datapath_genl_family __ro_after_init = {
2137 	.hdrsize = sizeof(struct ovs_header),
2138 	.name = OVS_DATAPATH_FAMILY,
2139 	.version = OVS_DATAPATH_VERSION,
2140 	.maxattr = OVS_DP_ATTR_MAX,
2141 	.policy = datapath_policy,
2142 	.netnsok = true,
2143 	.parallel_ops = true,
2144 	.small_ops = dp_datapath_genl_ops,
2145 	.n_small_ops = ARRAY_SIZE(dp_datapath_genl_ops),
2146 	.resv_start_op = OVS_DP_CMD_SET + 1,
2147 	.mcgrps = &ovs_dp_datapath_multicast_group,
2148 	.n_mcgrps = 1,
2149 	.module = THIS_MODULE,
2150 };
2151 
2152 /* Called with ovs_mutex or RCU read lock. */
2153 static int ovs_vport_cmd_fill_info(struct vport *vport, struct sk_buff *skb,
2154 				   struct net *net, u32 portid, u32 seq,
2155 				   u32 flags, u8 cmd, gfp_t gfp)
2156 {
2157 	struct ovs_header *ovs_header;
2158 	struct ovs_vport_stats vport_stats;
2159 	struct net *net_vport;
2160 	int err;
2161 
2162 	ovs_header = genlmsg_put(skb, portid, seq, &dp_vport_genl_family,
2163 				 flags, cmd);
2164 	if (!ovs_header)
2165 		return -EMSGSIZE;
2166 
2167 	ovs_header->dp_ifindex = get_dpifindex(vport->dp);
2168 
2169 	if (nla_put_u32(skb, OVS_VPORT_ATTR_PORT_NO, vport->port_no) ||
2170 	    nla_put_u32(skb, OVS_VPORT_ATTR_TYPE, vport->ops->type) ||
2171 	    nla_put_string(skb, OVS_VPORT_ATTR_NAME,
2172 			   ovs_vport_name(vport)) ||
2173 	    nla_put_u32(skb, OVS_VPORT_ATTR_IFINDEX, vport->dev->ifindex))
2174 		goto nla_put_failure;
2175 
2176 	rcu_read_lock();
2177 	net_vport = dev_net_rcu(vport->dev);
2178 	if (!net_eq(net, net_vport)) {
2179 		int id = peernet2id_alloc(net, net_vport, GFP_ATOMIC);
2180 
2181 		if (nla_put_s32(skb, OVS_VPORT_ATTR_NETNSID, id))
2182 			goto nla_put_failure_unlock;
2183 	}
2184 	rcu_read_unlock();
2185 
2186 	ovs_vport_get_stats(vport, &vport_stats);
2187 	if (nla_put_64bit(skb, OVS_VPORT_ATTR_STATS,
2188 			  sizeof(struct ovs_vport_stats), &vport_stats,
2189 			  OVS_VPORT_ATTR_PAD))
2190 		goto nla_put_failure;
2191 
2192 	if (ovs_vport_get_upcall_stats(vport, skb))
2193 		goto nla_put_failure;
2194 
2195 	if (ovs_vport_get_upcall_portids(vport, skb))
2196 		goto nla_put_failure;
2197 
2198 	err = ovs_vport_get_options(vport, skb);
2199 	if (err == -EMSGSIZE)
2200 		goto error;
2201 
2202 	genlmsg_end(skb, ovs_header);
2203 	return 0;
2204 
2205 nla_put_failure_unlock:
2206 	rcu_read_unlock();
2207 nla_put_failure:
2208 	err = -EMSGSIZE;
2209 error:
2210 	genlmsg_cancel(skb, ovs_header);
2211 	return err;
2212 }
2213 
2214 static size_t ovs_vport_cmd_msg_size(void)
2215 {
2216 	size_t msgsize = NLMSG_ALIGN(sizeof(struct ovs_header));
2217 
2218 	msgsize += nla_total_size(sizeof(u32)); /* OVS_VPORT_ATTR_PORT_NO */
2219 	msgsize += nla_total_size(sizeof(u32)); /* OVS_VPORT_ATTR_TYPE */
2220 	msgsize += nla_total_size(IFNAMSIZ);    /* OVS_VPORT_ATTR_NAME */
2221 	msgsize += nla_total_size(sizeof(u32)); /* OVS_VPORT_ATTR_IFINDEX */
2222 	msgsize += nla_total_size(sizeof(s32)); /* OVS_VPORT_ATTR_NETNSID */
2223 
2224 	/* OVS_VPORT_ATTR_STATS */
2225 	msgsize += nla_total_size_64bit(sizeof(struct ovs_vport_stats));
2226 
2227 	/* OVS_VPORT_ATTR_UPCALL_STATS(OVS_VPORT_UPCALL_ATTR_SUCCESS +
2228 	 *                             OVS_VPORT_UPCALL_ATTR_FAIL)
2229 	 */
2230 	msgsize += nla_total_size(nla_total_size_64bit(sizeof(u64)) +
2231 				  nla_total_size_64bit(sizeof(u64)));
2232 
2233 	/* OVS_VPORT_ATTR_UPCALL_PID */
2234 	msgsize += nla_total_size(nr_cpu_ids * sizeof(u32));
2235 
2236 	/* OVS_VPORT_ATTR_OPTIONS(OVS_TUNNEL_ATTR_DST_PORT +
2237 	 *                        OVS_TUNNEL_ATTR_EXTENSION(OVS_VXLAN_EXT_GBP))
2238 	 */
2239 	msgsize += nla_total_size(nla_total_size(sizeof(u16)) +
2240 				  nla_total_size(nla_total_size(0)));
2241 
2242 	return msgsize;
2243 }
2244 
2245 static struct sk_buff *ovs_vport_cmd_alloc_info(void)
2246 {
2247 	return genlmsg_new(ovs_vport_cmd_msg_size(), GFP_KERNEL);
2248 }
2249 
2250 /* Called with ovs_mutex, only via ovs_dp_notify_wq(). */
2251 struct sk_buff *ovs_vport_cmd_build_info(struct vport *vport, struct net *net,
2252 					 u32 portid, u32 seq, u8 cmd)
2253 {
2254 	struct sk_buff *skb;
2255 	int retval;
2256 
2257 	skb = ovs_vport_cmd_alloc_info();
2258 	if (!skb)
2259 		return ERR_PTR(-ENOMEM);
2260 
2261 	retval = ovs_vport_cmd_fill_info(vport, skb, net, portid, seq, 0, cmd,
2262 					 GFP_KERNEL);
2263 	BUG_ON(retval < 0);
2264 
2265 	return skb;
2266 }
2267 
2268 /* Called with ovs_mutex or RCU read lock. */
2269 static struct vport *lookup_vport(struct net *net,
2270 				  const struct ovs_header *ovs_header,
2271 				  struct nlattr *a[OVS_VPORT_ATTR_MAX + 1])
2272 {
2273 	struct datapath *dp;
2274 	struct vport *vport;
2275 
2276 	if (a[OVS_VPORT_ATTR_IFINDEX])
2277 		return ERR_PTR(-EOPNOTSUPP);
2278 	if (a[OVS_VPORT_ATTR_NAME]) {
2279 		vport = ovs_vport_locate(net, nla_data(a[OVS_VPORT_ATTR_NAME]));
2280 		if (!vport)
2281 			return ERR_PTR(-ENODEV);
2282 		if (ovs_header->dp_ifindex &&
2283 		    ovs_header->dp_ifindex != get_dpifindex(vport->dp))
2284 			return ERR_PTR(-ENODEV);
2285 		return vport;
2286 	} else if (a[OVS_VPORT_ATTR_PORT_NO]) {
2287 		u32 port_no = nla_get_u32(a[OVS_VPORT_ATTR_PORT_NO]);
2288 
2289 		if (port_no >= DP_MAX_PORTS)
2290 			return ERR_PTR(-EFBIG);
2291 
2292 		dp = get_dp(net, ovs_header->dp_ifindex);
2293 		if (!dp)
2294 			return ERR_PTR(-ENODEV);
2295 
2296 		vport = ovs_vport_ovsl_rcu(dp, port_no);
2297 		if (!vport)
2298 			return ERR_PTR(-ENODEV);
2299 		return vport;
2300 	} else
2301 		return ERR_PTR(-EINVAL);
2302 
2303 }
2304 
2305 static unsigned int ovs_get_max_headroom(struct datapath *dp)
2306 {
2307 	unsigned int dev_headroom, max_headroom = 0;
2308 	struct net_device *dev;
2309 	struct vport *vport;
2310 	int i;
2311 
2312 	for (i = 0; i < DP_VPORT_HASH_BUCKETS; i++) {
2313 		hlist_for_each_entry_rcu(vport, &dp->ports[i], dp_hash_node,
2314 					 lockdep_ovsl_is_held()) {
2315 			dev = vport->dev;
2316 			dev_headroom = netdev_get_fwd_headroom(dev);
2317 			if (dev_headroom > max_headroom)
2318 				max_headroom = dev_headroom;
2319 		}
2320 	}
2321 
2322 	return max_headroom;
2323 }
2324 
2325 /* Called with ovs_mutex */
2326 static void ovs_update_headroom(struct datapath *dp, unsigned int new_headroom)
2327 {
2328 	struct vport *vport;
2329 	int i;
2330 
2331 	dp->max_headroom = new_headroom;
2332 	for (i = 0; i < DP_VPORT_HASH_BUCKETS; i++) {
2333 		hlist_for_each_entry_rcu(vport, &dp->ports[i], dp_hash_node,
2334 					 lockdep_ovsl_is_held())
2335 			netdev_set_rx_headroom(vport->dev, new_headroom);
2336 	}
2337 }
2338 
2339 static int ovs_vport_cmd_new(struct sk_buff *skb, struct genl_info *info)
2340 {
2341 	struct nlattr **a = info->attrs;
2342 	struct ovs_header *ovs_header = genl_info_userhdr(info);
2343 	struct vport_parms parms;
2344 	struct sk_buff *reply;
2345 	struct vport *vport;
2346 	struct datapath *dp;
2347 	unsigned int new_headroom;
2348 	u32 port_no;
2349 	int err;
2350 
2351 	if (!a[OVS_VPORT_ATTR_NAME] || !a[OVS_VPORT_ATTR_TYPE] ||
2352 	    !a[OVS_VPORT_ATTR_UPCALL_PID])
2353 		return -EINVAL;
2354 
2355 	parms.type = nla_get_u32(a[OVS_VPORT_ATTR_TYPE]);
2356 
2357 	if (a[OVS_VPORT_ATTR_IFINDEX] && parms.type != OVS_VPORT_TYPE_INTERNAL)
2358 		return -EOPNOTSUPP;
2359 
2360 	port_no = nla_get_u32_default(a[OVS_VPORT_ATTR_PORT_NO], 0);
2361 	if (port_no >= DP_MAX_PORTS)
2362 		return -EFBIG;
2363 
2364 	reply = ovs_vport_cmd_alloc_info();
2365 	if (!reply)
2366 		return -ENOMEM;
2367 
2368 	ovs_lock();
2369 restart:
2370 	dp = get_dp(sock_net(skb->sk), ovs_header->dp_ifindex);
2371 	err = -ENODEV;
2372 	if (!dp)
2373 		goto exit_unlock_free;
2374 
2375 	if (port_no) {
2376 		vport = ovs_vport_ovsl(dp, port_no);
2377 		err = -EBUSY;
2378 		if (vport)
2379 			goto exit_unlock_free;
2380 	} else {
2381 		for (port_no = 1; ; port_no++) {
2382 			if (port_no >= DP_MAX_PORTS) {
2383 				err = -EFBIG;
2384 				goto exit_unlock_free;
2385 			}
2386 			vport = ovs_vport_ovsl(dp, port_no);
2387 			if (!vport)
2388 				break;
2389 		}
2390 	}
2391 
2392 	parms.name = nla_data(a[OVS_VPORT_ATTR_NAME]);
2393 	parms.options = a[OVS_VPORT_ATTR_OPTIONS];
2394 	parms.dp = dp;
2395 	parms.port_no = port_no;
2396 	parms.upcall_portids = a[OVS_VPORT_ATTR_UPCALL_PID];
2397 	parms.desired_ifindex = nla_get_s32_default(a[OVS_VPORT_ATTR_IFINDEX],
2398 						    0);
2399 
2400 	vport = new_vport(&parms);
2401 	err = PTR_ERR(vport);
2402 	if (IS_ERR(vport)) {
2403 		if (err == -EAGAIN)
2404 			goto restart;
2405 		goto exit_unlock_free;
2406 	}
2407 
2408 	err = ovs_vport_cmd_fill_info(vport, reply, genl_info_net(info),
2409 				      info->snd_portid, info->snd_seq, 0,
2410 				      OVS_VPORT_CMD_NEW, GFP_KERNEL);
2411 
2412 	new_headroom = netdev_get_fwd_headroom(vport->dev);
2413 
2414 	if (new_headroom > dp->max_headroom)
2415 		ovs_update_headroom(dp, new_headroom);
2416 	else
2417 		netdev_set_rx_headroom(vport->dev, dp->max_headroom);
2418 
2419 	BUG_ON(err < 0);
2420 	ovs_unlock();
2421 
2422 	ovs_notify(&dp_vport_genl_family, reply, info);
2423 	return 0;
2424 
2425 exit_unlock_free:
2426 	ovs_unlock();
2427 	kfree_skb(reply);
2428 	return err;
2429 }
2430 
2431 static int ovs_vport_cmd_set(struct sk_buff *skb, struct genl_info *info)
2432 {
2433 	struct nlattr **a = info->attrs;
2434 	struct sk_buff *reply;
2435 	struct vport *vport;
2436 	int err;
2437 
2438 	reply = ovs_vport_cmd_alloc_info();
2439 	if (!reply)
2440 		return -ENOMEM;
2441 
2442 	ovs_lock();
2443 	vport = lookup_vport(sock_net(skb->sk), genl_info_userhdr(info), a);
2444 	err = PTR_ERR(vport);
2445 	if (IS_ERR(vport))
2446 		goto exit_unlock_free;
2447 
2448 	if (a[OVS_VPORT_ATTR_TYPE] &&
2449 	    nla_get_u32(a[OVS_VPORT_ATTR_TYPE]) != vport->ops->type) {
2450 		err = -EINVAL;
2451 		goto exit_unlock_free;
2452 	}
2453 
2454 	if (a[OVS_VPORT_ATTR_OPTIONS]) {
2455 		err = ovs_vport_set_options(vport, a[OVS_VPORT_ATTR_OPTIONS]);
2456 		if (err)
2457 			goto exit_unlock_free;
2458 	}
2459 
2460 
2461 	if (a[OVS_VPORT_ATTR_UPCALL_PID]) {
2462 		struct nlattr *ids = a[OVS_VPORT_ATTR_UPCALL_PID];
2463 
2464 		err = ovs_vport_set_upcall_portids(vport, ids);
2465 		if (err)
2466 			goto exit_unlock_free;
2467 	}
2468 
2469 	err = ovs_vport_cmd_fill_info(vport, reply, genl_info_net(info),
2470 				      info->snd_portid, info->snd_seq, 0,
2471 				      OVS_VPORT_CMD_SET, GFP_KERNEL);
2472 	BUG_ON(err < 0);
2473 
2474 	ovs_unlock();
2475 	ovs_notify(&dp_vport_genl_family, reply, info);
2476 	return 0;
2477 
2478 exit_unlock_free:
2479 	ovs_unlock();
2480 	kfree_skb(reply);
2481 	return err;
2482 }
2483 
2484 static int ovs_vport_cmd_del(struct sk_buff *skb, struct genl_info *info)
2485 {
2486 	bool update_headroom = false;
2487 	struct nlattr **a = info->attrs;
2488 	struct sk_buff *reply;
2489 	struct datapath *dp;
2490 	struct vport *vport;
2491 	unsigned int new_headroom;
2492 	int err;
2493 
2494 	reply = ovs_vport_cmd_alloc_info();
2495 	if (!reply)
2496 		return -ENOMEM;
2497 
2498 	ovs_lock();
2499 	vport = lookup_vport(sock_net(skb->sk), genl_info_userhdr(info), a);
2500 	err = PTR_ERR(vport);
2501 	if (IS_ERR(vport))
2502 		goto exit_unlock_free;
2503 
2504 	if (vport->port_no == OVSP_LOCAL) {
2505 		err = -EINVAL;
2506 		goto exit_unlock_free;
2507 	}
2508 
2509 	err = ovs_vport_cmd_fill_info(vport, reply, genl_info_net(info),
2510 				      info->snd_portid, info->snd_seq, 0,
2511 				      OVS_VPORT_CMD_DEL, GFP_KERNEL);
2512 	BUG_ON(err < 0);
2513 
2514 	/* the vport deletion may trigger dp headroom update */
2515 	dp = vport->dp;
2516 	if (netdev_get_fwd_headroom(vport->dev) == dp->max_headroom)
2517 		update_headroom = true;
2518 
2519 	netdev_reset_rx_headroom(vport->dev);
2520 	ovs_dp_detach_port(vport);
2521 
2522 	if (update_headroom) {
2523 		new_headroom = ovs_get_max_headroom(dp);
2524 
2525 		if (new_headroom < dp->max_headroom)
2526 			ovs_update_headroom(dp, new_headroom);
2527 	}
2528 	ovs_unlock();
2529 
2530 	ovs_notify(&dp_vport_genl_family, reply, info);
2531 	return 0;
2532 
2533 exit_unlock_free:
2534 	ovs_unlock();
2535 	kfree_skb(reply);
2536 	return err;
2537 }
2538 
2539 static int ovs_vport_cmd_get(struct sk_buff *skb, struct genl_info *info)
2540 {
2541 	struct nlattr **a = info->attrs;
2542 	struct ovs_header *ovs_header = genl_info_userhdr(info);
2543 	struct sk_buff *reply;
2544 	struct vport *vport;
2545 	int err;
2546 
2547 	reply = ovs_vport_cmd_alloc_info();
2548 	if (!reply)
2549 		return -ENOMEM;
2550 
2551 	rcu_read_lock();
2552 	vport = lookup_vport(sock_net(skb->sk), ovs_header, a);
2553 	err = PTR_ERR(vport);
2554 	if (IS_ERR(vport))
2555 		goto exit_unlock_free;
2556 	err = ovs_vport_cmd_fill_info(vport, reply, genl_info_net(info),
2557 				      info->snd_portid, info->snd_seq, 0,
2558 				      OVS_VPORT_CMD_GET, GFP_ATOMIC);
2559 	BUG_ON(err < 0);
2560 	rcu_read_unlock();
2561 
2562 	return genlmsg_reply(reply, info);
2563 
2564 exit_unlock_free:
2565 	rcu_read_unlock();
2566 	kfree_skb(reply);
2567 	return err;
2568 }
2569 
2570 static int ovs_vport_cmd_dump(struct sk_buff *skb, struct netlink_callback *cb)
2571 {
2572 	struct ovs_header *ovs_header = genlmsg_data(nlmsg_data(cb->nlh));
2573 	struct datapath *dp;
2574 	int bucket = cb->args[0], skip = cb->args[1];
2575 	int i, j = 0;
2576 
2577 	rcu_read_lock();
2578 	dp = get_dp_rcu(sock_net(skb->sk), ovs_header->dp_ifindex);
2579 	if (!dp) {
2580 		rcu_read_unlock();
2581 		return -ENODEV;
2582 	}
2583 	for (i = bucket; i < DP_VPORT_HASH_BUCKETS; i++) {
2584 		struct vport *vport;
2585 
2586 		j = 0;
2587 		hlist_for_each_entry_rcu(vport, &dp->ports[i], dp_hash_node) {
2588 			if (j >= skip &&
2589 			    ovs_vport_cmd_fill_info(vport, skb,
2590 						    sock_net(skb->sk),
2591 						    NETLINK_CB(cb->skb).portid,
2592 						    cb->nlh->nlmsg_seq,
2593 						    NLM_F_MULTI,
2594 						    OVS_VPORT_CMD_GET,
2595 						    GFP_ATOMIC) < 0)
2596 				goto out;
2597 
2598 			j++;
2599 		}
2600 		skip = 0;
2601 	}
2602 out:
2603 	rcu_read_unlock();
2604 
2605 	cb->args[0] = i;
2606 	cb->args[1] = j;
2607 
2608 	return skb->len;
2609 }
2610 
2611 static void ovs_dp_masks_rebalance(struct work_struct *work)
2612 {
2613 	struct ovs_net *ovs_net = container_of(work, struct ovs_net,
2614 					       masks_rebalance.work);
2615 	struct datapath *dp;
2616 
2617 	ovs_lock();
2618 
2619 	list_for_each_entry(dp, &ovs_net->dps, list_node)
2620 		ovs_flow_masks_rebalance(&dp->table);
2621 
2622 	ovs_unlock();
2623 
2624 	schedule_delayed_work(&ovs_net->masks_rebalance,
2625 			      msecs_to_jiffies(DP_MASKS_REBALANCE_INTERVAL));
2626 }
2627 
2628 static const struct nla_policy vport_policy[OVS_VPORT_ATTR_MAX + 1] = {
2629 	[OVS_VPORT_ATTR_NAME] = { .type = NLA_NUL_STRING, .len = IFNAMSIZ - 1 },
2630 	[OVS_VPORT_ATTR_STATS] = { .len = sizeof(struct ovs_vport_stats) },
2631 	[OVS_VPORT_ATTR_PORT_NO] = { .type = NLA_U32 },
2632 	[OVS_VPORT_ATTR_TYPE] = { .type = NLA_U32 },
2633 	[OVS_VPORT_ATTR_UPCALL_PID] = { .type = NLA_UNSPEC },
2634 	[OVS_VPORT_ATTR_OPTIONS] = { .type = NLA_NESTED },
2635 	[OVS_VPORT_ATTR_IFINDEX] = NLA_POLICY_MIN(NLA_S32, 0),
2636 	[OVS_VPORT_ATTR_NETNSID] = { .type = NLA_S32 },
2637 	[OVS_VPORT_ATTR_UPCALL_STATS] = { .type = NLA_NESTED },
2638 };
2639 
2640 static const struct genl_small_ops dp_vport_genl_ops[] = {
2641 	{ .cmd = OVS_VPORT_CMD_NEW,
2642 	  .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2643 	  .flags = GENL_UNS_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
2644 	  .doit = ovs_vport_cmd_new
2645 	},
2646 	{ .cmd = OVS_VPORT_CMD_DEL,
2647 	  .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2648 	  .flags = GENL_UNS_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
2649 	  .doit = ovs_vport_cmd_del
2650 	},
2651 	{ .cmd = OVS_VPORT_CMD_GET,
2652 	  .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2653 	  .flags = 0,		    /* OK for unprivileged users. */
2654 	  .doit = ovs_vport_cmd_get,
2655 	  .dumpit = ovs_vport_cmd_dump
2656 	},
2657 	{ .cmd = OVS_VPORT_CMD_SET,
2658 	  .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2659 	  .flags = GENL_UNS_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
2660 	  .doit = ovs_vport_cmd_set,
2661 	},
2662 };
2663 
2664 struct genl_family dp_vport_genl_family __ro_after_init = {
2665 	.hdrsize = sizeof(struct ovs_header),
2666 	.name = OVS_VPORT_FAMILY,
2667 	.version = OVS_VPORT_VERSION,
2668 	.maxattr = OVS_VPORT_ATTR_MAX,
2669 	.policy = vport_policy,
2670 	.netnsok = true,
2671 	.parallel_ops = true,
2672 	.small_ops = dp_vport_genl_ops,
2673 	.n_small_ops = ARRAY_SIZE(dp_vport_genl_ops),
2674 	.resv_start_op = OVS_VPORT_CMD_SET + 1,
2675 	.mcgrps = &ovs_dp_vport_multicast_group,
2676 	.n_mcgrps = 1,
2677 	.module = THIS_MODULE,
2678 };
2679 
2680 static struct genl_family * const dp_genl_families[] = {
2681 	&dp_datapath_genl_family,
2682 	&dp_vport_genl_family,
2683 	&dp_flow_genl_family,
2684 	&dp_packet_genl_family,
2685 	&dp_meter_genl_family,
2686 #if	IS_ENABLED(CONFIG_NETFILTER_CONNCOUNT)
2687 	&dp_ct_limit_genl_family,
2688 #endif
2689 };
2690 
2691 static void dp_unregister_genl(int n_families)
2692 {
2693 	int i;
2694 
2695 	for (i = 0; i < n_families; i++)
2696 		genl_unregister_family(dp_genl_families[i]);
2697 }
2698 
2699 static int __init dp_register_genl(void)
2700 {
2701 	int err;
2702 	int i;
2703 
2704 	for (i = 0; i < ARRAY_SIZE(dp_genl_families); i++) {
2705 
2706 		err = genl_register_family(dp_genl_families[i]);
2707 		if (err)
2708 			goto error;
2709 	}
2710 
2711 	return 0;
2712 
2713 error:
2714 	dp_unregister_genl(i);
2715 	return err;
2716 }
2717 
2718 static int __net_init ovs_init_net(struct net *net)
2719 {
2720 	struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
2721 	int err;
2722 
2723 	INIT_LIST_HEAD(&ovs_net->dps);
2724 	INIT_WORK(&ovs_net->dp_notify_work, ovs_dp_notify_wq);
2725 	INIT_DELAYED_WORK(&ovs_net->masks_rebalance, ovs_dp_masks_rebalance);
2726 
2727 	err = ovs_ct_init(net);
2728 	if (err)
2729 		return err;
2730 
2731 	schedule_delayed_work(&ovs_net->masks_rebalance,
2732 			      msecs_to_jiffies(DP_MASKS_REBALANCE_INTERVAL));
2733 	return 0;
2734 }
2735 
2736 static void __net_exit list_vports_from_net(struct net *net, struct net *dnet,
2737 					    struct list_head *head)
2738 {
2739 	struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
2740 	struct datapath *dp;
2741 
2742 	list_for_each_entry(dp, &ovs_net->dps, list_node) {
2743 		int i;
2744 
2745 		for (i = 0; i < DP_VPORT_HASH_BUCKETS; i++) {
2746 			struct vport *vport;
2747 
2748 			hlist_for_each_entry(vport, &dp->ports[i], dp_hash_node) {
2749 				if (vport->ops->type != OVS_VPORT_TYPE_INTERNAL)
2750 					continue;
2751 
2752 				if (dev_net(vport->dev) == dnet)
2753 					list_add(&vport->detach_list, head);
2754 			}
2755 		}
2756 	}
2757 }
2758 
2759 static void __net_exit ovs_exit_net(struct net *dnet)
2760 {
2761 	struct datapath *dp, *dp_next;
2762 	struct ovs_net *ovs_net = net_generic(dnet, ovs_net_id);
2763 	struct vport *vport, *vport_next;
2764 	struct net *net;
2765 	LIST_HEAD(head);
2766 
2767 	ovs_lock();
2768 
2769 	ovs_ct_exit(dnet);
2770 
2771 	list_for_each_entry_safe(dp, dp_next, &ovs_net->dps, list_node)
2772 		__dp_destroy(dp);
2773 
2774 	down_read(&net_rwsem);
2775 	for_each_net(net)
2776 		list_vports_from_net(net, dnet, &head);
2777 	up_read(&net_rwsem);
2778 
2779 	/* Detach all vports from given namespace. */
2780 	list_for_each_entry_safe(vport, vport_next, &head, detach_list) {
2781 		list_del(&vport->detach_list);
2782 		ovs_dp_detach_port(vport);
2783 	}
2784 
2785 	ovs_unlock();
2786 
2787 	cancel_delayed_work_sync(&ovs_net->masks_rebalance);
2788 	cancel_work_sync(&ovs_net->dp_notify_work);
2789 }
2790 
2791 static struct pernet_operations ovs_net_ops = {
2792 	.init = ovs_init_net,
2793 	.exit = ovs_exit_net,
2794 	.id   = &ovs_net_id,
2795 	.size = sizeof(struct ovs_net),
2796 };
2797 
2798 static const char * const ovs_drop_reasons[] = {
2799 #define S(x) [(x) & ~SKB_DROP_REASON_SUBSYS_MASK] = (#x),
2800 	OVS_DROP_REASONS(S)
2801 #undef S
2802 };
2803 
2804 static struct drop_reason_list drop_reason_list_ovs = {
2805 	.reasons = ovs_drop_reasons,
2806 	.n_reasons = ARRAY_SIZE(ovs_drop_reasons),
2807 };
2808 
2809 static int __init ovs_alloc_percpu_storage(void)
2810 {
2811 	unsigned int cpu;
2812 
2813 	ovs_pcpu_storage = alloc_percpu(*ovs_pcpu_storage);
2814 	if (!ovs_pcpu_storage)
2815 		return -ENOMEM;
2816 
2817 	for_each_possible_cpu(cpu) {
2818 		struct ovs_pcpu_storage *ovs_pcpu;
2819 
2820 		ovs_pcpu = per_cpu_ptr(ovs_pcpu_storage, cpu);
2821 		local_lock_init(&ovs_pcpu->bh_lock);
2822 	}
2823 	return 0;
2824 }
2825 
2826 static void ovs_free_percpu_storage(void)
2827 {
2828 	free_percpu(ovs_pcpu_storage);
2829 }
2830 
2831 static int __init dp_init(void)
2832 {
2833 	int err;
2834 
2835 	BUILD_BUG_ON(sizeof(struct ovs_skb_cb) >
2836 		     sizeof_field(struct sk_buff, cb));
2837 
2838 	pr_info("Open vSwitch switching datapath\n");
2839 
2840 	err = ovs_alloc_percpu_storage();
2841 	if (err)
2842 		goto error;
2843 
2844 	err = ovs_internal_dev_rtnl_link_register();
2845 	if (err)
2846 		goto error;
2847 
2848 	err = ovs_flow_init();
2849 	if (err)
2850 		goto error_unreg_rtnl_link;
2851 
2852 	err = ovs_vport_init();
2853 	if (err)
2854 		goto error_flow_exit;
2855 
2856 	err = register_pernet_device(&ovs_net_ops);
2857 	if (err)
2858 		goto error_vport_exit;
2859 
2860 	err = register_netdevice_notifier(&ovs_dp_device_notifier);
2861 	if (err)
2862 		goto error_netns_exit;
2863 
2864 	err = ovs_netdev_init();
2865 	if (err)
2866 		goto error_unreg_notifier;
2867 
2868 	err = dp_register_genl();
2869 	if (err < 0)
2870 		goto error_unreg_netdev;
2871 
2872 	drop_reasons_register_subsys(SKB_DROP_REASON_SUBSYS_OPENVSWITCH,
2873 				     &drop_reason_list_ovs);
2874 
2875 	return 0;
2876 
2877 error_unreg_netdev:
2878 	ovs_netdev_exit();
2879 error_unreg_notifier:
2880 	unregister_netdevice_notifier(&ovs_dp_device_notifier);
2881 error_netns_exit:
2882 	unregister_pernet_device(&ovs_net_ops);
2883 error_vport_exit:
2884 	ovs_vport_exit();
2885 error_flow_exit:
2886 	ovs_flow_exit();
2887 error_unreg_rtnl_link:
2888 	ovs_internal_dev_rtnl_link_unregister();
2889 error:
2890 	ovs_free_percpu_storage();
2891 	return err;
2892 }
2893 
2894 static void dp_cleanup(void)
2895 {
2896 	dp_unregister_genl(ARRAY_SIZE(dp_genl_families));
2897 	ovs_netdev_exit();
2898 	unregister_netdevice_notifier(&ovs_dp_device_notifier);
2899 	unregister_pernet_device(&ovs_net_ops);
2900 	drop_reasons_unregister_subsys(SKB_DROP_REASON_SUBSYS_OPENVSWITCH);
2901 	rcu_barrier();
2902 	ovs_vport_exit();
2903 	ovs_flow_exit();
2904 	ovs_internal_dev_rtnl_link_unregister();
2905 	ovs_free_percpu_storage();
2906 }
2907 
2908 module_init(dp_init);
2909 module_exit(dp_cleanup);
2910 
2911 MODULE_DESCRIPTION("Open vSwitch switching datapath");
2912 MODULE_LICENSE("GPL");
2913 MODULE_ALIAS_GENL_FAMILY(OVS_DATAPATH_FAMILY);
2914 MODULE_ALIAS_GENL_FAMILY(OVS_VPORT_FAMILY);
2915 MODULE_ALIAS_GENL_FAMILY(OVS_FLOW_FAMILY);
2916 MODULE_ALIAS_GENL_FAMILY(OVS_PACKET_FAMILY);
2917 MODULE_ALIAS_GENL_FAMILY(OVS_METER_FAMILY);
2918 MODULE_ALIAS_GENL_FAMILY(OVS_CT_LIMIT_FAMILY);
2919