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