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