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