netdev: Get rid of netdev_open_tap().
[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 /* Pads 'buffer' out with zero-bytes to the minimum valid length of an
532  * Ethernet packet, if necessary.  */
533 static void
534 pad_to_minimum_length(struct ofpbuf *buffer)
535 {
536     if (buffer->size < ETH_TOTAL_MIN) {
537         ofpbuf_put_zeros(buffer, ETH_TOTAL_MIN - buffer->size);
538     }
539 }
540
541 /* Attempts to receive a packet from 'netdev' into 'buffer', which the caller
542  * must have initialized with sufficient room for the packet.  The space
543  * required to receive any packet is ETH_HEADER_LEN bytes, plus VLAN_HEADER_LEN
544  * bytes, plus the device's MTU (which may be retrieved via netdev_get_mtu()).
545  * (Some devices do not allow for a VLAN header, in which case VLAN_HEADER_LEN
546  * need not be included.)
547  *
548  * If a packet is successfully retrieved, returns 0.  In this case 'buffer' is
549  * guaranteed to contain at least ETH_TOTAL_MIN bytes.  Otherwise, returns a
550  * positive errno value.  Returns EAGAIN immediately if no packet is ready to
551  * be returned.
552  */
553 int
554 netdev_recv(struct netdev *netdev, struct ofpbuf *buffer)
555 {
556     ssize_t n_bytes;
557
558     assert(buffer->size == 0);
559     assert(ofpbuf_tailroom(buffer) >= ETH_TOTAL_MIN);
560     do {
561         n_bytes = read(netdev->tap_fd,
562                        ofpbuf_tail(buffer), ofpbuf_tailroom(buffer));
563     } while (n_bytes < 0 && errno == EINTR);
564     if (n_bytes < 0) {
565         if (errno != EAGAIN) {
566             VLOG_WARN_RL(&rl, "error receiving Ethernet packet on %s: %s",
567                          strerror(errno), netdev->name);
568         }
569         return errno;
570     } else {
571         COVERAGE_INC(netdev_received);
572         buffer->size += n_bytes;
573
574         /* When the kernel internally sends out an Ethernet frame on an
575          * interface, it gives us a copy *before* padding the frame to the
576          * minimum length.  Thus, when it sends out something like an ARP
577          * request, we see a too-short frame.  So pad it out to the minimum
578          * length. */
579         pad_to_minimum_length(buffer);
580         return 0;
581     }
582 }
583
584 /* Registers with the poll loop to wake up from the next call to poll_block()
585  * when a packet is ready to be received with netdev_recv() on 'netdev'. */
586 void
587 netdev_recv_wait(struct netdev *netdev)
588 {
589     poll_fd_wait(netdev->tap_fd, POLLIN);
590 }
591
592 /* Discards all packets waiting to be received from 'netdev'. */
593 int
594 netdev_drain(struct netdev *netdev)
595 {
596     if (netdev->tap_fd != netdev->netdev_fd) {
597         drain_fd(netdev->tap_fd, netdev->txqlen);
598         return 0;
599     } else {
600         return drain_rcvbuf(netdev->netdev_fd);
601     }
602 }
603
604 /* Sends 'buffer' on 'netdev'.  Returns 0 if successful, otherwise a positive
605  * errno value.  Returns EAGAIN without blocking if the packet cannot be queued
606  * immediately.  Returns EMSGSIZE if a partial packet was transmitted or if
607  * the packet is too big or too small to transmit on the device.
608  *
609  * The caller retains ownership of 'buffer' in all cases.
610  *
611  * The kernel maintains a packet transmission queue, so the caller is not
612  * expected to do additional queuing of packets. */
613 int
614 netdev_send(struct netdev *netdev, const struct ofpbuf *buffer)
615 {
616     ssize_t n_bytes;
617
618     do {
619         n_bytes = write(netdev->tap_fd, buffer->data, buffer->size);
620     } while (n_bytes < 0 && errno == EINTR);
621
622     if (n_bytes < 0) {
623         /* The Linux AF_PACKET implementation never blocks waiting for room
624          * for packets, instead returning ENOBUFS.  Translate this into EAGAIN
625          * for the caller. */
626         if (errno == ENOBUFS) {
627             return EAGAIN;
628         } else if (errno != EAGAIN) {
629             VLOG_WARN_RL(&rl, "error sending Ethernet packet on %s: %s",
630                          netdev->name, strerror(errno));
631         }
632         return errno;
633     } else if (n_bytes != buffer->size) {
634         VLOG_WARN_RL(&rl,
635                      "send partial Ethernet packet (%d bytes of %zu) on %s",
636                      (int) n_bytes, buffer->size, netdev->name);
637         return EMSGSIZE;
638     } else {
639         COVERAGE_INC(netdev_sent);
640         return 0;
641     }
642 }
643
644 /* Registers with the poll loop to wake up from the next call to poll_block()
645  * when the packet transmission queue has sufficient room to transmit a packet
646  * with netdev_send().
647  *
648  * The kernel maintains a packet transmission queue, so the client is not
649  * expected to do additional queuing of packets.  Thus, this function is
650  * unlikely to ever be used.  It is included for completeness. */
651 void
652 netdev_send_wait(struct netdev *netdev)
653 {
654     if (netdev->tap_fd == netdev->netdev_fd) {
655         poll_fd_wait(netdev->tap_fd, POLLOUT);
656     } else {
657         /* TAP device always accepts packets.*/
658         poll_immediate_wake();
659     }
660 }
661
662 /* Attempts to set 'netdev''s MAC address to 'mac'.  Returns 0 if successful,
663  * otherwise a positive errno value. */
664 int
665 netdev_set_etheraddr(struct netdev *netdev, const uint8_t mac[ETH_ADDR_LEN])
666 {
667     int error = set_etheraddr(netdev->name, netdev->hwaddr_family, mac);
668     if (!error) {
669         memcpy(netdev->etheraddr, mac, ETH_ADDR_LEN);
670     }
671     return error;
672 }
673
674 int
675 netdev_nodev_set_etheraddr(const char *name, const uint8_t mac[ETH_ADDR_LEN])
676 {
677     init_netdev();
678     return set_etheraddr(name, ARPHRD_ETHER, mac);
679 }
680
681 /* Retrieves 'netdev''s MAC address.  If successful, returns 0 and copies the
682  * the MAC address into 'mac'.  On failure, returns a positive errno value and
683  * clears 'mac' to all-zeros. */
684 int
685 netdev_get_etheraddr(const struct netdev *netdev, uint8_t mac[ETH_ADDR_LEN])
686 {
687     memcpy(mac, netdev->etheraddr, ETH_ADDR_LEN);
688     return 0;
689 }
690
691 /* Returns the name of the network device that 'netdev' represents,
692  * e.g. "eth0".  The caller must not modify or free the returned string. */
693 const char *
694 netdev_get_name(const struct netdev *netdev)
695 {
696     return netdev->name;
697 }
698
699 /* Retrieves the MTU of 'netdev'.  The MTU is the maximum size of transmitted
700  * (and received) packets, in bytes, not including the hardware header; thus,
701  * this is typically 1500 bytes for Ethernet devices.
702  *
703  * If successful, returns 0 and stores the MTU size in '*mtup'.  On failure,
704  * returns a positive errno value and stores ETH_PAYLOAD_MAX (1500) in
705  * '*mtup'. */
706 int
707 netdev_get_mtu(const struct netdev *netdev, int *mtup)
708 {
709     *mtup = netdev->mtu;
710     return 0;
711 }
712
713 /* Stores the features supported by 'netdev' into each of '*current',
714  * '*advertised', '*supported', and '*peer' that are non-null.  Each value is a
715  * bitmap of "enum ofp_port_features" bits, in host byte order.  Returns 0 if
716  * successful, otherwise a positive errno value.  On failure, all of the
717  * passed-in values are set to 0. */
718 int
719 netdev_get_features(struct netdev *netdev,
720                     uint32_t *current, uint32_t *advertised,
721                     uint32_t *supported, uint32_t *peer)
722 {
723     uint32_t dummy[4];
724     return do_get_features(netdev,
725                            current ? current : &dummy[0],
726                            advertised ? advertised : &dummy[1],
727                            supported ? supported : &dummy[2],
728                            peer ? peer : &dummy[3]);
729 }
730
731 /* Set the features advertised by 'netdev' to 'advertise'. */
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 0.  Otherwise, returns a positive errno value
786  * and sets '*in4' to INADDR_ANY (0). */
787 int
788 netdev_nodev_get_in4(const char *netdev_name, struct in_addr *in4)
789 {
790     struct ifreq ifr;
791     struct in_addr ip = { INADDR_ANY };
792     int error;
793
794     init_netdev();
795
796     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
797     ifr.ifr_addr.sa_family = AF_INET;
798     COVERAGE_INC(netdev_get_in4);
799     if (ioctl(af_inet_sock, SIOCGIFADDR, &ifr) == 0) {
800         struct sockaddr_in *sin = (struct sockaddr_in *) &ifr.ifr_addr;
801         ip = sin->sin_addr;
802         error = ip.s_addr != INADDR_ANY ? 0 : EADDRNOTAVAIL;
803     } else {
804         VLOG_DBG_RL(&rl, "%s: ioctl(SIOCGIFADDR) failed: %s",
805                     netdev_name, strerror(errno));
806         error = errno;
807     }
808     if (in4) {
809         *in4 = ip;
810     }
811     return error;
812 }
813
814 int
815 netdev_get_in4(const struct netdev *netdev, struct in_addr *in4)
816 {
817     return netdev_nodev_get_in4(netdev->name, in4);
818 }
819
820 static void
821 make_in4_sockaddr(struct sockaddr *sa, struct in_addr addr)
822 {
823     struct sockaddr_in sin;
824     memset(&sin, 0, sizeof sin);
825     sin.sin_family = AF_INET;
826     sin.sin_addr = addr;
827     sin.sin_port = 0;
828
829     memset(sa, 0, sizeof *sa);
830     memcpy(sa, &sin, sizeof sin);
831 }
832
833 static int
834 do_set_addr(struct netdev *netdev, int sock,
835             int ioctl_nr, const char *ioctl_name, struct in_addr addr)
836 {
837     struct ifreq ifr;
838     int error;
839
840     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
841     make_in4_sockaddr(&ifr.ifr_addr, addr);
842     COVERAGE_INC(netdev_set_in4);
843     error = ioctl(sock, ioctl_nr, &ifr) < 0 ? errno : 0;
844     if (error) {
845         VLOG_WARN("ioctl(%s): %s", ioctl_name, strerror(error));
846     }
847     return error;
848 }
849
850 /* Assigns 'addr' as 'netdev''s IPv4 address and 'mask' as its netmask.  If
851  * 'addr' is INADDR_ANY, 'netdev''s IPv4 address is cleared.  Returns a
852  * positive errno value. */
853 int
854 netdev_set_in4(struct netdev *netdev, struct in_addr addr, struct in_addr mask)
855 {
856     int error;
857
858     error = do_set_addr(netdev, af_inet_sock,
859                         SIOCSIFADDR, "SIOCSIFADDR", addr);
860     if (!error && addr.s_addr != INADDR_ANY) {
861         error = do_set_addr(netdev, af_inet_sock,
862                             SIOCSIFNETMASK, "SIOCSIFNETMASK", mask);
863     }
864     return error;
865 }
866
867 /* Adds 'router' as a default IP gateway. */
868 int
869 netdev_add_router(struct in_addr router)
870 {
871     struct in_addr any = { INADDR_ANY };
872     struct rtentry rt;
873     int error;
874
875     memset(&rt, 0, sizeof rt);
876     make_in4_sockaddr(&rt.rt_dst, any);
877     make_in4_sockaddr(&rt.rt_gateway, router);
878     make_in4_sockaddr(&rt.rt_genmask, any);
879     rt.rt_flags = RTF_UP | RTF_GATEWAY;
880     COVERAGE_INC(netdev_add_router);
881     error = ioctl(af_inet_sock, SIOCADDRT, &rt) < 0 ? errno : 0;
882     if (error) {
883         VLOG_WARN("ioctl(SIOCADDRT): %s", strerror(error));
884     }
885     return error;
886 }
887
888 /* If 'netdev' has an assigned IPv6 address, sets '*in6' to that address (if
889  * 'in6' is non-null) and returns true.  Otherwise, returns false. */
890 bool
891 netdev_get_in6(const struct netdev *netdev, struct in6_addr *in6)
892 {
893     if (in6) {
894         *in6 = netdev->in6;
895     }
896     return memcmp(&netdev->in6, &in6addr_any, sizeof netdev->in6) != 0;
897 }
898
899 /* Obtains the current flags for 'netdev' and stores them into '*flagsp'.
900  * Returns 0 if successful, otherwise a positive errno value.  On failure,
901  * stores 0 into '*flagsp'. */
902 int
903 netdev_get_flags(const struct netdev *netdev, enum netdev_flags *flagsp)
904 {
905     return netdev_nodev_get_flags(netdev->name, flagsp);
906 }
907
908 static int
909 nd_to_iff_flags(enum netdev_flags nd)
910 {
911     int iff = 0;
912     if (nd & NETDEV_UP) {
913         iff |= IFF_UP;
914     }
915     if (nd & NETDEV_PROMISC) {
916         iff |= IFF_PROMISC;
917     }
918     return iff;
919 }
920
921 /* On 'netdev', turns off the flags in 'off' and then turns on the flags in
922  * 'on'.  If 'permanent' is true, the changes will persist; otherwise, they
923  * will be reverted when 'netdev' is closed or the program exits.  Returns 0 if
924  * successful, otherwise a positive errno value. */
925 static int
926 do_update_flags(struct netdev *netdev, enum netdev_flags off,
927                 enum netdev_flags on, bool permanent)
928 {
929     int old_flags, new_flags;
930     int error;
931
932     error = get_flags(netdev->name, &old_flags);
933     if (error) {
934         return error;
935     }
936
937     new_flags = (old_flags & ~nd_to_iff_flags(off)) | nd_to_iff_flags(on);
938     if (!permanent) {
939         netdev->changed_flags |= new_flags ^ old_flags; 
940     }
941     if (new_flags != old_flags) {
942         error = set_flags(netdev->name, new_flags);
943     }
944     return error;
945 }
946
947 /* Sets the flags for 'netdev' to 'flags'.
948  * If 'permanent' is true, the changes will persist; otherwise, they
949  * will be reverted when 'netdev' is closed or the program exits.
950  * Returns 0 if successful, otherwise a positive errno value. */
951 int
952 netdev_set_flags(struct netdev *netdev, enum netdev_flags flags,
953                  bool permanent)
954 {
955     return do_update_flags(netdev, -1, flags, permanent);
956 }
957
958 /* Turns on the specified 'flags' on 'netdev'.
959  * If 'permanent' is true, the changes will persist; otherwise, they
960  * will be reverted when 'netdev' is closed or the program exits.
961  * Returns 0 if successful, otherwise a positive errno value. */
962 int
963 netdev_turn_flags_on(struct netdev *netdev, enum netdev_flags flags,
964                      bool permanent)
965 {
966     return do_update_flags(netdev, 0, flags, permanent);
967 }
968
969 /* Turns off the specified 'flags' on 'netdev'.
970  * If 'permanent' is true, the changes will persist; otherwise, they
971  * will be reverted when 'netdev' is closed or the program exits.
972  * Returns 0 if successful, otherwise a positive errno value. */
973 int
974 netdev_turn_flags_off(struct netdev *netdev, enum netdev_flags flags,
975                       bool permanent)
976 {
977     return do_update_flags(netdev, flags, 0, permanent);
978 }
979
980 /* Looks up the ARP table entry for 'ip' on 'netdev'.  If one exists and can be
981  * successfully retrieved, it stores the corresponding MAC address in 'mac' and
982  * returns 0.  Otherwise, it returns a positive errno value; in particular,
983  * ENXIO indicates that there is not ARP table entry for 'ip' on 'netdev'. */
984 int
985 netdev_nodev_arp_lookup(const char *netdev_name, uint32_t ip, 
986                         uint8_t mac[ETH_ADDR_LEN]) 
987 {
988     struct arpreq r;
989     struct sockaddr_in *pa;
990     int retval;
991
992     init_netdev();
993
994     memset(&r, 0, sizeof r);
995     pa = (struct sockaddr_in *) &r.arp_pa;
996     pa->sin_family = AF_INET;
997     pa->sin_addr.s_addr = ip;
998     pa->sin_port = 0;
999     r.arp_ha.sa_family = ARPHRD_ETHER;
1000     r.arp_flags = 0;
1001     strncpy(r.arp_dev, netdev_name, sizeof r.arp_dev);
1002     COVERAGE_INC(netdev_arp_lookup);
1003     retval = ioctl(af_inet_sock, SIOCGARP, &r) < 0 ? errno : 0;
1004     if (!retval) {
1005         memcpy(mac, r.arp_ha.sa_data, ETH_ADDR_LEN);
1006     } else if (retval != ENXIO) {
1007         VLOG_WARN_RL(&rl, "%s: could not look up ARP entry for "IP_FMT": %s",
1008                      netdev_name, IP_ARGS(&ip), strerror(retval));
1009     }
1010     return retval;
1011 }
1012
1013 int
1014 netdev_arp_lookup(const struct netdev *netdev, uint32_t ip, 
1015                   uint8_t mac[ETH_ADDR_LEN]) 
1016 {
1017     return netdev_nodev_arp_lookup(netdev->name, ip, mac);
1018 }
1019
1020 static int
1021 get_stats_via_netlink(int ifindex, struct netdev_stats *stats)
1022 {
1023     struct ofpbuf request;
1024     struct ofpbuf *reply;
1025     struct ifinfomsg *ifi;
1026     const struct rtnl_link_stats *rtnl_stats;
1027     struct nlattr *attrs[ARRAY_SIZE(rtnlgrp_link_policy)];
1028     int error;
1029
1030     ofpbuf_init(&request, 0);
1031     nl_msg_put_nlmsghdr(&request, rtnl_sock, sizeof *ifi,
1032                         RTM_GETLINK, NLM_F_REQUEST);
1033     ifi = ofpbuf_put_zeros(&request, sizeof *ifi);
1034     ifi->ifi_family = PF_UNSPEC;
1035     ifi->ifi_index = ifindex;
1036     error = nl_sock_transact(rtnl_sock, &request, &reply);
1037     ofpbuf_uninit(&request);
1038     if (error) {
1039         return error;
1040     }
1041
1042     if (!nl_policy_parse(reply, NLMSG_HDRLEN + sizeof(struct ifinfomsg),
1043                          rtnlgrp_link_policy,
1044                          attrs, ARRAY_SIZE(rtnlgrp_link_policy))) {
1045         ofpbuf_delete(reply);
1046         return EPROTO;
1047     }
1048
1049     if (!attrs[IFLA_STATS]) {
1050         VLOG_WARN_RL(&rl, "RTM_GETLINK reply lacks stats");
1051         return EPROTO;
1052     }
1053
1054     rtnl_stats = nl_attr_get(attrs[IFLA_STATS]);
1055     stats->rx_packets = rtnl_stats->rx_packets;
1056     stats->tx_packets = rtnl_stats->tx_packets;
1057     stats->rx_bytes = rtnl_stats->rx_bytes;
1058     stats->tx_bytes = rtnl_stats->tx_bytes;
1059     stats->rx_errors = rtnl_stats->rx_errors;
1060     stats->tx_errors = rtnl_stats->tx_errors;
1061     stats->rx_dropped = rtnl_stats->rx_dropped;
1062     stats->tx_dropped = rtnl_stats->tx_dropped;
1063     stats->multicast = rtnl_stats->multicast;
1064     stats->collisions = rtnl_stats->collisions;
1065     stats->rx_length_errors = rtnl_stats->rx_length_errors;
1066     stats->rx_over_errors = rtnl_stats->rx_over_errors;
1067     stats->rx_crc_errors = rtnl_stats->rx_crc_errors;
1068     stats->rx_frame_errors = rtnl_stats->rx_frame_errors;
1069     stats->rx_fifo_errors = rtnl_stats->rx_fifo_errors;
1070     stats->rx_missed_errors = rtnl_stats->rx_missed_errors;
1071     stats->tx_aborted_errors = rtnl_stats->tx_aborted_errors;
1072     stats->tx_carrier_errors = rtnl_stats->tx_carrier_errors;
1073     stats->tx_fifo_errors = rtnl_stats->tx_fifo_errors;
1074     stats->tx_heartbeat_errors = rtnl_stats->tx_heartbeat_errors;
1075     stats->tx_window_errors = rtnl_stats->tx_window_errors;
1076
1077     return 0;
1078 }
1079
1080 static int
1081 get_stats_via_proc(const char *netdev_name, struct netdev_stats *stats)
1082 {
1083     static const char fn[] = "/proc/net/dev";
1084     char line[1024];
1085     FILE *stream;
1086     int ln;
1087
1088     stream = fopen(fn, "r");
1089     if (!stream) {
1090         VLOG_WARN_RL(&rl, "%s: open failed: %s", fn, strerror(errno));
1091         return errno;
1092     }
1093
1094     ln = 0;
1095     while (fgets(line, sizeof line, stream)) {
1096         if (++ln >= 3) {
1097             char devname[16];
1098 #define X64 "%"SCNu64
1099             if (sscanf(line,
1100                        " %15[^:]:"
1101                        X64 X64 X64 X64 X64 X64 X64 "%*u"
1102                        X64 X64 X64 X64 X64 X64 X64 "%*u",
1103                        devname,
1104                        &stats->rx_bytes,
1105                        &stats->rx_packets,
1106                        &stats->rx_errors,
1107                        &stats->rx_dropped,
1108                        &stats->rx_fifo_errors,
1109                        &stats->rx_frame_errors,
1110                        &stats->multicast,
1111                        &stats->tx_bytes,
1112                        &stats->tx_packets,
1113                        &stats->tx_errors,
1114                        &stats->tx_dropped,
1115                        &stats->tx_fifo_errors,
1116                        &stats->collisions,
1117                        &stats->tx_carrier_errors) != 15) {
1118                 VLOG_WARN_RL(&rl, "%s:%d: parse error", fn, ln);
1119             } else if (!strcmp(devname, netdev_name)) {
1120                 stats->rx_length_errors = UINT64_MAX;
1121                 stats->rx_over_errors = UINT64_MAX;
1122                 stats->rx_crc_errors = UINT64_MAX;
1123                 stats->rx_missed_errors = UINT64_MAX;
1124                 stats->tx_aborted_errors = UINT64_MAX;
1125                 stats->tx_heartbeat_errors = UINT64_MAX;
1126                 stats->tx_window_errors = UINT64_MAX;
1127                 fclose(stream);
1128                 return 0;
1129             }
1130         }
1131     }
1132     VLOG_WARN_RL(&rl, "%s: no stats for %s", fn, netdev_name);
1133     fclose(stream);
1134     return ENODEV;
1135 }
1136
1137 /* Sets 'carrier' to true if carrier is active (link light is on) on 
1138  * 'netdev'. */
1139 int
1140 netdev_get_carrier(const struct netdev *netdev, bool *carrier)
1141 {
1142     return netdev_nodev_get_carrier(netdev->name, carrier);
1143 }
1144
1145 int
1146 netdev_nodev_get_carrier(const char *netdev_name, bool *carrier)
1147 {
1148     char line[8];
1149     int retval;
1150     int error;
1151     char *fn;
1152     int fd;
1153
1154     *carrier = false;
1155
1156     fn = xasprintf("/sys/class/net/%s/carrier", netdev_name);
1157     fd = open(fn, O_RDONLY);
1158     if (fd < 0) {
1159         error = errno;
1160         VLOG_WARN_RL(&rl, "%s: open failed: %s", fn, strerror(error));
1161         goto exit;
1162     }
1163
1164     retval = read(fd, line, sizeof line);
1165     if (retval < 0) {
1166         error = errno;
1167         if (error == EINVAL) {
1168             /* This is the normal return value when we try to check carrier if
1169              * the network device is not up. */
1170         } else {
1171             VLOG_WARN_RL(&rl, "%s: read failed: %s", fn, strerror(error));
1172         }
1173         goto exit_close;
1174     } else if (retval == 0) {
1175         error = EPROTO;
1176         VLOG_WARN_RL(&rl, "%s: unexpected end of file", fn);
1177         goto exit_close;
1178     }
1179
1180     if (line[0] != '0' && line[0] != '1') {
1181         error = EPROTO;
1182         VLOG_WARN_RL(&rl, "%s: value is %c (expected 0 or 1)", fn, line[0]);
1183         goto exit_close;
1184     }
1185     *carrier = line[0] != '0';
1186     error = 0;
1187
1188 exit_close:
1189     close(fd);
1190 exit:
1191     free(fn);
1192     return error;
1193 }
1194
1195 /* Retrieves current device stats for 'netdev'. */
1196 int
1197 netdev_get_stats(const struct netdev *netdev, struct netdev_stats *stats)
1198 {
1199     int error;
1200
1201     COVERAGE_INC(netdev_get_stats);
1202     if (use_netlink_stats) {
1203         int ifindex;
1204
1205         error = get_ifindex(netdev, &ifindex);
1206         if (!error) {
1207             error = get_stats_via_netlink(ifindex, stats);
1208         }
1209     } else {
1210         error = get_stats_via_proc(netdev->name, stats);
1211     }
1212
1213     if (error) {
1214         memset(stats, 0xff, sizeof *stats);
1215     }
1216     return error;
1217 }
1218
1219 #define POLICE_ADD_CMD "/sbin/tc qdisc add dev %s handle ffff: ingress"
1220 #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"
1221 /* We redirect stderr to /dev/null because we often want to remove all
1222  * traffic control configuration on a port so its in a known state.  If
1223  * this done when there is no such configuration, tc complains, so we just
1224  * always ignore it.
1225  */
1226 #define POLICE_DEL_CMD "/sbin/tc qdisc del dev %s handle ffff: ingress 2>/dev/null"
1227
1228 /* Attempts to set input rate limiting (policing) policy. */
1229 int
1230 netdev_nodev_set_policing(const char *netdev_name, uint32_t kbits_rate,
1231                           uint32_t kbits_burst)
1232 {
1233     char command[1024];
1234
1235     init_netdev();
1236
1237     COVERAGE_INC(netdev_set_policing);
1238     if (kbits_rate) {
1239         if (!kbits_burst) {
1240             /* Default to 10 kilobits if not specified. */
1241             kbits_burst = 10;
1242         }
1243
1244         /* xxx This should be more careful about only adding if it
1245          * xxx actually exists, as opposed to always deleting it. */
1246         snprintf(command, sizeof(command), POLICE_DEL_CMD, netdev_name);
1247         if (system(command) == -1) {
1248             VLOG_WARN_RL(&rl, "%s: problem removing policing", netdev_name);
1249         }
1250
1251         snprintf(command, sizeof(command), POLICE_ADD_CMD, netdev_name);
1252         if (system(command) != 0) {
1253             VLOG_WARN_RL(&rl, "%s: problem adding policing", netdev_name);
1254             return -1;
1255         }
1256
1257         snprintf(command, sizeof(command), POLICE_CONFIG_CMD, netdev_name,
1258                 kbits_rate, kbits_burst);
1259         if (system(command) != 0) {
1260             VLOG_WARN_RL(&rl, "%s: problem configuring policing", 
1261                     netdev_name);
1262             return -1;
1263         }
1264     } else {
1265         snprintf(command, sizeof(command), POLICE_DEL_CMD, netdev_name);
1266         if (system(command) == -1) {
1267             VLOG_WARN_RL(&rl, "%s: problem removing policing", netdev_name);
1268         }
1269     }
1270
1271     return 0;
1272 }
1273
1274 int
1275 netdev_set_policing(struct netdev *netdev, uint32_t kbits_rate,
1276                     uint32_t kbits_burst)
1277 {
1278     return netdev_nodev_set_policing(netdev->name, kbits_rate, kbits_burst);
1279 }
1280
1281 /* Initializes 'svec' with a list of the names of all known network devices. */
1282 void
1283 netdev_enumerate(struct svec *svec)
1284 {
1285     struct if_nameindex *names;
1286
1287     svec_init(svec);
1288     names = if_nameindex();
1289     if (names) {
1290         size_t i;
1291
1292         for (i = 0; names[i].if_name != NULL; i++) {
1293             svec_add(svec, names[i].if_name);
1294         }
1295         if_freenameindex(names);
1296     } else {
1297         VLOG_WARN("could not obtain list of network device names: %s",
1298                   strerror(errno));
1299     }
1300 }
1301
1302 /* Attempts to locate a device based on its IPv4 address.  The caller
1303  * may provide a hint as to the device by setting 'netdev_name' to a
1304  * likely device name.  This string must be malloc'd, since if it is 
1305  * not correct then it will be freed.  If there is no hint, then
1306  * 'netdev_name' must be the NULL pointer.
1307  *
1308  * If the device is found, the return value will be true and 'netdev_name' 
1309  * contains the device's name as a string, which the caller is responsible 
1310  * for freeing.  If the device is not found, the return value is false. */
1311 bool
1312 netdev_find_dev_by_in4(const struct in_addr *in4, char **netdev_name)
1313 {
1314     int i;
1315     struct in_addr dev_in4;
1316     struct svec dev_list;
1317
1318     /* Check the hint first. */
1319     if (*netdev_name && !netdev_nodev_get_in4(*netdev_name, &dev_in4)
1320             && (dev_in4.s_addr == in4->s_addr)) {
1321         return true;
1322     }
1323
1324     free(*netdev_name);
1325     *netdev_name = NULL;
1326     netdev_enumerate(&dev_list);
1327
1328     for (i=0; i<dev_list.n; i++) {
1329         if (!netdev_nodev_get_in4(dev_list.names[i], &dev_in4)
1330                 && (dev_in4.s_addr == in4->s_addr)) {
1331             *netdev_name = xstrdup(dev_list.names[i]);
1332             svec_destroy(&dev_list);
1333             return true;
1334         }
1335     }
1336
1337     svec_destroy(&dev_list);
1338     return false;
1339 }
1340
1341 /* Obtains the current flags for the network device named 'netdev_name' and
1342  * stores them into '*flagsp'.  Returns 0 if successful, otherwise a positive
1343  * errno value.  On error, stores 0 into '*flagsp'.
1344  *
1345  * If only device flags are needed, this is more efficient than calling
1346  * netdev_open(), netdev_get_flags(), netdev_close(). */
1347 int
1348 netdev_nodev_get_flags(const char *netdev_name, enum netdev_flags *flagsp)
1349 {
1350     int error, flags;
1351
1352     init_netdev();
1353
1354     *flagsp = 0;
1355     error = get_flags(netdev_name, &flags);
1356     if (error) {
1357         return error;
1358     }
1359
1360     if (flags & IFF_UP) {
1361         *flagsp |= NETDEV_UP;
1362     }
1363     if (flags & IFF_PROMISC) {
1364         *flagsp |= NETDEV_PROMISC;
1365     }
1366     return 0;
1367 }
1368
1369 int
1370 netdev_nodev_get_etheraddr(const char *netdev_name, uint8_t mac[6])
1371 {
1372     init_netdev();
1373
1374     return get_etheraddr(netdev_name, mac, NULL);
1375 }
1376
1377 /* If 'netdev_name' is the name of a VLAN network device (e.g. one created with
1378  * vconfig(8)), sets '*vlan_vid' to the VLAN VID associated with that device
1379  * and returns 0.  Otherwise returns a errno value (specifically ENOENT if
1380  * 'netdev_name' is the name of a network device that is not a VLAN device) and
1381  * sets '*vlan_vid' to -1. */
1382 int
1383 netdev_get_vlan_vid(const char *netdev_name, int *vlan_vid)
1384 {
1385     struct ds line = DS_EMPTY_INITIALIZER;
1386     FILE *stream = NULL;
1387     int error;
1388     char *fn;
1389
1390     COVERAGE_INC(netdev_get_vlan_vid);
1391     fn = xasprintf("/proc/net/vlan/%s", netdev_name);
1392     stream = fopen(fn, "r");
1393     if (!stream) {
1394         error = errno;
1395         goto done;
1396     }
1397
1398     if (ds_get_line(&line, stream)) {
1399         if (ferror(stream)) {
1400             error = errno;
1401             VLOG_ERR_RL(&rl, "error reading \"%s\": %s", fn, strerror(errno));
1402         } else {
1403             error = EPROTO;
1404             VLOG_ERR_RL(&rl, "unexpected end of file reading \"%s\"", fn);
1405         }
1406         goto done;
1407     }
1408
1409     if (!sscanf(ds_cstr(&line), "%*s VID: %d", vlan_vid)) {
1410         error = EPROTO;
1411         VLOG_ERR_RL(&rl, "parse error reading \"%s\" line 1: \"%s\"",
1412                     fn, ds_cstr(&line));
1413         goto done;
1414     }
1415
1416     error = 0;
1417
1418 done:
1419     free(fn);
1420     if (stream) {
1421         fclose(stream);
1422     }
1423     ds_destroy(&line);
1424     if (error) {
1425         *vlan_vid = -1;
1426     }
1427     return error;
1428 }
1429 \f
1430 struct netdev_monitor {
1431     struct linux_netdev_notifier notifier;
1432     struct shash polled_netdevs;
1433     struct shash changed_netdevs;
1434 };
1435
1436 static void netdev_monitor_change(const struct linux_netdev_change *change,
1437                                   void *monitor);
1438
1439 int
1440 netdev_monitor_create(struct netdev_monitor **monitorp)
1441 {
1442     struct netdev_monitor *monitor;
1443     int error;
1444
1445     monitor = xmalloc(sizeof *monitor);
1446     error = linux_netdev_notifier_register(&monitor->notifier,
1447                                            netdev_monitor_change, monitor);
1448     if (error) {
1449         free(monitor);
1450         return error;
1451     }
1452     shash_init(&monitor->polled_netdevs);
1453     shash_init(&monitor->changed_netdevs);
1454     *monitorp = monitor;
1455     return 0;
1456 }
1457
1458 void
1459 netdev_monitor_destroy(struct netdev_monitor *monitor)
1460 {
1461     if (monitor) {
1462         linux_netdev_notifier_unregister(&monitor->notifier);
1463         shash_destroy(&monitor->polled_netdevs);
1464         free(monitor);
1465     }
1466 }
1467
1468 void
1469 netdev_monitor_add(struct netdev_monitor *monitor, struct netdev *netdev)
1470 {
1471     if (!shash_find(&monitor->polled_netdevs, netdev_get_name(netdev))) {
1472         shash_add(&monitor->polled_netdevs, netdev_get_name(netdev), NULL);
1473     }
1474 }
1475
1476 void
1477 netdev_monitor_remove(struct netdev_monitor *monitor, struct netdev *netdev)
1478 {
1479     struct shash_node *node;
1480
1481     node = shash_find(&monitor->polled_netdevs, netdev_get_name(netdev));
1482     if (node) {
1483         shash_delete(&monitor->polled_netdevs, node);
1484         node = shash_find(&monitor->changed_netdevs, netdev_get_name(netdev));
1485         if (node) {
1486             shash_delete(&monitor->changed_netdevs, node);
1487         }
1488     }
1489 }
1490
1491 int
1492 netdev_monitor_poll(struct netdev_monitor *monitor, char **devnamep)
1493 {
1494     int error = linux_netdev_notifier_get_error(&monitor->notifier);
1495     *devnamep = NULL;
1496     if (!error) {
1497         struct shash_node *node = shash_first(&monitor->changed_netdevs);
1498         if (!node) {
1499             return EAGAIN;
1500         }
1501         *devnamep = xstrdup(node->name);
1502         shash_delete(&monitor->changed_netdevs, node);
1503     } else {
1504         shash_clear(&monitor->changed_netdevs);
1505     }
1506     return error;
1507 }
1508
1509 void
1510 netdev_monitor_poll_wait(const struct netdev_monitor *monitor)
1511 {
1512     if (!shash_is_empty(&monitor->changed_netdevs)
1513         || linux_netdev_notifier_peek_error(&monitor->notifier)) {
1514         poll_immediate_wake();
1515     } else {
1516         linux_netdev_notifier_wait();
1517     }
1518 }
1519
1520 static void
1521 netdev_monitor_change(const struct linux_netdev_change *change, void *monitor_)
1522 {
1523     struct netdev_monitor *monitor = monitor_;
1524     if (shash_find(&monitor->polled_netdevs, change->ifname)
1525         && !shash_find(&monitor->changed_netdevs, change->ifname)) {
1526         shash_add(&monitor->changed_netdevs, change->ifname, NULL);
1527     }
1528 }
1529 \f
1530 static void restore_all_flags(void *aux);
1531
1532 /* Set up a signal hook to restore network device flags on program
1533  * termination.  */
1534 static void
1535 init_netdev(void)
1536 {
1537     static bool inited;
1538     if (!inited) {
1539         int ifindex;
1540         int error;
1541
1542         inited = true;
1543
1544         fatal_signal_add_hook(restore_all_flags, NULL, true);
1545
1546         af_inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
1547         if (af_inet_sock < 0) {
1548             ovs_fatal(errno, "socket(AF_INET)");
1549         }
1550
1551         error = nl_sock_create(NETLINK_ROUTE, 0, 0, 0, &rtnl_sock);
1552         if (error) {
1553             ovs_fatal(error, "socket(AF_NETLINK, NETLINK_ROUTE)");
1554         }
1555
1556         /* Decide on the netdev_get_stats() implementation to use.  Netlink is
1557          * preferable, so if that works, we'll use it. */
1558         ifindex = do_get_ifindex("lo");
1559         if (ifindex < 0) {
1560             VLOG_WARN("failed to get ifindex for lo, "
1561                       "obtaining netdev stats from proc");
1562             use_netlink_stats = false;
1563         } else {
1564             struct netdev_stats stats;
1565             error = get_stats_via_netlink(ifindex, &stats);
1566             if (!error) {
1567                 VLOG_DBG("obtaining netdev stats via rtnetlink");
1568                 use_netlink_stats = true;
1569             } else {
1570                 VLOG_INFO("RTM_GETLINK failed (%s), obtaining netdev stats "
1571                           "via proc (you are probably running a pre-2.6.19 "
1572                           "kernel)", strerror(error));
1573                 use_netlink_stats = false;
1574             }
1575         }
1576     }
1577 }
1578
1579 /* Restore the network device flags on 'netdev' to those that were active
1580  * before we changed them.  Returns 0 if successful, otherwise a positive
1581  * errno value.
1582  *
1583  * To avoid reentry, the caller must ensure that fatal signals are blocked. */
1584 static int
1585 restore_flags(struct netdev *netdev)
1586 {
1587     struct ifreq ifr;
1588     int restore_flags;
1589
1590     /* Get current flags. */
1591     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
1592     COVERAGE_INC(netdev_get_flags);
1593     if (ioctl(netdev->netdev_fd, SIOCGIFFLAGS, &ifr) < 0) {
1594         return errno;
1595     }
1596
1597     /* Restore flags that we might have changed, if necessary. */
1598     restore_flags = netdev->changed_flags & (IFF_PROMISC | IFF_UP);
1599     if ((ifr.ifr_flags ^ netdev->save_flags) & restore_flags) {
1600         ifr.ifr_flags &= ~restore_flags;
1601         ifr.ifr_flags |= netdev->save_flags & restore_flags;
1602         COVERAGE_INC(netdev_set_flags);
1603         if (ioctl(netdev->netdev_fd, SIOCSIFFLAGS, &ifr) < 0) {
1604             return errno;
1605         }
1606     }
1607
1608     return 0;
1609 }
1610
1611 /* Retores all the flags on all network devices that we modified.  Called from
1612  * a signal handler, so it does not attempt to report error conditions. */
1613 static void
1614 restore_all_flags(void *aux UNUSED)
1615 {
1616     struct netdev *netdev;
1617     LIST_FOR_EACH (netdev, struct netdev, node, &netdev_list) {
1618         restore_flags(netdev);
1619     }
1620 }
1621
1622 static int
1623 get_flags(const char *netdev_name, int *flags)
1624 {
1625     struct ifreq ifr;
1626     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
1627     COVERAGE_INC(netdev_get_flags);
1628     if (ioctl(af_inet_sock, SIOCGIFFLAGS, &ifr) < 0) {
1629         VLOG_ERR("ioctl(SIOCGIFFLAGS) on %s device failed: %s",
1630                  netdev_name, strerror(errno));
1631         return errno;
1632     }
1633     *flags = ifr.ifr_flags;
1634     return 0;
1635 }
1636
1637 static int
1638 set_flags(const char *netdev_name, int flags)
1639 {
1640     struct ifreq ifr;
1641     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
1642     ifr.ifr_flags = flags;
1643     COVERAGE_INC(netdev_set_flags);
1644     if (ioctl(af_inet_sock, SIOCSIFFLAGS, &ifr) < 0) {
1645         VLOG_ERR("ioctl(SIOCSIFFLAGS) on %s device failed: %s",
1646                  netdev_name, strerror(errno));
1647         return errno;
1648     }
1649     return 0;
1650 }
1651
1652 static int
1653 do_get_ifindex(const char *netdev_name)
1654 {
1655     struct ifreq ifr;
1656
1657     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
1658     COVERAGE_INC(netdev_get_ifindex);
1659     if (ioctl(af_inet_sock, SIOCGIFINDEX, &ifr) < 0) {
1660         VLOG_WARN_RL(&rl, "ioctl(SIOCGIFINDEX) on %s device failed: %s",
1661                      netdev_name, strerror(errno));
1662         return -errno;
1663     }
1664     return ifr.ifr_ifindex;
1665 }
1666
1667 static int
1668 get_ifindex(const struct netdev *netdev, int *ifindexp)
1669 {
1670     *ifindexp = 0;
1671     if (netdev->ifindex < 0) {
1672         int ifindex = do_get_ifindex(netdev->name);
1673         if (ifindex < 0) {
1674             return -ifindex;
1675         }
1676         ((struct netdev *) netdev)->ifindex = ifindex;
1677     }
1678     *ifindexp = netdev->ifindex;
1679     return 0;
1680 }
1681
1682 static int
1683 get_etheraddr(const char *netdev_name, uint8_t ea[ETH_ADDR_LEN],
1684               int *hwaddr_familyp)
1685 {
1686     struct ifreq ifr;
1687
1688     memset(&ifr, 0, sizeof ifr);
1689     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
1690     COVERAGE_INC(netdev_get_hwaddr);
1691     if (ioctl(af_inet_sock, SIOCGIFHWADDR, &ifr) < 0) {
1692         VLOG_ERR("ioctl(SIOCGIFHWADDR) on %s device failed: %s",
1693                  netdev_name, strerror(errno));
1694         return errno;
1695     }
1696     if (hwaddr_familyp) {
1697         int hwaddr_family = ifr.ifr_hwaddr.sa_family;
1698         *hwaddr_familyp = hwaddr_family;
1699         if (hwaddr_family != AF_UNSPEC && hwaddr_family != ARPHRD_ETHER) {
1700             VLOG_WARN("%s device has unknown hardware address family %d",
1701                       netdev_name, hwaddr_family);
1702         }
1703     }
1704     memcpy(ea, ifr.ifr_hwaddr.sa_data, ETH_ADDR_LEN);
1705     return 0;
1706 }
1707
1708 static int
1709 set_etheraddr(const char *netdev_name, int hwaddr_family,
1710               const uint8_t mac[ETH_ADDR_LEN])
1711 {
1712     struct ifreq ifr;
1713
1714     memset(&ifr, 0, sizeof ifr);
1715     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
1716     ifr.ifr_hwaddr.sa_family = hwaddr_family;
1717     memcpy(ifr.ifr_hwaddr.sa_data, mac, ETH_ADDR_LEN);
1718     COVERAGE_INC(netdev_set_hwaddr);
1719     if (ioctl(af_inet_sock, SIOCSIFHWADDR, &ifr) < 0) {
1720         VLOG_ERR("ioctl(SIOCSIFHWADDR) on %s device failed: %s",
1721                  netdev_name, strerror(errno));
1722         return errno;
1723     }
1724     return 0;
1725 }