netdev: Fix reversed arguments in netdev_recv warning.
[sliver-openvswitch.git] / lib / netdev.c
1 /*
2  * Copyright (c) 2008, 2009 Nicira Networks.
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 #include "netdev.h"
19
20 #include <assert.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <arpa/inet.h>
24 #include <inttypes.h>
25 #include <linux/if_tun.h>
26 #include <linux/types.h>
27 #include <linux/ethtool.h>
28 #include <linux/rtnetlink.h>
29 #include <linux/sockios.h>
30 #include <linux/version.h>
31 #include <sys/types.h>
32 #include <sys/ioctl.h>
33 #include <sys/socket.h>
34 #include <netpacket/packet.h>
35 #include <net/ethernet.h>
36 #include <net/if.h>
37 #include <net/if_arp.h>
38 #include <net/if_packet.h>
39 #include <net/route.h>
40 #include <netinet/in.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <unistd.h>
44
45 #include "coverage.h"
46 #include "dynamic-string.h"
47 #include "fatal-signal.h"
48 #include "list.h"
49 #include "netlink.h"
50 #include "ofpbuf.h"
51 #include "openflow/openflow.h"
52 #include "packets.h"
53 #include "poll-loop.h"
54 #include "socket-util.h"
55 #include "svec.h"
56
57 /* linux/if.h defines IFF_LOWER_UP, net/if.h doesn't.
58  * net/if.h defines if_nameindex(), linux/if.h doesn't.
59  * We can't include both headers, so define IFF_LOWER_UP ourselves. */
60 #ifndef IFF_LOWER_UP
61 #define IFF_LOWER_UP 0x10000
62 #endif
63
64 /* These were introduced in Linux 2.6.14, so they might be missing if we have
65  * old headers. */
66 #ifndef ADVERTISED_Pause
67 #define ADVERTISED_Pause                (1 << 13)
68 #endif
69 #ifndef ADVERTISED_Asym_Pause
70 #define ADVERTISED_Asym_Pause           (1 << 14)
71 #endif
72
73 #define THIS_MODULE VLM_netdev
74 #include "vlog.h"
75
76 struct netdev {
77     struct list node;
78     char *name;
79
80     /* File descriptors.  For ordinary network devices, the two fds below are
81      * the same; for tap devices, they differ. */
82     int netdev_fd;              /* Network device. */
83     int tap_fd;                 /* TAP character device, if any, otherwise the
84                                  * network device. */
85
86     /* Cached network device information. */
87     int ifindex;                /* -1 if not known. */
88     uint8_t etheraddr[ETH_ADDR_LEN];
89     struct in6_addr in6;
90     int speed;
91     int mtu;
92     int txqlen;
93     int hwaddr_family;
94
95     int save_flags;             /* Initial device flags. */
96     int changed_flags;          /* Flags that we changed. */
97 };
98
99 /* Policy for RTNLGRP_LINK messages.
100  *
101  * There are *many* more fields in these messages, but currently we only care
102  * about interface names. */
103 static const struct nl_policy rtnlgrp_link_policy[] = {
104     [IFLA_IFNAME] = { .type = NL_A_STRING, .optional = false },
105     [IFLA_STATS] = { .type = NL_A_UNSPEC, .optional = true,
106                      .min_len = sizeof(struct rtnl_link_stats) },
107 };
108
109 /* All open network devices. */
110 static struct list netdev_list = LIST_INITIALIZER(&netdev_list);
111
112 /* An AF_INET socket (used for ioctl operations). */
113 static int af_inet_sock = -1;
114
115 /* NETLINK_ROUTE socket. */
116 static struct nl_sock *rtnl_sock;
117
118 /* Can we use RTM_GETLINK to get network device statistics?  (In pre-2.6.19
119  * kernels, this was only available if wireless extensions were enabled.) */
120 static bool use_netlink_stats;
121
122 /* This is set pretty low because we probably won't learn anything from the
123  * additional log messages. */
124 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
125
126 static void init_netdev(void);
127 static int do_open_netdev(const char *name, int ethertype, int tap_fd,
128                           struct netdev **netdev_);
129 static int restore_flags(struct netdev *netdev);
130 static int get_flags(const char *netdev_name, int *flagsp);
131 static int set_flags(const char *netdev_name, int flags);
132 static int do_get_ifindex(const char *netdev_name);
133 static int get_ifindex(const struct netdev *, int *ifindexp);
134 static int get_etheraddr(const char *netdev_name, uint8_t ea[ETH_ADDR_LEN],
135                          int *hwaddr_familyp);
136 static int set_etheraddr(const char *netdev_name, int hwaddr_family,
137                          const uint8_t[ETH_ADDR_LEN]);
138
139 /* Obtains the IPv6 address for 'name' into 'in6'. */
140 static void
141 get_ipv6_address(const char *name, struct in6_addr *in6)
142 {
143     FILE *file;
144     char line[128];
145
146     file = fopen("/proc/net/if_inet6", "r");
147     if (file == NULL) {
148         /* This most likely indicates that the host doesn't have IPv6 support,
149          * so it's not really a failure condition.*/
150         *in6 = in6addr_any;
151         return;
152     }
153
154     while (fgets(line, sizeof line, file)) {
155         uint8_t *s6 = in6->s6_addr;
156         char ifname[16 + 1];
157
158 #define X8 "%2"SCNx8
159         if (sscanf(line, " "X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8
160                    "%*x %*x %*x %*x %16s\n",
161                    &s6[0], &s6[1], &s6[2], &s6[3],
162                    &s6[4], &s6[5], &s6[6], &s6[7],
163                    &s6[8], &s6[9], &s6[10], &s6[11],
164                    &s6[12], &s6[13], &s6[14], &s6[15],
165                    ifname) == 17
166             && !strcmp(name, ifname))
167         {
168             fclose(file);
169             return;
170         }
171     }
172     *in6 = in6addr_any;
173
174     fclose(file);
175 }
176
177 static int
178 do_ethtool(struct netdev *netdev, struct ethtool_cmd *ecmd,
179            int cmd, const char *cmd_name)
180 {
181     struct ifreq ifr;
182
183     memset(&ifr, 0, sizeof ifr);
184     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
185     ifr.ifr_data = (caddr_t) ecmd;
186
187     ecmd->cmd = cmd;
188     COVERAGE_INC(netdev_ethtool);
189     if (ioctl(netdev->netdev_fd, SIOCETHTOOL, &ifr) == 0) {
190         return 0;
191     } else {
192         if (errno != EOPNOTSUPP) {
193             VLOG_WARN_RL(&rl, "ethtool command %s on network device %s "
194                          "failed: %s", cmd_name, netdev->name,
195                          strerror(errno));
196         } else {
197             /* The device doesn't support this operation.  That's pretty
198              * common, so there's no point in logging anything. */
199         }
200         return errno;
201     }
202 }
203
204 static int
205 do_get_features(struct netdev *netdev,
206                 uint32_t *current, uint32_t *advertised,
207                 uint32_t *supported, uint32_t *peer)
208 {
209     struct ethtool_cmd ecmd;
210     int error;
211
212     *current = 0;
213     *supported = 0;
214     *advertised = 0;
215     *peer = 0;
216
217     memset(&ecmd, 0, sizeof ecmd);
218     error = do_ethtool(netdev, &ecmd, ETHTOOL_GSET, "ETHTOOL_GSET");
219     if (error) {
220         return error;
221     }
222
223     if (ecmd.supported & SUPPORTED_10baseT_Half) {
224         *supported |= OFPPF_10MB_HD;
225     }
226     if (ecmd.supported & SUPPORTED_10baseT_Full) {
227         *supported |= OFPPF_10MB_FD;
228     }
229     if (ecmd.supported & SUPPORTED_100baseT_Half)  {
230         *supported |= OFPPF_100MB_HD;
231     }
232     if (ecmd.supported & SUPPORTED_100baseT_Full) {
233         *supported |= OFPPF_100MB_FD;
234     }
235     if (ecmd.supported & SUPPORTED_1000baseT_Half) {
236         *supported |= OFPPF_1GB_HD;
237     }
238     if (ecmd.supported & SUPPORTED_1000baseT_Full) {
239         *supported |= OFPPF_1GB_FD;
240     }
241     if (ecmd.supported & SUPPORTED_10000baseT_Full) {
242         *supported |= OFPPF_10GB_FD;
243     }
244     if (ecmd.supported & SUPPORTED_TP) {
245         *supported |= OFPPF_COPPER;
246     }
247     if (ecmd.supported & SUPPORTED_FIBRE) {
248         *supported |= OFPPF_FIBER;
249     }
250     if (ecmd.supported & SUPPORTED_Autoneg) {
251         *supported |= OFPPF_AUTONEG;
252     }
253     if (ecmd.supported & SUPPORTED_Pause) {
254         *supported |= OFPPF_PAUSE;
255     }
256     if (ecmd.supported & SUPPORTED_Asym_Pause) {
257         *supported |= OFPPF_PAUSE_ASYM;
258     }
259
260     /* Set the advertised features */
261     if (ecmd.advertising & ADVERTISED_10baseT_Half) {
262         *advertised |= OFPPF_10MB_HD;
263     }
264     if (ecmd.advertising & ADVERTISED_10baseT_Full) {
265         *advertised |= OFPPF_10MB_FD;
266     }
267     if (ecmd.advertising & ADVERTISED_100baseT_Half) {
268         *advertised |= OFPPF_100MB_HD;
269     }
270     if (ecmd.advertising & ADVERTISED_100baseT_Full) {
271         *advertised |= OFPPF_100MB_FD;
272     }
273     if (ecmd.advertising & ADVERTISED_1000baseT_Half) {
274         *advertised |= OFPPF_1GB_HD;
275     }
276     if (ecmd.advertising & ADVERTISED_1000baseT_Full) {
277         *advertised |= OFPPF_1GB_FD;
278     }
279     if (ecmd.advertising & ADVERTISED_10000baseT_Full) {
280         *advertised |= OFPPF_10GB_FD;
281     }
282     if (ecmd.advertising & ADVERTISED_TP) {
283         *advertised |= OFPPF_COPPER;
284     }
285     if (ecmd.advertising & ADVERTISED_FIBRE) {
286         *advertised |= OFPPF_FIBER;
287     }
288     if (ecmd.advertising & ADVERTISED_Autoneg) {
289         *advertised |= OFPPF_AUTONEG;
290     }
291     if (ecmd.advertising & ADVERTISED_Pause) {
292         *advertised |= OFPPF_PAUSE;
293     }
294     if (ecmd.advertising & ADVERTISED_Asym_Pause) {
295         *advertised |= OFPPF_PAUSE_ASYM;
296     }
297
298     /* Set the current features */
299     if (ecmd.speed == SPEED_10) {
300         *current = (ecmd.duplex) ? OFPPF_10MB_FD : OFPPF_10MB_HD;
301     }
302     else if (ecmd.speed == SPEED_100) {
303         *current = (ecmd.duplex) ? OFPPF_100MB_FD : OFPPF_100MB_HD;
304     }
305     else if (ecmd.speed == SPEED_1000) {
306         *current = (ecmd.duplex) ? OFPPF_1GB_FD : OFPPF_1GB_HD;
307     }
308     else if (ecmd.speed == SPEED_10000) {
309         *current = OFPPF_10GB_FD;
310     }
311
312     if (ecmd.port == PORT_TP) {
313         *current |= OFPPF_COPPER;
314     }
315     else if (ecmd.port == PORT_FIBRE) {
316         *current |= OFPPF_FIBER;
317     }
318
319     if (ecmd.autoneg) {
320         *current |= OFPPF_AUTONEG;
321     }
322     return 0;
323 }
324
325 /* Opens the network device named 'name' (e.g. "eth0") and returns zero if
326  * successful, otherwise a positive errno value.  On success, sets '*netdevp'
327  * to the new network device, otherwise to null.
328  *
329  * 'ethertype' may be a 16-bit Ethernet protocol value in host byte order to
330  * capture frames of that type received on the device.  It may also be one of
331  * the 'enum netdev_pseudo_ethertype' values to receive frames in one of those
332  * categories. */
333 int
334 netdev_open(const char *name, int ethertype, struct netdev **netdevp) 
335 {
336     if (!strncmp(name, "tap:", 4)) {
337         return netdev_open_tap(name + 4, netdevp);
338     } else {
339         return do_open_netdev(name, ethertype, -1, netdevp); 
340     }
341 }
342
343 /* Opens a TAP virtual network device.  If 'name' is a nonnull, non-empty
344  * string, attempts to assign that name to the TAP device (failing if the name
345  * is already in use); otherwise, a name is automatically assigned.  Returns
346  * zero if successful, otherwise a positive errno value.  On success, sets
347  * '*netdevp' to the new network device, otherwise to null.  */
348 int
349 netdev_open_tap(const char *name, struct netdev **netdevp)
350 {
351     static const char tap_dev[] = "/dev/net/tun";
352     struct ifreq ifr;
353     int error;
354     int tap_fd;
355
356     tap_fd = open(tap_dev, O_RDWR);
357     if (tap_fd < 0) {
358         ovs_error(errno, "opening \"%s\" failed", tap_dev);
359         return errno;
360     }
361
362     memset(&ifr, 0, sizeof ifr);
363     ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
364     if (name) {
365         strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
366     }
367     if (ioctl(tap_fd, TUNSETIFF, &ifr) < 0) {
368         int error = errno;
369         ovs_error(error, "ioctl(TUNSETIFF) on \"%s\" failed", tap_dev);
370         close(tap_fd);
371         return error;
372     }
373
374     error = set_nonblocking(tap_fd);
375     if (error) {
376         ovs_error(error, "set_nonblocking on \"%s\" failed", tap_dev);
377         close(tap_fd);
378         return error;
379     }
380
381     error = do_open_netdev(ifr.ifr_name, NETDEV_ETH_TYPE_NONE, tap_fd,
382                            netdevp);
383     if (error) {
384         close(tap_fd);
385     }
386     return error;
387 }
388
389 static int
390 do_open_netdev(const char *name, int ethertype, int tap_fd,
391                struct netdev **netdev_)
392 {
393     int netdev_fd;
394     struct sockaddr_ll sll;
395     struct ifreq ifr;
396     int ifindex = -1;
397     uint8_t etheraddr[ETH_ADDR_LEN];
398     struct in6_addr in6;
399     int mtu;
400     int txqlen;
401     int hwaddr_family;
402     int error;
403     struct netdev *netdev;
404
405     init_netdev();
406     *netdev_ = NULL;
407     COVERAGE_INC(netdev_open);
408
409     /* Create raw socket. */
410     netdev_fd = socket(PF_PACKET, SOCK_RAW,
411                        htons(ethertype == NETDEV_ETH_TYPE_NONE ? 0
412                              : ethertype == NETDEV_ETH_TYPE_ANY ? ETH_P_ALL
413                              : ethertype == NETDEV_ETH_TYPE_802_2 ? ETH_P_802_2
414                              : ethertype));
415     if (netdev_fd < 0) {
416         return errno;
417     }
418
419     if (ethertype != NETDEV_ETH_TYPE_NONE) {
420         /* Set non-blocking mode. */
421         error = set_nonblocking(netdev_fd);
422         if (error) {
423             goto error_already_set;
424         }
425
426         /* Get ethernet device index. */
427         ifindex = do_get_ifindex(name);
428         if (ifindex < 0) {
429             return -ifindex;
430         }
431
432         /* Bind to specific ethernet device. */
433         memset(&sll, 0, sizeof sll);
434         sll.sll_family = AF_PACKET;
435         sll.sll_ifindex = ifindex;
436         if (bind(netdev_fd, (struct sockaddr *) &sll, sizeof sll) < 0) {
437             VLOG_ERR("bind to %s failed: %s", name, strerror(errno));
438             goto error;
439         }
440
441         /* Between the socket() and bind() calls above, the socket receives all
442          * packets of the requested type on all system interfaces.  We do not
443          * want to receive that data, but there is no way to avoid it.  So we
444          * must now drain out the receive queue. */
445         error = drain_rcvbuf(netdev_fd);
446         if (error) {
447             goto error_already_set;
448         }
449     }
450
451     /* Get MAC address. */
452     error = get_etheraddr(name, etheraddr, &hwaddr_family);
453     if (error) {
454         goto error_already_set;
455     }
456
457     /* Get MTU. */
458     strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
459     if (ioctl(netdev_fd, SIOCGIFMTU, &ifr) < 0) {
460         VLOG_ERR("ioctl(SIOCGIFMTU) on %s device failed: %s",
461                  name, strerror(errno));
462         goto error;
463     }
464     mtu = ifr.ifr_mtu;
465
466     /* Get TX queue length. */
467     if (ioctl(netdev_fd, SIOCGIFTXQLEN, &ifr) < 0) {
468         VLOG_ERR("ioctl(SIOCGIFTXQLEN) on %s device failed: %s",
469                  name, strerror(errno));
470         goto error;
471     }
472     txqlen = ifr.ifr_qlen;
473
474     get_ipv6_address(name, &in6);
475
476     /* Allocate network device. */
477     netdev = xmalloc(sizeof *netdev);
478     netdev->name = xstrdup(name);
479     netdev->ifindex = ifindex;
480     netdev->txqlen = txqlen;
481     netdev->hwaddr_family = hwaddr_family;
482     netdev->netdev_fd = netdev_fd;
483     netdev->tap_fd = tap_fd < 0 ? netdev_fd : tap_fd;
484     memcpy(netdev->etheraddr, etheraddr, sizeof etheraddr);
485     netdev->mtu = mtu;
486     netdev->in6 = in6;
487
488     /* Save flags to restore at close or exit. */
489     error = get_flags(netdev->name, &netdev->save_flags);
490     if (error) {
491         goto error_already_set;
492     }
493     netdev->changed_flags = 0;
494     fatal_signal_block();
495     list_push_back(&netdev_list, &netdev->node);
496     fatal_signal_unblock();
497
498     /* Success! */
499     *netdev_ = netdev;
500     return 0;
501
502 error:
503     error = errno;
504 error_already_set:
505     close(netdev_fd);
506     if (tap_fd >= 0) {
507         close(tap_fd);
508     }
509     return error;
510 }
511
512 /* Closes and destroys 'netdev'. */
513 void
514 netdev_close(struct netdev *netdev)
515 {
516     if (netdev) {
517         /* Bring down interface and drop promiscuous mode, if we brought up
518          * the interface or enabled promiscuous mode. */
519         int error;
520         fatal_signal_block();
521         error = restore_flags(netdev);
522         list_remove(&netdev->node);
523         fatal_signal_unblock();
524         if (error) {
525             VLOG_WARN("failed to restore network device flags on %s: %s",
526                       netdev->name, strerror(error));
527         }
528
529         /* Free. */
530         free(netdev->name);
531         close(netdev->netdev_fd);
532         if (netdev->netdev_fd != netdev->tap_fd) {
533             close(netdev->tap_fd);
534         }
535         free(netdev);
536     }
537 }
538
539 /* Pads 'buffer' out with zero-bytes to the minimum valid length of an
540  * Ethernet packet, if necessary.  */
541 static void
542 pad_to_minimum_length(struct ofpbuf *buffer)
543 {
544     if (buffer->size < ETH_TOTAL_MIN) {
545         ofpbuf_put_zeros(buffer, ETH_TOTAL_MIN - buffer->size);
546     }
547 }
548
549 /* Attempts to receive a packet from 'netdev' into 'buffer', which the caller
550  * must have initialized with sufficient room for the packet.  The space
551  * required to receive any packet is ETH_HEADER_LEN bytes, plus VLAN_HEADER_LEN
552  * bytes, plus the device's MTU (which may be retrieved via netdev_get_mtu()).
553  * (Some devices do not allow for a VLAN header, in which case VLAN_HEADER_LEN
554  * need not be included.)
555  *
556  * If a packet is successfully retrieved, returns 0.  In this case 'buffer' is
557  * guaranteed to contain at least ETH_TOTAL_MIN bytes.  Otherwise, returns a
558  * positive errno value.  Returns EAGAIN immediately if no packet is ready to
559  * be returned.
560  */
561 int
562 netdev_recv(struct netdev *netdev, struct ofpbuf *buffer)
563 {
564     ssize_t n_bytes;
565
566     assert(buffer->size == 0);
567     assert(ofpbuf_tailroom(buffer) >= ETH_TOTAL_MIN);
568     do {
569         n_bytes = read(netdev->tap_fd,
570                        ofpbuf_tail(buffer), ofpbuf_tailroom(buffer));
571     } while (n_bytes < 0 && errno == EINTR);
572     if (n_bytes < 0) {
573         if (errno != EAGAIN) {
574             VLOG_WARN_RL(&rl, "error receiving Ethernet packet on %s: %s",
575                          netdev->name, strerror(errno));
576         }
577         return errno;
578     } else {
579         COVERAGE_INC(netdev_received);
580         buffer->size += n_bytes;
581
582         /* When the kernel internally sends out an Ethernet frame on an
583          * interface, it gives us a copy *before* padding the frame to the
584          * minimum length.  Thus, when it sends out something like an ARP
585          * request, we see a too-short frame.  So pad it out to the minimum
586          * length. */
587         pad_to_minimum_length(buffer);
588         return 0;
589     }
590 }
591
592 /* Registers with the poll loop to wake up from the next call to poll_block()
593  * when a packet is ready to be received with netdev_recv() on 'netdev'. */
594 void
595 netdev_recv_wait(struct netdev *netdev)
596 {
597     poll_fd_wait(netdev->tap_fd, POLLIN);
598 }
599
600 /* Discards all packets waiting to be received from 'netdev'. */
601 int
602 netdev_drain(struct netdev *netdev)
603 {
604     if (netdev->tap_fd != netdev->netdev_fd) {
605         drain_fd(netdev->tap_fd, netdev->txqlen);
606         return 0;
607     } else {
608         return drain_rcvbuf(netdev->netdev_fd);
609     }
610 }
611
612 /* Sends 'buffer' on 'netdev'.  Returns 0 if successful, otherwise a positive
613  * errno value.  Returns EAGAIN without blocking if the packet cannot be queued
614  * immediately.  Returns EMSGSIZE if a partial packet was transmitted or if
615  * the packet is too big or too small to transmit on the device.
616  *
617  * The caller retains ownership of 'buffer' in all cases.
618  *
619  * The kernel maintains a packet transmission queue, so the caller is not
620  * expected to do additional queuing of packets. */
621 int
622 netdev_send(struct netdev *netdev, const struct ofpbuf *buffer)
623 {
624     ssize_t n_bytes;
625
626     do {
627         n_bytes = write(netdev->tap_fd, buffer->data, buffer->size);
628     } while (n_bytes < 0 && errno == EINTR);
629
630     if (n_bytes < 0) {
631         /* The Linux AF_PACKET implementation never blocks waiting for room
632          * for packets, instead returning ENOBUFS.  Translate this into EAGAIN
633          * for the caller. */
634         if (errno == ENOBUFS) {
635             return EAGAIN;
636         } else if (errno != EAGAIN) {
637             VLOG_WARN_RL(&rl, "error sending Ethernet packet on %s: %s",
638                          netdev->name, strerror(errno));
639         }
640         return errno;
641     } else if (n_bytes != buffer->size) {
642         VLOG_WARN_RL(&rl,
643                      "send partial Ethernet packet (%d bytes of %zu) on %s",
644                      (int) n_bytes, buffer->size, netdev->name);
645         return EMSGSIZE;
646     } else {
647         COVERAGE_INC(netdev_sent);
648         return 0;
649     }
650 }
651
652 /* Registers with the poll loop to wake up from the next call to poll_block()
653  * when the packet transmission queue has sufficient room to transmit a packet
654  * with netdev_send().
655  *
656  * The kernel maintains a packet transmission queue, so the client is not
657  * expected to do additional queuing of packets.  Thus, this function is
658  * unlikely to ever be used.  It is included for completeness. */
659 void
660 netdev_send_wait(struct netdev *netdev)
661 {
662     if (netdev->tap_fd == netdev->netdev_fd) {
663         poll_fd_wait(netdev->tap_fd, POLLOUT);
664     } else {
665         /* TAP device always accepts packets.*/
666         poll_immediate_wake();
667     }
668 }
669
670 /* Attempts to set 'netdev''s MAC address to 'mac'.  Returns 0 if successful,
671  * otherwise a positive errno value. */
672 int
673 netdev_set_etheraddr(struct netdev *netdev, const uint8_t mac[ETH_ADDR_LEN])
674 {
675     int error = set_etheraddr(netdev->name, netdev->hwaddr_family, mac);
676     if (!error) {
677         memcpy(netdev->etheraddr, mac, ETH_ADDR_LEN);
678     }
679     return error;
680 }
681
682 int
683 netdev_nodev_set_etheraddr(const char *name, const uint8_t mac[ETH_ADDR_LEN])
684 {
685     init_netdev();
686     return set_etheraddr(name, ARPHRD_ETHER, mac);
687 }
688
689 /* Returns a pointer to 'netdev''s MAC address.  The caller must not modify or
690  * free the returned buffer. */
691 const uint8_t *
692 netdev_get_etheraddr(const struct netdev *netdev)
693 {
694     return netdev->etheraddr;
695 }
696
697 /* Returns the name of the network device that 'netdev' represents,
698  * e.g. "eth0".  The caller must not modify or free the returned string. */
699 const char *
700 netdev_get_name(const struct netdev *netdev)
701 {
702     return netdev->name;
703 }
704
705 /* Returns the maximum size of transmitted (and received) packets on 'netdev',
706  * in bytes, not including the hardware header; thus, this is typically 1500
707  * bytes for Ethernet devices. */
708 int
709 netdev_get_mtu(const struct netdev *netdev) 
710 {
711     return netdev->mtu;
712 }
713
714 /* Stores the features supported by 'netdev' into each of '*current',
715  * '*advertised', '*supported', and '*peer' that are non-null.  Each value is a
716  * bitmap of "enum ofp_port_features" bits, in host byte order.  Returns 0 if
717  * successful, otherwise a positive errno value.  On failure, all of the
718  * passed-in values are set to 0. */
719 int
720 netdev_get_features(struct netdev *netdev,
721                     uint32_t *current, uint32_t *advertised,
722                     uint32_t *supported, uint32_t *peer)
723 {
724     uint32_t dummy[4];
725     return do_get_features(netdev,
726                            current ? current : &dummy[0],
727                            advertised ? advertised : &dummy[1],
728                            supported ? supported : &dummy[2],
729                            peer ? peer : &dummy[3]);
730 }
731
732 int
733 netdev_set_advertisements(struct netdev *netdev, uint32_t advertise)
734 {
735     struct ethtool_cmd ecmd;
736     int error;
737
738     memset(&ecmd, 0, sizeof ecmd);
739     error = do_ethtool(netdev, &ecmd, ETHTOOL_GSET, "ETHTOOL_GSET");
740     if (error) {
741         return error;
742     }
743
744     ecmd.advertising = 0;
745     if (advertise & OFPPF_10MB_HD) {
746         ecmd.advertising |= ADVERTISED_10baseT_Half;
747     }
748     if (advertise & OFPPF_10MB_FD) {
749         ecmd.advertising |= ADVERTISED_10baseT_Full;
750     }
751     if (advertise & OFPPF_100MB_HD) {
752         ecmd.advertising |= ADVERTISED_100baseT_Half;
753     }
754     if (advertise & OFPPF_100MB_FD) {
755         ecmd.advertising |= ADVERTISED_100baseT_Full;
756     }
757     if (advertise & OFPPF_1GB_HD) {
758         ecmd.advertising |= ADVERTISED_1000baseT_Half;
759     }
760     if (advertise & OFPPF_1GB_FD) {
761         ecmd.advertising |= ADVERTISED_1000baseT_Full;
762     }
763     if (advertise & OFPPF_10GB_FD) {
764         ecmd.advertising |= ADVERTISED_10000baseT_Full;
765     }
766     if (advertise & OFPPF_COPPER) {
767         ecmd.advertising |= ADVERTISED_TP;
768     }
769     if (advertise & OFPPF_FIBER) {
770         ecmd.advertising |= ADVERTISED_FIBRE;
771     }
772     if (advertise & OFPPF_AUTONEG) {
773         ecmd.advertising |= ADVERTISED_Autoneg;
774     }
775     if (advertise & OFPPF_PAUSE) {
776         ecmd.advertising |= ADVERTISED_Pause;
777     }
778     if (advertise & OFPPF_PAUSE_ASYM) {
779         ecmd.advertising |= ADVERTISED_Asym_Pause;
780     }
781     return do_ethtool(netdev, &ecmd, ETHTOOL_SSET, "ETHTOOL_SSET");
782 }
783
784 /* If 'netdev' has an assigned IPv4 address, sets '*in4' to that address (if
785  * 'in4' is non-null) and returns true.  Otherwise, returns false. */
786 bool
787 netdev_nodev_get_in4(const char *netdev_name, struct in_addr *in4)
788 {
789     struct ifreq ifr;
790     struct in_addr ip = { INADDR_ANY };
791
792     init_netdev();
793
794     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
795     ifr.ifr_addr.sa_family = AF_INET;
796     COVERAGE_INC(netdev_get_in4);
797     if (ioctl(af_inet_sock, SIOCGIFADDR, &ifr) == 0) {
798         struct sockaddr_in *sin = (struct sockaddr_in *) &ifr.ifr_addr;
799         ip = sin->sin_addr;
800     } else {
801         VLOG_DBG_RL(&rl, "%s: ioctl(SIOCGIFADDR) failed: %s",
802                     netdev_name, strerror(errno));
803     }
804     if (in4) {
805         *in4 = ip;
806     }
807     return ip.s_addr != INADDR_ANY;
808 }
809
810 bool
811 netdev_get_in4(const struct netdev *netdev, struct in_addr *in4)
812 {
813     return netdev_nodev_get_in4(netdev->name, in4);
814 }
815
816 static void
817 make_in4_sockaddr(struct sockaddr *sa, struct in_addr addr)
818 {
819     struct sockaddr_in sin;
820     memset(&sin, 0, sizeof sin);
821     sin.sin_family = AF_INET;
822     sin.sin_addr = addr;
823     sin.sin_port = 0;
824
825     memset(sa, 0, sizeof *sa);
826     memcpy(sa, &sin, sizeof sin);
827 }
828
829 static int
830 do_set_addr(struct netdev *netdev, int sock,
831             int ioctl_nr, const char *ioctl_name, struct in_addr addr)
832 {
833     struct ifreq ifr;
834     int error;
835
836     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
837     make_in4_sockaddr(&ifr.ifr_addr, addr);
838     COVERAGE_INC(netdev_set_in4);
839     error = ioctl(sock, ioctl_nr, &ifr) < 0 ? errno : 0;
840     if (error) {
841         VLOG_WARN("ioctl(%s): %s", ioctl_name, strerror(error));
842     }
843     return error;
844 }
845
846 /* Assigns 'addr' as 'netdev''s IPv4 address and 'mask' as its netmask.  If
847  * 'addr' is INADDR_ANY, 'netdev''s IPv4 address is cleared.  Returns a
848  * positive errno value. */
849 int
850 netdev_set_in4(struct netdev *netdev, struct in_addr addr, struct in_addr mask)
851 {
852     int error;
853
854     error = do_set_addr(netdev, af_inet_sock,
855                         SIOCSIFADDR, "SIOCSIFADDR", addr);
856     if (!error && addr.s_addr != INADDR_ANY) {
857         error = do_set_addr(netdev, af_inet_sock,
858                             SIOCSIFNETMASK, "SIOCSIFNETMASK", mask);
859     }
860     return error;
861 }
862
863 /* Adds 'router' as a default IP gateway. */
864 int
865 netdev_add_router(struct in_addr router)
866 {
867     struct in_addr any = { INADDR_ANY };
868     struct rtentry rt;
869     int error;
870
871     memset(&rt, 0, sizeof rt);
872     make_in4_sockaddr(&rt.rt_dst, any);
873     make_in4_sockaddr(&rt.rt_gateway, router);
874     make_in4_sockaddr(&rt.rt_genmask, any);
875     rt.rt_flags = RTF_UP | RTF_GATEWAY;
876     COVERAGE_INC(netdev_add_router);
877     error = ioctl(af_inet_sock, SIOCADDRT, &rt) < 0 ? errno : 0;
878     if (error) {
879         VLOG_WARN("ioctl(SIOCADDRT): %s", strerror(error));
880     }
881     return error;
882 }
883
884 /* If 'netdev' has an assigned IPv6 address, sets '*in6' to that address (if
885  * 'in6' is non-null) and returns true.  Otherwise, returns false. */
886 bool
887 netdev_get_in6(const struct netdev *netdev, struct in6_addr *in6)
888 {
889     if (in6) {
890         *in6 = netdev->in6;
891     }
892     return memcmp(&netdev->in6, &in6addr_any, sizeof netdev->in6) != 0;
893 }
894
895 /* Obtains the current flags for 'netdev' and stores them into '*flagsp'.
896  * Returns 0 if successful, otherwise a positive errno value.  On failure,
897  * stores 0 into '*flagsp'. */
898 int
899 netdev_get_flags(const struct netdev *netdev, enum netdev_flags *flagsp)
900 {
901     return netdev_nodev_get_flags(netdev->name, flagsp);
902 }
903
904 static int
905 nd_to_iff_flags(enum netdev_flags nd)
906 {
907     int iff = 0;
908     if (nd & NETDEV_UP) {
909         iff |= IFF_UP;
910     }
911     if (nd & NETDEV_PROMISC) {
912         iff |= IFF_PROMISC;
913     }
914     return iff;
915 }
916
917 /* On 'netdev', turns off the flags in 'off' and then turns on the flags in
918  * 'on'.  If 'permanent' is true, the changes will persist; otherwise, they
919  * will be reverted when 'netdev' is closed or the program exits.  Returns 0 if
920  * successful, otherwise a positive errno value. */
921 static int
922 do_update_flags(struct netdev *netdev, enum netdev_flags off,
923                 enum netdev_flags on, bool permanent)
924 {
925     int old_flags, new_flags;
926     int error;
927
928     error = get_flags(netdev->name, &old_flags);
929     if (error) {
930         return error;
931     }
932
933     new_flags = (old_flags & ~nd_to_iff_flags(off)) | nd_to_iff_flags(on);
934     if (!permanent) {
935         netdev->changed_flags |= new_flags ^ old_flags; 
936     }
937     if (new_flags != old_flags) {
938         error = set_flags(netdev->name, new_flags);
939     }
940     return error;
941 }
942
943 /* Sets the flags for 'netdev' to 'flags'.
944  * If 'permanent' is true, the changes will persist; otherwise, they
945  * will be reverted when 'netdev' is closed or the program exits.
946  * Returns 0 if successful, otherwise a positive errno value. */
947 int
948 netdev_set_flags(struct netdev *netdev, enum netdev_flags flags,
949                  bool permanent)
950 {
951     return do_update_flags(netdev, -1, flags, permanent);
952 }
953
954 /* Turns on the specified 'flags' on 'netdev'.
955  * If 'permanent' is true, the changes will persist; otherwise, they
956  * will be reverted when 'netdev' is closed or the program exits.
957  * Returns 0 if successful, otherwise a positive errno value. */
958 int
959 netdev_turn_flags_on(struct netdev *netdev, enum netdev_flags flags,
960                      bool permanent)
961 {
962     return do_update_flags(netdev, 0, flags, permanent);
963 }
964
965 /* Turns off the specified 'flags' on 'netdev'.
966  * If 'permanent' is true, the changes will persist; otherwise, they
967  * will be reverted when 'netdev' is closed or the program exits.
968  * Returns 0 if successful, otherwise a positive errno value. */
969 int
970 netdev_turn_flags_off(struct netdev *netdev, enum netdev_flags flags,
971                       bool permanent)
972 {
973     return do_update_flags(netdev, flags, 0, permanent);
974 }
975
976 /* Looks up the ARP table entry for 'ip' on 'netdev'.  If one exists and can be
977  * successfully retrieved, it stores the corresponding MAC address in 'mac' and
978  * returns 0.  Otherwise, it returns a positive errno value; in particular,
979  * ENXIO indicates that there is not ARP table entry for 'ip' on 'netdev'. */
980 int
981 netdev_nodev_arp_lookup(const char *netdev_name, uint32_t ip, 
982                         uint8_t mac[ETH_ADDR_LEN]) 
983 {
984     struct arpreq r;
985     struct sockaddr_in *pa;
986     int retval;
987
988     init_netdev();
989
990     memset(&r, 0, sizeof r);
991     pa = (struct sockaddr_in *) &r.arp_pa;
992     pa->sin_family = AF_INET;
993     pa->sin_addr.s_addr = ip;
994     pa->sin_port = 0;
995     r.arp_ha.sa_family = ARPHRD_ETHER;
996     r.arp_flags = 0;
997     strncpy(r.arp_dev, netdev_name, sizeof r.arp_dev);
998     COVERAGE_INC(netdev_arp_lookup);
999     retval = ioctl(af_inet_sock, SIOCGARP, &r) < 0 ? errno : 0;
1000     if (!retval) {
1001         memcpy(mac, r.arp_ha.sa_data, ETH_ADDR_LEN);
1002     } else if (retval != ENXIO) {
1003         VLOG_WARN_RL(&rl, "%s: could not look up ARP entry for "IP_FMT": %s",
1004                      netdev_name, IP_ARGS(&ip), strerror(retval));
1005     }
1006     return retval;
1007 }
1008
1009 int
1010 netdev_arp_lookup(const struct netdev *netdev, uint32_t ip, 
1011                   uint8_t mac[ETH_ADDR_LEN]) 
1012 {
1013     return netdev_nodev_arp_lookup(netdev->name, ip, mac);
1014 }
1015
1016 static int
1017 get_stats_via_netlink(int ifindex, struct netdev_stats *stats)
1018 {
1019     struct ofpbuf request;
1020     struct ofpbuf *reply;
1021     struct ifinfomsg *ifi;
1022     const struct rtnl_link_stats *rtnl_stats;
1023     struct nlattr *attrs[ARRAY_SIZE(rtnlgrp_link_policy)];
1024     int error;
1025
1026     ofpbuf_init(&request, 0);
1027     nl_msg_put_nlmsghdr(&request, rtnl_sock, sizeof *ifi,
1028                         RTM_GETLINK, NLM_F_REQUEST);
1029     ifi = ofpbuf_put_zeros(&request, sizeof *ifi);
1030     ifi->ifi_family = PF_UNSPEC;
1031     ifi->ifi_index = ifindex;
1032     error = nl_sock_transact(rtnl_sock, &request, &reply);
1033     ofpbuf_uninit(&request);
1034     if (error) {
1035         return error;
1036     }
1037
1038     if (!nl_policy_parse(reply, NLMSG_HDRLEN + sizeof(struct ifinfomsg),
1039                          rtnlgrp_link_policy,
1040                          attrs, ARRAY_SIZE(rtnlgrp_link_policy))) {
1041         ofpbuf_delete(reply);
1042         return EPROTO;
1043     }
1044
1045     if (!attrs[IFLA_STATS]) {
1046         VLOG_WARN_RL(&rl, "RTM_GETLINK reply lacks stats");
1047         return EPROTO;
1048     }
1049
1050     rtnl_stats = nl_attr_get(attrs[IFLA_STATS]);
1051     stats->rx_packets = rtnl_stats->rx_packets;
1052     stats->tx_packets = rtnl_stats->tx_packets;
1053     stats->rx_bytes = rtnl_stats->rx_bytes;
1054     stats->tx_bytes = rtnl_stats->tx_bytes;
1055     stats->rx_errors = rtnl_stats->rx_errors;
1056     stats->tx_errors = rtnl_stats->tx_errors;
1057     stats->rx_dropped = rtnl_stats->rx_dropped;
1058     stats->tx_dropped = rtnl_stats->tx_dropped;
1059     stats->multicast = rtnl_stats->multicast;
1060     stats->collisions = rtnl_stats->collisions;
1061     stats->rx_length_errors = rtnl_stats->rx_length_errors;
1062     stats->rx_over_errors = rtnl_stats->rx_over_errors;
1063     stats->rx_crc_errors = rtnl_stats->rx_crc_errors;
1064     stats->rx_frame_errors = rtnl_stats->rx_frame_errors;
1065     stats->rx_fifo_errors = rtnl_stats->rx_fifo_errors;
1066     stats->rx_missed_errors = rtnl_stats->rx_missed_errors;
1067     stats->tx_aborted_errors = rtnl_stats->tx_aborted_errors;
1068     stats->tx_carrier_errors = rtnl_stats->tx_carrier_errors;
1069     stats->tx_fifo_errors = rtnl_stats->tx_fifo_errors;
1070     stats->tx_heartbeat_errors = rtnl_stats->tx_heartbeat_errors;
1071     stats->tx_window_errors = rtnl_stats->tx_window_errors;
1072
1073     return 0;
1074 }
1075
1076 static int
1077 get_stats_via_proc(const char *netdev_name, struct netdev_stats *stats)
1078 {
1079     static const char fn[] = "/proc/net/dev";
1080     char line[1024];
1081     FILE *stream;
1082     int ln;
1083
1084     stream = fopen(fn, "r");
1085     if (!stream) {
1086         VLOG_WARN_RL(&rl, "%s: open failed: %s", fn, strerror(errno));
1087         return errno;
1088     }
1089
1090     ln = 0;
1091     while (fgets(line, sizeof line, stream)) {
1092         if (++ln >= 3) {
1093             char devname[16];
1094 #define X64 "%"SCNu64
1095             if (sscanf(line,
1096                        " %15[^:]:"
1097                        X64 X64 X64 X64 X64 X64 X64 "%*u"
1098                        X64 X64 X64 X64 X64 X64 X64 "%*u",
1099                        devname,
1100                        &stats->rx_bytes,
1101                        &stats->rx_packets,
1102                        &stats->rx_errors,
1103                        &stats->rx_dropped,
1104                        &stats->rx_fifo_errors,
1105                        &stats->rx_frame_errors,
1106                        &stats->multicast,
1107                        &stats->tx_bytes,
1108                        &stats->tx_packets,
1109                        &stats->tx_errors,
1110                        &stats->tx_dropped,
1111                        &stats->tx_fifo_errors,
1112                        &stats->collisions,
1113                        &stats->tx_carrier_errors) != 15) {
1114                 VLOG_WARN_RL(&rl, "%s:%d: parse error", fn, ln);
1115             } else if (!strcmp(devname, netdev_name)) {
1116                 stats->rx_length_errors = UINT64_MAX;
1117                 stats->rx_over_errors = UINT64_MAX;
1118                 stats->rx_crc_errors = UINT64_MAX;
1119                 stats->rx_missed_errors = UINT64_MAX;
1120                 stats->tx_aborted_errors = UINT64_MAX;
1121                 stats->tx_heartbeat_errors = UINT64_MAX;
1122                 stats->tx_window_errors = UINT64_MAX;
1123                 fclose(stream);
1124                 return 0;
1125             }
1126         }
1127     }
1128     VLOG_WARN_RL(&rl, "%s: no stats for %s", fn, netdev_name);
1129     fclose(stream);
1130     return ENODEV;
1131 }
1132
1133 int
1134 netdev_get_carrier(const struct netdev *netdev, bool *carrier)
1135 {
1136     return netdev_nodev_get_carrier(netdev->name, carrier);
1137 }
1138
1139 int
1140 netdev_nodev_get_carrier(const char *netdev_name, bool *carrier)
1141 {
1142     char line[8];
1143     int retval;
1144     int error;
1145     char *fn;
1146     int fd;
1147
1148     *carrier = false;
1149
1150     fn = xasprintf("/sys/class/net/%s/carrier", netdev_name);
1151     fd = open(fn, O_RDONLY);
1152     if (fd < 0) {
1153         error = errno;
1154         VLOG_WARN_RL(&rl, "%s: open failed: %s", fn, strerror(error));
1155         goto exit;
1156     }
1157
1158     retval = read(fd, line, sizeof line);
1159     if (retval < 0) {
1160         error = errno;
1161         if (error == EINVAL) {
1162             /* This is the normal return value when we try to check carrier if
1163              * the network device is not up. */
1164         } else {
1165             VLOG_WARN_RL(&rl, "%s: read failed: %s", fn, strerror(error));
1166         }
1167         goto exit_close;
1168     } else if (retval == 0) {
1169         error = EPROTO;
1170         VLOG_WARN_RL(&rl, "%s: unexpected end of file", fn);
1171         goto exit_close;
1172     }
1173
1174     if (line[0] != '0' && line[0] != '1') {
1175         error = EPROTO;
1176         VLOG_WARN_RL(&rl, "%s: value is %c (expected 0 or 1)", fn, line[0]);
1177         goto exit_close;
1178     }
1179     *carrier = line[0] != '0';
1180     error = 0;
1181
1182 exit_close:
1183     close(fd);
1184 exit:
1185     free(fn);
1186     return error;
1187 }
1188
1189 int
1190 netdev_get_stats(const struct netdev *netdev, struct netdev_stats *stats)
1191 {
1192     int error;
1193
1194     COVERAGE_INC(netdev_get_stats);
1195     if (use_netlink_stats) {
1196         int ifindex;
1197
1198         error = get_ifindex(netdev, &ifindex);
1199         if (!error) {
1200             error = get_stats_via_netlink(ifindex, stats);
1201         }
1202     } else {
1203         error = get_stats_via_proc(netdev->name, stats);
1204     }
1205
1206     if (error) {
1207         memset(stats, 0xff, sizeof *stats);
1208     }
1209     return error;
1210 }
1211
1212 #define POLICE_ADD_CMD "/sbin/tc qdisc add dev %s handle ffff: ingress"
1213 #define POLICE_CONFIG_CMD "/sbin/tc filter add dev %s parent ffff: protocol ip prio 50 u32 match ip src 0.0.0.0/0 police rate %dkbit burst %dk mtu 65535 drop flowid :1"
1214 /* We redirect stderr to /dev/null because we often want to remove all
1215  * traffic control configuration on a port so its in a known state.  If
1216  * this done when there is no such configuration, tc complains, so we just
1217  * always ignore it.
1218  */
1219 #define POLICE_DEL_CMD "/sbin/tc qdisc del dev %s handle ffff: ingress 2>/dev/null"
1220
1221 /* Attempts to set input rate limiting (policing) policy. */
1222 int
1223 netdev_nodev_set_policing(const char *netdev_name, uint32_t kbits_rate,
1224                           uint32_t kbits_burst)
1225 {
1226     char command[1024];
1227
1228     init_netdev();
1229
1230     COVERAGE_INC(netdev_set_policing);
1231     if (kbits_rate) {
1232         if (!kbits_burst) {
1233             /* Default to 10 kilobits if not specified. */
1234             kbits_burst = 10;
1235         }
1236
1237         /* xxx This should be more careful about only adding if it
1238          * xxx actually exists, as opposed to always deleting it. */
1239         snprintf(command, sizeof(command), POLICE_DEL_CMD, netdev_name);
1240         if (system(command) == -1) {
1241             VLOG_WARN_RL(&rl, "%s: problem removing policing", netdev_name);
1242         }
1243
1244         snprintf(command, sizeof(command), POLICE_ADD_CMD, netdev_name);
1245         if (system(command) != 0) {
1246             VLOG_WARN_RL(&rl, "%s: problem adding policing", netdev_name);
1247             return -1;
1248         }
1249
1250         snprintf(command, sizeof(command), POLICE_CONFIG_CMD, netdev_name,
1251                 kbits_rate, kbits_burst);
1252         if (system(command) != 0) {
1253             VLOG_WARN_RL(&rl, "%s: problem configuring policing", 
1254                     netdev_name);
1255             return -1;
1256         }
1257     } else {
1258         snprintf(command, sizeof(command), POLICE_DEL_CMD, netdev_name);
1259         if (system(command) == -1) {
1260             VLOG_WARN_RL(&rl, "%s: problem removing policing", netdev_name);
1261         }
1262     }
1263
1264     return 0;
1265 }
1266
1267 int
1268 netdev_set_policing(struct netdev *netdev, uint32_t kbits_rate,
1269                     uint32_t kbits_burst)
1270 {
1271     return netdev_nodev_set_policing(netdev->name, kbits_rate, kbits_burst);
1272 }
1273
1274 /* Initializes 'svec' with a list of the names of all known network devices. */
1275 void
1276 netdev_enumerate(struct svec *svec)
1277 {
1278     struct if_nameindex *names;
1279
1280     svec_init(svec);
1281     names = if_nameindex();
1282     if (names) {
1283         size_t i;
1284
1285         for (i = 0; names[i].if_name != NULL; i++) {
1286             svec_add(svec, names[i].if_name);
1287         }
1288         if_freenameindex(names);
1289     } else {
1290         VLOG_WARN("could not obtain list of network device names: %s",
1291                   strerror(errno));
1292     }
1293 }
1294
1295 /* Attempts to locate a device based on its IPv4 address.  The caller
1296  * may provide a hint as to the device by setting 'netdev_name' to a
1297  * likely device name.  This string must be malloc'd, since if it is 
1298  * not correct then it will be freed.  If there is no hint, then
1299  * 'netdev_name' must be the NULL pointer.
1300  *
1301  * If the device is found, the return value will be true and 'netdev_name' 
1302  * contains the device's name as a string, which the caller is responsible 
1303  * for freeing.  If the device is not found, the return value is false. */
1304 bool
1305 netdev_find_dev_by_in4(const struct in_addr *in4, char **netdev_name)
1306 {
1307     int i;
1308     struct in_addr dev_in4;
1309     struct svec dev_list;
1310
1311     /* Check the hint first. */
1312     if (*netdev_name && (netdev_nodev_get_in4(*netdev_name, &dev_in4)) 
1313             && (dev_in4.s_addr == in4->s_addr)) {
1314         return true;
1315     }
1316
1317     free(*netdev_name);
1318     *netdev_name = NULL;
1319     netdev_enumerate(&dev_list);
1320
1321     for (i=0; i<dev_list.n; i++) {
1322         if ((netdev_nodev_get_in4(dev_list.names[i], &dev_in4)) 
1323                 && (dev_in4.s_addr == in4->s_addr)) {
1324             *netdev_name = xstrdup(dev_list.names[i]);
1325             svec_destroy(&dev_list);
1326             return true;
1327         }
1328     }
1329
1330     svec_destroy(&dev_list);
1331     return false;
1332 }
1333
1334 /* Obtains the current flags for the network device named 'netdev_name' and
1335  * stores them into '*flagsp'.  Returns 0 if successful, otherwise a positive
1336  * errno value.  On error, stores 0 into '*flagsp'.
1337  *
1338  * If only device flags are needed, this is more efficient than calling
1339  * netdev_open(), netdev_get_flags(), netdev_close(). */
1340 int
1341 netdev_nodev_get_flags(const char *netdev_name, enum netdev_flags *flagsp)
1342 {
1343     int error, flags;
1344
1345     init_netdev();
1346
1347     *flagsp = 0;
1348     error = get_flags(netdev_name, &flags);
1349     if (error) {
1350         return error;
1351     }
1352
1353     if (flags & IFF_UP) {
1354         *flagsp |= NETDEV_UP;
1355     }
1356     if (flags & IFF_PROMISC) {
1357         *flagsp |= NETDEV_PROMISC;
1358     }
1359     return 0;
1360 }
1361
1362 int
1363 netdev_nodev_get_etheraddr(const char *netdev_name, uint8_t mac[6])
1364 {
1365     init_netdev();
1366
1367     return get_etheraddr(netdev_name, mac, NULL);
1368 }
1369
1370 /* If 'netdev_name' is the name of a VLAN network device (e.g. one created with
1371  * vconfig(8)), sets '*vlan_vid' to the VLAN VID associated with that device
1372  * and returns 0.  Otherwise returns a errno value (specifically ENOENT if
1373  * 'netdev_name' is the name of a network device that is not a VLAN device) and
1374  * sets '*vlan_vid' to -1. */
1375 int
1376 netdev_get_vlan_vid(const char *netdev_name, int *vlan_vid)
1377 {
1378     struct ds line = DS_EMPTY_INITIALIZER;
1379     FILE *stream = NULL;
1380     int error;
1381     char *fn;
1382
1383     COVERAGE_INC(netdev_get_vlan_vid);
1384     fn = xasprintf("/proc/net/vlan/%s", netdev_name);
1385     stream = fopen(fn, "r");
1386     if (!stream) {
1387         error = errno;
1388         goto done;
1389     }
1390
1391     if (ds_get_line(&line, stream)) {
1392         if (ferror(stream)) {
1393             error = errno;
1394             VLOG_ERR_RL(&rl, "error reading \"%s\": %s", fn, strerror(errno));
1395         } else {
1396             error = EPROTO;
1397             VLOG_ERR_RL(&rl, "unexpected end of file reading \"%s\"", fn);
1398         }
1399         goto done;
1400     }
1401
1402     if (!sscanf(ds_cstr(&line), "%*s VID: %d", vlan_vid)) {
1403         error = EPROTO;
1404         VLOG_ERR_RL(&rl, "parse error reading \"%s\" line 1: \"%s\"",
1405                     fn, ds_cstr(&line));
1406         goto done;
1407     }
1408
1409     error = 0;
1410
1411 done:
1412     free(fn);
1413     if (stream) {
1414         fclose(stream);
1415     }
1416     ds_destroy(&line);
1417     if (error) {
1418         *vlan_vid = -1;
1419     }
1420     return error;
1421 }
1422 \f
1423 static void restore_all_flags(void *aux);
1424
1425 /* Set up a signal hook to restore network device flags on program
1426  * termination.  */
1427 static void
1428 init_netdev(void)
1429 {
1430     static bool inited;
1431     if (!inited) {
1432         int ifindex;
1433         int error;
1434
1435         inited = true;
1436
1437         fatal_signal_add_hook(restore_all_flags, NULL, true);
1438
1439         af_inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
1440         if (af_inet_sock < 0) {
1441             ovs_fatal(errno, "socket(AF_INET)");
1442         }
1443
1444         error = nl_sock_create(NETLINK_ROUTE, 0, 0, 0, &rtnl_sock);
1445         if (error) {
1446             ovs_fatal(error, "socket(AF_NETLINK, NETLINK_ROUTE)");
1447         }
1448
1449         /* Decide on the netdev_get_stats() implementation to use.  Netlink is
1450          * preferable, so if that works, we'll use it. */
1451         ifindex = do_get_ifindex("lo");
1452         if (ifindex < 0) {
1453             VLOG_WARN("failed to get ifindex for lo, "
1454                       "obtaining netdev stats from proc");
1455             use_netlink_stats = false;
1456         } else {
1457             struct netdev_stats stats;
1458             error = get_stats_via_netlink(ifindex, &stats);
1459             if (!error) {
1460                 VLOG_DBG("obtaining netdev stats via rtnetlink");
1461                 use_netlink_stats = true;
1462             } else {
1463                 VLOG_INFO("RTM_GETLINK failed (%s), obtaining netdev stats "
1464                           "via proc (you are probably running a pre-2.6.19 "
1465                           "kernel)", strerror(error));
1466                 use_netlink_stats = false;
1467             }
1468         }
1469     }
1470 }
1471
1472 /* Restore the network device flags on 'netdev' to those that were active
1473  * before we changed them.  Returns 0 if successful, otherwise a positive
1474  * errno value.
1475  *
1476  * To avoid reentry, the caller must ensure that fatal signals are blocked. */
1477 static int
1478 restore_flags(struct netdev *netdev)
1479 {
1480     struct ifreq ifr;
1481     int restore_flags;
1482
1483     /* Get current flags. */
1484     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
1485     COVERAGE_INC(netdev_get_flags);
1486     if (ioctl(netdev->netdev_fd, SIOCGIFFLAGS, &ifr) < 0) {
1487         return errno;
1488     }
1489
1490     /* Restore flags that we might have changed, if necessary. */
1491     restore_flags = netdev->changed_flags & (IFF_PROMISC | IFF_UP);
1492     if ((ifr.ifr_flags ^ netdev->save_flags) & restore_flags) {
1493         ifr.ifr_flags &= ~restore_flags;
1494         ifr.ifr_flags |= netdev->save_flags & restore_flags;
1495         COVERAGE_INC(netdev_set_flags);
1496         if (ioctl(netdev->netdev_fd, SIOCSIFFLAGS, &ifr) < 0) {
1497             return errno;
1498         }
1499     }
1500
1501     return 0;
1502 }
1503
1504 /* Retores all the flags on all network devices that we modified.  Called from
1505  * a signal handler, so it does not attempt to report error conditions. */
1506 static void
1507 restore_all_flags(void *aux UNUSED)
1508 {
1509     struct netdev *netdev;
1510     LIST_FOR_EACH (netdev, struct netdev, node, &netdev_list) {
1511         restore_flags(netdev);
1512     }
1513 }
1514
1515 static int
1516 get_flags(const char *netdev_name, int *flags)
1517 {
1518     struct ifreq ifr;
1519     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
1520     COVERAGE_INC(netdev_get_flags);
1521     if (ioctl(af_inet_sock, SIOCGIFFLAGS, &ifr) < 0) {
1522         VLOG_ERR("ioctl(SIOCGIFFLAGS) on %s device failed: %s",
1523                  netdev_name, strerror(errno));
1524         return errno;
1525     }
1526     *flags = ifr.ifr_flags;
1527     return 0;
1528 }
1529
1530 static int
1531 set_flags(const char *netdev_name, int flags)
1532 {
1533     struct ifreq ifr;
1534     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
1535     ifr.ifr_flags = flags;
1536     COVERAGE_INC(netdev_set_flags);
1537     if (ioctl(af_inet_sock, SIOCSIFFLAGS, &ifr) < 0) {
1538         VLOG_ERR("ioctl(SIOCSIFFLAGS) on %s device failed: %s",
1539                  netdev_name, strerror(errno));
1540         return errno;
1541     }
1542     return 0;
1543 }
1544
1545 static int
1546 do_get_ifindex(const char *netdev_name)
1547 {
1548     struct ifreq ifr;
1549
1550     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
1551     COVERAGE_INC(netdev_get_ifindex);
1552     if (ioctl(af_inet_sock, SIOCGIFINDEX, &ifr) < 0) {
1553         VLOG_WARN_RL(&rl, "ioctl(SIOCGIFINDEX) on %s device failed: %s",
1554                      netdev_name, strerror(errno));
1555         return -errno;
1556     }
1557     return ifr.ifr_ifindex;
1558 }
1559
1560 static int
1561 get_ifindex(const struct netdev *netdev, int *ifindexp)
1562 {
1563     *ifindexp = 0;
1564     if (netdev->ifindex < 0) {
1565         int ifindex = do_get_ifindex(netdev->name);
1566         if (ifindex < 0) {
1567             return -ifindex;
1568         }
1569         ((struct netdev *) netdev)->ifindex = ifindex;
1570     }
1571     *ifindexp = netdev->ifindex;
1572     return 0;
1573 }
1574
1575 static int
1576 get_etheraddr(const char *netdev_name, uint8_t ea[ETH_ADDR_LEN],
1577               int *hwaddr_familyp)
1578 {
1579     struct ifreq ifr;
1580
1581     memset(&ifr, 0, sizeof ifr);
1582     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
1583     COVERAGE_INC(netdev_get_hwaddr);
1584     if (ioctl(af_inet_sock, SIOCGIFHWADDR, &ifr) < 0) {
1585         VLOG_ERR("ioctl(SIOCGIFHWADDR) on %s device failed: %s",
1586                  netdev_name, strerror(errno));
1587         return errno;
1588     }
1589     if (hwaddr_familyp) {
1590         int hwaddr_family = ifr.ifr_hwaddr.sa_family;
1591         *hwaddr_familyp = hwaddr_family;
1592         if (hwaddr_family != AF_UNSPEC && hwaddr_family != ARPHRD_ETHER) {
1593             VLOG_WARN("%s device has unknown hardware address family %d",
1594                       netdev_name, hwaddr_family);
1595         }
1596     }
1597     memcpy(ea, ifr.ifr_hwaddr.sa_data, ETH_ADDR_LEN);
1598     return 0;
1599 }
1600
1601 static int
1602 set_etheraddr(const char *netdev_name, int hwaddr_family,
1603               const uint8_t mac[ETH_ADDR_LEN])
1604 {
1605     struct ifreq ifr;
1606
1607     memset(&ifr, 0, sizeof ifr);
1608     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
1609     ifr.ifr_hwaddr.sa_family = hwaddr_family;
1610     memcpy(ifr.ifr_hwaddr.sa_data, mac, ETH_ADDR_LEN);
1611     COVERAGE_INC(netdev_set_hwaddr);
1612     if (ioctl(af_inet_sock, SIOCSIFHWADDR, &ifr) < 0) {
1613         VLOG_ERR("ioctl(SIOCSIFHWADDR) on %s device failed: %s",
1614                  netdev_name, strerror(errno));
1615         return errno;
1616     }
1617     return 0;
1618 }