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