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