xref: /DragonOS/kernel/src/filesystem/vfs/syscall.rs (revision fae6e9ade46a52976ad5d099643d51cc20876448)
1 use core::ffi::c_void;
2 use core::mem::size_of;
3 
4 use alloc::{string::String, sync::Arc, vec::Vec};
5 use log::warn;
6 use system_error::SystemError;
7 
8 use crate::producefs;
9 use crate::syscall::user_access::UserBufferReader;
10 use crate::{
11     driver::base::{block::SeekFrom, device::device_number::DeviceNumber},
12     filesystem::vfs::{core as Vcore, file::FileDescriptorVec},
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::{syscall::PosixTimeval, PosixTimeSpec},
21 };
22 
23 use super::core::do_symlinkat;
24 use super::{
25     core::{do_mkdir_at, 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, do_utimensat, do_utimes},
29     utils::{rsplit_path, user_path_at},
30     Dirent, FileType, IndexNode, SuperBlock, FSMAKER, MAX_PATHLEN, ROOT_INODE,
31     VFS_MAX_FOLLOW_SYMLINK_TIMES,
32 };
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 bitflags! {
328     pub struct UtimensFlags: u32 {
329         /// 不需要解释符号链接
330         const AT_SYMLINK_NOFOLLOW = 0x100;
331     }
332 }
333 
334 #[repr(C)]
335 #[derive(Debug, Clone, Copy)]
336 pub struct PosixStatfs {
337     f_type: u64,
338     f_bsize: u64,
339     f_blocks: u64,
340     f_bfree: u64,
341     f_bavail: u64,
342     f_files: u64,
343     f_ffree: u64,
344     f_fsid: u64,
345     f_namelen: u64,
346     f_frsize: u64,
347     f_flags: u64,
348     f_spare: [u64; 4],
349 }
350 
351 impl From<SuperBlock> for PosixStatfs {
352     fn from(super_block: SuperBlock) -> Self {
353         Self {
354             f_type: super_block.magic.bits,
355             f_bsize: super_block.bsize,
356             f_blocks: super_block.blocks,
357             f_bfree: super_block.bfree,
358             f_bavail: super_block.bavail,
359             f_files: super_block.files,
360             f_ffree: super_block.ffree,
361             f_fsid: super_block.fsid,
362             f_namelen: super_block.namelen,
363             f_frsize: super_block.frsize,
364             f_flags: super_block.flags,
365             f_spare: [0u64; 4],
366         }
367     }
368 }
369 ///
370 ///  Arguments for how openat2(2) should open the target path. If only @flags and
371 ///  @mode are non-zero, then openat2(2) operates very similarly to openat(2).
372 ///
373 ///  However, unlike openat(2), unknown or invalid bits in @flags result in
374 ///  -EINVAL rather than being silently ignored. @mode must be zero unless one of
375 ///  {O_CREAT, O_TMPFILE} are set.
376 ///
377 /// ## 成员变量
378 ///
379 /// - flags: O_* flags.
380 /// - mode: O_CREAT/O_TMPFILE file mode.
381 /// - resolve: RESOLVE_* flags.
382 #[derive(Debug, Clone, Copy)]
383 #[repr(C)]
384 pub struct PosixOpenHow {
385     pub flags: u64,
386     pub mode: u64,
387     pub resolve: u64,
388 }
389 
390 impl PosixOpenHow {
391     #[allow(dead_code)]
392     pub fn new(flags: u64, mode: u64, resolve: u64) -> Self {
393         Self {
394             flags,
395             mode,
396             resolve,
397         }
398     }
399 }
400 
401 #[allow(dead_code)]
402 #[derive(Debug, Clone, Copy)]
403 pub struct OpenHow {
404     pub o_flags: FileMode,
405     pub mode: ModeType,
406     pub resolve: OpenHowResolve,
407 }
408 
409 impl OpenHow {
410     pub fn new(mut o_flags: FileMode, mut mode: ModeType, resolve: OpenHowResolve) -> Self {
411         if !o_flags.contains(FileMode::O_CREAT) {
412             mode = ModeType::empty();
413         }
414 
415         if o_flags.contains(FileMode::O_PATH) {
416             o_flags = o_flags.intersection(FileMode::O_PATH_FLAGS);
417         }
418 
419         Self {
420             o_flags,
421             mode,
422             resolve,
423         }
424     }
425 }
426 
427 impl From<PosixOpenHow> for OpenHow {
428     fn from(posix_open_how: PosixOpenHow) -> Self {
429         let o_flags = FileMode::from_bits_truncate(posix_open_how.flags as u32);
430         let mode = ModeType::from_bits_truncate(posix_open_how.mode as u32);
431         let resolve = OpenHowResolve::from_bits_truncate(posix_open_how.resolve);
432         return Self::new(o_flags, mode, resolve);
433     }
434 }
435 
436 bitflags! {
437     pub struct OpenHowResolve: u64{
438         /// Block mount-point crossings
439         ///     (including bind-mounts).
440         const RESOLVE_NO_XDEV = 0x01;
441 
442         /// Block traversal through procfs-style
443         ///     "magic-links"
444         const RESOLVE_NO_MAGICLINKS = 0x02;
445 
446         /// Block traversal through all symlinks
447         ///     (implies OEXT_NO_MAGICLINKS)
448         const RESOLVE_NO_SYMLINKS = 0x04;
449         /// Block "lexical" trickery like
450         ///     "..", symlinks, and absolute
451         const RESOLVE_BENEATH = 0x08;
452         /// Make all jumps to "/" and ".."
453         ///     be scoped inside the dirfd
454         ///     (similar to chroot(2)).
455         const RESOLVE_IN_ROOT = 0x10;
456         // Only complete if resolution can be
457         // 			completed through cached lookup. May
458         // 			return -EAGAIN if that's not
459         // 			possible.
460         const RESOLVE_CACHED = 0x20;
461     }
462 }
463 
464 bitflags! {
465     pub struct UmountFlag: i32 {
466         const DEFAULT = 0;          /* Default call to umount. */
467         const MNT_FORCE = 1;        /* Force unmounting.  */
468         const MNT_DETACH = 2;       /* Just detach from the tree.  */
469         const MNT_EXPIRE = 4;       /* Mark for expiry.  */
470         const UMOUNT_NOFOLLOW = 8;  /* Don't follow symlink on umount.  */
471     }
472 }
473 
474 impl Syscall {
475     /// @brief 为当前进程打开一个文件
476     ///
477     /// @param path 文件路径
478     /// @param o_flags 打开文件的标志位
479     ///
480     /// @return 文件描述符编号,或者是错误码
481     pub fn open(
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             .into_string()
489             .map_err(|_| SystemError::EINVAL)?;
490 
491         let open_flags: FileMode = FileMode::from_bits(o_flags).ok_or(SystemError::EINVAL)?;
492         let mode = ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?;
493         return do_sys_open(
494             AtFlags::AT_FDCWD.bits(),
495             &path,
496             open_flags,
497             mode,
498             follow_symlink,
499         );
500     }
501 
502     pub fn openat(
503         dirfd: i32,
504         path: *const u8,
505         o_flags: u32,
506         mode: u32,
507         follow_symlink: bool,
508     ) -> Result<usize, SystemError> {
509         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?
510             .into_string()
511             .map_err(|_| SystemError::EINVAL)?;
512 
513         let open_flags: FileMode = FileMode::from_bits(o_flags).ok_or(SystemError::EINVAL)?;
514         let mode = ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?;
515         return do_sys_open(dirfd, &path, open_flags, mode, follow_symlink);
516     }
517 
518     /// @brief 关闭文件
519     ///
520     /// @param fd 文件描述符编号
521     ///
522     /// @return 成功返回0,失败返回错误码
523     pub fn close(fd: usize) -> Result<usize, SystemError> {
524         let binding = ProcessManager::current_pcb().fd_table();
525         let mut fd_table_guard = binding.write();
526         let _file = fd_table_guard.drop_fd(fd as i32)?;
527         drop(fd_table_guard);
528         Ok(0)
529     }
530 
531     /// @brief 发送命令到文件描述符对应的设备,
532     ///
533     /// @param fd 文件描述符编号
534     /// @param cmd 设备相关的请求类型
535     ///
536     /// @return Ok(usize) 成功返回0
537     /// @return Err(SystemError) 读取失败,返回posix错误码
538     pub fn ioctl(fd: usize, cmd: u32, data: usize) -> Result<usize, SystemError> {
539         let binding = ProcessManager::current_pcb().fd_table();
540         let fd_table_guard = binding.read();
541 
542         let file = fd_table_guard
543             .get_file_by_fd(fd as i32)
544             .ok_or(SystemError::EBADF)?;
545 
546         // drop guard 以避免无法调度的问题
547         drop(fd_table_guard);
548         let r = file.inode().ioctl(cmd, data, &file.private_data.lock());
549         return r;
550     }
551 
552     /// @brief 根据文件描述符,读取文件数据。尝试读取的数据长度与buf的长度相同。
553     ///
554     /// @param fd 文件描述符编号
555     /// @param buf 输出缓冲区
556     ///
557     /// @return Ok(usize) 成功读取的数据的字节数
558     /// @return Err(SystemError) 读取失败,返回posix错误码
559     pub fn read(fd: i32, buf: &mut [u8]) -> Result<usize, SystemError> {
560         let binding = ProcessManager::current_pcb().fd_table();
561         let fd_table_guard = binding.read();
562 
563         let file = fd_table_guard.get_file_by_fd(fd);
564         if file.is_none() {
565             return Err(SystemError::EBADF);
566         }
567         // drop guard 以避免无法调度的问题
568         drop(fd_table_guard);
569         let file = file.unwrap();
570 
571         return file.read(buf.len(), buf);
572     }
573 
574     /// @brief 根据文件描述符,向文件写入数据。尝试写入的数据长度与buf的长度相同。
575     ///
576     /// @param fd 文件描述符编号
577     /// @param buf 输入缓冲区
578     ///
579     /// @return Ok(usize) 成功写入的数据的字节数
580     /// @return Err(SystemError) 写入失败,返回posix错误码
581     pub fn write(fd: i32, buf: &[u8]) -> Result<usize, SystemError> {
582         let binding = ProcessManager::current_pcb().fd_table();
583         let fd_table_guard = binding.read();
584 
585         let file = fd_table_guard
586             .get_file_by_fd(fd)
587             .ok_or(SystemError::EBADF)?;
588 
589         // drop guard 以避免无法调度的问题
590         drop(fd_table_guard);
591         return file.write(buf.len(), buf);
592     }
593 
594     /// @brief 调整文件操作指针的位置
595     ///
596     /// @param fd 文件描述符编号
597     /// @param seek 调整的方式
598     ///
599     /// @return Ok(usize) 调整后,文件访问指针相对于文件头部的偏移量
600     /// @return Err(SystemError) 调整失败,返回posix错误码
601     pub fn lseek(fd: i32, offset: i64, seek: u32) -> Result<usize, SystemError> {
602         let seek = match seek {
603             SEEK_SET => Ok(SeekFrom::SeekSet(offset)),
604             SEEK_CUR => Ok(SeekFrom::SeekCurrent(offset)),
605             SEEK_END => Ok(SeekFrom::SeekEnd(offset)),
606             SEEK_MAX => Ok(SeekFrom::SeekEnd(0)),
607             _ => Err(SystemError::EINVAL),
608         }?;
609 
610         let binding = ProcessManager::current_pcb().fd_table();
611         let fd_table_guard = binding.read();
612         let file = fd_table_guard
613             .get_file_by_fd(fd)
614             .ok_or(SystemError::EBADF)?;
615 
616         // drop guard 以避免无法调度的问题
617         drop(fd_table_guard);
618         return file.lseek(seek);
619     }
620 
621     /// # sys_pread64 系统调用的实际执行函数
622     ///
623     /// ## 参数
624     /// - `fd`: 文件描述符
625     /// - `buf`: 读出缓冲区
626     /// - `len`: 要读取的字节数
627     /// - `offset`: 文件偏移量
628     pub fn pread(fd: i32, buf: &mut [u8], len: usize, offset: usize) -> Result<usize, SystemError> {
629         let binding = ProcessManager::current_pcb().fd_table();
630         let fd_table_guard = binding.read();
631 
632         let file = fd_table_guard.get_file_by_fd(fd);
633         if file.is_none() {
634             return Err(SystemError::EBADF);
635         }
636         // drop guard 以避免无法调度的问题
637         drop(fd_table_guard);
638         let file = file.unwrap();
639 
640         return file.pread(offset, len, buf);
641     }
642 
643     /// # sys_pwrite64 系统调用的实际执行函数
644     ///
645     /// ## 参数
646     /// - `fd`: 文件描述符
647     /// - `buf`: 写入缓冲区
648     /// - `len`: 要写入的字节数
649     /// - `offset`: 文件偏移量
650     pub fn pwrite(fd: i32, buf: &[u8], len: usize, offset: usize) -> Result<usize, SystemError> {
651         let binding = ProcessManager::current_pcb().fd_table();
652         let fd_table_guard = binding.read();
653 
654         let file = fd_table_guard.get_file_by_fd(fd);
655         if file.is_none() {
656             return Err(SystemError::EBADF);
657         }
658         // drop guard 以避免无法调度的问题
659         drop(fd_table_guard);
660         let file = file.unwrap();
661 
662         return file.pwrite(offset, len, buf);
663     }
664 
665     /// @brief 切换工作目录
666     ///
667     /// @param dest_path 目标路径
668     ///
669     /// @return   返回码  描述
670     ///      0       |          成功
671     ///
672     ///   EACCESS    |        权限不足
673     ///
674     ///    ELOOP     | 解析path时遇到路径循环
675     ///
676     /// ENAMETOOLONG |       路径名过长
677     ///
678     ///    ENOENT    |  目标文件或目录不存在
679     ///
680     ///    ENODIR    |  检索期间发现非目录项
681     ///
682     ///    ENOMEM    |      系统内存不足
683     ///
684     ///    EFAULT    |       错误的地址
685     ///
686     /// ENAMETOOLONG |        路径过长
687     pub fn chdir(path: *const u8) -> Result<usize, SystemError> {
688         if path.is_null() {
689             return Err(SystemError::EFAULT);
690         }
691 
692         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?
693             .into_string()
694             .map_err(|_| SystemError::EINVAL)?;
695 
696         let proc = ProcessManager::current_pcb();
697         // Copy path to kernel space to avoid some security issues
698         let mut new_path = String::from("");
699         if !path.is_empty() {
700             let cwd = match path.as_bytes()[0] {
701                 b'/' => String::from("/"),
702                 _ => proc.basic().cwd(),
703             };
704             let mut cwd_vec: Vec<_> = cwd.split('/').filter(|&x| !x.is_empty()).collect();
705             let path_split = path.split('/').filter(|&x| !x.is_empty());
706             for seg in path_split {
707                 if seg == ".." {
708                     cwd_vec.pop();
709                 } else if seg == "." {
710                     // 当前目录
711                 } else {
712                     cwd_vec.push(seg);
713                 }
714             }
715             //proc.basic().set_path(String::from(""));
716             for seg in cwd_vec {
717                 new_path.push('/');
718                 new_path.push_str(seg);
719             }
720             if new_path.is_empty() {
721                 new_path = String::from("/");
722             }
723         }
724         let inode =
725             match ROOT_INODE().lookup_follow_symlink(&new_path, VFS_MAX_FOLLOW_SYMLINK_TIMES) {
726                 Err(_) => {
727                     return Err(SystemError::ENOENT);
728                 }
729                 Ok(i) => i,
730             };
731         let metadata = inode.metadata()?;
732         if metadata.file_type == FileType::Dir {
733             proc.basic_mut().set_cwd(new_path);
734             return Ok(0);
735         } else {
736             return Err(SystemError::ENOTDIR);
737         }
738     }
739 
740     /// @brief 获取当前进程的工作目录路径
741     ///
742     /// @param buf 指向缓冲区的指针
743     /// @param size 缓冲区的大小
744     ///
745     /// @return 成功,返回的指针指向包含工作目录路径的字符串
746     /// @return 错误,没有足够的空间
747     pub fn getcwd(buf: &mut [u8]) -> Result<VirtAddr, SystemError> {
748         let proc = ProcessManager::current_pcb();
749         let cwd = proc.basic().cwd();
750 
751         let cwd_bytes = cwd.as_bytes();
752         let cwd_len = cwd_bytes.len();
753         if cwd_len + 1 > buf.len() {
754             return Err(SystemError::ENOMEM);
755         }
756         buf[..cwd_len].copy_from_slice(cwd_bytes);
757         buf[cwd_len] = 0;
758 
759         return Ok(VirtAddr::new(buf.as_ptr() as usize));
760     }
761 
762     /// @brief 获取目录中的数据
763     ///
764     /// TODO: 这个函数的语义与Linux不一致,需要修改!!!
765     ///
766     /// @param fd 文件描述符号
767     /// @param buf 输出缓冲区
768     ///
769     /// @return 成功返回读取的字节数,失败返回错误码
770     pub fn getdents(fd: i32, buf: &mut [u8]) -> Result<usize, SystemError> {
771         let dirent =
772             unsafe { (buf.as_mut_ptr() as *mut Dirent).as_mut() }.ok_or(SystemError::EFAULT)?;
773 
774         if fd < 0 || fd as usize > FileDescriptorVec::PROCESS_MAX_FD {
775             return Err(SystemError::EBADF);
776         }
777 
778         // 获取fd
779         let binding = ProcessManager::current_pcb().fd_table();
780         let fd_table_guard = binding.read();
781         let file = fd_table_guard
782             .get_file_by_fd(fd)
783             .ok_or(SystemError::EBADF)?;
784 
785         // drop guard 以避免无法调度的问题
786         drop(fd_table_guard);
787 
788         let res = file.readdir(dirent).map(|x| x as usize);
789 
790         return res;
791     }
792 
793     /// @brief 创建文件夹
794     ///
795     /// @param path(r8) 路径 / mode(r9) 模式
796     ///
797     /// @return uint64_t 负数错误码 / 0表示成功
798     pub fn mkdir(path: *const u8, mode: usize) -> Result<usize, SystemError> {
799         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?
800             .into_string()
801             .map_err(|_| SystemError::EINVAL)?;
802 
803         do_mkdir_at(
804             AtFlags::AT_FDCWD.bits(),
805             &path,
806             FileMode::from_bits_truncate(mode as u32),
807         )?;
808         return Ok(0);
809     }
810 
811     pub fn mkdir_at(dirfd: i32, path: *const u8, mode: usize) -> Result<usize, SystemError> {
812         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?
813             .into_string()
814             .map_err(|_| SystemError::EINVAL)?;
815         do_mkdir_at(dirfd, &path, FileMode::from_bits_truncate(mode as u32))?;
816         return Ok(0);
817     }
818 
819     /// **创建硬连接的系统调用**
820     ///
821     /// ## 参数
822     ///
823     /// - 'oldfd': 用于解析源文件路径的文件描述符
824     /// - 'old': 源文件路径
825     /// - 'newfd': 用于解析新文件路径的文件描述符
826     /// - 'new': 新文件将创建的路径
827     /// - 'flags': 标志位,仅以位或方式包含AT_EMPTY_PATH和AT_SYMLINK_FOLLOW
828     ///
829     ///
830     pub fn do_linkat(
831         oldfd: i32,
832         old: &str,
833         newfd: i32,
834         new: &str,
835         flags: AtFlags,
836     ) -> Result<usize, SystemError> {
837         // flag包含其他未规定值时返回EINVAL
838         if !(AtFlags::AT_EMPTY_PATH | AtFlags::AT_SYMLINK_FOLLOW).contains(flags) {
839             return Err(SystemError::EINVAL);
840         }
841         // TODO AT_EMPTY_PATH标志启用时,进行调用者CAP_DAC_READ_SEARCH或相似的检查
842         let symlink_times = if flags.contains(AtFlags::AT_SYMLINK_FOLLOW) {
843             0_usize
844         } else {
845             VFS_MAX_FOLLOW_SYMLINK_TIMES
846         };
847         let pcb = ProcessManager::current_pcb();
848 
849         // 得到源路径的inode
850         let old_inode: Arc<dyn IndexNode> = if old.is_empty() {
851             if flags.contains(AtFlags::AT_EMPTY_PATH) {
852                 // 在AT_EMPTY_PATH启用时,old可以为空,old_inode实际为oldfd所指文件,但该文件不能为目录。
853                 let binding = pcb.fd_table();
854                 let fd_table_guard = binding.read();
855                 let file = fd_table_guard
856                     .get_file_by_fd(oldfd)
857                     .ok_or(SystemError::EBADF)?;
858                 let old_inode = file.inode();
859                 old_inode
860             } else {
861                 return Err(SystemError::ENONET);
862             }
863         } else {
864             let (old_begin_inode, old_remain_path) = user_path_at(&pcb, oldfd, old)?;
865             old_begin_inode.lookup_follow_symlink(&old_remain_path, symlink_times)?
866         };
867 
868         // old_inode为目录时返回EPERM
869         if old_inode.metadata().unwrap().file_type == FileType::Dir {
870             return Err(SystemError::EPERM);
871         }
872 
873         // 得到新创建节点的父节点
874         let (new_begin_inode, new_remain_path) = user_path_at(&pcb, newfd, new)?;
875         let (new_name, new_parent_path) = rsplit_path(&new_remain_path);
876         let new_parent =
877             new_begin_inode.lookup_follow_symlink(new_parent_path.unwrap_or("/"), symlink_times)?;
878 
879         // 被调用者利用downcast_ref判断两inode是否为同一文件系统
880         return new_parent.link(new_name, &old_inode).map(|_| 0);
881     }
882 
883     pub fn link(old: *const u8, new: *const u8) -> Result<usize, SystemError> {
884         let get_path = |cstr: *const u8| -> Result<String, SystemError> {
885             let res = check_and_clone_cstr(cstr, Some(MAX_PATHLEN))?
886                 .into_string()
887                 .map_err(|_| SystemError::EINVAL)?;
888 
889             if res.len() >= MAX_PATHLEN {
890                 return Err(SystemError::ENAMETOOLONG);
891             }
892             if res.is_empty() {
893                 return Err(SystemError::ENOENT);
894             }
895             Ok(res)
896         };
897         let old = get_path(old)?;
898         let new = get_path(new)?;
899         return Self::do_linkat(
900             AtFlags::AT_FDCWD.bits(),
901             &old,
902             AtFlags::AT_FDCWD.bits(),
903             &new,
904             AtFlags::empty(),
905         );
906     }
907 
908     pub fn linkat(
909         oldfd: i32,
910         old: *const u8,
911         newfd: i32,
912         new: *const u8,
913         flags: i32,
914     ) -> Result<usize, SystemError> {
915         let old = check_and_clone_cstr(old, Some(MAX_PATHLEN))?
916             .into_string()
917             .map_err(|_| SystemError::EINVAL)?;
918         let new = check_and_clone_cstr(new, Some(MAX_PATHLEN))?
919             .into_string()
920             .map_err(|_| SystemError::EINVAL)?;
921         if old.len() >= MAX_PATHLEN || new.len() >= MAX_PATHLEN {
922             return Err(SystemError::ENAMETOOLONG);
923         }
924         // old 根据flags & AtFlags::AT_EMPTY_PATH判空
925         if new.is_empty() {
926             return Err(SystemError::ENOENT);
927         }
928         let flags = AtFlags::from_bits(flags).ok_or(SystemError::EINVAL)?;
929         Self::do_linkat(oldfd, &old, newfd, &new, flags)
930     }
931 
932     /// **删除文件夹、取消文件的链接、删除文件的系统调用**
933     ///
934     /// ## 参数
935     ///
936     /// - `dirfd`:文件夹的文件描述符.目前暂未实现
937     /// - `pathname`:文件夹的路径
938     /// - `flags`:标志位
939     ///
940     ///
941     pub fn unlinkat(dirfd: i32, path: *const u8, flags: u32) -> Result<usize, SystemError> {
942         let flags = AtFlags::from_bits(flags as i32).ok_or(SystemError::EINVAL)?;
943 
944         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?
945             .into_string()
946             .map_err(|_| SystemError::EINVAL)?;
947 
948         if flags.contains(AtFlags::AT_REMOVEDIR) {
949             // debug!("rmdir");
950             match do_remove_dir(dirfd, &path) {
951                 Err(err) => {
952                     return Err(err);
953                 }
954                 Ok(_) => {
955                     return Ok(0);
956                 }
957             }
958         }
959 
960         match do_unlink_at(dirfd, &path) {
961             Err(err) => {
962                 return Err(err);
963             }
964             Ok(_) => {
965                 return Ok(0);
966             }
967         }
968     }
969 
970     pub fn rmdir(path: *const u8) -> Result<usize, SystemError> {
971         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?
972             .into_string()
973             .map_err(|_| SystemError::EINVAL)?;
974         return do_remove_dir(AtFlags::AT_FDCWD.bits(), &path).map(|v| v as usize);
975     }
976 
977     pub fn unlink(path: *const u8) -> Result<usize, SystemError> {
978         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?
979             .into_string()
980             .map_err(|_| SystemError::EINVAL)?;
981         return do_unlink_at(AtFlags::AT_FDCWD.bits(), &path).map(|v| v as usize);
982     }
983 
984     pub fn symlink(oldname: *const u8, newname: *const u8) -> Result<usize, SystemError> {
985         return do_symlinkat(oldname, AtFlags::AT_FDCWD.bits(), newname);
986     }
987 
988     pub fn symlinkat(
989         oldname: *const u8,
990         newdfd: i32,
991         newname: *const u8,
992     ) -> Result<usize, SystemError> {
993         return do_symlinkat(oldname, newdfd, newname);
994     }
995 
996     /// # 修改文件名
997     ///
998     ///
999     /// ## 参数
1000     ///
1001     /// - oldfd: 源文件夹文件描述符
1002     /// - filename_from: 源文件路径
1003     /// - newfd: 目标文件夹文件描述符
1004     /// - filename_to: 目标文件路径
1005     /// - flags: 标志位
1006     ///
1007     ///
1008     /// ## 返回值
1009     /// - Ok(返回值类型): 返回值的说明
1010     /// - Err(错误值类型): 错误的说明
1011     ///
1012     pub fn do_renameat2(
1013         oldfd: i32,
1014         filename_from: *const u8,
1015         newfd: i32,
1016         filename_to: *const u8,
1017         _flags: u32,
1018     ) -> Result<usize, SystemError> {
1019         let filename_from = check_and_clone_cstr(filename_from, Some(MAX_PATHLEN))
1020             .unwrap()
1021             .into_string()
1022             .map_err(|_| SystemError::EINVAL)?;
1023         let filename_to = check_and_clone_cstr(filename_to, Some(MAX_PATHLEN))
1024             .unwrap()
1025             .into_string()
1026             .map_err(|_| SystemError::EINVAL)?;
1027         // 文件名过长
1028         if filename_from.len() > MAX_PATHLEN || filename_to.len() > MAX_PATHLEN {
1029             return Err(SystemError::ENAMETOOLONG);
1030         }
1031 
1032         //获取pcb,文件节点
1033         let pcb = ProcessManager::current_pcb();
1034         let (_old_inode_begin, old_remain_path) = user_path_at(&pcb, oldfd, &filename_from)?;
1035         let (_new_inode_begin, new_remain_path) = user_path_at(&pcb, newfd, &filename_to)?;
1036         //获取父目录
1037         let (old_filename, old_parent_path) = rsplit_path(&old_remain_path);
1038         let old_parent_inode = ROOT_INODE()
1039             .lookup_follow_symlink(old_parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
1040         let (new_filename, new_parent_path) = rsplit_path(&new_remain_path);
1041         let new_parent_inode = ROOT_INODE()
1042             .lookup_follow_symlink(new_parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
1043         old_parent_inode.move_to(old_filename, &new_parent_inode, new_filename)?;
1044         return Ok(0);
1045     }
1046 
1047     /// @brief 根据提供的文件描述符的fd,复制对应的文件结构体,并返回新复制的文件结构体对应的fd
1048     pub fn dup(oldfd: i32) -> Result<usize, SystemError> {
1049         let binding = ProcessManager::current_pcb().fd_table();
1050         let mut fd_table_guard = binding.write();
1051 
1052         let old_file = fd_table_guard
1053             .get_file_by_fd(oldfd)
1054             .ok_or(SystemError::EBADF)?;
1055 
1056         let new_file = old_file.try_clone().ok_or(SystemError::EBADF)?;
1057         // dup默认非cloexec
1058         new_file.set_close_on_exec(false);
1059         // 申请文件描述符,并把文件对象存入其中
1060         let res = fd_table_guard.alloc_fd(new_file, None).map(|x| x as usize);
1061         return res;
1062     }
1063 
1064     /// 根据提供的文件描述符的fd,和指定新fd,复制对应的文件结构体,
1065     /// 并返回新复制的文件结构体对应的fd.
1066     /// 如果新fd已经打开,则会先关闭新fd.
1067     ///
1068     /// ## 参数
1069     ///
1070     /// - `oldfd`:旧文件描述符
1071     /// - `newfd`:新文件描述符
1072     ///
1073     /// ## 返回值
1074     ///
1075     /// - 成功:新文件描述符
1076     /// - 失败:错误码
1077     pub fn dup2(oldfd: i32, newfd: i32) -> Result<usize, SystemError> {
1078         let binding = ProcessManager::current_pcb().fd_table();
1079         let mut fd_table_guard = binding.write();
1080         return Self::do_dup2(oldfd, newfd, &mut fd_table_guard);
1081     }
1082 
1083     pub fn dup3(oldfd: i32, newfd: i32, flags: u32) -> Result<usize, SystemError> {
1084         let flags = FileMode::from_bits_truncate(flags);
1085         if (flags.bits() & !FileMode::O_CLOEXEC.bits()) != 0 {
1086             return Err(SystemError::EINVAL);
1087         }
1088 
1089         if oldfd == newfd {
1090             return Err(SystemError::EINVAL);
1091         }
1092 
1093         let binding = ProcessManager::current_pcb().fd_table();
1094         let mut fd_table_guard = binding.write();
1095         return Self::do_dup3(oldfd, newfd, flags, &mut fd_table_guard);
1096     }
1097 
1098     fn do_dup2(
1099         oldfd: i32,
1100         newfd: i32,
1101         fd_table_guard: &mut RwLockWriteGuard<'_, FileDescriptorVec>,
1102     ) -> Result<usize, SystemError> {
1103         Self::do_dup3(oldfd, newfd, FileMode::empty(), fd_table_guard)
1104     }
1105 
1106     fn do_dup3(
1107         oldfd: i32,
1108         newfd: i32,
1109         flags: FileMode,
1110         fd_table_guard: &mut RwLockWriteGuard<'_, FileDescriptorVec>,
1111     ) -> Result<usize, SystemError> {
1112         // 确认oldfd, newid是否有效
1113         if !(FileDescriptorVec::validate_fd(oldfd) && FileDescriptorVec::validate_fd(newfd)) {
1114             return Err(SystemError::EBADF);
1115         }
1116 
1117         if oldfd == newfd {
1118             // 若oldfd与newfd相等
1119             return Ok(newfd as usize);
1120         }
1121         let new_exists = fd_table_guard.get_file_by_fd(newfd).is_some();
1122         if new_exists {
1123             // close newfd
1124             if fd_table_guard.drop_fd(newfd).is_err() {
1125                 // An I/O error occurred while attempting to close fildes2.
1126                 return Err(SystemError::EIO);
1127             }
1128         }
1129 
1130         let old_file = fd_table_guard
1131             .get_file_by_fd(oldfd)
1132             .ok_or(SystemError::EBADF)?;
1133         let new_file = old_file.try_clone().ok_or(SystemError::EBADF)?;
1134 
1135         if flags.contains(FileMode::O_CLOEXEC) {
1136             new_file.set_close_on_exec(true);
1137         } else {
1138             new_file.set_close_on_exec(false);
1139         }
1140         // 申请文件描述符,并把文件对象存入其中
1141         let res = fd_table_guard
1142             .alloc_fd(new_file, Some(newfd))
1143             .map(|x| x as usize);
1144         return res;
1145     }
1146 
1147     /// # fcntl
1148     ///
1149     /// ## 参数
1150     ///
1151     /// - `fd`:文件描述符
1152     /// - `cmd`:命令
1153     /// - `arg`:参数
1154     pub fn fcntl(fd: i32, cmd: FcntlCommand, arg: i32) -> Result<usize, SystemError> {
1155         // debug!("fcntl ({cmd:?}) fd: {fd}, arg={arg}");
1156         match cmd {
1157             FcntlCommand::DupFd | FcntlCommand::DupFdCloexec => {
1158                 if arg < 0 || arg as usize >= FileDescriptorVec::PROCESS_MAX_FD {
1159                     return Err(SystemError::EBADF);
1160                 }
1161                 let arg = arg as usize;
1162                 for i in arg..FileDescriptorVec::PROCESS_MAX_FD {
1163                     let binding = ProcessManager::current_pcb().fd_table();
1164                     let mut fd_table_guard = binding.write();
1165                     if fd_table_guard.get_file_by_fd(i as i32).is_none() {
1166                         if cmd == FcntlCommand::DupFd {
1167                             return Self::do_dup2(fd, i as i32, &mut fd_table_guard);
1168                         } else {
1169                             return Self::do_dup3(
1170                                 fd,
1171                                 i as i32,
1172                                 FileMode::O_CLOEXEC,
1173                                 &mut fd_table_guard,
1174                             );
1175                         }
1176                     }
1177                 }
1178                 return Err(SystemError::EMFILE);
1179             }
1180             FcntlCommand::GetFd => {
1181                 // Get file descriptor flags.
1182                 let binding = ProcessManager::current_pcb().fd_table();
1183                 let fd_table_guard = binding.read();
1184 
1185                 if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
1186                     // drop guard 以避免无法调度的问题
1187                     drop(fd_table_guard);
1188 
1189                     if file.close_on_exec() {
1190                         return Ok(FD_CLOEXEC as usize);
1191                     } else {
1192                         return Ok(0);
1193                     }
1194                 }
1195                 return Err(SystemError::EBADF);
1196             }
1197             FcntlCommand::SetFd => {
1198                 // Set file descriptor flags.
1199                 let binding = ProcessManager::current_pcb().fd_table();
1200                 let fd_table_guard = binding.write();
1201 
1202                 if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
1203                     // drop guard 以避免无法调度的问题
1204                     drop(fd_table_guard);
1205                     let arg = arg as u32;
1206                     if arg & FD_CLOEXEC != 0 {
1207                         file.set_close_on_exec(true);
1208                     } else {
1209                         file.set_close_on_exec(false);
1210                     }
1211                     return Ok(0);
1212                 }
1213                 return Err(SystemError::EBADF);
1214             }
1215 
1216             FcntlCommand::GetFlags => {
1217                 // Get file status flags.
1218                 let binding = ProcessManager::current_pcb().fd_table();
1219                 let fd_table_guard = binding.read();
1220 
1221                 if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
1222                     // drop guard 以避免无法调度的问题
1223                     drop(fd_table_guard);
1224                     return Ok(file.mode().bits() as usize);
1225                 }
1226 
1227                 return Err(SystemError::EBADF);
1228             }
1229             FcntlCommand::SetFlags => {
1230                 // Set file status flags.
1231                 let binding = ProcessManager::current_pcb().fd_table();
1232                 let fd_table_guard = binding.write();
1233 
1234                 if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
1235                     let arg = arg as u32;
1236                     let mode = FileMode::from_bits(arg).ok_or(SystemError::EINVAL)?;
1237                     // drop guard 以避免无法调度的问题
1238                     drop(fd_table_guard);
1239                     file.set_mode(mode)?;
1240                     return Ok(0);
1241                 }
1242 
1243                 return Err(SystemError::EBADF);
1244             }
1245             _ => {
1246                 // TODO: unimplemented
1247                 // 未实现的命令,返回0,不报错。
1248 
1249                 warn!("fcntl: unimplemented command: {:?}, defaults to 0.", cmd);
1250                 return Err(SystemError::ENOSYS);
1251             }
1252         }
1253     }
1254 
1255     /// # ftruncate
1256     ///
1257     /// ## 描述
1258     ///
1259     /// 改变文件大小.
1260     /// 如果文件大小大于原来的大小,那么文件的内容将会被扩展到指定的大小,新的空间将会用0填充.
1261     /// 如果文件大小小于原来的大小,那么文件的内容将会被截断到指定的大小.
1262     ///
1263     /// ## 参数
1264     ///
1265     /// - `fd`:文件描述符
1266     /// - `len`:文件大小
1267     ///
1268     /// ## 返回值
1269     ///
1270     /// 如果成功,返回0,否则返回错误码.
1271     pub fn ftruncate(fd: i32, len: usize) -> Result<usize, SystemError> {
1272         let binding = ProcessManager::current_pcb().fd_table();
1273         let fd_table_guard = binding.read();
1274 
1275         if let Some(file) = fd_table_guard.get_file_by_fd(fd) {
1276             // drop guard 以避免无法调度的问题
1277             drop(fd_table_guard);
1278             let r = file.ftruncate(len).map(|_| 0);
1279             return r;
1280         }
1281 
1282         return Err(SystemError::EBADF);
1283     }
1284 
1285     fn do_fstat(fd: i32) -> Result<PosixKstat, SystemError> {
1286         let binding = ProcessManager::current_pcb().fd_table();
1287         let fd_table_guard = binding.read();
1288         let file = fd_table_guard
1289             .get_file_by_fd(fd)
1290             .ok_or(SystemError::EBADF)?;
1291         // drop guard 以避免无法调度的问题
1292         drop(fd_table_guard);
1293 
1294         let mut kstat = PosixKstat::new();
1295         // 获取文件信息
1296         let metadata = file.metadata()?;
1297         kstat.size = metadata.size;
1298         kstat.dev_id = metadata.dev_id as u64;
1299         kstat.inode = metadata.inode_id.into() as u64;
1300         kstat.blcok_size = metadata.blk_size as i64;
1301         kstat.blocks = metadata.blocks as u64;
1302 
1303         kstat.atime.tv_sec = metadata.atime.tv_sec;
1304         kstat.atime.tv_nsec = metadata.atime.tv_nsec;
1305         kstat.mtime.tv_sec = metadata.mtime.tv_sec;
1306         kstat.mtime.tv_nsec = metadata.mtime.tv_nsec;
1307         kstat.ctime.tv_sec = metadata.ctime.tv_sec;
1308         kstat.ctime.tv_nsec = metadata.ctime.tv_nsec;
1309 
1310         kstat.nlink = metadata.nlinks as u64;
1311         kstat.uid = metadata.uid as i32;
1312         kstat.gid = metadata.gid as i32;
1313         kstat.rdev = metadata.raw_dev.data() as i64;
1314         kstat.mode = metadata.mode;
1315         match file.file_type() {
1316             FileType::File => kstat.mode.insert(ModeType::S_IFREG),
1317             FileType::Dir => kstat.mode.insert(ModeType::S_IFDIR),
1318             FileType::BlockDevice => kstat.mode.insert(ModeType::S_IFBLK),
1319             FileType::CharDevice => kstat.mode.insert(ModeType::S_IFCHR),
1320             FileType::SymLink => kstat.mode.insert(ModeType::S_IFLNK),
1321             FileType::Socket => kstat.mode.insert(ModeType::S_IFSOCK),
1322             FileType::Pipe => kstat.mode.insert(ModeType::S_IFIFO),
1323             FileType::KvmDevice => kstat.mode.insert(ModeType::S_IFCHR),
1324             FileType::FramebufferDevice => kstat.mode.insert(ModeType::S_IFCHR),
1325         }
1326 
1327         return Ok(kstat);
1328     }
1329 
1330     pub fn fstat(fd: i32, usr_kstat: *mut PosixKstat) -> Result<usize, SystemError> {
1331         let mut writer = UserBufferWriter::new(usr_kstat, size_of::<PosixKstat>(), true)?;
1332         let kstat = Self::do_fstat(fd)?;
1333 
1334         writer.copy_one_to_user(&kstat, 0)?;
1335         return Ok(0);
1336     }
1337 
1338     pub fn stat(path: *const u8, user_kstat: *mut PosixKstat) -> Result<usize, SystemError> {
1339         let fd = Self::open(
1340             path,
1341             FileMode::O_RDONLY.bits(),
1342             ModeType::empty().bits(),
1343             true,
1344         )?;
1345         let r = Self::fstat(fd as i32, user_kstat);
1346         Self::close(fd).ok();
1347         return r;
1348     }
1349 
1350     pub fn lstat(path: *const u8, user_kstat: *mut PosixKstat) -> Result<usize, SystemError> {
1351         let fd = Self::open(
1352             path,
1353             FileMode::O_RDONLY.bits(),
1354             ModeType::empty().bits(),
1355             false,
1356         )?;
1357         let r = Self::fstat(fd as i32, user_kstat);
1358         Self::close(fd).ok();
1359         return r;
1360     }
1361 
1362     pub fn statfs(path: *const u8, user_statfs: *mut PosixStatfs) -> Result<usize, SystemError> {
1363         let mut writer = UserBufferWriter::new(user_statfs, size_of::<PosixStatfs>(), true)?;
1364         let fd = Self::open(
1365             path,
1366             FileMode::O_RDONLY.bits(),
1367             ModeType::empty().bits(),
1368             true,
1369         )?;
1370         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))
1371             .unwrap()
1372             .into_string()
1373             .map_err(|_| SystemError::EINVAL)?;
1374         let pcb = ProcessManager::current_pcb();
1375         let (_inode_begin, remain_path) = user_path_at(&pcb, fd as i32, &path)?;
1376         let inode = ROOT_INODE().lookup_follow_symlink(&remain_path, MAX_PATHLEN)?;
1377         let statfs = PosixStatfs::from(inode.fs().super_block());
1378         writer.copy_one_to_user(&statfs, 0)?;
1379         return Ok(0);
1380     }
1381 
1382     pub fn fstatfs(fd: i32, user_statfs: *mut PosixStatfs) -> Result<usize, SystemError> {
1383         let mut writer = UserBufferWriter::new(user_statfs, size_of::<PosixStatfs>(), true)?;
1384         let binding = ProcessManager::current_pcb().fd_table();
1385         let fd_table_guard = binding.read();
1386         let file = fd_table_guard
1387             .get_file_by_fd(fd)
1388             .ok_or(SystemError::EBADF)?;
1389         drop(fd_table_guard);
1390         let statfs = PosixStatfs::from(file.inode().fs().super_block());
1391         writer.copy_one_to_user(&statfs, 0)?;
1392         return Ok(0);
1393     }
1394 
1395     pub fn do_statx(
1396         fd: i32,
1397         path: *const u8,
1398         flags: u32,
1399         mask: u32,
1400         usr_kstat: *mut PosixStatx,
1401     ) -> Result<usize, SystemError> {
1402         if usr_kstat.is_null() {
1403             return Err(SystemError::EFAULT);
1404         }
1405 
1406         let mask = PosixStatxMask::from_bits_truncate(mask);
1407 
1408         if mask.contains(PosixStatxMask::STATX_RESERVED) {
1409             return Err(SystemError::ENAVAIL);
1410         }
1411 
1412         let flags = FileMode::from_bits_truncate(flags);
1413         let ofd = Self::open(path, flags.bits(), ModeType::empty().bits, true)?;
1414 
1415         let binding = ProcessManager::current_pcb().fd_table();
1416         let fd_table_guard = binding.read();
1417         let file = fd_table_guard
1418             .get_file_by_fd(ofd as i32)
1419             .ok_or(SystemError::EBADF)?;
1420         // drop guard 以避免无法调度的问题
1421         drop(fd_table_guard);
1422         let mut writer = UserBufferWriter::new(usr_kstat, size_of::<PosixStatx>(), true)?;
1423         let mut tmp: PosixStatx = PosixStatx::new();
1424         // 获取文件信息
1425         let metadata = file.metadata()?;
1426 
1427         tmp.stx_mask |= PosixStatxMask::STATX_BASIC_STATS;
1428         tmp.stx_blksize = metadata.blk_size as u32;
1429         if mask.contains(PosixStatxMask::STATX_MODE) || mask.contains(PosixStatxMask::STATX_TYPE) {
1430             tmp.stx_mode = metadata.mode;
1431         }
1432         if mask.contains(PosixStatxMask::STATX_NLINK) {
1433             tmp.stx_nlink = metadata.nlinks as u32;
1434         }
1435         if mask.contains(PosixStatxMask::STATX_UID) {
1436             tmp.stx_uid = metadata.uid as u32;
1437         }
1438         if mask.contains(PosixStatxMask::STATX_GID) {
1439             tmp.stx_gid = metadata.gid as u32;
1440         }
1441         if mask.contains(PosixStatxMask::STATX_ATIME) {
1442             tmp.stx_atime.tv_sec = metadata.atime.tv_sec;
1443             tmp.stx_atime.tv_nsec = metadata.atime.tv_nsec;
1444         }
1445         if mask.contains(PosixStatxMask::STATX_MTIME) {
1446             tmp.stx_mtime.tv_sec = metadata.ctime.tv_sec;
1447             tmp.stx_mtime.tv_nsec = metadata.ctime.tv_nsec;
1448         }
1449         if mask.contains(PosixStatxMask::STATX_CTIME) {
1450             // ctime是文件上次修改状态的时间
1451             tmp.stx_ctime.tv_sec = metadata.mtime.tv_sec;
1452             tmp.stx_ctime.tv_nsec = metadata.mtime.tv_nsec;
1453         }
1454         if mask.contains(PosixStatxMask::STATX_INO) {
1455             tmp.stx_inode = metadata.inode_id.into() as u64;
1456         }
1457         if mask.contains(PosixStatxMask::STATX_SIZE) {
1458             tmp.stx_size = metadata.size;
1459         }
1460         if mask.contains(PosixStatxMask::STATX_BLOCKS) {
1461             tmp.stx_blocks = metadata.blocks as u64;
1462         }
1463 
1464         if mask.contains(PosixStatxMask::STATX_BTIME) {
1465             // btime是文件创建时间
1466             tmp.stx_btime.tv_sec = metadata.ctime.tv_sec;
1467             tmp.stx_btime.tv_nsec = metadata.ctime.tv_nsec;
1468         }
1469         if mask.contains(PosixStatxMask::STATX_ALL) {
1470             tmp.stx_attributes = StxAttributes::STATX_ATTR_APPEND;
1471             tmp.stx_attributes_mask |=
1472                 StxAttributes::STATX_ATTR_AUTOMOUNT | StxAttributes::STATX_ATTR_DAX;
1473             tmp.stx_dev_major = metadata.dev_id as u32;
1474             tmp.stx_dev_minor = metadata.dev_id as u32; //
1475             tmp.stx_rdev_major = metadata.raw_dev.data();
1476             tmp.stx_rdev_minor = metadata.raw_dev.data();
1477         }
1478         if mask.contains(PosixStatxMask::STATX_MNT_ID) {
1479             tmp.stx_mnt_id = 0;
1480         }
1481         if mask.contains(PosixStatxMask::STATX_DIOALIGN) {
1482             tmp.stx_dio_mem_align = 0;
1483             tmp.stx_dio_offset_align = 0;
1484         }
1485 
1486         match file.file_type() {
1487             FileType::File => tmp.stx_mode.insert(ModeType::S_IFREG),
1488             FileType::Dir => tmp.stx_mode.insert(ModeType::S_IFDIR),
1489             FileType::BlockDevice => tmp.stx_mode.insert(ModeType::S_IFBLK),
1490             FileType::CharDevice => tmp.stx_mode.insert(ModeType::S_IFCHR),
1491             FileType::SymLink => tmp.stx_mode.insert(ModeType::S_IFLNK),
1492             FileType::Socket => tmp.stx_mode.insert(ModeType::S_IFSOCK),
1493             FileType::Pipe => tmp.stx_mode.insert(ModeType::S_IFIFO),
1494             FileType::KvmDevice => tmp.stx_mode.insert(ModeType::S_IFCHR),
1495             FileType::FramebufferDevice => tmp.stx_mode.insert(ModeType::S_IFCHR),
1496         }
1497 
1498         writer.copy_one_to_user(&tmp, 0)?;
1499         Self::close(fd as usize).ok();
1500         return Ok(0);
1501     }
1502 
1503     pub fn mknod(
1504         path: *const u8,
1505         mode: ModeType,
1506         dev_t: DeviceNumber,
1507     ) -> Result<usize, SystemError> {
1508         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?
1509             .into_string()
1510             .map_err(|_| SystemError::EINVAL)?;
1511         let path = path.as_str().trim();
1512 
1513         let inode: Result<Arc<dyn IndexNode>, SystemError> =
1514             ROOT_INODE().lookup_follow_symlink(path, VFS_MAX_FOLLOW_SYMLINK_TIMES);
1515 
1516         if inode.is_ok() {
1517             return Err(SystemError::EEXIST);
1518         }
1519 
1520         let (filename, parent_path) = rsplit_path(path);
1521 
1522         // 查找父目录
1523         let parent_inode: Arc<dyn IndexNode> = ROOT_INODE()
1524             .lookup_follow_symlink(parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
1525         // 创建nod
1526         parent_inode.mknod(filename, mode, dev_t)?;
1527 
1528         return Ok(0);
1529     }
1530 
1531     pub fn writev(fd: i32, iov: usize, count: usize) -> Result<usize, SystemError> {
1532         // IoVecs会进行用户态检验
1533         let iovecs = unsafe { IoVecs::from_user(iov as *const IoVec, count, false) }?;
1534 
1535         let data = iovecs.gather();
1536 
1537         Self::write(fd, &data)
1538     }
1539 
1540     pub fn readv(fd: i32, iov: usize, count: usize) -> Result<usize, SystemError> {
1541         // IoVecs会进行用户态检验
1542         let mut iovecs = unsafe { IoVecs::from_user(iov as *const IoVec, count, true) }?;
1543 
1544         let mut data = vec![0; iovecs.0.iter().map(|x| x.len()).sum()];
1545 
1546         let len = Self::read(fd, &mut data)?;
1547 
1548         iovecs.scatter(&data[..len]);
1549 
1550         return Ok(len);
1551     }
1552 
1553     pub fn readlink_at(
1554         dirfd: i32,
1555         path: *const u8,
1556         user_buf: *mut u8,
1557         buf_size: usize,
1558     ) -> Result<usize, SystemError> {
1559         let path = check_and_clone_cstr(path, Some(MAX_PATHLEN))?
1560             .into_string()
1561             .map_err(|_| SystemError::EINVAL)?;
1562         let path = path.as_str().trim();
1563         let mut user_buf = UserBufferWriter::new(user_buf, buf_size, true)?;
1564 
1565         let (inode, path) = user_path_at(&ProcessManager::current_pcb(), dirfd, path)?;
1566 
1567         let inode = inode.lookup(path.as_str())?;
1568         if inode.metadata()?.file_type != FileType::SymLink {
1569             return Err(SystemError::EINVAL);
1570         }
1571 
1572         let ubuf = user_buf.buffer::<u8>(0).unwrap();
1573 
1574         let file = File::new(inode, FileMode::O_RDONLY)?;
1575 
1576         let len = file.read(buf_size, ubuf)?;
1577 
1578         return Ok(len);
1579     }
1580 
1581     pub fn readlink(
1582         path: *const u8,
1583         user_buf: *mut u8,
1584         buf_size: usize,
1585     ) -> Result<usize, SystemError> {
1586         return Self::readlink_at(AtFlags::AT_FDCWD.bits(), path, user_buf, buf_size);
1587     }
1588 
1589     pub fn access(pathname: *const u8, mode: u32) -> Result<usize, SystemError> {
1590         return do_faccessat(
1591             AtFlags::AT_FDCWD.bits(),
1592             pathname,
1593             ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
1594             0,
1595         );
1596     }
1597 
1598     pub fn faccessat2(
1599         dirfd: i32,
1600         pathname: *const u8,
1601         mode: u32,
1602         flags: u32,
1603     ) -> Result<usize, SystemError> {
1604         return do_faccessat(
1605             dirfd,
1606             pathname,
1607             ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
1608             flags,
1609         );
1610     }
1611 
1612     pub fn chmod(pathname: *const u8, mode: u32) -> Result<usize, SystemError> {
1613         return do_fchmodat(
1614             AtFlags::AT_FDCWD.bits(),
1615             pathname,
1616             ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
1617         );
1618     }
1619 
1620     pub fn fchmodat(dirfd: i32, pathname: *const u8, mode: u32) -> Result<usize, SystemError> {
1621         return do_fchmodat(
1622             dirfd,
1623             pathname,
1624             ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?,
1625         );
1626     }
1627 
1628     pub fn fchmod(fd: i32, mode: u32) -> Result<usize, SystemError> {
1629         let _mode = ModeType::from_bits(mode).ok_or(SystemError::EINVAL)?;
1630         let binding = ProcessManager::current_pcb().fd_table();
1631         let fd_table_guard = binding.read();
1632         let _file = fd_table_guard
1633             .get_file_by_fd(fd)
1634             .ok_or(SystemError::EBADF)?;
1635 
1636         // fchmod没完全实现,因此不修改文件的权限
1637         // todo: 实现fchmod
1638         warn!("fchmod not fully implemented");
1639         return Ok(0);
1640     }
1641     /// #挂载文件系统
1642     ///
1643     /// 用于挂载文件系统,目前仅支持ramfs挂载
1644     ///
1645     /// ## 参数:
1646     ///
1647     /// - source       挂载设备(暂时不支持)
1648     /// - target       挂载目录
1649     /// - filesystemtype   文件系统
1650     /// - mountflags     挂载选项(暂未实现)
1651     /// - data        带数据挂载
1652     ///
1653     /// ## 返回值
1654     /// - Ok(0): 挂载成功
1655     /// - Err(SystemError) :挂载过程中出错
1656     pub fn mount(
1657         _source: *const u8,
1658         target: *const u8,
1659         filesystemtype: *const u8,
1660         _mountflags: usize,
1661         _data: *const c_void,
1662     ) -> Result<usize, SystemError> {
1663         let target = user_access::check_and_clone_cstr(target, Some(MAX_PATHLEN))?
1664             .into_string()
1665             .map_err(|_| SystemError::EINVAL)?;
1666 
1667         let fstype_str = user_access::check_and_clone_cstr(filesystemtype, Some(MAX_PATHLEN))?;
1668         let fstype_str = fstype_str.to_str().map_err(|_| SystemError::EINVAL)?;
1669 
1670         let fstype = producefs!(FSMAKER, fstype_str)?;
1671 
1672         Vcore::do_mount(fstype, &target)?;
1673 
1674         return Ok(0);
1675     }
1676 
1677     // 想法:可以在VFS中实现一个文件系统分发器,流程如下:
1678     // 1. 接受从上方传来的文件类型字符串
1679     // 2. 将传入值与启动时准备好的字符串数组逐个比较(probe)
1680     // 3. 直接在函数内调用构造方法并直接返回文件系统对象
1681 
1682     /// src/linux/mount.c `umount` & `umount2`
1683     ///
1684     /// [umount(2) — Linux manual page](https://www.man7.org/linux/man-pages/man2/umount.2.html)
1685     pub fn umount2(target: *const u8, flags: i32) -> Result<(), SystemError> {
1686         let target = user_access::check_and_clone_cstr(target, Some(MAX_PATHLEN))?
1687             .into_string()
1688             .map_err(|_| SystemError::EINVAL)?;
1689         Vcore::do_umount2(
1690             AtFlags::AT_FDCWD.bits(),
1691             &target,
1692             UmountFlag::from_bits(flags).ok_or(SystemError::EINVAL)?,
1693         )?;
1694         return Ok(());
1695     }
1696 
1697     pub fn sys_utimensat(
1698         dirfd: i32,
1699         pathname: *const u8,
1700         times: *const PosixTimeSpec,
1701         flags: u32,
1702     ) -> Result<usize, SystemError> {
1703         let pathname = if pathname.is_null() {
1704             None
1705         } else {
1706             let pathname = check_and_clone_cstr(pathname, Some(MAX_PATHLEN))?
1707                 .into_string()
1708                 .map_err(|_| SystemError::EINVAL)?;
1709             Some(pathname)
1710         };
1711         let flags = UtimensFlags::from_bits(flags).ok_or(SystemError::EINVAL)?;
1712         let times = if times.is_null() {
1713             None
1714         } else {
1715             let times_reader = UserBufferReader::new(times, size_of::<PosixTimeSpec>() * 2, true)?;
1716             let times = times_reader.read_from_user::<PosixTimeSpec>(0)?;
1717             Some([times[0], times[1]])
1718         };
1719         do_utimensat(dirfd, pathname, times, flags)
1720     }
1721 
1722     pub fn sys_utimes(
1723         pathname: *const u8,
1724         times: *const PosixTimeval,
1725     ) -> Result<usize, SystemError> {
1726         let pathname = check_and_clone_cstr(pathname, Some(MAX_PATHLEN))?
1727             .into_string()
1728             .map_err(|_| SystemError::EINVAL)?;
1729         let times = if times.is_null() {
1730             None
1731         } else {
1732             let times_reader = UserBufferReader::new(times, size_of::<PosixTimeval>() * 2, true)?;
1733             let times = times_reader.read_from_user::<PosixTimeval>(0)?;
1734             Some([times[0], times[1]])
1735         };
1736         do_utimes(&pathname, times)
1737     }
1738 }
1739 
1740 #[repr(C)]
1741 #[derive(Debug, Clone, Copy)]
1742 pub struct IoVec {
1743     /// 缓冲区的起始地址
1744     pub iov_base: *mut u8,
1745     /// 缓冲区的长度
1746     pub iov_len: usize,
1747 }
1748 
1749 /// 用于存储多个来自用户空间的IoVec
1750 ///
1751 /// 由于目前内核中的文件系统还不支持分散读写,所以暂时只支持将用户空间的IoVec聚合成一个缓冲区,然后进行操作。
1752 /// TODO:支持分散读写
1753 #[derive(Debug)]
1754 pub struct IoVecs(Vec<&'static mut [u8]>);
1755 
1756 impl IoVecs {
1757     /// 从用户空间的IoVec中构造IoVecs
1758     ///
1759     /// @param iov 用户空间的IoVec
1760     /// @param iovcnt 用户空间的IoVec的数量
1761     /// @param readv 是否为readv系统调用
1762     ///
1763     /// @return 构造成功返回IoVecs,否则返回错误码
1764     pub unsafe fn from_user(
1765         iov: *const IoVec,
1766         iovcnt: usize,
1767         _readv: bool,
1768     ) -> Result<Self, SystemError> {
1769         // 检查iov指针所在空间是否合法
1770         verify_area(
1771             VirtAddr::new(iov as usize),
1772             iovcnt * core::mem::size_of::<IoVec>(),
1773         )
1774         .map_err(|_| SystemError::EFAULT)?;
1775 
1776         // 将用户空间的IoVec转换为引用(注意:这里的引用是静态的,因为用户空间的IoVec不会被释放)
1777         let iovs: &[IoVec] = core::slice::from_raw_parts(iov, iovcnt);
1778 
1779         let mut slices: Vec<&mut [u8]> = Vec::with_capacity(iovs.len());
1780 
1781         for iov in iovs.iter() {
1782             if iov.iov_len == 0 {
1783                 continue;
1784             }
1785 
1786             verify_area(
1787                 VirtAddr::new(iov.iov_base as usize),
1788                 iovcnt * core::mem::size_of::<IoVec>(),
1789             )
1790             .map_err(|_| SystemError::EFAULT)?;
1791 
1792             slices.push(core::slice::from_raw_parts_mut(iov.iov_base, iov.iov_len));
1793         }
1794 
1795         return Ok(Self(slices));
1796     }
1797 
1798     /// @brief 将IoVecs中的数据聚合到一个缓冲区中
1799     ///
1800     /// @return 返回聚合后的缓冲区
1801     pub fn gather(&self) -> Vec<u8> {
1802         let mut buf = Vec::new();
1803         for slice in self.0.iter() {
1804             buf.extend_from_slice(slice);
1805         }
1806         return buf;
1807     }
1808 
1809     /// @brief 将给定的数据分散写入到IoVecs中
1810     pub fn scatter(&mut self, data: &[u8]) {
1811         let mut data: &[u8] = data;
1812         for slice in self.0.iter_mut() {
1813             let len = core::cmp::min(slice.len(), data.len());
1814             if len == 0 {
1815                 continue;
1816             }
1817 
1818             slice[..len].copy_from_slice(&data[..len]);
1819             data = &data[len..];
1820         }
1821     }
1822 
1823     /// @brief 创建与IoVecs等长的缓冲区
1824     ///
1825     /// @param set_len 是否设置返回的Vec的len。
1826     /// 如果为true,则返回的Vec的len为所有IoVec的长度之和;
1827     /// 否则返回的Vec的len为0,capacity为所有IoVec的长度之和.
1828     ///
1829     /// @return 返回创建的缓冲区
1830     pub fn new_buf(&self, set_len: bool) -> Vec<u8> {
1831         let total_len: usize = self.0.iter().map(|slice| slice.len()).sum();
1832         let mut buf: Vec<u8> = Vec::with_capacity(total_len);
1833 
1834         if set_len {
1835             buf.resize(total_len, 0);
1836         }
1837         return buf;
1838     }
1839 }
1840