xref: /DragonOS/kernel/src/driver/net/loopback.rs (revision 28fe4ad2a0b0d8b5abf1f0cb402b1c3204b42242)
11ea2daadSSMALLC use crate::arch::rand::rand;
21ea2daadSSMALLC use crate::driver::base::class::Class;
31ea2daadSSMALLC use crate::driver::base::device::bus::Bus;
41ea2daadSSMALLC use crate::driver::base::device::driver::Driver;
5*28fe4ad2S黄铭涛 use crate::driver::base::device::{Device, DeviceCommonData, DeviceType, IdTable};
6*28fe4ad2S黄铭涛 use crate::driver::base::kobject::{
7*28fe4ad2S黄铭涛     KObjType, KObject, KObjectCommonData, KObjectState, LockedKObjectState,
8*28fe4ad2S黄铭涛 };
9*28fe4ad2S黄铭涛 use crate::driver::base::kset::KSet;
10*28fe4ad2S黄铭涛 use crate::filesystem::kernfs::KernFSInode;
111ea2daadSSMALLC use crate::init::initcall::INITCALL_DEVICE;
12*28fe4ad2S黄铭涛 use crate::libs::rwlock::{RwLockReadGuard, RwLockWriteGuard};
13*28fe4ad2S黄铭涛 use crate::libs::spinlock::{SpinLock, SpinLockGuard};
141ea2daadSSMALLC use crate::net::{generate_iface_id, NET_DEVICES};
151ea2daadSSMALLC use crate::time::Instant;
161ea2daadSSMALLC use alloc::collections::VecDeque;
171ea2daadSSMALLC use alloc::fmt::Debug;
181ea2daadSSMALLC use alloc::string::{String, ToString};
191ea2daadSSMALLC use alloc::sync::{Arc, Weak};
201ea2daadSSMALLC use alloc::vec::Vec;
211ea2daadSSMALLC use core::cell::UnsafeCell;
221ea2daadSSMALLC use core::ops::{Deref, DerefMut};
231ea2daadSSMALLC use smoltcp::wire::HardwareAddress;
241ea2daadSSMALLC use smoltcp::{
251ea2daadSSMALLC     phy::{self},
261ea2daadSSMALLC     wire::{IpAddress, IpCidr},
271ea2daadSSMALLC };
281ea2daadSSMALLC use system_error::SystemError;
291ea2daadSSMALLC use unified_init::macros::unified_init;
301ea2daadSSMALLC 
31*28fe4ad2S黄铭涛 use super::{register_netdevice, NetDeivceState, NetDevice, NetDeviceCommonData, Operstate};
321ea2daadSSMALLC 
331ea2daadSSMALLC const DEVICE_NAME: &str = "loopback";
341ea2daadSSMALLC 
351ea2daadSSMALLC /// ## 环回接收令牌
361ea2daadSSMALLC /// 用于储存lo网卡接收到的数据
371ea2daadSSMALLC pub struct LoopbackRxToken {
381ea2daadSSMALLC     buffer: Vec<u8>,
391ea2daadSSMALLC }
401ea2daadSSMALLC 
411ea2daadSSMALLC impl phy::RxToken for LoopbackRxToken {
421ea2daadSSMALLC     /// ## 实现Rxtoken的consume函数
431ea2daadSSMALLC     /// 接受一个函数 `f`,并在 `self.buffer` 上调用它。
441ea2daadSSMALLC     ///
451ea2daadSSMALLC     /// ## 参数
461ea2daadSSMALLC     /// - mut self :一个可变的 `LoopbackRxToken` 实例。
471ea2daadSSMALLC     /// - f :接受一个可变的 u8 切片,并返回类型 `R` 的结果。
481ea2daadSSMALLC     ///
491ea2daadSSMALLC     /// ## 返回值
501ea2daadSSMALLC     /// 返回函数 `f` 在 `self.buffer` 上的调用结果。
consume<R, F>(mut self, f: F) -> R where F: FnOnce(&mut [u8]) -> R,511ea2daadSSMALLC     fn consume<R, F>(mut self, f: F) -> R
521ea2daadSSMALLC     where
531ea2daadSSMALLC         F: FnOnce(&mut [u8]) -> R,
541ea2daadSSMALLC     {
551ea2daadSSMALLC         f(self.buffer.as_mut_slice())
561ea2daadSSMALLC     }
571ea2daadSSMALLC }
581ea2daadSSMALLC 
591ea2daadSSMALLC /// ## 环回发送令牌
601ea2daadSSMALLC /// 返回驱动用于操作lo设备
611ea2daadSSMALLC pub struct LoopbackTxToken {
621ea2daadSSMALLC     driver: LoopbackDriver,
631ea2daadSSMALLC }
641ea2daadSSMALLC 
651ea2daadSSMALLC impl phy::TxToken for LoopbackTxToken {
661ea2daadSSMALLC     /// ## 实现TxToken的consume函数
671ea2daadSSMALLC     /// 向lo的队列推入待发送的数据报,实现环回
681ea2daadSSMALLC     ///
691ea2daadSSMALLC     /// ## 参数
701ea2daadSSMALLC     /// - self
711ea2daadSSMALLC     /// - len:数据包的长度
721ea2daadSSMALLC     /// - f:接受一个可变的 u8 切片,并返回类型 `R` 的结果。
731ea2daadSSMALLC     ///
741ea2daadSSMALLC     /// ## 返回值
751ea2daadSSMALLC     /// 返回f对数据包操纵的结果
consume<R, F>(self, len: usize, f: F) -> R where F: FnOnce(&mut [u8]) -> R,761ea2daadSSMALLC     fn consume<R, F>(self, len: usize, f: F) -> R
771ea2daadSSMALLC     where
781ea2daadSSMALLC         F: FnOnce(&mut [u8]) -> R,
791ea2daadSSMALLC     {
801ea2daadSSMALLC         let mut buffer = vec![0; len];
811ea2daadSSMALLC         let result = f(buffer.as_mut_slice());
821ea2daadSSMALLC         let mut device = self.driver.inner.lock();
831ea2daadSSMALLC         device.loopback_transmit(buffer);
841ea2daadSSMALLC         result
851ea2daadSSMALLC     }
861ea2daadSSMALLC }
871ea2daadSSMALLC 
881ea2daadSSMALLC /// ## Loopback设备
891ea2daadSSMALLC /// 成员是一个队列,用来存放接受到的数据包。
901ea2daadSSMALLC /// 当使用lo发送数据包时,不会把数据包传到link层,而是直接发送到该队列,实现环回。
911ea2daadSSMALLC pub struct Loopback {
921ea2daadSSMALLC     //回环设备的缓冲区,接受的数据包会存放在这里,发送的数据包也会发送到这里,实现环回
931ea2daadSSMALLC     queue: VecDeque<Vec<u8>>,
941ea2daadSSMALLC }
951ea2daadSSMALLC 
961ea2daadSSMALLC impl Loopback {
971ea2daadSSMALLC     /// ## Loopback创建函数
981ea2daadSSMALLC     /// 创建lo设备
new() -> Self991ea2daadSSMALLC     pub fn new() -> Self {
1001ea2daadSSMALLC         let queue = VecDeque::new();
1011ea2daadSSMALLC         Loopback { queue }
1021ea2daadSSMALLC     }
1031ea2daadSSMALLC     /// ## Loopback处理接受到的数据包函数
1041ea2daadSSMALLC     /// Loopback接受到数据后会调用这个函数来弹出接收的数据,返回给协议栈
1051ea2daadSSMALLC     ///
1061ea2daadSSMALLC     /// ## 参数
1071ea2daadSSMALLC     /// - &mut self :自身可变引用
1081ea2daadSSMALLC     ///
1091ea2daadSSMALLC     /// ## 返回值
1101ea2daadSSMALLC     /// - queue的头部数据包
loopback_receive(&mut self) -> Vec<u8>1111ea2daadSSMALLC     pub fn loopback_receive(&mut self) -> Vec<u8> {
1121ea2daadSSMALLC         let buffer = self.queue.pop_front();
1131ea2daadSSMALLC         match buffer {
1141ea2daadSSMALLC             Some(buffer) => {
1151ea2daadSSMALLC                 //debug!("lo receive:{:?}", buffer);
1161ea2daadSSMALLC                 return buffer;
1171ea2daadSSMALLC             }
1181ea2daadSSMALLC             None => {
1191ea2daadSSMALLC                 return Vec::new();
1201ea2daadSSMALLC             }
1211ea2daadSSMALLC         }
1221ea2daadSSMALLC     }
1231ea2daadSSMALLC     /// ## Loopback发送数据包的函数
1241ea2daadSSMALLC     /// Loopback发送数据包给自己的接收队列,实现环回
1251ea2daadSSMALLC     ///
1261ea2daadSSMALLC     /// ## 参数
1271ea2daadSSMALLC     /// - &mut self:自身可变引用
1281ea2daadSSMALLC     /// - buffer:需要发送的数据包
loopback_transmit(&mut self, buffer: Vec<u8>)1291ea2daadSSMALLC     pub fn loopback_transmit(&mut self, buffer: Vec<u8>) {
1301ea2daadSSMALLC         //debug!("lo transmit!");
1311ea2daadSSMALLC         self.queue.push_back(buffer)
1321ea2daadSSMALLC     }
1331ea2daadSSMALLC }
1341ea2daadSSMALLC 
1351ea2daadSSMALLC /// ## driver的包裹器
1361ea2daadSSMALLC /// 为实现获得不可变引用的Interface的内部可变性,故为Driver提供UnsafeCell包裹器
1371ea2daadSSMALLC ///
1381ea2daadSSMALLC /// 参考virtio_net.rs
1391ea2daadSSMALLC struct LoopbackDriverWapper(UnsafeCell<LoopbackDriver>);
1401ea2daadSSMALLC unsafe impl Send for LoopbackDriverWapper {}
1411ea2daadSSMALLC unsafe impl Sync for LoopbackDriverWapper {}
1421ea2daadSSMALLC 
1431ea2daadSSMALLC /// ## deref 方法返回一个指向 `LoopbackDriver` 的引用。
1441ea2daadSSMALLC impl Deref for LoopbackDriverWapper {
1451ea2daadSSMALLC     type Target = LoopbackDriver;
deref(&self) -> &Self::Target1461ea2daadSSMALLC     fn deref(&self) -> &Self::Target {
1471ea2daadSSMALLC         unsafe { &*self.0.get() }
1481ea2daadSSMALLC     }
1491ea2daadSSMALLC }
1501ea2daadSSMALLC /// ## `deref_mut` 方法返回一个指向可变 `LoopbackDriver` 的引用。
1511ea2daadSSMALLC impl DerefMut for LoopbackDriverWapper {
deref_mut(&mut self) -> &mut Self::Target1521ea2daadSSMALLC     fn deref_mut(&mut self) -> &mut Self::Target {
1531ea2daadSSMALLC         unsafe { &mut *self.0.get() }
1541ea2daadSSMALLC     }
1551ea2daadSSMALLC }
1561ea2daadSSMALLC 
1571ea2daadSSMALLC impl LoopbackDriverWapper {
1581ea2daadSSMALLC     /// ## force_get_mut返回一个指向可变 `LoopbackDriver` 的引用。
1591ea2daadSSMALLC     #[allow(clippy::mut_from_ref)]
1601ea2daadSSMALLC     #[allow(clippy::mut_from_ref)]
force_get_mut(&self) -> &mut LoopbackDriver1611ea2daadSSMALLC     fn force_get_mut(&self) -> &mut LoopbackDriver {
1621ea2daadSSMALLC         unsafe { &mut *self.0.get() }
1631ea2daadSSMALLC     }
1641ea2daadSSMALLC }
1651ea2daadSSMALLC 
1661ea2daadSSMALLC /// ## Loopback驱动
1671ea2daadSSMALLC /// 负责操作Loopback设备实现基本的网卡功能
1681ea2daadSSMALLC pub struct LoopbackDriver {
1691ea2daadSSMALLC     pub inner: Arc<SpinLock<Loopback>>,
1701ea2daadSSMALLC }
1711ea2daadSSMALLC 
1721ea2daadSSMALLC impl LoopbackDriver {
1731ea2daadSSMALLC     /// ## LoopbackDriver创建函数
new() -> Self1741ea2daadSSMALLC     pub fn new() -> Self {
1751ea2daadSSMALLC         let inner = Arc::new(SpinLock::new(Loopback::new()));
1761ea2daadSSMALLC         LoopbackDriver { inner }
1771ea2daadSSMALLC     }
1781ea2daadSSMALLC }
1791ea2daadSSMALLC 
1801ea2daadSSMALLC impl Clone for LoopbackDriver {
clone(&self) -> Self1811ea2daadSSMALLC     fn clone(&self) -> Self {
1821ea2daadSSMALLC         LoopbackDriver {
1831ea2daadSSMALLC             inner: self.inner.clone(),
1841ea2daadSSMALLC         }
1851ea2daadSSMALLC     }
1861ea2daadSSMALLC }
1871ea2daadSSMALLC 
1881ea2daadSSMALLC impl phy::Device for LoopbackDriver {
1891ea2daadSSMALLC     type RxToken<'a> = LoopbackRxToken where Self: 'a;
1901ea2daadSSMALLC     type TxToken<'a> = LoopbackTxToken where Self: 'a;
1911ea2daadSSMALLC     /// ## 返回设备的物理层特性。
1921ea2daadSSMALLC     /// lo设备的最大传输单元为65535,最大突发大小为1,传输介质默认为Ethernet
capabilities(&self) -> phy::DeviceCapabilities1931ea2daadSSMALLC     fn capabilities(&self) -> phy::DeviceCapabilities {
1941ea2daadSSMALLC         let mut result = phy::DeviceCapabilities::default();
1951ea2daadSSMALLC         result.max_transmission_unit = 65535;
1961ea2daadSSMALLC         result.max_burst_size = Some(1);
1971ea2daadSSMALLC         result.medium = smoltcp::phy::Medium::Ethernet;
1981ea2daadSSMALLC         return result;
1991ea2daadSSMALLC     }
2001ea2daadSSMALLC     /// ## Loopback驱动处理接受数据事件
2011ea2daadSSMALLC     /// 驱动调用Loopback的receive函数,处理buffer封装成(rx,tx)返回给上层
2021ea2daadSSMALLC     ///
2031ea2daadSSMALLC     /// ## 参数
2041ea2daadSSMALLC     /// - `&mut self` :自身可变引用
2051ea2daadSSMALLC     /// - `_timestamp`
2061ea2daadSSMALLC     ///
2071ea2daadSSMALLC     /// ## 返回值
2081ea2daadSSMALLC     /// - None: 如果接收队列为空,返回 `None`,以通知上层没有可以接收的包
2091ea2daadSSMALLC     /// - Option::Some((rx, tx)):如果接收队列不为空,返回 `Some`,其中包含一个接收令牌 `rx` 和一个发送令牌 `tx`
receive( &mut self, _timestamp: smoltcp::time::Instant, ) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)>2101ea2daadSSMALLC     fn receive(
2111ea2daadSSMALLC         &mut self,
2121ea2daadSSMALLC         _timestamp: smoltcp::time::Instant,
2131ea2daadSSMALLC     ) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> {
2141ea2daadSSMALLC         let buffer = self.inner.lock().loopback_receive();
2151ea2daadSSMALLC         //receive队列为为空,返回NONE值以通知上层没有可以receive的包
2161ea2daadSSMALLC         if buffer.is_empty() {
2171ea2daadSSMALLC             return Option::None;
2181ea2daadSSMALLC         }
2191ea2daadSSMALLC         let rx = LoopbackRxToken { buffer };
2201ea2daadSSMALLC         let tx = LoopbackTxToken {
2211ea2daadSSMALLC             driver: self.clone(),
2221ea2daadSSMALLC         };
2231ea2daadSSMALLC         return Option::Some((rx, tx));
2241ea2daadSSMALLC     }
2251ea2daadSSMALLC     /// ## Loopback驱动处理发送数据包事件
2261ea2daadSSMALLC     /// Loopback驱动在需要发送数据时会调用这个函数来获取一个发送令牌。
2271ea2daadSSMALLC     ///
2281ea2daadSSMALLC     /// ## 参数
2291ea2daadSSMALLC     /// - `&mut self` :自身可变引用
2301ea2daadSSMALLC     /// - `_timestamp`
2311ea2daadSSMALLC     ///
2321ea2daadSSMALLC     /// ## 返回值
2331ea2daadSSMALLC     /// - 返回一个 `Some`,其中包含一个发送令牌,该令牌包含一个对自身的克隆引用
transmit(&mut self, _timestamp: smoltcp::time::Instant) -> Option<Self::TxToken<'_>>2341ea2daadSSMALLC     fn transmit(&mut self, _timestamp: smoltcp::time::Instant) -> Option<Self::TxToken<'_>> {
2351ea2daadSSMALLC         Some(LoopbackTxToken {
2361ea2daadSSMALLC             driver: self.clone(),
2371ea2daadSSMALLC         })
2381ea2daadSSMALLC     }
2391ea2daadSSMALLC }
2401ea2daadSSMALLC 
2411ea2daadSSMALLC /// ## LoopbackInterface结构
2421ea2daadSSMALLC /// 封装驱动包裹器和iface,设置接口名称
243*28fe4ad2S黄铭涛 #[cast_to([sync] NetDevice)]
244*28fe4ad2S黄铭涛 #[cast_to([sync] Device)]
2451ea2daadSSMALLC pub struct LoopbackInterface {
2461ea2daadSSMALLC     driver: LoopbackDriverWapper,
2471ea2daadSSMALLC     iface_id: usize,
2481ea2daadSSMALLC     iface: SpinLock<smoltcp::iface::Interface>,
2491ea2daadSSMALLC     name: String,
250*28fe4ad2S黄铭涛     inner: SpinLock<InnerLoopbackInterface>,
251*28fe4ad2S黄铭涛     locked_kobj_state: LockedKObjectState,
252*28fe4ad2S黄铭涛 }
253*28fe4ad2S黄铭涛 
254*28fe4ad2S黄铭涛 #[derive(Debug)]
255*28fe4ad2S黄铭涛 pub struct InnerLoopbackInterface {
256*28fe4ad2S黄铭涛     netdevice_common: NetDeviceCommonData,
257*28fe4ad2S黄铭涛     device_common: DeviceCommonData,
258*28fe4ad2S黄铭涛     kobj_common: KObjectCommonData,
2591ea2daadSSMALLC }
2601ea2daadSSMALLC 
2611ea2daadSSMALLC impl LoopbackInterface {
2621ea2daadSSMALLC     /// ## `new` 是一个公共函数,用于创建一个新的 `LoopbackInterface` 实例。
2631ea2daadSSMALLC     /// 生成一个新的接口 ID。创建一个新的接口配置,设置其硬件地址和随机种子,使用接口配置和驱动器创建一个新的 `smoltcp::iface::Interface` 实例。
2641ea2daadSSMALLC     /// 设置接口的 IP 地址为 127.0.0.1。
2651ea2daadSSMALLC     /// 创建一个新的 `LoopbackDriverWapper` 实例,包装驱动器。
2661ea2daadSSMALLC     /// 创建一个新的 `LoopbackInterface` 实例,包含驱动器、接口 ID、接口和名称,并将其封装在一个 `Arc` 中。
2671ea2daadSSMALLC     /// ## 参数
2681ea2daadSSMALLC     /// - `driver`:一个 `LoopbackDriver` 实例,用于驱动网络环回操作。
2691ea2daadSSMALLC     ///
2701ea2daadSSMALLC     /// ## 返回值
2711ea2daadSSMALLC     /// 返回一个 `Arc<Self>`,即一个指向新创建的 `LoopbackInterface` 实例的智能指针。
new(mut driver: LoopbackDriver) -> Arc<Self>2721ea2daadSSMALLC     pub fn new(mut driver: LoopbackDriver) -> Arc<Self> {
2731ea2daadSSMALLC         let iface_id = generate_iface_id();
2741ea2daadSSMALLC         let mut iface_config = smoltcp::iface::Config::new(HardwareAddress::Ethernet(
2751ea2daadSSMALLC             smoltcp::wire::EthernetAddress([0x02, 0x00, 0x00, 0x00, 0x00, 0x01]),
2761ea2daadSSMALLC         ));
2771ea2daadSSMALLC         iface_config.random_seed = rand() as u64;
2781ea2daadSSMALLC 
2791ea2daadSSMALLC         let mut iface =
2801ea2daadSSMALLC             smoltcp::iface::Interface::new(iface_config, &mut driver, Instant::now().into());
2811ea2daadSSMALLC         //设置网卡地址为127.0.0.1
2821ea2daadSSMALLC         iface.update_ip_addrs(|ip_addrs| {
2831ea2daadSSMALLC             ip_addrs
2841ea2daadSSMALLC                 .push(IpCidr::new(IpAddress::v4(127, 0, 0, 1), 8))
2851ea2daadSSMALLC                 .unwrap();
2861ea2daadSSMALLC         });
2871ea2daadSSMALLC         let driver = LoopbackDriverWapper(UnsafeCell::new(driver));
2881ea2daadSSMALLC         Arc::new(LoopbackInterface {
2891ea2daadSSMALLC             driver,
2901ea2daadSSMALLC             iface_id,
2911ea2daadSSMALLC             iface: SpinLock::new(iface),
2921ea2daadSSMALLC             name: "lo".to_string(),
293*28fe4ad2S黄铭涛             inner: SpinLock::new(InnerLoopbackInterface {
294*28fe4ad2S黄铭涛                 netdevice_common: NetDeviceCommonData::default(),
295*28fe4ad2S黄铭涛                 device_common: DeviceCommonData::default(),
296*28fe4ad2S黄铭涛                 kobj_common: KObjectCommonData::default(),
297*28fe4ad2S黄铭涛             }),
298*28fe4ad2S黄铭涛             locked_kobj_state: LockedKObjectState::default(),
2991ea2daadSSMALLC         })
3001ea2daadSSMALLC     }
301*28fe4ad2S黄铭涛 
inner(&self) -> SpinLockGuard<InnerLoopbackInterface>302*28fe4ad2S黄铭涛     fn inner(&self) -> SpinLockGuard<InnerLoopbackInterface> {
303*28fe4ad2S黄铭涛         return self.inner.lock();
304*28fe4ad2S黄铭涛     }
3051ea2daadSSMALLC }
3061ea2daadSSMALLC 
3071ea2daadSSMALLC impl Debug for LoopbackInterface {
fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result3081ea2daadSSMALLC     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
3091ea2daadSSMALLC         f.debug_struct("LoopbackInterface")
3101ea2daadSSMALLC             .field("iface_id", &self.iface_id)
3111ea2daadSSMALLC             .field("iface", &"smtoltcp::iface::Interface")
3121ea2daadSSMALLC             .field("name", &self.name)
3131ea2daadSSMALLC             .finish()
3141ea2daadSSMALLC     }
3151ea2daadSSMALLC }
316*28fe4ad2S黄铭涛 
3171ea2daadSSMALLC impl KObject for LoopbackInterface {
as_any_ref(&self) -> &dyn core::any::Any3181ea2daadSSMALLC     fn as_any_ref(&self) -> &dyn core::any::Any {
3191ea2daadSSMALLC         self
3201ea2daadSSMALLC     }
3211ea2daadSSMALLC 
set_inode(&self, inode: Option<Arc<KernFSInode>>)322*28fe4ad2S黄铭涛     fn set_inode(&self, inode: Option<Arc<KernFSInode>>) {
323*28fe4ad2S黄铭涛         self.inner().kobj_common.kern_inode = inode;
3241ea2daadSSMALLC     }
3251ea2daadSSMALLC 
inode(&self) -> Option<Arc<KernFSInode>>326*28fe4ad2S黄铭涛     fn inode(&self) -> Option<Arc<KernFSInode>> {
327*28fe4ad2S黄铭涛         self.inner().kobj_common.kern_inode.clone()
3281ea2daadSSMALLC     }
3291ea2daadSSMALLC 
parent(&self) -> Option<Weak<dyn KObject>>330*28fe4ad2S黄铭涛     fn parent(&self) -> Option<Weak<dyn KObject>> {
331*28fe4ad2S黄铭涛         self.inner().kobj_common.parent.clone()
3321ea2daadSSMALLC     }
3331ea2daadSSMALLC 
set_parent(&self, parent: Option<Weak<dyn KObject>>)334*28fe4ad2S黄铭涛     fn set_parent(&self, parent: Option<Weak<dyn KObject>>) {
335*28fe4ad2S黄铭涛         self.inner().kobj_common.parent = parent;
3361ea2daadSSMALLC     }
3371ea2daadSSMALLC 
kset(&self) -> Option<Arc<KSet>>338*28fe4ad2S黄铭涛     fn kset(&self) -> Option<Arc<KSet>> {
339*28fe4ad2S黄铭涛         self.inner().kobj_common.kset.clone()
3401ea2daadSSMALLC     }
3411ea2daadSSMALLC 
set_kset(&self, kset: Option<Arc<KSet>>)342*28fe4ad2S黄铭涛     fn set_kset(&self, kset: Option<Arc<KSet>>) {
343*28fe4ad2S黄铭涛         self.inner().kobj_common.kset = kset;
3441ea2daadSSMALLC     }
3451ea2daadSSMALLC 
kobj_type(&self) -> Option<&'static dyn KObjType>346*28fe4ad2S黄铭涛     fn kobj_type(&self) -> Option<&'static dyn KObjType> {
347*28fe4ad2S黄铭涛         self.inner().kobj_common.kobj_type
3481ea2daadSSMALLC     }
3491ea2daadSSMALLC 
name(&self) -> String3501ea2daadSSMALLC     fn name(&self) -> String {
3511ea2daadSSMALLC         self.name.clone()
3521ea2daadSSMALLC     }
3531ea2daadSSMALLC 
set_name(&self, _name: String)3541ea2daadSSMALLC     fn set_name(&self, _name: String) {
355*28fe4ad2S黄铭涛         // do nothing
3561ea2daadSSMALLC     }
3571ea2daadSSMALLC 
kobj_state(&self) -> RwLockReadGuard<KObjectState>358*28fe4ad2S黄铭涛     fn kobj_state(&self) -> RwLockReadGuard<KObjectState> {
359*28fe4ad2S黄铭涛         self.locked_kobj_state.read()
3601ea2daadSSMALLC     }
3611ea2daadSSMALLC 
kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState>362*28fe4ad2S黄铭涛     fn kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState> {
363*28fe4ad2S黄铭涛         self.locked_kobj_state.write()
3641ea2daadSSMALLC     }
3651ea2daadSSMALLC 
set_kobj_state(&self, state: KObjectState)366*28fe4ad2S黄铭涛     fn set_kobj_state(&self, state: KObjectState) {
367*28fe4ad2S黄铭涛         *self.locked_kobj_state.write() = state;
3681ea2daadSSMALLC     }
3691ea2daadSSMALLC 
set_kobj_type(&self, ktype: Option<&'static dyn KObjType>)370*28fe4ad2S黄铭涛     fn set_kobj_type(&self, ktype: Option<&'static dyn KObjType>) {
371*28fe4ad2S黄铭涛         self.inner().kobj_common.kobj_type = ktype;
3721ea2daadSSMALLC     }
3731ea2daadSSMALLC }
3741ea2daadSSMALLC 
3751ea2daadSSMALLC impl Device for LoopbackInterface {
dev_type(&self) -> DeviceType3761ea2daadSSMALLC     fn dev_type(&self) -> DeviceType {
3771ea2daadSSMALLC         DeviceType::Net
3781ea2daadSSMALLC     }
3791ea2daadSSMALLC 
id_table(&self) -> IdTable3801ea2daadSSMALLC     fn id_table(&self) -> IdTable {
3811ea2daadSSMALLC         IdTable::new(DEVICE_NAME.to_string(), None)
3821ea2daadSSMALLC     }
3831ea2daadSSMALLC 
bus(&self) -> Option<Weak<dyn Bus>>384*28fe4ad2S黄铭涛     fn bus(&self) -> Option<Weak<dyn Bus>> {
385*28fe4ad2S黄铭涛         self.inner().device_common.bus.clone()
3861ea2daadSSMALLC     }
3871ea2daadSSMALLC 
set_bus(&self, bus: Option<Weak<dyn Bus>>)388*28fe4ad2S黄铭涛     fn set_bus(&self, bus: Option<Weak<dyn Bus>>) {
389*28fe4ad2S黄铭涛         self.inner().device_common.bus = bus;
390*28fe4ad2S黄铭涛     }
391*28fe4ad2S黄铭涛 
class(&self) -> Option<Arc<dyn Class>>392*28fe4ad2S黄铭涛     fn class(&self) -> Option<Arc<dyn Class>> {
393*28fe4ad2S黄铭涛         let mut guard = self.inner();
394*28fe4ad2S黄铭涛         let r = guard.device_common.class.clone()?.upgrade();
395*28fe4ad2S黄铭涛         if r.is_none() {
396*28fe4ad2S黄铭涛             guard.device_common.class = None;
397*28fe4ad2S黄铭涛         }
398*28fe4ad2S黄铭涛 
399*28fe4ad2S黄铭涛         return r;
400*28fe4ad2S黄铭涛     }
401*28fe4ad2S黄铭涛 
set_class(&self, class: Option<Weak<dyn Class>>)402*28fe4ad2S黄铭涛     fn set_class(&self, class: Option<Weak<dyn Class>>) {
403*28fe4ad2S黄铭涛         self.inner().device_common.class = class;
4041ea2daadSSMALLC     }
4051ea2daadSSMALLC 
driver(&self) -> Option<Arc<dyn Driver>>4061ea2daadSSMALLC     fn driver(&self) -> Option<Arc<dyn Driver>> {
407*28fe4ad2S黄铭涛         let r = self.inner().device_common.driver.clone()?.upgrade();
408*28fe4ad2S黄铭涛         if r.is_none() {
409*28fe4ad2S黄铭涛             self.inner().device_common.driver = None;
4101ea2daadSSMALLC         }
4111ea2daadSSMALLC 
412*28fe4ad2S黄铭涛         return r;
413*28fe4ad2S黄铭涛     }
414*28fe4ad2S黄铭涛 
set_driver(&self, driver: Option<Weak<dyn Driver>>)415*28fe4ad2S黄铭涛     fn set_driver(&self, driver: Option<Weak<dyn Driver>>) {
416*28fe4ad2S黄铭涛         self.inner().device_common.driver = driver;
4171ea2daadSSMALLC     }
4181ea2daadSSMALLC 
is_dead(&self) -> bool4191ea2daadSSMALLC     fn is_dead(&self) -> bool {
420*28fe4ad2S黄铭涛         false
4211ea2daadSSMALLC     }
4221ea2daadSSMALLC 
can_match(&self) -> bool4231ea2daadSSMALLC     fn can_match(&self) -> bool {
424*28fe4ad2S黄铭涛         self.inner().device_common.can_match
4251ea2daadSSMALLC     }
4261ea2daadSSMALLC 
set_can_match(&self, can_match: bool)427*28fe4ad2S黄铭涛     fn set_can_match(&self, can_match: bool) {
428*28fe4ad2S黄铭涛         self.inner().device_common.can_match = can_match;
4291ea2daadSSMALLC     }
4301ea2daadSSMALLC 
state_synced(&self) -> bool4311ea2daadSSMALLC     fn state_synced(&self) -> bool {
4321ea2daadSSMALLC         true
4331ea2daadSSMALLC     }
434*28fe4ad2S黄铭涛 
dev_parent(&self) -> Option<Weak<dyn Device>>435*28fe4ad2S黄铭涛     fn dev_parent(&self) -> Option<Weak<dyn Device>> {
436*28fe4ad2S黄铭涛         self.inner().device_common.get_parent_weak_or_clear()
437*28fe4ad2S黄铭涛     }
438*28fe4ad2S黄铭涛 
set_dev_parent(&self, parent: Option<Weak<dyn Device>>)439*28fe4ad2S黄铭涛     fn set_dev_parent(&self, parent: Option<Weak<dyn Device>>) {
440*28fe4ad2S黄铭涛         self.inner().device_common.parent = parent;
441*28fe4ad2S黄铭涛     }
4421ea2daadSSMALLC }
4431ea2daadSSMALLC 
4441ea2daadSSMALLC impl NetDevice for LoopbackInterface {
445*28fe4ad2S黄铭涛     /// 由于lo网卡设备不是实际的物理设备,其mac地址需要手动设置为一个默认值,这里默认为00:00:00:00:00
mac(&self) -> smoltcp::wire::EthernetAddress4461ea2daadSSMALLC     fn mac(&self) -> smoltcp::wire::EthernetAddress {
447*28fe4ad2S黄铭涛         let mac = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
4481ea2daadSSMALLC         smoltcp::wire::EthernetAddress(mac)
4491ea2daadSSMALLC     }
4501ea2daadSSMALLC 
4511ea2daadSSMALLC     #[inline]
nic_id(&self) -> usize4521ea2daadSSMALLC     fn nic_id(&self) -> usize {
4531ea2daadSSMALLC         self.iface_id
4541ea2daadSSMALLC     }
4551ea2daadSSMALLC 
4561ea2daadSSMALLC     #[inline]
iface_name(&self) -> String457*28fe4ad2S黄铭涛     fn iface_name(&self) -> String {
4581ea2daadSSMALLC         self.name.clone()
4591ea2daadSSMALLC     }
4601ea2daadSSMALLC     /// ## `update_ip_addrs` 用于更新接口的 IP 地址。
4611ea2daadSSMALLC     ///
4621ea2daadSSMALLC     /// ## 参数
4631ea2daadSSMALLC     /// - `&self` :自身引用
4641ea2daadSSMALLC     /// - `ip_addrs` :一个包含 `smoltcp::wire::IpCidr` 的切片,表示要设置的 IP 地址和子网掩码
4651ea2daadSSMALLC     ///
4661ea2daadSSMALLC     /// ## 返回值
4671ea2daadSSMALLC     /// - 如果 `ip_addrs` 的长度不为 1,返回 `Err(SystemError::EINVAL)`,表示输入参数无效
4681ea2daadSSMALLC     /// - 如果更新成功,返回 `Ok(())`
update_ip_addrs( &self, ip_addrs: &[smoltcp::wire::IpCidr], ) -> Result<(), system_error::SystemError>4691ea2daadSSMALLC     fn update_ip_addrs(
4701ea2daadSSMALLC         &self,
4711ea2daadSSMALLC         ip_addrs: &[smoltcp::wire::IpCidr],
4721ea2daadSSMALLC     ) -> Result<(), system_error::SystemError> {
4731ea2daadSSMALLC         if ip_addrs.len() != 1 {
4741ea2daadSSMALLC             return Err(SystemError::EINVAL);
4751ea2daadSSMALLC         }
4761ea2daadSSMALLC 
4771ea2daadSSMALLC         self.iface.lock().update_ip_addrs(|addrs| {
4781ea2daadSSMALLC             let dest = addrs.iter_mut().next();
4791ea2daadSSMALLC 
4801ea2daadSSMALLC             if let Some(dest) = dest {
4811ea2daadSSMALLC                 *dest = ip_addrs[0];
4821ea2daadSSMALLC             } else {
4831ea2daadSSMALLC                 addrs.push(ip_addrs[0]).expect("Push ipCidr failed: full");
4841ea2daadSSMALLC             }
4851ea2daadSSMALLC         });
4861ea2daadSSMALLC         return Ok(());
4871ea2daadSSMALLC     }
4881ea2daadSSMALLC     /// ## `poll` 用于轮询接口的状态。
4891ea2daadSSMALLC     ///
4901ea2daadSSMALLC     /// ## 参数
4911ea2daadSSMALLC     /// - `&self` :自身引用
4921ea2daadSSMALLC     /// - `sockets` :一个可变引用到 `smoltcp::iface::SocketSet`,表示要轮询的套接字集
4931ea2daadSSMALLC     ///
4941ea2daadSSMALLC     /// ## 返回值
4951ea2daadSSMALLC     /// - 如果轮询成功,返回 `Ok(())`
4961ea2daadSSMALLC     /// - 如果轮询失败,返回 `Err(SystemError::EAGAIN_OR_EWOULDBLOCK)`,表示需要再次尝试或者操作会阻塞
poll(&self, sockets: &mut smoltcp::iface::SocketSet) -> Result<(), SystemError>4971ea2daadSSMALLC     fn poll(&self, sockets: &mut smoltcp::iface::SocketSet) -> Result<(), SystemError> {
4981ea2daadSSMALLC         let timestamp: smoltcp::time::Instant = Instant::now().into();
4991ea2daadSSMALLC         let mut guard = self.iface.lock();
5001ea2daadSSMALLC         let poll_res = guard.poll(timestamp, self.driver.force_get_mut(), sockets);
5011ea2daadSSMALLC         if poll_res {
5021ea2daadSSMALLC             return Ok(());
5031ea2daadSSMALLC         }
5041ea2daadSSMALLC         return Err(SystemError::EAGAIN_OR_EWOULDBLOCK);
5051ea2daadSSMALLC     }
5061ea2daadSSMALLC 
5071ea2daadSSMALLC     #[inline(always)]
inner_iface(&self) -> &SpinLock<smoltcp::iface::Interface>5081ea2daadSSMALLC     fn inner_iface(&self) -> &SpinLock<smoltcp::iface::Interface> {
5091ea2daadSSMALLC         return &self.iface;
5101ea2daadSSMALLC     }
511*28fe4ad2S黄铭涛 
addr_assign_type(&self) -> u8512*28fe4ad2S黄铭涛     fn addr_assign_type(&self) -> u8 {
513*28fe4ad2S黄铭涛         return self.inner().netdevice_common.addr_assign_type;
514*28fe4ad2S黄铭涛     }
515*28fe4ad2S黄铭涛 
net_device_type(&self) -> u16516*28fe4ad2S黄铭涛     fn net_device_type(&self) -> u16 {
517*28fe4ad2S黄铭涛         self.inner().netdevice_common.net_device_type = 24; // 环回设备
518*28fe4ad2S黄铭涛         return self.inner().netdevice_common.net_device_type;
519*28fe4ad2S黄铭涛     }
520*28fe4ad2S黄铭涛 
net_state(&self) -> NetDeivceState521*28fe4ad2S黄铭涛     fn net_state(&self) -> NetDeivceState {
522*28fe4ad2S黄铭涛         return self.inner().netdevice_common.state;
523*28fe4ad2S黄铭涛     }
524*28fe4ad2S黄铭涛 
set_net_state(&self, state: NetDeivceState)525*28fe4ad2S黄铭涛     fn set_net_state(&self, state: NetDeivceState) {
526*28fe4ad2S黄铭涛         self.inner().netdevice_common.state |= state;
527*28fe4ad2S黄铭涛     }
528*28fe4ad2S黄铭涛 
operstate(&self) -> Operstate529*28fe4ad2S黄铭涛     fn operstate(&self) -> Operstate {
530*28fe4ad2S黄铭涛         return self.inner().netdevice_common.operstate;
531*28fe4ad2S黄铭涛     }
532*28fe4ad2S黄铭涛 
set_operstate(&self, state: Operstate)533*28fe4ad2S黄铭涛     fn set_operstate(&self, state: Operstate) {
534*28fe4ad2S黄铭涛         self.inner().netdevice_common.operstate = state;
535*28fe4ad2S黄铭涛     }
5361ea2daadSSMALLC }
5371ea2daadSSMALLC 
loopback_probe()5381ea2daadSSMALLC pub fn loopback_probe() {
5391ea2daadSSMALLC     loopback_driver_init();
5401ea2daadSSMALLC }
5411ea2daadSSMALLC /// ## lo网卡设备初始化函数
5421ea2daadSSMALLC /// 创建驱动和iface,初始化一个lo网卡,添加到全局NET_DEVICES中
loopback_driver_init()5431ea2daadSSMALLC pub fn loopback_driver_init() {
5441ea2daadSSMALLC     let driver = LoopbackDriver::new();
5451ea2daadSSMALLC     let iface = LoopbackInterface::new(driver);
546*28fe4ad2S黄铭涛     // 标识网络设备已经启动
547*28fe4ad2S黄铭涛     iface.set_net_state(NetDeivceState::__LINK_STATE_START);
5481ea2daadSSMALLC 
5491ea2daadSSMALLC     NET_DEVICES
5501ea2daadSSMALLC         .write_irqsave()
5511ea2daadSSMALLC         .insert(iface.iface_id, iface.clone());
552*28fe4ad2S黄铭涛 
553*28fe4ad2S黄铭涛     register_netdevice(iface.clone()).expect("register lo device failed");
5541ea2daadSSMALLC }
5551ea2daadSSMALLC 
5561ea2daadSSMALLC /// ## lo网卡设备的注册函数
5571ea2daadSSMALLC #[unified_init(INITCALL_DEVICE)]
loopback_init() -> Result<(), SystemError>5581ea2daadSSMALLC pub fn loopback_init() -> Result<(), SystemError> {
5591ea2daadSSMALLC     loopback_probe();
5601ea2daadSSMALLC     return Ok(());
5611ea2daadSSMALLC }
562