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 {
run(&mut self) -> Result<(), SystemError>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 
net_init() -> Result<(), SystemError>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 }
dhcp_query() -> Result<(), SystemError>39 fn dhcp_query() -> Result<(), SystemError> {
40     let binding = NET_DRIVERS.write();
41 
42     let net_face = binding.get(&0).ok_or(SystemError::ENODEV)?.clone();
43 
44     drop(binding);
45 
46     // Create sockets
47     let mut dhcp_socket = dhcpv4::Socket::new();
48 
49     // Set a ridiculously short max lease time to show DHCP renews work properly.
50     // This will cause the DHCP client to start renewing after 5 seconds, and give up the
51     // lease after 10 seconds if renew hasn't succeeded.
52     // IMPORTANT: This should be removed in production.
53     dhcp_socket.set_max_lease_duration(Some(smoltcp::time::Duration::from_secs(10)));
54 
55     let mut sockets = smoltcp::iface::SocketSet::new(vec![]);
56     let dhcp_handle = sockets.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         let _flag = net_face.poll(&mut sockets);
62         let event = sockets.get_mut::<dhcpv4::Socket>(dhcp_handle).poll();
63         // kdebug!("event = {event:?} !!!");
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 
poll_ifaces()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((-1i64) as u64);
130 }
131 
132 /// 对ifaces进行轮询,最多对SOCKET_SET尝试times次加锁。
133 ///
134 /// @return 轮询成功,返回Ok(())
135 /// @return 加锁超时,返回SystemError::EAGAIN_OR_EWOULDBLOCK
136 /// @return 没有网卡,返回SystemError::ENODEV
poll_ifaces_try_lock(times: u16) -> Result<(), SystemError>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((-1i64) as u64);
158         return Ok(());
159     }
160 
161     // 尝试次数用完,返回错误
162     return Err(SystemError::EAGAIN_OR_EWOULDBLOCK);
163 }
164