xref: /DragonOS/kernel/src/net/socket/mod.rs (revision 634349e0ebfca487e6aa2761a796f04895908718)
14ad52e57S裕依2439 use core::{any::Any, fmt::Debug, sync::atomic::AtomicUsize};
24ad52e57S裕依2439 
34ad52e57S裕依2439 use alloc::{
44ad52e57S裕依2439     boxed::Box,
54ad52e57S裕依2439     collections::LinkedList,
64ad52e57S裕依2439     string::String,
74ad52e57S裕依2439     sync::{Arc, Weak},
84ad52e57S裕依2439     vec::Vec,
94ad52e57S裕依2439 };
104ad52e57S裕依2439 use hashbrown::HashMap;
112eab6dd7S曾俊 use log::warn;
124ad52e57S裕依2439 use smoltcp::{
13d623e902SGnoCiYeH     iface::SocketSet,
1493c37970Ssun5etop     socket::{self, raw, tcp, udp},
154ad52e57S裕依2439 };
164ad52e57S裕依2439 use system_error::SystemError;
174ad52e57S裕依2439 
184ad52e57S裕依2439 use crate::{
19f0c87a89SGnoCiYeH     arch::rand::rand,
204ad52e57S裕依2439     filesystem::vfs::{
214ad52e57S裕依2439         file::FileMode, syscall::ModeType, FilePrivateData, FileSystem, FileType, IndexNode,
224ad52e57S裕依2439         Metadata,
234ad52e57S裕依2439     },
244ad52e57S裕依2439     libs::{
25*634349e0SLoGin         rwlock::{RwLock, RwLockWriteGuard},
264ad52e57S裕依2439         spinlock::{SpinLock, SpinLockGuard},
274ad52e57S裕依2439         wait_queue::EventWaitQueue,
284ad52e57S裕依2439     },
2937cef00bSSamuel Dai     process::{Pid, ProcessManager},
30f0c87a89SGnoCiYeH     sched::{schedule, SchedMode},
314ad52e57S裕依2439 };
324ad52e57S裕依2439 
336046f775S裕依 use self::{
34d623e902SGnoCiYeH     handle::GlobalSocketHandle,
356046f775S裕依     inet::{RawSocket, TcpSocket, UdpSocket},
366046f775S裕依     unix::{SeqpacketSocket, StreamSocket},
376046f775S裕依 };
384ad52e57S裕依2439 
394ad52e57S裕依2439 use super::{
404ad52e57S裕依2439     event_poll::{EPollEventType, EPollItem, EventPoll},
414ad52e57S裕依2439     Endpoint, Protocol, ShutdownType,
424ad52e57S裕依2439 };
434ad52e57S裕依2439 
44d623e902SGnoCiYeH pub mod handle;
456046f775S裕依 pub mod inet;
466046f775S裕依 pub mod unix;
474ad52e57S裕依2439 
484ad52e57S裕依2439 lazy_static! {
494ad52e57S裕依2439     /// 所有socket的集合
504ad52e57S裕依2439     /// TODO: 优化这里,自己实现SocketSet!!!现在这样的话,不管全局有多少个网卡,每个时间点都只会有1个进程能够访问socket
514ad52e57S裕依2439     pub static ref SOCKET_SET: SpinLock<SocketSet<'static >> = SpinLock::new(SocketSet::new(vec![]));
524ad52e57S裕依2439     /// SocketHandle表,每个SocketHandle对应一个SocketHandleItem,
534ad52e57S裕依2439     /// 注意!:在网卡中断中需要拿到这张表的��,在获取读锁时应该确保关中断避免死锁
54d623e902SGnoCiYeH     pub static ref HANDLE_MAP: RwLock<HashMap<GlobalSocketHandle, SocketHandleItem>> = RwLock::new(HashMap::new());
554ad52e57S裕依2439     /// 端口管理器
564ad52e57S裕依2439     pub static ref PORT_MANAGER: PortManager = PortManager::new();
574ad52e57S裕依2439 }
584ad52e57S裕依2439 
594ad52e57S裕依2439 /* For setsockopt(2) */
604ad52e57S裕依2439 // See: linux-5.19.10/include/uapi/asm-generic/socket.h#9
614ad52e57S裕依2439 pub const SOL_SOCKET: u8 = 1;
624ad52e57S裕依2439 
634ad52e57S裕依2439 /// 根据地址族、socket类型和协议创建socket
new_socket( address_family: AddressFamily, socket_type: PosixSocketType, protocol: Protocol, ) -> Result<Box<dyn Socket>, SystemError>644ad52e57S裕依2439 pub(super) fn new_socket(
654ad52e57S裕依2439     address_family: AddressFamily,
664ad52e57S裕依2439     socket_type: PosixSocketType,
674ad52e57S裕依2439     protocol: Protocol,
684ad52e57S裕依2439 ) -> Result<Box<dyn Socket>, SystemError> {
694ad52e57S裕依2439     let socket: Box<dyn Socket> = match address_family {
704ad52e57S裕依2439         AddressFamily::Unix => match socket_type {
716046f775S裕依             PosixSocketType::Stream => Box::new(StreamSocket::new(SocketOptions::default())),
724ad52e57S裕依2439             PosixSocketType::SeqPacket => Box::new(SeqpacketSocket::new(SocketOptions::default())),
734ad52e57S裕依2439             _ => {
744ad52e57S裕依2439                 return Err(SystemError::EINVAL);
754ad52e57S裕依2439             }
764ad52e57S裕依2439         },
774ad52e57S裕依2439         AddressFamily::INet => match socket_type {
784ad52e57S裕依2439             PosixSocketType::Stream => Box::new(TcpSocket::new(SocketOptions::default())),
794ad52e57S裕依2439             PosixSocketType::Datagram => Box::new(UdpSocket::new(SocketOptions::default())),
804ad52e57S裕依2439             PosixSocketType::Raw => Box::new(RawSocket::new(protocol, SocketOptions::default())),
814ad52e57S裕依2439             _ => {
824ad52e57S裕依2439                 return Err(SystemError::EINVAL);
834ad52e57S裕依2439             }
844ad52e57S裕依2439         },
854ad52e57S裕依2439         _ => {
864ad52e57S裕依2439             return Err(SystemError::EAFNOSUPPORT);
874ad52e57S裕依2439         }
884ad52e57S裕依2439     };
89d623e902SGnoCiYeH 
90*634349e0SLoGin     let handle_item = SocketHandleItem::new(Arc::downgrade(&socket.posix_item()));
91d623e902SGnoCiYeH     HANDLE_MAP
92d623e902SGnoCiYeH         .write_irqsave()
93d623e902SGnoCiYeH         .insert(socket.socket_handle(), handle_item);
944ad52e57S裕依2439     Ok(socket)
954ad52e57S裕依2439 }
964ad52e57S裕依2439 
974ad52e57S裕依2439 pub trait Socket: Sync + Send + Debug + Any {
984ad52e57S裕依2439     /// @brief 从socket中读取数据,如果socket是阻塞的,那么直到读取到数据才返回
994ad52e57S裕依2439     ///
1004ad52e57S裕依2439     /// @param buf 读取到的数据存放的缓冲区
1014ad52e57S裕依2439     ///
1024ad52e57S裕依2439     /// @return - 成功:(返回读取的数据的长度,读取数据的端点).
1034ad52e57S裕依2439     ///         - 失败:错误码
read(&self, buf: &mut [u8]) -> (Result<usize, SystemError>, Endpoint)1046046f775S裕依     fn read(&self, buf: &mut [u8]) -> (Result<usize, SystemError>, Endpoint);
1054ad52e57S裕依2439 
1064ad52e57S裕依2439     /// @brief 向socket中写入数据。如果socket是阻塞的,那么直到写入的数据全部写入socket中才返回
1074ad52e57S裕依2439     ///
1084ad52e57S裕依2439     /// @param buf 要写入的数据
1094ad52e57S裕依2439     /// @param to 要写入的目的端点,如果是None,那么写入的数据将会被丢弃
1104ad52e57S裕依2439     ///
1114ad52e57S裕依2439     /// @return 返回写入的数据的长度
write(&self, buf: &[u8], to: Option<Endpoint>) -> Result<usize, SystemError>1124ad52e57S裕依2439     fn write(&self, buf: &[u8], to: Option<Endpoint>) -> Result<usize, SystemError>;
1134ad52e57S裕依2439 
1144ad52e57S裕依2439     /// @brief 对应于POSIX的connect函数,用于连接到指定的远程服务器端点
1154ad52e57S裕依2439     ///
1164ad52e57S裕依2439     /// It is used to establish a connection to a remote server.
1174ad52e57S裕依2439     /// When a socket is connected to a remote server,
1184ad52e57S裕依2439     /// the operating system will establish a network connection with the server
1194ad52e57S裕依2439     /// and allow data to be sent and received between the local socket and the remote server.
1204ad52e57S裕依2439     ///
1214ad52e57S裕依2439     /// @param endpoint 要连接的端点
1224ad52e57S裕依2439     ///
1234ad52e57S裕依2439     /// @return 返回连接是否成功
connect(&mut self, _endpoint: Endpoint) -> Result<(), SystemError>1246046f775S裕依     fn connect(&mut self, _endpoint: Endpoint) -> Result<(), SystemError>;
1254ad52e57S裕依2439 
1264ad52e57S裕依2439     /// @brief 对应于POSIX的bind函数,用于绑定到本机指定的端点
1274ad52e57S裕依2439     ///
1284ad52e57S裕依2439     /// The bind() function is used to associate a socket with a particular IP address and port number on the local machine.
1294ad52e57S裕依2439     ///
1304ad52e57S裕依2439     /// @param endpoint 要绑定的端点
1314ad52e57S裕依2439     ///
1324ad52e57S裕依2439     /// @return 返回绑定是否成功
bind(&mut self, _endpoint: Endpoint) -> Result<(), SystemError>1334ad52e57S裕依2439     fn bind(&mut self, _endpoint: Endpoint) -> Result<(), SystemError> {
1346046f775S裕依         Err(SystemError::ENOSYS)
1354ad52e57S裕依2439     }
1364ad52e57S裕依2439 
1374ad52e57S裕依2439     /// @brief 对应于 POSIX 的 shutdown 函数,用于关闭socket。
1384ad52e57S裕依2439     ///
1394ad52e57S裕依2439     /// shutdown() 函数用于启动网络连接的正常关闭。
1404ad52e57S裕依2439     /// 当在两个端点之间建立网络连接时,任一端点都可以通过调用其端点对象上的 shutdown() 函数来启动关闭序列。
1414ad52e57S裕依2439     /// 此函数向远程端点发送关闭消息以指示本地端点不再接受新数据。
1424ad52e57S裕依2439     ///
1434ad52e57S裕依2439     /// @return 返回是否成功关闭
shutdown(&mut self, _type: ShutdownType) -> Result<(), SystemError>1444ad52e57S裕依2439     fn shutdown(&mut self, _type: ShutdownType) -> Result<(), SystemError> {
1456046f775S裕依         Err(SystemError::ENOSYS)
1464ad52e57S裕依2439     }
1474ad52e57S裕依2439 
1484ad52e57S裕依2439     /// @brief 对应于POSIX的listen函数,用于监听端点
1494ad52e57S裕依2439     ///
1504ad52e57S裕依2439     /// @param backlog 最大的等待连接数
1514ad52e57S裕依2439     ///
1524ad52e57S裕依2439     /// @return 返回监听是否成功
listen(&mut self, _backlog: usize) -> Result<(), SystemError>1534ad52e57S裕依2439     fn listen(&mut self, _backlog: usize) -> Result<(), SystemError> {
1546046f775S裕依         Err(SystemError::ENOSYS)
1554ad52e57S裕依2439     }
1564ad52e57S裕依2439 
1574ad52e57S裕依2439     /// @brief 对应于POSIX的accept函数,用于接受连接
1584ad52e57S裕依2439     ///
1594ad52e57S裕依2439     /// @param endpoint 对端的端点
1604ad52e57S裕依2439     ///
1614ad52e57S裕依2439     /// @return 返回接受连接是否成功
accept(&mut self) -> Result<(Box<dyn Socket>, Endpoint), SystemError>1624ad52e57S裕依2439     fn accept(&mut self) -> Result<(Box<dyn Socket>, Endpoint), SystemError> {
1636046f775S裕依         Err(SystemError::ENOSYS)
1644ad52e57S裕依2439     }
1654ad52e57S裕依2439 
1664ad52e57S裕依2439     /// @brief 获取socket的端点
1674ad52e57S裕依2439     ///
1684ad52e57S裕依2439     /// @return 返回socket的端点
endpoint(&self) -> Option<Endpoint>1694ad52e57S裕依2439     fn endpoint(&self) -> Option<Endpoint> {
1706046f775S裕依         None
1714ad52e57S裕依2439     }
1724ad52e57S裕依2439 
1734ad52e57S裕依2439     /// @brief 获取socket的对端端点
1744ad52e57S裕依2439     ///
1754ad52e57S裕依2439     /// @return 返回socket的对端端点
peer_endpoint(&self) -> Option<Endpoint>1764ad52e57S裕依2439     fn peer_endpoint(&self) -> Option<Endpoint> {
1774ad52e57S裕依2439         None
1784ad52e57S裕依2439     }
1794ad52e57S裕依2439 
1804ad52e57S裕依2439     /// @brief
1814ad52e57S裕依2439     ///     The purpose of the poll function is to provide
1824ad52e57S裕依2439     ///     a non-blocking way to check if a socket is ready for reading or writing,
1834ad52e57S裕依2439     ///     so that you can efficiently handle multiple sockets in a single thread or event loop.
1844ad52e57S裕依2439     ///
1854ad52e57S裕依2439     /// @return (in, out, err)
1864ad52e57S裕依2439     ///
1874ad52e57S裕依2439     ///     The first boolean value indicates whether the socket is ready for reading. If it is true, then there is data available to be read from the socket without blocking.
1884ad52e57S裕依2439     ///     The second boolean value indicates whether the socket is ready for writing. If it is true, then data can be written to the socket without blocking.
1894ad52e57S裕依2439     ///     The third boolean value indicates whether the socket has encountered an error condition. If it is true, then the socket is in an error state and should be closed or reset
1904ad52e57S裕依2439     ///
poll(&self) -> EPollEventType1914ad52e57S裕依2439     fn poll(&self) -> EPollEventType {
1926046f775S裕依         EPollEventType::empty()
1934ad52e57S裕依2439     }
1944ad52e57S裕依2439 
1954ad52e57S裕依2439     /// @brief socket的ioctl函数
1964ad52e57S裕依2439     ///
1974ad52e57S裕依2439     /// @param cmd ioctl命令
1984ad52e57S裕依2439     /// @param arg0 ioctl命令的第一个参数
1994ad52e57S裕依2439     /// @param arg1 ioctl命令的第二个参数
2004ad52e57S裕依2439     /// @param arg2 ioctl命令的第三个参数
2014ad52e57S裕依2439     ///
2024ad52e57S裕依2439     /// @return 返回ioctl命令的返回值
ioctl( &self, _cmd: usize, _arg0: usize, _arg1: usize, _arg2: usize, ) -> Result<usize, SystemError>2034ad52e57S裕依2439     fn ioctl(
2044ad52e57S裕依2439         &self,
2054ad52e57S裕依2439         _cmd: usize,
2064ad52e57S裕依2439         _arg0: usize,
2074ad52e57S裕依2439         _arg1: usize,
2084ad52e57S裕依2439         _arg2: usize,
2094ad52e57S裕依2439     ) -> Result<usize, SystemError> {
2106046f775S裕依         Ok(0)
2114ad52e57S裕依2439     }
2124ad52e57S裕依2439 
2134ad52e57S裕依2439     /// @brief 获取socket的元数据
metadata(&self) -> SocketMetadata2146046f775S裕依     fn metadata(&self) -> SocketMetadata;
2154ad52e57S裕依2439 
box_clone(&self) -> Box<dyn Socket>2164ad52e57S裕依2439     fn box_clone(&self) -> Box<dyn Socket>;
2174ad52e57S裕依2439 
2184ad52e57S裕依2439     /// @brief 设置socket的选项
2194ad52e57S裕依2439     ///
2204ad52e57S裕依2439     /// @param level 选项的层次
2214ad52e57S裕依2439     /// @param optname 选项的名称
2224ad52e57S裕依2439     /// @param optval 选项的值
2234ad52e57S裕依2439     ///
2244ad52e57S裕依2439     /// @return 返回设置是否成功, 如果不支持该选项,返回ENOSYS
setsockopt( &self, _level: usize, _optname: usize, _optval: &[u8], ) -> Result<(), SystemError>2254ad52e57S裕依2439     fn setsockopt(
2264ad52e57S裕依2439         &self,
2274ad52e57S裕依2439         _level: usize,
2284ad52e57S裕依2439         _optname: usize,
2294ad52e57S裕依2439         _optval: &[u8],
2304ad52e57S裕依2439     ) -> Result<(), SystemError> {
2312eab6dd7S曾俊         warn!("setsockopt is not implemented");
2326046f775S裕依         Ok(())
2334ad52e57S裕依2439     }
2344ad52e57S裕依2439 
socket_handle(&self) -> GlobalSocketHandle235d623e902SGnoCiYeH     fn socket_handle(&self) -> GlobalSocketHandle;
2364ad52e57S裕依2439 
write_buffer(&self, _buf: &[u8]) -> Result<usize, SystemError>2376046f775S裕依     fn write_buffer(&self, _buf: &[u8]) -> Result<usize, SystemError> {
2386046f775S裕依         todo!()
2396046f775S裕依     }
2406046f775S裕依 
as_any_ref(&self) -> &dyn Any2416046f775S裕依     fn as_any_ref(&self) -> &dyn Any;
2426046f775S裕依 
as_any_mut(&mut self) -> &mut dyn Any2436046f775S裕依     fn as_any_mut(&mut self) -> &mut dyn Any;
2446046f775S裕依 
add_epoll(&mut self, epitem: Arc<EPollItem>) -> Result<(), SystemError>2454ad52e57S裕依2439     fn add_epoll(&mut self, epitem: Arc<EPollItem>) -> Result<(), SystemError> {
246*634349e0SLoGin         let posix_item = self.posix_item();
247*634349e0SLoGin         posix_item.add_epoll(epitem);
2484ad52e57S裕依2439         Ok(())
2494ad52e57S裕依2439     }
2504ad52e57S裕依2439 
remove_epoll(&mut self, epoll: &Weak<SpinLock<EventPoll>>) -> Result<(), SystemError>2514ad52e57S裕依2439     fn remove_epoll(&mut self, epoll: &Weak<SpinLock<EventPoll>>) -> Result<(), SystemError> {
252*634349e0SLoGin         let posix_item = self.posix_item();
253*634349e0SLoGin         posix_item.remove_epoll(epoll)?;
2544ad52e57S裕依2439 
2554ad52e57S裕依2439         Ok(())
2564ad52e57S裕依2439     }
2574ad52e57S裕依2439 
clear_epoll(&mut self) -> Result<(), SystemError>2584ad52e57S裕依2439     fn clear_epoll(&mut self) -> Result<(), SystemError> {
259*634349e0SLoGin         let posix_item = self.posix_item();
2604ad52e57S裕依2439 
261*634349e0SLoGin         for epitem in posix_item.epitems.lock_irqsave().iter() {
2624ad52e57S裕依2439             let epoll = epitem.epoll();
263*634349e0SLoGin 
264*634349e0SLoGin             if let Some(epoll) = epoll.upgrade() {
265*634349e0SLoGin                 EventPoll::ep_remove(&mut epoll.lock_irqsave(), epitem.fd(), None)?;
2664ad52e57S裕依2439             }
2674ad52e57S裕依2439         }
2684ad52e57S裕依2439 
2694ad52e57S裕依2439         Ok(())
2704ad52e57S裕依2439     }
271d623e902SGnoCiYeH 
close(&mut self)272d623e902SGnoCiYeH     fn close(&mut self);
273*634349e0SLoGin 
posix_item(&self) -> Arc<PosixSocketHandleItem>274*634349e0SLoGin     fn posix_item(&self) -> Arc<PosixSocketHandleItem>;
2754ad52e57S裕依2439 }
2764ad52e57S裕依2439 
2774ad52e57S裕依2439 impl Clone for Box<dyn Socket> {
clone(&self) -> Box<dyn Socket>2784ad52e57S裕依2439     fn clone(&self) -> Box<dyn Socket> {
2794ad52e57S裕依2439         self.box_clone()
2804ad52e57S裕依2439     }
2814ad52e57S裕依2439 }
2824ad52e57S裕依2439 
2834ad52e57S裕依2439 /// # Socket在文件系统中的inode封装
2844ad52e57S裕依2439 #[derive(Debug)]
2854ad52e57S裕依2439 pub struct SocketInode(SpinLock<Box<dyn Socket>>, AtomicUsize);
2864ad52e57S裕依2439 
2874ad52e57S裕依2439 impl SocketInode {
new(socket: Box<dyn Socket>) -> Arc<Self>2884ad52e57S裕依2439     pub fn new(socket: Box<dyn Socket>) -> Arc<Self> {
2894ad52e57S裕依2439         Arc::new(Self(SpinLock::new(socket), AtomicUsize::new(0)))
2904ad52e57S裕依2439     }
2914ad52e57S裕依2439 
2924ad52e57S裕依2439     #[inline]
inner(&self) -> SpinLockGuard<Box<dyn Socket>>2934ad52e57S裕依2439     pub fn inner(&self) -> SpinLockGuard<Box<dyn Socket>> {
2946046f775S裕依         self.0.lock()
2954ad52e57S裕依2439     }
2964ad52e57S裕依2439 
inner_no_preempt(&self) -> SpinLockGuard<Box<dyn Socket>>2974ad52e57S裕依2439     pub unsafe fn inner_no_preempt(&self) -> SpinLockGuard<Box<dyn Socket>> {
2986046f775S裕依         self.0.lock_no_preempt()
2994ad52e57S裕依2439     }
30037cef00bSSamuel Dai 
do_close(&self) -> Result<(), SystemError>30137cef00bSSamuel Dai     fn do_close(&self) -> Result<(), SystemError> {
30237cef00bSSamuel Dai         let prev_ref_count = self.1.fetch_sub(1, core::sync::atomic::Ordering::SeqCst);
30337cef00bSSamuel Dai         if prev_ref_count == 1 {
30437cef00bSSamuel Dai             // 最后一次关闭,需要释放
30537cef00bSSamuel Dai             let mut socket = self.0.lock_irqsave();
30637cef00bSSamuel Dai 
30737cef00bSSamuel Dai             if socket.metadata().socket_type == SocketType::Unix {
30837cef00bSSamuel Dai                 return Ok(());
30937cef00bSSamuel Dai             }
31037cef00bSSamuel Dai 
31137cef00bSSamuel Dai             if let Some(Endpoint::Ip(Some(ip))) = socket.endpoint() {
31237cef00bSSamuel Dai                 PORT_MANAGER.unbind_port(socket.metadata().socket_type, ip.port);
31337cef00bSSamuel Dai             }
31437cef00bSSamuel Dai 
31537cef00bSSamuel Dai             socket.clear_epoll()?;
31637cef00bSSamuel Dai 
31737cef00bSSamuel Dai             HANDLE_MAP
31837cef00bSSamuel Dai                 .write_irqsave()
31937cef00bSSamuel Dai                 .remove(&socket.socket_handle())
32037cef00bSSamuel Dai                 .unwrap();
32137cef00bSSamuel Dai             socket.close();
32237cef00bSSamuel Dai         }
32337cef00bSSamuel Dai 
32437cef00bSSamuel Dai         Ok(())
32537cef00bSSamuel Dai     }
32637cef00bSSamuel Dai }
32737cef00bSSamuel Dai 
32837cef00bSSamuel Dai impl Drop for SocketInode {
drop(&mut self)32937cef00bSSamuel Dai     fn drop(&mut self) {
33037cef00bSSamuel Dai         for _ in 0..self.1.load(core::sync::atomic::Ordering::SeqCst) {
33137cef00bSSamuel Dai             let _ = self.do_close();
33237cef00bSSamuel Dai         }
33337cef00bSSamuel Dai     }
3344ad52e57S裕依2439 }
3354ad52e57S裕依2439 
3364ad52e57S裕依2439 impl IndexNode for SocketInode {
open( &self, _data: SpinLockGuard<FilePrivateData>, _mode: &FileMode, ) -> Result<(), SystemError>337dfe53cf0SGnoCiYeH     fn open(
338dfe53cf0SGnoCiYeH         &self,
339dfe53cf0SGnoCiYeH         _data: SpinLockGuard<FilePrivateData>,
340dfe53cf0SGnoCiYeH         _mode: &FileMode,
341dfe53cf0SGnoCiYeH     ) -> Result<(), SystemError> {
3424ad52e57S裕依2439         self.1.fetch_add(1, core::sync::atomic::Ordering::SeqCst);
3434ad52e57S裕依2439         Ok(())
3444ad52e57S裕依2439     }
3454ad52e57S裕依2439 
close(&self, _data: SpinLockGuard<FilePrivateData>) -> Result<(), SystemError>346dfe53cf0SGnoCiYeH     fn close(&self, _data: SpinLockGuard<FilePrivateData>) -> Result<(), SystemError> {
34737cef00bSSamuel Dai         self.do_close()
3484ad52e57S裕依2439     }
3494ad52e57S裕依2439 
read_at( &self, _offset: usize, len: usize, buf: &mut [u8], data: SpinLockGuard<FilePrivateData>, ) -> Result<usize, SystemError>3504ad52e57S裕依2439     fn read_at(
3514ad52e57S裕依2439         &self,
3524ad52e57S裕依2439         _offset: usize,
3534ad52e57S裕依2439         len: usize,
3544ad52e57S裕依2439         buf: &mut [u8],
355f0c87a89SGnoCiYeH         data: SpinLockGuard<FilePrivateData>,
3564ad52e57S裕依2439     ) -> Result<usize, SystemError> {
357f0c87a89SGnoCiYeH         drop(data);
3586046f775S裕依         self.0.lock_no_preempt().read(&mut buf[0..len]).0
3594ad52e57S裕依2439     }
3604ad52e57S裕依2439 
write_at( &self, _offset: usize, len: usize, buf: &[u8], data: SpinLockGuard<FilePrivateData>, ) -> Result<usize, SystemError>3614ad52e57S裕依2439     fn write_at(
3624ad52e57S裕依2439         &self,
3634ad52e57S裕依2439         _offset: usize,
3644ad52e57S裕依2439         len: usize,
3654ad52e57S裕依2439         buf: &[u8],
366f0c87a89SGnoCiYeH         data: SpinLockGuard<FilePrivateData>,
3674ad52e57S裕依2439     ) -> Result<usize, SystemError> {
368f0c87a89SGnoCiYeH         drop(data);
3696046f775S裕依         self.0.lock_no_preempt().write(&buf[0..len], None)
3704ad52e57S裕依2439     }
3714ad52e57S裕依2439 
poll(&self, _private_data: &FilePrivateData) -> Result<usize, SystemError>3724ad52e57S裕依2439     fn poll(&self, _private_data: &FilePrivateData) -> Result<usize, SystemError> {
3734ad52e57S裕依2439         let events = self.0.lock_irqsave().poll();
3744ad52e57S裕依2439         return Ok(events.bits() as usize);
3754ad52e57S裕依2439     }
3764ad52e57S裕依2439 
fs(&self) -> Arc<dyn FileSystem>3774ad52e57S裕依2439     fn fs(&self) -> Arc<dyn FileSystem> {
3784ad52e57S裕依2439         todo!()
3794ad52e57S裕依2439     }
3804ad52e57S裕依2439 
as_any_ref(&self) -> &dyn Any3814ad52e57S裕依2439     fn as_any_ref(&self) -> &dyn Any {
3824ad52e57S裕依2439         self
3834ad52e57S裕依2439     }
3844ad52e57S裕依2439 
list(&self) -> Result<Vec<String>, SystemError>3854ad52e57S裕依2439     fn list(&self) -> Result<Vec<String>, SystemError> {
3864ad52e57S裕依2439         return Err(SystemError::ENOTDIR);
3874ad52e57S裕依2439     }
3884ad52e57S裕依2439 
metadata(&self) -> Result<Metadata, SystemError>3894ad52e57S裕依2439     fn metadata(&self) -> Result<Metadata, SystemError> {
3904ad52e57S裕依2439         let meta = Metadata {
3914ad52e57S裕依2439             mode: ModeType::from_bits_truncate(0o755),
3924ad52e57S裕依2439             file_type: FileType::Socket,
3934ad52e57S裕依2439             ..Default::default()
3944ad52e57S裕依2439         };
3954ad52e57S裕依2439 
3964ad52e57S裕依2439         return Ok(meta);
3974ad52e57S裕依2439     }
3984ad52e57S裕依2439 
resize(&self, _len: usize) -> Result<(), SystemError>3994ad52e57S裕依2439     fn resize(&self, _len: usize) -> Result<(), SystemError> {
4004ad52e57S裕依2439         return Ok(());
4014ad52e57S裕依2439     }
4024ad52e57S裕依2439 }
4034ad52e57S裕依2439 
4044ad52e57S裕依2439 #[derive(Debug)]
405*634349e0SLoGin pub struct PosixSocketHandleItem {
4064ad52e57S裕依2439     /// socket的waitqueue
407*634349e0SLoGin     wait_queue: Arc<EventWaitQueue>,
408*634349e0SLoGin 
4094ad52e57S裕依2439     pub epitems: SpinLock<LinkedList<Arc<EPollItem>>>,
4104ad52e57S裕依2439 }
4114ad52e57S裕依2439 
412*634349e0SLoGin impl PosixSocketHandleItem {
new(wait_queue: Option<Arc<EventWaitQueue>>) -> Self41337cef00bSSamuel Dai     pub fn new(wait_queue: Option<Arc<EventWaitQueue>>) -> Self {
4144ad52e57S裕依2439         Self {
41537cef00bSSamuel Dai             wait_queue: wait_queue.unwrap_or(Arc::new(EventWaitQueue::new())),
4164ad52e57S裕依2439             epitems: SpinLock::new(LinkedList::new()),
4174ad52e57S裕依2439         }
4184ad52e57S裕依2439     }
4196046f775S裕依     /// ## 在socket的等待队列上睡眠
sleep(&self, events: u64)420*634349e0SLoGin     pub fn sleep(&self, events: u64) {
4214ad52e57S裕依2439         unsafe {
422*634349e0SLoGin             ProcessManager::preempt_disable();
423*634349e0SLoGin             self.wait_queue.sleep_without_schedule(events);
424*634349e0SLoGin             ProcessManager::preempt_enable();
425*634349e0SLoGin         }
426f0c87a89SGnoCiYeH         schedule(SchedMode::SM_NONE);
4274ad52e57S裕依2439     }
4284ad52e57S裕依2439 
add_epoll(&self, epitem: Arc<EPollItem>)429*634349e0SLoGin     pub fn add_epoll(&self, epitem: Arc<EPollItem>) {
4304ad52e57S裕依2439         self.epitems.lock_irqsave().push_back(epitem)
4314ad52e57S裕依2439     }
4324ad52e57S裕依2439 
remove_epoll(&self, epoll: &Weak<SpinLock<EventPoll>>) -> Result<(), SystemError>433*634349e0SLoGin     pub fn remove_epoll(&self, epoll: &Weak<SpinLock<EventPoll>>) -> Result<(), SystemError> {
4344ad52e57S裕依2439         let is_remove = !self
4354ad52e57S裕依2439             .epitems
4364ad52e57S裕依2439             .lock_irqsave()
4374ad52e57S裕依2439             .extract_if(|x| x.epoll().ptr_eq(epoll))
4384ad52e57S裕依2439             .collect::<Vec<_>>()
4394ad52e57S裕依2439             .is_empty();
4404ad52e57S裕依2439 
4414ad52e57S裕依2439         if is_remove {
4424ad52e57S裕依2439             return Ok(());
4434ad52e57S裕依2439         }
4444ad52e57S裕依2439 
4454ad52e57S裕依2439         Err(SystemError::ENOENT)
4464ad52e57S裕依2439     }
447*634349e0SLoGin 
448*634349e0SLoGin     /// ### 唤醒该队列上等待events的进程
449*634349e0SLoGin     ///
450*634349e0SLoGin     ///  ### 参数
451*634349e0SLoGin     /// - events: 发生的事件
452*634349e0SLoGin     ///
453*634349e0SLoGin     /// 需要注意的是,只要触发了events中的任意一件事件,进程都会被唤醒
wakeup_any(&self, events: u64)454*634349e0SLoGin     pub fn wakeup_any(&self, events: u64) {
455*634349e0SLoGin         self.wait_queue.wakeup_any(events);
456*634349e0SLoGin     }
457*634349e0SLoGin }
458*634349e0SLoGin #[derive(Debug)]
459*634349e0SLoGin pub struct SocketHandleItem {
460*634349e0SLoGin     /// 对应的posix socket是否为listen的
461*634349e0SLoGin     pub is_posix_listen: bool,
462*634349e0SLoGin     /// shutdown状态
463*634349e0SLoGin     pub shutdown_type: RwLock<ShutdownType>,
464*634349e0SLoGin     pub posix_item: Weak<PosixSocketHandleItem>,
465*634349e0SLoGin }
466*634349e0SLoGin 
467*634349e0SLoGin impl SocketHandleItem {
new(posix_item: Weak<PosixSocketHandleItem>) -> Self468*634349e0SLoGin     pub fn new(posix_item: Weak<PosixSocketHandleItem>) -> Self {
469*634349e0SLoGin         Self {
470*634349e0SLoGin             is_posix_listen: false,
471*634349e0SLoGin             shutdown_type: RwLock::new(ShutdownType::empty()),
472*634349e0SLoGin             posix_item,
473*634349e0SLoGin         }
474*634349e0SLoGin     }
475*634349e0SLoGin 
shutdown_type(&self) -> ShutdownType476*634349e0SLoGin     pub fn shutdown_type(&self) -> ShutdownType {
477*634349e0SLoGin         *self.shutdown_type.read()
478*634349e0SLoGin     }
479*634349e0SLoGin 
shutdown_type_writer(&mut self) -> RwLockWriteGuard<ShutdownType>480*634349e0SLoGin     pub fn shutdown_type_writer(&mut self) -> RwLockWriteGuard<ShutdownType> {
481*634349e0SLoGin         self.shutdown_type.write_irqsave()
482*634349e0SLoGin     }
483*634349e0SLoGin 
reset_shutdown_type(&self)484*634349e0SLoGin     pub fn reset_shutdown_type(&self) {
485*634349e0SLoGin         *self.shutdown_type.write() = ShutdownType::empty();
486*634349e0SLoGin     }
487*634349e0SLoGin 
posix_item(&self) -> Option<Arc<PosixSocketHandleItem>>488*634349e0SLoGin     pub fn posix_item(&self) -> Option<Arc<PosixSocketHandleItem>> {
489*634349e0SLoGin         self.posix_item.upgrade()
490*634349e0SLoGin     }
4914ad52e57S裕依2439 }
4924ad52e57S裕依2439 
4934ad52e57S裕依2439 /// # TCP 和 UDP 的端口管理器。
4944ad52e57S裕依2439 /// 如果 TCP/UDP 的 socket 绑定了某个端口,它会在对应的表中记录,以检测端口冲突。
4954ad52e57S裕依2439 pub struct PortManager {
4964ad52e57S裕依2439     // TCP 端口记录表
49737cef00bSSamuel Dai     tcp_port_table: SpinLock<HashMap<u16, Pid>>,
4984ad52e57S裕依2439     // UDP 端口记录表
49937cef00bSSamuel Dai     udp_port_table: SpinLock<HashMap<u16, Pid>>,
5004ad52e57S裕依2439 }
5014ad52e57S裕依2439 
5024ad52e57S裕依2439 impl PortManager {
new() -> Self5034ad52e57S裕依2439     pub fn new() -> Self {
5044ad52e57S裕依2439         return Self {
5054ad52e57S裕依2439             tcp_port_table: SpinLock::new(HashMap::new()),
5064ad52e57S裕依2439             udp_port_table: SpinLock::new(HashMap::new()),
5074ad52e57S裕依2439         };
5084ad52e57S裕依2439     }
5094ad52e57S裕依2439 
5104ad52e57S裕依2439     /// @brief 自动分配一个相对应协议中未被使用的PORT,如果动态端口均已被占用,返回错误码 EADDRINUSE
get_ephemeral_port(&self, socket_type: SocketType) -> Result<u16, SystemError>5114ad52e57S裕依2439     pub fn get_ephemeral_port(&self, socket_type: SocketType) -> Result<u16, SystemError> {
5124ad52e57S裕依2439         // TODO: selects non-conflict high port
5134ad52e57S裕依2439 
5144ad52e57S裕依2439         static mut EPHEMERAL_PORT: u16 = 0;
5154ad52e57S裕依2439         unsafe {
5164ad52e57S裕依2439             if EPHEMERAL_PORT == 0 {
5174ad52e57S裕依2439                 EPHEMERAL_PORT = (49152 + rand() % (65536 - 49152)) as u16;
5184ad52e57S裕依2439             }
5194ad52e57S裕依2439         }
5204ad52e57S裕依2439 
5214ad52e57S裕依2439         let mut remaining = 65536 - 49152; // 剩余尝试分配端口次数
5224ad52e57S裕依2439         let mut port: u16;
5234ad52e57S裕依2439         while remaining > 0 {
5244ad52e57S裕依2439             unsafe {
5254ad52e57S裕依2439                 if EPHEMERAL_PORT == 65535 {
5264ad52e57S裕依2439                     EPHEMERAL_PORT = 49152;
5274ad52e57S裕依2439                 } else {
528b5b571e0SLoGin                     EPHEMERAL_PORT += 1;
5294ad52e57S裕依2439                 }
5304ad52e57S裕依2439                 port = EPHEMERAL_PORT;
5314ad52e57S裕依2439             }
5324ad52e57S裕依2439 
5334ad52e57S裕依2439             // 使用 ListenTable 检查端口是否被占用
5344ad52e57S裕依2439             let listen_table_guard = match socket_type {
535b5b571e0SLoGin                 SocketType::Udp => self.udp_port_table.lock(),
536b5b571e0SLoGin                 SocketType::Tcp => self.tcp_port_table.lock(),
5374ad52e57S裕依2439                 _ => panic!("{:?} cann't get a port", socket_type),
5384ad52e57S裕依2439             };
539b5b571e0SLoGin             if listen_table_guard.get(&port).is_none() {
5404ad52e57S裕依2439                 drop(listen_table_guard);
5414ad52e57S裕依2439                 return Ok(port);
5424ad52e57S裕依2439             }
5434ad52e57S裕依2439             remaining -= 1;
5444ad52e57S裕依2439         }
5454ad52e57S裕依2439         return Err(SystemError::EADDRINUSE);
5464ad52e57S裕依2439     }
5474ad52e57S裕依2439 
5484ad52e57S裕依2439     /// @brief 检测给定端口是否已被占用,如果未被占用则在 TCP/UDP 对应的表中记录
5494ad52e57S裕依2439     ///
5504ad52e57S裕依2439     /// TODO: 增加支持端口复用的逻辑
bind_port(&self, socket_type: SocketType, port: u16) -> Result<(), SystemError>55137cef00bSSamuel Dai     pub fn bind_port(&self, socket_type: SocketType, port: u16) -> Result<(), SystemError> {
5524ad52e57S裕依2439         if port > 0 {
5534ad52e57S裕依2439             let mut listen_table_guard = match socket_type {
554b5b571e0SLoGin                 SocketType::Udp => self.udp_port_table.lock(),
555b5b571e0SLoGin                 SocketType::Tcp => self.tcp_port_table.lock(),
5564ad52e57S裕依2439                 _ => panic!("{:?} cann't bind a port", socket_type),
5574ad52e57S裕依2439             };
5584ad52e57S裕依2439             match listen_table_guard.get(&port) {
5594ad52e57S裕依2439                 Some(_) => return Err(SystemError::EADDRINUSE),
56037cef00bSSamuel Dai                 None => listen_table_guard.insert(port, ProcessManager::current_pid()),
5614ad52e57S裕依2439             };
5624ad52e57S裕依2439             drop(listen_table_guard);
5634ad52e57S裕依2439         }
5644ad52e57S裕依2439         return Ok(());
5654ad52e57S裕依2439     }
5664ad52e57S裕依2439 
5674ad52e57S裕依2439     /// @brief 在对应的端口记录表中将端口和 socket 解绑
56837cef00bSSamuel Dai     /// should call this function when socket is closed or aborted
unbind_port(&self, socket_type: SocketType, port: u16)56937cef00bSSamuel Dai     pub fn unbind_port(&self, socket_type: SocketType, port: u16) {
5704ad52e57S裕依2439         let mut listen_table_guard = match socket_type {
571b5b571e0SLoGin             SocketType::Udp => self.udp_port_table.lock(),
572b5b571e0SLoGin             SocketType::Tcp => self.tcp_port_table.lock(),
57337cef00bSSamuel Dai             _ => {
57437cef00bSSamuel Dai                 return;
57537cef00bSSamuel Dai             }
5764ad52e57S裕依2439         };
5774ad52e57S裕依2439         listen_table_guard.remove(&port);
5784ad52e57S裕依2439         drop(listen_table_guard);
5794ad52e57S裕依2439     }
5804ad52e57S裕依2439 }
5814ad52e57S裕依2439 
5824ad52e57S裕依2439 /// @brief socket的类型
5834ad52e57S裕依2439 #[derive(Debug, Clone, Copy, PartialEq)]
5844ad52e57S裕依2439 pub enum SocketType {
5854ad52e57S裕依2439     /// 原始的socket
586b5b571e0SLoGin     Raw,
5874ad52e57S裕依2439     /// 用于Tcp通信的 Socket
588b5b571e0SLoGin     Tcp,
5894ad52e57S裕依2439     /// 用于Udp通信的 Socket
590b5b571e0SLoGin     Udp,
5916046f775S裕依     /// unix域的 Socket
5926046f775S裕依     Unix,
5934ad52e57S裕依2439 }
5944ad52e57S裕依2439 
5954ad52e57S裕依2439 bitflags! {
5964ad52e57S裕依2439     /// @brief socket的选项
5974ad52e57S裕依2439     #[derive(Default)]
5984ad52e57S裕依2439     pub struct SocketOptions: u32 {
5994ad52e57S裕依2439         /// 是否阻塞
6004ad52e57S裕依2439         const BLOCK = 1 << 0;
6014ad52e57S裕依2439         /// 是否允许广播
6024ad52e57S裕依2439         const BROADCAST = 1 << 1;
6034ad52e57S裕依2439         /// 是否允许多播
6044ad52e57S裕依2439         const MULTICAST = 1 << 2;
6054ad52e57S裕依2439         /// 是否允许重用地址
6064ad52e57S裕依2439         const REUSEADDR = 1 << 3;
6074ad52e57S裕依2439         /// 是否允许重用端口
6084ad52e57S裕依2439         const REUSEPORT = 1 << 4;
6094ad52e57S裕依2439     }
6104ad52e57S裕依2439 }
6114ad52e57S裕依2439 
6124ad52e57S裕依2439 #[derive(Debug, Clone)]
6134ad52e57S裕依2439 /// @brief 在trait Socket的metadata函数中返回该结构体供外部使用
6144ad52e57S裕依2439 pub struct SocketMetadata {
6154ad52e57S裕依2439     /// socket的类型
6164ad52e57S裕依2439     pub socket_type: SocketType,
6174ad52e57S裕依2439     /// 接收缓冲区的大小
6184ad52e57S裕依2439     pub rx_buf_size: usize,
6194ad52e57S裕依2439     /// 发送缓冲区的大小
6204ad52e57S裕依2439     pub tx_buf_size: usize,
6214ad52e57S裕依2439     /// 元数据的缓冲区的大小
6224ad52e57S裕依2439     pub metadata_buf_size: usize,
6234ad52e57S裕依2439     /// socket的选项
6244ad52e57S裕依2439     pub options: SocketOptions,
6254ad52e57S裕依2439 }
6264ad52e57S裕依2439 
6274ad52e57S裕依2439 impl SocketMetadata {
new( socket_type: SocketType, rx_buf_size: usize, tx_buf_size: usize, metadata_buf_size: usize, options: SocketOptions, ) -> Self6284ad52e57S裕依2439     fn new(
6294ad52e57S裕依2439         socket_type: SocketType,
6304ad52e57S裕依2439         rx_buf_size: usize,
6314ad52e57S裕依2439         tx_buf_size: usize,
6324ad52e57S裕依2439         metadata_buf_size: usize,
6334ad52e57S裕依2439         options: SocketOptions,
6344ad52e57S裕依2439     ) -> Self {
6354ad52e57S裕依2439         Self {
6364ad52e57S裕依2439             socket_type,
6374ad52e57S裕依2439             rx_buf_size,
6384ad52e57S裕依2439             tx_buf_size,
6394ad52e57S裕依2439             metadata_buf_size,
6404ad52e57S裕依2439             options,
6414ad52e57S裕依2439         }
6424ad52e57S裕依2439     }
6434ad52e57S裕依2439 }
6444ad52e57S裕依2439 
6454ad52e57S裕依2439 /// @brief 地址族的枚举
6464ad52e57S裕依2439 ///
6474ad52e57S裕依2439 /// 参考:https://code.dragonos.org.cn/xref/linux-5.19.10/include/linux/socket.h#180
6484ad52e57S裕依2439 #[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive, ToPrimitive)]
6494ad52e57S裕依2439 pub enum AddressFamily {
6504ad52e57S裕依2439     /// AF_UNSPEC 表示地址族未指定
6514ad52e57S裕依2439     Unspecified = 0,
6524ad52e57S裕依2439     /// AF_UNIX 表示Unix域的socket (与AF_LOCAL相同)
6534ad52e57S裕依2439     Unix = 1,
6544ad52e57S裕依2439     ///  AF_INET 表示IPv4的socket
6554ad52e57S裕依2439     INet = 2,
6564ad52e57S裕依2439     /// AF_AX25 表示AMPR AX.25的socket
6574ad52e57S裕依2439     AX25 = 3,
6584ad52e57S裕依2439     /// AF_IPX 表示IPX的socket
6594ad52e57S裕依2439     IPX = 4,
6604ad52e57S裕依2439     /// AF_APPLETALK 表示Appletalk的socket
6614ad52e57S裕依2439     Appletalk = 5,
6624ad52e57S裕依2439     /// AF_NETROM 表示AMPR NET/ROM的socket
6634ad52e57S裕依2439     Netrom = 6,
6644ad52e57S裕依2439     /// AF_BRIDGE 表示多协议桥接的socket
6654ad52e57S裕依2439     Bridge = 7,
6664ad52e57S裕依2439     /// AF_ATMPVC 表示ATM PVCs的socket
6674ad52e57S裕依2439     Atmpvc = 8,
6684ad52e57S裕依2439     /// AF_X25 表示X.25的socket
6694ad52e57S裕依2439     X25 = 9,
6704ad52e57S裕依2439     /// AF_INET6 表示IPv6的socket
6714ad52e57S裕依2439     INet6 = 10,
6724ad52e57S裕依2439     /// AF_ROSE 表示AMPR ROSE的socket
6734ad52e57S裕依2439     Rose = 11,
6744ad52e57S裕依2439     /// AF_DECnet Reserved for DECnet project
6754ad52e57S裕依2439     Decnet = 12,
6764ad52e57S裕依2439     /// AF_NETBEUI Reserved for 802.2LLC project
6774ad52e57S裕依2439     Netbeui = 13,
6784ad52e57S裕依2439     /// AF_SECURITY 表示Security callback的伪AF
6794ad52e57S裕依2439     Security = 14,
6804ad52e57S裕依2439     /// AF_KEY 表示Key management API
6814ad52e57S裕依2439     Key = 15,
6824ad52e57S裕依2439     /// AF_NETLINK 表示Netlink的socket
6834ad52e57S裕依2439     Netlink = 16,
6844ad52e57S裕依2439     /// AF_PACKET 表示Low level packet interface
6854ad52e57S裕依2439     Packet = 17,
6864ad52e57S裕依2439     /// AF_ASH 表示Ash
6874ad52e57S裕依2439     Ash = 18,
6884ad52e57S裕依2439     /// AF_ECONET 表示Acorn Econet
6894ad52e57S裕依2439     Econet = 19,
6904ad52e57S裕依2439     /// AF_ATMSVC 表示ATM SVCs
6914ad52e57S裕依2439     Atmsvc = 20,
6924ad52e57S裕依2439     /// AF_RDS 表示Reliable Datagram Sockets
6934ad52e57S裕依2439     Rds = 21,
6944ad52e57S裕依2439     /// AF_SNA 表示Linux SNA Project
6954ad52e57S裕依2439     Sna = 22,
6964ad52e57S裕依2439     /// AF_IRDA 表示IRDA sockets
6974ad52e57S裕依2439     Irda = 23,
6984ad52e57S裕依2439     /// AF_PPPOX 表示PPPoX sockets
6994ad52e57S裕依2439     Pppox = 24,
7004ad52e57S裕依2439     /// AF_WANPIPE 表示WANPIPE API sockets
7014ad52e57S裕依2439     WanPipe = 25,
7024ad52e57S裕依2439     /// AF_LLC 表示Linux LLC
7034ad52e57S裕依2439     Llc = 26,
7044ad52e57S裕依2439     /// AF_IB 表示Native InfiniBand address
7054ad52e57S裕依2439     /// 介绍:https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/9/html-single/configuring_infiniband_and_rdma_networks/index#understanding-infiniband-and-rdma_configuring-infiniband-and-rdma-networks
7064ad52e57S裕依2439     Ib = 27,
7074ad52e57S裕依2439     /// AF_MPLS 表示MPLS
7084ad52e57S裕依2439     Mpls = 28,
7094ad52e57S裕依2439     /// AF_CAN 表示Controller Area Network
7104ad52e57S裕依2439     Can = 29,
7114ad52e57S裕依2439     /// AF_TIPC 表示TIPC sockets
7124ad52e57S裕依2439     Tipc = 30,
7134ad52e57S裕依2439     /// AF_BLUETOOTH 表示Bluetooth sockets
7144ad52e57S裕依2439     Bluetooth = 31,
7154ad52e57S裕依2439     /// AF_IUCV 表示IUCV sockets
7164ad52e57S裕依2439     Iucv = 32,
7174ad52e57S裕依2439     /// AF_RXRPC 表示RxRPC sockets
7184ad52e57S裕依2439     Rxrpc = 33,
7194ad52e57S裕依2439     /// AF_ISDN 表示mISDN sockets
7204ad52e57S裕依2439     Isdn = 34,
7214ad52e57S裕依2439     /// AF_PHONET 表示Phonet sockets
7224ad52e57S裕依2439     Phonet = 35,
7234ad52e57S裕依2439     /// AF_IEEE802154 表示IEEE 802.15.4 sockets
7244ad52e57S裕依2439     Ieee802154 = 36,
7254ad52e57S裕依2439     /// AF_CAIF 表示CAIF sockets
7264ad52e57S裕依2439     Caif = 37,
7274ad52e57S裕依2439     /// AF_ALG 表示Algorithm sockets
7284ad52e57S裕依2439     Alg = 38,
7294ad52e57S裕依2439     /// AF_NFC 表示NFC sockets
7304ad52e57S裕依2439     Nfc = 39,
7314ad52e57S裕依2439     /// AF_VSOCK 表示vSockets
7324ad52e57S裕依2439     Vsock = 40,
7334ad52e57S裕依2439     /// AF_KCM 表示Kernel Connection Multiplexor
7344ad52e57S裕依2439     Kcm = 41,
7354ad52e57S裕依2439     /// AF_QIPCRTR 表示Qualcomm IPC Router
7364ad52e57S裕依2439     Qipcrtr = 42,
7374ad52e57S裕依2439     /// AF_SMC 表示SMC-R sockets.
7384ad52e57S裕依2439     /// reserve number for PF_SMC protocol family that reuses AF_INET address family
7394ad52e57S裕依2439     Smc = 43,
7404ad52e57S裕依2439     /// AF_XDP 表示XDP sockets
7414ad52e57S裕依2439     Xdp = 44,
7424ad52e57S裕依2439     /// AF_MCTP 表示Management Component Transport Protocol
7434ad52e57S裕依2439     Mctp = 45,
7444ad52e57S裕依2439     /// AF_MAX 表示最大的地址族
7454ad52e57S裕依2439     Max = 46,
7464ad52e57S裕依2439 }
7474ad52e57S裕依2439 
7484ad52e57S裕依2439 impl TryFrom<u16> for AddressFamily {
7494ad52e57S裕依2439     type Error = SystemError;
try_from(x: u16) -> Result<Self, Self::Error>7504ad52e57S裕依2439     fn try_from(x: u16) -> Result<Self, Self::Error> {
7514ad52e57S裕依2439         use num_traits::FromPrimitive;
752b5b571e0SLoGin         return <Self as FromPrimitive>::from_u16(x).ok_or(SystemError::EINVAL);
7534ad52e57S裕依2439     }
7544ad52e57S裕依2439 }
7554ad52e57S裕依2439 
7564ad52e57S裕依2439 /// @brief posix套接字类型的枚举(这些值与linux内核中的值一致)
7574ad52e57S裕依2439 #[derive(Debug, Clone, Copy, PartialEq, Eq, FromPrimitive, ToPrimitive)]
7584ad52e57S裕依2439 pub enum PosixSocketType {
7594ad52e57S裕依2439     Stream = 1,
7604ad52e57S裕依2439     Datagram = 2,
7614ad52e57S裕依2439     Raw = 3,
7624ad52e57S裕依2439     Rdm = 4,
7634ad52e57S裕依2439     SeqPacket = 5,
7644ad52e57S裕依2439     Dccp = 6,
7654ad52e57S裕依2439     Packet = 10,
7664ad52e57S裕依2439 }
7674ad52e57S裕依2439 
7684ad52e57S裕依2439 impl TryFrom<u8> for PosixSocketType {
7694ad52e57S裕依2439     type Error = SystemError;
try_from(x: u8) -> Result<Self, Self::Error>7704ad52e57S裕依2439     fn try_from(x: u8) -> Result<Self, Self::Error> {
7714ad52e57S裕依2439         use num_traits::FromPrimitive;
772b5b571e0SLoGin         return <Self as FromPrimitive>::from_u8(x).ok_or(SystemError::EINVAL);
7734ad52e57S裕依2439     }
7744ad52e57S裕依2439 }
7754ad52e57S裕依2439 
7764ad52e57S裕依2439 /// ### 为socket提供无锁的poll方法
7774ad52e57S裕依2439 ///
7784ad52e57S裕依2439 /// 因为在网卡中断中,需要轮询socket的状态,如果使用socket文件或者其inode来poll
7794ad52e57S裕依2439 /// 在当前的设计,会必然死锁,所以引用这一个设计来解决,提供无��的poll
7804ad52e57S裕依2439 pub struct SocketPollMethod;
7814ad52e57S裕依2439 
7824ad52e57S裕依2439 impl SocketPollMethod {
poll(socket: &socket::Socket, handle_item: &SocketHandleItem) -> EPollEventType783*634349e0SLoGin     pub fn poll(socket: &socket::Socket, handle_item: &SocketHandleItem) -> EPollEventType {
784*634349e0SLoGin         let shutdown = handle_item.shutdown_type();
7854ad52e57S裕依2439         match socket {
7864ad52e57S裕依2439             socket::Socket::Udp(udp) => Self::udp_poll(udp, shutdown),
787*634349e0SLoGin             socket::Socket::Tcp(tcp) => Self::tcp_poll(tcp, shutdown, handle_item.is_posix_listen),
78893c37970Ssun5etop             socket::Socket::Raw(raw) => Self::raw_poll(raw, shutdown),
7894ad52e57S裕依2439             _ => todo!(),
7904ad52e57S裕依2439         }
7914ad52e57S裕依2439     }
7924ad52e57S裕依2439 
tcp_poll( socket: &tcp::Socket, shutdown: ShutdownType, is_posix_listen: bool, ) -> EPollEventType793*634349e0SLoGin     pub fn tcp_poll(
794*634349e0SLoGin         socket: &tcp::Socket,
795*634349e0SLoGin         shutdown: ShutdownType,
796*634349e0SLoGin         is_posix_listen: bool,
797*634349e0SLoGin     ) -> EPollEventType {
7984ad52e57S裕依2439         let mut events = EPollEventType::empty();
799*634349e0SLoGin         // debug!("enter tcp_poll! is_posix_listen:{}", is_posix_listen);
800*634349e0SLoGin         // 处理listen的socket
801*634349e0SLoGin         if is_posix_listen {
802*634349e0SLoGin             // 如果是listen的socket,那么只有EPOLLIN和EPOLLRDNORM
803*634349e0SLoGin             if socket.is_active() {
804*634349e0SLoGin                 events.insert(EPollEventType::EPOLL_LISTEN_CAN_ACCEPT);
805*634349e0SLoGin             }
806*634349e0SLoGin 
807*634349e0SLoGin             // debug!("tcp_poll listen socket! events:{:?}", events);
8084ad52e57S裕依2439             return events;
8094ad52e57S裕依2439         }
8104ad52e57S裕依2439 
811*634349e0SLoGin         let state = socket.state();
812*634349e0SLoGin 
813*634349e0SLoGin         if shutdown == ShutdownType::SHUTDOWN_MASK || state == tcp::State::Closed {
814*634349e0SLoGin             events.insert(EPollEventType::EPOLLHUP);
8154ad52e57S裕依2439         }
816*634349e0SLoGin 
8174ad52e57S裕依2439         if shutdown.contains(ShutdownType::RCV_SHUTDOWN) {
8184ad52e57S裕依2439             events.insert(
8194ad52e57S裕依2439                 EPollEventType::EPOLLIN | EPollEventType::EPOLLRDNORM | EPollEventType::EPOLLRDHUP,
8204ad52e57S裕依2439             );
8214ad52e57S裕依2439         }
8224ad52e57S裕依2439 
823*634349e0SLoGin         // Connected or passive Fast Open socket?
8244ad52e57S裕依2439         if state != tcp::State::SynSent && state != tcp::State::SynReceived {
8254ad52e57S裕依2439             // socket有可读数据
8264ad52e57S裕依2439             if socket.can_recv() {
8274ad52e57S裕依2439                 events.insert(EPollEventType::EPOLLIN | EPollEventType::EPOLLRDNORM);
8284ad52e57S裕依2439             }
8294ad52e57S裕依2439 
8304ad52e57S裕依2439             if !(shutdown.contains(ShutdownType::SEND_SHUTDOWN)) {
831*634349e0SLoGin                 // 缓冲区可写(这里判断可写的逻辑好像跟linux不太一样)
8324ad52e57S裕依2439                 if socket.send_queue() < socket.send_capacity() {
8334ad52e57S裕依2439                     events.insert(EPollEventType::EPOLLOUT | EPollEventType::EPOLLWRNORM);
8344ad52e57S裕依2439                 } else {
835*634349e0SLoGin                     // TODO:触发缓冲区已满的信号SIGIO
836*634349e0SLoGin                     todo!("A signal SIGIO that the buffer is full needs to be sent");
8374ad52e57S裕依2439                 }
8384ad52e57S裕依2439             } else {
8394ad52e57S裕依2439                 // 如果我们的socket关闭了SEND_SHUTDOWN,epoll事件就是EPOLLOUT
8404ad52e57S裕依2439                 events.insert(EPollEventType::EPOLLOUT | EPollEventType::EPOLLWRNORM);
8414ad52e57S裕依2439             }
8424ad52e57S裕依2439         } else if state == tcp::State::SynSent {
8434ad52e57S裕依2439             events.insert(EPollEventType::EPOLLOUT | EPollEventType::EPOLLWRNORM);
8444ad52e57S裕依2439         }
8454ad52e57S裕依2439 
8464ad52e57S裕依2439         // socket发生错误
847*634349e0SLoGin         // TODO: 这里的逻辑可能有问题,需要进一步验证是否is_active()==false就代表socket发生错误
8484ad52e57S裕依2439         if !socket.is_active() {
8494ad52e57S裕依2439             events.insert(EPollEventType::EPOLLERR);
8504ad52e57S裕依2439         }
8514ad52e57S裕依2439 
8524ad52e57S裕依2439         events
8534ad52e57S裕依2439     }
8544ad52e57S裕依2439 
udp_poll(socket: &udp::Socket, shutdown: ShutdownType) -> EPollEventType8554ad52e57S裕依2439     pub fn udp_poll(socket: &udp::Socket, shutdown: ShutdownType) -> EPollEventType {
8564ad52e57S裕依2439         let mut event = EPollEventType::empty();
8574ad52e57S裕依2439 
8584ad52e57S裕依2439         if shutdown.contains(ShutdownType::RCV_SHUTDOWN) {
8594ad52e57S裕依2439             event.insert(
8604ad52e57S裕依2439                 EPollEventType::EPOLLRDHUP | EPollEventType::EPOLLIN | EPollEventType::EPOLLRDNORM,
8614ad52e57S裕依2439             );
8624ad52e57S裕依2439         }
8634ad52e57S裕依2439         if shutdown.contains(ShutdownType::SHUTDOWN_MASK) {
8644ad52e57S裕依2439             event.insert(EPollEventType::EPOLLHUP);
8654ad52e57S裕依2439         }
8664ad52e57S裕依2439 
8674ad52e57S裕依2439         if socket.can_recv() {
8684ad52e57S裕依2439             event.insert(EPollEventType::EPOLLIN | EPollEventType::EPOLLRDNORM);
8694ad52e57S裕依2439         }
8704ad52e57S裕依2439 
8714ad52e57S裕依2439         if socket.can_send() {
8724ad52e57S裕依2439             event.insert(
8734ad52e57S裕依2439                 EPollEventType::EPOLLOUT
8744ad52e57S裕依2439                     | EPollEventType::EPOLLWRNORM
8754ad52e57S裕依2439                     | EPollEventType::EPOLLWRBAND,
8764ad52e57S裕依2439             );
8774ad52e57S裕依2439         } else {
8784ad52e57S裕依2439             // TODO: 缓冲区空间不够,需要使用信号处理
8794ad52e57S裕依2439             todo!()
8804ad52e57S裕依2439         }
8814ad52e57S裕依2439 
8824ad52e57S裕依2439         return event;
8834ad52e57S裕依2439     }
88493c37970Ssun5etop 
raw_poll(socket: &raw::Socket, shutdown: ShutdownType) -> EPollEventType88593c37970Ssun5etop     pub fn raw_poll(socket: &raw::Socket, shutdown: ShutdownType) -> EPollEventType {
8862eab6dd7S曾俊         //debug!("enter raw_poll!");
88793c37970Ssun5etop         let mut event = EPollEventType::empty();
88893c37970Ssun5etop 
88993c37970Ssun5etop         if shutdown.contains(ShutdownType::RCV_SHUTDOWN) {
89093c37970Ssun5etop             event.insert(
89193c37970Ssun5etop                 EPollEventType::EPOLLRDHUP | EPollEventType::EPOLLIN | EPollEventType::EPOLLRDNORM,
89293c37970Ssun5etop             );
89393c37970Ssun5etop         }
89493c37970Ssun5etop         if shutdown.contains(ShutdownType::SHUTDOWN_MASK) {
89593c37970Ssun5etop             event.insert(EPollEventType::EPOLLHUP);
89693c37970Ssun5etop         }
89793c37970Ssun5etop 
89893c37970Ssun5etop         if socket.can_recv() {
8992eab6dd7S曾俊             //debug!("poll can recv!");
90093c37970Ssun5etop             event.insert(EPollEventType::EPOLLIN | EPollEventType::EPOLLRDNORM);
90193c37970Ssun5etop         } else {
9022eab6dd7S曾俊             //debug!("poll can not recv!");
90393c37970Ssun5etop         }
90493c37970Ssun5etop 
90593c37970Ssun5etop         if socket.can_send() {
9062eab6dd7S曾俊             //debug!("poll can send!");
90793c37970Ssun5etop             event.insert(
90893c37970Ssun5etop                 EPollEventType::EPOLLOUT
90993c37970Ssun5etop                     | EPollEventType::EPOLLWRNORM
91093c37970Ssun5etop                     | EPollEventType::EPOLLWRBAND,
91193c37970Ssun5etop             );
91293c37970Ssun5etop         } else {
9132eab6dd7S曾俊             //debug!("poll can not send!");
91493c37970Ssun5etop             // TODO: 缓冲区空间不够,需要使用信号处理
91593c37970Ssun5etop             todo!()
91693c37970Ssun5etop         }
91793c37970Ssun5etop         return event;
91893c37970Ssun5etop     }
9194ad52e57S裕依2439 }
920