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