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         WARN(dp->user_features, "Dropping previously announced user features\n");
1609         dp->user_features = 0;
1610 }
1611
1612 DEFINE_STATIC_KEY_FALSE(tc_recirc_sharing_support);
1613
1614 static int ovs_dp_set_upcall_portids(struct datapath *dp,
1615                               const struct nlattr *ids)
1616 {
1617         struct dp_nlsk_pids *old, *dp_nlsk_pids;
1618
1619         if (!nla_len(ids) || nla_len(ids) % sizeof(u32))
1620                 return -EINVAL;
1621
1622         old = ovsl_dereference(dp->upcall_portids);
1623
1624         dp_nlsk_pids = kmalloc(sizeof(*dp_nlsk_pids) + nla_len(ids),
1625                                GFP_KERNEL);
1626         if (!dp_nlsk_pids)
1627                 return -ENOMEM;
1628
1629         dp_nlsk_pids->n_pids = nla_len(ids) / sizeof(u32);
1630         nla_memcpy(dp_nlsk_pids->pids, ids, nla_len(ids));
1631
1632         rcu_assign_pointer(dp->upcall_portids, dp_nlsk_pids);
1633
1634         kfree_rcu(old, rcu);
1635
1636         return 0;
1637 }
1638
1639 u32 ovs_dp_get_upcall_portid(const struct datapath *dp, uint32_t cpu_id)
1640 {
1641         struct dp_nlsk_pids *dp_nlsk_pids;
1642
1643         dp_nlsk_pids = rcu_dereference(dp->upcall_portids);
1644
1645         if (dp_nlsk_pids) {
1646                 if (cpu_id < dp_nlsk_pids->n_pids) {
1647                         return dp_nlsk_pids->pids[cpu_id];
1648                 } else if (dp_nlsk_pids->n_pids > 0 &&
1649                            cpu_id >= dp_nlsk_pids->n_pids) {
1650                         /* If the number of netlink PIDs is mismatched with
1651                          * the number of CPUs as seen by the kernel, log this
1652                          * and send the upcall to an arbitrary socket (0) in
1653                          * order to not drop packets
1654                          */
1655                         pr_info_ratelimited("cpu_id mismatch with handler threads");
1656                         return dp_nlsk_pids->pids[cpu_id %
1657                                                   dp_nlsk_pids->n_pids];
1658                 } else {
1659                         return 0;
1660                 }
1661         } else {
1662                 return 0;
1663         }
1664 }
1665
1666 static int ovs_dp_change(struct datapath *dp, struct nlattr *a[])
1667 {
1668         u32 user_features = 0;
1669         int err;
1670
1671         if (a[OVS_DP_ATTR_USER_FEATURES]) {
1672                 user_features = nla_get_u32(a[OVS_DP_ATTR_USER_FEATURES]);
1673
1674                 if (user_features & ~(OVS_DP_F_VPORT_PIDS |
1675                                       OVS_DP_F_UNALIGNED |
1676                                       OVS_DP_F_TC_RECIRC_SHARING |
1677                                       OVS_DP_F_DISPATCH_UPCALL_PER_CPU))
1678                         return -EOPNOTSUPP;
1679
1680 #if !IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
1681                 if (user_features & OVS_DP_F_TC_RECIRC_SHARING)
1682                         return -EOPNOTSUPP;
1683 #endif
1684         }
1685
1686         if (a[OVS_DP_ATTR_MASKS_CACHE_SIZE]) {
1687                 int err;
1688                 u32 cache_size;
1689
1690                 cache_size = nla_get_u32(a[OVS_DP_ATTR_MASKS_CACHE_SIZE]);
1691                 err = ovs_flow_tbl_masks_cache_resize(&dp->table, cache_size);
1692                 if (err)
1693                         return err;
1694         }
1695
1696         dp->user_features = user_features;
1697
1698         if (dp->user_features & OVS_DP_F_DISPATCH_UPCALL_PER_CPU &&
1699             a[OVS_DP_ATTR_PER_CPU_PIDS]) {
1700                 /* Upcall Netlink Port IDs have been updated */
1701                 err = ovs_dp_set_upcall_portids(dp,
1702                                                 a[OVS_DP_ATTR_PER_CPU_PIDS]);
1703                 if (err)
1704                         return err;
1705         }
1706
1707         if (dp->user_features & OVS_DP_F_TC_RECIRC_SHARING)
1708                 static_branch_enable(&tc_recirc_sharing_support);
1709         else
1710                 static_branch_disable(&tc_recirc_sharing_support);
1711
1712         return 0;
1713 }
1714
1715 static int ovs_dp_stats_init(struct datapath *dp)
1716 {
1717         dp->stats_percpu = netdev_alloc_pcpu_stats(struct dp_stats_percpu);
1718         if (!dp->stats_percpu)
1719                 return -ENOMEM;
1720
1721         return 0;
1722 }
1723
1724 static int ovs_dp_vport_init(struct datapath *dp)
1725 {
1726         int i;
1727
1728         dp->ports = kmalloc_array(DP_VPORT_HASH_BUCKETS,
1729                                   sizeof(struct hlist_head),
1730                                   GFP_KERNEL);
1731         if (!dp->ports)
1732                 return -ENOMEM;
1733
1734         for (i = 0; i < DP_VPORT_HASH_BUCKETS; i++)
1735                 INIT_HLIST_HEAD(&dp->ports[i]);
1736
1737         return 0;
1738 }
1739
1740 static int ovs_dp_cmd_new(struct sk_buff *skb, struct genl_info *info)
1741 {
1742         struct nlattr **a = info->attrs;
1743         struct vport_parms parms;
1744         struct sk_buff *reply;
1745         struct datapath *dp;
1746         struct vport *vport;
1747         struct ovs_net *ovs_net;
1748         int err;
1749
1750         err = -EINVAL;
1751         if (!a[OVS_DP_ATTR_NAME] || !a[OVS_DP_ATTR_UPCALL_PID])
1752                 goto err;
1753
1754         reply = ovs_dp_cmd_alloc_info();
1755         if (!reply)
1756                 return -ENOMEM;
1757
1758         err = -ENOMEM;
1759         dp = kzalloc(sizeof(*dp), GFP_KERNEL);
1760         if (dp == NULL)
1761                 goto err_destroy_reply;
1762
1763         ovs_dp_set_net(dp, sock_net(skb->sk));
1764
1765         /* Allocate table. */
1766         err = ovs_flow_tbl_init(&dp->table);
1767         if (err)
1768                 goto err_destroy_dp;
1769
1770         err = ovs_dp_stats_init(dp);
1771         if (err)
1772                 goto err_destroy_table;
1773
1774         err = ovs_dp_vport_init(dp);
1775         if (err)
1776                 goto err_destroy_stats;
1777
1778         err = ovs_meters_init(dp);
1779         if (err)
1780                 goto err_destroy_ports;
1781
1782         /* Set up our datapath device. */
1783         parms.name = nla_data(a[OVS_DP_ATTR_NAME]);
1784         parms.type = OVS_VPORT_TYPE_INTERNAL;
1785         parms.options = NULL;
1786         parms.dp = dp;
1787         parms.port_no = OVSP_LOCAL;
1788         parms.upcall_portids = a[OVS_DP_ATTR_UPCALL_PID];
1789
1790         /* So far only local changes have been made, now need the lock. */
1791         ovs_lock();
1792
1793         err = ovs_dp_change(dp, a);
1794         if (err)
1795                 goto err_unlock_and_destroy_meters;
1796
1797         vport = new_vport(&parms);
1798         if (IS_ERR(vport)) {
1799                 err = PTR_ERR(vport);
1800                 if (err == -EBUSY)
1801                         err = -EEXIST;
1802
1803                 if (err == -EEXIST) {
1804                         /* An outdated user space instance that does not understand
1805                          * the concept of user_features has attempted to create a new
1806                          * datapath and is likely to reuse it. Drop all user features.
1807                          */
1808                         if (info->genlhdr->version < OVS_DP_VER_FEATURES)
1809                                 ovs_dp_reset_user_features(skb, info);
1810                 }
1811
1812                 goto err_destroy_portids;
1813         }
1814
1815         err = ovs_dp_cmd_fill_info(dp, reply, info->snd_portid,
1816                                    info->snd_seq, 0, OVS_DP_CMD_NEW);
1817         BUG_ON(err < 0);
1818
1819         ovs_net = net_generic(ovs_dp_get_net(dp), ovs_net_id);
1820         list_add_tail_rcu(&dp->list_node, &ovs_net->dps);
1821
1822         ovs_unlock();
1823
1824         ovs_notify(&dp_datapath_genl_family, reply, info);
1825         return 0;
1826
1827 err_destroy_portids:
1828         kfree(rcu_dereference_raw(dp->upcall_portids));
1829 err_unlock_and_destroy_meters:
1830         ovs_unlock();
1831         ovs_meters_exit(dp);
1832 err_destroy_ports:
1833         kfree(dp->ports);
1834 err_destroy_stats:
1835         free_percpu(dp->stats_percpu);
1836 err_destroy_table:
1837         ovs_flow_tbl_destroy(&dp->table);
1838 err_destroy_dp:
1839         kfree(dp);
1840 err_destroy_reply:
1841         kfree_skb(reply);
1842 err:
1843         return err;
1844 }
1845
1846 /* Called with ovs_mutex. */
1847 static void __dp_destroy(struct datapath *dp)
1848 {
1849         struct flow_table *table = &dp->table;
1850         int i;
1851
1852         for (i = 0; i < DP_VPORT_HASH_BUCKETS; i++) {
1853                 struct vport *vport;
1854                 struct hlist_node *n;
1855
1856                 hlist_for_each_entry_safe(vport, n, &dp->ports[i], dp_hash_node)
1857                         if (vport->port_no != OVSP_LOCAL)
1858                                 ovs_dp_detach_port(vport);
1859         }
1860
1861         list_del_rcu(&dp->list_node);
1862
1863         /* OVSP_LOCAL is datapath internal port. We need to make sure that
1864          * all ports in datapath are destroyed first before freeing datapath.
1865          */
1866         ovs_dp_detach_port(ovs_vport_ovsl(dp, OVSP_LOCAL));
1867
1868         /* Flush sw_flow in the tables. RCU cb only releases resource
1869          * such as dp, ports and tables. That may avoid some issues
1870          * such as RCU usage warning.
1871          */
1872         table_instance_flow_flush(table, ovsl_dereference(table->ti),
1873                                   ovsl_dereference(table->ufid_ti));
1874
1875         /* RCU destroy the ports, meters and flow tables. */
1876         call_rcu(&dp->rcu, destroy_dp_rcu);
1877 }
1878
1879 static int ovs_dp_cmd_del(struct sk_buff *skb, struct genl_info *info)
1880 {
1881         struct sk_buff *reply;
1882         struct datapath *dp;
1883         int err;
1884
1885         reply = ovs_dp_cmd_alloc_info();
1886         if (!reply)
1887                 return -ENOMEM;
1888
1889         ovs_lock();
1890         dp = lookup_datapath(sock_net(skb->sk), info->userhdr, info->attrs);
1891         err = PTR_ERR(dp);
1892         if (IS_ERR(dp))
1893                 goto err_unlock_free;
1894
1895         err = ovs_dp_cmd_fill_info(dp, reply, info->snd_portid,
1896                                    info->snd_seq, 0, OVS_DP_CMD_DEL);
1897         BUG_ON(err < 0);
1898
1899         __dp_destroy(dp);
1900         ovs_unlock();
1901
1902         ovs_notify(&dp_datapath_genl_family, reply, info);
1903
1904         return 0;
1905
1906 err_unlock_free:
1907         ovs_unlock();
1908         kfree_skb(reply);
1909         return err;
1910 }
1911
1912 static int ovs_dp_cmd_set(struct sk_buff *skb, struct genl_info *info)
1913 {
1914         struct sk_buff *reply;
1915         struct datapath *dp;
1916         int err;
1917
1918         reply = ovs_dp_cmd_alloc_info();
1919         if (!reply)
1920                 return -ENOMEM;
1921
1922         ovs_lock();
1923         dp = lookup_datapath(sock_net(skb->sk), info->userhdr, info->attrs);
1924         err = PTR_ERR(dp);
1925         if (IS_ERR(dp))
1926                 goto err_unlock_free;
1927
1928         err = ovs_dp_change(dp, info->attrs);
1929         if (err)
1930                 goto err_unlock_free;
1931
1932         err = ovs_dp_cmd_fill_info(dp, reply, info->snd_portid,
1933                                    info->snd_seq, 0, OVS_DP_CMD_SET);
1934         BUG_ON(err < 0);
1935
1936         ovs_unlock();
1937         ovs_notify(&dp_datapath_genl_family, reply, info);
1938
1939         return 0;
1940
1941 err_unlock_free:
1942         ovs_unlock();
1943         kfree_skb(reply);
1944         return err;
1945 }
1946
1947 static int ovs_dp_cmd_get(struct sk_buff *skb, struct genl_info *info)
1948 {
1949         struct sk_buff *reply;
1950         struct datapath *dp;
1951         int err;
1952
1953         reply = ovs_dp_cmd_alloc_info();
1954         if (!reply)
1955                 return -ENOMEM;
1956
1957         ovs_lock();
1958         dp = lookup_datapath(sock_net(skb->sk), info->userhdr, info->attrs);
1959         if (IS_ERR(dp)) {
1960                 err = PTR_ERR(dp);
1961                 goto err_unlock_free;
1962         }
1963         err = ovs_dp_cmd_fill_info(dp, reply, info->snd_portid,
1964                                    info->snd_seq, 0, OVS_DP_CMD_GET);
1965         BUG_ON(err < 0);
1966         ovs_unlock();
1967
1968         return genlmsg_reply(reply, info);
1969
1970 err_unlock_free:
1971         ovs_unlock();
1972         kfree_skb(reply);
1973         return err;
1974 }
1975
1976 static int ovs_dp_cmd_dump(struct sk_buff *skb, struct netlink_callback *cb)
1977 {
1978         struct ovs_net *ovs_net = net_generic(sock_net(skb->sk), ovs_net_id);
1979         struct datapath *dp;
1980         int skip = cb->args[0];
1981         int i = 0;
1982
1983         ovs_lock();
1984         list_for_each_entry(dp, &ovs_net->dps, list_node) {
1985                 if (i >= skip &&
1986                     ovs_dp_cmd_fill_info(dp, skb, NETLINK_CB(cb->skb).portid,
1987                                          cb->nlh->nlmsg_seq, NLM_F_MULTI,
1988                                          OVS_DP_CMD_GET) < 0)
1989                         break;
1990                 i++;
1991         }
1992         ovs_unlock();
1993
1994         cb->args[0] = i;
1995
1996         return skb->len;
1997 }
1998
1999 static const struct nla_policy datapath_policy[OVS_DP_ATTR_MAX + 1] = {
2000         [OVS_DP_ATTR_NAME] = { .type = NLA_NUL_STRING, .len = IFNAMSIZ - 1 },
2001         [OVS_DP_ATTR_UPCALL_PID] = { .type = NLA_U32 },
2002         [OVS_DP_ATTR_USER_FEATURES] = { .type = NLA_U32 },
2003         [OVS_DP_ATTR_MASKS_CACHE_SIZE] =  NLA_POLICY_RANGE(NLA_U32, 0,
2004                 PCPU_MIN_UNIT_SIZE / sizeof(struct mask_cache_entry)),
2005 };
2006
2007 static const struct genl_small_ops dp_datapath_genl_ops[] = {
2008         { .cmd = OVS_DP_CMD_NEW,
2009           .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2010           .flags = GENL_UNS_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
2011           .doit = ovs_dp_cmd_new
2012         },
2013         { .cmd = OVS_DP_CMD_DEL,
2014           .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2015           .flags = GENL_UNS_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
2016           .doit = ovs_dp_cmd_del
2017         },
2018         { .cmd = OVS_DP_CMD_GET,
2019           .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2020           .flags = 0,               /* OK for unprivileged users. */
2021           .doit = ovs_dp_cmd_get,
2022           .dumpit = ovs_dp_cmd_dump
2023         },
2024         { .cmd = OVS_DP_CMD_SET,
2025           .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2026           .flags = GENL_UNS_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
2027           .doit = ovs_dp_cmd_set,
2028         },
2029 };
2030
2031 static struct genl_family dp_datapath_genl_family __ro_after_init = {
2032         .hdrsize = sizeof(struct ovs_header),
2033         .name = OVS_DATAPATH_FAMILY,
2034         .version = OVS_DATAPATH_VERSION,
2035         .maxattr = OVS_DP_ATTR_MAX,
2036         .policy = datapath_policy,
2037         .netnsok = true,
2038         .parallel_ops = true,
2039         .small_ops = dp_datapath_genl_ops,
2040         .n_small_ops = ARRAY_SIZE(dp_datapath_genl_ops),
2041         .mcgrps = &ovs_dp_datapath_multicast_group,
2042         .n_mcgrps = 1,
2043         .module = THIS_MODULE,
2044 };
2045
2046 /* Called with ovs_mutex or RCU read lock. */
2047 static int ovs_vport_cmd_fill_info(struct vport *vport, struct sk_buff *skb,
2048                                    struct net *net, u32 portid, u32 seq,
2049                                    u32 flags, u8 cmd, gfp_t gfp)
2050 {
2051         struct ovs_header *ovs_header;
2052         struct ovs_vport_stats vport_stats;
2053         int err;
2054
2055         ovs_header = genlmsg_put(skb, portid, seq, &dp_vport_genl_family,
2056                                  flags, cmd);
2057         if (!ovs_header)
2058                 return -EMSGSIZE;
2059
2060         ovs_header->dp_ifindex = get_dpifindex(vport->dp);
2061
2062         if (nla_put_u32(skb, OVS_VPORT_ATTR_PORT_NO, vport->port_no) ||
2063             nla_put_u32(skb, OVS_VPORT_ATTR_TYPE, vport->ops->type) ||
2064             nla_put_string(skb, OVS_VPORT_ATTR_NAME,
2065                            ovs_vport_name(vport)) ||
2066             nla_put_u32(skb, OVS_VPORT_ATTR_IFINDEX, vport->dev->ifindex))
2067                 goto nla_put_failure;
2068
2069         if (!net_eq(net, dev_net(vport->dev))) {
2070                 int id = peernet2id_alloc(net, dev_net(vport->dev), gfp);
2071
2072                 if (nla_put_s32(skb, OVS_VPORT_ATTR_NETNSID, id))
2073                         goto nla_put_failure;
2074         }
2075
2076         ovs_vport_get_stats(vport, &vport_stats);
2077         if (nla_put_64bit(skb, OVS_VPORT_ATTR_STATS,
2078                           sizeof(struct ovs_vport_stats), &vport_stats,
2079                           OVS_VPORT_ATTR_PAD))
2080                 goto nla_put_failure;
2081
2082         if (ovs_vport_get_upcall_portids(vport, skb))
2083                 goto nla_put_failure;
2084
2085         err = ovs_vport_get_options(vport, skb);
2086         if (err == -EMSGSIZE)
2087                 goto error;
2088
2089         genlmsg_end(skb, ovs_header);
2090         return 0;
2091
2092 nla_put_failure:
2093         err = -EMSGSIZE;
2094 error:
2095         genlmsg_cancel(skb, ovs_header);
2096         return err;
2097 }
2098
2099 static struct sk_buff *ovs_vport_cmd_alloc_info(void)
2100 {
2101         return nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
2102 }
2103
2104 /* Called with ovs_mutex, only via ovs_dp_notify_wq(). */
2105 struct sk_buff *ovs_vport_cmd_build_info(struct vport *vport, struct net *net,
2106                                          u32 portid, u32 seq, u8 cmd)
2107 {
2108         struct sk_buff *skb;
2109         int retval;
2110
2111         skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
2112         if (!skb)
2113                 return ERR_PTR(-ENOMEM);
2114
2115         retval = ovs_vport_cmd_fill_info(vport, skb, net, portid, seq, 0, cmd,
2116                                          GFP_KERNEL);
2117         BUG_ON(retval < 0);
2118
2119         return skb;
2120 }
2121
2122 /* Called with ovs_mutex or RCU read lock. */
2123 static struct vport *lookup_vport(struct net *net,
2124                                   const struct ovs_header *ovs_header,
2125                                   struct nlattr *a[OVS_VPORT_ATTR_MAX + 1])
2126 {
2127         struct datapath *dp;
2128         struct vport *vport;
2129
2130         if (a[OVS_VPORT_ATTR_IFINDEX])
2131                 return ERR_PTR(-EOPNOTSUPP);
2132         if (a[OVS_VPORT_ATTR_NAME]) {
2133                 vport = ovs_vport_locate(net, nla_data(a[OVS_VPORT_ATTR_NAME]));
2134                 if (!vport)
2135                         return ERR_PTR(-ENODEV);
2136                 if (ovs_header->dp_ifindex &&
2137                     ovs_header->dp_ifindex != get_dpifindex(vport->dp))
2138                         return ERR_PTR(-ENODEV);
2139                 return vport;
2140         } else if (a[OVS_VPORT_ATTR_PORT_NO]) {
2141                 u32 port_no = nla_get_u32(a[OVS_VPORT_ATTR_PORT_NO]);
2142
2143                 if (port_no >= DP_MAX_PORTS)
2144                         return ERR_PTR(-EFBIG);
2145
2146                 dp = get_dp(net, ovs_header->dp_ifindex);
2147                 if (!dp)
2148                         return ERR_PTR(-ENODEV);
2149
2150                 vport = ovs_vport_ovsl_rcu(dp, port_no);
2151                 if (!vport)
2152                         return ERR_PTR(-ENODEV);
2153                 return vport;
2154         } else
2155                 return ERR_PTR(-EINVAL);
2156
2157 }
2158
2159 static unsigned int ovs_get_max_headroom(struct datapath *dp)
2160 {
2161         unsigned int dev_headroom, max_headroom = 0;
2162         struct net_device *dev;
2163         struct vport *vport;
2164         int i;
2165
2166         for (i = 0; i < DP_VPORT_HASH_BUCKETS; i++) {
2167                 hlist_for_each_entry_rcu(vport, &dp->ports[i], dp_hash_node,
2168                                          lockdep_ovsl_is_held()) {
2169                         dev = vport->dev;
2170                         dev_headroom = netdev_get_fwd_headroom(dev);
2171                         if (dev_headroom > max_headroom)
2172                                 max_headroom = dev_headroom;
2173                 }
2174         }
2175
2176         return max_headroom;
2177 }
2178
2179 /* Called with ovs_mutex */
2180 static void ovs_update_headroom(struct datapath *dp, unsigned int new_headroom)
2181 {
2182         struct vport *vport;
2183         int i;
2184
2185         dp->max_headroom = new_headroom;
2186         for (i = 0; i < DP_VPORT_HASH_BUCKETS; i++) {
2187                 hlist_for_each_entry_rcu(vport, &dp->ports[i], dp_hash_node,
2188                                          lockdep_ovsl_is_held())
2189                         netdev_set_rx_headroom(vport->dev, new_headroom);
2190         }
2191 }
2192
2193 static int ovs_vport_cmd_new(struct sk_buff *skb, struct genl_info *info)
2194 {
2195         struct nlattr **a = info->attrs;
2196         struct ovs_header *ovs_header = info->userhdr;
2197         struct vport_parms parms;
2198         struct sk_buff *reply;
2199         struct vport *vport;
2200         struct datapath *dp;
2201         unsigned int new_headroom;
2202         u32 port_no;
2203         int err;
2204
2205         if (!a[OVS_VPORT_ATTR_NAME] || !a[OVS_VPORT_ATTR_TYPE] ||
2206             !a[OVS_VPORT_ATTR_UPCALL_PID])
2207                 return -EINVAL;
2208         if (a[OVS_VPORT_ATTR_IFINDEX])
2209                 return -EOPNOTSUPP;
2210
2211         port_no = a[OVS_VPORT_ATTR_PORT_NO]
2212                 ? nla_get_u32(a[OVS_VPORT_ATTR_PORT_NO]) : 0;
2213         if (port_no >= DP_MAX_PORTS)
2214                 return -EFBIG;
2215
2216         reply = ovs_vport_cmd_alloc_info();
2217         if (!reply)
2218                 return -ENOMEM;
2219
2220         ovs_lock();
2221 restart:
2222         dp = get_dp(sock_net(skb->sk), ovs_header->dp_ifindex);
2223         err = -ENODEV;
2224         if (!dp)
2225                 goto exit_unlock_free;
2226
2227         if (port_no) {
2228                 vport = ovs_vport_ovsl(dp, port_no);
2229                 err = -EBUSY;
2230                 if (vport)
2231                         goto exit_unlock_free;
2232         } else {
2233                 for (port_no = 1; ; port_no++) {
2234                         if (port_no >= DP_MAX_PORTS) {
2235                                 err = -EFBIG;
2236                                 goto exit_unlock_free;
2237                         }
2238                         vport = ovs_vport_ovsl(dp, port_no);
2239                         if (!vport)
2240                                 break;
2241                 }
2242         }
2243
2244         parms.name = nla_data(a[OVS_VPORT_ATTR_NAME]);
2245         parms.type = nla_get_u32(a[OVS_VPORT_ATTR_TYPE]);
2246         parms.options = a[OVS_VPORT_ATTR_OPTIONS];
2247         parms.dp = dp;
2248         parms.port_no = port_no;
2249         parms.upcall_portids = a[OVS_VPORT_ATTR_UPCALL_PID];
2250
2251         vport = new_vport(&parms);
2252         err = PTR_ERR(vport);
2253         if (IS_ERR(vport)) {
2254                 if (err == -EAGAIN)
2255                         goto restart;
2256                 goto exit_unlock_free;
2257         }
2258
2259         err = ovs_vport_cmd_fill_info(vport, reply, genl_info_net(info),
2260                                       info->snd_portid, info->snd_seq, 0,
2261                                       OVS_VPORT_CMD_NEW, GFP_KERNEL);
2262
2263         new_headroom = netdev_get_fwd_headroom(vport->dev);
2264
2265         if (new_headroom > dp->max_headroom)
2266                 ovs_update_headroom(dp, new_headroom);
2267         else
2268                 netdev_set_rx_headroom(vport->dev, dp->max_headroom);
2269
2270         BUG_ON(err < 0);
2271         ovs_unlock();
2272
2273         ovs_notify(&dp_vport_genl_family, reply, info);
2274         return 0;
2275
2276 exit_unlock_free:
2277         ovs_unlock();
2278         kfree_skb(reply);
2279         return err;
2280 }
2281
2282 static int ovs_vport_cmd_set(struct sk_buff *skb, struct genl_info *info)
2283 {
2284         struct nlattr **a = info->attrs;
2285         struct sk_buff *reply;
2286         struct vport *vport;
2287         int err;
2288
2289         reply = ovs_vport_cmd_alloc_info();
2290         if (!reply)
2291                 return -ENOMEM;
2292
2293         ovs_lock();
2294         vport = lookup_vport(sock_net(skb->sk), info->userhdr, a);
2295         err = PTR_ERR(vport);
2296         if (IS_ERR(vport))
2297                 goto exit_unlock_free;
2298
2299         if (a[OVS_VPORT_ATTR_TYPE] &&
2300             nla_get_u32(a[OVS_VPORT_ATTR_TYPE]) != vport->ops->type) {
2301                 err = -EINVAL;
2302                 goto exit_unlock_free;
2303         }
2304
2305         if (a[OVS_VPORT_ATTR_OPTIONS]) {
2306                 err = ovs_vport_set_options(vport, a[OVS_VPORT_ATTR_OPTIONS]);
2307                 if (err)
2308                         goto exit_unlock_free;
2309         }
2310
2311
2312         if (a[OVS_VPORT_ATTR_UPCALL_PID]) {
2313                 struct nlattr *ids = a[OVS_VPORT_ATTR_UPCALL_PID];
2314
2315                 err = ovs_vport_set_upcall_portids(vport, ids);
2316                 if (err)
2317                         goto exit_unlock_free;
2318         }
2319
2320         err = ovs_vport_cmd_fill_info(vport, reply, genl_info_net(info),
2321                                       info->snd_portid, info->snd_seq, 0,
2322                                       OVS_VPORT_CMD_SET, GFP_KERNEL);
2323         BUG_ON(err < 0);
2324
2325         ovs_unlock();
2326         ovs_notify(&dp_vport_genl_family, reply, info);
2327         return 0;
2328
2329 exit_unlock_free:
2330         ovs_unlock();
2331         kfree_skb(reply);
2332         return err;
2333 }
2334
2335 static int ovs_vport_cmd_del(struct sk_buff *skb, struct genl_info *info)
2336 {
2337         bool update_headroom = false;
2338         struct nlattr **a = info->attrs;
2339         struct sk_buff *reply;
2340         struct datapath *dp;
2341         struct vport *vport;
2342         unsigned int new_headroom;
2343         int err;
2344
2345         reply = ovs_vport_cmd_alloc_info();
2346         if (!reply)
2347                 return -ENOMEM;
2348
2349         ovs_lock();
2350         vport = lookup_vport(sock_net(skb->sk), info->userhdr, a);
2351         err = PTR_ERR(vport);
2352         if (IS_ERR(vport))
2353                 goto exit_unlock_free;
2354
2355         if (vport->port_no == OVSP_LOCAL) {
2356                 err = -EINVAL;
2357                 goto exit_unlock_free;
2358         }
2359
2360         err = ovs_vport_cmd_fill_info(vport, reply, genl_info_net(info),
2361                                       info->snd_portid, info->snd_seq, 0,
2362                                       OVS_VPORT_CMD_DEL, GFP_KERNEL);
2363         BUG_ON(err < 0);
2364
2365         /* the vport deletion may trigger dp headroom update */
2366         dp = vport->dp;
2367         if (netdev_get_fwd_headroom(vport->dev) == dp->max_headroom)
2368                 update_headroom = true;
2369
2370         netdev_reset_rx_headroom(vport->dev);
2371         ovs_dp_detach_port(vport);
2372
2373         if (update_headroom) {
2374                 new_headroom = ovs_get_max_headroom(dp);
2375
2376                 if (new_headroom < dp->max_headroom)
2377                         ovs_update_headroom(dp, new_headroom);
2378         }
2379         ovs_unlock();
2380
2381         ovs_notify(&dp_vport_genl_family, reply, info);
2382         return 0;
2383
2384 exit_unlock_free:
2385         ovs_unlock();
2386         kfree_skb(reply);
2387         return err;
2388 }
2389
2390 static int ovs_vport_cmd_get(struct sk_buff *skb, struct genl_info *info)
2391 {
2392         struct nlattr **a = info->attrs;
2393         struct ovs_header *ovs_header = info->userhdr;
2394         struct sk_buff *reply;
2395         struct vport *vport;
2396         int err;
2397
2398         reply = ovs_vport_cmd_alloc_info();
2399         if (!reply)
2400                 return -ENOMEM;
2401
2402         rcu_read_lock();
2403         vport = lookup_vport(sock_net(skb->sk), ovs_header, a);
2404         err = PTR_ERR(vport);
2405         if (IS_ERR(vport))
2406                 goto exit_unlock_free;
2407         err = ovs_vport_cmd_fill_info(vport, reply, genl_info_net(info),
2408                                       info->snd_portid, info->snd_seq, 0,
2409                                       OVS_VPORT_CMD_GET, GFP_ATOMIC);
2410         BUG_ON(err < 0);
2411         rcu_read_unlock();
2412
2413         return genlmsg_reply(reply, info);
2414
2415 exit_unlock_free:
2416         rcu_read_unlock();
2417         kfree_skb(reply);
2418         return err;
2419 }
2420
2421 static int ovs_vport_cmd_dump(struct sk_buff *skb, struct netlink_callback *cb)
2422 {
2423         struct ovs_header *ovs_header = genlmsg_data(nlmsg_data(cb->nlh));
2424         struct datapath *dp;
2425         int bucket = cb->args[0], skip = cb->args[1];
2426         int i, j = 0;
2427
2428         rcu_read_lock();
2429         dp = get_dp_rcu(sock_net(skb->sk), ovs_header->dp_ifindex);
2430         if (!dp) {
2431                 rcu_read_unlock();
2432                 return -ENODEV;
2433         }
2434         for (i = bucket; i < DP_VPORT_HASH_BUCKETS; i++) {
2435                 struct vport *vport;
2436
2437                 j = 0;
2438                 hlist_for_each_entry_rcu(vport, &dp->ports[i], dp_hash_node) {
2439                         if (j >= skip &&
2440                             ovs_vport_cmd_fill_info(vport, skb,
2441                                                     sock_net(skb->sk),
2442                                                     NETLINK_CB(cb->skb).portid,
2443                                                     cb->nlh->nlmsg_seq,
2444                                                     NLM_F_MULTI,
2445                                                     OVS_VPORT_CMD_GET,
2446                                                     GFP_ATOMIC) < 0)
2447                                 goto out;
2448
2449                         j++;
2450                 }
2451                 skip = 0;
2452         }
2453 out:
2454         rcu_read_unlock();
2455
2456         cb->args[0] = i;
2457         cb->args[1] = j;
2458
2459         return skb->len;
2460 }
2461
2462 static void ovs_dp_masks_rebalance(struct work_struct *work)
2463 {
2464         struct ovs_net *ovs_net = container_of(work, struct ovs_net,
2465                                                masks_rebalance.work);
2466         struct datapath *dp;
2467
2468         ovs_lock();
2469
2470         list_for_each_entry(dp, &ovs_net->dps, list_node)
2471                 ovs_flow_masks_rebalance(&dp->table);
2472
2473         ovs_unlock();
2474
2475         schedule_delayed_work(&ovs_net->masks_rebalance,
2476                               msecs_to_jiffies(DP_MASKS_REBALANCE_INTERVAL));
2477 }
2478
2479 static const struct nla_policy vport_policy[OVS_VPORT_ATTR_MAX + 1] = {
2480         [OVS_VPORT_ATTR_NAME] = { .type = NLA_NUL_STRING, .len = IFNAMSIZ - 1 },
2481         [OVS_VPORT_ATTR_STATS] = { .len = sizeof(struct ovs_vport_stats) },
2482         [OVS_VPORT_ATTR_PORT_NO] = { .type = NLA_U32 },
2483         [OVS_VPORT_ATTR_TYPE] = { .type = NLA_U32 },
2484         [OVS_VPORT_ATTR_UPCALL_PID] = { .type = NLA_UNSPEC },
2485         [OVS_VPORT_ATTR_OPTIONS] = { .type = NLA_NESTED },
2486         [OVS_VPORT_ATTR_IFINDEX] = { .type = NLA_U32 },
2487         [OVS_VPORT_ATTR_NETNSID] = { .type = NLA_S32 },
2488 };
2489
2490 static const struct genl_small_ops dp_vport_genl_ops[] = {
2491         { .cmd = OVS_VPORT_CMD_NEW,
2492           .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2493           .flags = GENL_UNS_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
2494           .doit = ovs_vport_cmd_new
2495         },
2496         { .cmd = OVS_VPORT_CMD_DEL,
2497           .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2498           .flags = GENL_UNS_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
2499           .doit = ovs_vport_cmd_del
2500         },
2501         { .cmd = OVS_VPORT_CMD_GET,
2502           .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2503           .flags = 0,               /* OK for unprivileged users. */
2504           .doit = ovs_vport_cmd_get,
2505           .dumpit = ovs_vport_cmd_dump
2506         },
2507         { .cmd = OVS_VPORT_CMD_SET,
2508           .validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2509           .flags = GENL_UNS_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
2510           .doit = ovs_vport_cmd_set,
2511         },
2512 };
2513
2514 struct genl_family dp_vport_genl_family __ro_after_init = {
2515         .hdrsize = sizeof(struct ovs_header),
2516         .name = OVS_VPORT_FAMILY,
2517         .version = OVS_VPORT_VERSION,
2518         .maxattr = OVS_VPORT_ATTR_MAX,
2519         .policy = vport_policy,
2520         .netnsok = true,
2521         .parallel_ops = true,
2522         .small_ops = dp_vport_genl_ops,
2523         .n_small_ops = ARRAY_SIZE(dp_vport_genl_ops),
2524         .mcgrps = &ovs_dp_vport_multicast_group,
2525         .n_mcgrps = 1,
2526         .module = THIS_MODULE,
2527 };
2528
2529 static struct genl_family * const dp_genl_families[] = {
2530         &dp_datapath_genl_family,
2531         &dp_vport_genl_family,
2532         &dp_flow_genl_family,
2533         &dp_packet_genl_family,
2534         &dp_meter_genl_family,
2535 #if     IS_ENABLED(CONFIG_NETFILTER_CONNCOUNT)
2536         &dp_ct_limit_genl_family,
2537 #endif
2538 };
2539
2540 static void dp_unregister_genl(int n_families)
2541 {
2542         int i;
2543
2544         for (i = 0; i < n_families; i++)
2545                 genl_unregister_family(dp_genl_families[i]);
2546 }
2547
2548 static int __init dp_register_genl(void)
2549 {
2550         int err;
2551         int i;
2552
2553         for (i = 0; i < ARRAY_SIZE(dp_genl_families); i++) {
2554
2555                 err = genl_register_family(dp_genl_families[i]);
2556                 if (err)
2557                         goto error;
2558         }
2559
2560         return 0;
2561
2562 error:
2563         dp_unregister_genl(i);
2564         return err;
2565 }
2566
2567 static int __net_init ovs_init_net(struct net *net)
2568 {
2569         struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
2570         int err;
2571
2572         INIT_LIST_HEAD(&ovs_net->dps);
2573         INIT_WORK(&ovs_net->dp_notify_work, ovs_dp_notify_wq);
2574         INIT_DELAYED_WORK(&ovs_net->masks_rebalance, ovs_dp_masks_rebalance);
2575
2576         err = ovs_ct_init(net);
2577         if (err)
2578                 return err;
2579
2580         schedule_delayed_work(&ovs_net->masks_rebalance,
2581                               msecs_to_jiffies(DP_MASKS_REBALANCE_INTERVAL));
2582         return 0;
2583 }
2584
2585 static void __net_exit list_vports_from_net(struct net *net, struct net *dnet,
2586                                             struct list_head *head)
2587 {
2588         struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
2589         struct datapath *dp;
2590
2591         list_for_each_entry(dp, &ovs_net->dps, list_node) {
2592                 int i;
2593
2594                 for (i = 0; i < DP_VPORT_HASH_BUCKETS; i++) {
2595                         struct vport *vport;
2596
2597                         hlist_for_each_entry(vport, &dp->ports[i], dp_hash_node) {
2598                                 if (vport->ops->type != OVS_VPORT_TYPE_INTERNAL)
2599                                         continue;
2600
2601                                 if (dev_net(vport->dev) == dnet)
2602                                         list_add(&vport->detach_list, head);
2603                         }
2604                 }
2605         }
2606 }
2607
2608 static void __net_exit ovs_exit_net(struct net *dnet)
2609 {
2610         struct datapath *dp, *dp_next;
2611         struct ovs_net *ovs_net = net_generic(dnet, ovs_net_id);
2612         struct vport *vport, *vport_next;
2613         struct net *net;
2614         LIST_HEAD(head);
2615
2616         ovs_lock();
2617
2618         ovs_ct_exit(dnet);
2619
2620         list_for_each_entry_safe(dp, dp_next, &ovs_net->dps, list_node)
2621                 __dp_destroy(dp);
2622
2623         down_read(&net_rwsem);
2624         for_each_net(net)
2625                 list_vports_from_net(net, dnet, &head);
2626         up_read(&net_rwsem);
2627
2628         /* Detach all vports from given namespace. */
2629         list_for_each_entry_safe(vport, vport_next, &head, detach_list) {
2630                 list_del(&vport->detach_list);
2631                 ovs_dp_detach_port(vport);
2632         }
2633
2634         ovs_unlock();
2635
2636         cancel_delayed_work_sync(&ovs_net->masks_rebalance);
2637         cancel_work_sync(&ovs_net->dp_notify_work);
2638 }
2639
2640 static struct pernet_operations ovs_net_ops = {
2641         .init = ovs_init_net,
2642         .exit = ovs_exit_net,
2643         .id   = &ovs_net_id,
2644         .size = sizeof(struct ovs_net),
2645 };
2646
2647 static int __init dp_init(void)
2648 {
2649         int err;
2650
2651         BUILD_BUG_ON(sizeof(struct ovs_skb_cb) >
2652                      sizeof_field(struct sk_buff, cb));
2653
2654         pr_info("Open vSwitch switching datapath\n");
2655
2656         err = action_fifos_init();
2657         if (err)
2658                 goto error;
2659
2660         err = ovs_internal_dev_rtnl_link_register();
2661         if (err)
2662                 goto error_action_fifos_exit;
2663
2664         err = ovs_flow_init();
2665         if (err)
2666                 goto error_unreg_rtnl_link;
2667
2668         err = ovs_vport_init();
2669         if (err)
2670                 goto error_flow_exit;
2671
2672         err = register_pernet_device(&ovs_net_ops);
2673         if (err)
2674                 goto error_vport_exit;
2675
2676         err = register_netdevice_notifier(&ovs_dp_device_notifier);
2677         if (err)
2678                 goto error_netns_exit;
2679
2680         err = ovs_netdev_init();
2681         if (err)
2682                 goto error_unreg_notifier;
2683
2684         err = dp_register_genl();
2685         if (err < 0)
2686                 goto error_unreg_netdev;
2687
2688         return 0;
2689
2690 error_unreg_netdev:
2691         ovs_netdev_exit();
2692 error_unreg_notifier:
2693         unregister_netdevice_notifier(&ovs_dp_device_notifier);
2694 error_netns_exit:
2695         unregister_pernet_device(&ovs_net_ops);
2696 error_vport_exit:
2697         ovs_vport_exit();
2698 error_flow_exit:
2699         ovs_flow_exit();
2700 error_unreg_rtnl_link:
2701         ovs_internal_dev_rtnl_link_unregister();
2702 error_action_fifos_exit:
2703         action_fifos_exit();
2704 error:
2705         return err;
2706 }
2707
2708 static void dp_cleanup(void)
2709 {
2710         dp_unregister_genl(ARRAY_SIZE(dp_genl_families));
2711         ovs_netdev_exit();
2712         unregister_netdevice_notifier(&ovs_dp_device_notifier);
2713         unregister_pernet_device(&ovs_net_ops);
2714         rcu_barrier();
2715         ovs_vport_exit();
2716         ovs_flow_exit();
2717         ovs_internal_dev_rtnl_link_unregister();
2718         action_fifos_exit();
2719 }
2720
2721 module_init(dp_init);
2722 module_exit(dp_cleanup);
2723
2724 MODULE_DESCRIPTION("Open vSwitch switching datapath");
2725 MODULE_LICENSE("GPL");
2726 MODULE_ALIAS_GENL_FAMILY(OVS_DATAPATH_FAMILY);
2727 MODULE_ALIAS_GENL_FAMILY(OVS_VPORT_FAMILY);
2728 MODULE_ALIAS_GENL_FAMILY(OVS_FLOW_FAMILY);
2729 MODULE_ALIAS_GENL_FAMILY(OVS_PACKET_FAMILY);
2730 MODULE_ALIAS_GENL_FAMILY(OVS_METER_FAMILY);
2731 MODULE_ALIAS_GENL_FAMILY(OVS_CT_LIMIT_FAMILY);