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