net_core.rs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. use alloc::{boxed::Box, collections::BTreeMap, sync::Arc};
  2. use smoltcp::{socket::dhcpv4, wire};
  3. use crate::{
  4. driver::net::NetDriver,
  5. kdebug, kinfo, kwarn,
  6. libs::rwlock::RwLockReadGuard,
  7. net::NET_DRIVERS,
  8. syscall::SystemError,
  9. time::timer::{next_n_ms_timer_jiffies, Timer, TimerFunction},
  10. };
  11. use super::socket::{SOCKET_SET, SOCKET_WAITQUEUE};
  12. /// The network poll function, which will be called by timer.
  13. ///
  14. /// The main purpose of this function is to poll all network interfaces.
  15. #[derive(Debug)]
  16. struct NetWorkPollFunc;
  17. impl TimerFunction for NetWorkPollFunc {
  18. fn run(&mut self) -> Result<(), SystemError> {
  19. poll_ifaces_try_lock(10).ok();
  20. let next_time = next_n_ms_timer_jiffies(10);
  21. let timer = Timer::new(Box::new(NetWorkPollFunc), next_time);
  22. timer.activate();
  23. return Ok(());
  24. }
  25. }
  26. pub fn net_init() -> Result<(), SystemError> {
  27. dhcp_query()?;
  28. // Init poll timer function
  29. // let next_time = next_n_ms_timer_jiffies(5);
  30. // let timer = Timer::new(Box::new(NetWorkPollFunc), next_time);
  31. // timer.activate();
  32. return Ok(());
  33. }
  34. fn dhcp_query() -> Result<(), SystemError> {
  35. let binding = NET_DRIVERS.write();
  36. let net_face = binding.get(&0).ok_or(SystemError::ENODEV)?.clone();
  37. drop(binding);
  38. // Create sockets
  39. let mut dhcp_socket = dhcpv4::Socket::new();
  40. // Set a ridiculously short max lease time to show DHCP renews work properly.
  41. // This will cause the DHCP client to start renewing after 5 seconds, and give up the
  42. // lease after 10 seconds if renew hasn't succeeded.
  43. // IMPORTANT: This should be removed in production.
  44. dhcp_socket.set_max_lease_duration(Some(smoltcp::time::Duration::from_secs(10)));
  45. let dhcp_handle = SOCKET_SET.lock().add(dhcp_socket);
  46. const DHCP_TRY_ROUND: u8 = 10;
  47. for i in 0..DHCP_TRY_ROUND {
  48. kdebug!("DHCP try round: {}", i);
  49. net_face.poll(&mut SOCKET_SET.lock()).ok();
  50. let mut binding = SOCKET_SET.lock();
  51. let event = binding.get_mut::<dhcpv4::Socket>(dhcp_handle).poll();
  52. match event {
  53. None => {}
  54. Some(dhcpv4::Event::Configured(config)) => {
  55. // kdebug!("Find Config!! {config:?}");
  56. // kdebug!("Find ip address: {}", config.address);
  57. // kdebug!("iface.ip_addrs={:?}", net_face.inner_iface.ip_addrs());
  58. net_face
  59. .update_ip_addrs(&[wire::IpCidr::Ipv4(config.address)])
  60. .ok();
  61. if let Some(router) = config.router {
  62. net_face
  63. .inner_iface()
  64. .lock()
  65. .routes_mut()
  66. .add_default_ipv4_route(router)
  67. .unwrap();
  68. let cidr = net_face.inner_iface().lock().ip_addrs().first().cloned();
  69. if cidr.is_some() {
  70. let cidr = cidr.unwrap();
  71. kinfo!("Successfully allocated ip by Dhcpv4! Ip:{}", cidr);
  72. return Ok(());
  73. }
  74. } else {
  75. net_face
  76. .inner_iface()
  77. .lock()
  78. .routes_mut()
  79. .remove_default_ipv4_route();
  80. }
  81. }
  82. Some(dhcpv4::Event::Deconfigured) => {
  83. kdebug!("Dhcp v4 deconfigured");
  84. net_face
  85. .update_ip_addrs(&[smoltcp::wire::IpCidr::Ipv4(wire::Ipv4Cidr::new(
  86. wire::Ipv4Address::UNSPECIFIED,
  87. 0,
  88. ))])
  89. .ok();
  90. net_face
  91. .inner_iface()
  92. .lock()
  93. .routes_mut()
  94. .remove_default_ipv4_route();
  95. }
  96. }
  97. }
  98. return Err(SystemError::ETIMEDOUT);
  99. }
  100. pub fn poll_ifaces() {
  101. let guard: RwLockReadGuard<BTreeMap<usize, Arc<dyn NetDriver>>> = NET_DRIVERS.read();
  102. if guard.len() == 0 {
  103. kwarn!("poll_ifaces: No net driver found!");
  104. return;
  105. }
  106. let mut sockets = SOCKET_SET.lock();
  107. for (_, iface) in guard.iter() {
  108. iface.poll(&mut sockets).ok();
  109. }
  110. SOCKET_WAITQUEUE.wakeup_all(None);
  111. }
  112. /// 对ifaces进行轮询,最多对SOCKET_SET尝试times次加锁。
  113. ///
  114. /// @return 轮询成功,返回Ok(())
  115. /// @return 加锁超时,返回SystemError::EAGAIN_OR_EWOULDBLOCK
  116. /// @return 没有网卡,返回SystemError::ENODEV
  117. pub fn poll_ifaces_try_lock(times: u16) -> Result<(), SystemError> {
  118. let mut i = 0;
  119. while i < times {
  120. let guard: RwLockReadGuard<BTreeMap<usize, Arc<dyn NetDriver>>> = NET_DRIVERS.read();
  121. if guard.len() == 0 {
  122. kwarn!("poll_ifaces: No net driver found!");
  123. // 没有网卡,返回错误
  124. return Err(SystemError::ENODEV);
  125. }
  126. let sockets = SOCKET_SET.try_lock();
  127. // 加锁失败,继续尝试
  128. if sockets.is_err() {
  129. i += 1;
  130. continue;
  131. }
  132. let mut sockets = sockets.unwrap();
  133. for (_, iface) in guard.iter() {
  134. iface.poll(&mut sockets).ok();
  135. }
  136. SOCKET_WAITQUEUE.wakeup_all(None);
  137. return Ok(());
  138. }
  139. // 尝试次数用完,返回错误
  140. return Err(SystemError::EAGAIN_OR_EWOULDBLOCK);
  141. }
  142. /// 对ifaces进行轮询,最多对SOCKET_SET尝试一次加锁。
  143. ///
  144. /// @return 轮询成功,返回Ok(())
  145. /// @return 加锁超时,返回SystemError::EAGAIN_OR_EWOULDBLOCK
  146. /// @return 没有网卡,返回SystemError::ENODEV
  147. pub fn poll_ifaces_try_lock_onetime() -> Result<(), SystemError> {
  148. let guard: RwLockReadGuard<BTreeMap<usize, Arc<dyn NetDriver>>> = NET_DRIVERS.read();
  149. if guard.len() == 0 {
  150. kwarn!("poll_ifaces: No net driver found!");
  151. // 没有网卡,返回错误
  152. return Err(SystemError::ENODEV);
  153. }
  154. let mut sockets = SOCKET_SET.try_lock()?;
  155. for (_, iface) in guard.iter() {
  156. iface.poll(&mut sockets).ok();
  157. }
  158. SOCKET_WAITQUEUE.wakeup_all(None);
  159. return Ok(());
  160. }