Skip to content

Commit

Permalink
fix the alloc error and add unix socket
Browse files Browse the repository at this point in the history
  • Loading branch information
Godones committed Aug 22, 2024
1 parent 5fd6ef4 commit 233a139
Show file tree
Hide file tree
Showing 18 changed files with 163 additions and 78 deletions.
6 changes: 6 additions & 0 deletions .cargo/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[profile.release]
#strip = true
#incremental = true
#debug = true
opt-level = 3
lto = true
3 changes: 0 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 1 addition & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,6 @@ members = [
"user/apps/*",
"user/musl/hello",
"user/musl/async_test",
"user/musl/ftest",
]


[profile.release]
#lto = true
#codegen-units = 1

32 changes: 28 additions & 4 deletions kernel/src/net/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use alloc::{sync::Arc, vec, vec::Vec};
use constants::{io::OpenFlags, net::*, AlienResult, LinuxErrno};
use knet::{
addr::RawIpV4Addr,
socket::{SocketData, SocketFile, SocketFileExt},
socket::{Socket, SocketData, SocketFile, SocketFileExt},
};
use vfs::kfile::File;

Expand Down Expand Up @@ -460,21 +460,45 @@ pub fn socket_pair(domain: usize, s_type: usize, protocol: usize, sv: usize) ->
}
// println_color!(32,
// "socketpair: {:?}, {:?}, {:?}, {:?}",
// domain, s_type, protocol, sv
// domain, socket_type, protocol, sv
// );
let file1 = SocketData::new(domain, socket_type, protocol)?;
let file2 = file1.clone();
info!("socket domain: {:?}, type: {:?}", domain, socket_type);
let file2 = SocketData::new(domain, socket_type, protocol)?;
if s_type & SocketType::SOCK_NONBLOCK as usize != 0 {
let socket = file1.get_socketdata()?;
file1.set_open_flag(file1.get_open_flag() | OpenFlags::O_NONBLOCK);
socket.set_socket_nonblock(true);
let socket = file2.get_socketdata()?;
file2.set_open_flag(file2.get_open_flag() | OpenFlags::O_NONBLOCK);
socket.set_socket_nonblock(true);
info!("socket with nonblock");
}
if s_type & SocketType::SOCK_CLOEXEC as usize != 0 {
file1.set_close_on_exec();
file2.set_close_on_exec();
info!("socket with cloexec");
}

