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