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