xref: /DragonOS/kernel/src/net/net_core.rs (revision 0d6cf65aa124ee55bfee44cbb5196917ea6522fa)
1cde5492fSlogin use alloc::{boxed::Box, collections::BTreeMap, sync::Arc};
240609970SGnoCiYeH use smoltcp::{iface::SocketHandle, 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::{
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> {
44*0d6cf65aSLoGin     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 
59*0d6cf65aSLoGin     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);
64*0d6cf65aSLoGin         net_face.poll(&mut SOCKET_SET.lock_irqsave()).ok();
65*0d6cf65aSLoGin         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() {
123*0d6cf65aSLoGin     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     }
128*0d6cf65aSLoGin     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 {
143*0d6cf65aSLoGin         let guard: RwLockReadGuard<BTreeMap<usize, Arc<dyn NetDriver>>> =
144*0d6cf65aSLoGin             NET_DRIVERS.read_irqsave();
145cde5492fSlogin         if guard.len() == 0 {
146cde5492fSlogin             kwarn!("poll_ifaces: No net driver found!");
147cde5492fSlogin             // 没有网卡,返回错误
148cde5492fSlogin             return Err(SystemError::ENODEV);
149cde5492fSlogin         }
150*0d6cf65aSLoGin         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> {
175*0d6cf65aSLoGin     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     }
181*0d6cf65aSLoGin     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);
23140609970SGnoCiYeH         wakeup_epoll(handle, events as u32)?;
23240609970SGnoCiYeH         // crate::kdebug!(
23340609970SGnoCiYeH         //     "{} send_event {:?}",
23440609970SGnoCiYeH         //     handle,
23540609970SGnoCiYeH         //     EPollEventType::from_bits_truncate(events as u32)
23640609970SGnoCiYeH         // );
23740609970SGnoCiYeH     }
23840609970SGnoCiYeH     Ok(())
23940609970SGnoCiYeH }
24040609970SGnoCiYeH 
24140609970SGnoCiYeH /// ### 处理epoll
24240609970SGnoCiYeH fn wakeup_epoll(handle: SocketHandle, events: u32) -> Result<(), SystemError> {
24340609970SGnoCiYeH     let mut handle_guard = HANDLE_MAP.write_irqsave();
24440609970SGnoCiYeH     let handle_item = handle_guard.get_mut(&handle).unwrap();
245*0d6cf65aSLoGin     let mut epitems_guard = handle_item.epitems.try_lock_irqsave()?;
24640609970SGnoCiYeH 
24740609970SGnoCiYeH     // 从events拿到epoll相关事件
24840609970SGnoCiYeH     let pollflags = EPollEventType::from_bits_truncate(events);
24940609970SGnoCiYeH 
25040609970SGnoCiYeH     // 一次只取一个,因为一次也只有一个进程能拿到对应文件的��
25140609970SGnoCiYeH     if let Some(epitem) = epitems_guard.pop_front() {
25240609970SGnoCiYeH         let epoll = epitem.epoll().upgrade().unwrap();
253*0d6cf65aSLoGin         let mut epoll_guard = epoll.try_lock_irqsave()?;
25440609970SGnoCiYeH         let binding = epitem.clone();
255*0d6cf65aSLoGin         let event_guard = binding.event().read_irqsave();
25640609970SGnoCiYeH         let ep_events = EPollEventType::from_bits_truncate(event_guard.events());
25740609970SGnoCiYeH 
25840609970SGnoCiYeH         // 检查事件合理性以及是否有感兴趣的事件
25940609970SGnoCiYeH         if !(ep_events
26040609970SGnoCiYeH             .difference(EPollEventType::EP_PRIVATE_BITS)
26140609970SGnoCiYeH             .is_empty()
26240609970SGnoCiYeH             || pollflags.difference(ep_events).is_empty())
26340609970SGnoCiYeH         {
26440609970SGnoCiYeH             // TODO: 未处理pm相关
26540609970SGnoCiYeH 
26640609970SGnoCiYeH             // 首先将就绪的epitem加入等待队列
26740609970SGnoCiYeH             epoll_guard.ep_add_ready(epitem.clone());
26840609970SGnoCiYeH 
26940609970SGnoCiYeH             if epoll_guard.ep_has_waiter() {
27040609970SGnoCiYeH                 if ep_events.contains(EPollEventType::EPOLLEXCLUSIVE)
27140609970SGnoCiYeH                     && !pollflags.contains(EPollEventType::POLLFREE)
27240609970SGnoCiYeH                 {
27340609970SGnoCiYeH                     // 避免惊群
27440609970SGnoCiYeH                     epoll_guard.ep_wake_one();
27540609970SGnoCiYeH                 } else {
27640609970SGnoCiYeH                     epoll_guard.ep_wake_all();
27740609970SGnoCiYeH                 }
27840609970SGnoCiYeH             }
27940609970SGnoCiYeH         }
28040609970SGnoCiYeH 
28140609970SGnoCiYeH         epitems_guard.push_back(epitem);
28240609970SGnoCiYeH     }
28340609970SGnoCiYeH     Ok(())
28440609970SGnoCiYeH }
285