1 use alloc::{boxed::Box, collections::BTreeMap, sync::Arc};
2 use smoltcp::{socket::dhcpv4, wire};
3 use system_error::SystemError;
4 
5 use crate::{
6     driver::net::NetDriver,
7     kdebug, kinfo, kwarn,
8     libs::rwlock::RwLockReadGuard,
9     net::{socket::SocketPollMethod, NET_DRIVERS},
10     time::timer::{next_n_ms_timer_jiffies, Timer, TimerFunction},
11 };
12 
13 use super::{
14     event_poll::{EPollEventType, EventPoll},
15     socket::{sockets::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 {
run(&mut self) -> Result<(), SystemError>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 
net_init() -> Result<(), SystemError>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 
dhcp_query() -> Result<(), SystemError>43 fn dhcp_query() -> Result<(), SystemError> {
44     let binding = NET_DRIVERS.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         kdebug!("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                 // kdebug!("Find Config!! {config:?}");
73                 // kdebug!("Find ip address: {}", config.address);
74                 // kdebug!("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 cidr.is_some() {
89                         let cidr = cidr.unwrap();
90                         kinfo!("Successfully allocated ip by Dhcpv4! Ip:{}", cidr);
91                         return Ok(());
92                     }
93                 } else {
94                     net_face
95                         .inner_iface()
96                         .lock()
97                         .routes_mut()
98                         .remove_default_ipv4_route();
99                 }
100             }
101 
102             Some(dhcpv4::Event::Deconfigured) => {
103                 kdebug!("Dhcp v4 deconfigured");
104                 net_face
105                     .update_ip_addrs(&[smoltcp::wire::IpCidr::Ipv4(wire::Ipv4Cidr::new(
106                         wire::Ipv4Address::UNSPECIFIED,
107                         0,
108                     ))])
109                     .ok();
110                 net_face
111                     .inner_iface()
112                     .lock()
113                     .routes_mut()
114                     .remove_default_ipv4_route();
115             }
116         }
117     }
118 
119     return Err(SystemError::ETIMEDOUT);
120 }
121 
poll_ifaces()122 pub fn poll_ifaces() {
123     let guard: RwLockReadGuard<BTreeMap<usize, Arc<dyn NetDriver>>> = NET_DRIVERS.read_irqsave();
124     if guard.len() == 0 {
125         kwarn!("poll_ifaces: No net driver found!");
126         return;
127     }
128     let mut sockets = SOCKET_SET.lock_irqsave();
129     for (_, iface) in guard.iter() {
130         iface.poll(&mut sockets).ok();
131     }
132     let _ = send_event(&sockets);
133 }
134 
135 /// 对ifaces进行轮询,最多对SOCKET_SET尝试times次加锁。
136 ///
137 /// @return 轮询成功,返回Ok(())
138 /// @return 加锁超时,返回SystemError::EAGAIN_OR_EWOULDBLOCK
139 /// @return 没有网卡,返回SystemError::ENODEV
poll_ifaces_try_lock(times: u16) -> Result<(), SystemError>140 pub fn poll_ifaces_try_lock(times: u16) -> Result<(), SystemError> {
141     let mut i = 0;
142     while i < times {
143         let guard: RwLockReadGuard<BTreeMap<usize, Arc<dyn NetDriver>>> =
144             NET_DRIVERS.read_irqsave();
145         if guard.len() == 0 {
146             kwarn!("poll_ifaces: No net driver found!");
147             // 没有网卡,返回错误
148             return Err(SystemError::ENODEV);
149         }
150         let sockets = SOCKET_SET.try_lock_irqsave();
151         // 加锁失败,继续尝试
152         if sockets.is_err() {
153             i += 1;
154             continue;
155         }
156 
157         let mut sockets = sockets.unwrap();
158         for (_, iface) in guard.iter() {
159             iface.poll(&mut sockets).ok();
160         }
161         send_event(&sockets)?;
162         return Ok(());
163     }
164 
165     // 尝试次数用完,返回错误
166     return Err(SystemError::EAGAIN_OR_EWOULDBLOCK);
167 }
168 
169 /// 对ifaces进行轮询,最多对SOCKET_SET尝试一次加锁。
170 ///
171 /// @return 轮询成功,返回Ok(())
172 /// @return 加锁超时,返回SystemError::EAGAIN_OR_EWOULDBLOCK
173 /// @return 没有网卡,返回SystemError::ENODEV
poll_ifaces_try_lock_onetime() -> Result<(), SystemError>174 pub fn poll_ifaces_try_lock_onetime() -> Result<(), SystemError> {
175     let guard: RwLockReadGuard<BTreeMap<usize, Arc<dyn NetDriver>>> = NET_DRIVERS.read_irqsave();
176     if guard.len() == 0 {
177         kwarn!("poll_ifaces: No net driver found!");
178         // 没有网卡,返回错误
179         return Err(SystemError::ENODEV);
180     }
181     let mut sockets = SOCKET_SET.try_lock_irqsave()?;
182     for (_, iface) in guard.iter() {
183         iface.poll(&mut sockets).ok();
184     }
185     send_event(&sockets)?;
186     return Ok(());
187 }
188 
189 /// ### 处理轮询后的事件
send_event(sockets: &smoltcp::iface::SocketSet) -> Result<(), SystemError>190 fn send_event(sockets: &smoltcp::iface::SocketSet) -> Result<(), SystemError> {
191     for (handle, socket_type) in sockets.iter() {
192         let handle_guard = HANDLE_MAP.read_irqsave();
193         let item = handle_guard.get(&handle);
194         if item.is_none() {
195             continue;
196         }
197 
198         let handle_item = item.unwrap();
199 
200         // 获取socket上的事件
201         let mut events =
202             SocketPollMethod::poll(socket_type, handle_item.shutdown_type()).bits() as u64;
203 
204         // 分发到相应类型socket处理
205         match socket_type {
206             smoltcp::socket::Socket::Raw(_) | smoltcp::socket::Socket::Udp(_) => {
207                 handle_guard
208                     .get(&handle)
209                     .unwrap()
210                     .wait_queue
211                     .wakeup_any(events);
212             }
213             smoltcp::socket::Socket::Icmp(_) => unimplemented!("Icmp socket hasn't unimplemented"),
214             smoltcp::socket::Socket::Tcp(inner_socket) => {
215                 if inner_socket.is_active() {
216                     events |= TcpSocket::CAN_ACCPET;
217                 }
218                 if inner_socket.state() == smoltcp::socket::tcp::State::Established {
219                     events |= TcpSocket::CAN_CONNECT;
220                 }
221                 handle_guard
222                     .get(&handle)
223                     .unwrap()
224                     .wait_queue
225                     .wakeup_any(events);
226             }
227             smoltcp::socket::Socket::Dhcpv4(_) => {}
228             smoltcp::socket::Socket::Dns(_) => unimplemented!("Dns socket hasn't unimplemented"),
229         }
230         drop(handle_guard);
231         let mut handle_guard = HANDLE_MAP.write_irqsave();
232         let handle_item = handle_guard.get_mut(&handle).unwrap();
233         EventPoll::wakeup_epoll(
234             &mut handle_item.epitems,
235             EPollEventType::from_bits_truncate(events as u32),
236         )?;
237         // crate::kdebug!(
238         //     "{} send_event {:?}",
239         //     handle,
240         //     EPollEventType::from_bits_truncate(events as u32)
241         // );
242     }
243     Ok(())
244 }
245