netdev-bsd: compilation fixes
[sliver-openvswitch.git] / lib / netdev-bsd.c
1 /*
2  * Copyright (c) 2011, 2013 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 <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_rxq_bsd {
71     struct netdev_rxq 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_rxq_bsd *
171 netdev_rxq_bsd_cast(const struct netdev_rxq *rxq)
172 {
173     ovs_assert(is_netdev_bsd_class(netdev_get_class(rxq->netdev)));
174     return CONTAINER_OF(rxq, struct netdev_rxq_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_rxq *
479 netdev_bsd_rxq_alloc(void)
480 {
481     struct netdev_rxq_bsd *rxq = xzalloc(sizeof *rxq);
482     return &rxq->up;
483 }
484
485 static int
486 netdev_bsd_rxq_construct(struct netdev_rxq *rxq_)
487 {
488     struct netdev_rxq_bsd *rxq = netdev_rxq_bsd_cast(rxq_);
489     struct netdev *netdev_ = rxq->up.netdev;
490     struct netdev_bsd *netdev = netdev_bsd_cast(netdev_);
491     int error;
492
493     if (!strcmp(netdev_get_type(netdev_), "tap")) {
494         rxq->pcap_handle = NULL;
495         rxq->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                                      &rxq->pcap_handle, &rxq->fd);
501         ovs_mutex_unlock(&netdev->mutex);
502     }
503
504     return error;
505 }
506
507 static void
508 netdev_bsd_rxq_destruct(struct netdev_rxq *rxq_)
509 {
510     struct netdev_rxq_bsd *rxq = netdev_rxq_bsd_cast(rxq_);
511
512     if (rxq->pcap_handle) {
513         pcap_close(rxq->pcap_handle);
514     }
515 }
516
517 static void
518 netdev_bsd_rxq_dealloc(struct netdev_rxq *rxq_)
519 {
520     struct netdev_rxq_bsd *rxq = netdev_rxq_bsd_cast(rxq_);
521
522     free(rxq);
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 rxq->pcap.
571  */
572 static int
573 netdev_rxq_bsd_recv_pcap(struct netdev_rxq_bsd *rxq, 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(rxq->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  * 'rxq->fd' is initialized with the tap file descriptor.
603  */
604 static int
605 netdev_rxq_bsd_recv_tap(struct netdev_rxq_bsd *rxq, struct ofpbuf *buffer)
606 {
607     size_t size = ofpbuf_tailroom(buffer);
608
609     for (;;) {
610         ssize_t retval = read(rxq->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_rxq_get_name(&rxq->up));
618             }
619             return errno;
620         }
621     }
622 }
623
624 static int
625 netdev_bsd_rxq_recv(struct netdev_rxq *rxq_, struct ofpbuf **packet, int *c)
626 {
627     struct netdev_rxq_bsd *rxq = netdev_rxq_bsd_cast(rxq_);
628     struct netdev *netdev = rxq->up.netdev;
629     struct ofpbuf *buffer;
630     ssize_t retval;
631     int mtu;
632
633     if (netdev_bsd_get_mtu(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 = (rxq->pcap_handle
640             ? netdev_rxq_bsd_recv_pcap(rxq, buffer)
641             : netdev_rxq_bsd_recv_tap(rxq, 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_rxq_recv() on 'rxq'.
656  */
657 static void
658 netdev_bsd_rxq_wait(struct netdev_rxq *rxq_)
659 {
660     struct netdev_rxq_bsd *rxq = netdev_rxq_bsd_cast(rxq_);
661
662     poll_fd_wait(rxq->fd, POLLIN);
663 }
664
665 /* Discards all packets waiting to be received from 'rxq'. */
666 static int
667 netdev_bsd_rxq_drain(struct netdev_rxq *rxq_)
668 {
669     struct ifreq ifr;
670     struct netdev_rxq_bsd *rxq = netdev_rxq_bsd_cast(rxq_);
671
672     strcpy(ifr.ifr_name, netdev_get_kernel_name(netdev_rxq_get_netdev(rxq_)));
673     if (ioctl(rxq->fd, BIOCFLUSH, &ifr) == -1) {
674         VLOG_DBG_RL(&rl, "%s: ioctl(BIOCFLUSH) failed: %s",
675                     netdev_rxq_get_name(rxq_), 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_, struct ofpbuf *pkt, bool may_steal)
687 {
688     struct netdev_bsd *dev = netdev_bsd_cast(netdev_);
689     const char *name = netdev_get_name(netdev_);
690     const void *data = pkt->data;
691     size_t size = pkt->size;
692     int error;
693
694     ovs_mutex_lock(&dev->mutex);
695     if (dev->tap_fd < 0 && !dev->pcap) {
696         error = netdev_bsd_open_pcap(name, &dev->pcap, &dev->fd);
697     } else {
698         error = 0;
699     }
700
701     while (!error) {
702         ssize_t retval;
703         if (dev->tap_fd >= 0) {
704             retval = write(dev->tap_fd, data, size);
705         } else {
706             retval = pcap_inject(dev->pcap, data, size);
707         }
708         if (retval < 0) {
709             if (errno == EINTR) {
710                 continue;
711             } else {
712                 error = errno;
713                 if (error != EAGAIN) {
714                     VLOG_WARN_RL(&rl, "error sending Ethernet packet on %s: "
715                                  "%s", name, ovs_strerror(error));
716                 }
717             }
718         } else if (retval != size) {
719             VLOG_WARN_RL(&rl, "sent partial Ethernet packet (%"PRIuSIZE"d bytes of "
720                          "%"PRIuSIZE") on %s", retval, size, name);
721             error = EMSGSIZE;
722         } else {
723             break;
724         }
725     }
726
727     ovs_mutex_unlock(&dev->mutex);
728     if (may_steal) {
729         ofpbuf_delete(pkt);
730     }
731
732     return error;
733 }
734
735 /*
736  * Registers with the poll loop to wake up from the next call to poll_block()
737  * when the packet transmission queue has sufficient room to transmit a packet
738  * with netdev_send().
739  */
740 static void
741 netdev_bsd_send_wait(struct netdev *netdev_)
742 {
743     struct netdev_bsd *dev = netdev_bsd_cast(netdev_);
744
745     ovs_mutex_lock(&dev->mutex);
746     if (dev->tap_fd >= 0) {
747         /* TAP device always accepts packets. */
748         poll_immediate_wake();
749     } else if (dev->pcap) {
750         poll_fd_wait(dev->fd, POLLOUT);
751     } else {
752         /* We haven't even tried to send a packet yet. */
753         poll_immediate_wake();
754     }
755     ovs_mutex_unlock(&dev->mutex);
756 }
757
758 /*
759  * Attempts to set 'netdev''s MAC address to 'mac'.  Returns 0 if successful,
760  * otherwise a positive errno value.
761  */
762 static int
763 netdev_bsd_set_etheraddr(struct netdev *netdev_,
764                          const uint8_t mac[ETH_ADDR_LEN])
765 {
766     struct netdev_bsd *netdev = netdev_bsd_cast(netdev_);
767     int error = 0;
768
769     ovs_mutex_lock(&netdev->mutex);
770     if (!(netdev->cache_valid & VALID_ETHERADDR)
771         || !eth_addr_equals(netdev->etheraddr, mac)) {
772         error = set_etheraddr(netdev_get_kernel_name(netdev_), AF_LINK,
773                               ETH_ADDR_LEN, mac);
774         if (!error) {
775             netdev->cache_valid |= VALID_ETHERADDR;
776             memcpy(netdev->etheraddr, mac, ETH_ADDR_LEN);
777             seq_change(connectivity_seq_get());
778         }
779     }
780     ovs_mutex_unlock(&netdev->mutex);
781
782     return error;
783 }
784
785 /*
786  * Returns a pointer to 'netdev''s MAC address.  The caller must not modify or
787  * free the returned buffer.
788  */
789 static int
790 netdev_bsd_get_etheraddr(const struct netdev *netdev_,
791                          uint8_t mac[ETH_ADDR_LEN])
792 {
793     struct netdev_bsd *netdev = netdev_bsd_cast(netdev_);
794     int error = 0;
795
796     ovs_mutex_lock(&netdev->mutex);
797     if (!(netdev->cache_valid & VALID_ETHERADDR)) {
798         error = get_etheraddr(netdev_get_kernel_name(netdev_),
799                               netdev->etheraddr);
800         if (!error) {
801             netdev->cache_valid |= VALID_ETHERADDR;
802         }
803     }
804     if (!error) {
805         memcpy(mac, netdev->etheraddr, ETH_ADDR_LEN);
806     }
807     ovs_mutex_unlock(&netdev->mutex);
808
809     return error;
810 }
811
812 /*
813  * Returns the maximum size of transmitted (and received) packets on 'netdev',
814  * in bytes, not including the hardware header; thus, this is typically 1500
815  * bytes for Ethernet devices.
816  */
817 static int
818 netdev_bsd_get_mtu(const struct netdev *netdev_, int *mtup)
819 {
820     struct netdev_bsd *netdev = netdev_bsd_cast(netdev_);
821     int error = 0;
822
823     ovs_mutex_lock(&netdev->mutex);
824     if (!(netdev->cache_valid & VALID_MTU)) {
825         struct ifreq ifr;
826
827         error = af_inet_ifreq_ioctl(netdev_get_kernel_name(netdev_), &ifr,
828                                     SIOCGIFMTU, "SIOCGIFMTU");
829         if (!error) {
830             netdev->mtu = ifr.ifr_mtu;
831             netdev->cache_valid |= VALID_MTU;
832         }
833     }
834     if (!error) {
835         *mtup = netdev->mtu;
836     }
837     ovs_mutex_unlock(&netdev->mutex);
838
839     return 0;
840 }
841
842 static int
843 netdev_bsd_get_ifindex(const struct netdev *netdev_)
844 {
845     struct netdev_bsd *netdev = netdev_bsd_cast(netdev_);
846     int ifindex, error;
847
848     ovs_mutex_lock(&netdev->mutex);
849     error = get_ifindex(netdev_, &ifindex);
850     ovs_mutex_unlock(&netdev->mutex);
851
852     return error ? -error : ifindex;
853 }
854
855 static int
856 netdev_bsd_get_carrier(const struct netdev *netdev_, bool *carrier)
857 {
858     struct netdev_bsd *netdev = netdev_bsd_cast(netdev_);
859     int error = 0;
860
861     ovs_mutex_lock(&netdev->mutex);
862     if (!(netdev->cache_valid & VALID_CARRIER)) {
863         struct ifmediareq ifmr;
864
865         memset(&ifmr, 0, sizeof(ifmr));
866         strncpy(ifmr.ifm_name, netdev_get_kernel_name(netdev_),
867                 sizeof ifmr.ifm_name);
868
869         error = af_inet_ioctl(SIOCGIFMEDIA, &ifmr);
870         if (!error) {
871             netdev->carrier = (ifmr.ifm_status & IFM_ACTIVE) == IFM_ACTIVE;
872             netdev->cache_valid |= VALID_CARRIER;
873
874             /* If the interface doesn't report whether the media is active,
875              * just assume it is active. */
876             if ((ifmr.ifm_status & IFM_AVALID) == 0) {
877                 netdev->carrier = true;
878             }
879         } else {
880             VLOG_DBG_RL(&rl, "%s: ioctl(SIOCGIFMEDIA) failed: %s",
881                         netdev_get_name(netdev_), ovs_strerror(error));
882         }
883     }
884     if (!error) {
885         *carrier = netdev->carrier;
886     }
887     ovs_mutex_unlock(&netdev->mutex);
888
889     return error;
890 }
891
892 static void
893 convert_stats_system(struct netdev_stats *stats, const struct if_data *ifd)
894 {
895     /*
896      * note: UINT64_MAX means unsupported
897      */
898     stats->rx_packets = ifd->ifi_ipackets;
899     stats->tx_packets = ifd->ifi_opackets;
900     stats->rx_bytes = ifd->ifi_obytes;
901     stats->tx_bytes = ifd->ifi_ibytes;
902     stats->rx_errors = ifd->ifi_ierrors;
903     stats->tx_errors = ifd->ifi_oerrors;
904     stats->rx_dropped = ifd->ifi_iqdrops;
905     stats->tx_dropped = UINT64_MAX;
906     stats->multicast = ifd->ifi_imcasts;
907     stats->collisions = ifd->ifi_collisions;
908     stats->rx_length_errors = UINT64_MAX;
909     stats->rx_over_errors = UINT64_MAX;
910     stats->rx_crc_errors = UINT64_MAX;
911     stats->rx_frame_errors = UINT64_MAX;
912     stats->rx_fifo_errors = UINT64_MAX;
913     stats->rx_missed_errors = UINT64_MAX;
914     stats->tx_aborted_errors = UINT64_MAX;
915     stats->tx_carrier_errors = UINT64_MAX;
916     stats->tx_fifo_errors = UINT64_MAX;
917     stats->tx_heartbeat_errors = UINT64_MAX;
918     stats->tx_window_errors = UINT64_MAX;
919 }
920
921 static void
922 convert_stats_tap(struct netdev_stats *stats, const struct if_data *ifd)
923 {
924     /*
925      * Similar to convert_stats_system but swapping rxq and tx
926      * because 'ifd' is stats for the network interface side of the
927      * tap device and what the caller wants is one for the character
928      * device side.
929      *
930      * note: UINT64_MAX means unsupported
931      */
932     stats->rx_packets = ifd->ifi_opackets;
933     stats->tx_packets = ifd->ifi_ipackets;
934     stats->rx_bytes = ifd->ifi_ibytes;
935     stats->tx_bytes = ifd->ifi_obytes;
936     stats->rx_errors = ifd->ifi_oerrors;
937     stats->tx_errors = ifd->ifi_ierrors;
938     stats->rx_dropped = UINT64_MAX;
939     stats->tx_dropped = ifd->ifi_iqdrops;
940     stats->multicast = ifd->ifi_omcasts;
941     stats->collisions = UINT64_MAX;
942     stats->rx_length_errors = UINT64_MAX;
943     stats->rx_over_errors = UINT64_MAX;
944     stats->rx_crc_errors = UINT64_MAX;
945     stats->rx_frame_errors = UINT64_MAX;
946     stats->rx_fifo_errors = UINT64_MAX;
947     stats->rx_missed_errors = UINT64_MAX;
948     stats->tx_aborted_errors = UINT64_MAX;
949     stats->tx_carrier_errors = UINT64_MAX;
950     stats->tx_fifo_errors = UINT64_MAX;
951     stats->tx_heartbeat_errors = UINT64_MAX;
952     stats->tx_window_errors = UINT64_MAX;
953 }
954
955 static void
956 convert_stats(const struct netdev *netdev, struct netdev_stats *stats,
957               const struct if_data *ifd)
958 {
959     if (netdev_bsd_cast(netdev)->tap_fd == -1) {
960         convert_stats_system(stats, ifd);
961     } else {
962         convert_stats_tap(stats, ifd);
963     }
964 }
965
966 /* Retrieves current device stats for 'netdev'. */
967 static int
968 netdev_bsd_get_stats(const struct netdev *netdev_, struct netdev_stats *stats)
969 {
970 #if defined(__FreeBSD__)
971     int if_count, i;
972     int mib[6];
973     size_t len;
974     struct ifmibdata ifmd;
975
976
977     mib[0] = CTL_NET;
978     mib[1] = PF_LINK;
979     mib[2] = NETLINK_GENERIC;
980     mib[3] = IFMIB_SYSTEM;
981     mib[4] = IFMIB_IFCOUNT;
982
983     len = sizeof(if_count);
984
985     if (sysctl(mib, 5, &if_count, &len, (void *)0, 0) == -1) {
986         VLOG_DBG_RL(&rl, "%s: sysctl failed: %s",
987                     netdev_get_name(netdev_), ovs_strerror(errno));
988         return errno;
989     }
990
991     mib[5] = IFDATA_GENERAL;
992     mib[3] = IFMIB_IFDATA;
993     len = sizeof(ifmd);
994     for (i = 1; i <= if_count; i++) {
995         mib[4] = i; //row
996         if (sysctl(mib, 6, &ifmd, &len, (void *)0, 0) == -1) {
997             VLOG_DBG_RL(&rl, "%s: sysctl failed: %s",
998                         netdev_get_name(netdev_), ovs_strerror(errno));
999             return errno;
1000         } else if (!strcmp(ifmd.ifmd_name, netdev_get_name(netdev_))) {
1001             convert_stats(netdev, stats, &ifdr.ifdr_data);
1002             break;
1003         }
1004     }
1005
1006     return 0;
1007 #elif defined(__NetBSD__)
1008     struct ifdatareq ifdr;
1009     int error;
1010
1011     memset(&ifdr, 0, sizeof(ifdr));
1012     strncpy(ifdr.ifdr_name, netdev_get_kernel_name(netdev_),
1013             sizeof(ifdr.ifdr_name));
1014     error = af_link_ioctl(SIOCGIFDATA, &ifdr);
1015     if (!error) {
1016         convert_stats(netdev_, stats, &ifdr.ifdr_data);
1017     }
1018     return error;
1019 #else
1020 #error not implemented
1021 #endif
1022 }
1023
1024 static uint32_t
1025 netdev_bsd_parse_media(int media)
1026 {
1027     uint32_t supported = 0;
1028     bool half_duplex = media & IFM_HDX ? true : false;
1029
1030     switch (IFM_SUBTYPE(media)) {
1031     case IFM_10_2:
1032     case IFM_10_5:
1033     case IFM_10_STP:
1034     case IFM_10_T:
1035         supported |= half_duplex ? NETDEV_F_10MB_HD : NETDEV_F_10MB_FD;
1036         supported |= NETDEV_F_COPPER;
1037         break;
1038
1039     case IFM_10_FL:
1040         supported |= half_duplex ? NETDEV_F_10MB_HD : NETDEV_F_10MB_FD;
1041         supported |= NETDEV_F_FIBER;
1042         break;
1043
1044     case IFM_100_T2:
1045     case IFM_100_T4:
1046     case IFM_100_TX:
1047     case IFM_100_VG:
1048         supported |= half_duplex ? NETDEV_F_100MB_HD : NETDEV_F_100MB_FD;
1049         supported |= NETDEV_F_COPPER;
1050         break;
1051
1052     case IFM_100_FX:
1053         supported |= half_duplex ? NETDEV_F_100MB_HD : NETDEV_F_100MB_FD;
1054         supported |= NETDEV_F_FIBER;
1055         break;
1056
1057     case IFM_1000_CX:
1058     case IFM_1000_T:
1059         supported |= half_duplex ? NETDEV_F_1GB_HD : NETDEV_F_1GB_FD;
1060         supported |= NETDEV_F_COPPER;
1061         break;
1062
1063     case IFM_1000_LX:
1064     case IFM_1000_SX:
1065         supported |= half_duplex ? NETDEV_F_1GB_HD : NETDEV_F_1GB_FD;
1066         supported |= NETDEV_F_FIBER;
1067         break;
1068
1069     case IFM_10G_CX4:
1070         supported |= NETDEV_F_10GB_FD;
1071         supported |= NETDEV_F_COPPER;
1072         break;
1073
1074     case IFM_10G_LR:
1075     case IFM_10G_SR:
1076         supported |= NETDEV_F_10GB_FD;
1077         supported |= NETDEV_F_FIBER;
1078         break;
1079
1080     default:
1081         return 0;
1082     }
1083
1084     if (IFM_SUBTYPE(media) == IFM_AUTO) {
1085         supported |= NETDEV_F_AUTONEG;
1086     }
1087     /*
1088     if (media & IFM_ETH_FMASK) {
1089         supported |= NETDEV_F_PAUSE;
1090     }
1091     */
1092
1093     return supported;
1094 }
1095
1096 /*
1097  * Stores the features supported by 'netdev' into each of '*current',
1098  * '*advertised', '*supported', and '*peer' that are non-null.  Each value is a
1099  * bitmap of "enum ofp_port_features" bits, in host byte order.  Returns 0 if
1100  * successful, otherwise a positive errno value.  On failure, all of the
1101  * passed-in values are set to 0.
1102  */
1103 static int
1104 netdev_bsd_get_features(const struct netdev *netdev,
1105                         enum netdev_features *current, uint32_t *advertised,
1106                         enum netdev_features *supported, uint32_t *peer)
1107 {
1108     struct ifmediareq ifmr;
1109     int *media_list;
1110     int i;
1111     int error;
1112
1113
1114     /* XXX Look into SIOCGIFCAP instead of SIOCGIFMEDIA */
1115
1116     memset(&ifmr, 0, sizeof(ifmr));
1117     strncpy(ifmr.ifm_name, netdev_get_name(netdev), sizeof ifmr.ifm_name);
1118
1119     /* We make two SIOCGIFMEDIA ioctl calls.  The first to determine the
1120      * number of supported modes, and a second with a buffer to retrieve
1121      * them. */
1122     error = af_inet_ioctl(SIOCGIFMEDIA, &ifmr);
1123     if (error) {
1124         VLOG_DBG_RL(&rl, "%s: ioctl(SIOCGIFMEDIA) failed: %s",
1125                     netdev_get_name(netdev), ovs_strerror(error));
1126         return error;
1127     }
1128
1129     media_list = xcalloc(ifmr.ifm_count, sizeof(int));
1130     ifmr.ifm_ulist = media_list;
1131
1132     if (IFM_TYPE(ifmr.ifm_current) != IFM_ETHER) {
1133         VLOG_DBG_RL(&rl, "%s: doesn't appear to be ethernet",
1134                     netdev_get_name(netdev));
1135         error = EINVAL;
1136         goto cleanup;
1137     }
1138
1139     error = af_inet_ioctl(SIOCGIFMEDIA, &ifmr);
1140     if (error) {
1141         VLOG_DBG_RL(&rl, "%s: ioctl(SIOCGIFMEDIA) failed: %s",
1142                     netdev_get_name(netdev), ovs_strerror(error));
1143         goto cleanup;
1144     }
1145
1146     /* Current settings. */
1147     *current = netdev_bsd_parse_media(ifmr.ifm_active);
1148
1149     /* Advertised features. */
1150     *advertised = netdev_bsd_parse_media(ifmr.ifm_current);
1151
1152     /* Supported features. */
1153     *supported = 0;
1154     for (i = 0; i < ifmr.ifm_count; i++) {
1155         *supported |= netdev_bsd_parse_media(ifmr.ifm_ulist[i]);
1156     }
1157
1158     /* Peer advertisements. */
1159     *peer = 0;                  /* XXX */
1160
1161     error = 0;
1162 cleanup:
1163     free(media_list);
1164     return error;
1165 }
1166
1167 /*
1168  * If 'netdev' has an assigned IPv4 address, sets '*in4' to that address and
1169  * '*netmask' to its netmask and returns true.  Otherwise, returns false.
1170  */
1171 static int
1172 netdev_bsd_get_in4(const struct netdev *netdev_, struct in_addr *in4,
1173                    struct in_addr *netmask)
1174 {
1175     struct netdev_bsd *netdev = netdev_bsd_cast(netdev_);
1176     int error = 0;
1177
1178     ovs_mutex_lock(&netdev->mutex);
1179     if (!(netdev->cache_valid & VALID_IN4)) {
1180         struct ifreq ifr;
1181
1182         ifr.ifr_addr.sa_family = AF_INET;
1183         error = af_inet_ifreq_ioctl(netdev_get_kernel_name(netdev_), &ifr,
1184                                     SIOCGIFADDR, "SIOCGIFADDR");
1185         if (!error) {
1186             const struct sockaddr_in *sin;
1187
1188             sin = (struct sockaddr_in *) &ifr.ifr_addr;
1189             netdev->in4 = sin->sin_addr;
1190             netdev->cache_valid |= VALID_IN4;
1191             error = af_inet_ifreq_ioctl(netdev_get_kernel_name(netdev_), &ifr,
1192                                         SIOCGIFNETMASK, "SIOCGIFNETMASK");
1193             if (!error) {
1194                 *netmask = sin->sin_addr;
1195             }
1196         }
1197     }
1198     if (!error) {
1199         *in4 = netdev->in4;
1200         *netmask = netdev->netmask;
1201     }
1202     ovs_mutex_unlock(&netdev->mutex);
1203
1204     return error ? error : in4->s_addr == INADDR_ANY ? EADDRNOTAVAIL : 0;
1205 }
1206
1207 /*
1208  * Assigns 'addr' as 'netdev''s IPv4 address and 'mask' as its netmask.  If
1209  * 'addr' is INADDR_ANY, 'netdev''s IPv4 address is cleared.  Returns a
1210  * positive errno value.
1211  */
1212 static int
1213 netdev_bsd_set_in4(struct netdev *netdev_, struct in_addr addr,
1214                    struct in_addr mask)
1215 {
1216     struct netdev_bsd *netdev = netdev_bsd_cast(netdev_);
1217     int error;
1218
1219     ovs_mutex_lock(&netdev->mutex);
1220     error = do_set_addr(netdev_, SIOCSIFADDR, "SIOCSIFADDR", addr);
1221     if (!error) {
1222         if (addr.s_addr != INADDR_ANY) {
1223             error = do_set_addr(netdev_, SIOCSIFNETMASK,
1224                                 "SIOCSIFNETMASK", mask);
1225             if (!error) {
1226                 netdev->cache_valid |= VALID_IN4;
1227                 netdev->in4 = addr;
1228                 netdev->netmask = mask;
1229             }
1230         }
1231         seq_change(connectivity_seq_get());
1232     }
1233     ovs_mutex_unlock(&netdev->mutex);
1234
1235     return error;
1236 }
1237
1238 static int
1239 netdev_bsd_get_in6(const struct netdev *netdev_, struct in6_addr *in6)
1240 {
1241     struct netdev_bsd *netdev = netdev_bsd_cast(netdev_);
1242     if (!(netdev->cache_valid & VALID_IN6)) {
1243         struct ifaddrs *ifa, *head;
1244         struct sockaddr_in6 *sin6;
1245         const char *netdev_name = netdev_get_name(netdev_);
1246
1247         if (getifaddrs(&head) != 0) {
1248             VLOG_ERR("getifaddrs on %s device failed: %s", netdev_name,
1249                     ovs_strerror(errno));
1250             return errno;
1251         }
1252
1253         for (ifa = head; ifa; ifa = ifa->ifa_next) {
1254             if (ifa->ifa_addr->sa_family == AF_INET6 &&
1255                     !strcmp(ifa->ifa_name, netdev_name)) {
1256                 sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
1257                 if (sin6) {
1258                     memcpy(&netdev->in6, &sin6->sin6_addr, sin6->sin6_len);
1259                     netdev->cache_valid |= VALID_IN6;
1260                     *in6 = netdev->in6;
1261                     freeifaddrs(head);
1262                     return 0;
1263                 }
1264             }
1265         }
1266         return EADDRNOTAVAIL;
1267     }
1268     *in6 = netdev->in6;
1269     return 0;
1270 }
1271
1272 #if defined(__NetBSD__)
1273 static char *
1274 netdev_bsd_kernel_name_to_ovs_name(const char *kernel_name)
1275 {
1276     char *ovs_name = NULL;
1277     struct shash device_shash;
1278     struct shash_node *node;
1279
1280     shash_init(&device_shash);
1281     netdev_get_devices(&netdev_tap_class, &device_shash);
1282     SHASH_FOR_EACH(node, &device_shash) {
1283         struct netdev *netdev = node->data;
1284         struct netdev_bsd * const dev = netdev_bsd_cast(netdev);
1285
1286         if (!strcmp(dev->kernel_name, kernel_name)) {
1287             free(ovs_name);
1288             ovs_name = xstrdup(netdev_get_name(&dev->up));
1289         }
1290         netdev_close(netdev);
1291     }
1292     shash_destroy(&device_shash);
1293
1294     return ovs_name ? ovs_name : xstrdup(kernel_name);
1295 }
1296 #endif
1297
1298 static int
1299 netdev_bsd_get_next_hop(const struct in_addr *host OVS_UNUSED,
1300                         struct in_addr *next_hop OVS_UNUSED,
1301                         char **netdev_name OVS_UNUSED)
1302 {
1303 #if defined(__NetBSD__)
1304     static int seq = 0;
1305     struct sockaddr_in sin;
1306     struct sockaddr_dl sdl;
1307     int s;
1308     int i;
1309     struct {
1310         struct rt_msghdr h;
1311         char space[512];
1312     } buf;
1313     struct rt_msghdr *rtm = &buf.h;
1314     const pid_t pid = getpid();
1315     char *cp;
1316     ssize_t ssz;
1317     bool gateway = false;
1318     char *ifname = NULL;
1319     int saved_errno;
1320
1321     memset(next_hop, 0, sizeof(*next_hop));
1322     *netdev_name = NULL;
1323
1324     memset(&sin, 0, sizeof(sin));
1325     sin.sin_len = sizeof(sin);
1326     sin.sin_family = AF_INET;
1327     sin.sin_port = 0;
1328     sin.sin_addr = *host;
1329
1330     memset(&sdl, 0, sizeof(sdl));
1331     sdl.sdl_len = sizeof(sdl);
1332     sdl.sdl_family = AF_LINK;
1333
1334     s = socket(PF_ROUTE, SOCK_RAW, 0);
1335     memset(&buf, 0, sizeof(buf));
1336     rtm->rtm_flags = RTF_HOST|RTF_UP;
1337     rtm->rtm_version = RTM_VERSION;
1338     rtm->rtm_addrs = RTA_DST|RTA_IFP;
1339     cp = (void *)&buf.space;
1340     memcpy(cp, &sin, sizeof(sin));
1341     RT_ADVANCE(cp, (struct sockaddr *)(void *)&sin);
1342     memcpy(cp, &sdl, sizeof(sdl));
1343     RT_ADVANCE(cp, (struct sockaddr *)(void *)&sdl);
1344     rtm->rtm_msglen = cp - (char *)(void *)rtm;
1345     rtm->rtm_seq = ++seq;
1346     rtm->rtm_type = RTM_GET;
1347     rtm->rtm_pid = pid;
1348     write(s, rtm, rtm->rtm_msglen);
1349     memset(&buf, 0, sizeof(buf));
1350     do {
1351         ssz = read(s, &buf, sizeof(buf));
1352     } while (ssz > 0 && (rtm->rtm_seq != seq || rtm->rtm_pid != pid));
1353     saved_errno = errno;
1354     close(s);
1355     if (ssz <= 0) {
1356         if (ssz < 0) {
1357             return saved_errno;
1358         }
1359         return EPIPE; /* XXX */
1360     }
1361     cp = (void *)&buf.space;
1362     for (i = 1; i; i <<= 1) {
1363         if ((rtm->rtm_addrs & i) != 0) {
1364             const struct sockaddr *sa = (const void *)cp;
1365
1366             if ((i == RTA_GATEWAY) && sa->sa_family == AF_INET) {
1367                 const struct sockaddr_in * const sin =
1368                   (const struct sockaddr_in *)sa;
1369
1370                 *next_hop = sin->sin_addr;
1371                 gateway = true;
1372             }
1373             if ((i == RTA_IFP) && sa->sa_family == AF_LINK) {
1374                 const struct sockaddr_dl * const sdl =
1375                   (const struct sockaddr_dl *)sa;
1376                 char *kernel_name;
1377
1378                 kernel_name = xmemdup0(sdl->sdl_data, sdl->sdl_nlen);
1379                 ifname = netdev_bsd_kernel_name_to_ovs_name(kernel_name);
1380                 free(kernel_name);
1381             }
1382             RT_ADVANCE(cp, sa);
1383         }
1384     }
1385     if (ifname == NULL) {
1386         return ENXIO;
1387     }
1388     if (!gateway) {
1389         *next_hop = *host;
1390     }
1391     *netdev_name = ifname;
1392     VLOG_DBG("host " IP_FMT " next-hop " IP_FMT " if %s",
1393       IP_ARGS(host->s_addr), IP_ARGS(next_hop->s_addr), *netdev_name);
1394     return 0;
1395 #else
1396     return EOPNOTSUPP;
1397 #endif
1398 }
1399
1400 static int
1401 netdev_bsd_arp_lookup(const struct netdev *netdev OVS_UNUSED,
1402                       ovs_be32 ip OVS_UNUSED,
1403                       uint8_t mac[ETH_ADDR_LEN] OVS_UNUSED)
1404 {
1405 #if defined(__NetBSD__)
1406     const struct rt_msghdr *rtm;
1407     size_t needed;
1408     char *buf;
1409     const char *cp;
1410     const char *ep;
1411     int mib[6];
1412     int error;
1413
1414     buf = NULL;
1415     mib[0] = CTL_NET;
1416     mib[1] = PF_ROUTE;
1417     mib[2] = 0;
1418     mib[3] = AF_INET;
1419     mib[4] = NET_RT_FLAGS;
1420     mib[5] = RTF_LLINFO;
1421     if (sysctl(mib, 6, NULL, &needed, NULL, 0) == -1) {
1422         error = errno;
1423         goto error;
1424     }
1425     buf = xmalloc(needed);
1426     if (sysctl(mib, 6, buf, &needed, NULL, 0) == -1) {
1427         error = errno;
1428         goto error;
1429     }
1430     ep = buf + needed;
1431     for (cp = buf; cp < ep; cp += rtm->rtm_msglen) {
1432         const struct sockaddr_inarp *sina;
1433         const struct sockaddr_dl *sdl;
1434
1435         rtm = (const void *)cp;
1436         sina = (const void *)(rtm + 1);
1437         if (ip != sina->sin_addr.s_addr) {
1438             continue;
1439         }
1440         sdl = (const void *)
1441            ((const char *)(const void *)sina + RT_ROUNDUP(sina->sin_len));
1442         if (sdl->sdl_alen == ETH_ADDR_LEN) {
1443             memcpy(mac, &sdl->sdl_data[sdl->sdl_nlen], ETH_ADDR_LEN);
1444             error = 0;
1445             goto error;
1446         }
1447     }
1448     error = ENXIO;
1449 error:
1450     free(buf);
1451     return error;
1452 #else
1453     return EOPNOTSUPP;
1454 #endif
1455 }
1456
1457 static void
1458 make_in4_sockaddr(struct sockaddr *sa, struct in_addr addr)
1459 {
1460     struct sockaddr_in sin;
1461     memset(&sin, 0, sizeof sin);
1462     sin.sin_family = AF_INET;
1463     sin.sin_addr = addr;
1464     sin.sin_port = 0;
1465
1466     memset(sa, 0, sizeof *sa);
1467     memcpy(sa, &sin, sizeof sin);
1468 }
1469
1470 static int
1471 do_set_addr(struct netdev *netdev,
1472             unsigned long ioctl_nr, const char *ioctl_name,
1473             struct in_addr addr)
1474 {
1475     struct ifreq ifr;
1476     make_in4_sockaddr(&ifr.ifr_addr, addr);
1477     return af_inet_ifreq_ioctl(netdev_get_kernel_name(netdev), &ifr, ioctl_nr,
1478                                ioctl_name);
1479 }
1480
1481 static int
1482 nd_to_iff_flags(enum netdev_flags nd)
1483 {
1484     int iff = 0;
1485     if (nd & NETDEV_UP) {
1486         iff |= IFF_UP;
1487     }
1488     if (nd & NETDEV_PROMISC) {
1489         iff |= IFF_PROMISC;
1490 #if defined(IFF_PPROMISC)
1491         iff |= IFF_PPROMISC;
1492 #endif
1493     }
1494     if (nd & NETDEV_LOOPBACK) {
1495         iff |= IFF_LOOPBACK;
1496     }
1497     return iff;
1498 }
1499
1500 static int
1501 iff_to_nd_flags(int iff)
1502 {
1503     enum netdev_flags nd = 0;
1504     if (iff & IFF_UP) {
1505         nd |= NETDEV_UP;
1506     }
1507     if (iff & IFF_PROMISC) {
1508         nd |= NETDEV_PROMISC;
1509     }
1510     if (iff & IFF_LOOPBACK) {
1511         nd |= NETDEV_LOOPBACK;
1512     }
1513     return nd;
1514 }
1515
1516 static int
1517 netdev_bsd_update_flags(struct netdev *netdev_, enum netdev_flags off,
1518                         enum netdev_flags on, enum netdev_flags *old_flagsp)
1519 {
1520     int old_flags, new_flags;
1521     int error;
1522
1523     error = get_flags(netdev_, &old_flags);
1524     if (!error) {
1525         *old_flagsp = iff_to_nd_flags(old_flags);
1526         new_flags = (old_flags & ~nd_to_iff_flags(off)) | nd_to_iff_flags(on);
1527         if (new_flags != old_flags) {
1528             error = set_flags(netdev_get_kernel_name(netdev_), new_flags);
1529             seq_change(connectivity_seq_get());
1530         }
1531     }
1532     return error;
1533 }
1534
1535 /* Linux has also different GET_STATS, SET_STATS,
1536  * GET_STATUS)
1537  */
1538 #define NETDEV_BSD_CLASS(NAME, CONSTRUCT,            \
1539                          GET_FEATURES)               \
1540 {                                                    \
1541     NAME,                                            \
1542                                                      \
1543     NULL, /* init */                                 \
1544     netdev_bsd_run,                                  \
1545     netdev_bsd_wait,                                 \
1546     netdev_bsd_alloc,                                \
1547     CONSTRUCT,                                       \
1548     netdev_bsd_destruct,                             \
1549     netdev_bsd_dealloc,                              \
1550     NULL, /* get_config */                           \
1551     NULL, /* set_config */                           \
1552     NULL, /* get_tunnel_config */                    \
1553                                                      \
1554     netdev_bsd_send,                                 \
1555     netdev_bsd_send_wait,                            \
1556                                                      \
1557     netdev_bsd_set_etheraddr,                        \
1558     netdev_bsd_get_etheraddr,                        \
1559     netdev_bsd_get_mtu,                              \
1560     NULL, /* set_mtu */                              \
1561     netdev_bsd_get_ifindex,                          \
1562     netdev_bsd_get_carrier,                          \
1563     NULL, /* get_carrier_resets */                   \
1564     NULL, /* set_miimon_interval */                  \
1565     netdev_bsd_get_stats,                            \
1566     NULL, /* set_stats */                            \
1567                                                      \
1568     GET_FEATURES,                                    \
1569     NULL, /* set_advertisement */                    \
1570     NULL, /* set_policing */                         \
1571     NULL, /* get_qos_type */                         \
1572     NULL, /* get_qos_capabilities */                 \
1573     NULL, /* get_qos */                              \
1574     NULL, /* set_qos */                              \
1575     NULL, /* get_queue */                            \
1576     NULL, /* set_queue */                            \
1577     NULL, /* delete_queue */                         \
1578     NULL, /* get_queue_stats */                      \
1579     NULL, /* queue_dump_start */                     \
1580     NULL, /* queue_dump_next */                      \
1581     NULL, /* queue_dump_done */                      \
1582     NULL, /* dump_queue_stats */                     \
1583                                                      \
1584     netdev_bsd_get_in4,                              \
1585     netdev_bsd_set_in4,                              \
1586     netdev_bsd_get_in6,                              \
1587     NULL, /* add_router */                           \
1588     netdev_bsd_get_next_hop,                         \
1589     NULL, /* get_status */                           \
1590     netdev_bsd_arp_lookup, /* arp_lookup */          \
1591                                                      \
1592     netdev_bsd_update_flags,                         \
1593                                                      \
1594     netdev_bsd_rxq_alloc,                            \
1595     netdev_bsd_rxq_construct,                        \
1596     netdev_bsd_rxq_destruct,                         \
1597     netdev_bsd_rxq_dealloc,                          \
1598     netdev_bsd_rxq_recv,                             \
1599     netdev_bsd_rxq_wait,                             \
1600     netdev_bsd_rxq_drain,                            \
1601 }
1602
1603 const struct netdev_class netdev_bsd_class =
1604     NETDEV_BSD_CLASS(
1605         "system",
1606         netdev_bsd_construct_system,
1607         netdev_bsd_get_features);
1608
1609 const struct netdev_class netdev_tap_class =
1610     NETDEV_BSD_CLASS(
1611         "tap",
1612         netdev_bsd_construct_tap,
1613         netdev_bsd_get_features);
1614 \f
1615
1616 static void
1617 destroy_tap(int fd, const char *name)
1618 {
1619     struct ifreq ifr;
1620
1621     close(fd);
1622     strcpy(ifr.ifr_name, name);
1623     /* XXX What to do if this call fails? */
1624     af_inet_ioctl(SIOCIFDESTROY, &ifr);
1625 }
1626
1627 static int
1628 get_flags(const struct netdev *netdev, int *flags)
1629 {
1630     struct ifreq ifr;
1631     int error;
1632
1633     error = af_inet_ifreq_ioctl(netdev_get_kernel_name(netdev), &ifr,
1634                                 SIOCGIFFLAGS, "SIOCGIFFLAGS");
1635
1636     *flags = ifr_get_flags(&ifr);
1637
1638     return error;
1639 }
1640
1641 static int
1642 set_flags(const char *name, int flags)
1643 {
1644     struct ifreq ifr;
1645
1646     ifr_set_flags(&ifr, flags);
1647
1648     return af_inet_ifreq_ioctl(name, &ifr, SIOCSIFFLAGS, "SIOCSIFFLAGS");
1649 }
1650
1651 static int
1652 get_ifindex(const struct netdev *netdev_, int *ifindexp)
1653 {
1654     struct netdev_bsd *netdev = netdev_bsd_cast(netdev_);
1655     *ifindexp = 0;
1656     if (!(netdev->cache_valid & VALID_IFINDEX)) {
1657         int ifindex = if_nametoindex(netdev_get_name(netdev_));
1658         if (ifindex <= 0) {
1659             return errno;
1660         }
1661         netdev->cache_valid |= VALID_IFINDEX;
1662         netdev->ifindex = ifindex;
1663     }
1664     *ifindexp = netdev->ifindex;
1665     return 0;
1666 }
1667
1668 static int
1669 get_etheraddr(const char *netdev_name, uint8_t ea[ETH_ADDR_LEN])
1670 {
1671     struct ifaddrs *head;
1672     struct ifaddrs *ifa;
1673     struct sockaddr_dl *sdl;
1674
1675     if (getifaddrs(&head) != 0) {
1676         VLOG_ERR("getifaddrs on %s device failed: %s", netdev_name,
1677                 ovs_strerror(errno));
1678         return errno;
1679     }
1680
1681     for (ifa = head; ifa; ifa = ifa->ifa_next) {
1682         if (ifa->ifa_addr->sa_family == AF_LINK) {
1683             if (!strcmp(ifa->ifa_name, netdev_name)) {
1684                 sdl = (struct sockaddr_dl *)ifa->ifa_addr;
1685                 if (sdl) {
1686                     memcpy(ea, LLADDR(sdl), sdl->sdl_alen);
1687                     freeifaddrs(head);
1688                     return 0;
1689                 }
1690             }
1691         }
1692     }
1693
1694     VLOG_ERR("could not find ethernet address for %s device", netdev_name);
1695     freeifaddrs(head);
1696     return ENODEV;
1697 }
1698
1699 static int
1700 set_etheraddr(const char *netdev_name OVS_UNUSED, int hwaddr_family OVS_UNUSED,
1701               int hwaddr_len OVS_UNUSED,
1702               const uint8_t mac[ETH_ADDR_LEN] OVS_UNUSED)
1703 {
1704 #if defined(__FreeBSD__)
1705     struct ifreq ifr;
1706     int error;
1707
1708     memset(&ifr, 0, sizeof ifr);
1709     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
1710     ifr.ifr_addr.sa_family = hwaddr_family;
1711     ifr.ifr_addr.sa_len = hwaddr_len;
1712     memcpy(ifr.ifr_addr.sa_data, mac, hwaddr_len);
1713     error = af_inet_ioctl(SIOCSIFLLADDR, &ifr);
1714     if (error) {
1715         VLOG_ERR("ioctl(SIOCSIFLLADDR) on %s device failed: %s",
1716                  netdev_name, ovs_strerror(error));
1717         return error;
1718     }
1719     return 0;
1720 #elif defined(__NetBSD__)
1721     struct if_laddrreq req;
1722     struct sockaddr_dl *sdl;
1723     struct sockaddr_storage oldaddr;
1724     int error;
1725
1726     /*
1727      * get the old address, add new one, and then remove old one.
1728      */
1729
1730     if (hwaddr_len != ETH_ADDR_LEN) {
1731         /* just to be safe about sockaddr storage size */
1732         return EOPNOTSUPP;
1733     }
1734     memset(&req, 0, sizeof(req));
1735     strncpy(req.iflr_name, netdev_name, sizeof(req.iflr_name));
1736     req.addr.ss_len = sizeof(req.addr);
1737     req.addr.ss_family = hwaddr_family;
1738     sdl = (struct sockaddr_dl *)&req.addr;
1739     sdl->sdl_alen = hwaddr_len;
1740
1741     error = af_link_ioctl(SIOCGLIFADDR, &req);
1742     if (error) {
1743         return error;
1744     }
1745     if (!memcmp(&sdl->sdl_data[sdl->sdl_nlen], mac, hwaddr_len)) {
1746         return 0;
1747     }
1748     oldaddr = req.addr;
1749
1750     memset(&req, 0, sizeof(req));
1751     strncpy(req.iflr_name, netdev_name, sizeof(req.iflr_name));
1752     req.flags = IFLR_ACTIVE;
1753     sdl = (struct sockaddr_dl *)&req.addr;
1754     sdl->sdl_len = offsetof(struct sockaddr_dl, sdl_data) + hwaddr_len;
1755     sdl->sdl_alen = hwaddr_len;
1756     sdl->sdl_family = hwaddr_family;
1757     memcpy(sdl->sdl_data, mac, hwaddr_len);
1758     error = af_link_ioctl(SIOCALIFADDR, &req);
1759     if (error) {
1760         return error;
1761     }
1762
1763     memset(&req, 0, sizeof(req));
1764     strncpy(req.iflr_name, netdev_name, sizeof(req.iflr_name));
1765     req.addr = oldaddr;
1766     return af_link_ioctl(SIOCDLIFADDR, &req);
1767 #else
1768 #error not implemented
1769 #endif
1770 }
1771
1772 static int
1773 ifr_get_flags(const struct ifreq *ifr)
1774 {
1775 #ifdef HAVE_STRUCT_IFREQ_IFR_FLAGSHIGH
1776     return (ifr->ifr_flagshigh << 16) | ifr->ifr_flags;
1777 #else
1778     return ifr->ifr_flags;
1779 #endif
1780 }
1781
1782 static void
1783 ifr_set_flags(struct ifreq *ifr, int flags)
1784 {
1785     ifr->ifr_flags = flags;
1786 #ifdef HAVE_STRUCT_IFREQ_IFR_FLAGSHIGH
1787     ifr->ifr_flagshigh = flags >> 16;
1788 #endif
1789 }
1790
1791 /* Calls ioctl() on an AF_LINK sock, passing the specified 'command' and
1792  * 'arg'.  Returns 0 if successful, otherwise a positive errno value. */
1793 int
1794 af_link_ioctl(unsigned long command, const void *arg)
1795 {
1796     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
1797     static int sock;
1798
1799     if (ovsthread_once_start(&once)) {
1800         sock = socket(AF_LINK, SOCK_DGRAM, 0);
1801         if (sock < 0) {
1802             sock = -errno;
1803             VLOG_ERR("failed to create link socket: %s", ovs_strerror(errno));
1804         }
1805         ovsthread_once_done(&once);
1806     }
1807
1808     return (sock < 0 ? -sock
1809             : ioctl(sock, command, arg) == -1 ? errno
1810             : 0);
1811 }