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