xref: /DragonOS/kernel/src/net/net_core.rs (revision 3c82aa56d1b784ea7371100b3e906365be8332fd)
1 use alloc::{boxed::Box, collections::BTreeMap, sync::Arc};
2 use smoltcp::{socket::dhcpv4, wire};
3 
4 use crate::{
5     driver::net::NetDriver,
6     kdebug, kinfo, kwarn,
7     libs::rwlock::RwLockReadGuard,
8     net::NET_DRIVERS,
9     syscall::SystemError,
10     time::timer::{next_n_ms_timer_jiffies, Timer, TimerFunction},
11 };
12 
13 use super::socket::{SOCKET_SET, SOCKET_WAITQUEUE};
14 
15 /// The network poll function, which will be called by timer.
16 ///
17 /// The main purpose of this function is to poll all network interfaces.
18 #[derive(Debug)]
19 struct NetWorkPollFunc;
20 
21 impl TimerFunction for NetWorkPollFunc {
22     fn run(&mut self) -> Result<(), SystemError> {
23         poll_ifaces_try_lock(10).ok();
24         let next_time = next_n_ms_timer_jiffies(10);
25         let timer = Timer::new(Box::new(NetWorkPollFunc), next_time);
26         timer.activate();
27         return Ok(());
28     }
29 }
30 
31 pub fn net_init() -> Result<(), SystemError> {
32     dhcp_query()?;
33     // Init poll timer function
34     // let next_time = next_n_ms_timer_jiffies(5);
35     // let timer = Timer::new(Box::new(NetWorkPollFunc), next_time);
36     // timer.activate();
37     return Ok(());
38 }
39 
40 fn dhcp_query() -> Result<(), SystemError> {
41     let binding = NET_DRIVERS.write();
42 
43     let net_face = binding.get(&0).ok_or(SystemError::ENODEV)?.clone();
44 
45     drop(binding);
46 
47     // Create sockets
48     let mut dhcp_socket = dhcpv4::Socket::new();
49 
50     // Set a ridiculously short max lease time to show DHCP renews work properly.
51     // This will cause the DHCP client to start renewing after 5 seconds, and give up the
52     // lease after 10 seconds if renew hasn't succeeded.
53     // IMPORTANT: This should be removed in production.
54     dhcp_socket.set_max_lease_duration(Some(smoltcp::time::Duration::from_secs(10)));
55 
56     let dhcp_handle = SOCKET_SET.lock().add(dhcp_socket);
57 
58     const DHCP_TRY_ROUND: u8 = 10;
59     for i in 0..DHCP_TRY_ROUND {
60         kdebug!("DHCP try round: {}", i);
61         net_face.poll(&mut SOCKET_SET.lock()).ok();
62         let mut binding = SOCKET_SET.lock();
63         let event = binding.get_mut::<dhcpv4::Socket>(dhcp_handle).poll();
64 
65         match event {
66             None => {}
67 
68             Some(dhcpv4::Event::Configured(config)) => {
69                 // kdebug!("Find Config!! {config:?}");
70                 // kdebug!("Find ip address: {}", config.address);
71                 // kdebug!("iface.ip_addrs={:?}", net_face.inner_iface.ip_addrs());
72 
73                 net_face
74                     .update_ip_addrs(&[wire::IpCidr::Ipv4(config.address)])
75                     .ok();
76 
77                 if let Some(router) = config.router {
78                     net_face
79                         .inner_iface()
80                         .lock()
81                         .routes_mut()
82                         .add_default_ipv4_route(router)
83                         .unwrap();
84                     let cidr = net_face.inner_iface().lock().ip_addrs().first().cloned();
85                     if cidr.is_some() {
86                         let cidr = cidr.unwrap();
87                         kinfo!("Successfully allocated ip by Dhcpv4! Ip:{}", cidr);
88                         return Ok(());
89                     }
90                 } else {
91                     net_face
92                         .inner_iface()
93                         .lock()
94                         .routes_mut()
95                         .remove_default_ipv4_route();
96                 }
97             }
98 
99             Some(dhcpv4::Event::Deconfigured) => {
100                 kdebug!("Dhcp v4 deconfigured");
101                 net_face
102                     .update_ip_addrs(&[smoltcp::wire::IpCidr::Ipv4(wire::Ipv4Cidr::new(
103                         wire::Ipv4Address::UNSPECIFIED,
104                         0,
105                     ))])
106                     .ok();
107                 net_face
108                     .inner_iface()
109                     .lock()
110                     .routes_mut()
111                     .remove_default_ipv4_route();
112             }
113         }
114     }
115 
116     return Err(SystemError::ETIMEDOUT);
117 }
118 
119 pub fn poll_ifaces() {
120     let guard: RwLockReadGuard<BTreeMap<usize, Arc<dyn NetDriver>>> = NET_DRIVERS.read();
121     if guard.len() == 0 {
122         kwarn!("poll_ifaces: No net driver found!");
123         return;
124     }
125     let mut sockets = SOCKET_SET.lock();
126     for (_, iface) in guard.iter() {
127         iface.poll(&mut sockets).ok();
128     }
129     SOCKET_WAITQUEUE.wakeup_all(None);
130 }
131 
132 /// 对ifaces进行轮询,最多对SOCKET_SET尝试times次加锁。
133 ///
134 /// @return 轮询成功,返回Ok(())
135 /// @return 加锁超时,返回SystemError::EAGAIN_OR_EWOULDBLOCK
136 /// @return 没有网卡,返回SystemError::ENODEV
137 pub fn poll_ifaces_try_lock(times: u16) -> Result<(), SystemError> {
138     let mut i = 0;
139     while i < times {
140         let guard: RwLockReadGuard<BTreeMap<usize, Arc<dyn NetDriver>>> = NET_DRIVERS.read();
141         if guard.len() == 0 {
142             kwarn!("poll_ifaces: No net driver found!");
143             // 没有网卡,返回错误
144             return Err(SystemError::ENODEV);
145         }
146         let sockets = SOCKET_SET.try_lock();
147         // 加锁失败,继续尝试
148         if sockets.is_err() {
149             i += 1;
150             continue;
151         }
152 
153         let mut sockets = sockets.unwrap();
154         for (_, iface) in guard.iter() {
155             iface.poll(&mut sockets).ok();
156         }
157         SOCKET_WAITQUEUE.wakeup_all(None);
158         return Ok(());
159     }
160 
161     // 尝试次数用完,返回错误
162     return Err(SystemError::EAGAIN_OR_EWOULDBLOCK);
163 }
164 
165 /// 对ifaces进行轮询,最多对SOCKET_SET尝试一次加锁。
166 ///
167 /// @return 轮询成功,返回Ok(())
168 /// @return 加锁超时,返回SystemError::EAGAIN_OR_EWOULDBLOCK
169 /// @return 没有网卡,返回SystemError::ENODEV
170 pub fn poll_ifaces_try_lock_onetime() -> Result<(), SystemError> {
171     let guard: RwLockReadGuard<BTreeMap<usize, Arc<dyn NetDriver>>> = NET_DRIVERS.read();
172     if guard.len() == 0 {
173         kwarn!("poll_ifaces: No net driver found!");
174         // 没有网卡,返回错误
175         return Err(SystemError::ENODEV);
176     }
177     let mut sockets = SOCKET_SET.try_lock()?;
178     for (_, iface) in guard.iter() {
179         iface.poll(&mut sockets).ok();
180     }
181     SOCKET_WAITQUEUE.wakeup_all(None);
182     return Ok(());
183 }
184