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