Skip to content

Commit 00ea232

Browse files
authored
fix: loopback and udp resource problem (#1086)
* fix: loopback, udp resource aquire - remove tcp useless status update - enable smoltcp medium-ip feature - change loopback device use ip for addressing, avoid arp procedure - fix udp couldn't close bug - fix udp resource aquire didn't lock port - remove useless Timer in network initialization
1 parent c33082c commit 00ea232

File tree

8 files changed

+68
-80
lines changed

8 files changed

+68
-80
lines changed

kernel/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ linkme = "=0.3.27"
5252
num = { version = "=0.4.0", default-features = false }
5353
num-derive = "=0.3"
5454
num-traits = { git = "https://git.mirrors.dragonos.org.cn/DragonOS-Community/num-traits.git", rev="1597c1c", default-features = false }
55-
smoltcp = { git = "https://git.mirrors.dragonos.org.cn/DragonOS-Community/smoltcp.git", rev = "3e61c909fd540d05575068d16dc4574e196499ed", default-features = false, features = ["log", "alloc", "socket-raw", "socket-udp", "socket-tcp", "socket-icmp", "socket-dhcpv4", "socket-dns", "proto-ipv4", "proto-ipv6"]}
55+
smoltcp = { git = "https://git.mirrors.dragonos.org.cn/DragonOS-Community/smoltcp.git", rev = "3e61c909fd540d05575068d16dc4574e196499ed", default-features = false, features = ["log", "alloc", "socket-raw", "socket-udp", "socket-tcp", "socket-icmp", "socket-dhcpv4", "socket-dns", "proto-ipv4", "proto-ipv6", "medium-ip"]}
5656
system_error = { path = "crates/system_error" }
5757
uefi = { version = "=0.26.0", features = ["alloc"] }
5858
uefi-raw = "=0.5.0"

kernel/src/driver/net/loopback.rs

+6-4
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,7 @@ impl phy::Device for LoopbackDriver {
204204
let mut result = phy::DeviceCapabilities::default();
205205
result.max_transmission_unit = 65535;
206206
result.max_burst_size = Some(1);
207-
result.medium = smoltcp::phy::Medium::Ethernet;
207+
result.medium = smoltcp::phy::Medium::Ip;
208208
return result;
209209
}
210210
/// ## Loopback驱动处理接受数据事件
@@ -284,9 +284,11 @@ impl LoopbackInterface {
284284
pub fn new(mut driver: LoopbackDriver) -> Arc<Self> {
285285
let iface_id = generate_iface_id();
286286

287-
let hardware_addr = HardwareAddress::Ethernet(smoltcp::wire::EthernetAddress([
288-
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
289-
]));
287+
// let hardware_addr = HardwareAddress::Ethernet(smoltcp::wire::EthernetAddress([
288+
// 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
289+
// ]));
290+
291+
let hardware_addr = HardwareAddress::Ip;
290292

291293
let mut iface_config = smoltcp::iface::Config::new(hardware_addr);
292294

kernel/src/net/net_core.rs

+12-34
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use alloc::{boxed::Box, collections::BTreeMap, sync::Arc};
1+
use alloc::{collections::BTreeMap, sync::Arc};
22
use log::{debug, info, warn};
33
use smoltcp::{socket::dhcpv4, wire};
44
use system_error::SystemError;
@@ -7,45 +7,23 @@ use crate::{
77
driver::net::{Iface, Operstate},
88
libs::rwlock::RwLockReadGuard,
99
net::NET_DEVICES,
10-
time::{
11-
sleep::nanosleep,
12-
timer::{next_n_ms_timer_jiffies, Timer, TimerFunction},
13-
PosixTimeSpec,
14-
},
10+
time::{sleep::nanosleep, PosixTimeSpec},
1511
};
1612

17-
/// The network poll function, which will be called by timer.
18-
///
19-
/// The main purpose of this function is to poll all network interfaces.
20-
#[derive(Debug)]
21-
#[allow(dead_code)]
22-
struct NetWorkPollFunc;
23-
24-
impl TimerFunction for NetWorkPollFunc {
25-
fn run(&mut self) -> Result<(), SystemError> {
26-
poll_ifaces();
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-
3413
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(());
14+
dhcp_query()
4115
}
4216

4317
fn dhcp_query() -> Result<(), SystemError> {
4418
let binding = NET_DEVICES.write_irqsave();
45-
// log::debug!("binding: {:?}", *binding);
46-
//由于现在os未实现在用户态为网卡动态分配内存,而lo网卡的id最先分配且ip固定不能被分配
47-
//所以特判取用id为1的网卡(也就是virtio_net)
48-
let net_face = binding.get(&1).ok_or(SystemError::ENODEV)?.clone();
19+
20+
// Default iface, misspelled to net_face
21+
let net_face = binding
22+
.iter()
23+
.find(|(_, iface)| iface.common().is_default_iface())
24+
.unwrap()
25+
.1
26+
.clone();
4927

5028
drop(binding);
5129

@@ -149,7 +127,7 @@ fn dhcp_query() -> Result<(), SystemError> {
149127
}
150128

151129
pub fn poll_ifaces() {
152-
log::debug!("poll_ifaces");
130+
// log::debug!("poll_ifaces");
153131
let guard: RwLockReadGuard<BTreeMap<usize, Arc<dyn Iface>>> = NET_DEVICES.read_irqsave();
154132
if guard.len() == 0 {
155133
warn!("poll_ifaces: No net driver found!");

kernel/src/net/socket/inet/datagram/inner.rs

+3-9
Original file line numberDiff line numberDiff line change
@@ -33,16 +33,14 @@ impl UnboundUdp {
3333
}
3434

3535
pub fn bind(self, local_endpoint: smoltcp::wire::IpEndpoint) -> Result<BoundUdp, SystemError> {
36-
// let (addr, port) = (local_endpoint.addr, local_endpoint.port);
37-
// if self.socket.bind(local_endpoint).is_err() {
38-
// log::debug!("bind failed!");
39-
// return Err(EINVAL);
40-
// }
4136
let inner = BoundInner::bind(self.socket, &local_endpoint.addr)?;
4237
let bind_addr = local_endpoint.addr;
4338
let bind_port = if local_endpoint.port == 0 {
4439
inner.port_manager().bind_ephemeral_port(InetTypes::Udp)?
4540
} else {
41+
inner
42+
.port_manager()
43+
.bind_port(InetTypes::Udp, local_endpoint.port)?;
4644
local_endpoint.port
4745
};
4846

@@ -77,10 +75,6 @@ impl UnboundUdp {
7775
remote: SpinLock::new(Some(endpoint)),
7876
})
7977
}
80-
81-
pub fn close(&mut self) {
82-
self.socket.close();
83-
}
8478
}
8579

8680
#[derive(Debug)]

kernel/src/net/socket/inet/datagram/mod.rs

+20-12
Original file line numberDiff line numberDiff line change
@@ -78,28 +78,31 @@ impl UdpSocket {
7878
bound.close();
7979
inner.take();
8080
}
81+
// unbound socket just drop (only need to free memory)
8182
}
8283

8384
pub fn try_recv(
8485
&self,
8586
buf: &mut [u8],
8687
) -> Result<(usize, smoltcp::wire::IpEndpoint), SystemError> {
87-
let received = match self.inner.read().as_ref().expect("Udp Inner is None") {
88-
UdpInner::Bound(bound) => bound.try_recv(buf),
88+
match self.inner.read().as_ref().expect("Udp Inner is None") {
89+
UdpInner::Bound(bound) => {
90+
let ret = bound.try_recv(buf);
91+
poll_ifaces();
92+
ret
93+
}
8994
_ => Err(ENOTCONN),
90-
};
91-
poll_ifaces();
92-
return received;
95+
}
9396
}
9497

9598
#[inline]
9699
pub fn can_recv(&self) -> bool {
97-
self.on_events().contains(EP::EPOLLIN)
100+
self.event().contains(EP::EPOLLIN)
98101
}
99102

100103
#[inline]
101104
pub fn can_send(&self) -> bool {
102-
self.on_events().contains(EP::EPOLLOUT)
105+
self.event().contains(EP::EPOLLOUT)
103106
}
104107

105108
pub fn try_send(
@@ -138,7 +141,7 @@ impl UdpSocket {
138141
}
139142
}
140143

141-
pub fn on_events(&self) -> EPollEventType {
144+
pub fn event(&self) -> EPollEventType {
142145
let mut event = EPollEventType::empty();
143146
match self.inner.read().as_ref().unwrap() {
144147
UdpInner::Unbound(_) => {
@@ -154,8 +157,6 @@ impl UdpSocket {
154157

155158
if can_send {
156159
event.insert(EP::EPOLLOUT | EP::EPOLLWRNORM | EP::EPOLLWRBAND);
157-
} else {
158-
todo!("缓冲区空间不够,需要使用信号处理");
159160
}
160161
}
161162
}
@@ -169,7 +170,7 @@ impl Socket for UdpSocket {
169170
}
170171

171172
fn poll(&self) -> usize {
172-
self.on_events().bits() as usize
173+
self.event().bits() as usize
173174
}
174175

175176
fn bind(&self, local_endpoint: Endpoint) -> Result<(), SystemError> {
@@ -195,7 +196,9 @@ impl Socket for UdpSocket {
195196

196197
fn connect(&self, endpoint: Endpoint) -> Result<(), SystemError> {
197198
if let Endpoint::Ip(remote) = endpoint {
198-
self.bind_emphemeral(remote.addr)?;
199+
if !self.is_bound() {
200+
self.bind_emphemeral(remote.addr)?;
201+
}
199202
if let UdpInner::Bound(inner) = self.inner.read().as_ref().expect("UDP Inner disappear")
200203
{
201204
inner.connect(remote);
@@ -272,6 +275,11 @@ impl Socket for UdpSocket {
272275
}
273276
.map(|(len, remote)| (len, Endpoint::Ip(remote)));
274277
}
278+
279+
fn close(&self) -> Result<(), SystemError> {
280+
self.close();
281+
Ok(())
282+
}
275283
}
276284

277285
impl InetSocket for UdpSocket {

kernel/src/net/socket/inet/stream/inner.rs

+11-6
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,15 @@ impl Connecting {
268268
.expect("A Connecting Tcp With No Local Endpoint")
269269
})
270270
}
271+
272+
pub fn get_peer_name(&self) -> smoltcp::wire::IpEndpoint {
273+
self.inner
274+
.with::<smoltcp::socket::tcp::Socket, _, _>(|socket| {
275+
socket
276+
.remote_endpoint()
277+
.expect("A Connecting Tcp With No Remote Endpoint")
278+
})
279+
}
271280
}
272281

273282
#[derive(Debug)]
@@ -377,10 +386,6 @@ impl Established {
377386
self.inner.with_mut(f)
378387
}
379388

380-
pub fn with<R, F: Fn(&smoltcp::socket::tcp::Socket<'static>) -> R>(&self, f: F) -> R {
381-
self.inner.with(f)
382-
}
383-
384389
pub fn close(&self) {
385390
self.inner
386391
.with_mut::<smoltcp::socket::tcp::Socket, _, _>(|socket| socket.close());
@@ -391,13 +396,13 @@ impl Established {
391396
self.inner.release();
392397
}
393398

394-
pub fn local_endpoint(&self) -> smoltcp::wire::IpEndpoint {
399+
pub fn get_name(&self) -> smoltcp::wire::IpEndpoint {
395400
self.inner
396401
.with::<smoltcp::socket::tcp::Socket, _, _>(|socket| socket.local_endpoint())
397402
.unwrap()
398403
}
399404

400-
pub fn remote_endpoint(&self) -> smoltcp::wire::IpEndpoint {
405+
pub fn get_peer_name(&self) -> smoltcp::wire::IpEndpoint {
401406
self.inner
402407
.with::<smoltcp::socket::tcp::Socket, _, _>(|socket| socket.remote_endpoint().unwrap())
403408
}

kernel/src/net/socket/inet/stream/mod.rs

+13-12
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,6 @@ impl TcpSocket {
9999
}
100100

101101
pub fn try_accept(&self) -> Result<(Arc<TcpSocket>, smoltcp::wire::IpEndpoint), SystemError> {
102-
// poll_ifaces();
103102
match self.inner.write().as_mut().expect("Tcp Inner is None") {
104103
Inner::Listening(listening) => listening.accept().map(|(stream, remote)| {
105104
(
@@ -227,16 +226,9 @@ impl TcpSocket {
227226
}
228227
}
229228

230-
fn in_notify(&self) -> bool {
231-
self.update_events();
232-
// shouldn't pollee but just get the status of the socket
229+
fn incoming(&self) -> bool {
233230
EP::from_bits_truncate(self.poll() as u32).contains(EP::EPOLLIN)
234231
}
235-
236-
fn out_notify(&self) -> bool {
237-
self.update_events();
238-
EP::from_bits_truncate(self.poll() as u32).contains(EP::EPOLLOUT)
239-
}
240232
}
241233

242234
impl Socket for TcpSocket {
@@ -252,16 +244,25 @@ impl Socket for TcpSocket {
252244
})),
253245
Inner::Init(Init::Bound((_, local))) => Ok(Endpoint::Ip(*local)),
254246
Inner::Connecting(connecting) => Ok(Endpoint::Ip(connecting.get_name())),
255-
Inner::Established(established) => Ok(Endpoint::Ip(established.local_endpoint())),
247+
Inner::Established(established) => Ok(Endpoint::Ip(established.get_name())),
256248
Inner::Listening(listening) => Ok(Endpoint::Ip(listening.get_name())),
257249
}
258250
}
259251

252+
fn get_peer_name(&self) -> Result<Endpoint, SystemError> {
253+
match self.inner.read().as_ref().expect("Tcp Inner is None") {
254+
Inner::Init(_) => Err(ENOTCONN),
255+
Inner::Connecting(connecting) => Ok(Endpoint::Ip(connecting.get_peer_name())),
256+
Inner::Established(established) => Ok(Endpoint::Ip(established.get_peer_name())),
257+
Inner::Listening(_) => Err(ENOTCONN),
258+
}
259+
}
260+
260261
fn bind(&self, endpoint: Endpoint) -> Result<(), SystemError> {
261262
if let Endpoint::Ip(addr) = endpoint {
262263
return self.do_bind(addr);
263264
}
264-
log::warn!("TcpSocket::bind: invalid endpoint");
265+
log::debug!("TcpSocket::bind: invalid endpoint");
265266
return Err(EINVAL);
266267
}
267268

@@ -295,7 +296,7 @@ impl Socket for TcpSocket {
295296
loop {
296297
match self.try_accept() {
297298
Err(EAGAIN_OR_EWOULDBLOCK) => {
298-
wq_wait_event_interruptible!(self.wait_queue, self.in_notify(), {})?;
299+
wq_wait_event_interruptible!(self.wait_queue, self.incoming(), {})?;
299300
}
300301
result => break result,
301302
}

kernel/src/net/socket/unix/seqpacket/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -471,12 +471,12 @@ impl Socket for SeqpacketSocket {
471471
}
472472

473473
fn send_buffer_size(&self) -> usize {
474-
log::warn!("using default buffer size");
474+
// log::warn!("using default buffer size");
475475
SeqpacketSocket::DEFAULT_BUF_SIZE
476476
}
477477

478478
fn recv_buffer_size(&self) -> usize {
479-
log::warn!("using default buffer size");
479+
// log::warn!("using default buffer size");
480480
SeqpacketSocket::DEFAULT_BUF_SIZE
481481
}
482482

0 commit comments

Comments
 (0)