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