1cde5492fSlogin use alloc::{boxed::Box, collections::BTreeMap, sync::Arc}; 2*5e948c56SGnoCiYeH use smoltcp::{socket::dhcpv4, wire}; 391e9d4abSLoGin use system_error::SystemError; 413776c11Slogin 5cde5492fSlogin use crate::{ 6cde5492fSlogin driver::net::NetDriver, 7cde5492fSlogin kdebug, kinfo, kwarn, 8cde5492fSlogin libs::rwlock::RwLockReadGuard, 940609970SGnoCiYeH net::{socket::SocketPollMethod, NET_DRIVERS}, 10cde5492fSlogin time::timer::{next_n_ms_timer_jiffies, Timer, TimerFunction}, 11cde5492fSlogin }; 12cde5492fSlogin 1340609970SGnoCiYeH use super::{ 14*5e948c56SGnoCiYeH event_poll::{EPollEventType, EventPoll}, 1540609970SGnoCiYeH socket::{TcpSocket, HANDLE_MAP, SOCKET_SET}, 1640609970SGnoCiYeH }; 17cde5492fSlogin 18cde5492fSlogin /// The network poll function, which will be called by timer. 19cde5492fSlogin /// 20cde5492fSlogin /// The main purpose of this function is to poll all network interfaces. 2136fd0130Shoumkh #[derive(Debug)] 2236fd0130Shoumkh struct NetWorkPollFunc; 2336fd0130Shoumkh 24cde5492fSlogin impl TimerFunction for NetWorkPollFunc { 2536fd0130Shoumkh fn run(&mut self) -> Result<(), SystemError> { 26cde5492fSlogin poll_ifaces_try_lock(10).ok(); 27cde5492fSlogin let next_time = next_n_ms_timer_jiffies(10); 2836fd0130Shoumkh let timer = Timer::new(Box::new(NetWorkPollFunc), next_time); 29cde5492fSlogin timer.activate(); 3036fd0130Shoumkh return Ok(()); 31cde5492fSlogin } 32cde5492fSlogin } 3313776c11Slogin 3413776c11Slogin pub fn net_init() -> Result<(), SystemError> { 3513776c11Slogin dhcp_query()?; 36cde5492fSlogin // Init poll timer function 370dd8ff43SYJwu2023 // let next_time = next_n_ms_timer_jiffies(5); 380dd8ff43SYJwu2023 // let timer = Timer::new(Box::new(NetWorkPollFunc), next_time); 390dd8ff43SYJwu2023 // timer.activate(); 4013776c11Slogin return Ok(()); 4113776c11Slogin } 420dd8ff43SYJwu2023 4313776c11Slogin fn dhcp_query() -> Result<(), SystemError> { 440d6cf65aSLoGin let binding = NET_DRIVERS.write_irqsave(); 4513776c11Slogin 46cde5492fSlogin let net_face = binding.get(&0).ok_or(SystemError::ENODEV)?.clone(); 4713776c11Slogin 4813776c11Slogin drop(binding); 4913776c11Slogin 5013776c11Slogin // Create sockets 5113776c11Slogin let mut dhcp_socket = dhcpv4::Socket::new(); 5213776c11Slogin 5313776c11Slogin // Set a ridiculously short max lease time to show DHCP renews work properly. 5413776c11Slogin // This will cause the DHCP client to start renewing after 5 seconds, and give up the 5513776c11Slogin // lease after 10 seconds if renew hasn't succeeded. 5613776c11Slogin // IMPORTANT: This should be removed in production. 5713776c11Slogin dhcp_socket.set_max_lease_duration(Some(smoltcp::time::Duration::from_secs(10))); 5813776c11Slogin 590d6cf65aSLoGin let dhcp_handle = SOCKET_SET.lock_irqsave().add(dhcp_socket); 6013776c11Slogin 6113776c11Slogin const DHCP_TRY_ROUND: u8 = 10; 6213776c11Slogin for i in 0..DHCP_TRY_ROUND { 6313776c11Slogin kdebug!("DHCP try round: {}", i); 640d6cf65aSLoGin net_face.poll(&mut SOCKET_SET.lock_irqsave()).ok(); 650d6cf65aSLoGin let mut binding = SOCKET_SET.lock_irqsave(); 660dd8ff43SYJwu2023 let event = binding.get_mut::<dhcpv4::Socket>(dhcp_handle).poll(); 6713776c11Slogin 6813776c11Slogin match event { 6913776c11Slogin None => {} 7013776c11Slogin 7113776c11Slogin Some(dhcpv4::Event::Configured(config)) => { 7213776c11Slogin // kdebug!("Find Config!! {config:?}"); 7313776c11Slogin // kdebug!("Find ip address: {}", config.address); 7413776c11Slogin // kdebug!("iface.ip_addrs={:?}", net_face.inner_iface.ip_addrs()); 7513776c11Slogin 7613776c11Slogin net_face 7713776c11Slogin .update_ip_addrs(&[wire::IpCidr::Ipv4(config.address)]) 7813776c11Slogin .ok(); 7913776c11Slogin 8013776c11Slogin if let Some(router) = config.router { 8113776c11Slogin net_face 8213776c11Slogin .inner_iface() 8313776c11Slogin .lock() 8413776c11Slogin .routes_mut() 8513776c11Slogin .add_default_ipv4_route(router) 8613776c11Slogin .unwrap(); 8713776c11Slogin let cidr = net_face.inner_iface().lock().ip_addrs().first().cloned(); 8813776c11Slogin if cidr.is_some() { 8913776c11Slogin let cidr = cidr.unwrap(); 9013776c11Slogin kinfo!("Successfully allocated ip by Dhcpv4! Ip:{}", cidr); 9113776c11Slogin return Ok(()); 9213776c11Slogin } 9313776c11Slogin } else { 9413776c11Slogin net_face 9513776c11Slogin .inner_iface() 9613776c11Slogin .lock() 9713776c11Slogin .routes_mut() 9813776c11Slogin .remove_default_ipv4_route(); 9913776c11Slogin } 10013776c11Slogin } 10113776c11Slogin 10213776c11Slogin Some(dhcpv4::Event::Deconfigured) => { 10313776c11Slogin kdebug!("Dhcp v4 deconfigured"); 10413776c11Slogin net_face 10513776c11Slogin .update_ip_addrs(&[smoltcp::wire::IpCidr::Ipv4(wire::Ipv4Cidr::new( 10613776c11Slogin wire::Ipv4Address::UNSPECIFIED, 10713776c11Slogin 0, 10813776c11Slogin ))]) 10913776c11Slogin .ok(); 11013776c11Slogin net_face 11113776c11Slogin .inner_iface() 11213776c11Slogin .lock() 11313776c11Slogin .routes_mut() 11413776c11Slogin .remove_default_ipv4_route(); 11513776c11Slogin } 11613776c11Slogin } 11713776c11Slogin } 11813776c11Slogin 11913776c11Slogin return Err(SystemError::ETIMEDOUT); 12013776c11Slogin } 121cde5492fSlogin 122cde5492fSlogin pub fn poll_ifaces() { 1230d6cf65aSLoGin let guard: RwLockReadGuard<BTreeMap<usize, Arc<dyn NetDriver>>> = NET_DRIVERS.read_irqsave(); 124cde5492fSlogin if guard.len() == 0 { 125cde5492fSlogin kwarn!("poll_ifaces: No net driver found!"); 126cde5492fSlogin return; 127cde5492fSlogin } 1280d6cf65aSLoGin let mut sockets = SOCKET_SET.lock_irqsave(); 129cde5492fSlogin for (_, iface) in guard.iter() { 130cde5492fSlogin iface.poll(&mut sockets).ok(); 131cde5492fSlogin } 13240609970SGnoCiYeH let _ = send_event(&sockets); 133cde5492fSlogin } 134cde5492fSlogin 135cde5492fSlogin /// 对ifaces进行轮询,最多对SOCKET_SET尝试times次加锁。 136cde5492fSlogin /// 137cde5492fSlogin /// @return 轮询成功,返回Ok(()) 138cde5492fSlogin /// @return 加锁超时,返回SystemError::EAGAIN_OR_EWOULDBLOCK 139cde5492fSlogin /// @return 没有网卡,返回SystemError::ENODEV 140cde5492fSlogin pub fn poll_ifaces_try_lock(times: u16) -> Result<(), SystemError> { 141cde5492fSlogin let mut i = 0; 142cde5492fSlogin while i < times { 1430d6cf65aSLoGin let guard: RwLockReadGuard<BTreeMap<usize, Arc<dyn NetDriver>>> = 1440d6cf65aSLoGin NET_DRIVERS.read_irqsave(); 145cde5492fSlogin if guard.len() == 0 { 146cde5492fSlogin kwarn!("poll_ifaces: No net driver found!"); 147cde5492fSlogin // 没有网卡,返回错误 148cde5492fSlogin return Err(SystemError::ENODEV); 149cde5492fSlogin } 1500d6cf65aSLoGin let sockets = SOCKET_SET.try_lock_irqsave(); 151cde5492fSlogin // 加锁失败,继续尝试 152cde5492fSlogin if sockets.is_err() { 153cde5492fSlogin i += 1; 154cde5492fSlogin continue; 155cde5492fSlogin } 156cde5492fSlogin 157cde5492fSlogin let mut sockets = sockets.unwrap(); 158cde5492fSlogin for (_, iface) in guard.iter() { 159cde5492fSlogin iface.poll(&mut sockets).ok(); 160cde5492fSlogin } 16140609970SGnoCiYeH let _ = send_event(&sockets); 162cde5492fSlogin return Ok(()); 163cde5492fSlogin } 164cde5492fSlogin 165cde5492fSlogin // 尝试次数用完,返回错误 166cde5492fSlogin return Err(SystemError::EAGAIN_OR_EWOULDBLOCK); 167cde5492fSlogin } 1680dd8ff43SYJwu2023 169afc95d5cSYJwu2023 /// 对ifaces进行轮询,最多对SOCKET_SET尝试一次加锁。 1700dd8ff43SYJwu2023 /// 1710dd8ff43SYJwu2023 /// @return 轮询成功,返回Ok(()) 1720dd8ff43SYJwu2023 /// @return 加锁超时,返回SystemError::EAGAIN_OR_EWOULDBLOCK 1730dd8ff43SYJwu2023 /// @return 没有网卡,返回SystemError::ENODEV 1740dd8ff43SYJwu2023 pub fn poll_ifaces_try_lock_onetime() -> Result<(), SystemError> { 1750d6cf65aSLoGin let guard: RwLockReadGuard<BTreeMap<usize, Arc<dyn NetDriver>>> = NET_DRIVERS.read_irqsave(); 1760dd8ff43SYJwu2023 if guard.len() == 0 { 1770dd8ff43SYJwu2023 kwarn!("poll_ifaces: No net driver found!"); 1780dd8ff43SYJwu2023 // 没有网卡,返回错误 1790dd8ff43SYJwu2023 return Err(SystemError::ENODEV); 1800dd8ff43SYJwu2023 } 1810d6cf65aSLoGin let mut sockets = SOCKET_SET.try_lock_irqsave()?; 1820dd8ff43SYJwu2023 for (_, iface) in guard.iter() { 1830dd8ff43SYJwu2023 iface.poll(&mut sockets).ok(); 1840dd8ff43SYJwu2023 } 18540609970SGnoCiYeH send_event(&sockets)?; 1860dd8ff43SYJwu2023 return Ok(()); 1870dd8ff43SYJwu2023 } 18840609970SGnoCiYeH 18940609970SGnoCiYeH /// ### 处理轮询后的事件 19040609970SGnoCiYeH fn send_event(sockets: &smoltcp::iface::SocketSet) -> Result<(), SystemError> { 19140609970SGnoCiYeH for (handle, socket_type) in sockets.iter() { 19240609970SGnoCiYeH let handle_guard = HANDLE_MAP.read_irqsave(); 19340609970SGnoCiYeH let item = handle_guard.get(&handle); 19440609970SGnoCiYeH if item.is_none() { 19540609970SGnoCiYeH continue; 19640609970SGnoCiYeH } 19740609970SGnoCiYeH 19840609970SGnoCiYeH let handle_item = item.unwrap(); 19940609970SGnoCiYeH 20040609970SGnoCiYeH // 获取socket上的事件 20140609970SGnoCiYeH let mut events = 20240609970SGnoCiYeH SocketPollMethod::poll(socket_type, handle_item.shutdown_type()).bits() as u64; 20340609970SGnoCiYeH 20440609970SGnoCiYeH // 分发到相应类型socket处理 20540609970SGnoCiYeH match socket_type { 20640609970SGnoCiYeH smoltcp::socket::Socket::Raw(_) | smoltcp::socket::Socket::Udp(_) => { 20740609970SGnoCiYeH handle_guard 20840609970SGnoCiYeH .get(&handle) 20940609970SGnoCiYeH .unwrap() 21040609970SGnoCiYeH .wait_queue 21140609970SGnoCiYeH .wakeup_any(events); 21240609970SGnoCiYeH } 21340609970SGnoCiYeH smoltcp::socket::Socket::Icmp(_) => unimplemented!("Icmp socket hasn't unimplemented"), 21440609970SGnoCiYeH smoltcp::socket::Socket::Tcp(inner_socket) => { 21540609970SGnoCiYeH if inner_socket.is_active() { 21640609970SGnoCiYeH events |= TcpSocket::CAN_ACCPET; 21740609970SGnoCiYeH } 21840609970SGnoCiYeH if inner_socket.state() == smoltcp::socket::tcp::State::Established { 21940609970SGnoCiYeH events |= TcpSocket::CAN_CONNECT; 22040609970SGnoCiYeH } 22140609970SGnoCiYeH handle_guard 22240609970SGnoCiYeH .get(&handle) 22340609970SGnoCiYeH .unwrap() 22440609970SGnoCiYeH .wait_queue 22540609970SGnoCiYeH .wakeup_any(events); 22640609970SGnoCiYeH } 22740609970SGnoCiYeH smoltcp::socket::Socket::Dhcpv4(_) => {} 22840609970SGnoCiYeH smoltcp::socket::Socket::Dns(_) => unimplemented!("Dns socket hasn't unimplemented"), 22940609970SGnoCiYeH } 23040609970SGnoCiYeH drop(handle_guard); 231*5e948c56SGnoCiYeH let mut handle_guard = HANDLE_MAP.write_irqsave(); 232*5e948c56SGnoCiYeH let handle_item = handle_guard.get_mut(&handle).unwrap(); 233*5e948c56SGnoCiYeH EventPoll::wakeup_epoll( 234*5e948c56SGnoCiYeH &mut handle_item.epitems, 235*5e948c56SGnoCiYeH EPollEventType::from_bits_truncate(events as u32), 236*5e948c56SGnoCiYeH )?; 23740609970SGnoCiYeH // crate::kdebug!( 23840609970SGnoCiYeH // "{} send_event {:?}", 23940609970SGnoCiYeH // handle, 24040609970SGnoCiYeH // EPollEventType::from_bits_truncate(events as u32) 24140609970SGnoCiYeH // ); 24240609970SGnoCiYeH } 24340609970SGnoCiYeH Ok(()) 24440609970SGnoCiYeH } 245