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