xref: /DragonOS/kernel/src/net/net_core.rs (revision 7162a8358d94c7799dd2b5300192b6a794b23d79)
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::{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_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 let Some(cidr) = cidr {
89                         kinfo!("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                 kdebug!("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 NetDriver>>> = NET_DRIVERS.read_irqsave();
123     if guard.len() == 0 {
124         kwarn!("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 NetDriver>>> =
143             NET_DRIVERS.read_irqsave();
144         if guard.len() == 0 {
145             kwarn!("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 NetDriver>>> = NET_DRIVERS.read_irqsave();
174     if guard.len() == 0 {
175         kwarn!("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 item = handle_guard.get(&handle);
192         if item.is_none() {
193             continue;
194         }
195 
196         let handle_item = item.unwrap();
197 
198         // 获取socket上的事件
199         let mut events =
200             SocketPollMethod::poll(socket_type, handle_item.shutdown_type()).bits() as u64;
201 
202         // 分发到相应类型socket处理
203         match socket_type {
204             smoltcp::socket::Socket::Raw(_) | smoltcp::socket::Socket::Udp(_) => {
205                 handle_guard
206                     .get(&handle)
207                     .unwrap()
208                     .wait_queue
209                     .wakeup_any(events);
210             }
211             smoltcp::socket::Socket::Icmp(_) => unimplemented!("Icmp socket hasn't unimplemented"),
212             smoltcp::socket::Socket::Tcp(inner_socket) => {
213                 if inner_socket.is_active() {
214                     events |= TcpSocket::CAN_ACCPET;
215                 }
216                 if inner_socket.state() == smoltcp::socket::tcp::State::Established {
217                     events |= TcpSocket::CAN_CONNECT;
218                 }
219                 handle_guard
220                     .get(&handle)
221                     .unwrap()
222                     .wait_queue
223                     .wakeup_any(events);
224             }
225             smoltcp::socket::Socket::Dhcpv4(_) => {}
226             smoltcp::socket::Socket::Dns(_) => unimplemented!("Dns socket hasn't unimplemented"),
227         }
228         drop(handle_guard);
229         let mut handle_guard = HANDLE_MAP.write_irqsave();
230         let handle_item = handle_guard.get_mut(&handle).unwrap();
231         EventPoll::wakeup_epoll(
232             &handle_item.epitems,
233             EPollEventType::from_bits_truncate(events as u32),
234         )?;
235         // crate::kdebug!(
236         //     "{} send_event {:?}",
237         //     handle,
238         //     EPollEventType::from_bits_truncate(events as u32)
239         // );
240     }
241     Ok(())
242 }
243