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