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