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 static void init_netdev(void);
82 static int restore_flags(struct netdev *netdev);
84 /* Obtains the IPv4 address for 'name' into 'in4'. Returns true if
87 get_ipv4_address(const char *name, struct in_addr *in4)
92 sock = socket(AF_INET, SOCK_DGRAM, 0);
94 VLOG_WARN("socket(AF_INET): %s", strerror(errno));
98 strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
99 ifr.ifr_addr.sa_family = AF_INET;
100 if (ioctl(sock, SIOCGIFADDR, &ifr) == 0) {
101 struct sockaddr_in *sin = (struct sockaddr_in *) &ifr.ifr_addr;
102 *in4 = sin->sin_addr;
104 in4->s_addr = INADDR_ANY;
111 /* Obtains the IPv6 address for 'name' into 'in6'. */
113 get_ipv6_address(const char *name, struct in6_addr *in6)
118 file = fopen("/proc/net/if_inet6", "r");
120 /* This most likely indicates that the host doesn't have IPv6 support,
121 * so it's not really a failure condition.*/
126 while (fgets(line, sizeof line, file)) {
127 uint8_t *s6 = in6->s6_addr;
131 if (sscanf(line, " "X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8
132 "%*x %*x %*x %*x %16s\n",
133 &s6[0], &s6[1], &s6[2], &s6[3],
134 &s6[4], &s6[5], &s6[6], &s6[7],
135 &s6[8], &s6[9], &s6[10], &s6[11],
136 &s6[12], &s6[13], &s6[14], &s6[15],
138 && !strcmp(name, ifname))
149 do_ethtool(struct netdev *netdev)
152 struct ethtool_cmd ecmd;
155 netdev->features = 0;
157 memset(&ifr, 0, sizeof ifr);
158 strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
159 ifr.ifr_data = (caddr_t) &ecmd;
161 memset(&ecmd, 0, sizeof ecmd);
162 ecmd.cmd = ETHTOOL_GSET;
163 if (ioctl(netdev->fd, SIOCETHTOOL, &ifr) == 0) {
164 if (ecmd.supported & SUPPORTED_10baseT_Half) {
165 netdev->features |= OFPPF_10MB_HD;
167 if (ecmd.supported & SUPPORTED_10baseT_Full) {
168 netdev->features |= OFPPF_10MB_FD;
170 if (ecmd.supported & SUPPORTED_100baseT_Half) {
171 netdev->features |= OFPPF_100MB_HD;
173 if (ecmd.supported & SUPPORTED_100baseT_Full) {
174 netdev->features |= OFPPF_100MB_FD;
176 if (ecmd.supported & SUPPORTED_1000baseT_Half) {
177 netdev->features |= OFPPF_1GB_HD;
179 if (ecmd.supported & SUPPORTED_1000baseT_Full) {
180 netdev->features |= OFPPF_1GB_FD;
182 /* 10Gbps half-duplex doesn't exist... */
183 if (ecmd.supported & SUPPORTED_10000baseT_Full) {
184 netdev->features |= OFPPF_10GB_FD;
187 switch (ecmd.speed) {
197 netdev->speed = 1000;
201 netdev->speed = 2500;
205 netdev->speed = 10000;
209 VLOG_DBG("ioctl(SIOCETHTOOL) failed: %s", strerror(errno));
213 /* Opens the network device named 'name' (e.g. "eth0") and returns zero if
214 * successful, otherwise a positive errno value. On success, sets '*netdev'
215 * to the new network device, otherwise to null. */
217 netdev_open(const char *name, struct netdev **netdev_)
222 unsigned int ifindex;
223 socklen_t rcvbuf_len;
225 uint8_t etheraddr[ETH_ADDR_LEN];
230 struct netdev *netdev;
235 /* Create raw socket.
237 * We have to use SOCK_PACKET, despite its deprecation, because only
238 * SOCK_PACKET lets us set the hardware source address of outgoing
240 fd = socket(PF_PACKET, SOCK_PACKET, htons(ETH_P_ALL));
245 /* Bind to specific ethernet device. */
246 memset(&sa, 0, sizeof sa);
247 sa.sa_family = AF_UNSPEC;
248 strncpy((char *) sa.sa_data, name, sizeof sa.sa_data);
249 if (bind(fd, &sa, sizeof sa) < 0) {
250 VLOG_ERR("bind to %s failed: %s", name, strerror(errno));
254 /* Between the socket() and bind() calls above, the socket receives all
255 * packets on all system interfaces. We do not want to receive that
256 * data, but there is no way to avoid it. So we must now drain out the
257 * receive queue. There is no way to know how long the receive queue is,
258 * but we know that the total number of bytes queued does not exceed the
259 * receive buffer size, so we pull packets until none are left or we've
260 * read that many bytes. */
261 rcvbuf_len = sizeof rcvbuf;
262 if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, &rcvbuf_len) < 0) {
263 VLOG_ERR("getsockopt(SO_RCVBUF) on %s device failed: %s",
264 name, strerror(errno));
269 ssize_t n_bytes = recv(fd, &buffer, 1, MSG_TRUNC | MSG_DONTWAIT);
276 /* Get ethernet device index. */
277 strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
278 if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0) {
279 VLOG_ERR("ioctl(SIOCGIFINDEX) on %s device failed: %s",
280 name, strerror(errno));
283 ifindex = ifr.ifr_ifindex;
285 /* Get MAC address. */
286 if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) {
287 VLOG_ERR("ioctl(SIOCGIFHWADDR) on %s device failed: %s",
288 name, strerror(errno));
291 if (ifr.ifr_hwaddr.sa_family != AF_UNSPEC
292 && ifr.ifr_hwaddr.sa_family != ARPHRD_ETHER) {
293 VLOG_WARN("%s device has unknown hardware address family %d",
294 name, (int) ifr.ifr_hwaddr.sa_family);
296 memcpy(etheraddr, ifr.ifr_hwaddr.sa_data, sizeof etheraddr);
299 if (ioctl(fd, SIOCGIFMTU, &ifr) < 0) {
300 VLOG_ERR("ioctl(SIOCGIFMTU) on %s device failed: %s",
301 name, strerror(errno));
306 if (!get_ipv4_address(name, &in4)) {
309 get_ipv6_address(name, &in6);
311 /* Allocate network device. */
312 netdev = xmalloc(sizeof *netdev);
313 netdev->name = xstrdup(name);
315 memcpy(netdev->etheraddr, etheraddr, sizeof etheraddr);
320 /* Get speed, features. */
323 /* Save flags to restore at close or exit. */
324 if (ioctl(fd, SIOCGIFFLAGS, &ifr) < 0) {
325 VLOG_ERR("ioctl(SIOCGIFFLAGS) on %s device failed: %s",
326 name, strerror(errno));
329 netdev->save_flags = ifr.ifr_flags;
330 fatal_signal_block();
331 list_push_back(&netdev_list, &netdev->node);
332 fatal_signal_unblock();
334 /* Bring up interface and set promiscuous mode. */
335 ifr.ifr_flags |= IFF_PROMISC | IFF_UP;
336 if (ioctl(fd, SIOCSIFFLAGS, &ifr) < 0) {
338 VLOG_ERR("failed to set promiscuous mode on %s device: %s",
339 name, strerror(errno));
340 netdev_close(netdev);
354 /* Closes and destroys 'netdev'. */
356 netdev_close(struct netdev *netdev)
359 /* Bring down interface and drop promiscuous mode, if we brought up
360 * the interface or enabled promiscuous mode. */
362 fatal_signal_block();
363 error = restore_flags(netdev);
364 list_remove(&netdev->node);
365 fatal_signal_unblock();
367 VLOG_WARN("failed to restore network device flags on %s: %s",
368 netdev->name, strerror(error));
378 /* Pads 'buffer' out with zero-bytes to the minimum valid length of an
379 * Ethernet packet, if necessary. */
381 pad_to_minimum_length(struct buffer *buffer)
383 if (buffer->size < ETH_TOTAL_MIN) {
384 size_t shortage = ETH_TOTAL_MIN - buffer->size;
385 memset(buffer_put_uninit(buffer, shortage), 0, shortage);
389 /* Attempts to receive a packet from 'netdev' into 'buffer', which the caller
390 * must have initialized with sufficient room for the packet. The space
391 * required to receive any packet is ETH_HEADER_LEN bytes, plus VLAN_HEADER_LEN
392 * bytes, plus the device's MTU (which may be retrieved via netdev_get_mtu()).
393 * (Some devices do not allow for a VLAN header, in which case VLAN_HEADER_LEN
394 * need not be included.)
396 * If a packet is successfully retrieved, returns 0. In this case 'buffer' is
397 * guaranteed to contain at least ETH_TOTAL_MIN bytes. Otherwise, returns a
398 * positive errno value. Returns EAGAIN immediately if no packet is ready to
402 netdev_recv(struct netdev *netdev, struct buffer *buffer)
406 assert(buffer->size == 0);
407 assert(buffer_tailroom(buffer) >= ETH_TOTAL_MIN);
409 n_bytes = recv(netdev->fd,
410 buffer_tail(buffer), buffer_tailroom(buffer),
412 } while (n_bytes < 0 && errno == EINTR);
414 if (errno != EAGAIN) {
415 VLOG_WARN("error receiving Ethernet packet on %s: %s",
416 strerror(errno), netdev->name);
420 buffer->size += n_bytes;
422 /* When the kernel internally sends out an Ethernet frame on an
423 * interface, it gives us a copy *before* padding the frame to the
424 * minimum length. Thus, when it sends out something like an ARP
425 * request, we see a too-short frame. So pad it out to the minimum
427 pad_to_minimum_length(buffer);
432 /* Registers with the poll loop to wake up from the next call to poll_block()
433 * when a packet is ready to be received with netdev_recv() on 'netdev'. */
435 netdev_recv_wait(struct netdev *netdev)
437 poll_fd_wait(netdev->fd, POLLIN);
440 /* Sends 'buffer' on 'netdev'. Returns 0 if successful, otherwise a positive
441 * errno value. Returns EAGAIN without blocking if the packet cannot be queued
442 * immediately. Returns EMSGSIZE if a partial packet was transmitted or if
443 * the packet is too big to transmit on the device.
445 * The kernel maintains a packet transmission queue, so the caller is not
446 * expected to do additional queuing of packets. */
448 netdev_send(struct netdev *netdev, struct buffer *buffer)
451 const struct eth_header *eh;
452 struct sockaddr_pkt spkt;
454 /* Ensure packet is long enough. (Although all incoming packets are at
455 * least ETH_TOTAL_MIN bytes long, we could have trimmed some data off a
456 * minimum-size packet, e.g. by dropping a vlan header.)
458 * The kernel does not require this, but it ensures that we always access
459 * valid memory in grabbing the sockaddr below. */
460 pad_to_minimum_length(buffer);
462 /* Construct packet sockaddr, which SOCK_PACKET requires. */
463 spkt.spkt_family = AF_PACKET;
464 strncpy((char *) spkt.spkt_device, netdev->name, sizeof spkt.spkt_device);
465 eh = buffer_at_assert(buffer, 0, sizeof *eh);
466 spkt.spkt_protocol = eh->eth_type;
469 n_bytes = sendto(netdev->fd, buffer->data, buffer->size, 0,
470 (const struct sockaddr *) &spkt, sizeof spkt);
471 } while (n_bytes < 0 && errno == EINTR);
474 /* The Linux AF_PACKET implementation never blocks waiting for room
475 * for packets, instead returning ENOBUFS. Translate this into EAGAIN
477 if (errno == ENOBUFS) {
479 } else if (errno != EAGAIN) {
480 VLOG_WARN("error sending Ethernet packet on %s: %s",
481 netdev->name, strerror(errno));
484 } else if (n_bytes != buffer->size) {
485 VLOG_WARN("send partial Ethernet packet (%d bytes of %zu) on %s",
486 (int) n_bytes, buffer->size, netdev->name);
493 /* Registers with the poll loop to wake up from the next call to poll_block()
494 * when the packet transmission queue has sufficient room to transmit a packet
495 * with netdev_send().
497 * The kernel maintains a packet transmission queue, so the client is not
498 * expected to do additional queuing of packets. Thus, this function is
499 * unlikely to ever be used. It is included for completeness. */
501 netdev_send_wait(struct netdev *netdev)
503 poll_fd_wait(netdev->fd, POLLOUT);
506 /* Returns a pointer to 'netdev''s MAC address. The caller must not modify or
507 * free the returned buffer. */
509 netdev_get_etheraddr(const struct netdev *netdev)
511 return netdev->etheraddr;
514 /* Returns the name of the network device that 'netdev' represents,
515 * e.g. "eth0". The caller must not modify or free the returned string. */
517 netdev_get_name(const struct netdev *netdev)
522 /* Returns the maximum size of transmitted (and received) packets on 'netdev',
523 * in bytes, not including the hardware header; thus, this is typically 1500
524 * bytes for Ethernet devices. */
526 netdev_get_mtu(const struct netdev *netdev)
531 /* Returns the current speed of the network device that 'netdev' represents, in
532 * megabits per second, or 0 if the speed is unknown. */
534 netdev_get_speed(const struct netdev *netdev)
536 return netdev->speed;
539 /* Returns the features supported by 'netdev', as a bitmap of bits from enum
540 * ofp_phy_port, in host byte order. */
542 netdev_get_features(const struct netdev *netdev)
544 return netdev->features;
547 /* If 'netdev' has an assigned IPv4 address, sets '*in4' to that address and
548 * returns true. Otherwise, returns false. */
550 netdev_get_in4(const struct netdev *netdev, struct in_addr *in4)
553 return in4->s_addr != INADDR_ANY;
556 /* If 'netdev' has an assigned IPv6 address, sets '*in6' to that address and
557 * returns true. Otherwise, returns false. */
559 netdev_get_in6(const struct netdev *netdev, struct in6_addr *in6)
562 return memcmp(in6, &in6addr_any, sizeof *in6) != 0;
565 static void restore_all_flags(void *aux);
567 /* Set up a signal hook to restore network device flags on program
575 fatal_signal_add_hook(restore_all_flags, NULL);
579 /* Restore the network device flags on 'netdev' to those that were active
580 * before we changed them. Returns 0 if successful, otherwise a positive
583 * To avoid reentry, the caller must ensure that fatal signals are blocked. */
585 restore_flags(struct netdev *netdev)
589 /* Get current flags. */
590 strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
591 if (ioctl(netdev->fd, SIOCGIFFLAGS, &ifr) < 0) {
595 /* Restore flags that we might have changed, if necessary. */
596 if ((ifr.ifr_flags ^ netdev->save_flags) & (IFF_PROMISC | IFF_UP)) {
597 ifr.ifr_flags &= ~(IFF_PROMISC | IFF_UP);
598 ifr.ifr_flags |= netdev->save_flags & (IFF_PROMISC | IFF_UP);
599 if (ioctl(netdev->fd, SIOCSIFFLAGS, &ifr) < 0) {
607 /* Retores all the flags on all network devices that we modified. Called from
608 * a signal handler, so it does not attempt to report error conditions. */
610 restore_all_flags(void *aux UNUSED)
612 struct netdev *netdev;
613 LIST_FOR_EACH (netdev, struct netdev, node, &netdev_list) {
614 restore_flags(netdev);