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