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