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