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