let socket_guard = file1.get_socketdata()?;
match &socket_guard.socket {
Socket::Unix(unix_socket) => {
unix_socket.set_remote(&(file2));
}
_ => {
panic!("socket_pair: unsupported socket type")
}
}
drop(socket_guard);
let socket_guard = file2.get_socketdata()?;
match &socket_guard.socket {
Socket::Unix(unix_socket) => {
unix_socket.set_remote(&file1);
}
_ => {
panic!("socket_pair: unsupported socket type")
}
}
drop(socket_guard);
let task = current_task().unwrap();
let fd1 = task.add_file(file1).map_err(|_| LinuxErrno::EMFILE)?;
let fd2 = task.add_file(file2).map_err(|_| LinuxErrno::EMFILE)?;
Expand Down
2 changes: 1 addition & 1 deletion kernel/src/task/cpu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ pub fn do_exit(exit_code: i32, exit_group: u8) -> isize {
/// 目前该系统调用直接调用[`do_exit`],有关进程组的相关功能有待实现。
#[syscall_func(94)]
pub fn exit_group(exit_code: i32) -> isize {
do_exit(exit_code, 1)
do_exit(exit_code, 0)
}

pub fn check_exit_group() {
Expand Down
21 changes: 20 additions & 1 deletion kernel/src/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,30 @@ use constants::{
use log::{info, warn};
use platform::{config::CLOCK_FREQ, set_timer};
use syscall_table::syscall_func;
use timer::{read_timer, TimeNow, Times, ToClock};
use timer::{get_time_ms, read_timer, TimeNow, Times, ToClock};
use vfs::timerfd::TimerFile;

use crate::task::{current_task, do_suspend, StatisticalData};

#[inline]
#[allow(unused)]
pub fn read_time_ms() -> u64 {
get_time_ms() as u64
}

#[inline]
#[allow(unused)]
pub fn read_time_ns() -> u64 {
let time = read_timer();
time as u64 * 1_000_000_000 / CLOCK_FREQ as u64
}

#[inline]
#[allow(unused)]
pub fn read_time_us() -> u64 {
let time = read_timer();
time as u64 * 1_000_000 / CLOCK_FREQ as u64
}
/// 每秒包含的 时间片 数,每隔一个时间片,就会产生一个时钟中断
const TICKS_PER_SEC: usize = 10;
// const TICKS_PER_SEC_IN_KERNEL: usize = 1000;
Expand Down
15 changes: 11 additions & 4 deletions subsystems/knet/src/socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
use alloc::{boxed::Box, sync::Arc};
use core::{
fmt::{Debug, Formatter},
net::SocketAddr,
net::{Ipv4Addr, SocketAddr, SocketAddrV4},
};

use constants::{
Expand Down Expand Up @@ -266,7 +266,7 @@ impl SocketData {
.map_err(neterror2alien)?;
}
_ => {
panic!("bind is not supported")
panic!("bind is not supported socket addr: {:?}", socket_addr);
}
}
Ok(())
Expand Down Expand Up @@ -329,8 +329,9 @@ impl SocketData {
udp.send(message).map_err(neterror2alien)
}
}
Socket::Unix(unix) => unix.send_to(message),
_ => {
panic!("bind is not supported")
panic!("send_to is not supported")
}
}
}
Expand All @@ -348,6 +349,11 @@ impl SocketData {
// let peer_addr = udp.peer_addr().map_err(neterror2linux)?;
Ok((recv.0, recv.1))
}
Socket::Unix(unix) => {
let socket_addr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), 0));
let len = unix.recvfrom(message)?;
Ok((len, socket_addr))
}
_ => {
panic!("bind is not supported")
}
Expand Down Expand Up @@ -434,8 +440,9 @@ impl SocketData {
false
}
}
Socket::Unix(unix) => unix.ready_read(),
_ => {
panic!("bind is not supported")
panic!("ready_read is not supported")
}
}
}
Expand Down
64 changes: 54 additions & 10 deletions subsystems/knet/src/unix.rs
Original file line number Diff line number Diff line change
@@ -1,30 +1,74 @@
//! 有关 Unix 协议族下的套接字结构。(目前有关的功能有待支持)
use alloc::{string::String, sync::Arc};
use alloc::{
string::String,
sync::{Arc, Weak},
vec::Vec,
};

use constants::LinuxErrno;
use constants::{AlienResult, LinuxErrno};
use ksync::Mutex;
use vfs::kfile::File;

use crate::socket::{Socket, SocketFile, SocketFileExt};

/// Unix 协议族下的套接字结构
#[allow(unused)]
pub struct UnixSocket {
/// 文件路径,即套接字地址
file_path: Mutex<Option<String>>,
/// 套接字数据
file: Mutex<Option<Arc<dyn File>>>,
inner: Mutex<UnixSocketInner>,
}

struct UnixSocketInner {
remote: Weak<SocketFile>,
buf: Vec<u8>,
}

