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