xref: /DragonOS/kernel/src/net/net_core.rs (revision f79998f626801329580c782fd05e36cb2027f474)
1 use alloc::{boxed::Box, collections::BTreeMap, sync::Arc};
2 use log::{debug, info, warn};
3 use smoltcp::{socket::dhcpv4, wire};
4 use system_error::SystemError;
5 
6 use crate::{
7     driver::net::NetDevice,
8     libs::rwlock::RwLockReadGuard,
9     net::{socket::SocketPollMethod, NET_DEVICES},
10     time::timer::{next_n_ms_timer_jiffies, Timer, TimerFunction},
11 };
12 
13 use super::{
14     event_poll::{EPollEventType, EventPoll},
15     socket::{handle::GlobalSocketHandle, inet::TcpSocket, HANDLE_MAP, SOCKET_SET},
16 };
17 
18 /// The network poll function, which will be called by timer.
19 ///
20 /// The main purpose of this function is to poll all network interfaces.
21 #[derive(Debug)]
22 struct NetWorkPollFunc;
23 
24 impl TimerFunction for NetWorkPollFunc {
25     fn run(&mut self) -> Result<(), SystemError> {
26         poll_ifaces_try_lock(10).ok();
27         let next_time = next_n_ms_timer_jiffies(10);
28         let timer = Timer::new(Box::new(NetWorkPollFunc), next_time);
29         timer.activate();
30         return Ok(());
31     }
32 }
33 
34 pub fn net_init() -> Result<(), SystemError> {
35     dhcp_query()?;
36     // Init poll timer function
37     // let next_time = next_n_ms_timer_jiffies(5);
38     // let timer = Timer::new(Box::new(NetWorkPollFunc), next_time);
39     // timer.activate();
40     return Ok(());
41 }
42 
43 fn dhcp_query() -> Result<(), SystemError> {
44     let binding = NET_DEVICES.write_irqsave();
45 
46     let net_face = binding.get(&0).ok_or(SystemError::ENODEV)?.clone();
47 
48     drop(binding);
49 
50     // Create sockets
51     let mut dhcp_socket = dhcpv4::Socket::new();
52 
53     // Set a ridiculously short max lease time to show DHCP renews work properly.
54     // This will cause the DHCP client to start renewing after 5 seconds, and give up the
55     // lease after 10 seconds if renew hasn't succeeded.
56     // IMPORTANT: This should be removed in production.
57     dhcp_socket.set_max_lease_duration(Some(smoltcp::time::Duration::from_secs(10)));
58 
59     let dhcp_handle = SOCKET_SET.lock_irqsave().add(dhcp_socket);
60 
61     const DHCP_TRY_ROUND: u8 = 10;
62     for i in 0..DHCP_TRY_ROUND {
63         debug!("DHCP try round: {}", i);
64         net_face.poll(&mut SOCKET_SET.lock_irqsave()).ok();
65         let mut binding = SOCKET_SET.lock_irqsave();
66         let event = binding.get_mut::<dhcpv4::Socket>(dhcp_handle).poll();
67 
68         match event {
69             None => {}
70 
71             Some(dhcpv4::Event::Configured(config)) => {
72                 // debug!("Find Config!! {config:?}");
73                 // debug!("Find ip address: {}", config.address);
74                 // debug!("iface.ip_addrs={:?}", net_face.inner_iface.ip_addrs());
75 
76                 net_face
77                     .update_ip_addrs(&[wire::IpCidr::Ipv4(config.address)])
78                     .ok();
79 
80                 if let Some(router) = config.router {
81                     net_face
82                         .inner_iface()
83                         .lock()
84                         .routes_mut()
85                         .add_default_ipv4_route(router)
86                         .unwrap();
87                     let cidr = net_face.inner_iface().lock().ip_addrs().first().cloned();
88                     if let Some(cidr) = cidr {
89                         info!("Successfully allocated ip by Dhcpv4! Ip:{}", cidr);
90                         return Ok(());
91                     }
92                 } else {
93                     net_face
94                         .inner_iface()
95                         .lock()
96                         .routes_mut()
97                         .remove_default_ipv4_route();
98                 }
99             }
100 
101             Some(dhcpv4::Event::Deconfigured) => {
102                 debug!("Dhcp v4 deconfigured");
103                 net_face
104                     .update_ip_addrs(&[smoltcp::wire::IpCidr::Ipv4(wire::Ipv4Cidr::new(
105                         wire::Ipv4Address::UNSPECIFIED,
106                         0,
107                     ))])
108                     .ok();
109                 net_face
110                     .inner_iface()
111                     .lock()
112                     .routes_mut()
113                     .remove_default_ipv4_route();
114             }
115         }
116     }
117 
118     return Err(SystemError::ETIMEDOUT);
119 }
120 
121 pub fn poll_ifaces() {
122     let guard: RwLockReadGuard<BTreeMap<usize, Arc<dyn NetDevice>>> = NET_DEVICES.read_irqsave();
123     if guard.len() == 0 {
124         warn!("poll_ifaces: No net driver found!");
125         return;
126     }
127     let mut sockets = SOCKET_SET.lock_irqsave();
128     for (_, iface) in guard.iter() {
129         iface.poll(&mut sockets).ok();
130     }
131     let _ = send_event(&sockets);
132 }
133 
134 /// 对ifaces进行轮询,最多对SOCKET_SET尝试times次加锁。
135 ///
136 /// @return 轮询成功,返回Ok(())
137 /// @return 加锁超时,返回SystemError::EAGAIN_OR_EWOULDBLOCK
138 /// @return 没有网卡,返回SystemError::ENODEV
139 pub fn poll_ifaces_try_lock(times: u16) -> Result<(), SystemError> {
140     let mut i = 0;
141     while i < times {
142         let guard: RwLockReadGuard<BTreeMap<usize, Arc<dyn NetDevice>>> =
143             NET_DEVICES.read_irqsave();
144         if guard.len() == 0 {
145             warn!("poll_ifaces: No net driver found!");
146             // 没有网卡,返回错误
147             return Err(SystemError::ENODEV);
148         }
149         let sockets = SOCKET_SET.try_lock_irqsave();
150         // 加锁失败,继续尝试
151         if sockets.is_err() {
152             i += 1;
153             continue;
154         }
155 
156         let mut sockets = sockets.unwrap();
157         for (_, iface) in guard.iter() {
158             iface.poll(&mut sockets).ok();
159         }
160         send_event(&sockets)?;
161         return Ok(());
162     }
163     // 尝试次数用完,返回错误
164     return Err(SystemError::EAGAIN_OR_EWOULDBLOCK);
165 }
166 
167 /// 对ifaces进行轮询,最多对SOCKET_SET尝试一次加锁。
168 ///
169 /// @return 轮询成功,返回Ok(())
170 /// @return 加锁超时,返回SystemError::EAGAIN_OR_EWOULDBLOCK
171 /// @return 没有网卡,返回SystemError::ENODEV
172 pub fn poll_ifaces_try_lock_onetime() -> Result<(), SystemError> {
173     let guard: RwLockReadGuard<BTreeMap<usize, Arc<dyn NetDevice>>> = NET_DEVICES.read_irqsave();
174     if guard.len() == 0 {
175         warn!("poll_ifaces: No net driver found!");
176         // 没有网卡,返回错误
177         return Err(SystemError::ENODEV);
178     }
179     let mut sockets = SOCKET_SET.try_lock_irqsave()?;
180     for (_, iface) in guard.iter() {
181         iface.poll(&mut sockets).ok();
182     }
183     send_event(&sockets)?;
184     return Ok(());
185 }
186 
187 /// ### 处理轮询后的事件
188 fn send_event(sockets: &smoltcp::iface::SocketSet) -> Result<(), SystemError> {
189     for (handle, socket_type) in sockets.iter() {
190         let handle_guard = HANDLE_MAP.read_irqsave();
191         let global_handle = GlobalSocketHandle::new_smoltcp_handle(handle);
192         let item = handle_guard.get(&global_handle);
193         if item.is_none() {
194             continue;
195         }
196 
197         let handle_item = item.unwrap();
198 
199         // 获取socket上的事件
200         let mut events =
201             SocketPollMethod::poll(socket_type, handle_item.shutdown_type()).bits() as u64;
202 
203         // 分发到相应类型socket处理
204         match socket_type {
205             smoltcp::socket::Socket::Raw(_) | smoltcp::socket::Socket::Udp(_) => {
206                 handle_guard
207                     .get(&global_handle)
208                     .unwrap()
209                     .wait_queue
210                     .wakeup_any(events);
211             }
212             smoltcp::socket::Socket::Icmp(_) => unimplemented!("Icmp socket hasn't unimplemented"),
213             smoltcp::socket::Socket::Tcp(inner_socket) => {
214                 if inner_socket.is_active() {
215                     events |= TcpSocket::CAN_ACCPET;
216                 }
217                 if inner_socket.state() == smoltcp::socket::tcp::State::Established {
218                     events |= TcpSocket::CAN_CONNECT;
219                 }
220                 if inner_socket.state() == smoltcp::socket::tcp::State::CloseWait {
221                     events |= EPollEventType::EPOLLHUP.bits() as u64;
222                 }
223                 handle_guard
224                     .get(&global_handle)
225                     .unwrap()
226                     .wait_queue
227                     .wakeup_any(events);
228             }
229             smoltcp::socket::Socket::Dhcpv4(_) => {}
230             smoltcp::socket::Socket::Dns(_) => unimplemented!("Dns socket hasn't unimplemented"),
231         }
232         EventPoll::wakeup_epoll(
233             &handle_item.epitems,
234             EPollEventType::from_bits_truncate(events as u32),
235         )?;
236         drop(handle_guard);
237         // crate::debug!(
238         //     "{} send_event {:?}",
239         //     handle,
240         //     EPollEventType::from_bits_truncate(events as u32)
241         // );
242     }
243     Ok(())
244 }
245