1 //这个文件的绝大部分内容是copy virtio_net.rs的,考虑到所有的驱动都要用操作系统提供的协议栈,我觉得可以把这些内容抽象出来 2 3 use crate::{ 4 driver::{ 5 base::{ 6 device::{bus::Bus, driver::Driver, Device, IdTable}, 7 kobject::{KObjType, KObject, KObjectState}, 8 }, 9 net::NetDriver, 10 }, 11 kinfo, 12 libs::spinlock::SpinLock, 13 net::{generate_iface_id, NET_DRIVERS}, 14 time::Instant, 15 }; 16 use alloc::{ 17 string::String, 18 sync::{Arc, Weak}, 19 }; 20 use core::{ 21 cell::UnsafeCell, 22 fmt::Debug, 23 ops::{Deref, DerefMut}, 24 }; 25 use smoltcp::{phy, wire}; 26 use system_error::SystemError; 27 28 use super::e1000e::{E1000EBuffer, E1000EDevice}; 29 30 pub struct E1000ERxToken(E1000EBuffer); 31 pub struct E1000ETxToken { 32 driver: E1000EDriver, 33 } 34 pub struct E1000EDriver { 35 pub inner: Arc<SpinLock<E1000EDevice>>, 36 } 37 38 /// @brief 网卡驱动的包裹器,这是为了获取网卡驱动的可变引用而设计的。 39 /// 参阅virtio_net.rs 40 struct E1000EDriverWrapper(UnsafeCell<E1000EDriver>); 41 unsafe impl Send for E1000EDriverWrapper {} 42 unsafe impl Sync for E1000EDriverWrapper {} 43 44 impl Deref for E1000EDriverWrapper { 45 type Target = E1000EDriver; 46 fn deref(&self) -> &Self::Target { 47 unsafe { &*self.0.get() } 48 } 49 } 50 impl DerefMut for E1000EDriverWrapper { 51 fn deref_mut(&mut self) -> &mut Self::Target { 52 unsafe { &mut *self.0.get() } 53 } 54 } 55 56 impl E1000EDriverWrapper { 57 fn force_get_mut(&self) -> &mut E1000EDriver { 58 unsafe { &mut *self.0.get() } 59 } 60 } 61 62 impl Debug for E1000EDriverWrapper { 63 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 64 f.debug_struct("E1000ENICDriver").finish() 65 } 66 } 67 68 pub struct E1000EInterface { 69 driver: E1000EDriverWrapper, 70 iface_id: usize, 71 iface: SpinLock<smoltcp::iface::Interface>, 72 name: String, 73 } 74 impl phy::RxToken for E1000ERxToken { 75 fn consume<R, F>(mut self, f: F) -> R 76 where 77 F: FnOnce(&mut [u8]) -> R, 78 { 79 let result = f(&mut self.0.as_mut_slice()); 80 self.0.free_buffer(); 81 return result; 82 } 83 } 84 85 impl phy::TxToken for E1000ETxToken { 86 fn consume<R, F>(self, _len: usize, f: F) -> R 87 where 88 F: FnOnce(&mut [u8]) -> R, 89 { 90 let mut buffer = E1000EBuffer::new(4096); 91 let result = f(buffer.as_mut_slice()); 92 let mut device = self.driver.inner.lock(); 93 device.e1000e_transmit(buffer); 94 buffer.free_buffer(); 95 return result; 96 } 97 } 98 99 impl E1000EDriver { 100 pub fn new(device: E1000EDevice) -> Self { 101 let mut iface_config = smoltcp::iface::Config::new(); 102 103 // todo: 随机设定这个值。 104 // 参见 https://docs.rs/smoltcp/latest/smoltcp/iface/struct.Config.html#structfield.random_seed 105 iface_config.random_seed = 12345; 106 107 iface_config.hardware_addr = Some(wire::HardwareAddress::Ethernet( 108 smoltcp::wire::EthernetAddress(device.mac_address()), 109 )); 110 111 let inner: Arc<SpinLock<E1000EDevice>> = Arc::new(SpinLock::new(device)); 112 let result = E1000EDriver { inner }; 113 return result; 114 } 115 } 116 117 impl Clone for E1000EDriver { 118 fn clone(&self) -> Self { 119 return E1000EDriver { 120 inner: self.inner.clone(), 121 }; 122 } 123 } 124 125 impl phy::Device for E1000EDriver { 126 type RxToken<'a> = E1000ERxToken; 127 type TxToken<'a> = E1000ETxToken; 128 129 fn receive( 130 &mut self, 131 _timestamp: smoltcp::time::Instant, 132 ) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> { 133 match self.inner.lock().e1000e_receive() { 134 Some(buffer) => Some(( 135 E1000ERxToken(buffer), 136 E1000ETxToken { 137 driver: self.clone(), 138 }, 139 )), 140 None => { 141 return None; 142 } 143 } 144 } 145 146 fn transmit(&mut self, _timestamp: smoltcp::time::Instant) -> Option<Self::TxToken<'_>> { 147 match self.inner.lock().e1000e_can_transmit() { 148 true => Some(E1000ETxToken { 149 driver: self.clone(), 150 }), 151 false => None, 152 } 153 } 154 155 fn capabilities(&self) -> smoltcp::phy::DeviceCapabilities { 156 let mut caps = smoltcp::phy::DeviceCapabilities::default(); 157 // 网卡的最大传输单元. 请与IP层的MTU进行区分。这个值应当是网卡的最大传输单元,而不是IP层的MTU。 158 // The maximum size of the received packet is limited by the 82574 hardware to 1536 bytes. Packets larger then 1536 bytes are silently discarded. Any packet smaller than 1536 bytes is processed by the 82574. 159 // 82574l manual pp205 160 caps.max_transmission_unit = 1536; 161 /* 162 Maximum burst size, in terms of MTU. 163 The network device is unable to send or receive bursts large than the value returned by this function. 164 If None, there is no fixed limit on burst size, e.g. if network buffers are dynamically allocated. 165 */ 166 caps.max_burst_size = Some(1); 167 return caps; 168 } 169 } 170 171 impl E1000EInterface { 172 pub fn new(mut driver: E1000EDriver) -> Arc<Self> { 173 let iface_id = generate_iface_id(); 174 let mut iface_config = smoltcp::iface::Config::new(); 175 176 // todo: 随机设定这个值。 177 // 参见 https://docs.rs/smoltcp/latest/smoltcp/iface/struct.Config.html#structfield.random_seed 178 iface_config.random_seed = 12345; 179 180 iface_config.hardware_addr = Some(wire::HardwareAddress::Ethernet( 181 smoltcp::wire::EthernetAddress(driver.inner.lock().mac_address()), 182 )); 183 let iface = smoltcp::iface::Interface::new(iface_config, &mut driver); 184 185 let driver: E1000EDriverWrapper = E1000EDriverWrapper(UnsafeCell::new(driver)); 186 let result = Arc::new(E1000EInterface { 187 driver, 188 iface_id, 189 iface: SpinLock::new(iface), 190 name: format!("eth{}", iface_id), 191 }); 192 193 return result; 194 } 195 } 196 197 impl Debug for E1000EInterface { 198 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 199 f.debug_struct("E1000EInterface") 200 .field("iface_id", &self.iface_id) 201 .field("iface", &"smoltcp::iface::Interface") 202 .field("name", &self.name) 203 .finish() 204 } 205 } 206 207 impl Driver for E1000EInterface { 208 fn id_table(&self) -> Option<IdTable> { 209 todo!() 210 } 211 212 fn add_device(&self, _device: Arc<dyn Device>) { 213 todo!() 214 } 215 216 fn delete_device(&self, _device: &Arc<dyn Device>) { 217 todo!() 218 } 219 220 fn devices(&self) -> alloc::vec::Vec<Arc<dyn Device>> { 221 todo!() 222 } 223 224 fn bus(&self) -> Option<Weak<dyn Bus>> { 225 todo!() 226 } 227 228 fn set_bus(&self, _bus: Option<Weak<dyn Bus>>) { 229 todo!() 230 } 231 } 232 233 impl NetDriver for E1000EInterface { 234 fn mac(&self) -> smoltcp::wire::EthernetAddress { 235 let mac = self.driver.inner.lock().mac_address(); 236 return smoltcp::wire::EthernetAddress::from_bytes(&mac); 237 } 238 239 #[inline] 240 fn nic_id(&self) -> usize { 241 return self.iface_id; 242 } 243 244 #[inline] 245 fn name(&self) -> String { 246 return self.name.clone(); 247 } 248 249 fn update_ip_addrs(&self, ip_addrs: &[wire::IpCidr]) -> Result<(), SystemError> { 250 if ip_addrs.len() != 1 { 251 return Err(SystemError::EINVAL); 252 } 253 254 self.iface.lock().update_ip_addrs(|addrs| { 255 let dest = addrs.iter_mut().next(); 256 if let None = dest { 257 addrs.push(ip_addrs[0]).expect("Push ipCidr failed: full"); 258 } else { 259 let dest = dest.unwrap(); 260 *dest = ip_addrs[0]; 261 } 262 }); 263 return Ok(()); 264 } 265 266 fn poll(&self, sockets: &mut smoltcp::iface::SocketSet) -> Result<(), SystemError> { 267 let timestamp: smoltcp::time::Instant = Instant::now().into(); 268 let mut guard = self.iface.lock(); 269 let poll_res = guard.poll(timestamp, self.driver.force_get_mut(), sockets); 270 if poll_res { 271 return Ok(()); 272 } 273 return Err(SystemError::EAGAIN_OR_EWOULDBLOCK); 274 } 275 276 #[inline(always)] 277 fn inner_iface(&self) -> &SpinLock<smoltcp::iface::Interface> { 278 return &self.iface; 279 } 280 } 281 282 impl KObject for E1000EInterface { 283 fn as_any_ref(&self) -> &dyn core::any::Any { 284 self 285 } 286 287 fn set_inode(&self, _inode: Option<Arc<crate::filesystem::kernfs::KernFSInode>>) { 288 todo!() 289 } 290 291 fn inode(&self) -> Option<Arc<crate::filesystem::kernfs::KernFSInode>> { 292 todo!() 293 } 294 295 fn parent(&self) -> Option<alloc::sync::Weak<dyn KObject>> { 296 todo!() 297 } 298 299 fn set_parent(&self, _parent: Option<alloc::sync::Weak<dyn KObject>>) { 300 todo!() 301 } 302 303 fn kset(&self) -> Option<Arc<crate::driver::base::kset::KSet>> { 304 todo!() 305 } 306 307 fn set_kset(&self, _kset: Option<Arc<crate::driver::base::kset::KSet>>) { 308 todo!() 309 } 310 311 fn kobj_type(&self) -> Option<&'static dyn crate::driver::base::kobject::KObjType> { 312 todo!() 313 } 314 315 fn name(&self) -> String { 316 self.name.clone() 317 } 318 319 fn set_name(&self, _name: String) { 320 todo!() 321 } 322 323 fn kobj_state( 324 &self, 325 ) -> crate::libs::rwlock::RwLockReadGuard<crate::driver::base::kobject::KObjectState> { 326 todo!() 327 } 328 329 fn kobj_state_mut( 330 &self, 331 ) -> crate::libs::rwlock::RwLockWriteGuard<crate::driver::base::kobject::KObjectState> { 332 todo!() 333 } 334 335 fn set_kobj_state(&self, _state: KObjectState) { 336 todo!() 337 } 338 339 fn set_kobj_type(&self, _ktype: Option<&'static dyn KObjType>) { 340 todo!() 341 } 342 } 343 344 pub fn e1000e_driver_init(device: E1000EDevice) { 345 let mac = smoltcp::wire::EthernetAddress::from_bytes(&device.mac_address()); 346 let driver = E1000EDriver::new(device); 347 let iface = E1000EInterface::new(driver); 348 // 将网卡的接口信息注册到全局的网卡接口信息表中 349 NET_DRIVERS 350 .write_irqsave() 351 .insert(iface.nic_id(), iface.clone()); 352 kinfo!("e1000e driver init successfully!\tMAC: [{}]", mac); 353 } 354