xref: /DragonOS/kernel/src/driver/net/virtio_net.rs (revision 84c528f53d91118bfc79e6d706b5b2de31e89915)
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> = VirtioNetToken where Self: 'a;
543     type TxToken<'a> = VirtioNetToken where Self: 'a;
544 
receive( &mut self, _timestamp: smoltcp::time::Instant, ) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)>545     fn receive(
546         &mut self,
547         _timestamp: smoltcp::time::Instant,
548     ) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> {
549         match self.inner.lock().receive() {
550             Ok(buf) => Some((
551                 VirtioNetToken::new(self.clone(), Some(buf)),
552                 VirtioNetToken::new(self.clone(), None),
553             )),
554             Err(virtio_drivers::Error::NotReady) => None,
555             Err(err) => panic!("VirtIO receive failed: {}", err),
556         }
557     }
558 
transmit(&mut self, _timestamp: smoltcp::time::Instant) -> Option<Self::TxToken<'_>>559     fn transmit(&mut self, _timestamp: smoltcp::time::Instant) -> Option<Self::TxToken<'_>> {
560         // debug!("VirtioNet: transmit");
561         if self.inner.lock_irqsave().can_send() {
562             // debug!("VirtioNet: can send");
563             return Some(VirtioNetToken::new(self.clone(), None));
564         } else {
565             // debug!("VirtioNet: can not send");
566             return None;
567         }
568     }
569 
capabilities(&self) -> phy::DeviceCapabilities570     fn capabilities(&self) -> phy::DeviceCapabilities {
571         let mut caps = phy::DeviceCapabilities::default();
572         // 网卡的最大传输单元. 请与IP层的MTU进行区分。这个值应当是网卡的最大传输单元,而不是IP层的MTU。
573         caps.max_transmission_unit = 2000;
574         /*
575            Maximum burst size, in terms of MTU.
576            The network device is unable to send or receive bursts large than the value returned by this function.
577            If None, there is no fixed limit on burst size, e.g. if network buffers are dynamically allocated.
578         */
579         caps.max_burst_size = Some(1);
580         return caps;
581     }
582 }
583 
584 impl phy::TxToken for VirtioNetToken {
consume<R, F>(self, len: usize, f: F) -> R where F: FnOnce(&mut [u8]) -> R,585     fn consume<R, F>(self, len: usize, f: F) -> R
586     where
587         F: FnOnce(&mut [u8]) -> R,
588     {
589         // // 为了线程安全,这里需要对VirtioNet进行加【写锁】,以保证对设备的互斥访问。
590         let mut driver_net = self.driver.inner.lock();
591         let mut tx_buf = driver_net.new_tx_buffer(len);
592         let result = f(tx_buf.packet_mut());
593         driver_net.send(tx_buf).expect("virtio_net send failed");
594         return result;
595     }
596 }
597 
598 impl phy::RxToken for VirtioNetToken {
consume<R, F>(self, f: F) -> R where F: FnOnce(&mut [u8]) -> R,599     fn consume<R, F>(self, f: F) -> R
600     where
601         F: FnOnce(&mut [u8]) -> R,
602     {
603         // 为了线程安全,这里需要对VirtioNet进行加【写锁】,以保证对设备的互斥访问。
604         let mut rx_buf = self.rx_buffer.unwrap();
605         let result = f(rx_buf.packet_mut());
606         self.driver
607             .inner
608             .lock()
609             .recycle_rx_buffer(rx_buf)
610             .expect("virtio_net recv failed");
611         result
612     }
613 }
614 
615 /// @brief virtio-net 驱动的初始化与测试
virtio_net( transport: VirtIOTransport, dev_id: Arc<DeviceId>, dev_parent: Option<Arc<dyn Device>>, )616 pub fn virtio_net(
617     transport: VirtIOTransport,
618     dev_id: Arc<DeviceId>,
619     dev_parent: Option<Arc<dyn Device>>,
620 ) {
621     let virtio_net_deivce = VirtIONetDevice::new(transport, dev_id);
622     if let Some(virtio_net_deivce) = virtio_net_deivce {
623         debug!("VirtIONetDevice '{:?}' created", virtio_net_deivce.dev_id);
624         if let Some(dev_parent) = dev_parent {
625             virtio_net_deivce.set_dev_parent(Some(Arc::downgrade(&dev_parent)));
626         }
627         virtio_device_manager()
628             .device_add(virtio_net_deivce.clone() as Arc<dyn VirtIODevice>)
629             .expect("Add virtio net failed");
630     }
631 }
632 
633 impl NetDevice for VirtioInterface {
mac(&self) -> wire::EthernetAddress634     fn mac(&self) -> wire::EthernetAddress {
635         let mac: [u8; 6] = self.device_inner.inner.lock().mac_address();
636         return wire::EthernetAddress::from_bytes(&mac);
637     }
638 
639     #[inline]
nic_id(&self) -> usize640     fn nic_id(&self) -> usize {
641         return self.iface_id;
642     }
643 
644     #[inline]
iface_name(&self) -> String645     fn iface_name(&self) -> String {
646         return self.iface_name.clone();
647     }
648 
update_ip_addrs(&self, ip_addrs: &[wire::IpCidr]) -> Result<(), SystemError>649     fn update_ip_addrs(&self, ip_addrs: &[wire::IpCidr]) -> Result<(), SystemError> {
650         if ip_addrs.len() != 1 {
651             return Err(SystemError::EINVAL);
652         }
653 
654         self.iface.lock().update_ip_addrs(|addrs| {
655             let dest = addrs.iter_mut().next();
656 
657             if let Some(dest) = dest {
658                 *dest = ip_addrs[0];
659             } else {
660                 addrs
661                     .push(ip_addrs[0])
662                     .expect("Push wire::IpCidr failed: full");
663             }
664         });
665         return Ok(());
666     }
667 
poll(&self, sockets: &mut iface::SocketSet) -> Result<(), SystemError>668     fn poll(&self, sockets: &mut iface::SocketSet) -> Result<(), SystemError> {
669         let timestamp: smoltcp::time::Instant = Instant::now().into();
670         let mut guard = self.iface.lock();
671         let poll_res = guard.poll(timestamp, self.device_inner.force_get_mut(), sockets);
672         // todo: notify!!!
673         // debug!("Virtio Interface poll:{poll_res}");
674         if poll_res {
675             return Ok(());
676         }
677         return Err(SystemError::EAGAIN_OR_EWOULDBLOCK);
678     }
679 
680     #[inline(always)]
inner_iface(&self) -> &SpinLock<iface::Interface>681     fn inner_iface(&self) -> &SpinLock<iface::Interface> {
682         return &self.iface;
683     }
684     // fn as_any_ref(&'static self) -> &'static dyn core::any::Any {
685     //     return self;
686     // }
687 
addr_assign_type(&self) -> u8688     fn addr_assign_type(&self) -> u8 {
689         return self.inner().netdevice_common.addr_assign_type;
690     }
691 
net_device_type(&self) -> u16692     fn net_device_type(&self) -> u16 {
693         self.inner().netdevice_common.net_device_type = 1; // 以太网设备
694         return self.inner().netdevice_common.net_device_type;
695     }
696 
net_state(&self) -> NetDeivceState697     fn net_state(&self) -> NetDeivceState {
698         return self.inner().netdevice_common.state;
699     }
700 
set_net_state(&self, state: NetDeivceState)701     fn set_net_state(&self, state: NetDeivceState) {
702         self.inner().netdevice_common.state |= state;
703     }
704 
operstate(&self) -> Operstate705     fn operstate(&self) -> Operstate {
706         return self.inner().netdevice_common.operstate;
707     }
708 
set_operstate(&self, state: Operstate)709     fn set_operstate(&self, state: Operstate) {
710         self.inner().netdevice_common.operstate = state;
711     }
712 }
713 
714 impl KObject for VirtioInterface {
as_any_ref(&self) -> &dyn core::any::Any715     fn as_any_ref(&self) -> &dyn core::any::Any {
716         self
717     }
718 
set_inode(&self, inode: Option<Arc<KernFSInode>>)719     fn set_inode(&self, inode: Option<Arc<KernFSInode>>) {
720         self.inner().kobj_common.kern_inode = inode;
721     }
722 
inode(&self) -> Option<Arc<KernFSInode>>723     fn inode(&self) -> Option<Arc<KernFSInode>> {
724         self.inner().kobj_common.kern_inode.clone()
725     }
726 
parent(&self) -> Option<Weak<dyn KObject>>727     fn parent(&self) -> Option<Weak<dyn KObject>> {
728         self.inner().kobj_common.parent.clone()
729     }
730 
set_parent(&self, parent: Option<Weak<dyn KObject>>)731     fn set_parent(&self, parent: Option<Weak<dyn KObject>>) {
732         self.inner().kobj_common.parent = parent;
733     }
734 
kset(&self) -> Option<Arc<KSet>>735     fn kset(&self) -> Option<Arc<KSet>> {
736         self.inner().kobj_common.kset.clone()
737     }
738 
set_kset(&self, kset: Option<Arc<KSet>>)739     fn set_kset(&self, kset: Option<Arc<KSet>>) {
740         self.inner().kobj_common.kset = kset;
741     }
742 
kobj_type(&self) -> Option<&'static dyn KObjType>743     fn kobj_type(&self) -> Option<&'static dyn KObjType> {
744         self.inner().kobj_common.kobj_type
745     }
746 
name(&self) -> String747     fn name(&self) -> String {
748         self.iface_name.clone()
749     }
750 
set_name(&self, _name: String)751     fn set_name(&self, _name: String) {
752         // do nothing
753     }
754 
kobj_state(&self) -> RwLockReadGuard<KObjectState>755     fn kobj_state(&self) -> RwLockReadGuard<KObjectState> {
756         self.locked_kobj_state.read()
757     }
758 
kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState>759     fn kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState> {
760         self.locked_kobj_state.write()
761     }
762 
set_kobj_state(&self, state: KObjectState)763     fn set_kobj_state(&self, state: KObjectState) {
764         *self.locked_kobj_state.write() = state;
765     }
766 
set_kobj_type(&self, ktype: Option<&'static dyn KObjType>)767     fn set_kobj_type(&self, ktype: Option<&'static dyn KObjType>) {
768         self.inner().kobj_common.kobj_type = ktype;
769     }
770 }
771 
772 #[unified_init(INITCALL_POSTCORE)]
virtio_net_driver_init() -> Result<(), SystemError>773 fn virtio_net_driver_init() -> Result<(), SystemError> {
774     let driver = VirtIONetDriver::new();
775     virtio_driver_manager()
776         .register(driver.clone() as Arc<dyn VirtIODriver>)
777         .expect("Add virtio net driver failed");
778     unsafe {
779         VIRTIO_NET_DRIVER = Some(driver);
780     }
781 
782     return Ok(());
783 }
784 
785 #[derive(Debug)]
786 #[cast_to([sync] VirtIODriver)]
787 #[cast_to([sync] Driver)]
788 struct VirtIONetDriver {
789     inner: SpinLock<InnerVirtIODriver>,
790     kobj_state: LockedKObjectState,
791 }
792 
793 impl VirtIONetDriver {
new() -> Arc<Self>794     pub fn new() -> Arc<Self> {
795         let inner = InnerVirtIODriver {
796             virtio_driver_common: VirtIODriverCommonData::default(),
797             driver_common: DriverCommonData::default(),
798             kobj_common: KObjectCommonData::default(),
799         };
800 
801         let id_table = VirtioDeviceId::new(
802             virtio_drivers::transport::DeviceType::Network as u32,
803             VIRTIO_VENDOR_ID.into(),
804         );
805         let result = VirtIONetDriver {
806             inner: SpinLock::new(inner),
807             kobj_state: LockedKObjectState::default(),
808         };
809         result.add_virtio_id(id_table);
810 
811         return Arc::new(result);
812     }
813 
inner(&self) -> SpinLockGuard<InnerVirtIODriver>814     fn inner(&self) -> SpinLockGuard<InnerVirtIODriver> {
815         return self.inner.lock();
816     }
817 }
818 
819 #[derive(Debug)]
820 struct InnerVirtIODriver {
821     virtio_driver_common: VirtIODriverCommonData,
822     driver_common: DriverCommonData,
823     kobj_common: KObjectCommonData,
824 }
825 
826 impl VirtIODriver for VirtIONetDriver {
probe(&self, device: &Arc<dyn VirtIODevice>) -> Result<(), SystemError>827     fn probe(&self, device: &Arc<dyn VirtIODevice>) -> Result<(), SystemError> {
828         log::debug!("VirtIONetDriver::probe()");
829         let virtio_net_device = device
830             .clone()
831             .arc_any()
832             .downcast::<VirtIONetDevice>()
833             .map_err(|_| {
834                 error!(
835                     "VirtIONetDriver::probe() failed: device is not a VirtIODevice. Device: '{:?}'",
836                     device.name()
837                 );
838                 SystemError::EINVAL
839             })?;
840 
841         let iface: Arc<VirtioInterface> =
842             VirtioInterface::new(virtio_net_device.inner().device_inner.clone());
843         // 标识网络设备已经启动
844         iface.set_net_state(NetDeivceState::__LINK_STATE_START);
845         // 设置iface的父设备为virtio_net_device
846         iface.set_dev_parent(Some(Arc::downgrade(&virtio_net_device) as Weak<dyn Device>));
847         // 在sysfs中注册iface
848         register_netdevice(iface.clone() as Arc<dyn NetDevice>)?;
849 
850         // 将网卡的接口信息注册到全局的网卡接口信息表中
851         NET_DEVICES
852             .write_irqsave()
853             .insert(iface.nic_id(), iface.clone());
854 
855         virtio_irq_manager()
856             .register_device(device.clone())
857             .expect("Register virtio net irq failed");
858 
859         return Ok(());
860     }
861 
virtio_id_table(&self) -> LinkedList<VirtioDeviceId>862     fn virtio_id_table(&self) -> LinkedList<VirtioDeviceId> {
863         self.inner().virtio_driver_common.id_table.clone()
864     }
865 
add_virtio_id(&self, id: VirtioDeviceId)866     fn add_virtio_id(&self, id: VirtioDeviceId) {
867         self.inner().virtio_driver_common.id_table.push_back(id);
868     }
869 }
870 
871 impl Driver for VirtIONetDriver {
id_table(&self) -> Option<IdTable>872     fn id_table(&self) -> Option<IdTable> {
873         Some(IdTable::new(VIRTIO_NET_BASENAME.to_string(), None))
874     }
875 
add_device(&self, device: Arc<dyn Device>)876     fn add_device(&self, device: Arc<dyn Device>) {
877         let virtio_net_device = device
878             .arc_any()
879             .downcast::<VirtIONetDevice>()
880             .expect("VirtIONetDriver::add_device() failed: device is not a VirtioInterface");
881 
882         self.inner()
883             .driver_common
884             .devices
885             .push(virtio_net_device as Arc<dyn Device>);
886     }
887 
delete_device(&self, device: &Arc<dyn Device>)888     fn delete_device(&self, device: &Arc<dyn Device>) {
889         let _virtio_net_device = device
890             .clone()
891             .arc_any()
892             .downcast::<VirtIONetDevice>()
893             .expect("VirtIONetDriver::delete_device() failed: device is not a VirtioInterface");
894 
895         let mut guard = self.inner();
896         let index = guard
897             .driver_common
898             .devices
899             .iter()
900             .position(|dev| Arc::ptr_eq(device, dev))
901             .expect("VirtIONetDriver::delete_device() failed: device not found");
902 
903         guard.driver_common.devices.remove(index);
904     }
905 
devices(&self) -> Vec<Arc<dyn Device>>906     fn devices(&self) -> Vec<Arc<dyn Device>> {
907         self.inner().driver_common.devices.clone()
908     }
909 
bus(&self) -> Option<Weak<dyn Bus>>910     fn bus(&self) -> Option<Weak<dyn Bus>> {
911         Some(Arc::downgrade(&virtio_bus()) as Weak<dyn Bus>)
912     }
913 
set_bus(&self, _bus: Option<Weak<dyn Bus>>)914     fn set_bus(&self, _bus: Option<Weak<dyn Bus>>) {
915         // do nothing
916     }
917 }
918 
919 impl KObject for VirtIONetDriver {
as_any_ref(&self) -> &dyn Any920     fn as_any_ref(&self) -> &dyn Any {
921         self
922     }
923 
set_inode(&self, inode: Option<Arc<KernFSInode>>)924     fn set_inode(&self, inode: Option<Arc<KernFSInode>>) {
925         self.inner().kobj_common.kern_inode = inode;
926     }
927 
inode(&self) -> Option<Arc<KernFSInode>>928     fn inode(&self) -> Option<Arc<KernFSInode>> {
929         self.inner().kobj_common.kern_inode.clone()
930     }
931 
parent(&self) -> Option<Weak<dyn KObject>>932     fn parent(&self) -> Option<Weak<dyn KObject>> {
933         self.inner().kobj_common.parent.clone()
934     }
935 
set_parent(&self, parent: Option<Weak<dyn KObject>>)936     fn set_parent(&self, parent: Option<Weak<dyn KObject>>) {
937         self.inner().kobj_common.parent = parent;
938     }
939 
kset(&self) -> Option<Arc<KSet>>940     fn kset(&self) -> Option<Arc<KSet>> {
941         self.inner().kobj_common.kset.clone()
942     }
943 
set_kset(&self, kset: Option<Arc<KSet>>)944     fn set_kset(&self, kset: Option<Arc<KSet>>) {
945         self.inner().kobj_common.kset = kset;
946     }
947 
kobj_type(&self) -> Option<&'static dyn KObjType>948     fn kobj_type(&self) -> Option<&'static dyn KObjType> {
949         self.inner().kobj_common.kobj_type
950     }
951 
set_kobj_type(&self, ktype: Option<&'static dyn KObjType>)952     fn set_kobj_type(&self, ktype: Option<&'static dyn KObjType>) {
953         self.inner().kobj_common.kobj_type = ktype;
954     }
955 
name(&self) -> String956     fn name(&self) -> String {
957         VIRTIO_NET_BASENAME.to_string()
958     }
959 
set_name(&self, _name: String)960     fn set_name(&self, _name: String) {
961         // do nothing
962     }
963 
kobj_state(&self) -> RwLockReadGuard<KObjectState>964     fn kobj_state(&self) -> RwLockReadGuard<KObjectState> {
965         self.kobj_state.read()
966     }
967 
kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState>968     fn kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState> {
969         self.kobj_state.write()
970     }
971 
set_kobj_state(&self, state: KObjectState)972     fn set_kobj_state(&self, state: KObjectState) {
973         *self.kobj_state.write() = state;
974     }
975 }
976