xref: /DragonOS/kernel/src/net/net_core.rs (revision 406099704eb939ae23b18f0cfb3ed36c534c1c84)
1cde5492fSlogin use alloc::{boxed::Box, collections::BTreeMap, sync::Arc};
2*40609970SGnoCiYeH use smoltcp::{iface::SocketHandle, socket::dhcpv4, wire};
313776c11Slogin 
4cde5492fSlogin use crate::{
5cde5492fSlogin     driver::net::NetDriver,
6cde5492fSlogin     kdebug, kinfo, kwarn,
7cde5492fSlogin     libs::rwlock::RwLockReadGuard,
8*40609970SGnoCiYeH     net::{socket::SocketPollMethod, NET_DRIVERS},
9cde5492fSlogin     syscall::SystemError,
10cde5492fSlogin     time::timer::{next_n_ms_timer_jiffies, Timer, TimerFunction},
11cde5492fSlogin };
12cde5492fSlogin 
13*40609970SGnoCiYeH use super::{
14*40609970SGnoCiYeH     event_poll::EPollEventType,
15*40609970SGnoCiYeH     socket::{TcpSocket, HANDLE_MAP, SOCKET_SET},
16*40609970SGnoCiYeH };
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     }
132*40609970SGnoCiYeH     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         }
160*40609970SGnoCiYeH         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     }
184*40609970SGnoCiYeH     send_event(&sockets)?;
1850dd8ff43SYJwu2023     return Ok(());
1860dd8ff43SYJwu2023 }
187*40609970SGnoCiYeH 
188*40609970SGnoCiYeH /// ### 处理轮询后的事件
189*40609970SGnoCiYeH fn send_event(sockets: &smoltcp::iface::SocketSet) -> Result<(), SystemError> {
190*40609970SGnoCiYeH     for (handle, socket_type) in sockets.iter() {
191*40609970SGnoCiYeH         let handle_guard = HANDLE_MAP.read_irqsave();
192*40609970SGnoCiYeH         let item = handle_guard.get(&handle);
193*40609970SGnoCiYeH         if item.is_none() {
194*40609970SGnoCiYeH             continue;
195*40609970SGnoCiYeH         }
196*40609970SGnoCiYeH 
197*40609970SGnoCiYeH         let handle_item = item.unwrap();
198*40609970SGnoCiYeH 
199*40609970SGnoCiYeH         // 获取socket上的事件
200*40609970SGnoCiYeH         let mut events =
201*40609970SGnoCiYeH             SocketPollMethod::poll(socket_type, handle_item.shutdown_type()).bits() as u64;
202*40609970SGnoCiYeH 
203*40609970SGnoCiYeH         // 分发到相应类型socket处理
204*40609970SGnoCiYeH         match socket_type {
205*40609970SGnoCiYeH             smoltcp::socket::Socket::Raw(_) | smoltcp::socket::Socket::Udp(_) => {
206*40609970SGnoCiYeH                 handle_guard
207*40609970SGnoCiYeH                     .get(&handle)
208*40609970SGnoCiYeH                     .unwrap()
209*40609970SGnoCiYeH                     .wait_queue
210*40609970SGnoCiYeH                     .wakeup_any(events);
211*40609970SGnoCiYeH             }
212*40609970SGnoCiYeH             smoltcp::socket::Socket::Icmp(_) => unimplemented!("Icmp socket hasn't unimplemented"),
213*40609970SGnoCiYeH             smoltcp::socket::Socket::Tcp(inner_socket) => {
214*40609970SGnoCiYeH                 if inner_socket.is_active() {
215*40609970SGnoCiYeH                     events |= TcpSocket::CAN_ACCPET;
216*40609970SGnoCiYeH                 }
217*40609970SGnoCiYeH                 if inner_socket.state() == smoltcp::socket::tcp::State::Established {
218*40609970SGnoCiYeH                     events |= TcpSocket::CAN_CONNECT;
219*40609970SGnoCiYeH                 }
220*40609970SGnoCiYeH                 handle_guard
221*40609970SGnoCiYeH                     .get(&handle)
222*40609970SGnoCiYeH                     .unwrap()
223*40609970SGnoCiYeH                     .wait_queue
224*40609970SGnoCiYeH                     .wakeup_any(events);
225*40609970SGnoCiYeH             }
226*40609970SGnoCiYeH             smoltcp::socket::Socket::Dhcpv4(_) => {}
227*40609970SGnoCiYeH             smoltcp::socket::Socket::Dns(_) => unimplemented!("Dns socket hasn't unimplemented"),
228*40609970SGnoCiYeH         }
229*40609970SGnoCiYeH         drop(handle_guard);
230*40609970SGnoCiYeH         wakeup_epoll(handle, events as u32)?;
231*40609970SGnoCiYeH         // crate::kdebug!(
232*40609970SGnoCiYeH         //     "{} send_event {:?}",
233*40609970SGnoCiYeH         //     handle,
234*40609970SGnoCiYeH         //     EPollEventType::from_bits_truncate(events as u32)
235*40609970SGnoCiYeH         // );
236*40609970SGnoCiYeH     }
237*40609970SGnoCiYeH     Ok(())
238*40609970SGnoCiYeH }
239*40609970SGnoCiYeH 
240*40609970SGnoCiYeH /// ### 处理epoll
241*40609970SGnoCiYeH fn wakeup_epoll(handle: SocketHandle, events: u32) -> Result<(), SystemError> {
242*40609970SGnoCiYeH     let mut handle_guard = HANDLE_MAP.write_irqsave();
243*40609970SGnoCiYeH     let handle_item = handle_guard.get_mut(&handle).unwrap();
244*40609970SGnoCiYeH     let mut epitems_guard = handle_item.epitems.try_lock()?;
245*40609970SGnoCiYeH 
246*40609970SGnoCiYeH     // 从events拿到epoll相关事件
247*40609970SGnoCiYeH     let pollflags = EPollEventType::from_bits_truncate(events);
248*40609970SGnoCiYeH 
249*40609970SGnoCiYeH     // 一次只取一个,因为一次也只有一个进程能拿到对应文件的��
250*40609970SGnoCiYeH     if let Some(epitem) = epitems_guard.pop_front() {
251*40609970SGnoCiYeH         let epoll = epitem.epoll().upgrade().unwrap();
252*40609970SGnoCiYeH         let mut epoll_guard = epoll.try_lock()?;
253*40609970SGnoCiYeH         let binding = epitem.clone();
254*40609970SGnoCiYeH         let event_guard = binding.event().read();
255*40609970SGnoCiYeH         let ep_events = EPollEventType::from_bits_truncate(event_guard.events());
256*40609970SGnoCiYeH 
257*40609970SGnoCiYeH         // 检查事件合理性以及是否有感兴趣的事件
258*40609970SGnoCiYeH         if !(ep_events
259*40609970SGnoCiYeH             .difference(EPollEventType::EP_PRIVATE_BITS)
260*40609970SGnoCiYeH             .is_empty()
261*40609970SGnoCiYeH             || pollflags.difference(ep_events).is_empty())
262*40609970SGnoCiYeH         {
263*40609970SGnoCiYeH             // TODO: 未处理pm相关
264*40609970SGnoCiYeH 
265*40609970SGnoCiYeH             // 首先将就绪的epitem加入等待队列
266*40609970SGnoCiYeH             epoll_guard.ep_add_ready(epitem.clone());
267*40609970SGnoCiYeH 
268*40609970SGnoCiYeH             if epoll_guard.ep_has_waiter() {
269*40609970SGnoCiYeH                 if ep_events.contains(EPollEventType::EPOLLEXCLUSIVE)
270*40609970SGnoCiYeH                     && !pollflags.contains(EPollEventType::POLLFREE)
271*40609970SGnoCiYeH                 {
272*40609970SGnoCiYeH                     // 避免惊群
273*40609970SGnoCiYeH                     epoll_guard.ep_wake_one();
274*40609970SGnoCiYeH                 } else {
275*40609970SGnoCiYeH                     epoll_guard.ep_wake_all();
276*40609970SGnoCiYeH                 }
277*40609970SGnoCiYeH             }
278*40609970SGnoCiYeH         }
279*40609970SGnoCiYeH 
280*40609970SGnoCiYeH         epitems_guard.push_back(epitem);
281*40609970SGnoCiYeH     }
282*40609970SGnoCiYeH     Ok(())
283*40609970SGnoCiYeH }
284