loopback.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. use crate::arch::rand::rand;
  2. use crate::driver::base::class::Class;
  3. use crate::driver::base::device::bus::Bus;
  4. use crate::driver::base::device::driver::Driver;
  5. use crate::driver::base::device::{Device, DeviceCommonData, DeviceType, IdTable};
  6. use crate::driver::base::kobject::{
  7. KObjType, KObject, KObjectCommonData, KObjectState, LockedKObjectState,
  8. };
  9. use crate::driver::base::kset::KSet;
  10. use crate::filesystem::kernfs::KernFSInode;
  11. // use crate::init::initcall::INITCALL_DEVICE;
  12. use crate::libs::rwlock::{RwLockReadGuard, RwLockWriteGuard};
  13. use crate::libs::spinlock::{SpinLock, SpinLockGuard};
  14. use crate::net::{generate_iface_id, NET_DEVICES};
  15. use crate::time::Instant;
  16. use alloc::collections::VecDeque;
  17. use alloc::fmt::Debug;
  18. use alloc::string::{String, ToString};
  19. use alloc::sync::{Arc, Weak};
  20. use alloc::vec::Vec;
  21. use core::cell::UnsafeCell;
  22. use core::ops::{Deref, DerefMut};
  23. use smoltcp::wire::HardwareAddress;
  24. use smoltcp::{
  25. phy::{self},
  26. wire::{IpAddress, IpCidr},
  27. };
  28. use system_error::SystemError;
  29. // use unified_init::macros::unified_init;
  30. use super::{register_netdevice, NetDeivceState, NetDeviceCommonData, Operstate};
  31. use super::{Iface, IfaceCommon};
  32. const DEVICE_NAME: &str = "loopback";
  33. /// ## 环回接收令牌
  34. /// 用于储存lo网卡接收到的数据
  35. pub struct LoopbackRxToken {
  36. buffer: Vec<u8>,
  37. }
  38. impl phy::RxToken for LoopbackRxToken {
  39. /// ## 实现Rxtoken的consume函数
  40. /// 接受一个函数 `f`,并在 `self.buffer` 上调用它。
  41. ///
  42. /// ## 参数
  43. /// - mut self :一个可变的 `LoopbackRxToken` 实例。
  44. /// - f :接受一个可变的 u8 切片,并返回类型 `R` 的结果。
  45. ///
  46. /// ## 返回值
  47. /// 返回函数 `f` 在 `self.buffer` 上的调用结果。
  48. fn consume<R, F>(mut self, f: F) -> R
  49. where
  50. F: FnOnce(&mut [u8]) -> R,
  51. {
  52. f(self.buffer.as_mut_slice())
  53. }
  54. }
  55. /// ## 环回发送令牌
  56. /// 返回驱动用于操作lo设备
  57. pub struct LoopbackTxToken {
  58. driver: LoopbackDriver,
  59. }
  60. impl phy::TxToken for LoopbackTxToken {
  61. /// ## 实现TxToken的consume函数
  62. /// 向lo的队列推入待发送的数据报,实现环回
  63. ///
  64. /// ## 参数
  65. /// - self
  66. /// - len:数据包的长度
  67. /// - f:接受一个可变的 u8 切片,并返回类型 `R` 的结果。
  68. ///
  69. /// ## 返回值
  70. /// 返回f对数据包操纵的结果
  71. fn consume<R, F>(self, len: usize, f: F) -> R
  72. where
  73. F: FnOnce(&mut [u8]) -> R,
  74. {
  75. let mut buffer = vec![0; len];
  76. let result = f(buffer.as_mut_slice());
  77. let mut device = self.driver.inner.lock();
  78. device.loopback_transmit(buffer);
  79. // debug!("lo transmit!");
  80. result
  81. }
  82. }
  83. /// ## Loopback设备
  84. /// 成员是一个队列,用来存放接受到的数据包。
  85. /// 当使用lo发送数据包时,不会把数据包传到link层,而是直接发送到该队列,实现环回。
  86. pub struct Loopback {
  87. //回环设备的缓冲区,接受的数据包会存放在这里,发送的数据包也会发送到这里,实现环回
  88. queue: VecDeque<Vec<u8>>,
  89. }
  90. impl Loopback {
  91. /// ## Loopback创建函数
  92. /// 创建lo设备
  93. pub fn new() -> Self {
  94. let queue = VecDeque::new();
  95. Loopback { queue }
  96. }
  97. /// ## Loopback处理接受到的数据包函数
  98. /// Loopback接受到数据后会调用这个函数来弹出接收的数据,返回给协议栈
  99. ///
  100. /// ## 参数
  101. /// - &mut self :自身可变引用
  102. ///
  103. /// ## 返回值
  104. /// - queue的头部数据包
  105. pub fn loopback_receive(&mut self) -> Vec<u8> {
  106. let buffer = self.queue.pop_front();
  107. match buffer {
  108. Some(buffer) => {
  109. // debug!("lo receive:{:?}", buffer);
  110. return buffer;
  111. }
  112. None => {
  113. return Vec::new();
  114. }
  115. }
  116. }
  117. /// ## Loopback发送数据包的函数
  118. /// Loopback发送数据包给自己的接收队列,实现环回
  119. ///
  120. /// ## 参数
  121. /// - &mut self:自身可变引用
  122. /// - buffer:需要发送的数据包
  123. pub fn loopback_transmit(&mut self, buffer: Vec<u8>) {
  124. // debug!("lo transmit:{:?}", buffer);
  125. self.queue.push_back(buffer)
  126. }
  127. }
  128. /// ## driver的包裹器
  129. /// 为实现获得不可变引用的Interface的内部可变性,故为Driver提供UnsafeCell包裹器
  130. ///
  131. /// 参考virtio_net.rs
  132. #[derive(Debug)]
  133. struct LoopbackDriverWapper(UnsafeCell<LoopbackDriver>);
  134. unsafe impl Send for LoopbackDriverWapper {}
  135. unsafe impl Sync for LoopbackDriverWapper {}
  136. /// ## deref 方法返回一个指向 `LoopbackDriver` 的引用。
  137. impl Deref for LoopbackDriverWapper {
  138. type Target = LoopbackDriver;
  139. fn deref(&self) -> &Self::Target {
  140. unsafe { &*self.0.get() }
  141. }
  142. }
  143. /// ## `deref_mut` 方法返回一个指向可变 `LoopbackDriver` 的引用。
  144. impl DerefMut for LoopbackDriverWapper {
  145. fn deref_mut(&mut self) -> &mut Self::Target {
  146. unsafe { &mut *self.0.get() }
  147. }
  148. }
  149. impl LoopbackDriverWapper {
  150. /// ## force_get_mut返回一个指向可变 `LoopbackDriver` 的引用。
  151. #[allow(clippy::mut_from_ref)]
  152. #[allow(clippy::mut_from_ref)]
  153. fn force_get_mut(&self) -> &mut LoopbackDriver {
  154. unsafe { &mut *self.0.get() }
  155. }
  156. }
  157. /// ## Loopback驱动
  158. /// 负责操作Loopback设备实现基本的网卡功能
  159. pub struct LoopbackDriver {
  160. pub inner: Arc<SpinLock<Loopback>>,
  161. }
  162. impl LoopbackDriver {
  163. /// ## LoopbackDriver创建函数
  164. pub fn new() -> Self {
  165. let inner = Arc::new(SpinLock::new(Loopback::new()));
  166. LoopbackDriver { inner }
  167. }
  168. }
  169. impl Clone for LoopbackDriver {
  170. fn clone(&self) -> Self {
  171. LoopbackDriver {
  172. inner: self.inner.clone(),
  173. }
  174. }
  175. }
  176. impl phy::Device for LoopbackDriver {
  177. type RxToken<'a> = LoopbackRxToken where Self: 'a;
  178. type TxToken<'a> = LoopbackTxToken where Self: 'a;
  179. /// ## 返回设备的物理层特性。
  180. /// lo设备的最大传输单元为65535,最大突发大小为1,传输介质默认为Ethernet
  181. fn capabilities(&self) -> phy::DeviceCapabilities {
  182. let mut result = phy::DeviceCapabilities::default();
  183. result.max_transmission_unit = 65535;
  184. result.max_burst_size = Some(1);
  185. result.medium = smoltcp::phy::Medium::Ethernet;
  186. return result;
  187. }
  188. /// ## Loopback驱动处理接受数据事件
  189. /// 驱动调用Loopback的receive函数,处理buffer封装成(rx,tx)返回给上层
  190. ///
  191. /// ## 参数
  192. /// - `&mut self` :自身可变引用
  193. /// - `_timestamp`
  194. ///
  195. /// ## 返回值
  196. /// - None: 如果接收队列为空,返回 `None`,以通知上层没有可以接收的包
  197. /// - Option::Some((rx, tx)):如果接收队列不为空,返回 `Some`,其中包含一个接收令牌 `rx` 和一个发送令牌 `tx`
  198. fn receive(
  199. &mut self,
  200. _timestamp: smoltcp::time::Instant,
  201. ) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> {
  202. let buffer = self.inner.lock().loopback_receive();
  203. //receive队列为为空,返回NONE值以通知上层没有可以receive的包
  204. if buffer.is_empty() {
  205. // log::debug!("lo receive none!");
  206. return Option::None;
  207. }
  208. // log::debug!("lo receive!");
  209. let rx = LoopbackRxToken { buffer };
  210. let tx = LoopbackTxToken {
  211. driver: self.clone(),
  212. };
  213. return Option::Some((rx, tx));
  214. }
  215. /// ## Loopback驱动处理发送数据包事件
  216. /// Loopback驱动在需要发送数据时会调用这个函数来获取一个发送令牌。
  217. ///
  218. /// ## 参数
  219. /// - `&mut self` :自身可变引用
  220. /// - `_timestamp`
  221. ///
  222. /// ## 返回值
  223. /// - 返回一个 `Some`,其中包含一个发送令牌,该令牌包含一个对自身的克隆引用
  224. fn transmit(&mut self, _timestamp: smoltcp::time::Instant) -> Option<Self::TxToken<'_>> {
  225. // log::debug!("lo transmit!");
  226. Some(LoopbackTxToken {
  227. driver: self.clone(),
  228. })
  229. }
  230. }
  231. /// ## LoopbackInterface结构
  232. /// 封装驱动包裹器和iface,设置接口名称
  233. #[cast_to([sync] Iface)]
  234. #[cast_to([sync] Device)]
  235. #[derive(Debug)]
  236. pub struct LoopbackInterface {
  237. driver: LoopbackDriverWapper,
  238. common: IfaceCommon,
  239. inner: SpinLock<InnerLoopbackInterface>,
  240. locked_kobj_state: LockedKObjectState,
  241. }
  242. #[derive(Debug)]
  243. pub struct InnerLoopbackInterface {
  244. netdevice_common: NetDeviceCommonData,
  245. device_common: DeviceCommonData,
  246. kobj_common: KObjectCommonData,
  247. }
  248. impl LoopbackInterface {
  249. /// ## `new` 是一个公共函数,用于创建一个新的 `LoopbackInterface` 实例。
  250. /// 生成一个新的接口 ID。创建一个新的接口配置,设置其硬件地址和随机种子,使用接口配置和驱动器创建一个新的 `smoltcp::iface::Interface` 实例。
  251. /// 设置接口的 IP 地址为 127.0.0.1。
  252. /// 创建一个新的 `LoopbackDriverWapper` 实例,包装驱动器。
  253. /// 创建一个新的 `LoopbackInterface` 实例,包含驱动器、接口 ID、接口和名称,并将其封装在一个 `Arc` 中。
  254. /// ## 参数
  255. /// - `driver`:一个 `LoopbackDriver` 实例,用于驱动网络环回操作。
  256. ///
  257. /// ## 返回值
  258. /// 返回一个 `Arc<Self>`,即一个指向新创建的 `LoopbackInterface` 实例的智能指针。
  259. pub fn new(mut driver: LoopbackDriver) -> Arc<Self> {
  260. let iface_id = generate_iface_id();
  261. let mut iface_config = smoltcp::iface::Config::new(HardwareAddress::Ethernet(
  262. smoltcp::wire::EthernetAddress([0x02, 0x00, 0x00, 0x00, 0x00, 0x01]),
  263. ));
  264. iface_config.random_seed = rand() as u64;
  265. let mut iface =
  266. smoltcp::iface::Interface::new(iface_config, &mut driver, Instant::now().into());
  267. //设置网卡地址为127.0.0.1
  268. iface.update_ip_addrs(|ip_addrs| {
  269. for i in 1..=2 {
  270. ip_addrs
  271. .push(IpCidr::new(IpAddress::v4(127, 0, 0, i), 8))
  272. .expect("Push ipCidr failed: full");
  273. }
  274. });
  275. // iface.routes_mut().update(|routes_map| {
  276. // routes_map[0].
  277. // });
  278. Arc::new(LoopbackInterface {
  279. driver: LoopbackDriverWapper(UnsafeCell::new(driver)),
  280. common: IfaceCommon::new(iface_id, iface),
  281. inner: SpinLock::new(InnerLoopbackInterface {
  282. netdevice_common: NetDeviceCommonData::default(),
  283. device_common: DeviceCommonData::default(),
  284. kobj_common: KObjectCommonData::default(),
  285. }),
  286. locked_kobj_state: LockedKObjectState::default(),
  287. })
  288. }
  289. fn inner(&self) -> SpinLockGuard<InnerLoopbackInterface> {
  290. return self.inner.lock();
  291. }
  292. }
  293. //TODO: 向sysfs注册lo设备
  294. impl KObject for LoopbackInterface {
  295. fn as_any_ref(&self) -> &dyn core::any::Any {
  296. self
  297. }
  298. fn set_inode(&self, inode: Option<Arc<KernFSInode>>) {
  299. self.inner().kobj_common.kern_inode = inode;
  300. }
  301. fn inode(&self) -> Option<Arc<KernFSInode>> {
  302. self.inner().kobj_common.kern_inode.clone()
  303. }
  304. fn parent(&self) -> Option<Weak<dyn KObject>> {
  305. self.inner().kobj_common.parent.clone()
  306. }
  307. fn set_parent(&self, parent: Option<Weak<dyn KObject>>) {
  308. self.inner().kobj_common.parent = parent;
  309. }
  310. fn kset(&self) -> Option<Arc<KSet>> {
  311. self.inner().kobj_common.kset.clone()
  312. }
  313. fn set_kset(&self, kset: Option<Arc<KSet>>) {
  314. self.inner().kobj_common.kset = kset;
  315. }
  316. fn kobj_type(&self) -> Option<&'static dyn KObjType> {
  317. self.inner().kobj_common.kobj_type
  318. }
  319. fn name(&self) -> String {
  320. "lo".to_string()
  321. }
  322. fn set_name(&self, _name: String) {
  323. // do nothing
  324. }
  325. fn kobj_state(&self) -> RwLockReadGuard<KObjectState> {
  326. self.locked_kobj_state.read()
  327. }
  328. fn kobj_state_mut(&self) -> RwLockWriteGuard<KObjectState> {
  329. self.locked_kobj_state.write()
  330. }
  331. fn set_kobj_state(&self, state: KObjectState) {
  332. *self.locked_kobj_state.write() = state;
  333. }
  334. fn set_kobj_type(&self, ktype: Option<&'static dyn KObjType>) {
  335. self.inner().kobj_common.kobj_type = ktype;
  336. }
  337. }
  338. impl Device for LoopbackInterface {
  339. fn dev_type(&self) -> DeviceType {
  340. DeviceType::Net
  341. }
  342. fn id_table(&self) -> IdTable {
  343. IdTable::new(DEVICE_NAME.to_string(), None)
  344. }
  345. fn bus(&self) -> Option<Weak<dyn Bus>> {
  346. self.inner().device_common.bus.clone()
  347. }
  348. fn set_bus(&self, bus: Option<Weak<dyn Bus>>) {
  349. self.inner().device_common.bus = bus;
  350. }
  351. fn class(&self) -> Option<Arc<dyn Class>> {
  352. let mut guard = self.inner();
  353. let r = guard.device_common.class.clone()?.upgrade();
  354. if r.is_none() {
  355. guard.device_common.class = None;
  356. }
  357. return r;
  358. }
  359. fn set_class(&self, class: Option<Weak<dyn Class>>) {
  360. self.inner().device_common.class = class;
  361. }
  362. fn driver(&self) -> Option<Arc<dyn Driver>> {
  363. let r = self.inner().device_common.driver.clone()?.upgrade();
  364. if r.is_none() {
  365. self.inner().device_common.driver = None;
  366. }
  367. return r;
  368. }
  369. fn set_driver(&self, driver: Option<Weak<dyn Driver>>) {
  370. self.inner().device_common.driver = driver;
  371. }
  372. fn is_dead(&self) -> bool {
  373. false
  374. }
  375. fn can_match(&self) -> bool {
  376. self.inner().device_common.can_match
  377. }
  378. fn set_can_match(&self, can_match: bool) {
  379. self.inner().device_common.can_match = can_match;
  380. }
  381. fn state_synced(&self) -> bool {
  382. true
  383. }
  384. fn dev_parent(&self) -> Option<Weak<dyn Device>> {
  385. self.inner().device_common.get_parent_weak_or_clear()
  386. }
  387. fn set_dev_parent(&self, parent: Option<Weak<dyn Device>>) {
  388. self.inner().device_common.parent = parent;
  389. }
  390. }
  391. impl Iface for LoopbackInterface {
  392. fn common(&self) -> &IfaceCommon {
  393. &self.common
  394. }
  395. fn iface_name(&self) -> String {
  396. "lo".to_string()
  397. }
  398. /// 由于lo网卡设备不是实际的物理设备,其mac地址需要手动设置为一个默认值,这里默认为00:00:00:00:00
  399. fn mac(&self) -> smoltcp::wire::EthernetAddress {
  400. let mac = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
  401. smoltcp::wire::EthernetAddress(mac)
  402. }
  403. fn poll(&self) {
  404. self.common.poll(self.driver.force_get_mut())
  405. }
  406. fn addr_assign_type(&self) -> u8 {
  407. return self.inner().netdevice_common.addr_assign_type;
  408. }
  409. fn net_device_type(&self) -> u16 {
  410. self.inner().netdevice_common.net_device_type = 24; // 环回设备
  411. return self.inner().netdevice_common.net_device_type;
  412. }
  413. fn net_state(&self) -> NetDeivceState {
  414. return self.inner().netdevice_common.state;
  415. }
  416. fn set_net_state(&self, state: NetDeivceState) {
  417. self.inner().netdevice_common.state |= state;
  418. }
  419. fn operstate(&self) -> Operstate {
  420. return self.inner().netdevice_common.operstate;
  421. }
  422. fn set_operstate(&self, state: Operstate) {
  423. self.inner().netdevice_common.operstate = state;
  424. }
  425. }
  426. pub fn loopback_probe() {
  427. loopback_driver_init();
  428. }
  429. /// # lo网卡设备初始化函数
  430. /// 创建驱动和iface,初始化一个lo网卡,添加到全局NET_DEVICES中
  431. pub fn loopback_driver_init() {
  432. let driver = LoopbackDriver::new();
  433. let iface = LoopbackInterface::new(driver);
  434. // 标识网络设备已经启动
  435. iface.set_net_state(NetDeivceState::__LINK_STATE_START);
  436. NET_DEVICES
  437. .write_irqsave()
  438. .insert(iface.nic_id(), iface.clone());
  439. register_netdevice(iface.clone()).expect("register lo device failed");
  440. }
  441. /// ## lo网卡设备的注册函数
  442. //TODO: 现在先不用初始化宏进行注册,使virtonet排在网卡列表头,待网络子系统重构后再使用初始化宏并修复该bug
  443. // #[unified_init(INITCALL_DEVICE)]
  444. pub fn loopback_init() -> Result<(), SystemError> {
  445. loopback_probe();
  446. log::debug!("Successfully init loopback device");
  447. return Ok(());
  448. }