xref: /DragonOS/kernel/src/driver/net/e1000e/e1000e_driver.rs (revision b5b571e02693d91eb6918d3b7561e088c3e7ee81)
177799ccaSWu Mianzhi //这个文件的绝大部分内容是copy virtio_net.rs的,考虑到所有的驱动都要用操作系统提供的协议栈,我觉得可以把这些内容抽象出来
277799ccaSWu Mianzhi 
377799ccaSWu Mianzhi use crate::{
477799ccaSWu Mianzhi     driver::{
577799ccaSWu Mianzhi         base::{
6971462beSGnoCiYeH             device::{bus::Bus, driver::Driver, Device, IdTable},
777799ccaSWu Mianzhi             kobject::{KObjType, KObject, KObjectState},
877799ccaSWu Mianzhi         },
977799ccaSWu Mianzhi         net::NetDriver,
1077799ccaSWu Mianzhi     },
11971462beSGnoCiYeH     kinfo,
1277799ccaSWu Mianzhi     libs::spinlock::SpinLock,
1377799ccaSWu Mianzhi     net::{generate_iface_id, NET_DRIVERS},
1477799ccaSWu Mianzhi     time::Instant,
1577799ccaSWu Mianzhi };
16c566df45SLoGin use alloc::{
17c566df45SLoGin     string::String,
18c566df45SLoGin     sync::{Arc, Weak},
19c566df45SLoGin };
2077799ccaSWu Mianzhi use core::{
2177799ccaSWu Mianzhi     cell::UnsafeCell,
2277799ccaSWu Mianzhi     fmt::Debug,
2377799ccaSWu Mianzhi     ops::{Deref, DerefMut},
2477799ccaSWu Mianzhi };
2577799ccaSWu Mianzhi use smoltcp::{phy, wire};
2691e9d4abSLoGin use system_error::SystemError;
2777799ccaSWu Mianzhi 
2877799ccaSWu Mianzhi use super::e1000e::{E1000EBuffer, E1000EDevice};
2977799ccaSWu Mianzhi 
3077799ccaSWu Mianzhi pub struct E1000ERxToken(E1000EBuffer);
3177799ccaSWu Mianzhi pub struct E1000ETxToken {
3277799ccaSWu Mianzhi     driver: E1000EDriver,
3377799ccaSWu Mianzhi }
3477799ccaSWu Mianzhi pub struct E1000EDriver {
3577799ccaSWu Mianzhi     pub inner: Arc<SpinLock<E1000EDevice>>,
3677799ccaSWu Mianzhi }
37*b5b571e0SLoGin unsafe impl Send for E1000EDriver {}
38*b5b571e0SLoGin unsafe impl Sync for E1000EDriver {}
3977799ccaSWu Mianzhi 
4077799ccaSWu Mianzhi /// @brief 网卡驱动的包裹器,这是为了获取网卡驱动的可变引用而设计的。
4177799ccaSWu Mianzhi /// 参阅virtio_net.rs
4277799ccaSWu Mianzhi struct E1000EDriverWrapper(UnsafeCell<E1000EDriver>);
4377799ccaSWu Mianzhi unsafe impl Send for E1000EDriverWrapper {}
4477799ccaSWu Mianzhi unsafe impl Sync for E1000EDriverWrapper {}
4577799ccaSWu Mianzhi 
4677799ccaSWu Mianzhi impl Deref for E1000EDriverWrapper {
4777799ccaSWu Mianzhi     type Target = E1000EDriver;
4877799ccaSWu Mianzhi     fn deref(&self) -> &Self::Target {
4977799ccaSWu Mianzhi         unsafe { &*self.0.get() }
5077799ccaSWu Mianzhi     }
5177799ccaSWu Mianzhi }
5277799ccaSWu Mianzhi impl DerefMut for E1000EDriverWrapper {
5377799ccaSWu Mianzhi     fn deref_mut(&mut self) -> &mut Self::Target {
5477799ccaSWu Mianzhi         unsafe { &mut *self.0.get() }
5577799ccaSWu Mianzhi     }
5677799ccaSWu Mianzhi }
5777799ccaSWu Mianzhi 
5877799ccaSWu Mianzhi impl E1000EDriverWrapper {
59*b5b571e0SLoGin     #[allow(clippy::mut_from_ref)]
6077799ccaSWu Mianzhi     fn force_get_mut(&self) -> &mut E1000EDriver {
6177799ccaSWu Mianzhi         unsafe { &mut *self.0.get() }
6277799ccaSWu Mianzhi     }
6377799ccaSWu Mianzhi }
6477799ccaSWu Mianzhi 
6577799ccaSWu Mianzhi impl Debug for E1000EDriverWrapper {
6677799ccaSWu Mianzhi     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
6777799ccaSWu Mianzhi         f.debug_struct("E1000ENICDriver").finish()
6877799ccaSWu Mianzhi     }
6977799ccaSWu Mianzhi }
7077799ccaSWu Mianzhi 
7177799ccaSWu Mianzhi pub struct E1000EInterface {
7277799ccaSWu Mianzhi     driver: E1000EDriverWrapper,
7377799ccaSWu Mianzhi     iface_id: usize,
7477799ccaSWu Mianzhi     iface: SpinLock<smoltcp::iface::Interface>,
7577799ccaSWu Mianzhi     name: String,
7677799ccaSWu Mianzhi }
7777799ccaSWu Mianzhi impl phy::RxToken for E1000ERxToken {
7877799ccaSWu Mianzhi     fn consume<R, F>(mut self, f: F) -> R
7977799ccaSWu Mianzhi     where
8077799ccaSWu Mianzhi         F: FnOnce(&mut [u8]) -> R,
8177799ccaSWu Mianzhi     {
82*b5b571e0SLoGin         let result = f(self.0.as_mut_slice());
8377799ccaSWu Mianzhi         self.0.free_buffer();
8477799ccaSWu Mianzhi         return result;
8577799ccaSWu Mianzhi     }
8677799ccaSWu Mianzhi }
8777799ccaSWu Mianzhi 
8877799ccaSWu Mianzhi impl phy::TxToken for E1000ETxToken {
89971462beSGnoCiYeH     fn consume<R, F>(self, _len: usize, f: F) -> R
9077799ccaSWu Mianzhi     where
9177799ccaSWu Mianzhi         F: FnOnce(&mut [u8]) -> R,
9277799ccaSWu Mianzhi     {
9377799ccaSWu Mianzhi         let mut buffer = E1000EBuffer::new(4096);
9477799ccaSWu Mianzhi         let result = f(buffer.as_mut_slice());
9577799ccaSWu Mianzhi         let mut device = self.driver.inner.lock();
9677799ccaSWu Mianzhi         device.e1000e_transmit(buffer);
972f6f547aSGnoCiYeH         buffer.free_buffer();
9877799ccaSWu Mianzhi         return result;
9977799ccaSWu Mianzhi     }
10077799ccaSWu Mianzhi }
10177799ccaSWu Mianzhi 
10277799ccaSWu Mianzhi impl E1000EDriver {
103*b5b571e0SLoGin     #[allow(clippy::arc_with_non_send_sync)]
10477799ccaSWu Mianzhi     pub fn new(device: E1000EDevice) -> Self {
10577799ccaSWu Mianzhi         let mut iface_config = smoltcp::iface::Config::new();
10677799ccaSWu Mianzhi 
10777799ccaSWu Mianzhi         // todo: 随机设定这个值。
10877799ccaSWu Mianzhi         // 参见 https://docs.rs/smoltcp/latest/smoltcp/iface/struct.Config.html#structfield.random_seed
10977799ccaSWu Mianzhi         iface_config.random_seed = 12345;
11077799ccaSWu Mianzhi 
11177799ccaSWu Mianzhi         iface_config.hardware_addr = Some(wire::HardwareAddress::Ethernet(
11277799ccaSWu Mianzhi             smoltcp::wire::EthernetAddress(device.mac_address()),
11377799ccaSWu Mianzhi         ));
11477799ccaSWu Mianzhi 
11577799ccaSWu Mianzhi         let inner: Arc<SpinLock<E1000EDevice>> = Arc::new(SpinLock::new(device));
11677799ccaSWu Mianzhi         let result = E1000EDriver { inner };
11777799ccaSWu Mianzhi         return result;
11877799ccaSWu Mianzhi     }
11977799ccaSWu Mianzhi }
12077799ccaSWu Mianzhi 
12177799ccaSWu Mianzhi impl Clone for E1000EDriver {
12277799ccaSWu Mianzhi     fn clone(&self) -> Self {
12377799ccaSWu Mianzhi         return E1000EDriver {
12477799ccaSWu Mianzhi             inner: self.inner.clone(),
12577799ccaSWu Mianzhi         };
12677799ccaSWu Mianzhi     }
12777799ccaSWu Mianzhi }
12877799ccaSWu Mianzhi 
12977799ccaSWu Mianzhi impl phy::Device for E1000EDriver {
13077799ccaSWu Mianzhi     type RxToken<'a> = E1000ERxToken;
13177799ccaSWu Mianzhi     type TxToken<'a> = E1000ETxToken;
13277799ccaSWu Mianzhi 
13377799ccaSWu Mianzhi     fn receive(
13477799ccaSWu Mianzhi         &mut self,
13577799ccaSWu Mianzhi         _timestamp: smoltcp::time::Instant,
13677799ccaSWu Mianzhi     ) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> {
13777799ccaSWu Mianzhi         match self.inner.lock().e1000e_receive() {
13877799ccaSWu Mianzhi             Some(buffer) => Some((
13977799ccaSWu Mianzhi                 E1000ERxToken(buffer),
14077799ccaSWu Mianzhi                 E1000ETxToken {
14177799ccaSWu Mianzhi                     driver: self.clone(),
14277799ccaSWu Mianzhi                 },
14377799ccaSWu Mianzhi             )),
14477799ccaSWu Mianzhi             None => {
14577799ccaSWu Mianzhi                 return None;
14677799ccaSWu Mianzhi             }
14777799ccaSWu Mianzhi         }
14877799ccaSWu Mianzhi     }
14977799ccaSWu Mianzhi 
15077799ccaSWu Mianzhi     fn transmit(&mut self, _timestamp: smoltcp::time::Instant) -> Option<Self::TxToken<'_>> {
15177799ccaSWu Mianzhi         match self.inner.lock().e1000e_can_transmit() {
15277799ccaSWu Mianzhi             true => Some(E1000ETxToken {
15377799ccaSWu Mianzhi                 driver: self.clone(),
15477799ccaSWu Mianzhi             }),
15577799ccaSWu Mianzhi             false => None,
15677799ccaSWu Mianzhi         }
15777799ccaSWu Mianzhi     }
15877799ccaSWu Mianzhi 
15977799ccaSWu Mianzhi     fn capabilities(&self) -> smoltcp::phy::DeviceCapabilities {
16077799ccaSWu Mianzhi         let mut caps = smoltcp::phy::DeviceCapabilities::default();
16177799ccaSWu Mianzhi         // 网卡的最大传输单元. 请与IP层的MTU进行区分。这个值应当是网卡的最大传输单元,而不是IP层的MTU。
16277799ccaSWu Mianzhi         // 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.
16377799ccaSWu Mianzhi         // 82574l manual pp205
16477799ccaSWu Mianzhi         caps.max_transmission_unit = 1536;
16577799ccaSWu Mianzhi         /*
16677799ccaSWu Mianzhi            Maximum burst size, in terms of MTU.
16777799ccaSWu Mianzhi            The network device is unable to send or receive bursts large than the value returned by this function.
16877799ccaSWu Mianzhi            If None, there is no fixed limit on burst size, e.g. if network buffers are dynamically allocated.
16977799ccaSWu Mianzhi         */
17077799ccaSWu Mianzhi         caps.max_burst_size = Some(1);
17177799ccaSWu Mianzhi         return caps;
17277799ccaSWu Mianzhi     }
17377799ccaSWu Mianzhi }
17477799ccaSWu Mianzhi 
17577799ccaSWu Mianzhi impl E1000EInterface {
17677799ccaSWu Mianzhi     pub fn new(mut driver: E1000EDriver) -> Arc<Self> {
17777799ccaSWu Mianzhi         let iface_id = generate_iface_id();
17877799ccaSWu Mianzhi         let mut iface_config = smoltcp::iface::Config::new();
17977799ccaSWu Mianzhi 
18077799ccaSWu Mianzhi         // todo: 随机设定这个值。
18177799ccaSWu Mianzhi         // 参见 https://docs.rs/smoltcp/latest/smoltcp/iface/struct.Config.html#structfield.random_seed
18277799ccaSWu Mianzhi         iface_config.random_seed = 12345;
18377799ccaSWu Mianzhi 
18477799ccaSWu Mianzhi         iface_config.hardware_addr = Some(wire::HardwareAddress::Ethernet(
18577799ccaSWu Mianzhi             smoltcp::wire::EthernetAddress(driver.inner.lock().mac_address()),
18677799ccaSWu Mianzhi         ));
18777799ccaSWu Mianzhi         let iface = smoltcp::iface::Interface::new(iface_config, &mut driver);
18877799ccaSWu Mianzhi 
18977799ccaSWu Mianzhi         let driver: E1000EDriverWrapper = E1000EDriverWrapper(UnsafeCell::new(driver));
19077799ccaSWu Mianzhi         let result = Arc::new(E1000EInterface {
19177799ccaSWu Mianzhi             driver,
19277799ccaSWu Mianzhi             iface_id,
19377799ccaSWu Mianzhi             iface: SpinLock::new(iface),
19477799ccaSWu Mianzhi             name: format!("eth{}", iface_id),
19577799ccaSWu Mianzhi         });
19677799ccaSWu Mianzhi 
19777799ccaSWu Mianzhi         return result;
19877799ccaSWu Mianzhi     }
19977799ccaSWu Mianzhi }
20077799ccaSWu Mianzhi 
20177799ccaSWu Mianzhi impl Debug for E1000EInterface {
20277799ccaSWu Mianzhi     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
20377799ccaSWu Mianzhi         f.debug_struct("E1000EInterface")
20477799ccaSWu Mianzhi             .field("iface_id", &self.iface_id)
20577799ccaSWu Mianzhi             .field("iface", &"smoltcp::iface::Interface")
20677799ccaSWu Mianzhi             .field("name", &self.name)
20777799ccaSWu Mianzhi             .finish()
20877799ccaSWu Mianzhi     }
20977799ccaSWu Mianzhi }
21077799ccaSWu Mianzhi 
21177799ccaSWu Mianzhi impl Driver for E1000EInterface {
21277799ccaSWu Mianzhi     fn id_table(&self) -> Option<IdTable> {
21377799ccaSWu Mianzhi         todo!()
21477799ccaSWu Mianzhi     }
21577799ccaSWu Mianzhi 
21677799ccaSWu Mianzhi     fn add_device(&self, _device: Arc<dyn Device>) {
21777799ccaSWu Mianzhi         todo!()
21877799ccaSWu Mianzhi     }
21977799ccaSWu Mianzhi 
22077799ccaSWu Mianzhi     fn delete_device(&self, _device: &Arc<dyn Device>) {
22177799ccaSWu Mianzhi         todo!()
22277799ccaSWu Mianzhi     }
22377799ccaSWu Mianzhi 
22477799ccaSWu Mianzhi     fn devices(&self) -> alloc::vec::Vec<Arc<dyn Device>> {
22577799ccaSWu Mianzhi         todo!()
22677799ccaSWu Mianzhi     }
22777799ccaSWu Mianzhi 
228c566df45SLoGin     fn bus(&self) -> Option<Weak<dyn Bus>> {
22977799ccaSWu Mianzhi         todo!()
23077799ccaSWu Mianzhi     }
23177799ccaSWu Mianzhi 
232c566df45SLoGin     fn set_bus(&self, _bus: Option<Weak<dyn Bus>>) {
23377799ccaSWu Mianzhi         todo!()
23477799ccaSWu Mianzhi     }
23577799ccaSWu Mianzhi }
23677799ccaSWu Mianzhi 
23777799ccaSWu Mianzhi impl NetDriver for E1000EInterface {
23877799ccaSWu Mianzhi     fn mac(&self) -> smoltcp::wire::EthernetAddress {
23977799ccaSWu Mianzhi         let mac = self.driver.inner.lock().mac_address();
24077799ccaSWu Mianzhi         return smoltcp::wire::EthernetAddress::from_bytes(&mac);
24177799ccaSWu Mianzhi     }
24277799ccaSWu Mianzhi 
24377799ccaSWu Mianzhi     #[inline]
24477799ccaSWu Mianzhi     fn nic_id(&self) -> usize {
24577799ccaSWu Mianzhi         return self.iface_id;
24677799ccaSWu Mianzhi     }
24777799ccaSWu Mianzhi 
24877799ccaSWu Mianzhi     #[inline]
24977799ccaSWu Mianzhi     fn name(&self) -> String {
25077799ccaSWu Mianzhi         return self.name.clone();
25177799ccaSWu Mianzhi     }
25277799ccaSWu Mianzhi 
25377799ccaSWu Mianzhi     fn update_ip_addrs(&self, ip_addrs: &[wire::IpCidr]) -> Result<(), SystemError> {
25477799ccaSWu Mianzhi         if ip_addrs.len() != 1 {
25577799ccaSWu Mianzhi             return Err(SystemError::EINVAL);
25677799ccaSWu Mianzhi         }
25777799ccaSWu Mianzhi 
25877799ccaSWu Mianzhi         self.iface.lock().update_ip_addrs(|addrs| {
25977799ccaSWu Mianzhi             let dest = addrs.iter_mut().next();
260*b5b571e0SLoGin 
261*b5b571e0SLoGin             if let Some(dest) = dest {
26277799ccaSWu Mianzhi                 *dest = ip_addrs[0];
263*b5b571e0SLoGin             } else {
264*b5b571e0SLoGin                 addrs.push(ip_addrs[0]).expect("Push ipCidr failed: full");
26577799ccaSWu Mianzhi             }
26677799ccaSWu Mianzhi         });
26777799ccaSWu Mianzhi         return Ok(());
26877799ccaSWu Mianzhi     }
26977799ccaSWu Mianzhi 
27091e9d4abSLoGin     fn poll(&self, sockets: &mut smoltcp::iface::SocketSet) -> Result<(), SystemError> {
27177799ccaSWu Mianzhi         let timestamp: smoltcp::time::Instant = Instant::now().into();
27277799ccaSWu Mianzhi         let mut guard = self.iface.lock();
27377799ccaSWu Mianzhi         let poll_res = guard.poll(timestamp, self.driver.force_get_mut(), sockets);
27477799ccaSWu Mianzhi         if poll_res {
27577799ccaSWu Mianzhi             return Ok(());
27677799ccaSWu Mianzhi         }
27777799ccaSWu Mianzhi         return Err(SystemError::EAGAIN_OR_EWOULDBLOCK);
27877799ccaSWu Mianzhi     }
27977799ccaSWu Mianzhi 
28077799ccaSWu Mianzhi     #[inline(always)]
28177799ccaSWu Mianzhi     fn inner_iface(&self) -> &SpinLock<smoltcp::iface::Interface> {
28277799ccaSWu Mianzhi         return &self.iface;
28377799ccaSWu Mianzhi     }
28477799ccaSWu Mianzhi }
28577799ccaSWu Mianzhi 
28677799ccaSWu Mianzhi impl KObject for E1000EInterface {
28777799ccaSWu Mianzhi     fn as_any_ref(&self) -> &dyn core::any::Any {
28877799ccaSWu Mianzhi         self
28977799ccaSWu Mianzhi     }
29077799ccaSWu Mianzhi 
29177799ccaSWu Mianzhi     fn set_inode(&self, _inode: Option<Arc<crate::filesystem::kernfs::KernFSInode>>) {
29277799ccaSWu Mianzhi         todo!()
29377799ccaSWu Mianzhi     }
29477799ccaSWu Mianzhi 
29577799ccaSWu Mianzhi     fn inode(&self) -> Option<Arc<crate::filesystem::kernfs::KernFSInode>> {
29677799ccaSWu Mianzhi         todo!()
29777799ccaSWu Mianzhi     }
29877799ccaSWu Mianzhi 
29977799ccaSWu Mianzhi     fn parent(&self) -> Option<alloc::sync::Weak<dyn KObject>> {
30077799ccaSWu Mianzhi         todo!()
30177799ccaSWu Mianzhi     }
30277799ccaSWu Mianzhi 
30377799ccaSWu Mianzhi     fn set_parent(&self, _parent: Option<alloc::sync::Weak<dyn KObject>>) {
30477799ccaSWu Mianzhi         todo!()
30577799ccaSWu Mianzhi     }
30677799ccaSWu Mianzhi 
30777799ccaSWu Mianzhi     fn kset(&self) -> Option<Arc<crate::driver::base::kset::KSet>> {
30877799ccaSWu Mianzhi         todo!()
30977799ccaSWu Mianzhi     }
31077799ccaSWu Mianzhi 
31177799ccaSWu Mianzhi     fn set_kset(&self, _kset: Option<Arc<crate::driver::base::kset::KSet>>) {
31277799ccaSWu Mianzhi         todo!()
31377799ccaSWu Mianzhi     }
31477799ccaSWu Mianzhi 
31577799ccaSWu Mianzhi     fn kobj_type(&self) -> Option<&'static dyn crate::driver::base::kobject::KObjType> {
31677799ccaSWu Mianzhi         todo!()
31777799ccaSWu Mianzhi     }
31877799ccaSWu Mianzhi 
31977799ccaSWu Mianzhi     fn name(&self) -> String {
32077799ccaSWu Mianzhi         self.name.clone()
32177799ccaSWu Mianzhi     }
32277799ccaSWu Mianzhi 
32377799ccaSWu Mianzhi     fn set_name(&self, _name: String) {
32477799ccaSWu Mianzhi         todo!()
32577799ccaSWu Mianzhi     }
32677799ccaSWu Mianzhi 
32777799ccaSWu Mianzhi     fn kobj_state(
32877799ccaSWu Mianzhi         &self,
32977799ccaSWu Mianzhi     ) -> crate::libs::rwlock::RwLockReadGuard<crate::driver::base::kobject::KObjectState> {
33077799ccaSWu Mianzhi         todo!()
33177799ccaSWu Mianzhi     }
33277799ccaSWu Mianzhi 
33377799ccaSWu Mianzhi     fn kobj_state_mut(
33477799ccaSWu Mianzhi         &self,
33577799ccaSWu Mianzhi     ) -> crate::libs::rwlock::RwLockWriteGuard<crate::driver::base::kobject::KObjectState> {
33677799ccaSWu Mianzhi         todo!()
33777799ccaSWu Mianzhi     }
33877799ccaSWu Mianzhi 
33977799ccaSWu Mianzhi     fn set_kobj_state(&self, _state: KObjectState) {
34077799ccaSWu Mianzhi         todo!()
34177799ccaSWu Mianzhi     }
34277799ccaSWu Mianzhi 
34377799ccaSWu Mianzhi     fn set_kobj_type(&self, _ktype: Option<&'static dyn KObjType>) {
34477799ccaSWu Mianzhi         todo!()
34577799ccaSWu Mianzhi     }
34677799ccaSWu Mianzhi }
34777799ccaSWu Mianzhi 
34877799ccaSWu Mianzhi pub fn e1000e_driver_init(device: E1000EDevice) {
34977799ccaSWu Mianzhi     let mac = smoltcp::wire::EthernetAddress::from_bytes(&device.mac_address());
35077799ccaSWu Mianzhi     let driver = E1000EDriver::new(device);
35177799ccaSWu Mianzhi     let iface = E1000EInterface::new(driver);
35277799ccaSWu Mianzhi     // 将网卡的接口信息注册到全局的网卡接口信息表中
3530d6cf65aSLoGin     NET_DRIVERS
3540d6cf65aSLoGin         .write_irqsave()
3550d6cf65aSLoGin         .insert(iface.nic_id(), iface.clone());
35677799ccaSWu Mianzhi     kinfo!("e1000e driver init successfully!\tMAC: [{}]", mac);
35777799ccaSWu Mianzhi }
358