GNU Linux-libre 4.19.286-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_key *key;
907         struct sw_flow_actions *acts;
908         struct sw_flow_match match;
909         u32 ufid_flags = ovs_nla_get_ufid_flags(a[OVS_FLOW_ATTR_UFID_FLAGS]);
910         int error;
911         bool log = !a[OVS_FLOW_ATTR_PROBE];
912
913         /* Must have key and actions. */
914         error = -EINVAL;
915         if (!a[OVS_FLOW_ATTR_KEY]) {
916                 OVS_NLERR(log, "Flow key attr not present in new flow.");
917                 goto error;
918         }
919         if (!a[OVS_FLOW_ATTR_ACTIONS]) {
920                 OVS_NLERR(log, "Flow actions attr not present in new flow.");
921                 goto error;
922         }
923
924         /* Most of the time we need to allocate a new flow, do it before
925          * locking.
926          */
927         new_flow = ovs_flow_alloc();
928         if (IS_ERR(new_flow)) {
929                 error = PTR_ERR(new_flow);
930                 goto error;
931         }
932
933         /* Extract key. */
934         key = kzalloc(sizeof(*key), GFP_KERNEL);
935         if (!key) {
936                 error = -ENOMEM;
937                 goto err_kfree_flow;
938         }
939
940         ovs_match_init(&match, key, false, &mask);
941         error = ovs_nla_get_match(net, &match, a[OVS_FLOW_ATTR_KEY],
942                                   a[OVS_FLOW_ATTR_MASK], log);
943         if (error)
944                 goto err_kfree_key;
945
946         ovs_flow_mask_key(&new_flow->key, key, true, &mask);
947
948         /* Extract flow identifier. */
949         error = ovs_nla_get_identifier(&new_flow->id, a[OVS_FLOW_ATTR_UFID],
950                                        key, log);
951         if (error)
952                 goto err_kfree_key;
953
954         /* Validate actions. */
955         error = ovs_nla_copy_actions(net, a[OVS_FLOW_ATTR_ACTIONS],
956                                      &new_flow->key, &acts, log);
957         if (error) {
958                 OVS_NLERR(log, "Flow actions may not be safe on all matching packets.");
959                 goto err_kfree_key;
960         }
961
962         reply = ovs_flow_cmd_alloc_info(acts, &new_flow->id, info, false,
963                                         ufid_flags);
964         if (IS_ERR(reply)) {
965                 error = PTR_ERR(reply);
966                 goto err_kfree_acts;
967         }
968
969         ovs_lock();
970         dp = get_dp(net, ovs_header->dp_ifindex);
971         if (unlikely(!dp)) {
972                 error = -ENODEV;
973                 goto err_unlock_ovs;
974         }
975
976         /* Check if this is a duplicate flow */
977         if (ovs_identifier_is_ufid(&new_flow->id))
978                 flow = ovs_flow_tbl_lookup_ufid(&dp->table, &new_flow->id);
979         if (!flow)
980                 flow = ovs_flow_tbl_lookup(&dp->table, key);
981         if (likely(!flow)) {
982                 rcu_assign_pointer(new_flow->sf_acts, acts);
983
984                 /* Put flow in bucket. */
985                 error = ovs_flow_tbl_insert(&dp->table, new_flow, &mask);
986                 if (unlikely(error)) {
987                         acts = NULL;
988                         goto err_unlock_ovs;
989                 }
990
991                 if (unlikely(reply)) {
992                         error = ovs_flow_cmd_fill_info(new_flow,
993                                                        ovs_header->dp_ifindex,
994                                                        reply, info->snd_portid,
995                                                        info->snd_seq, 0,
996                                                        OVS_FLOW_CMD_NEW,
997                                                        ufid_flags);
998                         BUG_ON(error < 0);
999                 }
1000                 ovs_unlock();
1001         } else {
1002                 struct sw_flow_actions *old_acts;
1003
1004                 /* Bail out if we're not allowed to modify an existing flow.
1005                  * We accept NLM_F_CREATE in place of the intended NLM_F_EXCL
1006                  * because Generic Netlink treats the latter as a dump
1007                  * request.  We also accept NLM_F_EXCL in case that bug ever
1008                  * gets fixed.
1009                  */
1010                 if (unlikely(info->nlhdr->nlmsg_flags & (NLM_F_CREATE
1011                                                          | NLM_F_EXCL))) {
1012                         error = -EEXIST;
1013                         goto err_unlock_ovs;
1014                 }
1015                 /* The flow identifier has to be the same for flow updates.
1016                  * Look for any overlapping flow.
1017                  */
1018                 if (unlikely(!ovs_flow_cmp(flow, &match))) {
1019                         if (ovs_identifier_is_key(&flow->id))
1020                                 flow = ovs_flow_tbl_lookup_exact(&dp->table,
1021                                                                  &match);
1022                         else /* UFID matches but key is different */
1023                                 flow = NULL;
1024                         if (!flow) {
1025                                 error = -ENOENT;
1026                                 goto err_unlock_ovs;
1027                         }
1028                 }
1029                 /* Update actions. */
1030                 old_acts = ovsl_dereference(flow->sf_acts);
1031                 rcu_assign_pointer(flow->sf_acts, acts);
1032
1033                 if (unlikely(reply)) {
1034                         error = ovs_flow_cmd_fill_info(flow,
1035                                                        ovs_header->dp_ifindex,
1036                                                        reply, info->snd_portid,
1037                                                        info->snd_seq, 0,
1038                                                        OVS_FLOW_CMD_NEW,
1039                                                        ufid_flags);
1040                         BUG_ON(error < 0);
1041                 }
1042                 ovs_unlock();
1043
1044                 ovs_nla_free_flow_actions_rcu(old_acts);
1045                 ovs_flow_free(new_flow, false);
1046         }
1047
1048         if (reply)
1049                 ovs_notify(&dp_flow_genl_family, reply, info);
1050
1051         kfree(key);
1052         return 0;
1053
1054 err_unlock_ovs:
1055         ovs_unlock();
1056         kfree_skb(reply);
1057 err_kfree_acts:
1058         ovs_nla_free_flow_actions(acts);
1059 err_kfree_key:
1060         kfree(key);
1061 err_kfree_flow:
1062         ovs_flow_free(new_flow, false);
1063 error:
1064         return error;
1065 }
1066
1067 /* Factor out action copy to avoid "Wframe-larger-than=1024" warning. */
1068 static struct sw_flow_actions *get_flow_actions(struct net *net,
1069                                                 const struct nlattr *a,
1070                                                 const struct sw_flow_key *key,
1071                                                 const struct sw_flow_mask *mask,
1072                                                 bool log)
1073 {
1074         struct sw_flow_actions *acts;
1075         struct sw_flow_key masked_key;
1076         int error;
1077
1078         ovs_flow_mask_key(&masked_key, key, true, mask);
1079         error = ovs_nla_copy_actions(net, a, &masked_key, &acts, log);
1080         if (error) {
1081                 OVS_NLERR(log,
1082                           "Actions may not be safe on all matching packets");
1083                 return ERR_PTR(error);
1084         }
1085
1086         return acts;
1087 }
1088
1089 /* Factor out match-init and action-copy to avoid
1090  * "Wframe-larger-than=1024" warning. Because mask is only
1091  * used to get actions, we new a function to save some
1092  * stack space.
1093  *
1094  * If there are not key and action attrs, we return 0
1095  * directly. In the case, the caller will also not use the
1096  * match as before. If there is action attr, we try to get
1097  * actions and save them to *acts. Before returning from
1098  * the function, we reset the match->mask pointer. Because
1099  * we should not to return match object with dangling reference
1100  * to mask.
1101  * */
1102 static int ovs_nla_init_match_and_action(struct net *net,
1103                                          struct sw_flow_match *match,
1104                                          struct sw_flow_key *key,
1105                                          struct nlattr **a,
1106                                          struct sw_flow_actions **acts,
1107                                          bool log)
1108 {
1109         struct sw_flow_mask mask;
1110         int error = 0;
1111
1112         if (a[OVS_FLOW_ATTR_KEY]) {
1113                 ovs_match_init(match, key, true, &mask);
1114                 error = ovs_nla_get_match(net, match, a[OVS_FLOW_ATTR_KEY],
1115                                           a[OVS_FLOW_ATTR_MASK], log);
1116                 if (error)
1117                         goto error;
1118         }
1119
1120         if (a[OVS_FLOW_ATTR_ACTIONS]) {
1121                 if (!a[OVS_FLOW_ATTR_KEY]) {
1122                         OVS_NLERR(log,
1123                                   "Flow key attribute not present in set flow.");
1124                         error = -EINVAL;
1125                         goto error;
1126                 }
1127
1128                 *acts = get_flow_actions(net, a[OVS_FLOW_ATTR_ACTIONS], key,
1129                                          &mask, log);
1130                 if (IS_ERR(*acts)) {
1131                         error = PTR_ERR(*acts);
1132                         goto error;
1133                 }
1134         }
1135
1136         /* On success, error is 0. */
1137 error:
1138         match->mask = NULL;
1139         return error;
1140 }
1141
1142 static int ovs_flow_cmd_set(struct sk_buff *skb, struct genl_info *info)
1143 {
1144         struct net *net = sock_net(skb->sk);
1145         struct nlattr **a = info->attrs;
1146         struct ovs_header *ovs_header = info->userhdr;
1147         struct sw_flow_key key;
1148         struct sw_flow *flow;
1149         struct sk_buff *reply = NULL;
1150         struct datapath *dp;
1151         struct sw_flow_actions *old_acts = NULL, *acts = NULL;
1152         struct sw_flow_match match;
1153         struct sw_flow_id sfid;
1154         u32 ufid_flags = ovs_nla_get_ufid_flags(a[OVS_FLOW_ATTR_UFID_FLAGS]);
1155         int error = 0;
1156         bool log = !a[OVS_FLOW_ATTR_PROBE];
1157         bool ufid_present;
1158
1159         ufid_present = ovs_nla_get_ufid(&sfid, a[OVS_FLOW_ATTR_UFID], log);
1160         if (!a[OVS_FLOW_ATTR_KEY] && !ufid_present) {
1161                 OVS_NLERR(log,
1162                           "Flow set message rejected, Key attribute missing.");
1163                 return -EINVAL;
1164         }
1165
1166         error = ovs_nla_init_match_and_action(net, &match, &key, a,
1167                                               &acts, log);
1168         if (error)
1169                 goto error;
1170
1171         if (acts) {
1172                 /* Can allocate before locking if have acts. */
1173                 reply = ovs_flow_cmd_alloc_info(acts, &sfid, info, false,
1174                                                 ufid_flags);
1175                 if (IS_ERR(reply)) {
1176                         error = PTR_ERR(reply);
1177                         goto err_kfree_acts;
1178                 }
1179         }
1180
1181         ovs_lock();
1182         dp = get_dp(net, ovs_header->dp_ifindex);
1183         if (unlikely(!dp)) {
1184                 error = -ENODEV;
1185                 goto err_unlock_ovs;
1186         }
1187         /* Check that the flow exists. */
1188         if (ufid_present)
1189                 flow = ovs_flow_tbl_lookup_ufid(&dp->table, &sfid);
1190         else
1191                 flow = ovs_flow_tbl_lookup_exact(&dp->table, &match);
1192         if (unlikely(!flow)) {
1193                 error = -ENOENT;
1194                 goto err_unlock_ovs;
1195         }
1196
1197         /* Update actions, if present. */
1198         if (likely(acts)) {
1199                 old_acts = ovsl_dereference(flow->sf_acts);
1200                 rcu_assign_pointer(flow->sf_acts, acts);
1201
1202                 if (unlikely(reply)) {
1203                         error = ovs_flow_cmd_fill_info(flow,
1204                                                        ovs_header->dp_ifindex,
1205                                                        reply, info->snd_portid,
1206                                                        info->snd_seq, 0,
1207                                                        OVS_FLOW_CMD_NEW,
1208                                                        ufid_flags);
1209                         BUG_ON(error < 0);
1210                 }
1211         } else {
1212                 /* Could not alloc without acts before locking. */
1213                 reply = ovs_flow_cmd_build_info(flow, ovs_header->dp_ifindex,
1214                                                 info, OVS_FLOW_CMD_NEW, false,
1215                                                 ufid_flags);
1216
1217                 if (IS_ERR(reply)) {
1218                         error = PTR_ERR(reply);
1219                         goto err_unlock_ovs;
1220                 }
1221         }
1222
1223         /* Clear stats. */
1224         if (a[OVS_FLOW_ATTR_CLEAR])
1225                 ovs_flow_stats_clear(flow);
1226         ovs_unlock();
1227
1228         if (reply)
1229                 ovs_notify(&dp_flow_genl_family, reply, info);
1230         if (old_acts)
1231                 ovs_nla_free_flow_actions_rcu(old_acts);
1232
1233         return 0;
1234
1235 err_unlock_ovs:
1236         ovs_unlock();
1237         kfree_skb(reply);
1238 err_kfree_acts:
1239         ovs_nla_free_flow_actions(acts);
1240 error:
1241         return error;
1242 }
1243
1244 static int ovs_flow_cmd_get(struct sk_buff *skb, struct genl_info *info)
1245 {
1246         struct nlattr **a = info->attrs;
1247         struct ovs_header *ovs_header = info->userhdr;
1248         struct net *net = sock_net(skb->sk);
1249         struct sw_flow_key key;
1250         struct sk_buff *reply;
1251         struct sw_flow *flow;
1252         struct datapath *dp;
1253         struct sw_flow_match match;
1254         struct sw_flow_id ufid;
1255         u32 ufid_flags = ovs_nla_get_ufid_flags(a[OVS_FLOW_ATTR_UFID_FLAGS]);
1256         int err = 0;
1257         bool log = !a[OVS_FLOW_ATTR_PROBE];
1258         bool ufid_present;
1259
1260         ufid_present = ovs_nla_get_ufid(&ufid, a[OVS_FLOW_ATTR_UFID], log);
1261         if (a[OVS_FLOW_ATTR_KEY]) {
1262                 ovs_match_init(&match, &key, true, NULL);
1263                 err = ovs_nla_get_match(net, &match, a[OVS_FLOW_ATTR_KEY], NULL,
1264                                         log);
1265         } else if (!ufid_present) {
1266                 OVS_NLERR(log,
1267                           "Flow get message rejected, Key attribute missing.");
1268                 err = -EINVAL;
1269         }
1270         if (err)
1271                 return err;
1272
1273         ovs_lock();
1274         dp = get_dp(sock_net(skb->sk), ovs_header->dp_ifindex);
1275         if (!dp) {
1276                 err = -ENODEV;
1277                 goto unlock;
1278         }
1279
1280         if (ufid_present)
1281                 flow = ovs_flow_tbl_lookup_ufid(&dp->table, &ufid);
1282         else
1283                 flow = ovs_flow_tbl_lookup_exact(&dp->table, &match);
1284         if (!flow) {
1285                 err = -ENOENT;
1286                 goto unlock;
1287         }
1288
1289         reply = ovs_flow_cmd_build_info(flow, ovs_header->dp_ifindex, info,
1290                                         OVS_FLOW_CMD_NEW, true, ufid_flags);
1291         if (IS_ERR(reply)) {
1292                 err = PTR_ERR(reply);
1293                 goto unlock;
1294         }
1295
1296         ovs_unlock();
1297         return genlmsg_reply(reply, info);
1298 unlock:
1299         ovs_unlock();
1300         return err;
1301 }
1302
1303 static int ovs_flow_cmd_del(struct sk_buff *skb, struct genl_info *info)
1304 {
1305         struct nlattr **a = info->attrs;
1306         struct ovs_header *ovs_header = info->userhdr;
1307         struct net *net = sock_net(skb->sk);
1308         struct sw_flow_key key;
1309         struct sk_buff *reply;
1310         struct sw_flow *flow = NULL;
1311         struct datapath *dp;
1312         struct sw_flow_match match;
1313         struct sw_flow_id ufid;
1314         u32 ufid_flags = ovs_nla_get_ufid_flags(a[OVS_FLOW_ATTR_UFID_FLAGS]);
1315         int err;
1316         bool log = !a[OVS_FLOW_ATTR_PROBE];
1317         bool ufid_present;
1318
1319         ufid_present = ovs_nla_get_ufid(&ufid, a[OVS_FLOW_ATTR_UFID], log);
1320         if (a[OVS_FLOW_ATTR_KEY]) {
1321                 ovs_match_init(&match, &key, true, NULL);
1322                 err = ovs_nla_get_match(net, &match, a[OVS_FLOW_ATTR_KEY],
1323                                         NULL, log);
1324                 if (unlikely(err))
1325                         return err;
1326         }
1327
1328         ovs_lock();
1329         dp = get_dp(sock_net(skb->sk), ovs_header->dp_ifindex);
1330         if (unlikely(!dp)) {
1331                 err = -ENODEV;
1332                 goto unlock;
1333         }
1334
1335         if (unlikely(!a[OVS_FLOW_ATTR_KEY] && !ufid_present)) {
1336                 err = ovs_flow_tbl_flush(&dp->table);
1337                 goto unlock;
1338         }
1339
1340         if (ufid_present)
1341                 flow = ovs_flow_tbl_lookup_ufid(&dp->table, &ufid);
1342         else
1343                 flow = ovs_flow_tbl_lookup_exact(&dp->table, &match);
1344         if (unlikely(!flow)) {
1345                 err = -ENOENT;
1346                 goto unlock;
1347         }
1348
1349         ovs_flow_tbl_remove(&dp->table, flow);
1350         ovs_unlock();
1351
1352         reply = ovs_flow_cmd_alloc_info((const struct sw_flow_actions __force *) flow->sf_acts,
1353                                         &flow->id, info, false, ufid_flags);
1354         if (likely(reply)) {
1355                 if (likely(!IS_ERR(reply))) {
1356                         rcu_read_lock();        /*To keep RCU checker happy. */
1357                         err = ovs_flow_cmd_fill_info(flow, ovs_header->dp_ifindex,
1358                                                      reply, info->snd_portid,
1359                                                      info->snd_seq, 0,
1360                                                      OVS_FLOW_CMD_DEL,
1361                                                      ufid_flags);
1362                         rcu_read_unlock();
1363                         if (WARN_ON_ONCE(err < 0)) {
1364                                 kfree_skb(reply);
1365                                 goto out_free;
1366                         }
1367
1368                         ovs_notify(&dp_flow_genl_family, reply, info);
1369                 } else {
1370                         netlink_set_err(sock_net(skb->sk)->genl_sock, 0, 0, PTR_ERR(reply));
1371                 }
1372         }
1373
1374 out_free:
1375         ovs_flow_free(flow, true);
1376         return 0;
1377 unlock:
1378         ovs_unlock();
1379         return err;
1380 }
1381
1382 static int ovs_flow_cmd_dump(struct sk_buff *skb, struct netlink_callback *cb)
1383 {
1384         struct nlattr *a[__OVS_FLOW_ATTR_MAX];
1385         struct ovs_header *ovs_header = genlmsg_data(nlmsg_data(cb->nlh));
1386         struct table_instance *ti;
1387         struct datapath *dp;
1388         u32 ufid_flags;
1389         int err;
1390
1391         err = genlmsg_parse(cb->nlh, &dp_flow_genl_family, a,
1392                             OVS_FLOW_ATTR_MAX, flow_policy, NULL);
1393         if (err)
1394                 return err;
1395         ufid_flags = ovs_nla_get_ufid_flags(a[OVS_FLOW_ATTR_UFID_FLAGS]);
1396
1397         rcu_read_lock();
1398         dp = get_dp_rcu(sock_net(skb->sk), ovs_header->dp_ifindex);
1399         if (!dp) {
1400                 rcu_read_unlock();
1401                 return -ENODEV;
1402         }
1403
1404         ti = rcu_dereference(dp->table.ti);
1405         for (;;) {
1406                 struct sw_flow *flow;
1407                 u32 bucket, obj;
1408
1409                 bucket = cb->args[0];
1410                 obj = cb->args[1];
1411                 flow = ovs_flow_tbl_dump_next(ti, &bucket, &obj);
1412                 if (!flow)
1413                         break;
1414
1415                 if (ovs_flow_cmd_fill_info(flow, ovs_header->dp_ifindex, skb,
1416                                            NETLINK_CB(cb->skb).portid,
1417                                            cb->nlh->nlmsg_seq, NLM_F_MULTI,
1418                                            OVS_FLOW_CMD_NEW, ufid_flags) < 0)
1419                         break;
1420
1421                 cb->args[0] = bucket;
1422                 cb->args[1] = obj;
1423         }
1424         rcu_read_unlock();
1425         return skb->len;
1426 }
1427
1428 static const struct nla_policy flow_policy[OVS_FLOW_ATTR_MAX + 1] = {
1429         [OVS_FLOW_ATTR_KEY] = { .type = NLA_NESTED },
1430         [OVS_FLOW_ATTR_MASK] = { .type = NLA_NESTED },
1431         [OVS_FLOW_ATTR_ACTIONS] = { .type = NLA_NESTED },
1432         [OVS_FLOW_ATTR_CLEAR] = { .type = NLA_FLAG },
1433         [OVS_FLOW_ATTR_PROBE] = { .type = NLA_FLAG },
1434         [OVS_FLOW_ATTR_UFID] = { .type = NLA_UNSPEC, .len = 1 },
1435         [OVS_FLOW_ATTR_UFID_FLAGS] = { .type = NLA_U32 },
1436 };
1437
1438 static const struct genl_ops dp_flow_genl_ops[] = {
1439         { .cmd = OVS_FLOW_CMD_NEW,
1440           .flags = GENL_UNS_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1441           .policy = flow_policy,
1442           .doit = ovs_flow_cmd_new
1443         },
1444         { .cmd = OVS_FLOW_CMD_DEL,
1445           .flags = GENL_UNS_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1446           .policy = flow_policy,
1447           .doit = ovs_flow_cmd_del
1448         },
1449         { .cmd = OVS_FLOW_CMD_GET,
1450           .flags = 0,               /* OK for unprivileged users. */
1451           .policy = flow_policy,
1452           .doit = ovs_flow_cmd_get,
1453           .dumpit = ovs_flow_cmd_dump
1454         },
1455         { .cmd = OVS_FLOW_CMD_SET,
1456           .flags = GENL_UNS_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1457           .policy = flow_policy,
1458           .doit = ovs_flow_cmd_set,
1459         },
1460 };
1461
1462 static struct genl_family dp_flow_genl_family __ro_after_init = {
1463         .hdrsize = sizeof(struct ovs_header),
1464         .name = OVS_FLOW_FAMILY,
1465         .version = OVS_FLOW_VERSION,
1466         .maxattr = OVS_FLOW_ATTR_MAX,
1467         .netnsok = true,
1468         .parallel_ops = true,
1469         .ops = dp_flow_genl_ops,
1470         .n_ops = ARRAY_SIZE(dp_flow_genl_ops),
1471         .mcgrps = &ovs_dp_flow_multicast_group,
1472         .n_mcgrps = 1,
1473         .module = THIS_MODULE,
1474 };
1475
1476 static size_t ovs_dp_cmd_msg_size(void)
1477 {
1478         size_t msgsize = NLMSG_ALIGN(sizeof(struct ovs_header));
1479
1480         msgsize += nla_total_size(IFNAMSIZ);
1481         msgsize += nla_total_size_64bit(sizeof(struct ovs_dp_stats));
1482         msgsize += nla_total_size_64bit(sizeof(struct ovs_dp_megaflow_stats));
1483         msgsize += nla_total_size(sizeof(u32)); /* OVS_DP_ATTR_USER_FEATURES */
1484
1485         return msgsize;
1486 }
1487
1488 /* Called with ovs_mutex. */
1489 static int ovs_dp_cmd_fill_info(struct datapath *dp, struct sk_buff *skb,
1490                                 u32 portid, u32 seq, u32 flags, u8 cmd)
1491 {
1492         struct ovs_header *ovs_header;
1493         struct ovs_dp_stats dp_stats;
1494         struct ovs_dp_megaflow_stats dp_megaflow_stats;
1495         int err;
1496
1497         ovs_header = genlmsg_put(skb, portid, seq, &dp_datapath_genl_family,
1498                                    flags, cmd);
1499         if (!ovs_header)
1500                 goto error;
1501
1502         ovs_header->dp_ifindex = get_dpifindex(dp);
1503
1504         err = nla_put_string(skb, OVS_DP_ATTR_NAME, ovs_dp_name(dp));
1505         if (err)
1506                 goto nla_put_failure;
1507
1508         get_dp_stats(dp, &dp_stats, &dp_megaflow_stats);
1509         if (nla_put_64bit(skb, OVS_DP_ATTR_STATS, sizeof(struct ovs_dp_stats),
1510                           &dp_stats, OVS_DP_ATTR_PAD))
1511                 goto nla_put_failure;
1512
1513         if (nla_put_64bit(skb, OVS_DP_ATTR_MEGAFLOW_STATS,
1514                           sizeof(struct ovs_dp_megaflow_stats),
1515                           &dp_megaflow_stats, OVS_DP_ATTR_PAD))
1516                 goto nla_put_failure;
1517
1518         if (nla_put_u32(skb, OVS_DP_ATTR_USER_FEATURES, dp->user_features))
1519                 goto nla_put_failure;
1520
1521         genlmsg_end(skb, ovs_header);
1522         return 0;
1523
1524 nla_put_failure:
1525         genlmsg_cancel(skb, ovs_header);
1526 error:
1527         return -EMSGSIZE;
1528 }
1529
1530 static struct sk_buff *ovs_dp_cmd_alloc_info(void)
1531 {
1532         return genlmsg_new(ovs_dp_cmd_msg_size(), GFP_KERNEL);
1533 }
1534
1535 /* Called with rcu_read_lock or ovs_mutex. */
1536 static struct datapath *lookup_datapath(struct net *net,
1537                                         const struct ovs_header *ovs_header,
1538                                         struct nlattr *a[OVS_DP_ATTR_MAX + 1])
1539 {
1540         struct datapath *dp;
1541
1542         if (!a[OVS_DP_ATTR_NAME])
1543                 dp = get_dp(net, ovs_header->dp_ifindex);
1544         else {
1545                 struct vport *vport;
1546
1547                 vport = ovs_vport_locate(net, nla_data(a[OVS_DP_ATTR_NAME]));
1548                 dp = vport && vport->port_no == OVSP_LOCAL ? vport->dp : NULL;
1549         }
1550         return dp ? dp : ERR_PTR(-ENODEV);
1551 }
1552
1553 static void ovs_dp_reset_user_features(struct sk_buff *skb, struct genl_info *info)
1554 {
1555         struct datapath *dp;
1556
1557         dp = lookup_datapath(sock_net(skb->sk), info->userhdr, info->attrs);
1558         if (IS_ERR(dp))
1559                 return;
1560
1561         pr_warn("%s: Dropping previously announced user features\n",
1562                 ovs_dp_name(dp));
1563         dp->user_features = 0;
1564 }
1565
1566 static void ovs_dp_change(struct datapath *dp, struct nlattr *a[])
1567 {
1568         if (a[OVS_DP_ATTR_USER_FEATURES])
1569                 dp->user_features = nla_get_u32(a[OVS_DP_ATTR_USER_FEATURES]);
1570 }
1571
1572 static int ovs_dp_cmd_new(struct sk_buff *skb, struct genl_info *info)
1573 {
1574         struct nlattr **a = info->attrs;
1575         struct vport_parms parms;
1576         struct sk_buff *reply;
1577         struct datapath *dp;
1578         struct vport *vport;
1579         struct ovs_net *ovs_net;
1580         int err, i;
1581
1582         err = -EINVAL;
1583         if (!a[OVS_DP_ATTR_NAME] || !a[OVS_DP_ATTR_UPCALL_PID])
1584                 goto err;
1585
1586         reply = ovs_dp_cmd_alloc_info();
1587         if (!reply)
1588                 return -ENOMEM;
1589
1590         err = -ENOMEM;
1591         dp = kzalloc(sizeof(*dp), GFP_KERNEL);
1592         if (dp == NULL)
1593                 goto err_free_reply;
1594
1595         ovs_dp_set_net(dp, sock_net(skb->sk));
1596
1597         /* Allocate table. */
1598         err = ovs_flow_tbl_init(&dp->table);
1599         if (err)
1600                 goto err_free_dp;
1601
1602         dp->stats_percpu = netdev_alloc_pcpu_stats(struct dp_stats_percpu);
1603         if (!dp->stats_percpu) {
1604                 err = -ENOMEM;
1605                 goto err_destroy_table;
1606         }
1607
1608         dp->ports = kmalloc_array(DP_VPORT_HASH_BUCKETS,
1609                                   sizeof(struct hlist_head),
1610                                   GFP_KERNEL);
1611         if (!dp->ports) {
1612                 err = -ENOMEM;
1613                 goto err_destroy_percpu;
1614         }
1615
1616         for (i = 0; i < DP_VPORT_HASH_BUCKETS; i++)
1617                 INIT_HLIST_HEAD(&dp->ports[i]);
1618
1619         err = ovs_meters_init(dp);
1620         if (err)
1621                 goto err_destroy_ports_array;
1622
1623         /* Set up our datapath device. */
1624         parms.name = nla_data(a[OVS_DP_ATTR_NAME]);
1625         parms.type = OVS_VPORT_TYPE_INTERNAL;
1626         parms.options = NULL;
1627         parms.dp = dp;
1628         parms.port_no = OVSP_LOCAL;
1629         parms.upcall_portids = a[OVS_DP_ATTR_UPCALL_PID];
1630
1631         ovs_dp_change(dp, a);
1632
1633         /* So far only local changes have been made, now need the lock. */
1634         ovs_lock();
1635
1636         vport = new_vport(&parms);
1637         if (IS_ERR(vport)) {
1638                 err = PTR_ERR(vport);
1639                 if (err == -EBUSY)
1640                         err = -EEXIST;
1641
1642                 if (err == -EEXIST) {
1643                         /* An outdated user space instance that does not understand
1644                          * the concept of user_features has attempted to create a new
1645                          * datapath and is likely to reuse it. Drop all user features.
1646                          */
1647                         if (info->genlhdr->version < OVS_DP_VER_FEATURES)
1648                                 ovs_dp_reset_user_features(skb, info);
1649                 }
1650
1651                 goto err_destroy_meters;
1652         }
1653
1654         err = ovs_dp_cmd_fill_info(dp, reply, info->snd_portid,
1655                                    info->snd_seq, 0, OVS_DP_CMD_NEW);
1656         BUG_ON(err < 0);
1657
1658         ovs_net = net_generic(ovs_dp_get_net(dp), ovs_net_id);
1659         list_add_tail_rcu(&dp->list_node, &ovs_net->dps);
1660
1661         ovs_unlock();
1662
1663         ovs_notify(&dp_datapath_genl_family, reply, info);
1664         return 0;
1665
1666 err_destroy_meters:
1667         ovs_unlock();
1668         ovs_meters_exit(dp);
1669 err_destroy_ports_array:
1670         kfree(dp->ports);
1671 err_destroy_percpu:
1672         free_percpu(dp->stats_percpu);
1673 err_destroy_table:
1674         ovs_flow_tbl_destroy(&dp->table);
1675 err_free_dp:
1676         kfree(dp);
1677 err_free_reply:
1678         kfree_skb(reply);
1679 err:
1680         return err;
1681 }
1682
1683 /* Called with ovs_mutex. */
1684 static void __dp_destroy(struct datapath *dp)
1685 {
1686         int i;
1687
1688         for (i = 0; i < DP_VPORT_HASH_BUCKETS; i++) {
1689                 struct vport *vport;
1690                 struct hlist_node *n;
1691
1692                 hlist_for_each_entry_safe(vport, n, &dp->ports[i], dp_hash_node)
1693                         if (vport->port_no != OVSP_LOCAL)
1694                                 ovs_dp_detach_port(vport);
1695         }
1696
1697         list_del_rcu(&dp->list_node);
1698
1699         /* OVSP_LOCAL is datapath internal port. We need to make sure that
1700          * all ports in datapath are destroyed first before freeing datapath.
1701          */
1702         ovs_dp_detach_port(ovs_vport_ovsl(dp, OVSP_LOCAL));
1703
1704         /* RCU destroy the flow table */
1705         call_rcu(&dp->rcu, destroy_dp_rcu);
1706 }
1707
1708 static int ovs_dp_cmd_del(struct sk_buff *skb, struct genl_info *info)
1709 {
1710         struct sk_buff *reply;
1711         struct datapath *dp;
1712         int err;
1713
1714         reply = ovs_dp_cmd_alloc_info();
1715         if (!reply)
1716                 return -ENOMEM;
1717
1718         ovs_lock();
1719         dp = lookup_datapath(sock_net(skb->sk), info->userhdr, info->attrs);
1720         err = PTR_ERR(dp);
1721         if (IS_ERR(dp))
1722                 goto err_unlock_free;
1723
1724         err = ovs_dp_cmd_fill_info(dp, reply, info->snd_portid,
1725                                    info->snd_seq, 0, OVS_DP_CMD_DEL);
1726         BUG_ON(err < 0);
1727
1728         __dp_destroy(dp);
1729         ovs_unlock();
1730
1731         ovs_notify(&dp_datapath_genl_family, reply, info);
1732
1733         return 0;
1734
1735 err_unlock_free:
1736         ovs_unlock();
1737         kfree_skb(reply);
1738         return err;
1739 }
1740
1741 static int ovs_dp_cmd_set(struct sk_buff *skb, struct genl_info *info)
1742 {
1743         struct sk_buff *reply;
1744         struct datapath *dp;
1745         int err;
1746
1747         reply = ovs_dp_cmd_alloc_info();
1748         if (!reply)
1749                 return -ENOMEM;
1750
1751         ovs_lock();
1752         dp = lookup_datapath(sock_net(skb->sk), info->userhdr, info->attrs);
1753         err = PTR_ERR(dp);
1754         if (IS_ERR(dp))
1755                 goto err_unlock_free;
1756
1757         ovs_dp_change(dp, info->attrs);
1758
1759         err = ovs_dp_cmd_fill_info(dp, reply, info->snd_portid,
1760                                    info->snd_seq, 0, OVS_DP_CMD_NEW);
1761         BUG_ON(err < 0);
1762
1763         ovs_unlock();
1764         ovs_notify(&dp_datapath_genl_family, reply, info);
1765
1766         return 0;
1767
1768 err_unlock_free:
1769         ovs_unlock();
1770         kfree_skb(reply);
1771         return err;
1772 }
1773
1774 static int ovs_dp_cmd_get(struct sk_buff *skb, struct genl_info *info)
1775 {
1776         struct sk_buff *reply;
1777         struct datapath *dp;
1778         int err;
1779
1780         reply = ovs_dp_cmd_alloc_info();
1781         if (!reply)
1782                 return -ENOMEM;
1783
1784         ovs_lock();
1785         dp = lookup_datapath(sock_net(skb->sk), info->userhdr, info->attrs);
1786         if (IS_ERR(dp)) {
1787                 err = PTR_ERR(dp);
1788                 goto err_unlock_free;
1789         }
1790         err = ovs_dp_cmd_fill_info(dp, reply, info->snd_portid,
1791                                    info->snd_seq, 0, OVS_DP_CMD_NEW);
1792         BUG_ON(err < 0);
1793         ovs_unlock();
1794
1795         return genlmsg_reply(reply, info);
1796
1797 err_unlock_free:
1798         ovs_unlock();
1799         kfree_skb(reply);
1800         return err;
1801 }
1802
1803 static int ovs_dp_cmd_dump(struct sk_buff *skb, struct netlink_callback *cb)
1804 {
1805         struct ovs_net *ovs_net = net_generic(sock_net(skb->sk), ovs_net_id);
1806         struct datapath *dp;
1807         int skip = cb->args[0];
1808         int i = 0;
1809
1810         ovs_lock();
1811         list_for_each_entry(dp, &ovs_net->dps, list_node) {
1812                 if (i >= skip &&
1813                     ovs_dp_cmd_fill_info(dp, skb, NETLINK_CB(cb->skb).portid,
1814                                          cb->nlh->nlmsg_seq, NLM_F_MULTI,
1815                                          OVS_DP_CMD_NEW) < 0)
1816                         break;
1817                 i++;
1818         }
1819         ovs_unlock();
1820
1821         cb->args[0] = i;
1822
1823         return skb->len;
1824 }
1825
1826 static const struct nla_policy datapath_policy[OVS_DP_ATTR_MAX + 1] = {
1827         [OVS_DP_ATTR_NAME] = { .type = NLA_NUL_STRING, .len = IFNAMSIZ - 1 },
1828         [OVS_DP_ATTR_UPCALL_PID] = { .type = NLA_U32 },
1829         [OVS_DP_ATTR_USER_FEATURES] = { .type = NLA_U32 },
1830 };
1831
1832 static const struct genl_ops dp_datapath_genl_ops[] = {
1833         { .cmd = OVS_DP_CMD_NEW,
1834           .flags = GENL_UNS_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1835           .policy = datapath_policy,
1836           .doit = ovs_dp_cmd_new
1837         },
1838         { .cmd = OVS_DP_CMD_DEL,
1839           .flags = GENL_UNS_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1840           .policy = datapath_policy,
1841           .doit = ovs_dp_cmd_del
1842         },
1843         { .cmd = OVS_DP_CMD_GET,
1844           .flags = 0,               /* OK for unprivileged users. */
1845           .policy = datapath_policy,
1846           .doit = ovs_dp_cmd_get,
1847           .dumpit = ovs_dp_cmd_dump
1848         },
1849         { .cmd = OVS_DP_CMD_SET,
1850           .flags = GENL_UNS_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
1851           .policy = datapath_policy,
1852           .doit = ovs_dp_cmd_set,
1853         },
1854 };
1855
1856 static struct genl_family dp_datapath_genl_family __ro_after_init = {
1857         .hdrsize = sizeof(struct ovs_header),
1858         .name = OVS_DATAPATH_FAMILY,
1859         .version = OVS_DATAPATH_VERSION,
1860         .maxattr = OVS_DP_ATTR_MAX,
1861         .netnsok = true,
1862         .parallel_ops = true,
1863         .ops = dp_datapath_genl_ops,
1864         .n_ops = ARRAY_SIZE(dp_datapath_genl_ops),
1865         .mcgrps = &ovs_dp_datapath_multicast_group,
1866         .n_mcgrps = 1,
1867         .module = THIS_MODULE,
1868 };
1869
1870 /* Called with ovs_mutex or RCU read lock. */
1871 static int ovs_vport_cmd_fill_info(struct vport *vport, struct sk_buff *skb,
1872                                    struct net *net, u32 portid, u32 seq,
1873                                    u32 flags, u8 cmd, gfp_t gfp)
1874 {
1875         struct ovs_header *ovs_header;
1876         struct ovs_vport_stats vport_stats;
1877         int err;
1878
1879         ovs_header = genlmsg_put(skb, portid, seq, &dp_vport_genl_family,
1880                                  flags, cmd);
1881         if (!ovs_header)
1882                 return -EMSGSIZE;
1883
1884         ovs_header->dp_ifindex = get_dpifindex(vport->dp);
1885
1886         if (nla_put_u32(skb, OVS_VPORT_ATTR_PORT_NO, vport->port_no) ||
1887             nla_put_u32(skb, OVS_VPORT_ATTR_TYPE, vport->ops->type) ||
1888             nla_put_string(skb, OVS_VPORT_ATTR_NAME,
1889                            ovs_vport_name(vport)) ||
1890             nla_put_u32(skb, OVS_VPORT_ATTR_IFINDEX, vport->dev->ifindex))
1891                 goto nla_put_failure;
1892
1893         if (!net_eq(net, dev_net(vport->dev))) {
1894                 int id = peernet2id_alloc(net, dev_net(vport->dev), gfp);
1895
1896                 if (nla_put_s32(skb, OVS_VPORT_ATTR_NETNSID, id))
1897                         goto nla_put_failure;
1898         }
1899
1900         ovs_vport_get_stats(vport, &vport_stats);
1901         if (nla_put_64bit(skb, OVS_VPORT_ATTR_STATS,
1902                           sizeof(struct ovs_vport_stats), &vport_stats,
1903                           OVS_VPORT_ATTR_PAD))
1904                 goto nla_put_failure;
1905
1906         if (ovs_vport_get_upcall_portids(vport, skb))
1907                 goto nla_put_failure;
1908
1909         err = ovs_vport_get_options(vport, skb);
1910         if (err == -EMSGSIZE)
1911                 goto error;
1912
1913         genlmsg_end(skb, ovs_header);
1914         return 0;
1915
1916 nla_put_failure:
1917         err = -EMSGSIZE;
1918 error:
1919         genlmsg_cancel(skb, ovs_header);
1920         return err;
1921 }
1922
1923 static struct sk_buff *ovs_vport_cmd_alloc_info(void)
1924 {
1925         return nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
1926 }
1927
1928 /* Called with ovs_mutex, only via ovs_dp_notify_wq(). */
1929 struct sk_buff *ovs_vport_cmd_build_info(struct vport *vport, struct net *net,
1930                                          u32 portid, u32 seq, u8 cmd)
1931 {
1932         struct sk_buff *skb;
1933         int retval;
1934
1935         skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
1936         if (!skb)
1937                 return ERR_PTR(-ENOMEM);
1938
1939         retval = ovs_vport_cmd_fill_info(vport, skb, net, portid, seq, 0, cmd,
1940                                          GFP_KERNEL);
1941         BUG_ON(retval < 0);
1942
1943         return skb;
1944 }
1945
1946 /* Called with ovs_mutex or RCU read lock. */
1947 static struct vport *lookup_vport(struct net *net,
1948                                   const struct ovs_header *ovs_header,
1949                                   struct nlattr *a[OVS_VPORT_ATTR_MAX + 1])
1950 {
1951         struct datapath *dp;
1952         struct vport *vport;
1953
1954         if (a[OVS_VPORT_ATTR_IFINDEX])
1955                 return ERR_PTR(-EOPNOTSUPP);
1956         if (a[OVS_VPORT_ATTR_NAME]) {
1957                 vport = ovs_vport_locate(net, nla_data(a[OVS_VPORT_ATTR_NAME]));
1958                 if (!vport)
1959                         return ERR_PTR(-ENODEV);
1960                 if (ovs_header->dp_ifindex &&
1961                     ovs_header->dp_ifindex != get_dpifindex(vport->dp))
1962                         return ERR_PTR(-ENODEV);
1963                 return vport;
1964         } else if (a[OVS_VPORT_ATTR_PORT_NO]) {
1965                 u32 port_no = nla_get_u32(a[OVS_VPORT_ATTR_PORT_NO]);
1966
1967                 if (port_no >= DP_MAX_PORTS)
1968                         return ERR_PTR(-EFBIG);
1969
1970                 dp = get_dp(net, ovs_header->dp_ifindex);
1971                 if (!dp)
1972                         return ERR_PTR(-ENODEV);
1973
1974                 vport = ovs_vport_ovsl_rcu(dp, port_no);
1975                 if (!vport)
1976                         return ERR_PTR(-ENODEV);
1977                 return vport;
1978         } else
1979                 return ERR_PTR(-EINVAL);
1980
1981 }
1982
1983 /* Called with ovs_mutex */
1984 static void update_headroom(struct datapath *dp)
1985 {
1986         unsigned dev_headroom, max_headroom = 0;
1987         struct net_device *dev;
1988         struct vport *vport;
1989         int i;
1990
1991         for (i = 0; i < DP_VPORT_HASH_BUCKETS; i++) {
1992                 hlist_for_each_entry_rcu(vport, &dp->ports[i], dp_hash_node) {
1993                         dev = vport->dev;
1994                         dev_headroom = netdev_get_fwd_headroom(dev);
1995                         if (dev_headroom > max_headroom)
1996                                 max_headroom = dev_headroom;
1997                 }
1998         }
1999
2000         dp->max_headroom = max_headroom;
2001         for (i = 0; i < DP_VPORT_HASH_BUCKETS; i++)
2002                 hlist_for_each_entry_rcu(vport, &dp->ports[i], dp_hash_node)
2003                         netdev_set_rx_headroom(vport->dev, max_headroom);
2004 }
2005
2006 static int ovs_vport_cmd_new(struct sk_buff *skb, struct genl_info *info)
2007 {
2008         struct nlattr **a = info->attrs;
2009         struct ovs_header *ovs_header = info->userhdr;
2010         struct vport_parms parms;
2011         struct sk_buff *reply;
2012         struct vport *vport;
2013         struct datapath *dp;
2014         u32 port_no;
2015         int err;
2016
2017         if (!a[OVS_VPORT_ATTR_NAME] || !a[OVS_VPORT_ATTR_TYPE] ||
2018             !a[OVS_VPORT_ATTR_UPCALL_PID])
2019                 return -EINVAL;
2020         if (a[OVS_VPORT_ATTR_IFINDEX])
2021                 return -EOPNOTSUPP;
2022
2023         port_no = a[OVS_VPORT_ATTR_PORT_NO]
2024                 ? nla_get_u32(a[OVS_VPORT_ATTR_PORT_NO]) : 0;
2025         if (port_no >= DP_MAX_PORTS)
2026                 return -EFBIG;
2027
2028         reply = ovs_vport_cmd_alloc_info();
2029         if (!reply)
2030                 return -ENOMEM;
2031
2032         ovs_lock();
2033 restart:
2034         dp = get_dp(sock_net(skb->sk), ovs_header->dp_ifindex);
2035         err = -ENODEV;
2036         if (!dp)
2037                 goto exit_unlock_free;
2038
2039         if (port_no) {
2040                 vport = ovs_vport_ovsl(dp, port_no);
2041                 err = -EBUSY;
2042                 if (vport)
2043                         goto exit_unlock_free;
2044         } else {
2045                 for (port_no = 1; ; port_no++) {
2046                         if (port_no >= DP_MAX_PORTS) {
2047                                 err = -EFBIG;
2048                                 goto exit_unlock_free;
2049                         }
2050                         vport = ovs_vport_ovsl(dp, port_no);
2051                         if (!vport)
2052                                 break;
2053                 }
2054         }
2055
2056         parms.name = nla_data(a[OVS_VPORT_ATTR_NAME]);
2057         parms.type = nla_get_u32(a[OVS_VPORT_ATTR_TYPE]);
2058         parms.options = a[OVS_VPORT_ATTR_OPTIONS];
2059         parms.dp = dp;
2060         parms.port_no = port_no;
2061         parms.upcall_portids = a[OVS_VPORT_ATTR_UPCALL_PID];
2062
2063         vport = new_vport(&parms);
2064         err = PTR_ERR(vport);
2065         if (IS_ERR(vport)) {
2066                 if (err == -EAGAIN)
2067                         goto restart;
2068                 goto exit_unlock_free;
2069         }
2070
2071         err = ovs_vport_cmd_fill_info(vport, reply, genl_info_net(info),
2072                                       info->snd_portid, info->snd_seq, 0,
2073                                       OVS_VPORT_CMD_NEW, GFP_KERNEL);
2074
2075         if (netdev_get_fwd_headroom(vport->dev) > dp->max_headroom)
2076                 update_headroom(dp);
2077         else
2078                 netdev_set_rx_headroom(vport->dev, dp->max_headroom);
2079
2080         BUG_ON(err < 0);
2081         ovs_unlock();
2082
2083         ovs_notify(&dp_vport_genl_family, reply, info);
2084         return 0;
2085
2086 exit_unlock_free:
2087         ovs_unlock();
2088         kfree_skb(reply);
2089         return err;
2090 }
2091
2092 static int ovs_vport_cmd_set(struct sk_buff *skb, struct genl_info *info)
2093 {
2094         struct nlattr **a = info->attrs;
2095         struct sk_buff *reply;
2096         struct vport *vport;
2097         int err;
2098
2099         reply = ovs_vport_cmd_alloc_info();
2100         if (!reply)
2101                 return -ENOMEM;
2102
2103         ovs_lock();
2104         vport = lookup_vport(sock_net(skb->sk), info->userhdr, a);
2105         err = PTR_ERR(vport);
2106         if (IS_ERR(vport))
2107                 goto exit_unlock_free;
2108
2109         if (a[OVS_VPORT_ATTR_TYPE] &&
2110             nla_get_u32(a[OVS_VPORT_ATTR_TYPE]) != vport->ops->type) {
2111                 err = -EINVAL;
2112                 goto exit_unlock_free;
2113         }
2114
2115         if (a[OVS_VPORT_ATTR_OPTIONS]) {
2116                 err = ovs_vport_set_options(vport, a[OVS_VPORT_ATTR_OPTIONS]);
2117                 if (err)
2118                         goto exit_unlock_free;
2119         }
2120
2121
2122         if (a[OVS_VPORT_ATTR_UPCALL_PID]) {
2123                 struct nlattr *ids = a[OVS_VPORT_ATTR_UPCALL_PID];
2124
2125                 err = ovs_vport_set_upcall_portids(vport, ids);
2126                 if (err)
2127                         goto exit_unlock_free;
2128         }
2129
2130         err = ovs_vport_cmd_fill_info(vport, reply, genl_info_net(info),
2131                                       info->snd_portid, info->snd_seq, 0,
2132                                       OVS_VPORT_CMD_NEW, GFP_ATOMIC);
2133         BUG_ON(err < 0);
2134
2135         ovs_unlock();
2136         ovs_notify(&dp_vport_genl_family, reply, info);
2137         return 0;
2138
2139 exit_unlock_free:
2140         ovs_unlock();
2141         kfree_skb(reply);
2142         return err;
2143 }
2144
2145 static int ovs_vport_cmd_del(struct sk_buff *skb, struct genl_info *info)
2146 {
2147         bool must_update_headroom = false;
2148         struct nlattr **a = info->attrs;
2149         struct sk_buff *reply;
2150         struct datapath *dp;
2151         struct vport *vport;
2152         int err;
2153
2154         reply = ovs_vport_cmd_alloc_info();
2155         if (!reply)
2156                 return -ENOMEM;
2157
2158         ovs_lock();
2159         vport = lookup_vport(sock_net(skb->sk), info->userhdr, a);
2160         err = PTR_ERR(vport);
2161         if (IS_ERR(vport))
2162                 goto exit_unlock_free;
2163
2164         if (vport->port_no == OVSP_LOCAL) {
2165                 err = -EINVAL;
2166                 goto exit_unlock_free;
2167         }
2168
2169         err = ovs_vport_cmd_fill_info(vport, reply, genl_info_net(info),
2170                                       info->snd_portid, info->snd_seq, 0,
2171                                       OVS_VPORT_CMD_DEL, GFP_KERNEL);
2172         BUG_ON(err < 0);
2173
2174         /* the vport deletion may trigger dp headroom update */
2175         dp = vport->dp;
2176         if (netdev_get_fwd_headroom(vport->dev) == dp->max_headroom)
2177                 must_update_headroom = true;
2178         netdev_reset_rx_headroom(vport->dev);
2179         ovs_dp_detach_port(vport);
2180
2181         if (must_update_headroom)
2182                 update_headroom(dp);
2183         ovs_unlock();
2184
2185         ovs_notify(&dp_vport_genl_family, reply, info);
2186         return 0;
2187
2188 exit_unlock_free:
2189         ovs_unlock();
2190         kfree_skb(reply);
2191         return err;
2192 }
2193
2194 static int ovs_vport_cmd_get(struct sk_buff *skb, struct genl_info *info)
2195 {
2196         struct nlattr **a = info->attrs;
2197         struct ovs_header *ovs_header = info->userhdr;
2198         struct sk_buff *reply;
2199         struct vport *vport;
2200         int err;
2201
2202         reply = ovs_vport_cmd_alloc_info();
2203         if (!reply)
2204                 return -ENOMEM;
2205
2206         rcu_read_lock();
2207         vport = lookup_vport(sock_net(skb->sk), ovs_header, a);
2208         err = PTR_ERR(vport);
2209         if (IS_ERR(vport))
2210                 goto exit_unlock_free;
2211         err = ovs_vport_cmd_fill_info(vport, reply, genl_info_net(info),
2212                                       info->snd_portid, info->snd_seq, 0,
2213                                       OVS_VPORT_CMD_NEW, GFP_ATOMIC);
2214         BUG_ON(err < 0);
2215         rcu_read_unlock();
2216
2217         return genlmsg_reply(reply, info);
2218
2219 exit_unlock_free:
2220         rcu_read_unlock();
2221         kfree_skb(reply);
2222         return err;
2223 }
2224
2225 static int ovs_vport_cmd_dump(struct sk_buff *skb, struct netlink_callback *cb)
2226 {
2227         struct ovs_header *ovs_header = genlmsg_data(nlmsg_data(cb->nlh));
2228         struct datapath *dp;
2229         int bucket = cb->args[0], skip = cb->args[1];
2230         int i, j = 0;
2231
2232         rcu_read_lock();
2233         dp = get_dp_rcu(sock_net(skb->sk), ovs_header->dp_ifindex);
2234         if (!dp) {
2235                 rcu_read_unlock();
2236                 return -ENODEV;
2237         }
2238         for (i = bucket; i < DP_VPORT_HASH_BUCKETS; i++) {
2239                 struct vport *vport;
2240
2241                 j = 0;
2242                 hlist_for_each_entry_rcu(vport, &dp->ports[i], dp_hash_node) {
2243                         if (j >= skip &&
2244                             ovs_vport_cmd_fill_info(vport, skb,
2245                                                     sock_net(skb->sk),
2246                                                     NETLINK_CB(cb->skb).portid,
2247                                                     cb->nlh->nlmsg_seq,
2248                                                     NLM_F_MULTI,
2249                                                     OVS_VPORT_CMD_NEW,
2250                                                     GFP_ATOMIC) < 0)
2251                                 goto out;
2252
2253                         j++;
2254                 }
2255                 skip = 0;
2256         }
2257 out:
2258         rcu_read_unlock();
2259
2260         cb->args[0] = i;
2261         cb->args[1] = j;
2262
2263         return skb->len;
2264 }
2265
2266 static const struct nla_policy vport_policy[OVS_VPORT_ATTR_MAX + 1] = {
2267         [OVS_VPORT_ATTR_NAME] = { .type = NLA_NUL_STRING, .len = IFNAMSIZ - 1 },
2268         [OVS_VPORT_ATTR_STATS] = { .len = sizeof(struct ovs_vport_stats) },
2269         [OVS_VPORT_ATTR_PORT_NO] = { .type = NLA_U32 },
2270         [OVS_VPORT_ATTR_TYPE] = { .type = NLA_U32 },
2271         [OVS_VPORT_ATTR_UPCALL_PID] = { .type = NLA_UNSPEC },
2272         [OVS_VPORT_ATTR_OPTIONS] = { .type = NLA_NESTED },
2273         [OVS_VPORT_ATTR_IFINDEX] = { .type = NLA_U32 },
2274         [OVS_VPORT_ATTR_NETNSID] = { .type = NLA_S32 },
2275 };
2276
2277 static const struct genl_ops dp_vport_genl_ops[] = {
2278         { .cmd = OVS_VPORT_CMD_NEW,
2279           .flags = GENL_UNS_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
2280           .policy = vport_policy,
2281           .doit = ovs_vport_cmd_new
2282         },
2283         { .cmd = OVS_VPORT_CMD_DEL,
2284           .flags = GENL_UNS_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
2285           .policy = vport_policy,
2286           .doit = ovs_vport_cmd_del
2287         },
2288         { .cmd = OVS_VPORT_CMD_GET,
2289           .flags = 0,               /* OK for unprivileged users. */
2290           .policy = vport_policy,
2291           .doit = ovs_vport_cmd_get,
2292           .dumpit = ovs_vport_cmd_dump
2293         },
2294         { .cmd = OVS_VPORT_CMD_SET,
2295           .flags = GENL_UNS_ADMIN_PERM, /* Requires CAP_NET_ADMIN privilege. */
2296           .policy = vport_policy,
2297           .doit = ovs_vport_cmd_set,
2298         },
2299 };
2300
2301 struct genl_family dp_vport_genl_family __ro_after_init = {
2302         .hdrsize = sizeof(struct ovs_header),
2303         .name = OVS_VPORT_FAMILY,
2304         .version = OVS_VPORT_VERSION,
2305         .maxattr = OVS_VPORT_ATTR_MAX,
2306         .netnsok = true,
2307         .parallel_ops = true,
2308         .ops = dp_vport_genl_ops,
2309         .n_ops = ARRAY_SIZE(dp_vport_genl_ops),
2310         .mcgrps = &ovs_dp_vport_multicast_group,
2311         .n_mcgrps = 1,
2312         .module = THIS_MODULE,
2313 };
2314
2315 static struct genl_family * const dp_genl_families[] = {
2316         &dp_datapath_genl_family,
2317         &dp_vport_genl_family,
2318         &dp_flow_genl_family,
2319         &dp_packet_genl_family,
2320         &dp_meter_genl_family,
2321 #if     IS_ENABLED(CONFIG_NETFILTER_CONNCOUNT)
2322         &dp_ct_limit_genl_family,
2323 #endif
2324 };
2325
2326 static void dp_unregister_genl(int n_families)
2327 {
2328         int i;
2329
2330         for (i = 0; i < n_families; i++)
2331                 genl_unregister_family(dp_genl_families[i]);
2332 }
2333
2334 static int __init dp_register_genl(void)
2335 {
2336         int err;
2337         int i;
2338
2339         for (i = 0; i < ARRAY_SIZE(dp_genl_families); i++) {
2340
2341                 err = genl_register_family(dp_genl_families[i]);
2342                 if (err)
2343                         goto error;
2344         }
2345
2346         return 0;
2347
2348 error:
2349         dp_unregister_genl(i);
2350         return err;
2351 }
2352
2353 static int __net_init ovs_init_net(struct net *net)
2354 {
2355         struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
2356
2357         INIT_LIST_HEAD(&ovs_net->dps);
2358         INIT_WORK(&ovs_net->dp_notify_work, ovs_dp_notify_wq);
2359         return ovs_ct_init(net);
2360 }
2361
2362 static void __net_exit list_vports_from_net(struct net *net, struct net *dnet,
2363                                             struct list_head *head)
2364 {
2365         struct ovs_net *ovs_net = net_generic(net, ovs_net_id);
2366         struct datapath *dp;
2367
2368         list_for_each_entry(dp, &ovs_net->dps, list_node) {
2369                 int i;
2370
2371                 for (i = 0; i < DP_VPORT_HASH_BUCKETS; i++) {
2372                         struct vport *vport;
2373
2374                         hlist_for_each_entry(vport, &dp->ports[i], dp_hash_node) {
2375                                 if (vport->ops->type != OVS_VPORT_TYPE_INTERNAL)
2376                                         continue;
2377
2378                                 if (dev_net(vport->dev) == dnet)
2379                                         list_add(&vport->detach_list, head);
2380                         }
2381                 }
2382         }
2383 }
2384
2385 static void __net_exit ovs_exit_net(struct net *dnet)
2386 {
2387         struct datapath *dp, *dp_next;
2388         struct ovs_net *ovs_net = net_generic(dnet, ovs_net_id);
2389         struct vport *vport, *vport_next;
2390         struct net *net;
2391         LIST_HEAD(head);
2392
2393         ovs_ct_exit(dnet);
2394         ovs_lock();
2395         list_for_each_entry_safe(dp, dp_next, &ovs_net->dps, list_node)
2396                 __dp_destroy(dp);
2397
2398         down_read(&net_rwsem);
2399         for_each_net(net)
2400                 list_vports_from_net(net, dnet, &head);
2401         up_read(&net_rwsem);
2402
2403         /* Detach all vports from given namespace. */
2404         list_for_each_entry_safe(vport, vport_next, &head, detach_list) {
2405                 list_del(&vport->detach_list);
2406                 ovs_dp_detach_port(vport);
2407         }
2408
2409         ovs_unlock();
2410
2411         cancel_work_sync(&ovs_net->dp_notify_work);
2412 }
2413
2414 static struct pernet_operations ovs_net_ops = {
2415         .init = ovs_init_net,
2416         .exit = ovs_exit_net,
2417         .id   = &ovs_net_id,
2418         .size = sizeof(struct ovs_net),
2419 };
2420
2421 static int __init dp_init(void)
2422 {
2423         int err;
2424
2425         BUILD_BUG_ON(sizeof(struct ovs_skb_cb) > FIELD_SIZEOF(struct sk_buff, cb));
2426
2427         pr_info("Open vSwitch switching datapath\n");
2428
2429         err = action_fifos_init();
2430         if (err)
2431                 goto error;
2432
2433         err = ovs_internal_dev_rtnl_link_register();
2434         if (err)
2435                 goto error_action_fifos_exit;
2436
2437         err = ovs_flow_init();
2438         if (err)
2439                 goto error_unreg_rtnl_link;
2440
2441         err = ovs_vport_init();
2442         if (err)
2443                 goto error_flow_exit;
2444
2445         err = register_pernet_device(&ovs_net_ops);
2446         if (err)
2447                 goto error_vport_exit;
2448
2449         err = register_netdevice_notifier(&ovs_dp_device_notifier);
2450         if (err)
2451                 goto error_netns_exit;
2452
2453         err = ovs_netdev_init();
2454         if (err)
2455                 goto error_unreg_notifier;
2456
2457         err = dp_register_genl();
2458         if (err < 0)
2459                 goto error_unreg_netdev;
2460
2461         return 0;
2462
2463 error_unreg_netdev:
2464         ovs_netdev_exit();
2465 error_unreg_notifier:
2466         unregister_netdevice_notifier(&ovs_dp_device_notifier);
2467 error_netns_exit:
2468         unregister_pernet_device(&ovs_net_ops);
2469 error_vport_exit:
2470         ovs_vport_exit();
2471 error_flow_exit:
2472         ovs_flow_exit();
2473 error_unreg_rtnl_link:
2474         ovs_internal_dev_rtnl_link_unregister();
2475 error_action_fifos_exit:
2476         action_fifos_exit();
2477 error:
2478         return err;
2479 }
2480
2481 static void dp_cleanup(void)
2482 {
2483         dp_unregister_genl(ARRAY_SIZE(dp_genl_families));
2484         ovs_netdev_exit();
2485         unregister_netdevice_notifier(&ovs_dp_device_notifier);
2486         unregister_pernet_device(&ovs_net_ops);
2487         rcu_barrier();
2488         ovs_vport_exit();
2489         ovs_flow_exit();
2490         ovs_internal_dev_rtnl_link_unregister();
2491         action_fifos_exit();
2492 }
2493
2494 module_init(dp_init);
2495 module_exit(dp_cleanup);
2496
2497 MODULE_DESCRIPTION("Open vSwitch switching datapath");
2498 MODULE_LICENSE("GPL");
2499 MODULE_ALIAS_GENL_FAMILY(OVS_DATAPATH_FAMILY);
2500 MODULE_ALIAS_GENL_FAMILY(OVS_VPORT_FAMILY);
2501 MODULE_ALIAS_GENL_FAMILY(OVS_FLOW_FAMILY);
2502 MODULE_ALIAS_GENL_FAMILY(OVS_PACKET_FAMILY);
2503 MODULE_ALIAS_GENL_FAMILY(OVS_METER_FAMILY);
2504 MODULE_ALIAS_GENL_FAMILY(OVS_CT_LIMIT_FAMILY);