xref: /DragonOS/kernel/src/driver/net/virtio_net.rs (revision 7c28051e8c601312d3d0fd7bcb71bc71450d10c0)
1 use core::{
2     any::Any,
3     cell::UnsafeCell,
4     fmt::Debug,
5     ops::{Deref, DerefMut},
6 };
7 
8 use alloc::{
9     collections::LinkedList,
10     string::{String, ToString},
11     sync::{Arc, Weak},
12     vec::Vec,
13 };
14 use log::{debug, error};
15 use smoltcp::{iface, phy, wire};
16 use unified_init::macros::unified_init;
17 use virtio_drivers::device::net::VirtIONet;
18 
19 use super::{NetDeivceState, NetDevice, NetDeviceCommonData, Operstate};
20 use crate::{
21     arch::rand::rand,
22     driver::{
23         base::{
24             class::Class,
25             device::{
26                 bus::Bus,
27                 driver::{Driver, DriverCommonData},
28                 Device, DeviceCommonData, DeviceId, DeviceType, IdTable,
29             },
30             kobject::{KObjType, KObject, KObjectCommonData, KObjectState, LockedKObjectState},
31             kset::KSet,
32         },
33         net::register_netdevice,
34         virtio::{
35             irq::virtio_irq_manager,
36             sysfs::{virtio_bus, virtio_device_manager, virtio_driver_manager},
37             transport::VirtIOTransport,
38             virtio_impl::HalImpl,
39             VirtIODevice, VirtIODeviceIndex, VirtIODriver, VirtIODriverCommonData, VirtioDeviceId,
40             VIRTIO_VENDOR_ID,
41         },
42     },
43     exception::{irqdesc::IrqReturn, IrqNumber},
44     filesystem::kernfs::KernFSInode,
45     init::initcall::INITCALL_POSTCORE,
46     libs::{
47         rwlock::{RwLockReadGuard, RwLockWriteGuard},
48         spinlock::{SpinLock, SpinLockGuard},
49     },
50     net::{generate_iface_id, net_core::poll_ifaces_try_lock_onetime, NET_DEVICES},
51     time::Instant,
52 };
53 use system_error::SystemError;
54 
55 static mut VIRTIO_NET_DRIVER: Option<Arc<VirtIONetDriver>> = None;
56 
57 const VIRTIO_NET_BASENAME: &str = "virtio_net";
58 
59 #[inline(always)]
60 #[allow(dead_code)]
virtio_net_driver() -> Arc<VirtIONetDriver>61 fn virtio_net_driver() -> Arc<VirtIONetDriver> {
62     unsafe { VIRTIO_NET_DRIVER.as_ref().unwrap().clone() }
63 }
64 
65 /// virtio net device
66 #[derive(Debug)]
67 #[cast_to([sync] VirtIODevice)]
68 #[cast_to([sync] Device)]
69 pub struct VirtIONetDevice {
70     dev_id: Arc<DeviceId>,
71     inner: SpinLock<InnerVirtIONetDevice>,
72     locked_kobj_state: LockedKObjectState,
73 }
74 
75 unsafe impl Send for VirtIONetDevice {}
76 unsafe impl Sync for VirtIONetDevice {}
77 
78 struct InnerVirtIONetDevice {
79     device_inner: VirtIONicDeviceInner,
80     name: Option<String>,
81     virtio_index: Option<VirtIODeviceIndex>,
82     kobj_common: KObjectCommonData,
83     device_common: DeviceCommonData,
84 }
85 
86 impl Debug for InnerVirtIONetDevice {
fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result87     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
88         f.debug_struct("InnerVirtIOBlkDevice").finish()
89     }
90 }
91 
92 impl VirtIONetDevice {
new(transport: VirtIOTransport, dev_id: Arc<DeviceId>) -> Option<Arc<Self>>93     pub fn new(transport: VirtIOTransport, dev_id: Arc<DeviceId>) -> Option<Arc<Self>> {
94         // 设置中断
95         if let Err(err) = transport.setup_irq(dev_id.clone()) {
96             error!("VirtIONetDevice '{dev_id:?}' setup_irq failed: {:?}", err);
97             return None;
98         }
99 
100         let driver_net: VirtIONet<HalImpl, VirtIOTransport, 2> =
101             match VirtIONet::<HalImpl, VirtIOTransport, 2>::new(transport, 4096) {
102                 Ok(net) => net,
103                 Err(_) => {
104                     error!("VirtIONet init failed");
105                     return None;
106                 }
107             };
108         let mac = wire::EthernetAddress::from_bytes(&driver_net.mac_address());
109         debug!("VirtIONetDevice mac: {:?}", mac);
110         let device_inner = VirtIONicDeviceInner::new(driver_net);
111 
112         let dev = Arc::new(Self {
113             dev_id,
114             inner: SpinLock::new(InnerVirtIONetDevice {
115                 device_inner,
116                 name: None,
117                 virtio_index: None,
118                 kobj_common: KObjectCommonData::default(),
119                 device_common: DeviceCommonData::default(),
120             }),
121             locked_kobj_state: LockedKObjectState::default(),
122         });
123 
124         // dev.set_driver(Some(Arc::downgrade(&virtio_net_driver()) as Weak<dyn Driver>));
125 
126         return Some(dev);
127     }
128 
inner(&self) -> SpinLockGuard<InnerVirtIONetDevice>129     fn inner(&self) -> SpinLockGuard<InnerVirtIONetDevice> {
130         return self.inner.lock();
131     }
132 }
133 
134 impl KObject for VirtIONetDevice {
as_any_ref(&self) -> &dyn Any135     fn as_any_ref(&self) -> &dyn Any {
136         self
137     }
138 
set_inode(&self, inode: Option<Arc<KernFSInode>>)139     fn set_inode(&self, inode: Option<Arc<KernFSInode>>) {
140         self.inner().kobj_common.kern_inode = inode;
141     }
142 
inode(&self) -> Option<Arc<KernFSInode>>143     fn inode(&self) -> Option<Arc<KernFSInode>> {
144         self.inner().kobj_common.kern_inode.clone()
145     }
146 
parent(&self) -> Option<Weak<dyn KObject>>147     fn parent(&self) -> Option<Weak<dyn KObject>> {
148         self.inner().kobj_common.parent.clone()
149     }
150 
set_parent(&self, parent: Option<Weak<dyn KObject>>)151     fn set_parent(&self, parent: Option<Weak<dyn KObject>>) {
152         self.inner().kobj_common.parent = parent;
153     }
154 
kset(&self) -> Option<Arc<KSet>>155     fn kset(&self) -> Option<Arc<KSet>> {
156         self.inner().kobj_common.kset.clone()
157     }
158 
set_kset(&self, kset: Option<Arc<KSet>>)159     fn set_kset(&self, kset: Option<Arc<KSet>>) {
160         self.inner().kobj_common.kset = kset;
161     }
162 
kobj_type(&self) -> Option<&'static dyn KObjType>163     fn kobj_type(&self) -> Option<&'static dyn KObjType> {
164         self.inner().kobj_common.kobj_type
165     }
166 
set_kobj_type(&self, ktype: Option<&'static dyn KObjType>)167     fn set_kobj_type(&self, ktype: Option<&'static dyn KObjType>) {
168         self.inner().kobj_common.kobj_type = ktype;
169     }
170 
name(&self) -> String171     fn name(&self) -> String {
172         self.device_name()
173     }
174 
set_name(&self, _name: String)175     fn set_name(&self, _name: String) {
176         // do nothing
177     }
178 
kobj_state(&self) -> RwLockReadGuard<KObjectState>179     fn kobj_state(&self) -> RwLockReadGuard<KObjectState> {
180         self.locked_kobj_state.read()
181     }
182 
kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState>183     fn kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState> {
184         self.locked_kobj_state.write()
185     }
186 
set_kobj_state(&self, state: KObjectState)187     fn set_kobj_state(&self, state: KObjectState) {
188         *self.locked_kobj_state.write() = state;
189     }
190 }
191 
192 impl Device for VirtIONetDevice {
dev_type(&self) -> DeviceType193     fn dev_type(&self) -> DeviceType {
194         DeviceType::Net
195     }
196 
id_table(&self) -> IdTable197     fn id_table(&self) -> IdTable {
198         IdTable::new(VIRTIO_NET_BASENAME.to_string(), None)
199     }
200 
bus(&self) -> Option<Weak<dyn Bus>>201     fn bus(&self) -> Option<Weak<dyn Bus>> {
202         self.inner().device_common.bus.clone()
203     }
204 
set_bus(&self, bus: Option<Weak<dyn Bus>>)205     fn set_bus(&self, bus: Option<Weak<dyn Bus>>) {
206         self.inner().device_common.bus = bus;
207     }
208 
class(&self) -> Option<Arc<dyn Class>>209     fn class(&self) -> Option<Arc<dyn Class>> {
210         let mut guard = self.inner();
211         let r = guard.device_common.class.clone()?.upgrade();
212         if r.is_none() {
213             guard.device_common.class = None;
214         }
215 
216         return r;
217     }
218 
set_class(&self, class: Option<Weak<dyn Class>>)219     fn set_class(&self, class: Option<Weak<dyn Class>>) {
220         self.inner().device_common.class = class;
221     }
222 
driver(&self) -> Option<Arc<dyn Driver>>223     fn driver(&self) -> Option<Arc<dyn Driver>> {
224         let r = self.inner().device_common.driver.clone()?.upgrade();
225         if r.is_none() {
226             self.inner().device_common.driver = None;
227         }
228 
229         return r;
230     }
231 
set_driver(&self, driver: Option<Weak<dyn Driver>>)232     fn set_driver(&self, driver: Option<Weak<dyn Driver>>) {
233         self.inner().device_common.driver = driver;
234     }
235 
is_dead(&self) -> bool236     fn is_dead(&self) -> bool {
237         false
238     }
239 
can_match(&self) -> bool240     fn can_match(&self) -> bool {
241         self.inner().device_common.can_match
242     }
243 
set_can_match(&self, can_match: bool)244     fn set_can_match(&self, can_match: bool) {
245         self.inner().device_common.can_match = can_match;
246     }
state_synced(&self) -> bool247     fn state_synced(&self) -> bool {
248         true
249     }
250 
dev_parent(&self) -> Option<Weak<dyn Device>>251     fn dev_parent(&self) -> Option<Weak<dyn Device>> {
252         self.inner().device_common.get_parent_weak_or_clear()
253     }
254 
set_dev_parent(&self, parent: Option<Weak<dyn Device>>)255     fn set_dev_parent(&self, parent: Option<Weak<dyn Device>>) {
256         self.inner().device_common.parent = parent;
257     }
258 }
259 
260 impl VirtIODevice for VirtIONetDevice {
handle_irq(&self, _irq: IrqNumber) -> Result<IrqReturn, SystemError>261     fn handle_irq(&self, _irq: IrqNumber) -> Result<IrqReturn, SystemError> {
262         poll_ifaces_try_lock_onetime().ok();
263         return Ok(IrqReturn::Handled);
264     }
265 
dev_id(&self) -> &Arc<DeviceId>266     fn dev_id(&self) -> &Arc<DeviceId> {
267         return &self.dev_id;
268     }
269 
set_device_name(&self, name: String)270     fn set_device_name(&self, name: String) {
271         self.inner().name = Some(name);
272     }
273 
device_name(&self) -> String274     fn device_name(&self) -> String {
275         self.inner()
276             .name
277             .clone()
278             .unwrap_or_else(|| "virtio_net".to_string())
279     }
280 
set_virtio_device_index(&self, index: VirtIODeviceIndex)281     fn set_virtio_device_index(&self, index: VirtIODeviceIndex) {
282         self.inner().virtio_index = Some(index);
283     }
284 
virtio_device_index(&self) -> Option<VirtIODeviceIndex>285     fn virtio_device_index(&self) -> Option<VirtIODeviceIndex> {
286         return self.inner().virtio_index;
287     }
288 
device_type_id(&self) -> u32289     fn device_type_id(&self) -> u32 {
290         virtio_drivers::transport::DeviceType::Network as u32
291     }
292 
vendor(&self) -> u32293     fn vendor(&self) -> u32 {
294         VIRTIO_VENDOR_ID.into()
295     }
296 
irq(&self) -> Option<IrqNumber>297     fn irq(&self) -> Option<IrqNumber> {
298         None
299     }
300 }
301 
302 pub struct VirtIoNetImpl {
303     inner: VirtIONet<HalImpl, VirtIOTransport, 2>,
304 }
305 
306 impl VirtIoNetImpl {
new(inner: VirtIONet<HalImpl, VirtIOTransport, 2>) -> Self307     const fn new(inner: VirtIONet<HalImpl, VirtIOTransport, 2>) -> Self {
308         Self { inner }
309     }
310 }
311 
312 impl Deref for VirtIoNetImpl {
313     type Target = VirtIONet<HalImpl, VirtIOTransport, 2>;
deref(&self) -> &Self::Target314     fn deref(&self) -> &Self::Target {
315         &self.inner
316     }
317 }
318 
319 impl DerefMut for VirtIoNetImpl {
deref_mut(&mut self) -> &mut Self::Target320     fn deref_mut(&mut self) -> &mut Self::Target {
321         &mut self.inner
322     }
323 }
324 
325 unsafe impl Send for VirtIoNetImpl {}
326 unsafe impl Sync for VirtIoNetImpl {}
327 
328 #[derive(Debug)]
329 struct VirtIONicDeviceInnerWrapper(UnsafeCell<VirtIONicDeviceInner>);
330 unsafe impl Send for VirtIONicDeviceInnerWrapper {}
331 unsafe impl Sync for VirtIONicDeviceInnerWrapper {}
332 
333 impl Deref for VirtIONicDeviceInnerWrapper {
334     type Target = VirtIONicDeviceInner;
deref(&self) -> &Self::Target335     fn deref(&self) -> &Self::Target {
336         unsafe { &*self.0.get() }
337     }
338 }
339 impl DerefMut for VirtIONicDeviceInnerWrapper {
deref_mut(&mut self) -> &mut Self::Target340     fn deref_mut(&mut self) -> &mut Self::Target {
341         unsafe { &mut *self.0.get() }
342     }
343 }
344 
345 #[allow(clippy::mut_from_ref)]
346 impl VirtIONicDeviceInnerWrapper {
force_get_mut(&self) -> &mut <VirtIONicDeviceInnerWrapper as Deref>::Target347     fn force_get_mut(&self) -> &mut <VirtIONicDeviceInnerWrapper as Deref>::Target {
348         unsafe { &mut *self.0.get() }
349     }
350 }
351 
352 /// Virtio网络设备驱动(加锁)
353 pub struct VirtIONicDeviceInner {
354     pub inner: Arc<SpinLock<VirtIoNetImpl>>,
355 }
356 
357 impl Clone for VirtIONicDeviceInner {
clone(&self) -> Self358     fn clone(&self) -> Self {
359         return VirtIONicDeviceInner {
360             inner: self.inner.clone(),
361         };
362     }
363 }
364 
365 impl Debug for VirtIONicDeviceInner {
fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result366     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
367         f.debug_struct("VirtIONicDriver").finish()
368     }
369 }
370 
371 #[cast_to([sync] NetDevice)]
372 #[cast_to([sync] Device)]
373 pub struct VirtioInterface {
374     device_inner: VirtIONicDeviceInnerWrapper,
375     iface_id: usize,
376     iface_name: String,
377     iface: SpinLock<iface::Interface>,
378     inner: SpinLock<InnerVirtIOInterface>,
379     locked_kobj_state: LockedKObjectState,
380 }
381 
382 #[derive(Debug)]
383 struct InnerVirtIOInterface {
384     kobj_common: KObjectCommonData,
385     device_common: DeviceCommonData,
386     netdevice_common: NetDeviceCommonData,
387 }
388 
389 impl core::fmt::Debug for VirtioInterface {
fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result390     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
391         f.debug_struct("VirtioInterface")
392             .field("iface_id", &self.iface_id)
393             .field("iface_name", &self.iface_name)
394             .field("inner", &self.inner)
395             .field("locked_kobj_state", &self.locked_kobj_state)
396             .finish()
397     }
398 }
399 
400 impl VirtioInterface {
new(mut device_inner: VirtIONicDeviceInner) -> Arc<Self>401     pub fn new(mut device_inner: VirtIONicDeviceInner) -> Arc<Self> {
402         let iface_id = generate_iface_id();
403         let mut iface_config = iface::Config::new(wire::HardwareAddress::Ethernet(
404             wire::EthernetAddress(device_inner.inner.lock().mac_address()),
405         ));
406         iface_config.random_seed = rand() as u64;
407 
408         let iface = iface::Interface::new(iface_config, &mut device_inner, Instant::now().into());
409 
410         let result = Arc::new(VirtioInterface {
411             device_inner: VirtIONicDeviceInnerWrapper(UnsafeCell::new(device_inner)),
412             iface_id,
413             locked_kobj_state: LockedKObjectState::default(),
414             iface: SpinLock::new(iface),
415             iface_name: format!("eth{}", iface_id),
416             inner: SpinLock::new(InnerVirtIOInterface {
417                 kobj_common: KObjectCommonData::default(),
418                 device_common: DeviceCommonData::default(),
419                 netdevice_common: NetDeviceCommonData::default(),
420             }),
421         });
422 
423         return result;
424     }
425 
inner(&self) -> SpinLockGuard<InnerVirtIOInterface>426     fn inner(&self) -> SpinLockGuard<InnerVirtIOInterface> {
427         return self.inner.lock();
428     }
429 
430     /// 获取网卡接口的名称
431     #[allow(dead_code)]
iface_name(&self) -> String432     pub fn iface_name(&self) -> String {
433         self.iface_name.clone()
434     }
435 }
436 
437 impl Drop for VirtioInterface {
drop(&mut self)438     fn drop(&mut self) {
439         // 从全局的网卡接口信息表中删除这个网卡的接口信息
440         NET_DEVICES.write_irqsave().remove(&self.iface_id);
441     }
442 }
443 
444 impl Device for VirtioInterface {
dev_type(&self) -> DeviceType445     fn dev_type(&self) -> DeviceType {
446         DeviceType::Net
447     }
448 
id_table(&self) -> IdTable449     fn id_table(&self) -> IdTable {
450         IdTable::new(VIRTIO_NET_BASENAME.to_string(), None)
451     }
452 
bus(&self) -> Option<Weak<dyn Bus>>453     fn bus(&self) -> Option<Weak<dyn Bus>> {
454         self.inner().device_common.bus.clone()
455     }
456 
set_bus(&self, bus: Option<Weak<dyn Bus>>)457     fn set_bus(&self, bus: Option<Weak<dyn Bus>>) {
458         self.inner().device_common.bus = bus;
459     }
460 
class(&self) -> Option<Arc<dyn Class>>461     fn class(&self) -> Option<Arc<dyn Class>> {
462         let mut guard = self.inner();
463         let r = guard.device_common.class.clone()?.upgrade();
464         if r.is_none() {
465             guard.device_common.class = None;
466         }
467 
468         return r;
469     }
470 
set_class(&self, class: Option<Weak<dyn Class>>)471     fn set_class(&self, class: Option<Weak<dyn Class>>) {
472         self.inner().device_common.class = class;
473     }
474 
driver(&self) -> Option<Arc<dyn Driver>>475     fn driver(&self) -> Option<Arc<dyn Driver>> {
476         let r = self.inner().device_common.driver.clone()?.upgrade();
477         if r.is_none() {
478             self.inner().device_common.driver = None;
479         }
480 
481         return r;
482     }
483 
set_driver(&self, driver: Option<Weak<dyn Driver>>)484     fn set_driver(&self, driver: Option<Weak<dyn Driver>>) {
485         self.inner().device_common.driver = driver;
486     }
487 
is_dead(&self) -> bool488     fn is_dead(&self) -> bool {
489         false
490     }
491 
can_match(&self) -> bool492     fn can_match(&self) -> bool {
493         self.inner().device_common.can_match
494     }
495 
set_can_match(&self, can_match: bool)496     fn set_can_match(&self, can_match: bool) {
497         self.inner().device_common.can_match = can_match;
498     }
499 
state_synced(&self) -> bool500     fn state_synced(&self) -> bool {
501         true
502     }
503 
dev_parent(&self) -> Option<Weak<dyn Device>>504     fn dev_parent(&self) -> Option<Weak<dyn Device>> {
505         self.inner().device_common.get_parent_weak_or_clear()
506     }
507 
set_dev_parent(&self, parent: Option<Weak<dyn Device>>)508     fn set_dev_parent(&self, parent: Option<Weak<dyn Device>>) {
509         self.inner().device_common.parent = parent;
510     }
511 }
512 
513 impl VirtIONicDeviceInner {
new(driver_net: VirtIONet<HalImpl, VirtIOTransport, 2>) -> Self514     pub fn new(driver_net: VirtIONet<HalImpl, VirtIOTransport, 2>) -> Self {
515         let mut iface_config = iface::Config::new(wire::HardwareAddress::Ethernet(
516             wire::EthernetAddress(driver_net.mac_address()),
517         ));
518 
519         iface_config.random_seed = rand() as u64;
520 
521         let inner = Arc::new(SpinLock::new(VirtIoNetImpl::new(driver_net)));
522         let result = VirtIONicDeviceInner { inner };
523         return result;
524     }
525 }
526 
527 pub struct VirtioNetToken {
528     driver: VirtIONicDeviceInner,
529     rx_buffer: Option<virtio_drivers::device::net::RxBuffer>,
530 }
531 
532 impl VirtioNetToken {
new( driver: VirtIONicDeviceInner, rx_buffer: Option<virtio_drivers::device::net::RxBuffer>, ) -> Self533     pub fn new(
534         driver: VirtIONicDeviceInner,
535         rx_buffer: Option<virtio_drivers::device::net::RxBuffer>,
536     ) -> Self {
537         return Self { driver, rx_buffer };
538     }
539 }
540 
541 impl phy::Device for VirtIONicDeviceInner {
542     type RxToken<'a>
543         = VirtioNetToken
544     where
545         Self: 'a;
546     type TxToken<'a>
547         = VirtioNetToken
548     where
549         Self: 'a;
550 
receive( &mut self, _timestamp: smoltcp::time::Instant, ) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)>551     fn receive(
552         &mut self,
553         _timestamp: smoltcp::time::Instant,
554     ) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> {
555         match self.inner.lock().receive() {
556             Ok(buf) => Some((
557                 VirtioNetToken::new(self.clone(), Some(buf)),
558                 VirtioNetToken::new(self.clone(), None),
559             )),
560             Err(virtio_drivers::Error::NotReady) => None,
561             Err(err) => panic!("VirtIO receive failed: {}", err),
562         }
563     }
564 
transmit(&mut self, _timestamp: smoltcp::time::Instant) -> Option<Self::TxToken<'_>>565     fn transmit(&mut self, _timestamp: smoltcp::time::Instant) -> Option<Self::TxToken<'_>> {
566         // debug!("VirtioNet: transmit");
567         if self.inner.lock_irqsave().can_send() {
568             // debug!("VirtioNet: can send");
569             return Some(VirtioNetToken::new(self.clone(), None));
570         } else {
571             // debug!("VirtioNet: can not send");
572             return None;
573         }
574     }
575 
capabilities(&self) -> phy::DeviceCapabilities576     fn capabilities(&self) -> phy::DeviceCapabilities {
577         let mut caps = phy::DeviceCapabilities::default();
578         // 网卡的最大传输单元. 请与IP层的MTU进行区分。这个值应当是网卡的最大传输单元,而不是IP层的MTU。
579         caps.max_transmission_unit = 2000;
580         /*
581            Maximum burst size, in terms of MTU.
582            The network device is unable to send or receive bursts large than the value returned by this function.
583            If None, there is no fixed limit on burst size, e.g. if network buffers are dynamically allocated.
584         */
585         caps.max_burst_size = Some(1);
586         return caps;
587     }
588 }
589 
590 impl phy::TxToken for VirtioNetToken {
consume<R, F>(self, len: usize, f: F) -> R where F: FnOnce(&mut [u8]) -> R,591     fn consume<R, F>(self, len: usize, f: F) -> R
592     where
593         F: FnOnce(&mut [u8]) -> R,
594     {
595         // // 为了线程安全,这里需要对VirtioNet进行加【写锁】,以保证对设备的互斥访问。
596         let mut driver_net = self.driver.inner.lock();
597         let mut tx_buf = driver_net.new_tx_buffer(len);
598         let result = f(tx_buf.packet_mut());
599         driver_net.send(tx_buf).expect("virtio_net send failed");
600         return result;
601     }
602 }
603 
604 impl phy::RxToken for VirtioNetToken {
consume<R, F>(self, f: F) -> R where F: FnOnce(&mut [u8]) -> R,605     fn consume<R, F>(self, f: F) -> R
606     where
607         F: FnOnce(&mut [u8]) -> R,
608     {
609         // 为了线程安全,这里需要对VirtioNet进行加【写锁】,以保证对设备的互斥访问。
610         let mut rx_buf = self.rx_buffer.unwrap();
611         let result = f(rx_buf.packet_mut());
612         self.driver
613             .inner
614             .lock()
615             .recycle_rx_buffer(rx_buf)
616             .expect("virtio_net recv failed");
617         result
618     }
619 }
620 
621 /// @brief virtio-net 驱动的初始化与测试
virtio_net( transport: VirtIOTransport, dev_id: Arc<DeviceId>, dev_parent: Option<Arc<dyn Device>>, )622 pub fn virtio_net(
623     transport: VirtIOTransport,
624     dev_id: Arc<DeviceId>,
625     dev_parent: Option<Arc<dyn Device>>,
626 ) {
627     let virtio_net_deivce = VirtIONetDevice::new(transport, dev_id);
628     if let Some(virtio_net_deivce) = virtio_net_deivce {
629         debug!("VirtIONetDevice '{:?}' created", virtio_net_deivce.dev_id);
630         if let Some(dev_parent) = dev_parent {
631             virtio_net_deivce.set_dev_parent(Some(Arc::downgrade(&dev_parent)));
632         }
633         virtio_device_manager()
634             .device_add(virtio_net_deivce.clone() as Arc<dyn VirtIODevice>)
635             .expect("Add virtio net failed");
636     }
637 }
638 
639 impl NetDevice for VirtioInterface {
mac(&self) -> wire::EthernetAddress640     fn mac(&self) -> wire::EthernetAddress {
641         let mac: [u8; 6] = self.device_inner.inner.lock().mac_address();
642         return wire::EthernetAddress::from_bytes(&mac);
643     }
644 
645     #[inline]
nic_id(&self) -> usize646     fn nic_id(&self) -> usize {
647         return self.iface_id;
648     }
649 
650     #[inline]
iface_name(&self) -> String651     fn iface_name(&self) -> String {
652         return self.iface_name.clone();
653     }
654 
update_ip_addrs(&self, ip_addrs: &[wire::IpCidr]) -> Result<(), SystemError>655     fn update_ip_addrs(&self, ip_addrs: &[wire::IpCidr]) -> Result<(), SystemError> {
656         if ip_addrs.len() != 1 {
657             return Err(SystemError::EINVAL);
658         }
659 
660         self.iface.lock().update_ip_addrs(|addrs| {
661             let dest = addrs.iter_mut().next();
662 
663             if let Some(dest) = dest {
664                 *dest = ip_addrs[0];
665             } else {
666                 addrs
667                     .push(ip_addrs[0])
668                     .expect("Push wire::IpCidr failed: full");
669             }
670         });
671         return Ok(());
672     }
673 
poll(&self, sockets: &mut iface::SocketSet) -> Result<(), SystemError>674     fn poll(&self, sockets: &mut iface::SocketSet) -> Result<(), SystemError> {
675         let timestamp: smoltcp::time::Instant = Instant::now().into();
676         let mut guard = self.iface.lock();
677         let poll_res = guard.poll(timestamp, self.device_inner.force_get_mut(), sockets);
678         // todo: notify!!!
679         // debug!("Virtio Interface poll:{poll_res}");
680         if poll_res {
681             return Ok(());
682         }
683         return Err(SystemError::EAGAIN_OR_EWOULDBLOCK);
684     }
685 
686     #[inline(always)]
inner_iface(&self) -> &SpinLock<iface::Interface>687     fn inner_iface(&self) -> &SpinLock<iface::Interface> {
688         return &self.iface;
689     }
690     // fn as_any_ref(&'static self) -> &'static dyn core::any::Any {
691     //     return self;
692     // }
693 
addr_assign_type(&self) -> u8694     fn addr_assign_type(&self) -> u8 {
695         return self.inner().netdevice_common.addr_assign_type;
696     }
697 
net_device_type(&self) -> u16698     fn net_device_type(&self) -> u16 {
699         self.inner().netdevice_common.net_device_type = 1; // 以太网设备
700         return self.inner().netdevice_common.net_device_type;
701     }
702 
net_state(&self) -> NetDeivceState703     fn net_state(&self) -> NetDeivceState {
704         return self.inner().netdevice_common.state;
705     }
706 
set_net_state(&self, state: NetDeivceState)707     fn set_net_state(&self, state: NetDeivceState) {
708         self.inner().netdevice_common.state |= state;
709     }
710 
operstate(&self) -> Operstate711     fn operstate(&self) -> Operstate {
712         return self.inner().netdevice_common.operstate;
713     }
714 
set_operstate(&self, state: Operstate)715     fn set_operstate(&self, state: Operstate) {
716         self.inner().netdevice_common.operstate = state;
717     }
718 }
719 
720 impl KObject for VirtioInterface {
as_any_ref(&self) -> &dyn core::any::Any721     fn as_any_ref(&self) -> &dyn core::any::Any {
722         self
723     }
724 
set_inode(&self, inode: Option<Arc<KernFSInode>>)725     fn set_inode(&self, inode: Option<Arc<KernFSInode>>) {
726         self.inner().kobj_common.kern_inode = inode;
727     }
728 
inode(&self) -> Option<Arc<KernFSInode>>729     fn inode(&self) -> Option<Arc<KernFSInode>> {
730         self.inner().kobj_common.kern_inode.clone()
731     }
732 
parent(&self) -> Option<Weak<dyn KObject>>733     fn parent(&self) -> Option<Weak<dyn KObject>> {
734         self.inner().kobj_common.parent.clone()
735     }
736 
set_parent(&self, parent: Option<Weak<dyn KObject>>)737     fn set_parent(&self, parent: Option<Weak<dyn KObject>>) {
738         self.inner().kobj_common.parent = parent;
739     }
740 
kset(&self) -> Option<Arc<KSet>>741     fn kset(&self) -> Option<Arc<KSet>> {
742         self.inner().kobj_common.kset.clone()
743     }
744 
set_kset(&self, kset: Option<Arc<KSet>>)745     fn set_kset(&self, kset: Option<Arc<KSet>>) {
746         self.inner().kobj_common.kset = kset;
747     }
748 
kobj_type(&self) -> Option<&'static dyn KObjType>749     fn kobj_type(&self) -> Option<&'static dyn KObjType> {
750         self.inner().kobj_common.kobj_type
751     }
752 
name(&self) -> String753     fn name(&self) -> String {
754         self.iface_name.clone()
755     }
756 
set_name(&self, _name: String)757     fn set_name(&self, _name: String) {
758         // do nothing
759     }
760 
kobj_state(&self) -> RwLockReadGuard<KObjectState>761     fn kobj_state(&self) -> RwLockReadGuard<KObjectState> {
762         self.locked_kobj_state.read()
763     }
764 
kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState>765     fn kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState> {
766         self.locked_kobj_state.write()
767     }
768 
set_kobj_state(&self, state: KObjectState)769     fn set_kobj_state(&self, state: KObjectState) {
770         *self.locked_kobj_state.write() = state;
771     }
772 
set_kobj_type(&self, ktype: Option<&'static dyn KObjType>)773     fn set_kobj_type(&self, ktype: Option<&'static dyn KObjType>) {
774         self.inner().kobj_common.kobj_type = ktype;
775     }
776 }
777 
778 #[unified_init(INITCALL_POSTCORE)]
virtio_net_driver_init() -> Result<(), SystemError>779 fn virtio_net_driver_init() -> Result<(), SystemError> {
780     let driver = VirtIONetDriver::new();
781     virtio_driver_manager()
782         .register(driver.clone() as Arc<dyn VirtIODriver>)
783         .expect("Add virtio net driver failed");
784     unsafe {
785         VIRTIO_NET_DRIVER = Some(driver);
786     }
787 
788     return Ok(());
789 }
790 
791 #[derive(Debug)]
792 #[cast_to([sync] VirtIODriver)]
793 #[cast_to([sync] Driver)]
794 struct VirtIONetDriver {
795     inner: SpinLock<InnerVirtIODriver>,
796     kobj_state: LockedKObjectState,
797 }
798 
799 impl VirtIONetDriver {
new() -> Arc<Self>800     pub fn new() -> Arc<Self> {
801         let inner = InnerVirtIODriver {
802             virtio_driver_common: VirtIODriverCommonData::default(),
803             driver_common: DriverCommonData::default(),
804             kobj_common: KObjectCommonData::default(),
805         };
806 
807         let id_table = VirtioDeviceId::new(
808             virtio_drivers::transport::DeviceType::Network as u32,
809             VIRTIO_VENDOR_ID.into(),
810         );
811         let result = VirtIONetDriver {
812             inner: SpinLock::new(inner),
813             kobj_state: LockedKObjectState::default(),
814         };
815         result.add_virtio_id(id_table);
816 
817         return Arc::new(result);
818     }
819 
inner(&self) -> SpinLockGuard<InnerVirtIODriver>820     fn inner(&self) -> SpinLockGuard<InnerVirtIODriver> {
821         return self.inner.lock();
822     }
823 }
824 
825 #[derive(Debug)]
826 struct InnerVirtIODriver {
827     virtio_driver_common: VirtIODriverCommonData,
828     driver_common: DriverCommonData,
829     kobj_common: KObjectCommonData,
830 }
831 
832 impl VirtIODriver for VirtIONetDriver {
probe(&self, device: &Arc<dyn VirtIODevice>) -> Result<(), SystemError>833     fn probe(&self, device: &Arc<dyn VirtIODevice>) -> Result<(), SystemError> {
834         log::debug!("VirtIONetDriver::probe()");
835         let virtio_net_device = device
836             .clone()
837             .arc_any()
838             .downcast::<VirtIONetDevice>()
839             .map_err(|_| {
840                 error!(
841                     "VirtIONetDriver::probe() failed: device is not a VirtIODevice. Device: '{:?}'",
842                     device.name()
843                 );
844                 SystemError::EINVAL
845             })?;
846 
847         let iface: Arc<VirtioInterface> =
848             VirtioInterface::new(virtio_net_device.inner().device_inner.clone());
849         // 标识网络设备已经启动
850         iface.set_net_state(NetDeivceState::__LINK_STATE_START);
851         // 设置iface的父设备为virtio_net_device
852         iface.set_dev_parent(Some(Arc::downgrade(&virtio_net_device) as Weak<dyn Device>));
853         // 在sysfs中注册iface
854         register_netdevice(iface.clone() as Arc<dyn NetDevice>)?;
855 
856         // 将网卡的接口信息注册到全局的网卡接口信息表中
857         NET_DEVICES
858             .write_irqsave()
859             .insert(iface.nic_id(), iface.clone());
860 
861         virtio_irq_manager()
862             .register_device(device.clone())
863             .expect("Register virtio net irq failed");
864 
865         return Ok(());
866     }
867 
virtio_id_table(&self) -> LinkedList<VirtioDeviceId>868     fn virtio_id_table(&self) -> LinkedList<VirtioDeviceId> {
869         self.inner().virtio_driver_common.id_table.clone()
870     }
871 
add_virtio_id(&self, id: VirtioDeviceId)872     fn add_virtio_id(&self, id: VirtioDeviceId) {
873         self.inner().virtio_driver_common.id_table.push_back(id);
874     }
875 }
876 
877 impl Driver for VirtIONetDriver {
id_table(&self) -> Option<IdTable>878     fn id_table(&self) -> Option<IdTable> {
879         Some(IdTable::new(VIRTIO_NET_BASENAME.to_string(), None))
880     }
881 
add_device(&self, device: Arc<dyn Device>)882     fn add_device(&self, device: Arc<dyn Device>) {
883         let virtio_net_device = device
884             .arc_any()
885             .downcast::<VirtIONetDevice>()
886             .expect("VirtIONetDriver::add_device() failed: device is not a VirtioInterface");
887 
888         self.inner()
889             .driver_common
890             .devices
891             .push(virtio_net_device as Arc<dyn Device>);
892     }
893 
delete_device(&self, device: &Arc<dyn Device>)894     fn delete_device(&self, device: &Arc<dyn Device>) {
895         let _virtio_net_device = device
896             .clone()
897             .arc_any()
898             .downcast::<VirtIONetDevice>()
899             .expect("VirtIONetDriver::delete_device() failed: device is not a VirtioInterface");
900 
901         let mut guard = self.inner();
902         let index = guard
903             .driver_common
904             .devices
905             .iter()
906             .position(|dev| Arc::ptr_eq(device, dev))
907             .expect("VirtIONetDriver::delete_device() failed: device not found");
908 
909         guard.driver_common.devices.remove(index);
910     }
911 
devices(&self) -> Vec<Arc<dyn Device>>912     fn devices(&self) -> Vec<Arc<dyn Device>> {
913         self.inner().driver_common.devices.clone()
914     }
915 
bus(&self) -> Option<Weak<dyn Bus>>916     fn bus(&self) -> Option<Weak<dyn Bus>> {
917         Some(Arc::downgrade(&virtio_bus()) as Weak<dyn Bus>)
918     }
919 
set_bus(&self, _bus: Option<Weak<dyn Bus>>)920     fn set_bus(&self, _bus: Option<Weak<dyn Bus>>) {
921         // do nothing
922     }
923 }
924 
925 impl KObject for VirtIONetDriver {
as_any_ref(&self) -> &dyn Any926     fn as_any_ref(&self) -> &dyn Any {
927         self
928     }
929 
set_inode(&self, inode: Option<Arc<KernFSInode>>)930     fn set_inode(&self, inode: Option<Arc<KernFSInode>>) {
931         self.inner().kobj_common.kern_inode = inode;
932     }
933 
inode(&self) -> Option<Arc<KernFSInode>>934     fn inode(&self) -> Option<Arc<KernFSInode>> {
935         self.inner().kobj_common.kern_inode.clone()
936     }
937 
parent(&self) -> Option<Weak<dyn KObject>>938     fn parent(&self) -> Option<Weak<dyn KObject>> {
939         self.inner().kobj_common.parent.clone()
940     }
941 
set_parent(&self, parent: Option<Weak<dyn KObject>>)942     fn set_parent(&self, parent: Option<Weak<dyn KObject>>) {
943         self.inner().kobj_common.parent = parent;
944     }
945 
kset(&self) -> Option<Arc<KSet>>946     fn kset(&self) -> Option<Arc<KSet>> {
947         self.inner().kobj_common.kset.clone()
948     }
949 
set_kset(&self, kset: Option<Arc<KSet>>)950     fn set_kset(&self, kset: Option<Arc<KSet>>) {
951         self.inner().kobj_common.kset = kset;
952     }
953 
kobj_type(&self) -> Option<&'static dyn KObjType>954     fn kobj_type(&self) -> Option<&'static dyn KObjType> {
955         self.inner().kobj_common.kobj_type
956     }
957 
set_kobj_type(&self, ktype: Option<&'static dyn KObjType>)958     fn set_kobj_type(&self, ktype: Option<&'static dyn KObjType>) {
959         self.inner().kobj_common.kobj_type = ktype;
960     }
961 
name(&self) -> String962     fn name(&self) -> String {
963         VIRTIO_NET_BASENAME.to_string()
964     }
965 
set_name(&self, _name: String)966     fn set_name(&self, _name: String) {
967         // do nothing
968     }
969 
kobj_state(&self) -> RwLockReadGuard<KObjectState>970     fn kobj_state(&self) -> RwLockReadGuard<KObjectState> {
971         self.kobj_state.read()
972     }
973 
kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState>974     fn kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState> {
975         self.kobj_state.write()
976     }
977 
set_kobj_state(&self, state: KObjectState)978     fn set_kobj_state(&self, state: KObjectState) {
979         *self.kobj_state.write() = state;
980     }
981 }
982