1 // Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 // SPDX-License-Identifier: Apache-2.0 3 // 4 // Portions Copyright 2017 The Chromium OS Authors. All rights reserved. 5 // Use of this source code is governed by a BSD-style license that can be 6 // found in the THIRD-PARTY file. 7 8 #[macro_use] 9 extern crate log; 10 11 mod ctrl_queue; 12 mod mac; 13 mod open_tap; 14 mod queue_pair; 15 mod tap; 16 17 use std::io::Error as IoError; 18 use std::os::raw::c_uint; 19 use std::os::unix::io::{FromRawFd, RawFd}; 20 use std::{io, mem, net}; 21 22 use serde::{Deserialize, Serialize}; 23 use thiserror::Error; 24 use virtio_bindings::virtio_net::{ 25 virtio_net_hdr_v1, VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX, VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN, 26 VIRTIO_NET_F_GUEST_CSUM, VIRTIO_NET_F_GUEST_ECN, VIRTIO_NET_F_GUEST_TSO4, 27 VIRTIO_NET_F_GUEST_TSO6, VIRTIO_NET_F_GUEST_UFO, VIRTIO_NET_F_MAC, VIRTIO_NET_F_MQ, 28 }; 29 use vm_memory::bitmap::AtomicBitmap; 30 use vm_memory::ByteValued; 31 32 type GuestMemoryMmap = vm_memory::GuestMemoryMmap<AtomicBitmap>; 33 34 pub use ctrl_queue::{CtrlQueue, Error as CtrlQueueError}; 35 pub use mac::{MacAddr, MAC_ADDR_LEN}; 36 pub use open_tap::{open_tap, Error as OpenTapError}; 37 pub use queue_pair::{NetCounters, NetQueuePair, NetQueuePairError, RxVirtio, TxVirtio}; 38 pub use tap::{Error as TapError, Tap}; 39 40 #[derive(Error, Debug)] 41 pub enum Error { 42 #[error("Failed to create a socket: {0}")] 43 CreateSocket(IoError), 44 } 45 46 pub type Result<T> = std::result::Result<T, Error>; 47 48 #[repr(C, packed)] 49 #[derive(Copy, Clone, Debug, Default, Serialize, Deserialize)] 50 pub struct VirtioNetConfig { 51 pub mac: [u8; 6], 52 pub status: u16, 53 pub max_virtqueue_pairs: u16, 54 pub mtu: u16, 55 pub speed: u32, 56 pub duplex: u8, 57 } 58 59 // SAFETY: it only has data and has no implicit padding. 60 unsafe impl ByteValued for VirtioNetConfig {} 61 62 /// Create a sockaddr_in from an IPv4 address, and expose it as 63 /// an opaque sockaddr suitable for usage by socket ioctls. 64 fn create_sockaddr(ip_addr: net::Ipv4Addr) -> net_gen::sockaddr { 65 // IPv4 addresses big-endian (network order), but Ipv4Addr will give us 66 // a view of those bytes directly so we can avoid any endian trickiness. 67 let addr_in = net_gen::sockaddr_in { 68 sin_family: net_gen::AF_INET as u16, 69 sin_port: 0, 70 // SAFETY: ip_addr can be safely transmute to in_addr 71 sin_addr: unsafe { mem::transmute::<[u8; 4], net_gen::inn::in_addr>(ip_addr.octets()) }, 72 __pad: [0; 8usize], 73 }; 74 75 // SAFETY: addr_in can be safely transmute to sockaddr 76 unsafe { mem::transmute(addr_in) } 77 } 78 79 fn create_inet_socket() -> Result<net::UdpSocket> { 80 // SAFETY: we check the return value. 81 let sock = unsafe { libc::socket(libc::AF_INET, libc::SOCK_DGRAM, 0) }; 82 if sock < 0 { 83 return Err(Error::CreateSocket(IoError::last_os_error())); 84 } 85 86 // SAFETY: nothing else will use or hold onto the raw sock fd. 87 Ok(unsafe { net::UdpSocket::from_raw_fd(sock) }) 88 } 89 90 fn create_unix_socket() -> Result<net::UdpSocket> { 91 // SAFETY: we check the return value. 92 let sock = unsafe { libc::socket(libc::AF_UNIX, libc::SOCK_DGRAM, 0) }; 93 if sock < 0 { 94 return Err(Error::CreateSocket(IoError::last_os_error())); 95 } 96 97 // SAFETY: nothing else will use or hold onto the raw sock fd. 98 Ok(unsafe { net::UdpSocket::from_raw_fd(sock) }) 99 } 100 101 fn vnet_hdr_len() -> usize { 102 std::mem::size_of::<virtio_net_hdr_v1>() 103 } 104 105 pub fn register_listener( 106 epoll_fd: RawFd, 107 fd: RawFd, 108 ev_type: epoll::Events, 109 data: u64, 110 ) -> std::result::Result<(), io::Error> { 111 epoll::ctl( 112 epoll_fd, 113 epoll::ControlOptions::EPOLL_CTL_ADD, 114 fd, 115 epoll::Event::new(ev_type, data), 116 ) 117 } 118 119 pub fn unregister_listener( 120 epoll_fd: RawFd, 121 fd: RawFd, 122 ev_type: epoll::Events, 123 data: u64, 124 ) -> std::result::Result<(), io::Error> { 125 epoll::ctl( 126 epoll_fd, 127 epoll::ControlOptions::EPOLL_CTL_DEL, 128 fd, 129 epoll::Event::new(ev_type, data), 130 ) 131 } 132 133 pub fn build_net_config_space( 134 config: &mut VirtioNetConfig, 135 mac: MacAddr, 136 num_queues: usize, 137 mtu: Option<u16>, 138 avail_features: &mut u64, 139 ) { 140 config.mac.copy_from_slice(mac.get_bytes()); 141 *avail_features |= 1 << VIRTIO_NET_F_MAC; 142 143 build_net_config_space_with_mq(config, num_queues, mtu, avail_features); 144 } 145 146 pub fn build_net_config_space_with_mq( 147 config: &mut VirtioNetConfig, 148 num_queues: usize, 149 mtu: Option<u16>, 150 avail_features: &mut u64, 151 ) { 152 let num_queue_pairs = (num_queues / 2) as u16; 153 if (num_queue_pairs >= VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN as u16) 154 && (num_queue_pairs <= VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX as u16) 155 { 156 config.max_virtqueue_pairs = num_queue_pairs; 157 *avail_features |= 1 << VIRTIO_NET_F_MQ; 158 } 159 if let Some(mtu) = mtu { 160 config.mtu = mtu; 161 } 162 } 163 164 pub fn virtio_features_to_tap_offload(features: u64) -> c_uint { 165 let mut tap_offloads: c_uint = 0; 166 if features & (1 << VIRTIO_NET_F_GUEST_CSUM) != 0 { 167 tap_offloads |= net_gen::TUN_F_CSUM; 168 } 169 if features & (1 << VIRTIO_NET_F_GUEST_TSO4) != 0 { 170 tap_offloads |= net_gen::TUN_F_TSO4; 171 } 172 if features & (1 << VIRTIO_NET_F_GUEST_TSO6) != 0 { 173 tap_offloads |= net_gen::TUN_F_TSO6; 174 } 175 if features & (1 << VIRTIO_NET_F_GUEST_ECN) != 0 { 176 tap_offloads |= net_gen::TUN_F_TSO_ECN; 177 } 178 if features & (1 << VIRTIO_NET_F_GUEST_UFO) != 0 { 179 tap_offloads |= net_gen::TUN_F_UFO; 180 } 181 182 tap_offloads 183 } 184 185 #[cfg(test)] 186 mod tests { 187 use super::*; 188 189 #[test] 190 fn test_create_sockaddr() { 191 let addr: net::Ipv4Addr = "10.0.0.1".parse().unwrap(); 192 let sockaddr = create_sockaddr(addr); 193 194 assert_eq!(sockaddr.sa_family, net_gen::AF_INET as u16); 195 196 let data = &sockaddr.sa_data[..]; 197 198 // The first two bytes should represent the port, which is 0. 199 assert_eq!(data[0], 0); 200 assert_eq!(data[1], 0); 201 202 // The next four bytes should represent the actual IPv4 address, in network order. 203 assert_eq!(data[2], 10); 204 assert_eq!(data[3], 0); 205 assert_eq!(data[4], 0); 206 assert_eq!(data[5], 1); 207 } 208 } 209