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