rhel: Add buildrequires for procps-ng.
[cascardo/ovs.git] / lib / netdev-bsd.c
1 /*
2  * Copyright (c) 2011, 2013, 2014 Gaetano Catalli.
3  * Copyright (c) 2013, 2014 YAMAMOTO Takashi.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at:
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #include <config.h>
19
20 #include "netdev-provider.h"
21 #include <stdlib.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <sys/types.h>
25 #include <sys/time.h>
26 #include <sys/ioctl.h>
27 #include <sys/socket.h>
28 #include <sys/sockio.h>
29 #include <net/bpf.h>
30 #include <ifaddrs.h>
31 #include <pcap/pcap.h>
32 #include <net/if.h>
33 #include <net/if_dl.h>
34 #include <net/if_media.h>
35 #include <net/if_tap.h>
36 #include <netinet/in.h>
37 #ifdef HAVE_NET_IF_MIB_H
38 #include <net/if_mib.h>
39 #endif
40 #include <poll.h>
41 #include <string.h>
42 #include <unistd.h>
43 #include <sys/sysctl.h>
44 #if defined(__NetBSD__)
45 #include <net/route.h>
46 #include <netinet/in.h>
47 #include <netinet/if_inarp.h>
48 #endif
49
50 #include "rtbsd.h"
51 #include "coverage.h"
52 #include "dpif-netdev.h"
53 #include "dynamic-string.h"
54 #include "fatal-signal.h"
55 #include "ofpbuf.h"
56 #include "openflow/openflow.h"
57 #include "ovs-thread.h"
58 #include "packets.h"
59 #include "poll-loop.h"
60 #include "shash.h"
61 #include "socket-util.h"
62 #include "svec.h"
63 #include "util.h"
64 #include "vlog.h"
65
66 VLOG_DEFINE_THIS_MODULE(netdev_bsd);
67
68 \f
69 struct netdev_rxq_bsd {
70     struct netdev_rxq up;
71
72     /* Packet capture descriptor for a system network device.
73      * For a tap device this is NULL. */
74     pcap_t *pcap_handle;
75
76     /* Selectable file descriptor for the network device.
77      * This descriptor will be used for polling operations. */
78     int fd;
79 };
80
81 struct netdev_bsd {
82     struct netdev up;
83
84     /* Never changes after initialization. */
85     char *kernel_name;
86
87     /* Protects all members below. */
88     struct ovs_mutex mutex;
89
90     unsigned int cache_valid;
91
92     int ifindex;
93     uint8_t etheraddr[ETH_ADDR_LEN];
94     struct in_addr in4;
95     struct in_addr netmask;
96     struct in6_addr in6;
97     int mtu;
98     int carrier;
99
100     int tap_fd;         /* TAP character device, if any, otherwise -1. */
101
102     /* Used for sending packets on non-tap devices. */
103     pcap_t *pcap;
104     int fd;
105 };
106
107
108 enum {
109     VALID_IFINDEX = 1 << 0,
110     VALID_ETHERADDR = 1 << 1,
111     VALID_IN4 = 1 << 2,
112     VALID_IN6 = 1 << 3,
113     VALID_MTU = 1 << 4,
114     VALID_CARRIER = 1 << 5
115 };
116
117 #define PCAP_SNAPLEN 2048
118
119
120 /*
121  * Notifier used to invalidate device informations in case of status change.
122  *
123  * It will be registered with a 'rtbsd_notifier_register()' when the first
124  * device will be created with the call of either 'netdev_bsd_tap_create()' or
125  * 'netdev_bsd_system_create()'.
126  *
127  * The callback associated with this notifier ('netdev_bsd_cache_cb()') will
128  * invalidate cached information about the device.
129  */
130 static struct rtbsd_notifier netdev_bsd_cache_notifier;
131 static int cache_notifier_refcount;
132
133 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
134
135 static void destroy_tap(int fd, const char *name);
136 static int get_flags(const struct netdev *, int *flagsp);
137 static int set_flags(const char *, int flags);
138 static int do_set_addr(struct netdev *netdev,
139                        unsigned long ioctl_nr, const char *ioctl_name,
140                        struct in_addr addr);
141 static int get_etheraddr(const char *netdev_name, uint8_t ea[ETH_ADDR_LEN]);
142 static int set_etheraddr(const char *netdev_name, int hwaddr_family,
143                          int hwaddr_len, const uint8_t[ETH_ADDR_LEN]);
144 static int get_ifindex(const struct netdev *, int *ifindexp);
145
146 static int ifr_get_flags(const struct ifreq *);
147 static void ifr_set_flags(struct ifreq *, int flags);
148
149 #ifdef __NetBSD__
150 static int af_link_ioctl(unsigned long command, const void *arg);
151 #endif
152
153 static void netdev_bsd_run(void);
154 static int netdev_bsd_get_mtu(const struct netdev *netdev_, int *mtup);
155
156 static bool
157 is_netdev_bsd_class(const struct netdev_class *netdev_class)
158 {
159     return netdev_class->run == netdev_bsd_run;
160 }
161
162 static struct netdev_bsd *
163 netdev_bsd_cast(const struct netdev *netdev)
164 {
165     ovs_assert(is_netdev_bsd_class(netdev_get_class(netdev)));
166     return CONTAINER_OF(netdev, struct netdev_bsd, up);
167 }
168
169 static struct netdev_rxq_bsd *
170 netdev_rxq_bsd_cast(const struct netdev_rxq *rxq)
171 {
172     ovs_assert(is_netdev_bsd_class(netdev_get_class(rxq->netdev)));
173     return CONTAINER_OF(rxq, struct netdev_rxq_bsd, up);
174 }
175
176 static const char *
177 netdev_get_kernel_name(const struct netdev *netdev)
178 {
179     return netdev_bsd_cast(netdev)->kernel_name;
180 }
181
182 /*
183  * Perform periodic work needed by netdev. In BSD netdevs it checks for any
184  * interface status changes, and eventually calls all the user callbacks.
185  */
186 static void
187 netdev_bsd_run(void)
188 {
189     rtbsd_notifier_run();
190 }
191
192 /*
193  * Arranges for poll_block() to wake up if the "run" member function needs to
194  * be called.
195  */
196 static void
197 netdev_bsd_wait(void)
198 {
199     rtbsd_notifier_wait();
200 }
201
202 /* Invalidate cache in case of interface status change. */
203 static void
204 netdev_bsd_cache_cb(const struct rtbsd_change *change,
205                     void *aux OVS_UNUSED)
206 {
207     struct netdev_bsd *dev;
208
209     if (change) {
210         struct netdev *base_dev = netdev_from_name(change->if_name);
211
212         if (base_dev) {
213             const struct netdev_class *netdev_class =
214                                                 netdev_get_class(base_dev);
215
216             if (is_netdev_bsd_class(netdev_class)) {
217                 dev = netdev_bsd_cast(base_dev);
218                 dev->cache_valid = 0;
219                 netdev_change_seq_changed(base_dev);
220             }
221             netdev_close(base_dev);
222         }
223     } else {
224         /*
225          * XXX the API is lacking, we should be able to iterate on the list of
226          * netdevs without having to store the info in a temp shash.
227          */
228         struct shash device_shash;
229         struct shash_node *node;
230
231         shash_init(&device_shash);
232         netdev_get_devices(&netdev_bsd_class, &device_shash);
233         SHASH_FOR_EACH (node, &device_shash) {
234             struct netdev *netdev = node->data;
235             dev = netdev_bsd_cast(netdev);
236             dev->cache_valid = 0;
237             netdev_change_seq_changed(netdev);
238             netdev_close(netdev);
239         }
240         shash_destroy(&device_shash);
241     }
242 }
243
244 static int
245 cache_notifier_ref(void)
246 {
247     int ret = 0;
248
249     if (!cache_notifier_refcount) {
250         ret = rtbsd_notifier_register(&netdev_bsd_cache_notifier,
251                                                 netdev_bsd_cache_cb, NULL);
252         if (ret) {
253             return ret;
254         }
255     }
256     cache_notifier_refcount++;
257     return 0;
258 }
259
260 static int
261 cache_notifier_unref(void)
262 {
263     cache_notifier_refcount--;
264     if (cache_notifier_refcount == 0) {
265         rtbsd_notifier_unregister(&netdev_bsd_cache_notifier);
266     }
267     return 0;
268 }
269
270 static struct netdev *
271 netdev_bsd_alloc(void)
272 {
273     struct netdev_bsd *netdev = xzalloc(sizeof *netdev);
274     return &netdev->up;
275 }
276
277 static int
278 netdev_bsd_construct_system(struct netdev *netdev_)
279 {
280     struct netdev_bsd *netdev = netdev_bsd_cast(netdev_);
281     enum netdev_flags flags;
282     int error;
283
284     error = cache_notifier_ref();
285     if (error) {
286         return error;
287     }
288
289     ovs_mutex_init(&netdev->mutex);
290     netdev->tap_fd = -1;
291     netdev->kernel_name = xstrdup(netdev_->name);
292
293     /* Verify that the netdev really exists by attempting to read its flags */
294     error = netdev_get_flags(netdev_, &flags);
295     if (error == ENXIO) {
296         free(netdev->kernel_name);
297         cache_notifier_unref();
298         return error;
299     }
300
301     return 0;
302 }
303
304 static int
305 netdev_bsd_construct_tap(struct netdev *netdev_)
306 {
307     struct netdev_bsd *netdev = netdev_bsd_cast(netdev_);
308     const char *name = netdev_->name;
309     int error = 0;
310     struct ifreq ifr;
311     char *kernel_name = NULL;
312
313     error = cache_notifier_ref();
314     if (error) {
315         goto error;
316     }
317
318     memset(&ifr, 0, sizeof(ifr));
319
320     /* Create a tap device by opening /dev/tap.  The TAPGIFNAME ioctl is used
321      * to retrieve the name of the tap device. */
322     ovs_mutex_init(&netdev->mutex);
323     netdev->tap_fd = open("/dev/tap", O_RDWR);
324     if (netdev->tap_fd < 0) {
325         error = errno;
326         VLOG_WARN("opening \"/dev/tap\" failed: %s", ovs_strerror(error));
327         goto error_unref_notifier;
328     }
329
330     /* Retrieve tap name (e.g. tap0) */
331     if (ioctl(netdev->tap_fd, TAPGIFNAME, &ifr) == -1) {
332         /* XXX Need to destroy the device? */
333         error = errno;
334         close(netdev->tap_fd);
335         goto error_unref_notifier;
336     }
337
338     /* Change the name of the tap device */
339 #if defined(SIOCSIFNAME)
340     ifr.ifr_data = (void *)name;
341     error = af_inet_ioctl(SIOCSIFNAME, &ifr);
342     if (error) {
343         destroy_tap(netdev->tap_fd, ifr.ifr_name);
344         goto error_unref_notifier;
345     }
346     kernel_name = xstrdup(name);
347 #else
348     /*
349      * NetBSD doesn't support inteface renaming.
350      */
351     VLOG_INFO("tap %s is created for bridge %s", ifr.ifr_name, name);
352     kernel_name = xstrdup(ifr.ifr_name);
353 #endif
354
355     /* set non-blocking. */
356     error = set_nonblocking(netdev->tap_fd);
357     if (error) {
358         destroy_tap(netdev->tap_fd, kernel_name);
359         goto error_unref_notifier;
360     }
361
362     /* Turn device UP */
363     ifr_set_flags(&ifr, IFF_UP);
364     strncpy(ifr.ifr_name, kernel_name, sizeof ifr.ifr_name);
365     error = af_inet_ioctl(SIOCSIFFLAGS, &ifr);
366     if (error) {
367         destroy_tap(netdev->tap_fd, kernel_name);
368         goto error_unref_notifier;
369     }
370
371     netdev->kernel_name = kernel_name;
372
373     return 0;
374
375 error_unref_notifier:
376     ovs_mutex_destroy(&netdev->mutex);
377     cache_notifier_unref();
378 error:
379     free(kernel_name);
380     return error;
381 }
382
383 static void
384 netdev_bsd_destruct(struct netdev *netdev_)
385 {
386     struct netdev_bsd *netdev = netdev_bsd_cast(netdev_);
387
388     cache_notifier_unref();
389
390     if (netdev->tap_fd >= 0) {
391         destroy_tap(netdev->tap_fd, netdev_get_kernel_name(netdev_));
392     }
393     if (netdev->pcap) {
394         pcap_close(netdev->pcap);
395     }
396     free(netdev->kernel_name);
397     ovs_mutex_destroy(&netdev->mutex);
398 }
399
400 static void
401 netdev_bsd_dealloc(struct netdev *netdev_)
402 {
403     struct netdev_bsd *netdev = netdev_bsd_cast(netdev_);
404
405     free(netdev);
406 }
407
408 static int
409 netdev_bsd_open_pcap(const char *name, pcap_t **pcapp, int *fdp)
410 {
411     char errbuf[PCAP_ERRBUF_SIZE];
412     pcap_t *pcap = NULL;
413     int one = 1;
414     int error;
415     int fd;
416
417     /* Open the pcap device.  The device is opened in non-promiscuous mode
418      * because the interface flags are manually set by the caller. */
419     errbuf[0] = '\0';
420     pcap = pcap_open_live(name, PCAP_SNAPLEN, 0, 1000, errbuf);
421     if (!pcap) {
422         VLOG_ERR_RL(&rl, "%s: pcap_open_live failed: %s", name, errbuf);
423         error = EIO;
424         goto error;
425     }
426     if (errbuf[0] != '\0') {
427         VLOG_WARN_RL(&rl, "%s: pcap_open_live: %s", name, errbuf);
428     }
429
430     /* Get the underlying fd. */
431     fd = pcap_get_selectable_fd(pcap);
432     if (fd == -1) {
433         VLOG_WARN_RL(&rl, "%s: no selectable file descriptor", name);
434         error = errno;
435         goto error;
436     }
437
438     /* Set non-blocking mode. Also the BIOCIMMEDIATE ioctl must be called
439      * on the file descriptor returned by pcap_get_selectable_fd to achieve
440      * a real non-blocking behaviour.*/
441     error = pcap_setnonblock(pcap, 1, errbuf);
442     if (error == -1) {
443         error = errno;
444         goto error;
445     }
446
447     /* This call assure that reads return immediately upon packet
448      * reception.  Otherwise, a read will block until either the kernel
449      * buffer becomes full or a timeout occurs. */
450     if (ioctl(fd, BIOCIMMEDIATE, &one) < 0 ) {
451         VLOG_ERR_RL(&rl, "ioctl(BIOCIMMEDIATE) on %s device failed: %s",
452                     name, ovs_strerror(errno));
453         error = errno;
454         goto error;
455     }
456
457     /* Capture only incoming packets. */
458     error = pcap_setdirection(pcap, PCAP_D_IN);
459     if (error == -1) {
460         error = errno;
461         goto error;
462     }
463
464     *pcapp = pcap;
465     *fdp = fd;
466     return 0;
467
468 error:
469     if (pcap) {
470         pcap_close(pcap);
471     }
472     *pcapp = NULL;
473     *fdp = -1;
474     return error;
475 }
476
477 static struct netdev_rxq *
478 netdev_bsd_rxq_alloc(void)
479 {
480     struct netdev_rxq_bsd *rxq = xzalloc(sizeof *rxq);
481     return &rxq->up;
482 }
483
484 static int
485 netdev_bsd_rxq_construct(struct netdev_rxq *rxq_)
486 {
487     struct netdev_rxq_bsd *rxq = netdev_rxq_bsd_cast(rxq_);
488     struct netdev *netdev_ = rxq->up.netdev;
489     struct netdev_bsd *netdev = netdev_bsd_cast(netdev_);
490     int error;
491
492     if (!strcmp(netdev_get_type(netdev_), "tap")) {
493         rxq->pcap_handle = NULL;
494         rxq->fd = netdev->tap_fd;
495         error = 0;
496     } else {
497         ovs_mutex_lock(&netdev->mutex);
498         error = netdev_bsd_open_pcap(netdev_get_kernel_name(netdev_),
499                                      &rxq->pcap_handle, &rxq->fd);
500         ovs_mutex_unlock(&netdev->mutex);
501     }
502
503     return error;
504 }
505
506 static void
507 netdev_bsd_rxq_destruct(struct netdev_rxq *rxq_)
508 {
509     struct netdev_rxq_bsd *rxq = netdev_rxq_bsd_cast(rxq_);
510
511     if (rxq->pcap_handle) {
512         pcap_close(rxq->pcap_handle);
513     }
514 }
515
516 static void
517 netdev_bsd_rxq_dealloc(struct netdev_rxq *rxq_)
518 {
519     struct netdev_rxq_bsd *rxq = netdev_rxq_bsd_cast(rxq_);
520
521     free(rxq);
522 }
523
524 /* The recv callback of the netdev class returns the number of bytes of the
525  * received packet.
526  *
527  * This can be done by the pcap_next() function. Unfortunately pcap_next() does
528  * not make difference between a missing packet on the capture interface and
529  * an error during the file capture.  We can use the pcap_dispatch() function
530  * instead, which is able to distinguish between errors and null packet.
531  *
532  * To make pcap_dispatch() returns the number of bytes read from the interface
533  * we need to define the following callback and argument.
534  */
535 struct pcap_arg {
536     void *data;
537     int size;
538     int retval;
539 };
540
541 /*
542  * This callback will be executed on every captured packet.
543  *
544  * If the packet captured by pcap_dispatch() does not fit the pcap buffer,
545  * pcap returns a truncated packet and we follow this behavior.
546  *
547  * The argument args->retval is the packet size in bytes.
548  */
549 static void
550 proc_pkt(u_char *args_, const struct pcap_pkthdr *hdr, const u_char *packet)
551 {
552     struct pcap_arg *args = ALIGNED_CAST(struct pcap_arg *, args_);
553
554     if (args->size < hdr->len) {
555         VLOG_WARN_RL(&rl, "packet truncated");
556         args->retval = args->size;
557     } else {
558         args->retval = hdr->len;
559     }
560
561     /* copy the packet to our buffer */
562     memcpy(args->data, packet, args->retval);
563 }
564
565 /*
566  * This function attempts to receive a packet from the specified network
567  * device. It is assumed that the network device is a system device or a tap
568  * device opened as a system one. In this case the read operation is performed
569  * from rxq->pcap.
570  */
571 static int
572 netdev_rxq_bsd_recv_pcap(struct netdev_rxq_bsd *rxq, struct ofpbuf *buffer)
573 {
574     struct pcap_arg arg;
575     int ret;
576
577     /* prepare the pcap argument to store the packet */
578     arg.size = ofpbuf_tailroom(buffer);
579     arg.data = ofpbuf_data(buffer);
580
581     for (;;) {
582         ret = pcap_dispatch(rxq->pcap_handle, 1, proc_pkt, (u_char *) &arg);
583
584         if (ret > 0) {
585             ofpbuf_set_size(buffer, ofpbuf_size(buffer) + arg.retval);
586             return 0;
587         }
588         if (ret == -1) {
589             if (errno == EINTR) {
590                  continue;
591             }
592         }
593
594         return EAGAIN;
595     }
596 }
597
598 /*
599  * This function attempts to receive a packet from the specified network
600  * device. It is assumed that the network device is a tap device and
601  * 'rxq->fd' is initialized with the tap file descriptor.
602  */
603 static int
604 netdev_rxq_bsd_recv_tap(struct netdev_rxq_bsd *rxq, struct ofpbuf *buffer)
605 {
606     size_t size = ofpbuf_tailroom(buffer);
607
608     for (;;) {
609         ssize_t retval = read(rxq->fd, ofpbuf_data(buffer), size);
610         if (retval >= 0) {
611             ofpbuf_set_size(buffer, ofpbuf_size(buffer) + retval);
612             return 0;
613         } else if (errno != EINTR) {
614             if (errno != EAGAIN) {
615                 VLOG_WARN_RL(&rl, "error receiving Ethernet packet on %s: %s",
616                              ovs_strerror(errno), netdev_rxq_get_name(&rxq->up));
617             }
618             return errno;
619         }
620     }
621 }
622
623 static int
624 netdev_bsd_rxq_recv(struct netdev_rxq *rxq_, struct ofpbuf **packet, int *c)
625 {
626     struct netdev_rxq_bsd *rxq = netdev_rxq_bsd_cast(rxq_);
627     struct netdev *netdev = rxq->up.netdev;
628     struct ofpbuf *buffer;
629     ssize_t retval;
630     int mtu;
631
632     if (netdev_bsd_get_mtu(netdev, &mtu)) {
633         mtu = ETH_PAYLOAD_MAX;
634     }
635
636     buffer = ofpbuf_new_with_headroom(VLAN_ETH_HEADER_LEN + mtu, DP_NETDEV_HEADROOM);
637
638     retval = (rxq->pcap_handle
639             ? netdev_rxq_bsd_recv_pcap(rxq, buffer)
640             : netdev_rxq_bsd_recv_tap(rxq, buffer));
641
642     if (retval) {
643         ofpbuf_delete(buffer);
644     } else {
645         dp_packet_pad(buffer);
646         packet[0] = buffer;
647         *c = 1;
648     }
649     return retval;
650 }
651
652 /*
653  * Registers with the poll loop to wake up from the next call to poll_block()
654  * when a packet is ready to be received with netdev_rxq_recv() on 'rxq'.
655  */
656 static void
657 netdev_bsd_rxq_wait(struct netdev_rxq *rxq_)
658 {
659     struct netdev_rxq_bsd *rxq = netdev_rxq_bsd_cast(rxq_);
660
661     poll_fd_wait(rxq->fd, POLLIN);
662 }
663
664 /* Discards all packets waiting to be received from 'rxq'. */
665 static int
666 netdev_bsd_rxq_drain(struct netdev_rxq *rxq_)
667 {
668     struct ifreq ifr;
669     struct netdev_rxq_bsd *rxq = netdev_rxq_bsd_cast(rxq_);
670
671     strcpy(ifr.ifr_name, netdev_get_kernel_name(netdev_rxq_get_netdev(rxq_)));
672     if (ioctl(rxq->fd, BIOCFLUSH, &ifr) == -1) {
673         VLOG_DBG_RL(&rl, "%s: ioctl(BIOCFLUSH) failed: %s",
674                     netdev_rxq_get_name(rxq_), ovs_strerror(errno));
675         return errno;
676     }
677     return 0;
678 }
679
680 /*
681  * Send a packet on the specified network device. The device could be either a
682  * system or a tap device.
683  */
684 static int
685 netdev_bsd_send(struct netdev *netdev_, struct ofpbuf *pkt, bool may_steal)
686 {
687     struct netdev_bsd *dev = netdev_bsd_cast(netdev_);
688     const char *name = netdev_get_name(netdev_);
689     const void *data = ofpbuf_data(pkt);
690     size_t size = ofpbuf_size(pkt);
691     int error;
692
693     ovs_mutex_lock(&dev->mutex);
694     if (dev->tap_fd < 0 && !dev->pcap) {
695         error = netdev_bsd_open_pcap(name, &dev->pcap, &dev->fd);
696     } else {
697         error = 0;
698     }
699
700     while (!error) {
701         ssize_t retval;
702         if (dev->tap_fd >= 0) {
703             retval = write(dev->tap_fd, data, size);
704         } else {
705             retval = pcap_inject(dev->pcap, data, size);
706         }
707         if (retval < 0) {
708             if (errno == EINTR) {
709                 continue;
710             } else {
711                 error = errno;
712                 if (error != EAGAIN) {
713                     VLOG_WARN_RL(&rl, "error sending Ethernet packet on %s: "
714                                  "%s", name, ovs_strerror(error));
715                 }
716             }
717         } else if (retval != size) {
718             VLOG_WARN_RL(&rl, "sent partial Ethernet packet (%"PRIuSIZE" bytes of "
719                          "%"PRIuSIZE") on %s", retval, size, name);
720             error = EMSGSIZE;
721         } else {
722             break;
723         }
724     }
725
726     ovs_mutex_unlock(&dev->mutex);
727     if (may_steal) {
728         ofpbuf_delete(pkt);
729     }
730
731     return error;
732 }
733
734 /*
735  * Registers with the poll loop to wake up from the next call to poll_block()
736  * when the packet transmission queue has sufficient room to transmit a packet
737  * with netdev_send().
738  */
739 static void
740 netdev_bsd_send_wait(struct netdev *netdev_)
741 {
742     struct netdev_bsd *dev = netdev_bsd_cast(netdev_);
743
744     ovs_mutex_lock(&dev->mutex);
745     if (dev->tap_fd >= 0) {
746         /* TAP device always accepts packets. */
747         poll_immediate_wake();
748     } else if (dev->pcap) {
749         poll_fd_wait(dev->fd, POLLOUT);
750     } else {
751         /* We haven't even tried to send a packet yet. */
752         poll_immediate_wake();
753     }
754     ovs_mutex_unlock(&dev->mutex);
755 }
756
757 /*
758  * Attempts to set 'netdev''s MAC address to 'mac'.  Returns 0 if successful,
759  * otherwise a positive errno value.
760  */
761 static int
762 netdev_bsd_set_etheraddr(struct netdev *netdev_,
763                          const uint8_t mac[ETH_ADDR_LEN])
764 {
765     struct netdev_bsd *netdev = netdev_bsd_cast(netdev_);
766     int error = 0;
767
768     ovs_mutex_lock(&netdev->mutex);
769     if (!(netdev->cache_valid & VALID_ETHERADDR)
770         || !eth_addr_equals(netdev->etheraddr, mac)) {
771         error = set_etheraddr(netdev_get_kernel_name(netdev_), AF_LINK,
772                               ETH_ADDR_LEN, mac);
773         if (!error) {
774             netdev->cache_valid |= VALID_ETHERADDR;
775             memcpy(netdev->etheraddr, mac, ETH_ADDR_LEN);
776             netdev_change_seq_changed(netdev_);
777         }
778     }
779     ovs_mutex_unlock(&netdev->mutex);
780
781     return error;
782 }
783
784 /*
785  * Returns a pointer to 'netdev''s MAC address.  The caller must not modify or
786  * free the returned buffer.
787  */
788 static int
789 netdev_bsd_get_etheraddr(const struct netdev *netdev_,
790                          uint8_t mac[ETH_ADDR_LEN])
791 {
792     struct netdev_bsd *netdev = netdev_bsd_cast(netdev_);
793     int error = 0;
794
795     ovs_mutex_lock(&netdev->mutex);
796     if (!(netdev->cache_valid & VALID_ETHERADDR)) {
797         error = get_etheraddr(netdev_get_kernel_name(netdev_),
798                               netdev->etheraddr);
799         if (!error) {
800             netdev->cache_valid |= VALID_ETHERADDR;
801         }
802     }
803     if (!error) {
804         memcpy(mac, netdev->etheraddr, ETH_ADDR_LEN);
805     }
806     ovs_mutex_unlock(&netdev->mutex);
807
808     return error;
809 }
810
811 /*
812  * Returns the maximum size of transmitted (and received) packets on 'netdev',
813  * in bytes, not including the hardware header; thus, this is typically 1500
814  * bytes for Ethernet devices.
815  */
816 static int
817 netdev_bsd_get_mtu(const struct netdev *netdev_, int *mtup)
818 {
819     struct netdev_bsd *netdev = netdev_bsd_cast(netdev_);
820     int error = 0;
821
822     ovs_mutex_lock(&netdev->mutex);
823     if (!(netdev->cache_valid & VALID_MTU)) {
824         struct ifreq ifr;
825
826         error = af_inet_ifreq_ioctl(netdev_get_kernel_name(netdev_), &ifr,
827                                     SIOCGIFMTU, "SIOCGIFMTU");
828         if (!error) {
829             netdev->mtu = ifr.ifr_mtu;
830             netdev->cache_valid |= VALID_MTU;
831         }
832     }
833     if (!error) {
834         *mtup = netdev->mtu;
835     }
836     ovs_mutex_unlock(&netdev->mutex);
837
838     return error;
839 }
840
841 static int
842 netdev_bsd_get_ifindex(const struct netdev *netdev_)
843 {
844     struct netdev_bsd *netdev = netdev_bsd_cast(netdev_);
845     int ifindex, error;
846
847     ovs_mutex_lock(&netdev->mutex);
848     error = get_ifindex(netdev_, &ifindex);
849     ovs_mutex_unlock(&netdev->mutex);
850
851     return error ? -error : ifindex;
852 }
853
854 static int
855 netdev_bsd_get_carrier(const struct netdev *netdev_, bool *carrier)
856 {
857     struct netdev_bsd *netdev = netdev_bsd_cast(netdev_);
858     int error = 0;
859
860     ovs_mutex_lock(&netdev->mutex);
861     if (!(netdev->cache_valid & VALID_CARRIER)) {
862         struct ifmediareq ifmr;
863
864         memset(&ifmr, 0, sizeof(ifmr));
865         strncpy(ifmr.ifm_name, netdev_get_kernel_name(netdev_),
866                 sizeof ifmr.ifm_name);
867
868         error = af_inet_ioctl(SIOCGIFMEDIA, &ifmr);
869         if (!error) {
870             netdev->carrier = (ifmr.ifm_status & IFM_ACTIVE) == IFM_ACTIVE;
871             netdev->cache_valid |= VALID_CARRIER;
872
873             /* If the interface doesn't report whether the media is active,
874              * just assume it is active. */
875             if ((ifmr.ifm_status & IFM_AVALID) == 0) {
876                 netdev->carrier = true;
877             }
878         } else {
879             VLOG_DBG_RL(&rl, "%s: ioctl(SIOCGIFMEDIA) failed: %s",
880                         netdev_get_name(netdev_), ovs_strerror(error));
881         }
882     }
883     if (!error) {
884         *carrier = netdev->carrier;
885     }
886     ovs_mutex_unlock(&netdev->mutex);
887
888     return error;
889 }
890
891 static void
892 convert_stats_system(struct netdev_stats *stats, const struct if_data *ifd)
893 {
894     /*
895      * note: UINT64_MAX means unsupported
896      */
897     stats->rx_packets = ifd->ifi_ipackets;
898     stats->tx_packets = ifd->ifi_opackets;
899     stats->rx_bytes = ifd->ifi_obytes;
900     stats->tx_bytes = ifd->ifi_ibytes;
901     stats->rx_errors = ifd->ifi_ierrors;
902     stats->tx_errors = ifd->ifi_oerrors;
903     stats->rx_dropped = ifd->ifi_iqdrops;
904     stats->tx_dropped = UINT64_MAX;
905     stats->multicast = ifd->ifi_imcasts;
906     stats->collisions = ifd->ifi_collisions;
907     stats->rx_length_errors = UINT64_MAX;
908     stats->rx_over_errors = UINT64_MAX;
909     stats->rx_crc_errors = UINT64_MAX;
910     stats->rx_frame_errors = UINT64_MAX;
911     stats->rx_fifo_errors = UINT64_MAX;
912     stats->rx_missed_errors = UINT64_MAX;
913     stats->tx_aborted_errors = UINT64_MAX;
914     stats->tx_carrier_errors = UINT64_MAX;
915     stats->tx_fifo_errors = UINT64_MAX;
916     stats->tx_heartbeat_errors = UINT64_MAX;
917     stats->tx_window_errors = UINT64_MAX;
918 }
919
920 static void
921 convert_stats_tap(struct netdev_stats *stats, const struct if_data *ifd)
922 {
923     /*
924      * Similar to convert_stats_system but swapping rxq and tx
925      * because 'ifd' is stats for the network interface side of the
926      * tap device and what the caller wants is one for the character
927      * device side.
928      *
929      * note: UINT64_MAX means unsupported
930      */
931     stats->rx_packets = ifd->ifi_opackets;
932     stats->tx_packets = ifd->ifi_ipackets;
933     stats->rx_bytes = ifd->ifi_ibytes;
934     stats->tx_bytes = ifd->ifi_obytes;
935     stats->rx_errors = ifd->ifi_oerrors;
936     stats->tx_errors = ifd->ifi_ierrors;
937     stats->rx_dropped = UINT64_MAX;
938     stats->tx_dropped = ifd->ifi_iqdrops;
939     stats->multicast = ifd->ifi_omcasts;
940     stats->collisions = UINT64_MAX;
941     stats->rx_length_errors = UINT64_MAX;
942     stats->rx_over_errors = UINT64_MAX;
943     stats->rx_crc_errors = UINT64_MAX;
944     stats->rx_frame_errors = UINT64_MAX;
945     stats->rx_fifo_errors = UINT64_MAX;
946     stats->rx_missed_errors = UINT64_MAX;
947     stats->tx_aborted_errors = UINT64_MAX;
948     stats->tx_carrier_errors = UINT64_MAX;
949     stats->tx_fifo_errors = UINT64_MAX;
950     stats->tx_heartbeat_errors = UINT64_MAX;
951     stats->tx_window_errors = UINT64_MAX;
952 }
953
954 static void
955 convert_stats(const struct netdev *netdev, struct netdev_stats *stats,
956               const struct if_data *ifd)
957 {
958     if (netdev_bsd_cast(netdev)->tap_fd == -1) {
959         convert_stats_system(stats, ifd);
960     } else {
961         convert_stats_tap(stats, ifd);
962     }
963 }
964
965 /* Retrieves current device stats for 'netdev'. */
966 static int
967 netdev_bsd_get_stats(const struct netdev *netdev_, struct netdev_stats *stats)
968 {
969 #if defined(__FreeBSD__)
970     int if_count, i;
971     int mib[6];
972     size_t len;
973     struct ifmibdata ifmd;
974
975
976     mib[0] = CTL_NET;
977     mib[1] = PF_LINK;
978     mib[2] = NETLINK_GENERIC;
979     mib[3] = IFMIB_SYSTEM;
980     mib[4] = IFMIB_IFCOUNT;
981
982     len = sizeof(if_count);
983
984     if (sysctl(mib, 5, &if_count, &len, (void *)0, 0) == -1) {
985         VLOG_DBG_RL(&rl, "%s: sysctl failed: %s",
986                     netdev_get_name(netdev_), ovs_strerror(errno));
987         return errno;
988     }
989
990     mib[5] = IFDATA_GENERAL;
991     mib[3] = IFMIB_IFDATA;
992     len = sizeof(ifmd);
993     for (i = 1; i <= if_count; i++) {
994         mib[4] = i; //row
995         if (sysctl(mib, 6, &ifmd, &len, (void *)0, 0) == -1) {
996             VLOG_DBG_RL(&rl, "%s: sysctl failed: %s",
997                         netdev_get_name(netdev_), ovs_strerror(errno));
998             return errno;
999         } else if (!strcmp(ifmd.ifmd_name, netdev_get_name(netdev_))) {
1000             convert_stats(netdev_, stats, &ifmd.ifmd_data);
1001             break;
1002         }
1003     }
1004
1005     return 0;
1006 #elif defined(__NetBSD__)
1007     struct ifdatareq ifdr;
1008     int error;
1009
1010     memset(&ifdr, 0, sizeof(ifdr));
1011     strncpy(ifdr.ifdr_name, netdev_get_kernel_name(netdev_),
1012             sizeof(ifdr.ifdr_name));
1013     error = af_link_ioctl(SIOCGIFDATA, &ifdr);
1014     if (!error) {
1015         convert_stats(netdev_, stats, &ifdr.ifdr_data);
1016     }
1017     return error;
1018 #else
1019 #error not implemented
1020 #endif
1021 }
1022
1023 static uint32_t
1024 netdev_bsd_parse_media(int media)
1025 {
1026     uint32_t supported = 0;
1027     bool half_duplex = media & IFM_HDX ? true : false;
1028
1029     switch (IFM_SUBTYPE(media)) {
1030     case IFM_10_2:
1031     case IFM_10_5:
1032     case IFM_10_STP:
1033     case IFM_10_T:
1034         supported |= half_duplex ? NETDEV_F_10MB_HD : NETDEV_F_10MB_FD;
1035         supported |= NETDEV_F_COPPER;
1036         break;
1037
1038     case IFM_10_FL:
1039         supported |= half_duplex ? NETDEV_F_10MB_HD : NETDEV_F_10MB_FD;
1040         supported |= NETDEV_F_FIBER;
1041         break;
1042
1043     case IFM_100_T2:
1044     case IFM_100_T4:
1045     case IFM_100_TX:
1046     case IFM_100_VG:
1047         supported |= half_duplex ? NETDEV_F_100MB_HD : NETDEV_F_100MB_FD;
1048         supported |= NETDEV_F_COPPER;
1049         break;
1050
1051     case IFM_100_FX:
1052         supported |= half_duplex ? NETDEV_F_100MB_HD : NETDEV_F_100MB_FD;
1053         supported |= NETDEV_F_FIBER;
1054         break;
1055
1056     case IFM_1000_CX:
1057     case IFM_1000_T:
1058         supported |= half_duplex ? NETDEV_F_1GB_HD : NETDEV_F_1GB_FD;
1059         supported |= NETDEV_F_COPPER;
1060         break;
1061
1062     case IFM_1000_LX:
1063     case IFM_1000_SX:
1064         supported |= half_duplex ? NETDEV_F_1GB_HD : NETDEV_F_1GB_FD;
1065         supported |= NETDEV_F_FIBER;
1066         break;
1067
1068     case IFM_10G_CX4:
1069         supported |= NETDEV_F_10GB_FD;
1070         supported |= NETDEV_F_COPPER;
1071         break;
1072
1073     case IFM_10G_LR:
1074     case IFM_10G_SR:
1075         supported |= NETDEV_F_10GB_FD;
1076         supported |= NETDEV_F_FIBER;
1077         break;
1078
1079     default:
1080         return 0;
1081     }
1082
1083     if (IFM_SUBTYPE(media) == IFM_AUTO) {
1084         supported |= NETDEV_F_AUTONEG;
1085     }
1086     /*
1087     if (media & IFM_ETH_FMASK) {
1088         supported |= NETDEV_F_PAUSE;
1089     }
1090     */
1091
1092     return supported;
1093 }
1094
1095 /*
1096  * Stores the features supported by 'netdev' into each of '*current',
1097  * '*advertised', '*supported', and '*peer' that are non-null.  Each value is a
1098  * bitmap of "enum ofp_port_features" bits, in host byte order.  Returns 0 if
1099  * successful, otherwise a positive errno value.  On failure, all of the
1100  * passed-in values are set to 0.
1101  */
1102 static int
1103 netdev_bsd_get_features(const struct netdev *netdev,
1104                         enum netdev_features *current, uint32_t *advertised,
1105                         enum netdev_features *supported, uint32_t *peer)
1106 {
1107     struct ifmediareq ifmr;
1108     int *media_list;
1109     int i;
1110     int error;
1111
1112
1113     /* XXX Look into SIOCGIFCAP instead of SIOCGIFMEDIA */
1114
1115     memset(&ifmr, 0, sizeof(ifmr));
1116     strncpy(ifmr.ifm_name, netdev_get_name(netdev), sizeof ifmr.ifm_name);
1117
1118     /* We make two SIOCGIFMEDIA ioctl calls.  The first to determine the
1119      * number of supported modes, and a second with a buffer to retrieve
1120      * them. */
1121     error = af_inet_ioctl(SIOCGIFMEDIA, &ifmr);
1122     if (error) {
1123         VLOG_DBG_RL(&rl, "%s: ioctl(SIOCGIFMEDIA) failed: %s",
1124                     netdev_get_name(netdev), ovs_strerror(error));
1125         return error;
1126     }
1127
1128     media_list = xcalloc(ifmr.ifm_count, sizeof(int));
1129     ifmr.ifm_ulist = media_list;
1130
1131     if (IFM_TYPE(ifmr.ifm_current) != IFM_ETHER) {
1132         VLOG_DBG_RL(&rl, "%s: doesn't appear to be ethernet",
1133                     netdev_get_name(netdev));
1134         error = EINVAL;
1135         goto cleanup;
1136     }
1137
1138     error = af_inet_ioctl(SIOCGIFMEDIA, &ifmr);
1139     if (error) {
1140         VLOG_DBG_RL(&rl, "%s: ioctl(SIOCGIFMEDIA) failed: %s",
1141                     netdev_get_name(netdev), ovs_strerror(error));
1142         goto cleanup;
1143     }
1144
1145     /* Current settings. */
1146     *current = netdev_bsd_parse_media(ifmr.ifm_active);
1147
1148     /* Advertised features. */
1149     *advertised = netdev_bsd_parse_media(ifmr.ifm_current);
1150
1151     /* Supported features. */
1152     *supported = 0;
1153     for (i = 0; i < ifmr.ifm_count; i++) {
1154         *supported |= netdev_bsd_parse_media(ifmr.ifm_ulist[i]);
1155     }
1156
1157     /* Peer advertisements. */
1158     *peer = 0;                  /* XXX */
1159
1160     error = 0;
1161 cleanup:
1162     free(media_list);
1163     return error;
1164 }
1165
1166 /*
1167  * If 'netdev' has an assigned IPv4 address, sets '*in4' to that address and
1168  * '*netmask' to its netmask and returns true.  Otherwise, returns false.
1169  */
1170 static int
1171 netdev_bsd_get_in4(const struct netdev *netdev_, struct in_addr *in4,
1172                    struct in_addr *netmask)
1173 {
1174     struct netdev_bsd *netdev = netdev_bsd_cast(netdev_);
1175     int error = 0;
1176
1177     ovs_mutex_lock(&netdev->mutex);
1178     if (!(netdev->cache_valid & VALID_IN4)) {
1179         struct ifreq ifr;
1180
1181         ifr.ifr_addr.sa_family = AF_INET;
1182         error = af_inet_ifreq_ioctl(netdev_get_kernel_name(netdev_), &ifr,
1183                                     SIOCGIFADDR, "SIOCGIFADDR");
1184         if (!error) {
1185             const struct sockaddr_in *sin;
1186
1187             sin = ALIGNED_CAST(struct sockaddr_in *, &ifr.ifr_addr);
1188             netdev->in4 = sin->sin_addr;
1189             netdev->cache_valid |= VALID_IN4;
1190             error = af_inet_ifreq_ioctl(netdev_get_kernel_name(netdev_), &ifr,
1191                                         SIOCGIFNETMASK, "SIOCGIFNETMASK");
1192             if (!error) {
1193                 *netmask = sin->sin_addr;
1194             }
1195         }
1196     }
1197     if (!error) {
1198         *in4 = netdev->in4;
1199         *netmask = netdev->netmask;
1200     }
1201     ovs_mutex_unlock(&netdev->mutex);
1202
1203     return error ? error : in4->s_addr == INADDR_ANY ? EADDRNOTAVAIL : 0;
1204 }
1205
1206 /*
1207  * Assigns 'addr' as 'netdev''s IPv4 address and 'mask' as its netmask.  If
1208  * 'addr' is INADDR_ANY, 'netdev''s IPv4 address is cleared.  Returns a
1209  * positive errno value.
1210  */
1211 static int
1212 netdev_bsd_set_in4(struct netdev *netdev_, struct in_addr addr,
1213                    struct in_addr mask)
1214 {
1215     struct netdev_bsd *netdev = netdev_bsd_cast(netdev_);
1216     int error;
1217
1218     ovs_mutex_lock(&netdev->mutex);
1219     error = do_set_addr(netdev_, SIOCSIFADDR, "SIOCSIFADDR", addr);
1220     if (!error) {
1221         if (addr.s_addr != INADDR_ANY) {
1222             error = do_set_addr(netdev_, SIOCSIFNETMASK,
1223                                 "SIOCSIFNETMASK", mask);
1224             if (!error) {
1225                 netdev->cache_valid |= VALID_IN4;
1226                 netdev->in4 = addr;
1227                 netdev->netmask = mask;
1228             }
1229         }
1230         netdev_change_seq_changed(netdev_);
1231     }
1232     ovs_mutex_unlock(&netdev->mutex);
1233
1234     return error;
1235 }
1236
1237 static int
1238 netdev_bsd_get_in6(const struct netdev *netdev_, struct in6_addr *in6)
1239 {
1240     struct netdev_bsd *netdev = netdev_bsd_cast(netdev_);
1241     if (!(netdev->cache_valid & VALID_IN6)) {
1242         struct ifaddrs *ifa, *head;
1243         struct sockaddr_in6 *sin6;
1244         const char *netdev_name = netdev_get_name(netdev_);
1245
1246         if (getifaddrs(&head) != 0) {
1247             VLOG_ERR("getifaddrs on %s device failed: %s", netdev_name,
1248                     ovs_strerror(errno));
1249             return errno;
1250         }
1251
1252         for (ifa = head; ifa; ifa = ifa->ifa_next) {
1253             if (ifa->ifa_addr->sa_family == AF_INET6 &&
1254                     !strcmp(ifa->ifa_name, netdev_name)) {
1255                 sin6 = ALIGNED_CAST(struct sockaddr_in6 *, ifa->ifa_addr);
1256                 if (sin6) {
1257                     memcpy(&netdev->in6, &sin6->sin6_addr, sin6->sin6_len);
1258                     netdev->cache_valid |= VALID_IN6;
1259                     *in6 = netdev->in6;
1260                     freeifaddrs(head);
1261                     return 0;
1262                 }
1263             }
1264         }
1265         return EADDRNOTAVAIL;
1266     }
1267     *in6 = netdev->in6;
1268     return 0;
1269 }
1270
1271 #if defined(__NetBSD__)
1272 static char *
1273 netdev_bsd_kernel_name_to_ovs_name(const char *kernel_name)
1274 {
1275     char *ovs_name = NULL;
1276     struct shash device_shash;
1277     struct shash_node *node;
1278
1279     shash_init(&device_shash);
1280     netdev_get_devices(&netdev_tap_class, &device_shash);
1281     SHASH_FOR_EACH(node, &device_shash) {
1282         struct netdev *netdev = node->data;
1283         struct netdev_bsd * const dev = netdev_bsd_cast(netdev);
1284
1285         if (!strcmp(dev->kernel_name, kernel_name)) {
1286             free(ovs_name);
1287             ovs_name = xstrdup(netdev_get_name(&dev->up));
1288         }
1289         netdev_close(netdev);
1290     }
1291     shash_destroy(&device_shash);
1292
1293     return ovs_name ? ovs_name : xstrdup(kernel_name);
1294 }
1295 #endif
1296
1297 static int
1298 netdev_bsd_get_next_hop(const struct in_addr *host OVS_UNUSED,
1299                         struct in_addr *next_hop OVS_UNUSED,
1300                         char **netdev_name OVS_UNUSED)
1301 {
1302 #if defined(__NetBSD__)
1303     static int seq = 0;
1304     struct sockaddr_in sin;
1305     struct sockaddr_dl sdl;
1306     int s;
1307     int i;
1308     struct {
1309         struct rt_msghdr h;
1310         char space[512];
1311     } buf;
1312     struct rt_msghdr *rtm = &buf.h;
1313     const pid_t pid = getpid();
1314     char *cp;
1315     ssize_t ssz;
1316     bool gateway = false;
1317     char *ifname = NULL;
1318     int saved_errno;
1319
1320     memset(next_hop, 0, sizeof(*next_hop));
1321     *netdev_name = NULL;
1322
1323     memset(&sin, 0, sizeof(sin));
1324     sin.sin_len = sizeof(sin);
1325     sin.sin_family = AF_INET;
1326     sin.sin_port = 0;
1327     sin.sin_addr = *host;
1328
1329     memset(&sdl, 0, sizeof(sdl));
1330     sdl.sdl_len = sizeof(sdl);
1331     sdl.sdl_family = AF_LINK;
1332
1333     s = socket(PF_ROUTE, SOCK_RAW, 0);
1334     memset(&buf, 0, sizeof(buf));
1335     rtm->rtm_flags = RTF_HOST|RTF_UP;
1336     rtm->rtm_version = RTM_VERSION;
1337     rtm->rtm_addrs = RTA_DST|RTA_IFP;
1338     cp = (void *)&buf.space;
1339     memcpy(cp, &sin, sizeof(sin));
1340     RT_ADVANCE(cp, (struct sockaddr *)(void *)&sin);
1341     memcpy(cp, &sdl, sizeof(sdl));
1342     RT_ADVANCE(cp, (struct sockaddr *)(void *)&sdl);
1343     rtm->rtm_msglen = cp - (char *)(void *)rtm;
1344     rtm->rtm_seq = ++seq;
1345     rtm->rtm_type = RTM_GET;
1346     rtm->rtm_pid = pid;
1347     write(s, rtm, rtm->rtm_msglen);
1348     memset(&buf, 0, sizeof(buf));
1349     do {
1350         ssz = read(s, &buf, sizeof(buf));
1351     } while (ssz > 0 && (rtm->rtm_seq != seq || rtm->rtm_pid != pid));
1352     saved_errno = errno;
1353     close(s);
1354     if (ssz <= 0) {
1355         if (ssz < 0) {
1356             return saved_errno;
1357         }
1358         return EPIPE; /* XXX */
1359     }
1360     cp = (void *)&buf.space;
1361     for (i = 1; i; i <<= 1) {
1362         if ((rtm->rtm_addrs & i) != 0) {
1363             const struct sockaddr *sa = (const void *)cp;
1364
1365             if ((i == RTA_GATEWAY) && sa->sa_family == AF_INET) {
1366                 const struct sockaddr_in * const sin =
1367                   ALIGNED_CAST(const struct sockaddr_in *, sa);
1368
1369                 *next_hop = sin->sin_addr;
1370                 gateway = true;
1371             }
1372             if ((i == RTA_IFP) && sa->sa_family == AF_LINK) {
1373                 const struct sockaddr_dl * const sdl =
1374                   ALIGNED_CAST(const struct sockaddr_dl *, sa);
1375                 char *kernel_name;
1376
1377                 kernel_name = xmemdup0(sdl->sdl_data, sdl->sdl_nlen);
1378                 ifname = netdev_bsd_kernel_name_to_ovs_name(kernel_name);
1379                 free(kernel_name);
1380             }
1381             RT_ADVANCE(cp, sa);
1382         }
1383     }
1384     if (ifname == NULL) {
1385         return ENXIO;
1386     }
1387     if (!gateway) {
1388         *next_hop = *host;
1389     }
1390     *netdev_name = ifname;
1391     VLOG_DBG("host " IP_FMT " next-hop " IP_FMT " if %s",
1392       IP_ARGS(host->s_addr), IP_ARGS(next_hop->s_addr), *netdev_name);
1393     return 0;
1394 #else
1395     return EOPNOTSUPP;
1396 #endif
1397 }
1398
1399 static int
1400 netdev_bsd_arp_lookup(const struct netdev *netdev OVS_UNUSED,
1401                       ovs_be32 ip OVS_UNUSED,
1402                       uint8_t mac[ETH_ADDR_LEN] OVS_UNUSED)
1403 {
1404 #if defined(__NetBSD__)
1405     const struct rt_msghdr *rtm;
1406     size_t needed;
1407     char *buf;
1408     const char *cp;
1409     const char *ep;
1410     int mib[6];
1411     int error;
1412
1413     buf = NULL;
1414     mib[0] = CTL_NET;
1415     mib[1] = PF_ROUTE;
1416     mib[2] = 0;
1417     mib[3] = AF_INET;
1418     mib[4] = NET_RT_FLAGS;
1419     mib[5] = RTF_LLINFO;
1420     if (sysctl(mib, 6, NULL, &needed, NULL, 0) == -1) {
1421         error = errno;
1422         goto error;
1423     }
1424     buf = xmalloc(needed);
1425     if (sysctl(mib, 6, buf, &needed, NULL, 0) == -1) {
1426         error = errno;
1427         goto error;
1428     }
1429     ep = buf + needed;
1430     for (cp = buf; cp < ep; cp += rtm->rtm_msglen) {
1431         const struct sockaddr_inarp *sina;
1432         const struct sockaddr_dl *sdl;
1433
1434         rtm = (const void *)cp;
1435         sina = (const void *)(rtm + 1);
1436         if (ip != sina->sin_addr.s_addr) {
1437             continue;
1438         }
1439         sdl = (const void *)
1440            ((const char *)(const void *)sina + RT_ROUNDUP(sina->sin_len));
1441         if (sdl->sdl_alen == ETH_ADDR_LEN) {
1442             memcpy(mac, &sdl->sdl_data[sdl->sdl_nlen], ETH_ADDR_LEN);
1443             error = 0;
1444             goto error;
1445         }
1446     }
1447     error = ENXIO;
1448 error:
1449     free(buf);
1450     return error;
1451 #else
1452     return EOPNOTSUPP;
1453 #endif
1454 }
1455
1456 static void
1457 make_in4_sockaddr(struct sockaddr *sa, struct in_addr addr)
1458 {
1459     struct sockaddr_in sin;
1460     memset(&sin, 0, sizeof sin);
1461     sin.sin_family = AF_INET;
1462     sin.sin_addr = addr;
1463     sin.sin_port = 0;
1464
1465     memset(sa, 0, sizeof *sa);
1466     memcpy(sa, &sin, sizeof sin);
1467 }
1468
1469 static int
1470 do_set_addr(struct netdev *netdev,
1471             unsigned long ioctl_nr, const char *ioctl_name,
1472             struct in_addr addr)
1473 {
1474     struct ifreq ifr;
1475     make_in4_sockaddr(&ifr.ifr_addr, addr);
1476     return af_inet_ifreq_ioctl(netdev_get_kernel_name(netdev), &ifr, ioctl_nr,
1477                                ioctl_name);
1478 }
1479
1480 static int
1481 nd_to_iff_flags(enum netdev_flags nd)
1482 {
1483     int iff = 0;
1484     if (nd & NETDEV_UP) {
1485         iff |= IFF_UP;
1486     }
1487     if (nd & NETDEV_PROMISC) {
1488         iff |= IFF_PROMISC;
1489 #if defined(IFF_PPROMISC)
1490         iff |= IFF_PPROMISC;
1491 #endif
1492     }
1493     if (nd & NETDEV_LOOPBACK) {
1494         iff |= IFF_LOOPBACK;
1495     }
1496     return iff;
1497 }
1498
1499 static int
1500 iff_to_nd_flags(int iff)
1501 {
1502     enum netdev_flags nd = 0;
1503     if (iff & IFF_UP) {
1504         nd |= NETDEV_UP;
1505     }
1506     if (iff & IFF_PROMISC) {
1507         nd |= NETDEV_PROMISC;
1508     }
1509     if (iff & IFF_LOOPBACK) {
1510         nd |= NETDEV_LOOPBACK;
1511     }
1512     return nd;
1513 }
1514
1515 static int
1516 netdev_bsd_update_flags(struct netdev *netdev_, enum netdev_flags off,
1517                         enum netdev_flags on, enum netdev_flags *old_flagsp)
1518 {
1519     int old_flags, new_flags;
1520     int error;
1521
1522     error = get_flags(netdev_, &old_flags);
1523     if (!error) {
1524         *old_flagsp = iff_to_nd_flags(old_flags);
1525         new_flags = (old_flags & ~nd_to_iff_flags(off)) | nd_to_iff_flags(on);
1526         if (new_flags != old_flags) {
1527             error = set_flags(netdev_get_kernel_name(netdev_), new_flags);
1528             netdev_change_seq_changed(netdev_);
1529         }
1530     }
1531     return error;
1532 }
1533
1534 /* Linux has also different GET_STATS, SET_STATS,
1535  * GET_STATUS)
1536  */
1537 #define NETDEV_BSD_CLASS(NAME, CONSTRUCT,            \
1538                          GET_FEATURES)               \
1539 {                                                    \
1540     NAME,                                            \
1541                                                      \
1542     NULL, /* init */                                 \
1543     netdev_bsd_run,                                  \
1544     netdev_bsd_wait,                                 \
1545     netdev_bsd_alloc,                                \
1546     CONSTRUCT,                                       \
1547     netdev_bsd_destruct,                             \
1548     netdev_bsd_dealloc,                              \
1549     NULL, /* get_config */                           \
1550     NULL, /* set_config */                           \
1551     NULL, /* get_tunnel_config */                    \
1552                                                      \
1553     netdev_bsd_send,                                 \
1554     netdev_bsd_send_wait,                            \
1555                                                      \
1556     netdev_bsd_set_etheraddr,                        \
1557     netdev_bsd_get_etheraddr,                        \
1558     netdev_bsd_get_mtu,                              \
1559     NULL, /* set_mtu */                              \
1560     netdev_bsd_get_ifindex,                          \
1561     netdev_bsd_get_carrier,                          \
1562     NULL, /* get_carrier_resets */                   \
1563     NULL, /* set_miimon_interval */                  \
1564     netdev_bsd_get_stats,                            \
1565     NULL, /* set_stats */                            \
1566                                                      \
1567     GET_FEATURES,                                    \
1568     NULL, /* set_advertisement */                    \
1569     NULL, /* set_policing */                         \
1570     NULL, /* get_qos_type */                         \
1571     NULL, /* get_qos_capabilities */                 \
1572     NULL, /* get_qos */                              \
1573     NULL, /* set_qos */                              \
1574     NULL, /* get_queue */                            \
1575     NULL, /* set_queue */                            \
1576     NULL, /* delete_queue */                         \
1577     NULL, /* get_queue_stats */                      \
1578     NULL, /* queue_dump_start */                     \
1579     NULL, /* queue_dump_next */                      \
1580     NULL, /* queue_dump_done */                      \
1581     NULL, /* dump_queue_stats */                     \
1582                                                      \
1583     netdev_bsd_get_in4,                              \
1584     netdev_bsd_set_in4,                              \
1585     netdev_bsd_get_in6,                              \
1586     NULL, /* add_router */                           \
1587     netdev_bsd_get_next_hop,                         \
1588     NULL, /* get_status */                           \
1589     netdev_bsd_arp_lookup, /* arp_lookup */          \
1590                                                      \
1591     netdev_bsd_update_flags,                         \
1592                                                      \
1593     netdev_bsd_rxq_alloc,                            \
1594     netdev_bsd_rxq_construct,                        \
1595     netdev_bsd_rxq_destruct,                         \
1596     netdev_bsd_rxq_dealloc,                          \
1597     netdev_bsd_rxq_recv,                             \
1598     netdev_bsd_rxq_wait,                             \
1599     netdev_bsd_rxq_drain,                            \
1600 }
1601
1602 const struct netdev_class netdev_bsd_class =
1603     NETDEV_BSD_CLASS(
1604         "system",
1605         netdev_bsd_construct_system,
1606         netdev_bsd_get_features);
1607
1608 const struct netdev_class netdev_tap_class =
1609     NETDEV_BSD_CLASS(
1610         "tap",
1611         netdev_bsd_construct_tap,
1612         netdev_bsd_get_features);
1613 \f
1614
1615 static void
1616 destroy_tap(int fd, const char *name)
1617 {
1618     struct ifreq ifr;
1619
1620     close(fd);
1621     strcpy(ifr.ifr_name, name);
1622     /* XXX What to do if this call fails? */
1623     af_inet_ioctl(SIOCIFDESTROY, &ifr);
1624 }
1625
1626 static int
1627 get_flags(const struct netdev *netdev, int *flags)
1628 {
1629     struct ifreq ifr;
1630     int error;
1631
1632     error = af_inet_ifreq_ioctl(netdev_get_kernel_name(netdev), &ifr,
1633                                 SIOCGIFFLAGS, "SIOCGIFFLAGS");
1634
1635     *flags = ifr_get_flags(&ifr);
1636
1637     return error;
1638 }
1639
1640 static int
1641 set_flags(const char *name, int flags)
1642 {
1643     struct ifreq ifr;
1644
1645     ifr_set_flags(&ifr, flags);
1646
1647     return af_inet_ifreq_ioctl(name, &ifr, SIOCSIFFLAGS, "SIOCSIFFLAGS");
1648 }
1649
1650 static int
1651 get_ifindex(const struct netdev *netdev_, int *ifindexp)
1652 {
1653     struct netdev_bsd *netdev = netdev_bsd_cast(netdev_);
1654     *ifindexp = 0;
1655     if (!(netdev->cache_valid & VALID_IFINDEX)) {
1656         int ifindex = if_nametoindex(netdev_get_name(netdev_));
1657         if (ifindex <= 0) {
1658             return errno;
1659         }
1660         netdev->cache_valid |= VALID_IFINDEX;
1661         netdev->ifindex = ifindex;
1662     }
1663     *ifindexp = netdev->ifindex;
1664     return 0;
1665 }
1666
1667 static int
1668 get_etheraddr(const char *netdev_name, uint8_t ea[ETH_ADDR_LEN])
1669 {
1670     struct ifaddrs *head;
1671     struct ifaddrs *ifa;
1672     struct sockaddr_dl *sdl;
1673
1674     if (getifaddrs(&head) != 0) {
1675         VLOG_ERR("getifaddrs on %s device failed: %s", netdev_name,
1676                 ovs_strerror(errno));
1677         return errno;
1678     }
1679
1680     for (ifa = head; ifa; ifa = ifa->ifa_next) {
1681         if (ifa->ifa_addr->sa_family == AF_LINK) {
1682             if (!strcmp(ifa->ifa_name, netdev_name)) {
1683                 sdl = ALIGNED_CAST(struct sockaddr_dl *, ifa->ifa_addr);
1684                 if (sdl) {
1685                     memcpy(ea, LLADDR(sdl), sdl->sdl_alen);
1686                     freeifaddrs(head);
1687                     return 0;
1688                 }
1689             }
1690         }
1691     }
1692
1693     VLOG_ERR("could not find ethernet address for %s device", netdev_name);
1694     freeifaddrs(head);
1695     return ENODEV;
1696 }
1697
1698 static int
1699 set_etheraddr(const char *netdev_name OVS_UNUSED, int hwaddr_family OVS_UNUSED,
1700               int hwaddr_len OVS_UNUSED,
1701               const uint8_t mac[ETH_ADDR_LEN] OVS_UNUSED)
1702 {
1703 #if defined(__FreeBSD__)
1704     struct ifreq ifr;
1705     int error;
1706
1707     memset(&ifr, 0, sizeof ifr);
1708     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
1709     ifr.ifr_addr.sa_family = hwaddr_family;
1710     ifr.ifr_addr.sa_len = hwaddr_len;
1711     memcpy(ifr.ifr_addr.sa_data, mac, hwaddr_len);
1712     error = af_inet_ioctl(SIOCSIFLLADDR, &ifr);
1713     if (error) {
1714         VLOG_ERR("ioctl(SIOCSIFLLADDR) on %s device failed: %s",
1715                  netdev_name, ovs_strerror(error));
1716         return error;
1717     }
1718     return 0;
1719 #elif defined(__NetBSD__)
1720     struct if_laddrreq req;
1721     struct sockaddr_dl *sdl;
1722     struct sockaddr_storage oldaddr;
1723     int error;
1724
1725     /*
1726      * get the old address, add new one, and then remove old one.
1727      */
1728
1729     if (hwaddr_len != ETH_ADDR_LEN) {
1730         /* just to be safe about sockaddr storage size */
1731         return EOPNOTSUPP;
1732     }
1733     memset(&req, 0, sizeof(req));
1734     strncpy(req.iflr_name, netdev_name, sizeof(req.iflr_name));
1735     req.addr.ss_len = sizeof(req.addr);
1736     req.addr.ss_family = hwaddr_family;
1737     sdl = (struct sockaddr_dl *)&req.addr;
1738     sdl->sdl_alen = hwaddr_len;
1739
1740     error = af_link_ioctl(SIOCGLIFADDR, &req);
1741     if (error) {
1742         return error;
1743     }
1744     if (!memcmp(&sdl->sdl_data[sdl->sdl_nlen], mac, hwaddr_len)) {
1745         return 0;
1746     }
1747     oldaddr = req.addr;
1748
1749     memset(&req, 0, sizeof(req));
1750     strncpy(req.iflr_name, netdev_name, sizeof(req.iflr_name));
1751     req.flags = IFLR_ACTIVE;
1752     sdl = (struct sockaddr_dl *)&req.addr;
1753     sdl->sdl_len = offsetof(struct sockaddr_dl, sdl_data) + hwaddr_len;
1754     sdl->sdl_alen = hwaddr_len;
1755     sdl->sdl_family = hwaddr_family;
1756     memcpy(sdl->sdl_data, mac, hwaddr_len);
1757     error = af_link_ioctl(SIOCALIFADDR, &req);
1758     if (error) {
1759         return error;
1760     }
1761
1762     memset(&req, 0, sizeof(req));
1763     strncpy(req.iflr_name, netdev_name, sizeof(req.iflr_name));
1764     req.addr = oldaddr;
1765     return af_link_ioctl(SIOCDLIFADDR, &req);
1766 #else
1767 #error not implemented
1768 #endif
1769 }
1770
1771 static int
1772 ifr_get_flags(const struct ifreq *ifr)
1773 {
1774 #ifdef HAVE_STRUCT_IFREQ_IFR_FLAGSHIGH
1775     return (ifr->ifr_flagshigh << 16) | (ifr->ifr_flags & 0xffff);
1776 #else
1777     return ifr->ifr_flags;
1778 #endif
1779 }
1780
1781 static void
1782 ifr_set_flags(struct ifreq *ifr, int flags)
1783 {
1784 #ifdef HAVE_STRUCT_IFREQ_IFR_FLAGSHIGH
1785     ifr->ifr_flags = flags & 0xffff;
1786     ifr->ifr_flagshigh = flags >> 16;
1787 #else
1788     ifr->ifr_flags = flags;
1789 #endif
1790 }
1791
1792 #if defined(__NetBSD__)
1793 /* Calls ioctl() on an AF_LINK sock, passing the specified 'command' and
1794  * 'arg'.  Returns 0 if successful, otherwise a positive errno value. */
1795 int
1796 af_link_ioctl(unsigned long command, const void *arg)
1797 {
1798     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
1799     static int sock;
1800
1801     if (ovsthread_once_start(&once)) {
1802         sock = socket(AF_LINK, SOCK_DGRAM, 0);
1803         if (sock < 0) {
1804             sock = -errno;
1805             VLOG_ERR("failed to create link socket: %s", ovs_strerror(errno));
1806         }
1807         ovsthread_once_done(&once);
1808     }
1809
1810     return (sock < 0 ? -sock
1811             : ioctl(sock, command, arg) == -1 ? errno
1812             : 0);
1813 }
1814 #endif