xref: /DragonOS/kernel/src/driver/net/e1000e/e1000e_driver.rs (revision c635d8a9cfe25bc11779f323ef0c7d7a0f597d4a)
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, DeviceCommonData, DeviceType, IdTable},
9             kobject::{KObjType, KObject, KObjectCommonData, KObjectState, LockedKObjectState},
10         },
11         net::{register_netdevice, NetDeivceState, NetDevice, NetDeviceCommonData, Operstate},
12     },
13     libs::{
14         rwlock::{RwLockReadGuard, RwLockWriteGuard},
15         spinlock::{SpinLock, SpinLockGuard},
16     },
17     net::{generate_iface_id, NET_DEVICES},
18     time::Instant,
19 };
20 use alloc::{
21     string::{String, ToString},
22     sync::{Arc, Weak},
23 };
24 use core::{
25     cell::UnsafeCell,
26     fmt::Debug,
27     ops::{Deref, DerefMut},
28 };
29 use log::info;
30 use smoltcp::{
31     phy,
32     wire::{self, HardwareAddress},
33 };
34 use system_error::SystemError;
35 
36 use super::e1000e::{E1000EBuffer, E1000EDevice};
37 
38 const DEVICE_NAME: &str = "e1000e";
39 
40 pub struct E1000ERxToken(E1000EBuffer);
41 pub struct E1000ETxToken {
42     driver: E1000EDriver,
43 }
44 pub struct E1000EDriver {
45     pub inner: Arc<SpinLock<E1000EDevice>>,
46 }
47 unsafe impl Send for E1000EDriver {}
48 unsafe impl Sync for E1000EDriver {}
49 
50 /// @brief 网卡驱动的包裹器,这是为了获取网卡驱动的可变引用而设计的。
51 /// 参阅virtio_net.rs
52 struct E1000EDriverWrapper(UnsafeCell<E1000EDriver>);
53 unsafe impl Send for E1000EDriverWrapper {}
54 unsafe impl Sync for E1000EDriverWrapper {}
55 
56 impl Deref for E1000EDriverWrapper {
57     type Target = E1000EDriver;
58     fn deref(&self) -> &Self::Target {
59         unsafe { &*self.0.get() }
60     }
61 }
62 impl DerefMut for E1000EDriverWrapper {
63     fn deref_mut(&mut self) -> &mut Self::Target {
64         unsafe { &mut *self.0.get() }
65     }
66 }
67 
68 impl E1000EDriverWrapper {
69     #[allow(clippy::mut_from_ref)]
70     fn force_get_mut(&self) -> &mut E1000EDriver {
71         unsafe { &mut *self.0.get() }
72     }
73 }
74 
75 impl Debug for E1000EDriverWrapper {
76     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
77         f.debug_struct("E1000ENICDriver").finish()
78     }
79 }
80 
81 #[cast_to([sync] NetDevice)]
82 #[cast_to([sync] Device)]
83 pub struct E1000EInterface {
84     driver: E1000EDriverWrapper,
85     iface_id: usize,
86     iface: SpinLock<smoltcp::iface::Interface>,
87     name: String,
88     inner: SpinLock<InnerE1000EInterface>,
89     locked_kobj_state: LockedKObjectState,
90 }
91 
92 #[derive(Debug)]
93 pub struct InnerE1000EInterface {
94     netdevice_common: NetDeviceCommonData,
95     device_common: DeviceCommonData,
96     kobj_common: KObjectCommonData,
97 }
98 
99 impl phy::RxToken for E1000ERxToken {
100     fn consume<R, F>(mut self, f: F) -> R
101     where
102         F: FnOnce(&mut [u8]) -> R,
103     {
104         let result = f(self.0.as_mut_slice());
105         self.0.free_buffer();
106         return result;
107     }
108 }
109 
110 impl phy::TxToken for E1000ETxToken {
111     fn consume<R, F>(self, _len: usize, f: F) -> R
112     where
113         F: FnOnce(&mut [u8]) -> R,
114     {
115         let mut buffer = E1000EBuffer::new(4096);
116         let result = f(buffer.as_mut_slice());
117         let mut device = self.driver.inner.lock();
118         device.e1000e_transmit(buffer);
119         buffer.free_buffer();
120         return result;
121     }
122 }
123 
124 impl E1000EDriver {
125     #[allow(clippy::arc_with_non_send_sync)]
126     pub fn new(device: E1000EDevice) -> Self {
127         let mut iface_config = smoltcp::iface::Config::new(HardwareAddress::Ethernet(
128             smoltcp::wire::EthernetAddress(device.mac_address()),
129         ));
130 
131         iface_config.random_seed = rand() as u64;
132 
133         let inner: Arc<SpinLock<E1000EDevice>> = Arc::new(SpinLock::new(device));
134         let result = E1000EDriver { inner };
135         return result;
136     }
137 }
138 
139 impl Clone for E1000EDriver {
140     fn clone(&self) -> Self {
141         return E1000EDriver {
142             inner: self.inner.clone(),
143         };
144     }
145 }
146 
147 impl phy::Device for E1000EDriver {
148     type RxToken<'a> = E1000ERxToken;
149     type TxToken<'a> = E1000ETxToken;
150 
151     fn receive(
152         &mut self,
153         _timestamp: smoltcp::time::Instant,
154     ) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> {
155         match self.inner.lock().e1000e_receive() {
156             Some(buffer) => Some((
157                 E1000ERxToken(buffer),
158                 E1000ETxToken {
159                     driver: self.clone(),
160                 },
161             )),
162             None => {
163                 return None;
164             }
165         }
166     }
167 
168     fn transmit(&mut self, _timestamp: smoltcp::time::Instant) -> Option<Self::TxToken<'_>> {
169         match self.inner.lock().e1000e_can_transmit() {
170             true => Some(E1000ETxToken {
171                 driver: self.clone(),
172             }),
173             false => None,
174         }
175     }
176 
177     fn capabilities(&self) -> smoltcp::phy::DeviceCapabilities {
178         let mut caps = smoltcp::phy::DeviceCapabilities::default();
179         // 网卡的最大传输单元. 请与IP层的MTU进行区分。这个值应当是网卡的最大传输单元,而不是IP层的MTU。
180         // 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.
181         // 82574l manual pp205
182         caps.max_transmission_unit = 1536;
183         /*
184            Maximum burst size, in terms of MTU.
185            The network device is unable to send or receive bursts large than the value returned by this function.
186            If None, there is no fixed limit on burst size, e.g. if network buffers are dynamically allocated.
187         */
188         caps.max_burst_size = Some(1);
189         return caps;
190     }
191 }
192 
193 impl E1000EInterface {
194     pub fn new(mut driver: E1000EDriver) -> Arc<Self> {
195         let iface_id = generate_iface_id();
196         let mut iface_config = smoltcp::iface::Config::new(HardwareAddress::Ethernet(
197             smoltcp::wire::EthernetAddress(driver.inner.lock().mac_address()),
198         ));
199         iface_config.random_seed = rand() as u64;
200 
201         let iface =
202             smoltcp::iface::Interface::new(iface_config, &mut driver, Instant::now().into());
203 
204         let driver: E1000EDriverWrapper = E1000EDriverWrapper(UnsafeCell::new(driver));
205         let result = Arc::new(E1000EInterface {
206             driver,
207             iface_id,
208             iface: SpinLock::new(iface),
209             name: format!("eth{}", iface_id),
210             inner: SpinLock::new(InnerE1000EInterface {
211                 netdevice_common: NetDeviceCommonData::default(),
212                 device_common: DeviceCommonData::default(),
213                 kobj_common: KObjectCommonData::default(),
214             }),
215             locked_kobj_state: LockedKObjectState::default(),
216         });
217 
218         return result;
219     }
220 
221     pub fn inner(&self) -> SpinLockGuard<InnerE1000EInterface> {
222         return self.inner.lock();
223     }
224 }
225 
226 impl Debug for E1000EInterface {
227     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
228         f.debug_struct("E1000EInterface")
229             .field("iface_id", &self.iface_id)
230             .field("iface", &"smoltcp::iface::Interface")
231             .field("name", &self.name)
232             .finish()
233     }
234 }
235 
236 impl Device for E1000EInterface {
237     fn dev_type(&self) -> DeviceType {
238         DeviceType::Net
239     }
240 
241     fn id_table(&self) -> IdTable {
242         IdTable::new(DEVICE_NAME.to_string(), None)
243     }
244 
245     fn bus(&self) -> Option<Weak<dyn Bus>> {
246         self.inner().device_common.bus.clone()
247     }
248 
249     fn set_bus(&self, bus: Option<Weak<dyn Bus>>) {
250         self.inner().device_common.bus = bus;
251     }
252 
253     fn class(&self) -> Option<Arc<dyn Class>> {
254         let mut guard = self.inner();
255         let r = guard.device_common.class.clone()?.upgrade();
256         if r.is_none() {
257             guard.device_common.class = None;
258         }
259 
260         return r;
261     }
262 
263     fn set_class(&self, class: Option<Weak<dyn Class>>) {
264         self.inner().device_common.class = class;
265     }
266 
267     fn driver(&self) -> Option<Arc<dyn Driver>> {
268         let r = self.inner().device_common.driver.clone()?.upgrade();
269         if r.is_none() {
270             self.inner().device_common.driver = None;
271         }
272 
273         return r;
274     }
275 
276     fn set_driver(&self, driver: Option<Weak<dyn Driver>>) {
277         self.inner().device_common.driver = driver;
278     }
279 
280     fn is_dead(&self) -> bool {
281         false
282     }
283 
284     fn can_match(&self) -> bool {
285         self.inner().device_common.can_match
286     }
287 
288     fn set_can_match(&self, can_match: bool) {
289         self.inner().device_common.can_match = can_match;
290     }
291 
292     fn state_synced(&self) -> bool {
293         true
294     }
295 
296     fn dev_parent(&self) -> Option<Weak<dyn Device>> {
297         self.inner().device_common.get_parent_weak_or_clear()
298     }
299 
300     fn set_dev_parent(&self, parent: Option<Weak<dyn Device>>) {
301         self.inner().device_common.parent = parent;
302     }
303 }
304 
305 impl NetDevice for E1000EInterface {
306     fn mac(&self) -> smoltcp::wire::EthernetAddress {
307         let mac = self.driver.inner.lock().mac_address();
308         return smoltcp::wire::EthernetAddress::from_bytes(&mac);
309     }
310 
311     #[inline]
312     fn nic_id(&self) -> usize {
313         return self.iface_id;
314     }
315 
316     #[inline]
317     fn iface_name(&self) -> String {
318         return self.name.clone();
319     }
320 
321     fn update_ip_addrs(&self, ip_addrs: &[wire::IpCidr]) -> Result<(), SystemError> {
322         if ip_addrs.len() != 1 {
323             return Err(SystemError::EINVAL);
324         }
325 
326         self.iface.lock().update_ip_addrs(|addrs| {
327             let dest = addrs.iter_mut().next();
328 
329             if let Some(dest) = dest {
330                 *dest = ip_addrs[0];
331             } else {
332                 addrs.push(ip_addrs[0]).expect("Push ipCidr failed: full");
333             }
334         });
335         return Ok(());
336     }
337 
338     fn poll(&self, sockets: &mut smoltcp::iface::SocketSet) -> Result<(), SystemError> {
339         let timestamp: smoltcp::time::Instant = Instant::now().into();
340         let mut guard = self.iface.lock();
341         let poll_res = guard.poll(timestamp, self.driver.force_get_mut(), sockets);
342         if poll_res {
343             return Ok(());
344         }
345         return Err(SystemError::EAGAIN_OR_EWOULDBLOCK);
346     }
347 
348     #[inline(always)]
349     fn inner_iface(&self) -> &SpinLock<smoltcp::iface::Interface> {
350         return &self.iface;
351     }
352 
353     fn addr_assign_type(&self) -> u8 {
354         return self.inner().netdevice_common.addr_assign_type;
355     }
356 
357     fn net_device_type(&self) -> u16 {
358         self.inner().netdevice_common.net_device_type = 1; // 以太网设备
359         return self.inner().netdevice_common.net_device_type;
360     }
361 
362     fn net_state(&self) -> NetDeivceState {
363         return self.inner().netdevice_common.state;
364     }
365 
366     fn set_net_state(&self, state: NetDeivceState) {
367         self.inner().netdevice_common.state |= state;
368     }
369 
370     fn operstate(&self) -> Operstate {
371         return self.inner().netdevice_common.operstate;
372     }
373 
374     fn set_operstate(&self, state: Operstate) {
375         self.inner().netdevice_common.operstate = state;
376     }
377 }
378 
379 impl KObject for E1000EInterface {
380     fn as_any_ref(&self) -> &dyn core::any::Any {
381         self
382     }
383 
384     fn set_inode(&self, inode: Option<Arc<crate::filesystem::kernfs::KernFSInode>>) {
385         self.inner().kobj_common.kern_inode = inode;
386     }
387 
388     fn inode(&self) -> Option<Arc<crate::filesystem::kernfs::KernFSInode>> {
389         self.inner().kobj_common.kern_inode.clone()
390     }
391 
392     fn parent(&self) -> Option<alloc::sync::Weak<dyn KObject>> {
393         self.inner().kobj_common.parent.clone()
394     }
395 
396     fn set_parent(&self, parent: Option<alloc::sync::Weak<dyn KObject>>) {
397         self.inner().kobj_common.parent = parent;
398     }
399 
400     fn kset(&self) -> Option<Arc<crate::driver::base::kset::KSet>> {
401         self.inner().kobj_common.kset.clone()
402     }
403 
404     fn set_kset(&self, kset: Option<Arc<crate::driver::base::kset::KSet>>) {
405         self.inner().kobj_common.kset = kset;
406     }
407 
408     fn kobj_type(&self) -> Option<&'static dyn crate::driver::base::kobject::KObjType> {
409         self.inner().kobj_common.kobj_type
410     }
411 
412     fn name(&self) -> String {
413         self.name.clone()
414     }
415 
416     fn set_name(&self, _name: String) {
417         // do nothing
418     }
419 
420     fn kobj_state(&self) -> RwLockReadGuard<KObjectState> {
421         self.locked_kobj_state.read()
422     }
423 
424     fn kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState> {
425         self.locked_kobj_state.write()
426     }
427 
428     fn set_kobj_state(&self, state: KObjectState) {
429         *self.locked_kobj_state.write() = state;
430     }
431 
432     fn set_kobj_type(&self, ktype: Option<&'static dyn KObjType>) {
433         self.inner().kobj_common.kobj_type = ktype;
434     }
435 }
436 
437 pub fn e1000e_driver_init(device: E1000EDevice) {
438     let mac = smoltcp::wire::EthernetAddress::from_bytes(&device.mac_address());
439     let driver = E1000EDriver::new(device);
440     let iface = E1000EInterface::new(driver);
441     // 标识网络设备已经启动
442     iface.set_net_state(NetDeivceState::__LINK_STATE_START);
443 
444     // 将网卡的接口信息注册到全局的网卡接口信息表中
445     NET_DEVICES
446         .write_irqsave()
447         .insert(iface.nic_id(), iface.clone());
448     info!("e1000e driver init successfully!\tMAC: [{}]", mac);
449 
450     register_netdevice(iface.clone()).expect("register lo device failed");
451 }
452