xref: /DragonOS/kernel/src/net/net_core.rs (revision 91e9d4ab55ef960f57a1b6287bc523ca4341f67a)
1cde5492fSlogin use alloc::{boxed::Box, collections::BTreeMap, sync::Arc};
240609970SGnoCiYeH use smoltcp::{iface::SocketHandle, socket::dhcpv4, wire};
3*91e9d4abSLoGin 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::{
1440609970SGnoCiYeH     event_poll::EPollEventType,
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> {
4413776c11Slogin     let binding = NET_DRIVERS.write();
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 
590dd8ff43SYJwu2023     let dhcp_handle = SOCKET_SET.lock().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);
640dd8ff43SYJwu2023         net_face.poll(&mut SOCKET_SET.lock()).ok();
650dd8ff43SYJwu2023         let mut binding = SOCKET_SET.lock();
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() {
123cde5492fSlogin     let guard: RwLockReadGuard<BTreeMap<usize, Arc<dyn NetDriver>>> = NET_DRIVERS.read();
124cde5492fSlogin     if guard.len() == 0 {
125cde5492fSlogin         kwarn!("poll_ifaces: No net driver found!");
126cde5492fSlogin         return;
127cde5492fSlogin     }
128cde5492fSlogin     let mut sockets = SOCKET_SET.lock();
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 {
143cde5492fSlogin         let guard: RwLockReadGuard<BTreeMap<usize, Arc<dyn NetDriver>>> = NET_DRIVERS.read();
144cde5492fSlogin         if guard.len() == 0 {
145cde5492fSlogin             kwarn!("poll_ifaces: No net driver found!");
146cde5492fSlogin             // 没有网卡,返回错误
147cde5492fSlogin             return Err(SystemError::ENODEV);
148cde5492fSlogin         }
149cde5492fSlogin         let sockets = SOCKET_SET.try_lock();
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         }
16040609970SGnoCiYeH         let _ = send_event(&sockets);
161cde5492fSlogin         return Ok(());
162cde5492fSlogin     }
163cde5492fSlogin 
164cde5492fSlogin     // 尝试次数用完,返回错误
165cde5492fSlogin     return Err(SystemError::EAGAIN_OR_EWOULDBLOCK);
166cde5492fSlogin }
1670dd8ff43SYJwu2023 
168afc95d5cSYJwu2023 /// 对ifaces进行轮询,最多对SOCKET_SET尝试一次加锁。
1690dd8ff43SYJwu2023 ///
1700dd8ff43SYJwu2023 /// @return 轮询成功,返回Ok(())
1710dd8ff43SYJwu2023 /// @return 加锁超时,返回SystemError::EAGAIN_OR_EWOULDBLOCK
1720dd8ff43SYJwu2023 /// @return 没有网卡,返回SystemError::ENODEV
1730dd8ff43SYJwu2023 pub fn poll_ifaces_try_lock_onetime() -> Result<(), SystemError> {
1740dd8ff43SYJwu2023     let guard: RwLockReadGuard<BTreeMap<usize, Arc<dyn NetDriver>>> = NET_DRIVERS.read();
1750dd8ff43SYJwu2023     if guard.len() == 0 {
1760dd8ff43SYJwu2023         kwarn!("poll_ifaces: No net driver found!");
1770dd8ff43SYJwu2023         // 没有网卡,返回错误
1780dd8ff43SYJwu2023         return Err(SystemError::ENODEV);
1790dd8ff43SYJwu2023     }
1800dd8ff43SYJwu2023     let mut sockets = SOCKET_SET.try_lock()?;
1810dd8ff43SYJwu2023     for (_, iface) in guard.iter() {
1820dd8ff43SYJwu2023         iface.poll(&mut sockets).ok();
1830dd8ff43SYJwu2023     }
18440609970SGnoCiYeH     send_event(&sockets)?;
1850dd8ff43SYJwu2023     return Ok(());
1860dd8ff43SYJwu2023 }
18740609970SGnoCiYeH 
18840609970SGnoCiYeH /// ### 处理轮询后的事件
18940609970SGnoCiYeH fn send_event(sockets: &smoltcp::iface::SocketSet) -> Result<(), SystemError> {
19040609970SGnoCiYeH     for (handle, socket_type) in sockets.iter() {
19140609970SGnoCiYeH         let handle_guard = HANDLE_MAP.read_irqsave();
19240609970SGnoCiYeH         let item = handle_guard.get(&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
20740609970SGnoCiYeH                     .get(&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
22140609970SGnoCiYeH                     .get(&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);
23040609970SGnoCiYeH         wakeup_epoll(handle, events as u32)?;
23140609970SGnoCiYeH         // crate::kdebug!(
23240609970SGnoCiYeH         //     "{} send_event {:?}",
23340609970SGnoCiYeH         //     handle,
23440609970SGnoCiYeH         //     EPollEventType::from_bits_truncate(events as u32)
23540609970SGnoCiYeH         // );
23640609970SGnoCiYeH     }
23740609970SGnoCiYeH     Ok(())
23840609970SGnoCiYeH }
23940609970SGnoCiYeH 
24040609970SGnoCiYeH /// ### 处理epoll
24140609970SGnoCiYeH fn wakeup_epoll(handle: SocketHandle, events: u32) -> Result<(), SystemError> {
24240609970SGnoCiYeH     let mut handle_guard = HANDLE_MAP.write_irqsave();
24340609970SGnoCiYeH     let handle_item = handle_guard.get_mut(&handle).unwrap();
24440609970SGnoCiYeH     let mut epitems_guard = handle_item.epitems.try_lock()?;
24540609970SGnoCiYeH 
24640609970SGnoCiYeH     // 从events拿到epoll相关事件
24740609970SGnoCiYeH     let pollflags = EPollEventType::from_bits_truncate(events);
24840609970SGnoCiYeH 
24940609970SGnoCiYeH     // 一次只取一个,因为一次也只有一个进程能拿到对应文件的��
25040609970SGnoCiYeH     if let Some(epitem) = epitems_guard.pop_front() {
25140609970SGnoCiYeH         let epoll = epitem.epoll().upgrade().unwrap();
25240609970SGnoCiYeH         let mut epoll_guard = epoll.try_lock()?;
25340609970SGnoCiYeH         let binding = epitem.clone();
25440609970SGnoCiYeH         let event_guard = binding.event().read();
25540609970SGnoCiYeH         let ep_events = EPollEventType::from_bits_truncate(event_guard.events());
25640609970SGnoCiYeH 
25740609970SGnoCiYeH         // 检查事件合理性以及是否有感兴趣的事件
25840609970SGnoCiYeH         if !(ep_events
25940609970SGnoCiYeH             .difference(EPollEventType::EP_PRIVATE_BITS)
26040609970SGnoCiYeH             .is_empty()
26140609970SGnoCiYeH             || pollflags.difference(ep_events).is_empty())
26240609970SGnoCiYeH         {
26340609970SGnoCiYeH             // TODO: 未处理pm相关
26440609970SGnoCiYeH 
26540609970SGnoCiYeH             // 首先将就绪的epitem加入等待队列
26640609970SGnoCiYeH             epoll_guard.ep_add_ready(epitem.clone());
26740609970SGnoCiYeH 
26840609970SGnoCiYeH             if epoll_guard.ep_has_waiter() {
26940609970SGnoCiYeH                 if ep_events.contains(EPollEventType::EPOLLEXCLUSIVE)
27040609970SGnoCiYeH                     && !pollflags.contains(EPollEventType::POLLFREE)
27140609970SGnoCiYeH                 {
27240609970SGnoCiYeH                     // 避免惊群
27340609970SGnoCiYeH                     epoll_guard.ep_wake_one();
27440609970SGnoCiYeH                 } else {
27540609970SGnoCiYeH                     epoll_guard.ep_wake_all();
27640609970SGnoCiYeH                 }
27740609970SGnoCiYeH             }
27840609970SGnoCiYeH         }
27940609970SGnoCiYeH 
28040609970SGnoCiYeH         epitems_guard.push_back(epitem);
28140609970SGnoCiYeH     }
28240609970SGnoCiYeH     Ok(())
28340609970SGnoCiYeH }
284