eventfd.rs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. use crate::filesystem::vfs::file::{File, FileMode};
  2. use crate::filesystem::vfs::syscall::ModeType;
  3. use crate::filesystem::vfs::{FilePrivateData, FileSystem, FileType, IndexNode, Metadata};
  4. use crate::libs::spinlock::{SpinLock, SpinLockGuard};
  5. use crate::libs::wait_queue::WaitQueue;
  6. use crate::net::event_poll::{EPollEventType, EPollItem, EventPoll, KernelIoctlData};
  7. use crate::process::ProcessManager;
  8. use crate::syscall::Syscall;
  9. use alloc::collections::LinkedList;
  10. use alloc::string::String;
  11. use alloc::sync::Arc;
  12. use alloc::sync::Weak;
  13. use alloc::vec::Vec;
  14. use core::any::Any;
  15. use ida::IdAllocator;
  16. use system_error::SystemError;
  17. static EVENTFD_ID_ALLOCATOR: SpinLock<IdAllocator> =
  18. SpinLock::new(IdAllocator::new(0, u32::MAX as usize).unwrap());
  19. bitflags! {
  20. pub struct EventFdFlags: u32{
  21. /// Provide semaphore-like semantics for reads from the new
  22. /// file descriptor.
  23. const EFD_SEMAPHORE = 0o1;
  24. /// Set the close-on-exec (FD_CLOEXEC) flag on the new file
  25. /// descriptor
  26. const EFD_CLOEXEC = 0o2000000;
  27. /// Set the O_NONBLOCK file status flag on the open file
  28. /// description (see open(2)) referred to by the new file
  29. /// descriptor
  30. const EFD_NONBLOCK = 0o0004000;
  31. }
  32. }
  33. #[derive(Debug)]
  34. pub struct EventFd {
  35. count: u64,
  36. flags: EventFdFlags,
  37. #[allow(unused)]
  38. id: u32,
  39. }
  40. impl EventFd {
  41. pub fn new(count: u64, flags: EventFdFlags, id: u32) -> Self {
  42. EventFd { count, flags, id }
  43. }
  44. }
  45. #[derive(Debug)]
  46. pub struct EventFdInode {
  47. eventfd: SpinLock<EventFd>,
  48. wait_queue: WaitQueue,
  49. epitems: SpinLock<LinkedList<Arc<EPollItem>>>,
  50. }
  51. impl EventFdInode {
  52. pub fn new(eventfd: EventFd) -> Self {
  53. EventFdInode {
  54. eventfd: SpinLock::new(eventfd),
  55. wait_queue: WaitQueue::default(),
  56. epitems: SpinLock::new(LinkedList::new()),
  57. }
  58. }
  59. pub fn remove_epoll(&self, epoll: &Weak<SpinLock<EventPoll>>) -> Result<(), SystemError> {
  60. let is_remove = !self
  61. .epitems
  62. .lock_irqsave()
  63. .extract_if(|x| x.epoll().ptr_eq(epoll))
  64. .collect::<Vec<_>>()
  65. .is_empty();
  66. if is_remove {
  67. return Ok(());
  68. }
  69. Err(SystemError::ENOENT)
  70. }
  71. }
  72. impl IndexNode for EventFdInode {
  73. fn open(
  74. &self,
  75. _data: SpinLockGuard<FilePrivateData>,
  76. _mode: &FileMode,
  77. ) -> Result<(), SystemError> {
  78. Ok(())
  79. }
  80. fn close(&self, _data: SpinLockGuard<FilePrivateData>) -> Result<(), SystemError> {
  81. Ok(())
  82. }
  83. /// # 从 counter 里读取一个 8 字节的int值
  84. ///
  85. /// 1. counter !=0
  86. /// - EFD_SEMAPHORE 如果没有被设置,从 eventfd read,会得到 counter,并将它归0
  87. /// - EFD_SEMAPHORE 如果被设置,从 eventfd read,会得到值 1,并将 counter - 1
  88. /// 2. counter == 0
  89. /// - EFD_NONBLOCK 如果被设置,那么会以 EAGAIN 的错失败
  90. /// - 否则 read 会被阻塞,直到为非0。
  91. fn read_at(
  92. &self,
  93. _offset: usize,
  94. len: usize,
  95. buf: &mut [u8],
  96. data: SpinLockGuard<FilePrivateData>,
  97. ) -> Result<usize, SystemError> {
  98. if len < 8 {
  99. return Err(SystemError::EINVAL);
  100. }
  101. let mut val = loop {
  102. let val = self.eventfd.lock().count;
  103. if val != 0 {
  104. break val;
  105. }
  106. if self
  107. .eventfd
  108. .lock()
  109. .flags
  110. .contains(EventFdFlags::EFD_NONBLOCK)
  111. {
  112. return Err(SystemError::EAGAIN_OR_EWOULDBLOCK);
  113. }
  114. self.wait_queue.sleep();
  115. };
  116. let mut eventfd = self.eventfd.lock();
  117. if eventfd.flags.contains(EventFdFlags::EFD_SEMAPHORE) {
  118. eventfd.count -= 1;
  119. val = 1;
  120. } else {
  121. eventfd.count = 0;
  122. }
  123. let val_bytes = val.to_ne_bytes();
  124. buf[..8].copy_from_slice(&val_bytes);
  125. let pollflag = EPollEventType::from_bits_truncate(self.poll(&data)? as u32);
  126. // 唤醒epoll中等待的进程
  127. EventPoll::wakeup_epoll(&self.epitems, pollflag)?;
  128. return Ok(8);
  129. }
  130. /// # 把一个 8 字节的int值写入到 counter 里
  131. ///
  132. /// - counter 最大值是 2^64 - 1
  133. /// - 如果写入时会发生溢出,则write会被阻塞
  134. /// - 如果 EFD_NONBLOCK 被设置,那么以 EAGAIN 失败
  135. /// - 以不合法的值写入时,会以 EINVAL 失败
  136. /// - 比如 0xffffffffffffffff 不合法
  137. /// - 比如 写入的值 size 小于8字节
  138. fn write_at(
  139. &self,
  140. _offset: usize,
  141. len: usize,
  142. buf: &[u8],
  143. data: SpinLockGuard<FilePrivateData>,
  144. ) -> Result<usize, SystemError> {
  145. if len < 8 {
  146. return Err(SystemError::EINVAL);
  147. }
  148. let val = u64::from_ne_bytes(buf[..8].try_into().unwrap());
  149. if val == u64::MAX {
  150. return Err(SystemError::EINVAL);
  151. }
  152. loop {
  153. let eventfd = self.eventfd.lock();
  154. if u64::MAX - eventfd.count > val {
  155. break;
  156. }
  157. // block until a read() is performed on the
  158. // file descriptor, or fails with the error EAGAIN if the
  159. // file descriptor has been made nonblocking.
  160. if eventfd.flags.contains(EventFdFlags::EFD_NONBLOCK) {
  161. return Err(SystemError::EAGAIN_OR_EWOULDBLOCK);
  162. }
  163. drop(eventfd);
  164. self.wait_queue.sleep();
  165. }
  166. let mut eventfd = self.eventfd.lock();
  167. eventfd.count += val;
  168. self.wait_queue.wakeup_all(None);
  169. let pollflag = EPollEventType::from_bits_truncate(self.poll(&data)? as u32);
  170. // 唤醒epoll中等待的进程
  171. EventPoll::wakeup_epoll(&self.epitems, pollflag)?;
  172. return Ok(8);
  173. }
  174. /// # 检查 eventfd 的状态
  175. ///
  176. /// - 如果 counter 的值大于 0 ,那么 fd 的状态就是可读的
  177. /// - 如果能无阻塞地写入一个至少为 1 的值,那么 fd 的状态就是可写的
  178. fn poll(&self, _private_data: &FilePrivateData) -> Result<usize, SystemError> {
  179. let mut events = EPollEventType::empty();
  180. if self.eventfd.lock().count != 0 {
  181. events |= EPollEventType::EPOLLIN | EPollEventType::EPOLLRDNORM;
  182. }
  183. if self.eventfd.lock().count != u64::MAX {
  184. events |= EPollEventType::EPOLLOUT | EPollEventType::EPOLLWRNORM;
  185. }
  186. return Ok(events.bits() as usize);
  187. }
  188. fn metadata(&self) -> Result<Metadata, SystemError> {
  189. let meta = Metadata {
  190. mode: ModeType::from_bits_truncate(0o755),
  191. file_type: FileType::File,
  192. ..Default::default()
  193. };
  194. Ok(meta)
  195. }
  196. fn resize(&self, _len: usize) -> Result<(), SystemError> {
  197. Ok(())
  198. }
  199. fn kernel_ioctl(
  200. &self,
  201. arg: Arc<dyn KernelIoctlData>,
  202. _data: &FilePrivateData,
  203. ) -> Result<usize, SystemError> {
  204. let epitem = arg
  205. .arc_any()
  206. .downcast::<EPollItem>()
  207. .map_err(|_| SystemError::EFAULT)?;
  208. self.epitems.lock().push_back(epitem);
  209. Ok(0)
  210. }
  211. fn fs(&self) -> Arc<dyn FileSystem> {
  212. panic!("EventFd does not have a filesystem")
  213. }
  214. fn as_any_ref(&self) -> &dyn Any {
  215. self
  216. }
  217. fn list(&self) -> Result<Vec<String>, SystemError> {
  218. Err(SystemError::EINVAL)
  219. }
  220. }
  221. impl Syscall {
  222. /// # 创建一个 eventfd 文件描述符
  223. ///
  224. /// ## 参数
  225. /// - `init_val`: u32: eventfd 的初始值
  226. /// - `flags`: u32: eventfd 的标志
  227. ///
  228. /// ## 返回值
  229. /// - `Ok(usize)`: 成功创建的文件描述符
  230. /// - `Err(SystemError)`: 创建失败
  231. ///
  232. /// See: https://man7.org/linux/man-pages/man2/eventfd2.2.html
  233. pub fn sys_eventfd(init_val: u32, flags: u32) -> Result<usize, SystemError> {
  234. let flags = EventFdFlags::from_bits(flags).ok_or(SystemError::EINVAL)?;
  235. let id = EVENTFD_ID_ALLOCATOR
  236. .lock()
  237. .alloc()
  238. .ok_or(SystemError::ENOMEM)? as u32;
  239. let eventfd = EventFd::new(init_val as u64, flags, id);
  240. let inode = Arc::new(EventFdInode::new(eventfd));
  241. let filemode = if flags.contains(EventFdFlags::EFD_CLOEXEC) {
  242. FileMode::O_RDWR | FileMode::O_CLOEXEC
  243. } else {
  244. FileMode::O_RDWR
  245. };
  246. let file = File::new(inode, filemode)?;
  247. let binding = ProcessManager::current_pcb().fd_table();
  248. let mut fd_table_guard = binding.write();
  249. let fd = fd_table_guard.alloc_fd(file, None).map(|x| x as usize);
  250. return fd;
  251. }
  252. }