feat: remove syscall prettier printing (#988)

* 重新组织代码分布

* remove unused imports

* fix it back to old syscall printing style

* regulate naming to posix

* todo: socket close 及 port 接触占用

* fix: format check
This commit is contained in:
Samuel Dai 2024-10-17 14:46:35 +08:00 committed by GitHub
parent 10e62c7a47
commit 7cd11b4ff8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
38 changed files with 351 additions and 1359 deletions

View File

@ -1,7 +1,7 @@
use crate::{
arch::{
ipc::signal::X86_64SignalArch,
syscall::nr::{SysCall, SYS_ARCH_PRCTL, SYS_RT_SIGRETURN},
syscall::nr::{SYS_ARCH_PRCTL, SYS_RT_SIGRETURN},
CurrentIrqArch,
},
exception::InterruptArch,
@ -53,7 +53,7 @@ macro_rules! syscall_return {
if $show {
let pid = ProcessManager::current_pcb().pid();
debug!("[SYS] [Pid: {:?}] [Retn: {:?}]", pid, ret as i64);
debug!("syscall return:pid={:?},ret= {:?}\n", pid, ret as isize);
}
unsafe {
@ -63,24 +63,6 @@ macro_rules! syscall_return {
}};
}
macro_rules! normal_syscall_return {
($val:expr, $regs:expr, $show:expr) => {{
let ret = $val;
if $show {
let pid = ProcessManager::current_pcb().pid();
debug!("[SYS] [Pid: {:?}] [Retn: {:?}]", pid, ret);
}
$regs.rax = ret.unwrap_or_else(|e| e.to_posix_errno() as usize) as u64;
unsafe {
CurrentIrqArch::interrupt_disable();
}
return;
}};
}
#[no_mangle]
pub extern "sysv64" fn syscall_handler(frame: &mut TrapFrame) {
let syscall_num = frame.rax as usize;
@ -105,38 +87,15 @@ pub extern "sysv64" fn syscall_handler(frame: &mut TrapFrame) {
];
mfence();
let pid = ProcessManager::current_pcb().pid();
let mut show = (syscall_num != SYS_SCHED) && (pid.data() >= 7);
// let mut show = true;
let show = false;
// let show = if syscall_num != SYS_SCHED && pid.data() >= 7 {
// true
// } else {
// false
// };
let to_print = SysCall::try_from(syscall_num);
if let Ok(to_print) = to_print {
use SysCall::*;
match to_print {
SYS_ACCEPT | SYS_ACCEPT4 | SYS_BIND | SYS_CONNECT | SYS_SHUTDOWN | SYS_LISTEN => {
show &= true;
}
SYS_RECVFROM | SYS_SENDTO | SYS_SENDMSG | SYS_RECVMSG => {
show &= true;
}
SYS_SOCKET | SYS_GETSOCKNAME | SYS_GETPEERNAME | SYS_SOCKETPAIR | SYS_SETSOCKOPT
| SYS_GETSOCKOPT => {
show &= true;
}
SYS_OPEN | SYS_OPENAT | SYS_CREAT | SYS_CLOSE => {
show &= true;
}
SYS_READ | SYS_WRITE | SYS_READV | SYS_WRITEV | SYS_PREAD64 | SYS_PWRITE64
| SYS_PREADV | SYS_PWRITEV | SYS_PREADV2 => {
show &= true;
}
_ => {
show &= false;
}
}
show &= false;
if show {
debug!("[SYS] [Pid: {:?}] [Call: {:?}]", pid, to_print);
}
if show {
debug!("syscall: pid: {:?}, num={:?}\n", pid, syscall_num);
}
// Arch specific syscall
@ -149,11 +108,21 @@ pub extern "sysv64" fn syscall_handler(frame: &mut TrapFrame) {
);
}
SYS_ARCH_PRCTL => {
normal_syscall_return!(Syscall::arch_prctl(args[0], args[1]), frame, show);
syscall_return!(
Syscall::arch_prctl(args[0], args[1])
.unwrap_or_else(|e| e.to_posix_errno() as usize),
frame,
show
);
}
_ => {}
}
normal_syscall_return!(Syscall::handle(syscall_num, &args, frame), frame, show);
syscall_return!(
Syscall::handle(syscall_num, &args, frame).unwrap_or_else(|e| e.to_posix_errno() as usize)
as u64,
frame,
show
);
}
/// 系统调用初始化

View File

@ -355,381 +355,3 @@ pub const SYS_WAIT4: usize = 61;
pub const SYS_WAITID: usize = 247;
pub const SYS_WRITE: usize = 1;
pub const SYS_WRITEV: usize = 20;
use num_traits::{FromPrimitive, ToPrimitive};
use system_error::SystemError;
#[allow(non_camel_case_types)]
#[derive(Debug, Clone, Copy, FromPrimitive, ToPrimitive, PartialEq, Eq)]
pub enum SysCall {
SYS__SYSCTL = 156,
SYS_ACCEPT = 43,
SYS_ACCEPT4 = 288,
SYS_ACCESS = 21,
SYS_ACCT = 163,
SYS_ADD_KEY = 248,
SYS_ADJTIMEX = 159,
SYS_AFS_SYSCALL = 183,
SYS_ALARM = 37,
SYS_ARCH_PRCTL = 158,
SYS_BIND = 49,
SYS_BPF = 321,
SYS_BRK = 12,
SYS_CAPGET = 125,
SYS_CAPSET = 126,
SYS_CHDIR = 80,
SYS_CHMOD = 90,
SYS_CHOWN = 92,
SYS_CHROOT = 161,
SYS_CLOCK_ADJTIME = 305,
SYS_CLOCK_GETRES = 229,
SYS_CLOCK_GETTIME = 228,
SYS_CLOCK_NANOSLEEP = 230,
SYS_CLOCK_SETTIME = 227,
SYS_CLONE = 56,
SYS_CLONE3 = 435,
SYS_CLOSE = 3,
SYS_CLOSE_RANGE = 436,
SYS_CONNECT = 42,
SYS_COPY_FILE_RANGE = 326,
SYS_CREAT = 85,
SYS_CREATE_MODULE = 174,
SYS_DELETE_MODULE = 176,
SYS_DUP = 32,
SYS_DUP2 = 33,
SYS_DUP3 = 292,
SYS_EPOLL_CREATE = 213,
SYS_EPOLL_CREATE1 = 291,
SYS_EPOLL_CTL = 233,
SYS_EPOLL_CTL_OLD = 214,
SYS_EPOLL_PWAIT = 281,
SYS_EPOLL_PWAIT2 = 441,
SYS_EPOLL_WAIT = 232,
SYS_EPOLL_WAIT_OLD = 215,
SYS_EVENTFD = 284,
SYS_EVENTFD2 = 290,
SYS_EXECVE = 59,
SYS_EXECVEAT = 322,
SYS_EXIT = 60,
SYS_EXIT_GROUP = 231,
SYS_FACCESSAT = 269,
SYS_FACCESSAT2 = 439,
SYS_FADVISE64 = 221,
SYS_FALLOCATE = 285,
SYS_FANOTIFY_INIT = 300,
SYS_FANOTIFY_MARK = 301,
SYS_FCHDIR = 81,
SYS_FCHMOD = 91,
SYS_FCHMODAT = 268,
SYS_FCHOWN = 93,
SYS_FCHOWNAT = 260,
SYS_FCNTL = 72,
SYS_FDATASYNC = 75,
SYS_FGETXATTR = 193,
SYS_FINIT_MODULE = 313,
SYS_FLISTXATTR = 196,
SYS_FLOCK = 73,
SYS_FORK = 57,
SYS_FREMOVEXATTR = 199,
SYS_FSCONFIG = 431,
SYS_FSETXATTR = 190,
SYS_FSMOUNT = 432,
SYS_FSOPEN = 430,
SYS_FSPICK = 433,
SYS_FSTAT = 5,
SYS_FSTATFS = 138,
SYS_FSYNC = 74,
SYS_FTRUNCATE = 77,
SYS_FUTEX = 202,
SYS_FUTIMESAT = 261,
SYS_GET_KERNEL_SYMS = 177,
SYS_GET_MEMPOLICY = 239,
SYS_GET_ROBUST_LIST = 274,
SYS_GET_THREAD_AREA = 211,
SYS_GETCPU = 309,
SYS_GETCWD = 79,
SYS_GETDENTS = 78,
SYS_GETDENTS64 = 217,
SYS_GETEGID = 108,
SYS_GETEUID = 107,
SYS_GETGID = 104,
SYS_GETGROUPS = 115,
SYS_GETITIMER = 36,
SYS_GETPEERNAME = 52,
SYS_GETPGID = 121,
SYS_GETPGRP = 111,
SYS_GETPID = 39,
SYS_GETPMSG = 181,
SYS_GETPPID = 110,
SYS_GETPRIORITY = 140,
SYS_GETRANDOM = 318,
SYS_GETRESGID = 120,
SYS_GETRESUID = 118,
SYS_GETRLIMIT = 97,
SYS_GETRUSAGE = 98,
SYS_GETSID = 124,
SYS_GETSOCKNAME = 51,
SYS_GETSOCKOPT = 55,
SYS_GETTID = 186,
SYS_GETTIMEOFDAY = 96,
SYS_GETUID = 102,
SYS_GETXATTR = 191,
SYS_INIT_MODULE = 175,
SYS_INOTIFY_ADD_WATCH = 254,
SYS_INOTIFY_INIT = 253,
SYS_INOTIFY_INIT1 = 294,
SYS_INOTIFY_RM_WATCH = 255,
SYS_IO_CANCEL = 210,
SYS_IO_DESTROY = 207,
SYS_IO_GETEVENTS = 208,
SYS_IO_PGETEVENTS = 333,
SYS_IO_SETUP = 206,
SYS_IO_SUBMIT = 209,
SYS_IO_URING_ENTER = 426,
SYS_IO_URING_REGISTER = 427,
SYS_IO_URING_SETUP = 425,
SYS_IOCTL = 16,
SYS_IOPERM = 173,
SYS_IOPL = 172,
SYS_IOPRIO_GET = 252,
SYS_IOPRIO_SET = 251,
SYS_KCMP = 312,
SYS_KEXEC_FILE_LOAD = 320,
SYS_KEXEC_LOAD = 246,
SYS_KEYCTL = 250,
SYS_KILL = 62,
SYS_LCHOWN = 94,
SYS_LGETXATTR = 192,
SYS_LINK = 86,
SYS_LINKAT = 265,
SYS_LISTEN = 50,
SYS_LISTXATTR = 194,
SYS_LLISTXATTR = 195,
SYS_LOOKUP_DCOOKIE = 212,
SYS_LREMOVEXATTR = 198,
SYS_LSEEK = 8,
SYS_LSETXATTR = 189,
SYS_LSTAT = 6,
SYS_MADVISE = 28,
SYS_MBIND = 237,
SYS_MEMBARRIER = 324,
SYS_MEMFD_CREATE = 319,
SYS_MIGRATE_PAGES = 256,
SYS_MINCORE = 27,
SYS_MKDIR = 83,
SYS_MKDIRAT = 258,
SYS_MKNOD = 133,
SYS_MKNODAT = 259,
SYS_MLOCK = 149,
SYS_MLOCK2 = 325,
SYS_MLOCKALL = 151,
SYS_MMAP = 9,
SYS_MODIFY_LDT = 154,
SYS_MOUNT = 165,
SYS_MOUNT_SETATTR = 442,
SYS_MOVE_MOUNT = 429,
SYS_MOVE_PAGES = 279,
SYS_MPROTECT = 10,
SYS_MQ_GETSETATTR = 245,
SYS_MQ_NOTIFY = 244,
SYS_MQ_OPEN = 240,
SYS_MQ_TIMEDRECEIVE = 243,
SYS_MQ_TIMEDSEND = 242,
SYS_MQ_UNLINK = 241,
SYS_MREMAP = 25,
SYS_MSGCTL = 71,
SYS_MSGGET = 68,
SYS_MSGRCV = 70,
SYS_MSGSND = 69,
SYS_MSYNC = 26,
SYS_MUNLOCK = 150,
SYS_MUNLOCKALL = 152,
SYS_MUNMAP = 11,
SYS_NAME_TO_HANDLE_AT = 303,
SYS_NANOSLEEP = 35,
SYS_NEWFSTATAT = 262,
SYS_NFSSERVCTL = 180,
SYS_OPEN = 2,
SYS_OPEN_BY_HANDLE_AT = 304,
SYS_OPEN_TREE = 428,
SYS_OPENAT = 257,
SYS_OPENAT2 = 437,
SYS_PAUSE = 34,
SYS_PERF_EVENT_OPEN = 298,
SYS_PERSONALITY = 135,
SYS_PIDFD_GETFD = 438,
SYS_PIDFD_OPEN = 434,
SYS_PIDFD_SEND_SIGNAL = 424,
SYS_PIPE = 22,
SYS_PIPE2 = 293,
SYS_PIVOT_ROOT = 155,
SYS_PKEY_ALLOC = 330,
SYS_PKEY_FREE = 331,
SYS_PKEY_MPROTECT = 329,
SYS_POLL = 7,
SYS_PPOLL = 271,
SYS_PRCTL = 157,
SYS_PREAD64 = 17,
SYS_PREADV = 295,
SYS_PREADV2 = 327,
SYS_PRLIMIT64 = 302,
SYS_PROCESS_MADVISE = 440,
SYS_PROCESS_VM_READV = 310,
SYS_PROCESS_VM_WRITEV = 311,
SYS_PSELECT6 = 270,
SYS_PTRACE = 101,
SYS_PUTPMSG = 182,
SYS_PWRITE64 = 18,
SYS_PWRITEV = 296,
SYS_PWRITEV2 = 328,
SYS_QUERY_MODULE = 178,
SYS_QUOTACTL = 179,
SYS_READ = 0,
SYS_READAHEAD = 187,
SYS_READLINK = 89,
SYS_READLINKAT = 267,
SYS_READV = 19,
SYS_REBOOT = 169,
SYS_RECVFROM = 45,
SYS_RECVMMSG = 299,
SYS_RECVMSG = 47,
SYS_REMAP_FILE_PAGES = 216,
SYS_REMOVEXATTR = 197,
SYS_RENAME = 82,
SYS_RENAMEAT = 264,
SYS_RENAMEAT2 = 316,
SYS_REQUEST_KEY = 249,
SYS_RESTART_SYSCALL = 219,
SYS_RMDIR = 84,
SYS_RSEQ = 334,
SYS_RT_SIGACTION = 13,
SYS_RT_SIGPENDING = 127,
SYS_RT_SIGPROCMASK = 14,
SYS_RT_SIGQUEUEINFO = 129,
SYS_RT_SIGRETURN = 15,
SYS_RT_SIGSUSPEND = 130,
SYS_RT_SIGTIMEDWAIT = 128,
SYS_RT_TGSIGQUEUEINFO = 297,
SYS_SCHED_GET_PRIORITY_MAX = 146,
SYS_SCHED_GET_PRIORITY_MIN = 147,
SYS_SCHED_GETAFFINITY = 204,
SYS_SCHED_GETATTR = 315,
SYS_SCHED_GETPARAM = 143,
SYS_SCHED_GETSCHEDULER = 145,
SYS_SCHED_RR_GET_INTERVAL = 148,
SYS_SCHED_SETAFFINITY = 203,
SYS_SCHED_SETATTR = 314,
SYS_SCHED_SETPARAM = 142,
SYS_SCHED_SETSCHEDULER = 144,
SYS_SCHED_YIELD = 24,
SYS_SECCOMP = 317,
SYS_SECURITY = 185,
SYS_SELECT = 23,
SYS_SEMCTL = 66,
SYS_SEMGET = 64,
SYS_SEMOP = 65,
SYS_SEMTIMEDOP = 220,
SYS_SENDFILE = 40,
SYS_SENDMMSG = 307,
SYS_SENDMSG = 46,
SYS_SENDTO = 44,
SYS_SET_MEMPOLICY = 238,
SYS_SET_ROBUST_LIST = 273,
SYS_SET_THREAD_AREA = 205,
SYS_SET_TID_ADDRESS = 218,
SYS_SETDOMAINNAME = 171,
SYS_SETFSGID = 123,
SYS_SETFSUID = 122,
SYS_SETGID = 106,
SYS_SETGROUPS = 116,
SYS_SETHOSTNAME = 170,
SYS_SETITIMER = 38,
SYS_SETNS = 308,
SYS_SETPGID = 109,
SYS_SETPRIORITY = 141,
SYS_SETREGID = 114,
SYS_SETRESGID = 119,
SYS_SETRESUID = 117,
SYS_SETREUID = 113,
SYS_SETRLIMIT = 160,
SYS_SETSID = 112,
SYS_SETSOCKOPT = 54,
SYS_SETTIMEOFDAY = 164,
SYS_SETUID = 105,
SYS_SETXATTR = 188,
SYS_SHMAT = 30,
SYS_SHMCTL = 31,
SYS_SHMDT = 67,
SYS_SHMGET = 29,
SYS_SHUTDOWN = 48,
SYS_SIGALTSTACK = 131,
SYS_SIGNALFD = 282,
SYS_SIGNALFD4 = 289,
SYS_SOCKET = 41,
SYS_SOCKETPAIR = 53,
SYS_SPLICE = 275,
SYS_STAT = 4,
SYS_STATFS = 137,
SYS_STATX = 332,
SYS_SWAPOFF = 168,
SYS_SWAPON = 167,
SYS_SYMLINK = 88,
SYS_SYMLINKAT = 266,
SYS_SYNC = 162,
SYS_SYNC_FILE_RANGE = 277,
SYS_SYNCFS = 306,
SYS_SYSFS = 139,
SYS_SYSINFO = 99,
SYS_SYSLOG = 103,
SYS_TEE = 276,
SYS_TGKILL = 234,
SYS_TIME = 201,
SYS_TIMER_CREATE = 222,
SYS_TIMER_DELETE = 226,
SYS_TIMER_GETOVERRUN = 225,
SYS_TIMER_GETTIME = 224,
SYS_TIMER_SETTIME = 223,
SYS_TIMERFD_CREATE = 283,
SYS_TIMERFD_GETTIME = 287,
SYS_TIMERFD_SETTIME = 286,
SYS_TIMES = 100,
SYS_TKILL = 200,
SYS_TRUNCATE = 76,
SYS_TUXCALL = 184,
SYS_UMASK = 95,
SYS_UMOUNT2 = 166,
SYS_UNAME = 63,
SYS_UNLINK = 87,
SYS_UNLINKAT = 263,
SYS_UNSHARE = 272,
SYS_USELIB = 134,
SYS_USERFAULTFD = 323,
SYS_USTAT = 136,
SYS_UTIME = 132,
SYS_UTIMENSAT = 280,
SYS_UTIMES = 235,
SYS_VFORK = 58,
SYS_VHANGUP = 153,
SYS_VMSPLICE = 278,
SYS_VSERVER = 236,
SYS_WAIT4 = 61,
SYS_WAITID = 247,
SYS_WRITE = 1,
SYS_WRITEV = 20,
}
impl TryFrom<usize> for SysCall {
type Error = SystemError;
fn try_from(value: usize) -> Result<Self, Self::Error> {
match <Self as FromPrimitive>::from_usize(value) {
Some(p) => Ok(p),
None => Err(SystemError::EINVAL),
}
}
}
impl From<SysCall> for usize {
fn from(value: SysCall) -> Self {
<SysCall as ToPrimitive>::to_usize(&value).unwrap()
}
}

View File

@ -506,7 +506,7 @@ impl DeviceManager {
}
let kobject_parent = self.get_device_parent(&device, deivce_parent)?;
if let Some(ref kobj) = kobject_parent {
log::info!("kobject parent: {:?}", kobj.name());
log::debug!("kobject parent: {:?}", kobj.name());
}
if let Some(kobject_parent) = kobject_parent {
// debug!(

View File

@ -8,7 +8,7 @@ use crate::driver::base::kobject::{
};
use crate::driver::base::kset::KSet;
use crate::filesystem::kernfs::KernFSInode;
use crate::init::initcall::INITCALL_DEVICE;
// use crate::init::initcall::INITCALL_DEVICE;
use crate::libs::rwlock::{RwLockReadGuard, RwLockWriteGuard};
use crate::libs::spinlock::{SpinLock, SpinLockGuard};
use crate::net::{generate_iface_id, NET_DEVICES};
@ -26,7 +26,7 @@ use smoltcp::{
wire::{IpAddress, IpCidr},
};
use system_error::SystemError;
use unified_init::macros::unified_init;
// use unified_init::macros::unified_init;
use super::{register_netdevice, NetDeivceState, NetDeviceCommonData, Operstate};

View File

@ -1,9 +1,5 @@
use alloc::{fmt, vec::Vec};
use alloc::{string::String, sync::Arc};
use smoltcp::{
iface,
wire::{self, EthernetAddress},
};
use sysfs::netdev_register_kobject;
use crate::{

View File

@ -1,5 +1,4 @@
use alloc::sync::Arc;
use log::{debug, warn};
use system_error::SystemError;
use super::{
@ -58,7 +57,7 @@ pub fn do_fchmodat(dirfd: i32, path: *const u8, _mode: ModeType) -> Result<usize
// 如果找不到文件则返回错误码ENOENT
let _inode = inode.lookup_follow_symlink(path.as_str(), VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
warn!("do_fchmodat: not implemented yet\n");
log::warn!("do_fchmodat: not implemented yet\n");
// todo: 真正去改变文件的权限
return Ok(0);

View File

@ -2,7 +2,6 @@ use core::ffi::c_void;
use core::mem::size_of;
use alloc::{string::String, sync::Arc, vec::Vec};
use log::{debug, warn};
use system_error::SystemError;
use crate::producefs;
@ -1225,7 +1224,7 @@ impl Syscall {
// TODO: unimplemented
// 未实现的命令返回0不报错。
warn!("fcntl: unimplemented command: {:?}, defaults to 0.", cmd);
log::warn!("fcntl: unimplemented command: {:?}, defaults to 0.", cmd);
return Err(SystemError::ENOSYS);
}
}
@ -1614,7 +1613,7 @@ impl Syscall {
// fchmod没完全实现因此不修改文件的权限
// todo: 实现fchmod
warn!("fchmod not fully implemented");
log::warn!("fchmod not fully implemented");
return Ok(0);
}
/// #挂载文件系统

View File

@ -2,10 +2,7 @@
//! 注意net模块下为了方便导入模块细分且共用部分模块直接使用
//! `pub use`导出,导入时也常见`use crate::net::socket::*`的写法,
//! 敬请注意。
use core::{
fmt::{self, Debug},
sync::atomic::AtomicUsize,
};
use core::sync::atomic::AtomicUsize;
use alloc::{collections::BTreeMap, sync::Arc};

View File

@ -145,99 +145,3 @@ pub fn poll_ifaces() {
iface.poll();
}
}
// /// 对ifaces进行轮询最多对SOCKET_SET尝试times次加锁。
// ///
// /// @return 轮询成功返回Ok(())
// /// @return 加锁超时返回SystemError::EAGAIN_OR_EWOULDBLOCK
// /// @return 没有网卡返回SystemError::ENODEV
// pub fn poll_ifaces_try_lock(times: u16) -> Result<(), SystemError> {
// let mut i = 0;
// while i < times {
// let guard: RwLockReadGuard<BTreeMap<usize, Arc<dyn Iface>>> =
// NET_DEVICES.read_irqsave();
// if guard.len() == 0 {
// warn!("poll_ifaces: No net driver found!");
// // 没有网卡,返回错误
// return Err(SystemError::ENODEV);
// }
// for (_, iface) in guard.iter() {
// iface.poll();
// }
// return Ok(());
// }
// // 尝试次数用完,返回错误
// return Err(SystemError::EAGAIN_OR_EWOULDBLOCK);
// }
// /// 对ifaces进行轮询最多对SOCKET_SET尝试一次加锁。
// ///
// /// @return 轮询成功返回Ok(())
// /// @return 加锁超时返回SystemError::EAGAIN_OR_EWOULDBLOCK
// /// @return 没有网卡返回SystemError::ENODEV
// pub fn poll_ifaces_try_lock_onetime() -> Result<(), SystemError> {
// let guard: RwLockReadGuard<BTreeMap<usize, Arc<dyn Iface>>> = NET_DEVICES.read_irqsave();
// if guard.len() == 0 {
// warn!("poll_ifaces: No net driver found!");
// // 没有网卡,返回错误
// return Err(SystemError::ENODEV);
// }
// for (_, iface) in guard.iter() {
// let _ = iface.poll();
// }
// send_event()?;
// return Ok(());
// }
// /// ### 处理轮询后的事件
// fn send_event() -> Result<(), SystemError> {
// for (handle, socket_type) in .lock().iter() {
// let global_handle = GlobalSocketHandle::new_smoltcp_handle(handle);
// let handle_guard = HANDLE_MAP.read_irqsave();
// let item: Option<&super::socket::SocketHandleItem> = handle_guard.get(&global_handle);
// if item.is_none() {
// continue;
// }
// let handle_item = item.unwrap();
// let posix_item = handle_item.posix_item();
// if posix_item.is_none() {
// continue;
// }
// let posix_item = posix_item.unwrap();
// // 获取socket上的事件
// let mut events = SocketPollMethod::poll(socket_type, handle_item).bits() as u64;
// // 分发到相应类型socket处理
// match socket_type {
// smoltcp::socket::Socket::Raw(_) | smoltcp::socket::Socket::Udp(_) => {
// posix_item.wakeup_any(events);
// }
// smoltcp::socket::Socket::Icmp(_) => unimplemented!("Icmp socket hasn't unimplemented"),
// smoltcp::socket::Socket::Tcp(inner_socket) => {
// if inner_socket.is_active() {
// events |= TcpSocket::CAN_ACCPET;
// }
// if inner_socket.state() == smoltcp::socket::tcp::State::Established {
// events |= TcpSocket::CAN_CONNECT;
// }
// if inner_socket.state() == smoltcp::socket::tcp::State::CloseWait {
// events |= EPollEventType::EPOLLHUP.bits() as u64;
// }
// posix_item.wakeup_any(events);
// }
// smoltcp::socket::Socket::Dhcpv4(_) => {}
// smoltcp::socket::Socket::Dns(_) => unimplemented!("Dns socket hasn't unimplemented"),
// }
// EventPoll::wakeup_epoll(
// &posix_item.epitems,
// EPollEventType::from_bits_truncate(events as u32),
// )?;
// drop(handle_guard);
// }
// Ok(())
// }

View File

@ -58,12 +58,7 @@ pub trait Socket: Sync + Send + Debug + Any {
}
/// # `get_option`
/// 对应于 Posix `getsockopt` 获取socket选项
fn get_option(
&self,
level: OptionsLevel,
name: usize,
value: &mut [u8],
) -> Result<usize, SystemError> {
fn get_option(&self, level: PSOL, name: usize, value: &mut [u8]) -> Result<usize, SystemError> {
log::warn!("getsockopt is not implemented");
Ok(0)
}
@ -76,42 +71,37 @@ pub trait Socket: Sync + Send + Debug + Any {
// pselect
/// # `read`
fn read(&self, buffer: &mut [u8]) -> Result<usize, SystemError> {
self.recv(buffer, MessageFlag::empty())
self.recv(buffer, PMSG::empty())
}
/// # `recv`
/// 接收数据,`read` = `recv` with flags = 0
fn recv(&self, buffer: &mut [u8], flags: MessageFlag) -> Result<usize, SystemError> {
fn recv(&self, buffer: &mut [u8], flags: PMSG) -> Result<usize, SystemError> {
Err(ENOSYS)
}
/// # `recv_from`
fn recv_from(
&self,
buffer: &mut [u8],
flags: MessageFlag,
flags: PMSG,
address: Option<Endpoint>,
) -> Result<(usize, Endpoint), SystemError> {
Err(ENOSYS)
}
/// # `recv_msg`
fn recv_msg(&self, msg: &mut MsgHdr, flags: MessageFlag) -> Result<usize, SystemError> {
fn recv_msg(&self, msg: &mut MsgHdr, flags: PMSG) -> Result<usize, SystemError> {
Err(ENOSYS)
}
// select
/// # `send`
fn send(&self, buffer: &[u8], flags: MessageFlag) -> Result<usize, SystemError> {
fn send(&self, buffer: &[u8], flags: PMSG) -> Result<usize, SystemError> {
Err(ENOSYS)
}
/// # `send_msg`
fn send_msg(&self, msg: &MsgHdr, flags: MessageFlag) -> Result<usize, SystemError> {
fn send_msg(&self, msg: &MsgHdr, flags: PMSG) -> Result<usize, SystemError> {
Err(ENOSYS)
}
/// # `send_to`
fn send_to(
&self,
buffer: &[u8],
flags: MessageFlag,
address: Endpoint,
) -> Result<usize, SystemError> {
fn send_to(&self, buffer: &[u8], flags: PMSG, address: Endpoint) -> Result<usize, SystemError> {
Err(ENOSYS)
}
/// # `set_option`
@ -122,7 +112,7 @@ pub trait Socket: Sync + Send + Debug + Any {
/// - value 选项的值
/// ## Reference
/// https://code.dragonos.org.cn/s?refs=sk_setsockopt&project=linux-6.6.21
fn set_option(&self, level: OptionsLevel, name: usize, val: &[u8]) -> Result<(), SystemError> {
fn set_option(&self, level: PSOL, name: usize, val: &[u8]) -> Result<(), SystemError> {
log::warn!("setsockopt is not implemented");
Ok(())
}
@ -135,7 +125,7 @@ pub trait Socket: Sync + Send + Debug + Any {
// socketpair
/// # `write`
fn write(&self, buffer: &[u8]) -> Result<usize, SystemError> {
self.send(buffer, MessageFlag::empty())
self.send(buffer, PMSG::empty())
}
// fn write_buffer(&self, _buf: &[u8]) -> Result<usize, SystemError> {
// todo!()

View File

@ -1,6 +1,6 @@
use alloc::vec::Vec;
use alloc::{string::String, sync::Arc};
use alloc::sync::Arc;
use system_error::SystemError;
use crate::libs::spinlock::SpinLock;
@ -75,6 +75,7 @@ impl Buffer {
#[derive(Debug)]
pub struct Metadata {
/// 默认的元数据缓冲区大小
#[allow(dead_code)]
metadata_buf_size: usize,
/// 默认的缓冲区大小
buf_size: usize,

View File

@ -6,10 +6,8 @@ use alloc::{
use system_error::SystemError;
use crate::{
libs::{spinlock::SpinLock, wait_queue::EventWaitQueue},
net::event_poll::{EPollEventType, EPollItem, EventPoll},
process::ProcessManager,
sched::{schedule, SchedMode},
libs::spinlock::SpinLock,
net::event_poll::{EPollItem, EventPoll},
};
#[derive(Debug, Clone)]

View File

@ -1,10 +1,8 @@
// pub mod poll_unit;
mod epoll_items;
pub mod shutdown;
pub mod shutdown;
pub use epoll_items::EPollItems;
#[allow(dead_code)]
pub use shutdown::Shutdown;
// /// @brief 在trait Socket的metadata函数中返回该结构体供外部使用
// #[derive(Debug, Clone)]

View File

@ -1,115 +0,0 @@
// pub const SOL_SOCKET: u8 = 1,
// bitflags::bitflags! {
// pub struct OptionsLevel: u32 {
// const IP = 0,
// // const SOL_ICMP = 1, // No-no-no! Due to Linux :-) we cannot
// const SOCKET = 1,
// const TCP = 6,
// const UDP = 17,
// const IPV6 = 41,
// const ICMPV6 = 58,
// const SCTP = 132,
// const UDPLITE = 136, // UDP-Lite (RFC 3828)
// const RAW = 255,
// const IPX = 256,
// const AX25 = 257,
// const ATALK = 258,
// const NETROM = 259,
// const ROSE = 260,
// const DECNET = 261,
// const X25 = 262,
// const PACKET = 263,
// const ATM = 264, // ATM layer (cell level)
// const AAL = 265, // ATM Adaption Layer (packet level)
// const IRDA = 266,
// const NETBEUI = 267,
// const LLC = 268,
// const DCCP = 269,
// const NETLINK = 270,
// const TIPC = 271,
// const RXRPC = 272,
// const PPPOL2TP = 273,
// const BLUETOOTH = 274,
// const PNPIPE = 275,
// const RDS = 276,
// const IUCV = 277,
// const CAIF = 278,
// const ALG = 279,
// const NFC = 280,
// const KCM = 281,
// const TLS = 282,
// const XDP = 283,
// const MPTCP = 284,
// const MCTP = 285,
// const SMC = 286,
// const VSOCK = 287,
// }
// }
/// # SOL (Socket Option Level)
/// Setsockoptions(2) level. Thanks to BSD these must match IPPROTO_xxx
/// ## Reference
/// - [Setsockoptions(2) level](https://code.dragonos.org.cn/xref/linux-6.6.21/include/linux/socket.h#345)
#[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive, ToPrimitive)]
#[allow(non_camel_case_types)]
pub enum OptionsLevel {
IP = 0,
SOCKET = 1,
// ICMP = 1, No-no-no! Due to Linux :-) we cannot
TCP = 6,
UDP = 17,
IPV6 = 41,
ICMPV6 = 58,
SCTP = 132,
UDPLITE = 136, // UDP-Lite (RFC 3828)
RAW = 255,
IPX = 256,
AX25 = 257,
ATALK = 258,
NETROM = 259,
ROSE = 260,
DECNET = 261,
X25 = 262,
PACKET = 263,
ATM = 264, // ATM layer (cell level)
AAL = 265, // ATM Adaption Layer (packet level)
IRDA = 266,
NETBEUI = 267,
LLC = 268,
DCCP = 269,
NETLINK = 270,
TIPC = 271,
RXRPC = 272,
PPPOL2TP = 273,
BLUETOOTH = 274,
PNPIPE = 275,
RDS = 276,
IUCV = 277,
CAIF = 278,
ALG = 279,
NFC = 280,
KCM = 281,
TLS = 282,
XDP = 283,
MPTCP = 284,
MCTP = 285,
SMC = 286,
VSOCK = 287,
}
impl TryFrom<u32> for OptionsLevel {
type Error = system_error::SystemError;
fn try_from(value: u32) -> Result<Self, Self::Error> {
match <Self as num_traits::FromPrimitive>::from_u32(value) {
Some(p) => Ok(p),
None => Err(system_error::SystemError::EPROTONOSUPPORT),
}
}
}
impl From<OptionsLevel> for u32 {
fn from(value: OptionsLevel) -> Self {
<OptionsLevel as num_traits::ToPrimitive>::to_u32(&value).unwrap()
}
}

View File

@ -1,133 +0,0 @@
// bitflags! {
// // #[derive(PartialEq, Eq, Debug, Clone, Copy)]
// pub struct Options: u32 {
// const DEBUG = 1;
// const REUSEADDR = 2;
// const TYPE = 3;
// const ERROR = 4;
// const DONTROUTE = 5;
// const BROADCAST = 6;
// const SNDBUF = 7;
// const RCVBUF = 8;
// const SNDBUFFORCE = 32;
// const RCVBUFFORCE = 33;
// const KEEPALIVE = 9;
// const OOBINLINE = 10;
// const NO_CHECK = 11;
// const PRIORITY = 12;
// const LINGER = 13;
// const BSDCOMPAT = 14;
// const REUSEPORT = 15;
// const PASSCRED = 16;
// const PEERCRED = 17;
// const RCVLOWAT = 18;
// const SNDLOWAT = 19;
// const RCVTIMEO_OLD = 20;
// const SNDTIMEO_OLD = 21;
//
// const SECURITY_AUTHENTICATION = 22;
// const SECURITY_ENCRYPTION_TRANSPORT = 23;
// const SECURITY_ENCRYPTION_NETWORK = 24;
//
// const BINDTODEVICE = 25;
//
// /// 与GET_FILTER相同
// const ATTACH_FILTER = 26;
// const DETACH_FILTER = 27;
//
// const PEERNAME = 28;
//
// const ACCEPTCONN = 30;
//
// const PEERSEC = 31;
// const PASSSEC = 34;
//
// const MARK = 36;
//
// const PROTOCOL = 38;
// const DOMAIN = 39;
//
// const RXQ_OVFL = 40;
//
// /// 与SCM_WIFI_STATUS相同
// const WIFI_STATUS = 41;
// const PEEK_OFF = 42;
//
// /* Instruct lower device to use last 4-bytes of skb data as FCS */
// const NOFCS = 43;
//
// const LOCK_FILTER = 44;
// const SELECT_ERR_QUEUE = 45;
// const BUSY_POLL = 46;
// const MAX_PACING_RATE = 47;
// const BPF_EXTENSIONS = 48;
// const INCOMING_CPU = 49;
// const ATTACH_BPF = 50;
// // DETACH_BPF = DETACH_FILTER;
// const ATTACH_REUSEPORT_CBPF = 51;
// const ATTACH_REUSEPORT_EBPF = 52;
//
// const CNX_ADVICE = 53;
// const SCM_TIMESTAMPING_OPT_STATS = 54;
// const MEMINFO = 55;
// const INCOMING_NAPI_ID = 56;
// const COOKIE = 57;
// const SCM_TIMESTAMPING_PKTINFO = 58;
// const PEERGROUPS = 59;
// const ZEROCOPY = 60;
// /// 与SCM_TXTIME相同
// const TXTIME = 61;
//
// const BINDTOIFINDEX = 62;
//
// const TIMESTAMP_OLD = 29;
// const TIMESTAMPNS_OLD = 35;
// const TIMESTAMPING_OLD = 37;
// const TIMESTAMP_NEW = 63;
// const TIMESTAMPNS_NEW = 64;
// const TIMESTAMPING_NEW = 65;
//
// const RCVTIMEO_NEW = 66;
// const SNDTIMEO_NEW = 67;
//
// const DETACH_REUSEPORT_BPF = 68;
//
// const PREFER_BUSY_POLL = 69;
// const BUSY_POLL_BUDGET = 70;
//
// const NETNS_COOKIE = 71;
// const BUF_LOCK = 72;
// const RESERVE_MEM = 73;
// const TXREHASH = 74;
// const RCVMARK = 75;
// }
// }
// bitflags::bitflags! {
// pub struct Level: i32 {
// const SOL_SOCKET = 1;
// const IPPROTO_IP = super::ip::Protocol::IP.bits();
// const IPPROTO_IPV6 = super::ip::Protocol::IPv6.bits();
// const IPPROTO_TCP = super::ip::Protocol::TCP.bits();
// }
// }
// bitflags! {
// /// @brief socket的选项
// #[derive(Default)]
// pub struct Options: u32 {
// /// 是否阻塞
// const BLOCK = 1 << 0;
// /// 是否允许广播
// const BROADCAST = 1 << 1;
// /// 是否允许多播
// const MULTICAST = 1 << 2;
// /// 是否允许重用地址
// const REUSEADDR = 1 << 3;
// /// 是否允许重用端口
// const REUSEPORT = 1 << 4;
// }
// }

View File

@ -117,5 +117,5 @@ use crate::net::socket;
use alloc::sync::Arc;
pub trait Family {
fn socket(stype: socket::Type, protocol: u32) -> Result<Arc<socket::Inode>, SystemError>;
fn socket(stype: socket::PSOCK, protocol: u32) -> Result<Arc<socket::Inode>, SystemError>;
}

View File

@ -5,6 +5,7 @@ use system_error::SystemError::{self, *};
pub mod port;
pub use port::PortManager;
#[allow(dead_code)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Types {
Raw,

View File

@ -2,9 +2,7 @@ use inet::InetSocket;
use smoltcp;
use system_error::SystemError::{self, *};
use crate::filesystem::vfs::IndexNode;
use crate::libs::rwlock::RwLock;
use crate::libs::spinlock::SpinLock;
use crate::net::event_poll::EPollEventType;
use crate::net::net_core::poll_ifaces;
use crate::net::socket::*;
@ -209,46 +207,30 @@ impl Socket for UdpSocket {
return Err(EAFNOSUPPORT);
}
fn send(&self, buffer: &[u8], flags: MessageFlag) -> Result<usize, SystemError> {
// if flags.contains(MessageFlag::DONTWAIT) {
fn send(&self, buffer: &[u8], flags: PMSG) -> Result<usize, SystemError> {
if flags.contains(PMSG::DONTWAIT) {
log::warn!("Nonblock send is not implemented yet");
}
return self.try_send(buffer, None);
// } else {
// // return self
// // .wait_queue
// // .busy_wait(EP::EPOLLOUT, || self.try_send(buffer, None));
// todo!()
// }
}
fn send_to(
&self,
buffer: &[u8],
flags: MessageFlag,
address: Endpoint,
) -> Result<usize, SystemError> {
// if flags.contains(MessageFlag::DONTWAIT) {
fn send_to(&self, buffer: &[u8], flags: PMSG, address: Endpoint) -> Result<usize, SystemError> {
if flags.contains(PMSG::DONTWAIT) {
log::warn!("Nonblock send is not implemented yet");
}
if let Endpoint::Ip(remote) = address {
return self.try_send(buffer, Some(remote));
}
// } else {
// // return self
// // .wait_queue
// // .busy_wait(EP::EPOLLOUT, || {
// // if let Endpoint::Ip(remote) = address {
// // return self.try_send(buffer, Some(remote.addr));
// // }
// // return Err(EAFNOSUPPORT);
// // });
// todo!()
// }
return Err(EINVAL);
}
fn recv(&self, buffer: &mut [u8], flags: MessageFlag) -> Result<usize, SystemError> {
fn recv(&self, buffer: &mut [u8], flags: PMSG) -> Result<usize, SystemError> {
use crate::sched::SchedMode;
return if self.is_nonblock() || flags.contains(MessageFlag::DONTWAIT) {
return if self.is_nonblock() || flags.contains(PMSG::DONTWAIT) {
self.try_recv(buffer)
} else {
loop {
@ -266,7 +248,7 @@ impl Socket for UdpSocket {
fn recv_from(
&self,
buffer: &mut [u8],
flags: MessageFlag,
flags: PMSG,
address: Option<Endpoint>,
) -> Result<(usize, Endpoint), SystemError> {
use crate::sched::SchedMode;
@ -275,7 +257,7 @@ impl Socket for UdpSocket {
self.connect(endpoint)?;
}
return if self.is_nonblock() || flags.contains(MessageFlag::DONTWAIT) {
return if self.is_nonblock() || flags.contains(PMSG::DONTWAIT) {
self.try_recv(buffer)
} else {
loop {

View File

@ -1,6 +1,4 @@
use alloc::sync::Arc;
use smoltcp;
use system_error::SystemError::{self, *};
// pub mod raw;
// pub mod icmp;
@ -16,8 +14,6 @@ pub use datagram::UdpSocket;
pub use stream::TcpSocket;
pub use syscall::Inet;
use crate::filesystem::vfs::IndexNode;
use super::Socket;
use smoltcp::wire::*;
@ -85,66 +81,3 @@ pub trait InetSocket: Socket {
// todo!()
// }
// }
// pub trait Socket: FileLike + Send + Sync {
// /// Assign the address specified by socket_addr to the socket
// fn bind(&self, _socket_addr: SocketAddr) -> Result<()> {
// return_errno_with_message!(Errno::EOPNOTSUPP, "bind() is not supported");
// }
// /// Build connection for a given address
// fn connect(&self, _socket_addr: SocketAddr) -> Result<()> {
// return_errno_with_message!(Errno::EOPNOTSUPP, "connect() is not supported");
// }
// /// Listen for connections on a socket
// fn listen(&self, _backlog: usize) -> Result<()> {
// return_errno_with_message!(Errno::EOPNOTSUPP, "listen() is not supported");
// }
// /// Accept a connection on a socket
// fn accept(&self) -> Result<(Arc<dyn FileLike>, SocketAddr)> {
// return_errno_with_message!(Errno::EOPNOTSUPP, "accept() is not supported");
// }
// /// Shut down part of a full-duplex connection
// fn shutdown(&self, _cmd: SockShutdownCmd) -> Result<()> {
// return_errno_with_message!(Errno::EOPNOTSUPP, "shutdown() is not supported");
// }
// /// Get address of this socket.
// fn addr(&self) -> Result<SocketAddr> {
// return_errno_with_message!(Errno::EOPNOTSUPP, "getsockname() is not supported");
// }
// /// Get address of peer socket
// fn peer_addr(&self) -> Result<SocketAddr> {
// return_errno_with_message!(Errno::EOPNOTSUPP, "getpeername() is not supported");
// }
// /// Get options on the socket. The resulted option will put in the `option` parameter, if
// /// this method returns success.
// fn get_option(&self, _option: &mut dyn SocketOption) -> Result<()> {
// return_errno_with_message!(Errno::EOPNOTSUPP, "getsockopt() is not supported");
// }
// /// Set options on the socket.
// fn set_option(&self, _option: &dyn SocketOption) -> Result<()> {
// return_errno_with_message!(Errno::EOPNOTSUPP, "setsockopt() is not supported");
// }
// /// Sends a message on a socket.
// fn sendmsg(
// &self,
// io_vecs: &[IoVec],
// message_header: MessageHeader,
// flags: SendRecvFlags,
// ) -> Result<usize>;
// /// Receives a message from a socket.
// ///
// /// If successful, the `io_vecs` buffer will be filled with the received content.
// /// This method returns the length of the received message,
// /// and the message header.
// fn recvmsg(&self, io_vecs: &[IoVec], flags: SendRecvFlags) -> Result<(usize, MessageHeader)>;
// }

View File

@ -1,4 +1,4 @@
const SOL_SOCKET: u16 = 1;
pub const SOL_SOCKET: u16 = 1;
#[derive(Debug, Clone, Copy, FromPrimitive, ToPrimitive, PartialEq, Eq)]
pub enum IPProtocol {

View File

@ -1,4 +1,4 @@
use core::sync::atomic::{AtomicU32, AtomicUsize};
use core::sync::atomic::AtomicUsize;
use crate::libs::rwlock::RwLock;
use crate::net::socket::EPollEventType;
@ -10,7 +10,7 @@ use system_error::SystemError::{self, *};
use super::inet::UNSPECIFIED_LOCAL_ENDPOINT;
pub const DEFAULT_METADATA_BUF_SIZE: usize = 1024;
// pub const DEFAULT_METADATA_BUF_SIZE: usize = 1024;
pub const DEFAULT_RX_BUF_SIZE: usize = 512 * 1024;
pub const DEFAULT_TX_BUF_SIZE: usize = 512 * 1024;

View File

@ -10,16 +10,19 @@ use crate::sched::SchedMode;
use inet::{InetSocket, UNSPECIFIED_LOCAL_ENDPOINT};
use smoltcp;
pub mod inner;
mod inner;
use inner::*;
mod option;
pub use option::Options as TcpOption;
type EP = EPollEventType;
#[derive(Debug)]
pub struct TcpSocket {
inner: RwLock<Option<Inner>>,
shutdown: Shutdown,
#[allow(dead_code)]
shutdown: Shutdown, // TODO set shutdown status
nonblock: AtomicBool,
epitems: EPollItems,
wait_queue: WaitQueue,
self_ref: Weak<Self>,
pollee: AtomicUsize,
@ -31,7 +34,6 @@ impl TcpSocket {
inner: RwLock::new(Some(Inner::Init(Init::new()))),
shutdown: Shutdown::new(),
nonblock: AtomicBool::new(nonblock),
epitems: EPollItems::default(),
wait_queue: WaitQueue::default(),
self_ref: me.clone(),
pollee: AtomicUsize::new((EP::EPOLLIN.bits() | EP::EPOLLOUT.bits()) as usize),
@ -43,7 +45,6 @@ impl TcpSocket {
inner: RwLock::new(Some(Inner::Established(inner))),
shutdown: Shutdown::new(),
nonblock: AtomicBool::new(nonblock),
epitems: EPollItems::default(),
wait_queue: WaitQueue::default(),
self_ref: me.clone(),
pollee: AtomicUsize::new((EP::EPOLLIN.bits() | EP::EPOLLOUT.bits()) as usize),
@ -54,18 +55,6 @@ impl TcpSocket {
self.nonblock.load(core::sync::atomic::Ordering::Relaxed)
}
#[inline]
fn write_state<F>(&self, mut f: F) -> Result<(), SystemError>
where
F: FnMut(Inner) -> Result<Inner, SystemError>,
{
let mut inner_guard = self.inner.write();
let inner = inner_guard.take().expect("Tcp Inner is None");
let update = f(inner)?;
inner_guard.replace(update);
Ok(())
}
pub fn do_bind(&self, local_endpoint: smoltcp::wire::IpEndpoint) -> Result<(), SystemError> {
let mut writer = self.inner.write();
match writer.take().expect("Tcp Inner is None") {
@ -289,11 +278,11 @@ impl Socket for TcpSocket {
.map(|(inner, endpoint)| (Inode::new(inner), Endpoint::Ip(endpoint)))
}
fn recv(&self, buffer: &mut [u8], _flags: MessageFlag) -> Result<usize, SystemError> {
fn recv(&self, buffer: &mut [u8], _flags: PMSG) -> Result<usize, SystemError> {
self.try_recv(buffer)
}
fn send(&self, buffer: &[u8], _flags: MessageFlag) -> Result<usize, SystemError> {
fn send(&self, buffer: &[u8], _flags: PMSG) -> Result<usize, SystemError> {
self.try_send(buffer)
}
@ -314,181 +303,27 @@ impl Socket for TcpSocket {
}
fn close(&self) -> Result<(), SystemError> {
match self.inner.read().as_ref().expect("Tcp Inner is None") {
Inner::Init(_) => {}
Inner::Connecting(_) => {
return Err(EINPROGRESS);
}
Inner::Established(es) => {
es.close();
es.release();
}
Inner::Listening(_) => {}
}
Ok(())
self.inner
.read()
.as_ref()
.map(|inner| match inner {
Inner::Connecting(_) => Err(EINPROGRESS),
Inner::Established(es) => {
es.close();
es.release();
Ok(())
}
_ => Ok(()),
})
.unwrap_or(Ok(()))
}
}
impl InetSocket for TcpSocket {
fn on_iface_events(&self) {
if self.update_events() {
let result = self.finish_connect();
let _result = self.finish_connect();
// set error
}
}
}
// #[derive(Debug)]
// // #[cast_to([sync] IndexNode)]
// struct TcpStream {
// inner: Established,
// shutdown: Shutdown,
// nonblock: AtomicBool,
// epitems: EPollItems,
// wait_queue: WaitQueue,
// self_ref: Weak<Self>,
// }
// impl TcpStream {
// pub fn is_nonblock(&self) -> bool {
// self.nonblock.load(core::sync::atomic::Ordering::Relaxed)
// }
// pub fn read(&self, buf: &mut [u8]) -> Result<usize, SystemError> {
// if self.nonblock.load(core::sync::atomic::Ordering::Relaxed) {
// return self.recv_slice(buf);
// } else {
// return self.wait_queue().busy_wait(
// EP::EPOLLIN,
// || self.recv_slice(buf)
// )
// }
// }
// pub fn recv_slice(&self, buf: &mut [u8]) -> Result<usize, SystemError> {
// let received = self.inner.recv_slice(buf);
// poll_ifaces();
// received
// }
// pub fn send_slice(&self, buf: &[u8]) -> Result<usize, SystemError> {
// let sent = self.inner.send_slice(buf);
// poll_ifaces();
// sent
// }
// }
// use crate::net::socket::{Inode, Socket};
// use crate::filesystem::vfs::IndexNode;
// impl IndexNode for TcpStream {
// fn read_at(
// &self,
// _offset: usize,
// _len: usize,
// buf: &mut [u8],
// data: crate::libs::spinlock::SpinLockGuard<crate::filesystem::vfs::FilePrivateData>,
// ) -> Result<usize, SystemError> {
// drop(data);
// self.read(buf)
// }
// fn write_at(
// &self,
// _offset: usize,
// _len: usize,
// buf: &[u8],
// data: crate::libs::spinlock::SpinLockGuard<crate::filesystem::vfs::FilePrivateData>,
// ) -> Result<usize, SystemError> {
// drop(data);
// self.send_slice(buf)
// }
// fn fs(&self) -> alloc::sync::Arc<dyn crate::filesystem::vfs::FileSystem> {
// todo!("TcpSocket::fs")
// }
// fn as_any_ref(&self) -> &dyn core::any::Any {
// self
// }
// fn list(&self) -> Result<alloc::vec::Vec<alloc::string::String>, SystemError> {
// todo!("TcpSocket::list")
// }
// }
// impl Socket for TcpStream {
// fn wait_queue(&self) -> WaitQueue {
// self.wait_queue.clone()
// }
// fn poll(&self) -> usize {
// // self.inner.with(|socket| {
// // let mut mask = EPollEventType::empty();
// // let shutdown = self.shutdown.get();
// // let state = socket.state();
// // use smoltcp::socket::tcp::State::*;
// // type EP = crate::net::event_poll::EPollEventType;
// // if shutdown.is_both_shutdown() || state == Closed {
// // mask |= EP::EPOLLHUP;
// // }
// // if shutdown.is_recv_shutdown() {
// // mask |= EP::EPOLLIN | EP::EPOLLRDNORM | EP::EPOLLRDHUP;
// // }
// // if state != SynSent && state != SynReceived {
// // if socket.can_recv() {
// // mask |= EP::EPOLLIN | EP::EPOLLRDNORM;
// // }
// // if !shutdown.is_send_shutdown() {
// // // __sk_stream_is_writeable这是一个内联函数用于判断一个TCP套接字是否可写。
// // //
// // // 以下是函数的逐行解释:
// // // static inline bool __sk_stream_is_writeable(const struct sock *sk, int wake)
// // // - 这行定义了函数__sk_stream_is_writeable它是一个内联函数static inline
// // // 这意味着在调用点直接展开代码,而不是调用函数体。函数接收两个参数:
// // // 一个指向struct sock对象的指针sk代表套接字和一个整型变量wake。
// // //
// // // return sk_stream_wspace(sk) >= sk_stream_min_wspace(sk) &&
// // // - 这行代码调用了sk_stream_wspace函数获取套接字sk的可写空间write space大小。
// // // 随后与sk_stream_min_wspace调用结果进行比较该函数返回套接字为了保持稳定写入速度所需的
// // // 最小可写空间。如果当前可写空间大于或等于最小可写空间,则表达式为真。
// // // __sk_stream_memory_free(sk, wake);
// // // - 这行代码调用了__sk_stream_memory_free函数它可能用于检查套接字的内存缓冲区是否
// // // 有足够的空间可供写入数据。参数wake可能用于通知网络协议栈有数据需要发送如果设置了相应的标志。
// // // 综上所述__sk_stream_is_writeable函数的目的是判断一个TCP套接字是否可以安全地进行写操作
// // // 它基于套接字的当前可写空间和所需的最小空间以及内存缓冲区的可用性。只有当这两个条件都满足时,
// // // 函数才会返回true表示套接字是可写的。
// // if socket.can_send() {
// // mask |= EP::EPOLLOUT | EP::EPOLLWRNORM | EP::EPOLLWRBAND;
// // } else {
// // todo!("TcpStream::poll: buffer space not enough");
// // }
// // } else {
// // mask |= EP::EPOLLOUT | EP::EPOLLWRNORM;
// // }
// // // TODO tcp urg data => EPOLLPRI
// // } else if state == SynSent /* inet_test_bit */ {
// // log::warn!("Active TCP fastopen socket with defer_connect");
// // mask |= EP::EPOLLOUT | EP::EPOLLWRNORM;
// // }
// // // TODO socket error
// // return Ok(mask);
// // })
// self.pollee.load(core::sync::atomic::Ordering::Relaxed)
// }
// fn send_buffer_size(&self) -> usize {
// self.inner.with(|socket| socket.send_capacity())
// }
// fn recv_buffer_size(&self) -> usize {
// self.inner.with(|socket| socket.recv_capacity())
// }
// }

View File

@ -0,0 +1,91 @@
use num_traits::{FromPrimitive, ToPrimitive};
#[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive, ToPrimitive)]
pub enum Options {
/// Turn off Nagle's algorithm.
NoDelay = 1,
/// Limit MSS.
MaxSegment = 2,
/// Never send partially complete segments.
Cork = 3,
/// Start keeplives after this period.
KeepIdle = 4,
/// Interval between keepalives.
KeepIntvl = 5,
/// Number of keepalives before death.
KeepCnt = 6,
/// Number of SYN retransmits.
Syncnt = 7,
/// Lifetime for orphaned FIN-WAIT-2 state.
Linger2 = 8,
/// Wake up listener only when data arrive.
DeferAccept = 9,
/// Bound advertised window
WindowClamp = 10,
/// Information about this connection.
Info = 11,
/// Block/reenable quick acks.
QuickAck = 12,
/// Congestion control algorithm.
Congestion = 13,
/// TCP MD5 Signature (RFC2385).
Md5Sig = 14,
/// Use linear timeouts for thin streams
ThinLinearTimeouts = 16,
/// Fast retrans. after 1 dupack.
ThinDupack = 17,
/// How long for loss retry before timeout.
UserTimeout = 18,
/// TCP sock is under repair right now.
Repair = 19,
RepairQueue = 20,
QueueSeq = 21,
#[allow(clippy::enum_variant_names)]
RepairOptions = 22,
/// Enable FastOpen on listeners
FastOpen = 23,
Timestamp = 24,
/// Limit number of unsent bytes in write queue.
NotSentLowat = 25,
/// Get Congestion Control (optional) info.
CCInfo = 26,
/// Record SYN headers for new connections.
SaveSyn = 27,
/// Get SYN headers recorded for connection.
SavedSyn = 28,
/// Get/set window parameters.
RepairWindow = 29,
/// Attempt FastOpen with connect.
FastOpenConnect = 30,
/// Attach a ULP to a TCP connection.
ULP = 31,
/// TCP MD5 Signature with extensions.
Md5SigExt = 32,
/// Set the key for Fast Open(cookie).
FastOpenKey = 33,
/// Enable TFO without a TFO cookie.
FastOpenNoCookie = 34,
ZeroCopyReceive = 35,
/// Notify bytes available to read as a cmsg on read.
/// 与TCP_CM_INQ相同
INQ = 36,
/// delay outgoing packets by XX usec
TxDelay = 37,
}
impl TryFrom<i32> for Options {
type Error = system_error::SystemError;
fn try_from(value: i32) -> Result<Self, Self::Error> {
match <Self as FromPrimitive>::from_i32(value) {
Some(p) => Ok(p),
None => Err(Self::Error::EINVAL),
}
}
}
impl From<Options> for i32 {
fn from(val: Options) -> Self {
<Options as ToPrimitive>::to_i32(&val).unwrap()
}
}

View File

@ -8,14 +8,13 @@ use inet::{TcpSocket, UdpSocket};
use crate::net::socket::*;
fn create_inet_socket(
socket_type: Type,
socket_type: PSOCK,
protocol: smoltcp::wire::IpProtocol,
) -> Result<Arc<dyn Socket>, SystemError> {
// log::debug!("type: {:?}, protocol: {:?}", socket_type, protocol);
use smoltcp::wire::IpProtocol::*;
use Type::*;
match socket_type {
Datagram => {
PSOCK::Datagram => {
match protocol {
HopByHop | Udp => {
return Ok(UdpSocket::new(false));
@ -29,7 +28,7 @@ fn create_inet_socket(
// }
// return Ok(UdpSocket::new(false));
}
Stream => match protocol {
PSOCK::Stream => match protocol {
HopByHop | Tcp => {
return Ok(TcpSocket::new(false));
}
@ -37,7 +36,7 @@ fn create_inet_socket(
return Err(EPROTONOSUPPORT);
}
},
Raw => {
PSOCK::Raw => {
todo!("raw")
}
_ => {
@ -48,7 +47,7 @@ fn create_inet_socket(
pub struct Inet;
impl family::Family for Inet {
fn socket(stype: Type, protocol: u32) -> Result<Arc<Inode>, SystemError> {
fn socket(stype: PSOCK, protocol: u32) -> Result<Arc<Inode>, SystemError> {
let socket = create_inet_socket(stype, smoltcp::wire::IpProtocol::from(protocol as u8))?;
Ok(Inode::new(socket))
}

View File

@ -47,11 +47,7 @@ impl IndexNode for Inode {
unimplemented!()
}
fn poll(
&self,
private_data: &crate::filesystem::vfs::FilePrivateData,
) -> Result<usize, SystemError> {
// let _ = private_data;
fn poll(&self, _: &crate::filesystem::vfs::FilePrivateData) -> Result<usize, SystemError> {
Ok(self.inner.poll())
}
@ -103,18 +99,13 @@ impl Inode {
self.inner.bind(endpoint)
}
pub fn set_option(
&self,
level: OptionsLevel,
name: usize,
value: &[u8],
) -> Result<(), SystemError> {
pub fn set_option(&self, level: PSOL, name: usize, value: &[u8]) -> Result<(), SystemError> {
self.inner.set_option(level, name, value)
}
pub fn get_option(
&self,
level: OptionsLevel,
level: PSOL,
name: usize,
value: &mut [u8],
) -> Result<usize, SystemError> {
@ -129,16 +120,16 @@ impl Inode {
&self,
buffer: &[u8],
address: Endpoint,
flags: MessageFlag,
flags: PMSG,
) -> Result<usize, SystemError> {
self.inner.send_to(buffer, flags, address)
}
pub fn send(&self, buffer: &[u8], flags: MessageFlag) -> Result<usize, SystemError> {
pub fn send(&self, buffer: &[u8], flags: PMSG) -> Result<usize, SystemError> {
self.inner.send(buffer, flags)
}
pub fn recv(&self, buffer: &mut [u8], flags: MessageFlag) -> Result<usize, SystemError> {
pub fn recv(&self, buffer: &mut [u8], flags: PMSG) -> Result<usize, SystemError> {
self.inner.recv(buffer, flags)
}
@ -146,7 +137,7 @@ impl Inode {
pub fn recv_from(
&self,
buffer: &mut [u8],
flags: MessageFlag,
flags: PMSG,
address: Option<Endpoint>,
) -> Result<(usize, Endpoint), SystemError> {
self.inner.recv_from(buffer, flags, address)
@ -181,11 +172,11 @@ impl Inode {
self.epoll_items.clone()
}
pub fn set_nonblock(&self, nonblock: bool) {
pub fn set_nonblock(&self, _nonblock: bool) {
log::warn!("nonblock is not support yet");
}
pub fn set_close_on_exec(&self, close_on_exec: bool) {
pub fn set_close_on_exec(&self, _close_on_exec: bool) {
log::warn!("close_on_exec is not support yet");
}

View File

@ -1,26 +1,26 @@
mod base;
mod buffer;
mod common;
mod define;
mod endpoint;
mod family;
pub mod inet;
mod inode;
mod posix;
pub mod unix;
mod utils;
use crate::libs::wait_queue::WaitQueue;
pub use base::Socket;
use buffer::Buffer;
pub use common::{
shutdown::*,
// poll_unit::{EPollItems, WaitQueue},
EPollItems,
};
pub use define::*;
pub use endpoint::*;
pub use family::{AddressFamily, Family};
pub use inode::Inode;
pub use posix::*;
pub use utils::create_socket;
pub use crate::net::event_poll::EPollEventType;

View File

@ -0,0 +1,12 @@
// posix socket and arguments definitions
// now all posix definitions are with P front like MSG -> PMSG,
// for better understanding and avoiding conflicts with other definitions
mod msg_flag;
mod option;
mod option_level;
mod types;
pub use msg_flag::MessageFlag as PMSG; // Socket message flags MSG_*
pub use option::Options as PSO; // Socket options SO_*
pub use option_level::OptionLevel as PSOL; // Socket options level SOL_*
pub use types::Type as PSOCK; // Socket types SOCK_*

View File

@ -0,0 +1,67 @@
/// # SOL (Socket Option Level)
/// Setsockoptions(2) level. Thanks to BSD these must match IPPROTO_xxx
/// ## Reference
/// - [Setsockoptions(2) level](https://code.dragonos.org.cn/xref/linux-6.6.21/include/linux/socket.h#345)
#[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive, ToPrimitive)]
#[allow(non_camel_case_types)]
pub enum OptionLevel {
IP = 0,
SOCKET = 1,
// ICMP = 1, No-no-no! Due to Linux :-) we cannot
TCP = 6,
UDP = 17,
IPV6 = 41,
ICMPV6 = 58,
SCTP = 132,
UDPLITE = 136, // UDP-Lite (RFC 3828)
RAW = 255,
IPX = 256,
AX25 = 257,
ATALK = 258,
NETROM = 259,
ROSE = 260,
DECNET = 261,
X25 = 262,
PACKET = 263,
ATM = 264, // ATM layer (cell level)
AAL = 265, // ATM Adaption Layer (packet level)
IRDA = 266,
NETBEUI = 267,
LLC = 268,
DCCP = 269,
NETLINK = 270,
TIPC = 271,
RXRPC = 272,
PPPOL2TP = 273,
BLUETOOTH = 274,
PNPIPE = 275,
RDS = 276,
IUCV = 277,
CAIF = 278,
ALG = 279,
NFC = 280,
KCM = 281,
TLS = 282,
XDP = 283,
MPTCP = 284,
MCTP = 285,
SMC = 286,
VSOCK = 287,
}
impl TryFrom<u32> for OptionLevel {
type Error = system_error::SystemError;
fn try_from(value: u32) -> Result<Self, Self::Error> {
match <Self as num_traits::FromPrimitive>::from_u32(value) {
Some(p) => Ok(p),
None => Err(system_error::SystemError::EPROTONOSUPPORT),
}
}
}
impl From<OptionLevel> for u32 {
fn from(value: OptionLevel) -> Self {
<OptionLevel as num_traits::ToPrimitive>::to_u32(&value).unwrap()
}
}

View File

@ -1,15 +1,3 @@
mod option;
pub use option::Options;
mod option_level;
pub use option_level::OptionsLevel;
mod msg_flag;
pub use msg_flag::MessageFlag;
mod ipproto;
pub use ipproto::IPProtocol;
#[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive, ToPrimitive)]
pub enum Type {
Stream = 1,
@ -21,10 +9,10 @@ pub enum Type {
Packet = 10,
}
use crate::net::syscall_util::SysArgSocketType;
impl TryFrom<SysArgSocketType> for Type {
use crate::net::syscall_util::PosixArgsSocketType;
impl TryFrom<PosixArgsSocketType> for Type {
type Error = system_error::SystemError;
fn try_from(x: SysArgSocketType) -> Result<Self, Self::Error> {
fn try_from(x: PosixArgsSocketType) -> Result<Self, Self::Error> {
use num_traits::FromPrimitive;
return <Self as FromPrimitive>::from_u32(x.types().bits())
.ok_or(system_error::SystemError::EINVAL);

View File

@ -10,27 +10,27 @@ lazy_static! {
pub static ref INODE_MAP: RwLock<HashMap<InodeId, Endpoint>> = RwLock::new(HashMap::new());
}
fn create_unix_socket(sock_type: Type) -> Result<Arc<Inode>, SystemError> {
fn create_unix_socket(sock_type: PSOCK) -> Result<Arc<Inode>, SystemError> {
match sock_type {
Type::Stream | Type::Datagram => stream::StreamSocket::new_inode(),
Type::SeqPacket => seqpacket::SeqpacketSocket::new_inode(false),
PSOCK::Stream | PSOCK::Datagram => stream::StreamSocket::new_inode(),
PSOCK::SeqPacket => seqpacket::SeqpacketSocket::new_inode(false),
_ => Err(EPROTONOSUPPORT),
}
}
impl family::Family for Unix {
fn socket(stype: Type, _protocol: u32) -> Result<Arc<Inode>, SystemError> {
fn socket(stype: PSOCK, _protocol: u32) -> Result<Arc<Inode>, SystemError> {
let socket = create_unix_socket(stype)?;
Ok(socket)
}
}
impl Unix {
pub fn new_pairs(socket_type: Type) -> Result<(Arc<Inode>, Arc<Inode>), SystemError> {
pub fn new_pairs(socket_type: PSOCK) -> Result<(Arc<Inode>, Arc<Inode>), SystemError> {
// log::debug!("socket_type {:?}", socket_type);
match socket_type {
Type::SeqPacket => seqpacket::SeqpacketSocket::new_pairs(),
Type::Stream | Type::Datagram => stream::StreamSocket::new_pairs(),
PSOCK::SeqPacket => seqpacket::SeqpacketSocket::new_pairs(),
PSOCK::Stream | PSOCK::Datagram => stream::StreamSocket::new_pairs(),
_ => todo!(),
}
}

View File

@ -118,6 +118,7 @@ impl SeqpacketSocket {
self.is_nonblocking.load(Ordering::Relaxed)
}
#[allow(dead_code)]
fn set_nonblocking(&self, nonblocking: bool) {
self.is_nonblocking.store(nonblocking, Ordering::Relaxed);
}
@ -243,7 +244,7 @@ impl Socket for SeqpacketSocket {
fn set_option(
&self,
_level: crate::net::socket::OptionsLevel,
_level: crate::net::socket::PSOL,
_optname: usize,
_optval: &[u8],
) -> Result<(), SystemError> {
@ -293,7 +294,7 @@ impl Socket for SeqpacketSocket {
fn get_option(
&self,
_level: crate::net::socket::OptionsLevel,
_level: crate::net::socket::PSOL,
_name: usize,
_value: &mut [u8],
) -> Result<usize, SystemError> {
@ -302,18 +303,18 @@ impl Socket for SeqpacketSocket {
}
fn read(&self, buffer: &mut [u8]) -> Result<usize, SystemError> {
self.recv(buffer, crate::net::socket::MessageFlag::empty())
self.recv(buffer, crate::net::socket::PMSG::empty())
}
fn recv(
&self,
buffer: &mut [u8],
flags: crate::net::socket::MessageFlag,
flags: crate::net::socket::PMSG,
) -> Result<usize, SystemError> {
if flags.contains(MessageFlag::OOB) {
if flags.contains(PMSG::OOB) {
return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
}
if !flags.contains(MessageFlag::DONTWAIT) {
if !flags.contains(PMSG::DONTWAIT) {
loop {
wq_wait_event_interruptible!(
self.wait_queue,
@ -343,23 +344,19 @@ impl Socket for SeqpacketSocket {
fn recv_msg(
&self,
_msg: &mut crate::net::syscall::MsgHdr,
_flags: crate::net::socket::MessageFlag,
_flags: crate::net::socket::PMSG,
) -> Result<usize, SystemError> {
Err(SystemError::ENOSYS)
}
fn send(
&self,
buffer: &[u8],
flags: crate::net::socket::MessageFlag,
) -> Result<usize, SystemError> {
if flags.contains(MessageFlag::OOB) {
fn send(&self, buffer: &[u8], flags: crate::net::socket::PMSG) -> Result<usize, SystemError> {
if flags.contains(PMSG::OOB) {
return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
}
if self.is_peer_shutdown()? {
return Err(SystemError::EPIPE);
}
if !flags.contains(MessageFlag::DONTWAIT) {
if !flags.contains(PMSG::DONTWAIT) {
loop {
match &*self.inner.write() {
Inner::Connected(connected) => match connected.try_write(buffer) {
@ -383,26 +380,26 @@ impl Socket for SeqpacketSocket {
fn send_msg(
&self,
_msg: &crate::net::syscall::MsgHdr,
_flags: crate::net::socket::MessageFlag,
_flags: crate::net::socket::PMSG,
) -> Result<usize, SystemError> {
Err(SystemError::ENOSYS)
}
fn write(&self, buffer: &[u8]) -> Result<usize, SystemError> {
self.send(buffer, crate::net::socket::MessageFlag::empty())
self.send(buffer, crate::net::socket::PMSG::empty())
}
fn recv_from(
&self,
buffer: &mut [u8],
flags: MessageFlag,
flags: PMSG,
_address: Option<Endpoint>,
) -> Result<(usize, Endpoint), SystemError> {
// log::debug!("recvfrom flags {:?}", flags);
if flags.contains(MessageFlag::OOB) {
if flags.contains(PMSG::OOB) {
return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
}
if !flags.contains(MessageFlag::DONTWAIT) {
if !flags.contains(PMSG::DONTWAIT) {
loop {
wq_wait_event_interruptible!(
self.wait_queue,

View File

@ -241,12 +241,7 @@ impl Socket for StreamSocket {
}
}
fn set_option(
&self,
_level: OptionsLevel,
_optname: usize,
_optval: &[u8],
) -> Result<(), SystemError> {
fn set_option(&self, _level: PSOL, _optname: usize, _optval: &[u8]) -> Result<(), SystemError> {
log::warn!("setsockopt is not implemented");
Ok(())
}
@ -329,7 +324,7 @@ impl Socket for StreamSocket {
fn get_option(
&self,
_level: OptionsLevel,
_level: PSOL,
_name: usize,
_value: &mut [u8],
) -> Result<usize, SystemError> {
@ -338,11 +333,11 @@ impl Socket for StreamSocket {
}
fn read(&self, buffer: &mut [u8]) -> Result<usize, SystemError> {
self.recv(buffer, socket::MessageFlag::empty())
self.recv(buffer, socket::PMSG::empty())
}
fn recv(&self, buffer: &mut [u8], flags: socket::MessageFlag) -> Result<usize, SystemError> {
if !flags.contains(MessageFlag::DONTWAIT) {
fn recv(&self, buffer: &mut [u8], flags: socket::PMSG) -> Result<usize, SystemError> {
if !flags.contains(PMSG::DONTWAIT) {
loop {
log::debug!("socket try recv");
wq_wait_event_interruptible!(
@ -373,13 +368,13 @@ impl Socket for StreamSocket {
fn recv_from(
&self,
buffer: &mut [u8],
flags: socket::MessageFlag,
flags: socket::PMSG,
_address: Option<Endpoint>,
) -> Result<(usize, Endpoint), SystemError> {
if flags.contains(MessageFlag::OOB) {
if flags.contains(PMSG::OOB) {
return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
}
if !flags.contains(MessageFlag::DONTWAIT) {
if !flags.contains(PMSG::DONTWAIT) {
loop {
log::debug!("socket try recv from");
@ -413,16 +408,16 @@ impl Socket for StreamSocket {
fn recv_msg(
&self,
_msg: &mut crate::net::syscall::MsgHdr,
_flags: socket::MessageFlag,
_flags: socket::PMSG,
) -> Result<usize, SystemError> {
Err(SystemError::ENOSYS)
}
fn send(&self, buffer: &[u8], flags: socket::MessageFlag) -> Result<usize, SystemError> {
fn send(&self, buffer: &[u8], flags: socket::PMSG) -> Result<usize, SystemError> {
if self.is_peer_shutdown()? {
return Err(SystemError::EPIPE);
}
if !flags.contains(MessageFlag::DONTWAIT) {
if !flags.contains(PMSG::DONTWAIT) {
loop {
match &*self.inner.write() {
Inner::Connected(connected) => match connected.try_send(buffer) {
@ -446,7 +441,7 @@ impl Socket for StreamSocket {
fn send_msg(
&self,
_msg: &crate::net::syscall::MsgHdr,
_flags: socket::MessageFlag,
_flags: socket::PMSG,
) -> Result<usize, SystemError> {
todo!()
}
@ -454,14 +449,14 @@ impl Socket for StreamSocket {
fn send_to(
&self,
_buffer: &[u8],
_flags: socket::MessageFlag,
_flags: socket::PMSG,
_address: Endpoint,
) -> Result<usize, SystemError> {
Err(SystemError::ENOSYS)
}
fn write(&self, buffer: &[u8]) -> Result<usize, SystemError> {
self.send(buffer, socket::MessageFlag::empty())
self.send(buffer, socket::PMSG::empty())
}
fn send_buffer_size(&self) -> usize {

View File

@ -5,7 +5,7 @@ use system_error::SystemError;
pub fn create_socket(
family: socket::AddressFamily,
socket_type: socket::Type,
socket_type: socket::PSOCK,
protocol: u32,
is_nonblock: bool,
is_close_on_exec: bool,
@ -21,7 +21,7 @@ pub fn create_socket(
todo!("unsupport address family");
}
};
// inode.set_nonblock(is_nonblock);
// inode.set_close_on_exec(is_close_on_exec);
inode.set_nonblock(is_nonblock);
inode.set_close_on_exec(is_close_on_exec);
return Ok(inode);
}

View File

@ -1,27 +1,14 @@
use core::{cmp::min, ffi::CStr};
use acpi::address;
use alloc::{boxed::Box, sync::Arc};
use alloc::sync::Arc;
use log::debug;
use num_traits::{FromPrimitive, ToPrimitive};
use smoltcp::wire;
use system_error::SystemError::{self, *};
use crate::{
filesystem::vfs::{
file::{File, FileMode},
syscall::{IoVec, IoVecs},
FileType,
},
libs::spinlock::SpinLockGuard,
mm::{verify_area, VirtAddr},
// net::socket::{netlink::af_netlink::NetlinkSock, AddressFamily},
filesystem::vfs::file::{File, FileMode},
process::ProcessManager,
syscall::Syscall,
};
use super::socket::{self, Endpoint, Socket};
use super::socket::{unix::Unix, AddressFamily as AF};
use super::socket::{self, unix::Unix, AddressFamily as AF, Endpoint};
pub use super::syscall_util::*;
@ -48,10 +35,10 @@ impl Syscall {
// protocol
// );
let address_family = socket::AddressFamily::try_from(address_family as u16)?;
let type_arg = SysArgSocketType::from_bits_truncate(socket_type as u32);
let type_arg = PosixArgsSocketType::from_bits_truncate(socket_type as u32);
let is_nonblock = type_arg.is_nonblock();
let is_close_on_exec = type_arg.is_cloexec();
let stype = socket::Type::try_from(type_arg)?;
let stype = socket::PSOCK::try_from(type_arg)?;
// log::debug!("type_arg {:?} stype {:?}", type_arg, stype);
let inode = socket::create_socket(
@ -86,39 +73,22 @@ impl Syscall {
fds: &mut [i32],
) -> Result<usize, SystemError> {
let address_family = AF::try_from(address_family as u16)?;
let socket_type = SysArgSocketType::from_bits_truncate(socket_type as u32);
let stype = socket::Type::try_from(socket_type)?;
let socket_type = PosixArgsSocketType::from_bits_truncate(socket_type as u32);
let stype = socket::PSOCK::try_from(socket_type)?;
let binding = ProcessManager::current_pcb().fd_table();
let mut fd_table_guard = binding.write();
// check address family, only support AF_UNIX
if address_family != AF::Unix {
log::warn!(
"only support AF_UNIX, {:?} with protocol {:?} is not supported",
address_family,
protocol
);
return Err(SystemError::EAFNOSUPPORT);
}
// 创建一对socket
// let inode0 = socket::create_socket(
// address_family,
// stype,
// protocol as u32,
// socket_type.is_nonblock(),
// socket_type.is_cloexec(),
// )?;
// let inode1 = socket::create_socket(
// address_family,
// stype,
// protocol as u32,
// socket_type.is_nonblock(),
// socket_type.is_cloexec(),
// )?;
// // 进行pair
// unsafe {
// inode0.connect(socket::Endpoint::Inode(inode1.clone()))?;
// inode1.connect(socket::Endpoint::Inode(inode0.clone()))?;
// }
// 创建一对新的unix socket pair
let (inode0, inode1) = Unix::new_pairs(stype)?;
@ -142,7 +112,7 @@ impl Syscall {
optname: usize,
optval: &[u8],
) -> Result<usize, SystemError> {
let sol = socket::OptionsLevel::try_from(level as u32)?;
let sol = socket::PSOL::try_from(level as u32)?;
let socket: Arc<socket::Inode> = ProcessManager::current_pcb()
.get_socket(fd as i32)
.ok_or(SystemError::EBADF)?;
@ -172,14 +142,14 @@ impl Syscall {
.get_socket(fd as i32)
.ok_or(EBADF)?;
let level = socket::OptionsLevel::try_from(level as u32)?;
use socket::{PSO, PSOL};
use socket::Options as SO;
use socket::OptionsLevel as SOL;
if matches!(level, SOL::SOCKET) {
let optname = SO::try_from(optname as u32).map_err(|_| ENOPROTOOPT)?;
let level = PSOL::try_from(level as u32)?;
if matches!(level, PSOL::SOCKET) {
let optname = PSO::try_from(optname as u32).map_err(|_| ENOPROTOOPT)?;
match optname {
SO::SNDBUF => {
PSO::SNDBUF => {
// 返回发送缓冲区大小
unsafe {
*optval = socket.send_buffer_size() as u32;
@ -187,7 +157,7 @@ impl Syscall {
}
return Ok(0);
}
SO::RCVBUF => {
PSO::RCVBUF => {
// 返回默认的接收缓冲区大小
unsafe {
*optval = socket.recv_buffer_size() as u32;
@ -208,11 +178,11 @@ impl Syscall {
// to be interpreted by the TCP protocol, level should be set to the
// protocol number of TCP.
if matches!(level, SOL::TCP) {
let optname =
PosixTcpSocketOptions::try_from(optname as i32).map_err(|_| ENOPROTOOPT)?;
if matches!(level, PSOL::TCP) {
use socket::inet::stream::TcpOption;
let optname = TcpOption::try_from(optname as i32).map_err(|_| ENOPROTOOPT)?;
match optname {
PosixTcpSocketOptions::Congestion => return Ok(0),
TcpOption::Congestion => return Ok(0),
_ => {
return Err(ENOPROTOOPT);
}
@ -283,7 +253,7 @@ impl Syscall {
Some(SockAddr::to_endpoint(addr, addrlen)?)
};
let flags = socket::MessageFlag::from_bits_truncate(flags);
let flags = socket::PMSG::from_bits_truncate(flags);
let socket: Arc<socket::Inode> = ProcessManager::current_pcb()
.get_socket(fd as i32)
@ -315,7 +285,7 @@ impl Syscall {
let socket: Arc<socket::Inode> = ProcessManager::current_pcb()
.get_socket(fd as i32)
.ok_or(SystemError::EBADF)?;
let flags = socket::MessageFlag::from_bits_truncate(flags);
let flags = socket::PMSG::from_bits_truncate(flags);
if addr.is_null() {
let (n, _) = socket.recv_from(buf, flags, None)?;
@ -357,7 +327,7 @@ impl Syscall {
// .get_socket(fd as i32)
// .ok_or(SystemError::EBADF)?;
// let flags = socket::MessageFlag::from_bits_truncate(flags as u32);
// let flags = socket::PMSG::from_bits_truncate(flags as u32);
// let mut buf = iovs.new_buf(true);
// // 从socket中读取数据
@ -548,92 +518,3 @@ impl Syscall {
return Ok(0);
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive, ToPrimitive)]
pub enum PosixTcpSocketOptions {
/// Turn off Nagle's algorithm.
NoDelay = 1,
/// Limit MSS.
MaxSegment = 2,
/// Never send partially complete segments.
Cork = 3,
/// Start keeplives after this period.
KeepIdle = 4,
/// Interval between keepalives.
KeepIntvl = 5,
/// Number of keepalives before death.
KeepCnt = 6,
/// Number of SYN retransmits.
Syncnt = 7,
/// Lifetime for orphaned FIN-WAIT-2 state.
Linger2 = 8,
/// Wake up listener only when data arrive.
DeferAccept = 9,
/// Bound advertised window
WindowClamp = 10,
/// Information about this connection.
Info = 11,
/// Block/reenable quick acks.
QuickAck = 12,
/// Congestion control algorithm.
Congestion = 13,
/// TCP MD5 Signature (RFC2385).
Md5Sig = 14,
/// Use linear timeouts for thin streams
ThinLinearTimeouts = 16,
/// Fast retrans. after 1 dupack.
ThinDupack = 17,
/// How long for loss retry before timeout.
UserTimeout = 18,
/// TCP sock is under repair right now.
Repair = 19,
RepairQueue = 20,
QueueSeq = 21,
RepairOptions = 22,
/// Enable FastOpen on listeners
FastOpen = 23,
Timestamp = 24,
/// Limit number of unsent bytes in write queue.
NotSentLowat = 25,
/// Get Congestion Control (optional) info.
CCInfo = 26,
/// Record SYN headers for new connections.
SaveSyn = 27,
/// Get SYN headers recorded for connection.
SavedSyn = 28,
/// Get/set window parameters.
RepairWindow = 29,
/// Attempt FastOpen with connect.
FastOpenConnect = 30,
/// Attach a ULP to a TCP connection.
ULP = 31,
/// TCP MD5 Signature with extensions.
Md5SigExt = 32,
/// Set the key for Fast Open(cookie).
FastOpenKey = 33,
/// Enable TFO without a TFO cookie.
FastOpenNoCookie = 34,
ZeroCopyReceive = 35,
/// Notify bytes available to read as a cmsg on read.
/// 与TCP_CM_INQ相同
INQ = 36,
/// delay outgoing packets by XX usec
TxDelay = 37,
}
impl TryFrom<i32> for PosixTcpSocketOptions {
type Error = SystemError;
fn try_from(value: i32) -> Result<Self, Self::Error> {
match <Self as FromPrimitive>::from_i32(value) {
Some(p) => Ok(p),
None => Err(SystemError::EINVAL),
}
}
}
impl From<PosixTcpSocketOptions> for i32 {
fn from(val: PosixTcpSocketOptions) -> Self {
<PosixTcpSocketOptions as ToPrimitive>::to_i32(&val).unwrap()
}
}

View File

@ -1,6 +1,6 @@
bitflags::bitflags! {
// #[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub struct SysArgSocketType: u32 {
pub struct PosixArgsSocketType: u32 {
const DGRAM = 1; // 0b0000_0001
const STREAM = 2; // 0b0000_0010
const RAW = 3; // 0b0000_0011
@ -14,39 +14,34 @@ bitflags::bitflags! {
}
}
impl SysArgSocketType {
impl PosixArgsSocketType {
#[inline(always)]
pub fn types(&self) -> SysArgSocketType {
SysArgSocketType::from_bits(self.bits() & 0b_1111).unwrap()
pub fn types(&self) -> PosixArgsSocketType {
PosixArgsSocketType::from_bits(self.bits() & 0b_1111).unwrap()
}
#[inline(always)]
pub fn is_nonblock(&self) -> bool {
self.contains(SysArgSocketType::NONBLOCK)
self.contains(PosixArgsSocketType::NONBLOCK)
}
#[inline(always)]
pub fn is_cloexec(&self) -> bool {
self.contains(SysArgSocketType::CLOEXEC)
self.contains(PosixArgsSocketType::CLOEXEC)
}
}
use alloc::sync::Arc;
use core::ffi::CStr;
use unix::INODE_MAP;
use crate::{
filesystem::vfs::{
file::FileMode, FileType, IndexNode, MAX_PATHLEN, ROOT_INODE, VFS_MAX_FOLLOW_SYMLINK_TIMES,
},
libs::casting::DowncastArc,
filesystem::vfs::{FileType, IndexNode, ROOT_INODE, VFS_MAX_FOLLOW_SYMLINK_TIMES},
mm::{verify_area, VirtAddr},
net::socket::{self, *},
net::socket::*,
process::ProcessManager,
syscall::Syscall,
};
use smoltcp;
use system_error::SystemError::{self, *};
use system_error::SystemError;
// 参考资料: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/netinet_in.h.html#tag_13_32
#[repr(C)]