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