Skip to content

Commit bb48772

Browse files
committed
chore: little improvement to axnet
1 parent bf51dc7 commit bb48772

12 files changed

Lines changed: 70 additions & 62 deletions

File tree

modules/axdriver/src/dummy.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@
33
#![allow(unused_imports)]
44
#![allow(dead_code)]
55

6-
use super::prelude::*;
76
use cfg_if::cfg_if;
87

8+
use super::prelude::*;
9+
910
cfg_if! {
1011
if #[cfg(net_dev = "dummy")] {
1112
use axdriver_net::{EthernetAddress, NetBuf, NetBufBox, NetBufPool, NetBufPtr};
@@ -176,7 +177,7 @@ cfg_if! {
176177
fn abort(&mut self, _cid: VsockConnId) -> DevResult<()> {
177178
Err(DevError::Unsupported)
178179
}
179-
fn poll_event(&mut self, _buf: &mut [u8]) -> DevResult<Option<VsockDriverEvent>> {
180+
fn poll_event(&mut self) -> DevResult<Option<VsockDriverEvent>> {
180181
Err(DevError::Unsupported)
181182
}
182183
}

modules/axnet/Cargo.toml

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,7 @@
22
name = "axnet"
33
version.workspace = true
44
edition.workspace = true
5-
authors = [
6-
"Yuekai Jia <equation618@gmail.com>",
7-
"ChengXiang Qi <kuangjux@outlook.com>",
8-
]
5+
authors = ["Mivik <mivikq@gmail.com>"]
96
description = "ArceOS network module"
107
license.workspace = true
118
homepage.workspace = true
@@ -16,29 +13,27 @@ documentation = "https://arceos-org.github.io/arceos/axnet/index.html"
1613
vsock = ["axdriver/vsock"]
1714

1815
[dependencies]
16+
async-channel = { version = "2.5", default-features = false }
17+
async-trait = "0.1"
1918
axconfig = { workspace = true }
2019
axdriver = { workspace = true, features = ["net"] }
21-
axhal = { workspace = true }
22-
axsync = { workspace = true }
23-
axtask = { workspace = true }
24-
2520
axerrno = { workspace = true }
2621
axfs = { workspace = true }
2722
axfs-ng-vfs = { workspace = true }
23+
axhal = { workspace = true }
2824
axio = { workspace = true }
2925
axpoll = { workspace = true }
26+
axsync = { workspace = true }
27+
axtask = { workspace = true }
3028
bitflags = "2.9.1"
3129
cfg-if = { workspace = true }
3230
enum_dispatch = { workspace = true }
31+
event-listener = { version = "5.4", default-features = false }
3332
hashbrown = "0.16"
34-
lazyinit = { workspace = true }
3533
lazy_static = { workspace = true }
3634
log = { workspace = true }
37-
spin = { workspace = true }
3835
ringbuf = { version = "0.4.8", default-features = false, features = ["alloc"] }
39-
async-channel = { version = "2.5.0", default-features = false }
40-
event-listener = { version = "5.4.0", default-features = false }
41-
async-trait = "0.1.88"
36+
spin = { workspace = true }
4237

4338
[dependencies.smoltcp]
4439
package = "starry-smoltcp"

modules/axnet/src/device/vsock.rs

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use alloc::collections::VecDeque;
1+
use alloc::{collections::VecDeque, string::ToString};
22
use core::{
33
sync::atomic::{AtomicBool, AtomicU64, Ordering},
44
time::Duration,
@@ -9,7 +9,7 @@ use axerrno::{AxError, AxResult, ax_bail};
99
use axsync::Mutex;
1010
use axtask::future::{block_on, interruptible};
1111

12-
use crate::{alloc::string::ToString, vsock::connection_manager::VSOCK_CONN_MANAGER};
12+
use crate::vsock::connection_manager::VSOCK_CONN_MANAGER;
1313

1414
// we need a global and static only one vsock device
1515
static VSOCK_DEVICE: Mutex<Option<AxVsockDevice>> = Mutex::new(None);
@@ -210,7 +210,10 @@ fn handle_vsock_event(event: VsockDriverEvent, dev: &mut AxVsockDevice, buf: &mu
210210

211211
VsockDriverEvent::CreditUpdate(conn_id) => {
212212
if let Err(e) = manager.on_credit_update(conn_id) {
213-
warn!("Failed to handle credit update: {:?}, error={:?}", conn_id, e);
213+
warn!(
214+
"Failed to handle credit update: {:?}, error={:?}",
215+
conn_id, e
216+
);
214217
}
215218
}
216219

@@ -242,7 +245,7 @@ pub fn vsock_connect(conn_id: VsockConnId) -> AxResult<()> {
242245
}
243246

244247
pub fn vsock_send(conn_id: VsockConnId, buf: &[u8]) -> AxResult<usize> {
245-
let max_retries = 10; // Tests have shown that no more than two retries will be notified
248+
let max_retries = 10; // Tests have shown that no more than two retries will be notified
246249
for _ in 0..max_retries {
247250
let result = {
248251
let mut guard = VSOCK_DEVICE.lock();
@@ -258,7 +261,7 @@ pub fn vsock_send(conn_id: VsockConnId, buf: &[u8]) -> AxResult<usize> {
258261
conn.lock().wait_for_tx();
259262
};
260263
}
261-
Err(e) => return Err(map_dev_err(e)),
264+
Err(e) => return Err(map_dev_err(e)),
262265
}
263266
}
264267
Err(map_dev_err(DevError::Again))

modules/axnet/src/general.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use axpoll::{IoEvents, Pollable};
99
use axtask::future::{block_on, poll_io, timeout};
1010

1111
use crate::{
12-
SERVICE,
12+
get_service,
1313
options::{Configurable, GetSocketOption, SetSocketOption},
1414
};
1515

@@ -70,7 +70,7 @@ impl GeneralOptions {
7070
}
7171

7272
pub fn register_waker(&self, waker: &Waker) {
73-
SERVICE.lock().register_waker(self.device_mask(), waker);
73+
get_service().register_waker(self.device_mask(), waker);
7474
}
7575

7676
pub fn send_poller<P: Pollable, F: FnMut() -> AxResult<T>, T>(

modules/axnet/src/lib.rs

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -38,11 +38,11 @@ use alloc::{borrow::ToOwned, boxed::Box};
3838

3939
use axdriver::{AxDeviceContainer, prelude::*};
4040
use axsync::Mutex;
41-
use lazyinit::LazyInit;
4241
use smoltcp::wire::{EthernetAddress, Ipv4Address, Ipv4Cidr};
43-
pub use socket::*;
42+
use spin::{Lazy, Once};
4443

45-
use crate::{
44+
pub use self::socket::*;
45+
use self::{
4646
consts::{GATEWAY, IP, IP_PREFIX},
4747
device::{EthernetDevice, LoopbackDevice},
4848
listen_table::ListenTable,
@@ -51,10 +51,17 @@ use crate::{
5151
wrapper::SocketSetWrapper,
5252
};
5353

54-
static LISTEN_TABLE: LazyInit<ListenTable> = LazyInit::new();
55-
static SOCKET_SET: LazyInit<SocketSetWrapper> = LazyInit::new();
54+
static LISTEN_TABLE: Lazy<ListenTable> = Lazy::new(ListenTable::new);
55+
static SOCKET_SET: Lazy<SocketSetWrapper> = Lazy::new(SocketSetWrapper::new);
5656

57-
static SERVICE: LazyInit<Mutex<Service>> = LazyInit::new();
57+
static SERVICE: Once<Mutex<Service>> = Once::new();
58+
59+
fn get_service() -> axsync::MutexGuard<'static, Service> {
60+
SERVICE
61+
.get()
62+
.expect("Network service not initialized")
63+
.lock()
64+
}
5865

5966
/// Initializes the network subsystem by NIC devices.
6067
pub fn init_network(mut net_devs: AxDeviceContainer<AxNetDevice>) {
@@ -111,16 +118,13 @@ pub fn init_network(mut net_devs: AxDeviceContainer<AxNetDevice>) {
111118
ip_addrs.push(eth0_ip.into()).unwrap();
112119
}
113120
});
114-
SERVICE.init_once(Mutex::new(service));
115-
116-
SOCKET_SET.init_once(SocketSetWrapper::new());
117-
LISTEN_TABLE.init_once(ListenTable::new());
121+
SERVICE.call_once(|| Mutex::new(service));
118122
}
119123

120124
/// Init vsock subsystem by vsock devices.
121125
#[cfg(feature = "vsock")]
122126
pub fn init_vsock(mut vsock_devs: AxDeviceContainer<AxVsockDevice>) {
123-
use crate::device::register_vsock_device;
127+
use self::device::register_vsock_device;
124128
info!("Initialize vsock subsystem...");
125129
if let Some(dev) = vsock_devs.take_one() {
126130
info!(" use vsock 0: {:?}", dev.device_name());
@@ -133,5 +137,5 @@ pub fn init_vsock(mut vsock_devs: AxDeviceContainer<AxVsockDevice>) {
133137
}
134138

135139
pub fn poll_interfaces() {
136-
while SERVICE.lock().poll(&mut SOCKET_SET.inner.lock()) {}
140+
while get_service().poll(&mut SOCKET_SET.inner.lock()) {}
137141
}

modules/axnet/src/listen_table.rs

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,12 @@ use crate::{
1616

1717
const PORT_NUM: usize = 65536;
1818

19-
struct ListenTableEntry {
19+
struct ListenTableEntryInner {
2020
listen_endpoint: IpListenEndpoint,
2121
syn_queue: VecDeque<SocketHandle>,
2222
}
2323

24-
impl ListenTableEntry {
24+
impl ListenTableEntryInner {
2525
pub fn new(listen_endpoint: IpListenEndpoint) -> Self {
2626
Self {
2727
listen_endpoint,
@@ -30,16 +30,18 @@ impl ListenTableEntry {
3030
}
3131
}
3232

33-
impl Drop for ListenTableEntry {
33+
impl Drop for ListenTableEntryInner {
3434
fn drop(&mut self) {
3535
for &handle in &self.syn_queue {
3636
SOCKET_SET.remove(handle);
3737
}
3838
}
3939
}
4040

41+
type ListenTableEntry = Arc<Mutex<Option<Box<ListenTableEntryInner>>>>;
42+
4143
pub struct ListenTable {
42-
tcp: Box<[Arc<Mutex<Option<Box<ListenTableEntry>>>>]>,
44+
tcp: Box<[ListenTableEntry]>,
4345
}
4446

4547
impl ListenTable {
@@ -63,7 +65,7 @@ impl ListenTable {
6365
assert_ne!(port, 0);
6466
let mut entry = self.tcp[port as usize].lock();
6567
if entry.is_none() {
66-
*entry = Some(Box::new(ListenTableEntry::new(listen_endpoint)));
68+
*entry = Some(Box::new(ListenTableEntryInner::new(listen_endpoint)));
6769
Ok(())
6870
} else {
6971
warn!("socket already listening on port {port}");
@@ -76,7 +78,7 @@ impl ListenTable {
7678
*self.tcp[port as usize].lock() = None;
7779
}
7880

79-
fn listen_entry(&self, port: u16) -> Arc<Mutex<Option<Box<ListenTableEntry>>>> {
81+
fn listen_entry(&self, port: u16) -> Arc<Mutex<Option<Box<ListenTableEntryInner>>>> {
8082
self.tcp[port as usize].clone()
8183
}
8284

modules/axnet/src/tcp.rs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,12 @@ use smoltcp::{
1616
wire::{IpEndpoint, IpListenEndpoint},
1717
};
1818

19-
use super::{LISTEN_TABLE, SOCKET_SET};
2019
use crate::{
21-
RecvFlags, RecvOptions, SERVICE, SendOptions, Shutdown, Socket, SocketAddrEx, SocketOps,
20+
LISTEN_TABLE, RecvFlags, RecvOptions, SOCKET_SET, SendOptions, Shutdown, Socket, SocketAddrEx,
21+
SocketOps,
2222
consts::{TCP_RX_BUF_LEN, TCP_TX_BUF_LEN},
2323
general::GeneralOptions,
24+
get_service,
2425
options::{Configurable, GetSocketOption, SetSocketOption},
2526
poll_interfaces,
2627
state::*,
@@ -71,7 +72,7 @@ impl TcpSocket {
7172
result.with_smol_socket(|socket| {
7273
result
7374
.general
74-
.set_device_mask(SERVICE.lock().device_mask_for(&socket.get_bound_endpoint()));
75+
.set_device_mask(get_service().device_mask_for(&socket.get_bound_endpoint()));
7576
});
7677
result
7778
}
@@ -232,7 +233,7 @@ impl SocketOps for TcpSocket {
232233
};
233234
socket.set_bound_endpoint(endpoint);
234235
self.general
235-
.set_device_mask(SERVICE.lock().device_mask_for(&endpoint));
236+
.set_device_mask(get_service().device_mask_for(&endpoint));
236237
Ok(())
237238
})?;
238239
debug!("TCP socket {}: binding to {}", self.handle, local_addr);
@@ -260,7 +261,7 @@ impl SocketOps for TcpSocket {
260261
self.with_smol_socket(|socket| socket.get_bound_endpoint());
261262
if bound_endpoint.addr.is_none() {
262263
bound_endpoint.addr =
263-
Some(SERVICE.lock().get_source_address(&remote_endpoint.addr));
264+
Some(get_service().get_source_address(&remote_endpoint.addr));
264265
}
265266
if bound_endpoint.port == 0 {
266267
bound_endpoint.port = get_ephemeral_port()?;
@@ -273,10 +274,10 @@ impl SocketOps for TcpSocket {
273274
self.with_smol_socket(|socket| {
274275
socket.set_bound_endpoint(bound_endpoint);
275276
self.general
276-
.set_device_mask(SERVICE.lock().device_mask_for(&bound_endpoint));
277+
.set_device_mask(get_service().device_mask_for(&bound_endpoint));
277278
socket
278279
.connect(
279-
crate::SERVICE.lock().iface.context(),
280+
get_service().iface.context(),
280281
remote_endpoint,
281282
bound_endpoint,
282283
)

modules/axnet/src/udp.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,10 @@ use smoltcp::{
1818
use spin::RwLock;
1919

2020
use crate::{
21-
RecvFlags, RecvOptions, SERVICE, SOCKET_SET, SendOptions, Shutdown, SocketAddrEx, SocketOps,
21+
RecvFlags, RecvOptions, SOCKET_SET, SendOptions, Shutdown, SocketAddrEx, SocketOps,
2222
consts::{UDP_RX_BUF_LEN, UDP_TX_BUF_LEN},
2323
general::GeneralOptions,
24+
get_service,
2425
options::{Configurable, GetSocketOption, SetSocketOption},
2526
poll_interfaces,
2627
};
@@ -141,7 +142,7 @@ impl SocketOps for UdpSocket {
141142
})
142143
})?;
143144
self.general
144-
.set_device_mask(SERVICE.lock().device_mask_for(&endpoint));
145+
.set_device_mask(get_service().device_mask_for(&endpoint));
145146

146147
*guard = Some(local_endpoint);
147148
info!("UDP socket {}: bound on {}", self.handle, endpoint);
@@ -159,7 +160,7 @@ impl SocketOps for UdpSocket {
159160
}
160161

161162
let remote_addr = IpEndpoint::from(remote_addr);
162-
let src = SERVICE.lock().get_source_address(&remote_addr.addr);
163+
let src = get_service().get_source_address(&remote_addr.addr);
163164
*guard = Some((remote_addr, src));
164165
debug!("UDP socket {}: connected to {}", self.handle, remote_addr);
165166
Ok(())
@@ -169,7 +170,7 @@ impl SocketOps for UdpSocket {
169170
let (remote_addr, source_addr) = match options.to {
170171
Some(addr) => {
171172
let addr = IpEndpoint::from(addr.into_ip()?);
172-
let src = SERVICE.lock().get_source_address(&addr.addr);
173+
let src = get_service().get_source_address(&addr.addr);
173174
(addr, src)
174175
}
175176
None => self.remote_endpoint()?,

modules/axnet/src/vsock/connection_manager.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use axtask::WaitQueue;
77
use ringbuf::{HeapCons, HeapProd, HeapRb, traits::*};
88

99
use super::{VsockAddr, VsockConnId};
10+
use crate::device::{start_vsock_poll, stop_vsock_poll};
1011

1112
pub const VSOCK_RX_BUFFER_SIZE: usize = 64 * 1024; // 64KB receive buffer
1213
const VSOCK_ACCEPT_QUEUE_SIZE: usize = 128; // accept queue size
@@ -367,7 +368,7 @@ impl VsockConnectionManager {
367368
if self.connections.contains_key(&conn_id) {
368369
info!("Connection {:?} already exists, overwriting", conn_id);
369370
} else {
370-
crate::device::start_vsock_poll();
371+
start_vsock_poll();
371372
}
372373
self.connections.insert(conn_id, conn.clone());
373374
debug!(
@@ -386,7 +387,8 @@ impl VsockConnectionManager {
386387
pub fn remove_connection(&mut self, conn_id: VsockConnId) {
387388
if let Some(conn) = self.connections.remove(&conn_id) {
388389
let conn = conn.lock();
389-
crate::device::stop_vsock_poll();
390+
391+
stop_vsock_poll();
390392
debug!(
391393
"Removed connection {:?}: rx={} bytes, tx={} bytes, dropped={} bytes",
392394
conn_id, conn.rx_bytes, conn.tx_bytes, conn.dropped_bytes
@@ -420,7 +422,7 @@ impl VsockConnectionManager {
420422

421423
// 加入 accept 队列
422424
let mut queue_guard = queue.lock();
423-
if let Err(_) = queue_guard.accept_queue.push(conn_id) {
425+
if queue_guard.accept_queue.push(conn_id).is_err() {
424426
info!(
425427
"Accept queue full for port {}, dropping connection from {:?}",
426428
conn_id.local_port, conn_id.peer_addr

0 commit comments

Comments
 (0)