netdev: New function netdev_get_dpif_port().
[sliver-openvswitch.git] / lib / dpif-linux.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18
19 #include "dpif-linux.h"
20
21 #include <ctype.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <inttypes.h>
25 #include <net/if.h>
26 #include <linux/types.h>
27 #include <linux/pkt_sched.h>
28 #include <linux/rtnetlink.h>
29 #include <linux/sockios.h>
30 #include <poll.h>
31 #include <stdlib.h>
32 #include <strings.h>
33 #include <sys/epoll.h>
34 #include <sys/stat.h>
35 #include <unistd.h>
36
37 #include "bitmap.h"
38 #include "dpif-provider.h"
39 #include "dynamic-string.h"
40 #include "flow.h"
41 #include "netdev.h"
42 #include "netdev-linux.h"
43 #include "netdev-vport.h"
44 #include "netlink-notifier.h"
45 #include "netlink-socket.h"
46 #include "netlink.h"
47 #include "odp-util.h"
48 #include "ofpbuf.h"
49 #include "openvswitch/datapath-compat.h"
50 #include "openvswitch/tunnel.h"
51 #include "packets.h"
52 #include "poll-loop.h"
53 #include "random.h"
54 #include "shash.h"
55 #include "sset.h"
56 #include "timeval.h"
57 #include "unaligned.h"
58 #include "util.h"
59 #include "vlog.h"
60
61 VLOG_DEFINE_THIS_MODULE(dpif_linux);
62 enum { MAX_PORTS = USHRT_MAX };
63
64 /* This ethtool flag was introduced in Linux 2.6.24, so it might be
65  * missing if we have old headers. */
66 #define ETH_FLAG_LRO      (1 << 15)    /* LRO is enabled */
67
68 struct dpif_linux_dp {
69     /* Generic Netlink header. */
70     uint8_t cmd;
71
72     /* struct ovs_header. */
73     int dp_ifindex;
74
75     /* Attributes. */
76     const char *name;                  /* OVS_DP_ATTR_NAME. */
77     const uint32_t *upcall_pid;        /* OVS_DP_UPCALL_PID. */
78     struct ovs_dp_stats stats;         /* OVS_DP_ATTR_STATS. */
79 };
80
81 static void dpif_linux_dp_init(struct dpif_linux_dp *);
82 static int dpif_linux_dp_from_ofpbuf(struct dpif_linux_dp *,
83                                      const struct ofpbuf *);
84 static void dpif_linux_dp_dump_start(struct nl_dump *);
85 static int dpif_linux_dp_transact(const struct dpif_linux_dp *request,
86                                   struct dpif_linux_dp *reply,
87                                   struct ofpbuf **bufp);
88 static int dpif_linux_dp_get(const struct dpif *, struct dpif_linux_dp *reply,
89                              struct ofpbuf **bufp);
90
91 struct dpif_linux_flow {
92     /* Generic Netlink header. */
93     uint8_t cmd;
94
95     /* struct ovs_header. */
96     unsigned int nlmsg_flags;
97     int dp_ifindex;
98
99     /* Attributes.
100      *
101      * The 'stats' member points to 64-bit data that might only be aligned on
102      * 32-bit boundaries, so get_unaligned_u64() should be used to access its
103      * values.
104      *
105      * If 'actions' is nonnull then OVS_FLOW_ATTR_ACTIONS will be included in
106      * the Netlink version of the command, even if actions_len is zero. */
107     const struct nlattr *key;           /* OVS_FLOW_ATTR_KEY. */
108     size_t key_len;
109     const struct nlattr *actions;       /* OVS_FLOW_ATTR_ACTIONS. */
110     size_t actions_len;
111     const struct ovs_flow_stats *stats; /* OVS_FLOW_ATTR_STATS. */
112     const uint8_t *tcp_flags;           /* OVS_FLOW_ATTR_TCP_FLAGS. */
113     const ovs_32aligned_u64 *used;      /* OVS_FLOW_ATTR_USED. */
114     bool clear;                         /* OVS_FLOW_ATTR_CLEAR. */
115 };
116
117 static void dpif_linux_flow_init(struct dpif_linux_flow *);
118 static int dpif_linux_flow_from_ofpbuf(struct dpif_linux_flow *,
119                                        const struct ofpbuf *);
120 static void dpif_linux_flow_to_ofpbuf(const struct dpif_linux_flow *,
121                                       struct ofpbuf *);
122 static int dpif_linux_flow_transact(struct dpif_linux_flow *request,
123                                     struct dpif_linux_flow *reply,
124                                     struct ofpbuf **bufp);
125 static void dpif_linux_flow_get_stats(const struct dpif_linux_flow *,
126                                       struct dpif_flow_stats *);
127
128 /* One of the dpif channels between the kernel and userspace. */
129 struct dpif_channel {
130     struct nl_sock *sock;       /* Netlink socket. */
131     long long int last_poll;    /* Last time this channel was polled. */
132 };
133
134 static void report_loss(struct dpif *, struct dpif_channel *);
135
136 /* Datapath interface for the openvswitch Linux kernel module. */
137 struct dpif_linux {
138     struct dpif dpif;
139     int dp_ifindex;
140
141     /* Upcall messages. */
142     int uc_array_size;          /* Size of 'channels' and 'epoll_events'. */
143     struct dpif_channel *channels;
144     struct epoll_event *epoll_events;
145     int epoll_fd;               /* epoll fd that includes channel socks. */
146     int n_events;               /* Num events returned by epoll_wait(). */
147     int event_offset;           /* Offset into 'epoll_events'. */
148
149     /* Change notification. */
150     struct sset changed_ports;  /* Ports that have changed. */
151     struct nln_notifier *port_notifier;
152     bool change_error;
153 };
154
155 static struct vlog_rate_limit error_rl = VLOG_RATE_LIMIT_INIT(9999, 5);
156
157 /* Generic Netlink family numbers for OVS. */
158 static int ovs_datapath_family;
159 static int ovs_vport_family;
160 static int ovs_flow_family;
161 static int ovs_packet_family;
162
163 /* Generic Netlink socket. */
164 static struct nl_sock *genl_sock;
165 static struct nln *nln = NULL;
166
167 static int dpif_linux_init(void);
168 static void open_dpif(const struct dpif_linux_dp *, struct dpif **);
169 static bool dpif_linux_nln_parse(struct ofpbuf *, void *);
170 static void dpif_linux_port_changed(const void *vport, void *dpif);
171 static uint32_t dpif_linux_port_get_pid(const struct dpif *, uint32_t port_no);
172
173 static void dpif_linux_vport_to_ofpbuf(const struct dpif_linux_vport *,
174                                        struct ofpbuf *);
175 static int dpif_linux_vport_from_ofpbuf(struct dpif_linux_vport *,
176                                         const struct ofpbuf *);
177
178 static struct dpif_linux *
179 dpif_linux_cast(const struct dpif *dpif)
180 {
181     dpif_assert_class(dpif, &dpif_linux_class);
182     return CONTAINER_OF(dpif, struct dpif_linux, dpif);
183 }
184
185 static int
186 dpif_linux_enumerate(struct sset *all_dps)
187 {
188     struct nl_dump dump;
189     struct ofpbuf msg;
190     int error;
191
192     error = dpif_linux_init();
193     if (error) {
194         return error;
195     }
196
197     dpif_linux_dp_dump_start(&dump);
198     while (nl_dump_next(&dump, &msg)) {
199         struct dpif_linux_dp dp;
200
201         if (!dpif_linux_dp_from_ofpbuf(&dp, &msg)) {
202             sset_add(all_dps, dp.name);
203         }
204     }
205     return nl_dump_done(&dump);
206 }
207
208 static int
209 dpif_linux_open(const struct dpif_class *class OVS_UNUSED, const char *name,
210                 bool create, struct dpif **dpifp)
211 {
212     struct dpif_linux_dp dp_request, dp;
213     struct ofpbuf *buf;
214     uint32_t upcall_pid;
215     int error;
216
217     error = dpif_linux_init();
218     if (error) {
219         return error;
220     }
221
222     /* Create or look up datapath. */
223     dpif_linux_dp_init(&dp_request);
224     if (create) {
225         dp_request.cmd = OVS_DP_CMD_NEW;
226         upcall_pid = 0;
227         dp_request.upcall_pid = &upcall_pid;
228     } else {
229         dp_request.cmd = OVS_DP_CMD_GET;
230     }
231     dp_request.name = name;
232     error = dpif_linux_dp_transact(&dp_request, &dp, &buf);
233     if (error) {
234         return error;
235     }
236
237     open_dpif(&dp, dpifp);
238     ofpbuf_delete(buf);
239     return 0;
240 }
241
242 static void
243 open_dpif(const struct dpif_linux_dp *dp, struct dpif **dpifp)
244 {
245     struct dpif_linux *dpif;
246
247     dpif = xzalloc(sizeof *dpif);
248     dpif->port_notifier = nln_notifier_create(nln, dpif_linux_port_changed,
249                                               dpif);
250     dpif->epoll_fd = -1;
251
252     dpif_init(&dpif->dpif, &dpif_linux_class, dp->name,
253               dp->dp_ifindex, dp->dp_ifindex);
254
255     dpif->dp_ifindex = dp->dp_ifindex;
256     sset_init(&dpif->changed_ports);
257     *dpifp = &dpif->dpif;
258 }
259
260 static void
261 destroy_channels(struct dpif_linux *dpif)
262 {
263     int i;
264
265     if (dpif->epoll_fd < 0) {
266         return;
267     }
268
269     for (i = 0; i < dpif->uc_array_size; i++ ) {
270         struct dpif_linux_vport vport_request;
271         struct dpif_channel *ch = &dpif->channels[i];
272         uint32_t upcall_pid = 0;
273
274         if (!ch->sock) {
275             continue;
276         }
277
278         /* Turn off upcalls. */
279         dpif_linux_vport_init(&vport_request);
280         vport_request.cmd = OVS_VPORT_CMD_SET;
281         vport_request.dp_ifindex = dpif->dp_ifindex;
282         vport_request.port_no = i;
283         vport_request.upcall_pid = &upcall_pid;
284         dpif_linux_vport_transact(&vport_request, NULL, NULL);
285
286         nl_sock_destroy(ch->sock);
287     }
288
289     free(dpif->channels);
290     dpif->channels = NULL;
291     dpif->uc_array_size = 0;
292
293     free(dpif->epoll_events);
294     dpif->epoll_events = NULL;
295     dpif->n_events = dpif->event_offset = 0;
296
297     close(dpif->epoll_fd);
298     dpif->epoll_fd = -1;
299 }
300
301 static int
302 add_channel(struct dpif_linux *dpif, uint32_t port_no, struct nl_sock *sock)
303 {
304     struct epoll_event event;
305
306     if (dpif->epoll_fd < 0) {
307         return 0;
308     }
309
310     /* We assume that the datapath densely chooses port numbers, which
311      * can therefore be used as an index into an array of channels. */
312     if (port_no >= dpif->uc_array_size) {
313         int new_size = port_no + 1;
314         int i;
315
316         if (new_size > 65535) {
317             VLOG_WARN_RL(&error_rl, "%s: datapath port %"PRIu32" too big",
318                          dpif_name(&dpif->dpif), port_no);
319             return EFBIG;
320         }
321
322         dpif->channels = xrealloc(dpif->channels,
323                                   new_size * sizeof *dpif->channels);
324         for (i = dpif->uc_array_size; i < new_size; i++) {
325             dpif->channels[i].sock = NULL;
326         }
327
328         dpif->epoll_events = xrealloc(dpif->epoll_events,
329                                       new_size * sizeof *dpif->epoll_events);
330         dpif->uc_array_size = new_size;
331     }
332
333     memset(&event, 0, sizeof event);
334     event.events = EPOLLIN;
335     event.data.u32 = port_no;
336     if (epoll_ctl(dpif->epoll_fd, EPOLL_CTL_ADD, nl_sock_fd(sock),
337                   &event) < 0) {
338         return errno;
339     }
340
341     dpif->channels[port_no].sock = sock;
342     dpif->channels[port_no].last_poll = LLONG_MIN;
343
344     return 0;
345 }
346
347 static void
348 del_channel(struct dpif_linux *dpif, uint32_t port_no)
349 {
350     struct dpif_channel *ch;
351
352     if (dpif->epoll_fd < 0 || port_no >= dpif->uc_array_size) {
353         return;
354     }
355
356     ch = &dpif->channels[port_no];
357     if (!ch->sock) {
358         return;
359     }
360
361     epoll_ctl(dpif->epoll_fd, EPOLL_CTL_DEL, nl_sock_fd(ch->sock), NULL);
362
363     nl_sock_destroy(ch->sock);
364     ch->sock = NULL;
365 }
366
367 static void
368 dpif_linux_close(struct dpif *dpif_)
369 {
370     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
371
372     nln_notifier_destroy(dpif->port_notifier);
373     destroy_channels(dpif);
374     sset_destroy(&dpif->changed_ports);
375     free(dpif);
376 }
377
378 static int
379 dpif_linux_destroy(struct dpif *dpif_)
380 {
381     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
382     struct dpif_linux_dp dp;
383
384     dpif_linux_dp_init(&dp);
385     dp.cmd = OVS_DP_CMD_DEL;
386     dp.dp_ifindex = dpif->dp_ifindex;
387     return dpif_linux_dp_transact(&dp, NULL, NULL);
388 }
389
390 static void
391 dpif_linux_run(struct dpif *dpif_ OVS_UNUSED)
392 {
393     if (nln) {
394         nln_run(nln);
395     }
396 }
397
398 static void
399 dpif_linux_wait(struct dpif *dpif OVS_UNUSED)
400 {
401     if (nln) {
402         nln_wait(nln);
403     }
404 }
405
406 static int
407 dpif_linux_get_stats(const struct dpif *dpif_, struct dpif_dp_stats *stats)
408 {
409     struct dpif_linux_dp dp;
410     struct ofpbuf *buf;
411     int error;
412
413     error = dpif_linux_dp_get(dpif_, &dp, &buf);
414     if (!error) {
415         stats->n_hit    = dp.stats.n_hit;
416         stats->n_missed = dp.stats.n_missed;
417         stats->n_lost   = dp.stats.n_lost;
418         stats->n_flows  = dp.stats.n_flows;
419         ofpbuf_delete(buf);
420     }
421     return error;
422 }
423
424 static int
425 dpif_linux_port_add(struct dpif *dpif_, struct netdev *netdev,
426                     uint32_t *port_nop)
427 {
428     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
429     const char *name = netdev_vport_get_dpif_port(netdev);
430     const char *type = netdev_get_type(netdev);
431     struct dpif_linux_vport request, reply;
432     const struct ofpbuf *options;
433     struct nl_sock *sock = NULL;
434     uint32_t upcall_pid;
435     struct ofpbuf *buf;
436     int error;
437
438     if (dpif->epoll_fd >= 0) {
439         error = nl_sock_create(NETLINK_GENERIC, &sock);
440         if (error) {
441             return error;
442         }
443     }
444
445     dpif_linux_vport_init(&request);
446     request.cmd = OVS_VPORT_CMD_NEW;
447     request.dp_ifindex = dpif->dp_ifindex;
448     request.type = netdev_vport_get_vport_type(netdev);
449     if (request.type == OVS_VPORT_TYPE_UNSPEC) {
450         VLOG_WARN_RL(&error_rl, "%s: cannot create port `%s' because it has "
451                      "unsupported type `%s'",
452                      dpif_name(dpif_), name, type);
453         nl_sock_destroy(sock);
454         return EINVAL;
455     }
456     request.name = name;
457
458     options = netdev_vport_get_options(netdev);
459     if (options && options->size) {
460         request.options = options->data;
461         request.options_len = options->size;
462     }
463
464     if (request.type == OVS_VPORT_TYPE_NETDEV) {
465         netdev_linux_ethtool_set_flag(netdev, ETH_FLAG_LRO, "LRO", false);
466     }
467
468     request.port_no = *port_nop;
469     upcall_pid = sock ? nl_sock_pid(sock) : 0;
470     request.upcall_pid = &upcall_pid;
471
472     error = dpif_linux_vport_transact(&request, &reply, &buf);
473     if (!error) {
474         *port_nop = reply.port_no;
475         VLOG_DBG("%s: assigning port %"PRIu32" to netlink pid %"PRIu32,
476                  dpif_name(dpif_), reply.port_no, upcall_pid);
477     } else {
478         if (error == EBUSY && *port_nop != UINT32_MAX) {
479             VLOG_INFO("%s: requested port %"PRIu32" is in use",
480                       dpif_name(dpif_), *port_nop);
481         }
482         nl_sock_destroy(sock);
483         ofpbuf_delete(buf);
484         return error;
485     }
486     ofpbuf_delete(buf);
487
488     if (sock) {
489         error = add_channel(dpif, *port_nop, sock);
490         if (error) {
491             VLOG_INFO("%s: could not add channel for port %s",
492                       dpif_name(dpif_), name);
493
494             /* Delete the port. */
495             dpif_linux_vport_init(&request);
496             request.cmd = OVS_VPORT_CMD_DEL;
497             request.dp_ifindex = dpif->dp_ifindex;
498             request.port_no = *port_nop;
499             dpif_linux_vport_transact(&request, NULL, NULL);
500
501             nl_sock_destroy(sock);
502             return error;
503         }
504     }
505
506     return 0;
507 }
508
509 static int
510 dpif_linux_port_del(struct dpif *dpif_, uint32_t port_no)
511 {
512     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
513     struct dpif_linux_vport vport;
514     int error;
515
516     dpif_linux_vport_init(&vport);
517     vport.cmd = OVS_VPORT_CMD_DEL;
518     vport.dp_ifindex = dpif->dp_ifindex;
519     vport.port_no = port_no;
520     error = dpif_linux_vport_transact(&vport, NULL, NULL);
521
522     del_channel(dpif, port_no);
523
524     return error;
525 }
526
527 static int
528 dpif_linux_port_query__(const struct dpif *dpif, uint32_t port_no,
529                         const char *port_name, struct dpif_port *dpif_port)
530 {
531     struct dpif_linux_vport request;
532     struct dpif_linux_vport reply;
533     struct ofpbuf *buf;
534     int error;
535
536     dpif_linux_vport_init(&request);
537     request.cmd = OVS_VPORT_CMD_GET;
538     request.dp_ifindex = dpif_linux_cast(dpif)->dp_ifindex;
539     request.port_no = port_no;
540     request.name = port_name;
541
542     error = dpif_linux_vport_transact(&request, &reply, &buf);
543     if (!error) {
544         if (reply.dp_ifindex != request.dp_ifindex) {
545             /* A query by name reported that 'port_name' is in some datapath
546              * other than 'dpif', but the caller wants to know about 'dpif'. */
547             error = ENODEV;
548         } else if (dpif_port) {
549             dpif_port->name = xstrdup(reply.name);
550             dpif_port->type = xstrdup(netdev_vport_get_netdev_type(&reply));
551             dpif_port->port_no = reply.port_no;
552         }
553         ofpbuf_delete(buf);
554     }
555     return error;
556 }
557
558 static int
559 dpif_linux_port_query_by_number(const struct dpif *dpif, uint32_t port_no,
560                                 struct dpif_port *dpif_port)
561 {
562     return dpif_linux_port_query__(dpif, port_no, NULL, dpif_port);
563 }
564
565 static int
566 dpif_linux_port_query_by_name(const struct dpif *dpif, const char *devname,
567                               struct dpif_port *dpif_port)
568 {
569     return dpif_linux_port_query__(dpif, 0, devname, dpif_port);
570 }
571
572 static int
573 dpif_linux_get_max_ports(const struct dpif *dpif OVS_UNUSED)
574 {
575     return MAX_PORTS;
576 }
577
578 static uint32_t
579 dpif_linux_port_get_pid(const struct dpif *dpif_, uint32_t port_no)
580 {
581     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
582
583     if (dpif->epoll_fd < 0) {
584         return 0;
585     } else {
586         /* The UINT32_MAX "reserved" port number uses the "ovs-system"'s
587          * channel, since it is not heavily loaded. */
588         int idx = (port_no >= dpif->uc_array_size) ? 0 : port_no;
589         return nl_sock_pid(dpif->channels[idx].sock);
590     }
591 }
592
593 static int
594 dpif_linux_flow_flush(struct dpif *dpif_)
595 {
596     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
597     struct dpif_linux_flow flow;
598
599     dpif_linux_flow_init(&flow);
600     flow.cmd = OVS_FLOW_CMD_DEL;
601     flow.dp_ifindex = dpif->dp_ifindex;
602     return dpif_linux_flow_transact(&flow, NULL, NULL);
603 }
604
605 struct dpif_linux_port_state {
606     struct nl_dump dump;
607 };
608
609 static int
610 dpif_linux_port_dump_start(const struct dpif *dpif_, void **statep)
611 {
612     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
613     struct dpif_linux_port_state *state;
614     struct dpif_linux_vport request;
615     struct ofpbuf *buf;
616
617     *statep = state = xmalloc(sizeof *state);
618
619     dpif_linux_vport_init(&request);
620     request.cmd = OVS_DP_CMD_GET;
621     request.dp_ifindex = dpif->dp_ifindex;
622
623     buf = ofpbuf_new(1024);
624     dpif_linux_vport_to_ofpbuf(&request, buf);
625     nl_dump_start(&state->dump, genl_sock, buf);
626     ofpbuf_delete(buf);
627
628     return 0;
629 }
630
631 static int
632 dpif_linux_port_dump_next(const struct dpif *dpif OVS_UNUSED, void *state_,
633                           struct dpif_port *dpif_port)
634 {
635     struct dpif_linux_port_state *state = state_;
636     struct dpif_linux_vport vport;
637     struct ofpbuf buf;
638     int error;
639
640     if (!nl_dump_next(&state->dump, &buf)) {
641         return EOF;
642     }
643
644     error = dpif_linux_vport_from_ofpbuf(&vport, &buf);
645     if (error) {
646         return error;
647     }
648
649     dpif_port->name = CONST_CAST(char *, vport.name);
650     dpif_port->type = CONST_CAST(char *, netdev_vport_get_netdev_type(&vport));
651     dpif_port->port_no = vport.port_no;
652     return 0;
653 }
654
655 static int
656 dpif_linux_port_dump_done(const struct dpif *dpif_ OVS_UNUSED, void *state_)
657 {
658     struct dpif_linux_port_state *state = state_;
659     int error = nl_dump_done(&state->dump);
660
661     free(state);
662     return error;
663 }
664
665 static int
666 dpif_linux_port_poll(const struct dpif *dpif_, char **devnamep)
667 {
668     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
669
670     if (dpif->change_error) {
671         dpif->change_error = false;
672         sset_clear(&dpif->changed_ports);
673         return ENOBUFS;
674     } else if (!sset_is_empty(&dpif->changed_ports)) {
675         *devnamep = sset_pop(&dpif->changed_ports);
676         return 0;
677     } else {
678         return EAGAIN;
679     }
680 }
681
682 static void
683 dpif_linux_port_poll_wait(const struct dpif *dpif_)
684 {
685     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
686     if (!sset_is_empty(&dpif->changed_ports) || dpif->change_error) {
687         poll_immediate_wake();
688     }
689 }
690
691 static int
692 dpif_linux_flow_get__(const struct dpif *dpif_,
693                       const struct nlattr *key, size_t key_len,
694                       struct dpif_linux_flow *reply, struct ofpbuf **bufp)
695 {
696     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
697     struct dpif_linux_flow request;
698
699     dpif_linux_flow_init(&request);
700     request.cmd = OVS_FLOW_CMD_GET;
701     request.dp_ifindex = dpif->dp_ifindex;
702     request.key = key;
703     request.key_len = key_len;
704     return dpif_linux_flow_transact(&request, reply, bufp);
705 }
706
707 static int
708 dpif_linux_flow_get(const struct dpif *dpif_,
709                     const struct nlattr *key, size_t key_len,
710                     struct ofpbuf **actionsp, struct dpif_flow_stats *stats)
711 {
712     struct dpif_linux_flow reply;
713     struct ofpbuf *buf;
714     int error;
715
716     error = dpif_linux_flow_get__(dpif_, key, key_len, &reply, &buf);
717     if (!error) {
718         if (stats) {
719             dpif_linux_flow_get_stats(&reply, stats);
720         }
721         if (actionsp) {
722             buf->data = CONST_CAST(struct nlattr *, reply.actions);
723             buf->size = reply.actions_len;
724             *actionsp = buf;
725         } else {
726             ofpbuf_delete(buf);
727         }
728     }
729     return error;
730 }
731
732 static void
733 dpif_linux_init_flow_put(struct dpif *dpif_, const struct dpif_flow_put *put,
734                          struct dpif_linux_flow *request)
735 {
736     static struct nlattr dummy_action;
737
738     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
739
740     dpif_linux_flow_init(request);
741     request->cmd = (put->flags & DPIF_FP_CREATE
742                     ? OVS_FLOW_CMD_NEW : OVS_FLOW_CMD_SET);
743     request->dp_ifindex = dpif->dp_ifindex;
744     request->key = put->key;
745     request->key_len = put->key_len;
746     /* Ensure that OVS_FLOW_ATTR_ACTIONS will always be included. */
747     request->actions = put->actions ? put->actions : &dummy_action;
748     request->actions_len = put->actions_len;
749     if (put->flags & DPIF_FP_ZERO_STATS) {
750         request->clear = true;
751     }
752     request->nlmsg_flags = put->flags & DPIF_FP_MODIFY ? 0 : NLM_F_CREATE;
753 }
754
755 static int
756 dpif_linux_flow_put(struct dpif *dpif_, const struct dpif_flow_put *put)
757 {
758     struct dpif_linux_flow request, reply;
759     struct ofpbuf *buf;
760     int error;
761
762     dpif_linux_init_flow_put(dpif_, put, &request);
763     error = dpif_linux_flow_transact(&request,
764                                      put->stats ? &reply : NULL,
765                                      put->stats ? &buf : NULL);
766     if (!error && put->stats) {
767         dpif_linux_flow_get_stats(&reply, put->stats);
768         ofpbuf_delete(buf);
769     }
770     return error;
771 }
772
773 static void
774 dpif_linux_init_flow_del(struct dpif *dpif_, const struct dpif_flow_del *del,
775                          struct dpif_linux_flow *request)
776 {
777     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
778
779     dpif_linux_flow_init(request);
780     request->cmd = OVS_FLOW_CMD_DEL;
781     request->dp_ifindex = dpif->dp_ifindex;
782     request->key = del->key;
783     request->key_len = del->key_len;
784 }
785
786 static int
787 dpif_linux_flow_del(struct dpif *dpif_, const struct dpif_flow_del *del)
788 {
789     struct dpif_linux_flow request, reply;
790     struct ofpbuf *buf;
791     int error;
792
793     dpif_linux_init_flow_del(dpif_, del, &request);
794     error = dpif_linux_flow_transact(&request,
795                                      del->stats ? &reply : NULL,
796                                      del->stats ? &buf : NULL);
797     if (!error && del->stats) {
798         dpif_linux_flow_get_stats(&reply, del->stats);
799         ofpbuf_delete(buf);
800     }
801     return error;
802 }
803
804 struct dpif_linux_flow_state {
805     struct nl_dump dump;
806     struct dpif_linux_flow flow;
807     struct dpif_flow_stats stats;
808     struct ofpbuf *buf;
809 };
810
811 static int
812 dpif_linux_flow_dump_start(const struct dpif *dpif_, void **statep)
813 {
814     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
815     struct dpif_linux_flow_state *state;
816     struct dpif_linux_flow request;
817     struct ofpbuf *buf;
818
819     *statep = state = xmalloc(sizeof *state);
820
821     dpif_linux_flow_init(&request);
822     request.cmd = OVS_DP_CMD_GET;
823     request.dp_ifindex = dpif->dp_ifindex;
824
825     buf = ofpbuf_new(1024);
826     dpif_linux_flow_to_ofpbuf(&request, buf);
827     nl_dump_start(&state->dump, genl_sock, buf);
828     ofpbuf_delete(buf);
829
830     state->buf = NULL;
831
832     return 0;
833 }
834
835 static int
836 dpif_linux_flow_dump_next(const struct dpif *dpif_ OVS_UNUSED, void *state_,
837                           const struct nlattr **key, size_t *key_len,
838                           const struct nlattr **actions, size_t *actions_len,
839                           const struct dpif_flow_stats **stats)
840 {
841     struct dpif_linux_flow_state *state = state_;
842     struct ofpbuf buf;
843     int error;
844
845     do {
846         ofpbuf_delete(state->buf);
847         state->buf = NULL;
848
849         if (!nl_dump_next(&state->dump, &buf)) {
850             return EOF;
851         }
852
853         error = dpif_linux_flow_from_ofpbuf(&state->flow, &buf);
854         if (error) {
855             return error;
856         }
857
858         if (actions && !state->flow.actions) {
859             error = dpif_linux_flow_get__(dpif_, state->flow.key,
860                                           state->flow.key_len,
861                                           &state->flow, &state->buf);
862             if (error == ENOENT) {
863                 VLOG_DBG("dumped flow disappeared on get");
864             } else if (error) {
865                 VLOG_WARN("error fetching dumped flow: %s", strerror(error));
866             }
867         }
868     } while (error);
869
870     if (actions) {
871         *actions = state->flow.actions;
872         *actions_len = state->flow.actions_len;
873     }
874     if (key) {
875         *key = state->flow.key;
876         *key_len = state->flow.key_len;
877     }
878     if (stats) {
879         dpif_linux_flow_get_stats(&state->flow, &state->stats);
880         *stats = &state->stats;
881     }
882     return error;
883 }
884
885 static int
886 dpif_linux_flow_dump_done(const struct dpif *dpif OVS_UNUSED, void *state_)
887 {
888     struct dpif_linux_flow_state *state = state_;
889     int error = nl_dump_done(&state->dump);
890     ofpbuf_delete(state->buf);
891     free(state);
892     return error;
893 }
894
895 static void
896 dpif_linux_encode_execute(int dp_ifindex, const struct dpif_execute *d_exec,
897                           struct ofpbuf *buf)
898 {
899     struct ovs_header *k_exec;
900
901     ofpbuf_prealloc_tailroom(buf, (64
902                                    + d_exec->packet->size
903                                    + d_exec->key_len
904                                    + d_exec->actions_len));
905
906     nl_msg_put_genlmsghdr(buf, 0, ovs_packet_family, NLM_F_REQUEST,
907                           OVS_PACKET_CMD_EXECUTE, OVS_PACKET_VERSION);
908
909     k_exec = ofpbuf_put_uninit(buf, sizeof *k_exec);
910     k_exec->dp_ifindex = dp_ifindex;
911
912     nl_msg_put_unspec(buf, OVS_PACKET_ATTR_PACKET,
913                       d_exec->packet->data, d_exec->packet->size);
914     nl_msg_put_unspec(buf, OVS_PACKET_ATTR_KEY, d_exec->key, d_exec->key_len);
915     nl_msg_put_unspec(buf, OVS_PACKET_ATTR_ACTIONS,
916                       d_exec->actions, d_exec->actions_len);
917 }
918
919 static int
920 dpif_linux_execute__(int dp_ifindex, const struct dpif_execute *execute)
921 {
922     uint64_t request_stub[1024 / 8];
923     struct ofpbuf request;
924     int error;
925
926     ofpbuf_use_stub(&request, request_stub, sizeof request_stub);
927     dpif_linux_encode_execute(dp_ifindex, execute, &request);
928     error = nl_sock_transact(genl_sock, &request, NULL);
929     ofpbuf_uninit(&request);
930
931     return error;
932 }
933
934 static int
935 dpif_linux_execute(struct dpif *dpif_, const struct dpif_execute *execute)
936 {
937     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
938
939     return dpif_linux_execute__(dpif->dp_ifindex, execute);
940 }
941
942 #define MAX_OPS 50
943
944 static void
945 dpif_linux_operate__(struct dpif *dpif_, struct dpif_op **ops, size_t n_ops)
946 {
947     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
948
949     struct op_auxdata {
950         struct nl_transaction txn;
951
952         struct ofpbuf request;
953         uint64_t request_stub[1024 / 8];
954
955         struct ofpbuf reply;
956         uint64_t reply_stub[1024 / 8];
957     } auxes[MAX_OPS];
958
959     struct nl_transaction *txnsp[MAX_OPS];
960     size_t i;
961
962     ovs_assert(n_ops <= MAX_OPS);
963     for (i = 0; i < n_ops; i++) {
964         struct op_auxdata *aux = &auxes[i];
965         struct dpif_op *op = ops[i];
966         struct dpif_flow_put *put;
967         struct dpif_flow_del *del;
968         struct dpif_execute *execute;
969         struct dpif_linux_flow flow;
970
971         ofpbuf_use_stub(&aux->request,
972                         aux->request_stub, sizeof aux->request_stub);
973         aux->txn.request = &aux->request;
974
975         ofpbuf_use_stub(&aux->reply, aux->reply_stub, sizeof aux->reply_stub);
976         aux->txn.reply = NULL;
977
978         switch (op->type) {
979         case DPIF_OP_FLOW_PUT:
980             put = &op->u.flow_put;
981             dpif_linux_init_flow_put(dpif_, put, &flow);
982             if (put->stats) {
983                 flow.nlmsg_flags |= NLM_F_ECHO;
984                 aux->txn.reply = &aux->reply;
985             }
986             dpif_linux_flow_to_ofpbuf(&flow, &aux->request);
987             break;
988
989         case DPIF_OP_FLOW_DEL:
990             del = &op->u.flow_del;
991             dpif_linux_init_flow_del(dpif_, del, &flow);
992             if (del->stats) {
993                 flow.nlmsg_flags |= NLM_F_ECHO;
994                 aux->txn.reply = &aux->reply;
995             }
996             dpif_linux_flow_to_ofpbuf(&flow, &aux->request);
997             break;
998
999         case DPIF_OP_EXECUTE:
1000             execute = &op->u.execute;
1001             dpif_linux_encode_execute(dpif->dp_ifindex, execute,
1002                                       &aux->request);
1003             break;
1004
1005         default:
1006             NOT_REACHED();
1007         }
1008     }
1009
1010     for (i = 0; i < n_ops; i++) {
1011         txnsp[i] = &auxes[i].txn;
1012     }
1013     nl_sock_transact_multiple(genl_sock, txnsp, n_ops);
1014
1015     for (i = 0; i < n_ops; i++) {
1016         struct op_auxdata *aux = &auxes[i];
1017         struct nl_transaction *txn = &auxes[i].txn;
1018         struct dpif_op *op = ops[i];
1019         struct dpif_flow_put *put;
1020         struct dpif_flow_del *del;
1021
1022         op->error = txn->error;
1023
1024         switch (op->type) {
1025         case DPIF_OP_FLOW_PUT:
1026             put = &op->u.flow_put;
1027             if (put->stats) {
1028                 if (!op->error) {
1029                     struct dpif_linux_flow reply;
1030
1031                     op->error = dpif_linux_flow_from_ofpbuf(&reply,
1032                                                             txn->reply);
1033                     if (!op->error) {
1034                         dpif_linux_flow_get_stats(&reply, put->stats);
1035                     }
1036                 }
1037
1038                 if (op->error) {
1039                     memset(put->stats, 0, sizeof *put->stats);
1040                 }
1041             }
1042             break;
1043
1044         case DPIF_OP_FLOW_DEL:
1045             del = &op->u.flow_del;
1046             if (del->stats) {
1047                 if (!op->error) {
1048                     struct dpif_linux_flow reply;
1049
1050                     op->error = dpif_linux_flow_from_ofpbuf(&reply,
1051                                                             txn->reply);
1052                     if (!op->error) {
1053                         dpif_linux_flow_get_stats(&reply, del->stats);
1054                     }
1055                 }
1056
1057                 if (op->error) {
1058                     memset(del->stats, 0, sizeof *del->stats);
1059                 }
1060             }
1061             break;
1062
1063         case DPIF_OP_EXECUTE:
1064             break;
1065
1066         default:
1067             NOT_REACHED();
1068         }
1069
1070         ofpbuf_uninit(&aux->request);
1071         ofpbuf_uninit(&aux->reply);
1072     }
1073 }
1074
1075 static void
1076 dpif_linux_operate(struct dpif *dpif, struct dpif_op **ops, size_t n_ops)
1077 {
1078     while (n_ops > 0) {
1079         size_t chunk = MIN(n_ops, MAX_OPS);
1080         dpif_linux_operate__(dpif, ops, chunk);
1081         ops += chunk;
1082         n_ops -= chunk;
1083     }
1084 }
1085
1086 static int
1087 dpif_linux_recv_set(struct dpif *dpif_, bool enable)
1088 {
1089     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1090
1091     if ((dpif->epoll_fd >= 0) == enable) {
1092         return 0;
1093     }
1094
1095     if (!enable) {
1096         destroy_channels(dpif);
1097     } else {
1098         struct dpif_port_dump port_dump;
1099         struct dpif_port port;
1100
1101         dpif->epoll_fd = epoll_create(10);
1102         if (dpif->epoll_fd < 0) {
1103             return errno;
1104         }
1105
1106         DPIF_PORT_FOR_EACH (&port, &port_dump, &dpif->dpif) {
1107             struct dpif_linux_vport vport_request;
1108             struct nl_sock *sock;
1109             uint32_t upcall_pid;
1110             int error;
1111
1112             error = nl_sock_create(NETLINK_GENERIC, &sock);
1113             if (error) {
1114                 return error;
1115             }
1116
1117             upcall_pid = nl_sock_pid(sock);
1118
1119             dpif_linux_vport_init(&vport_request);
1120             vport_request.cmd = OVS_VPORT_CMD_SET;
1121             vport_request.dp_ifindex = dpif->dp_ifindex;
1122             vport_request.port_no = port.port_no;
1123             vport_request.upcall_pid = &upcall_pid;
1124             error = dpif_linux_vport_transact(&vport_request, NULL, NULL);
1125             if (!error) {
1126                 VLOG_DBG("%s: assigning port %"PRIu32" to netlink pid %"PRIu32,
1127                          dpif_name(&dpif->dpif), vport_request.port_no,
1128                          upcall_pid);
1129             } else {
1130                 VLOG_WARN_RL(&error_rl,
1131                              "%s: failed to set upcall pid on port: %s",
1132                              dpif_name(&dpif->dpif), strerror(error));
1133                 nl_sock_destroy(sock);
1134
1135                 if (error == ENODEV || error == ENOENT) {
1136                     /* This device isn't there, but keep trying the others. */
1137                     continue;
1138                 } else {
1139                     return error;
1140                 }
1141             }
1142
1143             error = add_channel(dpif, port.port_no, sock);
1144             if (error) {
1145                 VLOG_INFO("%s: could not add channel for port %s",
1146                           dpif_name(dpif_), port.name);
1147                 nl_sock_destroy(sock);
1148                 return error;
1149             }
1150         }
1151     }
1152
1153     return 0;
1154 }
1155
1156 static int
1157 dpif_linux_queue_to_priority(const struct dpif *dpif OVS_UNUSED,
1158                              uint32_t queue_id, uint32_t *priority)
1159 {
1160     if (queue_id < 0xf000) {
1161         *priority = TC_H_MAKE(1 << 16, queue_id + 1);
1162         return 0;
1163     } else {
1164         return EINVAL;
1165     }
1166 }
1167
1168 static int
1169 parse_odp_packet(struct ofpbuf *buf, struct dpif_upcall *upcall,
1170                  int *dp_ifindex)
1171 {
1172     static const struct nl_policy ovs_packet_policy[] = {
1173         /* Always present. */
1174         [OVS_PACKET_ATTR_PACKET] = { .type = NL_A_UNSPEC,
1175                                      .min_len = ETH_HEADER_LEN },
1176         [OVS_PACKET_ATTR_KEY] = { .type = NL_A_NESTED },
1177
1178         /* OVS_PACKET_CMD_ACTION only. */
1179         [OVS_PACKET_ATTR_USERDATA] = { .type = NL_A_U64, .optional = true },
1180     };
1181
1182     struct ovs_header *ovs_header;
1183     struct nlattr *a[ARRAY_SIZE(ovs_packet_policy)];
1184     struct nlmsghdr *nlmsg;
1185     struct genlmsghdr *genl;
1186     struct ofpbuf b;
1187     int type;
1188
1189     ofpbuf_use_const(&b, buf->data, buf->size);
1190
1191     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1192     genl = ofpbuf_try_pull(&b, sizeof *genl);
1193     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1194     if (!nlmsg || !genl || !ovs_header
1195         || nlmsg->nlmsg_type != ovs_packet_family
1196         || !nl_policy_parse(&b, 0, ovs_packet_policy, a,
1197                             ARRAY_SIZE(ovs_packet_policy))) {
1198         return EINVAL;
1199     }
1200
1201     type = (genl->cmd == OVS_PACKET_CMD_MISS ? DPIF_UC_MISS
1202             : genl->cmd == OVS_PACKET_CMD_ACTION ? DPIF_UC_ACTION
1203             : -1);
1204     if (type < 0) {
1205         return EINVAL;
1206     }
1207
1208     memset(upcall, 0, sizeof *upcall);
1209     upcall->type = type;
1210     upcall->packet = buf;
1211     upcall->packet->data = CONST_CAST(struct nlattr *,
1212                                       nl_attr_get(a[OVS_PACKET_ATTR_PACKET]));
1213     upcall->packet->size = nl_attr_get_size(a[OVS_PACKET_ATTR_PACKET]);
1214     upcall->key = CONST_CAST(struct nlattr *,
1215                              nl_attr_get(a[OVS_PACKET_ATTR_KEY]));
1216     upcall->key_len = nl_attr_get_size(a[OVS_PACKET_ATTR_KEY]);
1217     upcall->userdata = (a[OVS_PACKET_ATTR_USERDATA]
1218                         ? nl_attr_get_u64(a[OVS_PACKET_ATTR_USERDATA])
1219                         : 0);
1220     *dp_ifindex = ovs_header->dp_ifindex;
1221
1222     return 0;
1223 }
1224
1225 static int
1226 dpif_linux_recv(struct dpif *dpif_, struct dpif_upcall *upcall,
1227                 struct ofpbuf *buf)
1228 {
1229     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1230     int read_tries = 0;
1231
1232     if (dpif->epoll_fd < 0) {
1233        return EAGAIN;
1234     }
1235
1236     if (dpif->event_offset >= dpif->n_events) {
1237         int retval;
1238
1239         dpif->event_offset = dpif->n_events = 0;
1240
1241         do {
1242             retval = epoll_wait(dpif->epoll_fd, dpif->epoll_events,
1243                                 dpif->uc_array_size, 0);
1244         } while (retval < 0 && errno == EINTR);
1245         if (retval < 0) {
1246             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
1247             VLOG_WARN_RL(&rl, "epoll_wait failed (%s)", strerror(errno));
1248         } else if (retval > 0) {
1249             dpif->n_events = retval;
1250         }
1251     }
1252
1253     while (dpif->event_offset < dpif->n_events) {
1254         int idx = dpif->epoll_events[dpif->event_offset].data.u32;
1255         struct dpif_channel *ch = &dpif->channels[idx];
1256
1257         dpif->event_offset++;
1258
1259         for (;;) {
1260             int dp_ifindex;
1261             int error;
1262
1263             if (++read_tries > 50) {
1264                 return EAGAIN;
1265             }
1266
1267             error = nl_sock_recv(ch->sock, buf, false);
1268             if (error == ENOBUFS) {
1269                 /* ENOBUFS typically means that we've received so many
1270                  * packets that the buffer overflowed.  Try again
1271                  * immediately because there's almost certainly a packet
1272                  * waiting for us. */
1273                 report_loss(dpif_, ch);
1274                 continue;
1275             }
1276
1277             ch->last_poll = time_msec();
1278             if (error) {
1279                 if (error == EAGAIN) {
1280                     break;
1281                 }
1282                 return error;
1283             }
1284
1285             error = parse_odp_packet(buf, upcall, &dp_ifindex);
1286             if (!error && dp_ifindex == dpif->dp_ifindex) {
1287                 return 0;
1288             } else if (error) {
1289                 return error;
1290             }
1291         }
1292     }
1293
1294     return EAGAIN;
1295 }
1296
1297 static void
1298 dpif_linux_recv_wait(struct dpif *dpif_)
1299 {
1300     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1301
1302     if (dpif->epoll_fd < 0) {
1303        return;
1304     }
1305
1306     poll_fd_wait(dpif->epoll_fd, POLLIN);
1307 }
1308
1309 static void
1310 dpif_linux_recv_purge(struct dpif *dpif_)
1311 {
1312     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1313     struct dpif_channel *ch;
1314
1315     if (dpif->epoll_fd < 0) {
1316        return;
1317     }
1318
1319     for (ch = dpif->channels; ch < &dpif->channels[dpif->uc_array_size]; ch++) {
1320         if (ch->sock) {
1321             nl_sock_drain(ch->sock);
1322         }
1323     }
1324 }
1325
1326 const struct dpif_class dpif_linux_class = {
1327     "system",
1328     dpif_linux_enumerate,
1329     NULL,
1330     dpif_linux_open,
1331     dpif_linux_close,
1332     dpif_linux_destroy,
1333     dpif_linux_run,
1334     dpif_linux_wait,
1335     dpif_linux_get_stats,
1336     dpif_linux_port_add,
1337     dpif_linux_port_del,
1338     dpif_linux_port_query_by_number,
1339     dpif_linux_port_query_by_name,
1340     dpif_linux_get_max_ports,
1341     dpif_linux_port_get_pid,
1342     dpif_linux_port_dump_start,
1343     dpif_linux_port_dump_next,
1344     dpif_linux_port_dump_done,
1345     dpif_linux_port_poll,
1346     dpif_linux_port_poll_wait,
1347     dpif_linux_flow_get,
1348     dpif_linux_flow_put,
1349     dpif_linux_flow_del,
1350     dpif_linux_flow_flush,
1351     dpif_linux_flow_dump_start,
1352     dpif_linux_flow_dump_next,
1353     dpif_linux_flow_dump_done,
1354     dpif_linux_execute,
1355     dpif_linux_operate,
1356     dpif_linux_recv_set,
1357     dpif_linux_queue_to_priority,
1358     dpif_linux_recv,
1359     dpif_linux_recv_wait,
1360     dpif_linux_recv_purge,
1361 };
1362 \f
1363 static int
1364 dpif_linux_init(void)
1365 {
1366     static int error = -1;
1367
1368     if (error < 0) {
1369         unsigned int ovs_vport_mcgroup;
1370
1371         error = nl_lookup_genl_family(OVS_DATAPATH_FAMILY,
1372                                       &ovs_datapath_family);
1373         if (error) {
1374             VLOG_ERR("Generic Netlink family '%s' does not exist. "
1375                      "The Open vSwitch kernel module is probably not loaded.",
1376                      OVS_DATAPATH_FAMILY);
1377         }
1378         if (!error) {
1379             error = nl_lookup_genl_family(OVS_VPORT_FAMILY, &ovs_vport_family);
1380         }
1381         if (!error) {
1382             error = nl_lookup_genl_family(OVS_FLOW_FAMILY, &ovs_flow_family);
1383         }
1384         if (!error) {
1385             error = nl_lookup_genl_family(OVS_PACKET_FAMILY,
1386                                           &ovs_packet_family);
1387         }
1388         if (!error) {
1389             error = nl_sock_create(NETLINK_GENERIC, &genl_sock);
1390         }
1391         if (!error) {
1392             error = nl_lookup_genl_mcgroup(OVS_VPORT_FAMILY, OVS_VPORT_MCGROUP,
1393                                            &ovs_vport_mcgroup,
1394                                            OVS_VPORT_MCGROUP_FALLBACK_ID);
1395         }
1396         if (!error) {
1397             static struct dpif_linux_vport vport;
1398             nln = nln_create(NETLINK_GENERIC, ovs_vport_mcgroup,
1399                              dpif_linux_nln_parse, &vport);
1400         }
1401     }
1402
1403     return error;
1404 }
1405
1406 bool
1407 dpif_linux_is_internal_device(const char *name)
1408 {
1409     struct dpif_linux_vport reply;
1410     struct ofpbuf *buf;
1411     int error;
1412
1413     error = dpif_linux_vport_get(name, &reply, &buf);
1414     if (!error) {
1415         ofpbuf_delete(buf);
1416     } else if (error != ENODEV && error != ENOENT) {
1417         VLOG_WARN_RL(&error_rl, "%s: vport query failed (%s)",
1418                      name, strerror(error));
1419     }
1420
1421     return reply.type == OVS_VPORT_TYPE_INTERNAL;
1422 }
1423
1424 static bool
1425 dpif_linux_nln_parse(struct ofpbuf *buf, void *vport_)
1426 {
1427     struct dpif_linux_vport *vport = vport_;
1428     return dpif_linux_vport_from_ofpbuf(vport, buf) == 0;
1429 }
1430
1431 static void
1432 dpif_linux_port_changed(const void *vport_, void *dpif_)
1433 {
1434     const struct dpif_linux_vport *vport = vport_;
1435     struct dpif_linux *dpif = dpif_;
1436
1437     if (vport) {
1438         if (vport->dp_ifindex == dpif->dp_ifindex
1439             && (vport->cmd == OVS_VPORT_CMD_NEW
1440                 || vport->cmd == OVS_VPORT_CMD_DEL
1441                 || vport->cmd == OVS_VPORT_CMD_SET)) {
1442             VLOG_DBG("port_changed: dpif:%s vport:%s cmd:%"PRIu8,
1443                      dpif->dpif.full_name, vport->name, vport->cmd);
1444             sset_add(&dpif->changed_ports, vport->name);
1445         }
1446     } else {
1447         dpif->change_error = true;
1448     }
1449 }
1450 \f
1451 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
1452  * by Netlink attributes, into 'vport'.  Returns 0 if successful, otherwise a
1453  * positive errno value.
1454  *
1455  * 'vport' will contain pointers into 'buf', so the caller should not free
1456  * 'buf' while 'vport' is still in use. */
1457 static int
1458 dpif_linux_vport_from_ofpbuf(struct dpif_linux_vport *vport,
1459                              const struct ofpbuf *buf)
1460 {
1461     static const struct nl_policy ovs_vport_policy[] = {
1462         [OVS_VPORT_ATTR_PORT_NO] = { .type = NL_A_U32 },
1463         [OVS_VPORT_ATTR_TYPE] = { .type = NL_A_U32 },
1464         [OVS_VPORT_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
1465         [OVS_VPORT_ATTR_UPCALL_PID] = { .type = NL_A_U32 },
1466         [OVS_VPORT_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_vport_stats),
1467                                    .optional = true },
1468         [OVS_VPORT_ATTR_OPTIONS] = { .type = NL_A_NESTED, .optional = true },
1469     };
1470
1471     struct nlattr *a[ARRAY_SIZE(ovs_vport_policy)];
1472     struct ovs_header *ovs_header;
1473     struct nlmsghdr *nlmsg;
1474     struct genlmsghdr *genl;
1475     struct ofpbuf b;
1476
1477     dpif_linux_vport_init(vport);
1478
1479     ofpbuf_use_const(&b, buf->data, buf->size);
1480     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1481     genl = ofpbuf_try_pull(&b, sizeof *genl);
1482     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1483     if (!nlmsg || !genl || !ovs_header
1484         || nlmsg->nlmsg_type != ovs_vport_family
1485         || !nl_policy_parse(&b, 0, ovs_vport_policy, a,
1486                             ARRAY_SIZE(ovs_vport_policy))) {
1487         return EINVAL;
1488     }
1489
1490     vport->cmd = genl->cmd;
1491     vport->dp_ifindex = ovs_header->dp_ifindex;
1492     vport->port_no = nl_attr_get_u32(a[OVS_VPORT_ATTR_PORT_NO]);
1493     vport->type = nl_attr_get_u32(a[OVS_VPORT_ATTR_TYPE]);
1494     vport->name = nl_attr_get_string(a[OVS_VPORT_ATTR_NAME]);
1495     if (a[OVS_VPORT_ATTR_UPCALL_PID]) {
1496         vport->upcall_pid = nl_attr_get(a[OVS_VPORT_ATTR_UPCALL_PID]);
1497     }
1498     if (a[OVS_VPORT_ATTR_STATS]) {
1499         vport->stats = nl_attr_get(a[OVS_VPORT_ATTR_STATS]);
1500     }
1501     if (a[OVS_VPORT_ATTR_OPTIONS]) {
1502         vport->options = nl_attr_get(a[OVS_VPORT_ATTR_OPTIONS]);
1503         vport->options_len = nl_attr_get_size(a[OVS_VPORT_ATTR_OPTIONS]);
1504     }
1505     return 0;
1506 }
1507
1508 /* Appends to 'buf' (which must initially be empty) a "struct ovs_header"
1509  * followed by Netlink attributes corresponding to 'vport'. */
1510 static void
1511 dpif_linux_vport_to_ofpbuf(const struct dpif_linux_vport *vport,
1512                            struct ofpbuf *buf)
1513 {
1514     struct ovs_header *ovs_header;
1515
1516     nl_msg_put_genlmsghdr(buf, 0, ovs_vport_family, NLM_F_REQUEST | NLM_F_ECHO,
1517                           vport->cmd, OVS_VPORT_VERSION);
1518
1519     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
1520     ovs_header->dp_ifindex = vport->dp_ifindex;
1521
1522     if (vport->port_no != UINT32_MAX) {
1523         nl_msg_put_u32(buf, OVS_VPORT_ATTR_PORT_NO, vport->port_no);
1524     }
1525
1526     if (vport->type != OVS_VPORT_TYPE_UNSPEC) {
1527         nl_msg_put_u32(buf, OVS_VPORT_ATTR_TYPE, vport->type);
1528     }
1529
1530     if (vport->name) {
1531         nl_msg_put_string(buf, OVS_VPORT_ATTR_NAME, vport->name);
1532     }
1533
1534     if (vport->upcall_pid) {
1535         nl_msg_put_u32(buf, OVS_VPORT_ATTR_UPCALL_PID, *vport->upcall_pid);
1536     }
1537
1538     if (vport->stats) {
1539         nl_msg_put_unspec(buf, OVS_VPORT_ATTR_STATS,
1540                           vport->stats, sizeof *vport->stats);
1541     }
1542
1543     if (vport->options) {
1544         nl_msg_put_nested(buf, OVS_VPORT_ATTR_OPTIONS,
1545                           vport->options, vport->options_len);
1546     }
1547 }
1548
1549 /* Clears 'vport' to "empty" values. */
1550 void
1551 dpif_linux_vport_init(struct dpif_linux_vport *vport)
1552 {
1553     memset(vport, 0, sizeof *vport);
1554     vport->port_no = UINT32_MAX;
1555 }
1556
1557 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
1558  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
1559  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
1560  * result of the command is expected to be an ovs_vport also, which is decoded
1561  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
1562  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
1563 int
1564 dpif_linux_vport_transact(const struct dpif_linux_vport *request,
1565                           struct dpif_linux_vport *reply,
1566                           struct ofpbuf **bufp)
1567 {
1568     struct ofpbuf *request_buf;
1569     int error;
1570
1571     ovs_assert((reply != NULL) == (bufp != NULL));
1572
1573     error = dpif_linux_init();
1574     if (error) {
1575         if (reply) {
1576             *bufp = NULL;
1577             dpif_linux_vport_init(reply);
1578         }
1579         return error;
1580     }
1581
1582     request_buf = ofpbuf_new(1024);
1583     dpif_linux_vport_to_ofpbuf(request, request_buf);
1584     error = nl_sock_transact(genl_sock, request_buf, bufp);
1585     ofpbuf_delete(request_buf);
1586
1587     if (reply) {
1588         if (!error) {
1589             error = dpif_linux_vport_from_ofpbuf(reply, *bufp);
1590         }
1591         if (error) {
1592             dpif_linux_vport_init(reply);
1593             ofpbuf_delete(*bufp);
1594             *bufp = NULL;
1595         }
1596     }
1597     return error;
1598 }
1599
1600 /* Obtains information about the kernel vport named 'name' and stores it into
1601  * '*reply' and '*bufp'.  The caller must free '*bufp' when the reply is no
1602  * longer needed ('reply' will contain pointers into '*bufp').  */
1603 int
1604 dpif_linux_vport_get(const char *name, struct dpif_linux_vport *reply,
1605                      struct ofpbuf **bufp)
1606 {
1607     struct dpif_linux_vport request;
1608
1609     dpif_linux_vport_init(&request);
1610     request.cmd = OVS_VPORT_CMD_GET;
1611     request.name = name;
1612
1613     return dpif_linux_vport_transact(&request, reply, bufp);
1614 }
1615 \f
1616 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
1617  * by Netlink attributes, into 'dp'.  Returns 0 if successful, otherwise a
1618  * positive errno value.
1619  *
1620  * 'dp' will contain pointers into 'buf', so the caller should not free 'buf'
1621  * while 'dp' is still in use. */
1622 static int
1623 dpif_linux_dp_from_ofpbuf(struct dpif_linux_dp *dp, const struct ofpbuf *buf)
1624 {
1625     static const struct nl_policy ovs_datapath_policy[] = {
1626         [OVS_DP_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
1627         [OVS_DP_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_dp_stats),
1628                                 .optional = true },
1629     };
1630
1631     struct nlattr *a[ARRAY_SIZE(ovs_datapath_policy)];
1632     struct ovs_header *ovs_header;
1633     struct nlmsghdr *nlmsg;
1634     struct genlmsghdr *genl;
1635     struct ofpbuf b;
1636
1637     dpif_linux_dp_init(dp);
1638
1639     ofpbuf_use_const(&b, buf->data, buf->size);
1640     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1641     genl = ofpbuf_try_pull(&b, sizeof *genl);
1642     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1643     if (!nlmsg || !genl || !ovs_header
1644         || nlmsg->nlmsg_type != ovs_datapath_family
1645         || !nl_policy_parse(&b, 0, ovs_datapath_policy, a,
1646                             ARRAY_SIZE(ovs_datapath_policy))) {
1647         return EINVAL;
1648     }
1649
1650     dp->cmd = genl->cmd;
1651     dp->dp_ifindex = ovs_header->dp_ifindex;
1652     dp->name = nl_attr_get_string(a[OVS_DP_ATTR_NAME]);
1653     if (a[OVS_DP_ATTR_STATS]) {
1654         /* Can't use structure assignment because Netlink doesn't ensure
1655          * sufficient alignment for 64-bit members. */
1656         memcpy(&dp->stats, nl_attr_get(a[OVS_DP_ATTR_STATS]),
1657                sizeof dp->stats);
1658     }
1659
1660     return 0;
1661 }
1662
1663 /* Appends to 'buf' the Generic Netlink message described by 'dp'. */
1664 static void
1665 dpif_linux_dp_to_ofpbuf(const struct dpif_linux_dp *dp, struct ofpbuf *buf)
1666 {
1667     struct ovs_header *ovs_header;
1668
1669     nl_msg_put_genlmsghdr(buf, 0, ovs_datapath_family,
1670                           NLM_F_REQUEST | NLM_F_ECHO, dp->cmd,
1671                           OVS_DATAPATH_VERSION);
1672
1673     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
1674     ovs_header->dp_ifindex = dp->dp_ifindex;
1675
1676     if (dp->name) {
1677         nl_msg_put_string(buf, OVS_DP_ATTR_NAME, dp->name);
1678     }
1679
1680     if (dp->upcall_pid) {
1681         nl_msg_put_u32(buf, OVS_DP_ATTR_UPCALL_PID, *dp->upcall_pid);
1682     }
1683
1684     /* Skip OVS_DP_ATTR_STATS since we never have a reason to serialize it. */
1685 }
1686
1687 /* Clears 'dp' to "empty" values. */
1688 static void
1689 dpif_linux_dp_init(struct dpif_linux_dp *dp)
1690 {
1691     memset(dp, 0, sizeof *dp);
1692 }
1693
1694 static void
1695 dpif_linux_dp_dump_start(struct nl_dump *dump)
1696 {
1697     struct dpif_linux_dp request;
1698     struct ofpbuf *buf;
1699
1700     dpif_linux_dp_init(&request);
1701     request.cmd = OVS_DP_CMD_GET;
1702
1703     buf = ofpbuf_new(1024);
1704     dpif_linux_dp_to_ofpbuf(&request, buf);
1705     nl_dump_start(dump, genl_sock, buf);
1706     ofpbuf_delete(buf);
1707 }
1708
1709 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
1710  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
1711  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
1712  * result of the command is expected to be of the same form, which is decoded
1713  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
1714  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
1715 static int
1716 dpif_linux_dp_transact(const struct dpif_linux_dp *request,
1717                        struct dpif_linux_dp *reply, struct ofpbuf **bufp)
1718 {
1719     struct ofpbuf *request_buf;
1720     int error;
1721
1722     ovs_assert((reply != NULL) == (bufp != NULL));
1723
1724     request_buf = ofpbuf_new(1024);
1725     dpif_linux_dp_to_ofpbuf(request, request_buf);
1726     error = nl_sock_transact(genl_sock, request_buf, bufp);
1727     ofpbuf_delete(request_buf);
1728
1729     if (reply) {
1730         if (!error) {
1731             error = dpif_linux_dp_from_ofpbuf(reply, *bufp);
1732         }
1733         if (error) {
1734             dpif_linux_dp_init(reply);
1735             ofpbuf_delete(*bufp);
1736             *bufp = NULL;
1737         }
1738     }
1739     return error;
1740 }
1741
1742 /* Obtains information about 'dpif_' and stores it into '*reply' and '*bufp'.
1743  * The caller must free '*bufp' when the reply is no longer needed ('reply'
1744  * will contain pointers into '*bufp').  */
1745 static int
1746 dpif_linux_dp_get(const struct dpif *dpif_, struct dpif_linux_dp *reply,
1747                   struct ofpbuf **bufp)
1748 {
1749     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1750     struct dpif_linux_dp request;
1751
1752     dpif_linux_dp_init(&request);
1753     request.cmd = OVS_DP_CMD_GET;
1754     request.dp_ifindex = dpif->dp_ifindex;
1755
1756     return dpif_linux_dp_transact(&request, reply, bufp);
1757 }
1758 \f
1759 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
1760  * by Netlink attributes, into 'flow'.  Returns 0 if successful, otherwise a
1761  * positive errno value.
1762  *
1763  * 'flow' will contain pointers into 'buf', so the caller should not free 'buf'
1764  * while 'flow' is still in use. */
1765 static int
1766 dpif_linux_flow_from_ofpbuf(struct dpif_linux_flow *flow,
1767                             const struct ofpbuf *buf)
1768 {
1769     static const struct nl_policy ovs_flow_policy[] = {
1770         [OVS_FLOW_ATTR_KEY] = { .type = NL_A_NESTED },
1771         [OVS_FLOW_ATTR_ACTIONS] = { .type = NL_A_NESTED, .optional = true },
1772         [OVS_FLOW_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_flow_stats),
1773                                   .optional = true },
1774         [OVS_FLOW_ATTR_TCP_FLAGS] = { .type = NL_A_U8, .optional = true },
1775         [OVS_FLOW_ATTR_USED] = { .type = NL_A_U64, .optional = true },
1776         /* The kernel never uses OVS_FLOW_ATTR_CLEAR. */
1777     };
1778
1779     struct nlattr *a[ARRAY_SIZE(ovs_flow_policy)];
1780     struct ovs_header *ovs_header;
1781     struct nlmsghdr *nlmsg;
1782     struct genlmsghdr *genl;
1783     struct ofpbuf b;
1784
1785     dpif_linux_flow_init(flow);
1786
1787     ofpbuf_use_const(&b, buf->data, buf->size);
1788     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1789     genl = ofpbuf_try_pull(&b, sizeof *genl);
1790     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1791     if (!nlmsg || !genl || !ovs_header
1792         || nlmsg->nlmsg_type != ovs_flow_family
1793         || !nl_policy_parse(&b, 0, ovs_flow_policy, a,
1794                             ARRAY_SIZE(ovs_flow_policy))) {
1795         return EINVAL;
1796     }
1797
1798     flow->nlmsg_flags = nlmsg->nlmsg_flags;
1799     flow->dp_ifindex = ovs_header->dp_ifindex;
1800     flow->key = nl_attr_get(a[OVS_FLOW_ATTR_KEY]);
1801     flow->key_len = nl_attr_get_size(a[OVS_FLOW_ATTR_KEY]);
1802     if (a[OVS_FLOW_ATTR_ACTIONS]) {
1803         flow->actions = nl_attr_get(a[OVS_FLOW_ATTR_ACTIONS]);
1804         flow->actions_len = nl_attr_get_size(a[OVS_FLOW_ATTR_ACTIONS]);
1805     }
1806     if (a[OVS_FLOW_ATTR_STATS]) {
1807         flow->stats = nl_attr_get(a[OVS_FLOW_ATTR_STATS]);
1808     }
1809     if (a[OVS_FLOW_ATTR_TCP_FLAGS]) {
1810         flow->tcp_flags = nl_attr_get(a[OVS_FLOW_ATTR_TCP_FLAGS]);
1811     }
1812     if (a[OVS_FLOW_ATTR_USED]) {
1813         flow->used = nl_attr_get(a[OVS_FLOW_ATTR_USED]);
1814     }
1815     return 0;
1816 }
1817
1818 /* Appends to 'buf' (which must initially be empty) a "struct ovs_header"
1819  * followed by Netlink attributes corresponding to 'flow'. */
1820 static void
1821 dpif_linux_flow_to_ofpbuf(const struct dpif_linux_flow *flow,
1822                           struct ofpbuf *buf)
1823 {
1824     struct ovs_header *ovs_header;
1825
1826     nl_msg_put_genlmsghdr(buf, 0, ovs_flow_family,
1827                           NLM_F_REQUEST | flow->nlmsg_flags,
1828                           flow->cmd, OVS_FLOW_VERSION);
1829
1830     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
1831     ovs_header->dp_ifindex = flow->dp_ifindex;
1832
1833     if (flow->key_len) {
1834         nl_msg_put_unspec(buf, OVS_FLOW_ATTR_KEY, flow->key, flow->key_len);
1835     }
1836
1837     if (flow->actions || flow->actions_len) {
1838         nl_msg_put_unspec(buf, OVS_FLOW_ATTR_ACTIONS,
1839                           flow->actions, flow->actions_len);
1840     }
1841
1842     /* We never need to send these to the kernel. */
1843     ovs_assert(!flow->stats);
1844     ovs_assert(!flow->tcp_flags);
1845     ovs_assert(!flow->used);
1846
1847     if (flow->clear) {
1848         nl_msg_put_flag(buf, OVS_FLOW_ATTR_CLEAR);
1849     }
1850 }
1851
1852 /* Clears 'flow' to "empty" values. */
1853 static void
1854 dpif_linux_flow_init(struct dpif_linux_flow *flow)
1855 {
1856     memset(flow, 0, sizeof *flow);
1857 }
1858
1859 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
1860  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
1861  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
1862  * result of the command is expected to be a flow also, which is decoded and
1863  * stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the reply
1864  * is no longer needed ('reply' will contain pointers into '*bufp'). */
1865 static int
1866 dpif_linux_flow_transact(struct dpif_linux_flow *request,
1867                          struct dpif_linux_flow *reply, struct ofpbuf **bufp)
1868 {
1869     struct ofpbuf *request_buf;
1870     int error;
1871
1872     ovs_assert((reply != NULL) == (bufp != NULL));
1873
1874     if (reply) {
1875         request->nlmsg_flags |= NLM_F_ECHO;
1876     }
1877
1878     request_buf = ofpbuf_new(1024);
1879     dpif_linux_flow_to_ofpbuf(request, request_buf);
1880     error = nl_sock_transact(genl_sock, request_buf, bufp);
1881     ofpbuf_delete(request_buf);
1882
1883     if (reply) {
1884         if (!error) {
1885             error = dpif_linux_flow_from_ofpbuf(reply, *bufp);
1886         }
1887         if (error) {
1888             dpif_linux_flow_init(reply);
1889             ofpbuf_delete(*bufp);
1890             *bufp = NULL;
1891         }
1892     }
1893     return error;
1894 }
1895
1896 static void
1897 dpif_linux_flow_get_stats(const struct dpif_linux_flow *flow,
1898                           struct dpif_flow_stats *stats)
1899 {
1900     if (flow->stats) {
1901         stats->n_packets = get_unaligned_u64(&flow->stats->n_packets);
1902         stats->n_bytes = get_unaligned_u64(&flow->stats->n_bytes);
1903     } else {
1904         stats->n_packets = 0;
1905         stats->n_bytes = 0;
1906     }
1907     stats->used = flow->used ? get_32aligned_u64(flow->used) : 0;
1908     stats->tcp_flags = flow->tcp_flags ? *flow->tcp_flags : 0;
1909 }
1910 \f
1911 /* Logs information about a packet that was recently lost in 'ch' (in
1912  * 'dpif_'). */
1913 static void
1914 report_loss(struct dpif *dpif_, struct dpif_channel *ch)
1915 {
1916     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1917     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
1918     struct ds s;
1919
1920     if (VLOG_DROP_WARN(&rl)) {
1921         return;
1922     }
1923
1924     ds_init(&s);
1925     if (ch->last_poll != LLONG_MIN) {
1926         ds_put_format(&s, " (last polled %lld ms ago)",
1927                       time_msec() - ch->last_poll);
1928     }
1929
1930     VLOG_WARN("%s: lost packet on channel %td%s",
1931               dpif_name(dpif_), ch - dpif->channels, ds_cstr(&s));
1932     ds_destroy(&s);
1933 }