-
-
Notifications
You must be signed in to change notification settings - Fork 194
Expand file tree
/
Copy pathmod.rs
More file actions
2561 lines (2326 loc) · 87.1 KB
/
Copy pathmod.rs
File metadata and controls
2561 lines (2326 loc) · 87.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
pub mod append_lock;
pub mod fasync;
pub mod fcntl;
pub mod file;
pub mod flock;
pub mod inode_lifecycle;
pub mod iov;
pub mod mount;
pub mod open;
pub mod permission;
pub mod posix_lock;
pub mod stat;
pub mod syscall;
pub mod utils;
pub mod vcore;
pub mod writeback;
use alloc::{string::String, sync::Arc, vec::Vec};
use core::{
any::Any,
fmt::{Debug, Display, Write},
sync::atomic::AtomicUsize,
};
use derive_builder::Builder;
use intertrait::CastFromSync;
use mount::MountFlags;
use system_error::SystemError;
use crate::{
driver::base::{
block::block_device::BlockDevice, char::CharDevice, device::device_number::DeviceNumber,
},
filesystem::{
epoll::EPollItem,
vfs::{file::File, permission::PermissionMask, syscall::RenameFlags},
},
ipc::pipe::LockedPipeInode,
libs::{
casting::DowncastArc,
mutex::{Mutex, MutexGuard},
},
mm::{fault::PageFaultMessage, VirtRegion, VmFaultReason, VmFlags},
net::socket::Socket,
process::ProcessManager,
syscall::{user_access::UserBufferReader, user_buffer::UserBuffer},
time::PosixTimeSpec,
};
pub use self::inode_lifecycle::{EvictionEpoch, InodeRetentionKind, InodeRetentionState};
pub use self::{file::FilePrivateData, mount::MountFS};
use self::{
file::{FileFlags, FileMode, PreopenedFile},
utils::DName,
vcore::generate_inode_id,
};
use super::page_cache::PageCache;
/// vfs容许的最大的路径名称长度
pub const MAX_PATHLEN: usize = 4096;
/// 单个文件名的最大长度
pub const NAME_MAX: usize = 255;
// 定义inode号
int_like!(InodeId, AtomicInodeId, usize, AtomicUsize);
impl Display for InodeId {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}", self.0)
}
}
/// 文件的类型
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileType {
/// 文件
File,
/// 文件夹
Dir,
/// 块设备
BlockDevice,
/// 字符设备
CharDevice,
/// 帧缓冲设备
FramebufferDevice,
/// kvm设备
KvmDevice,
/// 管道文件
Pipe,
/// 符号链接
SymLink,
/// 套接字
Socket,
}
bitflags! {
/// 文件类型和权限
#[repr(C)]
pub struct InodeMode: u32 {
/// 掩码
const S_IFMT = 0o0_170_000;
/// 文件类型
const S_IFSOCK = 0o140000;
const S_IFLNK = 0o120000;
const S_IFREG = 0o100000;
const S_IFBLK = 0o060000;
const S_IFDIR = 0o040000;
const S_IFCHR = 0o020000;
const S_IFIFO = 0o010000;
const S_ISUID = 0o004000;
const S_ISGID = 0o002000;
const S_ISVTX = 0o001000;
/// 文件用户权限
const S_IRWXU = 0o0700;
const S_IRUSR = 0o0400;
const S_IWUSR = 0o0200;
const S_IXUSR = 0o0100;
/// 文件组权限
const S_IRWXG = 0o0070;
const S_IRGRP = 0o0040;
const S_IWGRP = 0o0020;
const S_IXGRP = 0o0010;
/// 文件其他用户权限
const S_IRWXO = 0o0007;
const S_IROTH = 0o0004;
const S_IWOTH = 0o0002;
const S_IXOTH = 0o0001;
/// 0o777
const S_IRWXUGO = Self::S_IRWXU.bits | Self::S_IRWXG.bits | Self::S_IRWXO.bits;
/// 0o7777
const S_IALLUGO = Self::S_ISUID.bits | Self::S_ISGID.bits | Self::S_ISVTX.bits| Self::S_IRWXUGO.bits;
/// 0o444
const S_IRUGO = Self::S_IRUSR.bits | Self::S_IRGRP.bits | Self::S_IROTH.bits;
/// 0o222
const S_IWUGO = Self::S_IWUSR.bits | Self::S_IWGRP.bits | Self::S_IWOTH.bits;
/// 0o111
const S_IXUGO = Self::S_IXUSR.bits | Self::S_IXGRP.bits | Self::S_IXOTH.bits;
}
}
/// Merge only fields selected by `mask` into an existing metadata snapshot.
/// Intent-only bits do not map to stored fields.
pub fn merge_metadata_masked(target: &mut Metadata, requested: &Metadata, mask: SetMetadataMask) {
if mask.contains(SetMetadataMask::MODE) {
target.mode = requested.mode;
}
if mask.contains(SetMetadataMask::UID) {
target.uid = requested.uid;
}
if mask.contains(SetMetadataMask::GID) {
target.gid = requested.gid;
}
if mask.contains(SetMetadataMask::ATIME) {
target.atime = requested.atime;
}
if mask.contains(SetMetadataMask::MTIME) {
target.mtime = requested.mtime;
}
if mask.contains(SetMetadataMask::CTIME) {
target.ctime = requested.ctime;
}
}
/// Apply Linux relatime rules and update only the inode access time.
///
/// Local filesystems call this while holding the lock that protects their
/// metadata, so the decision and the single-field update form one atomic
/// operation with respect to chmod, chown, writes, and other timestamp updates.
pub fn update_atime_locked(metadata: &mut Metadata, now: PosixTimeSpec, relatime: bool) -> bool {
if metadata.flags.contains(InodeFlags::S_NOATIME) {
return false;
}
if !should_update_atime(
metadata.atime,
metadata.mtime,
metadata.ctime,
now,
relatime,
) {
return false;
}
metadata.atime = now;
true
}
/// Evaluate Linux strictatime/relatime policy from authoritative in-memory
/// inode timestamps. Filesystems with a native inode cache can use this helper
/// without constructing a full metadata snapshot or reading the disk inode.
pub fn should_update_atime(
atime: PosixTimeSpec,
mtime: PosixTimeSpec,
ctime: PosixTimeSpec,
now: PosixTimeSpec,
relatime: bool,
) -> bool {
if relatime {
let recent = now.tv_sec.saturating_sub(atime.tv_sec) < 24 * 60 * 60;
let atime_after_mtime = (atime.tv_sec, atime.tv_nsec) > (mtime.tv_sec, mtime.tv_nsec);
let atime_after_ctime = (atime.tv_sec, atime.tv_nsec) > (ctime.tv_sec, ctime.tv_nsec);
if atime_after_mtime && atime_after_ctime && recent {
return false;
}
}
atime != now
}
impl From<FileType> for InodeMode {
fn from(val: FileType) -> Self {
match val {
FileType::File => InodeMode::S_IFREG,
FileType::Dir => InodeMode::S_IFDIR,
FileType::BlockDevice => InodeMode::S_IFBLK,
FileType::CharDevice => InodeMode::S_IFCHR,
FileType::SymLink => InodeMode::S_IFLNK,
FileType::Socket => InodeMode::S_IFSOCK,
FileType::Pipe => InodeMode::S_IFIFO,
FileType::KvmDevice => InodeMode::S_IFCHR,
FileType::FramebufferDevice => InodeMode::S_IFCHR,
}
}
}
impl From<InodeMode> for FileType {
fn from(mode: InodeMode) -> Self {
// 提取文件类型部分
match mode & InodeMode::S_IFMT {
t if t == InodeMode::S_IFREG => FileType::File,
t if t == InodeMode::S_IFDIR => FileType::Dir,
t if t == InodeMode::S_IFBLK => FileType::BlockDevice,
t if t == InodeMode::S_IFCHR => FileType::CharDevice,
t if t == InodeMode::S_IFLNK => FileType::SymLink,
t if t == InodeMode::S_IFSOCK => FileType::Socket,
t if t == InodeMode::S_IFIFO => FileType::Pipe,
// 默认情况,通常应该不会发生,因为 S_IFMT 应该覆盖所有情况
_ => FileType::File,
}
}
}
bitflags! {
pub struct InodeFlags: u32 {
/// 写入时立即同步到磁盘
const S_SYNC = (1 << 0);
/// 不更新访问时间
const S_NOATIME = (1 << 1);
/// 只允许追加写入
const S_APPEND = (1 << 2);
/// 不可修改的文件
const S_IMMUTABLE = (1 << 3);
/// 目录已删除但仍被打开
const S_DEAD = (1 << 4);
/// 不计入磁盘配额
const S_NOQUOTA = (1 << 5);
/// 目录操作同步写入
const S_DIRSYNC = (1 << 6);
/// 不更新 ctime/mtime
const S_NOCMTIME = (1 << 7);
/// 交换文件,禁止截断(swapon已获取块映射)
const S_SWAPFILE = (1 << 8);
/// 文件系统内部使用的私有inode
const S_PRIVATE = (1 << 9);
/// 关联了IMA(完整性度量架构)结构
const S_IMA = (1 << 10);
/// 自动挂载点或引用目录
const S_AUTOMOUNT = (1 << 11);
/// 无suid或xattr安全属性
const S_NOSEC = (1 << 12);
/// 直接访问模式,绕过页缓存
const S_DAX = (1 << 13);
/// 加密文件(使用fs/crypto/)
const S_ENCRYPTED = (1 << 14);
/// 大小写不敏感的文件
const S_CASEFOLD = (1 << 15);
/// 完整性校验文件(使用fs/verity/)
const S_VERITY = (1 << 16);
/// 内核正在使用的文件(如cachefiles)
const S_KERNEL_FILE = (1 << 17);
}
}
bitflags! {
/// 指定 `set_metadata_masked()` 实际要更新的元数据字段。
///
/// 该掩码对应 Linux `iattr::ia_valid` 中 DragonOS 当前可表达的
/// setattr 字段,避免将调用者读取的完整元数据快照误当成完整更新。
pub struct SetMetadataMask: u32 {
const MODE = 1 << 0;
const UID = 1 << 1;
const GID = 1 << 2;
const ATIME = 1 << 3;
const MTIME = 1 << 4;
/// 仅供 VFS/backing 自动维护;用户态 setattr 不能提供任意 ctime。
const CTIME = 1 << 5;
/// 时间设置来自“当前时间”请求,可由当前写权限授权。
const TIMES_BY_WRITE = 1 << 6;
/// 已授权的数据写/size change 引发的 metadata 副作用。
const WRITE_SIDE_EFFECT = 1 << 7;
}
}
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub enum SpecialNodeData {
/// 管道文件
Pipe(Arc<LockedPipeInode>),
/// 字符设备
CharDevice(Arc<dyn CharDevice>),
/// 块设备
BlockDevice(Arc<dyn BlockDevice>),
/// 指向其他 inode 的引用(用于 /proc/self/fd/N 这种魔法链接)
Reference(Arc<dyn IndexNode>),
}
/* these are defined by POSIX and also present in glibc's dirent.h */
/// 完整含义请见 http://www.gnu.org/software/libc/manual/html_node/Directory-Entries.html
#[allow(dead_code)]
pub const DT_UNKNOWN: u16 = 0;
/// 命名管道,或者FIFO
pub const DT_FIFO: u16 = 1;
// 字符设备
pub const DT_CHR: u16 = 2;
// 目录
pub const DT_DIR: u16 = 4;
// 块设备
pub const DT_BLK: u16 = 6;
// 常规文件
pub const DT_REG: u16 = 8;
// 符号链接
pub const DT_LNK: u16 = 10;
// 是一个socket
pub const DT_SOCK: u16 = 12;
// 这个是抄Linux的,还不知道含义
#[allow(dead_code)]
pub const DT_WHT: u16 = 14;
#[allow(dead_code)]
pub const DT_MAX: u16 = 16;
/// Filesystem-supplied directory record used by `getdents(2)`.
///
/// `next_cookie` is an opaque continuation token. Filesystems backed by an
/// external daemon must preserve that token instead of replacing it with a
/// vector index.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DirectoryEntry {
/// Raw name bytes; Linux directory entries do not require UTF-8.
pub name: Vec<u8>,
pub ino: u64,
pub d_type: u8,
pub next_cookie: u64,
}
/// VFS 允许的最大符号链接跟随次数。
///
/// Linux 6.6: MAXSYMLINKS = 40
///
/// 重要约定(兼容既有调用点):
/// - `max_follow_times == 0` 表示 **完全禁用** symlink 跟随(旧行为:不会因为 symlink 而返回 ELOOP)
/// - `max_follow_times == 1` 表示"计数已耗尽",此时若仍需要跟随 symlink,应返回 `ELOOP`
/// - `max_follow_times >= 2` 才允许继续跟随,并在每次跟随时递减
///
/// 因此这里取 41,以"保留 0 的禁用语义"同时实现"最多 40 次跟随"的 Linux 语义。
pub const VFS_MAX_FOLLOW_SYMLINK_TIMES: usize = 41;
impl FileType {
pub fn get_file_type_num(&self) -> u16 {
return match self {
FileType::File => DT_REG,
FileType::Dir => DT_DIR,
FileType::BlockDevice => DT_BLK,
FileType::CharDevice => DT_CHR,
FileType::KvmDevice => DT_CHR,
FileType::Pipe => DT_FIFO,
FileType::SymLink => DT_LNK,
FileType::Socket => DT_SOCK,
FileType::FramebufferDevice => DT_CHR,
};
}
}
bitflags! {
/// @brief inode的状态(由poll方法返回)
pub struct PollStatus: u8 {
const WRITE = 1u8 << 0;
const READ = 1u8 << 1;
const ERROR = 1u8 << 2;
}
}
/// The pollable inode trait
pub trait PollableInode: Any + Sync + Send + Debug + CastFromSync {
/// Return the poll status of the inode
fn poll(&self, private_data: &FilePrivateData) -> Result<usize, SystemError>;
/// Add an epoll item to the inode
fn add_epitem(
&self,
epitem: Arc<EPollItem>,
private_data: &FilePrivateData,
) -> Result<(), SystemError>;
/// Remove epitems associated with the epoll
fn remove_epitem(
&self,
epitm: &Arc<EPollItem>,
private_data: &FilePrivateData,
) -> Result<(), SystemError>;
/// Add a fasync item for SIGIO notification
fn add_fasync(
&self,
_fasync_item: fasync::FAsyncItem,
_private_data: &FilePrivateData,
) -> Result<(), SystemError> {
// Default implementation: not supported
Err(SystemError::ENOSYS)
}
/// Remove a fasync item
fn remove_fasync(
&self,
_file: &alloc::sync::Weak<file::File>,
_private_data: &FilePrivateData,
) -> Result<(), SystemError> {
// Default implementation: not supported
Err(SystemError::ENOSYS)
}
}
pub trait IndexNode: Any + Sync + Send + Debug + CastFromSync {
/// Optional VFS accounting embedded by this canonical inode.
fn retention_state(&self) -> Option<&InodeRetentionState> {
None
}
/// Retain this canonical inode lifetime for a semantic VFS owner.
///
/// This is deliberately distinct from `open()`: `O_PATH`, caches and
/// asynchronous work retain an inode without a filesystem open callback.
/// Admission of a new canonical lifetime must be resolved before this
/// infallible hook is called.
fn retain(&self, kind: InodeRetentionKind) -> Result<(), SystemError> {
if let Some(state) = self.retention_state() {
state.retain(kind)
} else {
Ok(())
}
}
/// Release one semantic inode lifetime owner.
///
/// Implementations must not sleep or perform fallible I/O here. The final
/// release may publish a one-shot eviction request for an explicit worker
/// or shutdown drain.
fn release(&self, kind: InodeRetentionKind) {
if self
.retention_state()
.is_some_and(|state| state.release(kind))
{
self.on_zero_retention();
}
}
/// Non-blocking final-release notification. Implementations may enqueue,
/// but must not execute, fallible eviction work here.
fn on_zero_retention(&self) {}
/// 是否为"流式"文件(不可 random access / 不可 seek)。
///
/// 语义目标:把"pread/pwrite/lseek 应返回 ESPIPE"的判定收敛在 VFS 层,
/// 避免在 syscall 层枚举 FileType 或做硬编码特判。
///
/// 默认规则仅覆盖"天然流式"的基础类型:Pipe/Socket。
/// 其它伪文件(eventfd/epollfd/...)应在各自 inode 中覆写此方法。
fn is_stream(&self) -> bool {
match self.metadata() {
Ok(md) => matches!(md.file_type, FileType::Pipe | FileType::Socket),
// 元数据都拿不到时,保守起见按不可 seek 处理,避免误放行 pread/pwrite。
Err(_) => true,
}
}
/// Return the stable filesystem owner used to identify this inode's
/// atomic-append lock domain.
///
/// Anonymous and protocol-style inodes default to no append lock: their
/// writes do not use regular-file offsets and some do not belong to a
/// mountable filesystem at all. Inodes implementing ordinary persistent
/// file semantics must opt in with their canonical filesystem instance.
fn append_lock_fs(&self) -> Option<Arc<dyn FileSystem>> {
None
}
/// 是否支持 seek(lseek)。
///
/// 默认:普通文件/目录/块设备可 seek;Pipe/Socket/CharDevice 不可 seek;
/// 其它类型保守按可 seek(更接近现有行为:lseek 仅显式拒绝 Pipe/CharDevice)。
fn supports_seek(&self) -> bool {
if self.is_stream() {
return false;
}
match self.metadata() {
Ok(md) => !matches!(
md.file_type,
FileType::Pipe | FileType::Socket | FileType::CharDevice
),
Err(_) => false,
}
}
/// 是否允许 pread(随机读,不推进文件偏移)。
///
/// 默认:对 stream 文件返回 false;对非 stream 默认允许。
/// 伪文件(如 eventfd/epollfd)应覆写 `is_stream()` 或此方法以匹配 Linux 语义。
fn supports_pread(&self) -> bool {
!self.is_stream()
}
/// 是否允许 pwrite(随机写,不推进文件偏移)。
fn supports_pwrite(&self) -> bool {
!self.is_stream()
}
fn truncate_before_open(&self, flags: &FileFlags) -> bool {
flags.contains(FileFlags::O_TRUNC)
}
fn mmap(&self, _start: usize, _len: usize, _offset: usize) -> Result<(), SystemError> {
return Err(SystemError::ENOSYS);
}
fn check_mmap_file(
&self,
_file: &Arc<File>,
_len: usize,
_offset: usize,
_vm_flags: VmFlags,
) -> Result<(), SystemError> {
Ok(())
}
/// Allow a filesystem to add internal VMA flags after VFS permission
/// checks derived the user-visible protection and sharing flags.
fn mmap_vm_flags(&self, _file: &Arc<File>, vm_flags: VmFlags) -> Result<VmFlags, SystemError> {
Ok(vm_flags)
}
fn mmap_effective_file(&self, file: &Arc<File>) -> Result<Arc<File>, SystemError> {
Ok(file.clone())
}
fn mmap_file(
&self,
_file: &Arc<File>,
start: usize,
len: usize,
offset: usize,
_vm_flags: VmFlags,
) -> Result<(), SystemError> {
self.mmap(start, len, offset)
}
fn read_sync(&self, _offset: usize, _buf: &mut [u8]) -> Result<usize, SystemError> {
return Err(SystemError::ENOSYS);
}
fn write_sync(&self, _offset: usize, _buf: &[u8]) -> Result<usize, SystemError> {
return Err(SystemError::ENOSYS);
}
/// @brief 打开文件
///
/// @return 成功:Ok()
/// 失败:Err(错误码)
fn open(
&self,
_data: MutexGuard<FilePrivateData>,
_flags: &FileFlags,
) -> Result<(), SystemError> {
Ok(())
}
/// Adjust per-open file mode bits after `open()` initialized private data.
///
/// This models Linux helpers such as `nonseekable_open()` and
/// `stream_open()` without making VFS syscalls know filesystem-specific
/// protocol flags.
fn adjust_file_mode_after_open(&self, _data: &FilePrivateData, _mode: &mut FileMode) {}
/// Whether the VFS write path should apply Linux `generic_write_sync()`
/// semantics after a successful positive-length write.
///
/// This is intentionally opt-in: many pseudo files are reported as regular
/// files but their Linux write paths do not perform generic write syncing.
fn supports_post_write_sync(&self, _file_type: FileType) -> bool {
false
}
/// @brief 关闭文件
///
/// @return 成功:Ok()
/// 失败:Err(错误码)
fn flush_file(
&self,
_data: MutexGuard<FilePrivateData>,
_lock_owner: u64,
) -> Result<(), SystemError> {
Ok(())
}
/// @brief 释放最后一个 open file description 引用
///
/// @return 成功:Ok()
/// 失败:Err(错误码)
fn close(&self, _data: MutexGuard<FilePrivateData>) -> Result<(), SystemError> {
// 若文件系统没有实现此方法,则返回"不支持"
return Err(SystemError::ENOSYS);
}
/// @brief 在inode的指定偏移量开始,读取指定大小的数据
///
/// @param offset 起始位置在Inode中的偏移量
/// @param len 要读取的字节数
/// @param buf 缓冲区. 请注意,必须满足@buf.len()>=@len
/// @param _data 各文件系统系统所需私有信息
///
/// @return 成功:Ok(读取的字节数)
/// 失败:Err(Posix错误码)
// TODO: data argument should be redesigned to avoid preempt issues
fn read_at(
&self,
offset: usize,
len: usize,
buf: &mut [u8],
_data: MutexGuard<FilePrivateData>,
) -> Result<usize, SystemError>;
/// @brief 在inode的指定偏移量开始,写入指定大小的数据(从buf的第0byte开始写入)
///
/// @param offset 起始位置在Inode中的偏移量
/// @param len 要写入的字节数
/// @param buf 缓冲区. 请注意,必须满足@buf.len()>=@len
/// @param _data 各文件系统系统所需私有信息
///
/// @return 成功:Ok(写入的字节数)
/// 失败:Err(Posix错误码)
fn write_at(
&self,
offset: usize,
len: usize,
buf: &[u8],
_data: MutexGuard<FilePrivateData>,
) -> Result<usize, SystemError>;
/// Write to the inode from a userspace buffer.
///
/// By default returns `None`, causing the VFS `File` layer to follow the
/// traditional path of first copying into a kernel buffer and then calling
/// `write_at()`. Inodes that need to avoid an upfront bulk copy (e.g. socket
/// streams) can override this method and consume the user buffer directly.
fn write_user_at(
&self,
_offset: usize,
_len: usize,
_reader: &UserBufferReader<'_>,
data: MutexGuard<FilePrivateData>,
) -> Result<Option<usize>, SystemError> {
drop(data);
Ok(None)
}
/// 基于打开文件上下文执行 fallocate。
///
/// 默认不模拟预分配;只有真正支持 fallocate 语义的文件系统应覆盖此方法。
fn fallocate_file(
&self,
_mode: i32,
_offset: usize,
_len: usize,
_lock_owner: u64,
data: MutexGuard<FilePrivateData>,
) -> Result<(), SystemError> {
drop(data);
Err(SystemError::EOPNOTSUPP_OR_ENOTSUP)
}
/// # 在inode的指定偏移量开始,读取指定大小的数据,忽略PageCache
///
/// ## 参数
///
/// - `offset`: 起始位置在Inode中的偏移量
/// - `len`: 要读取的字节数
/// - `buf`: 缓冲区
/// - `data`: 各文件系统系统所需私有信息
///
/// ## 返回值
///
/// - `Ok(usize)``: Ok(读取的字节数)
/// - `Err(SystemError)``: Err(Posix错误码)
fn read_direct(
&self,
_offset: usize,
_len: usize,
_buf: &mut [u8],
_data: MutexGuard<FilePrivateData>,
) -> Result<usize, SystemError> {
return Err(SystemError::ENOSYS);
}
/// # 在inode的指定偏移量开始,写入指定大小的数据,忽略PageCache
///
/// ## 参数
///
/// - `offset`: 起始位置在Inode中的偏移量
/// - `len`: 要读取的字节数
/// - `buf`: 缓冲区
/// - `data`: 各文件系统系统所需私有信息
///
/// ## 返回值
///
/// - `Ok(usize)``: Ok(读取的字节数)
/// - `Err(SystemError)``: Err(Posix错误码)
fn write_direct(
&self,
_offset: usize,
_len: usize,
_buf: &[u8],
_data: MutexGuard<FilePrivateData>,
) -> Result<usize, SystemError> {
return Err(SystemError::ENOSYS);
}
/// @brief 获取inode的元数据
///
/// @return 成功:Ok(inode的元数据)
/// 失败:Err(错误码)
fn metadata(&self) -> Result<Metadata, SystemError> {
// 若文件系统没有实现此方法,则返回"不支持"
return Err(SystemError::ENOSYS);
}
/// Incarnation paired with `inode_id` for VFS cache identity.
///
/// Filesystems which can reuse inode numbers while old dentries are still
/// referenced (notably FUSE) must override this with an identity that
/// changes whenever a new in-memory inode replaces the old one. Filesystems
/// without such reuse may keep zero.
fn inode_generation(&self) -> u64 {
0
}
/// @brief 设置inode的元数据
///
/// @return 成功:Ok()
/// 失败:Err(错误码)
fn set_metadata(&self, _metadata: &Metadata) -> Result<(), SystemError> {
// 若文件系统没有实现此方法,则返回"不支持"
return Err(SystemError::ENOSYS);
}
/// 仅更新 `mask` 指定的元数据字段。
///
/// 旧文件系统默认回退到完整 metadata 更新,以保持现有实现兼容;需要在
/// copy-up 等并发边界精确保留未请求字段的堆叠文件系统应覆盖此方法。
fn set_metadata_masked(
&self,
metadata: &Metadata,
mask: SetMetadataMask,
) -> Result<(), SystemError> {
if mask.is_empty() {
return Ok(());
}
self.set_metadata(metadata)
}
/// Atomically evaluate atime policy and update only atime.
///
/// Pseudo filesystems that do not maintain access timestamps may keep the
/// no-op default. Mutable local and protocol filesystems must override this
/// instead of feeding a lockless full metadata snapshot to `set_metadata`.
fn update_atime(&self, _now: PosixTimeSpec, _relatime: bool) -> Result<(), SystemError> {
Ok(())
}
/// @brief 重新设置文件的大小
///
/// 如果文件大小增加,则文件内容不变,但是文件的空洞部分会被填充为0
/// 如果文件大小减小,则文件内容会被截断
///
/// @return 成功:Ok()
/// 失败:Err(错误码)
fn resize(&self, _len: usize) -> Result<(), SystemError> {
// 若文件系统没有实现此方法,则返回"不支持"
return Err(SystemError::ENOSYS);
}
/// 基于当前 files_struct lock owner 重新设置文件大小。
///
/// 默认回退到 inode 级 resize;需要 mandatory-locking 协议语义的文件系统
/// 可覆盖该方法。
fn resize_with_lock_owner(&self, len: usize, _lock_owner: u64) -> Result<(), SystemError> {
self.resize(len)
}
/// 基于打开文件上下文重新设置文件大小。
///
/// 默认回退到 inode 级 resize;需要文件句柄语义的文件系统(如 FUSE)
/// 可覆盖该方法,从 `FilePrivateData` 中取得 per-open 状态。
fn resize_file(
&self,
len: usize,
lock_owner: u64,
data: MutexGuard<FilePrivateData>,
) -> Result<(), SystemError> {
drop(data);
self.resize_with_lock_owner(len, lock_owner)
}
/// Atomically apply a size change and its VFS-computed metadata side
/// effects when the filesystem can represent them in one operation.
///
/// Local filesystems that keep size and inode metadata separately can use
/// the default two-step implementation. Protocol and stacking
/// filesystems should override this method to preserve their transaction
/// and request-context semantics.
fn resize_with_metadata(
&self,
len: usize,
lock_owner: u64,
metadata: &Metadata,
mask: SetMetadataMask,
) -> Result<(), SystemError> {
self.resize_with_lock_owner(len, lock_owner)?;
let mut current = self.metadata()?;
merge_metadata_masked(&mut current, metadata, mask);
self.set_metadata_masked(¤t, mask)
}
/// File-context variant of `resize_with_metadata()`.
fn resize_file_with_metadata(
&self,
len: usize,
lock_owner: u64,
data: MutexGuard<FilePrivateData>,
metadata: &Metadata,
mask: SetMetadataMask,
) -> Result<(), SystemError> {
self.resize_file(len, lock_owner, data)?;
let mut current = self.metadata()?;
merge_metadata_masked(&mut current, metadata, mask);
self.set_metadata_masked(¤t, mask)
}
/// @brief 在当前目录下创建一个新的inode
///
/// @param name 目录项的名字
/// @param file_type 文件类型
/// @param mode 权限
///
/// @return 创建成功:返回Ok(新的inode的Arc指针)
/// @return 创建失败:返回Err(错误码)
fn create(
&self,
name: &str,
file_type: FileType,
mode: InodeMode,
) -> Result<Arc<dyn IndexNode>, SystemError> {
// 若文件系统没有实现此方法,则默认调用其create_with_data方法。如果仍未实现,则会得到一个Err(-ENOSYS)的返回值
return self.create_with_data(name, file_type, mode, 0);
}
/// Atomically create and open a regular file when supported by the
/// filesystem. The returned guard owns the open handle until VFS builds
/// the corresponding open file description.
fn create_and_open(
&self,
_name: &str,
_mode: InodeMode,
_flags: &FileFlags,
) -> Result<PreopenedFile, SystemError> {
Err(SystemError::ENOSYS)
}
/// @brief 在当前目录下创建一个新的inode,并传入一个简单的data字段,方便进行初始化。
///
/// @param name 目录项的名字
/// @param file_type 文件类型
/// @param mode 权限
/// @param data 用于初始化该inode的数据。(为0则表示忽略此字段)对于不同的文件系统来说,代表的含义可能不同。
///
/// @return 创建成功:返回Ok(新的inode的Arc指针)
/// @return 创建失败:返回Err(错误码)
fn create_with_data(
&self,
_name: &str,
_file_type: FileType,
_mode: InodeMode,
_data: usize,
) -> Result<Arc<dyn IndexNode>, SystemError> {
// 若文件系统没有实现此方法,则返回"不支持"
return Err(SystemError::ENOSYS);
}
/// @brief 在当前目录下创建符号链接(name -> target)
fn symlink(&self, name: &str, target: &str) -> Result<Arc<dyn IndexNode>, SystemError> {
let inode = self.create_with_data(name, FileType::SymLink, InodeMode::S_IRWXUGO, 0)?;
let bytes = target.as_bytes();
let len = bytes.len();
inode.write_at(0, len, bytes, Mutex::new(FilePrivateData::Unused).lock())?;
Ok(inode)
}
/// @brief 在当前目录下,创建一个名为Name的硬链接,指向另一个IndexNode
///
/// @param name 硬链接的名称
/// @param other 要被指向的IndexNode的Arc指针
///
/// @return 成功:Ok()
/// 失败:Err(错误码)
fn link(&self, _name: &str, _other: &Arc<dyn IndexNode>) -> Result<(), SystemError> {
// 若文件系统没有实现此方法,则返回"不支持"
return Err(SystemError::ENOSYS);
}
/// @brief 在当前目录下,删除一个名为Name的硬链接
///
/// @param name 硬链接的名称
///
/// @return 成功:Ok()
/// 失败:Err(错误码)
fn unlink(&self, _name: &str) -> Result<(), SystemError> {
// 若文件系统没有实现此方法,则返回"不支持"
return Err(SystemError::ENOSYS);
}
/// Execute a namespace mutation as part of one layered VFS transaction.
/// Filesystems that delegate to mounted backing paths must propagate the
/// context instead of recursively acquiring the global dentry lock.
fn unlink_with_context(
&self,
name: &str,
context: &mount::DentryMutationContext<'_>,
) -> Result<(), SystemError> {
context.ensure_locked();
self.unlink(name)
}
/// @brief 删除文件夹
///
/// @param name 文件夹名称
///
/// @return 成功 Ok(())
/// @return 失败 Err(错误码)
fn rmdir(&self, _name: &str) -> Result<(), SystemError> {
return Err(SystemError::ENOSYS);
}
fn rmdir_with_context(
&self,
name: &str,
context: &mount::DentryMutationContext<'_>,
) -> Result<(), SystemError> {
context.ensure_locked();
self.rmdir(name)
}
/// 将指定的`old_name`子目录项移动到target目录下, 并予以`new_name`。
///
/// # Behavior
/// 如果old_name所指向的inode与target的相同,那么则直接**执行重命名的操作**。
fn move_to(
&self,
_old_name: &str,
_target: &Arc<dyn IndexNode>,
_new_name: &str,
_flag: RenameFlags,
) -> Result<(), SystemError> {
// 若文件系统没有实现此方法,则返回"不支持"
return Err(SystemError::ENOSYS);
}
fn move_to_with_context(
&self,
old_name: &str,
target: &Arc<dyn IndexNode>,
new_name: &str,
flag: RenameFlags,
context: &mount::DentryMutationContext<'_>,
) -> Result<(), SystemError> {
context.ensure_locked();
self.move_to(old_name, target, new_name, flag)
}
/// @brief 专用于 remote 权限模型下 access(2) 的检查
fn check_access(&self, _mask: PermissionMask) -> Result<(), SystemError> {
Err(SystemError::ENOSYS)
}
/// @brief 寻找一个名为Name的inode
///