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