xref: /DragonOS/kernel/src/net/net_core.rs (revision e32effb1507773d32c216d9e77b963786e275c06)
1cde5492fSlogin use alloc::{boxed::Box, collections::BTreeMap, sync::Arc};
25e948c56SGnoCiYeH use smoltcp::{socket::dhcpv4, wire};
391e9d4abSLoGin use system_error::SystemError;
413776c11Slogin 
5cde5492fSlogin use crate::{
6*e32effb1SLoGin     driver::net::NetDevice,
7cde5492fSlogin     kdebug, kinfo, kwarn,
8cde5492fSlogin     libs::rwlock::RwLockReadGuard,
9*e32effb1SLoGin     net::{socket::SocketPollMethod, NET_DEVICES},
10cde5492fSlogin     time::timer::{next_n_ms_timer_jiffies, Timer, TimerFunction},
11cde5492fSlogin };
12cde5492fSlogin 
1340609970SGnoCiYeH use super::{
145e948c56SGnoCiYeH     event_poll::{EPollEventType, EventPoll},
15d623e902SGnoCiYeH     socket::{handle::GlobalSocketHandle, inet::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> {
44*e32effb1SLoGin     let binding = NET_DEVICES.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();
88b5b571e0SLoGin                     if let Some(cidr) = cidr {
8913776c11Slogin                         kinfo!("Successfully allocated ip by Dhcpv4! Ip:{}", cidr);
9013776c11Slogin                         return Ok(());
9113776c11Slogin                     }
9213776c11Slogin                 } else {
9313776c11Slogin                     net_face
9413776c11Slogin                         .inner_iface()
9513776c11Slogin                         .lock()
9613776c11Slogin                         .routes_mut()
9713776c11Slogin                         .remove_default_ipv4_route();
9813776c11Slogin                 }
9913776c11Slogin             }
10013776c11Slogin 
10113776c11Slogin             Some(dhcpv4::Event::Deconfigured) => {
10213776c11Slogin                 kdebug!("Dhcp v4 deconfigured");
10313776c11Slogin                 net_face
10413776c11Slogin                     .update_ip_addrs(&[smoltcp::wire::IpCidr::Ipv4(wire::Ipv4Cidr::new(
10513776c11Slogin                         wire::Ipv4Address::UNSPECIFIED,
10613776c11Slogin                         0,
10713776c11Slogin                     ))])
10813776c11Slogin                     .ok();
10913776c11Slogin                 net_face
11013776c11Slogin                     .inner_iface()
11113776c11Slogin                     .lock()
11213776c11Slogin                     .routes_mut()
11313776c11Slogin                     .remove_default_ipv4_route();
11413776c11Slogin             }
11513776c11Slogin         }
11613776c11Slogin     }
11713776c11Slogin 
11813776c11Slogin     return Err(SystemError::ETIMEDOUT);
11913776c11Slogin }
120cde5492fSlogin 
121cde5492fSlogin pub fn poll_ifaces() {
122*e32effb1SLoGin     let guard: RwLockReadGuard<BTreeMap<usize, Arc<dyn NetDevice>>> = NET_DEVICES.read_irqsave();
123cde5492fSlogin     if guard.len() == 0 {
124cde5492fSlogin         kwarn!("poll_ifaces: No net driver found!");
125cde5492fSlogin         return;
126cde5492fSlogin     }
1270d6cf65aSLoGin     let mut sockets = SOCKET_SET.lock_irqsave();
128cde5492fSlogin     for (_, iface) in guard.iter() {
129cde5492fSlogin         iface.poll(&mut sockets).ok();
130cde5492fSlogin     }
13140609970SGnoCiYeH     let _ = send_event(&sockets);
132cde5492fSlogin }
133cde5492fSlogin 
134cde5492fSlogin /// 对ifaces进行轮询,最多对SOCKET_SET尝试times次加锁。
135cde5492fSlogin ///
136cde5492fSlogin /// @return 轮询成功,返回Ok(())
137cde5492fSlogin /// @return 加锁超时,返回SystemError::EAGAIN_OR_EWOULDBLOCK
138cde5492fSlogin /// @return 没有网卡,返回SystemError::ENODEV
139cde5492fSlogin pub fn poll_ifaces_try_lock(times: u16) -> Result<(), SystemError> {
140cde5492fSlogin     let mut i = 0;
141cde5492fSlogin     while i < times {
142*e32effb1SLoGin         let guard: RwLockReadGuard<BTreeMap<usize, Arc<dyn NetDevice>>> =
143*e32effb1SLoGin             NET_DEVICES.read_irqsave();
144cde5492fSlogin         if guard.len() == 0 {
145cde5492fSlogin             kwarn!("poll_ifaces: No net driver found!");
146cde5492fSlogin             // 没有网卡,返回错误
147cde5492fSlogin             return Err(SystemError::ENODEV);
148cde5492fSlogin         }
1490d6cf65aSLoGin         let sockets = SOCKET_SET.try_lock_irqsave();
150cde5492fSlogin         // 加锁失败,继续尝试
151cde5492fSlogin         if sockets.is_err() {
152cde5492fSlogin             i += 1;
153cde5492fSlogin             continue;
154cde5492fSlogin         }
155cde5492fSlogin 
156cde5492fSlogin         let mut sockets = sockets.unwrap();
157cde5492fSlogin         for (_, iface) in guard.iter() {
158cde5492fSlogin             iface.poll(&mut sockets).ok();
159cde5492fSlogin         }
1604ad52e57S裕依2439         send_event(&sockets)?;
161cde5492fSlogin         return Ok(());
162cde5492fSlogin     }
163cde5492fSlogin     // 尝试次数用完,返回错误
164cde5492fSlogin     return Err(SystemError::EAGAIN_OR_EWOULDBLOCK);
165cde5492fSlogin }
1660dd8ff43SYJwu2023 
167afc95d5cSYJwu2023 /// 对ifaces进行轮询,最多对SOCKET_SET尝试一次加锁。
1680dd8ff43SYJwu2023 ///
1690dd8ff43SYJwu2023 /// @return 轮询成功,返回Ok(())
1700dd8ff43SYJwu2023 /// @return 加锁超时,返回SystemError::EAGAIN_OR_EWOULDBLOCK
1710dd8ff43SYJwu2023 /// @return 没有网卡,返回SystemError::ENODEV
1720dd8ff43SYJwu2023 pub fn poll_ifaces_try_lock_onetime() -> Result<(), SystemError> {
173*e32effb1SLoGin     let guard: RwLockReadGuard<BTreeMap<usize, Arc<dyn NetDevice>>> = NET_DEVICES.read_irqsave();
1740dd8ff43SYJwu2023     if guard.len() == 0 {
1750dd8ff43SYJwu2023         kwarn!("poll_ifaces: No net driver found!");
1760dd8ff43SYJwu2023         // 没有网卡,返回错误
1770dd8ff43SYJwu2023         return Err(SystemError::ENODEV);
1780dd8ff43SYJwu2023     }
1790d6cf65aSLoGin     let mut sockets = SOCKET_SET.try_lock_irqsave()?;
1800dd8ff43SYJwu2023     for (_, iface) in guard.iter() {
1810dd8ff43SYJwu2023         iface.poll(&mut sockets).ok();
1820dd8ff43SYJwu2023     }
18340609970SGnoCiYeH     send_event(&sockets)?;
1840dd8ff43SYJwu2023     return Ok(());
1850dd8ff43SYJwu2023 }
18640609970SGnoCiYeH 
18740609970SGnoCiYeH /// ### 处理轮询后的事件
18840609970SGnoCiYeH fn send_event(sockets: &smoltcp::iface::SocketSet) -> Result<(), SystemError> {
18940609970SGnoCiYeH     for (handle, socket_type) in sockets.iter() {
19040609970SGnoCiYeH         let handle_guard = HANDLE_MAP.read_irqsave();
191d623e902SGnoCiYeH         let global_handle = GlobalSocketHandle::new_smoltcp_handle(handle);
192d623e902SGnoCiYeH         let item = handle_guard.get(&global_handle);
19340609970SGnoCiYeH         if item.is_none() {
19440609970SGnoCiYeH             continue;
19540609970SGnoCiYeH         }
19640609970SGnoCiYeH 
19740609970SGnoCiYeH         let handle_item = item.unwrap();
19840609970SGnoCiYeH 
19940609970SGnoCiYeH         // 获取socket上的事件
20040609970SGnoCiYeH         let mut events =
20140609970SGnoCiYeH             SocketPollMethod::poll(socket_type, handle_item.shutdown_type()).bits() as u64;
20240609970SGnoCiYeH 
20340609970SGnoCiYeH         // 分发到相应类型socket处理
20440609970SGnoCiYeH         match socket_type {
20540609970SGnoCiYeH             smoltcp::socket::Socket::Raw(_) | smoltcp::socket::Socket::Udp(_) => {
20640609970SGnoCiYeH                 handle_guard
207d623e902SGnoCiYeH                     .get(&global_handle)
20840609970SGnoCiYeH                     .unwrap()
20940609970SGnoCiYeH                     .wait_queue
21040609970SGnoCiYeH                     .wakeup_any(events);
21140609970SGnoCiYeH             }
21240609970SGnoCiYeH             smoltcp::socket::Socket::Icmp(_) => unimplemented!("Icmp socket hasn't unimplemented"),
21340609970SGnoCiYeH             smoltcp::socket::Socket::Tcp(inner_socket) => {
21440609970SGnoCiYeH                 if inner_socket.is_active() {
21540609970SGnoCiYeH                     events |= TcpSocket::CAN_ACCPET;
21640609970SGnoCiYeH                 }
21740609970SGnoCiYeH                 if inner_socket.state() == smoltcp::socket::tcp::State::Established {
21840609970SGnoCiYeH                     events |= TcpSocket::CAN_CONNECT;
21940609970SGnoCiYeH                 }
22040609970SGnoCiYeH                 handle_guard
221d623e902SGnoCiYeH                     .get(&global_handle)
22240609970SGnoCiYeH                     .unwrap()
22340609970SGnoCiYeH                     .wait_queue
22440609970SGnoCiYeH                     .wakeup_any(events);
22540609970SGnoCiYeH             }
22640609970SGnoCiYeH             smoltcp::socket::Socket::Dhcpv4(_) => {}
22740609970SGnoCiYeH             smoltcp::socket::Socket::Dns(_) => unimplemented!("Dns socket hasn't unimplemented"),
22840609970SGnoCiYeH         }
22940609970SGnoCiYeH         drop(handle_guard);
2305e948c56SGnoCiYeH         let mut handle_guard = HANDLE_MAP.write_irqsave();
231d623e902SGnoCiYeH         let handle_item = handle_guard.get_mut(&global_handle).unwrap();
2325e948c56SGnoCiYeH         EventPoll::wakeup_epoll(
233b5b571e0SLoGin             &handle_item.epitems,
2345e948c56SGnoCiYeH             EPollEventType::from_bits_truncate(events as u32),
2355e948c56SGnoCiYeH         )?;
23640609970SGnoCiYeH         // crate::kdebug!(
23740609970SGnoCiYeH         //     "{} send_event {:?}",
23840609970SGnoCiYeH         //     handle,
23940609970SGnoCiYeH         //     EPollEventType::from_bits_truncate(events as u32)
24040609970SGnoCiYeH         // );
24140609970SGnoCiYeH     }
24240609970SGnoCiYeH     Ok(())
24340609970SGnoCiYeH }
244