impl UnixSocket {
/// 创建一个新的 Unix 协议族下的套接字结构
pub fn new() -> Self {
Self {
file_path: Mutex::new(None),
file: Mutex::new(None),
inner: Mutex::new(UnixSocketInner {
remote: Weak::<SocketFile>::new(),
buf: Vec::new(),
}),
}
}

/// UnixSocket 的 connect 操作
pub fn connect(&self, _file_path: String) -> Result<(), LinuxErrno> {
pub fn connect(&self, _file_path: String) -> AlienResult<()> {
Err(LinuxErrno::ENOENT)
}

pub fn set_remote(&self, remote: &Arc<SocketFile>) {
self.inner.lock().remote = Arc::downgrade(remote);
}

pub fn send_to(&self, buf: &[u8]) -> AlienResult<usize> {
if let Some(remote) = self.inner.lock().remote.upgrade() {
let socket_guard = remote.get_socketdata()?;
match socket_guard.socket {
Socket::Unix(ref unix_socket) => {
unix_socket.inner.lock().buf.extend_from_slice(buf);
Ok(buf.len())
}
_ => Err(LinuxErrno::EINVAL),
}
} else {
Err(LinuxErrno::ENOTCONN)
}
}

pub fn ready_read(&self) -> bool {
self.inner.lock().buf.len() > 0
}

pub fn recvfrom(&self, buf: &mut [u8]) -> AlienResult<usize> {
let inner_buf = &mut self.inner.lock().buf;
if inner_buf.len() > 0 {
let len = inner_buf.len().min(buf.len());
buf[..len].copy_from_slice(&inner_buf[..len]);
inner_buf.drain(..len);
Ok(len)
} else {
Err(LinuxErrno::EAGAIN)
}
}
}
2 changes: 1 addition & 1 deletion subsystems/platform/src/hifive_riscv/config.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
pub const CLOCK_FREQ: usize = 100_0000;
pub const BLOCK_CACHE_FRAMES: usize = 1024 * 4 * 4;
pub const HEAP_SIZE: usize = 0x40_00000; //64M
pub const HEAP_SIZE: usize = 0x70_00000; //64M

pub const MMIO: &[(usize, usize)] = &[
(0xc000000, 0x4000000), //PLIC
Expand Down
2 changes: 1 addition & 1 deletion subsystems/platform/src/qemu_riscv/config.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
pub const CLOCK_FREQ: usize = 1250_0000;
pub const BLOCK_CACHE_FRAMES: usize = 1024 * 4 * 4;
pub const HEAP_SIZE: usize = 0x40_00000; // (32+6)MB
pub const HEAP_SIZE: usize = 0x70_00000; // (32+6)MB

/// qemu的设备地址空间
pub const MMIO: &[(usize, usize)] = &[
Expand Down
2 changes: 1 addition & 1 deletion subsystems/platform/src/starfive2_riscv/config.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
pub const CLOCK_FREQ: usize = 400_0000;
pub const BLOCK_CACHE_FRAMES: usize = 1024 * 4 * 4;
pub const HEAP_SIZE: usize = 0x40_00000;
pub const HEAP_SIZE: usize = 0x70_00000;

/// vf2的设备地址空间

Expand Down
Binary file added tests/testbin-second-stage/bash2
Binary file not shown.
1 change: 0 additions & 1 deletion tools/qemu-loongarch-runenv
Submodule qemu-loongarch-runenv deleted from bb489f
1 change: 0 additions & 1 deletion user/apps/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ BUILD_CRATES := \
sleep \
socket_test \
final_test \
ftest \
# shell \
print \

Expand Down
42 changes: 0 additions & 42 deletions user/apps/ftest/src/main.rs

This file was deleted.

3 changes: 2 additions & 1 deletion user/musl/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@ build:

BUILD_CRATES := \
hello \
async_test
async_test \
ftest
3 changes: 1 addition & 2 deletions user/apps/ftest/Cargo.toml → user/musl/ftest/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,4 @@ name = "ftest"
version = "0.1.0"
edition = "2021"

[dependencies]
Mstd = {path = "../../userlib" }
[dependencies]
36 changes: 36 additions & 0 deletions user/musl/ftest/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
use std::{fs::File, io::Read, time::Instant};

fn main() {
read_bash_test();
// in cache
read_bash_test();
// read_once_test();
}
fn read_bash_test() {
let mut file = File::open("/tests/bash2").unwrap();
let now = Instant::now();
let mut buf = [0u8; 4096];
let mut bytes = 0;
loop {
let res = file.read(&mut buf).unwrap();
if res == 0 {
break;
}
bytes += res;
}
let ms = now.elapsed().as_millis();
let speed = bytes as f64 * 1000.0 / ms as f64 / 1024.0;
println!(
"Read {} bytes in {}ms, speed: {} KB/s",
bytes, ms, speed as isize
);
}

fn read_once_test() {
let mut file = File::open("/tests/bash2").unwrap();
let now = Instant::now();
let mut buf = [0u8; 4096];
let res = file.read(&mut buf).unwrap();
let ms = now.elapsed().as_micros();
println!("Read {} bytes in {}us", res, ms);
}

0 comments on commit 233a139

Please sign in to comment.