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