netdev-vport: Use vport set_stats instead of internal dev.
[sliver-openvswitch.git] / lib / netdev-linux.c
1 /*
2  * Copyright (c) 2009, 2010 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 <assert.h>
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <arpa/inet.h>
22 #include <inttypes.h>
23 #include <linux/if_tun.h>
24 #include <linux/ip.h>
25 #include <linux/types.h>
26 #include <linux/ethtool.h>
27 #include <linux/pkt_sched.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 <linux/if_tunnel.h>
38 #include <net/if_arp.h>
39 #include <net/if_packet.h>
40 #include <net/route.h>
41 #include <netinet/in.h>
42 #include <poll.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <unistd.h>
46
47 #include "coverage.h"
48 #include "dynamic-string.h"
49 #include "fatal-signal.h"
50 #include "netdev-provider.h"
51 #include "netdev-vport.h"
52 #include "netlink.h"
53 #include "ofpbuf.h"
54 #include "openflow/openflow.h"
55 #include "openvswitch/gre.h"
56 #include "packets.h"
57 #include "poll-loop.h"
58 #include "rtnetlink.h"
59 #include "socket-util.h"
60 #include "shash.h"
61 #include "svec.h"
62
63 #define THIS_MODULE VLM_netdev_linux
64 #include "vlog.h"
65 \f
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 static struct rtnetlink_notifier netdev_linux_cache_notifier;
76 static int cache_notifier_refcount;
77
78 enum {
79     VALID_IFINDEX           = 1 << 0,
80     VALID_ETHERADDR         = 1 << 1,
81     VALID_IN4               = 1 << 2,
82     VALID_IN6               = 1 << 3,
83     VALID_MTU               = 1 << 4,
84     VALID_CARRIER           = 1 << 5,
85     VALID_IS_PSEUDO         = 1 << 6, /* Represents is_internal and is_tap. */
86     VALID_POLICING          = 1 << 7,
87     VALID_HAVE_VPORT_STATS  = 1 << 8
88 };
89
90 struct tap_state {
91     int fd;
92     bool opened;
93 };
94
95 struct netdev_dev_linux {
96     struct netdev_dev netdev_dev;
97
98     struct shash_node *shash_node;
99     unsigned int cache_valid;
100
101     /* The following are figured out "on demand" only.  They are only valid
102      * when the corresponding VALID_* bit in 'cache_valid' is set. */
103     int ifindex;
104     uint8_t etheraddr[ETH_ADDR_LEN];
105     struct in_addr address, netmask;
106     struct in6_addr in6;
107     int mtu;
108     int carrier;
109     bool is_internal;           /* Is this an openvswitch internal device? */
110     bool is_tap;                /* Is this a tuntap device? */
111     uint32_t kbits_rate;        /* Policing data. */
112     uint32_t kbits_burst;
113     bool have_vport_stats;
114
115     union {
116         struct tap_state tap;
117     } state;
118 };
119
120 struct netdev_linux {
121     struct netdev netdev;
122     int fd;
123 };
124
125 /* An AF_INET socket (used for ioctl operations). */
126 static int af_inet_sock = -1;
127
128 struct netdev_linux_notifier {
129     struct netdev_notifier notifier;
130     struct list node;
131 };
132
133 static struct shash netdev_linux_notifiers =
134     SHASH_INITIALIZER(&netdev_linux_notifiers);
135 static struct rtnetlink_notifier netdev_linux_poll_notifier;
136
137 /* This is set pretty low because we probably won't learn anything from the
138  * additional log messages. */
139 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
140
141 static int netdev_linux_init(void);
142
143 static int netdev_linux_do_ethtool(const char *name, struct ethtool_cmd *,
144                                    int cmd, const char *cmd_name);
145 static int netdev_linux_do_ioctl(const char *name, struct ifreq *, int cmd,
146                                  const char *cmd_name);
147 static int netdev_linux_get_ipv4(const struct netdev *, struct in_addr *,
148                                  int cmd, const char *cmd_name);
149 static int get_flags(const struct netdev *, int *flagsp);
150 static int set_flags(struct netdev *, int flags);
151 static int do_get_ifindex(const char *netdev_name);
152 static int get_ifindex(const struct netdev *, int *ifindexp);
153 static int do_set_addr(struct netdev *netdev,
154                        int ioctl_nr, const char *ioctl_name,
155                        struct in_addr addr);
156 static int get_etheraddr(const char *netdev_name, uint8_t ea[ETH_ADDR_LEN]);
157 static int set_etheraddr(const char *netdev_name, int hwaddr_family,
158                          const uint8_t[ETH_ADDR_LEN]);
159 static int get_stats_via_netlink(int ifindex, struct netdev_stats *stats);
160 static int get_stats_via_proc(const char *netdev_name, struct netdev_stats *stats);
161 static int get_rtnl_sock(struct nl_sock **);
162
163 static bool
164 is_netdev_linux_class(const struct netdev_class *netdev_class)
165 {
166     return netdev_class->init == netdev_linux_init;
167 }
168
169 static struct netdev_dev_linux *
170 netdev_dev_linux_cast(const struct netdev_dev *netdev_dev)
171 {
172     const struct netdev_class *netdev_class = netdev_dev_get_class(netdev_dev);
173     assert(is_netdev_linux_class(netdev_class));
174
175     return CONTAINER_OF(netdev_dev, struct netdev_dev_linux, netdev_dev);
176 }
177
178 static struct netdev_linux *
179 netdev_linux_cast(const struct netdev *netdev)
180 {
181     struct netdev_dev *netdev_dev = netdev_get_dev(netdev);
182     const struct netdev_class *netdev_class = netdev_dev_get_class(netdev_dev);
183     assert(is_netdev_linux_class(netdev_class));
184
185     return CONTAINER_OF(netdev, struct netdev_linux, netdev);
186 }
187
188 static int
189 netdev_linux_init(void)
190 {
191     static int status = -1;
192     if (status < 0) {
193         af_inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
194         status = af_inet_sock >= 0 ? 0 : errno;
195         if (status) {
196             VLOG_ERR("failed to create inet socket: %s", strerror(status));
197         }
198     }
199     return status;
200 }
201
202 static void
203 netdev_linux_run(void)
204 {
205     rtnetlink_notifier_run();
206 }
207
208 static void
209 netdev_linux_wait(void)
210 {
211     rtnetlink_notifier_wait();
212 }
213
214 static void
215 netdev_linux_cache_cb(const struct rtnetlink_change *change,
216                       void *aux OVS_UNUSED)
217 {
218     struct netdev_dev_linux *dev;
219     if (change) {
220         struct netdev_dev *base_dev = netdev_dev_from_name(change->ifname);
221         if (base_dev) {
222             const struct netdev_class *netdev_class =
223                                                 netdev_dev_get_class(base_dev);
224
225             if (is_netdev_linux_class(netdev_class)) {
226                 dev = netdev_dev_linux_cast(base_dev);
227                 dev->cache_valid = 0;
228             }
229         }
230     } else {
231         struct shash device_shash;
232         struct shash_node *node;
233
234         shash_init(&device_shash);
235         netdev_dev_get_devices(&netdev_linux_class, &device_shash);
236         SHASH_FOR_EACH (node, &device_shash) {
237             dev = node->data;
238             dev->cache_valid = 0;
239         }
240         shash_destroy(&device_shash);
241     }
242 }
243
244 /* Creates the netdev device of 'type' with 'name'. */
245 static int
246 netdev_linux_create_system(const char *name, const char *type OVS_UNUSED,
247                     const struct shash *args, struct netdev_dev **netdev_devp)
248 {
249     struct netdev_dev_linux *netdev_dev;
250     int error;
251
252     if (!shash_is_empty(args)) {
253         VLOG_WARN("%s: arguments for system devices should be empty", name);
254     }
255
256     if (!cache_notifier_refcount) {
257         error = rtnetlink_notifier_register(&netdev_linux_cache_notifier,
258                                             netdev_linux_cache_cb, NULL);
259         if (error) {
260             return error;
261         }
262     }
263     cache_notifier_refcount++;
264
265     netdev_dev = xzalloc(sizeof *netdev_dev);
266     netdev_dev_init(&netdev_dev->netdev_dev, name, &netdev_linux_class);
267
268     *netdev_devp = &netdev_dev->netdev_dev;
269     return 0;
270 }
271
272 /* For most types of netdevs we open the device for each call of
273  * netdev_open().  However, this is not the case with tap devices,
274  * since it is only possible to open the device once.  In this
275  * situation we share a single file descriptor, and consequently
276  * buffers, across all readers.  Therefore once data is read it will
277  * be unavailable to other reads for tap devices. */
278 static int
279 netdev_linux_create_tap(const char *name, const char *type OVS_UNUSED,
280                     const struct shash *args, struct netdev_dev **netdev_devp)
281 {
282     struct netdev_dev_linux *netdev_dev;
283     struct tap_state *state;
284     static const char tap_dev[] = "/dev/net/tun";
285     struct ifreq ifr;
286     int error;
287
288     if (!shash_is_empty(args)) {
289         VLOG_WARN("%s: arguments for TAP devices should be empty", name);
290     }
291
292     netdev_dev = xzalloc(sizeof *netdev_dev);
293     state = &netdev_dev->state.tap;
294
295     /* Open tap device. */
296     state->fd = open(tap_dev, O_RDWR);
297     if (state->fd < 0) {
298         error = errno;
299         VLOG_WARN("opening \"%s\" failed: %s", tap_dev, strerror(error));
300         goto error;
301     }
302
303     /* Create tap device. */
304     ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
305     strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
306     if (ioctl(state->fd, TUNSETIFF, &ifr) == -1) {
307         VLOG_WARN("%s: creating tap device failed: %s", name,
308                   strerror(errno));
309         error = errno;
310         goto error;
311     }
312
313     /* Make non-blocking. */
314     error = set_nonblocking(state->fd);
315     if (error) {
316         goto error;
317     }
318
319     netdev_dev_init(&netdev_dev->netdev_dev, name, &netdev_tap_class);
320     *netdev_devp = &netdev_dev->netdev_dev;
321     return 0;
322
323 error:
324     free(netdev_dev);
325     return error;
326 }
327
328 static void
329 destroy_tap(struct netdev_dev_linux *netdev_dev)
330 {
331     struct tap_state *state = &netdev_dev->state.tap;
332
333     if (state->fd >= 0) {
334         close(state->fd);
335     }
336 }
337
338 /* Destroys the netdev device 'netdev_dev_'. */
339 static void
340 netdev_linux_destroy(struct netdev_dev *netdev_dev_)
341 {
342     struct netdev_dev_linux *netdev_dev = netdev_dev_linux_cast(netdev_dev_);
343     const char *type = netdev_dev_get_type(netdev_dev_);
344
345     if (!strcmp(type, "system")) {
346         cache_notifier_refcount--;
347
348         if (!cache_notifier_refcount) {
349             rtnetlink_notifier_unregister(&netdev_linux_cache_notifier);
350         }
351     } else if (!strcmp(type, "tap")) {
352         destroy_tap(netdev_dev);
353     }
354
355     free(netdev_dev);
356 }
357
358 static int
359 netdev_linux_open(struct netdev_dev *netdev_dev_, int ethertype,
360                   struct netdev **netdevp)
361 {
362     struct netdev_dev_linux *netdev_dev = netdev_dev_linux_cast(netdev_dev_);
363     struct netdev_linux *netdev;
364     enum netdev_flags flags;
365     int error;
366
367     /* Allocate network device. */
368     netdev = xzalloc(sizeof *netdev);
369     netdev->fd = -1;
370     netdev_init(&netdev->netdev, netdev_dev_);
371
372     error = netdev_get_flags(&netdev->netdev, &flags);
373     if (error == ENODEV) {
374         goto error;
375     }
376
377     if (!strcmp(netdev_dev_get_type(netdev_dev_), "tap") &&
378         !netdev_dev->state.tap.opened) {
379
380         /* We assume that the first user of the tap device is the primary user
381          * and give them the tap FD.  Subsequent users probably just expect
382          * this to be a system device so open it normally to avoid send/receive
383          * directions appearing to be reversed. */
384         netdev->fd = netdev_dev->state.tap.fd;
385         netdev_dev->state.tap.opened = true;
386     } else if (ethertype != NETDEV_ETH_TYPE_NONE) {
387         struct sockaddr_ll sll;
388         int protocol;
389         int ifindex;
390
391         /* Create file descriptor. */
392         protocol = (ethertype == NETDEV_ETH_TYPE_ANY ? ETH_P_ALL
393                     : ethertype == NETDEV_ETH_TYPE_802_2 ? ETH_P_802_2
394                     : ethertype);
395         netdev->fd = socket(PF_PACKET, SOCK_RAW, htons(protocol));
396         if (netdev->fd < 0) {
397             error = errno;
398             goto error;
399         }
400
401         /* Set non-blocking mode. */
402         error = set_nonblocking(netdev->fd);
403         if (error) {
404             goto error;
405         }
406
407         /* Get ethernet device index. */
408         error = get_ifindex(&netdev->netdev, &ifindex);
409         if (error) {
410             goto error;
411         }
412
413         /* Bind to specific ethernet device. */
414         memset(&sll, 0, sizeof sll);
415         sll.sll_family = AF_PACKET;
416         sll.sll_ifindex = ifindex;
417         if (bind(netdev->fd,
418                  (struct sockaddr *) &sll, sizeof sll) < 0) {
419             error = errno;
420             VLOG_ERR("bind to %s failed: %s", netdev_dev_get_name(netdev_dev_),
421                      strerror(error));
422             goto error;
423         }
424
425         /* Between the socket() and bind() calls above, the socket receives all
426          * packets of the requested type on all system interfaces.  We do not
427          * want to receive that data, but there is no way to avoid it.  So we
428          * must now drain out the receive queue. */
429         error = drain_rcvbuf(netdev->fd);
430         if (error) {
431             goto error;
432         }
433     }
434
435     *netdevp = &netdev->netdev;
436     return 0;
437
438 error:
439     netdev_uninit(&netdev->netdev, true);
440     return error;
441 }
442
443 /* Closes and destroys 'netdev'. */
444 static void
445 netdev_linux_close(struct netdev *netdev_)
446 {
447     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
448
449     if (netdev->fd > 0 && strcmp(netdev_get_type(netdev_), "tap")) {
450         close(netdev->fd);
451     }
452     free(netdev);
453 }
454
455 /* Initializes 'svec' with a list of the names of all known network devices. */
456 static int
457 netdev_linux_enumerate(struct svec *svec)
458 {
459     struct if_nameindex *names;
460
461     names = if_nameindex();
462     if (names) {
463         size_t i;
464
465         for (i = 0; names[i].if_name != NULL; i++) {
466             svec_add(svec, names[i].if_name);
467         }
468         if_freenameindex(names);
469         return 0;
470     } else {
471         VLOG_WARN("could not obtain list of network device names: %s",
472                   strerror(errno));
473         return errno;
474     }
475 }
476
477 static int
478 netdev_linux_recv(struct netdev *netdev_, void *data, size_t size)
479 {
480     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
481
482     if (netdev->fd < 0) {
483         /* Device was opened with NETDEV_ETH_TYPE_NONE. */
484         return -EAGAIN;
485     }
486
487     for (;;) {
488         ssize_t retval = read(netdev->fd, data, size);
489         if (retval >= 0) {
490             return retval;
491         } else if (errno != EINTR) {
492             if (errno != EAGAIN) {
493                 VLOG_WARN_RL(&rl, "error receiving Ethernet packet on %s: %s",
494                              strerror(errno), netdev_get_name(netdev_));
495             }
496             return -errno;
497         }
498     }
499 }
500
501 /* Registers with the poll loop to wake up from the next call to poll_block()
502  * when a packet is ready to be received with netdev_recv() on 'netdev'. */
503 static void
504 netdev_linux_recv_wait(struct netdev *netdev_)
505 {
506     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
507     if (netdev->fd >= 0) {
508         poll_fd_wait(netdev->fd, POLLIN);
509     }
510 }
511
512 /* Discards all packets waiting to be received from 'netdev'. */
513 static int
514 netdev_linux_drain(struct netdev *netdev_)
515 {
516     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
517     if (netdev->fd < 0) {
518         return 0;
519     } else if (!strcmp(netdev_get_type(netdev_), "tap")) {
520         struct ifreq ifr;
521         int error = netdev_linux_do_ioctl(netdev_get_name(netdev_), &ifr,
522                                           SIOCGIFTXQLEN, "SIOCGIFTXQLEN");
523         if (error) {
524             return error;
525         }
526         drain_fd(netdev->fd, ifr.ifr_qlen);
527         return 0;
528     } else {
529         return drain_rcvbuf(netdev->fd);
530     }
531 }
532
533 /* Sends 'buffer' on 'netdev'.  Returns 0 if successful, otherwise a positive
534  * errno value.  Returns EAGAIN without blocking if the packet cannot be queued
535  * immediately.  Returns EMSGSIZE if a partial packet was transmitted or if
536  * the packet is too big or too small to transmit on the device.
537  *
538  * The caller retains ownership of 'buffer' in all cases.
539  *
540  * The kernel maintains a packet transmission queue, so the caller is not
541  * expected to do additional queuing of packets. */
542 static int
543 netdev_linux_send(struct netdev *netdev_, const void *data, size_t size)
544 {
545     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
546
547     /* XXX should support sending even if 'ethertype' was NETDEV_ETH_TYPE_NONE.
548      */
549     if (netdev->fd < 0) {
550         return EPIPE;
551     }
552
553     for (;;) {
554         ssize_t retval = write(netdev->fd, data, size);
555         if (retval < 0) {
556             /* The Linux AF_PACKET implementation never blocks waiting for room
557              * for packets, instead returning ENOBUFS.  Translate this into
558              * EAGAIN for the caller. */
559             if (errno == ENOBUFS) {
560                 return EAGAIN;
561             } else if (errno == EINTR) {
562                 continue;
563             } else if (errno != EAGAIN) {
564                 VLOG_WARN_RL(&rl, "error sending Ethernet packet on %s: %s",
565                              netdev_get_name(netdev_), strerror(errno));
566             }
567             return errno;
568         } else if (retval != size) {
569             VLOG_WARN_RL(&rl, "sent partial Ethernet packet (%zd bytes of "
570                          "%zu) on %s", retval, size, netdev_get_name(netdev_));
571             return EMSGSIZE;
572         } else {
573             return 0;
574         }
575     }
576 }
577
578 /* Registers with the poll loop to wake up from the next call to poll_block()
579  * when the packet transmission queue has sufficient room to transmit a packet
580  * with netdev_send().
581  *
582  * The kernel maintains a packet transmission queue, so the client is not
583  * expected to do additional queuing of packets.  Thus, this function is
584  * unlikely to ever be used.  It is included for completeness. */
585 static void
586 netdev_linux_send_wait(struct netdev *netdev_)
587 {
588     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
589     if (netdev->fd < 0) {
590         /* Nothing to do. */
591     } else if (strcmp(netdev_get_type(netdev_), "tap")) {
592         poll_fd_wait(netdev->fd, POLLOUT);
593     } else {
594         /* TAP device always accepts packets.*/
595         poll_immediate_wake();
596     }
597 }
598
599 /* Attempts to set 'netdev''s MAC address to 'mac'.  Returns 0 if successful,
600  * otherwise a positive errno value. */
601 static int
602 netdev_linux_set_etheraddr(struct netdev *netdev_,
603                            const uint8_t mac[ETH_ADDR_LEN])
604 {
605     struct netdev_dev_linux *netdev_dev =
606                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
607     int error;
608
609     if (!(netdev_dev->cache_valid & VALID_ETHERADDR)
610         || !eth_addr_equals(netdev_dev->etheraddr, mac)) {
611         error = set_etheraddr(netdev_get_name(netdev_), ARPHRD_ETHER, mac);
612         if (!error) {
613             netdev_dev->cache_valid |= VALID_ETHERADDR;
614             memcpy(netdev_dev->etheraddr, mac, ETH_ADDR_LEN);
615         }
616     } else {
617         error = 0;
618     }
619     return error;
620 }
621
622 /* Returns a pointer to 'netdev''s MAC address.  The caller must not modify or
623  * free the returned buffer. */
624 static int
625 netdev_linux_get_etheraddr(const struct netdev *netdev_,
626                            uint8_t mac[ETH_ADDR_LEN])
627 {
628     struct netdev_dev_linux *netdev_dev =
629                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
630     if (!(netdev_dev->cache_valid & VALID_ETHERADDR)) {
631         int error = get_etheraddr(netdev_get_name(netdev_),
632                                   netdev_dev->etheraddr);
633         if (error) {
634             return error;
635         }
636         netdev_dev->cache_valid |= VALID_ETHERADDR;
637     }
638     memcpy(mac, netdev_dev->etheraddr, ETH_ADDR_LEN);
639     return 0;
640 }
641
642 /* Returns the maximum size of transmitted (and received) packets on 'netdev',
643  * in bytes, not including the hardware header; thus, this is typically 1500
644  * bytes for Ethernet devices. */
645 static int
646 netdev_linux_get_mtu(const struct netdev *netdev_, int *mtup)
647 {
648     struct netdev_dev_linux *netdev_dev =
649                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
650     if (!(netdev_dev->cache_valid & VALID_MTU)) {
651         struct ifreq ifr;
652         int error;
653
654         error = netdev_linux_do_ioctl(netdev_get_name(netdev_), &ifr,
655                                       SIOCGIFMTU, "SIOCGIFMTU");
656         if (error) {
657             return error;
658         }
659         netdev_dev->mtu = ifr.ifr_mtu;
660         netdev_dev->cache_valid |= VALID_MTU;
661     }
662     *mtup = netdev_dev->mtu;
663     return 0;
664 }
665
666 /* Returns the ifindex of 'netdev', if successful, as a positive number.
667  * On failure, returns a negative errno value. */
668 static int
669 netdev_linux_get_ifindex(const struct netdev *netdev)
670 {
671     int ifindex, error;
672
673     error = get_ifindex(netdev, &ifindex);
674     return error ? -error : ifindex;
675 }
676
677 static int
678 netdev_linux_get_carrier(const struct netdev *netdev_, bool *carrier)
679 {
680     struct netdev_dev_linux *netdev_dev =
681                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
682     int error = 0;
683     char *fn = NULL;
684     int fd = -1;
685
686     if (!(netdev_dev->cache_valid & VALID_CARRIER)) {
687         char line[8];
688         int retval;
689
690         fn = xasprintf("/sys/class/net/%s/carrier",
691                        netdev_get_name(netdev_));
692         fd = open(fn, O_RDONLY);
693         if (fd < 0) {
694             error = errno;
695             VLOG_WARN_RL(&rl, "%s: open failed: %s", fn, strerror(error));
696             goto exit;
697         }
698
699         retval = read(fd, line, sizeof line);
700         if (retval < 0) {
701             error = errno;
702             if (error == EINVAL) {
703                 /* This is the normal return value when we try to check carrier
704                  * if the network device is not up. */
705             } else {
706                 VLOG_WARN_RL(&rl, "%s: read failed: %s", fn, strerror(error));
707             }
708             goto exit;
709         } else if (retval == 0) {
710             error = EPROTO;
711             VLOG_WARN_RL(&rl, "%s: unexpected end of file", fn);
712             goto exit;
713         }
714
715         if (line[0] != '0' && line[0] != '1') {
716             error = EPROTO;
717             VLOG_WARN_RL(&rl, "%s: value is %c (expected 0 or 1)",
718                          fn, line[0]);
719             goto exit;
720         }
721         netdev_dev->carrier = line[0] != '0';
722         netdev_dev->cache_valid |= VALID_CARRIER;
723     }
724     *carrier = netdev_dev->carrier;
725     error = 0;
726
727 exit:
728     if (fd >= 0) {
729         close(fd);
730     }
731     free(fn);
732     return error;
733 }
734
735 /* Check whether we can we use RTM_GETLINK to get network device statistics.
736  * In pre-2.6.19 kernels, this was only available if wireless extensions were
737  * enabled. */
738 static bool
739 check_for_working_netlink_stats(void)
740 {
741     /* Decide on the netdev_get_stats() implementation to use.  Netlink is
742      * preferable, so if that works, we'll use it. */
743     int ifindex = do_get_ifindex("lo");
744     if (ifindex < 0) {
745         VLOG_WARN("failed to get ifindex for lo, "
746                   "obtaining netdev stats from proc");
747         return false;
748     } else {
749         struct netdev_stats stats;
750         int error = get_stats_via_netlink(ifindex, &stats);
751         if (!error) {
752             VLOG_DBG("obtaining netdev stats via rtnetlink");
753             return true;
754         } else {
755             VLOG_INFO("RTM_GETLINK failed (%s), obtaining netdev stats "
756                       "via proc (you are probably running a pre-2.6.19 "
757                       "kernel)", strerror(error));
758             return false;
759         }
760     }
761 }
762
763 /* Brings the 'is_internal' and 'is_tap' members of 'netdev_dev' up-to-date. */
764 static void
765 netdev_linux_update_is_pseudo(struct netdev_dev_linux *netdev_dev)
766 {
767     if (!(netdev_dev->cache_valid & VALID_IS_PSEUDO)) {
768         const char *name = netdev_dev_get_name(&netdev_dev->netdev_dev);
769         const char *type = netdev_dev_get_type(&netdev_dev->netdev_dev);
770         
771         netdev_dev->is_tap = !strcmp(type, "tap");
772         netdev_dev->is_internal = false;
773         if (!netdev_dev->is_tap) {
774             struct ethtool_drvinfo drvinfo;
775             int error;
776
777             memset(&drvinfo, 0, sizeof drvinfo);
778             error = netdev_linux_do_ethtool(name,
779                                             (struct ethtool_cmd *)&drvinfo,
780                                             ETHTOOL_GDRVINFO,
781                                             "ETHTOOL_GDRVINFO");
782
783             if (!error && !strcmp(drvinfo.driver, "openvswitch")) {
784                 netdev_dev->is_internal = true;
785             }
786         }
787
788         netdev_dev->cache_valid |= VALID_IS_PSEUDO;
789     }
790 }
791
792 static void
793 swap_uint64(uint64_t *a, uint64_t *b)
794 {
795     *a ^= *b;
796     *b ^= *a;
797     *a ^= *b;
798 }
799
800 /* Retrieves current device stats for 'netdev'. */
801 static int
802 netdev_linux_get_stats(const struct netdev *netdev_,
803                        struct netdev_stats *stats)
804 {
805     struct netdev_dev_linux *netdev_dev =
806                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
807     static int use_netlink_stats = -1;
808     int error;
809
810     COVERAGE_INC(netdev_get_stats);
811
812     if (netdev_dev->have_vport_stats ||
813         !(netdev_dev->cache_valid & VALID_HAVE_VPORT_STATS)) {
814
815         error = netdev_vport_get_stats(netdev_, stats);
816         netdev_dev->have_vport_stats = !error;
817         netdev_dev->cache_valid |= VALID_HAVE_VPORT_STATS;
818     }
819
820     if (!netdev_dev->have_vport_stats) {
821         if (use_netlink_stats < 0) {
822             use_netlink_stats = check_for_working_netlink_stats();
823         }
824         if (use_netlink_stats) {
825             int ifindex;
826
827             error = get_ifindex(netdev_, &ifindex);
828             if (!error) {
829                 error = get_stats_via_netlink(ifindex, stats);
830             }
831         } else {
832             error = get_stats_via_proc(netdev_get_name(netdev_), stats);
833         }
834     }
835
836     /* If this port is an internal port then the transmit and receive stats
837      * will appear to be swapped relative to the other ports since we are the
838      * one sending the data, not a remote computer.  For consistency, we swap
839      * them back here. This does not apply if we are getting stats from the
840      * vport layer because it always tracks stats from the perspective of the
841      * switch. */
842     netdev_linux_update_is_pseudo(netdev_dev);
843     if (!error && !netdev_dev->have_vport_stats &&
844         (netdev_dev->is_internal || netdev_dev->is_tap)) {
845         swap_uint64(&stats->rx_packets, &stats->tx_packets);
846         swap_uint64(&stats->rx_bytes, &stats->tx_bytes);
847         swap_uint64(&stats->rx_errors, &stats->tx_errors);
848         swap_uint64(&stats->rx_dropped, &stats->tx_dropped);
849         stats->rx_length_errors = 0;
850         stats->rx_over_errors = 0;
851         stats->rx_crc_errors = 0;
852         stats->rx_frame_errors = 0;
853         stats->rx_fifo_errors = 0;
854         stats->rx_missed_errors = 0;
855         stats->tx_aborted_errors = 0;
856         stats->tx_carrier_errors = 0;
857         stats->tx_fifo_errors = 0;
858         stats->tx_heartbeat_errors = 0;
859         stats->tx_window_errors = 0;
860     }
861
862     return error;
863 }
864
865 /* Stores the features supported by 'netdev' into each of '*current',
866  * '*advertised', '*supported', and '*peer' that are non-null.  Each value is a
867  * bitmap of "enum ofp_port_features" bits, in host byte order.  Returns 0 if
868  * successful, otherwise a positive errno value. */
869 static int
870 netdev_linux_get_features(struct netdev *netdev,
871                           uint32_t *current, uint32_t *advertised,
872                           uint32_t *supported, uint32_t *peer)
873 {
874     struct ethtool_cmd ecmd;
875     int error;
876
877     memset(&ecmd, 0, sizeof ecmd);
878     error = netdev_linux_do_ethtool(netdev_get_name(netdev), &ecmd,
879                                     ETHTOOL_GSET, "ETHTOOL_GSET");
880     if (error) {
881         return error;
882     }
883
884     /* Supported features. */
885     *supported = 0;
886     if (ecmd.supported & SUPPORTED_10baseT_Half) {
887         *supported |= OFPPF_10MB_HD;
888     }
889     if (ecmd.supported & SUPPORTED_10baseT_Full) {
890         *supported |= OFPPF_10MB_FD;
891     }
892     if (ecmd.supported & SUPPORTED_100baseT_Half)  {
893         *supported |= OFPPF_100MB_HD;
894     }
895     if (ecmd.supported & SUPPORTED_100baseT_Full) {
896         *supported |= OFPPF_100MB_FD;
897     }
898     if (ecmd.supported & SUPPORTED_1000baseT_Half) {
899         *supported |= OFPPF_1GB_HD;
900     }
901     if (ecmd.supported & SUPPORTED_1000baseT_Full) {
902         *supported |= OFPPF_1GB_FD;
903     }
904     if (ecmd.supported & SUPPORTED_10000baseT_Full) {
905         *supported |= OFPPF_10GB_FD;
906     }
907     if (ecmd.supported & SUPPORTED_TP) {
908         *supported |= OFPPF_COPPER;
909     }
910     if (ecmd.supported & SUPPORTED_FIBRE) {
911         *supported |= OFPPF_FIBER;
912     }
913     if (ecmd.supported & SUPPORTED_Autoneg) {
914         *supported |= OFPPF_AUTONEG;
915     }
916     if (ecmd.supported & SUPPORTED_Pause) {
917         *supported |= OFPPF_PAUSE;
918     }
919     if (ecmd.supported & SUPPORTED_Asym_Pause) {
920         *supported |= OFPPF_PAUSE_ASYM;
921     }
922
923     /* Advertised features. */
924     *advertised = 0;
925     if (ecmd.advertising & ADVERTISED_10baseT_Half) {
926         *advertised |= OFPPF_10MB_HD;
927     }
928     if (ecmd.advertising & ADVERTISED_10baseT_Full) {
929         *advertised |= OFPPF_10MB_FD;
930     }
931     if (ecmd.advertising & ADVERTISED_100baseT_Half) {
932         *advertised |= OFPPF_100MB_HD;
933     }
934     if (ecmd.advertising & ADVERTISED_100baseT_Full) {
935         *advertised |= OFPPF_100MB_FD;
936     }
937     if (ecmd.advertising & ADVERTISED_1000baseT_Half) {
938         *advertised |= OFPPF_1GB_HD;
939     }
940     if (ecmd.advertising & ADVERTISED_1000baseT_Full) {
941         *advertised |= OFPPF_1GB_FD;
942     }
943     if (ecmd.advertising & ADVERTISED_10000baseT_Full) {
944         *advertised |= OFPPF_10GB_FD;
945     }
946     if (ecmd.advertising & ADVERTISED_TP) {
947         *advertised |= OFPPF_COPPER;
948     }
949     if (ecmd.advertising & ADVERTISED_FIBRE) {
950         *advertised |= OFPPF_FIBER;
951     }
952     if (ecmd.advertising & ADVERTISED_Autoneg) {
953         *advertised |= OFPPF_AUTONEG;
954     }
955     if (ecmd.advertising & ADVERTISED_Pause) {
956         *advertised |= OFPPF_PAUSE;
957     }
958     if (ecmd.advertising & ADVERTISED_Asym_Pause) {
959         *advertised |= OFPPF_PAUSE_ASYM;
960     }
961
962     /* Current settings. */
963     if (ecmd.speed == SPEED_10) {
964         *current = ecmd.duplex ? OFPPF_10MB_FD : OFPPF_10MB_HD;
965     } else if (ecmd.speed == SPEED_100) {
966         *current = ecmd.duplex ? OFPPF_100MB_FD : OFPPF_100MB_HD;
967     } else if (ecmd.speed == SPEED_1000) {
968         *current = ecmd.duplex ? OFPPF_1GB_FD : OFPPF_1GB_HD;
969     } else if (ecmd.speed == SPEED_10000) {
970         *current = OFPPF_10GB_FD;
971     } else {
972         *current = 0;
973     }
974
975     if (ecmd.port == PORT_TP) {
976         *current |= OFPPF_COPPER;
977     } else if (ecmd.port == PORT_FIBRE) {
978         *current |= OFPPF_FIBER;
979     }
980
981     if (ecmd.autoneg) {
982         *current |= OFPPF_AUTONEG;
983     }
984
985     /* Peer advertisements. */
986     *peer = 0;                  /* XXX */
987
988     return 0;
989 }
990
991 /* Set the features advertised by 'netdev' to 'advertise'. */
992 static int
993 netdev_linux_set_advertisements(struct netdev *netdev, uint32_t advertise)
994 {
995     struct ethtool_cmd ecmd;
996     int error;
997
998     memset(&ecmd, 0, sizeof ecmd);
999     error = netdev_linux_do_ethtool(netdev_get_name(netdev), &ecmd,
1000                                     ETHTOOL_GSET, "ETHTOOL_GSET");
1001     if (error) {
1002         return error;
1003     }
1004
1005     ecmd.advertising = 0;
1006     if (advertise & OFPPF_10MB_HD) {
1007         ecmd.advertising |= ADVERTISED_10baseT_Half;
1008     }
1009     if (advertise & OFPPF_10MB_FD) {
1010         ecmd.advertising |= ADVERTISED_10baseT_Full;
1011     }
1012     if (advertise & OFPPF_100MB_HD) {
1013         ecmd.advertising |= ADVERTISED_100baseT_Half;
1014     }
1015     if (advertise & OFPPF_100MB_FD) {
1016         ecmd.advertising |= ADVERTISED_100baseT_Full;
1017     }
1018     if (advertise & OFPPF_1GB_HD) {
1019         ecmd.advertising |= ADVERTISED_1000baseT_Half;
1020     }
1021     if (advertise & OFPPF_1GB_FD) {
1022         ecmd.advertising |= ADVERTISED_1000baseT_Full;
1023     }
1024     if (advertise & OFPPF_10GB_FD) {
1025         ecmd.advertising |= ADVERTISED_10000baseT_Full;
1026     }
1027     if (advertise & OFPPF_COPPER) {
1028         ecmd.advertising |= ADVERTISED_TP;
1029     }
1030     if (advertise & OFPPF_FIBER) {
1031         ecmd.advertising |= ADVERTISED_FIBRE;
1032     }
1033     if (advertise & OFPPF_AUTONEG) {
1034         ecmd.advertising |= ADVERTISED_Autoneg;
1035     }
1036     if (advertise & OFPPF_PAUSE) {
1037         ecmd.advertising |= ADVERTISED_Pause;
1038     }
1039     if (advertise & OFPPF_PAUSE_ASYM) {
1040         ecmd.advertising |= ADVERTISED_Asym_Pause;
1041     }
1042     return netdev_linux_do_ethtool(netdev_get_name(netdev), &ecmd,
1043                                    ETHTOOL_SSET, "ETHTOOL_SSET");
1044 }
1045
1046 /* If 'netdev_name' is the name of a VLAN network device (e.g. one created with
1047  * vconfig(8)), sets '*vlan_vid' to the VLAN VID associated with that device
1048  * and returns 0.  Otherwise returns a errno value (specifically ENOENT if
1049  * 'netdev_name' is the name of a network device that is not a VLAN device) and
1050  * sets '*vlan_vid' to -1. */
1051 static int
1052 netdev_linux_get_vlan_vid(const struct netdev *netdev, int *vlan_vid)
1053 {
1054     const char *netdev_name = netdev_get_name(netdev);
1055     struct ds line = DS_EMPTY_INITIALIZER;
1056     FILE *stream = NULL;
1057     int error;
1058     char *fn;
1059
1060     COVERAGE_INC(netdev_get_vlan_vid);
1061     fn = xasprintf("/proc/net/vlan/%s", netdev_name);
1062     stream = fopen(fn, "r");
1063     if (!stream) {
1064         error = errno;
1065         goto done;
1066     }
1067
1068     if (ds_get_line(&line, stream)) {
1069         if (ferror(stream)) {
1070             error = errno;
1071             VLOG_ERR_RL(&rl, "error reading \"%s\": %s", fn, strerror(errno));
1072         } else {
1073             error = EPROTO;
1074             VLOG_ERR_RL(&rl, "unexpected end of file reading \"%s\"", fn);
1075         }
1076         goto done;
1077     }
1078
1079     if (!sscanf(ds_cstr(&line), "%*s VID: %d", vlan_vid)) {
1080         error = EPROTO;
1081         VLOG_ERR_RL(&rl, "parse error reading \"%s\" line 1: \"%s\"",
1082                     fn, ds_cstr(&line));
1083         goto done;
1084     }
1085
1086     error = 0;
1087
1088 done:
1089     free(fn);
1090     if (stream) {
1091         fclose(stream);
1092     }
1093     ds_destroy(&line);
1094     if (error) {
1095         *vlan_vid = -1;
1096     }
1097     return error;
1098 }
1099
1100 #define POLICE_ADD_CMD "/sbin/tc qdisc add dev %s handle ffff: ingress"
1101 #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"
1102
1103 /* Remove ingress policing from 'netdev'.  Returns 0 if successful, otherwise a
1104  * positive errno value.
1105  *
1106  * This function is equivalent to running
1107  *     /sbin/tc qdisc del dev %s handle ffff: ingress
1108  * but it is much, much faster.
1109  */
1110 static int
1111 netdev_linux_remove_policing(struct netdev *netdev)
1112 {
1113     struct netdev_dev_linux *netdev_dev =
1114         netdev_dev_linux_cast(netdev_get_dev(netdev));
1115     const char *netdev_name = netdev_get_name(netdev);
1116
1117     struct ofpbuf request;
1118     struct ofpbuf *reply;
1119     struct tcmsg *tcmsg;
1120     struct nl_sock *rtnl_sock;
1121     int ifindex;
1122     int error;
1123
1124     error = get_ifindex(netdev, &ifindex);
1125     if (error) {
1126         return error;
1127     }
1128
1129     error = get_rtnl_sock(&rtnl_sock);
1130     if (error) {
1131         return error;
1132     }
1133
1134     ofpbuf_init(&request, 0);
1135     nl_msg_put_nlmsghdr(&request, rtnl_sock, sizeof *tcmsg,
1136                         RTM_DELQDISC, NLM_F_REQUEST);
1137     tcmsg = ofpbuf_put_zeros(&request, sizeof *tcmsg);
1138     tcmsg->tcm_family = AF_UNSPEC;
1139     tcmsg->tcm_ifindex = ifindex;
1140     tcmsg->tcm_handle = 0xffff0000;
1141     tcmsg->tcm_parent = TC_H_INGRESS;
1142     nl_msg_put_string(&request, TCA_KIND, "ingress");
1143     nl_msg_put_unspec(&request, TCA_OPTIONS, NULL, 0);
1144     error = nl_sock_transact(rtnl_sock, &request, &reply);
1145     ofpbuf_uninit(&request);
1146     ofpbuf_delete(reply);
1147     if (error && error != ENOENT && error != EINVAL) {
1148         VLOG_WARN_RL(&rl, "%s: removing policing failed: %s",
1149                      netdev_name, strerror(error));
1150         return error;
1151     }
1152
1153     netdev_dev->kbits_rate = 0;
1154     netdev_dev->kbits_burst = 0;
1155     netdev_dev->cache_valid |= VALID_POLICING;
1156     return 0;
1157 }
1158
1159 /* Attempts to set input rate limiting (policing) policy. */
1160 static int
1161 netdev_linux_set_policing(struct netdev *netdev,
1162                           uint32_t kbits_rate, uint32_t kbits_burst)
1163 {
1164     struct netdev_dev_linux *netdev_dev =
1165         netdev_dev_linux_cast(netdev_get_dev(netdev));
1166     const char *netdev_name = netdev_get_name(netdev);
1167     char command[1024];
1168
1169     COVERAGE_INC(netdev_set_policing);
1170
1171     kbits_burst = (!kbits_rate ? 0       /* Force to 0 if no rate specified. */
1172                    : !kbits_burst ? 1000 /* Default to 1000 kbits if 0. */
1173                    : kbits_burst);       /* Stick with user-specified value. */
1174
1175     if (netdev_dev->cache_valid & VALID_POLICING
1176         && netdev_dev->kbits_rate == kbits_rate
1177         && netdev_dev->kbits_burst == kbits_burst) {
1178         /* Assume that settings haven't changed since we last set them. */
1179         return 0;
1180     }
1181
1182     netdev_linux_remove_policing(netdev);
1183     if (kbits_rate) {
1184         snprintf(command, sizeof(command), POLICE_ADD_CMD, netdev_name);
1185         if (system(command) != 0) {
1186             VLOG_WARN_RL(&rl, "%s: problem adding policing", netdev_name);
1187             return -1;
1188         }
1189
1190         snprintf(command, sizeof(command), POLICE_CONFIG_CMD, netdev_name,
1191                 kbits_rate, kbits_burst);
1192         if (system(command) != 0) {
1193             VLOG_WARN_RL(&rl, "%s: problem configuring policing",
1194                     netdev_name);
1195             return -1;
1196         }
1197
1198         netdev_dev->kbits_rate = kbits_rate;
1199         netdev_dev->kbits_burst = kbits_burst;
1200         netdev_dev->cache_valid |= VALID_POLICING;
1201     }
1202
1203     return 0;
1204 }
1205
1206 static int
1207 netdev_linux_get_in4(const struct netdev *netdev_,
1208                      struct in_addr *address, struct in_addr *netmask)
1209 {
1210     struct netdev_dev_linux *netdev_dev =
1211                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
1212
1213     if (!(netdev_dev->cache_valid & VALID_IN4)) {
1214         int error;
1215
1216         error = netdev_linux_get_ipv4(netdev_, &netdev_dev->address,
1217                                       SIOCGIFADDR, "SIOCGIFADDR");
1218         if (error) {
1219             return error;
1220         }
1221
1222         error = netdev_linux_get_ipv4(netdev_, &netdev_dev->netmask,
1223                                       SIOCGIFNETMASK, "SIOCGIFNETMASK");
1224         if (error) {
1225             return error;
1226         }
1227
1228         netdev_dev->cache_valid |= VALID_IN4;
1229     }
1230     *address = netdev_dev->address;
1231     *netmask = netdev_dev->netmask;
1232     return address->s_addr == INADDR_ANY ? EADDRNOTAVAIL : 0;
1233 }
1234
1235 static int
1236 netdev_linux_set_in4(struct netdev *netdev_, struct in_addr address,
1237                      struct in_addr netmask)
1238 {
1239     struct netdev_dev_linux *netdev_dev =
1240                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
1241     int error;
1242
1243     error = do_set_addr(netdev_, SIOCSIFADDR, "SIOCSIFADDR", address);
1244     if (!error) {
1245         netdev_dev->cache_valid |= VALID_IN4;
1246         netdev_dev->address = address;
1247         netdev_dev->netmask = netmask;
1248         if (address.s_addr != INADDR_ANY) {
1249             error = do_set_addr(netdev_, SIOCSIFNETMASK,
1250                                 "SIOCSIFNETMASK", netmask);
1251         }
1252     }
1253     return error;
1254 }
1255
1256 static bool
1257 parse_if_inet6_line(const char *line,
1258                     struct in6_addr *in6, char ifname[16 + 1])
1259 {
1260     uint8_t *s6 = in6->s6_addr;
1261 #define X8 "%2"SCNx8
1262     return sscanf(line,
1263                   " "X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8
1264                   "%*x %*x %*x %*x %16s\n",
1265                   &s6[0], &s6[1], &s6[2], &s6[3],
1266                   &s6[4], &s6[5], &s6[6], &s6[7],
1267                   &s6[8], &s6[9], &s6[10], &s6[11],
1268                   &s6[12], &s6[13], &s6[14], &s6[15],
1269                   ifname) == 17;
1270 }
1271
1272 /* If 'netdev' has an assigned IPv6 address, sets '*in6' to that address (if
1273  * 'in6' is non-null) and returns true.  Otherwise, returns false. */
1274 static int
1275 netdev_linux_get_in6(const struct netdev *netdev_, struct in6_addr *in6)
1276 {
1277     struct netdev_dev_linux *netdev_dev =
1278                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
1279     if (!(netdev_dev->cache_valid & VALID_IN6)) {
1280         FILE *file;
1281         char line[128];
1282
1283         netdev_dev->in6 = in6addr_any;
1284
1285         file = fopen("/proc/net/if_inet6", "r");
1286         if (file != NULL) {
1287             const char *name = netdev_get_name(netdev_);
1288             while (fgets(line, sizeof line, file)) {
1289                 struct in6_addr in6;
1290                 char ifname[16 + 1];
1291                 if (parse_if_inet6_line(line, &in6, ifname)
1292                     && !strcmp(name, ifname))
1293                 {
1294                     netdev_dev->in6 = in6;
1295                     break;
1296                 }
1297             }
1298             fclose(file);
1299         }
1300         netdev_dev->cache_valid |= VALID_IN6;
1301     }
1302     *in6 = netdev_dev->in6;
1303     return 0;
1304 }
1305
1306 static void
1307 make_in4_sockaddr(struct sockaddr *sa, struct in_addr addr)
1308 {
1309     struct sockaddr_in sin;
1310     memset(&sin, 0, sizeof sin);
1311     sin.sin_family = AF_INET;
1312     sin.sin_addr = addr;
1313     sin.sin_port = 0;
1314
1315     memset(sa, 0, sizeof *sa);
1316     memcpy(sa, &sin, sizeof sin);
1317 }
1318
1319 static int
1320 do_set_addr(struct netdev *netdev,
1321             int ioctl_nr, const char *ioctl_name, struct in_addr addr)
1322 {
1323     struct ifreq ifr;
1324     strncpy(ifr.ifr_name, netdev_get_name(netdev), sizeof ifr.ifr_name);
1325     make_in4_sockaddr(&ifr.ifr_addr, addr);
1326
1327     return netdev_linux_do_ioctl(netdev_get_name(netdev), &ifr, ioctl_nr,
1328                                  ioctl_name);
1329 }
1330
1331 /* Adds 'router' as a default IP gateway. */
1332 static int
1333 netdev_linux_add_router(struct netdev *netdev OVS_UNUSED, struct in_addr router)
1334 {
1335     struct in_addr any = { INADDR_ANY };
1336     struct rtentry rt;
1337     int error;
1338
1339     memset(&rt, 0, sizeof rt);
1340     make_in4_sockaddr(&rt.rt_dst, any);
1341     make_in4_sockaddr(&rt.rt_gateway, router);
1342     make_in4_sockaddr(&rt.rt_genmask, any);
1343     rt.rt_flags = RTF_UP | RTF_GATEWAY;
1344     COVERAGE_INC(netdev_add_router);
1345     error = ioctl(af_inet_sock, SIOCADDRT, &rt) < 0 ? errno : 0;
1346     if (error) {
1347         VLOG_WARN("ioctl(SIOCADDRT): %s", strerror(error));
1348     }
1349     return error;
1350 }
1351
1352 static int
1353 netdev_linux_get_next_hop(const struct in_addr *host, struct in_addr *next_hop,
1354                           char **netdev_name)
1355 {
1356     static const char fn[] = "/proc/net/route";
1357     FILE *stream;
1358     char line[256];
1359     int ln;
1360
1361     *netdev_name = NULL;
1362     stream = fopen(fn, "r");
1363     if (stream == NULL) {
1364         VLOG_WARN_RL(&rl, "%s: open failed: %s", fn, strerror(errno));
1365         return errno;
1366     }
1367
1368     ln = 0;
1369     while (fgets(line, sizeof line, stream)) {
1370         if (++ln >= 2) {
1371             char iface[17];
1372             uint32_t dest, gateway, mask;
1373             int refcnt, metric, mtu;
1374             unsigned int flags, use, window, irtt;
1375
1376             if (sscanf(line,
1377                        "%16s %"SCNx32" %"SCNx32" %04X %d %u %d %"SCNx32
1378                        " %d %u %u\n",
1379                        iface, &dest, &gateway, &flags, &refcnt,
1380                        &use, &metric, &mask, &mtu, &window, &irtt) != 11) {
1381
1382                 VLOG_WARN_RL(&rl, "%s: could not parse line %d: %s", 
1383                         fn, ln, line);
1384                 continue;
1385             }
1386             if (!(flags & RTF_UP)) {
1387                 /* Skip routes that aren't up. */
1388                 continue;
1389             }
1390
1391             /* The output of 'dest', 'mask', and 'gateway' were given in
1392              * network byte order, so we don't need need any endian 
1393              * conversions here. */
1394             if ((dest & mask) == (host->s_addr & mask)) {
1395                 if (!gateway) {
1396                     /* The host is directly reachable. */
1397                     next_hop->s_addr = 0;
1398                 } else {
1399                     /* To reach the host, we must go through a gateway. */
1400                     next_hop->s_addr = gateway;
1401                 }
1402                 *netdev_name = xstrdup(iface);
1403                 fclose(stream);
1404                 return 0;
1405             }
1406         }
1407     }
1408
1409     fclose(stream);
1410     return ENXIO;
1411 }
1412
1413 /* Looks up the ARP table entry for 'ip' on 'netdev'.  If one exists and can be
1414  * successfully retrieved, it stores the corresponding MAC address in 'mac' and
1415  * returns 0.  Otherwise, it returns a positive errno value; in particular,
1416  * ENXIO indicates that there is not ARP table entry for 'ip' on 'netdev'. */
1417 static int
1418 netdev_linux_arp_lookup(const struct netdev *netdev,
1419                         uint32_t ip, uint8_t mac[ETH_ADDR_LEN])
1420 {
1421     struct arpreq r;
1422     struct sockaddr_in sin;
1423     int retval;
1424
1425     memset(&r, 0, sizeof r);
1426     sin.sin_family = AF_INET;
1427     sin.sin_addr.s_addr = ip;
1428     sin.sin_port = 0;
1429     memcpy(&r.arp_pa, &sin, sizeof sin);
1430     r.arp_ha.sa_family = ARPHRD_ETHER;
1431     r.arp_flags = 0;
1432     strncpy(r.arp_dev, netdev_get_name(netdev), sizeof r.arp_dev);
1433     COVERAGE_INC(netdev_arp_lookup);
1434     retval = ioctl(af_inet_sock, SIOCGARP, &r) < 0 ? errno : 0;
1435     if (!retval) {
1436         memcpy(mac, r.arp_ha.sa_data, ETH_ADDR_LEN);
1437     } else if (retval != ENXIO) {
1438         VLOG_WARN_RL(&rl, "%s: could not look up ARP entry for "IP_FMT": %s",
1439                      netdev_get_name(netdev), IP_ARGS(&ip), strerror(retval));
1440     }
1441     return retval;
1442 }
1443
1444 static int
1445 nd_to_iff_flags(enum netdev_flags nd)
1446 {
1447     int iff = 0;
1448     if (nd & NETDEV_UP) {
1449         iff |= IFF_UP;
1450     }
1451     if (nd & NETDEV_PROMISC) {
1452         iff |= IFF_PROMISC;
1453     }
1454     return iff;
1455 }
1456
1457 static int
1458 iff_to_nd_flags(int iff)
1459 {
1460     enum netdev_flags nd = 0;
1461     if (iff & IFF_UP) {
1462         nd |= NETDEV_UP;
1463     }
1464     if (iff & IFF_PROMISC) {
1465         nd |= NETDEV_PROMISC;
1466     }
1467     return nd;
1468 }
1469
1470 static int
1471 netdev_linux_update_flags(struct netdev *netdev, enum netdev_flags off,
1472                           enum netdev_flags on, enum netdev_flags *old_flagsp)
1473 {
1474     int old_flags, new_flags;
1475     int error;
1476
1477     error = get_flags(netdev, &old_flags);
1478     if (!error) {
1479         *old_flagsp = iff_to_nd_flags(old_flags);
1480         new_flags = (old_flags & ~nd_to_iff_flags(off)) | nd_to_iff_flags(on);
1481         if (new_flags != old_flags) {
1482             error = set_flags(netdev, new_flags);
1483         }
1484     }
1485     return error;
1486 }
1487
1488 static void
1489 poll_notify(struct list *list)
1490 {
1491     struct netdev_linux_notifier *notifier;
1492     LIST_FOR_EACH (notifier, struct netdev_linux_notifier, node, list) {
1493         struct netdev_notifier *n = &notifier->notifier;
1494         n->cb(n);
1495     }
1496 }
1497
1498 static void
1499 netdev_linux_poll_cb(const struct rtnetlink_change *change,
1500                      void *aux OVS_UNUSED)
1501 {
1502     if (change) {
1503         struct list *list = shash_find_data(&netdev_linux_notifiers,
1504                                             change->ifname);
1505         if (list) {
1506             poll_notify(list);
1507         }
1508     } else {
1509         struct shash_node *node;
1510         SHASH_FOR_EACH (node, &netdev_linux_notifiers) {
1511             poll_notify(node->data);
1512         }
1513     }
1514 }
1515
1516 static int
1517 netdev_linux_poll_add(struct netdev *netdev,
1518                       void (*cb)(struct netdev_notifier *), void *aux,
1519                       struct netdev_notifier **notifierp)
1520 {
1521     const char *netdev_name = netdev_get_name(netdev);
1522     struct netdev_linux_notifier *notifier;
1523     struct list *list;
1524
1525     if (shash_is_empty(&netdev_linux_notifiers)) {
1526         int error = rtnetlink_notifier_register(&netdev_linux_poll_notifier,
1527                                                    netdev_linux_poll_cb, NULL);
1528         if (error) {
1529             return error;
1530         }
1531     }
1532
1533     list = shash_find_data(&netdev_linux_notifiers, netdev_name);
1534     if (!list) {
1535         list = xmalloc(sizeof *list);
1536         list_init(list);
1537         shash_add(&netdev_linux_notifiers, netdev_name, list);
1538     }
1539
1540     notifier = xmalloc(sizeof *notifier);
1541     netdev_notifier_init(&notifier->notifier, netdev, cb, aux);
1542     list_push_back(list, &notifier->node);
1543     *notifierp = &notifier->notifier;
1544     return 0;
1545 }
1546
1547 static void
1548 netdev_linux_poll_remove(struct netdev_notifier *notifier_)
1549 {
1550     struct netdev_linux_notifier *notifier =
1551         CONTAINER_OF(notifier_, struct netdev_linux_notifier, notifier);
1552     struct list *list;
1553
1554     /* Remove 'notifier' from its list. */
1555     list = list_remove(&notifier->node);
1556     if (list_is_empty(list)) {
1557         /* The list is now empty.  Remove it from the hash and free it. */
1558         const char *netdev_name = netdev_get_name(notifier->notifier.netdev);
1559         shash_delete(&netdev_linux_notifiers,
1560                      shash_find(&netdev_linux_notifiers, netdev_name));
1561         free(list);
1562     }
1563     free(notifier);
1564
1565     /* If that was the last notifier, unregister. */
1566     if (shash_is_empty(&netdev_linux_notifiers)) {
1567         rtnetlink_notifier_unregister(&netdev_linux_poll_notifier);
1568     }
1569 }
1570
1571 const struct netdev_class netdev_linux_class = {
1572     "system",
1573
1574     netdev_linux_init,
1575     netdev_linux_run,
1576     netdev_linux_wait,
1577
1578     netdev_linux_create_system,
1579     netdev_linux_destroy,
1580     NULL,                       /* reconfigure */
1581
1582     netdev_linux_open,
1583     netdev_linux_close,
1584
1585     netdev_linux_enumerate,
1586
1587     netdev_linux_recv,
1588     netdev_linux_recv_wait,
1589     netdev_linux_drain,
1590
1591     netdev_linux_send,
1592     netdev_linux_send_wait,
1593
1594     netdev_linux_set_etheraddr,
1595     netdev_linux_get_etheraddr,
1596     netdev_linux_get_mtu,
1597     netdev_linux_get_ifindex,
1598     netdev_linux_get_carrier,
1599     netdev_linux_get_stats,
1600     netdev_vport_set_stats,
1601
1602     netdev_linux_get_features,
1603     netdev_linux_set_advertisements,
1604     netdev_linux_get_vlan_vid,
1605     netdev_linux_set_policing,
1606
1607     netdev_linux_get_in4,
1608     netdev_linux_set_in4,
1609     netdev_linux_get_in6,
1610     netdev_linux_add_router,
1611     netdev_linux_get_next_hop,
1612     netdev_linux_arp_lookup,
1613
1614     netdev_linux_update_flags,
1615
1616     netdev_linux_poll_add,
1617     netdev_linux_poll_remove,
1618 };
1619
1620 const struct netdev_class netdev_tap_class = {
1621     "tap",
1622
1623     netdev_linux_init,
1624     netdev_linux_run,
1625     netdev_linux_wait,
1626
1627     netdev_linux_create_tap,
1628     netdev_linux_destroy,
1629     NULL,                       /* reconfigure */
1630
1631     netdev_linux_open,
1632     netdev_linux_close,
1633
1634     NULL,                       /* enumerate */
1635
1636     netdev_linux_recv,
1637     netdev_linux_recv_wait,
1638     netdev_linux_drain,
1639
1640     netdev_linux_send,
1641     netdev_linux_send_wait,
1642
1643     netdev_linux_set_etheraddr,
1644     netdev_linux_get_etheraddr,
1645     netdev_linux_get_mtu,
1646     netdev_linux_get_ifindex,
1647     netdev_linux_get_carrier,
1648     netdev_linux_get_stats,
1649     NULL,                       /* set_stats */
1650
1651     netdev_linux_get_features,
1652     netdev_linux_set_advertisements,
1653     netdev_linux_get_vlan_vid,
1654     netdev_linux_set_policing,
1655
1656     netdev_linux_get_in4,
1657     netdev_linux_set_in4,
1658     netdev_linux_get_in6,
1659     netdev_linux_add_router,
1660     netdev_linux_get_next_hop,
1661     netdev_linux_arp_lookup,
1662
1663     netdev_linux_update_flags,
1664
1665     netdev_linux_poll_add,
1666     netdev_linux_poll_remove,
1667 };
1668
1669 \f
1670 static int
1671 get_stats_via_netlink(int ifindex, struct netdev_stats *stats)
1672 {
1673     /* Policy for RTNLGRP_LINK messages.
1674      *
1675      * There are *many* more fields in these messages, but currently we only
1676      * care about these fields. */
1677     static const struct nl_policy rtnlgrp_link_policy[] = {
1678         [IFLA_IFNAME] = { .type = NL_A_STRING, .optional = false },
1679         [IFLA_STATS] = { .type = NL_A_UNSPEC, .optional = true,
1680                          .min_len = sizeof(struct rtnl_link_stats) },
1681     };
1682
1683     struct nl_sock *rtnl_sock;
1684     struct ofpbuf request;
1685     struct ofpbuf *reply;
1686     struct ifinfomsg *ifi;
1687     const struct rtnl_link_stats *rtnl_stats;
1688     struct nlattr *attrs[ARRAY_SIZE(rtnlgrp_link_policy)];
1689     int error;
1690
1691     error = get_rtnl_sock(&rtnl_sock);
1692     if (error) {
1693         return error;
1694     }
1695
1696     ofpbuf_init(&request, 0);
1697     nl_msg_put_nlmsghdr(&request, rtnl_sock, sizeof *ifi,
1698                         RTM_GETLINK, NLM_F_REQUEST);
1699     ifi = ofpbuf_put_zeros(&request, sizeof *ifi);
1700     ifi->ifi_family = PF_UNSPEC;
1701     ifi->ifi_index = ifindex;
1702     error = nl_sock_transact(rtnl_sock, &request, &reply);
1703     ofpbuf_uninit(&request);
1704     if (error) {
1705         return error;
1706     }
1707
1708     if (!nl_policy_parse(reply, NLMSG_HDRLEN + sizeof(struct ifinfomsg),
1709                          rtnlgrp_link_policy,
1710                          attrs, ARRAY_SIZE(rtnlgrp_link_policy))) {
1711         ofpbuf_delete(reply);
1712         return EPROTO;
1713     }
1714
1715     if (!attrs[IFLA_STATS]) {
1716         VLOG_WARN_RL(&rl, "RTM_GETLINK reply lacks stats");
1717         ofpbuf_delete(reply);
1718         return EPROTO;
1719     }
1720
1721     rtnl_stats = nl_attr_get(attrs[IFLA_STATS]);
1722     stats->rx_packets = rtnl_stats->rx_packets;
1723     stats->tx_packets = rtnl_stats->tx_packets;
1724     stats->rx_bytes = rtnl_stats->rx_bytes;
1725     stats->tx_bytes = rtnl_stats->tx_bytes;
1726     stats->rx_errors = rtnl_stats->rx_errors;
1727     stats->tx_errors = rtnl_stats->tx_errors;
1728     stats->rx_dropped = rtnl_stats->rx_dropped;
1729     stats->tx_dropped = rtnl_stats->tx_dropped;
1730     stats->multicast = rtnl_stats->multicast;
1731     stats->collisions = rtnl_stats->collisions;
1732     stats->rx_length_errors = rtnl_stats->rx_length_errors;
1733     stats->rx_over_errors = rtnl_stats->rx_over_errors;
1734     stats->rx_crc_errors = rtnl_stats->rx_crc_errors;
1735     stats->rx_frame_errors = rtnl_stats->rx_frame_errors;
1736     stats->rx_fifo_errors = rtnl_stats->rx_fifo_errors;
1737     stats->rx_missed_errors = rtnl_stats->rx_missed_errors;
1738     stats->tx_aborted_errors = rtnl_stats->tx_aborted_errors;
1739     stats->tx_carrier_errors = rtnl_stats->tx_carrier_errors;
1740     stats->tx_fifo_errors = rtnl_stats->tx_fifo_errors;
1741     stats->tx_heartbeat_errors = rtnl_stats->tx_heartbeat_errors;
1742     stats->tx_window_errors = rtnl_stats->tx_window_errors;
1743
1744     ofpbuf_delete(reply);
1745
1746     return 0;
1747 }
1748
1749 static int
1750 get_stats_via_proc(const char *netdev_name, struct netdev_stats *stats)
1751 {
1752     static const char fn[] = "/proc/net/dev";
1753     char line[1024];
1754     FILE *stream;
1755     int ln;
1756
1757     stream = fopen(fn, "r");
1758     if (!stream) {
1759         VLOG_WARN_RL(&rl, "%s: open failed: %s", fn, strerror(errno));
1760         return errno;
1761     }
1762
1763     ln = 0;
1764     while (fgets(line, sizeof line, stream)) {
1765         if (++ln >= 3) {
1766             char devname[16];
1767 #define X64 "%"SCNu64
1768             if (sscanf(line,
1769                        " %15[^:]:"
1770                        X64 X64 X64 X64 X64 X64 X64 "%*u"
1771                        X64 X64 X64 X64 X64 X64 X64 "%*u",
1772                        devname,
1773                        &stats->rx_bytes,
1774                        &stats->rx_packets,
1775                        &stats->rx_errors,
1776                        &stats->rx_dropped,
1777                        &stats->rx_fifo_errors,
1778                        &stats->rx_frame_errors,
1779                        &stats->multicast,
1780                        &stats->tx_bytes,
1781                        &stats->tx_packets,
1782                        &stats->tx_errors,
1783                        &stats->tx_dropped,
1784                        &stats->tx_fifo_errors,
1785                        &stats->collisions,
1786                        &stats->tx_carrier_errors) != 15) {
1787                 VLOG_WARN_RL(&rl, "%s:%d: parse error", fn, ln);
1788             } else if (!strcmp(devname, netdev_name)) {
1789                 stats->rx_length_errors = UINT64_MAX;
1790                 stats->rx_over_errors = UINT64_MAX;
1791                 stats->rx_crc_errors = UINT64_MAX;
1792                 stats->rx_missed_errors = UINT64_MAX;
1793                 stats->tx_aborted_errors = UINT64_MAX;
1794                 stats->tx_heartbeat_errors = UINT64_MAX;
1795                 stats->tx_window_errors = UINT64_MAX;
1796                 fclose(stream);
1797                 return 0;
1798             }
1799         }
1800     }
1801     VLOG_WARN_RL(&rl, "%s: no stats for %s", fn, netdev_name);
1802     fclose(stream);
1803     return ENODEV;
1804 }
1805 \f
1806 static int
1807 get_flags(const struct netdev *netdev, int *flags)
1808 {
1809     struct ifreq ifr;
1810     int error;
1811
1812     error = netdev_linux_do_ioctl(netdev_get_name(netdev), &ifr, SIOCGIFFLAGS,
1813                                   "SIOCGIFFLAGS");
1814     *flags = ifr.ifr_flags;
1815     return error;
1816 }
1817
1818 static int
1819 set_flags(struct netdev *netdev, int flags)
1820 {
1821     struct ifreq ifr;
1822
1823     ifr.ifr_flags = flags;
1824     return netdev_linux_do_ioctl(netdev_get_name(netdev), &ifr, SIOCSIFFLAGS,
1825                                  "SIOCSIFFLAGS");
1826 }
1827
1828 static int
1829 do_get_ifindex(const char *netdev_name)
1830 {
1831     struct ifreq ifr;
1832
1833     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
1834     COVERAGE_INC(netdev_get_ifindex);
1835     if (ioctl(af_inet_sock, SIOCGIFINDEX, &ifr) < 0) {
1836         VLOG_WARN_RL(&rl, "ioctl(SIOCGIFINDEX) on %s device failed: %s",
1837                      netdev_name, strerror(errno));
1838         return -errno;
1839     }
1840     return ifr.ifr_ifindex;
1841 }
1842
1843 static int
1844 get_ifindex(const struct netdev *netdev_, int *ifindexp)
1845 {
1846     struct netdev_dev_linux *netdev_dev =
1847                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
1848     *ifindexp = 0;
1849     if (!(netdev_dev->cache_valid & VALID_IFINDEX)) {
1850         int ifindex = do_get_ifindex(netdev_get_name(netdev_));
1851         if (ifindex < 0) {
1852             return -ifindex;
1853         }
1854         netdev_dev->cache_valid |= VALID_IFINDEX;
1855         netdev_dev->ifindex = ifindex;
1856     }
1857     *ifindexp = netdev_dev->ifindex;
1858     return 0;
1859 }
1860
1861 static int
1862 get_etheraddr(const char *netdev_name, uint8_t ea[ETH_ADDR_LEN])
1863 {
1864     struct ifreq ifr;
1865     int hwaddr_family;
1866
1867     memset(&ifr, 0, sizeof ifr);
1868     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
1869     COVERAGE_INC(netdev_get_hwaddr);
1870     if (ioctl(af_inet_sock, SIOCGIFHWADDR, &ifr) < 0) {
1871         VLOG_ERR("ioctl(SIOCGIFHWADDR) on %s device failed: %s",
1872                  netdev_name, strerror(errno));
1873         return errno;
1874     }
1875     hwaddr_family = ifr.ifr_hwaddr.sa_family;
1876     if (hwaddr_family != AF_UNSPEC && hwaddr_family != ARPHRD_ETHER) {
1877         VLOG_WARN("%s device has unknown hardware address family %d",
1878                   netdev_name, hwaddr_family);
1879     }
1880     memcpy(ea, ifr.ifr_hwaddr.sa_data, ETH_ADDR_LEN);
1881     return 0;
1882 }
1883
1884 static int
1885 set_etheraddr(const char *netdev_name, int hwaddr_family,
1886               const uint8_t mac[ETH_ADDR_LEN])
1887 {
1888     struct ifreq ifr;
1889
1890     memset(&ifr, 0, sizeof ifr);
1891     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
1892     ifr.ifr_hwaddr.sa_family = hwaddr_family;
1893     memcpy(ifr.ifr_hwaddr.sa_data, mac, ETH_ADDR_LEN);
1894     COVERAGE_INC(netdev_set_hwaddr);
1895     if (ioctl(af_inet_sock, SIOCSIFHWADDR, &ifr) < 0) {
1896         VLOG_ERR("ioctl(SIOCSIFHWADDR) on %s device failed: %s",
1897                  netdev_name, strerror(errno));
1898         return errno;
1899     }
1900     return 0;
1901 }
1902
1903 static int
1904 netdev_linux_do_ethtool(const char *name, struct ethtool_cmd *ecmd,
1905                         int cmd, const char *cmd_name)
1906 {
1907     struct ifreq ifr;
1908
1909     memset(&ifr, 0, sizeof ifr);
1910     strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
1911     ifr.ifr_data = (caddr_t) ecmd;
1912
1913     ecmd->cmd = cmd;
1914     COVERAGE_INC(netdev_ethtool);
1915     if (ioctl(af_inet_sock, SIOCETHTOOL, &ifr) == 0) {
1916         return 0;
1917     } else {
1918         if (errno != EOPNOTSUPP) {
1919             VLOG_WARN_RL(&rl, "ethtool command %s on network device %s "
1920                          "failed: %s", cmd_name, name, strerror(errno));
1921         } else {
1922             /* The device doesn't support this operation.  That's pretty
1923              * common, so there's no point in logging anything. */
1924         }
1925         return errno;
1926     }
1927 }
1928
1929 static int
1930 netdev_linux_do_ioctl(const char *name, struct ifreq *ifr, int cmd,
1931                       const char *cmd_name)
1932 {
1933     strncpy(ifr->ifr_name, name, sizeof ifr->ifr_name);
1934     if (ioctl(af_inet_sock, cmd, ifr) == -1) {
1935         VLOG_DBG_RL(&rl, "%s: ioctl(%s) failed: %s", name, cmd_name,
1936                      strerror(errno));
1937         return errno;
1938     }
1939     return 0;
1940 }
1941
1942 static int
1943 netdev_linux_get_ipv4(const struct netdev *netdev, struct in_addr *ip,
1944                       int cmd, const char *cmd_name)
1945 {
1946     struct ifreq ifr;
1947     int error;
1948
1949     ifr.ifr_addr.sa_family = AF_INET;
1950     error = netdev_linux_do_ioctl(netdev_get_name(netdev), &ifr, cmd, cmd_name);
1951     if (!error) {
1952         const struct sockaddr_in *sin = (struct sockaddr_in *) &ifr.ifr_addr;
1953         *ip = sin->sin_addr;
1954     }
1955     return error;
1956 }
1957
1958 /* Obtains a Netlink routing socket that is not subscribed to any multicast
1959  * groups.  Returns 0 if successful, otherwise a positive errno value.  Stores
1960  * the socket in '*rtnl_sockp' if successful, otherwise a null pointer. */
1961 static int
1962 get_rtnl_sock(struct nl_sock **rtnl_sockp)
1963 {
1964     static struct nl_sock *sock;
1965     int error;
1966
1967     if (!sock) {
1968         error = nl_sock_create(NETLINK_ROUTE, 0, 0, 0, &sock);
1969         if (error) {
1970             VLOG_ERR_RL(&rl, "failed to create rtnetlink socket: %s",
1971                         strerror(error));
1972         }
1973     } else {
1974         error = 0;
1975     }
1976
1977     *rtnl_sockp = sock;
1978     return error;
1979 }