-
-
Notifications
You must be signed in to change notification settings - Fork 194
Expand file tree
/
Copy pathinode.rs
More file actions
2259 lines (2076 loc) · 82.2 KB
/
Copy pathinode.rs
File metadata and controls
2259 lines (2076 loc) · 82.2 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
use crate::{
arch::{CurrentTimeArch, MMArch},
driver::base::device::device_number::{DeviceNumber, Major},
filesystem::{
page_cache::{AsyncPageCacheBackend, PageCache},
vfs::{
self, syscall::RenameFlags, utils::DName, vcore::generate_inode_id, FilePrivateData,
IndexNode, InodeFlags, InodeId, InodeMode, InodeRetentionState, SetMetadataMask,
SpecialNodeData, XattrFlags,
},
},
ipc::pipe::LockedPipeInode,
libs::{
casting::DowncastArc,
mutex::{Mutex, MutexGuard},
rwsem::{RwSem, RwSemReadGuard},
spinlock::SpinLock,
wait_queue::WaitQueue,
},
mm::MemoryManagementArch,
process::{ProcessManager, RawPid},
sched::sched_yield,
time::sleep::nanosleep,
time::{PosixTimeSpec, TimeArch},
};
use alloc::{
collections::BTreeMap,
format,
string::String,
sync::{Arc, Weak},
vec::Vec,
};
use core::fmt::Debug;
use kdepends::another_ext4::{self, FileType};
use num::ToPrimitive;
use system_error::SystemError;
use super::filesystem::Ext4FileSystem;
const WHITEOUT_DEV: DeviceNumber = DeviceNumber::new(Major::UNNAMED_MAJOR, 0);
bitflags! {
/// Inode 脏状态标志位,对应 Linux `inode->i_state` 中的 `I_DIRTY_*` 位。
pub(super) struct InodeDirtyState: u32 {
/// 文件大小变更未刷盘,对应 I_DIRTY_SYNC (1 << 0)
const SIZE_DIRTY = 1 << 0;
/// mtime 变更未刷盘,对应 I_DIRTY_DATASYNC (1 << 1)
const MTIME_DIRTY = 1 << 1;
/// atime 变更未刷盘。读路径仅更新缓存,由 inode writeback 持久化。
const ATIME_DIRTY = 1 << 2;
/// 该 inode 已在文件系统 dirty_inodes 队列中。
const QUEUED = 1 << 3;
/// 该 inode 正在执行元数据写回。
const WRITEBACK = 1 << 4;
/// 需要持久化的缓存元数据集合。
const PERSISTENT_DIRTY = Self::SIZE_DIRTY.bits()
| Self::MTIME_DIRTY.bits()
| Self::ATIME_DIRTY.bits();
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum Ext4InodeLifecycleState {
Live,
Freeing,
Retired,
Poisoned(SystemError),
}
#[derive(Debug)]
struct Ext4InodeLifecycleInner {
state: Ext4InodeLifecycleState,
active_operations: usize,
operation_owners: BTreeMap<RawPid, usize>,
}
#[derive(Debug)]
pub(super) struct Ext4InodeLifecycle {
inner: Mutex<Ext4InodeLifecycleInner>,
link_mutation: Mutex<()>,
wait_queue: WaitQueue,
}
impl Ext4InodeLifecycle {
pub(super) fn new() -> Arc<Self> {
Arc::new(Self {
inner: Mutex::new(Ext4InodeLifecycleInner {
state: Ext4InodeLifecycleState::Live,
active_operations: 0,
operation_owners: BTreeMap::new(),
}),
link_mutation: Mutex::new(()),
wait_queue: WaitQueue::default(),
})
}
pub(super) fn state(&self) -> Ext4InodeLifecycleState {
self.inner.lock().state.clone()
}
/// Serializes link-count mutations for all aliases of this canonical inode.
pub(super) fn lock_link_mutation(&self) -> MutexGuard<'_, ()> {
self.link_mutation.lock()
}
pub(super) fn begin_operation(self: &Arc<Self>) -> Result<Ext4InodeOperation, SystemError> {
let owner = ProcessManager::current_pcb().raw_pid();
let mut inner = self.inner.lock();
match inner.state.clone() {
Ext4InodeLifecycleState::Live => {}
Ext4InodeLifecycleState::Freeing if inner.operation_owners.contains_key(&owner) => {}
Ext4InodeLifecycleState::Freeing => return Err(SystemError::EBUSY),
Ext4InodeLifecycleState::Retired => return Err(SystemError::ESTALE),
Ext4InodeLifecycleState::Poisoned(error) => return Err(error),
}
let active_operations = inner
.active_operations
.checked_add(1)
.ok_or(SystemError::EOVERFLOW)?;
let owner_depth = inner
.operation_owners
.get(&owner)
.copied()
.unwrap_or(0)
.checked_add(1)
.ok_or(SystemError::EOVERFLOW)?;
inner.active_operations = active_operations;
inner.operation_owners.insert(owner, owner_depth);
Ok(Ext4InodeOperation {
lifecycle: self.clone(),
owner,
})
}
pub(super) fn begin_freeing(&self) -> Result<(), SystemError> {
let mut inner = self.inner.lock();
match inner.state.clone() {
Ext4InodeLifecycleState::Live => {
inner.state = Ext4InodeLifecycleState::Freeing;
Ok(())
}
Ext4InodeLifecycleState::Freeing => Err(SystemError::EBUSY),
Ext4InodeLifecycleState::Retired => Err(SystemError::ESTALE),
Ext4InodeLifecycleState::Poisoned(error) => Err(error),
}
}
pub(super) fn wait_for_quiescent(&self) {
self.wait_queue.wait_until(|| {
let inner = self.inner.lock();
(inner.active_operations == 0).then_some(())
});
}
pub(super) fn wait_while_freeing(&self) -> Ext4InodeLifecycleState {
self.wait_queue.wait_until(|| {
let state = self.inner.lock().state.clone();
(state != Ext4InodeLifecycleState::Freeing).then_some(state)
})
}
pub(super) fn set_state(&self, state: Ext4InodeLifecycleState) {
self.inner.lock().state = state;
self.wait_queue.wake_all();
}
}
#[must_use]
pub(super) struct Ext4InodeOperation {
lifecycle: Arc<Ext4InodeLifecycle>,
owner: RawPid,
}
/// Keeps the ext4 mmap write-preparation critical section alive until the
/// generic page-cache layer has made the page writable and dirty.
pub(super) struct Ext4MmapWriteGuard<'a> {
_operation: Ext4InodeOperation,
_size_guard: RwSemReadGuard<'a, ()>,
}
impl Drop for Ext4InodeOperation {
fn drop(&mut self) {
let should_wake = {
let mut inner = self.lifecycle.inner.lock();
debug_assert!(inner.active_operations > 0);
inner.active_operations = inner.active_operations.saturating_sub(1);
let remove_owner =
if let Some(owner_depth) = inner.operation_owners.get_mut(&self.owner) {
debug_assert!(*owner_depth > 0);
*owner_depth = owner_depth.saturating_sub(1);
*owner_depth == 0
} else {
debug_assert!(false, "missing ext4 lifecycle operation owner");
false
};
if remove_owner {
inner.operation_owners.remove(&self.owner);
}
inner.active_operations == 0
};
if should_wake {
self.lifecycle.wait_queue.wake_all();
}
}
}
type PrivateData<'a> = crate::libs::mutex::MutexGuard<'a, vfs::FilePrivateData>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct Ext4InodeTimes {
pub(super) atime: u32,
pub(super) mtime: u32,
pub(super) ctime: u32,
}
impl From<&another_ext4::FileAttr> for Ext4InodeTimes {
fn from(attr: &another_ext4::FileAttr) -> Self {
Self {
atime: attr.atime,
mtime: attr.mtime,
ctime: attr.ctime,
}
}
}
pub struct Ext4Inode {
// 对应another_ext4里面的inode号,用于在ext4文件系统中查找相应的inode
pub(super) inner_inode_num: u32,
pub(super) fs_ptr: Weak<super::filesystem::Ext4FileSystem>,
pub(super) page_cache: Option<Arc<PageCache>>,
pub(super) children: BTreeMap<DName, Arc<LockedExt4Inode>>,
pub(super) dname: DName,
// 对应vfs的inode id,用于标识系统中唯一的inode
pub(super) vfs_inode_id: InodeId,
// 指向父级IndexNode的Weak指针
pub(super) parent: Weak<LockedExt4Inode>,
// 指向自身的Weak指针,用于获取Arc<Self>
pub(super) self_ref: Weak<LockedExt4Inode>,
// 特殊节点数据(用于 FIFO 的 pipe inode)
pub(super) special_node: Option<SpecialNodeData>,
/// 缓存的文件大小,避免频繁调用 getattr/setattr。
/// None 表示未初始化(第一次写时从磁盘读取并缓存)。
pub(super) cached_file_size: Option<u64>,
/// Linux inode-style authoritative in-memory timestamps. They are loaded
/// before the canonical inode is published; atime/mtime writeback is lazy.
pub(super) cached_times: Ext4InodeTimes,
/// Monotonic sequence for atime cache mutations. Disk commits compare the
/// sequence, not only the value, so A->B->A updates cannot be lost.
pub(super) cached_atime_version: u64,
/// Monotonic sequence for mtime cache mutations; mmap write preparation
/// updates mtime after releasing io_lock, so setters/writeback use this
/// sequence to avoid same-second ABA and lost dirty state.
pub(super) cached_mtime_version: u64,
/// 脏状态标志位,对应 Linux `inode->i_state & I_DIRTY_*`。
pub(super) dirty_state: InodeDirtyState,
}
#[derive(Debug)]
pub struct LockedExt4Inode {
pub(super) inner: Mutex<Ext4Inode>,
pub(super) io_lock: Mutex<()>,
pub(super) size_lock: RwSem<()>,
pub(super) namespace_lock: Mutex<()>,
pub(super) lifecycle: Arc<Ext4InodeLifecycle>,
pub(super) retention: InodeRetentionState,
pub(super) pending_reclaim: SpinLock<Option<another_ext4::InodeReclaimHandle>>,
pub(super) eviction_scheduled: SpinLock<bool>,
pub(super) retention_callback_self: Weak<LockedExt4Inode>,
pub(super) eviction_filesystem: SpinLock<Weak<Ext4FileSystem>>,
}
impl IndexNode for LockedExt4Inode {
fn append_lock_fs(&self) -> Option<Arc<dyn vfs::FileSystem>> {
Some(self.fs())
}
fn supports_post_write_sync(&self, file_type: vfs::FileType) -> bool {
file_type == vfs::FileType::File
}
fn retention_state(&self) -> Option<&InodeRetentionState> {
Some(&self.retention)
}
fn on_zero_retention(&self) {
let inode = self.retention_callback_self.upgrade();
if let Some(inode) = inode {
let _ = inode.try_schedule_deferred_eviction();
}
}
fn mmap(&self, _start: usize, _len: usize, _offset: usize) -> Result<(), SystemError> {
Ok(())
}
fn open(
&self,
_data: crate::libs::mutex::MutexGuard<vfs::FilePrivateData>,
_mode: &vfs::file::FileFlags,
) -> Result<(), SystemError> {
Ok(())
}
fn create(
&self,
name: &str,
file_type: vfs::FileType,
mode: vfs::InodeMode,
) -> Result<Arc<dyn IndexNode>, SystemError> {
let _operation = self.begin_operation()?;
let _io = self.io_lock.lock();
let _namespace = self.namespace_lock.lock();
let parent_metadata = self.metadata()?;
let init = vfs::permission::child_inode_init(&parent_metadata, file_type, mode);
let mut guard = self.inner.lock();
// another_ext4的高4位是文件类型,低12位是权限
let file_mode = InodeMode::from(file_type).union(init.mode);
let file_mode = another_ext4::InodeMode::from_bits_truncate(file_mode.bits() as u16);
let fs = guard.concret_fs();
let _reuse = fs.begin_allocation()?;
let ext4 = &fs.fs;
// Resolve the parent lifetime before publishing the on-disk name so
// no fallible parent lookup remains after the namespace transaction.
let self_arc = guard.self_ref.upgrade().ok_or(SystemError::ENOENT)?;
let attr = if file_type == vfs::FileType::Dir {
Self::retry_metadata_contention(|| {
ext4.mkdir_with_owner_and_attr(
guard.inner_inode_num,
name,
file_mode,
another_ext4::InodeOwner {
uid: init.uid as u32,
gid: init.gid as u32,
},
)
})?
} else {
Self::retry_metadata_contention(|| {
ext4.create_with_owner_and_attr(
guard.inner_inode_num,
name,
file_mode,
another_ext4::InodeOwner {
uid: init.uid as u32,
gid: init.gid as u32,
},
)
})?
};
let dname = DName::from(name);
let inode = fs.publish_allocated_inode(
attr,
dname.clone(),
Some(Arc::downgrade(&self_arc)),
&_reuse,
)?;
// 更新 children 缓存
guard.children.insert(dname, inode.clone());
drop(guard);
Ok(inode as Arc<dyn IndexNode>)
}
fn create_with_data(
&self,
name: &str,
file_type: vfs::FileType,
mode: InodeMode,
data: usize,
) -> Result<Arc<dyn IndexNode>, SystemError> {
if data == 0 {
return self.create(name, file_type, mode);
}
Err(SystemError::ENOSYS)
}
fn read_at(
&self,
offset: usize,
len: usize,
buf: &mut [u8],
data: PrivateData,
) -> Result<usize, SystemError> {
let _operation = self.begin_operation()?;
let len = core::cmp::min(len, buf.len());
let buf = &mut buf[0..len];
// 关键修复:不要在持有 Ext4 inode 自旋锁期间调用 PageCache::{read,write}。
// PageCache 读写路径内部会调用 inode.metadata() 获取文件大小:
// - prepare_read(): inode.metadata()
// 若此处持有 inode 锁,则会在 metadata() 再次尝试获取同一把锁而自旋死锁。
let page_cache = {
let guard = self.inner.lock();
guard.page_cache.clone()
};
if let Some(page_cache) = page_cache {
// 性能优化:不再每次 read 都同步更新 atime 到磁盘。
// 这等同于 Linux 的 noatime 挂载选项,避免每次读取引发
// read_inode + write_inode 的额外磁盘 I/O。
page_cache.read(offset, buf)
} else {
self.read_direct(offset, len, buf, data)
}
}
fn read_sync(&self, offset: usize, buf: &mut [u8]) -> Result<usize, SystemError> {
let _operation = self.begin_operation()?;
let (fs, inode_num) = {
let guard = self.inner.lock();
(guard.concret_fs(), guard.inner_inode_num)
};
match fs.fs.getattr(inode_num)?.ftype {
FileType::Directory => Err(SystemError::EISDIR),
FileType::Unknown => Err(SystemError::EROFS),
FileType::RegularFile => fs.fs.read(inode_num, offset, buf).map_err(From::from),
FileType::SymLink => fs.fs.readlink(inode_num, offset, buf).map_err(From::from),
_ => Err(SystemError::EINVAL),
}
}
fn read_direct(
&self,
offset: usize,
len: usize,
buf: &mut [u8],
_data: crate::libs::mutex::MutexGuard<vfs::FilePrivateData>,
) -> Result<usize, SystemError> {
let len = core::cmp::min(len, buf.len());
self.read_sync(offset, &mut buf[0..len])
}
fn write_at(
&self,
offset: usize,
len: usize,
buf: &[u8],
data: PrivateData,
) -> Result<usize, SystemError> {
let _operation = self.begin_operation()?;
let len = core::cmp::min(len, buf.len());
if len == 0 {
return Ok(0);
}
let buf = &buf[0..len];
let (fs, inode_num, page_cache) = {
let guard = self.inner.lock();
(
guard.concret_fs(),
guard.inner_inode_num,
guard.page_cache.clone(),
)
};
if let Some(page_cache) = page_cache {
let _invalidate = page_cache.invalidate_write();
let _size_guard = self.size_lock.read();
let _io_guard = self.io_lock.lock();
// 使用缓存的文件大小,避免 getattr 磁盘 I/O
let old_file_size = {
let cached_size = self.inner.lock().cached_file_size;
match cached_size {
Some(size) => size,
None => {
let size = fs.fs.getattr(inode_num)?.size;
self.inner.lock().cached_file_size = Some(size);
size
}
}
};
let new_end = offset.checked_add(len).ok_or(SystemError::EFBIG)?;
let alloc_start = (offset >> MMArch::PAGE_SHIFT) << MMArch::PAGE_SHIFT;
let alloc_end = new_end
.checked_add(MMArch::PAGE_SIZE - 1)
.ok_or(SystemError::EFBIG)?
& !(MMArch::PAGE_SIZE - 1);
let alloc_len = alloc_end
.checked_sub(alloc_start)
.ok_or(SystemError::EFBIG)?;
let time = PosixTimeSpec::now().tv_sec.to_u32().unwrap_or_else(|| {
log::warn!("Failed to get current time, using 0");
0
});
let stats_start = fs
.fs
.prepare_stats_enabled()
.then(CurrentTimeArch::get_cycles);
let prepare_result = Self::retry_metadata_contention(|| {
fs.fs.prepare_buffered_write(
inode_num,
alloc_start,
alloc_len,
new_end as u64,
Some(time),
)
});
if let Some(start) = stats_start {
fs.fs.record_prepare_elapsed_cycles(
CurrentTimeArch::get_cycles().wrapping_sub(start),
);
}
prepare_result?;
// 写入范围的磁盘块已就绪,现在安全写入 page cache。
let write_len = PageCache::write(&page_cache, offset, buf)?;
if write_len > 0 {
let written_end = offset.checked_add(write_len).ok_or(SystemError::EFBIG)?;
let current_file_size = core::cmp::max(old_file_size, written_end as u64);
let self_arc = {
let mut guard = self.inner.lock();
guard.cached_file_size = Some(current_file_size);
guard.cached_times.mtime = time;
guard.cached_mtime_version = guard.cached_mtime_version.wrapping_add(1);
guard.self_ref.upgrade().ok_or(SystemError::ENOENT)?
};
Ext4FileSystem::mark_inode_dirty(
&self_arc,
InodeDirtyState::SIZE_DIRTY | InodeDirtyState::MTIME_DIRTY,
)?;
}
Ok(write_len)
} else {
let _size_guard = self.size_lock.read();
self.write_direct(offset, len, buf, data)
}
}
fn write_sync(&self, offset: usize, buf: &[u8]) -> Result<usize, SystemError> {
let _operation = self.begin_operation()?;
let _io_guard = self.io_lock.lock();
let (fs, inode_num) = {
let guard = self.inner.lock();
(guard.concret_fs(), guard.inner_inode_num)
};
match fs.fs.getattr(inode_num)?.ftype {
FileType::Directory => Err(SystemError::EISDIR),
FileType::Unknown => Err(SystemError::EROFS),
// Use write_data_only: blocks are pre-allocated by prepare_buffered_write() in write_at().
// Using Ext4::write() here would cause it to call write_inode_with_csum()
// which overwrites the inode's block_count/extent tree with a stale
// snapshot, causing setattr to re-allocate blocks endlessly until
// the extent tree overflows (entries > max_entries → EIO).
FileType::RegularFile => {
Self::retry_metadata_contention(|| fs.fs.write_data_only(inode_num, offset, buf))
}
_ => Err(SystemError::EINVAL),
}
}
fn write_direct(
&self,
offset: usize,
len: usize,
buf: &[u8],
_data: MutexGuard<FilePrivateData>,
) -> Result<usize, SystemError> {
let len = core::cmp::min(len, buf.len());
self.write_sync(offset, &buf[0..len])
}
fn fs(&self) -> Arc<dyn vfs::FileSystem> {
self.inner.lock().concret_fs()
}
fn as_any_ref(&self) -> &dyn core::any::Any {
self
}
fn find(&self, name: &str) -> Result<Arc<dyn IndexNode>, SystemError> {
let _operation = self.begin_operation()?;
let _namespace = self.namespace_lock.lock();
let mut guard = self.inner.lock();
let dname = DName::from(name);
if let Some(child) = guard.children.get(&dname) {
let child = child.clone();
let fs = guard.concret_fs();
if fs.validate_inode(&child).is_ok() {
return Ok(child as Arc<dyn IndexNode>);
}
guard.children.remove(&dname);
}
let fs = guard.concret_fs();
let next_inode = fs.fs.lookup(guard.inner_inode_num, name)?;
// 通过self_ref获取Arc<Self>,然后转换为Arc<dyn IndexNode>
let self_arc = guard.self_ref.upgrade().ok_or(SystemError::ENOENT)?;
let inode =
fs.get_or_create_inode(next_inode, dname.clone(), Some(Arc::downgrade(&self_arc)))?;
guard.children.insert(dname, inode.clone());
Ok(inode)
}
fn parent(&self) -> Result<Arc<dyn IndexNode>, SystemError> {
// 只有目录才有父目录的概念
// 先检查当前inode是否为目录
let guard = self.inner.lock();
// 如果存储了父级指针,直接返回
if let Some(parent) = guard.parent.upgrade() {
return Ok(parent);
}
Err(SystemError::ENOENT)
}
fn list(&self) -> Result<Vec<String>, SystemError> {
let _operation = self.begin_operation()?;
let guard = self.inner.lock();
let dentry = guard.concret_fs().fs.listdir(guard.inner_inode_num)?;
let mut list = Vec::new();
for entry in dentry {
list.push(entry.name());
}
Ok(list)
}
fn link(&self, name: &str, other: &Arc<dyn IndexNode>) -> Result<(), SystemError> {
let _operation = self.begin_operation()?;
let _namespace = self.namespace_lock.lock();
let mut guard = self.inner.lock();
let fs = guard.concret_fs();
let ext4 = &fs.fs;
let inode_num = guard.inner_inode_num;
let other_arc = other
.clone()
.downcast_arc::<LockedExt4Inode>()
.ok_or(SystemError::EINVAL)?;
let other_fs = other_arc.inner.lock().concret_fs();
if !Arc::ptr_eq(&fs, &other_fs) {
return Err(SystemError::EXDEV);
}
let other_lifecycle = other_arc.lifecycle().clone();
let _link_mutation = other_lifecycle.lock_link_mutation();
let _other_operation = other_arc.begin_operation()?;
let other_inode_num = other_arc.inner.lock().inner_inode_num;
let my_attr = ext4.getattr(inode_num)?;
let other_attr = ext4.getattr(other_inode_num)?;
if my_attr.ftype != another_ext4::FileType::Directory {
return Err(SystemError::ENOTDIR);
}
if other_attr.ftype == another_ext4::FileType::Directory {
return Err(SystemError::EISDIR);
}
if ext4.lookup(inode_num, name).is_ok() {
return Err(SystemError::EEXIST);
}
Self::retry_metadata_contention(|| ext4.link(other_inode_num, inode_num, name))?;
if other_attr.links == 0 {
// The orphan-del transaction made this inode live again. Discard
// the one-shot capability published by its previous final unlink
// before the fd retention that enabled AT_EMPTY_PATH can vanish.
other_arc.cancel_deferred_reclaim_after_relink();
}
let dname = DName::from(name);
guard.children.insert(dname, other_arc);
Ok(())
}
fn unlink(&self, name: &str) -> Result<(), SystemError> {
let _operation = self.begin_operation()?;
let _namespace = self.namespace_lock.lock();
let mut guard = self.inner.lock();
let fs = guard.concret_fs();
let ext4 = &fs.fs;
let inode_num = guard.inner_inode_num;
let attr = ext4.getattr(inode_num)?;
if attr.ftype != another_ext4::FileType::Directory {
return Err(SystemError::ENOTDIR);
}
let target_num = ext4.lookup(inode_num, name)?;
if ext4.getattr(target_num)?.ftype == FileType::Directory {
return Err(SystemError::EISDIR);
}
let self_arc = guard.self_ref.upgrade().ok_or(SystemError::ENOENT)?;
let target = fs.get_or_create_inode(
target_num,
DName::from(name),
Some(Arc::downgrade(&self_arc)),
)?;
let target_lifecycle = target.lifecycle().clone();
let _link_mutation = target_lifecycle.lock_link_mutation();
let _target_operation = target.begin_operation()?;
match ext4.lookup(inode_num, name) {
Ok(current) if current == target_num => {}
Ok(_) => return Err(SystemError::EAGAIN_OR_EWOULDBLOCK),
Err(error) => return Err(error.into()),
}
let reclaim = Self::retry_metadata_contention(|| ext4.unlink(inode_num, name))?;
target.handoff_namespace_reclaim(reclaim)?;
// 清理 children 缓存
let _ = guard.children.remove(&DName::from(name));
Ok(())
}
fn metadata(&self) -> Result<vfs::Metadata, SystemError> {
let _operation = self.begin_operation()?;
let (fs, inode_num, vfs_inode_id, cached_size) = {
let guard = self.inner.lock();
(
guard.concret_fs(),
guard.inner_inode_num,
guard.vfs_inode_id,
guard.cached_file_size,
)
};
let attr = fs.fs.getattr(inode_num)?;
// Disk attributes provide non-cached fields. Read the authoritative
// in-memory values afterwards so a concurrent atime update cannot be
// hidden by a stale pre-getattr snapshot.
let cached_times = self.inner.lock().cached_times;
let size = cached_size.unwrap_or(attr.size);
// dev_id: filesystem device number (st_dev)
let dev_id = fs.raw_dev.data() as usize;
// raw_dev: device node's rdev (st_rdev), only for char/block devices
let raw_dev = if matches!(attr.ftype, FileType::CharacterDev | FileType::BlockDev) {
let (major, minor) = attr.rdev;
DeviceNumber::new(
crate::driver::base::device::device_number::Major::new(major),
minor,
)
} else {
DeviceNumber::default()
};
Ok(vfs::Metadata {
inode_id: vfs_inode_id,
size: size as i64,
blk_size: another_ext4::BLOCK_SIZE,
blocks: attr.blocks as usize,
atime: PosixTimeSpec::new(cached_times.atime.into(), 0),
btime: PosixTimeSpec::new(attr.atime.into(), 0),
mtime: PosixTimeSpec::new(cached_times.mtime.into(), 0),
ctime: PosixTimeSpec::new(cached_times.ctime.into(), 0),
file_type: Self::file_type(attr.ftype),
mode: InodeMode::from_bits_truncate(attr.perm.bits() as u32),
flags: InodeFlags::empty(),
nlinks: attr.links as usize,
uid: attr.uid as usize,
gid: attr.gid as usize,
dev_id,
raw_dev,
})
}
fn close(&self, _: PrivateData) -> Result<(), SystemError> {
Ok(())
}
fn sync(&self) -> Result<(), SystemError> {
let _operation = self.begin_operation()?;
if let Some(page_cache) = self.page_cache() {
page_cache.manager().sync()?;
}
self.flush_metadata(false)?;
let fs = self.inner.lock().concret_fs();
fs.finish_sync_durability_boundary()
}
fn datasync(&self) -> Result<(), SystemError> {
let _operation = self.begin_operation()?;
if let Some(page_cache) = self.page_cache() {
page_cache.manager().sync()?;
}
self.flush_metadata(true)?;
let fs = self.inner.lock().concret_fs();
fs.finish_sync_durability_boundary()
}
fn sync_file(&self, datasync: bool, _data: PrivateData) -> Result<(), SystemError> {
if datasync {
self.datasync()
} else {
self.sync()
}
}
fn sync_file_range(
&self,
start: usize,
end: usize,
datasync: bool,
_data: PrivateData,
) -> Result<(), SystemError> {
let _operation = self.begin_operation()?;
if let Some(page_cache) = self.page_cache() {
let start_index = start >> MMArch::PAGE_SHIFT;
let end_index = end >> MMArch::PAGE_SHIFT;
page_cache
.manager()
.writeback_range(start_index, end_index)?;
}
self.flush_metadata(datasync)?;
let fs = self.inner.lock().concret_fs();
fs.finish_sync_durability_boundary()
}
fn write_inode(&self, _wbc: &vfs::WritebackControl) -> Result<(), SystemError> {
self.flush_metadata(false)
}
fn page_cache(&self) -> Option<Arc<PageCache>> {
self.inner.lock().page_cache.clone()
}
fn set_metadata(&self, metadata: &vfs::Metadata) -> Result<(), SystemError> {
let _operation = self.begin_operation()?;
let _io_guard = self.io_lock.lock();
let mode = metadata.mode.union(InodeMode::from(metadata.file_type));
let to_ext4_time =
|time: &PosixTimeSpec| -> u32 { time.tv_sec.max(0).min(u32::MAX as i64) as u32 };
let (fs, inode_num, before_atime_version, before_mtime_version) = {
let guard = self.inner.lock();
(
guard.concret_fs(),
guard.inner_inode_num,
guard.cached_atime_version,
guard.cached_mtime_version,
)
};
let ext4 = &fs.fs;
Self::retry_metadata_contention(|| {
ext4.setattr(
inode_num,
another_ext4::SetAttr {
mode: Some(another_ext4::InodeMode::from_bits_truncate(
mode.bits() as u16
)),
uid: Some(metadata.uid as u32),
gid: Some(metadata.gid as u32),
size: Some(metadata.size as u64),
atime: Some(to_ext4_time(&metadata.atime)),
mtime: Some(to_ext4_time(&metadata.mtime)),
ctime: Some(to_ext4_time(&metadata.ctime)),
crtime: Some(to_ext4_time(&metadata.btime)),
},
)
})?;
{
let mut guard = self.inner.lock();
guard.cached_file_size = Some(metadata.size as u64);
if guard.cached_atime_version == before_atime_version {
guard.cached_times.atime = to_ext4_time(&metadata.atime);
guard.cached_atime_version = guard.cached_atime_version.wrapping_add(1);
guard.dirty_state.remove(InodeDirtyState::ATIME_DIRTY);
}
if guard.cached_mtime_version == before_mtime_version {
guard.cached_times.mtime = to_ext4_time(&metadata.mtime);
guard.cached_mtime_version = guard.cached_mtime_version.wrapping_add(1);
guard.dirty_state.remove(InodeDirtyState::MTIME_DIRTY);
}
guard.cached_times.ctime = to_ext4_time(&metadata.ctime);
guard.dirty_state.remove(InodeDirtyState::SIZE_DIRTY);
}
self.release_clean_metadata_queue_owner(&fs);
Ok(())
}
fn set_metadata_masked(
&self,
metadata: &vfs::Metadata,
mask: SetMetadataMask,
) -> Result<(), SystemError> {
if mask.is_empty() {
return Ok(());
}
let _operation = self.begin_operation()?;
let _io_guard = self.io_lock.lock();
let to_ext4_time =
|time: &PosixTimeSpec| -> u32 { time.tv_sec.max(0).min(u32::MAX as i64) as u32 };
let (fs, inode_num, before_atime_version, before_mtime_version) = {
let guard = self.inner.lock();
(
guard.concret_fs(),
guard.inner_inode_num,
guard.cached_atime_version,
guard.cached_mtime_version,
)
};
let mode = metadata.mode.union(InodeMode::from(metadata.file_type));
let atime = mask
.contains(SetMetadataMask::ATIME)
.then(|| to_ext4_time(&metadata.atime));
let mtime = mask
.contains(SetMetadataMask::MTIME)
.then(|| to_ext4_time(&metadata.mtime));
let ctime = mask
.contains(SetMetadataMask::CTIME)
.then(|| to_ext4_time(&metadata.ctime));
Self::retry_metadata_contention(|| {
fs.fs.setattr(
inode_num,
another_ext4::SetAttr {
mode: mask
.contains(SetMetadataMask::MODE)
.then(|| another_ext4::InodeMode::from_bits_truncate(mode.bits() as u16)),
uid: mask
.contains(SetMetadataMask::UID)
.then_some(metadata.uid as u32),
gid: mask
.contains(SetMetadataMask::GID)
.then_some(metadata.gid as u32),
atime,
mtime,
ctime,
..Default::default()
},
)
})?;
{
let mut guard = self.inner.lock();
// Buffered reads/writes can update cached times without io_lock.
// Preserve and leave dirty any value that changed while setattr
// was in flight; writeback will then persist the newer value.
if let Some(atime) = atime {
if guard.cached_atime_version == before_atime_version {
guard.cached_times.atime = atime;
guard.cached_atime_version = guard.cached_atime_version.wrapping_add(1);
guard.dirty_state.remove(InodeDirtyState::ATIME_DIRTY);
}
}
if let Some(mtime) = mtime {
if guard.cached_mtime_version == before_mtime_version {
guard.cached_times.mtime = mtime;
guard.cached_mtime_version = guard.cached_mtime_version.wrapping_add(1);
guard.dirty_state.remove(InodeDirtyState::MTIME_DIRTY);
}
}
if let Some(ctime) = ctime {
guard.cached_times.ctime = ctime;
}
}
self.release_clean_metadata_queue_owner(&fs);
Ok(())
}
fn update_atime(&self, now: PosixTimeSpec, relatime: bool) -> Result<(), SystemError> {
let atime = now.tv_sec.max(0).min(u32::MAX as i64) as u32;
let now = PosixTimeSpec::new(atime.into(), 0);
let self_arc = {
let guard = self.inner.lock();
let times = guard.cached_times;
if !vfs::should_update_atime(
PosixTimeSpec::new(times.atime.into(), 0),
PosixTimeSpec::new(times.mtime.into(), 0),
PosixTimeSpec::new(times.ctime.into(), 0),
now,
relatime,
) {
return Ok(());
}
guard.self_ref.upgrade().ok_or(SystemError::ENOENT)?
};
Ext4FileSystem::mark_inode_atime_dirty(&self_arc, atime, relatime)
}
fn resize(&self, len: usize) -> Result<(), SystemError> {
let _operation = self.begin_operation()?;
let (fs, inode_num, page_cache) = {
let guard = self.inner.lock();
(
guard.concret_fs(),
guard.inner_inode_num,
guard.page_cache.clone(),
)
};
let apply_resize = || -> Result<(), SystemError> {
let _io_guard = self.io_lock.lock();
let ext4 = &fs.fs;
// 仅调整文件大小,其他属性保持不变
Self::retry_metadata_contention(|| {
ext4.setattr(
inode_num,