xref: /DragonOS/kernel/src/filesystem/vfs/syscall.rs (revision c719ddc6312acd7976e0f6fd449a94ff9abad5a6) !
1 use core::ffi::c_void;
2 use core::mem::size_of;
3 
4 use alloc::string::ToString;
5 use alloc::{string::String, sync::Arc, vec::Vec};
6 use system_error::SystemError;
7 
8 use crate::producefs;
9 use crate::{
10     driver::base::{block::SeekFrom, device::device_number::DeviceNumber},
11     filesystem::vfs::{core as Vcore, file::FileDescriptorVec},
12     kerror,
13     libs::rwlock::RwLockWriteGuard,
14     mm::{verify_area, VirtAddr},
15     process::ProcessManager,
16     syscall::{
17         user_access::{self, check_and_clone_cstr, UserBufferWriter},
18         Syscall,
19     },
20     time::PosixTimeSpec,
21 };
22 
23 use super::SuperBlock;
24 use super::{
25     core::{do_mkdir, do_remove_dir, do_unlink_at},
26     fcntl::{AtFlags, FcntlCommand, FD_CLOEXEC},
27     file::{File, FileMode},
28     open::{do_faccessat, do_fchmodat, do_sys_open},
29     utils::{rsplit_path, user_path_at},
30     Dirent, FileType, IndexNode, FSMAKER, MAX_PATHLEN, ROOT_INODE, VFS_MAX_FOLLOW_SYMLINK_TIMES,
31 };
32 // use crate::kdebug;
33 
34 pub const SEEK_SET: u32 = 0;
35 pub const SEEK_CUR: u32 = 1;
36 pub const SEEK_END: u32 = 2;
37 pub const SEEK_MAX: u32 = 3;
38 
39 bitflags! {
40     /// 文件类型和权限
41     #[repr(C)]
42     pub struct ModeType: u32 {
43         /// 掩码
44         const S_IFMT = 0o0_170_000;
45         /// 文件类型
46         const S_IFSOCK = 0o140000;
47         const S_IFLNK = 0o120000;
48         const S_IFREG = 0o100000;
49         const S_IFBLK = 0o060000;
50         const S_IFDIR = 0o040000;
51         const S_IFCHR = 0o020000;
52         const S_IFIFO = 0o010000;
53 
54         const S_ISUID = 0o004000;
55         const S_ISGID = 0o002000;
56         const S_ISVTX = 0o001000;
57         /// 文件用户权限
58         const S_IRWXU = 0o0700;
59         const S_IRUSR = 0o0400;
60         const S_IWUSR = 0o0200;
61         const S_IXUSR = 0o0100;
62         /// 文件组权限
63         const S_IRWXG = 0o0070;
64         const S_IRGRP = 0o0040;
65         const S_IWGRP = 0o0020;
66         const S_IXGRP = 0o0010;
67         /// 文件其他用户权限
68         const S_IRWXO = 0o0007;
69         const S_IROTH = 0o0004;
70         const S_IWOTH = 0o0002;
71         const S_IXOTH = 0o0001;
72 
73         /// 0o777
74         const S_IRWXUGO = Self::S_IRWXU.bits | Self::S_IRWXG.bits | Self::S_IRWXO.bits;
75         /// 0o7777
76         const S_IALLUGO = Self::S_ISUID.bits | Self::S_ISGID.bits | Self::S_ISVTX.bits| Self::S_IRWXUGO.bits;
77         /// 0o444
78         const S_IRUGO = Self::S_IRUSR.bits | Self::S_IRGRP.bits | Self::S_IROTH.bits;
79         /// 0o222
80         const S_IWUGO = Self::S_IWUSR.bits | Self::S_IWGRP.bits | Self::S_IWOTH.bits;
81         /// 0o111
82         const S_IXUGO = Self::S_IXUSR.bits | Self::S_IXGRP.bits | Self::S_IXOTH.bits;
83 
84 
85     }
86 }
87 
88 #[repr(C)]
89 #[derive(Clone, Copy)]
90 /// # 文件信息结构体
91 pub struct PosixKstat {
92     /// 硬件设备ID
93     dev_id: u64,
94     /// inode号
95     inode: u64,
96     /// 硬链接数
97     nlink: u64,
98     /// 文件权限
99     mode: ModeType,
100     /// 所有者用户ID
101     uid: i32,
102     /// 所有者组ID
103     gid: i32,
104     /// 设备ID
105     rdev: i64,
106     /// 文件大小
107     size: i64,
108     /// 文件系统块大小
109     blcok_size: i64,
110     /// 分配的512B块数
111     blocks: u64,
112     /// 最后访问时间
113     atime: PosixTimeSpec,
114     /// 最后修改时间
115     mtime: PosixTimeSpec,
116     /// 最后状态变化时间
117     ctime: PosixTimeSpec,
118     /// 用于填充结构体大小的空白数据
119     pub _pad: [i8; 24],
120 }
121 impl PosixKstat {
122     fn new() -> Self {
123         Self {
124             inode: 0,
125             dev_id: 0,
126             mode: ModeType { bits: 0 },
127             nlink: 0,
128             uid: 0,
129             gid: 0,
130             rdev: 0,
131             size: 0,
132             atime: PosixTimeSpec {
133                 tv_sec: 0,
134                 tv_nsec: 0,
135             },
136             mtime: PosixTimeSpec {
137                 tv_sec: 0,
138                 tv_nsec: 0,
139             },
140             ctime: PosixTimeSpec {
141                 tv_sec: 0,
142                 tv_nsec: 0,
143             },
144             blcok_size: 0,
145             blocks: 0,
146             _pad: Default::default(),
147         }
148     }
149 }
150 
151 #[repr(C)]
152 #[derive(Clone, Copy)]
153 /// # 文件信息结构体X
154 pub struct PosixStatx {
155     /* 0x00 */
156     stx_mask: PosixStatxMask,
157     /// 文件系统块大小
158     stx_blksize: u32,
159     /// Flags conveying information about the file [uncond]
160     stx_attributes: StxAttributes,
161     /* 0x10 */
162     /// 硬链接数
163     stx_nlink: u32,
164     /// 所有者用户ID
165     stx_uid: u32,
166     /// 所有者组ID
167     stx_gid: u32,
168     /// 文件权限
169     stx_mode: ModeType,
170 
171     /* 0x20 */
172     /// inode号
173     stx_inode: u64,
174     /// 文件大小
175     stx_size: i64,
176     /// 分配的512B块数
177     stx_blocks: u64,
178     /// Mask to show what's supported in stx_attributes
179     stx_attributes_mask: StxAttributes,
180 
181     /* 0x40 */
182     /// 最后访问时间
183     stx_atime: PosixTimeSpec,
184     /// 文件创建时间
185     stx_btime: PosixTimeSpec,
186     /// 最后状态变化时间
187     stx_ctime: PosixTimeSpec,
188     /// 最后修改时间
189     stx_mtime: PosixTimeSpec,
190 
191     /* 0x80 */
192     /// 主设备ID
193     stx_rdev_major: u32,
194     /// 次设备ID
195     stx_rdev_minor: u32,
196     /// 主硬件设备ID
197     stx_dev_major: u32,
198     /// 次硬件设备ID
199     stx_dev_minor: u32,
200 
201     /* 0x90 */
202     stx_mnt_id: u64,
203     stx_dio_mem_align: u32,
204     stx_dio_offset_align: u32,
205 }
206 impl PosixStatx {
207     fn new() -> Self {
208         Self {
209             stx_mask: PosixStatxMask::STATX_BASIC_STATS,
210             stx_blksize: 0,
211             stx_attributes: StxAttributes::STATX_ATTR_APPEND,
212             stx_nlink: 0,
213             stx_uid: 0,
214             stx_gid: 0,
215             stx_mode: ModeType { bits: 0 },
216             stx_inode: 0,
217             stx_size: 0,
218             stx_blocks: 0,
219             stx_attributes_mask: StxAttributes::STATX_ATTR_APPEND,
220             stx_atime: PosixTimeSpec {
221                 tv_sec: 0,
222                 tv_nsec: 0,
223             },
224             stx_btime: PosixTimeSpec {
225                 tv_sec: 0,
226                 tv_nsec: 0,
227             },
228             stx_ctime: PosixTimeSpec {
229                 tv_sec: 0,
230                 tv_nsec: 0,
231             },
232             stx_mtime: PosixTimeSpec {
233                 tv_sec: 0,
234                 tv_nsec: 0,
235             },
236             stx_rdev_major: 0,
237             stx_rdev_minor: 0,
238             stx_dev_major: 0,
239             stx_dev_minor: 0,
240             stx_mnt_id: 0,
241             stx_dio_mem_align: 0,
242             stx_dio_offset_align: 0,
243         }
244     }
245 }
246 
247 bitflags! {
248     pub struct PosixStatxMask: u32{
249         ///  Want stx_mode & S_IFMT
250         const STATX_TYPE = 0x00000001;
251 
252         /// Want stx_mode & ~S_IFMT
253         const STATX_MODE = 0x00000002;
254 
255         /// Want stx_nlink
256         const STATX_NLINK = 0x00000004;
257 
258         /// Want stx_uid
259         const STATX_UID = 0x00000008;
260 
261         /// Want stx_gid
262         const STATX_GID = 0x00000010;
263 
264         /// Want stx_atime
265         const STATX_ATIME = 0x00000020;
266 
267         /// Want stx_mtime
268         const STATX_MTIME = 0x00000040;
269 
270         /// Want stx_ctime
271         const STATX_CTIME = 0x00000080;
272 
273         /// Want stx_ino
274         const STATX_INO = 0x00000100;
275 
276         /// Want stx_size
277         const STATX_SIZE = 0x00000200;
278 
279         /// Want stx_blocks
280         const STATX_BLOCKS = 0x00000400;
281 
282         /// [All of the above]
283         const STATX_BASIC_STATS = 0x000007ff;
284 
285         /// Want stx_btime
286         const STATX_BTIME = 0x00000800;
287 
288         /// The same as STATX_BASIC_STATS | STATX_BTIME.
289         /// It is deprecated and should not be used.
290         const STATX_ALL = 0x00000fff;
291 
292         /// Want stx_mnt_id (since Linux 5.8)
293         const STATX_MNT_ID = 0x00001000;
294 
295         /// Want stx_dio_mem_align and stx_dio_offset_align
296         /// (since Linux 6.1; support varies by filesystem)
297         const STATX_DIOALIGN = 0x00002000;
298 
299         /// Reserved for future struct statx expansion
300         const STATX_RESERVED = 0x80000000;
301     }
302 }
303 
304 bitflags! {
305     pub struct StxAttributes: u64 {
306         /// 文件被文件系统压缩
307         const STATX_ATTR_COMPRESSED = 0x00000004;
308         /// 文件被标记为不可修改
309         const STATX_ATTR_IMMUTABLE = 0x00000010;
310         /// 文件是只追加写入的
311         const STATX_ATTR_APPEND = 0x00000020;
312         /// 文件不会被备份
313         const STATX_ATTR_NODUMP = 0x00000040;
314         /// 文件需要密钥才能在文件系统中解密
315         const STATX_ATTR_ENCRYPTED = 0x00000800;
316         /// 目录是自动挂载触发器
317         const STATX_ATTR_AUTOMOUNT = 0x00001000;
318         /// 目录是挂载点的根目录
319         const STATX_ATTR_MOUNT_ROOT = 0x00002000;
320         /// 文件受到 Verity 保护
321         const STATX_ATTR_VERITY = 0x00100000;
322         /// 文件当前处于 DAX 状态 CPU直接访问
323         const STATX_ATTR_DAX = 0x00200000;
324     }
325 }
326 
327 #[repr(C)]
328 #[derive(Debug, Clone, Copy)]
329 pub struct PosixStatfs {
330     f_type: u64,
331     f_bsize: u64,
332     f_blocks: u64,
333     f_bfree: u64,
334     f_bavail: u64,
335     f_files: u64,
336     f_ffree: u64,
337     f_fsid: u64,
338     f_namelen: u64,
339     f_frsize: u64,
340     f_flags: u64,
341     f_spare: [u64; 4],
342 }
343 
344 impl From<SuperBlock> for PosixStatfs {
345     fn from(super_block: SuperBlock) -> Self {
346         Self {
347             f_type: super_block.magic.bits,
348             f_bsize: super_block.bsize,
349             f_blocks: super_block.blocks,
350             f_bfree: super_block.bfree,
351             f_bavail: super_block.bavail,
352             f_files: super_block.files,
353             f_ffree: super_block.ffree,
354             f_fsid: super_block.fsid,
355             f_namelen: super_block.namelen,
356             f_frsize: super_block.frsize,
357             f_flags: super_block.flags,
358             f_spare: [0u64; 4],
359         }
360     }
361 }
362 ///
363 ///  Arguments for how openat2(2) should open the target path. If only @flags and
364 ///  @mode are non-zero, then openat2(2) operates very similarly to openat(2).
365 ///
366 ///  However, unlike openat(2), unknown or invalid bits in @flags result in
367 ///  -EINVAL rather than being silently ignored. @mode must be zero unless one of
368 ///  {O_CREAT, O_TMPFILE} are set.
369 ///
370 /// ## 成员变量
371 ///
372 /// - flags: O_* flags.
373 /// - mode: O_CREAT/O_TMPFILE file mode.
374 /// - resolve: RESOLVE_* flags.
375 #[derive(Debug, Clone, Copy)]
376 #[repr(C)]
377 pub struct PosixOpenHow {
378     pub flags: u64,
379     pub mode: u64,
380     pub resolve: u64,
381 }
382 
383 impl PosixOpenHow {
384     #[allow(dead_code)]
385     pub fn new(flags: u64, mode: u64, resolve: u64) -> Self {
386         Self {
387             flags,
388             mode,
389             resolve,
390         }
391     }
392 }
393 
394 #[derive(Debug, Clone, Copy)]
395 pub struct OpenHow {
396     pub o_flags: FileMode,
397     pub mode: ModeType,
398     pub resolve: OpenHowResolve,
399 }
400 
401 impl OpenHow {
402     pub fn new(mut o_flags: FileMode, mut mode: ModeType, resolve: OpenHowResolve) -> Self {
403         if !o_flags.contains(FileMode::O_CREAT) {
404             mode = ModeType::empty();
405         }
406 
407         if o_flags.contains(FileMode::O_PATH) {
408             o_flags = o_flags.intersection(FileMode::O_PATH_FLAGS);
409         }
410 
411         Self {
412             o_flags,
413             mode,
414             resolve,
415         }
416     }
417 }
418 
419 impl From<PosixOpenHow> for OpenHow {
420     fn from(posix_open_how: PosixOpenHow) -> Self {
421         let o_flags = FileMode::from_bits_truncate(posix_open_how.flags as u32);
422         let mode = ModeType::from_bits_truncate(posix_open_how.mode as u32);
423         let resolve = OpenHowResolve::from_bits_truncate(posix_open_how.resolve);
424         return Self::new(o_flags, mode, resolve);
425     }
426 }
427 
428 bitflags! {
429     pub struct OpenHowResolve: u64{
430         /// Block mount-point crossings
431         ///     (including bind-mounts).
432         const RESOLVE_NO_XDEV = 0x01;
433 
434         /// Block traversal through procfs-style
435         ///     "magic-links"
436         const RESOLVE_NO_MAGICLINKS = 0x02;
437 
438         /// Block traversal through all symlinks
439         ///     (implies OEXT_NO_MAGICLINKS)
440         const RESOLVE_NO_SYMLINKS = 0x04;
441         /// Block "lexical" trickery like
442         ///     "..", symlinks, and absolute
443         const RESOLVE_BENEATH = 0x08;
444         /// Make all jumps to "/" and ".."
445         ///     be scoped inside the dirfd
446         ///     (similar to chroot(2)).
447         const RESOLVE_IN_ROOT = 0x10;
448         // Only complete if resolution can be
449         // 			completed through cached lookup. May
450         // 			return -EAGAIN if that's not
451         // 			possible.
452         const RESOLVE_CACHED = 0x20;
453     }
454 }
455 impl Syscall {
456     /// @brief 为当前进程打开一个文件
457     ///
458     /// @param path 文件路径
459     /// @param o_flags 打开文件的标志位
460     ///
461     /// @return 文件描述符编号,或者是错误码
462     pub fn open(
463         path: *const u8,
464         o_flags: u32,
465         mode: u32,
466         follow_symlink: bool,
467     ) -> Result<usize, SystemError> {
468         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?;
469         let open_flags: FileMode = FileMode::from_bits(o_flags).ok_or(SystemError::EINVAL)?;
470         let mode = ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?;
471         return do_sys_open(
472             AtFlags::AT_FDCWD.bits(),
473             &path,
474             open_flags,
475             mode,
476             follow_symlink,
477         );
478     }
479 
480     pub fn openat(
481         dirfd: i32,
482         path: *const u8,
483         o_flags: u32,
484         mode: u32,
485         follow_symlink: bool,
486     ) -> Result<usize, SystemError> {
487         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?;
488         let open_flags: FileMode = FileMode::from_bits(o_flags).ok_or(SystemError::EINVAL)?;
489         let mode = ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?;
490         return do_sys_open(dirfd, &path, open_flags, mode, follow_symlink);
491     }
492 
493     /// @brief 关闭文件
494     ///
495     /// @param fd 文件描述符编号
496     ///
497     /// @return 成功返回0,失败返回错误码
498     pub fn close(fd: usize) -> Result<usize, SystemError> {
499         let binding = ProcessManager::current_pcb().fd_table();
500         let mut fd_table_guard = binding.write();
501 
502         fd_table_guard.drop_fd(fd as i32).map(|_| 0)
503     }
504 
505     /// @brief 发送命令到文件描述符对应的设备,
506     ///
507     /// @param fd 文件描述符编号
508     /// @param cmd 设备相关的请求类型
509     ///
510     /// @return Ok(usize) 成功返回0
511     /// @return Err(SystemError) 读取失败,返回posix错误码
512     pub fn ioctl(fd: usize, cmd: u32, data: usize) -> Result<usize, SystemError> {
513         let binding = ProcessManager::current_pcb().fd_table();
514         let fd_table_guard = binding.read();
515 
516         let file = fd_table_guard
517             .get_file_by_fd(fd as i32)
518             .ok_or(SystemError::EBADF)?;
519 
520         // drop guard 以避免无法调度的问题
521         drop(fd_table_guard);
522         let r = file.inode().ioctl(cmd, data, &file.private_data.lock());
523         return r;
524     }
525 
526     /// @brief 根据文件描述符,读取文件数据。尝试读取的数据长度与buf的长度相同。
527     ///
528     /// @param fd 文件描述符编号
529     /// @param buf 输出缓冲区
530     ///
531     /// @return Ok(usize) 成功读取的数据的字节数
532     /// @return Err(SystemError) 读取失败,返回posix错误码
533     pub fn read(fd: i32, buf: &mut [u8]) -> Result<usize, SystemError> {
534         let binding = ProcessManager::current_pcb().fd_table();
535         let fd_table_guard = binding.read();
536 
537         let file = fd_table_guard.get_file_by_fd(fd);
538         if file.is_none() {
539             return Err(SystemError::EBADF);
540         }
541         // drop guard 以避免无法调度的问题
542         drop(fd_table_guard);
543         let file = file.unwrap();
544 
545         return file.read(buf.len(), buf);
546     }
547 
548     /// @brief 根据文件描述符,向文件写入数据。尝试写入的数据长度与buf的长度相同。
549     ///
550     /// @param fd 文件描述符编号
551     /// @param buf 输入缓冲区
552     ///
553     /// @return Ok(usize) 成功写入的数据的字节数
554     /// @return Err(SystemError) 写入失败,返回posix错误码
555     pub fn write(fd: i32, buf: &[u8]) -> Result<usize, SystemError> {
556         let binding = ProcessManager::current_pcb().fd_table();
557         let fd_table_guard = binding.read();
558 
559         let file = fd_table_guard
560             .get_file_by_fd(fd)
561             .ok_or(SystemError::EBADF)?;
562 
563         // drop guard 以避免无法调度的问题
564         drop(fd_table_guard);
565         return file.write(buf.len(), buf);
566     }
567 
568     /// @brief 调整文件操作指针的位置
569     ///
570     /// @param fd 文件描述符编号
571     /// @param seek 调整的方式
572     ///
573     /// @return Ok(usize) 调整后,文件访问指针相对于文件头部的偏移量
574     /// @return Err(SystemError) 调整失败,返回posix错误码
575     pub fn lseek(fd: i32, offset: i64, seek: u32) -> Result<usize, SystemError> {
576         let seek = match seek {
577             SEEK_SET => Ok(SeekFrom::SeekSet(offset)),
578             SEEK_CUR => Ok(SeekFrom::SeekCurrent(offset)),
579             SEEK_END => Ok(SeekFrom::SeekEnd(offset)),
580             SEEK_MAX => Ok(SeekFrom::SeekEnd(0)),
581             _ => Err(SystemError::EINVAL),
582         }?;
583 
584         let binding = ProcessManager::current_pcb().fd_table();
585         let fd_table_guard = binding.read();
586         let file = fd_table_guard
587             .get_file_by_fd(fd)
588             .ok_or(SystemError::EBADF)?;
589 
590         // drop guard 以避免无法调度的问题
591         drop(fd_table_guard);
592         return file.lseek(seek);
593     }
594 
595     /// # sys_pread64 系统调用的实际执行函数
596     ///
597     /// ## 参数
598     /// - `fd`: 文件描述符
599     /// - `buf`: 读出缓冲区
600     /// - `len`: 要读取的字节数
601     /// - `offset`: 文件偏移量
602     pub fn pread(fd: i32, buf: &mut [u8], len: usize, offset: usize) -> Result<usize, SystemError> {
603         let binding = ProcessManager::current_pcb().fd_table();
604         let fd_table_guard = binding.read();
605 
606         let file = fd_table_guard.get_file_by_fd(fd);
607         if file.is_none() {
608             return Err(SystemError::EBADF);
609         }
610         // drop guard 以避免无法调度的问题
611         drop(fd_table_guard);
612         let file = file.unwrap();
613 
614         return file.pread(offset, len, buf);
615     }
616 
617     /// # sys_pwrite64 系统调用的实际执行函数
618     ///
619     /// ## 参数
620     /// - `fd`: 文件描述符
621     /// - `buf`: 写入缓冲区
622     /// - `len`: 要写入的字节数
623     /// - `offset`: 文件偏移量
624     pub fn pwrite(fd: i32, buf: &[u8], len: usize, offset: usize) -> Result<usize, SystemError> {
625         let binding = ProcessManager::current_pcb().fd_table();
626         let fd_table_guard = binding.read();
627 
628         let file = fd_table_guard.get_file_by_fd(fd);
629         if file.is_none() {
630             return Err(SystemError::EBADF);
631         }
632         // drop guard 以避免无法调度的问题
633         drop(fd_table_guard);
634         let file = file.unwrap();
635 
636         return file.pwrite(offset, len, buf);
637     }
638 
639     /// @brief 切换工作目录
640     ///
641     /// @param dest_path 目标路径
642     ///
643     /// @return   返回码  描述
644     ///      0       |          成功
645     ///
646     ///   EACCESS    |        权限不足
647     ///
648     ///    ELOOP     | 解析path时遇到路径循环
649     ///
650     /// ENAMETOOLONG |       路径名过长
651     ///
652     ///    ENOENT    |  目标文件或目录不存在
653     ///
654     ///    ENODIR    |  检索期间发现非目录项
655     ///
656     ///    ENOMEM    |      系统内存不足
657     ///
658     ///    EFAULT    |       错误的地址
659     ///
660     /// ENAMETOOLONG |        路径过长
661     pub fn chdir(path: *const u8) -> Result<usize, SystemError> {
662         if path.is_null() {
663             return Err(SystemError::EFAULT);
664         }
665 
666         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?;
667         let proc = ProcessManager::current_pcb();
668         // Copy path to kernel space to avoid some security issues
669         let mut new_path = String::from("");
670         if !path.is_empty() {
671             let cwd = match path.as_bytes()[0] {
672                 b'/' => String::from("/"),
673                 _ => proc.basic().cwd(),
674             };
675             let mut cwd_vec: Vec<_> = cwd.split('/').filter(|&x| !x.is_empty()).collect();
676             let path_split = path.split('/').filter(|&x| !x.is_empty());
677             for seg in path_split {
678                 if seg == ".." {
679                     cwd_vec.pop();
680                 } else if seg == "." {
681                     // 当前目录
682                 } else {
683                     cwd_vec.push(seg);
684                 }
685             }
686             //proc.basic().set_path(String::from(""));
687             for seg in cwd_vec {
688                 new_path.push('/');
689                 new_path.push_str(seg);
690             }
691             if new_path.is_empty() {
692                 new_path = String::from("/");
693             }
694         }
695         let inode =
696             match ROOT_INODE().lookup_follow_symlink(&new_path, VFS_MAX_FOLLOW_SYMLINK_TIMES) {
697                 Err(_) => {
698                     return Err(SystemError::ENOENT);
699                 }
700                 Ok(i) => i,
701             };
702         let metadata = inode.metadata()?;
703         if metadata.file_type == FileType::Dir {
704             proc.basic_mut().set_cwd(new_path);
705             return Ok(0);
706         } else {
707             return Err(SystemError::ENOTDIR);
708         }
709     }
710 
711     /// @brief 获取当前进程的工作目录路径
712     ///
713     /// @param buf 指向缓冲区的指针
714     /// @param size 缓冲区的大小
715     ///
716     /// @return 成功,返回的指针指向包含工作目录路径的字符串
717     /// @return 错误,没有足够的空间
718     pub fn getcwd(buf: &mut [u8]) -> Result<VirtAddr, SystemError> {
719         let proc = ProcessManager::current_pcb();
720         let cwd = proc.basic().cwd();
721 
722         let cwd_bytes = cwd.as_bytes();
723         let cwd_len = cwd_bytes.len();
724         if cwd_len + 1 > buf.len() {
725             return Err(SystemError::ENOMEM);
726         }
727         buf[..cwd_len].copy_from_slice(cwd_bytes);
728         buf[cwd_len] = 0;
729 
730         return Ok(VirtAddr::new(buf.as_ptr() as usize));
731     }
732 
733     /// @brief 获取目录中的数据
734     ///
735     /// TODO: 这个函数的语义与Linux不一致,需要修改!!!
736     ///
737     /// @param fd 文件描述符号
738     /// @param buf 输出缓冲区
739     ///
740     /// @return 成功返回读取的字节数,失败返回错误码
741     pub fn getdents(fd: i32, buf: &mut [u8]) -> Result<usize, SystemError> {
742         let dirent =
743             unsafe { (buf.as_mut_ptr() as *mut Dirent).as_mut() }.ok_or(SystemError::EFAULT)?;
744 
745         if fd < 0 || fd as usize > FileDescriptorVec::PROCESS_MAX_FD {
746             return Err(SystemError::EBADF);
747         }
748 
749         // 获取fd
750         let binding = ProcessManager::current_pcb().fd_table();
751         let fd_table_guard = binding.read();
752         let file = fd_table_guard
753             .get_file_by_fd(fd)
754             .ok_or(SystemError::EBADF)?;
755 
756         // drop guard 以避免无法调度的问题
757         drop(fd_table_guard);
758 
759         let res = file.readdir(dirent).map(|x| x as usize);
760 
761         return res;
762     }
763 
764     /// @brief 创建文件夹
765     ///
766     /// @param path(r8) 路径 / mode(r9) 模式
767     ///
768     /// @return uint64_t 负数错误码 / 0表示成功
769     pub fn mkdir(path: *const u8, mode: usize) -> Result<usize, SystemError> {
770         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?;
771         return do_mkdir(&path, FileMode::from_bits_truncate(mode as u32)).map(|x| x as usize);
772     }
773 
774     /// **创建硬连接的系统调用**
775     ///
776     /// ## 参数
777     ///
778     /// - 'oldfd': 用于解析源文件路径的文件描述符
779     /// - 'old': 源文件路径
780     /// - 'newfd': 用于解析新文件路径的文件描述符
781     /// - 'new': 新文件将创建的路径
782     /// - 'flags': 标志位,仅以位或方式包含AT_EMPTY_PATH和AT_SYMLINK_FOLLOW
783     ///
784     ///
785     pub fn do_linkat(
786         oldfd: i32,
787         old: &str,
788         newfd: i32,
789         new: &str,
790         flags: AtFlags,
791     ) -> Result<usize, SystemError> {
792         // flag包含其他未规定值时返回EINVAL
793         if !(AtFlags::AT_EMPTY_PATH | AtFlags::AT_SYMLINK_FOLLOW).contains(flags) {
794             return Err(SystemError::EINVAL);
795         }
796         // TODO AT_EMPTY_PATH标志启用时,进行调用者CAP_DAC_READ_SEARCH或相似的检查
797         let symlink_times = if flags.contains(AtFlags::AT_SYMLINK_FOLLOW) {
798             0_usize
799         } else {
800             VFS_MAX_FOLLOW_SYMLINK_TIMES
801         };
802         let pcb = ProcessManager::current_pcb();
803 
804         // 得到源路径的inode
805         let old_inode: Arc<dyn IndexNode> = if old.is_empty() {
806             if flags.contains(AtFlags::AT_EMPTY_PATH) {
807                 // 在AT_EMPTY_PATH启用时,old可以为空,old_inode实际为oldfd所指文件,但该文件不能为目录。
808                 let binding = pcb.fd_table();
809                 let fd_table_guard = binding.read();
810                 let file = fd_table_guard
811                     .get_file_by_fd(oldfd)
812                     .ok_or(SystemError::EBADF)?;
813                 let old_inode = file.inode();
814                 old_inode
815             } else {
816                 return Err(SystemError::ENONET);
817             }
818         } else {
819             let (old_begin_inode, old_remain_path) = user_path_at(&pcb, oldfd, old)?;
820             old_begin_inode.lookup_follow_symlink(&old_remain_path, symlink_times)?
821         };
822 
823         // old_inode为目录时返回EPERM
824         if old_inode.metadata().unwrap().file_type == FileType::Dir {
825             return Err(SystemError::EPERM);
826         }
827 
828         // 得到新创建节点的父节点
829         let (new_begin_inode, new_remain_path) = user_path_at(&pcb, newfd, new)?;
830         let (new_name, new_parent_path) = rsplit_path(&new_remain_path);
831         let new_parent =
832             new_begin_inode.lookup_follow_symlink(new_parent_path.unwrap_or("/"), symlink_times)?;
833 
834         // 被调用者利用downcast_ref判断两inode是否为同一文件系统
835         return new_parent.link(new_name, &old_inode).map(|_| 0);
836     }
837 
838     pub fn link(old: *const u8, new: *const u8) -> Result<usize, SystemError> {
839         let get_path = |cstr: *const u8| -> Result<String, SystemError> {
840             let res = check_and_clone_cstr(cstr, Some(MAX_PATHLEN))?;
841             if res.len() >= MAX_PATHLEN {
842                 return Err(SystemError::ENAMETOOLONG);
843             }
844             if res.is_empty() {
845                 return Err(SystemError::ENOENT);
846             }
847             Ok(res)
848         };
849         let old = get_path(old)?;
850         let new = get_path(new)?;
851         return Self::do_linkat(
852             AtFlags::AT_FDCWD.bits(),
853             &old,
854             AtFlags::AT_FDCWD.bits(),
855             &new,
856             AtFlags::empty(),
857         );
858     }
859 
860     pub fn linkat(
861         oldfd: i32,
862         old: *const u8,
863         newfd: i32,
864         new: *const u8,
865         flags: i32,
866     ) -> Result<usize, SystemError> {
867         let old = check_and_clone_cstr(old, Some(MAX_PATHLEN))?;
868         let new = check_and_clone_cstr(new, Some(MAX_PATHLEN))?;
869         if old.len() >= MAX_PATHLEN || new.len() >= MAX_PATHLEN {
870             return Err(SystemError::ENAMETOOLONG);
871         }
872         // old 根据flags & AtFlags::AT_EMPTY_PATH判空
873         if new.is_empty() {
874             return Err(SystemError::ENOENT);
875         }
876         let flags = AtFlags::from_bits(flags).ok_or(SystemError::EINVAL)?;
877         Self::do_linkat(oldfd, &old, newfd, &new, flags)
878     }
879 
880     /// **删除文件夹、取消文件的链接、删除文件的系统调用**
881     ///
882     /// ## 参数
883     ///
884     /// - `dirfd`:文件夹的文件描述符.目前暂未实现
885     /// - `pathname`:文件夹的路径
886     /// - `flags`:标志位
887     ///
888     ///
889     pub fn unlinkat(dirfd: i32, path: *const u8, flags: u32) -> Result<usize, SystemError> {
890         let flags = AtFlags::from_bits(flags as i32).ok_or(SystemError::EINVAL)?;
891 
892         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?;
893 
894         if flags.contains(AtFlags::AT_REMOVEDIR) {
895             // kdebug!("rmdir");
896             match do_remove_dir(dirfd, &path) {
897                 Err(err) => {
898                     return Err(err);
899                 }
900                 Ok(_) => {
901                     return Ok(0);
902                 }
903             }
904         }
905 
906         match do_unlink_at(dirfd, &path) {
907             Err(err) => {
908                 return Err(err);
909             }
910             Ok(_) => {
911                 return Ok(0);
912             }
913         }
914     }
915 
916     pub fn rmdir(path: *const u8) -> Result<usize, SystemError> {
917         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?;
918         return do_remove_dir(AtFlags::AT_FDCWD.bits(), &path).map(|v| v as usize);
919     }
920 
921     pub fn unlink(path: *const u8) -> Result<usize, SystemError> {
922         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?;
923         return do_unlink_at(AtFlags::AT_FDCWD.bits(), &path).map(|v| v as usize);
924     }
925 
926     /// # 修改文件名
927     ///
928     ///
929     /// ## 参数
930     ///
931     /// - oldfd: 源文件描述符
932     /// - filename_from: 源文件路径
933     /// - newfd: 目标文件描述符
934     /// - filename_to: 目标文件路径
935     /// - flags: 标志位
936     ///
937     ///
938     /// ## 返回值
939     /// - Ok(返回值类型): 返回值的说明
940     /// - Err(错误值类型): 错误的说明
941     ///
942     pub fn do_renameat2(
943         oldfd: i32,
944         filename_from: *const u8,
945         newfd: i32,
946         filename_to: *const u8,
947         _flags: u32,
948     ) -> Result<usize, SystemError> {
949         let filename_from = check_and_clone_cstr(filename_from, Some(MAX_PATHLEN)).unwrap();
950         let filename_to = check_and_clone_cstr(filename_to, Some(MAX_PATHLEN)).unwrap();
951         // 文件名过长
952         if filename_from.len() > MAX_PATHLEN || filename_to.len() > MAX_PATHLEN {
953             return Err(SystemError::ENAMETOOLONG);
954         }
955 
956         //获取pcb,文件节点
957         let pcb = ProcessManager::current_pcb();
958         let (_old_inode_begin, old_remain_path) = user_path_at(&pcb, oldfd, &filename_from)?;
959         let (_new_inode_begin, new_remain_path) = user_path_at(&pcb, newfd, &filename_to)?;
960         //获取父目录
961         let (old_filename, old_parent_path) = rsplit_path(&old_remain_path);
962         let old_parent_inode = ROOT_INODE()
963             .lookup_follow_symlink(old_parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
964         let (new_filename, new_parent_path) = rsplit_path(&new_remain_path);
965         let new_parent_inode = ROOT_INODE()
966             .lookup_follow_symlink(new_parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
967         old_parent_inode.move_to(old_filename, &new_parent_inode, new_filename)?;
968         return Ok(0);
969     }
970 
971     /// @brief 根据提供的文件描述符的fd,复制对应的文件结构体,并返回新复制的文件结构体对应的fd
972     pub fn dup(oldfd: i32) -> Result<usize, SystemError> {
973         let binding = ProcessManager::current_pcb().fd_table();
974         let mut fd_table_guard = binding.write();
975 
976         let old_file = fd_table_guard
977             .get_file_by_fd(oldfd)
978             .ok_or(SystemError::EBADF)?;
979 
980         let new_file = old_file.try_clone().ok_or(SystemError::EBADF)?;
981         // dup默认非cloexec
982         new_file.set_close_on_exec(false);
983         // 申请文件描述符,并把文件对象存入其中
984         let res = fd_table_guard.alloc_fd(new_file, None).map(|x| x as usize);
985         return res;
986     }
987 
988     /// 根据提供的文件描述符的fd,和指定新fd,复制对应的文件结构体,
989     /// 并返回新复制的文件结构体对应的fd.
990     /// 如果新fd已经打开,则会先关闭新fd.
991     ///
992     /// ## 参数
993     ///
994     /// - `oldfd`:旧文件描述符
995     /// - `newfd`:新文件描述符
996     ///
997     /// ## 返回值
998     ///
999     /// - 成功:新文件描述符
1000     /// - 失败:错误码
1001     pub fn dup2(oldfd: i32, newfd: i32) -> Result<usize, SystemError> {
1002         let binding = ProcessManager::current_pcb().fd_table();
1003         let mut fd_table_guard = binding.write();
1004         return Self::do_dup2(oldfd, newfd, &mut fd_table_guard);
1005     }
1006 
1007     fn do_dup2(
1008         oldfd: i32,
1009         newfd: i32,
1010         fd_table_guard: &mut RwLockWriteGuard<'_, FileDescriptorVec>,
1011     ) -> Result<usize, SystemError> {
1012         // 确认oldfd, newid是否有效
1013         if !(FileDescriptorVec::validate_fd(oldfd) && FileDescriptorVec::validate_fd(newfd)) {
1014             return Err(SystemError::EBADF);
1015         }
1016 
1017         if oldfd == newfd {
1018             // 若oldfd与newfd相等
1019             return Ok(newfd as usize);
1020         }
1021         let new_exists = fd_table_guard.get_file_by_fd(newfd).is_some();
1022         if new_exists {
1023             // close newfd
1024             if fd_table_guard.drop_fd(newfd).is_err() {
1025                 // An I/O error occurred while attempting to close fildes2.
1026                 return Err(SystemError::EIO);
1027             }
1028         }
1029 
1030         let old_file = fd_table_guard
1031             .get_file_by_fd(oldfd)
1032             .ok_or(SystemError::EBADF)?;
1033         let new_file = old_file.try_clone().ok_or(SystemError::EBADF)?;
1034         // dup2默认非cloexec
1035         new_file.set_close_on_exec(false);
1036         // 申请文件描述符,并把文件对象存入其中
1037         let res = fd_table_guard
1038             .alloc_fd(new_file, Some(newfd))
1039             .map(|x| x as usize);
1040         return res;
1041     }
1042 
1043     /// # fcntl
1044     ///
1045     /// ## 参数
1046     ///
1047     /// - `fd`:文件描述符
1048     /// - `cmd`:命令
1049     /// - `arg`:参数
1050     pub fn fcntl(fd: i32, cmd: FcntlCommand, arg: i32) -> Result<usize, SystemError> {
1051         match cmd {
1052             FcntlCommand::DupFd => {
1053                 if arg < 0 || arg as usize >= FileDescriptorVec::PROCESS_MAX_FD {
1054                     return Err(SystemError::EBADF);
1055                 }
1056                 let arg = arg as usize;
1057                 for i in arg..FileDescriptorVec::PROCESS_MAX_FD {
1058                     let binding = ProcessManager::current_pcb().fd_table();
1059                     let mut fd_table_guard = binding.write();
1060                     if fd_table_guard.get_file_by_fd(i as i32).is_none() {
1061                         return Self::do_dup2(fd, i as i32, &mut fd_table_guard);
1062                     }
1063                 }
1064                 return Err(SystemError::EMFILE);
1065             }
1066             FcntlCommand::GetFd => {
1067                 // Get file descriptor flags.
1068                 let binding = ProcessManager::current_pcb().fd_table();
1069                 let fd_table_guard = binding.read();
1070                 if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
1071                     // drop guard 以避免无法调度的问题
1072                     drop(fd_table_guard);
1073 
1074                     if file.close_on_exec() {
1075                         return Ok(FD_CLOEXEC as usize);
1076                     }
1077                 }
1078                 return Err(SystemError::EBADF);
1079             }
1080             FcntlCommand::SetFd => {
1081                 // Set file descriptor flags.
1082                 let binding = ProcessManager::current_pcb().fd_table();
1083                 let fd_table_guard = binding.write();
1084 
1085                 if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
1086                     // drop guard 以避免无法调度的问题
1087                     drop(fd_table_guard);
1088                     let arg = arg as u32;
1089                     if arg & FD_CLOEXEC != 0 {
1090                         file.set_close_on_exec(true);
1091                     } else {
1092                         file.set_close_on_exec(false);
1093                     }
1094                     return Ok(0);
1095                 }
1096                 return Err(SystemError::EBADF);
1097             }
1098 
1099             FcntlCommand::GetFlags => {
1100                 // Get file status flags.
1101                 let binding = ProcessManager::current_pcb().fd_table();
1102                 let fd_table_guard = binding.read();
1103 
1104                 if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
1105                     // drop guard 以避免无法调度的问题
1106                     drop(fd_table_guard);
1107                     return Ok(file.mode().bits() as usize);
1108                 }
1109 
1110                 return Err(SystemError::EBADF);
1111             }
1112             FcntlCommand::SetFlags => {
1113                 // Set file status flags.
1114                 let binding = ProcessManager::current_pcb().fd_table();
1115                 let fd_table_guard = binding.write();
1116 
1117                 if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
1118                     let arg = arg as u32;
1119                     let mode = FileMode::from_bits(arg).ok_or(SystemError::EINVAL)?;
1120                     // drop guard 以避免无法调度的问题
1121                     drop(fd_table_guard);
1122                     file.set_mode(mode)?;
1123                     return Ok(0);
1124                 }
1125 
1126                 return Err(SystemError::EBADF);
1127             }
1128             _ => {
1129                 // TODO: unimplemented
1130                 // 未实现的命令,返回0,不报错。
1131 
1132                 // kwarn!("fcntl: unimplemented command: {:?}, defaults to 0.", cmd);
1133                 return Ok(0);
1134             }
1135         }
1136     }
1137 
1138     /// # ftruncate
1139     ///
1140     /// ## 描述
1141     ///
1142     /// 改变文件大小.
1143     /// 如果文件大小大于原来的大小,那么文件的内容将会被扩展到指定的大小,新的空间将会用0填充.
1144     /// 如果文件大小小于原来的大小,那么文件的内容将会被截断到指定的大小.
1145     ///
1146     /// ## 参数
1147     ///
1148     /// - `fd`:文件描述符
1149     /// - `len`:文件大小
1150     ///
1151     /// ## 返回值
1152     ///
1153     /// 如果成功,返回0,否则返回错误码.
1154     pub fn ftruncate(fd: i32, len: usize) -> Result<usize, SystemError> {
1155         let binding = ProcessManager::current_pcb().fd_table();
1156         let fd_table_guard = binding.read();
1157 
1158         if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
1159             // drop guard 以避免无法调度的问题
1160             drop(fd_table_guard);
1161             let r = file.ftruncate(len).map(|_| 0);
1162             return r;
1163         }
1164 
1165         return Err(SystemError::EBADF);
1166     }
1167 
1168     fn do_fstat(fd: i32) -> Result<PosixKstat, SystemError> {
1169         let binding = ProcessManager::current_pcb().fd_table();
1170         let fd_table_guard = binding.read();
1171         let file = fd_table_guard
1172             .get_file_by_fd(fd)
1173             .ok_or(SystemError::EBADF)?;
1174         // drop guard 以避免无法调度的问题
1175         drop(fd_table_guard);
1176 
1177         let mut kstat = PosixKstat::new();
1178         // 获取文件信息
1179         let metadata = file.metadata()?;
1180         kstat.size = metadata.size;
1181         kstat.dev_id = metadata.dev_id as u64;
1182         kstat.inode = metadata.inode_id.into() as u64;
1183         kstat.blcok_size = metadata.blk_size as i64;
1184         kstat.blocks = metadata.blocks as u64;
1185 
1186         kstat.atime.tv_sec = metadata.atime.tv_sec;
1187         kstat.atime.tv_nsec = metadata.atime.tv_nsec;
1188         kstat.mtime.tv_sec = metadata.mtime.tv_sec;
1189         kstat.mtime.tv_nsec = metadata.mtime.tv_nsec;
1190         kstat.ctime.tv_sec = metadata.ctime.tv_sec;
1191         kstat.ctime.tv_nsec = metadata.ctime.tv_nsec;
1192 
1193         kstat.nlink = metadata.nlinks as u64;
1194         kstat.uid = metadata.uid as i32;
1195         kstat.gid = metadata.gid as i32;
1196         kstat.rdev = metadata.raw_dev.data() as i64;
1197         kstat.mode = metadata.mode;
1198         match file.file_type() {
1199             FileType::File => kstat.mode.insert(ModeType::S_IFREG),
1200             FileType::Dir => kstat.mode.insert(ModeType::S_IFDIR),
1201             FileType::BlockDevice => kstat.mode.insert(ModeType::S_IFBLK),
1202             FileType::CharDevice => kstat.mode.insert(ModeType::S_IFCHR),
1203             FileType::SymLink => kstat.mode.insert(ModeType::S_IFLNK),
1204             FileType::Socket => kstat.mode.insert(ModeType::S_IFSOCK),
1205             FileType::Pipe => kstat.mode.insert(ModeType::S_IFIFO),
1206             FileType::KvmDevice => kstat.mode.insert(ModeType::S_IFCHR),
1207             FileType::FramebufferDevice => kstat.mode.insert(ModeType::S_IFCHR),
1208         }
1209 
1210         return Ok(kstat);
1211     }
1212 
1213     pub fn fstat(fd: i32, usr_kstat: *mut PosixKstat) -> Result<usize, SystemError> {
1214         let mut writer = UserBufferWriter::new(usr_kstat, size_of::<PosixKstat>(), true)?;
1215         let kstat = Self::do_fstat(fd)?;
1216 
1217         writer.copy_one_to_user(&kstat, 0)?;
1218         return Ok(0);
1219     }
1220 
1221     pub fn stat(path: *const u8, user_kstat: *mut PosixKstat) -> Result<usize, SystemError> {
1222         let fd = Self::open(
1223             path,
1224             FileMode::O_RDONLY.bits(),
1225             ModeType::empty().bits(),
1226             true,
1227         )?;
1228         let r = Self::fstat(fd as i32, user_kstat);
1229         Self::close(fd).ok();
1230         return r;
1231     }
1232 
1233     pub fn lstat(path: *const u8, user_kstat: *mut PosixKstat) -> Result<usize, SystemError> {
1234         let fd = Self::open(
1235             path,
1236             FileMode::O_RDONLY.bits(),
1237             ModeType::empty().bits(),
1238             false,
1239         )?;
1240         let r = Self::fstat(fd as i32, user_kstat);
1241         Self::close(fd).ok();
1242         return r;
1243     }
1244 
1245     pub fn statfs(path: *const u8, user_statfs: *mut PosixStatfs) -> Result<usize, SystemError> {
1246         let mut writer = UserBufferWriter::new(user_statfs, size_of::<PosixStatfs>(), true)?;
1247         let fd = Self::open(
1248             path,
1249             FileMode::O_RDONLY.bits(),
1250             ModeType::empty().bits(),
1251             true,
1252         )?;
1253         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN)).unwrap();
1254         let pcb = ProcessManager::current_pcb();
1255         let (_inode_begin, remain_path) = user_path_at(&pcb, fd as i32, &path)?;
1256         let inode = ROOT_INODE().lookup_follow_symlink(&remain_path, MAX_PATHLEN)?;
1257         let statfs = PosixStatfs::from(inode.fs().super_block());
1258         writer.copy_one_to_user(&statfs, 0)?;
1259         return Ok(0);
1260     }
1261 
1262     pub fn fstatfs(fd: i32, user_statfs: *mut PosixStatfs) -> Result<usize, SystemError> {
1263         let mut writer = UserBufferWriter::new(user_statfs, size_of::<PosixStatfs>(), true)?;
1264         let binding = ProcessManager::current_pcb().fd_table();
1265         let fd_table_guard = binding.read();
1266         let file = fd_table_guard
1267             .get_file_by_fd(fd)
1268             .ok_or(SystemError::EBADF)?;
1269         drop(fd_table_guard);
1270         let statfs = PosixStatfs::from(file.inode().fs().super_block());
1271         writer.copy_one_to_user(&statfs, 0)?;
1272         return Ok(0);
1273     }
1274 
1275     pub fn do_statx(
1276         fd: i32,
1277         path: *const u8,
1278         flags: u32,
1279         mask: u32,
1280         usr_kstat: *mut PosixStatx,
1281     ) -> Result<usize, SystemError> {
1282         if usr_kstat.is_null() {
1283             return Err(SystemError::EFAULT);
1284         }
1285 
1286         let mask = PosixStatxMask::from_bits_truncate(mask);
1287 
1288         if mask.contains(PosixStatxMask::STATX_RESERVED) {
1289             return Err(SystemError::ENAVAIL);
1290         }
1291 
1292         let flags = FileMode::from_bits_truncate(flags);
1293         let ofd = Self::open(path, flags.bits(), ModeType::empty().bits, true)?;
1294 
1295         let binding = ProcessManager::current_pcb().fd_table();
1296         let fd_table_guard = binding.read();
1297         let file = fd_table_guard
1298             .get_file_by_fd(ofd as i32)
1299             .ok_or(SystemError::EBADF)?;
1300         // drop guard 以避免无法调度的问题
1301         drop(fd_table_guard);
1302         let mut writer = UserBufferWriter::new(usr_kstat, size_of::<PosixStatx>(), true)?;
1303         let mut tmp: PosixStatx = PosixStatx::new();
1304         // 获取文件信息
1305         let metadata = file.metadata()?;
1306 
1307         tmp.stx_mask |= PosixStatxMask::STATX_BASIC_STATS;
1308         tmp.stx_blksize = metadata.blk_size as u32;
1309         if mask.contains(PosixStatxMask::STATX_MODE) || mask.contains(PosixStatxMask::STATX_TYPE) {
1310             tmp.stx_mode = metadata.mode;
1311         }
1312         if mask.contains(PosixStatxMask::STATX_NLINK) {
1313             tmp.stx_nlink = metadata.nlinks as u32;
1314         }
1315         if mask.contains(PosixStatxMask::STATX_UID) {
1316             tmp.stx_uid = metadata.uid as u32;
1317         }
1318         if mask.contains(PosixStatxMask::STATX_GID) {
1319             tmp.stx_gid = metadata.gid as u32;
1320         }
1321         if mask.contains(PosixStatxMask::STATX_ATIME) {
1322             tmp.stx_atime.tv_sec = metadata.atime.tv_sec;
1323             tmp.stx_atime.tv_nsec = metadata.atime.tv_nsec;
1324         }
1325         if mask.contains(PosixStatxMask::STATX_MTIME) {
1326             tmp.stx_mtime.tv_sec = metadata.ctime.tv_sec;
1327             tmp.stx_mtime.tv_nsec = metadata.ctime.tv_nsec;
1328         }
1329         if mask.contains(PosixStatxMask::STATX_CTIME) {
1330             // ctime是文件上次修改状态的时间
1331             tmp.stx_ctime.tv_sec = metadata.mtime.tv_sec;
1332             tmp.stx_ctime.tv_nsec = metadata.mtime.tv_nsec;
1333         }
1334         if mask.contains(PosixStatxMask::STATX_INO) {
1335             tmp.stx_inode = metadata.inode_id.into() as u64;
1336         }
1337         if mask.contains(PosixStatxMask::STATX_SIZE) {
1338             tmp.stx_size = metadata.size;
1339         }
1340         if mask.contains(PosixStatxMask::STATX_BLOCKS) {
1341             tmp.stx_blocks = metadata.blocks as u64;
1342         }
1343 
1344         if mask.contains(PosixStatxMask::STATX_BTIME) {
1345             // btime是文件创建时间
1346             tmp.stx_btime.tv_sec = metadata.ctime.tv_sec;
1347             tmp.stx_btime.tv_nsec = metadata.ctime.tv_nsec;
1348         }
1349         if mask.contains(PosixStatxMask::STATX_ALL) {
1350             tmp.stx_attributes = StxAttributes::STATX_ATTR_APPEND;
1351             tmp.stx_attributes_mask |=
1352                 StxAttributes::STATX_ATTR_AUTOMOUNT | StxAttributes::STATX_ATTR_DAX;
1353             tmp.stx_dev_major = metadata.dev_id as u32;
1354             tmp.stx_dev_minor = metadata.dev_id as u32; //
1355             tmp.stx_rdev_major = metadata.raw_dev.data();
1356             tmp.stx_rdev_minor = metadata.raw_dev.data();
1357         }
1358         if mask.contains(PosixStatxMask::STATX_MNT_ID) {
1359             tmp.stx_mnt_id = 0;
1360         }
1361         if mask.contains(PosixStatxMask::STATX_DIOALIGN) {
1362             tmp.stx_dio_mem_align = 0;
1363             tmp.stx_dio_offset_align = 0;
1364         }
1365 
1366         match file.file_type() {
1367             FileType::File => tmp.stx_mode.insert(ModeType::S_IFREG),
1368             FileType::Dir => tmp.stx_mode.insert(ModeType::S_IFDIR),
1369             FileType::BlockDevice => tmp.stx_mode.insert(ModeType::S_IFBLK),
1370             FileType::CharDevice => tmp.stx_mode.insert(ModeType::S_IFCHR),
1371             FileType::SymLink => tmp.stx_mode.insert(ModeType::S_IFLNK),
1372             FileType::Socket => tmp.stx_mode.insert(ModeType::S_IFSOCK),
1373             FileType::Pipe => tmp.stx_mode.insert(ModeType::S_IFIFO),
1374             FileType::KvmDevice => tmp.stx_mode.insert(ModeType::S_IFCHR),
1375             FileType::FramebufferDevice => tmp.stx_mode.insert(ModeType::S_IFCHR),
1376         }
1377 
1378         writer.copy_one_to_user(&tmp, 0)?;
1379         Self::close(fd as usize).ok();
1380         return Ok(0);
1381     }
1382 
1383     pub fn mknod(
1384         path: *const u8,
1385         mode: ModeType,
1386         dev_t: DeviceNumber,
1387     ) -> Result<usize, SystemError> {
1388         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?;
1389         let path = path.as_str().trim();
1390 
1391         let inode: Result<Arc<dyn IndexNode>, SystemError> =
1392             ROOT_INODE().lookup_follow_symlink(path, VFS_MAX_FOLLOW_SYMLINK_TIMES);
1393 
1394         if inode.is_ok() {
1395             return Err(SystemError::EEXIST);
1396         }
1397 
1398         let (filename, parent_path) = rsplit_path(path);
1399 
1400         // 查找父目录
1401         let parent_inode: Arc<dyn IndexNode> = ROOT_INODE()
1402             .lookup_follow_symlink(parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
1403         // 创建nod
1404         parent_inode.mknod(filename, mode, dev_t)?;
1405 
1406         return Ok(0);
1407     }
1408 
1409     pub fn writev(fd: i32, iov: usize, count: usize) -> Result<usize, SystemError> {
1410         // IoVecs会进行用户态检验
1411         let iovecs = unsafe { IoVecs::from_user(iov as *const IoVec, count, false) }?;
1412 
1413         let data = iovecs.gather();
1414 
1415         Self::write(fd, &data)
1416     }
1417 
1418     pub fn readv(fd: i32, iov: usize, count: usize) -> Result<usize, SystemError> {
1419         // IoVecs会进行用户态检验
1420         let mut iovecs = unsafe { IoVecs::from_user(iov as *const IoVec, count, true) }?;
1421 
1422         let mut data = vec![0; iovecs.0.iter().map(|x| x.len()).sum()];
1423 
1424         let len = Self::read(fd, &mut data)?;
1425 
1426         iovecs.scatter(&data[..len]);
1427 
1428         return Ok(len);
1429     }
1430 
1431     pub fn readlink_at(
1432         dirfd: i32,
1433         path: *const u8,
1434         user_buf: *mut u8,
1435         buf_size: usize,
1436     ) -> Result<usize, SystemError> {
1437         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?;
1438         let path = path.as_str().trim();
1439         let mut user_buf = UserBufferWriter::new(user_buf, buf_size, true)?;
1440 
1441         let (inode, path) = user_path_at(&ProcessManager::current_pcb(), dirfd, path)?;
1442 
1443         let inode = inode.lookup(path.as_str())?;
1444         if inode.metadata()?.file_type != FileType::SymLink {
1445             return Err(SystemError::EINVAL);
1446         }
1447 
1448         let ubuf = user_buf.buffer::<u8>(0).unwrap();
1449 
1450         let file = File::new(inode, FileMode::O_RDONLY)?;
1451 
1452         let len = file.read(buf_size, ubuf)?;
1453 
1454         return Ok(len);
1455     }
1456 
1457     pub fn readlink(
1458         path: *const u8,
1459         user_buf: *mut u8,
1460         buf_size: usize,
1461     ) -> Result<usize, SystemError> {
1462         return Self::readlink_at(AtFlags::AT_FDCWD.bits(), path, user_buf, buf_size);
1463     }
1464 
1465     pub fn access(pathname: *const u8, mode: u32) -> Result<usize, SystemError> {
1466         return do_faccessat(
1467             AtFlags::AT_FDCWD.bits(),
1468             pathname,
1469             ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
1470             0,
1471         );
1472     }
1473 
1474     pub fn faccessat2(
1475         dirfd: i32,
1476         pathname: *const u8,
1477         mode: u32,
1478         flags: u32,
1479     ) -> Result<usize, SystemError> {
1480         return do_faccessat(
1481             dirfd,
1482             pathname,
1483             ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
1484             flags,
1485         );
1486     }
1487 
1488     pub fn chmod(pathname: *const u8, mode: u32) -> Result<usize, SystemError> {
1489         return do_fchmodat(
1490             AtFlags::AT_FDCWD.bits(),
1491             pathname,
1492             ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
1493         );
1494     }
1495 
1496     pub fn fchmodat(dirfd: i32, pathname: *const u8, mode: u32) -> Result<usize, SystemError> {
1497         return do_fchmodat(
1498             dirfd,
1499             pathname,
1500             ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
1501         );
1502     }
1503 
1504     pub fn fchmod(fd: i32, mode: u32) -> Result<usize, SystemError> {
1505         let _mode = ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?;
1506         let binding = ProcessManager::current_pcb().fd_table();
1507         let fd_table_guard = binding.read();
1508         let _file = fd_table_guard
1509             .get_file_by_fd(fd)
1510             .ok_or(SystemError::EBADF)?;
1511 
1512         // fchmod没完全实现,因此不修改文件的权限
1513         // todo: 实现fchmod
1514         kwarn!("fchmod not fully implemented");
1515         return Ok(0);
1516     }
1517     /// #挂载文件系统
1518     ///
1519     /// 用于挂载文件系统,目前仅支持ramfs挂载
1520     ///
1521     /// ## 参数:
1522     ///
1523     /// - source       挂载设备(暂时不支持)
1524     /// - target       挂载目录
1525     /// - filesystemtype   文件系统
1526     /// - mountflags     挂载选项(暂未实现)
1527     /// - data        带数据挂载
1528     ///
1529     /// ## 返回值
1530     /// - Ok(0): 挂载成功
1531     /// - Err(SystemError) :挂载过程中出错
1532     pub fn mount(
1533         _source: *const u8,
1534         target: *const u8,
1535         filesystemtype: *const u8,
1536         _mountflags: usize,
1537         _data: *const c_void,
1538     ) -> Result<usize, SystemError> {
1539         let target = user_access::check_and_clone_cstr(target, Some(MAX_PATHLEN))?;
1540 
1541         let filesystemtype = user_access::check_and_clone_cstr(filesystemtype, Some(MAX_PATHLEN))?;
1542 
1543         let filesystemtype = producefs!(FSMAKER, filesystemtype)?;
1544 
1545         return Vcore::do_mount(filesystemtype, target.to_string().as_str());
1546     }
1547 
1548     // 想法:可以在VFS中实现一个文件系统分发器,流程如下:
1549     // 1. 接受从上方传来的文件类型字符串
1550     // 2. 将传入值与启动时准备好的字符串数组逐个比较(probe)
1551     // 3. 直接在函数内调用构造方法并直接返回文件系统对象
1552 }
1553 
1554 #[repr(C)]
1555 #[derive(Debug, Clone, Copy)]
1556 pub struct IoVec {
1557     /// 缓冲区的起始地址
1558     pub iov_base: *mut u8,
1559     /// 缓冲区的长度
1560     pub iov_len: usize,
1561 }
1562 
1563 /// 用于存储多个来自用户空间的IoVec
1564 ///
1565 /// 由于目前内核中的文件系统还不支持分散读写,所以暂时只支持将用户空间的IoVec聚合成一个缓冲区,然后进行操作。
1566 /// TODO:支持分散读写
1567 #[derive(Debug)]
1568 pub struct IoVecs(Vec<&'static mut [u8]>);
1569 
1570 impl IoVecs {
1571     /// 从用户空间的IoVec中构造IoVecs
1572     ///
1573     /// @param iov 用户空间的IoVec
1574     /// @param iovcnt 用户空间的IoVec的数量
1575     /// @param readv 是否为readv系统调用
1576     ///
1577     /// @return 构造成功返回IoVecs,否则返回错误码
1578     pub unsafe fn from_user(
1579         iov: *const IoVec,
1580         iovcnt: usize,
1581         _readv: bool,
1582     ) -> Result<Self, SystemError> {
1583         // 检查iov指针所在空间是否合法
1584         verify_area(
1585             VirtAddr::new(iov as usize),
1586             iovcnt * core::mem::size_of::<IoVec>(),
1587         )
1588         .map_err(|_| SystemError::EFAULT)?;
1589 
1590         // 将用户空间的IoVec转换为引用(注意:这里的引用是静态的,因为用户空间的IoVec不会被释放)
1591         let iovs: &[IoVec] = core::slice::from_raw_parts(iov, iovcnt);
1592 
1593         let mut slices: Vec<&mut [u8]> = vec![];
1594         slices.reserve(iovs.len());
1595 
1596         for iov in iovs.iter() {
1597             if iov.iov_len == 0 {
1598                 continue;
1599             }
1600 
1601             verify_area(
1602                 VirtAddr::new(iov.iov_base as usize),
1603                 iovcnt * core::mem::size_of::<IoVec>(),
1604             )
1605             .map_err(|_| SystemError::EFAULT)?;
1606 
1607             slices.push(core::slice::from_raw_parts_mut(iov.iov_base, iov.iov_len));
1608         }
1609 
1610         return Ok(Self(slices));
1611     }
1612 
1613     /// @brief 将IoVecs中的数据聚合到一个缓冲区中
1614     ///
1615     /// @return 返回聚合后的缓冲区
1616     pub fn gather(&self) -> Vec<u8> {
1617         let mut buf = Vec::new();
1618         for slice in self.0.iter() {
1619             buf.extend_from_slice(slice);
1620         }
1621         return buf;
1622     }
1623 
1624     /// @brief 将给定的数据分散写入到IoVecs中
1625     pub fn scatter(&mut self, data: &[u8]) {
1626         let mut data: &[u8] = data;
1627         for slice in self.0.iter_mut() {
1628             let len = core::cmp::min(slice.len(), data.len());
1629             if len == 0 {
1630                 continue;
1631             }
1632 
1633             slice[..len].copy_from_slice(&data[..len]);
1634             data = &data[len..];
1635         }
1636     }
1637 
1638     /// @brief 创建与IoVecs等长的缓冲区
1639     ///
1640     /// @param set_len 是否设置返回的Vec的len。
1641     /// 如果为true,则返回的Vec的len为所有IoVec的长度之和;
1642     /// 否则返回的Vec的len为0,capacity为所有IoVec的长度之和.
1643     ///
1644     /// @return 返回创建的缓冲区
1645     pub fn new_buf(&self, set_len: bool) -> Vec<u8> {
1646         let total_len: usize = self.0.iter().map(|slice| slice.len()).sum();
1647         let mut buf: Vec<u8> = Vec::with_capacity(total_len);
1648 
1649         if set_len {
1650             buf.resize(total_len, 0);
1651         }
1652         return buf;
1653     }
1654 }
1655