Skip to main content

hiver_runtime/driver/
queue.rs

1//! Queue entries for I/O operations
2//! I/O操作的队列条目
3//!
4//! This module defines the submission and completion queue entries
5//! used by the driver for asynchronous I/O operations.
6//!
7//! 本模块定义driver用于异步I/O操作的提交和完成队列条目。
8
9use std::ptr::NonNull;
10
11/// I/O operation state machine
12/// I/O操作状态机
13///
14/// Tracks the lifecycle of an I/O operation from submission to completion.
15/// 跟踪I/O操作从提交到完成的生命周期。
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17#[repr(u8)]
18pub enum IoState {
19    /// Operation is idle, not yet submitted / 操作空闲,尚未提交
20    Idle = 0,
21    /// Operation has been submitted to kernel / 操作已提交给内核
22    Submitted = 1,
23    /// Operation is in progress / 操作进行中
24    InProgress = 2,
25    /// Operation completed successfully / 操作成功完成
26    Completed = 3,
27    /// Operation was cancelled / 操作被取消
28    Cancelled = 4,
29    /// Operation failed / 操作失败
30    Failed = 5,
31}
32
33impl IoState {
34    /// Check if the operation is finished (completed, cancelled, or failed)
35    /// 检查操作是否已完成(成功、取消或失败)
36    #[must_use]
37    pub const fn is_finished(self) -> bool {
38        matches!(self, Self::Completed | Self::Cancelled | Self::Failed)
39    }
40
41    /// Check if the operation is in progress (submitted or in progress)
42    /// 检查操作是否进行中(已提交或进行中)
43    #[must_use]
44    pub const fn is_in_progress(self) -> bool {
45        matches!(self, Self::Submitted | Self::InProgress)
46    }
47
48    /// Check if the operation succeeded
49    /// 检查操作是否成功
50    #[must_use]
51    pub fn is_success(self) -> bool {
52        matches!(self, Self::Completed)
53    }
54}
55
56/// Submission queue entry
57/// 提交队列条目
58///
59/// Represents a single I/O operation to be submitted to the kernel.
60/// 表示要提交给内核的单个I/O操作。
61///
62/// # Safety / 安全性
63///
64/// - `buf_ptr` must be valid for `buf_len` bytes if non-null
65/// - The buffer must remain valid until the operation completes
66/// - 如果非空,`buf_ptr` 必须对 `buf_len` 字节有效
67/// - 缓冲区必须在操作完成前保持有效
68#[derive(Debug, Clone)]
69pub struct SubmitEntry {
70    /// File descriptor to operate on / 操作的文件描述符
71    pub fd: i32,
72    /// Operation opcode (READ, WRITE, etc.) / 操作操作码
73    pub opcode: u8,
74    /// Operation flags / 操作标志
75    pub flags: u16,
76    /// User data for completion correlation (opaque pointer)
77    /// 用于完成关联的用户数据(不透明指针)
78    pub user_data: u64,
79    /// Buffer pointer / 缓冲区指针
80    pub buf_ptr: Option<NonNull<u8>>,
81    /// Buffer length in bytes / 缓冲区长度(字节)
82    pub buf_len: u32,
83    /// Offset for file operations / 文件操作的偏移量
84    pub offset: u64,
85    /// Address for connect/accept operations / 连接/接受操作的地址
86    pub addr: Option<SockAddr>,
87}
88
89/// Socket address storage for connection operations
90/// 连接操作的套接字地址存储
91#[derive(Debug, Clone)]
92pub struct SockAddr {
93    /// The raw socket address / 原始套接字地址
94    pub storage: libc::sockaddr_storage,
95    /// Length of the address / 地址长度
96    pub len: libc::socklen_t,
97}
98
99impl SockAddr {
100    /// Create a new socket address from a raw sockaddr_storage
101    /// 从原始sockaddr_storage创建新的套接字地址
102    ///
103    /// # Safety / 安全性
104    ///
105    /// The storage must contain a valid socket address.
106    /// storage必须包含有效的套接字地址。
107    pub unsafe fn from_raw(storage: libc::sockaddr_storage, len: libc::socklen_t) -> Self {
108        Self { storage, len }
109    }
110}
111
112impl SubmitEntry {
113    /// Create a new submission entry
114    /// 创建新的提交条目
115    #[must_use]
116    pub const fn new(fd: i32, opcode: u8, user_data: u64) -> Self {
117        Self {
118            fd,
119            opcode,
120            flags: 0,
121            user_data,
122            buf_ptr: None,
123            buf_len: 0,
124            offset: 0,
125            addr: None,
126        }
127    }
128
129    /// Create a read operation entry
130    /// 创建读操作条目
131    ///
132    /// # Safety / 安全性
133    ///
134    /// `buf` must be valid for reads and remain valid until completion.
135    /// `buf` 必须对读取有效并在完成前保持有效。
136    #[must_use]
137    pub unsafe fn read(fd: i32, buf: *mut u8, buf_len: u32, user_data: u64) -> Self {
138        Self {
139            fd,
140            opcode: super::opcode::READ,
141            flags: 0,
142            user_data,
143            buf_ptr: NonNull::new(buf),
144            buf_len,
145            offset: 0,
146            addr: None,
147        }
148    }
149
150    /// Create a write operation entry
151    /// 创建写操作条目
152    ///
153    /// # Safety / 安全性
154    ///
155    /// `buf` must be valid for reads and remain valid until completion.
156    /// `buf` 必须对读取有效并在完成前保持有效。
157    #[must_use]
158    pub unsafe fn write(fd: i32, buf: *const u8, buf_len: u32, user_data: u64) -> Self {
159        Self {
160            fd,
161            opcode: super::opcode::WRITE,
162            flags: 0,
163            user_data,
164            buf_ptr: NonNull::new(buf.cast_mut()),
165            buf_len,
166            offset: 0,
167            addr: None,
168        }
169    }
170
171    /// Set the buffer for this operation
172    /// 为此操作设置缓冲区
173    ///
174    /// # Safety / 安全性
175    ///
176    /// `buf` must be valid for `buf_len` bytes.
177    /// `buf` 必须对 `buf_len` 字节有效。
178    #[must_use]
179    pub unsafe fn with_buffer(mut self, buf: *mut u8, buf_len: u32) -> Self {
180        self.buf_ptr = NonNull::new(buf);
181        self.buf_len = buf_len;
182        self
183    }
184
185    /// Set the offset for file operations
186    /// 为文件操作设置偏移量
187    #[must_use]
188    pub const fn with_offset(mut self, offset: u64) -> Self {
189        self.offset = offset;
190        self
191    }
192
193    /// Set operation flags
194    /// 设置操作标志
195    #[must_use]
196    pub const fn with_flags(mut self, flags: u16) -> Self {
197        self.flags = flags;
198        self
199    }
200
201    /// Set socket address for connect/accept
202    /// 为connect/accept设置套接字地址
203    #[must_use]
204    pub fn with_addr(mut self, addr: SockAddr) -> Self {
205        self.addr = Some(addr);
206        self
207    }
208
209    /// Get the buffer as a slice if available
210    /// 如果可用,获取缓冲区的切片
211    ///
212    /// # Safety / 安全性
213    ///
214    /// The returned slice is only valid if the buffer is still alive.
215    /// 返回的切片仅在缓冲区仍然存活时有效。
216    #[must_use]
217    pub unsafe fn buffer(&self) -> Option<&[u8]> {
218        self.buf_ptr
219            .map(|ptr| std::slice::from_raw_parts(ptr.as_ptr(), self.buf_len as usize))
220    }
221
222    /// Get the buffer as a mutable slice if available
223    /// 如果可用,获取缓冲区的可变切片
224    ///
225    /// # Safety / 安全性
226    ///
227    /// The returned slice is only valid if the buffer is still alive and mutable.
228    /// 返回的切片仅在缓冲区仍然存活且可变时有效。
229    #[must_use]
230    pub unsafe fn buffer_mut(&self) -> Option<&mut [u8]> {
231        self.buf_ptr
232            .map(|ptr| std::slice::from_raw_parts_mut(ptr.as_ptr(), self.buf_len as usize))
233    }
234}
235
236// Safety: SubmitEntry can be sent between threads if the underlying buffer is valid
237// unsafe impl Send for SubmitEntry {}
238//
239// Note: We don't implement Send automatically because the buf_ptr may reference
240// data that isn't Send-safe. Users must ensure thread safety.
241
242/// Completion queue entry
243/// 完成队列条目
244///
245/// Represents a completed I/O operation returned from the kernel.
246/// 表示从内核返回的已完成的I/O操作。
247#[derive(Debug, Clone, Copy)]
248pub struct CompletionEntry {
249    /// User data from the corresponding submission / 来自相应提交的用户数据
250    pub user_data: u64,
251    /// Result code: positive = bytes transferred, negative = error code
252    /// 结果码:正数=传输的字节数,负数=错误码
253    pub result: i32,
254    /// Operation flags / 操作标志
255    pub flags: u32,
256}
257
258impl CompletionEntry {
259    /// Create a new completion entry
260    /// 创建新的完成条目
261    #[must_use]
262    pub const fn new(user_data: u64, result: i32, flags: u32) -> Self {
263        Self {
264            user_data,
265            result,
266            flags,
267        }
268    }
269
270    /// Check if the operation succeeded
271    /// 检查操作是否成功
272    #[must_use]
273    pub const fn is_success(self) -> bool {
274        self.result >= 0
275    }
276
277    /// Check if the operation failed
278    /// 检查操作是否失败
279    #[must_use]
280    pub const fn is_error(self) -> bool {
281        self.result < 0
282    }
283
284    /// Get the number of bytes transferred
285    /// 获取传输的字节数
286    ///
287    /// Returns `None` if the operation failed.
288    /// 如果操作失败则返回 `None`。
289    #[must_use]
290    pub const fn bytes_transferred(self) -> Option<u32> {
291        if self.result >= 0 {
292            Some(self.result as u32)
293        } else {
294            None
295        }
296    }
297
298    /// Get the error code if the operation failed
299    /// 如果操作失败,获取错误码
300    #[must_use]
301    pub const fn error_code(self) -> Option<i32> {
302        if self.result < 0 {
303            Some(-self.result)
304        } else {
305            None
306        }
307    }
308
309    /// Convert the result to a `std::io::Result`
310    /// 将结果转换为 `std::io::Result`
311    ///
312    /// Returns `Ok(bytes_transferred)` on success, `Err(error)` on failure.
313    /// 成功返回 `Ok(bytes_transferred)`,失败返回 `Err(error)`。
314    #[must_use = "the result of the operation should be checked"]
315    pub fn into_result(self) -> std::io::Result<u32> {
316        if self.result >= 0 {
317            Ok(self.result as u32)
318        } else {
319            Err(std::io::Error::from_raw_os_error(-self.result))
320        }
321    }
322}
323
324#[cfg(test)]
325mod tests {
326    use super::*;
327
328    #[test]
329    fn test_io_state() {
330        assert!(IoState::Completed.is_finished());
331        assert!(IoState::Cancelled.is_finished());
332        assert!(IoState::Failed.is_finished());
333        assert!(!IoState::Idle.is_finished());
334        assert!(!IoState::Submitted.is_finished());
335
336        assert!(IoState::Submitted.is_in_progress());
337        assert!(IoState::InProgress.is_in_progress());
338        assert!(!IoState::Idle.is_in_progress());
339    }
340
341    #[test]
342    fn test_completion_entry() {
343        // Success case / 成功情况
344        let entry = CompletionEntry::new(123, 1024, 0);
345        assert!(entry.is_success());
346        assert!(!entry.is_error());
347        assert_eq!(entry.bytes_transferred(), Some(1024));
348        assert_eq!(entry.into_result().unwrap(), 1024);
349
350        // Error case / 错误情况
351        let entry = CompletionEntry::new(456, -2, 0);
352        assert!(!entry.is_success());
353        assert!(entry.is_error());
354        assert_eq!(entry.bytes_transferred(), None);
355        assert_eq!(entry.error_code(), Some(2));
356    }
357
358    #[test]
359    fn test_submit_entry_builder() {
360        let buf = [0u8; 1024];
361        let entry = unsafe {
362            SubmitEntry::read(0, buf.as_ptr() as *mut u8, 1024, 42)
363                .with_offset(100)
364                .with_flags(0x0001)
365        };
366
367        assert_eq!(entry.fd, 0);
368        assert_eq!(entry.opcode, super::super::opcode::READ);
369        assert_eq!(entry.user_data, 42);
370        assert_eq!(entry.buf_len, 1024);
371        assert_eq!(entry.offset, 100);
372        assert_eq!(entry.flags, 0x0001);
373    }
374
375    #[test]
376    fn test_interest_builder() {
377        let interest = crate::driver::Interest::readable()
378            .with_writable()
379            .with_edge();
380
381        assert!(interest.readable);
382        assert!(interest.writable);
383        assert!(interest.edge);
384    }
385}