xref: /DragonOS/kernel/src/driver/net/e1000e/e1000e_driver.rs (revision 4b0170bd6bb374d0e9699a0076cc23b976ad6db7)
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::{
17     string::String,
18     sync::{Arc, Weak},
19 };
20 use core::{
21     cell::UnsafeCell,
22     fmt::Debug,
23     ops::{Deref, DerefMut},
24 };
25 use smoltcp::{phy, wire};
26 use system_error::SystemError;
27 
28 use super::e1000e::{E1000EBuffer, E1000EDevice};
29 
30 pub struct E1000ERxToken(E1000EBuffer);
31 pub struct E1000ETxToken {
32     driver: E1000EDriver,
33 }
34 pub struct E1000EDriver {
35     pub inner: Arc<SpinLock<E1000EDevice>>,
36 }
37 unsafe impl Send for E1000EDriver {}
38 unsafe impl Sync for E1000EDriver {}
39 
40 /// @brief 网卡驱动的包裹器,这是为了获取网卡驱动的可变引用而设计的。
41 /// 参阅virtio_net.rs
42 struct E1000EDriverWrapper(UnsafeCell<E1000EDriver>);
43 unsafe impl Send for E1000EDriverWrapper {}
44 unsafe impl Sync for E1000EDriverWrapper {}
45 
46 impl Deref for E1000EDriverWrapper {
47     type Target = E1000EDriver;
48     fn deref(&self) -> &Self::Target {
49         unsafe { &*self.0.get() }
50     }
51 }
52 impl DerefMut for E1000EDriverWrapper {
53     fn deref_mut(&mut self) -> &mut Self::Target {
54         unsafe { &mut *self.0.get() }
55     }
56 }
57 
58 impl E1000EDriverWrapper {
59     #[allow(clippy::mut_from_ref)]
60     fn force_get_mut(&self) -> &mut E1000EDriver {
61         unsafe { &mut *self.0.get() }
62     }
63 }
64 
65 impl Debug for E1000EDriverWrapper {
66     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
67         f.debug_struct("E1000ENICDriver").finish()
68     }
69 }
70 
71 pub struct E1000EInterface {
72     driver: E1000EDriverWrapper,
73     iface_id: usize,
74     iface: SpinLock<smoltcp::iface::Interface>,
75     name: String,
76 }
77 impl phy::RxToken for E1000ERxToken {
78     fn consume<R, F>(mut self, f: F) -> R
79     where
80         F: FnOnce(&mut [u8]) -> R,
81     {
82         let result = f(self.0.as_mut_slice());
83         self.0.free_buffer();
84         return result;
85     }
86 }
87 
88 impl phy::TxToken for E1000ETxToken {
89     fn consume<R, F>(self, _len: usize, f: F) -> R
90     where
91         F: FnOnce(&mut [u8]) -> R,
92     {
93         let mut buffer = E1000EBuffer::new(4096);
94         let result = f(buffer.as_mut_slice());
95         let mut device = self.driver.inner.lock();
96         device.e1000e_transmit(buffer);
97         buffer.free_buffer();
98         return result;
99     }
100 }
101 
102 impl E1000EDriver {
103     #[allow(clippy::arc_with_non_send_sync)]
104     pub fn new(device: E1000EDevice) -> Self {
105         let mut iface_config = smoltcp::iface::Config::new();
106 
107         // todo: 随机设定这个值。
108         // 参见 https://docs.rs/smoltcp/latest/smoltcp/iface/struct.Config.html#structfield.random_seed
109         iface_config.random_seed = 12345;
110 
111         iface_config.hardware_addr = Some(wire::HardwareAddress::Ethernet(
112             smoltcp::wire::EthernetAddress(device.mac_address()),
113         ));
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();
179 
180         // todo: 随机设定这个值。
181         // 参见 https://docs.rs/smoltcp/latest/smoltcp/iface/struct.Config.html#structfield.random_seed
182         iface_config.random_seed = 12345;
183 
184         iface_config.hardware_addr = Some(wire::HardwareAddress::Ethernet(
185             smoltcp::wire::EthernetAddress(driver.inner.lock().mac_address()),
186         ));
187         let iface = smoltcp::iface::Interface::new(iface_config, &mut driver);
188 
189         let driver: E1000EDriverWrapper = E1000EDriverWrapper(UnsafeCell::new(driver));
190         let result = Arc::new(E1000EInterface {
191             driver,
192             iface_id,
193             iface: SpinLock::new(iface),
194             name: format!("eth{}", iface_id),
195         });
196 
197         return result;
198     }
199 }
200 
201 impl Debug for E1000EInterface {
202     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
203         f.debug_struct("E1000EInterface")
204             .field("iface_id", &self.iface_id)
205             .field("iface", &"smoltcp::iface::Interface")
206             .field("name", &self.name)
207             .finish()
208     }
209 }
210 
211 impl Driver for E1000EInterface {
212     fn id_table(&self) -> Option<IdTable> {
213         todo!()
214     }
215 
216     fn add_device(&self, _device: Arc<dyn Device>) {
217         todo!()
218     }
219 
220     fn delete_device(&self, _device: &Arc<dyn Device>) {
221         todo!()
222     }
223 
224     fn devices(&self) -> alloc::vec::Vec<Arc<dyn Device>> {
225         todo!()
226     }
227 
228     fn bus(&self) -> Option<Weak<dyn Bus>> {
229         todo!()
230     }
231 
232     fn set_bus(&self, _bus: Option<Weak<dyn Bus>>) {
233         todo!()
234     }
235 }
236 
237 impl NetDriver for E1000EInterface {
238     fn mac(&self) -> smoltcp::wire::EthernetAddress {
239         let mac = self.driver.inner.lock().mac_address();
240         return smoltcp::wire::EthernetAddress::from_bytes(&mac);
241     }
242 
243     #[inline]
244     fn nic_id(&self) -> usize {
245         return self.iface_id;
246     }
247 
248     #[inline]
249     fn name(&self) -> String {
250         return self.name.clone();
251     }
252 
253     fn update_ip_addrs(&self, ip_addrs: &[wire::IpCidr]) -> Result<(), SystemError> {
254         if ip_addrs.len() != 1 {
255             return Err(SystemError::EINVAL);
256         }
257 
258         self.iface.lock().update_ip_addrs(|addrs| {
259             let dest = addrs.iter_mut().next();
260 
261             if let Some(dest) = dest {
262                 *dest = ip_addrs[0];
263             } else {
264                 addrs.push(ip_addrs[0]).expect("Push ipCidr failed: full");
265             }
266         });
267         return Ok(());
268     }
269 
270     fn poll(&self, sockets: &mut smoltcp::iface::SocketSet) -> Result<(), SystemError> {
271         let timestamp: smoltcp::time::Instant = Instant::now().into();
272         let mut guard = self.iface.lock();
273         let poll_res = guard.poll(timestamp, self.driver.force_get_mut(), sockets);
274         if poll_res {
275             return Ok(());
276         }
277         return Err(SystemError::EAGAIN_OR_EWOULDBLOCK);
278     }
279 
280     #[inline(always)]
281     fn inner_iface(&self) -> &SpinLock<smoltcp::iface::Interface> {
282         return &self.iface;
283     }
284 }
285 
286 impl KObject for E1000EInterface {
287     fn as_any_ref(&self) -> &dyn core::any::Any {
288         self
289     }
290 
291     fn set_inode(&self, _inode: Option<Arc<crate::filesystem::kernfs::KernFSInode>>) {
292         todo!()
293     }
294 
295     fn inode(&self) -> Option<Arc<crate::filesystem::kernfs::KernFSInode>> {
296         todo!()
297     }
298 
299     fn parent(&self) -> Option<alloc::sync::Weak<dyn KObject>> {
300         todo!()
301     }
302 
303     fn set_parent(&self, _parent: Option<alloc::sync::Weak<dyn KObject>>) {
304         todo!()
305     }
306 
307     fn kset(&self) -> Option<Arc<crate::driver::base::kset::KSet>> {
308         todo!()
309     }
310 
311     fn set_kset(&self, _kset: Option<Arc<crate::driver::base::kset::KSet>>) {
312         todo!()
313     }
314 
315     fn kobj_type(&self) -> Option<&'static dyn crate::driver::base::kobject::KObjType> {
316         todo!()
317     }
318 
319     fn name(&self) -> String {
320         self.name.clone()
321     }
322 
323     fn set_name(&self, _name: String) {
324         todo!()
325     }
326 
327     fn kobj_state(
328         &self,
329     ) -> crate::libs::rwlock::RwLockReadGuard<crate::driver::base::kobject::KObjectState> {
330         todo!()
331     }
332 
333     fn kobj_state_mut(
334         &self,
335     ) -> crate::libs::rwlock::RwLockWriteGuard<crate::driver::base::kobject::KObjectState> {
336         todo!()
337     }
338 
339     fn set_kobj_state(&self, _state: KObjectState) {
340         todo!()
341     }
342 
343     fn set_kobj_type(&self, _ktype: Option<&'static dyn KObjType>) {
344         todo!()
345     }
346 }
347 
348 pub fn e1000e_driver_init(device: E1000EDevice) {
349     let mac = smoltcp::wire::EthernetAddress::from_bytes(&device.mac_address());
350     let driver = E1000EDriver::new(device);
351     let iface = E1000EInterface::new(driver);
352     // 将网卡的接口信息注册到全局的网卡接口信息表中
353     NET_DRIVERS
354         .write_irqsave()
355         .insert(iface.nic_id(), iface.clone());
356     kinfo!("e1000e driver init successfully!\tMAC: [{}]", mac);
357 }
358