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