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