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