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