dpif-linux: Report dropped lost messages at WARN level.
[cascardo/ovs.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 = CONST_CAST(char *, vport.name);
599     dpif_port->type = CONST_CAST(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 = CONST_CAST(struct nlattr *, 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 = CONST_CAST(struct nlattr *,
1173                                       nl_attr_get(a[OVS_PACKET_ATTR_PACKET]));
1174     upcall->packet->size = nl_attr_get_size(a[OVS_PACKET_ATTR_PACKET]);
1175     upcall->key = CONST_CAST(struct nlattr *,
1176                              nl_attr_get(a[OVS_PACKET_ATTR_KEY]));
1177     upcall->key_len = nl_attr_get_size(a[OVS_PACKET_ATTR_KEY]);
1178     upcall->userdata = (a[OVS_PACKET_ATTR_USERDATA]
1179                         ? nl_attr_get_u64(a[OVS_PACKET_ATTR_USERDATA])
1180                         : 0);
1181     *dp_ifindex = ovs_header->dp_ifindex;
1182
1183     return 0;
1184 }
1185
1186 static int
1187 dpif_linux_recv(struct dpif *dpif_, struct dpif_upcall *upcall,
1188                 struct ofpbuf *buf)
1189 {
1190     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1191     int read_tries = 0;
1192
1193     if (dpif->epoll_fd < 0) {
1194        return EAGAIN;
1195     }
1196
1197     if (!dpif->ready_mask) {
1198         struct epoll_event events[N_CHANNELS];
1199         int retval;
1200         int i;
1201
1202         do {
1203             retval = epoll_wait(dpif->epoll_fd, events, N_CHANNELS, 0);
1204         } while (retval < 0 && errno == EINTR);
1205         if (retval < 0) {
1206             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
1207             VLOG_WARN_RL(&rl, "epoll_wait failed (%s)", strerror(errno));
1208         }
1209
1210         for (i = 0; i < retval; i++) {
1211             dpif->ready_mask |= 1u << events[i].data.u32;
1212         }
1213     }
1214
1215     while (dpif->ready_mask) {
1216         int indx = ffs(dpif->ready_mask) - 1;
1217         struct dpif_channel *ch = &dpif->channels[indx];
1218
1219         dpif->ready_mask &= ~(1u << indx);
1220
1221         for (;;) {
1222             int dp_ifindex;
1223             int error;
1224
1225             if (++read_tries > 50) {
1226                 return EAGAIN;
1227             }
1228
1229             error = nl_sock_recv(ch->sock, buf, false);
1230             if (error == ENOBUFS) {
1231                 /* ENOBUFS typically means that we've received so many
1232                  * packets that the buffer overflowed.  Try again
1233                  * immediately because there's almost certainly a packet
1234                  * waiting for us. */
1235                 report_loss(dpif_, ch);
1236                 continue;
1237             }
1238
1239             ch->last_poll = time_msec();
1240             if (error) {
1241                 if (error == EAGAIN) {
1242                     break;
1243                 }
1244                 return error;
1245             }
1246
1247             error = parse_odp_packet(buf, upcall, &dp_ifindex);
1248             if (!error && dp_ifindex == dpif->dp_ifindex) {
1249                 const struct nlattr *in_port;
1250
1251                 in_port = nl_attr_find__(upcall->key, upcall->key_len,
1252                                          OVS_KEY_ATTR_IN_PORT);
1253                 if (in_port) {
1254                     update_sketch(ch, nl_attr_get_u32(in_port));
1255                 }
1256                 return 0;
1257             }
1258             if (error) {
1259                 return error;
1260             }
1261         }
1262     }
1263
1264     return EAGAIN;
1265 }
1266
1267 static void
1268 dpif_linux_recv_wait(struct dpif *dpif_)
1269 {
1270     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1271
1272     if (dpif->epoll_fd < 0) {
1273        return;
1274     }
1275
1276     poll_fd_wait(dpif->epoll_fd, POLLIN);
1277 }
1278
1279 static void
1280 dpif_linux_recv_purge(struct dpif *dpif_)
1281 {
1282     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1283     struct dpif_channel *ch;
1284
1285     if (dpif->epoll_fd < 0) {
1286        return;
1287     }
1288
1289     for (ch = dpif->channels; ch < &dpif->channels[N_CHANNELS]; ch++) {
1290         nl_sock_drain(ch->sock);
1291     }
1292 }
1293
1294 const struct dpif_class dpif_linux_class = {
1295     "system",
1296     dpif_linux_enumerate,
1297     dpif_linux_open,
1298     dpif_linux_close,
1299     dpif_linux_destroy,
1300     dpif_linux_run,
1301     dpif_linux_wait,
1302     dpif_linux_get_stats,
1303     dpif_linux_port_add,
1304     dpif_linux_port_del,
1305     dpif_linux_port_query_by_number,
1306     dpif_linux_port_query_by_name,
1307     dpif_linux_get_max_ports,
1308     dpif_linux_port_get_pid,
1309     dpif_linux_port_dump_start,
1310     dpif_linux_port_dump_next,
1311     dpif_linux_port_dump_done,
1312     dpif_linux_port_poll,
1313     dpif_linux_port_poll_wait,
1314     dpif_linux_flow_get,
1315     dpif_linux_flow_put,
1316     dpif_linux_flow_del,
1317     dpif_linux_flow_flush,
1318     dpif_linux_flow_dump_start,
1319     dpif_linux_flow_dump_next,
1320     dpif_linux_flow_dump_done,
1321     dpif_linux_execute,
1322     dpif_linux_operate,
1323     dpif_linux_recv_set,
1324     dpif_linux_queue_to_priority,
1325     dpif_linux_recv,
1326     dpif_linux_recv_wait,
1327     dpif_linux_recv_purge,
1328 };
1329 \f
1330 static int
1331 dpif_linux_init(void)
1332 {
1333     static int error = -1;
1334
1335     if (error < 0) {
1336         unsigned int ovs_vport_mcgroup;
1337
1338         error = nl_lookup_genl_family(OVS_DATAPATH_FAMILY,
1339                                       &ovs_datapath_family);
1340         if (error) {
1341             VLOG_ERR("Generic Netlink family '%s' does not exist. "
1342                      "The Open vSwitch kernel module is probably not loaded.",
1343                      OVS_DATAPATH_FAMILY);
1344         }
1345         if (!error) {
1346             error = nl_lookup_genl_family(OVS_VPORT_FAMILY, &ovs_vport_family);
1347         }
1348         if (!error) {
1349             error = nl_lookup_genl_family(OVS_FLOW_FAMILY, &ovs_flow_family);
1350         }
1351         if (!error) {
1352             error = nl_lookup_genl_family(OVS_PACKET_FAMILY,
1353                                           &ovs_packet_family);
1354         }
1355         if (!error) {
1356             error = nl_sock_create(NETLINK_GENERIC, &genl_sock);
1357         }
1358         if (!error) {
1359             error = nl_lookup_genl_mcgroup(OVS_VPORT_FAMILY, OVS_VPORT_MCGROUP,
1360                                            &ovs_vport_mcgroup,
1361                                            OVS_VPORT_MCGROUP_FALLBACK_ID);
1362         }
1363         if (!error) {
1364             static struct dpif_linux_vport vport;
1365             nln = nln_create(NETLINK_GENERIC, ovs_vport_mcgroup,
1366                              dpif_linux_nln_parse, &vport);
1367         }
1368     }
1369
1370     return error;
1371 }
1372
1373 bool
1374 dpif_linux_is_internal_device(const char *name)
1375 {
1376     struct dpif_linux_vport reply;
1377     struct ofpbuf *buf;
1378     int error;
1379
1380     error = dpif_linux_vport_get(name, &reply, &buf);
1381     if (!error) {
1382         ofpbuf_delete(buf);
1383     } else if (error != ENODEV && error != ENOENT) {
1384         VLOG_WARN_RL(&error_rl, "%s: vport query failed (%s)",
1385                      name, strerror(error));
1386     }
1387
1388     return reply.type == OVS_VPORT_TYPE_INTERNAL;
1389 }
1390
1391 int
1392 dpif_linux_vport_send(int dp_ifindex, uint32_t port_no,
1393                       const void *data, size_t size)
1394 {
1395     struct ofpbuf actions, key, packet;
1396     struct odputil_keybuf keybuf;
1397     struct dpif_execute execute;
1398     struct flow flow;
1399     uint64_t action;
1400
1401     ofpbuf_use_const(&packet, data, size);
1402     flow_extract(&packet, 0, 0, NULL, 0, &flow);
1403
1404     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
1405     odp_flow_key_from_flow(&key, &flow);
1406
1407     ofpbuf_use_stack(&actions, &action, sizeof action);
1408     nl_msg_put_u32(&actions, OVS_ACTION_ATTR_OUTPUT, port_no);
1409
1410     execute.key = key.data;
1411     execute.key_len = key.size;
1412     execute.actions = actions.data;
1413     execute.actions_len = actions.size;
1414     execute.packet = &packet;
1415     return dpif_linux_execute__(dp_ifindex, &execute);
1416 }
1417
1418 static bool
1419 dpif_linux_nln_parse(struct ofpbuf *buf, void *vport_)
1420 {
1421     struct dpif_linux_vport *vport = vport_;
1422     return dpif_linux_vport_from_ofpbuf(vport, buf) == 0;
1423 }
1424
1425 static void
1426 dpif_linux_port_changed(const void *vport_, void *dpif_)
1427 {
1428     const struct dpif_linux_vport *vport = vport_;
1429     struct dpif_linux *dpif = dpif_;
1430
1431     if (vport) {
1432         if (vport->dp_ifindex == dpif->dp_ifindex
1433             && (vport->cmd == OVS_VPORT_CMD_NEW
1434                 || vport->cmd == OVS_VPORT_CMD_DEL
1435                 || vport->cmd == OVS_VPORT_CMD_SET)) {
1436             VLOG_DBG("port_changed: dpif:%s vport:%s cmd:%"PRIu8,
1437                      dpif->dpif.full_name, vport->name, vport->cmd);
1438             sset_add(&dpif->changed_ports, vport->name);
1439         }
1440     } else {
1441         dpif->change_error = true;
1442     }
1443 }
1444 \f
1445 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
1446  * by Netlink attributes, into 'vport'.  Returns 0 if successful, otherwise a
1447  * positive errno value.
1448  *
1449  * 'vport' will contain pointers into 'buf', so the caller should not free
1450  * 'buf' while 'vport' is still in use. */
1451 static int
1452 dpif_linux_vport_from_ofpbuf(struct dpif_linux_vport *vport,
1453                              const struct ofpbuf *buf)
1454 {
1455     static const struct nl_policy ovs_vport_policy[] = {
1456         [OVS_VPORT_ATTR_PORT_NO] = { .type = NL_A_U32 },
1457         [OVS_VPORT_ATTR_TYPE] = { .type = NL_A_U32 },
1458         [OVS_VPORT_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
1459         [OVS_VPORT_ATTR_UPCALL_PID] = { .type = NL_A_U32 },
1460         [OVS_VPORT_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_vport_stats),
1461                                    .optional = true },
1462         [OVS_VPORT_ATTR_ADDRESS] = { .type = NL_A_UNSPEC,
1463                                      .min_len = ETH_ADDR_LEN,
1464                                      .max_len = ETH_ADDR_LEN,
1465                                      .optional = true },
1466         [OVS_VPORT_ATTR_OPTIONS] = { .type = NL_A_NESTED, .optional = true },
1467     };
1468
1469     struct nlattr *a[ARRAY_SIZE(ovs_vport_policy)];
1470     struct ovs_header *ovs_header;
1471     struct nlmsghdr *nlmsg;
1472     struct genlmsghdr *genl;
1473     struct ofpbuf b;
1474
1475     dpif_linux_vport_init(vport);
1476
1477     ofpbuf_use_const(&b, buf->data, buf->size);
1478     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1479     genl = ofpbuf_try_pull(&b, sizeof *genl);
1480     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1481     if (!nlmsg || !genl || !ovs_header
1482         || nlmsg->nlmsg_type != ovs_vport_family
1483         || !nl_policy_parse(&b, 0, ovs_vport_policy, a,
1484                             ARRAY_SIZE(ovs_vport_policy))) {
1485         return EINVAL;
1486     }
1487
1488     vport->cmd = genl->cmd;
1489     vport->dp_ifindex = ovs_header->dp_ifindex;
1490     vport->port_no = nl_attr_get_u32(a[OVS_VPORT_ATTR_PORT_NO]);
1491     vport->type = nl_attr_get_u32(a[OVS_VPORT_ATTR_TYPE]);
1492     vport->name = nl_attr_get_string(a[OVS_VPORT_ATTR_NAME]);
1493     if (a[OVS_VPORT_ATTR_UPCALL_PID]) {
1494         vport->upcall_pid = nl_attr_get(a[OVS_VPORT_ATTR_UPCALL_PID]);
1495     }
1496     if (a[OVS_VPORT_ATTR_STATS]) {
1497         vport->stats = nl_attr_get(a[OVS_VPORT_ATTR_STATS]);
1498     }
1499     if (a[OVS_VPORT_ATTR_ADDRESS]) {
1500         vport->address = nl_attr_get(a[OVS_VPORT_ATTR_ADDRESS]);
1501     }
1502     if (a[OVS_VPORT_ATTR_OPTIONS]) {
1503         vport->options = nl_attr_get(a[OVS_VPORT_ATTR_OPTIONS]);
1504         vport->options_len = nl_attr_get_size(a[OVS_VPORT_ATTR_OPTIONS]);
1505     }
1506     return 0;
1507 }
1508
1509 /* Appends to 'buf' (which must initially be empty) a "struct ovs_header"
1510  * followed by Netlink attributes corresponding to 'vport'. */
1511 static void
1512 dpif_linux_vport_to_ofpbuf(const struct dpif_linux_vport *vport,
1513                            struct ofpbuf *buf)
1514 {
1515     struct ovs_header *ovs_header;
1516
1517     nl_msg_put_genlmsghdr(buf, 0, ovs_vport_family, NLM_F_REQUEST | NLM_F_ECHO,
1518                           vport->cmd, OVS_VPORT_VERSION);
1519
1520     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
1521     ovs_header->dp_ifindex = vport->dp_ifindex;
1522
1523     if (vport->port_no != UINT32_MAX) {
1524         nl_msg_put_u32(buf, OVS_VPORT_ATTR_PORT_NO, vport->port_no);
1525     }
1526
1527     if (vport->type != OVS_VPORT_TYPE_UNSPEC) {
1528         nl_msg_put_u32(buf, OVS_VPORT_ATTR_TYPE, vport->type);
1529     }
1530
1531     if (vport->name) {
1532         nl_msg_put_string(buf, OVS_VPORT_ATTR_NAME, vport->name);
1533     }
1534
1535     if (vport->upcall_pid) {
1536         nl_msg_put_u32(buf, OVS_VPORT_ATTR_UPCALL_PID, *vport->upcall_pid);
1537     }
1538
1539     if (vport->stats) {
1540         nl_msg_put_unspec(buf, OVS_VPORT_ATTR_STATS,
1541                           vport->stats, sizeof *vport->stats);
1542     }
1543
1544     if (vport->address) {
1545         nl_msg_put_unspec(buf, OVS_VPORT_ATTR_ADDRESS,
1546                           vport->address, ETH_ADDR_LEN);
1547     }
1548
1549     if (vport->options) {
1550         nl_msg_put_nested(buf, OVS_VPORT_ATTR_OPTIONS,
1551                           vport->options, vport->options_len);
1552     }
1553 }
1554
1555 /* Clears 'vport' to "empty" values. */
1556 void
1557 dpif_linux_vport_init(struct dpif_linux_vport *vport)
1558 {
1559     memset(vport, 0, sizeof *vport);
1560     vport->port_no = UINT32_MAX;
1561 }
1562
1563 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
1564  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
1565  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
1566  * result of the command is expected to be an ovs_vport also, which is decoded
1567  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
1568  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
1569 int
1570 dpif_linux_vport_transact(const struct dpif_linux_vport *request,
1571                           struct dpif_linux_vport *reply,
1572                           struct ofpbuf **bufp)
1573 {
1574     struct ofpbuf *request_buf;
1575     int error;
1576
1577     assert((reply != NULL) == (bufp != NULL));
1578
1579     error = dpif_linux_init();
1580     if (error) {
1581         if (reply) {
1582             *bufp = NULL;
1583             dpif_linux_vport_init(reply);
1584         }
1585         return error;
1586     }
1587
1588     request_buf = ofpbuf_new(1024);
1589     dpif_linux_vport_to_ofpbuf(request, request_buf);
1590     error = nl_sock_transact(genl_sock, request_buf, bufp);
1591     ofpbuf_delete(request_buf);
1592
1593     if (reply) {
1594         if (!error) {
1595             error = dpif_linux_vport_from_ofpbuf(reply, *bufp);
1596         }
1597         if (error) {
1598             dpif_linux_vport_init(reply);
1599             ofpbuf_delete(*bufp);
1600             *bufp = NULL;
1601         }
1602     }
1603     return error;
1604 }
1605
1606 /* Obtains information about the kernel vport named 'name' and stores it into
1607  * '*reply' and '*bufp'.  The caller must free '*bufp' when the reply is no
1608  * longer needed ('reply' will contain pointers into '*bufp').  */
1609 int
1610 dpif_linux_vport_get(const char *name, struct dpif_linux_vport *reply,
1611                      struct ofpbuf **bufp)
1612 {
1613     struct dpif_linux_vport request;
1614
1615     dpif_linux_vport_init(&request);
1616     request.cmd = OVS_VPORT_CMD_GET;
1617     request.name = name;
1618
1619     return dpif_linux_vport_transact(&request, reply, bufp);
1620 }
1621 \f
1622 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
1623  * by Netlink attributes, into 'dp'.  Returns 0 if successful, otherwise a
1624  * positive errno value.
1625  *
1626  * 'dp' will contain pointers into 'buf', so the caller should not free 'buf'
1627  * while 'dp' is still in use. */
1628 static int
1629 dpif_linux_dp_from_ofpbuf(struct dpif_linux_dp *dp, const struct ofpbuf *buf)
1630 {
1631     static const struct nl_policy ovs_datapath_policy[] = {
1632         [OVS_DP_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
1633         [OVS_DP_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_dp_stats),
1634                                 .optional = true },
1635     };
1636
1637     struct nlattr *a[ARRAY_SIZE(ovs_datapath_policy)];
1638     struct ovs_header *ovs_header;
1639     struct nlmsghdr *nlmsg;
1640     struct genlmsghdr *genl;
1641     struct ofpbuf b;
1642
1643     dpif_linux_dp_init(dp);
1644
1645     ofpbuf_use_const(&b, buf->data, buf->size);
1646     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1647     genl = ofpbuf_try_pull(&b, sizeof *genl);
1648     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1649     if (!nlmsg || !genl || !ovs_header
1650         || nlmsg->nlmsg_type != ovs_datapath_family
1651         || !nl_policy_parse(&b, 0, ovs_datapath_policy, a,
1652                             ARRAY_SIZE(ovs_datapath_policy))) {
1653         return EINVAL;
1654     }
1655
1656     dp->cmd = genl->cmd;
1657     dp->dp_ifindex = ovs_header->dp_ifindex;
1658     dp->name = nl_attr_get_string(a[OVS_DP_ATTR_NAME]);
1659     if (a[OVS_DP_ATTR_STATS]) {
1660         /* Can't use structure assignment because Netlink doesn't ensure
1661          * sufficient alignment for 64-bit members. */
1662         memcpy(&dp->stats, nl_attr_get(a[OVS_DP_ATTR_STATS]),
1663                sizeof dp->stats);
1664     }
1665
1666     return 0;
1667 }
1668
1669 /* Appends to 'buf' the Generic Netlink message described by 'dp'. */
1670 static void
1671 dpif_linux_dp_to_ofpbuf(const struct dpif_linux_dp *dp, struct ofpbuf *buf)
1672 {
1673     struct ovs_header *ovs_header;
1674
1675     nl_msg_put_genlmsghdr(buf, 0, ovs_datapath_family,
1676                           NLM_F_REQUEST | NLM_F_ECHO, dp->cmd,
1677                           OVS_DATAPATH_VERSION);
1678
1679     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
1680     ovs_header->dp_ifindex = dp->dp_ifindex;
1681
1682     if (dp->name) {
1683         nl_msg_put_string(buf, OVS_DP_ATTR_NAME, dp->name);
1684     }
1685
1686     if (dp->upcall_pid) {
1687         nl_msg_put_u32(buf, OVS_DP_ATTR_UPCALL_PID, *dp->upcall_pid);
1688     }
1689
1690     /* Skip OVS_DP_ATTR_STATS since we never have a reason to serialize it. */
1691 }
1692
1693 /* Clears 'dp' to "empty" values. */
1694 static void
1695 dpif_linux_dp_init(struct dpif_linux_dp *dp)
1696 {
1697     memset(dp, 0, sizeof *dp);
1698 }
1699
1700 static void
1701 dpif_linux_dp_dump_start(struct nl_dump *dump)
1702 {
1703     struct dpif_linux_dp request;
1704     struct ofpbuf *buf;
1705
1706     dpif_linux_dp_init(&request);
1707     request.cmd = OVS_DP_CMD_GET;
1708
1709     buf = ofpbuf_new(1024);
1710     dpif_linux_dp_to_ofpbuf(&request, buf);
1711     nl_dump_start(dump, genl_sock, buf);
1712     ofpbuf_delete(buf);
1713 }
1714
1715 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
1716  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
1717  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
1718  * result of the command is expected to be of the same form, which is decoded
1719  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
1720  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
1721 static int
1722 dpif_linux_dp_transact(const struct dpif_linux_dp *request,
1723                        struct dpif_linux_dp *reply, struct ofpbuf **bufp)
1724 {
1725     struct ofpbuf *request_buf;
1726     int error;
1727
1728     assert((reply != NULL) == (bufp != NULL));
1729
1730     request_buf = ofpbuf_new(1024);
1731     dpif_linux_dp_to_ofpbuf(request, request_buf);
1732     error = nl_sock_transact(genl_sock, request_buf, bufp);
1733     ofpbuf_delete(request_buf);
1734
1735     if (reply) {
1736         if (!error) {
1737             error = dpif_linux_dp_from_ofpbuf(reply, *bufp);
1738         }
1739         if (error) {
1740             dpif_linux_dp_init(reply);
1741             ofpbuf_delete(*bufp);
1742             *bufp = NULL;
1743         }
1744     }
1745     return error;
1746 }
1747
1748 /* Obtains information about 'dpif_' and stores it into '*reply' and '*bufp'.
1749  * The caller must free '*bufp' when the reply is no longer needed ('reply'
1750  * will contain pointers into '*bufp').  */
1751 static int
1752 dpif_linux_dp_get(const struct dpif *dpif_, struct dpif_linux_dp *reply,
1753                   struct ofpbuf **bufp)
1754 {
1755     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1756     struct dpif_linux_dp request;
1757
1758     dpif_linux_dp_init(&request);
1759     request.cmd = OVS_DP_CMD_GET;
1760     request.dp_ifindex = dpif->dp_ifindex;
1761
1762     return dpif_linux_dp_transact(&request, reply, bufp);
1763 }
1764 \f
1765 /* Parses the contents of 'buf', which contains a "struct ovs_header" followed
1766  * by Netlink attributes, into 'flow'.  Returns 0 if successful, otherwise a
1767  * positive errno value.
1768  *
1769  * 'flow' will contain pointers into 'buf', so the caller should not free 'buf'
1770  * while 'flow' is still in use. */
1771 static int
1772 dpif_linux_flow_from_ofpbuf(struct dpif_linux_flow *flow,
1773                             const struct ofpbuf *buf)
1774 {
1775     static const struct nl_policy ovs_flow_policy[] = {
1776         [OVS_FLOW_ATTR_KEY] = { .type = NL_A_NESTED },
1777         [OVS_FLOW_ATTR_ACTIONS] = { .type = NL_A_NESTED, .optional = true },
1778         [OVS_FLOW_ATTR_STATS] = { NL_POLICY_FOR(struct ovs_flow_stats),
1779                                   .optional = true },
1780         [OVS_FLOW_ATTR_TCP_FLAGS] = { .type = NL_A_U8, .optional = true },
1781         [OVS_FLOW_ATTR_USED] = { .type = NL_A_U64, .optional = true },
1782         /* The kernel never uses OVS_FLOW_ATTR_CLEAR. */
1783     };
1784
1785     struct nlattr *a[ARRAY_SIZE(ovs_flow_policy)];
1786     struct ovs_header *ovs_header;
1787     struct nlmsghdr *nlmsg;
1788     struct genlmsghdr *genl;
1789     struct ofpbuf b;
1790
1791     dpif_linux_flow_init(flow);
1792
1793     ofpbuf_use_const(&b, buf->data, buf->size);
1794     nlmsg = ofpbuf_try_pull(&b, sizeof *nlmsg);
1795     genl = ofpbuf_try_pull(&b, sizeof *genl);
1796     ovs_header = ofpbuf_try_pull(&b, sizeof *ovs_header);
1797     if (!nlmsg || !genl || !ovs_header
1798         || nlmsg->nlmsg_type != ovs_flow_family
1799         || !nl_policy_parse(&b, 0, ovs_flow_policy, a,
1800                             ARRAY_SIZE(ovs_flow_policy))) {
1801         return EINVAL;
1802     }
1803
1804     flow->nlmsg_flags = nlmsg->nlmsg_flags;
1805     flow->dp_ifindex = ovs_header->dp_ifindex;
1806     flow->key = nl_attr_get(a[OVS_FLOW_ATTR_KEY]);
1807     flow->key_len = nl_attr_get_size(a[OVS_FLOW_ATTR_KEY]);
1808     if (a[OVS_FLOW_ATTR_ACTIONS]) {
1809         flow->actions = nl_attr_get(a[OVS_FLOW_ATTR_ACTIONS]);
1810         flow->actions_len = nl_attr_get_size(a[OVS_FLOW_ATTR_ACTIONS]);
1811     }
1812     if (a[OVS_FLOW_ATTR_STATS]) {
1813         flow->stats = nl_attr_get(a[OVS_FLOW_ATTR_STATS]);
1814     }
1815     if (a[OVS_FLOW_ATTR_TCP_FLAGS]) {
1816         flow->tcp_flags = nl_attr_get(a[OVS_FLOW_ATTR_TCP_FLAGS]);
1817     }
1818     if (a[OVS_FLOW_ATTR_USED]) {
1819         flow->used = nl_attr_get(a[OVS_FLOW_ATTR_USED]);
1820     }
1821     return 0;
1822 }
1823
1824 /* Appends to 'buf' (which must initially be empty) a "struct ovs_header"
1825  * followed by Netlink attributes corresponding to 'flow'. */
1826 static void
1827 dpif_linux_flow_to_ofpbuf(const struct dpif_linux_flow *flow,
1828                           struct ofpbuf *buf)
1829 {
1830     struct ovs_header *ovs_header;
1831
1832     nl_msg_put_genlmsghdr(buf, 0, ovs_flow_family,
1833                           NLM_F_REQUEST | flow->nlmsg_flags,
1834                           flow->cmd, OVS_FLOW_VERSION);
1835
1836     ovs_header = ofpbuf_put_uninit(buf, sizeof *ovs_header);
1837     ovs_header->dp_ifindex = flow->dp_ifindex;
1838
1839     if (flow->key_len) {
1840         nl_msg_put_unspec(buf, OVS_FLOW_ATTR_KEY, flow->key, flow->key_len);
1841     }
1842
1843     if (flow->actions || flow->actions_len) {
1844         nl_msg_put_unspec(buf, OVS_FLOW_ATTR_ACTIONS,
1845                           flow->actions, flow->actions_len);
1846     }
1847
1848     /* We never need to send these to the kernel. */
1849     assert(!flow->stats);
1850     assert(!flow->tcp_flags);
1851     assert(!flow->used);
1852
1853     if (flow->clear) {
1854         nl_msg_put_flag(buf, OVS_FLOW_ATTR_CLEAR);
1855     }
1856 }
1857
1858 /* Clears 'flow' to "empty" values. */
1859 static void
1860 dpif_linux_flow_init(struct dpif_linux_flow *flow)
1861 {
1862     memset(flow, 0, sizeof *flow);
1863 }
1864
1865 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
1866  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
1867  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
1868  * result of the command is expected to be a flow also, which is decoded and
1869  * stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the reply
1870  * is no longer needed ('reply' will contain pointers into '*bufp'). */
1871 static int
1872 dpif_linux_flow_transact(struct dpif_linux_flow *request,
1873                          struct dpif_linux_flow *reply, struct ofpbuf **bufp)
1874 {
1875     struct ofpbuf *request_buf;
1876     int error;
1877
1878     assert((reply != NULL) == (bufp != NULL));
1879
1880     if (reply) {
1881         request->nlmsg_flags |= NLM_F_ECHO;
1882     }
1883
1884     request_buf = ofpbuf_new(1024);
1885     dpif_linux_flow_to_ofpbuf(request, request_buf);
1886     error = nl_sock_transact(genl_sock, request_buf, bufp);
1887     ofpbuf_delete(request_buf);
1888
1889     if (reply) {
1890         if (!error) {
1891             error = dpif_linux_flow_from_ofpbuf(reply, *bufp);
1892         }
1893         if (error) {
1894             dpif_linux_flow_init(reply);
1895             ofpbuf_delete(*bufp);
1896             *bufp = NULL;
1897         }
1898     }
1899     return error;
1900 }
1901
1902 static void
1903 dpif_linux_flow_get_stats(const struct dpif_linux_flow *flow,
1904                           struct dpif_flow_stats *stats)
1905 {
1906     if (flow->stats) {
1907         stats->n_packets = get_unaligned_u64(&flow->stats->n_packets);
1908         stats->n_bytes = get_unaligned_u64(&flow->stats->n_bytes);
1909     } else {
1910         stats->n_packets = 0;
1911         stats->n_bytes = 0;
1912     }
1913     stats->used = flow->used ? get_32aligned_u64(flow->used) : 0;
1914     stats->tcp_flags = flow->tcp_flags ? *flow->tcp_flags : 0;
1915 }
1916 \f
1917 /* Metwally "space-saving" algorithm implementation. */
1918
1919 /* Updates 'ch' to record that a packet was received on 'port_no'. */
1920 static void
1921 update_sketch(struct dpif_channel *ch, uint32_t port_no)
1922 {
1923     struct dpif_sketch *sk;
1924
1925     /* Find an existing counting element for 'port_no' or, if none, replace the
1926      * counting element with the fewest hits by 'port_no'. */
1927     for (sk = ch->sketches; ; sk++) {
1928         if (port_no == sk->port_no) {
1929             break;
1930         } else if (sk == &ch->sketches[N_SKETCHES - 1]) {
1931             sk->port_no = port_no;
1932             sk->error = sk->hits;
1933             break;
1934         }
1935     }
1936
1937     /* Increment the hit count, then re-sort the counting elements (usually
1938      * nothing needs to be done). */
1939     sk->hits++;
1940     while (sk > ch->sketches && sk[-1].hits > sk->hits) {
1941         struct dpif_sketch tmp = sk[-1];
1942         sk[-1] = *sk;
1943         *sk = tmp;
1944         sk--;
1945     }
1946 }
1947
1948 /* Divide the counts of all the the counting elements in 'dpif' by 2.  See the
1949  * comment on SCALE_INTERVAL. */
1950 static void
1951 scale_sketches(struct dpif *dpif_)
1952 {
1953     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1954     struct dpif_channel *ch;
1955
1956     for (ch = dpif->channels; ch < &dpif->channels[N_CHANNELS]; ch++) {
1957         struct dpif_sketch *sk;
1958
1959         for (sk = ch->sketches; sk < &ch->sketches[N_SKETCHES]; sk++) {
1960             sk->hits /= 2;
1961             sk->error /= 2;
1962         }
1963     }
1964 }
1965
1966 /* Logs information about a packet that was recently lost in 'ch' (in
1967  * 'dpif_'). */
1968 static void
1969 report_loss(struct dpif *dpif_, struct dpif_channel *ch)
1970 {
1971     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
1972     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
1973     struct dpif_sketch *sk;
1974     struct ds s;
1975
1976     if (VLOG_DROP_WARN(&rl)) {
1977         return;
1978     }
1979
1980     ds_init(&s);
1981     if (ch->last_poll != LLONG_MIN) {
1982         ds_put_format(&s, " (last polled %lld ms ago)",
1983                       time_msec() - ch->last_poll);
1984     }
1985     ds_put_cstr(&s, ", most frequent sources are");
1986     for (sk = ch->sketches; sk < &ch->sketches[N_SKETCHES]; sk++) {
1987         if (sk->hits) {
1988             struct dpif_port port;
1989
1990             ds_put_format(&s, " %"PRIu32, sk->port_no);
1991             if (!dpif_port_query_by_number(dpif_, sk->port_no, &port)) {
1992                 ds_put_format(&s, "(%s)", port.name);
1993                 dpif_port_destroy(&port);
1994             }
1995             if (sk->error) {
1996                 ds_put_format(&s, ": %u to %u,",
1997                               sk->hits - sk->error, sk->hits);
1998             } else {
1999                 ds_put_format(&s, ": %u,", sk->hits);
2000             }
2001         }
2002     }
2003     ds_chomp(&s, ',');
2004
2005     VLOG_WARN("%s: lost packet on channel %td%s",
2006               dpif_name(dpif_), ch - dpif->channels, ds_cstr(&s));
2007     ds_destroy(&s);
2008 }