Merge commit '180c6d0b440961cbc873c4d045eb8b2daa1364e9'
[sliver-openvswitch.git] / lib / netdev-bsd.c
1 /*
2  * Copyright (c) 2011 Gaetano Catalli.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18
19 #include "netdev-provider.h"
20 #include <stdlib.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <sys/types.h>
24 #include <sys/time.h>
25 #include <sys/ioctl.h>
26 #include <sys/socket.h>
27 #include <sys/sockio.h>
28 #include <ifaddrs.h>
29 #include <pcap/pcap.h>
30 #include <net/if.h>
31 #include <net/if_dl.h>
32 #include <net/if_media.h>
33 #include <net/if_tap.h>
34 #include <netinet/in.h>
35 #include <net/if_mib.h>
36 #include <poll.h>
37 #include <string.h>
38 #include <unistd.h>
39 #include <sys/sysctl.h>
40
41 #include "rtbsd.h"
42 #include "coverage.h"
43 #include "dynamic-string.h"
44 #include "fatal-signal.h"
45 #include "ofpbuf.h"
46 #include "openflow/openflow.h"
47 #include "packets.h"
48 #include "poll-loop.h"
49 #include "socket-util.h"
50 #include "shash.h"
51 #include "svec.h"
52 #include "util.h"
53 #include "vlog.h"
54
55 VLOG_DEFINE_THIS_MODULE(netdev_bsd);
56
57 \f
58 /*
59  * This file implements objects to access interfaces.
60  * Externally, interfaces are represented by three structures:
61  *   + struct netdev_dev, representing a network device,
62  *     containing e.g. name and a refcount;
63  *     We can have private variables by embedding the
64  *     struct netdev_dev into our own structure
65  *     (e.g. netdev_dev_bsd)
66  *
67  *   + struct netdev, representing an instance of an open netdev_dev.
68  *     The structure contains a pointer to the 'struct netdev'
69  *     representing the device.
70  *
71  *   + struct netdev_rx, which represents a netdev open to capture received
72  *     packets.  Again, private information such as file descriptor etc. are
73  *     stored in our own struct netdev_rx_bsd which includes a struct
74  *     netdev_rx.
75  *
76  * 'struct netdev', 'struct netdev_dev', and 'struct netdev_rx' are referenced
77  * in containers which hold pointers to the data structures.  We can reach our
78  * own struct netdev_XXX_bsd by putting a struct netdev_XXX within our own
79  * struct, and using CONTAINER_OF to access the parent structure.
80  */
81 struct netdev_bsd {
82     struct netdev up;
83 };
84
85 struct netdev_rx_bsd {
86     struct netdev_rx up;
87
88     /* Packet capture descriptor for a system network device.
89      * For a tap device this is NULL. */
90     pcap_t *pcap_handle;
91
92     /* Selectable file descriptor for the network device.
93      * This descriptor will be used for polling operations. */
94     int fd;
95 };
96
97 static const struct netdev_rx_class netdev_rx_bsd_class;
98
99 struct netdev_dev_bsd {
100     struct netdev_dev up;
101     unsigned int cache_valid;
102     unsigned int change_seq;
103
104     int ifindex;
105     uint8_t etheraddr[ETH_ADDR_LEN];
106     struct in_addr in4;
107     struct in6_addr in6;
108     int mtu;
109     int carrier;
110
111     int tap_fd;         /* TAP character device, if any, otherwise -1. */
112
113     /* Used for sending packets on non-tap devices. */
114     pcap_t *pcap;
115     int fd;
116 };
117
118
119 enum {
120     VALID_IFINDEX = 1 << 0,
121     VALID_ETHERADDR = 1 << 1,
122     VALID_IN4 = 1 << 2,
123     VALID_IN6 = 1 << 3,
124     VALID_MTU = 1 << 4,
125     VALID_CARRIER = 1 << 5
126 };
127
128 /* An AF_INET socket (used for ioctl operations). */
129 static int af_inet_sock = -1;
130
131 #define PCAP_SNAPLEN 2048
132
133
134 /*
135  * Notifier used to invalidate device informations in case of status change.
136  *
137  * It will be registered with a 'rtbsd_notifier_register()' when the first
138  * device will be created with the call of either 'netdev_bsd_tap_create()' or
139  * 'netdev_bsd_system_create()'.
140  *
141  * The callback associated with this notifier ('netdev_bsd_cache_cb()') will
142  * invalidate cached information about the device.
143  */
144 static struct rtbsd_notifier netdev_bsd_cache_notifier;
145 static int cache_notifier_refcount;
146
147 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
148
149 static int netdev_bsd_do_ioctl(const char *, struct ifreq *, unsigned long cmd,
150                                const char *cmd_name);
151 static void destroy_tap(int fd, const char *name);
152 static int get_flags(const struct netdev_dev *, int *flagsp);
153 static int set_flags(const char *, int flags);
154 static int do_set_addr(struct netdev *netdev,
155                        int ioctl_nr, const char *ioctl_name,
156                        struct in_addr addr);
157 static int get_etheraddr(const char *netdev_name, uint8_t ea[ETH_ADDR_LEN]);
158 static int set_etheraddr(const char *netdev_name, int hwaddr_family,
159                          int hwaddr_len, const uint8_t[ETH_ADDR_LEN]);
160 static int get_ifindex(const struct netdev *, int *ifindexp);
161
162 static int netdev_bsd_init(void);
163
164 static bool
165 is_netdev_bsd_class(const struct netdev_class *netdev_class)
166 {
167     return netdev_class->init == netdev_bsd_init;
168 }
169
170 static struct netdev_bsd *
171 netdev_bsd_cast(const struct netdev *netdev)
172 {
173     ovs_assert(is_netdev_bsd_class(netdev_dev_get_class(
174                                        netdev_get_dev(netdev))));
175     return CONTAINER_OF(netdev, struct netdev_bsd, up);
176 }
177
178 static struct netdev_dev_bsd *
179 netdev_dev_bsd_cast(const struct netdev_dev *netdev_dev)
180 {
181     ovs_assert(is_netdev_bsd_class(netdev_dev_get_class(netdev_dev)));
182     return CONTAINER_OF(netdev_dev, struct netdev_dev_bsd, up);
183 }
184
185 static struct netdev_rx_bsd *
186 netdev_rx_bsd_cast(const struct netdev_rx *rx)
187 {
188     netdev_rx_assert_class(rx, &netdev_rx_bsd_class);
189     return CONTAINER_OF(rx, struct netdev_rx_bsd, up);
190 }
191
192 /* Initialize the AF_INET socket used for ioctl operations */
193 static int
194 netdev_bsd_init(void)
195 {
196     static int status = -1;
197
198     if (status >= 0) {  /* already initialized */
199         return status;
200     }
201
202     af_inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
203     status = af_inet_sock >= 0 ? 0 : errno;
204
205     if (status) {
206         VLOG_ERR("failed to create inet socket: %s", strerror(status));
207     }
208
209     return status;
210 }
211
212 /*
213  * Perform periodic work needed by netdev. In BSD netdevs it checks for any
214  * interface status changes, and eventually calls all the user callbacks.
215  */
216 static void
217 netdev_bsd_run(void)
218 {
219     rtbsd_notifier_run();
220 }
221
222 /*
223  * Arranges for poll_block() to wake up if the "run" member function needs to
224  * be called.
225  */
226 static void
227 netdev_bsd_wait(void)
228 {
229     rtbsd_notifier_wait();
230 }
231
232 static void
233 netdev_dev_bsd_changed(struct netdev_dev_bsd *dev)
234 {
235     dev->change_seq++;
236     if (!dev->change_seq) {
237         dev->change_seq++;
238     }
239 }
240
241 /* Invalidate cache in case of interface status change. */
242 static void
243 netdev_bsd_cache_cb(const struct rtbsd_change *change,
244                     void *aux OVS_UNUSED)
245 {
246     struct netdev_dev_bsd *dev;
247
248     if (change) {
249         struct netdev_dev *base_dev = netdev_dev_from_name(change->if_name);
250
251         if (base_dev) {
252             const struct netdev_class *netdev_class =
253                                                 netdev_dev_get_class(base_dev);
254
255             if (is_netdev_bsd_class(netdev_class)) {
256                 dev = netdev_dev_bsd_cast(base_dev);
257                 dev->cache_valid = 0;
258                 netdev_dev_bsd_changed(dev);
259             }
260         }
261     } else {
262         /*
263          * XXX the API is lacking, we should be able to iterate on the list of
264          * netdevs without having to store the info in a temp shash.
265          */
266         struct shash device_shash;
267         struct shash_node *node;
268
269         shash_init(&device_shash);
270         netdev_dev_get_devices(&netdev_bsd_class, &device_shash);
271         SHASH_FOR_EACH (node, &device_shash) {
272             dev = node->data;
273             dev->cache_valid = 0;
274             netdev_dev_bsd_changed(dev);
275         }
276         shash_destroy(&device_shash);
277     }
278 }
279
280 static int
281 cache_notifier_ref(void)
282 {
283     int ret = 0;
284
285     if (!cache_notifier_refcount) {
286         ret = rtbsd_notifier_register(&netdev_bsd_cache_notifier,
287                                                 netdev_bsd_cache_cb, NULL);
288         if (ret) {
289             return ret;
290         }
291     }
292     cache_notifier_refcount++;
293     return 0;
294 }
295
296 static int
297 cache_notifier_unref(void)
298 {
299     cache_notifier_refcount--;
300     if (cache_notifier_refcount == 0) {
301         rtbsd_notifier_unregister(&netdev_bsd_cache_notifier);
302     }
303     return 0;
304 }
305
306 /* Allocate a netdev_dev_bsd structure */
307 static int
308 netdev_bsd_create_system(const struct netdev_class *class, const char *name,
309                   struct netdev_dev **netdev_devp)
310 {
311     struct netdev_dev_bsd *netdev_dev;
312     int error;
313
314     error = cache_notifier_ref();
315     if (error) {
316         return error;
317     }
318
319     netdev_dev = xzalloc(sizeof *netdev_dev);
320     netdev_dev->change_seq = 1;
321     netdev_dev_init(&netdev_dev->up, name, class);
322     netdev_dev->tap_fd = -1;
323     *netdev_devp = &netdev_dev->up;
324
325     return 0;
326 }
327
328 /*
329  * Allocate a netdev_dev_bsd structure with 'tap' class.
330  */
331 static int
332 netdev_bsd_create_tap(const struct netdev_class *class, const char *name,
333                   struct netdev_dev **netdev_devp)
334 {
335     struct netdev_dev_bsd *netdev_dev = NULL;
336     int error = 0;
337     struct ifreq ifr;
338
339     error = cache_notifier_ref();
340     if (error) {
341         goto error;
342     }
343
344     /* allocate the device structure and set the internal flag */
345     netdev_dev = xzalloc(sizeof *netdev_dev);
346
347     memset(&ifr, 0, sizeof(ifr));
348
349     /* Create a tap device by opening /dev/tap.  The TAPGIFNAME ioctl is used
350      * to retrieve the name of the tap device. */
351     netdev_dev->tap_fd = open("/dev/tap", O_RDWR);
352     netdev_dev->change_seq = 1;
353     if (netdev_dev->tap_fd < 0) {
354         error = errno;
355         VLOG_WARN("opening \"/dev/tap\" failed: %s", strerror(error));
356         goto error_undef_notifier;
357     }
358
359     /* Retrieve tap name (e.g. tap0) */
360     if (ioctl(netdev_dev->tap_fd, TAPGIFNAME, &ifr) == -1) {
361         /* XXX Need to destroy the device? */
362         error = errno;
363         goto error_undef_notifier;
364     }
365
366     /* Change the name of the tap device */
367     ifr.ifr_data = (void *)name;
368     if (ioctl(af_inet_sock, SIOCSIFNAME, &ifr) == -1) {
369         error = errno;
370         destroy_tap(netdev_dev->tap_fd, ifr.ifr_name);
371         goto error_undef_notifier;
372     }
373
374     /* set non-blocking. */
375     error = set_nonblocking(netdev_dev->tap_fd);
376     if (error) {
377         destroy_tap(netdev_dev->tap_fd, name);
378         goto error_undef_notifier;
379     }
380
381     /* Turn device UP */
382     ifr.ifr_flags = (uint16_t)IFF_UP;
383     ifr.ifr_flagshigh = 0;
384     strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
385     if (ioctl(af_inet_sock, SIOCSIFFLAGS, &ifr) == -1) {
386         error = errno;
387         destroy_tap(netdev_dev->tap_fd, name);
388         goto error_undef_notifier;
389     }
390
391     /* initialize the device structure and
392      * link the structure to its netdev */
393     netdev_dev_init(&netdev_dev->up, name, class);
394     *netdev_devp = &netdev_dev->up;
395
396     return 0;
397
398 error_undef_notifier:
399     cache_notifier_unref();
400 error:
401     free(netdev_dev);
402     return error;
403 }
404
405 static void
406 netdev_bsd_destroy(struct netdev_dev *netdev_dev_)
407 {
408     struct netdev_dev_bsd *netdev_dev = netdev_dev_bsd_cast(netdev_dev_);
409
410     cache_notifier_unref();
411
412     if (netdev_dev->tap_fd >= 0) {
413         destroy_tap(netdev_dev->tap_fd, netdev_dev_get_name(netdev_dev_));
414     }
415     if (netdev_dev->pcap) {
416         pcap_close(netdev_dev->pcap);
417     }
418     free(netdev_dev);
419 }
420
421
422 static int
423 netdev_bsd_open_system(struct netdev_dev *netdev_dev_, struct netdev **netdevp)
424 {
425     struct netdev_bsd *netdev;
426     int error;
427     enum netdev_flags flags;
428
429     /* Allocate network device. */
430     netdev = xcalloc(1, sizeof *netdev);
431     netdev_init(&netdev->up, netdev_dev_);
432
433     /* Verify that the netdev really exists by attempting to read its flags */
434     error = netdev_get_flags(&netdev->up, &flags);
435     if (error == ENXIO) {
436         goto error;
437     }
438
439     *netdevp = &netdev->up;
440     return 0;
441
442 error:
443     netdev_uninit(&netdev->up, true);
444     return error;
445 }
446
447
448
449 /* Close a 'netdev'. */
450 static void
451 netdev_bsd_close(struct netdev *netdev_)
452 {
453     struct netdev_bsd *netdev = netdev_bsd_cast(netdev_);
454
455     free(netdev);
456 }
457
458 static int
459 netdev_bsd_open_pcap(const char *name, pcap_t **pcapp, int *fdp)
460 {
461     char errbuf[PCAP_ERRBUF_SIZE];
462     pcap_t *pcap = NULL;
463     int one = 1;
464     int error;
465     int fd;
466
467     /* Open the pcap device.  The device is opened in non-promiscuous mode
468      * because the interface flags are manually set by the caller. */
469     errbuf[0] = '\0';
470     pcap = pcap_open_live(name, PCAP_SNAPLEN, 0, 1000, errbuf);
471     if (!pcap) {
472         VLOG_ERR_RL(&rl, "%s: pcap_open_live failed: %s", name, errbuf);
473         error = EIO;
474         goto error;
475     }
476     if (errbuf[0] != '\0') {
477         VLOG_WARN_RL(&rl, "%s: pcap_open_live: %s", name, errbuf);
478     }
479
480     /* Get the underlying fd. */
481     fd = pcap_get_selectable_fd(pcap);
482     if (fd == -1) {
483         VLOG_WARN_RL(&rl, "%s: no selectable file descriptor", name);
484         error = errno;
485         goto error;
486     }
487
488     /* Set non-blocking mode. Also the BIOCIMMEDIATE ioctl must be called
489      * on the file descriptor returned by pcap_get_selectable_fd to achieve
490      * a real non-blocking behaviour.*/
491     error = pcap_setnonblock(pcap, 1, errbuf);
492     if (error == -1) {
493         error = errno;
494         goto error;
495     }
496
497     /* This call assure that reads return immediately upon packet
498      * reception.  Otherwise, a read will block until either the kernel
499      * buffer becomes full or a timeout occurs. */
500     if (ioctl(fd, BIOCIMMEDIATE, &one) < 0 ) {
501         VLOG_ERR_RL(&rl, "ioctl(BIOCIMMEDIATE) on %s device failed: %s",
502                     name, strerror(errno));
503         error = errno;
504         goto error;
505     }
506
507     /* Capture only incoming packets. */
508     error = pcap_setdirection(pcap, PCAP_D_IN);
509     if (error == -1) {
510         error = errno;
511         goto error;
512     }
513
514     *pcapp = pcap;
515     *fdp = fd;
516     return 0;
517
518 error:
519     if (pcap) {
520         pcap_close(pcap);
521     }
522     *pcapp = NULL;
523     *fdp = -1;
524     return error;
525 }
526
527 static int
528 netdev_bsd_rx_open(struct netdev *netdev_, struct netdev_rx **rxp)
529 {
530     struct netdev_dev_bsd *netdev_dev =
531                               netdev_dev_bsd_cast(netdev_get_dev(netdev_));
532
533     struct netdev_rx_bsd *rx;
534     pcap_t *pcap;
535     int fd;
536
537     if (!strcmp(netdev_get_type(netdev_), "tap")) {
538         pcap = NULL;
539         fd = netdev_dev->tap_fd;
540     } else {
541         int error = netdev_bsd_open_pcap(netdev_get_name(netdev_), &pcap, &fd);
542         if (error) {
543             return error;
544         }
545
546         netdev_dev_bsd_changed(netdev_dev);
547     }
548
549     rx = xmalloc(sizeof *rx);
550     netdev_rx_init(&rx->up, netdev_get_dev(netdev_), &netdev_rx_bsd_class);
551     rx->pcap_handle = pcap;
552     rx->fd = fd;
553
554     *rxp = &rx->up;
555     return 0;
556 }
557
558 static void
559 netdev_rx_bsd_destroy(struct netdev_rx *rx_)
560 {
561     struct netdev_rx_bsd *rx = netdev_rx_bsd_cast(rx_);
562
563     if (rx->pcap_handle) {
564         pcap_close(rx->pcap_handle);
565     }
566     free(rx);
567 }
568
569 /* The recv callback of the netdev class returns the number of bytes of the
570  * received packet.
571  *
572  * This can be done by the pcap_next() function. Unfortunately pcap_next() does
573  * not make difference between a missing packet on the capture interface and
574  * an error during the file capture.  We can use the pcap_dispatch() function
575  * instead, which is able to distinguish between errors and null packet.
576  *
577  * To make pcap_dispatch() returns the number of bytes read from the interface
578  * we need to define the following callback and argument.
579  */
580 struct pcap_arg {
581     void *data;
582     int size;
583     int retval;
584 };
585
586 /*
587  * This callback will be executed on every captured packet.
588  *
589  * If the packet captured by pcap_dispatch() does not fit the pcap buffer,
590  * pcap returns a truncated packet and we follow this behavior.
591  *
592  * The argument args->retval is the packet size in bytes.
593  */
594 static void
595 proc_pkt(u_char *args_, const struct pcap_pkthdr *hdr, const u_char *packet)
596 {
597     struct pcap_arg *args = (struct pcap_arg *)args_;
598
599     if (args->size < hdr->len) {
600         VLOG_WARN_RL(&rl, "packet truncated");
601         args->retval = args->size;
602     } else {
603         args->retval = hdr->len;
604     }
605
606     /* copy the packet to our buffer */
607     memcpy(args->data, packet, args->retval);
608 }
609
610 /*
611  * This function attempts to receive a packet from the specified network
612  * device. It is assumed that the network device is a system device or a tap
613  * device opened as a system one. In this case the read operation is performed
614  * from rx->pcap.
615  */
616 static int
617 netdev_rx_bsd_recv_pcap(struct netdev_rx_bsd *rx, void *data, size_t size)
618 {
619     struct pcap_arg arg;
620     int ret;
621
622     /* prepare the pcap argument to store the packet */
623     arg.size = size;
624     arg.data = data;
625
626     for (;;) {
627         ret = pcap_dispatch(rx->pcap_handle, 1, proc_pkt, (u_char *) &arg);
628
629         if (ret > 0) {
630             return arg.retval;  /* arg.retval < 0 is handled in the caller */
631         }
632         if (ret == -1) {
633             if (errno == EINTR) {
634                  continue;
635             }
636         }
637
638         return -EAGAIN;
639     }
640 }
641
642 /*
643  * This function attempts to receive a packet from the specified network
644  * device. It is assumed that the network device is a tap device and
645  * 'rx->fd' is initialized with the tap file descriptor.
646  */
647 static int
648 netdev_rx_bsd_recv_tap(struct netdev_rx_bsd *rx, void *data, size_t size)
649 {
650     for (;;) {
651         ssize_t retval = read(rx->fd, data, size);
652         if (retval >= 0) {
653             return retval;
654         } else if (errno != EINTR) {
655             if (errno != EAGAIN) {
656                 VLOG_WARN_RL(&rl, "error receiving Ethernet packet on %s: %s",
657                              strerror(errno), netdev_rx_get_name(&rx->up));
658             }
659             return -errno;
660         }
661     }
662 }
663
664
665 static int
666 netdev_rx_bsd_recv(struct netdev_rx *rx_, void *data, size_t size)
667 {
668     struct netdev_rx_bsd *rx = netdev_rx_bsd_cast(rx_);
669
670     return (rx->pcap_handle
671             ? netdev_rx_bsd_recv_pcap(rx, data, size)
672             : netdev_rx_bsd_recv_tap(rx, data, size));
673 }
674
675 /*
676  * Registers with the poll loop to wake up from the next call to poll_block()
677  * when a packet is ready to be received with netdev_rx_recv() on 'rx'.
678  */
679 static void
680 netdev_rx_bsd_wait(struct netdev_rx *rx_)
681 {
682     struct netdev_rx_bsd *rx = netdev_rx_bsd_cast(rx_);
683
684     poll_fd_wait(rx->fd, POLLIN);
685 }
686
687 /* Discards all packets waiting to be received from 'rx'. */
688 static int
689 netdev_rx_bsd_drain(struct netdev_rx *rx_)
690 {
691     struct ifreq ifr;
692     struct netdev_rx_bsd *rx = netdev_rx_bsd_cast(rx_);
693
694     strcpy(ifr.ifr_name, netdev_rx_get_name(rx_));
695     if (ioctl(rx->fd, BIOCFLUSH, &ifr) == -1) {
696         VLOG_DBG_RL(&rl, "%s: ioctl(BIOCFLUSH) failed: %s",
697                     netdev_rx_get_name(rx_), strerror(errno));
698         return errno;
699     }
700     return 0;
701 }
702
703 /*
704  * Send a packet on the specified network device. The device could be either a
705  * system or a tap device.
706  */
707 static int
708 netdev_bsd_send(struct netdev *netdev_, const void *data, size_t size)
709 {
710     struct netdev_dev_bsd *dev = netdev_dev_bsd_cast(netdev_get_dev(netdev_));
711     const char *name = netdev_get_name(netdev_);
712
713     if (dev->tap_fd < 0 && !dev->pcap) {
714         int error = netdev_bsd_open_pcap(name, &dev->pcap, &dev->fd);
715         if (error) {
716             return error;
717         }
718     }
719
720     for (;;) {
721         ssize_t retval;
722         if (dev->tap_fd >= 0) {
723             retval = write(dev->tap_fd, data, size);
724         } else {
725             retval = pcap_inject(dev->pcap, data, size);
726         }
727         if (retval < 0) {
728             if (errno == EINTR) {
729                 continue;
730             } else if (errno != EAGAIN) {
731                 VLOG_WARN_RL(&rl, "error sending Ethernet packet on %s: %s",
732                              name, strerror(errno));
733             }
734             return errno;
735         } else if (retval != size) {
736             VLOG_WARN_RL(&rl, "sent partial Ethernet packet (%zd bytes of "
737                          "%zu) on %s", retval, size, name);
738            return EMSGSIZE;
739         } else {
740             return 0;
741         }
742     }
743 }
744
745 /*
746  * Registers with the poll loop to wake up from the next call to poll_block()
747  * when the packet transmission queue has sufficient room to transmit a packet
748  * with netdev_send().
749  */
750 static void
751 netdev_bsd_send_wait(struct netdev *netdev_)
752 {
753     struct netdev_dev_bsd *dev = netdev_dev_bsd_cast(netdev_get_dev(netdev_));
754
755     if (dev->tap_fd >= 0) {
756         /* TAP device always accepts packets. */
757         poll_immediate_wake();
758     } else if (dev->pcap) {
759         poll_fd_wait(dev->fd, POLLOUT);
760     } else {
761         /* We haven't even tried to send a packet yet. */
762         poll_immediate_wake();
763     }
764 }
765
766 /*
767  * Attempts to set 'netdev''s MAC address to 'mac'.  Returns 0 if successful,
768  * otherwise a positive errno value.
769  */
770 static int
771 netdev_bsd_set_etheraddr(struct netdev *netdev_,
772                          const uint8_t mac[ETH_ADDR_LEN])
773 {
774     struct netdev_dev_bsd *netdev_dev =
775                                 netdev_dev_bsd_cast(netdev_get_dev(netdev_));
776     int error;
777
778     if (!(netdev_dev->cache_valid & VALID_ETHERADDR)
779         || !eth_addr_equals(netdev_dev->etheraddr, mac)) {
780         error = set_etheraddr(netdev_get_name(netdev_), AF_LINK, ETH_ADDR_LEN,
781                               mac);
782         if (!error) {
783             netdev_dev->cache_valid |= VALID_ETHERADDR;
784             memcpy(netdev_dev->etheraddr, mac, ETH_ADDR_LEN);
785             netdev_dev_bsd_changed(netdev_dev);
786         }
787     } else {
788         error = 0;
789     }
790     return error;
791 }
792
793 /*
794  * Returns a pointer to 'netdev''s MAC address.  The caller must not modify or
795  * free the returned buffer.
796  */
797 static int
798 netdev_bsd_get_etheraddr(const struct netdev *netdev_,
799                          uint8_t mac[ETH_ADDR_LEN])
800 {
801     struct netdev_dev_bsd *netdev_dev =
802         netdev_dev_bsd_cast(netdev_get_dev(netdev_));
803
804     if (!(netdev_dev->cache_valid & VALID_ETHERADDR)) {
805         int error = get_etheraddr(netdev_get_name(netdev_),
806                                   netdev_dev->etheraddr);
807         if (error) {
808             return error;
809         }
810         netdev_dev->cache_valid |= VALID_ETHERADDR;
811     }
812     memcpy(mac, netdev_dev->etheraddr, ETH_ADDR_LEN);
813
814     return 0;
815 }
816
817 /*
818  * Returns the maximum size of transmitted (and received) packets on 'netdev',
819  * in bytes, not including the hardware header; thus, this is typically 1500
820  * bytes for Ethernet devices.
821  */
822 static int
823 netdev_bsd_get_mtu(const struct netdev *netdev_, int *mtup)
824 {
825     struct netdev_dev_bsd *netdev_dev =
826         netdev_dev_bsd_cast(netdev_get_dev(netdev_));
827
828     if (!(netdev_dev->cache_valid & VALID_MTU)) {
829         struct ifreq ifr;
830         int error;
831
832         error = netdev_bsd_do_ioctl(netdev_get_name(netdev_), &ifr, SIOCGIFMTU,
833                                     "SIOCGIFMTU");
834         if (error) {
835             return error;
836         }
837         netdev_dev->mtu = ifr.ifr_mtu;
838         netdev_dev->cache_valid |= VALID_MTU;
839     }
840
841     *mtup = netdev_dev->mtu;
842     return 0;
843 }
844
845 static int
846 netdev_bsd_get_ifindex(const struct netdev *netdev)
847 {
848     int ifindex, error;
849
850     error = get_ifindex(netdev, &ifindex);
851     return error ? -error : ifindex;
852 }
853
854 static int
855 netdev_bsd_get_carrier(const struct netdev *netdev_, bool *carrier)
856 {
857     struct netdev_dev_bsd *netdev_dev =
858         netdev_dev_bsd_cast(netdev_get_dev(netdev_));
859
860     if (!(netdev_dev->cache_valid & VALID_CARRIER)) {
861         struct ifmediareq ifmr;
862
863         memset(&ifmr, 0, sizeof(ifmr));
864         strncpy(ifmr.ifm_name, netdev_get_name(netdev_), sizeof ifmr.ifm_name);
865
866         if (ioctl(af_inet_sock, SIOCGIFMEDIA, &ifmr) == -1) {
867             VLOG_DBG_RL(&rl, "%s: ioctl(SIOCGIFMEDIA) failed: %s",
868                         netdev_get_name(netdev_), strerror(errno));
869             return errno;
870         }
871
872         netdev_dev->carrier = (ifmr.ifm_status & IFM_ACTIVE) == IFM_ACTIVE;
873         netdev_dev->cache_valid |= VALID_CARRIER;
874
875         /* If the interface doesn't report whether the media is active,
876          * just assume it is active. */
877         if ((ifmr.ifm_status & IFM_AVALID) == 0) {
878             netdev_dev->carrier = true;
879         }
880     }
881     *carrier = netdev_dev->carrier;
882
883     return 0;
884 }
885
886 /* Retrieves current device stats for 'netdev'. */
887 static int
888 netdev_bsd_get_stats(const struct netdev *netdev_, struct netdev_stats *stats)
889 {
890     int if_count, i;
891     int mib[6];
892     size_t len;
893     struct ifmibdata ifmd;
894
895
896     mib[0] = CTL_NET;
897     mib[1] = PF_LINK;
898     mib[2] = NETLINK_GENERIC;
899     mib[3] = IFMIB_SYSTEM;
900     mib[4] = IFMIB_IFCOUNT;
901
902     len = sizeof(if_count);
903
904     if (sysctl(mib, 5, &if_count, &len, (void *)0, 0) == -1) {
905         VLOG_DBG_RL(&rl, "%s: sysctl failed: %s",
906                     netdev_get_name(netdev_), strerror(errno));
907         return errno;
908     }
909
910     mib[5] = IFDATA_GENERAL;
911     mib[3] = IFMIB_IFDATA;
912     len = sizeof(ifmd);
913     for (i = 1; i <= if_count; i++) {
914         mib[4] = i; //row
915         if (sysctl(mib, 6, &ifmd, &len, (void *)0, 0) == -1) {
916             VLOG_DBG_RL(&rl, "%s: sysctl failed: %s",
917                         netdev_get_name(netdev_), strerror(errno));
918             return errno;
919         } else if (!strcmp(ifmd.ifmd_name, netdev_get_name(netdev_))) {
920             stats->rx_packets = ifmd.ifmd_data.ifi_ipackets;
921             stats->tx_packets = ifmd.ifmd_data.ifi_opackets;
922             stats->rx_bytes = ifmd.ifmd_data.ifi_ibytes;
923             stats->tx_bytes = ifmd.ifmd_data.ifi_obytes;
924             stats->rx_errors = ifmd.ifmd_data.ifi_ierrors;
925             stats->tx_errors = ifmd.ifmd_data.ifi_oerrors;
926             stats->rx_dropped = ifmd.ifmd_data.ifi_iqdrops;
927             stats->tx_dropped = UINT64_MAX;
928             stats->multicast = ifmd.ifmd_data.ifi_imcasts;
929             stats->collisions = ifmd.ifmd_data.ifi_collisions;
930
931             stats->rx_length_errors = UINT64_MAX;
932             stats->rx_over_errors = UINT64_MAX;
933             stats->rx_crc_errors = UINT64_MAX;
934             stats->rx_frame_errors = UINT64_MAX;
935             stats->rx_fifo_errors = UINT64_MAX;
936             stats->rx_missed_errors = UINT64_MAX;
937
938             stats->tx_aborted_errors = UINT64_MAX;
939             stats->tx_carrier_errors = UINT64_MAX;
940             stats->tx_fifo_errors = UINT64_MAX;
941             stats->tx_heartbeat_errors = UINT64_MAX;
942             stats->tx_window_errors = UINT64_MAX;
943             break;
944         }
945     }
946
947     return 0;
948 }
949
950 static uint32_t
951 netdev_bsd_parse_media(int media)
952 {
953     uint32_t supported = 0;
954     bool half_duplex = media & IFM_HDX ? true : false;
955
956     switch (IFM_SUBTYPE(media)) {
957     case IFM_10_2:
958     case IFM_10_5:
959     case IFM_10_STP:
960     case IFM_10_T:
961         supported |= half_duplex ? NETDEV_F_10MB_HD : NETDEV_F_10MB_FD;
962         supported |= NETDEV_F_COPPER;
963         break;
964
965     case IFM_10_FL:
966         supported |= half_duplex ? NETDEV_F_10MB_HD : NETDEV_F_10MB_FD;
967         supported |= NETDEV_F_FIBER;
968         break;
969
970     case IFM_100_T2:
971     case IFM_100_T4:
972     case IFM_100_TX:
973     case IFM_100_VG:
974         supported |= half_duplex ? NETDEV_F_100MB_HD : NETDEV_F_100MB_FD;
975         supported |= NETDEV_F_COPPER;
976         break;
977
978     case IFM_100_FX:
979         supported |= half_duplex ? NETDEV_F_100MB_HD : NETDEV_F_100MB_FD;
980         supported |= NETDEV_F_FIBER;
981         break;
982
983     case IFM_1000_CX:
984     case IFM_1000_T:
985         supported |= half_duplex ? NETDEV_F_1GB_HD : NETDEV_F_1GB_FD;
986         supported |= NETDEV_F_COPPER;
987         break;
988
989     case IFM_1000_LX:
990     case IFM_1000_SX:
991         supported |= half_duplex ? NETDEV_F_1GB_HD : NETDEV_F_1GB_FD;
992         supported |= NETDEV_F_FIBER;
993         break;
994
995     case IFM_10G_CX4:
996         supported |= NETDEV_F_10GB_FD;
997         supported |= NETDEV_F_COPPER;
998         break;
999
1000     case IFM_10G_LR:
1001     case IFM_10G_SR:
1002         supported |= NETDEV_F_10GB_FD;
1003         supported |= NETDEV_F_FIBER;
1004         break;
1005
1006     default:
1007         return 0;
1008     }
1009
1010     if (IFM_SUBTYPE(media) == IFM_AUTO) {
1011         supported |= NETDEV_F_AUTONEG;
1012     }
1013     /*
1014     if (media & IFM_ETH_FMASK) {
1015         supported |= NETDEV_F_PAUSE;
1016     }
1017     */
1018
1019     return supported;
1020 }
1021
1022 /*
1023  * Stores the features supported by 'netdev' into each of '*current',
1024  * '*advertised', '*supported', and '*peer' that are non-null.  Each value is a
1025  * bitmap of "enum ofp_port_features" bits, in host byte order.  Returns 0 if
1026  * successful, otherwise a positive errno value.  On failure, all of the
1027  * passed-in values are set to 0.
1028  */
1029 static int
1030 netdev_bsd_get_features(const struct netdev *netdev,
1031                         enum netdev_features *current, uint32_t *advertised,
1032                         enum netdev_features *supported, uint32_t *peer)
1033 {
1034     struct ifmediareq ifmr;
1035     int *media_list;
1036     int i;
1037     int error;
1038
1039
1040     /* XXX Look into SIOCGIFCAP instead of SIOCGIFMEDIA */
1041
1042     memset(&ifmr, 0, sizeof(ifmr));
1043     strncpy(ifmr.ifm_name, netdev_get_name(netdev), sizeof ifmr.ifm_name);
1044
1045     /* We make two SIOCGIFMEDIA ioctl calls.  The first to determine the
1046      * number of supported modes, and a second with a buffer to retrieve
1047      * them. */
1048     if (ioctl(af_inet_sock, SIOCGIFMEDIA, &ifmr) == -1) {
1049         VLOG_DBG_RL(&rl, "%s: ioctl(SIOCGIFMEDIA) failed: %s",
1050                     netdev_get_name(netdev), strerror(errno));
1051         return errno;
1052     }
1053
1054     media_list = xcalloc(ifmr.ifm_count, sizeof(int));
1055     ifmr.ifm_ulist = media_list;
1056
1057     if (IFM_TYPE(ifmr.ifm_current) != IFM_ETHER) {
1058         VLOG_DBG_RL(&rl, "%s: doesn't appear to be ethernet",
1059                     netdev_get_name(netdev));
1060         error = EINVAL;
1061         goto cleanup;
1062     }
1063
1064     if (ioctl(af_inet_sock, SIOCGIFMEDIA, &ifmr) == -1) {
1065         VLOG_DBG_RL(&rl, "%s: ioctl(SIOCGIFMEDIA) failed: %s",
1066                     netdev_get_name(netdev), strerror(errno));
1067         error = errno;
1068         goto cleanup;
1069     }
1070
1071     /* Current settings. */
1072     *current = netdev_bsd_parse_media(ifmr.ifm_active);
1073
1074     /* Advertised features. */
1075     *advertised = netdev_bsd_parse_media(ifmr.ifm_current);
1076
1077     /* Supported features. */
1078     *supported = 0;
1079     for (i = 0; i < ifmr.ifm_count; i++) {
1080         *supported |= netdev_bsd_parse_media(ifmr.ifm_ulist[i]);
1081     }
1082
1083     /* Peer advertisements. */
1084     *peer = 0;                  /* XXX */
1085
1086     error = 0;
1087 cleanup:
1088     free(media_list);
1089     return error;
1090 }
1091
1092 /*
1093  * If 'netdev' has an assigned IPv4 address, sets '*in4' to that address (if
1094  * 'in4' is non-null) and returns true.  Otherwise, returns false.
1095  */
1096 static int
1097 netdev_bsd_get_in4(const struct netdev *netdev_, struct in_addr *in4,
1098                    struct in_addr *netmask)
1099 {
1100     struct netdev_dev_bsd *netdev_dev =
1101         netdev_dev_bsd_cast(netdev_get_dev(netdev_));
1102
1103     if (!(netdev_dev->cache_valid & VALID_IN4)) {
1104         const struct sockaddr_in *sin;
1105         struct ifreq ifr;
1106         int error;
1107
1108         ifr.ifr_addr.sa_family = AF_INET;
1109         error = netdev_bsd_do_ioctl(netdev_get_name(netdev_), &ifr,
1110                                     SIOCGIFADDR, "SIOCGIFADDR");
1111         if (error) {
1112             return error;
1113         }
1114
1115         sin = (struct sockaddr_in *) &ifr.ifr_addr;
1116         netdev_dev->in4 = sin->sin_addr;
1117         netdev_dev->cache_valid |= VALID_IN4;
1118         error = netdev_bsd_do_ioctl(netdev_get_name(netdev_), &ifr,
1119                                     SIOCGIFNETMASK, "SIOCGIFNETMASK");
1120         if (error) {
1121             return error;
1122         }
1123         *netmask = ((struct sockaddr_in*)&ifr.ifr_addr)->sin_addr;
1124     }
1125     *in4 = netdev_dev->in4;
1126
1127     return in4->s_addr == INADDR_ANY ? EADDRNOTAVAIL : 0;
1128 }
1129
1130 /*
1131  * Assigns 'addr' as 'netdev''s IPv4 address and 'mask' as its netmask.  If
1132  * 'addr' is INADDR_ANY, 'netdev''s IPv4 address is cleared.  Returns a
1133  * positive errno value.
1134  */
1135 static int
1136 netdev_bsd_set_in4(struct netdev *netdev_, struct in_addr addr,
1137                    struct in_addr mask)
1138 {
1139     struct netdev_dev_bsd *netdev_dev =
1140         netdev_dev_bsd_cast(netdev_get_dev(netdev_));
1141     int error;
1142
1143     error = do_set_addr(netdev_, SIOCSIFADDR, "SIOCSIFADDR", addr);
1144     if (!error) {
1145         netdev_dev->cache_valid |= VALID_IN4;
1146         netdev_dev->in4 = addr;
1147         if (addr.s_addr != INADDR_ANY) {
1148             error = do_set_addr(netdev_, SIOCSIFNETMASK,
1149                                 "SIOCSIFNETMASK", mask);
1150         }
1151         netdev_dev_bsd_changed(netdev_dev);
1152     }
1153     return error;
1154 }
1155
1156 static int
1157 netdev_bsd_get_in6(const struct netdev *netdev_, struct in6_addr *in6)
1158 {
1159     struct netdev_dev_bsd *netdev_dev =
1160                                 netdev_dev_bsd_cast(netdev_get_dev(netdev_));
1161     if (!(netdev_dev->cache_valid & VALID_IN6)) {
1162         struct ifaddrs *ifa, *head;
1163         struct sockaddr_in6 *sin6;
1164         const char *netdev_name = netdev_get_name(netdev_);
1165
1166         if (getifaddrs(&head) != 0) {
1167             VLOG_ERR("getifaddrs on %s device failed: %s", netdev_name,
1168                     strerror(errno));
1169             return errno;
1170         }
1171
1172         for (ifa = head; ifa; ifa = ifa->ifa_next) {
1173             if (ifa->ifa_addr->sa_family == AF_INET6 &&
1174                     !strcmp(ifa->ifa_name, netdev_name)) {
1175                 sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
1176                 if (sin6) {
1177                     memcpy(&netdev_dev->in6, &sin6->sin6_addr, sin6->sin6_len);
1178                     netdev_dev->cache_valid |= VALID_IN6;
1179                     *in6 = netdev_dev->in6;
1180                     freeifaddrs(head);
1181                     return 0;
1182                 }
1183             }
1184         }
1185         return EADDRNOTAVAIL;
1186     }
1187     *in6 = netdev_dev->in6;
1188     return 0;
1189 }
1190
1191 static void
1192 make_in4_sockaddr(struct sockaddr *sa, struct in_addr addr)
1193 {
1194     struct sockaddr_in sin;
1195     memset(&sin, 0, sizeof sin);
1196     sin.sin_family = AF_INET;
1197     sin.sin_addr = addr;
1198     sin.sin_port = 0;
1199
1200     memset(sa, 0, sizeof *sa);
1201     memcpy(sa, &sin, sizeof sin);
1202 }
1203
1204 static int
1205 do_set_addr(struct netdev *netdev,
1206             int ioctl_nr, const char *ioctl_name, struct in_addr addr)
1207 {
1208     struct ifreq ifr;
1209     make_in4_sockaddr(&ifr.ifr_addr, addr);
1210     return netdev_bsd_do_ioctl(netdev, &ifr, ioctl_nr, ioctl_name);
1211 }
1212
1213 static int
1214 nd_to_iff_flags(enum netdev_flags nd)
1215 {
1216     int iff = 0;
1217     if (nd & NETDEV_UP) {
1218         iff |= IFF_UP;
1219     }
1220     if (nd & NETDEV_PROMISC) {
1221         iff |= IFF_PROMISC;
1222         iff |= IFF_PPROMISC;
1223     }
1224     return iff;
1225 }
1226
1227 static int
1228 iff_to_nd_flags(int iff)
1229 {
1230     enum netdev_flags nd = 0;
1231     if (iff & IFF_UP) {
1232         nd |= NETDEV_UP;
1233     }
1234     if (iff & IFF_PROMISC) {
1235         nd |= NETDEV_PROMISC;
1236     }
1237     return nd;
1238 }
1239
1240 static int
1241 netdev_bsd_update_flags(struct netdev_dev *dev_, enum netdev_flags off,
1242                         enum netdev_flags on, enum netdev_flags *old_flagsp)
1243 {
1244     struct netdev_dev_bsd *netdev_dev;
1245     int old_flags, new_flags;
1246     int error;
1247
1248     netdev_dev = netdev_dev_bsd_cast(dev_);
1249     error = get_flags(dev_, &old_flags);
1250     if (!error) {
1251         *old_flagsp = iff_to_nd_flags(old_flags);
1252         new_flags = (old_flags & ~nd_to_iff_flags(off)) | nd_to_iff_flags(on);
1253         if (new_flags != old_flags) {
1254             error = set_flags(netdev_dev_get_name(dev_), new_flags);
1255             netdev_dev_bsd_changed(netdev_dev);
1256         }
1257     }
1258     return error;
1259 }
1260
1261 static unsigned int
1262 netdev_bsd_change_seq(const struct netdev *netdev)
1263 {
1264     return netdev_dev_bsd_cast(netdev_get_dev(netdev))->change_seq;
1265 }
1266
1267
1268 const struct netdev_class netdev_bsd_class = {
1269     "system",
1270
1271     netdev_bsd_init,
1272     netdev_bsd_run,
1273     netdev_bsd_wait,
1274     netdev_bsd_create_system,
1275     netdev_bsd_destroy,
1276     NULL, /* get_config */
1277     NULL, /* set_config */
1278     NULL, /* get_tunnel_config */
1279     netdev_bsd_open_system,
1280     netdev_bsd_close,
1281
1282     netdev_bsd_rx_open,
1283
1284     netdev_bsd_send,
1285     netdev_bsd_send_wait,
1286
1287     netdev_bsd_set_etheraddr,
1288     netdev_bsd_get_etheraddr,
1289     netdev_bsd_get_mtu,
1290     NULL, /* set_mtu */
1291     netdev_bsd_get_ifindex,
1292     netdev_bsd_get_carrier,
1293     NULL, /* get_carrier_resets */
1294     NULL, /* set_miimon_interval */
1295     netdev_bsd_get_stats,
1296     NULL, /* set_stats */
1297
1298     netdev_bsd_get_features,
1299     NULL, /* set_advertisement */
1300     NULL, /* set_policing */
1301     NULL, /* get_qos_type */
1302     NULL, /* get_qos_capabilities */
1303     NULL, /* get_qos */
1304     NULL, /* set_qos */
1305     NULL, /* get_queue */
1306     NULL, /* set_queue */
1307     NULL, /* delete_queue */
1308     NULL, /* get_queue_stats */
1309     NULL, /* dump_queue */
1310     NULL, /* dump_queue_stats */
1311
1312     netdev_bsd_get_in4,
1313     netdev_bsd_set_in4,
1314     netdev_bsd_get_in6,
1315     NULL, /* add_router */
1316     NULL, /* get_next_hop */
1317     NULL, /* get_status */
1318     NULL, /* arp_lookup */
1319
1320     netdev_bsd_update_flags,
1321
1322     netdev_bsd_change_seq
1323 };
1324
1325 const struct netdev_class netdev_tap_class = {
1326     "tap",
1327
1328     netdev_bsd_init,
1329     netdev_bsd_run,
1330     netdev_bsd_wait,
1331     netdev_bsd_create_tap,
1332     netdev_bsd_destroy,
1333     NULL, /* get_config */
1334     NULL, /* set_config */
1335     NULL, /* get_tunnel_config */
1336     netdev_bsd_open_system,
1337     netdev_bsd_close,
1338
1339     netdev_bsd_rx_open,
1340
1341     netdev_bsd_send,
1342     netdev_bsd_send_wait,
1343
1344     netdev_bsd_set_etheraddr,
1345     netdev_bsd_get_etheraddr,
1346     netdev_bsd_get_mtu,
1347     NULL, /* set_mtu */
1348     netdev_bsd_get_ifindex,
1349     netdev_bsd_get_carrier,
1350     NULL, /* get_carrier_resets */
1351     NULL, /* set_miimon_interval */
1352     netdev_bsd_get_stats,
1353     NULL, /* set_stats */
1354
1355     netdev_bsd_get_features,
1356     NULL, /* set_advertisement */
1357     NULL, /* set_policing */
1358     NULL, /* get_qos_type */
1359     NULL, /* get_qos_capabilities */
1360     NULL, /* get_qos */
1361     NULL, /* set_qos */
1362     NULL, /* get_queue */
1363     NULL, /* set_queue */
1364     NULL, /* delete_queue */
1365     NULL, /* get_queue_stats */
1366     NULL, /* dump_queue */
1367     NULL, /* dump_queue_stats */
1368
1369     netdev_bsd_get_in4,
1370     netdev_bsd_set_in4,
1371     netdev_bsd_get_in6,
1372     NULL, /* add_router */
1373     NULL, /* get_next_hop */
1374     NULL, /* get_status */
1375     NULL, /* arp_lookup */
1376
1377     netdev_bsd_update_flags,
1378
1379     netdev_bsd_change_seq
1380 };
1381
1382 static const struct netdev_rx_class netdev_rx_bsd_class = {
1383     netdev_rx_bsd_destroy,
1384     netdev_rx_bsd_recv,
1385     netdev_rx_bsd_wait,
1386     netdev_rx_bsd_drain,
1387 };
1388 \f
1389
1390 static void
1391 destroy_tap(int fd, const char *name)
1392 {
1393     struct ifreq ifr;
1394
1395     close(fd);
1396     strcpy(ifr.ifr_name, name);
1397     /* XXX What to do if this call fails? */
1398     ioctl(af_inet_sock, SIOCIFDESTROY, &ifr);
1399 }
1400
1401 static int
1402 get_flags(const struct netdev_dev *dev, int *flags)
1403 {
1404     struct ifreq ifr;
1405     int error;
1406
1407     error = netdev_bsd_do_ioctl(dev->name, &ifr, SIOCGIFFLAGS, "SIOCGIFFLAGS");
1408
1409     *flags = 0xFFFF0000 & (ifr.ifr_flagshigh << 16);
1410     *flags |= 0x0000FFFF & ifr.ifr_flags;
1411
1412     return error;
1413 }
1414
1415 static int
1416 set_flags(const char *name, int flags)
1417 {
1418     struct ifreq ifr;
1419
1420     ifr.ifr_flags = 0x0000FFFF & flags;
1421     ifr.ifr_flagshigh = (0xFFFF0000 & flags) >> 16;
1422
1423     return netdev_bsd_do_ioctl(name, &ifr, SIOCSIFFLAGS, "SIOCSIFFLAGS");
1424 }
1425
1426 static int
1427 get_ifindex(const struct netdev *netdev_, int *ifindexp)
1428 {
1429     struct netdev_dev_bsd *netdev_dev =
1430                                 netdev_dev_bsd_cast(netdev_get_dev(netdev_));
1431     *ifindexp = 0;
1432     if (!(netdev_dev->cache_valid & VALID_IFINDEX)) {
1433         int ifindex = if_nametoindex(netdev_get_name(netdev_));
1434         if (ifindex <= 0) {
1435             return errno;
1436         }
1437         netdev_dev->cache_valid |= VALID_IFINDEX;
1438         netdev_dev->ifindex = ifindex;
1439     }
1440     *ifindexp = netdev_dev->ifindex;
1441     return 0;
1442 }
1443
1444 static int
1445 get_etheraddr(const char *netdev_name, uint8_t ea[ETH_ADDR_LEN])
1446 {
1447     struct ifaddrs *head;
1448     struct ifaddrs *ifa;
1449     struct sockaddr_dl *sdl;
1450
1451     if (getifaddrs(&head) != 0) {
1452         VLOG_ERR("getifaddrs on %s device failed: %s", netdev_name,
1453                 strerror(errno));
1454         return errno;
1455     }
1456
1457     for (ifa = head; ifa; ifa = ifa->ifa_next) {
1458         if (ifa->ifa_addr->sa_family == AF_LINK) {
1459             if (!strcmp(ifa->ifa_name, netdev_name)) {
1460                 sdl = (struct sockaddr_dl *)ifa->ifa_addr;
1461                 if (sdl) {
1462                     memcpy(ea, LLADDR(sdl), sdl->sdl_alen);
1463                     freeifaddrs(head);
1464                     return 0;
1465                 }
1466             }
1467         }
1468     }
1469
1470     VLOG_ERR("could not find ethernet address for %s device", netdev_name);
1471     freeifaddrs(head);
1472     return ENODEV;
1473 }
1474
1475 static int
1476 set_etheraddr(const char *netdev_name, int hwaddr_family,
1477               int hwaddr_len, const uint8_t mac[ETH_ADDR_LEN])
1478 {
1479     struct ifreq ifr;
1480
1481     memset(&ifr, 0, sizeof ifr);
1482     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
1483     ifr.ifr_addr.sa_family = hwaddr_family;
1484     ifr.ifr_addr.sa_len = hwaddr_len;
1485     memcpy(ifr.ifr_addr.sa_data, mac, hwaddr_len);
1486     if (ioctl(af_inet_sock, SIOCSIFLLADDR, &ifr) < 0) {
1487         VLOG_ERR("ioctl(SIOCSIFLLADDR) on %s device failed: %s",
1488                  netdev_name, strerror(errno));
1489         return errno;
1490     }
1491     return 0;
1492 }
1493
1494 static int
1495 netdev_bsd_do_ioctl(const char *name, struct ifreq *ifr, unsigned long cmd,
1496                     const char *cmd_name)
1497 {
1498     strncpy(ifr->ifr_name, name, sizeof ifr->ifr_name);
1499     if (ioctl(af_inet_sock, cmd, ifr) == -1) {
1500         VLOG_DBG_RL(&rl, "%s: ioctl(%s) failed: %s", name, cmd_name,
1501                     strerror(errno));
1502         return errno;
1503     }
1504     return 0;
1505 }