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