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