-
-
Notifications
You must be signed in to change notification settings - Fork 194
Expand file tree
/
Copy pathmod.rs
More file actions
4572 lines (4147 loc) · 160 KB
/
Copy pathmod.rs
File metadata and controls
4572 lines (4147 loc) · 160 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 super::{
file::{File, FileFlags, FileMode, PreopenedFile},
utils::DName,
DirectoryEntry, FilePrivateData, FileSystem, FileType, IndexNode, InodeId, InodeMode,
InodeRetentionKind, PollableInode, SetMetadataMask, SuperBlock, XattrFlags,
};
use crate::{
driver::base::device::device_number::{DeviceNumber, Major},
exception::workqueue::{schedule_work, Work},
filesystem::{
page_cache::list_page_caches,
page_cache::PageCache,
vfs::{fcntl::AtFlags, syscall::RenameFlags, vcore::do_mkdir_at},
},
libs::{
casting::DowncastArc,
errseq::{ErrSeq, ErrSeqValue},
mutex::{Mutex, MutexGuard},
rwsem::{RwSem, RwSemReadGuard, RwSemWriteGuard},
spinlock::SpinLock,
wait_queue::WaitQueue,
},
mm::{fault::PageFaultMessage, VirtRegion, VmFaultReason, VmFlags},
process::{
namespace::{
mnt::MntNamespace,
propagation::{
abort_mount_propagation, commit_mount_propagation_locked, detach_mount_propagation,
ensure_subtree_shared, inherit_bind_mount_propagation,
prepare_mount_propagation_locked, propagate_umount_sources,
propagation_umount_busy, MountPropagation,
},
user_namespace::UserNamespace,
},
ProcessManager,
},
};
use alloc::{
collections::BTreeMap,
string::{String, ToString},
sync::{Arc, Weak},
vec::Vec,
};
use core::{
any::Any,
cell::RefCell,
fmt::Debug,
hash::Hash,
sync::atomic::{compiler_fence, AtomicBool, AtomicU32, AtomicUsize, Ordering},
};
use hashbrown::HashMap;
use ida::IdAllocator;
use lazy_static::lazy_static;
use system_error::SystemError;
/// Serializes mount pin admission against multi-mount busy preflight and
/// detach, including propagation peers in other namespaces.
///
/// Mount topology and propagation code acquires locks in this order:
/// lifecycle -> namespace -> dentry mount gates (ordered by dentry ID) ->
/// dentry topology snapshot -> parent mountpoints -> peer registry -> one
/// mount's propagation state -> propagation group allocator.
/// A lower layer must never acquire the lifecycle/topology layers in reverse.
pub(crate) static MOUNT_LIFECYCLE_LOCK: Mutex<()> = Mutex::new(());
lazy_static! {
/// Serializes pathname rendering against alias rename/disconnect. Mount
/// topology is protected separately by `MOUNT_LIFECYCLE_LOCK`; readers
/// acquire it first when both are needed.
static ref DENTRY_TOPOLOGY_LOCK: RwSem<()> = RwSem::new(());
}
/// Stable snapshot of both mount edges and dentry parent/name relationships.
///
/// Keep the field order in sync with the required release order: Rust drops
/// fields in declaration order, so the dentry reader is released before the
/// outer mount-lifecycle mutex.
pub struct MountTopologyGuard {
_dentries: RwSemReadGuard<'static, ()>,
_mounts: MutexGuard<'static, ()>,
}
/// First stage of a mount-topology transaction.
///
/// Edge commits which also need dentry mount gates use this capability to
/// acquire those gates before completing the dentry topology snapshot.
pub(crate) struct MountLifecycleGuard {
mounts: MutexGuard<'static, ()>,
}
/// Proof that every dentry gate used by one mount-edge commit is held.
/// The fields are private so only the gate-set helper can construct it.
pub(crate) struct MountEdgeCommitToken {
dentries: [Option<DentryId>; 3],
}
impl MountEdgeCommitToken {
fn covers(&self, mountpoint: &MountFSInode) -> bool {
let id = mountpoint.dentry.id;
self.dentries.iter().flatten().any(|entry| *entry == id)
}
}
pub(crate) fn lock_mount_lifecycle() -> MountLifecycleGuard {
MountLifecycleGuard {
mounts: MOUNT_LIFECYCLE_LOCK.lock(),
}
}
/// Acquire the complete VFS topology snapshot in the canonical lock order.
pub(crate) fn lock_mount_topology() -> MountTopologyGuard {
lock_mount_lifecycle().complete()
}
impl MountLifecycleGuard {
fn complete(self) -> MountTopologyGuard {
let dentries = DENTRY_TOPOLOGY_LOCK.read();
MountTopologyGuard {
_dentries: dentries,
_mounts: self.mounts,
}
}
/// Lock every dentry gate touched by an exact edge commit before taking
/// the dentry snapshot. Directory mutations hold the same gate while
/// acquiring the topology writer, so waiting for a gate under a read
/// snapshot would invert that order.
pub(crate) fn commit_mount_edges(
self,
mountpoints: [Option<Arc<MountFSInode>>; 3],
operation: impl FnOnce(&MountEdgeCommitToken) -> Result<(), SystemError>,
) -> Result<MountTopologyGuard, SystemError> {
let mounts = self.mounts;
let dentries = mountpoints.map(|mountpoint| mountpoint.map(|inode| inode.dentry.clone()));
with_dentry_mount_gate_set(dentries, |token| {
let snapshot = DENTRY_TOPOLOGY_LOCK.read();
operation(token)?;
Ok(MountTopologyGuard {
_dentries: snapshot,
_mounts: mounts,
})
})
}
}
fn with_dentry_mount_gate_set<T>(
mut dentries: [Option<Arc<VfsDentry>>; 3],
operation: impl FnOnce(&MountEdgeCommitToken) -> T,
) -> T {
dentries.sort_unstable_by_key(|entry| {
entry
.as_ref()
.map(|dentry| dentry.id.0)
.unwrap_or(usize::MAX)
});
let mut unique: [Option<Arc<VfsDentry>>; 3] = [None, None, None];
let mut count = 0;
for dentry in dentries.into_iter().flatten() {
if count == 0
|| unique[count - 1]
.as_ref()
.is_none_or(|previous| previous.id != dentry.id)
{
unique[count] = Some(dentry);
count += 1;
}
}
let token = MountEdgeCommitToken {
dentries: unique
.each_ref()
.map(|entry| entry.as_ref().map(|dentry| dentry.id)),
};
match count {
0 => operation(&token),
1 => {
let _first = unique[0].as_ref().unwrap().mount_gate.lock();
operation(&token)
}
2 => {
let _first = unique[0].as_ref().unwrap().mount_gate.lock();
let _second = unique[1].as_ref().unwrap().mount_gate.lock();
operation(&token)
}
3 => {
let _first = unique[0].as_ref().unwrap().mount_gate.lock();
let _second = unique[1].as_ref().unwrap().mount_gate.lock();
let _third = unique[2].as_ref().unwrap().mount_gate.lock();
operation(&token)
}
_ => unreachable!(),
}
}
/// Capability for one layered directory mutation to acquire the global dentry
/// topology write lock exactly once. Acquisition is deliberately lazy:
/// layered filesystems may prepare a copy-up before the innermost backing
/// filesystem reaches its namespace commit, avoiding both a copy-up/global-lock
/// inversion and holding a system-wide lock across file-data I/O.
pub struct DentryMutationContext<'a> {
guard: RefCell<Option<RwSemWriteGuard<'a, ()>>>,
}
impl DentryMutationContext<'static> {
fn new() -> Self {
Self {
guard: RefCell::new(None),
}
}
}
impl DentryMutationContext<'_> {
/// Enter the namespace commit phase. The guard remains owned by this
/// context until the outermost mount wrapper has updated every alias.
pub(crate) fn ensure_locked(&self) {
let mut guard = self.guard.borrow_mut();
if guard.is_none() {
*guard = Some(DENTRY_TOPOLOGY_LOCK.write());
}
}
}
pub(crate) fn with_topology_snapshot<T>(f: impl FnOnce() -> T) -> T {
let _topology = lock_mount_topology();
f()
}
bitflags! {
/// Mount flags for filesystem independent mount options
/// These flags correspond to the MS_* constants in Linux
///
/// Reference: https://code.dragonos.org.cn/xref/linux-6.6.21/include/uapi/linux/mount.h#13
pub struct MountFlags: u32 {
/// Mount read-only (MS_RDONLY)
const RDONLY = 1;
/// Ignore suid and sgid bits (MS_NOSUID)
const NOSUID = 2;
/// Disallow access to device special files (MS_NODEV)
const NODEV = 4;
/// Disallow program execution (MS_NOEXEC)
const NOEXEC = 8;
/// Writes are synced at once (MS_SYNCHRONOUS)
const SYNCHRONOUS = 16;
/// Alter flags of a mounted FS (MS_REMOUNT)
const REMOUNT = 32;
/// Allow mandatory locks on an FS (MS_MANDLOCK)
const MANDLOCK = 64;
/// Directory modifications are synchronous (MS_DIRSYNC)
const DIRSYNC = 128;
/// Do not follow symlinks (MS_NOSYMFOLLOW)
const NOSYMFOLLOW = 256;
/// Do not update access times (MS_NOATIME)
const NOATIME = 1024;
/// Do not update directory access times (MS_NODIRATIME)
const NODIRATIME = 2048;
/// Bind mount (MS_BIND)
const BIND = 4096;
/// Move mount (MS_MOVE)
const MOVE = 8192;
/// Recursive mount (MS_REC)
const REC = 16384;
/// Silent mount (MS_SILENT, deprecated MS_VERBOSE)
const SILENT = 32768;
/// VFS does not apply the umask (MS_POSIXACL)
const POSIXACL = 1 << 16;
/// Change to unbindable (MS_UNBINDABLE)
const UNBINDABLE = 1 << 17;
/// Change to private (MS_PRIVATE)
const PRIVATE = 1 << 18;
/// Change to slave (MS_SLAVE)
const SLAVE = 1 << 19;
/// Change to shared (MS_SHARED)
const SHARED = 1 << 20;
/// Update atime relative to mtime/ctime (MS_RELATIME)
const RELATIME = 1 << 21;
/// This is a kern_mount call (MS_KERNMOUNT)
const KERNMOUNT = 1 << 22;
/// Update inode I_version field (MS_I_VERSION)
const I_VERSION = 1 << 23;
/// Always perform atime updates (MS_STRICTATIME)
const STRICTATIME = 1 << 24;
/// Update the on-disk [acm]times lazily (MS_LAZYTIME)
const LAZYTIME = 1 << 25;
/// This is a submount (MS_SUBMOUNT)
const SUBMOUNT = 1 << 26;
/// Do not allow remote locking (MS_NOREMOTELOCK)
const NOREMOTELOCK = 1 << 27;
/// Do not perform security checks (MS_NOSEC)
const NOSEC = 1 << 28;
/// This mount has been created by the kernel (MS_BORN)
const BORN = 1 << 29;
/// This mount is active (MS_ACTIVE)
const ACTIVE = 1 << 30;
/// Mount flags not allowed from userspace (MS_NOUSER)
const NOUSER = 1 << 31;
/// Superblock flags that can be altered by MS_REMOUNT
const RMT_MASK = MountFlags::RDONLY.bits() |
MountFlags::SYNCHRONOUS.bits() |
MountFlags::MANDLOCK.bits() |
MountFlags::I_VERSION.bits() |
MountFlags::LAZYTIME.bits();
const SB_SETTABLE_MASK = MountFlags::RDONLY.bits()
| MountFlags::SYNCHRONOUS.bits()
| MountFlags::MANDLOCK.bits()
| MountFlags::DIRSYNC.bits()
| MountFlags::SILENT.bits()
| MountFlags::POSIXACL.bits()
| MountFlags::I_VERSION.bits()
| MountFlags::LAZYTIME.bits();
/// Old magic mount flag and mask
const MGC_VAL = 0xC0ED0000; // Magic value for mount flags
const MGC_MASK = 0xFFFF0000; // Mask for magic mount flags
/// Set of mount flags that userspace can modify via MS_REMOUNT.
const MNT_USER_SETTABLE_MASK = MountFlags::RDONLY.bits()
| MountFlags::NOSUID.bits()
| MountFlags::NODEV.bits()
| MountFlags::NOEXEC.bits()
| MountFlags::NOATIME.bits()
| MountFlags::NODIRATIME.bits()
| MountFlags::RELATIME.bits()
| MountFlags::NOSYMFOLLOW.bits();
const MNT_ATIME_MASK = MountFlags::NOATIME.bits()
| MountFlags::NODIRATIME.bits()
| MountFlags::RELATIME.bits();
}
}
impl MountFlags {
/// `ro` or `rw` token for proc mount options.
pub fn proc_rw_token(&self) -> &'static str {
if self.contains(MountFlags::RDONLY) {
"ro"
} else {
"rw"
}
}
/// Per-mount options excluding rw and super-block flags.
pub fn proc_per_mount_options(&self) -> String {
let mut options = Vec::new();
if self.contains(MountFlags::NOSUID) {
options.push("nosuid");
}
if self.contains(MountFlags::NODEV) {
options.push("nodev");
}
if self.contains(MountFlags::NOEXEC) {
options.push("noexec");
}
if self.contains(MountFlags::NOSYMFOLLOW) {
options.push("nosymfollow");
}
if self.contains(MountFlags::NOATIME) {
options.push("noatime");
}
if self.contains(MountFlags::NODIRATIME) {
options.push("nodiratime");
}
if self.contains(MountFlags::RELATIME) {
options.push("relatime");
}
if self.contains(MountFlags::STRICTATIME) {
options.push("strictatime");
}
options.join(",")
}
/// Super-block options excluding rw and per-mount flags.
pub fn proc_super_block_options(&self) -> String {
let mut options = Vec::new();
if self.contains(MountFlags::SYNCHRONOUS) {
options.push("sync");
}
if self.contains(MountFlags::MANDLOCK) {
options.push("mand");
}
if self.contains(MountFlags::DIRSYNC) {
options.push("dirsync");
}
if self.contains(MountFlags::LAZYTIME) {
options.push("lazytime");
}
options.join(",")
}
/// Convert mount flags to a comma-separated string representation
///
/// This function converts MountFlags to a string format similar to /proc/mounts,
/// such as "rw,nosuid,nodev,noexec,relatime".
#[inline(never)]
pub fn options_string(&self) -> String {
let mut options = self.proc_rw_token().to_string();
append_comma_options(&mut options, self.proc_per_mount_options());
append_comma_options(&mut options, self.proc_super_block_options());
options
}
}
bitflags! {
/// Internal per-mount locks corresponding to Linux `MNT_LOCK_*` flags.
///
/// These are deliberately separate from userspace-visible `MS_*` flags:
/// topology locking and attribute locking have different lifetimes. In
/// particular, a mount propagated across a user-namespace boundary may
/// have its topology lock cleared while retaining all attribute locks.
struct MountLockFlags: u32 {
const TOPOLOGY = 1 << 0;
const ATIME = 1 << 1;
const READONLY = 1 << 2;
const NODEV = 1 << 3;
const NOSUID = 1 << 4;
const NOEXEC = 1 << 5;
}
}
pub(crate) fn append_comma_options(base: &mut String, extra: String) {
if extra.is_empty() {
return;
}
if !base.is_empty() {
base.push(',');
}
base.push_str(&extra);
}
// MountId type
int_like!(MountId, usize);
static NEXT_MOUNT_ID: AtomicUsize = AtomicUsize::new(0);
static NEXT_DENTRY_ID: AtomicUsize = AtomicUsize::new(1);
/// Linux `unnamed_dev_ida` 的 DragonOS 等价物。minor 0 保留为“尚未分配”,
/// 上界传入 `MINOR_MASK + 1` 是因为 `IdAllocator` 的 max_id 为开区间。
static UNNAMED_DEV_ID_ALLOCATOR: Mutex<IdAllocator> =
Mutex::new(IdAllocator::new(1, DeviceNumber::MINOR_MASK as usize + 1).unwrap());
lazy_static! {
static ref MOUNTED_SUPERBLOCKS: SpinLock<Vec<Weak<MountFS>>> = SpinLock::new(Vec::new());
}
impl MountId {
fn alloc() -> Self {
let id = NEXT_MOUNT_ID
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
.expect("mount ID space exhausted");
MountId(id)
}
/// Allocate an ID for a mount object represented only by namespace
/// metadata, such as DragonOS's hidden initial-root anchor.
pub(crate) fn alloc_conceptual() -> Self {
Self::alloc()
}
}
/// @brief Mount filesystem
/// When mounting a filesystem, a MountFS wrapper layer is applied to support recursive mounting.
pub struct MountFS {
// The inner filesystem wrapped by MountFS
inner_filesystem: Arc<dyn FileSystem>,
/// The root inode exposed by this mount. For bind-mount subdirectories, this is not the global root of the underlying filesystem.
root_inner_inode: Arc<dyn IndexNode>,
/// Shared alias identity of `root_inner_inode`. Bind mounts and namespace
/// copies retain this exact object instead of reconstructing an alias from
/// an inode number or a pathname.
root_dentry: Arc<VfsDentry>,
/// Stable VFS wrapper for the root of this mount. Besides avoiding needless
/// allocations, this keeps the root dentry's child cache shared by all
/// lookups that enter the mount.
root_inode: Mutex<Weak<MountFSInode>>,
/// Per-mount projections of shared dentries. The values are weak because
/// paths and topology edges own the semantic references.
wrapper_cache: Mutex<BTreeMap<DentryId, Weak<MountFSInode>>>,
/// Ordered shadow stack for every exact `(parent mount, dentry)` edge.
/// The last element is the visible/top mount.
mountpoints: Mutex<HashMap<DentryId, Vec<Arc<MountFS>>>>,
/// Marks a covered topper reparented onto a propagated underlay root.
/// The edge role is copied with the mount object.
tucked_under: AtomicBool,
/// The inode of the mount point where this filesystem is mounted
self_mountpoint: RwSem<Option<Arc<MountFSInode>>>,
/// Weak reference to this MountFS
self_ref: Weak<MountFS>,
namespace: RwSem<MountNamespaceMembership>,
propagation: Arc<MountPropagation>,
mount_id: MountId,
mount_flags: RwSem<MountFlags>,
super_block_state: Arc<SuperBlockState>,
mount_source: RwSem<Option<String>>,
/// Internal `MNT_LOCK_*` state; never exposed as userspace `MS_*` bits.
mount_locks: AtomicU32,
lifecycle: Mutex<MountLifecycle>,
}
#[derive(Debug, Default)]
struct MountNamespaceMembership {
owner: Option<Weak<MntNamespace>>,
accounted: bool,
}
/// Capacity reserved for one future mount edge. Creating an empty map entry is
/// topology-neutral; if prepare aborts before the slot is consumed, Drop
/// removes that entry so failed events leave no mountpoint residue.
pub(crate) struct MountEdgeReservation {
parent: Arc<MountFS>,
mountpoint: Arc<MountFSInode>,
}
impl Drop for MountEdgeReservation {
fn drop(&mut self) {
let mut mountpoints = self.parent.mountpoints.lock();
let dentry_id = self.mountpoint.dentry.id;
if mountpoints
.get(&dentry_id)
.is_some_and(|stack| stack.is_empty())
{
mountpoints.remove(&dentry_id);
}
}
}
impl MountEdgeReservation {
pub(crate) fn mountpoint(&self) -> &Arc<MountFSInode> {
&self.mountpoint
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum MountLifecycleState {
Constructing,
Live,
Detaching,
DetachedConnected,
Detached,
}
#[derive(Debug)]
struct MountLifecycle {
state: MountLifecycleState,
external_pins: usize,
construction_reserved: bool,
propagation_attached: bool,
detached_component: Option<Arc<DetachedMountComponent>>,
}
#[derive(Debug)]
struct DetachedMountComponent {
root: Weak<MountFS>,
members: Vec<Weak<MountFS>>,
pins: AtomicUsize,
}
impl DetachedMountComponent {
const INITIALIZING: usize = 1usize << (usize::BITS - 1);
fn new(root: &Arc<MountFS>, members: &[Arc<MountFS>]) -> Arc<Self> {
Arc::new(Self {
root: Arc::downgrade(root),
members: members.iter().map(Arc::downgrade).collect(),
pins: AtomicUsize::new(Self::INITIALIZING),
})
}
fn add_initial_pins(&self, pins: usize) {
self.pins.fetch_add(pins, Ordering::Relaxed);
}
fn finish_initialization(self: &Arc<Self>) {
let previous = self.pins.fetch_and(!Self::INITIALIZING, Ordering::AcqRel);
if previous == Self::INITIALIZING {
self.schedule_cleanup();
}
}
fn try_pin(&self) -> bool {
let mut current = self.pins.load(Ordering::Acquire);
loop {
if current & !Self::INITIALIZING == 0 && current & Self::INITIALIZING == 0 {
return false;
}
match self.pins.compare_exchange_weak(
current,
current + 1,
Ordering::AcqRel,
Ordering::Acquire,
) {
Ok(_) => return true,
Err(observed) => current = observed,
}
}
}
fn unpin(self: &Arc<Self>) {
let previous = self.pins.fetch_sub(1, Ordering::AcqRel);
debug_assert_ne!(previous & !Self::INITIALIZING, 0);
if previous == 1 {
self.schedule_cleanup();
}
}
fn schedule_cleanup(self: &Arc<Self>) {
let component = self.clone();
schedule_work(Work::new(move || component.cleanup()));
}
fn cleanup(&self) {
let _topology = MOUNT_LIFECYCLE_LOCK.lock();
if self.pins.load(Ordering::Acquire) != 0 {
return;
}
let Some(root) = self.root.upgrade() else {
return;
};
for member in self.members.iter().filter_map(Weak::upgrade) {
let mut lifecycle = member.lifecycle.lock();
lifecycle.detached_component = None;
}
MountFS::deactivate_disconnected_subtree(&root);
}
}
/// A semantic reference to a path or open file description on one mount.
///
/// Unlike an `Arc<MountFS>`, this reference participates in ordinary umount's
/// busy decision. It is intentionally not `Clone`: every independently owned
/// path must explicitly acquire its own pin.
#[derive(Debug)]
pub struct MountExternalGuard {
mount: Arc<MountFS>,
}
/// Keeps the superblock backend alive while a topology snapshot is rendered,
/// without making ordinary umount report the mount busy.
#[derive(Debug)]
pub(crate) struct MountSnapshotGuard {
mount: Arc<MountFS>,
}
unsafe impl Send for MountSnapshotGuard {}
unsafe impl Sync for MountSnapshotGuard {}
// SAFETY: MountExternalGuard only owns an Arc<MountFS>. Every mutable MountFS
// field reachable from the guard is protected by Mutex/RwSem/SpinLock or is
// atomic. These explicit impls break the recursive auto-trait proof cycle
// MountFS -> MountFSInode/File -> MountExternalGuard -> MountFS, which some
// cross-target rustc builds cannot normalize within the default recursion
// limit; they do not weaken the synchronization requirements of MountFS.
unsafe impl Send for MountExternalGuard {}
unsafe impl Sync for MountExternalGuard {}
#[derive(Debug)]
pub struct SuperBlockState {
/// User namespace that owns this superblock, matching Linux `s_user_ns`.
/// Bind mounts and mount-namespace copies retain the same owner.
owner_user_ns: Arc<UserNamespace>,
flags: RwSem<MountFlags>,
write_count: AtomicUsize,
wb_error: ErrSeq,
umount_lock: RwSem<()>,
unnamed_dev_minor: Mutex<Option<u32>>,
/// Shared by all mounts of this superblock, including bind mounts.
dentry_namespace_lock: RwSem<()>,
dentry_registry: Mutex<BTreeMap<DentryRegistryKey, Weak<VfsDentry>>>,
lifecycle: Mutex<SuperBlockLifecycle>,
shutdown_wait: WaitQueue,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SuperBlockLifecycleState {
Active,
Dying,
Dead,
}
#[derive(Debug)]
struct SuperBlockLifecycle {
active_mounts: usize,
external_pins: usize,
state: SuperBlockLifecycleState,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct DentryRegistryKey {
parent: Option<DentryId>,
child: InodeId,
child_generation: u64,
name: Option<DName>,
}
int_like!(DentryId, usize);
impl DentryId {
fn alloc() -> Self {
Self(NEXT_DENTRY_ID.fetch_add(1, Ordering::Relaxed))
}
}
/// Minimal superblock-wide dentry identity.
///
/// This deliberately does not implement a complete dcache. It only owns the
/// alias state that must be observed consistently by every bind mount and
/// mount-namespace copy of the same superblock.
#[derive(Debug)]
pub struct VfsDentry {
id: DentryId,
inode: Arc<dyn IndexNode>,
registry_child: InodeId,
/// Generation captured when this alias entered the registry. It must not
/// follow later FUSE invalidations, otherwise the original key could no
/// longer be removed deterministically.
registry_generation: u64,
/// Serializes exact-edge attach/detach against rename/unlink/rmdir of this
/// alias without holding a global mount lock across filesystem I/O.
mount_gate: Mutex<()>,
/// Serializes lookup/registration and namespace mutations of this
/// directory's children. Layered copy-up may run while this per-directory
/// gate is held, but unrelated directories and filesystems remain free.
children_gate: Mutex<()>,
/// Global fast-path hint; namespace-local checks still inspect topology.
mount_edges: AtomicUsize,
automount_gate: Mutex<()>,
state: Mutex<VfsDentryState>,
}
#[derive(Debug, Default)]
struct VfsDentryState {
name: Option<DName>,
parent: Option<Arc<VfsDentry>>,
disconnected: bool,
}
impl VfsDentry {
pub fn id(&self) -> DentryId {
self.id
}
fn is_disconnected(&self) -> bool {
self.state.lock().disconnected
}
fn is_local_mountpoint(&self) -> bool {
if self.mount_edges.load(Ordering::Acquire) == 0 {
return false;
}
let current_namespace = ProcessManager::current_mntns();
let mounts = {
let mut registry = MOUNTED_SUPERBLOCKS.lock_irqsave();
registry.retain(|mount| mount.strong_count() != 0);
registry.clone()
};
mounts.iter().filter_map(Weak::upgrade).any(|mount| {
mount.is_belongs_to_mntns(¤t_namespace)
&& mount
.self_mountpoint()
.is_some_and(|mountpoint| mountpoint.dentry.id == self.id)
})
}
}
fn dentry_is_descendant_of(dentry: &Arc<VfsDentry>, ancestor: &Arc<VfsDentry>) -> bool {
let mut current = Some(dentry.clone());
let mut visited = hashbrown::HashSet::new();
while let Some(dentry) = current {
if dentry.id == ancestor.id {
return true;
}
if !visited.insert(dentry.id) {
log::warn!("cycle detected in shared VFS dentry ancestry");
return false;
}
current = dentry.state.lock().parent.clone();
}
false
}
fn with_dentry_mount_gates<T>(
first: Option<&Arc<VfsDentry>>,
second: Option<&Arc<VfsDentry>>,
operation: impl FnOnce() -> Result<T, SystemError>,
) -> Result<T, SystemError> {
match (first, second) {
(None, None) => operation(),
(Some(dentry), None) | (None, Some(dentry)) => {
let _guard = dentry.mount_gate.lock();
operation()
}
(Some(left), Some(right)) if left.id == right.id => {
let _guard = left.mount_gate.lock();
operation()
}
(Some(left), Some(right)) if left.id < right.id => {
let _left = left.mount_gate.lock();
let _right = right.mount_gate.lock();
operation()
}
(Some(left), Some(right)) => {
let _right = right.mount_gate.lock();
let _left = left.mount_gate.lock();
operation()
}
}
}
fn with_dentry_children_gates<T>(
first: &Arc<VfsDentry>,
second: &Arc<VfsDentry>,
operation: impl FnOnce() -> Result<T, SystemError>,
) -> Result<T, SystemError> {
if first.id == second.id {
let _guard = first.children_gate.lock();
operation()
} else if first.id < second.id {
let _first = first.children_gate.lock();
let _second = second.children_gate.lock();
operation()
} else {
let _second = second.children_gate.lock();
let _first = first.children_gate.lock();
operation()
}
}
struct MountStateInit {
super_block_state: Arc<SuperBlockState>,
mount_source: Option<String>,
construction_reserved: bool,
}
impl SuperBlockState {
pub fn new(flags: MountFlags) -> Self {
Self {
owner_user_ns: ProcessManager::current_user_ns(),
flags: RwSem::new(flags & MountFlags::SB_SETTABLE_MASK),
write_count: AtomicUsize::new(0),
wb_error: ErrSeq::new(),
umount_lock: RwSem::new(()),
unnamed_dev_minor: Mutex::new(None),
dentry_namespace_lock: RwSem::new(()),
dentry_registry: Mutex::new(BTreeMap::new()),
lifecycle: Mutex::new(SuperBlockLifecycle {
active_mounts: 0,
external_pins: 0,
state: SuperBlockLifecycleState::Active,
}),
shutdown_wait: WaitQueue::default(),
}
}
pub fn owner_user_ns(&self) -> &Arc<UserNamespace> {
&self.owner_user_ns
}
fn activate_mount(&self, construction_reserved: bool) -> Result<(), SystemError> {
let mut lifecycle = self.lifecycle.lock();
if lifecycle.state != SuperBlockLifecycleState::Active {
return Err(SystemError::ESTALE);
}
lifecycle.active_mounts += 1;
if construction_reserved {
debug_assert!(lifecycle.external_pins > 0);
lifecycle.external_pins -= 1;
}
Ok(())
}
fn try_add_external_pin(&self) -> bool {
let mut lifecycle = self.lifecycle.lock();
if lifecycle.state != SuperBlockLifecycleState::Active {
return false;
}
lifecycle.external_pins += 1;
true
}
fn remove_external_pin(&self) -> bool {
let mut lifecycle = self.lifecycle.lock();
debug_assert!(lifecycle.external_pins > 0);
lifecycle.external_pins -= 1;
Self::try_begin_shutdown(&mut lifecycle)
}
fn remove_mount(&self) -> bool {
let mut lifecycle = self.lifecycle.lock();
debug_assert!(lifecycle.active_mounts > 0);
lifecycle.active_mounts -= 1;
Self::try_begin_shutdown(&mut lifecycle)
}
fn try_begin_shutdown(lifecycle: &mut SuperBlockLifecycle) -> bool {
if lifecycle.state == SuperBlockLifecycleState::Active
&& lifecycle.active_mounts == 0
&& lifecycle.external_pins == 0
{
lifecycle.state = SuperBlockLifecycleState::Dying;
true
} else {
false
}
}
fn finish_shutdown(&self) {
let mut lifecycle = self.lifecycle.lock();
debug_assert_eq!(lifecycle.state, SuperBlockLifecycleState::Dying);
lifecycle.state = SuperBlockLifecycleState::Dead;
drop(lifecycle);
self.shutdown_wait.wake_all();
}
/// Wait only when this unmount started the final superblock shutdown.
/// A still-active shared superblock needs no shutdown completion wait.
fn wait_for_shutdown_if_started(&self) {
self.shutdown_wait.wait_until(|| {
let state = self.lifecycle.lock().state;
(state != SuperBlockLifecycleState::Dying).then_some(())
});
}
fn get_or_create_dentry(
&self,
parent: Option<&Arc<VfsDentry>>,
inode: Arc<dyn IndexNode>,
name: Option<DName>,
) -> Result<Arc<VfsDentry>, SystemError> {
let child = inode.metadata()?.inode_id;
let child_generation = inode.inode_generation();
let key = DentryRegistryKey {
parent: parent.map(|dentry| dentry.id),
child,
child_generation,
name: name.clone(),
};
let mut registry = self.dentry_registry.lock();
if let Some(dentry) = registry.get(&key).and_then(Weak::upgrade) {
if !dentry.is_disconnected() {
return Ok(dentry);
}
}
if !registry.is_empty() && registry.len().is_multiple_of(256) {
registry.retain(|_, dentry| dentry.strong_count() != 0);
}
let dentry = Arc::new(VfsDentry {
id: DentryId::alloc(),
inode,
registry_child: child,
registry_generation: child_generation,
mount_gate: Mutex::new(()),
children_gate: Mutex::new(()),
mount_edges: AtomicUsize::new(0),
automount_gate: Mutex::new(()),
state: Mutex::new(VfsDentryState {
name,
parent: parent.cloned(),
disconnected: false,
}),
});
registry.insert(key, Arc::downgrade(&dentry));
Ok(dentry)
}
fn remove_dentry_key(&self, dentry: &Arc<VfsDentry>) {
let state = dentry.state.lock();
let key = DentryRegistryKey {
parent: state.parent.as_ref().map(|parent| parent.id),
child: dentry.registry_child,
child_generation: dentry.registry_generation,
name: state.name.clone(),
};
drop(state);
self.dentry_registry.lock().remove(&key);
}
fn get_registered_dentry(
&self,
parent: &Arc<VfsDentry>,
name: &DName,
inode: &Arc<dyn IndexNode>,
) -> Result<Option<Arc<VfsDentry>>, SystemError> {
let child = inode.metadata()?.inode_id;
let key = DentryRegistryKey {
parent: Some(parent.id),
child,
child_generation: inode.inode_generation(),
name: Some(name.clone()),
};
let registry = self.dentry_registry.lock();
Ok(registry.get(&key).and_then(Weak::upgrade))
}