datapath: Convert ODP_FLOW_* and ODP_EXECUTE to put dp_idx into message.
[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/ethtool.h>
29 #include <linux/pkt_sched.h>
30 #include <linux/rtnetlink.h>
31 #include <linux/sockios.h>
32 #include <stdlib.h>
33 #include <sys/ioctl.h>
34 #include <sys/stat.h>
35 #include <unistd.h>
36
37 #include "dpif-provider.h"
38 #include "netdev.h"
39 #include "netdev-vport.h"
40 #include "netlink.h"
41 #include "odp-util.h"
42 #include "ofpbuf.h"
43 #include "openvswitch/tunnel.h"
44 #include "packets.h"
45 #include "poll-loop.h"
46 #include "rtnetlink.h"
47 #include "rtnetlink-link.h"
48 #include "shash.h"
49 #include "svec.h"
50 #include "util.h"
51 #include "vlog.h"
52
53 VLOG_DEFINE_THIS_MODULE(dpif_linux);
54
55 /* Datapath interface for the openvswitch Linux kernel module. */
56 struct dpif_linux {
57     struct dpif dpif;
58     int fd;
59
60     /* Used by dpif_linux_get_all_names(). */
61     char *local_ifname;
62     int minor;
63
64     /* Change notification. */
65     int local_ifindex;          /* Ifindex of local port. */
66     struct shash changed_ports;  /* Ports that have changed. */
67     struct rtnetlink_notifier port_notifier;
68     bool change_error;
69 };
70
71 static struct vlog_rate_limit error_rl = VLOG_RATE_LIMIT_INIT(9999, 5);
72
73 static int do_ioctl(const struct dpif *, int cmd, const void *arg);
74 static int open_dpif(const struct dpif_linux_vport *local_vport,
75                      struct dpif **);
76 static int get_openvswitch_major(void);
77 static int create_minor(const char *name, int minor);
78 static int open_minor(int minor, int *fdp);
79 static int make_openvswitch_device(int minor, char **fnp);
80 static void dpif_linux_port_changed(const struct rtnetlink_link_change *,
81                                     void *dpif);
82
83 static struct dpif_linux *
84 dpif_linux_cast(const struct dpif *dpif)
85 {
86     dpif_assert_class(dpif, &dpif_linux_class);
87     return CONTAINER_OF(dpif, struct dpif_linux, dpif);
88 }
89
90 static int
91 dpif_linux_enumerate(struct svec *all_dps)
92 {
93     int major;
94     int error;
95     int i;
96
97     /* Check that the Open vSwitch module is loaded. */
98     major = get_openvswitch_major();
99     if (major < 0) {
100         return -major;
101     }
102
103     error = 0;
104     for (i = 0; i < ODP_MAX; i++) {
105         struct dpif *dpif;
106         char devname[16];
107         int retval;
108
109         sprintf(devname, "dp%d", i);
110         retval = dpif_open(devname, "system", &dpif);
111         if (!retval) {
112             svec_add(all_dps, devname);
113             dpif_uninit(dpif, true);
114         } else if (retval != ENODEV && !error) {
115             error = retval;
116         }
117     }
118     return error;
119 }
120
121 static int
122 dpif_linux_open(const struct dpif_class *class OVS_UNUSED, const char *name,
123                 bool create, struct dpif **dpifp)
124 {
125     struct dpif_linux_vport request, reply;
126     struct ofpbuf *buf;
127     int minor;
128     int error;
129
130     minor = !strncmp(name, "dp", 2)
131             && isdigit((unsigned char)name[2]) ? atoi(name + 2) : -1;
132     if (create) {
133         if (minor >= 0) {
134             error = create_minor(name, minor);
135             if (error) {
136                 return error;
137             }
138         } else {
139             /* Scan for unused minor number. */
140             for (minor = 0; ; minor++) {
141                 if (minor >= ODP_MAX) {
142                     /* All datapath numbers in use. */
143                     return ENOBUFS;
144                 }
145
146                 error = create_minor(name, minor);
147                 if (!error) {
148                     break;
149                 } else if (error != EBUSY) {
150                     return error;
151                 }
152             }
153         }
154     }
155
156     dpif_linux_vport_init(&request);
157     request.cmd = ODP_VPORT_GET;
158     request.port_no = ODPP_LOCAL;
159     if (minor >= 0) {
160         request.dp_idx = minor;
161     } else {
162         request.name = name;
163     }
164
165     error = dpif_linux_vport_transact(&request, &reply, &buf);
166     if (error) {
167         return error;
168     } else if (reply.port_no != ODPP_LOCAL) {
169         /* This is an Open vSwitch device but not the local port.  We
170          * intentionally support only using the name of the local port as the
171          * name of a datapath; otherwise, it would be too difficult to
172          * enumerate all the names of a datapath. */
173         error = EOPNOTSUPP;
174     } else {
175         error = open_dpif(&reply, dpifp);
176     }
177
178     ofpbuf_delete(buf);
179     return error;
180 }
181
182 static int
183 open_dpif(const struct dpif_linux_vport *local_vport, struct dpif **dpifp)
184 {
185     int dp_idx = local_vport->dp_idx;
186     struct dpif_linux *dpif;
187     char *name;
188     int error;
189     int fd;
190
191     error = open_minor(dp_idx, &fd);
192     if (error) {
193         goto error;
194     }
195
196     dpif = xmalloc(sizeof *dpif);
197     error = rtnetlink_link_notifier_register(&dpif->port_notifier,
198                                              dpif_linux_port_changed, dpif);
199     if (error) {
200         goto error_free;
201     }
202
203     name = xasprintf("dp%d", dp_idx);
204     dpif_init(&dpif->dpif, &dpif_linux_class, name, dp_idx, dp_idx);
205     free(name);
206
207     dpif->fd = fd;
208     dpif->local_ifname = xstrdup(local_vport->name);
209     dpif->local_ifindex = local_vport->ifindex;
210     dpif->minor = dp_idx;
211     shash_init(&dpif->changed_ports);
212     dpif->change_error = false;
213     *dpifp = &dpif->dpif;
214
215     return 0;
216
217 error_free:
218     free(dpif);
219     close(fd);
220 error:
221     return error;
222 }
223
224 static void
225 dpif_linux_close(struct dpif *dpif_)
226 {
227     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
228     rtnetlink_link_notifier_unregister(&dpif->port_notifier);
229     shash_destroy(&dpif->changed_ports);
230     free(dpif->local_ifname);
231     close(dpif->fd);
232     free(dpif);
233 }
234
235 static int
236 dpif_linux_get_all_names(const struct dpif *dpif_, struct svec *all_names)
237 {
238     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
239
240     svec_add_nocopy(all_names, xasprintf("dp%d", dpif->minor));
241     svec_add(all_names, dpif->local_ifname);
242     return 0;
243 }
244
245 static int
246 dpif_linux_destroy(struct dpif *dpif_)
247 {
248     return do_ioctl(dpif_, ODP_DP_DESTROY, NULL);
249 }
250
251 static int
252 dpif_linux_get_stats(const struct dpif *dpif_, struct odp_stats *stats)
253 {
254     memset(stats, 0, sizeof *stats);
255     return do_ioctl(dpif_, ODP_DP_STATS, stats);
256 }
257
258 static int
259 dpif_linux_get_drop_frags(const struct dpif *dpif_, bool *drop_fragsp)
260 {
261     int drop_frags;
262     int error;
263
264     error = do_ioctl(dpif_, ODP_GET_DROP_FRAGS, &drop_frags);
265     if (!error) {
266         *drop_fragsp = drop_frags & 1;
267     }
268     return error;
269 }
270
271 static int
272 dpif_linux_set_drop_frags(struct dpif *dpif_, bool drop_frags)
273 {
274     int drop_frags_int = drop_frags;
275     return do_ioctl(dpif_, ODP_SET_DROP_FRAGS, &drop_frags_int);
276 }
277
278 static int
279 dpif_linux_port_add(struct dpif *dpif_, struct netdev *netdev,
280                     uint16_t *port_nop)
281 {
282     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
283     const char *name = netdev_get_name(netdev);
284     const char *type = netdev_get_type(netdev);
285     struct dpif_linux_vport request, reply;
286     const struct ofpbuf *options;
287     struct ofpbuf *buf;
288     int error;
289
290     dpif_linux_vport_init(&request);
291     request.cmd = ODP_VPORT_NEW;
292     request.dp_idx = dpif->minor;
293     request.type = netdev_vport_get_vport_type(netdev);
294     if (request.type == ODP_VPORT_TYPE_UNSPEC) {
295         VLOG_WARN_RL(&error_rl, "%s: cannot create port `%s' because it has "
296                      "unsupported type `%s'",
297                      dpif_name(dpif_), name, type);
298         return EINVAL;
299     }
300     request.name = name;
301
302     options = netdev_vport_get_options(netdev);
303     if (options && options->size) {
304         request.options = options->data;
305         request.options_len = options->size;
306     }
307
308     error = dpif_linux_vport_transact(&request, &reply, &buf);
309     if (!error) {
310         *port_nop = reply.port_no;
311         ofpbuf_delete(buf);
312     }
313
314     return error;
315 }
316
317 static int
318 dpif_linux_port_del(struct dpif *dpif_, uint16_t port_no)
319 {
320     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
321     struct dpif_linux_vport vport;
322
323     dpif_linux_vport_init(&vport);
324     vport.cmd = ODP_VPORT_DEL;
325     vport.dp_idx = dpif->minor;
326     vport.port_no = port_no;
327     return dpif_linux_vport_transact(&vport, NULL, NULL);
328 }
329
330 static int
331 dpif_linux_port_query__(const struct dpif *dpif, uint32_t port_no,
332                         const char *port_name, struct dpif_port *dpif_port)
333 {
334     struct dpif_linux_vport request;
335     struct dpif_linux_vport reply;
336     struct ofpbuf *buf;
337     int error;
338
339     dpif_linux_vport_init(&request);
340     request.cmd = ODP_VPORT_GET;
341     request.dp_idx = dpif_linux_cast(dpif)->minor;
342     request.port_no = port_no;
343     request.name = port_name;
344
345     error = dpif_linux_vport_transact(&request, &reply, &buf);
346     if (!error) {
347         dpif_port->name = xstrdup(reply.name);
348         dpif_port->type = xstrdup(netdev_vport_get_netdev_type(&reply));
349         dpif_port->port_no = reply.port_no;
350         ofpbuf_delete(buf);
351     }
352     return error;
353 }
354
355 static int
356 dpif_linux_port_query_by_number(const struct dpif *dpif, uint16_t port_no,
357                                 struct dpif_port *dpif_port)
358 {
359     return dpif_linux_port_query__(dpif, port_no, NULL, dpif_port);
360 }
361
362 static int
363 dpif_linux_port_query_by_name(const struct dpif *dpif, const char *devname,
364                               struct dpif_port *dpif_port)
365 {
366     return dpif_linux_port_query__(dpif, 0, devname, dpif_port);
367 }
368
369 static int
370 dpif_linux_get_max_ports(const struct dpif *dpif OVS_UNUSED)
371 {
372     /* If the datapath increases its range of supported ports, then it should
373      * start reporting that. */
374     return 1024;
375 }
376
377 static int
378 dpif_linux_flow_flush(struct dpif *dpif_)
379 {
380     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
381     return ioctl(dpif->fd, ODP_FLOW_FLUSH, dpif->minor) ? errno : 0;
382 }
383
384 struct dpif_linux_port_state {
385     struct ofpbuf *buf;
386     uint32_t next;
387 };
388
389 static int
390 dpif_linux_port_dump_start(const struct dpif *dpif OVS_UNUSED, void **statep)
391 {
392     *statep = xzalloc(sizeof(struct dpif_linux_port_state));
393     return 0;
394 }
395
396 static int
397 dpif_linux_port_dump_next(const struct dpif *dpif, void *state_,
398                           struct dpif_port *dpif_port)
399 {
400     struct dpif_linux_port_state *state = state_;
401     struct dpif_linux_vport request, reply;
402     struct ofpbuf *buf;
403     int error;
404
405     ofpbuf_delete(state->buf);
406     state->buf = NULL;
407
408     dpif_linux_vport_init(&request);
409     request.cmd = ODP_VPORT_DUMP;
410     request.dp_idx = dpif_linux_cast(dpif)->minor;
411     request.port_no = state->next;
412     error = dpif_linux_vport_transact(&request, &reply, &buf);
413     if (error) {
414         return error == ENODEV ? EOF : error;
415     } else {
416         dpif_port->name = (char *) reply.name;
417         dpif_port->type = (char *) netdev_vport_get_netdev_type(&reply);
418         dpif_port->port_no = reply.port_no;
419         state->buf = buf;
420         state->next = reply.port_no + 1;
421         return 0;
422     }
423 }
424
425 static int
426 dpif_linux_port_dump_done(const struct dpif *dpif OVS_UNUSED, void *state_)
427 {
428     struct dpif_linux_port_state *state = state_;
429     ofpbuf_delete(state->buf);
430     free(state);
431     return 0;
432 }
433
434 static int
435 dpif_linux_port_poll(const struct dpif *dpif_, char **devnamep)
436 {
437     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
438
439     if (dpif->change_error) {
440         dpif->change_error = false;
441         shash_clear(&dpif->changed_ports);
442         return ENOBUFS;
443     } else if (!shash_is_empty(&dpif->changed_ports)) {
444         struct shash_node *node = shash_first(&dpif->changed_ports);
445         *devnamep = shash_steal(&dpif->changed_ports, node);
446         return 0;
447     } else {
448         return EAGAIN;
449     }
450 }
451
452 static void
453 dpif_linux_port_poll_wait(const struct dpif *dpif_)
454 {
455     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
456     if (!shash_is_empty(&dpif->changed_ports) || dpif->change_error) {
457         poll_immediate_wake();
458     } else {
459         rtnetlink_link_notifier_wait();
460     }
461 }
462
463 static void
464 odp_flow_stats_to_dpif_flow_stats(const struct odp_flow_stats *ofs,
465                                   struct dpif_flow_stats *dfs)
466 {
467     dfs->n_packets = ofs->n_packets;
468     dfs->n_bytes = ofs->n_bytes;
469     dfs->used = ofs->used_sec * 1000 + ofs->used_nsec / 1000000;
470     dfs->tcp_flags = ofs->tcp_flags;
471 }
472
473 static int
474 dpif_linux_flow_get(const struct dpif *dpif_,
475                     const struct nlattr *key, size_t key_len,
476                     struct ofpbuf **actionsp, struct dpif_flow_stats *stats)
477 {
478     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
479     struct ofpbuf *actions = NULL;
480     struct odp_flow odp_flow;
481     int error;
482
483     memset(&odp_flow, 0, sizeof odp_flow);
484     odp_flow.dp_idx = dpif->minor;
485     odp_flow.key = (struct nlattr *) key;
486     odp_flow.key_len = key_len;
487     if (actionsp) {
488         actions = *actionsp = ofpbuf_new(65536);
489         odp_flow.actions = actions->base;
490         odp_flow.actions_len = actions->allocated;
491     }
492
493     error = do_ioctl(dpif_, ODP_FLOW_GET, &odp_flow);
494     if (!error) {
495         if (stats) {
496             odp_flow_stats_to_dpif_flow_stats(&odp_flow.stats, stats);
497         }
498         if (actions) {
499             actions->size = odp_flow.actions_len;
500             ofpbuf_trim(actions);
501         }
502     } else {
503         if (actions) {
504             ofpbuf_delete(actions);
505         }
506     }
507     return error;
508 }
509
510 static int
511 dpif_linux_flow_put(struct dpif *dpif_, enum dpif_flow_put_flags flags,
512                     const struct nlattr *key, size_t key_len,
513                     const struct nlattr *actions, size_t actions_len,
514                     struct dpif_flow_stats *stats)
515 {
516     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
517     struct odp_flow_put put;
518     int error;
519
520     memset(&put, 0, sizeof put);
521     put.flow.dp_idx = dpif->minor;
522     put.flow.key = (struct nlattr *) key;
523     put.flow.key_len = key_len;
524     put.flow.actions = (struct nlattr *) actions;
525     put.flow.actions_len = actions_len;
526     put.flags = 0;
527     if (flags & DPIF_FP_CREATE) {
528         put.flags |= ODPPF_CREATE;
529     }
530     if (flags & DPIF_FP_MODIFY) {
531         put.flags |= ODPPF_MODIFY;
532     }
533     if (flags & DPIF_FP_ZERO_STATS) {
534         put.flags |= ODPPF_ZERO_STATS;
535     }
536     error = do_ioctl(dpif_, ODP_FLOW_PUT, &put);
537     if (!error && stats) {
538         odp_flow_stats_to_dpif_flow_stats(&put.flow.stats, stats);
539     }
540     return error;
541 }
542
543 static int
544 dpif_linux_flow_del(struct dpif *dpif_,
545                     const struct nlattr *key, size_t key_len,
546                     struct dpif_flow_stats *stats)
547 {
548     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
549     struct odp_flow odp_flow;
550     int error;
551
552     memset(&odp_flow, 0, sizeof odp_flow);
553     odp_flow.dp_idx = dpif->minor;
554     odp_flow.key = (struct nlattr *) key;
555     odp_flow.key_len = key_len;
556     error = do_ioctl(dpif_, ODP_FLOW_DEL, &odp_flow);
557     if (!error && stats) {
558         odp_flow_stats_to_dpif_flow_stats(&odp_flow.stats, stats);
559     }
560     return error;
561 }
562
563 struct dpif_linux_flow_state {
564     struct odp_flow_dump dump;
565     struct odp_flow flow;
566     uint32_t keybuf[ODPUTIL_FLOW_KEY_U32S];
567     uint32_t actionsbuf[65536 / sizeof(uint32_t)];
568     struct dpif_flow_stats stats;
569 };
570
571 static int
572 dpif_linux_flow_dump_start(const struct dpif *dpif_, void **statep)
573 {
574     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
575     struct dpif_linux_flow_state *state;
576
577     *statep = state = xmalloc(sizeof *state);
578     state->dump.dp_idx = dpif->minor;
579     state->dump.state[0] = 0;
580     state->dump.state[1] = 0;
581     state->dump.flow = &state->flow;
582     return 0;
583 }
584
585 static int
586 dpif_linux_flow_dump_next(const struct dpif *dpif, void *state_,
587                           const struct nlattr **key, size_t *key_len,
588                           const struct nlattr **actions, size_t *actions_len,
589                           const struct dpif_flow_stats **stats)
590 {
591     struct dpif_linux_flow_state *state = state_;
592     int error;
593
594     memset(&state->flow, 0, sizeof state->flow);
595     state->flow.key = (struct nlattr *) state->keybuf;
596     state->flow.key_len = sizeof state->keybuf;
597     if (actions) {
598         state->flow.actions = (struct nlattr *) state->actionsbuf;
599         state->flow.actions_len = sizeof state->actionsbuf;
600     }
601
602     error = do_ioctl(dpif, ODP_FLOW_DUMP, &state->dump);
603     if (!error) {
604         if (!state->flow.key_len) {
605             return EOF;
606         }
607         if (key) {
608             *key = (const struct nlattr *) state->keybuf;
609             *key_len = state->flow.key_len;
610         }
611         if (actions) {
612             *actions = (const struct nlattr *) state->actionsbuf;
613             *actions_len = state->flow.actions_len;
614         }
615         if (stats) {
616             odp_flow_stats_to_dpif_flow_stats(&state->flow.stats,
617                                               &state->stats);
618             *stats = &state->stats;
619         }
620     }
621     return error;
622 }
623
624 static int
625 dpif_linux_flow_dump_done(const struct dpif *dpif OVS_UNUSED, void *state)
626 {
627     free(state);
628     return 0;
629 }
630
631 static int
632 dpif_linux_execute(struct dpif *dpif_,
633                    const struct nlattr *actions, size_t actions_len,
634                    const struct ofpbuf *buf)
635 {
636     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
637     struct odp_execute execute;
638
639     memset(&execute, 0, sizeof execute);
640     execute.dp_idx = dpif->minor;
641     execute.actions = (struct nlattr *) actions;
642     execute.actions_len = actions_len;
643     execute.data = buf->data;
644     execute.length = buf->size;
645     return do_ioctl(dpif_, ODP_EXECUTE, &execute);
646 }
647
648 static int
649 dpif_linux_recv_get_mask(const struct dpif *dpif_, int *listen_mask)
650 {
651     return do_ioctl(dpif_, ODP_GET_LISTEN_MASK, listen_mask);
652 }
653
654 static int
655 dpif_linux_recv_set_mask(struct dpif *dpif_, int listen_mask)
656 {
657     return do_ioctl(dpif_, ODP_SET_LISTEN_MASK, &listen_mask);
658 }
659
660 static int
661 dpif_linux_get_sflow_probability(const struct dpif *dpif_,
662                                  uint32_t *probability)
663 {
664     return do_ioctl(dpif_, ODP_GET_SFLOW_PROBABILITY, probability);
665 }
666
667 static int
668 dpif_linux_set_sflow_probability(struct dpif *dpif_, uint32_t probability)
669 {
670     return do_ioctl(dpif_, ODP_SET_SFLOW_PROBABILITY, &probability);
671 }
672
673 static int
674 dpif_linux_queue_to_priority(const struct dpif *dpif OVS_UNUSED,
675                              uint32_t queue_id, uint32_t *priority)
676 {
677     if (queue_id < 0xf000) {
678         *priority = TC_H_MAKE(1 << 16, queue_id + 1);
679         return 0;
680     } else {
681         return EINVAL;
682     }
683 }
684
685 static int
686 parse_odp_packet(struct ofpbuf *buf, struct dpif_upcall *upcall)
687 {
688     static const struct nl_policy odp_packet_policy[] = {
689         /* Always present. */
690         [ODP_PACKET_ATTR_TYPE] = { .type = NL_A_U32 },
691         [ODP_PACKET_ATTR_PACKET] = { .type = NL_A_UNSPEC,
692                                      .min_len = ETH_HEADER_LEN },
693         [ODP_PACKET_ATTR_KEY] = { .type = NL_A_NESTED },
694
695         /* _ODPL_ACTION_NR only. */
696         [ODP_PACKET_ATTR_USERDATA] = { .type = NL_A_U64, .optional = true },
697
698         /* _ODPL_SFLOW_NR only. */
699         [ODP_PACKET_ATTR_SAMPLE_POOL] = { .type = NL_A_U32, .optional = true },
700         [ODP_PACKET_ATTR_ACTIONS] = { .type = NL_A_NESTED, .optional = true },
701     };
702
703     struct odp_packet *odp_packet = buf->data;
704     struct nlattr *a[ARRAY_SIZE(odp_packet_policy)];
705
706     if (!nl_policy_parse(buf, sizeof *odp_packet, odp_packet_policy,
707                          a, ARRAY_SIZE(odp_packet_policy))) {
708         return EINVAL;
709     }
710
711     memset(upcall, 0, sizeof *upcall);
712     upcall->type = nl_attr_get_u32(a[ODP_PACKET_ATTR_TYPE]);
713     upcall->packet = buf;
714     upcall->packet->data = (void *) nl_attr_get(a[ODP_PACKET_ATTR_PACKET]);
715     upcall->packet->size = nl_attr_get_size(a[ODP_PACKET_ATTR_PACKET]);
716     upcall->key = (void *) nl_attr_get(a[ODP_PACKET_ATTR_KEY]);
717     upcall->key_len = nl_attr_get_size(a[ODP_PACKET_ATTR_KEY]);
718     upcall->userdata = (a[ODP_PACKET_ATTR_USERDATA]
719                         ? nl_attr_get_u64(a[ODP_PACKET_ATTR_USERDATA])
720                         : 0);
721     upcall->sample_pool = (a[ODP_PACKET_ATTR_SAMPLE_POOL]
722                         ? nl_attr_get_u32(a[ODP_PACKET_ATTR_SAMPLE_POOL])
723                            : 0);
724     if (a[ODP_PACKET_ATTR_ACTIONS]) {
725         upcall->actions = (void *) nl_attr_get(a[ODP_PACKET_ATTR_ACTIONS]);
726         upcall->actions_len = nl_attr_get_size(a[ODP_PACKET_ATTR_ACTIONS]);
727     }
728
729     return 0;
730 }
731
732 static int
733 dpif_linux_recv(struct dpif *dpif_, struct dpif_upcall *upcall)
734 {
735     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
736     struct ofpbuf *buf;
737     int retval;
738     int error;
739
740     buf = ofpbuf_new(65536);
741     retval = read(dpif->fd, ofpbuf_tail(buf), ofpbuf_tailroom(buf));
742     if (retval < 0) {
743         error = errno;
744         if (error != EAGAIN) {
745             VLOG_WARN_RL(&error_rl, "%s: read failed: %s",
746                          dpif_name(dpif_), strerror(error));
747         }
748     } else if (retval >= sizeof(struct odp_packet)) {
749         struct odp_packet *odp_packet = buf->data;
750         buf->size += retval;
751
752         if (odp_packet->len <= retval) {
753             error = parse_odp_packet(buf, upcall);
754         } else {
755             VLOG_WARN_RL(&error_rl, "%s: discarding message truncated "
756                          "from %"PRIu32" bytes to %d",
757                          dpif_name(dpif_), odp_packet->len, retval);
758             error = ERANGE;
759         }
760     } else if (!retval) {
761         VLOG_WARN_RL(&error_rl, "%s: unexpected end of file", dpif_name(dpif_));
762         error = EPROTO;
763     } else {
764         VLOG_WARN_RL(&error_rl, "%s: discarding too-short message (%d bytes)",
765                      dpif_name(dpif_), retval);
766         error = ERANGE;
767     }
768
769     if (error) {
770         ofpbuf_delete(buf);
771     }
772     return error;
773 }
774
775 static void
776 dpif_linux_recv_wait(struct dpif *dpif_)
777 {
778     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
779     poll_fd_wait(dpif->fd, POLLIN);
780 }
781
782 static void
783 dpif_linux_recv_purge(struct dpif *dpif_)
784 {
785     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
786     int i;
787
788     /* This is somewhat bogus because it assumes that the following macros have
789      * fixed values, but it's going to go away later.  */
790 #define DP_N_QUEUES 3
791 #define DP_MAX_QUEUE_LEN 100
792     for (i = 0; i < DP_N_QUEUES * DP_MAX_QUEUE_LEN; i++) {
793         /* Reading even 1 byte discards a whole datagram and saves time. */
794         char buffer;
795
796         if (read(dpif->fd, &buffer, 1) != 1) {
797             break;
798         }
799     }
800 }
801
802 const struct dpif_class dpif_linux_class = {
803     "system",
804     NULL,
805     NULL,
806     dpif_linux_enumerate,
807     dpif_linux_open,
808     dpif_linux_close,
809     dpif_linux_get_all_names,
810     dpif_linux_destroy,
811     dpif_linux_get_stats,
812     dpif_linux_get_drop_frags,
813     dpif_linux_set_drop_frags,
814     dpif_linux_port_add,
815     dpif_linux_port_del,
816     dpif_linux_port_query_by_number,
817     dpif_linux_port_query_by_name,
818     dpif_linux_get_max_ports,
819     dpif_linux_port_dump_start,
820     dpif_linux_port_dump_next,
821     dpif_linux_port_dump_done,
822     dpif_linux_port_poll,
823     dpif_linux_port_poll_wait,
824     dpif_linux_flow_get,
825     dpif_linux_flow_put,
826     dpif_linux_flow_del,
827     dpif_linux_flow_flush,
828     dpif_linux_flow_dump_start,
829     dpif_linux_flow_dump_next,
830     dpif_linux_flow_dump_done,
831     dpif_linux_execute,
832     dpif_linux_recv_get_mask,
833     dpif_linux_recv_set_mask,
834     dpif_linux_get_sflow_probability,
835     dpif_linux_set_sflow_probability,
836     dpif_linux_queue_to_priority,
837     dpif_linux_recv,
838     dpif_linux_recv_wait,
839     dpif_linux_recv_purge,
840 };
841 \f
842 static int get_openvswitch_major(void);
843 static int get_major(const char *target);
844
845 static int
846 do_ioctl(const struct dpif *dpif_, int cmd, const void *arg)
847 {
848     struct dpif_linux *dpif = dpif_linux_cast(dpif_);
849     return ioctl(dpif->fd, cmd, arg) ? errno : 0;
850 }
851
852 bool
853 dpif_linux_is_internal_device(const char *name)
854 {
855     struct dpif_linux_vport reply;
856     struct ofpbuf *buf;
857     int error;
858
859     error = dpif_linux_vport_get(name, &reply, &buf);
860     if (!error) {
861         ofpbuf_delete(buf);
862     } else if (error != ENODEV) {
863         VLOG_WARN_RL(&error_rl, "%s: vport query failed (%s)",
864                      name, strerror(error));
865     }
866
867     return reply.type == ODP_VPORT_TYPE_INTERNAL;
868 }
869
870 static int
871 make_openvswitch_device(int minor, char **fnp)
872 {
873     const char dirname[] = "/dev/net";
874     int major;
875     dev_t dev;
876     struct stat s;
877     char fn[128];
878
879     *fnp = NULL;
880
881     major = get_openvswitch_major();
882     if (major < 0) {
883         return -major;
884     }
885     dev = makedev(major, minor);
886
887     sprintf(fn, "%s/dp%d", dirname, minor);
888     if (!stat(fn, &s)) {
889         if (!S_ISCHR(s.st_mode)) {
890             VLOG_WARN_RL(&error_rl, "%s is not a character device, fixing",
891                          fn);
892         } else if (s.st_rdev != dev) {
893             VLOG_WARN_RL(&error_rl,
894                          "%s is device %u:%u but should be %u:%u, fixing",
895                          fn, major(s.st_rdev), minor(s.st_rdev),
896                          major(dev), minor(dev));
897         } else {
898             goto success;
899         }
900         if (unlink(fn)) {
901             VLOG_WARN_RL(&error_rl, "%s: unlink failed (%s)",
902                          fn, strerror(errno));
903             return errno;
904         }
905     } else if (errno == ENOENT) {
906         if (stat(dirname, &s)) {
907             if (errno == ENOENT) {
908                 if (mkdir(dirname, 0755)) {
909                     VLOG_WARN_RL(&error_rl, "%s: mkdir failed (%s)",
910                                  dirname, strerror(errno));
911                     return errno;
912                 }
913             } else {
914                 VLOG_WARN_RL(&error_rl, "%s: stat failed (%s)",
915                              dirname, strerror(errno));
916                 return errno;
917             }
918         }
919     } else {
920         VLOG_WARN_RL(&error_rl, "%s: stat failed (%s)", fn, strerror(errno));
921         return errno;
922     }
923
924     /* The device needs to be created. */
925     if (mknod(fn, S_IFCHR | 0700, dev)) {
926         VLOG_WARN_RL(&error_rl,
927                      "%s: creating character device %u:%u failed (%s)",
928                      fn, major(dev), minor(dev), strerror(errno));
929         return errno;
930     }
931
932 success:
933     *fnp = xstrdup(fn);
934     return 0;
935 }
936
937 /* Return the major device number of the Open vSwitch device.  If it
938  * cannot be determined, a negative errno is returned. */
939 static int
940 get_openvswitch_major(void)
941 {
942     static int openvswitch_major = -1;
943     if (openvswitch_major < 0) {
944         openvswitch_major = get_major("openvswitch");
945     }
946     return openvswitch_major;
947 }
948
949 static int
950 get_major(const char *target)
951 {
952     const char fn[] = "/proc/devices";
953     char line[128];
954     FILE *file;
955     int ln;
956
957     file = fopen(fn, "r");
958     if (!file) {
959         VLOG_ERR("opening %s failed (%s)", fn, strerror(errno));
960         return -errno;
961     }
962
963     for (ln = 1; fgets(line, sizeof line, file); ln++) {
964         char name[64];
965         int major;
966
967         if (!strncmp(line, "Character", 9) || line[0] == '\0') {
968             /* Nothing to do. */
969         } else if (!strncmp(line, "Block", 5)) {
970             /* We only want character devices, so skip the rest of the file. */
971             break;
972         } else if (sscanf(line, "%d %63s", &major, name)) {
973             if (!strcmp(name, target)) {
974                 fclose(file);
975                 return major;
976             }
977         } else {
978             VLOG_WARN_ONCE("%s:%d: syntax error", fn, ln);
979         }
980     }
981
982     fclose(file);
983
984     VLOG_ERR("%s: %s major not found (is the module loaded?)", fn, target);
985     return -ENODEV;
986 }
987
988 static int
989 create_minor(const char *name, int minor)
990 {
991     int error;
992     int fd;
993
994     error = open_minor(minor, &fd);
995     if (error) {
996         return error;
997     }
998
999     error = ioctl(fd, ODP_DP_CREATE, name) ? errno : 0;
1000     close(fd);
1001     return error;
1002 }
1003
1004 static int
1005 open_minor(int minor, int *fdp)
1006 {
1007     int error;
1008     char *fn;
1009
1010     error = make_openvswitch_device(minor, &fn);
1011     if (error) {
1012         return error;
1013     }
1014
1015     *fdp = open(fn, O_RDONLY | O_NONBLOCK);
1016     if (*fdp < 0) {
1017         error = errno;
1018         VLOG_WARN("%s: open failed (%s)", fn, strerror(error));
1019         free(fn);
1020         return error;
1021     }
1022     free(fn);
1023     return 0;
1024 }
1025
1026 static void
1027 dpif_linux_port_changed(const struct rtnetlink_link_change *change,
1028                         void *dpif_)
1029 {
1030     struct dpif_linux *dpif = dpif_;
1031
1032     if (change) {
1033         if (change->master_ifindex == dpif->local_ifindex
1034             && (change->nlmsg_type == RTM_NEWLINK
1035                 || change->nlmsg_type == RTM_DELLINK))
1036         {
1037             /* Our datapath changed, either adding a new port or deleting an
1038              * existing one. */
1039             shash_add_once(&dpif->changed_ports, change->ifname, NULL);
1040         }
1041     } else {
1042         dpif->change_error = true;
1043     }
1044 }
1045 \f
1046 /* Parses the contents of 'buf', which contains a "struct odp_vport" followed
1047  * by Netlink attributes, into 'vport'.  Returns 0 if successful, otherwise a
1048  * positive errno value.
1049  *
1050  * 'vport' will contain pointers into 'buf', so the caller should not free
1051  * 'buf' while 'vport' is still in use. */
1052 static int
1053 dpif_linux_vport_from_ofpbuf(struct dpif_linux_vport *vport,
1054                              const struct ofpbuf *buf)
1055 {
1056     static const struct nl_policy odp_vport_policy[] = {
1057         [ODP_VPORT_ATTR_PORT_NO] = { .type = NL_A_U32 },
1058         [ODP_VPORT_ATTR_TYPE] = { .type = NL_A_U32 },
1059         [ODP_VPORT_ATTR_NAME] = { .type = NL_A_STRING, .max_len = IFNAMSIZ },
1060         [ODP_VPORT_ATTR_STATS] = { .type = NL_A_UNSPEC,
1061                                    .min_len = sizeof(struct rtnl_link_stats64),
1062                                    .max_len = sizeof(struct rtnl_link_stats64),
1063                                    .optional = true },
1064         [ODP_VPORT_ATTR_ADDRESS] = { .type = NL_A_UNSPEC,
1065                                      .min_len = ETH_ADDR_LEN,
1066                                      .max_len = ETH_ADDR_LEN,
1067                                      .optional = true },
1068         [ODP_VPORT_ATTR_MTU] = { .type = NL_A_U32, .optional = true },
1069         [ODP_VPORT_ATTR_OPTIONS] = { .type = NL_A_NESTED, .optional = true },
1070         [ODP_VPORT_ATTR_IFINDEX] = { .type = NL_A_U32, .optional = true },
1071         [ODP_VPORT_ATTR_IFLINK] = { .type = NL_A_U32, .optional = true },
1072     };
1073
1074     struct odp_vport *odp_vport;
1075     struct nlattr *a[ARRAY_SIZE(odp_vport_policy)];
1076
1077     dpif_linux_vport_init(vport);
1078
1079     if (!nl_policy_parse(buf, sizeof *odp_vport, odp_vport_policy,
1080                          a, ARRAY_SIZE(odp_vport_policy))) {
1081         return EINVAL;
1082     }
1083     odp_vport = buf->data;
1084
1085     vport->dp_idx = odp_vport->dp_idx;
1086     vport->port_no = nl_attr_get_u32(a[ODP_VPORT_ATTR_PORT_NO]);
1087     vport->type = nl_attr_get_u32(a[ODP_VPORT_ATTR_TYPE]);
1088     vport->name = nl_attr_get_string(a[ODP_VPORT_ATTR_NAME]);
1089     if (a[ODP_VPORT_ATTR_STATS]) {
1090         vport->stats = nl_attr_get(a[ODP_VPORT_ATTR_STATS]);
1091     }
1092     if (a[ODP_VPORT_ATTR_ADDRESS]) {
1093         vport->address = nl_attr_get(a[ODP_VPORT_ATTR_ADDRESS]);
1094     }
1095     if (a[ODP_VPORT_ATTR_MTU]) {
1096         vport->mtu = nl_attr_get_u32(a[ODP_VPORT_ATTR_MTU]);
1097     }
1098     if (a[ODP_VPORT_ATTR_OPTIONS]) {
1099         vport->options = nl_attr_get(a[ODP_VPORT_ATTR_OPTIONS]);
1100         vport->options_len = nl_attr_get_size(a[ODP_VPORT_ATTR_OPTIONS]);
1101     }
1102     if (a[ODP_VPORT_ATTR_IFINDEX]) {
1103         vport->ifindex = nl_attr_get_u32(a[ODP_VPORT_ATTR_IFINDEX]);
1104     }
1105     if (a[ODP_VPORT_ATTR_IFLINK]) {
1106         vport->iflink = nl_attr_get_u32(a[ODP_VPORT_ATTR_IFLINK]);
1107     }
1108     return 0;
1109 }
1110
1111 /* Appends to 'buf' (which must initially be empty) a "struct odp_vport"
1112  * followed by Netlink attributes corresponding to 'vport'. */
1113 static void
1114 dpif_linux_vport_to_ofpbuf(const struct dpif_linux_vport *vport,
1115                            struct ofpbuf *buf)
1116 {
1117     struct odp_vport *odp_vport;
1118
1119     ofpbuf_reserve(buf, sizeof odp_vport);
1120
1121     if (vport->port_no != UINT32_MAX) {
1122         nl_msg_put_u32(buf, ODP_VPORT_ATTR_PORT_NO, vport->port_no);
1123     }
1124
1125     if (vport->type != ODP_VPORT_TYPE_UNSPEC) {
1126         nl_msg_put_u32(buf, ODP_VPORT_ATTR_TYPE, vport->type);
1127     }
1128
1129     if (vport->name) {
1130         nl_msg_put_string(buf, ODP_VPORT_ATTR_NAME, vport->name);
1131     }
1132
1133     if (vport->stats) {
1134         nl_msg_put_unspec(buf, ODP_VPORT_ATTR_STATS,
1135                           vport->stats, sizeof *vport->stats);
1136     }
1137
1138     if (vport->address) {
1139         nl_msg_put_unspec(buf, ODP_VPORT_ATTR_ADDRESS,
1140                           vport->address, ETH_ADDR_LEN);
1141     }
1142
1143     if (vport->mtu) {
1144         nl_msg_put_u32(buf, ODP_VPORT_ATTR_MTU, vport->mtu);
1145     }
1146
1147     if (vport->options) {
1148         nl_msg_put_nested(buf, ODP_VPORT_ATTR_OPTIONS,
1149                           vport->options, vport->options_len);
1150     }
1151
1152     if (vport->ifindex) {
1153         nl_msg_put_u32(buf, ODP_VPORT_ATTR_IFINDEX, vport->ifindex);
1154     }
1155
1156     if (vport->iflink) {
1157         nl_msg_put_u32(buf, ODP_VPORT_ATTR_IFLINK, vport->iflink);
1158     }
1159
1160     odp_vport = ofpbuf_push_uninit(buf, sizeof *odp_vport);
1161     odp_vport->dp_idx = vport->dp_idx;
1162     odp_vport->len = buf->size;
1163     odp_vport->total_len = (char *) ofpbuf_end(buf) - (char *) buf->data;
1164 }
1165
1166 /* Clears 'vport' to "empty" values. */
1167 void
1168 dpif_linux_vport_init(struct dpif_linux_vport *vport)
1169 {
1170     memset(vport, 0, sizeof *vport);
1171     vport->dp_idx = UINT32_MAX;
1172     vport->port_no = UINT32_MAX;
1173 }
1174
1175 /* Executes 'request' in the kernel datapath.  If the command fails, returns a
1176  * positive errno value.  Otherwise, if 'reply' and 'bufp' are null, returns 0
1177  * without doing anything else.  If 'reply' and 'bufp' are nonnull, then the
1178  * result of the command is expected to be an odp_vport also, which is decoded
1179  * and stored in '*reply' and '*bufp'.  The caller must free '*bufp' when the
1180  * reply is no longer needed ('reply' will contain pointers into '*bufp'). */
1181 int
1182 dpif_linux_vport_transact(const struct dpif_linux_vport *request,
1183                           struct dpif_linux_vport *reply,
1184                           struct ofpbuf **bufp)
1185 {
1186     static int dp0_fd = -1;
1187     struct ofpbuf *buf = NULL;
1188     int error;
1189
1190     assert((reply != NULL) == (bufp != NULL));
1191     if (dp0_fd < 0) {
1192         int fd;
1193
1194         error = open_minor(0, &fd);
1195         if (error) {
1196             goto error;
1197         }
1198         dp0_fd = fd;
1199     }
1200
1201     buf = ofpbuf_new(1024);
1202     dpif_linux_vport_to_ofpbuf(request, buf);
1203
1204     error = ioctl(dp0_fd, request->cmd, buf->data) ? errno : 0;
1205     if (error) {
1206         goto error;
1207     }
1208
1209     if (bufp) {
1210         buf->size = ((struct odp_vport *) buf->data)->len;
1211         error = dpif_linux_vport_from_ofpbuf(reply, buf);
1212         if (error) {
1213             goto error;
1214         }
1215         *bufp = buf;
1216     } else {
1217         ofpbuf_delete(buf);
1218     }
1219     return 0;
1220
1221 error:
1222     ofpbuf_delete(buf);
1223     if (bufp) {
1224         memset(reply, 0, sizeof *reply);
1225         *bufp = NULL;
1226     }
1227     return error;
1228 }
1229
1230 /* Obtains information about the kernel vport named 'name' and stores it into
1231  * '*reply' and '*bufp'.  The caller must free '*bufp' when the reply is no
1232  * longer needed ('reply' will contain pointers into '*bufp').  */
1233 int
1234 dpif_linux_vport_get(const char *name, struct dpif_linux_vport *reply,
1235                      struct ofpbuf **bufp)
1236 {
1237     struct dpif_linux_vport request;
1238
1239     dpif_linux_vport_init(&request);
1240     request.cmd = ODP_VPORT_GET;
1241     request.name = name;
1242
1243     return dpif_linux_vport_transact(&request, reply, bufp);
1244 }
1245