1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
4 * We are making the OpenFlow specification and associated documentation
5 * (Software) available for public use and benefit with the expectation
6 * that others will use, modify and enhance the Software and contribute
7 * those enhancements back to the community. However, since we would
8 * like to make the Software available for broadest use, with as few
9 * restrictions as possible permission is hereby granted, free of
10 * charge, to any person obtaining a copy of this Software to deal in
11 * the Software under the copyrights without restriction, including
12 * without limitation the rights to use, copy, modify, merge, publish,
13 * distribute, sublicense, and/or sell copies of the Software, and to
14 * permit persons to whom the Software is furnished to do so, subject to
15 * the following conditions:
17 * The above copyright notice and this permission notice shall be
18 * included in all copies or substantial portions of the Software.
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
24 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 * The name and trademarks of copyright holder(s) may NOT be used in
30 * advertising or publicity pertaining to the Software or any
31 * derivatives without specific, written prior permission.
38 #include <arpa/inet.h>
40 #include <linux/types.h>
41 #include <linux/ethtool.h>
42 #include <linux/sockios.h>
43 #include <sys/types.h>
44 #include <sys/ioctl.h>
45 #include <sys/socket.h>
46 #include <netpacket/packet.h>
47 #include <net/ethernet.h>
49 #include <net/if_arp.h>
50 #include <net/if_packet.h>
51 #include <netinet/in.h>
57 #include "fatal-signal.h"
61 #include "poll-loop.h"
63 #define THIS_MODULE VLM_netdev
70 uint8_t etheraddr[ETH_ADDR_LEN];
79 static struct list netdev_list = LIST_INITIALIZER(&netdev_list);
81 /* An AF_INET socket (used for ioctl operations). */
82 static int af_inet_sock = -1;
84 static void init_netdev(void);
85 static int restore_flags(struct netdev *netdev);
86 static int get_flags(const struct netdev *, int *flagsp);
87 static int set_flags(struct netdev *, int flags);
89 /* Obtains the IPv4 address for 'name' into 'in4'. Returns true if
92 get_ipv4_address(const char *name, struct in_addr *in4)
96 strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
97 ifr.ifr_addr.sa_family = AF_INET;
98 if (ioctl(af_inet_sock, SIOCGIFADDR, &ifr) == 0) {
99 struct sockaddr_in *sin = (struct sockaddr_in *) &ifr.ifr_addr;
100 *in4 = sin->sin_addr;
102 in4->s_addr = INADDR_ANY;
108 /* Obtains the IPv6 address for 'name' into 'in6'. */
110 get_ipv6_address(const char *name, struct in6_addr *in6)
115 file = fopen("/proc/net/if_inet6", "r");
117 /* This most likely indicates that the host doesn't have IPv6 support,
118 * so it's not really a failure condition.*/
123 while (fgets(line, sizeof line, file)) {
124 uint8_t *s6 = in6->s6_addr;
128 if (sscanf(line, " "X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8
129 "%*x %*x %*x %*x %16s\n",
130 &s6[0], &s6[1], &s6[2], &s6[3],
131 &s6[4], &s6[5], &s6[6], &s6[7],
132 &s6[8], &s6[9], &s6[10], &s6[11],
133 &s6[12], &s6[13], &s6[14], &s6[15],
135 && !strcmp(name, ifname))
146 do_ethtool(struct netdev *netdev)
149 struct ethtool_cmd ecmd;
152 netdev->features = 0;
154 memset(&ifr, 0, sizeof ifr);
155 strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
156 ifr.ifr_data = (caddr_t) &ecmd;
158 memset(&ecmd, 0, sizeof ecmd);
159 ecmd.cmd = ETHTOOL_GSET;
160 if (ioctl(netdev->fd, SIOCETHTOOL, &ifr) == 0) {
161 if (ecmd.supported & SUPPORTED_10baseT_Half) {
162 netdev->features |= OFPPF_10MB_HD;
164 if (ecmd.supported & SUPPORTED_10baseT_Full) {
165 netdev->features |= OFPPF_10MB_FD;
167 if (ecmd.supported & SUPPORTED_100baseT_Half) {
168 netdev->features |= OFPPF_100MB_HD;
170 if (ecmd.supported & SUPPORTED_100baseT_Full) {
171 netdev->features |= OFPPF_100MB_FD;
173 if (ecmd.supported & SUPPORTED_1000baseT_Half) {
174 netdev->features |= OFPPF_1GB_HD;
176 if (ecmd.supported & SUPPORTED_1000baseT_Full) {
177 netdev->features |= OFPPF_1GB_FD;
179 /* 10Gbps half-duplex doesn't exist... */
180 if (ecmd.supported & SUPPORTED_10000baseT_Full) {
181 netdev->features |= OFPPF_10GB_FD;
184 switch (ecmd.speed) {
194 netdev->speed = 1000;
198 netdev->speed = 2500;
202 netdev->speed = 10000;
206 VLOG_DBG("ioctl(SIOCETHTOOL) failed: %s", strerror(errno));
210 /* Opens the network device named 'name' (e.g. "eth0") and returns zero if
211 * successful, otherwise a positive errno value. On success, sets '*netdev'
212 * to the new network device, otherwise to null. */
214 netdev_open(const char *name, struct netdev **netdev_)
219 unsigned int ifindex;
220 socklen_t rcvbuf_len;
222 uint8_t etheraddr[ETH_ADDR_LEN];
227 struct netdev *netdev;
232 /* Create raw socket.
234 * We have to use SOCK_PACKET, despite its deprecation, because only
235 * SOCK_PACKET lets us set the hardware source address of outgoing
237 fd = socket(PF_PACKET, SOCK_PACKET, htons(ETH_P_ALL));
242 /* Bind to specific ethernet device. */
243 memset(&sa, 0, sizeof sa);
244 sa.sa_family = AF_UNSPEC;
245 strncpy((char *) sa.sa_data, name, sizeof sa.sa_data);
246 if (bind(fd, &sa, sizeof sa) < 0) {
247 VLOG_ERR("bind to %s failed: %s", name, strerror(errno));
251 /* Between the socket() and bind() calls above, the socket receives all
252 * packets on all system interfaces. We do not want to receive that
253 * data, but there is no way to avoid it. So we must now drain out the
254 * receive queue. There is no way to know how long the receive queue is,
255 * but we know that the total number of bytes queued does not exceed the
256 * receive buffer size, so we pull packets until none are left or we've
257 * read that many bytes. */
258 rcvbuf_len = sizeof rcvbuf;
259 if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, &rcvbuf_len) < 0) {
260 VLOG_ERR("getsockopt(SO_RCVBUF) on %s device failed: %s",
261 name, strerror(errno));
266 ssize_t n_bytes = recv(fd, &buffer, 1, MSG_TRUNC | MSG_DONTWAIT);
273 /* Get ethernet device index. */
274 strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
275 if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0) {
276 VLOG_ERR("ioctl(SIOCGIFINDEX) on %s device failed: %s",
277 name, strerror(errno));
280 ifindex = ifr.ifr_ifindex;
282 /* Get MAC address. */
283 if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) {
284 VLOG_ERR("ioctl(SIOCGIFHWADDR) on %s device failed: %s",
285 name, strerror(errno));
288 if (ifr.ifr_hwaddr.sa_family != AF_UNSPEC
289 && ifr.ifr_hwaddr.sa_family != ARPHRD_ETHER) {
290 VLOG_WARN("%s device has unknown hardware address family %d",
291 name, (int) ifr.ifr_hwaddr.sa_family);
293 memcpy(etheraddr, ifr.ifr_hwaddr.sa_data, sizeof etheraddr);
296 if (ioctl(fd, SIOCGIFMTU, &ifr) < 0) {
297 VLOG_ERR("ioctl(SIOCGIFMTU) on %s device failed: %s",
298 name, strerror(errno));
303 if (!get_ipv4_address(name, &in4)) {
306 get_ipv6_address(name, &in6);
308 /* Allocate network device. */
309 netdev = xmalloc(sizeof *netdev);
310 netdev->name = xstrdup(name);
312 memcpy(netdev->etheraddr, etheraddr, sizeof etheraddr);
317 /* Get speed, features. */
320 /* Save flags to restore at close or exit. */
321 error = get_flags(netdev, &netdev->save_flags);
325 fatal_signal_block();
326 list_push_back(&netdev_list, &netdev->node);
327 fatal_signal_unblock();
340 /* Closes and destroys 'netdev'. */
342 netdev_close(struct netdev *netdev)
345 /* Bring down interface and drop promiscuous mode, if we brought up
346 * the interface or enabled promiscuous mode. */
348 fatal_signal_block();
349 error = restore_flags(netdev);
350 list_remove(&netdev->node);
351 fatal_signal_unblock();
353 VLOG_WARN("failed to restore network device flags on %s: %s",
354 netdev->name, strerror(error));
364 /* Pads 'buffer' out with zero-bytes to the minimum valid length of an
365 * Ethernet packet, if necessary. */
367 pad_to_minimum_length(struct buffer *buffer)
369 if (buffer->size < ETH_TOTAL_MIN) {
370 size_t shortage = ETH_TOTAL_MIN - buffer->size;
371 memset(buffer_put_uninit(buffer, shortage), 0, shortage);
375 /* Attempts to receive a packet from 'netdev' into 'buffer', which the caller
376 * must have initialized with sufficient room for the packet. The space
377 * required to receive any packet is ETH_HEADER_LEN bytes, plus VLAN_HEADER_LEN
378 * bytes, plus the device's MTU (which may be retrieved via netdev_get_mtu()).
379 * (Some devices do not allow for a VLAN header, in which case VLAN_HEADER_LEN
380 * need not be included.)
382 * If a packet is successfully retrieved, returns 0. In this case 'buffer' is
383 * guaranteed to contain at least ETH_TOTAL_MIN bytes. Otherwise, returns a
384 * positive errno value. Returns EAGAIN immediately if no packet is ready to
388 netdev_recv(struct netdev *netdev, struct buffer *buffer)
392 assert(buffer->size == 0);
393 assert(buffer_tailroom(buffer) >= ETH_TOTAL_MIN);
395 n_bytes = recv(netdev->fd,
396 buffer_tail(buffer), buffer_tailroom(buffer),
398 } while (n_bytes < 0 && errno == EINTR);
400 if (errno != EAGAIN) {
401 VLOG_WARN("error receiving Ethernet packet on %s: %s",
402 strerror(errno), netdev->name);
406 buffer->size += n_bytes;
408 /* When the kernel internally sends out an Ethernet frame on an
409 * interface, it gives us a copy *before* padding the frame to the
410 * minimum length. Thus, when it sends out something like an ARP
411 * request, we see a too-short frame. So pad it out to the minimum
413 pad_to_minimum_length(buffer);
418 /* Registers with the poll loop to wake up from the next call to poll_block()
419 * when a packet is ready to be received with netdev_recv() on 'netdev'. */
421 netdev_recv_wait(struct netdev *netdev)
423 poll_fd_wait(netdev->fd, POLLIN);
426 /* Sends 'buffer' on 'netdev'. Returns 0 if successful, otherwise a positive
427 * errno value. Returns EAGAIN without blocking if the packet cannot be queued
428 * immediately. Returns EMSGSIZE if a partial packet was transmitted or if
429 * the packet is too big or too small to transmit on the device.
431 * The caller retains ownership of 'buffer' in all cases.
433 * The kernel maintains a packet transmission queue, so the caller is not
434 * expected to do additional queuing of packets. */
436 netdev_send(struct netdev *netdev, const struct buffer *buffer)
439 const struct eth_header *eh;
440 struct sockaddr_pkt spkt;
442 /* Pull out the Ethernet header. */
443 if (buffer->size < ETH_HEADER_LEN) {
444 VLOG_WARN("cannot send %zu-byte frame on %s",
445 buffer->size, netdev->name);
448 eh = buffer_at_assert(buffer, 0, sizeof *eh);
450 /* Construct packet sockaddr, which SOCK_PACKET requires. */
451 spkt.spkt_family = AF_PACKET;
452 strncpy((char *) spkt.spkt_device, netdev->name, sizeof spkt.spkt_device);
453 spkt.spkt_protocol = eh->eth_type;
456 n_bytes = sendto(netdev->fd, buffer->data, buffer->size, 0,
457 (const struct sockaddr *) &spkt, sizeof spkt);
458 } while (n_bytes < 0 && errno == EINTR);
461 /* The Linux AF_PACKET implementation never blocks waiting for room
462 * for packets, instead returning ENOBUFS. Translate this into EAGAIN
464 if (errno == ENOBUFS) {
466 } else if (errno != EAGAIN) {
467 VLOG_WARN("error sending Ethernet packet on %s: %s",
468 netdev->name, strerror(errno));
471 } else if (n_bytes != buffer->size) {
472 VLOG_WARN("send partial Ethernet packet (%d bytes of %zu) on %s",
473 (int) n_bytes, buffer->size, netdev->name);
480 /* Registers with the poll loop to wake up from the next call to poll_block()
481 * when the packet transmission queue has sufficient room to transmit a packet
482 * with netdev_send().
484 * The kernel maintains a packet transmission queue, so the client is not
485 * expected to do additional queuing of packets. Thus, this function is
486 * unlikely to ever be used. It is included for completeness. */
488 netdev_send_wait(struct netdev *netdev)
490 poll_fd_wait(netdev->fd, POLLOUT);
493 /* Returns a pointer to 'netdev''s MAC address. The caller must not modify or
494 * free the returned buffer. */
496 netdev_get_etheraddr(const struct netdev *netdev)
498 return netdev->etheraddr;
501 /* Returns the name of the network device that 'netdev' represents,
502 * e.g. "eth0". The caller must not modify or free the returned string. */
504 netdev_get_name(const struct netdev *netdev)
509 /* Returns the maximum size of transmitted (and received) packets on 'netdev',
510 * in bytes, not including the hardware header; thus, this is typically 1500
511 * bytes for Ethernet devices. */
513 netdev_get_mtu(const struct netdev *netdev)
518 /* Returns the current speed of the network device that 'netdev' represents, in
519 * megabits per second, or 0 if the speed is unknown. */
521 netdev_get_speed(const struct netdev *netdev)
523 return netdev->speed;
526 /* Returns the features supported by 'netdev', as a bitmap of bits from enum
527 * ofp_phy_port, in host byte order. */
529 netdev_get_features(const struct netdev *netdev)
531 return netdev->features;
534 /* If 'netdev' has an assigned IPv4 address, sets '*in4' to that address and
535 * returns true. Otherwise, returns false. */
537 netdev_get_in4(const struct netdev *netdev, struct in_addr *in4)
540 return in4->s_addr != INADDR_ANY;
543 /* If 'netdev' has an assigned IPv6 address, sets '*in6' to that address and
544 * returns true. Otherwise, returns false. */
546 netdev_get_in6(const struct netdev *netdev, struct in6_addr *in6)
549 return memcmp(in6, &in6addr_any, sizeof *in6) != 0;
552 /* Obtains the current flags for 'netdev' and stores them into '*flagsp'.
553 * Returns 0 if successful, otherwise a positive errno value. */
555 netdev_get_flags(const struct netdev *netdev, enum netdev_flags *flagsp)
559 error = get_flags(netdev, &flags);
565 if (flags & IFF_UP) {
566 *flagsp |= NETDEV_UP;
568 if (flags & IFF_PROMISC) {
569 *flagsp |= NETDEV_PROMISC;
574 /* Sets the flags for 'netdev' to 'nd_flags'.
575 * Returns 0 if successful, otherwise a positive errno value. */
577 netdev_set_flags(struct netdev *netdev, enum netdev_flags nd_flags)
579 int old_flags, new_flags;
582 error = get_flags(netdev, &old_flags);
587 new_flags = old_flags & ~(IFF_UP | IFF_PROMISC);
588 if (nd_flags & NETDEV_UP) {
591 if (nd_flags & NETDEV_PROMISC) {
592 new_flags |= IFF_PROMISC;
594 if (new_flags != old_flags) {
595 error = set_flags(netdev, new_flags);
600 /* Looks up the ARP table entry for 'ip' on 'netdev'. If one exists and can be
601 * successfully retrieved, it stores the corresponding MAC address in 'mac' and
602 * returns 0. Otherwise, it returns a positive errno value; in particular,
603 * ENXIO indicates that there is not ARP table entry for 'ip' on 'netdev'. */
605 netdev_arp_lookup(const struct netdev *netdev,
606 uint32_t ip, uint8_t mac[ETH_ADDR_LEN])
609 struct sockaddr_in *pa;
612 memset(&r, 0, sizeof r);
613 pa = (struct sockaddr_in *) &r.arp_pa;
614 pa->sin_family = AF_INET;
615 pa->sin_addr.s_addr = ip;
617 r.arp_ha.sa_family = ARPHRD_ETHER;
619 strncpy(r.arp_dev, netdev->name, sizeof r.arp_dev);
620 retval = ioctl(af_inet_sock, SIOCGARP, &r) < 0 ? errno : 0;
622 memcpy(mac, r.arp_ha.sa_data, ETH_ADDR_LEN);
623 } else if (retval != ENXIO) {
624 VLOG_WARN("%s: could not look up ARP entry for "IP_FMT": %s",
625 netdev->name, IP_ARGS(&ip), strerror(retval));
630 static void restore_all_flags(void *aux);
632 /* Set up a signal hook to restore network device flags on program
640 fatal_signal_add_hook(restore_all_flags, NULL);
641 af_inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
642 if (af_inet_sock < 0) {
643 fatal(errno, "socket(AF_INET)");
648 /* Restore the network device flags on 'netdev' to those that were active
649 * before we changed them. Returns 0 if successful, otherwise a positive
652 * To avoid reentry, the caller must ensure that fatal signals are blocked. */
654 restore_flags(struct netdev *netdev)
658 /* Get current flags. */
659 strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
660 if (ioctl(netdev->fd, SIOCGIFFLAGS, &ifr) < 0) {
664 /* Restore flags that we might have changed, if necessary. */
665 if ((ifr.ifr_flags ^ netdev->save_flags) & (IFF_PROMISC | IFF_UP)) {
666 ifr.ifr_flags &= ~(IFF_PROMISC | IFF_UP);
667 ifr.ifr_flags |= netdev->save_flags & (IFF_PROMISC | IFF_UP);
668 if (ioctl(netdev->fd, SIOCSIFFLAGS, &ifr) < 0) {
676 /* Retores all the flags on all network devices that we modified. Called from
677 * a signal handler, so it does not attempt to report error conditions. */
679 restore_all_flags(void *aux UNUSED)
681 struct netdev *netdev;
682 LIST_FOR_EACH (netdev, struct netdev, node, &netdev_list) {
683 restore_flags(netdev);
688 get_flags(const struct netdev *netdev, int *flags)
691 strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
692 if (ioctl(netdev->fd, SIOCGIFFLAGS, &ifr) < 0) {
693 VLOG_ERR("ioctl(SIOCGIFFLAGS) on %s device failed: %s",
694 netdev->name, strerror(errno));
697 *flags = ifr.ifr_flags;
702 set_flags(struct netdev *netdev, int flags)
705 strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
706 ifr.ifr_flags = flags;
707 if (ioctl(netdev->fd, SIOCSIFFLAGS, &ifr) < 0) {
708 VLOG_ERR("ioctl(SIOCSIFFLAGS) on %s device failed: %s",
709 netdev->name, strerror(errno));