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